From 151ebfcfc9f2383ee11ce3c771c3bf92900d6b43 Mon Sep 17 00:00:00 2001 From: Lingkai Dong Date: Wed, 10 Mar 2021 09:37:20 +0000 Subject: [PATCH] Add integer overflow check to the malloc wrappers Add a check that the combined size of the buffer to allocate and alloc_info_t does not exceed the maximum integer value representable by size_t. --- platform/source/mbed_alloc_wrappers.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/platform/source/mbed_alloc_wrappers.cpp b/platform/source/mbed_alloc_wrappers.cpp index 1d06a4873f5..2e736359037 100644 --- a/platform/source/mbed_alloc_wrappers.cpp +++ b/platform/source/mbed_alloc_wrappers.cpp @@ -105,7 +105,10 @@ extern "C" void *malloc_wrapper(struct _reent *r, size_t size, void *caller) #endif #ifdef MBED_HEAP_STATS_ENABLED malloc_stats_mutex->lock(); - alloc_info_t *alloc_info = (alloc_info_t *)__real__malloc_r(r, size + sizeof(alloc_info_t)); + alloc_info_t *alloc_info = NULL; + if (size <= SIZE_MAX - sizeof(alloc_info_t)) { + alloc_info = (alloc_info_t *)__real__malloc_r(r, size + sizeof(alloc_info_t)); + } if (alloc_info != NULL) { alloc_info->size = size; alloc_info->signature = MBED_HEAP_STATS_SIGNATURE; @@ -292,7 +295,10 @@ extern "C" void *malloc_wrapper(size_t size, void *caller) #endif #ifdef MBED_HEAP_STATS_ENABLED malloc_stats_mutex->lock(); - alloc_info_t *alloc_info = (alloc_info_t *)SUPER_MALLOC(size + sizeof(alloc_info_t)); + alloc_info_t *alloc_info = NULL; + if (size <= SIZE_MAX - sizeof(alloc_info_t)) { + alloc_info = (alloc_info_t *)SUPER_MALLOC(size + sizeof(alloc_info_t)); + } if (alloc_info != NULL) { alloc_info->size = size; alloc_info->signature = MBED_HEAP_STATS_SIGNATURE;