5151#endif
5252
5353/* A few bytes might be lost to byte aligning the heap start address. */
54- #define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )
54+ #define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )
55+
56+ /* Max value that fits in a size_t type. */
57+ #define heapSIZE_MAX ( ~( ( size_t ) 0 ) )
58+
59+ /* Check if adding a and b will result in overflow. */
60+ #define heapADD_WILL_OVERFLOW ( a , b ) ( ( a ) > ( heapSIZE_MAX - ( b ) ) )
61+
62+ /*-----------------------------------------------------------*/
5563
5664/* Allocate the memory for the heap. */
5765#if ( configAPPLICATION_ALLOCATED_HEAP == 1 )
@@ -76,12 +84,16 @@ void * pvPortMalloc( size_t xWantedSize )
7684 /* Ensure that blocks are always aligned. */
7785 #if ( portBYTE_ALIGNMENT != 1 )
7886 {
79- if ( xWantedSize & portBYTE_ALIGNMENT_MASK )
87+ size_t xAdditionalRequiredSize ;
88+
89+ if ( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
8090 {
81- /* Byte alignment required. Check for overflow. */
82- if ( ( xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) ) > xWantedSize )
91+ /* Byte alignment required. */
92+ xAdditionalRequiredSize = portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK );
93+
94+ if ( heapADD_WILL_OVERFLOW ( xWantedSize , xAdditionalRequiredSize ) == 0 )
8395 {
84- xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) ;
96+ xWantedSize += xAdditionalRequiredSize ;
8597 }
8698 else
8799 {
@@ -96,13 +108,14 @@ void * pvPortMalloc( size_t xWantedSize )
96108 if ( pucAlignedHeap == NULL )
97109 {
98110 /* Ensure the heap starts on a correctly aligned boundary. */
99- pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) & ucHeap [ portBYTE_ALIGNMENT - 1 ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );
111+ pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) & ( ucHeap [ portBYTE_ALIGNMENT - 1 ] ) ) &
112+ ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );
100113 }
101114
102- /* Check there is enough room left for the allocation and . */
103- if ( ( xWantedSize > 0 ) && /* valid size */
104- ( ( xNextFreeByte + xWantedSize ) < configADJUSTED_HEAP_SIZE ) &&
105- ( ( xNextFreeByte + xWantedSize ) > xNextFreeByte ) ) /* Check for overflow. */
115+ /* Check there is enough room left for the allocation. */
116+ if ( ( xWantedSize > 0 ) &&
117+ ( heapADD_WILL_OVERFLOW ( xNextFreeByte , xWantedSize ) == 0 ) &&
118+ ( ( xNextFreeByte + xWantedSize ) < configADJUSTED_HEAP_SIZE ) )
106119 {
107120 /* Return the next free byte then increment the index past this
108121 * block. */
0 commit comments