Is it possible to print the function name of the calling function?
>
Not portably.
For example, f1() and f2() both calls f3(), in f3() I would like to
print the name of the function calling f3() which could either be f1()
or f2().
So the caller can't rely on f3() behaving consistently?
If you need more info than you pass in the function arguments, the
obvious suggestion is to simply add some more function arguments.
In gdb it is possible to get a call trace, how can gdb get the call
trace? Does gdb use some OS-specific functions for this?
gdb uses system-specific ways to get the function's addresses, but
loads the compiler-generated debug info (including the calling
function's name) from the executable. In your own code, you cannot
even assume that your own program can read itself, let alone rely on a
specific debugging format.
It gets worse than that. Also, gdb has been known to get this
WRONG, especially if something managed to clobber the stack (if
there is one) frame.
- You cannot assume that your own program can even FIND itself. argv[0]
need not be a *file* name. Also, it's easy for malicious invokers to
fake this information. Same goes for getenv("PATH").
- Not all systems have things like /proc/curproc/file (FreeBSD) or
/proc/self/exe (Linux) which provide a symlink to the executable.
You still might not have permission to access it in any case.
- You cannot assume that you have read permission on the executable.
Execute-only permission is possible in a number of operating systems.
Plus, the higher-level directory permissions may not permit access.
- You cannot assume that you can open the executable for read while it's
running. Some operating systems give an ETXTBSY error. (More give
ETXTBSY if you try opening for *write*).
- You cannot assume that the executable has any debugging symbols in *ANY*
format, much less one that you can interpret. They may not be generated,
or they may be stripped off later for production use. Among other things,
in a large software distribution, those symbols can take up a lot of
disk space. And closed-source software distributions will probably remove
symbols to avoid giving away too much information.
- Even if the executable has debugging symbols, you may not have all the
debugging symbols you need (e.g. for libraries, static-linked or dynamic-
linked). Sometimes a library function can call YOUR function (e.g.
qsort calling a compare function).
- Finding the symbols for a dynamic-linked library can be very
system-dependent. No, you can't depend on having dynamic-linked libraries,
but neither can you depend on NOT having them.
- Even if you have all the function addresses, stack (if there is one) frame
formats and calling sequences are very system-dependent.
- The symbol associated with the function name may bear minimal resemblance
to the actual function name (C++ name-mangling, for example).