source: libcfa/src/heap.cfa@ 941e14a

ADT ast-experimental enum forall-pointer-decay pthread-emulation qualifiedEnum
Last change on this file since 941e14a was 578ec01c, checked in by Peter A. Buhr <pabuhr@…>, 4 years ago

update heap statistics to new format (incomplete)

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