//! 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 instruction ran. trap, /// 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, /// 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. pub fn spawn(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) !Process { const pid = try check(linux.fork()); if (pid == 0) { // The child: raw syscalls only until exec. _ = linux.ptrace(P.TRACEME, 0, 0, 0, 0); _ = linux.execve(path, argv, envp); linux.exit_group(127); } 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.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; } /// 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 { try p.run(P.SINGLESTEP); return p.wait(p.tid); } /// The current thread until its next breakpoint, signal or exit. pub fn cont(p: *Process) !Stop { try p.run(P.CONT); return p.wait(p.tid); } /// The current thread until its next syscall entry or exit. pub fn syscall(p: *Process) !Stop { try p.run(P.SYSCALL); return p.wait(p.tid); } /// 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; } /// 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 { return (try p.next(tid, WALL)).?; } /// The same without waiting: null while nothing has stopped. pub fn poll(p: *Process, tid: linux.pid_t) !?Stop { return p.next(tid, WALL | linux.W.NOHANG); } fn next(p: *Process, tid: linux.pid_t, flags: u32) !?Stop { var status: u32 = 0; const stopped = try check(linux.waitpid(tid, @ptrCast(&status), flags)); if (stopped == 0) return null; p.tid = @intCast(stopped); 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 == @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) }; } p.resume_signal = 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.tid, 0, @intFromPtr(&out), 0)); return out; } pub fn setRegs(p: *const Process, r: *const Regs) !void { _ = try check(linux.ptrace(P.SETREGS, p.tid, 0, @intFromPtr(r), 0)); } /// The target's memory in one syscall, however long. Returns the bytes /// read: short where the range leaves mapped memory. pub fn read(p: *const Process, addr: u64, buf: []u8) usize { // Nothing is mapped at 0, and a pointer type cannot say 0. if (addr == 0 or buf.len == 0) return 0; const local = [1]std.posix.iovec{.{ .base = buf.ptr, .len = buf.len }}; const remote = [1]std.posix.iovec_const{.{ .base = @ptrFromInt(addr), .len = buf.len }}; const rc = linux.process_vm_readv(p.pid, &local, &remote, 0); return if (linux.errno(rc) == .SUCCESS) rc else 0; } /// 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]; } /// 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; } }; fn check(rc: usize) !usize { return switch (linux.errno(rc)) { .SUCCESS => rc, .SRCH => error.NoSuchProcess, .PERM => error.PermissionDenied, .FAULT, .IO => error.BadAddress, else => error.Ptrace, }; } 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" { 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, "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_); 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(); }