Repository navigation
Expand file tree
/
Copy patheasy_memory.h
More file actions
5866 lines (5040 loc) · 242 KB
/
Copy patheasy_memory.h
File metadata and controls
5866 lines (5040 loc) · 242 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 EASY_MEMORY_H
#define EASY_MEMORY_H
/*
* Easy Memory Allocator (easy_memory.h)
* A lightweight, platform-agnostic, and safe memory management system for C.
*
* Features:
* - Dynamic and static memory arenas
* - Scoped nested arenas for hierarchical memory management
* - Iterative Left-Leaning Red-Black (LLRB) trees for free-block management
* - Tail-end scratchpad allocations for temporary lifecycle isolation
* - Modular sub-allocators:
* - Bump: O(1) linear allocator with trim and bulk-reset support
* - Slab: O(1) fixed-size block pool using hybrid lazy-bump / free-list
* - Stack: O(1) LIFO allocator on an inverted bi-directional buffer with dynamic metadata scaling
*
* Configurable via macros for safety policies, assertions, and memory poisoning.
* Suitable for embedded systems, game development, and performance-critical applications.
*
* Author: gooderfreed
* License: MIT (see license text below)
*
* ============================================================================
* LICENSE (MIT)
* ============================================================================
* Copyright (c) 2026 gooderfreed
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* ============================================================================
* CONFIGURATION QUICK REFERENCE
* ============================================================================
* Define these macros before including this header to customize behavior.
*
* SAFETY & VERIFICATION:
* #define EM_SAFETY_POLICY <N> // 0: CONTRACT (Design-by-Contract), 1: DEFENSIVE (Fault-Tolerant) [Default]
* #define DEBUG // Enables assertions and auto-enables poisoning
* #define EM_ASSERT_STAYS // Forces assertions to remain active even in Release builds
* #define EM_ASSERT_PANIC // Assertions call abort() (Hardened Release)
* #define EM_ASSERT_OPTIMIZE // Assertions are optimization hints (Danger!)
* #define EM_ASSERT(cond) // Override with custom assertion logic
*
* MEMORY POISONING:
* #define EM_POISONING // Force ENABLE poisoning (even in Release)
* #define EM_NO_POISONING // Force DISABLE poisoning (even in Debug)
* #define EM_POISON_BYTE 0xDD // Custom byte pattern for freed memory
*
* SYSTEM & LINKAGE:
* #define EM_NO_MALLOC // Disable stdlib dependencies (Bare Metal mode)
* #define EM_STATIC // Make all functions static (Private linkage)
* #define EM_RESTRICT // Manual override for 'restrict' keyword definition
* #define EM_NO_ATTRIBUTES // Disable all compiler-specific attributes
*
* TUNING:
* #define EM_MAGIC <value> // Custom magic number for block validation
* #define EM_DEFAULT_ALIGNMENT <value> // Global alignment baseline
* #define EM_MIN_BUFFER_SIZE <value> // Minimum split block size
* ============================================================================
*/
/*
* Configuration: C++ Compatibility Wrapper
* Ensures the header can be included in both C and C++ projects without linkage issues.
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stddef.h>
// Structure type forward declarations
typedef struct Block Block;
typedef struct EM EM;
typedef struct Bump Bump;
typedef struct Slab Slab;
typedef struct Stack Stack;
#ifdef _MSC_VER
#include <intrin.h>
#endif
/*
* Configuration: Static Assertions
*
* Behavior depends on defined macros:
* 1. C11 or C++11 and above:
* Uses standard static_assert.
*
* 2. Pre-C11/C++11:
* Uses a typedef trick to create a compile-time error on failure.
*/
#define EM_CONCAT_INTERNAL(a, b) a##b
#define EM_CONCAT(a, b) EM_CONCAT_INTERNAL(a, b)
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) || defined(__cplusplus)
# include <assert.h>
# define EM_STATIC_ASSERT(cond, msg) static_assert(cond, #msg)
#else
# define EM_STATIC_ASSERT(cond, msg) \
typedef char EM_CONCAT(static_assertion_at_line_, __LINE__)[(cond) ? 1 : -1]
#endif
/*
* Configuration: Architecture Verification
* easy_memory relies heavily on bit-packing, tight alignment math, and standard
* pointer sizes. We must ensure the architecture uses standard 8-bit bytes.
* Exotic architectures (e.g., DSPs with 16-bit bytes) are strictly not supported.
*/
#if defined(__CHAR_BIT__)
# define EM_INTERNAL_CHAR_BIT __CHAR_BIT__
#else
/* Fallback to limits.h if builtins are not available */
# include <limits.h>
# define EM_INTERNAL_CHAR_BIT CHAR_BIT
#endif
EM_STATIC_ASSERT(EM_INTERNAL_CHAR_BIT == 8, "EasyMem requires 8-bit byte architecture");
/*
* Configuration: EMDEF Macro
* Controls the linkage of the Easy Memory functions.
*
* Behavior depends on defined macros:
* 1. EM_STATIC:
* Functions are declared as static, limiting their visibility to the current translation unit.
*
* 2. Default (None of the above):
* Functions are declared as extern, allowing linkage across multiple translation units.
*/
#ifndef EMDEF
# ifdef EM_STATIC
# define EMDEF static
# else
# define EMDEF extern
# endif
#endif
/*
* Configuration: Assertions
*
* Behavior depends on defined macros:
* 1. DEBUG or EM_ASSERT_STAYS:
* Standard C assert(). Aborts and prints file/line on failure.
*
* 2. EM_ASSERT_PANIC:
* Hardened Release. Calls abort() on failure.
* Recommended for security-critical environments to prevent heap exploitation.
*
* 3. EM_ASSERT_OPTIMIZE:
* Performance Release. Uses compiler hints (__builtin_unreachable/__assume).
* WARNING: Invokes Undefined Behavior if the condition is false.
* Use only if you are 100% sure about invariants.
*
* 4. Default (None of the above):
* No-op. Assertions are compiled out completely. Safe and fast.
*/
#ifndef EM_ASSERT
# if defined(DEBUG) || defined(EM_ASSERT_STAYS)
# include <assert.h>
# define EM_ASSERT(cond) assert(cond)
# elif defined(EM_ASSERT_PANIC)
# include <stdlib.h>
# define EM_ASSERT(cond) do { if (!(cond)) abort(); } while(0)
# elif defined(EM_ASSERT_OPTIMIZE)
# if defined(__GNUC__) || defined(__clang__)
# define EM_ASSERT(cond) do { if (!(cond)) __builtin_unreachable(); } while(0)
# elif defined(_MSC_VER)
# define EM_ASSERT(cond) __assume(cond)
# else
# define EM_ASSERT(cond) ((void)0)
# endif
# else
// Default Release: Safe No-op
# define EM_ASSERT(cond) ((void)0)
# endif
#endif
/*
* Configuration: EM_RESTRICT Macro
* Defines the restrict qualifier for pointer parameters to indicate non-aliasing.
*
* Behavior depends on defined macros:
* 1. C99 or C++ (with compiler support):
* Uses standard restrict or compiler-specific equivalents.
*
* 2. Pre-C99/C++ (without compiler support):
* Defined as empty, effectively disabling the restrict qualifier.
*/
#ifndef EM_RESTRICT
# if defined(__cplusplus)
# if defined(_MSC_VER)
# define EM_RESTRICT __restrict
# elif defined(__GNUC__) || defined(__clang__)
# define EM_RESTRICT __restrict__
# else
# define EM_RESTRICT
# endif
# elif defined(_MSC_VER)
# define EM_RESTRICT __restrict
# elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
# define EM_RESTRICT restrict
# else
# define EM_RESTRICT
# endif
#endif
/*
* Configuration: Safety Policies
*
* Defines the methodology for handling invariant violations and API misuse.
* This allows the developer to choose how the library responds to errors.
*
* EM_POLICY_CONTRACT (0):
* - Philosophy: Post-conditions and invariants are treated as a contract.
* - Behavior: Checks are delegated to the EM_ASSERT mechanism.
* - Outcome: The final behavior (whether checks are compiled out, lead to a panic,
* or stay in release via EM_ASSERT_STAYS) is determined entirely by the
* configured Assertion Strategy.
* - Best for: Fine-grained control over debugging and performance.
*
* EM_POLICY_DEFENSIVE (1) [DEFAULT]:
* - Philosophy: Runtime resilience and fault-tolerance.
* - Behavior: Performs explicit 'if' checks in both Debug and Release.
* - Outcome: Gracefully returns NULL or exits the function on violation.
* - Best for: Production environments where the program must survive misuse
* without hard crashes.
*/
#define EM_POLICY_CONTRACT 0
#define EM_POLICY_DEFENSIVE 1
#ifndef EM_SAFETY_POLICY
# define EM_SAFETY_POLICY EM_POLICY_DEFENSIVE
#endif
/*
* Internal Safety Macros
*
* EM_CHECK - Used in functions returning values (e.g., pointers, size_t).
* EM_CHECK_V - Used in void functions (e.g., em_free, em_destroy).
*
* These macros adapt to the chosen EM_SAFETY_POLICY, providing either
* a fail-fast assertion or a graceful runtime exit.
*/
#if EM_SAFETY_POLICY == EM_POLICY_CONTRACT
# define EM_CHECK(cond, ret, msg) EM_ASSERT((cond) && msg)
# define EM_CHECK_V(cond, msg) EM_ASSERT((cond) && msg)
#else
# define EM_CHECK(cond, ret, msg) do { if (!(cond)) return (ret); } while(0)
# define EM_CHECK_V(cond, msg) do { if (!(cond)) return; } while(0)
#endif
/*
* Configuration: Force Disable Attributes
* Disables all compiler-specific attributes, regardless of compiler support.
*
*/
#ifndef EM_NO_ATTRIBUTES
# if defined(EASY_MEMORY_IMPLEMENTATION) && defined(EM_STATIC)
# define EM_NO_ATTRIBUTES
# endif
#endif
/*
* Configuration: Compiler Attributes
* Adds compiler-specific attributes to functions for optimization and correctness hints.
*
* Behavior depends on defined macros:
* 1. EM_NO_ATTRIBUTES:
* Disables all attributes, regardless of compiler support.
*
* 2. GCC or Clang:
* Uses __attribute__ syntax. Takes index arguments, ignores name arguments.
*
* 3. MSVC:
* Uses __declspec and SAL annotations. Takes name arguments, ignores index arguments.
* Requires <sal.h>.
*
* 4. Other Compilers:
* Attributes are defined as empty.
*/
#if defined(_MSC_VER)
# include <sal.h>
#endif
#if defined(EM_NO_ATTRIBUTES)
# define EM_ATTR_MALLOC
# define EM_ATTR_WARN_UNUSED
# define EM_ATTR_ALLOC_SIZE(idx, name)
# define EM_ATTR_ALLOC_SIZE2(idx1, idx2, name1, name2)
#elif defined(__GNUC__) || defined(__clang__)
// GCC / Clang
# define EM_ATTR_MALLOC __attribute__((malloc))
# define EM_ATTR_WARN_UNUSED __attribute__((warn_unused_result))
// GCC uses argument INDICES (1-based)
# define EM_ATTR_ALLOC_SIZE(idx, name) __attribute__((alloc_size(idx)))
# define EM_ATTR_ALLOC_SIZE2(idx1, idx2, name1, name2) __attribute__((alloc_size(idx1, idx2)))
#elif defined(_MSC_VER)
// MSVC (Windows)
# define EM_ATTR_MALLOC __declspec(restrict) _Ret_maybenull_
# define EM_ATTR_WARN_UNUSED _Check_return_
// MSVC uses argument NAMES.
// We use _Post_writable_byte_size_ to tell static analysis how much memory is valid.
# define EM_ATTR_ALLOC_SIZE(idx, name) _Post_writable_byte_size_(name)
// For calloc-like logic, we can multiply names directly in SAL
# define EM_ATTR_ALLOC_SIZE2(idx1, idx2, name1, name2) _Post_writable_byte_size_((name1) * (name2))
#else
// Unknown Compiler
# define EM_ATTR_MALLOC
# define EM_ATTR_WARN_UNUSED
# define EM_ATTR_ALLOC_SIZE(idx, name)
# define EM_ATTR_ALLOC_SIZE2(idx1, idx2, name1, name2)
#endif
/*
* Configuration: Memory Poisoning
* Helps detect use-after-free and memory corruption bugs by filling freed memory with a known pattern.
*
* Behavior depends on defined macros:
* 1. EM_NO_POISONING:
* Disables all poisoning features, regardless of build type.
*
* 2. DEBUG (without EM_NO_POISONING):
* Enables poisoning in debug builds for maximum safety.
*
* 3. Default (Release without EM_NO_POISONING):
* Disables poisoning to maximize performance.
*/
#ifdef EM_NO_POISONING
# if defined(EM_POISONING)
# undef EM_POISONING
# endif
#elif defined(DEBUG) && !defined(EM_POISONING)
# define EM_POISONING
#endif
/*
* Configuration: Poison Byte
* Byte value used to fill freed memory when poisoning is enabled.
* Default is 0xDD, but can be customized by defining EM_POISON_BYTE before including this header.
*/
#ifndef EM_POISON_BYTE
# define EM_POISON_BYTE 0xDD
#endif
EM_STATIC_ASSERT((EM_POISON_BYTE >= 0x00) && (EM_POISON_BYTE <= 0xFF), "EM_POISON_BYTE must be a valid byte value (0x00 to 0xFF).");
/*
* Configuration: Minimum Buffer Size
* Defines the minimum size of the usable memory buffer within a block.
* This prevents creation of useless zero-sized free blocks.
* Default is 2 * sizeof(uintptr_t) bytes(2 words) to prevent creating blocks
* where useful data significantly smaller than the header(4 words).
* Can be customized by defining EM_MIN_BUFFER_SIZE before including this header.
*/
#ifndef EM_MIN_BUFFER_SIZE
# define EM_MIN_BUFFER_SIZE (2 * sizeof(uintptr_t))
#endif
EM_STATIC_ASSERT(EM_MIN_BUFFER_SIZE > 0, "MIN_BUFFER_SIZE must be a positive value to prevent creation of useless zero-sized free blocks.");
/*
* Configuration: Magic Number
* Unique identifier used to validate memory blocks and detect corruption.
* Default values are chosen based on pointer size to ensure uniqueness.
* Can be customized by defining EM_MAGIC before including this header.
*/
#ifndef EM_MAGIC
# if UINTPTR_MAX > 0xFFFFFFFFUL
# define EM_MAGIC 0xDEADBEEFDEADBEEFULL
# elif UINTPTR_MAX > 0xFFFFU
# define EM_MAGIC 0xDEADBEEFUL
# else
# define EM_MAGIC 0xBEEFU
# endif
#endif
EM_STATIC_ASSERT((EM_MAGIC != 0), "EM_MAGIC must be a non-zero value to ensure effective block validation.");
/*
* Constant: Minimum Exponent
* Used to calculate minimum and maximum alignment limits based on pointer size.
* For test compatibility with 16-bit systems, we force EMMIN_EXPONENT to be at least 2,
* so all the bits shinanigans with alignment encoding in capacity_and_alignment and other fields work properly.
* But it also means that on 16-bit systems, some part of memory will be wasted due to alignment requirements.
*/
#if defined(__GNUC__) || defined(__clang__)
# define EMMIN_EXPONENT (__builtin_ctz(sizeof(uintptr_t)))
#else
# define EMMIN_EXPONENT ( \
(sizeof(uintptr_t) == 2) ? 2 : \
(sizeof(uintptr_t) == 4) ? 2 : \
(sizeof(uintptr_t) == 8) ? 3 : \
4 \
)
#endif
/*
* Constant: Maximum Alignment Limit
* Maximum alignment is 512 on 32-bit systems and 1024 on 64-bit systems.
*/
#define EMMAX_ALIGNMENT ((size_t)(256 << EMMIN_EXPONENT))
/*
* Constant: Minimum Alignment Limit
* Minimum alignment is based on the size of uintptr_t.
*/
#define EMMIN_ALIGNMENT ((size_t)sizeof(uintptr_t))
/*
* Configuration: Default Alignment
* Defines the default memory alignment for the easy memory allocator.
* Default is 16 bytes, but can be customized by defining EM_DEFAULT_ALIGNMENT before including this header.
*/
#ifndef EM_DEFAULT_ALIGNMENT
# define EM_DEFAULT_ALIGNMENT 16
#endif
EM_STATIC_ASSERT((EM_DEFAULT_ALIGNMENT & (EM_DEFAULT_ALIGNMENT - 1)) == 0, "EM_DEFAULT_ALIGNMENT must be a power of two.");
EM_STATIC_ASSERT(EM_DEFAULT_ALIGNMENT >= EMMIN_ALIGNMENT, "EM_DEFAULT_ALIGNMENT must be at least EMMIN_ALIGNMENT.");
EM_STATIC_ASSERT(EM_DEFAULT_ALIGNMENT <= EMMAX_ALIGNMENT, "EM_DEFAULT_ALIGNMENT must be at most EMMAX_ALIGNMENT.");
/*
* Constant: Maximum LLRB Tree Height
* Defines the exact, mathematical maximum stack depth required for iterative
* tree traversal algorithms (insertion, deletion) to prevent recursion.
*
* Rationale:
* Since this allocator targets environments ranging from 64-bit servers down to
* 16-bit bare-metal microcontrollers, using a static "safe" stack array (e.g.,
* 128 elements) is unacceptable. It wastes RAM on MCUs and risks stack overflows.
* We must compute the strict minimum required depth at compile-time.
*
* Mathematical Limits:
* 1. Max Capacity Limit: 2^(WORD_BITS - 3) bytes (due to 3 reserved bits in EM header).
* 2. Min Block Size: 6 machine words (4 words EM header + 2 words minimum buffer).
* 3. Max Nodes (N): Max Capacity / Min Block Size (worst-case fragmentation scenario).
* 4. Max LLRB Depth (H): Structurally guaranteed to be H <= 2 * log2(N + 1).
*
* Calculated worst-case boundaries:
* -- 64-bit (Word: 8B, Min Block: 48B): Max N ≈ 2^55.4 -> Max H = 111
* -- 32-bit (Word: 4B, Min Block: 24B): Max N ≈ 2^24.4 -> Max H = 49
* -- 16-bit (Word: 2B, Min Block: 12B): Max N ≈ 2^9.4 -> Max H = 19
*
* Deriving the Formula:
* The true depth formula expands to: H = 2 * (WORD_BITS - 3 - log2(6 * WORD_BYTES)).
* Since log2() cannot be used in the preprocessor, we approximate this curve:
*
* a) The "-12" baseline offset (derived from WORD_BITS - 6):
* We lose exactly 3 bits of representable space to the header capacity flags.
* We "lose" another ~2.58 bits because the smallest node requires 6 words of
* space (log2(6) ≈ 2.58). Rounding 2.58 up to 3 means we effectively subtract
* 6 bits from WORD_BITS. Multiplying by the LLRB height factor of 2 gives us
* the flat baseline reduction of -12.
*
* b) The architecture divergence (-0.5 multiplier):
* The remaining log2(WORD_BYTES) part causes the depth to diverge slightly across
* architectures. To linearize this without complex math, we reduce the base
* word multiplier from 16 to 15.5.
*
* Final linear approximation: (15.5 * sizeof(void*)) - 12
* Expressed as integer math: ((31 * sizeof(void*)) / 2) - 12
*
* Bounds Verification:
* -- 64-bit (8B): (31 * 8) / 2 - 12 = 112 (Safely covers 111, +1 safety margin)
* -- 32-bit (4B): (31 * 4) / 2 - 12 = 50 (Safely covers 49, +1 safety margin)
* -- 16-bit (2B): (31 * 2) / 2 - 12 = 19 (Exactly covers 19, zero wasted space)
*/
#define EM_MAX_TREE_HEIGHT (((31 * sizeof(Block*)) / 2) - 12)
/*
* Constant: Alignment Mask
* Mask to extract alignment bits from capacity_and_alignment field.
*/
#define EMALIGNMENT_MASK ((uintptr_t)7)
/*
* Constant: Capacity Mask
* Mask to extract capacity bits from capacity_and_alignment field.
*/
#define EMCAPACITY_MASK (~(uintptr_t)7)
/*
* Constant: Reserved Mask
* Mask to extract all reserved bits from size_and_reserved field.
*/
#define EMALL_RESERVED_MASK ((uintptr_t)31)
/*
* Constant: Size Mask
* Mask to extract size bits from size_and_reserved field.
*/
#define EMSIZE_MASK (~EMALL_RESERVED_MASK)
/*
* Constant: Alignment Shift
* Number of bits to shift to encode/decode alignment in size_and_reserved field.
*/
#define EMALIGNMENT_SHIFT 3
/*
* Constant: Reserved Shift
* Number of bits reserved for future use in size_and_reserved field.
* Currently reserved for potential sub-allocator metadata (e.g., Slab allocator).
*/
#define EMRESERVED_SHIFT 2
/*
* Constant: Total Reserved Shift
* Total number of bits reserved in size_and_reserved field (alignment + reserved).
*/
#define EMALL_RESERVED_SHIFT (EMALIGNMENT_SHIFT + EMRESERVED_SHIFT)
/*
* Constant: IS_FREE Mask
* Mask to check if a block is free.
*/
#define EMIS_FREE_FLAG ((uintptr_t)1)
/*
* Constant: COLOR Mask
* Mask to check the color of a block in the red-black tree.
*/
#define EMCOLOR_FLAG ((uintptr_t)2)
/*
* Constant: Previous Block Mask
* Mask to extract the previous block pointer from prev field.
*/
#define EMPREV_MASK (~(uintptr_t)3)
/*
* Constant: Is Dynamic Mask
* Mask to check if the EM is dynamically allocated.
*/
#define EMIS_DYNAMIC_FLAG ((uintptr_t)1)
/*
* Constant: Is Nested Mask
* Mask to check if the EM is a nested EM.
*/
#define EMIS_NESTED_FLAG ((uintptr_t)2)
/*
* Constant: Tail Block Mask
* Mask to extract the tail block pointer from tail field.
*/
#define EMTAIL_MASK (~(uintptr_t)3)
/*
* Constant: Padding Mask
* Mask used to ensure Zero in least significant bit of `free_blocks` pointer.
* Needed for `Magic LSB Padding Detector` trick to work properly.
* For more info, see comment in `em_create_static_aligned` function.
*/
#define EMIS_PADDING ((uintptr_t)1)
/*
* Constant: Has Scratch Mask
* Mask to check if the EM scratchpad slot currently in use.
*/
#define EMHAS_SCRATCH_FLAG ((uintptr_t)2)
/*
* Constant: Free Blocks Mask
* Mask to extract the free blocks tree pointer from free_blocks field.
*/
#define EMFREE_BLOCKS_MASK (~(uintptr_t)3)
/*
* Constant: Slab Chunk Low Mask
* Mask to extract the lower 5 bits of the chunk size from capacity_and_chunk_low field.
*/
#define EMSLAB_CHUNK_LOW_MASK ((size_t)31)
/*
* Constant: Slab Chunk High Mask
* Mask to extract the upper 3 bits of the chunk size from free_index_and_chunk_high field.
*/
#define EMSLAB_CHUNK_HIGH_MASK ((uintptr_t)7)
/*
* Constant: Slab Index Shift
* Number of bits to shift to encode/decode the free index in free_index_and_chunk_high field.
*/
#define EMSLAB_INDEX_SHIFT 3
/*
* Constant: Slab Index Mask
* Mask to extract the free index bits from free_index_and_chunk_high field.
*/
#define EMSLAB_INDEX_MASK (~EMSLAB_CHUNK_HIGH_MASK)
/*
* Constant: Slab Chunk High Shift
* Number of bits to shift the upper part of chunk size when assembling the raw size.
*/
#define EMSLAB_CHUNK_HIGH_ASSEMBLY_SHIFT 5
/*
* Constant: Stack Meta Mask
* Mask to extract/set the 2-bit metadata type from capacity_and_meta_size field.
* 0: uint8_t, 1: uint16_t, 2: uint32_t, 3: uint64_t
*/
#define EM_STACK_META_MASK ((uintptr_t)3)
/*
* Constant: EM Color Definitions
* Defines the color values for blocks in the red-black tree.
*/
#define EMRED false
#define EMBLACK true
/*
* Constant: Minimum Block Size
* The minimum size required to create a valid EM instance.
*/
#define EMBLOCK_MIN_SIZE (sizeof(Block) + EM_MIN_BUFFER_SIZE)
/*
* Constant: Minimum EM Size
* The minimum size required to create a valid EM instance.
*/
#define EMMIN_SIZE (sizeof(EM) + EMBLOCK_MIN_SIZE)
/*
* Constant: Maximum EM Size
* The maximum size allowed for an EM instance to prevent overflow issues.
*/
#define EMMAX_SIZE (SIZE_MAX >> 3)
/*
* Macro: Block Data Pointer
* Calculates the pointer to the usable data area of a block.
*/
#define block_data(block) ((void *)((uintptr_t)(block) + sizeof(Block)))
/* ==============================================================================================
* MEMORY LAYOUT: Block Metadata
* ==============================================================================================
* The Block structure is the fundamental unit of memory management. It utilizes aggressive
* bit-packing and pointer tagging to maintain a minimal footprint (4 machine words).
*
* [ WORD 0: size_and_reserved ] -> 64/32/16 bits (size_t)
* ┌────────────────────────────────────────────────────────────────────────┬─────────────────┐
* │ Size │ Reserved │
* │ [63/31/15 ....................................................... 5] │ [4 .. 0] │
* └────────────────────────────────────────────────────────────────────────┴─────────────────┘
* - Reserved (5 bits):
* These 5 lowest bits are the secret sauce of ABI compatibility.
* Their meaning strictly depends on WHAT this "Block" actually is:
*
* ► IF IT'S A STANDARD BLOCK (Payload wrapper):
* These 5 bits are ALWAYS ZERO (0b00000).
* - Bits [4..3]: Zero due to internal size rounding (always a multiple of 4).
* - Bits [2..0]: Zero because individual blocks DO NOT store their own alignment
* metadata (alignment is resolved dynamically via padding/addresses).
* *Note: These 5 guaranteed zero bits are reserved for future sub-allocators (e.g. Slab).*
*
* ► IF IT'S AN ARENA HEADER (Nested EM / Root EM masquerading as a Block):
* - Bits [4..3]: Still Zero (arena capacity is also rounded).
* - Bits [2..0]: Store the Arena's Baseline Alignment Exponent.
* True alignment = 2^(EMMIN_EXPONENT + Alignment).
*
* - Size (N bits): Usable payload size of the block in bytes (shifted left by 3).
*
* [ WORD 1: prev ] -> 64/32/16 bits (Block pointer) - POINTER TAGGING ENABLED
* ┌───────────────────────────────────────────────────────────────────┬──────────┬───────────┐
* │ Previous Block Address │ Color │ Is Free │
* │ │ (LLRB) │ │
* │ [63/31/15 .................................................. 2] │ [1] │ [0] │
* └───────────────────────────────────────────────────────────────────┴──────────┴───────────┘
* - Is Free (Bit 0): 1 if the block is currently FREE, 0 if OCCUPIED.
* - Color (Bit 1): 1 if BLACK, 0 if RED. Used for LLRB tree balancing AND Scratchpad detection.
* - Address: Pointer to the physically preceding Block in memory (masked with ~3).
*
* [ WORD 2 & 3: union as ] -> 2 Machine Words - CONTEXT DEPENDENT
* ┌──────────────────────────────────────────────────────────────────────────────────────────┐
* │ IF FREE (as.free): │
* │ ┌────────────────────────────────────────┐ ┌───────────────────────────────────────────┐ │
* │ │ Block *left_free (LLRB Left Child) │ │ Block *right_free (LLRB Right Child) │ │
* │ │ [63/31/15 ....................... 3] │ │ [63/31/15 .......................... 3] │ │
* │ └────────────────────────────────────────┘ └───────────────────────────────────────────┘ │
* ├──────────────────────────────────────────────────────────────────────────────────────────┤
* │ IF OCCUPIED (as.occupied): │
* │ ┌────────────────────────────────────────┐ ┌───────────────────────────────────────────┐ │
* │ │ EM *em (Pointer to Owning Arena) │ │ uintptr_t magic (XORed with Payload Ptr) │ │
* │ │ [63/31/15 ....................... 3] │ │ [63/31/15 .......................... 3] │ │
* │ └────────────────────────────────────────┘ └───────────────────────────────────────────┘ │
* └──────────────────────────────────────────────────────────────────────────────────────────┘
* ==============================================================================================
*
* [63/31/15 ......................................................... 3]
*/
struct Block {
size_t size_and_reserved; // Packed: [Size][Reserved:5]
Block *prev; // Tagged: [Physical Prev Ptr][Color:1][Is_Free:1]
union {
struct {
Block *left_free; // LLRB-Tree left child (Valid only if Is_Free == 1)
Block *right_free; // LLRB-Tree right child (Valid only if Is_Free == 1)
} free;
struct {
EM *em; // Parent Arena pointer (Valid only if Is_Free == 0)
uintptr_t magic; // XOR payload validation (Valid only if Is_Free == 0)
} occupied;
} as;
};
/* ==============================================================================================
* MEMORY LAYOUT: Easy Memory (EM) Header (ABI Compatible with Block)
* ==============================================================================================
* The EM structure acts as the root allocator context. Crucially, it is strictly ABI-compatible
* with the 'Block' structure. This allows nested EM instances to masquerade as standard occupied
* blocks to their parent arena, achieving zero-cost parent tracking.
*
* [ WORD 0: as.self.capacity_and_alignment ] -> Maps to Block.size_and_reserved
* ┌──────────────────────────────────────────────────────────────────────────┬───────────────┐
* │ Total Capacity │ Base Alignmnt │
* │ [63/31/15 ......................................................... 3] │ [2..0] │
* └──────────────────────────────────────────────────────────────────────────┴───────────────┘
* - Alignment (3 bits): Exponent offset. True alignment = 2^(EMMIN_EXPONENT + Alignment).
* - Capacity (N bits): Total usable payload capacity of the arena (shifted left by 3).
* Note: Unlike Block.size, bits [4..3] are NOT reserved here.
*
* [ WORD 1: as.self.prev ] -> Maps to Block.prev
* ┌──────────────────────────────────────────────────────────────────────────────────────────┐
* │ Previous Block Address (Physical Neighbor) │
* │ [63/31/15 ......................................................................... 0] │
* └──────────────────────────────────────────────────────────────────────────────────────────┘
* - Address: Pointer to the physically preceding Block (if this EM is nested/scratch).
* For root arenas (dynamic or static top-level), this is NULL.
*
* [ WORD 2: as.self.tail ] -> Maps to Block.as.occupied.em (POINTER TAGGING ENABLED)
* ┌───────────────────────────────────────────────────────────────────────┬────────┬─────────┐
* │ Tail Block Address │ Is │ Is │
* │ │ Nested │ Dynamic │
* │ [63/31/15 ...................................................... 2] │ [1] │ [0] │
* └───────────────────────────────────────────────────────────────────────┴────────┴─────────┘
* - Is Dynamic (Bit 0): 1 if EM was allocated via system malloc() (needs system free()).
* - Is Nested (Bit 1): 1 if EM was carved out of a parent EM instance.
* - Tail Address: Pointer to the last logical block in the active arena space.
*
* [ WORD 3: as.self.free_blocks ] -> Maps to Block.as.occupied.magic (POINTER TAGGING ENABLED)
* ┌────────────────────────────────────────────────────────────────────────┬─────────┬───────┐
* │ LLRB Tree Root Address (Free Blocks) │ Has │ Magic │
* │ │ Scratch │ Zero │
* │ [63/31/15 ....................................................... 2] │ [1] │ [0] │
* └────────────────────────────────────────────────────────────────────────┴─────────┴───────┘
* - Magic Zero (Bit 0): ALWAYS 0. Critical for the 'Magic LSB Padding Detector' logic to
* distinguish this pointer from a padding offset (which ends in 1).
* - Has Scratch (Bit 1): 1 if the extreme tail block is currently reserved as a Scratchpad.
* - Root Address: Pointer to the root node of the free blocks LLRB tree.
* ==============================================================================================
*/
struct EM {
union {
Block block_representation; // Standard ABI compatibility layer
struct {
size_t capacity_and_alignment; // Packed: [Capacity][Alignment:3]
Block *prev; // Physical Prev Ptr (NULL if root arena)
Block *tail; // Tagged: [Tail Ptr][Is_Nested:1][Is_Dynamic:1]
Block *free_blocks; // Tagged: [LLRB Root Ptr][Has_Scratch:1][Magic_Zero:1]
} self;
} as;
};
EM_STATIC_ASSERT(offsetof(EM, as.self.capacity_and_alignment) == offsetof(Block, size_and_reserved),
EM_capacity_offset_mismatch);
EM_STATIC_ASSERT(offsetof(EM, as.self.prev) == offsetof(Block, prev),
EM_prev_offset_mismatch);
EM_STATIC_ASSERT(offsetof(EM, as.self.tail) == offsetof(Block, as.occupied.em),
EM_tail_offset_mismatch);
EM_STATIC_ASSERT((sizeof(EM) == sizeof(Block)), Size_mismatch_between_Bump_and_Block);
/* ==============================================================================================
* MEMORY LAYOUT: Bump Allocator Header (ABI Compatible with Block)
* ==============================================================================================
* The Bump allocator is a lightning-fast, linear memory pool. Like the EM header, it is
* strictly ABI-compatible with the 'Block' structure. To the parent arena, a Bump instance
* is indistinguishable from a standard occupied memory block.
*
* [ WORD 0: as.self.capacity ] -> Maps to Block.size_and_reserved
* ┌─────────────────────────────────────────────────────────────────────────────┬────────────┐
* │ Capacity │ Reserved │
* │ [63/31/15 ............................................................ 5] │ [4..0] │
* └─────────────────────────────────────────────────────────────────────────────┴────────────┘
* - Reserved (5 bits): Always 0. Because a Bump allocator is allocated from the parent arena
* as a standard block, its total size is inherently rounded to a multiple
* of 4, guaranteeing these bits remain empty.
* - Capacity (N bits): Total payload capacity carved out from the parent (shifted left by 3).
*
* [ WORD 1: as.self.prev ] -> Maps to Block.prev
* ┌──────────────────────────────────────────────────────────────────────────────────────────┐
* │ Previous Block Address (Physical Neighbor) │
* │ [63/31/15 ......................................................................... 0] │
* └──────────────────────────────────────────────────────────────────────────────────────────┘
* - Address: Pointer to the physically preceding Block (if any).
* Essential for O(1) merging when the Bump allocator is destroyed.
*
* [ WORD 2: as.self.em ] -> Maps to Block.as.occupied.em (NO POINTER TAGGING NEEDED)
* ┌──────────────────────────────────────────────────────────────────────────────────────────┐
* │ Parent EM Address │
* │ [63/31/15 ......................................................................... 0] │
* └──────────────────────────────────────────────────────────────────────────────────────────┘
* - Parent Addr: Direct pointer to the Easy Memory instance that created this Bump allocator.
*
* [ WORD 3: as.self.offset ] -> Maps to Block.as.occupied.magic (OFFSET TRACKING)
* ┌──────────────────────────────────────────────────────────────────────────────────────────┐
* │ Current Allocation Offset │
* │ [63/31/15 ......................................................................... 0] │
* └──────────────────────────────────────────────────────────────────────────────────────────┘
* - Offset: Byte offset from the start of the Bump header to the next available free byte.
* Initialized to sizeof(Bump) (4 machine words).
* Advances linearly with every allocation.
* ==============================================================================================
*/
struct Bump {
union {
Block block_representation; // Standard ABI compatibility layer
struct {
size_t capacity; // Packed: [Capacity][Reserved:5] (Always 0 alignment bits)
Block *prev; // Physical Prev Ptr for merging
EM *em; // Direct Parent Pointer (O(1) access)
size_t offset; // Linear allocation cursor
} self;
} as;
};
EM_STATIC_ASSERT(offsetof(Bump, as.self.capacity) == offsetof(Block, size_and_reserved),
Bump_capacity_offset_mismatch);
EM_STATIC_ASSERT(offsetof(Bump, as.self.prev) == offsetof(Block, prev),
Bump_prev_offset_mismatch);
EM_STATIC_ASSERT(offsetof(Bump, as.self.em) == offsetof(Block, as.occupied.em),
Bump_em_offset_mismatch);
EM_STATIC_ASSERT((sizeof(Bump) == sizeof(Block)), Size_mismatch_between_Bump_and_Block);
/* ==============================================================================================
* MEMORY LAYOUT: Slab Allocator Header (ABI Compatible with Block)
* ==============================================================================================
* The Slab allocator provides a highly efficient fixed-size block pool. Like the EM and Bump
* headers, it is strictly ABI-compatible with the 'Block' structure, masquerading as a
* standard occupied block to its parent arena.
*
* [ WORD 0: as.self.capacity_and_chunk_low ] -> Maps to Block.size_and_reserved
* ┌─────────────────────────────────────────────────────────────────────────────┬────────────┐
* │ Capacity │ Chunk Low │
* │ [63/31/15 ............................................................ 5] │ [4..0] │
* └─────────────────────────────────────────────────────────────────────────────┴────────────┘
* - Chunk Low (5 bits): The lower 5 bits of the 8-bit compressed chunk size representation.
* - Capacity (N bits): Total payload capacity carved out from the parent (shifted left by 5).
*
* [ WORD 1: as.self.prev ] -> Maps to Block.prev
* ┌──────────────────────────────────────────────────────────────────────────────────────────┐
* │ Previous Block Address (Physical Neighbor) │
* │ [63/31/15 ......................................................................... 0] │
* └──────────────────────────────────────────────────────────────────────────────────────────┘
* - Address: Pointer to the physically preceding Block (if any).
* Essential for O(1) merging when the Slab allocator is destroyed.
*
* [ WORD 2: as.self.em ] -> Maps to Block.as.occupied.em (NO POINTER TAGGING NEEDED)
* ┌──────────────────────────────────────────────────────────────────────────────────────────┐
* │ Parent EM Address │
* │ [63/31/15 ......................................................................... 0] │
* └──────────────────────────────────────────────────────────────────────────────────────────┘
* - Parent Addr: Direct pointer to the Easy Memory instance that created this Slab allocator.
*
* [ WORD 3: as.self.free_index_and_chunk_high ] -> Maps to Block.as.occupied.magic
* ┌─────────────────────────────────────────────────────────────────────────────┬────────────┐
* │ Free Index │ Chunk High │
* │ [63/31/15 ............................................................ 3] │ [2..0] │
* └─────────────────────────────────────────────────────────────────────────────┴────────────┘
* - Chunk High (3 bits): The upper 3 bits of the 8-bit compressed chunk size.
* Raw Size = (Chunk High << 5) | Chunk Low.
* Actual Byte Size = (Raw Size + 1) << EMMIN_EXPONENT.
* - Free Index (N bits): A 1-based cursor driving the hybrid Bump/Free-List state machine.
* - Value `0` acts as a FULL marker (no memory available).
* - The Slab avoids O(N) zeroing on creation by utilizing a self-referential
* index logic: if a chunk contains its own index, it acts as the
* uninitialized Bump frontier. Otherwise, it acts as a Free-List node.
* ==============================================================================================
*/
struct Slab {
union {
Block block_representation;
struct {
size_t capacity_and_chunk_low;
Block *prev;
EM *em;
uintptr_t free_index_and_chunk_high;
} self;
} as;
};
EM_STATIC_ASSERT(offsetof(Slab, as.self.capacity_and_chunk_low) == offsetof(Block, size_and_reserved),
Slab_capacity_offset_mismatch);
EM_STATIC_ASSERT(offsetof(Slab, as.self.prev) == offsetof(Block, prev),
Slab_prev_offset_mismatch);
EM_STATIC_ASSERT(offsetof(Slab, as.self.em) == offsetof(Block, as.occupied.em),
Slab_em_offset_mismatch);
EM_STATIC_ASSERT(offsetof(Slab, as.self.free_index_and_chunk_high) == offsetof(Block, as.occupied.magic),
Slab_magic_offset_mismatch);
EM_STATIC_ASSERT((sizeof(Slab) == sizeof(Block)), Size_mismatch_between_Slab_and_Block);
/* ==============================================================================================
* MEMORY LAYOUT: Stack Allocator Header (ABI Compatible with Block)
* ==============================================================================================
* The Stack allocator provides a highly efficient bi-directional LIFO stack. Like the EM and
* Slab headers, it is strictly ABI-compatible with the 'Block' structure, masquerading as a
* standard occupied block to its parent arena.
*
* [ WORD 0: as.self.capacity_and_meta_size ] -> Maps to Block.size_and_reserved
* ┌─────────────────────────────────────────────────────────────────────────────┬────────────┐
* │ Capacity │ Meta Type │
* │ [63/31/15 ............................................................ 5] │ [4..0] │
* └─────────────────────────────────────────────────────────────────────────────┴────────────┘
* - Meta Type (2 bits used of 5): The 2 lowest bits store the 2-bit compressed metadata size.
* - Value `0`: uint8_t offsets (capacity < 256 B)
* - Value `1`: uint16_t offsets (capacity < 64 KB)
* - Value `2`: uint32_t offsets (capacity < 4 GB)
* - Value `3`: uint64_t offsets (capacity >= 4 GB)
* - Capacity (N bits): Total payload capacity carved out from the parent (shifted left by 5).
*
* [ WORD 1: as.self.prev ] -> Maps to Block.prev
* ┌──────────────────────────────────────────────────────────────────────────────────────────┐
* │ Previous Block Address (Physical Neighbor) │
* │ [63/31/15 ......................................................................... 0] │
* └──────────────────────────────────────────────────────────────────────────────────────────┘
* - Address: Pointer to the physically preceding Block (if any).
* Essential for O(1) merging when the Stack allocator is destroyed.
*
* [ WORD 2: as.self.em ] -> Maps to Block.as.occupied.em (NO POINTER TAGGING NEEDED)
* ┌──────────────────────────────────────────────────────────────────────────────────────────┐
* │ Parent EM Address │
* │ [63/31/15 ......................................................................... 0] │
* └──────────────────────────────────────────────────────────────────────────────────────────┘
* - Parent Addr: Direct pointer to the Easy Memory instance that created this Stack allocator.
*
* [ WORD 3: as.self.meta_index ] -> Maps to Block.as.occupied.magic (INDEX TRACKING)
* ┌──────────────────────────────────────────────────────────────────────────────────────────┐
* │ Current Allocation Index │
* │ [63/31/15 ......................................................................... 0] │
* └──────────────────────────────────────────────────────────────────────────────────────────┘
* - Index (N bits): A 1-based allocation counter (0 represents an empty stack).
* Used to track active elements and map directly to metadata array indices.
* ==============================================================================================