summaryrefslogtreecommitdiff
path: root/anim/src/disasm.zig
blob: cf16c6a8c395beaf94c88eaeea43c186d71cac99 (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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
//! `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 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,

    /// 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,

    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);
        // On the map its box is as long as the instructions the recording has round the pc.
        if (ui.mapping) map.measure(.disasm, listing(u, rec, now.marks[1], theme.map.disasm_rows, (theme.map.disasm_rows - 1) / 2).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];
        }
        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) "" else names[1] });
        if (renamed) {
            u.faded(1 - going).tagNote(box.w, names[0]);
            u.faded(going).tagNote(box.w, names[1]);
        }
        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]];
        // 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 > 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 });
        }

        // `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.
        const ran = u.f.scratch.alloc(?Ran, merged.len) catch return;
        @memset(ran, null);
        for (0..3) |k| {
            const first = now.stops[@min(base + 1 + k, now.stops.len - 1)];
            const last = now.stops[base + 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.line_count);
        // 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]u32{ rec.own[now.marks[0]], rec.own[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);
        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.
            for (&runs, lines_of) |*r, of| r.add(line != null and line.? == of 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 });
            const is_pc = row.addr == pc[if (going >= 0.5) 1 else 0];
            const was = if (is_pc) null else ran[j];
            if (was) |r| lit.trail(c.mark, y, r.k);
            const hangs = d.insn(lit, now, row, y, box.w, widen, line, line != last_line, current_line, lead, if (is_pc) .current else if (was) |r| .{ .ran = r } else .ahead, base, covered > 0, 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 (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);
    }

    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) c.annotation else x) - gap - c.operands, t.faint);
            u.text(.mono, size, x, base_y, name, t.faint);
            return 0;
        }
        _ = at.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);
        };
        // Padding touches nothing: faint, with its operands.
        const pad = row.padding();
        u.text(.mono_bold, size, c.mnemonic, base_y, row.mnemonic(), if (pad) t.faint else theme.color.code.keyword);
        // How wide the annotation is, drawn where nothing shows; then where it goes.
        const need = d.annotation(u.faded(0), now, row, y, c.annotation, std.math.inf(f32), state, base, 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| pltName(u, rec, to) else "";
        var x = room + gap;
        if (need.drawn) x = annotationX(operandsWidth(u, row, ops, stub), room, need.end - c.annotation);
        operands(u, row, ops, stub, base_y, (if (covered) @min(x, c.annotation) else x) - gap - c.operands, if (pad) t.faint else theme.color.code.plain);
        // 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;
    }

    const Note = struct { drawn: bool = false, end: f32 = 0, hangs: usize = 0 };
    /// The row that set the flags a conditional jump reads, while the jump
    /// runs: its chips are framed as read with it (an `echo`).
    const Echo = struct { addr: u64, shows: f32 };

    /// The annotation: what it does, now, from `x`, cut where `room` ends.
    /// What it left behind is shown only where the step ran this
    /// instruction alone: a step by line runs others after it, and the
    /// state after them is not its doing.
    fn annotation(d: *const Disasm, u: ui.Ui, now: cursors.Now, row: Insn, y: f32, x: f32, room: f32, state: State, base: usize, 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.
                if (state == .ran) if (returned(rec, row, moment, now.stops[base])) |back| {
                    return a.said(a.cForm(row, b.to, moment, rec.register(back, "rax"), a.room - a.x), t.primary);
                };
                var note = a.callee(b.to, moment);
                // Its arguments hang under it, a small `reg` a row, as many as the prototype has.
                if (state == .current) note.hangs = a.arguments(row, b.to, moment);
                return note;
            },
            .ret => {
                u.text(.mono, size, x, base_y, "\u{2192}", t.faint);
                return .{ .drawn = true, .end = u.address(x + 2 * adv, base_y, b.to, .{ .ink = ui.rgb(code_ink), .name = rec.strings.get(b.to) orelse "" }) };
            },
            .jump => {
                // 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 .{};
        }
        // A compare: the two values, then (once it has run) the flags it leaves.
        if (std.mem.eql(u8, mn, "cmp") or std.mem.eql(u8, mn, "test")) {
            const left = a.compared(row, moment, touches[0]);
            var end = a.word(x, left[0], t.primary);
            end = a.word(end, " : ", t.faint);
            end = a.word(end, left[1], t.primary);
            const left_at: ?u64 = switch (state) {
                .ran => after,
                .current => if (after != null and now.landed(.cpu, 0)) after else null,
                .ahead, .waiting => null,
            };
            if (left_at) |l| {
                var buf: [256]u8 = undefined;
                const next = rec.instruction(moment, row.addr + row.len, &buf);
                var mask = if (next) |n| flagsRead((Insn{ .addr = 0, .len = 0, .text = n.text }).mnemonic()) else 0;
                if (mask == 0) mask = flag_bits.cf | flag_bits.zf | flag_bits.sf | flag_bits.of;
                end = flags(u, end + 2 * adv, y, rec.register(l, "eflags"), mask, if (echo) |e| if (e.addr == row.addr) e.shows else 0 else 0);
            }
            return .{ .drawn = true, .end = end };
        }
        // The rest is what it left behind, or where it reads: by what it is.
        const value_at: ?u64 = switch (state) {
            .ran => after,
            .current => if (after != null and now.landed(.cpu, 0)) after.? else null,
            .ahead, .waiting => null,
        };
        // A place the C library's layout names: the canary.
        if (std.mem.indexOf(u8, row.text, "fs:[0x28]") != null) {
            const end = a.word(x, if (x + 35 * adv <= room) "the stack's canary" else "canary", t.dim);
            const word_ = if (touches[0]) |touch| Recording.word(rec.moment(value_at orelse moment), touch.addr, 8) catch null else null;
            if (word_) |v| return .{ .drawn = true, .end = a.word(end + adv, u.print("{x}", .{v}), t.primary) };
            u.unknown(.{ .x = end + adv, .y = y, .w = 24, .h = m.row });
            return .{ .drawn = true, .end = end + adv + 24 };
        }
        // `lea`: `=` and what it made.
        if (std.mem.eql(u8, mn, "lea")) {
            const at = value_at orelse return .{};
            const reg = written(row) orelse return .{};
            const end = a.word(x, "=", t.faint);
            return .{ .drawn = true, .end = rows.chain(u, end + adv, y, rec.moment(at), rec.register(at, reg), room, .{}).end };
        }
        // A `rep`: how many times, how wide each, and where it goes.
        if (std.mem.startsWith(u8, mn, "rep")) {
            const each: u8 = switch (mn[mn.len - 1]) {
                'b' => 1,
                'w' => 2,
                'd' => 4,
                else => 8,
            };
            var end = a.word(x, "rcx", t.dim);
            end = a.word(end + adv, u.print("{d}", .{rec.register(moment, "rcx")}), t.primary);
            end = a.word(end + adv, u.print("\u{00b7} {d} bytes each", .{each}), t.faint);
            end = a.word(end + adv, "rdi", t.dim);
            return .{ .drawn = true, .end = rows.chain(u, end + adv, y, rec.moment(moment), rec.register(moment, "rdi"), room, .{}).end };
        }
        // Memory: a chain from the address it computes. Before the step,
        // where it will look; in the step its first hop is read (with the
        // 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.landed(.memory, 0)) shown = rec.moment(aa);
                if (in_step) {
                    marks.changed = 1;
                    marks.changed_heat = now.written(touch.addr, touch.len, .memory, 0);
                }
            };
            // 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);
        u.text(.mono, size, x, base_y, reg, t.dim);
        return .{ .drawn = true, .end = rows.chain(u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, rec.moment(at), value, room, .{}).end };
    }
};

