camber_hu 发表于 2012-08-27 23:24

如何打印出call trace中的函数名

写了个程序,当程序异常时,捕捉内核发送的信号,然后想把栈上的call trace打印出来;

问题是,栈上都是函数地址,如何找到地址所对应的函数名呢?

我目前都是手动反汇编ELF文件,然后根据地址去找函数,有没有方法可以让程序自己找到地址所对应的函数名呢?

MMMIX 发表于 2012-08-28 09:43

回复 1# camber_hu


    http://stackoverflow.com/questions/10374005/how-to-trace-function-call-in-c

xiyoulaoyuanjia 发表于 2012-08-28 11:46

连接十分不错~~刚刚的~~   :em03:With the GNU C Library, you can use the backtrace module. Here is an example for that:

#include <stdio.h>
#include <execinfo.h>
#include <stdlib.h>


void handler(char *caller) {
void *array;
size_t size;
printf("Stack Trace Start for %s\n",caller);
size = backtrace(array, 10);
backtrace_symbols_fd(array, size, 2);
printf("Stack Trace End\n");
}

void car() {
    handler("car()");
    printf("Continue Execution");
}
void baz() {car(); }

void bar() { baz(); }
void foo() { bar(); }


int main(int argc, char **argv) {
foo();
}
compile with -g -rdynamic compiler option to load the symbols

gcc -g -rdynamic Test1.c -o Test
You will see an output similar to

Stack Trace Start for car()
./Test(handler+0x2d)
./Test(car+0x12)
./Test(baz+0xb)
./Test(bar+0xb)
./Test(foo+0xb)
./Test(main+0xb)
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xe7)
./Test
Stack Trace End
Continue Execution in car
You can write this handler function and call from anywhere in your program at any number of time. Remember to increase the array size as required.

ivy_zhao 发表于 2014-10-31 15:38

Very good. Thank you very much!
页: [1]
查看完整版本: 如何打印出call trace中的函数名