summaryrefslogtreecommitdiff
path: root/anim/src/descent.zig
blob: 5dd156c4906fca0e7cbb0b6fe76b38c3b5a6fafa (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
//! `descent` (design/README.md, "3. Panels"): the disassembly a level up,
//! a call followed down. The panel is a stack of windows, one a call deep:
//! the scene's function's on top, each callee's under the row that called
//! it (that row `waiting`, ringed; a PLT stub gone through keeps its `jmp`,
//! `pass`), a head row over each, the call lane from ring to head; and
//! under the deepest, while a system call crosses, the kernel on vellum.
//! Down is deeper, and the way back up is drawn.
//!
//! Every row has a key (an instruction's address, a head's function), so
//! the panel at one moment and at the next are two lists of the same
//! rows: a step is the rows both have gliding, and the others leaving or
//! arriving, on the timetable of its verb (`descend`, `ascend`, `cross`;
//! design/motion.md, "A call followed down", "A system call").
const std = @import("std");
const sk = @import("sketch");
const anim = @import("anim");
const ui = @import("ui.zig");
const rows = @import("rows.zig");
const cursors = @import("cursor.zig");
const Recording = @import("Recording.zig");
const ties = @import("ties.zig");
const map = @import("map.zig");
const context = @import("context.zig");
const disasm = @import("disasm.zig");
const graph = @import("graph.zig");
const syscalls = @import("syscalls.zig");
const Stage = @import("stage.zig").Stage;
const theme = ui.theme;
const Rect = ui.Rect;
const t = theme.color.text;
const k = theme.color.on_kernel;
const m = theme.metric.context;
const c = theme.metric.insn;
const size = theme.size.mono.context;
const adv = size * 3 / 5;
const Insn = disasm.Insn;

/// Frames at 60 a second, as motion.md counts them.
fn f(n: f32) f32 {
    return n / 60.0;
}

fn clamp01(v: f32) f32 {
    return std.math.clamp(v, 0, 1);
}

/// One step of `by` from where the cursor is, timed as its verb
/// (design/motion.md, "A call followed down"): into a call (`descend`, 2.9
/// s), on through a PLT stub's `jmp` (2.2 s), out by a `ret` (`ascend`, 2.5
/// s), across into the kernel (`cross`: `syscalls.step`); any other walked.
/// A window opens and closes in two moves, never at once: the rows it gives
/// up fade, then the rows it keeps glide (and back: they glide, then fade in).
pub fn step(cur: cursors.Cursor, s: *anim.Frame, by: Recording.Stop) void {
    const rec = cur.rec;
    const from = cur.moment(s);
    const to = rec.next(by, from);
    for (rec.syscalls) |made| if (made.enter > from and made.enter <= to) return syscalls.step(cur, s, by);
    if (to != from + 1) return cur.walk(s, by, to);
    const b = rec.insn_branches[from] orelse return cur.walk(s, by, to);
    var name_buf: [256]u8 = undefined;
    const here = (rec.moment(from).string(rec.register(from, "rip"), &name_buf) catch null) orelse "";
    const plan: cursors.Plan = switch (b.kind) {
        .call => .{ .at = .{ f(24), f(60), f(60) }, .advance = f(138), .travel = f(12), .total = f(174) },
        .ret => .{ .at = .{ f(36), f(18), f(36) }, .advance = f(114), .travel = f(12), .total = f(150) },
        .jump => if (std.mem.indexOf(u8, here, "@plt") != null) .{ .at = .{ f(18), f(24), f(24) }, .advance = f(96), .travel = f(12), .total = f(132) } else return cur.walk(s, by, to),
        .none => return cur.walk(s, by, to),
    };
    cur.step(s, to, plan, plan.total);
}

/// A row of the panel.
const Item = struct {
    key: u64,
    row: f32,
    /// The window it is in, 0 the top.
    window: u8,
    what: union(enum) { insn: Insn, head: struct { name: []const u8, note: []const u8 }, more: []const u8 },
    state: enum { plain, waiting, pass, current } = .plain,
    /// A waiting or passed row: the moment it ran.
    at: u64 = 0,
};

/// The panel at a moment.
const Layout = struct {
    items: []Item,
    /// Windows of code (a fold counts as none).
    windows: usize,
    /// The bottom three rows are the kernel's (the pc is at, or has just
    /// come back from, a `syscall`).
    kernel: bool,
    /// The deepest function and its module: the panel's tag.
    tag: []const u8,
    in_stub: bool,
};

pub const Descent = struct {
    cursor: cursors.Cursor,
    stage: *const Stage,
    focus: bool = false,
    /// The function whose window is on top: where the scene follows from.
    root: []const u8 = "main",

    pub fn draw(d: *const Descent, fr: *sk.Frame, placed: anim.Placed) void {
        const box = d.stage.box(placed, .disasm);
        const u = context.at(fr, placed, box);
        const now = d.cursor.now(placed);
        const rec = d.cursor.rec;
        const room = theme.layout.rowsIn(box.h);
        const before = layout(u, rec, now.stops[1], room, d.root);
        const after = layout(u, rec, now.stops[0], room, d.root);
        // On the map its box is as long as the rows it has wanted: not 69 for a function of 30.
        if (ui.mapping) map.measure(.disasm, @max(before.items.len, after.items.len));
        const tm = now.time;
        const going = now.advancing();
        const kind: enum { same, down, through, up } = if (now.resting() or now.stops[0] == now.stops[1]) .same else if (after.windows > before.windows) (if (before.in_stub) .through else .down) else if (after.windows < before.windows) .up else .same;
        const shown = if (going >= 0.5) after else before;
        // A tag that changes with the advance crossfades over it.
        const retag = !std.mem.eql(u8, before.tag, after.tag);
        const body = u.panel(box.w, box.h, "disassembly", .{ .focus = d.focus, .note = if (retag) "" else shown.tag });
        if (retag) {
            u.faded(1 - going).tagNote(box.w, before.tag);
            u.faded(going).tagNote(box.w, after.tag);
        }
        const top = body.y + m.pad;
        u.clip(.{ .x = theme.stroke.rule, .y = m.tag, .w = box.w - 2 * theme.stroke.rule, .h = box.h - m.tag - theme.stroke.rule });
        defer u.unclip();

        // How far the rows both lists have are on their way, and how much
        // of each that leaves or comes shows: the verb's timetable.
        const move: f32 = switch (kind) {
            .same => cursors.glide(going),
            .down => cursors.glide(clamp01((tm - f(78)) / f(18))),
            .through => cursors.glide(clamp01((tm - f(36)) / f(18))),
            .up => cursors.glide(clamp01((tm - f(84)) / f(18))),
        };
        const Placed = struct { item: Item, y: f32, shows: f32, rise: f32, old: ?Item, new: ?Item, twin: bool = false };
        // A row whose state the verb changes (the call row going to wait, a
        // stub's jmp passing, a waiting call taking its result) crossfades from
        // the one to the other (12 f; 6 f up), its hanging arguments with it.
        const turn: f32 = switch (kind) {
            .same => 0,
            .down => clamp01((tm - f(66)) / f(12)),
            .through => clamp01((tm - f(24)) / f(12)),
            .up => clamp01((tm - f(114)) / f(6)),
        };
        var placed_items: std.ArrayList(Placed) = .empty;
        const a = u.f.scratch;
        // Leaving: bottom up when a window closes, all at once when a caller gives up rows.
        var leaving: usize = 0;
        var i = before.items.len;
        while (i > 0) {
            i -= 1;
            const it = before.items[i];
            if (find(after.items, it.key)) |_| continue;
            const shows: f32 = switch (kind) {
                .same => 1 - clamp01(2 * going),
                .down => 1 - clamp01((tm - f(66)) / f(12)),
                .through => 1 - clamp01((tm - f(24)) / f(12)),
                .up => 1 - clamp01((tm - f(48) - @as(f32, @floatFromInt(leaving)) * f(2)) / f(12)),
            };
            leaving += 1;
            placed_items.append(a, .{ .item = it, .y = top + it.row * m.row, .shows = shows, .rise = 0, .old = it, .new = null }) catch {};
        }
        // Arriving: a head rising, then its rows top down, 2 f apart.
        var arriving: usize = 0;
        for (after.items) |it| {
            if (find(before.items, it.key)) |old| {
                const y = top + std.math.lerp(old.row, it.row, move) * m.row;
                if (kind != .same and old.state != it.state) {
                    placed_items.append(a, .{ .item = old, .y = y, .shows = 1 - turn, .rise = 0, .old = old, .new = it }) catch {};
                    placed_items.append(a, .{ .item = it, .y = y, .shows = turn, .rise = 0, .old = old, .new = it, .twin = true }) catch {};
                    continue;
                }
                placed_items.append(a, .{ .item = if (going < 0.5) old else it, .y = y, .shows = 1, .rise = 0, .old = old, .new = it }) catch {};
                continue;
            }
            const head = it.what == .head;
            const shows: f32 = switch (kind) {
                .same => clamp01(2 * going - 1),
                .down => if (head) clamp01((tm - f(108)) / f(12)) else clamp01((tm - f(114) - @as(f32, @floatFromInt(arriving)) * f(2)) / f(12)),
                .through => if (head) clamp01((tm - f(66)) / f(12)) else clamp01((tm - f(72) - @as(f32, @floatFromInt(arriving)) * f(2)) / f(12)),
                .up => clamp01((tm - f(102)) / f(12)),
            };
            if (!head) arriving += 1;
            placed_items.append(a, .{ .item = it, .y = top + it.row * m.row, .shows = shows, .rise = if (head and kind != .same) (1 - cursors.standard(shows)) * theme.time.caption_rise else 0, .old = null, .new = it }) catch {};
        }
        std.mem.sort(Placed, placed_items.items, {}, struct {
            fn above(_: void, x: Placed, y: Placed) bool {
                return x.y < y.y;
            }
        }.above);

        // The marks: the pc's plaque, leaving the row it was on and landing
        // on the next; the ring on a waiting call; a passed stub's bar.
        const marked = now.marks[if (going >= 0.5) 1 else 0];
        const plaque = [2]f32{
            // The one it leaves: in a descend it becomes the ring (84 to 96 f),
            // through a stub the pass bar (24 to 36), up it closes with its window.
            switch (kind) {
                .same => 1,
                .down => 1 - clamp01((tm - f(84)) / f(12)),
                .through => 1 - clamp01((tm - f(24)) / f(12)),
                .up => 1 - clamp01((tm - f(48)) / f(12)),
            },
            // The one it lands on, with the advance.
            if (kind == .same) 1 else clamp01(going * 2),
        };
        // A crossing stepped over: the kernel's window opens under the call
        // row, past the arguments hanging under it; the rows after them make
        // room first (18 f, as the lane sets off) and close up with the
        // window as it draws back.
        var under: ?f32 = null;
        if (steppedOver(now)) |made| for (placed_items.items) |p| if (p.old) |o| if (o.state == .current and o.what == .insn) {
            const at = p.y + @as(f32, @floatFromInt(1 + disasm.hanging(u, rec, o.what.insn, now.stops[1]))) * m.row;
            const sp = syscalls.Plan.in(now, made);
            const opening = cursors.glide(clamp01((tm - sp.enters) / f(18)));
            const room_ = 3 * m.row * @min(opening, 1 - clamp01((tm - now.plan.advance) / f(12)));
            for (placed_items.items) |*q| if (q.y >= at - 1) {
                q.y += room_;
            };
            under = at;
            break;
        };
        var pc_y = [2]?f32{ null, null };
        for (placed_items.items) |p| {
            if (p.old) |o| if (o.state == .current) {
                pc_y[0] = p.y;
            };
            if (p.new) |n| if (n.state == .current) {
                pc_y[1] = p.y;
            };
        }
        // In one window the plaque slides from row to row, with the advance.
        var mark: ?struct { y: f32, shows: f32 } = null;
        if (kind == .same) {
            if (pc_y[0] != null and pc_y[1] != null) mark = .{ .y = std.math.lerp(pc_y[0].?, pc_y[1].?, cursors.standard(going)), .shows = 1 } else if (pc_y[1]) |y| {
                mark = .{ .y = y, .shows = clamp01(2 * going - 1) };
            } else if (pc_y[0]) |y| {
                mark = .{ .y = y, .shows = 1 - clamp01(2 * going) };
            }
        }
        const fire = now.fires(.disasm);
        if (mark) |mk| plaqueAt(u, box.w, mk.y, mk.shows, fire) else {
            if (pc_y[0]) |y| if (going < 0.5) plaqueAt(u, box.w, y, plaque[0], fire);
            if (pc_y[1]) |y| if (going >= 0.5) plaqueAt(u, box.w, y, plaque[1], 0);
        }

        // Which rows ran in the last three steps: the trail.
        const ran = recentRows(a, now, if (going >= 0.5) 0 else 1);
        // The line the source panel is on, in the file it shows: rows of that file carry their numbers.
        const current = rec.shown[marked];
        const current_line = current.line;
        const widen0 = rows.numberRoom(rec.most_lines);
        var covered: usize = 0;
        var covered_before: usize = 0;
        var runs: disasm.Runs = .{};
        var last_line: ?u32 = null;
        var last_window: ?u8 = null;
        const dd: disasm.Disasm = .{ .cursor = d.cursor, .stage = d.stage };
        const base: usize = if (going >= 0.5) 0 else 1;
        // Each window's blocks (`graph`), read once: a rule over each one's first row, its visits where the row has room.
        var rules: [8]?graph.Rules = @splat(null);
        for (placed_items.items) |p| {
            const v = u.faded(p.shows);
            const y = p.y + p.rise;
            if (p.shows <= 0) continue;
            if (last_window == null or last_window.? != p.item.window) last_line = null;
            last_window = p.item.window;
            switch (p.item.what) {
                .head => |h| {
                    v.fill(.{ .x = theme.stroke.rule, .y = y, .w = box.w - 2 * theme.stroke.rule, .h = theme.stroke.rule }, theme.color.rule);
                    v.text(.sans_medium, theme.size.sans.micro, c.address, y + 18, h.name, t.primary);
                    v.text(.sans, theme.size.sans.micro, map.content(box.w) - m.side - v.width(.sans, theme.size.sans.micro, h.note), y + 18, h.note, t.faint);
                    covered -|= 1;
                },
                .more => |words| {
                    _ = v.arrow(c.address, y + m.row / 2, .more);
                    v.text(.mono, size, c.address + m.arrow_w + adv, rows.baseline(y), words, t.faint);
                    covered -|= 1;
                },
                .insn => |row| {
                    const window_items = windowOf(placed_items.items, p.item.window);
                    var addrs: [80]u64 = undefined;
                    var n: usize = 0;
                    for (window_items) |w| if (w.item.what == .insn and n < addrs.len) {
                        addrs[n] = w.item.key;
                        n += 1;
                    };
                    const lead = ui.shared(addrs[0..n]);
                    const wide = @as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv;
                    const line = if (row.outside or row.src != current.src) null else row.line;
                    const state: disasm.Disasm.State = switch (p.item.state) {
                        // The row the plaque has not reached yet is ahead.
                        .current => if (p.old == null or p.old.?.state != .current) (if (going >= 0.5) .current else .ahead) else if (p.new == null or p.new.?.state != .current) (if (going < 0.5) .current else .ahead) else .current,
                        .waiting => .{ .waiting = p.item.at },
                        .pass => .{ .ran = .{ .k = 0, .at = p.item.at } },
                        .plain => if (ranOf(ran, row.addr)) |r| .{ .ran = r } else .ahead,
                    };
                    // The marks at the row's left: the trail, the ring, the pass.
                    switch (p.item.state) {
                        .plain => if (ranOf(ran, row.addr)) |r| v.trail(c.mark, y, r.k),
                        .pass => v.trail(c.mark, y, 0),
                        .waiting => {
                            // The ring comes as the plaque leaves; going up it becomes a trail bar.
                            const ring: f32 = if (p.old != null and p.old.?.state == .waiting) (if (kind == .up) 1 - clamp01((tm - f(114)) / f(12)) else 1) else if (kind == .down) clamp01((tm - f(84)) / f(12)) else 1;
                            ringAt(v.faded(ring), y);
                            if (ring < 1) v.faded(1 - ring).trail(c.mark, y, 0);
                        },
                        .current => {},
                    }
                    runs.add(line != null and line.? == current_line, y, y + m.row);
                    // A row drawn twice (crossfading) counts once for the arguments that hang over the rows under it.
                    const covers = if (p.twin) covered_before > 0 else covered > 0;
                    const hangs = dd.insn(v, now, row, y, map.content(box.w), widen0 + wide, line, line != last_line, current_line, lead, state, base, covers, .{ addrs[0], addrs[n -| 1] }, null);
                    const w = @min(p.item.window, rules.len - 1);
                    if (rules[w] == null) rules[w] = graph.Rules.init(u.f.scratch, rec, now.marks, .{ row.addr, row.addr }, going);
                    rules[w].?.draw(v, row.addr, y, map.content(box.w), !covers and !row.outside and !dd.noted(v, now, row, y, state, base, .{ addrs[0], addrs[n -| 1] }, null));
                    if (!p.twin) covered_before = covered;
                    covered = if (p.twin) @max(covered, hangs) else @max(covered -| 1, hangs);
                    last_line = line;
                    map.row(.disasm, row.addr, u, .{ .x = 0, .y = y, .w = box.w, .h = m.row });
                },
            }
        }
        runs.add(false, box.h, box.h);
        disasm.threadRuns(u, box.w, .{ .{}, runs }, 1);

        // The call lane: from each waiting ring (or passed jmp) down to the
        // head of the window under it, turning in to its name.
        for (placed_items.items) |p| {
            if (p.item.what != .head or p.item.window == 0) continue;
            const from = for (placed_items.items) |q| {
                if (q.item.window + 1 == p.item.window and (q.item.state == .waiting or q.item.state == .pass)) break q;
            } else continue;
            const drawn: f32 = if (p.old != null and p.new != null) 1 else if (p.new != null) switch (kind) {
                .down => clamp01((tm - f(96)) / f(18)),
                .through => clamp01((tm - f(54)) / f(18)),
                else => clamp01(2 * going - 1),
            } else switch (kind) {
                .up => 1 - clamp01((tm - f(72)) / f(12)),
                else => 1 - clamp01(2 * going),
            };
            if (drawn <= 0) continue;
            const ya = from.y + m.row - 3;
            const yb = p.y + m.row / 2;
            u.route(&.{ .{ 14, ya }, .{ 14, yb }, .{ c.address - 4, yb } }, t.primary, .{ .width = theme.stroke.rule, .head = .{ 7, 8 }, .radius = 4, .progress = cursors.standard(drawn) });
        }
        // Its strip is the deepest window's function's column, that window framed on it.
        map.window(.disasm, deepest(after), deepest(before), cursors.glide(going));
        if (pc_y[1] orelse pc_y[0]) |y| ties.anchor(u, .pc, .{ .x = 0, .y = y, .w = theme.metric.plaque.pc, .h = m.row });
        kernel(u, now, box, under orelse top + @as(f32, @floatFromInt(room -| 3)) * m.row, pc_y[0] orelse pc_y[1]);
        context.veiled(u, box, now.veil);
        // Going down or up, the strip is another function's column: it fades through as the mark lands (24 f).
        map.strip(.disasm, if (kind == .same) u else u.faded(map.through(now, now.plan.travel + f(12))), box);
    }
};

/// The pc's plaque on the row at `y`.
fn plaqueAt(u: ui.Ui, w: f32, y: f32, shows: f32, fire: f32) void {
    if (shows <= 0) return;
    const v = u.faded(shows);
    v.current(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = m.row }, theme.metric.plaque.pc, fire);
    sk.draw.polygon(u.f, &.{ .{ 20, y + m.row / 2 }, .{ 10, y + 6 }, .{ 10, y + m.row - 6 } }, v.at.pen(.{ .fill = ui.rgb(theme.mark(.current).on_solid) }));
}

