source: libcfa/src/heap.cfa @ 2b23d78

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

check for allocation size change and reset if necessary in resize and realloc

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