diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-10 20:16:54 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-10 20:27:13 -0300 |
| commit | dc3b58781420be6070fca896e55776bc27db905d (patch) | |
| tree | f77ebd77edf5a360df0ea9255f55daf47e5baf34 | |
| parent | 13fe4003276daf884da4e29112fb4db8630ad46a (diff) | |
| download | computeranim-dc3b58781420be6070fca896e55776bc27db905d.tar.gz computeranim-dc3b58781420be6070fca896e55776bc27db905d.zip | |
canim: a scene from a real program: SQLite's row on its way to disk
Three inserts stopped at sqlite3BtreeInsert with their payloads read off
the caller's stack, the commit's backtrace from unixWrite up to main, the
pwrite64 crossing into the kernel, and page 2 as the kernel took it: its
header, its cell pointers and the three rows, read by field. The scene
is built only where SQLite's source is (-Dsqlite=DIR); its recording is
181 moments, 95 KB.
What a real program asked of the blocks: a dump read by the fields a
scene gives it, with the rows between collapsed; addresses of twelve
digits and line numbers of six; the backtrace as a lens's drawing; a
continue's motion (shared frames slide, a far window fades); memory drawn
only where the stop read it. In the kernel lens a register is framed as
carrying an argument only while it holds it at the stop shown, and an
allocator row is read only where an allocation follows the word.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
| -rw-r--r-- | anim/README.md | 109 | ||||
| -rw-r--r-- | anim/build.zig | 48 | ||||
| -rw-r--r-- | anim/scenes/gallery.zig | 8 | ||||
| -rw-r--r-- | anim/scenes/sqlite.zig | 223 | ||||
| -rw-r--r-- | anim/src/Recording.zig | 8 | ||||
| -rw-r--r-- | anim/src/calls.zig | 8 | ||||
| -rw-r--r-- | anim/src/context.zig | 269 | ||||
| -rw-r--r-- | anim/src/cursor.zig | 7 | ||||
| -rw-r--r-- | anim/src/disasm.zig | 17 | ||||
| -rw-r--r-- | anim/src/hexdump.zig | 276 | ||||
| -rw-r--r-- | anim/src/root.zig | 4 | ||||
| -rw-r--r-- | anim/src/rows.zig | 55 | ||||
| -rw-r--r-- | anim/src/source.zig | 13 | ||||
| -rw-r--r-- | anim/src/syscalls.zig | 98 | ||||
| -rw-r--r-- | anim/src/ties.zig | 5 | ||||
| -rw-r--r-- | anim/test/sqlite.script | 10 | ||||
| -rw-r--r-- | anim/tools/chart.py | 2 | ||||
| -rw-r--r-- | anim/tools/sqlite.c | 18 |
18 files changed, 990 insertions, 188 deletions
diff --git a/anim/README.md b/anim/README.md index 57beeb5..5801c74 100644 --- a/anim/README.md +++ b/anim/README.md @@ -20,7 +20,12 @@ python3 tools/chart.py chart out/fib-1080.mp4 --out out/motion/fib # the desig ``` Needs what sketchbook and ztrace need, and `setarch`, `clang` (the pass -plugin), `ffmpeg` (videos), python with numpy and Pillow (charts). +plugin), `ffmpeg` (videos), python with numpy and Pillow (charts). The +`sqlite` scene also needs SQLite's amalgamation (`-Dsqlite=DIR`, the +directory of `sqlite3.c` and `sqlite3.h`; by default +`~/05-genizah/sqlite/sqlite-amalgamation-3500400`) and `objdump`; where +the directory is not there the scene is not made, and the rest builds +and tests as before. Dependencies are by path (`..` is ztrace, `../../sketchbook`, `../../02-pardes-code`); `zig-pkg` is a symlink to pardes's. @@ -72,6 +77,19 @@ pace down and up again (each step 0.6 of the one before) to a run (0.30 s a step) or a sprint, `step` takes an explicit `Plan` (`Array.swap`, `syscalls.step`). Components read it through `Cursor.now(at)`. +## The scenes + +| Scene | Shows | Split, lens | Recording | +| --- | --- | --- | --- | +| `title` | the series and the legend of marks | a card | | +| `fib` | recursion: each call a frame and a node | `subject`, `calls` | `steps` | +| `list` | a list reversed: each `next` turned | `subject`, `nodes` | `list` | +| `sort` | insertion sort: compares and swaps | `subject`, `array` | `sort` | +| `syscalls` | open, read, close, write: the kernel's side | `subject`, `syscalls` | `hello` | +| `zoom` | one line of C as its instructions, the call's bytes | `none`, the camera at x2 | `steps` | +| `sqlite` | a row's way to disk in SQLite: from `sqlite3_step` to `sqlite3BtreeInsert` (three continues, the row's struct on the stack), the commit's `unixWrite` nine calls under `main`, `pwrite64` of page 2 into the kernel, and the page read as a B-tree leaf | `subject` with the backtrace in the drawing's place, then `syscalls`; its view a `hexdump.Dump` | `sqlite` | +| `gallery` | every block in its states | all three | `gallery` | + ## The blocks The catalogue's layers, and where each block is. Every block is drawn in @@ -81,13 +99,13 @@ every state the code has in the `gallery` scene. | --- | --- | --- | --- | | 0 tokens | grid, colour, type, the splits | `src/theme.zig` | per "Token changes"; JetBrains Mono NL (`.code*` faces) for all mono, Medium under 30 | | 1 atom | `address` (`lead`, `name`, `rwx`), `value` (and `Ui.typed`: `fd`, `bool`, `char`), `arrow` (`points`, `holds`, `more`), `mark`s, `plaque` (`chip`), `pin` (`row`, `under`), `bracket` (`quiet`, `tie`, `thread`), `tag` | `src/ui.zig` (`Ui.address`, `.value`, `.arrow`, `.written`, `.read`, `.cellWritten`, `.cellRead`, `.current`, `.trail`, `.unknown`, `.chip`, `.pinRow`, `.pinUnder`, `.bracket`, `.panel`) | marks in the context: `armed`, `struck`, `held` (a tick), `read`; in a lens's cell the same with a bar | -| | `byte` | `src/rows.zig` `bytes` | `number`, `pointer`, `allocator`, `unread`; `pad` | +| | `byte` | `src/rows.zig` `bytes` | `number`, `pointer`, `text` (a string's ink), `allocator` (also bytes that are no field of what a dump is about), `unread`; `pad`; `bytesAt` moves the bytes right of a long (stack) address | | 2 row | `chain`, `reg` (and `rip` with the flags), `slot`, `line`, `bytes`, `call` (`span`, `callRow`) | `src/rows.zig` | `chain` follows `zt.telescope.chase`; cut at its far end, `more` | | | `insn` | `src/disasm.zig` | columns at 2, 31, 40, 134, 180, 264, 564; operands whole, the annotation from 564 or a character after them; then a size word goes, then the operands give way, never inside `[]`; `current`, `ran` (every instruction of the last three steps), `ahead`, `outside`; the jump lane from the jump just before the pc's moment | -| 3 panel | `registers`, `stack`, `backtrace` | `src/context.zig` | the stack's window on `[rsp, rbp+16)` keeping the touched word in view, rsp and rbp's pins travelling; `call` spans and the backtrace (`#n`, name, arguments at 384, file and line) from `zt.telescope.frames` | -| | `source` | `src/source.zig` | the whole file in a window, its middle third | +| 3 panel | `registers`, `stack`, `backtrace` | `src/context.zig` | the stack's window on `[rsp, rbp+16)` keeping the touched word in view, rsp and rbp's pins travelling (keeping their place among the names they leave and join); a window that moves more than 16 words fades out and in round memory's strike; a frame's name longer than the spans' room shortens the chains beside it; `call` spans and the backtrace (`#n`, name, arguments at 384, file and line) from `zt.telescope.frames`, the frames two stops share sliding to their new depth | +| | `source` | `src/source.zig` | the whole file in a window, its middle third; numbers as wide as the window needs (SQLite's have five digits), the text moved right by as much; a window more than two windows away fades out and in | | | `disasm` | `src/disasm.zig` | 17 rows (9 as subject), fewer above near a function's start | -| | `hexdump` | `src/hexdump.zig` | a lens's view (`hexdump.panel`): `bytes` rows and their reading, veiled at a sprint | +| | `hexdump` | `src/hexdump.zig` | a lens's view (`hexdump.panel`): `bytes` rows and their reading, veiled at a sprint; `Dump`, a view of a region by the fields a scene gives it (`Field`: where, how long, read as a number, big-endian or not, a pointer, text, or left to the eye), the rows that hold a field and a `more` row for those left out, marks the scene plays, the bytes a syscall was given as the kernel took them, and only what the debugger read at the stop (`seen`) | | | lenses: `nodes`, `array`, `calls`, `syscalls` | `src/nodes.zig`, `src/array.zig`, `src/calls.zig` (`Tree`), `src/syscalls.zig` (`Crossing`) | the drawing in `band` (over the program column), its view in `view` (over the state column): `nodes` and `array` a dump (`hexdump.panel`), `calls` the backtrace with arguments, `syscalls` the bytes the call is given or fills | | 4 tie | `thread`, `link` (and its `pin`), `projection`, `echo` | `src/ties.zig` | panels publish places (`anchor`); `Ties`, added last, draws in the channels: a link climbs to a node by the gutter's left lane and goes down to a slot by the right, its name riding its head, a target past the stack's window a stub and a row count; a projection from the view's bytes, or from a frame's return address to its call's node | | 5 frame | `stage` and `relayout` | `src/stage.zig` | splits `none`, `beside`, `subject` (`theme.layout.split`): the band is `band` (the drawing) and `view`; `relayout` fades the drawing round its move; `holdStack` holds the stack's window for the camera, with `free` slots | @@ -118,6 +136,7 @@ and no canary stepped through that the source does not say. | `sort` | `sort.c`, `ztrace cc --instr vars --only sort,a` | every instruction, `--from main` | 5076, 617 KB | `--ring`: the variables' names and types; each `__zt_var` call is stepped (4 of them) | | `list` | `list.c`, `ztrace cc --instr vars --only push,reverse,head` | every instruction, `--from reverse` | 3421, 528 KB | `--alloc --preload` the agent: allocator headers are read; the pushes (the agent's and the runtime's first calls) run through | | `gallery` | the old `list` by line, kept in `test/gallery/list.ztrace` | | 134, 88 KB | the gallery's pictures depend on the drawing only | +| `sqlite` | `sqlite.c` (three rows into a table, committed) with SQLite 3.50.4's amalgamation, system clang `-O2 -g -fno-omit-frame-pointer -no-pie -fno-stack-protector -Wl,-z,now`, glibc | `--by break`: `sqlite3_step`, `sqlite3BtreeInsert`, `unixWrite`, and the instruction after its `pwrite64` (found by objdump); every syscall recorded, `-s 4096`, `--stack 512` | 181 (42 stops, 138 syscalls), 95 KB | made only with `-Dsqlite=DIR` (default `~/05-genizah/sqlite/sqlite-amalgamation-3500400`), in a new temporary directory each time; `sqlite3.c` is embedded as the source | A recording that begins inside a call (`--from`) has that call open from its first stop (`Recording.index`, from the frame chain). Writes are the @@ -135,31 +154,41 @@ holds is named from its module's first mapping (`list+2c89`). checks; its regions follow the two-panel band now). Encoded with `-g 600`: x264's keyframe at 10, 20, 30 s is a one-frame fade the instrument sees. -| | fib | list | sort | syscalls | zoom | -| --- | --- | --- | --- | --- | --- | -| POP, round 2 / 3 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | -| CROWD, round 2 / 3 | 7 / 2 | 2 / 7 | 10 / 5 | 5 / 1 | 4 / 3 | -| RUSH, round 2 / 3 | 0 / 0 | 0 / 2 | 2 / 0 | 1 / 2 | 0 / 0 | -| AIR, round 3 | 0 | 0 | 1 | 0 | 1 | -| seconds, round 3 | 41.5 | 60.5 | 46.7 | 38.2 | 32.0 | +| | fib | list | sort | syscalls | zoom | sqlite | +| --- | --- | --- | --- | --- | --- | --- | +| POP, round 2 / 3 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | – / 0 | +| CROWD, round 2 / 3 | 7 / 2 | 2 / 7 | 10 / 6 | 5 / 1 | 4 / 3 | – / 1 | +| RUSH, round 2 / 3 | 0 / 0 | 0 / 2 | 2 / 0 | 1 / 2 | 0 / 0 | – / 1 | +| AIR, round 3 | 0 | 0 | 0 | 0 | 1 | 4 | +| seconds, round 3 | 41.5 | 60.5 | 42.0 | 38.5 | 32.0 | 64.6 | + +(sort as the coordinator re-exported it without the camera; syscalls and +sqlite after the crossing's changes: a register carries a call only while +it holds the argument at the stop shown, `rax` is struck after the +kernel's `returns` row; fib, list and zoom are the round-3 exports, made +before the stack's and backtrace's motions below.) What fires, and why it is left: -- CROWD: fib 12.05 and 27.20, list 30.62 and 32.18, sort 22.28 are the +- CROWD: fib 12.05 and 27.20, list 30.62 and 32.18, sort 17.58 are the veil coming over the registers, stack and disassembly at the first - shortened step (one veil over three panels); sort 9.60 and zoom 9.65 - and 21.55 the camera (the regions are fixed on the screen); zoom 11.75 - the stack's window scrolling to its hold under the camera (the stack - fills every region there). The rest (list 15.92, 19.32 and the others - like them, sort 31.82 and 34.12, syscalls 35.05) are an `advance`: the - thread, the plaques and rip move as one mark, the source and the - disassembly scroll with it, and a link or projection goes back into its - pin, all on the catalogue's one frame. -- RUSH: list 29.20 and 29.55, syscalls 29.17 and 29.52: a caption - arrives, and the next change the instrument sees is the keyframe at - 30.00 (a fade of every region over one frame, 0.00% at its peak). -- AIR: the last caption's reading time and the 2 s on the finished - picture (sort 42.17, 4.6 s; zoom 26.88, 3.1 s). + shortened step (one veil over three panels); zoom 9.65 and 21.55 the + camera (the regions are fixed on the screen); zoom 11.75 the stack's + window scrolling to its hold under the camera (the stack fills every + region there). The rest (list 15.92, 19.32 and the others like them, + sort 11.68, 27.12, 29.42 and the others, syscalls 35.35, sqlite 43.40) + are an `advance`: the thread, the plaques and rip move as one mark, the + source and the disassembly scroll with it, and a link or projection + goes back into its pin, all on the catalogue's one frame. +- RUSH: list 29.20 and 29.55, syscalls 29.37 and 29.72, sqlite 9.10: a + caption arrives, and the next change the instrument sees is the + keyframe at 30.00 (10.00) (a fade of every region over one frame, + 0.00% at its peak). +- AIR: a caption's reading time on a still picture: the last one's and + the 2 s on the finished picture (zoom 26.88, 3.1 s; sqlite 60.02, + 4.6 s), and in sqlite three more, each a dense caption over a stop + (11.38, 7.2 s: the arguments; 32.72, 3.5 s: the commit's backtrace; + 50.03, 4.9 s: the page's header), its fields framed as it names them. ## What is not done @@ -169,17 +198,35 @@ What fires, and why it is left: - Names keep their side when one of two leaves a pin and when a pin's name travels; a name that arrives where another already is takes the right, and once it has landed the pin's own order (variables, then - registers) may put it on the other side. + registers) may put it on the other side. (In the stack's lane, rsp or + rbp travelling alone keeps its place among the names it leaves and + joins; both travelling to rows with other names is not handled.) - The hexdump's reading of a `char` or `bool` field (the lens's values and cells read them by type; the dump's reading column does not). -- A link to a slot past the stack's window ends in its stub and row count - (`12 rows`); no scene's link has such a target, so it is drawn in no - export. +- A link to a slot past the stack's window ends in its stub and row count: + drawn in the sqlite scene only (rsi to the struct on the caller's + stack, `23 rows`, 4.2 s). - The calls tree's leaf spacing holds for fib(5); past about ten leaves nodes and badges collide (the catalogue's known case). - `heap` and `pages` lenses are not in the band (`Timeline` is the old far view). -- SQLite (the next rung) is not started. +- A recording holds the bytes it has seen, each as last seen: it cannot + tell a byte read again and unchanged from one not read since. Memory + nothing watches (SQLite's page cache) is read at a stop only where a + pointer leads (32 bytes), so a view of it says what the stop read + (`hexdump.Fields.seen`); a syscall's buffer is shown as the kernel took + it, from its capture. The recorder should say what it read at each stop. +- A frame's file and line are known only where the recording stopped in + it: return addresses are recorded with names, not lines, so a deep + backtrace's older rows have none. +- A program's frame arguments are in the backtrace only for calls the + recording tells (an instrumented program's); at a breakpoint the + callee's are in its registers, which the scene's captions name. +- The sqlite scene changes what is over the band (the backtrace, then the + kernel's side) and its view (the SQL at rbx, the row, the page) by a + fade, not by a verb of the catalogue; the backtrace in the band's + drawing is a split the catalogue does not have (`subject` with the + backtrace where the drawing goes: eleven rows). - `zig build test` prints "failed command" for each scripted scene: that is the run echoing its stderr (the Vulkan headless warning), not a failure; the summary line is the verdict. diff --git a/anim/build.zig b/anim/build.zig index 5646f1a..29a4b05 100644 --- a/anim/build.zig +++ b/anim/build.zig @@ -11,7 +11,8 @@ //! zig build motion -Dscene=list -Doptimize=ReleaseFast how a scene moves: contact sheets and change plots in out/motion/list //! //! Needs, besides what sketchbook and ztrace need: `setarch`, and for -//! `videos`, `ffmpeg`. +//! `videos`, `ffmpeg`. The sqlite scene also needs `clang` and SQLite's +//! amalgamation (`-Dsqlite=DIR`); without it that scene is not made. const std = @import("std"); const sketchbook = @import("sketchbook"); @@ -136,6 +137,48 @@ pub fn build(b: *std.Build) void { _ = embedded.addCopyFile(source, r.source); table.print(b.allocator, "pub const {s}: Program = .{{ .trace = @embedFile(\"{s}\"), .file = \"{s}\", .source = @embedFile(\"{s}\") }};\n", .{ r.name, file, r.source, r.source }) catch @panic("OOM"); } + // SQLite, the next rung: its amalgamation is not ours to copy, so the + // scene is made only where it is. Built as the bench builds it (-O2, + // frame pointers kept), and as the instrumented ones are (no PIE, bound + // at load, no canary); run once under the debugger, stopping where a + // statement's bytecode is run (`sqlite3_step`), where a row enters the + // B-tree (`sqlite3BtreeInsert`), where a page is written + // (`unixWrite`) and where its `pwrite64` has returned to it (the + // instruction after the call, found by objdump: there is no name for + // it); every syscall recorded with the bytes it points at, up to a page. + // In a directory of its own each time: the database it makes must not be there. + const sqlite_dir = b.option([]const u8, "sqlite", "SQLite's amalgamation (sqlite3.c, sqlite3.h): the sqlite scene is made only with it") orelse b.pathJoin(&.{ b.graph.environ_map.get("HOME") orelse "/", "05-genizah/sqlite/sqlite-amalgamation-3500400" }); + const sqlite_c = b.pathJoin(&.{ sqlite_dir, "sqlite3.c" }); + const has_sqlite = if (std.Io.Dir.cwd().access(b.graph.io, sqlite_c, .{})) |_| true else |_| false; + if (has_sqlite) { + const cc = b.addSystemCommand(&.{ "clang", "-O2", "-g", "-fno-omit-frame-pointer", "-no-pie", "-fno-stack-protector", "-Wl,-z,now", "-w" }); + cc.addPrefixedDirectoryArg("-I", .{ .cwd_relative = sqlite_dir }); + cc.addFileArg(b.path("tools/sqlite.c")); + cc.addFileArg(.{ .cwd_relative = sqlite_c }); + cc.addArgs(&.{ "-lm", "-o" }); + const program = cc.addOutputFileArg("sqlite"); + const run = b.addSystemCommand(&.{ "sh", "-c", + \\set -e + \\ztrace=$(realpath "$0") program=$(realpath "$1") + \\case $2 in /*) out=$2 ;; *) out=$PWD/$2 ;; esac + \\back=$(objdump -d --no-show-raw-insn "$program" | awk '/<unixWrite>:/ { f = 1 } f && /call.*pwrite64/ { getline; sub(":", "", $1); print "0x" $1; exit }') + \\[ -n "$back" ] || { echo "no call of pwrite64 in unixWrite" >&2; exit 1; } + \\d=$(mktemp -d) + \\trap 'rm -rf "$d"' EXIT + \\cp "$program" "$d/sqlite" + \\cd "$d" + \\env -i setarch -R "$ztrace" record --by break -b sqlite3_step -b sqlite3BtreeInsert -b unixWrite -b "*$back" --stack 512 -s 4096 -o "$out" -- ./sqlite + }); + run.addArtifactArg(ztrace); + run.addFileArg(program); + const trace = run.addOutputFileArg("sqlite.ztrace"); + run.expectStdErrMatch("exit 0"); + record_step.dependOn(&b.addInstallFile(trace, "recordings/sqlite.ztrace").step); + _ = embedded.addCopyFile(trace, "sqlite.ztrace"); + _ = embedded.addCopyFile(.{ .cwd_relative = sqlite_c }, "sqlite3.c"); + table.print(b.allocator, "pub const sqlite: Program = .{{ .trace = @embedFile(\"sqlite.ztrace\"), .file = \"sqlite3.c\", .source = @embedFile(\"sqlite3.c\") }};\n", .{}) catch @panic("OOM"); + } + // The gallery's own: a recording of the list kept in test/gallery, so its // pictures change when the drawing does and not when a new recording does. _ = embedded.addCopyFile(b.path("test/gallery/list.ztrace"), "gallery.ztrace"); @@ -170,7 +213,8 @@ pub fn build(b: *std.Build) void { // ---- Scenes. const videos = b.step("videos", "Export every scene to out/NAME-1080.mp4 and out/NAME-2160.mp4 (use -Doptimize=ReleaseFast)"); - for (scenes) |name| { + for (scenes ++ [_][]const u8{"sqlite"}) |name| { + if (std.mem.eql(u8, name, "sqlite") and !has_sqlite) continue; const scene = sb.addScene(.{ .root_source_file = b.path(b.fmt("scenes/{s}.zig", .{name})), .imports = &.{ .{ .name = "canim", .module = canim }, .{ .name = "recordings", .module = recordings }, diff --git a/anim/scenes/gallery.zig b/anim/scenes/gallery.zig index 3b66a24..2cc3d9f 100644 --- a/anim/scenes/gallery.zig +++ b/anim/scenes/gallery.zig @@ -256,11 +256,11 @@ fn rowsPage(u: ui.Ui, p: *const Pages) void { panel = u.moved(64, y); const plain = " cur->next = prev;"; const styles: [128]u8 = @splat(0); - rows.line(panel, 0, 880, 22, plain, styles[0..plain.len], .{ .current = 0 }); - rows.line(panel, row, 880, 21, " node *next = cur->next;", styles[0..31], .{ .trail = 0 }); - rows.line(panel, 2 * row, 880, 20, " while (cur) {", styles[0..17], .{ .trail = 1 }); + rows.line(panel, 0, 880, 22, 0, plain, styles[0..plain.len], .{ .current = 0 }); + rows.line(panel, row, 880, 21, 0, " node *next = cur->next;", styles[0..31], .{ .trail = 0 }); + rows.line(panel, 2 * row, 880, 20, 0, " while (cur) {", styles[0..17], .{ .trail = 1 }); const long = " a line of source longer than the panel has room for, which is cut at its end"; - rows.line(panel, 3 * row, 880, 9, long, styles[0..long.len], .plain); + rows.line(panel, 3 * row, 880, 9, 0, long, styles[0..long.len], .plain); y = 750; title(u, 64, y, "bytes"); diff --git a/anim/scenes/sqlite.zig b/anim/scenes/sqlite.zig new file mode 100644 index 0000000..f145da6 --- /dev/null +++ b/anim/scenes/sqlite.zig @@ -0,0 +1,223 @@ +//! A row's way to disk: SQLite (the real one, its amalgamation built -O2) +//! puts three rows into a table in a transaction and commits. The scene +//! follows the first row from the bytecode interpreter into the B-tree, +//! and at the commit the 4 KiB page that holds all three into the kernel, +//! where its bytes are read as the page they are: the header, the cell +//! pointers, the rows at its end, last in first. +//! +//! How it moves (design/motion.md): the context at a breakpoint in +//! `sqlite3_step`, then a `continue` to `sqlite3BtreeInsert` (the backtrace +//! grows two frames, the arguments arrive in the registers); the argument +//! the row is (a struct on the caller's stack) comes in as the view; two +//! more continues, each rowid struck in it; a continue to the commit's +//! `unixWrite`, nine calls under `main`, the page it is handed as the view; +//! the lens changes to the kernel's side, and `pwrite64` crosses; then the +//! page's fields are read, a group at a time, as the captions name them. +const std = @import("std"); +const anim = @import("anim"); +const canim = @import("canim"); +const recordings = @import("recordings"); + +pub const background = canim.background; +pub const scene = anim.Live(frame, struct {}); + +const Field = canim.hexdump.Field; + +/// The breakpoints' stops: the last at or before `before` where the +/// program stopped at `name` (`sqlite3BtreeInsert+4`; a prefix, `unixWrite+`). +fn stopAt(rec: *canim.Recording, name: []const u8, before: u64) u64 { + var i = before + 1; + while (i > 0) { + i -= 1; + const here = rec.strings.get(rec.registers[i].rip) orelse continue; + if (std.mem.startsWith(u8, here, name)) return i; + } + std.debug.panic("sqlite: no stop at {s} before moment {d}", .{ name, before }); +} + +/// The struct the row is handed to the B-tree in (`BtreePayload`, the +/// source's lines 16740 to 16748): its members, from its first byte. +const payload = [_]Field{ + .{ .at = 0, .len = 8, .reads = .pointer }, // pKey: NULL for a table + .{ .at = 8, .len = 8, .mark = 0 }, // nKey: the rowid + .{ .at = 16, .len = 8, .reads = .pointer }, // pData: the record + .{ .at = 24, .len = 8, .reads = .pointer }, // aMem + .{ .at = 32, .len = 2 }, // nMem + .{ .at = 36, .len = 4, .mark = 1 }, // nData: the record's length + .{ .at = 40, .len = 4 }, // nZero +}; + +/// A table's leaf page, as SQLite's file format has it, read from its +/// bytes: the header (type, first freeblock, cells, where their content +/// begins, fragments), the cell pointers after it, and each cell (its +/// payload's length, its rowid, the record's header, the text of its one +/// column). Every number in it is big-endian; every varint here is a byte. +fn leaf(arena: std.mem.Allocator, page: []const u8) []const Field { + std.debug.assert(page[0] == 0x0d); + const cells = std.mem.readInt(u16, page[3..5], .big); + var out: std.ArrayList(Field) = .empty; + out.appendSlice(arena, &.{ + .{ .at = 0, .len = 1, .mark = 0 }, + .{ .at = 1, .len = 2, .reads = .bytes, .big = true, .mark = 0 }, + .{ .at = 3, .len = 2, .big = true, .mark = 0 }, + .{ .at = 5, .len = 2, .reads = .bytes, .big = true, .mark = 0 }, + .{ .at = 7, .len = 1, .reads = .bytes, .mark = 0 }, + }) catch @panic("OOM"); + for (0..cells) |k| out.append(arena, .{ .at = 8 + 2 * k, .len = 2, .big = true, .mark = 1 }) catch @panic("OOM"); + for (0..cells) |k| { + const at: usize = std.mem.readInt(u16, page[8 + 2 * k ..][0..2], .big); + const size = page[at]; + const header = page[at + 2]; + std.debug.assert(size < 0x80 and page[at + 1] < 0x80 and header == 2); + const mark: u8 = @intCast(2 + k); + out.appendSlice(arena, &.{ + .{ .at = at, .len = 1, .reads = .bytes, .mark = mark }, + .{ .at = at + 1, .len = 1, .mark = mark }, + .{ .at = at + 2, .len = 2, .reads = .bytes, .mark = mark }, + .{ .at = at + 4, .len = size - 2, .reads = .text, .mark = mark }, + }) catch @panic("OOM"); + } + return out.items; +} + +fn frame(s: *anim.Frame) void { + const rec = canim.open(recordings.sqlite); + const t = canim.theme.time; + const region = canim.theme.color.region; + + // The commit's write of page 2: 4096 bytes at offset 4096. The pager + // hands it to unixWrite, which calls pwrite64; and back. + const write = for (0..rec.syscalls.len) |k| { + const c = rec.syscalls[rec.syscalls.len - 1 - k]; + if (c.nr == @intFromEnum(std.os.linux.SYS.pwrite64) and c.args[2] == 4096 and c.args[3] == 4096) break c; + } else @panic("sqlite: no write of page 2"); + const handed = stopAt(rec, "unixWrite+4", write.enter); + const back = stopAt(rec, "unixWrite+", write.enter + 1); + std.debug.assert(handed + 1 == write.enter and back == write.enter + 1); + // The three rows' inserts, and the stop before the first: its statement's bytecode starting. + const third = stopAt(rec, "sqlite3BtreeInsert+", handed); + const second = stopAt(rec, "sqlite3BtreeInsert+", third - 1); + const first = stopAt(rec, "sqlite3BtreeInsert+", second - 1); + const start = stopAt(rec, "sqlite3_step+", first); + + var at = canim.cursor(s, rec, start); + at.levels = .{ .source_rows = 10 }; + at.journey(.moment, back); + // The lens is the subject: the call chain, eleven rows, over the + // program column (where the kernel's side comes later), and over the + // state column the bytes the newest call is handed. + var split = canim.layout.split.subject; + split.backtrace = split.band; + const ctx = canim.context(s, at, .{ .split = split, .syscalls = true }); + const kernel = canim.crossing(s, .{ .cursor = at, .stage = ctx.stage, .view = false }); + // What the opening stop's rbx points at: the SQL sqlite3_exec is running. + const sql = canim.add(s, canim.hexdump.Dump{ + .cursor = at, + .stage = ctx.stage, + .about = "the SQL being run, at rbx", + .of = .{ .base = rec.register(start, "rbx"), .len = 32, .fields = &.{.{ .at = 0, .len = 32, .reads = .text }}, .region = region.rodata }, + }); + // The row, as sqlite3BtreeInsert is handed it: rsi. + // (The views keep their marks: in the frame's arena, not on this stack.) + const row_marks = s.new([_]anim.Value{ s.value(0), s.value(0) }); + const row = canim.add(s, canim.hexdump.Dump{ + .cursor = at, + .stage = ctx.stage, + .about = "pX, the row: a BtreePayload, at rsi", + .of = .{ .base = rec.register(first, "rsi"), .len = 48, .fields = &payload, .region = region.stack }, + .marks = row_marks, + }); + // The page, as unixWrite is handed it: rsi. At that stop the debugger + // has read 32 bytes of it (where rsi leads); the kernel takes it whole. + const bytes = write.text; + std.debug.assert(bytes.len == 4096 and bytes[0] == 0x0d and bytes[4] == 3); + std.debug.assert(std.mem.eql(u8, bytes[8..14], &.{ 0x0f, 0xf7, 0x0f, 0xef, 0x0f, 0xe6 })); + std.debug.assert(rec.register(handed, "rsi") == write.args[1]); + const page_marks = s.new([_]anim.Value{ s.value(0), s.value(0), s.value(0), s.value(0), s.value(0) }); + const page = canim.add(s, canim.hexdump.Dump{ + .cursor = at, + .stage = ctx.stage, + .about = "pBuf: page 2 of t.db, at rsi", + .of = .{ .base = write.args[1], .len = 4096, .fields = leaf(s.arena, bytes), .region = region.heap, .seen = .{ .addr = write.args[1], .len = 32 } }, + .marks = page_marks, + }); + const joins = ctx.ties(s); + var says: canim.Narrator = .{}; + + const fade = struct { + fn in(f: *anim.Frame, o: anim.Obj) void { + f.play(.{o.fadeIn()}, .{ .seconds = canim.theme.time.quick, .ease = anim.ease.linear }); + } + fn out(f: *anim.Frame, o: anim.Obj) void { + f.play(.{o.fadeOut()}, .{ .seconds = canim.theme.time.quick, .ease = anim.ease.linear }); + } + }; + // A field read, as the caption names it: framed in, and out when the caption goes. + const mark = struct { + fn in(f: *anim.Frame, v: anim.Value) void { + f.play(.{v.to(1)}, .{ .seconds = canim.theme.time.read.in, .ease = anim.ease.linear }); + } + fn out(f: *anim.Frame, vs: []const anim.Value) void { + const from = f.cursor; + for (vs) |v| { + f.cursor = from; + f.play(.{v.to(0)}, .{ .seconds = canim.theme.time.read.out, .ease = anim.ease.linear }); + } + } + }; + // A continue: straight to the next stop, timed by what it changed. + const walk = struct { + fn to(c: canim.Cursor, f: *anim.Frame, moment: u64) void { + const plan = c.reading(c.moment(f), moment); + c.step(f, moment, plan, plan.total); + } + }.to; + + canim.establish(s, .{ ctx.clock, ctx.registers, ctx.stack, ctx.source, ctx.disasm, sql, ctx.backtrace, joins }); + says.line(s, "SQLite at a breakpoint in `sqlite3_step`, which runs\n`INSERT INTO t VALUES ('alpha')`. Continue:"); + // What rbx showed was this stop's: it goes before the program moves on. + fade.out(s, sql); + walk(at, s, first); + s.wait(t.beat); + // The row it was handed: a struct on its caller's stack. + fade.in(s, row); + + says.line(s, "`sqlite3VdbeExec`, the bytecode's loop, calls the B-tree: `rdi` is\nthe table's cursor, `rsi` the row: rowid 1, a record of 7 bytes."); + // Each field as the caption reaches it: the rowid, then the record's length. + mark.in(s, row_marks[0]); + s.wait(2 * t.beat); + mark.in(s, row_marks[1]); + + says.line(s, "Two more continues, the same call: rowid 2, then 3, records\nof 6 and 7 bytes. The rows are in memory, not yet on disk."); + mark.out(s, row_marks); + walk(at, s, second); + s.wait(t.beat); + walk(at, s, third); + + says.line(s, "`COMMIT`: `unixWrite`, nine calls under `main`, is handed\npage 2 of the file: 4096 bytes, for offset 4096."); + fade.out(s, row); + walk(at, s, handed); + s.wait(t.beat); + fade.in(s, page); + + says.line(s, "`pwrite64` takes it into the kernel: descriptor 3, the page,\n4096 bytes, offset 4096. The kernel says 4096 were written."); + // The lens changes to the kernel's side, where the page goes. + fade.out(s, ctx.backtrace); + fade.in(s, kernel); + s.wait(t.beat); + const crossing = canim.syscalls.Plan.of(write); + at.step(s, back, crossing.step(), crossing.total); + + says.line(s, "Page 2 as the kernel took it: `0d`, a table's leaf; 3 cells;\ntheir offsets, `0ff7 0fef 0fe6`, each a row at the page's end."); + mark.in(s, page_marks[0]); + s.wait(3 * t.beat); + mark.in(s, page_marks[1]); + says.line(s, "Each cell: its length, its rowid, the record's header, the text.\n'alpha' went in first and sits last: cells fill from the end."); + mark.out(s, page_marks[0..2]); + // The rows from the page's end: the first one in, then the next two. + for (page_marks[2..]) |v| { + mark.in(s, v); + s.wait(2 * t.beat); + } + says.close(s); +} diff --git a/anim/src/Recording.zig b/anim/src/Recording.zig index 280d14a..41619aa 100644 --- a/anim/src/Recording.zig +++ b/anim/src/Recording.zig @@ -210,6 +210,14 @@ pub fn lineOf(r: *const Recording, addr: u64) ?u32 { return if (addr - near.addr <= 96) near.line else null; } +/// The line of the program's own source moment `i` is on; null where it is +/// elsewhere (a library's code, a stop with no line). +pub fn ownLine(r: *const Recording, i: u64) ?u32 { + const l = r.lines[@min(i, r.end())]; + if (l.line == 0 or !std.mem.eql(u8, std.fs.path.basename(r.name(l.file)), r.file)) return null; + return l.line; +} + /// The first line a source panel of `fit` lines shows when the program is /// on `line`: the whole file when it fits; else a window that has the line /// in its middle third, and is the same window for every line of that diff --git a/anim/src/calls.zig b/anim/src/calls.zig index e66da1a..0765ce4 100644 --- a/anim/src/calls.zig +++ b/anim/src/calls.zig @@ -153,11 +153,7 @@ pub const Tree = struct { const y = body.y + cm.pad + @as(f32, @floatFromInt(i)) * cm.row; const name = ui.symbol(u, rec.strings.get(frame.pc) orelse u.print("{x}", .{frame.pc})); // The call this frame is, by its place on the chain: its arguments. - const call: ?Recording.Call = if (i < open.len) open[open.len - 1 - i] else null; - const args = if (call) |c| arguments(u, rec, c) else ""; - const line = if (i == 0) rec.own[now.marked()] else rec.lineOf(frame.pc) orelse 0; - const where = if (line > 0 and (i == 0 or rec.lineOf(frame.pc) != null)) u.print("{s}:{d}", .{ rec.file, line }) else ""; - rows.callRow(u, y, box.w, i, name, args, where, i == 0); + rows.callRow(u, y, box.w, i, name, context.callArguments(u, rec, open, i, frame.pc), context.frameWhere(u, rec, now.marked(), i, frame.pc), i == 0); } context.veiled(u, box, now.sprint_veil); } @@ -172,6 +168,8 @@ pub fn arguments(u: ui.Ui, rec: *const Recording, c: Recording.Call) []const u8 if (!f.takes) return ""; const arg = c.arg orelse return ""; const name = if (c.parameter_name) |id| rec.name(id) else f.param; + // A pointer is an address, hex; a number is its decimal. + if (rows.regionOf(rec.moment(c.enter), arg) != .none) return u.print("{s}={x}", .{ name, arg }); return u.print("{s}={d}", .{ name, @as(i64, @bitCast(arg)) }); } diff --git a/anim/src/context.zig b/anim/src/context.zig index b3591fc..2e86399 100644 --- a/anim/src/context.zig +++ b/anim/src/context.zig @@ -134,54 +134,45 @@ pub const Registers = struct { var landed = now.landed(.cpu, 0); var note: []const u8 = ""; const crossing: ?Recording.Syscall = if (r.syscalls) syscalls.inStep(now) else null; - // A register the call neither carries nor answers in is any register. - const takes_part = if (crossing) |made| std.mem.eql(u8, name, "rax") or for (syscalls.carried(made), 0..) |carried, k| { - if (std.mem.eql(u8, carried, name) and value_now == made.args[k]) break true; - } else false else false; - if (if (takes_part) crossing else null) |made| { - const plan = syscalls.Plan.of(made); - const is_rax = std.mem.eql(u8, name, "rax"); - const carrier: ?usize = if (is_rax) null else for (syscalls.carried(made), 1..) |carried, k| { - if (std.mem.eql(u8, carried, name) and value_now == made.args[k - 1]) break k; - } else null; - // What carries the call is framed as read, one register at a - // time: they are what crosses the line. - const framed = now.time - plan.registers - @as(f32, @floatFromInt(carrier orelse 0)) * time.flight.second; - landed = framed >= 0; - if (carrier != null) { - 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 (landed and carrier.? >= 1 and carrier.? <= names.len and std.mem.endsWith(u8, names[carrier.? - 1], "fd")) note = rec.openOn(u.f.scratch, value_now, made.enter); - } - if (is_rax) { - // rax: what was there, then the result coming back (the - // call's number is the crossing's: it went in at the wrapper). - const back = now.time - plan.returns; - 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); + // 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. - const after_call: f32 = if (crossing) |made| syscalls.Plan.of(made).returns - syscalls.Plan.of(made).registers else 0; - const delay = (if (age == 0) ties.strikeDelay(now, i) else 0) + after_call; + // (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. @@ -242,6 +233,24 @@ fn spanName(u: ui.Ui, rec: *const Recording, open: []const Recording.Call, i: us 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}); @@ -280,12 +289,21 @@ pub const Stack = struct { 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; - const window = if (held) [2]u64{ held_at, held_at } else [2]u64{ windowAt(now, is, slots, 0), windowAt(now, was, slots, 1) }; + 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; - const landed = now.landed(.memory, 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); @@ -317,11 +335,46 @@ pub const Stack = struct { // 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 was.named(name) != is.named(name)) { + 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; @@ -336,10 +389,23 @@ pub const Stack = struct { } // `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(u, y, memory, addr, lead); + rows.free(v, y, memory, addr, lead); continue; } - const hops = rows.slot(u, y, box.w, memory, addr, names.names, names.shows, marks); + // 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 }); @@ -351,7 +417,6 @@ pub const Stack = struct { 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. - const going = cursors.standard(if (now.resting()) 1 else std.math.clamp(now.since(.cpu, 0) / time.move, 0, 1)); 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; @@ -362,33 +427,42 @@ pub const Stack = struct { 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; - u.pinRow(theme.metric.slot.lane, top + place * m.row, if (both) &.{ "rsp", "rbp" } else &.{name}, theme.color.region.stack); + // 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); } - // 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. - var buf: [16]Frame = undefined; - var old_buf: [16]Frame = undefined; - const chain = frames(rec, now.stops[0], &buf); - const old_chain = frames(rec, now.stops[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; + 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; } - }.at; - 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; - rows.span(u, box.w, top + @max(first, 0) * m.row, y1, spanName(u, rec, open_calls, i, if (i < named.len) named[i].pc else frame.pc), i == 0, open); + u.text(.mono_bold, size, x, theme.baseline(y, m.row, size), o, t.primary); + x += u.width(.mono, size, o) + ui.advance(size); } - veiled(u, box, now.veil); + 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, @@ -454,20 +528,49 @@ pub const Backtrace = struct { const u = at(f, placed, box); const now = b.cursor.now(placed); const rec = b.cursor.rec; - var buf: [24]Frame = undefined; - const chain = frames(rec, now.stop(.cpu), &buf); + // 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 body = u.panel(box.w, box.h, "backtrace", .{ .focus = b.focus, .note = if (chain.len > room) u.print("newest on top \u{00b7} {d} more", .{chain.len - room}) else "newest on top" }); + 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(); - for (chain[0..@min(chain.len, room)], 0..) |frame, i| { - const y = body.y + m.pad + @as(f32, @floatFromInt(i)) * m.row; - const name = ui.symbol(u, rec.strings.get(frame.pc) orelse u.print("{x}", .{frame.pc})); - // The program's own frame says where in its source it is. - const where = if (i == 0) u.print("{s}:{d}", .{ rec.file, rec.own[now.marked()] }) else if (rec.lineOf(frame.pc)) |l| u.print("{s}:{d}", .{ rec.file, l }) else ""; - const open = rec.stack(u.f.scratch, now.stop(.cpu)); - const args = if (i < open.len) @import("calls.zig").arguments(u, rec, open[open.len - 1 - i]) else ""; - rows.callRow(u, y, box.w, i, name, args, where, i == 0); + 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); } diff --git a/anim/src/cursor.zig b/anim/src/cursor.zig index 6e3a5b7..ec05ec0 100644 --- a/anim/src/cursor.zig +++ b/anim/src/cursor.zig @@ -58,6 +58,10 @@ pub const Levels = struct { /// How many lines the source panel shows (the split's): a step that /// takes the program out of its window has the window's glide to wait for. source_rows: u32 = 12, + /// A step that makes one syscall is drawn as its crossing (the context + /// sets it, `Context.Options.syscalls`): what the step changed in the + /// registers strikes once the call is back. + crossings: bool = false, }; /// How a step is drawn. Walk: everything, as a sentence. Run: the mark and @@ -351,6 +355,7 @@ pub const Cursor = struct { .of = c.of, .place = 0, .fired = c.levels.fire, + .crossings = c.levels.crossings, .way = .{ c.first, c.last }, }; for (&n.stops, c.stops) |*stop_at, v| stop_at.* = whole(rec, placed.value(v)); @@ -403,6 +408,8 @@ pub const Now = struct { place: f32, /// Where the scene's steps fire (`Levels.fire`). fired: @FieldType(Levels, "fire") = .source, + /// Steps that make a syscall cross into the kernel (`Levels.crossings`). + crossings: bool = false, /// The scene's way through the recording: its first moment and its last. way: [2]u64 = .{ 0, 0 }, diff --git a/anim/src/disasm.zig b/anim/src/disasm.zig index efdb80e..6faaade 100644 --- a/anim/src/disasm.zig +++ b/anim/src/disasm.zig @@ -158,6 +158,11 @@ pub const Disasm = struct { }; var last_line: ?u32 = null; + // A source of many lines (SQLite's) has wider numbers: what is + // right of them moves right by as much. + var widest: u32 = 0; + for (merged) |row| widest = @max(widest, row.line orelse 0); + const widen = rows.numberRoom(widest); // The thread's runs: of the line the mark leaves and of the one it // goes to, each a span of rows; published sliding from the one to // the other with the advance (`threadRuns`). @@ -182,7 +187,7 @@ pub const Disasm = struct { const is_pc = row.addr == pc[if (going >= 0.5) 1 else 0]; const was = if (is_pc) null else ran[j]; if (was) |r| lit.trail(c.mark, y, r.k); - const hangs = d.insn(lit, now, row, y, box.w, line, line != last_line, current_line, lead, if (is_pc) .current else if (was) |r| .{ .ran = r } else .ahead, base, covered > 0); + const hangs = d.insn(lit, now, row, y, box.w, widen, line, line != last_line, current_line, lead, if (is_pc) .current else if (was) |r| .{ .ran = r } else .ahead, base, covered > 0); covered = @max(covered -| 1, hangs); last_line = if (above_body) null else line; if (jumped == row.addr and !is_pc) lanes[0] = y; @@ -209,15 +214,17 @@ pub const Disasm = struct { /// where the annotation carries the address they name. `covered`: a /// call's arguments above hang in this row's annotation column. Returns /// how many rows under it its own arguments hang in. - fn insn(d: *const Disasm, u: ui.Ui, now: cursors.Now, row: Insn, y: f32, w: f32, line: ?u32, first_of_line: bool, current_line: u32, lead: usize, state: State, base: usize, covered: bool) usize { + fn insn(d: *const Disasm, at: ui.Ui, now: cursors.Now, row: Insn, y: f32, w: f32, widen: f32, line: ?u32, first_of_line: bool, current_line: u32, lead: usize, state: State, base: usize, covered: bool) usize { const rec = d.cursor.rec; const base_y = rows.baseline(y); const code_ink = theme.color.region.code_; - const room = w - m.side; + // Right of the line's column, all of it moved by `widen`. + const u = at.moved(widen, 0); + const room = w - m.side - widen; if (row.outside) { // The function ends: a rule, and the next one's name. u.fill(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = theme.stroke.rule }, theme.color.rule); - _ = u.address(c.address, base_y, row.addr, .{ .ink = ui.mix(code_ink, theme.color.page, theme.metric.context.lead_alpha) }); + _ = at.address(c.address, base_y, row.addr, .{ .ink = ui.mix(code_ink, theme.color.page, theme.metric.context.lead_alpha) }); u.text(.mono, size, c.mnemonic, base_y, row.mnemonic(), t.faint); const name = if (rec.strings.get(row.addr)) |n| n[0 .. std.mem.lastIndexOfScalar(u8, n, '+') orelse n.len] else ""; const x = if (name.len > 0) annotationX(operandsWidth(row, row.operands()), room, @as(f32, @floatFromInt(name.len)) * adv) else room + gap; @@ -225,7 +232,7 @@ pub const Disasm = struct { u.text(.mono, size, x, base_y, name, t.faint); return 0; } - _ = u.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(code_ink), .lead = lead }); + _ = at.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(code_ink), .lead = lead }); if (first_of_line) if (line) |l| { const num = u.print("{d}", .{l}); const now_line = l == current_line; diff --git a/anim/src/hexdump.zig b/anim/src/hexdump.zig index bd76150..b98d9bd 100644 --- a/anim/src/hexdump.zig +++ b/anim/src/hexdump.zig @@ -79,6 +79,52 @@ pub fn panel(f: *@import("sketch").Frame, placed: @import("anim").Placed, stage: return .{ .u = u, .rows = theme.layout.rowsIn(box.h), .box = box }; } +/// A view of a region the scene names (`of`), by its fields: the band's +/// right half, over the state column. The scene marks fields as read +/// (`marks`, a value each: how much the frame shows). In a step that hands +/// the region to the kernel (a write's buffer), its fields are framed as +/// read while the kernel takes them, and the bytes the recording had not +/// seen come in from the call's capture, dots to digits, with no mark. +pub const Dump = struct { + cursor: cursors.Cursor, + stage: *const @import("stage.zig").Stage, + /// The tag's words, after `its bytes`; and the legend of its fields. + about: []const u8, + legend: []const ui.Legend = &.{}, + of: Fields, + marks: []const @import("anim").Value = &.{}, + + pub fn draw(d: *const Dump, f: *@import("sketch").Frame, placed: @import("anim").Placed) void { + const v = panel(f, placed, d.stage, d.about, d.legend); + defer v.u.unclip(); + if (v.rows == 0) return; + const now = d.cursor.now(placed); + var of = d.of; + var shows: [8]f32 = @splat(0); + const marked = @min(d.marks.len, shows.len); + for (d.marks[0..marked], shows[0..marked]) |mark, *value| value.* = placed.value(mark); + of.marks = shows[0..marked]; + // A call the step made that was given these bytes: as the kernel + // took them, from when its work begins (and at the stop after it; + // a step later the program may have written them again). + const syscalls = @import("syscalls.zig"); + for (d.cursor.rec.syscalls) |made| { + if (made.enter <= now.stops[1] or made.enter > now.stops[0]) continue; + const span = syscalls.bufferRead(made) orelse continue; + if (span.addr >= of.base + of.len or span.addr + span.len <= of.base) continue; + var shown: f32 = 1; + if (!now.resting()) { + const p = syscalls.Plan.of(made); + shown = std.math.clamp((now.time - p.work) / theme.time.quick, 0, 1); + of.read = now.held(p.work); + } + of.given = .{ .addr = span.addr, .bytes = made.text[0..@min(made.text.len, span.len)], .shows = shown }; + } + fielded(v, now, m.tag + m.pad, of); + v.veil(now); + } +}; + /// The view's panel as drawn: its `Ui`, how many rows it holds, its box. pub const View = struct { u: ui.Ui, @@ -140,14 +186,14 @@ pub fn draw(u: ui.Ui, now: cursors.Now, x: f32, y: f32, first: u64, count: usize at += run.len; } rows.bytes(v, ry, addr, &values, &known, runs[0..n], of.region, lead, holds_drawn, moment); - reading(v, ry, moment, &values, &known, runs[0..n]); + reading(v, ry, addr, moment, &values, &known, runs[0..n]); } } /// The reading: what the runs read as, little-endian. A number ranged /// right in three characters; a pointer as `points` and its address; /// `NULL` dim; an allocator's run as a note, faint. -fn reading(u: ui.Ui, y: f32, moment: Recording.Moment, values: *const [16]u8, known: *const [16]bool, runs: []const rows.Run) void { +fn reading(u: ui.Ui, y: f32, addr: u64, moment: Recording.Moment, values: *const [16]u8, known: *const [16]bool, runs: []const rows.Run) void { const size = theme.size.mono.context; const base = rows.baseline(y); var x: f32 = b.reading; @@ -173,12 +219,234 @@ fn reading(u: ui.Ui, y: f32, moment: Recording.Moment, values: *const [16]u8, kn x = u.arrow(x, y + m.row / 2, .points); x = u.address(x, base, word, .{ .ink = ui.rgb(rows.ink(rows.regionOf(moment, word))) }) + 8; }, - .allocator => if (run.first == 8 and run.len == 8) { + .allocator => if (run.first == 8 and run.len == 8 and chunkAfter(moment, addr + 8)) { // The size word of the chunk after: malloc's. u.text(.sans, theme.size.sans.micro, x, base - 1, u.print("malloc's: a chunk of {d}", .{word & ~@as(u64, 7)}), t.faint); return; }, - .unread => {}, + .text, .unread => {}, + } + } +} + +/// Whether an allocation the recording has begins just after the word at +/// `word` (the chunk's size word, glibc's and musl's alike): only there are +/// bytes between allocations the allocator's own, to be read as its. +fn chunkAfter(moment: Recording.Moment, word: u64) bool { + const a = (moment.allocation(word + 8) catch return false) orelse return false; + return a.ptr == word + 8; +} + +/// What a field of a region reads as: a number (little-endian, or `big`), +/// a pointer, text (in quotes, C's escapes), or bytes the reading leaves +/// to the eye. +pub const Reads = enum { number, pointer, text, bytes }; + +/// A field of the region a view is about, from the region's first byte. +pub const Field = struct { + at: u64, + len: u64, + reads: Reads = .number, + /// Stored high byte first (SQLite's pages are). + big: bool = false, + /// Which of the view's marks frames it as read (`Fields.marks`). + mark: ?u8 = null, +}; + +/// What a dump of fields is of, and how it is marked now. +pub const Fields = struct { + /// The region: where it begins, how long it is, the ink of its memory. + base: u64, + len: u64, + fields: []const Field, + region: u24 = theme.color.region.heap, + /// How much each of the view's marks shows (a frame, read's colour). + marks: []const f32 = &.{}, + /// Bytes known from elsewhere than the moment's memory (what a syscall + /// was given, as the kernel took them), and how much they show (0 to 1). + given: ?struct { addr: u64, bytes: []const u8, shows: f32 } = null, + /// How much a frame round every field shows: the kernel reading them. + read: f32 = 0, + /// The part of the region the recording read at the stop shown (null: + /// all of it as last seen). Memory nothing watches is read only where a + /// pointer leads, 32 bytes at a stop; elsewhere its last seen bytes may + /// be long out of date, and are drawn as not seen. + seen: ?Recording.Span = null, +}; + +/// The region's rows in view `v`, from `y`, sixteen bytes a row from its +/// first byte: those that hold a field (all of them, where they fit), and +/// for a stretch left out one row of `more`'s dots and how many rows it +/// stands for. A field is a run, cut where a row ends; a byte that is no +/// field is drawn as the allocator's (dim, no paper) and reads as nothing. +pub fn fielded(v: View, now: cursors.Now, y: f32, of: Fields) void { + const u = v.u; + const moment = now.shown(.memory); + const total = (of.len + 15) / 16; + var shown: [16]u64 = undefined; + var n: usize = 0; + for (0..total) |r| { + const lo = of.base + 16 * r; + const holds = for (of.fields) |field| { + if (of.base + field.at < lo + 16 and of.base + field.at + field.len > lo) break true; + } else false; + if ((holds or total <= v.rows) and n < shown.len) { + shown[n] = r; + n += 1; + } + } + const lead = ui.shared(&.{ of.base, of.base + 16 * (total -| 1) }); + var ry = y; + var last: ?u64 = null; + for (shown[0..n]) |r| { + if (last) |l| if (r > l + 1) { + // A stretch left out: one row, three dots and a count. + const after = u.arrow(b.address, ry + m.row / 2, .more); + u.text(.mono, theme.size.mono.context, after + adv, rows.baseline(ry), u.print("{d} rows", .{r - l - 1}), t.faint); + ry += m.row; + }; + last = r; + fieldRow(u, now, ry, of.base + 16 * r, moment, of, lead); + ry += m.row; + } +} + +fn fieldRow(u: ui.Ui, now: cursors.Now, y: f32, addr: u64, moment: Recording.Moment, of: Fields, lead: usize) void { + var values: [16]u8 = undefined; + var known: [16]bool = undefined; + moment.read(addr, &values, &known) catch return; + if (of.seen) |seen| for (&known, 0..) |*k, i| { + if (addr + i < seen.addr or addr + i >= seen.addr + seen.len) k.* = false; + }; + // What a call was given is as the kernel took it, and not what the + // recording saw there before (a debugger reads a buffer it is not + // watching only where a pointer leads, 32 bytes at a stop: the rest + // is as it was when last seen): it comes in over what was drawn. + var given_values = values; + var given_known = known; + var gives = false; + var given_from: u8 = 16; + var given_to: u8 = 0; + if (of.given) |g| for (0..16) |i| { + const a = addr + i; + if (a < g.addr or a >= g.addr + g.bytes.len) continue; + given_values[i] = g.bytes[a - g.addr]; + given_known[i] = true; + gives = true; + given_from = @min(given_from, @as(u8, @intCast(i))); + given_to = @max(given_to, @as(u8, @intCast(i))); + }; + const shift = rows.addressRoom(addr); + var runs: [16]rows.Run = undefined; + var readings: [16]Field = undefined; + var n: usize = 0; + var at: u8 = 0; + while (at < 16 and addr + at < of.base + of.len) { + const here = addr + at; + const field = for (of.fields) |field| { + if (of.base + field.at <= here and here < of.base + field.at + field.len) break field; + } else null; + var run: rows.Run = .{ .first = at, .len = 1, .kind = .allocator }; + if (field) |fl| { + run.len = @intCast(@min(of.base + fl.at + fl.len - here, 16 - @as(u64, at))); + run.kind = switch (fl.reads) { + .number, .bytes => .number, + .pointer => .pointer, + .text => .text, + }; + run.heat = now.written(here, run.len, .memory, 0); + var framed: f32 = 0; + if (fl.mark) |k| if (k < of.marks.len) { + framed = of.marks[k]; + }; + if (now.wasRead(here, run.len) and now.writeAge(here, run.len) != 0) framed = @max(framed, now.reading(.memory, 0)); + run.read = framed; + readings[n] = .{ .at = at, .len = run.len, .reads = fl.reads, .big = fl.big }; + ties.anchor(u, .{ .dump_run = here }, .{ .x = shift + rows.byteX(run.first) - 4, .y = y, .w = rows.byteX(run.first + run.len - 1) + 28 - rows.byteX(run.first) + 4, .h = m.row }); + } else { + // Up to the next field, or the row's end. + var end: u64 = @min(16, of.base + of.len - addr); + for (of.fields) |other| if (of.base + other.at > here and of.base + other.at < addr + end) { + end = of.base + other.at - addr; + }; + run.len = @intCast(end - at); + readings[n] = .{ .at = at, .len = run.len, .reads = .bytes }; + } + runs[n] = run; + n += 1; + at += run.len; + } + // The kernel reading them: one frame round what it took of the row. + if (gives and of.read > 0) u.faded(of.read).frame(.{ .x = shift + rows.byteX(given_from) - 7, .y = y - 1, .w = rows.byteX(given_to) - rows.byteX(given_from) + 38, .h = m.row + 2 }, theme.mark(.read).solid, 2); + const shows = if (of.given) |g| g.shows else 0; + if (gives and shows > 0) { + if (shows < 1) rows.bytesAt(u.faded(1 - shows), y, addr, &values, &known, runs[0..n], of.region, lead, true, moment, shift); + rows.bytesAt(u.faded(shows), y, addr, &given_values, &given_known, runs[0..n], of.region, lead, true, moment, shift); + fieldReading(u.faded(shows), y, shift, moment, &given_values, &given_known, readings[0..n]); + } else { + rows.bytesAt(u, y, addr, &values, &known, runs[0..n], of.region, lead, true, moment, shift); + fieldReading(u, y, shift, moment, &values, &known, readings[0..n]); + } +} + +/// The reading of a row of fields, left to right, a character apart: a +/// number in decimal, a pointer as `points` and its address, text in +/// quotes; bytes left to the eye read as nothing. Cut where the panel +/// ends, with `…`. +fn fieldReading(u: ui.Ui, y: f32, shift: f32, moment: Recording.Moment, values: *const [16]u8, known: *const [16]bool, fields: []const Field) void { + const size = theme.size.mono.context; + const base = rows.baseline(y); + const room = theme.layout.state.w - theme.metric.context.side; + var x: f32 = b.reading + shift; + for (fields) |fl| { + const first: usize = @intCast(fl.at); + const len: usize = @intCast(fl.len); + if (fl.reads == .bytes) continue; + if (std.mem.indexOfScalar(bool, known[first..][0..len], false) != null) continue; + const bytes = values[first..][0..len]; + const words: []const u8 = switch (fl.reads) { + .number => blk: { + var word: u64 = 0; + for (0..@min(len, 8)) |k| word |= @as(u64, bytes[if (fl.big) len - 1 - k else k]) << @intCast(8 * k); + break :blk u.print("{d}", .{word}); + }, + .pointer => blk: { + var word: u64 = 0; + for (0..@min(len, 8)) |k| word |= @as(u64, bytes[k]) << @intCast(8 * k); + if (word == 0) break :blk "NULL"; + if (x + theme.metric.context.arrow_w + @as(f32, @floatFromInt(ui.digits(word))) * adv > room) break :blk "\u{2026}"; + x = u.arrow(x, y + m.row / 2, .points); + x = u.address(x, base, word, .{ .ink = ui.rgb(rows.ink(rows.regionOf(moment, word))) }) + adv; + continue; + }, + .text => quoted(u, bytes), + .bytes => unreachable, + }; + const w = u.width(.mono, size, words); + const fits = x + w <= room; + const shown = if (fits) words else rows.fitted(u, words, room - x); + const ink = if (fl.reads == .text) theme.color.string else if (std.mem.eql(u8, words, "NULL")) t.dim else t.primary; + u.text(.mono, size, x, base, shown, ink); + if (!fits) return; + x += w + adv; + } +} + +/// Bytes as C text, in quotes: the printable as they are, the rest by C's +/// escapes; a NUL ends it. +fn quoted(u: ui.Ui, bytes: []const u8) []const u8 { + const a = u.f.scratch; + var out: std.ArrayList(u8) = .empty; + out.append(a, '"') catch return ""; + for (bytes) |c| { + if (c == 0) break; + switch (c) { + '\n' => out.appendSlice(a, "\\n") catch {}, + '\t' => out.appendSlice(a, "\\t") catch {}, + '"', '\\' => out.appendSlice(a, &.{ '\\', c }) catch {}, + else => if (std.ascii.isPrint(c)) out.append(a, c) catch {} else out.print(a, "\\x{x:0>2}", .{c}) catch {}, } } + out.append(a, '"') catch {}; + return out.items; } diff --git a/anim/src/root.zig b/anim/src/root.zig index 6aa47de..2f59420 100644 --- a/anim/src/root.zig +++ b/anim/src/root.zig @@ -251,8 +251,10 @@ pub const Context = struct { } }; -pub fn context(s: *anim.Frame, at: Cursor, options: Context.Options) Context { +pub fn context(s: *anim.Frame, cursor_: Cursor, options: Context.Options) Context { const stage = Stage.init(s, options.split); + var at = cursor_; + at.levels.crossings = options.syscalls; return .{ .stage = stage, .cursor = at, diff --git a/anim/src/rows.zig b/anim/src/rows.zig index 4d8a42b..9e5bbba 100644 --- a/anim/src/rows.zig +++ b/anim/src/rows.zig @@ -233,9 +233,13 @@ pub fn span(u: ui.Ui, w: f32, y0: f32, y1: f32, name: []const u8, newest: bool, const x = w - theme.metric.slot.span; const c = if (newest) theme.mark(.current).solid else theme.color.rule; u.bracket(x, y0 + 3, y1 - @as(f32, if (open) 0 else 3), c, theme.metric.bracket.quiet, -1, open); - const micro = theme.size.sans.micro; const mid = (y0 + y1) / 2 + 6; - u.text(.sans_medium, micro, x - 14 - u.width(.sans_medium, micro, name), mid, name, if (newest) t.bright else t.dim); + u.text(.sans_medium, theme.size.sans.micro, spanNameX(u, w, name), mid, name, if (newest) t.bright else t.dim); +} + +/// Where a `span`'s name begins, in a panel `w` wide. +pub fn spanNameX(u: ui.Ui, w: f32, name: []const u8) f32 { + return w - theme.metric.slot.span - 14 - u.width(.sans_medium, theme.size.sans.micro, name); } /// `call` `row`: `#n` at 12 (a gold plaque 40 wide on the newest), the @@ -266,18 +270,19 @@ pub fn fitted(u: ui.Ui, text: []const u8, width: f32) []const u8 { /// then a faint `…`. `current`: a gold plaque 50 wide on the number (its /// edges out `fire`), ember across; `marked`: the number as on the plaque, /// which its panel draws where the mark is (it slides). `trail`: the bar -/// (0 newest). -pub fn line(u: ui.Ui, y: f32, w: f32, number: u32, text: []const u8, styles: []const u8, state: union(enum) { plain, current: f32, marked, trail: usize }) void { +/// (0 newest). `widen`: how much more room the numbers of the window take +/// than three characters (`numberRoom`); the text moves right by as much. +pub fn line(u: ui.Ui, y: f32, w: f32, number: u32, widen: f32, text: []const u8, styles: []const u8, state: union(enum) { plain, current: f32, marked, trail: usize }) void { const gold = theme.mark(.current); switch (state) { - .current => |fire| u.current(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = row_h }, theme.metric.plaque.line, fire), + .current => |fire| u.current(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = row_h }, theme.metric.plaque.line + widen, fire), .trail => |k| u.trail(theme.stroke.rule, y, k), .plain, .marked => {}, } const on = state == .current or state == .marked; const num = u.print("{d}", .{number}); - u.text(if (on) .mono_bold else .mono, size, m.line_number_end - @as(f32, @floatFromInt(num.len)) * adv, baseline(y), num, if (on) gold.on_solid else t.faint); - const limit: usize = m.source_chars; + u.text(if (on) .mono_bold else .mono, size, m.line_number_end + widen - @as(f32, @floatFromInt(num.len)) * adv, baseline(y), num, if (on) gold.on_solid else t.faint); + const limit: usize = m.source_chars - @as(usize, @intFromFloat(widen / adv)); const end = @min(text.len, limit); var i: usize = 0; while (i < end) { @@ -285,11 +290,17 @@ pub fn line(u: ui.Ui, y: f32, w: f32, number: u32, text: []const u8, styles: []c while (j < end and styles[j] == styles[i]) j += 1; if (std.mem.indexOfNone(u8, text[i..j], " ") != null) { const class = styles[i]; - u.text(codeFace(class), size, m.line_text + @as(f32, @floatFromInt(i)) * adv, baseline(y), text[i..j], codeInk(class)); + u.text(codeFace(class), size, m.line_text + widen + @as(f32, @floatFromInt(i)) * adv, baseline(y), text[i..j], codeInk(class)); } i = j; } - if (text.len > limit) u.text(.mono, size, m.line_text + @as(f32, @floatFromInt(limit)) * adv, baseline(y), "\u{2026}", t.faint); + if (text.len > limit) u.text(.mono, size, m.line_text + widen + @as(f32, @floatFromInt(limit)) * adv, baseline(y), "\u{2026}", t.faint); +} + +/// How much wider than three characters a column of line numbers up to +/// `widest` is: nothing for a small program; SQLite's lines have six digits. +pub fn numberRoom(widest: u32) f32 { + return @as(f32, @floatFromInt(@max(std.fmt.count("{d}", .{widest}), 3) - 3)) * adv; } /// pardes's classes: none, keyword, string, number, comment. @@ -316,7 +327,7 @@ fn codeFace(class: u8) ui.Face { pub const Run = struct { first: u8, len: u8, - kind: enum { number, pointer, allocator, unread }, + kind: enum { number, pointer, text, allocator, unread }, /// Its mark: struck (heat), read (shows), held is in the heat. heat: ui.Heat = .none, read: f32 = 0, @@ -327,19 +338,34 @@ pub const Run = struct { /// region ink with `lead` at 18 (at 60% on a row that holds no drawn /// thing), the bytes from 132 on a pitch of 30, 12 more after the /// eighth; a field's bytes on raised paper in their ink (a pointer's in -/// the region it points into), an allocator's dim with no paper, never +/// the region it points into, text's in a string's), an allocator's (and +/// any that are no field of what the dump is about) dim with no paper, never /// read two dots a byte; a word's padding bytes faint. `reading` is drawn /// by the caller at 640. pub fn bytes(u: ui.Ui, y: f32, addr: u64, values: *const [16]u8, known: *const [16]bool, runs: []const Run, region: u24, lead: usize, holds_drawn: bool, moment: Recording.Moment) void { + bytesAt(u, y, addr, values, known, runs, region, lead, holds_drawn, moment, 0); +} + +/// How far right of their column a row's bytes (and its reading) go to +/// leave its address room: none for one of eight digits, 42 for a stack +/// address's twelve. +pub fn addressRoom(addr: u64) f32 { + const b = theme.metric.bytes; + return @max(b.address + @as(f32, @floatFromInt(ui.digits(addr))) * adv + adv - b.first, 0); +} + +/// `bytes`, the sixteen bytes `shift` right of their column (`addressRoom`). +pub fn bytesAt(at: ui.Ui, y: f32, addr: u64, values: *const [16]u8, known: *const [16]bool, runs: []const Run, region: u24, lead: usize, holds_drawn: bool, moment: Recording.Moment, shift: f32) void { const b = theme.metric.bytes; const base = baseline(y); - _ = u.address(b.address, base, addr, .{ .ink = if (holds_drawn) ui.rgb(region) else ui.mix(region, theme.color.page, theme.metric.context.lead_alpha), .lead = lead }); - if (holds_drawn) u.bracket(b.bracket, y + 3, y + row_h - 3, ui.mix(region, theme.color.page, theme.metric.context.lead_alpha), theme.metric.bracket.quiet, 1, false); + _ = at.address(b.address, base, addr, .{ .ink = if (holds_drawn) ui.rgb(region) else ui.mix(region, theme.color.page, theme.metric.context.lead_alpha), .lead = lead }); + if (holds_drawn) at.bracket(b.bracket, y + 3, y + row_h - 3, ui.mix(region, theme.color.page, theme.metric.context.lead_alpha), theme.metric.bracket.quiet, 1, false); + const u = at.moved(shift, 0); for (runs) |run| { const x0 = byteX(run.first) - 4; const x1 = byteX(run.first + run.len - 1) + 28; const r: Rect = .{ .x = x0, .y = y + 1, .w = x1 - x0, .h = row_h - 2 }; - const field = run.kind == .number or run.kind == .pointer; + const field = run.kind == .number or run.kind == .pointer or run.kind == .text; if (field) u.fill(r, theme.color.raised); // Marks per run, never per byte: struck (the paper solid), read (a // frame 3 out), held (a tick in the gap at the run's left). @@ -367,6 +393,7 @@ pub fn bytes(u: ui.Ui, y: f32, addr: u64, values: *const [16]u8, known: *const [ const run_ink: ui.Color = switch (run.kind) { .number => ui.rgb(t.primary), .pointer => ui.rgb(if (run.len == 8) ink(regionOf(moment, word)) else t.primary), + .text => ui.rgb(theme.color.string), .allocator => ui.rgb(t.dim), .unread => ui.rgb(t.faint), }; diff --git a/anim/src/source.zig b/anim/src/source.zig index 0bba714..6b693a4 100644 --- a/anim/src/source.zig +++ b/anim/src/source.zig @@ -42,7 +42,12 @@ pub const Source = struct { // moves on) gliding to where the next one does. It never cuts. const going = now.advancing(); const windows = [2]f32{ @floatFromInt(rec.viewFirst(fit, was)), @floatFromInt(rec.viewFirst(fit, here)) }; - const first = std.math.lerp(windows[0], windows[1], cursors.glide(going)); + // Further than two windows (a large file, another function far + // off): what leaves has left before what replaces it arrives; a + // scroll through thousands of lines would be a blur, and say nothing. + const far = @abs(windows[1] - windows[0]) > 2 * @as(f32, @floatFromInt(fit)); + const first = if (far) windows[if (going >= 0.5) 1 else 0] else std.math.lerp(windows[0], windows[1], cursors.glide(going)); + const lit = if (far and going < 1) u.faded(@abs(2 * going - 1)) else u; const from: u32 = @intFromFloat(@floor(first)); const last: u32 = @min(from + @as(u32, @intCast(context.rowsOf(box))), rec.line_count); const shown_first: u32 = @intFromFloat(windows[if (going >= 0.5) 1 else 0]); @@ -73,11 +78,13 @@ pub const Source = struct { } } const mark_y = top + (mark_at - first) * m.row; + // The numbers of the two windows, as wide as the widest needs. + const widen = rows.numberRoom(@min(@as(u32, @intFromFloat(@max(windows[0], windows[1]))) + @as(u32, @intCast(context.rowsOf(box))), rec.line_count)); context.clipBody(u, box); defer u.unclip(); // The plaque over the number. Fire: on the line about to run its // edges go out and come back, once, and nothing else moves. - if (shows > 0) u.faded(shows).current(.{ .x = theme.stroke.rule, .y = mark_y, .w = box.w - 2 * theme.stroke.rule, .h = m.row }, theme.metric.plaque.line, now.fires(.source)); + if (shows > 0) u.faded(shows).current(.{ .x = theme.stroke.rule, .y = mark_y, .w = box.w - 2 * theme.stroke.rule, .h = m.row }, theme.metric.plaque.line + widen, now.fires(.source)); if (shows >= 1 and mark_y >= body.y and mark_y + m.row <= box.h) ties.anchor(u, .source, .{ .x = 0, .y = mark_y, .w = box.w, .h = m.row }); // The trail: the last three other lines it was on. It shifts without animation. @@ -99,7 +106,7 @@ pub const Source = struct { const span = text.lines[line - 1]; const k = std.mem.indexOfScalar(u32, trail[0..found], line); const on = shows >= 0.5 and line == mark_line; - rows.line(u, y, box.w, line, text.bytes[span[0]..span[1]], text.styles[span[0]..span[1]], if (on) .marked else if (k) |n| .{ .trail = n } else .plain); + rows.line(lit, y, box.w, line, widen, text.bytes[span[0]..span[1]], text.styles[span[0]..span[1]], if (on) .marked else if (k) |n| .{ .trail = n } else .plain); } // The source is read at a run; at a sprint it is veiled too. context.veiled(u, box, now.sprint_veil); diff --git a/anim/src/syscalls.zig b/anim/src/syscalls.zig index 67085c2..b3e080d 100644 --- a/anim/src/syscalls.zig +++ b/anim/src/syscalls.zig @@ -29,8 +29,8 @@ const k = theme.color.on_kernel; /// 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` 4.0 s, a `read` of -/// fifteen bytes 5.1. +/// So a call is as long as what it does: `close` 4.1 s, a `read` of +/// fifteen bytes 5.2. pub const Plan = struct { registers: f32 = time.cascade, enters: f32 = 0.80, @@ -45,14 +45,16 @@ pub const Plan = struct { work: f32 = 2.00, fills: f32 = 2.40, bytes: f32 = 0, - /// The arrow back sets off; rax is struck; the `returns` row takes the - /// value; the program stores what came back (memory, after its - /// cause); the mark moves on. + /// The arrow back sets off; as it lands the `returns` row takes the + /// value; then rax is armed, and struck (nothing is marked as come + /// back before it has); the program stores what came back (memory, + /// after its cause); the mark moves on. back: f32 = 2.00, returns: f32 = 2.40, - stored: f32 = 2.80, - advance: f32 = 3.40, - total: f32 = 4.00, + struck: f32 = 2.60, + stored: f32 = 2.90, + advance: f32 = 3.50, + total: f32 = 4.10, pub const cross = 0.40; pub const row = 0.10; @@ -66,7 +68,8 @@ pub const Plan = struct { 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.stored = p.returns + row + time.cascade; + p.struck = p.returns + time.strike.arm; + p.stored = p.struck + time.cascade; p.advance = p.stored + time.read_value; p.total = p.advance + time.step + time.rest; return p; @@ -97,6 +100,16 @@ pub fn step(c: cursors.Cursor, s: *anim.Frame, by: Recording.Stop) void { c.step(s, to, p.step(), p.total); } +/// 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.of(made); + return p.struck - p.registers; +} + /// The argument registers of a syscall, in order. const carriers = [_][]const u8{ "rdi", "rsi", "rdx", "r10", "r8", "r9" }; @@ -110,10 +123,13 @@ pub fn latest(rec: *const Recording, i: u64) ?usize { return found; } -/// The syscall the cursor's step made (the newest, when it made several). +/// 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; } @@ -147,12 +163,15 @@ 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 { - c.view(f, placed); + 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)); @@ -167,7 +186,7 @@ pub const Crossing = struct { 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 live = inStep(now) != null 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]); @@ -196,7 +215,7 @@ pub const Crossing = struct { v.frame(card, k.ink, theme.stroke.rule); const name = zt.syscalls.name(done.nr) orelse "?"; // The result ranged right, when it is short; the name has the rest, and is cut only there. - const words = if ((i != newest or t >= p.returns + Plan.row) and done.exit != null) result(u, done) else ""; + const words = if ((i != newest or t >= p.returns) and done.exit != null) result(u, done) else ""; const said = if (words.len > 0 and words.len <= 4) words else ""; if (said.len > 0) v.text(.mono, size, card.x + card.w - 8 - u.width(.mono, size, said), theme.baseline(card.y, card.h, size), said, k.dim); v.text(if (gold) .mono_bold else .mono, size, card.x + 8, theme.baseline(card.y, card.h, size), rows.fitted(u, name, card.w - 16 - (if (said.len > 0) u.width(.mono, size, said) + 12 else 0)), k.ink); @@ -206,12 +225,12 @@ pub const Crossing = struct { /// Its view: the bytes the newest call is given or fills (its path, a /// buffer), as a dump over the state column; struck as the kernel /// fills them. - fn view(c: *const Crossing, f: *sk.Frame, placed: anim.Placed) void { + fn bytesView(c: *const Crossing, f: *sk.Frame, placed: anim.Placed) void { const rec = c.cursor.rec; const now = c.cursor.now(placed); var newest = latest(rec, now.stops[0]); // No effect before its cause: until the kernel has taken the call, the last one's bytes. - if (newest) |n| if (rec.syscalls[n].enter > now.stops[1] and now.walking() and now.time < Plan.of(rec.syscalls[n]).name) { + if (newest) |n| if (inStep(now) != null and now.walking() and now.time < Plan.of(rec.syscalls[n]).name) { newest = if (n > 0) n - 1 else null; }; const made: ?Recording.Syscall = if (newest) |n| rec.syscalls[n] else null; @@ -222,9 +241,20 @@ pub const Crossing = struct { defer v.u.unclip(); const sp = span orelse return; if (v.rows == 0) return; - const first = sp.addr & ~@as(u64, 15); - const n = @min(v.rows, (sp.addr + sp.len - first + 15) / 16); - hexdump.draw(v.u, now, 0, theme.metric.context.tag + theme.metric.context.pad, first, n, .{ .region = context.ink(context.regionOf(now.moment(), sp.addr)) }); + // 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 given = made.?; + const text = given.text[0..@min(given.text.len, sp.len)]; + 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(v, 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 }, + }); v.veil(now); } @@ -263,7 +293,7 @@ pub const Crossing = struct { row(u.faded(shows), row_y, carriers[arg], meaning, value(u, made, kind, arg, &text_used), note); row_y += row_h + 4; } - const back = t >= p.returns + Plan.row and made.exit != null; + const back = t >= p.returns and made.exit != null; // What `open` returns is a descriptor: open on the path it was given. const opened = back and std.mem.eql(u8, zt.syscalls.name(made.nr) orelse "", "open") and @as(i64, @bitCast(made.result)) >= 0; 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 (opened) rec.openOn(u.f.scratch, made.result, made.exit.? + 1) else ""); @@ -273,6 +303,9 @@ pub const Crossing = struct { 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); + const text = for (made.text[0..shown]) |byte| { + if (!std.ascii.isPrint(byte) and byte != '\n') break false; + } else true; for (made.text[0..shown], 0..) |byte, j| { const cell: Rect = .{ .x = bytes_x + @as(f32, @floatFromInt(j % per_row)) * 28, .y = body.y + 32 + @as(f32, @floatFromInt(j / per_row)) * 30, .w = 26, .h = 26 }; // Each fills as it is copied, two frames a byte: struck, then held. @@ -285,7 +318,10 @@ pub const Crossing = struct { 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); + // Text as its characters; anything else (a page of a file) as hex. + if (!text) { + u.label(.mono, size, cell, .center, u.print("{x:0>2}", .{byte}), k.ink); + } else 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); } } @@ -321,16 +357,10 @@ pub const Crossing = struct { } }; -/// 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. +/// What an argument is called: by the call's own names where the tracer's +/// table has them, else from its letter in `zt.syscalls.signature`. 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 => &.{}, - }; + const names = zt.syscalls.names(nr); if (arg < names.len) return names[arg]; return switch (kind) { 'i' => "number", @@ -421,12 +451,12 @@ pub const Timeline = struct { }; test "a crossing is as long as what the call does" { - // A call with no work: 4.0 s. Fifteen bytes copied up: 5.1. - try std.testing.expectApproxEqAbs(@as(f32, 4.00), Plan.of(.{ .nr = 3, .args = @splat(0), .enter = 0 }).total, 1e-3); + // A call with no work: 4.1 s. Fifteen bytes copied up: 5.2. + try std.testing.expectApproxEqAbs(@as(f32, 4.10), 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, 5.07), read.total, 1e-2); - // What came back is stored after it came back. - try std.testing.expect(read.stored > read.returns); + try std.testing.expectApproxEqAbs(@as(f32, 5.17), read.total, 1e-2); + // What came back is read in the kernel's rows, then struck in rax, then stored. + try std.testing.expect(read.struck >= read.returns + theme.time.strike.arm and read.stored > read.struck); // 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); diff --git a/anim/src/ties.zig b/anim/src/ties.zig index 3968d23..1f2532d 100644 --- a/anim/src/ties.zig +++ b/anim/src/ties.zig @@ -99,7 +99,8 @@ fn find(place: Place) ?[4]f32 { /// When register `i` strikes in this step: the registers one step wrote /// strike 6 f apart, in the registers' order; from the fourth on with the -/// third, within the CPU's slot of the cascade. +/// third, within the CPU's slot of the cascade; in a crossing, once the +/// call is back. Its pin and its link go with it. pub fn strikeDelay(now: cursors.Now, i: usize) f32 { var before: f32 = 0; for (theme.metric.all_registers[0..16]) |name| { @@ -107,7 +108,7 @@ pub fn strikeDelay(now: cursors.Now, i: usize) f32 { if (k == i) break; if (now.registerAge(k) == 0) before += 1; } - return @min(before * cursors.write_apart, time.cascade); + return @min(before * cursors.write_apart, time.cascade) + @import("syscalls.zig").crossingDelay(now); } /// How long a link draws: to a slot near by, or across to the lens. diff --git a/anim/test/sqlite.script b/anim/test/sqlite.script new file mode 100644 index 0000000..663caf5 --- /dev/null +++ b/anim/test/sqlite.script @@ -0,0 +1,10 @@ +# The sqlite scene, headless: it runs to three instants of its timeline without failing +# (the opening stop, the crossing, the page read). Built only where SQLite's source is. +frames 2 +console set playing false +console set t 5 +screenshot .zig-cache/canim/sqlite-early.png +console set t 44 +screenshot .zig-cache/canim/sqlite-mid.png +console set t 999 +screenshot .zig-cache/canim/sqlite-end.png diff --git a/anim/tools/chart.py b/anim/tools/chart.py index 78ba34d..168060a 100644 --- a/anim/tools/chart.py +++ b/anim/tools/chart.py @@ -42,6 +42,8 @@ motion.REGIONS.update({ "sort": {**subject, **words}, "syscalls": {**subject, **words}, "list": {**subject, **words}, + # The band's drawing is the backtrace, then the kernel's side. + "sqlite": {**subject, **words}, "zoom": {**none, **words}, "gallery": {**beside, **words}, }) diff --git a/anim/tools/sqlite.c b/anim/tools/sqlite.c new file mode 100644 index 0000000..5d018c6 --- /dev/null +++ b/anim/tools/sqlite.c @@ -0,0 +1,18 @@ +// Three rows into a table of a file database, in one transaction: SQLite's +// amalgamation (not ours: build.zig takes it from -Dsqlite) as a library. +#include "sqlite3.h" + +int main(void) { + sqlite3 *db; + if (sqlite3_open("t.db", &db) != SQLITE_OK) return 1; + int rc = sqlite3_exec(db, + "CREATE TABLE t(word TEXT);" + "BEGIN;" + "INSERT INTO t VALUES ('alpha');" + "INSERT INTO t VALUES ('beta');" + "INSERT INTO t VALUES ('gamma');" + "COMMIT;", + 0, 0, 0); + sqlite3_close(db); + return rc; +} |
