How to Traceback C++ in conditions like double free detected or floating point error etc

64 Views Asked by At
#include <cstdio>
#include <execinfo.h>
#include <csignal>
#include <cstdlib>
#include <unistd.h>
#include "stacktrace.h"

//// TRACEBACK TEST
void trace_handler(int sig) {
    void *array[10];
    size_t size;

    // get void*'s for all entries on the stack
    size = backtrace(array, 10);

    // print out all the frames to stderr


    fprintf(stderr, "Error: signal %d:\n", sig);
    backtrace_symbols_fd(array, size, STDERR_FILENO);

//    print_stacktrace();
    exit(1);
}
int TestTrace1() {

    int a = 8;
    int b = 5;
    int c;
    printf("In Trace 1\n");
    
    // TEST -A ----------
    int * deneme;
    deneme = (int *) malloc(20);
    free(deneme);
    free(deneme);
    
    // TEST -B ----------
//    for (int i = 0; i < 20; i++) {
//        c = b / (a - i);
//        printf("Res: %d\n", c);
//    }

    // TEST -C ----------
//    int *foo = (int*)-1; // make a bad pointer
//    printf("%d\n", *foo);       // causes segfault

    return 9;
}

int TestTrace2() {

    TestTrace1();
    return 0;
}

void TraceTest() {
    signal(SIGSEGV, trace_handler);
    signal(SIGTERM, trace_handler);
    signal(SIGFPE, trace_handler);
    signal(SIGABRT, trace_handler);
    signal(SIGBUS, trace_handler);
    signal(SIGSYS, trace_handler);
    signal(SIGPIPE, trace_handler);
    printf("i am in\n");


    int b;
    b = TestTrace2();
    printf("Result is %d\n", b);
}

//// TRACEBACK TEST ENDS

int main(int argc, char **argv) {
    TraceTest();
    return 0;
}

I can get traceback in TEST -C like this (Segmentation fault):

i am in
In Trace 1
Error: signal 11:
./test.bin(_Z13trace_handleri+0x20)[0x73200]
/lib/libc.so.6(+0x25550)[0xa46dd550]
./test.bin(_Z10TestTrace1v+0x34)[0x73278]
./test.bin(_Z10TestTrace2v+0xc)[0x732a8]
./test.bin(_Z9TraceTestv+0x8c)[0x73340]
./test.bin(main+0x24)[0x73388]
/lib/libc.so.6(__libc_start_main+0x97)[0xa46cf4e4]

However if i try to trace double free error( TEST -A) i can catch SIGABTR but cannot traceback the code. Same issue for floating point errors too

i am in
In Trace 1
free(): double free detected in tcache 2
Error: signal 6:
./mlmfirmwarePlayground.bin(_Z13trace_handleri+0x20)[0x73200]
/lib/libc.so.6(+0x25550)[0xa465c550]
/lib/libc.so.6(+0x17706)[0xa464e706]

If i disable catching signals, execution gives an error like

i am in
In Trace 1
free(): double free detected in tcache 2

And then quits. This makes me think somehow compiler injects something within code which handles the signalsa like SIGABTR or SIGFPE?

The Environment is linux and cross compiled arm32

How can i get a valid traceback?

0

There are 0 best solutions below