source: libcfa/src/heap.cfa@ a51b8f6

ADT ast-experimental
Last change on this file since a51b8f6 was 116a2ea, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

new heap and associated tests updated

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