brians | 0ab60bb | 2013-01-31 02:21:51 +0000 | [diff] [blame^] | 1 | /* |
| 2 | * This is a glue between newlib and FreeRTOS heap2 allocator ! |
| 3 | * You need to understand how heap2 works and its limitations, |
| 4 | * otherwise you will run out of memory. |
| 5 | * |
| 6 | * Michal Demin - 2010 |
| 7 | * |
| 8 | * TODO: reent is there for a reason ! |
| 9 | * |
| 10 | */ |
| 11 | |
| 12 | #include <stdlib.h> |
| 13 | #include <string.h> |
| 14 | #include "FreeRTOS.h" |
| 15 | #include "task.h" |
| 16 | |
| 17 | /* definition of block structure, copied from heap2 allocator */ |
| 18 | typedef struct A_BLOCK_LINK |
| 19 | { |
| 20 | struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ |
| 21 | size_t xBlockSize; /*<< The size of the free block. */ |
| 22 | } xBlockLink; |
| 23 | |
| 24 | static const unsigned short heapSTRUCT_SIZE = ( sizeof( xBlockLink ) + portBYTE_ALIGNMENT - ( sizeof( xBlockLink ) % portBYTE_ALIGNMENT ) ); |
| 25 | |
| 26 | _PTR _realloc_r(struct _reent *re, _PTR oldAddr, size_t newSize) { |
| 27 | xBlockLink *block; |
| 28 | size_t toCopy; |
| 29 | void *newAddr; |
| 30 | |
| 31 | newAddr = pvPortMalloc(newSize); |
| 32 | |
| 33 | if (newAddr == NULL) |
| 34 | return NULL; |
| 35 | |
| 36 | /* We need the block struct pointer to get the current size */ |
| 37 | block = oldAddr; |
| 38 | block -= heapSTRUCT_SIZE; |
| 39 | |
| 40 | /* determine the size to be copied */ |
| 41 | toCopy = (newSize<block->xBlockSize)?(newSize):(block->xBlockSize); |
| 42 | |
| 43 | /* copy old block into new one */ |
| 44 | memcpy((void *)newAddr, (void *)oldAddr, (size_t)toCopy); |
| 45 | |
| 46 | vPortFree(oldAddr); |
| 47 | |
| 48 | return newAddr; |
| 49 | } |
| 50 | |
| 51 | _PTR _calloc_r(struct _reent *re, size_t num, size_t size) { |
| 52 | return pvPortMalloc(num*size); |
| 53 | } |
| 54 | |
| 55 | _PTR _malloc_r(struct _reent *re, size_t size) { |
| 56 | return pvPortMalloc(size); |
| 57 | } |
| 58 | |
| 59 | _VOID _free_r(struct _reent *re, _PTR ptr) { |
| 60 | vPortFree(ptr); |
| 61 | } |
| 62 | |