Skip to content

Commit 55e646a

Browse files
author
Github Executorch
committed
Fix integer overflow in PlatformMemoryAllocator::allocate() (TOB-EXECUTORCH-26)
Add overflow checking before computing the total allocation size (sizeof(AllocationNode) + size + alignment) in PlatformMemoryAllocator::allocate(). Previously, when this sum exceeded SIZE_MAX, it would wrap around to a small value, causing pal_allocate to allocate an undersized buffer. This could lead to subsequent out-of-bounds writes. The fix validates each addition step against SIZE_MAX and returns nullptr on overflow. This PR was authored with the assistance of Claude.
1 parent 3d2c853 commit 55e646a

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

runtime/executor/platform_memory_allocator.h

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#include <cinttypes>
1313
#include <cstdint>
1414

15+
#include <c10/util/safe_numerics.h>
1516
#include <executorch/runtime/core/memory_allocator.h>
1617
#include <executorch/runtime/platform/log.h>
1718
#include <executorch/runtime/platform/platform.h>
@@ -46,8 +47,20 @@ class PlatformMemoryAllocator final : public MemoryAllocator {
4647
return nullptr;
4748
}
4849

49-
// Allocate enough memory for the node, the data and the alignment bump.
50-
size_t alloc_size = sizeof(AllocationNode) + size + alignment;
50+
// Check for overflow before computing total allocation size.
51+
// Allocate enough for the node, data, and alignment bump (at most
52+
// alignment - 1 extra bytes to align the data pointer).
53+
size_t alloc_size = 0;
54+
if (c10::add_overflows(sizeof(AllocationNode), size, &alloc_size) ||
55+
c10::add_overflows(alloc_size, alignment - 1, &alloc_size)) {
56+
ET_LOG(
57+
Error,
58+
"Allocation size overflow: size %zu, alignment %zu",
59+
size,
60+
alignment);
61+
return nullptr;
62+
}
63+
5164
void* node_memory = runtime::pal_allocate(alloc_size);
5265

5366
// If allocation failed, log message and return nullptr.

0 commit comments

Comments
 (0)