一、源码
使用 backtrace 获得 Linux 函数调用栈
源码来自:man backtrace
#include
#include
#include
#include
void myfunc3(void)
{
int j, nptrs;
#define SIZE 100
void *buffer[100];
char **strings;
nptrs = backtrace(buffer, SIZE);
printf("backtrace() returned %d addresses\n", nptrs);
/* The call backtrace_symbols_fd(buffer, nptrs, STDOUT_FILENO)
would produce similar output to the following: */
strings = backtrace_symbols(buffer, nptrs);
if (strings == NULL) {
perror("backtrace_symbols");
exit(EXIT_FAILURE);
}
for (j = 0; j < nptrs; j++)
printf("%s\n", strings[j]);
free(strings);
}
/* "static" means don't export the symbol... */
static void myfunc2(void)
{
myfunc3();
}
void myfunc(int ncalls)
{
if (ncalls > 1)
myfunc(ncalls - 1);
else
myfunc2();
}
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "%s num-calls\n", argv[0]);
exit(EXIT_FAILURE);
}
myfunc(atoi(argv[1]));
exit(EXIT_SUCCESS);
}
二、函数地址
编译并运行,只能看得函数地址:
$ gcc main.c
$ ./a.out 3
backtrace() returned 8 addresses
./a.out() [0x400844]
./a.out() [0x400912]
./a.out() [0x40093a]
./a.out() [0x400933]
./a.out() [0x400933]
./a.out() [0x400996]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f1eee52f830]
./a.out() [0x400749]
三、函数名称
尝试修改编译参数,然后运行,可以看得函数名称,但看不到行号:
$ gcc -rdynamic main.c
$ ./a.out 3
backtrace() returned 8 addresses
./a.out(myfunc3+0x2e) [0x400af4]
./a.out() [0x400bc2]
./a.out(myfunc+0x25) [0x400bea]
./a.out(myfunc+0x1e) [0x400be3]
./a.out(myfunc+0x1e) [0x400be3]
./a.out(main+0x59) [0x400c46]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7fbfad119830]
./a.out(_start+0x29) [0x4009f9]
四、函数源文件和行号
尝试通过 addr2line 试图源文件名和行号,但依旧看不到:
$ addr2line 0x400af4 -e ./a.out -f
myfunc3
??:?
修改编译参数,添加调试信息,再次尝试,可以看到:
$ gcc -rdynamic main.c -g
$ ./a.out 3
backtrace() returned 8 addresses
./a.out(myfunc3+0x2e) [0x400af4]
./a.out() [0x400bc2]
./a.out(myfunc+0x25) [0x400bea]
./a.out(myfunc+0x1e) [0x400be3]
./a.out(myfunc+0x1e) [0x400be3]
./a.out(main+0x59) [0x400c46]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f7ce2c62830]
./a.out(_start+0x29) [0x4009f9]
likui@likui:~/dev/demo/trace$ addr2line 0x400af4 -e ./a.out -f
myfunc3
/home/likui/dev/demo/trace/main.c:13
五、例外:static 函数
但如果执行如下命令,会发现看不到 myfunc2 的信息。因为没有导出该函数符号。
$ ./a.out 2
backtrace() returned 7 addresses
./a.out(myfunc3+0x2e) [0x400af4]
./a.out() [0x400bc2]
./a.out(myfunc+0x25) [0x400bea]
./a.out(myfunc+0x1e) [0x400be3]
./a.out(main+0x59) [0x400c46]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0) [0x7f745daea830]
./a.out(_start+0x29) [0x4009f9]
参考
1. 利用backtrace和backtrace_symbols打印函数的调用关系:http://blog.csdn.net/wind19/article/details/6105617
2. 栈调用关系跟踪:http://blog.chinaunix.net/uid-24774106-id-3457205.html
3. 高效获得Linux函数调用栈/backtrace的方法:http://blog.csdn.net/littlefang/article/details/42295803