source: libcfa/src/heap.cfa@ da3b790

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since da3b790 was c1f38e6c, checked in by Peter A. Buhr <pabuhr@…>, 5 years ago

formatting, rename variable allocFree to allocUnfreed, fakeHeader returns libAlign() for no fake header instead of 0, update resize/realloc aligned to work with the fakeHeader change.

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