summaryrefslogtreecommitdiff
path: root/anim/src/syscalls.zig
blob: a19324fa80b7506b4a5fbd8731a45f721b201783 (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
//! 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 cursors = @import("cursor.zig");
const Recording = @import("Recording.zig");
const context = @import("context.zig");
const Stage = @import("stage.zig").Stage;
const theme = ui.theme;
const time = theme.time;
const Rect = ui.Rect;
const k = theme.color.on_kernel;

/// 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 arrow comes back, and what came back strikes rax.
/// So a call is as long as what it does: `close` 3.7 s, a `read` of
/// fifteen bytes 4.8.
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 arrow back sets off; rax is struck; the mark moves on.
    back: f32 = 2.00,
    returns: f32 = 2.40,
    advance: f32 = 3.10,
    total: f32 = 3.70,

    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 it was given. Up: the bytes it wrote into the program.
        const down: usize = @min(call.text.len, shown_bytes);
        const up: u64 = if (fills(call)) |span| span.len else 0;
        p.bytes = @floatFromInt(@max(down, @min(up, 32)));
        if (p.bytes > 0) p.back = p.fills + p.bytes * byte + 10.0 / 60.0;
        p.returns = p.back + cross;
        p.advance = p.returns + row + time.read_value;
        p.total = p.advance + time.step + time.rest;
        return p;
    }

    /// 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.fills, p.fills }, .advance = p.advance, .travel = time.step, .total = p.total };
    }
};

/// How many of the bytes a call was given the kernel's side shows.
const shown_bytes = 2 * 11;

/// One line of the program and the call into the kernel it makes, as one
/// step of the cursor, timed by the crossing. 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 from = c.moment(s);
    const to = c.rec.next(by, from);
    const made = for (c.rec.syscalls) |made| {
        if (made.enter > from and made.enter <= to) break made;
    } else return c.walk(s, by, to);
    const p = Plan.of(made);
    c.step(s, to, p.step(), p.total);
}

/// 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 (the newest, when it made several).
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];
    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 kernel as a lens: solid vellum, and nothing else on the frame is.