/// What an annotation says, from `x` on the row at `y`, cut where `room` ends.
const Say = struct {
    u: ui.Ui,
    rec: *const Recording,
    y: f32,
    x: f32,
    room: f32,

    /// `text` at `x` in `ink`; where it ends.
    fn word(a: Say, x: f32, text: []const u8, ink: u24) f32 {
        a.u.text(.mono, size, x, rows.baseline(a.y), text, ink);
        return x + @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(text) catch text.len)) * adv;
    }

    /// `text` from the annotation's place, cut at the room's end.
    fn said(a: Say, text: []const u8, ink: u24) Disasm.Note {
        return .{ .drawn = true, .end = a.word(a.x, if (std.math.isInf(a.room)) text else rows.fitted(a.u, text, a.room - a.x), ink) };
    }

    /// A function's name as a caller knows it: a PLT stub's is the
    /// function it reaches (`open`), or the resolver while its slot is lazy.
    fn functionName(a: Say, to: u64, moment: u64) []const u8 {
        const name = ui.symbol(a.u, a.rec.strings.get(to) orelse return a.u.print("{x}", .{to}));
        const bare = name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len];
        if (!std.mem.endsWith(u8, bare, "@plt")) return bare;
        var buf: [256]u8 = undefined;
        const jmp = a.rec.instruction(moment, to, &buf) orelse return bare[0 .. bare.len - 4];
        if (ripSlot(.{ .addr = to, .len = jmp.len, .text = jmp.text })) |slot| if ((zt.telescope.got(a.rec.moment(moment), slot) catch null)) |held| {
            if (held.lazy orelse false) return "the resolver";
        };
        return bare[0 .. bare.len - 4];
    }

    /// A direct call's callee, bright.
    fn callee(a: Say, to: u64, moment: u64) Disasm.Note {
        return .{ .drawn = true, .end = a.word(a.x, a.functionName(to, moment), t.bright) };
    }

    /// A call's arguments under it, a small `reg` a row: as many as its
    /// prototype has (the debug info's, the source's, a system call's of
    /// its name), three when none says. How many rows they take.
    fn arguments(a: Say, row: Insn, to: u64, moment: u64) usize {
        const name = a.functionName(to, moment);
        const count = 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| @intFromEnum(sys) else null;
        const names: []const []const u8 = if (nr) |n| zt.syscalls.names(n) else &.{};
        for (carriers[0..count], 1..) |reg, k| {
            const ry = a.y + @as(f32, @floatFromInt(k)) * m.row;
            a.u.text(.mono, size, a.x, rows.baseline(ry), reg, t.dim);
            const v = a.rec.register(moment, reg);
            if (k - 1 < names.len and std.mem.eql(u8, names[k - 1], "flags")) {
                a.u.text(.mono, size, a.x + 4 * adv, rows.baseline(ry), openFlags(a.u, v), t.primary);
            } else _ = rows.chain(a.u, a.x + 4 * adv, ry, shown, v, a.room, .{});
        }
        return count;
    }

    /// 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| @intFromEnum(sys) else null;
        const names: []const []const u8 = if (nr) |n| zt.syscalls.names(n) else &.{};
        const count = @min(row.params orelse argumentCount(a.rec, row, name) orelse names.len, 6);
        // Out of room the arguments go from the right, `…` for them; the result stays.
        var shown = count;
        while (true) : (shown -= 1) {
            var out: []const u8 = u.print("{s}(", .{name});
            for (carriers[0..shown], 0..) |reg, k| {
                const v = a.rec.register(moment, reg);
                out = u.print("{s}{s}{s}", .{ out, if (k > 0) ", " else "", argument(u, a.rec, moment, if (k < names.len) names[k] else "", v) });
            }
            if (shown < count) out = u.print("{s}{s}\u{2026}", .{ out, if (shown > 0) ", " else "" });
            out = u.print("{s})", .{out});
            if (result) |r| out = u.print("{s} = {d}", .{ out, @as(i64, @bitCast(r)) });
            if (shown == 0 or @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(out) catch out.len)) * adv <= width) return out;
        }
    }

    /// Where a call or a jump through memory or a register went: `→ addr
    /// name`, then faint where it was read, `· read from open@got, 403fd8`.
    /// Out of room the slot goes first, then the digits; the name stays.
    fn went(a: Say, to: u64, slot: ?Recording.Touch, moment: u64) Disasm.Note {
        const u = a.u;
        const name = a.functionName(to, moment);
        const from: []const u8 = if (slot) |s| blk: {
            const named = ui.symbol(u, a.rec.strings.get(s.addr) orelse "");
            break :blk u.print("\u{00b7} read from {s}{s}{x}", .{ named[0 .. std.mem.lastIndexOfScalar(u8, named, '+') orelse named.len], if (named.len > 0) ", " else "", s.addr });
        } else "";
        const digits_w = @as(f32, @floatFromInt(ui.digits(to) + 1)) * adv;
        const name_w = @as(f32, @floatFromInt(name.len)) * adv;
        const from_w = @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(from) catch from.len)) * adv;
        const fits_all = a.x + 2 * adv + digits_w + name_w + adv + from_w <= a.room;
        const fits_digits = a.x + 2 * adv + digits_w + name_w <= a.room;
        var end = a.word(a.x, "\u{2192}", t.faint) + adv;
        if (fits_digits) {
            end = u.address(end, rows.baseline(a.y), to, .{ .ink = ui.rgb(theme.color.region.code_), .name = name });
        } else end = a.word(end, name, t.primary);
        if (fits_all and from.len > 0) end = a.word(end + adv, from, t.faint);
        return .{ .drawn = true, .end = end };
    }

    /// The two values a compare compares, as its operands' size reads them.
    fn compared(a: Say, row: Insn, moment: u64, touch: ?Recording.Touch) [2][]const u8 {
        const ops = shorn(a.u, row);
        var parts = std.mem.splitScalar(u8, ops.text, ',');
        var operands_: [2][]const u8 = .{ "", "" };
        for (&operands_) |*o| o.* = std.mem.trim(u8, parts.next() orelse "", " ");
        // The size: a register's, else the width's, else a word's.
        var bytes: u8 = if (ops.bytes > 0) ops.bytes else 8;
        for (operands_) |o| if (registerSize(o)) |n| {
            bytes = n;
        };
        var out: [2][]const u8 = undefined;
        for (operands_, &out) |o, *v| {
            const raw: ?u64 = if (std.mem.indexOfScalar(u8, o, '[') != null)
                (if (touch) |tt| Recording.word(a.rec.moment(moment), tt.addr, @min(tt.len, 8)) catch null else null)
            else if (full(o)) |reg|
                a.rec.register(moment, reg)
            else
                parseImmediate(o);
            v.* = if (raw) |r| number(a.u, r, bytes) else "..";
        }
        return out;
    }

    /// `syscall`: its name and number (`openat nr 257`); its arguments hang
    /// under it, a register a row, each read as its name says.
    fn syscall(a: Say, moment: u64, current: bool) Disasm.Note {
        const u = a.u;
        const nr = a.rec.register(moment, "rax");
        var end = a.word(a.x, zt.syscalls.name(nr) orelse "syscall", t.bright);
        end = a.word(end + adv, "nr", t.faint);
        end = a.word(end + adv, u.print("{d}", .{nr}), t.primary);
        const names = zt.syscalls.names(nr);
        const n = @min(zt.syscalls.signature(nr).len, 6);
        if (!current) return .{ .drawn = true, .end = end };
        for (carriers_sys[0..n], 0..) |reg, k| {
            const ry = a.y + @as(f32, @floatFromInt(k + 1)) * m.row;
            u.text(.mono, size, a.x, rows.baseline(ry), reg, t.dim);
            const v = a.rec.register(moment, reg);
            const what = if (k < names.len) names[k] else "";
            const ax = a.x + 4 * adv;
            if (std.mem.eql(u8, what, "path") or std.mem.eql(u8, what, "buf")) {
                _ = rows.chain(u, ax, ry, a.rec.moment(moment), v, a.room, .{});
            } else if (std.mem.endsWith(u8, what, "fd") and v == fdcwd) {
                // The value class `fd`: the number, and faint what it names.
                u.text(.mono, size, ax, rows.baseline(ry), "-100", t.primary);
                u.text(.mono, size, ax + 5 * adv, rows.baseline(ry), "AT_FDCWD", t.faint);
            } else if (std.mem.endsWith(u8, what, "fd")) {
                _ = u.typed(ax, rows.baseline(ry), v, .{ .fd = a.rec.openOn(u.f.scratch, v, moment) }, .{});
            } else u.text(.mono, size, ax, rows.baseline(ry), argument(u, a.rec, moment, what, v), t.primary);
        }
        return .{ .drawn = true, .end = end, .hangs = n };
    }
};

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

