source: libcfa/src/heap.cfa @ 07b59ec

Last change on this file since 07b59ec was 07b59ec, checked in by Peter A. Buhr <pabuhr@…>, 13 months ago

change startup sequence by adding back heapManagerBootFlag, add build flag for non-null return for malloc(0)

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