Files
ptrace-inject-cpp/src/ptrace_utils.h
T
xiaozhou233 b78aa07f78 Port ptrace library injection to C++ as a reusable library
Add a C ABI library (libptrace_inject), a thin CLI (ptrace-inject), and
C/C++ examples that inject a .so into a running x86-64 Linux process.

Injection flow:
- stop every thread with PTRACE_ATTACH, re-scanning /proc/<pid>/task for
  threads created while attaching
- patch a 6-byte shellcode (nop; nop; call r9; int3) into a private,
  file-backed executable mapping, then call target malloc/dlopen/free via
  PTRACE_SETREGS + PTRACE_CONT and read the result from rax
- write the library path with /proc/<pid>/mem, free it, restore the
  original bytes and registers, then PTRACE_DETACH all threads

Safety:
- validate before modifying anything: library path, libc/libdl build
  identity via device:inode, relocated symbol addresses are executable,
  patch site avoids stopped threads' RIPs, stack pointer is writable
- only accept the SIGTRAP whose RIP is shellcode+6
- forward unexpected signals back to the target on detach
- best-effort rollback of code and registers on failure
- shared library exports only the two public entry points

API: ptrace_inject_by_pid() and ptrace_inject_by_name(), with an optional
log callback and an error buffer; silent by default.

Build with CMake (no install rules); docs in README.md (EN) and
README.ZH.md (ZH).
2026-10-18 21:38:52 +08:00

38 lines
1.2 KiB
C++

#pragma once
#include <sys/types.h>
#include <sys/user.h>
#include <cstdint>
#include <stdexcept>
#include <string>
#include <vector>
#include "log.h"
// Thrown when the tracee stops with a signal that is not our int3 SIGTRAP.
// main() uses it to deliver that signal back to the target on detach.
struct TraceeSignalError : public std::runtime_error {
TraceeSignalError(pid_t tracee, int signo, const std::string& what)
: std::runtime_error(what), tid(tracee), signal(signo) {}
pid_t tid;
int signal;
};
user_regs_struct get_registers(pid_t tid);
void set_registers(pid_t tid, const user_regs_struct& regs);
void continue_tracee(pid_t tid);
// Wait for our int3. expected_rip must be kShellcodeAddress + kShellcode.size().
void wait_for_trap(pid_t tid, std::uint64_t expected_rip);
// Stop every thread of `pid`; on return all of them are ptrace-stopped.
void attach_all_threads(pid_t pid, std::vector<pid_t>& attached,
const LogSink* log);
// Detach all threads. If signal != 0, deliver it to signal_tid on detach.
void detach_all_threads(std::vector<pid_t>& attached, pid_t signal_tid,
int signal, const LogSink* log);