source: libcfa/src/heap.cfa @ 61248a4

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

update comments for public C allocation routines

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