/// `waiting`: the plaque's place ringed, a 2-unit primary frame 24 by 24
/// with a primary head in it, as a waiting call node is; no wash.
fn ringAt(u: ui.Ui, y: f32) void {
    u.frame(.{ .x = c.mark + 1, .y = y + 1, .w = 22, .h = 22 }, t.primary, theme.stroke.rule);
    sk.draw.polygon(u.f, &.{ .{ 19, y + m.row / 2 }, .{ 10, y + 7 }, .{ 10, y + m.row - 7 } }, u.at.pen(.{ .fill = ui.rgb(t.primary) }));
}

fn find(items: []const Item, key: u64) ?Item {
    for (items) |it| if (it.key == key) return it;
    return null;
}

fn windowOf(items: anytype, window: u8) @TypeOf(items) {
    var lo: usize = items.len;
    var hi: usize = 0;
    for (items, 0..) |p, j| if (p.item.window == window) {
        lo = @min(lo, j);
        hi = j + 1;
    };
    return if (lo < hi) items[lo..hi] else items[0..0];
}

/// The first and last instruction of the deepest window of code.
fn deepest(l: Layout) [2]u64 {
    var window: u8 = 0;
    for (l.items) |it| if (it.what == .insn) {
        window = @max(window, it.window);
    };
    var out = [2]u64{ std.math.maxInt(u64), 0 };
    for (l.items) |it| if (it.what == .insn and it.window == window) {
        out = .{ @min(out[0], it.key), @max(out[1], it.key) };
    };
    return out;
}

