//! 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] [--heap] \\ [--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. \\--heap also records glibc's heap at every stop, as `ztrace show` reads it \\(pwndbg's heap and bins): each chunk's size word, the main arena, the \\tcache, and the links of every chunk on a list; at most 4096 chunks and \\256 entries a list. glibc 2.40 and 2.44 only, linked dynamically or \\statically; the main arena's heap, the stopped thread's tcache. \\--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 heap = 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 (std.mem.eql(u8, arg, "--heap")) { heap = 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 (heap) d.heap = .{}; 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 }); if (d.heap) |h| if (h.glibc) |g| { std.debug.print("heap: glibc {d}.{d}{s}, main_arena {x}{s}\n", .{ g.major, g.minor, if (g.by_size != 0) " (no version in the binary: by the size of main_arena)" else "", g.arena, if (h.tcache == null) ", no tcache seen" else "" }); } else switch (h.trouble) { .none => std.debug.print("heap: not recorded: no glibc malloc found\n", .{}), .no_version => std.debug.print("heap: not recorded: no glibc version in the C library, nor a main_arena symbol\n", .{}), .no_layout => std.debug.print("heap: not recorded: no layout known for glibc {d}.{d} (known: 2.40, 2.44)\n", .{ h.version[0], h.version[1] }), .no_arena => std.debug.print("heap: not recorded: more than one place in glibc looks like the main arena\n", .{}), }; 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, }); }