Skip to content

Commit 1e9c41d

Browse files
[SYCL] Fix potential misaligned allocation size (#18375)
The use of std::aligned_alloc requires the size of the memory allocated to be a multiple of the alignment. This patch fixes the use of std::aligned_alloc in DynRTDeviceBinaryImage to adhere to these requirements. Note that _aligned_malloc from MSVC does not have this requirement. Signed-off-by: Larsen, Steffen <[email protected]>
1 parent 44ed9b7 commit 1e9c41d

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

sycl/source/detail/device_binary_image.cpp

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -594,20 +594,25 @@ DynRTDeviceBinaryImage::DynRTDeviceBinaryImage(
594594
const size_t PropertySectionSize = PropertyCount * PaddedPropertyByteSize;
595595

596596
// Allocate the memory aligned to the property entry alignment.
597+
#ifdef _MSC_VER
597598
// Note: MSVC does not implement std::aligned_alloc.
598599
Data = std::unique_ptr<char[], std::function<void(void *)>>(
599-
#ifdef _MSC_VER
600600
static_cast<char *>(_aligned_malloc(sizeof(char) * PropertySectionSize +
601601
PropertyContentByteSize,
602602
PropertyAlignment)),
603-
_aligned_free
603+
_aligned_free);
604604
#else
605-
static_cast<char *>(std::aligned_alloc(
606-
PropertyAlignment,
607-
sizeof(char) * PropertySectionSize + PropertyContentByteSize)),
608-
std::free
605+
// std::aligned_alloc requires the allocation size to be a multiple of the
606+
// alignment, so we may over-allocate a little.
607+
const size_t AllocSize =
608+
sizeof(char) * PropertySectionSize + PropertyContentByteSize;
609+
const size_t AlignedAllocSize = (AllocSize + PropertyAlignment - 1) /
610+
PropertyAlignment * PropertyAlignment;
611+
Data = std::unique_ptr<char[], std::function<void(void *)>>(
612+
static_cast<char *>(
613+
std::aligned_alloc(PropertyAlignment, AlignedAllocSize)),
614+
std::free);
609615
#endif
610-
);
611616

612617
auto NextFreeProperty =
613618
reinterpret_cast<sycl_device_binary_property>(Data.get());

0 commit comments

Comments
 (0)