summaryrefslogtreecommitdiff
path: root/anim/src/syscalls.zig
blob: c00aec5b5576b8ac653aeef535bdb6f73cc4032b (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
//! The other side of a system call. `Crossing` is the kernel as a lens,
//! on solid vellum: the call the current
//! step made, decoded (its name, each argument in the register that
//! carried it, what it pointed at, and what came back in rax), the calls
//! before it, and the arrow that crosses the line and returns. `Timeline`
//! is the same boundary from far away: every call of the run as a block
//! under the line, the current one in gold.
//! Both read the recording's index of `syscall_enter` and `syscall_exit`.
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 context = @import("context.zig");
const hexdump = @import("hexdump.zig");
const Stage = @import("stage.zig").Stage;
const theme = ui.theme;
const time = theme.time;
const Rect = ui.Rect;

/// A crossing's timetable, in seconds into its step (design/motion.md, "A
/// system call"). Staging, one thing at a time and no effect before its
/// cause: the line fires; the registers that carry the call are framed,
/// one by one; the arrow goes down through the line; only then does the
/// kernel's side change, the last call giving way to this one, its name,
/// its rows, its card; the work is done a byte at a time (a call with
/// none skips it); the kernel's rows say what it returns, the arrow comes
/// back with it, and it strikes rax as the arrow lands. So a call is as
/// long as what it does: `close` 3.9 s, a `read` of fifteen bytes 5.0.
pub const Plan = struct {
    registers: f32 = time.cascade,
    enters: f32 = 0.80,
    /// The kernel's side: the last call out, this one's name in, its
    /// rows (one every `row`), its card pushed.
    leaves: f32 = 1.00,
    name: f32 = 1.20,
    rows: f32 = 1.40,
    card: f32 = 1.70,
    /// The work: a flow between the kernel and the program's bytes, then
    /// the bytes, one every `byte`, `bytes` of them.
    work: f32 = 2.00,
    fills: f32 = 2.40,
    bytes: f32 = 0,
    /// The `returns` row takes the value 6 f before the arrow back sets
    /// off (the kernel answers before the answer travels); rax is armed
    /// while the arrow travels and struck as it lands (nothing is marked as
    /// come back before it has); everything else the step changed waits
    /// for rax; the program stores what came back (memory, after its
    /// cause); the mark moves on.
    returns: f32 = 1.90,
    back: f32 = 2.00,
    struck: f32 = 2.40,
    stored: f32 = 2.70,
    advance: f32 = 3.30,
    total: f32 = 3.90,

    pub const cross = 0.40;
    pub const row = 0.10;
    pub const byte = 2.0 / 60.0;

    pub fn of(call: Recording.Syscall) Plan {
        var p: Plan = .{};
        // Down: the bytes of a buffer it was given (a path is read as the
        // call comes in: no work). Up: the bytes it wrote into the program.
        const down: usize = if (bufferRead(call) != null) @min(call.text.len, shown_bytes) else 0;
        const up: u64 = if (fills(call)) |span| span.len else 0;
        p.bytes = @floatFromInt(@max(down, @min(up, 32)));
        // The kernel answers when its work is done; a call with none (open,
        // close) at frame 108, straight after its call has come in.
        p.returns = if (p.bytes > 0) p.fills + p.bytes * byte + 6.0 / 60.0 else 108.0 / 60.0;
        p.back = p.returns + 6.0 / 60.0;
        p.struck = p.back + cross;
        p.stored = p.struck + time.cascade;
        p.advance = p.stored + time.read_value;
        p.total = p.advance + time.step + time.rest;
        return p;
    }

    /// The plan of the call this step crosses with: stepped over (the step
    /// went on from the call row the cascade before it advanced onto), the
    /// chart with its frame 18 at the step's first: no second fire.
    pub fn in(now: cursors.Now, made: Recording.Syscall) Plan {
        const p = of(made);
        return if (fromCall(now.rec, now.stops[1])) p.shifted(-time.cascade) else p;
    }

    fn shifted(p: Plan, by: f32) Plan {
        var q = p;
        inline for (.{ "registers", "enters", "leaves", "name", "rows", "card", "work", "fills", "returns", "back", "struck", "stored", "advance", "total" }) |field| @field(q, field) += by;
        return q;
    }

    /// When byte `k` of what the call fills lands in the program's memory.
    pub fn filled(p: Plan, k: u64) f32 {
        return p.fills + @as(f32, @floatFromInt(@min(k, 31))) * byte;
    }

    /// The same as the cursor's plan: the registers are the CPU's level,
    /// the bytes memory's.
    pub fn step(p: Plan) cursors.Plan {
        return .{ .at = .{ p.registers, p.stored, p.stored }, .advance = p.advance, .travel = time.step, .total = p.total };
    }
};

/// How many of the bytes a call was given the kernel's side shows.
/// Ten a row, two rows, in the drawing's 880 beside the arrows.
const per_row = 10;
const shown_bytes = 2 * per_row;

/// One line of the program and the call into the kernel it makes, timed
/// by the crossing. Stepped over (the line calls libc's wrapper), in two
/// steps of the cursor: the instructions before the call as a cascade, the
/// mark advancing onto the call's row; then the crossing from that row,
/// with what the line stores after the call in memory's slot, after rax.
/// A line that makes no call is walked like any other.
pub fn step(c: cursors.Cursor, s: *anim.Frame, by: Recording.Stop) void {
    const rec = c.rec;
    const from = c.moment(s);
    const to = rec.next(by, from);
    const made = for (rec.syscalls) |made| {
        if (made.enter > from and made.enter <= to) break made;
    } else return c.walk(s, by, to);
    // The call that leads to it: the line's first.
    var call = from;
    while (call < made.enter and !(if (rec.insn_branches[call]) |b| b.kind == .call else false)) call += 1;
    if (call >= made.enter) call = from;
    // 1, the instructions before the call: a cascade, the plaque onto the
    // call's row 12 f after the last strike, no rest (the line stays current):
    // what it struck cools on into the crossing.
    var cooling: f32 = 0;
    if (call > from) {
        var before = c.reading(from, call);
        const regs_before: f32 = @floatFromInt(@popCount(rec.registersChanged(from, call) & ~cursors.quiet));
        var last = before.at[0] + @min(@max(regs_before - 1, 0), 3) * cursors.write_apart;
        for (rec.written(from, call)) |span| if (rec.drawn(span, from, call)) {
            last = @max(last, before.at[1]);
        };
        before.advance = last + 12.0 / 60.0;
        before.travel = time.step;
        before.total = before.advance + before.travel;
        cooling = time.strike.cool - before.travel;
        c.step(s, call, before, before.total);
    }
    // 2, the crossing from the call row (its chart's frame 18 first); 3, the stores after.
    const p = if (call > from) Plan.of(made).shifted(-time.cascade) else Plan.of(made);
    var plan = p.step();
    plan.fires = call == from;
    plan.cooling = cooling;
    // The store after the call: 18 f after rax, and after the registers the call left (6 f apart).
    const regs: f32 = @floatFromInt(@popCount(rec.registersChanged(call, to) & ~cursors.quiet));
    const last_register = p.struck + @min(@max(regs - 1, 0), 3) * cursors.write_apart;
    var stores = false;
    for (rec.written(call, to)) |span| if (rec.drawn(span, call, to)) {
        if (fills(made)) |fill| if (span.addr >= fill.addr and span.addr < fill.addr + fill.len) continue;
        stores = true;
    };
    plan.at[1] = @max(p.stored, last_register + cursors.write_apart);
    plan.at[2] = plan.at[1];
    plan.advance = (if (stores) plan.at[1] else last_register) + time.read_value;
    plan.total = plan.advance + time.step + time.rest;
    c.step(s, to, plan, plan.total);
}

/// In a crossing, when the kernel's write of the byte at `addr` lands in
/// the program's memory (seconds into the step): what a read fills strikes
/// there as the kernel's work does it, before it returns. Null for any other byte.
pub fn filledAt(now: cursors.Now, addr: u64) ?f32 {
    if (!now.crossings) return null;
    const made = inStep(now) orelse return null;
    const span = fills(made) orelse return null;
    if (addr < span.addr or addr >= span.addr + span.len) return null;
    return Plan.in(now, made).filled(addr - span.addr);
}

/// How long after its slot in the cascade a register this step changed
/// strikes, in a step drawn as a crossing: once the call is back, after
/// rax. 0 in any other step.
pub fn crossingDelay(now: cursors.Now) f32 {
    if (!now.crossings) return 0;
    const made = inStep(now) orelse return 0;
    const p = Plan.in(now, made);
    return p.struck - p.registers;
}

/// Whether the instruction at moment `i` is a call: a step from it that
/// crosses into the kernel went over libc's wrapper.
fn fromCall(rec: *const Recording, i: u64) bool {
    return if (i < rec.insn_branches.len) if (rec.insn_branches[i]) |b| b.kind == .call else false else false;
}

/// The argument registers of a syscall, in order.
const carriers = [_][]const u8{ "rdi", "rsi", "rdx", "r10", "r8", "r9" };

/// The newest syscall entered by moment `i`.
pub fn latest(rec: *const Recording, i: u64) ?usize {
    var found: ?usize = null;
    for (rec.syscalls, 0..) |s, n| {
        if (s.enter > i) break;
        found = n;
    }
    return found;
}

/// The syscall the cursor's step made, crossed on screen. A step that made
/// several (a debugger's continue through a library's calls) crosses none:
/// it is a step like any other, and the kernel's side shows the newest.
pub fn inStep(now: cursors.Now) ?Recording.Syscall {
    const n = latest(now.rec, now.stops[0]) orelse return null;
    const call = now.rec.syscalls[n];
    if (n > 0 and now.rec.syscalls[n - 1].enter > now.stops[1]) return null;
    return if (call.enter > now.stops[1]) call else null;
}

/// The registers that carried `call`'s arguments, in order.
pub fn carried(call: Recording.Syscall) []const []const u8 {
    return carriers[0..@min(zt.syscalls.signature(call.nr).len, carriers.len)];
}

/// The bytes the kernel read from the program for `call`: the buffer of a
/// write. Null for a call that is given none.
pub fn bufferRead(call: Recording.Syscall) ?Recording.Span {
    const signature = zt.syscalls.signature(call.nr);
    const at = std.mem.indexOfScalar(u8, signature, 'b') orelse return null;
    return .{ .addr = call.args[at], .len = call.args[at + 1] };
}

/// The bytes the kernel wrote into the program for `call`: what a read
/// put in its buffer. Null for a call that fills none.
/// shortcut: `read` alone; the recorder tells the bytes of any call, and a scene of `pread` or `recv` wants them named here.
pub fn fills(call: Recording.Syscall) ?Recording.Span {
    const got: i64 = @bitCast(call.result);
    return if (call.nr == @intFromEnum(std.os.linux.SYS.read) and got > 0) .{ .addr = call.args[1], .len = @intCast(got) } else null;
}

/// The `syscalls` lens: the program's conversation with the kernel. Its
/// drawing is the calls so far as strace writes them, a row each, oldest
/// on top and the newest at the bottom (its row comes in once the call is
/// back, with the turned corner); not the kernel, and not on vellum: the
/// kernel is under the program, the floor of the disassembly's `descent`.
/// Its view, the bytes the newest call was given or filled.
pub const Crossing = struct {
    cursor: cursors.Cursor,
    stage: *const Stage,
    focus: bool = false,
    /// Its view, the bytes of the newest call: false where the scene's own
    /// view stands over the state column (`hexdump.Dump`).
    view: bool = true,

    const row_h = theme.metric.context.row;
    const size = theme.size.mono.context;

    pub fn draw(c: *const Crossing, f: *sk.Frame, placed: anim.Placed) void {
        if (c.view) c.bytesView(f, placed);
        const box = c.stage.box(placed, .band);
        if (box.h < theme.metric.context.tag + 24) return;
        const u = context.at(f, placed, box).faded(placed.value(c.stage.drawing));
        // A relayout moves the band: what is drawn in it stays inside it.
        u.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h });
        defer u.unclip();
        const now = c.cursor.now(placed);
        const rec = c.cursor.rec;
        const room = context.rowsOf(box);
        // The calls from the scene's first moment: the program's, not its loader's.
        var first: usize = 0;
        while (first < rec.syscalls.len and rec.syscalls[first].enter < c.cursor.first) first += 1;
        var newest = latest(rec, now.stops[0]);
        // A crossing's own row comes in once it is back (rax struck): the
        // rows make room for it, a full log scrolling a row (24 f, `glide`),
        // as it fades in (12 f), and the count above crossfades with them.
        var arrives: f32 = 1;
        if (newest) |n| if (inStep(now) != null and now.walking()) {
            const p = Plan.in(now, rec.syscalls[n]);
            arrives = std.math.clamp((now.time - p.struck - 6.0 / 60.0) / theme.time.move, 0, 1);
        };
        if (newest) |n| if (n < first) {
            newest = null;
        };
        const count = if (newest) |n| n + 1 - first else 0;
        const above = [2]usize{ (count -| 1) -| room, count -| room };
        const notes = [2][]const u8{ logNote(u, above[0]), logNote(u, above[1]) };
        // From rest it moves at once, a pixel a frame at least: a glide's first
        // frames are each under a pixel, and the rows, drawn on whole pixels,
        // would step one and stand still a frame.
        const scroll = @min(@max(cursors.glide(arrives), arrives * theme.time.move * 60 / (row_h * @max(u.at.scale, 0.01))), 1);
        const renote = above[0] != above[1] and arrives < 1;
        const body = u.panel(box.w, box.h, "system calls", .{ .focus = c.focus, .note = if (renote) "" else notes[1] });
        if (renote) {
            u.faded(1 - scroll).tagNote(box.w, notes[0]);
            u.faded(scroll).tagNote(box.w, notes[1]);
        }
        context.clipBody(u, box);
        defer u.unclip();
        const n = newest orelse return;
        const top = body.y + theme.metric.context.pad;
        const shown = @min(count, room);
        // A full log's oldest row shown goes up and out as the new one comes.
        const scrolls = arrives < 1 and count > room;
        const from = n + 1 - shown - @intFromBool(scrolls);
        for (from..n + 1) |i| {
            const fresh = std.math.clamp(arrives * theme.time.move / theme.time.quick - 1, 0, 1);
            const v = if (i == n) u.faded(fresh) else u;
            const row: f32 = @as(f32, @floatFromInt(i - from)) - if (scrolls) scroll else 0;
            const y = top + row * row_h;
            logRow(v, rec, rec.syscalls[i], y, box.w - theme.metric.context.side);
            // The newest's turned corner; the one before keeps it until the new row is in.
            if (i == n) v.corner(theme.metric.context.side, y + 2, theme.metric.context.corner, 1);
            if (i + 1 == n and fresh < 1) u.faded(1 - fresh).corner(theme.metric.context.side, y + 2, theme.metric.context.corner, 1);
        }
    }

    fn logNote(u: ui.Ui, above: usize) []const u8 {
        return if (above > 0) u.print("as strace writes them \u{00b7} newest at the bottom \u{00b7} {d} more above", .{above}) else "as strace writes them \u{00b7} newest at the bottom";
    }

    /// A call as strace writes it, its arguments by name: `read fd 3
    /// "note" buf 7fffffffecd0 count 32 = 15`, a path by its string (as the
    /// kernel took it, where the stop did not read it). Out of room the
    /// faint names go first, then the arguments from the right (`…`); what
    /// it returned stays.
    fn logRow(u: ui.Ui, rec: *const Recording, made: Recording.Syscall, y: f32, room: f32) void {
        const base = theme.baseline(y, row_h, size);
        const adv = ui.advance(size);
        var x: f32 = theme.metric.context.side;
        const name = zt.syscalls.name(made.nr) orelse "syscall";
        u.text(.mono_bold, size, x, base, name, theme.color.text.bright);
        x += u.width(.mono_bold, size, name) + adv;
        const names = zt.syscalls.names(made.nr);
        const n = @min(zt.syscalls.signature(made.nr).len, 6);
        const Part = struct { text: []const u8, ink: u24, name: bool = false };
        var parts: [32]Part = undefined;
        var np: usize = 0;
        for (0..n) |j| {
            const what = if (j < names.len) names[j] else "";
            if (what.len > 0) {
                parts[np] = .{ .text = what, .ink = theme.color.text.dim, .name = true };
                np += 1;
            }
            var said = @import("disasm.zig").argument(u, rec, made.enter, what, made.args[j]);
            if (std.mem.eql(u8, what, "path") and said[0] != '"' and made.text.len > 0) said = u.print("\"{s}\"", .{made.text[0 .. std.mem.indexOfScalar(u8, made.text, 0) orelse made.text.len]});
            parts[np] = .{ .text = said, .ink = theme.color.text.primary };
            np += 1;
            if (std.mem.endsWith(u8, what, "fd")) {
                const on = rec.openOn(u.f.scratch, made.args[j], made.enter);
                if (on.len > 0) {
                    parts[np] = .{ .text = on, .ink = theme.color.text.faint };
                    np += 1;
                }
            }
        }
        const answer = u.print("= {s}", .{if (made.exit != null) result(u, made) else "?"});
        const answer_w = u.width(.mono, size, answer);
        var total: f32 = 0;
        for (parts[0..np]) |part| total += u.width(.mono, size, part.text) + adv;
        // The faint names first, where all of it does not fit.
        const named = x + total + answer_w <= room;
        for (parts[0..np]) |part| {
            if (part.name and !named) continue;
            const w = u.width(.mono, size, part.text);
            if (x + w + adv + answer_w > room) {
                u.text(.mono, size, x, base, "\u{2026}", theme.color.text.faint);
                x += 2 * adv;
                break;
            }
            u.text(.mono, size, x, base, part.text, part.ink);
            x += w + adv;
        }
        u.text(.mono, size, x, base, "=", theme.color.text.faint);
        u.text(.mono, size, x + 2 * adv, base, answer[2..], theme.color.text.primary);
    }

    /// Its view: the bytes the call crossing in this step is given or
    /// fills (its path, a buffer), as a dump over the state column. They
    /// come in with the argument framing (the note before them out 12 f,
    /// they in 12 f); what a read fills lands a byte every 2 f with the
    /// kernel's work, struck; a write's buffer is framed as read while the
    /// kernel takes it; and they clear with the log's new row. Between
    /// crossings the view is clear.
    fn bytesView(c: *const Crossing, f: *sk.Frame, placed: anim.Placed) void {
        const now = c.cursor.now(placed);
        const made: ?Recording.Syscall = if (now.walking()) inStep(now) else null;
        const tm = now.time;
        const quick = theme.time.quick;
        // The call's bytes, and the note that says there is none crossing.
        var shows: f32 = 0;
        var clear: f32 = 1;
        if (made) |given| {
            const p = Plan.in(now, given);
            const out = std.math.clamp((tm - p.struck - 6.0 / 60.0) / quick, 0, 1);
            shows = std.math.clamp((tm - p.registers - quick) / quick, 0, 1) * (1 - out);
            clear = @max(1 - std.math.clamp((tm - p.registers) / quick, 0, 1), std.math.clamp((tm - p.struck - 6.0 / 60.0 - quick) / quick, 0, 1));
        }
        const path_at: ?usize = if (made) |given| std.mem.indexOfScalar(u8, zt.syscalls.signature(given.nr), 's') else null;
        const span: ?Recording.Span = if (made) |given| bufferRead(given) orelse fills(given) orelse if (given.text.len > 0 and path_at != null) .{ .addr = given.args[path_at.?], .len = given.text.len + 1 } else null else null;
        if (span) |sp| @import("map.zig").measure(.view, (sp.len + 15) / 16);
        const v = hexdump.panel(f, placed, c.stage, "", &.{});
        defer v.u.unclip();
        const note_x = 28 + v.u.width(.sans_medium, theme.size.sans.tag, "its bytes") + 12;
        const note_y = theme.metric.context.tag - 6;
        if (clear > 0) v.u.faded(clear).text(.sans, theme.size.sans.micro, note_x, note_y, "no call crossing now", theme.color.text.faint);
        if (shows <= 0) return;
        const given = made.?;
        const about = if (span) |sp| v.u.print("the {s}, {x} to {x}", .{ if (bufferRead(given) != null) "buffer given" else if (fills(given) != null) "buffer it fills" else "path given", sp.addr, sp.addr + sp.len - 1 }) else "the call names no bytes";
        v.u.faded(shows).text(.sans, theme.size.sans.micro, note_x, note_y, about, theme.color.text.faint);
        const sp = span orelse return;
        if (v.rows == 0) return;
        // The bytes it names are the field the view is about: a path or a
        // buffer of text reads as text, anything else is left to the eye.
        const p = Plan.in(now, given);
        // What a read fills is what the program's memory holds after it.
        var text = given.text[0..@min(given.text.len, sp.len)];
        if (fills(given) != null) {
            const after = v.u.f.scratch.alloc(u8, sp.len) catch return;
            now.moment().read(sp.addr, after, null) catch return;
            text = after;
        }
        const printable = for (text) |byte| {
            if (!std.ascii.isPrint(byte) and byte != '\n' and byte != '\t' and byte != 0) break false;
        } else true;
        hexdump.fielded(.{ .u = v.u.faded(shows), .rows = v.rows, .box = v.box }, now, theme.metric.context.tag + theme.metric.context.pad, .{
            .base = sp.addr,
            .len = sp.len,
            .fields = &.{.{ .at = 0, .len = sp.len, .reads = if (printable) .text else .bytes }},
            .region = context.ink(context.regionOf(now.moment(), sp.addr)),
            .given = .{ .addr = sp.addr, .bytes = text, .shows = 1, .since = if (fills(given) != null) tm - p.fills else null },
            .read = if (bufferRead(given) != null) now.held(p.work) else 0,
            .pins = true,
        });
        // The log is whole: no strip.
        context.veiled(v.u, v.box, now.sprint_veil);
    }
};

