how to trace function call in C?

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

    Sometimes I have to trace lots of function calls, even for external libraries I don't have any control, or I don't want to modify.

    Sometime ago, I realized that you can combine gdb's regular expression breakpoints (regular ones are ok, too) and then just execute a set of commands to be run each time those breakpoints are triggered. See: http://www.ofb.net/gnu/gdb/gdb_35.html

    For example, if you want to trace all the functions which start with "MPI_" prefix, you can do:

    (gdb) rbreak MPI_
    [...]
    (gdb) command 1-XX
    (gdb) silent
    (gdb) bt 1
    (gdb) echo \n\n
    (gdb) continue
    (gdb) end
    

    Silent command is used to hide gdb messages when a breakpoint is found. I usually print a couple of empty lines, so that it is easier to read.

    Then, you just run the program: (gdb) run

    Once your program starts running, gdb will print the N topmost backtrace levels.

    #0  0x000000000040dc60 in MPI_Initialized@plt ()
    
    
    #0  PMPI_Initialized (flag=0x7fffffffba78) at ../../src/mpi/init/initialized.c:46
    
    
    #0  0x000000000040d9b0 in MPI_Init_thread@plt ()
    
    
    #0  PMPI_Init_thread (argc=0x7fffffffbe78, argv=0x7fffffffbde0, required=3, provided=0x7fffffffba74) at ../../src/mpi/init/initthread.c:946
    
    
    #0  0x000000000040e390 in MPI_Comm_rank@plt ()
    
    
    #0  PMPI_Comm_rank (comm=1140850688, rank=0x7fffffffba7c) at ../../src/mpi/comm/comm_rank.c:53
    
    
    #0  0x000000000040e050 in MPI_Type_create_struct@plt ()
    
    
    #0  PMPI_Type_create_struct (count=3, array_of_blocklengths=0x7fffffffba90, array_of_displacements=0x7fffffffbab0, array_of_types=0x7fffffffba80, newtype=0x69de20) at ../../src/mpi/datatype/type_create_struct.c:116
    
    
    #0  0x000000000040e2a0 in MPI_Type_commit@plt ()
    
    
    #0  PMPI_Type_commit (datatype=0x69de20) at ../../src/mpi/datatype/type_commit.c:75
    

    If you want more detailed information, printing local variables of a given breakpoint is also possible, just insert more commands between command and end.

    Bonus tip: add all of these to your .gdbinit file and pipe the execution into a file.

提交回复
热议问题