summaryrefslogtreecommitdiff
path: root/src/trace/ptrace.zig
blob: 40a9a7a3ac44e93256b128ac9ad40e011f76cf7e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
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 => {},
    };
}