1 /*
2  * FreeRTOS Kernel V11.1.0
3  * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4  *
5  * SPDX-License-Identifier: MIT
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy of
8  * this software and associated documentation files (the "Software"), to deal in
9  * the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11  * the Software, and to permit persons to whom the Software is furnished to do so,
12  * subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in all
15  * copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
19  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
20  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
21  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * https://www.FreeRTOS.org
25  * https://github.com/FreeRTOS
26  *
27  */
28 
29 /*
30  * A sample implementation of pvPortMalloc() that allows the heap to be defined
31  * across multiple non-contiguous blocks and combines (coalescences) adjacent
32  * memory blocks as they are freed.
33  *
34  * See heap_1.c, heap_2.c, heap_3.c and heap_4.c for alternative
35  * implementations, and the memory management pages of https://www.FreeRTOS.org
36  * for more information.
37  *
38  * Usage notes:
39  *
40  * vPortDefineHeapRegions() ***must*** be called before pvPortMalloc().
41  * pvPortMalloc() will be called if any task objects (tasks, queues, event
42  * groups, etc.) are created, therefore vPortDefineHeapRegions() ***must*** be
43  * called before any other objects are defined.
44  *
45  * vPortDefineHeapRegions() takes a single parameter.  The parameter is an array
46  * of HeapRegion_t structures.  HeapRegion_t is defined in portable.h as
47  *
48  * typedef struct HeapRegion
49  * {
50  *  uint8_t *pucStartAddress; << Start address of a block of memory that will be part of the heap.
51  *  size_t xSizeInBytes;      << Size of the block of memory.
52  * } HeapRegion_t;
53  *
54  * The array is terminated using a NULL zero sized region definition, and the
55  * memory regions defined in the array ***must*** appear in address order from
56  * low address to high address.  So the following is a valid example of how
57  * to use the function.
58  *
59  * HeapRegion_t xHeapRegions[] =
60  * {
61  *  { ( uint8_t * ) 0x80000000UL, 0x10000 }, << Defines a block of 0x10000 bytes starting at address 0x80000000
62  *  { ( uint8_t * ) 0x90000000UL, 0xa0000 }, << Defines a block of 0xa0000 bytes starting at address of 0x90000000
63  *  { NULL, 0 }                << Terminates the array.
64  * };
65  *
66  * vPortDefineHeapRegions( xHeapRegions ); << Pass the array into vPortDefineHeapRegions().
67  *
68  * Note 0x80000000 is the lower address so appears in the array first.
69  *
70  */
71 #include <stdlib.h>
72 #include <string.h>
73 
74 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
75  * all the API functions to use the MPU wrappers.  That should only be done when
76  * task.h is included from an application file. */
77 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
78 
79 #include "FreeRTOS.h"
80 #include "task.h"
81 
82 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
83 
84 #if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 )
85     #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
86 #endif
87 
88 #ifndef configHEAP_CLEAR_MEMORY_ON_FREE
89     #define configHEAP_CLEAR_MEMORY_ON_FREE    0
90 #endif
91 
92 /* Block sizes must not get too small. */
93 #define heapMINIMUM_BLOCK_SIZE    ( ( size_t ) ( xHeapStructSize << 1 ) )
94 
95 /* Assumes 8bit bytes! */
96 #define heapBITS_PER_BYTE         ( ( size_t ) 8 )
97 
98 /* Max value that fits in a size_t type. */
99 #define heapSIZE_MAX              ( ~( ( size_t ) 0 ) )
100 
101 /* Check if multiplying a and b will result in overflow. */
102 #define heapMULTIPLY_WILL_OVERFLOW( a, b )     ( ( ( a ) > 0 ) && ( ( b ) > ( heapSIZE_MAX / ( a ) ) ) )
103 
104 /* Check if adding a and b will result in overflow. */
105 #define heapADD_WILL_OVERFLOW( a, b )          ( ( a ) > ( heapSIZE_MAX - ( b ) ) )
106 
107 /* Check if the subtraction operation ( a - b ) will result in underflow. */
108 #define heapSUBTRACT_WILL_UNDERFLOW( a, b )    ( ( a ) < ( b ) )
109 
110 /* MSB of the xBlockSize member of an BlockLink_t structure is used to track
111  * the allocation status of a block.  When MSB of the xBlockSize member of
112  * an BlockLink_t structure is set then the block belongs to the application.
113  * When the bit is free the block is still part of the free heap space. */
114 #define heapBLOCK_ALLOCATED_BITMASK    ( ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ) )
115 #define heapBLOCK_SIZE_IS_VALID( xBlockSize )    ( ( ( xBlockSize ) & heapBLOCK_ALLOCATED_BITMASK ) == 0 )
116 #define heapBLOCK_IS_ALLOCATED( pxBlock )        ( ( ( pxBlock->xBlockSize ) & heapBLOCK_ALLOCATED_BITMASK ) != 0 )
117 #define heapALLOCATE_BLOCK( pxBlock )            ( ( pxBlock->xBlockSize ) |= heapBLOCK_ALLOCATED_BITMASK )
118 #define heapFREE_BLOCK( pxBlock )                ( ( pxBlock->xBlockSize ) &= ~heapBLOCK_ALLOCATED_BITMASK )
119 
120 /* Setting configENABLE_HEAP_PROTECTOR to 1 enables heap block pointers
121  * protection using an application supplied canary value to catch heap
122  * corruption should a heap buffer overflow occur.
123  */
124 #if ( configENABLE_HEAP_PROTECTOR == 1 )
125 
126 /* Macro to load/store BlockLink_t pointers to memory. By XORing the
127  * pointers with a random canary value, heap overflows will result
128  * in randomly unpredictable pointer values which will be caught by
129  * heapVALIDATE_BLOCK_POINTER assert. */
130     #define heapPROTECT_BLOCK_POINTER( pxBlock )    ( ( BlockLink_t * ) ( ( ( portPOINTER_SIZE_TYPE ) ( pxBlock ) ) ^ xHeapCanary ) )
131 
132 /* Assert that a heap block pointer is within the heap bounds. */
133     #define heapVALIDATE_BLOCK_POINTER( pxBlock )                       \
134     configASSERT( ( pucHeapHighAddress != NULL ) &&                     \
135                   ( pucHeapLowAddress != NULL ) &&                      \
136                   ( ( uint8_t * ) ( pxBlock ) >= pucHeapLowAddress ) && \
137                   ( ( uint8_t * ) ( pxBlock ) < pucHeapHighAddress ) )
138 
139 #else /* if ( configENABLE_HEAP_PROTECTOR == 1 ) */
140 
141     #define heapPROTECT_BLOCK_POINTER( pxBlock )    ( pxBlock )
142 
143     #define heapVALIDATE_BLOCK_POINTER( pxBlock )
144 
145 #endif /* configENABLE_HEAP_PROTECTOR */
146 
147 /*-----------------------------------------------------------*/
148 
149 /* Define the linked list structure.  This is used to link free blocks in order
150  * of their memory address. */
151 typedef struct A_BLOCK_LINK
152 {
153     struct A_BLOCK_LINK * pxNextFreeBlock; /**< The next free block in the list. */
154     size_t xBlockSize;                     /**< The size of the free block. */
155 } BlockLink_t;
156 
157 /*-----------------------------------------------------------*/
158 
159 /*
160  * Inserts a block of memory that is being freed into the correct position in
161  * the list of free memory blocks.  The block being freed will be merged with
162  * the block in front it and/or the block behind it if the memory blocks are
163  * adjacent to each other.
164  */
165 static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) PRIVILEGED_FUNCTION;
166 void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) PRIVILEGED_FUNCTION;
167 
168 #if ( configENABLE_HEAP_PROTECTOR == 1 )
169 
170 /**
171  * @brief Application provided function to get a random value to be used as canary.
172  *
173  * @param pxHeapCanary [out] Output parameter to return the canary value.
174  */
175     extern void vApplicationGetRandomHeapCanary( portPOINTER_SIZE_TYPE * pxHeapCanary );
176 #endif /* configENABLE_HEAP_PROTECTOR */
177 
178 /*-----------------------------------------------------------*/
179 
180 /* The size of the structure placed at the beginning of each allocated memory
181  * block must by correctly byte aligned. */
182 static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
183 
184 /* Create a couple of list links to mark the start and end of the list. */
185 PRIVILEGED_DATA static BlockLink_t xStart;
186 PRIVILEGED_DATA static BlockLink_t * pxEnd = NULL;
187 
188 /* Keeps track of the number of calls to allocate and free memory as well as the
189  * number of free bytes remaining, but says nothing about fragmentation. */
190 PRIVILEGED_DATA static size_t xFreeBytesRemaining = ( size_t ) 0U;
191 PRIVILEGED_DATA static size_t xMinimumEverFreeBytesRemaining = ( size_t ) 0U;
192 PRIVILEGED_DATA static size_t xNumberOfSuccessfulAllocations = ( size_t ) 0U;
193 PRIVILEGED_DATA static size_t xNumberOfSuccessfulFrees = ( size_t ) 0U;
194 
195 #if ( configENABLE_HEAP_PROTECTOR == 1 )
196 
197 /* Canary value for protecting internal heap pointers. */
198     PRIVILEGED_DATA static portPOINTER_SIZE_TYPE xHeapCanary;
199 
200 /* Highest and lowest heap addresses used for heap block bounds checking. */
201     PRIVILEGED_DATA static uint8_t * pucHeapHighAddress = NULL;
202     PRIVILEGED_DATA static uint8_t * pucHeapLowAddress = NULL;
203 
204 #endif /* configENABLE_HEAP_PROTECTOR */
205 
206 /*-----------------------------------------------------------*/
207 
pvPortMalloc(size_t xWantedSize)208 void * pvPortMalloc( size_t xWantedSize )
209 {
210     BlockLink_t * pxBlock;
211     BlockLink_t * pxPreviousBlock;
212     BlockLink_t * pxNewBlockLink;
213     void * pvReturn = NULL;
214     size_t xAdditionalRequiredSize;
215 
216     /* The heap must be initialised before the first call to
217      * pvPortMalloc(). */
218     configASSERT( pxEnd );
219 
220     if( xWantedSize > 0 )
221     {
222         /* The wanted size must be increased so it can contain a BlockLink_t
223          * structure in addition to the requested amount of bytes. */
224         if( heapADD_WILL_OVERFLOW( xWantedSize, xHeapStructSize ) == 0 )
225         {
226             xWantedSize += xHeapStructSize;
227 
228             /* Ensure that blocks are always aligned to the required number
229              * of bytes. */
230             if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
231             {
232                 /* Byte alignment required. */
233                 xAdditionalRequiredSize = portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK );
234 
235                 if( heapADD_WILL_OVERFLOW( xWantedSize, xAdditionalRequiredSize ) == 0 )
236                 {
237                     xWantedSize += xAdditionalRequiredSize;
238                 }
239                 else
240                 {
241                     xWantedSize = 0;
242                 }
243             }
244             else
245             {
246                 mtCOVERAGE_TEST_MARKER();
247             }
248         }
249         else
250         {
251             xWantedSize = 0;
252         }
253     }
254     else
255     {
256         mtCOVERAGE_TEST_MARKER();
257     }
258 
259     vTaskSuspendAll();
260     {
261         /* Check the block size we are trying to allocate is not so large that the
262          * top bit is set.  The top bit of the block size member of the BlockLink_t
263          * structure is used to determine who owns the block - the application or
264          * the kernel, so it must be free. */
265         if( heapBLOCK_SIZE_IS_VALID( xWantedSize ) != 0 )
266         {
267             if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
268             {
269                 /* Traverse the list from the start (lowest address) block until
270                  * one of adequate size is found. */
271                 pxPreviousBlock = &xStart;
272                 pxBlock = heapPROTECT_BLOCK_POINTER( xStart.pxNextFreeBlock );
273                 heapVALIDATE_BLOCK_POINTER( pxBlock );
274 
275                 while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != heapPROTECT_BLOCK_POINTER( NULL ) ) )
276                 {
277                     pxPreviousBlock = pxBlock;
278                     pxBlock = heapPROTECT_BLOCK_POINTER( pxBlock->pxNextFreeBlock );
279                     heapVALIDATE_BLOCK_POINTER( pxBlock );
280                 }
281 
282                 /* If the end marker was reached then a block of adequate size
283                  * was not found. */
284                 if( pxBlock != pxEnd )
285                 {
286                     /* Return the memory space pointed to - jumping over the
287                      * BlockLink_t structure at its start. */
288                     pvReturn = ( void * ) ( ( ( uint8_t * ) heapPROTECT_BLOCK_POINTER( pxPreviousBlock->pxNextFreeBlock ) ) + xHeapStructSize );
289                     heapVALIDATE_BLOCK_POINTER( pvReturn );
290 
291                     /* This block is being returned for use so must be taken out
292                      * of the list of free blocks. */
293                     pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
294 
295                     /* If the block is larger than required it can be split into
296                      * two. */
297                     configASSERT( heapSUBTRACT_WILL_UNDERFLOW( pxBlock->xBlockSize, xWantedSize ) == 0 );
298 
299                     if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
300                     {
301                         /* This block is to be split into two.  Create a new
302                          * block following the number of bytes requested. The void
303                          * cast is used to prevent byte alignment warnings from the
304                          * compiler. */
305                         pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
306                         configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 );
307 
308                         /* Calculate the sizes of two blocks split from the
309                          * single block. */
310                         pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
311                         pxBlock->xBlockSize = xWantedSize;
312 
313                         /* Insert the new block into the list of free blocks. */
314                         pxNewBlockLink->pxNextFreeBlock = pxPreviousBlock->pxNextFreeBlock;
315                         pxPreviousBlock->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxNewBlockLink );
316                     }
317                     else
318                     {
319                         mtCOVERAGE_TEST_MARKER();
320                     }
321 
322                     xFreeBytesRemaining -= pxBlock->xBlockSize;
323 
324                     if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
325                     {
326                         xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
327                     }
328                     else
329                     {
330                         mtCOVERAGE_TEST_MARKER();
331                     }
332 
333                     /* The block is being returned - it is allocated and owned
334                      * by the application and has no "next" block. */
335                     heapALLOCATE_BLOCK( pxBlock );
336                     pxBlock->pxNextFreeBlock = NULL;
337                     xNumberOfSuccessfulAllocations++;
338                 }
339                 else
340                 {
341                     mtCOVERAGE_TEST_MARKER();
342                 }
343             }
344             else
345             {
346                 mtCOVERAGE_TEST_MARKER();
347             }
348         }
349         else
350         {
351             mtCOVERAGE_TEST_MARKER();
352         }
353 
354         traceMALLOC( pvReturn, xWantedSize );
355     }
356     ( void ) xTaskResumeAll();
357 
358     #if ( configUSE_MALLOC_FAILED_HOOK == 1 )
359     {
360         if( pvReturn == NULL )
361         {
362             vApplicationMallocFailedHook();
363         }
364         else
365         {
366             mtCOVERAGE_TEST_MARKER();
367         }
368     }
369     #endif /* if ( configUSE_MALLOC_FAILED_HOOK == 1 ) */
370 
371     configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 );
372     return pvReturn;
373 }
374 /*-----------------------------------------------------------*/
375 
vPortFree(void * pv)376 void vPortFree( void * pv )
377 {
378     uint8_t * puc = ( uint8_t * ) pv;
379     BlockLink_t * pxLink;
380 
381     if( pv != NULL )
382     {
383         /* The memory being freed will have an BlockLink_t structure immediately
384          * before it. */
385         puc -= xHeapStructSize;
386 
387         /* This casting is to keep the compiler from issuing warnings. */
388         pxLink = ( void * ) puc;
389 
390         heapVALIDATE_BLOCK_POINTER( pxLink );
391         configASSERT( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 );
392         configASSERT( pxLink->pxNextFreeBlock == NULL );
393 
394         if( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 )
395         {
396             if( pxLink->pxNextFreeBlock == NULL )
397             {
398                 /* The block is being returned to the heap - it is no longer
399                  * allocated. */
400                 heapFREE_BLOCK( pxLink );
401                 #if ( configHEAP_CLEAR_MEMORY_ON_FREE == 1 )
402                 {
403                     /* Check for underflow as this can occur if xBlockSize is
404                      * overwritten in a heap block. */
405                     if( heapSUBTRACT_WILL_UNDERFLOW( pxLink->xBlockSize, xHeapStructSize ) == 0 )
406                     {
407                         ( void ) memset( puc + xHeapStructSize, 0, pxLink->xBlockSize - xHeapStructSize );
408                     }
409                 }
410                 #endif
411 
412                 vTaskSuspendAll();
413                 {
414                     /* Add this block to the list of free blocks. */
415                     xFreeBytesRemaining += pxLink->xBlockSize;
416                     traceFREE( pv, pxLink->xBlockSize );
417                     prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
418                     xNumberOfSuccessfulFrees++;
419                 }
420                 ( void ) xTaskResumeAll();
421             }
422             else
423             {
424                 mtCOVERAGE_TEST_MARKER();
425             }
426         }
427         else
428         {
429             mtCOVERAGE_TEST_MARKER();
430         }
431     }
432 }
433 /*-----------------------------------------------------------*/
434 
xPortGetFreeHeapSize(void)435 size_t xPortGetFreeHeapSize( void )
436 {
437     return xFreeBytesRemaining;
438 }
439 /*-----------------------------------------------------------*/
440 
xPortGetMinimumEverFreeHeapSize(void)441 size_t xPortGetMinimumEverFreeHeapSize( void )
442 {
443     return xMinimumEverFreeBytesRemaining;
444 }
445 /*-----------------------------------------------------------*/
446 
pvPortCalloc(size_t xNum,size_t xSize)447 void * pvPortCalloc( size_t xNum,
448                      size_t xSize )
449 {
450     void * pv = NULL;
451 
452     if( heapMULTIPLY_WILL_OVERFLOW( xNum, xSize ) == 0 )
453     {
454         pv = pvPortMalloc( xNum * xSize );
455 
456         if( pv != NULL )
457         {
458             ( void ) memset( pv, 0, xNum * xSize );
459         }
460     }
461 
462     return pv;
463 }
464 /*-----------------------------------------------------------*/
465 
prvInsertBlockIntoFreeList(BlockLink_t * pxBlockToInsert)466 static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) /* PRIVILEGED_FUNCTION */
467 {
468     BlockLink_t * pxIterator;
469     uint8_t * puc;
470 
471     /* Iterate through the list until a block is found that has a higher address
472      * than the block being inserted. */
473     for( pxIterator = &xStart; heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock ) < pxBlockToInsert; pxIterator = heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock ) )
474     {
475         /* Nothing to do here, just iterate to the right position. */
476     }
477 
478     if( pxIterator != &xStart )
479     {
480         heapVALIDATE_BLOCK_POINTER( pxIterator );
481     }
482 
483     /* Do the block being inserted, and the block it is being inserted after
484      * make a contiguous block of memory? */
485     puc = ( uint8_t * ) pxIterator;
486 
487     if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
488     {
489         pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
490         pxBlockToInsert = pxIterator;
491     }
492     else
493     {
494         mtCOVERAGE_TEST_MARKER();
495     }
496 
497     /* Do the block being inserted, and the block it is being inserted before
498      * make a contiguous block of memory? */
499     puc = ( uint8_t * ) pxBlockToInsert;
500 
501     if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock ) )
502     {
503         if( heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock ) != pxEnd )
504         {
505             /* Form one big block from the two blocks. */
506             pxBlockToInsert->xBlockSize += heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock )->xBlockSize;
507             pxBlockToInsert->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock )->pxNextFreeBlock;
508         }
509         else
510         {
511             pxBlockToInsert->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxEnd );
512         }
513     }
514     else
515     {
516         pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
517     }
518 
519     /* If the block being inserted plugged a gap, so was merged with the block
520      * before and the block after, then it's pxNextFreeBlock pointer will have
521      * already been set, and should not be set here as that would make it point
522      * to itself. */
523     if( pxIterator != pxBlockToInsert )
524     {
525         pxIterator->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxBlockToInsert );
526     }
527     else
528     {
529         mtCOVERAGE_TEST_MARKER();
530     }
531 }
532 /*-----------------------------------------------------------*/
533 
vPortDefineHeapRegions(const HeapRegion_t * const pxHeapRegions)534 void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) /* PRIVILEGED_FUNCTION */
535 {
536     BlockLink_t * pxFirstFreeBlockInRegion = NULL;
537     BlockLink_t * pxPreviousFreeBlock;
538     portPOINTER_SIZE_TYPE xAlignedHeap;
539     size_t xTotalRegionSize, xTotalHeapSize = 0;
540     BaseType_t xDefinedRegions = 0;
541     portPOINTER_SIZE_TYPE xAddress;
542     const HeapRegion_t * pxHeapRegion;
543 
544     /* Can only call once! */
545     configASSERT( pxEnd == NULL );
546 
547     #if ( configENABLE_HEAP_PROTECTOR == 1 )
548     {
549         vApplicationGetRandomHeapCanary( &( xHeapCanary ) );
550     }
551     #endif
552 
553     pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
554 
555     while( pxHeapRegion->xSizeInBytes > 0 )
556     {
557         xTotalRegionSize = pxHeapRegion->xSizeInBytes;
558 
559         /* Ensure the heap region starts on a correctly aligned boundary. */
560         xAddress = ( portPOINTER_SIZE_TYPE ) pxHeapRegion->pucStartAddress;
561 
562         if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
563         {
564             xAddress += ( portBYTE_ALIGNMENT - 1 );
565             xAddress &= ~( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK;
566 
567             /* Adjust the size for the bytes lost to alignment. */
568             xTotalRegionSize -= ( size_t ) ( xAddress - ( portPOINTER_SIZE_TYPE ) pxHeapRegion->pucStartAddress );
569         }
570 
571         xAlignedHeap = xAddress;
572 
573         /* Set xStart if it has not already been set. */
574         if( xDefinedRegions == 0 )
575         {
576             /* xStart is used to hold a pointer to the first item in the list of
577              *  free blocks.  The void cast is used to prevent compiler warnings. */
578             xStart.pxNextFreeBlock = ( BlockLink_t * ) heapPROTECT_BLOCK_POINTER( xAlignedHeap );
579             xStart.xBlockSize = ( size_t ) 0;
580         }
581         else
582         {
583             /* Should only get here if one region has already been added to the
584              * heap. */
585             configASSERT( pxEnd != heapPROTECT_BLOCK_POINTER( NULL ) );
586 
587             /* Check blocks are passed in with increasing start addresses. */
588             configASSERT( ( size_t ) xAddress > ( size_t ) pxEnd );
589         }
590 
591         #if ( configENABLE_HEAP_PROTECTOR == 1 )
592         {
593             if( ( pucHeapLowAddress == NULL ) ||
594                 ( ( uint8_t * ) xAlignedHeap < pucHeapLowAddress ) )
595             {
596                 pucHeapLowAddress = ( uint8_t * ) xAlignedHeap;
597             }
598         }
599         #endif /* configENABLE_HEAP_PROTECTOR */
600 
601         /* Remember the location of the end marker in the previous region, if
602          * any. */
603         pxPreviousFreeBlock = pxEnd;
604 
605         /* pxEnd is used to mark the end of the list of free blocks and is
606          * inserted at the end of the region space. */
607         xAddress = xAlignedHeap + ( portPOINTER_SIZE_TYPE ) xTotalRegionSize;
608         xAddress -= ( portPOINTER_SIZE_TYPE ) xHeapStructSize;
609         xAddress &= ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK );
610         pxEnd = ( BlockLink_t * ) xAddress;
611         pxEnd->xBlockSize = 0;
612         pxEnd->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( NULL );
613 
614         /* To start with there is a single free block in this region that is
615          * sized to take up the entire heap region minus the space taken by the
616          * free block structure. */
617         pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap;
618         pxFirstFreeBlockInRegion->xBlockSize = ( size_t ) ( xAddress - ( portPOINTER_SIZE_TYPE ) pxFirstFreeBlockInRegion );
619         pxFirstFreeBlockInRegion->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxEnd );
620 
621         /* If this is not the first region that makes up the entire heap space
622          * then link the previous region to this region. */
623         if( pxPreviousFreeBlock != NULL )
624         {
625             pxPreviousFreeBlock->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxFirstFreeBlockInRegion );
626         }
627 
628         xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize;
629 
630         #if ( configENABLE_HEAP_PROTECTOR == 1 )
631         {
632             if( ( pucHeapHighAddress == NULL ) ||
633                 ( ( ( ( uint8_t * ) pxFirstFreeBlockInRegion ) + pxFirstFreeBlockInRegion->xBlockSize ) > pucHeapHighAddress ) )
634             {
635                 pucHeapHighAddress = ( ( uint8_t * ) pxFirstFreeBlockInRegion ) + pxFirstFreeBlockInRegion->xBlockSize;
636             }
637         }
638         #endif
639 
640         /* Move onto the next HeapRegion_t structure. */
641         xDefinedRegions++;
642         pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
643     }
644 
645     xMinimumEverFreeBytesRemaining = xTotalHeapSize;
646     xFreeBytesRemaining = xTotalHeapSize;
647 
648     /* Check something was actually defined before it is accessed. */
649     configASSERT( xTotalHeapSize );
650 }
651 /*-----------------------------------------------------------*/
652 
vPortGetHeapStats(HeapStats_t * pxHeapStats)653 void vPortGetHeapStats( HeapStats_t * pxHeapStats )
654 {
655     BlockLink_t * pxBlock;
656     size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */
657 
658     vTaskSuspendAll();
659     {
660         pxBlock = heapPROTECT_BLOCK_POINTER( xStart.pxNextFreeBlock );
661 
662         /* pxBlock will be NULL if the heap has not been initialised.  The heap
663          * is initialised automatically when the first allocation is made. */
664         if( pxBlock != NULL )
665         {
666             while( pxBlock != pxEnd )
667             {
668                 /* Increment the number of blocks and record the largest block seen
669                  * so far. */
670                 xBlocks++;
671 
672                 if( pxBlock->xBlockSize > xMaxSize )
673                 {
674                     xMaxSize = pxBlock->xBlockSize;
675                 }
676 
677                 /* Heap five will have a zero sized block at the end of each
678                  * each region - the block is only used to link to the next
679                  * heap region so it not a real block. */
680                 if( pxBlock->xBlockSize != 0 )
681                 {
682                     if( pxBlock->xBlockSize < xMinSize )
683                     {
684                         xMinSize = pxBlock->xBlockSize;
685                     }
686                 }
687 
688                 /* Move to the next block in the chain until the last block is
689                  * reached. */
690                 pxBlock = heapPROTECT_BLOCK_POINTER( pxBlock->pxNextFreeBlock );
691             }
692         }
693     }
694     ( void ) xTaskResumeAll();
695 
696     pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize;
697     pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize;
698     pxHeapStats->xNumberOfFreeBlocks = xBlocks;
699 
700     taskENTER_CRITICAL();
701     {
702         pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining;
703         pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations;
704         pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees;
705         pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining;
706     }
707     taskEXIT_CRITICAL();
708 }
709 /*-----------------------------------------------------------*/
710 
711 /*
712  * Reset the state in this file. This state is normally initialized at start up.
713  * This function must be called by the application before restarting the
714  * scheduler.
715  */
vPortHeapResetState(void)716 void vPortHeapResetState( void )
717 {
718     pxEnd = NULL;
719 
720     xFreeBytesRemaining = ( size_t ) 0U;
721     xMinimumEverFreeBytesRemaining = ( size_t ) 0U;
722     xNumberOfSuccessfulAllocations = ( size_t ) 0U;
723     xNumberOfSuccessfulFrees = ( size_t ) 0U;
724 
725     #if ( configENABLE_HEAP_PROTECTOR == 1 )
726         pucHeapHighAddress = NULL;
727         pucHeapLowAddress = NULL;
728     #endif /* #if ( configENABLE_HEAP_PROTECTOR == 1 ) */
729 }
730 /*-----------------------------------------------------------*/
731