summaryrefslogtreecommitdiff
path: root/src/trace/ptrace.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/trace/ptrace.zig')
-rw-r--r--src/trace/ptrace.zig158
1 files changed, 158 insertions, 0 deletions
diff --git a/src/trace/ptrace.zig b/src/trace/ptrace.zig
new file mode 100644
index 0000000..40a9a7a
--- /dev/null
+++ b/src/trace/ptrace.zig
@@ -0,0 +1,158 @@
+//! 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.
+const std = @import("std");
+const linux = std.os.linux;
+const event = @import("event.zig");
+const Regs = event.Regs;
+const P = linux.PTRACE;
+
+pub const Stop = union(enum) {
+ /// A single step finished, or a breakpoint was hit.
+ trap,
+ /// At a syscall's entry or exit (they alternate).
+ syscall,
+ /// A signal is about to be delivered; `resume_signal` holds it.
+ signal: linux.SIG,
+ exited: u8,
+ killed: linux.SIG,
+};
+
+pub const Process = struct {
+ pid: linux.pid_t,
+ /// The signal the next resume delivers.
+ resume_signal: u32 = 0,
+ in_syscall: bool = false,
+
+ /// 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) };
+ switch (try p.wait()) {
+ // 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));
+ return p;
+ }
+
+ /// One instruction.
+ pub fn stepi(p: *Process) !Stop {
+ return p.run(P.SINGLESTEP);
+ }
+
+ /// Until the next breakpoint, signal or exit.
+ pub fn cont(p: *Process) !Stop {
+ return p.run(P.CONT);
+ }
+
+ /// Until the next syscall entry or exit.
+ pub fn syscall(p: *Process) !Stop {
+ return p.run(P.SYSCALL);
+ }
+
+ fn run(p: *Process, request: u32) !Stop {
+ _ = try check(linux.ptrace(request, p.pid, 0, p.resume_signal, 0));
+ p.resume_signal = 0;
+ return p.wait();
+ }
+
+ fn wait(p: *Process) !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) };
+ const sig: u32 = (status >> 8) & 0xff;
+ if (sig == @intFromEnum(linux.SIG.TRAP) | 0x80) {
+ p.in_syscall = !p.in_syscall;
+ return .syscall;
+ }
+ if (sig == @intFromEnum(linux.SIG.TRAP)) return .trap;
+ p.resume_signal = sig;
+ return .{ .signal = @enumFromInt(sig) };
+ }
+
+ pub fn regs(p: *const Process) !Regs {
+ var out: Regs = undefined;
+ _ = try check(linux.ptrace(P.GETREGS, p.pid, 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));
+ }
+
+ /// 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 {
+ 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;
+ }
+
+ /// 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;
+ }
+ }
+
+ pub fn kill(p: *Process) void {
+ _ = linux.kill(p.pid, .KILL);
+ var status: u32 = 0;
+ _ = linux.waitpid(p.pid, @ptrCast(&status), 0);
+ }
+};
+
+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,
+ };
+}
+
+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();
+ 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((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 std.testing.expectEqual(@as(usize, 16), p.read(before.rsp - 64, &buf));
+ try std.testing.expectEqualStrings("0123456789a", buf[0..11]);
+ try std.testing.expectEqual(@as(usize, 0), p.read(8, &buf));
+
+ try std.testing.expectEqual(Stop.syscall, try p.syscall());
+ while (true) switch (try p.cont()) {
+ .exited => |code| {
+ try std.testing.expectEqual(@as(u8, 0), code);
+ break;
+ },
+ else => {},
+ };
+}