source: libcfa/src/heap.cfa @ 8419b76

ADTast-experimentalpthread-emulationqualifiedEnum
Last change on this file since 8419b76 was 032234bd, checked in by Thierry Delisle <tdelisle@…>, 2 years ago

Visibility of the core libcfa files.

  • 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        Heap * homeManager;
512        if ( unlikely( freeHead == 0p || // freed and only free-list node => null link
513                                   // freed and link points at another free block not to a bucket in the bucket array.
514                                   freeHead < &freeLists[0] || &freeLists[NoBucketSizes] <= freeHead ) ) {
515                abort( "**** Error **** attempt to %s storage %p with corrupted header.\n"
516                           "Possible cause is duplicate free on same block or overwriting of header information.",
517                           name, addr );
518        } // if
[c4f68dc]519        #endif // __CFA_DEBUG__
[19e5d65d]520
[bcb14b5]521        return false;
[c4f68dc]522} // headers
523
[709b812]524// #ifdef __CFA_DEBUG__
525// #if __SIZEOF_POINTER__ == 4
526// #define MASK 0xdeadbeef
527// #else
528// #define MASK 0xdeadbeefdeadbeef
529// #endif
530// #define STRIDE size_t
[e4b6b7d3]531
[709b812]532// static void * Memset( void * addr, STRIDE size ) {           // debug only
533//      if ( size % sizeof(STRIDE) != 0 ) abort( "Memset() : internal error, size %zd not multiple of %zd.", size, sizeof(STRIDE) );
534//      if ( (STRIDE)addr % sizeof(STRIDE) != 0 ) abort( "Memset() : internal error, addr %p not multiple of %zd.", addr, sizeof(STRIDE) );
[e4b6b7d3]535
[709b812]536//      STRIDE * end = (STRIDE *)addr + size / sizeof(STRIDE);
537//      for ( STRIDE * p = (STRIDE *)addr; p < end; p += 1 ) *p = MASK;
538//      return addr;
539// } // Memset
540// #endif // __CFA_DEBUG__
[e4b6b7d3]541
[13fece5]542
[92aca37]543#define NO_MEMORY_MSG "insufficient heap memory available for allocating %zd new bytes."
[c4f68dc]544
[9c438546]545static inline void * extend( size_t size ) with( heapManager ) {
[b6830d74]546        lock( extlock __cfaabi_dbg_ctx2 );
[19e5d65d]547
[b6830d74]548        ptrdiff_t rem = heapRemaining - size;
[19e5d65d]549        if ( unlikely( rem < 0 ) ) {
[c4f68dc]550                // If the size requested is bigger than the current remaining storage, increase the size of the heap.
551
[69ec0fb]552                size_t increase = ceiling2( size > heapExpand ? size : heapExpand, __page_size );
[ad2dced]553                // Do not call abort or strerror( errno ) as they may call malloc.
[92aca37]554                if ( sbrk( increase ) == (void *)-1 ) {                 // failed, no memory ?
[c4f68dc]555                        unlock( extlock );
[ad2dced]556                        __cfaabi_bits_print_nolock( STDERR_FILENO, NO_MEMORY_MSG, size );
[709b812]557                        _exit( EXIT_FAILURE );                                          // give up
[92aca37]558                } // if
[19e5d65d]559
[709b812]560                // Make storage executable for thunks.
[69ec0fb]561                if ( mprotect( (char *)heapEnd + heapRemaining, increase, __map_prot ) ) {
562                        unlock( extlock );
563                        __cfaabi_bits_print_nolock( STDERR_FILENO, "extend() : internal error, mprotect failure, heapEnd:%p size:%zd, errno:%d.\n", heapEnd, increase, errno );
564                        _exit( EXIT_FAILURE );
565                } // if
[19e5d65d]566
[bcb14b5]567                #ifdef __STATISTICS__
[c4f68dc]568                sbrk_calls += 1;
569                sbrk_storage += increase;
[bcb14b5]570                #endif // __STATISTICS__
[433905a]571
[bcb14b5]572                #ifdef __CFA_DEBUG__
[c4f68dc]573                // Set new memory to garbage so subsequent uninitialized usages might fail.
[13fece5]574                memset( (char *)heapEnd + heapRemaining, '\xde', increase );
[ad2dced]575                //Memset( (char *)heapEnd + heapRemaining, increase );
[bcb14b5]576                #endif // __CFA_DEBUG__
[433905a]577
[c4f68dc]578                rem = heapRemaining + increase - size;
[b6830d74]579        } // if
[c4f68dc]580
[31a5f418]581        Heap.Storage * block = (Heap.Storage *)heapEnd;
[b6830d74]582        heapRemaining = rem;
583        heapEnd = (char *)heapEnd + size;
584        unlock( extlock );
585        return block;
[c4f68dc]586} // extend
587
588
[9c438546]589static inline void * doMalloc( size_t size ) with( heapManager ) {
[31a5f418]590        Heap.Storage * block;                                           // pointer to new block of storage
[c4f68dc]591
[b6830d74]592        // Look up size in the size list.  Make sure the user request includes space for the header that must be allocated
593        // along with the block and is a multiple of the alignment size.
[69ec0fb]594
[31a5f418]595        size_t tsize = size + sizeof(Heap.Storage);
[19e5d65d]596
[b6830d74]597        if ( likely( tsize < mmapStart ) ) {                            // small size => sbrk
[e723100]598                size_t posn;
599                #ifdef FASTLOOKUP
600                if ( tsize < LookupSizes ) posn = lookup[tsize];
601                else
602                #endif // FASTLOOKUP
603                        posn = Bsearchl( (unsigned int)tsize, bucketSizes, (size_t)maxBucketsUsed );
[31a5f418]604                Heap.FreeHeader * freeElem = &freeLists[posn];
[c1f38e6c]605                verify( freeElem <= &freeLists[maxBucketsUsed] ); // subscripting error ?
606                verify( tsize <= freeElem->blockSize );                 // search failure ?
[c4f68dc]607                tsize = freeElem->blockSize;                                    // total space needed for request
608
609                // Spin until the lock is acquired for this particular size of block.
610
[9c438546]611                #if BUCKETLOCK == SPINLOCK
[bcb14b5]612                lock( freeElem->lock __cfaabi_dbg_ctx2 );
613                block = freeElem->freeList;                                             // remove node from stack
[c4f68dc]614                #else
[9c438546]615                block = pop( freeElem->freeList );
616                #endif // BUCKETLOCK
[95eb7cf]617                if ( unlikely( block == 0p ) ) {                                // no free block ?
[9c438546]618                        #if BUCKETLOCK == SPINLOCK
[c4f68dc]619                        unlock( freeElem->lock );
[9c438546]620                        #endif // BUCKETLOCK
[bcb14b5]621
[c4f68dc]622                        // Freelist for that size was empty, so carve it out of the heap if there's enough left, or get some more
623                        // and then carve it off.
624
[31a5f418]625                        block = (Heap.Storage *)extend( tsize );        // mutual exclusion on call
[9c438546]626                #if BUCKETLOCK == SPINLOCK
[c4f68dc]627                } else {
628                        freeElem->freeList = block->header.kind.real.next;
629                        unlock( freeElem->lock );
[9c438546]630                #endif // BUCKETLOCK
[c4f68dc]631                } // if
632
633                block->header.kind.real.home = freeElem;                // pointer back to free list of apropriate size
[bcb14b5]634        } else {                                                                                        // large size => mmap
[ad2dced]635  if ( unlikely( size > ULONG_MAX - __page_size ) ) return 0p;
636                tsize = ceiling2( tsize, __page_size );                 // must be multiple of page size
[c4f68dc]637                #ifdef __STATISTICS__
[31a5f418]638                __atomic_add_fetch( &stats.mmap_calls, 1, __ATOMIC_SEQ_CST );
639                __atomic_add_fetch( &stats.mmap_storage_request, size, __ATOMIC_SEQ_CST );
640                __atomic_add_fetch( &stats.mmap_storage_alloc, tsize, __ATOMIC_SEQ_CST );
[c4f68dc]641                #endif // __STATISTICS__
[92aca37]642
[31a5f418]643                block = (Heap.Storage *)mmap( 0, tsize, __map_prot, MAP_PRIVATE | MAP_ANONYMOUS, mmapFd, 0 );
644                if ( block == (Heap.Storage *)MAP_FAILED ) { // failed ?
[92aca37]645                        if ( errno == ENOMEM ) abort( NO_MEMORY_MSG, tsize ); // no memory
[c4f68dc]646                        // Do not call strerror( errno ) as it may call malloc.
[31a5f418]647                        abort( "(Heap &)0x%p.doMalloc() : internal error, mmap failure, size:%zu errno:%d.", &heapManager, tsize, errno );
[92aca37]648                } //if
[bcb14b5]649                #ifdef __CFA_DEBUG__
[c4f68dc]650                // Set new memory to garbage so subsequent uninitialized usages might fail.
[13fece5]651                memset( block, '\xde', tsize );
[ad2dced]652                //Memset( block, tsize );
[bcb14b5]653                #endif // __CFA_DEBUG__
[19e5d65d]654                block->header.kind.real.blockSize = MarkMmappedBit( tsize ); // storage size for munmap
[bcb14b5]655        } // if
[c4f68dc]656
[9c438546]657        block->header.kind.real.size = size;                            // store allocation size
[95eb7cf]658        void * addr = &(block->data);                                           // adjust off header to user bytes
[c1f38e6c]659        verify( ((uintptr_t)addr & (libAlign() - 1)) == 0 ); // minimum alignment ?
[c4f68dc]660
661        #ifdef __CFA_DEBUG__
[c1f38e6c]662        __atomic_add_fetch( &allocUnfreed, tsize, __ATOMIC_SEQ_CST );
[bcb14b5]663        if ( traceHeap() ) {
[433905a]664                char helpText[64];
665                __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText),
666                                                                        "%p = Malloc( %zu ) (allocated %zu)\n", addr, size, tsize ); // print debug/nodebug
[bcb14b5]667        } // if
[c4f68dc]668        #endif // __CFA_DEBUG__
669
[95eb7cf]670        return addr;
[c4f68dc]671} // doMalloc
672
673
[9c438546]674static inline void doFree( void * addr ) with( heapManager ) {
[c4f68dc]675        #ifdef __CFA_DEBUG__
[95eb7cf]676        if ( unlikely( heapManager.heapBegin == 0p ) ) {
[bcb14b5]677                abort( "doFree( %p ) : internal error, called before heap is initialized.", addr );
678        } // if
[c4f68dc]679        #endif // __CFA_DEBUG__
680
[31a5f418]681        Heap.Storage.Header * header;
682        Heap.FreeHeader * freeElem;
[b6830d74]683        size_t size, alignment;                                                         // not used (see realloc)
[c4f68dc]684
[b6830d74]685        if ( headers( "free", addr, header, freeElem, size, alignment ) ) { // mmapped ?
[c4f68dc]686                #ifdef __STATISTICS__
[31a5f418]687                __atomic_add_fetch( &stats.munmap_calls, 1, __ATOMIC_SEQ_CST );
688                __atomic_add_fetch( &stats.munmap_storage_request, header->kind.real.size, __ATOMIC_SEQ_CST );
689                __atomic_add_fetch( &stats.munmap_storage_alloc, size, __ATOMIC_SEQ_CST );
[c4f68dc]690                #endif // __STATISTICS__
691                if ( munmap( header, size ) == -1 ) {
692                        abort( "Attempt to deallocate storage %p not allocated or with corrupt header.\n"
[bcb14b5]693                                   "Possible cause is invalid pointer.",
694                                   addr );
[c4f68dc]695                } // if
[bcb14b5]696        } else {
[c4f68dc]697                #ifdef __CFA_DEBUG__
[bcb14b5]698                // Set free memory to garbage so subsequent usages might fail.
[31a5f418]699                memset( ((Heap.Storage *)header)->data, '\xde', freeElem->blockSize - sizeof( Heap.Storage ) );
700                //Memset( ((Heap.Storage *)header)->data, freeElem->blockSize - sizeof( Heap.Storage ) );
[c4f68dc]701                #endif // __CFA_DEBUG__
702
703                #ifdef __STATISTICS__
[31a5f418]704                __atomic_add_fetch( &stats.free_calls, 1, __ATOMIC_SEQ_CST );
705                __atomic_add_fetch( &stats.free_storage_request, header->kind.real.size, __ATOMIC_SEQ_CST );
706                __atomic_add_fetch( &stats.free_storage_alloc, size, __ATOMIC_SEQ_CST );
[c4f68dc]707                #endif // __STATISTICS__
[b38b22f]708
[9c438546]709                #if BUCKETLOCK == SPINLOCK
[bcb14b5]710                lock( freeElem->lock __cfaabi_dbg_ctx2 );               // acquire spin lock
711                header->kind.real.next = freeElem->freeList;    // push on stack
[31a5f418]712                freeElem->freeList = (Heap.Storage *)header;
[bcb14b5]713                unlock( freeElem->lock );                                               // release spin lock
[c4f68dc]714                #else
[31a5f418]715                push( freeElem->freeList, *(Heap.Storage *)header );
[9c438546]716                #endif // BUCKETLOCK
[bcb14b5]717        } // if
[c4f68dc]718
719        #ifdef __CFA_DEBUG__
[c1f38e6c]720        __atomic_add_fetch( &allocUnfreed, -size, __ATOMIC_SEQ_CST );
[bcb14b5]721        if ( traceHeap() ) {
[92aca37]722                char helpText[64];
[433905a]723                __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText),
724                                                                        "Free( %p ) size:%zu\n", addr, size ); // print debug/nodebug
[bcb14b5]725        } // if
[c4f68dc]726        #endif // __CFA_DEBUG__
727} // doFree
728
729
[032234bd]730static size_t prtFree( Heap & manager ) with( manager ) {
[b6830d74]731        size_t total = 0;
[c4f68dc]732        #ifdef __STATISTICS__
[95eb7cf]733        __cfaabi_bits_acquire();
734        __cfaabi_bits_print_nolock( STDERR_FILENO, "\nBin lists (bin size : free blocks on list)\n" );
[c4f68dc]735        #endif // __STATISTICS__
[b6830d74]736        for ( unsigned int i = 0; i < maxBucketsUsed; i += 1 ) {
[d46ed6e]737                size_t size = freeLists[i].blockSize;
738                #ifdef __STATISTICS__
739                unsigned int N = 0;
740                #endif // __STATISTICS__
[b6830d74]741
[9c438546]742                #if BUCKETLOCK == SPINLOCK
[31a5f418]743                for ( Heap.Storage * p = freeLists[i].freeList; p != 0p; p = p->header.kind.real.next ) {
[d46ed6e]744                #else
[b4aa1ab]745                        for(;;) {
[31a5f418]746//              for ( Heap.Storage * p = top( freeLists[i].freeList ); p != 0p; p = (p)`next->top ) {
747//              for ( Heap.Storage * p = top( freeLists[i].freeList ); p != 0p; /* p = getNext( p )->top */) {
748//                      Heap.Storage * temp = p->header.kind.real.next.top; // FIX ME: direct assignent fails, initialization works`
[7cfef0d]749//                      typeof(p) temp = (( p )`next)->top;                     // FIX ME: direct assignent fails, initialization works`
750//                      p = temp;
[9c438546]751                #endif // BUCKETLOCK
[d46ed6e]752                        total += size;
753                        #ifdef __STATISTICS__
754                        N += 1;
755                        #endif // __STATISTICS__
[b6830d74]756                } // for
757
[d46ed6e]758                #ifdef __STATISTICS__
[95eb7cf]759                __cfaabi_bits_print_nolock( STDERR_FILENO, "%7zu, %-7u  ", size, N );
760                if ( (i + 1) % 8 == 0 ) __cfaabi_bits_print_nolock( STDERR_FILENO, "\n" );
[d46ed6e]761                #endif // __STATISTICS__
762        } // for
763        #ifdef __STATISTICS__
[95eb7cf]764        __cfaabi_bits_print_nolock( STDERR_FILENO, "\ntotal free blocks:%zu\n", total );
765        __cfaabi_bits_release();
[d46ed6e]766        #endif // __STATISTICS__
767        return (char *)heapEnd - (char *)heapBegin - total;
[95eb7cf]768} // prtFree
769
770
[31a5f418]771static void ?{}( Heap & manager ) with( manager ) {
[ad2dced]772        __page_size = sysconf( _SC_PAGESIZE );
773        __map_prot = PROT_READ | PROT_WRITE | PROT_EXEC;
[95eb7cf]774
775        for ( unsigned int i = 0; i < NoBucketSizes; i += 1 ) { // initialize the free lists
776                freeLists[i].blockSize = bucketSizes[i];
777        } // for
778
779        #ifdef FASTLOOKUP
780        unsigned int idx = 0;
781        for ( unsigned int i = 0; i < LookupSizes; i += 1 ) {
782                if ( i > bucketSizes[idx] ) idx += 1;
783                lookup[i] = idx;
784        } // for
785        #endif // FASTLOOKUP
786
[31a5f418]787        if ( ! setMmapStart( malloc_mmap_start() ) ) {
788                abort( "Heap : internal error, mmap start initialization failure." );
[95eb7cf]789        } // if
[31a5f418]790        heapExpand = malloc_expansion();
[95eb7cf]791
[1e034d9]792        char * end = (char *)sbrk( 0 );
[ad2dced]793        heapBegin = heapEnd = sbrk( (char *)ceiling2( (long unsigned int)end, __page_size ) - end ); // move start of heap to multiple of alignment
[31a5f418]794} // Heap
[95eb7cf]795
796
[31a5f418]797static void ^?{}( Heap & ) {
[95eb7cf]798        #ifdef __STATISTICS__
[baf608a]799        if ( traceHeapTerm() ) {
800                printStats();
[92aca37]801                // prtUnfreed() called in heapAppStop()
[baf608a]802        } // if
[95eb7cf]803        #endif // __STATISTICS__
[31a5f418]804} // ~Heap
[95eb7cf]805
806
807static void memory_startup( void ) __attribute__(( constructor( STARTUP_PRIORITY_MEMORY ) ));
808void memory_startup( void ) {
809        #ifdef __CFA_DEBUG__
[92aca37]810        if ( heapBoot ) {                                                                       // check for recursion during system boot
[95eb7cf]811                abort( "boot() : internal error, recursively invoked during system boot." );
812        } // if
813        heapBoot = true;
814        #endif // __CFA_DEBUG__
815
[c1f38e6c]816        //verify( heapManager.heapBegin != 0 );
[95eb7cf]817        //heapManager{};
[1076d05]818        if ( heapManager.heapBegin == 0p ) heapManager{};       // sanity check
[95eb7cf]819} // memory_startup
820
821static void memory_shutdown( void ) __attribute__(( destructor( STARTUP_PRIORITY_MEMORY ) ));
822void memory_shutdown( void ) {
823        ^heapManager{};
824} // memory_shutdown
[c4f68dc]825
[bcb14b5]826
827static inline void * mallocNoStats( size_t size ) {             // necessary for malloc statistics
[92aca37]828        verify( heapManager.heapBegin != 0p );                          // called before memory_startup ?
[dd23e66]829  if ( unlikely( size ) == 0 ) return 0p;                               // 0 BYTE ALLOCATION RETURNS NULL POINTER
[d5d3a90]830
[76e2113]831#if __SIZEOF_POINTER__ == 8
832        verify( size < ((typeof(size_t))1 << 48) );
833#endif // __SIZEOF_POINTER__ == 8
[d5d3a90]834        return doMalloc( size );
[bcb14b5]835} // mallocNoStats
[c4f68dc]836
837
[92aca37]838static inline void * memalignNoStats( size_t alignment, size_t size ) {
[dd23e66]839  if ( unlikely( size ) == 0 ) return 0p;                               // 0 BYTE ALLOCATION RETURNS NULL POINTER
[d5d3a90]840
[bcb14b5]841        #ifdef __CFA_DEBUG__
[b6830d74]842        checkAlign( alignment );                                                        // check alignment
[bcb14b5]843        #endif // __CFA_DEBUG__
[c4f68dc]844
[b6830d74]845        // if alignment <= default alignment, do normal malloc as two headers are unnecessary
[bcb14b5]846  if ( unlikely( alignment <= libAlign() ) ) return mallocNoStats( size );
[b6830d74]847
848        // Allocate enough storage to guarantee an address on the alignment boundary, and sufficient space before it for
849        // administrative storage. NOTE, WHILE THERE ARE 2 HEADERS, THE FIRST ONE IS IMPLICITLY CREATED BY DOMALLOC.
850        //      .-------------v-----------------v----------------v----------,
851        //      | Real Header | ... padding ... |   Fake Header  | data ... |
852        //      `-------------^-----------------^-+--------------^----------'
853        //      |<--------------------------------' offset/align |<-- alignment boundary
854
855        // subtract libAlign() because it is already the minimum alignment
856        // add sizeof(Storage) for fake header
[31a5f418]857        char * addr = (char *)mallocNoStats( size + alignment - libAlign() + sizeof(Heap.Storage) );
[b6830d74]858
859        // address in the block of the "next" alignment address
[31a5f418]860        char * user = (char *)ceiling2( (uintptr_t)(addr + sizeof(Heap.Storage)), alignment );
[b6830d74]861
862        // address of header from malloc
[19e5d65d]863        Heap.Storage.Header * RealHeader = HeaderAddr( addr );
864        RealHeader->kind.real.size = size;                                      // correct size to eliminate above alignment offset
[b6830d74]865        // address of fake header * before* the alignment location
[19e5d65d]866        Heap.Storage.Header * fakeHeader = HeaderAddr( user );
[b6830d74]867        // SKULLDUGGERY: insert the offset to the start of the actual storage block and remember alignment
[19e5d65d]868        fakeHeader->kind.fake.offset = (char *)fakeHeader - (char *)RealHeader;
[69ec0fb]869        // SKULLDUGGERY: odd alignment implies fake header
[19e5d65d]870        fakeHeader->kind.fake.alignment = MarkAlignmentBit( alignment );
[b6830d74]871
872        return user;
[bcb14b5]873} // memalignNoStats
[c4f68dc]874
875
[19e5d65d]876//####################### Memory Allocation Routines ####################
877
878
[c4f68dc]879extern "C" {
[61248a4]880        // Allocates size bytes and returns a pointer to the allocated memory.  The contents are undefined. If size is 0,
881        // then malloc() returns a unique pointer value that can later be successfully passed to free().
[032234bd]882        void * malloc( size_t size ) libcfa_public {
[c4f68dc]883                #ifdef __STATISTICS__
[709b812]884                if ( likely( size > 0 ) ) {
[31a5f418]885                        __atomic_add_fetch( &stats.malloc_calls, 1, __ATOMIC_SEQ_CST );
886                        __atomic_add_fetch( &stats.malloc_storage_request, size, __ATOMIC_SEQ_CST );
[709b812]887                } else {
[31a5f418]888                        __atomic_add_fetch( &stats.malloc_0_calls, 1, __ATOMIC_SEQ_CST );
[709b812]889                } // if
[c4f68dc]890                #endif // __STATISTICS__
891
[bcb14b5]892                return mallocNoStats( size );
893        } // malloc
[c4f68dc]894
[76e2113]895
[61248a4]896        // Same as malloc() except size bytes is an array of dim elements each of elemSize bytes.
[032234bd]897        void * aalloc( size_t dim, size_t elemSize ) libcfa_public {
[92aca37]898                size_t size = dim * elemSize;
[76e2113]899                #ifdef __STATISTICS__
[709b812]900                if ( likely( size > 0 ) ) {
[31a5f418]901                        __atomic_add_fetch( &stats.aalloc_calls, 1, __ATOMIC_SEQ_CST );
902                        __atomic_add_fetch( &stats.aalloc_storage_request, size, __ATOMIC_SEQ_CST );
[709b812]903                } else {
[31a5f418]904                        __atomic_add_fetch( &stats.aalloc_0_calls, 1, __ATOMIC_SEQ_CST );
[709b812]905                } // if
[76e2113]906                #endif // __STATISTICS__
907
[92aca37]908                return mallocNoStats( size );
[76e2113]909        } // aalloc
910
911
[61248a4]912        // Same as aalloc() with memory set to zero.
[032234bd]913        void * calloc( size_t dim, size_t elemSize ) libcfa_public {
[709b812]914                size_t size = dim * elemSize;
915          if ( unlikely( size ) == 0 ) {                        // 0 BYTE ALLOCATION RETURNS NULL POINTER
916                        #ifdef __STATISTICS__
[31a5f418]917                        __atomic_add_fetch( &stats.calloc_0_calls, 1, __ATOMIC_SEQ_CST );
[709b812]918                        #endif // __STATISTICS__
919                        return 0p;
920                } // if
[c4f68dc]921                #ifdef __STATISTICS__
[31a5f418]922                __atomic_add_fetch( &stats.calloc_calls, 1, __ATOMIC_SEQ_CST );
923                __atomic_add_fetch( &stats.calloc_storage_request, dim * elemSize, __ATOMIC_SEQ_CST );
[c4f68dc]924                #endif // __STATISTICS__
925
[709b812]926                char * addr = (char *)mallocNoStats( size );
927
[31a5f418]928                Heap.Storage.Header * header;
929                Heap.FreeHeader * freeElem;
[709b812]930                size_t bsize, alignment;
931
932                #ifndef __CFA_DEBUG__
933                bool mapped =
934                        #endif // __CFA_DEBUG__
935                        headers( "calloc", addr, header, freeElem, bsize, alignment );
936
937                #ifndef __CFA_DEBUG__
938                // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
939                if ( ! mapped )
940                #endif // __CFA_DEBUG__
941                        // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined
942                        // `-header`-addr                      `-size
943                        memset( addr, '\0', size );                                     // set to zeros
944
[19e5d65d]945                MarkZeroFilledBit( header );                                    // mark as zero fill
[709b812]946                return addr;
[bcb14b5]947        } // calloc
[c4f68dc]948
[92aca37]949
[61248a4]950        // Change the size of the memory block pointed to by oaddr to size bytes. The contents are undefined.  If oaddr is
951        // 0p, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and oaddr is
952        // not 0p, then the call is equivalent to free(oaddr). Unless oaddr is 0p, it must have been returned by an earlier
953        // call to malloc(), alloc(), calloc() or realloc(). If the area pointed to was moved, a free(oaddr) is done.
[032234bd]954        void * resize( void * oaddr, size_t size ) libcfa_public {
[709b812]955                // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
956          if ( unlikely( size == 0 ) ) {                                        // special cases
957                        #ifdef __STATISTICS__
[31a5f418]958                        __atomic_add_fetch( &stats.resize_0_calls, 1, __ATOMIC_SEQ_CST );
[709b812]959                        #endif // __STATISTICS__
960                        free( oaddr );
961                        return 0p;
962                } // if
[cfbc703d]963                #ifdef __STATISTICS__
[31a5f418]964                __atomic_add_fetch( &stats.resize_calls, 1, __ATOMIC_SEQ_CST );
[cfbc703d]965                #endif // __STATISTICS__
966
[92aca37]967          if ( unlikely( oaddr == 0p ) ) {
968                        #ifdef __STATISTICS__
[31a5f418]969                        __atomic_add_fetch( &stats.resize_storage_request, size, __ATOMIC_SEQ_CST );
[92aca37]970                        #endif // __STATISTICS__
971                        return mallocNoStats( size );
972                } // if
[cfbc703d]973
[31a5f418]974                Heap.Storage.Header * header;
975                Heap.FreeHeader * freeElem;
[92aca37]976                size_t bsize, oalign;
[cfbc703d]977                headers( "resize", oaddr, header, freeElem, bsize, oalign );
[92847f7]978
[19e5d65d]979                size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
[cfbc703d]980                // same size, DO NOT preserve STICKY PROPERTIES.
[92847f7]981                if ( oalign == libAlign() && size <= odsize && odsize <= size * 2 ) { // allow 50% wasted storage for smaller size
[19e5d65d]982                        ClearZeroFillBit( header );                                     // no alignment and turn off 0 fill
[d5d3a90]983                        header->kind.real.size = size;                          // reset allocation size
[cfbc703d]984                        return oaddr;
985                } // if
[0f89d4f]986
[92aca37]987                #ifdef __STATISTICS__
[31a5f418]988                __atomic_add_fetch( &stats.resize_storage_request, size, __ATOMIC_SEQ_CST );
[92aca37]989                #endif // __STATISTICS__
990
[cfbc703d]991                // change size, DO NOT preserve STICKY PROPERTIES.
992                free( oaddr );
[d5d3a90]993                return mallocNoStats( size );                                   // create new area
[cfbc703d]994        } // resize
995
996
[61248a4]997        // Same as resize() but the contents are unchanged in the range from the start of the region up to the minimum of
[cfbc703d]998        // the old and new sizes.
[032234bd]999        void * realloc( void * oaddr, size_t size ) libcfa_public {
[709b812]1000                // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
1001          if ( unlikely( size == 0 ) ) {                                        // special cases
1002                        #ifdef __STATISTICS__
[31a5f418]1003                        __atomic_add_fetch( &stats.realloc_0_calls, 1, __ATOMIC_SEQ_CST );
[709b812]1004                        #endif // __STATISTICS__
1005                        free( oaddr );
1006                        return 0p;
1007                } // if
[c4f68dc]1008                #ifdef __STATISTICS__
[31a5f418]1009                __atomic_add_fetch( &stats.realloc_calls, 1, __ATOMIC_SEQ_CST );
[c4f68dc]1010                #endif // __STATISTICS__
1011
[92aca37]1012          if ( unlikely( oaddr == 0p ) ) {
1013                        #ifdef __STATISTICS__
[31a5f418]1014                        __atomic_add_fetch( &stats.realloc_storage_request, size, __ATOMIC_SEQ_CST );
[92aca37]1015                        #endif // __STATISTICS__
1016                        return mallocNoStats( size );
1017                } // if
[c4f68dc]1018
[31a5f418]1019                Heap.Storage.Header * header;
1020                Heap.FreeHeader * freeElem;
[92aca37]1021                size_t bsize, oalign;
[95eb7cf]1022                headers( "realloc", oaddr, header, freeElem, bsize, oalign );
1023
[19e5d65d]1024                size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
[d5d3a90]1025                size_t osize = header->kind.real.size;                  // old allocation size
[19e5d65d]1026                bool ozfill = ZeroFillBit( header );                    // old allocation zero filled
[92847f7]1027          if ( unlikely( size <= odsize ) && odsize <= size * 2 ) { // allow up to 50% wasted storage
[d5d3a90]1028                        header->kind.real.size = size;                          // reset allocation size
1029                        if ( unlikely( ozfill ) && size > osize ) {     // previous request zero fill and larger ?
[e4b6b7d3]1030                                memset( (char *)oaddr + osize, '\0', size - osize ); // initialize added storage
[d5d3a90]1031                        } // if
[95eb7cf]1032                        return oaddr;
[c4f68dc]1033                } // if
1034
[92aca37]1035                #ifdef __STATISTICS__
[31a5f418]1036                __atomic_add_fetch( &stats.realloc_storage_request, size, __ATOMIC_SEQ_CST );
[92aca37]1037                #endif // __STATISTICS__
1038
[95eb7cf]1039                // change size and copy old content to new storage
1040
1041                void * naddr;
[92847f7]1042                if ( likely( oalign == libAlign() ) ) {                 // previous request not aligned ?
[d5d3a90]1043                        naddr = mallocNoStats( size );                          // create new area
[c4f68dc]1044                } else {
[d5d3a90]1045                        naddr = memalignNoStats( oalign, size );        // create new aligned area
[c4f68dc]1046                } // if
[1e034d9]1047
[95eb7cf]1048                headers( "realloc", naddr, header, freeElem, bsize, oalign );
[47dd0d2]1049                memcpy( naddr, oaddr, min( osize, size ) );             // copy bytes
[95eb7cf]1050                free( oaddr );
[d5d3a90]1051
1052                if ( unlikely( ozfill ) ) {                                             // previous request zero fill ?
[19e5d65d]1053                        MarkZeroFilledBit( header );                            // mark new request as zero filled
[d5d3a90]1054                        if ( size > osize ) {                                           // previous request larger ?
[e4b6b7d3]1055                                memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage
[d5d3a90]1056                        } // if
1057                } // if
[95eb7cf]1058                return naddr;
[b6830d74]1059        } // realloc
[c4f68dc]1060
[c1f38e6c]1061
[19e5d65d]1062        // Same as realloc() except the new allocation size is large enough for an array of nelem elements of size elsize.
[032234bd]1063        void * reallocarray( void * oaddr, size_t dim, size_t elemSize ) libcfa_public {
[19e5d65d]1064                return realloc( oaddr, dim * elemSize );
1065        } // reallocarray
1066
1067
[61248a4]1068        // Same as malloc() except the memory address is a multiple of alignment, which must be a power of two. (obsolete)
[032234bd]1069        void * memalign( size_t alignment, size_t size ) libcfa_public {
[c4f68dc]1070                #ifdef __STATISTICS__
[709b812]1071                if ( likely( size > 0 ) ) {
[31a5f418]1072                        __atomic_add_fetch( &stats.memalign_calls, 1, __ATOMIC_SEQ_CST );
1073                        __atomic_add_fetch( &stats.memalign_storage_request, size, __ATOMIC_SEQ_CST );
[709b812]1074                } else {
[31a5f418]1075                        __atomic_add_fetch( &stats.memalign_0_calls, 1, __ATOMIC_SEQ_CST );
[709b812]1076                } // if
[c4f68dc]1077                #endif // __STATISTICS__
1078
[95eb7cf]1079                return memalignNoStats( alignment, size );
[bcb14b5]1080        } // memalign
[c4f68dc]1081
[95eb7cf]1082
[76e2113]1083        // Same as aalloc() with memory alignment.
[032234bd]1084        void * amemalign( size_t alignment, size_t dim, size_t elemSize ) libcfa_public {
[92aca37]1085                size_t size = dim * elemSize;
[76e2113]1086                #ifdef __STATISTICS__
[709b812]1087                if ( likely( size > 0 ) ) {
[31a5f418]1088                        __atomic_add_fetch( &stats.cmemalign_calls, 1, __ATOMIC_SEQ_CST );
1089                        __atomic_add_fetch( &stats.cmemalign_storage_request, size, __ATOMIC_SEQ_CST );
[709b812]1090                } else {
[31a5f418]1091                        __atomic_add_fetch( &stats.cmemalign_0_calls, 1, __ATOMIC_SEQ_CST );
[709b812]1092                } // if
[76e2113]1093                #endif // __STATISTICS__
1094
[92aca37]1095                return memalignNoStats( alignment, size );
[76e2113]1096        } // amemalign
1097
1098
[ca7949b]1099        // Same as calloc() with memory alignment.
[032234bd]1100        void * cmemalign( size_t alignment, size_t dim, size_t elemSize ) libcfa_public {
[709b812]1101                size_t size = dim * elemSize;
1102          if ( unlikely( size ) == 0 ) {                                        // 0 BYTE ALLOCATION RETURNS NULL POINTER
1103                        #ifdef __STATISTICS__
[31a5f418]1104                        __atomic_add_fetch( &stats.cmemalign_0_calls, 1, __ATOMIC_SEQ_CST );
[709b812]1105                        #endif // __STATISTICS__
1106                        return 0p;
1107                } // if
[95eb7cf]1108                #ifdef __STATISTICS__
[31a5f418]1109                __atomic_add_fetch( &stats.cmemalign_calls, 1, __ATOMIC_SEQ_CST );
1110                __atomic_add_fetch( &stats.cmemalign_storage_request, dim * elemSize, __ATOMIC_SEQ_CST );
[95eb7cf]1111                #endif // __STATISTICS__
1112
[709b812]1113                char * addr = (char *)memalignNoStats( alignment, size );
1114
[31a5f418]1115                Heap.Storage.Header * header;
1116                Heap.FreeHeader * freeElem;
[709b812]1117                size_t bsize;
1118
1119                #ifndef __CFA_DEBUG__
1120                bool mapped =
1121                        #endif // __CFA_DEBUG__
1122                        headers( "cmemalign", addr, header, freeElem, bsize, alignment );
1123
1124                // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
1125                #ifndef __CFA_DEBUG__
1126                if ( ! mapped )
1127                #endif // __CFA_DEBUG__
1128                        // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined
1129                        // `-header`-addr                      `-size
1130                        memset( addr, '\0', size );                                     // set to zeros
1131
[19e5d65d]1132                MarkZeroFilledBit( header );                                    // mark as zero filled
[709b812]1133                return addr;
[95eb7cf]1134        } // cmemalign
1135
[13fece5]1136
[ca7949b]1137        // Same as memalign(), but ISO/IEC 2011 C11 Section 7.22.2 states: the value of size shall be an integral multiple
[19e5d65d]1138        // of alignment. This requirement is universally ignored.
[032234bd]1139        void * aligned_alloc( size_t alignment, size_t size ) libcfa_public {
[c4f68dc]1140                return memalign( alignment, size );
[b6830d74]1141        } // aligned_alloc
[c4f68dc]1142
1143
[ca7949b]1144        // Allocates size bytes and places the address of the allocated memory in *memptr. The address of the allocated
1145        // memory shall be a multiple of alignment, which must be a power of two and a multiple of sizeof(void *). If size
1146        // is 0, then posix_memalign() returns either 0p, or a unique pointer value that can later be successfully passed to
1147        // free(3).
[032234bd]1148        int posix_memalign( void ** memptr, size_t alignment, size_t size ) libcfa_public {
[69ec0fb]1149          if ( unlikely( alignment < libAlign() || ! is_pow2( alignment ) ) ) return EINVAL; // check alignment
[19e5d65d]1150                *memptr = memalign( alignment, size );
[c4f68dc]1151                return 0;
[b6830d74]1152        } // posix_memalign
[c4f68dc]1153
[13fece5]1154
[ca7949b]1155        // Allocates size bytes and returns a pointer to the allocated memory. The memory address shall be a multiple of the
1156        // page size.  It is equivalent to memalign(sysconf(_SC_PAGESIZE),size).
[032234bd]1157        void * valloc( size_t size ) libcfa_public {
[ad2dced]1158                return memalign( __page_size, size );
[b6830d74]1159        } // valloc
[c4f68dc]1160
1161
[ca7949b]1162        // Same as valloc but rounds size to multiple of page size.
[032234bd]1163        void * pvalloc( size_t size ) libcfa_public {
[19e5d65d]1164                return memalign( __page_size, ceiling2( size, __page_size ) ); // round size to multiple of page size
[ca7949b]1165        } // pvalloc
1166
1167
1168        // Frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc()
[1076d05]1169        // or realloc().  Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is
[ca7949b]1170        // 0p, no operation is performed.
[032234bd]1171        void free( void * addr ) libcfa_public {
[95eb7cf]1172          if ( unlikely( addr == 0p ) ) {                                       // special case
[709b812]1173                        #ifdef __STATISTICS__
[31a5f418]1174                        __atomic_add_fetch( &stats.free_null_calls, 1, __ATOMIC_SEQ_CST );
[709b812]1175                        #endif // __STATISTICS__
1176
[95eb7cf]1177                        // #ifdef __CFA_DEBUG__
1178                        // if ( traceHeap() ) {
1179                        //      #define nullmsg "Free( 0x0 ) size:0\n"
[1e034d9]1180                        //      // Do not debug print free( 0p ), as it can cause recursive entry from sprintf.
[95eb7cf]1181                        //      __cfaabi_dbg_write( nullmsg, sizeof(nullmsg) - 1 );
1182                        // } // if
1183                        // #endif // __CFA_DEBUG__
[c4f68dc]1184                        return;
1185                } // exit
1186
1187                doFree( addr );
[b6830d74]1188        } // free
[93c2e0a]1189
[c4f68dc]1190
[76e2113]1191        // Returns the alignment of an allocation.
[032234bd]1192        size_t malloc_alignment( void * addr ) libcfa_public {
[95eb7cf]1193          if ( unlikely( addr == 0p ) ) return libAlign();      // minimum alignment
[19e5d65d]1194                Heap.Storage.Header * header = HeaderAddr( addr );
1195                if ( unlikely( AlignmentBit( header ) ) ) {             // fake header ?
1196                        return ClearAlignmentBit( header );                     // clear flag from value
[c4f68dc]1197                } else {
[cfbc703d]1198                        return libAlign();                                                      // minimum alignment
[c4f68dc]1199                } // if
[bcb14b5]1200        } // malloc_alignment
[c4f68dc]1201
[92aca37]1202
[76e2113]1203        // Returns true if the allocation is zero filled, e.g., allocated by calloc().
[032234bd]1204        bool malloc_zero_fill( void * addr ) libcfa_public {
[95eb7cf]1205          if ( unlikely( addr == 0p ) ) return false;           // null allocation is not zero fill
[19e5d65d]1206                Heap.Storage.Header * header = HeaderAddr( addr );
1207                if ( unlikely( AlignmentBit( header ) ) ) {             // fake header ?
1208                        header = RealHeader( header );                          // backup from fake to real header
[c4f68dc]1209                } // if
[19e5d65d]1210                return ZeroFillBit( header );                                   // zero filled ?
[bcb14b5]1211        } // malloc_zero_fill
[c4f68dc]1212
[19e5d65d]1213
1214        // Returns original total allocation size (not bucket size) => array size is dimension * sizeof(T).
[032234bd]1215        size_t malloc_size( void * addr ) libcfa_public {
[849fb370]1216          if ( unlikely( addr == 0p ) ) return 0;                       // null allocation has zero size
[19e5d65d]1217                Heap.Storage.Header * header = HeaderAddr( addr );
1218                if ( unlikely( AlignmentBit( header ) ) ) {             // fake header ?
1219                        header = RealHeader( header );                          // backup from fake to real header
[cfbc703d]1220                } // if
[9c438546]1221                return header->kind.real.size;
[76e2113]1222        } // malloc_size
1223
[cfbc703d]1224
[ca7949b]1225        // Returns the number of usable bytes in the block pointed to by ptr, a pointer to a block of memory allocated by
1226        // malloc or a related function.
[032234bd]1227        size_t malloc_usable_size( void * addr ) libcfa_public {
[95eb7cf]1228          if ( unlikely( addr == 0p ) ) return 0;                       // null allocation has 0 size
[31a5f418]1229                Heap.Storage.Header * header;
1230                Heap.FreeHeader * freeElem;
[95eb7cf]1231                size_t bsize, alignment;
1232
1233                headers( "malloc_usable_size", addr, header, freeElem, bsize, alignment );
[19e5d65d]1234                return DataStorage( bsize, addr, header );              // data storage in bucket
[95eb7cf]1235        } // malloc_usable_size
1236
1237
[ca7949b]1238        // Prints (on default standard error) statistics about memory allocated by malloc and related functions.
[032234bd]1239        void malloc_stats( void ) libcfa_public {
[c4f68dc]1240                #ifdef __STATISTICS__
[bcb14b5]1241                printStats();
[95eb7cf]1242                if ( prtFree() ) prtFree( heapManager );
[c4f68dc]1243                #endif // __STATISTICS__
[bcb14b5]1244        } // malloc_stats
[c4f68dc]1245
[92aca37]1246
[19e5d65d]1247        // Changes the file descriptor where malloc_stats() writes statistics.
[032234bd]1248        int malloc_stats_fd( int fd __attribute__(( unused )) ) libcfa_public {
[c4f68dc]1249                #ifdef __STATISTICS__
[709b812]1250                int temp = stats_fd;
1251                stats_fd = fd;
[bcb14b5]1252                return temp;
[c4f68dc]1253                #else
[19e5d65d]1254                return -1;                                                                              // unsupported
[c4f68dc]1255                #endif // __STATISTICS__
[bcb14b5]1256        } // malloc_stats_fd
[c4f68dc]1257
[95eb7cf]1258
[19e5d65d]1259        // Prints an XML string that describes the current state of the memory-allocation implementation in the caller.
1260        // The string is printed on the file stream stream.  The exported string includes information about all arenas (see
1261        // malloc).
[032234bd]1262        int malloc_info( int options, FILE * stream __attribute__(( unused )) ) libcfa_public {
[19e5d65d]1263          if ( options != 0 ) { errno = EINVAL; return -1; }
1264                #ifdef __STATISTICS__
1265                return printStatsXML( stream );
1266                #else
1267                return 0;                                                                               // unsupported
1268                #endif // __STATISTICS__
1269        } // malloc_info
1270
1271
[1076d05]1272        // Adjusts parameters that control the behaviour of the memory-allocation functions (see malloc). The param argument
[ca7949b]1273        // specifies the parameter to be modified, and value specifies the new value for that parameter.
[032234bd]1274        int mallopt( int option, int value ) libcfa_public {
[19e5d65d]1275          if ( value < 0 ) return 0;
[95eb7cf]1276                choose( option ) {
1277                  case M_TOP_PAD:
[19e5d65d]1278                        heapExpand = ceiling2( value, __page_size );
1279                        return 1;
[95eb7cf]1280                  case M_MMAP_THRESHOLD:
1281                        if ( setMmapStart( value ) ) return 1;
[19e5d65d]1282                } // choose
[95eb7cf]1283                return 0;                                                                               // error, unsupported
1284        } // mallopt
1285
[c1f38e6c]1286
[ca7949b]1287        // Attempt to release free memory at the top of the heap (by calling sbrk with a suitable argument).
[032234bd]1288        int malloc_trim( size_t ) libcfa_public {
[95eb7cf]1289                return 0;                                                                               // => impossible to release memory
1290        } // malloc_trim
1291
1292
[ca7949b]1293        // Records the current state of all malloc internal bookkeeping variables (but not the actual contents of the heap
1294        // or the state of malloc_hook functions pointers).  The state is recorded in a system-dependent opaque data
1295        // structure dynamically allocated via malloc, and a pointer to that data structure is returned as the function
1296        // result.  (The caller must free this memory.)
[032234bd]1297        void * malloc_get_state( void ) libcfa_public {
[95eb7cf]1298                return 0p;                                                                              // unsupported
[c4f68dc]1299        } // malloc_get_state
1300
[bcb14b5]1301
[ca7949b]1302        // Restores the state of all malloc internal bookkeeping variables to the values recorded in the opaque data
1303        // structure pointed to by state.
[032234bd]1304        int malloc_set_state( void * ) libcfa_public {
[bcb14b5]1305                return 0;                                                                               // unsupported
[c4f68dc]1306        } // malloc_set_state
[31a5f418]1307
[19e5d65d]1308
[31a5f418]1309        // Sets the amount (bytes) to extend the heap when there is insufficent free storage to service an allocation.
[032234bd]1310        __attribute__((weak)) size_t malloc_expansion() libcfa_public { return __CFA_DEFAULT_HEAP_EXPANSION__; }
[31a5f418]1311
1312        // Sets the crossover point between allocations occuring in the sbrk area or separately mmapped.
[032234bd]1313        __attribute__((weak)) size_t malloc_mmap_start() libcfa_public { return __CFA_DEFAULT_MMAP_START__; }
[31a5f418]1314
1315        // Amount subtracted to adjust for unfreed program storage (debug only).
[032234bd]1316        __attribute__((weak)) size_t malloc_unfreed() libcfa_public { return __CFA_DEFAULT_HEAP_UNFREED__; }
[c4f68dc]1317} // extern "C"
1318
1319
[95eb7cf]1320// Must have CFA linkage to overload with C linkage realloc.
[032234bd]1321void * resize( void * oaddr, size_t nalign, size_t size ) libcfa_public {
[709b812]1322        // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
1323  if ( unlikely( size == 0 ) ) {                                                // special cases
1324                #ifdef __STATISTICS__
[31a5f418]1325                __atomic_add_fetch( &stats.resize_0_calls, 1, __ATOMIC_SEQ_CST );
[709b812]1326                #endif // __STATISTICS__
1327                free( oaddr );
1328                return 0p;
1329        } // if
[95eb7cf]1330
[c86f587]1331        if ( unlikely( nalign < libAlign() ) ) nalign = libAlign(); // reset alignment to minimum
1332        #ifdef __CFA_DEBUG__
[709b812]1333        else checkAlign( nalign );                                                      // check alignment
[c86f587]1334        #endif // __CFA_DEBUG__
1335
[92aca37]1336  if ( unlikely( oaddr == 0p ) ) {
1337                #ifdef __STATISTICS__
[31a5f418]1338                __atomic_add_fetch( &stats.resize_calls, 1, __ATOMIC_SEQ_CST );
1339                __atomic_add_fetch( &stats.resize_storage_request, size, __ATOMIC_SEQ_CST );
[92aca37]1340                #endif // __STATISTICS__
1341                return memalignNoStats( nalign, size );
1342        } // if
[cfbc703d]1343
[92847f7]1344        // Attempt to reuse existing alignment.
[19e5d65d]1345        Heap.Storage.Header * header = HeaderAddr( oaddr );
1346        bool isFakeHeader = AlignmentBit( header );                     // old fake header ?
[92847f7]1347        size_t oalign;
[19e5d65d]1348
1349        if ( unlikely( isFakeHeader ) ) {
1350                oalign = ClearAlignmentBit( header );                   // old alignment
1351                if ( unlikely( (uintptr_t)oaddr % nalign == 0   // lucky match ?
[92847f7]1352                         && ( oalign <= nalign                                          // going down
1353                                  || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ?
[19e5d65d]1354                        ) ) {
1355                        HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
[31a5f418]1356                        Heap.FreeHeader * freeElem;
[92847f7]1357                        size_t bsize, oalign;
1358                        headers( "resize", oaddr, header, freeElem, bsize, oalign );
[19e5d65d]1359                        size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
[a3ade94]1360
[92847f7]1361                        if ( size <= odsize && odsize <= size * 2 ) { // allow 50% wasted data storage
[19e5d65d]1362                                HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1363                                ClearZeroFillBit( header );                             // turn off 0 fill
[92847f7]1364                                header->kind.real.size = size;                  // reset allocation size
1365                                return oaddr;
1366                        } // if
[cfbc703d]1367                } // if
[92847f7]1368        } else if ( ! isFakeHeader                                                      // old real header (aligned on libAlign) ?
1369                                && nalign == libAlign() ) {                             // new alignment also on libAlign => no fake header needed
[113d785]1370                return resize( oaddr, size );                                   // duplicate special case checks
[cfbc703d]1371        } // if
1372
[92aca37]1373        #ifdef __STATISTICS__
[31a5f418]1374        __atomic_add_fetch( &stats.resize_storage_request, size, __ATOMIC_SEQ_CST );
[92aca37]1375        #endif // __STATISTICS__
1376
[dd23e66]1377        // change size, DO NOT preserve STICKY PROPERTIES.
[cfbc703d]1378        free( oaddr );
[dd23e66]1379        return memalignNoStats( nalign, size );                         // create new aligned area
[cfbc703d]1380} // resize
1381
1382
[032234bd]1383void * realloc( void * oaddr, size_t nalign, size_t size ) libcfa_public {
[709b812]1384        // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
1385  if ( unlikely( size == 0 ) ) {                                                // special cases
1386                #ifdef __STATISTICS__
[31a5f418]1387                __atomic_add_fetch( &stats.realloc_0_calls, 1, __ATOMIC_SEQ_CST );
[709b812]1388                #endif // __STATISTICS__
1389                free( oaddr );
1390                return 0p;
1391        } // if
1392
[c1f38e6c]1393        if ( unlikely( nalign < libAlign() ) ) nalign = libAlign(); // reset alignment to minimum
[cfbc703d]1394        #ifdef __CFA_DEBUG__
[709b812]1395        else checkAlign( nalign );                                                      // check alignment
[cfbc703d]1396        #endif // __CFA_DEBUG__
1397
[c86f587]1398  if ( unlikely( oaddr == 0p ) ) {
1399                #ifdef __STATISTICS__
[31a5f418]1400                __atomic_add_fetch( &stats.realloc_calls, 1, __ATOMIC_SEQ_CST );
1401                __atomic_add_fetch( &stats.realloc_storage_request, size, __ATOMIC_SEQ_CST );
[c86f587]1402                #endif // __STATISTICS__
1403                return memalignNoStats( nalign, size );
1404        } // if
1405
[92847f7]1406        // Attempt to reuse existing alignment.
[19e5d65d]1407        Heap.Storage.Header * header = HeaderAddr( oaddr );
1408        bool isFakeHeader = AlignmentBit( header );                     // old fake header ?
[92847f7]1409        size_t oalign;
[19e5d65d]1410        if ( unlikely( isFakeHeader ) ) {
1411                oalign = ClearAlignmentBit( header );                   // old alignment
1412                if ( unlikely( (uintptr_t)oaddr % nalign == 0   // lucky match ?
[92847f7]1413                         && ( oalign <= nalign                                          // going down
1414                                  || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ?
[19e5d65d]1415                        ) ) {
1416                        HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1417                        return realloc( oaddr, size );                          // duplicate special case checks
[92847f7]1418                } // if
1419        } else if ( ! isFakeHeader                                                      // old real header (aligned on libAlign) ?
[19e5d65d]1420                                && nalign == libAlign() ) {                             // new alignment also on libAlign => no fake header needed
1421                return realloc( oaddr, size );                                  // duplicate special case checks
1422        } // if
[cfbc703d]1423
[1e034d9]1424        #ifdef __STATISTICS__
[31a5f418]1425        __atomic_add_fetch( &stats.realloc_calls, 1, __ATOMIC_SEQ_CST );
1426        __atomic_add_fetch( &stats.realloc_storage_request, size, __ATOMIC_SEQ_CST );
[1e034d9]1427        #endif // __STATISTICS__
1428
[31a5f418]1429        Heap.FreeHeader * freeElem;
[92847f7]1430        size_t bsize;
1431        headers( "realloc", oaddr, header, freeElem, bsize, oalign );
1432
1433        // change size and copy old content to new storage
1434
[dd23e66]1435        size_t osize = header->kind.real.size;                          // old allocation size
[19e5d65d]1436        bool ozfill = ZeroFillBit( header );                            // old allocation zero filled
[dd23e66]1437
1438        void * naddr = memalignNoStats( nalign, size );         // create new aligned area
[95eb7cf]1439
[1e034d9]1440        headers( "realloc", naddr, header, freeElem, bsize, oalign );
[47dd0d2]1441        memcpy( naddr, oaddr, min( osize, size ) );                     // copy bytes
[1e034d9]1442        free( oaddr );
[d5d3a90]1443
1444        if ( unlikely( ozfill ) ) {                                                     // previous request zero fill ?
[19e5d65d]1445                MarkZeroFilledBit( header );                                    // mark new request as zero filled
[d5d3a90]1446                if ( size > osize ) {                                                   // previous request larger ?
[e4b6b7d3]1447                        memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage
[d5d3a90]1448                } // if
1449        } // if
[1e034d9]1450        return naddr;
[95eb7cf]1451} // realloc
1452
1453
[c4f68dc]1454// Local Variables: //
1455// tab-width: 4 //
[f8cd310]1456// compile-command: "cfa -nodebug -O2 heap.cfa" //
[c4f68dc]1457// End: //
Note: See TracBrowser for help on using the repository browser.