From 26250fe14a555f68e93eb52c9888b95492c83cfa Mon Sep 17 00:00:00 2001 From: Itamar Date: Sun, 5 Feb 2023 22:53:21 +0200 Subject: [PATCH] LibDebug: Add static attach() function This function is similar to exec_and_attach(), but instead of spawning a new process and debugging it, it attaches to an existing process. --- Userland/Libraries/LibDebug/DebugSession.cpp | 20 ++++++++++++++++++++ Userland/Libraries/LibDebug/DebugSession.h | 1 + 2 files changed, 21 insertions(+) diff --git a/Userland/Libraries/LibDebug/DebugSession.cpp b/Userland/Libraries/LibDebug/DebugSession.cpp index 0c3896a69f..6566da1b78 100644 --- a/Userland/Libraries/LibDebug/DebugSession.cpp +++ b/Userland/Libraries/LibDebug/DebugSession.cpp @@ -129,6 +129,26 @@ OwnPtr DebugSession::exec_and_attach(DeprecatedString const& comma return debug_session; } +OwnPtr DebugSession::attach(pid_t pid, DeprecatedString source_root) +{ + if (ptrace(PT_ATTACH, pid, 0, 0) < 0) { + perror("PT_ATTACH"); + return {}; + } + + int status = 0; + if (waitpid(pid, &status, WSTOPPED | WEXITED) != pid || !WIFSTOPPED(status)) { + perror("waitpid"); + return {}; + } + + auto debug_session = adopt_own(*new DebugSession(pid, source_root)); + // At this point, libraries should have been loaded + debug_session->update_loaded_libs(); + + return debug_session; +} + bool DebugSession::poke(FlatPtr address, FlatPtr data) { if (ptrace(PT_POKE, m_debuggee_pid, bit_cast(address), bit_cast(data)) < 0) { diff --git a/Userland/Libraries/LibDebug/DebugSession.h b/Userland/Libraries/LibDebug/DebugSession.h index dad0e4bd2c..df279698f8 100644 --- a/Userland/Libraries/LibDebug/DebugSession.h +++ b/Userland/Libraries/LibDebug/DebugSession.h @@ -28,6 +28,7 @@ namespace Debug { class DebugSession : public ProcessInspector { public: static OwnPtr exec_and_attach(DeprecatedString const& command, DeprecatedString source_root = {}, Function()> setup_child = {}); + static OwnPtr attach(pid_t pid, DeprecatedString source_root = {}); virtual ~DebugSession() override;