source: libcfa/src/heap.cfa@ 19e5d65d

ADT ast-experimental pthread-emulation qualifiedEnum
Last change on this file since 19e5d65d was 19e5d65d, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

second update of heap allocator towards new heap-per-thread version

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