-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheasy_stack.h
More file actions
1755 lines (1556 loc) · 69.8 KB
/
Copy patheasy_stack.h
File metadata and controls
1755 lines (1556 loc) · 69.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 EASY_STACK_H
#define EASY_STACK_H
/*
* Easy Stack Allocator (easy_stack.h)
* A stupidly fast, lightweight, platform-agnostic, and safe LIFO stack allocator for C.
*
* ============================================================================
* 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.
* ============================================================================
*
* Features:
* - O(1) Constant Time allocations and deallocations.
* - Inverted bi-directional buffer layout:
* - Metadata grows forward from the start.
* - Payloads grow backward from the end.
* - Dynamic metadata bit-width scaling (uint8_t, uint16_t, uint32_t, uint64_t)
* based on capacity, reducing metadata footprint up to 8x.
* - XOR-hardened Stack Markers for secure rollbacks and preventing
* cross-allocator marker pollution.
*
* Configurable via macros for safety policies, assertions, and memory poisoning.
* Suitable for embedded systems, game development, and performance-critical applications.
*
* Author: gooderfreed
* License: MIT
*/
/*
* ============================================================================
* CONFIGURATION QUICK REFERENCE
* ============================================================================
* Define these macros before including this header to customize behavior.
*
* SAFETY & VERIFICATION:
* #define ESTACK_SAFETY_POLICY <N> // 0: CONTRACT (Design-by-Contract), 1: DEFENSIVE (Fault-Tolerant) [Default]
* #define DEBUG // Enables assertions and auto-enables poisoning
* #define ESTACK_ASSERT_STAYS // Forces assertions to remain active even in Release builds
* #define ESTACK_ASSERT_PANIC // Assertions call abort() (Hardened Release)
* #define ESTACK_ASSERT_OPTIMIZE // Assertions are optimization hints (Danger!)
* #define ESTACK_ASSERT(cond) // Override with custom assertion logic
*
* MEMORY POISONING:
* #define ESTACK_POISONING // Force ENABLE poisoning (even in Release)
* #define ESTACK_NO_POISONING // Force DISABLE poisoning (even in Debug)
* #define ESTACK_POISON_BYTE 0xDD // Custom byte pattern for freed memory
*
* ALIGNMENT & OPTIMIZATION:
* #define ESTACK_NO_AUTO_ALIGN // Disable user payload alignment (saves MCU RAM)
* #define ESTACK_NO_ALIGN_HEADER // Disable EStack header alignment (saves MCU RAM)
* #define ESTACK_DEFAULT_HEADER_ALIGNMENT <val> // Override optimal header alignment (defaults to 64/32/word bytes)
*
* SYSTEM & LINKAGE:
* #define ESTACK_STATIC // Make all functions static (Private linkage)
* #define ESTACK_RESTRICT // Manual override for 'restrict' keyword definition
* #define ESTACK_NO_ATTRIBUTES // Disable all compiler-specific attributes
* #define ESTACK_NO_BRANCH_HINTS // Disable compiler branch prediction hints
*
* TUNING:
* #define ESTACK_MAGIC <value> // Custom magic number for stack validation
* ============================================================================
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stddef.h>
// Forward declaration of the EStack structure.
typedef struct EStack EStack;
#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 ESTACK_CONCAT_INTERNAL(a, b) a##b
#define ESTACK_CONCAT(a, b) ESTACK_CONCAT_INTERNAL(a, b)
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) || defined(__cplusplus)
# include <assert.h>
# define ESTACK_STATIC_ASSERT(cond, msg) static_assert(cond, #msg)
#else
# define ESTACK_STATIC_ASSERT(cond, msg) \
typedef char ESTACK_CONCAT(static_assertion_at_line_, __LINE__)[(cond) ? 1 : -1]
#endif
/*
* Configuration: Architecture Verification
* easy_stack 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 ESTACK_INTERNAL_CHAR_BIT __CHAR_BIT__
#else
# include <limits.h>
# define ESTACK_INTERNAL_CHAR_BIT CHAR_BIT
#endif
ESTACK_STATIC_ASSERT(ESTACK_INTERNAL_CHAR_BIT == 8, "EStack requires 8-bit byte architecture");
/*
* Configuration: ESTACKDEF Macro
* Controls the linkage of the EasyStack functions.
*
* Behavior depends on defined macros:
* 1. ESTACK_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 ESTACKDEF
# ifdef ESTACK_STATIC
# define ESTACKDEF static
# else
# define ESTACKDEF extern
# endif
#endif
/*
* Configuration: Assertions
*
* Behavior depends on defined macros:
* 1. DEBUG or ESTACK_ASSERT_STAYS:
* Standard C assert(). Aborts and prints file/line on failure.
*
* 2. ESTACK_ASSERT_PANIC:
* Hardened Release. Calls abort() on failure.
* Recommended for security-critical environments to prevent heap exploitation.
*
* 3. ESTACK_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 ESTACK_ASSERT
# if defined(DEBUG) || defined(ESTACK_ASSERT_STAYS)
# include <assert.h>
# define ESTACK_ASSERT(cond) assert(cond)
# elif defined(ESTACK_ASSERT_PANIC)
# include <stdlib.h>
# define ESTACK_ASSERT(cond) do { if (!(cond)) abort(); } while(0)
# elif defined(ESTACK_ASSERT_OPTIMIZE)
# if defined(__GNUC__) || defined(__clang__)
# define ESTACK_ASSERT(cond) do { if (!(cond)) __builtin_unreachable(); } while(0)
# elif defined(_MSC_VER)
# define ESTACK_ASSERT(cond) __assume(cond)
# else
# define ESTACK_ASSERT(cond) ((void)0)
# endif
# else
// Default Release: Safe No-op
# define ESTACK_ASSERT(cond) ((void)0)
# endif
#endif
/*
* Configuration: ESTACK_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 ESTACK_RESTRICT
# if defined(__cplusplus)
# if defined(_MSC_VER)
# define ESTACK_RESTRICT __restrict
# elif defined(__GNUC__) || defined(__clang__)
# define ESTACK_RESTRICT __restrict__
# else
# define ESTACK_RESTRICT
# endif
# elif defined(_MSC_VER)
# define ESTACK_RESTRICT __restrict
# elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
# define ESTACK_RESTRICT restrict
# else
# define ESTACK_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.
*
* ESTACK_POLICY_CONTRACT (0):
* - Philosophy: Post-conditions and invariants are treated as a contract.
* - Behavior: Checks are delegated to the ESTACK_ASSERT mechanism.
* - Outcome: The final behavior (whether checks are compiled out, lead to a panic,
* or stay in release via ESTACK_ASSERT_STAYS) is determined entirely by the
* configured Assertion Strategy.
* - Best for: Fine-grained control over debugging and performance.
*
* ESTACK_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 ESTACK_POLICY_CONTRACT 0
#define ESTACK_POLICY_DEFENSIVE 1
#ifndef ESTACK_SAFETY_POLICY
# define ESTACK_SAFETY_POLICY ESTACK_POLICY_DEFENSIVE
#endif
/*
* Internal Safety Macros
*
* ESTACK_CHECK - Used in functions returning values (e.g., pointers, size_t).
* ESTACK_CHECK_V - Used in void functions (e.g., estack_free, estack_destroy).
*
* These macros adapt to the chosen ESTACK_SAFETY_POLICY, providing either
* a fail-fast assertion or a graceful runtime exit.
*/
#if ESTACK_SAFETY_POLICY == ESTACK_POLICY_CONTRACT
# define ESTACK_CHECK(cond, ret, msg) ESTACK_ASSERT((cond) && msg)
# define ESTACK_CHECK_V(cond, msg) ESTACK_ASSERT((cond) && msg)
#else
# define ESTACK_CHECK(cond, ret, msg) do { if (!(cond)) return (ret); } while(0)
# define ESTACK_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 ESTACK_NO_ATTRIBUTES
# if defined(EASY_STACK_IMPLEMENTATION) && defined(ESTACK_STATIC)
# define ESTACK_NO_ATTRIBUTES
# endif
#endif
/*
* Configuration: Compiler Attributes
* Adds compiler-specific attributes to functions for optimization and correctness hints.
*
* Behavior depends on defined macros:
* 1. ESTACK_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(ESTACK_NO_ATTRIBUTES)
# define ESTACK_ATTR_MALLOC
# define ESTACK_ATTR_WARN_UNUSED
# define ESTACK_ATTR_ALLOC_SIZE(idx, name)
#elif defined(__GNUC__) || defined(__clang__)
# define ESTACK_ATTR_MALLOC __attribute__((malloc))
# define ESTACK_ATTR_WARN_UNUSED __attribute__((warn_unused_result))
# define ESTACK_ATTR_ALLOC_SIZE(idx, name) __attribute__((alloc_size(idx)))
#elif defined(_MSC_VER)
# define ESTACK_ATTR_MALLOC __declspec(restrict) _Ret_maybenull_
# define ESTACK_ATTR_WARN_UNUSED _Check_return_
# define ESTACK_ATTR_ALLOC_SIZE(idx, name) _Post_writable_byte_size_(name)
#else
# define ESTACK_ATTR_MALLOC
# define ESTACK_ATTR_WARN_UNUSED
# define ESTACK_ATTR_ALLOC_SIZE(idx, name)
#endif
/*
* Configuration: Branch Prediction Hints
*
* Uses compiler builtins to guide the branch predictor for hot paths.
* Can be completely disabled by defining ESTACK_NO_BRANCH_HINTS before including this header.
*/
#if !defined(ESTACK_NO_BRANCH_HINTS) && (defined(__GNUC__) || defined(__clang__))
# define ESTACK_LIKELY(x) __builtin_expect(!!(x), 1)
# define ESTACK_UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
# define ESTACK_LIKELY(x) (x)
# define ESTACK_UNLIKELY(x) (x)
#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. ESTACK_NO_POISONING:
* Disables all poisoning features, regardless of build type.
*
* 2. DEBUG (without ESTACK_NO_POISONING):
* Enables poisoning in debug builds for maximum safety.
*
* 3. Default (Release without ESTACK_NO_POISONING):
* Disables poisoning to maximize performance.
*/
#ifdef ESTACK_NO_POISONING
# if defined(ESTACK_POISONING)
# undef ESTACK_POISONING
# endif
#elif defined(DEBUG) && !defined(ESTACK_POISONING)
# define ESTACK_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 ESTACK_POISON_BYTE before including this header.
*/
#ifndef ESTACK_POISON_BYTE
# define ESTACK_POISON_BYTE 0xDD
#endif
ESTACK_STATIC_ASSERT((ESTACK_POISON_BYTE >= 0x00) && (ESTACK_POISON_BYTE <= 0xFF), "ESTACK_POISON_BYTE must be a valid byte value.");
/*
* 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 ESTACK_MAGIC before including this header.
*/
#ifndef ESTACK_MAGIC
# if UINTPTR_MAX > 0xFFFFFFFFUL
# define ESTACK_MAGIC 0xDEADBEEFDEADBEEFULL
# elif UINTPTR_MAX > 0xFFFFU
# define ESTACK_MAGIC 0xDEADBEEFUL
# else
# define ESTACK_MAGIC 0xBEEFU
# endif
#endif
ESTACK_STATIC_ASSERT((ESTACK_MAGIC != 0), "ESTACK_MAGIC must be a non-zero value to ensure effective validation.");
/*
* Configuration: Minimum Alignment Limit
*
* Minimum payload alignment boundary.
* If auto-alignment is disabled, the minimum allowed alignment is 1 byte.
* Otherwise, it defaults to the machine-word size.
*/
#ifdef ESTACK_NO_AUTO_ALIGN
# define ESTACK_MIN_ALIGNMENT ((size_t)1)
#else
# define ESTACK_MIN_ALIGNMENT ((size_t)sizeof(uintptr_t))
#endif
/*
* Configuration: Header Alignment Selection
*
* Automatically forces ESTACK_NO_ALIGN_HEADER on 16-bit or 8-bit systems.
*/
#if !defined(ESTACK_NO_ALIGN_HEADER) && (UINTPTR_MAX <= 0xFFFFU)
# define ESTACK_NO_ALIGN_HEADER
#endif
/*
* Configuration: Header Alignment Selection
*
* Configures the optimal alignment boundary for the EStack context header.
* - If ESTACK_NO_ALIGN_HEADER is defined, alignment is disabled (1-byte).
* - If UINTPTR_MAX <= 0xFFFF (16-bit or 8-bit), we automatically force ESTACK_NO_ALIGN_HEADER.
* - For modern 64-bit desktop/server architectures, we default to 64-byte alignment
* to guarantee the L1 cache-line "free lunch" prefetching.
* - For 32-bit application processors (x86, ARM Cortex-A), we default to 32-byte alignment
* to match their typical L1 cache line size while minimizing memory overhead.
* - Otherwise, falls back to standard machine-word alignment.
*/
#ifndef ESTACK_NO_ALIGN_HEADER
# ifndef ESTACK_DEFAULT_HEADER_ALIGNMENT
# if defined(__x86_64__) || defined(__aarch64__) || defined(_M_X64) || defined(_M_ARM64)
# define ESTACK_DEFAULT_HEADER_ALIGNMENT ((size_t)64) // 64-byte cache line for 64-bit platforms
# elif defined(__i386__) || defined(__arm__) || defined(_M_IX86)
# define ESTACK_DEFAULT_HEADER_ALIGNMENT ((size_t)32) // 32-byte cache line for 32-bit platforms
# else
# define ESTACK_DEFAULT_HEADER_ALIGNMENT ((size_t)sizeof(uintptr_t)) // Fallback to word alignment
# endif
# endif
#endif
/*
* Bit-packing Masks and Shifts for `capacity_and_meta_size`
*
* Layout of capacity_and_meta_size:
* [ Bits N..3 ] -> Capacity (Total usable capacity of the buffer, shifted left by 3)
* [ Bit 2 ] -> Is Dynamic Flag (1 = allocated via malloc, 0 = user static buffer)
* [ Bits 1..0 ] -> Meta Type (0: uint8_t, 1: uint16_t, 2: uint32_t, 3: uint64_t)
*/
#define ESTACK_META_MASK ((uintptr_t)3) // Bits 0 and 1
#define ESTACK_IS_DYNAMIC_FLAG ((uintptr_t)4) // Bit 2
#define ESTACK_RESERVED_MASK ((uintptr_t)7) // All reserved bits (0, 1, 2)
#define ESTACK_CAPACITY_MASK (~ESTACK_RESERVED_MASK)
#define ESTACK_CAPACITY_SHIFT 3
/*
* Constant: Minimum and Maximum Stack Sizes
*/
#ifndef ESTACK_MIN_BUFFER_SIZE
# define ESTACK_MIN_BUFFER_SIZE (2 * sizeof(uintptr_t))
#endif
ESTACK_STATIC_ASSERT(ESTACK_MIN_BUFFER_SIZE > 0, "ESTACK_MIN_BUFFER_SIZE must be a positive value.");
#define ESTACK_MIN_SIZE (sizeof(EStack) + ESTACK_MIN_BUFFER_SIZE)
#define ESTACK_MAX_SIZE (SIZE_MAX >> ESTACK_CAPACITY_SHIFT)
/* ==============================================================================================
* MEMORY LAYOUT: Easy Stack (EStack) Header
* ==============================================================================================
* The EStack structure serves as the standalone context of the LIFO stack allocator.
* It utilizes a bi-directional inverted layout to achieve zero inline metadata overhead:
* - Metadata grows forward from the end of the header (lowest addresses).
* - Payloads grow backward from the physical end of the buffer (highest addresses).
*
* [ WORD 0: capacity_and_meta_size ] -> 64/32/16 bits (size_t)
* ┌─────────────────────────────────────────────────────────┬──────────┬───────────┐
* │ Capacity │ Is │ Meta Type │
* │ │ Dynamic │ │
* │ [63/31/15 ........................................ 3] │ [2] │ [1 .. 0] │
* └─────────────────────────────────────────────────────────┴──────────┴───────────┘
* - Meta Type (Bits 1..0):
* Stores the 2-bit compressed metadata offset size representing the width of
* each array element in the metadata segment.
* - 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)
*
* - Is Dynamic (Bit 2):
* 1 if the stack was allocated dynamically via system malloc() and must be
* reclaimed using the system free() inside `estack_destroy()`.
* 0 if initialized over a static user-provided buffer.
*
* - Capacity (N bits):
* Total usable payload capacity of the buffer (shifted left by 3).
*
* [ WORD 1: meta_index ] -> 64/32/16 bits (uintptr_t)
* ┌────────────────────────────────────────────────────────────────────────────────┐
* │ 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.
* ==============================================================================================
*/
struct EStack {
size_t capacity_and_meta_size; // Packed: [Capacity][Is_Dynamic:1][Meta_Type:2]
uintptr_t meta_index; // 1-based active allocation cursor
};
/*
* Helper Macro: ESTACK_REQUIRED_BUFFER_SIZE
*
* Calculates the exact raw buffer size (in bytes) required to guarantee
* a specific usable payload capacity, accounting for the EStack header
* and the maximum potential alignment padding.
*
* Usage:
* uint8_t memory_pool[ESTACK_REQUIRED_BUFFER_SIZE(1024)]; // Exactly 1024 bytes of usable space
* EStack *stack = estack_create_static(memory_pool, sizeof(memory_pool));
*/
#ifdef ESTACK_NO_ALIGN_HEADER
# define ESTACK_REQUIRED_BUFFER_SIZE(capacity) (sizeof(EStack) + (size_t)(capacity))
#else
# define ESTACK_REQUIRED_BUFFER_SIZE(capacity) (sizeof(EStack) + (size_t)(capacity) + ESTACK_DEFAULT_HEADER_ALIGNMENT)
#endif
/*
* Stack Allocator Rollback Marker (EStackMarker)
*
* A secure, XOR-hardened structure representing the state of a Stack allocator.
* Both the index and the signature are cryptographically masked with the stack's
* base address to prevent cross-allocator marker pollution and memory corruption
* during LIFO rollback operations.
*/
typedef struct {
size_t index; // XOR-encoded allocation index (cur_index ^ stack_address)
uintptr_t magic; // XOR-encoded verification signature (ESTACK_MAGIC ^ stack_address)
} EStackMarker;
/*
* ======================================================================================
* Public API Declarations
* ======================================================================================
*/
#ifdef DEBUG
#include <stdio.h>
/*
* Diagnostic & Visualization API
*/
ESTACKDEF void estack_print(const EStack *stack);
#endif // DEBUG
// --- Stack Creation (Dynamic) ---
#ifndef ESTACK_NO_MALLOC
/*
* Allocate and initialize a dynamic EStack on the heap.
* Requires standard library malloc() support.
*/
ESTACKDEF ESTACK_ATTR_MALLOC ESTACK_ATTR_WARN_UNUSED
EStack *estack_create(size_t capacity);
#endif // ESTACK_NO_MALLOC
// --- Stack Creation (Static) ---
/*
* Initialize an EStack instance over a static, pre-allocated raw memory buffer.
* Safe for bare-metal, shared memory, and stack-allocated environments.
*/
ESTACKDEF ESTACK_ATTR_WARN_UNUSED
EStack *estack_create_static(void *ESTACK_RESTRICT memory, size_t size);
// --- Allocation Core ---
/*
* Allocate memory from the EStack with baseline machine-word alignment.
*/
ESTACKDEF ESTACK_ATTR_MALLOC ESTACK_ATTR_WARN_UNUSED ESTACK_ATTR_ALLOC_SIZE(2, size)
void *estack_alloc(EStack *ESTACK_RESTRICT stack, size_t size);
/*
* Allocate memory from the EStack with customized power-of-two alignment boundaries.
*/
ESTACKDEF ESTACK_ATTR_MALLOC ESTACK_ATTR_WARN_UNUSED ESTACK_ATTR_ALLOC_SIZE(2, size)
void *estack_alloc_aligned(EStack *ESTACK_RESTRICT stack, size_t size, size_t alignment);
// --- Deallocation & Rollback ---
/*
* Reclaim the most recent (LIFO) allocation and verify the active stack boundary.
*/
ESTACKDEF void estack_free(EStack *ESTACK_RESTRICT stack, void *pointer);
/*
* Create an XOR-hardened snapshot of the current allocation cursor.
*/
ESTACKDEF EStackMarker estack_get_marker(const EStack *stack);
/*
* Roll back the allocation state to the snapshot captured by the provided marker.
*/
ESTACKDEF void estack_free_to_marker(EStack *ESTACK_RESTRICT stack, EStackMarker marker);
// --- Lifecycle & Reset ---
/*
* Reset the allocation index to zero without clearing the memory payload.
*/
ESTACKDEF void estack_reset(EStack *ESTACK_RESTRICT stack);
/*
* Reset the allocation index to zero and physically fill the payload space with zeros.
*/
ESTACKDEF void estack_reset_zero(EStack *ESTACK_RESTRICT stack);
/*
* Tear down the stack and reclaim dynamically allocated resources (if any).
*/
ESTACKDEF void estack_destroy(EStack *stack);
#ifdef EASY_STACK_IMPLEMENTATION
/*
* Helper function to Align up
* Rounds up the given size to the nearest multiple of alignment
*/
static inline size_t align_up(size_t size, size_t alignment) {
return (size + alignment - 1) & ~(alignment - 1);
}
/*
* Helper function to Align down
* Rounds down the given size to the nearest multiple of alignment
*/
static inline size_t align_down(size_t size, size_t alignment) {
return size & ~(alignment - 1);
}
/* ==============================================================================================
* EStack Bit-Packed Header Manipulation API
* ==============================================================================================
*/
/*
* Get the total payload capacity of the EStack.
* Decodes the capacity stored in the upper bits of `capacity_and_meta_size`.
*/
static inline size_t estack_get_capacity(const EStack *stack) {
ESTACK_ASSERT(stack != NULL && "Internal Error: 'estack_get_capacity' called on NULL pointer");
return (stack->capacity_and_meta_size & ESTACK_CAPACITY_MASK) >> ESTACK_CAPACITY_SHIFT;
}
/*
* Set the total payload capacity of the EStack.
* Encodes the capacity into the upper bits of `capacity_and_meta_size` while preserving metadata flags.
*/
static inline void estack_set_capacity(EStack *stack, size_t capacity) {
ESTACK_ASSERT(stack != NULL && "Internal Error: 'estack_set_capacity' called on NULL pointer");
ESTACK_ASSERT(capacity <= ESTACK_MAX_SIZE && "Internal Error: 'estack_set_capacity' size exceeds representable limit");
/*
* Why size limit?
* Since we utilize 3 bits of capacity_and_meta_size field for meta type, we have the remaining bits available for size.
*
* On 32-bit systems, size_t is 4 bytes (32 bits), so we have 29 bits left for size (32 - 3 = 29).
* This gives us a maximum size of 2^29 - 1 = 536,870,911 bytes (approximately 512 MiB).
* In 32-bit systems, where maximum addressable memory in user space is 2-3 GiB, this limitation is acceptable.
* Bigger size is not practical since we cannot allocate a contiguous memory block that **literally** 30%+ of all accessible memory,
* malloc is extremely likely to return NULL due to heap fragmentation.
* Like, what you even gonna do with 1GB of contiguous memory, when even all operating system use ~1-2GB?
* Play "Bad Apple" 8K 120fps via raw frames?
*
* On the other hand,
*
* On 64-bit systems, size_t is 8 bytes (64 bits), so we have 61 bits left for size (64 - 3 = 61).
* This gives us a maximum size of 2^61 - 1 = 2,305,843,009,213,693,951 bytes (approximately 2 EiB).
* In 64-bit systems, this limitation is practically non-existent since current hardware and OS limitations are far below this threshold.
*
* Conclusion: This limitation is a deliberate trade-off that avoids any *real* constraints on both 32-bit and 64-bit systems while optimizing memory usage.
*/
size_t reserved = stack->capacity_and_meta_size & ESTACK_RESERVED_MASK;
stack->capacity_and_meta_size = (capacity << ESTACK_CAPACITY_SHIFT) | reserved;
}
/*
* Check if the EStack is dynamically allocated.
* Extracts the 1-bit allocation flag from bit 2.
*/
static inline bool estack_get_is_dynamic(const EStack *stack) {
ESTACK_ASSERT(stack != NULL && "Internal Error: 'estack_get_is_dynamic' called on NULL pointer");
return (stack->capacity_and_meta_size & ESTACK_IS_DYNAMIC_FLAG) != 0;
}
/*
* Set the dynamic allocation flag of the EStack on bit 2.
*/
static inline void estack_set_is_dynamic(EStack *stack, bool is_dynamic) {
ESTACK_ASSERT(stack != NULL && "Internal Error: 'estack_set_is_dynamic' called on NULL pointer");
if (is_dynamic) {
stack->capacity_and_meta_size |= ESTACK_IS_DYNAMIC_FLAG;
} else {
stack->capacity_and_meta_size &= ~ESTACK_IS_DYNAMIC_FLAG;
}
}
/*
* Get the metadata entry size (type) for the stack.
* Extracts the 2-bit type code from bits 1..0.
*/
static inline size_t estack_get_meta_type(const EStack *stack) {
ESTACK_ASSERT(stack != NULL && "Internal Error: 'estack_get_meta_type' called on NULL pointer");
return stack->capacity_and_meta_size & ESTACK_META_MASK;
}
/*
* Set the metadata entry size (type) for the stack on bits 1..0.
*/
static inline void estack_set_meta_type(EStack *stack, size_t meta_type) {
ESTACK_ASSERT(stack != NULL && "Internal Error: 'estack_set_meta_type' called on NULL pointer");
ESTACK_ASSERT(meta_type <= 3 && "Internal Error: 'estack_set_meta_type' called with invalid metadata type code");
stack->capacity_and_meta_size = (stack->capacity_and_meta_size & ~ESTACK_META_MASK) | meta_type;
}
/*
* Get the current allocation meta index.
*/
static inline size_t estack_get_meta_index(const EStack *stack) {
ESTACK_ASSERT(stack != NULL && "Internal Error: 'estack_get_meta_index' called on NULL pointer");
return stack->meta_index;
}
/*
* Set the current allocation meta index.
*/
static inline void estack_set_meta_index(EStack *stack, size_t meta_index) {
ESTACK_ASSERT(stack != NULL && "Internal Error: 'estack_set_meta_index' called on NULL pointer");
stack->meta_index = meta_index;
}
/* ==============================================================================================
* EStack Metadata Processing Operations
* ==============================================================================================
*/
/*
* Calculate the optimal metadata integer width based on the stack's physical capacity.
* Minimizes RAM footprint by sizing metadata cells strictly to fit capacity limits.
*/
static inline size_t estack_calculate_meta_type(size_t capacity) {
if (capacity <= UINT8_MAX) return 0; // Fits in uint8_t
#if SIZE_MAX <= UINT16_MAX
return 1; // Max 64KB, fits in uint16_t
#else
if (capacity <= UINT16_MAX) return 1; // Fits in uint16_t
#if SIZE_MAX <= UINT32_MAX
return 2; // Fits in uint32_t
#else
if (capacity <= UINT32_MAX) return 2; // Fits in uint32_t
return 3; // Requires uint64_t
#endif
#endif
}
/*
* Fetch a metadata value (relative payload offset) from the metadata array.
* Dynamically scales and casts offsets based on the stack's configured meta_type.
* Optimized with branch prediction hints for the most common capacities.
*/
static inline size_t estack_read_meta(const EStack *stack, size_t meta_type, size_t index) {
uintptr_t end_of_stack_header = (uintptr_t)stack + sizeof(EStack);
// Case 1 (< 64 KB): Highly likely scenario for thread-local/scratchpad workloads
if (ESTACK_LIKELY(meta_type == 1)) {
uint16_t val;
memcpy(&val, (const void *)(end_of_stack_header + (index * sizeof(uint16_t))), sizeof(uint16_t));
return val;
}
// Case 2 (< 4 GB): Highly likely scenario for large desktop/game-engine stacks
#if UINTPTR_MAX >= 0xFFFFFFFFUL
if (ESTACK_LIKELY(meta_type == 2)) {
uint32_t val;
memcpy(&val, (const void *)(end_of_stack_header + (index * sizeof(uint32_t))), sizeof(uint32_t));
return val;
}
#endif
// Case 0 (< 256 B): Micro-allocations or small static buffers
if (meta_type == 0) {
return ((const uint8_t *)(const void *)end_of_stack_header)[index];
}
// Case 3 (>= 4 GB): Highly unlikely for standard stack allocators
#if UINTPTR_MAX == 0xFFFFFFFFFFFFFFFFULL
if (ESTACK_UNLIKELY(meta_type == 3)) {
uint64_t val;
memcpy(&val, (const void *)(end_of_stack_header + (index * sizeof(uint64_t))), sizeof(uint64_t));
return val;
}
#endif
// LCOV_EXCL_START
ESTACK_ASSERT(false && "Invalid meta type in stack allocator");
return 0;
// LCOV_EXCL_STOP
}
/*
* Store a metadata value (relative payload offset) into the metadata array.
* Dynamically scales and casts writes based on the stack's configured meta_type.
* Optimized with branch prediction hints for the most common capacities.
*/
static inline void estack_write_meta(EStack *stack, size_t meta_type, size_t index, size_t value) {
uintptr_t end_of_stack_header = (uintptr_t)stack + sizeof(EStack);
// Case 1 (< 64 KB): Highly likely scenario for thread-local/scratchpad workloads
if (ESTACK_LIKELY(meta_type == 1)) {
uint16_t val16 = (uint16_t)value;
memcpy((void *)(end_of_stack_header + index * sizeof(uint16_t)), &val16, sizeof(uint16_t));
return;
}
// Case 2 (< 4 GB): Highly likely scenario for large desktop/game-engine stacks
#if UINTPTR_MAX >= 0xFFFFFFFFUL
if (ESTACK_LIKELY(meta_type == 2)) {
uint32_t val32 = (uint32_t)value;
memcpy((void *)(end_of_stack_header + index * sizeof(uint32_t)), &val32, sizeof(uint32_t));
return;
}
#endif
// Case 0 (< 256 B): Micro-allocations or small static buffers
if (meta_type == 0) {
((uint8_t *)(void *)end_of_stack_header)[index] = (uint8_t)value;
return;
}
// Case 3 (>= 4 GB): Highly unlikely for standard stack allocators
#if UINTPTR_MAX == 0xFFFFFFFFFFFFFFFFULL
if (ESTACK_UNLIKELY(meta_type == 3)) {
uint64_t val64 = (uint64_t)value;
memcpy((void *)(end_of_stack_header + index * sizeof(uint64_t)), &val64, sizeof(uint64_t));
return;
}
#endif
// LCOV_EXCL_START
ESTACK_ASSERT(false && "Invalid meta type in stack allocator");
// LCOV_EXCL_STOP
}
/* ==============================================================================================
* EStack Creation & Initialization API
* ==============================================================================================
*/
/*
* Initialize an EStack instance over a static, pre-allocated raw memory buffer
*
* Transforms a raw pre-allocated block of memory into a fully functional and
* safe LIFO stack allocator. This is the primary initialization function for
* bare-metal, stack-allocated, or shared memory environments.
*
* Header Alignment and Memory Overhead:
* To achieve the L1 cache-line "free lunch" prefetching, the function automatically
* aligns the starting address of the EStack structure to the boundary configured by
* ESTACK_DEFAULT_HEADER_ALIGNMENT (64 bytes on 64-bit systems, 32 bytes on 32-bit systems).
*
* This self-alignment shift might introduce a padding overhead, reducing the usable
* capacity from the provided total 'size' by up to:
* - 63 bytes on 64-bit systems (x86_64, aarch64)
* - 31 bytes on 32-bit systems (x86_32, arm32)
*
* If you need to guarantee EXACTLY 'C' bytes of usable payload capacity, you should
* define your static buffer size using the helper macro:
* uint8_t buffer[ESTACK_REQUIRED_BUFFER_SIZE(C)];
*
* This automatically handles the EStack header size and the system's optimal
* alignment padding (ESTACK_DEFAULT_HEADER_ALIGNMENT) behind the scenes.
*
* For memory-constrained microcontrollers where cache alignment is not critical or
* the hardware natively supports fast arbitrary/unaligned memory reads, you can completely
* disable this header alignment overhead by defining ESTACK_NO_ALIGN_HEADER before
* including this header. This forces 1-byte header alignment, eliminating all alignment waste.
*
* Capacity Limits:
* - Minimum: ESTACK_MIN_SIZE (calculated as sizeof(EStack) + ESTACK_MIN_BUFFER_SIZE).
* - Physical Max: 512 MiB (32-bit systems) or 2 EiB (64-bit systems), limited by bit-packing.
* - Usable Max: Total 'size' minus internal alignment padding and the EStack
* header overhead (sizeof(EStack)).
*
* Parameters:
* - memory: Pointer to the start of the buffer (alignment is handled internally).
* - size: Total size of the provided buffer in bytes.
*
* Returns:
* A pointer to the initialized EStack header within the provided buffer,
* or NULL if the usable area (after self-alignment) is below the minimum threshold.
*
* Safety & Behavior:
* - ESTACK_SAFETY_POLICY == ESTACK_POLICY_CONTRACT:
* Triggers ESTACK_ASSERT on NULL memory or if size is outside [Min..Max] range.
*
* - ESTACK_SAFETY_POLICY == ESTACK_POLICY_DEFENSIVE:
* Gracefully returns NULL if input parameters are invalid or if the
* buffer cannot satisfy the initialization overhead.
*/
ESTACKDEF EStack *estack_create_static(void *ESTACK_RESTRICT memory, size_t size) {
ESTACK_CHECK(memory != NULL, NULL, "EStack: 'estack_create_static' called with NULL memory pointer");
ESTACK_CHECK(size >= ESTACK_MIN_SIZE, NULL, "EStack: 'estack_create_static' buffer size is below ESTACK_MIN_SIZE");
ESTACK_CHECK(size <= ESTACK_MAX_SIZE, NULL, "EStack: 'estack_create_static' buffer size exceeds maximum limit");
#ifdef ESTACK_NO_ALIGN_HEADER
uintptr_t aligned_addr = (uintptr_t)memory;
size_t padding = 0;
#else
// Align the raw address to the selected header boundary (cache-line or word)
uintptr_t raw_addr = (uintptr_t)memory;
uintptr_t aligned_addr = align_up(raw_addr, ESTACK_DEFAULT_HEADER_ALIGNMENT);
size_t padding = aligned_addr - raw_addr;
#endif
// Check if the remaining buffer is still large enough after alignment adjustment
// LCOV_EXCL_START
if (size < padding + ESTACK_MIN_SIZE) {
return NULL;
}
// LCOV_EXCL_STOP
EStack *stack = (EStack *)aligned_addr;
// Clear memory fields to avoid dirty-state pollution
stack->capacity_and_meta_size = 0;
stack->meta_index = 0;
// Calculate usable capacity (buffer trailing space after header)
size_t capacity = size - padding - sizeof(EStack);
// Initialize bit-packed fields
estack_set_capacity(stack, capacity);
estack_set_is_dynamic(stack, false); // Static by default
// Automatically determine the narrowest safe metadata integer size
size_t meta_type = estack_calculate_meta_type(capacity);
estack_set_meta_type(stack, meta_type);
return stack;
}
#ifndef ESTACK_NO_MALLOC
/*
* Allocate and initialize a dynamic EStack on the heap
*
* Allocates a contiguous block from the system heap (via malloc) and
* initializes it as a dynamic LIFO stack allocator.
*
* Performance:
* - O(1) + system malloc() overhead.
*
* Capacity Limits:
* - Minimum Usable: ESTACK_MIN_BUFFER_SIZE bytes.
* - Physical Max: 512 MiB (32-bit systems) or 2 EiB (64-bit systems), limited by bit-packing.
* - Usable Max: Equal to the requested 'capacity'.
* Note: The actual system memory consumption will be higher due to the
* EStack header overhead (sizeof(EStack)).
*
* Parameters:
* - capacity: The requested usable capacity of the stack.
*
* Returns:
* - Pointer to the new EStack instance, or NULL if system malloc fails or
* if capacity causes an integer overflow.
*
* Safety & Behavior:
* - ESTACK_SAFETY_POLICY == ESTACK_POLICY_CONTRACT:
* Triggers ESTACK_ASSERT if capacity is out of range or overhead calculation overflows.
*
* - ESTACK_SAFETY_POLICY == ESTACK_POLICY_DEFENSIVE:
* Performs an unconditional overflow check and returns NULL if the
* request is mathematically impossible to satisfy.
*/
ESTACKDEF EStack *estack_create(size_t capacity) {
ESTACK_CHECK(capacity >= ESTACK_MIN_BUFFER_SIZE, NULL, "EStack: requested capacity is too small");
ESTACK_CHECK(capacity <= ESTACK_MAX_SIZE, NULL, "EStack: requested capacity exceeds limits");
#ifdef ESTACK_NO_ALIGN_HEADER
size_t total_size = sizeof(EStack) + capacity + sizeof(uintptr_t);
#else
size_t total_size = sizeof(EStack) + capacity + ESTACK_DEFAULT_HEADER_ALIGNMENT + sizeof(uintptr_t);
#endif
void *raw_mem = malloc(total_size);
// LCOV_EXCL_START
if (!raw_mem) {
return NULL;
}
// LCOV_EXCL_STOP