Skip to content

print stack trace when crashing #102

@igaw

Description

@igaw

In case the library or nvme-cl crashes it would really help to get a stack trace.

Here two simple examples.

#define _GNU_SOURCE
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>

void print_stacktrace(void)
{
    void *buffer[64];
    int nptrs = backtrace(buffer, 64);

    printf("Stack trace (%d frames):\n", nptrs);

    char **symbols = backtrace_symbols(buffer, nptrs);
    if (!symbols) {
        perror("backtrace_symbols");
        exit(EXIT_FAILURE);
    }

    for (int i = 0; i < nptrs; i++)
        printf("  %s\n", symbols[i]);

    free(symbols);
}

void foo(void) { print_stacktrace(); }
void bar(void) { foo(); }

int main(void)
{
    bar();
    return 0;
}
$ gcc -g -rdynamic stacktrace.c -o stacktrace
$ ./stacktrace
Stack trace (7 frames):
  ./stacktrace(print_stacktrace+0x1f) [0x4004d5]
  ./stacktrace(foo+0x9) [0x400575]
  ./stacktrace(bar+0x9) [0x400581]
  ./stacktrace(main+0x9) [0x40058d]
  /lib64/libc.so.6(+0x35b5) [0x7fa9106355b5]
  /lib64/libc.so.6(__libc_start_main+0x88) [0x7fa910635668]
  ./stacktrace(_start+0x25) [0x4003f5]
#include <libunwind.h>
#include <stdio.h>

void print_stacktrace(void)
{
    unw_cursor_t cursor;
    unw_context_t context;

    unw_getcontext(&context);
    unw_init_local(&cursor, &context);

    printf("Stack trace:\n");
    while (unw_step(&cursor) > 0) {
        unw_word_t offset, pc;
        char func[256];

        unw_get_reg(&cursor, UNW_REG_IP, &pc);
        printf("  0x%lx: ", (long) pc);

        if (!unw_get_proc_name(&cursor, func, sizeof(func), &offset))
            printf("%s + 0x%lx\n", func, (long) offset);
        else
            printf("?\n");
    }
}

void foo(void) { print_stacktrace(); }
void bar(void) { foo(); }

int main(void)
{
    bar();
    return 0;
}
$ gcc -g stacktrace.c -lunwind -lunwind-x86_64 -o stacktrace
$ ./stacktrace
Stack trace:
  0x4005b8: foo + 0x9
  0x4005c4: bar + 0x9
  0x4005d0: main + 0x9
  0x7fee978de5b5: __libc_start_call_main + 0x75
  0x7fee978de668: __libc_start_main + 0x88
  0x400405: _start + 0x25

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    Ready

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions