views:

1375

answers:

4

Can someone please provide an implementation of a C function that gets invoked to dump the current stack? It's for a x86 linux system. It can be invoked in 2 ways: explicitly by another function, or after a crash (probably as a trap/int handler). The output can be either to the screen or to a file, as indicated by a parameter (handle). A clear explanation/comments of how the stack is unwound would obviously be very helpful. Thank you.

+4  A: 

See this question.

Adam Rosenfield
jd
Link doesn't work (title has changed), should now be:http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
squelart
Thanks, fixed now.
Adam Rosenfield
+2  A: 

following on Adam's answer, the source code that shows how to perform the actual stack backtracing is in gnu libc's backtrace(), under /libc/debug/backtrace.c - not sure if the full link below will be accepted by stackoverflow's html filters...

http://cvs.savannah.gnu.org/viewvc/*checkout*/libc/debug/backtrace.c?root=libc&revision=1.1.2.1&content-type=text%2Fplain

jd
+1  A: 

The documentation for the backtrace() function is in the GNU LIBC MANUAL.

Phillip Whelan
A: 

When function calls are nested, the stack grows downwards and builds a chain of stack frames. At any given point in a program it is theoretically possible to backtrace the sequence of stack frames to the original calling point. The backtrace() function navigates the stack frames from the calling point to the beginning of the program and provides an array of return addresses. The implementation of backtrace() in the glibc library contains platform-specific code for each platform.

In the case of an x86 platform, the contents of the ebp (base pointer) and esp (stack pointer) CPU registers, which hold the address of the current stack frame and of the stack pointer for any given function, are used to follow the chain of pointers and move up to the initial stack frame. This allows the sequence of return addresses to be gathered to build the backtrace.

If you would like to know more information on how backtrace() works and how to use it, I would recommend reading Stack Backtracing Inside Your Program (LINUX Journal).


Since you mentioned executing a backtrace from a signal handler for an x86 platform, I would like to add to Adam's answer and direct you to my response to the question he linked to for details on how to ensure a backtrace from a signal handler points to the actual location of the fault.

jschmier