const Ran = disasm.Disasm.Ran;
const RanRow = struct { addr: u64, ran: Ran };

/// The rows the last three steps ran (`base`: 1 while the mark is still
/// on the step's first row), the newest step's mark on each.
fn recentRows(a: std.mem.Allocator, now: cursors.Now, base: usize) []const RanRow {
    var out: std.ArrayList(RanRow) = .empty;
    for (0..3) |s| {
        const from = now.stops[@min(base + 1 + s, now.stops.len - 1)];
        const to = now.stops[base + s];
        var at = to;
        while (at > from and to - at < 512) {
            at -= 1;
            const pc = now.rec.register(at, "rip");
            if (ranOf(out.items, pc) == null) out.append(a, .{ .addr = pc, .ran = .{ .k = s, .at = at } }) catch break;
            // A return marks the call it comes back from: it has run, with its result.
            if (now.rec.insn_branches[at]) |b| if (b.kind == .ret) {
                var buf: [256]u8 = undefined;
                const after = now.rec.instruction(at, b.to, &buf) orelse continue;
                if (after.back == 0) continue;
                const call = b.to - after.back;
                if (ranOf(out.items, call) == null) out.append(a, .{ .addr = call, .ran = .{ .k = s, .at = madeAt(now.rec, at, call) } }) catch break;
            };
        }
    }
    return out.items;
}

