source: libcfa/src/heap.cfa @ 708ae38

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since 708ae38 was 578ec01c, checked in by Peter A. Buhr <pabuhr@…>, 2 years ago

update heap statistics to new format (incomplete)

  • Property mode set to 100644
File size: 56.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 : Sun Jan  2 23:29:41 2022
13// Update Count     : 1058
14//
15
16#include <unistd.h>                                                                             // sbrk, sysconf
17#include <stdlib.h>                                                                             // EXIT_FAILURE
18#include <stdbool.h>                                                                    // true, false
19#include <stdio.h>                                                                              // snprintf, fileno
20#include <errno.h>                                                                              // errno
21#include <string.h>                                                                             // memset, memcpy
22#include <limits.h>                                                                             // ULONG_MAX
23#include <malloc.h>                                                                             // memalign, malloc_usable_size
24#include <sys/mman.h>                                                                   // mmap, munmap
25
26#include "bits/align.hfa"                                                               // libAlign
27#include "bits/defs.hfa"                                                                // likely, unlikely
28#include "bits/locks.hfa"                                                               // __spinlock_t
29#include "startup.hfa"                                                                  // STARTUP_PRIORITY_MEMORY
30#include "math.hfa"                                                                             // min
31#include "bitmanip.hfa"                                                                 // is_pow2, ceiling2
32
33static bool traceHeap = false;
34
35inline bool traceHeap() { return traceHeap; }
36
37bool traceHeapOn() {
38        bool temp = traceHeap;
39        traceHeap = true;
40        return temp;
41} // traceHeapOn
42
43bool traceHeapOff() {
44        bool temp = traceHeap;
45        traceHeap = false;
46        return temp;
47} // traceHeapOff
48
49bool traceHeapTerm() { return false; }
50
51
52static bool prtFree = false;
53
54bool prtFree() {
55        return prtFree;
56} // prtFree
57
58bool prtFreeOn() {
59        bool temp = prtFree;
60        prtFree = true;
61        return temp;
62} // prtFreeOn
63
64bool prtFreeOff() {
65        bool temp = prtFree;
66        prtFree = false;
67        return temp;
68} // prtFreeOff
69
70
71enum {
72        // Define the default extension heap amount in units of bytes. When the uC++ supplied heap reaches the brk address,
73        // the brk address is extended by the extension amount.
74        __CFA_DEFAULT_HEAP_EXPANSION__ = (10 * 1024 * 1024),
75
76        // Define the mmap crossover point during allocation. Allocations less than this amount are allocated from buckets;
77        // values greater than or equal to this value are mmap from the operating system.
78        __CFA_DEFAULT_MMAP_START__ = (512 * 1024 + 1),
79};
80
81size_t default_mmap_start() __attribute__(( weak )) {
82        return __CFA_DEFAULT_MMAP_START__;
83} // default_mmap_start
84
85size_t default_heap_expansion() __attribute__(( weak )) {
86        return __CFA_DEFAULT_HEAP_EXPANSION__;
87} // default_heap_expansion
88
89
90#ifdef __CFA_DEBUG__
91static size_t allocUnfreed;                                                             // running total of allocations minus frees
92
93static void prtUnfreed() {
94        if ( allocUnfreed != 0 ) {
95                // DO NOT USE STREAMS AS THEY MAY BE UNAVAILABLE AT THIS POINT.
96                char helpText[512];
97                int len = snprintf( helpText, sizeof(helpText), "CFA warning (UNIX pid:%ld) : program terminating with %zu(0x%zx) bytes of storage allocated but not freed.\n"
98                                                        "Possible cause is unfreed storage allocated by the program or system/library routines called from the program.\n",
99                                                        (long int)getpid(), allocUnfreed, allocUnfreed ); // always print the UNIX pid
100                __cfaabi_bits_write( STDERR_FILENO, helpText, len ); // print debug/nodebug
101        } // if
102} // prtUnfreed
103
104extern int cfa_main_returned;                                                   // from interpose.cfa
105extern "C" {
106        void heapAppStart() {                                                           // called by __cfaabi_appready_startup
107                allocUnfreed = 0;
108        } // heapAppStart
109
110        void heapAppStop() {                                                            // called by __cfaabi_appready_startdown
111                fclose( stdin ); fclose( stdout );
112                if ( cfa_main_returned ) prtUnfreed();                  // do not check unfreed storage if exit called
113        } // heapAppStop
114} // extern "C"
115#endif // __CFA_DEBUG__
116
117
118// statically allocated variables => zero filled.
119size_t __page_size;                                                                             // architecture pagesize
120int __map_prot;                                                                                 // common mmap/mprotect protection
121static size_t heapExpand;                                                               // sbrk advance
122static size_t mmapStart;                                                                // cross over point for mmap
123static unsigned int maxBucketsUsed;                                             // maximum number of buckets in use
124
125
126#define SPINLOCK 0
127#define LOCKFREE 1
128#define BUCKETLOCK SPINLOCK
129#if BUCKETLOCK == SPINLOCK
130#elif BUCKETLOCK == LOCKFREE
131#include <stackLockFree.hfa>
132#else
133        #error undefined lock type for bucket lock
134#endif // LOCKFREE
135
136// Recursive definitions: HeapManager needs size of bucket array and bucket area needs sizeof HeapManager storage.
137// Break recusion by hardcoding number of buckets and statically checking number is correct after bucket array defined.
138enum { NoBucketSizes = 91 };                                                    // number of buckets sizes
139
140struct HeapManager {
141        struct Storage {
142                struct Header {                                                                 // header
143                        union Kind {
144                                struct RealHeader {
145                                        union {
146                                                struct {                                                // 4-byte word => 8-byte header, 8-byte word => 16-byte header
147                                                        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ && __SIZEOF_POINTER__ == 4
148                                                        uint64_t padding;                       // unused, force home/blocksize to overlay alignment in fake header
149                                                        #endif // __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ && __SIZEOF_POINTER__ == 4
150
151                                                        union {
152                                                                // FreeHeader * home;           // allocated block points back to home locations (must overlay alignment)
153                                                                // 2nd low-order bit => zero filled
154                                                                void * home;                    // allocated block points back to home locations (must overlay alignment)
155                                                                size_t blockSize;               // size for munmap (must overlay alignment)
156                                                                #if BUCKETLOCK == SPINLOCK
157                                                                Storage * next;                 // freed block points next freed block of same size
158                                                                #endif // SPINLOCK
159                                                        };
160                                                        size_t size;                            // allocation size in bytes
161
162                                                        #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ && __SIZEOF_POINTER__ == 4
163                                                        uint64_t padding;                       // unused, force home/blocksize to overlay alignment in fake header
164                                                        #endif // __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ && __SIZEOF_POINTER__ == 4
165                                                };
166                                                #if BUCKETLOCK == LOCKFREE
167                                                Link(Storage) next;                             // freed block points next freed block of same size (double-wide)
168                                                #endif // LOCKFREE
169                                        };
170                                } real; // RealHeader
171
172                                struct FakeHeader {
173                                        #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
174                                        uint32_t alignment;                                     // 1st low-order bit => fake header & alignment
175                                        #endif // __ORDER_LITTLE_ENDIAN__
176
177                                        uint32_t offset;
178
179                                        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
180                                        uint32_t alignment;                                     // low-order bits of home/blockSize used for tricks
181                                        #endif // __ORDER_BIG_ENDIAN__
182                                } fake; // FakeHeader
183                        } kind; // Kind
184                } header; // Header
185                char pad[libAlign() - sizeof( Header )];
186                char data[0];                                                                   // storage
187        }; // Storage
188
189        static_assert( libAlign() >= sizeof( Storage ), "libAlign() < sizeof( Storage )" );
190
191        struct FreeHeader {
192                #if BUCKETLOCK == SPINLOCK
193                __spinlock_t lock;                                                              // must be first field for alignment
194                Storage * freeList;
195                #else
196                StackLF(Storage) freeList;
197                #endif // BUCKETLOCK
198                size_t blockSize;                                                               // size of allocations on this list
199        }; // FreeHeader
200
201        // must be first fields for alignment
202        __spinlock_t extlock;                                                           // protects allocation-buffer extension
203        FreeHeader freeLists[NoBucketSizes];                            // buckets for different allocation sizes
204
205        void * heapBegin;                                                                       // start of heap
206        void * heapEnd;                                                                         // logical end of heap
207        size_t heapRemaining;                                                           // amount of storage not allocated in the current chunk
208}; // HeapManager
209
210#if BUCKETLOCK == LOCKFREE
211static inline {
212        Link(HeapManager.Storage) * ?`next( HeapManager.Storage * this ) { return &this->header.kind.real.next; }
213        void ?{}( HeapManager.FreeHeader & ) {}
214        void ^?{}( HeapManager.FreeHeader & ) {}
215} // distribution
216#endif // LOCKFREE
217
218static inline size_t getKey( const HeapManager.FreeHeader & freeheader ) { return freeheader.blockSize; }
219
220
221#define FASTLOOKUP
222#define __STATISTICS__
223
224// Size of array must harmonize with NoBucketSizes and individual bucket sizes must be multiple of 16.
225// Smaller multiples of 16 and powers of 2 are common allocation sizes, so make them generate the minimum required bucket size.
226// malloc(0) returns 0p, so no bucket is necessary for 0 bytes returning an address that can be freed.
227static const unsigned int bucketSizes[] @= {                    // different bucket sizes
228        16 + sizeof(HeapManager.Storage), 32 + sizeof(HeapManager.Storage), 48 + sizeof(HeapManager.Storage), 64 + sizeof(HeapManager.Storage), // 4
229        96 + sizeof(HeapManager.Storage), 112 + sizeof(HeapManager.Storage), 128 + sizeof(HeapManager.Storage), // 3
230        160, 192, 224, 256 + sizeof(HeapManager.Storage), // 4
231        320, 384, 448, 512 + sizeof(HeapManager.Storage), // 4
232        640, 768, 896, 1_024 + sizeof(HeapManager.Storage), // 4
233        1_536, 2_048 + sizeof(HeapManager.Storage), // 2
234        2_560, 3_072, 3_584, 4_096 + sizeof(HeapManager.Storage), // 4
235        6_144, 8_192 + sizeof(HeapManager.Storage), // 2
236        9_216, 10_240, 11_264, 12_288, 13_312, 14_336, 15_360, 16_384 + sizeof(HeapManager.Storage), // 8
237        18_432, 20_480, 22_528, 24_576, 26_624, 28_672, 30_720, 32_768 + sizeof(HeapManager.Storage), // 8
238        36_864, 40_960, 45_056, 49_152, 53_248, 57_344, 61_440, 65_536 + sizeof(HeapManager.Storage), // 8
239        73_728, 81_920, 90_112, 98_304, 106_496, 114_688, 122_880, 131_072 + sizeof(HeapManager.Storage), // 8
240        147_456, 163_840, 180_224, 196_608, 212_992, 229_376, 245_760, 262_144 + sizeof(HeapManager.Storage), // 8
241        294_912, 327_680, 360_448, 393_216, 425_984, 458_752, 491_520, 524_288 + sizeof(HeapManager.Storage), // 8
242        655_360, 786_432, 917_504, 1_048_576 + sizeof(HeapManager.Storage), // 4
243        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(HeapManager.Storage), // 8
244        2_621_440, 3_145_728, 3_670_016, 4_194_304 + sizeof(HeapManager.Storage), // 4
245};
246
247static_assert( NoBucketSizes == sizeof(bucketSizes) / sizeof(bucketSizes[0] ), "size of bucket array wrong" );
248
249#ifdef FASTLOOKUP
250enum { LookupSizes = 65_536 + sizeof(HeapManager.Storage) }; // number of fast lookup sizes
251static unsigned char lookup[LookupSizes];                               // O(1) lookup for small sizes
252#endif // FASTLOOKUP
253
254static const off_t mmapFd = -1;                                                 // fake or actual fd for anonymous file
255#ifdef __CFA_DEBUG__
256static bool heapBoot = 0;                                                               // detect recursion during boot
257#endif // __CFA_DEBUG__
258
259// The constructor for heapManager is called explicitly in memory_startup.
260static HeapManager heapManager __attribute__(( aligned (128) )) @= {}; // size of cache line to prevent false sharing
261
262
263#ifdef __STATISTICS__
264// Heap statistics counters.
265static unsigned int malloc_calls, malloc_0_calls;
266static unsigned long long int malloc_storage_request, malloc_storage_alloc;
267static unsigned int aalloc_calls, aalloc_0_calls;
268static unsigned long long int aalloc_storage_request, aalloc_storage_alloc;
269static unsigned int calloc_calls, calloc_0_calls;
270static unsigned long long int calloc_storage_request, calloc_storage_alloc;
271static unsigned int memalign_calls, memalign_0_calls;
272static unsigned long long int memalign_storage_request, memalign_storage_alloc;
273static unsigned int amemalign_calls, amemalign_0_calls;
274static unsigned long long int amemalign_storage_request, amemalign_storage_alloc;
275static unsigned int cmemalign_calls, cmemalign_0_calls;
276static unsigned long long int cmemalign_storage_request, cmemalign_storage_alloc;
277static unsigned int resize_calls, resize_0_calls;
278static unsigned long long int resize_storage_request, resize_storage_alloc;
279static unsigned int realloc_calls, realloc_0_calls;
280static unsigned long long int realloc_storage_request, realloc_storage_alloc;
281static unsigned int free_calls, free_null_calls;
282static unsigned long long int free_storage_request, free_storage_alloc;
283static unsigned int mmap_calls;
284static unsigned long long int mmap_storage_request, mmap_storage_alloc;
285static unsigned int munmap_calls;
286static unsigned long long int munmap_storage_request, munmap_storage_alloc;
287static unsigned int sbrk_calls;
288static unsigned long long int sbrk_storage;
289// Statistics file descriptor (changed by malloc_stats_fd).
290static int stats_fd = STDERR_FILENO;                                    // default stderr
291
292// Use "write" because streams may be shutdown when calls are made.
293static void printStats() {
294        char helpText[1024];
295        __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText),
296                                                                "\nHeap statistics: (storage request / allocation + header)\n"
297                                                                "  malloc    >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n"
298                                                                "  aalloc    >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n"
299                                                                "  calloc    >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n"
300                                                                "  memalign  >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n"
301                                                                "  amemalign >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n"
302                                                                "  cmemalign >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n"
303                                                                "  resize    >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n"
304                                                                "  realloc   >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n"
305                                                                "  free      !null calls %'u; null calls %'u; storage %'llu / %'llu bytes\n"
306                                                                "  sbrk      calls %'u; storage %'llu bytes\n"
307                                                                "  mmap      calls %'u; storage %'llu / %'llu bytes\n"
308                                                                "  munmap    calls %'u; storage %'llu / %'llu bytes\n",
309                                                                malloc_calls, malloc_0_calls, malloc_storage_request, malloc_storage_alloc,
310                                                                aalloc_calls, aalloc_0_calls, aalloc_storage_request, aalloc_storage_alloc,
311                                                                calloc_calls, calloc_0_calls, calloc_storage_request, calloc_storage_alloc,
312                                                                memalign_calls, memalign_0_calls, memalign_storage_request, memalign_storage_alloc,
313                                                                amemalign_calls, amemalign_0_calls, amemalign_storage_request, amemalign_storage_alloc,
314                                                                cmemalign_calls, cmemalign_0_calls, cmemalign_storage_request, cmemalign_storage_alloc,
315                                                                resize_calls, resize_0_calls, resize_storage_request, resize_storage_alloc,
316                                                                realloc_calls, realloc_0_calls, realloc_storage_request, realloc_storage_alloc,
317                                                                free_calls, free_null_calls, free_storage_request, free_storage_alloc,
318                                                                sbrk_calls, sbrk_storage,
319                                                                mmap_calls, mmap_storage_request, mmap_storage_alloc,
320                                                                munmap_calls, munmap_storage_request, munmap_storage_alloc
321                );
322} // printStats
323
324static int printStatsXML( FILE * stream ) {                             // see malloc_info
325        char helpText[1024];
326        int len = snprintf( helpText, sizeof(helpText),
327                                                "<malloc version=\"1\">\n"
328                                                "<heap nr=\"0\">\n"
329                                                "<sizes>\n"
330                                                "</sizes>\n"
331                                                "<total type=\"malloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n"
332                                                "<total type=\"aalloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n"
333                                                "<total type=\"calloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n"
334                                                "<total type=\"memalign\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n"
335                                                "<total type=\"amemalign\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n"
336                                                "<total type=\"cmemalign\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n"
337                                                "<total type=\"resize\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n"
338                                                "<total type=\"realloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n"
339                                                "<total type=\"free\" !null=\"%'u;\" 0 null=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n"
340                                                "<total type=\"sbrk\" count=\"%'u;\" size=\"%'llu\"/> bytes\n"
341                                                "<total type=\"mmap\" count=\"%'u;\" size=\"%'llu / %'llu\" / > bytes\n"
342                                                "<total type=\"munmap\" count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n"
343                                                "</malloc>",
344                                                malloc_calls, malloc_0_calls, malloc_storage_request, malloc_storage_alloc,
345                                                aalloc_calls, aalloc_0_calls, aalloc_storage_request, aalloc_storage_alloc,
346                                                calloc_calls, calloc_0_calls, calloc_storage_request, calloc_storage_alloc,
347                                                memalign_calls, memalign_0_calls, memalign_storage_request, memalign_storage_alloc,
348                                                amemalign_calls, amemalign_0_calls, amemalign_storage_request, amemalign_storage_alloc,
349                                                cmemalign_calls, cmemalign_0_calls, cmemalign_storage_request, cmemalign_storage_alloc,
350                                                resize_calls, resize_0_calls, resize_storage_request, resize_storage_alloc,
351                                                realloc_calls, realloc_0_calls, realloc_storage_request, realloc_storage_alloc,
352                                                free_calls, free_null_calls, free_storage_request, free_storage_alloc,
353                                                sbrk_calls, sbrk_storage,
354                                                mmap_calls, mmap_storage_request, mmap_storage_alloc,
355                                                munmap_calls, munmap_storage_request, munmap_storage_alloc
356                );
357        __cfaabi_bits_write( fileno( stream ), helpText, len ); // ensures all bytes written or exit
358        return len;
359} // printStatsXML
360#endif // __STATISTICS__
361
362
363// thunk problem
364size_t Bsearchl( unsigned int key, const unsigned int * vals, size_t dim ) {
365        size_t l = 0, m, h = dim;
366        while ( l < h ) {
367                m = (l + h) / 2;
368                if ( (unsigned int &)(vals[m]) < key ) {                // cast away const
369                        l = m + 1;
370                } else {
371                        h = m;
372                } // if
373        } // while
374        return l;
375} // Bsearchl
376
377
378static inline bool setMmapStart( size_t value ) {               // true => mmapped, false => sbrk
379  if ( value < __page_size || bucketSizes[NoBucketSizes - 1] < value ) return false;
380        mmapStart = value;                                                                      // set global
381
382        // find the closest bucket size less than or equal to the mmapStart size
383        maxBucketsUsed = Bsearchl( (unsigned int)mmapStart, bucketSizes, NoBucketSizes ); // binary search
384        assert( maxBucketsUsed < NoBucketSizes );                       // subscript failure ?
385        assert( mmapStart <= bucketSizes[maxBucketsUsed] ); // search failure ?
386        return true;
387} // setMmapStart
388
389
390// <-------+----------------------------------------------------> bsize (bucket size)
391// |header |addr
392//==================================================================================
393//                   align/offset |
394// <-----------------<------------+-----------------------------> bsize (bucket size)
395//                   |fake-header | addr
396#define headerAddr( addr ) ((HeapManager.Storage.Header *)( (char *)addr - sizeof(HeapManager.Storage) ))
397#define realHeader( header ) ((HeapManager.Storage.Header *)((char *)header - header->kind.fake.offset))
398
399// <-------<<--------------------- dsize ---------------------->> bsize (bucket size)
400// |header |addr
401//==================================================================================
402//                   align/offset |
403// <------------------------------<<---------- dsize --------->>> bsize (bucket size)
404//                   |fake-header |addr
405#define dataStorage( bsize, addr, header ) (bsize - ( (char *)addr - (char *)header ))
406
407
408static inline void checkAlign( size_t alignment ) {
409        if ( alignment < libAlign() || ! is_pow2( alignment ) ) {
410                abort( "Alignment %zu for memory allocation is less than %d and/or not a power of 2.", alignment, libAlign() );
411        } // if
412} // checkAlign
413
414
415static inline void checkHeader( bool check, const char name[], void * addr ) {
416        if ( unlikely( check ) ) {                                                      // bad address ?
417                abort( "Attempt to %s storage %p with address outside the heap.\n"
418                           "Possible cause is duplicate free on same block or overwriting of memory.",
419                           name, addr );
420        } // if
421} // checkHeader
422
423
424static inline void fakeHeader( HeapManager.Storage.Header *& header, size_t & alignment ) {
425        if ( unlikely( (header->kind.fake.alignment & 1) == 1 ) ) { // fake header ?
426                alignment = header->kind.fake.alignment & -2;   // remove flag from value
427                #ifdef __CFA_DEBUG__
428                checkAlign( alignment );                                                // check alignment
429                #endif // __CFA_DEBUG__
430                header = realHeader( header );                                  // backup from fake to real header
431        } else {
432                alignment = libAlign();                                                 // => no fake header
433        } // if
434} // fakeHeader
435
436
437static inline bool headers( const char name[] __attribute__(( unused )), void * addr, HeapManager.Storage.Header *& header, HeapManager.FreeHeader *& freeElem,
438                                                        size_t & size, size_t & alignment ) with( heapManager ) {
439        header = headerAddr( addr );
440
441  if ( unlikely( addr < heapBegin || heapEnd < addr ) ) { // mmapped ?
442                fakeHeader( header, alignment );
443                size = header->kind.real.blockSize & -3;                // mmap size
444                return true;
445        } // if
446
447        #ifdef __CFA_DEBUG__
448        checkHeader( header < (HeapManager.Storage.Header *)heapBegin, name, addr ); // bad low address ?
449        #endif // __CFA_DEBUG__
450
451        // header may be safe to dereference
452        fakeHeader( header, alignment );
453        #ifdef __CFA_DEBUG__
454        checkHeader( header < (HeapManager.Storage.Header *)heapBegin || (HeapManager.Storage.Header *)heapEnd < header, name, addr ); // bad address ? (offset could be + or -)
455        #endif // __CFA_DEBUG__
456
457        freeElem = (HeapManager.FreeHeader *)((size_t)header->kind.real.home & -3);
458        #ifdef __CFA_DEBUG__
459        if ( freeElem < &freeLists[0] || &freeLists[NoBucketSizes] <= freeElem ) {
460                abort( "Attempt to %s storage %p with corrupted header.\n"
461                           "Possible cause is duplicate free on same block or overwriting of header information.",
462                           name, addr );
463        } // if
464        #endif // __CFA_DEBUG__
465        size = freeElem->blockSize;
466        return false;
467} // headers
468
469// #ifdef __CFA_DEBUG__
470// #if __SIZEOF_POINTER__ == 4
471// #define MASK 0xdeadbeef
472// #else
473// #define MASK 0xdeadbeefdeadbeef
474// #endif
475// #define STRIDE size_t
476
477// static void * Memset( void * addr, STRIDE size ) {           // debug only
478//      if ( size % sizeof(STRIDE) != 0 ) abort( "Memset() : internal error, size %zd not multiple of %zd.", size, sizeof(STRIDE) );
479//      if ( (STRIDE)addr % sizeof(STRIDE) != 0 ) abort( "Memset() : internal error, addr %p not multiple of %zd.", addr, sizeof(STRIDE) );
480
481//      STRIDE * end = (STRIDE *)addr + size / sizeof(STRIDE);
482//      for ( STRIDE * p = (STRIDE *)addr; p < end; p += 1 ) *p = MASK;
483//      return addr;
484// } // Memset
485// #endif // __CFA_DEBUG__
486
487
488#define NO_MEMORY_MSG "insufficient heap memory available for allocating %zd new bytes."
489
490static inline void * extend( size_t size ) with( heapManager ) {
491        lock( extlock __cfaabi_dbg_ctx2 );
492        ptrdiff_t rem = heapRemaining - size;
493        if ( rem < 0 ) {
494                // If the size requested is bigger than the current remaining storage, increase the size of the heap.
495
496                size_t increase = ceiling2( size > heapExpand ? size : heapExpand, __page_size );
497                // Do not call abort or strerror( errno ) as they may call malloc.
498                if ( sbrk( increase ) == (void *)-1 ) {                 // failed, no memory ?
499                        unlock( extlock );
500                        __cfaabi_bits_print_nolock( STDERR_FILENO, NO_MEMORY_MSG, size );
501                        _exit( EXIT_FAILURE );                                          // give up
502                } // if
503                // Make storage executable for thunks.
504                if ( mprotect( (char *)heapEnd + heapRemaining, increase, __map_prot ) ) {
505                        unlock( extlock );
506                        __cfaabi_bits_print_nolock( STDERR_FILENO, "extend() : internal error, mprotect failure, heapEnd:%p size:%zd, errno:%d.\n", heapEnd, increase, errno );
507                        _exit( EXIT_FAILURE );
508                } // if
509                #ifdef __STATISTICS__
510                sbrk_calls += 1;
511                sbrk_storage += increase;
512                #endif // __STATISTICS__
513                #ifdef __CFA_DEBUG__
514                // Set new memory to garbage so subsequent uninitialized usages might fail.
515                memset( (char *)heapEnd + heapRemaining, '\xde', increase );
516                //Memset( (char *)heapEnd + heapRemaining, increase );
517                #endif // __CFA_DEBUG__
518                rem = heapRemaining + increase - size;
519        } // if
520
521        HeapManager.Storage * block = (HeapManager.Storage *)heapEnd;
522        heapRemaining = rem;
523        heapEnd = (char *)heapEnd + size;
524        unlock( extlock );
525        return block;
526} // extend
527
528
529static inline void * doMalloc( size_t size ) with( heapManager ) {
530        HeapManager.Storage * block;                                            // pointer to new block of storage
531
532        // Look up size in the size list.  Make sure the user request includes space for the header that must be allocated
533        // along with the block and is a multiple of the alignment size.
534
535  if ( unlikely( size > ULONG_MAX - sizeof(HeapManager.Storage) ) ) return 0p;
536        size_t tsize = size + sizeof(HeapManager.Storage);
537        if ( likely( tsize < mmapStart ) ) {                            // small size => sbrk
538                size_t posn;
539                #ifdef FASTLOOKUP
540                if ( tsize < LookupSizes ) posn = lookup[tsize];
541                else
542                #endif // FASTLOOKUP
543                        posn = Bsearchl( (unsigned int)tsize, bucketSizes, (size_t)maxBucketsUsed );
544                HeapManager.FreeHeader * freeElem = &freeLists[posn];
545                verify( freeElem <= &freeLists[maxBucketsUsed] ); // subscripting error ?
546                verify( tsize <= freeElem->blockSize );                 // search failure ?
547                tsize = freeElem->blockSize;                                    // total space needed for request
548
549                // Spin until the lock is acquired for this particular size of block.
550
551                #if BUCKETLOCK == SPINLOCK
552                lock( freeElem->lock __cfaabi_dbg_ctx2 );
553                block = freeElem->freeList;                                             // remove node from stack
554                #else
555                block = pop( freeElem->freeList );
556                #endif // BUCKETLOCK
557                if ( unlikely( block == 0p ) ) {                                // no free block ?
558                        #if BUCKETLOCK == SPINLOCK
559                        unlock( freeElem->lock );
560                        #endif // BUCKETLOCK
561
562                        // Freelist for that size was empty, so carve it out of the heap if there's enough left, or get some more
563                        // and then carve it off.
564
565                        block = (HeapManager.Storage *)extend( tsize ); // mutual exclusion on call
566                #if BUCKETLOCK == SPINLOCK
567                } else {
568                        freeElem->freeList = block->header.kind.real.next;
569                        unlock( freeElem->lock );
570                #endif // BUCKETLOCK
571                } // if
572
573                block->header.kind.real.home = freeElem;                // pointer back to free list of apropriate size
574        } else {                                                                                        // large size => mmap
575  if ( unlikely( size > ULONG_MAX - __page_size ) ) return 0p;
576                tsize = ceiling2( tsize, __page_size );                 // must be multiple of page size
577                #ifdef __STATISTICS__
578                __atomic_add_fetch( &mmap_calls, 1, __ATOMIC_SEQ_CST );
579                __atomic_add_fetch( &mmap_storage_request, size, __ATOMIC_SEQ_CST );
580                __atomic_add_fetch( &mmap_storage_alloc, tsize, __ATOMIC_SEQ_CST );
581                #endif // __STATISTICS__
582
583                block = (HeapManager.Storage *)mmap( 0, tsize, __map_prot, MAP_PRIVATE | MAP_ANONYMOUS, mmapFd, 0 );
584                if ( block == (HeapManager.Storage *)MAP_FAILED ) { // failed ?
585                        if ( errno == ENOMEM ) abort( NO_MEMORY_MSG, tsize ); // no memory
586                        // Do not call strerror( errno ) as it may call malloc.
587                        abort( "(HeapManager &)0x%p.doMalloc() : internal error, mmap failure, size:%zu errno:%d.", &heapManager, tsize, errno );
588                } //if
589                #ifdef __CFA_DEBUG__
590                // Set new memory to garbage so subsequent uninitialized usages might fail.
591                memset( block, '\xde', tsize );
592                //Memset( block, tsize );
593                #endif // __CFA_DEBUG__
594                block->header.kind.real.blockSize = tsize;              // storage size for munmap
595        } // if
596
597        block->header.kind.real.size = size;                            // store allocation size
598        void * addr = &(block->data);                                           // adjust off header to user bytes
599        verify( ((uintptr_t)addr & (libAlign() - 1)) == 0 ); // minimum alignment ?
600
601        #ifdef __CFA_DEBUG__
602        __atomic_add_fetch( &allocUnfreed, tsize, __ATOMIC_SEQ_CST );
603        if ( traceHeap() ) {
604                enum { BufferSize = 64 };
605                char helpText[BufferSize];
606                int len = snprintf( helpText, BufferSize, "%p = Malloc( %zu ) (allocated %zu)\n", addr, size, tsize );
607                __cfaabi_bits_write( STDERR_FILENO, helpText, len ); // print debug/nodebug
608        } // if
609        #endif // __CFA_DEBUG__
610
611        return addr;
612} // doMalloc
613
614
615static inline void doFree( void * addr ) with( heapManager ) {
616        #ifdef __CFA_DEBUG__
617        if ( unlikely( heapManager.heapBegin == 0p ) ) {
618                abort( "doFree( %p ) : internal error, called before heap is initialized.", addr );
619        } // if
620        #endif // __CFA_DEBUG__
621
622        HeapManager.Storage.Header * header;
623        HeapManager.FreeHeader * freeElem;
624        size_t size, alignment;                                                         // not used (see realloc)
625
626        if ( headers( "free", addr, header, freeElem, size, alignment ) ) { // mmapped ?
627                #ifdef __STATISTICS__
628                __atomic_add_fetch( &munmap_calls, 1, __ATOMIC_SEQ_CST );
629                __atomic_add_fetch( &munmap_storage_request, header->kind.real.size, __ATOMIC_SEQ_CST );
630                __atomic_add_fetch( &munmap_storage_alloc, size, __ATOMIC_SEQ_CST );
631                #endif // __STATISTICS__
632                if ( munmap( header, size ) == -1 ) {
633                        abort( "Attempt to deallocate storage %p not allocated or with corrupt header.\n"
634                                   "Possible cause is invalid pointer.",
635                                   addr );
636                } // if
637        } else {
638                #ifdef __CFA_DEBUG__
639                // Set free memory to garbage so subsequent usages might fail.
640                memset( ((HeapManager.Storage *)header)->data, '\xde', freeElem->blockSize - sizeof( HeapManager.Storage ) );
641                //Memset( ((HeapManager.Storage *)header)->data, freeElem->blockSize - sizeof( HeapManager.Storage ) );
642                #endif // __CFA_DEBUG__
643
644                #ifdef __STATISTICS__
645                __atomic_add_fetch( &free_calls, 1, __ATOMIC_SEQ_CST );
646                __atomic_add_fetch( &free_storage_request, header->kind.real.size, __ATOMIC_SEQ_CST );
647                __atomic_add_fetch( &free_storage_alloc, size, __ATOMIC_SEQ_CST );
648                #endif // __STATISTICS__
649
650                #if BUCKETLOCK == SPINLOCK
651                lock( freeElem->lock __cfaabi_dbg_ctx2 );               // acquire spin lock
652                header->kind.real.next = freeElem->freeList;    // push on stack
653                freeElem->freeList = (HeapManager.Storage *)header;
654                unlock( freeElem->lock );                                               // release spin lock
655                #else
656                push( freeElem->freeList, *(HeapManager.Storage *)header );
657                #endif // BUCKETLOCK
658        } // if
659
660        #ifdef __CFA_DEBUG__
661        __atomic_add_fetch( &allocUnfreed, -size, __ATOMIC_SEQ_CST );
662        if ( traceHeap() ) {
663                char helpText[64];
664                int len = snprintf( helpText, sizeof(helpText), "Free( %p ) size:%zu\n", addr, size );
665                __cfaabi_bits_write( STDERR_FILENO, helpText, len ); // print debug/nodebug
666        } // if
667        #endif // __CFA_DEBUG__
668} // doFree
669
670
671size_t prtFree( HeapManager & manager ) with( manager ) {
672        size_t total = 0;
673        #ifdef __STATISTICS__
674        __cfaabi_bits_acquire();
675        __cfaabi_bits_print_nolock( STDERR_FILENO, "\nBin lists (bin size : free blocks on list)\n" );
676        #endif // __STATISTICS__
677        for ( unsigned int i = 0; i < maxBucketsUsed; i += 1 ) {
678                size_t size = freeLists[i].blockSize;
679                #ifdef __STATISTICS__
680                unsigned int N = 0;
681                #endif // __STATISTICS__
682
683                #if BUCKETLOCK == SPINLOCK
684                for ( HeapManager.Storage * p = freeLists[i].freeList; p != 0p; p = p->header.kind.real.next ) {
685                #else
686                        for(;;) {
687//              for ( HeapManager.Storage * p = top( freeLists[i].freeList ); p != 0p; p = (p)`next->top ) {
688//              for ( HeapManager.Storage * p = top( freeLists[i].freeList ); p != 0p; /* p = getNext( p )->top */) {
689//                      HeapManager.Storage * temp = p->header.kind.real.next.top; // FIX ME: direct assignent fails, initialization works`
690//                      typeof(p) temp = (( p )`next)->top;                     // FIX ME: direct assignent fails, initialization works`
691//                      p = temp;
692                #endif // BUCKETLOCK
693                        total += size;
694                        #ifdef __STATISTICS__
695                        N += 1;
696                        #endif // __STATISTICS__
697                } // for
698
699                #ifdef __STATISTICS__
700                __cfaabi_bits_print_nolock( STDERR_FILENO, "%7zu, %-7u  ", size, N );
701                if ( (i + 1) % 8 == 0 ) __cfaabi_bits_print_nolock( STDERR_FILENO, "\n" );
702                #endif // __STATISTICS__
703        } // for
704        #ifdef __STATISTICS__
705        __cfaabi_bits_print_nolock( STDERR_FILENO, "\ntotal free blocks:%zu\n", total );
706        __cfaabi_bits_release();
707        #endif // __STATISTICS__
708        return (char *)heapEnd - (char *)heapBegin - total;
709} // prtFree
710
711
712static void ?{}( HeapManager & manager ) with( manager ) {
713        __page_size = sysconf( _SC_PAGESIZE );
714        __map_prot = PROT_READ | PROT_WRITE | PROT_EXEC;
715
716        for ( unsigned int i = 0; i < NoBucketSizes; i += 1 ) { // initialize the free lists
717                freeLists[i].blockSize = bucketSizes[i];
718        } // for
719
720        #ifdef FASTLOOKUP
721        unsigned int idx = 0;
722        for ( unsigned int i = 0; i < LookupSizes; i += 1 ) {
723                if ( i > bucketSizes[idx] ) idx += 1;
724                lookup[i] = idx;
725        } // for
726        #endif // FASTLOOKUP
727
728        if ( ! setMmapStart( default_mmap_start() ) ) {
729                abort( "HeapManager : internal error, mmap start initialization failure." );
730        } // if
731        heapExpand = default_heap_expansion();
732
733        char * end = (char *)sbrk( 0 );
734        heapBegin = heapEnd = sbrk( (char *)ceiling2( (long unsigned int)end, __page_size ) - end ); // move start of heap to multiple of alignment
735} // HeapManager
736
737
738static void ^?{}( HeapManager & ) {
739        #ifdef __STATISTICS__
740        if ( traceHeapTerm() ) {
741                printStats();
742                // prtUnfreed() called in heapAppStop()
743        } // if
744        #endif // __STATISTICS__
745} // ~HeapManager
746
747
748static void memory_startup( void ) __attribute__(( constructor( STARTUP_PRIORITY_MEMORY ) ));
749void memory_startup( void ) {
750        #ifdef __CFA_DEBUG__
751        if ( heapBoot ) {                                                                       // check for recursion during system boot
752                abort( "boot() : internal error, recursively invoked during system boot." );
753        } // if
754        heapBoot = true;
755        #endif // __CFA_DEBUG__
756
757        //verify( heapManager.heapBegin != 0 );
758        //heapManager{};
759        if ( heapManager.heapBegin == 0p ) heapManager{};       // sanity check
760} // memory_startup
761
762static void memory_shutdown( void ) __attribute__(( destructor( STARTUP_PRIORITY_MEMORY ) ));
763void memory_shutdown( void ) {
764        ^heapManager{};
765} // memory_shutdown
766
767
768static inline void * mallocNoStats( size_t size ) {             // necessary for malloc statistics
769        verify( heapManager.heapBegin != 0p );                          // called before memory_startup ?
770  if ( unlikely( size ) == 0 ) return 0p;                               // 0 BYTE ALLOCATION RETURNS NULL POINTER
771
772#if __SIZEOF_POINTER__ == 8
773        verify( size < ((typeof(size_t))1 << 48) );
774#endif // __SIZEOF_POINTER__ == 8
775        return doMalloc( size );
776} // mallocNoStats
777
778
779static inline void * memalignNoStats( size_t alignment, size_t size ) {
780  if ( unlikely( size ) == 0 ) return 0p;                               // 0 BYTE ALLOCATION RETURNS NULL POINTER
781
782        #ifdef __CFA_DEBUG__
783        checkAlign( alignment );                                                        // check alignment
784        #endif // __CFA_DEBUG__
785
786        // if alignment <= default alignment, do normal malloc as two headers are unnecessary
787  if ( unlikely( alignment <= libAlign() ) ) return mallocNoStats( size );
788
789        // Allocate enough storage to guarantee an address on the alignment boundary, and sufficient space before it for
790        // administrative storage. NOTE, WHILE THERE ARE 2 HEADERS, THE FIRST ONE IS IMPLICITLY CREATED BY DOMALLOC.
791        //      .-------------v-----------------v----------------v----------,
792        //      | Real Header | ... padding ... |   Fake Header  | data ... |
793        //      `-------------^-----------------^-+--------------^----------'
794        //      |<--------------------------------' offset/align |<-- alignment boundary
795
796        // subtract libAlign() because it is already the minimum alignment
797        // add sizeof(Storage) for fake header
798        char * addr = (char *)mallocNoStats( size + alignment - libAlign() + sizeof(HeapManager.Storage) );
799
800        // address in the block of the "next" alignment address
801        char * user = (char *)ceiling2( (uintptr_t)(addr + sizeof(HeapManager.Storage)), alignment );
802
803        // address of header from malloc
804        HeapManager.Storage.Header * realHeader = headerAddr( addr );
805        realHeader->kind.real.size = size;                                      // correct size to eliminate above alignment offset
806        // address of fake header * before* the alignment location
807        HeapManager.Storage.Header * fakeHeader = headerAddr( user );
808        // SKULLDUGGERY: insert the offset to the start of the actual storage block and remember alignment
809        fakeHeader->kind.fake.offset = (char *)fakeHeader - (char *)realHeader;
810        // SKULLDUGGERY: odd alignment imples fake header
811        fakeHeader->kind.fake.alignment = alignment | 1;
812
813        return user;
814} // memalignNoStats
815
816
817extern "C" {
818        // Allocates size bytes and returns a pointer to the allocated memory.  The contents are undefined. If size is 0,
819        // then malloc() returns a unique pointer value that can later be successfully passed to free().
820        void * malloc( size_t size ) {
821                #ifdef __STATISTICS__
822                if ( likely( size > 0 ) ) {
823                        __atomic_add_fetch( &malloc_calls, 1, __ATOMIC_SEQ_CST );
824                        __atomic_add_fetch( &malloc_storage_request, size, __ATOMIC_SEQ_CST );
825                } else {
826                        __atomic_add_fetch( &malloc_0_calls, 1, __ATOMIC_SEQ_CST );
827                } // if
828                #endif // __STATISTICS__
829
830                return mallocNoStats( size );
831        } // malloc
832
833
834        // Same as malloc() except size bytes is an array of dim elements each of elemSize bytes.
835        void * aalloc( size_t dim, size_t elemSize ) {
836                size_t size = dim * elemSize;
837                #ifdef __STATISTICS__
838                if ( likely( size > 0 ) ) {
839                        __atomic_add_fetch( &aalloc_calls, 1, __ATOMIC_SEQ_CST );
840                        __atomic_add_fetch( &aalloc_storage_request, size, __ATOMIC_SEQ_CST );
841                } else {
842                        __atomic_add_fetch( &aalloc_0_calls, 1, __ATOMIC_SEQ_CST );
843                } // if
844                #endif // __STATISTICS__
845
846                return mallocNoStats( size );
847        } // aalloc
848
849
850        // Same as aalloc() with memory set to zero.
851        void * calloc( size_t dim, size_t elemSize ) {
852                size_t size = dim * elemSize;
853          if ( unlikely( size ) == 0 ) {                        // 0 BYTE ALLOCATION RETURNS NULL POINTER
854                        #ifdef __STATISTICS__
855                        __atomic_add_fetch( &calloc_0_calls, 1, __ATOMIC_SEQ_CST );
856                        #endif // __STATISTICS__
857                        return 0p;
858                } // if
859                #ifdef __STATISTICS__
860                __atomic_add_fetch( &calloc_calls, 1, __ATOMIC_SEQ_CST );
861                __atomic_add_fetch( &calloc_storage_request, dim * elemSize, __ATOMIC_SEQ_CST );
862                #endif // __STATISTICS__
863
864                char * addr = (char *)mallocNoStats( size );
865
866                HeapManager.Storage.Header * header;
867                HeapManager.FreeHeader * freeElem;
868                size_t bsize, alignment;
869
870                #ifndef __CFA_DEBUG__
871                bool mapped =
872                        #endif // __CFA_DEBUG__
873                        headers( "calloc", addr, header, freeElem, bsize, alignment );
874
875                #ifndef __CFA_DEBUG__
876                // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
877                if ( ! mapped )
878                #endif // __CFA_DEBUG__
879                        // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined
880                        // `-header`-addr                      `-size
881                        memset( addr, '\0', size );                                     // set to zeros
882
883                header->kind.real.blockSize |= 2;                               // mark as zero filled
884                return addr;
885        } // calloc
886
887
888        // Change the size of the memory block pointed to by oaddr to size bytes. The contents are undefined.  If oaddr is
889        // 0p, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and oaddr is
890        // not 0p, then the call is equivalent to free(oaddr). Unless oaddr is 0p, it must have been returned by an earlier
891        // call to malloc(), alloc(), calloc() or realloc(). If the area pointed to was moved, a free(oaddr) is done.
892        void * resize( void * oaddr, size_t size ) {
893                // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
894          if ( unlikely( size == 0 ) ) {                                        // special cases
895                        #ifdef __STATISTICS__
896                        __atomic_add_fetch( &resize_0_calls, 1, __ATOMIC_SEQ_CST );
897                        #endif // __STATISTICS__
898                        free( oaddr );
899                        return 0p;
900                } // if
901                #ifdef __STATISTICS__
902                __atomic_add_fetch( &resize_calls, 1, __ATOMIC_SEQ_CST );
903                #endif // __STATISTICS__
904
905          if ( unlikely( oaddr == 0p ) ) {
906                        #ifdef __STATISTICS__
907                        __atomic_add_fetch( &resize_storage_request, size, __ATOMIC_SEQ_CST );
908                        #endif // __STATISTICS__
909                        return mallocNoStats( size );
910                } // if
911
912                HeapManager.Storage.Header * header;
913                HeapManager.FreeHeader * freeElem;
914                size_t bsize, oalign;
915                headers( "resize", oaddr, header, freeElem, bsize, oalign );
916
917                size_t odsize = dataStorage( bsize, oaddr, header ); // data storage available in bucket
918                // same size, DO NOT preserve STICKY PROPERTIES.
919                if ( oalign == libAlign() && size <= odsize && odsize <= size * 2 ) { // allow 50% wasted storage for smaller size
920                        header->kind.real.blockSize &= -2;                      // no alignment and turn off 0 fill
921                        header->kind.real.size = size;                          // reset allocation size
922                        return oaddr;
923                } // if
924
925                #ifdef __STATISTICS__
926                __atomic_add_fetch( &resize_storage_request, size, __ATOMIC_SEQ_CST );
927                #endif // __STATISTICS__
928
929                // change size, DO NOT preserve STICKY PROPERTIES.
930                free( oaddr );
931                return mallocNoStats( size );                                   // create new area
932        } // resize
933
934
935        // Same as resize() but the contents are unchanged in the range from the start of the region up to the minimum of
936        // the old and new sizes.
937        void * realloc( void * oaddr, size_t size ) {
938                // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
939          if ( unlikely( size == 0 ) ) {                                        // special cases
940                        #ifdef __STATISTICS__
941                        __atomic_add_fetch( &realloc_0_calls, 1, __ATOMIC_SEQ_CST );
942                        #endif // __STATISTICS__
943                        free( oaddr );
944                        return 0p;
945                } // if
946                #ifdef __STATISTICS__
947                __atomic_add_fetch( &realloc_calls, 1, __ATOMIC_SEQ_CST );
948                #endif // __STATISTICS__
949
950          if ( unlikely( oaddr == 0p ) ) {
951                        #ifdef __STATISTICS__
952                        __atomic_add_fetch( &realloc_storage_request, size, __ATOMIC_SEQ_CST );
953                        #endif // __STATISTICS__
954                        return mallocNoStats( size );
955                } // if
956
957                HeapManager.Storage.Header * header;
958                HeapManager.FreeHeader * freeElem;
959                size_t bsize, oalign;
960                headers( "realloc", oaddr, header, freeElem, bsize, oalign );
961
962                size_t odsize = dataStorage( bsize, oaddr, header ); // data storage available in bucket
963                size_t osize = header->kind.real.size;                  // old allocation size
964                bool ozfill = (header->kind.real.blockSize & 2); // old allocation zero filled
965          if ( unlikely( size <= odsize ) && odsize <= size * 2 ) { // allow up to 50% wasted storage
966                        header->kind.real.size = size;                          // reset allocation size
967                        if ( unlikely( ozfill ) && size > osize ) {     // previous request zero fill and larger ?
968                                memset( (char *)oaddr + osize, '\0', size - osize ); // initialize added storage
969                        } // if
970                        return oaddr;
971                } // if
972
973                #ifdef __STATISTICS__
974                __atomic_add_fetch( &realloc_storage_request, size, __ATOMIC_SEQ_CST );
975                #endif // __STATISTICS__
976
977                // change size and copy old content to new storage
978
979                void * naddr;
980                if ( likely( oalign == libAlign() ) ) {                 // previous request not aligned ?
981                        naddr = mallocNoStats( size );                          // create new area
982                } else {
983                        naddr = memalignNoStats( oalign, size );        // create new aligned area
984                } // if
985
986                headers( "realloc", naddr, header, freeElem, bsize, oalign );
987                memcpy( naddr, oaddr, min( osize, size ) );             // copy bytes
988                free( oaddr );
989
990                if ( unlikely( ozfill ) ) {                                             // previous request zero fill ?
991                        header->kind.real.blockSize |= 2;                       // mark new request as zero filled
992                        if ( size > osize ) {                                           // previous request larger ?
993                                memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage
994                        } // if
995                } // if
996                return naddr;
997        } // realloc
998
999
1000        // Same as malloc() except the memory address is a multiple of alignment, which must be a power of two. (obsolete)
1001        void * memalign( size_t alignment, size_t size ) {
1002                #ifdef __STATISTICS__
1003                if ( likely( size > 0 ) ) {
1004                        __atomic_add_fetch( &memalign_calls, 1, __ATOMIC_SEQ_CST );
1005                        __atomic_add_fetch( &memalign_storage_request, size, __ATOMIC_SEQ_CST );
1006                } else {
1007                        __atomic_add_fetch( &memalign_0_calls, 1, __ATOMIC_SEQ_CST );
1008                } // if
1009                #endif // __STATISTICS__
1010
1011                return memalignNoStats( alignment, size );
1012        } // memalign
1013
1014
1015        // Same as aalloc() with memory alignment.
1016        void * amemalign( size_t alignment, size_t dim, size_t elemSize ) {
1017                size_t size = dim * elemSize;
1018                #ifdef __STATISTICS__
1019                if ( likely( size > 0 ) ) {
1020                        __atomic_add_fetch( &cmemalign_calls, 1, __ATOMIC_SEQ_CST );
1021                        __atomic_add_fetch( &cmemalign_storage_request, size, __ATOMIC_SEQ_CST );
1022                } else {
1023                        __atomic_add_fetch( &cmemalign_0_calls, 1, __ATOMIC_SEQ_CST );
1024                } // if
1025                #endif // __STATISTICS__
1026
1027                return memalignNoStats( alignment, size );
1028        } // amemalign
1029
1030
1031        // Same as calloc() with memory alignment.
1032        void * cmemalign( size_t alignment, size_t dim, size_t elemSize ) {
1033                size_t size = dim * elemSize;
1034          if ( unlikely( size ) == 0 ) {                                        // 0 BYTE ALLOCATION RETURNS NULL POINTER
1035                        #ifdef __STATISTICS__
1036                        __atomic_add_fetch( &cmemalign_0_calls, 1, __ATOMIC_SEQ_CST );
1037                        #endif // __STATISTICS__
1038                        return 0p;
1039                } // if
1040                #ifdef __STATISTICS__
1041                __atomic_add_fetch( &cmemalign_calls, 1, __ATOMIC_SEQ_CST );
1042                __atomic_add_fetch( &cmemalign_storage_request, dim * elemSize, __ATOMIC_SEQ_CST );
1043                #endif // __STATISTICS__
1044
1045                char * addr = (char *)memalignNoStats( alignment, size );
1046
1047                HeapManager.Storage.Header * header;
1048                HeapManager.FreeHeader * freeElem;
1049                size_t bsize;
1050
1051                #ifndef __CFA_DEBUG__
1052                bool mapped =
1053                        #endif // __CFA_DEBUG__
1054                        headers( "cmemalign", addr, header, freeElem, bsize, alignment );
1055
1056                // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
1057                #ifndef __CFA_DEBUG__
1058                if ( ! mapped )
1059                #endif // __CFA_DEBUG__
1060                        // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined
1061                        // `-header`-addr                      `-size
1062                        memset( addr, '\0', size );                                     // set to zeros
1063
1064                header->kind.real.blockSize |= 2;                               // mark as zero filled
1065                return addr;
1066        } // cmemalign
1067
1068
1069        // Same as memalign(), but ISO/IEC 2011 C11 Section 7.22.2 states: the value of size shall be an integral multiple
1070    // of alignment. This requirement is universally ignored.
1071        void * aligned_alloc( size_t alignment, size_t size ) {
1072                return memalign( alignment, size );
1073        } // aligned_alloc
1074
1075
1076        // Allocates size bytes and places the address of the allocated memory in *memptr. The address of the allocated
1077        // memory shall be a multiple of alignment, which must be a power of two and a multiple of sizeof(void *). If size
1078        // is 0, then posix_memalign() returns either 0p, or a unique pointer value that can later be successfully passed to
1079        // free(3).
1080        int posix_memalign( void ** memptr, size_t alignment, size_t size ) {
1081          if ( alignment < libAlign() || ! is_pow2( alignment ) ) return EINVAL; // check alignment
1082                * memptr = memalign( alignment, size );
1083                return 0;
1084        } // posix_memalign
1085
1086
1087        // Allocates size bytes and returns a pointer to the allocated memory. The memory address shall be a multiple of the
1088        // page size.  It is equivalent to memalign(sysconf(_SC_PAGESIZE),size).
1089        void * valloc( size_t size ) {
1090                return memalign( __page_size, size );
1091        } // valloc
1092
1093
1094        // Same as valloc but rounds size to multiple of page size.
1095        void * pvalloc( size_t size ) {
1096                return memalign( __page_size, ceiling2( size, __page_size ) );
1097        } // pvalloc
1098
1099
1100        // Frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc()
1101        // or realloc().  Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is
1102        // 0p, no operation is performed.
1103        void free( void * addr ) {
1104          if ( unlikely( addr == 0p ) ) {                                       // special case
1105                        #ifdef __STATISTICS__
1106                        __atomic_add_fetch( &free_null_calls, 1, __ATOMIC_SEQ_CST );
1107                        #endif // __STATISTICS__
1108
1109                        // #ifdef __CFA_DEBUG__
1110                        // if ( traceHeap() ) {
1111                        //      #define nullmsg "Free( 0x0 ) size:0\n"
1112                        //      // Do not debug print free( 0p ), as it can cause recursive entry from sprintf.
1113                        //      __cfaabi_dbg_write( nullmsg, sizeof(nullmsg) - 1 );
1114                        // } // if
1115                        // #endif // __CFA_DEBUG__
1116                        return;
1117                } // exit
1118
1119                doFree( addr );
1120        } // free
1121
1122
1123        // Returns the alignment of an allocation.
1124        size_t malloc_alignment( void * addr ) {
1125          if ( unlikely( addr == 0p ) ) return libAlign();      // minimum alignment
1126                HeapManager.Storage.Header * header = headerAddr( addr );
1127                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
1128                        return header->kind.fake.alignment & -2;        // remove flag from value
1129                } else {
1130                        return libAlign();                                                      // minimum alignment
1131                } // if
1132        } // malloc_alignment
1133
1134
1135        // Set the alignment for an the allocation and return previous alignment or 0 if no alignment.
1136        size_t malloc_alignment_set$( void * addr, size_t alignment ) {
1137          if ( unlikely( addr == 0p ) ) return libAlign();      // minimum alignment
1138                size_t ret;
1139                HeapManager.Storage.Header * header = headerAddr( addr );
1140                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
1141                        ret = header->kind.fake.alignment & -2;         // remove flag from old value
1142                        header->kind.fake.alignment = alignment | 1; // add flag to new value
1143                } else {
1144                        ret = 0;                                                                        // => no alignment to change
1145                } // if
1146                return ret;
1147        } // malloc_alignment_set$
1148
1149
1150        // Returns true if the allocation is zero filled, e.g., allocated by calloc().
1151        bool malloc_zero_fill( void * addr ) {
1152          if ( unlikely( addr == 0p ) ) return false;           // null allocation is not zero fill
1153                HeapManager.Storage.Header * header = headerAddr( addr );
1154                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
1155                        header = realHeader( header );                          // backup from fake to real header
1156                } // if
1157                return (header->kind.real.blockSize & 2) != 0;  // zero filled ?
1158        } // malloc_zero_fill
1159
1160        // Set allocation is zero filled and return previous zero filled.
1161        bool malloc_zero_fill_set$( void * addr ) {
1162          if ( unlikely( addr == 0p ) ) return false;           // null allocation is not zero fill
1163                HeapManager.Storage.Header * header = headerAddr( addr );
1164                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
1165                        header = realHeader( header );                          // backup from fake to real header
1166                } // if
1167                bool ret = (header->kind.real.blockSize & 2) != 0; // zero filled ?
1168                header->kind.real.blockSize |= 2;                               // mark as zero filled
1169                return ret;
1170        } // malloc_zero_fill_set$
1171
1172
1173        // Returns original total allocation size (not bucket size) => array size is dimension * sizeif(T).
1174        size_t malloc_size( void * addr ) {
1175          if ( unlikely( addr == 0p ) ) return 0;                       // null allocation has zero size
1176                HeapManager.Storage.Header * header = headerAddr( addr );
1177                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
1178                        header = realHeader( header );                          // backup from fake to real header
1179                } // if
1180                return header->kind.real.size;
1181        } // malloc_size
1182
1183        // Set allocation size and return previous size.
1184        size_t malloc_size_set$( void * addr, size_t size ) {
1185          if ( unlikely( addr == 0p ) ) return 0;                       // null allocation has 0 size
1186                HeapManager.Storage.Header * header = headerAddr( addr );
1187                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
1188                        header = realHeader( header );                          // backup from fake to real header
1189                } // if
1190                size_t ret = header->kind.real.size;
1191                header->kind.real.size = size;
1192                return ret;
1193        } // malloc_size_set$
1194
1195
1196        // Returns the number of usable bytes in the block pointed to by ptr, a pointer to a block of memory allocated by
1197        // malloc or a related function.
1198        size_t malloc_usable_size( void * addr ) {
1199          if ( unlikely( addr == 0p ) ) return 0;                       // null allocation has 0 size
1200                HeapManager.Storage.Header * header;
1201                HeapManager.FreeHeader * freeElem;
1202                size_t bsize, alignment;
1203
1204                headers( "malloc_usable_size", addr, header, freeElem, bsize, alignment );
1205                return dataStorage( bsize, addr, header );              // data storage in bucket
1206        } // malloc_usable_size
1207
1208
1209        // Prints (on default standard error) statistics about memory allocated by malloc and related functions.
1210        void malloc_stats( void ) {
1211                #ifdef __STATISTICS__
1212                printStats();
1213                if ( prtFree() ) prtFree( heapManager );
1214                #endif // __STATISTICS__
1215        } // malloc_stats
1216
1217
1218        // Changes the file descripter where malloc_stats() writes statistics.
1219        int malloc_stats_fd( int fd __attribute__(( unused )) ) {
1220                #ifdef __STATISTICS__
1221                int temp = stats_fd;
1222                stats_fd = fd;
1223                return temp;
1224                #else
1225                return -1;
1226                #endif // __STATISTICS__
1227        } // malloc_stats_fd
1228
1229
1230        // Adjusts parameters that control the behaviour of the memory-allocation functions (see malloc). The param argument
1231        // specifies the parameter to be modified, and value specifies the new value for that parameter.
1232        int mallopt( int option, int value ) {
1233                choose( option ) {
1234                  case M_TOP_PAD:
1235                        heapExpand = ceiling2( value, __page_size ); return 1;
1236                  case M_MMAP_THRESHOLD:
1237                        if ( setMmapStart( value ) ) return 1;
1238                        break;
1239                } // switch
1240                return 0;                                                                               // error, unsupported
1241        } // mallopt
1242
1243
1244        // Attempt to release free memory at the top of the heap (by calling sbrk with a suitable argument).
1245        int malloc_trim( size_t ) {
1246                return 0;                                                                               // => impossible to release memory
1247        } // malloc_trim
1248
1249
1250        // Exports an XML string that describes the current state of the memory-allocation implementation in the caller.
1251        // The string is printed on the file stream stream.  The exported string includes information about all arenas (see
1252        // malloc).
1253        int malloc_info( int options, FILE * stream __attribute__(( unused )) ) {
1254          if ( options != 0 ) { errno = EINVAL; return -1; }
1255                #ifdef __STATISTICS__
1256                return printStatsXML( stream );
1257                #else
1258                return 0;                                                                               // unsupported
1259                #endif // __STATISTICS__
1260        } // malloc_info
1261
1262
1263        // Records the current state of all malloc internal bookkeeping variables (but not the actual contents of the heap
1264        // or the state of malloc_hook functions pointers).  The state is recorded in a system-dependent opaque data
1265        // structure dynamically allocated via malloc, and a pointer to that data structure is returned as the function
1266        // result.  (The caller must free this memory.)
1267        void * malloc_get_state( void ) {
1268                return 0p;                                                                              // unsupported
1269        } // malloc_get_state
1270
1271
1272        // Restores the state of all malloc internal bookkeeping variables to the values recorded in the opaque data
1273        // structure pointed to by state.
1274        int malloc_set_state( void * ) {
1275                return 0;                                                                               // unsupported
1276        } // malloc_set_state
1277} // extern "C"
1278
1279
1280// Must have CFA linkage to overload with C linkage realloc.
1281void * resize( void * oaddr, size_t nalign, size_t size ) {
1282        // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
1283  if ( unlikely( size == 0 ) ) {                                                // special cases
1284                #ifdef __STATISTICS__
1285                __atomic_add_fetch( &resize_0_calls, 1, __ATOMIC_SEQ_CST );
1286                #endif // __STATISTICS__
1287                free( oaddr );
1288                return 0p;
1289        } // if
1290
1291        if ( unlikely( nalign < libAlign() ) ) nalign = libAlign(); // reset alignment to minimum
1292        #ifdef __CFA_DEBUG__
1293        else checkAlign( nalign );                                                      // check alignment
1294        #endif // __CFA_DEBUG__
1295
1296  if ( unlikely( oaddr == 0p ) ) {
1297                #ifdef __STATISTICS__
1298                __atomic_add_fetch( &resize_calls, 1, __ATOMIC_SEQ_CST );
1299                __atomic_add_fetch( &resize_storage_request, size, __ATOMIC_SEQ_CST );
1300                #endif // __STATISTICS__
1301                return memalignNoStats( nalign, size );
1302        } // if
1303
1304        // Attempt to reuse existing alignment.
1305        HeapManager.Storage.Header * header = headerAddr( oaddr );
1306        bool isFakeHeader = header->kind.fake.alignment & 1; // old fake header ?
1307        size_t oalign;
1308        if ( isFakeHeader ) {
1309                oalign = header->kind.fake.alignment & -2;              // old alignment
1310                if ( (uintptr_t)oaddr % nalign == 0                             // lucky match ?
1311                         && ( oalign <= nalign                                          // going down
1312                                  || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ?
1313                        ) {
1314                        headerAddr( oaddr )->kind.fake.alignment = nalign | 1; // update alignment (could be the same)
1315                        HeapManager.FreeHeader * freeElem;
1316                        size_t bsize, oalign;
1317                        headers( "resize", oaddr, header, freeElem, bsize, oalign );
1318                        size_t odsize = dataStorage( bsize, oaddr, header ); // data storage available in bucket
1319
1320                        if ( size <= odsize && odsize <= size * 2 ) { // allow 50% wasted data storage
1321                                headerAddr( oaddr )->kind.fake.alignment = nalign | 1; // update alignment (could be the same)
1322
1323                                header->kind.real.blockSize &= -2;              // turn off 0 fill
1324                                header->kind.real.size = size;                  // reset allocation size
1325                                return oaddr;
1326                        } // if
1327                } // if
1328        } else if ( ! isFakeHeader                                                      // old real header (aligned on libAlign) ?
1329                                && nalign == libAlign() ) {                             // new alignment also on libAlign => no fake header needed
1330                return resize( oaddr, size );                                   // duplicate special case checks
1331        } // if
1332
1333        #ifdef __STATISTICS__
1334        __atomic_add_fetch( &resize_storage_request, size, __ATOMIC_SEQ_CST );
1335        #endif // __STATISTICS__
1336
1337        // change size, DO NOT preserve STICKY PROPERTIES.
1338        free( oaddr );
1339        return memalignNoStats( nalign, size );                         // create new aligned area
1340} // resize
1341
1342
1343void * realloc( void * oaddr, size_t nalign, size_t size ) {
1344        // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
1345  if ( unlikely( size == 0 ) ) {                                                // special cases
1346                #ifdef __STATISTICS__
1347                __atomic_add_fetch( &realloc_0_calls, 1, __ATOMIC_SEQ_CST );
1348                #endif // __STATISTICS__
1349                free( oaddr );
1350                return 0p;
1351        } // if
1352
1353        if ( unlikely( nalign < libAlign() ) ) nalign = libAlign(); // reset alignment to minimum
1354        #ifdef __CFA_DEBUG__
1355        else checkAlign( nalign );                                                      // check alignment
1356        #endif // __CFA_DEBUG__
1357
1358  if ( unlikely( oaddr == 0p ) ) {
1359                #ifdef __STATISTICS__
1360                __atomic_add_fetch( &realloc_calls, 1, __ATOMIC_SEQ_CST );
1361                __atomic_add_fetch( &realloc_storage_request, size, __ATOMIC_SEQ_CST );
1362                #endif // __STATISTICS__
1363                return memalignNoStats( nalign, size );
1364        } // if
1365
1366        // Attempt to reuse existing alignment.
1367        HeapManager.Storage.Header * header = headerAddr( oaddr );
1368        bool isFakeHeader = header->kind.fake.alignment & 1; // old fake header ?
1369        size_t oalign;
1370        if ( isFakeHeader ) {
1371                oalign = header->kind.fake.alignment & -2;              // old alignment
1372                if ( (uintptr_t)oaddr % nalign == 0                             // lucky match ?
1373                         && ( oalign <= nalign                                          // going down
1374                                  || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ?
1375                        ) {
1376                        headerAddr( oaddr )->kind.fake.alignment = nalign | 1; // update alignment (could be the same)
1377                        return realloc( oaddr, size );                          // duplicate alignment and special case checks
1378                } // if
1379        } else if ( ! isFakeHeader                                                      // old real header (aligned on libAlign) ?
1380                                && nalign == libAlign() )                               // new alignment also on libAlign => no fake header needed
1381                return realloc( oaddr, size );                                  // duplicate alignment and special case checks
1382
1383        #ifdef __STATISTICS__
1384        __atomic_add_fetch( &realloc_calls, 1, __ATOMIC_SEQ_CST );
1385        __atomic_add_fetch( &realloc_storage_request, size, __ATOMIC_SEQ_CST );
1386        #endif // __STATISTICS__
1387
1388        HeapManager.FreeHeader * freeElem;
1389        size_t bsize;
1390        headers( "realloc", oaddr, header, freeElem, bsize, oalign );
1391
1392        // change size and copy old content to new storage
1393
1394        size_t osize = header->kind.real.size;                          // old allocation size
1395        bool ozfill = (header->kind.real.blockSize & 2);        // old allocation zero filled
1396
1397        void * naddr = memalignNoStats( nalign, size );         // create new aligned area
1398
1399        headers( "realloc", naddr, header, freeElem, bsize, oalign );
1400        memcpy( naddr, oaddr, min( osize, size ) );                     // copy bytes
1401        free( oaddr );
1402
1403        if ( unlikely( ozfill ) ) {                                                     // previous request zero fill ?
1404                header->kind.real.blockSize |= 2;                               // mark new request as zero filled
1405                if ( size > osize ) {                                                   // previous request larger ?
1406                        memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage
1407                } // if
1408        } // if
1409        return naddr;
1410} // realloc
1411
1412
1413// Local Variables: //
1414// tab-width: 4 //
1415// compile-command: "cfa -nodebug -O2 heap.cfa" //
1416// End: //
Note: See TracBrowser for help on using the repository browser.