/// The slot a `jmp` or `call` through `[rip + X]` reads.
fn ripSlot(row: Insn) ?u64 {
    const ops = row.operands();
    const at = std.mem.indexOf(u8, ops, "[rip + 0x") orelse return null;
    const close = std.mem.indexOfScalarPos(u8, ops, at, ']') orelse return null;
    const disp = std.fmt.parseInt(u64, ops[at + 9 .. close], 16) catch return null;
    return row.addr + row.len + disp;
}

/// An immediate operand's value.
fn parseImmediate(o: []const u8) ?u64 {
    const negative = std.mem.startsWith(u8, o, "-");
    const digits_ = if (negative) o[1..] else o;
    const v = (if (std.mem.startsWith(u8, digits_, "0x")) std.fmt.parseInt(u64, digits_[2..], 16) else std.fmt.parseInt(u64, digits_, 10)) catch return null;
    return if (negative) 0 -% v else v;
}

/// `v` as a number `bytes` wide: signed and in decimal when small, else hex.
fn number(u: ui.Ui, v: u64, bytes: u8) []const u8 {
    const bits: u7 = @as(u7, @min(bytes, 8)) * 8;
    const masked = if (bits == 64) v else v & ((@as(u64, 1) << @intCast(bits)) - 1);
    const signed: i64 = if (bits == 64) @bitCast(masked) else @as(i64, @bitCast(masked << @intCast(64 - @as(u7, bits)))) >> @intCast(64 - @as(u7, bits));
    if (signed > -0x10000 and signed < 0x10000) return u.print("{d}", .{signed});
    return u.print("{x}", .{masked});
}

