//! 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"); } };