fn ranOf(list: []const RanRow, addr: u64) ?Ran {
    for (list) |r| if (r.addr == addr) return r.ran;
    return null;
}

/// A level of the descent: a function's window.
const Level = struct { at: u64, kind: enum { caller, pass, deepest }, name: []const u8, moment: u64 = 0 };

/// The panel at moment `i`, `room` rows: the root's window on top, a
/// window a call deep under it, the deepest round the pc, three at most
/// (a longer chain keeps the first and the last two, the rest one row).
fn layout(u: ui.Ui, rec: *const Recording, i: u64, room: usize, root: []const u8) Layout {
    const a = u.f.scratch;
    var items: std.ArrayList(Item) = .empty;
    const pc = rec.register(i, "rip");
    var buf: [24]context.Frame = undefined;
    const chain = context.frames(rec, i, &buf);
    var r: usize = 0;
    for (chain, 0..) |fr, j| if (std.mem.eql(u8, context.frameName(u, rec, fr.pc), root)) {
        r = j;
        break;
    };
    var levels: [24]Level = undefined;
    var n: usize = 0;
    var j = r;
    while (j > 0 and n + 2 < levels.len) : (j -= 1) {
        const call = callBefore(u, rec, i, chain[j].pc) orelse break;
        levels[n] = .{ .at = call.addr, .kind = .caller, .name = context.frameName(u, rec, chain[j].pc), .moment = madeAt(rec, i, call.addr) };
        n += 1;
        // Through a stub to a function that is not it: the stub's jmp, passed.
        if (disasm.target(call)) |to| {
            const stub = context.frameName(u, rec, to);
            if (std.mem.endsWith(u8, stub, "@plt") and !std.mem.eql(u8, stub, context.frameName(u, rec, chain[j - 1].pc))) {
                levels[n] = .{ .at = to, .kind = .pass, .name = stub, .moment = madeAt(rec, i, to) };
                n += 1;
            }
        }
    }
    const here = context.frameName(u, rec, pc);
    const in_stub = std.mem.endsWith(u8, here, "@plt");
    levels[n] = .{ .at = pc, .kind = .deepest, .name = here };
    n += 1;
    // Folded past three windows: the first, then a row of `more`, then the last two.
    var fold: []const u8 = "";
    var kept: []const Level = levels[0..n];
    var kept_buf: [3]Level = undefined;
    if (n > 3) {
        fold = u.print("{d} calls:", .{n - 3});
        for (levels[1 .. n - 2]) |l| fold = u.print("{s} {s}", .{ fold, l.name });
        kept_buf = .{ levels[0], levels[n - 2], levels[n - 1] };
        kept = &kept_buf;
    }
    // At a `syscall`, or just back from one: the floor is the kernel's.
    const at_syscall = isSyscall(rec, i, pc) or (i > 0 and isSyscall(rec, i - 1, rec.register(i - 1, "rip")) and rec.register(i - 1, "rip") + 2 == pc);
    var fixed: usize = if (at_syscall and kept.len > 1) 3 else 0;
    for (kept, 0..) |l, li| {
        if (li > 0) fixed += 1;
        fixed += switch (l.kind) {
            .caller => 3,
            .pass => 1,
            .deepest => 0,
        };
    }
    if (fold.len > 0) fixed += 1;
    const remaining = room -| fixed;
    var deepest_rows = if (kept.len == 1) room else if (in_stub) @min(remaining, stubRows(rec, i, pc)) else remaining;
    const extra = remaining -| deepest_rows;
    // The nearest caller takes the rows the deepest does not use, all above
    // its call row: it keeps one row after the call, so the callee's head is
    // directly under its return row. Where its function starts first, what
    // is left goes back to the deepest window.
    var nearest_rows: usize = 3 + extra;
    if (kept.len >= 2 and kept[kept.len - 2].kind == .caller) {
        const above = disasm.listingAt(u, rec, i, kept[kept.len - 2].at, nearest_rows, nearest_rows - 2).pc;
        const short = nearest_rows - 2 - above;
        nearest_rows -= short;
        deepest_rows += short;
    }
    var row: f32 = 0;
    var tag: []const u8 = "";
    for (kept, 0..) |l, li| {
        const window: u8 = @intCast(li);
        if (li == 1 and fold.len > 0) {
            items.append(a, .{ .key = std.hash.Wyhash.hash(1, fold), .row = row, .window = window, .what = .{ .more = fold } }) catch {};
            row += 1;
        }
        if (li > 0) {
            items.append(a, .{ .key = std.hash.Wyhash.hash(0, l.name) | 1 << 63, .row = row, .window = window, .what = .{ .head = .{ .name = l.name, .note = headNote(u, rec, i, l) } } }) catch {};
            row += 1;
        }
        const nearest = li + 2 == kept.len and l.kind == .caller;
        const count: usize = switch (l.kind) {
            .caller => if (nearest) nearest_rows else 3,
            .pass => 1,
            .deepest => deepest_rows,
        };
        const above: usize = switch (l.kind) {
            .caller => count - 2,
            .pass => 0,
            // Under a `syscall` four rows hold its arguments.
            .deepest => if (in_stub) 0 else if (isSyscall(rec, i, pc) and count > 5) count - 5 else (count -| 1) / 2,
        };
        const list = disasm.listingAt(u, rec, i, l.at, count, above);
        for (list.rows, 0..) |insn, q| {
            const on = q == list.pc;
            items.append(a, .{ .key = insn.addr, .row = row + @as(f32, @floatFromInt(q)), .window = window, .what = .{ .insn = insn }, .state = if (!on) .plain else switch (l.kind) {
                .caller => .waiting,
                .pass => .pass,
                .deepest => .current,
            }, .at = l.moment }) catch {};
        }
        row += @floatFromInt(count);
        if (l.kind == .deepest) tag = if (kept.len == 1) l.name else u.print("{s} \u{00b7} {s}", .{ l.name, moduleOf(u, rec, i, pc) });
    }
    return .{ .items = items.items, .windows = kept.len, .kernel = at_syscall, .tag = tag, .in_stub = in_stub };
}