/// eflags' bits a reader meets.
const flag_bits = struct {
    const cf: u16 = 1 << 0;
    const pf: u16 = 1 << 2;
    const zf: u16 = 1 << 6;
    const sf: u16 = 1 << 7;
    const of: u16 = 1 << 11;
};

/// The flags a conditional (`jcc`, `setcc`, `cmovcc`) reads; 0 for anything else.
pub fn flagsRead(mn: []const u8) u16 {
    const cond = if (std.mem.startsWith(u8, mn, "cmov")) mn[4..] else if (std.mem.startsWith(u8, mn, "set")) mn[3..] else if (mn.len > 1 and mn[0] == 'j' and !std.mem.eql(u8, mn, "jmp")) mn[1..] else return 0;
    const f = flag_bits;
    const table = [_]struct { []const u8, u16 }{
        .{ "a", f.cf | f.zf },  .{ "nbe", f.cf | f.zf }, .{ "be", f.cf | f.zf },        .{ "na", f.cf | f.zf },
        .{ "ae", f.cf },        .{ "nb", f.cf },         .{ "nc", f.cf },               .{ "b", f.cf },
        .{ "c", f.cf },         .{ "nae", f.cf },        .{ "e", f.zf },                .{ "z", f.zf },
        .{ "ne", f.zf },        .{ "nz", f.zf },         .{ "g", f.zf | f.sf | f.of },  .{ "nle", f.zf | f.sf | f.of },
        .{ "le", f.zf | f.sf | f.of }, .{ "ng", f.zf | f.sf | f.of }, .{ "ge", f.sf | f.of }, .{ "nl", f.sf | f.of },
        .{ "l", f.sf | f.of },  .{ "nge", f.sf | f.of }, .{ "o", f.of },                .{ "no", f.of },
        .{ "s", f.sf },         .{ "ns", f.sf },         .{ "p", f.pf },                .{ "pe", f.pf },
        .{ "np", f.pf },        .{ "po", f.pf },
    };
    for (table) |e| if (std.mem.eql(u8, cond, e[0])) return e[1];
    return 0;
}

