source: libcfa/src/heap.cfa @ 7332629

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

add separate statistics counters for zero allocations and nullptr free, update printing of malloc_stats, fix statistics gathering issues, code restructuring for heap

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