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() and vPortFree() that combines
31  * (coalescences) adjacent memory blocks as they are freed, and in so doing
32  * limits memory fragmentation.
33  *
34  * See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the
35  * memory management pages of https://www.FreeRTOS.org for more information.
36  */
37 #include <stdlib.h>
38 #include <string.h>
39 
40 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
41  * all the API functions to use the MPU wrappers.  That should only be done when
42  * task.h is included from an application file. */
43 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
44 
45 #include "FreeRTOS.h"
46 #include "task.h"
47 
48 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
49 
50 #if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 )
51     #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
52 #endif
53 
54 #ifndef configHEAP_CLEAR_MEMORY_ON_FREE
55     #define configHEAP_CLEAR_MEMORY_ON_FREE    0
56 #endif
57 
58 /* Block sizes must not get too small. */
59 #define heapMINIMUM_BLOCK_SIZE    ( ( size_t ) ( xHeapStructSize << 1 ) )
60 
61 /* Assumes 8bit bytes! */
62 #define heapBITS_PER_BYTE         ( ( size_t ) 8 )
63 
64 /* Max value that fits in a size_t type. */
65 #define heapSIZE_MAX              ( ~( ( size_t ) 0 ) )
66 
67 /* Check if multiplying a and b will result in overflow. */
68 #define heapMULTIPLY_WILL_OVERFLOW( a, b )     ( ( ( a ) > 0 ) && ( ( b ) > ( heapSIZE_MAX / ( a ) ) ) )
69 
70 /* Check if adding a and b will result in overflow. */
71 #define heapADD_WILL_OVERFLOW( a, b )          ( ( a ) > ( heapSIZE_MAX - ( b ) ) )
72 
73 /* Check if the subtraction operation ( a - b ) will result in underflow. */
74 #define heapSUBTRACT_WILL_UNDERFLOW( a, b )    ( ( a ) < ( b ) )
75 
76 /* MSB of the xBlockSize member of an BlockLink_t structure is used to track
77  * the allocation status of a block.  When MSB of the xBlockSize member of
78  * an BlockLink_t structure is set then the block belongs to the application.
79  * When the bit is free the block is still part of the free heap space. */
80 #define heapBLOCK_ALLOCATED_BITMASK    ( ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ) )
81 #define heapBLOCK_SIZE_IS_VALID( xBlockSize )    ( ( ( xBlockSize ) & heapBLOCK_ALLOCATED_BITMASK ) == 0 )
82 #define heapBLOCK_IS_ALLOCATED( pxBlock )        ( ( ( pxBlock->xBlockSize ) & heapBLOCK_ALLOCATED_BITMASK ) != 0 )
83 #define heapALLOCATE_BLOCK( pxBlock )            ( ( pxBlock->xBlockSize ) |= heapBLOCK_ALLOCATED_BITMASK )
84 #define heapFREE_BLOCK( pxBlock )                ( ( pxBlock->xBlockSize ) &= ~heapBLOCK_ALLOCATED_BITMASK )
85 
86 /*-----------------------------------------------------------*/
87 
88 /* Allocate the memory for the heap. */
89 #if ( configAPPLICATION_ALLOCATED_HEAP == 1 )
90 
91 /* The application writer has already defined the array used for the RTOS
92 * heap - probably so it can be placed in a special segment or address. */
93     extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
94 #else
95     PRIVILEGED_DATA static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
96 #endif /* configAPPLICATION_ALLOCATED_HEAP */
97 
98 /* Define the linked list structure.  This is used to link free blocks in order
99  * of their memory address. */
100 typedef struct A_BLOCK_LINK
101 {
102     struct A_BLOCK_LINK * pxNextFreeBlock; /**< The next free block in the list. */
103     size_t xBlockSize;                     /**< The size of the free block. */
104 } BlockLink_t;
105 
106 /* Setting configENABLE_HEAP_PROTECTOR to 1 enables heap block pointers
107  * protection using an application supplied canary value to catch heap
108  * corruption should a heap buffer overflow occur.
109  */
110 #if ( configENABLE_HEAP_PROTECTOR == 1 )
111 
112 /**
113  * @brief Application provided function to get a random value to be used as canary.
114  *
115  * @param pxHeapCanary [out] Output parameter to return the canary value.
116  */
117     extern void vApplicationGetRandomHeapCanary( portPOINTER_SIZE_TYPE * pxHeapCanary );
118 
119 /* Canary value for protecting internal heap pointers. */
120     PRIVILEGED_DATA static portPOINTER_SIZE_TYPE xHeapCanary;
121 
122 /* Macro to load/store BlockLink_t pointers to memory. By XORing the
123  * pointers with a random canary value, heap overflows will result
124  * in randomly unpredictable pointer values which will be caught by
125  * heapVALIDATE_BLOCK_POINTER assert. */
126     #define heapPROTECT_BLOCK_POINTER( pxBlock )    ( ( BlockLink_t * ) ( ( ( portPOINTER_SIZE_TYPE ) ( pxBlock ) ) ^ xHeapCanary ) )
127 #else
128 
129     #define heapPROTECT_BLOCK_POINTER( pxBlock )    ( pxBlock )
130 
131 #endif /* configENABLE_HEAP_PROTECTOR */
132 
133 /* Assert that a heap block pointer is within the heap bounds. */
134 #define heapVALIDATE_BLOCK_POINTER( pxBlock )                          \
135     configASSERT( ( ( uint8_t * ) ( pxBlock ) >= &( ucHeap[ 0 ] ) ) && \
136                   ( ( uint8_t * ) ( pxBlock ) <= &( ucHeap[ configTOTAL_HEAP_SIZE - 1 ] ) ) )
137 
138 /*-----------------------------------------------------------*/
139 
140 /*
141  * Inserts a block of memory that is being freed into the correct position in
142  * the list of free memory blocks.  The block being freed will be merged with
143  * the block in front it and/or the block behind it if the memory blocks are
144  * adjacent to each other.
145  */
146 static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) PRIVILEGED_FUNCTION;
147 
148 /*
149  * Called automatically to setup the required heap structures the first time
150  * pvPortMalloc() is called.
151  */
152 static void prvHeapInit( void ) PRIVILEGED_FUNCTION;
153 
154 /*-----------------------------------------------------------*/
155 
156 /* The size of the structure placed at the beginning of each allocated memory
157  * block must by correctly byte aligned. */
158 static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
159 
160 /* Create a couple of list links to mark the start and end of the list. */
161 PRIVILEGED_DATA static BlockLink_t xStart;
162 PRIVILEGED_DATA static BlockLink_t * pxEnd = NULL;
163 
164 /* Keeps track of the number of calls to allocate and free memory as well as the
165  * number of free bytes remaining, but says nothing about fragmentation. */
166 PRIVILEGED_DATA static size_t xFreeBytesRemaining = ( size_t ) 0U;
167 PRIVILEGED_DATA static size_t xMinimumEverFreeBytesRemaining = ( size_t ) 0U;
168 PRIVILEGED_DATA static size_t xNumberOfSuccessfulAllocations = ( size_t ) 0U;
169 PRIVILEGED_DATA static size_t xNumberOfSuccessfulFrees = ( size_t ) 0U;
170 
171 /*-----------------------------------------------------------*/
172 
pvPortMalloc(size_t xWantedSize)173 void * pvPortMalloc( size_t xWantedSize )
174 {
175     BlockLink_t * pxBlock;
176     BlockLink_t * pxPreviousBlock;
177     BlockLink_t * pxNewBlockLink;
178     void * pvReturn = NULL;
179     size_t xAdditionalRequiredSize;
180 
181     if( xWantedSize > 0 )
182     {
183         /* The wanted size must be increased so it can contain a BlockLink_t
184          * structure in addition to the requested amount of bytes. */
185         if( heapADD_WILL_OVERFLOW( xWantedSize, xHeapStructSize ) == 0 )
186         {
187             xWantedSize += xHeapStructSize;
188 
189             /* Ensure that blocks are always aligned to the required number
190              * of bytes. */
191             if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
192             {
193                 /* Byte alignment required. */
194                 xAdditionalRequiredSize = portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK );
195 
196                 if( heapADD_WILL_OVERFLOW( xWantedSize, xAdditionalRequiredSize ) == 0 )
197                 {
198                     xWantedSize += xAdditionalRequiredSize;
199                 }
200                 else
201                 {
202                     xWantedSize = 0;
203                 }
204             }
205             else
206             {
207                 mtCOVERAGE_TEST_MARKER();
208             }
209         }
210         else
211         {
212             xWantedSize = 0;
213         }
214     }
215     else
216     {
217         mtCOVERAGE_TEST_MARKER();
218     }
219 
220     vTaskSuspendAll();
221     {
222         /* If this is the first call to malloc then the heap will require
223          * initialisation to setup the list of free blocks. */
224         if( pxEnd == NULL )
225         {
226             prvHeapInit();
227         }
228         else
229         {
230             mtCOVERAGE_TEST_MARKER();
231         }
232 
233         /* Check the block size we are trying to allocate is not so large that the
234          * top bit is set.  The top bit of the block size member of the BlockLink_t
235          * structure is used to determine who owns the block - the application or
236          * the kernel, so it must be free. */
237         if( heapBLOCK_SIZE_IS_VALID( xWantedSize ) != 0 )
238         {
239             if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
240             {
241                 /* Traverse the list from the start (lowest address) block until
242                  * one of adequate size is found. */
243                 pxPreviousBlock = &xStart;
244                 pxBlock = heapPROTECT_BLOCK_POINTER( xStart.pxNextFreeBlock );
245                 heapVALIDATE_BLOCK_POINTER( pxBlock );
246 
247                 while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != heapPROTECT_BLOCK_POINTER( NULL ) ) )
248                 {
249                     pxPreviousBlock = pxBlock;
250                     pxBlock = heapPROTECT_BLOCK_POINTER( pxBlock->pxNextFreeBlock );
251                     heapVALIDATE_BLOCK_POINTER( pxBlock );
252                 }
253 
254                 /* If the end marker was reached then a block of adequate size
255                  * was not found. */
256                 if( pxBlock != pxEnd )
257                 {
258                     /* Return the memory space pointed to - jumping over the
259                      * BlockLink_t structure at its start. */
260                     pvReturn = ( void * ) ( ( ( uint8_t * ) heapPROTECT_BLOCK_POINTER( pxPreviousBlock->pxNextFreeBlock ) ) + xHeapStructSize );
261                     heapVALIDATE_BLOCK_POINTER( pvReturn );
262 
263                     /* This block is being returned for use so must be taken out
264                      * of the list of free blocks. */
265                     pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
266 
267                     /* If the block is larger than required it can be split into
268                      * two. */
269                     configASSERT( heapSUBTRACT_WILL_UNDERFLOW( pxBlock->xBlockSize, xWantedSize ) == 0 );
270 
271                     if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
272                     {
273                         /* This block is to be split into two.  Create a new
274                          * block following the number of bytes requested. The void
275                          * cast is used to prevent byte alignment warnings from the
276                          * compiler. */
277                         pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
278                         configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 );
279 
280                         /* Calculate the sizes of two blocks split from the
281                          * single block. */
282                         pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
283                         pxBlock->xBlockSize = xWantedSize;
284 
285                         /* Insert the new block into the list of free blocks. */
286                         pxNewBlockLink->pxNextFreeBlock = pxPreviousBlock->pxNextFreeBlock;
287                         pxPreviousBlock->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxNewBlockLink );
288                     }
289                     else
290                     {
291                         mtCOVERAGE_TEST_MARKER();
292                     }
293 
294                     xFreeBytesRemaining -= pxBlock->xBlockSize;
295 
296                     if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
297                     {
298                         xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
299                     }
300                     else
301                     {
302                         mtCOVERAGE_TEST_MARKER();
303                     }
304 
305                     /* The block is being returned - it is allocated and owned
306                      * by the application and has no "next" block. */
307                     heapALLOCATE_BLOCK( pxBlock );
308                     pxBlock->pxNextFreeBlock = NULL;
309                     xNumberOfSuccessfulAllocations++;
310                 }
311                 else
312                 {
313                     mtCOVERAGE_TEST_MARKER();
314                 }
315             }
316             else
317             {
318                 mtCOVERAGE_TEST_MARKER();
319             }
320         }
321         else
322         {
323             mtCOVERAGE_TEST_MARKER();
324         }
325 
326         traceMALLOC( pvReturn, xWantedSize );
327     }
328     ( void ) xTaskResumeAll();
329 
330     #if ( configUSE_MALLOC_FAILED_HOOK == 1 )
331     {
332         if( pvReturn == NULL )
333         {
334             vApplicationMallocFailedHook();
335         }
336         else
337         {
338             mtCOVERAGE_TEST_MARKER();
339         }
340     }
341     #endif /* if ( configUSE_MALLOC_FAILED_HOOK == 1 ) */
342 
343     configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 );
344     return pvReturn;
345 }
346 /*-----------------------------------------------------------*/
347 
vPortFree(void * pv)348 void vPortFree( void * pv )
349 {
350     uint8_t * puc = ( uint8_t * ) pv;
351     BlockLink_t * pxLink;
352 
353     if( pv != NULL )
354     {
355         /* The memory being freed will have an BlockLink_t structure immediately
356          * before it. */
357         puc -= xHeapStructSize;
358 
359         /* This casting is to keep the compiler from issuing warnings. */
360         pxLink = ( void * ) puc;
361 
362         heapVALIDATE_BLOCK_POINTER( pxLink );
363         configASSERT( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 );
364         configASSERT( pxLink->pxNextFreeBlock == NULL );
365 
366         if( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 )
367         {
368             if( pxLink->pxNextFreeBlock == NULL )
369             {
370                 /* The block is being returned to the heap - it is no longer
371                  * allocated. */
372                 heapFREE_BLOCK( pxLink );
373                 #if ( configHEAP_CLEAR_MEMORY_ON_FREE == 1 )
374                 {
375                     /* Check for underflow as this can occur if xBlockSize is
376                      * overwritten in a heap block. */
377                     if( heapSUBTRACT_WILL_UNDERFLOW( pxLink->xBlockSize, xHeapStructSize ) == 0 )
378                     {
379                         ( void ) memset( puc + xHeapStructSize, 0, pxLink->xBlockSize - xHeapStructSize );
380                     }
381                 }
382                 #endif
383 
384                 vTaskSuspendAll();
385                 {
386                     /* Add this block to the list of free blocks. */
387                     xFreeBytesRemaining += pxLink->xBlockSize;
388                     traceFREE( pv, pxLink->xBlockSize );
389                     prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
390                     xNumberOfSuccessfulFrees++;
391                 }
392                 ( void ) xTaskResumeAll();
393             }
394             else
395             {
396                 mtCOVERAGE_TEST_MARKER();
397             }
398         }
399         else
400         {
401             mtCOVERAGE_TEST_MARKER();
402         }
403     }
404 }
405 /*-----------------------------------------------------------*/
406 
xPortGetFreeHeapSize(void)407 size_t xPortGetFreeHeapSize( void )
408 {
409     return xFreeBytesRemaining;
410 }
411 /*-----------------------------------------------------------*/
412 
xPortGetMinimumEverFreeHeapSize(void)413 size_t xPortGetMinimumEverFreeHeapSize( void )
414 {
415     return xMinimumEverFreeBytesRemaining;
416 }
417 /*-----------------------------------------------------------*/
418 
vPortInitialiseBlocks(void)419 void vPortInitialiseBlocks( void )
420 {
421     /* This just exists to keep the linker quiet. */
422 }
423 /*-----------------------------------------------------------*/
424 
pvPortCalloc(size_t xNum,size_t xSize)425 void * pvPortCalloc( size_t xNum,
426                      size_t xSize )
427 {
428     void * pv = NULL;
429 
430     if( heapMULTIPLY_WILL_OVERFLOW( xNum, xSize ) == 0 )
431     {
432         pv = pvPortMalloc( xNum * xSize );
433 
434         if( pv != NULL )
435         {
436             ( void ) memset( pv, 0, xNum * xSize );
437         }
438     }
439 
440     return pv;
441 }
442 /*-----------------------------------------------------------*/
443 
prvHeapInit(void)444 static void prvHeapInit( void ) /* PRIVILEGED_FUNCTION */
445 {
446     BlockLink_t * pxFirstFreeBlock;
447     portPOINTER_SIZE_TYPE uxStartAddress, uxEndAddress;
448     size_t xTotalHeapSize = configTOTAL_HEAP_SIZE;
449 
450     /* Ensure the heap starts on a correctly aligned boundary. */
451     uxStartAddress = ( portPOINTER_SIZE_TYPE ) ucHeap;
452 
453     if( ( uxStartAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
454     {
455         uxStartAddress += ( portBYTE_ALIGNMENT - 1 );
456         uxStartAddress &= ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK );
457         xTotalHeapSize -= ( size_t ) ( uxStartAddress - ( portPOINTER_SIZE_TYPE ) ucHeap );
458     }
459 
460     #if ( configENABLE_HEAP_PROTECTOR == 1 )
461     {
462         vApplicationGetRandomHeapCanary( &( xHeapCanary ) );
463     }
464     #endif
465 
466     /* xStart is used to hold a pointer to the first item in the list of free
467      * blocks.  The void cast is used to prevent compiler warnings. */
468     xStart.pxNextFreeBlock = ( void * ) heapPROTECT_BLOCK_POINTER( uxStartAddress );
469     xStart.xBlockSize = ( size_t ) 0;
470 
471     /* pxEnd is used to mark the end of the list of free blocks and is inserted
472      * at the end of the heap space. */
473     uxEndAddress = uxStartAddress + ( portPOINTER_SIZE_TYPE ) xTotalHeapSize;
474     uxEndAddress -= ( portPOINTER_SIZE_TYPE ) xHeapStructSize;
475     uxEndAddress &= ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK );
476     pxEnd = ( BlockLink_t * ) uxEndAddress;
477     pxEnd->xBlockSize = 0;
478     pxEnd->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( NULL );
479 
480     /* To start with there is a single free block that is sized to take up the
481      * entire heap space, minus the space taken by pxEnd. */
482     pxFirstFreeBlock = ( BlockLink_t * ) uxStartAddress;
483     pxFirstFreeBlock->xBlockSize = ( size_t ) ( uxEndAddress - ( portPOINTER_SIZE_TYPE ) pxFirstFreeBlock );
484     pxFirstFreeBlock->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxEnd );
485 
486     /* Only one block exists - and it covers the entire usable heap space. */
487     xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
488     xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
489 }
490 /*-----------------------------------------------------------*/
491 
prvInsertBlockIntoFreeList(BlockLink_t * pxBlockToInsert)492 static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) /* PRIVILEGED_FUNCTION */
493 {
494     BlockLink_t * pxIterator;
495     uint8_t * puc;
496 
497     /* Iterate through the list until a block is found that has a higher address
498      * than the block being inserted. */
499     for( pxIterator = &xStart; heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock ) < pxBlockToInsert; pxIterator = heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock ) )
500     {
501         /* Nothing to do here, just iterate to the right position. */
502     }
503 
504     if( pxIterator != &xStart )
505     {
506         heapVALIDATE_BLOCK_POINTER( pxIterator );
507     }
508 
509     /* Do the block being inserted, and the block it is being inserted after
510      * make a contiguous block of memory? */
511     puc = ( uint8_t * ) pxIterator;
512 
513     if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
514     {
515         pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
516         pxBlockToInsert = pxIterator;
517     }
518     else
519     {
520         mtCOVERAGE_TEST_MARKER();
521     }
522 
523     /* Do the block being inserted, and the block it is being inserted before
524      * make a contiguous block of memory? */
525     puc = ( uint8_t * ) pxBlockToInsert;
526 
527     if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock ) )
528     {
529         if( heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock ) != pxEnd )
530         {
531             /* Form one big block from the two blocks. */
532             pxBlockToInsert->xBlockSize += heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock )->xBlockSize;
533             pxBlockToInsert->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock )->pxNextFreeBlock;
534         }
535         else
536         {
537             pxBlockToInsert->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxEnd );
538         }
539     }
540     else
541     {
542         pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
543     }
544 
545     /* If the block being inserted plugged a gab, so was merged with the block
546      * before and the block after, then it's pxNextFreeBlock pointer will have
547      * already been set, and should not be set here as that would make it point
548      * to itself. */
549     if( pxIterator != pxBlockToInsert )
550     {
551         pxIterator->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxBlockToInsert );
552     }
553     else
554     {
555         mtCOVERAGE_TEST_MARKER();
556     }
557 }
558 /*-----------------------------------------------------------*/
559 
vPortGetHeapStats(HeapStats_t * pxHeapStats)560 void vPortGetHeapStats( HeapStats_t * pxHeapStats )
561 {
562     BlockLink_t * pxBlock;
563     size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */
564 
565     vTaskSuspendAll();
566     {
567         pxBlock = heapPROTECT_BLOCK_POINTER( xStart.pxNextFreeBlock );
568 
569         /* pxBlock will be NULL if the heap has not been initialised.  The heap
570          * is initialised automatically when the first allocation is made. */
571         if( pxBlock != NULL )
572         {
573             while( pxBlock != pxEnd )
574             {
575                 /* Increment the number of blocks and record the largest block seen
576                  * so far. */
577                 xBlocks++;
578 
579                 if( pxBlock->xBlockSize > xMaxSize )
580                 {
581                     xMaxSize = pxBlock->xBlockSize;
582                 }
583 
584                 if( pxBlock->xBlockSize < xMinSize )
585                 {
586                     xMinSize = pxBlock->xBlockSize;
587                 }
588 
589                 /* Move to the next block in the chain until the last block is
590                  * reached. */
591                 pxBlock = heapPROTECT_BLOCK_POINTER( pxBlock->pxNextFreeBlock );
592             }
593         }
594     }
595     ( void ) xTaskResumeAll();
596 
597     pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize;
598     pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize;
599     pxHeapStats->xNumberOfFreeBlocks = xBlocks;
600 
601     taskENTER_CRITICAL();
602     {
603         pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining;
604         pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations;
605         pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees;
606         pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining;
607     }
608     taskEXIT_CRITICAL();
609 }
610 /*-----------------------------------------------------------*/
611 
612 /*
613  * Reset the state in this file. This state is normally initialized at start up.
614  * This function must be called by the application before restarting the
615  * scheduler.
616  */
vPortHeapResetState(void)617 void vPortHeapResetState( void )
618 {
619     pxEnd = NULL;
620 
621     xFreeBytesRemaining = ( size_t ) 0U;
622     xMinimumEverFreeBytesRemaining = ( size_t ) 0U;
623     xNumberOfSuccessfulAllocations = ( size_t ) 0U;
624     xNumberOfSuccessfulFrees = ( size_t ) 0U;
625 }
626 /*-----------------------------------------------------------*/
627