diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-10 11:43:24 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-10 11:58:53 -0300 |
| commit | 3fdb67c479dcc1ad0f1e51832bc086622692249c (patch) | |
| tree | dcc2e947644cb6d9a8bb0a19a29153256f4bc951 /src/trace/ptrace.zig | |
| parent | f15f4670991110829dcf123625c049224eba9838 (diff) | |
| download | computeranim-3fdb67c479dcc1ad0f1e51832bc086622692249c.tar.gz computeranim-3fdb67c479dcc1ad0f1e51832bc086622692249c.zip | |
debugger: steps by instruction and line, breakpoints, hooks, watches, threads; ztrace dbg
ptrace.zig follows the threads a target makes, attaches, tells a step from
a breakpoint, and writes memory in one call (through /proc/pid/mem where
the page is read-only). Debugger.zig is the layer above: cont, stepi, step
(a source line, through std.debug's DWARF), breakpoints with hooks, syscall
stops and hooks with the path or buffer captured, watched regions sent as
the words that changed, and every stop an event. Symbols.zig is modules,
ELF symbols and line tables; syscalls.zig their names and shapes.
ztrace dbg is a small REPL on it that records as it goes and looks back
into the recording; ztrace record stops by instruction, line, syscall or
breakpoint, prints syscalls as strace does, and ends cleanly when the
recording is full.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Diffstat (limited to 'src/trace/ptrace.zig')
| -rw-r--r-- | src/trace/ptrace.zig | 232 |
1 files changed, 181 insertions, 51 deletions
diff --git a/src/trace/ptrace.zig b/src/trace/ptrace.zig index 40a9a7a..fd7ebd1 100644 --- a/src/trace/ptrace.zig +++ b/src/trace/ptrace.zig @@ -1,28 +1,44 @@ -//! The out-of-process backend: a target run under ptrace. Start it, stop it -//! at instructions, syscalls and breakpoints, read its registers and memory. -//! x86-64 Linux. +//! The out-of-process backend: a target under ptrace. Start it or attach to +//! it, run it to its next instruction, syscall, breakpoint or signal, read +//! and write its registers and memory. The threads it makes are traced too: +//! `tid` is the one the last stop came from, and what registers and resumes +//! act on. x86-64 Linux. `Debugger` is the layer above. const std = @import("std"); const linux = std.os.linux; const event = @import("event.zig"); const Regs = event.Regs; const P = linux.PTRACE; +const WALL = 0x40000000; + pub const Stop = union(enum) { - /// A single step finished, or a breakpoint was hit. + /// A single step finished, or a breakpoint instruction ran. trap, - /// At a syscall's entry or exit (they alternate). + /// At a syscall's entry or exit: `inSyscall` tells which. syscall, + /// The thread made this new one, traced from its first instruction. + clone: linux.pid_t, /// A signal is about to be delivered; `resume_signal` holds it. signal: linux.SIG, + /// The thread is gone, and the process with it when it is the first. exited: u8, killed: linux.SIG, }; pub const Process = struct { pid: linux.pid_t, + /// The thread the last stop came from. + tid: linux.pid_t, /// The signal the next resume delivers. resume_signal: u32 = 0, - in_syscall: bool = false, + /// Traced threads alive. + threads: u32 = 1, + /// Attached to, not started: `close` lets it go on instead of killing it. + attached: bool = false, + /// The process has exited and was reaped. + gone: bool = false, + /// /proc/pid/mem, opened by the first write that needs it. + mem_fd: linux.fd_t = -1, /// Runs `argv` stopped at its first instruction. `path` is the /// executable; `argv` and `envp` are what it gets. @@ -34,61 +50,130 @@ pub const Process = struct { _ = linux.execve(path, argv, envp); linux.exit_group(127); } - var p: Process = .{ .pid = @intCast(pid) }; - switch (try p.wait()) { + var p: Process = .{ .pid = @intCast(pid), .tid = @intCast(pid) }; + switch (try p.wait(p.pid)) { // The stop exec makes under PTRACE_TRACEME. .signal, .trap => {}, else => return error.ExecFailed, } p.resume_signal = 0; - _ = try check(linux.ptrace(P.SETOPTIONS, p.pid, 0, P.O.TRACESYSGOOD | P.O.EXITKILL, 0)); + _ = try check(linux.ptrace(P.SETOPTIONS, p.pid, 0, P.O.TRACESYSGOOD | P.O.TRACECLONE | P.O.EXITKILL, 0)); + return p; + } + + /// Stops a running process and traces it from there. + // shortcut: only the thread `pid` names is attached, upgrade by walking /proc/pid/task when a threaded target needs it. + pub fn attach(pid: linux.pid_t) !Process { + _ = try check(linux.ptrace(P.ATTACH, pid, 0, 0, 0)); + var p: Process = .{ .pid = pid, .tid = pid, .attached = true }; + errdefer _ = linux.ptrace(P.DETACH, pid, 0, 0, 0); + // The SIGSTOP attaching sends. + _ = try p.wait(pid); + p.resume_signal = 0; + _ = try check(linux.ptrace(P.SETOPTIONS, pid, 0, P.O.TRACESYSGOOD | P.O.TRACECLONE, 0)); return p; } - /// One instruction. + /// Ends the session: an attached process runs on, a spawned one is killed. + pub fn close(p: *Process) void { + if (p.mem_fd >= 0) _ = linux.close(p.mem_fd); + if (p.gone) return; + if (p.attached) { + _ = linux.ptrace(P.DETACH, p.tid, 0, 0, 0); + return; + } + _ = linux.kill(p.pid, .KILL); + // Each traced thread is reaped before the process itself can be. + while (!p.gone) _ = p.waitAny() catch return; + } + + /// One instruction of the current thread. pub fn stepi(p: *Process) !Stop { - return p.run(P.SINGLESTEP); + try p.run(P.SINGLESTEP); + return p.wait(p.tid); } - /// Until the next breakpoint, signal or exit. + /// The current thread until its next breakpoint, signal or exit. pub fn cont(p: *Process) !Stop { - return p.run(P.CONT); + try p.run(P.CONT); + return p.wait(p.tid); } - /// Until the next syscall entry or exit. + /// The current thread until its next syscall entry or exit. pub fn syscall(p: *Process) !Stop { - return p.run(P.SYSCALL); + try p.run(P.SYSCALL); + return p.wait(p.tid); } - fn run(p: *Process, request: u32) !Stop { - _ = try check(linux.ptrace(request, p.pid, 0, p.resume_signal, 0)); + /// Resumes the current thread: `request` is PTRACE_CONT, SYSCALL or SINGLESTEP. + pub fn run(p: *Process, request: u32) !void { + _ = try check(linux.ptrace(request, p.tid, 0, p.resume_signal, 0)); p.resume_signal = 0; - return p.wait(); } - fn wait(p: *Process) !Stop { + /// The next stop of any traced thread. + // shortcut: with threads this waits for any child of the tracer, so one threaded target a tracer process; upgrade with a wait per known tid. + pub fn waitAny(p: *Process) !Stop { + return p.wait(if (p.threads > 1) -1 else p.pid); + } + + /// The next stop of one thread (-1: of any child), which becomes the current one. + pub fn wait(p: *Process, tid: linux.pid_t) !Stop { var status: u32 = 0; - _ = try check(linux.waitpid(p.pid, @ptrCast(&status), linux.W.UNTRACED)); - if (linux.W.IFEXITED(status)) return .{ .exited = linux.W.EXITSTATUS(status) }; - if (linux.W.IFSIGNALED(status)) return .{ .killed = linux.W.TERMSIG(status) }; + p.tid = @intCast(try check(linux.waitpid(tid, @ptrCast(&status), WALL))); + if (linux.W.IFEXITED(status) or linux.W.IFSIGNALED(status)) { + if (p.tid == p.pid) p.gone = true else p.threads -= 1; + return if (linux.W.IFEXITED(status)) .{ .exited = linux.W.EXITSTATUS(status) } else .{ .killed = linux.W.TERMSIG(status) }; + } const sig: u32 = (status >> 8) & 0xff; - if (sig == @intFromEnum(linux.SIG.TRAP) | 0x80) { - p.in_syscall = !p.in_syscall; - return .syscall; + if (sig == @backingInt(linux.SIG.TRAP) | 0x80) return .syscall; + if (sig == @backingInt(linux.SIG.TRAP)) { + if (status >> 16 != P.EVENT.CLONE) return .trap; + var child: usize = 0; + _ = try check(linux.ptrace(P.GETEVENTMSG, p.tid, 0, @intFromPtr(&child), 0)); + p.threads += 1; + return .{ .clone = @intCast(child) }; } - if (sig == @intFromEnum(linux.SIG.TRAP)) return .trap; p.resume_signal = sig; - return .{ .signal = @enumFromInt(sig) }; + return .{ .signal = @fromBackingInt(@intCast(sig)) }; + } + + /// At a `syscall` stop: true at the entry, false at the exit. + pub fn inSyscall(p: *const Process) !bool { + // The head of the kernel's `ptrace_syscall_info`: op (1 entry, 2 exit), then the instruction and stack pointers. + var info: extern struct { op: u8, pad: [3]u8, arch: u32, ip: u64, sp: u64 } = undefined; + _ = try check(linux.ptrace(P.GET_SYSCALL_INFO, p.tid, @sizeOf(@TypeOf(info)), @intFromPtr(&info), 0)); + return info.op == 1; + } + + fn siginfo(p: *const Process) ?linux.siginfo_t { + var info: linux.siginfo_t = undefined; + return if (linux.errno(linux.ptrace(P.GETSIGINFO, p.tid, 0, @intFromPtr(&info), 0)) == .SUCCESS) info else null; + } + + /// At a `signal` stop: the address a fault is about, 0 for another signal. + pub fn faultAddress(p: *const Process) u64 { + const info = p.siginfo() orelse return 0; + return switch (info.signo) { + .SEGV, .BUS, .ILL, .FPE => @intFromPtr(info.fields.sigfault.addr), + else => 0, + }; + } + + /// At a `trap` stop: true when a breakpoint instruction ran, false when a single step finished. + pub fn atBreakpoint(p: *const Process) bool { + // SI_KERNEL is x86's code for int3. Not TRAP_BRKPT: a step that ends in a syscall says that. + return if (p.siginfo()) |info| info.code == 0x80 else false; } pub fn regs(p: *const Process) !Regs { var out: Regs = undefined; - _ = try check(linux.ptrace(P.GETREGS, p.pid, 0, @intFromPtr(&out), 0)); + _ = try check(linux.ptrace(P.GETREGS, p.tid, 0, @intFromPtr(&out), 0)); return out; } pub fn setRegs(p: *const Process, r: *const Regs) !void { - _ = try check(linux.ptrace(P.SETREGS, p.pid, 0, @intFromPtr(r), 0)); + _ = try check(linux.ptrace(P.SETREGS, p.tid, 0, @intFromPtr(r), 0)); } /// The target's memory in one syscall, however long. Returns the bytes @@ -100,23 +185,28 @@ pub const Process = struct { return if (linux.errno(rc) == .SUCCESS) rc else 0; } - /// Writes through ptrace, so read-only pages (code) can be patched. - pub fn write(p: *const Process, addr: u64, bytes: []const u8) !void { - var at: usize = 0; - while (at < bytes.len) { - var word: [8]u8 = undefined; - const n = @min(8, bytes.len - at); - if (n < 8 and p.read(addr + at, &word) != 8) return error.BadAddress; - @memcpy(word[0..n], bytes[at..][0..n]); - _ = try check(linux.ptrace(P.POKEDATA, p.pid, addr + at, @bitCast(word), 0)); - at += n; - } + /// The NUL-terminated string at `addr`, cut at `buf.len`. + pub fn readString(p: *const Process, addr: u64, buf: []u8) []u8 { + // To the end of the page first: the string may end right before an unmapped one. + const first = @min(buf.len, 4096 - addr % 4096); + var n = p.read(addr, buf[0..first]); + if (n == first and std.mem.indexOfScalar(u8, buf[0..n], 0) == null) n += p.read(addr + n, buf[n..]); + return buf[0 .. std.mem.indexOfScalar(u8, buf[0..n], 0) orelse n]; } - pub fn kill(p: *Process) void { - _ = linux.kill(p.pid, .KILL); - var status: u32 = 0; - _ = linux.waitpid(p.pid, @ptrCast(&status), 0); + /// Into the target's memory in one syscall. Where the page is not + /// writable (code, for a breakpoint) through /proc/pid/mem, which a + /// tracer may write whatever the protection. + pub fn write(p: *Process, addr: u64, bytes: []const u8) !void { + const local = [1]std.posix.iovec_const{.{ .base = bytes.ptr, .len = bytes.len }}; + const remote = [1]std.posix.iovec_const{.{ .base = @ptrFromInt(addr), .len = bytes.len }}; + if (linux.process_vm_writev(p.pid, &local, &remote, 0) == bytes.len) return; + if (p.mem_fd < 0) { + var path: [32]u8 = undefined; + const name = std.fmt.bufPrintSentinel(&path, "/proc/{d}/mem", .{p.pid}, 0) catch unreachable; + p.mem_fd = @intCast(try check(linux.open(name, .{ .ACCMODE = .RDWR, .CLOEXEC = true }, 0))); + } + if (linux.pwrite(p.mem_fd, bytes.ptr, bytes.len, @intCast(addr)) != bytes.len) return error.BadAddress; } }; @@ -130,29 +220,69 @@ fn check(rc: usize) !usize { }; } +const test_argv = [_:null]?[*:0]const u8{ "/bin/true", null }; +const test_envp = [_:null]?[*:0]const u8{null}; + test "a child is stepped, read, patched and run to its exit" { - const argv = [_:null]?[*:0]const u8{ "/bin/true", null }; - const envp = [_:null]?[*:0]const u8{null}; - var p = try Process.spawn("/bin/true", &argv, &envp); - errdefer p.kill(); + var p = try Process.spawn("/bin/true", &test_argv, &test_envp); + defer p.close(); const before = try p.regs(); try std.testing.expect(before.rip != 0); try std.testing.expectEqual(Stop.trap, try p.stepi()); + try std.testing.expect(!p.atBreakpoint()); try std.testing.expect((try p.regs()).rip != before.rip); // The stack is writable and reads back. var buf: [16]u8 = undefined; - try p.write(before.rsp - 64, "0123456789abcdef"[0..11]); + try p.write(before.rsp - 64, "0123456789a\x00"); try std.testing.expectEqual(@as(usize, 16), p.read(before.rsp - 64, &buf)); try std.testing.expectEqualStrings("0123456789a", buf[0..11]); + try std.testing.expectEqualStrings("0123456789a", p.readString(before.rsp - 64, &buf)); try std.testing.expectEqual(@as(usize, 0), p.read(8, &buf)); + // Code is not writable, and is written all the same. + var code: [4]u8 = undefined; + try std.testing.expectEqual(@as(usize, 4), p.read(before.rip, &code)); + try p.write(before.rip, &.{ 0xcc, 0xcc }); + try std.testing.expectEqual(@as(usize, 16), p.read(before.rip, &buf)); + try std.testing.expectEqualSlices(u8, &.{ 0xcc, 0xcc, code[2], code[3] }, buf[0..4]); + // ... and runs: a breakpoint, told from a step. + try p.setRegs(&before); + try std.testing.expectEqual(Stop.trap, try p.cont()); + try std.testing.expect(p.atBreakpoint()); + try std.testing.expectEqual(before.rip + 1, (try p.regs()).rip); + try p.write(before.rip, &code); + try p.setRegs(&before); + try std.testing.expectEqual(Stop.syscall, try p.syscall()); + try std.testing.expect(try p.inSyscall()); + try std.testing.expectEqual(Stop.syscall, try p.syscall()); + try std.testing.expect(!try p.inSyscall()); while (true) switch (try p.cont()) { - .exited => |code| { - try std.testing.expectEqual(@as(u8, 0), code); + .exited => |code_| { + try std.testing.expectEqual(@as(u8, 0), code_); break; }, else => {}, }; + try std.testing.expect(p.gone); +} + +test "a running child is attached to and let go" { + // A child that waits to be killed: attaching is allowed to a parent whatever ptrace_scope says below 2. + const pid: linux.pid_t = @intCast(try check(linux.fork())); + if (pid == 0) { + while (true) _ = linux.pause(); + } + defer { + _ = linux.kill(pid, .KILL); + var status: u32 = 0; + _ = linux.waitpid(pid, @ptrCast(&status), 0); + } + var p = try Process.attach(pid); + try std.testing.expect((try p.regs()).rip != 0); + p.close(); + // Detached, it runs on: a second attach finds it alive. + p = try Process.attach(pid); + p.close(); } |
