//! `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 graph = @import("graph.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.9 /// s), on through a PLT stub's `jmp` (2.2 s), out by a `ret` (`ascend`, 2.5 /// s), across into the kernel (`cross`: `syscalls.step`); any other walked. /// A window opens and closes in two moves, never at once: the rows it gives /// up fade, then the rows it keeps glide (and back: they glide, then fade in). 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 ""; // `tied`: the push or the read first, as any call's or return's (the touch, the word, rsp's pin, the // window following: the stack's own timetable), then the windows, 42 f (a call) or 48 f (a return) later. const tied = cur.levels.annotation == .tied; const plan: cursors.Plan = switch (b.kind) { .call => if (tied) stacked(cur, from, to, f(180), f(216)) else .{ .at = .{ f(24), f(60), f(60) }, .advance = f(138), .travel = f(12), .total = f(174) }, .ret => if (tied) stacked(cur, from, to, f(162), f(198)) else .{ .at = .{ f(36), f(18), f(36) }, .advance = f(114), .travel = f(12), .total = f(150) }, .jump => if (std.mem.indexOf(u8, here, "@plt") != null) .{ .at = .{ f(18), f(24), f(24) }, .advance = f(96), .travel = f(12), .total = f(132) } else return cur.walk(s, by, to), .none => return cur.walk(s, by, to), }; cur.step(s, to, plan, plan.total); } /// A caller's window standing alone (the introduction, motion.md II2: the /// first code on screen): a descent's head row (the function, its file /// ranged right) over its call, the row the call returns to and the next, /// each said as a place (`row`) for an aim, a call's callee named where the /// annotation goes. `in` (frames): the head, then the rows 2 f apart, 12 f /// each; `faint` (0 to 1): to half, as it stays under what follows. pub const Caller = struct { rec: *const Recording, at: u64, /// The call instruction's address. call: u64, box: Rect, in: anim.Value, faint: anim.Value, pub fn draw(r: *const Caller, fr: *sk.Frame, placed: anim.Placed) void { const clock = placed.value(r.in); if (clock < 0) return; const u = (ui.Ui{ .f = fr, .at = placed }).moved(r.box.x, r.box.y).faded(1 - 0.5 * std.math.clamp(placed.value(r.faint), 0, 1)); const moment = r.rec.moment(r.at); var name_buf: [128]u8 = undefined; const head = u.faded(std.math.clamp(clock / 12, 0, 1)); const name = (moment.string(r.call, &name_buf) catch null) orelse ""; head.fill(.{ .x = theme.stroke.rule, .y = 0, .w = r.box.w - 2 * theme.stroke.rule, .h = theme.stroke.rule }, theme.color.rule); head.text(.sans_medium, theme.size.sans.micro, c.address, 18, u.print("{s}", .{name[0 .. std.mem.indexOfScalar(u8, name, '+') orelse name.len]}), t.primary); head.text(.sans, theme.size.sans.micro, r.box.w - 12 - head.width(.sans, theme.size.sans.micro, r.rec.file), 18, r.rec.file, t.faint); var addr = r.call; var buf: [256]u8 = undefined; for (0..3) |n| { const insn = r.rec.instruction(r.at, addr, &buf) orelse return; const y = m.row * @as(f32, @floatFromInt(n + 1)); const rv = u.faded(std.math.clamp((clock - 12 - 2 * @as(f32, @floatFromInt(n))) / 12, 0, 1)); _ = rv.address(c.address, rows.baseline(y), addr, .{ .ink = ui.rgb(theme.color.region.code_) }); const row: Insn = .{ .addr = addr, .len = insn.len, .text = insn.text, .line = insn.line }; disasm.bareRow(rv, row, y); if (disasm.target(row)) |to| if (std.mem.startsWith(u8, insn.text, "call")) { if (moment.string(to, &name_buf) catch null) |callee| rv.text(.mono, size, c.annotation, rows.baseline(y), ui.symbol(rv, callee[0 .. std.mem.indexOfScalar(u8, callee, '+') orelse callee.len]), t.primary); }; ties.anchor(u, .{ .row = addr }, .{ .x = 0, .y = y, .w = r.box.w, .h = m.row }); addr += insn.len; } } }; /// The key of the head row over function `name`'s window (a `ties.Place.row`). pub fn headKey(name: []const u8) u64 { return std.hash.Wyhash.hash(0, name) | 1 << 63; } /// The stack's own timetable for the step (`Cursor.planned`), its advance and its end the descent's. fn stacked(cur: cursors.Cursor, from: u64, to: u64, advance: f32, total: f32) cursors.Plan { var plan = cur.planned(from, to, false); plan.advance = advance; plan.travel = f(12); plan.total = total; return plan; } /// 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); // The panel growing or shrinking at rest (a column's change): the rows of // its two heights' layouts glide between them, the rest fade at the edge; never empty. const resize = if (now.resting()) d.stage.resizing(placed, .disasm) else null; const before = layout(u, rec, now.stops[if (resize != null) 0 else 1], if (resize) |r| theme.layout.rowsIn(r.from) else room, d.root); const after = layout(u, rec, now.stops[0], if (resize) |r| theme.layout.rowsIn(r.to) else room, d.root); // On the map its box is as long as the rows it has wanted: not 69 for a function of 30. if (ui.mapping) map.measure(.disasm, @max(before.items.len, after.items.len)); 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; // `tied` (a plan with the stack's own moves, `stacked`): the windows move once the stack has, 42 f later down, 48 f up. const shift: f32 = if (now.plan.follow < 0) 0 else switch (kind) { .down => f(42), .up => f(48), .same, .through => 0, }; const tm = now.time - shift; const shown = if (going >= 0.5) after else before; // A tag that changes with the advance crossfades over it. const retag = !std.mem.eql(u8, before.tag, after.tag); const body = u.panel(box.w, box.h, "disassembly", .{ .focus = d.focus, .note = if (retag) "" else shown.tag }); if (retag) { u.faded(1 - going).tagNote(box.w, before.tag); u.faded(going).tagNote(box.w, after.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. // At rest `going` is 1; a resize slides by its own progress. const slide = if (resize) |r| r.p else going; const move: f32 = switch (kind) { .same => if (resize != null) slide else cursors.glide(going), .down => cursors.glide(clamp01((tm - f(78)) / f(18))), .through => cursors.glide(clamp01((tm - f(36)) / 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, twin: bool = false }; // A row whose state the verb changes (the call row going to wait, a // stub's jmp passing, a waiting call taking its result) crossfades from // the one to the other (12 f; 6 f up), its hanging arguments with it. const turn: f32 = switch (kind) { .same => 0, .down => clamp01((tm - f(66)) / f(12)), .through => clamp01((tm - f(24)) / f(12)), .up => clamp01((tm - f(114)) / f(6)), }; 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 * slide), .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; if (kind != .same and old.state != it.state) { placed_items.append(a, .{ .item = old, .y = y, .shows = 1 - turn, .rise = 0, .old = old, .new = it }) catch {}; placed_items.append(a, .{ .item = it, .y = y, .shows = turn, .rise = 0, .old = old, .new = it, .twin = true }) catch {}; continue; } placed_items.append(a, .{ .item = if (going < 0.5) old else it, .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 * slide - 1), .down => if (head) clamp01((tm - f(108)) / f(12)) else clamp01((tm - f(114) - @as(f32, @floatFromInt(arriving)) * f(2)) / f(12)), .through => if (head) clamp01((tm - f(66)) / f(12)) else clamp01((tm - f(72) - @as(f32, @floatFromInt(arriving)) * f(2)) / f(12)), .up => clamp01((tm - f(102)) / f(12)), }; 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 (84 to 96 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(84)) / 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 - 1), }; // A crossing stepped over: the kernel's window opens under the call // row, past the arguments hanging under it; the rows after them make // room first (18 f, as the lane sets off) and close up with the // window as it draws back. var under: ?f32 = null; if (steppedOver(now)) |made| for (placed_items.items) |p| if (p.old) |o| if (o.state == .current and o.what == .insn) { const at = p.y + @as(f32, @floatFromInt(1 + disasm.hanging(u, rec, o.what.insn, now.stops[1]))) * m.row; const sp = syscalls.Plan.in(now, made); const opening = cursors.glide(clamp01((tm - sp.enters) / f(18))); const room_ = 3 * m.row * @min(opening, 1 - clamp01((tm - now.plan.advance) / f(12))); for (placed_items.items) |*q| if (q.y >= at - 1) { q.y += room_; }; under = at; break; }; 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].?, if (resize != null) slide else cursors.standard(going)), .shows = 1 } else if (pc_y[1]) |y| { mark = .{ .y = y, .shows = clamp01(2 * slide - 1) }; } else if (pc_y[0]) |y| { mark = .{ .y = y, .shows = 1 - clamp01(2 * slide) }; } } 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_before = recentRows(a, now, 1); const ran_after = recentRows(a, now, 0); // The line the source panel is on, in the file it shows: rows of that file carry their numbers. const current = rec.shown[marked]; const current_line = current.line; const widen0 = rows.numberRoom(rec.most_lines); var covered: usize = 0; var covered_before: 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 }; // Each window's blocks (`graph`), read once: a rule over each one's first row, its visits where the row has room. var rules: [8]?graph.Rules = @splat(null); 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| { ties.anchor(u, .{ .row = p.item.key }, .{ .x = 0, .y = y, .w = box.w, .h = m.row }); 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, map.content(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; // Its own rows that show: not another window's between them, nor a row gone at rest. for (window_items) |w| if (w.item.what == .insn and w.item.window == p.item.window and w.shows > 0 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; // The row as before the advance and as after it (the pc's row, its trail, // the line numbers of the file the source shows): where the two differ, the // one crossfades to the other over the advance's middle, never in a frame. const after_side = going >= 0.5; const across: f32 = if (kind == .same and now.resting()) 1 else clamp01((going - 0.25) * 2); var line: ?u32 = null; var hangs: usize = 0; const covers = if (p.twin) covered_before > 0 else covered > 0; for ([2]bool{ !after_side, after_side }) |side| { const ran_s = if (side) ran_after else ran_before; const cur_s = rec.shown[now.marks[@intFromBool(side)]]; const line_s = if (row.outside or row.src != cur_s.src) 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 (side) .current else .ahead) else if (p.new == null or p.new.?.state != .current) (if (!side) .current else .ahead) else .current, .waiting => .{ .waiting = p.item.at }, .pass => .{ .ran = .{ .k = 0, .at = p.item.at } }, .plain => if (ranOf(ran_s, row.addr)) |r| .{ .ran = r } else .ahead, }; // The side the advance is on draws in full where the two are the same. const main = side == after_side; const other_line = if (row.outside or row.src != rec.shown[now.marks[@intFromBool(!side)]].src) null else row.line; const ran_o = if (!side) ran_after else ran_before; const same = std.meta.eql(line_s, other_line) and cur_s.line == rec.shown[now.marks[@intFromBool(!side)]].line and p.item.state != .current and std.meta.eql(ranOf(ran_s, row.addr), ranOf(ran_o, row.addr)); const alpha: f32 = if (same) (if (main) 1 else 0) else if (side) across else 1 - across; if (main) line = line_s; if (alpha <= 0) continue; const vs = v.faded(alpha); const base_s: usize = if (side) 0 else 1; // The marks at the row's left: the trail, the ring, the pass. switch (p.item.state) { .plain => if (ranOf(ran_s, row.addr)) |r| vs.trail(c.mark, y, r.k), .pass => vs.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(114)) / f(12)) else 1) else if (kind == .down) clamp01((tm - f(84)) / f(12)) else 1; ringAt(vs.faded(ring), y); if (ring < 1) vs.faded(1 - ring).trail(c.mark, y, 0); }, .current => {}, } // A row drawn twice (crossfading) counts once for the arguments that hang over the rows under it. const h = dd.insn(vs, now, row, y, map.content(box.w), widen0 + wide, line_s, line_s != last_line, cur_s.line, lead, state, base_s, covers, .{ addrs[0], addrs[n -| 1] }, null); if (main) hangs = h; const w = @min(p.item.window, rules.len - 1); if (rules[w] == null) rules[w] = graph.Rules.init(u.f.scratch, rec, now.marks, .{ row.addr, row.addr }, going); rules[w].?.draw(vs, row.addr, y, map.content(box.w), !covers and !row.outside and !dd.noted(vs, now, row, y, state, base_s, .{ addrs[0], addrs[n -| 1] }, null)); } runs.add(line != null and line.? == current_line, y, y + m.row); if (!p.twin) covered_before = covered; covered = if (p.twin) @max(covered, hangs) else @max(covered -| 1, hangs); last_line = line; map.row(.disasm, row.addr, u, .{ .x = 0, .y = y, .w = box.w, .h = m.row }); if (!p.twin) ties.anchor(u, .{ .row = row.addr }, .{ .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(96)) / f(18)), .through => clamp01((tm - f(54)) / 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) }); } // Its strip is the deepest window's function's column, that window framed on it. map.window(.disasm, deepest(after), deepest(before), cursors.glide(going)); 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 }); const floor = under orelse top + @as(f32, @floatFromInt(room -| 3)) * m.row; if (shown.kernel) ties.anchor(u, .floor, .{ .x = 0, .y = floor, .w = box.w, .h = m.row }); kernel(u, now, box, floor, pc_y[0] orelse pc_y[1]); context.veiled(u, box, now.veil); // Going down or up, the strip is another function's column: it fades through as the mark lands (24 f). map.strip(.disasm, if (kind == .same) u else u.faded(map.through(now, now.plan.travel + f(12))), box); } }; /// 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]; } /// The first and last instruction of the deepest window of code. fn deepest(l: Layout) [2]u64 { var window: u8 = 0; for (l.items) |it| if (it.what == .insn) { window = @max(window, it.window); }; var out = [2]u64{ std.math.maxInt(u64), 0 }; for (l.items) |it| if (it.what == .insn and it.window == window) { out = .{ @min(out[0], it.key), @max(out[1], 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; var deepest_rows = if (kept.len == 1) room else if (in_stub) @min(remaining, stubRows(rec, i, pc)) else remaining; const extra = remaining -| deepest_rows; // The nearest caller takes the rows the deepest does not use, all above // its call row: it keeps one row after the call, so the callee's head is // directly under its return row. Where its function starts first, what // is left goes back to the deepest window. var nearest_rows: usize = 3 + extra; if (kept.len >= 2 and kept[kept.len - 2].kind == .caller) { const above = disasm.listingAt(u, rec, i, kept[kept.len - 2].at, nearest_rows, nearest_rows - 2).pc; const short = nearest_rows - 2 - above; nearest_rows -= short; deepest_rows += short; } 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 = headKey(l.name), .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 => if (nearest) nearest_rows else 3, .pass => 1, .deepest => deepest_rows, }; const above: usize = switch (l.kind) { .caller => count - 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; } /// The call this step crosses with, where it was stepped over (the step /// began on a call to libc's wrapper, not on the `syscall` itself). fn steppedOver(now: cursors.Now) ?Recording.Syscall { if (!now.crossings or !now.walking()) return null; const made = syscalls.inStep(now) orelse return null; return if (isSyscall(now.rec, now.stops[1], now.rec.register(now.stops[1], "rip"))) null else made; } 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; // Its source, where the build gave it: the program's own file, or the library's (its entry's: not the header a line of it is inlined from). const entry = if (@import("ztrace").telescope.function(rec.moment(i), l.at)) |fun| fun.start else l.at; if (rec.instruction(i, entry, &buf)) |here| if (here.line != null) return if (here.src == 0) rec.file else u.print("{s} \u{00b7} {s}", .{ module, rec.sources[here.src].name() }); 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, y0: f32, 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.in(now, made); const tm = now.time; 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.glide(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); } }