Automatically adding Enter/Exit Function Logs to a Project

后端 未结 5 889
攒了一身酷
攒了一身酷 2020-11-29 04:42

I have a 3rd party source code that I have to investigate. I want to see in what order the functions are called but I don\'t want to waste my time typing:

pr         


        
相关标签:
5条回答
  • 2020-11-29 05:03

    Besides the usual debugger and aspect-oriented programming techniques, you can also inject your own instrumentation functions using gcc's -finstrument-functions command line options. You'll have to implement your own __cyg_profile_func_enter() and __cyg_profile_func_exit() functions (declare these as extern "C" in C++).

    They provide a means to track what function was called from where. However, the interface is a bit difficult to use since the address of the function being called and its call site are passed instead of a function name, for example. You could log the addresses, and then pull the corresponding names from the symbol table using something like objdump --syms or nm, assuming of course the symbols haven't been stripped from the binaries in question.

    It may just be easier to use gdb. YMMV. :)

    0 讨论(0)
  • 2020-11-29 05:15

    Use /Gh (Enable _penter Hook Function) and /GH (Enable _pexit Hook Function) compiler switches (if you can compile the sources ofcourse)

    NOTE: you won't be able to use those macro's. See here ("you will need to get the function address (in EIP register) and compare it against addresses in the map file that can be generated by the linker (assuming no rebasing has occurred). It'll be very slow though.")

    0 讨论(0)
  • 2020-11-29 05:23

    If you're using gcc, the magic compiler flag is -g. Compile with debugging symbols, run the program under gdb, and generate stack traces. You could also use ptrace, but it's probably a lot easier to just use gdb.

    0 讨论(0)
  • 2020-11-29 05:24

    You said "nor do I want to touch any source file"... fair game if you let a script do it for you?

    Run this on all your .cpp files

    sed 's/^{/{ENTRY/'
    

    So that it transforms them into this:

    void foo()
    {ENTRY
      // code here
    }
    

    Put this in a header that can be #included by every unit:

    #define ENTRY EntryRaiiObject obj ## __LINE__ (__FUNCTION__);
    
    struct EntryRaiiObject {
      EntryRaiiObject(const char *f) : f_(f) { printf("Entered into %s", f_); }
      ~EntryRaiiObject() { printf("Exited from %s", f_); }
      const char *f_;
    };
    

    You may have to get fancier with the sed script. You can also put the ENTRY macro anywhere else you want to probe, like some deeply nested inner scope of a function.

    0 讨论(0)
  • 2020-11-29 05:24

    Agree with William, use gdb to see the run time flow.
    There are some static code analyzer which can tell which functions call which and can give you some call flow graph. One tool is "Understand C++" (support C/C++) but thats not free i guess. But you can find similar tools.

    0 讨论(0)
提交回复
热议问题