heap_2.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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() and vPortFree() that permits
  30. * allocated blocks to be freed, but does not combine adjacent free blocks
  31. * into a single larger block (and so will fragment memory). See heap_4.c for
  32. * an equivalent that does combine adjacent blocks into single larger blocks.
  33. *
  34. * See heap_1.c, heap_3.c and heap_4.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. /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
  40. * all the API functions to use the MPU wrappers. That should only be done when
  41. * task.h is included from an application file. */
  42. #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  43. #include "FreeRTOS.h"
  44. #include "task.h"
  45. #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  46. #if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 )
  47. #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
  48. #endif
  49. #ifndef configHEAP_CLEAR_MEMORY_ON_FREE
  50. #define configHEAP_CLEAR_MEMORY_ON_FREE 0
  51. #endif
  52. /* A few bytes might be lost to byte aligning the heap start address. */
  53. #define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )
  54. /* Assumes 8bit bytes! */
  55. #define heapBITS_PER_BYTE ( ( size_t ) 8 )
  56. /* Max value that fits in a size_t type. */
  57. #define heapSIZE_MAX ( ~( ( size_t ) 0 ) )
  58. /* Check if multiplying a and b will result in overflow. */
  59. #define heapMULTIPLY_WILL_OVERFLOW( a, b ) ( ( ( a ) > 0 ) && ( ( b ) > ( heapSIZE_MAX / ( a ) ) ) )
  60. /* Check if adding a and b will result in overflow. */
  61. #define heapADD_WILL_OVERFLOW( a, b ) ( ( a ) > ( heapSIZE_MAX - ( b ) ) )
  62. /* MSB of the xBlockSize member of an BlockLink_t structure is used to track
  63. * the allocation status of a block. When MSB of the xBlockSize member of
  64. * an BlockLink_t structure is set then the block belongs to the application.
  65. * When the bit is free the block is still part of the free heap space. */
  66. #define heapBLOCK_ALLOCATED_BITMASK ( ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ) )
  67. #define heapBLOCK_SIZE_IS_VALID( xBlockSize ) ( ( ( xBlockSize ) & heapBLOCK_ALLOCATED_BITMASK ) == 0 )
  68. #define heapBLOCK_IS_ALLOCATED( pxBlock ) ( ( ( pxBlock->xBlockSize ) & heapBLOCK_ALLOCATED_BITMASK ) != 0 )
  69. #define heapALLOCATE_BLOCK( pxBlock ) ( ( pxBlock->xBlockSize ) |= heapBLOCK_ALLOCATED_BITMASK )
  70. #define heapFREE_BLOCK( pxBlock ) ( ( pxBlock->xBlockSize ) &= ~heapBLOCK_ALLOCATED_BITMASK )
  71. /*-----------------------------------------------------------*/
  72. /* Allocate the memory for the heap. */
  73. #if ( configAPPLICATION_ALLOCATED_HEAP == 1 )
  74. /* The application writer has already defined the array used for the RTOS
  75. * heap - probably so it can be placed in a special segment or address. */
  76. extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
  77. #else
  78. PRIVILEGED_DATA static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
  79. #endif /* configAPPLICATION_ALLOCATED_HEAP */
  80. /* Define the linked list structure. This is used to link free blocks in order
  81. * of their size. */
  82. typedef struct A_BLOCK_LINK
  83. {
  84. struct A_BLOCK_LINK * pxNextFreeBlock; /*<< The next free block in the list. */
  85. size_t xBlockSize; /*<< The size of the free block. */
  86. } BlockLink_t;
  87. static const size_t xHeapStructSize = ( ( sizeof( BlockLink_t ) + ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ) );
  88. #define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize * 2 ) )
  89. /* Create a couple of list links to mark the start and end of the list. */
  90. PRIVILEGED_DATA static BlockLink_t xStart, xEnd;
  91. /* Keeps track of the number of free bytes remaining, but says nothing about
  92. * fragmentation. */
  93. PRIVILEGED_DATA static size_t xFreeBytesRemaining = configADJUSTED_HEAP_SIZE;
  94. /* Indicates whether the heap has been initialised or not. */
  95. PRIVILEGED_DATA static BaseType_t xHeapHasBeenInitialised = pdFALSE;
  96. /*-----------------------------------------------------------*/
  97. /*
  98. * Initialises the heap structures before their first use.
  99. */
  100. static void prvHeapInit( void ) PRIVILEGED_FUNCTION;
  101. /*-----------------------------------------------------------*/
  102. /* STATIC FUNCTIONS ARE DEFINED AS MACROS TO MINIMIZE THE FUNCTION CALL DEPTH. */
  103. /*
  104. * Insert a block into the list of free blocks - which is ordered by size of
  105. * the block. Small blocks at the start of the list and large blocks at the end
  106. * of the list.
  107. */
  108. #define prvInsertBlockIntoFreeList( pxBlockToInsert ) \
  109. { \
  110. BlockLink_t * pxIterator; \
  111. size_t xBlockSize; \
  112. \
  113. xBlockSize = pxBlockToInsert->xBlockSize; \
  114. \
  115. /* Iterate through the list until a block is found that has a larger size */ \
  116. /* than the block we are inserting. */ \
  117. for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \
  118. { \
  119. /* There is nothing to do here - just iterate to the correct position. */ \
  120. } \
  121. \
  122. /* Update the list to include the block being inserted in the correct */ \
  123. /* position. */ \
  124. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; \
  125. pxIterator->pxNextFreeBlock = pxBlockToInsert; \
  126. }
  127. /*-----------------------------------------------------------*/
  128. void * pvPortMalloc( size_t xWantedSize )
  129. {
  130. BlockLink_t * pxBlock;
  131. BlockLink_t * pxPreviousBlock;
  132. BlockLink_t * pxNewBlockLink;
  133. void * pvReturn = NULL;
  134. size_t xAdditionalRequiredSize;
  135. if( xWantedSize > 0 )
  136. {
  137. /* The wanted size must be increased so it can contain a BlockLink_t
  138. * structure in addition to the requested amount of bytes. */
  139. if( heapADD_WILL_OVERFLOW( xWantedSize, xHeapStructSize ) == 0 )
  140. {
  141. xWantedSize += xHeapStructSize;
  142. /* Ensure that blocks are always aligned to the required number
  143. * of bytes. */
  144. if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
  145. {
  146. /* Byte alignment required. */
  147. xAdditionalRequiredSize = portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK );
  148. if( heapADD_WILL_OVERFLOW( xWantedSize, xAdditionalRequiredSize ) == 0 )
  149. {
  150. xWantedSize += xAdditionalRequiredSize;
  151. }
  152. else
  153. {
  154. xWantedSize = 0;
  155. }
  156. }
  157. else
  158. {
  159. mtCOVERAGE_TEST_MARKER();
  160. }
  161. }
  162. else
  163. {
  164. xWantedSize = 0;
  165. }
  166. }
  167. else
  168. {
  169. mtCOVERAGE_TEST_MARKER();
  170. }
  171. vTaskSuspendAll();
  172. {
  173. /* If this is the first call to malloc then the heap will require
  174. * initialisation to setup the list of free blocks. */
  175. if( xHeapHasBeenInitialised == pdFALSE )
  176. {
  177. prvHeapInit();
  178. xHeapHasBeenInitialised = pdTRUE;
  179. }
  180. /* Check the block size we are trying to allocate is not so large that the
  181. * top bit is set. The top bit of the block size member of the BlockLink_t
  182. * structure is used to determine who owns the block - the application or
  183. * the kernel, so it must be free. */
  184. if( heapBLOCK_SIZE_IS_VALID( xWantedSize ) != 0 )
  185. {
  186. if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
  187. {
  188. /* Blocks are stored in byte order - traverse the list from the start
  189. * (smallest) block until one of adequate size is found. */
  190. pxPreviousBlock = &xStart;
  191. pxBlock = xStart.pxNextFreeBlock;
  192. while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
  193. {
  194. pxPreviousBlock = pxBlock;
  195. pxBlock = pxBlock->pxNextFreeBlock;
  196. }
  197. /* If we found the end marker then a block of adequate size was not found. */
  198. if( pxBlock != &xEnd )
  199. {
  200. /* Return the memory space - jumping over the BlockLink_t structure
  201. * at its start. */
  202. pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
  203. /* This block is being returned for use so must be taken out of the
  204. * list of free blocks. */
  205. pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
  206. /* If the block is larger than required it can be split into two. */
  207. if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
  208. {
  209. /* This block is to be split into two. Create a new block
  210. * following the number of bytes requested. The void cast is
  211. * used to prevent byte alignment warnings from the compiler. */
  212. pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
  213. /* Calculate the sizes of two blocks split from the single
  214. * block. */
  215. pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
  216. pxBlock->xBlockSize = xWantedSize;
  217. /* Insert the new block into the list of free blocks.
  218. * The list of free blocks is sorted by their size, we have to
  219. * iterate to find the right place to insert new block. */
  220. prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
  221. }
  222. xFreeBytesRemaining -= pxBlock->xBlockSize;
  223. /* The block is being returned - it is allocated and owned
  224. * by the application and has no "next" block. */
  225. heapALLOCATE_BLOCK( pxBlock );
  226. pxBlock->pxNextFreeBlock = NULL;
  227. }
  228. }
  229. }
  230. traceMALLOC( pvReturn, xWantedSize );
  231. }
  232. ( void ) xTaskResumeAll();
  233. #if ( configUSE_MALLOC_FAILED_HOOK == 1 )
  234. {
  235. if( pvReturn == NULL )
  236. {
  237. vApplicationMallocFailedHook();
  238. }
  239. }
  240. #endif
  241. return pvReturn;
  242. }
  243. /*-----------------------------------------------------------*/
  244. void vPortFree( void * pv )
  245. {
  246. uint8_t * puc = ( uint8_t * ) pv;
  247. BlockLink_t * pxLink;
  248. if( pv != NULL )
  249. {
  250. /* The memory being freed will have an BlockLink_t structure immediately
  251. * before it. */
  252. puc -= xHeapStructSize;
  253. /* This unexpected casting is to keep some compilers from issuing
  254. * byte alignment warnings. */
  255. pxLink = ( void * ) puc;
  256. configASSERT( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 );
  257. configASSERT( pxLink->pxNextFreeBlock == NULL );
  258. if( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 )
  259. {
  260. if( pxLink->pxNextFreeBlock == NULL )
  261. {
  262. /* The block is being returned to the heap - it is no longer
  263. * allocated. */
  264. heapFREE_BLOCK( pxLink );
  265. #if ( configHEAP_CLEAR_MEMORY_ON_FREE == 1 )
  266. {
  267. ( void ) memset( puc + xHeapStructSize, 0, pxLink->xBlockSize - xHeapStructSize );
  268. }
  269. #endif
  270. vTaskSuspendAll();
  271. {
  272. /* Add this block to the list of free blocks. */
  273. prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
  274. xFreeBytesRemaining += pxLink->xBlockSize;
  275. traceFREE( pv, pxLink->xBlockSize );
  276. }
  277. ( void ) xTaskResumeAll();
  278. }
  279. }
  280. }
  281. }
  282. /*-----------------------------------------------------------*/
  283. size_t xPortGetFreeHeapSize( void )
  284. {
  285. return xFreeBytesRemaining;
  286. }
  287. /*-----------------------------------------------------------*/
  288. void vPortInitialiseBlocks( void )
  289. {
  290. /* This just exists to keep the linker quiet. */
  291. }
  292. /*-----------------------------------------------------------*/
  293. void * pvPortCalloc( size_t xNum,
  294. size_t xSize )
  295. {
  296. void * pv = NULL;
  297. if( heapMULTIPLY_WILL_OVERFLOW( xNum, xSize ) == 0 )
  298. {
  299. pv = pvPortMalloc( xNum * xSize );
  300. if( pv != NULL )
  301. {
  302. ( void ) memset( pv, 0, xNum * xSize );
  303. }
  304. }
  305. return pv;
  306. }
  307. /*-----------------------------------------------------------*/
  308. static void prvHeapInit( void ) /* PRIVILEGED_FUNCTION */
  309. {
  310. BlockLink_t * pxFirstFreeBlock;
  311. uint8_t * pucAlignedHeap;
  312. /* Ensure the heap starts on a correctly aligned boundary. */
  313. pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) & ucHeap[ portBYTE_ALIGNMENT - 1 ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );
  314. /* xStart is used to hold a pointer to the first item in the list of free
  315. * blocks. The void cast is used to prevent compiler warnings. */
  316. xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;
  317. xStart.xBlockSize = ( size_t ) 0;
  318. /* xEnd is used to mark the end of the list of free blocks. */
  319. xEnd.xBlockSize = configADJUSTED_HEAP_SIZE;
  320. xEnd.pxNextFreeBlock = NULL;
  321. /* To start with there is a single free block that is sized to take up the
  322. * entire heap space. */
  323. pxFirstFreeBlock = ( BlockLink_t * ) pucAlignedHeap;
  324. pxFirstFreeBlock->xBlockSize = configADJUSTED_HEAP_SIZE;
  325. pxFirstFreeBlock->pxNextFreeBlock = &xEnd;
  326. }
  327. /*-----------------------------------------------------------*/
  328. /*
  329. * Reset the state in this file. This state is normally initialized at start up.
  330. * This function must be called by the application before restarting the
  331. * scheduler.
  332. */
  333. void vPortHeapResetState( void )
  334. {
  335. xFreeBytesRemaining = configADJUSTED_HEAP_SIZE;
  336. xHeapHasBeenInitialised = pdFALSE;
  337. }
  338. /*-----------------------------------------------------------*/