source: libcfa/src/heap.cfa@ 926d358

ADT ast-experimental
Last change on this file since 926d358 was 5a076837, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Remove unnecessary declaration in heap

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