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
Line 
1//
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.
6//
7// heap.cfa --
8//
9// Author : Peter A. Buhr
10// Created On : Tue Dec 19 21:58:35 2017
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Tue Oct 11 15:08:33 2022
13// Update Count : 1525
14//
15
16#include <stdio.h>
17#include <string.h> // memset, memcpy
18#include <limits.h> // ULONG_MAX
19#include <stdlib.h> // EXIT_FAILURE
20#include <errno.h> // errno, ENOMEM, EINVAL
21#include <unistd.h> // STDERR_FILENO, sbrk, sysconf
22#include <malloc.h> // memalign, malloc_usable_size
23#include <sys/mman.h> // mmap, munmap
24extern "C" {
25#include <sys/sysinfo.h> // get_nprocs
26} // extern "C"
27
28#include "bits/align.hfa" // libAlign
29#include "bits/defs.hfa" // likely, unlikely
30#include "bits/locks.hfa" // __spinlock_t
31#include "concurrency/kernel/fwd.hfa" // __POLL_PREEMPTION
32#include "startup.hfa" // STARTUP_PRIORITY_MEMORY
33#include "math.hfa" // ceiling, min
34#include "bitmanip.hfa" // is_pow2, ceiling2
35
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 ####################
72
73
74static bool traceHeap = false;
75
76inline bool traceHeap() libcfa_public { return traceHeap; }
77
78bool traceHeapOn() libcfa_public {
79 bool temp = traceHeap;
80 traceHeap = true;
81 return temp;
82} // traceHeapOn
83
84bool traceHeapOff() libcfa_public {
85 bool temp = traceHeap;
86 traceHeap = false;
87 return temp;
88} // traceHeapOff
89
90bool traceHeapTerm() libcfa_public { return false; }
91
92
93static bool prtFree = false;
94
95bool prtFree() {
96 return prtFree;
97} // prtFree
98
99bool prtFreeOn() {
100 bool temp = prtFree;
101 prtFree = true;
102 return temp;
103} // prtFreeOn
104
105bool prtFreeOff() {
106 bool temp = prtFree;
107 prtFree = false;
108 return temp;
109} // prtFreeOff
110
111
112//######################### Spin Lock #########################
113
114
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
142
143
144//####################### Heap Statistics ####################
145
146
147#ifdef __STATISTICS__
148enum { CntTriples = 12 }; // number of counter triples
149enum { MALLOC, AALLOC, CALLOC, MEMALIGN, AMEMALIGN, CMEMALIGN, RESIZE, REALLOC, FREE };
150
151struct StatsOverlay { // overlay for iteration
152 unsigned int calls, calls_0;
153 unsigned long long int request, alloc;
154};
155
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;
177 unsigned int return_pulls, return_pushes;
178 unsigned long long int return_storage_request, return_storage_alloc;
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
186
187static_assert( sizeof(HeapStatistics) == CntTriples * sizeof(StatsOverlay),
188 "Heap statistics counter-triplets does not match with array size" );
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__
207
208
209#define SPINLOCK 0
210#define LOCKFREE 1
211#define BUCKETLOCK SPINLOCK
212#if BUCKETLOCK == SPINLOCK
213#elif BUCKETLOCK == LOCKFREE
214#include <stackLockFree.hfa>
215#else
216 #error undefined lock type for bucket lock
217#endif // LOCKFREE
218
219// Recursive definitions: HeapManager needs size of bucket array and bucket area needs sizeof HeapManager storage.
220// Break recursion by hardcoding number of buckets and statically checking number is correct after bucket array defined.
221enum { NoBucketSizes = 91 }; // number of buckets sizes
222
223struct Heap {
224 struct Storage {
225 struct Header { // header
226 union Kind {
227 struct RealHeader {
228 union {
229 struct { // 4-byte word => 8-byte header, 8-byte word => 16-byte header
230 union {
231 // 2nd low-order bit => zero filled, 3rd low-order bit => mmapped
232 // FreeHeader * home; // allocated block points back to home locations (must overlay alignment)
233 void * home; // allocated block points back to home locations (must overlay alignment)
234 size_t blockSize; // size for munmap (must overlay alignment)
235 #if BUCKETLOCK == SPINLOCK
236 Storage * next; // freed block points to next freed block of same size
237 #endif // SPINLOCK
238 };
239 size_t size; // allocation size in bytes
240 };
241 #if BUCKETLOCK == LOCKFREE
242 Link(Storage) next; // freed block points next freed block of same size (double-wide)
243 #endif // LOCKFREE
244 };
245 } real; // RealHeader
246
247 struct FakeHeader {
248 uintptr_t alignment; // 1st low-order bit => fake header & alignment
249 uintptr_t offset;
250 } fake; // FakeHeader
251 } kind; // Kind
252 } header; // Header
253
254 char pad[libAlign() - sizeof( Header )];
255 char data[0]; // storage
256 }; // Storage
257
258 static_assert( libAlign() >= sizeof( Storage ), "minimum alignment < sizeof( Storage )" );
259
260 struct __attribute__(( aligned (8) )) FreeHeader {
261 size_t blockSize __attribute__(( aligned(8) )); // size of allocations on this list
262 #if BUCKETLOCK == SPINLOCK
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
270 #else
271 StackLF(Storage) freeList;
272 #endif // BUCKETLOCK
273 Heap * homeManager; // heap owner (free storage to bucket, from bucket to heap)
274 }; // FreeHeader
275
276 FreeHeader freeLists[NoBucketSizes]; // buckets for different allocation sizes
277 void * heapBuffer; // start of free storage in buffer
278 size_t heapReserve; // amount of remaining free storage in buffer
279
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__
292}; // Heap
293
294#if BUCKETLOCK == LOCKFREE
295inline __attribute__((always_inline))
296static {
297 Link(Heap.Storage) * ?`next( Heap.Storage * this ) { return &this->header.kind.real.next; }
298 void ?{}( Heap.FreeHeader & ) {}
299 void ^?{}( Heap.FreeHeader & ) {}
300} // distribution
301#endif // LOCKFREE
302
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
332
333
334#ifdef FASTLOOKUP
335enum { LookupSizes = 65_536 + sizeof(Heap.Storage) }; // number of fast lookup sizes
336static unsigned char lookup[LookupSizes]; // O(1) lookup for small sizes
337#endif // FASTLOOKUP
338
339static volatile bool heapMasterBootFlag = false; // trigger for first heap
340static HeapMaster heapMaster @= {}; // program global
341
342static void heapMasterCtor();
343static void heapMasterDtor();
344static Heap * getHeap();
345
346
347// Size of array must harmonize with NoBucketSizes and individual bucket sizes must be multiple of 16.
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.
350static const unsigned int bucketSizes[] @= { // different bucket sizes
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
368};
369
370static_assert( NoBucketSizes == sizeof(bucketSizes) / sizeof(bucketSizes[0] ), "size of bucket array wrong" );
371
372
373// extern visibility, used by runtime kernel
374libcfa_public size_t __page_size; // architecture pagesize
375libcfa_public int __map_prot; // common mmap/mprotect protection
376
377
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
382
383
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
516 } // if
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
558
559extern int cfa_main_returned; // from interpose.cfa
560extern "C" {
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
569 void heapAppStart() { // called by __cfaabi_appready_startup
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__
578 } // heapAppStart
579
580 void heapAppStop() { // called by __cfaabi_appready_startdown
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__
602 } // heapAppStop
603} // extern "C"
604
605
606#ifdef __STATISTICS__
607static HeapStatistics stats; // zero filled
608
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" \
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"
626
627// Use "write" because streams may be shutdown when calls are made.
628static int printStats( HeapStatistics & stats ) with( heapMaster, stats ) { // see malloc_stats
629 char helpText[sizeof(prtFmt) + 1024]; // space for message and values
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,
641 sbrk_calls, sbrk_storage,
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
646 );
647} // printStats
648
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" \
663 "<total type=\"return\" pulls=\"%'u;\" 0 pushes=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
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" \
667 "<total type=\"threads\" started=\"%'lu;\" exited=\"%'lu\"/>\n" \
668 "<total type=\"heaps\" new=\"%'lu;\" reused=\"%'lu\"/>\n" \
669 "</malloc>"
670
671static int printStatsXML( HeapStatistics & stats, FILE * stream ) with( heapMaster, stats ) { // see malloc_info
672 char helpText[sizeof(prtFmtXML) + 1024]; // space for message and values
673 return __cfaabi_bits_print_buffer( fileno( stream ), helpText, sizeof(helpText), prtFmtXML,
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,
684 sbrk_calls, sbrk_storage,
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
689 );
690} // printStatsXML
691
692static HeapStatistics & collectStats( HeapStatistics & stats ) with( heapMaster ) {
693 lock( mgrLock );
694
695 stats += heapMaster.stats;
696 for ( Heap * heap = heapManagersList; heap; heap = heap->nextHeapManager ) {
697 stats += heap->stats;
698 } // for
699
700 unlock( mgrLock );
701 return stats;
702} // collectStats
703#endif // __STATISTICS__
704
705
706static bool setMmapStart( size_t value ) with( heapMaster ) { // true => mmapped, false => sbrk
707 if ( value < __page_size || bucketSizes[NoBucketSizes - 1] < value ) return false;
708 mmapStart = value; // set global
709
710 // find the closest bucket size less than or equal to the mmapStart size
711 maxBucketsUsed = Bsearchl( mmapStart, bucketSizes, NoBucketSizes ); // binary search
712 verify( maxBucketsUsed < NoBucketSizes ); // subscript failure ?
713 verify( mmapStart <= bucketSizes[maxBucketsUsed] ); // search failure ?
714 return true;
715} // setMmapStart
716
717
718// <-------+----------------------------------------------------> bsize (bucket size)
719// |header |addr
720//==================================================================================
721// align/offset |
722// <-----------------<------------+-----------------------------> bsize (bucket size)
723// |fake-header | addr
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))
726
727// <-------<<--------------------- dsize ---------------------->> bsize (bucket size)
728// |header |addr
729//==================================================================================
730// align/offset |
731// <------------------------------<<---------- dsize --------->>> bsize (bucket size)
732// |fake-header |addr
733#define DataStorage( bsize, addr, header ) (bsize - ( (char *)addr - (char *)header ))
734
735
736inline __attribute__((always_inline))
737static void checkAlign( size_t alignment ) {
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() );
740 } // if
741} // checkAlign
742
743
744inline __attribute__((always_inline))
745static void checkHeader( bool check, const char name[], void * addr ) {
746 if ( unlikely( check ) ) { // bad address ?
747 abort( "**** Error **** attempt to %s storage %p with address outside the heap.\n"
748 "Possible cause is duplicate free on same block or overwriting of memory.",
749 name, addr );
750 } // if
751} // checkHeader
752
753
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
770inline __attribute__((always_inline))
771static void fakeHeader( Heap.Storage.Header *& header, size_t & alignment ) {
772 if ( unlikely( AlignmentBit( header ) ) ) { // fake header ?
773 alignment = ClearAlignmentBit( header ); // clear flag from value
774 #ifdef __CFA_DEBUG__
775 checkAlign( alignment ); // check alignment
776 #endif // __CFA_DEBUG__
777 header = RealHeader( header ); // backup from fake to real header
778 } else {
779 alignment = libAlign(); // => no fake header
780 } // if
781} // fakeHeader
782
783
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 ) {
787 header = HeaderAddr( addr );
788
789 #ifdef __CFA_DEBUG__
790 checkHeader( header < (Heap.Storage.Header *)heapBegin, name, addr ); // bad low address ?
791 #endif // __CFA_DEBUG__
792
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 );
798 if ( unlikely( MmappedBit( header ) ) ) { // mmapped ?
799 verify( addr < heapBegin || heapEnd < addr );
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
808 #ifdef __CFA_DEBUG__
809 checkHeader( header < (Heap.Storage.Header *)heapBegin || (Heap.Storage.Header *)heapEnd < header, name, addr ); // bad address ? (offset could be + or -)
810
811 Heap * homeManager;
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.
814 (homeManager = freeHead->homeManager, freeHead < &homeManager->freeLists[0] ||
815 &homeManager->freeLists[NoBucketSizes] <= freeHead ) ) ) {
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
820 #endif // __CFA_DEBUG__
821
822 return false;
823} // headers
824
825
826static void * master_extend( size_t size ) with( heapMaster ) {
827 lock( extLock );
828
829 ptrdiff_t rem = heapRemaining - size;
830 if ( unlikely( rem < 0 ) ) {
831 // If the size requested is bigger than the current remaining storage, increase the size of the heap.
832
833 size_t increase = ceiling2( size > heapExpand ? size : heapExpand, libAlign() );
834 // Do not call abort or strerror( errno ) as they may call malloc.
835 if ( unlikely( sbrk( increase ) == (void *)-1 ) ) { // failed, no memory ?
836 unlock( extLock );
837 __cfaabi_bits_print_nolock( STDERR_FILENO, NO_MEMORY_MSG, size );
838 _exit( EXIT_FAILURE ); // give up
839 } // if
840 rem = heapRemaining + increase - size;
841
842 #ifdef __STATISTICS__
843 sbrk_calls += 1;
844 sbrk_storage += increase;
845 #endif // __STATISTICS__
846 } // if
847
848 Heap.Storage * block = (Heap.Storage *)heapEnd;
849 heapRemaining = rem;
850 heapEnd = (char *)heapEnd + size;
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
894 return block;
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
924
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'
929
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
935
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.
938 size_t tsize = size + sizeof(Heap.Storage);
939
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;
951 #ifdef FASTLOOKUP
952 if ( likely( tsize < LookupSizes ) ) bucket = lookup[tsize];
953 else
954 #endif // FASTLOOKUP
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__
966
967 // Spin until the lock is acquired for this particular size of block.
968
969 #if BUCKETLOCK == SPINLOCK
970 block = freeHead->freeList; // remove node from stack
971 #else
972 block = pop( freeHead->freeList );
973 #endif // BUCKETLOCK
974 if ( unlikely( block == 0p ) ) { // no free block ?
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
979 #if BUCKETLOCK == SPINLOCK
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__
1001 #endif // BUCKETLOCK
1002 #ifdef OWNERSHIP
1003 } else { // merge returnList into freeHead
1004 #ifdef __STATISTICS__
1005 stats.return_pulls += 1;
1006 #endif // __STATISTICS__
1007
1008 // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED.
1009
1010 freeHead->freeList = block->header.kind.real.next;
1011 } // if
1012 #endif // OWNERSHIP
1013 } else {
1014 // Memory is scrubbed in doFree.
1015 freeHead->freeList = block->header.kind.real.next;
1016 } // if
1017
1018 block->header.kind.real.home = freeHead; // pointer back to free list of apropriate size
1019 } else { // large size => mmap
1020 if ( unlikely( size > ULONG_MAX - __page_size ) ) return 0p;
1021 tsize = ceiling2( tsize, __page_size ); // must be multiple of page size
1022 #ifdef __STATISTICS__
1023 stats.counters[STAT_NAME].alloc += tsize;
1024 stats.mmap_calls += 1;
1025 stats.mmap_storage_request += size;
1026 stats.mmap_storage_alloc += tsize;
1027 #endif // __STATISTICS__
1028
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 ?
1036 if ( errno == ENOMEM ) abort( NO_MEMORY_MSG, tsize ); // no memory
1037 // Do not call strerror( errno ) as it may call malloc.
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
1042 #ifdef __CFA_DEBUG__
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) ) );
1046 #endif // __CFA_DEBUG__
1047 } // if
1048
1049 block->header.kind.real.size = size; // store allocation size
1050 void * addr = &(block->data); // adjust off header to user bytes
1051 verify( ((uintptr_t)addr & (libAlign() - 1)) == 0 ); // minimum alignment ?
1052
1053 #ifdef __CFA_DEBUG__
1054 if ( traceHeap() ) {
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
1058 } // if
1059 #endif // __CFA_DEBUG__
1060
1061// poll_interrupts(); // call rollforward
1062
1063 return addr;
1064} // doMalloc
1065
1066
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
1071
1072 Heap.Storage.Header * header;
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__
1089
1090 if ( unlikely( mapped ) ) { // mmapped ?
1091 #ifdef __STATISTICS__
1092 stats.munmap_calls += 1;
1093 stats.munmap_storage_request += rsize;
1094 stats.munmap_storage_alloc += size;
1095 #endif // __STATISTICS__
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 );
1105 } // if
1106 } else {
1107 #ifdef __CFA_DEBUG__
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 );
1120 #endif // __CFA_DEBUG__
1121
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
1156 } // if
1157
1158 #ifdef __CFA_DEBUG__
1159 if ( traceHeap() ) {
1160 char helpText[64];
1161 __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText),
1162 "Free( %p ) size:%zu\n", addr, size ); // print debug/nodebug
1163 } // if
1164 #endif // __CFA_DEBUG__
1165
1166// poll_interrupts(); // call rollforward
1167} // doFree
1168
1169
1170size_t prtFree( Heap & manager ) with( manager ) {
1171 size_t total = 0;
1172 #ifdef __STATISTICS__
1173 __cfaabi_bits_acquire();
1174 __cfaabi_bits_print_nolock( STDERR_FILENO, "\nBin lists (bin size : free blocks on list)\n" );
1175 #endif // __STATISTICS__
1176 for ( unsigned int i = 0; i < heapMaster.maxBucketsUsed; i += 1 ) {
1177 size_t size = freeLists[i].blockSize;
1178 #ifdef __STATISTICS__
1179 unsigned int N = 0;
1180 #endif // __STATISTICS__
1181
1182 #if BUCKETLOCK == SPINLOCK
1183 for ( Heap.Storage * p = freeLists[i].freeList; p != 0p; p = p->header.kind.real.next ) {
1184 #else
1185 for(;;) {
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`
1189// typeof(p) temp = (( p )`next)->top; // FIX ME: direct assignent fails, initialization works`
1190// p = temp;
1191 #endif // BUCKETLOCK
1192 total += size;
1193 #ifdef __STATISTICS__
1194 N += 1;
1195 #endif // __STATISTICS__
1196 } // for
1197
1198 #ifdef __STATISTICS__
1199 __cfaabi_bits_print_nolock( STDERR_FILENO, "%7zu, %-7u ", size, N );
1200 if ( (i + 1) % 8 == 0 ) __cfaabi_bits_print_nolock( STDERR_FILENO, "\n" );
1201 #endif // __STATISTICS__
1202 } // for
1203 #ifdef __STATISTICS__
1204 __cfaabi_bits_print_nolock( STDERR_FILENO, "\ntotal free blocks:%zu\n", total );
1205 __cfaabi_bits_release();
1206 #endif // __STATISTICS__
1207 return (char *)heapMaster.heapEnd - (char *)heapMaster.heapBegin - total;
1208} // prtFree
1209
1210
1211#ifdef __STATISTICS__
1212static void incCalls( long int statName ) libcfa_nopreempt {
1213 heapManager->stats.counters[statName].calls += 1;
1214} // incCalls
1215
1216static void incZeroCalls( long int statName ) libcfa_nopreempt {
1217 heapManager->stats.counters[statName].calls_0 += 1;
1218} // incZeroCalls
1219#endif // __STATISTICS__
1220
1221#ifdef __CFA_DEBUG__
1222static void incUnfreed( size_t offset ) libcfa_nopreempt {
1223 heapManager->allocUnfreed += offset;
1224} // incUnfreed
1225#endif // __CFA_DEBUG__
1226
1227
1228static void * memalignNoStats( size_t alignment, size_t size STAT_PARM ) {
1229 checkAlign( alignment ); // check alignment
1230
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 ) );
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
1243 size_t offset = alignment - libAlign() + sizeof(Heap.Storage);
1244 char * addr = (char *)doMalloc( size + offset STAT_ARG( STAT_NAME ) );
1245
1246 // address in the block of the "next" alignment address
1247 char * user = (char *)ceiling2( (uintptr_t)(addr + sizeof(Heap.Storage)), alignment );
1248
1249 // address of header from malloc
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
1257 Heap.Storage.Header * fakeHeader = HeaderAddr( user );
1258
1259 // SKULLDUGGERY: insert the offset to the start of the actual storage block and remember alignment
1260 fakeHeader->kind.fake.offset = (char *)fakeHeader - (char *)realHeader;
1261 // SKULLDUGGERY: odd alignment implies fake header
1262 fakeHeader->kind.fake.alignment = MarkAlignmentBit( alignment );
1263
1264 return user;
1265} // memalignNoStats
1266
1267
1268//####################### Memory Allocation Routines ####################
1269
1270
1271extern "C" {
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().
1274 void * malloc( size_t size ) libcfa_public {
1275 return doMalloc( size STAT_ARG( MALLOC ) );
1276 } // malloc
1277
1278
1279 // Same as malloc() except size bytes is an array of dim elements each of elemSize bytes.
1280 void * aalloc( size_t dim, size_t elemSize ) libcfa_public {
1281 return doMalloc( dim * elemSize STAT_ARG( AALLOC ) );
1282 } // aalloc
1283
1284
1285 // Same as aalloc() with memory set to zero.
1286 void * calloc( size_t dim, size_t elemSize ) libcfa_public {
1287 size_t size = dim * elemSize;
1288 char * addr = (char *)doMalloc( size STAT_ARG( CALLOC ) );
1289
1290 if ( unlikely( addr == NULL ) ) return NULL; // stop further processing if 0p is returned
1291
1292 Heap.Storage.Header * header;
1293 Heap.FreeHeader * freeHead;
1294 size_t bsize, alignment;
1295
1296 #ifndef __CFA_DEBUG__
1297 bool mapped =
1298 #endif // __CFA_DEBUG__
1299 headers( "calloc", addr, header, freeHead, bsize, alignment );
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.
1303 if ( likely( ! mapped ) )
1304 #endif // __CFA_DEBUG__
1305 // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined
1306 // `-header`-addr `-size
1307 memset( addr, '\0', size ); // set to zeros
1308
1309 MarkZeroFilledBit( header ); // mark as zero fill
1310 return addr;
1311 } // calloc
1312
1313
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.
1318 void * resize( void * oaddr, size_t size ) libcfa_public {
1319 if ( unlikely( oaddr == 0p ) ) { // => malloc( size )
1320 return doMalloc( size STAT_ARG( RESIZE ) );
1321 } // if
1322
1323 PROLOG( RESIZE, doFree( oaddr ) ); // => free( oaddr )
1324
1325 Heap.Storage.Header * header;
1326 Heap.FreeHeader * freeHead;
1327 size_t bsize, oalign;
1328 headers( "resize", oaddr, header, freeHead, bsize, oalign );
1329
1330 size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
1331 // same size, DO NOT preserve STICKY PROPERTIES.
1332 if ( oalign == libAlign() && size <= odsize && odsize <= size * 2 ) { // allow 50% wasted storage for smaller size
1333 ClearZeroFillBit( header ); // no alignment and turn off 0 fill
1334 #ifdef __CFA_DEBUG__
1335 incUnfreed( size - header->kind.real.size ); // adjustment off the size difference
1336 #endif // __CFA_DEBUG__
1337 header->kind.real.size = size; // reset allocation size
1338 #ifdef __STATISTICS__
1339 incCalls( RESIZE );
1340 #endif // __STATISTICS__
1341 return oaddr;
1342 } // if
1343
1344 // change size, DO NOT preserve STICKY PROPERTIES.
1345 doFree( oaddr ); // free previous storage
1346
1347 return doMalloc( size STAT_ARG( RESIZE ) ); // create new area
1348 } // resize
1349
1350
1351 // Same as resize() but the contents are unchanged in the range from the start of the region up to the minimum of
1352 // the old and new sizes.
1353 void * realloc( void * oaddr, size_t size ) libcfa_public {
1354 if ( unlikely( oaddr == 0p ) ) { // => malloc( size )
1355 return doMalloc( size STAT_ARG( REALLOC ) );
1356 } // if
1357
1358 PROLOG( REALLOC, doFree( oaddr ) ); // => free( oaddr )
1359
1360 Heap.Storage.Header * header;
1361 Heap.FreeHeader * freeHead;
1362 size_t bsize, oalign;
1363 headers( "realloc", oaddr, header, freeHead, bsize, oalign );
1364
1365 size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
1366 size_t osize = header->kind.real.size; // old allocation size
1367 bool ozfill = ZeroFillBit( header ); // old allocation zero filled
1368 if ( unlikely( size <= odsize ) && odsize <= size * 2 ) { // allow up to 50% wasted storage
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
1373 if ( unlikely( ozfill ) && size > osize ) { // previous request zero fill and larger ?
1374 memset( (char *)oaddr + osize, '\0', size - osize ); // initialize added storage
1375 } // if
1376 #ifdef __STATISTICS__
1377 incCalls( REALLOC );
1378 #endif // __STATISTICS__
1379 return oaddr;
1380 } // if
1381
1382 // change size and copy old content to new storage
1383
1384 void * naddr;
1385 if ( likely( oalign <= libAlign() ) ) { // previous request not aligned ?
1386 naddr = doMalloc( size STAT_ARG( REALLOC ) ); // create new area
1387 } else {
1388 naddr = memalignNoStats( oalign, size STAT_ARG( REALLOC ) ); // create new aligned area
1389 } // if
1390
1391 headers( "realloc", naddr, header, freeHead, bsize, oalign );
1392 // To preserve prior fill, the entire bucket must be copied versus the size.
1393 memcpy( naddr, oaddr, min( osize, size ) ); // copy bytes
1394 doFree( oaddr ); // free previous storage
1395
1396 if ( unlikely( ozfill ) ) { // previous request zero fill ?
1397 MarkZeroFilledBit( header ); // mark new request as zero filled
1398 if ( size > osize ) { // previous request larger ?
1399 memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage
1400 } // if
1401 } // if
1402 return naddr;
1403 } // realloc
1404
1405
1406 // Same as realloc() except the new allocation size is large enough for an array of nelem elements of size elsize.
1407 void * reallocarray( void * oaddr, size_t dim, size_t elemSize ) libcfa_public {
1408 return realloc( oaddr, dim * elemSize );
1409 } // reallocarray
1410
1411
1412 // Same as malloc() except the memory address is a multiple of alignment, which must be a power of two. (obsolete)
1413 void * memalign( size_t alignment, size_t size ) libcfa_public {
1414 return memalignNoStats( alignment, size STAT_ARG( MEMALIGN ) );
1415 } // memalign
1416
1417
1418 // Same as aalloc() with memory alignment.
1419 void * amemalign( size_t alignment, size_t dim, size_t elemSize ) libcfa_public {
1420 return memalignNoStats( alignment, dim * elemSize STAT_ARG( AMEMALIGN ) );
1421 } // amemalign
1422
1423
1424 // Same as calloc() with memory alignment.
1425 void * cmemalign( size_t alignment, size_t dim, size_t elemSize ) libcfa_public {
1426 size_t size = dim * elemSize;
1427 char * addr = (char *)memalignNoStats( alignment, size STAT_ARG( CMEMALIGN ) );
1428
1429 if ( unlikely( addr == NULL ) ) return NULL; // stop further processing if 0p is returned
1430
1431 Heap.Storage.Header * header;
1432 Heap.FreeHeader * freeHead;
1433 size_t bsize;
1434
1435 #ifndef __CFA_DEBUG__
1436 bool mapped =
1437 #endif // __CFA_DEBUG__
1438 headers( "cmemalign", addr, header, freeHead, bsize, alignment );
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
1448 MarkZeroFilledBit( header ); // mark as zero filled
1449 return addr;
1450 } // cmemalign
1451
1452
1453 // Same as memalign(), but ISO/IEC 2011 C11 Section 7.22.2 states: the value of size shall be an integral multiple
1454 // of alignment. This requirement is universally ignored.
1455 void * aligned_alloc( size_t alignment, size_t size ) libcfa_public {
1456 return memalign( alignment, size );
1457 } // aligned_alloc
1458
1459
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).
1464 int posix_memalign( void ** memptr, size_t alignment, size_t size ) libcfa_public {
1465 if ( unlikely( alignment < libAlign() || ! is_pow2( alignment ) ) ) return EINVAL; // check alignment
1466 *memptr = memalign( alignment, size );
1467 return 0;
1468 } // posix_memalign
1469
1470
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).
1473 void * valloc( size_t size ) libcfa_public {
1474 return memalign( __page_size, size );
1475 } // valloc
1476
1477
1478 // Same as valloc but rounds size to multiple of page size.
1479 void * pvalloc( size_t size ) libcfa_public {
1480 return memalign( __page_size, ceiling2( size, __page_size ) ); // round size to multiple of page size
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()
1485 // or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is
1486 // 0p, no operation is performed.
1487 void free( void * addr ) libcfa_public {
1488// verify( heapManager );
1489
1490 if ( unlikely( addr == 0p ) ) { // special case
1491 #ifdef __STATISTICS__
1492 if ( heapManager )
1493 incZeroCalls( FREE );
1494 #endif // __STATISTICS__
1495 return;
1496 } // if
1497
1498 #ifdef __STATISTICS__
1499 incCalls( FREE );
1500 #endif // __STATISTICS__
1501
1502 doFree( addr ); // handles heapManager == nullptr
1503 } // free
1504
1505
1506 // Returns the alignment of an allocation.
1507 size_t malloc_alignment( void * addr ) libcfa_public {
1508 if ( unlikely( addr == 0p ) ) return libAlign(); // minimum alignment
1509 Heap.Storage.Header * header = HeaderAddr( addr );
1510 if ( unlikely( AlignmentBit( header ) ) ) { // fake header ?
1511 return ClearAlignmentBit( header ); // clear flag from value
1512 } else {
1513 return libAlign(); // minimum alignment
1514 } // if
1515 } // malloc_alignment
1516
1517
1518 // Returns true if the allocation is zero filled, e.g., allocated by calloc().
1519 bool malloc_zero_fill( void * addr ) libcfa_public {
1520 if ( unlikely( addr == 0p ) ) return false; // null allocation is not zero fill
1521 Heap.Storage.Header * header = HeaderAddr( addr );
1522 if ( unlikely( AlignmentBit( header ) ) ) { // fake header ?
1523 header = RealHeader( header ); // backup from fake to real header
1524 } // if
1525 return ZeroFillBit( header ); // zero filled ?
1526 } // malloc_zero_fill
1527
1528
1529 // Returns original total allocation size (not bucket size) => array size is dimension * sizeof(T).
1530 size_t malloc_size( void * addr ) libcfa_public {
1531 if ( unlikely( addr == 0p ) ) return 0; // null allocation has zero size
1532 Heap.Storage.Header * header = HeaderAddr( addr );
1533 if ( unlikely( AlignmentBit( header ) ) ) { // fake header ?
1534 header = RealHeader( header ); // backup from fake to real header
1535 } // if
1536 return header->kind.real.size;
1537 } // malloc_size
1538
1539
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.
1542 size_t malloc_usable_size( void * addr ) libcfa_public {
1543 if ( unlikely( addr == 0p ) ) return 0; // null allocation has 0 size
1544 Heap.Storage.Header * header;
1545 Heap.FreeHeader * freeHead;
1546 size_t bsize, alignment;
1547
1548 headers( "malloc_usable_size", addr, header, freeHead, bsize, alignment );
1549 return DataStorage( bsize, addr, header ); // data storage in bucket
1550 } // malloc_usable_size
1551
1552
1553 // Prints (on default standard error) statistics about memory allocated by malloc and related functions.
1554 void malloc_stats( void ) libcfa_public {
1555 #ifdef __STATISTICS__
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 ) {
1562 #endif // __STATISTICS__
1563 abort( "write failed in malloc_stats" );
1564 } // if
1565 } // malloc_stats
1566
1567
1568 // Changes the file descriptor where malloc_stats() writes statistics.
1569 int malloc_stats_fd( int fd __attribute__(( unused )) ) libcfa_public {
1570 #ifdef __STATISTICS__
1571 int temp = heapMaster.stats_fd;
1572 heapMaster.stats_fd = fd;
1573 return temp;
1574 #else
1575 return -1; // unsupported
1576 #endif // __STATISTICS__
1577 } // malloc_stats_fd
1578
1579
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).
1583 int malloc_info( int options, FILE * stream __attribute__(( unused )) ) libcfa_public {
1584 if ( options != 0 ) { errno = EINVAL; return -1; }
1585 #ifdef __STATISTICS__
1586 HeapStatistics stats;
1587 HeapStatisticsCtor( stats );
1588 return printStatsXML( collectStats( stats ), stream ); // returns bytes written or -1
1589 #else
1590 return 0; // unsupported
1591 #endif // __STATISTICS__
1592 } // malloc_info
1593
1594
1595 // Adjusts parameters that control the behaviour of the memory-allocation functions (see malloc). The param argument
1596 // specifies the parameter to be modified, and value specifies the new value for that parameter.
1597 int mallopt( int option, int value ) libcfa_public {
1598 if ( value < 0 ) return 0;
1599 choose( option ) {
1600 case M_TOP_PAD:
1601 heapMaster.heapExpand = ceiling2( value, __page_size );
1602 return 1;
1603 case M_MMAP_THRESHOLD:
1604 if ( setMmapStart( value ) ) return 1;
1605 } // choose
1606 return 0; // error, unsupported
1607 } // mallopt
1608
1609
1610 // Attempt to release free memory at the top of the heap (by calling sbrk with a suitable argument).
1611 int malloc_trim( size_t ) libcfa_public {
1612 return 0; // => impossible to release memory
1613 } // malloc_trim
1614
1615
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.)
1620 void * malloc_get_state( void ) libcfa_public {
1621 return 0p; // unsupported
1622 } // malloc_get_state
1623
1624
1625 // Restores the state of all malloc internal bookkeeping variables to the values recorded in the opaque data
1626 // structure pointed to by state.
1627 int malloc_set_state( void * ) libcfa_public {
1628 return 0; // unsupported
1629 } // malloc_set_state
1630
1631
1632 // Sets the amount (bytes) to extend the heap when there is insufficent free storage to service an allocation.
1633 __attribute__((weak)) size_t malloc_expansion() libcfa_public { return __CFA_DEFAULT_HEAP_EXPANSION__; }
1634
1635 // Sets the crossover point between allocations occuring in the sbrk area or separately mmapped.
1636 __attribute__((weak)) size_t malloc_mmap_start() libcfa_public { return __CFA_DEFAULT_MMAP_START__; }
1637
1638 // Amount subtracted to adjust for unfreed program storage (debug only).
1639 __attribute__((weak)) size_t malloc_unfreed() libcfa_public { return __CFA_DEFAULT_HEAP_UNFREED__; }
1640} // extern "C"
1641
1642
1643// Must have CFA linkage to overload with C linkage realloc.
1644void * resize( void * oaddr, size_t nalign, size_t size ) libcfa_public {
1645 if ( unlikely( oaddr == 0p ) ) { // => malloc( size )
1646 return memalignNoStats( nalign, size STAT_ARG( RESIZE ) );
1647 } // if
1648
1649 PROLOG( RESIZE, doFree( oaddr ) ); // => free( oaddr )
1650
1651 // Attempt to reuse existing alignment.
1652 Heap.Storage.Header * header = HeaderAddr( oaddr );
1653 bool isFakeHeader = AlignmentBit( header ); // old fake header ?
1654 size_t oalign;
1655
1656 if ( unlikely( isFakeHeader ) ) {
1657 checkAlign( nalign ); // check alignment
1658 oalign = ClearAlignmentBit( header ); // old alignment
1659 if ( unlikely( (uintptr_t)oaddr % nalign == 0 // lucky match ?
1660 && ( oalign <= nalign // going down
1661 || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ?
1662 ) ) {
1663 HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1664 Heap.FreeHeader * freeHead;
1665 size_t bsize, oalign;
1666 headers( "resize", oaddr, header, freeHead, bsize, oalign );
1667 size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
1668
1669 if ( size <= odsize && odsize <= size * 2 ) { // allow 50% wasted data storage
1670 HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1671 ClearZeroFillBit( header ); // turn off 0 fill
1672 #ifdef __CFA_DEBUG__
1673 incUnfreed( size - header->kind.real.size ); // adjustment off the size difference
1674 #endif // __CFA_DEBUG__
1675 header->kind.real.size = size; // reset allocation size
1676 #ifdef __STATISTICS__
1677 incCalls( RESIZE );
1678 #endif // __STATISTICS__
1679 return oaddr;
1680 } // if
1681 } // if
1682 } else if ( ! isFakeHeader // old real header (aligned on libAlign) ?
1683 && nalign == libAlign() ) { // new alignment also on libAlign => no fake header needed
1684 return resize( oaddr, size ); // duplicate special case checks
1685 } // if
1686
1687 // change size, DO NOT preserve STICKY PROPERTIES.
1688 doFree( oaddr ); // free previous storage
1689 return memalignNoStats( nalign, size STAT_ARG( RESIZE ) ); // create new aligned area
1690} // resize
1691
1692
1693void * realloc( void * oaddr, size_t nalign, size_t size ) libcfa_public {
1694 if ( unlikely( oaddr == 0p ) ) { // => malloc( size )
1695 return memalignNoStats( nalign, size STAT_ARG( REALLOC ) );
1696 } // if
1697
1698 PROLOG( REALLOC, doFree( oaddr ) ); // => free( oaddr )
1699
1700 // Attempt to reuse existing alignment.
1701 Heap.Storage.Header * header = HeaderAddr( oaddr );
1702 bool isFakeHeader = AlignmentBit( header ); // old fake header ?
1703 size_t oalign;
1704 if ( unlikely( isFakeHeader ) ) {
1705 checkAlign( nalign ); // check alignment
1706 oalign = ClearAlignmentBit( header ); // old alignment
1707 if ( unlikely( (uintptr_t)oaddr % nalign == 0 // lucky match ?
1708 && ( oalign <= nalign // going down
1709 || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ?
1710 ) ) {
1711 HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1712 return realloc( oaddr, size ); // duplicate special case checks
1713 } // if
1714 } else if ( ! isFakeHeader // old real header (aligned on libAlign) ?
1715 && nalign == libAlign() ) { // new alignment also on libAlign => no fake header needed
1716 return realloc( oaddr, size ); // duplicate special case checks
1717 } // if
1718
1719 Heap.FreeHeader * freeHead;
1720 size_t bsize;
1721 headers( "realloc", oaddr, header, freeHead, bsize, oalign );
1722
1723 // change size and copy old content to new storage
1724
1725 size_t osize = header->kind.real.size; // old allocation size
1726 bool ozfill = ZeroFillBit( header ); // old allocation zero filled
1727
1728 void * naddr = memalignNoStats( nalign, size STAT_ARG( REALLOC ) ); // create new aligned area
1729
1730 headers( "realloc", naddr, header, freeHead, bsize, oalign );
1731 memcpy( naddr, oaddr, min( osize, size ) ); // copy bytes
1732 doFree( oaddr ); // free previous storage
1733
1734 if ( unlikely( ozfill ) ) { // previous request zero fill ?
1735 MarkZeroFilledBit( header ); // mark new request as zero filled
1736 if ( size > osize ) { // previous request larger ?
1737 memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage
1738 } // if
1739 } // if
1740 return naddr;
1741} // realloc
1742
1743
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
1749// Local Variables: //
1750// tab-width: 4 //
1751// compile-command: "cfa -nodebug -O2 heap.cfa" //
1752// End: //
Note: See TracBrowser for help on using the repository browser.