source: libcfa/src/heap.cfa @ 594e1db

ADTast-experimentalpthread-emulation
Last change on this file since 594e1db was 5a076837, checked in by Thierry Delisle <tdelisle@…>, 2 years ago

Remove unnecessary declaration in heap

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