/// The call the step made, decoded (its name, a row an argument by the
/// argument's own name, what came back), the calls before it, the bytes it
/// was given; and the arrow that crosses into it from the registers'
/// side and returns.
pub const Crossing = struct {
    cursor: cursors.Cursor,
    stage: *const Stage,
    focus: bool = false,

    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 {
        const box = c.stage.box(placed, .band);
        if (box.h < theme.metric.context.tag + 24) return;
        const u = context.at(f, placed, box);
        const now = c.cursor.now(placed);
        const rec = c.cursor.rec;
        const body = u.panel(box.w, box.h, "kernel", .{ .focus = c.focus, .note = "the other side of a system call" });
        u.fill(.{ .x = theme.stroke.rule, .y = body.y, .w = body.w - 2 * theme.stroke.rule, .h = body.h - theme.stroke.rule }, theme.color.kernel);
        context.clipBody(u, box);
        defer u.unclip();
        u.text(.sans, theme.size.sans.micro, 12, body.y + 22, "calls so far", k.dim);
        const newest = latest(rec, now.stops[0]) orelse return;
        const live = rec.syscalls[newest].enter > now.stops[1] and now.walking();
        const p = Plan.of(rec.syscalls[newest]);
        const t: f32 = if (live) now.time else std.math.inf(f32);
        if (t >= p.enters) arrows(u, body, t, p, rec.syscalls[newest]);
        // No effect before its cause: until the arrow is through the
        // line the kernel knows nothing of this call, and shows the last.
        if (t < p.name) {
            if (newest > 0) c.call(u.faded(1 - theme.ease(.exit, std.math.clamp((t - p.leaves) / (p.name - p.leaves), 0, 1))), body, rec.syscalls[newest - 1], .{}, std.math.inf(f32));
        } else c.call(u, body, rec.syscalls[newest], p, t);

        // The calls so far, newest on top. This one's row pushes in when
        // the kernel has taken the call: the others make room first.
        const pushed = cursors.standard(std.math.clamp((t - p.card) / theme.time.quick, 0, 1));
        const arrived = std.math.clamp((t - p.card - theme.time.snap) / theme.time.quick, 0, 1);
        const top = body.y + 32;
        var i = newest + 1;
        while (i > 0) {
            i -= 1;
            const place = @as(f32, @floatFromInt(newest - i)) - (if (i == newest) 0 else 1 - pushed);
            const y = top + place * (row_h + 4) - (if (i == newest) (1 - arrived) * 8 else 0);
            if (y + row_h > body.y + body.h - 6) continue;
            const v = if (i == newest) u.faded(arrived) else u;
            const card: Rect = .{ .x = 12, .y = y, .w = 196, .h = row_h };
            const done = rec.syscalls[i];
            const gold = if (i == newest) arrived >= 1 else i + 1 == newest and arrived < 1;
            if (gold) v.fill(card, theme.mark(.current).solid);
            v.frame(card, k.ink, theme.stroke.rule);
            const name = zt.syscalls.name(done.nr) orelse "?";
            v.text(if (gold) .mono_bold else .mono, size, card.x + 8, theme.baseline(card.y, card.h, size), name[0..@min(name.len, 11)], k.ink);
            if ((i != newest or t >= p.returns + Plan.row) and done.exit != null) {
                const words = result(u, done);
                if (words.len <= 4) v.text(.mono, size, card.x + card.w - 8 - u.width(.mono, size, words), theme.baseline(card.y, card.h, size), words, k.dim);
            }
        }
    }

    /// A call, decoded: its name, a row for each argument, what came
    /// back; and to the right the bytes it was given, as the kernel
    /// copies them.
    fn call(c: *const Crossing, u: ui.Ui, body: Rect, made: Recording.Syscall, p: Plan, t: f32) void {
        _ = c;
        const x = 236;
        const name = zt.syscalls.name(made.nr) orelse "syscall";
        // The name arrives rising, as a caption does.
        const named = theme.ease(.enter, std.math.clamp((t - p.name) / theme.time.quick, 0, 1));
        const title = u.faded(named);
        const rise = (1 - named) * theme.time.caption_rise;
        title.text(.mono_bold, theme.size.mono.value, x, body.y + 46 + rise, name, k.ink);
        title.text(.sans, theme.size.sans.micro, x + u.width(.mono_bold, theme.size.mono.value, name) + 16, body.y + 44 + rise, u.print("system call {d}", .{made.nr}), k.dim);
        const signature = zt.syscalls.signature(made.nr);
        var row_y: f32 = body.y + 62;
        var text_used = false;
        const row = struct {
            fn draw(v: ui.Ui, y: f32, register: []const u8, meaning: []const u8, words: []const u8) void {
                v.fill(.{ .x = x, .y = y, .w = 300, .h = theme.stroke.rule }, k.rule);
                const base = theme.baseline(y, row_h + 4, size);
                v.text(.mono, size, x, base, register, k.dim);
                v.text(.sans_medium, theme.size.sans.tag, x + 52, base, meaning, k.ink);
                v.text(.mono, size, x + 130, base, words, k.ink);
            }
        }.draw;
        for (signature, 0..) |kind, arg| {
            if (arg >= 4) break;
            const shows = std.math.clamp((t - p.rows - @as(f32, @floatFromInt(arg)) * Plan.row) / Plan.row, 0, 1);
            row(u.faded(shows), row_y, carriers[arg], what(made.nr, kind, arg), value(u, made, kind, arg, &text_used));
            row_y += row_h + 4;
        }
        const back = t >= p.returns + Plan.row and made.exit != null;
        row(u.faded(std.math.clamp((t - p.rows - @as(f32, @floatFromInt(@min(signature.len, 4))) * Plan.row) / Plan.row, 0, 1)), row_y, "rax", "returns", if (back) result(u, made) else "\u{2014}");

        if (made.text.len == 0) return;
        const bytes_x = 564;
        const framed = u.faded(std.math.clamp((t - p.work) / Plan.row, 0, 1));
        framed.text(.sans, theme.size.sans.micro, bytes_x, body.y + 22, if (std.mem.indexOfScalar(u8, signature, 's') != null) "the path it was given" else "the bytes it was given", k.dim);
        const shown = @min(made.text.len, shown_bytes);
        for (made.text[0..shown], 0..) |byte, j| {
            const cell: Rect = .{ .x = bytes_x + @as(f32, @floatFromInt(j % 11)) * 28, .y = body.y + 32 + @as(f32, @floatFromInt(j / 11)) * 30, .w = 26, .h = 26 };
            // Each fills as it is copied, two frames a byte: struck, then held.
            const since = t - p.fills - @as(f32, @floatFromInt(j)) * Plan.byte;
            if (since < 0) {
                framed.frame(cell, k.rule, theme.stroke.rule);
                continue;
            }
            const in = std.math.clamp(since / theme.time.strike.in, 0, 1);
            u.fill(cell, ui.mix(theme.color.kernel, ui.mix(theme.mark(.write).solid, k.held, std.math.clamp((since - theme.time.quick) / theme.time.strike.cool, 0, 1)), in));
            u.frame(cell, k.ink, theme.stroke.rule);
            if (in < 0.5) continue;
            if (std.ascii.isPrint(byte) and byte != ' ') u.label(.mono, size, cell, .center, &.{byte}, k.ink) else if (byte == '\n') u.label(.mono, size, cell, .center, "\\n", k.dim);
        }
    }

    /// The crossing itself: in from the side the registers are on as the
    /// call enters, and back out as it returns. Vellum outside the
    /// kernel, ink inside it. Machines do not lob: straight.
    /// The crossing itself: up out of the registers below the band (the
    /// ones that carried it), into the kernel, as the call enters; and back
    /// down as it returns. Machines do not lob: straight.
    fn arrows(u: ui.Ui, body: Rect, t: f32, p: Plan, made: Recording.Syscall) void {
        const x = theme.layout.state.x - theme.layout.program.x + 40;
        const bottom = body.y + body.h;
        const reach = 64;
        // Off promptly, and settling in the kernel.
        const up = cursors.standard(std.math.clamp((t - p.enters) / Plan.cross, 0, 1));
        const gone = std.math.clamp((t - p.returns - theme.time.quick) / theme.time.read.out, 0, 1);
        const v = u.faded(1 - gone);
        if (t < p.back) along(v, x, bottom, bottom - up * reach);
        if (made.exit != null and t > p.back) along(v, x + 40, bottom - reach, bottom - reach + cursors.standard(std.math.clamp((t - p.back) / Plan.cross, 0, 1)) * reach);
    }

    /// An arrow down the column at `x` from `from` to `to`, in ink: it is inside the kernel.
    fn along(u: ui.Ui, x: f32, from: f32, to: f32) void {
        if (@abs(to - from) < 1) return;
        const w = theme.stroke.arrow;
        const head = theme.stroke.flow_head;
        const dir: f32 = if (to > from) 1 else -1;
        const neck = to - dir * (head[0] - 2);
        if ((neck - from) * dir > 0) u.fill(.{ .x = x - w / 2, .y = @min(from, neck), .w = w, .h = @abs(neck - from) }, k.ink);
        if (@abs(to - from) < head[0]) return;
        sk.draw.polygon(u.f, &.{ .{ x, to }, .{ x - head[1] / 2, to - dir * head[0] }, .{ x + head[1] / 2, to - dir * head[0] } }, u.at.pen(.{ .fill = ui.rgb(k.ink) }));
    }
};

