source: libcfa/src/heap.cfa @ a1574e2

ADTast-experimentalenumforall-pointer-decaypthread-emulationqualifiedEnum
Last change on this file since a1574e2 was 7dd98b6, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Moved cfa_main_returned to libcfa so it works when the main is written in C.

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