Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

RoyBellingan commented Oct 13, 2017

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
You can’t perform that action at this time.