本篇 ShengYu 介紹 C/C++ dump stack backtrace 的方法,
C/C++ 印出 backtrace 的方法如下,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// g++ -g -rdynamic cpp-backtrace.cpp -o a.out
void print_backtrace() {
void *buffer[64];
char **symbols;
int num = backtrace(buffer, 64);
printf("backtrace() returned %d addresses\n", num);
symbols = backtrace_symbols(buffer, num);
if (symbols == NULL) {
perror("backtrace_symbols");
exit(EXIT_FAILURE);
}
for (int j = 0; j < num; j++)
printf("%s\n", symbols[j]);
free(symbols);
}
void myfunc3() {
print_backtrace();
}
void myfunc2() {
myfunc3();
}
void myfunc1() {
myfunc2();
}
int main() {
myfunc1();
}
輸出如下,1
2
3
4
5
6
7
8backtrace() returned 7 addresses
./a.out(_Z15print_backtracev+0x2e) [0x400a94]
./a.out(_Z7myfunc3v+0x9) [0x400b79]
./a.out(_Z7myfunc2v+0x9) [0x400b85]
./a.out(_Z7myfunc1v+0x9) [0x400b91]
./a.out(main+0x9) [0x400b9d]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7fb39bc04840]
./a.out(_start+0x29) [0x400999]
用 addr2line 來看 0x400a94 address 是在程式碼的那一行,1
2
3addr2line -fie a.out 0x400a94
_Z15print_backtracev
cpp-backtrace.cpp:9
發現輸出結果 _Z15print_backtracev 看得似懂非懂,addr2line 加上 -C
來解析 C++ 的名稱,這樣就解決了!1
2
3
4
5
6
7
8
9
10
11
12
13
14
15addr2line -Cfie a.out 0x400a94
print_backtrace()
cpp-backtrace.cpp:9
$ addr2line -Cfie a.out 0x400b79
myfunc3()
cpp-backtrace.cpp:30
$ addr2line -Cfie a.out 0x400b85
myfunc2()
cpp-backtrace.cpp:34
$ addr2line -Cfie a.out 0x400b91
myfunc1()
cpp-backtrace.cpp:38
$ addr2line -Cfie a.out 0x400b9d
main
cpp-backtrace.cpp:42
在這篇是乾脆就順便用 abi::__cxa_demangle()
直接解析出 C++ 的符號了,過程中需要自行從 symbols 裡的 mangled function name 擷取出來後在執行 abi::__cxa_demangle()
,還蠻費工的~
其它參考
Unix backtrace
https://man7.org/linux/man-pages/man3/backtrace.3.html
Windows CaptureBackTrace
http://msdn.microsoft.com/en-us/library/windows/desktop/bb204633(v=vs.85).aspx
C++ Code Snippet - Print Stack Backtrace Programmatically with Demangled Function Names
https://panthema.net/2008/0901-stacktrace-demangled/
C++的backtrace
https://owent.net/2018/1801.html