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