Skip to content

Commit 693c88f

Browse files
Log and return early if std::malloc returns nullptr
Differential Revision: D86130282 Pull Request resolved: #15532
1 parent 55452bf commit 693c88f

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

extension/memory_allocator/malloc_memory_allocator.h

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,21 @@ class MallocMemoryAllocator : public executorch::runtime::MemoryAllocator {
5858
// To get higher alignments, allocate extra and then align the returned
5959
// pointer. This will waste an extra `alignment` bytes every time, but
6060
// this is the only portable way to get aligned memory from the heap.
61+
62+
// Check for overflow before adding alignment to size
63+
if (size > SIZE_MAX - alignment) {
64+
ET_LOG(
65+
Error, "Size %zu + alignment %zu would overflow", size, alignment);
66+
return nullptr;
67+
}
6168
size += alignment;
6269
}
63-
mem_ptrs_.emplace_back(std::malloc(size));
70+
void* mem_ptr = std::malloc(size);
71+
if (mem_ptr == nullptr) {
72+
ET_LOG(Error, "Failed to allocate %zu bytes", size);
73+
return nullptr;
74+
}
75+
mem_ptrs_.emplace_back(mem_ptr);
6476
return alignPointer(mem_ptrs_.back(), alignment);
6577
}
6678

extension/memory_allocator/test/malloc_memory_allocator_test.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,3 +131,15 @@ TEST_F(MallocMemoryAllocatorTest, ResetSucceeds) {
131131
EXPECT_NE(p, nullptr);
132132
EXPECT_ALIGNED(p, kDefaultAlignment);
133133
}
134+
135+
TEST_F(MallocMemoryAllocatorTest, OverflowDetectionOnSizePlusAlignment) {
136+
MallocMemoryAllocator allocator = MallocMemoryAllocator();
137+
138+
constexpr size_t kLargeAlignment = kDefaultAlignment * 64;
139+
constexpr size_t kSizeThatWouldOverflow = SIZE_MAX - kLargeAlignment + 1;
140+
141+
auto p = allocator.allocate(kSizeThatWouldOverflow, kLargeAlignment);
142+
143+
// Should return nullptr due to overflow detection.
144+
EXPECT_EQ(p, nullptr);
145+
}

0 commit comments

Comments
 (0)