Skip to content

Commit 2eb0e87

Browse files
JacobSzwejbkafacebook-github-bot
authored andcommitted
Check overflow in allocation (pytorch#12683)
Summary: Overflow is unsafe as a user will get back much less memory then expected Reviewed By: lucylq Differential Revision: D78678540
1 parent a27dd42 commit 2eb0e87

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

runtime/core/memory_allocator.h

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,15 @@
1212
#include <cinttypes>
1313
#include <cstdint>
1414

15+
#include <c10/util/safe_numerics.h>
16+
1517
#include <executorch/runtime/core/error.h>
1618
#include <executorch/runtime/platform/assert.h>
1719
#include <executorch/runtime/platform/compiler.h>
1820
#include <executorch/runtime/platform/log.h>
1921
#include <executorch/runtime/platform/profiler.h>
2022

23+
2124
namespace executorch {
2225
namespace runtime {
2326

@@ -137,7 +140,17 @@ class MemoryAllocator {
137140
// Some users of this method allocate lists of pointers, causing the next
138141
// line to expand to `sizeof(type *)`, which triggers a clang-tidy warning.
139142
// NOLINTNEXTLINE(bugprone-sizeof-expression)
140-
return static_cast<T*>(this->allocate(size * sizeof(T), alignment));
143+
size_t bytes_size = 0;
144+
bool overflow =
145+
c10::mul_overflows(size, sizeof(T), &bytes_size);
146+
if (overflow) {
147+
ET_LOG(
148+
Error,
149+
"Failed to allocate list of type %zu: size * sizeof(T) overflowed",
150+
size);
151+
return nullptr;
152+
}
153+
return static_cast<T*>(this->allocate(bytes_size, alignment));
141154
}
142155

143156
// Returns the allocator memory's base address.

0 commit comments

Comments
 (0)