/// The call instruction a return address `ret` comes back after.
fn callBefore(u: ui.Ui, rec: *const Recording, i: u64, ret: u64) ?Insn {
    var buf: [256]u8 = undefined;
    const after = rec.instruction(i, ret, &buf) orelse return null;
    if (after.back == 0) return null;
    const at = ret - after.back;
    const call = rec.instruction(i, at, &buf) orelse return null;
    if (!std.mem.startsWith(u8, call.text, "call")) return null;
    return .{ .addr = at, .len = call.len, .text = u.print("{s}", .{call.text}) };
}

/// The moment the instruction at `addr` last ran, at or before `i`.
fn madeAt(rec: *const Recording, i: u64, addr: u64) u64 {
    var at = i;
    while (at > 0 and i - at < 4096) : (at -= 1) if (rec.register(at, "rip") == addr) return at;
    return i;
}

/// The call this step crosses with, where it was stepped over (the step
/// began on a call to libc's wrapper, not on the `syscall` itself).
fn steppedOver(now: cursors.Now) ?Recording.Syscall {
    if (!now.crossings or !now.walking()) return null;
    const made = syscalls.inStep(now) orelse return null;
    return if (isSyscall(now.rec, now.stops[1], now.rec.register(now.stops[1], "rip"))) null else made;
}

