]> git.sur5r.net Git - freertos/blob - FreeRTOS/Source/portable/MemMang/heap_4.c
Enhance heap_4.c to prevent blocks accidentally being freed twice, or blocks that...
[freertos] / FreeRTOS / Source / portable / MemMang / heap_4.c
1 /*\r
2     FreeRTOS V7.4.2 - Copyright (C) 2013 Real Time Engineers Ltd.\r
3 \r
4     FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME.  PLEASE VISIT\r
5     http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.\r
6 \r
7     ***************************************************************************\r
8      *                                                                       *\r
9      *    FreeRTOS tutorial books are available in pdf and paperback.        *\r
10      *    Complete, revised, and edited pdf reference manuals are also       *\r
11      *    available.                                                         *\r
12      *                                                                       *\r
13      *    Purchasing FreeRTOS documentation will not only help you, by       *\r
14      *    ensuring you get running as quickly as possible and with an        *\r
15      *    in-depth knowledge of how to use FreeRTOS, it will also help       *\r
16      *    the FreeRTOS project to continue with its mission of providing     *\r
17      *    professional grade, cross platform, de facto standard solutions    *\r
18      *    for microcontrollers - completely free of charge!                  *\r
19      *                                                                       *\r
20      *    >>> See http://www.FreeRTOS.org/Documentation for details. <<<     *\r
21      *                                                                       *\r
22      *    Thank you for using FreeRTOS, and thank you for your support!      *\r
23      *                                                                       *\r
24     ***************************************************************************\r
25 \r
26 \r
27     This file is part of the FreeRTOS distribution.\r
28 \r
29     FreeRTOS is free software; you can redistribute it and/or modify it under\r
30     the terms of the GNU General Public License (version 2) as published by the\r
31     Free Software Foundation AND MODIFIED BY the FreeRTOS exception.\r
32 \r
33     >>>>>>NOTE<<<<<< The modification to the GPL is included to allow you to\r
34     distribute a combined work that includes FreeRTOS without being obliged to\r
35     provide the source code for proprietary components outside of the FreeRTOS\r
36     kernel.\r
37 \r
38     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
39     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
40     FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more\r
41     details. You should have received a copy of the GNU General Public License\r
42     and the FreeRTOS license exception along with FreeRTOS; if not it can be\r
43     viewed here: http://www.freertos.org/a00114.html and also obtained by\r
44     writing to Real Time Engineers Ltd., contact details for whom are available\r
45     on the FreeRTOS WEB site.\r
46 \r
47     1 tab == 4 spaces!\r
48 \r
49     ***************************************************************************\r
50      *                                                                       *\r
51      *    Having a problem?  Start by reading the FAQ "My application does   *\r
52      *    not run, what could be wrong?"                                     *\r
53      *                                                                       *\r
54      *    http://www.FreeRTOS.org/FAQHelp.html                               *\r
55      *                                                                       *\r
56     ***************************************************************************\r
57 \r
58 \r
59     http://www.FreeRTOS.org - Documentation, books, training, latest versions, \r
60     license and Real Time Engineers Ltd. contact details.\r
61 \r
62     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
63     including FreeRTOS+Trace - an indispensable productivity tool, and our new\r
64     fully thread aware and reentrant UDP/IP stack.\r
65 \r
66     http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High \r
67     Integrity Systems, who sell the code with commercial support, \r
68     indemnification and middleware, under the OpenRTOS brand.\r
69     \r
70     http://www.SafeRTOS.com - High Integrity Systems also provide a safety \r
71     engineered and independently SIL3 certified version for use in safety and \r
72     mission critical applications that require provable dependability.\r
73 */\r
74 \r
75 /*\r
76  * A sample implementation of pvPortMalloc() and vPortFree() that combines \r
77  * (coalescences) adjacent memory blocks as they are freed, and in so doing \r
78  * limits memory fragmentation.\r
79  *\r
80  * See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the \r
81  * memory management pages of http://www.FreeRTOS.org for more information.\r
82  */\r
83 #include <stdlib.h>\r
84 \r
85 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining\r
86 all the API functions to use the MPU wrappers.  That should only be done when\r
87 task.h is included from an application file. */\r
88 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE\r
89 \r
90 #include "FreeRTOS.h"\r
91 #include "task.h"\r
92 \r
93 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE\r
94 \r
95 /* Block sizes must not get too small. */\r
96 #define heapMINIMUM_BLOCK_SIZE  ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) )\r
97 \r
98 /* Assumes 8bit bytes! */\r
99 #define heapBITS_PER_BYTE               ( ( size_t ) 8 )\r
100 \r
101 /* A few bytes might be lost to byte aligning the heap start address. */\r
102 #define heapADJUSTED_HEAP_SIZE  ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )\r
103 \r
104 /* Allocate the memory for the heap. */\r
105 static unsigned char ucHeap[ configTOTAL_HEAP_SIZE ];\r
106 \r
107 /* Define the linked list structure.  This is used to link free blocks in order\r
108 of their memory address. */\r
109 typedef struct A_BLOCK_LINK\r
110 {\r
111         struct A_BLOCK_LINK *pxNextFreeBlock;   /*<< The next free block in the list. */\r
112         size_t xBlockSize;                                              /*<< The size of the free block. */\r
113 } xBlockLink;\r
114 \r
115 /*-----------------------------------------------------------*/\r
116 \r
117 /*\r
118  * Inserts a block of memory that is being freed into the correct position in \r
119  * the list of free memory blocks.  The block being freed will be merged with\r
120  * the block in front it and/or the block behind it if the memory blocks are\r
121  * adjacent to each other.\r
122  */\r
123 static void prvInsertBlockIntoFreeList( xBlockLink *pxBlockToInsert );\r
124 \r
125 /*\r
126  * Called automatically to setup the required heap structures the first time\r
127  * pvPortMalloc() is called.\r
128  */\r
129 static void prvHeapInit( void );\r
130 \r
131 /*-----------------------------------------------------------*/\r
132 \r
133 /* The size of the structure placed at the beginning of each allocated memory\r
134 block must by correctly byte aligned. */\r
135 static const unsigned short heapSTRUCT_SIZE     = ( ( sizeof ( xBlockLink ) + ( portBYTE_ALIGNMENT - 1 ) ) & ~portBYTE_ALIGNMENT_MASK );\r
136 \r
137 /* Ensure the pxEnd pointer will end up on the correct byte alignment. */\r
138 static const size_t xTotalHeapSize = ( ( size_t ) heapADJUSTED_HEAP_SIZE ) & ( ( size_t ) ~portBYTE_ALIGNMENT_MASK );\r
139 \r
140 /* Create a couple of list links to mark the start and end of the list. */\r
141 static xBlockLink xStart, *pxEnd = NULL;\r
142 \r
143 /* Keeps track of the number of free bytes remaining, but says nothing about\r
144 fragmentation. */\r
145 static size_t xFreeBytesRemaining = ( ( size_t ) heapADJUSTED_HEAP_SIZE ) & ( ( size_t ) ~portBYTE_ALIGNMENT_MASK );\r
146 \r
147 /* Gets set to the top bit of an size_t type.  When this bit in the xBlockSize \r
148 member of an xBlockLink structure is set then the block belongs to the \r
149 application.  When the bit is free the block is still part of the free heap\r
150 space. */\r
151 static size_t xBlockAllocatedBit = 0;\r
152 \r
153 /*-----------------------------------------------------------*/\r
154 \r
155 void *pvPortMalloc( size_t xWantedSize )\r
156 {\r
157 xBlockLink *pxBlock, *pxPreviousBlock, *pxNewBlockLink;\r
158 void *pvReturn = NULL;\r
159 \r
160         vTaskSuspendAll();\r
161         {\r
162                 /* If this is the first call to malloc then the heap will require\r
163                 initialisation to setup the list of free blocks. */\r
164                 if( pxEnd == NULL )\r
165                 {\r
166                         prvHeapInit();\r
167                 }\r
168 \r
169                 /* Check the requested block size is not so large that the top bit is\r
170                 set.  The top bit of the block size member of the xBlockLink structure \r
171                 is used to determine who owns the block - the application or the\r
172                 kernel, so it must be free. */\r
173                 if( ( xWantedSize & xBlockAllocatedBit ) == 0 )\r
174                 {\r
175                         /* The wanted size is increased so it can contain a xBlockLink\r
176                         structure in addition to the requested amount of bytes. */\r
177                         if( xWantedSize > 0 )\r
178                         {\r
179                                 xWantedSize += heapSTRUCT_SIZE;\r
180 \r
181                                 /* Ensure that blocks are always aligned to the required number \r
182                                 of bytes. */\r
183                                 if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )\r
184                                 {\r
185                                         /* Byte alignment required. */\r
186                                         xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );\r
187                                 }\r
188                         }\r
189 \r
190                         if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )\r
191                         {\r
192                                 /* Traverse the list from the start     (lowest address) block until \r
193                                 one     of adequate size is found. */\r
194                                 pxPreviousBlock = &xStart;\r
195                                 pxBlock = xStart.pxNextFreeBlock;\r
196                                 while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )\r
197                                 {\r
198                                         pxPreviousBlock = pxBlock;\r
199                                         pxBlock = pxBlock->pxNextFreeBlock;\r
200                                 }\r
201 \r
202                                 /* If the end marker was reached then a block of adequate size \r
203                                 was     not found. */\r
204                                 if( pxBlock != pxEnd )\r
205                                 {\r
206                                         /* Return the memory space pointed to - jumping over the \r
207                                         xBlockLink structure at its start. */\r
208                                         pvReturn = ( void * ) ( ( ( unsigned char * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE );\r
209 \r
210                                         /* This block is being returned for use so must be taken out \r
211                                         of the list of free blocks. */\r
212                                         pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;\r
213 \r
214                                         /* If the block is larger than required it can be split into \r
215                                         two. */\r
216                                         if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )\r
217                                         {\r
218                                                 /* This block is to be split into two.  Create a new \r
219                                                 block following the number of bytes requested. The void \r
220                                                 cast is used to prevent byte alignment warnings from the \r
221                                                 compiler. */\r
222                                                 pxNewBlockLink = ( void * ) ( ( ( unsigned char * ) pxBlock ) + xWantedSize );\r
223 \r
224                                                 /* Calculate the sizes of two blocks split from the \r
225                                                 single block. */\r
226                                                 pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;\r
227                                                 pxBlock->xBlockSize = xWantedSize;\r
228 \r
229                                                 /* Insert the new block into the list of free blocks. */\r
230                                                 prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );\r
231                                         }\r
232 \r
233                                         xFreeBytesRemaining -= pxBlock->xBlockSize;\r
234 \r
235                                         /* The block is being returned - it is allocated and owned\r
236                                         by the application and has no "next" block. */\r
237                                         pxBlock->xBlockSize |= xBlockAllocatedBit;\r
238                                         pxBlock->pxNextFreeBlock = NULL;\r
239                                 }\r
240                         }\r
241                 }\r
242         }\r
243         xTaskResumeAll();\r
244 \r
245         #if( configUSE_MALLOC_FAILED_HOOK == 1 )\r
246         {\r
247                 if( pvReturn == NULL )\r
248                 {\r
249                         extern void vApplicationMallocFailedHook( void );\r
250                         vApplicationMallocFailedHook();\r
251                 }\r
252         }\r
253         #endif\r
254 \r
255         return pvReturn;\r
256 }\r
257 /*-----------------------------------------------------------*/\r
258 \r
259 void vPortFree( void *pv )\r
260 {\r
261 unsigned char *puc = ( unsigned char * ) pv;\r
262 xBlockLink *pxLink;\r
263 \r
264         if( pv != NULL )\r
265         {\r
266                 /* The memory being freed will have an xBlockLink structure immediately\r
267                 before it. */\r
268                 puc -= heapSTRUCT_SIZE;\r
269 \r
270                 /* This casting is to keep the compiler from issuing warnings. */\r
271                 pxLink = ( void * ) puc;\r
272 \r
273                 /* Check the block is actually allocated. */\r
274                 configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );\r
275                 configASSERT( pxLink->pxNextFreeBlock == NULL );\r
276                 \r
277                 if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )\r
278                 {\r
279                         if( pxLink->pxNextFreeBlock == NULL )\r
280                         {\r
281                                 /* The block is being returned to the heap - it is no longer\r
282                                 allocated. */\r
283                                 pxLink->xBlockSize &= ~xBlockAllocatedBit;\r
284 \r
285                                 vTaskSuspendAll();\r
286                                 {\r
287                                         /* Add this block to the list of free blocks. */\r
288                                         xFreeBytesRemaining += pxLink->xBlockSize;\r
289                                         prvInsertBlockIntoFreeList( ( ( xBlockLink * ) pxLink ) );\r
290                                 }\r
291                                 xTaskResumeAll();\r
292                         }\r
293                 }\r
294         }\r
295 }\r
296 /*-----------------------------------------------------------*/\r
297 \r
298 size_t xPortGetFreeHeapSize( void )\r
299 {\r
300         return xFreeBytesRemaining;\r
301 }\r
302 /*-----------------------------------------------------------*/\r
303 \r
304 void vPortInitialiseBlocks( void )\r
305 {\r
306         /* This just exists to keep the linker quiet. */\r
307 }\r
308 /*-----------------------------------------------------------*/\r
309 \r
310 static void prvHeapInit( void )\r
311 {\r
312 xBlockLink *pxFirstFreeBlock;\r
313 unsigned char *pucHeapEnd, *pucAlignedHeap;\r
314 \r
315         /* Ensure the heap starts on a correctly aligned boundary. */\r
316         pucAlignedHeap = ( unsigned char * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ( portPOINTER_SIZE_TYPE ) ~portBYTE_ALIGNMENT_MASK ) );\r
317 \r
318         /* xStart is used to hold a pointer to the first item in the list of free\r
319         blocks.  The void cast is used to prevent compiler warnings. */\r
320         xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;\r
321         xStart.xBlockSize = ( size_t ) 0;\r
322 \r
323         /* pxEnd is used to mark the end of the list of free blocks and is inserted\r
324         at the end of the heap space. */\r
325         pucHeapEnd = pucAlignedHeap + xTotalHeapSize;\r
326         pucHeapEnd -= heapSTRUCT_SIZE;\r
327         pxEnd = ( void * ) pucHeapEnd;\r
328         configASSERT( ( ( ( unsigned long ) pxEnd ) & ( ( unsigned long ) portBYTE_ALIGNMENT_MASK ) ) == 0UL );\r
329         pxEnd->xBlockSize = 0;\r
330         pxEnd->pxNextFreeBlock = NULL;\r
331 \r
332         /* To start with there is a single free block that is sized to take up the\r
333         entire heap space, minus the space taken by pxEnd. */\r
334         pxFirstFreeBlock = ( void * ) pucAlignedHeap;\r
335         pxFirstFreeBlock->xBlockSize = xTotalHeapSize - heapSTRUCT_SIZE;\r
336         pxFirstFreeBlock->pxNextFreeBlock = pxEnd;\r
337 \r
338         /* The heap now contains pxEnd. */\r
339         xFreeBytesRemaining -= heapSTRUCT_SIZE;\r
340 \r
341         /* Work out the position of the top bit in a size_t variable. */\r
342         xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );\r
343 }\r
344 /*-----------------------------------------------------------*/\r
345 \r
346 static void prvInsertBlockIntoFreeList( xBlockLink *pxBlockToInsert )\r
347 {\r
348 xBlockLink *pxIterator;\r
349 unsigned char *puc;\r
350 \r
351         /* Iterate through the list until a block is found that has a higher address\r
352         than the block being inserted. */\r
353         for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )\r
354         {\r
355                 /* Nothing to do here, just iterate to the right position. */\r
356         }\r
357 \r
358         /* Do the block being inserted, and the block it is being inserted after\r
359         make a contiguous block of memory? */   \r
360         puc = ( unsigned char * ) pxIterator;\r
361         if( ( puc + pxIterator->xBlockSize ) == ( unsigned char * ) pxBlockToInsert )\r
362         {\r
363                 pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;\r
364                 pxBlockToInsert = pxIterator;\r
365         }\r
366 \r
367         /* Do the block being inserted, and the block it is being inserted before\r
368         make a contiguous block of memory? */\r
369         puc = ( unsigned char * ) pxBlockToInsert;\r
370         if( ( puc + pxBlockToInsert->xBlockSize ) == ( unsigned char * ) pxIterator->pxNextFreeBlock )\r
371         {\r
372                 if( pxIterator->pxNextFreeBlock != pxEnd )\r
373                 {\r
374                         /* Form one big block from the two blocks. */\r
375                         pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;\r
376                         pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;\r
377                 }\r
378                 else\r
379                 {\r
380                         pxBlockToInsert->pxNextFreeBlock = pxEnd;\r
381                 }\r
382         }\r
383         else\r
384         {\r
385                 pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;         \r
386         }\r
387 \r
388         /* If the block being inserted plugged a gab, so was merged with the block\r
389         before and the block after, then it's pxNextFreeBlock pointer will have\r
390         already been set, and should not be set here as that would make it point\r
391         to itself. */\r
392         if( pxIterator != pxBlockToInsert )\r
393         {\r
394                 pxIterator->pxNextFreeBlock = pxBlockToInsert;\r
395         }\r
396 }\r
397 \r