//! `disasm` (design/README.md, "3. Panels"): seventeen `insn`s in address //! order, the pc's, eight above and eight below (eleven as the lens's //! subject): pwndbg's way, each instruction and what its operands are now. //! Rows above the pc are the function's own; near its start there are //! fewer and the pc's row sits higher. Past the function's end the rows //! are `outside`. The rows that ran in the last three steps are `ran`, //! with the jump lane showing how control came here. The current line's //! runs of instructions are published for the `thread`. //! Reads the recorded instructions (`zt.telescope.instruction`), each //! moment's `touch` and `branch`, and the registers. const std = @import("std"); const sk = @import("sketch"); const anim = @import("anim"); const zt = @import("ztrace"); 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 graph = @import("graph.zig"); const Stage = @import("stage.zig").Stage; const theme = ui.theme; const time = theme.time; const Rect = ui.Rect; const t = theme.color.text; const m = theme.metric.context; const c = theme.metric.insn; const size = theme.size.mono.context; const adv = size * 3 / 5; /// An instruction in the window. pub const Insn = struct { addr: u64, len: u8, text: []const u8, /// Past the function's end. outside: bool = false, /// The line it was compiled from, of `src` (`Recording.sources`). line: ?u32 = null, src: u16 = 0, /// A direct call's callee's parameter count. params: ?u8 = null, /// A graph's row: its block's head carries the address, the row its offset. bare: bool = false, /// Its mnemonic, with a prefix that is part of it (`rep stosq`). pub fn mnemonic(i: Insn) []const u8 { 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 { return std.mem.trim(u8, i.text[i.mnemonic().len..], " "); } }; /// The window at a moment: the instructions, and which is the pc's. 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, /// On the map its box is as long as what it shows (not where it is a strip's column alone). measures: bool = true, /// Its window this many rows whatever its box (a `pair`'s stopped run: the box shortens over its lower rows). rows: ?usize = null, /// A `pair`'s: its run's name before the function's on the tag (`plain · fill`). run: []const u8 = "", /// A `pair`'s alignment: the pc's line's first row at the window's top while /// the pc is in its upper half, so that two runs' rows of one line start level. aligned: bool = false, /// A `pair`'s stopped run, 0 to 1: the call at the pc never returned. Its /// row reads so, the plaque goes, the tag says `stopped`. stopped: ?anim.Value = null, /// 0 to 1: how much the pc's mark shows (the introduction's code arrives before its mark, II4). mark_in: ?anim.Value = null, pub fn draw(d: *const Disasm, f: *sk.Frame, placed: anim.Placed) void { const box = d.stage.box(placed, .disasm); const u = context.at(f, placed, box); const now = d.cursor.now(placed); const rec = d.cursor.rec; const room = d.rows orelse theme.layout.rowsIn(box.h); const stop = if (d.stopped) |v| placed.value(v) else 0; // The mark: it moves last, with the source's and rip. const going = now.advancing(); const from = listing(u, rec, now.marks[0], room, d.aligned); const to = listing(u, rec, now.marks[1], room, d.aligned); // On the map its box is as long as the instructions the recording has round the pc. // (Of the moment the pane shows: a continue's destination repacks the map as the pane goes there, not as it sets off.) if (ui.mapping and d.measures) map.measure(.disasm, listing(u, rec, now.marks[if (going >= 0.5) 1 else 0], theme.map.disasm_rows, false).rows.len); const pc = [2]u64{ rec.register(now.marks[0], "rip"), rec.register(now.marks[1], "rip") }; // The function's name: one that changes with the advance crossfades over it. var names: [2][]const u8 = undefined; for (pc, &names) |at_pc, *name| { const sym = rec.strings.get(at_pc) orelse ""; name.* = sym[0 .. std.mem.lastIndexOfScalar(u8, sym, '+') orelse sym.len]; if (d.run.len > 0) name.* = u.print("{s} \u{00b7} {s}", .{ d.run, name.* }); } const renamed = !std.mem.eql(u8, names[0], names[1]); const body = u.panel(box.w, box.h, "disassembly", .{ .focus = d.focus, .note = if (renamed or stop > 0) "" else names[1] }); if (renamed) { u.faded(1 - going).tagNote(box.w, names[0]); u.faded(going).tagNote(box.w, names[1]); } else if (stop > 0) { u.faded(1 - stop).tagNote(box.w, names[1]); u.faded(stop).tagNote(box.w, u.print("{s} \u{00b7} stopped", .{names[1]})); } const top = body.y + m.pad; // The rows' own room: a row going out of the window passes under the padding, its block's rule too. u.clip(.{ .x = theme.stroke.rule, .y = m.tag, .w = box.w - 2 * theme.stroke.rule, .h = box.h - m.tag - m.pad }); defer u.unclip(); // The two windows as one list, if they are of one function: the // rows scroll, whole rows, on `glide`; else what leaves has left // before what replaces it arrives. var merged: []const Insn = to.rows; var offsets = [2]f32{ 0, 0 }; var fade: f32 = 1; var shown = to; if (pc[0] != pc[1] and going < 1) { if (merge(u, from.rows, to.rows)) |both| { merged = both.rows; offsets = .{ @floatFromInt(both.from), @floatFromInt(both.to) }; } else { // On the map, for the strip, the other column as the advance starts: the strip shows where the pane goes first. const over = if (ui.mapping) going > 0 else going >= 0.5; merged = if (over) to.rows else from.rows; shown = if (over) to else from; fade = if (ui.mapping) 1 else @abs(2 * going - 1); } } const scroll = std.math.lerp(offsets[0], offsets[1], cursors.glidePixels(going, now.plan.travel, @abs(offsets[1] - offsets[0]) * m.row * u.at.scale)); const lit = if (fade < 1) u.faded(fade) else u; // Where the pc's plaque is: it slides from the row it was on to the // one it goes to (in one function), or goes out and comes in. var mark_y = top + @as(f32, @floatFromInt(shown.pc)) * m.row; var mark_shows: f32 = fade; if (pc[0] != pc[1] and going < 1 and fade >= 1) { const j = std.math.lerp(@as(f32, @floatFromInt(from.pc)) + offsets[0], @as(f32, @floatFromInt(to.pc)) + offsets[1], cursors.standard(going)); mark_y = top + (j - scroll) * m.row; } if (to.rows.len == 0) mark_shows = 0; if (d.mark_in) |v| mark_shows *= std.math.clamp(placed.value(v), 0, 1); // Which moment the current mark stands for, and the three steps before it. const base: usize = if (going >= 0.5) 0 else 1; // The line the source panel is on, in the file it shows: rows of that file carry their numbers. const current = rec.shown[now.marks[if (going >= 0.5) 1 else 0]]; // The addresses' shared digits, of the window the mark is in: they // change with the advance, not before it. const lead = blk: { var addrs: [24]u64 = undefined; var n: usize = 0; for ((if (going >= 0.5) to else from).rows) |row| if (!row.outside and n < addrs.len) { addrs[n] = row.addr; n += 1; }; break :blk ui.shared(addrs[0..n]); }; // The pc's row: gold ember across, a plaque with an ink triangle. const gold = theme.mark(.current); const out = now.fires(.disasm); if (mark_shows * (1 - stop) > 0) { const v = u.faded(mark_shows * (1 - stop)); v.current(.{ .x = theme.stroke.rule, .y = mark_y, .w = box.w - 2 * theme.stroke.rule, .h = m.row }, theme.metric.plaque.pc, out); sk.draw.polygon(u.f, &.{ .{ 20, mark_y + m.row / 2 }, .{ 10, mark_y + 6 }, .{ 10, mark_y + m.row - 6 } }, v.at.pen(.{ .fill = ui.rgb(gold.on_solid) })); ties.anchor(u, .pc, .{ .x = 0, .y = mark_y, .w = theme.metric.plaque.pc, .h = m.row }); } // `ran`: what the last three steps ran (every instruction, where the // recording is by instruction), the newest step's mark on each row, // and the moment it last ran at for its annotation. // As before the advance and as after it (`base` 1 and 0): the row crossfades between them. var rans: [2][]?Ran = undefined; for (&rans, [2]usize{ 1, 0 }) |*ran, b| { ran.* = u.f.scratch.alloc(?Ran, merged.len) catch return; @memset(ran.*, null); for (0..3) |k| { const first = now.stops[@min(b + 1 + k, now.stops.len - 1)]; const last = now.stops[b + k]; var at = last; // shortcut: a step through more than 4096 moments marks its last 4096. while (at > first and last - at < 4096) { at -= 1; const j = rowOf(merged, rec.register(at, "rip")) orelse continue; if (ran.*[j] == null) ran.*[j] = .{ .k = k, .at = at }; } } } // The jump that brought control here: the instruction just before // the pc's moment, a jump taken to it. const jumped: ?u64 = blk: { const at = now.stops[base]; if (at == 0 or at <= now.stops[base + 1]) break :blk null; const b = rec.insn_branches[at - 1] orelse break :blk null; if (b.kind != .jump or !b.taken or b.to != rec.register(at, "rip")) break :blk null; break :blk rec.register(at - 1, "rip"); }; if (to.rows.len > 0) map.window(.disasm, .{ to.rows[0].addr, to.rows[to.rows.len - 1].addr }, if (from.rows.len > 0) .{ from.rows[0].addr, from.rows[from.rows.len - 1].addr } else .{ to.rows[0].addr, to.rows[to.rows.len - 1].addr }, cursors.glide(going)); var last_line: ?u32 = null; // A source of many lines (SQLite's) has wider numbers, as wide as // its largest: what is right of them moves right by as much. const widen = rows.numberRoom(rec.most_lines); // The thread's runs: of the line the mark leaves and of the one it // goes to, each a span of rows; published sliding from the one to // the other with the advance (`threadRuns`). var runs: [2]Runs = .{ .{}, .{} }; const lines_of = [2]Recording.Shown{ rec.shown[now.marks[0]], rec.shown[now.marks[1]] }; 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); // The blocks (`graph`): a rule over each one's first row, its visits where the row has room. const rules = graph.Rules.init(u.f.scratch, rec, now.marks, pc, going); for (merged, 0..) |row, j| { const y = top + (@as(f32, @floatFromInt(j)) - scroll) * m.row; const line = if (row.outside or row.src != current.src) null else row.line; // The thread: the current line's runs of instructions. for (&runs, lines_of) |*r, of| r.add(!row.outside and row.line != null and row.line.? == of.line and row.src == of.src and mark_shows >= 1, @max(y, top), @min(y, box.h - m.pad)); // A row wholly above the body (the window it scrolls from or to) // does not take the line number from the first row shown. const above_body = y + m.row <= top + 0.5; if (y + m.row < m.tag or y > box.h) { last_line = if (above_body) null else line; covered -|= 1; continue; } map.row(.disasm, row.addr, u, .{ .x = 0, .y = y, .w = box.w, .h = m.row }); ties.anchor(u, .{ .row = row.addr }, .{ .x = 0, .y = y, .w = box.w, .h = m.row }); const is_pc = row.addr == pc[if (going >= 0.5) 1 else 0]; // The row as before the advance and as after it (its state, its trail, its // line number, the moment its annotation reads): where they differ, the one // crossfades to the other over the advance's middle, at a run over the whole // advance (the run's ease, 8 f, as a dump's values), never in a frame. const across: f32 = if (now.resting()) 1 else if (now.plan.gait == .run) going else std.math.clamp((going - 0.25) * 2, 0, 1); var hangs: usize = 0; for ([2]usize{ 1, 0 }) |b| { const cur_s = rec.shown[now.marks[1 - b]]; const line_s = if (row.outside or row.src != cur_s.src) null else row.line; const pc_s = row.addr == pc[1 - b]; const was_s = if (pc_s) null else rans[1 - b][j]; const state: State = if (pc_s) .current else if (was_s) |r| .{ .ran = r } else .ahead; const main = b == base; const o = 1 - b; const cur_o = rec.shown[now.marks[1 - o]]; const line_o = if (row.outside or row.src != cur_o.src) null else row.line; const pc_o = row.addr == pc[1 - o]; const same = pc_s == pc_o and (!pc_s or now.marks[1 - b] == now.marks[1 - o]) and std.meta.eql(line_s, line_o) and cur_s.line == cur_o.line and std.meta.eql(was_s, if (pc_o) null else rans[1 - o][j]); const alpha: f32 = if (same) (if (main) 1 else 0) else if (b == 0) across else 1 - across; if (alpha <= 0) continue; // A stopped run's call (`stopped`): the row as run, `never returned`, crossfading from the pc's. const gone: f32 = if (pc_s) stop else 0; if (gone > 0) { const ran: Ran = .{ .k = 0, .at = now.marks[1 - b] }; lit.faded(alpha * gone).trail(c.mark, y, ran.k); _ = d.insn(lit.faded(alpha * gone), now, row, y, map.content(box.w), widen, line_s, line_s != last_line, cur_s.line, lead, .{ .ran = ran }, b, covered > 0, window, echo); } const v = lit.faded(alpha * (1 - gone)); if (was_s) |r| v.trail(c.mark, y, r.k); const h = d.insn(v, now, row, y, map.content(box.w), widen, line_s, line_s != last_line, cur_s.line, lead, state, b, covered > 0, window, echo); if (main) hangs = h; rules.draw(v, row.addr, y, map.content(box.w), covered == 0 and !row.outside and !d.noted(v, now, row, y, state, b, 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; if (is_pc) lanes[1] = y; } const end_y = @min(top + (@as(f32, @floatFromInt(merged.len)) - scroll) * m.row, box.h - m.pad); for (&runs) |*r| r.add(false, end_y, end_y); threadRuns(u, box.w, runs, if (std.meta.eql(lines_of[0], lines_of[1])) 1 else cursors.standard(going)); if (lanes[0] != null and lanes[1] != null and lanes[0].? != lanes[1].?) { const ya = lanes[0].? + m.row / 2; const yb = lanes[1].? + m.row / 2; lit.route(&.{ .{ 38, ya }, .{ c.jump_lane, ya }, .{ c.jump_lane, yb }, .{ 39, yb } }, theme.color.trail[0], .{ .width = theme.stroke.rule, .head = .{ 7, 8 }, .radius = 4 }); } context.veiled(u, box, now.veil); // A window going to another column (another function): its strip goes over // as the advance starts (the strip's drawings are 6 f apart: the column going over is a 6 f crossfade on it, ahead of the pane's fade.) map.strip(.disasm, u, box); } 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`. 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 /// begin to fit (never left of its column), and are cut only there, /// 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. 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_; // Right of the line's column, all of it moved by `widen`. const u = at.moved(widen, 0); const room = w - m.side - widen; if (row.outside) { // The function ends: a rule, and the next one's name. u.fill(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = theme.stroke.rule }, theme.color.rule); _ = 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 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) annotationColumn() else x) - gap - c.operands, t.faint); u.text(.mono, size, x, base_y, name, t.faint); return 0; } if (!row.bare) _ = at.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(code_ink), .lead = lead }); // `tied`: the row the step's touch (or carry) leaves from, its right rule, for the ties. if (!ui.mapping and now.annotation == .tied and now.walking() and (now.plan.touch >= 0 or now.plan.carry >= 0)) if (touchPc(rec, now)) |pc| if (pc == row.addr) { const a = at.at.xf.apply(.{ w + theme.strip.cost, y }); const b = at.at.xf.apply(.{ w + theme.strip.cost, y + m.row }); ties.of(at.f).touch_row = .{ a[0], a[1], b[0], b[1] }; }; if (first_of_line) if (line) |l| { const num = u.print("{d}", .{l}); 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); }; // 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, annotationColumn(), 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 the operands give way. const ops = shorn(u, row); const stub = if (target(row)) |to| (if (d.never(now, row, state, base)) bareName(u, rec, to) else pltName(u, rec, to)) else ""; var x = room + gap; if (need.drawn) x = annotationX(operandsWidth(u, row, ops, stub), room, need.end - annotationColumn()); operands(u, row, ops, stub, base_y, (if (covered) @min(x, annotationColumn()) else x) - gap - c.operands, if (pad) t.faint else theme.color.code.plain); // Its annotation column holds the arguments of a call above: its own gives way. return if (need.drawn and !covered) d.annotation(u, now, row, y, x, room, state, base, window, echo).hangs else 0; } /// A stopped run's call that has run and not come back (`stopped`, mock 38). fn never(d: *const Disasm, now: cursors.Now, row: Insn, state: State, base: usize) bool { if (d.stopped == null or state != .ran or !std.mem.eql(u8, row.mnemonic(), "call")) return false; return returned(d.cursor.rec, row, state.ran.at, now.stops[base]) == null; } /// Whether `row` has an annotation: where it has none, its block's visits may be ranged right. pub fn noted(d: *const Disasm, u: ui.Ui, now: cursors.Now, row: Insn, y: f32, state: State, base: usize, window: [2]u64, echo: ?Echo) bool { return d.annotation(u.faded(0), now, row, y, annotationColumn(), std.math.inf(f32), state, base, window, echo).drawn; } 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`). pub 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, window: [2]u64, echo: ?Echo) Note { const rec = d.cursor.rec; const base_y = rows.baseline(y); const code_ink = theme.color.region.code_; const moment, var after = switch (state) { // The moment the mark stands for (at a sprint it waits at a // phrase's end while the steps go on): the pc's row is its. .current => blk: { const marked = now.marks[if (base == 0) 1 else 0]; break :blk .{ marked, if (base == 1 and marked == now.stops[1]) now.stops[0] else null }; }, .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 => { // 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 (struck with rax while the step that stepped over it plays). if (state == .ran) if (returned(rec, row, moment, now.stops[base])) |back| { if (now.plan.result >= 0 and state.ran.at == now.stops[1]) return a.returning(row, b.to, moment, rec.register(back, "rax"), now.register(cursors.rax_index, 0)); return a.said(a.cForm(row, b.to, moment, rec.register(back, "rax"), a.room - a.x), t.primary); }; // A call stepped over (`Plan.result`, design/motion.md "A call stepped over"): its // callee and its arguments hanging under it, framed as read from 18 f; then, as rax // strikes, its C form and its result, struck with it, the hanging rows going (6 f). if (now.plan.result >= 0 and state == .current and !now.resting()) if (returned(rec, row, moment, now.stops[0])) |back| { const k = std.math.clamp((now.time - now.plan.at[0]) / (6.0 / 60.0), 0, 1); var note: Note = .{}; if (k < 1) { const before: Say = .{ .u = u.faded(1 - k), .rec = rec, .y = y, .x = x, .room = room }; note = before.callee(b.to, moment); note.hangs = before.arguments(row, b.to, moment); const framed = std.math.clamp((now.time - 18.0 / 60.0) / (6.0 / 60.0), 0, 1) * (1 - k); for (carriers[0..note.hangs], 1..) |reg, j| { const v = rec.register(moment, reg); const shown = ui.Value.of(v, rows.regionOf(rec.moment(moment), v) != .none); u.read(.{ .x = x + 4 * adv, .y = y + @as(f32, @floatFromInt(j)) * m.row, .w = shown.width(), .h = m.row }, framed); } } if (k > 0) { const struck: Say = .{ .u = u.faded(k), .rec = rec, .y = y, .x = x, .room = room }; note = struck.returning(row, b.to, moment, rec.register(back, "rax"), now.register(cursors.rax_index, 0)); } return note; }; // `tied`: a call to the program's own function in C's form (a PLT stub's callee by name, // its arguments under it), then its move of rsp, struck with rsp: `fib(4) · rsp -8`. if (now.annotation == .tied and state == .current) { const stub = pltName(u, rec, target(row).?).len > 0; var note = if (stub) a.callee(b.to, moment) else a.said(a.cForm(row, b.to, moment, null, a.room - a.x - 10 * adv), t.primary); // (The introduction walks no call: the one it shows is stepped over, rsp as it was after it.) if (!now.introduction) note.end = a.move(note.end + adv, -8, a.rspHeat(now, base), null, true); if (stub) note.hangs = a.arguments(row, b.to, moment); return note; } // A stopped run's call (`stopped`): its callee named on its address, and it never came back. if (d.never(now, row, state, base)) return a.said("never returned", t.dim); 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) note.hangs = a.arguments(row, b.to, moment); return note; }, .ret => { u.text(.mono, size, x, base_y, "\u{2192}", t.faint); const end = u.address(x + 2 * adv, base_y, b.to, .{ .ink = ui.rgb(code_ink), .name = rec.strings.get(b.to) orelse "" }); // `tied`: then its move of rsp, `· rsp +8`. if (now.annotation == .tied) return .{ .drawn = true, .end = a.move(end + adv, 8, if (state == .current) a.rspHeat(now, base) else .none, null, true) }; return .{ .drawn = true, .end = end }; }, .jump => { // 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 (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 .{}; } // `tied`: an instruction that moves rsp or rbp says the move first. if (now.annotation == .tied) if (a.stackMove(now, row, moment, after, state, base)) |note| return note; // What it left behind is shown once it has run; in the step that // makes it, it fades in from the CPU's strike (12 f), never in a frame. const appears: f32 = if (state == .current and after != null) now.moving(.cpu, 0, theme.time.quick) else 1; const value_at: ?u64 = switch (state) { .ran => after, .current => if (after != null and appears > 0) after.? else null, .ahead, .waiting => null, }; const new = Say{ .u = u.faded(appears), .rec = rec, .y = y, .x = x, .room = room }; // 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); if (value_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(new.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. // 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 = (if (value_at != null) new else 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 = new.word(x, "=", t.faint); return .{ .drawn = true, .end = rows.chain(new.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 // dump's run: an echo), or the value it leaves is struck. if (touches[0]) |touch| { // In the step that runs it: the read is this step's (an echo of // the dump's or the stack's), and a write's value after it, struck. const in_step = state == .current and base == 1; const reads = touch.how & 1 != 0; const writes = touch.how & 2 != 0; var marks: rows.Marks = .{}; var shown = rec.moment(moment); if (in_step and reads and !writes) { marks.read = 0; marks.read_shows = now.reading(.memory, 0); } if (writes) if (after) |aa| { if (state == .ran or now.landedAt(touch.addr, touch.len)) shown = rec.moment(aa); if (in_step) { marks.changed = 1; marks.changed_heat = now.written(touch.addr, touch.len, .memory, 0); } }; // `tied`: the word by its name and the value, one hop (the stack's row holds the rest). if (now.annotation == .tied) if (a.tiedWord(touch, moment, shown, marks, d.stage.first.view.h > 0 or d.stage.last().view.h > 0)) |note| return note; // Narrower than a word, it is read at its width. if (touch.len < 8) return .{ .drawn = true, .end = rows.narrow(u, x, y, shown, touch.addr, touch.len, room, marks).end }; return .{ .drawn = true, .end = rows.chain(u, x, y, shown, touch.addr, room, marks).end }; } // Only a register: a small `reg` of what it left there. const reg = written(row) orelse return .{}; const at = value_at orelse return .{}; const value = rec.register(at, reg); new.u.text(.mono, size, x, base_y, reg, t.dim); // `tied`: its first value (the registers' row has its chain, struck in the same frame); // in the introduction struck with its register (a part's bytes are struck so: `reg` `parts`). var marks: rows.Marks = .{ .most = if (now.annotation == .tied) 1 else 6 }; if (now.introduction and state == .current) if (context.index(reg)) |ri| { marks.first = now.register(ri, ties.strikeDelay(now, ri)); }; return .{ .drawn = true, .end = rows.chain(new.u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, rec.moment(at), value, room, marks).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]; } /// rsp's mark in this step, for the amount an annotation moves it by: an echo of its strike. fn rspHeat(a: Say, now: cursors.Now, base: usize) ui.Heat { _ = a; if (base != 1 or now.resting()) return .none; // The amount is new in this row: no corner of rsp's last change under it. return now.heat(now.registerAge(cursors.sp_index), null, now.since(.cpu, ties.strikeDelay(now, cursors.sp_index))); } /// `rsp -8` from `x` (after something else: `· rsp -8`): the amount /// `by` (in bytes) struck with `heat`; then, `· role` faint and its /// role, where the word it writes or reads has one. fn move(a: Say, x: f32, by: i64, heat: ui.Heat, role: ?Role, after: bool) f32 { var end = a.word(if (after) a.word(x, "\u{00b7}", t.faint) + adv else x, "rsp", t.dim); const n: u64 = @abs(by); const amount = if (n <= 9) a.u.print("{c}{d}", .{ @as(u8, if (by < 0) '-' else '+'), n }) else a.u.print("{c}0x{x}", .{ @as(u8, if (by < 0) '-' else '+'), n }); end = a.struck(end + adv, amount, heat); if (role) |r| if (r.shows > 0) { const v = a.u.faded(r.shows); const b: Say = .{ .u = v, .rec = a.rec, .y = a.y, .x = a.x, .room = a.room }; end = b.word(b.word(end + adv, "\u{00b7}", t.faint) + adv, r.name, if (r.local) t.primary else t.dim); }; return end; } /// A word's role in an annotation, and how much of it shows. const Role = struct { name: []const u8, local: bool, shows: f32 = 1 }; /// `text` at `x` in primary, marked as `heat` says (armed, struck, held): where it ends. fn struck(a: Say, x: f32, text: []const u8, heat: ui.Heat) f32 { const w = @as(f32, @floatFromInt(text.len)) * adv; var ink: ui.Ink = .{ .ink = ui.rgb(t.primary) }; if (a.u.written(.{ .x = x, .y = a.y, .w = w, .h = m.row }, heat)) |s| ink = s; a.u.text(ink.face, size, x, rows.baseline(a.y), text, ink.ink); return x + w; } /// Under `tied` (design/README.md, `insn`, "moves rsp or rbp"): the move /// in its own terms, first, its amount struck with rsp's strike: `rsp -8 /// · saved rbp` (a `push`; its word's role once the step has made it), /// `rsp +8 · saved rbp` (a `pop`), `rsp +0x20 · saved rbp` (a `leave`), /// `rsp -0x18 3 words` (`sub`, `add`), `rbp = rsp` (and its value, /// struck as rbp lands). Null for any other instruction. fn stackMove(a: Say, now: cursors.Now, row: Insn, moment: u64, after: ?u64, state: Disasm.State, base: usize) ?Disasm.Note { const mn = row.mnemonic(); const ops = row.operands(); const eql = std.mem.eql; const regs = a.rec.registers[@min(moment, a.rec.end())]; const heat = if (state == .current) a.rspHeat(now, base) else ui.Heat.none; var by: i64 = 0; var touched: ?u64 = null; var word_at = moment; var counts = false; if (eql(u8, mn, "push")) { by = -8; touched = regs.rsp -% 8; // The word it makes has its role at the push's own stop (a recording that says so); // else the moment after's, arriving with the touch. if (wordName(a.u, a.rec, moment, regs.rsp -% 8, 8) == null) if (after) |aa| { word_at = aa; }; } else if (eql(u8, mn, "pop")) { by = 8; touched = regs.rsp; } else if (eql(u8, mn, "leave")) { by = @bitCast(regs.rbp +% 8 -% regs.rsp); touched = regs.rbp; } else if ((eql(u8, mn, "sub") or eql(u8, mn, "add")) and std.mem.startsWith(u8, ops, "rsp, ")) { const n: i64 = @bitCast(parseImmediate(std.mem.trim(u8, ops[5..], " ")) orelse return null); by = if (eql(u8, mn, "sub")) -n else n; counts = true; } else if (eql(u8, mn, "mov") and eql(u8, ops, "rbp, rsp")) { var end = a.word(a.x, "rbp = rsp", t.primary); // Its value once rbp has landed, struck with it. const lands = ties.strikeDelay(now, cursors.bp_index); // In from rbp's strike (12 f), never in a frame. const shows: f32 = if (state == .current and after != null) now.moving(.cpu, -lands, theme.time.quick) else 1; const value_at: ?u64 = switch (state) { .ran => after, .current => if (after != null and shows > 0) after.? else null, .ahead, .waiting => null, }; const b: Say = .{ .u = a.u.faded(shows), .rec = a.rec, .y = a.y, .x = a.x, .room = a.room }; if (value_at) |v| end = b.struck(end + adv, a.u.print("{x}", .{a.rec.register(v, "rbp")}), if (state == .current and base == 1) now.heat(now.registerAge(cursors.bp_index), null, now.since(.cpu, lands)) else .none); return .{ .drawn = true, .end = end }; } else return null; var role: ?Role = null; if (touched) |w| if (wordName(a.u, a.rec, word_at, w, 8)) |named| { role = .{ .name = named.name, .local = named.local }; // A push's word arrives with the touch's landing (12 f), never in a frame. if (word_at != moment and state == .current and !now.resting() and now.plan.touch >= 0) role.?.shows = std.math.clamp((now.time - now.plan.touch - theme.time.tied.touch) / theme.time.quick, 0, 1); }; var end = a.move(a.x, by, heat, role, false); if (counts) end = a.word(end + 2 * adv, a.u.print("{d} words", .{@abs(by) / 8}), t.faint); return .{ .drawn = true, .end = end }; } /// Under `tied` (design/README.md, `insn`, and its fallbacks), a word of /// memory the instruction reads or writes: a stack word by its name, bold /// in the stack's ink (an unnamed one by its address), and the value it /// holds at the access's width, one hop: `next → 405010`, `n ◂ 15`, /// `7fffffffecd0 ◂ 1`; a word a view on screen shows (`view`), its /// address and one hop, `405038 → 405010`. The name (or address) framed /// as read in the step, a write's value struck. Null for a word no pane /// shows: the whole chain stands. fn tiedWord(a: Say, touch: Recording.Touch, moment: u64, shown: Recording.Moment, marks: rows.Marks, view: bool) ?Disasm.Note { const u = a.u; const region = rows.regionOf(a.rec.moment(moment), touch.addr); const named = if (region == .stack) wordName(u, a.rec, moment, touch.addr, touch.len) else null; // The band's view is a dump of the heap. A word no pane shows (a global) keeps its whole // chain, its data name in place of the address where it has one (`head → 405050 ◂ 9`). if (region != .stack and !(view and region == .heap)) return a.globalWord(touch, moment, shown, marks); const base_y = rows.baseline(a.y); const mid = a.y + m.row / 2; var x = a.x; const w = if (named) |n| @as(f32, @floatFromInt(n.name.len)) * adv else ui.Value.of(touch.addr, true).width(); if (marks.read == 0) u.read(.{ .x = x, .y = a.y, .w = w, .h = m.row }, marks.read_shows); if (named) |n| u.text(.mono_bold, size, x, base_y, n.name, rows.ink(.stack)) else _ = u.address(x, base_y, touch.addr, .{ .ink = ui.rgb(rows.ink(region)) }); x += w; const len: usize = @intCast(@min(touch.len, 8)); var raw: [8]u8 = @splat(0); var known: [8]bool = @splat(false); shown.read(touch.addr, raw[0..len], known[0..len]) catch return .{ .drawn = true, .end = x }; if (std.mem.indexOfScalar(bool, known[0..len], false) != null) { x = u.arrow(x, mid, .points); u.unknown(.{ .x = x, .y = a.y, .w = 24, .h = m.row }); return .{ .drawn = true, .end = x + 24 }; } const v = std.mem.readInt(u64, &raw, .little); const pointer = len == 8 and rows.regionOf(shown, v) != .none; x = u.arrow(x, mid, if (pointer) .points else .holds); // The value, its first hop alone (a code address with its name), cut with `…` where the row ends; a write's struck. return .{ .drawn = true, .end = rows.chain(u, x, a.y, shown, v, a.room, .{ .first = if (marks.changed == 1) marks.changed_heat else .none, .most = 1 }).end }; } /// Under `tied`, a word no pane shows: its whole chain with its data /// name (`head`, `big+4096`) in place of its address, bold in its /// region's ink, read in the step; a write's value struck. Null where it /// has no name (the chain as `whole` draws it). fn globalWord(a: Say, touch: Recording.Touch, moment: u64, shown: Recording.Moment, marks: rows.Marks) ?Disasm.Note { if (touch.len != 8) return null; const full_name = ui.symbol(a.u, a.rec.strings.get(touch.addr) orelse return null); // `head+0` is `head`. const name = if (std.mem.endsWith(u8, full_name, "+0")) full_name[0 .. full_name.len - 2] else full_name; const u = a.u; const w = @as(f32, @floatFromInt(name.len)) * adv; if (marks.read == 0) u.read(.{ .x = a.x, .y = a.y, .w = w, .h = m.row }, marks.read_shows); u.text(.mono_bold, size, a.x, rows.baseline(a.y), name, rows.ink(rows.regionOf(a.rec.moment(moment), touch.addr))); const v = (Recording.word(shown, touch.addr, 8) catch null) orelse return .{ .drawn = true, .end = a.x + w }; const x = u.arrow(a.x + w, a.y + m.row / 2, if (rows.regionOf(shown, v) != .none) .points else .holds); return .{ .drawn = true, .end = rows.chain(u, x, a.y, shown, v, a.room, .{ .first = if (marks.changed == 1) marks.changed_heat else .none }).end }; } /// A call that has run, in C's form with its result struck as `heat` says (rax's: an echo). fn returning(a: Say, row: Insn, to: u64, moment: u64, value: u64, heat: ui.Heat) Disasm.Note { const back = resultText(a.u, a.rec, moment, value); var end = a.word(a.x, a.cForm(row, to, moment, null, a.room - a.x - @as(f32, @floatFromInt(back.len + 3)) * adv), t.primary); end = a.word(end, " = ", t.primary); return .{ .drawn = true, .end = a.struck(end, back, heat) }; } /// 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 = a.argumentRows(row, to, moment); 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| @backingInt(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; } /// How many argument rows hang under a call to `to`. fn argumentRows(a: Say, row: Insn, to: u64, moment: u64) usize { const name = a.functionName(to, moment); return @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); } /// 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| @backingInt(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} = {s}", .{ out, resultText(u, a.rec, moment, 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 }; } }; /// The pc of the instruction a step's touch leaves from (`cursors.stackTouch`), kept for the step. var touch_memo: struct { rec: ?*const Recording = null, from: u64 = 0, to: u64 = 0, pc: ?u64 = null } = .{}; fn touchPc(rec: *const Recording, now: cursors.Now) ?u64 { if (touch_memo.rec != rec or touch_memo.from != now.stops[1] or touch_memo.to != now.stops[0]) { const tt = cursors.stackTouch(rec, now.stops[1], now.stops[0]); touch_memo = .{ .rec = rec, .from = now.stops[1], .to = now.stops[0], .pc = if (tt) |x| rec.register(x.at, "rip") else null }; } return touch_memo.pc; } /// A stack word's name under `tied`, its role at moment `i` (a local's /// name, primary; `saved rbp`, `argv[0]`, dim), for an access of `len` /// bytes at `addr`; null where it has none, or where the local the word is /// named by does not hold those bytes (two locals in a word: never a guess). fn wordName(u: ui.Ui, rec: *const Recording, i: u64, addr: u64, len: u64) ?struct { name: []const u8, local: bool } { const regs = rec.registers[@min(i, rec.end())]; var one: [1]zt.telescope.Slot = undefined; const word = addr & ~@as(u64, 7); const got = zt.telescope.slots(rec.moment(i), ®s, word, &one) catch return null; if (got.len == 0) return null; return switch (got[0].role) { .none, .return_address => null, // Of the locals that share the word (`Slot.also`), the one the access is to. .local => |first| for ([_]?zt.telescope.Local{first} ++ got[0].also) |maybe| { const l = maybe orelse continue; const at = word -% @as(u64, @bitCast(@as(i64, l.offset))); if (if (l.size > 0) addr >= at and addr + len <= at + l.size else addr == at) break .{ .name = l.name, .local = true }; } else null, else => |role| .{ .name = context.Stack.roleName(u, role, (Recording.word(rec.moment(i), addr & ~@as(u64, 7), 8) catch null) orelse 1).name, .local = false }, }; } /// How many rows of arguments hang under `row` while it is current at /// `moment`: a direct call's, a `syscall`'s; 0 for anything else. pub fn hanging(u: ui.Ui, rec: *const Recording, row: Insn, moment: u64) usize { const a: Say = .{ .u = u, .rec = rec, .y = 0, .x = 0, .room = 0 }; if (std.mem.eql(u8, row.mnemonic(), "syscall")) return @min(zt.syscalls.signature(rec.register(moment, "rax")).len, 6); const b = rec.insn_branches[moment] orelse return 0; if (b.kind != .call or target(row) == null) return 0; return a.argumentRows(row, b.to, moment); } /// 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; } /// A call's result as a caller reads it: an address in hex, as the chains write it; else signed, in decimal. fn resultText(u: ui.Ui, rec: *const Recording, moment: u64, r: u64) []const u8 { if (rows.regionOf(rec.moment(moment), r) != .none) return u.print("{x}", .{r}); return u.print("{d}", .{@as(i64, @bitCast(r))}); } /// 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; } /// An explicit 64-bit address, using registers only at this moment's PC. fn operandAddress(row: Insn, regs: zt.Regs) ?u64 { const ops = row.operands(); if (row.padding() or std.mem.eql(u8, row.mnemonic(), "pop")) return null; // shortcut: segment overrides and address-size overrides stay inert; add them when needed. if (std.mem.indexOfScalar(u8, ops, ':') != null) return null; const open = std.mem.indexOfScalar(u8, ops, '[') orelse return null; const close = std.mem.indexOfScalarPos(u8, ops, open, ']') orelse return null; if (std.mem.indexOfScalarPos(u8, ops, close + 1, '[') != null) return null; var rest = std.mem.trim(u8, ops[open + 1 .. close], " "); if (rest.len == 0) return null; var result: u64 = 0; var subtract = false; while (rest.len > 0) { const end = std.mem.indexOfAny(u8, rest, "+-") orelse rest.len; const term = std.mem.trim(u8, rest[0..end], " "); const star = std.mem.indexOfScalar(u8, term, '*') orelse term.len; const name = std.mem.trim(u8, term[0..star], " "); const value = if (std.mem.eql(u8, name, "rip")) row.addr +% row.len else if (full(name)) |reg| blk: { if (row.addr != regs.rip or !std.mem.eql(u8, name, reg)) return null; break :blk regs.named(reg) orelse return null; } else parseImmediate(name) orelse return null; const scale = if (star < term.len) blk: { if (full(name) == null) return null; const n = parseImmediate(std.mem.trim(u8, term[star + 1 ..], " ")) orelse return null; if (n != 1 and n != 2 and n != 4 and n != 8) return null; break :blk n; } else @as(u64, 1); result = if (subtract) result -% (value *% scale) else result +% (value *% scale); if (end == rest.len) return result; subtract = rest[end] == '-'; rest = std.mem.trim(u8, rest[end + 1 ..], " "); } return null; } /// `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. pub 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()); } /// Where an annotation starts: 564 on the map, 540 in a pane with a strip. fn annotationColumn() f32 { return if (ui.mapping) c.annotation else c.annotation - theme.strip.cost / 2; } /// 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. pub const Runs = struct { spans: [8][2]f32 = undefined, n: usize = 0, open: ?f32 = null, 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) { r.spans[r.n] = .{ y0, end }; r.n += 1; } r.open = null; }; } }; /// 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. 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) { const shown = if (p >= 0.5 or from.n == 0) to else from; for (shown.spans[0..shown.n], 0..) |span, k| ties.anchor(u, .{ .run = k }, .{ .x = 0, .y = span[0], .w = w, .h = span[1] - span[0] }); return; } for (0..@max(from.n, to.n)) |k| { const a = from.spans[@min(k, from.n - 1)]; const b = to.spans[@min(k, to.n - 1)]; const y0 = std.math.lerp(a[0], b[0], p); ties.anchor(u, .{ .run = k }, .{ .x = 0, .y = y0, .w = w, .h = std.math.lerp(a[1], b[1], p) - y0 }); } } /// Where an annotation `need` wide goes in a row that ends at `room`, /// after operands `width` wide: at its column, or a character after the /// operands, or (when both do not fit) where it just fits. fn annotationX(width: f32, room: f32, need: f32) f32 { return @max(annotationColumn(), @min(c.operands + width + gap, room - need)); } /// The row in `rows` (in address order) of the instruction at `addr`. fn rowOf(list: []const Insn, addr: u64) ?usize { var lo: usize = 0; var hi: usize = list.len; while (lo < hi) { const mid = (lo + hi) / 2; if (list[mid].addr < addr) lo = mid + 1 else hi = mid; } return if (lo < list.len and list[lo].addr == addr) lo else null; } /// Whether the step from moment `i` to `after` ran the instruction `row` /// alone: the moment after it is at the next instruction, or where it jumped. fn alone(rec: *const Recording, i: u64, after: u64, row: Insn) bool { if (after != i + 1) return false; const next = rec.register(after, "rip"); if (next == row.addr + row.len) return true; if (rec.insn_branches[i]) |b| return b.to == next; return false; } /// A jump's or a call's target, when the disassembler wrote it as one. 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; } /// 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 { _ = u.address(c.address, rows.baseline(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. bareRow(u.moved(@as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv, 0), row, y); } /// The same instruction atoms for a live debugger: one moment, without /// indexing an animation's entire recording. Only observed operands are annotated. pub fn liveRow(at: ui.Ui, row: Insn, y: f32, width: f32, moment: Recording.Moment, regs: zt.Regs, options: struct { compact: bool = false, current: bool = false, executed: bool = false, lead: usize = 0, touch: ?Recording.Touch = null, branch: ?Recording.Branch = null, heat: ui.Heat = .none, }) void { const base_y = rows.baseline(y); if (options.compact) { at.text(.mono, size, c.address, base_y, at.print("…{x:0>4}", .{row.addr & 0xffff}), theme.color.region.code_); at.hitAddress(row.addr, .{ .x = c.address, .y = y, .w = 5 * adv, .h = 24 }); } else _ = at.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(theme.color.region.code_), .lead = options.lead }); const shift: f32 = if (options.compact) -64 else @as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv; const u = at.moved(shift, 0); const room = width - shift - m.side; const pad = row.padding(); const mn = row.mnemonic(); if (!options.compact) if (row.line) |line| u.text(.mono, size, c.line, base_y, u.print("{d}", .{line}), t.faint); u.text(.mono_bold, size, c.mnemonic, base_y, mn, if (pad) t.faint else theme.color.code.keyword); var name_buf: [192]u8 = undefined; const name = if (target(row)) |to| (moment.string(to, &name_buf) catch null) orelse "" else ""; const annotated = options.current or options.executed; var ops = shorn(u, row); ops.address = operandAddress(row, regs); operands(u, row, ops, name, base_y, (if (annotated) annotationColumn() else room) - gap - c.operands, if (pad) t.faint else t.primary); if (!annotated) return; var x = annotationColumn(); if (options.branch) |branch| { const label = switch (branch.kind) { .call => "call", .ret => "return", .jump => if (branch.taken) "taken" else "not taken", .none => "", }; u.text(.mono, size, x, base_y, label, if (branch.taken) t.primary else t.dim); x += u.width(.mono, size, label) + adv; if (branch.kind == .jump and flagsRead(mn) != 0) { _ = flags(u, x, y, regs.eflags, flagsRead(mn), if (options.current) 1 else 0); } else { _ = rows.chain(u, x, y, moment, branch.to, room, .{ .most = 1 }); } return; } if (options.touch) |touch| { const label: []const u8 = if (touch.how == 1) "read" else if (touch.how == 2) "write" else "read/write"; u.text(.mono, size, x, base_y, label, t.dim); x += u.width(.mono, size, label) + adv; const marks: rows.Marks = .{ .read = if (options.current and touch.how & 1 != 0) 0 else null, .read_shows = 1 }; if (touch.len < 8) _ = rows.narrow(u, x, y, moment, touch.addr, touch.len, room, marks) else _ = rows.chain(u, x, y, moment, touch.addr, room, marks); return; } if (options.executed) { const reg = written(row) orelse return; u.text(.mono, size, x, base_y, reg, t.dim); _ = rows.chain(u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, moment, regs.named(reg).?, room, .{ .first = options.heat }); return; } // Register operands at the current instruction, using their real width. var words = std.mem.tokenizeAny(u8, row.operands(), " ,[]*+-:"); var seen: ?[]const u8 = null; while (words.next()) |word| { const reg = full(word) orelse continue; if (seen) |previous| if (std.mem.eql(u8, reg, previous)) continue; const raw = regs.named(reg) orelse continue; const value = number(u, if (word.len == 2 and word[1] == 'h') raw >> 8 else raw, registerSize(word) orelse 8); const text = u.print("{s} {s}", .{ word, value }); const w = u.width(.mono, size, text); if (x + w > room) break; u.text(.mono, size, x, base_y, word, t.dim); u.text(.mono, size, x + @as(f32, @floatFromInt(word.len + 1)) * adv, base_y, value, t.primary); x += w + 2 * adv; seen = reg; } } /// Its mnemonic and operands alone, at their columns (a graph's row, whose head carries the address). pub fn bareRow(u: ui.Ui, row: Insn, y: f32) void { const base_y = rows.baseline(y); const pad = row.padding(); u.text(.mono_bold, size, c.mnemonic, base_y, row.mnemonic(), if (pad) t.faint else theme.color.code.keyword); operands(u, row, shorn(u, row), "", base_y, annotationColumn() - gap - c.operands, if (pad) t.faint else theme.color.code.plain); } /// 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, address: ?u64 = null }; 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(); 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 stub = bareName(u, rec, to); return if (std.mem.endsWith(u8, stub, "@plt")) stub else ""; } /// The function at `to`, by name ("" where it has none). fn bareName(u: ui.Ui, rec: *const Recording, to: u64) []const u8 { const name = ui.symbol(u, rec.strings.get(to) orelse return ""); return name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len]; } /// 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| { const end = u.address(c.operands, base_y, to, .{ .ink = ui.rgb(theme.color.region.code_) }); const remaining = c.operands + width - end - 10; if (stub.len > 0 and remaining >= adv) u.text(.mono, size, end + 10, base_y, rows.fitted(u, ui.symbol(u, stub), remaining), t.primary); return; } const text = ops.text; var shown: usize = 0; defer if (ops.address) |address| { const open = std.mem.indexOfScalar(u8, text, '[').?; const close = std.mem.indexOfScalarPos(u8, text, open, ']').?; if (close < shown) u.hitAddress(address, .{ .x = c.operands + @as(f32, @floatFromInt(open)) * adv, .y = base_y - rows.baseline(0), .w = @as(f32, @floatFromInt(close + 1 - open)) * adv, .h = m.row }); }; 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) { shown = text.len; 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; } 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 text[cut - 1] == ' ') cut -= 1; shown = cut; 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 /// (Intel syntax: the first operand is where it goes). fn written(row: Insn) ?[]const u8 { const mn = row.mnemonic(); for ([_][]const u8{ "cmp", "test", "push", "nop", "endbr64", "call", "ret", "leave", "hlt", "syscall", "ud2", "int3" }) |none| if (std.mem.eql(u8, mn, none)) return null; if (mn[0] == 'j' or std.mem.startsWith(u8, mn, "cmov") and false) return null; const ops = row.operands(); const dest = ops[0 .. std.mem.indexOfScalar(u8, ops, ',') orelse ops.len]; return full(std.mem.trim(u8, dest, " ")); } /// A register's 64-bit name, from any of its widths. fn full(name: []const u8) ?[]const u8 { const table = [_][2][]const u8{ .{ "rax", "eax" }, .{ "rbx", "ebx" }, .{ "rcx", "ecx" }, .{ "rdx", "edx" }, .{ "rsi", "esi" }, .{ "rdi", "edi" }, .{ "rbp", "ebp" }, .{ "rsp", "esp" }, }; for (table) |pair| { if (std.mem.eql(u8, name, pair[0]) or std.mem.eql(u8, name, pair[1])) return pair[0]; if (name.len == 2 and pair[0][1] == name[0] and (name[1] == 'x' or name[1] == 'l' or name[1] == 'h' or name[1] == 'i' or name[1] == 'p')) return pair[0]; } if (name.len >= 2 and name[0] == 'r' and std.ascii.isDigit(name[1])) { const digits = if (name.len >= 3 and std.ascii.isDigit(name[2])) name[0..3] else name[0..2]; for ([_][]const u8{ "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }) |r| if (std.mem.eql(u8, r, digits)) return r; } return null; } /// The window at moment `i`: up to `above` of the function's own /// 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`. /// `room` rows round the pc at moment `i`: in a pane, as many above as /// below; on the map, the function from its start where the pc is in its /// first three quarters of the rows (a strip's column stays still while /// the pc walks it), else round the pc. `aligned` (a `pair`'s): no more /// rows over the pc than its line has before it, so that the line's first /// row is the window's top while the pc is in the window's upper half. fn listing(u: ui.Ui, rec: *const Recording, i: u64, room: usize, aligned: bool) Listing { const pc = rec.register(i, "rip"); if (ui.mapping) { const whole = listingAt(u, rec, i, pc, room, room * 3 / 4); if (whole.pc < room * 3 / 4) return whole; } const above = (room -| 1) / 2; if (!aligned) return listingAt(u, rec, i, pc, room, above); const l = listingAt(u, rec, i, pc, room, ofLine(rec, i, pc, above)); // Where the code ends under the pc, the window is filled from above (as far as it would be unaligned). if (l.rows.len < room and l.pc < above) return listingAt(u, rec, i, pc, room, @min(above, l.pc + room - l.rows.len)); return l; } /// How many of the `most` instructions just before `pc` are of its line (`most` where it has none). fn ofLine(rec: *const Recording, i: u64, pc: u64, most: usize) usize { var buf: [256]u8 = undefined; const here = rec.instruction(i, pc, &buf) orelse return most; const line = here.line orelse return most; const src = here.src; var back = here.back; var addr = pc; var n: usize = 0; while (n < most and back != 0) : (n += 1) { addr -= back; const one = rec.instruction(i, addr, &buf) orelse break; if (one.line == null or one.line.? != line or one.src != src) break; back = one.back; } return n; } /// 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 }; var buf: [256]u8 = undefined; var up: [theme.map.disasm_rows]Insn = undefined; var n_up: usize = 0; var addr = pc; while (n_up < @min(above, up.len)) { const here = rec.instruction(i, addr, &buf) orelse break; if (here.back == 0) break; addr -= here.back; const one = rec.instruction(i, addr, &buf) orelse break; up[n_up] = .{ .addr = addr, .len = one.len, .text = u.print("{s}", .{one.text}), .line = one.line, .src = one.src, .params = one.params }; n_up += 1; } var n: usize = 0; while (n < n_up) : (n += 1) out[n] = up[n_up - 1 - n]; const pc_row = n; addr = pc; var outside = false; while (n < room) : (n += 1) { const one = rec.instruction(i, addr, &buf) orelse break; if (n > pc_row and one.back == 0) outside = true; out[n] = .{ .addr = addr, .len = one.len, .text = u.print("{s}", .{one.text}), .outside = outside, .line = one.line, .src = one.src, .params = one.params }; addr += one.len; } return .{ .rows = out[0..n], .pc = pc_row }; } /// Two windows of one function as one list in address order, and where each begins in it. fn merge(u: ui.Ui, a: []const Insn, b: []const Insn) ?struct { rows: []const Insn, from: usize, to: usize } { if (a.len == 0 or b.len == 0) return null; const lo = if (a[0].addr <= b[0].addr) a else b; const hi = if (lo.ptr == a.ptr) b else a; // Where `hi` begins in `lo`: they must overlap. const at = for (lo, 0..) |row, k| { if (row.addr == hi[0].addr) break k; } else return null; const total = @max(lo.len, at + hi.len); const out = u.f.scratch.alloc(Insn, total) catch return null; @memcpy(out[0..lo.len], lo); if (at + hi.len > lo.len) @memcpy(out[lo.len..], hi[lo.len - at ..]); 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").?); try std.testing.expectEqualStrings("r10", full("r10d").?); try std.testing.expectEqualStrings("rax", full("al").?); try std.testing.expect(full("qword ptr [rbp - 8]") == null); } test "operand addresses use current registers, never future or past register values" { const regs: zt.Regs = .{ .rip = 0x1000, .rbp = 0x8000, .rax = 0x4000, .rcx = 3 }; for ([_]struct { []const u8, ?u64 }{ .{ "mov rax, qword ptr [rbp - 8]", 0x7ff8 }, .{ "lea rdi, [rax + rcx*8 + 0x10]", 0x4028 }, .{ "mov rax, [rip - 0x10]", 0xff7 }, .{ "mov rax, [rcx - 8]", 0xffff_ffff_ffff_fffb }, .{ "mov rax, [0x8000]", 0x8000 }, .{ "mov rax, fs:[0x28]", null }, .{ "mov rax, [eax + 8]", null }, .{ "mov rax, [rax + xmm0*8]", null }, .{ "mov rax, [rax + rcx*3]", null }, .{ "mov rax, [rax +]", null }, .{ "mov rax, [rax + unknown]", null }, .{ "pop qword ptr [rsp]", null }, .{ "nop dword ptr [rax]", null }, }) |case| try std.testing.expectEqual(case[1], operandAddress(.{ .addr = regs.rip, .len = 7, .text = case[0] }, regs)); for ([_]u64{ 0xff0, 0x1010 }) |addr| { try std.testing.expectEqual(@as(?u64, null), operandAddress(.{ .addr = addr, .len = 7, .text = "lea rdi, [rax + rcx*8]" }, regs)); try std.testing.expectEqual(@as(?u64, addr + 7 + 0x10), operandAddress(.{ .addr = addr, .len = 7, .text = "mov rax, [rip + 0x10]" }, regs)); } }