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