Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid patching symbols in the extension module #685

Merged
merged 1 commit into from
Sep 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions news/685.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix some crashes caused by interposing symbols in memray itself
11 changes: 6 additions & 5 deletions src/memray/_memray/elf_shenanigans.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ namespace {
struct elf_patcher_context_t
{
bool restore_original;
std::set<std::string> patched;
std::set<std::string>& patched;
const std::string& self_so_name;
};

} // namespace
Expand Down Expand Up @@ -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;
}

Expand All @@ -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);
}

Expand Down
13 changes: 13 additions & 0 deletions src/memray/_memray/linker_shenanigans.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,27 @@
#include <set>
#include <string>

#include <dlfcn.h>

namespace memray::linker {

static void
_dummy(void){};

class SymbolPatcher
{
private:
std::set<std::string> 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;
};
Expand Down
Loading