I want to have stack trace not for my exceptions only but also for any descendants of std::exception
As I understand, stack trace is completely lost when exception is caught because of stack unwinding (unrolling).
So the only way I see to grab it is injection of code saving context info (stack trace) at the place of std::exception constructor call. Am I right?
If it is the case, please tell me how code injection can be done (if it can) in C++. Your method may be not completely safe because I need it for Debug version of my app only. May be I need to use assembler?
I’m interested only in solution for GCC. It can use c++0x features
Since you mentioned that you’re happy with something that is GCC specific I’ve put together an example of a way you might do this. It’s pure evil though, interposing on internals of the C++ support library. I’m not sure I’d want to use this in production code. Anyway:
We basically steal calls to the internal implementation function that GCC uses for dispatching thrown exceptions. At that point we take a stack trace and save it in a global variable. Then when we come across that exception later on in our try/catch we can work with the stacktrace to print/save or whatever it is you want to do. We use
dlsym()to find the real version of__cxa_throw.My example throws an
intto prove that you can do this with literally any type, not just your own user defined exceptions.It uses the
type_infoto get the name of the type that was thrown and then demangles it.You could encapsulate the global variables that store the stacktrace a bit better if you wanted to.
I compiled and tested this with:
Which gave the following when run:
Please don’t take this as an example of good advice though – it’s an example of what you can do with a little bit of trickery and poking around at the internals!