/// The flags of `mask`, as rip's row draws them: set, upper case on a
/// chip; clear, lower case and dim; each framed as read by `read`. Where they end.
fn flags(u: ui.Ui, x: f32, y: f32, eflags: u64, mask: u16, read: f32) f32 {
    var at = x;
    for (rows.flags) |flag| {
        if (@as(u64, mask) >> flag.bit & 1 == 0) continue;
        const chip: Rect = .{ .x = at, .y = y + 2, .w = theme.metric.flags.chip[0], .h = theme.metric.flags.chip[1] };
        if (eflags >> flag.bit & 1 != 0) {
            u.chip(chip);
            u.text(.mono_bold, size, at + 4, rows.baseline(y), flag.name, t.bright);
        } else u.text(.mono, size, at + 4, rows.baseline(y), u.print("{c}{c}", .{ std.ascii.toLower(flag.name[0]), std.ascii.toLower(flag.name[1]) }), t.dim);
        if (read > 0) u.read(chip, read);
        at += chip.w + 4;
    }
    return at - 4;
}

/// While a conditional jump runs (the mark on it, its step under way), the
/// row that set the flags it reads: the instruction just before it ran.
fn jumpEcho(now: cursors.Now, base: usize) ?Disasm.Echo {
    if (base != 1 or now.resting()) return null;
    const flags_ = readsFlags(now.rec, now.stops[1]);
    if (flags_ == 0 or now.stops[1] == 0) return null;
    return .{ .addr = now.rec.register(now.stops[1] - 1, "rip"), .shows = now.reading(.cpu, 0) };
}

