source: libcfa/src/heap.cfa @ e50d9cb8

ADTast-experimental
Last change on this file since e50d9cb8 was 0bdfcc3, checked in by Peter A. Buhr <pabuhr@…>, 19 months ago

formatting

  • Property mode set to 100644
File size: 66.9 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2017 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// heap.cfa --
8//
9// Author           : Peter A. Buhr
10// Created On       : Tue Dec 19 21:58:35 2017
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Sun Oct 30 20:56:20 2022
13// Update Count     : 1584
14//
15
16#include <stdio.h>
17#include <string.h>                                                                             // memset, memcpy
18#include <limits.h>                                                                             // ULONG_MAX
19#include <stdlib.h>                                                                             // EXIT_FAILURE
20#include <errno.h>                                                                              // errno, ENOMEM, EINVAL
21#include <unistd.h>                                                                             // STDERR_FILENO, sbrk, sysconf
22#include <malloc.h>                                                                             // memalign, malloc_usable_size
23#include <sys/mman.h>                                                                   // mmap, munmap
24extern "C" {
25#include <sys/sysinfo.h>                                                                // get_nprocs
26} // extern "C"
27
28#include "bits/align.hfa"                                                               // libAlign
29#include "bits/defs.hfa"                                                                // likely, unlikely
30#include "concurrency/kernel/fwd.hfa"                                   // __POLL_PREEMPTION
31#include "startup.hfa"                                                                  // STARTUP_PRIORITY_MEMORY
32#include "math.hfa"                                                                             // ceiling, min
33#include "bitmanip.hfa"                                                                 // is_pow2, ceiling2
34
35// supported mallopt options
36#ifndef M_MMAP_THRESHOLD
37#define M_MMAP_THRESHOLD (-1)
38#endif // M_MMAP_THRESHOLD
39
40#ifndef M_TOP_PAD
41#define M_TOP_PAD (-2)
42#endif // M_TOP_PAD
43
44#define FASTLOOKUP                                                                              // use O(1) table lookup from allocation size to bucket size
45#define OWNERSHIP                                                                               // return freed memory to owner thread
46#define RETURNSPIN                                                                              // toggle spinlock / lockfree queue
47#if ! defined( OWNERSHIP ) && defined( RETURNSPIN )
48#warning "RETURNSPIN is ignored without OWNERSHIP; suggest commenting out RETURNSPIN"
49#endif // ! OWNERSHIP && RETURNSPIN
50
51#define CACHE_ALIGN 64
52#define CALIGN __attribute__(( aligned(CACHE_ALIGN) ))
53
54#define TLSMODEL __attribute__(( tls_model("initial-exec") ))
55
56//#define __STATISTICS__
57
58enum {
59        // The default extension heap amount in units of bytes. When the current heap reaches the brk address, the brk
60        // address is extended by the extension amount.
61        __CFA_DEFAULT_HEAP_EXPANSION__ = 10 * 1024 * 1024,
62
63        // The mmap crossover point during allocation. Allocations less than this amount are allocated from buckets; values
64        // greater than or equal to this value are mmap from the operating system.
65        __CFA_DEFAULT_MMAP_START__ = 512 * 1024 + 1,
66
67        // The default unfreed storage amount in units of bytes. When the uC++ program ends it subtracts this amount from
68        // the malloc/free counter to adjust for storage the program does not free.
69        __CFA_DEFAULT_HEAP_UNFREED__ = 0
70}; // enum
71
72
73//####################### Heap Trace/Print ####################
74
75
76static bool traceHeap = false;
77
78inline bool traceHeap() libcfa_public { return traceHeap; }
79
80bool traceHeapOn() libcfa_public {
81        bool temp = traceHeap;
82        traceHeap = true;
83        return temp;
84} // traceHeapOn
85
86bool traceHeapOff() libcfa_public {
87        bool temp = traceHeap;
88        traceHeap = false;
89        return temp;
90} // traceHeapOff
91
92bool traceHeapTerm() libcfa_public { return false; }
93
94
95static bool prtFree = false;
96
97bool prtFree() {
98        return prtFree;
99} // prtFree
100
101bool prtFreeOn() {
102        bool temp = prtFree;
103        prtFree = true;
104        return temp;
105} // prtFreeOn
106
107bool prtFreeOff() {
108        bool temp = prtFree;
109        prtFree = false;
110        return temp;
111} // prtFreeOff
112
113
114//######################### Helpers #########################
115
116
117// generic Bsearchl does not inline, so substitute with hand-coded binary-search.
118inline __attribute__((always_inline))
119static size_t Bsearchl( unsigned int key, const unsigned int vals[], size_t dim ) {
120        size_t l = 0, m, h = dim;
121        while ( l < h ) {
122                m = (l + h) / 2;
123                if ( (unsigned int &)(vals[m]) < key ) {                // cast away const
124                        l = m + 1;
125                } else {
126                        h = m;
127                } // if
128        } // while
129        return l;
130} // Bsearchl
131
132
133// pause to prevent excess processor bus usage
134#if defined( __i386 ) || defined( __x86_64 )
135        #define Pause() __asm__ __volatile__ ( "pause" : : : )
136#elif defined(__ARM_ARCH)
137        #define Pause() __asm__ __volatile__ ( "YIELD" : : : )
138#else
139        #error unsupported architecture
140#endif
141
142typedef volatile uintptr_t SpinLock_t CALIGN;                   // aligned addressable word-size
143
144static inline __attribute__((always_inline)) void lock( volatile SpinLock_t & slock ) {
145        enum { SPIN_START = 4, SPIN_END = 64 * 1024, };
146        unsigned int spin = SPIN_START;
147
148        for ( unsigned int i = 1;; i += 1 ) {
149          if ( slock == 0 && __atomic_test_and_set( &slock, __ATOMIC_SEQ_CST ) == 0 ) break; // Fence
150                for ( volatile unsigned int s = 0; s < spin; s += 1 ) Pause(); // exponential spin
151                spin += spin;                                                                   // powers of 2
152                //if ( i % 64 == 0 ) spin += spin;                              // slowly increase by powers of 2
153                if ( spin > SPIN_END ) spin = SPIN_END;                 // cap spinning
154        } // for
155} // spin_lock
156
157static inline __attribute__((always_inline)) void unlock( volatile SpinLock_t & slock ) {
158        __atomic_clear( &slock, __ATOMIC_SEQ_CST );                     // Fence
159} // spin_unlock
160
161
162//####################### Heap Statistics ####################
163
164
165#ifdef __STATISTICS__
166enum { CntTriples = 12 };                                                               // number of counter triples
167enum { MALLOC, AALLOC, CALLOC, MEMALIGN, AMEMALIGN, CMEMALIGN, RESIZE, REALLOC, FREE };
168
169struct StatsOverlay {                                                                   // overlay for iteration
170        unsigned int calls, calls_0;
171        unsigned long long int request, alloc;
172};
173
174// Heap statistics counters.
175union HeapStatistics {
176        struct {                                                                                        // minimum qualification
177                unsigned int malloc_calls, malloc_0_calls;
178                unsigned long long int malloc_storage_request, malloc_storage_alloc;
179                unsigned int aalloc_calls, aalloc_0_calls;
180                unsigned long long int aalloc_storage_request, aalloc_storage_alloc;
181                unsigned int calloc_calls, calloc_0_calls;
182                unsigned long long int calloc_storage_request, calloc_storage_alloc;
183                unsigned int memalign_calls, memalign_0_calls;
184                unsigned long long int memalign_storage_request, memalign_storage_alloc;
185                unsigned int amemalign_calls, amemalign_0_calls;
186                unsigned long long int amemalign_storage_request, amemalign_storage_alloc;
187                unsigned int cmemalign_calls, cmemalign_0_calls;
188                unsigned long long int cmemalign_storage_request, cmemalign_storage_alloc;
189                unsigned int resize_calls, resize_0_calls;
190                unsigned long long int resize_storage_request, resize_storage_alloc;
191                unsigned int realloc_calls, realloc_0_calls;
192                unsigned long long int realloc_storage_request, realloc_storage_alloc;
193                unsigned int free_calls, free_null_calls;
194                unsigned long long int free_storage_request, free_storage_alloc;
195                unsigned int return_pulls, return_pushes;
196                unsigned long long int return_storage_request, return_storage_alloc;
197                unsigned int mmap_calls, mmap_0_calls;                  // no zero calls
198                unsigned long long int mmap_storage_request, mmap_storage_alloc;
199                unsigned int munmap_calls, munmap_0_calls;              // no zero calls
200                unsigned long long int munmap_storage_request, munmap_storage_alloc;
201        };
202        struct StatsOverlay counters[CntTriples];                       // overlay for iteration
203}; // HeapStatistics
204
205static_assert( sizeof(HeapStatistics) == CntTriples * sizeof(StatsOverlay),
206                           "Heap statistics counter-triplets does not match with array size" );
207
208static void HeapStatisticsCtor( HeapStatistics & stats ) {
209        memset( &stats, '\0', sizeof(stats) );                          // very fast
210        // for ( unsigned int i = 0; i < CntTriples; i += 1 ) {
211        //      stats.counters[i].calls = stats.counters[i].calls_0 = stats.counters[i].request = stats.counters[i].alloc = 0;
212        // } // for
213} // HeapStatisticsCtor
214
215static HeapStatistics & ?+=?( HeapStatistics & lhs, const HeapStatistics & rhs ) {
216        for ( unsigned int i = 0; i < CntTriples; i += 1 ) {
217                lhs.counters[i].calls += rhs.counters[i].calls;
218                lhs.counters[i].calls_0 += rhs.counters[i].calls_0;
219                lhs.counters[i].request += rhs.counters[i].request;
220                lhs.counters[i].alloc += rhs.counters[i].alloc;
221        } // for
222        return lhs;
223} // ?+=?
224#endif // __STATISTICS__
225
226
227// Recursive definitions: HeapManager needs size of bucket array and bucket area needs sizeof HeapManager storage.
228// Break recursion by hardcoding number of buckets and statically checking number is correct after bucket array defined.
229enum { NoBucketSizes = 91 };                                                    // number of buckets sizes
230
231struct Heap {
232        struct Storage {
233                struct Header {                                                                 // header
234                        union Kind {
235                                struct RealHeader {
236                                        union {
237                                                struct {                                                // 4-byte word => 8-byte header, 8-byte word => 16-byte header
238                                                        union {
239                                                                // 2nd low-order bit => zero filled, 3rd low-order bit => mmapped
240                                                                // FreeHeader * home;           // allocated block points back to home locations (must overlay alignment)
241                                                                void * home;                    // allocated block points back to home locations (must overlay alignment)
242                                                                size_t blockSize;               // size for munmap (must overlay alignment)
243                                                                Storage * next;                 // freed block points to next freed block of same size
244                                                        };
245                                                        size_t size;                            // allocation size in bytes
246                                                };
247                                        };
248                                } real; // RealHeader
249
250                                struct FakeHeader {
251                                        uintptr_t alignment;                            // 1st low-order bit => fake header & alignment
252                                        uintptr_t offset;
253                                } fake; // FakeHeader
254                        } kind; // Kind
255                } header; // Header
256
257                char pad[libAlign() - sizeof( Header )];
258                char data[0];                                                                   // storage
259        }; // Storage
260
261        static_assert( libAlign() >= sizeof( Storage ), "minimum alignment < sizeof( Storage )" );
262
263        struct __attribute__(( aligned (8) )) FreeHeader {
264                size_t blockSize __attribute__(( aligned(8) )); // size of allocations on this list
265                #ifdef OWNERSHIP
266                #ifdef RETURNSPIN
267                SpinLock_t returnLock;
268                #endif // RETURNSPIN
269                Storage * returnList;                                                   // other thread return list
270                #endif // OWNERSHIP
271
272                Storage * freeList;                                                             // thread free list
273                Heap * homeManager;                                                             // heap owner (free storage to bucket, from bucket to heap)
274        }; // FreeHeader
275
276        FreeHeader freeLists[NoBucketSizes];                            // buckets for different allocation sizes
277        void * heapBuffer;                                                                      // start of free storage in buffer
278        size_t heapReserve;                                                                     // amount of remaining free storage in buffer
279
280        #if defined( __STATISTICS__ ) || defined( __CFA_DEBUG__ )
281        Heap * nextHeapManager;                                                         // intrusive link of existing heaps; traversed to collect statistics or check unfreed storage
282        #endif // __STATISTICS__ || __CFA_DEBUG__
283        Heap * nextFreeHeapManager;                                                     // intrusive link of free heaps from terminated threads; reused by new threads
284
285        #ifdef __CFA_DEBUG__
286        int64_t allocUnfreed;                                                           // running total of allocations minus frees; can be negative
287        #endif // __CFA_DEBUG__
288
289        #ifdef __STATISTICS__
290        HeapStatistics stats;                                                           // local statistic table for this heap
291        #endif // __STATISTICS__
292}; // Heap
293
294
295struct HeapMaster {
296        SpinLock_t extLock;                                                                     // protects allocation-buffer extension
297        SpinLock_t mgrLock;                                                                     // protects freeHeapManagersList, heapManagersList, heapManagersStorage, heapManagersStorageEnd
298
299        void * heapBegin;                                                                       // start of heap
300        void * heapEnd;                                                                         // logical end of heap
301        size_t heapRemaining;                                                           // amount of storage not allocated in the current chunk
302        size_t pageSize;                                                                        // architecture pagesize
303        size_t heapExpand;                                                                      // sbrk advance
304        size_t mmapStart;                                                                       // cross over point for mmap
305        unsigned int maxBucketsUsed;                                            // maximum number of buckets in use
306
307        Heap * heapManagersList;                                                        // heap-list head
308        Heap * freeHeapManagersList;                                            // free-list head
309
310        // Heap superblocks are not linked; heaps in superblocks are linked via intrusive links.
311        Heap * heapManagersStorage;                                                     // next heap to use in heap superblock
312        Heap * heapManagersStorageEnd;                                          // logical heap outside of superblock's end
313
314        #ifdef __STATISTICS__
315        HeapStatistics stats;                                                           // global stats for thread-local heaps to add there counters when exiting
316        unsigned long int threads_started, threads_exited;      // counts threads that have started and exited
317        unsigned long int reused_heap, new_heap;                        // counts reusability of heaps
318        unsigned int sbrk_calls;
319        unsigned long long int sbrk_storage;
320        int stats_fd;
321        #endif // __STATISTICS__
322}; // HeapMaster
323
324
325#ifdef FASTLOOKUP
326enum { LookupSizes = 65_536 + sizeof(Heap.Storage) };   // number of fast lookup sizes
327static unsigned char lookup[LookupSizes];                               // O(1) lookup for small sizes
328#endif // FASTLOOKUP
329
330static volatile bool heapMasterBootFlag = false;                // trigger for first heap
331static HeapMaster heapMaster @= {};                                             // program global
332
333static void heapMasterCtor();
334static void heapMasterDtor();
335static Heap * getHeap();
336
337
338// Size of array must harmonize with NoBucketSizes and individual bucket sizes must be multiple of 16.
339// Smaller multiples of 16 and powers of 2 are common allocation sizes, so make them generate the minimum required bucket size.
340// malloc(0) returns 0p, so no bucket is necessary for 0 bytes returning an address that can be freed.
341static const unsigned int bucketSizes[] @= {                    // different bucket sizes
342        16 + sizeof(Heap.Storage), 32 + sizeof(Heap.Storage), 48 + sizeof(Heap.Storage), 64 + sizeof(Heap.Storage), // 4
343        96 + sizeof(Heap.Storage), 112 + sizeof(Heap.Storage), 128 + sizeof(Heap.Storage), // 3
344        160, 192, 224, 256 + sizeof(Heap.Storage), // 4
345        320, 384, 448, 512 + sizeof(Heap.Storage), // 4
346        640, 768, 896, 1_024 + sizeof(Heap.Storage), // 4
347        1_536, 2_048 + sizeof(Heap.Storage), // 2
348        2_560, 3_072, 3_584, 4_096 + sizeof(Heap.Storage), // 4
349        6_144, 8_192 + sizeof(Heap.Storage), // 2
350        9_216, 10_240, 11_264, 12_288, 13_312, 14_336, 15_360, 16_384 + sizeof(Heap.Storage), // 8
351        18_432, 20_480, 22_528, 24_576, 26_624, 28_672, 30_720, 32_768 + sizeof(Heap.Storage), // 8
352        36_864, 40_960, 45_056, 49_152, 53_248, 57_344, 61_440, 65_536 + sizeof(Heap.Storage), // 8
353        73_728, 81_920, 90_112, 98_304, 106_496, 114_688, 122_880, 131_072 + sizeof(Heap.Storage), // 8
354        147_456, 163_840, 180_224, 196_608, 212_992, 229_376, 245_760, 262_144 + sizeof(Heap.Storage), // 8
355        294_912, 327_680, 360_448, 393_216, 425_984, 458_752, 491_520, 524_288 + sizeof(Heap.Storage), // 8
356        655_360, 786_432, 917_504, 1_048_576 + sizeof(Heap.Storage), // 4
357        1_179_648, 1_310_720, 1_441_792, 1_572_864, 1_703_936, 1_835_008, 1_966_080, 2_097_152 + sizeof(Heap.Storage), // 8
358        2_621_440, 3_145_728, 3_670_016, 4_194_304 + sizeof(Heap.Storage), // 4
359};
360
361static_assert( NoBucketSizes == sizeof(bucketSizes) / sizeof(bucketSizes[0] ), "size of bucket array wrong" );
362
363
364// extern visibility, used by runtime kernel
365libcfa_public size_t __page_size;                                               // architecture pagesize
366libcfa_public int __map_prot;                                                   // common mmap/mprotect protection
367
368
369// Thread-local storage is allocated lazily when the storage is accessed.
370static __thread size_t PAD1 CALIGN TLSMODEL __attribute__(( unused )); // protect false sharing
371static __thread Heap * volatile heapManager CALIGN TLSMODEL;
372static __thread size_t PAD2 CALIGN TLSMODEL __attribute__(( unused )); // protect further false sharing
373
374
375// declare helper functions for HeapMaster
376void noMemory();                                                                                // forward, called by "builtin_new" when malloc returns 0
377
378
379void heapMasterCtor() with( heapMaster ) {
380        // Singleton pattern to initialize heap master
381
382        verify( bucketSizes[0] == (16 + sizeof(Heap.Storage)) );
383
384        __page_size = sysconf( _SC_PAGESIZE );
385        __map_prot = PROT_READ | PROT_WRITE | PROT_EXEC;
386
387        extLock = 0;
388        mgrLock = 0;
389
390        char * end = (char *)sbrk( 0 );
391        heapBegin = heapEnd = sbrk( (char *)ceiling2( (long unsigned int)end, libAlign() ) - end ); // move start of heap to multiple of alignment
392        heapRemaining = 0;
393        heapExpand = malloc_expansion();
394        mmapStart = malloc_mmap_start();
395
396        // find the closest bucket size less than or equal to the mmapStart size
397        maxBucketsUsed = Bsearchl( mmapStart, bucketSizes, NoBucketSizes ); // binary search
398
399        verify( (mmapStart >= pageSize) && (bucketSizes[NoBucketSizes - 1] >= mmapStart) );
400        verify( maxBucketsUsed < NoBucketSizes );                       // subscript failure ?
401        verify( mmapStart <= bucketSizes[maxBucketsUsed] ); // search failure ?
402
403        heapManagersList = 0p;
404        freeHeapManagersList = 0p;
405
406        heapManagersStorage = 0p;
407        heapManagersStorageEnd = 0p;
408
409        #ifdef __STATISTICS__
410        HeapStatisticsCtor( stats );                                            // clear statistic counters
411        threads_started = threads_exited = 0;
412        reused_heap = new_heap = 0;
413        sbrk_calls = sbrk_storage = 0;
414        stats_fd = STDERR_FILENO;
415        #endif // __STATISTICS__
416
417        #ifdef FASTLOOKUP
418        for ( unsigned int i = 0, idx = 0; i < LookupSizes; i += 1 ) {
419                if ( i > bucketSizes[idx] ) idx += 1;
420                lookup[i] = idx;
421                verify( i <= bucketSizes[idx] );
422                verify( (i <= 32 && idx == 0) || (i > bucketSizes[idx - 1]) );
423        } // for
424        #endif // FASTLOOKUP
425
426        heapMasterBootFlag = true;
427} // heapMasterCtor
428
429
430#define NO_MEMORY_MSG "**** Error **** insufficient heap memory available to allocate %zd new bytes."
431
432Heap * getHeap() with( heapMaster ) {
433        Heap * heap;
434        if ( freeHeapManagersList ) {                                           // free heap for reused ?
435                heap = freeHeapManagersList;
436                freeHeapManagersList = heap->nextFreeHeapManager;
437
438                #ifdef __STATISTICS__
439                reused_heap += 1;
440                #endif // __STATISTICS__
441        } else {                                                                                        // free heap not found, create new
442                // Heap size is about 12K, FreeHeader (128 bytes because of cache alignment) * NoBucketSizes (91) => 128 heaps *
443                // 12K ~= 120K byte superblock.  Where 128-heap superblock handles a medium sized multi-processor server.
444                size_t remaining = heapManagersStorageEnd - heapManagersStorage; // remaining free heaps in superblock
445                if ( ! heapManagersStorage || remaining != 0 ) {
446                        // Each block of heaps is a multiple of the number of cores on the computer.
447                        int HeapDim = get_nprocs();                                     // get_nprocs_conf does not work
448                        size_t size = HeapDim * sizeof( Heap );
449
450                        heapManagersStorage = (Heap *)mmap( 0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 );
451                        if ( unlikely( heapManagersStorage == (Heap *)MAP_FAILED ) ) { // failed ?
452                                if ( errno == ENOMEM ) abort( NO_MEMORY_MSG, size ); // no memory
453                                // Do not call strerror( errno ) as it may call malloc.
454                                abort( "**** Error **** attempt to allocate block of heaps of size %zu bytes and mmap failed with errno %d.", size, errno );
455                        } // if
456                        heapManagersStorageEnd = &heapManagersStorage[HeapDim]; // outside array
457                } // if
458
459                heap = heapManagersStorage;
460                heapManagersStorage = heapManagersStorage + 1; // bump next heap
461
462                #if defined( __STATISTICS__ ) || defined( __CFA_DEBUG__ )
463                heap->nextHeapManager = heapManagersList;
464                #endif // __STATISTICS__ || __CFA_DEBUG__
465                heapManagersList = heap;
466
467                #ifdef __STATISTICS__
468                new_heap += 1;
469                #endif // __STATISTICS__
470
471                with( *heap ) {
472                        for ( unsigned int j = 0; j < NoBucketSizes; j += 1 ) { // initialize free lists
473                                #ifdef OWNERSHIP
474                                #ifdef RETURNSPIN
475                                freeLists[j].returnLock = 0;
476                                freeLists[j].returnList = 0p;
477                                #endif // RETURNSPIN
478                                #endif // OWNERSHIP
479
480                                freeLists[j].freeList = 0p;
481                                freeLists[j].homeManager = heap;
482                                freeLists[j].blockSize = bucketSizes[j];
483                        } // for
484
485                        heapBuffer = 0p;
486                        heapReserve = 0;
487                        nextFreeHeapManager = 0p;
488                        #ifdef __CFA_DEBUG__
489                        allocUnfreed = 0;
490                        #endif // __CFA_DEBUG__
491                } // with
492        } // if
493
494        return heap;
495} // getHeap
496
497
498void heapManagerCtor() libcfa_public {
499        if ( unlikely( ! heapMasterBootFlag ) ) heapMasterCtor();
500
501        lock( heapMaster.mgrLock );                                                     // protect heapMaster counters
502
503        // get storage for heap manager
504
505        heapManager = getHeap();
506
507        #ifdef __STATISTICS__
508        HeapStatisticsCtor( heapManager->stats );                       // heap local
509        heapMaster.threads_started += 1;
510        #endif // __STATISTICS__
511
512        unlock( heapMaster.mgrLock );
513} // heapManagerCtor
514
515
516void heapManagerDtor() libcfa_public {
517        lock( heapMaster.mgrLock );
518
519        // place heap on list of free heaps for reusability
520        heapManager->nextFreeHeapManager = heapMaster.freeHeapManagersList;
521        heapMaster.freeHeapManagersList = heapManager;
522
523        #ifdef __STATISTICS__
524        heapMaster.threads_exited += 1;
525        #endif // __STATISTICS__
526
527        // Do not set heapManager to NULL because it is used after Cforall is shutdown but before the program shuts down.
528
529        unlock( heapMaster.mgrLock );
530} // heapManagerDtor
531
532
533//####################### Memory Allocation Routines Helpers ####################
534
535
536extern int cfa_main_returned;                                                   // from interpose.cfa
537extern "C" {
538        void memory_startup( void ) {
539                if ( ! heapMasterBootFlag ) heapManagerCtor();  // sanity check
540        } // memory_startup
541
542        void memory_shutdown( void ) {
543                heapManagerDtor();
544        } // memory_shutdown
545
546        void heapAppStart() {                                                           // called by __cfaabi_appready_startup
547                verify( heapManager );
548                #ifdef __CFA_DEBUG__
549                heapManager->allocUnfreed = 0;                                  // clear prior allocation counts
550                #endif // __CFA_DEBUG__
551
552                #ifdef __STATISTICS__
553                HeapStatisticsCtor( heapManager->stats );               // clear prior statistic counters
554                #endif // __STATISTICS__
555        } // heapAppStart
556
557        void heapAppStop() {                                                            // called by __cfaabi_appready_startdown
558                fclose( stdin ); fclose( stdout );                              // free buffer storage
559          if ( ! cfa_main_returned ) return;                            // do not check unfreed storage if exit called
560
561                #ifdef __CFA_DEBUG__
562                // allocUnfreed is set to 0 when a heap is created and it accumulates any unfreed storage during its multiple thread
563                // usages.  At the end, add up each heap allocUnfreed value across all heaps to get the total unfreed storage.
564                int64_t allocUnfreed = 0;
565                for ( Heap * heap = heapMaster.heapManagersList; heap; heap = heap->nextHeapManager ) {
566                        allocUnfreed += heap->allocUnfreed;
567                } // for
568
569                allocUnfreed -= malloc_unfreed();                               // subtract any user specified unfreed storage
570                if ( allocUnfreed > 0 ) {
571                        // DO NOT USE STREAMS AS THEY MAY BE UNAVAILABLE AT THIS POINT.
572                        char helpText[512];
573                        __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText),
574                                                                                "CFA warning (UNIX pid:%ld) : program terminating with %ju(0x%jx) bytes of storage allocated but not freed.\n"
575                                                                                "Possible cause is unfreed storage allocated by the program or system/library routines called from the program.\n",
576                                                                                (long int)getpid(), allocUnfreed, allocUnfreed ); // always print the UNIX pid
577                } // if
578                #endif // __CFA_DEBUG__
579        } // heapAppStop
580} // extern "C"
581
582
583#ifdef __STATISTICS__
584static HeapStatistics stats;                                                    // zero filled
585
586#define prtFmt \
587        "\nHeap statistics: (storage request / allocation)\n" \
588        "  malloc    >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
589        "  aalloc    >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
590        "  calloc    >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
591        "  memalign  >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
592        "  amemalign >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
593        "  cmemalign >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
594        "  resize    >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
595        "  realloc   >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
596        "  free      !null calls %'u; null calls %'u; storage %'llu / %'llu bytes\n" \
597        "  return    pulls %'u; pushes %'u; storage %'llu / %'llu bytes\n" \
598        "  sbrk      calls %'u; storage %'llu bytes\n" \
599        "  mmap      calls %'u; storage %'llu / %'llu bytes\n" \
600        "  munmap    calls %'u; storage %'llu / %'llu bytes\n" \
601        "  threads   started %'lu; exited %'lu\n" \
602        "  heaps     new %'lu; reused %'lu\n"
603
604// Use "write" because streams may be shutdown when calls are made.
605static int printStats( HeapStatistics & stats ) with( heapMaster, stats ) {     // see malloc_stats
606        char helpText[sizeof(prtFmt) + 1024];                           // space for message and values
607        return __cfaabi_bits_print_buffer( stats_fd, helpText, sizeof(helpText), prtFmt,
608                        malloc_calls, malloc_0_calls, malloc_storage_request, malloc_storage_alloc,
609                        aalloc_calls, aalloc_0_calls, aalloc_storage_request, aalloc_storage_alloc,
610                        calloc_calls, calloc_0_calls, calloc_storage_request, calloc_storage_alloc,
611                        memalign_calls, memalign_0_calls, memalign_storage_request, memalign_storage_alloc,
612                        amemalign_calls, amemalign_0_calls, amemalign_storage_request, amemalign_storage_alloc,
613                        cmemalign_calls, cmemalign_0_calls, cmemalign_storage_request, cmemalign_storage_alloc,
614                        resize_calls, resize_0_calls, resize_storage_request, resize_storage_alloc,
615                        realloc_calls, realloc_0_calls, realloc_storage_request, realloc_storage_alloc,
616                        free_calls, free_null_calls, free_storage_request, free_storage_alloc,
617                        return_pulls, return_pushes, return_storage_request, return_storage_alloc,
618                        sbrk_calls, sbrk_storage,
619                        mmap_calls, mmap_storage_request, mmap_storage_alloc,
620                        munmap_calls, munmap_storage_request, munmap_storage_alloc,
621                        threads_started, threads_exited,
622                        new_heap, reused_heap
623                );
624} // printStats
625
626#define prtFmtXML \
627        "<malloc version=\"1\">\n" \
628        "<heap nr=\"0\">\n" \
629        "<sizes>\n" \
630        "</sizes>\n" \
631        "<total type=\"malloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
632        "<total type=\"aalloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
633        "<total type=\"calloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
634        "<total type=\"memalign\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
635        "<total type=\"amemalign\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
636        "<total type=\"cmemalign\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
637        "<total type=\"resize\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
638        "<total type=\"realloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
639        "<total type=\"free\" !null=\"%'u;\" 0 null=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
640        "<total type=\"return\" pulls=\"%'u;\" 0 pushes=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
641        "<total type=\"sbrk\" count=\"%'u;\" size=\"%'llu\"/> bytes\n" \
642        "<total type=\"mmap\" count=\"%'u;\" size=\"%'llu / %'llu\" / > bytes\n" \
643        "<total type=\"munmap\" count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
644        "<total type=\"threads\" started=\"%'lu;\" exited=\"%'lu\"/>\n" \
645        "<total type=\"heaps\" new=\"%'lu;\" reused=\"%'lu\"/>\n" \
646        "</malloc>"
647
648static int printStatsXML( HeapStatistics & stats, FILE * stream ) with( heapMaster, stats ) { // see malloc_info
649        char helpText[sizeof(prtFmtXML) + 1024];                        // space for message and values
650        return __cfaabi_bits_print_buffer( fileno( stream ), helpText, sizeof(helpText), prtFmtXML,
651                        malloc_calls, malloc_0_calls, malloc_storage_request, malloc_storage_alloc,
652                        aalloc_calls, aalloc_0_calls, aalloc_storage_request, aalloc_storage_alloc,
653                        calloc_calls, calloc_0_calls, calloc_storage_request, calloc_storage_alloc,
654                        memalign_calls, memalign_0_calls, memalign_storage_request, memalign_storage_alloc,
655                        amemalign_calls, amemalign_0_calls, amemalign_storage_request, amemalign_storage_alloc,
656                        cmemalign_calls, cmemalign_0_calls, cmemalign_storage_request, cmemalign_storage_alloc,
657                        resize_calls, resize_0_calls, resize_storage_request, resize_storage_alloc,
658                        realloc_calls, realloc_0_calls, realloc_storage_request, realloc_storage_alloc,
659                        free_calls, free_null_calls, free_storage_request, free_storage_alloc,
660                        return_pulls, return_pushes, return_storage_request, return_storage_alloc,
661                        sbrk_calls, sbrk_storage,
662                        mmap_calls, mmap_storage_request, mmap_storage_alloc,
663                    munmap_calls, munmap_storage_request, munmap_storage_alloc,
664                        threads_started, threads_exited,
665                        new_heap, reused_heap
666                );
667} // printStatsXML
668
669static HeapStatistics & collectStats( HeapStatistics & stats ) with( heapMaster ) {
670        lock( mgrLock );
671
672        stats += heapMaster.stats;
673        for ( Heap * heap = heapManagersList; heap; heap = heap->nextHeapManager ) {
674                stats += heap->stats;
675        } // for
676
677        unlock( mgrLock );
678        return stats;
679} // collectStats
680#endif // __STATISTICS__
681
682
683static bool setMmapStart( size_t value ) with( heapMaster ) { // true => mmapped, false => sbrk
684  if ( value < __page_size || bucketSizes[NoBucketSizes - 1] < value ) return false;
685        mmapStart = value;                                                                      // set global
686
687        // find the closest bucket size less than or equal to the mmapStart size
688        maxBucketsUsed = Bsearchl( mmapStart, bucketSizes, NoBucketSizes ); // binary search
689
690        verify( maxBucketsUsed < NoBucketSizes );                       // subscript failure ?
691        verify( mmapStart <= bucketSizes[maxBucketsUsed] ); // search failure ?
692        return true;
693} // setMmapStart
694
695
696// <-------+----------------------------------------------------> bsize (bucket size)
697// |header |addr
698//==================================================================================
699//                   align/offset |
700// <-----------------<------------+-----------------------------> bsize (bucket size)
701//                   |fake-header | addr
702#define HeaderAddr( addr ) ((Heap.Storage.Header *)( (char *)addr - sizeof(Heap.Storage) ))
703#define RealHeader( header ) ((Heap.Storage.Header *)((char *)header - header->kind.fake.offset))
704
705// <-------<<--------------------- dsize ---------------------->> bsize (bucket size)
706// |header |addr
707//==================================================================================
708//                   align/offset |
709// <------------------------------<<---------- dsize --------->>> bsize (bucket size)
710//                   |fake-header |addr
711#define DataStorage( bsize, addr, header ) (bsize - ( (char *)addr - (char *)header ))
712
713
714inline __attribute__((always_inline))
715static void checkAlign( size_t alignment ) {
716        if ( unlikely( alignment < libAlign() || ! is_pow2( alignment ) ) ) {
717                abort( "**** Error **** alignment %zu for memory allocation is less than %d and/or not a power of 2.", alignment, libAlign() );
718        } // if
719} // checkAlign
720
721
722inline __attribute__((always_inline))
723static void checkHeader( bool check, const char name[], void * addr ) {
724        if ( unlikely( check ) ) {                                                      // bad address ?
725                abort( "**** Error **** attempt to %s storage %p with address outside the heap.\n"
726                           "Possible cause is duplicate free on same block or overwriting of memory.",
727                           name, addr );
728        } // if
729} // checkHeader
730
731
732// Manipulate sticky bits stored in unused 3 low-order bits of an address.
733//   bit0 => alignment => fake header
734//   bit1 => zero filled (calloc)
735//   bit2 => mapped allocation versus sbrk
736#define StickyBits( header ) (((header)->kind.real.blockSize & 0x7))
737#define ClearStickyBits( addr ) (typeof(addr))((uintptr_t)(addr) & ~7)
738#define MarkAlignmentBit( align ) ((align) | 1)
739#define AlignmentBit( header ) ((((header)->kind.fake.alignment) & 1))
740#define ClearAlignmentBit( header ) (((header)->kind.fake.alignment) & ~1)
741#define ZeroFillBit( header ) ((((header)->kind.real.blockSize) & 2))
742#define ClearZeroFillBit( header ) ((((header)->kind.real.blockSize) &= ~2))
743#define MarkZeroFilledBit( header ) ((header)->kind.real.blockSize |= 2)
744#define MmappedBit( header ) ((((header)->kind.real.blockSize) & 4))
745#define MarkMmappedBit( size ) ((size) | 4)
746
747
748inline __attribute__((always_inline))
749static void fakeHeader( Heap.Storage.Header *& header, size_t & alignment ) {
750        if ( unlikely( AlignmentBit( header ) ) ) {                     // fake header ?
751                alignment = ClearAlignmentBit( header );                // clear flag from value
752                #ifdef __CFA_DEBUG__
753                checkAlign( alignment );                                                // check alignment
754                #endif // __CFA_DEBUG__
755                header = RealHeader( header );                                  // backup from fake to real header
756        } else {
757                alignment = libAlign();                                                 // => no fake header
758        } // if
759} // fakeHeader
760
761
762inline __attribute__((always_inline))
763static bool headers( const char name[] __attribute__(( unused )), void * addr, Heap.Storage.Header *& header,
764                                                        Heap.FreeHeader *& freeHead, size_t & size, size_t & alignment ) with( heapMaster, *heapManager ) {
765        header = HeaderAddr( addr );
766
767        #ifdef __CFA_DEBUG__
768        checkHeader( header < (Heap.Storage.Header *)heapBegin, name, addr ); // bad low address ?
769        #endif // __CFA_DEBUG__
770
771        if ( likely( ! StickyBits( header ) ) ) {                       // no sticky bits ?
772                freeHead = (Heap.FreeHeader *)(header->kind.real.home);
773                alignment = libAlign();
774        } else {
775                fakeHeader( header, alignment );
776                if ( unlikely( MmappedBit( header ) ) ) {               // mmapped ?
777                        verify( addr < heapBegin || heapEnd < addr );
778                        size = ClearStickyBits( header->kind.real.blockSize ); // mmap size
779                        return true;
780                } // if
781
782                freeHead = (Heap.FreeHeader *)(ClearStickyBits( header->kind.real.home ));
783        } // if
784        size = freeHead->blockSize;
785
786        #ifdef __CFA_DEBUG__
787        checkHeader( header < (Heap.Storage.Header *)heapBegin || (Heap.Storage.Header *)heapEnd < header, name, addr ); // bad address ? (offset could be + or -)
788
789        Heap * homeManager;
790        if ( unlikely( freeHead == 0p || // freed and only free-list node => null link
791                                   // freed and link points at another free block not to a bucket in the bucket array.
792                                   (homeManager = freeHead->homeManager, freeHead < &homeManager->freeLists[0] ||
793                                        &homeManager->freeLists[NoBucketSizes] <= freeHead ) ) ) {
794                abort( "**** Error **** attempt to %s storage %p with corrupted header.\n"
795                           "Possible cause is duplicate free on same block or overwriting of header information.",
796                           name, addr );
797        } // if
798        #endif // __CFA_DEBUG__
799
800        return false;
801} // headers
802
803
804static void * master_extend( size_t size ) with( heapMaster ) {
805        lock( extLock );
806
807        ptrdiff_t rem = heapRemaining - size;
808        if ( unlikely( rem < 0 ) ) {
809                // If the size requested is bigger than the current remaining storage, increase the size of the heap.
810
811                size_t increase = ceiling2( size > heapExpand ? size : heapExpand, libAlign() );
812                if ( unlikely( sbrk( increase ) == (void *)-1 ) ) {     // failed, no memory ?
813                        unlock( extLock );
814                        abort( NO_MEMORY_MSG, size );                           // give up
815                } // if
816
817                // Make storage executable for thunks.
818                if ( mprotect( (char *)heapEnd + heapRemaining, increase, __map_prot ) ) {
819                        unlock( extLock );
820                        abort( "**** Error **** attempt to make heap storage executable for thunks and mprotect failed with errno %d.", errno );
821                } // if
822
823                rem = heapRemaining + increase - size;
824
825                #ifdef __STATISTICS__
826                sbrk_calls += 1;
827                sbrk_storage += increase;
828                #endif // __STATISTICS__
829        } // if
830
831        Heap.Storage * block = (Heap.Storage *)heapEnd;
832        heapRemaining = rem;
833        heapEnd = (char *)heapEnd + size;
834
835        unlock( extLock );
836        return block;
837} // master_extend
838
839
840__attribute__(( noinline ))
841static void * manager_extend( size_t size ) with( *heapManager ) {
842        ptrdiff_t rem = heapReserve - size;
843
844        if ( unlikely( rem < 0 ) ) {                                            // negative
845                // If the size requested is bigger than the current remaining reserve, use the current reserve to populate
846                // smaller freeLists, and increase the reserve.
847
848                rem = heapReserve;                                                              // positive
849
850                if ( rem >= bucketSizes[0] ) {                                  // minimal size ? otherwise ignore
851                        size_t bucket;
852                        #ifdef FASTLOOKUP
853                        if ( likely( rem < LookupSizes ) ) bucket = lookup[rem];
854                        #endif // FASTLOOKUP
855                                bucket = Bsearchl( rem, bucketSizes, heapMaster.maxBucketsUsed );
856                        verify( 0 <= bucket && bucket <= heapMaster.maxBucketsUsed );
857                        Heap.FreeHeader * freeHead = &(freeLists[bucket]);
858
859                        // The remaining storage many not be bucket size, whereas all other allocations are. Round down to previous
860                        // bucket size in this case.
861                        if ( unlikely( freeHead->blockSize > (size_t)rem ) ) freeHead -= 1;
862                        Heap.Storage * block = (Heap.Storage *)heapBuffer;
863
864                        block->header.kind.real.next = freeHead->freeList; // push on stack
865                        freeHead->freeList = block;
866                } // if
867
868                size_t increase = ceiling( size > ( heapMaster.heapExpand / 10 ) ? size : ( heapMaster.heapExpand / 10 ), libAlign() );
869                heapBuffer = master_extend( increase );
870                rem = increase - size;
871        } // if
872
873        Heap.Storage * block = (Heap.Storage *)heapBuffer;
874        heapReserve = rem;
875        heapBuffer = (char *)heapBuffer + size;
876
877        return block;
878} // manager_extend
879
880
881#define BOOT_HEAP_MANAGER \
882        if ( unlikely( ! heapMasterBootFlag ) ) { \
883                heapManagerCtor(); /* trigger for first heap */ \
884        } /* if */
885
886#ifdef __STATISTICS__
887#define STAT_NAME __counter
888#define STAT_PARM , unsigned int STAT_NAME
889#define STAT_ARG( name ) , name
890#define STAT_0_CNT( counter ) stats.counters[counter].calls_0 += 1
891#else
892#define STAT_NAME
893#define STAT_PARM
894#define STAT_ARG( name )
895#define STAT_0_CNT( counter )
896#endif // __STATISTICS__
897
898#define PROLOG( counter, ... ) \
899        BOOT_HEAP_MANAGER; \
900        if ( unlikely( size == 0 ) ||                                           /* 0 BYTE ALLOCATION RETURNS NULL POINTER */ \
901                unlikely( size > ULONG_MAX - sizeof(Heap.Storage) ) ) { /* error check */ \
902                STAT_0_CNT( counter ); \
903                __VA_ARGS__; \
904                return 0p; \
905        } /* if */
906
907
908#define SCRUB_SIZE 1024lu
909// Do not use '\xfe' for scrubbing because dereferencing an address composed of it causes a SIGSEGV *without* a valid IP
910// pointer in the interrupt frame.
911#define SCRUB '\xff'
912
913static void * doMalloc( size_t size STAT_PARM ) libcfa_nopreempt with( *heapManager ) {
914        PROLOG( STAT_NAME );
915
916        verify( heapManager );
917        Heap.Storage * block;                                                           // pointer to new block of storage
918
919        // Look up size in the size list.  Make sure the user request includes space for the header that must be allocated
920        // along with the block and is a multiple of the alignment size.
921        size_t tsize = size + sizeof(Heap.Storage);
922
923        #ifdef __STATISTICS__
924        stats.counters[STAT_NAME].calls += 1;
925        stats.counters[STAT_NAME].request += size;
926        #endif // __STATISTICS__
927
928        #ifdef __CFA_DEBUG__
929        allocUnfreed += size;
930        #endif // __CFA_DEBUG__
931
932        if ( likely( tsize < heapMaster.mmapStart ) ) {         // small size => sbrk
933                size_t bucket;
934                #ifdef FASTLOOKUP
935                if ( likely( tsize < LookupSizes ) ) bucket = lookup[tsize];
936                else
937                #endif // FASTLOOKUP
938                        bucket = Bsearchl( tsize, bucketSizes, heapMaster.maxBucketsUsed );
939                verify( 0 <= bucket && bucket <= heapMaster.maxBucketsUsed );
940                Heap.FreeHeader * freeHead = &freeLists[bucket];
941
942                verify( freeHead <= &freeLists[heapMaster.maxBucketsUsed] ); // subscripting error ?
943                verify( tsize <= freeHead->blockSize );                 // search failure ?
944
945                tsize = freeHead->blockSize;                                    // total space needed for request
946                #ifdef __STATISTICS__
947                stats.counters[STAT_NAME].alloc += tsize;
948                #endif // __STATISTICS__
949
950                block = freeHead->freeList;                                             // remove node from stack
951                if ( unlikely( block == 0p ) ) {                                // no free block ?
952                        // Freelist for this size is empty, so check return list (OWNERSHIP), carve it out of the heap, if there
953                        // is enough left, or get some more heap storage and carve it off.
954                        #ifdef OWNERSHIP
955                        if ( unlikely( freeHead->returnList ) ) {       // race, get next time if lose race
956                                #ifdef RETURNSPIN
957                                lock( freeHead->returnLock );
958                                block = freeHead->returnList;
959                                freeHead->returnList = 0p;
960                                unlock( freeHead->returnLock );
961                                #else
962                                block = __atomic_exchange_n( &freeHead->returnList, 0p, __ATOMIC_SEQ_CST );
963                                #endif // RETURNSPIN
964
965                                verify( block );
966                                #ifdef __STATISTICS__
967                                stats.return_pulls += 1;
968                                #endif // __STATISTICS__
969
970                                // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED.
971
972                                freeHead->freeList = block->header.kind.real.next; // merge returnList into freeHead
973                        } else {
974                        #endif // OWNERSHIP
975                                // Do not leave kernel thread as manager_extend accesses heapManager.
976                                disable_interrupts();
977                                block = (Heap.Storage *)manager_extend( tsize ); // mutual exclusion on call
978                                enable_interrupts( false );
979
980                                // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED.
981
982                                #ifdef __CFA_DEBUG__
983                                // Scrub new memory so subsequent uninitialized usages might fail. Only scrub the first SCRUB_SIZE bytes.
984                                memset( block->data, SCRUB, min( SCRUB_SIZE, tsize - sizeof(Heap.Storage) ) );
985                                #endif // __CFA_DEBUG__
986                        #ifdef OWNERSHIP
987                        } // if
988                        #endif // OWNERSHIP
989                } else {
990                        // Memory is scrubbed in doFree.
991                        freeHead->freeList = block->header.kind.real.next;
992                } // if
993
994                block->header.kind.real.home = freeHead;                // pointer back to free list of apropriate size
995        } else {                                                                                        // large size => mmap
996  if ( unlikely( size > ULONG_MAX - __page_size ) ) return 0p;
997                tsize = ceiling2( tsize, __page_size );                 // must be multiple of page size
998
999                #ifdef __STATISTICS__
1000                stats.counters[STAT_NAME].alloc += tsize;
1001                stats.mmap_calls += 1;
1002                stats.mmap_storage_request += size;
1003                stats.mmap_storage_alloc += tsize;
1004                #endif // __STATISTICS__
1005
1006                disable_interrupts();
1007                block = (Heap.Storage *)mmap( 0, tsize, __map_prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 );
1008                enable_interrupts( false );
1009
1010                // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED.
1011
1012                if ( unlikely( block == (Heap.Storage *)MAP_FAILED ) ) { // failed ?
1013                        if ( errno == ENOMEM ) abort( NO_MEMORY_MSG, tsize ); // no memory
1014                        // Do not call strerror( errno ) as it may call malloc.
1015                        abort( "**** Error **** attempt to allocate large object (> %zu) of size %zu bytes and mmap failed with errno %d.",
1016                                   size, heapMaster.mmapStart, errno );
1017                } // if
1018                block->header.kind.real.blockSize = MarkMmappedBit( tsize ); // storage size for munmap
1019
1020                #ifdef __CFA_DEBUG__
1021                // Scrub new memory so subsequent uninitialized usages might fail. Only scrub the first SCRUB_SIZE bytes. The
1022                // rest of the storage set to 0 by mmap.
1023                memset( block->data, SCRUB, min( SCRUB_SIZE, tsize - sizeof(Heap.Storage) ) );
1024                #endif // __CFA_DEBUG__
1025        } // if
1026
1027        block->header.kind.real.size = size;                            // store allocation size
1028        void * addr = &(block->data);                                           // adjust off header to user bytes
1029        verify( ((uintptr_t)addr & (libAlign() - 1)) == 0 ); // minimum alignment ?
1030
1031        #ifdef __CFA_DEBUG__
1032        if ( traceHeap() ) {
1033                char helpText[64];
1034                __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText),
1035                                                                        "%p = Malloc( %zu ) (allocated %zu)\n", addr, size, tsize ); // print debug/nodebug
1036        } // if
1037        #endif // __CFA_DEBUG__
1038
1039//      poll_interrupts();                                                                      // call rollforward
1040
1041        return addr;
1042} // doMalloc
1043
1044
1045static void doFree( void * addr ) libcfa_nopreempt with( *heapManager ) {
1046        verify( addr );
1047
1048        // detect free after thread-local storage destruction and use global stats in that case
1049
1050        Heap.Storage.Header * header;
1051        Heap.FreeHeader * freeHead;
1052        size_t size, alignment;
1053
1054        bool mapped = headers( "free", addr, header, freeHead, size, alignment );
1055        #if defined( __STATISTICS__ ) || defined( __CFA_DEBUG__ )
1056        size_t rsize = header->kind.real.size;                          // optimization
1057        #endif // __STATISTICS__ || __CFA_DEBUG__
1058
1059        #ifdef __STATISTICS__
1060        stats.free_storage_request += rsize;
1061        stats.free_storage_alloc += size;
1062        #endif // __STATISTICS__
1063
1064        #ifdef __CFA_DEBUG__
1065        allocUnfreed -= rsize;
1066        #endif // __CFA_DEBUG__
1067
1068        if ( unlikely( mapped ) ) {                                                     // mmapped ?
1069                #ifdef __STATISTICS__
1070                stats.munmap_calls += 1;
1071                stats.munmap_storage_request += rsize;
1072                stats.munmap_storage_alloc += size;
1073                #endif // __STATISTICS__
1074
1075                // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED.
1076
1077                // Does not matter where this storage is freed.
1078                if ( unlikely( munmap( header, size ) == -1 ) ) {
1079                        // Do not call strerror( errno ) as it may call malloc.
1080                        abort( "**** Error **** attempt to deallocate large object %p and munmap failed with errno %d.\n"
1081                                   "Possible cause is invalid delete pointer: either not allocated or with corrupt header.",
1082                                   addr, errno );
1083                } // if
1084        } else {
1085                #ifdef __CFA_DEBUG__
1086                // memset is NOT always inlined!
1087                disable_interrupts();
1088                // Scrub old memory so subsequent usages might fail. Only scrub the first/last SCRUB_SIZE bytes.
1089                char * data = ((Heap.Storage *)header)->data;   // data address
1090                size_t dsize = size - sizeof(Heap.Storage);             // data size
1091                if ( dsize <= SCRUB_SIZE * 2 ) {
1092                        memset( data, SCRUB, dsize );                           // scrub all
1093                } else {
1094                        memset( data, SCRUB, SCRUB_SIZE );                      // scrub front
1095                        memset( data + dsize - SCRUB_SIZE, SCRUB, SCRUB_SIZE ); // scrub back
1096                } // if
1097                enable_interrupts( false );
1098                #endif // __CFA_DEBUG__
1099
1100                #ifdef OWNERSHIP
1101                if ( likely( heapManager == freeHead->homeManager ) ) { // belongs to this thread
1102                        header->kind.real.next = freeHead->freeList; // push on stack
1103                        freeHead->freeList = (Heap.Storage *)header;
1104                } else {                                                                                // return to thread owner
1105                        verify( heapManager );
1106
1107                        #ifdef RETURNSPIN
1108                        lock( freeHead->returnLock );
1109                        header->kind.real.next = freeHead->returnList; // push to bucket return list
1110                        freeHead->returnList = (Heap.Storage *)header;
1111                        unlock( freeHead->returnLock );
1112                        #else                                                                           // lock free
1113                        header->kind.real.next = freeHead->returnList; // link new node to top node
1114                        // CAS resets header->kind.real.next = freeHead->returnList on failure
1115                        while ( ! __atomic_compare_exchange_n( &freeHead->returnList, &header->kind.real.next, (Heap.Storage *)header,
1116                                                                                                   false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ) );
1117                        #endif // RETURNSPIN
1118                } // if
1119
1120                #else                                                                                   // no OWNERSHIP
1121
1122                // kind.real.home is address in owner thread's freeLists, so compute the equivalent position in this thread's freeList.
1123                freeHead = &freeLists[ClearStickyBits( (Heap.FreeHeader *)(header->kind.real.home) ) - &freeHead->homeManager->freeLists[0]];
1124                header->kind.real.next = freeHead->freeList;    // push on stack
1125                freeHead->freeList = (Heap.Storage *)header;
1126                #endif // ! OWNERSHIP
1127
1128                #ifdef __U_STATISTICS__
1129                stats.return_pushes += 1;
1130                stats.return_storage_request += rsize;
1131                stats.return_storage_alloc += size;
1132                #endif // __U_STATISTICS__
1133
1134                // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED.
1135        } // if
1136
1137        #ifdef __CFA_DEBUG__
1138        if ( traceHeap() ) {
1139                char helpText[64];
1140                __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText),
1141                                                                        "Free( %p ) size:%zu\n", addr, size ); // print debug/nodebug
1142        } // if
1143        #endif // __CFA_DEBUG__
1144
1145//      poll_interrupts();                                                                      // call rollforward
1146} // doFree
1147
1148
1149size_t prtFree( Heap & manager ) with( manager ) {
1150        size_t total = 0;
1151        #ifdef __STATISTICS__
1152        __cfaabi_bits_acquire();
1153        __cfaabi_bits_print_nolock( STDERR_FILENO, "\nBin lists (bin size : free blocks on list)\n" );
1154        #endif // __STATISTICS__
1155        for ( unsigned int i = 0; i < heapMaster.maxBucketsUsed; i += 1 ) {
1156                size_t size = freeLists[i].blockSize;
1157                #ifdef __STATISTICS__
1158                unsigned int N = 0;
1159                #endif // __STATISTICS__
1160
1161                for ( Heap.Storage * p = freeLists[i].freeList; p != 0p; p = p->header.kind.real.next ) {
1162                        total += size;
1163                        #ifdef __STATISTICS__
1164                        N += 1;
1165                        #endif // __STATISTICS__
1166                } // for
1167
1168                #ifdef __STATISTICS__
1169                __cfaabi_bits_print_nolock( STDERR_FILENO, "%7zu, %-7u  ", size, N );
1170                if ( (i + 1) % 8 == 0 ) __cfaabi_bits_print_nolock( STDERR_FILENO, "\n" );
1171                #endif // __STATISTICS__
1172        } // for
1173        #ifdef __STATISTICS__
1174        __cfaabi_bits_print_nolock( STDERR_FILENO, "\ntotal free blocks:%zu\n", total );
1175        __cfaabi_bits_release();
1176        #endif // __STATISTICS__
1177        return (char *)heapMaster.heapEnd - (char *)heapMaster.heapBegin - total;
1178} // prtFree
1179
1180
1181#ifdef __STATISTICS__
1182static void incCalls( intptr_t statName ) libcfa_nopreempt {
1183        heapManager->stats.counters[statName].calls += 1;
1184} // incCalls
1185
1186static void incZeroCalls( intptr_t statName ) libcfa_nopreempt {
1187        heapManager->stats.counters[statName].calls_0 += 1;
1188} // incZeroCalls
1189#endif // __STATISTICS__
1190
1191#ifdef __CFA_DEBUG__
1192static void incUnfreed( intptr_t offset ) libcfa_nopreempt {
1193        heapManager->allocUnfreed += offset;
1194} // incUnfreed
1195#endif // __CFA_DEBUG__
1196
1197
1198static void * memalignNoStats( size_t alignment, size_t size STAT_PARM ) {
1199        checkAlign( alignment );                                                        // check alignment
1200
1201        // if alignment <= default alignment or size == 0, do normal malloc as two headers are unnecessary
1202  if ( unlikely( alignment <= libAlign() || size == 0 ) ) return doMalloc( size STAT_ARG( STAT_NAME ) );
1203
1204        // Allocate enough storage to guarantee an address on the alignment boundary, and sufficient space before it for
1205        // administrative storage. NOTE, WHILE THERE ARE 2 HEADERS, THE FIRST ONE IS IMPLICITLY CREATED BY DOMALLOC.
1206        //      .-------------v-----------------v----------------v----------,
1207        //      | Real Header | ... padding ... |   Fake Header  | data ... |
1208        //      `-------------^-----------------^-+--------------^----------'
1209        //      |<--------------------------------' offset/align |<-- alignment boundary
1210
1211        // subtract libAlign() because it is already the minimum alignment
1212        // add sizeof(Storage) for fake header
1213        size_t offset = alignment - libAlign() + sizeof(Heap.Storage);
1214        char * addr = (char *)doMalloc( size + offset STAT_ARG( STAT_NAME ) );
1215
1216        // address in the block of the "next" alignment address
1217        char * user = (char *)ceiling2( (uintptr_t)(addr + sizeof(Heap.Storage)), alignment );
1218
1219        // address of header from malloc
1220        Heap.Storage.Header * realHeader = HeaderAddr( addr );
1221        realHeader->kind.real.size = size;                                      // correct size to eliminate above alignment offset
1222        #ifdef __CFA_DEBUG__
1223        incUnfreed( -offset );                                                          // adjustment off the offset from call to doMalloc
1224        #endif // __CFA_DEBUG__
1225
1226        // address of fake header *before* the alignment location
1227        Heap.Storage.Header * fakeHeader = HeaderAddr( user );
1228
1229        // SKULLDUGGERY: insert the offset to the start of the actual storage block and remember alignment
1230        fakeHeader->kind.fake.offset = (char *)fakeHeader - (char *)realHeader;
1231        // SKULLDUGGERY: odd alignment implies fake header
1232        fakeHeader->kind.fake.alignment = MarkAlignmentBit( alignment );
1233
1234        return user;
1235} // memalignNoStats
1236
1237
1238//####################### Memory Allocation Routines ####################
1239
1240
1241extern "C" {
1242        // Allocates size bytes and returns a pointer to the allocated memory.  The contents are undefined. If size is 0,
1243        // then malloc() returns a unique pointer value that can later be successfully passed to free().
1244        void * malloc( size_t size ) libcfa_public {
1245                return doMalloc( size STAT_ARG( MALLOC ) );
1246        } // malloc
1247
1248
1249        // Same as malloc() except size bytes is an array of dim elements each of elemSize bytes.
1250        void * aalloc( size_t dim, size_t elemSize ) libcfa_public {
1251                return doMalloc( dim * elemSize STAT_ARG( AALLOC ) );
1252        } // aalloc
1253
1254
1255        // Same as aalloc() with memory set to zero.
1256        void * calloc( size_t dim, size_t elemSize ) libcfa_public {
1257                size_t size = dim * elemSize;
1258                char * addr = (char *)doMalloc( size STAT_ARG( CALLOC ) );
1259
1260          if ( unlikely( addr == NULL ) ) return NULL;          // stop further processing if 0p is returned
1261
1262                Heap.Storage.Header * header;
1263                Heap.FreeHeader * freeHead;
1264                size_t bsize, alignment;
1265
1266                #ifndef __CFA_DEBUG__
1267                bool mapped =
1268                        #endif // __CFA_DEBUG__
1269                        headers( "calloc", addr, header, freeHead, bsize, alignment );
1270
1271                #ifndef __CFA_DEBUG__
1272                // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
1273                if ( likely( ! mapped ) )
1274                #endif // __CFA_DEBUG__
1275                        // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined
1276                        // `-header`-addr                      `-size
1277                        memset( addr, '\0', size );                                     // set to zeros
1278
1279                MarkZeroFilledBit( header );                                    // mark as zero fill
1280                return addr;
1281        } // calloc
1282
1283
1284        // Change the size of the memory block pointed to by oaddr to size bytes. The contents are undefined.  If oaddr is
1285        // 0p, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and oaddr is
1286        // not 0p, then the call is equivalent to free(oaddr). Unless oaddr is 0p, it must have been returned by an earlier
1287        // call to malloc(), alloc(), calloc() or realloc(). If the area pointed to was moved, a free(oaddr) is done.
1288        void * resize( void * oaddr, size_t size ) libcfa_public {
1289          if ( unlikely( oaddr == 0p ) ) {                              // => malloc( size )
1290                        return doMalloc( size STAT_ARG( RESIZE ) );
1291                } // if
1292
1293                PROLOG( RESIZE, doFree( oaddr ) );                              // => free( oaddr )
1294
1295                Heap.Storage.Header * header;
1296                Heap.FreeHeader * freeHead;
1297                size_t bsize, oalign;
1298                headers( "resize", oaddr, header, freeHead, bsize, oalign );
1299
1300                size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
1301                // same size, DO NOT preserve STICKY PROPERTIES.
1302                if ( oalign == libAlign() && size <= odsize && odsize <= size * 2 ) { // allow 50% wasted storage for smaller size
1303                        ClearZeroFillBit( header );                                     // no alignment and turn off 0 fill
1304                        #ifdef __CFA_DEBUG__
1305                        incUnfreed( size - header->kind.real.size ); // adjustment off the size difference
1306                        #endif // __CFA_DEBUG__
1307                        header->kind.real.size = size;                          // reset allocation size
1308                        #ifdef __STATISTICS__
1309                        incCalls( RESIZE );
1310                        #endif // __STATISTICS__
1311                        return oaddr;
1312                } // if
1313
1314                // change size, DO NOT preserve STICKY PROPERTIES.
1315                doFree( oaddr );                                                                // free previous storage
1316
1317                return doMalloc( size STAT_ARG( RESIZE ) );             // create new area
1318        } // resize
1319
1320
1321        // Same as resize() but the contents are unchanged in the range from the start of the region up to the minimum of
1322        // the old and new sizes.
1323        void * realloc( void * oaddr, size_t size ) libcfa_public {
1324          if ( unlikely( oaddr == 0p ) ) {                                      // => malloc( size )
1325                  return doMalloc( size STAT_ARG( REALLOC ) );
1326                } // if
1327
1328                PROLOG( REALLOC, doFree( oaddr ) );                             // => free( oaddr )
1329
1330                Heap.Storage.Header * header;
1331                Heap.FreeHeader * freeHead;
1332                size_t bsize, oalign;
1333                headers( "realloc", oaddr, header, freeHead, bsize, oalign );
1334
1335                size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
1336                size_t osize = header->kind.real.size;                  // old allocation size
1337                bool ozfill = ZeroFillBit( header );                    // old allocation zero filled
1338          if ( unlikely( size <= odsize ) && odsize <= size * 2 ) { // allow up to 50% wasted storage
1339                        #ifdef __CFA_DEBUG__
1340                        incUnfreed( size - header->kind.real.size ); // adjustment off the size difference
1341                        #endif // __CFA_DEBUG__
1342                        header->kind.real.size = size;                          // reset allocation size
1343                        if ( unlikely( ozfill ) && size > osize ) {     // previous request zero fill and larger ?
1344                                memset( (char *)oaddr + osize, '\0', size - osize ); // initialize added storage
1345                        } // if
1346                        #ifdef __STATISTICS__
1347                        incCalls( REALLOC );
1348                        #endif // __STATISTICS__
1349                        return oaddr;
1350                } // if
1351
1352                // change size and copy old content to new storage
1353
1354                void * naddr;
1355                if ( likely( oalign <= libAlign() ) ) {                 // previous request not aligned ?
1356                        naddr = doMalloc( size STAT_ARG( REALLOC ) ); // create new area
1357                } else {
1358                        naddr = memalignNoStats( oalign, size STAT_ARG( REALLOC ) ); // create new aligned area
1359                } // if
1360
1361                headers( "realloc", naddr, header, freeHead, bsize, oalign );
1362                // To preserve prior fill, the entire bucket must be copied versus the size.
1363                memcpy( naddr, oaddr, min( osize, size ) );             // copy bytes
1364                doFree( oaddr );                                                                // free previous storage
1365
1366                if ( unlikely( ozfill ) ) {                                             // previous request zero fill ?
1367                        MarkZeroFilledBit( header );                            // mark new request as zero filled
1368                        if ( size > osize ) {                                           // previous request larger ?
1369                                memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage
1370                        } // if
1371                } // if
1372                return naddr;
1373        } // realloc
1374
1375
1376        // Same as realloc() except the new allocation size is large enough for an array of nelem elements of size elsize.
1377        void * reallocarray( void * oaddr, size_t dim, size_t elemSize ) libcfa_public {
1378                return realloc( oaddr, dim * elemSize );
1379        } // reallocarray
1380
1381
1382        // Same as malloc() except the memory address is a multiple of alignment, which must be a power of two. (obsolete)
1383        void * memalign( size_t alignment, size_t size ) libcfa_public {
1384                return memalignNoStats( alignment, size STAT_ARG( MEMALIGN ) );
1385        } // memalign
1386
1387
1388        // Same as aalloc() with memory alignment.
1389        void * amemalign( size_t alignment, size_t dim, size_t elemSize ) libcfa_public {
1390                return memalignNoStats( alignment, dim * elemSize STAT_ARG( AMEMALIGN ) );
1391        } // amemalign
1392
1393
1394        // Same as calloc() with memory alignment.
1395        void * cmemalign( size_t alignment, size_t dim, size_t elemSize ) libcfa_public {
1396                size_t size = dim * elemSize;
1397                char * addr = (char *)memalignNoStats( alignment, size STAT_ARG( CMEMALIGN ) );
1398
1399          if ( unlikely( addr == NULL ) ) return NULL;          // stop further processing if 0p is returned
1400
1401                Heap.Storage.Header * header;
1402                Heap.FreeHeader * freeHead;
1403                size_t bsize;
1404
1405                #ifndef __CFA_DEBUG__
1406                bool mapped =
1407                        #endif // __CFA_DEBUG__
1408                        headers( "cmemalign", addr, header, freeHead, bsize, alignment );
1409
1410                // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
1411                #ifndef __CFA_DEBUG__
1412                if ( ! mapped )
1413                #endif // __CFA_DEBUG__
1414                        // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined
1415                        // `-header`-addr                      `-size
1416                        memset( addr, '\0', size );                                     // set to zeros
1417
1418                MarkZeroFilledBit( header );                                    // mark as zero filled
1419                return addr;
1420        } // cmemalign
1421
1422
1423        // Same as memalign(), but ISO/IEC 2011 C11 Section 7.22.2 states: the value of size shall be an integral multiple
1424        // of alignment. This requirement is universally ignored.
1425        void * aligned_alloc( size_t alignment, size_t size ) libcfa_public {
1426                return memalign( alignment, size );
1427        } // aligned_alloc
1428
1429
1430        // Allocates size bytes and places the address of the allocated memory in *memptr. The address of the allocated
1431        // memory shall be a multiple of alignment, which must be a power of two and a multiple of sizeof(void *). If size
1432        // is 0, then posix_memalign() returns either 0p, or a unique pointer value that can later be successfully passed to
1433        // free(3).
1434        int posix_memalign( void ** memptr, size_t alignment, size_t size ) libcfa_public {
1435          if ( unlikely( alignment < libAlign() || ! is_pow2( alignment ) ) ) return EINVAL; // check alignment
1436                *memptr = memalign( alignment, size );
1437                return 0;
1438        } // posix_memalign
1439
1440
1441        // Allocates size bytes and returns a pointer to the allocated memory. The memory address shall be a multiple of the
1442        // page size.  It is equivalent to memalign(sysconf(_SC_PAGESIZE),size).
1443        void * valloc( size_t size ) libcfa_public {
1444                return memalign( __page_size, size );
1445        } // valloc
1446
1447
1448        // Same as valloc but rounds size to multiple of page size.
1449        void * pvalloc( size_t size ) libcfa_public {
1450                return memalign( __page_size, ceiling2( size, __page_size ) ); // round size to multiple of page size
1451        } // pvalloc
1452
1453
1454        // Frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc()
1455        // or realloc().  Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is
1456        // 0p, no operation is performed.
1457        void free( void * addr ) libcfa_public {
1458//              verify( heapManager );
1459
1460          if ( unlikely( addr == 0p ) ) {                                       // special case
1461                        #ifdef __STATISTICS__
1462                  if ( heapManager )
1463                        incZeroCalls( FREE );
1464                        #endif // __STATISTICS__
1465                        return;
1466                } // if
1467
1468                #ifdef __STATISTICS__
1469                incCalls( FREE );
1470                #endif // __STATISTICS__
1471
1472                doFree( addr );                                                                 // handles heapManager == nullptr
1473        } // free
1474
1475
1476        // Returns the alignment of an allocation.
1477        size_t malloc_alignment( void * addr ) libcfa_public {
1478          if ( unlikely( addr == 0p ) ) return libAlign();      // minimum alignment
1479                Heap.Storage.Header * header = HeaderAddr( addr );
1480                if ( unlikely( AlignmentBit( header ) ) ) {             // fake header ?
1481                        return ClearAlignmentBit( header );                     // clear flag from value
1482                } else {
1483                        return libAlign();                                                      // minimum alignment
1484                } // if
1485        } // malloc_alignment
1486
1487
1488        // Returns true if the allocation is zero filled, e.g., allocated by calloc().
1489        bool malloc_zero_fill( void * addr ) libcfa_public {
1490          if ( unlikely( addr == 0p ) ) return false;           // null allocation is not zero fill
1491                Heap.Storage.Header * header = HeaderAddr( addr );
1492                if ( unlikely( AlignmentBit( header ) ) ) {             // fake header ?
1493                        header = RealHeader( header );                          // backup from fake to real header
1494                } // if
1495                return ZeroFillBit( header );                                   // zero filled ?
1496        } // malloc_zero_fill
1497
1498
1499        // Returns original total allocation size (not bucket size) => array size is dimension * sizeof(T).
1500        size_t malloc_size( void * addr ) libcfa_public {
1501          if ( unlikely( addr == 0p ) ) return 0;                       // null allocation has zero size
1502                Heap.Storage.Header * header = HeaderAddr( addr );
1503                if ( unlikely( AlignmentBit( header ) ) ) {             // fake header ?
1504                        header = RealHeader( header );                          // backup from fake to real header
1505                } // if
1506                return header->kind.real.size;
1507        } // malloc_size
1508
1509
1510        // Returns the number of usable bytes in the block pointed to by ptr, a pointer to a block of memory allocated by
1511        // malloc or a related function.
1512        size_t malloc_usable_size( void * addr ) libcfa_public {
1513          if ( unlikely( addr == 0p ) ) return 0;                       // null allocation has 0 size
1514                Heap.Storage.Header * header;
1515                Heap.FreeHeader * freeHead;
1516                size_t bsize, alignment;
1517
1518                headers( "malloc_usable_size", addr, header, freeHead, bsize, alignment );
1519                return DataStorage( bsize, addr, header );              // data storage in bucket
1520        } // malloc_usable_size
1521
1522
1523        // Prints (on default standard error) statistics about memory allocated by malloc and related functions.
1524        void malloc_stats( void ) libcfa_public {
1525                #ifdef __STATISTICS__
1526                HeapStatistics stats;
1527                HeapStatisticsCtor( stats );
1528                if ( printStats( collectStats( stats ) ) == -1 ) {
1529                #else
1530                #define MALLOC_STATS_MSG "malloc_stats statistics disabled.\n"
1531                if ( write( STDERR_FILENO, MALLOC_STATS_MSG, sizeof( MALLOC_STATS_MSG ) - 1 /* size includes '\0' */ ) == -1 ) {
1532                #endif // __STATISTICS__
1533                        abort( "**** Error **** write failed in malloc_stats" );
1534                } // if
1535        } // malloc_stats
1536
1537
1538        // Changes the file descriptor where malloc_stats() writes statistics.
1539        int malloc_stats_fd( int fd __attribute__(( unused )) ) libcfa_public {
1540                #ifdef __STATISTICS__
1541                int temp = heapMaster.stats_fd;
1542                heapMaster.stats_fd = fd;
1543                return temp;
1544                #else
1545                return -1;                                                                              // unsupported
1546                #endif // __STATISTICS__
1547        } // malloc_stats_fd
1548
1549
1550        // Prints an XML string that describes the current state of the memory-allocation implementation in the caller.
1551        // The string is printed on the file stream stream.  The exported string includes information about all arenas (see
1552        // malloc).
1553        int malloc_info( int options, FILE * stream __attribute__(( unused )) ) libcfa_public {
1554          if ( options != 0 ) { errno = EINVAL; return -1; }
1555                #ifdef __STATISTICS__
1556                HeapStatistics stats;
1557                HeapStatisticsCtor( stats );
1558                return printStatsXML( collectStats( stats ), stream ); // returns bytes written or -1
1559                #else
1560                return 0;                                                                               // unsupported
1561                #endif // __STATISTICS__
1562        } // malloc_info
1563
1564
1565        // Adjusts parameters that control the behaviour of the memory-allocation functions (see malloc). The param argument
1566        // specifies the parameter to be modified, and value specifies the new value for that parameter.
1567        int mallopt( int option, int value ) libcfa_public {
1568          if ( value < 0 ) return 0;
1569                choose( option ) {
1570                  case M_TOP_PAD:
1571                        heapMaster.heapExpand = ceiling2( value, __page_size );
1572                        return 1;
1573                  case M_MMAP_THRESHOLD:
1574                        if ( setMmapStart( value ) ) return 1;
1575                } // choose
1576                return 0;                                                                               // error, unsupported
1577        } // mallopt
1578
1579
1580        // Attempt to release free memory at the top of the heap (by calling sbrk with a suitable argument).
1581        int malloc_trim( size_t ) libcfa_public {
1582                return 0;                                                                               // => impossible to release memory
1583        } // malloc_trim
1584
1585
1586        // Records the current state of all malloc internal bookkeeping variables (but not the actual contents of the heap
1587        // or the state of malloc_hook functions pointers).  The state is recorded in a system-dependent opaque data
1588        // structure dynamically allocated via malloc, and a pointer to that data structure is returned as the function
1589        // result.  (The caller must free this memory.)
1590        void * malloc_get_state( void ) libcfa_public {
1591                return 0p;                                                                              // unsupported
1592        } // malloc_get_state
1593
1594
1595        // Restores the state of all malloc internal bookkeeping variables to the values recorded in the opaque data
1596        // structure pointed to by state.
1597        int malloc_set_state( void * ) libcfa_public {
1598                return 0;                                                                               // unsupported
1599        } // malloc_set_state
1600
1601
1602        // Sets the amount (bytes) to extend the heap when there is insufficent free storage to service an allocation.
1603        __attribute__((weak)) size_t malloc_expansion() libcfa_public { return __CFA_DEFAULT_HEAP_EXPANSION__; }
1604
1605        // Sets the crossover point between allocations occuring in the sbrk area or separately mmapped.
1606        __attribute__((weak)) size_t malloc_mmap_start() libcfa_public { return __CFA_DEFAULT_MMAP_START__; }
1607
1608        // Amount subtracted to adjust for unfreed program storage (debug only).
1609        __attribute__((weak)) size_t malloc_unfreed() libcfa_public { return __CFA_DEFAULT_HEAP_UNFREED__; }
1610} // extern "C"
1611
1612
1613// Must have CFA linkage to overload with C linkage realloc.
1614void * resize( void * oaddr, size_t nalign, size_t size ) libcfa_public {
1615  if ( unlikely( oaddr == 0p ) ) {                                              // => malloc( size )
1616                return memalignNoStats( nalign, size STAT_ARG( RESIZE ) );
1617        } // if
1618
1619        PROLOG( RESIZE, doFree( oaddr ) );                                      // => free( oaddr )
1620
1621        // Attempt to reuse existing alignment.
1622        Heap.Storage.Header * header = HeaderAddr( oaddr );
1623        bool isFakeHeader = AlignmentBit( header );                     // old fake header ?
1624        size_t oalign;
1625
1626        if ( unlikely( isFakeHeader ) ) {
1627                checkAlign( nalign );                                                   // check alignment
1628                oalign = ClearAlignmentBit( header );                   // old alignment
1629                if ( unlikely( (uintptr_t)oaddr % nalign == 0   // lucky match ?
1630                         && ( oalign <= nalign                                          // going down
1631                                  || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ?
1632                        ) ) {
1633                        HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1634                        Heap.FreeHeader * freeHead;
1635                        size_t bsize, oalign;
1636                        headers( "resize", oaddr, header, freeHead, bsize, oalign );
1637                        size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
1638
1639                        if ( size <= odsize && odsize <= size * 2 ) { // allow 50% wasted data storage
1640                                HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1641                                ClearZeroFillBit( header );                             // turn off 0 fill
1642                                #ifdef __CFA_DEBUG__
1643                                incUnfreed( size - header->kind.real.size ); // adjustment off the size difference
1644                                #endif // __CFA_DEBUG__
1645                                header->kind.real.size = size;                  // reset allocation size
1646                                #ifdef __STATISTICS__
1647                                incCalls( RESIZE );
1648                                #endif // __STATISTICS__
1649                                return oaddr;
1650                        } // if
1651                } // if
1652        } else if ( ! isFakeHeader                                                      // old real header (aligned on libAlign) ?
1653                                && nalign == libAlign() ) {                             // new alignment also on libAlign => no fake header needed
1654                return resize( oaddr, size );                                   // duplicate special case checks
1655        } // if
1656
1657        // change size, DO NOT preserve STICKY PROPERTIES.
1658        doFree( oaddr );                                                                        // free previous storage
1659        return memalignNoStats( nalign, size STAT_ARG( RESIZE ) ); // create new aligned area
1660} // resize
1661
1662
1663void * realloc( void * oaddr, size_t nalign, size_t size ) libcfa_public {
1664  if ( unlikely( oaddr == 0p ) ) {                                              // => malloc( size )
1665                return memalignNoStats( nalign, size STAT_ARG( REALLOC ) );
1666        } // if
1667
1668        PROLOG( REALLOC, doFree( oaddr ) );                                     // => free( oaddr )
1669
1670        // Attempt to reuse existing alignment.
1671        Heap.Storage.Header * header = HeaderAddr( oaddr );
1672        bool isFakeHeader = AlignmentBit( header );                     // old fake header ?
1673        size_t oalign;
1674        if ( unlikely( isFakeHeader ) ) {
1675                checkAlign( nalign );                                                   // check alignment
1676                oalign = ClearAlignmentBit( header );                   // old alignment
1677                if ( unlikely( (uintptr_t)oaddr % nalign == 0   // lucky match ?
1678                         && ( oalign <= nalign                                          // going down
1679                                  || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ?
1680                        ) ) {
1681                        HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1682                        return realloc( oaddr, size );                          // duplicate special case checks
1683                } // if
1684        } else if ( ! isFakeHeader                                                      // old real header (aligned on libAlign) ?
1685                                && nalign == libAlign() ) {                             // new alignment also on libAlign => no fake header needed
1686                return realloc( oaddr, size );                                  // duplicate special case checks
1687        } // if
1688
1689        Heap.FreeHeader * freeHead;
1690        size_t bsize;
1691        headers( "realloc", oaddr, header, freeHead, bsize, oalign );
1692
1693        // change size and copy old content to new storage
1694
1695        size_t osize = header->kind.real.size;                          // old allocation size
1696        bool ozfill = ZeroFillBit( header );                            // old allocation zero filled
1697
1698        void * naddr = memalignNoStats( nalign, size STAT_ARG( REALLOC ) ); // create new aligned area
1699
1700        headers( "realloc", naddr, header, freeHead, bsize, oalign );
1701        memcpy( naddr, oaddr, min( osize, size ) );                     // copy bytes
1702        doFree( oaddr );                                                                        // free previous storage
1703
1704        if ( unlikely( ozfill ) ) {                                                     // previous request zero fill ?
1705                MarkZeroFilledBit( header );                                    // mark new request as zero filled
1706                if ( size > osize ) {                                                   // previous request larger ?
1707                        memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage
1708                } // if
1709        } // if
1710        return naddr;
1711} // realloc
1712
1713
1714void * reallocarray( void * oaddr, size_t nalign, size_t dim, size_t elemSize ) __THROW {
1715        return realloc( oaddr, nalign, dim * elemSize );
1716} // reallocarray
1717
1718
1719// Local Variables: //
1720// tab-width: 4 //
1721// compile-command: "cfa -nodebug -O2 heap.cfa" //
1722// End: //
Note: See TracBrowser for help on using the repository browser.