source: libcfa/src/heap.cfa @ 43784ac

ADTast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 43784ac was b38b22f, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

add missing heap statistic counters for free calls and free storage

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