From c3d9f7ba5effd615374b1359ad98ecf801559f83 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 11 Nov 2026 00:06:30 -0300 Subject: canim: a call followed down to the kernel; rows that say what they do; the heap from the inside From the user. The disassembly can descend: the syscalls scene is glibc's hello by instruction, and open is followed from main through its PLT stub, whose jmp reads the GOT, into libc's wrapper to the syscall row, which crosses to the kernel's window under it, and back up. The band keeps the calls so far as strace writes them. Operands lose their size words and show a width as byte cells only where nothing else says it. A compare shows its values and the flags it leaves, a jump the flags it reads, lea its result, an indirect jump its target and the slot it read, a call that has run its C form. The backtrace has its newest frame at the bottom. A new scene shows glibc 2.44's heap from blocks that exist: chunks read by fields (a size with its bits, a protected pointer), the free list as arcs, the tcache in a loupe, the program's list over malloc's own. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016Y9MNCKgYCGiANnEwcEQxa --- anim/src/Recording.zig | 16 +- anim/src/calls.zig | 12 +- anim/src/context.zig | 31 ++- anim/src/descent.zig | 620 ++++++++++++++++++++++++++++++++++++++++++ anim/src/disasm.zig | 717 +++++++++++++++++++++++++++++++++++++++++-------- anim/src/hexdump.zig | 79 +++++- anim/src/loupe.zig | 28 +- anim/src/root.zig | 20 +- anim/src/rows.zig | 12 +- anim/src/source.zig | 37 ++- anim/src/syscalls.zig | 252 ++++++----------- anim/src/theme.zig | 10 + anim/src/ties.zig | 8 +- 13 files changed, 1512 insertions(+), 330 deletions(-) create mode 100644 anim/src/descent.zig (limited to 'anim/src') diff --git a/anim/src/Recording.zig b/anim/src/Recording.zig index 833d17b..1a4d859 100644 --- a/anim/src/Recording.zig +++ b/anim/src/Recording.zig @@ -218,6 +218,14 @@ pub fn ownLine(r: *const Recording, i: u64) ?u32 { return l.line; } +/// Whether the pc at moment `i` is in the program's own source: not in a +/// library's code, a PLT stub, the vDSO (where `own` keeps the last line). +pub fn sourced(r: *const Recording, i: u64) bool { + var buf: [256]u8 = undefined; + const here = r.instruction(i, r.register(i, "rip"), &buf) orelse return r.ownLine(i) != null; + return here.line != null; +} + /// The first line a source panel of `fit` lines shows when the program is /// on `line`: the whole file when it fits; else a window that has the line /// in its middle third, and is the same window for every line of that @@ -425,7 +433,13 @@ fn index(r: *Recording) !void { try touch_list.append(arena, touched); pending = touched; try branch_list.append(arena, branched); - if (ours and regs != null) try code_lines.put(gpa, regs.?.rip, line.line); + // Not where the instruction says it has no line: a library's code (a + // PLT stub, libc) keeps the last line of ours in `lines`, and is not of it. + if (ours and regs != null) { + var text: [256]u8 = undefined; + const here = zt.telescope.instruction(m, regs.?.rip, &text) catch null; + if (here == null or here.?.line != null) try code_lines.put(gpa, regs.?.rip, line.line); + } try registers.append(arena, regs orelse before orelse .{}); if (!told and stepped and regs != null and before != null) { diff --git a/anim/src/calls.zig b/anim/src/calls.zig index 5eef946..d78c26c 100644 --- a/anim/src/calls.zig +++ b/anim/src/calls.zig @@ -127,8 +127,8 @@ pub const Tree = struct { } } - /// Its view: the backtrace, the waiting path read as rows, newest on - /// top, with each call's arguments (`n=4`) and where it is. + /// Its view: the backtrace, the waiting path read as rows, newest at + /// the bottom, with each call's arguments (`n=4`) and where it is. fn backtrace(k: *const Tree, f: *sk.Frame, at: anim.Placed) void { const box = k.stage.box(at, .view); const cm = theme.metric.context; @@ -143,10 +143,12 @@ pub const Tree = struct { var buf: [24]context.Frame = undefined; const chain = context.frames(rec, moment, &buf); const room = theme.layout.rowsIn(box.h); - const body = u.panel(box.w, box.h, "backtrace", .{ .note = if (chain.len > room) u.print("the calls waiting \u{00b7} newest on top \u{00b7} {d} more", .{chain.len - room}) else "the calls waiting \u{00b7} newest on top" }); + const body = u.panel(box.w, box.h, "backtrace", .{ .note = u.print("the calls waiting \u{00b7} {s}", .{context.newestAtBottom(u, chain.len, room)}) }); const open = rec.stack(f.scratch, moment); - for (chain[0..@min(chain.len, room)], 0..) |frame, i| { - const y = body.y + cm.pad + @as(f32, @floatFromInt(i)) * cm.row; + // Newest at the bottom, as the tree grows down beside it; the oldest go from the top. + const shown = @min(chain.len, room); + for (chain[0..shown], 0..) |frame, i| { + const y = body.y + cm.pad + @as(f32, @floatFromInt(shown - 1 - i)) * cm.row; const name = ui.symbol(u, rec.strings.get(frame.pc) orelse u.print("{x}", .{frame.pc})); // The call this frame is, by its place on the chain: its arguments. rows.callRow(u, y, box.w, i, name, context.callArguments(u, rec, open, i, frame.pc), context.frameWhere(u, rec, now.marked(), i, frame.pc), i == 0); diff --git a/anim/src/context.zig b/anim/src/context.zig index e5a226a..6123d26 100644 --- a/anim/src/context.zig +++ b/anim/src/context.zig @@ -140,7 +140,9 @@ pub const Registers = struct { if (age) |a| changed = rec.register(now.stops[a], "eflags") ^ rec.register(now.stops[a + 1], "eflags"); const heat = now.register(eflags_index, delay); const held = if (r.quiet) 0 else heat.level * heat.corner; - rows.rip(u, y, w, rec.moment(moment), rec.register(moment, "rip"), flags, changed, held, 0); + // While a conditional jump runs, the flags it reads are framed (an echo of the row that set them). + const reads: u64 = if (now.resting() or now.advancing() >= 0.5) 0 else @import("disasm.zig").readsFlags(rec, now.stops[1]); + rows.rip(u, y, w, rec.moment(moment), rec.register(moment, "rip"), flags, changed, held, 0, reads, now.reading(.cpu, 0)); } fn row(r: *const Registers, u: ui.Ui, now: cursors.Now, line_is: Shown, line_was: Shown, name: []const u8, y: f32, w: f32) void { @@ -288,8 +290,10 @@ fn callLine(rec: *const Recording, moment: u64, ret: u64) ?u32 { /// A frame's name: its function's (no offset), or its module's and offset where there is no symbol. pub fn frameName(u: ui.Ui, rec: *const Recording, pc: u64) []const u8 { const name = rec.strings.get(pc) orelse return u.print("{x}", .{pc}); - if (std.mem.indexOfScalar(u8, name, '!') != null) return ui.symbol(u, name); - return name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len]; + const shown = ui.symbol(u, name); + // A library's symbol (`libc.so.6!open+0`) by its name alone; one with none, `libc+27781`. + if (std.mem.indexOfScalar(u8, name, '!') != null and shown.ptr != name.ptr + std.mem.indexOfScalar(u8, name, '!').? + 1) return shown; + return shown[0 .. std.mem.lastIndexOfScalar(u8, shown, '+') orelse shown.len]; } /// The registers (of the sixteen) that hold `addr` in `regs`. @@ -489,7 +493,7 @@ pub const Stack = struct { for (pointers.items) |p_| { const word, const saved = p_; if (saved and !(now.writeAge(word.addr, 8) == 0 or now.wasRead(word.addr, 8))) continue; - hexdump.pointerArcs(&arcs, now, word.addr, word.y, at_rows.items, 8, .{ top - m.pad, box.h - m.pad }, false); + hexdump.pointerArcs(&arcs, now, word.addr, word.y, at_rows.items, 8, .{ top - m.pad, box.h - m.pad }, false, false); } arcs.draw(v, theme.metric.arc.stack_lanes); // Where the window is, for a link to a word outside it. @@ -659,30 +663,33 @@ pub const Backtrace = struct { const arrive = std.math.clamp((since - time.quick / 2.0 - time.move) / time.quick, 0, 1); const room = rowsOf(box); const total = chains[if (slide >= 0.5) 1 else 0].len; - const body = u.panel(box.w, box.h, "backtrace", .{ .focus = b.focus, .note = if (total > room) u.print("newest on top \u{00b7} {d} more", .{total - room}) else "newest on top" }); + const body = u.panel(box.w, box.h, "backtrace", .{ .focus = b.focus, .note = newestAtBottom(u, total, room) }); clipBody(u, box); defer u.unclip(); const opens = [2][]const Recording.Call{ rec.stack(u.f.scratch, now.stops[1]), rec.stack(u.f.scratch, now.stops[0]) }; const top = body.y + m.pad; + // Newest at the bottom, `#0` last: a frame's row is its place from + // the oldest, less the oldest that do not fit (dropped from the top). + const dropped = [2]usize{ chains[0].len -| room, chains[1].len -| room }; for (chains, 0..) |chain, side| { const shows = if (side == 0) 1 - leave else arrive; - for (chain[0..@min(chain.len, room + shared)], 0..) |frame, i| { + for (chain, 0..) |frame, i| { const from_end = chain.len - 1 - i; const kept = from_end < shared; // A frame both have is drawn once, from the old chain to its place in the new. if (kept and side == 1) continue; - var at_row: f32 = @floatFromInt(i); + var at_row = @as(f32, @floatFromInt(from_end)) - @as(f32, @floatFromInt(dropped[side])); var depth = i; var which = side; if (kept) { const to = chains[1].len - 1 - from_end; - at_row = std.math.lerp(at_row, @as(f32, @floatFromInt(to)), slide); + at_row = std.math.lerp(at_row, @as(f32, @floatFromInt(from_end)) - @as(f32, @floatFromInt(dropped[1])), slide); if (slide >= 0.5) { depth = to; which = 1; } } else if (shows <= 0) continue; - if (at_row >= @as(f32, @floatFromInt(room))) continue; + if (at_row <= -1 or at_row >= @as(f32, @floatFromInt(room))) continue; const v = if (kept) u else u.faded(shows); const name = ui.symbol(u, rec.strings.get(frame.pc) orelse u.print("{x}", .{frame.pc})); rows.callRow(v, top + at_row * m.row, box.w, depth, name, callArguments(u, rec, opens[which], depth, frame.pc), frameWhere(u, rec, if (which == 1) now.marks[1] else now.marks[0], depth, frame.pc), depth == 0); @@ -692,6 +699,12 @@ pub const Backtrace = struct { } }; +/// A backtrace's tag note: `newest at the bottom`, and how many of the +/// oldest a panel of `room` rows leaves out above. +pub fn newestAtBottom(u: ui.Ui, total: usize, room: usize) []const u8 { + return if (total > room) u.print("newest at the bottom \u{00b7} {d} more above", .{total - room}) else "newest at the bottom"; +} + test "the flags' bits" { try std.testing.expectEqual(@as(?usize, 17), index("eflags")); } diff --git a/anim/src/descent.zig b/anim/src/descent.zig new file mode 100644 index 0000000..302de38 --- /dev/null +++ b/anim/src/descent.zig @@ -0,0 +1,620 @@ +//! `descent` (design/README.md, "3. Panels"): the disassembly a level up, +//! a call followed down. The panel is a stack of windows, one a call deep: +//! the scene's function's on top, each callee's under the row that called +//! it (that row `waiting`, ringed; a PLT stub gone through keeps its `jmp`, +//! `pass`), a head row over each, the call lane from ring to head; and +//! under the deepest, while a system call crosses, the kernel on vellum. +//! Down is deeper, and the way back up is drawn. +//! +//! Every row has a key (an instruction's address, a head's function), so +//! the panel at one moment and at the next are two lists of the same +//! rows: a step is the rows both have gliding, and the others leaving or +//! arriving, on the timetable of its verb (`descend`, `ascend`, `cross`; +//! design/motion.md, "A call followed down", "A system call"). +const std = @import("std"); +const sk = @import("sketch"); +const anim = @import("anim"); +const ui = @import("ui.zig"); +const rows = @import("rows.zig"); +const cursors = @import("cursor.zig"); +const Recording = @import("Recording.zig"); +const ties = @import("ties.zig"); +const map = @import("map.zig"); +const context = @import("context.zig"); +const disasm = @import("disasm.zig"); +const syscalls = @import("syscalls.zig"); +const Stage = @import("stage.zig").Stage; +const theme = ui.theme; +const Rect = ui.Rect; +const t = theme.color.text; +const k = theme.color.on_kernel; +const m = theme.metric.context; +const c = theme.metric.insn; +const size = theme.size.mono.context; +const adv = size * 3 / 5; +const Insn = disasm.Insn; + +/// Frames at 60 a second, as motion.md counts them. +fn f(n: f32) f32 { + return n / 60.0; +} + +fn clamp01(v: f32) f32 { + return std.math.clamp(v, 0, 1); +} + +/// One step of `by` from where the cursor is, timed as its verb +/// (design/motion.md, "A call followed down"): into a call (`descend`, 2.7 +/// s), on through a PLT stub's `jmp` (2.0 s), out by a `ret` (`ascend`, 2.3 +/// s), across into the kernel (`cross`: `syscalls.step`); any other walked. +pub fn step(cur: cursors.Cursor, s: *anim.Frame, by: Recording.Stop) void { + const rec = cur.rec; + const from = cur.moment(s); + const to = rec.next(by, from); + for (rec.syscalls) |made| if (made.enter > from and made.enter <= to) return syscalls.step(cur, s, by); + if (to != from + 1) return cur.walk(s, by, to); + const b = rec.insn_branches[from] orelse return cur.walk(s, by, to); + var name_buf: [256]u8 = undefined; + const here = (rec.moment(from).string(rec.register(from, "rip"), &name_buf) catch null) orelse ""; + const plan: cursors.Plan = switch (b.kind) { + .call => .{ .at = .{ f(24), f(60), f(60) }, .advance = f(126), .travel = f(12), .total = f(162) }, + .ret => .{ .at = .{ f(36), f(18), f(36) }, .advance = f(102), .travel = f(12), .total = f(138) }, + .jump => if (std.mem.indexOf(u8, here, "@plt") != null) .{ .at = .{ f(18), f(24), f(24) }, .advance = f(84), .travel = f(12), .total = f(120) } else return cur.walk(s, by, to), + .none => return cur.walk(s, by, to), + }; + cur.step(s, to, plan, plan.total); +} + +/// A row of the panel. +const Item = struct { + key: u64, + row: f32, + /// The window it is in, 0 the top. + window: u8, + what: union(enum) { insn: Insn, head: struct { name: []const u8, note: []const u8 }, more: []const u8 }, + state: enum { plain, waiting, pass, current } = .plain, + /// A waiting or passed row: the moment it ran. + at: u64 = 0, +}; + +/// The panel at a moment. +const Layout = struct { + items: []Item, + /// Windows of code (a fold counts as none). + windows: usize, + /// The bottom three rows are the kernel's (the pc is at, or has just + /// come back from, a `syscall`). + kernel: bool, + /// The deepest function and its module: the panel's tag. + tag: []const u8, + in_stub: bool, +}; + +pub const Descent = struct { + cursor: cursors.Cursor, + stage: *const Stage, + focus: bool = false, + /// The function whose window is on top: where the scene follows from. + root: []const u8 = "main", + + pub fn draw(d: *const Descent, fr: *sk.Frame, placed: anim.Placed) void { + const box = d.stage.box(placed, .disasm); + const u = context.at(fr, placed, box); + const now = d.cursor.now(placed); + const rec = d.cursor.rec; + const room = theme.layout.rowsIn(box.h); + const before = layout(u, rec, now.stops[1], room, d.root); + const after = layout(u, rec, now.stops[0], room, d.root); + const tm = now.time; + const going = now.advancing(); + const kind: enum { same, down, through, up } = if (now.resting() or now.stops[0] == now.stops[1]) .same else if (after.windows > before.windows) (if (before.in_stub) .through else .down) else if (after.windows < before.windows) .up else .same; + const shown = if (going >= 0.5) after else before; + const body = u.panel(box.w, box.h, "disassembly", .{ .focus = d.focus, .note = shown.tag }); + const top = body.y + m.pad; + u.clip(.{ .x = theme.stroke.rule, .y = m.tag, .w = box.w - 2 * theme.stroke.rule, .h = box.h - m.tag - theme.stroke.rule }); + defer u.unclip(); + + // How far the rows both lists have are on their way, and how much + // of each that leaves or comes shows: the verb's timetable. + const move: f32 = switch (kind) { + .same => cursors.glide(going), + .down => cursors.glide(clamp01((tm - f(72)) / f(18))), + .through => cursors.glide(clamp01((tm - f(24)) / f(18))), + .up => cursors.glide(clamp01((tm - f(84)) / f(18))), + }; + const Placed = struct { item: Item, y: f32, shows: f32, rise: f32, old: ?Item, new: ?Item }; + var placed_items: std.ArrayList(Placed) = .empty; + const a = u.f.scratch; + // Leaving: bottom up when a window closes, all at once when a caller gives up rows. + var leaving: usize = 0; + var i = before.items.len; + while (i > 0) { + i -= 1; + const it = before.items[i]; + if (find(after.items, it.key)) |_| continue; + const shows: f32 = switch (kind) { + .same => 1 - clamp01(2 * going), + .down => 1 - clamp01((tm - f(66)) / f(12)), + .through => 1 - clamp01((tm - f(24)) / f(12)), + .up => 1 - clamp01((tm - f(48) - @as(f32, @floatFromInt(leaving)) * f(2)) / f(12)), + }; + leaving += 1; + placed_items.append(a, .{ .item = it, .y = top + it.row * m.row, .shows = shows, .rise = 0, .old = it, .new = null }) catch {}; + } + // Arriving: a head rising, then its rows top down, 2 f apart. + var arriving: usize = 0; + for (after.items) |it| { + if (find(before.items, it.key)) |old| { + const y = top + std.math.lerp(old.row, it.row, move) * m.row; + // Going up the rows keep what they were (the ring) until the advance. + const now_item = switch (kind) { + .same, .up => if (going >= 0.5) it else old, + // The call row is current until its plaque becomes the ring; a stub's jmp until it passes. + .down => if (tm >= f(72)) it else old, + .through => if (tm >= f(24)) it else old, + }; + placed_items.append(a, .{ .item = now_item, .y = y, .shows = 1, .rise = 0, .old = old, .new = it }) catch {}; + continue; + } + const head = it.what == .head; + const shows: f32 = switch (kind) { + .same => clamp01(2 * going - 1), + .down => if (head) clamp01((tm - f(96)) / f(12)) else clamp01((tm - f(102) - @as(f32, @floatFromInt(arriving)) * f(2)) / f(12)), + .through => if (head) clamp01((tm - f(54)) / f(12)) else clamp01((tm - f(60) - @as(f32, @floatFromInt(arriving)) * f(2)) / f(12)), + .up => clamp01((tm - f(84)) / f(18)), + }; + if (!head) arriving += 1; + placed_items.append(a, .{ .item = it, .y = top + it.row * m.row, .shows = shows, .rise = if (head and kind != .same) (1 - cursors.standard(shows)) * theme.time.caption_rise else 0, .old = null, .new = it }) catch {}; + } + std.mem.sort(Placed, placed_items.items, {}, struct { + fn above(_: void, x: Placed, y: Placed) bool { + return x.y < y.y; + } + }.above); + + // The marks: the pc's plaque, leaving the row it was on and landing + // on the next; the ring on a waiting call; a passed stub's bar. + const marked = now.marks[if (going >= 0.5) 1 else 0]; + const plaque = [2]f32{ + // The one it leaves: in a descend it becomes the ring (72 to 84 f), + // through a stub the pass bar (24 to 36), up it closes with its window. + switch (kind) { + .same => 1, + .down => 1 - clamp01((tm - f(72)) / f(12)), + .through => 1 - clamp01((tm - f(24)) / f(12)), + .up => 1 - clamp01((tm - f(48)) / f(12)), + }, + // The one it lands on, with the advance. + if (kind == .same) 1 else clamp01(going * 2), + }; + var pc_y = [2]?f32{ null, null }; + for (placed_items.items) |p| { + if (p.old) |o| if (o.state == .current) { + pc_y[0] = p.y; + }; + if (p.new) |n| if (n.state == .current) { + pc_y[1] = p.y; + }; + } + // In one window the plaque slides from row to row, with the advance. + var mark: ?struct { y: f32, shows: f32 } = null; + if (kind == .same) { + if (pc_y[0] != null and pc_y[1] != null) mark = .{ .y = std.math.lerp(pc_y[0].?, pc_y[1].?, cursors.standard(going)), .shows = 1 } else if (pc_y[1]) |y| { + mark = .{ .y = y, .shows = clamp01(2 * going - 1) }; + } else if (pc_y[0]) |y| { + mark = .{ .y = y, .shows = 1 - clamp01(2 * going) }; + } + } + const fire = now.fires(.disasm); + if (mark) |mk| plaqueAt(u, box.w, mk.y, mk.shows, fire) else { + if (pc_y[0]) |y| if (going < 0.5) plaqueAt(u, box.w, y, plaque[0], fire); + if (pc_y[1]) |y| if (going >= 0.5) plaqueAt(u, box.w, y, plaque[1], 0); + } + + // Which rows ran in the last three steps: the trail. + const ran = recentRows(a, now, if (going >= 0.5) 0 else 1); + const current_line = rec.own[marked]; + const widen0 = rows.numberRoom(rec.line_count); + var covered: usize = 0; + var runs: disasm.Runs = .{}; + var last_line: ?u32 = null; + var last_window: ?u8 = null; + const dd: disasm.Disasm = .{ .cursor = d.cursor, .stage = d.stage }; + const base: usize = if (going >= 0.5) 0 else 1; + for (placed_items.items) |p| { + const v = u.faded(p.shows); + const y = p.y + p.rise; + if (p.shows <= 0) continue; + if (last_window == null or last_window.? != p.item.window) last_line = null; + last_window = p.item.window; + switch (p.item.what) { + .head => |h| { + v.fill(.{ .x = theme.stroke.rule, .y = y, .w = box.w - 2 * theme.stroke.rule, .h = theme.stroke.rule }, theme.color.rule); + v.text(.sans_medium, theme.size.sans.micro, c.address, y + 18, h.name, t.primary); + v.text(.sans, theme.size.sans.micro, box.w - m.side - v.width(.sans, theme.size.sans.micro, h.note), y + 18, h.note, t.faint); + covered -|= 1; + }, + .more => |words| { + _ = v.arrow(c.address, y + m.row / 2, .more); + v.text(.mono, size, c.address + m.arrow_w + adv, rows.baseline(y), words, t.faint); + covered -|= 1; + }, + .insn => |row| { + const window_items = windowOf(placed_items.items, p.item.window); + var addrs: [80]u64 = undefined; + var n: usize = 0; + for (window_items) |w| if (w.item.what == .insn and n < addrs.len) { + addrs[n] = w.item.key; + n += 1; + }; + const lead = ui.shared(addrs[0..n]); + const wide = @as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv; + const line = if (row.outside) null else row.line; + const state: disasm.Disasm.State = switch (p.item.state) { + // The row the plaque has not reached yet is ahead. + .current => if (p.old == null or p.old.?.state != .current) (if (going >= 0.5) .current else .ahead) else if (p.new == null or p.new.?.state != .current) (if (going < 0.5) .current else .ahead) else .current, + .waiting => .{ .waiting = p.item.at }, + .pass => .{ .ran = .{ .k = 0, .at = p.item.at } }, + .plain => if (ranOf(ran, row.addr)) |r| .{ .ran = r } else .ahead, + }; + // The marks at the row's left: the trail, the ring, the pass. + switch (p.item.state) { + .plain => if (ranOf(ran, row.addr)) |r| v.trail(c.mark, y, r.k), + .pass => v.trail(c.mark, y, 0), + .waiting => { + // The ring comes as the plaque leaves; going up it becomes a trail bar. + const ring: f32 = if (p.old != null and p.old.?.state == .waiting) (if (kind == .up) 1 - clamp01((tm - f(102)) / f(12)) else 1) else if (kind == .down) clamp01((tm - f(72)) / f(12)) else 1; + ringAt(v.faded(ring), y); + if (ring < 1) v.faded(1 - ring).trail(c.mark, y, 0); + }, + .current => {}, + } + runs.add(line != null and line.? == current_line, y, y + m.row); + const hangs = dd.insn(v, now, row, y, box.w, widen0 + wide, line, line != last_line, current_line, lead, state, base, covered > 0, .{ addrs[0], addrs[n -| 1] }, null); + covered = @max(covered -| 1, hangs); + last_line = line; + map.row(.disasm, row.addr, u, .{ .x = 0, .y = y, .w = box.w, .h = m.row }); + }, + } + } + runs.add(false, box.h, box.h); + disasm.threadRuns(u, box.w, .{ .{}, runs }, 1); + + // The call lane: from each waiting ring (or passed jmp) down to the + // head of the window under it, turning in to its name. + for (placed_items.items) |p| { + if (p.item.what != .head or p.item.window == 0) continue; + const from = for (placed_items.items) |q| { + if (q.item.window + 1 == p.item.window and (q.item.state == .waiting or q.item.state == .pass)) break q; + } else continue; + const drawn: f32 = if (p.old != null and p.new != null) 1 else if (p.new != null) switch (kind) { + .down => clamp01((tm - f(84)) / f(18)), + .through => clamp01((tm - f(42)) / f(18)), + else => clamp01(2 * going - 1), + } else switch (kind) { + .up => 1 - clamp01((tm - f(72)) / f(12)), + else => 1 - clamp01(2 * going), + }; + if (drawn <= 0) continue; + const ya = from.y + m.row - 3; + const yb = p.y + m.row / 2; + u.route(&.{ .{ 14, ya }, .{ 14, yb }, .{ c.address - 4, yb } }, t.primary, .{ .width = theme.stroke.rule, .head = .{ 7, 8 }, .radius = 4, .progress = cursors.standard(drawn) }); + } + map.window(.disasm, first(shown), last(shown)); + if (pc_y[1] orelse pc_y[0]) |y| ties.anchor(u, .pc, .{ .x = 0, .y = y, .w = theme.metric.plaque.pc, .h = m.row }); + kernel(u, now, box, top, room, pc_y[0] orelse pc_y[1]); + context.veiled(u, box, now.veil); + } +}; + +/// The pc's plaque on the row at `y`. +fn plaqueAt(u: ui.Ui, w: f32, y: f32, shows: f32, fire: f32) void { + if (shows <= 0) return; + const v = u.faded(shows); + v.current(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = m.row }, theme.metric.plaque.pc, fire); + sk.draw.polygon(u.f, &.{ .{ 20, y + m.row / 2 }, .{ 10, y + 6 }, .{ 10, y + m.row - 6 } }, v.at.pen(.{ .fill = ui.rgb(theme.mark(.current).on_solid) })); +} + +/// `waiting`: the plaque's place ringed, a 2-unit primary frame 24 by 24 +/// with a primary head in it, as a waiting call node is; no wash. +fn ringAt(u: ui.Ui, y: f32) void { + u.frame(.{ .x = c.mark + 1, .y = y + 1, .w = 22, .h = 22 }, t.primary, theme.stroke.rule); + sk.draw.polygon(u.f, &.{ .{ 19, y + m.row / 2 }, .{ 10, y + 7 }, .{ 10, y + m.row - 7 } }, u.at.pen(.{ .fill = ui.rgb(t.primary) })); +} + +fn find(items: []const Item, key: u64) ?Item { + for (items) |it| if (it.key == key) return it; + return null; +} + +fn windowOf(items: anytype, window: u8) @TypeOf(items) { + var lo: usize = items.len; + var hi: usize = 0; + for (items, 0..) |p, j| if (p.item.window == window) { + lo = @min(lo, j); + hi = j + 1; + }; + return if (lo < hi) items[lo..hi] else items[0..0]; +} + +fn first(l: Layout) u64 { + for (l.items) |it| if (it.what == .insn) return it.key; + return 0; +} + +fn last(l: Layout) u64 { + var out: u64 = 0; + for (l.items) |it| if (it.what == .insn) { + out = it.key; + }; + return out; +} + +const Ran = disasm.Disasm.Ran; +const RanRow = struct { addr: u64, ran: Ran }; + +/// The rows the last three steps ran (`base`: 1 while the mark is still +/// on the step's first row), the newest step's mark on each. +fn recentRows(a: std.mem.Allocator, now: cursors.Now, base: usize) []const RanRow { + var out: std.ArrayList(RanRow) = .empty; + for (0..3) |s| { + const from = now.stops[@min(base + 1 + s, now.stops.len - 1)]; + const to = now.stops[base + s]; + var at = to; + while (at > from and to - at < 512) { + at -= 1; + const pc = now.rec.register(at, "rip"); + if (ranOf(out.items, pc) == null) out.append(a, .{ .addr = pc, .ran = .{ .k = s, .at = at } }) catch break; + // A return marks the call it comes back from: it has run, with its result. + if (now.rec.insn_branches[at]) |b| if (b.kind == .ret) { + var buf: [256]u8 = undefined; + const after = now.rec.instruction(at, b.to, &buf) orelse continue; + if (after.back == 0) continue; + const call = b.to - after.back; + if (ranOf(out.items, call) == null) out.append(a, .{ .addr = call, .ran = .{ .k = s, .at = madeAt(now.rec, at, call) } }) catch break; + }; + } + } + return out.items; +} + +fn ranOf(list: []const RanRow, addr: u64) ?Ran { + for (list) |r| if (r.addr == addr) return r.ran; + return null; +} + +/// A level of the descent: a function's window. +const Level = struct { at: u64, kind: enum { caller, pass, deepest }, name: []const u8, moment: u64 = 0 }; + +/// The panel at moment `i`, `room` rows: the root's window on top, a +/// window a call deep under it, the deepest round the pc, three at most +/// (a longer chain keeps the first and the last two, the rest one row). +fn layout(u: ui.Ui, rec: *const Recording, i: u64, room: usize, root: []const u8) Layout { + const a = u.f.scratch; + var items: std.ArrayList(Item) = .empty; + const pc = rec.register(i, "rip"); + var buf: [24]context.Frame = undefined; + const chain = context.frames(rec, i, &buf); + var r: usize = 0; + for (chain, 0..) |fr, j| if (std.mem.eql(u8, context.frameName(u, rec, fr.pc), root)) { + r = j; + break; + }; + var levels: [24]Level = undefined; + var n: usize = 0; + var j = r; + while (j > 0 and n + 2 < levels.len) : (j -= 1) { + const call = callBefore(u, rec, i, chain[j].pc) orelse break; + levels[n] = .{ .at = call.addr, .kind = .caller, .name = context.frameName(u, rec, chain[j].pc), .moment = madeAt(rec, i, call.addr) }; + n += 1; + // Through a stub to a function that is not it: the stub's jmp, passed. + if (disasm.target(call)) |to| { + const stub = context.frameName(u, rec, to); + if (std.mem.endsWith(u8, stub, "@plt") and !std.mem.eql(u8, stub, context.frameName(u, rec, chain[j - 1].pc))) { + levels[n] = .{ .at = to, .kind = .pass, .name = stub, .moment = madeAt(rec, i, to) }; + n += 1; + } + } + } + const here = context.frameName(u, rec, pc); + const in_stub = std.mem.endsWith(u8, here, "@plt"); + levels[n] = .{ .at = pc, .kind = .deepest, .name = here }; + n += 1; + // Folded past three windows: the first, then a row of `more`, then the last two. + var fold: []const u8 = ""; + var kept: []const Level = levels[0..n]; + var kept_buf: [3]Level = undefined; + if (n > 3) { + fold = u.print("{d} calls:", .{n - 3}); + for (levels[1 .. n - 2]) |l| fold = u.print("{s} {s}", .{ fold, l.name }); + kept_buf = .{ levels[0], levels[n - 2], levels[n - 1] }; + kept = &kept_buf; + } + // At a `syscall`, or just back from one: the floor is the kernel's. + const at_syscall = isSyscall(rec, i, pc) or (i > 0 and isSyscall(rec, i - 1, rec.register(i - 1, "rip")) and rec.register(i - 1, "rip") + 2 == pc); + var fixed: usize = if (at_syscall and kept.len > 1) 3 else 0; + for (kept, 0..) |l, li| { + if (li > 0) fixed += 1; + fixed += switch (l.kind) { + .caller => 3, + .pass => 1, + .deepest => 0, + }; + } + if (fold.len > 0) fixed += 1; + const remaining = room -| fixed; + const deepest_rows = if (kept.len == 1) room else if (in_stub) @min(remaining, stubRows(rec, i, pc)) else remaining; + const extra = remaining -| deepest_rows; + var row: f32 = 0; + var tag: []const u8 = ""; + for (kept, 0..) |l, li| { + const window: u8 = @intCast(li); + if (li == 1 and fold.len > 0) { + items.append(a, .{ .key = std.hash.Wyhash.hash(1, fold), .row = row, .window = window, .what = .{ .more = fold } }) catch {}; + row += 1; + } + if (li > 0) { + items.append(a, .{ .key = std.hash.Wyhash.hash(0, l.name) | 1 << 63, .row = row, .window = window, .what = .{ .head = .{ .name = l.name, .note = headNote(u, rec, i, l) } } }) catch {}; + row += 1; + } + const nearest = li + 2 == kept.len and l.kind == .caller; + const count: usize = switch (l.kind) { + .caller => 3 + if (nearest) extra else 0, + .pass => 1, + .deepest => deepest_rows, + }; + const above: usize = switch (l.kind) { + .caller => (count - 1) / 2, + .pass => 0, + // Under a `syscall` four rows hold its arguments. + .deepest => if (in_stub) 0 else if (isSyscall(rec, i, pc) and count > 5) count - 5 else (count -| 1) / 2, + }; + const list = disasm.listingAt(u, rec, i, l.at, count, above); + for (list.rows, 0..) |insn, q| { + const on = q == list.pc; + items.append(a, .{ .key = insn.addr, .row = row + @as(f32, @floatFromInt(q)), .window = window, .what = .{ .insn = insn }, .state = if (!on) .plain else switch (l.kind) { + .caller => .waiting, + .pass => .pass, + .deepest => .current, + }, .at = l.moment }) catch {}; + } + row += @floatFromInt(count); + if (l.kind == .deepest) tag = if (kept.len == 1) l.name else u.print("{s} \u{00b7} {s}", .{ l.name, moduleOf(u, rec, i, pc) }); + } + return .{ .items = items.items, .windows = kept.len, .kernel = at_syscall, .tag = tag, .in_stub = in_stub }; +} + +/// The call instruction a return address `ret` comes back after. +fn callBefore(u: ui.Ui, rec: *const Recording, i: u64, ret: u64) ?Insn { + var buf: [256]u8 = undefined; + const after = rec.instruction(i, ret, &buf) orelse return null; + if (after.back == 0) return null; + const at = ret - after.back; + const call = rec.instruction(i, at, &buf) orelse return null; + if (!std.mem.startsWith(u8, call.text, "call")) return null; + return .{ .addr = at, .len = call.len, .text = u.print("{s}", .{call.text}) }; +} + +/// The moment the instruction at `addr` last ran, at or before `i`. +fn madeAt(rec: *const Recording, i: u64, addr: u64) u64 { + var at = i; + while (at > 0 and i - at < 4096) : (at -= 1) if (rec.register(at, "rip") == addr) return at; + return i; +} + +fn isSyscall(rec: *const Recording, i: u64, pc: u64) bool { + var buf: [256]u8 = undefined; + const here = rec.instruction(i, pc, &buf) orelse return false; + return std.mem.eql(u8, here.text, "syscall"); +} + +/// How many instructions a PLT stub at `pc` has (three: its `jmp`, a push, a jmp to the resolver). +fn stubRows(rec: *const Recording, i: u64, pc: u64) usize { + var buf: [256]u8 = undefined; + var at = pc; + var n: usize = 0; + while (n < 4) : (n += 1) { + const one = rec.instruction(i, at, &buf) orelse break; + if (n > 0 and one.back == 0) break; + at += one.len; + } + return @max(n, 1); +} + +/// A window's head note: what the code is (`libc.so.6 · no source`, +/// `the PLT · its jmp reads open@got, 403fd8`, the program's file). +fn headNote(u: ui.Ui, rec: *const Recording, i: u64, l: Level) []const u8 { + if (std.mem.endsWith(u8, l.name, "@plt")) { + if (l.kind == .pass) return "the PLT, jumped through"; + var buf: [256]u8 = undefined; + const jmp = rec.instruction(i, l.at, &buf) orelse return "the PLT"; + const ops = std.mem.trim(u8, jmp.text[(std.mem.indexOfScalar(u8, jmp.text, ' ') orelse jmp.text.len)..], " "); + const at = std.mem.indexOf(u8, ops, "[rip + 0x") orelse return "the PLT"; + const close = std.mem.indexOfScalarPos(u8, ops, at, ']') orelse return "the PLT"; + const slot = l.at + jmp.len + (std.fmt.parseInt(u64, ops[at + 9 .. close], 16) catch return "the PLT"); + const named = ui.symbol(u, rec.strings.get(slot) orelse ""); + return u.print("the PLT \u{00b7} its jmp reads {s}, {x}", .{ named[0 .. std.mem.lastIndexOfScalar(u8, named, '+') orelse named.len], slot }); + } + const module = moduleOf(u, rec, i, l.at); + if (std.mem.eql(u8, module, "[vdso]")) return "vdso \u{00b7} the kernel's code, run here"; + var buf: [256]u8 = undefined; + if ((@import("ztrace").telescope.instruction(rec.moment(i), l.at, &buf) catch null)) |here| if (here.line != null) return rec.file; + return u.print("{s} \u{00b7} no source", .{module}); +} + +/// The file `addr`'s mapping is of, by its base name. +fn moduleOf(u: ui.Ui, rec: *const Recording, i: u64, addr: u64) []const u8 { + var name: []const u8 = ""; + var buf: [256]u8 = undefined; + _ = (rec.moment(i).mapping(addr, &name, &buf) catch null) orelse return ""; + return u.print("{s}", .{std.fs.path.basename(name)}); +} + +/// The kernel's window, at the floor, while a step crosses: the crossing +/// lane down from the pc's plaque, the vellum filling down from its head, +/// the head and the call in C's form, `returns` and what crossed back +/// with what it clobbered; the answer up the lane; and at the advance the +/// window drawing back up into the lane. +fn kernel(u: ui.Ui, now: cursors.Now, box: Rect, top: f32, room: usize, pc_y: ?f32) void { + if (!now.crossings or !now.walking()) return; + const made = syscalls.inStep(now) orelse return; + const rec = now.rec; + const p = syscalls.Plan.of(made); + const tm = now.time; + const y0 = top + @as(f32, @floatFromInt(room -| 3)) * m.row; + const from = (pc_y orelse y0 - m.row) + m.row; + const back_up = clamp01((tm - now.plan.advance) / f(12)); + // The lane: down 24 f from the plaque, 3 units of vellum; back into it after the window. + const down = cursors.standard(clamp01((tm - p.enters) / syscalls.Plan.cross)); + const lane_gone = clamp01((tm - now.plan.advance - f(12)) / f(12)); + if (down > 0 and lane_gone < 1) { + const end = std.math.lerp(from, y0 + 4, down * (1 - lane_gone)); + u.fill(.{ .x = 14 - 1.5, .y = from, .w = 3, .h = @max(end - from, 0) }, theme.color.kernel); + } + // The answer climbs the lane to the `syscall` row: a head of vellum going up it. + const climb = cursors.standard(clamp01((tm - p.back) / syscalls.Plan.cross)); + if (climb > 0 and climb < 1) { + const yh = std.math.lerp(y0, from, climb); + sk.draw.polygon(u.f, &.{ .{ 14, yh - 8 }, .{ 7, yh + 2 }, .{ 21, yh + 2 } }, u.at.pen(.{ .fill = ui.rgb(theme.color.kernel) })); + } + const opens = cursors.standard(clamp01((tm - p.enters - f(18)) / f(12))) * (1 - back_up); + if (opens <= 0) return; + const h = 3 * m.row * opens; + u.fill(.{ .x = theme.stroke.rule, .y = y0, .w = box.w - 2 * theme.stroke.rule, .h = h }, theme.color.kernel); + u.clip(.{ .x = 0, .y = y0, .w = box.w, .h = h }); + defer u.unclip(); + // The lane's head, in ink on the vellum. + sk.draw.polygon(u.f, &.{ .{ 14, y0 + 10 }, .{ 10, y0 + 2 }, .{ 18, y0 + 2 } }, u.at.pen(.{ .fill = ui.rgb(k.ink) })); + const name = @import("ztrace").syscalls.name(made.nr) orelse "syscall"; + const head = u.faded(clamp01((tm - p.enters - f(30)) / f(6))); + head.text(.sans_medium, theme.size.sans.micro, c.address, y0 + 18, "the kernel", k.ink); + const what = u.print("{s}, system call {d}", .{ name, made.nr }); + head.text(.sans, theme.size.sans.micro, box.w - m.side - u.width(.sans, theme.size.sans.micro, what), y0 + 18, what, k.dim); + // The call in C's form, as the kernel took it. + const names = @import("ztrace").syscalls.names(made.nr); + const n = @min(@import("ztrace").syscalls.signature(made.nr).len, 6); + var call: []const u8 = u.print("{s}(", .{name}); + for (0..n) |j| call = u.print("{s}{s}{s}", .{ call, if (j > 0) ", " else "", disasm.argument(u, rec, made.enter, if (j < names.len) names[j] else "", made.args[j]) }); + call = u.print("{s})", .{call}); + u.faded(clamp01((tm - p.enters - f(36)) / f(6))).text(.mono, size, c.address, rows.baseline(y0 + m.row), rows.fitted(u, call, box.w - m.side - c.address), k.ink); + // `returns`: the value, struck as it lands in the kernel's rows. + const ry = y0 + 2 * m.row; + const returns = tm - p.returns; + u.faded(clamp01((tm - p.enters - f(36)) / f(6))).text(.mono, size, c.address, rows.baseline(ry), "returns", k.dim); + if (returns >= 0 and made.exit != null) { + const got: i64 = @bitCast(made.result); + const value = u.print("{d}", .{got}); + const x = c.address + 8 * adv; + const cell: Rect = .{ .x = x, .y = ry, .w = @as(f32, @floatFromInt(value.len)) * adv, .h = m.row }; + const heat = now.heat(0, null, returns); + const ink = u.written(cell, heat) orelse ui.Ink{ .ink = ui.rgb(k.ink) }; + u.text(ink.face, size, x, rows.baseline(ry), value, ink.ink); + var end = x + cell.w + adv; + const on = rec.openOn(u.f.scratch, made.result, made.exit.? + 1); + if (std.mem.eql(u8, name, "openat") or std.mem.eql(u8, name, "open")) if (on.len > 0) { + u.text(.mono, size, end, rows.baseline(ry), on, k.dim); + end += u.width(.mono, size, on) + 2 * adv; + }; + u.text(.mono, size, end + adv, rows.baseline(ry), "rcx, r11: clobbered", k.dim); + } +} diff --git a/anim/src/disasm.zig b/anim/src/disasm.zig index 7f17ed6..0b6f931 100644 --- a/anim/src/disasm.zig +++ b/anim/src/disasm.zig @@ -41,8 +41,18 @@ pub const Insn = struct { /// A direct call's callee's parameter count. params: ?u8 = null, + /// Its mnemonic, with a prefix that is part of it (`rep stosq`). pub fn mnemonic(i: Insn) []const u8 { - return i.text[0 .. std.mem.indexOfScalar(u8, i.text, ' ') orelse i.text.len]; + const first = std.mem.indexOfScalar(u8, i.text, ' ') orelse return i.text; + for ([_][]const u8{ "rep", "repe", "repz", "repne", "repnz", "lock", "notrack", "bnd" }) |prefix| if (std.mem.eql(u8, i.text[0..first], prefix)) { + return i.text[0 .. std.mem.indexOfScalarPos(u8, i.text, first + 1, ' ') orelse i.text.len]; + }; + return i.text[0..first]; + } + + /// Padding, which touches nothing: drawn faint. + pub fn padding(i: Insn) bool { + return std.mem.startsWith(u8, i.mnemonic(), "nop") or std.mem.eql(u8, i.mnemonic(), "endbr64"); } pub fn operands(i: Insn) []const u8 { @@ -51,9 +61,11 @@ pub const Insn = struct { }; /// The window at a moment: the instructions, and which is the pc's. -const Listing = struct { rows: []Insn, pc: usize }; +pub const Listing = struct { rows: []Insn, pc: usize }; pub const Disasm = struct { + /// An instruction, as a row draws it. + pub const Row = Insn; cursor: cursors.Cursor, stage: *const Stage, focus: bool = false, @@ -171,6 +183,9 @@ pub const Disasm = struct { var lanes: [2]?f32 = .{ null, null }; // A call's arguments hang in the annotation column of the rows under it. var covered: usize = 0; + // What the window holds: a jump out of it says where it goes. + const window = [2]u64{ if (merged.len > 0) merged[0].addr else 0, if (merged.len > 0) merged[merged.len - 1].addr else 0 }; + const echo = jumpEcho(now, base); for (merged, 0..) |row, j| { const y = top + (@as(f32, @floatFromInt(j)) - scroll) * m.row; const line = if (row.outside) null else row.line; @@ -188,7 +203,7 @@ pub const Disasm = struct { const is_pc = row.addr == pc[if (going >= 0.5) 1 else 0]; const was = if (is_pc) null else ran[j]; if (was) |r| lit.trail(c.mark, y, r.k); - const hangs = d.insn(lit, now, row, y, box.w, widen, line, line != last_line, current_line, lead, if (is_pc) .current else if (was) |r| .{ .ran = r } else .ahead, base, covered > 0); + const hangs = d.insn(lit, now, row, y, box.w, widen, line, line != last_line, current_line, lead, if (is_pc) .current else if (was) |r| .{ .ran = r } else .ahead, base, covered > 0, window, echo); covered = @max(covered -| 1, hangs); last_line = if (above_body) null else line; if (jumped == row.addr and !is_pc) lanes[0] = y; @@ -205,9 +220,16 @@ pub const Disasm = struct { context.veiled(u, box, now.veil); } - const State = union(enum) { current, ran: Ran, ahead }; + pub const State = union(enum) { + current, + ran: Ran, + ahead, + /// A call whose callee's window is open under it (a `descent`): the + /// moment it was made. + waiting: u64, + }; /// A row that ran `k` steps ago (0 newest), last at moment `at`. - const Ran = struct { k: usize, at: u64 }; + pub const Ran = struct { k: usize, at: u64 }; /// `insn`: an instruction and its annotation, pwndbg's way. Nothing is /// cut that has room: the operands run on to where the annotation must @@ -215,7 +237,7 @@ pub const Disasm = struct { /// where the annotation carries the address they name. `covered`: a /// call's arguments above hang in this row's annotation column. Returns /// how many rows under it its own arguments hang in. - fn insn(d: *const Disasm, at: ui.Ui, now: cursors.Now, row: Insn, y: f32, w: f32, widen: f32, line: ?u32, first_of_line: bool, current_line: u32, lead: usize, state: State, base: usize, covered: bool) usize { + pub fn insn(d: *const Disasm, at: ui.Ui, now: cursors.Now, row: Insn, y: f32, w: f32, widen: f32, line: ?u32, first_of_line: bool, current_line: u32, lead: usize, state: State, base: usize, covered: bool, window: [2]u64, echo: ?Echo) usize { const rec = d.cursor.rec; const base_y = rows.baseline(y); const code_ink = theme.color.region.code_; @@ -228,8 +250,9 @@ pub const Disasm = struct { _ = at.address(c.address, base_y, row.addr, .{ .ink = ui.mix(code_ink, theme.color.page, theme.metric.context.lead_alpha) }); u.text(.mono, size, c.mnemonic, base_y, row.mnemonic(), t.faint); const name = if (rec.strings.get(row.addr)) |n| n[0 .. std.mem.lastIndexOfScalar(u8, n, '+') orelse n.len] else ""; - const x = if (name.len > 0) annotationX(operandsWidth(row, row.operands()), room, @as(f32, @floatFromInt(name.len)) * adv) else room + gap; - u.text(.mono, size, c.operands, base_y, rows.fitted(u, row.operands(), (if (covered) c.annotation else x) - gap - c.operands), t.faint); + const ops = shorn(u, row); + const x = if (name.len > 0) annotationX(operandsWidth(u, row, ops, ""), room, @as(f32, @floatFromInt(name.len)) * adv) else room + gap; + operands(u, row, ops, "", base_y, (if (covered) c.annotation else x) - gap - c.operands, t.faint); u.text(.mono, size, x, base_y, name, t.faint); return 0; } @@ -239,33 +262,31 @@ pub const Disasm = struct { const now_line = l == current_line; u.text(if (now_line) .mono_bold else .mono, size, c.line + 3 * adv - @as(f32, @floatFromInt(num.len)) * adv, base_y, num, if (now_line) theme.mark(.current).solid else t.faint); }; - u.text(.mono_bold, size, c.mnemonic, base_y, row.mnemonic(), theme.color.code.keyword); + // Padding touches nothing: faint, with its operands. + const pad = row.padding(); + u.text(.mono_bold, size, c.mnemonic, base_y, row.mnemonic(), if (pad) t.faint else theme.color.code.keyword); // How wide the annotation is, drawn where nothing shows; then where it goes. - const need = d.annotation(u.faded(0), now, row, y, c.annotation, std.math.inf(f32), state, base); + const need = d.annotation(u.faded(0), now, row, y, c.annotation, std.math.inf(f32), state, base, window, echo); // When the operands and the annotation do not both fit: the - // annotation moves left (never past its column), then a size word - // a register already gives goes, then the operands give way. - var ops = row.operands(); + // annotation moves left (never past its column), then the operands give way. + const ops = shorn(u, row); + const stub = if (target(row)) |to| pltName(u, rec, to) else ""; var x = room + gap; - if (need.drawn) { - const wide = need.end - c.annotation; - x = annotationX(operandsWidth(row, ops), room, wide); - if (c.operands + operandsWidth(row, ops) + gap > x) if (lean(u, row)) |shorter| { - ops = shorter; - x = annotationX(operandsWidth(row, ops), room, wide); - }; - } - operands(u, row, ops, base_y, (if (covered) @min(x, c.annotation) else x) - gap - c.operands); - return if (need.drawn) d.annotation(u, now, row, y, x, room, state, base).hangs else 0; + if (need.drawn) x = annotationX(operandsWidth(u, row, ops, stub), room, need.end - c.annotation); + operands(u, row, ops, stub, base_y, (if (covered) @min(x, c.annotation) else x) - gap - c.operands, if (pad) t.faint else theme.color.code.plain); + return if (need.drawn) d.annotation(u, now, row, y, x, room, state, base, window, echo).hangs else 0; } const Note = struct { drawn: bool = false, end: f32 = 0, hangs: usize = 0 }; + /// The row that set the flags a conditional jump reads, while the jump + /// runs: its chips are framed as read with it (an `echo`). + const Echo = struct { addr: u64, shows: f32 }; /// The annotation: what it does, now, from `x`, cut where `room` ends. /// What it left behind is shown only where the step ran this /// instruction alone: a step by line runs others after it, and the /// state after them is not its doing. - fn annotation(d: *const Disasm, u: ui.Ui, now: cursors.Now, row: Insn, y: f32, x: f32, room: f32, state: State, base: usize) Note { + fn annotation(d: *const Disasm, u: ui.Ui, now: cursors.Now, row: Insn, y: f32, x: f32, room: f32, state: State, base: usize, window: [2]u64, echo: ?Echo) Note { const rec = d.cursor.rec; const base_y = rows.baseline(y); const code_ink = theme.color.region.code_; @@ -278,33 +299,30 @@ pub const Disasm = struct { }, .ran => |r| .{ r.at, r.at + 1 }, .ahead => .{ now.stops[base], null }, + .waiting => |w| .{ w, null }, }; if (after) |a| if (!alone(rec, moment, a, row)) { after = null; }; const branch = if (state == .ahead) null else rec.insn_branches[moment]; const touches = if (state == .ahead) [2]?Recording.Touch{ null, null } else rec.insn_touches[moment]; + const mn = row.mnemonic(); + const a: Say = .{ .u = u, .rec = rec, .y = y, .x = x, .room = room }; + // Waiting on its callee: the call in C's form. + if (state == .waiting) if (branch) |b| return a.said(a.cForm(row, b.to, moment, null, a.room - a.x), t.primary); + // A system call: its name and number, its arguments hanging under it. + if (std.mem.eql(u8, mn, "syscall") and state != .ahead) return a.syscall(moment, state == .current); if (branch) |b| switch (b.kind) { .call => { - const callee = rec.strings.get(b.to) orelse ""; - const callee_name = callee[0 .. std.mem.lastIndexOfScalar(u8, callee, '+') orelse callee.len]; - u.text(.mono, size, x, base_y, callee_name, t.bright); - var note: Note = .{ .drawn = true, .end = x + @as(f32, @floatFromInt(callee_name.len)) * adv }; + // Through memory or a register: where it went, and where that was read. + if (target(row) == null) return a.went(b.to, touches[0], moment); + // Once it has run: the call in C's form and its result. + if (state == .ran) if (returned(rec, row, moment, now.stops[base])) |back| { + return a.said(a.cForm(row, b.to, moment, rec.register(back, "rax"), a.room - a.x), t.primary); + }; + var note = a.callee(b.to, moment); // Its arguments hang under it, a small `reg` a row, as many as the prototype has. - if (state == .current) { - // As many as the callee's prototype has (the debug info's, else the source's), three when neither says. - const count: usize = row.params orelse for (rec.functions) |fun| { - if (std.mem.eql(u8, fun.name, callee_name)) break fun.params; - } else 3; - const shown_moment = rec.moment(moment); - const args = [_][]const u8{ "rdi", "rsi", "rdx", "rcx", "r8", "r9" }; - for (args[0..@min(count, 6)], 1..) |reg, k| { - const ry = y + @as(f32, @floatFromInt(k)) * m.row; - u.text(.mono, size, x, rows.baseline(ry), reg, t.dim); - _ = rows.chain(u, x + 4 * adv, ry, shown_moment, rec.register(moment, reg), room, .{}); - } - note.hangs = @min(count, 6); - } + if (state == .current) note.hangs = a.arguments(row, b.to, moment); return note; }, .ret => { @@ -312,32 +330,80 @@ pub const Disasm = struct { return .{ .drawn = true, .end = u.address(x + 2 * adv, base_y, b.to, .{ .ink = ui.rgb(code_ink), .name = rec.strings.get(b.to) orelse "" }) }; }, .jump => { - // A jump always taken says nothing; a conditional one, which way. - if (std.mem.eql(u8, row.mnemonic(), "jmp")) return .{}; - const said = if (b.taken) "taken" else "not taken"; - u.text(.mono, size, x, base_y, said, if (b.taken) t.primary else t.dim); - return .{ .drawn = true, .end = x + @as(f32, @floatFromInt(said.len)) * adv }; + // Through memory or a register: where it goes. Straight: nothing to say. + if (std.mem.eql(u8, mn, "jmp")) return if (target(row) == null) a.went(b.to, touches[0], moment) else .{}; + // A conditional: which way, and the flags it reads; taken out of the window, where to. + var end = a.word(x, if (b.taken) "taken" else "not taken", if (b.taken) t.primary else t.dim); + end = a.word(end + adv, "\u{00b7} reads", t.faint); + end = flags(u, end + adv, y, rec.register(moment, "eflags"), flagsRead(mn), 0); + if (b.taken and (b.to < window[0] or b.to > window[1])) { + end = a.word(end + adv, "\u{2192}", t.faint); + end = u.address(end + adv, base_y, b.to, .{ .ink = ui.rgb(code_ink), .name = ui.symbol(u, rec.strings.get(b.to) orelse "") }); + } + return .{ .drawn = true, .end = end }; }, .none => {}, }; - if (std.mem.eql(u8, row.mnemonic(), "syscall") and state != .ahead) { - const nr = rec.register(moment, "rax"); - const name = zt.syscalls.name(nr) orelse "syscall"; - u.text(.mono, size, x, base_y, name, t.bright); - const names = zt.syscalls.names(nr); - const carriers = [_][]const u8{ "rdi", "rsi", "rdx" }; - const n = @min(names.len, 3); - if (state == .current) for (names[0..n], carriers[0..n], 1..) |arg, reg, k| { - const ry = y + @as(f32, @floatFromInt(k)) * m.row; - u.text(.mono, size, x, rows.baseline(ry), arg, t.dim); - const ax = x + @as(f32, @floatFromInt(arg.len + 1)) * adv; - const value = rec.register(moment, reg); - // A descriptor is the `value` class `fd`: what it is open on. - if (std.mem.endsWith(u8, arg, "fd")) { - _ = u.typed(ax, rows.baseline(ry), value, .{ .fd = rec.openOn(u.f.scratch, value, moment) }, .{}); - } else _ = rows.chain(u, ax, ry, rec.moment(moment), value, room, .{}); + if (state == .ahead) { + // Only what is static: a direct call's callee; a jump through the PLT's slot. + if (std.mem.eql(u8, mn, "call")) if (target(row)) |to| if (rec.strings.get(to) != null) return a.callee(to, moment); + if (std.mem.eql(u8, mn, "jmp")) if (ripSlot(row)) |slot| if ((zt.telescope.got(rec.moment(moment), slot) catch null)) |held| return a.went(held.value, .{ .addr = slot, .len = 8, .how = 1 }, moment); + return .{}; + } + // A compare: the two values, then (once it has run) the flags it leaves. + if (std.mem.eql(u8, mn, "cmp") or std.mem.eql(u8, mn, "test")) { + const left = a.compared(row, moment, touches[0]); + var end = a.word(x, left[0], t.primary); + end = a.word(end, " : ", t.faint); + end = a.word(end, left[1], t.primary); + const left_at: ?u64 = switch (state) { + .ran => after, + .current => if (after != null and now.landed(.cpu, 0)) after else null, + .ahead, .waiting => null, }; - return .{ .drawn = true, .end = x + @as(f32, @floatFromInt(name.len)) * adv, .hangs = if (state == .current) n else 0 }; + if (left_at) |l| { + var buf: [256]u8 = undefined; + const next = rec.instruction(moment, row.addr + row.len, &buf); + var mask = if (next) |n| flagsRead((Insn{ .addr = 0, .len = 0, .text = n.text }).mnemonic()) else 0; + if (mask == 0) mask = flag_bits.cf | flag_bits.zf | flag_bits.sf | flag_bits.of; + end = flags(u, end + 2 * adv, y, rec.register(l, "eflags"), mask, if (echo) |e| if (e.addr == row.addr) e.shows else 0 else 0); + } + return .{ .drawn = true, .end = end }; + } + // The rest is what it left behind, or where it reads: by what it is. + const value_at: ?u64 = switch (state) { + .ran => after, + .current => if (after != null and now.landed(.cpu, 0)) after.? else null, + .ahead, .waiting => null, + }; + // A place the C library's layout names: the canary. + if (std.mem.indexOf(u8, row.text, "fs:[0x28]") != null) { + const end = a.word(x, if (x + 35 * adv <= room) "the stack's canary" else "canary", t.dim); + const word_ = if (touches[0]) |touch| Recording.word(rec.moment(value_at orelse moment), touch.addr, 8) catch null else null; + if (word_) |v| return .{ .drawn = true, .end = a.word(end + adv, u.print("{x}", .{v}), t.primary) }; + u.unknown(.{ .x = end + adv, .y = y, .w = 24, .h = m.row }); + return .{ .drawn = true, .end = end + adv + 24 }; + } + // `lea`: `=` and what it made. + if (std.mem.eql(u8, mn, "lea")) { + const at = value_at orelse return .{}; + const reg = written(row) orelse return .{}; + const end = a.word(x, "=", t.faint); + return .{ .drawn = true, .end = rows.chain(u, end + adv, y, rec.moment(at), rec.register(at, reg), room, .{}).end }; + } + // A `rep`: how many times, how wide each, and where it goes. + if (std.mem.startsWith(u8, mn, "rep")) { + const each: u8 = switch (mn[mn.len - 1]) { + 'b' => 1, + 'w' => 2, + 'd' => 4, + else => 8, + }; + var end = a.word(x, "rcx", t.dim); + end = a.word(end + adv, u.print("{d}", .{rec.register(moment, "rcx")}), t.primary); + end = a.word(end + adv, u.print("\u{00b7} {d} bytes each", .{each}), t.faint); + end = a.word(end + adv, "rdi", t.dim); + return .{ .drawn = true, .end = rows.chain(u, end + adv, y, rec.moment(moment), rec.register(moment, "rdi"), room, .{}).end }; } // Memory: a chain from the address it computes. Before the step, // where it will look; in the step its first hop is read (with the @@ -354,8 +420,8 @@ pub const Disasm = struct { marks.read = 0; marks.read_shows = now.reading(.memory, 0); } - if (writes) if (after) |a| { - if (state == .ran or now.landed(.memory, 0)) shown = rec.moment(a); + if (writes) if (after) |aa| { + if (state == .ran or now.landed(.memory, 0)) shown = rec.moment(aa); if (in_step) { marks.changed = 1; marks.changed_heat = now.written(touch.addr, touch.len, .memory, 0); @@ -365,27 +431,350 @@ pub const Disasm = struct { } // Only a register: a small `reg` of what it left there. const reg = written(row) orelse return .{}; - const value_at = switch (state) { - .ran => after orelse return .{}, - .current => if (after != null and now.landed(.cpu, 0)) after.? else return .{}, - .ahead => return .{}, - }; - const value = rec.register(value_at, reg); + const at = value_at orelse return .{}; + const value = rec.register(at, reg); u.text(.mono, size, x, base_y, reg, t.dim); - return .{ .drawn = true, .end = rows.chain(u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, rec.moment(value_at), value, room, .{}).end }; + return .{ .drawn = true, .end = rows.chain(u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, rec.moment(at), value, room, .{}).end }; + } +}; + +/// What an annotation says, from `x` on the row at `y`, cut where `room` ends. +const Say = struct { + u: ui.Ui, + rec: *const Recording, + y: f32, + x: f32, + room: f32, + + /// `text` at `x` in `ink`; where it ends. + fn word(a: Say, x: f32, text: []const u8, ink: u24) f32 { + a.u.text(.mono, size, x, rows.baseline(a.y), text, ink); + return x + @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(text) catch text.len)) * adv; + } + + /// `text` from the annotation's place, cut at the room's end. + fn said(a: Say, text: []const u8, ink: u24) Disasm.Note { + return .{ .drawn = true, .end = a.word(a.x, if (std.math.isInf(a.room)) text else rows.fitted(a.u, text, a.room - a.x), ink) }; + } + + /// A function's name as a caller knows it: a PLT stub's is the + /// function it reaches (`open`), or the resolver while its slot is lazy. + fn functionName(a: Say, to: u64, moment: u64) []const u8 { + const name = ui.symbol(a.u, a.rec.strings.get(to) orelse return a.u.print("{x}", .{to})); + const bare = name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len]; + if (!std.mem.endsWith(u8, bare, "@plt")) return bare; + var buf: [256]u8 = undefined; + const jmp = a.rec.instruction(moment, to, &buf) orelse return bare[0 .. bare.len - 4]; + if (ripSlot(.{ .addr = to, .len = jmp.len, .text = jmp.text })) |slot| if ((zt.telescope.got(a.rec.moment(moment), slot) catch null)) |held| { + if (held.lazy orelse false) return "the resolver"; + }; + return bare[0 .. bare.len - 4]; + } + + /// A direct call's callee, bright. + fn callee(a: Say, to: u64, moment: u64) Disasm.Note { + return .{ .drawn = true, .end = a.word(a.x, a.functionName(to, moment), t.bright) }; + } + + /// A call's arguments under it, a small `reg` a row: as many as its + /// prototype has (the debug info's, the source's, a system call's of + /// its name), three when none says. How many rows they take. + fn arguments(a: Say, row: Insn, to: u64, moment: u64) usize { + const name = a.functionName(to, moment); + const count = @min(row.params orelse for (a.rec.functions) |fun| { + if (std.mem.eql(u8, fun.name, name)) break fun.params; + } else argumentCount(a.rec, row, name) orelse 3, 6); + const shown = a.rec.moment(moment); + // Flags by name, where a system call of its name says which argument they are. + const nr: ?u64 = if (std.meta.stringToEnum(std.os.linux.SYS, name)) |sys| @intFromEnum(sys) else null; + const names: []const []const u8 = if (nr) |n| zt.syscalls.names(n) else &.{}; + for (carriers[0..count], 1..) |reg, k| { + const ry = a.y + @as(f32, @floatFromInt(k)) * m.row; + a.u.text(.mono, size, a.x, rows.baseline(ry), reg, t.dim); + const v = a.rec.register(moment, reg); + if (k - 1 < names.len and std.mem.eql(u8, names[k - 1], "flags")) { + a.u.text(.mono, size, a.x + 4 * adv, rows.baseline(ry), openFlags(a.u, v), t.primary); + } else _ = rows.chain(a.u, a.x + 4 * adv, ry, shown, v, a.room, .{}); + } + return count; + } + + /// The call at `row` (to `to`, made at `moment`) in C's form, its + /// arguments as the source wrote that many and as the system call of its + /// name types them; with ` = result` when it has returned. + fn cForm(a: Say, row: Insn, to: u64, moment: u64, result: ?u64, width: f32) []const u8 { + const u = a.u; + const name = a.functionName(to, moment); + const nr: ?u64 = if (std.meta.stringToEnum(std.os.linux.SYS, name)) |sys| @intFromEnum(sys) else null; + const names: []const []const u8 = if (nr) |n| zt.syscalls.names(n) else &.{}; + const count = @min(row.params orelse argumentCount(a.rec, row, name) orelse names.len, 6); + // Out of room the arguments go from the right, `…` for them; the result stays. + var shown = count; + while (true) : (shown -= 1) { + var out: []const u8 = u.print("{s}(", .{name}); + for (carriers[0..shown], 0..) |reg, k| { + const v = a.rec.register(moment, reg); + out = u.print("{s}{s}{s}", .{ out, if (k > 0) ", " else "", argument(u, a.rec, moment, if (k < names.len) names[k] else "", v) }); + } + if (shown < count) out = u.print("{s}{s}\u{2026}", .{ out, if (shown > 0) ", " else "" }); + out = u.print("{s})", .{out}); + if (result) |r| out = u.print("{s} = {d}", .{ out, @as(i64, @bitCast(r)) }); + if (shown == 0 or @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(out) catch out.len)) * adv <= width) return out; + } + } + + /// Where a call or a jump through memory or a register went: `→ addr + /// name`, then faint where it was read, `· read from open@got, 403fd8`. + /// Out of room the slot goes first, then the digits; the name stays. + fn went(a: Say, to: u64, slot: ?Recording.Touch, moment: u64) Disasm.Note { + const u = a.u; + const name = a.functionName(to, moment); + const from: []const u8 = if (slot) |s| blk: { + const named = ui.symbol(u, a.rec.strings.get(s.addr) orelse ""); + break :blk u.print("\u{00b7} read from {s}{s}{x}", .{ named[0 .. std.mem.lastIndexOfScalar(u8, named, '+') orelse named.len], if (named.len > 0) ", " else "", s.addr }); + } else ""; + const digits_w = @as(f32, @floatFromInt(ui.digits(to) + 1)) * adv; + const name_w = @as(f32, @floatFromInt(name.len)) * adv; + const from_w = @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(from) catch from.len)) * adv; + const fits_all = a.x + 2 * adv + digits_w + name_w + adv + from_w <= a.room; + const fits_digits = a.x + 2 * adv + digits_w + name_w <= a.room; + var end = a.word(a.x, "\u{2192}", t.faint) + adv; + if (fits_digits) { + end = u.address(end, rows.baseline(a.y), to, .{ .ink = ui.rgb(theme.color.region.code_), .name = name }); + } else end = a.word(end, name, t.primary); + if (fits_all and from.len > 0) end = a.word(end + adv, from, t.faint); + return .{ .drawn = true, .end = end }; + } + + /// The two values a compare compares, as its operands' size reads them. + fn compared(a: Say, row: Insn, moment: u64, touch: ?Recording.Touch) [2][]const u8 { + const ops = shorn(a.u, row); + var parts = std.mem.splitScalar(u8, ops.text, ','); + var operands_: [2][]const u8 = .{ "", "" }; + for (&operands_) |*o| o.* = std.mem.trim(u8, parts.next() orelse "", " "); + // The size: a register's, else the width's, else a word's. + var bytes: u8 = if (ops.bytes > 0) ops.bytes else 8; + for (operands_) |o| if (registerSize(o)) |n| { + bytes = n; + }; + var out: [2][]const u8 = undefined; + for (operands_, &out) |o, *v| { + const raw: ?u64 = if (std.mem.indexOfScalar(u8, o, '[') != null) + (if (touch) |tt| Recording.word(a.rec.moment(moment), tt.addr, @min(tt.len, 8)) catch null else null) + else if (full(o)) |reg| + a.rec.register(moment, reg) + else + parseImmediate(o); + v.* = if (raw) |r| number(a.u, r, bytes) else ".."; + } + return out; + } + + /// `syscall`: its name and number (`openat nr 257`); its arguments hang + /// under it, a register a row, each read as its name says. + fn syscall(a: Say, moment: u64, current: bool) Disasm.Note { + const u = a.u; + const nr = a.rec.register(moment, "rax"); + var end = a.word(a.x, zt.syscalls.name(nr) orelse "syscall", t.bright); + end = a.word(end + adv, "nr", t.faint); + end = a.word(end + adv, u.print("{d}", .{nr}), t.primary); + const names = zt.syscalls.names(nr); + const n = @min(zt.syscalls.signature(nr).len, 6); + if (!current) return .{ .drawn = true, .end = end }; + for (carriers_sys[0..n], 0..) |reg, k| { + const ry = a.y + @as(f32, @floatFromInt(k + 1)) * m.row; + u.text(.mono, size, a.x, rows.baseline(ry), reg, t.dim); + const v = a.rec.register(moment, reg); + const what = if (k < names.len) names[k] else ""; + const ax = a.x + 4 * adv; + if (std.mem.eql(u8, what, "path") or std.mem.eql(u8, what, "buf")) { + _ = rows.chain(u, ax, ry, a.rec.moment(moment), v, a.room, .{}); + } else if (std.mem.endsWith(u8, what, "fd") and v == fdcwd) { + // The value class `fd`: the number, and faint what it names. + u.text(.mono, size, ax, rows.baseline(ry), "-100", t.primary); + u.text(.mono, size, ax + 5 * adv, rows.baseline(ry), "AT_FDCWD", t.faint); + } else if (std.mem.endsWith(u8, what, "fd")) { + _ = u.typed(ax, rows.baseline(ry), v, .{ .fd = a.rec.openOn(u.f.scratch, v, moment) }, .{}); + } else u.text(.mono, size, ax, rows.baseline(ry), argument(u, a.rec, moment, what, v), t.primary); + } + return .{ .drawn = true, .end = end, .hangs = n }; + } +}; + +/// A call's argument registers, in order; a system call's. +const carriers = [_][]const u8{ "rdi", "rsi", "rdx", "rcx", "r8", "r9" }; +const carriers_sys = [_][]const u8{ "rdi", "rsi", "rdx", "r10", "r8", "r9" }; +/// `AT_FDCWD`, as a register holds it. +const fdcwd: u64 = @bitCast(@as(i64, -100)); + +/// An argument's value as C would write it, by its name: a path as its +/// string, flags by name, a descriptor and a count in decimal, a pointer as +/// its address. +pub fn argument(u: ui.Ui, rec: *const Recording, moment: u64, what: []const u8, v: u64) []const u8 { + if (std.mem.eql(u8, what, "path")) { + var links: [2]zt.telescope.Link = undefined; + var text: [48]u8 = undefined; + const chain = zt.telescope.chase(rec.moment(moment), v, &links, &text) catch &.{}; + if (chain.len > 0 and chain[chain.len - 1].string) return u.print("\"{s}\"", .{chain[chain.len - 1].text}); + } + if (std.mem.eql(u8, what, "flags")) return openFlags(u, v); + if (std.mem.endsWith(u8, what, "fd") and v == fdcwd) return "AT_FDCWD"; + const signed: i64 = @bitCast(v); + if (signed > -4096 and signed < 0x10000) return u.print("{d}", .{signed}); + return u.print("{x}", .{v}); +} + +/// `open`'s flags by name, `O_RDONLY`; bits no name covers as `0x` and their hex. +fn openFlags(u: ui.Ui, v: u64) []const u8 { + var out: []const u8 = switch (v & 3) { + 0 => "O_RDONLY", + 1 => "O_WRONLY", + else => "O_RDWR", + }; + var rest = v & ~@as(u64, 3); + for ([_]struct { []const u8, u64 }{ .{ "O_CREAT", 0o100 }, .{ "O_EXCL", 0o200 }, .{ "O_NOCTTY", 0o400 }, .{ "O_TRUNC", 0o1000 }, .{ "O_APPEND", 0o2000 }, .{ "O_NONBLOCK", 0o4000 }, .{ "O_DIRECTORY", 0o200000 }, .{ "O_NOFOLLOW", 0o400000 }, .{ "O_CLOEXEC", 0o2000000 } }) |f| if (rest & f[1] != 0) { + out = u.print("{s}|{s}", .{ out, f[0] }); + rest &= ~f[1]; + }; + return if (rest != 0) u.print("{s} 0x{x}", .{ out, rest }) else out; +} + +/// How many arguments the program's source gives `name` on the call's line. +fn argumentCount(rec: *const Recording, row: Insn, name: []const u8) ?usize { + const line = row.line orelse return null; + var lines = std.mem.splitScalar(u8, rec.source, '\n'); + var n: u32 = 1; + const text = while (lines.next()) |l| : (n += 1) { + if (n == line) break l; + } else return null; + const open = (std.mem.indexOf(u8, text, name) orelse return null) + name.len; + if (open >= text.len or text[open] != '(') return null; + var depth: usize = 0; + var count: usize = 0; + var any = false; + for (text[open + 1 ..]) |ch| switch (ch) { + '(' => depth += 1, + ')' => { + if (depth == 0) return if (any) count + 1 else 0; + depth -= 1; + }, + ',' => if (depth == 0) { + count += 1; + }, + ' ' => {}, + else => any = true, + }; + return null; +} + +/// The moment a call made at `moment` from `row` came back to the row after +/// it, at or before `until`. +fn returned(rec: *const Recording, row: Insn, moment: u64, until: u64) ?u64 { + const sp = rec.register(moment, "rsp"); + var i = moment + 1; + while (i <= until) : (i += 1) { + if (rec.register(i, "rip") == row.addr + row.len and rec.register(i, "rsp") == sp) return i; } + return null; +} + +/// The slot a `jmp` or `call` through `[rip + X]` reads. +fn ripSlot(row: Insn) ?u64 { + const ops = row.operands(); + const at = std.mem.indexOf(u8, ops, "[rip + 0x") orelse return null; + const close = std.mem.indexOfScalarPos(u8, ops, at, ']') orelse return null; + const disp = std.fmt.parseInt(u64, ops[at + 9 .. close], 16) catch return null; + return row.addr + row.len + disp; +} + +/// An immediate operand's value. +fn parseImmediate(o: []const u8) ?u64 { + const negative = std.mem.startsWith(u8, o, "-"); + const digits_ = if (negative) o[1..] else o; + const v = (if (std.mem.startsWith(u8, digits_, "0x")) std.fmt.parseInt(u64, digits_[2..], 16) else std.fmt.parseInt(u64, digits_, 10)) catch return null; + return if (negative) 0 -% v else v; +} + +/// `v` as a number `bytes` wide: signed and in decimal when small, else hex. +fn number(u: ui.Ui, v: u64, bytes: u8) []const u8 { + const bits: u7 = @as(u7, @min(bytes, 8)) * 8; + const masked = if (bits == 64) v else v & ((@as(u64, 1) << @intCast(bits)) - 1); + const signed: i64 = if (bits == 64) @bitCast(masked) else @as(i64, @bitCast(masked << @intCast(64 - @as(u7, bits)))) >> @intCast(64 - @as(u7, bits)); + if (signed > -0x10000 and signed < 0x10000) return u.print("{d}", .{signed}); + return u.print("{x}", .{masked}); +} + +/// eflags' bits a reader meets. +const flag_bits = struct { + const cf: u16 = 1 << 0; + const pf: u16 = 1 << 2; + const zf: u16 = 1 << 6; + const sf: u16 = 1 << 7; + const of: u16 = 1 << 11; }; +/// The flags a conditional (`jcc`, `setcc`, `cmovcc`) reads; 0 for anything else. +pub fn flagsRead(mn: []const u8) u16 { + const cond = if (std.mem.startsWith(u8, mn, "cmov")) mn[4..] else if (std.mem.startsWith(u8, mn, "set")) mn[3..] else if (mn.len > 1 and mn[0] == 'j' and !std.mem.eql(u8, mn, "jmp")) mn[1..] else return 0; + const f = flag_bits; + const table = [_]struct { []const u8, u16 }{ + .{ "a", f.cf | f.zf }, .{ "nbe", f.cf | f.zf }, .{ "be", f.cf | f.zf }, .{ "na", f.cf | f.zf }, + .{ "ae", f.cf }, .{ "nb", f.cf }, .{ "nc", f.cf }, .{ "b", f.cf }, + .{ "c", f.cf }, .{ "nae", f.cf }, .{ "e", f.zf }, .{ "z", f.zf }, + .{ "ne", f.zf }, .{ "nz", f.zf }, .{ "g", f.zf | f.sf | f.of }, .{ "nle", f.zf | f.sf | f.of }, + .{ "le", f.zf | f.sf | f.of }, .{ "ng", f.zf | f.sf | f.of }, .{ "ge", f.sf | f.of }, .{ "nl", f.sf | f.of }, + .{ "l", f.sf | f.of }, .{ "nge", f.sf | f.of }, .{ "o", f.of }, .{ "no", f.of }, + .{ "s", f.sf }, .{ "ns", f.sf }, .{ "p", f.pf }, .{ "pe", f.pf }, + .{ "np", f.pf }, .{ "po", f.pf }, + }; + for (table) |e| if (std.mem.eql(u8, cond, e[0])) return e[1]; + return 0; +} + +/// The flags of `mask`, as rip's row draws them: set, upper case on a +/// chip; clear, lower case and dim; each framed as read by `read`. Where they end. +fn flags(u: ui.Ui, x: f32, y: f32, eflags: u64, mask: u16, read: f32) f32 { + var at = x; + for (rows.flags) |flag| { + if (@as(u64, mask) >> flag.bit & 1 == 0) continue; + const chip: Rect = .{ .x = at, .y = y + 2, .w = theme.metric.flags.chip[0], .h = theme.metric.flags.chip[1] }; + if (eflags >> flag.bit & 1 != 0) { + u.chip(chip); + u.text(.mono_bold, size, at + 4, rows.baseline(y), flag.name, t.bright); + } else u.text(.mono, size, at + 4, rows.baseline(y), u.print("{c}{c}", .{ std.ascii.toLower(flag.name[0]), std.ascii.toLower(flag.name[1]) }), t.dim); + if (read > 0) u.read(chip, read); + at += chip.w + 4; + } + return at - 4; +} + +/// While a conditional jump runs (the mark on it, its step under way), the +/// row that set the flags it reads: the instruction just before it ran. +fn jumpEcho(now: cursors.Now, base: usize) ?Disasm.Echo { + if (base != 1 or now.resting()) return null; + const flags_ = readsFlags(now.rec, now.stops[1]); + if (flags_ == 0 or now.stops[1] == 0) return null; + return .{ .addr = now.rec.register(now.stops[1] - 1, "rip"), .shows = now.reading(.cpu, 0) }; +} + +/// The flags the instruction at moment `i`'s pc reads, if it is a conditional. +pub fn readsFlags(rec: *const Recording, i: u64) u16 { + var buf: [256]u8 = undefined; + const pc = rec.register(i, "rip"); + const here = rec.instruction(i, pc, &buf) orelse return 0; + return flagsRead((Insn{ .addr = pc, .len = here.len, .text = here.text }).mnemonic()); +} + /// The gap between the operands and the annotation: a character. const gap = adv; /// The runs of rows of one line, top and bottom of each, as the rows go by. -const Runs = struct { +pub const Runs = struct { spans: [8][2]f32 = undefined, n: usize = 0, open: ?f32 = null, - fn add(r: *Runs, on: bool, y: f32, end: f32) void { + pub fn add(r: *Runs, on: bool, y: f32, end: f32) void { if (on and r.open == null) r.open = y; if (!on) if (r.open) |y0| { if (r.n < r.spans.len and end > y0) { @@ -400,7 +789,7 @@ const Runs = struct { /// The thread's runs, `p` of the way from the line the mark leaves to the /// one it goes to: each slides to its partner (by order, the last of the /// fewer standing in for the rest), as the source's bracket slides. -fn threadRuns(u: ui.Ui, w: f32, runs: [2]Runs, p: f32) void { +pub fn threadRuns(u: ui.Ui, w: f32, runs: [2]Runs, p: f32) void { const from = runs[0]; const to = runs[1]; if (to.n == 0 or p >= 1 or from.n == 0) { @@ -445,53 +834,147 @@ fn alone(rec: *const Recording, i: u64, after: u64, row: Insn) bool { } /// A jump's or a call's target, when the disassembler wrote it as one. -fn target(row: Insn) ?u64 { +pub fn target(row: Insn) ?u64 { const ops = row.operands(); const mn = row.mnemonic(); if (!(mn[0] == 'j' or std.mem.eql(u8, mn, "call")) or !std.mem.startsWith(u8, ops, "0x")) return null; return std.fmt.parseInt(u64, ops[2..], 16) catch null; } -/// How wide operands `ops` of `row` are, whole. -fn operandsWidth(row: Insn, ops: []const u8) f32 { - if (target(row)) |to| return @as(f32, @floatFromInt(ui.digits(to))) * adv; - return @as(f32, @floatFromInt(ops.len)) * adv; +/// An `insn` with no state and no annotation: its address, its mnemonic +/// (faint for padding) and its operands as canim draws them, at `y` in `u` +/// (the panel's origin). For the gallery's page of rows. +pub fn plainRow(u: ui.Ui, row: Insn, y: f32) void { + const base_y = rows.baseline(y); + _ = u.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(theme.color.region.code_) }); + // A library's twelve digits move what is right of them, 12 a digit past seven. + const v = u.moved(@as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv, 0); + const pad = row.padding(); + v.text(.mono_bold, size, c.mnemonic, base_y, row.mnemonic(), if (pad) t.faint else theme.color.code.keyword); + operands(v, row, shorn(v, row), "", base_y, c.annotation - gap - c.operands, if (pad) t.faint else theme.color.code.plain); } -/// The operands without the size word of a memory operand whose size a -/// register operand gives (`mov rax, [rbp - 0x28]`): nothing is lost. -/// Null where there is none to drop. -fn lean(u: ui.Ui, row: Insn) ?[]const u8 { +/// Operands as canim draws them (design/README.md, `insn` and `width`): +/// the disassembler's less every size word (`qword ptr `); and where no +/// register outside the brackets has the access's size and the mnemonic +/// does not fix it, how many bytes it touches (`bytes`), drawn as byte +/// cells after the `]` that ends at `after`. +const Operands = struct { text: []const u8, after: usize = 0, bytes: u8 = 0 }; + +fn shorn(u: ui.Ui, row: Insn) Operands { + var ops = row.operands(); + var bytes: u8 = 0; + while (std.mem.indexOf(u8, ops, " ptr ")) |ptr| { + var word = ptr; + while (word > 0 and ops[word - 1] != ' ' and ops[word - 1] != ',') word -= 1; + for ([_]struct { []const u8, u8 }{ .{ "byte", 1 }, .{ "word", 2 }, .{ "dword", 4 }, .{ "qword", 8 }, .{ "tbyte", 10 }, .{ "xmmword", 16 }, .{ "ymmword", 32 }, .{ "zmmword", 64 } }) |w| { + if (std.mem.eql(u8, ops[word..ptr], w[0])) bytes = w[1]; + } + ops = u.print("{s}{s}", .{ ops[0..word], ops[ptr + 5 ..] }); + } + const close = std.mem.indexOfScalar(u8, ops, ']') orelse return .{ .text = ops }; + if (bytes == 0) return .{ .text = ops }; + // Said already: by the mnemonic (a stack op, a branch through memory, + // what touches nothing, a string op's suffix, SSE's scalar ops), or by + // a register outside the brackets of the access's size. const mn = row.mnemonic(); - // These widen or convert: the register does not give the memory's size. - for ([_][]const u8{ "movzx", "movsx", "movsxd", "cvt" }) |w| if (std.mem.startsWith(u8, mn, w)) return null; - const ops = row.operands(); - const ptr = std.mem.indexOf(u8, ops, " ptr ") orelse return null; - var word = ptr; - while (word > 0 and ops[word - 1] != ' ' and ops[word - 1] != ',') word -= 1; - const comma = std.mem.indexOfScalar(u8, ops, ',') orelse return null; - const other = std.mem.trim(u8, if (comma < word) ops[0..comma] else ops[comma + 1 ..], " "); - if (full(other) == null) return null; - return u.print("{s}{s}", .{ ops[0..word], ops[ptr + 5 ..] }); + for ([_][]const u8{ "push", "pop", "call", "jmp", "lea", "nop", "rep" }) |says| if (std.mem.startsWith(u8, mn, says)) return .{ .text = ops }; + if (mn.len == 0 or mn[0] == 'j') return .{ .text = ops }; + var parts = std.mem.splitScalar(u8, ops, ','); + while (parts.next()) |part| { + const operand = std.mem.trim(u8, part, " "); + if (std.mem.indexOfScalar(u8, operand, '[') != null) continue; + const of = registerSize(operand) orelse continue; + if (of == bytes or of >= 16) return .{ .text = ops }; + } + return .{ .text = ops, .after = close + 1, .bytes = bytes }; +} + +/// How many bytes register `name` is; null for anything else. +fn registerSize(name: []const u8) ?u8 { + if (name.len < 2) return null; + for ([_]struct { []const u8, u8 }{ .{ "xmm", 16 }, .{ "ymm", 32 }, .{ "zmm", 64 } }) |v| if (std.mem.startsWith(u8, name, v[0])) return v[1]; + if (full(name) == null and !(name.len == 3 and name[2] == 'l')) return null; + if (name[0] == 'r' and std.ascii.isDigit(name[1])) return switch (name[name.len - 1]) { + 'd' => 4, + 'w' => 2, + 'b' => 1, + else => 8, + }; + if (name.len == 3) return switch (name[0]) { + 'r' => 8, + 'e' => 4, + else => 1, // sil, dil, bpl, spl + }; + return if (name[1] == 'l' or name[1] == 'h') 1 else 2; +} + +/// How wide `width`'s cells are for an access of `bytes`, with the gaps +/// round them (3 after the `]`, 4 before what follows) and, past eight +/// bytes, the count. +fn cellsWidth(u: ui.Ui, bytes: u8) f32 { + if (bytes == 0) return 0; + const w = theme.metric.width; + const n: f32 = @floatFromInt(@min(bytes, 8)); + const count: f32 = if (bytes > 8) u.width(.mono, size, u.print("{d}", .{bytes})) + w.after else 0; + return w.before + (n - 1) * w.pitch + w.cell[0] + w.after + count; +} + +/// `width`: `bytes` byte cells at `x`, standing on the baseline; a count past eight. +fn cells(u: ui.Ui, x: f32, base_y: f32, bytes: u8) void { + const w = theme.metric.width; + for (0..@min(bytes, 8)) |k| u.fill(.{ .x = x + w.before + @as(f32, @floatFromInt(k)) * w.pitch, .y = base_y - w.cell[1], .w = w.cell[0], .h = w.cell[1] }, t.dim); + if (bytes > 8) u.text(.mono, size, x + w.before + 7 * w.pitch + w.cell[0] + w.after, base_y, u.print("{d}", .{bytes}), t.faint); +} + +/// A PLT stub's name, for a call or a jump to one: `open@plt`; "" otherwise. +fn pltName(u: ui.Ui, rec: *const Recording, to: u64) []const u8 { + const name = ui.symbol(u, rec.strings.get(to) orelse return ""); + const stub = name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len]; + return if (std.mem.endsWith(u8, stub, "@plt")) stub else ""; } -/// The operands `ops`, in `width` units; a jump's or a call's target is -/// an `address` in code's ink. Cut only at their far end, saying so, and -/// never inside `[]`: a cut that would fall there falls before the `[`. -fn operands(u: ui.Ui, row: Insn, ops: []const u8, base_y: f32, width: f32) void { +/// How wide operands `ops` of `row` are, whole (a target with its stub's name `stub`). +fn operandsWidth(u: ui.Ui, row: Insn, ops: Operands, stub: []const u8) f32 { + if (target(row)) |to| return @as(f32, @floatFromInt(ui.digits(to) + if (stub.len > 0) stub.len + 1 else 0)) * adv; + return @as(f32, @floatFromInt(ops.text.len)) * adv + cellsWidth(u, ops.bytes); +} + +/// The operands `ops`, in `width` units, in `ink`; a jump's or a call's +/// target is an `address` in code's ink, a PLT stub's with its name. Cut +/// only at their far end, saying so, and never inside `[]`: a cut that +/// would fall there falls before the `[`. +fn operands(u: ui.Ui, row: Insn, ops: Operands, stub: []const u8, base_y: f32, width: f32, ink: u24) void { if (target(row)) |to| { - _ = u.address(c.operands, base_y, to, .{ .ink = ui.rgb(theme.color.region.code_) }); + _ = u.address(c.operands, base_y, to, .{ .ink = ui.rgb(theme.color.region.code_), .name = stub }); + return; + } + const text = ops.text; + const extra = cellsWidth(u, ops.bytes); + const at_after = c.operands + @as(f32, @floatFromInt(ops.after)) * adv; + if (@as(f32, @floatFromInt(text.len)) * adv + extra <= width) { + if (ops.bytes == 0) return u.text(.mono, size, c.operands, base_y, text, ink); + u.text(.mono, size, c.operands, base_y, text[0..ops.after], ink); + cells(u, at_after, base_y, ops.bytes); + u.text(.mono, size, at_after + extra, base_y, text[ops.after..], ink); return; } - const chars: usize = @intFromFloat(@max(width / adv, 1)); - if (ops.len <= chars) return u.text(.mono, size, c.operands, base_y, ops, theme.color.code.plain); - var cut = chars - 1; - if (std.mem.lastIndexOfScalar(u8, ops[0..cut], '[')) |open| { - if (std.mem.indexOfScalarPos(u8, ops, open, ']') orelse ops.len >= cut) cut = open; + var chars: usize = @intFromFloat(@max(width / adv, 1)); + if (ops.bytes > 0 and chars > ops.after) chars = @max(@as(usize, @intFromFloat(@max((width - extra) / adv, 1))), ops.after); + var cut = @min(chars - 1, text.len); + if (std.mem.lastIndexOfScalar(u8, text[0..cut], '[')) |open| { + if (std.mem.indexOfScalarPos(u8, text, open, ']') orelse text.len >= cut) cut = open; } - while (cut > 0 and ops[cut - 1] == ' ') cut -= 1; - u.text(.mono, size, c.operands, base_y, ops[0..cut], theme.color.code.plain); - u.text(.mono, size, c.operands + @as(f32, @floatFromInt(cut)) * adv, base_y, "\u{2026}", t.faint); + while (cut > 0 and text[cut - 1] == ' ') cut -= 1; + const shown_cells = ops.bytes > 0 and cut >= ops.after; + u.text(.mono, size, c.operands, base_y, text[0..if (shown_cells) ops.after else cut], ink); + var end = c.operands + @as(f32, @floatFromInt(cut)) * adv; + if (shown_cells) { + cells(u, at_after, base_y, ops.bytes); + u.text(.mono, size, at_after + extra, base_y, text[ops.after..cut], ink); + end += extra; + } + u.text(.mono, size, end, base_y, "\u{2026}", t.faint); } /// The register an instruction leaves a value in, if that is all it does @@ -526,8 +1009,12 @@ fn full(name: []const u8) ?[]const u8 { /// instructions over the pc (fewer near its start), the pc's, and as many /// after it as fill `room`; past the function's end, `outside`. fn listing(u: ui.Ui, rec: *const Recording, i: u64, room: usize, above: usize) Listing { + return listingAt(u, rec, i, rec.register(i, "rip"), room, above); +} + +/// The same round the instruction at `pc` (in the window, `Listing.pc`). +pub fn listingAt(u: ui.Ui, rec: *const Recording, i: u64, pc: u64, room: usize, above: usize) Listing { const out = u.f.scratch.alloc(Insn, room) catch return .{ .rows = &.{}, .pc = 0 }; - const pc = rec.register(i, "rip"); var buf: [256]u8 = undefined; var up: [16]Insn = undefined; var n_up: usize = 0; @@ -570,6 +1057,18 @@ fn merge(u: ui.Ui, a: []const Insn, b: []const Insn) ?struct { rows: []const Ins return .{ .rows = out, .from = if (lo.ptr == a.ptr) 0 else at, .to = if (lo.ptr == b.ptr) 0 else at }; } +test "a register's size, by its name" { + try std.testing.expectEqual(@as(?u8, 8), registerSize("rcx")); + try std.testing.expectEqual(@as(?u8, 4), registerSize("eax")); + try std.testing.expectEqual(@as(?u8, 4), registerSize("r10d")); + try std.testing.expectEqual(@as(?u8, 2), registerSize("ax")); + try std.testing.expectEqual(@as(?u8, 1), registerSize("dil")); + try std.testing.expectEqual(@as(?u8, 1), registerSize("al")); + try std.testing.expectEqual(@as(?u8, 16), registerSize("xmm0")); + try std.testing.expectEqual(@as(?u8, null), registerSize("0x10")); + try std.testing.expectEqual(@as(?u8, null), registerSize("fs:[0x28]")); +} + test "a register is known by any of its widths" { try std.testing.expectEqualStrings("rax", full("eax").?); try std.testing.expectEqualStrings("rdi", full("rdi").?); diff --git a/anim/src/hexdump.zig b/anim/src/hexdump.zig index f1087ab..cbd8f7f 100644 --- a/anim/src/hexdump.zig +++ b/anim/src/hexdump.zig @@ -216,7 +216,7 @@ pub fn drawArcs(u: ui.Ui, now: cursors.Now, x: f32, y: f32, first: u64, count: u } @import("map.zig").row(.view, addr, v, .{ .x = 0, .y = ry, .w = theme.layout.state.w, .h = m.row }); rows.bytesAt(v, ry, addr, &values, &known, runs[0..n], of.region, lead, holds_drawn, moment, shift); - for (runs[0..n]) |run| if (run.kind == .pointer and run.len == 8) pointerArcs(&arcs, now, addr + run.first, ry, shown_rows, 16, rule, loud); + for (runs[0..n]) |run| if (run.kind == .pointer and run.len == 8) pointerArcs(&arcs, now, addr + run.first, ry, shown_rows, 16, rule, loud, false); const end = reading(v, ry, shift, moment, &values, &known, readings[0..n]); // The size word of the chunk after: malloc's, a note after the reading. const last = runs[n - 1]; @@ -239,10 +239,12 @@ pub const RowAt = struct { addr: u64, y: f32 }; /// framed. A target in the same region past the rows shown: a stub to the /// panel's rule (`rule`: its top and bottom), only in the step that /// touches it. `loud`: full ink always (a loupe's, opened to show them). -pub fn pointerArcs(arcs: *rows.Arcs, now: cursors.Now, field: u64, from: f32, shown: []const RowAt, size: u64, rule: [2]f32, loud: bool) void { +pub fn pointerArcs(arcs: *rows.Arcs, now: cursors.Now, field: u64, from: f32, shown: []const RowAt, size: u64, rule: [2]f32, loud: bool, protected: bool) void { const a = time_arc; - const new = (Recording.word(now.moment(), field, 8) catch null) orelse return; - const old = (Recording.word(now.before(), field, 8) catch null) orelse new; + // Safe-linked: to the pointer it protects (a NULL so stored is the mask alone). + const mask: u64 = if (protected) field >> 12 else 0; + const new = ((Recording.word(now.moment(), field, 8) catch null) orelse return) ^ mask; + const old = if (Recording.word(now.before(), field, 8) catch null) |w| w ^ mask else new; const written = now.writeAge(field, 8) == 0 and old != new; const read = now.wasRead(field, 8) and !written; const hot = written or read; @@ -296,7 +298,19 @@ fn chunkAfter(moment: Recording.Moment, word: u64) bool { /// What a field of a region reads as: a number (little-endian, or `big`), /// a pointer, text (in quotes, C's escapes), or bytes the reading leaves /// to the eye. -pub const Reads = enum { number, pointer, text, bytes }; +pub const Reads = enum { + number, + pointer, + text, + bytes, + /// malloc's size word: the size, its three low bits cleared, in hex; + /// then the bits as rip's flags are drawn, `A M P` (`0x20 a m P`). + size, + /// A pointer glibc stores safe-linked (xor its own address shifted + /// right by 12): what it protects, `→ 405050`, or `NULL`, then the + /// mask, faint, `^ 405`. Its arc goes to the pointer it protects. + protected, +}; /// A field of the region a view is about, from the region's first byte. pub const Field = struct { @@ -310,6 +324,11 @@ pub const Field = struct { /// A number's type, where the debug info gives it: read as the lens's /// values are (`objects.reading`: a `char` quoted, a `bool` by name). type: ?Recording.types.Type = null, + /// A note from the scene, Go 18 faint, after the reading (`key`, `slots left`). + note: []const u8 = "", + /// Where the field is: a `protected` word's mask is its address shifted + /// right by 12 (`fieldRow` sets it). + addr: u64 = 0, }; /// What a dump of fields is of, and how it is marked now. @@ -380,9 +399,9 @@ pub fn fielded(v: View, now: cursors.Now, y: f32, of: Fields) void { if (shown[shown.len - 1] < total - 1) more(u, ry, total - 1 - shown[shown.len - 1]); // Its pointers to its own rows: arcs. var arcs: rows.Arcs = .{}; - if (at_rows.items.len > 1) for (of.fields) |field| if (field.reads == .pointer and field.len == 8) { + if (at_rows.items.len > 1) for (of.fields) |field| if ((field.reads == .pointer or field.reads == .protected) and field.len == 8) { const addr = of.base + field.at; - for (at_rows.items) |r| if (addr >= r.addr and addr < r.addr + 16) pointerArcs(&arcs, now, addr, r.y, at_rows.items, 16, .{ y - m.pad, ry + m.pad }, false); + for (at_rows.items) |r| if (addr >= r.addr and addr < r.addr + 16) pointerArcs(&arcs, now, addr, r.y, at_rows.items, 16, .{ y - m.pad, ry + m.pad }, false, field.reads == .protected); }; arcs.draw(u, theme.metric.arc.lanes.len); } @@ -479,7 +498,7 @@ fn fieldRow(u: ui.Ui, now: cursors.Now, y: f32, addr: u64, moment: Recording.Mom if (field) |fl| { run.len = @intCast(@min(of.base + fl.at + fl.len - here, 16 - @as(u64, at))); run.kind = switch (fl.reads) { - .number, .bytes => .number, + .number, .bytes, .size, .protected => .number, .pointer => .pointer, .text => .text, }; @@ -490,7 +509,7 @@ fn fieldRow(u: ui.Ui, now: cursors.Now, y: f32, addr: u64, moment: Recording.Mom }; if (of.watched > 0 and now.wasRead(here, run.len) and now.writeAge(here, run.len) != 0) framed = @max(framed, now.reading(.memory, 0)); run.read = framed; - readings[n] = .{ .at = at, .len = run.len, .reads = fl.reads, .big = fl.big, .type = fl.type }; + readings[n] = .{ .at = at, .len = run.len, .reads = fl.reads, .big = fl.big, .type = fl.type, .note = fl.note, .addr = here }; ties.anchor(u, .{ .dump_run = here }, .{ .x = shift + rows.byteX(run.first) - 4, .y = y, .w = rows.byteX(run.first + run.len - 1) + 28 - rows.byteX(run.first) + 4, .h = m.row }); } else { // Up to the next field, or the row's end. @@ -535,9 +554,45 @@ pub fn reading(u: ui.Ui, y: f32, shift: f32, moment: Recording.Moment, values: * const first: usize = @intCast(fl.at); // A typed number is as wide as its type (an `int` in a word: 4 bytes). const len: usize = @intCast(if (fl.type) |ty| @min(fl.len, ty.size() orelse fl.len) else fl.len); - if (fl.reads == .bytes or len == 0) continue; - if (std.mem.indexOfScalar(bool, known[first..][0..len], false) != null) continue; + if (len == 0 or std.mem.indexOfScalar(bool, known[first..][0..len], false) != null) continue; + defer if (fl.note.len > 0) { + u.text(.sans, theme.size.sans.micro, x, base - 1, fl.note, t.faint); + x += u.width(.sans, theme.size.sans.micro, fl.note) + adv; + }; + if (fl.reads == .bytes) continue; const bytes = values[first..][0..len]; + var word_: u64 = 0; + for (0..@min(len, 8)) |k| word_ |= @as(u64, bytes[k]) << @intCast(8 * k); + switch (fl.reads) { + .size => { + const shown_size = u.print("0x{x}", .{word_ & ~@as(u64, 7)}); + u.text(.mono, size, x, base, shown_size, t.primary); + x += u.width(.mono, size, shown_size) + adv; + // A M P: set on a chip, clear in dim lower case. + for ([_]struct { u8, u6 }{ .{ 'A', 2 }, .{ 'M', 1 }, .{ 'P', 0 } }) |bit| { + const set = word_ >> bit[1] & 1 != 0; + if (set) u.chip(.{ .x = x - 3, .y = y + 2, .w = adv + 6, .h = theme.metric.flags.chip[1] }); + u.text(if (set) .mono_bold else .mono, size, x, base, &.{if (set) bit[0] else std.ascii.toLower(bit[0])}, if (set) t.bright else t.dim); + x += 2 * adv; + } + continue; + }, + .protected => { + const target = word_ ^ (fl.addr >> 12); + if (target == 0) { + u.text(.mono, size, x, base, "NULL", t.dim); + x += 5 * adv; + } else { + x = u.arrow(x, y + m.row / 2, .points); + x = u.address(x, base, target, .{ .ink = ui.rgb(rows.ink(rows.regionOf(moment, target))) }) + adv; + } + const masked = u.print("^ {x}", .{fl.addr >> 12}); + u.text(.mono, size, x, base, masked, t.faint); + x += u.width(.mono, size, masked) + adv; + continue; + }, + else => {}, + } const words: []const u8 = switch (fl.reads) { .number => blk: { var word: u64 = 0; @@ -557,7 +612,7 @@ pub fn reading(u: ui.Ui, y: f32, shift: f32, moment: Recording.Moment, values: * continue; }, .text => quoted(u, bytes), - .bytes => unreachable, + .bytes, .size, .protected => unreachable, }; const w = u.width(.mono, size, words); const fits = x + w <= room; diff --git a/anim/src/loupe.zig b/anim/src/loupe.zig index 99dae71..623e966 100644 --- a/anim/src/loupe.zig +++ b/anim/src/loupe.zig @@ -40,7 +40,14 @@ pub const Loupe = struct { stage: *const Stage, /// What it opens from: a register, by name; or a pointer field (its /// address) of the loupe it hangs under. - from: union(enum) { register: []const u8, field: struct { loupe: *const Loupe, at: u64 } }, + /// Or the bytes of a dump's row (`at`, a field the view publishes as a + /// `dump_run`), opening on `fields` (the region it reads them as): a + /// struct the debug info does not type (malloc's tcache), named `name`. + from: union(enum) { + register: []const u8, + field: struct { loupe: *const Loupe, at: u64 }, + row: struct { at: u64, name: []const u8, note: []const u8, fields: hexdump.Fields }, + }, /// 0 to 1 as it opens (`time.loupe.open`) and as it closes (`close`). opening: anim.Value = undefined, closing: anim.Value = undefined, @@ -85,6 +92,14 @@ pub const Loupe = struct { target = (Recording.word(moment, field.at, 8) catch null) orelse return null; right = parent.box.x + 120; }, + .row => |row| { + const px = ties.find(.{ .dump_run = row.at }) orelse return null; + const back = u.at.xf.invert(); + const a = back.apply(.{ px[0], px[1] }); + const b = back.apply(.{ px[2], px[3] }); + pointer = .{ .x = a[0], .y = a[1], .w = b[0] - a[0], .h = b[1] - a[1] }; + target = row.fields.base; + }, } if (target == 0) return null; // shortcut: it keeps to the stage and does not yet move past the current marks or a changed row; the scene picks a pointer whose loupe covers neither. @@ -135,6 +150,10 @@ pub const Loupe = struct { x += v.width(.mono, size, name) + 6; }, .field => |field| x = v.address(x, base, field.at, .{ .ink = ui.rgb(rows.ink(rows.regionOf(moment, field.at))) }) + 6, + .row => |row| { + v.text(.mono, size, x, base, row.name, t.dim); + x += v.width(.mono, size, row.name) + 6; + }, } x = v.arrow(x, m.tag / 2, .points) + 8; _ = v.address(x, base, p.target, .{ .ink = ui.rgb(p.ink) }); @@ -146,16 +165,17 @@ pub const Loupe = struct { .rodata => "read-only", .none => "", }; - const note = if (object) |o| v.print("{s} \u{00b7} {s}, {d} bytes", .{ region, if (o.name.len > 0) o.name else "a struct", o.type.record.size }) else region; + const note = if (l.from == .row) l.from.row.note else if (object) |o| v.print("{s} \u{00b7} {s}, {d} bytes", .{ region, if (o.name.len > 0) o.name else "a struct", o.type.record.size }) else region; v.text(.sans, theme.size.sans.micro, b.w - 10 - v.width(.sans, theme.size.sans.micro, note), base, note, t.dim); // Its rows, typed where the recording types them, its own pointers as arcs at full ink. const top = m.tag + m.pad; v.clip(.{ .x = 0, .y = m.tag, .w = b.w, .h = b.h - m.tag }); - hexdump.drawArcs(v, now, 0, top, p.first, k.rows, .{ .things = things }, true, .{ m.tag, b.h - m.pad }); + // By the scene's fields: the rows that hold them, the rest `more`. + if (l.from == .row) hexdump.fielded(.{ .u = v, .rows = k.rows, .box = b }, now, top, l.from.row.fields) else hexdump.drawArcs(v, now, 0, top, p.first, k.rows, .{ .things = things }, true, .{ m.tag, b.h - m.pad }); v.unclip(); // Its target, framed bright: each field of the struct, or the word. const framed = std.math.clamp((since - time.stem - time.frame) / time.frame, 0, 1); - if (framed > 0) { + if (framed > 0 and l.from != .row) { const row_y = top + @as(f32, @floatFromInt((p.target - p.first) / 16)) * m.row; const shift = rows.addressRoom(p.first + 16 * (k.rows - 1)); const w = v.faded(framed); diff --git a/anim/src/root.zig b/anim/src/root.zig index d8c2c76..84758f8 100644 --- a/anim/src/root.zig +++ b/anim/src/root.zig @@ -20,6 +20,8 @@ pub const layout = theme.layout; pub const ui = @import("ui.zig"); pub const Rect = theme.Rect; pub const Recording = @import("Recording.zig"); +/// The tracer's reader, for what a scene reads itself (`ztrace.heap.glibc`). +pub const ztrace = @import("ztrace"); const cursors = @import("cursor.zig"); pub const Cursor = cursors.Cursor; pub const Now = cursors.Now; @@ -35,7 +37,9 @@ pub const Stack = contexts.Stack; pub const Backtrace = contexts.Backtrace; /// The registers' tag: what an address's ink says. pub const contextLegend = contexts.legend; -pub const Disasm = @import("disasm.zig").Disasm; +pub const disasm = @import("disasm.zig"); +pub const Disasm = disasm.Disasm; +pub const Descent = @import("descent.zig").Descent; pub const calls = @import("calls.zig"); pub const CallTree = calls.Tree; pub const Nodes = @import("nodes.zig").Nodes; @@ -46,6 +50,7 @@ pub const Place = tying.Place; pub const Array = @import("array.zig").Array; pub const Loupe = @import("loupe.zig").Loupe; pub const syscalls = @import("syscalls.zig"); +pub const descent = @import("descent.zig"); pub const Crossing = syscalls.Crossing; pub const Timeline = syscalls.Timeline; pub const objects = @import("objects.zig"); @@ -235,6 +240,10 @@ pub const Context = struct { /// (eleven rows as subject, five beside), when how the program came /// to be here is the story; the scene adds the drawing's view. backtrace: bool = false, + /// The disassembly as a `descent`: a call followed down opens its + /// callee's window under the call row, and a system call the + /// kernel's under the `syscall` (step with `descent.step`). + descent: bool = false, }; /// The ties between the panes, drawn over everything added before. @@ -268,8 +277,8 @@ pub fn context(s: *anim.Frame, cursor_: Cursor, options: Context.Options) Contex // The map first: while it fills the frame or falls to the minimap it is under the panels diving out of it. const whole = s.new(map.Map{ .stage = Stage.init(s, map.split(at.rec, options.split.band.h > 0)), .frame = stage, .t = s.value(map.diving.land + map.diving.still) }); whole.obj = s.custom(whole, .{ .x = -640, .y = -360, .scale = ui.scale }); - whole.add(s, Source{ .cursor = at, .stage = whole.stage }); - whole.add(s, Disasm{ .cursor = at, .stage = whole.stage }); + whole.add(s, Source{ .cursor = at, .stage = whole.stage, .descent = options.descent }); + if (options.descent) whole.add(s, Descent{ .cursor = at, .stage = whole.stage }) else whole.add(s, Disasm{ .cursor = at, .stage = whole.stage }); whole.add(s, Registers{ .cursor = at, .stage = whole.stage, .syscalls = options.syscalls, .quiet = options.quiet }); whole.add(s, Stack{ .cursor = at, .stage = whole.stage, .above = theme.map.stack_above }); whole.add(s, Backtrace{ .cursor = at, .stage = whole.stage }); @@ -278,8 +287,8 @@ pub fn context(s: *anim.Frame, cursor_: Cursor, options: Context.Options) Contex .map = whole, .cursor = at, .quiet = options.quiet, - .source = add(s, Source{ .cursor = at, .stage = stage }), - .disasm = add(s, Disasm{ .cursor = at, .stage = stage }), + .source = add(s, Source{ .cursor = at, .stage = stage, .descent = options.descent }), + .disasm = if (options.descent) add(s, Descent{ .cursor = at, .stage = stage }) else add(s, Disasm{ .cursor = at, .stage = stage }), .registers = add(s, Registers{ .cursor = at, .stage = stage, .syscalls = options.syscalls, .quiet = options.quiet }), .stack = add(s, Stack{ .cursor = at, .stage = stage }), .backtrace = add(s, Backtrace{ .cursor = at, .stage = stage, .lens = options.backtrace }), @@ -344,6 +353,7 @@ test { _ = rows; _ = contexts; _ = @import("disasm.zig"); + _ = @import("descent.zig"); _ = tying; _ = @import("hexdump.zig"); _ = calls; diff --git a/anim/src/rows.zig b/anim/src/rows.zig index 83064a6..1d097a1 100644 --- a/anim/src/rows.zig +++ b/anim/src/rows.zig @@ -125,8 +125,8 @@ pub fn chain(u: ui.Ui, x: f32, y: f32, moment: Recording.Moment, value: u64, roo if (link.string) { // What a pointer leads to, when it is text: quoted, cut to the room // there is (never under six characters), with `…` and no closing quote. - const fits: usize = @intFromFloat(@max((room - at - m.arrow_w) / adv, 0)); - if (fits < m.string_min + 2) break; + const fits: usize = @intFromFloat(std.math.clamp((room - at - m.arrow_w) / adv, 0, 4096)); + if (fits < @as(usize, @min(m.string_min, link.text.len)) + 2) break; at = v.arrow(at, mid, .holds); const whole = link.text.len + 2 <= fits; const text = if (whole) u.print("\"{s}\"", .{link.text}) else u.print("\"{s}\u{2026}", .{link.text[0 .. fits - 2]}); @@ -167,9 +167,10 @@ pub const flags = [_]Flag{ .{ .name = "CF", .bit = 0 }, .{ .name = "PF", .bit = /// code's ink and its name; never struck. At its right end the `flags`, /// eight names on a pitch of 42: set, upper case on a chip, bold, bright; /// clear, lower case, dim; changed, a turned corner (`changed`: a bit per -/// flag, and how much of the corner shows). The value of eflags is not -/// drawn: the names are the value. -pub fn rip(u: ui.Ui, y: f32, w: f32, moment: Recording.Moment, pc: u64, eflags: u64, changed: u64, held: f32, fire: f32) void { +/// flag, and how much of the corner shows); read, framed (`read`: a bit per +/// flag, while a conditional reads them: an echo of the row that set them, +/// `read_shows` how much). The value of eflags is not drawn: the names are the value. +pub fn rip(u: ui.Ui, y: f32, w: f32, moment: Recording.Moment, pc: u64, eflags: u64, changed: u64, held: f32, fire: f32, read: u64, read_shows: f32) void { const gold = theme.mark(.current); u.current(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = row_h }, theme.metric.plaque.rip, fire); u.text(.mono_bold, size, m.side, baseline(y), "rip", gold.on_solid); @@ -183,6 +184,7 @@ pub fn rip(u: ui.Ui, y: f32, w: f32, moment: Recording.Moment, pc: u64, eflags: u.text(.mono_bold, size, x + 4, baseline(y), flag.name, t.bright); } else u.text(.mono, size, x + 4, baseline(y), u.print("{c}{c}", .{ std.ascii.toLower(flag.name[0]), std.ascii.toLower(flag.name[1]) }), ui.mix(t.dim, gold.ember, 0.2)); if (changed >> flag.bit & 1 != 0) u.corner(x, y + 2, m.corner, held); + if (read >> flag.bit & 1 != 0 and read_shows > 0) u.read(.{ .x = x, .y = y + 2, .w = fl.chip[0], .h = fl.chip[1] }, read_shows); x += fl.pitch; } } diff --git a/anim/src/source.zig b/anim/src/source.zig index 58b9df0..bbc985e 100644 --- a/anim/src/source.zig +++ b/anim/src/source.zig @@ -17,6 +17,7 @@ const ties = @import("ties.zig"); const map = @import("map.zig"); const cursors = @import("cursor.zig"); const Stage = @import("stage.zig").Stage; +const Recording = @import("Recording.zig"); const Cursor = cursors.Cursor; const theme = ui.theme; const Rect = ui.Rect; @@ -28,6 +29,9 @@ pub const Source = struct { cursor: Cursor, stage: *const Stage, focus: bool = false, + /// In a `descent`: while the pc is in code without source, the line it + /// called from waits, ringed, and the tag says where the pc is. + descent: bool = false, pub fn draw(p: *const Source, f: *sk.Frame, placed: anim.Placed) void { const box = p.stage.box(placed, .source); @@ -52,7 +56,10 @@ pub const Source = struct { const from: u32 = @intFromFloat(@floor(first)); const last: u32 = @min(from + @as(u32, @intCast(context.rowsOf(box))), rec.line_count); const shown_first: u32 = @intFromFloat(windows[if (going >= 0.5) 1 else 0]); - const body = u.panel(box.w, box.h, rec.file, .{ .focus = p.focus, .note = if (rec.line_count > fit) u.print("lines {d} to {d} of {d}", .{ shown_first, @min(shown_first + fit - 1, rec.line_count), rec.line_count }) else u.print("{d} lines", .{rec.line_count}) }); + // Waiting: the pc is in code with no source, under this line's call. + const waits = p.descent and !rec.sourced(now.marked()) and rec.own[now.marked()] != 0; + const note = if (waits) u.print("{s} waits at line {d} \u{00b7} the pc is in {s}", .{ context.frameName(u, rec, rec.register(firstOwn(rec, now.marked()), "rip")), rec.own[now.marked()], whereIs(u, rec, now.marked()) }) else if (rec.line_count > fit) u.print("lines {d} to {d} of {d}", .{ shown_first, @min(shown_first + fit - 1, rec.line_count), rec.line_count }) else u.print("{d} lines", .{rec.line_count}); + const body = u.panel(box.w, box.h, rec.file, .{ .focus = p.focus, .note = note }); const top = body.y + m.pad; // Where the mark is, and how much of it. @@ -85,7 +92,11 @@ pub const Source = struct { defer u.unclip(); // The plaque over the number. Fire: on the line about to run its // edges go out and come back, once, and nothing else moves. - if (shows > 0) u.faded(shows).current(.{ .x = theme.stroke.rule, .y = mark_y, .w = box.w - 2 * theme.stroke.rule, .h = m.row }, theme.metric.plaque.line + widen, now.fires(.source)); + if (waits) { + // The number ringed: a 2-unit primary frame where the plaque would be, no wash. + u.faded(shows).frame(.{ .x = theme.stroke.rule + 1, .y = mark_y + 1, .w = theme.metric.plaque.line + widen - 2, .h = m.row - 2 }, theme.color.text.primary, theme.stroke.rule); + if (!ui.mapping) ties.thread_waits = true; + } else if (shows > 0) u.faded(shows).current(.{ .x = theme.stroke.rule, .y = mark_y, .w = box.w - 2 * theme.stroke.rule, .h = m.row }, theme.metric.plaque.line + widen, now.fires(.source)); if (shows >= 1 and mark_y >= body.y and mark_y + m.row <= box.h) ties.anchor(u, .source, .{ .x = 0, .y = mark_y, .w = box.w, .h = m.row }); // The trail: the last three other lines it was on. It shifts without animation. @@ -109,13 +120,33 @@ pub const Source = struct { const span = text.lines[line - 1]; const k = std.mem.indexOfScalar(u32, trail[0..found], line); const on = shows >= 0.5 and line == mark_line; - rows.line(lit, y, box.w, line, widen, text.bytes[span[0]..span[1]], text.styles[span[0]..span[1]], if (on) .marked else if (k) |n| .{ .trail = n } else .plain); + rows.line(lit, y, box.w, line, widen, text.bytes[span[0]..span[1]], text.styles[span[0]..span[1]], if (on and !waits) .marked else if (k) |n| .{ .trail = n } else .plain); } // The source is read at a run; at a sprint it is veiled too. context.veiled(u, box, now.sprint_veil); } }; +/// The last moment at or before `i` whose pc was on a line of the program's source. +fn firstOwn(rec: *const Recording, i: u64) u64 { + var at = i; + while (at > 0 and !rec.sourced(at)) at -= 1; + return at; +} + +/// Where the pc is at moment `i`, for the waiting line's tag: `the PLT`, +/// `libc's open`, `the vdso`. +fn whereIs(u: ui.Ui, rec: *const Recording, i: u64) []const u8 { + const name = context.frameName(u, rec, rec.register(i, "rip")); + if (std.mem.endsWith(u8, name, "@plt")) return "the PLT"; + var module: []const u8 = ""; + var buf: [256]u8 = undefined; + _ = (rec.moment(i).mapping(rec.register(i, "rip"), &module, &buf) catch null); + const base = std.fs.path.basename(module); + const short = base[0 .. std.mem.indexOfScalar(u8, base, '.') orelse base.len]; + return u.print("{s}'s {s}", .{ short, name }); +} + /// A source ready to draw: a class for each byte, and where each line is. const Text = struct { bytes: []const u8, diff --git a/anim/src/syscalls.zig b/anim/src/syscalls.zig index e184990..4a46170 100644 --- a/anim/src/syscalls.zig +++ b/anim/src/syscalls.zig @@ -20,7 +20,6 @@ const Stage = @import("stage.zig").Stage; const theme = ui.theme; const time = theme.time; const Rect = ui.Rect; -const k = theme.color.on_kernel; /// A crossing's timetable, in seconds into its step (design/motion.md, "A /// system call"). Staging, one thing at a time and no effect before its @@ -156,11 +155,12 @@ pub fn fills(call: Recording.Syscall) ?Recording.Span { return if (call.nr == @intFromEnum(std.os.linux.SYS.read) and got > 0) .{ .addr = call.args[1], .len = @intCast(got) } else null; } -/// The kernel as a lens: solid vellum, and nothing else on the frame is. -/// The call the step made, decoded (its name, a row an argument by the -/// argument's own name, what came back), the calls before it, the bytes it -/// was given; and the arrow that crosses into it from the registers' -/// side and returns. +/// The `syscalls` lens: the program's conversation with the kernel. Its +/// drawing is the calls so far as strace writes them, a row each, oldest +/// on top and the newest at the bottom (its row comes in once the call is +/// back, with the turned corner); not the kernel, and not on vellum: the +/// kernel is under the program, the floor of the disassembly's `descent`. +/// Its view, the bytes the newest call was given or filled. pub const Crossing = struct { cursor: cursors.Cursor, stage: *const Stage, @@ -182,45 +182,78 @@ pub const Crossing = struct { defer u.unclip(); const now = c.cursor.now(placed); const rec = c.cursor.rec; - const body = u.panel(box.w, box.h, "kernel", .{ .focus = c.focus, .note = "the other side of a system call" }); - u.fill(.{ .x = theme.stroke.rule, .y = body.y, .w = body.w - 2 * theme.stroke.rule, .h = body.h - theme.stroke.rule }, theme.color.kernel); + const room = context.rowsOf(box); + // The calls from the scene's first moment: the program's, not its loader's. + var first: usize = 0; + while (first < rec.syscalls.len and rec.syscalls[first].enter < c.cursor.first) first += 1; + var newest = latest(rec, now.stops[0]); + // A crossing's own row comes in once it is back (rax struck), 12 f. + var arrives: f32 = 1; + if (newest) |n| if (inStep(now) != null and now.walking()) { + const p = Plan.of(rec.syscalls[n]); + arrives = std.math.clamp((now.time - p.struck - 6.0 / 60.0) / theme.time.quick, 0, 1); + }; + if (newest) |n| if (n < first) { + newest = null; + }; + const count = if (newest) |n| n + 1 - first else 0; + const body = u.panel(box.w, box.h, "system calls", .{ .focus = c.focus, .note = if (count > room) u.print("as strace writes them \u{00b7} newest at the bottom \u{00b7} {d} more above", .{count - room}) else "as strace writes them \u{00b7} newest at the bottom" }); context.clipBody(u, box); defer u.unclip(); - u.text(.sans, theme.size.sans.micro, 12, body.y + 22, "calls so far", k.dim); - const newest = latest(rec, now.stops[0]) orelse return; - const live = inStep(now) != null and now.walking(); - const p = Plan.of(rec.syscalls[newest]); - const t: f32 = if (live) now.time else std.math.inf(f32); - if (t >= p.enters) arrows(u, body, t, p, rec.syscalls[newest]); - // No effect before its cause: until the arrow is through the - // line the kernel knows nothing of this call, and shows the last. - if (t < p.name) { - if (newest > 0) c.call(u.faded(1 - theme.ease(.exit, std.math.clamp((t - p.leaves) / (p.name - p.leaves), 0, 1))), body, rec.syscalls[newest - 1], .{}, std.math.inf(f32)); - } else c.call(u, body, rec.syscalls[newest], p, t); + const n = newest orelse return; + const top = body.y + theme.metric.context.pad; + const shown = @min(count, room); + for (0..shown) |j| { + const i = n + 1 - shown + j; + const v = if (i == n) u.faded(arrives) else u; + const y = top + @as(f32, @floatFromInt(j)) * row_h; + logRow(v, rec, rec.syscalls[i], y, box.w - theme.metric.context.side); + if (i == n) v.corner(theme.metric.context.side, y + 2, theme.metric.context.corner, 1); + } + } - // The calls so far, newest on top. This one's row pushes in when - // the kernel has taken the call: the others make room first. - const pushed = cursors.standard(std.math.clamp((t - p.card) / theme.time.quick, 0, 1)); - const arrived = std.math.clamp((t - p.card - theme.time.snap) / theme.time.quick, 0, 1); - const top = body.y + 32; - var i = newest + 1; - while (i > 0) { - i -= 1; - const place = @as(f32, @floatFromInt(newest - i)) - (if (i == newest) 0 else 1 - pushed); - const y = top + place * (row_h + 4) - (if (i == newest) (1 - arrived) * 8 else 0); - if (y + row_h > body.y + body.h - 6) continue; - const v = if (i == newest) u.faded(arrived) else u; - const card: Rect = .{ .x = 12, .y = y, .w = 196, .h = row_h }; - const done = rec.syscalls[i]; - const gold = if (i == newest) arrived >= 1 else i + 1 == newest and arrived < 1; - if (gold) v.fill(card, theme.mark(.current).solid); - v.frame(card, k.ink, theme.stroke.rule); - const name = zt.syscalls.name(done.nr) orelse "?"; - // The result ranged right, when it is short; the name has the rest, and is cut only there. - const words = if ((i != newest or t >= p.returns) and done.exit != null) result(u, done) else ""; - const said = if (words.len > 0 and words.len <= 4) words else ""; - if (said.len > 0) v.text(.mono, size, card.x + card.w - 8 - u.width(.mono, size, said), theme.baseline(card.y, card.h, size), said, k.dim); - v.text(if (gold) .mono_bold else .mono, size, card.x + 8, theme.baseline(card.y, card.h, size), rows.fitted(u, name, card.w - 16 - (if (said.len > 0) u.width(.mono, size, said) + 12 else 0)), k.ink); + /// A call as strace writes it, its arguments by name: `read fd 3 + /// "note" buf 7fffffffecd0 count 32 = 15`, cut at `room` with `…`. + fn logRow(u: ui.Ui, rec: *const Recording, made: Recording.Syscall, y: f32, room: f32) void { + const base = theme.baseline(y, row_h, size); + const adv = ui.advance(size); + var x: f32 = theme.metric.context.side; + const name = zt.syscalls.name(made.nr) orelse "syscall"; + u.text(.mono_bold, size, x, base, name, theme.color.text.bright); + x += u.width(.mono_bold, size, name) + adv; + const names = zt.syscalls.names(made.nr); + const n = @min(zt.syscalls.signature(made.nr).len, 6); + const Part = struct { text: []const u8, ink: u24 }; + var parts: [32]Part = undefined; + var np: usize = 0; + for (0..n) |j| { + const what = if (j < names.len) names[j] else ""; + if (what.len > 0) { + parts[np] = .{ .text = what, .ink = theme.color.text.dim }; + np += 1; + } + parts[np] = .{ .text = @import("disasm.zig").argument(u, rec, made.enter, what, made.args[j]), .ink = theme.color.text.primary }; + np += 1; + if (std.mem.endsWith(u8, what, "fd")) { + const on = rec.openOn(u.f.scratch, made.args[j], made.enter); + if (on.len > 0) { + parts[np] = .{ .text = on, .ink = theme.color.text.faint }; + np += 1; + } + } + } + parts[np] = .{ .text = "=", .ink = theme.color.text.faint }; + np += 1; + parts[np] = .{ .text = if (made.exit != null) result(u, made) else "?", .ink = theme.color.text.primary }; + np += 1; + for (parts[0..np]) |part| { + const w = u.width(.mono, size, part.text); + if (x + w > room) { + u.text(.mono, size, x, base, "\u{2026}", theme.color.text.faint); + return; + } + u.text(.mono, size, x, base, part.text, part.ink); + x += w + adv; } } @@ -236,7 +269,8 @@ pub const Crossing = struct { newest = if (n > 0) n - 1 else null; }; const made: ?Recording.Syscall = if (newest) |n| rec.syscalls[n] else null; - const span: ?Recording.Span = if (made) |given| bufferRead(given) orelse fills(given) orelse if (given.text.len > 0 and std.mem.indexOfScalar(u8, zt.syscalls.signature(given.nr), 's') != null) .{ .addr = given.args[0], .len = given.text.len + 1 } else null else null; + const path_at: ?usize = if (made) |given| std.mem.indexOfScalar(u8, zt.syscalls.signature(given.nr), 's') else null; + const span: ?Recording.Span = if (made) |given| bufferRead(given) orelse fills(given) orelse if (given.text.len > 0 and path_at != null) .{ .addr = given.args[path_at.?], .len = given.text.len + 1 } else null else null; const scratch = context.at(f, placed, c.stage.box(placed, .view)); const about = if (span) |sp| scratch.print("the {s}, {x} to {x}", .{ if (bufferRead(made.?) != null) "buffer given" else if (fills(made.?) != null) "buffer filled" else "path given", sp.addr, sp.addr + sp.len - 1 }) else "the call names no bytes"; const v = hexdump.panel(f, placed, c.stage, about, &.{}); @@ -259,140 +293,8 @@ pub const Crossing = struct { }); v.veil(now); } - - /// A call, decoded: its name, a row for each argument, what came - /// back; and to the right the bytes it was given, as the kernel - /// copies them. - fn call(c: *const Crossing, u: ui.Ui, body: Rect, made: Recording.Syscall, p: Plan, t: f32) void { - const rec = c.cursor.rec; - const x = 236; - const name = zt.syscalls.name(made.nr) orelse "syscall"; - // The name arrives rising, as a caption does. - const named = theme.ease(.enter, std.math.clamp((t - p.name) / theme.time.quick, 0, 1)); - const title = u.faded(named); - const rise = (1 - named) * theme.time.caption_rise; - title.text(.mono_bold, theme.size.mono.value, x, body.y + 46 + rise, name, k.ink); - title.text(.sans, theme.size.sans.micro, x + u.width(.mono_bold, theme.size.mono.value, name) + 16, body.y + 44 + rise, u.print("system call {d}", .{made.nr}), k.dim); - const signature = zt.syscalls.signature(made.nr); - var row_y: f32 = body.y + 62; - var text_used = false; - const row = struct { - /// `note`: faint after the words, what a descriptor is open on (the `value` class `fd`). - fn draw(v: ui.Ui, y: f32, register: []const u8, meaning: []const u8, words: []const u8, note: []const u8) void { - v.fill(.{ .x = x, .y = y, .w = 300, .h = theme.stroke.rule }, k.rule); - const base = theme.baseline(y, row_h + 4, size); - v.text(.mono, size, x, base, register, k.dim); - v.text(.sans_medium, theme.size.sans.tag, x + 52, base, meaning, k.ink); - v.text(.mono, size, x + 130, base, words, k.ink); - v.text(.mono, size, x + 130 + v.width(.mono, size, words) + 8, base, note, k.dim); - } - }.draw; - for (signature, 0..) |kind, arg| { - if (arg >= 4) break; - const shows = std.math.clamp((t - p.rows - @as(f32, @floatFromInt(arg)) * Plan.row) / Plan.row, 0, 1); - const meaning = what(made.nr, kind, arg); - const note = if (std.mem.eql(u8, meaning, "fd")) rec.openOn(u.f.scratch, made.args[arg], made.enter) else ""; - row(u.faded(shows), row_y, carriers[arg], meaning, value(u, made, kind, arg, &text_used), note); - row_y += row_h + 4; - } - const back = t >= p.returns and made.exit != null; - // What `open` returns is a descriptor: open on the path it was given. - const opened = back and std.mem.eql(u8, zt.syscalls.name(made.nr) orelse "", "open") and @as(i64, @bitCast(made.result)) >= 0; - row(u.faded(std.math.clamp((t - p.rows - @as(f32, @floatFromInt(@min(signature.len, 4))) * Plan.row) / Plan.row, 0, 1)), row_y, "rax", "returns", if (back) result(u, made) else "\u{2014}", if (opened) rec.openOn(u.f.scratch, made.result, made.exit.? + 1) else ""); - - if (made.text.len == 0) return; - const bytes_x = 564; - const framed = u.faded(std.math.clamp((t - p.work) / Plan.row, 0, 1)); - framed.text(.sans, theme.size.sans.micro, bytes_x, body.y + 22, if (std.mem.indexOfScalar(u8, signature, 's') != null) "the path it was given" else "the bytes it was given", k.dim); - const shown = @min(made.text.len, shown_bytes); - const text = for (made.text[0..shown]) |byte| { - if (!std.ascii.isPrint(byte) and byte != '\n') break false; - } else true; - for (made.text[0..shown], 0..) |byte, j| { - const cell: Rect = .{ .x = bytes_x + @as(f32, @floatFromInt(j % per_row)) * 28, .y = body.y + 32 + @as(f32, @floatFromInt(j / per_row)) * 30, .w = 26, .h = 26 }; - // Each fills as it is copied, two frames a byte: struck, then held. - const since = t - p.fills - @as(f32, @floatFromInt(j)) * Plan.byte; - if (since < 0) { - framed.frame(cell, k.rule, theme.stroke.rule); - continue; - } - const in = std.math.clamp(since / theme.time.strike.in, 0, 1); - u.fill(cell, ui.mix(theme.color.kernel, ui.mix(theme.mark(.write).solid, k.held, std.math.clamp((since - theme.time.quick) / theme.time.strike.cool, 0, 1)), in)); - u.frame(cell, k.ink, theme.stroke.rule); - if (in < 0.5) continue; - // Text as its characters; anything else (a page of a file) as hex. - if (!text) { - u.label(.mono, size, cell, .center, u.print("{x:0>2}", .{byte}), k.ink); - } else if (std.ascii.isPrint(byte) and byte != ' ') u.label(.mono, size, cell, .center, &.{byte}, k.ink) else if (byte == '\n') u.label(.mono, size, cell, .center, "\\n", k.dim); - } - } - - /// The crossing itself: in from the side the registers are on as the - /// call enters, and back out as it returns. Vellum outside the - /// kernel, ink inside it. Machines do not lob: straight. - /// The crossing itself: up out of the registers below the band (the - /// ones that carried it), into the kernel, as the call enters; and back - /// down as it returns. Machines do not lob: straight. - fn arrows(u: ui.Ui, body: Rect, t: f32, p: Plan, made: Recording.Syscall) void { - // At the drawing's right, where it meets the state column the call leaves from. - const x = body.w - 56; - const bottom = body.y + body.h; - const reach = 64; - // Off promptly, and settling in the kernel. - const up = cursors.standard(std.math.clamp((t - p.enters) / Plan.cross, 0, 1)); - const gone = std.math.clamp((t - p.struck - theme.time.quick) / theme.time.read.out, 0, 1); - const v = u.faded(1 - gone); - if (t < p.back) along(v, x, bottom, bottom - up * reach); - if (made.exit != null and t > p.back) along(v, x + 40, bottom - reach, bottom - reach + cursors.standard(std.math.clamp((t - p.back) / Plan.cross, 0, 1)) * reach); - } - - /// An arrow down the column at `x` from `from` to `to`, in ink: it is inside the kernel. - fn along(u: ui.Ui, x: f32, from: f32, to: f32) void { - if (@abs(to - from) < 1) return; - const w = theme.stroke.arrow; - const head = theme.stroke.flow_head; - const dir: f32 = if (to > from) 1 else -1; - const neck = to - dir * (head[0] - 2); - if ((neck - from) * dir > 0) u.fill(.{ .x = x - w / 2, .y = @min(from, neck), .w = w, .h = @abs(neck - from) }, k.ink); - if (@abs(to - from) < head[0]) return; - sk.draw.polygon(u.f, &.{ .{ x, to }, .{ x - head[1] / 2, to - dir * head[0] }, .{ x + head[1] / 2, to - dir * head[0] } }, u.at.pen(.{ .fill = ui.rgb(k.ink) })); - } }; -/// What an argument is called: by the call's own names where the tracer's -/// table has them, else from its letter in `zt.syscalls.signature`. -fn what(nr: u16, kind: u8, arg: usize) []const u8 { - const names = zt.syscalls.names(nr); - if (arg < names.len) return names[arg]; - return switch (kind) { - 'i' => "number", - 'd' => "size", - 's' => "path", - 'b' => "buffer", - else => "pointer", - }; -} - -fn value(u: ui.Ui, made: Recording.Syscall, kind: u8, arg: usize, text_used: *bool) []const u8 { - // Flags and a mode are bits: hex, said so. - const meaning = what(made.nr, kind, arg); - if (std.mem.eql(u8, meaning, "flags") or std.mem.eql(u8, meaning, "mode")) return u.print("0x{x}", .{made.args[arg]}); - const a = made.args[arg]; - switch (kind) { - 'i' => return u.print("{d}", .{@as(i32, @bitCast(@as(u32, @truncate(a))))}), - 'd' => return u.print("{d}", .{a}), - 's' => if (made.text.len > 0 and !text_used.*) { - text_used.* = true; - const base = std.fs.path.basename(made.text); - // A string cut says so: `…` and no closing quote. - return if (base.len <= 14) u.print("\"{s}\"", .{base}) else u.print("\"{s}\u{2026}", .{base[0..13]}); - }, - else => {}, - } - return u.print("{x}", .{a}); -} - - /// What came back: a count, an address, or an error by name. fn result(u: ui.Ui, made: Recording.Syscall) []const u8 { const ret: i64 = @bitCast(made.result); diff --git a/anim/src/theme.zig b/anim/src/theme.zig index 5a85f50..0c646d8 100644 --- a/anim/src/theme.zig +++ b/anim/src/theme.zig @@ -538,6 +538,16 @@ pub const metric = struct { pub const annotation = 564; }; + /// `width`: an access's size in byte cells, where nothing else in the + /// instruction says it: cells 5 by 10, 7 apart, `dim`, on the baseline 3 + /// after the `]`; what follows 4 after the last cell. + pub const width = struct { + pub const cell = [2]f32{ 5, 10 }; + pub const pitch = 7; + pub const before = 3; + pub const after = 4; + }; + /// `bytes`: a hexdump row, from its panel's left edge (the band's right /// half): its `arc` lanes, the quiet bracket at 24, the address at 34, /// the bytes 12 after it and at 132 at least. diff --git a/anim/src/ties.zig b/anim/src/ties.zig index 323cecf..d3a9ec7 100644 --- a/anim/src/ties.zig +++ b/anim/src/ties.zig @@ -77,6 +77,9 @@ pub const Place = union(enum) { /// where its pin lane runs (canvas pixels: x, the first row's top, the /// row's height). A link to a word outside it ends at its edge. pub var stack_window: ?struct { first: u64, slots: usize, x: f32, top: f32, row: f32 } = null; +/// The source's line waits (a `descent`: the pc is in code without source): +/// the thread waits with it, primary and 2 units. +pub var thread_waits = false; /// What this frame's components have said so far, in canvas pixels: left, top, right, bottom. /// shortcut: one table for the process, emptied by `Ties.draw`; a scene with two players at once wants it on the frame. @@ -175,6 +178,7 @@ pub const Ties = struct { pub fn draw(g: *const Ties, f: *sk.Frame, at: anim.Placed) void { defer said = 0; defer stack_window = null; + defer thread_waits = false; const now = g.cursor.now(at); // Diving or surfacing, the panels are on their way: no ties. for (@import("context.zig").zoomed) |z| if (z != null) return; @@ -193,8 +197,8 @@ pub const Ties = struct { fn thread(raw: ui.Ui, at: anim.Placed, k: f32) void { const line = find(.source) orelse return; const x = at.xf.apply(.{ theme.metric.tie.thread_x, 0 })[0]; - const gold = theme.mark(.current).solid; - const kind = [2]f32{ theme.metric.bracket.thread[0] * k, theme.metric.bracket.thread[1] * k }; + const gold = if (thread_waits) ui.rgb(theme.color.text.primary) else ui.rgb(theme.mark(.current).solid); + const kind = if (thread_waits) [2]f32{ theme.metric.bracket.quiet[0] * k, theme.metric.bracket.quiet[1] * k } else [2]f32{ theme.metric.bracket.thread[0] * k, theme.metric.bracket.thread[1] * k }; raw.bracket(x, line[1] + 2 * k, line[3] - 2 * k, gold, kind, 1, false); var bottom = line[3] - 2 * k; var top = line[1] + 2 * k; -- cgit v1.3