This question has been asked before and there have been windows-specific answers but no satisfactory gcc answer. I can use set_terminate()
to set a function that will be called (in place of terminate()
) when an unhandled exception is thrown. I know how to use the backtrace library to generate a stack trace from a given point in the program. However, this won't help when my terminate-replacement is called since at that point the stack has been unwound.
Yet if I simply allow the program to abort()
, it will produce a core-dump which contains the full stack information from the point at which the exception was thrown. So the information is there -- but is there a programmatic way to get it, for example so it can be logged, rather than having to examine a core file?
Edited Answer:
You can use std::set_terminate
giving this output:
assuming you have debug symbols in your binary, you can then use addr2line to construct a prettier stack trace postmortem
original answer is below
I've done this in the past using boost::error_info to inject the stack trace using
backtrace
fromexecinfo.h
into an exception that is thrown.Then when catching the exceptions, you can do
I doubt my experience would fit your needs but here it goes anyway.
I was overloading
abort()
: either by adding my own object file before the libc or using LD_PRELOAD. In my own version ofabort()
I was starting the debugger telling it to attach to the process (well, I surely know my PID) and dump the stack trace into a file (commands were passed to the debugger via command line). After debugger had finished, terminate the process with e.g._exit(100)
.That was on Linux using GDB. On Solaris I routinely employ similar trick but due to unavailability of a sane debugger I use the pstack tool:
system("pstack <PID>")
.You can use libunwind (just add
-lunwind
to linker parameters) (tested withclang++ 3.6
):demagle.hpp:
demangle.cpp:
backtrace.hpp:
backtrace.cpp:
backtrace_on_terminate.hpp:
There is good article concerning the issue.