]> begriffs open source - cmsis-freertos/blob - Source/portable/MemMang/heap_5.c
Correct memory allocation and access in osMemoryPoolNew (#142)
[cmsis-freertos] / Source / portable / MemMang / heap_5.c
1 /*
2  * FreeRTOS Kernel V11.2.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  * Setting configVALIDATE_HEAP_BLOCK_POINTER to 1 enables customized heap block pointers
134  * protection on heap_5. */
135     #ifndef configVALIDATE_HEAP_BLOCK_POINTER
136         #define heapVALIDATE_BLOCK_POINTER( pxBlock )                           \
137             configASSERT( ( pucHeapHighAddress != NULL ) &&                     \
138                           ( pucHeapLowAddress != NULL ) &&                      \
139                           ( ( uint8_t * ) ( pxBlock ) >= pucHeapLowAddress ) && \
140                           ( ( uint8_t * ) ( pxBlock ) < pucHeapHighAddress ) )
141     #else /* ifndef configVALIDATE_HEAP_BLOCK_POINTER */
142         #define heapVALIDATE_BLOCK_POINTER( pxBlock )                           \
143             configVALIDATE_HEAP_BLOCK_POINTER( pxBlock )
144     #endif /* configVALIDATE_HEAP_BLOCK_POINTER */
145
146 #else /* if ( configENABLE_HEAP_PROTECTOR == 1 ) */
147
148     #define heapPROTECT_BLOCK_POINTER( pxBlock )    ( pxBlock )
149
150     #define heapVALIDATE_BLOCK_POINTER( pxBlock )
151
152 #endif /* configENABLE_HEAP_PROTECTOR */
153
154 /*-----------------------------------------------------------*/
155
156 /* Define the linked list structure.  This is used to link free blocks in order
157  * of their memory address. */
158 typedef struct A_BLOCK_LINK
159 {
160     struct A_BLOCK_LINK * pxNextFreeBlock; /**< The next free block in the list. */
161     size_t xBlockSize;                     /**< The size of the free block. */
162 } BlockLink_t;
163
164 /*-----------------------------------------------------------*/
165
166 /*
167  * Inserts a block of memory that is being freed into the correct position in
168  * the list of free memory blocks.  The block being freed will be merged with
169  * the block in front it and/or the block behind it if the memory blocks are
170  * adjacent to each other.
171  */
172 static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) PRIVILEGED_FUNCTION;
173 void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) PRIVILEGED_FUNCTION;
174
175 #if ( configENABLE_HEAP_PROTECTOR == 1 )
176
177 /**
178  * @brief Application provided function to get a random value to be used as canary.
179  *
180  * @param pxHeapCanary [out] Output parameter to return the canary value.
181  */
182     extern void vApplicationGetRandomHeapCanary( portPOINTER_SIZE_TYPE * pxHeapCanary );
183 #endif /* configENABLE_HEAP_PROTECTOR */
184
185 /*-----------------------------------------------------------*/
186
187 /* The size of the structure placed at the beginning of each allocated memory
188  * block must by correctly byte aligned. */
189 static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
190
191 /* Create a couple of list links to mark the start and end of the list. */
192 PRIVILEGED_DATA static BlockLink_t xStart;
193 PRIVILEGED_DATA static BlockLink_t * pxEnd = NULL;
194
195 /* Keeps track of the number of calls to allocate and free memory as well as the
196  * number of free bytes remaining, but says nothing about fragmentation. */
197 PRIVILEGED_DATA static size_t xFreeBytesRemaining = ( size_t ) 0U;
198 PRIVILEGED_DATA static size_t xMinimumEverFreeBytesRemaining = ( size_t ) 0U;
199 PRIVILEGED_DATA static size_t xNumberOfSuccessfulAllocations = ( size_t ) 0U;
200 PRIVILEGED_DATA static size_t xNumberOfSuccessfulFrees = ( size_t ) 0U;
201
202 #if ( configENABLE_HEAP_PROTECTOR == 1 )
203
204 /* Canary value for protecting internal heap pointers. */
205     PRIVILEGED_DATA static portPOINTER_SIZE_TYPE xHeapCanary;
206
207 /* Highest and lowest heap addresses used for heap block bounds checking. */
208     PRIVILEGED_DATA static uint8_t * pucHeapHighAddress = NULL;
209     PRIVILEGED_DATA static uint8_t * pucHeapLowAddress = NULL;
210
211 #endif /* configENABLE_HEAP_PROTECTOR */
212
213 /*-----------------------------------------------------------*/
214
215 void * pvPortMalloc( size_t xWantedSize )
216 {
217     BlockLink_t * pxBlock;
218     BlockLink_t * pxPreviousBlock;
219     BlockLink_t * pxNewBlockLink;
220     void * pvReturn = NULL;
221     size_t xAdditionalRequiredSize;
222     size_t xAllocatedBlockSize = 0;
223
224     /* The heap must be initialised before the first call to
225      * pvPortMalloc(). */
226     configASSERT( pxEnd );
227
228     if( xWantedSize > 0 )
229     {
230         /* The wanted size must be increased so it can contain a BlockLink_t
231          * structure in addition to the requested amount of bytes. */
232         if( heapADD_WILL_OVERFLOW( xWantedSize, xHeapStructSize ) == 0 )
233         {
234             xWantedSize += xHeapStructSize;
235
236             /* Ensure that blocks are always aligned to the required number
237              * of bytes. */
238             if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
239             {
240                 /* Byte alignment required. */
241                 xAdditionalRequiredSize = portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK );
242
243                 if( heapADD_WILL_OVERFLOW( xWantedSize, xAdditionalRequiredSize ) == 0 )
244                 {
245                     xWantedSize += xAdditionalRequiredSize;
246                 }
247                 else
248                 {
249                     xWantedSize = 0;
250                 }
251             }
252             else
253             {
254                 mtCOVERAGE_TEST_MARKER();
255             }
256         }
257         else
258         {
259             xWantedSize = 0;
260         }
261     }
262     else
263     {
264         mtCOVERAGE_TEST_MARKER();
265     }
266
267     vTaskSuspendAll();
268     {
269         /* Check the block size we are trying to allocate is not so large that the
270          * top bit is set.  The top bit of the block size member of the BlockLink_t
271          * structure is used to determine who owns the block - the application or
272          * the kernel, so it must be free. */
273         if( heapBLOCK_SIZE_IS_VALID( xWantedSize ) != 0 )
274         {
275             if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
276             {
277                 /* Traverse the list from the start (lowest address) block until
278                  * one of adequate size is found. */
279                 pxPreviousBlock = &xStart;
280                 pxBlock = heapPROTECT_BLOCK_POINTER( xStart.pxNextFreeBlock );
281                 heapVALIDATE_BLOCK_POINTER( pxBlock );
282
283                 while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != heapPROTECT_BLOCK_POINTER( NULL ) ) )
284                 {
285                     pxPreviousBlock = pxBlock;
286                     pxBlock = heapPROTECT_BLOCK_POINTER( pxBlock->pxNextFreeBlock );
287                     heapVALIDATE_BLOCK_POINTER( pxBlock );
288                 }
289
290                 /* If the end marker was reached then a block of adequate size
291                  * was not found. */
292                 if( pxBlock != pxEnd )
293                 {
294                     /* Return the memory space pointed to - jumping over the
295                      * BlockLink_t structure at its start. */
296                     pvReturn = ( void * ) ( ( ( uint8_t * ) heapPROTECT_BLOCK_POINTER( pxPreviousBlock->pxNextFreeBlock ) ) + xHeapStructSize );
297                     heapVALIDATE_BLOCK_POINTER( pvReturn );
298
299                     /* This block is being returned for use so must be taken out
300                      * of the list of free blocks. */
301                     pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
302
303                     /* If the block is larger than required it can be split into
304                      * two. */
305                     configASSERT( heapSUBTRACT_WILL_UNDERFLOW( pxBlock->xBlockSize, xWantedSize ) == 0 );
306
307                     if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
308                     {
309                         /* This block is to be split into two.  Create a new
310                          * block following the number of bytes requested. The void
311                          * cast is used to prevent byte alignment warnings from the
312                          * compiler. */
313                         pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
314                         configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 );
315
316                         /* Calculate the sizes of two blocks split from the
317                          * single block. */
318                         pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
319                         pxBlock->xBlockSize = xWantedSize;
320
321                         /* Insert the new block into the list of free blocks. */
322                         pxNewBlockLink->pxNextFreeBlock = pxPreviousBlock->pxNextFreeBlock;
323                         pxPreviousBlock->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxNewBlockLink );
324                     }
325                     else
326                     {
327                         mtCOVERAGE_TEST_MARKER();
328                     }
329
330                     xFreeBytesRemaining -= pxBlock->xBlockSize;
331
332                     if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
333                     {
334                         xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
335                     }
336                     else
337                     {
338                         mtCOVERAGE_TEST_MARKER();
339                     }
340
341                     xAllocatedBlockSize = pxBlock->xBlockSize;
342
343                     /* The block is being returned - it is allocated and owned
344                      * by the application and has no "next" block. */
345                     heapALLOCATE_BLOCK( pxBlock );
346                     pxBlock->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( NULL );
347                     xNumberOfSuccessfulAllocations++;
348                 }
349                 else
350                 {
351                     mtCOVERAGE_TEST_MARKER();
352                 }
353             }
354             else
355             {
356                 mtCOVERAGE_TEST_MARKER();
357             }
358         }
359         else
360         {
361             mtCOVERAGE_TEST_MARKER();
362         }
363
364         traceMALLOC( pvReturn, xAllocatedBlockSize );
365
366         /* Prevent compiler warnings when trace macros are not used. */
367         ( void ) xAllocatedBlockSize;
368     }
369     ( void ) xTaskResumeAll();
370
371     #if ( configUSE_MALLOC_FAILED_HOOK == 1 )
372     {
373         if( pvReturn == NULL )
374         {
375             vApplicationMallocFailedHook();
376         }
377         else
378         {
379             mtCOVERAGE_TEST_MARKER();
380         }
381     }
382     #endif /* if ( configUSE_MALLOC_FAILED_HOOK == 1 ) */
383
384     configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 );
385     return pvReturn;
386 }
387 /*-----------------------------------------------------------*/
388
389 void vPortFree( void * pv )
390 {
391     uint8_t * puc = ( uint8_t * ) pv;
392     BlockLink_t * pxLink;
393
394     if( pv != NULL )
395     {
396         /* The memory being freed will have an BlockLink_t structure immediately
397          * before it. */
398         puc -= xHeapStructSize;
399
400         /* This casting is to keep the compiler from issuing warnings. */
401         pxLink = ( void * ) puc;
402
403         heapVALIDATE_BLOCK_POINTER( pxLink );
404         configASSERT( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 );
405         configASSERT( pxLink->pxNextFreeBlock == heapPROTECT_BLOCK_POINTER( NULL ) );
406
407         if( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 )
408         {
409             if( pxLink->pxNextFreeBlock == heapPROTECT_BLOCK_POINTER( NULL ) )
410             {
411                 /* The block is being returned to the heap - it is no longer
412                  * allocated. */
413                 heapFREE_BLOCK( pxLink );
414                 #if ( configHEAP_CLEAR_MEMORY_ON_FREE == 1 )
415                 {
416                     /* Check for underflow as this can occur if xBlockSize is
417                      * overwritten in a heap block. */
418                     if( heapSUBTRACT_WILL_UNDERFLOW( pxLink->xBlockSize, xHeapStructSize ) == 0 )
419                     {
420                         ( void ) memset( puc + xHeapStructSize, 0, pxLink->xBlockSize - xHeapStructSize );
421                     }
422                 }
423                 #endif
424
425                 vTaskSuspendAll();
426                 {
427                     /* Add this block to the list of free blocks. */
428                     xFreeBytesRemaining += pxLink->xBlockSize;
429                     traceFREE( pv, pxLink->xBlockSize );
430                     prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
431                     xNumberOfSuccessfulFrees++;
432                 }
433                 ( void ) xTaskResumeAll();
434             }
435             else
436             {
437                 mtCOVERAGE_TEST_MARKER();
438             }
439         }
440         else
441         {
442             mtCOVERAGE_TEST_MARKER();
443         }
444     }
445 }
446 /*-----------------------------------------------------------*/
447
448 size_t xPortGetFreeHeapSize( void )
449 {
450     return xFreeBytesRemaining;
451 }
452 /*-----------------------------------------------------------*/
453
454 size_t xPortGetMinimumEverFreeHeapSize( void )
455 {
456     return xMinimumEverFreeBytesRemaining;
457 }
458 /*-----------------------------------------------------------*/
459
460 void xPortResetHeapMinimumEverFreeHeapSize( void )
461 {
462     xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
463 }
464 /*-----------------------------------------------------------*/
465
466 void * pvPortCalloc( size_t xNum,
467                      size_t xSize )
468 {
469     void * pv = NULL;
470
471     if( heapMULTIPLY_WILL_OVERFLOW( xNum, xSize ) == 0 )
472     {
473         pv = pvPortMalloc( xNum * xSize );
474
475         if( pv != NULL )
476         {
477             ( void ) memset( pv, 0, xNum * xSize );
478         }
479     }
480
481     return pv;
482 }
483 /*-----------------------------------------------------------*/
484
485 static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) /* PRIVILEGED_FUNCTION */
486 {
487     BlockLink_t * pxIterator;
488     uint8_t * puc;
489
490     /* Iterate through the list until a block is found that has a higher address
491      * than the block being inserted. */
492     for( pxIterator = &xStart; heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock ) < pxBlockToInsert; pxIterator = heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock ) )
493     {
494         /* Nothing to do here, just iterate to the right position. */
495     }
496
497     if( pxIterator != &xStart )
498     {
499         heapVALIDATE_BLOCK_POINTER( pxIterator );
500     }
501
502     /* Do the block being inserted, and the block it is being inserted after
503      * make a contiguous block of memory? */
504     puc = ( uint8_t * ) pxIterator;
505
506     if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
507     {
508         pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
509         pxBlockToInsert = pxIterator;
510     }
511     else
512     {
513         mtCOVERAGE_TEST_MARKER();
514     }
515
516     /* Do the block being inserted, and the block it is being inserted before
517      * make a contiguous block of memory? */
518     puc = ( uint8_t * ) pxBlockToInsert;
519
520     if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock ) )
521     {
522         if( heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock ) != pxEnd )
523         {
524             /* Form one big block from the two blocks. */
525             pxBlockToInsert->xBlockSize += heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock )->xBlockSize;
526             pxBlockToInsert->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxIterator->pxNextFreeBlock )->pxNextFreeBlock;
527         }
528         else
529         {
530             pxBlockToInsert->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxEnd );
531         }
532     }
533     else
534     {
535         pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
536     }
537
538     /* If the block being inserted plugged a gap, so was merged with the block
539      * before and the block after, then it's pxNextFreeBlock pointer will have
540      * already been set, and should not be set here as that would make it point
541      * to itself. */
542     if( pxIterator != pxBlockToInsert )
543     {
544         pxIterator->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxBlockToInsert );
545     }
546     else
547     {
548         mtCOVERAGE_TEST_MARKER();
549     }
550 }
551 /*-----------------------------------------------------------*/
552
553 void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) /* PRIVILEGED_FUNCTION */
554 {
555     BlockLink_t * pxFirstFreeBlockInRegion = NULL;
556     BlockLink_t * pxPreviousFreeBlock;
557     portPOINTER_SIZE_TYPE xAlignedHeap;
558     size_t xTotalRegionSize, xTotalHeapSize = 0;
559     BaseType_t xDefinedRegions = 0;
560     portPOINTER_SIZE_TYPE xAddress;
561     const HeapRegion_t * pxHeapRegion;
562
563     /* Can only call once! */
564     configASSERT( pxEnd == NULL );
565
566     #if ( configENABLE_HEAP_PROTECTOR == 1 )
567     {
568         vApplicationGetRandomHeapCanary( &( xHeapCanary ) );
569     }
570     #endif
571
572     pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
573
574     while( pxHeapRegion->xSizeInBytes > 0 )
575     {
576         xTotalRegionSize = pxHeapRegion->xSizeInBytes;
577
578         /* Ensure the heap region starts on a correctly aligned boundary. */
579         xAddress = ( portPOINTER_SIZE_TYPE ) pxHeapRegion->pucStartAddress;
580
581         if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
582         {
583             xAddress += ( portBYTE_ALIGNMENT - 1 );
584             xAddress &= ~( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK;
585
586             /* Adjust the size for the bytes lost to alignment. */
587             xTotalRegionSize -= ( size_t ) ( xAddress - ( portPOINTER_SIZE_TYPE ) pxHeapRegion->pucStartAddress );
588         }
589
590         xAlignedHeap = xAddress;
591
592         /* Set xStart if it has not already been set. */
593         if( xDefinedRegions == 0 )
594         {
595             /* xStart is used to hold a pointer to the first item in the list of
596              *  free blocks.  The void cast is used to prevent compiler warnings. */
597             xStart.pxNextFreeBlock = ( BlockLink_t * ) heapPROTECT_BLOCK_POINTER( xAlignedHeap );
598             xStart.xBlockSize = ( size_t ) 0;
599         }
600         else
601         {
602             /* Should only get here if one region has already been added to the
603              * heap. */
604             configASSERT( pxEnd != heapPROTECT_BLOCK_POINTER( NULL ) );
605
606             /* Check blocks are passed in with increasing start addresses. */
607             configASSERT( ( size_t ) xAddress > ( size_t ) pxEnd );
608         }
609
610         #if ( configENABLE_HEAP_PROTECTOR == 1 )
611         {
612             if( ( pucHeapLowAddress == NULL ) ||
613                 ( ( uint8_t * ) xAlignedHeap < pucHeapLowAddress ) )
614             {
615                 pucHeapLowAddress = ( uint8_t * ) xAlignedHeap;
616             }
617         }
618         #endif /* configENABLE_HEAP_PROTECTOR */
619
620         /* Remember the location of the end marker in the previous region, if
621          * any. */
622         pxPreviousFreeBlock = pxEnd;
623
624         /* pxEnd is used to mark the end of the list of free blocks and is
625          * inserted at the end of the region space. */
626         xAddress = xAlignedHeap + ( portPOINTER_SIZE_TYPE ) xTotalRegionSize;
627         xAddress -= ( portPOINTER_SIZE_TYPE ) xHeapStructSize;
628         xAddress &= ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK );
629         pxEnd = ( BlockLink_t * ) xAddress;
630         pxEnd->xBlockSize = 0;
631         pxEnd->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( NULL );
632
633         /* To start with there is a single free block in this region that is
634          * sized to take up the entire heap region minus the space taken by the
635          * free block structure. */
636         pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap;
637         pxFirstFreeBlockInRegion->xBlockSize = ( size_t ) ( xAddress - ( portPOINTER_SIZE_TYPE ) pxFirstFreeBlockInRegion );
638         pxFirstFreeBlockInRegion->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxEnd );
639
640         /* If this is not the first region that makes up the entire heap space
641          * then link the previous region to this region. */
642         if( pxPreviousFreeBlock != NULL )
643         {
644             pxPreviousFreeBlock->pxNextFreeBlock = heapPROTECT_BLOCK_POINTER( pxFirstFreeBlockInRegion );
645         }
646
647         xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize;
648
649         #if ( configENABLE_HEAP_PROTECTOR == 1 )
650         {
651             if( ( pucHeapHighAddress == NULL ) ||
652                 ( ( ( ( uint8_t * ) pxFirstFreeBlockInRegion ) + pxFirstFreeBlockInRegion->xBlockSize ) > pucHeapHighAddress ) )
653             {
654                 pucHeapHighAddress = ( ( uint8_t * ) pxFirstFreeBlockInRegion ) + pxFirstFreeBlockInRegion->xBlockSize;
655             }
656         }
657         #endif
658
659         /* Move onto the next HeapRegion_t structure. */
660         xDefinedRegions++;
661         pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
662     }
663
664     xMinimumEverFreeBytesRemaining = xTotalHeapSize;
665     xFreeBytesRemaining = xTotalHeapSize;
666
667     /* Check something was actually defined before it is accessed. */
668     configASSERT( xTotalHeapSize );
669 }
670 /*-----------------------------------------------------------*/
671
672 void vPortGetHeapStats( HeapStats_t * pxHeapStats )
673 {
674     BlockLink_t * pxBlock;
675     size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */
676
677     vTaskSuspendAll();
678     {
679         pxBlock = heapPROTECT_BLOCK_POINTER( xStart.pxNextFreeBlock );
680
681         /* pxBlock will be NULL if the heap has not been initialised.  The heap
682          * is initialised automatically when the first allocation is made. */
683         if( pxBlock != NULL )
684         {
685             while( pxBlock != pxEnd )
686             {
687                 /* Increment the number of blocks and record the largest block seen
688                  * so far. */
689                 xBlocks++;
690
691                 if( pxBlock->xBlockSize > xMaxSize )
692                 {
693                     xMaxSize = pxBlock->xBlockSize;
694                 }
695
696                 /* Heap five will have a zero sized block at the end of each
697                  * each region - the block is only used to link to the next
698                  * heap region so it not a real block. */
699                 if( pxBlock->xBlockSize != 0 )
700                 {
701                     if( pxBlock->xBlockSize < xMinSize )
702                     {
703                         xMinSize = pxBlock->xBlockSize;
704                     }
705                 }
706
707                 /* Move to the next block in the chain until the last block is
708                  * reached. */
709                 pxBlock = heapPROTECT_BLOCK_POINTER( pxBlock->pxNextFreeBlock );
710             }
711         }
712     }
713     ( void ) xTaskResumeAll();
714
715     pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize;
716     pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize;
717     pxHeapStats->xNumberOfFreeBlocks = xBlocks;
718
719     taskENTER_CRITICAL();
720     {
721         pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining;
722         pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations;
723         pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees;
724         pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining;
725     }
726     taskEXIT_CRITICAL();
727 }
728 /*-----------------------------------------------------------*/
729
730 /*
731  * Reset the state in this file. This state is normally initialized at start up.
732  * This function must be called by the application before restarting the
733  * scheduler.
734  */
735 void vPortHeapResetState( void )
736 {
737     pxEnd = NULL;
738
739     xFreeBytesRemaining = ( size_t ) 0U;
740     xMinimumEverFreeBytesRemaining = ( size_t ) 0U;
741     xNumberOfSuccessfulAllocations = ( size_t ) 0U;
742     xNumberOfSuccessfulFrees = ( size_t ) 0U;
743
744     #if ( configENABLE_HEAP_PROTECTOR == 1 )
745         pucHeapHighAddress = NULL;
746         pucHeapLowAddress = NULL;
747     #endif /* #if ( configENABLE_HEAP_PROTECTOR == 1 ) */
748 }
749 /*-----------------------------------------------------------*/