fn isSyscall(rec: *const Recording, i: u64, pc: u64) bool {
    var buf: [256]u8 = undefined;
    const here = rec.instruction(i, pc, &buf) orelse return false;
    return std.mem.eql(u8, here.text, "syscall");
}

/// How many instructions a PLT stub at `pc` has (three: its `jmp`, a push, a jmp to the resolver).
fn stubRows(rec: *const Recording, i: u64, pc: u64) usize {
    var buf: [256]u8 = undefined;
    var at = pc;
    var n: usize = 0;
    while (n < 4) : (n += 1) {
        const one = rec.instruction(i, at, &buf) orelse break;
        if (n > 0 and one.back == 0) break;
        at += one.len;
    }
    return @max(n, 1);
}

/// A window's head note: what the code is (`libc.so.6 · no source`,
/// `the PLT · its jmp reads open@got, 403fd8`, the program's file).
fn headNote(u: ui.Ui, rec: *const Recording, i: u64, l: Level) []const u8 {
    if (std.mem.endsWith(u8, l.name, "@plt")) {
        if (l.kind == .pass) return "the PLT, jumped through";
        var buf: [256]u8 = undefined;
        const jmp = rec.instruction(i, l.at, &buf) orelse return "the PLT";
        const ops = std.mem.trim(u8, jmp.text[(std.mem.indexOfScalar(u8, jmp.text, ' ') orelse jmp.text.len)..], " ");
        const at = std.mem.indexOf(u8, ops, "[rip + 0x") orelse return "the PLT";
        const close = std.mem.indexOfScalarPos(u8, ops, at, ']') orelse return "the PLT";
        const slot = l.at + jmp.len + (std.fmt.parseInt(u64, ops[at + 9 .. close], 16) catch return "the PLT");
        const named = ui.symbol(u, rec.strings.get(slot) orelse "");
        return u.print("the PLT \u{00b7} its jmp reads {s}, {x}", .{ named[0 .. std.mem.lastIndexOfScalar(u8, named, '+') orelse named.len], slot });
    }
    const module = moduleOf(u, rec, i, l.at);
    if (std.mem.eql(u8, module, "[vdso]")) return "vdso \u{00b7} the kernel's code, run here";
    var buf: [256]u8 = undefined;
    // Its source, where the build gave it: the program's own file, or the library's (its entry's: not the header a line of it is inlined from).
    const entry = if (@import("ztrace").telescope.function(rec.moment(i), l.at)) |fun| fun.start else l.at;
    if (rec.instruction(i, entry, &buf)) |here| if (here.line != null) return if (here.src == 0) rec.file else u.print("{s} \u{00b7} {s}", .{ module, rec.sources[here.src].name() });
    return u.print("{s} \u{00b7} no source", .{module});
}

