summaryrefslogtreecommitdiff
path: root/src/cli/record.zig
blob: 8f002f40213e4c6a31059be3ef08c14e90de4857 (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
//! ztrace record: a program under the debugger, left to run, every stop a
//! moment of the recording.
const std = @import("std");
const zt = @import("ztrace");
const util = @import("util.zig");
const disasm = @import("disasm.zig");
const fail = util.fail;

pub const usage =
    \\usage: ztrace record [-o FILE] [--by insn|line|syscall|break] [-b WHERE]... [-w WHAT[,LEN]]...
    \\                     [--from WHERE] [--stack BYTES] [-s BYTES] [--telescope DEPTH]
    \\                     [--around BYTES] [--disasm ROWS] [--steps N]
    \\                     [--max-size BYTES] [--strace]
    \\                     [--ring] [--preload LIB] [--alloc] -- PROGRAM [ARGS]
    \\
    \\Runs PROGRAM under ptrace into a recording (default out.ztrace). --by
    \\says where it stops, each stop a moment:
    \\  insn      every instruction (the default)
    \\  line      every source line, from the program's entry (its loader is run through)
    \\  syscall   every syscall (--syscalls is the same)
    \\  break     the breakpoints only
    \\-b adds a breakpoint, in any of them: a function, file:line or *address.
    \\--from runs the program through to WHERE first, without a stop: the
    \\loader and the C library's start are not what one records by instruction.
    \\-b usdt:PROVIDER:NAME (* for any) records the program's static probes
    \\(USDT) instead, each hit a `probe` event with its arguments, without
    \\stopping there.
    \\Syscalls are recorded whatever the stops are, with at most -s bytes
    \\(default 256) of the path or the buffer each points at; --strace also
    \\prints them, a line each.
    \\Of memory, only what is asked for is recorded, and of that the words
    \\that changed since the stop before: the --stack bytes above the stack
    \\pointer (default 128; and the 128 under it) and each -w region, an address or a symbol, as
    \\long as the symbol unless LEN says.
    \\At every stop the registers and the top of the stack are also followed
    \\as pointers, --telescope deep (default 3, 0 for not at all): what they
    \\lead to is recorded with --around bytes each side of it (default 0:
    \\the 32 at the place; what an instruction reads or writes likewise),
    \\code they lead to is named, and the instructions
    \\at the pc are disassembled, --disasm rows above it and below (default
    \\8), so that a viewer can show what pwndbg's context shows.
    \\--steps ends the recording after N moments, and --max-size when the
    \\file is that large (default 1G). Sizes take a suffix: 64K, 4G.
    \\
++ util.Producer.usage;

/// Runs the target to the breakpoint `id`, or its end, and clears it:
/// what else stops it on the way (a syscall, a signal) is recorded and passed.
fn runTo(d: *zt.Debugger, id: u32) !zt.Debugger.Stop {
    defer d.clear(id);
    while (true) {
        const stop = try d.cont();
        switch (stop) {
            .breakpoint => |at| if (at == id) return stop,
            .exited, .killed => return stop,
            else => {},
        }
    }
}

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 max_moments: u64 = std.math.maxInt(u64);
    var by: enum { insn, line, syscall, @"break" } = .insn;
    var stack_bytes: usize = 128;
    var capture: ?usize = null;
    var max_bytes: ?u64 = null;
    var strace = false;
    var from: ?[]const u8 = null;
    var breaks: std.ArrayList([]const u8) = .empty;
    var watches: std.ArrayList([]const u8) = .empty;
    var producer: util.Producer = .{};
    var telescope: u8 = 3;
    var around: usize = 0;
    var disasm_rows: usize = 8;
    var i: usize = 0;
    while (i < args.len) : (i += 1) {
        const arg = args[i];
        const value: ?[]const u8 = if (i + 1 < args.len) args[i + 1] else null;
        if (std.mem.eql(u8, arg, "--")) {
            i += 1;
            break;
        } else if (std.mem.eql(u8, arg, "--syscalls")) {
            by = .syscall;
        } else if (std.mem.eql(u8, arg, "--strace")) {
            strace = true;
        } else if (producer.take(args, &i)) {
            // Its own argument, when it has one, is taken.
        } else if (value == null) {
            fail(usage, .{});
        } else if (std.mem.eql(u8, arg, "-o")) {
            out = value.?;
            i += 1;
        } else if (std.mem.eql(u8, arg, "--by")) {
            by = std.meta.stringToEnum(@TypeOf(by), value.?) orelse fail("--by needs insn, line, syscall or break\n", .{});
            i += 1;
        } else if (std.mem.eql(u8, arg, "-b")) {
            try breaks.append(arena, value.?);
            i += 1;
        } else if (std.mem.eql(u8, arg, "--from")) {
            from = value.?;
            i += 1;
        } else if (std.mem.eql(u8, arg, "-w")) {
            try watches.append(arena, value.?);
            i += 1;
        } else if (std.mem.eql(u8, arg, "--telescope")) {
            telescope = std.fmt.parseInt(u8, value.?, 10) catch fail("--telescope needs a depth\n", .{});
            i += 1;
        } else if (std.mem.eql(u8, arg, "--around")) {
            around = std.fmt.parseIntSizeSuffix(value.?, 10) catch fail("--around needs a size\n", .{});
            i += 1;
        } else if (std.mem.eql(u8, arg, "--disasm")) {
            disasm_rows = std.fmt.parseInt(usize, value.?, 10) catch fail("--disasm needs a number of rows\n", .{});
            i += 1;
        } else if (std.mem.eql(u8, arg, "--steps")) {
            max_moments = std.fmt.parseInt(u64, value.?, 0) catch fail("--steps needs a number\n", .{});
            i += 1;
        } else if (std.mem.eql(u8, arg, "--stack") or std.mem.eql(u8, arg, "-s") or std.mem.eql(u8, arg, "--max-size")) {
            const size = std.fmt.parseIntSizeSuffix(value.?, 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;
            i += 1;
        } else fail(usage, .{});
    }
    if (i >= args.len) fail(usage, .{});

    const path = try util.resolve(init, args[i]);
    const argv = try util.targetArgv(arena, args[i..]);
    var rec = try zt.Recorder.create(init.gpa, init.io, out);
    // A stop is a moment: the line it is at comes with it, not as one more.
    rec.cut &= ~zt.Kind.line.bit();
    if (max_bytes) |n| rec.max_bytes = n;
    var stderr_buf: [4096]u8 = undefined;
    var stderr = std.Io.File.stderr().writer(init.io, &stderr_buf);
    var printer: zt.syscalls.Printer = .{ .w = &stderr.interface, .next = rec.sink() };

    const produced = try producer.start(arena, init.minimal.environ.block.slice);
    var d = try zt.Debugger.spawn(init.gpa, init.io, path, argv, if (produced) |p| p.envp.ptr else init.minimal.environ.block.slice.ptr, if (strace) printer.sink() else rec.sink());
    defer d.deinit();
    if (produced) |p| d.ring = p.ring;
    d.disasm = disasm.one;
    d.syms.demangle = util.demangle;
    d.telescope = telescope;
    d.telescope_around = around;
    d.disasm_around = disasm_rows;
    // Every word of the stack that is recorded is followed, not the first sixteen only.
    d.telescope_words = @max(d.telescope_words, stack_bytes / 8);
    d.syscalls = if (by == .syscall) .stop else .record;
    d.stack_watch = stack_bytes;
    if (capture) |n| d.capture = n;
    for (breaks.items) |where| {
        if (std.mem.startsWith(u8, where, "usdt:")) {
            // A library's probes are there once the loader has mapped it.
            if (try d.usdt(where[5..]) == 0) {
                try d.toEntry();
                if (try d.usdt(where[5..]) == 0) fail("{s}: no such probe in the program or its libraries\n", .{where});
            }
            // A probe's hit is a moment, as any event asked for by name.
            rec.cut |= zt.Kind.probe.bit();
        } else _ = try d.breakAt(d.resolve(where) catch fail("{s}: no such place in the program\n", .{where}), null);
    }
    for (watches.items) |spec| {
        const comma = std.mem.indexOfScalar(u8, spec, ',') orelse spec.len;
        const what = d.place(spec[0..comma]) orelse fail("{s}: no such symbol\n", .{spec[0..comma]});
        const len = if (comma < spec.len) std.fmt.parseInt(usize, spec[comma + 1 ..], 0) catch fail("{s}: the length is no number\n", .{spec}) else @max(what.size, 8);
        try d.watch(what.addr, len);
    }

    // By line, the loader's hundred thousand instructions are run through
    // to a breakpoint at the entry: there are no lines in them. --from
    // names another place to run through to.
    var entry: ?u32 = null;
    if (from) |where| {
        entry = try d.breakAt(d.resolve(where) catch fail("{s}: no such place in the program\n", .{where}), null);
    } else if (by == .line) if (d.syms.entryPoint()) |at| if (at != d.regs.rip) {
        entry = try d.breakAt(at, null);
    };

    var timer = zt.event.now();
    var exit_code: u64 = 0;
    var full = false;
    while (rec.moments < max_moments) {
        const stop = (if (entry) |id| stop: {
            entry = null;
            break :stop runTo(&d, id);
        } else switch (by) {
            .insn => d.stepi(),
            .line => d.step(),
            .syscall, .@"break" => d.cont(),
        }) catch |err| switch (err) {
            error.RecordingFull => {
                full = true;
                break;
            },
            else => |e| return e,
        };
        switch (stop) {
            .exited => |code| {
                exit_code = code;
                break;
            },
            .killed => |sig| {
                exit_code = 128 + @as(u64, @backingInt(sig));
                break;
            },
            // A signal is delivered by the next resume.
            else => {},
        }
    }
    timer = zt.event.now() - timer;

    const moments = rec.moments + @intFromBool(rec.delta.items.len > 0);
    const events = rec.count;
    try rec.close();
    const size = (try std.Io.Dir.cwd().statFile(init.io, out, .{})).size;
    if (full) std.debug.print("{s}: full at {d} bytes, the program stopped there: record less (--by line, syscall or break; fewer -w; a smaller --stack or -s) or raise --max-size\n", .{ out, size });
    std.debug.print("{s}: {d} moments, {d} events, {d} bytes ({d} bytes/moment), {d:.1} ms, {d:.0} moments/s, exit {d}\n", .{
        out,                                                                       moments,
        events,                                                                    size,
        size / @max(moments, 1),                                                   @as(f64, @floatFromInt(timer)) / 1e6,
        @as(f64, @floatFromInt(moments)) / (@as(f64, @floatFromInt(timer)) / 1e9), exit_code,
    });
}