summaryrefslogtreecommitdiff
path: root/src/cli/dbg.zig
blob: 77ca40a55ea2a94d838c76229e19a5fdbbb08d35 (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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//! ztrace dbg: a program under the debugger, a command a line, every stop a
//! moment of a recording that the same commands can look back into.
const std = @import("std");
const zt = @import("ztrace");
const util = @import("util.zig");
const disasm = @import("disasm.zig");
const show_cmd = @import("show.zig");
const fail = util.fail;
const Moment = zt.store.Moment;

pub const usage =
    \\usage: ztrace dbg [-o FILE] [--stack BYTES] [-s BYTES] [--max-size BYTES]
    \\                  [--ring] [--preload LIB] [--alloc] -- PROGRAM [ARGS]
    \\       ztrace dbg [-o FILE] [--stack BYTES] [-s BYTES] [--max-size BYTES] -p PID
    \\
    \\Starts PROGRAM stopped at its first instruction (or attaches to PID)
    \\and reads commands, from a script when stdin is no terminal:
    \\
    \\  run, r, continue, c   run to a breakpoint, a signal or the exit
    \\  step, s               run to the next source line
    \\  stepi, si             run one instruction
    \\  break, b WHERE        stop at a function, file:line or *address
    \\  syscalls on|off|NAME  stop at each syscall's entry and exit, or at one's
    \\  watch WHAT [LEN]      record a region at every stop: an address or a symbol
    \\  regs                  the registers
    \\  x WHAT [LEN]          memory at an address, a symbol or $register (64 bytes)
    \\  bt                    the call chain, by the unwind tables or the frame pointer
    \\  context, ctx          everything at once, pwndbg's way: registers followed
    \\                        as pointers, the instructions at the pc, the stack
    \\  back [N]              look N moments back in the recording: regs, x
    \\  forward [N]           and bt then show the program as it was. The
    \\  goto MOMENT           program itself stays where it stopped last
    \\  quit, q
    \\
    \\Every stop is a moment of the recording (default out.ztrace), its
    \\number in brackets where it is printed. A moment has the registers,
    \\the words that changed in the --stack bytes above the stack pointer
    \\(default 4K, what bt needs) and in the watched regions, and at most -s
    \\bytes (default 256) of what a syscall points at. The session ends when
    \\the file reaches --max-size (default 1G).
    \\
++ util.Producer.usage;

pub fn run(init: std.process.Init, args: []const [:0]const u8) !void {
    const arena = init.arena.allocator();
    var out: []const u8 = "out.ztrace";
    var pid: ?std.os.linux.pid_t = null;
    // Enough of the stack in every moment for `bt` to work there.
    var stack_bytes: usize = 4096;
    var capture: ?usize = null;
    var max_bytes: ?u64 = null;
    var producer: util.Producer = .{};
    var i: usize = 0;
    while (i < args.len) : (i += 1) {
        const arg = args[i];
        if (std.mem.eql(u8, arg, "--")) {
            i += 1;
            break;
        } else if (producer.take(args, &i)) {
            // Its own argument, when it has one, is taken.
        } else if (std.mem.eql(u8, arg, "-o") and i + 1 < args.len) {
            i += 1;
            out = args[i];
        } else if (std.mem.eql(u8, arg, "-p") and i + 1 < args.len) {
            i += 1;
            pid = std.fmt.parseInt(std.os.linux.pid_t, args[i], 10) catch fail("-p needs a process id\n", .{});
        } else if ((std.mem.eql(u8, arg, "--stack") or std.mem.eql(u8, arg, "-s") or std.mem.eql(u8, arg, "--max-size")) and i + 1 < args.len) {
            i += 1;
            const size = std.fmt.parseIntSizeSuffix(args[i], 10) catch fail("{s} needs a size\n", .{arg});
            if (std.mem.eql(u8, arg, "-s")) capture = size else if (std.mem.eql(u8, arg, "--stack")) stack_bytes = size else max_bytes = size;
        } else fail(usage, .{});
    }
    if ((pid == null) == (i >= args.len)) fail(usage, .{});

    var out_buf: [4096]u8 = undefined;
    var stdout = std.Io.File.stdout().writer(init.io, &out_buf);
    var s: Session = .{ .gpa = init.gpa, .io = init.io, .out = out, .w = &stdout.interface, .rec = try .create(init.gpa, init.io, out), .d = undefined };
    // A moment a stop, syscall entries too: their line comes with them.
    s.rec.cut = (s.rec.cut | zt.Kind.syscall_enter.bit()) & ~zt.Kind.line.bit();
    if (max_bytes) |n| s.rec.max_bytes = n;
    const sink: zt.Sink = .{ .ctx = &s, .emitFn = Session.emit };
    const produced = if (pid == null) try producer.start(arena, init.minimal.environ.block.slice) else null;
    s.d = if (pid) |p|
        zt.Debugger.attach(init.gpa, init.io, p, sink) catch |err| fail("cannot attach to {d}: {t}\n", .{ p, err })
    else
        try zt.Debugger.spawn(init.gpa, init.io, try util.resolve(init, args[i]), try util.targetArgv(arena, args[i..]), if (produced) |p| p.envp.ptr else init.minimal.environ.block.slice.ptr, sink);
    defer s.d.deinit();
    if (produced) |p| s.d.ring = p.ring;
    s.d.disasm = disasm.one;
    s.d.syms.demangle = util.demangle;
    s.d.telescope = 3;
    defer s.stop_payload.deinit(init.gpa);
    s.d.stack_watch = stack_bytes;
    if (capture) |n| s.d.capture = n;
    try s.showStop();

    var in_buf: [4096]u8 = undefined;
    var stdin = std.Io.File.stdin().reader(init.io, &in_buf);
    const interactive = std.Io.File.stdin().isTty(init.io) catch false;
    while (true) {
        try s.w.writeAll("(ztrace) ");
        try s.w.flush();
        const line = (stdin.interface.takeDelimiter('\n') catch break) orelse break;
        // A script's commands show in its transcript, as a terminal echoes them.
        if (!interactive) try s.w.print("{s}\n", .{line});
        try s.w.flush();
        const more = s.command(line) catch |err| switch (err) {
            error.WriteFailed => return,
            // Nothing more can be recorded, so nothing more is run.
            error.RecordingFull => {
                try s.w.print("{s} is full, the program stops here: record less (fewer stops and watches, a smaller --stack or -s) or raise --max-size\n", .{out});
                break;
            },
            else => more: {
                try s.w.print("error: {t}\n", .{err});
                break :more true;
            },
        };
        if (!more) break;
    }
    if (s.trace) |*t| t.close();
    const moments = s.rec.moments;
    try s.rec.close();
    try s.w.print("{s}: {d} moments\n", .{ out, moments });
    try s.w.flush();
}

const Session = struct {
    gpa: std.mem.Allocator,
    io: std.Io,
    out: []const u8,
    w: *std.Io.Writer,
    rec: zt.Recorder,
    d: zt.Debugger,
    /// The moment looked at. Null is the last: the program as it is now.
    view: ?u64 = null,
    /// The recording, opened to look into it.
    trace: ?zt.Trace = null,
    /// The one syscall to stop at, when `syscalls NAME` asked.
    only_syscall: u16 = 0,
    /// The last stop as the debugger sent it: showing it reads no recording.
    stop: zt.Event = .{ .kind = .step },
    stop_payload: std.ArrayList(u8) = .empty,

    /// The debugger's sink: the recorder, with the last stop kept on the way.
    fn emit(ctx: *anyopaque, ev: *const zt.Event, payload: []const u8) anyerror!void {
        const s: *Session = @ptrCast(@alignCast(ctx));
        if (s.rec.cut & ev.kind.bit() != 0) {
            s.stop = ev.*;
            s.stop_payload.clearRetainingCapacity();
            try s.stop_payload.appendSlice(s.gpa, payload);
        }
        return s.rec.emit(ev.*, payload);
    }

    /// The syscall hook of `syscalls NAME`: the others are recorded and run through.
    fn onlySyscall(ctx: ?*anyopaque, _: *zt.Debugger, stop: zt.Debugger.Stop) anyerror!zt.Debugger.Action {
        const only: *const u16 = @ptrCast(@alignCast(ctx.?));
        return switch (stop) {
            .syscall_enter, .syscall_exit => |nr| if (nr == only.*) .stop else .go,
            else => .go,
        };
    }

    /// Runs a command. False to quit.
    fn command(s: *Session, line: []const u8) !bool {
        var words = std.mem.tokenizeAny(u8, line, " \t\r");
        const cmd = words.next() orelse return true;
        const arg = words.next();
        if (is(cmd, "quit", "q")) return false;
        if (is(cmd, "run", "r") or is(cmd, "continue", "c") or is(cmd, "step", "s") or is(cmd, "stepi", "si")) {
            if (s.d.done) return error.Exited;
            // Running leaves the past: the program goes on from where it is.
            s.view = null;
            _ = try if (is(cmd, "step", "s")) s.d.step() else if (is(cmd, "stepi", "si")) s.d.stepi() else s.d.cont();
            try s.showStop();
        } else if (std.mem.eql(u8, cmd, "source-map")) {
            const from = arg orelse return error.MissingArgument;
            const to = words.next() orelse return error.MissingArgument;
            if (words.next() != null) return error.InvalidSourceMap;
            try s.d.mapSource(from, to);
            try s.rec.flush();
        } else if (is(cmd, "break", "b")) {
            const where = arg orelse return error.MissingArgument;
            if (std.mem.startsWith(u8, where, "usdt:")) {
                s.rec.cut |= zt.Kind.probe.bit();
                try s.w.print("{d} probes armed: each hit is recorded, the program runs on\n", .{try s.d.usdt(where[5..])});
                return true;
            }
            const addr = try s.d.resolve(where);
            try s.w.print("breakpoint {d} at ", .{try s.d.breakAt(addr, null)});
            try s.d.describe(s.w, addr);
            try s.w.writeAll("\n");
        } else if (is(cmd, "syscalls", "sys")) {
            const which = arg orelse "on";
            s.d.syscalls = if (std.mem.eql(u8, which, "off")) .ignore else .stop;
            s.d.on_syscall = null;
            if (s.d.syscalls == .stop and !std.mem.eql(u8, which, "on")) {
                s.only_syscall = @intCast(@backingInt(std.meta.stringToEnum(std.os.linux.SYS, which) orelse return error.NoSuchSyscall));
                s.d.on_syscall = .{ .ctx = &s.only_syscall, .func = onlySyscall };
            }
        } else if (is(cmd, "watch", "w")) {
            const what = s.d.place(arg orelse return error.MissingArgument) orelse return error.NoSuchSymbol;
            const len = if (words.next()) |n| try std.fmt.parseInt(usize, n, 0) else @max(what.size, 8);
            try s.d.watch(what.addr, len);
            try s.w.print("watching {d} bytes at {x}\n", .{ len, what.addr });
        } else if (is(cmd, "regs", "reg")) {
            const r = try s.regs(try s.moment());
            inline for (zt.Regs.names, 0..) |name, n| {
                try s.w.print("  {s:<6} {x:0>16}{s}", .{ name, @field(r, name), if (n % 3 == 2) "\n" else "" });
            }
        } else if (is(cmd, "x", "x")) {
            const m = try s.moment();
            const text = arg orelse return error.MissingArgument;
            const addr = if (text[0] == '$')
                (try s.regs(m)).named(text[1..]) orelse return error.NoSuchRegister
            else
                (s.d.place(text) orelse return error.NoSuchSymbol).addr;
            const len = if (words.next()) |n| try std.fmt.parseInt(usize, n, 0) else 64;
            var at: usize = 0;
            while (at < len) : (at += 16) {
                var bytes: [16]u8 = undefined;
                var known: [16]bool = undefined;
                const n = @min(16, len - at);
                try s.fetch(m, addr + at, bytes[0..n], known[0..n]);
                try s.w.print("{x:0>12} ", .{addr + at});
                for (bytes[0..n], known[0..n]) |byte, k| {
                    if (k) try s.w.print(" {x:0>2}", .{byte}) else try s.w.writeAll(" ??");
                }
                try s.w.splatByteAll(' ', (16 - n) * 3 + 2);
                for (bytes[0..n], known[0..n]) |byte, k| try s.w.writeByte(if (k and std.ascii.isPrint(byte)) byte else '.');
                try s.w.writeAll("\n");
            }
        } else if (is(cmd, "bt", "backtrace")) {
            const m = try s.moment();
            const r = try s.regs(m);
            const at_entry = if (s.d.syms.symbolAt(r.rip)) |sym| sym.addr == r.rip else false;
            var frames: [64]u64 = undefined;
            for (zt.Debugger.backtrace(Memory{ .s = s, .m = m }, &r, at_entry, &frames), 0..) |pc, n| {
                try s.w.print("#{d} ", .{n});
                try s.d.describe(s.w, pc);
                try s.w.writeAll("\n");
            }
        } else if (is(cmd, "context", "ctx")) {
            // The whole of the moment looked at, as `ztrace show` prints it.
            const t = try s.recording();
            var arena: std.heap.ArenaAllocator = .init(s.gpa);
            defer arena.deinit();
            try show_cmd.state(arena.allocator(), t, s.view orelse t.len - 1, s.w, std.Io.File.stdout().isTty(s.io) catch false);
        } else if (is(cmd, "back", "forward") or is(cmd, "goto", "goto")) {
            const t = try s.recording();
            const n = if (arg) |a| try std.fmt.parseInt(u64, a, 10) else if (is(cmd, "goto", "goto")) return error.MissingArgument else 1;
            const now = s.view orelse t.len - 1;
            const to = if (std.mem.eql(u8, cmd, "back")) now -| n else if (std.mem.eql(u8, cmd, "forward")) @min(now +| n, t.len - 1) else n;
            if (to >= t.len) return error.NoSuchMoment;
            s.view = if (to == t.len - 1) null else to;
            try s.show(to);
        } else return error.UnknownCommand;
        return true;
    }

    fn is(cmd: []const u8, long: []const u8, short: []const u8) bool {
        return std.mem.eql(u8, cmd, long) or std.mem.eql(u8, cmd, short);
    }

    /// The recording with everything so far in it.
    fn recording(s: *Session) !*zt.Trace {
        try s.rec.flush();
        if (s.trace) |*t| t.close();
        s.trace = null;
        s.trace = try zt.Trace.open(s.gpa, s.io, s.out);
        return &s.trace.?;
    }

    /// The moment commands look at: null for the running program itself.
    fn moment(s: *Session) !?Moment {
        if (s.view == null and !s.d.done) return null;
        const t = try s.recording();
        return try t.moment(s.view orelse t.len - 1);
    }

    /// The thread a moment stopped in, and its registers then.
    fn regs(s: *Session, m: ?Moment) !zt.Regs {
        const past = m orelse return s.d.regs;
        var events = try past.events(s.gpa);
        defer events.deinit(s.gpa);
        var tid: u32 = @intCast(s.d.proc.pid);
        while (events.next()) |item| tid = item.ev.tid;
        return (try past.regs(tid)) orelse error.NoRegisters;
    }

    /// Memory as of a moment, or the program's: `known` tells the bytes there are.
    fn fetch(s: *Session, m: ?Moment, addr: u64, buf: []u8, known: []bool) !void {
        if (m) |past| return past.read(addr, buf, known);
        const n = s.d.read(addr, buf);
        @memset(known[0..n], true);
        @memset(known[n..], false);
    }

    /// What `Debugger.backtrace` reads frames from.
    const Memory = struct {
        s: *Session,
        m: ?Moment,

        pub fn read(mem: Memory, addr: u64, buf: []u8) usize {
            var known: [16]bool = undefined;
            mem.s.fetch(mem.m, addr, buf, known[0..buf.len]) catch return 0;
            return std.mem.indexOfScalar(bool, known[0..buf.len], false) orelse buf.len;
        }

        /// The program's call frame information, the same now as at any moment.
        pub fn cfi(mem: Memory, pc: u64) ?zt.Symbols.Cfi {
            return mem.s.d.cfi(pc);
        }
    };

    /// The stop the program is at now.
    fn showStop(s: *Session) !void {
        return s.print(s.rec.moments - 1, &s.stop, s.stop_payload.items, if (s.d.done) null else s.d.regs.rip);
    }

    /// The stop that ended a moment of the recording.
    fn show(s: *Session, index: u64) !void {
        const m = try (try s.recording()).moment(index);
        var events = try m.events(s.gpa);
        defer events.deinit(s.gpa);
        var last: ?zt.store.Events.Item = null;
        while (events.next()) |item| last = item;
        const stop = last orelse return;
        return s.print(index, &stop.ev, stop.payload, if (try m.regs(stop.ev.tid)) |r| r.rip else null);
    }

    /// A stop's line: its moment, what it was, and where.
    fn print(s: *Session, index: u64, ev: *const zt.Event, payload: []const u8, pc: ?u64) !void {
        try s.w.print("[{d}] ", .{index});
        switch (ev.kind) {
            .exit => return s.w.print("exited {d}\n", .{ev.a[0]}),
            .breakpoint => try s.w.print("breakpoint {d}", .{ev.a[1]}),
            .signal => try s.w.print("signal {t}", .{@as(std.os.linux.SIG, @fromBackingInt(@intCast(ev.aux)))}),
            .syscall_enter => {
                try s.w.writeAll("syscall ");
                try zt.syscalls.formatEnter(s.w, ev, payload);
            },
            .syscall_exit => {
                try s.w.print("syscall {s}", .{zt.syscalls.name(ev.aux) orelse "?"});
                try zt.syscalls.formatExit(s.w, ev);
            },
            else => try s.w.print("{t}", .{ev.kind}),
        }
        if (pc) |at| {
            try s.w.writeAll(" at ");
            try s.d.describe(s.w, at);
        }
        try s.w.writeAll("\n");
    }
};