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