source: libcfa/src/heap.cfa @ d5d3a90

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

abort when out of memory, return 0p for zero size allocation request, reduce storage zeroing in calloc and realloc, modify resize/realloc aligned

  • Property mode set to 100644
File size: 49.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.c --
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  3 19:01:22 2020
13// Update Count     : 828
14//
15
16#include <unistd.h>                                                                             // sbrk, sysconf
17#include <stdbool.h>                                                                    // true, false
18#include <stdio.h>                                                                              // snprintf, fileno
19#include <errno.h>                                                                              // errno
20#include <string.h>                                                                             // memset, memcpy
21#include <limits.h>                                                                             // ULONG_MAX
22#include <malloc.h>                                                                             // memalign, malloc_usable_size
23#include <sys/mman.h>                                                                   // mmap, munmap
24
25#include "bits/align.hfa"                                                               // libPow2
26#include "bits/defs.hfa"                                                                // likely, unlikely
27#include "bits/locks.hfa"                                                               // __spinlock_t
28#include "startup.hfa"                                                                  // STARTUP_PRIORITY_MEMORY
29//#include "stdlib.hfa"                                                                 // bsearchl
30#include "bitmanip.hfa"                                                                 // ceiling
31
32#define MIN(x, y) (y > x ? x : y)
33
34static bool traceHeap = false;
35
36inline bool traceHeap() { return traceHeap; }
37
38bool traceHeapOn() {
39        bool temp = traceHeap;
40        traceHeap = true;
41        return temp;
42} // traceHeapOn
43
44bool traceHeapOff() {
45        bool temp = traceHeap;
46        traceHeap = false;
47        return temp;
48} // traceHeapOff
49
50bool traceHeapTerm() { return false; }
51
52
53static bool prtFree = false;
54
55inline bool prtFree() {
56        return prtFree;
57} // prtFree
58
59bool prtFreeOn() {
60        bool temp = prtFree;
61        prtFree = true;
62        return temp;
63} // prtFreeOn
64
65bool prtFreeOff() {
66        bool temp = prtFree;
67        prtFree = false;
68        return temp;
69} // prtFreeOff
70
71
72enum {
73        // Define the default extension heap amount in units of bytes. When the uC++ supplied heap reaches the brk address,
74        // the brk address is extended by the extension amount.
75        __CFA_DEFAULT_HEAP_EXPANSION__ = (1 * 1024 * 1024),
76
77        // Define the mmap crossover point during allocation. Allocations less than this amount are allocated from buckets;
78        // values greater than or equal to this value are mmap from the operating system.
79        __CFA_DEFAULT_MMAP_START__ = (512 * 1024 + 1),
80};
81
82size_t default_heap_expansion() __attribute__(( weak )) {
83        return __CFA_DEFAULT_HEAP_EXPANSION__;
84} // default_heap_expansion
85
86size_t default_mmap_start() __attribute__(( weak )) {
87        return __CFA_DEFAULT_MMAP_START__;
88} // default_mmap_start
89
90
91#ifdef __CFA_DEBUG__
92static unsigned int allocFree;                                                  // running total of allocations minus frees
93
94static void prtUnfreed() {
95        if ( allocFree != 0 ) {
96                // DO NOT USE STREAMS AS THEY MAY BE UNAVAILABLE AT THIS POINT.
97                char helpText[512];
98                int len = snprintf( helpText, sizeof(helpText), "CFA warning (UNIX pid:%ld) : program terminating with %u(0x%x) bytes of storage allocated but not freed.\n"
99                                                        "Possible cause is unfreed storage allocated by the program or system/library routines called from the program.\n",
100                                                        (long int)getpid(), allocFree, allocFree ); // always print the UNIX pid
101                __cfaabi_bits_write( STDERR_FILENO, helpText, len ); // print debug/nodebug
102        } // if
103} // prtUnfreed
104
105extern "C" {
106        void heapAppStart() {                                                           // called by __cfaabi_appready_startup
107                allocFree = 0;
108        } // heapAppStart
109
110        void heapAppStop() {                                                            // called by __cfaabi_appready_startdown
111                fclose( stdin ); fclose( stdout );
112                prtUnfreed();
113        } // heapAppStop
114} // extern "C"
115#endif // __CFA_DEBUG__
116
117
118// statically allocated variables => zero filled.
119static size_t pageSize;                                                                 // architecture pagesize
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// Bucket size 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 int 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 long long int mmap_storage;
265static unsigned int mmap_calls;
266static unsigned long long int munmap_storage;
267static unsigned int munmap_calls;
268static unsigned long long int sbrk_storage;
269static unsigned int sbrk_calls;
270static unsigned long long int malloc_storage;
271static unsigned int malloc_calls;
272static unsigned long long int free_storage;
273static unsigned int free_calls;
274static unsigned long long int aalloc_storage;
275static unsigned int aalloc_calls;
276static unsigned long long int calloc_storage;
277static unsigned int calloc_calls;
278static unsigned long long int memalign_storage;
279static unsigned int memalign_calls;
280static unsigned long long int amemalign_storage;
281static unsigned int amemalign_calls;
282static unsigned long long int cmemalign_storage;
283static unsigned int cmemalign_calls;
284static unsigned long long int resize_storage;
285static unsigned int resize_calls;
286static unsigned long long int realloc_storage;
287static unsigned int realloc_calls;
288// Statistics file descriptor (changed by malloc_stats_fd).
289static int statfd = 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: calls %u / storage %llu\n"
297                                                                        "  aalloc: calls %u / storage %llu\n"
298                                                                        "  calloc: calls %u / storage %llu\n"
299                                                                        "  memalign: calls %u / storage %llu\n"
300                                                                        "  amemalign: calls %u / storage %llu\n"
301                                                                        "  cmemalign: calls %u / storage %llu\n"
302                                                                        "  resize: calls %u / storage %llu\n"
303                                                                        "  realloc: calls %u / storage %llu\n"
304                                                                        "  free: calls %u / storage %llu\n"
305                                                                        "  mmap: calls %u / storage %llu\n"
306                                                                        "  munmap: calls %u / storage %llu\n"
307                                                                        "  sbrk: calls %u / storage %llu\n",
308                                                                        malloc_calls, malloc_storage,
309                                                                        aalloc_calls, calloc_storage,
310                                                                        calloc_calls, calloc_storage,
311                                                                        memalign_calls, memalign_storage,
312                                                                        amemalign_calls, amemalign_storage,
313                                                                        cmemalign_calls, cmemalign_storage,
314                                                                        resize_calls, resize_storage,
315                                                                        realloc_calls, realloc_storage,
316                                                                        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\" count=\"%u\" size=\"%llu\"/>\n"
331                                                "<total type=\"aalloc\" count=\"%u\" size=\"%llu\"/>\n"
332                                                "<total type=\"calloc\" count=\"%u\" size=\"%llu\"/>\n"
333                                                "<total type=\"memalign\" count=\"%u\" size=\"%llu\"/>\n"
334                                                "<total type=\"amemalign\" count=\"%u\" size=\"%llu\"/>\n"
335                                                "<total type=\"cmemalign\" count=\"%u\" size=\"%llu\"/>\n"
336                                                "<total type=\"resize\" count=\"%u\" size=\"%llu\"/>\n"
337                                                "<total type=\"realloc\" count=\"%u\" size=\"%llu\"/>\n"
338                                                "<total type=\"free\" count=\"%u\" size=\"%llu\"/>\n"
339                                                "<total type=\"mmap\" count=\"%u\" size=\"%llu\"/>\n"
340                                                "<total type=\"munmap\" count=\"%u\" size=\"%llu\"/>\n"
341                                                "<total type=\"sbrk\" count=\"%u\" size=\"%llu\"/>\n"
342                                                "</malloc>",
343                                                malloc_calls, malloc_storage,
344                                                aalloc_calls, aalloc_storage,
345                                                calloc_calls, calloc_storage,
346                                                memalign_calls, memalign_storage,
347                                                amemalign_calls, amemalign_storage,
348                                                cmemalign_calls, cmemalign_storage,
349                                                resize_calls, resize_storage,
350                                                realloc_calls, realloc_storage,
351                                                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 < pageSize || 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
407// static inline void noMemory() {
408//      abort( "Heap memory exhausted at %zu bytes.\n"
409//                 "Possible cause is very large memory allocation and/or large amount of unfreed storage allocated by the program or system/library routines.",
410//                 ((char *)(sbrk( 0 )) - (char *)(heapManager.heapBegin)) );
411// } // noMemory
412
413
414static inline void checkAlign( size_t alignment ) {
415        if ( alignment < libAlign() || ! libPow2( alignment ) ) {
416                abort( "Alignment %zu for memory allocation is less than %d and/or not a power of 2.", alignment, libAlign() );
417        } // if
418} // checkAlign
419
420
421static inline void checkHeader( bool check, const char name[], void * addr ) {
422        if ( unlikely( check ) ) {                                                      // bad address ?
423                abort( "Attempt to %s storage %p with address outside the heap.\n"
424                           "Possible cause is duplicate free on same block or overwriting of memory.",
425                           name, addr );
426        } // if
427} // checkHeader
428
429
430static inline void fakeHeader( HeapManager.Storage.Header *& header, size_t & alignment ) {
431        if ( unlikely( (header->kind.fake.alignment & 1) == 1 ) ) { // fake header ?
432                alignment = header->kind.fake.alignment & -2;   // remove flag from value
433                #ifdef __CFA_DEBUG__
434                checkAlign( alignment );                                                // check alignment
435                #endif // __CFA_DEBUG__
436                header = realHeader( header );                                  // backup from fake to real header
437        } else {
438                alignment = 0;
439        } // if
440} // fakeHeader
441
442
443static inline bool headers( const char name[] __attribute__(( unused )), void * addr, HeapManager.Storage.Header *& header, HeapManager.FreeHeader *& freeElem,
444                                                        size_t & size, size_t & alignment ) with( heapManager ) {
445        header = headerAddr( addr );
446
447        if ( unlikely( heapEnd < addr ) ) {                                     // mmapped ?
448                fakeHeader( header, alignment );
449                size = header->kind.real.blockSize & -3;                // mmap size
450                return true;
451        } // if
452
453        #ifdef __CFA_DEBUG__
454        checkHeader( addr < heapBegin, name, addr );            // bad low address ?
455        #endif // __CFA_DEBUG__
456
457        // header may be safe to dereference
458        fakeHeader( header, alignment );
459        #ifdef __CFA_DEBUG__
460        checkHeader( header < (HeapManager.Storage.Header *)heapBegin || (HeapManager.Storage.Header *)heapEnd < header, name, addr ); // bad address ? (offset could be + or -)
461        #endif // __CFA_DEBUG__
462
463        freeElem = (HeapManager.FreeHeader *)((size_t)header->kind.real.home & -3);
464        #ifdef __CFA_DEBUG__
465        if ( freeElem < &freeLists[0] || &freeLists[NoBucketSizes] <= freeElem ) {
466                abort( "Attempt to %s storage %p with corrupted header.\n"
467                           "Possible cause is duplicate free on same block or overwriting of header information.",
468                           name, addr );
469        } // if
470        #endif // __CFA_DEBUG__
471        size = freeElem->blockSize;
472        return false;
473} // headers
474
475
476static inline void * extend( size_t size ) with( heapManager ) {
477        lock( extlock __cfaabi_dbg_ctx2 );
478        ptrdiff_t rem = heapRemaining - size;
479        if ( rem < 0 ) {
480                // If the size requested is bigger than the current remaining storage, increase the size of the heap.
481
482                size_t increase = libCeiling( size > heapExpand ? size : heapExpand, libAlign() );
483                if ( sbrk( increase ) == (void *)-1 ) {
484                        unlock( extlock );
485                        errno = ENOMEM;
486//                      return 0p;
487                        abort( "no memory" );
488                } // if
489                #ifdef __STATISTICS__
490                sbrk_calls += 1;
491                sbrk_storage += increase;
492                #endif // __STATISTICS__
493                #ifdef __CFA_DEBUG__
494                // Set new memory to garbage so subsequent uninitialized usages might fail.
495                memset( (char *)heapEnd + heapRemaining, '\377', increase );
496                #endif // __CFA_DEBUG__
497                rem = heapRemaining + increase - size;
498        } // if
499
500        HeapManager.Storage * block = (HeapManager.Storage *)heapEnd;
501        heapRemaining = rem;
502        heapEnd = (char *)heapEnd + size;
503        unlock( extlock );
504        return block;
505} // extend
506
507
508static inline void * doMalloc( size_t size ) with( heapManager ) {
509        HeapManager.Storage * block;                                            // pointer to new block of storage
510
511        // Look up size in the size list.  Make sure the user request includes space for the header that must be allocated
512        // along with the block and is a multiple of the alignment size.
513
514  if ( unlikely( size > ULONG_MAX - sizeof(HeapManager.Storage) ) ) return 0p;
515        size_t tsize = size + sizeof(HeapManager.Storage);
516        if ( likely( tsize < mmapStart ) ) {                            // small size => sbrk
517                size_t posn;
518                #ifdef FASTLOOKUP
519                if ( tsize < LookupSizes ) posn = lookup[tsize];
520                else
521                #endif // FASTLOOKUP
522                        posn = Bsearchl( (unsigned int)tsize, bucketSizes, (size_t)maxBucketsUsed );
523                HeapManager.FreeHeader * freeElem = &freeLists[posn];
524                // #ifdef FASTLOOKUP
525                // if ( tsize < LookupSizes )
526                //      freeElem = &freeLists[lookup[tsize]];
527                // else
528                // #endif // FASTLOOKUP
529                //      freeElem = bsearchl( tsize, freeLists, (size_t)maxBucketsUsed ); // binary search
530                // HeapManager.FreeHeader * freeElem =
531                //      #ifdef FASTLOOKUP
532                //      tsize < LookupSizes ? &freeLists[lookup[tsize]] :
533                //      #endif // FASTLOOKUP
534                //      bsearchl( tsize, freeLists, (size_t)maxBucketsUsed ); // binary search
535                assert( freeElem <= &freeLists[maxBucketsUsed] ); // subscripting error ?
536                assert( tsize <= freeElem->blockSize );                 // search failure ?
537                tsize = freeElem->blockSize;                                    // total space needed for request
538
539                // Spin until the lock is acquired for this particular size of block.
540
541                #if BUCKETLOCK == SPINLOCK
542                lock( freeElem->lock __cfaabi_dbg_ctx2 );
543                block = freeElem->freeList;                                             // remove node from stack
544                #else
545                block = pop( freeElem->freeList );
546                #endif // BUCKETLOCK
547                if ( unlikely( block == 0p ) ) {                                // no free block ?
548                        #if BUCKETLOCK == SPINLOCK
549                        unlock( freeElem->lock );
550                        #endif // BUCKETLOCK
551
552                        // Freelist for that size was empty, so carve it out of the heap if there's enough left, or get some more
553                        // and then carve it off.
554
555                        block = (HeapManager.Storage *)extend( tsize ); // mutual exclusion on call
556//      if ( unlikely( block == 0p ) ) return 0p;
557                #if BUCKETLOCK == SPINLOCK
558                } else {
559                        freeElem->freeList = block->header.kind.real.next;
560                        unlock( freeElem->lock );
561                #endif // BUCKETLOCK
562                } // if
563
564                block->header.kind.real.home = freeElem;                // pointer back to free list of apropriate size
565        } else {                                                                                        // large size => mmap
566  if ( unlikely( size > ULONG_MAX - pageSize ) ) return 0p;
567                tsize = libCeiling( tsize, pageSize );                  // must be multiple of page size
568                #ifdef __STATISTICS__
569                __atomic_add_fetch( &mmap_calls, 1, __ATOMIC_SEQ_CST );
570                __atomic_add_fetch( &mmap_storage, tsize, __ATOMIC_SEQ_CST );
571                #endif // __STATISTICS__
572                block = (HeapManager.Storage *)mmap( 0, tsize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, mmapFd, 0 );
573                if ( block == (HeapManager.Storage *)MAP_FAILED ) {
574                        // Do not call strerror( errno ) as it may call malloc.
575                        abort( "(HeapManager &)0x%p.doMalloc() : internal error, mmap failure, size:%zu error:%d.", &heapManager, tsize, errno );
576                } // if
577                #ifdef __CFA_DEBUG__
578                // Set new memory to garbage so subsequent uninitialized usages might fail.
579                memset( block, '\377', tsize );
580                #endif // __CFA_DEBUG__
581                block->header.kind.real.blockSize = tsize;              // storage size for munmap
582        } // if
583
584        block->header.kind.real.size = size;                            // store allocation size
585        void * addr = &(block->data);                                           // adjust off header to user bytes
586
587        #ifdef __CFA_DEBUG__
588        assert( ((uintptr_t)addr & (libAlign() - 1)) == 0 ); // minimum alignment ?
589        __atomic_add_fetch( &allocFree, tsize, __ATOMIC_SEQ_CST );
590        if ( traceHeap() ) {
591                enum { BufferSize = 64 };
592                char helpText[BufferSize];
593                int len = snprintf( helpText, BufferSize, "%p = Malloc( %zu ) (allocated %zu)\n", addr, size, tsize );
594                // int len = snprintf( helpText, BufferSize, "Malloc %p %zu\n", addr, size );
595                __cfaabi_bits_write( STDERR_FILENO, helpText, len ); // print debug/nodebug
596        } // if
597        #endif // __CFA_DEBUG__
598
599        return addr;
600} // doMalloc
601
602
603static inline void doFree( void * addr ) with( heapManager ) {
604        #ifdef __CFA_DEBUG__
605        if ( unlikely( heapManager.heapBegin == 0p ) ) {
606                abort( "doFree( %p ) : internal error, called before heap is initialized.", addr );
607        } // if
608        #endif // __CFA_DEBUG__
609
610        HeapManager.Storage.Header * header;
611        HeapManager.FreeHeader * freeElem;
612        size_t size, alignment;                                                         // not used (see realloc)
613
614        if ( headers( "free", addr, header, freeElem, size, alignment ) ) { // mmapped ?
615                #ifdef __STATISTICS__
616                __atomic_add_fetch( &munmap_calls, 1, __ATOMIC_SEQ_CST );
617                __atomic_add_fetch( &munmap_storage, size, __ATOMIC_SEQ_CST );
618                #endif // __STATISTICS__
619                if ( munmap( header, size ) == -1 ) {
620                        #ifdef __CFA_DEBUG__
621                        abort( "Attempt to deallocate storage %p not allocated or with corrupt header.\n"
622                                   "Possible cause is invalid pointer.",
623                                   addr );
624                        #endif // __CFA_DEBUG__
625                } // if
626        } else {
627                #ifdef __CFA_DEBUG__
628                // Set free memory to garbage so subsequent usages might fail.
629                memset( ((HeapManager.Storage *)header)->data, '\377', freeElem->blockSize - sizeof( HeapManager.Storage ) );
630                #endif // __CFA_DEBUG__
631
632                #ifdef __STATISTICS__
633                free_storage += size;
634                #endif // __STATISTICS__
635                #if BUCKETLOCK == SPINLOCK
636                lock( freeElem->lock __cfaabi_dbg_ctx2 );               // acquire spin lock
637                header->kind.real.next = freeElem->freeList;    // push on stack
638                freeElem->freeList = (HeapManager.Storage *)header;
639                unlock( freeElem->lock );                                               // release spin lock
640                #else
641                push( freeElem->freeList, *(HeapManager.Storage *)header );
642                #endif // BUCKETLOCK
643        } // if
644
645        #ifdef __CFA_DEBUG__
646        __atomic_add_fetch( &allocFree, -size, __ATOMIC_SEQ_CST );
647        if ( traceHeap() ) {
648                enum { BufferSize = 64 };
649                char helpText[BufferSize];
650                int len = snprintf( helpText, sizeof(helpText), "Free( %p ) size:%zu\n", addr, size );
651                __cfaabi_bits_write( STDERR_FILENO, helpText, len ); // print debug/nodebug
652        } // if
653        #endif // __CFA_DEBUG__
654} // doFree
655
656
657size_t prtFree( HeapManager & manager ) with( manager ) {
658        size_t total = 0;
659        #ifdef __STATISTICS__
660        __cfaabi_bits_acquire();
661        __cfaabi_bits_print_nolock( STDERR_FILENO, "\nBin lists (bin size : free blocks on list)\n" );
662        #endif // __STATISTICS__
663        for ( unsigned int i = 0; i < maxBucketsUsed; i += 1 ) {
664                size_t size = freeLists[i].blockSize;
665                #ifdef __STATISTICS__
666                unsigned int N = 0;
667                #endif // __STATISTICS__
668
669                #if BUCKETLOCK == SPINLOCK
670                for ( HeapManager.Storage * p = freeLists[i].freeList; p != 0p; p = p->header.kind.real.next ) {
671                #else
672                for ( HeapManager.Storage * p = top( freeLists[i].freeList ); p != 0p; /* p = getNext( p )->top */) {
673                        typeof(p) temp = ( p )`next->top;                       // FIX ME: direct assignent fails, initialization works
674                        p = temp;
675                #endif // BUCKETLOCK
676                        total += size;
677                        #ifdef __STATISTICS__
678                        N += 1;
679                        #endif // __STATISTICS__
680                } // for
681
682                #ifdef __STATISTICS__
683                __cfaabi_bits_print_nolock( STDERR_FILENO, "%7zu, %-7u  ", size, N );
684                if ( (i + 1) % 8 == 0 ) __cfaabi_bits_print_nolock( STDERR_FILENO, "\n" );
685                #endif // __STATISTICS__
686        } // for
687        #ifdef __STATISTICS__
688        __cfaabi_bits_print_nolock( STDERR_FILENO, "\ntotal free blocks:%zu\n", total );
689        __cfaabi_bits_release();
690        #endif // __STATISTICS__
691        return (char *)heapEnd - (char *)heapBegin - total;
692} // prtFree
693
694
695static void ?{}( HeapManager & manager ) with( manager ) {
696        pageSize = sysconf( _SC_PAGESIZE );
697
698        for ( unsigned int i = 0; i < NoBucketSizes; i += 1 ) { // initialize the free lists
699                freeLists[i].blockSize = bucketSizes[i];
700        } // for
701
702        #ifdef FASTLOOKUP
703        unsigned int idx = 0;
704        for ( unsigned int i = 0; i < LookupSizes; i += 1 ) {
705                if ( i > bucketSizes[idx] ) idx += 1;
706                lookup[i] = idx;
707        } // for
708        #endif // FASTLOOKUP
709
710        if ( ! setMmapStart( default_mmap_start() ) ) {
711                abort( "HeapManager : internal error, mmap start initialization failure." );
712        } // if
713        heapExpand = default_heap_expansion();
714
715        char * end = (char *)sbrk( 0 );
716        heapBegin = heapEnd = sbrk( (char *)libCeiling( (long unsigned int)end, libAlign() ) - end ); // move start of heap to multiple of alignment
717} // HeapManager
718
719
720static void ^?{}( HeapManager & ) {
721        #ifdef __STATISTICS__
722        if ( traceHeapTerm() ) {
723                printStats();
724                // if ( prtfree() ) prtFree( heapManager, true );
725        } // if
726        #endif // __STATISTICS__
727} // ~HeapManager
728
729
730static void memory_startup( void ) __attribute__(( constructor( STARTUP_PRIORITY_MEMORY ) ));
731void memory_startup( void ) {
732        #ifdef __CFA_DEBUG__
733        if ( unlikely( heapBoot ) ) {                                           // check for recursion during system boot
734                // DO NOT USE STREAMS AS THEY MAY BE UNAVAILABLE AT THIS POINT.
735                abort( "boot() : internal error, recursively invoked during system boot." );
736        } // if
737        heapBoot = true;
738        #endif // __CFA_DEBUG__
739
740        //assert( heapManager.heapBegin != 0 );
741        //heapManager{};
742        if ( heapManager.heapBegin == 0p ) heapManager{};       // sanity check
743} // memory_startup
744
745static void memory_shutdown( void ) __attribute__(( destructor( STARTUP_PRIORITY_MEMORY ) ));
746void memory_shutdown( void ) {
747        ^heapManager{};
748} // memory_shutdown
749
750
751static inline void * mallocNoStats( size_t size ) {             // necessary for malloc statistics
752        verify( heapManager.heapBegin != 0 );                           // called before memory_startup ?
753  if ( size == 0 ) return 0p;                                                   // 0 BYTE ALLOCATION RETURNS NULL POINTER
754
755#if __SIZEOF_POINTER__ == 8
756        verify( size < ((typeof(size_t))1 << 48) );
757#endif // __SIZEOF_POINTER__ == 8
758        return doMalloc( size );
759} // mallocNoStats
760
761
762static inline void * callocNoStats( size_t dim, size_t elemSize ) {
763        size_t size = dim * elemSize;
764  if ( size == 0 ) return 0p;                                                   // 0 BYTE ALLOCATION RETURNS NULL POINTER
765        char * addr = (char *)mallocNoStats( size );
766
767        HeapManager.Storage.Header * header;
768        HeapManager.FreeHeader * freeElem;
769        size_t bsize, alignment;
770        #ifndef __CFA_DEBUG__
771        bool mapped =
772        #endif // __CFA_DEBUG__
773                headers( "calloc", addr, header, freeElem, bsize, alignment );
774        #ifndef __CFA_DEBUG__
775        // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
776        if ( ! mapped )
777        #endif // __CFA_DEBUG__
778                // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined
779                // `-header`-addr                      `-size
780                memset( addr, '\0', size );                                             // set to zeros
781
782        header->kind.real.blockSize |= 2;                                       // mark as zero filled
783        return addr;
784} // callocNoStats
785
786
787static inline void * memalignNoStats( size_t alignment, size_t size ) { // necessary for malloc statistics
788  if ( size == 0 ) return 0p;                                                   // 0 BYTE ALLOCATION RETURNS NULL POINTER
789
790        #ifdef __CFA_DEBUG__
791        checkAlign( alignment );                                                        // check alignment
792        #endif // __CFA_DEBUG__
793
794        // if alignment <= default alignment, do normal malloc as two headers are unnecessary
795  if ( unlikely( alignment <= libAlign() ) ) return mallocNoStats( size );
796
797        // Allocate enough storage to guarantee an address on the alignment boundary, and sufficient space before it for
798        // administrative storage. NOTE, WHILE THERE ARE 2 HEADERS, THE FIRST ONE IS IMPLICITLY CREATED BY DOMALLOC.
799        //      .-------------v-----------------v----------------v----------,
800        //      | Real Header | ... padding ... |   Fake Header  | data ... |
801        //      `-------------^-----------------^-+--------------^----------'
802        //      |<--------------------------------' offset/align |<-- alignment boundary
803
804        // subtract libAlign() because it is already the minimum alignment
805        // add sizeof(Storage) for fake header
806        char * addr = (char *)mallocNoStats( size + alignment - libAlign() + sizeof(HeapManager.Storage) );
807
808        // address in the block of the "next" alignment address
809        char * user = (char *)libCeiling( (uintptr_t)(addr + sizeof(HeapManager.Storage)), alignment );
810
811        // address of header from malloc
812        HeapManager.Storage.Header * realHeader = headerAddr( addr );
813        realHeader->kind.real.size = size;                                      // correct size to eliminate above alignment offset
814        // address of fake header * before* the alignment location
815        HeapManager.Storage.Header * fakeHeader = headerAddr( user );
816        // SKULLDUGGERY: insert the offset to the start of the actual storage block and remember alignment
817        fakeHeader->kind.fake.offset = (char *)fakeHeader - (char *)realHeader;
818        // SKULLDUGGERY: odd alignment imples fake header
819        fakeHeader->kind.fake.alignment = alignment | 1;
820
821        return user;
822} // memalignNoStats
823
824
825static inline void * cmemalignNoStats( size_t alignment, size_t dim, size_t elemSize ) {
826        size_t size = dim * elemSize;
827  if ( size == 0 ) return 0p;                                                   // 0 BYTE ALLOCATION RETURNS NULL POINTER
828        char * addr = (char *)memalignNoStats( alignment, size );
829
830        HeapManager.Storage.Header * header;
831        HeapManager.FreeHeader * freeElem;
832        size_t bsize;
833        bool mapped __attribute__(( unused )) = headers( "cmemalign", addr, header, freeElem, bsize, alignment );
834        #ifndef __CFA_DEBUG__
835        // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
836        if ( ! mapped )
837        #endif // __CFA_DEBUG__
838                memset( addr, '\0', dataStorage( bsize, addr, header ) ); // set to zeros
839
840        header->kind.real.blockSize |= 2;                                       // mark as zero filled
841        return addr;
842} // cmemalignNoStats
843
844
845// supported mallopt options
846#ifndef M_MMAP_THRESHOLD
847#define M_MMAP_THRESHOLD (-1)
848#endif // M_TOP_PAD
849#ifndef M_TOP_PAD
850#define M_TOP_PAD (-2)
851#endif // M_TOP_PAD
852
853
854extern "C" {
855        // Allocates size bytes and returns a pointer to the allocated memory.  The contents are undefined. If size is 0,
856        // then malloc() returns a unique pointer value that can later be successfully passed to free().
857        void * malloc( size_t size ) {
858                #ifdef __STATISTICS__
859                __atomic_add_fetch( &malloc_calls, 1, __ATOMIC_SEQ_CST );
860                __atomic_add_fetch( &malloc_storage, size, __ATOMIC_SEQ_CST );
861                #endif // __STATISTICS__
862
863                return mallocNoStats( size );
864        } // malloc
865
866
867        // Same as malloc() except size bytes is an array of dim elements each of elemSize bytes.
868        void * aalloc( size_t dim, size_t elemSize ) {
869                #ifdef __STATISTICS__
870                __atomic_add_fetch( &aalloc_calls, 1, __ATOMIC_SEQ_CST );
871                __atomic_add_fetch( &aalloc_storage, dim * elemSize, __ATOMIC_SEQ_CST );
872                #endif // __STATISTICS__
873
874                return mallocNoStats( dim * elemSize );
875        } // aalloc
876
877
878        // Same as aalloc() with memory set to zero.
879        void * calloc( size_t dim, size_t elemSize ) {
880                #ifdef __STATISTICS__
881                __atomic_add_fetch( &calloc_calls, 1, __ATOMIC_SEQ_CST );
882                __atomic_add_fetch( &calloc_storage, dim * elemSize, __ATOMIC_SEQ_CST );
883                #endif // __STATISTICS__
884
885                return callocNoStats( dim, elemSize );
886        } // calloc
887
888        // Change the size of the memory block pointed to by oaddr to size bytes. The contents are undefined.  If oaddr is
889        // 0p, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and oaddr is
890        // not 0p, then the call is equivalent to free(oaddr). Unless oaddr is 0p, it must have been returned by an earlier
891        // call to malloc(), alloc(), calloc() or realloc(). If the area pointed to was moved, a free(oaddr) is done.
892        void * resize( void * oaddr, size_t size ) {
893                #ifdef __STATISTICS__
894                __atomic_add_fetch( &resize_calls, 1, __ATOMIC_SEQ_CST );
895                __atomic_add_fetch( &resize_storage, size, __ATOMIC_SEQ_CST );
896                #endif // __STATISTICS__
897
898                // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
899          if ( unlikely( size == 0 ) ) { free( oaddr ); return 0p; } // special cases
900          if ( unlikely( oaddr == 0p ) ) return mallocNoStats( size );
901
902                HeapManager.Storage.Header * header;
903                HeapManager.FreeHeader * freeElem;
904                size_t bsize, oalign = 0;
905                headers( "resize", oaddr, header, freeElem, bsize, oalign );
906
907                size_t odsize = dataStorage( bsize, oaddr, header ); // data storage available in bucket
908                // same size, DO NOT preserve STICKY PROPERTIES.
909          if ( oalign == 0 && size <= odsize && odsize <= size * 2 ) { // allow 50% wasted storage for smaller size
910                        header->kind.real.blockSize &= -2;                      // no alignment and turn off 0 fill
911                        header->kind.real.size = size;                          // reset allocation size
912                        return oaddr;
913                } // if
914
915                // change size, DO NOT preserve STICKY PROPERTIES.
916                free( oaddr );
917                return mallocNoStats( size );                                   // create new area
918        } // resize
919
920
921        // Same as resize() but the contents are unchanged in the range from the start of the region up to the minimum of
922        // the old and new sizes.
923        void * realloc( void * oaddr, size_t size ) {
924                #ifdef __STATISTICS__
925                __atomic_add_fetch( &realloc_calls, 1, __ATOMIC_SEQ_CST );
926                __atomic_add_fetch( &realloc_storage, size, __ATOMIC_SEQ_CST );
927                #endif // __STATISTICS__
928
929                // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
930          if ( unlikely( size == 0 ) ) { free( oaddr ); return 0p; } // special cases
931          if ( unlikely( oaddr == 0p ) ) return mallocNoStats( size );
932
933                HeapManager.Storage.Header * header;
934                HeapManager.FreeHeader * freeElem;
935                size_t bsize, oalign = 0;
936                headers( "realloc", oaddr, header, freeElem, bsize, oalign );
937
938                size_t odsize = dataStorage( bsize, oaddr, header ); // data storage available in bucket
939                size_t osize = header->kind.real.size;                  // old allocation size
940                bool ozfill = (header->kind.real.blockSize & 2) != 0; // old allocation zero filled
941          if ( unlikely( size <= odsize ) && size > odsize / 2 ) { // allow up to 50% wasted storage
942                        header->kind.real.size = size;                          // reset allocation size
943                        if ( unlikely( ozfill ) && size > osize ) {     // previous request zero fill and larger ?
944                                memset( (char *)oaddr + osize, (int)'\0', size - osize ); // initialize added storage
945                        } // if
946                        return oaddr;
947                } // if
948
949                // change size and copy old content to new storage
950
951                void * naddr;
952                if ( likely( oalign == 0 ) ) {                                  // previous request memalign?
953                        naddr = mallocNoStats( size );                          // create new area
954                } else {
955                        naddr = memalignNoStats( oalign, size );        // create new aligned area
956                } // if
957
958                headers( "realloc", naddr, header, freeElem, bsize, oalign );
959                memcpy( naddr, oaddr, MIN( osize, size ) );             // copy bytes
960                free( oaddr );
961
962                if ( unlikely( ozfill ) ) {                                             // previous request zero fill ?
963                        header->kind.real.blockSize |= 2;                       // mark new request as zero filled
964                        if ( size > osize ) {                                           // previous request larger ?
965                                memset( (char *)naddr + osize, (int)'\0', size - osize ); // initialize added storage
966                        } // if
967                } // if
968                return naddr;
969        } // realloc
970
971        // Same as malloc() except the memory address is a multiple of alignment, which must be a power of two. (obsolete)
972        void * memalign( size_t alignment, size_t size ) {
973                #ifdef __STATISTICS__
974                __atomic_add_fetch( &memalign_calls, 1, __ATOMIC_SEQ_CST );
975                __atomic_add_fetch( &memalign_storage, size, __ATOMIC_SEQ_CST );
976                #endif // __STATISTICS__
977
978                return memalignNoStats( alignment, size );
979        } // memalign
980
981
982        // Same as aalloc() with memory alignment.
983        void * amemalign( size_t alignment, size_t dim, size_t elemSize ) {
984                #ifdef __STATISTICS__
985                __atomic_add_fetch( &cmemalign_calls, 1, __ATOMIC_SEQ_CST );
986                __atomic_add_fetch( &cmemalign_storage, dim * elemSize, __ATOMIC_SEQ_CST );
987                #endif // __STATISTICS__
988
989                return memalignNoStats( alignment, dim * elemSize );
990        } // amemalign
991
992
993        // Same as calloc() with memory alignment.
994        void * cmemalign( size_t alignment, size_t dim, size_t elemSize ) {
995                #ifdef __STATISTICS__
996                __atomic_add_fetch( &cmemalign_calls, 1, __ATOMIC_SEQ_CST );
997                __atomic_add_fetch( &cmemalign_storage, dim * elemSize, __ATOMIC_SEQ_CST );
998                #endif // __STATISTICS__
999
1000                return cmemalignNoStats( alignment, dim, elemSize );
1001        } // cmemalign
1002
1003        // Same as memalign(), but ISO/IEC 2011 C11 Section 7.22.2 states: the value of size shall be an integral multiple
1004    // of alignment. This requirement is universally ignored.
1005        void * aligned_alloc( size_t alignment, size_t size ) {
1006                return memalign( alignment, size );
1007        } // aligned_alloc
1008
1009
1010        // Allocates size bytes and places the address of the allocated memory in *memptr. The address of the allocated
1011        // memory shall be a multiple of alignment, which must be a power of two and a multiple of sizeof(void *). If size
1012        // is 0, then posix_memalign() returns either 0p, or a unique pointer value that can later be successfully passed to
1013        // free(3).
1014        int posix_memalign( void ** memptr, size_t alignment, size_t size ) {
1015          if ( alignment < sizeof(void *) || ! libPow2( alignment ) ) return EINVAL; // check alignment
1016                * memptr = memalign( alignment, size );
1017                return 0;
1018        } // posix_memalign
1019
1020        // Allocates size bytes and returns a pointer to the allocated memory. The memory address shall be a multiple of the
1021        // page size.  It is equivalent to memalign(sysconf(_SC_PAGESIZE),size).
1022        void * valloc( size_t size ) {
1023                return memalign( pageSize, size );
1024        } // valloc
1025
1026
1027        // Same as valloc but rounds size to multiple of page size.
1028        void * pvalloc( size_t size ) {
1029                return memalign( pageSize, libCeiling( size, pageSize ) );
1030        } // pvalloc
1031
1032
1033        // Frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc()
1034        // or realloc().  Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is
1035        // 0p, no operation is performed.
1036        void free( void * addr ) {
1037                #ifdef __STATISTICS__
1038                __atomic_add_fetch( &free_calls, 1, __ATOMIC_SEQ_CST );
1039                #endif // __STATISTICS__
1040
1041          if ( unlikely( addr == 0p ) ) {                                       // special case
1042                        // #ifdef __CFA_DEBUG__
1043                        // if ( traceHeap() ) {
1044                        //      #define nullmsg "Free( 0x0 ) size:0\n"
1045                        //      // Do not debug print free( 0p ), as it can cause recursive entry from sprintf.
1046                        //      __cfaabi_dbg_write( nullmsg, sizeof(nullmsg) - 1 );
1047                        // } // if
1048                        // #endif // __CFA_DEBUG__
1049                        return;
1050                } // exit
1051
1052                doFree( addr );
1053        } // free
1054
1055
1056        // Returns the alignment of an allocation.
1057        size_t malloc_alignment( void * addr ) {
1058          if ( unlikely( addr == 0p ) ) return libAlign();      // minimum alignment
1059                HeapManager.Storage.Header * header = headerAddr( addr );
1060                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
1061                        return header->kind.fake.alignment & -2;        // remove flag from value
1062                } else {
1063                        return libAlign();                                                      // minimum alignment
1064                } // if
1065        } // malloc_alignment
1066
1067        // Set the alignment for an the allocation and return previous alignment or 0 if no alignment.
1068        size_t $malloc_alignment_set( void * addr, size_t alignment ) {
1069          if ( unlikely( addr == 0p ) ) return libAlign();      // minimum alignment
1070                size_t ret;
1071                HeapManager.Storage.Header * header = headerAddr( addr );
1072                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
1073                        ret = header->kind.fake.alignment & -2;         // remove flag from old value
1074                        header->kind.fake.alignment = alignment | 1; // add flag to new value
1075                } else {
1076                        ret = 0;                                                                        // => no alignment to change
1077                } // if
1078                return ret;
1079        } // $malloc_alignment_set
1080
1081
1082        // Returns true if the allocation is zero filled, e.g., allocated by calloc().
1083        bool malloc_zero_fill( void * addr ) {
1084          if ( unlikely( addr == 0p ) ) return false;           // null allocation is not zero fill
1085                HeapManager.Storage.Header * header = headerAddr( addr );
1086                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
1087                        header = realHeader( header );                          // backup from fake to real header
1088                } // if
1089                return (header->kind.real.blockSize & 2) != 0;  // zero filled ?
1090        } // malloc_zero_fill
1091
1092        // Set allocation is zero filled and return previous zero filled.
1093        bool $malloc_zero_fill_set( void * addr ) {
1094          if ( unlikely( addr == 0p ) ) return false;           // null allocation is not zero fill
1095                HeapManager.Storage.Header * header = headerAddr( addr );
1096                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
1097                        header = realHeader( header );                          // backup from fake to real header
1098                } // if
1099                bool ret = (header->kind.real.blockSize & 2) != 0; // zero filled ?
1100                header->kind.real.blockSize |= 2;                               // mark as zero filled
1101                return ret;
1102        } // $malloc_zero_fill_set
1103
1104
1105        // Returns original total allocation size (not bucket size) => array size is dimension * sizeif(T).
1106        size_t malloc_size( void * addr ) {
1107          if ( unlikely( addr == 0p ) ) return 0;                       // null allocation has zero size
1108                HeapManager.Storage.Header * header = headerAddr( addr );
1109                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
1110                        header = realHeader( header );                          // backup from fake to real header
1111                } // if
1112                return header->kind.real.size;
1113        } // malloc_size
1114
1115        // Set allocation size and return previous size.
1116        size_t $malloc_size_set( void * addr, size_t size ) {
1117          if ( unlikely( addr == 0p ) ) return 0;                       // null allocation has 0 size
1118                HeapManager.Storage.Header * header = headerAddr( addr );
1119                if ( (header->kind.fake.alignment & 1) == 1 ) { // fake header ?
1120                        header = realHeader( header );                          // backup from fake to real header
1121                } // if
1122                size_t ret = header->kind.real.size;
1123                header->kind.real.size = size;
1124                return ret;
1125        } // $malloc_size_set
1126
1127
1128        // Returns the number of usable bytes in the block pointed to by ptr, a pointer to a block of memory allocated by
1129        // malloc or a related function.
1130        size_t malloc_usable_size( void * addr ) {
1131          if ( unlikely( addr == 0p ) ) return 0;                       // null allocation has 0 size
1132                HeapManager.Storage.Header * header;
1133                HeapManager.FreeHeader * freeElem;
1134                size_t bsize, alignment;
1135
1136                headers( "malloc_usable_size", addr, header, freeElem, bsize, alignment );
1137                return dataStorage( bsize, addr, header );      // data storage in bucket
1138        } // malloc_usable_size
1139
1140
1141        // Prints (on default standard error) statistics about memory allocated by malloc and related functions.
1142        void malloc_stats( void ) {
1143                #ifdef __STATISTICS__
1144                printStats();
1145                if ( prtFree() ) prtFree( heapManager );
1146                #endif // __STATISTICS__
1147        } // malloc_stats
1148
1149        // Changes the file descripter where malloc_stats() writes statistics.
1150        int malloc_stats_fd( int fd __attribute__(( unused )) ) {
1151                #ifdef __STATISTICS__
1152                int temp = statfd;
1153                statfd = fd;
1154                return temp;
1155                #else
1156                return -1;
1157                #endif // __STATISTICS__
1158        } // malloc_stats_fd
1159
1160
1161        // Adjusts parameters that control the behaviour of the memory-allocation functions (see malloc). The param argument
1162        // specifies the parameter to be modified, and value specifies the new value for that parameter.
1163        int mallopt( int option, int value ) {
1164                choose( option ) {
1165                  case M_TOP_PAD:
1166                        heapExpand = ceiling( value, pageSize ); return 1;
1167                  case M_MMAP_THRESHOLD:
1168                        if ( setMmapStart( value ) ) return 1;
1169                        break;
1170                } // switch
1171                return 0;                                                                               // error, unsupported
1172        } // mallopt
1173
1174        // Attempt to release free memory at the top of the heap (by calling sbrk with a suitable argument).
1175        int malloc_trim( size_t ) {
1176                return 0;                                                                               // => impossible to release memory
1177        } // malloc_trim
1178
1179
1180        // Exports an XML string that describes the current state of the memory-allocation implementation in the caller.
1181        // The string is printed on the file stream stream.  The exported string includes information about all arenas (see
1182        // malloc).
1183        int malloc_info( int options, FILE * stream ) {
1184                if ( options != 0 ) { errno = EINVAL; return -1; }
1185                return printStatsXML( stream );
1186        } // malloc_info
1187
1188
1189        // Records the current state of all malloc internal bookkeeping variables (but not the actual contents of the heap
1190        // or the state of malloc_hook functions pointers).  The state is recorded in a system-dependent opaque data
1191        // structure dynamically allocated via malloc, and a pointer to that data structure is returned as the function
1192        // result.  (The caller must free this memory.)
1193        void * malloc_get_state( void ) {
1194                return 0p;                                                                              // unsupported
1195        } // malloc_get_state
1196
1197
1198        // Restores the state of all malloc internal bookkeeping variables to the values recorded in the opaque data
1199        // structure pointed to by state.
1200        int malloc_set_state( void * ptr ) {
1201                return 0;                                                                               // unsupported
1202        } // malloc_set_state
1203} // extern "C"
1204
1205
1206// Must have CFA linkage to overload with C linkage realloc.
1207void * resize( void * oaddr, size_t nalign, size_t size ) {
1208        #ifdef __STATISTICS__
1209        __atomic_add_fetch( &resize_calls, 1, __ATOMIC_SEQ_CST );
1210        __atomic_add_fetch( &resize_storage, size, __ATOMIC_SEQ_CST );
1211        #endif // __STATISTICS__
1212
1213        // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
1214  if ( unlikely( size == 0 ) ) { free( oaddr ); return 0p; } // special cases
1215  if ( unlikely( oaddr == 0p ) ) return memalignNoStats( nalign, size );
1216
1217        if ( unlikely( nalign == 0 ) ) nalign = libAlign();     // reset alignment to minimum
1218        #ifdef __CFA_DEBUG__
1219        else
1220                checkAlign( nalign );                                                   // check alignment
1221        #endif // __CFA_DEBUG__
1222
1223        HeapManager.Storage.Header * header;
1224        HeapManager.FreeHeader * freeElem;
1225        size_t bsize, oalign = 0;
1226        headers( "resize", oaddr, header, freeElem, bsize, oalign );
1227        size_t odsize = dataStorage( bsize, oaddr, header ); // data storage available in bucket
1228
1229        if ( oalign <= nalign && (uintptr_t)oaddr % nalign == 0 ) { // <= alignment and new alignment happens to match
1230                if ( oalign >= libAlign() ) {                                   // fake header ?
1231                        headerAddr( oaddr )->kind.fake.alignment = nalign | 1; // update alignment (could be the same)
1232                } // if
1233                if ( size <= odsize && odsize <= size * 2 ) {   // allow 50% wasted storage for smaller size
1234                        header->kind.real.blockSize &= -2;                      // turn off 0 fill
1235                        if ( size != odsize ) header->kind.real.size = size; // reset allocation size
1236                        return oaddr;
1237                } // if
1238        } // if
1239
1240        // change size
1241
1242        void * naddr = memalignNoStats( nalign, size );         // create new aligned area
1243        free( oaddr );
1244        return naddr;
1245} // resize
1246
1247
1248void * realloc( void * oaddr, size_t nalign, size_t size ) {
1249        if ( unlikely( nalign == 0 ) ) nalign = libAlign();     // reset alignment to minimum
1250        #ifdef __CFA_DEBUG__
1251        else
1252                checkAlign( nalign );                                                   // check alignment
1253        #endif // __CFA_DEBUG__
1254
1255        HeapManager.Storage.Header * header;
1256        HeapManager.FreeHeader * freeElem;
1257        size_t bsize, oalign = 0;
1258        headers( "realloc", oaddr, header, freeElem, bsize, oalign );
1259
1260        if ( oalign <= nalign && (uintptr_t)oaddr % nalign == 0 ) { // <= alignment and new alignment happens to match
1261                if ( oalign >= libAlign() ) {                                   // fake header ?
1262                        headerAddr( oaddr )->kind.fake.alignment = nalign | 1; // update alignment (could be the same)
1263                } // if
1264                return realloc( oaddr, size );
1265        } // if
1266
1267        // change size and copy old content to new storage
1268
1269        #ifdef __STATISTICS__
1270        __atomic_add_fetch( &realloc_calls, 1, __ATOMIC_SEQ_CST );
1271        __atomic_add_fetch( &realloc_storage, size, __ATOMIC_SEQ_CST );
1272        #endif // __STATISTICS__
1273
1274        size_t osize = header->kind.real.size;                  // old allocation size
1275        bool ozfill = (header->kind.real.blockSize & 2) != 0; // old allocation zero filled
1276
1277        // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
1278  if ( unlikely( size == 0 ) ) { free( oaddr ); return 0p; } // special cases
1279  if ( unlikely( oaddr == 0p ) ) return memalignNoStats( nalign, size );
1280
1281        void * naddr;
1282        if ( unlikely( header->kind.real.blockSize & 2 ) ) { // previous request zero fill
1283                naddr = cmemalignNoStats( nalign, 1, size );    // create new aligned area
1284        } else {
1285                naddr = memalignNoStats( nalign, size );                // create new aligned area
1286        } // if
1287
1288        headers( "realloc", naddr, header, freeElem, bsize, oalign );
1289        memcpy( naddr, oaddr, MIN( osize, size ) );                     // copy bytes
1290        free( oaddr );
1291
1292        if ( unlikely( ozfill ) ) {                                                     // previous request zero fill ?
1293                header->kind.real.blockSize |= 2;                               // mark new request as zero filled
1294                if ( size > osize ) {                                                   // previous request larger ?
1295                        memset( (char *)naddr + osize, (int)'\0', size - osize ); // initialize added storage
1296                } // if
1297        } // if
1298        return naddr;
1299} // realloc
1300
1301
1302// Local Variables: //
1303// tab-width: 4 //
1304// compile-command: "cfa -nodebug -O2 heap.cfa" //
1305// End: //
Note: See TracBrowser for help on using the repository browser.