/// What came back: a count, an address, or an error by name.
fn result(u: ui.Ui, made: Recording.Syscall) []const u8 {
    const ret: i64 = @bitCast(made.result);
    if (ret < 0 and ret > -4096) {
        if (std.enums.fromInt(std.os.linux.E, -ret)) |e| return u.print("{d} E{t}", .{ ret, e });
        return u.print("{d}", .{ret});
    }
    return if (ret > 0xffffff or ret < 0) u.print("{x}", .{made.result}) else u.print("{d}", .{ret});
}

pub const Timeline = struct {
    cursor: cursors.Cursor,
    box: Rect,
    focus: bool = false,

    pub fn draw(g: *const Timeline, f: *sk.Frame, at: anim.Placed) void {
        const u: ui.Ui = .{ .f = f, .at = at };
        const now = g.cursor.now(at);
        const rec = g.cursor.rec;
        const m = theme.metric.timeline;
        const txt = theme.color.text;
        const body = u.panel(g.box.w, g.box.h, "system calls", .{ .focus = g.focus, .note = "time runs right · a block is a call into the kernel" });
        const pad = theme.metric.panel.pad_x;
        const line_y = body.y + @min(body.h / 2 - 24, 84);
        u.text(.sans, theme.size.sans.note, pad, line_y - 14, "user", txt.dim);
        u.text(.sans, theme.size.sans.note, pad, line_y + 32, "kernel", txt.dim);
        u.fill(.{ .x = theme.stroke.rule, .y = line_y, .w = g.box.w - 2 * theme.stroke.rule, .h = m.baseline }, theme.color.kernel);
        if (rec.syscalls.len == 0) return;
        // shortcut: equal blocks; under ptrace a call's time is the tracer's, so widths would say nothing.
        const room = g.box.w - 2 * pad - 110;
        const apart = @min(96, room / @as(f32, @floatFromInt(rec.syscalls.len)));
        const w = @max(m.min_block, apart - m.min_gap);
        const current = latest(rec, now.stops[0]);
        var last_name_end: f32 = 0;
        for (rec.syscalls, 0..) |call, i| {
            const x = pad + 110 + @as(f32, @floatFromInt(i)) * apart;
            const block: Rect = .{ .x = x, .y = line_y + m.baseline, .w = w, .h = m.block_h };
            // Not yet made: hollow.
            if (call.enter > now.stops[0]) u.frame(block, theme.color.rule, theme.stroke.rule) else u.fill(block, theme.color.kernel);
            const name = zt.syscalls.name(call.nr) orelse "?";
            const name_w = u.width(.mono, theme.size.mono.small, name);
            const here = current == i;
            const name_x = x + w / 2 - name_w / 2;
            const base = block.y + block.h + 34;
            if (here) {
                const gold = theme.mark(.current);
                u.fill(.{ .x = x + w / 2 - m.now / 2, .y = line_y - 40, .w = m.now, .h = block.h + 52 }, gold.solid);
                u.fill(.{ .x = name_x - 10, .y = base - 28, .w = name_w + 20, .h = 38 }, gold.solid);
                u.text(.mono_bold, theme.size.mono.small, name_x, base, name, gold.on_solid);
                last_name_end = name_x + name_w + 24;
            } else if (name_x > last_name_end and (current == null or @abs(@as(f32, @floatFromInt(i)) - @as(f32, @floatFromInt(current.?))) * apart > name_w / 2 + 40)) {
                // Names wherever one fits.
                u.text(.mono, theme.size.mono.small, name_x, base, name, txt.dim);
                last_name_end = name_x + name_w + 16;
            }
        }
    }
};

