heap_5.c 28 KB

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