source: libcfa/src/heap.cfa@ 5416b44

ADT ast-experimental pthread-emulation qualifiedEnum
Last change on this file since 5416b44 was 032234bd, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Visibility of the core libcfa files.

  • 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 Heap * homeManager;
512 if ( unlikely( freeHead == 0p || // freed and only free-list node => null link
513 // freed and link points at another free block not to a bucket in the bucket array.
514 freeHead < &freeLists[0] || &freeLists[NoBucketSizes] <= freeHead ) ) {
515 abort( "**** Error **** attempt to %s storage %p with corrupted header.\n"
516 "Possible cause is duplicate free on same block or overwriting of header information.",
517 name, addr );
518 } // if
519 #endif // __CFA_DEBUG__
520
521 return false;
522} // headers
523
524// #ifdef __CFA_DEBUG__
525// #if __SIZEOF_POINTER__ == 4
526// #define MASK 0xdeadbeef
527// #else
528// #define MASK 0xdeadbeefdeadbeef
529// #endif
530// #define STRIDE size_t
531
532// static void * Memset( void * addr, STRIDE size ) { // debug only
533// if ( size % sizeof(STRIDE) != 0 ) abort( "Memset() : internal error, size %zd not multiple of %zd.", size, sizeof(STRIDE) );
534// if ( (STRIDE)addr % sizeof(STRIDE) != 0 ) abort( "Memset() : internal error, addr %p not multiple of %zd.", addr, sizeof(STRIDE) );
535
536// STRIDE * end = (STRIDE *)addr + size / sizeof(STRIDE);
537// for ( STRIDE * p = (STRIDE *)addr; p < end; p += 1 ) *p = MASK;
538// return addr;
539// } // Memset
540// #endif // __CFA_DEBUG__
541
542
543#define NO_MEMORY_MSG "insufficient heap memory available for allocating %zd new bytes."
544
545static inline void * extend( size_t size ) with( heapManager ) {
546 lock( extlock __cfaabi_dbg_ctx2 );
547
548 ptrdiff_t rem = heapRemaining - size;
549 if ( unlikely( rem < 0 ) ) {
550 // If the size requested is bigger than the current remaining storage, increase the size of the heap.
551
552 size_t increase = ceiling2( size > heapExpand ? size : heapExpand, __page_size );
553 // Do not call abort or strerror( errno ) as they may call malloc.
554 if ( sbrk( increase ) == (void *)-1 ) { // failed, no memory ?
555 unlock( extlock );
556 __cfaabi_bits_print_nolock( STDERR_FILENO, NO_MEMORY_MSG, size );
557 _exit( EXIT_FAILURE ); // give up
558 } // if
559
560 // Make storage executable for thunks.
561 if ( mprotect( (char *)heapEnd + heapRemaining, increase, __map_prot ) ) {
562 unlock( extlock );
563 __cfaabi_bits_print_nolock( STDERR_FILENO, "extend() : internal error, mprotect failure, heapEnd:%p size:%zd, errno:%d.\n", heapEnd, increase, errno );
564 _exit( EXIT_FAILURE );
565 } // if
566
567 #ifdef __STATISTICS__
568 sbrk_calls += 1;
569 sbrk_storage += increase;
570 #endif // __STATISTICS__
571
572 #ifdef __CFA_DEBUG__
573 // Set new memory to garbage so subsequent uninitialized usages might fail.
574 memset( (char *)heapEnd + heapRemaining, '\xde', increase );
575 //Memset( (char *)heapEnd + heapRemaining, increase );
576 #endif // __CFA_DEBUG__
577
578 rem = heapRemaining + increase - size;
579 } // if
580
581 Heap.Storage * block = (Heap.Storage *)heapEnd;
582 heapRemaining = rem;
583 heapEnd = (char *)heapEnd + size;
584 unlock( extlock );
585 return block;
586} // extend
587
588
589static inline void * doMalloc( size_t size ) with( heapManager ) {
590 Heap.Storage * block; // pointer to new block of storage
591
592 // Look up size in the size list. Make sure the user request includes space for the header that must be allocated
593 // along with the block and is a multiple of the alignment size.
594
595 size_t tsize = size + sizeof(Heap.Storage);
596
597 if ( likely( tsize < mmapStart ) ) { // small size => sbrk
598 size_t posn;
599 #ifdef FASTLOOKUP
600 if ( tsize < LookupSizes ) posn = lookup[tsize];
601 else
602 #endif // FASTLOOKUP
603 posn = Bsearchl( (unsigned int)tsize, bucketSizes, (size_t)maxBucketsUsed );
604 Heap.FreeHeader * freeElem = &freeLists[posn];
605 verify( freeElem <= &freeLists[maxBucketsUsed] ); // subscripting error ?
606 verify( tsize <= freeElem->blockSize ); // search failure ?
607 tsize = freeElem->blockSize; // total space needed for request
608
609 // Spin until the lock is acquired for this particular size of block.
610
611 #if BUCKETLOCK == SPINLOCK
612 lock( freeElem->lock __cfaabi_dbg_ctx2 );
613 block = freeElem->freeList; // remove node from stack
614 #else
615 block = pop( freeElem->freeList );
616 #endif // BUCKETLOCK
617 if ( unlikely( block == 0p ) ) { // no free block ?
618 #if BUCKETLOCK == SPINLOCK
619 unlock( freeElem->lock );
620 #endif // BUCKETLOCK
621
622 // Freelist for that size was empty, so carve it out of the heap if there's enough left, or get some more
623 // and then carve it off.
624
625 block = (Heap.Storage *)extend( tsize ); // mutual exclusion on call
626 #if BUCKETLOCK == SPINLOCK
627 } else {
628 freeElem->freeList = block->header.kind.real.next;
629 unlock( freeElem->lock );
630 #endif // BUCKETLOCK
631 } // if
632
633 block->header.kind.real.home = freeElem; // pointer back to free list of apropriate size
634 } else { // large size => mmap
635 if ( unlikely( size > ULONG_MAX - __page_size ) ) return 0p;
636 tsize = ceiling2( tsize, __page_size ); // must be multiple of page size
637 #ifdef __STATISTICS__
638 __atomic_add_fetch( &stats.mmap_calls, 1, __ATOMIC_SEQ_CST );
639 __atomic_add_fetch( &stats.mmap_storage_request, size, __ATOMIC_SEQ_CST );
640 __atomic_add_fetch( &stats.mmap_storage_alloc, tsize, __ATOMIC_SEQ_CST );
641 #endif // __STATISTICS__
642
643 block = (Heap.Storage *)mmap( 0, tsize, __map_prot, MAP_PRIVATE | MAP_ANONYMOUS, mmapFd, 0 );
644 if ( block == (Heap.Storage *)MAP_FAILED ) { // failed ?
645 if ( errno == ENOMEM ) abort( NO_MEMORY_MSG, tsize ); // no memory
646 // Do not call strerror( errno ) as it may call malloc.
647 abort( "(Heap &)0x%p.doMalloc() : internal error, mmap failure, size:%zu errno:%d.", &heapManager, tsize, errno );
648 } //if
649 #ifdef __CFA_DEBUG__
650 // Set new memory to garbage so subsequent uninitialized usages might fail.
651 memset( block, '\xde', tsize );
652 //Memset( block, tsize );
653 #endif // __CFA_DEBUG__
654 block->header.kind.real.blockSize = MarkMmappedBit( tsize ); // storage size for munmap
655 } // if
656
657 block->header.kind.real.size = size; // store allocation size
658 void * addr = &(block->data); // adjust off header to user bytes
659 verify( ((uintptr_t)addr & (libAlign() - 1)) == 0 ); // minimum alignment ?
660
661 #ifdef __CFA_DEBUG__
662 __atomic_add_fetch( &allocUnfreed, tsize, __ATOMIC_SEQ_CST );
663 if ( traceHeap() ) {
664 char helpText[64];
665 __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText),
666 "%p = Malloc( %zu ) (allocated %zu)\n", addr, size, tsize ); // print debug/nodebug
667 } // if
668 #endif // __CFA_DEBUG__
669
670 return addr;
671} // doMalloc
672
673
674static inline void doFree( void * addr ) with( heapManager ) {
675 #ifdef __CFA_DEBUG__
676 if ( unlikely( heapManager.heapBegin == 0p ) ) {
677 abort( "doFree( %p ) : internal error, called before heap is initialized.", addr );
678 } // if
679 #endif // __CFA_DEBUG__
680
681 Heap.Storage.Header * header;
682 Heap.FreeHeader * freeElem;
683 size_t size, alignment; // not used (see realloc)
684
685 if ( headers( "free", addr, header, freeElem, size, alignment ) ) { // mmapped ?
686 #ifdef __STATISTICS__
687 __atomic_add_fetch( &stats.munmap_calls, 1, __ATOMIC_SEQ_CST );
688 __atomic_add_fetch( &stats.munmap_storage_request, header->kind.real.size, __ATOMIC_SEQ_CST );
689 __atomic_add_fetch( &stats.munmap_storage_alloc, size, __ATOMIC_SEQ_CST );
690 #endif // __STATISTICS__
691 if ( munmap( header, size ) == -1 ) {
692 abort( "Attempt to deallocate storage %p not allocated or with corrupt header.\n"
693 "Possible cause is invalid pointer.",
694 addr );
695 } // if
696 } else {
697 #ifdef __CFA_DEBUG__
698 // Set free memory to garbage so subsequent usages might fail.
699 memset( ((Heap.Storage *)header)->data, '\xde', freeElem->blockSize - sizeof( Heap.Storage ) );
700 //Memset( ((Heap.Storage *)header)->data, freeElem->blockSize - sizeof( Heap.Storage ) );
701 #endif // __CFA_DEBUG__
702
703 #ifdef __STATISTICS__
704 __atomic_add_fetch( &stats.free_calls, 1, __ATOMIC_SEQ_CST );
705 __atomic_add_fetch( &stats.free_storage_request, header->kind.real.size, __ATOMIC_SEQ_CST );
706 __atomic_add_fetch( &stats.free_storage_alloc, size, __ATOMIC_SEQ_CST );
707 #endif // __STATISTICS__
708
709 #if BUCKETLOCK == SPINLOCK
710 lock( freeElem->lock __cfaabi_dbg_ctx2 ); // acquire spin lock
711 header->kind.real.next = freeElem->freeList; // push on stack
712 freeElem->freeList = (Heap.Storage *)header;
713 unlock( freeElem->lock ); // release spin lock
714 #else
715 push( freeElem->freeList, *(Heap.Storage *)header );
716 #endif // BUCKETLOCK
717 } // if
718
719 #ifdef __CFA_DEBUG__
720 __atomic_add_fetch( &allocUnfreed, -size, __ATOMIC_SEQ_CST );
721 if ( traceHeap() ) {
722 char helpText[64];
723 __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText),
724 "Free( %p ) size:%zu\n", addr, size ); // print debug/nodebug
725 } // if
726 #endif // __CFA_DEBUG__
727} // doFree
728
729
730static size_t prtFree( Heap & manager ) with( manager ) {
731 size_t total = 0;
732 #ifdef __STATISTICS__
733 __cfaabi_bits_acquire();
734 __cfaabi_bits_print_nolock( STDERR_FILENO, "\nBin lists (bin size : free blocks on list)\n" );
735 #endif // __STATISTICS__
736 for ( unsigned int i = 0; i < maxBucketsUsed; i += 1 ) {
737 size_t size = freeLists[i].blockSize;
738 #ifdef __STATISTICS__
739 unsigned int N = 0;
740 #endif // __STATISTICS__
741
742 #if BUCKETLOCK == SPINLOCK
743 for ( Heap.Storage * p = freeLists[i].freeList; p != 0p; p = p->header.kind.real.next ) {
744 #else
745 for(;;) {
746// for ( Heap.Storage * p = top( freeLists[i].freeList ); p != 0p; p = (p)`next->top ) {
747// for ( Heap.Storage * p = top( freeLists[i].freeList ); p != 0p; /* p = getNext( p )->top */) {
748// Heap.Storage * temp = p->header.kind.real.next.top; // FIX ME: direct assignent fails, initialization works`
749// typeof(p) temp = (( p )`next)->top; // FIX ME: direct assignent fails, initialization works`
750// p = temp;
751 #endif // BUCKETLOCK
752 total += size;
753 #ifdef __STATISTICS__
754 N += 1;
755 #endif // __STATISTICS__
756 } // for
757
758 #ifdef __STATISTICS__
759 __cfaabi_bits_print_nolock( STDERR_FILENO, "%7zu, %-7u ", size, N );
760 if ( (i + 1) % 8 == 0 ) __cfaabi_bits_print_nolock( STDERR_FILENO, "\n" );
761 #endif // __STATISTICS__
762 } // for
763 #ifdef __STATISTICS__
764 __cfaabi_bits_print_nolock( STDERR_FILENO, "\ntotal free blocks:%zu\n", total );
765 __cfaabi_bits_release();
766 #endif // __STATISTICS__
767 return (char *)heapEnd - (char *)heapBegin - total;
768} // prtFree
769
770
771static void ?{}( Heap & manager ) with( manager ) {
772 __page_size = sysconf( _SC_PAGESIZE );
773 __map_prot = PROT_READ | PROT_WRITE | PROT_EXEC;
774
775 for ( unsigned int i = 0; i < NoBucketSizes; i += 1 ) { // initialize the free lists
776 freeLists[i].blockSize = bucketSizes[i];
777 } // for
778
779 #ifdef FASTLOOKUP
780 unsigned int idx = 0;
781 for ( unsigned int i = 0; i < LookupSizes; i += 1 ) {
782 if ( i > bucketSizes[idx] ) idx += 1;
783 lookup[i] = idx;
784 } // for
785 #endif // FASTLOOKUP
786
787 if ( ! setMmapStart( malloc_mmap_start() ) ) {
788 abort( "Heap : internal error, mmap start initialization failure." );
789 } // if
790 heapExpand = malloc_expansion();
791
792 char * end = (char *)sbrk( 0 );
793 heapBegin = heapEnd = sbrk( (char *)ceiling2( (long unsigned int)end, __page_size ) - end ); // move start of heap to multiple of alignment
794} // Heap
795
796
797static void ^?{}( Heap & ) {
798 #ifdef __STATISTICS__
799 if ( traceHeapTerm() ) {
800 printStats();
801 // prtUnfreed() called in heapAppStop()
802 } // if
803 #endif // __STATISTICS__
804} // ~Heap
805
806
807static void memory_startup( void ) __attribute__(( constructor( STARTUP_PRIORITY_MEMORY ) ));
808void memory_startup( void ) {
809 #ifdef __CFA_DEBUG__
810 if ( heapBoot ) { // check for recursion during system boot
811 abort( "boot() : internal error, recursively invoked during system boot." );
812 } // if
813 heapBoot = true;
814 #endif // __CFA_DEBUG__
815
816 //verify( heapManager.heapBegin != 0 );
817 //heapManager{};
818 if ( heapManager.heapBegin == 0p ) heapManager{}; // sanity check
819} // memory_startup
820
821static void memory_shutdown( void ) __attribute__(( destructor( STARTUP_PRIORITY_MEMORY ) ));
822void memory_shutdown( void ) {
823 ^heapManager{};
824} // memory_shutdown
825
826
827static inline void * mallocNoStats( size_t size ) { // necessary for malloc statistics
828 verify( heapManager.heapBegin != 0p ); // called before memory_startup ?
829 if ( unlikely( size ) == 0 ) return 0p; // 0 BYTE ALLOCATION RETURNS NULL POINTER
830
831#if __SIZEOF_POINTER__ == 8
832 verify( size < ((typeof(size_t))1 << 48) );
833#endif // __SIZEOF_POINTER__ == 8
834 return doMalloc( size );
835} // mallocNoStats
836
837
838static inline void * memalignNoStats( size_t alignment, size_t size ) {
839 if ( unlikely( size ) == 0 ) return 0p; // 0 BYTE ALLOCATION RETURNS NULL POINTER
840
841 #ifdef __CFA_DEBUG__
842 checkAlign( alignment ); // check alignment
843 #endif // __CFA_DEBUG__
844
845 // if alignment <= default alignment, do normal malloc as two headers are unnecessary
846 if ( unlikely( alignment <= libAlign() ) ) return mallocNoStats( size );
847
848 // Allocate enough storage to guarantee an address on the alignment boundary, and sufficient space before it for
849 // administrative storage. NOTE, WHILE THERE ARE 2 HEADERS, THE FIRST ONE IS IMPLICITLY CREATED BY DOMALLOC.
850 // .-------------v-----------------v----------------v----------,
851 // | Real Header | ... padding ... | Fake Header | data ... |
852 // `-------------^-----------------^-+--------------^----------'
853 // |<--------------------------------' offset/align |<-- alignment boundary
854
855 // subtract libAlign() because it is already the minimum alignment
856 // add sizeof(Storage) for fake header
857 char * addr = (char *)mallocNoStats( size + alignment - libAlign() + sizeof(Heap.Storage) );
858
859 // address in the block of the "next" alignment address
860 char * user = (char *)ceiling2( (uintptr_t)(addr + sizeof(Heap.Storage)), alignment );
861
862 // address of header from malloc
863 Heap.Storage.Header * RealHeader = HeaderAddr( addr );
864 RealHeader->kind.real.size = size; // correct size to eliminate above alignment offset
865 // address of fake header * before* the alignment location
866 Heap.Storage.Header * fakeHeader = HeaderAddr( user );
867 // SKULLDUGGERY: insert the offset to the start of the actual storage block and remember alignment
868 fakeHeader->kind.fake.offset = (char *)fakeHeader - (char *)RealHeader;
869 // SKULLDUGGERY: odd alignment implies fake header
870 fakeHeader->kind.fake.alignment = MarkAlignmentBit( alignment );
871
872 return user;
873} // memalignNoStats
874
875
876//####################### Memory Allocation Routines ####################
877
878
879extern "C" {
880 // Allocates size bytes and returns a pointer to the allocated memory. The contents are undefined. If size is 0,
881 // then malloc() returns a unique pointer value that can later be successfully passed to free().
882 void * malloc( size_t size ) libcfa_public {
883 #ifdef __STATISTICS__
884 if ( likely( size > 0 ) ) {
885 __atomic_add_fetch( &stats.malloc_calls, 1, __ATOMIC_SEQ_CST );
886 __atomic_add_fetch( &stats.malloc_storage_request, size, __ATOMIC_SEQ_CST );
887 } else {
888 __atomic_add_fetch( &stats.malloc_0_calls, 1, __ATOMIC_SEQ_CST );
889 } // if
890 #endif // __STATISTICS__
891
892 return mallocNoStats( size );
893 } // malloc
894
895
896 // Same as malloc() except size bytes is an array of dim elements each of elemSize bytes.
897 void * aalloc( size_t dim, size_t elemSize ) libcfa_public {
898 size_t size = dim * elemSize;
899 #ifdef __STATISTICS__
900 if ( likely( size > 0 ) ) {
901 __atomic_add_fetch( &stats.aalloc_calls, 1, __ATOMIC_SEQ_CST );
902 __atomic_add_fetch( &stats.aalloc_storage_request, size, __ATOMIC_SEQ_CST );
903 } else {
904 __atomic_add_fetch( &stats.aalloc_0_calls, 1, __ATOMIC_SEQ_CST );
905 } // if
906 #endif // __STATISTICS__
907
908 return mallocNoStats( size );
909 } // aalloc
910
911
912 // Same as aalloc() with memory set to zero.
913 void * calloc( size_t dim, size_t elemSize ) libcfa_public {
914 size_t size = dim * elemSize;
915 if ( unlikely( size ) == 0 ) { // 0 BYTE ALLOCATION RETURNS NULL POINTER
916 #ifdef __STATISTICS__
917 __atomic_add_fetch( &stats.calloc_0_calls, 1, __ATOMIC_SEQ_CST );
918 #endif // __STATISTICS__
919 return 0p;
920 } // if
921 #ifdef __STATISTICS__
922 __atomic_add_fetch( &stats.calloc_calls, 1, __ATOMIC_SEQ_CST );
923 __atomic_add_fetch( &stats.calloc_storage_request, dim * elemSize, __ATOMIC_SEQ_CST );
924 #endif // __STATISTICS__
925
926 char * addr = (char *)mallocNoStats( size );
927
928 Heap.Storage.Header * header;
929 Heap.FreeHeader * freeElem;
930 size_t bsize, alignment;
931
932 #ifndef __CFA_DEBUG__
933 bool mapped =
934 #endif // __CFA_DEBUG__
935 headers( "calloc", addr, header, freeElem, bsize, alignment );
936
937 #ifndef __CFA_DEBUG__
938 // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
939 if ( ! mapped )
940 #endif // __CFA_DEBUG__
941 // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined
942 // `-header`-addr `-size
943 memset( addr, '\0', size ); // set to zeros
944
945 MarkZeroFilledBit( header ); // mark as zero fill
946 return addr;
947 } // calloc
948
949
950 // Change the size of the memory block pointed to by oaddr to size bytes. The contents are undefined. If oaddr is
951 // 0p, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and oaddr is
952 // not 0p, then the call is equivalent to free(oaddr). Unless oaddr is 0p, it must have been returned by an earlier
953 // call to malloc(), alloc(), calloc() or realloc(). If the area pointed to was moved, a free(oaddr) is done.
954 void * resize( void * oaddr, size_t size ) libcfa_public {
955 // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
956 if ( unlikely( size == 0 ) ) { // special cases
957 #ifdef __STATISTICS__
958 __atomic_add_fetch( &stats.resize_0_calls, 1, __ATOMIC_SEQ_CST );
959 #endif // __STATISTICS__
960 free( oaddr );
961 return 0p;
962 } // if
963 #ifdef __STATISTICS__
964 __atomic_add_fetch( &stats.resize_calls, 1, __ATOMIC_SEQ_CST );
965 #endif // __STATISTICS__
966
967 if ( unlikely( oaddr == 0p ) ) {
968 #ifdef __STATISTICS__
969 __atomic_add_fetch( &stats.resize_storage_request, size, __ATOMIC_SEQ_CST );
970 #endif // __STATISTICS__
971 return mallocNoStats( size );
972 } // if
973
974 Heap.Storage.Header * header;
975 Heap.FreeHeader * freeElem;
976 size_t bsize, oalign;
977 headers( "resize", oaddr, header, freeElem, bsize, oalign );
978
979 size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
980 // same size, DO NOT preserve STICKY PROPERTIES.
981 if ( oalign == libAlign() && size <= odsize && odsize <= size * 2 ) { // allow 50% wasted storage for smaller size
982 ClearZeroFillBit( header ); // no alignment and turn off 0 fill
983 header->kind.real.size = size; // reset allocation size
984 return oaddr;
985 } // if
986
987 #ifdef __STATISTICS__
988 __atomic_add_fetch( &stats.resize_storage_request, size, __ATOMIC_SEQ_CST );
989 #endif // __STATISTICS__
990
991 // change size, DO NOT preserve STICKY PROPERTIES.
992 free( oaddr );
993 return mallocNoStats( size ); // create new area
994 } // resize
995
996
997 // Same as resize() but the contents are unchanged in the range from the start of the region up to the minimum of
998 // the old and new sizes.
999 void * realloc( void * oaddr, size_t size ) libcfa_public {
1000 // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
1001 if ( unlikely( size == 0 ) ) { // special cases
1002 #ifdef __STATISTICS__
1003 __atomic_add_fetch( &stats.realloc_0_calls, 1, __ATOMIC_SEQ_CST );
1004 #endif // __STATISTICS__
1005 free( oaddr );
1006 return 0p;
1007 } // if
1008 #ifdef __STATISTICS__
1009 __atomic_add_fetch( &stats.realloc_calls, 1, __ATOMIC_SEQ_CST );
1010 #endif // __STATISTICS__
1011
1012 if ( unlikely( oaddr == 0p ) ) {
1013 #ifdef __STATISTICS__
1014 __atomic_add_fetch( &stats.realloc_storage_request, size, __ATOMIC_SEQ_CST );
1015 #endif // __STATISTICS__
1016 return mallocNoStats( size );
1017 } // if
1018
1019 Heap.Storage.Header * header;
1020 Heap.FreeHeader * freeElem;
1021 size_t bsize, oalign;
1022 headers( "realloc", oaddr, header, freeElem, bsize, oalign );
1023
1024 size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
1025 size_t osize = header->kind.real.size; // old allocation size
1026 bool ozfill = ZeroFillBit( header ); // old allocation zero filled
1027 if ( unlikely( size <= odsize ) && odsize <= size * 2 ) { // allow up to 50% wasted storage
1028 header->kind.real.size = size; // reset allocation size
1029 if ( unlikely( ozfill ) && size > osize ) { // previous request zero fill and larger ?
1030 memset( (char *)oaddr + osize, '\0', size - osize ); // initialize added storage
1031 } // if
1032 return oaddr;
1033 } // if
1034
1035 #ifdef __STATISTICS__
1036 __atomic_add_fetch( &stats.realloc_storage_request, size, __ATOMIC_SEQ_CST );
1037 #endif // __STATISTICS__
1038
1039 // change size and copy old content to new storage
1040
1041 void * naddr;
1042 if ( likely( oalign == libAlign() ) ) { // previous request not aligned ?
1043 naddr = mallocNoStats( size ); // create new area
1044 } else {
1045 naddr = memalignNoStats( oalign, size ); // create new aligned area
1046 } // if
1047
1048 headers( "realloc", naddr, header, freeElem, bsize, oalign );
1049 memcpy( naddr, oaddr, min( osize, size ) ); // copy bytes
1050 free( oaddr );
1051
1052 if ( unlikely( ozfill ) ) { // previous request zero fill ?
1053 MarkZeroFilledBit( header ); // mark new request as zero filled
1054 if ( size > osize ) { // previous request larger ?
1055 memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage
1056 } // if
1057 } // if
1058 return naddr;
1059 } // realloc
1060
1061
1062 // Same as realloc() except the new allocation size is large enough for an array of nelem elements of size elsize.
1063 void * reallocarray( void * oaddr, size_t dim, size_t elemSize ) libcfa_public {
1064 return realloc( oaddr, dim * elemSize );
1065 } // reallocarray
1066
1067
1068 // Same as malloc() except the memory address is a multiple of alignment, which must be a power of two. (obsolete)
1069 void * memalign( size_t alignment, size_t size ) libcfa_public {
1070 #ifdef __STATISTICS__
1071 if ( likely( size > 0 ) ) {
1072 __atomic_add_fetch( &stats.memalign_calls, 1, __ATOMIC_SEQ_CST );
1073 __atomic_add_fetch( &stats.memalign_storage_request, size, __ATOMIC_SEQ_CST );
1074 } else {
1075 __atomic_add_fetch( &stats.memalign_0_calls, 1, __ATOMIC_SEQ_CST );
1076 } // if
1077 #endif // __STATISTICS__
1078
1079 return memalignNoStats( alignment, size );
1080 } // memalign
1081
1082
1083 // Same as aalloc() with memory alignment.
1084 void * amemalign( size_t alignment, size_t dim, size_t elemSize ) libcfa_public {
1085 size_t size = dim * elemSize;
1086 #ifdef __STATISTICS__
1087 if ( likely( size > 0 ) ) {
1088 __atomic_add_fetch( &stats.cmemalign_calls, 1, __ATOMIC_SEQ_CST );
1089 __atomic_add_fetch( &stats.cmemalign_storage_request, size, __ATOMIC_SEQ_CST );
1090 } else {
1091 __atomic_add_fetch( &stats.cmemalign_0_calls, 1, __ATOMIC_SEQ_CST );
1092 } // if
1093 #endif // __STATISTICS__
1094
1095 return memalignNoStats( alignment, size );
1096 } // amemalign
1097
1098
1099 // Same as calloc() with memory alignment.
1100 void * cmemalign( size_t alignment, size_t dim, size_t elemSize ) libcfa_public {
1101 size_t size = dim * elemSize;
1102 if ( unlikely( size ) == 0 ) { // 0 BYTE ALLOCATION RETURNS NULL POINTER
1103 #ifdef __STATISTICS__
1104 __atomic_add_fetch( &stats.cmemalign_0_calls, 1, __ATOMIC_SEQ_CST );
1105 #endif // __STATISTICS__
1106 return 0p;
1107 } // if
1108 #ifdef __STATISTICS__
1109 __atomic_add_fetch( &stats.cmemalign_calls, 1, __ATOMIC_SEQ_CST );
1110 __atomic_add_fetch( &stats.cmemalign_storage_request, dim * elemSize, __ATOMIC_SEQ_CST );
1111 #endif // __STATISTICS__
1112
1113 char * addr = (char *)memalignNoStats( alignment, size );
1114
1115 Heap.Storage.Header * header;
1116 Heap.FreeHeader * freeElem;
1117 size_t bsize;
1118
1119 #ifndef __CFA_DEBUG__
1120 bool mapped =
1121 #endif // __CFA_DEBUG__
1122 headers( "cmemalign", addr, header, freeElem, bsize, alignment );
1123
1124 // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
1125 #ifndef __CFA_DEBUG__
1126 if ( ! mapped )
1127 #endif // __CFA_DEBUG__
1128 // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined
1129 // `-header`-addr `-size
1130 memset( addr, '\0', size ); // set to zeros
1131
1132 MarkZeroFilledBit( header ); // mark as zero filled
1133 return addr;
1134 } // cmemalign
1135
1136
1137 // Same as memalign(), but ISO/IEC 2011 C11 Section 7.22.2 states: the value of size shall be an integral multiple
1138 // of alignment. This requirement is universally ignored.
1139 void * aligned_alloc( size_t alignment, size_t size ) libcfa_public {
1140 return memalign( alignment, size );
1141 } // aligned_alloc
1142
1143
1144 // Allocates size bytes and places the address of the allocated memory in *memptr. The address of the allocated
1145 // memory shall be a multiple of alignment, which must be a power of two and a multiple of sizeof(void *). If size
1146 // is 0, then posix_memalign() returns either 0p, or a unique pointer value that can later be successfully passed to
1147 // free(3).
1148 int posix_memalign( void ** memptr, size_t alignment, size_t size ) libcfa_public {
1149 if ( unlikely( alignment < libAlign() || ! is_pow2( alignment ) ) ) return EINVAL; // check alignment
1150 *memptr = memalign( alignment, size );
1151 return 0;
1152 } // posix_memalign
1153
1154
1155 // Allocates size bytes and returns a pointer to the allocated memory. The memory address shall be a multiple of the
1156 // page size. It is equivalent to memalign(sysconf(_SC_PAGESIZE),size).
1157 void * valloc( size_t size ) libcfa_public {
1158 return memalign( __page_size, size );
1159 } // valloc
1160
1161
1162 // Same as valloc but rounds size to multiple of page size.
1163 void * pvalloc( size_t size ) libcfa_public {
1164 return memalign( __page_size, ceiling2( size, __page_size ) ); // round size to multiple of page size
1165 } // pvalloc
1166
1167
1168 // Frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc()
1169 // or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is
1170 // 0p, no operation is performed.
1171 void free( void * addr ) libcfa_public {
1172 if ( unlikely( addr == 0p ) ) { // special case
1173 #ifdef __STATISTICS__
1174 __atomic_add_fetch( &stats.free_null_calls, 1, __ATOMIC_SEQ_CST );
1175 #endif // __STATISTICS__
1176
1177 // #ifdef __CFA_DEBUG__
1178 // if ( traceHeap() ) {
1179 // #define nullmsg "Free( 0x0 ) size:0\n"
1180 // // Do not debug print free( 0p ), as it can cause recursive entry from sprintf.
1181 // __cfaabi_dbg_write( nullmsg, sizeof(nullmsg) - 1 );
1182 // } // if
1183 // #endif // __CFA_DEBUG__
1184 return;
1185 } // exit
1186
1187 doFree( addr );
1188 } // free
1189
1190
1191 // Returns the alignment of an allocation.
1192 size_t malloc_alignment( void * addr ) libcfa_public {
1193 if ( unlikely( addr == 0p ) ) return libAlign(); // minimum alignment
1194 Heap.Storage.Header * header = HeaderAddr( addr );
1195 if ( unlikely( AlignmentBit( header ) ) ) { // fake header ?
1196 return ClearAlignmentBit( header ); // clear flag from value
1197 } else {
1198 return libAlign(); // minimum alignment
1199 } // if
1200 } // malloc_alignment
1201
1202
1203 // Returns true if the allocation is zero filled, e.g., allocated by calloc().
1204 bool malloc_zero_fill( void * addr ) libcfa_public {
1205 if ( unlikely( addr == 0p ) ) return false; // null allocation is not zero fill
1206 Heap.Storage.Header * header = HeaderAddr( addr );
1207 if ( unlikely( AlignmentBit( header ) ) ) { // fake header ?
1208 header = RealHeader( header ); // backup from fake to real header
1209 } // if
1210 return ZeroFillBit( header ); // zero filled ?
1211 } // malloc_zero_fill
1212
1213
1214 // Returns original total allocation size (not bucket size) => array size is dimension * sizeof(T).
1215 size_t malloc_size( void * addr ) libcfa_public {
1216 if ( unlikely( addr == 0p ) ) return 0; // null allocation has zero size
1217 Heap.Storage.Header * header = HeaderAddr( addr );
1218 if ( unlikely( AlignmentBit( header ) ) ) { // fake header ?
1219 header = RealHeader( header ); // backup from fake to real header
1220 } // if
1221 return header->kind.real.size;
1222 } // malloc_size
1223
1224
1225 // Returns the number of usable bytes in the block pointed to by ptr, a pointer to a block of memory allocated by
1226 // malloc or a related function.
1227 size_t malloc_usable_size( void * addr ) libcfa_public {
1228 if ( unlikely( addr == 0p ) ) return 0; // null allocation has 0 size
1229 Heap.Storage.Header * header;
1230 Heap.FreeHeader * freeElem;
1231 size_t bsize, alignment;
1232
1233 headers( "malloc_usable_size", addr, header, freeElem, bsize, alignment );
1234 return DataStorage( bsize, addr, header ); // data storage in bucket
1235 } // malloc_usable_size
1236
1237
1238 // Prints (on default standard error) statistics about memory allocated by malloc and related functions.
1239 void malloc_stats( void ) libcfa_public {
1240 #ifdef __STATISTICS__
1241 printStats();
1242 if ( prtFree() ) prtFree( heapManager );
1243 #endif // __STATISTICS__
1244 } // malloc_stats
1245
1246
1247 // Changes the file descriptor where malloc_stats() writes statistics.
1248 int malloc_stats_fd( int fd __attribute__(( unused )) ) libcfa_public {
1249 #ifdef __STATISTICS__
1250 int temp = stats_fd;
1251 stats_fd = fd;
1252 return temp;
1253 #else
1254 return -1; // unsupported
1255 #endif // __STATISTICS__
1256 } // malloc_stats_fd
1257
1258
1259 // Prints an XML string that describes the current state of the memory-allocation implementation in the caller.
1260 // The string is printed on the file stream stream. The exported string includes information about all arenas (see
1261 // malloc).
1262 int malloc_info( int options, FILE * stream __attribute__(( unused )) ) libcfa_public {
1263 if ( options != 0 ) { errno = EINVAL; return -1; }
1264 #ifdef __STATISTICS__
1265 return printStatsXML( stream );
1266 #else
1267 return 0; // unsupported
1268 #endif // __STATISTICS__
1269 } // malloc_info
1270
1271
1272 // Adjusts parameters that control the behaviour of the memory-allocation functions (see malloc). The param argument
1273 // specifies the parameter to be modified, and value specifies the new value for that parameter.
1274 int mallopt( int option, int value ) libcfa_public {
1275 if ( value < 0 ) return 0;
1276 choose( option ) {
1277 case M_TOP_PAD:
1278 heapExpand = ceiling2( value, __page_size );
1279 return 1;
1280 case M_MMAP_THRESHOLD:
1281 if ( setMmapStart( value ) ) return 1;
1282 } // choose
1283 return 0; // error, unsupported
1284 } // mallopt
1285
1286
1287 // Attempt to release free memory at the top of the heap (by calling sbrk with a suitable argument).
1288 int malloc_trim( size_t ) libcfa_public {
1289 return 0; // => impossible to release memory
1290 } // malloc_trim
1291
1292
1293 // Records the current state of all malloc internal bookkeeping variables (but not the actual contents of the heap
1294 // or the state of malloc_hook functions pointers). The state is recorded in a system-dependent opaque data
1295 // structure dynamically allocated via malloc, and a pointer to that data structure is returned as the function
1296 // result. (The caller must free this memory.)
1297 void * malloc_get_state( void ) libcfa_public {
1298 return 0p; // unsupported
1299 } // malloc_get_state
1300
1301
1302 // Restores the state of all malloc internal bookkeeping variables to the values recorded in the opaque data
1303 // structure pointed to by state.
1304 int malloc_set_state( void * ) libcfa_public {
1305 return 0; // unsupported
1306 } // malloc_set_state
1307
1308
1309 // Sets the amount (bytes) to extend the heap when there is insufficent free storage to service an allocation.
1310 __attribute__((weak)) size_t malloc_expansion() libcfa_public { return __CFA_DEFAULT_HEAP_EXPANSION__; }
1311
1312 // Sets the crossover point between allocations occuring in the sbrk area or separately mmapped.
1313 __attribute__((weak)) size_t malloc_mmap_start() libcfa_public { return __CFA_DEFAULT_MMAP_START__; }
1314
1315 // Amount subtracted to adjust for unfreed program storage (debug only).
1316 __attribute__((weak)) size_t malloc_unfreed() libcfa_public { return __CFA_DEFAULT_HEAP_UNFREED__; }
1317} // extern "C"
1318
1319
1320// Must have CFA linkage to overload with C linkage realloc.
1321void * resize( void * oaddr, size_t nalign, size_t size ) libcfa_public {
1322 // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
1323 if ( unlikely( size == 0 ) ) { // special cases
1324 #ifdef __STATISTICS__
1325 __atomic_add_fetch( &stats.resize_0_calls, 1, __ATOMIC_SEQ_CST );
1326 #endif // __STATISTICS__
1327 free( oaddr );
1328 return 0p;
1329 } // if
1330
1331 if ( unlikely( nalign < libAlign() ) ) nalign = libAlign(); // reset alignment to minimum
1332 #ifdef __CFA_DEBUG__
1333 else checkAlign( nalign ); // check alignment
1334 #endif // __CFA_DEBUG__
1335
1336 if ( unlikely( oaddr == 0p ) ) {
1337 #ifdef __STATISTICS__
1338 __atomic_add_fetch( &stats.resize_calls, 1, __ATOMIC_SEQ_CST );
1339 __atomic_add_fetch( &stats.resize_storage_request, size, __ATOMIC_SEQ_CST );
1340 #endif // __STATISTICS__
1341 return memalignNoStats( nalign, size );
1342 } // if
1343
1344 // Attempt to reuse existing alignment.
1345 Heap.Storage.Header * header = HeaderAddr( oaddr );
1346 bool isFakeHeader = AlignmentBit( header ); // old fake header ?
1347 size_t oalign;
1348
1349 if ( unlikely( isFakeHeader ) ) {
1350 oalign = ClearAlignmentBit( header ); // old alignment
1351 if ( unlikely( (uintptr_t)oaddr % nalign == 0 // lucky match ?
1352 && ( oalign <= nalign // going down
1353 || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ?
1354 ) ) {
1355 HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1356 Heap.FreeHeader * freeElem;
1357 size_t bsize, oalign;
1358 headers( "resize", oaddr, header, freeElem, bsize, oalign );
1359 size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
1360
1361 if ( size <= odsize && odsize <= size * 2 ) { // allow 50% wasted data storage
1362 HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1363 ClearZeroFillBit( header ); // turn off 0 fill
1364 header->kind.real.size = size; // reset allocation size
1365 return oaddr;
1366 } // if
1367 } // if
1368 } else if ( ! isFakeHeader // old real header (aligned on libAlign) ?
1369 && nalign == libAlign() ) { // new alignment also on libAlign => no fake header needed
1370 return resize( oaddr, size ); // duplicate special case checks
1371 } // if
1372
1373 #ifdef __STATISTICS__
1374 __atomic_add_fetch( &stats.resize_storage_request, size, __ATOMIC_SEQ_CST );
1375 #endif // __STATISTICS__
1376
1377 // change size, DO NOT preserve STICKY PROPERTIES.
1378 free( oaddr );
1379 return memalignNoStats( nalign, size ); // create new aligned area
1380} // resize
1381
1382
1383void * realloc( void * oaddr, size_t nalign, size_t size ) libcfa_public {
1384 // If size is equal to 0, either NULL or a pointer suitable to be passed to free() is returned.
1385 if ( unlikely( size == 0 ) ) { // special cases
1386 #ifdef __STATISTICS__
1387 __atomic_add_fetch( &stats.realloc_0_calls, 1, __ATOMIC_SEQ_CST );
1388 #endif // __STATISTICS__
1389 free( oaddr );
1390 return 0p;
1391 } // if
1392
1393 if ( unlikely( nalign < libAlign() ) ) nalign = libAlign(); // reset alignment to minimum
1394 #ifdef __CFA_DEBUG__
1395 else checkAlign( nalign ); // check alignment
1396 #endif // __CFA_DEBUG__
1397
1398 if ( unlikely( oaddr == 0p ) ) {
1399 #ifdef __STATISTICS__
1400 __atomic_add_fetch( &stats.realloc_calls, 1, __ATOMIC_SEQ_CST );
1401 __atomic_add_fetch( &stats.realloc_storage_request, size, __ATOMIC_SEQ_CST );
1402 #endif // __STATISTICS__
1403 return memalignNoStats( nalign, size );
1404 } // if
1405
1406 // Attempt to reuse existing alignment.
1407 Heap.Storage.Header * header = HeaderAddr( oaddr );
1408 bool isFakeHeader = AlignmentBit( header ); // old fake header ?
1409 size_t oalign;
1410 if ( unlikely( isFakeHeader ) ) {
1411 oalign = ClearAlignmentBit( header ); // old alignment
1412 if ( unlikely( (uintptr_t)oaddr % nalign == 0 // lucky match ?
1413 && ( oalign <= nalign // going down
1414 || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ?
1415 ) ) {
1416 HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1417 return realloc( oaddr, size ); // duplicate special case checks
1418 } // if
1419 } else if ( ! isFakeHeader // old real header (aligned on libAlign) ?
1420 && nalign == libAlign() ) { // new alignment also on libAlign => no fake header needed
1421 return realloc( oaddr, size ); // duplicate special case checks
1422 } // if
1423
1424 #ifdef __STATISTICS__
1425 __atomic_add_fetch( &stats.realloc_calls, 1, __ATOMIC_SEQ_CST );
1426 __atomic_add_fetch( &stats.realloc_storage_request, size, __ATOMIC_SEQ_CST );
1427 #endif // __STATISTICS__
1428
1429 Heap.FreeHeader * freeElem;
1430 size_t bsize;
1431 headers( "realloc", oaddr, header, freeElem, bsize, oalign );
1432
1433 // change size and copy old content to new storage
1434
1435 size_t osize = header->kind.real.size; // old allocation size
1436 bool ozfill = ZeroFillBit( header ); // old allocation zero filled
1437
1438 void * naddr = memalignNoStats( nalign, size ); // create new aligned area
1439
1440 headers( "realloc", naddr, header, freeElem, bsize, oalign );
1441 memcpy( naddr, oaddr, min( osize, size ) ); // copy bytes
1442 free( oaddr );
1443
1444 if ( unlikely( ozfill ) ) { // previous request zero fill ?
1445 MarkZeroFilledBit( header ); // mark new request as zero filled
1446 if ( size > osize ) { // previous request larger ?
1447 memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage
1448 } // if
1449 } // if
1450 return naddr;
1451} // realloc
1452
1453
1454// Local Variables: //
1455// tab-width: 4 //
1456// compile-command: "cfa -nodebug -O2 heap.cfa" //
1457// End: //
Note: See TracBrowser for help on using the repository browser.