summaryrefslogtreecommitdiff
path: root/anim/src/context.zig
blob: 2e86399594bc73f61859c9202d42c4d92a0c885f (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
//! The state column (design/README.md, "3. Panels"): `registers`, all
//! seventeen, each followed as far as it points; `stack`, the words from
//! rsp with the frames they belong to as `call` spans down its right edge
//! and the registers that point at a word as `pin`s in its lane; and
//! `backtrace`, the call chain as rows, a panel of its own only in the
//! `none` split. Ink says what a thing is, paper what happened to it.
//! Reads `Moment.regs`, `Moment.read`, the mappings (through
//! `zt.telescope`), and the names the debugger recorded.
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 syscalls = @import("syscalls.zig");
const ties = @import("ties.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;

pub const ink = rows.ink;
pub const regionOf = rows.regionOf;

/// The registers' tag: the legend of what an address's ink says, always on screen, as pwndbg's is.
pub const legend = blk: {
    const c = theme.color.region;
    break :blk [_]ui.Legend{
        .{ .text = "stack", .ink = ui.rgb(c.stack) },
        .{ .text = "heap", .ink = ui.rgb(c.heap) },
        .{ .text = "code", .ink = ui.rgb(c.code_) },
        .{ .text = "data", .ink = ui.rgb(c.data) },
        .{ .text = "rwx", .ink = ui.rgb(c.data), .under = true },
        .{ .text = "read-only", .ink = ui.rgb(c.rodata) },
    };
};

/// A panel's `Ui`, moved to where the stage has its box now.
pub fn at(f: *sk.Frame, placed: anim.Placed, box: Rect) ui.Ui {
    return (ui.Ui{ .f = f, .at = placed }).moved(box.x, box.y);
}

pub fn veiled(u: ui.Ui, box: Rect, amount: f32) void {
    // Staging: what cannot be read at a sprint is dimmed, not removed.
    u.veil(.{ .x = theme.stroke.rule, .y = m.tag, .w = box.w - 2 * theme.stroke.rule, .h = box.h - m.tag - theme.stroke.rule }, amount);
}

/// The rows a panel `box` shows: while a relayout moves it, one more, cut by its edge.
pub fn rowsOf(box: Rect) usize {
    return @intFromFloat(@max(@ceil((box.h - m.tag - 2 * m.pad) / m.row), 0));
}

pub fn clipBody(u: ui.Ui, box: Rect) void {
    u.clip(.{ .x = theme.stroke.rule, .y = m.tag + m.pad - 1, .w = box.w - 2 * theme.stroke.rule, .h = box.h - m.tag - 2 * m.pad + 2 });
}

pub const Registers = struct {
    cursor: cursors.Cursor,
    stage: *const Stage,
    /// A step that makes a system call frames, as read, the registers
    /// that carry it, one at a time; and rax is struck when it returns.
    syscalls: bool = false,
    /// No strikes: for a program whose instrumentation uses the registers
    /// between any two lines, so that nearly all of them change at every one.
    quiet: bool = false,
    focus: bool = false,

    const Shown = struct { regs: zt.Regs, moment: Recording.Moment };

    pub fn draw(r: *const Registers, f: *sk.Frame, placed: anim.Placed) void {
        const box = r.stage.box(placed, .registers);
        const u = at(f, placed, box);
        const now = r.cursor.now(placed);
        const rec = r.cursor.rec;
        const is: Shown = .{ .regs = (now.moment().regs(rec.tid) catch null) orelse zt.Regs{}, .moment = now.moment() };
        const was: Shown = .{ .regs = (now.before().regs(rec.tid) catch null) orelse is.regs, .moment = now.before() };
        const body = u.panel(box.w, box.h, "registers", .{ .focus = r.focus, .legend = &legend });
        // A link leaves from the panel's edge, not through a name.
        ties.anchor(u, .registers, .{ .x = 0, .y = 0, .w = box.w, .h = box.h });
        clipBody(u, box);
        defer u.unclip();
        const shown = @min(rowsOf(box), theme.metric.all_registers.len);
        // Overlapping action: of the registers one step wrote, each strikes 2 f after the one above it.
        for (theme.metric.all_registers[0..shown], 0..) |name, i| {
            const y = body.y + m.pad + @as(f32, @floatFromInt(i)) * m.row;
            if (std.mem.eql(u8, name, "rip")) {
                r.rip(u, now, y, box.w, is, was);
                continue;
            }
            r.row(u, now, is, was, name, y, box.w);
        }
        veiled(u, box, now.veil);
    }

    fn shownAt(rec: *const Recording, i: u64) ?Shown {
        const moment = rec.moment(i);
        return .{ .regs = (moment.regs(rec.tid) catch return null) orelse return null, .moment = moment };
    }

    /// rip: where execution is, a current mark like the source's and the
    /// disassembly's; it moves with them, at the advance.
    fn rip(r: *const Registers, u: ui.Ui, now: cursors.Now, y: f32, w: f32, is: Shown, was: Shown) void {
        const rec = r.cursor.rec;
        const moment = now.marks[if (now.advancing() >= 0.5) 1 else 0];
        // The flags' ticks are secondary: 6 f after the registers strike, not with them.
        const landed = now.landed(.cpu, cursors.write_apart);
        const flags = (if (landed) is else was).regs.eflags;
        // The flags a step changed are ticked, for three steps.
        const eflags_index = comptime index("eflags").?;
        // Until this step's change lands, the ticks are the last one's: no effect before its cause.
        const age = if (landed) now.registerAge(eflags_index) else now.registerAgeFrom(eflags_index, 1);
        var changed: u64 = 0;
        if (age) |a| changed = rec.register(now.stops[a], "eflags") ^ rec.register(now.stops[a + 1], "eflags");
        const held = if (r.quiet) 0 else now.register(eflags_index, cursors.write_apart).level;
        rows.rip(u, y, w, rec.moment(moment), rec.register(moment, "rip"), flags, changed, held, 0);
    }

    fn row(r: *const Registers, u: ui.Ui, now: cursors.Now, line_is: Shown, line_was: Shown, name: []const u8, y: f32, w: f32) void {
        const rec = r.cursor.rec;
        const i = index(name) orelse return;
        // Every register is the program's, at its line stops, as every
        // other panel is: what crossed into the kernel is the crossing's
        // to show, and a register is framed as carrying it only where it
        // still holds what crossed.
        const is = line_is;
        const was = line_was;
        const value_now = is.regs.named(name) orelse return;
        const value_was = was.regs.named(name) orelse value_now;
        var marks: rows.Marks = .{};
        var landed = now.landed(.cpu, 0);
        var note: []const u8 = "";
        const crossing: ?Recording.Syscall = if (r.syscalls) syscalls.inStep(now) else null;
        // A register is framed as carrying the call only while it holds the
        // argument in the moment shown: the stop before the call, until the
        // call is back. (Set by the wrapper, between the stops, it carried
        // it where no stop saw it: the kernel's rows say it.)
        const carrier: ?usize = if (crossing) |made| for (syscalls.carried(made), 1..) |carried, k| {
            if (std.mem.eql(u8, carried, name) and value_was == made.args[k - 1]) break k;
        } else null else null;
        if (carrier) |k| if (crossing) |made| {
            const framed = now.time - syscalls.Plan.of(made).registers - @as(f32, @floatFromInt(k - 1)) * time.flight.second;
            marks.read = 0;
            marks.read_shows = @min(std.math.clamp(framed / time.read.in, 0, 1), now.reading(.cpu, 0));
            // A descriptor says what it is open on: the `value` class `fd`.
            const names = zt.syscalls.names(made.nr);
            if (k <= names.len and std.mem.endsWith(u8, names[k - 1], "fd")) note = rec.openOn(u.f.scratch, value_was, made.enter);
        };
        if (if (std.mem.eql(u8, name, "rax")) crossing else null) |made| {
            // rax: what was there, then the result, once the kernel's rows
            // have said it (the call's number went in at the wrapper).
            const back = now.time - syscalls.Plan.of(made).struck;
            const result = back >= time.strike.in / 2.0;
            const value: u64 = if (result) value_now else value_was;
            if (back >= -time.strike.arm) {
                marks = .{ .first = now.heat(0, null, back) };
                if (back >= 0 and now.walking()) marks.extend = back;
            }
            const hops = rows.reg(u, y, w, name, if (result) is.moment else was.moment, value, marks);
            // What `open` gave back is a descriptor: the `value` class
            // `fd`, this call's once it is back, the last one's before.
            const gave = if (result) made else if (syscalls.latest(rec, now.stops[1])) |n| rec.syscalls[n] else null;
            if (gave) |g| if (g.exit != null and g.result == value and std.mem.eql(u8, zt.syscalls.name(g.nr) orelse "", "open")) fdNote(u, hops, y, rec.openOn(u.f.scratch, value, g.exit.? + 1));
            return anchor(u, i, hops, y);
        } else if (r.quiet) {
            // Unmarked: the values change as the mark moves on.
            landed = now.advancing() >= 0.5;
        } else {
            const age = now.registerAge(i);
            // (In a step that crosses into the kernel, what else the line
            // changed is seen after the call is back, after rax: `strikeDelay`.)
            const delay = if (age == 0) ties.strikeDelay(now, i) else 0;
            landed = now.landed(.cpu, delay);
            marks.first = now.register(i, delay);
            // A register written: the rest of its chain is followed again.
            const since = now.since(.cpu, delay);
            if (age == 0 and now.walking() and since >= 0) marks.extend = since;
        }
        const hops = rows.reg(u, y, w, name, if (landed) is.moment else was.moment, if (landed) value_now else value_was, marks);
        fdNote(u, hops, y, note);
        anchor(u, i, hops, y);
    }

    /// The `fd` class's note after a register's value: faint, what it is open on.
    fn fdNote(u: ui.Ui, hops: rows.Hops, y: f32, on: []const u8) void {
        if (hops.n > 0 and on.len > 0) u.text(.mono, theme.size.mono.context, hops.end + 8, rows.baseline(y), on, t.faint);
    }

    fn anchor(u: ui.Ui, i: usize, hops: rows.Hops, y: f32) void {
        if (hops.n > 0) ties.anchor(u, .{ .register = i }, .{ .x = hops.x[0], .y = y, .w = hops.w[0], .h = m.row });
    }
};

/// A register's place in `Regs.names`.
pub fn index(name: []const u8) ?usize {
    for (zt.Regs.names, 0..) |known, i| if (std.mem.eql(u8, known, name)) return i;
    return null;
}

/// One frame of the call chain, on the stack: its function's pc, and the
/// slots that are the frame, from `lo` to `hi` (the last; null: its end is
/// not known, past what the recording holds).
pub const Frame = struct { pc: u64, lo: u64, hi: ?u64 };

/// The frames at moment `i`, newest first, with their extents, as the
/// tracer reads them off the frame-pointer chain.
pub fn frames(rec: *const Recording, i: u64, out: []Frame) []Frame {
    const moment = rec.moment(i);
    const regs = (moment.regs(rec.tid) catch return out[0..0]) orelse return out[0..0];
    var buf: [24]zt.Debugger.Frame = undefined;
    const found = zt.telescope.frames(moment, &regs, buf[0..@min(buf.len, out.len)]) catch return out[0..0];
    for (found, out[0..found.len]) |f, *o| o.* = .{ .pc = f.pc, .lo = f.low, .hi = if (f.high > f.low) f.high - 8 else null };
    return out[0..found.len];
}

/// A frame's span on the stack: its function's name, and as a call its
/// argument where it takes one (`fib(4)`): the digits on its node.
fn spanName(u: ui.Ui, rec: *const Recording, open: []const Recording.Call, i: usize, pc: u64) []const u8 {
    const name = frameName(u, rec, pc);
    if (i >= open.len) return name;
    const call = open[open.len - 1 - i];
    if (!std.mem.eql(u8, rec.name(call.function), name)) return name;
    const takes = for (rec.functions) |f| {
        if (std.mem.eql(u8, f.name, name)) break f.takes;
    } else false;
    const arg = call.arg orelse return name;
    if (!takes) return name;
    const v = ui.Value.of(arg, rows.regionOf(rec.moment(call.enter), arg) != .none);
    // A small number in decimal, as on the node; anything else as its class has it.
    return if (v.decimal) u.print("{s}({d})", .{ name, arg }) else u.print("{s}({s}{s})", .{ name, v.prefix, v.digits() });
}

/// Frame `i`'s arguments, from the call the recording knows it to be
/// (the `i`th open call from the newest, when it is of this frame's
/// function): "" where it knows none.
pub fn callArguments(u: ui.Ui, rec: *const Recording, open: []const Recording.Call, i: usize, pc: u64) []const u8 {
    if (i >= open.len) return "";
    const call = open[open.len - 1 - i];
    if (!std.mem.eql(u8, rec.name(call.function), frameName(u, rec, pc))) return "";
    return @import("calls.zig").arguments(u, rec, call);
}

/// Where frame `i` is in the program's source, `file:line`: the newest at
/// the moment's own line, when the moment is on one (in a library it is
/// not); an older one where the recording knows its return address's.
pub fn frameWhere(u: ui.Ui, rec: *const Recording, moment: u64, i: usize, pc: u64) []const u8 {
    const line = if (i == 0) rec.ownLine(moment) else rec.lineOf(pc);
    return if (line) |l| u.print("{s}:{d}", .{ rec.file, l }) else "";
}

/// A frame's name: its function's (no offset), or its module's and offset where there is no symbol.
pub fn frameName(u: ui.Ui, rec: *const Recording, pc: u64) []const u8 {
    const name = rec.strings.get(pc) orelse return u.print("{x}", .{pc});
    if (std.mem.indexOfScalar(u8, name, '!') != null) return ui.symbol(u, name);
    return name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len];
}

/// The registers (of the sixteen) that hold `addr` in `regs`.
fn pointing(u: ui.Ui, regs: zt.Regs, addr: u64) []const []const u8 {
    var out: std.ArrayList([]const u8) = .empty;
    for (theme.metric.all_registers[0..16]) |name| {
        if (regs.named(name) == addr) out.append(u.f.scratch, name) catch break;
    }
    return out.items;
}

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

    pub fn draw(k: *const Stack, f: *sk.Frame, placed: anim.Placed) void {
        const box = k.stage.box(placed, .stack);
        const u = at(f, placed, box);
        const now = k.cursor.now(placed);
        const rec = k.cursor.rec;
        const slots = rowsOf(box);
        const is = (now.moment().regs(rec.tid) catch null) orelse return;
        const was = (now.before().regs(rec.tid) catch null) orelse is;
        // The window: from rsp, or further into the frame ([rsp, rbp+16))
        // when that is longer than the panel, so that the word the last
        // steps touched is in its middle. When a step moves it the rows
        // slide, with the stack's words, a level after the registers.
        // Under the camera the window holds still, `free` words above the
        // rsp it was held at: pushes fill them, and rsp's pin climbs.
        const hold = placed.value(k.stage.hold);
        const held = hold >= 0;
        const held_at: u64 = if (held) rec.register(@intFromFloat(hold), "rsp") -% 8 * @as(u64, @intFromFloat(placed.value(k.stage.hold_free))) else 0;
        var window = if (held) [2]u64{ held_at, held_at } else [2]u64{ windowAt(now, is, slots, 0), windowAt(now, was, slots, 1) };
        // A window that goes further than its rows can slide (a continue
        // to a stop deeper or shallower than a call is): the old rows fade
        // out before memory strikes and the new ones in after, each with
        // the memory of its own stop.
        const landed = now.landed(.memory, 0);
        const jumped = @abs(@as(f32, @floatFromInt(@as(i64, @bitCast(window[0] -% window[1])))) / 8) > 16;
        const since_memory = now.since(.memory, 0);
        const jump_shows: f32 = if (!jumped or now.resting()) 1 else if (!landed) 1 - std.math.clamp((since_memory + time.quick) / time.quick, 0, 1) else std.math.clamp((since_memory - time.strike.in / 2.0) / time.quick, 0, 1);
        if (jumped) window = if (landed) .{ window[0], window[0] } else .{ window[1], window[1] };
        const v = u.faded(jump_shows);
        // Going to the hold and coming from it, the rows scroll: the
        // remaining way, in rows, from where the window would be.
        const natural = windowAt(now, is, slots, 0);
        const hold_scroll: f32 = if (held) @as(f32, @floatFromInt(@as(i64, @bitCast(held_at -% natural)))) / 8 * (1 - cursors.glide(placed.value(k.stage.hold_in))) else 0;
        // From rsp, or the range shown when the window is elsewhere: in
        // bytes from rsp, as the catalogue writes it (`rsp+20 to rsp+48`).
        const from_rsp: i64 = if (landed) @bitCast(window[0] -% is.rsp) else @bitCast(window[1] -% was.rsp);
        const offset = struct {
            fn of(u_: ui.Ui, d: i64) []const u8 {
                return if (d == 0) "rsp" else if (d > 0) u_.print("rsp+{x}", .{@as(u64, @intCast(d))}) else u_.print("rsp-{x}", .{@as(u64, @intCast(-d))});
            }
        }.of;
        const words = switch (slots) {
            4 => "four",
            6 => "six",
            8 => "eight",
            else => u.print("{d}", .{slots}),
        };
        const range = if (from_rsp == 0) u.print("{s} words from rsp", .{words}) else u.print("{s} to {s}", .{ offset(u, from_rsp), offset(u, from_rsp + 8 * @as(i64, @intCast(slots))) });
        const body = u.panel(box.w, box.h, "stack", .{ .focus = k.focus, .note = u.print("{s} \u{00b7} the frames they belong to", .{range}) });
        const p = cursors.glide(now.moving(.memory, 0, time.move));
        const moved = @as(f32, @floatFromInt(@as(i64, @bitCast(window[0] -% window[1])))) / 8;
        const slide: f32 = (if (@abs(moved) > 16) 0 else moved * (1 - p)) + hold_scroll;
        const top = body.y + m.pad;
        clipBody(u, box);
        defer u.unclip();
        // The addresses' shared digits: the rows read by their ends, of the
        // window shown (it changes with the slide, not before it).
        const shown_at = if (landed) window[0] else window[1];
        const lead = ui.shared(&.{ shown_at, shown_at + 8 * @as(u64, slots) });
        const memory = now.shown(.memory);
        // rsp and rbp, moved by the step with no link to land: their tags
        // travel down the lane from the old word to the new, with the slide.
        var travel_buf: [2][]const u8 = undefined;
        var travelling: usize = 0;
        for ([_][]const u8{ "rsp", "rbp" }) |name| if (!now.resting() and !jumped and was.named(name) != is.named(name)) {
            travel_buf[travelling] = name;
            travelling += 1;
        };
        const travel = travel_buf[0..travelling];
        // The backtrace, drawn on the words that are each frame: each span
        // glides from the frame's old extent to its new one with the slide.
        // Worked out first: a name longer than the spans' room takes room
        // from the chains of the rows beside it, which end before it.
        var buf: [16]Frame = undefined;
        var old_buf: [16]Frame = undefined;
        const chain = frames(rec, now.stops[if (jumped and !landed) 1 else 0], &buf);
        const old_chain = frames(rec, now.stops[if (jumped and landed) 0 else 1], &old_buf);
        // Placed as the rows are: against the window after the step, and slid.
        const open_calls = rec.stack(u.f.scratch, if (landed) now.stops[0] else now.stops[1]);
        const named = if (landed) chain else old_chain;
        const rows_of = struct {
            fn at(addr: u64, base: u64) f32 {
                return @as(f32, @floatFromInt(@as(i64, @bitCast(addr -% base)))) / 8;
            }
        }.at;
        const Span = struct { y0: f32, y1: f32, name: []const u8, newest: bool, open: bool };
        var spans: [16]Span = undefined;
        var n_spans: usize = 0;
        for (chain, 0..) |frame, i| {
            const old_frame = if (i < old_chain.len) old_chain[i] else frame;
            const first = std.math.lerp(rows_of(old_frame.lo, window[0]), rows_of(frame.lo, window[0]), p) + slide;
            if (first >= @as(f32, @floatFromInt(slots))) break;
            const last = if (frame.hi) |hi| std.math.lerp(if (old_frame.hi) |oh| rows_of(oh, window[0]) else rows_of(hi, window[0]), rows_of(hi, window[0]), p) + slide else std.math.inf(f32);
            if (last < 0) continue;
            const open = last >= @as(f32, @floatFromInt(slots));
            const y1 = top + (@min(last, @as(f32, @floatFromInt(slots)) - 1) + 1) * m.row;
            spans[n_spans] = .{ .y0 = top + @max(first, 0) * m.row, .y1 = y1, .name = spanName(u, rec, open_calls, i, if (i < named.len) named[i].pc else frame.pc), .newest = i == 0, .open = open };
            n_spans += 1;
        }
        // rsp or rbp travelling alone keeps its place in the pin it leaves and
        // the one it joins: room there, closing and opening as it goes.
        const going = cursors.standard(if (now.resting()) 1 else std.math.clamp(now.since(.cpu, ties.strikeDelay(now, index("rsp").?)) / time.move, 0, 1));
        const size = theme.size.mono.context;
        const lone: ?[]const u8 = if (travel.len == 1) travel[0] else null;
        var n: i64 = @as(i64, @intFromFloat(@floor(-slide))) - 1;
        while (n <= @as(i64, @intCast(slots)) - @as(i64, @intFromFloat(@floor(slide)))) : (n += 1) {
            const y = top + (@as(f32, @floatFromInt(n)) + slide) * m.row;
            if (y + m.row < body.y or y > box.h) continue;
            const addr = window[0] +% @as(u64, @bitCast(n * 8));
            // Who points here: a pin in the lane, landing with its link.
            const names = pins(u, now, is, was, addr, travel);
            var marks: rows.Marks = .{ .lead = lead, .first = now.written(addr, 8, .memory, 0) };
            if (now.wasRead(addr, 8) and now.writeAge(addr, 8) != 0) {
                marks.read = 0;
                marks.read_shows = now.reading(.memory, 0);
            }
            // `free`: above rsp, not yet reached: its address at 60%, its word faint.
            if (held and addr < (if (landed) is.rsp else was.rsp)) {
                rows.free(v, y, memory, addr, lead);
                continue;
            }
            // A frame's name beside this row: the chain ends a character before it.
            var room_w = box.w;
            for (spans[0..n_spans]) |sp| {
                const mid = (sp.y0 + sp.y1) / 2;
                if (mid + m.row / 2 > y and mid - m.row / 2 < y + m.row) room_w = @min(room_w, rows.spanNameX(u, box.w, sp.name) - ui.advance(theme.size.mono.context) + theme.metric.slot.room);
            }
            var gap: f32 = 0;
            if (lone) |name| {
                const share: f32 = if (was.named(name) == addr) 1 - going else if (is.named(name) == addr) going else 0;
                gap = share * (u.width(.mono, size, name) + ui.advance(size));
            }
            const gapped = gap > 0 and names.names.len > 0 and names.shows > 0;
            if (gapped) pinGap(v.faded(names.shows), y, names.names, lone.?, gap);
            const hops = rows.slot(v, y, room_w, memory, addr, if (gapped) &.{} else names.names, names.shows, marks);
            // Only a row on show is a place a tie can land.
            if (y >= top - 1 and y + m.row <= box.h - m.pad + 1) {
                ties.anchor(u, .{ .word = addr }, .{ .x = theme.metric.slot.chain, .y = y, .w = if (hops.n > 0) hops.x[0] + hops.w[0] - theme.metric.slot.chain else 120, .h = m.row });
                ties.anchor(u, .{ .slot_pin = addr }, .{ .x = theme.metric.slot.lane, .y = y, .w = theme.metric.slot.lane_end - theme.metric.slot.lane, .h = m.row });
            }
        }
        // Where the window is, for a link to a word outside it.
        const lane_at = u.at.xf.apply(.{ theme.metric.slot.lane, top });
        const row_px = u.at.xf.apply(.{ 0, top + m.row })[1] - lane_at[1];
        ties.stack_window = .{ .first = window[0], .slots = slots, .x = lane_at[0], .top = lane_at[1], .row = row_px };
        // The travelling tags: both of them at one word share a pin.
        var places: [2]f32 = undefined;
        for (travel, places[0..travel.len]) |name, *place| {
            const at_old = @as(f32, @floatFromInt(@as(i64, @bitCast((was.named(name) orelse 0) -% window[0])))) / 8 + slide;
            const at_new = @as(f32, @floatFromInt(@as(i64, @bitCast((is.named(name) orelse 0) -% window[0])))) / 8 + slide;
            place.* = std.math.lerp(at_old, at_new, going);
        }
        for (travel, places[0..travel.len], 0..) |name, place, i| {
            if (i == 1 and @abs(places[0] - place) < 0.05) continue;
            if (place < -0.5 or place > @as(f32, @floatFromInt(slots)) - 0.5) continue;
            const both = i == 0 and travel.len == 2 and @abs(places[1] - place) < 0.05;
            // Alone, from its place among the names it leaves to its place among those it joins.
            const x = if (lone != null) std.math.lerp(pinPlace(u, pins(u, now, is, was, was.named(name) orelse 0, travel).names, name), pinPlace(u, pins(u, now, is, was, is.named(name) orelse 0, travel).names, name), going) else theme.metric.slot.lane;
            u.pinRow(x, top + place * m.row, if (both) &.{ "rsp", "rbp" } else &.{name}, theme.color.region.stack);
        }
        for (spans[0..n_spans]) |sp| rows.span(v, box.w, sp.y0, sp.y1, sp.name, sp.newest, sp.open);
        veiled(u, box, now.veil);
    }

    /// Where `name` goes in a row pin of `others` and it, in the registers' order.
    fn pinPlace(u: ui.Ui, others: []const []const u8, name: []const u8) f32 {
        const size = theme.size.mono.context;
        var x: f32 = theme.metric.slot.lane;
        for (others) |o| if (index(o).? < index(name).?) {
            x += u.width(.mono, size, o) + ui.advance(size);
        };
        return x;
    }

    /// A row pin of `names` with room `gap` wide where `name` goes in it.
    fn pinGap(u: ui.Ui, y: f32, names: []const []const u8, name: []const u8, gap: f32) void {
        const size = theme.size.mono.context;
        const p = theme.metric.pin;
        var x: f32 = theme.metric.slot.lane;
        var gapped = false;
        for (names) |o| {
            if (!gapped and index(o).? > index(name).?) {
                x += gap;
                gapped = true;
            }
            u.text(.mono_bold, size, x, theme.baseline(y, m.row, size), o, t.primary);
            x += u.width(.mono, size, o) + ui.advance(size);
        }
        if (!gapped) x += gap;
        const hx = x - ui.advance(size) + p.row_gap;
        const mid = y + m.row / 2;
        sk.draw.polygon(u.f, &.{ .{ hx + p.row_head[0], mid }, .{ hx, mid - p.row_head[1] / 2 }, .{ hx, mid + p.row_head[1] / 2 } }, u.at.pen(.{ .fill = ui.rgb(theme.color.region.stack) }));
    }

    /// The first word a window of `slots` shows, `skip` steps back: rsp,
    /// or within [rsp, rbp+16) (the frame, with its saved rbp and its way
    /// back) so that the word the newest of the last three steps wrote or
    /// read there is in the window's middle.
    fn windowAt(now: cursors.Now, regs: zt.Regs, slots: usize, skip: usize) u64 {
        const frame_end = regs.rbp +% 16;
        if (frame_end <= regs.rsp or frame_end - regs.rsp > 8 * 64) return regs.rsp;
        const words = (frame_end - regs.rsp) / 8;
        if (words <= slots) return regs.rsp;
        for (skip..skip + 3) |age| {
            if (age + 1 >= now.stops.len) break;
            for ([_][]const Recording.Span{ now.rec.written(now.stops[age + 1], now.stops[age]), now.rec.read(now.stops[age + 1], now.stops[age]) }) |spans| {
                var k = spans.len;
                while (k > 0) {
                    k -= 1;
                    const a = spans[k].addr;
                    if (a < regs.rsp or a >= frame_end) continue;
                    const word = (a - regs.rsp) / 8;
                    const first = @min(word -| (slots - 1) / 2, words - slots);
                    return regs.rsp + 8 * first;
                }
            }
        }
        return regs.rsp;
    }

    const Pins = struct { names: []const []const u8, shows: f32 };

    /// The registers whose value is `addr`: before the step, and after it
    /// once their link has landed (`ties.pinShows`).
    fn pins(u: ui.Ui, now: cursors.Now, is: zt.Regs, was: zt.Regs, addr: u64, apart: []const []const u8) Pins {
        var out: std.ArrayList([]const u8) = .empty;
        var shows: f32 = 0;
        for (theme.metric.all_registers[0..16]) |name| {
            // Those drawn apart, travelling.
            if (for (apart) |a| {
                if (std.mem.eql(u8, a, name)) break true;
            } else false) continue;
            const i = index(name).?;
            const before = was.named(name) == addr;
            const after = is.named(name) == addr;
            if (!before and !after) continue;
            const s = ties.pinShows(now, i, .slot);
            const this = if (before and after) 1 else if (after) s.new else s.old;
            if (this < 0.5) continue;
            out.append(u.f.scratch, name) catch break;
            shows = @max(shows, this);
        }
        return .{ .names = out.items, .shows = shows };
    }
};

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

    pub fn draw(b: *const Backtrace, f: *sk.Frame, placed: anim.Placed) void {
        const box = b.stage.box(placed, .backtrace);
        if (box.h < m.tag) return;
        const u = at(f, placed, box);
        const now = b.cursor.now(placed);
        const rec = b.cursor.rec;
        // A frame is its words on the stack: the chain changes with memory.
        // The frames both chains have (the same way back, counted from the
        // oldest) slide to their new depth, as rows making room; those that
        // end fade out first, those that begin fade in after.
        var new_buf: [24]Frame = undefined;
        var old_buf: [24]Frame = undefined;
        const chains = [2][]Frame{ frames(rec, now.stops[1], &old_buf), frames(rec, now.stops[0], &new_buf) };
        var shared: usize = 0;
        while (shared < @min(chains[0].len, chains[1].len) and chains[0][chains[0].len - 1 - shared].pc == chains[1][chains[1].len - 1 - shared].pc) shared += 1;
        const since = if (now.walking()) now.since(.memory, 0) else if (now.landed(.memory, 0)) std.math.inf(f32) else -std.math.inf(f32);
        const leave = std.math.clamp(since / time.quick, 0, 1);
        const slide = cursors.glide(std.math.clamp((since - time.quick / 2.0) / time.move, 0, 1));
        const arrive = std.math.clamp((since - time.quick / 2.0 - time.move) / time.quick, 0, 1);
        const room = rowsOf(box);
        const total = chains[if (slide >= 0.5) 1 else 0].len;
        const body = u.panel(box.w, box.h, "backtrace", .{ .focus = b.focus, .note = if (total > room) u.print("newest on top \u{00b7} {d} more", .{total - room}) else "newest on top" });
        clipBody(u, box);
        defer u.unclip();
        const opens = [2][]const Recording.Call{ rec.stack(u.f.scratch, now.stops[1]), rec.stack(u.f.scratch, now.stops[0]) };
        const top = body.y + m.pad;
        for (chains, 0..) |chain, side| {
            const shows = if (side == 0) 1 - leave else arrive;
            for (chain[0..@min(chain.len, room + shared)], 0..) |frame, i| {
                const from_end = chain.len - 1 - i;
                const kept = from_end < shared;
                // A frame both have is drawn once, from the old chain to its place in the new.
                if (kept and side == 1) continue;
                var at_row: f32 = @floatFromInt(i);
                var depth = i;
                var which = side;
                if (kept) {
                    const to = chains[1].len - 1 - from_end;
                    at_row = std.math.lerp(at_row, @as(f32, @floatFromInt(to)), slide);
                    if (slide >= 0.5) {
                        depth = to;
                        which = 1;
                    }
                } else if (shows <= 0) continue;
                if (at_row >= @as(f32, @floatFromInt(room))) continue;
                const v = if (kept) u else u.faded(shows);
                const name = ui.symbol(u, rec.strings.get(frame.pc) orelse u.print("{x}", .{frame.pc}));
                rows.callRow(v, top + at_row * m.row, box.w, depth, name, callArguments(u, rec, opens[which], depth, frame.pc), frameWhere(u, rec, if (which == 1) now.marks[1] else now.marks[0], depth, frame.pc), depth == 0);
            }
        }
        veiled(u, box, now.veil);
    }
};

test "the flags' bits" {
    try std.testing.expectEqual(@as(?usize, 17), index("eflags"));
}