-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmemory_allocator.h
More file actions
1963 lines (1716 loc) · 68.8 KB
/
memory_allocator.h
File metadata and controls
1963 lines (1716 loc) · 68.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef MEMORY_ALLOCATOR_H
#define MEMORY_ALLOCATOR_H
#include <cstddef> // size_t
#include <cstdint> // uint32_t
#include <atomic>
#include <mutex>
#include <thread>
#include <vector>
#include <memory>
#include <cstring>
#include <algorithm>
#include <condition_variable>
#include <chrono>
#include <sched.h> // sched_yield
#include <sys/mman.h> // mmap, munmap, madvise
#include <unordered_set>
#include <unordered_map>
#include <cstdio> // fprintf for debug output
#include <new> // std::align
#include <cerrno> // EINVAL, ENOMEM for posix_memalign
//-------------------------------------------------------
// Debug/Safety Configuration
// Compile with -DFANCY_DEBUG to enable all safety checks
// Compile with -DFANCY_DEBUG_VERBOSE for detailed logging
//-------------------------------------------------------
#ifdef FANCY_DEBUG
#define FANCY_CANARY_CHECK 1 // Buffer overflow detection
#define FANCY_POISON_CHECK 1 // Use-after-free detection
#define FANCY_DOUBLE_FREE_CHECK 1 // Double-free detection
#define FANCY_STATS_DETAILED 1 // Per-bin statistics
#define FANCY_STATS_ENABLED 1 // Basic stats in hot path
#else
#define FANCY_CANARY_CHECK 0
#define FANCY_POISON_CHECK 0
#define FANCY_DOUBLE_FREE_CHECK 0
#define FANCY_STATS_DETAILED 0
#define FANCY_STATS_ENABLED 0 // No stats overhead in release
#endif
// Debug constants
static constexpr uint32_t CANARY_VALUE = 0xDEADCAFE; // Buffer overflow canary
static constexpr uint32_t POISON_FREED = 0xFEEDFACE; // Freed memory poison
static constexpr uint32_t POISON_UNINIT = 0xBAADF00D; // Uninitialized memory
static constexpr size_t FREED_TRACKER_SIZE = 16384; // Track last N freed pointers
//-------------------------------------------------------
// Memory allocation helpers using mmap for better performance
//-------------------------------------------------------
inline void* allocatePages(size_t size) {
// Round up to page size (4KB)
size = (size + 4095) & ~4095ULL;
// Try huge pages first for large allocations (2MB+)
#ifdef MAP_HUGETLB
if (size >= 2 * 1024 * 1024) {
void* p = mmap(nullptr, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0);
if (p != MAP_FAILED) return p;
}
#endif
// Fall back to regular pages with transparent huge page hint
void* p = mmap(nullptr, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p != MAP_FAILED) {
#ifdef MADV_HUGEPAGE
madvise(p, size, MADV_HUGEPAGE); // THP hint
#endif
}
return (p == MAP_FAILED) ? nullptr : p;
}
inline void freePages(void* ptr, size_t size) {
if (ptr) {
size = (size + 4095) & ~4095ULL;
munmap(ptr, size);
}
}
//-------------------------------------------------------
// Alignment helper functions
//-------------------------------------------------------
inline bool isPowerOfTwo(size_t n) {
return n > 0 && (n & (n - 1)) == 0;
}
inline size_t alignUp(size_t value, size_t alignment) {
return (value + alignment - 1) & ~(alignment - 1);
}
inline void* alignPointer(void* ptr, size_t alignment) {
uintptr_t addr = reinterpret_cast<uintptr_t>(ptr);
uintptr_t aligned = (addr + alignment - 1) & ~(alignment - 1);
return reinterpret_cast<void*>(aligned);
}
// Maximum supported alignment (must be power of 2)
static constexpr size_t MAX_ALIGNMENT = 4096;
static constexpr size_t DEFAULT_ALIGNMENT = 16; // Default for malloc compatibility
//-------------------------------------------------------
// Adaptive Spinlock - faster than std::mutex for short critical sections
//-------------------------------------------------------
class AdaptiveSpinlock {
std::atomic<int> state_{0}; // 0=free, 1=locked, 2=contended
public:
void lock() {
int expected = 0;
if (state_.compare_exchange_weak(expected, 1, std::memory_order_acquire))
return; // Fast path: got lock immediately
// Spin briefly with pause instruction
for (int i = 0; i < 100; i++) {
#if defined(__x86_64__) || defined(_M_X64)
__builtin_ia32_pause();
#elif defined(__aarch64__)
asm volatile("yield" ::: "memory");
#endif
expected = 0;
if (state_.compare_exchange_weak(expected, 1, std::memory_order_acquire))
return;
}
// Fall back to sched_yield for longer waits
while (state_.exchange(2, std::memory_order_acquire) != 0) {
sched_yield();
}
}
void unlock() {
state_.store(0, std::memory_order_release);
}
};
//-------------------------------------------------------
// 1) Stats - Basic and Detailed
//-------------------------------------------------------
struct AllocStatsSnapshot {
size_t totalAllocCalls;
size_t totalFreeCalls;
size_t currentUsedBytes;
size_t peakUsedBytes;
};
// Detailed per-bin statistics (enabled with FANCY_DEBUG)
struct DetailedStatsSnapshot {
AllocStatsSnapshot basic;
// Per-bin stats (small allocations)
size_t smallBinAllocCounts[16];
size_t smallBinFreeCounts[16];
size_t smallBinCurrentCount[16];
// Per-bin stats (large allocations)
size_t largeBinAllocCounts[16];
size_t largeBinFreeCounts[16];
size_t largeBinCurrentCount[16];
// Fragmentation metrics
size_t totalArenaBytes; // Total arena memory
size_t usedArenaBytes; // Actually used memory
size_t freeBlockCount; // Number of free blocks
size_t largestFreeBlock; // Largest contiguous free block
double fragmentationRatio; // 1.0 - (largest / total_free)
// Safety check stats
size_t doubleFreeAttempts;
size_t bufferOverflowsDetected;
size_t useAfterFreeDetected;
size_t corruptedBlocksDetected;
void print() const {
fprintf(stderr, "\n=== FancyAllocator Detailed Stats ===\n");
fprintf(stderr, "Total alloc calls: %zu\n", basic.totalAllocCalls);
fprintf(stderr, "Total free calls: %zu\n", basic.totalFreeCalls);
fprintf(stderr, "Current used bytes: %zu\n", basic.currentUsedBytes);
fprintf(stderr, "Peak used bytes: %zu\n", basic.peakUsedBytes);
fprintf(stderr, "\n--- Small Bin Stats (<=512B) ---\n");
const size_t smallSizes[] = {16, 32, 48, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512};
for (int i = 0; i < 16; i++) {
if (smallBinAllocCounts[i] > 0) {
fprintf(stderr, " Bin %2d (%3zuB): allocs=%zu, frees=%zu, live=%zu\n",
i, smallSizes[i], smallBinAllocCounts[i], smallBinFreeCounts[i], smallBinCurrentCount[i]);
}
}
fprintf(stderr, "\n--- Large Bin Stats (>512B) ---\n");
const char* largeSizeNames[] = {"1K", "2K", "4K", "8K", "16K", "32K", "64K", "128K",
"256K", "512K", "1M", "2M", "4M", "8M", "16M", "huge"};
for (int i = 0; i < 16; i++) {
if (largeBinAllocCounts[i] > 0) {
fprintf(stderr, " Bin %2d (%s): allocs=%zu, frees=%zu, live=%zu\n",
i, largeSizeNames[i], largeBinAllocCounts[i], largeBinFreeCounts[i], largeBinCurrentCount[i]);
}
}
fprintf(stderr, "\n--- Fragmentation ---\n");
fprintf(stderr, "Total arena bytes: %zu\n", totalArenaBytes);
fprintf(stderr, "Used arena bytes: %zu\n", usedArenaBytes);
fprintf(stderr, "Free block count: %zu\n", freeBlockCount);
fprintf(stderr, "Largest free block: %zu\n", largestFreeBlock);
fprintf(stderr, "Fragmentation ratio: %.2f%%\n", fragmentationRatio * 100.0);
if (doubleFreeAttempts > 0 || bufferOverflowsDetected > 0 ||
useAfterFreeDetected > 0 || corruptedBlocksDetected > 0) {
fprintf(stderr, "\n--- SAFETY VIOLATIONS ---\n");
if (doubleFreeAttempts > 0)
fprintf(stderr, " Double-free attempts: %zu\n", doubleFreeAttempts);
if (bufferOverflowsDetected > 0)
fprintf(stderr, " Buffer overflows: %zu\n", bufferOverflowsDetected);
if (useAfterFreeDetected > 0)
fprintf(stderr, " Use-after-free: %zu\n", useAfterFreeDetected);
if (corruptedBlocksDetected > 0)
fprintf(stderr, " Corrupted blocks: %zu\n", corruptedBlocksDetected);
}
fprintf(stderr, "=====================================\n\n");
}
};
// Cache-line aligned to prevent false sharing between cores
struct alignas(64) AllocStats {
std::atomic<size_t> totalAllocCalls{0};
char pad1[64 - sizeof(std::atomic<size_t>)];
std::atomic<size_t> totalFreeCalls{0};
char pad2[64 - sizeof(std::atomic<size_t>)];
std::atomic<size_t> currentUsedBytes{0};
char pad3[64 - sizeof(std::atomic<size_t>)];
std::atomic<size_t> peakUsedBytes{0};
char pad4[64 - sizeof(std::atomic<size_t>)];
#if FANCY_STATS_DETAILED
// Per-bin statistics (only in debug mode)
std::atomic<size_t> smallBinAllocs[16] = {};
std::atomic<size_t> smallBinFrees[16] = {};
std::atomic<size_t> largeBinAllocs[16] = {};
std::atomic<size_t> largeBinFrees[16] = {};
// Safety violation counters
std::atomic<size_t> doubleFreeAttempts{0};
std::atomic<size_t> bufferOverflows{0};
std::atomic<size_t> useAfterFree{0};
std::atomic<size_t> corruptedBlocks{0};
#endif
AllocStatsSnapshot snapshot() const {
AllocStatsSnapshot snap;
snap.totalAllocCalls = totalAllocCalls.load(std::memory_order_relaxed);
snap.totalFreeCalls = totalFreeCalls.load(std::memory_order_relaxed);
snap.currentUsedBytes = currentUsedBytes.load(std::memory_order_relaxed);
snap.peakUsedBytes = peakUsedBytes.load(std::memory_order_relaxed);
return snap;
}
};
//-------------------------------------------------------
// 2) Thread-Local small-block cache
// Expanded to 16 size classes for reduced fragmentation
//-------------------------------------------------------
static constexpr int SMALL_BIN_COUNT = 16;
static constexpr size_t SMALL_BIN_SIZE[SMALL_BIN_COUNT] = {
16, 32, 48, 64, 80, 96, 112, 128, // 8 tiny (16B quantum)
160, 192, 224, 256, // 4 small (32B quantum)
320, 384, 448, 512 // 4 medium (64B quantum)
};
static constexpr size_t MAX_SMALL_SIZE = 512;
// Magic for small block headers (different from Arena::MAGIC)
// Reduced to 16-bit for smaller header
static constexpr uint16_t SMALL_MAGIC = 0xFACE;
// Header must be 16 bytes for 16-byte aligned user data (required for malloc/SIMD compatibility)
// Layout: [header 16B][user data 16B-aligned]
struct alignas(16) SmallBlockHeader {
uint16_t magic; // 2 bytes - Always SMALL_MAGIC
uint8_t binIndex; // 1 byte - 0-15 bins (max 255)
uint8_t flags; // 1 byte - Reserved
uint32_t userSize; // 4 bytes - For realloc support
#if FANCY_CANARY_CHECK
uint32_t canaryHead; // 4 bytes - Debug only
uint32_t pad_; // 4 bytes - Pad to 16 in debug
#else
uint64_t pad_; // 8 bytes - Pad to 16 for user data alignment
#endif
};
static_assert(sizeof(SmallBlockHeader) == 16, "SmallBlockHeader must be 16 bytes for alignment");
struct SmallFreeBlock {
SmallBlockHeader hdr;
SmallFreeBlock* next;
};
// Canary trailer for buffer overflow detection (placed after user data)
struct SmallBlockTrailer {
uint32_t canaryTail;
};
// O(1) size-to-bin lookup - use bit manipulation directly
__attribute__((always_inline))
inline int fastFindSmallBin(size_t size) {
if (__builtin_expect(size > MAX_SMALL_SIZE, 0)) return -1;
if (size <= 16) return 0;
// Tiny: 16B quantum (bins 0-7) -> sizes 1-128
if (size <= 128) {
return ((size - 1) >> 4); // 0-7
}
// Small: 32B quantum (bins 8-11) -> sizes 129-256
if (size <= 256) {
return 8 + ((size - 129) >> 5); // 8-11
}
// Medium: 64B quantum (bins 12-15) -> sizes 257-512
return 12 + ((size - 257) >> 6); // 12-15
}
class ThreadLocalSmallCache {
static constexpr size_t SLAB_SIZE = 64 * 1024; // 64KB slabs
static constexpr size_t MAX_SLABS_PER_BIN = 64; // Track up to 64 slabs per bin
public:
ThreadLocalSmallCache() {
for (int i=0; i<SMALL_BIN_COUNT; i++){
freeList_[i] = nullptr;
slabCurrent_[i] = nullptr;
slabEnd_[i] = nullptr;
slabCount_[i] = 0;
}
ownerSlot_ = 0;
localAllocCalls_ = 0;
localFreeCalls_ = 0;
localBytesAllocated_ = 0;
localBytesFreed_ = 0;
#if FANCY_DOUBLE_FREE_CHECK
freedTrackerIdx_ = 0;
std::memset(freedTracker_, 0, sizeof(freedTracker_));
#endif
}
~ThreadLocalSmallCache() {
// Clean up all slabs
for (int bin = 0; bin < SMALL_BIN_COUNT; bin++) {
for (size_t i = 0; i < slabCount_[bin]; i++) {
if (slabs_[bin][i]) {
freePages(slabs_[bin][i], SLAB_SIZE);
}
}
}
}
void setOwnerSlot(uint16_t slot) { ownerSlot_ = slot; }
// Flush local stats to global (called periodically or on thread exit)
void flushStats(AllocStats& stats) {
if (localAllocCalls_ > 0) {
stats.totalAllocCalls.fetch_add(localAllocCalls_, std::memory_order_relaxed);
localAllocCalls_ = 0;
}
if (localFreeCalls_ > 0) {
stats.totalFreeCalls.fetch_add(localFreeCalls_, std::memory_order_relaxed);
localFreeCalls_ = 0;
}
if (localBytesAllocated_ > localBytesFreed_) {
stats.currentUsedBytes.fetch_add(localBytesAllocated_ - localBytesFreed_, std::memory_order_relaxed);
} else if (localBytesFreed_ > localBytesAllocated_) {
stats.currentUsedBytes.fetch_sub(localBytesFreed_ - localBytesAllocated_, std::memory_order_relaxed);
}
localBytesAllocated_ = 0;
localBytesFreed_ = 0;
}
// find bin index for a requested size - O(1) lookup
int findBin(size_t size) {
return fastFindSmallBin(size);
}
#if FANCY_DOUBLE_FREE_CHECK
bool isRecentlyFreed(void* ptr) {
for (size_t i = 0; i < FREED_TRACKER_SIZE; i++) {
if (freedTracker_[i] == ptr) return true;
}
return false;
}
void trackFreed(void* ptr) {
freedTracker_[freedTrackerIdx_] = ptr;
freedTrackerIdx_ = (freedTrackerIdx_ + 1) % FREED_TRACKER_SIZE;
}
void untrackFreed(void* ptr) {
for (size_t i = 0; i < FREED_TRACKER_SIZE; i++) {
if (freedTracker_[i] == ptr) {
freedTracker_[i] = nullptr;
return;
}
}
}
#endif
__attribute__((always_inline, hot))
void* allocateSmall(size_t reqSize, AllocStats& stats) {
int bin = findBin(reqSize);
if (__builtin_expect(bin < 0, 0)) return nullptr;
void* userPtr = nullptr;
char* block = freeList_[bin];
// Fast path: pop from free list
if (__builtin_expect(block != nullptr, 1)) {
// Get next pointer (stored in user area after header)
char* next = *reinterpret_cast<char**>(block + sizeof(SmallBlockHeader));
freeList_[bin] = next;
auto* hdr = reinterpret_cast<SmallBlockHeader*>(block);
hdr->magic = SMALL_MAGIC;
hdr->userSize = reqSize;
#if FANCY_CANARY_CHECK
hdr->canaryHead = CANARY_VALUE;
#endif
userPtr = block + sizeof(SmallBlockHeader);
#if FANCY_POISON_CHECK
uint32_t* poisonCheck = reinterpret_cast<uint32_t*>(userPtr);
if (*poisonCheck == POISON_FREED) {
size_t binSize = SMALL_BIN_SIZE[bin];
bool corrupted = false;
for (size_t i = sizeof(void*); i < binSize; i += sizeof(uint32_t)) {
if (i + sizeof(uint32_t) <= binSize) {
uint32_t* check = reinterpret_cast<uint32_t*>((char*)userPtr + i);
if (*check != POISON_FREED) {
corrupted = true;
break;
}
}
}
if (corrupted) {
#if FANCY_STATS_DETAILED
stats.useAfterFree.fetch_add(1, std::memory_order_relaxed);
#endif
#ifdef FANCY_DEBUG_VERBOSE
fprintf(stderr, "[FANCY] USE-AFTER-FREE detected at %p (bin %d)\n", userPtr, bin);
#endif
}
}
std::memset(userPtr, (POISON_UNINIT & 0xFF), SMALL_BIN_SIZE[bin]);
#endif
#if FANCY_CANARY_CHECK
char* canaryPos = (char*)userPtr + reqSize;
*reinterpret_cast<uint32_t*>(canaryPos) = CANARY_VALUE;
#endif
#if FANCY_DOUBLE_FREE_CHECK
untrackFreed(userPtr);
#endif
#if FANCY_STATS_DETAILED
stats.smallBinAllocs[bin].fetch_add(1, std::memory_order_relaxed);
#endif
#if FANCY_STATS_ENABLED
if (__builtin_expect((++localAllocCalls_ & 0x3FF) == 0, 0)) {
localBytesAllocated_ += localAllocCalls_ * 32;
flushStats(stats);
}
#endif
return userPtr;
}
// Slow path: allocate from slab (bump pointer)
size_t totalSz = sizeof(SmallBlockHeader) + SMALL_BIN_SIZE[bin];
#if FANCY_CANARY_CHECK
totalSz += sizeof(uint32_t);
#endif
// Always round up to 16 bytes for alignment (required for SIMD compatibility)
totalSz = alignUp(totalSz, 16);
if (__builtin_expect(slabCurrent_[bin] + totalSz > slabEnd_[bin], 0)) {
char* slab = (char*)allocatePages(SLAB_SIZE);
if (!slab) return nullptr;
slabCurrent_[bin] = slab;
slabEnd_[bin] = slab + SLAB_SIZE;
// Track slab for cleanup
if (slabCount_[bin] < MAX_SLABS_PER_BIN) {
slabs_[bin][slabCount_[bin]++] = slab;
}
}
char* newBlock = slabCurrent_[bin];
slabCurrent_[bin] += totalSz;
auto* hdr = reinterpret_cast<SmallBlockHeader*>(newBlock);
hdr->magic = SMALL_MAGIC;
hdr->binIndex = bin;
hdr->flags = 0;
hdr->userSize = reqSize;
#if FANCY_CANARY_CHECK
hdr->canaryHead = CANARY_VALUE;
#endif
userPtr = newBlock + sizeof(SmallBlockHeader);
#if FANCY_CANARY_CHECK
char* canaryPos = (char*)userPtr + reqSize;
*reinterpret_cast<uint32_t*>(canaryPos) = CANARY_VALUE;
#endif
#if FANCY_STATS_DETAILED
stats.smallBinAllocs[bin].fetch_add(1, std::memory_order_relaxed);
#endif
#if FANCY_STATS_ENABLED
localAllocCalls_++;
localBytesAllocated_ += totalSz;
#endif
return userPtr;
}
__attribute__((always_inline, hot))
void freeSmall(void* userPtr, AllocStats& stats) {
if (__builtin_expect(!userPtr, 0)) return;
char* blockStart = (char*)userPtr - sizeof(SmallBlockHeader);
auto* hdr = reinterpret_cast<SmallBlockHeader*>(blockStart);
// First verify this is actually a small block
if (__builtin_expect(hdr->magic != SMALL_MAGIC, 0)) {
#if FANCY_STATS_DETAILED
stats.corruptedBlocks.fetch_add(1, std::memory_order_relaxed);
#endif
#ifdef FANCY_DEBUG_VERBOSE
fprintf(stderr, "[FANCY] INVALID SMALL BLOCK at %p (bad magic 0x%X)\n", userPtr, hdr->magic);
#endif
return;
}
int bin = (int)hdr->binIndex;
// Safety check - corrupted block
if (__builtin_expect(bin < 0 || bin >= SMALL_BIN_COUNT, 0)) {
#if FANCY_STATS_DETAILED
stats.corruptedBlocks.fetch_add(1, std::memory_order_relaxed);
#endif
#ifdef FANCY_DEBUG_VERBOSE
fprintf(stderr, "[FANCY] CORRUPTED BLOCK at %p (invalid bin %d)\n", userPtr, bin);
#endif
return;
}
#if FANCY_CANARY_CHECK
// Check head canary
if (hdr->canaryHead != CANARY_VALUE) {
#if FANCY_STATS_DETAILED
stats.corruptedBlocks.fetch_add(1, std::memory_order_relaxed);
#endif
#ifdef FANCY_DEBUG_VERBOSE
fprintf(stderr, "[FANCY] HEAD CANARY CORRUPTED at %p (expected 0x%X, got 0x%X)\n",
userPtr, CANARY_VALUE, hdr->canaryHead);
#endif
}
// Check tail canary
char* canaryPos = (char*)userPtr + hdr->userSize;
uint32_t tailCanary = *reinterpret_cast<uint32_t*>(canaryPos);
if (tailCanary != CANARY_VALUE) {
#if FANCY_STATS_DETAILED
stats.bufferOverflows.fetch_add(1, std::memory_order_relaxed);
#endif
#ifdef FANCY_DEBUG_VERBOSE
fprintf(stderr, "[FANCY] BUFFER OVERFLOW at %p (tail canary expected 0x%X, got 0x%X)\n",
userPtr, CANARY_VALUE, tailCanary);
#endif
}
#endif
#if FANCY_DOUBLE_FREE_CHECK
// Check for double-free
if (isRecentlyFreed(userPtr)) {
#if FANCY_STATS_DETAILED
stats.doubleFreeAttempts.fetch_add(1, std::memory_order_relaxed);
#endif
#ifdef FANCY_DEBUG_VERBOSE
fprintf(stderr, "[FANCY] DOUBLE-FREE detected at %p (bin %d)\n", userPtr, bin);
#endif
return; // Don't actually free - prevent corruption
}
trackFreed(userPtr);
#endif
#if FANCY_POISON_CHECK
// Poison freed memory
size_t binSize = SMALL_BIN_SIZE[bin];
uint32_t* poisonStart = reinterpret_cast<uint32_t*>(userPtr);
for (size_t i = 0; i < binSize; i += sizeof(uint32_t)) {
poisonStart[i / sizeof(uint32_t)] = POISON_FREED;
}
#endif
#if FANCY_STATS_DETAILED
stats.smallBinFrees[bin].fetch_add(1, std::memory_order_relaxed);
#endif
// Push to free list - store next ptr in user area
*reinterpret_cast<char**>(blockStart + sizeof(SmallBlockHeader)) = freeList_[bin];
freeList_[bin] = blockStart;
#if FANCY_STATS_ENABLED
// Lightweight stats (batch flush every 1024 ops)
if (__builtin_expect((++localFreeCalls_ & 0x3FF) == 0, 0)) {
localBytesFreed_ += localFreeCalls_ * 32;
flushStats(stats);
}
#endif
}
// Get user-requested size for a small allocation
size_t getSmallAllocSize(void* userPtr) {
if (!userPtr) return 0;
char* blockStart = (char*)userPtr - sizeof(SmallBlockHeader);
auto* hdr = reinterpret_cast<SmallBlockHeader*>(blockStart);
if (hdr->magic != SMALL_MAGIC) return 0;
return hdr->userSize;
}
private:
// Per-bin free list (linked list through user area)
char* freeList_[SMALL_BIN_COUNT];
// Slab allocator for each bin (avoids calling glibc)
char* slabCurrent_[SMALL_BIN_COUNT];
char* slabEnd_[SMALL_BIN_COUNT];
// Track slabs for cleanup on thread exit
char* slabs_[SMALL_BIN_COUNT][MAX_SLABS_PER_BIN];
size_t slabCount_[SMALL_BIN_COUNT];
// Owner allocator slot for cross-thread deallocation
uint16_t ownerSlot_;
// Thread-local stats to avoid atomic contention
size_t localAllocCalls_;
size_t localFreeCalls_;
size_t localBytesAllocated_;
size_t localBytesFreed_;
#if FANCY_DOUBLE_FREE_CHECK
// Circular buffer tracking recently freed pointers
void* freedTracker_[FREED_TRACKER_SIZE];
size_t freedTrackerIdx_;
#endif
};
//-------------------------------------------------------
// 3) Arena for large blocks
// With segregated free lists for O(1) bin lookup
//-------------------------------------------------------
class Arena {
public:
static constexpr uint32_t MAGIC = 0xCAFEBABE;
// Segregated bin sizes for large allocations
static constexpr int LARGE_BIN_COUNT = 16;
static constexpr size_t LARGE_BIN_SIZE[LARGE_BIN_COUNT] = {
1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072,
262144, 524288, 1048576, 2097152, 4194304, 8388608,
16777216, 0xFFFFFFFFFFFFFFFF // Last bin for huge allocations
};
// O(1) bin lookup using CLZ
static int findLargeBin(size_t size) {
if (size <= 1024) return 0;
if (size > 16777216) return LARGE_BIN_COUNT - 1;
// Use leading zeros to find log2 and map to bin
int log2 = 63 - __builtin_clzll(size - 1);
return std::min(std::max(0, log2 - 9), LARGE_BIN_COUNT - 1);
}
// All block structures must be 16-byte aligned for better SIMD compatibility
struct alignas(16) BlockHeader {
uint32_t magic;
uint16_t ownerSlot; // Owner allocator slot (for cross-thread free)
uint16_t alignOffset; // Offset from header end to user ptr
size_t totalSize;
size_t userSize;
bool isFree;
char pad_[7]; // Pad to 16-byte boundary
};
static_assert(sizeof(BlockHeader) == 32, "BlockHeader must be 32 bytes");
static_assert(sizeof(BlockHeader) % 16 == 0, "BlockHeader must be 16-byte aligned");
struct alignas(16) BlockFooter {
uint32_t magic;
uint32_t padding_; // Explicit padding
size_t totalSize;
bool isFree;
char pad_[7]; // Pad to 16-byte boundary
};
static_assert(sizeof(BlockFooter) == 32, "BlockFooter must be 32 bytes");
static_assert(sizeof(BlockFooter) % 16 == 0, "BlockFooter must be 16-byte aligned");
struct alignas(16) FreeBlock {
BlockHeader hdr;
FreeBlock* next;
char pad_[8]; // Pad to 48 bytes (multiple of 16)
};
static_assert(sizeof(FreeBlock) % 16 == 0, "FreeBlock must be 16-byte aligned");
// Helper to round up to alignment (16-byte default for SIMD)
static constexpr size_t ARENA_ALIGNMENT = 16;
static constexpr size_t arenaAlignUp(size_t size) {
return (size + ARENA_ALIGNMENT - 1) & ~(ARENA_ALIGNMENT - 1);
}
Arena(size_t arenaSize)
: arenaSize_(arenaSize), usedBytes_(0)
{
// Use mmap for better performance and huge page support
memory_ = (char*)allocatePages(arenaSize_);
if (!memory_) {
throw std::bad_alloc();
}
// Initialize all bins to nullptr
for (int i = 0; i < LARGE_BIN_COUNT; i++) {
freeBins_[i] = nullptr;
}
auto* fb = reinterpret_cast<FreeBlock*>(memory_);
fb->hdr.magic=MAGIC;
fb->hdr.totalSize=arenaSize_;
fb->hdr.userSize=0;
fb->hdr.isFree=true;
fb->next=nullptr;
auto* foot = getFooter(&fb->hdr);
foot->magic=MAGIC;
foot->totalSize=arenaSize_;
foot->isFree=true;
// Insert into appropriate bin
insertIntoBin(fb);
}
~Arena(){
if(memory_){
freePages(memory_, arenaSize_);
memory_ = nullptr;
}
}
size_t usedBytes() const { return usedBytes_; }
size_t arenaSize() const { return arenaSize_; }
bool fullyFree() const { return usedBytes_ == 0; }
// Get the user-requested size of an allocation (for realloc)
// O(1) lookup using back-offset
size_t getAllocSize(void* userPtr) const {
if (!userPtr) return 0;
char* ptr = (char*)userPtr;
// Fast path: default alignment
auto* hdr = (BlockHeader*)(ptr - sizeof(BlockHeader));
if (hdr->magic == MAGIC && !hdr->isFree && hdr->alignOffset == 0) {
return hdr->userSize;
}
// Non-default alignment: use back-offset
uint16_t backOffset = *reinterpret_cast<const uint16_t*>(ptr - sizeof(uint16_t));
if (backOffset > 0 && backOffset <= MAX_ALIGNMENT) {
hdr = (BlockHeader*)(ptr - sizeof(BlockHeader) - backOffset);
if (hdr->magic == MAGIC && !hdr->isFree && hdr->alignOffset == backOffset) {
return hdr->userSize;
}
}
return 0;
}
// Check if this arena owns the given pointer
bool ownsPointer(void* ptr) const {
return ptr >= memory_ && ptr < memory_ + arenaSize_;
}
// Heap validation - walks all blocks and checks consistency
struct HeapValidationResult {
bool valid;
size_t totalBlocks;
size_t freeBlocks;
size_t usedBlocks;
size_t corruptedBlocks;
size_t totalFreeBytes;
size_t largestFreeBlock;
double fragmentationRatio;
std::vector<const char*> errors;
};
HeapValidationResult validateHeap() const {
HeapValidationResult result = {};
result.valid = true;
char* pos = memory_;
char* end = memory_ + arenaSize_;
size_t totalFree = 0;
size_t largestFree = 0;
while (pos < end) {
auto* hdr = reinterpret_cast<BlockHeader*>(pos);
// Check magic number
if (hdr->magic != MAGIC) {
result.valid = false;
result.corruptedBlocks++;
result.errors.push_back("Invalid magic number in block header");
break; // Can't continue - don't know block size
}
// Check block size sanity
if (hdr->totalSize == 0 || hdr->totalSize > arenaSize_) {
result.valid = false;
result.corruptedBlocks++;
result.errors.push_back("Invalid block size");
break;
}
// Check footer
auto* foot = reinterpret_cast<BlockFooter*>(pos + hdr->totalSize - sizeof(BlockFooter));
if (foot->magic != MAGIC) {
result.valid = false;
result.corruptedBlocks++;
result.errors.push_back("Invalid magic number in block footer");
}
if (foot->totalSize != hdr->totalSize) {
result.valid = false;
result.corruptedBlocks++;
result.errors.push_back("Header/footer size mismatch");
}
if (foot->isFree != hdr->isFree) {
result.valid = false;
result.corruptedBlocks++;
result.errors.push_back("Header/footer free flag mismatch");
}
result.totalBlocks++;
if (hdr->isFree) {
result.freeBlocks++;
totalFree += hdr->totalSize;
if (hdr->totalSize > largestFree) {
largestFree = hdr->totalSize;
}
} else {
result.usedBlocks++;
}
pos += hdr->totalSize;
}
result.totalFreeBytes = totalFree;
result.largestFreeBlock = largestFree;
if (totalFree > 0) {
result.fragmentationRatio = 1.0 - (double)largestFree / (double)totalFree;
} else {
result.fragmentationRatio = 0.0;
}
return result;
}
// Get fragmentation metrics
struct FragmentationMetrics {
size_t totalArenaBytes;
size_t usedBytes;
size_t freeBytes;
size_t freeBlockCount;
size_t largestFreeBlock;
size_t smallestFreeBlock;
double fragmentationRatio; // 0.0 = no fragmentation, 1.0 = fully fragmented
double utilizationRatio; // usedBytes / totalArenaBytes
};
FragmentationMetrics getFragmentation() const {
FragmentationMetrics m = {};
m.totalArenaBytes = arenaSize_;
m.usedBytes = usedBytes_;
m.freeBytes = arenaSize_ - usedBytes_;
m.smallestFreeBlock = SIZE_MAX;
// Walk the free lists
for (int bin = 0; bin < LARGE_BIN_COUNT; bin++) {
FreeBlock* cur = freeBins_[bin];
while (cur) {
m.freeBlockCount++;
if (cur->hdr.totalSize > m.largestFreeBlock) {
m.largestFreeBlock = cur->hdr.totalSize;
}
if (cur->hdr.totalSize < m.smallestFreeBlock) {
m.smallestFreeBlock = cur->hdr.totalSize;
}
cur = cur->next;
}
}
if (m.freeBlockCount == 0) {
m.smallestFreeBlock = 0;
}
if (m.freeBytes > 0 && m.largestFreeBlock > 0) {
m.fragmentationRatio = 1.0 - (double)m.largestFreeBlock / (double)m.freeBytes;
}
m.utilizationRatio = (double)m.usedBytes / (double)m.totalArenaBytes;
return m;
}
void destroy() {
// unmap
if(memory_) {
freePages(memory_, arenaSize_);
memory_=nullptr;
}
}
__attribute__((hot))
void* allocate(size_t reqSize, size_t alignment, AllocStats& stats, uint16_t ownerSlot = 0) {
// No lock needed - each thread has its own Arena
// Ensure alignment is at least ARENA_ALIGNMENT and power of 2
if (alignment < ARENA_ALIGNMENT) alignment = ARENA_ALIGNMENT;
if (!isPowerOfTwo(alignment) || alignment > MAX_ALIGNMENT) {
return nullptr; // Invalid alignment
}
constexpr size_t overhead = sizeof(BlockHeader) + sizeof(BlockFooter);
// Add extra space for alignment padding
const size_t alignPadding = (alignment > ARENA_ALIGNMENT) ? (alignment - 1) : 0;
const size_t totalNeeded = arenaAlignUp(reqSize + overhead + alignPadding);
const int startBin = findLargeBin(totalNeeded);
// Search bins from startBin upward for a fit
for (int bin = startBin; bin < LARGE_BIN_COUNT; bin++) {
FreeBlock* cur = freeBins_[bin];
if (__builtin_expect(cur == nullptr, 0)) continue;
FreeBlock* prev = nullptr;
do {
if (__builtin_expect(cur->hdr.totalSize >= totalNeeded, 1)) {
char* start = (char*)cur;
char* baseUserArea = start + sizeof(BlockHeader);
// Calculate aligned user pointer
char* alignedUserArea = (char*)alignPointer(baseUserArea, alignment);
uint16_t alignOffset = (uint16_t)(alignedUserArea - baseUserArea);
// Adjust needed size to account for actual alignment
size_t actualNeeded = arenaAlignUp(reqSize + overhead + alignOffset);
// Check if block is still large enough after alignment adjustment
if (actualNeeded > cur->hdr.totalSize) {
// This block doesn't fit after alignment, try next
prev = cur;
cur = cur->next;
continue;
}
// Remove from current bin (common: head of list)
if (__builtin_expect(prev == nullptr, 1))
freeBins_[bin] = cur->next;
else
prev->next = cur->next;
// Split if worthwhile - ensure leftover is also aligned
size_t leftover = cur->hdr.totalSize - actualNeeded;
const size_t minSplitSize = arenaAlignUp(sizeof(FreeBlock) + overhead);
if (leftover >= minSplitSize) {
char* leftoverAddr = start + actualNeeded;
auto* leftoverFB = (FreeBlock*)leftoverAddr;
leftoverFB->hdr.magic = MAGIC;
leftoverFB->hdr.totalSize = leftover;
leftoverFB->hdr.userSize = 0;
leftoverFB->hdr.isFree = true;
leftoverFB->hdr.ownerSlot = 0;
leftoverFB->hdr.alignOffset = 0;
leftoverFB->next = nullptr;
auto* leftoverFoot = getFooter(&leftoverFB->hdr);
leftoverFoot->magic = MAGIC;
leftoverFoot->totalSize = leftover;
leftoverFoot->isFree = true;
insertIntoBin(leftoverFB);
} else {
actualNeeded = cur->hdr.totalSize;
}
// Mark allocated with alignment info
cur->hdr.isFree = false;
cur->hdr.userSize = reqSize;
cur->hdr.totalSize = actualNeeded;
cur->hdr.ownerSlot = ownerSlot;
cur->hdr.alignOffset = alignOffset;
// Store back-offset right before user pointer for O(1) header lookup
// Only needed when alignOffset > 0 (non-default alignment)
if (alignOffset > 0) {
uint16_t* backOffset = reinterpret_cast<uint16_t*>(alignedUserArea) - 1;
*backOffset = alignOffset;
}
auto* foot = getFooter(&cur->hdr);
foot->magic = MAGIC;