source: libcfa/src/heap.cfa @ 6ce9a4f2

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 6ce9a4f2 was e4b6b7d3, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

for debug, fill deleted memory with deadbeef pattern

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