//! ztrace show: what a recording holds, and the program's state at a moment. const std = @import("std"); const zt = @import("ztrace"); const util = @import("util.zig"); pub const usage = \\usage: ztrace show FILE [MOMENT] \\ \\Without MOMENT: how many moments and events, and events by kind. \\With one (negative counts from the end), the context as of that moment, \\pwndbg's way: each thread's registers, every one followed as far as it \\points (a name for code, a string where there is one), the instructions \\at the pc, the top of the stack followed likewise, each word with what \\it is where the recording says (saved rbp, return address, a local by \\name, the canary's copy, argv[1]), the source line and \\the open calls; then glibc's heap when it was recorded (record --heap: \\its chunks, the tcache and the bins, each chunk on a list followed by its \\link as stored, in brackets, where safe-linking changed it), the live \\allocations, the named variables with their \\bytes, and the mapped regions. On a terminal a pointer is coloured by \\where it points: code red, stack yellow, heap blue, data purple, \\writable-and-executable underlined. \\ ; pub fn run(init: std.process.Init, args: []const [:0]const u8) !void { if (args.len < 1 or args.len > 2) util.fail(usage, .{}); var trace = try zt.Trace.open(init.gpa, init.io, args[0]); defer trace.close(); var buf: [4096]u8 = undefined; var file_writer = std.Io.File.stdout().writer(init.io, &buf); const w = &file_writer.interface; const result = if (args.len == 1) summary(init.gpa, &trace, w) else blk: { const n = std.fmt.parseInt(i64, args[1], 10) catch util.fail(usage, .{}); const index = if (n < 0) @as(i64, @intCast(trace.len)) + n else n; if (index < 0 or index >= trace.len) util.fail("{s}: {d} moments, no moment {d}\n", .{ args[0], trace.len, n }); break :blk state(init.arena.allocator(), &trace, @intCast(index), w, std.Io.File.stdout().isTty(init.io) catch false); }; result catch |err| switch (err) { // The reader went away (`| head`): not an error. error.WriteFailed => return, else => |e| return e, }; w.flush() catch {}; } fn summary(gpa: std.mem.Allocator, trace: *zt.Trace, w: *std.Io.Writer) !void { var by_kind: [64]u64 = @splat(0); var total: u64 = 0; for (0..trace.len) |index| { var events = try (try trace.moment(index)).events(gpa); defer events.deinit(gpa); while (events.next()) |item| : (total += 1) by_kind[@intFromEnum(item.ev.kind) & 63] += 1; } try w.print("{d} moments, {d} events\n", .{ trace.len, total }); for (by_kind, 0..) |n, kind| { if (n != 0) try w.print("{d:>10} {t}\n", .{ n, @as(zt.Kind, @enumFromInt(kind)) }); } } /// A string id as text, or the id itself when the recording never defined it. fn name(m: zt.store.Moment, arena: std.mem.Allocator, id: u64) ![]const u8 { const buf = try arena.alloc(u8, 4096); return (try m.string(id, buf)) orelse std.fmt.allocPrint(arena, "#{x}", .{id}); } /// A value and what it leads to: `7ffd1000 —▸ 5555b010 ◂— "hello"`. fn telescope(m: zt.store.Moment, w: *std.Io.Writer, value: u64, colour: bool) !void { var links: [5]zt.telescope.Link = undefined; var text: [64]u8 = undefined; for (try zt.telescope.chase(m, value, &links, &text), 0..) |link, i| { if (i > 0) try w.writeAll(if (link.region == .none) " ◂— " else " —▸ "); const paint: []const u8 = if (!colour) "" else switch (link.region) { .none => "", .code => "\x1b[31m", .rwx => "\x1b[4;31m", .stack => "\x1b[33m", .heap => "\x1b[34m", .data => "\x1b[35m", .rodata => "\x1b[2m", }; try w.print("{s}{x}{s}", .{ paint, link.value, if (paint.len > 0) "\x1b[0m" else "" }); if (link.string) try w.print(" ◂— \"{f}\"", .{std.zig.fmtString(link.text)}) else if (link.text.len > 0) try w.print(" ({s})", .{link.text}); } } /// What a stack word is (`zt.telescope.slots`), after its chain: `saved /// rbp`, `return address`, a local by name (`buf+8` a word into it, `i[0..4], /// n[4..8]` where it fills part of the word), `argv[1]`; nothing where the /// recording does not say. `word` is what it holds: 0 ends argv and envp. fn role(w: *std.Io.Writer, slot: zt.telescope.Slot, word: u64, colour: bool) !void { if (slot.role == .none) return; try w.writeAll(if (colour) " \x1b[2m" else " "); switch (slot.role) { .none => {}, .saved => |reg| try w.print("saved {s}", .{reg}), .return_address => try w.writeAll("return address"), .local => |first| for ([_]?zt.telescope.Local{first} ++ slot.also, 0..) |each, i| { const l = each orelse break; if (i > 0) try w.writeAll(", "); try w.writeAll(l.name); if (l.offset > 0) try w.print("+{x}", .{l.offset}); const from: i64 = @max(0, -l.offset); const to: i64 = if (l.size == 0) 8 else @min(8, @as(i64, l.size) - l.offset); if (from > 0 or to < 8) try w.print("[{d}..{d}]", .{ from, to }); }, .argc => try w.writeAll("argc"), .argv => |i| if (word == 0) try w.writeAll("argv end") else try w.print("argv[{d}]", .{i}), .envp => |i| if (word == 0) try w.writeAll("envp end") else try w.print("envp[{d}]", .{i}), .auxv => |i| try w.print("auxv[{d}]", .{i}), } if (colour) try w.writeAll("\x1b[0m"); } pub fn state(arena: std.mem.Allocator, trace: *zt.Trace, index: u64, w: *std.Io.Writer, colour: bool) !void { const m = try trace.moment(index); try w.print("moment {d} of {d}, {d} events so far\n", .{ index, trace.len, try m.count() }); for (try m.threads(arena)) |tid| { try w.print("\nthread {d}", .{tid}); if (try m.line(tid)) |line| try w.print(" {s}:{d}:{d}", .{ try name(m, arena, line.file), line.line, line.column }); try w.writeAll("\n"); if (try m.regs(tid)) |regs| { inline for (zt.Regs.names) |reg| { try w.print(" {s:<6} ", .{reg}); if (comptime std.mem.eql(u8, reg, "eflags")) try w.print("{x}", .{regs.eflags}) else try telescope(m, w, @field(regs, reg), colour); try w.writeAll("\n"); } // The instructions round the pc, as far as the recording has them: // eight above (inside a function they are known), the pc's, eight below. var text: [192]u8 = undefined; var from = regs.rip; for (0..8) |_| { const insn = (try zt.telescope.instruction(m, from, &text)) orelse break; if (insn.back == 0) break; from -= insn.back; } var pc = from; var below: usize = 0; try w.writeAll("\n"); while (below <= 8) { const insn = (try zt.telescope.instruction(m, pc, &text)) orelse break; try w.print("{s}{x:0>12} {s}\n", .{ if (pc == regs.rip) " ► " else " ", pc, insn.text }); if (pc >= regs.rip) below += 1; pc += insn.len; } // The top of the stack, a word a row, and what each word is. var words: [8]u64 = undefined; var known: [64]bool = undefined; try m.read(regs.rsp, std.mem.sliceAsBytes(&words), &known); var slots: [8]zt.telescope.Slot = undefined; _ = try zt.telescope.slots(m, ®s, regs.rsp, &slots); if (known[0]) try w.writeAll("\n"); for (words, slots, 0..) |word, slot, i| { if (!known[i * 8]) break; try w.print(" {x:0>2}:{x:0>4}│ {s} ", .{ i, i * 8, if (i == 0) "rsp" else " " }); try telescope(m, w, regs.rsp + i * 8, colour); try role(w, slot, word, colour); try w.writeAll("\n"); } } if (try m.regs(tid)) |regs| { // The call chain, by frame pointer; the calls the program itself // reported (instrumentation, hooks) follow it when there are any. var frames: [32]u64 = undefined; const chain = try zt.telescope.backtrace(m, ®s, &frames); if (chain.len > 1) try w.writeAll("\n"); if (chain.len > 1) for (chain, 0..) |pc, depth| { var text: [256]u8 = undefined; try w.print(" #{d} {x} {s}", .{ depth, pc, (try m.string(pc, &text)) orelse "" }); // Its line, as `bt` gives it: the pc's, a caller's call's (recorded `back` from where it returns). var at = pc; if (depth > 0) if (try zt.telescope.instruction(m, pc, &text)) |after| { at -= after.back; }; if (try zt.telescope.instruction(m, at, &text)) |insn| if (insn.line) |l| { try w.print(" ({s}:{d})", .{ std.fs.path.basename(try name(m, arena, l.file)), l.line }); }; try w.writeAll("\n"); }; } for (try m.stack(arena, tid), 0..) |frame, depth| { try w.print(" #{d} {s} from {x} sp {x}\n", .{ depth, try name(m, arena, frame.function), frame.site, frame.sp }); } } // glibc's heap (`record --heap`), with the tcache of the thread that stopped. var last_tid: u32 = 0; var events = try m.events(arena); while (events.next()) |item| last_tid = item.ev.tid; if (try zt.heap.glibc(arena, m, last_tid)) |h| try zt.heap.print(h, w); const heap = try m.heap(arena); if (heap.len > 0) try w.print("\nheap: {d} live\n", .{heap.len}); for (heap) |a| try w.print(" {x:0>12} {d:>8} bytes, by {x}, event {d}\n", .{ a.ptr, a.size, a.pc, a.born }); const variables = try m.variables(arena); if (variables.len > 0) try w.writeAll("\nvariables\n"); for (variables) |v| { var bytes: [16]u8 = undefined; var known: [16]bool = undefined; const n: usize = @intCast(@min(v.size, bytes.len)); try m.read(v.addr, bytes[0..n], known[0..n]); try w.print(" {x:0>12} {s}: {s} =", .{ v.addr, try name(m, arena, v.name), try name(m, arena, v.type) }); for (bytes[0..n], known[0..n]) |byte, k| { if (k) try w.print(" {x:0>2}", .{byte}) else try w.writeAll(" ??"); } try w.print("{s}\n", .{if (v.size > n) " ..." else ""}); } const mappings = try m.mappings(arena); if (mappings.len > 0) try w.writeAll("\nmappings\n"); var last: []const u8 = ""; for (mappings) |region| { var path: []const u8 = ""; var path_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; _ = try m.mapping(region.addr, &path, &path_buf); // As /proc/pid/maps has it: what may be done there, and where in the file it is from. const p = region.prot; try w.print(" {x:0>12}-{x:0>12} {c}{c}{c} {x:0>8} {s}", .{ region.addr, region.addr + region.len, @as(u8, if (p & 1 != 0) 'r' else '-'), @as(u8, if (p & 2 != 0) 'w' else '-'), @as(u8, if (p & 4 != 0) 'x' else '-'), region.offset, path }); // A module, once: which build it is, and whether its names come from its own debug info. if (!std.mem.eql(u8, path, last)) if (zt.telescope.module(m, path)) |module| { if (module.build_id.len > 0) try w.print(" build-id {x},", .{module.build_id}) else try w.writeAll(" no build id,"); try w.print(" debug info {s}", .{switch (module.debug) { .none => "none", .own => "in the file", .separate => "separate, of the same build", } }); }; last = try arena.dupe(u8, path); try w.writeAll("\n"); } }