如何使 backtrace()/backtrace_symbols() 打印函数名称? [英] How to make backtrace()/backtrace_symbols() print the function names?
问题描述
Linux 特定的backtrace()
和backtrace_symbols()
允许您生成程序的调用跟踪.但是,它只打印函数地址,而不是我的程序的名称.我怎样才能让他们也打印函数名称?我试过用 -g
和 -ggdb
编译程序.下面的测试用例只是打印这个:
我希望前 2 项也显示函数名称,foo
和 main
代码:
#include #include #include #include #include static void full_write(int fd, const char *buf, size_t len){而 (len > 0) {ssize_t ret = write(fd, buf, len);if ((ret == -1) && (errno != EINTR))休息;buf += (size_t) ret;len -= (size_t) ret;}}无效print_backtrace(无效){static const char start[] = "BACKTRACE ------------
";static const char end[] = "----------------------
";无效* bt [1024];int bt_size;字符 **bt_syms;国际我;bt_size = 回溯(bt,1024);bt_syms = backtrace_symbols(bt, bt_size);full_write(STDERR_FILENO, start, strlen(start));for (i = 1; i < bt_size; i++) {size_t len = strlen(bt_syms[i]);full_write(STDERR_FILENO, bt_syms[i], len);full_write(STDERR_FILENO, "
", 1);}full_write(STDERR_FILENO, end, strlen(end));免费(bt_syms);}空 foo(){打印回溯();}int main(){富();返回0;}
符号取自动态符号表;您需要gcc
的-rdynamic
选项,这使它向链接器传递一个标志,以确保所有 符号都放置在表中.
(请参阅 GCC 手册,和/或 glibc 手册的>回溯页面.)
The Linux specific backtrace()
and backtrace_symbols()
allows you to produce a call trace of the program. However, it only prints function addresses, not their names for my program. How can I make them print the function names as well ? I've tried compiling the program with -g
as well as -ggdb
. The test case below just prints this:
BACKTRACE ------------ ./a.out() [0x8048616] ./a.out() [0x8048623] /lib/libc.so.6(__libc_start_main+0xf3) [0x4a937413] ./a.out() [0x8048421] ----------------------
I'd want the first 2 items to also show the function names, foo
and main
Code:
#include <execinfo.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
static void full_write(int fd, const char *buf, size_t len)
{
while (len > 0) {
ssize_t ret = write(fd, buf, len);
if ((ret == -1) && (errno != EINTR))
break;
buf += (size_t) ret;
len -= (size_t) ret;
}
}
void print_backtrace(void)
{
static const char start[] = "BACKTRACE ------------
";
static const char end[] = "----------------------
";
void *bt[1024];
int bt_size;
char **bt_syms;
int i;
bt_size = backtrace(bt, 1024);
bt_syms = backtrace_symbols(bt, bt_size);
full_write(STDERR_FILENO, start, strlen(start));
for (i = 1; i < bt_size; i++) {
size_t len = strlen(bt_syms[i]);
full_write(STDERR_FILENO, bt_syms[i], len);
full_write(STDERR_FILENO, "
", 1);
}
full_write(STDERR_FILENO, end, strlen(end));
free(bt_syms);
}
void foo()
{
print_backtrace();
}
int main()
{
foo();
return 0;
}
The symbols are taken from the dynamic symbol table; you need the -rdynamic
option to gcc
, which makes it pass a flag to the linker which ensures that all symbols are placed in the table.
(See the Link Options page of the GCC manual, and / or the Backtraces page of the glibc manual.)
这篇关于如何使 backtrace()/backtrace_symbols() 打印函数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!