/// The file `addr`'s mapping is of, by its base name.
fn moduleOf(u: ui.Ui, rec: *const Recording, i: u64, addr: u64) []const u8 {
    var name: []const u8 = "";
    var buf: [256]u8 = undefined;
    _ = (rec.moment(i).mapping(addr, &name, &buf) catch null) orelse return "";
    return u.print("{s}", .{std.fs.path.basename(name)});
}

/// The kernel's window, at the floor, while a step crosses: the crossing
/// lane down from the pc's plaque, the vellum filling down from its head,
/// the head and the call in C's form, `returns` and what crossed back
/// with what it clobbered; the answer up the lane; and at the advance the
/// window drawing back up into the lane.
fn kernel(u: ui.Ui, now: cursors.Now, box: Rect, y0: f32, pc_y: ?f32) void {
    if (!now.crossings or !now.walking()) return;
    const made = syscalls.inStep(now) orelse return;
    const rec = now.rec;
    const p = syscalls.Plan.in(now, made);
    const tm = now.time;
    const from = (pc_y orelse y0 - m.row) + m.row;
    const back_up = clamp01((tm - now.plan.advance) / f(12));
    // The lane: down 24 f from the plaque, 3 units of vellum; back into it after the window.
    const down = cursors.standard(clamp01((tm - p.enters) / syscalls.Plan.cross));
    const lane_gone = clamp01((tm - now.plan.advance - f(12)) / f(12));
    if (down > 0 and lane_gone < 1) {
        const end = std.math.lerp(from, y0 + 4, down * (1 - lane_gone));
        u.fill(.{ .x = 14 - 1.5, .y = from, .w = 3, .h = @max(end - from, 0) }, theme.color.kernel);
    }
    // The answer climbs the lane to the `syscall` row: a head of vellum going up it.
    const climb = cursors.glide(clamp01((tm - p.back) / syscalls.Plan.cross));
    if (climb > 0 and climb < 1) {
        const yh = std.math.lerp(y0, from, climb);
        sk.draw.polygon(u.f, &.{ .{ 14, yh - 8 }, .{ 7, yh + 2 }, .{ 21, yh + 2 } }, u.at.pen(.{ .fill = ui.rgb(theme.color.kernel) }));
    }
    const opens = cursors.standard(clamp01((tm - p.enters - f(18)) / f(12))) * (1 - back_up);
    if (opens <= 0) return;
    const h = 3 * m.row * opens;
    u.fill(.{ .x = theme.stroke.rule, .y = y0, .w = box.w - 2 * theme.stroke.rule, .h = h }, theme.color.kernel);
    u.clip(.{ .x = 0, .y = y0, .w = box.w, .h = h });
    defer u.unclip();
    // The lane's head, in ink on the vellum.
    sk.draw.polygon(u.f, &.{ .{ 14, y0 + 10 }, .{ 10, y0 + 2 }, .{ 18, y0 + 2 } }, u.at.pen(.{ .fill = ui.rgb(k.ink) }));
    const name = @import("ztrace").syscalls.name(made.nr) orelse "syscall";
    const head = u.faded(clamp01((tm - p.enters - f(30)) / f(6)));
    head.text(.sans_medium, theme.size.sans.micro, c.address, y0 + 18, "the kernel", k.ink);
    const what = u.print("{s}, system call {d}", .{ name, made.nr });
    head.text(.sans, theme.size.sans.micro, box.w - m.side - u.width(.sans, theme.size.sans.micro, what), y0 + 18, what, k.dim);
    // The call in C's form, as the kernel took it.
    const names = @import("ztrace").syscalls.names(made.nr);
    const n = @min(@import("ztrace").syscalls.signature(made.nr).len, 6);
    var call: []const u8 = u.print("{s}(", .{name});
    for (0..n) |j| call = u.print("{s}{s}{s}", .{ call, if (j > 0) ", " else "", disasm.argument(u, rec, made.enter, if (j < names.len) names[j] else "", made.args[j]) });
    call = u.print("{s})", .{call});
    u.faded(clamp01((tm - p.enters - f(36)) / f(6))).text(.mono, size, c.address, rows.baseline(y0 + m.row), rows.fitted(u, call, box.w - m.side - c.address), k.ink);
    // `returns`: the value, struck as it lands in the kernel's rows.
    const ry = y0 + 2 * m.row;
    const returns = tm - p.returns;
    u.faded(clamp01((tm - p.enters - f(36)) / f(6))).text(.mono, size, c.address, rows.baseline(ry), "returns", k.dim);
    if (returns >= 0 and made.exit != null) {
        const got: i64 = @bitCast(made.result);
        const value = u.print("{d}", .{got});
        const x = c.address + 8 * adv;
        const cell: Rect = .{ .x = x, .y = ry, .w = @as(f32, @floatFromInt(value.len)) * adv, .h = m.row };
        const heat = now.heat(0, null, returns);
        const ink = u.written(cell, heat) orelse ui.Ink{ .ink = ui.rgb(k.ink) };
        u.text(ink.face, size, x, rows.baseline(ry), value, ink.ink);
        var end = x + cell.w + adv;
        const on = rec.openOn(u.f.scratch, made.result, made.exit.? + 1);
        if (std.mem.eql(u8, name, "openat") or std.mem.eql(u8, name, "open")) if (on.len > 0) {
            u.text(.mono, size, end, rows.baseline(ry), on, k.dim);
            end += u.width(.mono, size, on) + 2 * adv;
        };
        u.text(.mono, size, end + adv, rows.baseline(ry), "rcx, r11: clobbered", k.dim);
    }
}