/// What an argument is called: by the call's own names where they are
/// known, else from its letter in `zt.syscalls.signature`.
/// shortcut: four calls named; the recorder's table should carry every call's argument names.
fn what(nr: u16, kind: u8, arg: usize) []const u8 {
    const names: []const []const u8 = switch (std.enums.fromInt(std.os.linux.SYS, nr) orelse .restart_syscall) {
        .open => &.{ "path", "flags", "mode" },
        .read, .write => &.{ "fd", "buf", "count" },
        .close => &.{"fd"},
        else => &.{},
    };
    if (arg < names.len) return names[arg];
    return switch (kind) {
        'i' => "number",
        'd' => "size",
        's' => "path",
        'b' => "buffer",
        else => "pointer",
    };
}

fn value(u: ui.Ui, made: Recording.Syscall, kind: u8, arg: usize, text_used: *bool) []const u8 {
    const a = made.args[arg];
    switch (kind) {
        'i' => return u.print("{d}", .{@as(i32, @bitCast(@as(u32, @truncate(a))))}),
        'd' => return u.print("{d}", .{a}),
        's' => if (made.text.len > 0 and !text_used.*) {
            text_used.* = true;
            const base = std.fs.path.basename(made.text);
            return u.print("\"{s}\"", .{base[0..@min(base.len, 14)]});
        },
        else => {},
    }
    return u.print("{x}", .{a});
}


/// 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 work: 3.7 s. Fifteen bytes copied up: 4.8.
    try std.testing.expectApproxEqAbs(@as(f32, 3.70), Plan.of(.{ .nr = 3, .args = @splat(0), .enter = 0 }).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, 4.77), read.total, 1e-2);
    // Nothing on the kernel's side before the arrow is through the line.
    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.fills + 15 * Plan.byte);
}