assert-backtrace.c
1.49 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
// vim:set ts=4 sw=4 ai et:
#include <stdio.h>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
/*
Compile with "-rdynamic" to include function names in the backtrace output
Example output:
$ gcc -rdynamic -Werror assert-backtrace.c && ./a.out
Backtrace:
1 a.out(quux+0x9) [0x55d540c74cd4]
2 a.out(qux+0xe) [0x55d540c74d08]
3 a.out(baz+0xe) [0x55d540c74d19]
4 a.out(bar+0xe) [0x55d540c74d2a]
5 a.out(foo+0xe) [0x55d540c74d3b]
6 a.out(main+0x19) [0x55d540c74d57]
7 /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe7) [0x7fdc6b424b97]
8 a.out(_start+0x2a) [0x55d540c74a5a]
a.out: assert-backtrace.c:57: quux: Assertion `0 && "test assertion" || printbt()' failed.
Aborted (core dumped)
*/
#define assert_bt(...) assert(__VA_ARGS__ || printbt())
#define STACK_DEPTH 20
int printbt(void)
{
void *buffer[STACK_DEPTH];
char **strings;
int size, i;
size = backtrace(buffer, STACK_DEPTH);
strings = backtrace_symbols(buffer, size);
fprintf(stderr, "Backtrace:\n\n");
for (i = 1; i < size; i++) {
if (strings[i][0] == '.' && strings[i][1] == '/')
strings[i] += 2;
fprintf(stderr, " %3d %s\n", i, strings[i]);
}
fprintf(stderr, "\n");
return 0;
}
void quux() { assert_bt(0 && "test assertion"); }
void qux() { quux(); }
void baz() { qux(); }
void bar() { baz(); }
void foo() { bar(); }
int main(int argc, char **argv)
{
foo();
return 0;
}