source: libcfa/src/heap.cfa @ af67ee1

ADTast-experimentalenumforall-pointer-decayjacob/cs343-translationpthread-emulationqualifiedEnum
Last change on this file since af67ee1 was b42d0ea, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

do not print unfreed-storage message if program exits

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