how to trace function call in C?

后端 未结 8 1680
遇见更好的自我
遇见更好的自我 2020-12-02 13:45

Without modifying the source code, how can i trace which functions are called and with what parameters, when some function(say func100 in the following example) is in

8条回答
  •  有刺的猬
    2020-12-02 14:34

    With the GNU C Library, you can use the backtrace module. Here is an example for that:

    #include 
    #include 
    #include 
    
    
    void handler(char *caller) {
      void *array[10];
      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)[0x80486f1]
    ./Test(car+0x12)[0x804872e]
    ./Test(baz+0xb)[0x8048747]
    ./Test(bar+0xb)[0x8048754]
    ./Test(foo+0xb)[0x8048761]
    ./Test(main+0xb)[0x804876e]
    /lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xe7)[0x126e37]
    ./Test[0x8048631]
    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.

提交回复
热议问题