/// The flags the instruction at moment `i`'s pc reads, if it is a conditional.
pub fn readsFlags(rec: *const Recording, i: u64) u16 {
    var buf: [256]u8 = undefined;
    const pc = rec.register(i, "rip");
    const here = rec.instruction(i, pc, &buf) orelse return 0;
    return flagsRead((Insn{ .addr = pc, .len = here.len, .text = here.text }).mnemonic());
}

/// The gap between the operands and the annotation: a character.
const gap = adv;

/// The runs of rows of one line, top and bottom of each, as the rows go by.
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(c.annotation, @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 {
    const base_y = rows.baseline(y);
    _ = u.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(theme.color.region.code_) });
    // A library's twelve digits move what is right of them, 12 a digit past seven.
    const v = u.moved(@as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv, 0);
    const pad = row.padding();
    v.text(.mono_bold, size, c.mnemonic, base_y, row.mnemonic(), if (pad) t.faint else theme.color.code.keyword);
    operands(v, row, shorn(v, row), "", base_y, c.annotation - gap - c.operands, if (pad) t.faint else theme.color.code.plain);
}

/// Operands as canim draws them (design/README.md, `insn` and `width`):
/// the disassembler's less every size word (`qword ptr `); and where no
/// register outside the brackets has the access's size and the mnemonic
/// does not fix it, how many bytes it touches (`bytes`), drawn as byte
/// cells after the `]` that ends at `after`.
const Operands = struct { text: []const u8, after: usize = 0, bytes: u8 = 0 };

fn shorn(u: ui.Ui, row: Insn) Operands {
    var ops = row.operands();
    var bytes: u8 = 0;
    while (std.mem.indexOf(u8, ops, " ptr ")) |ptr| {
        var word = ptr;
        while (word > 0 and ops[word - 1] != ' ' and ops[word - 1] != ',') word -= 1;
        for ([_]struct { []const u8, u8 }{ .{ "byte", 1 }, .{ "word", 2 }, .{ "dword", 4 }, .{ "qword", 8 }, .{ "tbyte", 10 }, .{ "xmmword", 16 }, .{ "ymmword", 32 }, .{ "zmmword", 64 } }) |w| {
            if (std.mem.eql(u8, ops[word..ptr], w[0])) bytes = w[1];
        }
        ops = u.print("{s}{s}", .{ ops[0..word], ops[ptr + 5 ..] });
    }
    const close = std.mem.indexOfScalar(u8, ops, ']') orelse return .{ .text = ops };
    if (bytes == 0) return .{ .text = ops };
    // Said already: by the mnemonic (a stack op, a branch through memory,
    // what touches nothing, a string op's suffix, SSE's scalar ops), or by
    // a register outside the brackets of the access's size.
    const mn = row.mnemonic();
    for ([_][]const u8{ "push", "pop", "call", "jmp", "lea", "nop", "rep" }) |says| if (std.mem.startsWith(u8, mn, says)) return .{ .text = ops };
    if (mn.len == 0 or mn[0] == 'j') return .{ .text = ops };
    var parts = std.mem.splitScalar(u8, ops, ',');
    while (parts.next()) |part| {
        const operand = std.mem.trim(u8, part, " ");
        if (std.mem.indexOfScalar(u8, operand, '[') != null) continue;
        const of = registerSize(operand) orelse continue;
        if (of == bytes or of >= 16) return .{ .text = ops };
    }
    return .{ .text = ops, .after = close + 1, .bytes = bytes };
}

