I have a program written in C that runs on Linux, MacOS and Windows. Is there a way I can call a function and generate a stack trace? This would be super-useful for me. Ideally I'd like to do it on all three platforms, but Linux is the most important. (Windows is being compiled via mingw.)
Thanks.
You can obtain a stack trace from a thread – by calling the getStackTrace method on that Thread instance. This invocation returns an array of StackTraceElement, from which details about stack frames of the thread can be extracted.
Just use new Throwable(). printStackTrace() method and it will print complete stack trace from where a method is called, into the console.
For example, in GCC and the GNU libc
C library, you can use backtrace()
.
As @slugonamission suggests, Windows offers CaptureStackBackTrace()
- thanks!
Other platforms may offer similar features.
(This is obviously a platform-dependent question.)
(On a related note, there also exist self-disassembly libraries.)
I'm using this code to generate debug stack traces. It uses libunwind to get the stacktrace and libdwfl to read debug information.
It produces nice Java-like stack traces, with function names and source locations. eg.:
at c(stack_trace.c:95)
at b(stack_trace.c:100)
at a(stack_trace.c:105)
at main(stack_trace.c:110)
libunwind should work on Windows and Mac, but libdwfl is Linux and ELF specific.
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