Skip to content

Commit 2345ff7

Browse files
heap_1: reject configTOTAL_HEAP_SIZE <= portBYTE_ALIGNMENT at compile time
Defect: pvPortMalloc() in heap_1.c can return a pointer outside the ucHeap array when configTOTAL_HEAP_SIZE is configured smaller than or equal to portBYTE_ALIGNMENT. Root cause: configADJUSTED_HEAP_SIZE is defined as ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT ). When configTOTAL_HEAP_SIZE is not larger than portBYTE_ALIGNMENT this unsigned subtraction underflows to a very large size_t value. The "enough room left" check in pvPortMalloc() compares an unsigned index against configADJUSTED_HEAP_SIZE, so the underflowed value defeats the check and an allocation can be handed out past the end of the heap array. Fix: add a compile-time (compiler, not preprocessor) size check so a nonsensical, too-small heap is rejected during the build. The compiler-level check still works when configTOTAL_HEAP_SIZE is defined with a cast such as ( ( size_t ) 0x2000 ). A host regression test kept outside this repository demonstrates the fault before the change and its absence afterwards (red then green).
1 parent ae46383 commit 2345ff7

1 file changed

Lines changed: 11 additions & 0 deletions

File tree

portable/MemMang/heap_1.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,17 @@
5353
/* A few bytes might be lost to byte aligning the heap start address. */
5454
#define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )
5555

56+
/* configTOTAL_HEAP_SIZE must be larger than portBYTE_ALIGNMENT, otherwise the
57+
* configADJUSTED_HEAP_SIZE subtraction above underflows. The "enough room left"
58+
* check in pvPortMalloc() compares an unsigned size_t index against
59+
* configADJUSTED_HEAP_SIZE, so an underflowed (very large) value silently
60+
* defeats that check and pvPortMalloc() can return a pointer outside the ucHeap
61+
* array. Reject such a nonsensical, too-small heap at compile time. This is a
62+
* compiler (not preprocessor) check so that it still works when
63+
* configTOTAL_HEAP_SIZE is defined with a cast, e.g. ( ( size_t ) 0x2000 ). */
64+
typedef char heapCHECK_configTOTAL_HEAP_SIZE_EXCEEDS_portBYTE_ALIGNMENT
65+
[ ( ( configTOTAL_HEAP_SIZE ) > ( portBYTE_ALIGNMENT ) ) ? 1 : -1 ];
66+
5667
/* Max value that fits in a size_t type. */
5768
#define heapSIZE_MAX ( ~( ( size_t ) 0 ) )
5869

0 commit comments

Comments
 (0)