Skip to content

Instantly share code, notes, and snippets.

@nkuln
Created March 12, 2012 09:18
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nkuln/2020860 to your computer and use it in GitHub Desktop.
Save nkuln/2020860 to your computer and use it in GitHub Desktop.
Override __cxa_throw and prints backtrace when exception is thrown (Linux)
#include <dlfcn.h>
#include <execinfo.h>
typedef void (*cxa_throw_type)(void *, void *, void (*) (void *));
cxa_throw_type orig_cxa_throw = 0;
void load_orig_throw_code()
{
orig_cxa_throw = (cxa_throw_type) dlsym(RTLD_NEXT, "__cxa_throw");
}
extern "C"
void __cxa_throw (void *thrown_exception, void *pvtinfo, void (*dest)(void *)) {
printf(" ################ DETECT A THROWN !!!!! #############\n");
if (orig_cxa_throw == 0)
load_orig_throw_code();
{
static int throw_count = 0;
void *array[10];
size_t size;
size = backtrace(array, 10);
fprintf(stderr, "#### EXCEPTION THROWN (#%d) ####\n", ++throw_count);
backtrace_symbols_fd(array, size, 2); // 2 == stderr
}
orig_cxa_throw(thrown_exception, pvtinfo, dest);
}
@RoyBellingan
Copy link

Hy, I really suggest to give a look to https://github.com/bombela/backward-cpp
Much better stack trace it will print.
A bit of fiddling required, but result is outstanding!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment