1 /*
2  * FreeRTOS Kernel <DEVELOPMENT BRANCH>
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 /* Indicates whether the heap has been initialised or not. */
117 PRIVILEGED_DATA static BaseType_t xHeapHasBeenInitialised = pdFALSE;
118 
119 /*-----------------------------------------------------------*/
120 
121 /*
122  * Initialises the heap structures before their first use.
123  */
124 static void prvHeapInit( void ) PRIVILEGED_FUNCTION;
125 
126 /*-----------------------------------------------------------*/
127 
128 /* STATIC FUNCTIONS ARE DEFINED AS MACROS TO MINIMIZE THE FUNCTION CALL DEPTH. */
129 
130 /*
131  * Insert a block into the list of free blocks - which is ordered by size of
132  * the block.  Small blocks at the start of the list and large blocks at the end
133  * of the list.
134  */
135 #define prvInsertBlockIntoFreeList( pxBlockToInsert )                                                                               \
136     {                                                                                                                               \
137         BlockLink_t * pxIterator;                                                                                                   \
138         size_t xBlockSize;                                                                                                          \
139                                                                                                                                     \
140         xBlockSize = pxBlockToInsert->xBlockSize;                                                                                   \
141                                                                                                                                     \
142         /* Iterate through the list until a block is found that has a larger size */                                                \
143         /* than the block we are inserting. */                                                                                      \
144         for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \
145         {                                                                                                                           \
146             /* There is nothing to do here - just iterate to the correct position. */                                               \
147         }                                                                                                                           \
148                                                                                                                                     \
149         /* Update the list to include the block being inserted in the correct */                                                    \
150         /* position. */                                                                                                             \
151         pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;                                                             \
152         pxIterator->pxNextFreeBlock = pxBlockToInsert;                                                                              \
153     }
154 /*-----------------------------------------------------------*/
155 
pvPortMalloc(size_t xWantedSize)156 void * pvPortMalloc( size_t xWantedSize )
157 {
158     BlockLink_t * pxBlock;
159     BlockLink_t * pxPreviousBlock;
160     BlockLink_t * pxNewBlockLink;
161     void * pvReturn = NULL;
162     size_t xAdditionalRequiredSize;
163     size_t xAllocatedBlockSize = 0;
164 
165     if( xWantedSize > 0 )
166     {
167         /* The wanted size must be increased so it can contain a BlockLink_t
168          * structure in addition to the requested amount of bytes. */
169         if( heapADD_WILL_OVERFLOW( xWantedSize, xHeapStructSize ) == 0 )
170         {
171             xWantedSize += xHeapStructSize;
172 
173             /* Ensure that blocks are always aligned to the required number
174              * of bytes. */
175             if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
176             {
177                 /* Byte alignment required. */
178                 xAdditionalRequiredSize = portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK );
179 
180                 if( heapADD_WILL_OVERFLOW( xWantedSize, xAdditionalRequiredSize ) == 0 )
181                 {
182                     xWantedSize += xAdditionalRequiredSize;
183                 }
184                 else
185                 {
186                     xWantedSize = 0;
187                 }
188             }
189             else
190             {
191                 mtCOVERAGE_TEST_MARKER();
192             }
193         }
194         else
195         {
196             xWantedSize = 0;
197         }
198     }
199     else
200     {
201         mtCOVERAGE_TEST_MARKER();
202     }
203 
204     vTaskSuspendAll();
205     {
206         /* If this is the first call to malloc then the heap will require
207          * initialisation to setup the list of free blocks. */
208         if( xHeapHasBeenInitialised == pdFALSE )
209         {
210             prvHeapInit();
211             xHeapHasBeenInitialised = pdTRUE;
212         }
213 
214         /* Check the block size we are trying to allocate is not so large that the
215          * top bit is set.  The top bit of the block size member of the BlockLink_t
216          * structure is used to determine who owns the block - the application or
217          * the kernel, so it must be free. */
218         if( heapBLOCK_SIZE_IS_VALID( xWantedSize ) != 0 )
219         {
220             if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
221             {
222                 /* Blocks are stored in byte order - traverse the list from the start
223                  * (smallest) block until one of adequate size is found. */
224                 pxPreviousBlock = &xStart;
225                 pxBlock = xStart.pxNextFreeBlock;
226 
227                 while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
228                 {
229                     pxPreviousBlock = pxBlock;
230                     pxBlock = pxBlock->pxNextFreeBlock;
231                 }
232 
233                 /* If we found the end marker then a block of adequate size was not found. */
234                 if( pxBlock != &xEnd )
235                 {
236                     /* Return the memory space - jumping over the BlockLink_t structure
237                      * at its start. */
238                     pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
239 
240                     /* This block is being returned for use so must be taken out of the
241                      * list of free blocks. */
242                     pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
243 
244                     /* If the block is larger than required it can be split into two. */
245                     if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
246                     {
247                         /* This block is to be split into two.  Create a new block
248                          * following the number of bytes requested. The void cast is
249                          * used to prevent byte alignment warnings from the compiler. */
250                         pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
251 
252                         /* Calculate the sizes of two blocks split from the single
253                          * block. */
254                         pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
255                         pxBlock->xBlockSize = xWantedSize;
256 
257                         /* Insert the new block into the list of free blocks.
258                          * The list of free blocks is sorted by their size, we have to
259                          * iterate to find the right place to insert new block. */
260                         prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
261                     }
262 
263                     xFreeBytesRemaining -= pxBlock->xBlockSize;
264 
265                     xAllocatedBlockSize = pxBlock->xBlockSize;
266 
267                     /* The block is being returned - it is allocated and owned
268                      * by the application and has no "next" block. */
269                     heapALLOCATE_BLOCK( pxBlock );
270                     pxBlock->pxNextFreeBlock = NULL;
271                 }
272             }
273         }
274 
275         traceMALLOC( pvReturn, xAllocatedBlockSize );
276 
277         /* Prevent compiler warnings when trace macros are not used. */
278         ( void ) xAllocatedBlockSize;
279     }
280     ( void ) xTaskResumeAll();
281 
282     #if ( configUSE_MALLOC_FAILED_HOOK == 1 )
283     {
284         if( pvReturn == NULL )
285         {
286             vApplicationMallocFailedHook();
287         }
288     }
289     #endif
290 
291     return pvReturn;
292 }
293 /*-----------------------------------------------------------*/
294 
vPortFree(void * pv)295 void vPortFree( void * pv )
296 {
297     uint8_t * puc = ( uint8_t * ) pv;
298     BlockLink_t * pxLink;
299 
300     if( pv != NULL )
301     {
302         /* The memory being freed will have an BlockLink_t structure immediately
303          * before it. */
304         puc -= xHeapStructSize;
305 
306         /* This unexpected casting is to keep some compilers from issuing
307          * byte alignment warnings. */
308         pxLink = ( void * ) puc;
309 
310         configASSERT( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 );
311         configASSERT( pxLink->pxNextFreeBlock == NULL );
312 
313         if( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 )
314         {
315             if( pxLink->pxNextFreeBlock == NULL )
316             {
317                 /* The block is being returned to the heap - it is no longer
318                  * allocated. */
319                 heapFREE_BLOCK( pxLink );
320                 #if ( configHEAP_CLEAR_MEMORY_ON_FREE == 1 )
321                 {
322                     ( void ) memset( puc + xHeapStructSize, 0, pxLink->xBlockSize - xHeapStructSize );
323                 }
324                 #endif
325 
326                 vTaskSuspendAll();
327                 {
328                     /* Add this block to the list of free blocks. */
329                     prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
330                     xFreeBytesRemaining += pxLink->xBlockSize;
331                     traceFREE( pv, pxLink->xBlockSize );
332                 }
333                 ( void ) xTaskResumeAll();
334             }
335         }
336     }
337 }
338 /*-----------------------------------------------------------*/
339 
xPortGetFreeHeapSize(void)340 size_t xPortGetFreeHeapSize( void )
341 {
342     return xFreeBytesRemaining;
343 }
344 /*-----------------------------------------------------------*/
345 
vPortInitialiseBlocks(void)346 void vPortInitialiseBlocks( void )
347 {
348     /* This just exists to keep the linker quiet. */
349 }
350 /*-----------------------------------------------------------*/
351 
pvPortCalloc(size_t xNum,size_t xSize)352 void * pvPortCalloc( size_t xNum,
353                      size_t xSize )
354 {
355     void * pv = NULL;
356 
357     if( heapMULTIPLY_WILL_OVERFLOW( xNum, xSize ) == 0 )
358     {
359         pv = pvPortMalloc( xNum * xSize );
360 
361         if( pv != NULL )
362         {
363             ( void ) memset( pv, 0, xNum * xSize );
364         }
365     }
366 
367     return pv;
368 }
369 /*-----------------------------------------------------------*/
370 
prvHeapInit(void)371 static void prvHeapInit( void ) /* PRIVILEGED_FUNCTION */
372 {
373     BlockLink_t * pxFirstFreeBlock;
374     uint8_t * pucAlignedHeap;
375 
376     /* Ensure the heap starts on a correctly aligned boundary. */
377     pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) & ucHeap[ portBYTE_ALIGNMENT - 1 ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );
378 
379     /* xStart is used to hold a pointer to the first item in the list of free
380      * blocks.  The void cast is used to prevent compiler warnings. */
381     xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;
382     xStart.xBlockSize = ( size_t ) 0;
383 
384     /* xEnd is used to mark the end of the list of free blocks. */
385     xEnd.xBlockSize = configADJUSTED_HEAP_SIZE;
386     xEnd.pxNextFreeBlock = NULL;
387 
388     /* To start with there is a single free block that is sized to take up the
389      * entire heap space. */
390     pxFirstFreeBlock = ( BlockLink_t * ) pucAlignedHeap;
391     pxFirstFreeBlock->xBlockSize = configADJUSTED_HEAP_SIZE;
392     pxFirstFreeBlock->pxNextFreeBlock = &xEnd;
393 }
394 /*-----------------------------------------------------------*/
395 
396 /*
397  * Reset the state in this file. This state is normally initialized at start up.
398  * This function must be called by the application before restarting the
399  * scheduler.
400  */
vPortHeapResetState(void)401 void vPortHeapResetState( void )
402 {
403     xFreeBytesRemaining = configADJUSTED_HEAP_SIZE;
404 
405     xHeapHasBeenInitialised = pdFALSE;
406 }
407 /*-----------------------------------------------------------*/
408