Line data Source code
1 : /* 2 : multiple heap interface, allowing for an allocator that uses 3 : multiple underlying heaps to cope with multiple memory regions on 4 : STM32 boards 5 : */ 6 : 7 : #pragma once 8 : 9 : #include <AP_HAL/AP_HAL.h> 10 : #include <AP_HAL/Util.h> 11 : 12 : #include <stdint.h> 13 : #include <stdbool.h> 14 : 15 : class MultiHeap { 16 : public: 17 : /* 18 : allocate/deallocate heaps 19 : */ 20 : bool create(uint32_t total_size, uint8_t max_heaps, bool allow_expansion, uint32_t reserve_size); 21 : void destroy(void); 22 : 23 : // return true if the heap is available for operations 24 : bool available(void) const; 25 : 26 : // allocate memory within heaps 27 : void *allocate(uint32_t size); 28 : void deallocate(void *ptr); 29 : 30 : // change allocated size of a pointer - this operates in a similar 31 : // fashion to realloc, but requires an (accurate!) old_size value 32 : // when ptr is not NULL. This is guaranteed by the lua scripting 33 : // allocation API 34 : void *change_size(void *ptr, uint32_t old_size, uint32_t new_size); 35 : 36 : /* 37 : get the size that we have expanded to. Used by error reporting in scripting 38 : */ 39 91202 : uint32_t get_expansion_size(void) const { 40 91202 : return expanded_to; 41 : } 42 : 43 : private: 44 : struct Heap { 45 : void *hp; 46 : }; 47 : struct Heap *heaps; 48 : 49 : uint8_t num_heaps; 50 : bool allow_expansion; 51 : uint32_t reserve_size; 52 : uint32_t sum_size; 53 : uint32_t expanded_to; 54 : 55 : // we only do heap expansion if the last allocation failed this 56 : // encourages the lua scripting engine to garbage collect to 57 : // re-use memory when possible 58 : bool last_failed; 59 : 60 : 61 : /* 62 : low level allocation functions 63 : */ 64 : /* 65 : heap functions used by lua scripting 66 : */ 67 : // allocate a new heap 68 : void *heap_create(uint32_t size); 69 : 70 : // destroy a heap 71 : void heap_destroy(void *ptr); 72 : 73 : // allocate some memory on a specific heap 74 : void *heap_allocate(void *heap, uint32_t size); 75 : 76 : // free some memory that was allocated by heap_allocate. The implementation must 77 : // be able to determine which heap the allocation was from using the pointer 78 : void heap_free(void *ptr); 79 : };