ianlancetaylor / libbacktrace

A C library that may be linked into a C/C++ program to produce symbolic backtraces
Other
971 stars 228 forks source link

Libbacktrace issue with mingw #111

Closed jeremy-rifkin closed 1 year ago

jeremy-rifkin commented 1 year ago

I'm trying to use libbacktrace with msys2 / mingw-w64 but I'm getting the following output:

> g++ -Wall -g .\repro.cpp -lbacktrace -fno-PIE
> .\a.exe
Backtrace error libbacktrace could not find executable to open 0 00000067ad5ffd40
Backtrace error failed to read executable information -1 00000067ad5ffd40
Backtrace error failed to read executable information -1 00000067ad5ffd40
Backtrace error failed to read executable information -1 00000067ad5ffd40
Backtrace error failed to read executable information -1 00000067ad5ffd40
Backtrace error failed to read executable information -1 00000067ad5ffd40
Backtrace error failed to read executable information -1 00000067ad5ffd40

I'm using mingw-w64-ucrt-x86_64-libbacktrace provided by msys2.

My code is below:

#include <iostream>
#include <cstddef>

#include <backtrace.h>

int full_callback(void* data_pointer, uintptr_t address, const char* file, int line, const char* symbol) {
    std::cout
            << file
            << "||"
            << line
            << "||"
            << symbol
            << std::endl;
    return 0;
}

void error_callback(void* data, const char* msg, int errnum) {
    // nothing for now
    fprintf(stderr, "Backtrace error %s %d %p\n", msg, errnum, data);
}

void generate_trace() {
    backtrace_state* state = backtrace_create_state(nullptr, true, error_callback, nullptr);
    backtrace_full(state, 0, full_callback, error_callback, nullptr);
}

void foo() {
    generate_trace();
}

int main() {
    foo();
}

Am I doing something wrong?

I've seen other posts and issues where libbacktrace fails due to ASLR, but here it is failing even with -fno-PIE.

anarazel commented 1 year ago

I suspect this is because you're passing nullptr to backtrace_create_state(). It looks like libbacktrace doesn't know how to figure out the filename of the executable on windows.

anarazel commented 1 year ago

Hm, looks like that'd be reasonably easy to add, using https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea?redirectedfrom=MSDN

@ianlancetaylor Interested in a PR for that? Not a windows person, but the problem reproduces in wine, and I'd not mind useful backtraces from windows CI...

ianlancetaylor commented 1 year ago

Sure, thanks.

ianlancetaylor commented 1 year ago

Change committed.