17
votes

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.

3

3 Answers

8
votes

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.)

6
votes

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.

3
votes

Ian Lance Taylor's libbacktrace does this. It handles stack unwinding and provides support for DWARF debugging symbols.

https://github.com/ianlancetaylor/libbacktrace

As of October 2020, libbacktrace supports ELF, PE/COFF, Mach-O, and XCOFF executables with DWARF debugging information. In other words, it supports GNU/Linux, *BSD, macOS, Windows, and AIX. The library is written to make it straightforward to add support for other object file and debugging formats.