source: libcfa/src/heap.cfa @ baf608a

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

provide switch to print heap statistics on program termination

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