Linux Applications Debugging Techniques/The call stack

The API
Sometimes we need the call stack at a certain point in the program. These are the API functions to get basic stack information:

Notes:
 * C++ symbols are still mangled. Use abi::__cxa_demangle or something similar.
 * Some of the these functions do allocate memory - either temporarily either explicitly - and this might be a problem if the program is unstable already.
 * Some of the these functions do acquire locks (e.g. dladdr).
 * backtrace* are expensive calls on some platforms (x86_64 for instance), the deeper the call stack is the more expensive the call is.
 * dladdr will fail to rsolve any symbol that is not exported. Hence, to get the most out of it:
 * Link with -rdynamic and -ldl

To extract more information (file, line number), use libbfd. Possible alternatives: libbacktrace; http://libcsdbg.sourceforge.net/

A C++ wrapper
With this simple class, getting the stack is one line away:

This class can be used with assertions, logging or exceptions.

The full code can be found at the LPT site and it offers three symbol resolver varieties. This code will require a C++11 compiler.
 * A "basic" address-only resolver, without memory side-effects
 * A libc resolver
 * A libbfd resolver

A boost-based version of the call stack utilities collection can be found at https://github.com/melintea/Boost-Call_stack.

A stack resolved with the libc resolver, embedded in an exception, with debug-compiled code would look like:

Note how dladdr fails to resolve some of the frames. Whereas a stack resolved with the bfd resolver would show file and line numbers and would resolve all frames:

Caveats

 * Do NOT use in asynchronous interrupts such as signal handlers.
 * It might or it might not work when the program is unstable - prefer a core dump if possible. Same for memory issues handlers.
 * Performance hit varies greatly with platform and compiler version.

From within gdb
A canned command to resolve a stack address from within gdb:

Links

 * Calling conventions