-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasserted.h
More file actions
1291 lines (1159 loc) · 60.5 KB
/
Copy pathasserted.h
File metadata and controls
1291 lines (1159 loc) · 60.5 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
// The MIT License (MIT)
//
// Copyright(c) 2025, Damien Feneyrou <dfeneyrou@gmail.com>
//
// 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.
#pragma once
// 'asserted' is a library making a trade-off between weight and features.
// It rather places itself on the light side while bringing much needed features and ease C++ development.
//
// Features:
// - Context display via variable content
// - Stacktrace dump (requires libunwind to build on Linux, and addr2line at run time for symbol resolution)
// - Signals override to catch crashes
// - Compile-time enabling of group of assertions
// - No "unused variable" when assertions are disabled
// - Single header
// - Linux & Windows support
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4996) // Disable Windows's secure API warnings
#endif
//-----------------------------------------------------------------------------
// Library configuration
//-----------------------------------------------------------------------------
// The 3 main switches are:
// - ASSERTED_NO_ASSERT set to 1 to disable the assertions at compile time. They are enabled by default.
// - ASSERTED_NO_SIGNALS set to 1 to disable the signal catching. Catching is enabled by default.
// - ASSERTED_WITH_STACKTRACE set to 1 to enable the stacktrace dump. Disabled by default, due to dependencies
// Disable assertions
#ifndef ASSERTED_NO_ASSERT
#define ASSERTED_NO_ASSERT 0
#endif
// Disable installing signal handlers (ABRT, FPE, ILL, SEGV, TERM and INT (if ASSERTED_NO_SIGINT is 0) )
#ifndef ASSERTED_NO_SIGNALS
#define ASSERTED_NO_SIGNALS 0
#endif
// Disable catching the SIGINT signal (N/A if ASSERTED_NO_SIGNALS==1). Signal is enabled by default
#ifndef ASSERTED_NO_SIGINT
#define ASSERTED_NO_SIGINT 0
#endif
// Disable automatically breaking into an attached debugger when a crash occurs, right before the process would
// otherwise exit. Independent of ASSERTED_NO_SIGNALS: a plain failed assertion reaches this too, not just a
// caught signal. Enabled by default. Always a no-op when no debugger is attached - see isDebuggerPresent_() below.
#ifndef ASSERTED_NO_DEBUG_BREAK
#define ASSERTED_NO_DEBUG_BREAK 0
#endif
// Display messages using terminal colors. Enabled by default.
#ifndef ASSERTED_NO_COLOR
#define ASSERTED_NO_COLOR 0
#endif
#if ASSERTED_NO_COLOR == 1
#define ASSERTED_COLOR_RED ""
#define ASSERTED_COLOR_BLUE ""
#define ASSERTED_COLOR_NUMBER ""
#define ASSERTED_COLOR_FUNCTION ""
#define ASSERTED_COLOR_RESET ""
#else
#define ASSERTED_COLOR_RED "\033[31m"
#define ASSERTED_COLOR_BLUE "\033[34m"
#define ASSERTED_COLOR_NUMBER "\033[93m"
#define ASSERTED_COLOR_FUNCTION "\033[36m"
#define ASSERTED_COLOR_RESET "\033[0m"
#endif
// Stacktrace logging when a crash occurs
// - On Linux, stack trace logging is disabled by default. It requires libunwind.so (stack unwinding) to build:
// install with "apt install libunwind-dev". Resolving addresses into function names and file:line is done at
// run time by spawning 'addr2line' (part of binutils), rather than by linking a DWARF-reading library into
// the process: see ASSERTED_ADDR2LINE_BIN below. If 'addr2line' is not installed or not on $PATH when a crash
// happens, frames are still printed, just as raw addresses.
// - On Windows, stacktrace logging is enabled by default as base system libraries cover the requirements.
// Note: The executable shall contain debug information for file:line to resolve; function names, on Linux,
// resolve from the symbol table regardless (unless the binary is fully stripped of it too).
#if defined(_MSC_VER) && !defined(ASSERTED_WITH_STACKTRACE)
#define ASSERTED_WITH_STACKTRACE 1
#endif
#ifndef ASSERTED_WITH_STACKTRACE
#define ASSERTED_WITH_STACKTRACE 0
#endif
// Exit function when a crash occurs, called after displaying the crash information. Default is a call to quick_exit().
// Note: it is declared [[noreturn]]-equivalent internally, so a replacement MUST NOT return to its caller.
#ifndef ASSERTED_CRASH_EXIT_FUNC
#define ASSERTED_CRASH_EXIT_FUNC() quick_exit(1)
#endif
// Error display function. On Windows, it shall probably be redirected on a MessageBox
#ifndef ASSERTED_MESSAGE
#define ASSERTED_MESSAGE(msg, isLastFromCrash) fprintf(stderr, "%s", msg)
#endif
// Size in bytes of the alternate signal stack used on Linux/Unix so that a SIGSEGV caused by stack overflow still
// has room to run the crash handler and, when ASSERTED_WITH_STACKTRACE=1, capture the raw addresses and spawn
// addr2line (see ASSERTED_ADDR2LINE_BIN below) - the bulk of the stacktrace machinery's own scratch buffers are
// static rather than on-stack precisely so this doesn't need to be large. The virtual memory cost of leaving this
// generous is negligible: unless actually used, the extra pages are never committed.
#ifndef ASSERTED_ALT_STACK_SIZE
#define ASSERTED_ALT_STACK_SIZE (256 * 1024)
#endif
// Binary used on Linux/Unix to resolve captured addresses into function names and file:line, when
// ASSERTED_WITH_STACKTRACE=1. Looked up via $PATH (or pass an absolute path to bypass that). Unlike libdw, which
// used to be called in-process here, this is a run-time dependency: it does not need to be present at build
// time, but does need to be reachable on whichever machine the crash actually happens on. If it isn't installed,
// or fails for any reason, resolution falls back to raw addresses - the same degradation already used for
// addresses that can't be resolved at all.
#ifndef ASSERTED_ADDR2LINE_BIN
#define ASSERTED_ADDR2LINE_BIN "addr2line"
#endif
// Library version
#define ASSERTED_VERSION "0.1.0"
#define ASSERTED_VERSION_NUM 100 // Monotonic number. 100 per version component. Official releases are multiple of 100
#define ASSERTED_IS_ENABLED (ASSERTED_NO_SIGNALS == 0 || ASSERTED_NO_ASSERT == 0)
#ifndef ASSERTED_CRASH_MSG_SIZE
#define ASSERTED_CRASH_MSG_SIZE 2048
#endif
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
#if ASSERTED_IS_ENABLED
// Windows base header (hard to avoid this include...)
#if defined(_MSC_VER)
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers. If it is a problem, just comment it
#include <windows.h>
#include <cinttypes>
#include <cstdint>
#if ASSERTED_NO_DEBUG_BREAK == 0
#include <debugapi.h> // For IsDebuggerPresent()
#endif
#endif
#include <cstdio> // For snprintf etc...
#include <cstdlib> // For abort(), quick_exit...
#include <cstring> // For memset
#if ASSERTED_NO_ASSERT == 0
#include <string> // For the std::string display handler
#include <type_traits> // For the enum display handler
#endif
#if ASSERTED_NO_SIGNALS == 0 || (defined(__unix__) && ASSERTED_NO_DEBUG_BREAK == 0)
#include <csignal> // For raising signals in crash handler, and/or SIGTRAP (debugger-break feature on Linux/Unix)
#endif
#if defined(__unix__) && ASSERTED_NO_DEBUG_BREAK == 0
#include <fcntl.h> // For open() - detecting an attached debugger via /proc/self/status
#include <unistd.h> // For read(), close()
#endif
#if ASSERTED_WITH_STACKTRACE == 1
#if defined(__unix__)
#define UNW_LOCAL_ONLY
#include <fcntl.h> // For open()
#include <libunwind.h> // Stack unwinding (need package libunwind-dev)
#include <sys/wait.h> // For waitpid()
#include <unistd.h> // For fork(), execvp(), pipe(), dup2(), read(), close(), _exit()
#include <cstdint> // For uintptr_t
#endif // if defined(__unix__)
#if defined(_MSC_VER)
#include <dbghelp.h> // For the symbol decoding
#include <errhandlingapi.h> // For the HW exceptions
#pragma comment(lib, "DbgHelp.lib")
#endif // if defined(_MSC_VER)
#endif // if ASSERTED_WITH_STACKTRACE==1
#endif // if ASSERTED_IS_ENABLED
// This line below is unfortunately the only way found to remove the zero-arguments-variadic-macro and
// the prohibited-anonymous-structs warnings with GCC when the build is using the option -Wpedantic
#ifndef _MSC_VER
#pragma GCC system_header
#endif
//-----------------------------------------------------------------------------
// Public assertion API. Macro-based due to compile-time removal cosntraint
//-----------------------------------------------------------------------------
// Macros to handle disabled assertions. Up to 10 parameters
#define ASSERTED_PRIV_UNUSED0()
#define ASSERTED_PRIV_UNUSED1(a) (void)(a)
#define ASSERTED_PRIV_UNUSED2(a, b) (void)(a), ASSERTED_PRIV_UNUSED1(b)
#define ASSERTED_PRIV_UNUSED3(a, b, c) (void)(a), ASSERTED_PRIV_UNUSED2(b, c)
#define ASSERTED_PRIV_UNUSED4(a, b, c, d) (void)(a), ASSERTED_PRIV_UNUSED3(b, c, d)
#define ASSERTED_PRIV_UNUSED5(a, b, c, d, e) (void)(a), ASSERTED_PRIV_UNUSED4(b, c, d, e)
#define ASSERTED_PRIV_UNUSED6(a, b, c, d, e, f) (void)(a), ASSERTED_PRIV_UNUSED5(b, c, d, e, f)
#define ASSERTED_PRIV_UNUSED7(a, b, c, d, e, f, g) (void)(a), ASSERTED_PRIV_UNUSED6(b, c, d, e, f, g)
#define ASSERTED_PRIV_UNUSED8(a, b, c, d, e, f, g, h) (void)(a), ASSERTED_PRIV_UNUSED7(b, c, d, e, f, g, h)
#define ASSERTED_PRIV_UNUSED9(a, b, c, d, e, f, g, h, i) (void)(a), ASSERTED_PRIV_UNUSED8(b, c, d, e, f, g, h, i)
#define ASSERTED_PRIV_UNUSED10(a, b, c, d, e, f, g, h, i, j) (void)(a), ASSERTED_PRIV_UNUSED9(b, c, d, e, f, g, h, i, j)
#define ASSERTED_PRIV_VA_NUM_ARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define ASSERTED_PRIV_VA_NUM_ARGS(...) ASSERTED_PRIV_VA_NUM_ARGS_IMPL(100, ##__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define ASSERTED_PRIV_ALL_UNUSED_IMPL_(nargs) ASSERTED_PRIV_UNUSED##nargs
#define ASSERTED_PRIV_ALL_UNUSED_IMPL(nargs) ASSERTED_PRIV_ALL_UNUSED_IMPL_(nargs)
// Note: the whole chain is wrapped in a never-taken "if(false)" (not a bare (void)-cast expression) so that the
// arguments are referenced (silencing "unused variable" warnings) without ever being evaluated at runtime, even
// at -O0. This matters when an argument is a function call or has other side effects: unlike a (void)-cast, which
// still evaluates its operand and only discards the result, a dead branch is simply never executed.
#define ASSERTED_PRIV_ALL_UNUSED(...) \
do { \
if (false) { \
ASSERTED_PRIV_ALL_UNUSED_IMPL(ASSERTED_PRIV_VA_NUM_ARGS(__VA_ARGS__))(__VA_ARGS__); \
} \
} while (0)
// These assertions allow to easily dump the values which contribute to the condition.
// Ex: asserted(a<b); // Standard form
// asserted(a<b, "A shall always be less than b"); // Documented form
// asserted(a<b, a, b); // Extended form showing the values of 'a' and 'b' when assertion is failed
// asserted(a<b, "A shall always be less than b", a, b); // Displays up to 9 parameters... Ought to be enough for anybody (tm)
#if ASSERTED_NO_ASSERT == 0
// Macro to stringify the additional parameters of the enhanced assertions. Up to 10 parameters
// Note: in C99 and C++11, zero parameter is a problem, hence the forced & dummy first parameter "".
#define ASSERTED_PRIV_ASSERT_PARAM0() nullptr, 0
#define ASSERTED_PRIV_ASSERT_PARAM1(v1) nullptr, 0
#define ASSERTED_PRIV_ASSERT_PARAM2(v1, v2) nullptr, 0, #v2, v2
#define ASSERTED_PRIV_ASSERT_PARAM3(v1, v2, v3) nullptr, 0, #v2, v2, #v3, v3
#define ASSERTED_PRIV_ASSERT_PARAM4(v1, v2, v3, v4) nullptr, 0, #v2, v2, #v3, v3, #v4, v4
#define ASSERTED_PRIV_ASSERT_PARAM5(v1, v2, v3, v4, v5) nullptr, 0, #v2, v2, #v3, v3, #v4, v4, #v5, v5
#define ASSERTED_PRIV_ASSERT_PARAM6(v1, v2, v3, v4, v5, v6) nullptr, 0, #v2, v2, #v3, v3, #v4, v4, #v5, v5, #v6, v6
#define ASSERTED_PRIV_ASSERT_PARAM7(v1, v2, v3, v4, v5, v6, v7) nullptr, 0, #v2, v2, #v3, v3, #v4, v4, #v5, v5, #v6, v6, #v7, v7
#define ASSERTED_PRIV_ASSERT_PARAM8(v1, v2, v3, v4, v5, v6, v7, v8) \
nullptr, 0, #v2, v2, #v3, v3, #v4, v4, #v5, v5, #v6, v6, #v7, v7, #v8, v8
#define ASSERTED_PRIV_ASSERT_PARAM9(v1, v2, v3, v4, v5, v6, v7, v8, v9) \
nullptr, 0, #v2, v2, #v3, v3, #v4, v4, #v5, v5, #v6, v6, #v7, v7, #v8, v8, #v9, v9
#define ASSERTED_PRIV_ASSERT_PARAM10(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) \
nullptr, 0, #v2, v2, #v3, v3, #v4, v4, #v5, v5, #v6, v6, #v7, v7, #v8, v8, #v9, v9, #v10, v10
#define asserted(cond_, ...) \
if (ASSERTED_UNLIKELY(!(cond_))) \
assertedPriv::failedAssert(__FILE__, __LINE__, ASSERTED_FUNCTION, #cond_, \
ASSERTED_PRIV_CALL_OVERLOAD(ASSERTED_PRIV_ASSERT_PARAM, "", ##__VA_ARGS__))
#define group_asserted(group_, cond_, ...) \
ASSERTED_PRIV_IF(ASSERTED_IS_COMPILE_TIME_ENABLED_(group_), asserted(cond_, ##__VA_ARGS__), do {} while (0))
#ifdef NDEBUG
#define debug_asserted(...) ASSERTED_PRIV_ALL_UNUSED(__VA_ARGS__)
#else
#define debug_asserted(...) asserted(__VA_ARGS__)
#endif
#else // if ASSERTED_NO_ASSERT == 0
#define asserted(...) ASSERTED_PRIV_ALL_UNUSED(__VA_ARGS__)
#define group_asserted(group, ...) ASSERTED_PRIV_ALL_UNUSED(__VA_ARGS__)
#define debug_asserted(...) ASSERTED_PRIV_ALL_UNUSED(__VA_ARGS__)
#endif // if ASSERTED_NO_ASSERT==0
//-----------------------------------------------------------------------------
// Macro helpers
//-----------------------------------------------------------------------------
// Optimization of the branching
#if defined(__GNUC__) || defined(__clang__)
#define ASSERTED_LIKELY(x) (__builtin_expect(!!(x), 1))
#define ASSERTED_UNLIKELY(x) (__builtin_expect(!!(x), 0))
#define ASSERTED_NOINLINE __attribute__((noinline))
#define ASSERTED_NORETURN __attribute__((__noreturn__))
#else
#define ASSERTED_LIKELY(x) (x)
#define ASSERTED_UNLIKELY(x) (x)
#define ASSERTED_NOINLINE
#define ASSERTED_NORETURN
#endif
// Best possible function name for assertions
#if defined(__GNUC__) || defined(__clang__)
#define ASSERTED_FUNCTION __PRETTY_FUNCTION__
#elif defined(_MSC_VER)
#define ASSERTED_FUNCTION __FUNCSIG__
#else
#define ASSERTED_FUNCTION __func__
#endif
// Conditional inclusion macro trick
#define ASSERTED_PRIV_IF(cond, foo1, foo2) ASSERTED_PRIV_IF_IMPL(cond, foo1, foo2)
#define ASSERTED_PRIV_IF_IMPL(cond, foo1, foo2) ASSERTED_PRIV_IF_IMPL2(cond, foo1, foo2)
#define ASSERTED_PRIV_IF_IMPL2(cond, foo1, foo2) ASSERTED_PRIV_IF_##cond(foo1, foo2)
#define ASSERTED_PRIV_IF_0(foo1, foo2) foo2
#define ASSERTED_PRIV_IF_1(foo1, foo2) foo1
// Variadic macro trick (from 0 up to 10 arguments)
#define ASSERTED_PRIV_EXPAND(x) x
#define ASSERTED_PRIV_PREFIX(...) 0, ##__VA_ARGS__
#define ASSERTED_PRIV_LASTOF12(a, b, c, d, e, f, g, h, i, j, k, l, ...) l
#define ASSERTED_PRIV_SUB_NBARG(...) ASSERTED_PRIV_EXPAND(ASSERTED_PRIV_LASTOF12(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
#define ASSERTED_PRIV_NBARG(...) ASSERTED_PRIV_SUB_NBARG(ASSERTED_PRIV_PREFIX(__VA_ARGS__))
#define ASSERTED_PRIV_GLUE(x, y) x y
#define ASSERTED_PRIV_OVERLOAD_MACRO2(name, count) name##count
#define ASSERTED_PRIV_OVERLOAD_MACRO1(name, count) ASSERTED_PRIV_OVERLOAD_MACRO2(name, count)
#define ASSERTED_PRIV_OVERLOAD_MACRO(name, count) ASSERTED_PRIV_OVERLOAD_MACRO1(name, count)
#define ASSERTED_PRIV_CALL_OVERLOAD(name, ...) \
ASSERTED_PRIV_GLUE(ASSERTED_PRIV_OVERLOAD_MACRO(name, ASSERTED_PRIV_NBARG(__VA_ARGS__)), (__VA_ARGS__))
#define ASSERTED_IS_COMPILE_TIME_ENABLED_(group_) ASSERTED_GROUP_##group_
//-----------------------------------------------------------------------------
// Private implementation
//-----------------------------------------------------------------------------
#if ASSERTED_IS_ENABLED
// Tags assertedPriv's content with the configuration macros that affect its struct layouts and code paths
// (ASSERTED_NO_ASSERT, ASSERTED_NO_SIGNALS, ASSERTED_NO_SIGINT, ASSERTED_NO_DEBUG_BREAK, ASSERTED_WITH_STACKTRACE,
// ASSERTED_NO_COLOR). If two translation units in the same binary are built with different values for these -
// which the README warns against but nothing previously prevented - this makes their content live under distinct,
// non-colliding mangled names instead of silently violating the One Definition Rule (e.g. two different
// GlobalContext layouts sharing one symbol, with whichever definition the linker happens to keep used by every TU).
#define ASSERTED_PRIV_CAT2_(a, b) a##b
#define ASSERTED_PRIV_CAT_(a, b) ASSERTED_PRIV_CAT2_(a, b)
#define ASSERTED_PRIV_CFG_TAG_ \
ASSERTED_PRIV_CAT_( \
cfg, ASSERTED_PRIV_CAT_( \
ASSERTED_NO_ASSERT, \
ASSERTED_PRIV_CAT_(ASSERTED_NO_SIGNALS, \
ASSERTED_PRIV_CAT_(ASSERTED_NO_SIGINT, ASSERTED_PRIV_CAT_(ASSERTED_NO_DEBUG_BREAK, \
ASSERTED_PRIV_CAT_(ASSERTED_WITH_STACKTRACE, \
ASSERTED_NO_COLOR))))))
namespace assertedPriv
{
inline namespace ASSERTED_PRIV_CFG_TAG_
{
// Break inside this function in debugger
void ASSERTED_NORETURN
assertedCrash(const char* message);
#if ASSERTED_NO_ASSERT == 0
// Accumulates a snprintf() return value into offset, clamped to a valid [0, ASSERTED_CRASH_MSG_SIZE-1] range.
// snprintf() returns the length it *would* have written (which can exceed the buffer), or a negative value on an
// encoding error; either way, blindly adding it to offset could push it out of bounds and make a later
// `infoStr + offset` / `(size_t)(ASSERTED_CRASH_MSG_SIZE - offset)` under/overflow.
inline void
advanceOffset_(int& offset, int written)
{
if (written > 0) offset += written;
if (offset > ASSERTED_CRASH_MSG_SIZE - 1) offset = ASSERTED_CRASH_MSG_SIZE - 1;
if (offset < 0) offset = 0;
}
// Declared here (the specializations/overloads below need it declared first) but defined only after them - see
// the definition further down for why.
template<typename T>
inline void
printParamType_(char* infoStr, int& offset, const char* name, T param);
template<typename T>
inline void
printParamType_(char* infoStr, int& offset, const char* name, T* param)
{
advanceOffset_(offset, snprintf(infoStr + offset, (size_t)(ASSERTED_CRASH_MSG_SIZE - offset),
" %-7s %-20s => " ASSERTED_COLOR_NUMBER "%p\n" ASSERTED_COLOR_RESET, "pointer", name, (void*)param));
}
template<>
inline void
printParamType_<std::string>(char* infoStr, int& offset, const char* name, std::string param)
{
advanceOffset_(offset, snprintf(infoStr + offset, (size_t)(ASSERTED_CRASH_MSG_SIZE - offset),
" %-7s %-20s => " ASSERTED_COLOR_NUMBER "%s\n" ASSERTED_COLOR_RESET, "string", name, param.c_str()));
}
template<>
inline void
printParamType_<bool>(char* infoStr, int& offset, const char* name, bool param)
{
advanceOffset_(
offset, snprintf(infoStr + offset, (size_t)(ASSERTED_CRASH_MSG_SIZE - offset),
" %-7s %-20s => " ASSERTED_COLOR_NUMBER "%s\n" ASSERTED_COLOR_RESET, "bool", name, param ? "true" : "false"));
}
template<>
inline void
printParamType_<char>(char* infoStr, int& offset, const char* name, char* param)
{
// The stringified token of a string literal always starts with '"' (e.g. #v for `"text"` is `"\"text\""`),
// whereas the stringified token of an identifier never does. This tells apart the optional leading message
// (a literal, shown unlabeled) from a genuine named char*/const char* context variable (shown with its name,
// like the std::string case above), even though both share the exact same runtime type.
if (name && name[0] == '"') {
advanceOffset_(offset, snprintf(infoStr + offset, (size_t)(ASSERTED_CRASH_MSG_SIZE - offset),
" %-28s => " ASSERTED_COLOR_NUMBER "%s\n" ASSERTED_COLOR_RESET, "message", param));
} else {
advanceOffset_(
offset, snprintf(infoStr + offset, (size_t)(ASSERTED_CRASH_MSG_SIZE - offset),
" %-7s %-20s => " ASSERTED_COLOR_NUMBER "%s\n" ASSERTED_COLOR_RESET, "string", name ? name : "?", param));
}
}
template<>
inline void
printParamType_<const char>(char* infoStr, int& offset, const char* name, const char* param)
{
if (name && name[0] == '"') {
advanceOffset_(offset, snprintf(infoStr + offset, (size_t)(ASSERTED_CRASH_MSG_SIZE - offset),
" %-28s => " ASSERTED_COLOR_NUMBER "%s\n" ASSERTED_COLOR_RESET, "message", param));
} else {
advanceOffset_(
offset, snprintf(infoStr + offset, (size_t)(ASSERTED_CRASH_MSG_SIZE - offset),
" %-7s %-20s => " ASSERTED_COLOR_NUMBER "%s\n" ASSERTED_COLOR_RESET, "string", name ? name : "?", param));
}
}
#define ASSERTED_DECLARE_ASSERT_TYPE(type_, code_, display_) \
template<> \
inline void printParamType_<type_>(char* infoStr, int& offset, const char* name, type_ param) \
{ \
advanceOffset_(offset, \
snprintf(infoStr + offset, (size_t)(ASSERTED_CRASH_MSG_SIZE - offset), \
" %-7s %-20s => " ASSERTED_COLOR_NUMBER "%" #code_ "\n" ASSERTED_COLOR_RESET, #display_, name, param)); \
}
ASSERTED_DECLARE_ASSERT_TYPE(char, d, s8)
ASSERTED_DECLARE_ASSERT_TYPE(unsigned char, u, u8)
ASSERTED_DECLARE_ASSERT_TYPE(short int, d, s16)
ASSERTED_DECLARE_ASSERT_TYPE(unsigned short, u, u16)
ASSERTED_DECLARE_ASSERT_TYPE(int, d, int)
ASSERTED_DECLARE_ASSERT_TYPE(unsigned int, u, u32)
ASSERTED_DECLARE_ASSERT_TYPE(long, ld, s64)
ASSERTED_DECLARE_ASSERT_TYPE(unsigned long, lu, u64)
ASSERTED_DECLARE_ASSERT_TYPE(long long, lld, s64)
ASSERTED_DECLARE_ASSERT_TYPE(unsigned long long, llu, u64)
ASSERTED_DECLARE_ASSERT_TYPE(float, f, float)
ASSERTED_DECLARE_ASSERT_TYPE(double, lf, double)
// Fallback for every type without a dedicated overload above. Defined only now (rather than alongside the other
// overloads) so that, for an enum, the recursive call below to the underlying integer type's own overload is
// visible via ordinary lookup and actually dispatches to one of the numeric printers declared just above, instead
// of recursing back into this same fallback.
template<typename T>
inline void
printParamType_(char* infoStr, int& offset, const char* name, T param)
{
if constexpr (std::is_enum_v<T>) {
printParamType_(infoStr, offset, name, static_cast<std::underlying_type_t<T>>(param));
} else {
advanceOffset_(offset, snprintf(infoStr + offset, (size_t)(ASSERTED_CRASH_MSG_SIZE - offset),
" %s is not a numeric or string type\n", name));
(void)(param);
}
}
template<typename T>
inline void
printParams_(bool isFirst, char* infoStr, int& offset, const char* name, T param)
{
if (isFirst) {
advanceOffset_(offset, snprintf(infoStr + offset, (size_t)(ASSERTED_CRASH_MSG_SIZE - offset),
ASSERTED_COLOR_BLUE " Context:\n" ASSERTED_COLOR_RESET));
}
if (name) {
printParamType_(infoStr, offset, name, param);
}
}
template<typename T, typename... Args>
inline void
printParams_(bool isFirst, char* infoStr, int& offset, const char* name, T value, Args... args)
{
if (isFirst) {
advanceOffset_(offset, snprintf(infoStr + offset, (size_t)(ASSERTED_CRASH_MSG_SIZE - offset),
ASSERTED_COLOR_BLUE " Context:\n" ASSERTED_COLOR_RESET));
}
if (name) {
printParamType_(infoStr, offset, name, value);
}
printParams_(false, infoStr, offset, args...);
}
// Variadic template based assertion display
template<typename... Args>
void ASSERTED_NOINLINE ASSERTED_NORETURN
failedAssert(const char* filename, int lineNbr, const char* function, const char* condition, Args... args)
{
char infoStr[ASSERTED_CRASH_MSG_SIZE];
int offset = 0;
advanceOffset_(offset, snprintf(infoStr, sizeof(infoStr),
ASSERTED_COLOR_RED "[ASSERTED] Assertion failed: " ASSERTED_COLOR_NUMBER "%s\n" ASSERTED_COLOR_BLUE
" Where:\n" ASSERTED_COLOR_RESET " Function => " ASSERTED_COLOR_FUNCTION
"%s\n" ASSERTED_COLOR_RESET " File => " ASSERTED_COLOR_FUNCTION
"%s:" ASSERTED_COLOR_NUMBER "%d\n" ASSERTED_COLOR_RESET,
condition, function, filename, lineNbr));
printParams_(true, infoStr, offset, args...); // Recursive display of provided items
assertedCrash(infoStr);
}
#endif // if ASSERTED_NO_ASSERT==0
#if defined(_MSC_VER) && ASSERTED_WITH_STACKTRACE == 1
extern "C" {
typedef unsigned long(__stdcall* rtlWalkFrameChain_t)(void**, unsigned long, unsigned long);
}
#endif
typedef void (*assertedSignalHandler_t)(int);
inline struct GlobalContext {
bool signalHandlersSaved = false;
#if ASSERTED_NO_SIGNALS == 0 && defined(__unix__)
struct sigaction signalsOldHandlers[7] = {};
void* altStackMemory = nullptr; // Alternate signal stack, to survive SIGSEGV from stack overflow
stack_t altStackOld = {};
#if ASSERTED_NO_DEBUG_BREAK == 0
struct sigaction debugBreakOldHandler = {}; // Defensive fallback SIGTRAP handler, see maybeBreakIntoDebugger_()
bool debugBreakHandlerSaved = false;
#endif
#else
assertedSignalHandler_t signalsOldHandlers[7] = {0};
#endif
#if defined(_MSC_VER)
PVOID exceptionHandler = 0;
#if ASSERTED_WITH_STACKTRACE == 1
rtlWalkFrameChain_t rtlWalkFrameChain = 0;
#endif
#endif // if defined(_MSC_VER)
volatile int inCrash = 0; // Reentrancy guard: set once a crash starts being handled, see assertedCrash()
} gc;
#if ASSERTED_WITH_STACKTRACE == 1
#if defined(__unix__)
// Linux/Unix version.
//
// Only libunwind is used in-process, to capture raw return addresses - no DWARF reading, no demangling, no
// allocation. Turning those addresses into function names and file:line is done out-of-process, by spawning
// ASSERTED_ADDR2LINE_BIN (see its definition above): calling into libdw/__cxa_demangle directly from a signal
// handler, as an earlier version of this file did, risks a deadlock or worse if the thread that faulted was
// itself inside malloc() at the time (e.g. a crash caused by heap corruption), since both call it internally.
//
// fork() and the whole exec() family are POSIX async-signal-safe, and are the only two "risky-sounding" calls
// used here. Critically, argv is built entirely by the parent *before* forking, so the forked child does nothing
// beyond dup2()/close()/execvp() - also async-signal-safe - before its image is replaced outright by exec(), or
// it _exit()s if that failed: it never reuses the (possibly broken) inherited allocator state, which is what
// actually makes this safe, unlike the previous in-process approach. The /proc/self/maps parsing in between uses
// only open()/read()/close() plus plain string/number parsing (no stdio buffering, no allocation) - not
// officially on the async-signal-safe list, but with no shared/lockable state of their own, which is the
// specific hazard being avoided here.
// Describes one file-backed, executable mapping found in /proc/self/maps.
struct MappedModule_ {
uintptr_t start = 0;
uintptr_t end = 0;
uintptr_t bias = 0; // This mapping's start address minus its offset inside the backing file
char path[192] = {0};
};
// Parses one already null-terminated "/proc/self/maps" line. Returns true and fills *outModule if it describes a
// file-backed executable mapping - the only kind that can contain a return address addr2line can resolve.
inline bool
parseMapsLine_(const char* line, MappedModule_& outModule)
{
char* endp = nullptr;
unsigned long long start = strtoull(line, &endp, 16);
if (endp == line || *endp != '-') return false;
const char* p = endp + 1;
unsigned long long end = strtoull(p, &endp, 16);
if (endp == p) return false;
p = endp;
while (*p == ' ') ++p;
const char* perms = p;
while (*p && *p != ' ') ++p;
if (p - perms < 3 || perms[2] != 'x') return false; // Not executable: cannot hold a return address
while (*p == ' ') ++p;
unsigned long long fileOffset = strtoull(p, &endp, 16);
if (endp == p) return false;
const char* slash = strchr(endp, '/');
if (!slash) return false; // Anonymous mapping: no backing file for addr2line to read
outModule.start = (uintptr_t)start;
outModule.end = (uintptr_t)end;
outModule.bias = (uintptr_t)start - (uintptr_t)fileOffset;
size_t len = strlen(slash);
if (len >= sizeof(outModule.path)) len = sizeof(outModule.path) - 1;
memcpy(outModule.path, slash, len);
outModule.path[len] = 0;
return true;
}
// Reads "/proc/self/maps" (open()/read()/close() only) and fills modules[] with the file-backed executable
// mappings found in it. Returns how many were found.
inline int
buildModuleTable_(char* buf, size_t bufSize, MappedModule_* modules, int maxModules)
{
int fd = open("/proc/self/maps", O_RDONLY);
if (fd < 0) return 0;
size_t total = 0;
while (total + 1 < bufSize) {
ssize_t n = read(fd, buf + total, bufSize - 1 - total);
if (n <= 0) break;
total += (size_t)n;
}
close(fd);
buf[total] = 0;
int count = 0;
char* line = buf;
while (line && *line && count < maxModules) {
char* nextLine = strchr(line, '\n');
if (nextLine) *nextLine = 0;
if (parseMapsLine_(line, modules[count])) ++count;
line = nextLine ? nextLine + 1 : nullptr;
}
return count;
}
// Returns the index of the mapping containing 'addr', or -1.
inline int
findModule_(const MappedModule_* modules, int moduleQty, uintptr_t addr)
{
for (int i = 0; i < moduleQty; ++i) {
if (addr >= modules[i].start && addr < modules[i].end) return i;
}
return -1;
}
// Runs `addr2line -e modulePath -f -C -p -s <addrs...>` and captures its stdout into outBuf: one
// "function at file:line" pretty-printed line per requested address, in the same order (unresolved ones read as
// "?? at ??:?"). Returns false, leaving outBuf untouched, if the tool could not be run at all (e.g. not
// installed) or exited with an error - the caller then falls back to raw addresses for that batch.
inline bool
runAddr2Line_(const char* modulePath, const uintptr_t* addrs, int addrQty, char* outBuf, size_t outBufSize)
{
constexpr int MaxBatch = 48;
if (addrQty <= 0 || addrQty > MaxBatch) return false;
// Build argv fully before forking: the child must not construct anything itself, only hand off to exec().
char hexAddrs[MaxBatch][2 + sizeof(uintptr_t) * 2 + 1];
const char* argv[8 + MaxBatch + 1];
int argc = 0;
argv[argc++] = ASSERTED_ADDR2LINE_BIN;
argv[argc++] = "-e";
argv[argc++] = modulePath;
argv[argc++] = "-f";
argv[argc++] = "-C";
argv[argc++] = "-p";
argv[argc++] = "-s";
for (int i = 0; i < addrQty; ++i) {
snprintf(hexAddrs[i], sizeof(hexAddrs[i]), "0x%llx", (unsigned long long)addrs[i]);
argv[argc++] = hexAddrs[i];
}
argv[argc] = nullptr;
int pipeFds[2];
if (pipe(pipeFds) != 0) return false;
pid_t child = fork();
if (child < 0) {
close(pipeFds[0]);
close(pipeFds[1]);
return false;
}
if (child == 0) {
// Child: only async-signal-safe calls until execvp() replaces this image outright.
dup2(pipeFds[1], STDOUT_FILENO);
close(pipeFds[0]);
close(pipeFds[1]);
int devNull = open("/dev/null", O_WRONLY);
if (devNull >= 0) dup2(devNull, STDERR_FILENO);
execvp(ASSERTED_ADDR2LINE_BIN, (char* const*)argv);
_exit(127); // Only reached if execvp() itself failed (e.g. the tool is not installed)
}
// Parent: read the child's output, then reap it.
close(pipeFds[1]);
size_t total = 0;
while (total + 1 < outBufSize) {
ssize_t n = read(pipeFds[0], outBuf + total, outBufSize - 1 - total);
if (n <= 0) break;
total += (size_t)n;
}
outBuf[total] = 0;
close(pipeFds[0]);
int status = 0;
waitpid(child, &status, 0);
return WIFEXITED(status) && WEXITSTATUS(status) == 0 && total > 0;
}
inline void
crashLogStackTrace(void)
{
// Capture raw return addresses only - see the comment above for why resolving them happens further down.
unw_context_t uc;
unw_getcontext(&uc);
unw_cursor_t cursor;
unw_init_local(&cursor, &uc);
unw_word_t offset;
constexpr int MaxStackLines = 48;
// Scratch state below is static (not stack-allocated): it keeps the alternate signal stack small and, since
// GlobalContext::inCrash already ensures only one crash is handled process-wide at a time (see
// assertedCrash()), sharing it is safe in practice even though it is not itself thread-safe.
static uintptr_t addrs[MaxStackLines];
int addrQty = 0;
char tmpStr[128];
const int skipDepthQty = 2; // No need to display the bottom machinery (assertedCrash(), signalHandler())
int depth = 0;
while (unw_step(&cursor) > 0) {
unw_word_t ip;
unw_get_reg(&cursor, UNW_REG_IP, &ip);
if (depth >= skipDepthQty) {
// The frame libunwind itself flags as a signal frame is exactly where execution was interrupted, so
// it and everything after it is meaningful. Anything captured before it, on the other hand, is the
// kernel/libc signal-delivery trampoline rather than real caller frames: it can still "successfully"
// unwind to a plausible-looking but unrelated nearby symbol instead of failing outright, so discard
// whatever was captured so far as soon as the real starting point is found. Without an actual signal
// involved (e.g. a plain failed assertion, not a crash), no frame is ever flagged and this is a
// no-op - capturing just proceeds from skipDepthQty as usual.
if (unw_is_signal_frame(&cursor) > 0) addrQty = 0;
if (addrQty < MaxStackLines) addrs[addrQty++] = (uintptr_t)(ip - 4);
}
tmpStr[0] = 0;
unw_get_proc_name(&cursor, tmpStr, sizeof(tmpStr), &offset); // Fails if there is no debug symbols
if (!strcmp(tmpStr, "main")) break;
++depth;
} // End of unwinding
// Resolve which module (executable/shared library) each address belongs to and its file-relative address
static char mapsBuf[64 * 1024];
static MappedModule_ modules[128];
int moduleQty = buildModuleTable_(mapsBuf, sizeof(mapsBuf), modules, 128);
static int moduleIdx[MaxStackLines];
static uintptr_t vaddr[MaxStackLines];
for (int i = 0; i < addrQty; ++i) {
moduleIdx[i] = findModule_(modules, moduleQty, addrs[i]);
vaddr[i] = (moduleIdx[i] >= 0) ? addrs[i] - modules[moduleIdx[i]].bias : 0;
}
struct StackLine {
char filenameAndLineNbr[128];
char functionName[256];
int firstPartSize;
};
static StackLine lines[MaxStackLines];
int lineQty = 0;
int maxFirstPartSize = 0;
// Symbolize in per-module runs: consecutive frames commonly share the same module (e.g. deep recursion, or a
// whole stack local to the main executable), so this is typically one or two addr2line invocations for the
// entire stack rather than one per frame.
static char resolveBuf[8192];
for (int i = 0; i < addrQty;) {
int runEnd = i + 1;
while (runEnd < addrQty && moduleIdx[runEnd] == moduleIdx[i]) ++runEnd;
bool resolved =
(moduleIdx[i] >= 0) && runAddr2Line_(modules[moduleIdx[i]].path, &vaddr[i], runEnd - i, resolveBuf, sizeof(resolveBuf));
char* outLine = resolveBuf;
for (int frame = i; frame < runEnd; ++frame) {
StackLine& l = lines[lineQty++];
char* thisLine = nullptr;
if (resolved && outLine) {
thisLine = outLine;
char* nextLine = strchr(outLine, '\n');
if (nextLine) {
*nextLine = 0;
outLine = nextLine + 1;
} else {
outLine = nullptr;
}
}
if (thisLine) {
const char* sep = strstr(thisLine, " at ");
const char* func = thisLine;
size_t funcLen = sep ? (size_t)(sep - thisLine) : strlen(thisLine);
const char* loc = sep ? sep + 4 : nullptr;
const char* lastColon = loc ? strrchr(loc, ':') : nullptr;
if (loc && lastColon) {
snprintf(l.filenameAndLineNbr, sizeof(l.filenameAndLineNbr),
" #" ASSERTED_COLOR_NUMBER "%-2d " ASSERTED_COLOR_RESET "%.*s:" ASSERTED_COLOR_NUMBER "%s ", frame,
(int)(lastColon - loc), loc, lastColon + 1);
} else {
snprintf(l.filenameAndLineNbr, sizeof(l.filenameAndLineNbr),
" #" ASSERTED_COLOR_NUMBER "%-2d " ASSERTED_COLOR_RESET "0x%llx" ASSERTED_COLOR_NUMBER, frame,
(unsigned long long)addrs[frame]);
}
snprintf(l.functionName, sizeof(l.functionName), ASSERTED_COLOR_FUNCTION "%.*s", (int)funcLen, func);
} else {
snprintf(l.filenameAndLineNbr, sizeof(l.filenameAndLineNbr),
" #" ASSERTED_COLOR_NUMBER "%-2d " ASSERTED_COLOR_RESET "0x%llx" ASSERTED_COLOR_NUMBER, frame,
(unsigned long long)addrs[frame]);
snprintf(l.functionName, sizeof(l.functionName), ASSERTED_COLOR_FUNCTION "<unknown>");
}
l.firstPartSize = (int)strlen(l.filenameAndLineNbr);
if (l.firstPartSize > maxFirstPartSize) maxFirstPartSize = l.firstPartSize;
}
i = runEnd;
}
// Display the stack trace. Thanks to this 2-pass, the functions are aligned.
for (int lineNbr = 0; lineNbr < lineQty; ++lineNbr) {
StackLine& l = lines[lineNbr];
ASSERTED_MESSAGE(l.filenameAndLineNbr, false);
snprintf(tmpStr, sizeof(tmpStr), "%*s", maxFirstPartSize - l.firstPartSize, "");
ASSERTED_MESSAGE(tmpStr, false);
ASSERTED_MESSAGE(l.functionName, false);
// Avoid long line truncation
ASSERTED_MESSAGE(ASSERTED_COLOR_RESET "\n", false);
}
// End session
ASSERTED_MESSAGE("\n", false);
}
#endif // if defined(__unix__)
#if defined(_MSC_VER)
// Windows version
inline void
crashLogStackTrace(void)
{
char tmpStr[128];
char depthStr[8];
// Get the addresses of the stacktrace
constexpr int MaxStackLines = 64; // 64 levels of depth should be enough for everyone
struct StackLine {
char filenameAndLineNbr[128];
char functionName[256];
int firstPartSize;
};
StackLine lines[MaxStackLines];
int lineQty = 0;
int maxFirstPartSize = 0;
PVOID stacktrace[MaxStackLines];
int foundStackDepth = gc.rtlWalkFrameChain ? gc.rtlWalkFrameChain(stacktrace, 64, 0) : 0;
// Some required windows structures for the used APIs
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
DWORD displacement = 0;
constexpr int MaxNameSize = 8192;
char symBuffer[sizeof(SYMBOL_INFO) + MaxNameSize];
SYMBOL_INFO* symInfo = (SYMBOL_INFO*)symBuffer;
symInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
symInfo->MaxNameLen = MaxNameSize;
HANDLE proc = GetCurrentProcess();
#define ASSERTED_CRASH_STACKTRACE_DUMP_INFO_(itemNbrStr) \
if (isFuncValid || isLineValid) { \
snprintf(tmpStr, sizeof(tmpStr), ":%u", isLineValid ? line.LineNumber : 0); \
const char* shortFileName = "<unknown>"; \
if (isLineValid) { \
const char* backslash = strrchr(line.FileName, '\\'); \
shortFileName = backslash ? backslash + 1 : line.FileName; \
} \
snprintf(l.filenameAndLineNbr, sizeof(l.filenameAndLineNbr), \
" " ASSERTED_COLOR_NUMBER "%s " ASSERTED_COLOR_RESET "%s" ASSERTED_COLOR_NUMBER "%s ", itemNbrStr, shortFileName, \
isLineValid ? tmpStr : ""); \
snprintf(l.functionName, sizeof(l.functionName), ASSERTED_COLOR_FUNCTION "%s", isFuncValid ? symInfo->Name : "<unknown>"); \
} else { \
snprintf(l.filenameAndLineNbr, sizeof(l.filenameAndLineNbr), \
" " ASSERTED_COLOR_NUMBER "%s" ASSERTED_COLOR_FUNCTION " 0x%" PRIX64 ASSERTED_COLOR_RESET, itemNbrStr, ptr); \
l.functionName[0] = 0; \
} \
l.firstPartSize = (int)strlen(l.filenameAndLineNbr); \
if (l.firstPartSize > maxFirstPartSize) maxFirstPartSize = l.firstPartSize;
constexpr int skipDepthQty = 3; // No need to display the bottom machinery
for (int depth = skipDepthQty; depth < foundStackDepth; ++depth) {
// -1 because the captured PC is already pointing on the next code line at snapshot time
uint64_t ptr = ((uint64_t)stacktrace[depth]) - 1;
// Get the nested inline function calls, if any
DWORD frameIdx, curContext = 0;
int inlineQty = SymAddrIncludeInlineTrace(proc, ptr);
if (inlineQty > 0 && SymQueryInlineTrace(proc, ptr, 0, ptr, ptr, &curContext, &frameIdx)) {
for (int i = 0; i < inlineQty; ++i) {
bool isFuncValid = (SymFromInlineContext(proc, ptr, curContext, 0, symInfo) != 0);
bool isLineValid = (SymGetLineFromInlineContext(proc, ptr, curContext, 0, &displacement, &line) != 0);
++curContext;
if (lineQty < MaxStackLines) {
StackLine& l = lines[lineQty++];
ASSERTED_CRASH_STACKTRACE_DUMP_INFO_("inl");
}
}
}
// Get the function call for this depth
if (lineQty < MaxStackLines) {
StackLine& l = lines[lineQty++];
bool isFuncValid = (SymFromAddr(proc, ptr, 0, symInfo) != 0);
bool isLineValid = (SymGetLineFromAddr64(proc, ptr - 1, &displacement, &line) != 0);
snprintf(depthStr, sizeof(depthStr), "#%-2d", depth - skipDepthQty);
ASSERTED_CRASH_STACKTRACE_DUMP_INFO_(depthStr);
}
} // End of loop on stack depth
// Display the stack trace. Thanks to this 2-pass, the functions are aligned.
for (int lineNbr = 0; lineNbr < lineQty; ++lineNbr) {
StackLine& l = lines[lineNbr];
ASSERTED_MESSAGE(l.filenameAndLineNbr, false);
snprintf(tmpStr, sizeof(tmpStr), "%*s", maxFirstPartSize - l.firstPartSize, "");
ASSERTED_MESSAGE(tmpStr, false);
ASSERTED_MESSAGE(l.functionName, false);
// Avoid long line truncation
ASSERTED_MESSAGE(ASSERTED_COLOR_RESET "\n", false);
}
}
#endif // if defined(_MSC_VER)
#endif // if ASSERTED_WITH_STACKTRACE == 1
#if ASSERTED_NO_DEBUG_BREAK == 0
#if defined(__unix__)
// Returns true if a ptrace-based tracer (a debugger like gdb, or e.g. strace) is attached, by reading the
// TracerPid field of /proc/self/status. Uses only open()/read()/close(): no stdio buffering, no allocation.
inline bool
isDebuggerPresent_(void)
{
char buf[4096];
int fd = open("/proc/self/status", O_RDONLY);
if (fd < 0) return false;
ssize_t n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0) return false;
buf[n] = 0;
const char* tag = strstr(buf, "TracerPid:");
return tag && strtol(tag + 10, nullptr, 10) != 0;
}
#endif // if defined(__unix__)
// Traps into an attached debugger right at the point where the process is about to exit because of a crash, and
// is a complete no-op otherwise, so a run without a debugger is unaffected.
//
// On Linux/Unix: raise(SIGTRAP) is only ever called after confirming, via isDebuggerPresent_(), that a tracer is
// actually attached - gdb's default handling of SIGTRAP is to stop and not pass it to the program, so this halts
// execution right here without ever reaching debugBreakSignalHandler() (declared below, in the signal-handling
// section). That handler exists purely as a defensive fallback for e.g. the tracer detaching between the check
// and the raise: if SIGTRAP is ever delivered with nothing to intercept it, it does nothing and execution simply
// continues, rather than the process being killed by SIGTRAP's default disposition.
//
// On Windows: IsDebuggerPresent() is the direct equivalent check, and __debugbreak() the trap instruction. The
// existing VEH handler already declines to handle EXCEPTION_BREAKPOINT itself (see exceptionHandler() below),
// deferring to whichever debugger the OS delivered the first-chance exception to.
inline void
maybeBreakIntoDebugger_(void)
{
#if defined(__unix__)
if (isDebuggerPresent_()) raise(SIGTRAP);
#elif defined(_MSC_VER)
if (IsDebuggerPresent()) __debugbreak();
#endif
}
#endif // if ASSERTED_NO_DEBUG_BREAK==0
inline void ASSERTED_NORETURN
assertedCrash(const char* message)
{
// Reentrancy guard: a crash occurring while already handling one (a different signal firing mid-handling, or
// the handler itself faulting) bails out immediately instead of re-running through possibly broken state.
if (gc.inCrash) {
std::_Exit(1);
}
gc.inCrash = 1;
// Log and display the crash message
ASSERTED_MESSAGE(message, false);