// vim:set ts=4 sw=4 ai et: #include #include #include #include #include #include /* 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; }