summaryrefslogtreecommitdiff
path: root/anim/src/disasm.zig
blob: e42964359c2187e3c7e5991a175f121dc5467eaa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! `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 context = @import("context.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 of the program's source it was compiled from.
    line: ?u32 = null,
    /// A direct call's callee's parameter count.
    params: ?u8 = null,

    pub fn mnemonic(i: Insn) []const u8 {
        return i.text[0 .. std.mem.indexOfScalar(u8, i.text, ' ') orelse i.text.len];
    }

    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.
const Listing = struct { rows: []Insn, pc: usize };

pub const Disasm = struct {
    cursor: cursors.Cursor,
    stage: *const Stage,
    focus: bool = false,

    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 = theme.layout.rowsIn(box.h);
        const above = (room -| 1) / 2;
        // The mark: it moves last, with the source's and rip.
        const going = now.advancing();
        const from = listing(u, rec, now.marks[0], room, above);
        const to = listing(u, rec, now.marks[1], room, above);

        const pc = [2]u64{ rec.register(now.marks[0], "rip"), rec.register(now.marks[1], "rip") };
        const name = rec.strings.get(pc[if (going >= 0.5) 1 else 0]) orelse "";
        const body = u.panel(box.w, box.h, "disassembly", .{ .focus = d.focus, .note = name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len] });
        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();

        // 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 {
                merged = if (going < 0.5) from.rows else to.rows;
                shown = if (going < 0.5) from else to;
                fade = @abs(2 * going - 1);
            }
        }
        const scroll = std.math.lerp(offsets[0], offsets[1], cursors.glide(going));
        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;

        // Which moment the current mark stands for, and the three steps before it.
        const base: usize = if (going >= 0.5) 0 else 1;
        const current_line = rec.own[now.marks[if (going >= 0.5) 1 else 0]];
        const lead = blk: {
            var addrs: [24]u64 = undefined;
            var n: usize = 0;
            for (shown.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 > 0) {
            const v = u.faded(mark_shows);
            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 });
        }

        var last_line: ?u32 = null;
        var run: usize = 0;
        var run_start: ?f32 = null;
        var lanes: [2]?f32 = .{ null, null };
        for (merged, 0..) |row, j| {
            const y = top + (@as(f32, @floatFromInt(j)) - scroll) * m.row;
            const line = if (row.outside) null else row.line;
            // The thread: the current line's runs of instructions.
            const on_line = line != null and line.? == current_line and mark_shows >= 1;
            if (on_line and run_start == null) run_start = @max(y, top);
            if (!on_line and run_start != null) {
                ties.anchor(u, .{ .run = run }, .{ .x = 0, .y = run_start.?, .w = box.w, .h = @min(y, box.h - m.pad) - run_start.? });
                run += 1;
                run_start = null;
            }
            if (y + m.row < m.tag or y > box.h) {
                last_line = line;
                continue;
            }
            // `ran`: it ran in one of the last three steps.
            var ran: ?usize = null;
            for (0..3) |k| {
                const at_k = now.stops[@min(base + 1 + k, now.stops.len - 1)];
                if (at_k != now.stops[base] and rec.register(at_k, "rip") == row.addr) {
                    ran = k;
                    break;
                }
            }
            const is_pc = row.addr == pc[if (going >= 0.5) 1 else 0];
            if (ran != null and !is_pc) lit.trail(c.mark, y, ran.?);
            d.insn(lit, now, row, y, box.w, line, line != last_line, current_line, lead, if (is_pc) .current else if (ran) |k| .{ .ran = k } else .ahead, base);
            last_line = line;
            // The jump that brought control here: from its row, up or down the lane.
            if (ran == 0 and !is_pc) if (rec.insn_branches[now.stops[base + 1]]) |b| if (b.kind == .jump and b.taken) {
                lanes[0] = y;
            };
            if (is_pc) lanes[1] = y;
        }
        if (run_start) |y0| ties.anchor(u, .{ .run = run }, .{ .x = 0, .y = y0, .w = box.w, .h = @min(top + (@as(f32, @floatFromInt(merged.len)) - scroll) * m.row, box.h - m.pad) - y0 });
        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);
    }

    const State = union(enum) { current, ran: usize, ahead };

    /// `insn`: an instruction and its annotation, pwndbg's way.
    fn insn(d: *const Disasm, u: ui.Ui, now: cursors.Now, row: Insn, y: f32, w: f32, line: ?u32, first_of_line: bool, current_line: u32, lead: usize, state: State, base: usize) void {
        const rec = d.cursor.rec;
        const base_y = rows.baseline(y);
        const code_ink = theme.color.region.code_;
        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);
            _ = u.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);
            u.text(.mono, size, c.operands, base_y, clipText(u, row.operands(), c.operand_chars), t.faint);
            if (rec.strings.get(row.addr)) |name| u.text(.mono, size, c.annotation, base_y, name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len], t.faint);
            return;
        }
        const on = state == .current;
        _ = u.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(code_ink), .lead = lead });
        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);
        };
        u.text(.mono_bold, size, c.mnemonic, base_y, row.mnemonic(), theme.color.code.keyword);
        operands(u, row, base_y);

        // The annotation: what it does, now. 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.
        const moment, var after = switch (state) {
            .current => .{ now.stops[base], if (base == 1) now.stops[0] else null },
            .ran => |k| .{ now.stops[base + 1 + k], now.stops[base + k] },
            .ahead => .{ now.stops[base], null },
        };
        if (after) |a| if (!alone(rec, moment, a, row)) {
            after = null;
        };
        const room = w - m.side;
        const x: f32 = c.annotation;
        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];
        _ = on;
        if (branch) |b| switch (b.kind) {
            .call => {
                const callee = rec.strings.get(b.to) orelse "";
                u.text(.mono, size, x, base_y, callee[0 .. std.mem.lastIndexOfScalar(u8, callee, '+') orelse callee.len], t.bright);
                // Its arguments hang under it, a small `reg` a row, as many as the prototype has.
                if (state == .current) {
                    const callee_name = callee[0 .. std.mem.lastIndexOfScalar(u8, callee, '+') orelse callee.len];
                    // As many as the callee's prototype has (the debug info's, else the source's), three when neither says.
                    const count: usize = row.params orelse for (rec.functions) |fun| {
                        if (std.mem.eql(u8, fun.name, callee_name)) break fun.params;
                    } else 3;
                    const shown_moment = rec.moment(moment);
                    const args = [_][]const u8{ "rdi", "rsi", "rdx", "rcx", "r8", "r9" };
                    for (args[0..@min(count, 6)], 1..) |reg, k| {
                        const ry = y + @as(f32, @floatFromInt(k)) * m.row;
                        u.text(.mono, size, x, rows.baseline(ry), reg, t.dim);
                        _ = rows.chain(u, x + 4 * adv, ry, shown_moment, rec.register(moment, reg), room, .{});
                    }
                }
                return;
            },
            .ret => {
                u.text(.mono, size, x, base_y, "\u{2192}", t.faint);
                _ = u.address(x + 2 * adv, base_y, b.to, .{ .ink = ui.rgb(code_ink), .name = rec.strings.get(b.to) orelse "" });
                return;
            },
            .jump => {
                // A jump always taken says nothing; a conditional one, which way.
                if (std.mem.eql(u8, row.mnemonic(), "jmp")) return;
                if (!b.taken) return u.text(.mono, size, x, base_y, "not taken", t.dim);
                u.text(.mono, size, x, base_y, "taken", t.primary);
                return;
            },
            .none => {},
        };
        if (std.mem.eql(u8, row.mnemonic(), "syscall") and state != .ahead) {
            const nr = rec.register(moment, "rax");
            u.text(.mono, size, x, base_y, zt.syscalls.name(nr) orelse "syscall", t.bright);
            const names = zt.syscalls.names(nr);
            const carriers = [_][]const u8{ "rdi", "rsi", "rdx" };
            if (state == .current) for (names[0..@min(names.len, 3)], carriers[0..@min(names.len, 3)], 1..) |arg, reg, k| {
                const ry = y + @as(f32, @floatFromInt(k)) * m.row;
                u.text(.mono, size, x, rows.baseline(ry), arg, t.dim);
                _ = rows.chain(u, x + @as(f32, @floatFromInt(arg.len + 1)) * adv, ry, rec.moment(moment), rec.register(moment, reg), room, .{});
            };
            return;
        }
        // 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) |a| {
                if (state == .ran or now.landed(.memory, 0)) shown = rec.moment(a);
                if (in_step) {
                    marks.changed = 1;
                    marks.changed_heat = now.written(touch.addr, touch.len, .memory, 0);
                }
            };
            _ = rows.chain(u, x, y, shown, touch.addr, room, marks);
            return;
        }
        // Only a register: a small `reg` of what it left there.
        const reg = written(row) orelse return;
        const value_at = switch (state) {
            .ran => after orelse return,
            .current => if (after != null and now.landed(.cpu, 0)) after.? else return,
            .ahead => return,
        };
        const value = rec.register(value_at, reg);
        u.text(.mono, size, x, base_y, reg, t.dim);
        _ = rows.chain(u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, rec.moment(value_at), value, room, .{});
    }
};

/// 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;
}

/// `text` in `chars` characters: cut at its far end, and saying so.
fn clipText(u: ui.Ui, text: []const u8, chars: usize) []const u8 {
    if (text.len <= chars) return text;
    return u.print("{s}\u{2026}", .{text[0 .. chars - 1]});
}

/// The operands, as the disassembler writes them, 24 characters; a jump's
/// or a call's target is an `address` in code's ink.
fn operands(u: ui.Ui, row: Insn, base_y: f32) void {
    const ops = row.operands();
    const mn = row.mnemonic();
    const branches = mn[0] == 'j' or std.mem.eql(u8, mn, "call");
    if (branches and std.mem.startsWith(u8, ops, "0x")) {
        if (std.fmt.parseInt(u64, ops[2..], 16)) |target| {
            _ = u.address(c.operands, base_y, target, .{ .ink = ui.rgb(theme.color.region.code_) });
            return;
        } else |_| {}
    }
    u.text(.mono, size, c.operands, base_y, clipText(u, ops, c.operand_chars), theme.color.code.plain);
}

/// 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`.
fn listing(u: ui.Ui, rec: *const Recording, i: u64, room: usize, above: usize) Listing {
    const out = u.f.scratch.alloc(Insn, room) catch return .{ .rows = &.{}, .pc = 0 };
    const pc = rec.register(i, "rip");
    var buf: [256]u8 = undefined;
    var up: [16]Insn = undefined;
    var n_up: usize = 0;
    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, .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, .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 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);
}