source: libcfa/src/heap.cfa @ b5276fc

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

add resize and more "alloc" routines

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