jeremy-rifkin / cpptrace

Simple, portable, and self-contained stacktrace library for C++11 and newer
MIT License
621 stars 64 forks source link

possible null dereference in file_deleter #106

Closed eyalgolan1337 closed 5 months ago

eyalgolan1337 commented 5 months ago

in utils.hpp there's this function:

inline void file_deleter(std::FILE* ptr) {
        fclose(ptr);
}

this function is used in elf.hpp in elf_get_module_image_base() inside a raii_wrap:

        auto file = raii_wrap(std::fopen(object_path.c_str(), "rb"), file_deleter);
        if(file == nullptr) {
            throw file_error("Unable to read object file " + object_path);
}
...

if std::fopen fails then the internal FILE* will be nullptr. using fclose on a nullptr is undefined behaviour (in my case - segmentation fault).

suggested fix:

inline void file_deleter(std::FILE* ptr) {
        if (ptr != nullptr) {
                fclose(ptr);
        }
}

This issue arose when the object file the library tried to open did not exist. the resulting object_trace came back empty, which is a shame since the other object files could probably still be opened, so a stack trace of all call addresses and partial object paths could have still been generated

jeremy-rifkin commented 5 months ago

Thanks, good catch

eyalgolan1337 commented 5 months ago

i also suggest wrapping the call to elf_get_module_image_base() or the function calling it with try-catch to allow recovering and the continuation of the stack tracing with the other object files

jeremy-rifkin commented 5 months ago

Thanks, that’s also a good point. I think it may be taken care of as part of #102, which I hope to make progress on soon.