diff --git a/news/685.bugfix.rst b/news/685.bugfix.rst new file mode 100644 index 0000000000..057c58427d --- /dev/null +++ b/news/685.bugfix.rst @@ -0,0 +1 @@ +Fix some crashes caused by interposing symbols in memray itself diff --git a/src/memray/_memray/elf_shenanigans.cpp b/src/memray/_memray/elf_shenanigans.cpp index 997599ea74..cc08e23433 100644 --- a/src/memray/_memray/elf_shenanigans.cpp +++ b/src/memray/_memray/elf_shenanigans.cpp @@ -17,7 +17,8 @@ namespace { struct elf_patcher_context_t { bool restore_original; - std::set patched; + std::set& patched; + const std::string& self_so_name; }; } // namespace @@ -172,10 +173,10 @@ phdrs_callback(dl_phdr_info* info, [[maybe_unused]] size_t size, void* data) noe } if (strstr(info->dlpi_name, "/ld-linux") || strstr(info->dlpi_name, "/ld-musl") - || strstr(info->dlpi_name, "linux-vdso.so.1")) + || strstr(info->dlpi_name, "linux-vdso.so.1") + || strstr(info->dlpi_name, context.self_so_name.c_str())) { // Avoid chaos by not overwriting the symbols in the linker. - // TODO: Don't override the symbols in our shared library! return 0; } @@ -198,14 +199,14 @@ phdrs_callback(dl_phdr_info* info, [[maybe_unused]] size_t size, void* data) noe void SymbolPatcher::overwrite_symbols() noexcept { - elf_patcher_context_t context{false, symbols}; + elf_patcher_context_t context{false, symbols, self_so_name}; dl_iterate_phdr(&phdrs_callback, (void*)&context); } void SymbolPatcher::restore_symbols() noexcept { - elf_patcher_context_t context{true, symbols}; + elf_patcher_context_t context{true, symbols, self_so_name}; dl_iterate_phdr(&phdrs_callback, (void*)&context); } diff --git a/src/memray/_memray/linker_shenanigans.h b/src/memray/_memray/linker_shenanigans.h index 17ae39ff26..76a26a15fd 100644 --- a/src/memray/_memray/linker_shenanigans.h +++ b/src/memray/_memray/linker_shenanigans.h @@ -3,14 +3,27 @@ #include #include +#include + namespace memray::linker { +static void +_dummy(void){}; + class SymbolPatcher { private: std::set symbols; + std::string self_so_name = "_memray.cpython-"; public: + SymbolPatcher() + { + Dl_info info; + if (dladdr((void*)&_dummy, &info)) { + self_so_name = info.dli_fname; + } + } void overwrite_symbols() noexcept; void restore_symbols() noexcept; };