I am using gnu tool chain. How can I, at run time, find caller of a function? i.e for example function B() gets called by many functions using function pointers. Now, whenever B gets called, I want to print the callers name. I need this for debugging a certain issue.
If you're using GNU, you can use the backtrace functions. There's an example of the use on that man page.
The code location of the call to your function is kept by gcc in the __builtin_return_address()
intrinsic. To retrieve the name for that, you have to parse the program's symbol table; while that is possible to do, via dladdr()
, there are limits to this:
backtrace()
/dladdr()
(like, from signal handlers, or concurrently in a multithreaded program, or from contexts where you can't call malloc()
.).backtrace()
manpage states this as well, as does the one for dladdr()
in the "BUGS" section).It's often a better way to decouple tracing and function name resolving; i.e. just output the return addresses (as hex / binary) and then postprocess the resulting log against a symbol table retrieved when the program was running.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With