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