how to trace function call in C?

后端 未结 8 1706
遇见更好的自我
遇见更好的自我 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:26

    I also encountered this problem of having good function call traces. Therefore, I wrote a Python GDB script (https://gist.github.com/stettberger/e6f2fe61206471e22e9e6f1926668093) that sets a breakpoint on every interesting function (defined by the environment variable TRACE_FUNCTION). GDB then invokes the python function, which decodes the frame and all its arguments. If it encounters a pointer it tries to dereference it and so print a function call trace to TRACE_FILE (default: /tmp/log) with arguments. For the following program

    #include 
    
    struct foo {
        int a;
        struct foo * next;
    };
    
    int fib(int a, struct foo *b) {
        if (a <= 1) return 1;
        printf("%d\n", a);
        return fib(a-1, 0)+fib(a-2, 0);
    }
    
    int main() {
        struct foo b = {23, 0};
        return fib(5, &b);
    }
    

    I get a detailed trace, where every line is a python tuple that can be read with eval():

    ('call', None, 1, 'main', 'main', {})
    ('call', 1, 2, 'fib', 'fib', {'a': {'type': 'int', 'value': 5}, 'b': {'type': 'struct foo *', 'value': 140737488344320, 'deref': {'type': 'struct foo', 'value': {'a': {'type': 'int', 'value': 23}, 'next': {'type': 'struct foo *', 'value': 0, 'deref': None}}}}})
    ('call', 2, 3, 'fib', 'fib', {'a': {'type': 'int', 'value': 4}, 'b': {'type': 'struct foo *', 'value': 0, 'deref': None}})
    ....
    ('return', 'fib', 2, {'type': 'int', 'value': 8})
    ('exit', 8)
    

    The gist contains more information on the log file format.

提交回复
热议问题