/// How many bytes register `name` is; null for anything else.
fn registerSize(name: []const u8) ?u8 {
    if (name.len < 2) return null;
    for ([_]struct { []const u8, u8 }{ .{ "xmm", 16 }, .{ "ymm", 32 }, .{ "zmm", 64 } }) |v| if (std.mem.startsWith(u8, name, v[0])) return v[1];
    if (full(name) == null and !(name.len == 3 and name[2] == 'l')) return null;
    if (name[0] == 'r' and std.ascii.isDigit(name[1])) return switch (name[name.len - 1]) {
        'd' => 4,
        'w' => 2,
        'b' => 1,
        else => 8,
    };
    if (name.len == 3) return switch (name[0]) {
        'r' => 8,
        'e' => 4,
        else => 1, // sil, dil, bpl, spl
    };
    return if (name[1] == 'l' or name[1] == 'h') 1 else 2;
}

/// How wide `width`'s cells are for an access of `bytes`, with the gaps
/// round them (3 after the `]`, 4 before what follows) and, past eight
/// bytes, the count.
fn cellsWidth(u: ui.Ui, bytes: u8) f32 {
    if (bytes == 0) return 0;
    const w = theme.metric.width;
    const n: f32 = @floatFromInt(@min(bytes, 8));
    const count: f32 = if (bytes > 8) u.width(.mono, size, u.print("{d}", .{bytes})) + w.after else 0;
    return w.before + (n - 1) * w.pitch + w.cell[0] + w.after + count;
}

/// `width`: `bytes` byte cells at `x`, standing on the baseline; a count past eight.
fn cells(u: ui.Ui, x: f32, base_y: f32, bytes: u8) void {
    const w = theme.metric.width;
    for (0..@min(bytes, 8)) |k| u.fill(.{ .x = x + w.before + @as(f32, @floatFromInt(k)) * w.pitch, .y = base_y - w.cell[1], .w = w.cell[0], .h = w.cell[1] }, t.dim);
    if (bytes > 8) u.text(.mono, size, x + w.before + 7 * w.pitch + w.cell[0] + w.after, base_y, u.print("{d}", .{bytes}), t.faint);
}

/// A PLT stub's name, for a call or a jump to one: `open@plt`; "" otherwise.
fn pltName(u: ui.Ui, rec: *const Recording, to: u64) []const u8 {
    const name = ui.symbol(u, rec.strings.get(to) orelse return "");
    const stub = name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len];
    return if (std.mem.endsWith(u8, stub, "@plt")) stub else "";
}

/// How wide operands `ops` of `row` are, whole (a target with its stub's name `stub`).
fn operandsWidth(u: ui.Ui, row: Insn, ops: Operands, stub: []const u8) f32 {
    if (target(row)) |to| return @as(f32, @floatFromInt(ui.digits(to) + if (stub.len > 0) stub.len + 1 else 0)) * adv;
    return @as(f32, @floatFromInt(ops.text.len)) * adv + cellsWidth(u, ops.bytes);
}

/// The operands `ops`, in `width` units, in `ink`; a jump's or a call's
/// target is an `address` in code's ink, a PLT stub's with its name. Cut
/// only at their far end, saying so, and never inside `[]`: a cut that
/// would fall there falls before the `[`.
fn operands(u: ui.Ui, row: Insn, ops: Operands, stub: []const u8, base_y: f32, width: f32, ink: u24) void {
    if (target(row)) |to| {
        _ = u.address(c.operands, base_y, to, .{ .ink = ui.rgb(theme.color.region.code_), .name = stub });
        return;
    }
    const text = ops.text;
    const extra = cellsWidth(u, ops.bytes);
    const at_after = c.operands + @as(f32, @floatFromInt(ops.after)) * adv;
    if (@as(f32, @floatFromInt(text.len)) * adv + extra <= width) {
        if (ops.bytes == 0) return u.text(.mono, size, c.operands, base_y, text, ink);
        u.text(.mono, size, c.operands, base_y, text[0..ops.after], ink);
        cells(u, at_after, base_y, ops.bytes);
        u.text(.mono, size, at_after + extra, base_y, text[ops.after..], ink);
        return;
    }
    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;
    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`.
fn listing(u: ui.Ui, rec: *const Recording, i: u64, room: usize, above: usize) Listing {
    return listingAt(u, rec, i, rec.register(i, "rip"), room, above);
}

/// The same round the instruction at `pc` (in the window, `Listing.pc`).
pub fn listingAt(u: ui.Ui, rec: *const Recording, i: u64, pc: u64, room: usize, above: usize) Listing {
    const out = u.f.scratch.alloc(Insn, room) catch return .{ .rows = &.{}, .pc = 0 };
    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'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);
}