cpuinfo: Check for overflow in SIMD allocation If the size to be allocated is very large and untrusted, then adding the padding etc. might be enough to cause unsigned overflow, after which a very small amount of memory will be allocated. Signed-off-by: Simon McVittie <smcv@collabora.com>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
diff --git a/src/cpuinfo/SDL_cpuinfo.c b/src/cpuinfo/SDL_cpuinfo.c
index 53b6366..cc383ad 100644
--- a/src/cpuinfo/SDL_cpuinfo.c
+++ b/src/cpuinfo/SDL_cpuinfo.c
@@ -1059,9 +1059,17 @@ SDL_SIMDAlloc(const size_t len)
{
const size_t alignment = SDL_SIMDGetAlignment();
const size_t padding = (alignment - (len % alignment)) % alignment;
- const size_t padded = len + padding;
Uint8 *retval = NULL;
- Uint8 *ptr = (Uint8 *) SDL_malloc(padded + alignment + sizeof (void *));
+ Uint8 *ptr;
+ size_t to_allocate;
+
+ /* alignment + padding + sizeof (void *) is bounded (a few hundred
+ * bytes max), so no need to check for overflow within that argument */
+ if (SDL_size_add_overflow(len, alignment + padding + sizeof (void *), &to_allocate)) {
+ return NULL;
+ }
+
+ ptr = (Uint8 *) SDL_malloc(to_allocate);
if (ptr) {
/* store the actual allocated pointer right before our aligned pointer. */
retval = ptr + sizeof (void *);
@@ -1076,11 +1084,17 @@ SDL_SIMDRealloc(void *mem, const size_t len)
{
const size_t alignment = SDL_SIMDGetAlignment();
const size_t padding = (alignment - (len % alignment)) % alignment;
- const size_t padded = len + padding;
Uint8 *retval = (Uint8*) mem;
void *oldmem = mem;
size_t memdiff = 0, ptrdiff;
Uint8 *ptr;
+ size_t to_allocate;
+
+ /* alignment + padding + sizeof (void *) is bounded (a few hundred
+ * bytes max), so no need to check for overflow within that argument */
+ if (SDL_size_add_overflow(len, alignment + padding + sizeof (void *), &to_allocate)) {
+ return NULL;
+ }
if (mem) {
void **realptr = (void **) mem;
@@ -1091,7 +1105,7 @@ SDL_SIMDRealloc(void *mem, const size_t len)
memdiff = ((size_t) oldmem) - ((size_t) mem);
}
- ptr = (Uint8 *) SDL_realloc(mem, padded + alignment + sizeof (void *));
+ ptr = (Uint8 *) SDL_realloc(mem, to_allocate);
if (ptr == NULL) {
return NULL; /* Out of memory, bail! */