[73abe95] | 1 | // |
---|
[c4f68dc] | 2 | // Cforall Version 1.0.0 Copyright (C) 2017 University of Waterloo |
---|
| 3 | // |
---|
| 4 | // The contents of this file are covered under the licence agreement in the |
---|
| 5 | // file "LICENCE" distributed with Cforall. |
---|
[73abe95] | 6 | // |
---|
[92aca37] | 7 | // heap.cfa -- |
---|
[73abe95] | 8 | // |
---|
[c4f68dc] | 9 | // Author : Peter A. Buhr |
---|
| 10 | // Created On : Tue Dec 19 21:58:35 2017 |
---|
| 11 | // Last Modified By : Peter A. Buhr |
---|
[80fbdc9] | 12 | // Last Modified On : Thu Oct 13 22:21:52 2022 |
---|
| 13 | // Update Count : 1557 |
---|
[73abe95] | 14 | // |
---|
[c4f68dc] | 15 | |
---|
[116a2ea] | 16 | #include <stdio.h> |
---|
[1e034d9] | 17 | #include <string.h> // memset, memcpy |
---|
[1076d05] | 18 | #include <limits.h> // ULONG_MAX |
---|
[31a5f418] | 19 | #include <stdlib.h> // EXIT_FAILURE |
---|
| 20 | #include <errno.h> // errno, ENOMEM, EINVAL |
---|
| 21 | #include <unistd.h> // STDERR_FILENO, sbrk, sysconf |
---|
[ada0246d] | 22 | #include <malloc.h> // memalign, malloc_usable_size |
---|
[c4f68dc] | 23 | #include <sys/mman.h> // mmap, munmap |
---|
[116a2ea] | 24 | extern "C" { |
---|
[31a5f418] | 25 | #include <sys/sysinfo.h> // get_nprocs |
---|
[116a2ea] | 26 | } // extern "C" |
---|
[c4f68dc] | 27 | |
---|
[92aca37] | 28 | #include "bits/align.hfa" // libAlign |
---|
[bcb14b5] | 29 | #include "bits/defs.hfa" // likely, unlikely |
---|
[116a2ea] | 30 | #include "concurrency/kernel/fwd.hfa" // __POLL_PREEMPTION |
---|
[73abe95] | 31 | #include "startup.hfa" // STARTUP_PRIORITY_MEMORY |
---|
[116a2ea] | 32 | #include "math.hfa" // ceiling, min |
---|
[7cfef0d] | 33 | #include "bitmanip.hfa" // is_pow2, ceiling2 |
---|
[c4f68dc] | 34 | |
---|
[116a2ea] | 35 | // supported mallopt options |
---|
| 36 | #ifndef M_MMAP_THRESHOLD |
---|
| 37 | #define M_MMAP_THRESHOLD (-1) |
---|
| 38 | #endif // M_MMAP_THRESHOLD |
---|
| 39 | |
---|
| 40 | #ifndef M_TOP_PAD |
---|
| 41 | #define M_TOP_PAD (-2) |
---|
| 42 | #endif // M_TOP_PAD |
---|
| 43 | |
---|
| 44 | #define FASTLOOKUP // use O(1) table lookup from allocation size to bucket size |
---|
| 45 | #define RETURNSPIN // toggle spinlock / lockfree stack |
---|
| 46 | #define OWNERSHIP // return freed memory to owner thread |
---|
| 47 | |
---|
| 48 | #define CACHE_ALIGN 64 |
---|
| 49 | #define CALIGN __attribute__(( aligned(CACHE_ALIGN) )) |
---|
| 50 | |
---|
| 51 | #define TLSMODEL __attribute__(( tls_model("initial-exec") )) |
---|
| 52 | |
---|
| 53 | //#define __STATISTICS__ |
---|
| 54 | |
---|
| 55 | enum { |
---|
| 56 | // The default extension heap amount in units of bytes. When the current heap reaches the brk address, the brk |
---|
| 57 | // address is extended by the extension amount. |
---|
| 58 | __CFA_DEFAULT_HEAP_EXPANSION__ = 10 * 1024 * 1024, |
---|
| 59 | |
---|
| 60 | // The mmap crossover point during allocation. Allocations less than this amount are allocated from buckets; values |
---|
| 61 | // greater than or equal to this value are mmap from the operating system. |
---|
| 62 | __CFA_DEFAULT_MMAP_START__ = 512 * 1024 + 1, |
---|
| 63 | |
---|
| 64 | // The default unfreed storage amount in units of bytes. When the uC++ program ends it subtracts this amount from |
---|
| 65 | // the malloc/free counter to adjust for storage the program does not free. |
---|
| 66 | __CFA_DEFAULT_HEAP_UNFREED__ = 0 |
---|
| 67 | }; // enum |
---|
| 68 | |
---|
| 69 | |
---|
| 70 | //####################### Heap Trace/Print #################### |
---|
[31a5f418] | 71 | |
---|
| 72 | |
---|
[93c2e0a] | 73 | static bool traceHeap = false; |
---|
[d46ed6e] | 74 | |
---|
[032234bd] | 75 | inline bool traceHeap() libcfa_public { return traceHeap; } |
---|
[d46ed6e] | 76 | |
---|
[032234bd] | 77 | bool traceHeapOn() libcfa_public { |
---|
[93c2e0a] | 78 | bool temp = traceHeap; |
---|
[d46ed6e] | 79 | traceHeap = true; |
---|
| 80 | return temp; |
---|
| 81 | } // traceHeapOn |
---|
| 82 | |
---|
[032234bd] | 83 | bool traceHeapOff() libcfa_public { |
---|
[93c2e0a] | 84 | bool temp = traceHeap; |
---|
[d46ed6e] | 85 | traceHeap = false; |
---|
| 86 | return temp; |
---|
| 87 | } // traceHeapOff |
---|
| 88 | |
---|
[032234bd] | 89 | bool traceHeapTerm() libcfa_public { return false; } |
---|
[baf608a] | 90 | |
---|
[d46ed6e] | 91 | |
---|
[95eb7cf] | 92 | static bool prtFree = false; |
---|
[d46ed6e] | 93 | |
---|
[116a2ea] | 94 | bool prtFree() { |
---|
[95eb7cf] | 95 | return prtFree; |
---|
| 96 | } // prtFree |
---|
[5d4fa18] | 97 | |
---|
[116a2ea] | 98 | bool prtFreeOn() { |
---|
[95eb7cf] | 99 | bool temp = prtFree; |
---|
| 100 | prtFree = true; |
---|
[5d4fa18] | 101 | return temp; |
---|
[95eb7cf] | 102 | } // prtFreeOn |
---|
[5d4fa18] | 103 | |
---|
[116a2ea] | 104 | bool prtFreeOff() { |
---|
[95eb7cf] | 105 | bool temp = prtFree; |
---|
| 106 | prtFree = false; |
---|
[5d4fa18] | 107 | return temp; |
---|
[95eb7cf] | 108 | } // prtFreeOff |
---|
[5d4fa18] | 109 | |
---|
| 110 | |
---|
[116a2ea] | 111 | //######################### Spin Lock ######################### |
---|
[1e034d9] | 112 | |
---|
[dd23e66] | 113 | |
---|
[116a2ea] | 114 | // pause to prevent excess processor bus usage |
---|
| 115 | #if defined( __i386 ) || defined( __x86_64 ) |
---|
| 116 | #define Pause() __asm__ __volatile__ ( "pause" : : : ) |
---|
| 117 | #elif defined(__ARM_ARCH) |
---|
| 118 | #define Pause() __asm__ __volatile__ ( "YIELD" : : : ) |
---|
| 119 | #else |
---|
| 120 | #error unsupported architecture |
---|
| 121 | #endif |
---|
| 122 | |
---|
| 123 | typedef volatile uintptr_t SpinLock_t CALIGN; // aligned addressable word-size |
---|
| 124 | |
---|
| 125 | static inline __attribute__((always_inline)) void lock( volatile SpinLock_t & slock ) { |
---|
| 126 | enum { SPIN_START = 4, SPIN_END = 64 * 1024, }; |
---|
| 127 | unsigned int spin = SPIN_START; |
---|
| 128 | |
---|
| 129 | for ( unsigned int i = 1;; i += 1 ) { |
---|
| 130 | if ( slock == 0 && __atomic_test_and_set( &slock, __ATOMIC_SEQ_CST ) == 0 ) break; // Fence |
---|
| 131 | for ( volatile unsigned int s = 0; s < spin; s += 1 ) Pause(); // exponential spin |
---|
| 132 | spin += spin; // powers of 2 |
---|
| 133 | //if ( i % 64 == 0 ) spin += spin; // slowly increase by powers of 2 |
---|
| 134 | if ( spin > SPIN_END ) spin = SPIN_END; // cap spinning |
---|
| 135 | } // for |
---|
| 136 | } // spin_lock |
---|
| 137 | |
---|
| 138 | static inline __attribute__((always_inline)) void unlock( volatile SpinLock_t & slock ) { |
---|
| 139 | __atomic_clear( &slock, __ATOMIC_SEQ_CST ); // Fence |
---|
| 140 | } // spin_unlock |
---|
[e723100] | 141 | |
---|
| 142 | |
---|
[433905a] | 143 | //####################### Heap Statistics #################### |
---|
[d46ed6e] | 144 | |
---|
| 145 | |
---|
[433905a] | 146 | #ifdef __STATISTICS__ |
---|
| 147 | enum { CntTriples = 12 }; // number of counter triples |
---|
| 148 | enum { MALLOC, AALLOC, CALLOC, MEMALIGN, AMEMALIGN, CMEMALIGN, RESIZE, REALLOC, FREE }; |
---|
[bcb14b5] | 149 | |
---|
[433905a] | 150 | struct StatsOverlay { // overlay for iteration |
---|
| 151 | unsigned int calls, calls_0; |
---|
| 152 | unsigned long long int request, alloc; |
---|
| 153 | }; |
---|
[d46ed6e] | 154 | |
---|
[433905a] | 155 | // Heap statistics counters. |
---|
| 156 | union HeapStatistics { |
---|
| 157 | struct { // minimum qualification |
---|
| 158 | unsigned int malloc_calls, malloc_0_calls; |
---|
| 159 | unsigned long long int malloc_storage_request, malloc_storage_alloc; |
---|
| 160 | unsigned int aalloc_calls, aalloc_0_calls; |
---|
| 161 | unsigned long long int aalloc_storage_request, aalloc_storage_alloc; |
---|
| 162 | unsigned int calloc_calls, calloc_0_calls; |
---|
| 163 | unsigned long long int calloc_storage_request, calloc_storage_alloc; |
---|
| 164 | unsigned int memalign_calls, memalign_0_calls; |
---|
| 165 | unsigned long long int memalign_storage_request, memalign_storage_alloc; |
---|
| 166 | unsigned int amemalign_calls, amemalign_0_calls; |
---|
| 167 | unsigned long long int amemalign_storage_request, amemalign_storage_alloc; |
---|
| 168 | unsigned int cmemalign_calls, cmemalign_0_calls; |
---|
| 169 | unsigned long long int cmemalign_storage_request, cmemalign_storage_alloc; |
---|
| 170 | unsigned int resize_calls, resize_0_calls; |
---|
| 171 | unsigned long long int resize_storage_request, resize_storage_alloc; |
---|
| 172 | unsigned int realloc_calls, realloc_0_calls; |
---|
| 173 | unsigned long long int realloc_storage_request, realloc_storage_alloc; |
---|
| 174 | unsigned int free_calls, free_null_calls; |
---|
| 175 | unsigned long long int free_storage_request, free_storage_alloc; |
---|
[116a2ea] | 176 | unsigned int return_pulls, return_pushes; |
---|
| 177 | unsigned long long int return_storage_request, return_storage_alloc; |
---|
[433905a] | 178 | unsigned int mmap_calls, mmap_0_calls; // no zero calls |
---|
| 179 | unsigned long long int mmap_storage_request, mmap_storage_alloc; |
---|
| 180 | unsigned int munmap_calls, munmap_0_calls; // no zero calls |
---|
| 181 | unsigned long long int munmap_storage_request, munmap_storage_alloc; |
---|
| 182 | }; |
---|
| 183 | struct StatsOverlay counters[CntTriples]; // overlay for iteration |
---|
| 184 | }; // HeapStatistics |
---|
[1e034d9] | 185 | |
---|
[433905a] | 186 | static_assert( sizeof(HeapStatistics) == CntTriples * sizeof(StatsOverlay), |
---|
[116a2ea] | 187 | "Heap statistics counter-triplets does not match with array size" ); |
---|
[433905a] | 188 | |
---|
| 189 | static void HeapStatisticsCtor( HeapStatistics & stats ) { |
---|
| 190 | memset( &stats, '\0', sizeof(stats) ); // very fast |
---|
| 191 | // for ( unsigned int i = 0; i < CntTriples; i += 1 ) { |
---|
| 192 | // stats.counters[i].calls = stats.counters[i].calls_0 = stats.counters[i].request = stats.counters[i].alloc = 0; |
---|
| 193 | // } // for |
---|
| 194 | } // HeapStatisticsCtor |
---|
| 195 | |
---|
| 196 | static HeapStatistics & ?+=?( HeapStatistics & lhs, const HeapStatistics & rhs ) { |
---|
| 197 | for ( unsigned int i = 0; i < CntTriples; i += 1 ) { |
---|
| 198 | lhs.counters[i].calls += rhs.counters[i].calls; |
---|
| 199 | lhs.counters[i].calls_0 += rhs.counters[i].calls_0; |
---|
| 200 | lhs.counters[i].request += rhs.counters[i].request; |
---|
| 201 | lhs.counters[i].alloc += rhs.counters[i].alloc; |
---|
| 202 | } // for |
---|
| 203 | return lhs; |
---|
| 204 | } // ?+=? |
---|
| 205 | #endif // __STATISTICS__ |
---|
[e723100] | 206 | |
---|
| 207 | |
---|
| 208 | #define SPINLOCK 0 |
---|
| 209 | #define LOCKFREE 1 |
---|
| 210 | #define BUCKETLOCK SPINLOCK |
---|
[9c438546] | 211 | #if BUCKETLOCK == SPINLOCK |
---|
| 212 | #elif BUCKETLOCK == LOCKFREE |
---|
| 213 | #include <stackLockFree.hfa> |
---|
| 214 | #else |
---|
| 215 | #error undefined lock type for bucket lock |
---|
[e723100] | 216 | #endif // LOCKFREE |
---|
| 217 | |
---|
| 218 | // Recursive definitions: HeapManager needs size of bucket array and bucket area needs sizeof HeapManager storage. |
---|
[31a5f418] | 219 | // Break recursion by hardcoding number of buckets and statically checking number is correct after bucket array defined. |
---|
[95eb7cf] | 220 | enum { NoBucketSizes = 91 }; // number of buckets sizes |
---|
[d46ed6e] | 221 | |
---|
[31a5f418] | 222 | struct Heap { |
---|
[c4f68dc] | 223 | struct Storage { |
---|
[bcb14b5] | 224 | struct Header { // header |
---|
[c4f68dc] | 225 | union Kind { |
---|
| 226 | struct RealHeader { |
---|
| 227 | union { |
---|
[bcb14b5] | 228 | struct { // 4-byte word => 8-byte header, 8-byte word => 16-byte header |
---|
[c4f68dc] | 229 | union { |
---|
[31a5f418] | 230 | // 2nd low-order bit => zero filled, 3rd low-order bit => mmapped |
---|
[9c438546] | 231 | // FreeHeader * home; // allocated block points back to home locations (must overlay alignment) |
---|
[c4f68dc] | 232 | void * home; // allocated block points back to home locations (must overlay alignment) |
---|
| 233 | size_t blockSize; // size for munmap (must overlay alignment) |
---|
[9c438546] | 234 | #if BUCKETLOCK == SPINLOCK |
---|
[31a5f418] | 235 | Storage * next; // freed block points to next freed block of same size |
---|
[c4f68dc] | 236 | #endif // SPINLOCK |
---|
| 237 | }; |
---|
[9c438546] | 238 | size_t size; // allocation size in bytes |
---|
[c4f68dc] | 239 | }; |
---|
[9c438546] | 240 | #if BUCKETLOCK == LOCKFREE |
---|
| 241 | Link(Storage) next; // freed block points next freed block of same size (double-wide) |
---|
[c4f68dc] | 242 | #endif // LOCKFREE |
---|
| 243 | }; |
---|
[93c2e0a] | 244 | } real; // RealHeader |
---|
[9c438546] | 245 | |
---|
[c4f68dc] | 246 | struct FakeHeader { |
---|
[31a5f418] | 247 | uintptr_t alignment; // 1st low-order bit => fake header & alignment |
---|
| 248 | uintptr_t offset; |
---|
[93c2e0a] | 249 | } fake; // FakeHeader |
---|
| 250 | } kind; // Kind |
---|
[bcb14b5] | 251 | } header; // Header |
---|
[31a5f418] | 252 | |
---|
[95eb7cf] | 253 | char pad[libAlign() - sizeof( Header )]; |
---|
[bcb14b5] | 254 | char data[0]; // storage |
---|
[c4f68dc] | 255 | }; // Storage |
---|
| 256 | |
---|
[31a5f418] | 257 | static_assert( libAlign() >= sizeof( Storage ), "minimum alignment < sizeof( Storage )" ); |
---|
[c4f68dc] | 258 | |
---|
[116a2ea] | 259 | struct __attribute__(( aligned (8) )) FreeHeader { |
---|
| 260 | size_t blockSize __attribute__(( aligned(8) )); // size of allocations on this list |
---|
[9c438546] | 261 | #if BUCKETLOCK == SPINLOCK |
---|
[116a2ea] | 262 | #ifdef OWNERSHIP |
---|
| 263 | #ifdef RETURNSPIN |
---|
| 264 | SpinLock_t returnLock; |
---|
| 265 | #endif // RETURNSPIN |
---|
| 266 | Storage * returnList; // other thread return list |
---|
| 267 | #endif // OWNERSHIP |
---|
| 268 | Storage * freeList; // thread free list |
---|
[c4f68dc] | 269 | #else |
---|
[9c438546] | 270 | StackLF(Storage) freeList; |
---|
| 271 | #endif // BUCKETLOCK |
---|
[116a2ea] | 272 | Heap * homeManager; // heap owner (free storage to bucket, from bucket to heap) |
---|
| 273 | }; // FreeHeader |
---|
[c4f68dc] | 274 | |
---|
| 275 | FreeHeader freeLists[NoBucketSizes]; // buckets for different allocation sizes |
---|
[116a2ea] | 276 | void * heapBuffer; // start of free storage in buffer |
---|
| 277 | size_t heapReserve; // amount of remaining free storage in buffer |
---|
[c4f68dc] | 278 | |
---|
[116a2ea] | 279 | #if defined( __STATISTICS__ ) || defined( __CFA_DEBUG__ ) |
---|
| 280 | Heap * nextHeapManager; // intrusive link of existing heaps; traversed to collect statistics or check unfreed storage |
---|
| 281 | #endif // __STATISTICS__ || __CFA_DEBUG__ |
---|
| 282 | Heap * nextFreeHeapManager; // intrusive link of free heaps from terminated threads; reused by new threads |
---|
| 283 | |
---|
| 284 | #ifdef __CFA_DEBUG__ |
---|
| 285 | int64_t allocUnfreed; // running total of allocations minus frees; can be negative |
---|
| 286 | #endif // __CFA_DEBUG__ |
---|
| 287 | |
---|
| 288 | #ifdef __STATISTICS__ |
---|
| 289 | HeapStatistics stats; // local statistic table for this heap |
---|
| 290 | #endif // __STATISTICS__ |
---|
[31a5f418] | 291 | }; // Heap |
---|
[c4f68dc] | 292 | |
---|
[9c438546] | 293 | #if BUCKETLOCK == LOCKFREE |
---|
[116a2ea] | 294 | inline __attribute__((always_inline)) |
---|
| 295 | static { |
---|
[31a5f418] | 296 | Link(Heap.Storage) * ?`next( Heap.Storage * this ) { return &this->header.kind.real.next; } |
---|
| 297 | void ?{}( Heap.FreeHeader & ) {} |
---|
| 298 | void ^?{}( Heap.FreeHeader & ) {} |
---|
[c45d2fa] | 299 | } // distribution |
---|
[9c438546] | 300 | #endif // LOCKFREE |
---|
| 301 | |
---|
[116a2ea] | 302 | |
---|
| 303 | struct HeapMaster { |
---|
| 304 | SpinLock_t extLock; // protects allocation-buffer extension |
---|
| 305 | SpinLock_t mgrLock; // protects freeHeapManagersList, heapManagersList, heapManagersStorage, heapManagersStorageEnd |
---|
| 306 | |
---|
| 307 | void * heapBegin; // start of heap |
---|
| 308 | void * heapEnd; // logical end of heap |
---|
| 309 | size_t heapRemaining; // amount of storage not allocated in the current chunk |
---|
| 310 | size_t pageSize; // architecture pagesize |
---|
| 311 | size_t heapExpand; // sbrk advance |
---|
| 312 | size_t mmapStart; // cross over point for mmap |
---|
| 313 | unsigned int maxBucketsUsed; // maximum number of buckets in use |
---|
| 314 | |
---|
| 315 | Heap * heapManagersList; // heap-list head |
---|
| 316 | Heap * freeHeapManagersList; // free-list head |
---|
| 317 | |
---|
| 318 | // Heap superblocks are not linked; heaps in superblocks are linked via intrusive links. |
---|
| 319 | Heap * heapManagersStorage; // next heap to use in heap superblock |
---|
| 320 | Heap * heapManagersStorageEnd; // logical heap outside of superblock's end |
---|
| 321 | |
---|
| 322 | #ifdef __STATISTICS__ |
---|
| 323 | HeapStatistics stats; // global stats for thread-local heaps to add there counters when exiting |
---|
| 324 | unsigned long int threads_started, threads_exited; // counts threads that have started and exited |
---|
| 325 | unsigned long int reused_heap, new_heap; // counts reusability of heaps |
---|
| 326 | unsigned int sbrk_calls; |
---|
| 327 | unsigned long long int sbrk_storage; |
---|
| 328 | int stats_fd; |
---|
| 329 | #endif // __STATISTICS__ |
---|
| 330 | }; // HeapMaster |
---|
[5d4fa18] | 331 | |
---|
[e723100] | 332 | |
---|
[31a5f418] | 333 | #ifdef FASTLOOKUP |
---|
[116a2ea] | 334 | enum { LookupSizes = 65_536 + sizeof(Heap.Storage) }; // number of fast lookup sizes |
---|
[31a5f418] | 335 | static unsigned char lookup[LookupSizes]; // O(1) lookup for small sizes |
---|
| 336 | #endif // FASTLOOKUP |
---|
| 337 | |
---|
[116a2ea] | 338 | static volatile bool heapMasterBootFlag = false; // trigger for first heap |
---|
| 339 | static HeapMaster heapMaster @= {}; // program global |
---|
| 340 | |
---|
| 341 | static void heapMasterCtor(); |
---|
| 342 | static void heapMasterDtor(); |
---|
| 343 | static Heap * getHeap(); |
---|
[31a5f418] | 344 | |
---|
[5d4fa18] | 345 | |
---|
[c1f38e6c] | 346 | // Size of array must harmonize with NoBucketSizes and individual bucket sizes must be multiple of 16. |
---|
[d5d3a90] | 347 | // Smaller multiples of 16 and powers of 2 are common allocation sizes, so make them generate the minimum required bucket size. |
---|
| 348 | // malloc(0) returns 0p, so no bucket is necessary for 0 bytes returning an address that can be freed. |
---|
[e723100] | 349 | static const unsigned int bucketSizes[] @= { // different bucket sizes |
---|
[31a5f418] | 350 | 16 + sizeof(Heap.Storage), 32 + sizeof(Heap.Storage), 48 + sizeof(Heap.Storage), 64 + sizeof(Heap.Storage), // 4 |
---|
| 351 | 96 + sizeof(Heap.Storage), 112 + sizeof(Heap.Storage), 128 + sizeof(Heap.Storage), // 3 |
---|
| 352 | 160, 192, 224, 256 + sizeof(Heap.Storage), // 4 |
---|
| 353 | 320, 384, 448, 512 + sizeof(Heap.Storage), // 4 |
---|
| 354 | 640, 768, 896, 1_024 + sizeof(Heap.Storage), // 4 |
---|
| 355 | 1_536, 2_048 + sizeof(Heap.Storage), // 2 |
---|
| 356 | 2_560, 3_072, 3_584, 4_096 + sizeof(Heap.Storage), // 4 |
---|
| 357 | 6_144, 8_192 + sizeof(Heap.Storage), // 2 |
---|
| 358 | 9_216, 10_240, 11_264, 12_288, 13_312, 14_336, 15_360, 16_384 + sizeof(Heap.Storage), // 8 |
---|
| 359 | 18_432, 20_480, 22_528, 24_576, 26_624, 28_672, 30_720, 32_768 + sizeof(Heap.Storage), // 8 |
---|
| 360 | 36_864, 40_960, 45_056, 49_152, 53_248, 57_344, 61_440, 65_536 + sizeof(Heap.Storage), // 8 |
---|
| 361 | 73_728, 81_920, 90_112, 98_304, 106_496, 114_688, 122_880, 131_072 + sizeof(Heap.Storage), // 8 |
---|
| 362 | 147_456, 163_840, 180_224, 196_608, 212_992, 229_376, 245_760, 262_144 + sizeof(Heap.Storage), // 8 |
---|
| 363 | 294_912, 327_680, 360_448, 393_216, 425_984, 458_752, 491_520, 524_288 + sizeof(Heap.Storage), // 8 |
---|
| 364 | 655_360, 786_432, 917_504, 1_048_576 + sizeof(Heap.Storage), // 4 |
---|
| 365 | 1_179_648, 1_310_720, 1_441_792, 1_572_864, 1_703_936, 1_835_008, 1_966_080, 2_097_152 + sizeof(Heap.Storage), // 8 |
---|
| 366 | 2_621_440, 3_145_728, 3_670_016, 4_194_304 + sizeof(Heap.Storage), // 4 |
---|
[5d4fa18] | 367 | }; |
---|
[e723100] | 368 | |
---|
[c1f38e6c] | 369 | static_assert( NoBucketSizes == sizeof(bucketSizes) / sizeof(bucketSizes[0] ), "size of bucket array wrong" ); |
---|
[e723100] | 370 | |
---|
[5d4fa18] | 371 | |
---|
[116a2ea] | 372 | // extern visibility, used by runtime kernel |
---|
| 373 | libcfa_public size_t __page_size; // architecture pagesize |
---|
| 374 | libcfa_public int __map_prot; // common mmap/mprotect protection |
---|
[c4f68dc] | 375 | |
---|
[19e5d65d] | 376 | |
---|
[116a2ea] | 377 | // Thread-local storage is allocated lazily when the storage is accessed. |
---|
| 378 | static __thread size_t PAD1 CALIGN TLSMODEL __attribute__(( unused )); // protect false sharing |
---|
| 379 | static __thread Heap * volatile heapManager CALIGN TLSMODEL; |
---|
| 380 | static __thread size_t PAD2 CALIGN TLSMODEL __attribute__(( unused )); // protect further false sharing |
---|
[19e5d65d] | 381 | |
---|
[31a5f418] | 382 | |
---|
[116a2ea] | 383 | // declare helper functions for HeapMaster |
---|
| 384 | void noMemory(); // forward, called by "builtin_new" when malloc returns 0 |
---|
| 385 | |
---|
| 386 | |
---|
| 387 | // generic Bsearchl does not inline, so substitute with hand-coded binary-search. |
---|
| 388 | inline __attribute__((always_inline)) |
---|
| 389 | static size_t Bsearchl( unsigned int key, const unsigned int vals[], size_t dim ) { |
---|
| 390 | size_t l = 0, m, h = dim; |
---|
| 391 | while ( l < h ) { |
---|
| 392 | m = (l + h) / 2; |
---|
| 393 | if ( (unsigned int &)(vals[m]) < key ) { // cast away const |
---|
| 394 | l = m + 1; |
---|
| 395 | } else { |
---|
| 396 | h = m; |
---|
| 397 | } // if |
---|
| 398 | } // while |
---|
| 399 | return l; |
---|
| 400 | } // Bsearchl |
---|
| 401 | |
---|
| 402 | |
---|
| 403 | void heapMasterCtor() with( heapMaster ) { |
---|
| 404 | // Singleton pattern to initialize heap master |
---|
| 405 | |
---|
| 406 | verify( bucketSizes[0] == (16 + sizeof(Heap.Storage)) ); |
---|
| 407 | |
---|
| 408 | __page_size = sysconf( _SC_PAGESIZE ); |
---|
| 409 | __map_prot = PROT_READ | PROT_WRITE | PROT_EXEC; |
---|
| 410 | |
---|
| 411 | ?{}( extLock ); |
---|
| 412 | ?{}( mgrLock ); |
---|
| 413 | |
---|
| 414 | char * end = (char *)sbrk( 0 ); |
---|
| 415 | heapBegin = heapEnd = sbrk( (char *)ceiling2( (long unsigned int)end, libAlign() ) - end ); // move start of heap to multiple of alignment |
---|
| 416 | heapRemaining = 0; |
---|
| 417 | heapExpand = malloc_expansion(); |
---|
| 418 | mmapStart = malloc_mmap_start(); |
---|
| 419 | |
---|
| 420 | // find the closest bucket size less than or equal to the mmapStart size |
---|
| 421 | maxBucketsUsed = Bsearchl( mmapStart, bucketSizes, NoBucketSizes ); // binary search |
---|
| 422 | |
---|
| 423 | verify( (mmapStart >= pageSize) && (bucketSizes[NoBucketSizes - 1] >= mmapStart) ); |
---|
| 424 | verify( maxBucketsUsed < NoBucketSizes ); // subscript failure ? |
---|
| 425 | verify( mmapStart <= bucketSizes[maxBucketsUsed] ); // search failure ? |
---|
| 426 | |
---|
| 427 | heapManagersList = 0p; |
---|
| 428 | freeHeapManagersList = 0p; |
---|
| 429 | |
---|
| 430 | heapManagersStorage = 0p; |
---|
| 431 | heapManagersStorageEnd = 0p; |
---|
| 432 | |
---|
| 433 | #ifdef __STATISTICS__ |
---|
| 434 | HeapStatisticsCtor( stats ); // clear statistic counters |
---|
| 435 | threads_started = threads_exited = 0; |
---|
| 436 | reused_heap = new_heap = 0; |
---|
| 437 | sbrk_calls = sbrk_storage = 0; |
---|
| 438 | stats_fd = STDERR_FILENO; |
---|
| 439 | #endif // __STATISTICS__ |
---|
| 440 | |
---|
| 441 | #ifdef FASTLOOKUP |
---|
| 442 | for ( unsigned int i = 0, idx = 0; i < LookupSizes; i += 1 ) { |
---|
| 443 | if ( i > bucketSizes[idx] ) idx += 1; |
---|
| 444 | lookup[i] = idx; |
---|
| 445 | verify( i <= bucketSizes[idx] ); |
---|
| 446 | verify( (i <= 32 && idx == 0) || (i > bucketSizes[idx - 1]) ); |
---|
| 447 | } // for |
---|
| 448 | #endif // FASTLOOKUP |
---|
| 449 | |
---|
| 450 | heapMasterBootFlag = true; |
---|
| 451 | } // heapMasterCtor |
---|
| 452 | |
---|
| 453 | |
---|
[7671c6d] | 454 | #define NO_MEMORY_MSG "**** Error **** insufficient heap memory available to allocate %zd new bytes." |
---|
[116a2ea] | 455 | |
---|
| 456 | Heap * getHeap() with( heapMaster ) { |
---|
| 457 | Heap * heap; |
---|
| 458 | if ( freeHeapManagersList ) { // free heap for reused ? |
---|
| 459 | heap = freeHeapManagersList; |
---|
| 460 | freeHeapManagersList = heap->nextFreeHeapManager; |
---|
| 461 | |
---|
| 462 | #ifdef __STATISTICS__ |
---|
| 463 | reused_heap += 1; |
---|
| 464 | #endif // __STATISTICS__ |
---|
| 465 | } else { // free heap not found, create new |
---|
| 466 | // Heap size is about 12K, FreeHeader (128 bytes because of cache alignment) * NoBucketSizes (91) => 128 heaps * |
---|
| 467 | // 12K ~= 120K byte superblock. Where 128-heap superblock handles a medium sized multi-processor server. |
---|
| 468 | size_t remaining = heapManagersStorageEnd - heapManagersStorage; // remaining free heaps in superblock |
---|
| 469 | if ( ! heapManagersStorage || remaining != 0 ) { |
---|
| 470 | // Each block of heaps is a multiple of the number of cores on the computer. |
---|
| 471 | int HeapDim = get_nprocs(); // get_nprocs_conf does not work |
---|
| 472 | size_t size = HeapDim * sizeof( Heap ); |
---|
| 473 | |
---|
| 474 | heapManagersStorage = (Heap *)mmap( 0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 ); |
---|
| 475 | if ( unlikely( heapManagersStorage == (Heap *)MAP_FAILED ) ) { // failed ? |
---|
| 476 | if ( errno == ENOMEM ) abort( NO_MEMORY_MSG, size ); // no memory |
---|
| 477 | // Do not call strerror( errno ) as it may call malloc. |
---|
[7671c6d] | 478 | abort( "**** Error **** attempt to allocate block of heaps of size %zu bytes and mmap failed with errno %d.", size, errno ); |
---|
[116a2ea] | 479 | } // if |
---|
| 480 | heapManagersStorageEnd = &heapManagersStorage[HeapDim]; // outside array |
---|
| 481 | } // if |
---|
| 482 | |
---|
| 483 | heap = heapManagersStorage; |
---|
| 484 | heapManagersStorage = heapManagersStorage + 1; // bump next heap |
---|
| 485 | |
---|
| 486 | #if defined( __STATISTICS__ ) || defined( __CFA_DEBUG__ ) |
---|
| 487 | heap->nextHeapManager = heapManagersList; |
---|
| 488 | #endif // __STATISTICS__ || __CFA_DEBUG__ |
---|
| 489 | heapManagersList = heap; |
---|
| 490 | |
---|
| 491 | #ifdef __STATISTICS__ |
---|
| 492 | new_heap += 1; |
---|
| 493 | #endif // __STATISTICS__ |
---|
| 494 | |
---|
| 495 | with( *heap ) { |
---|
| 496 | for ( unsigned int j = 0; j < NoBucketSizes; j += 1 ) { // initialize free lists |
---|
| 497 | #ifdef OWNERSHIP |
---|
| 498 | #ifdef RETURNSPIN |
---|
| 499 | ?{}( freeLists[j].returnLock ); |
---|
| 500 | #endif // RETURNSPIN |
---|
| 501 | freeLists[j].returnList = 0p; |
---|
| 502 | #endif // OWNERSHIP |
---|
| 503 | freeLists[j].freeList = 0p; |
---|
| 504 | freeLists[j].homeManager = heap; |
---|
| 505 | freeLists[j].blockSize = bucketSizes[j]; |
---|
| 506 | } // for |
---|
| 507 | |
---|
| 508 | heapBuffer = 0p; |
---|
| 509 | heapReserve = 0; |
---|
| 510 | nextFreeHeapManager = 0p; |
---|
| 511 | #ifdef __CFA_DEBUG__ |
---|
| 512 | allocUnfreed = 0; |
---|
| 513 | #endif // __CFA_DEBUG__ |
---|
| 514 | } // with |
---|
[433905a] | 515 | } // if |
---|
[5951956] | 516 | |
---|
[116a2ea] | 517 | return heap; |
---|
| 518 | } // getHeap |
---|
| 519 | |
---|
| 520 | |
---|
| 521 | void heapManagerCtor() libcfa_public { |
---|
| 522 | if ( unlikely( ! heapMasterBootFlag ) ) heapMasterCtor(); |
---|
| 523 | |
---|
| 524 | lock( heapMaster.mgrLock ); // protect heapMaster counters |
---|
| 525 | |
---|
| 526 | // get storage for heap manager |
---|
| 527 | |
---|
| 528 | heapManager = getHeap(); |
---|
| 529 | |
---|
| 530 | #ifdef __STATISTICS__ |
---|
| 531 | HeapStatisticsCtor( heapManager->stats ); // heap local |
---|
| 532 | heapMaster.threads_started += 1; |
---|
| 533 | #endif // __STATISTICS__ |
---|
| 534 | |
---|
| 535 | unlock( heapMaster.mgrLock ); |
---|
| 536 | } // heapManagerCtor |
---|
| 537 | |
---|
| 538 | |
---|
| 539 | void heapManagerDtor() libcfa_public { |
---|
| 540 | lock( heapMaster.mgrLock ); |
---|
| 541 | |
---|
| 542 | // place heap on list of free heaps for reusability |
---|
| 543 | heapManager->nextFreeHeapManager = heapMaster.freeHeapManagersList; |
---|
| 544 | heapMaster.freeHeapManagersList = heapManager; |
---|
| 545 | |
---|
| 546 | #ifdef __STATISTICS__ |
---|
| 547 | heapMaster.threads_exited += 1; |
---|
| 548 | #endif // __STATISTICS__ |
---|
| 549 | |
---|
| 550 | // Do not set heapManager to NULL because it is used after Cforall is shutdown but before the program shuts down. |
---|
| 551 | |
---|
| 552 | unlock( heapMaster.mgrLock ); |
---|
| 553 | } // heapManagerDtor |
---|
| 554 | |
---|
| 555 | |
---|
| 556 | //####################### Memory Allocation Routines Helpers #################### |
---|
| 557 | |
---|
[31a5f418] | 558 | |
---|
[433905a] | 559 | extern int cfa_main_returned; // from interpose.cfa |
---|
| 560 | extern "C" { |
---|
[116a2ea] | 561 | void memory_startup( void ) { |
---|
| 562 | if ( ! heapMasterBootFlag ) heapManagerCtor(); // sanity check |
---|
| 563 | } // memory_startup |
---|
| 564 | |
---|
| 565 | void memory_shutdown( void ) { |
---|
| 566 | heapManagerDtor(); |
---|
| 567 | } // memory_shutdown |
---|
| 568 | |
---|
[433905a] | 569 | void heapAppStart() { // called by __cfaabi_appready_startup |
---|
[116a2ea] | 570 | verify( heapManager ); |
---|
| 571 | #ifdef __CFA_DEBUG__ |
---|
| 572 | heapManager->allocUnfreed = 0; // clear prior allocation counts |
---|
| 573 | #endif // __CFA_DEBUG__ |
---|
| 574 | |
---|
| 575 | #ifdef __STATISTICS__ |
---|
| 576 | HeapStatisticsCtor( heapManager->stats ); // clear prior statistic counters |
---|
| 577 | #endif // __STATISTICS__ |
---|
[433905a] | 578 | } // heapAppStart |
---|
[31a5f418] | 579 | |
---|
[433905a] | 580 | void heapAppStop() { // called by __cfaabi_appready_startdown |
---|
[116a2ea] | 581 | fclose( stdin ); fclose( stdout ); // free buffer storage |
---|
| 582 | if ( ! cfa_main_returned ) return; // do not check unfreed storage if exit called |
---|
| 583 | |
---|
| 584 | #ifdef __CFA_DEBUG__ |
---|
| 585 | // allocUnfreed is set to 0 when a heap is created and it accumulates any unfreed storage during its multiple thread |
---|
| 586 | // usages. At the end, add up each heap allocUnfreed value across all heaps to get the total unfreed storage. |
---|
[5951956] | 587 | int64_t allocUnfreed = 0; |
---|
[116a2ea] | 588 | for ( Heap * heap = heapMaster.heapManagersList; heap; heap = heap->nextHeapManager ) { |
---|
| 589 | allocUnfreed += heap->allocUnfreed; |
---|
| 590 | } // for |
---|
| 591 | |
---|
| 592 | allocUnfreed -= malloc_unfreed(); // subtract any user specified unfreed storage |
---|
| 593 | if ( allocUnfreed > 0 ) { |
---|
| 594 | // DO NOT USE STREAMS AS THEY MAY BE UNAVAILABLE AT THIS POINT. |
---|
| 595 | char helpText[512]; |
---|
| 596 | __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText), |
---|
[80fbdc9] | 597 | "CFA warning (UNIX pid:%ld) : program terminating with %ju(0x%jx) bytes of storage allocated but not freed.\n" |
---|
[116a2ea] | 598 | "Possible cause is unfreed storage allocated by the program or system/library routines called from the program.\n", |
---|
| 599 | (long int)getpid(), allocUnfreed, allocUnfreed ); // always print the UNIX pid |
---|
| 600 | } // if |
---|
| 601 | #endif // __CFA_DEBUG__ |
---|
[433905a] | 602 | } // heapAppStop |
---|
| 603 | } // extern "C" |
---|
[31a5f418] | 604 | |
---|
| 605 | |
---|
[433905a] | 606 | #ifdef __STATISTICS__ |
---|
[31a5f418] | 607 | static HeapStatistics stats; // zero filled |
---|
[c4f68dc] | 608 | |
---|
[31a5f418] | 609 | #define prtFmt \ |
---|
| 610 | "\nHeap statistics: (storage request / allocation)\n" \ |
---|
| 611 | " malloc >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \ |
---|
| 612 | " aalloc >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \ |
---|
| 613 | " calloc >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \ |
---|
| 614 | " memalign >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \ |
---|
| 615 | " amemalign >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \ |
---|
| 616 | " cmemalign >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \ |
---|
| 617 | " resize >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \ |
---|
| 618 | " realloc >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \ |
---|
| 619 | " free !null calls %'u; null calls %'u; storage %'llu / %'llu bytes\n" \ |
---|
[116a2ea] | 620 | " return pulls %'u; pushes %'u; storage %'llu / %'llu bytes\n" \ |
---|
| 621 | " sbrk calls %'u; storage %'llu bytes\n" \ |
---|
| 622 | " mmap calls %'u; storage %'llu / %'llu bytes\n" \ |
---|
| 623 | " munmap calls %'u; storage %'llu / %'llu bytes\n" \ |
---|
| 624 | " threads started %'lu; exited %'lu\n" \ |
---|
| 625 | " heaps new %'lu; reused %'lu\n" |
---|
[31a5f418] | 626 | |
---|
[c4f68dc] | 627 | // Use "write" because streams may be shutdown when calls are made. |
---|
[116a2ea] | 628 | static int printStats( HeapStatistics & stats ) with( heapMaster, stats ) { // see malloc_stats |
---|
[31a5f418] | 629 | char helpText[sizeof(prtFmt) + 1024]; // space for message and values |
---|
[116a2ea] | 630 | return __cfaabi_bits_print_buffer( stats_fd, helpText, sizeof(helpText), prtFmt, |
---|
| 631 | malloc_calls, malloc_0_calls, malloc_storage_request, malloc_storage_alloc, |
---|
| 632 | aalloc_calls, aalloc_0_calls, aalloc_storage_request, aalloc_storage_alloc, |
---|
| 633 | calloc_calls, calloc_0_calls, calloc_storage_request, calloc_storage_alloc, |
---|
| 634 | memalign_calls, memalign_0_calls, memalign_storage_request, memalign_storage_alloc, |
---|
| 635 | amemalign_calls, amemalign_0_calls, amemalign_storage_request, amemalign_storage_alloc, |
---|
| 636 | cmemalign_calls, cmemalign_0_calls, cmemalign_storage_request, cmemalign_storage_alloc, |
---|
| 637 | resize_calls, resize_0_calls, resize_storage_request, resize_storage_alloc, |
---|
| 638 | realloc_calls, realloc_0_calls, realloc_storage_request, realloc_storage_alloc, |
---|
| 639 | free_calls, free_null_calls, free_storage_request, free_storage_alloc, |
---|
| 640 | return_pulls, return_pushes, return_storage_request, return_storage_alloc, |
---|
[31a5f418] | 641 | sbrk_calls, sbrk_storage, |
---|
[116a2ea] | 642 | mmap_calls, mmap_storage_request, mmap_storage_alloc, |
---|
| 643 | munmap_calls, munmap_storage_request, munmap_storage_alloc, |
---|
| 644 | threads_started, threads_exited, |
---|
| 645 | new_heap, reused_heap |
---|
[c4f68dc] | 646 | ); |
---|
[d46ed6e] | 647 | } // printStats |
---|
[c4f68dc] | 648 | |
---|
[31a5f418] | 649 | #define prtFmtXML \ |
---|
| 650 | "<malloc version=\"1\">\n" \ |
---|
| 651 | "<heap nr=\"0\">\n" \ |
---|
| 652 | "<sizes>\n" \ |
---|
| 653 | "</sizes>\n" \ |
---|
| 654 | "<total type=\"malloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \ |
---|
| 655 | "<total type=\"aalloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \ |
---|
| 656 | "<total type=\"calloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \ |
---|
| 657 | "<total type=\"memalign\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \ |
---|
| 658 | "<total type=\"amemalign\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \ |
---|
| 659 | "<total type=\"cmemalign\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \ |
---|
| 660 | "<total type=\"resize\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \ |
---|
| 661 | "<total type=\"realloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \ |
---|
| 662 | "<total type=\"free\" !null=\"%'u;\" 0 null=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \ |
---|
[116a2ea] | 663 | "<total type=\"return\" pulls=\"%'u;\" 0 pushes=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \ |
---|
[31a5f418] | 664 | "<total type=\"sbrk\" count=\"%'u;\" size=\"%'llu\"/> bytes\n" \ |
---|
| 665 | "<total type=\"mmap\" count=\"%'u;\" size=\"%'llu / %'llu\" / > bytes\n" \ |
---|
| 666 | "<total type=\"munmap\" count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \ |
---|
[116a2ea] | 667 | "<total type=\"threads\" started=\"%'lu;\" exited=\"%'lu\"/>\n" \ |
---|
| 668 | "<total type=\"heaps\" new=\"%'lu;\" reused=\"%'lu\"/>\n" \ |
---|
[31a5f418] | 669 | "</malloc>" |
---|
| 670 | |
---|
[116a2ea] | 671 | static int printStatsXML( HeapStatistics & stats, FILE * stream ) with( heapMaster, stats ) { // see malloc_info |
---|
[31a5f418] | 672 | char helpText[sizeof(prtFmtXML) + 1024]; // space for message and values |
---|
| 673 | return __cfaabi_bits_print_buffer( fileno( stream ), helpText, sizeof(helpText), prtFmtXML, |
---|
[116a2ea] | 674 | malloc_calls, malloc_0_calls, malloc_storage_request, malloc_storage_alloc, |
---|
| 675 | aalloc_calls, aalloc_0_calls, aalloc_storage_request, aalloc_storage_alloc, |
---|
| 676 | calloc_calls, calloc_0_calls, calloc_storage_request, calloc_storage_alloc, |
---|
| 677 | memalign_calls, memalign_0_calls, memalign_storage_request, memalign_storage_alloc, |
---|
| 678 | amemalign_calls, amemalign_0_calls, amemalign_storage_request, amemalign_storage_alloc, |
---|
| 679 | cmemalign_calls, cmemalign_0_calls, cmemalign_storage_request, cmemalign_storage_alloc, |
---|
| 680 | resize_calls, resize_0_calls, resize_storage_request, resize_storage_alloc, |
---|
| 681 | realloc_calls, realloc_0_calls, realloc_storage_request, realloc_storage_alloc, |
---|
| 682 | free_calls, free_null_calls, free_storage_request, free_storage_alloc, |
---|
| 683 | return_pulls, return_pushes, return_storage_request, return_storage_alloc, |
---|
[31a5f418] | 684 | sbrk_calls, sbrk_storage, |
---|
[116a2ea] | 685 | mmap_calls, mmap_storage_request, mmap_storage_alloc, |
---|
| 686 | munmap_calls, munmap_storage_request, munmap_storage_alloc, |
---|
| 687 | threads_started, threads_exited, |
---|
| 688 | new_heap, reused_heap |
---|
[c4f68dc] | 689 | ); |
---|
[d46ed6e] | 690 | } // printStatsXML |
---|
[95eb7cf] | 691 | |
---|
[116a2ea] | 692 | static HeapStatistics & collectStats( HeapStatistics & stats ) with( heapMaster ) { |
---|
| 693 | lock( mgrLock ); |
---|
[433905a] | 694 | |
---|
[116a2ea] | 695 | stats += heapMaster.stats; |
---|
| 696 | for ( Heap * heap = heapManagersList; heap; heap = heap->nextHeapManager ) { |
---|
| 697 | stats += heap->stats; |
---|
| 698 | } // for |
---|
[433905a] | 699 | |
---|
[116a2ea] | 700 | unlock( mgrLock ); |
---|
| 701 | return stats; |
---|
| 702 | } // collectStats |
---|
| 703 | #endif // __STATISTICS__ |
---|
[1e034d9] | 704 | |
---|
| 705 | |
---|
[116a2ea] | 706 | static bool setMmapStart( size_t value ) with( heapMaster ) { // true => mmapped, false => sbrk |
---|
[ad2dced] | 707 | if ( value < __page_size || bucketSizes[NoBucketSizes - 1] < value ) return false; |
---|
[95eb7cf] | 708 | mmapStart = value; // set global |
---|
| 709 | |
---|
| 710 | // find the closest bucket size less than or equal to the mmapStart size |
---|
[116a2ea] | 711 | maxBucketsUsed = Bsearchl( mmapStart, bucketSizes, NoBucketSizes ); // binary search |
---|
| 712 | verify( maxBucketsUsed < NoBucketSizes ); // subscript failure ? |
---|
| 713 | verify( mmapStart <= bucketSizes[maxBucketsUsed] ); // search failure ? |
---|
[1076d05] | 714 | return true; |
---|
[95eb7cf] | 715 | } // setMmapStart |
---|
| 716 | |
---|
| 717 | |
---|
[cfbc703d] | 718 | // <-------+----------------------------------------------------> bsize (bucket size) |
---|
| 719 | // |header |addr |
---|
| 720 | //================================================================================== |
---|
| 721 | // align/offset | |
---|
| 722 | // <-----------------<------------+-----------------------------> bsize (bucket size) |
---|
| 723 | // |fake-header | addr |
---|
[19e5d65d] | 724 | #define HeaderAddr( addr ) ((Heap.Storage.Header *)( (char *)addr - sizeof(Heap.Storage) )) |
---|
| 725 | #define RealHeader( header ) ((Heap.Storage.Header *)((char *)header - header->kind.fake.offset)) |
---|
[cfbc703d] | 726 | |
---|
| 727 | // <-------<<--------------------- dsize ---------------------->> bsize (bucket size) |
---|
| 728 | // |header |addr |
---|
| 729 | //================================================================================== |
---|
| 730 | // align/offset | |
---|
| 731 | // <------------------------------<<---------- dsize --------->>> bsize (bucket size) |
---|
| 732 | // |fake-header |addr |
---|
[19e5d65d] | 733 | #define DataStorage( bsize, addr, header ) (bsize - ( (char *)addr - (char *)header )) |
---|
[cfbc703d] | 734 | |
---|
| 735 | |
---|
[116a2ea] | 736 | inline __attribute__((always_inline)) |
---|
| 737 | static void checkAlign( size_t alignment ) { |
---|
[19e5d65d] | 738 | if ( unlikely( alignment < libAlign() || ! is_pow2( alignment ) ) ) { |
---|
| 739 | abort( "**** Error **** alignment %zu for memory allocation is less than %d and/or not a power of 2.", alignment, libAlign() ); |
---|
[cfbc703d] | 740 | } // if |
---|
| 741 | } // checkAlign |
---|
| 742 | |
---|
| 743 | |
---|
[116a2ea] | 744 | inline __attribute__((always_inline)) |
---|
| 745 | static void checkHeader( bool check, const char name[], void * addr ) { |
---|
[b6830d74] | 746 | if ( unlikely( check ) ) { // bad address ? |
---|
[19e5d65d] | 747 | abort( "**** Error **** attempt to %s storage %p with address outside the heap.\n" |
---|
[bcb14b5] | 748 | "Possible cause is duplicate free on same block or overwriting of memory.", |
---|
| 749 | name, addr ); |
---|
[b6830d74] | 750 | } // if |
---|
[c4f68dc] | 751 | } // checkHeader |
---|
| 752 | |
---|
[95eb7cf] | 753 | |
---|
[19e5d65d] | 754 | // Manipulate sticky bits stored in unused 3 low-order bits of an address. |
---|
| 755 | // bit0 => alignment => fake header |
---|
| 756 | // bit1 => zero filled (calloc) |
---|
| 757 | // bit2 => mapped allocation versus sbrk |
---|
| 758 | #define StickyBits( header ) (((header)->kind.real.blockSize & 0x7)) |
---|
| 759 | #define ClearStickyBits( addr ) (typeof(addr))((uintptr_t)(addr) & ~7) |
---|
| 760 | #define MarkAlignmentBit( align ) ((align) | 1) |
---|
| 761 | #define AlignmentBit( header ) ((((header)->kind.fake.alignment) & 1)) |
---|
| 762 | #define ClearAlignmentBit( header ) (((header)->kind.fake.alignment) & ~1) |
---|
| 763 | #define ZeroFillBit( header ) ((((header)->kind.real.blockSize) & 2)) |
---|
| 764 | #define ClearZeroFillBit( header ) ((((header)->kind.real.blockSize) &= ~2)) |
---|
| 765 | #define MarkZeroFilledBit( header ) ((header)->kind.real.blockSize |= 2) |
---|
| 766 | #define MmappedBit( header ) ((((header)->kind.real.blockSize) & 4)) |
---|
| 767 | #define MarkMmappedBit( size ) ((size) | 4) |
---|
| 768 | |
---|
| 769 | |
---|
[116a2ea] | 770 | inline __attribute__((always_inline)) |
---|
| 771 | static void fakeHeader( Heap.Storage.Header *& header, size_t & alignment ) { |
---|
[19e5d65d] | 772 | if ( unlikely( AlignmentBit( header ) ) ) { // fake header ? |
---|
| 773 | alignment = ClearAlignmentBit( header ); // clear flag from value |
---|
[c4f68dc] | 774 | #ifdef __CFA_DEBUG__ |
---|
| 775 | checkAlign( alignment ); // check alignment |
---|
| 776 | #endif // __CFA_DEBUG__ |
---|
[19e5d65d] | 777 | header = RealHeader( header ); // backup from fake to real header |
---|
[d5d3a90] | 778 | } else { |
---|
[c1f38e6c] | 779 | alignment = libAlign(); // => no fake header |
---|
[b6830d74] | 780 | } // if |
---|
[c4f68dc] | 781 | } // fakeHeader |
---|
| 782 | |
---|
[95eb7cf] | 783 | |
---|
[116a2ea] | 784 | inline __attribute__((always_inline)) |
---|
| 785 | static bool headers( const char name[] __attribute__(( unused )), void * addr, Heap.Storage.Header *& header, |
---|
| 786 | Heap.FreeHeader *& freeHead, size_t & size, size_t & alignment ) with( heapMaster, *heapManager ) { |
---|
[19e5d65d] | 787 | header = HeaderAddr( addr ); |
---|
[c4f68dc] | 788 | |
---|
| 789 | #ifdef __CFA_DEBUG__ |
---|
[31a5f418] | 790 | checkHeader( header < (Heap.Storage.Header *)heapBegin, name, addr ); // bad low address ? |
---|
[c4f68dc] | 791 | #endif // __CFA_DEBUG__ |
---|
[b6830d74] | 792 | |
---|
[19e5d65d] | 793 | if ( likely( ! StickyBits( header ) ) ) { // no sticky bits ? |
---|
| 794 | freeHead = (Heap.FreeHeader *)(header->kind.real.home); |
---|
| 795 | alignment = libAlign(); |
---|
| 796 | } else { |
---|
| 797 | fakeHeader( header, alignment ); |
---|
[433905a] | 798 | if ( unlikely( MmappedBit( header ) ) ) { // mmapped ? |
---|
| 799 | verify( addr < heapBegin || heapEnd < addr ); |
---|
[19e5d65d] | 800 | size = ClearStickyBits( header->kind.real.blockSize ); // mmap size |
---|
| 801 | return true; |
---|
| 802 | } // if |
---|
| 803 | |
---|
| 804 | freeHead = (Heap.FreeHeader *)(ClearStickyBits( header->kind.real.home )); |
---|
| 805 | } // if |
---|
| 806 | size = freeHead->blockSize; |
---|
| 807 | |
---|
[c4f68dc] | 808 | #ifdef __CFA_DEBUG__ |
---|
[31a5f418] | 809 | checkHeader( header < (Heap.Storage.Header *)heapBegin || (Heap.Storage.Header *)heapEnd < header, name, addr ); // bad address ? (offset could be + or -) |
---|
[c4f68dc] | 810 | |
---|
[116a2ea] | 811 | Heap * homeManager; |
---|
[433905a] | 812 | if ( unlikely( freeHead == 0p || // freed and only free-list node => null link |
---|
| 813 | // freed and link points at another free block not to a bucket in the bucket array. |
---|
[116a2ea] | 814 | (homeManager = freeHead->homeManager, freeHead < &homeManager->freeLists[0] || |
---|
| 815 | &homeManager->freeLists[NoBucketSizes] <= freeHead ) ) ) { |
---|
[433905a] | 816 | abort( "**** Error **** attempt to %s storage %p with corrupted header.\n" |
---|
| 817 | "Possible cause is duplicate free on same block or overwriting of header information.", |
---|
| 818 | name, addr ); |
---|
| 819 | } // if |
---|
[c4f68dc] | 820 | #endif // __CFA_DEBUG__ |
---|
[19e5d65d] | 821 | |
---|
[bcb14b5] | 822 | return false; |
---|
[c4f68dc] | 823 | } // headers |
---|
| 824 | |
---|
| 825 | |
---|
[116a2ea] | 826 | static void * master_extend( size_t size ) with( heapMaster ) { |
---|
| 827 | lock( extLock ); |
---|
[19e5d65d] | 828 | |
---|
[b6830d74] | 829 | ptrdiff_t rem = heapRemaining - size; |
---|
[19e5d65d] | 830 | if ( unlikely( rem < 0 ) ) { |
---|
[c4f68dc] | 831 | // If the size requested is bigger than the current remaining storage, increase the size of the heap. |
---|
| 832 | |
---|
[116a2ea] | 833 | size_t increase = ceiling2( size > heapExpand ? size : heapExpand, libAlign() ); |
---|
[ad2dced] | 834 | // Do not call abort or strerror( errno ) as they may call malloc. |
---|
[116a2ea] | 835 | if ( unlikely( sbrk( increase ) == (void *)-1 ) ) { // failed, no memory ? |
---|
| 836 | unlock( extLock ); |
---|
[7671c6d] | 837 | abort( NO_MEMORY_MSG, size ); // no memory |
---|
[92aca37] | 838 | } // if |
---|
[7671c6d] | 839 | |
---|
| 840 | // Make storage executable for thunks. |
---|
| 841 | if ( mprotect( (char *)heapEnd + heapRemaining, increase, __map_prot ) ) { |
---|
| 842 | unlock( extLock ); |
---|
| 843 | abort( "**** Error **** attempt to make heap storage executable for thunks and mprotect failed with errno %d.", errno ); |
---|
| 844 | } // if |
---|
| 845 | |
---|
[116a2ea] | 846 | rem = heapRemaining + increase - size; |
---|
[19e5d65d] | 847 | |
---|
[bcb14b5] | 848 | #ifdef __STATISTICS__ |
---|
[c4f68dc] | 849 | sbrk_calls += 1; |
---|
| 850 | sbrk_storage += increase; |
---|
[bcb14b5] | 851 | #endif // __STATISTICS__ |
---|
[b6830d74] | 852 | } // if |
---|
[c4f68dc] | 853 | |
---|
[31a5f418] | 854 | Heap.Storage * block = (Heap.Storage *)heapEnd; |
---|
[b6830d74] | 855 | heapRemaining = rem; |
---|
| 856 | heapEnd = (char *)heapEnd + size; |
---|
[116a2ea] | 857 | |
---|
| 858 | unlock( extLock ); |
---|
| 859 | return block; |
---|
| 860 | } // master_extend |
---|
| 861 | |
---|
| 862 | |
---|
| 863 | __attribute__(( noinline )) |
---|
| 864 | static void * manager_extend( size_t size ) with( *heapManager ) { |
---|
| 865 | ptrdiff_t rem = heapReserve - size; |
---|
| 866 | |
---|
| 867 | if ( unlikely( rem < 0 ) ) { // negative |
---|
| 868 | // If the size requested is bigger than the current remaining reserve, use the current reserve to populate |
---|
| 869 | // smaller freeLists, and increase the reserve. |
---|
| 870 | |
---|
| 871 | rem = heapReserve; // positive |
---|
| 872 | |
---|
| 873 | if ( rem >= bucketSizes[0] ) { // minimal size ? otherwise ignore |
---|
| 874 | size_t bucket; |
---|
| 875 | #ifdef FASTLOOKUP |
---|
| 876 | if ( likely( rem < LookupSizes ) ) bucket = lookup[rem]; |
---|
| 877 | #endif // FASTLOOKUP |
---|
| 878 | bucket = Bsearchl( rem, bucketSizes, heapMaster.maxBucketsUsed ); |
---|
| 879 | verify( 0 <= bucket && bucket <= heapMaster.maxBucketsUsed ); |
---|
| 880 | Heap.FreeHeader * freeHead = &(freeLists[bucket]); |
---|
| 881 | |
---|
| 882 | // The remaining storage many not be bucket size, whereas all other allocations are. Round down to previous |
---|
| 883 | // bucket size in this case. |
---|
| 884 | if ( unlikely( freeHead->blockSize > (size_t)rem ) ) freeHead -= 1; |
---|
| 885 | Heap.Storage * block = (Heap.Storage *)heapBuffer; |
---|
| 886 | |
---|
| 887 | block->header.kind.real.next = freeHead->freeList; // push on stack |
---|
| 888 | freeHead->freeList = block; |
---|
| 889 | } // if |
---|
| 890 | |
---|
| 891 | size_t increase = ceiling( size > ( heapMaster.heapExpand / 10 ) ? size : ( heapMaster.heapExpand / 10 ), libAlign() ); |
---|
| 892 | heapBuffer = master_extend( increase ); |
---|
| 893 | rem = increase - size; |
---|
| 894 | } // if |
---|
| 895 | |
---|
| 896 | Heap.Storage * block = (Heap.Storage *)heapBuffer; |
---|
| 897 | heapReserve = rem; |
---|
| 898 | heapBuffer = (char *)heapBuffer + size; |
---|
| 899 | |
---|
[b6830d74] | 900 | return block; |
---|
[116a2ea] | 901 | } // manager_extend |
---|
| 902 | |
---|
| 903 | |
---|
| 904 | #define BOOT_HEAP_MANAGER \ |
---|
| 905 | if ( unlikely( ! heapMasterBootFlag ) ) { \ |
---|
| 906 | heapManagerCtor(); /* trigger for first heap */ \ |
---|
| 907 | } /* if */ |
---|
| 908 | |
---|
| 909 | #ifdef __STATISTICS__ |
---|
| 910 | #define STAT_NAME __counter |
---|
| 911 | #define STAT_PARM , unsigned int STAT_NAME |
---|
| 912 | #define STAT_ARG( name ) , name |
---|
| 913 | #define STAT_0_CNT( counter ) stats.counters[counter].calls_0 += 1 |
---|
| 914 | #else |
---|
| 915 | #define STAT_NAME |
---|
| 916 | #define STAT_PARM |
---|
| 917 | #define STAT_ARG( name ) |
---|
| 918 | #define STAT_0_CNT( counter ) |
---|
| 919 | #endif // __STATISTICS__ |
---|
| 920 | |
---|
| 921 | #define PROLOG( counter, ... ) \ |
---|
| 922 | BOOT_HEAP_MANAGER; \ |
---|
| 923 | if ( unlikely( size == 0 ) || /* 0 BYTE ALLOCATION RETURNS NULL POINTER */ \ |
---|
| 924 | unlikely( size > ULONG_MAX - sizeof(Heap.Storage) ) ) { /* error check */ \ |
---|
| 925 | STAT_0_CNT( counter ); \ |
---|
| 926 | __VA_ARGS__; \ |
---|
| 927 | return 0p; \ |
---|
| 928 | } /* if */ |
---|
| 929 | |
---|
[c4f68dc] | 930 | |
---|
[116a2ea] | 931 | #define SCRUB_SIZE 1024lu |
---|
| 932 | // Do not use '\xfe' for scrubbing because dereferencing an address composed of it causes a SIGSEGV *without* a valid IP |
---|
| 933 | // pointer in the interrupt frame. |
---|
| 934 | #define SCRUB '\xff' |
---|
[c4f68dc] | 935 | |
---|
[116a2ea] | 936 | static void * doMalloc( size_t size STAT_PARM ) libcfa_nopreempt with( *heapManager ) { |
---|
| 937 | PROLOG( STAT_NAME ); |
---|
| 938 | |
---|
| 939 | verify( heapManager ); |
---|
| 940 | Heap.Storage * block; // pointer to new block of storage |
---|
[c4f68dc] | 941 | |
---|
[b6830d74] | 942 | // Look up size in the size list. Make sure the user request includes space for the header that must be allocated |
---|
| 943 | // along with the block and is a multiple of the alignment size. |
---|
[31a5f418] | 944 | size_t tsize = size + sizeof(Heap.Storage); |
---|
[19e5d65d] | 945 | |
---|
[116a2ea] | 946 | #ifdef __STATISTICS__ |
---|
| 947 | stats.counters[STAT_NAME].calls += 1; |
---|
| 948 | stats.counters[STAT_NAME].request += size; |
---|
| 949 | #endif // __STATISTICS__ |
---|
| 950 | |
---|
| 951 | #ifdef __CFA_DEBUG__ |
---|
| 952 | allocUnfreed += size; |
---|
| 953 | #endif // __CFA_DEBUG__ |
---|
| 954 | |
---|
| 955 | if ( likely( tsize < heapMaster.mmapStart ) ) { // small size => sbrk |
---|
| 956 | size_t bucket; |
---|
[e723100] | 957 | #ifdef FASTLOOKUP |
---|
[116a2ea] | 958 | if ( likely( tsize < LookupSizes ) ) bucket = lookup[tsize]; |
---|
[e723100] | 959 | else |
---|
| 960 | #endif // FASTLOOKUP |
---|
[116a2ea] | 961 | bucket = Bsearchl( tsize, bucketSizes, heapMaster.maxBucketsUsed ); |
---|
| 962 | verify( 0 <= bucket && bucket <= heapMaster.maxBucketsUsed ); |
---|
| 963 | Heap.FreeHeader * freeHead = &freeLists[bucket]; |
---|
| 964 | |
---|
| 965 | verify( freeHead <= &freeLists[heapMaster.maxBucketsUsed] ); // subscripting error ? |
---|
| 966 | verify( tsize <= freeHead->blockSize ); // search failure ? |
---|
| 967 | |
---|
| 968 | tsize = freeHead->blockSize; // total space needed for request |
---|
| 969 | #ifdef __STATISTICS__ |
---|
| 970 | stats.counters[STAT_NAME].alloc += tsize; |
---|
| 971 | #endif // __STATISTICS__ |
---|
[c4f68dc] | 972 | |
---|
| 973 | // Spin until the lock is acquired for this particular size of block. |
---|
| 974 | |
---|
[9c438546] | 975 | #if BUCKETLOCK == SPINLOCK |
---|
[116a2ea] | 976 | block = freeHead->freeList; // remove node from stack |
---|
[c4f68dc] | 977 | #else |
---|
[116a2ea] | 978 | block = pop( freeHead->freeList ); |
---|
[9c438546] | 979 | #endif // BUCKETLOCK |
---|
[95eb7cf] | 980 | if ( unlikely( block == 0p ) ) { // no free block ? |
---|
[116a2ea] | 981 | #ifdef OWNERSHIP |
---|
| 982 | // Freelist for that size is empty, so carve it out of the heap, if there is enough left, or get some more |
---|
| 983 | // and then carve it off. |
---|
| 984 | #ifdef RETURNSPIN |
---|
[9c438546] | 985 | #if BUCKETLOCK == SPINLOCK |
---|
[116a2ea] | 986 | lock( freeHead->returnLock ); |
---|
| 987 | block = freeHead->returnList; |
---|
| 988 | freeHead->returnList = 0p; |
---|
| 989 | unlock( freeHead->returnLock ); |
---|
| 990 | #else |
---|
| 991 | block = __atomic_exchange_n( &freeHead->returnList, nullptr, __ATOMIC_SEQ_CST ); |
---|
| 992 | #endif // RETURNSPIN |
---|
| 993 | |
---|
| 994 | if ( likely( block == 0p ) ) { // return list also empty? |
---|
| 995 | #endif // OWNERSHIP |
---|
| 996 | // Do not leave kernel thread as manager_extend accesses heapManager. |
---|
| 997 | disable_interrupts(); |
---|
| 998 | block = (Heap.Storage *)manager_extend( tsize ); // mutual exclusion on call |
---|
| 999 | enable_interrupts( false ); |
---|
| 1000 | |
---|
| 1001 | // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED. |
---|
| 1002 | |
---|
| 1003 | #ifdef __CFA_DEBUG__ |
---|
| 1004 | // Scrub new memory so subsequent uninitialized usages might fail. Only scrub the first 1024 bytes. |
---|
| 1005 | memset( block->data, SCRUB, min( SCRUB_SIZE, tsize - sizeof(Heap.Storage) ) ); |
---|
| 1006 | #endif // __CFA_DEBUG__ |
---|
[9c438546] | 1007 | #endif // BUCKETLOCK |
---|
[116a2ea] | 1008 | #ifdef OWNERSHIP |
---|
| 1009 | } else { // merge returnList into freeHead |
---|
| 1010 | #ifdef __STATISTICS__ |
---|
| 1011 | stats.return_pulls += 1; |
---|
| 1012 | #endif // __STATISTICS__ |
---|
[bcb14b5] | 1013 | |
---|
[116a2ea] | 1014 | // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED. |
---|
[c4f68dc] | 1015 | |
---|
[116a2ea] | 1016 | freeHead->freeList = block->header.kind.real.next; |
---|
| 1017 | } // if |
---|
| 1018 | #endif // OWNERSHIP |
---|
[c4f68dc] | 1019 | } else { |
---|
[116a2ea] | 1020 | // Memory is scrubbed in doFree. |
---|
| 1021 | freeHead->freeList = block->header.kind.real.next; |
---|
[c4f68dc] | 1022 | } // if |
---|
| 1023 | |
---|
[116a2ea] | 1024 | block->header.kind.real.home = freeHead; // pointer back to free list of apropriate size |
---|
[bcb14b5] | 1025 | } else { // large size => mmap |
---|
[ad2dced] | 1026 | if ( unlikely( size > ULONG_MAX - __page_size ) ) return 0p; |
---|
| 1027 | tsize = ceiling2( tsize, __page_size ); // must be multiple of page size |
---|
[c4f68dc] | 1028 | #ifdef __STATISTICS__ |
---|
[116a2ea] | 1029 | stats.counters[STAT_NAME].alloc += tsize; |
---|
| 1030 | stats.mmap_calls += 1; |
---|
| 1031 | stats.mmap_storage_request += size; |
---|
| 1032 | stats.mmap_storage_alloc += tsize; |
---|
[c4f68dc] | 1033 | #endif // __STATISTICS__ |
---|
[92aca37] | 1034 | |
---|
[116a2ea] | 1035 | disable_interrupts(); |
---|
| 1036 | block = (Heap.Storage *)mmap( 0, tsize, __map_prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 ); |
---|
| 1037 | enable_interrupts( false ); |
---|
| 1038 | |
---|
| 1039 | // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED. |
---|
| 1040 | |
---|
| 1041 | if ( unlikely( block == (Heap.Storage *)MAP_FAILED ) ) { // failed ? |
---|
[92aca37] | 1042 | if ( errno == ENOMEM ) abort( NO_MEMORY_MSG, tsize ); // no memory |
---|
[c4f68dc] | 1043 | // Do not call strerror( errno ) as it may call malloc. |
---|
[5951956] | 1044 | abort( "**** Error **** attempt to allocate large object (> %zu) of size %zu bytes and mmap failed with errno %d.", size, heapMaster.mmapStart, errno ); |
---|
[116a2ea] | 1045 | } // if |
---|
| 1046 | block->header.kind.real.blockSize = MarkMmappedBit( tsize ); // storage size for munmap |
---|
| 1047 | |
---|
[bcb14b5] | 1048 | #ifdef __CFA_DEBUG__ |
---|
[116a2ea] | 1049 | // Scrub new memory so subsequent uninitialized usages might fail. Only scrub the first 1024 bytes. The rest of |
---|
| 1050 | // the storage set to 0 by mmap. |
---|
| 1051 | memset( block->data, SCRUB, min( SCRUB_SIZE, tsize - sizeof(Heap.Storage) ) ); |
---|
[bcb14b5] | 1052 | #endif // __CFA_DEBUG__ |
---|
| 1053 | } // if |
---|
[c4f68dc] | 1054 | |
---|
[9c438546] | 1055 | block->header.kind.real.size = size; // store allocation size |
---|
[95eb7cf] | 1056 | void * addr = &(block->data); // adjust off header to user bytes |
---|
[c1f38e6c] | 1057 | verify( ((uintptr_t)addr & (libAlign() - 1)) == 0 ); // minimum alignment ? |
---|
[c4f68dc] | 1058 | |
---|
| 1059 | #ifdef __CFA_DEBUG__ |
---|
[bcb14b5] | 1060 | if ( traceHeap() ) { |
---|
[433905a] | 1061 | char helpText[64]; |
---|
| 1062 | __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText), |
---|
| 1063 | "%p = Malloc( %zu ) (allocated %zu)\n", addr, size, tsize ); // print debug/nodebug |
---|
[bcb14b5] | 1064 | } // if |
---|
[c4f68dc] | 1065 | #endif // __CFA_DEBUG__ |
---|
| 1066 | |
---|
[116a2ea] | 1067 | // poll_interrupts(); // call rollforward |
---|
| 1068 | |
---|
[95eb7cf] | 1069 | return addr; |
---|
[c4f68dc] | 1070 | } // doMalloc |
---|
| 1071 | |
---|
| 1072 | |
---|
[116a2ea] | 1073 | static void doFree( void * addr ) libcfa_nopreempt with( *heapManager ) { |
---|
| 1074 | verify( addr ); |
---|
| 1075 | |
---|
| 1076 | // detect free after thread-local storage destruction and use global stats in that case |
---|
[c4f68dc] | 1077 | |
---|
[31a5f418] | 1078 | Heap.Storage.Header * header; |
---|
[116a2ea] | 1079 | Heap.FreeHeader * freeHead; |
---|
| 1080 | size_t size, alignment; |
---|
| 1081 | |
---|
| 1082 | bool mapped = headers( "free", addr, header, freeHead, size, alignment ); |
---|
| 1083 | #if defined( __STATISTICS__ ) || defined( __CFA_DEBUG__ ) |
---|
| 1084 | size_t rsize = header->kind.real.size; // optimization |
---|
| 1085 | #endif // __STATISTICS__ || __CFA_DEBUG__ |
---|
| 1086 | |
---|
| 1087 | #ifdef __STATISTICS__ |
---|
| 1088 | stats.free_storage_request += rsize; |
---|
| 1089 | stats.free_storage_alloc += size; |
---|
| 1090 | #endif // __STATISTICS__ |
---|
| 1091 | |
---|
| 1092 | #ifdef __CFA_DEBUG__ |
---|
| 1093 | allocUnfreed -= rsize; |
---|
| 1094 | #endif // __CFA_DEBUG__ |
---|
[c4f68dc] | 1095 | |
---|
[116a2ea] | 1096 | if ( unlikely( mapped ) ) { // mmapped ? |
---|
[c4f68dc] | 1097 | #ifdef __STATISTICS__ |
---|
[116a2ea] | 1098 | stats.munmap_calls += 1; |
---|
| 1099 | stats.munmap_storage_request += rsize; |
---|
| 1100 | stats.munmap_storage_alloc += size; |
---|
[c4f68dc] | 1101 | #endif // __STATISTICS__ |
---|
[116a2ea] | 1102 | |
---|
| 1103 | // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED. |
---|
| 1104 | |
---|
| 1105 | // Does not matter where this storage is freed. |
---|
| 1106 | if ( unlikely( munmap( header, size ) == -1 ) ) { |
---|
| 1107 | // Do not call strerror( errno ) as it may call malloc. |
---|
[5951956] | 1108 | abort( "**** Error **** attempt to deallocate large object %p and munmap failed with errno %d.\n" |
---|
[116a2ea] | 1109 | "Possible cause is invalid delete pointer: either not allocated or with corrupt header.", |
---|
| 1110 | addr, errno ); |
---|
[c4f68dc] | 1111 | } // if |
---|
[bcb14b5] | 1112 | } else { |
---|
[c4f68dc] | 1113 | #ifdef __CFA_DEBUG__ |
---|
[116a2ea] | 1114 | // memset is NOT always inlined! |
---|
| 1115 | disable_interrupts(); |
---|
| 1116 | // Scrub old memory so subsequent usages might fail. Only scrub the first/last SCRUB_SIZE bytes. |
---|
| 1117 | char * data = ((Heap.Storage *)header)->data; // data address |
---|
| 1118 | size_t dsize = size - sizeof(Heap.Storage); // data size |
---|
| 1119 | if ( dsize <= SCRUB_SIZE * 2 ) { |
---|
| 1120 | memset( data, SCRUB, dsize ); // scrub all |
---|
| 1121 | } else { |
---|
| 1122 | memset( data, SCRUB, SCRUB_SIZE ); // scrub front |
---|
| 1123 | memset( data + dsize - SCRUB_SIZE, SCRUB, SCRUB_SIZE ); // scrub back |
---|
| 1124 | } // if |
---|
| 1125 | enable_interrupts( false ); |
---|
[c4f68dc] | 1126 | #endif // __CFA_DEBUG__ |
---|
| 1127 | |
---|
[116a2ea] | 1128 | if ( likely( heapManager == freeHead->homeManager ) ) { // belongs to this thread |
---|
| 1129 | header->kind.real.next = freeHead->freeList; // push on stack |
---|
| 1130 | freeHead->freeList = (Heap.Storage *)header; |
---|
| 1131 | } else { // return to thread owner |
---|
| 1132 | verify( heapManager ); |
---|
| 1133 | |
---|
| 1134 | #ifdef OWNERSHIP |
---|
| 1135 | #ifdef RETURNSPIN |
---|
| 1136 | lock( freeHead->returnLock ); |
---|
| 1137 | header->kind.real.next = freeHead->returnList; // push to bucket return list |
---|
| 1138 | freeHead->returnList = (Heap.Storage *)header; |
---|
| 1139 | unlock( freeHead->returnLock ); |
---|
| 1140 | #else // lock free |
---|
| 1141 | header->kind.real.next = freeHead->returnList; // link new node to top node |
---|
| 1142 | // CAS resets header->kind.real.next = freeHead->returnList on failure |
---|
| 1143 | while ( ! __atomic_compare_exchange_n( &freeHead->returnList, &header->kind.real.next, header, |
---|
| 1144 | false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ) ); |
---|
| 1145 | #endif // RETURNSPIN |
---|
| 1146 | |
---|
| 1147 | #else // no OWNERSHIP |
---|
| 1148 | |
---|
| 1149 | freeHead = &heap->freeLists[ClearStickyBits( header->kind.real.home ) - &freeHead->homeManager->freeLists[0]]; |
---|
| 1150 | header->kind.real.next = freeHead->freeList; // push on stack |
---|
| 1151 | freeHead->freeList = (Heap.Storage *)header; |
---|
| 1152 | #endif // ! OWNERSHIP |
---|
| 1153 | |
---|
| 1154 | #ifdef __U_STATISTICS__ |
---|
| 1155 | stats.return_pushes += 1; |
---|
| 1156 | stats.return_storage_request += rsize; |
---|
| 1157 | stats.return_storage_alloc += size; |
---|
| 1158 | #endif // __U_STATISTICS__ |
---|
| 1159 | |
---|
| 1160 | // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED. |
---|
| 1161 | } // if |
---|
[bcb14b5] | 1162 | } // if |
---|
[c4f68dc] | 1163 | |
---|
| 1164 | #ifdef __CFA_DEBUG__ |
---|
[bcb14b5] | 1165 | if ( traceHeap() ) { |
---|
[92aca37] | 1166 | char helpText[64]; |
---|
[433905a] | 1167 | __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText), |
---|
| 1168 | "Free( %p ) size:%zu\n", addr, size ); // print debug/nodebug |
---|
[bcb14b5] | 1169 | } // if |
---|
[c4f68dc] | 1170 | #endif // __CFA_DEBUG__ |
---|
[116a2ea] | 1171 | |
---|
| 1172 | // poll_interrupts(); // call rollforward |
---|
[c4f68dc] | 1173 | } // doFree |
---|
| 1174 | |
---|
| 1175 | |
---|
[116a2ea] | 1176 | size_t prtFree( Heap & manager ) with( manager ) { |
---|
[b6830d74] | 1177 | size_t total = 0; |
---|
[c4f68dc] | 1178 | #ifdef __STATISTICS__ |
---|
[95eb7cf] | 1179 | __cfaabi_bits_acquire(); |
---|
| 1180 | __cfaabi_bits_print_nolock( STDERR_FILENO, "\nBin lists (bin size : free blocks on list)\n" ); |
---|
[c4f68dc] | 1181 | #endif // __STATISTICS__ |
---|
[116a2ea] | 1182 | for ( unsigned int i = 0; i < heapMaster.maxBucketsUsed; i += 1 ) { |
---|
[d46ed6e] | 1183 | size_t size = freeLists[i].blockSize; |
---|
| 1184 | #ifdef __STATISTICS__ |
---|
| 1185 | unsigned int N = 0; |
---|
| 1186 | #endif // __STATISTICS__ |
---|
[b6830d74] | 1187 | |
---|
[9c438546] | 1188 | #if BUCKETLOCK == SPINLOCK |
---|
[31a5f418] | 1189 | for ( Heap.Storage * p = freeLists[i].freeList; p != 0p; p = p->header.kind.real.next ) { |
---|
[d46ed6e] | 1190 | #else |
---|
[b4aa1ab] | 1191 | for(;;) { |
---|
[31a5f418] | 1192 | // for ( Heap.Storage * p = top( freeLists[i].freeList ); p != 0p; p = (p)`next->top ) { |
---|
| 1193 | // for ( Heap.Storage * p = top( freeLists[i].freeList ); p != 0p; /* p = getNext( p )->top */) { |
---|
| 1194 | // Heap.Storage * temp = p->header.kind.real.next.top; // FIX ME: direct assignent fails, initialization works` |
---|
[7cfef0d] | 1195 | // typeof(p) temp = (( p )`next)->top; // FIX ME: direct assignent fails, initialization works` |
---|
| 1196 | // p = temp; |
---|
[9c438546] | 1197 | #endif // BUCKETLOCK |
---|
[d46ed6e] | 1198 | total += size; |
---|
| 1199 | #ifdef __STATISTICS__ |
---|
| 1200 | N += 1; |
---|
| 1201 | #endif // __STATISTICS__ |
---|
[b6830d74] | 1202 | } // for |
---|
| 1203 | |
---|
[d46ed6e] | 1204 | #ifdef __STATISTICS__ |
---|
[95eb7cf] | 1205 | __cfaabi_bits_print_nolock( STDERR_FILENO, "%7zu, %-7u ", size, N ); |
---|
| 1206 | if ( (i + 1) % 8 == 0 ) __cfaabi_bits_print_nolock( STDERR_FILENO, "\n" ); |
---|
[d46ed6e] | 1207 | #endif // __STATISTICS__ |
---|
| 1208 | } // for |
---|
| 1209 | #ifdef __STATISTICS__ |
---|
[95eb7cf] | 1210 | __cfaabi_bits_print_nolock( STDERR_FILENO, "\ntotal free blocks:%zu\n", total ); |
---|
| 1211 | __cfaabi_bits_release(); |
---|
[d46ed6e] | 1212 | #endif // __STATISTICS__ |
---|
[116a2ea] | 1213 | return (char *)heapMaster.heapEnd - (char *)heapMaster.heapBegin - total; |
---|
[95eb7cf] | 1214 | } // prtFree |
---|
| 1215 | |
---|
| 1216 | |
---|
[116a2ea] | 1217 | #ifdef __STATISTICS__ |
---|
[5951956] | 1218 | static void incCalls( intptr_t statName ) libcfa_nopreempt { |
---|
[116a2ea] | 1219 | heapManager->stats.counters[statName].calls += 1; |
---|
| 1220 | } // incCalls |
---|
[d5d3a90] | 1221 | |
---|
[5951956] | 1222 | static void incZeroCalls( intptr_t statName ) libcfa_nopreempt { |
---|
[116a2ea] | 1223 | heapManager->stats.counters[statName].calls_0 += 1; |
---|
| 1224 | } // incZeroCalls |
---|
| 1225 | #endif // __STATISTICS__ |
---|
[c4f68dc] | 1226 | |
---|
[116a2ea] | 1227 | #ifdef __CFA_DEBUG__ |
---|
[5951956] | 1228 | static void incUnfreed( intptr_t offset ) libcfa_nopreempt { |
---|
[116a2ea] | 1229 | heapManager->allocUnfreed += offset; |
---|
| 1230 | } // incUnfreed |
---|
| 1231 | #endif // __CFA_DEBUG__ |
---|
[c4f68dc] | 1232 | |
---|
[d5d3a90] | 1233 | |
---|
[116a2ea] | 1234 | static void * memalignNoStats( size_t alignment, size_t size STAT_PARM ) { |
---|
[b6830d74] | 1235 | checkAlign( alignment ); // check alignment |
---|
[c4f68dc] | 1236 | |
---|
[116a2ea] | 1237 | // if alignment <= default alignment or size == 0, do normal malloc as two headers are unnecessary |
---|
| 1238 | if ( unlikely( alignment <= libAlign() || size == 0 ) ) return doMalloc( size STAT_ARG( STAT_NAME ) ); |
---|
[b6830d74] | 1239 | |
---|
| 1240 | // Allocate enough storage to guarantee an address on the alignment boundary, and sufficient space before it for |
---|
| 1241 | // administrative storage. NOTE, WHILE THERE ARE 2 HEADERS, THE FIRST ONE IS IMPLICITLY CREATED BY DOMALLOC. |
---|
| 1242 | // .-------------v-----------------v----------------v----------, |
---|
| 1243 | // | Real Header | ... padding ... | Fake Header | data ... | |
---|
| 1244 | // `-------------^-----------------^-+--------------^----------' |
---|
| 1245 | // |<--------------------------------' offset/align |<-- alignment boundary |
---|
| 1246 | |
---|
| 1247 | // subtract libAlign() because it is already the minimum alignment |
---|
| 1248 | // add sizeof(Storage) for fake header |
---|
[116a2ea] | 1249 | size_t offset = alignment - libAlign() + sizeof(Heap.Storage); |
---|
| 1250 | char * addr = (char *)doMalloc( size + offset STAT_ARG( STAT_NAME ) ); |
---|
[b6830d74] | 1251 | |
---|
| 1252 | // address in the block of the "next" alignment address |
---|
[31a5f418] | 1253 | char * user = (char *)ceiling2( (uintptr_t)(addr + sizeof(Heap.Storage)), alignment ); |
---|
[b6830d74] | 1254 | |
---|
| 1255 | // address of header from malloc |
---|
[116a2ea] | 1256 | Heap.Storage.Header * realHeader = HeaderAddr( addr ); |
---|
| 1257 | realHeader->kind.real.size = size; // correct size to eliminate above alignment offset |
---|
| 1258 | #ifdef __CFA_DEBUG__ |
---|
| 1259 | incUnfreed( -offset ); // adjustment off the offset from call to doMalloc |
---|
| 1260 | #endif // __CFA_DEBUG__ |
---|
| 1261 | |
---|
| 1262 | // address of fake header *before* the alignment location |
---|
[19e5d65d] | 1263 | Heap.Storage.Header * fakeHeader = HeaderAddr( user ); |
---|
[116a2ea] | 1264 | |
---|
[b6830d74] | 1265 | // SKULLDUGGERY: insert the offset to the start of the actual storage block and remember alignment |
---|
[116a2ea] | 1266 | fakeHeader->kind.fake.offset = (char *)fakeHeader - (char *)realHeader; |
---|
[69ec0fb] | 1267 | // SKULLDUGGERY: odd alignment implies fake header |
---|
[19e5d65d] | 1268 | fakeHeader->kind.fake.alignment = MarkAlignmentBit( alignment ); |
---|
[b6830d74] | 1269 | |
---|
| 1270 | return user; |
---|
[bcb14b5] | 1271 | } // memalignNoStats |
---|
[c4f68dc] | 1272 | |
---|
| 1273 | |
---|
[19e5d65d] | 1274 | //####################### Memory Allocation Routines #################### |
---|
| 1275 | |
---|
| 1276 | |
---|
[c4f68dc] | 1277 | extern "C" { |
---|
[61248a4] | 1278 | // Allocates size bytes and returns a pointer to the allocated memory. The contents are undefined. If size is 0, |
---|
| 1279 | // then malloc() returns a unique pointer value that can later be successfully passed to free(). |
---|
[032234bd] | 1280 | void * malloc( size_t size ) libcfa_public { |
---|
[116a2ea] | 1281 | return doMalloc( size STAT_ARG( MALLOC ) ); |
---|
[bcb14b5] | 1282 | } // malloc |
---|
[c4f68dc] | 1283 | |
---|
[76e2113] | 1284 | |
---|
[61248a4] | 1285 | // Same as malloc() except size bytes is an array of dim elements each of elemSize bytes. |
---|
[032234bd] | 1286 | void * aalloc( size_t dim, size_t elemSize ) libcfa_public { |
---|
[116a2ea] | 1287 | return doMalloc( dim * elemSize STAT_ARG( AALLOC ) ); |
---|
[76e2113] | 1288 | } // aalloc |
---|
| 1289 | |
---|
| 1290 | |
---|
[61248a4] | 1291 | // Same as aalloc() with memory set to zero. |
---|
[032234bd] | 1292 | void * calloc( size_t dim, size_t elemSize ) libcfa_public { |
---|
[709b812] | 1293 | size_t size = dim * elemSize; |
---|
[116a2ea] | 1294 | char * addr = (char *)doMalloc( size STAT_ARG( CALLOC ) ); |
---|
[c4f68dc] | 1295 | |
---|
[116a2ea] | 1296 | if ( unlikely( addr == NULL ) ) return NULL; // stop further processing if 0p is returned |
---|
[709b812] | 1297 | |
---|
[31a5f418] | 1298 | Heap.Storage.Header * header; |
---|
[116a2ea] | 1299 | Heap.FreeHeader * freeHead; |
---|
[709b812] | 1300 | size_t bsize, alignment; |
---|
| 1301 | |
---|
| 1302 | #ifndef __CFA_DEBUG__ |
---|
| 1303 | bool mapped = |
---|
| 1304 | #endif // __CFA_DEBUG__ |
---|
[116a2ea] | 1305 | headers( "calloc", addr, header, freeHead, bsize, alignment ); |
---|
[709b812] | 1306 | |
---|
| 1307 | #ifndef __CFA_DEBUG__ |
---|
| 1308 | // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero. |
---|
[116a2ea] | 1309 | if ( likely( ! mapped ) ) |
---|
[709b812] | 1310 | #endif // __CFA_DEBUG__ |
---|
| 1311 | // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined |
---|
| 1312 | // `-header`-addr `-size |
---|
| 1313 | memset( addr, '\0', size ); // set to zeros |
---|
| 1314 | |
---|
[19e5d65d] | 1315 | MarkZeroFilledBit( header ); // mark as zero fill |
---|
[709b812] | 1316 | return addr; |
---|
[bcb14b5] | 1317 | } // calloc |
---|
[c4f68dc] | 1318 | |
---|
[92aca37] | 1319 | |
---|
[61248a4] | 1320 | // Change the size of the memory block pointed to by oaddr to size bytes. The contents are undefined. If oaddr is |
---|
| 1321 | // 0p, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and oaddr is |
---|
| 1322 | // not 0p, then the call is equivalent to free(oaddr). Unless oaddr is 0p, it must have been returned by an earlier |
---|
| 1323 | // call to malloc(), alloc(), calloc() or realloc(). If the area pointed to was moved, a free(oaddr) is done. |
---|
[032234bd] | 1324 | void * resize( void * oaddr, size_t size ) libcfa_public { |
---|
[116a2ea] | 1325 | if ( unlikely( oaddr == 0p ) ) { // => malloc( size ) |
---|
| 1326 | return doMalloc( size STAT_ARG( RESIZE ) ); |
---|
[709b812] | 1327 | } // if |
---|
[cfbc703d] | 1328 | |
---|
[116a2ea] | 1329 | PROLOG( RESIZE, doFree( oaddr ) ); // => free( oaddr ) |
---|
[cfbc703d] | 1330 | |
---|
[31a5f418] | 1331 | Heap.Storage.Header * header; |
---|
[116a2ea] | 1332 | Heap.FreeHeader * freeHead; |
---|
[92aca37] | 1333 | size_t bsize, oalign; |
---|
[116a2ea] | 1334 | headers( "resize", oaddr, header, freeHead, bsize, oalign ); |
---|
[92847f7] | 1335 | |
---|
[19e5d65d] | 1336 | size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket |
---|
[cfbc703d] | 1337 | // same size, DO NOT preserve STICKY PROPERTIES. |
---|
[92847f7] | 1338 | if ( oalign == libAlign() && size <= odsize && odsize <= size * 2 ) { // allow 50% wasted storage for smaller size |
---|
[19e5d65d] | 1339 | ClearZeroFillBit( header ); // no alignment and turn off 0 fill |
---|
[116a2ea] | 1340 | #ifdef __CFA_DEBUG__ |
---|
| 1341 | incUnfreed( size - header->kind.real.size ); // adjustment off the size difference |
---|
| 1342 | #endif // __CFA_DEBUG__ |
---|
[d5d3a90] | 1343 | header->kind.real.size = size; // reset allocation size |
---|
[116a2ea] | 1344 | #ifdef __STATISTICS__ |
---|
| 1345 | incCalls( RESIZE ); |
---|
| 1346 | #endif // __STATISTICS__ |
---|
[cfbc703d] | 1347 | return oaddr; |
---|
| 1348 | } // if |
---|
[0f89d4f] | 1349 | |
---|
[cfbc703d] | 1350 | // change size, DO NOT preserve STICKY PROPERTIES. |
---|
[116a2ea] | 1351 | doFree( oaddr ); // free previous storage |
---|
| 1352 | |
---|
| 1353 | return doMalloc( size STAT_ARG( RESIZE ) ); // create new area |
---|
[cfbc703d] | 1354 | } // resize |
---|
| 1355 | |
---|
| 1356 | |
---|
[61248a4] | 1357 | // Same as resize() but the contents are unchanged in the range from the start of the region up to the minimum of |
---|
[cfbc703d] | 1358 | // the old and new sizes. |
---|
[032234bd] | 1359 | void * realloc( void * oaddr, size_t size ) libcfa_public { |
---|
[116a2ea] | 1360 | if ( unlikely( oaddr == 0p ) ) { // => malloc( size ) |
---|
| 1361 | return doMalloc( size STAT_ARG( REALLOC ) ); |
---|
[709b812] | 1362 | } // if |
---|
[c4f68dc] | 1363 | |
---|
[116a2ea] | 1364 | PROLOG( REALLOC, doFree( oaddr ) ); // => free( oaddr ) |
---|
[c4f68dc] | 1365 | |
---|
[31a5f418] | 1366 | Heap.Storage.Header * header; |
---|
[116a2ea] | 1367 | Heap.FreeHeader * freeHead; |
---|
[92aca37] | 1368 | size_t bsize, oalign; |
---|
[116a2ea] | 1369 | headers( "realloc", oaddr, header, freeHead, bsize, oalign ); |
---|
[95eb7cf] | 1370 | |
---|
[19e5d65d] | 1371 | size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket |
---|
[d5d3a90] | 1372 | size_t osize = header->kind.real.size; // old allocation size |
---|
[19e5d65d] | 1373 | bool ozfill = ZeroFillBit( header ); // old allocation zero filled |
---|
[92847f7] | 1374 | if ( unlikely( size <= odsize ) && odsize <= size * 2 ) { // allow up to 50% wasted storage |
---|
[116a2ea] | 1375 | #ifdef __CFA_DEBUG__ |
---|
| 1376 | incUnfreed( size - header->kind.real.size ); // adjustment off the size difference |
---|
| 1377 | #endif // __CFA_DEBUG__ |
---|
| 1378 | header->kind.real.size = size; // reset allocation size |
---|
[d5d3a90] | 1379 | if ( unlikely( ozfill ) && size > osize ) { // previous request zero fill and larger ? |
---|
[e4b6b7d3] | 1380 | memset( (char *)oaddr + osize, '\0', size - osize ); // initialize added storage |
---|
[d5d3a90] | 1381 | } // if |
---|
[116a2ea] | 1382 | #ifdef __STATISTICS__ |
---|
| 1383 | incCalls( REALLOC ); |
---|
| 1384 | #endif // __STATISTICS__ |
---|
[95eb7cf] | 1385 | return oaddr; |
---|
[c4f68dc] | 1386 | } // if |
---|
| 1387 | |
---|
[95eb7cf] | 1388 | // change size and copy old content to new storage |
---|
| 1389 | |
---|
| 1390 | void * naddr; |
---|
[116a2ea] | 1391 | if ( likely( oalign <= libAlign() ) ) { // previous request not aligned ? |
---|
| 1392 | naddr = doMalloc( size STAT_ARG( REALLOC ) ); // create new area |
---|
[c4f68dc] | 1393 | } else { |
---|
[116a2ea] | 1394 | naddr = memalignNoStats( oalign, size STAT_ARG( REALLOC ) ); // create new aligned area |
---|
[c4f68dc] | 1395 | } // if |
---|
[1e034d9] | 1396 | |
---|
[116a2ea] | 1397 | headers( "realloc", naddr, header, freeHead, bsize, oalign ); |
---|
| 1398 | // To preserve prior fill, the entire bucket must be copied versus the size. |
---|
[47dd0d2] | 1399 | memcpy( naddr, oaddr, min( osize, size ) ); // copy bytes |
---|
[116a2ea] | 1400 | doFree( oaddr ); // free previous storage |
---|
[d5d3a90] | 1401 | |
---|
| 1402 | if ( unlikely( ozfill ) ) { // previous request zero fill ? |
---|
[19e5d65d] | 1403 | MarkZeroFilledBit( header ); // mark new request as zero filled |
---|
[d5d3a90] | 1404 | if ( size > osize ) { // previous request larger ? |
---|
[e4b6b7d3] | 1405 | memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage |
---|
[d5d3a90] | 1406 | } // if |
---|
| 1407 | } // if |
---|
[95eb7cf] | 1408 | return naddr; |
---|
[b6830d74] | 1409 | } // realloc |
---|
[c4f68dc] | 1410 | |
---|
[c1f38e6c] | 1411 | |
---|
[19e5d65d] | 1412 | // Same as realloc() except the new allocation size is large enough for an array of nelem elements of size elsize. |
---|
[032234bd] | 1413 | void * reallocarray( void * oaddr, size_t dim, size_t elemSize ) libcfa_public { |
---|
[19e5d65d] | 1414 | return realloc( oaddr, dim * elemSize ); |
---|
| 1415 | } // reallocarray |
---|
| 1416 | |
---|
| 1417 | |
---|
[61248a4] | 1418 | // Same as malloc() except the memory address is a multiple of alignment, which must be a power of two. (obsolete) |
---|
[032234bd] | 1419 | void * memalign( size_t alignment, size_t size ) libcfa_public { |
---|
[116a2ea] | 1420 | return memalignNoStats( alignment, size STAT_ARG( MEMALIGN ) ); |
---|
[bcb14b5] | 1421 | } // memalign |
---|
[c4f68dc] | 1422 | |
---|
[95eb7cf] | 1423 | |
---|
[76e2113] | 1424 | // Same as aalloc() with memory alignment. |
---|
[032234bd] | 1425 | void * amemalign( size_t alignment, size_t dim, size_t elemSize ) libcfa_public { |
---|
[116a2ea] | 1426 | return memalignNoStats( alignment, dim * elemSize STAT_ARG( AMEMALIGN ) ); |
---|
[76e2113] | 1427 | } // amemalign |
---|
| 1428 | |
---|
| 1429 | |
---|
[ca7949b] | 1430 | // Same as calloc() with memory alignment. |
---|
[032234bd] | 1431 | void * cmemalign( size_t alignment, size_t dim, size_t elemSize ) libcfa_public { |
---|
[709b812] | 1432 | size_t size = dim * elemSize; |
---|
[116a2ea] | 1433 | char * addr = (char *)memalignNoStats( alignment, size STAT_ARG( CMEMALIGN ) ); |
---|
[95eb7cf] | 1434 | |
---|
[116a2ea] | 1435 | if ( unlikely( addr == NULL ) ) return NULL; // stop further processing if 0p is returned |
---|
[709b812] | 1436 | |
---|
[31a5f418] | 1437 | Heap.Storage.Header * header; |
---|
[116a2ea] | 1438 | Heap.FreeHeader * freeHead; |
---|
[709b812] | 1439 | size_t bsize; |
---|
| 1440 | |
---|
| 1441 | #ifndef __CFA_DEBUG__ |
---|
| 1442 | bool mapped = |
---|
| 1443 | #endif // __CFA_DEBUG__ |
---|
[116a2ea] | 1444 | headers( "cmemalign", addr, header, freeHead, bsize, alignment ); |
---|
[709b812] | 1445 | |
---|
| 1446 | // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero. |
---|
| 1447 | #ifndef __CFA_DEBUG__ |
---|
| 1448 | if ( ! mapped ) |
---|
| 1449 | #endif // __CFA_DEBUG__ |
---|
| 1450 | // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined |
---|
| 1451 | // `-header`-addr `-size |
---|
| 1452 | memset( addr, '\0', size ); // set to zeros |
---|
| 1453 | |
---|
[19e5d65d] | 1454 | MarkZeroFilledBit( header ); // mark as zero filled |
---|
[709b812] | 1455 | return addr; |
---|
[95eb7cf] | 1456 | } // cmemalign |
---|
| 1457 | |
---|
[13fece5] | 1458 | |
---|
[ca7949b] | 1459 | // Same as memalign(), but ISO/IEC 2011 C11 Section 7.22.2 states: the value of size shall be an integral multiple |
---|
[19e5d65d] | 1460 | // of alignment. This requirement is universally ignored. |
---|
[032234bd] | 1461 | void * aligned_alloc( size_t alignment, size_t size ) libcfa_public { |
---|
[c4f68dc] | 1462 | return memalign( alignment, size ); |
---|
[b6830d74] | 1463 | } // aligned_alloc |
---|
[c4f68dc] | 1464 | |
---|
| 1465 | |
---|
[ca7949b] | 1466 | // Allocates size bytes and places the address of the allocated memory in *memptr. The address of the allocated |
---|
| 1467 | // memory shall be a multiple of alignment, which must be a power of two and a multiple of sizeof(void *). If size |
---|
| 1468 | // is 0, then posix_memalign() returns either 0p, or a unique pointer value that can later be successfully passed to |
---|
| 1469 | // free(3). |
---|
[032234bd] | 1470 | int posix_memalign( void ** memptr, size_t alignment, size_t size ) libcfa_public { |
---|
[69ec0fb] | 1471 | if ( unlikely( alignment < libAlign() || ! is_pow2( alignment ) ) ) return EINVAL; // check alignment |
---|
[19e5d65d] | 1472 | *memptr = memalign( alignment, size ); |
---|
[c4f68dc] | 1473 | return 0; |
---|
[b6830d74] | 1474 | } // posix_memalign |
---|
[c4f68dc] | 1475 | |
---|
[13fece5] | 1476 | |
---|
[ca7949b] | 1477 | // Allocates size bytes and returns a pointer to the allocated memory. The memory address shall be a multiple of the |
---|
| 1478 | // page size. It is equivalent to memalign(sysconf(_SC_PAGESIZE),size). |
---|
[032234bd] | 1479 | void * valloc( size_t size ) libcfa_public { |
---|
[ad2dced] | 1480 | return memalign( __page_size, size ); |
---|
[b6830d74] | 1481 | } // valloc |
---|
[c4f68dc] | 1482 | |
---|
| 1483 | |
---|
[ca7949b] | 1484 | // Same as valloc but rounds size to multiple of page size. |
---|
[032234bd] | 1485 | void * pvalloc( size_t size ) libcfa_public { |
---|
[19e5d65d] | 1486 | return memalign( __page_size, ceiling2( size, __page_size ) ); // round size to multiple of page size |
---|
[ca7949b] | 1487 | } // pvalloc |
---|
| 1488 | |
---|
| 1489 | |
---|
| 1490 | // Frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() |
---|
[1076d05] | 1491 | // or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is |
---|
[ca7949b] | 1492 | // 0p, no operation is performed. |
---|
[032234bd] | 1493 | void free( void * addr ) libcfa_public { |
---|
[116a2ea] | 1494 | // verify( heapManager ); |
---|
| 1495 | |
---|
[95eb7cf] | 1496 | if ( unlikely( addr == 0p ) ) { // special case |
---|
[709b812] | 1497 | #ifdef __STATISTICS__ |
---|
[116a2ea] | 1498 | if ( heapManager ) |
---|
| 1499 | incZeroCalls( FREE ); |
---|
[709b812] | 1500 | #endif // __STATISTICS__ |
---|
[c4f68dc] | 1501 | return; |
---|
[116a2ea] | 1502 | } // if |
---|
| 1503 | |
---|
| 1504 | #ifdef __STATISTICS__ |
---|
| 1505 | incCalls( FREE ); |
---|
| 1506 | #endif // __STATISTICS__ |
---|
[c4f68dc] | 1507 | |
---|
[116a2ea] | 1508 | doFree( addr ); // handles heapManager == nullptr |
---|
[b6830d74] | 1509 | } // free |
---|
[93c2e0a] | 1510 | |
---|
[c4f68dc] | 1511 | |
---|
[76e2113] | 1512 | // Returns the alignment of an allocation. |
---|
[032234bd] | 1513 | size_t malloc_alignment( void * addr ) libcfa_public { |
---|
[95eb7cf] | 1514 | if ( unlikely( addr == 0p ) ) return libAlign(); // minimum alignment |
---|
[19e5d65d] | 1515 | Heap.Storage.Header * header = HeaderAddr( addr ); |
---|
| 1516 | if ( unlikely( AlignmentBit( header ) ) ) { // fake header ? |
---|
| 1517 | return ClearAlignmentBit( header ); // clear flag from value |
---|
[c4f68dc] | 1518 | } else { |
---|
[cfbc703d] | 1519 | return libAlign(); // minimum alignment |
---|
[c4f68dc] | 1520 | } // if |
---|
[bcb14b5] | 1521 | } // malloc_alignment |
---|
[c4f68dc] | 1522 | |
---|
[92aca37] | 1523 | |
---|
[76e2113] | 1524 | // Returns true if the allocation is zero filled, e.g., allocated by calloc(). |
---|
[032234bd] | 1525 | bool malloc_zero_fill( void * addr ) libcfa_public { |
---|
[95eb7cf] | 1526 | if ( unlikely( addr == 0p ) ) return false; // null allocation is not zero fill |
---|
[19e5d65d] | 1527 | Heap.Storage.Header * header = HeaderAddr( addr ); |
---|
| 1528 | if ( unlikely( AlignmentBit( header ) ) ) { // fake header ? |
---|
| 1529 | header = RealHeader( header ); // backup from fake to real header |
---|
[c4f68dc] | 1530 | } // if |
---|
[19e5d65d] | 1531 | return ZeroFillBit( header ); // zero filled ? |
---|
[bcb14b5] | 1532 | } // malloc_zero_fill |
---|
[c4f68dc] | 1533 | |
---|
[19e5d65d] | 1534 | |
---|
| 1535 | // Returns original total allocation size (not bucket size) => array size is dimension * sizeof(T). |
---|
[032234bd] | 1536 | size_t malloc_size( void * addr ) libcfa_public { |
---|
[849fb370] | 1537 | if ( unlikely( addr == 0p ) ) return 0; // null allocation has zero size |
---|
[19e5d65d] | 1538 | Heap.Storage.Header * header = HeaderAddr( addr ); |
---|
| 1539 | if ( unlikely( AlignmentBit( header ) ) ) { // fake header ? |
---|
| 1540 | header = RealHeader( header ); // backup from fake to real header |
---|
[cfbc703d] | 1541 | } // if |
---|
[9c438546] | 1542 | return header->kind.real.size; |
---|
[76e2113] | 1543 | } // malloc_size |
---|
| 1544 | |
---|
[cfbc703d] | 1545 | |
---|
[ca7949b] | 1546 | // Returns the number of usable bytes in the block pointed to by ptr, a pointer to a block of memory allocated by |
---|
| 1547 | // malloc or a related function. |
---|
[032234bd] | 1548 | size_t malloc_usable_size( void * addr ) libcfa_public { |
---|
[95eb7cf] | 1549 | if ( unlikely( addr == 0p ) ) return 0; // null allocation has 0 size |
---|
[31a5f418] | 1550 | Heap.Storage.Header * header; |
---|
[116a2ea] | 1551 | Heap.FreeHeader * freeHead; |
---|
[95eb7cf] | 1552 | size_t bsize, alignment; |
---|
| 1553 | |
---|
[116a2ea] | 1554 | headers( "malloc_usable_size", addr, header, freeHead, bsize, alignment ); |
---|
[19e5d65d] | 1555 | return DataStorage( bsize, addr, header ); // data storage in bucket |
---|
[95eb7cf] | 1556 | } // malloc_usable_size |
---|
| 1557 | |
---|
| 1558 | |
---|
[ca7949b] | 1559 | // Prints (on default standard error) statistics about memory allocated by malloc and related functions. |
---|
[032234bd] | 1560 | void malloc_stats( void ) libcfa_public { |
---|
[c4f68dc] | 1561 | #ifdef __STATISTICS__ |
---|
[116a2ea] | 1562 | HeapStatistics stats; |
---|
| 1563 | HeapStatisticsCtor( stats ); |
---|
| 1564 | if ( printStats( collectStats( stats ) ) == -1 ) { |
---|
| 1565 | #else |
---|
| 1566 | #define MALLOC_STATS_MSG "malloc_stats statistics disabled.\n" |
---|
| 1567 | if ( write( STDERR_FILENO, MALLOC_STATS_MSG, sizeof( MALLOC_STATS_MSG ) - 1 /* size includes '\0' */ ) == -1 ) { |
---|
[c4f68dc] | 1568 | #endif // __STATISTICS__ |
---|
[5951956] | 1569 | abort( "**** Error **** write failed in malloc_stats" ); |
---|
[116a2ea] | 1570 | } // if |
---|
[bcb14b5] | 1571 | } // malloc_stats |
---|
[c4f68dc] | 1572 | |
---|
[92aca37] | 1573 | |
---|
[19e5d65d] | 1574 | // Changes the file descriptor where malloc_stats() writes statistics. |
---|
[032234bd] | 1575 | int malloc_stats_fd( int fd __attribute__(( unused )) ) libcfa_public { |
---|
[c4f68dc] | 1576 | #ifdef __STATISTICS__ |
---|
[116a2ea] | 1577 | int temp = heapMaster.stats_fd; |
---|
| 1578 | heapMaster.stats_fd = fd; |
---|
[bcb14b5] | 1579 | return temp; |
---|
[c4f68dc] | 1580 | #else |
---|
[19e5d65d] | 1581 | return -1; // unsupported |
---|
[c4f68dc] | 1582 | #endif // __STATISTICS__ |
---|
[bcb14b5] | 1583 | } // malloc_stats_fd |
---|
[c4f68dc] | 1584 | |
---|
[95eb7cf] | 1585 | |
---|
[19e5d65d] | 1586 | // Prints an XML string that describes the current state of the memory-allocation implementation in the caller. |
---|
| 1587 | // The string is printed on the file stream stream. The exported string includes information about all arenas (see |
---|
| 1588 | // malloc). |
---|
[032234bd] | 1589 | int malloc_info( int options, FILE * stream __attribute__(( unused )) ) libcfa_public { |
---|
[19e5d65d] | 1590 | if ( options != 0 ) { errno = EINVAL; return -1; } |
---|
| 1591 | #ifdef __STATISTICS__ |
---|
[116a2ea] | 1592 | HeapStatistics stats; |
---|
| 1593 | HeapStatisticsCtor( stats ); |
---|
| 1594 | return printStatsXML( collectStats( stats ), stream ); // returns bytes written or -1 |
---|
[19e5d65d] | 1595 | #else |
---|
| 1596 | return 0; // unsupported |
---|
| 1597 | #endif // __STATISTICS__ |
---|
| 1598 | } // malloc_info |
---|
| 1599 | |
---|
| 1600 | |
---|
[1076d05] | 1601 | // Adjusts parameters that control the behaviour of the memory-allocation functions (see malloc). The param argument |
---|
[ca7949b] | 1602 | // specifies the parameter to be modified, and value specifies the new value for that parameter. |
---|
[032234bd] | 1603 | int mallopt( int option, int value ) libcfa_public { |
---|
[19e5d65d] | 1604 | if ( value < 0 ) return 0; |
---|
[95eb7cf] | 1605 | choose( option ) { |
---|
| 1606 | case M_TOP_PAD: |
---|
[116a2ea] | 1607 | heapMaster.heapExpand = ceiling2( value, __page_size ); |
---|
[19e5d65d] | 1608 | return 1; |
---|
[95eb7cf] | 1609 | case M_MMAP_THRESHOLD: |
---|
| 1610 | if ( setMmapStart( value ) ) return 1; |
---|
[19e5d65d] | 1611 | } // choose |
---|
[95eb7cf] | 1612 | return 0; // error, unsupported |
---|
| 1613 | } // mallopt |
---|
| 1614 | |
---|
[c1f38e6c] | 1615 | |
---|
[ca7949b] | 1616 | // Attempt to release free memory at the top of the heap (by calling sbrk with a suitable argument). |
---|
[032234bd] | 1617 | int malloc_trim( size_t ) libcfa_public { |
---|
[95eb7cf] | 1618 | return 0; // => impossible to release memory |
---|
| 1619 | } // malloc_trim |
---|
| 1620 | |
---|
| 1621 | |
---|
[ca7949b] | 1622 | // Records the current state of all malloc internal bookkeeping variables (but not the actual contents of the heap |
---|
| 1623 | // or the state of malloc_hook functions pointers). The state is recorded in a system-dependent opaque data |
---|
| 1624 | // structure dynamically allocated via malloc, and a pointer to that data structure is returned as the function |
---|
| 1625 | // result. (The caller must free this memory.) |
---|
[032234bd] | 1626 | void * malloc_get_state( void ) libcfa_public { |
---|
[95eb7cf] | 1627 | return 0p; // unsupported |
---|
[c4f68dc] | 1628 | } // malloc_get_state |
---|
| 1629 | |
---|
[bcb14b5] | 1630 | |
---|
[ca7949b] | 1631 | // Restores the state of all malloc internal bookkeeping variables to the values recorded in the opaque data |
---|
| 1632 | // structure pointed to by state. |
---|
[032234bd] | 1633 | int malloc_set_state( void * ) libcfa_public { |
---|
[bcb14b5] | 1634 | return 0; // unsupported |
---|
[c4f68dc] | 1635 | } // malloc_set_state |
---|
[31a5f418] | 1636 | |
---|
[19e5d65d] | 1637 | |
---|
[31a5f418] | 1638 | // Sets the amount (bytes) to extend the heap when there is insufficent free storage to service an allocation. |
---|
[032234bd] | 1639 | __attribute__((weak)) size_t malloc_expansion() libcfa_public { return __CFA_DEFAULT_HEAP_EXPANSION__; } |
---|
[31a5f418] | 1640 | |
---|
| 1641 | // Sets the crossover point between allocations occuring in the sbrk area or separately mmapped. |
---|
[032234bd] | 1642 | __attribute__((weak)) size_t malloc_mmap_start() libcfa_public { return __CFA_DEFAULT_MMAP_START__; } |
---|
[31a5f418] | 1643 | |
---|
| 1644 | // Amount subtracted to adjust for unfreed program storage (debug only). |
---|
[032234bd] | 1645 | __attribute__((weak)) size_t malloc_unfreed() libcfa_public { return __CFA_DEFAULT_HEAP_UNFREED__; } |
---|
[c4f68dc] | 1646 | } // extern "C" |
---|
| 1647 | |
---|
| 1648 | |
---|
[95eb7cf] | 1649 | // Must have CFA linkage to overload with C linkage realloc. |
---|
[032234bd] | 1650 | void * resize( void * oaddr, size_t nalign, size_t size ) libcfa_public { |
---|
[116a2ea] | 1651 | if ( unlikely( oaddr == 0p ) ) { // => malloc( size ) |
---|
| 1652 | return memalignNoStats( nalign, size STAT_ARG( RESIZE ) ); |
---|
[709b812] | 1653 | } // if |
---|
[95eb7cf] | 1654 | |
---|
[116a2ea] | 1655 | PROLOG( RESIZE, doFree( oaddr ) ); // => free( oaddr ) |
---|
[cfbc703d] | 1656 | |
---|
[92847f7] | 1657 | // Attempt to reuse existing alignment. |
---|
[19e5d65d] | 1658 | Heap.Storage.Header * header = HeaderAddr( oaddr ); |
---|
| 1659 | bool isFakeHeader = AlignmentBit( header ); // old fake header ? |
---|
[92847f7] | 1660 | size_t oalign; |
---|
[19e5d65d] | 1661 | |
---|
| 1662 | if ( unlikely( isFakeHeader ) ) { |
---|
[116a2ea] | 1663 | checkAlign( nalign ); // check alignment |
---|
[19e5d65d] | 1664 | oalign = ClearAlignmentBit( header ); // old alignment |
---|
| 1665 | if ( unlikely( (uintptr_t)oaddr % nalign == 0 // lucky match ? |
---|
[92847f7] | 1666 | && ( oalign <= nalign // going down |
---|
| 1667 | || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ? |
---|
[19e5d65d] | 1668 | ) ) { |
---|
| 1669 | HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same) |
---|
[116a2ea] | 1670 | Heap.FreeHeader * freeHead; |
---|
[92847f7] | 1671 | size_t bsize, oalign; |
---|
[116a2ea] | 1672 | headers( "resize", oaddr, header, freeHead, bsize, oalign ); |
---|
[19e5d65d] | 1673 | size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket |
---|
[a3ade94] | 1674 | |
---|
[92847f7] | 1675 | if ( size <= odsize && odsize <= size * 2 ) { // allow 50% wasted data storage |
---|
[19e5d65d] | 1676 | HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same) |
---|
| 1677 | ClearZeroFillBit( header ); // turn off 0 fill |
---|
[116a2ea] | 1678 | #ifdef __CFA_DEBUG__ |
---|
| 1679 | incUnfreed( size - header->kind.real.size ); // adjustment off the size difference |
---|
| 1680 | #endif // __CFA_DEBUG__ |
---|
[92847f7] | 1681 | header->kind.real.size = size; // reset allocation size |
---|
[116a2ea] | 1682 | #ifdef __STATISTICS__ |
---|
| 1683 | incCalls( RESIZE ); |
---|
| 1684 | #endif // __STATISTICS__ |
---|
[92847f7] | 1685 | return oaddr; |
---|
| 1686 | } // if |
---|
[cfbc703d] | 1687 | } // if |
---|
[92847f7] | 1688 | } else if ( ! isFakeHeader // old real header (aligned on libAlign) ? |
---|
| 1689 | && nalign == libAlign() ) { // new alignment also on libAlign => no fake header needed |
---|
[113d785] | 1690 | return resize( oaddr, size ); // duplicate special case checks |
---|
[cfbc703d] | 1691 | } // if |
---|
| 1692 | |
---|
[dd23e66] | 1693 | // change size, DO NOT preserve STICKY PROPERTIES. |
---|
[116a2ea] | 1694 | doFree( oaddr ); // free previous storage |
---|
| 1695 | return memalignNoStats( nalign, size STAT_ARG( RESIZE ) ); // create new aligned area |
---|
[cfbc703d] | 1696 | } // resize |
---|
| 1697 | |
---|
| 1698 | |
---|
[032234bd] | 1699 | void * realloc( void * oaddr, size_t nalign, size_t size ) libcfa_public { |
---|
[116a2ea] | 1700 | if ( unlikely( oaddr == 0p ) ) { // => malloc( size ) |
---|
| 1701 | return memalignNoStats( nalign, size STAT_ARG( REALLOC ) ); |
---|
[709b812] | 1702 | } // if |
---|
| 1703 | |
---|
[116a2ea] | 1704 | PROLOG( REALLOC, doFree( oaddr ) ); // => free( oaddr ) |
---|
[c86f587] | 1705 | |
---|
[92847f7] | 1706 | // Attempt to reuse existing alignment. |
---|
[19e5d65d] | 1707 | Heap.Storage.Header * header = HeaderAddr( oaddr ); |
---|
| 1708 | bool isFakeHeader = AlignmentBit( header ); // old fake header ? |
---|
[92847f7] | 1709 | size_t oalign; |
---|
[19e5d65d] | 1710 | if ( unlikely( isFakeHeader ) ) { |
---|
[116a2ea] | 1711 | checkAlign( nalign ); // check alignment |
---|
[19e5d65d] | 1712 | oalign = ClearAlignmentBit( header ); // old alignment |
---|
| 1713 | if ( unlikely( (uintptr_t)oaddr % nalign == 0 // lucky match ? |
---|
[92847f7] | 1714 | && ( oalign <= nalign // going down |
---|
| 1715 | || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ? |
---|
[19e5d65d] | 1716 | ) ) { |
---|
| 1717 | HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same) |
---|
| 1718 | return realloc( oaddr, size ); // duplicate special case checks |
---|
[92847f7] | 1719 | } // if |
---|
| 1720 | } else if ( ! isFakeHeader // old real header (aligned on libAlign) ? |
---|
[19e5d65d] | 1721 | && nalign == libAlign() ) { // new alignment also on libAlign => no fake header needed |
---|
| 1722 | return realloc( oaddr, size ); // duplicate special case checks |
---|
| 1723 | } // if |
---|
[cfbc703d] | 1724 | |
---|
[116a2ea] | 1725 | Heap.FreeHeader * freeHead; |
---|
[92847f7] | 1726 | size_t bsize; |
---|
[116a2ea] | 1727 | headers( "realloc", oaddr, header, freeHead, bsize, oalign ); |
---|
[92847f7] | 1728 | |
---|
| 1729 | // change size and copy old content to new storage |
---|
| 1730 | |
---|
[dd23e66] | 1731 | size_t osize = header->kind.real.size; // old allocation size |
---|
[19e5d65d] | 1732 | bool ozfill = ZeroFillBit( header ); // old allocation zero filled |
---|
[dd23e66] | 1733 | |
---|
[116a2ea] | 1734 | void * naddr = memalignNoStats( nalign, size STAT_ARG( REALLOC ) ); // create new aligned area |
---|
[95eb7cf] | 1735 | |
---|
[116a2ea] | 1736 | headers( "realloc", naddr, header, freeHead, bsize, oalign ); |
---|
[47dd0d2] | 1737 | memcpy( naddr, oaddr, min( osize, size ) ); // copy bytes |
---|
[116a2ea] | 1738 | doFree( oaddr ); // free previous storage |
---|
[d5d3a90] | 1739 | |
---|
| 1740 | if ( unlikely( ozfill ) ) { // previous request zero fill ? |
---|
[19e5d65d] | 1741 | MarkZeroFilledBit( header ); // mark new request as zero filled |
---|
[d5d3a90] | 1742 | if ( size > osize ) { // previous request larger ? |
---|
[e4b6b7d3] | 1743 | memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage |
---|
[d5d3a90] | 1744 | } // if |
---|
| 1745 | } // if |
---|
[1e034d9] | 1746 | return naddr; |
---|
[95eb7cf] | 1747 | } // realloc |
---|
| 1748 | |
---|
| 1749 | |
---|
[116a2ea] | 1750 | void * reallocarray( void * oaddr, size_t nalign, size_t dim, size_t elemSize ) __THROW { |
---|
| 1751 | return realloc( oaddr, nalign, dim * elemSize ); |
---|
| 1752 | } // reallocarray |
---|
| 1753 | |
---|
| 1754 | |
---|
[c4f68dc] | 1755 | // Local Variables: // |
---|
| 1756 | // tab-width: 4 // |
---|
[f8cd310] | 1757 | // compile-command: "cfa -nodebug -O2 heap.cfa" // |
---|
[c4f68dc] | 1758 | // End: // |
---|