From b9b4d8d7dadaef56058e175c51fa25486f0c5bd1 Mon Sep 17 00:00:00 2001 From: Dong Heng Date: Wed, 20 Jan 2021 14:52:17 +0800 Subject: [PATCH] fix(heap): Add integer overflow checks --- .../esp8266/include/priv/esp_heap_caps_priv.h | 2 ++ components/heap/src/esp_heap_caps.c | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/components/heap/port/esp8266/include/priv/esp_heap_caps_priv.h b/components/heap/port/esp8266/include/priv/esp_heap_caps_priv.h index ab092634..cc59076c 100644 --- a/components/heap/port/esp8266/include/priv/esp_heap_caps_priv.h +++ b/components/heap/port/esp8266/include/priv/esp_heap_caps_priv.h @@ -21,6 +21,8 @@ extern "C" { #endif +#define HEAP_MAX_SIZE (96 * 1024) + #define MEM_BLK_TAG 0x80000000 ///< Mark the memory block used #ifdef CONFIG_HEAP_TRACING diff --git a/components/heap/src/esp_heap_caps.c b/components/heap/src/esp_heap_caps.c index 61845422..0f49e9d6 100644 --- a/components/heap/src/esp_heap_caps.c +++ b/components/heap/src/esp_heap_caps.c @@ -101,6 +101,11 @@ void IRAM_ATTR *_heap_caps_malloc(size_t size, uint32_t caps, const char *file, uint32_t num; uint32_t mem_blk_size; + if (size > (HEAP_MAX_SIZE - sizeof(mem2_blk_t) * 2)) { + ESP_EARLY_LOGV(TAG, "size=%u is oveflow", size); + return NULL; + } + if (line == 0) { ESP_EARLY_LOGV(TAG, "caller func %p", file); } else { @@ -297,9 +302,16 @@ void IRAM_ATTR _heap_caps_free(void *ptr, const char *file, size_t line) */ void *_heap_caps_calloc(size_t count, size_t size, uint32_t caps, const char *file, size_t line) { - void *p = _heap_caps_malloc(count * size, caps, file, line); + size_t size_bytes; + + if (__builtin_mul_overflow(count, size, &size_bytes)) { + ESP_EARLY_LOGV(TAG, "count=%u size=%u is oveflow", count, size); + return NULL; + } + + void *p = _heap_caps_malloc(size_bytes, caps, file, line); if (p) - memset(p, 0, count * size); + memset(p, 0, size_bytes); return p; }