test "a crossing is as long as what the call does" {
    // A call with no bytes to move: `returns` at 108 f, then the full climb; 3.8 s. Fifteen bytes filled: 5.0.
    const close = Plan.of(.{ .nr = 3, .args = @splat(0), .enter = 0 });
    try std.testing.expectApproxEqAbs(@as(f32, 108.0 / 60.0), close.returns, 1e-3);
    try std.testing.expectApproxEqAbs(@as(f32, 3.80), close.total, 1e-3);
    const read = Plan.of(.{ .nr = 0, .args = .{ 3, 0x1000, 32, 0, 0, 0 }, .enter = 0, .exit = 0, .result = 15 });
    try std.testing.expectApproxEqAbs(@as(f32, 5.0), read.total, 1e-2);
    // What came back is in the kernel's rows before the answer climbs (24 f),
    // struck in rax as it lands (armed on its way), then stored.
    try std.testing.expect(read.returns < read.back and read.struck == read.back + Plan.cross and read.struck - time.strike.arm > read.back and read.stored > read.struck);
    // Nothing on the kernel's side before the lane is through; the last byte filled before `returns`.
    try std.testing.expect(read.leaves >= read.enters and read.name >= read.enters + Plan.cross);
    try std.testing.expect(read.fills > read.name and read.returns > read.filled(14));
    // Stepped over: the chart from its frame 18.
    try std.testing.expectApproxEqAbs(read.enters - time.cascade, read.shifted(-time.cascade).enters, 1e-4);
}