xref: /Kernel-v10.6.2/portable/GCC/ARM_CM33/secure/secure_heap.c (revision ef7b253b56c9788077f5ecd6c9deb4021923d646)
1 /*
2  * FreeRTOS Kernel V10.6.2
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 /* Standard includes. */
30 #include <stdint.h>
31 
32 /* Secure context heap includes. */
33 #include "secure_heap.h"
34 
35 /* Secure port macros. */
36 #include "secure_port_macros.h"
37 
38 /**
39  * @brief Total heap size.
40  */
41 #ifndef secureconfigTOTAL_HEAP_SIZE
42     #define secureconfigTOTAL_HEAP_SIZE    ( ( ( size_t ) ( 10 * 1024 ) ) )
43 #endif
44 
45 /* No test marker by default. */
46 #ifndef mtCOVERAGE_TEST_MARKER
47     #define mtCOVERAGE_TEST_MARKER()
48 #endif
49 
50 /* No tracing by default. */
51 #ifndef traceMALLOC
52     #define traceMALLOC( pvReturn, xWantedSize )
53 #endif
54 
55 /* No tracing by default. */
56 #ifndef traceFREE
57     #define traceFREE( pv, xBlockSize )
58 #endif
59 
60 /* Block sizes must not get too small. */
61 #define secureheapMINIMUM_BLOCK_SIZE    ( ( size_t ) ( xHeapStructSize << 1 ) )
62 
63 /* Assumes 8bit bytes! */
64 #define secureheapBITS_PER_BYTE         ( ( size_t ) 8 )
65 /*-----------------------------------------------------------*/
66 
67 /* Allocate the memory for the heap. */
68 #if ( configAPPLICATION_ALLOCATED_HEAP == 1 )
69 
70 /* The application writer has already defined the array used for the RTOS
71 * heap - probably so it can be placed in a special segment or address. */
72     extern uint8_t ucHeap[ secureconfigTOTAL_HEAP_SIZE ];
73 #else /* configAPPLICATION_ALLOCATED_HEAP */
74     static uint8_t ucHeap[ secureconfigTOTAL_HEAP_SIZE ];
75 #endif /* configAPPLICATION_ALLOCATED_HEAP */
76 
77 /**
78  * @brief The linked list structure.
79  *
80  * This is used to link free blocks in order of their memory address.
81  */
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 /*-----------------------------------------------------------*/
88 
89 /**
90  * @brief Called automatically to setup the required heap structures the first
91  * time pvPortMalloc() is called.
92  */
93 static void prvHeapInit( void );
94 
95 /**
96  * @brief Inserts a block of memory that is being freed into the correct
97  * position in the list of free memory blocks.
98  *
99  * The block being freed will be merged with the block in front it and/or the
100  * block behind it if the memory blocks are adjacent to each other.
101  *
102  * @param[in] pxBlockToInsert The block being freed.
103  */
104 static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert );
105 /*-----------------------------------------------------------*/
106 
107 /**
108  * @brief The size of the structure placed at the beginning of each allocated
109  * memory block must by correctly byte aligned.
110  */
111 static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( secureportBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) secureportBYTE_ALIGNMENT_MASK );
112 
113 /**
114  * @brief Create a couple of list links to mark the start and end of the list.
115  */
116 static BlockLink_t xStart;
117 static BlockLink_t * pxEnd = NULL;
118 
119 /**
120  * @brief Keeps track of the number of free bytes remaining, but says nothing
121  * about fragmentation.
122  */
123 static size_t xFreeBytesRemaining = 0U;
124 static size_t xMinimumEverFreeBytesRemaining = 0U;
125 
126 /**
127  * @brief Gets set to the top bit of an size_t type.
128  *
129  * When this bit in the xBlockSize member of an BlockLink_t structure is set
130  * then the block belongs to the application. When the bit is free the block is
131  * still part of the free heap space.
132  */
133 static size_t xBlockAllocatedBit = 0;
134 /*-----------------------------------------------------------*/
135 
prvHeapInit(void)136 static void prvHeapInit( void )
137 {
138     BlockLink_t * pxFirstFreeBlock;
139     uint8_t * pucAlignedHeap;
140     size_t uxAddress;
141     size_t xTotalHeapSize = secureconfigTOTAL_HEAP_SIZE;
142 
143     /* Ensure the heap starts on a correctly aligned boundary. */
144     uxAddress = ( size_t ) ucHeap;
145 
146     if( ( uxAddress & secureportBYTE_ALIGNMENT_MASK ) != 0 )
147     {
148         uxAddress += ( secureportBYTE_ALIGNMENT - 1 );
149         uxAddress &= ~( ( size_t ) secureportBYTE_ALIGNMENT_MASK );
150         xTotalHeapSize -= uxAddress - ( size_t ) ucHeap;
151     }
152 
153     pucAlignedHeap = ( uint8_t * ) uxAddress;
154 
155     /* xStart is used to hold a pointer to the first item in the list of free
156      * blocks.  The void cast is used to prevent compiler warnings. */
157     xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;
158     xStart.xBlockSize = ( size_t ) 0;
159 
160     /* pxEnd is used to mark the end of the list of free blocks and is inserted
161      * at the end of the heap space. */
162     uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize;
163     uxAddress -= xHeapStructSize;
164     uxAddress &= ~( ( size_t ) secureportBYTE_ALIGNMENT_MASK );
165     pxEnd = ( void * ) uxAddress;
166     pxEnd->xBlockSize = 0;
167     pxEnd->pxNextFreeBlock = NULL;
168 
169     /* To start with there is a single free block that is sized to take up the
170      * entire heap space, minus the space taken by pxEnd. */
171     pxFirstFreeBlock = ( void * ) pucAlignedHeap;
172     pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock;
173     pxFirstFreeBlock->pxNextFreeBlock = pxEnd;
174 
175     /* Only one block exists - and it covers the entire usable heap space. */
176     xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
177     xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
178 
179     /* Work out the position of the top bit in a size_t variable. */
180     xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * secureheapBITS_PER_BYTE ) - 1 );
181 }
182 /*-----------------------------------------------------------*/
183 
prvInsertBlockIntoFreeList(BlockLink_t * pxBlockToInsert)184 static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert )
185 {
186     BlockLink_t * pxIterator;
187     uint8_t * puc;
188 
189     /* Iterate through the list until a block is found that has a higher address
190      * than the block being inserted. */
191     for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
192     {
193         /* Nothing to do here, just iterate to the right position. */
194     }
195 
196     /* Do the block being inserted, and the block it is being inserted after
197      * make a contiguous block of memory? */
198     puc = ( uint8_t * ) pxIterator;
199 
200     if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
201     {
202         pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
203         pxBlockToInsert = pxIterator;
204     }
205     else
206     {
207         mtCOVERAGE_TEST_MARKER();
208     }
209 
210     /* Do the block being inserted, and the block it is being inserted before
211      * make a contiguous block of memory? */
212     puc = ( uint8_t * ) pxBlockToInsert;
213 
214     if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
215     {
216         if( pxIterator->pxNextFreeBlock != pxEnd )
217         {
218             /* Form one big block from the two blocks. */
219             pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
220             pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
221         }
222         else
223         {
224             pxBlockToInsert->pxNextFreeBlock = pxEnd;
225         }
226     }
227     else
228     {
229         pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
230     }
231 
232     /* If the block being inserted plugged a gab, so was merged with the block
233      * before and the block after, then it's pxNextFreeBlock pointer will have
234      * already been set, and should not be set here as that would make it point
235      * to itself. */
236     if( pxIterator != pxBlockToInsert )
237     {
238         pxIterator->pxNextFreeBlock = pxBlockToInsert;
239     }
240     else
241     {
242         mtCOVERAGE_TEST_MARKER();
243     }
244 }
245 /*-----------------------------------------------------------*/
246 
pvPortMalloc(size_t xWantedSize)247 void * pvPortMalloc( size_t xWantedSize )
248 {
249     BlockLink_t * pxBlock;
250     BlockLink_t * pxPreviousBlock;
251     BlockLink_t * pxNewBlockLink;
252     void * pvReturn = NULL;
253 
254     /* If this is the first call to malloc then the heap will require
255      * initialisation to setup the list of free blocks. */
256     if( pxEnd == NULL )
257     {
258         prvHeapInit();
259     }
260     else
261     {
262         mtCOVERAGE_TEST_MARKER();
263     }
264 
265     /* Check the requested block size is not so large that the top bit is set.
266      * The top bit of the block size member of the BlockLink_t structure is used
267      * to determine who owns the block - the application or the kernel, so it
268      * must be free. */
269     if( ( xWantedSize & xBlockAllocatedBit ) == 0 )
270     {
271         /* The wanted size is increased so it can contain a BlockLink_t
272          * structure in addition to the requested amount of bytes. */
273         if( xWantedSize > 0 )
274         {
275             xWantedSize += xHeapStructSize;
276 
277             /* Ensure that blocks are always aligned to the required number of
278              * bytes. */
279             if( ( xWantedSize & secureportBYTE_ALIGNMENT_MASK ) != 0x00 )
280             {
281                 /* Byte alignment required. */
282                 xWantedSize += ( secureportBYTE_ALIGNMENT - ( xWantedSize & secureportBYTE_ALIGNMENT_MASK ) );
283                 secureportASSERT( ( xWantedSize & secureportBYTE_ALIGNMENT_MASK ) == 0 );
284             }
285             else
286             {
287                 mtCOVERAGE_TEST_MARKER();
288             }
289         }
290         else
291         {
292             mtCOVERAGE_TEST_MARKER();
293         }
294 
295         if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
296         {
297             /* Traverse the list from the start (lowest address) block until
298              * one of adequate size is found. */
299             pxPreviousBlock = &xStart;
300             pxBlock = xStart.pxNextFreeBlock;
301 
302             while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
303             {
304                 pxPreviousBlock = pxBlock;
305                 pxBlock = pxBlock->pxNextFreeBlock;
306             }
307 
308             /* If the end marker was reached then a block of adequate size was
309              * not found. */
310             if( pxBlock != pxEnd )
311             {
312                 /* Return the memory space pointed to - jumping over the
313                  * BlockLink_t structure at its start. */
314                 pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
315 
316                 /* This block is being returned for use so must be taken out
317                  * of the list of free blocks. */
318                 pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
319 
320                 /* If the block is larger than required it can be split into
321                  * two. */
322                 if( ( pxBlock->xBlockSize - xWantedSize ) > secureheapMINIMUM_BLOCK_SIZE )
323                 {
324                     /* This block is to be split into two.  Create a new
325                      * block following the number of bytes requested. The void
326                      * cast is used to prevent byte alignment warnings from the
327                      * compiler. */
328                     pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
329                     secureportASSERT( ( ( ( size_t ) pxNewBlockLink ) & secureportBYTE_ALIGNMENT_MASK ) == 0 );
330 
331                     /* Calculate the sizes of two blocks split from the single
332                      * block. */
333                     pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
334                     pxBlock->xBlockSize = xWantedSize;
335 
336                     /* Insert the new block into the list of free blocks. */
337                     prvInsertBlockIntoFreeList( pxNewBlockLink );
338                 }
339                 else
340                 {
341                     mtCOVERAGE_TEST_MARKER();
342                 }
343 
344                 xFreeBytesRemaining -= pxBlock->xBlockSize;
345 
346                 if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
347                 {
348                     xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
349                 }
350                 else
351                 {
352                     mtCOVERAGE_TEST_MARKER();
353                 }
354 
355                 /* The block is being returned - it is allocated and owned by
356                  * the application and has no "next" block. */
357                 pxBlock->xBlockSize |= xBlockAllocatedBit;
358                 pxBlock->pxNextFreeBlock = NULL;
359             }
360             else
361             {
362                 mtCOVERAGE_TEST_MARKER();
363             }
364         }
365         else
366         {
367             mtCOVERAGE_TEST_MARKER();
368         }
369     }
370     else
371     {
372         mtCOVERAGE_TEST_MARKER();
373     }
374 
375     traceMALLOC( pvReturn, xWantedSize );
376 
377     #if ( secureconfigUSE_MALLOC_FAILED_HOOK == 1 )
378         {
379             if( pvReturn == NULL )
380             {
381                 extern void vApplicationMallocFailedHook( void );
382                 vApplicationMallocFailedHook();
383             }
384             else
385             {
386                 mtCOVERAGE_TEST_MARKER();
387             }
388         }
389     #endif /* if ( secureconfigUSE_MALLOC_FAILED_HOOK == 1 ) */
390 
391     secureportASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) secureportBYTE_ALIGNMENT_MASK ) == 0 );
392     return pvReturn;
393 }
394 /*-----------------------------------------------------------*/
395 
vPortFree(void * pv)396 void vPortFree( void * pv )
397 {
398     uint8_t * puc = ( uint8_t * ) pv;
399     BlockLink_t * pxLink;
400 
401     if( pv != NULL )
402     {
403         /* The memory being freed will have an BlockLink_t structure immediately
404          * before it. */
405         puc -= xHeapStructSize;
406 
407         /* This casting is to keep the compiler from issuing warnings. */
408         pxLink = ( void * ) puc;
409 
410         /* Check the block is actually allocated. */
411         secureportASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );
412         secureportASSERT( pxLink->pxNextFreeBlock == NULL );
413 
414         if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )
415         {
416             if( pxLink->pxNextFreeBlock == NULL )
417             {
418                 /* The block is being returned to the heap - it is no longer
419                  * allocated. */
420                 pxLink->xBlockSize &= ~xBlockAllocatedBit;
421 
422                 secureportDISABLE_NON_SECURE_INTERRUPTS();
423                 {
424                     /* Add this block to the list of free blocks. */
425                     xFreeBytesRemaining += pxLink->xBlockSize;
426                     traceFREE( pv, pxLink->xBlockSize );
427                     prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
428                 }
429                 secureportENABLE_NON_SECURE_INTERRUPTS();
430             }
431             else
432             {
433                 mtCOVERAGE_TEST_MARKER();
434             }
435         }
436         else
437         {
438             mtCOVERAGE_TEST_MARKER();
439         }
440     }
441 }
442 /*-----------------------------------------------------------*/
443 
xPortGetFreeHeapSize(void)444 size_t xPortGetFreeHeapSize( void )
445 {
446     return xFreeBytesRemaining;
447 }
448 /*-----------------------------------------------------------*/
449 
xPortGetMinimumEverFreeHeapSize(void)450 size_t xPortGetMinimumEverFreeHeapSize( void )
451 {
452     return xMinimumEverFreeBytesRemaining;
453 }
454 /*-----------------------------------------------------------*/
455