diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-11 23:46:02 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-12 01:40:04 -0300 |
| commit | 60e07feef401d9044db3a1c925cb9d1f6d20dac9 (patch) | |
| tree | 98957ba8425193f686c8e8692cd10a10f27dbf4b /anim | |
| parent | 9c0696447dbc5cf37e56aee562c7ebba4f4d4e6b (diff) | |
| download | computeranim-60e07feef401d9044db3a1c925cb9d1f6d20dac9.tar.gz computeranim-60e07feef401d9044db3a1c925cb9d1f6d20dac9.zip | |
canim: relations as one data-oriented subsystem; aim; the ASan pair; the introduction's chapters
From the user. Relations between panes are one subsystem: per-frame
tables of places and values in struct-of-arrays, owned by the frame;
the kinds one table of data; a resolver of pure passes (join, filter,
priority, cut) unit-tested on hand-written tables. Ported kinds draw
byte-identical frames; a synthetic map of 4000 places and 6000 values
resolves in 0.56 ms against the old table's 5.7. aim, a word holding a
code address tied to its row, is the first new kind, off unless a scene
turns it on.
The ASan pair: one overflow built plain and with ASan, recorded by
instruction; the frame as bytes eight a row; the plain run goes on alone
in the column, its return address aimed at main's row until the letters
reach it; the fault at ret. The introduction's three chapters are built
and tested, not yet exported. Annotations, rows and scrolls that changed
in one frame now fade; captions stand twelve seconds at most.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNCKgYCGiANnEwcEQxa
Diffstat (limited to 'anim')
41 files changed, 5148 insertions, 539 deletions
diff --git a/anim/README.md b/anim/README.md index 39a035f..bfc4f95 100644 --- a/anim/README.md +++ b/anim/README.md @@ -17,6 +17,7 @@ zig build test # unit tests, each scene run headless, zig build gallery # the gallery's pictures drawn anew into test/gallery zig build bench # what a recording costs a frame zig build bench -- NAME BY [FUNCTION] # a recording's steps (BY: moment, line, over), with what each changed +zig build bench -- relations # the relations' passes timed on a working frame's tables and a map's (CANIM_RELATIONS=1 on a scene: each frame's counts) python3 tools/chart.py chart out/fib-1080.mp4 --out out/motion/fib # the designer's timing chart and checks (POP, CROWD, METRONOME, CAPTION, AIR) CANIM_MAP=1 zig build export -Dscene=fib -- DIR --size 3840x2160 # every frame the scene's map filling it, as `list` opens on it: a map at 1:1 ``` @@ -113,10 +114,17 @@ before a walk and put it back after: ```zig at.levels = .{ .idea = .calls, .source_rows = 8, .annotation = .whole }; // before canim.context at.levels.carry = .arrow; at.walk(s, .moment, to); at.levels.carry = .off; // the value's way, for one beat +at.aim(s, .standing); /* ... */ at.aim(s, .off); // a word holding a code address tied to its row, for some beats ``` -**The text column, an experiment** (`src/column.zig`, design/README.md -"column (an experiment)"). A scene can tell its beats with the panes a beat +`aim` is off by default everywhere (design/README.md, "4. Ties": the +author's to turn on, never the budget's): `.standing` draws, for the words +on screen in memory that hold the address of an instruction whose row is +shown, one tie to that row, in and out with the knob (18 f, over what +follows); `.step` the one of the word a walked step writes or reads. + +**The text column** (`src/column.zig`, design/README.md "column"). A +scene can tell its beats with the panes a beat is about in the left column and its text beside them, level with the row it speaks of, every other pane folded to its tag on the shelf (y 48), a register struck on its tag as on its row. It is the author's instrument: @@ -129,12 +137,20 @@ row the beat's first step is on; `.{ .row = addr }`, `.{ .head = "open" }`, 744 }`) and where its stem points (`.level`, `.none`, `.{ .to = … }`), and the folded panes' notes (the registers', the source's and the disassembly's are computed where the beat gives none). Between beats, in a rest, the last -text dims, the panes that leave fade and fold to the shelf, those that stay -glide (a pane that changes its rows fades out and in round its glide), those -that come unfold and fade in; an older text in the way glides up (or down -where there is no room above), the new one arrives with its stem, and the -stem draws back as the step fires. Three texts stand at most; at a run only -the newest. `scenes/column.zig` is the trial (`open` followed down), +text dims; the panes that leave fade (6 f) and fold where they stand, closing +to their tags, which then travel to the shelf (18 f: only a tag crosses +another pane, never a panel); those that stay glide (24 f; a pane crossing to +the other column 24 f down its own, 24 f across), one that changes its height +keeping its rows (a descent's rows glide between its two heights' layouts, +the rest fading at the moving edge; a source's window glides); those that +come unfold (18 f) and fade in (6 f); an older text in the way glides up (or +down where there is no room above), the new one arrives with its stem, and +the stem draws back as the step fires. A bubble about a folded pane (its +level a row of a folded disassembly, a block of a folded drawing) points at +the pane's tag on the shelf. A bubble still being read more than 84 f after +its beat's steps is said once on stderr (`column: bubble N is still read +…`), unless the beat says its rest is meant (`.held = true`). Three texts +stand at most; at a run only the newest. `scenes/column.zig` is the trial (`open` followed down), `scenes/column_sort.zig` the wide placements on sort's rings: ```zig @@ -164,8 +180,12 @@ canim.descent.step(cur, s, .moment); | `zoom` | one line of C as its instructions, the call's bytes | `none`, the camera at x1.16 on the instructions and the stack in one view, cause and effect (the stack's window set before the move and held); the map's drawing the calls of `fib` (`Map.drawing`) | `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`, `backtrace` (`Context.Options.backtrace`), then `syscalls`; its view a `hexdump.Dump`; as the caption names them, rdi's `BtCursor` opened in a loupe, then rsi linked to its row in the view (`Context.tiesWith`); the page's fields named a group at a time, 2 s apart; the backtrace lens drawn on its map | `sqlite` | | `gallery` | every block in its states, a page or a state each 3 s; at 21 s the `blocks` lens (sort's rings at rest, `leave` mid-way, a `turn` landing with its ring's count struck; libc's `open` in `layers` at its `syscall`, what it has not reached folded), at 24 s the moves of a first time (sort's first swap `reach`ed, its pill filling; `open` stepped past its `syscall`, its fold mid-`unfold`; sort in `layers` panned to the pc; the fold open, at rest). Its context pages fold the registers its one step does not change | all three, `blocks` | `gallery`, and for the graph pages `test/gallery/sort.ztrace` and `hello.ztrace` (the second page's picture keeps the old name `graph-map.png`) | -| `column` | the trial of the text column (design/motion.md, "A scene in the column"): `syscalls`' story on the same recording and steps, beat by beat as the storyboard's table C1 to C12 has it: the opening `below` (the working frame whole, its caption); the arguments beside the source and the disassembly over the registers; the call and the stub's jmp beside the descent over a stack of twenty words (the touch from the call row down the gutter to the free word, rsp's pin climbing); the wrapper at a run, the text level with open's head; its last three beside the registers; the crossing beside a descent of twenty-four rows, the text level with the kernel's floor; back up, the text at main's call row; `read`, `close`, `write` stepped over, the bytes over the source, each text beside its call row; the close `below`. Every other pane on the shelf, the registers' strikes on their tag | the column (`column.zig`), the working frame `beside` at the opening and the close | `hello` | +| `column` | the text column (design/motion.md, "A scene in the column"): `syscalls`' story on the same recording and steps, beat by beat as the storyboard's table C1 to C12 has it, its texts as it cuts them (C4's 57 characters): the opening `below` (the working frame whole, its caption); the arguments beside the source and the disassembly over the registers; the call and the stub's jmp beside the descent over a stack of twenty words (the touch from the call row down the gutter to the free word, rsp's pin climbing); the wrapper at a run over a source of two lines, the text level with open's head; its last three beside the registers; the crossing beside a descent of twenty-four rows, the text level with the kernel's floor; back up, the text at main's call row; `read`, `close`, `write` stepped over, the bytes over the source, each text beside its call row; the close `below`. Every other pane on the shelf, the registers' strikes on their tag | the column (`column.zig`), the working frame `beside` at the opening and the close | `hello` | | `column_sort` | the column's wide placements on sort's first trip: the opening `below`, then the rings across both columns twice their size, the others on the shelf (`sort.c line 12`, `disassembly jne …`), a text `on` the drawing in the corner the rings leave free with its stem round the drawing's top to the pc's block; then a text `above` it; then the working frame again | `blocks`, then the drawing across both columns (`Stage.zoom`) | `sort` | +| `intro_memory` | the introduction's first chapter (design/motion.md, "A scene: the introduction", I1 to I10): the 128 bytes at the top of the stack under the camera at x2; `regroup`, sixteen a row to eight (the return address walked, the rest at a run); three words that hold addresses framed; into the column, the dump folded to a tag; the address space to scale (`segments`: a slim bar, then `enlarge` a cluster at a time, the stack, the libraries, the tracer's 64 MiB ring in a box of its own, the program by segment, start, end and size on every band), texts beside; back to the working frame: the dump's `tie` and `link` onto the stack's box, a visit at x4, `ink`, three chains | the working frame (`below`), the column for I4 to I6 | `list`, moment 77 (reverse's first `call`) | +| `intro_stack` | chapter II, from I's last picture: the words become the stack panel; the call's push walked as the tied stack walks it; `main+50` framed and the offsets counted; rbp's pin and the panel's tag; the registers built row by row; texts beside on the left, in the program column | the working frame without a backtrace, texts on the left | `list`, 77 to 78 | +| `intro_code` | chapter III: the code's bytes as a dump row in code's ink, an instruction's four framed; `decode` into `aligned` (`interleaved`, mock 33), the neighbours at a run; `align` to `columns` (mock 36); the working frame with the list's nodes, the camera at x1.5 and back; `surface` to the map | `aligned`, texts above; then `subject`, `nodes`; the map | `list`, moment 582 (the load on line 21) | +| `asan` | plain against AddressSanitizer on `overflow.c` (design/motion.md, "A scene: ASan against a plain build", A1 to A16): a `pair` (A1 to A9, A14 to A16: the shared source, each run's disassembly, registers and frame as bytes eight a row with ASan's shadow byte beside each row, `only here` and `differs` bars, the parting framed `attention`, ASan's stderr in place of its registers once stopped) and the column for A10 to A13 (ASan folded to one shelf tag, its report's first line on it; plain's disassembly a descent, main's window over fill's whole; plain's frame the column's rest; each text level with the field the letter lands in; `aim = .standing`: the return address aims at main's row after the call, glides to `fill+1` at i = 24 and frays at i = 25); i = 27 held 4.9 s (mock 38, the poster); the fault at `ret` (SIGSEGV, rip stays) | `pair.split`, then the column | `overflow`, `overflow_asan`, `overflow_report` | ## The blocks @@ -179,8 +199,8 @@ every state the code has in the `gallery` scene. | | `byte` | `src/rows.zig` `bytes` | `number`, `pointer`, `text` (a string's ink), `loose` (a byte of no field: the allocator's, padding, past what a dump is of), `unread`; `pad`; `bytesAt` moves the bytes right of a long (stack) address, by the dump's widest; a write's arm, strike and held corner cover the bytes whose value changed, first to last (`Run.changed`, `Now.changedBytes`), struck a byte a frame from the low address (what a read fills, 2 f apart); until its strike lands (s+3) a run keeps its old bytes and their reading, through the arm, read by its old field where the step retypes it (`hexdump.keepOld`, `Fields.was`) | | 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`; a register's reads memory as the panels show it, the step's bytes from their strike (s+3): its later hops fade out from the strike and are followed again 4 f after the bytes land (`Now.following`, `Marks.hops`). `slot`: pins from 16, the offset ranged right to 172 (under `tied` from the frame's base, the call frame information's CFA register: `context.frameBase`; under `whole` from rsp; a `free` word's crossfading), the address at 184, the chain, its role ranged right where the room ends (48 sooner in a pane: its strip), from `zt.telescope.slots` (`saved rbx`, a local's name in primary, `n, high half` for a narrower local in the word's top four bytes, `argc`, `argv[0]`, `argv end`, `envp end`, `auxv`; `i, n` where locals share a word (`Slot.also`); the stack protector's copy `canary`; nothing for a return address or `.none`). `bytes`: the bracket at 24, the address at 34, the bytes 12 after it and at 132 at least | | | `arc` | `src/rows.zig` (`Arcs`), `src/hexdump.zig` (`pointerArcs`) | a pointer to a row of its own panel: lanes at 4, 10, 16 in a dump or a loupe, 4 and 10 on the stack; longest outermost, a chain in one lane; standing at 60% toward the page, full in the step that writes or reads it and always in a loupe; rewritten: the old dashed with the arm, fading from 6 f after the strike as the new draws (12 f), quieting with the cool; a lane change glides while the arc that causes it draws or fades (`Arcs.assign`, with and without the arcs on their way); a stub to the rule for a target in the region past the window, only in its step; a saved rbp's only in its step, going with its advance (18 f); a dump withholds the arcs an open loupe carries | -| | `insn` | `src/disasm.zig` | columns at 2, 31, 40, 134, 180, 264, 564 (540 in a pane, whose strip takes 48 of the row; `map.content`); size words dropped from every operand, a `width` of byte cells (`metric.width`) after the `]` where no register outside the brackets has the access's size and the mnemonic does not fix it; `nop` and `endbr64` faint; a PLT target named (`401070 open@plt`); the annotation from 564 or a character after the operands, then the operands give way, never inside `[]`; `current`, `ran` (every instruction of the last three steps), `ahead`, `outside`, `waiting`, `pass`; the jump lane from the jump just before the pc's moment. The row's detail, every value the recording's at that moment: a compare's two values and the flags it leaves as chips (those the conditional after it reads; CF ZF SF OF when none); a conditional's `taken`/`not taken · reads` and its flags, `→ target` when it leaves the window, and while it runs the setting row's chips and rip's framed as read (an echo); `lea`'s `= value`; a call through memory or a register `→ target name · read from open@got, 403fd8` (out of room the slot goes, then the digits); a call through a PLT stub by the function it reaches (`the resolver` while its slot is lazy); `fs:[0x28]` as the stack's canary (`canary` where the row has no room); a `rep`'s count and step; `syscall` with its name and number, its arguments under it by register, typed (`-100 AT_FDCWD`, `O_RDONLY`), the rows they hang over giving up their own annotation; a call that has run in C's form with its result (`read(3, …) = 15`: out of room the arguments go from the right, the result stays); a memory access narrower than a word read at its width (`rows.narrow`: `7fffffffecc4 ◂ 15`). The annotation's form is the scene's knob (`Levels.annotation`, above): under `tied` a word the stack shows by its role and one hop (`tiedWord`; a local's name, the one of a shared word that holds the bytes accessed; an unnamed word, a spill, by its address and one hop; a store's value cut with `…`, never dropped), a heap word with a view on screen by its address and one hop, a word no pane shows its whole chain with its data name in place of the address (`head → 407050 ← 9`); a register set its first value; a move of rsp or rbp first (`stackMove`: `rsp -8 · saved rbp`, the role from the push's own stop, `rsp -0x20 4 words`, `rbp = rsp`, `leave`'s, `fib(4) · rsp -8`, `→ 4011ad main+45 · rsp +8`), the amount struck as rsp's pin lands; the row publishes where the touch leaves it (`ties.touch_row`); under `whole` the row as before | -| | `descent` | `src/descent.zig` (`Descent`, `step`) | the disassembly a call deep: the root's window on top (main), each callee's under the row that called it (that row `waiting`, ringed, its annotation the call in C's form), a PLT stub gone through kept as its `jmp`, `pass`; a head row over each window (the name at 40, Go Medium 18; what it is ranged right: `libc.so.6 · open64.c` (the file of its function's entry, where the build has the source), `libc.so.6 · no source`, `the PLT · its jmp reads open@got, 403fd8`, `the PLT, jumped through`); the call lane at x 14; the nearest caller takes the rows the deepest does not use, all above its call row (one row after it, the return row, the callee's head directly under that), and where its function starts first the rest go back to the deepest window; three code windows at most, the rest one `more` row; each window's addresses its own width; the tag the deepest function and its module (`open · libc.so.6`); at a `syscall` (and the stop after it) the floor's three rows are the kernel's: in a crossing the lane down from the plaque (3, vellum), the window filling down, `the kernel` and `openat, system call 257`, the call in C's form, `returns` struck, `rcx, r11: clobbered`, the answer climbing the lane (24 f, `glide`), the window drawing back at the advance. A crossing stepped over opens the same window under the call row, past the arguments hanging under it, the rows after them making room (18 f) and closing up with the window. Every row keyed (an address, a head), so a step is the rows both stops have gliding and the rest leaving or arriving on its verb's timetable, in two moves, never at once: `descend` (2.9 s: the given-up rows fade 66–78, the kept ones glide 78–96, ring 84–96, lane 96–114, head 108–120, rows 114–138), on through a stub's `jmp` (2.2 s), `ascend` (2.5 s: the window closes 48–72, lane back 72–84, the kept rows glide 84–102, the given-up ones fade in 102–114), `cross` (`syscalls.step`); a row whose state the verb changes (the call row to `waiting` with its hanging arguments, a jmp to `pass`, a waiting call taking its result) crossfades; with it the source's line `waiting` where the pc is in code without source (ringed, the tag `main waits at line 6 · the pc is in libc's open`, crossfading over the 12 f before the advance, as a stack span's name does) and the thread waiting (primary, 2); where the build has the library's source the panel goes on with the pc into it. Its strip is the deepest window's function's linear column (a `Disasm` drawn for the strip alone, `Map.In.strips`), that window framed on it; going down or up it fades through as the mark lands (`map.through`) | +| | `insn` | `src/disasm.zig` | columns at 2, 31, 40, 134, 180, 264, 564 (540 in a pane, whose strip takes 48 of the row; `map.content`); size words dropped from every operand, a `width` of byte cells (`metric.width`) after the `]` where no register outside the brackets has the access's size and the mnemonic does not fix it; `nop` and `endbr64` faint; a PLT target named (`401070 open@plt`); the annotation from 564 or a character after the operands, then the operands give way, never inside `[]`; `current`, `ran` (every instruction of the last three steps), `ahead`, `outside`, `waiting`, `pass`; the jump lane from the jump just before the pc's moment. The row's detail, every value the recording's at that moment: a compare's two values and the flags it leaves as chips (those the conditional after it reads; CF ZF SF OF when none); a conditional's `taken`/`not taken · reads` and its flags, `→ target` when it leaves the window, and while it runs the setting row's chips and rip's framed as read (an echo); `lea`'s `= value`; a call through memory or a register `→ target name · read from open@got, 403fd8` (out of room the slot goes, then the digits); a call through a PLT stub by the function it reaches (`the resolver` while its slot is lazy); `fs:[0x28]` as the stack's canary (`canary` where the row has no room); a `rep`'s count and step; `syscall` with its name and number, its arguments under it by register, typed (`-100 AT_FDCWD`, `O_RDONLY`), the rows they hang over giving up their own annotation; a call that has run in C's form with its result (`read(3, …) = 15`: out of room the arguments go from the right, the result stays); a memory access narrower than a word read at its width (`rows.narrow`: `7fffffffecc4 ◂ 15`). The annotation's form is the scene's knob (`Levels.annotation`, above): under `tied` a word the stack shows by its role and one hop (`tiedWord`; a local's name, the one of a shared word that holds the bytes accessed; an unnamed word, a spill, by its address and one hop; a store's value cut with `…`, never dropped), a heap word with a view on screen by its address and one hop, a word no pane shows its whole chain with its data name in place of the address (`head → 407050 ← 9`); a register set its first value; a move of rsp or rbp first (`stackMove`: `rsp -8 · saved rbp`, the role from the push's own stop, `rsp -0x20 4 words`, `rbp = rsp`, `leave`'s, `fib(4) · rsp -8`, `→ 4011ad main+45 · rsp +8`), the amount struck as rsp's pin lands; the row publishes where the touch leaves it (`ties.touch_row`); under `whole` the row as before. What the step leaves on its own row (`lea`'s `=`, a register's first value, a compare's flags, the canary's word, `rbp = rsp`'s value) fades in from its strike (12 f; at a run the run's ease); a row the advance changes (its state, its trail, its line number) is drawn as before and as after the advance and crossfades over its middle | +| | `descent` | `src/descent.zig` (`Descent`, `step`) | the disassembly a call deep: the root's window on top (main), each callee's under the row that called it (that row `waiting`, ringed, its annotation the call in C's form), a PLT stub gone through kept as its `jmp`, `pass`; a head row over each window (the name at 40, Go Medium 18; what it is ranged right: `libc.so.6 · open64.c` (the file of its function's entry, where the build has the source), `libc.so.6 · no source`, `the PLT · its jmp reads open@got, 403fd8`, `the PLT, jumped through`); the call lane at x 14; the nearest caller takes the rows the deepest does not use, all above its call row (one row after it, the return row, the callee's head directly under that), and where its function starts first the rest go back to the deepest window; three code windows at most, the rest one `more` row; each window's addresses its own width; the tag the deepest function and its module (`open · libc.so.6`); at a `syscall` (and the stop after it) the floor's three rows are the kernel's: in a crossing the lane down from the plaque (3, vellum), the window filling down, `the kernel` and `openat, system call 257`, the call in C's form, `returns` struck, `rcx, r11: clobbered`, the answer climbing the lane (24 f, `glide`), the window drawing back at the advance. A crossing stepped over opens the same window under the call row, past the arguments hanging under it, the rows after them making room (18 f) and closing up with the window. Every row keyed (an address, a head), so a step is the rows both stops have gliding (and a change of the panel's height at rest the rows both heights' layouts have, `Stage.resizing`; a row's shared digits are of its own window's rows that show) and the rest leaving or arriving on its verb's timetable, in two moves, never at once: `descend` (2.9 s: the given-up rows fade 66–78, the kept ones glide 78–96, ring 84–96, lane 96–114, head 108–120, rows 114–138), on through a stub's `jmp` (2.2 s), `ascend` (2.5 s: the window closes 48–72, lane back 72–84, the kept rows glide 84–102, the given-up ones fade in 102–114), `cross` (`syscalls.step`); a row whose state the verb changes (the call row to `waiting` with its hanging arguments, a jmp to `pass`, a waiting call taking its result) crossfades; with it the source's line `waiting` where the pc is in code without source (ringed, the tag `main waits at line 6 · the pc is in libc's open`, crossfading over the 12 f before the advance, as a stack span's name does) and the thread waiting (primary, 2); where the build has the library's source the panel goes on with the pc into it. Its strip is the deepest window's function's linear column (a `Disasm` drawn for the strip alone, `Map.In.strips`), that window framed on it; going down or up it fades through as the mark lands (`map.through`) | | 3 panel | `registers`, `stack`, `backtrace` | `src/context.zig` | the registers `quiet` (`Registers.moves`, `movedBy`, `registerRows`): the scene's set chosen once, from its clock's way (`Cursor.journey`: the registers any of its steps of that kind changes, net, with rsp, rbp and rip), each a row with its chain; the rest folded three to a row on a pitch of 285 under a 2-unit rule, in pwndbg's order (`rows.quiet`: the name faint at 12, the value at 60, a pointer cut to `more` at once, a code address alone; framed as read while it carries a system call), rip last; the panel as tall as its rows and the stack the rest (`layout.fit`); in a `dive` it arrives whole from the map and folds as it lands (`Zoom.fold`: each quiet row gliding into its cell, the chain past its first hop gone over the first 40% of the move, a rule fading in); rip's value crossfading over the advance, a flag set or cleared over the 6 f it lands in (`rows.RipWas`); the backtrace newest at the bottom, `#0` last, the oldest dropped from the top (`newest at the bottom · 2 more above`), as a panel, the calls lens's view, the backtrace lens and on the map, all one block (`backtraceRows`: frames leave, slide and arrive; what a kept row says that changes, its depth, its pc's offset, its line, and the tag's count, crossfades, 12 f before the advance); the stack's window on `[rsp, rbp+16)` keeping the touched word in view, its tag the first and last word shown (`rsp+20 to rsp+48`), a word's role and offset, and the tag, crossfading (12 f from memory's strike) where the step changes them, rsp and rbp's pins travelling 18 f after rsp's strike (`time.pin`, keeping their place among the names they leave and join), at rest only where the register points; a window that moves farther than its own height (six or eight slots) fades out and in round memory's strike (12 f each; at a run half its step each), and what it brings, and what changed before it, is plain; while rows slide they keep their roles (those of both windows are read), and a word becoming a saved rbp, or no longer one, has its arc go or come with its role; 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; the backtrace as a lens's drawing with `Context.Options.backtrace`. Under `tied` the window has two `free` words of headroom over rsp (a leaf's locals under rsp are the frame's), the tag says the base (`· offsets from rbp`, crossfading as it changes), and when rsp or rbp moves the rows hold while the pin travels (`Plan.pins`: the amount on it, `rsp -18`, counting row by row, a vermilion bracket over the rows crossed, each row gained or released as it passes, the newest frame's span riding it, the register struck as it lands; rbp's pin flies to rsp's, `pop rbp` moves rbp first), and only then the window follows (`Plan.follow`); under `whole` as before | | | `source` | `src/source.zig` | fourteen lines alone, eight with a lens, six with `blocks`; the file the pc is on a line of, of the recording's sources (`Recording.sources`, `shown`: the program's own, or a library's the build gave; else the last such line, a frame up, where the pc waits), whole in a window, its middle third; its lines cut at 63 characters in a pane (67 on the map); the trail's bars (of that file's lines) crossfading with the advance; numbers as wide as the widest file's largest line (SQLite's six digits), the text moved right by as much; another file: the panel fades through (12 f out, 12 f in), its tag's title and note crossfading with it, its strip with it (`map.through`); a window going farther than its own height in one file: the advance is 48 f, the window gliding on the strip for the first 24 (the gold lit on its new row there), then the pane out and in | | | `disasm` | `src/disasm.zig` | under the source in every split: 17 rows (11 as subject and with `blocks`), fewer above near a function's start; on the map 69 from the function's start where the pc is in its first three quarters (a strip's column stays still while the pc walks it), else round the pc; the line column as wide as the source's, a row's number where its line is of the file the source panel shows (libc's rows open64.c's while it shows open64.c, main's none then); two windows that overlap scroll, others fade out and in; its tag's function (a descent's tag too) crossfading with the advance; a 2-unit `rule` across over each block's first row (not its function's), and the block's visits by the moment shown ranged right, faint (`×3`), where the row's annotation leaves room, crossfading with the advance (`graph.Rules`, a descent's windows too); the rows clipped above the panel's padding (a row scrolling out takes its rule with it) | @@ -189,10 +209,15 @@ every state the code has in the `gallery` scene. | | `hexdump` | `src/hexdump.zig` | malloc's words: a field read as `size` (`0x20 a m P`, the bits as rip's flags) or `protected` (`→ 405050 ^ 405`, `NULL ^ 405`, its arc to the pointer it protects), and a field's `note` (Go 18 faint: `key`, `top`, `slots left`); a lens's view (`hexdump.panel`): `bytes` rows and their reading, veiled at a sprint; a row whose bytes the step changed where the recording saw no write (memory nothing watches, read anew at a stop), or that became known, crossfading over 12 f (`rowPasses`); one reading for every dump (`hexdump.reading`), a list a character apart, a typed number as its type reads (`char` quoted, `bool` by name); the address room once a dump, by its widest; `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 each stretch left out, and where those rows outnumber the window, a window kept round the first row a mark or the step is on, the rest folded into `more` rows; marks the scene plays, and the step's only from the stop it came in at (`since`); the bytes a syscall was given as the kernel took them (`given`), and only what the debugger read at the stop (`seen`) | | | `loupe` | `src/loupe.zig` (`canim.loupe`, `Loupe.open`, `.close`) | from a register, a loupe's field, or a dump's row read by the scene's fields (`.row`: malloc's tcache, `num_slots[0]` and `entries[0]`, the rest `more`); five rows round a pointer's target, lifted (`color.lift`, `lift_tag`, `shade` 12 and 16; 20 and 26 deeper), hanging from its pointer (its tag on the row's foot, 92 left of the digits, clamped to the stage), a 4-high bracket under the digits its stem, the target's fields framed bright; one opened from the band's view lies over the stack, never the registers, its stem down the gutter's right lane (x 962), its fields struck once it has opened (6 f after, 6 f apart: `Fields.struck`); a deeper one with no room to the right hangs under the one it opens from, its stem down to its tag; a note that does not fit is cut at a word with `…`; `open` 36 f (read 6, stem and rise 18 with the shadow, the frame 6 f after), `close` 12 f; it opens again after a close | | | lenses: `nodes`, `array`, `calls`, `syscalls`, `backtrace` | `src/nodes.zig`, `src/array.zig`, `src/calls.zig` (`Tree`), `src/syscalls.zig` (`Crossing`), `src/context.zig` (`Backtrace`, `lens`) | 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 calls so far as strace writes them (oldest on top, the newest coming in once it is back, held; the rows make room for it, a full log scrolling a row, 24 f, `glide`, but from rest at least a pixel a frame (the rows are drawn on whole pixels), the count above crossfading; out of room a row gives up its faint names first, then its arguments from the right, and keeps what it returned; a path by its string, the kernel's capture where the stop did not read it) over the bytes the call crossing in the step is given or fills (in with the argument framing, 12 f out and 12 f in; what a read fills landing a byte every 2 f, struck, the stack's words with them; a write's buffer framed as read while the kernel takes it; cleared with the log's new row: between crossings `no call crossing now`), `backtrace` (eleven rows as subject, five beside) a `Dump` the scene gives; an `under` pin's names in the order they came, the first left, faded out through the middle of a register's joining or leaving (`Pins.text`); a call node's look (gold, ringed, done) crossfading as the tree's moment changes (6 f), and at a sprint a new node coming in over its step; a left child's result on its left shoulder, off its parent; a view's row a register points into carries the register's `pin` at the row's end (`hexdump` `rowPin`; 48 to the left in a pane, its strip at the right), the reading ending before it; at a sprint the array's pins hold and move where a phrase ends | -| 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; to a view's row (`dump_pin`) by the left lane, into the row's edge; on a beat the narration names (`Context.tiesWith`, `ties.Beat`): the register framed as read, then its link, held, drawn back with the frame; a projection from the view's bytes, or from a frame's return address to its call's node. Under `tied`, `touch` (`Plan.touch`): from the row's right rule along the gutter's middle lane (x 956) to the word, onto the stack's rule nearer the lane (its right one where the stack stands under the disassembly, a column's beat), in read's or write's colour, the first of the three lines to give way; `carry` (`Levels.carry`, `Plan.carry`): the value's way between a stack word and a register along x 962, primary, an open chevron, `.value` its digits on a raised chip. Places a column's text is level with: `row` (a disassembly's row by its address, a descent's head by `descent.headKey`), `floor`, `block` | +| 4 tie | the relations: `thread`, `link` (and its `pin`), `projection`, `touch`, `carry`, `aim`, `echo` | `src/relations.zig` (the tables and the pure passes), `src/ties.zig` (`Ties`, the resolver; `anchor`, `show`, `find`, `of`) | the relations are one data problem (design/README.md, "4. Ties"): each frame's tables are in the frame's own scratch (`sk.Frame.user`, made at its first place: no process globals, two players at once each have theirs): `places` (a key, the place's kind in its top byte and its address below, its box, its pane; struct of arrays) that panels say as they draw (`anchor`), `values` (what a pane shows that may be an address: the value, its box, its pane, the word holding it, a register's index, its panel's rules: `show`, from the registers, the stack's words, a pair's frame), and the facts the panels publish beside them (the stack's window, the touch's row, the thread waiting); both sorted once by key (or value) after a change, a lookup a binary search (`find`), a join a merge of the two sorted sides (`relations.join`). `Ties`, added last, is the resolver, six passes, each a loop over one table: candidates (each kind's join, or the step's events against the places), the knobs (`relations.filter`: a kind whose default is off, `carry` and `aim`, only where the scene turned it on; the budget never turns one on), priority (`byPriority`), the budget (`cut`: the thread; one beat; a link, a projection and a touch, two of them, the touch giving way first; a carry; one aim), then each kind's route and drawing. The kinds are one table of data (`relations.specs`: knob, class, priority, most). Map panels say their places into the map's own tables. `CANIM_RELATIONS=1` says each frame's counts and times on stderr; `zig build bench -- relations` times the passes on a working frame's tables and a map's. The kinds' pictures and timings are as they were: fib, list, zoom, sqlite and column render identical frames before and after (every frame compared). `aim` (`Cursor.aim(s, .standing | .step | .off)`, off by default): a word in memory holding a code address whose row is on screen, out of its panel's rule nearer the gutter, up the left lane (x 950), onto the disassembly's right rule, the row's address framed in code's ink; standing at 60% toward the page, in and out with the knob over 18 f; the step's full ink after the word's strike, back with the advance; written again, its head glides to the new row 24 f after the strike, or it frays (dashed over 12 f, gone over 18 more) where the new value is no code. 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; to a view's row (`dump_pin`) by the left lane, into the row's edge; on a beat the narration names (`Context.tiesWith`, `ties.Beat`): the register framed as read, then its link, held, drawn back with the frame; a projection from the view's bytes, or from a frame's return address to its call's node. Under `tied`, `touch` (`Plan.touch`): from the row's right rule along the gutter's middle lane (x 956) to the word, onto the stack's rule nearer the lane (its right one where the stack stands under the disassembly, a column's beat), in read's or write's colour, the first of the three lines to give way; `carry` (`Levels.carry`, `Plan.carry`): the value's way between a stack word and a register along x 962, primary, an open chevron, `.value` its digits on a raised chip. Places a column's text is level with: `row` (a disassembly's row by its address, a descent's head by `descent.headKey`), `floor`, `block` | | 5 frame | `map`, `minimap`, `dive`, `surface` | `src/map.zig` (`Map`, `split`, `strip`, `Map.strips`), `Context.map` | the working frame's panels bound to a stage of 3840 by 2160 (`map.split`, packed by content: each box as long as the most rows its panel has wanted, `measure`, the backtrace's as long as the deepest call chain of the scene's way, so that it is packed once; the drawing, the source and under it the backtrace; the disassembly; the view (none where nothing draws one), the registers, and in the column's rest the stack going on, `stack, continued`; the stack from 16 words above rsp; and the first two columns' rest (`Split.spare`) given, in the catalogue's order, to `map.Spare`: a five-row dump round each place the registers (pwndbg's order, not rsp or rbp) and the 64 words up from rsp point at outside the stack and the code, none within another's rows, then the loupes open (`Map.loupes`, lifted, nine rows), then the key (the recording and the moment, the marks as drawn, the inks); only then page); its rows published while `ui.mapping` (the dumps' too); the working windows outlined (2 `dim`, 4 out), each window published with where its step took it from and how far its scroll has gone, so its outline glides; the thread across the gutter (x 1008), gold; a scene without a band can put a drawing on its map (`Map.drawing`); with `Context.Options.graph` the map's drawing is the `blocks` lens's (`graph.Blocks` at its size, 880 by 344, over the source: `split`'s band is the working frame's), the disassembly linear beside it with its blocks ruled. Each pane's minimap (`map.strip`): a strip 40 wide inside its frame at its right, under the tag, on `well` (`theme.strip`), drawn from its column of the map (the source's boxes, the stack's with `stack, continued`, the view's dump; the disassembly's the linear rows round the pc, drawn for the strips alone where the map has a graph or a descent: `Map.In.strips`) at 4 units a row and 36 of 880 across, from what the map drawn for it collects (`ui.strokes`, `ui.collected`: each run of text a stroke 3 high in its ink 65% from the page, the marks 4 by 4 at a row's left in the catalogue's order, an arc with an end off the window a 2-unit line down the left edge, a block's first row ticked); a column longer than the strip the rows round its window, the window in the middle, clamped to the ends, three faint dots where it goes on (fading in over its first row's scroll); the window framed 2 in primary; a mark no working window shows (a word struck or read on the stack or in the view's dump) flashing on its row (a ring 8 to 14 in the mark's colour, 12 f). The strips are one image a frame (`Map.strips`): the map drawn for them six times, each from the cursor's mirror a frame later (6 to 11 f behind: `Cursor.lagInto`) with the panes' windows as long ago (`past`), every strip drawn as it shows (its rows, dots and window in place) and the six averaged, so that every change on a strip fades in over 6 f from 6 f after its onset and nothing on it moves a pixel in a frame; the panes blit their part (source, disassembly and its descent and the `blocks` lens's view, stack, a dump's view: not the registers, a drawing, a loupe, the backtrace, the `syscalls` lens's log). A pane with a strip has 48 less for its rows (`map.content`). `Map.show`, `.dive` (outlines bright 6 f, veil to 24, each panel from its window to its place 60 f, 6 f apart, a panel drawn over another setting off first (drawing, view, disassembly, stack, source, registers) so that none in its place is crossed by one on its way, opaque on the way, its rows on the window's rows, its tag and rules in from 84 f; with each, the rest of its column (the rows its strip shows) squeezing from its place on the map into the strip, its width and height each on its logarithm (to 36 of 880, 4 of 24 a row), its window's outline riding on it, gone into the strip's own drawing over the 12 f before its pane lands (`Map.squeeze`, `stripShows`); the map's other parts fading where they are, 24 to 72; 120 f and 30 f still), `.surface` (the dive back, 84 f, then 30 f still); per-panel transforms through `context.at` (`context.zoomed`); the clock's count ranged right at 1856. `unroll` and `roll` (`Map.unroll`, `.roll`, `map.Unroll`, added over everything by `Context.ties`): the panes veiled and the strip's window framed bright (18 f), the pane's whole column growing out of its strip (36 f, `glide`) to as many rows as the stage holds (24 a row at most; right on the strip's edge, the window's rows level with the pane's where the stage allows), its scale on the logarithm from the strip's, the window's outline riding from the strip to the pane's rows in it; held as the scene says; `roll` the reverse (36 f), the veil lifting (18 f). A far jump in the same column at a walk (the source's window farther than its height to lines the map's column of the file holds too, `source.unrolling`, `inColumn`: no step said faster in a hurry) is `unroll`, the window travelling along the column (24 f, `glide`, the mark lighting gold at its new line as the window gets there, the tag's note changing then), `roll` (96 f: `Cursor.travel`), the pane going into the column and coming out of it at its new place, never a fade. Out of the column (another function, a long file) the map's column goes over as the advance starts, so the strip (6 to 11 f behind, a 6 f crossfade) shows where the pane goes before the pane fades through (`over`, `far` on the map at half its height); a window going farther than the column holds keeps its place on the strip until the column goes over (`spanOf2`); the tag's line range changes with the pane's fade; the map's disassembly is measured by the moment the pane shows (a continue repacks the map as the pane gets there), and a recording of breakpoints has its deepest chain read at every stop (`deepest`: the backtrace's box packed once) | | | `stage` and `relayout` | `src/stage.zig` | splits `none`, `beside`, `subject`, `blocks` (`theme.layout.split`, layout A: the disassembly under the source in every split; the source 14, 8, 8 and 6 lines, the disassembly 17, 17, 11 and 11 rows; `blocks` a drawing of 880 by 344 over the program column and no view, the state column the registers' and the stack's from the top), each for a registers panel of eleven rows; `layout.fit` gives the scene's registers their rows and the stack the rest above the backtrace, whole slots, any rest above it (`Stage.registers_rows`: every split a `relayout` goes to keeps them); 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; `glide` (a column's moves: no fit, no fade), `column` (the clock under the text column), `zoom` (the band's drawing drawn larger, its tag not: `graph.Blocks`) | -| | `column` (an experiment) | `src/column.zig` (`Column`, `canim.column`, `beat`) | the shelf (y 48: each folded pane's tag in the frame's order, its note: the scene's, or computed for the registers (those the step changed, the first's value struck as on its row, crossfading with the strike), the source (`line 12`) and the disassembly (`jne 4011af`), crossfading with the advance); the panes from 84 to 1032, 12 apart; texts: `beside` (Go 40 on 54, at most 40 characters a line, 16 of padding, on `raised` while newest, dimming to `dim` without paper, three at most, level with their row, riding it until the panes change or the row goes, an older one gliding above the newest's place or under it), `below` (the caption band), `above` (a band over the drawing), `on` (where the scene puts it, its stem round the drawing's top lane); the change between beats (`change`: fade 12 f, fold 24 f, glide 24 f (48 f between kinds of placement, a pane crossing to the other column going down its own first, then across), unfold 24 f, fade in 12 f; a pane that changes its rows fades out and in round its glide) | +| | `column` | `src/column.zig` (`Column`, `canim.column`, `beat`) | the shelf (y 48: each folded pane's tag in the frame's order, its note: the scene's, or computed for the registers (those the step changed, the first's value struck as on its row, crossfading with the strike), the source (`line 12`) and the disassembly (`jne 4011af`), crossfading with the advance); the panes from 84 to 1032, 12 apart; texts: `beside` (Go 40 on 54, at most 40 characters a line, 16 of padding, on `raised` while newest, dimming to `dim` without paper, three at most, level with their row, riding it until the panes change or the row goes, an older one gliding above the newest's place or under it), `below` (the caption band), `above` (a band over the drawing), `on` (where the scene puts it, its stem round the drawing's top lane); the change between beats (`change`: fade 6 f, fold where it stands and the tag to the shelf 18 f, glide 24 f (a pane crossing to the other column going down its own first, then across, 24 f each), unfold 18 f, fade in 6 f; a pane that changes its height keeps its rows: `Stage.resizing`, the descent's two layouts glided between, the source's window glided); a stem about a folded pane to its tag; `Beat.held`, and a bubble read past its beat flagged on stderr | +| | `segments` | `src/segments.zig` (`read`, `Segments`, `Place`) | the address space to true scale from the recording's mappings (permissions, file offsets): a slim bar the column's height, its ends' addresses and its size; clusters split at gaps of 16 MiB or more, and a band eight times the rest of its cluster in a box of its own; `enlarge` a box at a time (its bands with start, end and size, leaders to the bar), 108 wide; kept above y 888 under the camera (`clipStage`) | +| | the introduction's dump | `src/regroup.zig` (`Words`) | 128 bytes sixteen a row, no ink, the addresses faint; `regroup` to eight a row (bytes become words, low byte last), `ink`, `extend`, `become` (the words into the stack panel's rows) | +| | `aligned` | `src/aligned.zig` | the source and its instructions in one panel, each line level with its code: `interleaved` and `columns`; `decode` (an instruction's bytes to its row) and `align` (one form to the other) | +| | a text standing alone | `src/aside.zig` (`Aside`, `Asides`) | a column's bubble where no `Column` stands (the introduction's texts beside); `shortcut:` it repeats `column.zig`'s bubble drawing | +| | `pair` | `src/pair.zig` (`split`, `Frame`, `Report`, `Marks`, `Clock`, `Shelf`) | two runs on either side of the seam (design/README.md, `pair`): `split` each side's stage; `Frame` a frame as bytes eight a row read by its fields (`hexdump` `eight`: fields live from a moment, the letters keeping a string's ink in a pointer's field, the shadow byte of each row beside it, tall in the column, its words said as values for the relations); `Report` a stopped run's stderr in place of its registers; `Marks` `only here`, `differs`, `attention` and the `fault` (hazard bands round an ink plaque, SIGSEGV); `Clock` one rule and each run's moment; `Shelf` a folded side's tag | | | `clock`, `caption`, `veil`, `card` | `src/words.zig`, `src/root.zig` (`Narrator`, `Camera`) | the clock still while a step plays, its piece fading in once the mark lands; a caption stays its reading time; the title card is `scenes/title.zig` | | 6 verb | `fire`, `arm`, `strike`, `cool`, `read`, `extend`, `link`, `project`, `travel` (pins), `advance`, `cascade`, `continue` (`Cursor.continue`, `Plan.wave`), `run`, `sprint`, `establish` (`Context.establish`: a drawing's elements fade in rising, no lines), `scroll`, `relayout`, `visit`, `say`; `unroll` and `roll` (`Map.unroll`, `Map.roll`, above); `reach` and `unfold` (`graph`, above); `leave` and `turn` (`graph.leave`, from a block's last row, `graph.toEnd` to get there, along the curves of `rings` or `layers`: fire 0–12; the compare's chips framed as read from 18 (the CPU's slot, the jump's echo), held while the edge draws gold, head first, 24–42; the mark (a gold plaque, its point the way it goes) along the edge 42 to 42 + 12 f and 2 f a 100 units of the drawing's edge (42 f at most), round the ring's foot for a turn; landing, the advance; the target's count armed and struck 6 f after (a ring's turns at its centre armed as the mark leaves the latch, struck as it lands), cooled to nothing by the step's end; the trail recoloured over 18 f from the landing; a rest of 42 f from the landing); over a graph at a walk of several blocks, a run or a sprint the trail, the counts and the gold crossfade with the advance (8 f at a run, the step at a sprint), the pan gliding with it | `src/cursor.zig` (the timetable), `src/graph.zig` (`leave`, `instant`), the blocks (each draws its state at the instant) | tokens in `theme.time`; a level gives up its slot when nothing it touched is drawn (`Recording.drawn`); a label that changes in place with a step crossfades over the 12 f before the advance, or from the step's start where that is sooner (`Now.renaming`); at a run what marked a value goes with the run's ease (8 f) and a pin changes over it; at a sprint an ember and what grows come in over the step (4 f), never in a frame | @@ -203,7 +228,7 @@ and read (a debugger's `touch` reads count), each moment's `touch` and ## The recordings -`build.zig` records six programs of `tools/` under `ztrace record` (the +`build.zig` records the programs of `tools/` under `ztrace record` (the debugger: registers, the stack, what they point at, the instructions round the pc with their lines and callees' parameter counts, what each stack word is (`zt.telescope.slots`), at every stop: `--stack 1024 --around 256 @@ -253,6 +278,9 @@ before. The source panel follows the pc into any file it has | `musl` | `hello.c` again, built by Zig for `x86_64-linux-musl`, static, `-O0 -g` (musl compiled from its sources with it: no PLT, its lines its own) | every instruction, `--from main`, `--steps 166` (to main's return) | 173, 55 KB | reads `tools/note` | | `gallery` | the old `list` by line, kept in `test/gallery/list.ztrace`; for the graph pages `sort` and `hello` as recorded on 11 November (with blocks), kept in `test/gallery/sort.ztrace` and `hello.ztrace` (`gallery_sort`, `gallery_hello`) | | 134, 88 KB; 776 KB; 87 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` | 181 (42 stops, 138 syscalls), 494 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 | +| `overflow` | `overflow.c` (design/mock/overflow.c: a loop writing 32 bytes into `char buf[16]`), the system's clang `-O0 -g -fno-omit-frame-pointer -no-pie -fno-stack-protector`, glibc | every instruction, `--from main`, to the fault | 298, 60 KB | the recorder says `exit 139`; the SIGSEGV on the moment after `ret`, rip unchanged | +| `overflow_asan` | the same with `-fsanitize=address`, `ASAN_OPTIONS=detect_leaks=0` | every instruction, `--from main`, `--steps 582` (to `__asan_report_store1`'s first instruction) | 785, 257 KB | `--asan` (the shadow); the fake frame's header parsed by the scene from memory | +| `overflow_report` | the same run | `--by syscall --stack 0 --telescope 0 -s 4096` | 707, 401 KB | the report: its `write(2, …)`s, shown from their capture; `exit 1` | What builds each program: `fib.c` (`steps`) and `hello.c` for `musl`, Zig's build (`addExecutable`, musl, static); `hello.c` for `hello`, @@ -322,121 +350,183 @@ captions do not pair up it says so and checks no reading time), or the picture moving within 60 f of its arrival; chart.py does not count the list's dive (150 to 300 f) as a caption's change. -| | fib | list | sort | syscalls | musl | zoom | sqlite | heap | gallery | title | column | column_sort | -| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | -| POP, before / after | 7 / 10 | 12 / 13 | 5 / 3 | 7 / 21 | 16 / 16 | 4 / 5 | 4 / 7 | 16 / 17 | 9 / 9 | 0 / 0 | – / 9 | – / 6 | -| of them the strips' | 0 / 1 | 2 / 4 | 4 / 2 | 0 / 8 | 4 / 1 | 0 / 2 | 0 / 0 | 7 / 6 | 3 / 3 | 0 / 0 | – / 4 | – / 3 | -| POP exempt, before / after | | | | | | | | | cut 5 / cut 5 | | | | -| CROWD, before / after | 3 / 3 | 9 / 8 | 8 / 6 | 4 / 4 | 3 / 8 | 2 / 4 | 1 / 2 | 17 / 18 | 6 / 6 | 0 / 0 | – / 0 | – / 0 | -| METRONOME, before / after | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | – / 0 | – / 0 | -| CAPTION up over 720 f, before / after | 0 / 1 | 0 / 2 | 0 / 1 | 0 / 0 | 0 / 0 | 0 / 1 | 0 / 0 | 0 / 0 | 0 / 0 | | – / 0 | – / 1 | -| CAPTION under its reading time, before / after | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | | | not checked | not checked | -| CAPTION picture moving within 60 f, before / after | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | | not checked | – / 1 | -| AIR, before / after | 0 / 0 | 0 / 0 | 1 / 1 | 0 / 0 | 0 / 0 | 1 / 1 | 1 / 1 | 0 / 0 | 1 / 1 | 1 / 1 | – / 1 | – / 0 | -| seconds, before / after | 42.1 / 50.2 | 82.1 / 88.0 | 70.5 / 72.9 | 83.8 / 85.4 | 68.9 / 77.5 | 33.5 / 38.0 | 62.9 / 62.9 | 79.2 / 80.2 | 27.0 / 27.0 | 12.3 / 12.3 | – / 104.8 | – / 30.6 | +| | fib | list | sort | syscalls | musl | zoom | sqlite | heap | gallery | title | column | column_sort | asan | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| POP, before / after | 10 / 3 | 13 / 10 | 3 / 4 | 21 / 14 | 16 / 7 | 5 / 2 | 7 / 6 | 17 / 15 | 9 / 9 | 0 / 0 | 9 / 4 | 6 / 6 | – / 29 | +| of them the strips', before / after | 1 / 1 | 4 / 4 | 2 / 3 | 8 / 9 | 1 / 1 | 2 / 1 | 0 / 0 | 6 / 5 | 3 / 3 | 0 / 0 | 4 / 2 | 3 / 3 | – / 0 | +| POP exempt, before / after | | – / keyframe 1 | | | | | | | cut 5 / cut 5 | | | | | +| CROWD, before / after | 3 / 3 | 8 / 7 | 6 / 8 | 4 / 4 | 8 / 6 | 4 / 3 | 2 / 2 | 18 / 17 | 6 / 5 | 0 / 0 | 0 / 0 | 0 / 0 | – / 15 | +| METRONOME, before / after | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | – / 0 | +| CAPTION up over 720 f, before / after | 1 / 0 | 2 / 0 | 1 / 0 | 0 / 0 | 0 / 0 | 1 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | | 0 / 0 | 1 / 1 | – / 1 | +| CAPTION under its reading time, before / after | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | | | not checked | not checked | not checked | +| CAPTION picture moving within 60 f, before / after | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | | not checked | 1 / 1 | not checked | +| AIR, before / after | 0 / 0 | 0 / 0 | 1 / 1 | 0 / 0 | 0 / 0 | 1 / 1 | 1 / 1 | 0 / 0 | 1 / 1 | 1 / 1 | 1 / 0 | 0 / 0 | – / 1 | +| seconds, before / after | 50.2 / 48.2 | 88.0 / 83.9 | 72.9 / 74.5 | 85.4 / 85.4 | 77.5 / 66.8 | 38.0 / 34.9 | 62.9 / 62.9 | 80.2 / 80.2 | 27.0 / 27.0 | 12.3 / 12.3 | 104.8 / 95.3 | 30.6 / 29.5 | – / 120.0 | + +"Before" is the last pass's "after" (its gallery and title were the pass +before's: this pass exports every scene again). `asan` is new; the +introduction's three scenes (`intro_memory`, `intro_stack`, `intro_code`) +are built and tested but not exported (the round's order moved them to the +next). The column's, column_sort's and asan's "caption" regions are not a +caption's (the text column, a drawing's band), so their CAPTION lines are +not a caption's; the column's own check is the renderer's (`column: bubble N +is still read …`): C2's bubble (74 characters) 1.8 s past its three steps. + +What this pass changed, a kind of one-frame change at a time, each at its +block (the catalogue's rule: nothing changes in one frame): -"Before" is the last pass's "after". The gallery and the title were not -exported again (the gallery keeps `.whole` and its old recordings: its test -against its pictures passes); every other scene was, on the tracer's new -recordings. The scenes that walk stack code are longer: under `tied` a step -that touches the stack or moves rsp plays its verbs one after another -(touch, word, pin, window), and a call or a return walked in a descent takes -the stack's timetable before its windows move (fib +8.1 s, musl +8.6, list -+5.9, zoom +4.5, sort +2.4, syscalls +1.6; heap +1.0 under `.whole`, its new -pop and ret reads taking a memory slot). Five captions now stand over 720 f -(fib, list twice, sort, zoom): the steps under them grew longer, not the -captions. The column's regions are its own (`design/motion/motion.py`: -the shelf, the panes' column and its strips, the text column, the clock and -the caption band); its "caption" region is the text column, which in its -opening and close is the state column and where an older text dims and -glides: its CAPTION counts are not a caption's (the instrument finds 39 -"arrivals" for twelve texts), and are not checked. +- An instruction's in-step annotation (`lea`'s `= 402004 ← "note"`, a + register's first value, a compare's flags, the canary's word, `rbp = + rsp`'s value) fades in from its strike (12 f; at a run with the run's + ease) (`disasm.zig`); a row the advance changes (its state, its trail, its + line number) is drawn as before and as after and crossfades over the + advance's middle (`disasm.zig`, `descent.zig`); a descent's plaque lands + over the advance's second half; a descent window's shared digits are of + its own rows that show. +- Scrolls of the source and the disassembly move at least a pixel a frame + from rest (`cursor.glidePixels`): a glide's first frames, each under a + pixel, stood still a frame on whole pixels. +- The stack's `call` spans are matched by the frame they are (its foot), not + by depth: a call's step drew `_start_c` twice in its first frame; a new + frame comes in with rsp's pin, a frame taken off shrinks to its foot and + goes, the newest from the pin's middle. rsp's amount on its pin comes in + over 6 f; a stub arc (a pointer past the window) and a saved rbp's arc come + in over 12 f with their step and go with its advance; a write's arm frame + comes in over 4 f (the catalogue's 2 f left a few pixels for one frame). +- What the kernel fills (a `read`'s buffer) strikes a byte every 2 f by its + own landing times, each value at s+3, the fill under it; the list's view + scrolls its dump's window (24 f) where it jumped; a node's lone pin name + that had kept the right goes over to the left fading out and in, and two + names whose order a step turns crossfade; the shelf's struck digits + crossfade to bold; heap's own drawing lets its count's and the top's marks + leave as marks leave. +- The column: panes that leave fold where they stand and only their tags + travel to the shelf (6 f rows, 18 f fold), panes glide 24 f, one that + changes its height keeps its rows (the descent was empty 40 f at C7), a + source window of one or two lines shows its line (it showed lines 1 and 2 + of the file at C5 and C6); a drawing's tag note fades where it no longer + fits; C1 to C12's texts as the storyboard cuts them. +- Lengths: the steps the captions do not name run (musl's prologue, its + arguments, `__syscall_cp`'s frame; zoom's `mov rbp, rsp` and `sub rsp`; + list's last loop test said faster), and long captions retimed: fib's first + walks to its frame made (13.6 to 11.6 s), list's two end at the loop's test + (12.07 to under 12 s), sort's last value split in two (12.8 s), zoom's + frame-building one (14.3 to 11.1 s). sort is 1.6 s longer for its split. +- The relations (Part 1.5, above): their pictures and timings are as they + were, every frame of fib, list, zoom, sqlite and column compared before + and after. -What this pass built (design/README.md's "column (an experiment)", `insn`, -`slot`, `stack`, "4. Ties" (`touch`, `carry`); motion.md's "A scene in the -column", "A word touched", "A call pushed", "A return", "The stack's own -instructions"; mocks 44 to 56): +The relations' cost, measured (`CANIM_RELATIONS=1`, a line a frame; `zig +build bench -- relations`): -- The text column (`src/column.zig`, above): the shelf, the panes in one - column, texts `beside` (level with their row, riding it, dimming, three at - most), `below`, `above`, `on`; the change between beats in its order - (fade, fold, glide, unfold, fade in), a pane crossing to the other column - going down its own first, a pane that changes its rows faded round its - glide; `Stage.glide`, `Stage.column` (the clock under the text column), - `Stage.zoom` (a drawing across both columns, its tag at its size); places - for a text to be level with (`ties.Place.row`, `floor`, `block`). The - trial `column` (the storyboard's C1 to C12) and `column_sort` (`on` and - `above` sort's rings). -- The disassembly tied to the stack, the knob `annotation` (`.tied` the - default; `.whole` in heap, sqlite and the gallery): the row's names and one - hop, its moves of rsp and rbp, the stack's offsets from the frame's base - and its two words of headroom, the `touch`, the pin's travel (rows held, - the amount on the pin, rows gained or released, the span riding) and the - window following after, every verb in motion.md's order; the knob `carry` - (`.off` by default; `.arrow` on zoom's first beat). On the tracer's new - recordings: the touches of `push`, `pop`, `call`, `ret`, `leave`, data - names (`head`), the push's role at its own stop, shared words (`i, n`), - the canary. +| | places | values | candidates | drawn | sort | the resolver's passes | all, a frame | +| --- | --- | --- | --- | --- | --- | --- | --- | +| fib, the working frame, each frame | 64 (74 at most) | 27 | 3 at most | 3 at most | 5.5 µs | | 23 µs mean, 69 µs at the 95th, drawing included | +| list, the working frame | 87 (96) | 28 | 5 | 3 | 5.6 µs | | 16 µs, 52 µs | +| list, the map (269 frames) | 790 (827) | 288 | | | | | sort and join 57 µs mean, 81 µs at most | +| bench, a working frame's tables | 300 | 120 | 16 pairs | | 21 µs | join 0.9 µs, passes 0.6 µs | the old table: 11 µs (a lookup a scan) | +| bench, a map's | 4,000 | 6,000 | 746 pairs | | 516 µs | join 19 µs, passes 29 µs | 0.56 ms; the old table 5.7 ms | -Right in one frame, and exempted by name: the encoder's keyframes and the -gallery's cuts (above). +The old table's real cost a frame was not measured (it held under 512 +places and was scanned per lookup): at the working frame's size it was as +cheap; the tables' gain is the map's size and the frame owning them. -What fires still (this pass's exports; located where it says so, the rest -counted, not looked at): +What fires still (the finals; located where it says so): -- The column: four in the panes' strips (12 to 38 pixels, 16.90 to 91.53); - 35.73, a library address's shared digits changing in a frame as the run - enters libc (looked at: the disassembly's own `lead`, as in musl); 82.85, - the read's first byte landing over the buffer's dots (looked at, as in - syscalls before); 59.55 and 91.65, a tag note's struck digits turning - bold (20 to 28 pixels on the shelf, looked at); 20.32 (12 pixels) not - looked at. No CROWD: the panes change one move after another. AIR at - 28.93 (4.9 s): the stub's text (104 characters) is still being read after - its step. -- syscalls: 21, of them 8 in the strips. Looked at: 9.45 and 38.27, a row's - in-step annotation (the `lea`'s `= 402004 ← "note"`, a register set's - `r8 0`) appearing in one frame as the CPU's strike lands, not faded; 59.32, - the source and the disassembly scrolling to line 7 (its first frame the - largest). 11.05, 39.87, 41.47 (the disassembly), 16.62, 59.48, 81.70 (the - stack, 22 to 25 pixels), 44.88 and 49.80 (registers, 12 and 16 pixels), - 49.53 (source, 17), 65.85 (the view, 72: the read's first byte) not - looked at. The new ones are the tie's: they want the in-step annotation - faded in with its strike (`disasm.zig`'s `value_at`), for the same - instruction under `whole` too. -- fib 10, list 13, musl 16, heap 17, sqlite 7, zoom 5, sort 3, - column_sort 6: counted, not located this pass (their timings all moved). - musl's sixteen are mostly in the disassembly, 1.6 s apart in its walks: - likely the same in-step annotations. -- CAPTION over 720 f (fib 15.78, list 39.45 and 68.18, sort 45.48, zoom 1.25, - column_sort 9.67): the steps under a caption grew with the tie's order. -- AIR: sort's, zoom's and sqlite's last pictures (held by design), the - gallery's atoms page and the title's card (not exported again). -- CROWD: the advance (thread, plaques and rip as one mark), the veil over - three panels at a run's first step, sort's `surface` and `dive`; musl's - eight and zoom's four not looked at. +- asan, 29: A6's run, 14 in ASan's disassembly (12 to 29 pixels, 0.3 s + apart: the advance's crossfade at a run is 4 f, small text); plain's + registers' chain string growing at each store of A15 (80 pixels, every + 0.8 s, its rbp and rsp hops reading the letters); 100 pixels at 66.6 s in + plain's disassembly (into the column); the rest single. Its CAPTION over + 720 f is the column part (no caption band there), its AIR the poster's + held rest (meant). +- syscalls 14, 9 of them in the strips: six the disassembly's strip region + crossed by a touch's head (12 to 15 pixels, looked at: the touch leaving + the row's rule over the strip), three the stack's and the source's strips + (38 pixels, not looked at); 4.07, 59.48, 81.70 the stack (23 to 25 pixels, + not looked at); 44.88 and 49.80 registers (12, 19, not looked at). The + read's first byte landing in one frame (65.85) is gone. +- column 4: 28.53 the source's strip as the pane shrinks to two lines at + rest (its strip is drawn at the pane's height, not lagged: looked at); + 52.92 and 82.77 the shelf (106 pixels, not looked at); 60.98 a strip. +- fib 3, list 10, musl 7, sort 4, zoom 2, sqlite 6, heap 15, column_sort 6: + list's 13.62, 42.52 and 71.55 the nodes (120 to 280 pixels: 71.55 a pin's + names, now crossfaded, the others not looked at); musl's 55.68 and 64.28 + in the descent (112 pixels, not looked at); heap's drawing (88 to 197) and + its stack strip (68 to 71) not looked at; zoom's 17.40 registers (12 + pixels) and 24.67 its stack strip. +- The gallery's 12.62 and 15.40 are its relayouts (a page a state), 9.00 its + step. ## What is not done -- The column (an experiment): a text `on` a drawing sits where the scene - puts it (`Beat.where`) and its stem goes along the drawing's top lane and - down to the part it speaks of; nothing checks that it keeps 16 clear of - every element and path, nor falls back to `above` where it cannot. A text - about a folded pane does not point at its tag on the shelf; at a sprint - the scene does not surface to the map with a text `on` it. Only the - registers', the source's and the disassembly's tag notes are computed - (the lens's and the stack's are the scene's). A text rides its row until - the panes change or the row goes, then stays: remembered by the process - as frames are drawn in order (`last_level`, `latched`: an export, a - player playing), so after a seek a text whose row has gone sits at 400 - until its row is seen again. A pane that changes its rows fades them out - and in round its glide (they are laid out for its height), so the - descent is empty for about 40 f as it grows to the kernel's floor. The - panes keep their minimaps (mocks 49 to 53 draw none). The lens is one - object: its view can stand with its drawing folded (the bytes over the - source), not the other way round. The trial is 104.8 s against the - working frame's 85.3 (`syscalls` this pass): the storyboard's longer - texts' reading times and about 9.6 s of pane changes (seven of them); a - sixth longer would be 99.5 s. +- The column: a text `on` a drawing sits where the scene puts it + (`Beat.where`) and its stem goes along the drawing's top lane and down to + the part it speaks of; nothing checks that it keeps 16 clear of every + element and path, nor falls back to `above` where it cannot (the + catalogue asks the renderer to find and check the place). On the way back + to the working frame a drawing whose working box is the band (y 48) glides + over the shelf's tags before they unfold (`column_sort`, 26.6 to 27 s): the + order is the catalogue's (glide, then unfold), but the band's box and the + shelf are at one height; its tag's note now fades where it no longer fits. + A strip of a pane that changes its height at rest is drawn at the pane's + height now, not lagged and averaged (the source's strip at C5, one frame). + At a sprint the scene does not surface to the map with a text `on` it. + Only the registers', the source's and the disassembly's tag notes are + computed (the lens's and the stack's are the scene's). A text rides its + row until the panes change or the row goes, then stays: remembered by the + process as frames are drawn in order (`last_level`, `latched`: an export, + a player playing), so after a seek a text whose row has gone sits at 400 + until its row is seen again. The panes keep their minimaps (mocks 49 to 53 + draw none). The lens is one object: its view can stand with its drawing + folded (the bytes over the source), not the other way round. The bubble + check is the renderer's own (stderr, once a process), not chart.py's: the + instrument still cannot pair the column's texts with what it sees (its + "caption" region is the text column, where texts dim and glide). C2's + bubble (74 characters) is flagged: 1.8 s past its three steps. +- The ASan pair (`asan`): `never returned` on ASan's stopped call is not + drawn (its row keeps the plaque and its call); the disassemblies' tags say + `fill`, not `plain · fill`; plain's registers read rbp's and rsp's chain as + a string of A's (the mock's `← 0x4141414141414141` is not `rows.chain`'s); + a field keeps one held corner (the newest write's), not one a byte; the two + disassemblies keep their own windows round their pcs, not aligned by line; + the clock says `i 27 · plain moment N · asan moment M`. In the column, plain's + descent follows the frame chain, which the overwritten return address ends + in `fill` from i = 24: main's window goes over 82.4 to 83 s, after the aim + has glided to `fill+1`. The scene is 120 s against the storyboard's 112: + the two-line captions' reading times and the column's changes. A6's run + and A15's stores leave one-frame changes (above). The recorder cannot stop + a run by instruction at a function: ASan's is cut by a count (`--steps + 582`), which moves with the compiler; the fake frame's header is parsed by + the scene from memory, plain's fields from the instructions' rbp offsets, + and the two runs' stops are matched by pc. +- The introduction (`intro_memory`, `intro_stack`, `intro_code`): built and + tested before the round's order moved it to the next round; not exported, + and its chapters II and III not looked at again after their last texts + were cut. Chapter I follows its storyboard (68 s against 66): the bytes + under the camera, `regroup`, `segments` and `enlarge` (with a box of its + own for the tracer's 64 MiB ring, which the recording's mappings hold), + the tie, the visit, `ink`, the chains. II has no touch line (no + disassembly row on screen), its roles and spans come with the rows, its + stack shows 23 words (16 asked), its registers are canim's folded layout + (not mock 31's seventeen rows). III has no annotation column (mock 33's + chain) and no keyword ink in its source, `stack` is a crossfade (not a + morph), the minimaps do not draw themselves last, and the map's text is a + caption, not `on` the map. All three use `list` (moment 77; 582 for III): + `--from reverse` stops past the prologue, so the `push rbp` the storyboard + names is the call's push of its return address. +- The relations: arcs within a panel (the stack's, a dump's, a loupe's) + are still each panel's own (`rows.Arcs`, lanes per panel), not rows of + the frame's tables; the column's stems are drawn by the column, their + targets found in the tables; a loupe's stem and a dump's place are not + kinds yet. The beat's `emphasis` is not built; the carry keeps its own + budget (it was drawn beside a link and a projection before, and is still: + the catalogue counts it among the two active lines). The tables are made + and sorted every frame, not cached per moment and window. An aim for the + step (`.step`) has no slot of its own in the step's timetable (it draws + after the word's strike, over what follows). The map's places and values + are tabled and measured (`CANIM_RELATIONS=1`), but the map draws no + relation of the frame's: its thread and arcs are its panels' own. - The tie to the stack (Part B's leftovers): the window's scroll to a touched word outside it happens in the fire's frames, with no slot of its own; in a step by line all writes land before the pins and the call row does not diff --git a/anim/build.zig b/anim/build.zig index 6351250..9c7d63e 100644 --- a/anim/build.zig +++ b/anim/build.zig @@ -16,7 +16,7 @@ const std = @import("std"); const sketchbook = @import("sketchbook"); -const scenes = [_][]const u8{ "title", "fib", "list", "sort", "syscalls", "musl", "zoom", "heap", "gallery", "column", "column_sort" }; +const scenes = [_][]const u8{ "title", "fib", "list", "sort", "syscalls", "musl", "zoom", "heap", "gallery", "column", "column_sort", "intro_memory", "intro_stack", "intro_code", "asan" }; pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); @@ -222,6 +222,47 @@ pub fn build(b: *std.Build) void { source_modules.append(b.allocator, .{ .name = b.fmt("{s}-sources", .{r.name}), .module = sources }) catch @panic("OOM"); table.print(b.allocator, "pub const {s}: Program = .{{ .trace = @embedFile(\"{s}\"), .file = \"{s}\", .source = @embedFile(\"{s}\"), .sources = &@import(\"{s}-sources\").list }};\n", .{ r.name, file, r.source, r.source, r.name }) catch @panic("OOM"); } + // The pair (`asan`, design/motion.md "A scene: ASan against a plain + // build"): overflow.c built twice by the system's clang, plain and with + // AddressSanitizer, frame pointers kept and no canary (Arch's clang puts + // one in by default, and the plain run would die in `__stack_chk_fail`, + // not at `ret`). Each run as `./overflow` in a directory of its own, with + // no environment but ASan's leak check off (it fails under a tracer): + // plain by instruction from main to its fault at `ret` (the recorder + // says `exit 139`, SIGSEGV); ASan by instruction from main to the first + // instruction of `__asan_report_store1` (582 stops: the report itself is + // a million more), and the same run again by syscall alone, for the + // report's `write`s to fd 2 as written. + for ([_]struct { name: []const u8, asan: bool, args: []const []const u8, exit: []const u8 }{ + .{ .name = "overflow", .asan = false, .args = &.{ "--by", "insn", "--stack", "1024", "--around", "256", "--disasm", "69", "-s", "64", "--from", "main" }, .exit = "exit 139" }, + .{ .name = "overflow_asan", .asan = true, .args = &.{ "--asan", "--by", "insn", "--stack", "1024", "--around", "256", "--disasm", "69", "-s", "64", "--from", "main", "--steps", "582" }, .exit = "exit 0" }, + .{ .name = "overflow_report", .asan = true, .args = &.{ "--by", "syscall", "--stack", "0", "--telescope", "0", "-s", "4096" }, .exit = "exit 1" }, + }) |r| { + const cc = b.addSystemCommand(&.{ "clang", "-O0", "-g", "-fno-omit-frame-pointer", "-no-pie", "-fno-stack-protector" }); + if (r.asan) cc.addArg("-fsanitize=address"); + cc.addFileArg(b.path("tools/overflow.c")); + cc.addArg("-o"); + const program = cc.addOutputFileArg("overflow"); + const where = b.addWriteFiles(); + _ = where.addCopyFile(program, "overflow"); + const link = "ln -sfn \"" ++ debuginfod_cache ++ "\" debuginfod && exec env -i DEBUGINFOD_CACHE_PATH=debuginfod "; + const run = b.addSystemCommand(&.{ "sh", "-c", if (r.asan) link ++ "ASAN_OPTIONS=detect_leaks=0 setarch -R \"$0\" \"$@\"" else link ++ "setarch -R \"$0\" \"$@\"" }); + run.addArtifactArg(ztrace); + run.addArg("record"); + run.addArgs(r.args); + run.addArg("-o"); + const trace = run.addOutputFileArg(b.fmt("{s}.ztrace", .{r.name})); + run.addArgs(&.{ "--", "./overflow" }); + run.setCwd(where.getDirectory()); + run.expectExitCode(0); + run.expectStdErrMatch(r.exit); + const file = b.fmt("{s}.ztrace", .{r.name}); + record_step.dependOn(&b.addInstallFile(trace, b.fmt("recordings/{s}", .{file})).step); + _ = embedded.addCopyFile(trace, file); + table.print(b.allocator, "pub const {s}: Program = .{{ .trace = @embedFile(\"{s}\"), .file = \"overflow.c\", .source = @embedFile(\"overflow.c\") }};\n", .{ r.name, file }) catch @panic("OOM"); + } + _ = embedded.addCopyFile(b.path("tools/overflow.c"), "overflow.c"); + // 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 diff --git a/anim/scenes/asan.zig b/anim/scenes/asan.zig new file mode 100644 index 0000000..2fe743f --- /dev/null +++ b/anim/scenes/asan.zig @@ -0,0 +1,563 @@ +//! ASan against a plain build (design/motion.md, "A scene: ASan against a +//! plain build"): `overflow.c`'s loop writes 32 bytes into 16, built plain +//! and with AddressSanitizer, the two runs a `pair` (design/README.md): +//! the shared source, each run's disassembly, registers and frame as bytes +//! on its side of the seam, `buf` facing `buf`. They go together to i = 16, +//! where they part: plain stores into its saved rbp, ASan reads `f3` in the +//! shadow and calls its report, which comes in from the run's own `write`s +//! in place of its registers; plain goes on alone, a letter a turn, through +//! the saved rbp and the return address (the held rest at i = 27 is the +//! poster, mock 38), to `ret` and its fault. Beats A1 to A16, the +//! storyboard's texts as written; A10 to A13 in the pair as captions (see +//! the README: the column holds no frame as bytes). +const std = @import("std"); +const anim = @import("anim"); +const canim = @import("canim"); +const recordings = @import("recordings"); +const pair = canim.pair; + +pub const background = canim.background; +pub const scene = anim.Live(frame, struct {}); + +/// The first moment from `from` whose instruction begins with `text`. +fn on(rec: *canim.Recording, from: u64, text: []const u8) u64 { + var buf: [256]u8 = undefined; + var i = from; + while (i < rec.end()) : (i += 1) if (rec.instruction(i, rec.register(i, "rip"), &buf)) |here| if (std.mem.startsWith(u8, here.text, text)) return i; + return rec.end(); +} + +/// The `n`th moment (from 0) from `from` whose pc is `pc`. +fn nth(rec: *canim.Recording, from: u64, pc: u64, n: usize) u64 { + var seen: usize = 0; + var i = from; + while (i < rec.end()) : (i += 1) if (rec.register(i, "rip") == pc) { + if (seen == n) return i; + seen += 1; + }; + return rec.end(); +} + +/// Each moment from here to `until` walked, its whole sentence said in +/// `seconds` (null: as long as it takes). +fn walk(s: *anim.Frame, c: canim.Cursor, until: u64, seconds: ?f32) void { + var here = c.moment(s); + while (here < until) : (here += 1) { + const plan = c.reading(here, here + 1); + c.step(s, here + 1, plan, seconds orelse plan.total); + } +} + +/// Straight to `to` at a run: unmarked, values changing in place under 8 f crossfades. +fn run(s: *anim.Frame, c: canim.Cursor, to: u64, seconds: f32) void { + c.step(s, to, canim.Plan.running(seconds), seconds); +} + +/// To `until` at a run, `per` moments a step (each step at least 18 f: the +/// mark's 8 f ease and its 8 f advance), the first steps as long as `ramp` +/// says and the rest as long as its last. +fn runTo(s: *anim.Frame, c: canim.Cursor, until: u64, per: u64, ramp: []const f32) void { + var here = c.moment(s); + var k: usize = 0; + while (here < until) : (k += 1) { + const next = @min(here + per, until); + const sec = ramp[@min(k, ramp.len - 1)]; + run(s, c, next, sec); + here = next; + } +} + +/// The two runs from one instant: the scene goes on when the later is done. +const Together = struct { + start: f32, + end: f32, + fn begin(s: *anim.Frame) Together { + return .{ .start = s.cursor, .end = s.cursor }; + } + /// The next run's part, from the same start. + fn next(tg: *Together, s: *anim.Frame) void { + tg.end = @max(tg.end, s.cursor); + s.cursor = tg.start; + } + fn done(tg: *Together, s: *anim.Frame) void { + s.cursor = @max(tg.end, s.cursor); + } +}; + +/// Of the right run's function, the rows no row of the left faces (`only +/// here`): all but the frame's own instructions, the loop counter's (the +/// memory the loop's `cmp …, 0x20` reads), the branch after that compare, +/// `add eax, 1`, the store of 'A', and the jump back to the compare. +fn onlyHere(a: std.mem.Allocator, rec: *canim.Recording, at: u64, start: u64) []const u64 { + var out: std.ArrayList(u64) = .empty; + var buf: [256]u8 = undefined; + var counter: []const u8 = ""; + var head: u64 = 0; + var addr = start; + var after_head = false; + while (rec.instruction(at, addr, &buf)) |one| : (addr += one.len) { + const text = a.dupe(u8, one.text) catch break; + if (std.mem.startsWith(u8, text, "cmp dword ptr [") and std.mem.endsWith(u8, text, ", 0x20")) { + counter = text[std.mem.indexOfScalar(u8, text, '[').? .. std.mem.indexOfScalar(u8, text, ']').? + 1]; + head = addr; + } + } + addr = start; + while (rec.instruction(at, addr, &buf)) |one| : (addr += one.len) { + const text = one.text; + const jump_back = std.mem.startsWith(u8, text, "jmp") and std.mem.endsWith(u8, text, a.dupe(u8, std.fmt.bufPrint(buf[200..], "0x{x}", .{head}) catch "") catch ""); + const faces = std.mem.eql(u8, text, "push rbp") or std.mem.eql(u8, text, "mov rbp, rsp") or std.mem.eql(u8, text, "pop rbp") or + (counter.len > 0 and std.mem.indexOf(u8, text, counter) != null) or after_head or std.mem.eql(u8, text, "add eax, 1") or + (std.mem.startsWith(u8, text, "mov byte ptr") and std.mem.endsWith(u8, text, ", 0x41")) or jump_back; + after_head = addr == head; + if (!faces) out.append(a, addr) catch break; + if (std.mem.eql(u8, text, "ret")) break; + } + return out.items; +} + +/// The signal that stopped the run, if one did: its moment and its name. +fn signal(rec: *canim.Recording) ?struct { at: u64, name: []const u8 } { + var i = rec.end(); + while (i > 0) { + i -= 1; + var events = rec.moment(i).events(std.heap.page_allocator) catch continue; + defer events.deinit(std.heap.page_allocator); + while (events.next()) |item| if (item.ev.kind == .signal) { + return .{ .at = i, .name = switch (item.ev.aux) { + 4 => "SIGILL", + 5 => "SIGTRAP", + 6 => "SIGABRT", + 7 => "SIGBUS", + 8 => "SIGFPE", + 11 => "SIGSEGV", + else => "a signal", + } }; + }; + } + return null; +} + +/// A stopped run's tag on the shelf: `stopped:` and its report's first words +/// (the error's kind, and the access: `stack-buffer-overflow, WRITE of size 1`). +fn stopped(a: std.mem.Allocator, said: []const u8) []const u8 { + const kind = blk: { + const at = std.mem.indexOf(u8, said, "AddressSanitizer: ") orelse break :blk ""; + const rest = said[at + "AddressSanitizer: ".len ..]; + break :blk rest[0 .. std.mem.indexOfAny(u8, rest, " \n") orelse rest.len]; + }; + const access = blk: { + const at = std.mem.indexOf(u8, said, "WRITE of size") orelse std.mem.indexOf(u8, said, "READ of size") orelse break :blk ""; + const rest = said[at..]; + break :blk rest[0 .. std.mem.indexOf(u8, rest, " at ") orelse rest.len]; + }; + return std.fmt.allocPrint(a, "stopped: {s}, {s}", .{ kind, access }) catch "stopped"; +} + +fn frame(s: *anim.Frame) void { + const plain = canim.open(recordings.overflow); + const asan = canim.open(recordings.overflow_asan); + const report = canim.open(recordings.overflow_report); + const t = canim.theme.time; + + // Plain: main's call; fill's line 4; the turns, each from its compare; the store of each; the way out. + const p_call = on(plain, plain.call("main", 0).enter, "call"); + const p_line4 = plain.lineMoment(4, p_call + 1); + const p_head = plain.register(on(plain, p_line4, "cmp"), "rip"); + var p_turn: [33]u64 = undefined; + var p_store: [32]u64 = undefined; + for (&p_turn, 0..) |*m, i| m.* = nth(plain, p_line4, p_head, i); + for (&p_store, 0..) |*m, i| m.* = on(plain, p_turn[i], "mov byte ptr"); + const p_pop = on(plain, p_turn[32], "pop rbp"); + const fault = signal(plain); + const p_end = if (fault) |f| f.at else p_pop + 2; + + // ASan: the same call; its prologue and `__asan_stack_malloc_0`, stepped over; line 3; the turns. + const q_call = on(asan, asan.call("main", 0).enter, "call"); + const q_fill = q_call + 1; + const q_malloc = on(asan, q_fill, "call"); + var ibuf: [256]u8 = undefined; + const malloc_pc = asan.register(q_malloc, "rip"); + const q_back = nth(asan, q_malloc + 1, malloc_pc + asan.instruction(q_malloc, malloc_pc, &ibuf).?.len, 0); + const q_line3 = asan.lineMoment(3, q_back); + const q_line4 = asan.lineMoment(4, q_line3); + const q_head = asan.register(on(asan, q_line4, "cmp dword ptr"), "rip"); + var q_turn: [17]u64 = undefined; + for (&q_turn, 0..) |*m, i| m.* = nth(asan, q_line4, q_head, i); + const q_load = struct { + fn of(rec: *canim.Recording, from: u64) u64 { + var buf: [256]u8 = undefined; + var i = from; + while (i < rec.end()) : (i += 1) if (rec.instruction(i, rec.register(i, "rip"), &buf)) |here| if (std.mem.indexOf(u8, here.text, "0x7fff8000]") != null) return i; + return rec.end(); + } + }.of; + const report_call = on(asan, q_load(asan, q_turn[16]), "call"); + + // The frames: plain's from rbp at line 4 (`i` at rbp-0x14, `buf` at rbp-0x10, then the saved rbp and the + // return address); ASan's fake frame, where `__asan_stack_malloc_0` put it, by its descriptor. + const rbp = plain.register(p_line4, "rbp"); + const buf = rbp - 0x10; + const fake = asan.register(q_back, "rax"); + const real = asan.register(q_line4, "rbp"); + // The descriptor ("1 32 16 5 buf:3"): one variable, at 32, 16 long. + var var_at: u64 = 32; + var var_len: u64 = 16; + if (canim.Recording.word(asan.moment(q_line3), fake + 8, 8) catch null) |descr| { + var text: [32]u8 = undefined; + var known: [32]bool = undefined; + if (asan.moment(q_line3).read(descr, &text, &known)) |_| { + var it = std.mem.tokenizeScalar(u8, text[0 .. std.mem.indexOfScalar(u8, &text, 0) orelse text.len], ' '); + _ = it.next(); + if (it.next()) |a| var_at = std.fmt.parseInt(u64, a, 10) catch var_at; + if (it.next()) |a| var_len = std.fmt.parseInt(u64, a, 10) catch var_len; + } else |_| {} + } + const fake_buf = fake + var_at; + + var at = canim.cursor(s, plain, p_call); + var as = canim.cursor(s, asan, q_call); + for ([_]*canim.Cursor{ &at, &as }) |c| c.levels = .{ .source_rows = 5, .fire = .disasm }; + at.journey(.moment, p_end); + as.journey(.moment, report_call); + + const left = canim.Stage.init(s, pair.split(.left, false)); + const right = canim.Stage.init(s, pair.split(.right, false)); + const fake_in = s.value(0); + const differs = s.value(0); + const attention = s.value(0); + const framed = s.value(0); + + const source = canim.add(s, canim.Source{ .cursor = at, .stage = left, .tag = "both builds" }); + const dis_l = canim.add(s, canim.Disasm{ .cursor = at, .stage = left }); + // In the column (A10 to A13) plain's disassembly is a descent: main's window, the row + // its return address names among them, over fill's whole (motion.md, the column's panes). + const desc_l = canim.add(s, canim.Descent{ .cursor = at, .stage = left }); + const dis_r = canim.add(s, canim.Disasm{ .cursor = as, .stage = right, .rows = 9 }); + const reg_moves = struct { + fn of(names: []const []const u8) u32 { + var mask: u32 = 0; + for (names) |n| for (canim.ztrace.Regs.names, 0..) |known, i| { + if (std.mem.eql(u8, known, n)) mask |= @as(u32, 1) << @intCast(i); + }; + return mask; + } + }.of; + const regs_l = canim.add(s, canim.Registers{ .cursor = at, .stage = left, .moves = reg_moves(&.{ "rax", "rbp", "rsp", "rip" }), .folds = false, .title = "plain \u{00b7} registers" }); + const regs_r = canim.add(s, canim.Registers{ .cursor = as, .stage = right, .moves = reg_moves(&.{ "rax", "rbx", "rcx", "rip" }), .folds = false, .title = "asan \u{00b7} registers" }); + const offset = pair.shadowOffset(asan) orelse 0x7fff8000; + const frame_l = canim.add(s, pair.Frame{ + .cursor = at, + .stage = left, + .title = "plain \u{00b7} stack", + .note = "fill's frame as bytes, eight a row", + .first = buf - 32, + .rows = 10, + .fields = s.arena.dupe(pair.Field, &.{ + .{ .at = rbp - 0x14, .len = 4, .name = "i", .from = p_line4 }, + .{ .at = buf, .len = 16, .name = "buf", .reads = .text, .from = p_line4 }, + .{ .at = rbp, .len = 8, .name = "saved rbp", .reads = .pointer, .from = p_call + 2 }, + .{ .at = rbp + 8, .len = 8, .name = "return", .reads = .pointer, .from = p_call + 1 }, + }) catch unreachable, + .letters = buf, + .span = .{ rbp - 0x18, rbp + 16 }, + .span_from = p_call + 1, + .tall = rbp - 0x18, + .name = "fill", + .side = .left, + .shows = s.value(1), + .differs = differs, + .differ = s.arena.dupe(u64, &.{ rbp, rbp + 8 }) catch unreachable, + }); + const frame_r = canim.add(s, pair.Frame{ + .cursor = as, + .stage = right, + .title = "asan \u{00b7} fake frame", + .note = std.fmt.allocPrint(s.arena, "its shadow at addr >> 3 + {x} \u{00b7} then the real stack's way back", .{offset}) catch "", + .first = fake, + .rows = 8, + .then = real, + .more = 2, + .fields = s.arena.dupe(pair.Field, &.{ + .{ .at = fake, .len = 8, .name = "magic", .reads = .bytes }, + .{ .at = fake + 8, .len = 8, .name = "descr", .reads = .pointer }, + .{ .at = fake + 16, .len = 8, .name = "pc", .reads = .pointer }, + .{ .at = fake + 24, .len = 8, .name = "real stack", .reads = .pointer }, + .{ .at = fake_buf, .len = var_len, .name = "buf", .reads = .text }, + .{ .at = fake_buf + var_len, .len = 8, .name = "redzone", .reads = .bytes }, + .{ .at = fake_buf + var_len + 8, .len = 8, .name = "redzone", .reads = .bytes }, + .{ .at = real, .len = 8, .name = "saved rbp", .reads = .pointer, .from = q_fill + 1 }, + .{ .at = real + 8, .len = 8, .name = "return", .reads = .pointer, .from = q_fill }, + }) catch unreachable, + .letters = fake_buf, + .shadow = true, + .span = .{ fake, real + 16 }, + .span_from = q_fill, + .name = "fill", + .side = .right, + .shows = fake_in, + .differs = differs, + .differ = s.arena.dupe(u64, &.{ fake_buf + var_len, fake_buf + var_len + 8 }) catch unreachable, + }); + const stderr = canim.add(s, pair.Report{ + .rec = report, + .stage = right, + .title = "asan \u{00b7} stderr", + .lines = &.{ "ERROR: AddressSanitizer", "WRITE of size", "is located in stack", "This frame has", "<== Memory access", "=>0x" }, + .words = &.{ "stack-buffer-overflow", "WRITE of size 1", "[32, 48) 'buf'", "[f3]" }, + .framed = framed, + }); + const store_pc = plain.register(p_store[0], "rip"); + const load_pc = asan.register(q_load(asan, q_turn[0]), "rip"); + const right_shows = s.value(1); + const marks = canim.add(s, pair.Marks{ + .left = at, + .right = as, + .stages = .{ left, right }, + .name = "asan", + .only = onlyHere(s.arena, asan, q_fill, asan.register(q_fill, "rip")), + .attend = .{ store_pc, load_pc }, + .attention = attention, + .right_shows = right_shows, + .fault = if (fault) |f| .{ .at = f.at, .pc = plain.register(f.at, "rip"), .name = f.name } else null, + }); + const clock = canim.add(s, pair.Clock{ .left = at, .right = as, .names = .{ "plain", "asan" }, .counter = rbp - 0x14, .counting = p_line4 + 1, .stage = left }); + // A10 to A13 in the column (`canim.column`): plain's panes, its frame as bytes the column's height; ASan's + // side folded to one tag on the shelf, its report's first line its note. + const col = canim.column(s, .{ .stage = left, .source = source, .disasm = dis_l, .registers = regs_l, .stack = frame_l, .backtrace = frame_l, .cursor = at }, .{}); + const shelf_fold = s.value(0); + const said = pair.Report.stderr(report, s.arena); + const shelf = canim.add(s, pair.Shelf{ .stage = right, .title = "asan", .note = stopped(s.arena, said), .fold = shelf_fold }); + // No ties across the seam: this one draws nothing (no thread, no stack words) and clears the frame's places. + const joins = canim.add(s, canim.Ties{ .cursor = at, .stage = left, .threaded = false, .quiet = true }); + s.play(.{ marks.fadeIn(), joins.fadeIn(), shelf.fadeIn() }, .{ .seconds = 0 }); + var says: canim.Narrator = .{}; + + canim.establish(s, .{ clock, source, dis_l, dis_r, regs_l, regs_r, frame_l, frame_r }); + + // A1: fill() called in both, as any call. + says.line(s, "Plain against AddressSanitizer: a loop writes 32 bytes into 16."); + var tg = Together.begin(s); + walk(s, at, p_call + 1, null); + tg.next(s); + walk(s, as, q_fill, null); + tg.done(s); + + // A2: line 2, the prologues: plain's two rows walked; ASan's at a run (four rows a step), its + // stack_malloc stepped over, the fake frame's rows coming in as it is made; then the store that + // poisons the shadow walked, its cells struck 2 f apart. + says.line(s, "ASan's prologue moves `buf` to a fake frame\nand poisons its shadow: `f1` before `buf`, `f3` after."); + tg = Together.begin(s); + walk(s, at, p_line4, null); + tg.next(s); + { + const start = s.cursor; + s.play(.{ as.veil.to(1), as.hurried.to(1) }, .{ .seconds = t.veil }); + s.cursor = start; + // Ramping in: each step 0.6 of the one before, to a run's 18 f. + runTo(s, as, q_malloc, 4, &.{ 0.5, 0.36, 0.3 }); + run(s, as, q_back, 0.4); + // The fake frame is made: its rows come in (12 f). + const made = s.cursor; + s.play(.{fake_in.to(1)}, .{ .seconds = t.quick }); + s.cursor = made; + runTo(s, as, q_line3 - 1, 5, &.{ 0.3, 0.36, 0.5 }); + s.play(.{ as.veil.to(0), as.hurried.to(0) }, .{ .seconds = t.veil }); + s.wait(t.beat); + walk(s, as, q_line3, null); + } + tg.done(s); + + // A3: line 3, ASan's alone: buf's shadow f8 f8 turns 00 00. + says.line(s, "Line 3 is ASan's alone: `buf`'s shadow `f8 f8` turns `00 00`."); + // One step under a text read for 4.8 s: said slower, so that it covers the reading. + walk(s, as, q_line4, 2.2); + + // A4: i = 0, the check: plain at a run to its store, where it waits facing ASan's check; ASan's + // counter and compare at a run, then its address and check rows walked, 30 f a row, the load longer. + says.line(s, "Before each store ASan reads `buf[i]`'s shadow byte,\nat `(addr >> 3) + 7fff8000`."); + const q_check0 = q_load(asan, q_turn[0]); + tg = Together.begin(s); + runTo(s, at, p_store[0], 1, &.{ 0.4, 0.3, 0.3 }); + tg.next(s); + runTo(s, as, q_turn[0] + 2, 1, &.{ 0.4, 0.3, 0.3 }); + walk(s, as, q_check0, 0.5); + walk(s, as, q_check0 + 1, 0.9); + walk(s, as, q_check0 + 3, 0.5); + tg.done(s); + + // A5: i = 0, the stores: ASan's rows after the check, then both stores, plain first, and each side's i++. + says.line(s, "It is `00`: the store may go. Both write `'A'`;\nplain in one instruction, ASan in seventeen."); + const q_store0 = on(asan, q_check0, "mov byte ptr"); + walk(s, as, q_store0, 0.5); + tg = Together.begin(s); + walk(s, at, p_store[0] + 1, null); + tg.next(s); + s.wait(6.0 / 60.0); + walk(s, as, q_store0 + 1, null); + tg.done(s); + tg = Together.begin(s); + runTo(s, at, p_turn[1], 1, &.{ 0.3, 0.3, 0.36 }); + tg.next(s); + runTo(s, as, q_turn[1], 1, &.{ 0.3, 0.3, 0.36 }); + tg.done(s); + + // A6: i = 1 to 14 at a run, a turn a step on each side, ramping in and out. + says.line(s, "Fourteen more turns, at a run: `buf` fills on both sides."); + { + const start = s.cursor; + s.play(.{ at.veil.to(1), at.hurried.to(1), as.veil.to(1), as.hurried.to(1) }, .{ .seconds = t.veil }); + s.cursor = start; + const paces = [_]f32{ 0.6, 0.36, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.36, 0.6 }; + for (paces, 1..) |sec, i| { + tg = Together.begin(s); + run(s, at, p_turn[i + 1], sec); + tg.next(s); + run(s, as, q_turn[i + 1], sec); + tg.done(s); + } + s.play(.{ at.veil.to(0), at.hurried.to(0), as.veil.to(0), as.hurried.to(0) }, .{ .seconds = t.veil }); + s.wait(t.beat); + } + + // A7: i = 15: the rows to each side's store at a run, ASan's load walked (the last 00 read), both stores + // walked, plain first; then each side's i++ at a run, to the turn's first row. + says.line(s, "i = 15, `buf`'s last byte:\nstill `00` on ASan's side, still `buf` on plain's."); + const q_check15 = q_load(asan, q_turn[15]); + const q_store15 = on(asan, q_check15, "mov byte ptr"); + tg = Together.begin(s); + runTo(s, at, p_store[15], 2, &.{ 0.4, 0.4 }); + tg.next(s); + runTo(s, as, q_check15, 2, &.{ 0.4, 0.3, 0.3 }); + walk(s, as, q_check15 + 1, 1.0); + runTo(s, as, q_store15, 3, &.{0.3}); + tg.done(s); + tg = Together.begin(s); + walk(s, at, p_store[15] + 1, 1.4); + run(s, at, p_turn[16], 0.4); + tg.next(s); + s.wait(6.0 / 60.0); + walk(s, as, q_store15 + 1, 1.4); + run(s, as, q_turn[16], 0.4); + tg.done(s); + + // A8: i = 16, they part (the storyboard's chart): plain to its store at a run over the time ASan takes + // to reach its check; the two first different rows framed `attention`; plain's store into the saved + // rbp, its `differs` bar 12 f after; ASan's load reads f3, its compare, its `je` not taken. + says.line(s, "i = 16, one past `buf`: plain writes an A into the saved rbp;\nASan reads `f3`, a redzone."); + const q_check16 = q_load(asan, q_turn[16]); + tg = Together.begin(s); + runTo(s, at, p_store[16], 1, &.{ 0.4, 0.4, 0.4 }); + tg.next(s); + runTo(s, as, q_check16, 4, &.{ 0.6, 0.6 }); + tg.done(s); + s.play(.{attention.to(1)}, .{ .seconds = 6.0 / 60.0 }); + s.wait(6.0 / 60.0); + tg = Together.begin(s); + { + const plan = at.reading(p_store[16], p_store[16] + 1); + at.step(s, p_store[16] + 1, plan, plan.total); + const after = s.cursor; + s.cursor = tg.start + plan.at[1] + 12.0 / 60.0; + s.play(.{differs.to(1)}, .{ .seconds = t.quick }); + s.cursor = after; + } + tg.next(s); + s.wait(30.0 / 60.0); + for (q_check16..q_check16 + 3) |m| { + const plan = as.reading(m, m + 1); + as.step(s, m + 1, plan, plan.total * 0.75); + } + tg.done(s); + s.play(.{attention.to(0)}, .{ .seconds = t.quick }); + + // A9: ASan's partial check and its call walked; its run stops: its registers give way to its stderr. + says.line(s, "ASan does not store: it calls its report,\nwhich names `buf` and the write."); + // The partial check's compare and branch walked; the loads round them at a run. + runTo(s, as, q_check16 + 7, 1, &.{0.3}); + walk(s, as, q_check16 + 9, 0.9); + runTo(s, as, report_call, 1, &.{0.3}); + s.wait(t.beat); + s.play(.{regs_r.fadeOut()}, .{ .seconds = t.quick, .ease = anim.ease.linear }); + right.glide(s, pair.split(.right, true), 0.4); + s.play(.{stderr.fadeIn()}, .{ .seconds = t.quick, .ease = anim.ease.linear }); + s.play(.{framed.to(3)}, .{ .seconds = 18.0 / 60.0, .ease = anim.ease.linear }); + + // A10 to A13: plain goes on alone, a store a turn, into the saved rbp and then the return address, + // in the column: the caption leaves; ASan's side folds to one tag on the shelf; plain's panes glide left + // and its frame's bytes open to the column's height; each text level with the field the turn's letter lands in. + const Store = struct { + /// Turn `i`: its rows up to the store at a run, then the store walked. + fn turn(sf: *anim.Frame, c: canim.Cursor, store: u64) void { + turnIn(sf, c, store, 78.0 / 60.0); + } + /// The same, the store's step `seconds` long (the aim's glide or fray in it, its text read within the beat). + fn turnIn(sf: *anim.Frame, c: canim.Cursor, store: u64, seconds: f32) void { + run(sf, c, store, 18.0 / 60.0); + walk(sf, c, store + 1, seconds); + } + }; + s.wait(@max(says.read_by - s.cursor, 0)); + if (says.current) |caption| { + const out = s.cursor; + s.play(.{caption.fadeOut()}, .{ .seconds = t.caption_out, .ease = canim.ease.exit }); + s.cursor = out; + } + s.play(.{ dis_r.fadeOut(), stderr.fadeOut(), frame_r.fadeOut(), right_shows.to(0), differs.to(0), shelf_fold.to(1), dis_l.fadeOut(), desc_l.fadeIn() }, .{ .seconds = t.quick, .ease = anim.ease.linear }); + s.play(.{shelf_fold.to(2)}, .{ .seconds = 18.0 / 60.0, .ease = anim.ease.linear }); + col.beat(s, .{ .panes = &.{ .{ .source, 3 }, .{ .disasm, 18 }, .{ .stack, canim.column_rest } }, .say = "Plain goes on alone, an A a turn, into the saved rbp.", .level = .{ .row = rbp } }); + { + // `aim = .standing` for these four beats: once the bubble has arrived, the return + // address's field aims at the row it names (18 f), in the lead before the first store. + const fires = s.cursor; + s.cursor = fires - 0.7; + at.aim(s, .standing); + s.cursor = fires; + } + for (17..21) |i| Store.turn(s, at, p_store[i]); + col.beat(s, .{ .panes = &.{ .{ .source, 3 }, .{ .disasm, 18 }, .{ .stack, canim.column_rest } }, .say = "The saved rbp fills: `4141414141414141`, no longer an address.", .level = .{ .row = rbp } }); + for (21..24) |i| Store.turn(s, at, p_store[i]); + col.beat(s, .{ .panes = &.{ .{ .source, 3 }, .{ .disasm, 18 }, .{ .stack, canim.column_rest } }, .say = "i = 24, the return address: it reads `fill+1`, still code.", .level = .{ .row = rbp + 8 } }); + Store.turnIn(s, at, p_store[24], 132.0 / 60.0); + col.beat(s, .{ .panes = &.{ .{ .source, 3 }, .{ .disasm, 18 }, .{ .stack, canim.column_rest } }, .say = "Each turn makes it stranger: `404141` is data, `414141` is nowhere.", .level = .{ .row = rbp + 8 } }); + for (25..27) |i| Store.turnIn(s, at, p_store[i], 128.0 / 60.0); + // Back to the pair: the aim goes with the column; the texts leave together, plain's panes glide back to their side, ASan's unfolds from the shelf. + at.aim(s, .off); + col.beat(s, .{ .at = .below, .say = "" }); + s.play(.{ desc_l.fadeOut(), dis_l.fadeIn() }, .{ .seconds = t.quick, .ease = anim.ease.linear }); + s.play(.{shelf_fold.to(1)}, .{ .seconds = 18.0 / 60.0, .ease = anim.ease.linear }); + s.play(.{ dis_r.fadeIn(), stderr.fadeIn(), frame_r.fadeIn(), right_shows.to(1), differs.to(1), shelf_fold.to(0) }, .{ .seconds = t.quick, .ease = anim.ease.linear }); + says.read_by = 0; + + // A14: i = 27 walked, then the held rest (the poster: mock 38), ASan standing on its report. + says.line(s, "Half written: `41414141`, no longer an address.\nOn the right, ASan stopped at the first byte past `buf`."); + run(s, at, p_store[27], 18.0 / 60.0); + { + // Its hold runs on under its own text (4.9 s): the struck byte solid, the plaque on the store. + var plan = at.reading(p_store[27], p_store[27] + 1); + const held = 4.9; + plan.advance += held; + plan.total += held; + const start = s.cursor; + at.step(s, p_store[27] + 1, plan, plan.total); + const after = s.cursor; + // ASan's side, read meanwhile: the shadow byte its check stopped on, framed in its report. + s.cursor = start + plan.at[1] + 1.0; + s.play(.{framed.to(4)}, .{ .seconds = t.quick, .ease = anim.ease.linear }); + s.cursor = after; + } + + // A15: i = 28 to 31. + says.line(s, "Four more turns: the last A lands,\nand it reads `4141414141414141`."); + for (28..32) |i| Store.turn(s, at, p_store[i]); + + // A16: the loop's exit, pop rbp, ret, and the fault. + says.line(s, "The loop ends: `pop rbp`, then `ret` to `4141414141414141`:\nthe CPU faults. SIGSEGV."); + run(s, at, p_turn[32], 18.0 / 60.0); + runTo(s, at, p_pop, 1, &.{ 0.4, 0.4 }); + for (p_pop..p_end) |m| { + const plan = at.reading(m, m + 1); + at.step(s, m + 1, plan, if (m + 1 == p_end) plan.total else plan.total * 0.8); + } + says.close(s); +} diff --git a/anim/scenes/column.zig b/anim/scenes/column.zig index b1a8df7..db211a7 100644 --- a/anim/scenes/column.zig +++ b/anim/scenes/column.zig @@ -55,40 +55,40 @@ fn frame(s: *anim.Frame) void { // C2: the arguments, beside the rows that set them. col.beat(s, .{ .panes = &.{ .{ .source, 3 }, .{ .disasm, 11 }, .{ .registers, regs } }, - .say = "main puts open's arguments where the convention says: \"note\" in `rdi`, 0 (O_RDONLY) in `rsi`.", + .say = "main puts open's arguments in registers: \"note\" in `rdi`, O_RDONLY in `rsi`.", .notes = &.{ .{ .band, "none yet" }, .{ .view, "no call crossing" } }, }); cur.walk(s, .moment, stub - 1); // C3: the call goes down; the stack under the descent. col.beat(s, .{ .panes = &.{ .{ .source, 3 }, .{ .disasm, 11 }, .{ .stack, rest } }, - .say = "The call pushes where to come back to, `main+45`, and goes down to open's stub.", + .say = "The call pushes the way back, `main+45`, and goes down to the stub.", }); canim.descent.step(cur, s, .moment); s.wait(t.phrase_rest); // C4: the stub's jmp: the stack holds still. - col.beat(s, .{ .say = "The stub in the PLT is one jump: it reads `open@got`, where the loader wrote libc's `open`. It pushes nothing.", .panes = &.{ .{ .source, 3 }, .{ .disasm, 11 }, .{ .stack, rest } } }); + col.beat(s, .{ .say = "The stub is one jump through `open@got`: it pushes nothing.", .panes = &.{ .{ .source, 3 }, .{ .disasm, 11 }, .{ .stack, rest } } }); canim.descent.step(cur, s, .moment); s.wait(t.phrase_rest); // C5: the wrapper at a run, the bubble level with its window's head. col.beat(s, .{ - .panes = &.{ .{ .source, 3 }, .{ .disasm, 11 }, .{ .stack, rest } }, + .panes = &.{ .{ .source, 2 }, .{ .disasm, 11 }, .{ .stack, rest } }, .say = "libc's `open` is a wrapper: a few lines of C around the one instruction that calls the kernel.", .level = .{ .head = "open" }, }); cur.hurry(s, .moment, crossing - 3, .{}); // C6: its last three, beside the registers they set. col.beat(s, .{ - .panes = &.{ .{ .source, 3 }, .{ .disasm, 11 }, .{ .registers, regs } }, - .say = "Its last three set the kernel's arguments: AT_FDCWD in `rdi`, and 257, openat's number, in `rax`.", + .panes = &.{ .{ .source, 2 }, .{ .disasm, 11 }, .{ .registers, regs } }, + .say = "Its last three set the kernel's arguments, and openat's number, 257, in `rax`.", .stem = .none, - .notes = &.{ .{ .band, "none yet" }, .{ .view, "`\"note\"`" } }, + .notes = &.{ .{ .band, "none yet" }, .{ .view, "`\"note\"` handed in" }, .{ .stack, "open's frame, 16 words" } }, }); cur.walk(s, .moment, crossing); // C7: the crossing, the kernel at the descent's floor. col.beat(s, .{ .panes = &.{ .{ .source, 3 }, .{ .disasm, 24 } }, - .say = "`syscall` crosses down. The kernel opens \"note\" and answers 3: the file's descriptor, in `rax`.", + .say = "`syscall` crosses down; the kernel opens \"note\" and answers 3 in `rax`.", .level = .floor, .stem = .none, .notes = &.{ .{ .band, "none yet" }, .{ .view, "`\"note\"`" } }, diff --git a/anim/scenes/fib.zig b/anim/scenes/fib.zig index 5f958dd..983f2da 100644 --- a/anim/scenes/fib.zig +++ b/anim/scenes/fib.zig @@ -39,8 +39,8 @@ fn frame(s: *anim.Frame) void { const joins = ctx.ties(s); canim.establish(s, .{ ctx.clock, ctx.registers, ctx.stack, ctx.source, ctx.disasm, tree, joins }); says.line(s, "`fib` calls itself. A call is a frame on the stack and a node\nin the tree; its argument arrives in `rdi`."); - // The call, once, in full; and the two lines that lead to the next one. - at.walk(s, .line, rec.lineMoment(6, call(rec, 0).enter)); + // The call, once, in full, to its frame made; the lines after it run with the next caption's. + at.walk(s, .line, rec.lineMoment(4, call(rec, 0).enter)); s.wait(canim.theme.time.beat); // Pacing: the same three lines three times more. Seen once, so diff --git a/anim/scenes/heap.zig b/anim/scenes/heap.zig index 6e521d0..07eccea 100644 --- a/anim/scenes/heap.zig +++ b/anim/scenes/heap.zig @@ -176,7 +176,10 @@ const Lists = struct { const changed = counts[0] == null or !real[0] or counts[0].? != counts[1].?; const comes = !real[0] or counts[0] == null; const bv = v.faded(if (comes) after(now, 42, 6) else 1); - const heat = if (changed and now.walking()) now.heat(0, null, now.since(.idea, 0) - 60.0 / 60.0) else if (changed) canim.ui.Heat.ember else canim.ui.Heat.none; + // Changed in the step before: its mark leaves as any does (with a run's ease, or its embers' steps), never in a frame. + const before = if (heapAt(a, rec, now.stops[2])) |hp| holds(hp) else null; + const changed_before = now.stops[2] != now.stops[1] and real[0] and counts[0] != null and before != counts[0]; + const heat = if (changed and now.walking()) now.heat(0, null, now.since(.idea, 0) - 60.0 / 60.0) else if (changed) canim.ui.Heat.ember else if (changed_before) now.heat(1, null, std.math.inf(f32)) else canim.ui.Heat.none; bv.fill(badge, theme.color.page); const ink = bv.cellWritten(badge, heat, theme.color.page); // Framed, but while the strike's paper is on it. @@ -199,7 +202,15 @@ const Lists = struct { const sx = top_r.x + top_r.w - 16 - tv.width(.mono, theme.size.mono.context, size_text); tv.text(.mono, theme.size.mono.context, top_r.x + 16, theme.baseline(top_r.y, h, theme.size.mono.context), "top", t.dim); var ink: canim.ui.Ink = .{ .ink = ui.rgb(t.dim) }; - if (side == 1 and moved and tops[0] != null and now.walking()) ink = tv.cellWritten(.{ .x = sx - 4, .y = top_r.y + 10, .w = tv.width(.mono, theme.size.mono.context, size_text) + 8, .h = 24 }, now.heat(0, null, now.since(.idea, 0) - 12.0 / 60.0), null); + const cell: canim.Rect = .{ .x = sx - 4, .y = top_r.y + 10, .w = tv.width(.mono, theme.size.mono.context, size_text) + 8, .h = 24 }; + if (side == 1 and moved and tops[0] != null) ink = tv.cellWritten(cell, if (now.resting() and now.gaits[0] == .walk) canim.ui.Heat.ember else now.heat(0, null, now.since(.idea, 0) - 12.0 / 60.0), null) else if (side == 1 and !moved and now.stops[2] != now.stops[1] and now.gaits[1] == .walk) { + // Moved in the step before: its mark leaves as any does, never in a frame. + const old = heapAt(a, rec, now.stops[2]); + const was = if (old) |hp| (if (hp.chunks.len > 0) hp.chunks[hp.chunks.len - 1] else null) else null; + if (was) |top_was| if (top_was.addr != top.addr or top_was.size() != top.size()) { + ink = tv.cellWritten(cell, now.heat(1, null, std.math.inf(f32)), null); + }; + } tv.text(ink.face, theme.size.mono.context, sx, theme.baseline(top_r.y, h, theme.size.mono.context), size_text, ink.ink); _ = tv.address(top_r.x + 16, top_r.y - 8, top.addr, .{ .ink = ui.rgb(theme.color.region.heap) }); }; diff --git a/anim/scenes/intro_code.zig b/anim/scenes/intro_code.zig new file mode 100644 index 0000000..a5660ed --- /dev/null +++ b/anim/scenes/intro_code.zig @@ -0,0 +1,110 @@ +//! The introduction, chapter III: code and meaning (design/motion.md, "A +//! scene: the introduction", III1 to III5; mocks 32, 33, 36). On the +//! `list` recording at the load in `reverse` (line 21, `node *next = +//! cur->next;`, the instruction that reads `cur->next`): the code's bytes +//! as a dump row, that instruction's four framed; `decode`d into its row +//! of `aligned` (`interleaved`), its neighbours at a run, each line level +//! with its run; then `align` to `columns`; then the working frame with the +//! nodes drawn from the heap's bytes; then the map (`surface`). The texts +//! `above` the aligned panel, then below the working frame. +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 t = canim.theme.time; + +fn f(frames: f32) f32 { + return frames / 60; +} + +fn run(s: *anim.Frame, v: anim.Value, frames: f32) void { + s.play(.{v.to(0)}, .{ .seconds = 0 }); + s.play(.{v.to(frames)}, .{ .seconds = f(frames), .ease = anim.ease.linear }); +} + +fn on(rec: *canim.Recording, from: u64, text: []const u8) u64 { + var buf: [256]u8 = undefined; + var i = from; + while (i < rec.end()) : (i += 1) if (rec.instruction(i, rec.register(i, "rip"), &buf)) |here| if (std.mem.indexOf(u8, here.text, text) != null) return i; + return from; +} + +/// The variables whose tags the nodes carry, as the list scene's. +const tracked = [_][]const u8{ "prev", "cur", "next", "head" }; + +fn frame(s: *anim.Frame) void { + const rec = canim.open(recordings.list); + const reverse = rec.call("reverse", 0); + // The load: `cur->next` read, line 21's second instruction. + const moment = on(rec, rec.lineMoment(21, reverse.enter), "[rax + 8]"); + const pc = rec.register(moment, "rip"); + var buf: [256]u8 = undefined; + const insn = rec.instruction(moment, pc, &buf).?; + // Its bytes and its text as canim writes it (the size word dropped), from the recording. + var code: [16]u8 = undefined; + var known: [16]bool = undefined; + rec.moment(moment).read(pc, code[0..insn.len], known[0..insn.len]) catch {}; + var hex: std.ArrayList(u8) = .empty; + for (code[0..insn.len], 0..) |b, k| hex.print(s.arena, "{s}{x:0>2}", .{ if (k > 0) " " else "", b }) catch {}; + const text = std.mem.replaceOwned(u8, s.arena, insn.text, "qword ptr ", "") catch insn.text; + + var at = canim.cursor(s, rec, moment); + at.journey(.moment, moment + 1); + at.levels = .{ .idea = .data, .follow = t.move, .source_rows = 8 }; + const ctx = canim.context(s, at, .{ .split = canim.layout.split.subject }); + const list = canim.nodes(s, .{ .cursor = at, .stage = ctx.stage, .root = "head", .track = &tracked }); + ctx.map.add(s, canim.Nodes{ .cursor = at, .stage = ctx.map.stage, .root = "head", .track = &tracked }); + const joins = ctx.ties(s); + + const al = s.new(canim.Aligned.init(s, rec, moment)); + const panel = s.custom(al, .{ .x = -640, .y = -360, .scale = canim.ui.scale }); + s.play(.{panel.fadeIn()}, .{ .seconds = 0 }); + var asides: canim.Asides = .{}; + const left = canim.theme.canvas.margin_x; + const above = canim.theme.canvas.stage.y + 40; + + // III1: the code's bytes, one instruction's framed. + s.wait(1.0); + asides.say(s, std.fmt.allocPrint(s.arena, "Code is bytes too: `{s}` is one instruction.", .{hex.items}) catch "", left, above); + s.wait(t.caption_lead); + run(s, al.bytes, 12 + 2 * 15 + 12 + 6); + s.wait(t.beat); + + // III2: decoded into its row, its neighbours at a run, each line level with its run. + asides.say(s, std.fmt.allocPrint(s.arena, "Decoded: `{s}`, from line {d}. Each line sits level with its code.", .{ text, insn.line orelse 0 }) catch "", left, above); + run(s, al.decode, 60); + run(s, al.rows_in, 2 * 32 + 8); + run(s, al.chrome, 24); + s.wait(t.beat); + + // III2, the other form: two columns, each line level with the first of its instructions. + asides.say(s, "Two columns: each line level with its first instruction.", left, above); + run(s, al.form, 72); + s.wait(t.beat); + + // Into the working frame: the texts above leave, the panel goes, the frame comes in. + asides.leave(s); + s.play(.{panel.fadeOut()}, .{ .seconds = f(12), .ease = anim.ease.linear }); + var says: canim.Narrator = .{}; + var cam: canim.Camera = .{}; + canim.establish(s, .{ ctx.clock, ctx.registers, ctx.stack, ctx.source, ctx.disasm, joins }); + // III3: the node it reads, as bytes and drawn: the band comes in, its + // elements rising from their bytes, and the camera nearer on it (x1.5). + says.line(s, "`rax` points at a list node on the heap:\nits bytes, and drawn, the node."); + ctx.establish(s, .{list}, 3); + cam.go(s, .{ .x = 512, .y = 48, .w = 896, .h = 296 }, 1.5, .{}); + s.wait(t.beat); + // III4: the whole frame: the camera back to x1. + says.line(s, "This is the whole frame.\nEvery view in it is these same bytes."); + cam.back(s, .{}); + s.wait(t.beat); + // III5: the map. + says.line(s, "And all of it at once: the map."); + ctx.map.surface(s); + says.close(s); + cam.apply(s); +} diff --git a/anim/scenes/intro_memory.zig b/anim/scenes/intro_memory.zig new file mode 100644 index 0000000..07e694a --- /dev/null +++ b/anim/scenes/intro_memory.zig @@ -0,0 +1,186 @@ +//! The introduction, chapter I: memory (design/motion.md, "A scene: the +//! introduction", I1 to I10; mocks 29, 30, 34, 37). The frame built from +//! its bytes up, on the `list` recording stopped in `reverse`'s prologue, +//! at its first call (line 17: the push chapter II walks; the 128 bytes at +//! rsp then are the load's but for `prev`, not yet stored), each part in +//! the place it keeps: the 128 bytes at the top +//! of the stack where the stack panel will stand, under the camera at x2; +//! made words (`regroup`); three of them addresses; then the address space +//! to scale in the program column (`segments`), each cluster enlarged, its +//! text beside it; back to the working frame, the dump tied to its place, +//! a visit at x4, `ink`, and three chains. +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 t = canim.theme.time; + +fn f(frames: f32) f32 { + return frames / 60; +} + +/// Clock `v` from 0 to `frames`, linear, from the cursor; the cursor after it. +fn run(s: *anim.Frame, v: anim.Value, frames: f32) void { + s.play(.{v.to(0)}, .{ .seconds = 0 }); + s.play(.{v.to(frames)}, .{ .seconds = f(frames), .ease = anim.ease.linear }); +} + +/// The same, the cursor left where it was. +fn start(s: *anim.Frame, v: anim.Value, frames: f32) void { + const at = s.cursor; + run(s, v, frames); + s.cursor = at; +} + +/// The first moment from `from` whose instruction reads `text`. +fn on(rec: *canim.Recording, from: u64, text: []const u8) u64 { + var buf: [256]u8 = undefined; + var i = from; + while (i < rec.end()) : (i += 1) if (rec.instruction(i, rec.register(i, "rip"), &buf)) |here| if (std.mem.indexOf(u8, here.text, text) != null) return i; + return from; +} + +fn frame(s: *anim.Frame) void { + const rec = canim.open(recordings.list); + const reverse = rec.call("reverse", 0); + // reverse's first call (line 17, the tracer's `__zt_var` for its first + // local): the push chapter II walks. The recording begins after + // reverse's own `push rbp` (`--from` breaks past the prologue), so it is + // the first push of reverse's that the recording has. + const moment = on(rec, reverse.enter, "call"); + const ui = canim.ui; + const at = canim.regroup.at; + + const space = s.new(canim.Segments.init(s, rec, moment)); + const dump = s.new(canim.Words.init(s, rec, moment)); + const place = s.new(canim.segments.Place{ .segments = space, .addr = rec.register(moment, "rsp"), .x = at.bracket, .y0 = at.top + 2, .y1 = at.top + 16 * 24 - 2, .clock = s.value(-1), .quiet = s.value(0) }); + + // `ink`'s echoes: the walked word's band first, then the rest at a run, 2 f apart. + const values = canim.Words.read(rec, moment); + var order: [canim.regroup.words]usize = undefined; + order[0] = dump.walked; + var n_order: usize = 1; + for (0..canim.regroup.words) |i| if (i != dump.walked) { + order[n_order] = i; + n_order += 1; + }; + for (order, 0..) |i, k| { + space.echoes[k] = .{ .addr = values.words[i], .shows = s.value(0) }; + } + space.n_echoes = order.len; + + const objs = .{ s.custom(space, .{ .x = -640, .y = -360, .scale = ui.scale }), s.custom(dump, .{ .x = -640, .y = -360, .scale = ui.scale }), s.custom(place, .{ .x = -640, .y = -360, .scale = ui.scale }) }; + inline for (objs) |o| s.play(.{o.fadeIn()}, .{ .seconds = 0 }); + + // The camera at x2 on the dump from the first frame (I1 to I3). + const near = ui.framing(.{ .x = 888, .y = 72, .w = 896, .h = 408 }, 2); + var cam: canim.Camera = .{}; + cam.moves[0] = .{ .from = near, .to = near, .p = s.value(1) }; + cam.count = 1; + cam.at = near; + var says: canim.Narrator = .{}; + var asides: canim.Asides = .{}; + + // I1: the bytes, a row at a time. + s.wait(1.0); + says.line(s, "A running program is bytes in memory:\nhere, 128 of them at the top of the stack."); + run(s, dump.in, 7 * 12 + 18); + s.wait(t.beat); + + // I2: eight a row; the return address walked, the other fifteen at a run. + says.line(s, "Eight bytes make a word, stored low byte first:\nthe lowest byte is its last two digits."); + run(s, dump.regroup, 386); + s.wait(t.beat); + + // I3: three words that hold addresses, framed as read. + says.line(s, "Some words are addresses:\nthey name a place in memory."); + run(s, dump.framed, 66); + s.wait(@max(says.read_by - s.cursor, 0)); + + // Into the column: the caption leaves, the camera out to x1, the dump to its tag on the shelf. + s.play(.{says.current.?.fadeOut()}, .{ .seconds = t.caption_out, .ease = canim.ease.exit }); + says.current = canim.caption(s, ""); + s.wait(t.caption_gap); + cam.back(s, .{}); + run(s, dump.fold, 30); + // Folded, the three frames go with the rows: unfolded, the dump is plain words again. + s.play(.{dump.framed.to(-1)}, .{ .seconds = 0 }); + + // I4: the whole, deliberately. + const column_x = canim.theme.layout.state.x + 8; + const l = space.layout(0, s.arena); + asides.say(s, "Its address space, 128 TiB, to scale: mapped only at each end.", column_x, (l.top + l.foot) / 2); + run(s, space.whole, 72 + 18 + 72); + s.wait(t.beat); + + // I5: the top end, a box a cluster, each riding out as the one before lands. + const clusters = @min(l.space.clusters.len, 6); + var top_end: usize = 0; + while (top_end < clusters and l.space.clusters[top_end].lo > canim.segments.user_end / 2) top_end += 1; + asides.say(s, "Enlarged, the top end: the stack, the libraries and the tracer's ring, each band with its addresses and size.", column_x, l.boxes[0].y + 12); + for (0..top_end) |i| { + start(s, space.rides[i], 6 + 72 + 90 + 2 * 12 + 12); + s.wait(f(78)); + } + s.wait(f(90 + 2 * 12 + 12)); + // I6: the foot, the program by segment. + for (top_end..clusters) |i| { + asides.say(s, "At the foot, the program: its code, its data, its heap.", column_x, l.boxes[i].y + l.boxes[i].h / 2); + run(s, space.rides[i], 6 + 72 + 90 + 2 * 12 + 12); + } + s.wait(t.beat); + + // Back to the working frame: the texts leave, the drawing to the stage's height, the dump unfolds. + asides.leave(s); + s.play(.{space.form.to(1)}, .{ .seconds = f(24), .ease = anim.ease.linear }); + s.play(.{dump.fold.to(0)}, .{ .seconds = f(30), .ease = anim.ease.linear }); + + // I7: the dump's place: the tie bracket, the link onto the stack's box. + says.line(s, "These 128 bytes are here,\nat the very top of the stack."); + s.play(.{dump.placed.to(1)}, .{ .seconds = f(12), .ease = anim.ease.linear }); + s.cursor -= f(12); + run(s, place.clock, 60); + s.wait(t.beat); + + // I8: a visit at x4 to where the link lands, and back. + says.line(s, "Were the bar the Eiffel Tower,\nthey would be an atom thick, at its top."); + const landed = space.layout(1, s.arena); + const head = canim.Segments.place(landed, place.addr) orelse .{ 0, 0 }; + cam.go(s, .{ .x = head[0] - 112, .y = 48, .w = 224, .h = 104 }, 4, .{}); + s.wait(t.beat); + cam.back(s, .{}); + + // I9: `ink`: the return address walked, its band framed; the rest at a run; the link quiets. + const walked = values.words[dump.walked]; + const band = for (landed.space.bands) |b| { + if (walked >= b.lo and walked < b.hi) break b; + } else landed.space.bands[0]; + says.line(s, std.fmt.allocPrint(s.arena, "A word takes the ink of where it points:\n`{x}` is {s}'s code.", .{ walked, band.name }) catch ""); + const inking = s.cursor; + start(s, place.quiet, 24); + for (order[1..], 1..) |_, k| { + s.cursor = inking + f(@floatFromInt(72 + 2 * (k - 1))); + s.play(.{space.echoes[k].shows.to(1)}, .{ .seconds = f(4), .ease = anim.ease.linear }); + s.play(.{space.echoes[k].shows.to(0)}, .{ .seconds = f(8), .ease = anim.ease.linear }); + } + s.cursor = inking; + s.play(.{space.echoes[0].shows.to(1)}, .{ .seconds = f(6), .ease = anim.ease.linear }); + s.cursor = inking + f(72 + 2 * 16 + 12); + s.play(.{space.echoes[0].shows.to(0)}, .{ .seconds = f(18), .ease = anim.ease.linear }); + s.cursor = inking; + run(s, dump.ink, 72 + 2 * 16 + 12 + 18); + s.wait(t.beat); + + // I10: the words to their field's left, then three chains, walked. + says.line(s, "Follow an address and you reach another word:\na chain."); + run(s, dump.left, 24); + run(s, dump.chains, 36 * 2 + 30); + s.wait(t.beat); + // The chapter's last picture. + says.close(s); + cam.apply(s); +} diff --git a/anim/scenes/intro_stack.zig b/anim/scenes/intro_stack.zig new file mode 100644 index 0000000..e504ffc --- /dev/null +++ b/anim/scenes/intro_stack.zig @@ -0,0 +1,193 @@ +//! The introduction, chapter II: the stack (design/motion.md, "A scene: the +//! introduction", II1 to II4; mock 31). It opens on chapter I's last +//! picture, at the same moment of the `list` recording (reverse's first +//! call, line 17): the address space and the dump's link fade, the words +//! glide into the stack panel's rows where it stands in the working frame +//! and become it; a push walked from the recording (that call's: the +//! address to come back to, rsp's pin climbing onto it); the return +//! address main left, and the offsets; rbp's pin and the panel's tag last; +//! then the registers built over it a row at a time, their tag last. The +//! text stands beside on the left, in the program column, empty until +//! chapter III. +//! +//! What a beat has not reached yet is under the page (`Cover`), lifted as +//! the beat says it: the context's panels draw every column at once. +const std = @import("std"); +const anim = @import("anim"); +const sk = @import("sketch"); +const canim = @import("canim"); +const recordings = @import("recordings"); + +pub const background = canim.background; +pub const scene = anim.Live(frame, struct {}); + +const t = canim.theme.time; +const row = canim.theme.metric.context.row; +const tag = canim.theme.metric.context.tag; +const pad = canim.theme.metric.context.pad; + +fn f(frames: f32) f32 { + return frames / 60; +} + +fn place(s: *anim.Frame, data: anytype) anim.Obj { + return s.custom(data, .{ .x = -640, .y = -360, .scale = canim.ui.scale }); +} + +/// The page over a part of a panel the beat has not reached: lifted (its fade out) as the beat says it. +const Cover = struct { + box: canim.Rect, + pub fn draw(c: *const Cover, fr: *sk.Frame, placed: anim.Placed) void { + (canim.ui.Ui{ .f = fr, .at = placed }).fill(c.box, canim.theme.color.page); + } +}; + +/// A value framed as read (6 f in with its object's fade). +const Read = struct { + box: canim.Rect, + pub fn draw(r: *const Read, fr: *sk.Frame, placed: anim.Placed) void { + (canim.ui.Ui{ .f = fr, .at = placed }).read(r.box, 1); + } +}; + +fn cover(s: *anim.Frame, box: canim.Rect) anim.Obj { + const o = place(s, s.new(Cover{ .box = box })); + s.play(.{o.fadeIn()}, .{ .seconds = 0 }); + return o; +} + +/// A panel's tag and rules under the page, for `frame up`. +fn chrome(s: *anim.Frame, b: canim.Rect, strip: bool) [5]?anim.Obj { + const w = canim.theme.stroke.rule; + return .{ + cover(s, .{ .x = b.x, .y = b.y, .w = b.w, .h = tag }), + cover(s, .{ .x = b.x, .y = b.y + tag, .w = w, .h = b.h - tag }), + cover(s, .{ .x = b.x + b.w - w, .y = b.y + tag, .w = w, .h = b.h - tag }), + cover(s, .{ .x = b.x, .y = b.y + b.h - w, .w = b.w, .h = w }), + if (strip) cover(s, .{ .x = b.x + b.w - canim.theme.strip.cost, .y = b.y + tag, .w = canim.theme.strip.cost - w, .h = b.h - tag - w }) else null, + }; +} + +/// Lifts `covers` one after another, `apart` frames apart, `each` frames each, from the cursor; the cursor after the last. +fn lift(s: *anim.Frame, covers: []const ?anim.Obj, apart: f32, each: f32) void { + const at = s.cursor; + var end = at; + for (covers, 0..) |o, i| if (o) |obj| { + s.cursor = at + f(apart * @as(f32, @floatFromInt(i))); + s.play(.{obj.fadeOut()}, .{ .seconds = f(each), .ease = anim.ease.linear }); + end = s.cursor; + }; + s.cursor = end; +} + +fn on(rec: *canim.Recording, from: u64, text: []const u8) u64 { + var buf: [256]u8 = undefined; + var i = from; + while (i < rec.end()) : (i += 1) if (rec.instruction(i, rec.register(i, "rip"), &buf)) |here| if (std.mem.indexOf(u8, here.text, text) != null) return i; + return from; +} + +/// A value at once, from the cursor. +fn set(s: *anim.Frame, v: anim.Value, to: f32) void { + s.play(.{v.to(to)}, .{ .seconds = 0 }); +} + +fn frame(s: *anim.Frame) void { + const rec = canim.open(recordings.list); + const reverse = rec.call("reverse", 0); + // Chapter I's moment: reverse's first call, whose push is walked here. + const moment = on(rec, reverse.enter, "call"); + var at = canim.cursor(s, rec, moment); + at.journey(.moment, moment + 1); + at.levels = .{ .fire = .disasm, .source_rows = 14 }; + // The working frame with no backtrace: the stack goes to the stage's foot under the registers. + var split = canim.layout.split.none; + split.backtrace.h = 0; + const ctx = canim.context(s, at, .{ .split = split }); + const sb = ctx.stage.first.stack; + const rb = ctx.stage.first.registers; + const rsp = rec.register(moment, "rsp"); + const rsp_after = rec.register(moment + 1, "rsp"); + // The window has two `free` words over rsp; rows from the panel's tag and padding. + const first = rsp - 16; + const top = sb.y + tag + pad; + const slots = canim.layout.rowsIn(sb.h); + const rowY = struct { + fn y(t0: f32, from: u64, addr: u64) f32 { + return t0 + row * @as(f32, @floatFromInt((addr - from) / 8)); + } + }.y; + + // What has not been said yet, under the page: the stack's offsets, the + // pins' lane under rsp's row, its tag, rules and strip; the registers' rows, tag and rules. + var offsets: [32]?anim.Obj = @splat(null); + var lane: [32]?anim.Obj = @splat(null); + const rsp_row = (rsp - first) / 8; + for (0..@min(slots, 32)) |k| { + const y = top + row * @as(f32, @floatFromInt(k)); + offsets[k] = cover(s, .{ .x = sb.x + 92, .y = y, .w = 84, .h = row }); + if (k > rsp_row) lane[k] = cover(s, .{ .x = sb.x + 2, .y = y, .w = 88, .h = row }); + } + const stack_chrome = chrome(s, sb, true); + var regs_rows: [16]?anim.Obj = @splat(null); + for (0..@min(canim.layout.rowsIn(rb.h), 16)) |k| + regs_rows[k] = cover(s, .{ .x = rb.x + 2, .y = rb.y + tag + pad + row * @as(f32, @floatFromInt(k)), .w = rb.w - 4, .h = row }); + const regs_chrome = chrome(s, rb, false); + + // Chapter I's last picture: the address space, the words with their chains, the link standing. + const space = s.new(canim.Segments.init(s, rec, moment)); + const dump = s.new(canim.Words.init(s, rec, moment)); + dump.panel = .{ .x = sb.x, .top = top, .first = first }; + const at_ = canim.regroup.at; + const tie = s.new(canim.segments.Place{ .segments = space, .addr = rsp, .x = at_.bracket, .y0 = at_.top + 2, .y1 = at_.top + 16 * 24 - 2, .clock = s.value(60), .quiet = s.value(24) }); + for ([_]anim.Value{ space.form, dump.placed }) |v| set(s, v, 1); + set(s, space.whole, 999); + for (space.rides) |v| set(s, v, 999); + for ([_]anim.Value{ dump.in, dump.ink, dump.chains }) |v| set(s, v, 999); + set(s, dump.regroup, 386); + set(s, dump.left, 24); + const objs = .{ place(s, space), place(s, dump), place(s, tie) }; + inline for (objs) |o| s.play(.{o.fadeIn()}, .{ .seconds = 0 }); + const main_word: canim.Rect = .{ .x = sb.x + canim.theme.metric.slot.address + 12 * 12 + canim.theme.metric.context.arrow_w, .y = rowY(top, rsp_after - 16, rsp + 8 * dump.walked), .w = 6 * 12, .h = row }; + const framed = place(s, s.new(Read{ .box = main_word })); + var asides: canim.Asides = .{}; + const left = canim.theme.canvas.margin_x; + + // II1: the address space and the link fade (18 f); the words glide into + // the stack's rows (36 f) and become the panel (12 f); then the push. + s.wait(t.beat); + s.play(.{ objs[0].fadeOut(), objs[2].fadeOut() }, .{ .seconds = f(18), .ease = anim.ease.linear }); + s.play(.{dump.become.to(1)}, .{ .seconds = f(36), .ease = anim.ease.linear }); + s.play(.{ ctx.stack.fadeIn(), objs[1].fadeOut() }, .{ .seconds = f(12), .ease = anim.ease.linear }); + asides.say(s, "`rsp` holds the address of the stack's top; a push moves it down a word.", left, rowY(top, first, rsp) + row / 2); + at.walk(s, .moment, moment + 1); + s.wait(t.beat); + + // II2: the address the call pushed, and main's under it; the offsets, a column. + asides.say(s, "Each call pushes where to come back to: `main+50` is main's.", left, main_word.y + row / 2); + s.play(.{framed.fadeIn()}, .{ .seconds = f(6), .ease = anim.ease.linear }); + s.wait(f(24)); + lift(s, &offsets, 2, 12); + s.wait(t.beat); + + // II3: a function's frame: rbp's pin, and the panel's tag, last. + asides.say(s, "A function's words are its frame: saved rbp, locals, the way back.", left, rowY(top, rsp_after - 16, rec.register(moment + 1, "rbp")) + row / 2); + s.play(.{framed.fadeOut()}, .{ .seconds = f(18), .ease = anim.ease.linear }); + s.cursor -= f(18); + lift(s, &lane, 2, 12); + s.wait(t.beat); + // `frame up`: its rules (12 f), then its tag and strip (12 f). + lift(s, stack_chrome[1..4], 0, 12); + lift(s, &.{ stack_chrome[0], stack_chrome[4] }, 0, 12); + s.wait(t.beat); + + // II4: the registers built over the stack, a row at a time, their tag last. + asides.say(s, "The registers are the other place values live: seventeen of them.", left, rb.y + tag + pad + row * 2.5); + s.play(.{ctx.registers.fadeIn()}, .{ .seconds = 0 }); + lift(s, ®s_rows, 12, 12); + lift(s, regs_chrome[1..4], 0, 12); + lift(s, &.{regs_chrome[0]}, 0, 12); + // The chapter's last picture. + s.wait(@max(asides.read_by - s.cursor, 0)); + s.wait(t.before_cut); +} diff --git a/anim/scenes/list.zig b/anim/scenes/list.zig index d3d53ed..6a51d45 100644 --- a/anim/scenes/list.zig +++ b/anim/scenes/list.zig @@ -76,7 +76,8 @@ fn frame(s: *anim.Frame) void { says.line(s, "`cur->next` takes `prev`, NULL:\nthe first node is now the end of the list."); at.walk(s, .line, rec.lineMoment(23, loaded)); says.line(s, "Then `prev` and `cur` each step one node along,\nand the loop comes round to the second node."); - at.walk(s, .line, second_trip); + // To the loop's test: the test passing runs with the second trip (a caption is up 12 s at most). + at.walk(s, .line, rec.lineMoment(20, rec.lineMoment(24, first_trip))); // Pacing: the second trip is the same, so hurried; it keeps its rest. says.line(s, "The second node, the same way, faster:\nits `next` turns back to the first."); const third_trip = rec.lineMoment(21, rec.lineMoment(24, second_trip)); @@ -85,7 +86,9 @@ fn frame(s: *anim.Frame) void { says.line(s, "The last node: its `next` turns too,\nback to the node before it."); at.walk(s, .line, rec.lineMoment(23, third_trip)); says.line(s, "`prev` takes the last node, and `cur` runs off the end\nof the list: NULL, so the loop ends."); - at.walk(s, .line, rec.lineMoment(26, third_trip)); + at.walk(s, .line, rec.lineMoment(20, rec.lineMoment(24, third_trip))); + // The test failing, said faster (a caption is up 12 s at most). + at.hurry(s, .line, rec.lineMoment(26, third_trip), .{ .veil = false }); says.line(s, "`head` takes the last node: the same three nodes,\nin the same places, read the other way."); at.walk(s, .line, end); says.close(s); diff --git a/anim/scenes/musl.zig b/anim/scenes/musl.zig index 3112a27..87c4fe5 100644 --- a/anim/scenes/musl.zig +++ b/anim/scenes/musl.zig @@ -51,10 +51,11 @@ fn frame(s: *anim.Frame) void { const joins = ctx.ties(s); canim.establish(s, .{ ctx.clock, ctx.registers, ctx.stack, ctx.source, ctx.disasm, log, joins }); + // What the captions do not name runs: main's prologue and the call's arguments (the syscalls scene walks them). says.line(s, "The same `hello`, built by Zig against musl, static."); - cur.walk(s, .line, rec.lineMoment(6, main.enter)); + cur.hurry(s, .line, rec.lineMoment(6, main.enter), .{}); says.line(s, "`main` calls `open` itself: no PLT stub, no GOT.\nmusl is compiled from its source with the program."); - cur.walk(s, .moment, call_open); + cur.hurry(s, .moment, call_open, .{}); canim.descent.step(cur, s, .moment); s.wait(t.phrase_rest); says.line(s, "musl's `open` is open.c: the source follows it."); @@ -64,8 +65,9 @@ fn frame(s: *anim.Frame) void { canim.descent.step(cur, s, .moment); s.wait(t.phrase_rest); says.line(s, "Which jumps on to `__syscall_cp_c`, in the same file."); - // __syscall_cp's few rows, and its jump on. - while (cur.moment(s) <= jump) canim.descent.step(cur, s, .moment); + // __syscall_cp's few rows at a run (its frame made and unmade), and its jump on walked. + cur.hurry(s, .moment, jump, .{}); + canim.descent.step(cur, s, .moment); s.wait(t.phrase_rest); says.line(s, "The `syscall` is one line of C, in syscall_arch.h:\nrax holds 2, open's number, and rdi the path."); cur.hurry(s, .moment, crossing - 2, .{}); diff --git a/anim/scenes/sort.zig b/anim/scenes/sort.zig index 454c3ad..38c2a7f 100644 --- a/anim/scenes/sort.zig +++ b/anim/scenes/sort.zig @@ -73,9 +73,11 @@ fn frame(s: *anim.Frame) void { at.hurry(s, .over, last_trip, .{ .pace = t.sprint, .from = t.run }); ctx.map.dive(s); - says.line(s, "The last value, 20: 26 > 20, so `jne` takes the swap."); + // Two captions: one would be up over 12 s across the three blocks. + says.line(s, "The last value, 20: `j > 0`, and 26 > 20,"); block(at, s); block(at, s); + says.line(s, "so `jne` takes the swap."); block(at, s); says.line(s, "The swap, and the inner loop turns once more."); block(at, s); diff --git a/anim/scenes/zoom.zig b/anim/scenes/zoom.zig index 8164b3b..42ef60d 100644 --- a/anim/scenes/zoom.zig +++ b/anim/scenes/zoom.zig @@ -55,6 +55,9 @@ fn frame(s: *anim.Frame) void { at.walk(s, .moment, call.enter); // The frame built under them, under a caption of its own (12 s at most). says.line(s, "The new frame saves `rbp` under them,\nthen stores its own `n`."); + // `push rbp` and the store walked; `mov rbp, rsp` and `sub rsp`, which it does not name, said faster. + at.walk(s, .moment, call.enter + 1); + at.hurry(s, .moment, call.enter + 3, .{ .veil = false }); at.walk(s, .moment, call.enter + 4); s.wait(canim.theme.time.beat); ctx.stage.releaseStack(s); diff --git a/anim/src/Recording.zig b/anim/src/Recording.zig index 359305c..4bc9c1b 100644 --- a/anim/src/Recording.zig +++ b/anim/src/Recording.zig @@ -288,7 +288,9 @@ pub fn sourced(r: *const Recording, i: u64) bool { /// for every line of that third, so that the text moves only when the /// program has moved on. pub fn viewFirst(fit: u32, lines: u32, line: u32) u32 { - if (lines <= fit or fit < 3) return 1; + if (lines <= fit or fit == 0) return 1; + // One or two lines (a column's pane): the line itself, first. + if (fit < 3) return std.math.clamp(line, 1, lines - fit + 1); const third = fit / 3; const band = (@max(line, 1) - 1) / third; return std.math.clamp(@as(u32, @intCast(@max(@as(i64, band) - 1, 0))) * third + 1, 1, lines - fit + 1); diff --git a/anim/src/aligned.zig b/anim/src/aligned.zig new file mode 100644 index 0000000..a7c225d --- /dev/null +++ b/anim/src/aligned.zig @@ -0,0 +1,325 @@ +//! `aligned` (design/README.md, "aligned"; mocks 32, 33, 36): the source +//! with the instructions it compiled to, one panel across both columns, +//! each line level with its code; and the introduction's way into it +//! (motion.md, chapter III): the code's bytes as a dump row, one +//! instruction's bytes framed and `decode`d into its row, the rest at a +//! run, then `align` from one form to the other. Clocks the scene plays +//! (frames, linear): `bytes`, `decode`, `rows_in`, `chrome`, `form`. +//! +//! The rows: the pc's function from the first run of the line before the +//! pc's to the function's end, as the recording disassembled it at its +//! moment, each instruction's bytes as the recording read them. +//! +//! - `interleaved` (form 0), as `objdump -S` prints it: each run of a +//! line's instructions a group, its head the line on `raised` paper, its +//! rows under it; lines and addresses ranged right at 132 in one column; +//! a line's second run `again: its second run`, faint. +//! - `columns` (form 1): the source left, a 2-unit `rule` the seam 48 +//! after the longest line, the instructions right; a line level with the +//! first row of its run; a line with no code of its own in source order +//! after the line before it, faint, `no code of their own`. +//! +//! `align` between them (6. Verbs): the addresses and instructions glide +//! right into the instruction column (24 f, the bytes going), then every +//! row glides to its height (36 f: the verb's 24 read too quick for rows +//! crossing a column), then the lines with no code fade in (12 f). +const std = @import("std"); +const sk = @import("sketch"); +const anim = @import("anim"); +const ui = @import("ui.zig"); +const disasm = @import("disasm.zig"); +const Recording = @import("Recording.zig"); +const theme = ui.theme; +const Rect = ui.Rect; +const t = theme.color.text; + +const size = theme.size.mono.context; +const adv = ui.advance(size); +const pitch = theme.metric.context.row; +const tag = theme.metric.context.tag; +const pad = theme.metric.context.pad; + +/// The columns, from the panel's left (mock 33, 36). +const col = struct { + const place_end = 132; + const text = 156; + const bytes = 180; + const mnemonic = 360; + const seam_after = 48; + const instr = 156; +}; + +/// The dump row's first byte (`bytes`: at 132 at least). +const dump_first = theme.metric.bytes.first; + +fn clamp01(x: f32) f32 { + return std.math.clamp(x, 0, 1); +} + +fn glide(x: f32) f32 { + return theme.ease(.glide, clamp01(x)); +} + +const Row = struct { + kind: enum { head, insn, bare_line }, + line: u32, + insn: ?disasm.Insn = null, + again: bool = false, + /// The first row of its run (columns: where its line stands). + first: bool = false, + /// Its place in each form, in rows. + at: [2]f32 = .{ 0, 0 }, +}; + +pub const Aligned = struct { + rec: *const Recording, + at: u64, + /// Under a text `above` of two lines (48 to 182). + box: Rect = .{ .x = theme.canvas.margin_x, .y = 192, .w = theme.canvas.stage.w, .h = 696 }, + /// Where the dump row of the code's bytes stands (III1). + dump_y: f32 = 192 + tag + pad, + bytes: anim.Value, + decode: anim.Value, + rows_in: anim.Value, + chrome: anim.Value, + form: anim.Value, + + pub fn init(s: *anim.Frame, rec: *const Recording, moment: u64) Aligned { + return .{ .rec = rec, .at = moment, .bytes = s.value(-1), .decode = s.value(-1), .rows_in = s.value(-1), .chrome = s.value(-1), .form = s.value(0) }; + } + + fn sourceLine(a: *const Aligned, n: u32) []const u8 { + var it = std.mem.splitScalar(u8, a.rec.source, '\n'); + var k: u32 = 1; + while (it.next()) |l| : (k += 1) if (k == n) return std.mem.trimEnd(u8, l, " \r"); + return ""; + } + + /// The rows in interleaved order, with their places in both forms; the pc's index. + fn build(a: *const Aligned, u: ui.Ui) struct { rows: []Row, pc: usize, longest: f32 } { + const pc = a.rec.register(a.at, "rip"); + const listing = disasm.listingAt(u, a.rec, a.at, pc, 64, 64); + const all = listing.rows; + const pc_line = all[listing.pc].line orelse 0; + var start: usize = 0; + while (start < all.len and (all[start].line orelse 0) + 1 != pc_line) start += 1; + if (start == all.len) start = 0; + var end = start; + while (end < all.len and !all[end].outside) end += 1; + const shown = all[start..end]; + var out: std.ArrayList(Row) = .empty; + const arena = u.f.scratch; + var seen: [64]u32 = undefined; + var n_seen: usize = 0; + var lo: u32 = std.math.maxInt(u32); + var hi: u32 = 0; + for (shown) |r| if (r.line) |l| { + lo = @min(lo, l); + hi = @max(hi, l); + }; + var k: usize = 0; + var pc_index: usize = 0; + while (k < shown.len) { + const line = shown[k].line orelse 0; + const again = std.mem.indexOfScalar(u32, seen[0..n_seen], line) != null; + if (!again and n_seen < seen.len) { + seen[n_seen] = line; + n_seen += 1; + } + out.append(arena, .{ .kind = .head, .line = line, .again = again }) catch break; + var first = true; + while (k < shown.len and (shown[k].line orelse 0) == line) : (k += 1) { + if (shown[k].addr == pc) pc_index = out.items.len; + out.append(arena, .{ .kind = .insn, .line = line, .insn = shown[k], .first = first }) catch break; + first = false; + } + // Lines after this one in the source with no code of their own (columns only), once. + if (!again) { + var l = line + 1; + while (l < hi and !hasCode(all, l)) : (l += 1) + if (l > lo) out.append(arena, .{ .kind = .bare_line, .line = l, .first = l == line + 1 }) catch break; + } + } + // Their places: interleaved, heads and rows in order (no bare lines); + // columns, the instructions in order with the bare lines after theirs. + var inter: f32 = 0; + var cols: f32 = 0; + var longest: f32 = 0; + for (out.items) |*r| { + longest = @max(longest, @as(f32, @floatFromInt(a.sourceLine(r.line).len)) * adv); + switch (r.kind) { + .head => { + r.at = .{ inter, cols }; + inter += 1; + }, + .insn => { + r.at = .{ inter, cols }; + inter += 1; + cols += 1; + }, + .bare_line => { + r.at = .{ inter, cols }; + cols += 1; + }, + } + } + return .{ .rows = out.items, .pc = pc_index, .longest = longest }; + } + + fn hasCode(all: []const disasm.Insn, line: u32) bool { + for (all) |r| if (!r.outside and r.line == line) return true; + return false; + } + + pub fn draw(a: *const Aligned, f: *sk.Frame, placed: anim.Placed) void { + const u: ui.Ui = .{ .f = f, .at = placed }; + const built = a.build(u); + if (built.rows.len == 0) return; + const m = a.rec.moment(a.at); + const form = placed.value(a.form); + const across = glide(form / 24); + const down = glide((form - 24) / 36); + const bare = clamp01((form - 60) / 12); + const seam = col.text + built.longest + col.seam_after; + const rows_in = placed.value(a.rows_in); + const chrome = clamp01(placed.value(a.chrome) / 12); + const tag_in = clamp01((placed.value(a.chrome) - 12) / 12); + const v = u.moved(a.box.x, a.box.y); + const body = tag + pad; + var counts = [2]f32{ 0, 0 }; + for (built.rows) |r| counts = .{ @max(counts[0], r.at[0] + 1), @max(counts[1], r.at[1] + 1) }; + const h = body + pitch * std.math.lerp(counts[0], counts[1], down) + pad; + // The panel's rule and tag last (`frame up`). + if (tag_in > 0) { + const tv = v.faded(tag_in); + tv.fill(.{ .x = 0, .y = 0, .w = a.box.w, .h = tag }, theme.color.raised); + tv.fill(.{ .x = 8, .y = 6, .w = 12, .h = 12 }, theme.mark(.current).solid); + tv.text(.sans_medium, theme.size.sans.tag, 28, tag - 6, v.print("{s} \u{00b7} {s}", .{ a.rec.file, functionName(v, a.rec, a.at) }), t.primary); + const notes = [2][]const u8{ "each line, then the instructions it compiled to \u{00b7} lines and addresses in one column", "each line level with its instructions" }; + for (notes, [2]f32{ 1 - down, down }) |note, k| if (k > 0) tv.faded(k).tagNote(a.box.w, note); + } + if (chrome > 0) v.faded(chrome).frame(.{ .x = 0, .y = 0, .w = a.box.w, .h = h }, theme.color.rule, theme.stroke.rule); + // The seam, with the columns. + if (down > 0) v.faded(down).fill(.{ .x = seam, .y = tag, .w = theme.stroke.rule, .h = h - tag }, theme.color.rule); + + for (built.rows, 0..) |r, k| { + const y = body + pitch * std.math.lerp(r.at[0], r.at[1], down); + const order: f32 = @floatFromInt(k); + // At a run: rows top down, 2 f apart, 8 f each; the pc's row is the decoded one. + // The pc's row is the decoded one, once it has travelled to its place (48). + var shows: f32 = if (k == built.pc) @as(f32, if (placed.value(a.decode) >= 48) 1 else 0) else clamp01((rows_in - 2 * order) / 8); + if (r.kind == .bare_line) shows = @min(shows, bare); + if (shows <= 0) continue; + const rv = v.faded(shows); + const base = theme.baseline(y, pitch, size); + switch (r.kind) { + .head, .bare_line => { + // Interleaved: a head across the panel; columns: the line in its cell, level with its run. + const head_y = if (r.kind == .head) y else body + pitch * r.at[1]; + const hb = theme.baseline(head_y, pitch, size); + const paper_w = std.math.lerp(a.box.w - 4, seam - 2, down); + if (r.kind == .head and !r.again and chrome > 0) rv.faded(chrome).fill(.{ .x = 2, .y = head_y, .w = paper_w, .h = pitch }, theme.color.raised); + if (chrome > 0 and r.kind == .head) rv.faded(chrome).fill(.{ .x = 2, .y = head_y - 1, .w = a.box.w - 4, .h = theme.stroke.rule }, theme.color.rule); + const faint = r.again or r.kind == .bare_line; + const number = rv.print("{d}", .{r.line}); + const is_pc = !r.again and built.rows[built.pc].line == r.line and r.kind == .head; + if (is_pc) rv.fill(.{ .x = col.place_end - @as(f32, @floatFromInt(number.len)) * adv - 4, .y = head_y + 1, .w = @as(f32, @floatFromInt(number.len)) * adv + 6, .h = pitch - 2 }, theme.mark(.current).solid); + rv.text(.mono, size, col.place_end - @as(f32, @floatFromInt(number.len)) * adv, hb, number, if (is_pc) t.ink else t.faint); + rv.text(.mono, size, col.text, hb, a.sourceLine(r.line), if (faint) t.faint else t.primary); + if (r.again) rv.text(.sans, theme.size.sans.micro, std.math.lerp(col.mnemonic + 4, col.text + built.longest - 140, down), hb, "again: its second run", t.dim); + if (r.kind == .bare_line and r.first) rv.text(.sans, theme.size.sans.micro, seam + col.instr, hb, "no code of their own", t.dim); + }, + .insn => { + const insn = r.insn.?; + const ix = std.math.lerp(0, seam, across); + if (k == built.pc) { + const wash = rv.faded(clamp01((placed.value(a.decode) - 48) / 12)); + wash.current(.{ .x = ix + 2, .y = y, .w = a.box.w - ix - 4, .h = pitch }, theme.metric.plaque.pc, 0); + sk.draw.polygon(f, &.{ wash.at.xf.apply(.{ ix + 20, y + pitch / 2 }), wash.at.xf.apply(.{ ix + 10, y + 6 }), wash.at.xf.apply(.{ ix + 10, y + pitch - 6 }) }, wash.at.pen(.{ .fill = ui.rgb(theme.mark(.current).on_solid) })); + } + const digits: f32 = @floatFromInt(ui.digits(insn.addr)); + _ = rv.address(ix + col.place_end - digits * adv, base, insn.addr, .{ .ink = ui.rgb(theme.color.region.code_) }); + // Its bytes, as the recording read them: interleaved only. + if (across < 1) rv.faded(1 - across).text(.mono, size, col.bytes, base, hexBytes(rv, m, insn), t.dim); + disasm.bareRow(rv.moved(std.math.lerp(col.mnemonic - theme.metric.insn.mnemonic, seam + col.instr + 24 - theme.metric.insn.mnemonic, across), 0), insn, y); + }, + } + } + a.drawBytesRow(v, m, placed, built); + } + + /// III1 and the decode (III2): the code's sixteen bytes as a dump row, + /// in code's ink 2 f apart; the pc's instruction's bytes framed; then + /// they gather, its text fades in beside them, and the row travels to + /// its place in the panel. + fn drawBytesRow(a: *const Aligned, v: ui.Ui, m: Recording.Moment, placed: anim.Placed, built: anytype) void { + const clock = placed.value(a.bytes); + if (clock < 0) return; + const d = placed.value(a.decode); + const insn = built.rows[built.pc].insn.?; + const row_addr = insn.addr & ~@as(u64, 15); + var bytes: [16]u8 = undefined; + var known: [16]bool = undefined; + m.read(row_addr, &bytes, &known) catch return; + const dy = a.dump_y - a.box.y; + const target_y = tag + pad + pitch * built.rows[built.pc].at[0]; + const travel = glide((d - 24) / 24); + if (travel >= 1) return; + const y = std.math.lerp(dy, target_y, travel); + const base = theme.baseline(y, pitch, size); + const arrive = clamp01(clock / 12); + const gather = glide(d / 12); + const others = 1 - clamp01(d / 12); + const bx = struct { + fn at(k: usize) f32 { + return dump_first + @as(f32, @floatFromInt(k)) * theme.metric.bytes.pitch + @as(f32, if (k >= 8) theme.metric.bytes.middle else 0); + } + }.at; + // The row's address: the row's, then the instruction's. + const rv = v.faded(arrive); + const ad: f32 = @floatFromInt(ui.digits(row_addr)); + rv.faded(others).text(.mono, size, 34, base, rv.print("{x}", .{row_addr}), t.faint); + _ = rv.faded(1 - others).address(std.math.lerp(34, col.place_end - ad * adv, travel), base, insn.addr, .{ .ink = ui.rgb(theme.color.region.code_) }); + const first: usize = @intCast(insn.addr - row_addr); + const target_x = std.math.lerp(bx(first), col.bytes, travel); + for (0..16) |k| { + const mine = k >= first and k < first + insn.len; + const inked = clamp01((clock - 12 - 2 * @as(f32, @floatFromInt(k))) / 12); + const ink = ui.mix(t.primary, theme.color.region.code_, inked); + const text = if (known[k]) rv.print("{x:0>2}", .{bytes[k]}) else "??"; + if (!mine) { + if (others > 0) rv.faded(others).text(.mono, size, bx(k), base, text, ink); + continue; + } + // Gathered: three characters apart, from where the instruction's first byte stood. + const at_x = std.math.lerp(bx(k), target_x + @as(f32, @floatFromInt(k - first)) * 3 * adv, gather); + rv.text(.mono, size, at_x, base, text, ui.mix(ink, ui.rgb(t.dim), clamp01((d - 12) / 12))); + } + // The instruction's bytes framed once inked (6 f), until they gather. + const framed = clamp01((clock - 12 - 32 - 12) / 6) * (1 - clamp01(d / 6)); + if (framed > 0) rv.read(.{ .x = bx(first), .y = y, .w = bx(first + insn.len - 1) - bx(first) + 2 * adv, .h = pitch }, framed); + // Its text beside the bytes, at the panel's columns from them (12 f). + const text_in = clamp01((d - 12) / 12); + if (text_in > 0) disasm.bareRow(rv.faded(text_in).moved(target_x - col.bytes + col.mnemonic - theme.metric.insn.mnemonic, 0), insn, y); + } +}; + +fn hexBytes(u: ui.Ui, m: Recording.Moment, insn: disasm.Insn) []const u8 { + var bytes: [16]u8 = undefined; + var known: [16]bool = undefined; + const n = @min(insn.len, 16); + m.read(insn.addr, bytes[0..n], known[0..n]) catch return ""; + var out: std.ArrayList(u8) = .empty; + for (bytes[0..n], known[0..n], 0..) |b, kn, k| { + if (k > 0) out.append(u.f.scratch, ' ') catch {}; + out.appendSlice(u.f.scratch, if (kn) u.print("{x:0>2}", .{b}) else "??") catch {}; + } + return out.items; +} + +fn functionName(u: ui.Ui, rec: *const Recording, i: u64) []const u8 { + var buf: [128]u8 = undefined; + const name = (rec.moment(i).string(rec.register(i, "rip"), &buf) catch null) orelse return ""; + const plus = std.mem.indexOfScalar(u8, name, '+') orelse name.len; + return u.print("{s}", .{name[0..plus]}); +} diff --git a/anim/src/aside.zig b/anim/src/aside.zig new file mode 100644 index 0000000..7cf6867 --- /dev/null +++ b/anim/src/aside.zig @@ -0,0 +1,160 @@ +//! A text beside what it speaks of, for a scene that builds its parts in +//! place rather than in the column's panes (the introduction): the +//! column's `bubble` (design/README.md, "column"), standing alone. Go 40 +//! on 54, code in mono 35, at most 40 characters a line, 16 of padding; +//! the newest on `raised` paper, primary; an older one loses its paper and +//! dims to `dim` (`dim`, 18 f). It arrives rising 8 (its object's fade, +//! 18 f, `enter`) and leaves with its fade (12 f, `exit`). No stem: its +//! level is the tie. +//! shortcut: a second drawing of column.zig's bubble (wrap, paper); fold into one when the column takes custom panes. +const std = @import("std"); +const sk = @import("sketch"); +const anim = @import("anim"); +const ui = @import("ui.zig"); +const words = @import("words.zig"); +const theme = ui.theme; +const t = theme.color.text; + +const time = theme.time; +const pad = 16; +const chars = 40; +const first = 40; +const line_pitch = theme.size.sans.caption_leading; + +pub const Aside = struct { + text: []const u8, + /// The paper's left, and the middle of its first line. + x: f32, + level: f32, + /// 0 newest, 1 the account (no paper, `dim`). + dim: anim.Value, + + pub fn draw(a: *const Aside, f: *sk.Frame, placed: anim.Placed) void { + const u = (ui.Ui{ .f = f, .at = placed }).moved(0, (1 - placed.pose.opacity) * theme.time.caption_rise); + const wrapped = wrap(u, a.text); + const top = a.level - first; + const h = first * 2 + @as(f32, @floatFromInt(wrapped.len - 1)) * line_pitch; + var w: f32 = 0; + for (wrapped) |line| w = @max(w, width(u, line)); + const dim = std.math.clamp(placed.value(a.dim), 0, 1); + if (dim < 1) u.faded(1 - dim).fill(.{ .x = a.x, .y = top, .w = w + 2 * pad, .h = h }, theme.color.raised); + const ink = ui.mix(t.primary, t.dim, dim); + for (wrapped, 0..) |line, n| _ = words.runs(u, a.x + pad, top + first + @as(f32, @floatFromInt(n)) * line_pitch + 14, line, .sans, theme.size.sans.caption, theme.size.mono.value, ink); + } +}; + +/// A scene's texts beside their parts, said one after another: each waits +/// until the last has been read, arrives (18 f, `enter`), and is followed +/// by its lead (60 f); the one before it dims (18 f), or leaves (12 f, +/// `exit`) where the new one would stand on it. `leave`: all go together. +pub const Asides = struct { + shown: [8]?anim.Obj = @splat(null), + dims: [8]anim.Value = undefined, + spans: [8][2]f32 = undefined, + n: usize = 0, + read_by: f32 = 0, + + pub fn say(a: *Asides, s: *anim.Frame, text: []const u8, x: f32, level: f32) void { + s.wait(@max(a.read_by - s.cursor, 0)); + const dim = s.value(0); + const made = s.new(Aside{ .text = text, .x = x, .level = level, .dim = dim }); + const obj = s.custom(made, .{ .x = -640, .y = -360, .scale = ui.scale }); + const span = [2]f32{ level - first, level + first + @as(f32, @floatFromInt(lines(text) - 1)) * line_pitch }; + const at = s.cursor; + for (a.shown[0..a.n], a.dims[0..a.n], a.spans[0..a.n]) |*o, d, other| { + s.cursor = at; + if (o.* == null) continue; + if (other[0] < span[1] + 12 and span[0] < other[1] + 12) { + s.play(.{o.*.?.fadeOut()}, .{ .seconds = time.caption_out, .ease = easeExit }); + o.* = null; + } else s.play(.{d.to(1)}, .{ .seconds = 18.0 / 60.0, .ease = easeGlide }); + } + s.cursor = at; + s.play(.{obj.fadeIn()}, .{ .seconds = time.caption_in, .ease = easeEnter }); + a.shown[a.n] = obj; + a.dims[a.n] = dim; + a.spans[a.n] = span; + a.n += 1; + a.read_by = s.cursor + time.caption(@intCast(std.unicode.utf8CountCodepoints(text) catch text.len)); + s.wait(time.caption_lead); + } + + /// All leave together (12 f), once the last is read. + pub fn leave(a: *Asides, s: *anim.Frame) void { + s.wait(@max(a.read_by - s.cursor, 0)); + const at = s.cursor; + for (a.shown[0..a.n]) |o| if (o) |obj| { + s.cursor = at; + s.play(.{obj.fadeOut()}, .{ .seconds = time.caption_out, .ease = easeExit }); + }; + } +}; + +fn easeExit(x: f32) f32 { + return theme.ease(.exit, x); +} +fn easeEnter(x: f32) f32 { + return theme.ease(.enter, x); +} +fn easeGlide(x: f32) f32 { + return theme.ease(.glide, x); +} + +/// How many lines `wrap` makes of `text`. +fn lines(text: []const u8) usize { + var it = std.mem.splitScalar(u8, text, ' '); + var n: usize = 0; + var count: usize = 1; + while (it.next()) |word| { + const seen = (std.unicode.utf8CountCodepoints(word) catch word.len) - std.mem.count(u8, word, "`"); + if (n > 0 and n + 1 + seen > chars) { + count += 1; + n = 0; + } + if (n > 0) n += 1; + n += seen; + } + return count; +} + +fn width(u: ui.Ui, line: []const u8) f32 { + var w: f32 = 0; + var parts = std.mem.splitScalar(u8, line, '`'); + var code = false; + while (parts.next()) |part| : (code = !code) w += if (code) u.width(.mono, theme.size.mono.value, part) else u.width(.sans, theme.size.sans.caption, part); + return w; +} + +/// Lines of at most `chars` visible characters, broken at spaces; a code +/// run keeps its backticks on each line it spans. +fn wrap(u: ui.Ui, text: []const u8) []const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + var it = std.mem.splitScalar(u8, text, ' '); + var line: std.ArrayList(u8) = .empty; + var n: usize = 0; + while (it.next()) |word| { + const seen = std.unicode.utf8CountCodepoints(word) catch word.len; + const ticks = std.mem.count(u8, word, "`"); + if (n > 0 and n + 1 + seen - ticks > chars) { + out.append(u.f.scratch, line.items) catch break; + line = .empty; + n = 0; + } + if (n > 0) { + line.append(u.f.scratch, ' ') catch break; + n += 1; + } + line.appendSlice(u.f.scratch, word) catch break; + n += seen - ticks; + } + if (line.items.len > 0) out.append(u.f.scratch, line.items) catch {}; + if (out.items.len == 0) out.append(u.f.scratch, "") catch {}; + return out.items; +} + +test "lines of at most forty characters, backticks not counted" { + try std.testing.expectEqual(@as(usize, 1), lines("Its address space, 128 TiB, to scale.")); + try std.testing.expectEqual(@as(usize, 2), lines("Its address space, 128 TiB, to scale: mapped only at each end.")); + // Four code runs of nine: 39 shown, 47 with their backticks. + try std.testing.expectEqual(@as(usize, 1), lines("`012345678` `012345678` `012345678` `012345678`")); +} diff --git a/anim/src/column.zig b/anim/src/column.zig index 32b3d4d..1484796 100644 --- a/anim/src/column.zig +++ b/anim/src/column.zig @@ -19,9 +19,11 @@ //! }); //! //! Between beats, in a rest (design/README.md, "Panes between beats"): the -//! last bubble dims; the panes that leave fade (12 f) and fold to the shelf -//! (24 f, `glide`); those that stay glide (24 f); those that come unfold -//! (24 f) and fade in (12 f); an older bubble in the way glides out of it +//! last bubble dims; the panes that leave fade (6 f) and fold where they +//! stand, their tags travelling to the shelf (18 f, `glide`); those that +//! stay glide (24 f; a pane crossing to the other column 24 f each way), +//! one that changes its height keeping its rows; those that come unfold +//! (18 f) and fade in (6 f); an older bubble in the way glides out of it //! (24 f); the next arrives (18 f, rising 8), its stem drawing (12 f); the //! lead; the stem draws back as the step fires. A bubble never travels //! between placements: the last leaves (12 f), the frame changes (48 f), the @@ -78,6 +80,9 @@ pub const Beat = struct { notes: []const Note = &.{}, /// `on`: the bubble's top left in the frame (design units), in the drawing's free space. where: ?[2]f32 = null, + /// The rest after this beat's steps is meant (a poster's picture): its + /// bubble may still be read there longer than a hold (design/README.md, `bubble`). + held: bool = false, }; pub const Options = struct { @@ -92,10 +97,9 @@ pub const Options = struct { /// Frames, at 60 a second (design/README.md, "Panes between beats"). const f = struct { const dim = 18.0 / 60.0; - const rows = 12.0 / 60.0; - const fold = 24.0 / 60.0; + const rows = 6.0 / 60.0; + const fold = 18.0 / 60.0; const glide = 24.0 / 60.0; - const relayout = theme.time.relayout; const push = 24.0 / 60.0; const arrive = 18.0 / 60.0; const stem_after = 6.0 / 60.0; @@ -164,6 +168,8 @@ pub const Column = struct { zoom: f32 = 1, read_by: f32 = 0, said: bool = false, + /// The last beat's rest is meant: not flagged. + held: bool = false, /// One beat: the panes change (in a rest, never under a step), the text /// arrives where the beat places it, the lead, then the scene's step. @@ -197,8 +203,12 @@ pub const Column = struct { split.band = room; }, } - // Not before the text up has been read. - s.wait(@max(col.read_by - s.cursor, 0)); + // Not before the text up has been read; and its beat should have covered that + // (its lead, its steps and a hold of at most 84 f), unless its rest is meant. + const still = col.read_by - s.cursor; + if (col.said and !col.held and still > 84.0 / 60.0) flag(col.n, still); + s.wait(@max(still, 0)); + col.held = b.held; const kind = frameOf(at) != frameOf(col.placement); const moves = !std.meta.eql(to, col.standing) or !sameBoxes(col.split, split, to) or zoom != col.zoom or kind; const newest = col.newestStanding(); @@ -295,31 +305,25 @@ pub const Column = struct { fn change(col: *Column, s: *anim.Frame, to: [parts.len]bool, split: Split, at: Placement, zoom: f32, kind: bool) void { var leaving: [parts.len]bool = undefined; var coming: [parts.len]bool = undefined; - // A pane that stays but changes its rows: its rows fade out and in round the - // glide (they are laid out for its height), its frame gliding as the column's. - var resized: [parts.len]bool = undefined; + // A pane that stays and changes its height keeps its rows the whole way: + // it glides with the column, gaining or giving up rows at its moving edge. var any_leaving = false; var any_coming = false; - inline for (.{ "band", "view", "source", "disasm", "registers", "stack", "backtrace" }, 0..) |name, i| { + for (parts, 0..) |_, i| { leaving[i] = col.standing[i] and !to[i]; coming[i] = !col.standing[i] and to[i]; - resized[i] = col.standing[i] and to[i] and i > 1 and @field(col.split, name).h != @field(split, name).h; - any_leaving = any_leaving or leaving[i] or resized[i]; - any_coming = any_coming or coming[i] or resized[i]; + any_leaving = any_leaving or leaving[i]; + any_coming = any_coming or coming[i]; } const band = @intFromEnum(Part.band); const view = @intFromEnum(Part.view); if (any_leaving) { var anims: [3 * parts.len]anim.Animation = undefined; var n: usize = 0; - for (parts, 0..) |_, i| if (leaving[i] or resized[i]) { + for (parts, 0..) |_, i| if (leaving[i]) { anims[n] = col.ghost[i].to(1); n += 1; }; - for (parts, 0..) |_, i| if (resized[i]) if (col.objs[i]) |o| { - anims[n] = o.fadeOut(); - n += 1; - }; for (parts, 0..) |_, i| if (leaving[i]) if (col.objs[i]) |o| { // The lens is one object: it goes when neither of its panes stands (once). const lens = i == band or i == view; @@ -356,8 +360,6 @@ pub const Column = struct { if (i == band) next.band.h = 0; }; const glides = !sameBoxes(col.split, next, col.standing) or zoom != col.zoom or kind; - const seconds: f32 = if (!glides) 0 else if (kind) f.relayout else f.glide; - const start = s.cursor; // A pane going over to the other column goes down (or up) its own // first, as the others make room, then across: never over another's rows. var mid = next; @@ -366,6 +368,9 @@ pub const Column = struct { @field(mid, name).x = @field(col.split, name).x; crosses = true; }; + // 24 f; a pane crossing over, 24 f each way. + const seconds: f32 = if (!glides) 0 else if (crosses) 2 * f.glide else f.glide; + const start = s.cursor; if (crosses) col.stage.glide(s, mid, seconds / 2); col.stage.glide(s, next, if (crosses) seconds / 2 else seconds); const end = s.cursor; @@ -392,14 +397,10 @@ pub const Column = struct { }; if (n > 0) together(s, anims[0..n], f.fold, anim.ease.linear); n = 0; - for (parts, 0..) |_, i| if (coming[i] or resized[i]) { + for (parts, 0..) |_, i| if (coming[i]) { anims[n] = col.ghost[i].to(0); n += 1; }; - for (parts, 0..) |_, i| if (resized[i]) if (col.objs[i]) |o| { - anims[n] = o.fadeIn(); - n += 1; - }; for (parts, 0..) |_, i| if (coming[i]) if (col.objs[i]) |o| { const lens = i == band or i == view; if (!lens or !(col.standing[band] or col.standing[view]) and !(i == view and coming[band])) { @@ -492,10 +493,12 @@ pub const Column = struct { /// between its box and its place there. fn drawShelf(col: *const Column, u: ui.Ui, placed: anim.Placed) void { const before, const after, const p = col.notesNow(placed); + shelf_tags = @splat(null); var x: f32 = theme.layout.program.x; for (parts, 0..) |part, i| { if (col.objs[i] == null) continue; - const on = theme.ease(.glide, placed.value(col.shelf[i])); + const raw = placed.value(col.shelf[i]); + const on = theme.ease(.glide, raw); // Its frame drawn in the pane's stead: crossfading with the pane at its box, alone on its way. const ghost = placed.value(col.ghost[i]); if (on <= 0 and ghost <= 0) continue; @@ -504,7 +507,11 @@ pub const Column = struct { const slot: Rect = .{ .x = x, .y = shelf_y, .w = w, .h = m.tag }; const name = col.title(placed, part); const b = col.box(placed, part); - const r: Rect = if (ghost > 0) .{ .x = std.math.lerp(b.x, slot.x, on), .y = std.math.lerp(b.y, slot.y, on), .w = std.math.lerp(b.w, slot.w, on), .h = std.math.lerp(b.h, slot.h, on) } else slot; + // It closes to its tag where it stands, then the tag travels (unfolding, the + // reverse): only a tag ever crosses another pane, never a panel. + const shut = theme.ease(.glide, std.math.clamp(raw / 0.6, 0, 1)); + const go = theme.ease(.glide, std.math.clamp((raw - 0.4) / 0.6, 0, 1)); + const r: Rect = if (ghost > 0) .{ .x = std.math.lerp(b.x, slot.x, go), .y = std.math.lerp(b.y, slot.y, go), .w = std.math.lerp(b.w, slot.w, shut), .h = std.math.lerp(b.h, slot.h, shut) } else slot; const v = u.moved(r.x, r.y).faded(if (on > 0) 1 else ghost); _ = v.panel(r.w, r.h, name, .{}); // Its note comes as it lands on the shelf, and goes as it leaves. @@ -514,6 +521,7 @@ pub const Column = struct { if (p < 1) _ = col.tagNote(v.faded(shows * (1 - p)), placed, part, nx, notes[0]); _ = col.tagNote(v.faded(shows * p), placed, part, nx, notes[1]); } + if (on >= 1) shelf_tags[i] = slot; x += (w + theme.canvas.row_gap) * on; } } @@ -605,8 +613,12 @@ pub const Column = struct { const digits = if (v < 0x10000) u.print("{d}", .{v}) else u.print("{x}", .{v}); const dw = u.width(.mono, size, digits); const heat = if (age == 0) now.register(i, ties.strikeDelay(now, i)) else now.heat(1, null, 0); - const ink = u.written(.{ .x = at, .y = 0, .w = dw, .h = m.tag }, heat) orelse ui.Ink{}; - u.text(ink.face, size, at, base, digits, ink.ink); + _ = u.written(.{ .x = at, .y = 0, .w = dw, .h = m.tag }, heat); + // Struck, bold and bright: crossfading with the fill (a face changing in a frame on a tag this small is a pop). + const solid = if (heat.level >= 1) heat.solid * heat.in else 0; + const ink = ui.mix(t.primary, t.bright, solid); + if (solid < 1) u.faded(1 - solid).text(.mono, size, at, base, digits, ink); + if (solid > 0) u.faded(solid).text(.mono_bold, size, at, base, digits, ink); at += dw; } shown += 1; @@ -631,8 +643,8 @@ pub const Column = struct { }; var with: [48]f32 = undefined; var without: [48]f32 = undefined; - col.layout(placed, inv, newest, true, &with); - col.layout(placed, inv, newest, false, &without); + col.layout(u.f, placed, inv, newest, true, &with); + col.layout(u.f, placed, inv, newest, false, &without); const push = if (newest) |k| theme.ease(.glide, placed.value(col.texts[k].push)) else 1; for (col.texts[0..col.n], 0..) |x, k| { const in = placed.value(x.in); @@ -685,7 +697,7 @@ pub const Column = struct { /// Each beside text's top, the newest's or not: level with what it /// speaks of where it can be; an older one in a newer one's way above it, /// or under it where there is no room above. - fn layout(col: *const Column, placed: anim.Placed, inv: sk.math.Affine, newest: ?usize, with_newest: bool, out: *[48]f32) void { + fn layout(col: *const Column, fr: *sk.Frame, placed: anim.Placed, inv: sk.math.Affine, newest: ?usize, with_newest: bool, out: *[48]f32) void { var taken: [48][2]f32 = undefined; var n_taken: usize = 0; var k = col.n; @@ -699,7 +711,7 @@ pub const Column = struct { // Only what has arrived. if (newest == null or k > newest.?) continue; const h = height(x); - var top = std.math.clamp(levelY(placed, inv, k, x.level) - bubble.first, bubble.top, bubble.bottom - h); + var top = std.math.clamp(levelY(fr, inv, k, x.level) - bubble.first, bubble.top, bubble.bottom - h); // Above what is in its way, while there is room; else under it. var tries: usize = 0; while (tries < n_taken + 1) : (tries += 1) { @@ -725,7 +737,8 @@ pub const Column = struct { fn stemBeside(_: *const Column, u: ui.Ui, inv: sk.math.Affine, x: Text, top: f32, target: Level, placed: anim.Placed) void { const v = placed.value(x.stem_v); if (v <= 0 or v >= 2) return; - const r = find(inv, target) orelse return; + // About a folded pane: its tag on the shelf. + const r = if (paneOf(target)) |pane| if (shelf_tags[@intFromEnum(pane)]) |tag| [4]f32{ tag.x, tag.y, tag.x + tag.w, tag.y + tag.h } else find(u.f, inv, target) orelse return else find(u.f, inv, target) orelse return; const y0 = top + bubble.first; const y1 = (r[1] + r[3]) / 2; const lane = theme.metric.tie.link_lane + 6; @@ -739,7 +752,7 @@ pub const Column = struct { fn stemOn(col: *const Column, u: ui.Ui, inv: sk.math.Affine, x: Text, where: [2]f32, target: Level, placed: anim.Placed) void { const v = placed.value(x.stem_v); if (v <= 0 or v >= 2) return; - const r = find(inv, target) orelse return; + const r = find(u.f, inv, target) orelse return; const w = paperWidth(u, x); const lane = column_top + m.tag + 10; const from_x = where[0] + w - 32; @@ -790,7 +803,7 @@ fn settled(s: *const anim.Frame, v: anim.Value) f32 { } /// Where a level's place is this frame, in the frame's units: left, top, right, bottom. -fn find(inv: sk.math.Affine, level: Level) ?[4]f32 { +fn find(fr: *sk.Frame, inv: sk.math.Affine, level: Level) ?[4]f32 { const place: ties.Place = switch (level) { .pc => .pc, .row => |a| .{ .row = a }, @@ -799,7 +812,7 @@ fn find(inv: sk.math.Affine, level: Level) ?[4]f32 { .block => |a| .{ .block = a }, .y => |y| return .{ 0, y - m.row / 2, theme.layout.program.x + theme.layout.program.w, y + m.row / 2 }, }; - const r = ties.find(place) orelse return null; + const r = ties.find(fr, place) orelse return null; const a = inv.apply(.{ r[0], r[1] }); const b = inv.apply(.{ r[2], r[3] }); return .{ a[0], a[1], b[0], b[1] }; @@ -811,17 +824,39 @@ fn find(inv: sk.math.Affine, level: Level) ?[4]f32 { var last_level: [48]?f32 = @splat(null); /// Once its row has gone from a pane that is drawn, or the panes have changed, a text stays where it is (`latched`). var latched: [48]bool = @splat(false); -fn levelY(_: anim.Placed, inv: sk.math.Affine, k: usize, level: Level) f32 { - if (!latched[k]) if (find(inv, level)) |r| { +fn levelY(fr: *sk.Frame, inv: sk.math.Affine, k: usize, level: Level) f32 { + if (!latched[k]) if (find(fr, inv, level)) |r| { const y = (r[1] + r[3]) / 2; last_level[k] = y; return y; }; // A row of the disassembly, gone while the pane is there (its pc drawn): the text stays. - if (last_level[k] != null and (level == .row or level == .head or level == .floor) and ties.find(.pc) != null) latched[k] = true; + if (last_level[k] != null and (level == .row or level == .head or level == .floor) and ties.find(fr, .pc) != null) latched[k] = true; return last_level[k] orelse 400; } +/// Each folded pane's tag on the shelf this frame (`drawShelf`), for a stem about a folded pane. +var shelf_tags: [parts.len]?Rect = @splat(null); + +/// The pane a level is in. +fn paneOf(level: Level) ?Part { + return switch (level) { + .pc, .row, .head, .floor => .disasm, + .block => .band, + .y => null, + }; +} + +/// A bubble still being read after its beat's steps and an 84 f hold +/// (design/README.md, `bubble`): said once, on stderr. +var flagged: [48]bool = @splat(false); +fn flag(k: usize, still: f32) void { + const i = @min(k, flagged.len) -| 1; + if (flagged[i]) return; + flagged[i] = true; + std.debug.print("column: bubble {d} is still read {d:.1} s after its beat's steps (84 f at most)\n", .{ k, still }); +} + fn height(x: Text) f32 { const n = lineCount(x.text, bubble.chars); return bubble.first * 2 + @as(f32, @floatFromInt(n - 1)) * bubble.pitch; diff --git a/anim/src/context.zig b/anim/src/context.zig index 16278e3..9b466da 100644 --- a/anim/src/context.zig +++ b/anim/src/context.zig @@ -99,6 +99,10 @@ pub const Registers = struct { /// a row each, with its chain; the rest folded three to a row /// (design/README.md, `registers` `quiet`). All of them on the map. moves: u32 = every, + /// The quiet ones left out, not folded, rip under the rest: a `pair`'s four rows. + folds: bool = true, + /// Its tag's title (a `pair`'s names its run). + title: []const u8 = "registers", const Shown = struct { regs: zt.Regs, moment: Recording.Moment }; @@ -115,7 +119,7 @@ pub const Registers = struct { const was: Shown = .{ .regs = (now.before().regs(rec.tid) catch null) orelse is.regs, .moment = now.before() }; // Taller than its place on its way in: its own page under it. if (fold < 1) u.fill(.{ .x = 0, .y = m.tag, .w = shape.w, .h = shape.h - m.tag }, theme.color.page); - const body = u.panel(shape.w, shape.h, "registers", .{ .focus = r.focus, .legend = &legend }); + const body = u.panel(shape.w, shape.h, r.title, .{ .focus = r.focus, .legend = &legend }); // A link leaves from the panel's edge, not through a name. ties.anchor(u, .registers, .{ .x = 0, .y = 0, .w = shape.w, .h = shape.h }); clipBody(u, shape); @@ -124,7 +128,7 @@ pub const Registers = struct { const full = fullRows(r.moves); const top = body.y + m.pad; // The quiet ones under a rule across, in pwndbg's order; rip the last row. - if (full < 16) u.faded(fold).fill(.{ .x = theme.stroke.rule, .y = top + @as(f32, @floatFromInt(full)) * m.row - 1, .w = shape.w - 2 * theme.stroke.rule, .h = theme.stroke.rule }, theme.color.rule); + if (full < 16 and r.folds) u.faded(fold).fill(.{ .x = theme.stroke.rule, .y = top + @as(f32, @floatFromInt(full)) * m.row - 1, .w = shape.w - 2 * theme.stroke.rule, .h = theme.stroke.rule }, theme.color.rule); var rows_before: usize = 0; var quiet_before: usize = 0; for (theme.metric.all_registers[0..16], 0..) |name, i| { @@ -134,12 +138,13 @@ pub const Registers = struct { rows_before += 1; continue; } + if (!r.folds) continue; const y = std.math.lerp(unfolded, top + @as(f32, @floatFromInt(full + quiet_before / q.quiet_per_row)) * m.row, fold); const x = std.math.lerp(theme.metric.context.side, q.quiet_from + @as(f32, @floatFromInt(quiet_before % q.quiet_per_row)) * q.quiet_pitch, fold); quiet_before += 1; r.quietRow(u, now, is, was, name, x, y, shape.w, fold); } - r.rip(u, now, std.math.lerp(top + 16 * m.row, top + @as(f32, @floatFromInt(registerRows(r.moves) - 1)) * m.row, fold), shape.w, is, was); + r.rip(u, now, std.math.lerp(top + 16 * m.row, top + @as(f32, @floatFromInt(if (r.folds) registerRows(r.moves) - 1 else full)) * m.row, fold), shape.w, is, was); veiled(u, shape, now.veil); } @@ -155,7 +160,7 @@ pub const Registers = struct { _ = rows.reg(u.faded(1 - fold).moved(dx, 0), y, w - dx, name, is.moment, value, .{ .hops = 1 - std.math.clamp(fold / 0.4, 0, 1) }); } const hops = rows.quiet(u.faded(fold), x, y, name, is.moment, value, read_shows); - anchor(u, i, hops, y); + anchor(u, i, hops, y, value, w); } /// Whether `name` carries the system call the step makes, holding @@ -242,7 +247,7 @@ pub const Registers = struct { // `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); + return anchor(u, i, hops, y, value, w); } else if (r.quiet) { // Unmarked: the values change as the mark moves on. landed = now.advancing() >= 0.5; @@ -269,7 +274,7 @@ pub const Registers = struct { } const hops = rows.reg(if (ran < 1 and value_was != value_now) u.faded(ran) else u, y, w, name, memory, if (landed or ran < 1) value_now else value_was, marks); fdNote(u.faded(note_shows), hops, y, note); - anchor(u, i, hops, y); + anchor(u, i, hops, y, if (landed or ran < 1) value_now else value_was, w); } /// The `fd` class's note after a register's value: faint, what it is open on. @@ -277,8 +282,12 @@ pub const Registers = struct { if (hops.n > 0 and on.len > 0) u.text(.mono, theme.size.mono.context, hops.end + 8, rows.baseline(y), on, t.faint); } - fn anchor(u: ui.Ui, i: usize, hops: rows.Hops, y: f32) void { - if (hops.n > 0) ties.anchor(u, .{ .register = i }, .{ .x = hops.x[0], .y = y, .w = hops.w[0], .h = m.row }); + /// Its place, and its value shown there (a relation's join: `ties.show`). + fn anchor(u: ui.Ui, i: usize, hops: rows.Hops, y: f32, value: u64, w: f32) void { + if (hops.n == 0) return; + const r: Rect = .{ .x = hops.x[0], .y = y, .w = hops.w[0], .h = m.row }; + ties.anchor(u, .{ .register = i }, r); + ties.show(u, value, r, .registers, 0, @intCast(i), w); } }; @@ -605,7 +614,7 @@ pub const Stack = struct { 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, was: ?[]const u8 = null }; + const Span = struct { y0: f32, y1: f32, name: []const u8, newest: bool, open: bool, was: ?[]const u8 = null, shows: f32 = 1 }; // A frame whose name changes in place (on through a stub) crossfades over the 12 f before the advance. const renamed = now.renaming(); const calls_was = rec.stack(u.f.scratch, now.stops[1]); @@ -614,25 +623,53 @@ pub const Stack = struct { var n_spans: usize = 0; // Under `tied` the spans ride rsp's pin: the newest stretches or shrinks with it. const p_span = pin_sp orelse p; + // Each frame is the same frame before and after the step where it ends at the same + // word (a call puts one on top, a return takes one off): never matched by depth. + const sameAs = struct { + fn of(fr: Frame, in: []const Frame) ?usize { + for (in, 0..) |o, idx| if (std.meta.eql(o.hi, fr.hi)) return idx; + return null; + } + }.of; + const n_old = @min(old_chain.len, 16); + var kept: [16]bool = @splat(false); for (chain, 0..) |frame, i| { - const old_frame = if (i < old_chain.len) old_chain[i] else frame; + const j = sameAs(frame, old_chain); + if (j) |q| if (q < kept.len) { + kept[q] = true; + }; + // A new frame grows from its foot. + const old_frame = if (j) |q| old_chain[q] else Frame{ .pc = frame.pc, .lo = frame.hi orelse frame.lo, .hi = frame.hi }; const first = std.math.lerp(rows_of(old_frame.lo, window[0]), rows_of(frame.lo, window[0]), p_span) + 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_span) + 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 }; - if (now.walking() and !jumped and i < old_chain.len and old_chain[i].lo == frame.lo) { - const was_name = spanName(u, rec, calls_was, i, old_chain[i].pc); + // Named as the stop the panel shows has it: before the strike by the frame as it was. + const name = if (j == null) spanName(u, rec, calls_is, i, frame.pc) else if (landed) spanName(u, rec, open_calls, i, if (i < named.len) named[i].pc else frame.pc) else spanName(u, rec, open_calls, j.?, old_chain[j.?].pc); + // A new frame comes in as rsp's pin brings it; the newest is the new one from the pin's middle. + spans[n_spans] = .{ .y0 = top + @max(first, 0) * m.row, .y1 = y1, .name = name, .newest = if (p_span < 0.5) (j != null and j.? == 0) or (j == null and i == 0 and old_chain.len == 0) else i == 0, .open = open, .shows = if (j == null and old_chain.len > 0) p_span else 1 }; + if (now.walking() and !jumped) if (j) |q| if (old_chain[q].lo == frame.lo) { + const was_name = spanName(u, rec, calls_was, q, old_chain[q].pc); const is_name = spanName(u, rec, calls_is, i, frame.pc); if (!std.mem.eql(u8, was_name, is_name)) { spans[n_spans].name = is_name; spans[n_spans].was = was_name; } - } + }; n_spans += 1; + if (n_spans == spans.len) break; } + // A frame the step takes off shrinks to its foot as rsp's pin falls, and goes with it. + for (old_chain[0..n_old], 0..) |o, q| if (!kept[q] and n_spans < spans.len and !jumped) { + const hi = o.hi orelse continue; + const first = std.math.lerp(rows_of(o.lo, window[0]), rows_of(hi, window[0]), p_span) + slide; + const last = rows_of(hi, window[0]) + slide; + if (last < 0 or first >= @as(f32, @floatFromInt(slots))) continue; + spans[n_spans] = .{ .y0 = top + @max(first, 0) * m.row, .y1 = top + (@min(last, @as(f32, @floatFromInt(slots)) - 1) + 1) * m.row, .name = spanName(u, rec, calls_was, q, o.pc), .newest = q == 0 and p_span < 0.5, .open = false, .shows = 1 - p_span }; + 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. It // sets off 18 f after rsp's strike (`time.pin`): 24 f to the next @@ -749,6 +786,8 @@ pub const Stack = struct { // 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.address, .y = y, .w = if (hops.n > 0) hops.x[0] + hops.w[0] - theme.metric.slot.address else 120, .h = m.row }); + // Its value, where it may be an address: its first hop. + if (hops.n > 0) if (if (fades) word_is else (Recording.word(now.shownAt(addr, 8), addr, 8) catch null)) |value| ties.show(u, value, .{ .x = hops.x[0], .y = y, .w = hops.w[0], .h = m.row }, .stack, addr, 0, box.w); ties.anchor(u, .{ .slot_pin = addr }, .{ .x = theme.metric.slot.lane, .y = y, .w = theme.metric.slot.lane_end - theme.metric.slot.lane, .h = m.row }); } } @@ -764,7 +803,8 @@ pub const Stack = struct { hexdump.pointerArcs(&arcs, now, word.addr, word.y, at_rows.items, 8, .{ top - m.pad, box.h - m.pad }, false, false); if (arcs.n == before) continue; // Its step's alone: it goes with the advance (18 f), not in the next step's first frame. - if (saved and touched) arcs.items[before].shows *= 1 - std.math.clamp((now.time - now.plan.advance) / time.read.out, 0, 1); + // And it comes as the step begins (12 f), not in its first frame. + if ((saved or saved_was[0]) and touched) arcs.items[before].shows *= @min(1 - std.math.clamp((now.time - now.plan.advance) / time.read.out, 0, 1), if (now.resting()) 1 else std.math.clamp(now.time / time.quick, 0, 1)); // A word becoming a saved rbp, or no longer one, with the step: its arc goes or comes as its role does (12 f). if (!touched and saved != saved_was[0]) arcs.items[before].shows *= if (saved) 1 - recast else recast; } @@ -772,7 +812,7 @@ pub const Stack = struct { // Where the window is, for a link to a word outside it. const lane_at = u.at.xf.apply(.{ theme.metric.slot.lane, top }); const row_px = u.at.xf.apply(.{ 0, top + m.row })[1] - lane_at[1]; - if (!ui.mapping) ties.stack_window = .{ .first = window[0], .slots = slots, .x = lane_at[0], .top = lane_at[1], .row = row_px }; + if (!ui.mapping) ties.of(u.f).stack_window = .{ .first = window[0], .slots = slots, .x = lane_at[0], .top = lane_at[1], .row = row_px }; // The travelling tags: both of them at one word share a pin. var places: [2]f32 = undefined; var olds: [2]f32 = undefined; @@ -786,7 +826,7 @@ pub const Stack = struct { place.* = std.math.lerp(at_old, at_new, goes(now, was, is, name)); } // `tied`: rsp's move on its pin as it travels, counting a row at a time, held to the advance and crossfading to the bare name (12 f). - const amount_shows: f32 = if (tied and now.walking() and pin_sp != null and now.time >= now.plan.pins[0]) 1 - std.math.clamp((now.time - now.plan.advance) / time.quick, 0, 1) else 0; + const amount_shows: f32 = if (tied and now.walking() and pin_sp != null and now.time >= now.plan.pins[0]) @min(std.math.clamp((now.time - now.plan.pins[0]) / time.strike.in, 0, 1), 1 - std.math.clamp((now.time - now.plan.advance) / time.quick, 0, 1)) else 0; for (travel, places[0..travel.len], olds[0..travel.len], 0..) |name, place, old, i| { if (i == 1 and @abs(places[0] - place) < 0.05) continue; if (place < (if (tied) @as(f32, -1) else -0.5) or place > (if (tied) slots_f else slots_f - 0.5)) continue; @@ -805,10 +845,10 @@ pub const Stack = struct { if (crossed > 0.05) u.faded(amount_shows).bracket(theme.metric.arc.lanes[0], top + @min(place, old) * m.row + 2, top + @max(place, old) * m.row - 2, theme.mark(.write).solid, theme.metric.bracket.tie, 1, false); } else u.pinRow(x, top + place * m.row, names_, theme.color.region.stack); } - for (spans[0..n_spans]) |sp| if (sp.was) |was_name| { + for (spans[0..n_spans]) |sp| if (sp.shows > 0) if (sp.was) |was_name| { rows.span(v.faded(1 - renamed), map.content(box.w), sp.y0, sp.y1, was_name, sp.newest, sp.open); rows.span(v.faded(renamed), map.content(box.w), sp.y0, sp.y1, sp.name, sp.newest, sp.open); - } else rows.span(v, map.content(box.w), sp.y0, sp.y1, sp.name, sp.newest, sp.open); + } else rows.span(v.faded(sp.shows), map.content(box.w), sp.y0, sp.y1, sp.name, sp.newest, sp.open); veiled(u, box, now.veil); if (k.part == .stack) map.strip(.stack, u, box); } diff --git a/anim/src/cursor.zig b/anim/src/cursor.zig index 5cb625a..e9aab67 100644 --- a/anim/src/cursor.zig +++ b/anim/src/cursor.zig @@ -32,6 +32,14 @@ pub fn glide(t: f32) f32 { return theme.ease(.glide, t); } +/// `glide` for a scroll of `px` pixels over `seconds`, at least a pixel a +/// frame from rest: a glide's first frames are each under a pixel, and rows +/// drawn on whole pixels would step one and stand still a frame. +pub fn glidePixels(t: f32, seconds: f32, px: f32) f32 { + if (px < 1) return glide(t); + return @min(@max(glide(t), t * seconds * 60 / px), 1); +} + /// For things that answer the program (the mark, cards, tags, an arrow /// growing): off promptly, a long settle. pub fn standard(t: f32) f32 { @@ -292,6 +300,9 @@ pub const Cursor = struct { sprint_veil: anim.Value, /// Steps taken. count: anim.Value, + /// The `aim` relation's knob (design/README.md, "4. Ties"): 0 off (the + /// default), 1 standing (in and out over 18 f), 2 for the step. + aim_knob: anim.Value, /// The same values a little behind (`time.minimap_lag`, then a frame /// later each, `time.minimap_fade` of them): what the minimap draws /// from, secondary action that never starts on a primary onset's frame @@ -321,6 +332,7 @@ pub const Cursor = struct { .veil = s.value(0), .sprint_veil = s.value(0), .count = s.value(0), + .aim_knob = s.value(0), .lags = undefined, .first = start, .last = start, @@ -762,6 +774,20 @@ pub const Cursor = struct { } }; + /// The `aim` relation's knob from here on (design/README.md, "4. Ties": + /// off unless the author turns it on, for a scene or a beat): `.standing` + /// draws the aims of the words on screen, coming and going over 18 f; + /// `.step` those of the words a walked step writes or reads. + pub fn aim(c: Cursor, s: *anim.Frame, knob: enum { off, step, standing }) void { + // Over what follows: the timeline's cursor stays where it was. + const start = s.cursor; + defer s.cursor = start; + switch (knob) { + .off, .standing => s.play(.{c.aim_knob.to(if (knob == .off) 0 else 1)}, .{ .seconds = 18.0 / 60.0, .ease = anim.ease.linear }), + .step => s.play(.{c.aim_knob.to(2)}, .{ .seconds = 0 }), + } + } + /// There at once, with nothing struck: a cut. pub fn jump(c: Cursor, s: *anim.Frame, to: u64) void { const Jump = struct { @@ -797,6 +823,7 @@ pub const Cursor = struct { .crossings = c.levels.crossings, .annotation = c.levels.annotation, .way = .{ c.first, c.last }, + .aim = placed.value(c.aim_knob), }; var plan: [Plan.values]f32 = undefined; for (&plan, c.plan) |*is, v| is.* = placed.value(v); @@ -869,6 +896,8 @@ pub const Now = struct { annotation: @FieldType(Levels, "annotation") = .tied, /// The scene's way through the recording: its first moment and its last. way: [2]u64 = .{ 0, 0 }, + /// The `aim` knob: 0 off, up to 1 standing (coming or going), 2 for the step. + aim: f32 = 0, /// The program's state as shown. pub fn moment(n: Now) Recording.Moment { @@ -1069,7 +1098,8 @@ pub const Now = struct { if (n.resting()) return .ember; if (since_strike < 0) { var armed = was; - if (since_strike >= -s.arm) armed.arm = std.math.clamp((since_strike + s.arm) / time.stagger, 0, 1); + // In over 4 f (the catalogue's 2 f left a frame of a few pixels: a pop). + if (since_strike >= -s.arm) armed.arm = std.math.clamp((since_strike + s.arm) / (2 * time.stagger), 0, 1); return armed; } const in = std.math.clamp(since_strike / s.in, 0, 1); diff --git a/anim/src/descent.zig b/anim/src/descent.zig index ff478df..ad3a5c5 100644 --- a/anim/src/descent.zig +++ b/anim/src/descent.zig @@ -123,8 +123,11 @@ pub const Descent = struct { const now = d.cursor.now(placed); const rec = d.cursor.rec; const room = theme.layout.rowsIn(box.h); - const before = layout(u, rec, now.stops[1], room, d.root); - const after = layout(u, rec, now.stops[0], room, d.root); + // The panel growing or shrinking at rest (a column's change): the rows of + // its two heights' layouts glide between them, the rest fade at the edge; never empty. + const resize = if (now.resting()) d.stage.resizing(placed, .disasm) else null; + const before = layout(u, rec, now.stops[if (resize != null) 0 else 1], if (resize) |r| theme.layout.rowsIn(r.from) else room, d.root); + const after = layout(u, rec, now.stops[0], if (resize) |r| theme.layout.rowsIn(r.to) else room, d.root); // On the map its box is as long as the rows it has wanted: not 69 for a function of 30. if (ui.mapping) map.measure(.disasm, @max(before.items.len, after.items.len)); const going = now.advancing(); @@ -150,8 +153,10 @@ pub const Descent = struct { // How far the rows both lists have are on their way, and how much // of each that leaves or comes shows: the verb's timetable. + // At rest `going` is 1; a resize slides by its own progress. + const slide = if (resize) |r| r.p else going; const move: f32 = switch (kind) { - .same => cursors.glide(going), + .same => if (resize != null) slide else cursors.glide(going), .down => cursors.glide(clamp01((tm - f(78)) / f(18))), .through => cursors.glide(clamp01((tm - f(36)) / f(18))), .up => cursors.glide(clamp01((tm - f(84)) / f(18))), @@ -176,7 +181,7 @@ pub const Descent = struct { const it = before.items[i]; if (find(after.items, it.key)) |_| continue; const shows: f32 = switch (kind) { - .same => 1 - clamp01(2 * going), + .same => 1 - clamp01(2 * slide), .down => 1 - clamp01((tm - f(66)) / f(12)), .through => 1 - clamp01((tm - f(24)) / f(12)), .up => 1 - clamp01((tm - f(48) - @as(f32, @floatFromInt(leaving)) * f(2)) / f(12)), @@ -199,7 +204,7 @@ pub const Descent = struct { } const head = it.what == .head; const shows: f32 = switch (kind) { - .same => clamp01(2 * going - 1), + .same => clamp01(2 * slide - 1), .down => if (head) clamp01((tm - f(108)) / f(12)) else clamp01((tm - f(114) - @as(f32, @floatFromInt(arriving)) * f(2)) / f(12)), .through => if (head) clamp01((tm - f(66)) / f(12)) else clamp01((tm - f(72) - @as(f32, @floatFromInt(arriving)) * f(2)) / f(12)), .up => clamp01((tm - f(102)) / f(12)), @@ -226,7 +231,7 @@ pub const Descent = struct { .up => 1 - clamp01((tm - f(48)) / f(12)), }, // The one it lands on, with the advance. - if (kind == .same) 1 else clamp01(going * 2), + if (kind == .same) 1 else clamp01(going * 2 - 1), }; // A crossing stepped over: the kernel's window opens under the call // row, past the arguments hanging under it; the rows after them make @@ -256,10 +261,10 @@ pub const Descent = struct { // In one window the plaque slides from row to row, with the advance. var mark: ?struct { y: f32, shows: f32 } = null; if (kind == .same) { - if (pc_y[0] != null and pc_y[1] != null) mark = .{ .y = std.math.lerp(pc_y[0].?, pc_y[1].?, cursors.standard(going)), .shows = 1 } else if (pc_y[1]) |y| { - mark = .{ .y = y, .shows = clamp01(2 * going - 1) }; + if (pc_y[0] != null and pc_y[1] != null) mark = .{ .y = std.math.lerp(pc_y[0].?, pc_y[1].?, if (resize != null) slide else cursors.standard(going)), .shows = 1 } else if (pc_y[1]) |y| { + mark = .{ .y = y, .shows = clamp01(2 * slide - 1) }; } else if (pc_y[0]) |y| { - mark = .{ .y = y, .shows = 1 - clamp01(2 * going) }; + mark = .{ .y = y, .shows = 1 - clamp01(2 * slide) }; } } const fire = now.fires(.disasm); @@ -269,7 +274,8 @@ pub const Descent = struct { } // Which rows ran in the last three steps: the trail. - const ran = recentRows(a, now, if (going >= 0.5) 0 else 1); + const ran_before = recentRows(a, now, 1); + const ran_after = recentRows(a, now, 0); // The line the source panel is on, in the file it shows: rows of that file carry their numbers. const current = rec.shown[marked]; const current_line = current.line; @@ -280,7 +286,6 @@ pub const Descent = struct { var last_line: ?u32 = null; var last_window: ?u8 = null; const dd: disasm.Disasm = .{ .cursor = d.cursor, .stage = d.stage }; - const base: usize = if (going >= 0.5) 0 else 1; // Each window's blocks (`graph`), read once: a rule over each one's first row, its visits where the row has room. var rules: [8]?graph.Rules = @splat(null); for (placed_items.items) |p| { @@ -306,39 +311,62 @@ pub const Descent = struct { const window_items = windowOf(placed_items.items, p.item.window); var addrs: [80]u64 = undefined; var n: usize = 0; - for (window_items) |w| if (w.item.what == .insn and n < addrs.len) { + // Its own rows that show: not another window's between them, nor a row gone at rest. + for (window_items) |w| if (w.item.what == .insn and w.item.window == p.item.window and w.shows > 0 and n < addrs.len) { addrs[n] = w.item.key; n += 1; }; const lead = ui.shared(addrs[0..n]); const wide = @as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv; - const line = if (row.outside or row.src != current.src) null else row.line; - const state: disasm.Disasm.State = switch (p.item.state) { - // The row the plaque has not reached yet is ahead. - .current => if (p.old == null or p.old.?.state != .current) (if (going >= 0.5) .current else .ahead) else if (p.new == null or p.new.?.state != .current) (if (going < 0.5) .current else .ahead) else .current, - .waiting => .{ .waiting = p.item.at }, - .pass => .{ .ran = .{ .k = 0, .at = p.item.at } }, - .plain => if (ranOf(ran, row.addr)) |r| .{ .ran = r } else .ahead, - }; - // The marks at the row's left: the trail, the ring, the pass. - switch (p.item.state) { - .plain => if (ranOf(ran, row.addr)) |r| v.trail(c.mark, y, r.k), - .pass => v.trail(c.mark, y, 0), - .waiting => { - // The ring comes as the plaque leaves; going up it becomes a trail bar. - const ring: f32 = if (p.old != null and p.old.?.state == .waiting) (if (kind == .up) 1 - clamp01((tm - f(114)) / f(12)) else 1) else if (kind == .down) clamp01((tm - f(84)) / f(12)) else 1; - ringAt(v.faded(ring), y); - if (ring < 1) v.faded(1 - ring).trail(c.mark, y, 0); - }, - .current => {}, + // The row as before the advance and as after it (the pc's row, its trail, + // the line numbers of the file the source shows): where the two differ, the + // one crossfades to the other over the advance's middle, never in a frame. + const after_side = going >= 0.5; + const across: f32 = if (kind == .same and now.resting()) 1 else clamp01((going - 0.25) * 2); + var line: ?u32 = null; + var hangs: usize = 0; + const covers = if (p.twin) covered_before > 0 else covered > 0; + for ([2]bool{ !after_side, after_side }) |side| { + const ran_s = if (side) ran_after else ran_before; + const cur_s = rec.shown[now.marks[@intFromBool(side)]]; + const line_s = if (row.outside or row.src != cur_s.src) null else row.line; + const state: disasm.Disasm.State = switch (p.item.state) { + // The row the plaque has not reached yet is ahead. + .current => if (p.old == null or p.old.?.state != .current) (if (side) .current else .ahead) else if (p.new == null or p.new.?.state != .current) (if (!side) .current else .ahead) else .current, + .waiting => .{ .waiting = p.item.at }, + .pass => .{ .ran = .{ .k = 0, .at = p.item.at } }, + .plain => if (ranOf(ran_s, row.addr)) |r| .{ .ran = r } else .ahead, + }; + // The side the advance is on draws in full where the two are the same. + const main = side == after_side; + const other_line = if (row.outside or row.src != rec.shown[now.marks[@intFromBool(!side)]].src) null else row.line; + const ran_o = if (!side) ran_after else ran_before; + const same = std.meta.eql(line_s, other_line) and cur_s.line == rec.shown[now.marks[@intFromBool(!side)]].line and p.item.state != .current and std.meta.eql(ranOf(ran_s, row.addr), ranOf(ran_o, row.addr)); + const alpha: f32 = if (same) (if (main) 1 else 0) else if (side) across else 1 - across; + if (main) line = line_s; + if (alpha <= 0) continue; + const vs = v.faded(alpha); + const base_s: usize = if (side) 0 else 1; + // The marks at the row's left: the trail, the ring, the pass. + switch (p.item.state) { + .plain => if (ranOf(ran_s, row.addr)) |r| vs.trail(c.mark, y, r.k), + .pass => vs.trail(c.mark, y, 0), + .waiting => { + // The ring comes as the plaque leaves; going up it becomes a trail bar. + const ring: f32 = if (p.old != null and p.old.?.state == .waiting) (if (kind == .up) 1 - clamp01((tm - f(114)) / f(12)) else 1) else if (kind == .down) clamp01((tm - f(84)) / f(12)) else 1; + ringAt(vs.faded(ring), y); + if (ring < 1) vs.faded(1 - ring).trail(c.mark, y, 0); + }, + .current => {}, + } + // A row drawn twice (crossfading) counts once for the arguments that hang over the rows under it. + const h = dd.insn(vs, now, row, y, map.content(box.w), widen0 + wide, line_s, line_s != last_line, cur_s.line, lead, state, base_s, covers, .{ addrs[0], addrs[n -| 1] }, null); + if (main) hangs = h; + const w = @min(p.item.window, rules.len - 1); + if (rules[w] == null) rules[w] = graph.Rules.init(u.f.scratch, rec, now.marks, .{ row.addr, row.addr }, going); + rules[w].?.draw(vs, row.addr, y, map.content(box.w), !covers and !row.outside and !dd.noted(vs, now, row, y, state, base_s, .{ addrs[0], addrs[n -| 1] }, null)); } runs.add(line != null and line.? == current_line, y, y + m.row); - // A row drawn twice (crossfading) counts once for the arguments that hang over the rows under it. - const covers = if (p.twin) covered_before > 0 else covered > 0; - const hangs = dd.insn(v, now, row, y, map.content(box.w), widen0 + wide, line, line != last_line, current_line, lead, state, base, covers, .{ addrs[0], addrs[n -| 1] }, null); - const w = @min(p.item.window, rules.len - 1); - if (rules[w] == null) rules[w] = graph.Rules.init(u.f.scratch, rec, now.marks, .{ row.addr, row.addr }, going); - rules[w].?.draw(v, row.addr, y, map.content(box.w), !covers and !row.outside and !dd.noted(v, now, row, y, state, base, .{ addrs[0], addrs[n -| 1] }, null)); if (!p.twin) covered_before = covered; covered = if (p.twin) @max(covered, hangs) else @max(covered -| 1, hangs); last_line = line; diff --git a/anim/src/disasm.zig b/anim/src/disasm.zig index 085982d..6c9e2dc 100644 --- a/anim/src/disasm.zig +++ b/anim/src/disasm.zig @@ -75,13 +75,15 @@ pub const Disasm = struct { focus: bool = false, /// On the map its box is as long as what it shows (not where it is a strip's column alone). measures: bool = true, + /// Its window this many rows whatever its box (a `pair`'s stopped run: the box shortens over its lower rows). + rows: ?usize = null, pub fn draw(d: *const Disasm, f: *sk.Frame, placed: anim.Placed) void { const box = d.stage.box(placed, .disasm); const u = context.at(f, placed, box); const now = d.cursor.now(placed); const rec = d.cursor.rec; - const room = theme.layout.rowsIn(box.h); + const room = d.rows orelse theme.layout.rowsIn(box.h); // The mark: it moves last, with the source's and rip. const going = now.advancing(); const from = listing(u, rec, now.marks[0], room); @@ -127,7 +129,7 @@ pub const Disasm = struct { fade = if (ui.mapping) 1 else @abs(2 * going - 1); } } - const scroll = std.math.lerp(offsets[0], offsets[1], cursors.glide(going)); + const scroll = std.math.lerp(offsets[0], offsets[1], cursors.glidePixels(going, now.plan.travel, @abs(offsets[1] - offsets[0]) * m.row * u.at.scale)); const lit = if (fade < 1) u.faded(fade) else u; // Where the pc's plaque is: it slides from the row it was on to the @@ -144,7 +146,6 @@ pub const Disasm = struct { const base: usize = if (going >= 0.5) 0 else 1; // The line the source panel is on, in the file it shows: rows of that file carry their numbers. const current = rec.shown[now.marks[if (going >= 0.5) 1 else 0]]; - const current_line = current.line; // The addresses' shared digits, of the window the mark is in: they // change with the advance, not before it. const lead = blk: { @@ -170,17 +171,21 @@ pub const Disasm = struct { // `ran`: what the last three steps ran (every instruction, where the // recording is by instruction), the newest step's mark on each row, // and the moment it last ran at for its annotation. - const ran = u.f.scratch.alloc(?Ran, merged.len) catch return; - @memset(ran, null); - for (0..3) |k| { - const first = now.stops[@min(base + 1 + k, now.stops.len - 1)]; - const last = now.stops[base + k]; - var at = last; - // shortcut: a step through more than 4096 moments marks its last 4096. - while (at > first and last - at < 4096) { - at -= 1; - const j = rowOf(merged, rec.register(at, "rip")) orelse continue; - if (ran[j] == null) ran[j] = .{ .k = k, .at = at }; + // As before the advance and as after it (`base` 1 and 0): the row crossfades between them. + var rans: [2][]?Ran = undefined; + for (&rans, [2]usize{ 1, 0 }) |*ran, b| { + ran.* = u.f.scratch.alloc(?Ran, merged.len) catch return; + @memset(ran.*, null); + for (0..3) |k| { + const first = now.stops[@min(b + 1 + k, now.stops.len - 1)]; + const last = now.stops[b + k]; + var at = last; + // shortcut: a step through more than 4096 moments marks its last 4096. + while (at > first and last - at < 4096) { + at -= 1; + const j = rowOf(merged, rec.register(at, "rip")) orelse continue; + if (ran.*[j] == null) ran.*[j] = .{ .k = k, .at = at }; + } } } // The jump that brought control here: the instruction just before @@ -227,11 +232,31 @@ pub const Disasm = struct { map.row(.disasm, row.addr, u, .{ .x = 0, .y = y, .w = box.w, .h = m.row }); ties.anchor(u, .{ .row = row.addr }, .{ .x = 0, .y = y, .w = box.w, .h = m.row }); 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 state: State = if (is_pc) .current else if (was) |r| .{ .ran = r } else .ahead; - const hangs = d.insn(lit, now, row, y, map.content(box.w), widen, line, line != last_line, current_line, lead, state, base, covered > 0, window, echo); - rules.draw(lit, row.addr, y, map.content(box.w), covered == 0 and !row.outside and !d.noted(lit, now, row, y, state, base, window, echo)); + // The row as before the advance and as after it (its state, its trail, its + // line number): where they differ, the one crossfades to the other over the + // advance's middle, never in a frame. + const across: f32 = if (now.resting()) 1 else std.math.clamp((going - 0.25) * 2, 0, 1); + var hangs: usize = 0; + for ([2]usize{ 1, 0 }) |b| { + const cur_s = rec.shown[now.marks[1 - b]]; + const line_s = if (row.outside or row.src != cur_s.src) null else row.line; + const pc_s = row.addr == pc[1 - b]; + const was_s = if (pc_s) null else rans[1 - b][j]; + const state: State = if (pc_s) .current else if (was_s) |r| .{ .ran = r } else .ahead; + const main = b == base; + const o = 1 - b; + const cur_o = rec.shown[now.marks[1 - o]]; + const line_o = if (row.outside or row.src != cur_o.src) null else row.line; + const pc_o = row.addr == pc[1 - o]; + const same = pc_s == pc_o and std.meta.eql(line_s, line_o) and cur_s.line == cur_o.line and std.meta.eql(was_s, if (pc_o) null else rans[1 - o][j]); + const alpha: f32 = if (same) (if (main) 1 else 0) else if (b == 0) across else 1 - across; + if (alpha <= 0) continue; + const v = lit.faded(alpha); + if (was_s) |r| v.trail(c.mark, y, r.k); + const h = d.insn(v, now, row, y, map.content(box.w), widen, line_s, line_s != last_line, cur_s.line, lead, state, b, covered > 0, window, echo); + if (main) hangs = h; + rules.draw(v, row.addr, y, map.content(box.w), covered == 0 and !row.outside and !d.noted(v, now, row, y, state, b, window, echo)); + } covered = @max(covered -| 1, hangs); last_line = if (above_body) null else line; if (jumped == row.addr and !is_pc) lanes[0] = y; @@ -292,7 +317,7 @@ pub const Disasm = struct { if (!ui.mapping and now.annotation == .tied and now.walking() and (now.plan.touch >= 0 or now.plan.carry >= 0)) if (touchPc(rec, now)) |pc| if (pc == row.addr) { const a = at.at.xf.apply(.{ w + theme.strip.cost, y }); const b = at.at.xf.apply(.{ w + theme.strip.cost, y + m.row }); - ties.touch_row = .{ a[0], a[1], b[0], b[1] }; + ties.of(at.f).touch_row = .{ a[0], a[1], b[0], b[1] }; }; if (first_of_line) if (line) |l| { const num = u.print("{d}", .{l}); @@ -407,37 +432,36 @@ pub const Disasm = struct { } // `tied`: an instruction that moves rsp or rbp says the move first. if (now.annotation == .tied) if (a.stackMove(now, row, moment, after, state, base)) |note| return note; + // What it left behind is shown once it has run; in the step that + // makes it, it fades in from the CPU's strike (12 f), never in a frame. + const appears: f32 = if (state == .current and after != null) now.moving(.cpu, 0, theme.time.quick) else 1; + const value_at: ?u64 = switch (state) { + .ran => after, + .current => if (after != null and appears > 0) after.? else null, + .ahead, .waiting => null, + }; + const new = Say{ .u = u.faded(appears), .rec = rec, .y = y, .x = x, .room = room }; // A compare: the two values, then (once it has run) the flags it leaves. if (std.mem.eql(u8, mn, "cmp") or std.mem.eql(u8, mn, "test")) { const left = a.compared(row, moment, touches[0]); var end = a.word(x, left[0], t.primary); end = a.word(end, " : ", t.faint); end = a.word(end, left[1], t.primary); - const left_at: ?u64 = switch (state) { - .ran => after, - .current => if (after != null and now.landed(.cpu, 0)) after else null, - .ahead, .waiting => null, - }; - if (left_at) |l| { + if (value_at) |l| { var buf: [256]u8 = undefined; const next = rec.instruction(moment, row.addr + row.len, &buf); var mask = if (next) |n| flagsRead((Insn{ .addr = 0, .len = 0, .text = n.text }).mnemonic()) else 0; if (mask == 0) mask = flag_bits.cf | flag_bits.zf | flag_bits.sf | flag_bits.of; - end = flags(u, end + 2 * adv, y, rec.register(l, "eflags"), mask, if (echo) |e| if (e.addr == row.addr) e.shows else 0 else 0); + end = flags(new.u, end + 2 * adv, y, rec.register(l, "eflags"), mask, if (echo) |e| if (e.addr == row.addr) e.shows else 0 else 0); } return .{ .drawn = true, .end = end }; } // The rest is what it left behind, or where it reads: by what it is. - const value_at: ?u64 = switch (state) { - .ran => after, - .current => if (after != null and now.landed(.cpu, 0)) after.? else null, - .ahead, .waiting => null, - }; // A place the C library's layout names: the canary. if (std.mem.indexOf(u8, row.text, "fs:[0x28]") != null) { const end = a.word(x, if (x + 35 * adv <= room) "the stack's canary" else "canary", t.dim); const word_ = if (touches[0]) |touch| Recording.word(rec.moment(value_at orelse moment), touch.addr, 8) catch null else null; - if (word_) |v| return .{ .drawn = true, .end = a.word(end + adv, u.print("{x}", .{v}), t.primary) }; + if (word_) |v| return .{ .drawn = true, .end = (if (value_at != null) new else a).word(end + adv, u.print("{x}", .{v}), t.primary) }; u.unknown(.{ .x = end + adv, .y = y, .w = 24, .h = m.row }); return .{ .drawn = true, .end = end + adv + 24 }; } @@ -445,8 +469,8 @@ pub const Disasm = struct { if (std.mem.eql(u8, mn, "lea")) { const at = value_at orelse return .{}; const reg = written(row) orelse return .{}; - const end = a.word(x, "=", t.faint); - return .{ .drawn = true, .end = rows.chain(u, end + adv, y, rec.moment(at), rec.register(at, reg), room, .{}).end }; + const end = new.word(x, "=", t.faint); + return .{ .drawn = true, .end = rows.chain(new.u, end + adv, y, rec.moment(at), rec.register(at, reg), room, .{}).end }; } // A `rep`: how many times, how wide each, and where it goes. if (std.mem.startsWith(u8, mn, "rep")) { @@ -494,9 +518,9 @@ pub const Disasm = struct { const reg = written(row) orelse return .{}; const at = value_at orelse return .{}; const value = rec.register(at, reg); - u.text(.mono, size, x, base_y, reg, t.dim); + new.u.text(.mono, size, x, base_y, reg, t.dim); // `tied`: its first value (the registers' row has its chain, struck in the same frame). - return .{ .drawn = true, .end = rows.chain(u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, rec.moment(at), value, room, .{ .most = if (now.annotation == .tied) 1 else 6 }).end }; + return .{ .drawn = true, .end = rows.chain(new.u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, rec.moment(at), value, room, .{ .most = if (now.annotation == .tied) 1 else 6 }).end }; } }; @@ -607,12 +631,15 @@ const Say = struct { var end = a.word(a.x, "rbp = rsp", t.primary); // Its value once rbp has landed, struck with it. const lands = ties.strikeDelay(now, cursors.bp_index); + // In from rbp's strike (12 f), never in a frame. + const shows: f32 = if (state == .current and after != null) now.moving(.cpu, -lands, theme.time.quick) else 1; const value_at: ?u64 = switch (state) { .ran => after, - .current => if (after != null and now.landed(.cpu, lands)) after.? else null, + .current => if (after != null and shows > 0) after.? else null, .ahead, .waiting => null, }; - if (value_at) |v| end = a.struck(end + adv, a.u.print("{x}", .{a.rec.register(v, "rbp")}), if (state == .current and base == 1) now.heat(now.registerAge(cursors.bp_index), null, now.since(.cpu, lands)) else .none); + const b: Say = .{ .u = a.u.faded(shows), .rec = a.rec, .y = a.y, .x = a.x, .room = a.room }; + if (value_at) |v| end = b.struck(end + adv, a.u.print("{x}", .{a.rec.register(v, "rbp")}), if (state == .current and base == 1) now.heat(now.registerAge(cursors.bp_index), null, now.since(.cpu, lands)) else .none); return .{ .drawn = true, .end = end }; } else return null; var role: ?Role = null; diff --git a/anim/src/graph.zig b/anim/src/graph.zig index 01b4ac7..9eb6f2d 100644 --- a/anim/src/graph.zig +++ b/anim/src/graph.zig @@ -2035,7 +2035,11 @@ pub const Blocks = struct { const name = ui.symbol(u, full); const short = name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len]; const title = if (std.mem.indexOfScalar(u8, full, '!')) |bang| u.print("the blocks of {s} \u{00b7} {s}", .{ short, full[0..bang] }) else u.print("the blocks of {s}", .{short}); - _ = u.panel(box.w, box.h, title, .{ .focus = b.focus, .note = if (v.g.rings.len > 0) "its blocks \u{00b7} the visits so far \u{00b7} the path \u{00b7} the loops' turns" else "its blocks \u{00b7} the visits so far \u{00b7} the path" }); + const note = if (v.g.rings.len > 0) "its blocks \u{00b7} the visits so far \u{00b7} the path \u{00b7} the loops' turns" else "its blocks \u{00b7} the visits so far \u{00b7} the path"; + _ = u.panel(box.w, box.h, title, .{ .focus = b.focus }); + // Its labels stay inside its box at every size: the note fades where it no longer fits beside the title. + const need = 28 + u.width(.sans_medium, theme.size.sans.tag, title) + 24 + u.width(.sans, theme.size.sans.micro, note) + 10; + u.faded(std.math.clamp((box.w - need) / 48, 0, 1)).tagNote(box.w, note); u.clip(.{ .x = rule, .y = m.tag, .w = room[0] * z, .h = room[1] * z }); var big = u.moved(rule, m.tag); big.at.xf = big.at.xf.mul(.scale(z, z)); diff --git a/anim/src/hexdump.zig b/anim/src/hexdump.zig index a35f091..9b39bf6 100644 --- a/anim/src/hexdump.zig +++ b/anim/src/hexdump.zig @@ -46,10 +46,15 @@ pub fn kindOf(things: []const objects.Object, moment: Recording.Moment, addr: u6 /// The rows of a region (`lo .. hi`, sixteen-aligned) a dump of `count` /// rows shows: all of them, or a window round the first the step touched. pub fn window(now: cursors.Now, lo: u64, hi: u64, count: usize) u64 { + return windowAt(now.rec, now.stops[1], now.stops[0], lo, hi, count); +} + +/// The same for the step from moment `from` to `to`. +pub fn windowAt(rec: *const Recording, from: u64, to: u64, lo: u64, hi: u64, count: usize) u64 { const all = (hi - lo) / 16; if (all <= count) return lo; var touched: ?u64 = null; - for ([_][]const Recording.Span{ now.rec.written(now.stops[1], now.stops[0]), now.rec.read(now.stops[1], now.stops[0]) }) |spans| for (spans) |span| { + for ([_][]const Recording.Span{ rec.written(from, to), rec.read(from, to) }) |spans| for (spans) |span| { if (touched == null and span.addr >= lo and span.addr < hi) touched = span.addr & ~@as(u64, 15); }; const at = touched orelse lo; @@ -368,6 +373,20 @@ pub fn pointerArcs(arcs: *rows.Arcs, now: cursors.Now, field: u64, from: f32, sh const time_arc = theme.time.arc; +/// What the kernel fills strikes a byte every 2 f, as it lands: the +/// kernel's fill is no write the recording has, so by its own times, +/// cooling with the advance (`run` from `here`). +fn givenStrike(now: cursors.Now, of: anytype, here: u64, run: *rows.Run) void { + const g = of.given orelse return; + const since = g.since orelse return; + if (here + run.len <= g.addr or here >= g.addr + g.bytes.len) return; + const first = @max(here, g.addr) - g.addr; + const struck = since - @as(f32, @floatFromInt(first)) * @import("syscalls.zig").Plan.byte; + if (struck >= 0) run.heat = .{ .level = 1, .solid = 1 - std.math.clamp((now.time - now.plan.advance) / theme.time.strike.cool, 0, 1), .in = std.math.clamp(struck / theme.time.strike.in, 0, 1) }; + run.changed = .{ @intCast(@max(here, g.addr) - here), @intCast(@min(here + run.len, g.addr + g.bytes.len) - 1 - here) }; + run.apart = 2; +} + /// One arc from the row at `from` to the row of `shown` that holds /// `target`; a stub toward the rule for one in the region past them, only /// for the step's (`state.hot`). @@ -391,6 +410,8 @@ fn aim(arcs: *rows.Arcs, now: cursors.Now, field: u64, target: u64, from: f32, s // Past the rows: a stub, in the step that touches it, when it is the same region's. if (!state.hot or rows.regionOf(moment, target) != rows.regionOf(moment, field) or rows.regionOf(moment, target) == .none) return; arc.stub = true; + // Its step's alone (not a loupe's, always full): in as the step begins (12 f), out with the advance, never in a frame. + if (state.full < 1) arc.shows *= if (now.resting()) 0 else @min(std.math.clamp(now.time / theme.time.quick, 0, 1), 1 - std.math.clamp((now.time - now.plan.advance) / theme.time.read.out, 0, 1)); arc.to = if (target < shown[0].addr) rule[0] else rule[1]; arcs.add(arc); } @@ -606,7 +627,8 @@ fn fieldRow(u: ui.Ui, now: cursors.Now, y: f32, addr: u64, moment: Recording.Mom if (of.given) |g| for (0..16) |i| { const a = addr + i; if (a < g.addr or a >= g.addr + g.bytes.len) continue; - if (g.since) |since| if (since < @as(f32, @floatFromInt(a - g.addr)) * @import("syscalls.zig").Plan.byte) continue; + // Each byte as its strike lands (s+3), the fill coming in under it: never in a frame. + if (g.since) |since| if (since < @as(f32, @floatFromInt(a - g.addr)) * @import("syscalls.zig").Plan.byte + theme.time.strike.in / 2.0) continue; given_values[i] = g.bytes[a - g.addr]; given_known[i] = true; gives = true; @@ -643,6 +665,7 @@ fn fieldRow(u: ui.Ui, now: cursors.Now, y: f32, addr: u64, moment: Recording.Mom if (of.struck) |since| run.heat = now.writtenAt(here, run.len, since - @as(f32, @floatFromInt(field_k)) * cursors.write_apart); // What the kernel fills lands a byte every 2 f. if (@import("syscalls.zig").filledAt(now, here) != null) run.apart = 2; + givenStrike(now, of, here, &run); var framed: f32 = 0; if (fl.mark) |k| if (k < of.marks.len) { framed = of.marks[k]; @@ -669,6 +692,7 @@ fn fieldRow(u: ui.Ui, now: cursors.Now, y: f32, addr: u64, moment: Recording.Mom }; run.len = @intCast(end - at); readings[n] = .{ .at = at, .len = run.len, .reads = .bytes }; + givenStrike(now, of, here, &run); } runs[n] = run; n += 1; diff --git a/anim/src/loupe.zig b/anim/src/loupe.zig index d3ae878..ae709d5 100644 --- a/anim/src/loupe.zig +++ b/anim/src/loupe.zig @@ -94,7 +94,7 @@ pub const Loupe = struct { switch (l.from) { .register => |name| { const i = context.index(name) orelse return null; - const px = ties.find(.{ .register = i }) orelse return null; + const px = ties.find(u.f, .{ .register = i }) orelse return null; const back = u.at.xf.invert(); const a = back.apply(.{ px[0], px[1] }); const b = back.apply(.{ px[2], px[3] }); @@ -112,7 +112,7 @@ pub const Loupe = struct { right = parent.box.x + 120; }, .row => |row| { - const px = ties.find(.{ .dump_run = row.at }) orelse return null; + const px = ties.find(u.f, .{ .dump_run = row.at }) orelse return null; const back = u.at.xf.invert(); const a = back.apply(.{ px[0], px[1] }); const b = back.apply(.{ px[2], px[3] }); diff --git a/anim/src/nodes.zig b/anim/src/nodes.zig index 7c842d3..5218d7f 100644 --- a/anim/src/nodes.zig +++ b/anim/src/nodes.zig @@ -73,10 +73,22 @@ pub const Nodes = struct { if (lo < hi) { @import("map.zig").measure(.view, (hi - lo) / 16); const count = theme.layout.rowsIn(g.stage.box(placed, .view).h); - const first = hexdump.window(now, lo, hi, count); + // Its window round the rows the step touches: from the last step's, scrolled + // (whole rows, 24 f, as the step begins), never a jump. + const first_new = hexdump.window(now, lo, hi, count); + const first_old = hexdump.windowAt(rec, now.stops[2], now.stops[1], lo, hi, count); + const scroll = if (now.resting() or first_old == first_new) 1 else cursors.glide(std.math.clamp(now.time / time.move, 0, 1)); + const first = if (scroll >= 0.5) first_new else first_old; const shown = @min(count, (hi - first) / 16); const v = hexdump.panel(f, placed, g.stage, u.print("the heap, {x} to {x}", .{ first, first + 16 * shown - 1 }), &legend); - if (v.rows > 0) hexdump.draw(v.u, now, 0, m.tag + m.pad, first, @min(shown, v.rows), .{ .things = things }); + if (v.rows > 0) { + const top = @min(first_old, first_new); + const rows_apart: f32 = @floatFromInt((@max(first_old, first_new) - top) / 16); + const at = std.math.lerp(@as(f32, @floatFromInt((first_old - top) / 16)), @as(f32, @floatFromInt((first_new - top) / 16)), scroll); + v.u.clip(.{ .x = 0, .y = m.tag, .w = g.stage.box(placed, .view).w, .h = @as(f32, @floatFromInt(@min(shown, v.rows))) * m.row + 2 * m.pad }); + hexdump.draw(v.u, now, 0, m.tag + m.pad - at * m.row, top, @min(@min(shown, v.rows) + @as(usize, @intFromFloat(rows_apart)), (hi - top) / 16), .{ .things = things }); + v.u.unclip(); + } if (v.rows > 0) @import("map.zig").window(.view, .{ first, first + 16 * (@min(shown, v.rows) -| 1) }, .{ first, first + 16 * (@min(shown, v.rows) -| 1) }, 1); v.veil(now); u.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }); @@ -335,6 +347,27 @@ pub const Nodes = struct { std.mem.swap(u24, &inks.items[k - 1], &inks.items[k]); } } + // Two names whose order the step turns (one reassigned to the same node): the names + // fade out in the old order and in the new one over the step's first 24 f, never swapped in a frame. + if (out.items.len == 2 and !now.resting() and now.stops[1] != now.stops[2]) both: { + // Both on the pin before the step too. + const then = g.namesAt(u, now.stops[1], addr); + for (out.items) |name| { + if (for (then) |o| { + if (std.mem.eql(u8, o, name)) break false; + } else true) break :both; + } + const a = g.arrivalAt(u, now.stops[1], now.stops[2], out.items[0], addr); + const b = g.arrivalAt(u, now.stops[1], now.stops[2], out.items[1], addr); + if (a > b) { + const p = std.math.clamp(now.time / (2 * time.quick), 0, 1); + text = @min(text, @abs(2 * p - 1)); + if (p < 0.5) { + std.mem.swap([]const u8, &out.items[0], &out.items[1]); + std.mem.swap(u24, &inks.items[0], &inks.items[1]); + } + } + } // Both sides taken: a variable the scene names (what the narration // follows) takes the right from a register, which is counted. if (out.items.len > 2 and context.index(out.items[1]) != null) for (out.items[2..], 2..) |name, j| { @@ -348,7 +381,13 @@ pub const Nodes = struct { }; if (out.items.len == 1) { const first_before = g.firstBefore(u, now, addr, was); - if (first_before != null and !std.mem.eql(u8, first_before.?, out.items[0])) { + // Kept on the right in the step before (the other had just left): it goes over + // to the left at the start of this one, fading out and in (24 f), never in a frame. + const older = g.namesAt(u, now.stops[2], addr); + const was_right = now.stops[2] != now.stops[1] and older.len >= 2 and !std.mem.eql(u8, older[0], out.items[0]); + const over = if (now.resting()) 1 else std.math.clamp(now.time / (2 * time.quick), 0, 1); + if (was_right and first_before == null) text = @min(text, @abs(2 * over - 1)); + if ((first_before != null and !std.mem.eql(u8, first_before.?, out.items[0])) or (was_right and first_before == null and over < 0.5)) { out.insert(u.f.scratch, 0, "") catch {}; inks.insert(u.f.scratch, 0, t.primary) catch {}; } @@ -360,14 +399,19 @@ pub const Nodes = struct { /// became it (a variable's, its last assignment), as of the stop shown /// (or the one before, for a name that is leaving). fn arrival(g: *const Nodes, u: ui.Ui, now: cursors.Now, name: []const u8, addr: u64) u64 { + return g.arrivalAt(u, now.stops[0], now.stops[1], name, addr); + } + + /// The same, as of stop `here` (the one before it `before`). + fn arrivalAt(g: *const Nodes, u: ui.Ui, here: u64, before: u64, name: []const u8, addr: u64) u64 { const rec = g.cursor.rec; if (context.index(name)) |_| { - var i = if (rec.registers[now.stops[0]].named(name) == addr) now.stops[0] else now.stops[1]; + var i = if (rec.registers[here].named(name) == addr) here else before; while (i > 0 and rec.registers[i - 1].named(name) == addr) i -= 1; return i; } - const v = rec.variable(u.f.scratch, now.moment(), name) orelse return now.stops[0]; - var i = if ((Recording.word(now.moment(), v.addr, 8) catch null) == addr) now.stops[0] else now.stops[1]; + const v = rec.variable(u.f.scratch, rec.moment(here), name) orelse return here; + var i = if ((Recording.word(rec.moment(here), v.addr, 8) catch null) == addr) here else before; // Its assignment: a store, of a new value or of the one its slot held. while (i > 0 and !Recording.touches(rec.written(i - 1, i), v.addr, 8) and !Recording.touches(rec.storedSame(i - 1, i), v.addr, 8)) i -= 1; return i; @@ -395,6 +439,24 @@ pub const Nodes = struct { return out.items; } + /// The names on `addr`'s pin at moment `at`. + fn namesAt(g: *const Nodes, u: ui.Ui, at: u64, addr: u64) []const []const u8 { + const rec = g.cursor.rec; + const mo = rec.moment(at); + var out: std.ArrayList([]const u8) = .empty; + for (g.track) |name| { + const v = rec.variable(u.f.scratch, mo, name) orelse continue; + if (!rec.assigned(v, mo.index)) continue; + if ((Recording.word(mo, v.addr, 8) catch null) != addr) continue; + out.append(u.f.scratch, name) catch break; + } + const regs = (mo.regs(rec.tid) catch null) orelse return out.items; + if (!g.quiet) for (theme.metric.all_registers[0..16]) |name| if (regs.named(name) == addr) { + out.append(u.f.scratch, name) catch break; + }; + return out.items; + } + /// The ink of where variable `name` lives: stack for a local, data for a global. fn home(g: *const Nodes, u: ui.Ui, now: cursors.Now, name: []const u8) u24 { const v = g.cursor.rec.variable(u.f.scratch, now.moment(), name) orelse return t.primary; diff --git a/anim/src/pair.zig b/anim/src/pair.zig new file mode 100644 index 0000000..0f9cfe0 --- /dev/null +++ b/anim/src/pair.zig @@ -0,0 +1,780 @@ +//! `pair` (design/README.md, "pair"): two runs of one program seen against +//! each other, a split of the working frame. The shared source across both +//! columns (the left run's mark on its number, the right run's ranged right), +//! each run's disassembly, registers and frame on its side of the seam (the +//! gutter, 944 to 976); a row one run has and the other has not (`only +//! here`) a `dim` bar on its seam-side edge, a value that differs from its +//! counterpart (`differs`) a `bright` one; one clock with both moments, one +//! caption. Each side is a `Stage` of its own (`split`), so a panel of the +//! context (`Disasm`, `Registers`, `Source`) draws there as anywhere, on its +//! run's cursor; what the pair adds is here: the frame as bytes eight a row +//! (`hexdump` `eight`: `Frame`), a stopped run's output (`Report`), the +//! marks across the seam (`Marks`), the clock (`Clock`). +const std = @import("std"); +const sk = @import("sketch"); +const anim = @import("anim"); +const zt = @import("ztrace"); +const ui = @import("ui.zig"); +const rows = @import("rows.zig"); +const cursors = @import("cursor.zig"); +const context = @import("context.zig"); +const ties = @import("ties.zig"); +const words = @import("words.zig"); +const Stage = @import("stage.zig").Stage; +const Recording = @import("Recording.zig"); +const theme = ui.theme; +const Rect = ui.Rect; +const Split = theme.layout.Split; +const t = theme.color.text; +const m = theme.metric.context; +const size = theme.size.mono.context; +const adv = size * 3 / 5; + +pub const Side = enum { left, right }; + +/// The pair's boxes on one side of the seam (`pair` in design/README.md): +/// the source shared, five lines across both columns (48 to 200, the left +/// side's; the right has none), then in each column the disassembly, nine +/// rows (212 to 460), the registers, four (472 to 600), the frame, ten (612 +/// to 884). `stopped`: the right run once it has stopped, its disassembly +/// down to the call that stopped it (five rows, to 364) and its output in +/// `view` (six rows, 376 to 552), in place of its registers. +pub fn split(side: Side, stopped: bool) Split { + const ph = theme.layout.panelH; + const gap = theme.canvas.row_gap; + const x: f32 = if (side == .left) theme.layout.program.x else theme.layout.state.x; + const w = theme.layout.program.w; + const top = theme.canvas.stage.y; + const none: Rect = .{ .x = x, .y = top, .w = w, .h = 0 }; + const source: Rect = .{ .x = theme.canvas.stage.x, .y = top, .w = theme.canvas.stage.w, .h = if (side == .left) ph(5) else 0 }; + const disasm: Rect = .{ .x = x, .y = top + ph(5) + gap, .w = w, .h = ph(if (stopped) 5 else 9) }; + const registers: Rect = .{ .x = x, .y = top + ph(5) + ph(9) + 2 * gap, .w = w, .h = ph(4) }; + const stack: Rect = .{ .x = x, .y = registers.y + registers.h + gap, .w = w, .h = ph(10) }; + const view: Rect = if (stopped) .{ .x = x, .y = disasm.y + disasm.h + gap, .w = w, .h = ph(6) } else none; + return .{ .band = none, .view = view, .source = source, .disasm = disasm, .registers = registers, .stack = stack, .backtrace = none, .dump_rows = 0 }; +} + +test "the pair's boxes are the catalogue's" { + const l = split(.left, false); + try std.testing.expectEqual(@as(f32, 200), l.source.y + l.source.h); + try std.testing.expectEqual(@as(f32, 460), l.disasm.y + l.disasm.h); + try std.testing.expectEqual(@as(f32, 600), l.registers.y + l.registers.h); + try std.testing.expectEqual(@as(f32, 884), l.stack.y + l.stack.h); + const r = split(.right, true); + try std.testing.expectEqual(@as(f32, 364), r.disasm.y + r.disasm.h); + try std.testing.expectEqual(@as(f32, 552), r.view.y + r.view.h); + try std.testing.expectEqual(@as(f32, 976), r.stack.x); +} + +/// A field of a frame, from the debug info and the call frame information +/// (its locals, the saved rbp, the return address; an ASan fake frame's +/// header, buffer and redzones), by address. +pub const Field = struct { + at: u64, + len: u64, + name: []const u8, + reads: enum { number, pointer, text, bytes } = .number, + /// The moment it is the frame's from (the call pushes the return address, + /// the prologue the saved rbp and the locals): before it its bytes are + /// loose, and in the step that makes it its paper and reading fade in. + from: u64 = 0, +}; + +/// How much a thing that is the frame's from moment `from` shows now: none +/// before, all after, and over the step that makes it, from memory's slot (12 f). +fn live(now: cursors.Now, from: u64) f32 { + if (now.stops[0] < from) return 0; + if (now.stops[1] >= from or now.resting()) return 1; + return std.math.clamp(now.since(.memory, 0) / theme.time.quick, 0, 1); +} + +/// `hexdump` `eight` (design/README.md): a stack frame as bytes, eight a +/// row, so that a row is one word of the stack: rsp's and rbp's `row` pins +/// at 12, the row's shadow byte at 62 (a run built with ASan), the address +/// at 118, the bytes from 274 on a pitch of 30 (a field's on raised paper, +/// what no field covers `loose`), the reading at 522 (the field's name in Go +/// 18 dim, then what its bytes make), the frame's `call` span at 866. A byte +/// the loop stores past `buf` keeps the string's ink in the field it lands +/// in, whose reading says what the CPU will make of it. A store's byte is +/// struck as in `bytes`; the field's reading crossfades from 6 f after it +/// (12 f). Fixed rows: the pair scrolls each frame so that `buf` faces `buf`. +pub const Frame = struct { + cursor: cursors.Cursor, + stage: *const Stage, + title: []const u8, + note: []const u8 = "", + /// Its rows, eight bytes each from `first`; then, under a rule, `more` + /// rows from `then` (ASan's real stack, far from its fake frame). + first: u64, + rows: usize, + then: u64 = 0, + more: usize = 0, + fields: []const Field, + /// Where the loop's letters begin: a byte from there on, up to the first + /// that is not one, is drawn in a string's ink whatever field holds it. + letters: u64 = 0, + letter: u8 = 'A', + /// Each row of the first stretch with its shadow byte beside it. + shadow: bool = false, + /// The frame's `call` span, from its first word to past its last, its + /// name, and the moment it is made. + span: [2]u64 = .{ 0, 0 }, + span_from: u64 = 0, + /// In a box that holds more rows than it has (the column's): from this + /// word, as many rows as the box holds, and no second stretch; its rows + /// then the places a text is level with and a touch goes to (`ties`). + tall: u64 = 0, + name: []const u8 = "", + side: Side, + /// How much the first stretch shows (an ASan fake frame comes in as it is made). + shows: anim.Value, + /// How much the `differs` bars on rows `differ` show. + differs: anim.Value, + differ: []const u64 = &.{}, + + pub fn draw(frame: *const Frame, f: *sk.Frame, placed: anim.Placed) void { + const box = frame.stage.box(placed, .stack); + if (box.h < m.tag + m.row) return; + const fit = theme.layout.rowsIn(box.h); + var tall = frame.*; + const is_tall = frame.tall != 0 and fit > frame.rows + frame.more; + if (is_tall) { + tall.first = frame.tall; + tall.rows = fit; + tall.more = 0; + } + const fr = &tall; + const u = context.at(f, placed, box); + _ = u.panel(box.w, box.h, fr.title, .{ .note = fr.note }); + context.clipBody(u, box); + defer u.unclip(); + const now = fr.cursor.now(placed); + const top = m.tag + m.pad; + const shows = placed.value(fr.shows); + const passes = crossfade(now); + const n = fr.rows + fr.more; + for (0..n) |k| { + const second = k >= fr.rows; + const addr = fr.rowAddr(k); + const y = top + @as(f32, @floatFromInt(k)) * m.row; + const v = if (second) u else u.faded(shows); + if (is_tall) { + ties.anchor(u, .{ .row = addr }, .{ .x = 0, .y = y, .w = box.w, .h = m.row }); + ties.anchor(u, .{ .word = addr }, .{ .x = eight.address, .y = y, .w = eight.first - eight.address, .h = m.row }); + ties.anchor(u, .{ .slot_pin = addr }, .{ .x = theme.metric.slot.lane, .y = y, .w = theme.metric.slot.lane_end - theme.metric.slot.lane, .h = m.row }); + // The word its eight bytes make, as shown: what an `aim` leaves from. + if (Recording.word(now.shownAt(addr, 8), addr, 8) catch null) |word| ties.show(u, word, .{ .x = eight.first, .y = y, .w = box.w - eight.first, .h = m.row }, .stack, addr, 0, box.w); + } + // A rule across between the two stretches: they are far apart. + if (second and k == fr.rows) u.fill(.{ .x = theme.stroke.rule, .y = y - 1, .w = box.w - 2 * theme.stroke.rule, .h = theme.stroke.rule }, theme.color.rule); + const lead = ui.shared(if (second) &.{ fr.then, fr.then + 8 * (fr.more -| 1) } else &.{ fr.first, fr.first + 8 * (fr.rows -| 1) }); + // A row whose fields the step makes the frame's: its loose bytes going, its fields coming. + var q: f32 = 1; + for (fr.fields) |fl| if (fl.at < addr + 8 and fl.at + fl.len > addr) { + q = @min(q, live(now, fl.from)); + }; + for (passes.moments[0..passes.n], passes.shows[0..passes.n]) |moment, amount| { + if (q > 0) fr.row(v.faded(amount * q), now, moment, addr, y, lead, !second and fr.shadow, k, true); + if (q < 1) fr.row(v.faded(amount * (1 - q)), now, moment, addr, y, lead, !second and fr.shadow, k, false); + } + } + fr.pins(u, now, top); + if (fr.rowOf(fr.span[0])) |a| if (fr.rowOf(fr.span[1] - 8)) |b| { + rows.span(u.faded(live(now, fr.span_from)), box.w, top + @as(f32, @floatFromInt(a)) * m.row, top + @as(f32, @floatFromInt(b + 1)) * m.row, fr.name, true, false); + }; + // `differs`: a bright bar on the seam-side edge of each row whose value its counterpart does not hold. + const bars = placed.value(fr.differs); + if (bars > 0) for (fr.differ) |addr| if (fr.rowOf(addr)) |k| { + const x: f32 = if (fr.side == .left) box.w - theme.stroke.rule - 4 else theme.stroke.rule; + u.faded(bars).fill(.{ .x = x, .y = top + @as(f32, @floatFromInt(k)) * m.row + 1, .w = 4, .h = m.row - 2 }, t.bright); + }; + context.veiled(u, box, now.veil); + } + + fn rowAddr(fr: *const Frame, k: usize) u64 { + return if (k >= fr.rows) fr.then + 8 * (k - fr.rows) else fr.first + 8 * k; + } + + fn rowOf(fr: *const Frame, addr: u64) ?usize { + for (0..fr.rows + fr.more) |k| if (addr >= fr.rowAddr(k) and addr < fr.rowAddr(k) + 8) return k; + return null; + } + + /// The field that holds byte `a`, if any. + fn fieldAt(fr: *const Frame, a: u64) ?Field { + for (fr.fields) |fl| if (a >= fl.at and a < fl.at + fl.len) return fl; + return null; + } + + /// How many of the loop's letters stand from `letters` at `moment`. + fn lettered(fr: *const Frame, moment: Recording.Moment) u64 { + if (fr.letters == 0) return 0; + var buf: [64]u8 = undefined; + var known: [64]bool = undefined; + moment.read(fr.letters, &buf, &known) catch return 0; + var n: u64 = 0; + while (n < buf.len and known[n] and buf[n] == fr.letter) n += 1; + return n; + } + + /// One row of eight bytes at `addr`, its values from `moment` (a write of + /// the step keeping its old bytes until its strike lands). + fn row(fr: *const Frame, u: ui.Ui, now: cursors.Now, moment: Recording.Moment, addr: u64, y: f32, lead: usize, shadowed: bool, k: usize, fielded: bool) void { + const b = eight; + const base = rows.baseline(y); + var values: [8]u8 = undefined; + var known: [8]bool = undefined; + moment.read(addr, &values, &known) catch return; + var was: [8]u8 = undefined; + var known_was: [8]bool = undefined; + now.before().read(addr, &was, &known_was) catch { + was = values; + known_was = known; + }; + const letters_is = fr.lettered(moment); + const letters_was = fr.lettered(now.before()); + if (shadowed) fr.shadowCell(u, now, moment, addr, y, k); + const region = rows.regionOf(moment, addr); + _ = u.address(b.address, base, addr, .{ .ink = ui.rgb(rows.ink(region)), .lead = lead }); + // The runs: each field's part of the row, and the loose bytes between. + var j: u8 = 0; + var reading_x: f32 = b.reading; + while (j < 8) { + const here = addr + j; + const field = if (fielded) fr.fieldAt(here) else null; + var len: u8 = 1; + if (field) |fl| { + len = @intCast(@min(fl.at + fl.len - here, 8 - @as(u64, j))); + } else while (j + len < 8 and (!fielded or fr.fieldAt(here + len) == null)) len += 1; + const lo = j; + const hi = j + len; + // Until its strike lands (s+3) the run keeps its old bytes. + var shown = values; + var shown_known = known; + var letters_shown = letters_is; + if (now.struckAgo(here, len)) |ago| if (ago < theme.time.strike.in / 2.0) { + @memcpy(shown[lo..hi], was[lo..hi]); + @memcpy(shown_known[lo..hi], known_was[lo..hi]); + letters_shown = letters_was; + }; + const heat = now.written(here, len, .memory, 0); + const changed = now.changedBytes(here, len); + var read: f32 = 0; + if (now.wasRead(here, len) and now.writeAge(here, len) != 0) read = now.reading(.memory, 0); + // Until this step's strike lands, the held corner stays on what the last write changed. + const held = if (now.struckAgo(here, len)) |ago| (if (ago < theme.time.strike.in / 2.0) changedBefore(now, here, len) else changed) else changed; + fr.bytes(u, y, addr, lo, hi, &shown, &shown_known, field, heat, changed, held, read, letters_shown, moment); + if (field) |fl| reading_x = fr.reading(u, now, y, reading_x, addr, lo, hi, fl, &values, &known, &was, &known_was, moment); + j = hi; + } + } + + /// The bytes `lo .. hi` of the row at `addr`: paper for a field, the + /// strike's marks on the bytes the step changed, the digits in their ink. + fn bytes(fr: *const Frame, u: ui.Ui, y: f32, addr: u64, lo: u8, hi: u8, values: *const [8]u8, known: *const [8]bool, field: ?Field, h: ui.Heat, changed: ?[2]u8, held: ?[2]u8, read: f32, letters: u64, moment: Recording.Moment) void { + const base = rows.baseline(y); + const x0 = byteX(lo) - 4; + const x1 = byteX(hi - 1) + 28; + const r: Rect = .{ .x = x0, .y = y + 1, .w = x1 - x0, .h = m.row - 2 }; + if (field != null) u.fill(r, theme.color.raised); + const c_lo: u8 = lo + if (changed) |c| c[0] else 0; + const c_hi: u8 = lo + if (changed) |c| c[1] else hi - lo - 1; + const s0 = byteX(c_lo) - 4; + const s1 = byteX(c_hi) + 28; + if (h.arm > 0) u.faded(h.arm).frame(.{ .x = s0 - 3, .y = y - 1, .w = s1 - s0 + 6, .h = m.row + 2 }, theme.mark(.write).solid, 2); + var solid_of: [8]f32 = @splat(0); + if (h.level >= 1 and h.solid > 0) for (c_lo..@as(usize, c_hi) + 1) |i| { + const solid = h.solid * std.math.clamp(h.in - @as(f32, @floatFromInt(i - c_lo)) / (60.0 * theme.time.strike.in), 0, 1); + solid_of[i] = solid; + if (solid <= 0) continue; + const bx0 = byteX(@intCast(i)) - 4 - if (i == c_lo) h.out else 0; + const bx1 = (if (i < c_hi) byteX(@intCast(i + 1)) - 4 else byteX(@intCast(i)) + 28) + if (i == c_hi) h.out else 0; + u.fill(.{ .x = bx0, .y = r.y - h.out, .w = bx1 - bx0, .h = r.h + 2 * h.out }, ui.mix(theme.color.raised, theme.color.struck, solid)); + }; + u.corner(byteX(lo + if (held) |c| c[0] else 0) - 4, y + 2, m.corner, h.level * h.corner); + if (read > 0) u.faded(read).frame(.{ .x = x0 - 3, .y = y - 1, .w = x1 - x0 + 6, .h = m.row + 2 }, theme.mark(.read).solid, 2); + // A pointer's bytes in the ink of where the whole word points; a number's primary; padding faint. + var word: u64 = 0; + if (field) |fl| if (fl.len == 8 and fl.reads == .pointer and fl.at >= addr and fl.at + 8 <= addr + 8) { + for (0..8) |i| word |= @as(u64, values[i]) << @intCast(8 * i); + }; + const field_ink: u24 = if (field) |fl| switch (fl.reads) { + .pointer => rows.ink(rows.regionOf(moment, word)), + .text => theme.color.string, + .number => t.primary, + .bytes => t.primary, + } else t.dim; + var top: usize = lo; + for (lo..hi) |i| if (values[i] != 0) { + top = i; + }; + for (lo..hi) |i| { + const x = byteX(@intCast(i)); + if (!known[i]) { + u.fill(.{ .x = x + 5, .y = y + 11, .w = 4, .h = 4 }, t.faint); + u.fill(.{ .x = x + 15, .y = y + 11, .w = 4, .h = 4 }, t.faint); + continue; + } + const a = addr + i; + const letter = fr.letters != 0 and a >= fr.letters and a < fr.letters + letters; + const ink: u24 = if (letter) theme.color.string else field_ink; + const padding = field != null and field.?.reads != .text and !letter and i > top; + // Bright with the strike's paper, back to its ink as the paper cools (the face at the middle, where the colour moves fastest). + const c = ui.mix(if (padding) ui.mix(ink, theme.color.page, m.pad_alpha) else ui.rgb(ink), t.bright, solid_of[i]); + u.text(if (solid_of[i] >= 0.5) .mono_bold else .mono, size, x, base, u.print("{x:0>2}", .{values[i]}), c); + } + } + + /// The reading of field `fl`'s part `lo .. hi` of the row at `addr`, from + /// `x`: its name, then what its bytes make; as the step's strike lands it + /// crossfades from what they made (6 f after, over 12 f). Returns where it ends. + fn reading(fr: *const Frame, u: ui.Ui, now: cursors.Now, y: f32, x: f32, addr: u64, lo: u8, hi: u8, fl: Field, values: *const [8]u8, known: *const [8]bool, was: *const [8]u8, known_was: *const [8]bool, moment: Recording.Moment) f32 { + _ = fr; + const whole = fl.at >= addr and fl.at + fl.len <= addr + 8; + const name = if (whole) fl.name else u.print("{s}[{d}..{d}]", .{ fl.name, addr + lo - fl.at, addr + hi - 1 - fl.at }); + const micro = theme.size.sans.micro; + u.text(.sans, micro, x, rows.baseline(y) - 1, name, t.dim); + const vx = x + u.width(.sans, micro, name) + adv; + if (fl.reads == .bytes) return vx; + var q: f32 = 1; + if (now.struckAgo(addr + lo, hi - lo)) |ago| q = std.math.clamp((ago - 6.0 / 60.0) / theme.time.quick, 0, 1); + const same = std.mem.eql(u8, values[lo..hi], was[lo..hi]) and std.mem.eql(bool, known[lo..hi], known_was[lo..hi]); + if (same or q >= 1) return value(u.faded(1), vx, y, values[lo..hi], known[lo..hi], fl, moment); + const end_was = value(u.faded(1 - q), vx, y, was[lo..hi], known_was[lo..hi], fl, moment); + const end_is = value(u.faded(q), vx, y, values[lo..hi], known[lo..hi], fl, moment); + return @max(end_was, end_is); + } + + /// What `bytes` (a field's, or its part on a row) make, read as `fl` says, at `x`. + fn value(u: ui.Ui, x: f32, y: f32, bytes_: []const u8, known: []const bool, fl: Field, moment: Recording.Moment) f32 { + if (std.mem.indexOfScalar(bool, known, false) != null) return x; + const base = rows.baseline(y); + var word: u64 = 0; + for (bytes_[0..@min(bytes_.len, 8)], 0..) |c, i| word |= @as(u64, c) << @intCast(8 * i); + switch (fl.reads) { + .bytes => return x, + .text => { + const text = quoted(u, bytes_); + u.text(.mono, size, x, base, text, theme.color.string); + return x + u.width(.mono, size, text); + }, + .number => { + const bits: u6 = @intCast(64 - 8 * @as(u64, @min(bytes_.len, 8))); + const signed = @as(i64, @bitCast(word << bits)) >> bits; + const text = u.print("{d}", .{signed}); + u.text(.mono, size, x, base, text, t.primary); + return x + u.width(.mono, size, text); + }, + .pointer => { + // An address in its region's ink, and its name; once it is none, the number it is. + const region = rows.regionOf(moment, word); + if (region == .none) return u.value(x, base, word, false, .{}); + // Its first hop, as a chain has it: a code address's name, a string's text. + const at = u.arrow(x, y + m.row / 2, .points); + return rows.chain(u, at, y, moment, word, eight.room, .{ .most = 1 }).end; + }, + } + } + + /// The row's shadow byte, at 62: its value (`f1` a frame's left + /// redzone, `f3` its right, `00` addressable) primary where it poisons, + /// faint where not; struck where the step wrote it, 2 f a row apart; framed + /// as read while a check loads it. + fn shadowCell(fr: *const Frame, u: ui.Ui, now: cursors.Now, moment: Recording.Moment, addr: u64, y: f32, k: usize) void { + _ = fr; + const sh = (zt.telescope.shadow(moment, addr) catch return) orelse return; + const delay = @as(f32, @floatFromInt(k)) * 2.0 / 60.0; + var shown = sh.value orelse return; + if (now.struckAgo(sh.addr, 1)) |ago| if (ago - delay < theme.time.strike.in / 2.0) { + if (zt.telescope.shadow(now.before(), addr) catch null) |old| shown = old.value orelse shown; + }; + const cell: Rect = .{ .x = eight.shadow, .y = y, .w = 2 * adv, .h = m.row }; + const h = now.written(sh.addr, 1, .memory, delay); + const ink = u.written(cell, h); + if (now.wasRead(sh.addr, 1)) u.read(cell, now.reading(.memory, 0)); + const face: ui.Face = if (ink) |i| i.face else if (shown != 0) .mono_bold else .mono; + const c = if (ink) |i| i.ink else ui.rgb(if (shown != 0) t.primary else t.faint); + u.text(face, size, eight.shadow, rows.baseline(y), u.print("{x:0>2}", .{shown}), c); + } + + /// rsp's and rbp's `row` pins, as the stack's: each at the row it points + /// into, travelling there with the step (as the stack's pins do, on + /// `glide`); one that leaves the rows fades. + fn pins(fr: *const Frame, u: ui.Ui, now: cursors.Now, top: f32) void { + const rec = fr.cursor.rec; + const names = [2][]const u8{ "rsp", "rbp" }; + var ys: [2]?f32 = .{ null, null }; + var shows: [2]f32 = .{ 0, 0 }; + for (names, 0..) |name, k| { + const is = rec.register(now.stops[0], name); + const was = rec.register(now.stops[1], name); + const p = now.pinGone(k) orelse (if (now.resting()) 1 else std.math.clamp(now.since(.cpu, 0) / theme.time.tied.stack_pin, 0, 1)); + const a = fr.rowOf(was); + const b = fr.rowOf(is); + const at = struct { + fn y(t0: f32, row_: usize) f32 { + return t0 + @as(f32, @floatFromInt(row_)) * m.row; + } + }.y; + if (a != null and b != null) { + ys[k] = std.math.lerp(at(top, a.?), at(top, b.?), cursors.glide(p)); + shows[k] = 1; + } else if (b) |row_| { + ys[k] = at(top, row_); + shows[k] = p; + } else if (a) |row_| { + ys[k] = at(top, row_); + shows[k] = 1 - p; + } + } + const ink = theme.color.region.stack; + // rbp and rsp on one row: one pin, in pwndbg's order; a name joining or leaving it crossfades. + if (ys[0] != null and ys[1] != null and @abs(ys[0].? - ys[1].?) < 1) { + const both = @min(shows[0], shows[1]); + u.faded(both).pinRow(eight.pin, ys[0].?, &.{ "rbp", "rsp" }, ink); + const alone: usize = if (shows[0] > shows[1]) 0 else 1; + u.faded(@max(shows[0], shows[1]) - both).pinRow(eight.pin, ys[0].?, &.{names[alone]}, ink); + return; + } + for ([2]usize{ 1, 0 }) |k| if (ys[k]) |py| u.faded(shows[k]).pinRow(eight.pin, py, &.{names[k]}, ink); + } +}; + +/// Of `addr .. addr + len` (8 at most), the first and last byte (from +/// `addr`) the newest write before this step changed: where its held corner is. +fn changedBefore(now: cursors.Now, addr: u64, len: u64) ?[2]u8 { + const rec = now.rec; + for (1..now.stops.len - 1) |age| { + if (!Recording.touches(rec.written(now.stops[age + 1], now.stops[age]), addr, len)) continue; + var was: [8]u8 = undefined; + var is: [8]u8 = undefined; + var kw: [8]bool = undefined; + var ki: [8]bool = undefined; + const l: usize = @intCast(@min(len, 8)); + rec.moment(now.stops[age + 1]).read(addr, was[0..l], kw[0..l]) catch return null; + rec.moment(now.stops[age]).read(addr, is[0..l], ki[0..l]) catch return null; + var out: ?[2]u8 = null; + for (0..l) |i| if (kw[i] and ki[i] and was[i] != is[i]) { + const first: u8 = if (out) |o| o[0] else @intCast(i); + out = .{ first, @intCast(i) }; + }; + return out; + } + return null; +} + +/// `eight`'s columns (design/README.md, `hexdump`). +const eight = struct { + const pin = 12; + const shadow = 62; + const address = 118; + const first = 274; + const pitch = 30; + const reading = 522; + /// Where a reading ends: before the span's name (`fill`) and its bracket. + const room = 820; +}; + +fn byteX(i: u8) f32 { + return eight.first + @as(f32, @floatFromInt(i)) * eight.pitch; +} + +/// The memory a frame draws now, and how much each shows: at a run, what +/// the step changed crossfades over 8 f, unmarked (`hexdump`'s own). +const Passes = struct { moments: [2]Recording.Moment, shows: [2]f32, n: usize }; +fn crossfade(now: cursors.Now) Passes { + if (now.plan.gait == .run and !now.resting()) { + const q = std.math.clamp(now.since(.memory, 0) / theme.time.run_ease, 0, 1); + if (q > 0 and q < 1) return .{ .moments = .{ now.before(), now.moment() }, .shows = .{ 1 - q, q }, .n = 2 }; + } + return .{ .moments = .{ now.shown(.memory), undefined }, .shows = .{ 1, 0 }, .n = 1 }; +} + +/// Bytes as C text, in quotes, to the first NUL. +fn quoted(u: ui.Ui, bytes_: []const u8) []const u8 { + var out: std.ArrayList(u8) = .empty; + const a = u.f.scratch; + out.append(a, '"') catch return ""; + for (bytes_) |c| { + if (c == 0) break; + if (std.ascii.isPrint(c) and c != '"' and c != '\\') out.append(a, c) catch {} else out.print(a, "\\x{x:0>2}", .{c}) catch {}; + } + out.append(a, '"') catch {}; + return out.items; +} + +/// The address of ASan's shadow for `addr`'s granule: `(addr >> 3) + offset`, as the recording says it. +pub fn shadowOffset(rec: *const Recording) ?u64 { + const sh = (zt.telescope.shadow(rec.moment(0), 0) catch return null) orelse return null; + return sh.addr; +} + +/// A run's output as it wrote it (`write(2, …)`, from a recording that has +/// its system calls), in place of its registers and its disassembly's lower +/// rows once it has stopped (the stage's `view`): the lines the scene +/// names (`lines`: each the first that holds the text), as written, cut at +/// the panel's edge with `…`; the words the narration names framed bright, +/// one after another as `framed` (0 to their count) goes. +pub const Report = struct { + /// The recording of the run by system call. + rec: *const Recording, + stage: *const Stage, + title: []const u8, + lines: []const []const u8, + words: []const []const u8 = &.{}, + framed: anim.Value, + + /// What it wrote to fd 2, all of it. + pub fn stderr(rec: *const Recording, a: std.mem.Allocator) []const u8 { + var out: std.ArrayList(u8) = .empty; + for (rec.syscalls) |c| if (c.nr == 1 and c.args[0] == 2) out.appendSlice(a, c.text) catch {}; + return out.items; + } + + /// How it ended: the status it gave `exit_group`. + pub fn status(rec: *const Recording) ?u64 { + for (rec.syscalls) |c| if (c.nr == 231) return c.args[0]; + return null; + } + + pub fn draw(r: *const Report, f: *sk.Frame, placed: anim.Placed) void { + const box = r.stage.box(placed, .view); + if (box.h < m.tag + m.row) return; + const u = context.at(f, placed, box); + const exit = if (status(r.rec)) |st| u.print("its report, as written \u{00b7} exit {d}", .{st}) else "its report, as written"; + _ = u.panel(box.w, box.h, r.title, .{ .note = exit }); + context.clipBody(u, box); + defer u.unclip(); + const all = stderr(r.rec, u.f.scratch); + const room = box.w - 2 * m.side; + const framed = placed.value(r.framed); + var k: usize = 0; + var word: usize = 0; + for (r.lines) |want| { + var it = std.mem.splitScalar(u8, all, '\n'); + const line = while (it.next()) |l| { + if (std.mem.indexOf(u8, l, want) != null) break l; + } else continue; + const y = m.tag + m.pad + @as(f32, @floatFromInt(k)) * m.row; + const shown = rows.fitted(u, line, room); + u.text(.mono, size, m.side, rows.baseline(y), shown, t.primary); + // The words the narration names, framed bright where the line shows them whole. + for (r.words) |w| if (std.mem.indexOf(u8, line, w)) |at| { + defer word += 1; + const chars = std.unicode.utf8CountCodepoints(line[0..at]) catch at; + if (@as(f32, @floatFromInt(chars + w.len)) * adv > room - adv) continue; + const shows = std.math.clamp(framed - @as(f32, @floatFromInt(word)), 0, 1); + if (shows > 0) u.faded(shows).frame(.{ .x = m.side + @as(f32, @floatFromInt(chars)) * adv - 3, .y = y, .w = @as(f32, @floatFromInt(w.len)) * adv + 6, .h = m.row }, t.bright, theme.stroke.rule); + }; + k += 1; + } + } +}; + +/// The pair's marks across the seam, over its panels: the right run's mark +/// on the shared source (ranged right, a gold plaque pointing left, `asan` +/// before it), the `only here` bars on the right run's rows that no row of +/// the left faces, the two first rows that differ framed `attention` where +/// they part, and a fault on the left run's row (`fault`: hazard bands round +/// an ink plaque naming the signal; rip stays). +pub const Marks = struct { + left: cursors.Cursor, + right: cursors.Cursor, + stages: [2]*const Stage, + /// The right run's name, by its mark on the source. + name: []const u8, + /// The right run's rows no row of the left faces. + only: []const u64, + /// The rows framed `attention` (the left's, the right's), and how much. + attend: [2]u64 = .{ 0, 0 }, + attention: anim.Value, + /// How much the right run's marks show (it folds to the shelf while the left goes on alone). + right_shows: anim.Value, + /// The left run's fault: the moment its signal stops it, the row, its name. + fault: ?struct { at: u64, pc: u64, name: []const u8 } = null, + + pub fn draw(mk: *const Marks, f: *sk.Frame, placed: anim.Placed) void { + mk.sourceMark(f, placed); + // `only here`: a dim bar on the seam-side (left) edge of the right run's rows. + const dbox = mk.stages[1].box(placed, .disasm); + const du = context.at(f, placed, dbox); + const rnow = mk.right.now(placed); + const right = placed.value(mk.right_shows); + context.clipBody(du, dbox); + const k = placed.scale; + const origin = du.at.xf.apply(.{ 0, 0 }); + for (mk.only) |addr| if (ties.find(f, .{ .row = addr })) |r| { + const y = (r[1] - origin[1]) / k; + du.faded(right * (1 - 0.5 * rnow.veil)).fill(.{ .x = theme.stroke.rule, .y = y + 1, .w = 4, .h = m.row - 2 }, t.dim); + }; + du.unclip(); + const shows = placed.value(mk.attention); + if (shows > 0) for (mk.attend, 0..) |addr, side| if (ties.find(f, .{ .row = addr })) |r| { + const b = mk.stages[side].box(placed, .disasm); + const v = context.at(f, placed, b); + const o = v.at.xf.apply(.{ 0, 0 }); + v.faded(shows).frame(.{ .x = 0, .y = (r[1] - o[1]) / k - 1, .w = b.w, .h = m.row + 2 }, theme.mark(.attention).solid, theme.stroke.rule); + }; + if (mk.fault) |fault| mk.faultMark(f, placed, fault.at, fault.pc, fault.name); + } + + /// The right run's mark on the shared source: its line's row, gliding with its advance. + fn sourceMark(mk: *const Marks, f: *sk.Frame, placed: anim.Placed) void { + const box = mk.stages[0].box(placed, .source); + if (box.h < m.tag + m.row) return; + const u = context.at(f, placed, box); + const lnow = mk.left.now(placed); + const rnow = mk.right.now(placed); + const lrec = mk.left.rec; + const rrec = mk.right.rec; + const fit: u32 = @intCast(theme.layout.rowsIn(box.h)); + // The window, as the left's source has it (`Source`). + const going = lnow.advancing(); + const windows = [2]f32{ @floatFromInt(lrec.shownFirst(fit, lrec.shown[lnow.marks[0]])), @floatFromInt(lrec.shownFirst(fit, lrec.shown[lnow.marks[1]])) }; + const first = std.math.lerp(windows[0], windows[1], cursors.glide(going)); + const at = [2]Recording.Shown{ rrec.shown[rnow.marks[0]], rrec.shown[rnow.marks[1]] }; + if (at[1].line == 0) return; + const p = rnow.advancing(); + var line: f32 = @floatFromInt(at[1].line); + var shows: f32 = 1; + if (at[0].line != at[1].line and p < 1 and at[0].line != 0) { + if (cursors.jumps(rrec, rnow.marks[0], rnow.marks[1])) { + // Into a call or out of one: out there, then in here. + line = @floatFromInt(if (p < 0.5) at[0].line else at[1].line); + shows = @abs(2 * p - 1); + } else line = std.math.lerp(@as(f32, @floatFromInt(at[0].line)), line, cursors.standard(p)); + } + const y = m.tag + m.pad + (line - first) * m.row; + if (y < m.tag or y + m.row > box.h) return; + const gold = theme.mark(.current); + const w = theme.metric.plaque.pc; + const x = box.w - theme.stroke.rule - w; + const v = u.faded(shows * placed.value(mk.right_shows)); + v.fill(.{ .x = x, .y = y, .w = w, .h = m.row }, gold.solid); + sk.draw.polygon(u.f, &.{ .{ x + 7, y + m.row / 2 }, .{ x + 17, y + 6 }, .{ x + 17, y + m.row - 6 } }, v.at.pen(.{ .fill = ui.rgb(gold.on_solid) })); + const micro = theme.size.sans.micro; + v.text(.sans_medium, micro, x - 10 - u.width(.sans_medium, micro, mk.name), rows.baseline(y) - 1, mk.name, t.dim); + } + + /// `fault` on the row at `pc` in the left run's disassembly, from the + /// step that stops it at `at`: hazard bands round an ink plaque naming + /// the signal, in 12 f once the step has fired, at the row's right end. + fn faultMark(mk: *const Marks, f: *sk.Frame, placed: anim.Placed, at: u64, pc: u64, name: []const u8) void { + const now = mk.left.now(placed); + if (now.stops[0] < at) return; + const r = ties.find(f, .{ .row = pc }) orelse return; + var shows: f32 = 1; + if (now.stops[0] == at and !now.resting()) shows = std.math.clamp((now.time - theme.time.fire - theme.time.snap) / theme.time.quick, 0, 1); + if (shows <= 0) return; + const box = mk.stages[0].box(placed, .disasm); + const u = context.at(f, placed, box); + const o = u.at.xf.apply(.{ 0, 0 }); + const y = (r[1] - o[1]) / placed.scale; + const band = theme.stroke.hazard; + const tw = u.width(.mono_bold, size, name); + const w = tw + 2 * 10 + 2 * band; + // Where its operands would be: `ret` has none, and its annotation goes on after it. + const x: f32 = theme.metric.insn.operands - band; + const v = u.faded(shows); + const outer: Rect = .{ .x = x, .y = y - 2, .w = w, .h = m.row + 4 }; + // The bands: vermilion and ink at 45 degrees, 12 each, clipped to the plaque's frame. + v.fill(outer, t.ink); + v.clip(outer); + const fault = theme.mark(.fault).solid; + var bx: f32 = x - outer.h; + while (bx < x + w) : (bx += 2 * band) { + sk.draw.polygon(u.f, &.{ .{ bx, outer.y + outer.h }, .{ bx + band, outer.y + outer.h }, .{ bx + band + outer.h, outer.y }, .{ bx + outer.h, outer.y } }, v.at.pen(.{ .fill = ui.rgb(fault) })); + } + v.unclip(); + const inner: Rect = .{ .x = x + band, .y = y + 1, .w = w - 2 * band, .h = m.row - 2 }; + v.fill(inner, t.ink); + v.text(.mono_bold, size, inner.x + 10, rows.baseline(y), name, t.bright); + } +}; + +/// A run that has stopped, folded to one tag on the column's shelf (y 48, +/// ranged right in the panes' column) while the other goes on alone: its +/// panes' frame crossfading in at their boxes as they go (`fold` 0 to 1), +/// then travelling to the tag (1 to 2, `glide`), the note coming as it lands; +/// unfolding, the same backwards. +pub const Shelf = struct { + stage: *const Stage, + title: []const u8, + note: []const u8, + fold: anim.Value, + + pub fn draw(sh: *const Shelf, f: *sk.Frame, placed: anim.Placed) void { + const fold = placed.value(sh.fold); + if (fold <= 0) return; + const disasm = sh.stage.box(placed, .disasm); + const frame = sh.stage.box(placed, .stack); + const from: Rect = .{ .x = disasm.x, .y = disasm.y, .w = disasm.w, .h = frame.y + frame.h - disasm.y }; + const u = context.at(f, placed, .{ .x = 0, .y = 0, .w = theme.canvas.width, .h = theme.canvas.height }); + const sans = theme.size.sans; + const w = 28 + u.width(.sans_medium, sans.tag, sh.title) + 12 + u.width(.sans, sans.micro, sh.note) + 12; + const slot: Rect = .{ .x = theme.layout.program.x + theme.layout.program.w - w, .y = theme.canvas.stage.y, .w = w, .h = m.tag }; + const on = theme.ease(.glide, std.math.clamp(fold - 1, 0, 1)); + const r: Rect = .{ .x = std.math.lerp(from.x, slot.x, on), .y = std.math.lerp(from.y, slot.y, on), .w = std.math.lerp(from.w, slot.w, on), .h = std.math.lerp(from.h, slot.h, on) }; + const v = u.moved(r.x, r.y).faded(std.math.clamp(fold, 0, 1)); + _ = v.panel(r.w, r.h, sh.title, .{}); + const shows = std.math.clamp((on - 0.75) * 4, 0, 1); + if (shows > 0) v.faded(shows).text(.sans, sans.micro, 28 + v.width(.sans_medium, sans.tag, sh.title) + 12, m.tag - 6, sh.note, t.faint); + } +}; + +/// The pair's clock: one rule, gold along it as far as the left run has +/// come (its steps are the pair's), still while a step plays, the step's +/// piece fading in once its mark has landed (`words.Clock`); under its right +/// end the turn and each run's moment. +pub const Clock = struct { + left: cursors.Cursor, + right: cursors.Cursor, + names: [2][]const u8, + /// The loop's counter, where the left run keeps it (0: none), from the moment it counts. + counter: u64 = 0, + counting: u64 = 0, + /// The left run's stage: in the column (`Stage.column`) the clock is under the text column alone. + stage: ?*const Stage = null, + box: Rect = .{ .x = theme.canvas.stage.x, .y = theme.canvas.clock_y - 12, .w = theme.canvas.stage.w, .h = 24 }, + + pub fn draw(k: *const Clock, f: *sk.Frame, at: anim.Placed) void { + const u = words.fixed(f, at, 0); + const c = theme.canvas; + const now = k.left.now(at); + const rnow = k.right.now(at); + var stage = c.stage; + const in_column = if (k.stage) |st| at.value(st.column) else 0; + stage.x = std.math.lerp(c.stage.x, theme.layout.state.x, theme.ease(.glide, in_column)); + stage.w = c.stage.x + c.stage.w - stage.x; + u.fill(.{ .x = stage.x, .y = c.clock_y - 1, .w = stage.w, .h = theme.stroke.rule }, theme.color.rule); + const gold = theme.mark(.current).solid; + const place = struct { + fn of(n: cursors.Now, moment: u64) f32 { + return std.math.clamp(@as(f32, @floatFromInt(moment -| n.way[0])) / @as(f32, @floatFromInt(@max(n.way[1] -| n.way[0], 1))), 0, 1); + } + }.of; + if (now.plan.gait == .sprint or now.resting()) { + u.fill(.{ .x = stage.x, .y = c.clock_y - 2, .w = stage.w * now.place, .h = 4 }, gold); + } else { + const landed = now.plan.advance + now.plan.travel; + const fade = std.math.clamp((now.time - landed) / @as(f32, if (now.plan.gait == .run) theme.time.run_ease else theme.time.quick), 0, 1); + const from = place(now, now.stops[1]); + const to = place(now, now.stops[0]); + u.fill(.{ .x = stage.x, .y = c.clock_y - 2, .w = stage.w * from, .h = 4 }, gold); + if (fade > 0) u.fill(.{ .x = stage.x + stage.w * from, .y = c.clock_y - 2, .w = stage.w * (to - from), .h = 4 }, ui.mix(theme.color.page, gold, fade)); + } + // Each count changes as its run's step lands, never in the middle of a step. + const counts = [2]u64{ counted(now), counted(rnow) }; + var text = u.print("{s} moment {d} \u{00b7} {s} moment {d}", .{ k.names[0], counts[0] -| now.way[0], k.names[1], counts[1] -| rnow.way[0] }); + if (k.counter != 0 and counts[0] >= k.counting) if (Recording.word(k.left.rec.moment(counts[0]), k.counter, 4) catch null) |i| { + const turn: i32 = @bitCast(@as(u32, @truncate(i))); + if (turn >= 0 and turn <= 64) text = u.print("i {d} \u{00b7} {s}", .{ turn, text }); + }; + u.text(.mono, size, stage.x + stage.w - u.width(.mono, size, text), c.clock_y + 28, text, t.faint); + } + + fn counted(n: cursors.Now) u64 { + if (n.resting() or n.plan.gait == .sprint) return n.marked(); + return if (n.time >= n.plan.advance + n.plan.travel) n.stops[0] else n.stops[1]; + } +}; diff --git a/anim/src/regroup.zig b/anim/src/regroup.zig new file mode 100644 index 0000000..431abd8 --- /dev/null +++ b/anim/src/regroup.zig @@ -0,0 +1,348 @@ +//! The introduction's dump (design/motion.md, "A scene: the introduction", +//! chapter I; "A word read"; mocks 29, 30, 37): the 128 bytes at the top of +//! the stack, where the stack panel will stand (the state column), and the +//! verbs that make words of them, each a clock the scene plays (frames, +//! linear): +//! +//! - `in`: the rows arrive, sixteen bytes a row, 18 f each, 12 f apart; no +//! ink, the addresses faint. +//! - `regroup` (design/README.md, 6. Verbs): sixteen a row to eight, the +//! return address walked (its offsets, `low byte`, `high byte`, its bytes +//! flying low byte first on nested arcs to its word's field, the gaps +//! closing, `zeros in front`), the other fifteen at a run. +//! - `framed`: three words that hold addresses framed as read, 30 f apart. +//! - `fold`: the rows out (6 f), the dump's tag to the shelf (18 f, `glide`); back. +//! - `ink` (6. Verbs): a word's digits to its region's ink, the walked one +//! framed with its bytes (its band in `segments` is the scene's echo); +//! the rest at a run, 2 f apart. +//! - `left`: the words to their field's left (24 f, `glide`); `chains`: +//! three chains grow (`extend`), 36 f apart. +//! +//! Every byte and word from the recording at its moment. +const std = @import("std"); +const sk = @import("sketch"); +const anim = @import("anim"); +const zt = @import("ztrace"); +const ui = @import("ui.zig"); +const rows = @import("rows.zig"); +const Recording = @import("Recording.zig"); +const theme = ui.theme; +const Rect = ui.Rect; +const t = theme.color.text; + +pub const words = 16; +const size = theme.size.mono.context; +const adv = ui.advance(size); +const pitch = theme.metric.context.row; + +/// Where it stands: the state column, its rows from `top`; the bytes 12 +/// after the address, 30 apart, 12 more after the eighth; the word's field +/// eight pairs wide, 48 after the bytes, its words ranged right. +pub const at = struct { + pub const column = theme.layout.state.x; + pub const address = column + 24; + pub const bytes = address + 12 * adv + 12; + pub const pair = theme.metric.bytes.pitch; + pub const middle = theme.metric.bytes.middle; + pub const field = bytes + 7 * pair + 24 + 48; + pub const field_end = field + 7 * pair + 24; + pub const top = 96; + /// The tie's bracket, left of the addresses. + pub const bracket = address - 12; +}; + +/// Bytes drawn 50% toward the page: what stays of where a word's bytes were. +fn dimmed() ui.Color { + return ui.mix(theme.color.page, t.primary, 0.5); +} + +fn clamp01(x: f32) f32 { + return std.math.clamp(x, 0, 1); +} + +fn glide(x: f32) f32 { + return theme.ease(.glide, clamp01(x)); +} + +pub const Words = struct { + rec: *const Recording, + at: u64, + in: anim.Value, + regroup: anim.Value, + framed: anim.Value, + fold: anim.Value, + /// 0 to 1: the rows' addresses take the stack's ink (the dump tied to its place). + placed: anim.Value, + ink: anim.Value, + left: anim.Value, + chains: anim.Value, + /// The word walked (the return address), the three framed and chained, top down. + walked: usize, + three: [3]usize, + /// 0 to 1: the rows glide to the stack panel's (chapter II): the panel's + /// left, its first row's top and that row's address; the bytes and the + /// chains' hops go in the first half, each address to the slot's + /// address, each word to where the slot's chain has it. + become: anim.Value, + panel: struct { x: f32 = 0, top: f32 = 0, first: u64 = 0 } = .{}, + + pub fn init(s: *anim.Frame, rec: *const Recording, moment: u64) Words { + const picked = pick(rec, moment); + return .{ .rec = rec, .at = moment, .in = s.value(-1), .regroup = s.value(-1), .framed = s.value(-1), .fold = s.value(0), .placed = s.value(0), .ink = s.value(-1), .left = s.value(-1), .chains = s.value(-1), .walked = picked.walked, .three = picked.three, .become = s.value(0) }; + } + + /// The return address the newest frame has, and the first word that + /// points into the heap, into the stack, and the return address, top down. + pub fn pick(rec: *const Recording, moment: u64) struct { walked: usize, three: [3]usize } { + const m = rec.moment(moment); + const rsp = rec.register(moment, "rsp"); + var walked: usize = 0; + if (m.regs(rec.tid) catch null) |regs| { + var slots: [words]zt.telescope.Slot = undefined; + if (zt.telescope.slots(m, ®s, rsp, &slots)) |found| { + for (found, 0..) |slot, i| if (slot.role == .return_address) { + walked = i; + break; + }; + } else |_| {} + } + const values = read(rec, moment); + var heap: ?usize = null; + var stack: ?usize = null; + for (values.words, 0..) |v, i| switch (rows.regionOf(m, v)) { + .heap => heap = heap orelse i, + .stack => stack = stack orelse i, + else => {}, + }; + var three = [3]usize{ heap orelse 0, stack orelse 1, walked }; + std.mem.sort(usize, &three, {}, std.sort.asc(usize)); + return .{ .walked = walked, .three = three }; + } + + pub const Bytes = struct { base: u64, bytes: [8 * words]u8, known: [8 * words]bool, words: [words]u64 }; + + pub fn read(rec: *const Recording, moment: u64) Bytes { + var out: Bytes = .{ .base = rec.register(moment, "rsp"), .bytes = undefined, .known = undefined, .words = undefined }; + rec.moment(moment).read(out.base, &out.bytes, &out.known) catch @memset(&out.known, false); + for (&out.words, 0..) |*w, i| w.* = std.mem.readInt(u64, out.bytes[i * 8 ..][0..8], .little); + return out; + } + + /// Word `i`'s row's top, its bytes' first x, and how much its address shows, at regroup clock `r`. + fn where(i: usize, r: f32) struct { y: f32, x: f32, address: f32 } { + const row: f32 = @floatFromInt(i / 2); + const half: f32 = @floatFromInt(i % 2); + const a = glide(r / 18); + const b = glide((r - 18) / 12); + const c = glide((r - 30) / 18); + return .{ + .y = at.top + pitch * (row + row * a + half * b), + .x = at.bytes + half * (8 * at.pair + at.middle) * (1 - c), + .address = if (half == 0) 1 else clamp01((r - 36) / 12), + }; + } + + /// The word's text: its hex without the zeros in front. + fn digits(u: ui.Ui, v: u64) []const u8 { + return u.print("{x}", .{v}); + } + + pub fn draw(w: *const Words, f: *sk.Frame, placed: anim.Placed) void { + const u: ui.Ui = .{ .f = f, .at = placed }; + const in = placed.value(w.in); + if (in < 0) return; + const was = @import("segments.zig").clipStage(f, placed); + defer @import("segments.zig").unclipStage(f, was); + const r = placed.value(w.regroup); + const fold = placed.value(w.fold); + const shown = 1 - clamp01(fold / 6); + w.tag(u, fold); + if (shown <= 0) return; + const v = u.faded(shown); + const data = read(w.rec, w.at); + const m = w.rec.moment(w.at); + // The header (mock 29), with the first row; gone as the dump is tied to its place. + const header = clamp01(in / 18) * (1 - placed.value(w.placed)); + if (header > 0) v.faded(header).text(.sans, theme.size.sans.micro, at.address, at.top - 12, "128 bytes, from where rsp points", t.faint); + + // The veil over every row but the walked one, while it is walked. + const veil = clamp01((r - 48) / 18) - clamp01((r - 270) / 18); + const address_ink = ui.mix(t.faint, theme.color.region.stack, placed.value(w.placed)); + const become = placed.value(w.become); + const g = glide(become); + for (0..words) |i| { + const p = where(i, r); + const arrive = clamp01((in - 12 * @as(f32, @floatFromInt(i / 2))) / 18); + if (arrive <= 0) continue; + const row = v.faded(arrive * (if (i == w.walked) 1 else 1 - theme.color.veil_alpha * veil)); + const slot: f32 = @floatFromInt(@as(i64, @bitCast(data.base + 8 * i -% w.panel.first)) >> 3); + const y = std.math.lerp(p.y, w.panel.top + pitch * slot, g); + const base = theme.baseline(y, pitch, size); + const ax = std.math.lerp(at.address, w.panel.x + theme.metric.slot.address, g); + if (p.address > 0) _ = row.faded(p.address).address(ax, base, data.base + 8 * i, .{ .ink = address_ink }); + w.drawBytes(row.faded(1 - clamp01(become * 2)), data, i, p.x, base, r, placed); + w.drawWord(row, m, data.words[i], i, y, r, placed); + } + if (r >= 0) w.walk(v, data, r); + // The three words framed as read, 30 f apart, each in over 6 f. + const framed = placed.value(w.framed); + if (framed >= 0) for (w.three, 0..) |i, k| { + const shows = clamp01((framed - 30 * @as(f32, @floatFromInt(k))) / 6); + if (shows > 0) v.read(w.wordRect(i, data.words[i], placed), shows); + }; + } + + /// Word `i`'s digits as they stand in the field (ranged right, or at its left). + fn wordRect(w: *const Words, i: usize, value: u64, placed: anim.Placed) Rect { + const n: f32 = @floatFromInt(ui.digits(value)); + const left = glide(placed.value(w.left) / 24); + const x = std.math.lerp(at.field_end - n * adv, at.field, left); + return .{ .x = x, .y = at.top + pitch * @as(f32, @floatFromInt(i)), .w = n * adv, .h = pitch }; + } + + fn drawBytes(w: *const Words, u: ui.Ui, data: Bytes, i: usize, x: f32, base: f32, r: f32, placed: anim.Placed) void { + // Its bytes dim as its word comes in (the run), or are left faint where they flew from. + const dim = if (i == w.walked) 0 else w.runIn(i, r); + for (0..8) |k| { + const bx = x + @as(f32, @floatFromInt(k)) * at.pair; + const b = i * 8 + k; + if (i == w.walked and r >= 108) { + // In flight or landed: a faint copy fades into its place from a third of its flight. + const copy = clamp01((r - 120 - 6 * @as(f32, @floatFromInt(k))) / 12); + if (copy > 0) u.faded(copy).text(.mono, size, bx, base, u.print("{x:0>2}", .{data.bytes[b]}), dimmed()); + continue; + } + const text = if (data.known[b]) u.print("{x:0>2}", .{data.bytes[b]}) else "??"; + u.text(.mono, size, bx, base, text, ui.mix(ui.rgb(t.primary), dimmed(), dim)); + } + // The walked word's bytes framed with its word as it takes its ink. + if (i == w.walked) { + const shows = w.walkedFrame(placed); + if (shows > 0) u.read(.{ .x = x, .y = base - 7.2 - pitch / 2, .w = 7 * at.pair + 2 * adv, .h = pitch }, shows); + } + } + + /// How far the run has brought word `i` in (its word in, its bytes dim): 8 f, rows 6 f apart. + fn runIn(w: *const Words, i: usize, r: f32) f32 { + const q: f32 = @floatFromInt(if (i > w.walked) i - 1 else i); + return clamp01((r - 288 - 6 * q) / 8); + } + + fn walkedFrame(w: *const Words, placed: anim.Placed) f32 { + const ink = placed.value(w.ink); + if (ink < 0) return 0; + return clamp01(ink / 6) * (1 - clamp01((ink - 72 - 2 * words - 12) / 18)); + } + + fn drawWord(w: *const Words, u: ui.Ui, m: Recording.Moment, value: u64, i: usize, y: f32, r: f32, placed: anim.Placed) void { + const shows = if (i == w.walked) @as(f32, if (r >= 240) 1 else 0) else w.runIn(i, r); + if (shows <= 0) return; + const v = u.faded(shows); + const kind = rows.regionOf(m, value); + // `ink`: the walked word first (12 f), the rest at a run, 2 f apart, rows top down. + const ink_clock = placed.value(w.ink); + const order: f32 = @floatFromInt(if (i == w.walked) 0 else 72 + 2 * (if (i > w.walked) i - 1 else i)); + const inked = if (ink_clock < 0) 0 else clamp01((ink_clock - order) / 12); + const ink = ui.mix(t.primary, rows.ink(kind), inked); + var rect = w.wordRect(i, value, placed); + const g = glide(placed.value(w.become)); + rect.y = y; + rect.x = std.math.lerp(rect.x, w.panel.x + theme.metric.slot.address + 12 * adv + theme.metric.context.arrow_w, g); + const base = theme.baseline(y, pitch, size); + // `extend`: three chains grow from their word, 36 f apart. + const chains = placed.value(w.chains); + const k = std.mem.indexOfScalar(usize, &w.three, i); + if (chains >= 0 and k != null and kind != .none) { + const since = (chains - 36 * @as(f32, @floatFromInt(k.?))) / 60; + if (since >= 0 and (kind == .code or kind == .rwx)) { + // A code address's chain is its name: it comes in as a hop does (6 f). + const end = v.address(rect.x, base, value, .{ .ink = ink, .rwx = kind == .rwx }); + var name_buf: [128]u8 = undefined; + if (m.string(value, &name_buf) catch null) |name| v.faded(clamp01(since * 10)).text(.mono, size, end + 10, base, ui.symbol(u, name), t.primary); + return; + } + if (since >= 0) { + _ = rows.chain(v, rect.x, y, m, value, theme.layout.state.x + theme.layout.state.w, .{ .extend = since, .hops = 1 - clamp01(placed.value(w.become) * 2) }); + return; + } + } + if (kind == .none) v.text(.mono, size, rect.x, base, digits(u, value), ink) else _ = v.address(rect.x, base, value, .{ .ink = ink, .rwx = kind == .rwx }); + const frame = if (i == w.walked) w.walkedFrame(placed) else 0; + if (frame > 0) v.read(rect, frame); + } + + /// The walked word, from its offsets to its sixteen digits (motion.md, "A word read"). + fn walk(w: *const Words, u: ui.Ui, data: Bytes, r: f32) void { + if (r < 66 or r >= 240) return; + const y = at.top + pitch * @as(f32, @floatFromInt(w.walked)); + const base = theme.baseline(y, pitch, size); + const value = data.words[w.walked]; + // Under the row, its offsets and labels on the page (the veiled rows under them give way). + // They go as the gaps close (192), not after: closed, their pairs are 24 apart and they would touch. + const labels = clamp01((r - 84) / 12) * (1 - clamp01((r - 192) / 12)); + const offsets = clamp01((r - 66) / 12) * (1 - clamp01((r - 192) / 12)); + const zeros_mark = clamp01((r - 204) / 12) * (1 - clamp01((r - 228) / 12)); + const under = @max(offsets, zeros_mark); + if (under > 0) u.faded(under).fill(.{ .x = at.bytes - 12, .y = y + pitch, .w = at.field_end - at.bytes + 24, .h = 2 * pitch + 6 }, theme.color.page); + const close = glide((r - 192) / 12); + for (0..8) |k| { + const kf: f32 = @floatFromInt(k); + const s = clamp01((r - 108 - 6 * kf) / 36); + const from = at.bytes + kf * at.pair; + const pair = 7 - kf; + const to = std.math.lerp(at.field + pair * at.pair, at.field_end - (8 - pair) * 2 * adv, close); + const long = to - from; + const high = std.math.clamp(long / 4, theme.time.flight.arc_min, theme.time.flight.arc_max); + const x = std.math.lerp(from, to, theme.ease(.glide, s)); + const lift = high * @sin(std.math.pi * s); + // The byte itself: bright and bold in the air (from 108 the walk draws it, not the row). + if (r >= 108) { + const air = s > 0 and s < 1; + const text = u.print("{x:0>2}", .{data.bytes[w.walked * 8 + k]}); + // In the air it carries its ground: over the veiled rows it reads alone. + if (air) u.fill(.{ .x = x - 3, .y = base - lift - 18, .w = 2 * adv + 6, .h = 24 }, theme.color.page); + // Each digit of a pair on its own: a zero in front of the word fades on its own. + for (0..2) |d| { + const lead = 2 * (7 - k) + d < 16 - ui.digits(value); + const fade: f32 = if (lead and r >= 228) 1 - clamp01((r - 228) / 12) else 1; + if (fade > 0) u.faded(fade).text(if (air) .mono_bold else .mono, size, x + @as(f32, @floatFromInt(d)) * adv, base - lift, text[d .. d + 1], if (air) t.bright else t.primary); + } + } + // Its offset under it, going with it. + const off = offsets * clamp01((r - 66 - 2 * kf) / 12); + if (off > 0 and s > 0 and s < 1) u.faded(off).fill(.{ .x = x - 3, .y = base + pitch - lift - 18, .w = 2 * adv + 6, .h = 24 }, theme.color.page); + if (off > 0) u.faded(off).text(.mono, size, x, base + pitch - lift, u.print("+{d}", .{k}), t.dim); + // `low byte` from its byte's left, `high byte` to its byte's right: under the bytes, never the addresses. + if (k == 0 or k == 7) if (labels > 0) { + const label = if (k == 0) "low byte" else "high byte"; + const lw = u.width(.sans, theme.size.sans.tag, label); + u.faded(labels).text(.sans, theme.size.sans.tag, if (k == 0) x else x + 2 * adv - lw, base + 2 * pitch + 2 - lift, label, t.dim); + }; + } + // The zeros in front, bracketed (motion.md: 204 to 228). + if (zeros_mark > 0) { + const lead: f32 = @floatFromInt(16 - ui.digits(value)); + const x0 = at.field_end - 16 * adv; + const v = u.faded(zeros_mark); + v.fill(.{ .x = x0, .y = y + pitch - 2, .w = lead * adv, .h = 2 }, t.dim); + v.fill(.{ .x = x0, .y = y + pitch - 8, .w = 2, .h = 6 }, t.dim); + v.fill(.{ .x = x0 + lead * adv - 2, .y = y + pitch - 8, .w = 2, .h = 6 }, t.dim); + v.text(.sans, theme.size.sans.tag, x0, base + pitch + 2, "zeros in front", t.dim); + } + } + + /// The dump folded to its tag on the shelf (mock 49's shelf, y 48): the + /// rows out over 6 f, the tag from over the rows to the shelf (18 f, `glide`). + fn tag(_: *const Words, u: ui.Ui, fold: f32) void { + if (fold <= 0) return; + const title = "the stack's 128 bytes"; + const p = glide((fold - 6) / 18); + const w = u.width(.sans_medium, theme.size.sans.tag, title) + 40; + const x = std.math.lerp(at.address - 8, theme.canvas.margin_x, p); + const y = std.math.lerp(at.top - 30, theme.canvas.stage.y, p); + const v = u.faded(clamp01(fold / 6)).moved(x, y); + v.fill(.{ .x = 0, .y = 0, .w = w, .h = theme.metric.context.tag }, theme.color.raised); + v.frame(.{ .x = 8, .y = 6, .w = 12, .h = 12 }, t.faint, theme.stroke.rule); + v.text(.sans_medium, theme.size.sans.tag, 28, theme.metric.context.tag - 6, title, t.dim); + } +}; diff --git a/anim/src/relations.zig b/anim/src/relations.zig new file mode 100644 index 0000000..03165d5 --- /dev/null +++ b/anim/src/relations.zig @@ -0,0 +1,341 @@ +//! The relations' data (design/README.md, "4. Ties"), one table set a +//! frame, and the passes over it. The panels say, as they draw, where each +//! of their things is (`places`: a key, the kind of thing and its address +//! packed in one integer, a box, a pane) and which values they show that +//! could be addresses (`values`: the value, its box, its pane, a reference +//! such as a register's index). A relation is a join of the two on +//! address, or a step's own fact (a touch, a carry, the thread), and the +//! resolver (`ties.zig`) runs it as a pipeline of passes over slices: +//! candidates, `filter` by the knobs, `order` by priority, `cut` to the +//! budget, route, draw. `filter`, `order`, `cut` and `join` are pure, and +//! tested here with tables written by hand. +//! +//! Memory: the tables live in the frame's scratch arena (`sk.Frame.user`), +//! made at the frame's first place and gone with it: no process globals, +//! no allocation per relation, indices rather than pointers. +const std = @import("std"); + +/// The pane a place or a value is drawn in. +pub const Pane = enum(u8) { other, source, disasm, registers, stack, view, drawing, loupe }; + +/// A key: the kind of thing in its top byte, an address (or an index) in the rest. +pub const Key = u64; +pub const kind_shift = 56; +pub const address_mask: u64 = (1 << kind_shift) - 1; + +pub fn keyOf(kind: u8, address: u64) Key { + return @as(u64, kind) << kind_shift | (address & address_mask); +} + +pub fn kindOf(key: Key) u8 { + return @intCast(key >> kind_shift); +} + +pub const Place = struct { key: Key, box: [4]f32, pane: Pane }; +/// `at`: the address of the word that holds it (0: a register's); `ref`: a +/// register's index; `rules`: its panel's left and right rules. +pub const Value = struct { value: u64, box: [4]f32, pane: Pane, ref: u32 = 0, at: u64 = 0, rules: [2]f32 = .{ 0, 0 } }; + +/// One layer's tables: the working frame's, or the map's. +pub const Tables = struct { + places: std.MultiArrayList(Place) = .{}, + values: std.MultiArrayList(Value) = .{}, + /// `places` by key (then by the order they were said), and `values` by + /// value: built once, on the first lookup after a change. + places_by_key: std.ArrayList(u32) = .empty, + values_by_value: std.ArrayList(u32) = .empty, + places_sorted: bool = true, + values_sorted: bool = true, + /// Nanoseconds this frame spent sorting. + sort_ns: u64 = 0, + + pub fn add(t: *Tables, gpa: std.mem.Allocator, place: Place) void { + t.places.append(gpa, place) catch return; + t.places_sorted = false; + } + + pub fn show(t: *Tables, gpa: std.mem.Allocator, value: Value) void { + t.values.append(gpa, value) catch return; + t.values_sorted = false; + } + + /// The index of places by key: sorted once after a change. + pub fn byKey(t: *Tables, gpa: std.mem.Allocator) []const u32 { + if (!t.places_sorted) { + const start = clock(); + sortIndex(gpa, &t.places_by_key, t.places.items(.key)); + t.places_sorted = true; + t.sort_ns += clock() - start; + } + return t.places_by_key.items; + } + + pub fn byValue(t: *Tables, gpa: std.mem.Allocator) []const u32 { + if (!t.values_sorted) { + const start = clock(); + sortIndex(gpa, &t.values_by_value, t.values.items(.value)); + t.values_sorted = true; + t.sort_ns += clock() - start; + } + return t.values_by_value.items; + } + + /// The box of the first place said with `key`: a binary search. + pub fn find(t: *Tables, gpa: std.mem.Allocator, key: Key) ?[4]f32 { + const order = t.byKey(gpa); + const keys = t.places.items(.key); + const i = lowerBound(order, keys, key); + if (i == order.len or keys[order[i]] != key) return null; + return t.places.items(.box)[order[i]]; + } + + /// The indices (into `places`) of the keys in `[lo, hi)`, in key order. + pub fn range(t: *Tables, gpa: std.mem.Allocator, lo: Key, hi: Key) []const u32 { + const order = t.byKey(gpa); + const keys = t.places.items(.key); + return order[lowerBound(order, keys, lo)..lowerBound(order, keys, hi)]; + } + + /// The greatest key of kind `kind` at or below `address`, within `within` of it. + pub fn atOrBelow(t: *Tables, gpa: std.mem.Allocator, kind: u8, address: u64, within: u64) ?u64 { + const order = t.byKey(gpa); + const keys = t.places.items(.key); + const i = lowerBound(order, keys, keyOf(kind, address) + 1); + if (i == 0) return null; + const k = keys[order[i - 1]]; + if (kindOf(k) != kind) return null; + const a = k & address_mask; + return if (address - a < within) a else null; + } +}; + +/// `index` made the permutation of `keys` that sorts them, ties in their order. +fn sortIndex(gpa: std.mem.Allocator, index: *std.ArrayList(u32), keys: []const u64) void { + index.resize(gpa, keys.len) catch return; + for (index.items, 0..) |*v, i| v.* = @intCast(i); + std.sort.pdq(u32, index.items, keys, struct { + fn less(k: []const u64, a: u32, b: u32) bool { + return k[a] < k[b] or (k[a] == k[b] and a < b); + } + }.less); +} + +/// The first position in `order` whose key is not below `key`. +fn lowerBound(order: []const u32, keys: []const u64, key: u64) usize { + var lo: usize = 0; + var hi: usize = order.len; + while (lo < hi) { + const mid = (lo + hi) / 2; + if (keys[order[mid]] < key) lo = mid + 1 else hi = mid; + } + return lo; +} + +/// A value shown and the place of kind `kind` at its address (masked by +/// `mask`: a view's row is its first byte's): indices into the tables. +pub const Pair = struct { value: u32, place: u32 }; + +/// The join of `values` (by value, `by_value` their order) with the +/// places of kind `kind` (by key, `by_key` their order) on address: a merge +/// of the two sorted sides, each value with the first place said at its +/// address. Appends to `out`; a value that is no place's address has none. +pub fn join(values: []const u64, by_value: []const u32, keys: []const Key, by_key: []const u32, kind: u8, mask: u64, out: *std.ArrayList(Pair), gpa: std.mem.Allocator) void { + // The places of the kind: one run of the key order. + const lo = lowerBound(by_key, keys, keyOf(kind, 0)); + const hi = lowerBound(by_key, keys, keyOf(kind + 1, 0)); + const run = by_key[lo..hi]; + // Masking keeps the values' order (a mask clears low bits): one walk. + var p: usize = 0; + for (by_value) |v| { + const want = values[v] & mask & address_mask; + while (p < run.len and keys[run[p]] & address_mask < want) p += 1; + if (p == run.len) break; + if (keys[run[p]] & address_mask == want) out.append(gpa, .{ .value = v, .place = run[p] }) catch return; + } +} + +// ---- The resolver's pure passes. + +/// The kinds of relation, in the order they are drawn. +pub const Kind = enum(u8) { thread, beat, link, projection, touch, carry, code }; + +/// What turns a kind on. `always`: whenever the step has one (the scene's +/// beat, its own facts); the rest only where the author has turned it on +/// (or, for the thread and links, has not turned it off). +pub const Knob = enum(u8) { thread, links, carry, code, always }; + +/// A budget's class: how many of it a frame draws at most. +pub const Class = enum(u8) { standing, beat, step, carry, code }; + +/// A kind's row of data: its knob, its class, its priority (lower first) +/// and how many of it a frame draws at most. +pub const Spec = struct { knob: Knob, class: Class, priority: u8, most: u8 }; + +pub const specs = std.enums.EnumArray(Kind, Spec).init(.{ + .thread = .{ .knob = .thread, .class = .standing, .priority = 0, .most = 1 }, + .beat = .{ .knob = .always, .class = .beat, .priority = 1, .most = 1 }, + .link = .{ .knob = .links, .class = .step, .priority = 2, .most = 1 }, + .projection = .{ .knob = .always, .class = .step, .priority = 3, .most = 1 }, + // The first to give way: three lines at most, so not with a link and a projection. + .touch = .{ .knob = .always, .class = .step, .priority = 4, .most = 1 }, + .carry = .{ .knob = .carry, .class = .carry, .priority = 5, .most = 1 }, + // One at a time: a standing row across panes, or the step's. + .code = .{ .knob = .code, .class = .code, .priority = 6, .most = 1 }, +}); + +/// How many of a class a frame draws at most. +pub const budget = std.enums.EnumArray(Class, u8).init(.{ .standing = 1, .beat = 1, .step = 2, .carry = 1, .code = 1 }); + +/// The knobs as the scene has them this frame. +pub const Knobs = std.enums.EnumSet(Knob); + +/// A relation that could be drawn: its kind, its rank within its kind (a +/// register's place in pwndbg's order, a span's in the step), and the +/// indices of what it ties (`from`, `to`: into a table, or a kind's own). +pub const Candidate = struct { kind: Kind, rank: u32 = 0, from: u32 = 0, to: u32 = 0 }; + +/// Those whose kind's knob is on, in place. +pub fn filter(cands: []Candidate, knobs: Knobs) []Candidate { + var n: usize = 0; + for (cands) |c| if (knobs.contains(specs.get(c.kind).knob)) { + cands[n] = c; + n += 1; + }; + return cands[0..n]; +} + +/// By priority, then rank, then as they came (`from`, each its own). +pub fn byPriority(cands: []Candidate) void { + std.sort.pdq(Candidate, cands, {}, struct { + fn less(_: void, a: Candidate, b: Candidate) bool { + const pa = specs.get(a.kind).priority; + const pb = specs.get(b.kind).priority; + if (pa != pb) return pa < pb; + if (a.rank != b.rank) return a.rank < b.rank; + return a.from < b.from; + } + }.less); +} + +/// The first of each kind up to its most, and of each class up to its +/// budget, in place: what is cut is the least urgent. +pub fn cut(cands: []Candidate) []Candidate { + var per_kind = std.enums.EnumArray(Kind, u8).initFill(0); + var per_class = std.enums.EnumArray(Class, u8).initFill(0); + var n: usize = 0; + for (cands) |c| { + const spec = specs.get(c.kind); + if (per_kind.get(c.kind) >= spec.most or per_class.get(spec.class) >= budget.get(spec.class)) continue; + per_kind.set(c.kind, per_kind.get(c.kind) + 1); + per_class.set(spec.class, per_class.get(spec.class) + 1); + cands[n] = c; + n += 1; + } + return cands[0..n]; +} + +/// Counts and nanoseconds of a frame's relations (`CANIM_RELATIONS=1`: a line a frame on stderr). +pub const Stats = struct { + places: usize = 0, + values: usize = 0, + candidates: usize = 0, + kept: usize = 0, + drawn: usize = 0, + map_places: usize = 0, + map_values: usize = 0, + map_pairs: usize = 0, + ns: struct { sort: u64 = 0, candidates: u64 = 0, passes: u64 = 0, draw: u64 = 0, map: u64 = 0 } = .{}, +}; + +/// Whether to say each frame's counts and times on stderr (`CANIM_RELATIONS=1`), read once. +pub fn reporting() bool { + if (report_on == null) report_on = if (comptime @import("builtin").link_libc) std.c.getenv("CANIM_RELATIONS") != null else false; + return report_on.?; +} +var report_on: ?bool = null; + +pub fn clock() u64 { + var ts: std.os.linux.timespec = undefined; + _ = std.os.linux.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); +} + +// ---- Tests: hand-written tables in, tables out. + +test "a lookup is the first place said with its key, by binary search" { + const gpa = std.testing.allocator; + var t: Tables = .{}; + defer { + t.places.deinit(gpa); + t.places_by_key.deinit(gpa); + } + t.add(gpa, .{ .key = keyOf(3, 0x30), .box = .{ 1, 0, 0, 0 }, .pane = .stack }); + t.add(gpa, .{ .key = keyOf(1, 0x10), .box = .{ 2, 0, 0, 0 }, .pane = .registers }); + t.add(gpa, .{ .key = keyOf(3, 0x30), .box = .{ 3, 0, 0, 0 }, .pane = .stack }); + try std.testing.expectEqual(@as(f32, 1), t.find(gpa, keyOf(3, 0x30)).?[0]); + try std.testing.expectEqual(@as(f32, 2), t.find(gpa, keyOf(1, 0x10)).?[0]); + try std.testing.expect(t.find(gpa, keyOf(3, 0x38)) == null); + // Said after a lookup: the order is made again. + t.add(gpa, .{ .key = keyOf(2, 0x20), .box = .{ 4, 0, 0, 0 }, .pane = .view }); + try std.testing.expectEqual(@as(f32, 4), t.find(gpa, keyOf(2, 0x20)).?[0]); + // A range of one kind, and the nearest at or below an address. + t.add(gpa, .{ .key = keyOf(3, 0x50), .box = .{ 5, 0, 0, 0 }, .pane = .stack }); + try std.testing.expectEqual(@as(usize, 3), t.range(gpa, keyOf(3, 0), keyOf(4, 0)).len); + try std.testing.expectEqual(@as(?u64, 0x30), t.atOrBelow(gpa, 3, 0x48, 64)); + try std.testing.expectEqual(@as(?u64, null), t.atOrBelow(gpa, 3, 0x48, 8)); + try std.testing.expectEqual(@as(?u64, null), t.atOrBelow(gpa, 3, 0x10, 64)); +} + +test "a join pairs each value with the first place at its address, of one kind" { + const gpa = std.testing.allocator; + // Places: rows (kind 14) at 401000, 401004 (twice), 401010; a word (kind 3) at 401004. + const keys = [_]Key{ keyOf(14, 0x401004), keyOf(3, 0x401004), keyOf(14, 0x401000), keyOf(14, 0x401010), keyOf(14, 0x401004) }; + var by_key: std.ArrayList(u32) = .empty; + defer by_key.deinit(gpa); + sortIndex(gpa, &by_key, &keys); + // Values: 401004 (twice), 7fff0000, 401010, 401008. + const values = [_]u64{ 0x401004, 0x7fff0000, 0x401010, 0x401004, 0x401008 }; + var by_value: std.ArrayList(u32) = .empty; + defer by_value.deinit(gpa); + sortIndex(gpa, &by_value, &values); + var out: std.ArrayList(Pair) = .empty; + defer out.deinit(gpa); + join(&values, by_value.items, &keys, by_key.items, 14, ~@as(u64, 0), &out, gpa); + try std.testing.expectEqualSlices(Pair, &.{ .{ .value = 0, .place = 0 }, .{ .value = 3, .place = 0 }, .{ .value = 2, .place = 3 } }, out.items); + // Masked: a view's row is its first byte's (sixteen-aligned). + out.clearRetainingCapacity(); + join(&values, by_value.items, &keys, by_key.items, 14, ~@as(u64, 15), &out, gpa); + try std.testing.expectEqualSlices(Pair, &.{ .{ .value = 0, .place = 2 }, .{ .value = 3, .place = 2 }, .{ .value = 4, .place = 2 }, .{ .value = 2, .place = 3 } }, out.items); +} + +test "the passes: off unless its knob is on, by priority, cut to the budget" { + var cands = [_]Candidate{ + .{ .kind = .touch }, + .{ .kind = .code, .rank = 2 }, + .{ .kind = .link, .rank = 5 }, + .{ .kind = .projection }, + .{ .kind = .link, .rank = 1 }, + .{ .kind = .thread }, + .{ .kind = .code, .rank = 0 }, + }; + // The code kind is off by default: it goes; the rest are on. + var knobs = Knobs.initMany(&.{ .thread, .links, .always }); + var kept = filter(&cands, knobs); + try std.testing.expectEqual(@as(usize, 5), kept.len); + byPriority(kept); + try std.testing.expectEqual(Kind.thread, kept[0].kind); + try std.testing.expectEqual(@as(u32, 1), kept[1].rank); + kept = cut(kept); + // One thread, one link (the first in the registers' order), one projection; the touch gives way. + try std.testing.expectEqual(@as(usize, 3), kept.len); + try std.testing.expectEqualSlices(Kind, &.{ .thread, .link, .projection }, &.{ kept[0].kind, kept[1].kind, kept[2].kind }); + try std.testing.expectEqual(@as(u32, 1), kept[1].rank); + // With no projection the touch is drawn; with the knob on, one code pointer, the first in rank. + var more = [_]Candidate{ .{ .kind = .touch }, .{ .kind = .link }, .{ .kind = .code, .rank = 3 }, .{ .kind = .code, .rank = 1 } }; + knobs.insert(.code); + kept = filter(&more, knobs); + byPriority(kept); + kept = cut(kept); + try std.testing.expectEqualSlices(Kind, &.{ .link, .touch, .code }, &.{ kept[0].kind, kept[1].kind, kept[2].kind }); + try std.testing.expectEqual(@as(u32, 1), kept[2].rank); +} diff --git a/anim/src/root.zig b/anim/src/root.zig index fcdb572..596ac57 100644 --- a/anim/src/root.zig +++ b/anim/src/root.zig @@ -48,6 +48,8 @@ pub const CallTree = calls.Tree; pub const Nodes = @import("nodes.zig").Nodes; pub const hexdump = @import("hexdump.zig"); const tying = @import("ties.zig"); +/// The relations' tables and the resolver's pure passes (design/README.md, "4. Ties"). +pub const relations = @import("relations.zig"); pub const Ties = tying.Ties; pub const Place = tying.Place; pub const Array = @import("array.zig").Array; @@ -71,6 +73,22 @@ pub const Column = columns.Column; pub const column = columns.column; /// A column pane's rows: what the column has left. pub const column_rest = columns.rest; +/// Two runs against each other (design/README.md, `pair`): each side's +/// stage (`pair.split`), the frame as bytes (`pair.Frame`), a stopped +/// run's output (`pair.Report`), the marks across the seam, the clock. +pub const pair = @import("pair.zig"); +/// The introduction's blocks (design/motion.md, "A scene: the +/// introduction"): the address space to scale (`segments`), the bytes at +/// the stack's top made words (`regroup`), a text beside its part (`Aside`). +pub const segments = @import("segments.zig"); +pub const Segments = segments.Segments; +pub const regroup = @import("regroup.zig"); +pub const Words = regroup.Words; +pub const Aside = @import("aside.zig").Aside; +pub const Asides = @import("aside.zig").Asides; +/// The source with its instructions, one panel, each line level with its code (`aligned`). +pub const aligned = @import("aligned.zig"); +pub const Aligned = aligned.Aligned; /// The page behind every scene: `pub const background = canim.background;`. pub const background: u32 = theme.color.page; @@ -406,6 +424,7 @@ test { _ = @import("descent.zig"); _ = graph; _ = tying; + _ = relations; _ = @import("hexdump.zig"); _ = calls; _ = @import("nodes.zig"); @@ -416,4 +435,9 @@ test { _ = objects; _ = words; _ = columns; + _ = pair; + _ = segments; + _ = regroup; + _ = @import("aside.zig"); + _ = aligned; } diff --git a/anim/src/segments.zig b/anim/src/segments.zig new file mode 100644 index 0000000..d28d2dd --- /dev/null +++ b/anim/src/segments.zig @@ -0,0 +1,605 @@ +//! `segments` (design/README.md, "segments"; motion.md, "The address space +//! enlarged"; mocks 30 and 34, treatment A): the user half of the address +//! space to true scale, a slim bar, and each cluster of mappings enlarged +//! once, linear, a box beside it with every named band's start and end +//! addresses and its size. Everything from the recording's mappings at one +//! moment (`Moment.mappings`, `mapping`): nothing is placed by hand. +//! +//! Drawn in the program column (x 64, 880 wide), between `top` and `foot` +//! (the column's 84 to 888, the working frame's 80 to 864: `form`); the +//! scene plays its clocks (frames, linear): `whole` (the bar, its ends, the +//! mappings' lines), each cluster's `enlarge`, a band's `ink` echo. `Place` +//! is a dump's place in it: the `tie` bracket and the `link` onto the +//! stack's box. +const std = @import("std"); +const sk = @import("sketch"); +const anim = @import("anim"); +const zt = @import("ztrace"); +const ui = @import("ui.zig"); +const Recording = @import("Recording.zig"); +const theme = ui.theme; +const Rect = ui.Rect; +const Vec = ui.Vec; +const t = theme.color.text; +const region = theme.color.region; + +/// The user half: 0 to 7fffffffffff. +pub const user_end: u64 = 1 << 47; + +/// Touching mappings of one file and one permission (an anonymous one right +/// after a file's, its bss, with it). +pub const Band = struct { lo: u64, hi: u64, prot: u64, name: []const u8, ink: u24 }; +/// What has a row of names: a file once (the program by segment, each band its own). +pub const Unit = struct { lo: u64, hi: u64, prot: ?u64, name: []const u8, ink: u24, program: bool }; +pub const Cluster = struct { lo: u64, hi: u64, bands: [2]u16, units: [2]u16 }; + +pub const Space = struct { + bands: []Band, + units: []Unit, + clusters: []Cluster, + program: []const u8, +}; + +const Kind = zt.telescope.Region; + +fn inkOf(kind: Kind) u24 { + return switch (kind) { + .code, .rwx => region.code_, + .stack => region.stack, + .heap => region.heap, + .data => region.data, + .rodata => region.rodata, + .none => region.number, + }; +} + +/// A mapping's file as a name: its path's last part, without the kernel's ` (deleted)`. +fn nameOf(path: []const u8) []const u8 { + const base = if (std.mem.lastIndexOfScalar(u8, path, '/')) |k| path[k + 1 ..] else path; + return if (std.mem.endsWith(u8, base, " (deleted)")) base[0 .. base.len - " (deleted)".len] else base; +} + +/// The address space at moment `at`: its bands, the units named, the +/// clusters top down (highest first). A cluster is mappings with less than +/// 16 MiB between them; a band more than eight times the rest of its +/// cluster is a cluster of its own (the tracer's ring under libc: in the +/// libraries' box it would leave libc 12 units tall). +pub fn read(rec: *const Recording, at: u64, arena: std.mem.Allocator) Space { + const mo = rec.moment(at); + const maps = mo.mappings(arena) catch &.{}; + var bands: std.ArrayList(Band) = .empty; + var path_buf: [512]u8 = undefined; + for (maps) |mp| { + if (mp.addr >= user_end) continue; + var path: []const u8 = ""; + _ = mo.mapping(mp.addr, &path, &path_buf) catch null; + const name = arena.dupe(u8, nameOf(path)) catch ""; + if (bands.items.len > 0) { + const last = &bands.items[bands.items.len - 1]; + if (last.hi == mp.addr and last.prot == mp.prot and (std.mem.eql(u8, last.name, name) or (name.len == 0 and last.name.len > 0 and last.name[0] != '['))) { + last.hi = mp.addr + mp.len; + continue; + } + } + bands.append(arena, .{ .lo = mp.addr, .hi = mp.addr + mp.len, .prot = mp.prot, .name = name, .ink = inkOf(Kind.of(mp, name)) }) catch break; + } + // The program: the file the pc is in. + var pc_path: []const u8 = ""; + _ = mo.mapping(rec.register(at, "rip"), &pc_path, &path_buf) catch null; + const program = arena.dupe(u8, nameOf(pc_path)) catch ""; + + // Units: the program's bands each, every other file once. + var units: std.ArrayList(Unit) = .empty; + var k: usize = 0; + while (k < bands.items.len) { + const b = bands.items[k]; + if (b.name.len == 0) { + k += 1; + continue; + } + if (std.mem.eql(u8, b.name, program)) { + units.append(arena, .{ .lo = b.lo, .hi = b.hi, .prot = b.prot, .name = b.name, .ink = b.ink, .program = true }) catch break; + k += 1; + continue; + } + var u: Unit = .{ .lo = b.lo, .hi = b.hi, .prot = b.prot, .name = b.name, .ink = b.ink, .program = false }; + k += 1; + while (k < bands.items.len and bands.items[k].lo == u.hi and std.mem.eql(u8, bands.items[k].name, u.name)) : (k += 1) { + u.hi = bands.items[k].hi; + if (u.prot != bands.items[k].prot) { + u.prot = null; + u.ink = region.rodata; + } + } + units.append(arena, u) catch break; + } + + // Clusters, low to high first, then turned top down. + var clusters: std.ArrayList(Cluster) = .empty; + var first: usize = 0; + for (bands.items, 0..) |b, i| { + const last = i + 1 == bands.items.len or bands.items[i + 1].lo - b.hi >= 16 << 20; + if (!last) continue; + splitOff(arena, &clusters, bands.items, first, i + 1); + first = i + 1; + } + std.mem.reverse(Cluster, clusters.items); + for (clusters.items) |*c| { + var lo_u: u16 = @intCast(units.items.len); + var hi_u: u16 = 0; + for (units.items, 0..) |u, i| if (u.lo >= c.lo and u.hi <= c.hi) { + lo_u = @min(lo_u, @as(u16, @intCast(i))); + hi_u = @max(hi_u, @as(u16, @intCast(i + 1))); + }; + c.units = if (hi_u > lo_u) .{ lo_u, hi_u } else .{ 0, 0 }; + } + return .{ .bands = bands.items, .units = units.items, .clusters = clusters.items, .program = program }; +} + +/// Bands `a` to `b` as a cluster, or three where one band outweighs the rest eightfold. +fn splitOff(arena: std.mem.Allocator, out: *std.ArrayList(Cluster), bands: []const Band, a: usize, b: usize) void { + var big = a; + for (a..b) |i| if (bands[i].hi - bands[i].lo > bands[big].hi - bands[big].lo) { + big = i; + }; + const whole = bands[b - 1].hi - bands[a].lo; + const len = bands[big].hi - bands[big].lo; + if (b - a > 1 and len > 8 * (whole - len)) { + for ([_][2]usize{ .{ a, big }, .{ big, big + 1 }, .{ big + 1, b } }) |r| if (r[1] > r[0]) { + out.append(arena, .{ .lo = bands[r[0]].lo, .hi = bands[r[1] - 1].hi, .bands = .{ @intCast(r[0]), @intCast(r[1]) }, .units = .{ 0, 0 } }) catch {}; + }; + return; + } + out.append(arena, .{ .lo = bands[a].lo, .hi = bands[b - 1].hi, .bands = .{ @intCast(a), @intCast(b) }, .units = .{ 0, 0 } }) catch {}; +} + +/// A size as the names give it: `4 KiB`, `132 KiB`, `2.1 MiB`, `64 MiB`, `128 TiB`. +pub fn size(buf: []u8, bytes: u64) []const u8 { + const units = [_][]const u8{ "KiB", "MiB", "GiB", "TiB" }; + var v: f64 = @as(f64, @floatFromInt(bytes)) / 1024; + var u: usize = 0; + while (v >= 1024 and u + 1 < units.len) : (u += 1) v /= 1024; + if (u > 0 and v < 10 and @abs(v - @round(v)) >= 0.05) return std.fmt.bufPrint(buf, "{d:.1} {s}", .{ v, units[u] }) catch ""; + return std.fmt.bufPrint(buf, "{d} {s}", .{ @as(u64, @intFromFloat(@round(v))), units[u] }) catch ""; +} + +fn perms(prot: u64) [3]u8 { + return .{ if (prot & 1 != 0) 'r' else '-', if (prot & 2 != 0) 'w' else '-', if (prot & 4 != 0) 'x' else '-' }; +} + +/// Rows `pitch` apart, each as near its target as the others let it +/// (crowded ones pooled round their mean), in order, centres in `lo` to `hi`. +pub fn pool(targets: []const f32, out: []f32, lo: f32, hi: f32, pitch: f32) void { + const n = targets.len; + if (n == 0) return; + var sums: [64]f32 = undefined; + var counts: [64]f32 = undefined; + var nb: usize = 0; + for (targets, 0..) |target, i| { + sums[nb] = target - pitch * @as(f32, @floatFromInt(i)); + counts[nb] = 1; + nb += 1; + while (nb > 1 and sums[nb - 2] / counts[nb - 2] > sums[nb - 1] / counts[nb - 1]) { + sums[nb - 2] += sums[nb - 1]; + counts[nb - 2] += counts[nb - 1]; + nb -= 1; + } + } + var i: usize = 0; + const top = @max(hi - pitch * @as(f32, @floatFromInt(n - 1)), lo); + for (sums[0..nb], counts[0..nb]) |s, c| for (0..@intFromFloat(c)) |_| { + out[i] = std.math.clamp(s / c, lo, top) + pitch * @as(f32, @floatFromInt(i)); + i += 1; + }; +} + +// ------------------------------------------------------------- the drawing + +/// The program column's measures (mock 30): the bar 20 wide (inside 16), +/// the boxes 108 wide inside, the leaders' room, then the names. +const m = struct { + const bar = 160; + const bar_w = 20; + const box = 304; + const box_w = 108; + const leader = 8; + const address = 476; + const indent = 24; + const size_end = 632; + const name = 656; + const pitch = 24; + const mono = theme.size.mono.context; + /// Box heights: a cluster of one band; the rest share what is left. + const one = 72; + const gap_min = 24; +}; + +/// Frames of `enlarge` (motion.md): the line framed, the ride, the page lines, the names. +const e = struct { + const frame = 6; + const ride = 72; + const pages = 12; + const names = 90; + const apart = 2; + const leader = 6; + const fade = 12; +}; + +/// Under the camera (nearer than x1), nothing drawn under the stage (y 888): +/// the caption's band is the caption's. Returns the clip it replaced. +pub fn clipStage(f: *sk.Frame, placed: anim.Placed) ??sk.Rect { + const w = @floor(f.in.window_width); + const h = @floor(f.in.window_height); + const one = @min(w / theme.canvas.width, h / theme.canvas.height); + if (one <= 0 or placed.scale / one < 1.01) return null; + const was = ui.bound; + const stage: sk.Rect = .{ .x = 0, .y = 0, .w = w, .h = (h - theme.canvas.height * one) / 2 + (theme.canvas.stage.y + theme.canvas.stage.h) * one }; + ui.bound = stage; + f.clip(stage); + return was; +} + +pub fn unclipStage(f: *sk.Frame, was: ??sk.Rect) void { + const old = was orelse return; + ui.bound = old; + if (old) |r| f.clip(r) else f.clip(null); +} + +pub const Segments = struct { + rec: *const Recording, + at: u64, + x: f32 = theme.layout.program.x, + /// 0: the column's height (84 to 888); 1: the working frame's (80 to 864). + form: anim.Value, + /// Frames into the whole's build (negative: not begun). + whole: anim.Value, + /// Frames into each cluster's `enlarge`, top down (negative: not begun). + rides: [6]anim.Value, + /// `ink`'s echoes: the band holding `addr` framed as read, `shows` of it. + echoes: [16]Echo = undefined, + n_echoes: usize = 0, + + pub const Echo = struct { addr: u64, shows: anim.Value }; + + pub fn init(s: *anim.Frame, rec: *const Recording, at: u64) Segments { + var rides: [6]anim.Value = undefined; + for (&rides) |*r| r.* = s.value(-1); + return .{ .rec = rec, .at = at, .form = s.value(0), .whole = s.value(-1), .rides = rides }; + } + + /// The bar's top and foot at `form` (0 the column, 1 the working frame). + fn span(form: f32) [2]f32 { + const k = theme.ease(.glide, form); + return .{ std.math.lerp(84, 80, k), std.math.lerp(888, 864, k) }; + } + + pub const Layout = struct { + space: Space, + top: f32, + foot: f32, + /// Each cluster's box, as it lands (inside its frame). + boxes: [6]Rect, + /// Each cluster's line on the whole. + lines: [6]f32, + }; + + /// Where everything is at `form` (`Segments.form`'s value). + pub fn layout(g: *const Segments, form: f32, arena: std.mem.Allocator) Layout { + const ends = span(form); + const space = read(g.rec, g.at, arena); + var out: Layout = .{ .space = space, .top = ends[0], .foot = ends[1], .boxes = undefined, .lines = undefined }; + const n = @min(space.clusters.len, 6); + // Heights: a cluster of one band 72; the program's as its rows; the + // libraries' (the most units but the program's) what is left. + var heights: [6]f32 = @splat(0); + var fixed: f32 = 0; + var rest: ?usize = null; + for (space.clusters[0..n], 0..) |c, i| { + const lines: f32 = @floatFromInt(2 * (c.units[1] - c.units[0]) + 1); + const has_program = for (space.units[c.units[0]..c.units[1]]) |u| { + if (u.program) break true; + } else false; + if (c.bands[1] - c.bands[0] == 1 or lines <= 3) heights[i] = m.one else if (has_program) heights[i] = m.pitch * lines - 12 else if (rest == null) { + rest = i; + continue; + } else heights[i] = m.pitch * lines - 12; + fixed += heights[i]; + } + const gaps: f32 = @floatFromInt(@max(n, 1) - 1); + const room = ends[1] - ends[0]; + var gap: f32 = 44; + if (rest) |r| heights[r] = @max(room - fixed - gap * gaps, m.one) else gap = @max((room - fixed) / @max(gaps, 1), m.gap_min); + var y = ends[0]; + for (0..n) |i| { + out.boxes[i] = .{ .x = g.x + m.box, .y = y, .w = m.box_w, .h = heights[i] }; + y += heights[i] + gap; + // The lines on the whole: the top clusters 2 apart under its top, the foot's over its foot. + out.lines[i] = if (space.clusters[i].lo > user_end / 2) ends[0] + 2 + 2 * @as(f32, @floatFromInt(i)) else ends[1] - 4 - 2 * @as(f32, @floatFromInt(n - 1 - i)); + } + return out; + } + + /// Where `addr` is in its cluster's box once it has landed; null outside every box. + pub fn place(l: Layout, addr: u64) ?Vec { + for (l.space.clusters, 0..) |c, i| if (i < 6 and addr >= c.lo and addr < c.hi) { + const b = l.boxes[i]; + return .{ b.x + b.w / 2, b.y + b.h * @as(f32, @floatCast(@as(f64, @floatFromInt(c.hi - addr)) / @as(f64, @floatFromInt(c.hi - c.lo)))) }; + }; + return null; + } + + pub fn draw(g: *const Segments, f: *sk.Frame, placed: anim.Placed) void { + const u: ui.Ui = .{ .f = f, .at = placed }; + const l = g.layout(placed.value(g.form), f.scratch); + const whole = placed.value(g.whole); + if (whole < 0) return; + const was = clipStage(f, placed); + defer unclipStage(f, was); + const bar_x = g.x + m.bar; + const h = l.foot - l.top; + // The bar, from the top down (72 f), framed 2 in `dim`, coming in over its first 6 f. + const grown = h * theme.ease(.standard, std.math.clamp(whole / 72, 0, 1)); + u.faded(std.math.clamp(whole / 6, 0, 1)).frame(.{ .x = bar_x, .y = l.top, .w = m.bar_w, .h = @max(grown, 4) }, t.dim, theme.stroke.rule); + // Its ends' addresses and its size (18 f), ranged right 12 left of it. + const ends_in = std.math.clamp((whole - 72) / 18, 0, 1); + if (ends_in > 0) { + const v = u.faded(ends_in); + var buf: [16]u8 = undefined; + for ([_]struct { []const u8, f32 }{ .{ "7fffffffffff", l.top }, .{ "0", l.foot }, .{ size(&buf, user_end), (l.top + l.foot) / 2 } }) |row| + v.text(.mono, m.mono, bar_x - 12 - v.width(.mono, m.mono, row[0]), row[1] + 7.2, row[0], t.dim); + } + // Every mapping's line inside its end (12 f each, across 72 f). + const n = @min(l.space.clusters.len, 6); + for (0..n) |i| { + const shows = std.math.clamp((whole - 90 - 60 * @as(f32, @floatFromInt(i)) / @as(f32, @floatFromInt(@max(n, 2) - 1))) / 12, 0, 1); + if (shows > 0) u.faded(shows).fill(.{ .x = bar_x + 2, .y = l.lines[i], .w = m.bar_w - 4, .h = 2 }, biggest(l.space, l.space.clusters[i]).ink); + } + for (0..n) |i| g.enlarged(u, l, i, placed.value(g.rides[i])); + for (g.echoes[0..g.n_echoes]) |echo| g.echoed(u, l, echo.addr, placed.value(echo.shows)); + } + + /// The ink of a cluster's largest band (its line on the whole). + fn biggest(space: Space, c: Cluster) Band { + var best = space.bands[c.bands[0]]; + for (space.bands[c.bands[0]..c.bands[1]]) |b| if (b.hi - b.lo > best.hi - best.lo) { + best = b; + }; + return best; + } + + /// Cluster `i`'s `enlarge`, `clock` frames in. + fn enlarged(g: *const Segments, line_u: ui.Ui, l: Layout, i: usize, clock: f32) void { + if (clock < 0) return; + const c = l.space.clusters[i]; + const land = l.boxes[i]; + const bar_r = g.x + m.bar + m.bar_w; + const line_y = l.lines[i] + 1; + // The line framed bright (2 units, 3 out), going as the box lands. + const bright = std.math.clamp(clock / e.frame, 0, 1) * (1 - std.math.clamp((clock - 66) / 12, 0, 1)); + if (bright > 0) line_u.faded(bright).frame(.{ .x = g.x + m.bar - 1, .y = line_y - 5, .w = m.bar_w + 2, .h = 10 }, t.bright, theme.stroke.rule); + // The ride: the box's left corners along the magnification's lines. + const p = theme.ease(.glide, std.math.clamp((clock - e.frame) / e.ride, 0, 1)); + if (p <= 0) return; + const box: Rect = .{ + .x = std.math.lerp(bar_r, land.x, p), + .y = std.math.lerp(line_y, land.y, p), + .w = std.math.lerp(m.bar_w - 4, land.w, p), + .h = std.math.lerp(0, land.h, p), + }; + // Out of the line: the box comes in over the ride's first frames, never in one. + const u = line_u.faded(std.math.clamp(p * 8, 0, 1)); + u.line(.{ bar_r, line_y }, .{ box.x - 2, box.y - 1 }, theme.color.rule, theme.stroke.rule); + u.line(.{ bar_r, line_y }, .{ box.x - 2, box.y + box.h + 1 }, theme.color.rule, theme.stroke.rule); + // Its bands at its scale all the way: a mapping a 2-unit line until it is taller. + const scale = box.h / @as(f32, @floatFromInt(c.hi - c.lo)); + const pages = std.math.clamp((clock - e.frame - e.ride) / e.pages, 0, 1); + u.clip(.{ .x = box.x, .y = box.y - 1, .w = box.w, .h = box.h + 2 }); + for (l.space.bands[c.bands[0]..c.bands[1]], c.bands[0]..) |b, k| { + const top = box.y + @as(f32, @floatFromInt(c.hi - b.hi)) * scale; + const bh = @max(@as(f32, @floatFromInt(b.hi - b.lo)) * scale, 2); + u.fill(.{ .x = box.x, .y = top, .w = box.w, .h = bh }, ui.mix(theme.color.page, b.ink, 0.3)); + // Between two bands of one file a page line, where both are 6 tall. + if (k + 1 < c.bands[1] and pages > 0) { + const below = l.space.bands[k + 1]; + if (below.hi == b.lo and std.mem.eql(u8, below.name, b.name) and b.name.len > 0 and bh >= 6 and @as(f32, @floatFromInt(below.hi - below.lo)) * scale >= 6) + u.faded(pages).fill(.{ .x = box.x, .y = top + bh - 1, .w = box.w, .h = 2 }, theme.color.page); + } + } + u.unclip(); + u.frame(.{ .x = box.x - 2, .y = box.y - 2, .w = box.w + 4, .h = box.h + 4 }, t.dim, theme.stroke.rule); + // Its names, rows top down, once it has landed. + g.names(u, l, i, clock - e.names, scale); + } + + const Row = struct { kind: enum { edge, unit }, addr: u64, unit: usize, target: f32, ink: u24 }; + + /// Cluster `i`'s rows of names: an edge of every named unit, each unit + /// between its edges, top down (highest address first). + fn rows(l: Layout, i: usize, arena: std.mem.Allocator) []Row { + const c = l.space.clusters[i]; + const box = l.boxes[i]; + const scale = box.h / @as(f32, @floatFromInt(c.hi - c.lo)); + var out: std.ArrayList(Row) = .empty; + var k = c.units[1]; + while (k > c.units[0]) { + k -= 1; + const un = l.space.units[k]; + const tall = @as(f32, @floatFromInt(un.hi - un.lo)) * scale; + if (!un.program and tall < 6) continue; + const yh = box.y + @as(f32, @floatFromInt(c.hi - un.hi)) * scale; + const yl = box.y + @as(f32, @floatFromInt(c.hi - un.lo)) * scale; + const last = if (out.items.len > 0) out.items[out.items.len - 1] else null; + if (last == null or last.?.kind != .edge or last.?.addr != un.hi) out.append(arena, .{ .kind = .edge, .addr = un.hi, .unit = k, .target = yh, .ink = un.ink }) catch {}; + out.append(arena, .{ .kind = .unit, .addr = un.lo, .unit = k, .target = std.math.clamp((yh + yl) / 2, box.y, box.y + box.h), .ink = un.ink }) catch {}; + out.append(arena, .{ .kind = .edge, .addr = un.lo, .unit = k, .target = yl, .ink = un.ink }) catch {}; + } + // An edge two units share takes the ink of the one that starts there. + for (out.items, 0..) |*r, j| if (r.kind == .edge and j + 1 < out.items.len and out.items[j + 1].kind == .unit) { + r.ink = l.space.units[out.items[j + 1].unit].ink; + }; + return out.items; + } + + /// Where cluster `i`'s rows may stand: its share of the column, down to the gaps' middles. + fn share(l: Layout, i: usize) [2]f32 { + const n = @min(l.space.clusters.len, 6); + const lo = if (i == 0) l.top else (l.boxes[i - 1].y + l.boxes[i - 1].h + l.boxes[i].y) / 2 + 12; + const hi = if (i + 1 == n) l.foot + 12 else (l.boxes[i].y + l.boxes[i].h + l.boxes[i + 1].y) / 2 - 12; + return .{ lo, hi }; + } + + fn names(g: *const Segments, u: ui.Ui, l: Layout, i: usize, clock: f32, scale: f32) void { + if (clock < 0) return; + const all = rows(l, i, u.f.scratch); + if (all.len == 0) return; + var targets: [64]f32 = undefined; + var ys: [64]f32 = undefined; + const n = @min(all.len, 64); + for (all[0..n], 0..) |r, k| targets[k] = r.target; + const room = share(l, i); + pool(targets[0..n], ys[0..n], room[0], room[1], m.pitch); + const box = l.boxes[i]; + const right = box.x + box.w + 2; + const ax = g.x + m.address; + var buf: [32]u8 = undefined; + var first_program: ?usize = null; + var last_program: usize = 0; + for (all[0..n], 0..) |r, k| { + const at = clock - @as(f32, @floatFromInt(k)) * e.apart; + if (at <= 0) break; + const y = ys[k]; + const un = l.space.units[r.unit]; + switch (r.kind) { + .edge => { + const drawn = std.math.clamp(at / e.leader, 0, 1); + u.route(&.{ .{ right, r.target }, .{ right + m.leader, r.target }, .{ ax - 20, y }, .{ ax - 8, y } }, theme.color.rule, .{ .width = theme.stroke.rule, .head = null, .progress = drawn, .radius = 0 }); + const shows = std.math.clamp((at - e.leader) / e.fade, 0, 1); + if (shows > 0) _ = u.faded(shows).address(ax, y + 7.2, r.addr, .{ .ink = ui.rgb(r.ink) }); + }, + .unit => { + const v = u.faded(std.math.clamp(at / e.fade, 0, 1)); + if (un.prot) |p| v.text(.mono, m.mono, ax + m.indent, y + 7.2, &perms(p), t.dim); + const sz = size(&buf, un.hi - un.lo); + v.text(.mono, m.mono, g.x + m.size_end - v.width(.mono, m.mono, sz), y + 7.2, sz, t.dim); + if (un.program) { + if (first_program == null) first_program = k; + last_program = k; + } else v.text(.mono, m.mono, g.x + m.name, y + 7.2, un.name, t.primary); + // A file whose permissions differ: each part's written inside its band, where it is 28 tall. + if (un.prot == null) g.insides(v, l, i, un, scale); + }, + } + } + // The program's bracket and name, with its last row. + if (first_program) |a| { + const at = clock - @as(f32, @floatFromInt(last_program)) * e.apart; + const v = u.faded(std.math.clamp(at / e.fade, 0, 1)); + const bx = g.x + m.name - 14; + v.bracket(bx, ys[a] - 8, ys[last_program] + 8, theme.color.rule, theme.metric.bracket.quiet, -1, false); + v.text(.mono, m.mono, g.x + m.name, (ys[a] + ys[last_program]) / 2 + 7.2, l.space.program, t.primary); + } + } + + fn insides(_: *const Segments, v: ui.Ui, l: Layout, i: usize, un: Unit, scale: f32) void { + const c = l.space.clusters[i]; + const box = l.boxes[i]; + for (l.space.bands[c.bands[0]..c.bands[1]]) |b| if (b.lo >= un.lo and b.hi <= un.hi) { + const bh = @as(f32, @floatFromInt(b.hi - b.lo)) * scale; + if (bh < 28) continue; + const top = box.y + @as(f32, @floatFromInt(c.hi - b.hi)) * scale; + v.label(.mono, m.mono, .{ .x = box.x, .y = top, .w = box.w, .h = bh }, .center, &perms(b.prot), t.primary); + }; + } + + /// `ink`'s echo: the band holding `addr` framed as read inside its box + /// (2 units, 4 in from its sides, 6 over and under), its row of names with it. + fn echoed(g: *const Segments, u: ui.Ui, l: Layout, addr: u64, shows: f32) void { + if (shows <= 0) return; + const v = u.faded(shows); + const read_ink = theme.mark(.read).solid; + for (l.space.clusters, 0..) |c, i| if (i < 6 and addr >= c.lo and addr < c.hi) { + const box = l.boxes[i]; + const scale = box.h / @as(f32, @floatFromInt(c.hi - c.lo)); + for (l.space.bands[c.bands[0]..c.bands[1]]) |b| if (addr >= b.lo and addr < b.hi) { + const top = box.y + @as(f32, @floatFromInt(c.hi - b.hi)) * scale; + const bh = @max(@as(f32, @floatFromInt(b.hi - b.lo)) * scale, 2); + v.frame(.{ .x = box.x + 4, .y = top - 6, .w = box.w - 8, .h = bh + 12 }, read_ink, theme.stroke.rule); + }; + // Its row of names: the unit holding it. + const all = rows(l, i, u.f.scratch); + var targets: [64]f32 = undefined; + var ys: [64]f32 = undefined; + const n = @min(all.len, 64); + for (all[0..n], 0..) |r, k| targets[k] = r.target; + const room = share(l, i); + pool(targets[0..n], ys[0..n], room[0], room[1], m.pitch); + for (all[0..n], 0..) |r, k| if (r.kind == .unit) { + const un = l.space.units[r.unit]; + if (addr < un.lo or addr >= un.hi) continue; + const x0 = g.x + m.address + m.indent - 6; + v.frame(.{ .x = x0, .y = ys[k] - 12, .w = g.x + m.size_end + 6 - x0, .h = 24 }, read_ink, theme.stroke.rule); + }; + }; + } +}; + +/// A dump's place (design/README.md, `segments`, "a dump's place"): the +/// `tie` bracket on its rows in the stack's ink (6 f), then the `link` +/// from the bracket's top up into the stage's top margin (y 56), across, +/// and down onto the stack's box at the dump's address, head first (36 f, +/// `standard`); the stack's band framed bright as it lands (6 f in, 12 +/// out); then both quiet to standing (24 f, 60% toward the page). +pub const Place = struct { + segments: *const Segments, + addr: u64, + /// The bracket: its x and its rows' top and foot. + x: f32, + y0: f32, + y1: f32, + /// Frames into the tie (negative: not begun); frames into its quieting. + clock: anim.Value, + quiet: anim.Value, + + pub fn draw(p: *const Place, f: *sk.Frame, placed: anim.Placed) void { + const clock = placed.value(p.clock); + if (clock < 0) return; + const was = clipStage(f, placed); + defer unclipStage(f, was); + const u: ui.Ui = .{ .f = f, .at = placed }; + const k = 1 - (1 - theme.metric.arc.standing) * theme.ease(.glide, std.math.clamp(placed.value(p.quiet) / 24, 0, 1)); + const ink = ui.mix(theme.color.page, region.stack, k); + const v = u.faded(std.math.clamp(clock / 6, 0, 1)); + v.bracket(p.x, p.y0, p.y1, ink, theme.metric.bracket.tie, 1, false); + const l = p.segments.layout(placed.value(p.segments.form), f.scratch); + const to = Segments.place(l, p.addr) orelse return; + const top: f32 = 56; + const drawn = theme.ease(.standard, std.math.clamp((clock - 6) / 36, 0, 1)); + u.route(&.{ .{ p.x, p.y0 }, .{ p.x, top }, .{ to[0], top }, .{ to[0], to[1] } }, ink, .{ .width = theme.stroke.tie.link, .head = .{ 10, 10 }, .progress = drawn, .radius = 8 }); + // The stack's band framed bright as the head lands. + const bright = std.math.clamp((clock - 42) / 6, 0, 1) * (1 - std.math.clamp((clock - 48) / 12, 0, 1)); + if (bright > 0) for (l.space.clusters, 0..) |c, i| if (i < 6 and p.addr >= c.lo and p.addr < c.hi) { + const b = l.boxes[i]; + u.faded(bright).frame(.{ .x = b.x - 5, .y = b.y - 5, .w = b.w + 10, .h = b.h + 10 }, t.bright, theme.stroke.line); + }; + } +}; + +test "sizes as the names give them" { + var buf: [16]u8 = undefined; + try std.testing.expectEqualStrings("4 KiB", size(&buf, 4096)); + try std.testing.expectEqualStrings("132 KiB", size(&buf, 0x21000)); + try std.testing.expectEqualStrings("2.1 MiB", size(&buf, 0x223000)); + try std.testing.expectEqualStrings("64 MiB", size(&buf, 0x4002000)); + try std.testing.expectEqualStrings("128 TiB", size(&buf, user_end)); +} + +test "rows pooled round their mean, in order, inside their room" { + var ys: [4]f32 = undefined; + pool(&.{ 100, 100, 100, 300 }, &ys, 0, 1000, 24); + try std.testing.expectEqual(@as(f32, 76), ys[0]); + try std.testing.expectEqual(@as(f32, 124), ys[2]); + try std.testing.expectEqual(@as(f32, 300), ys[3]); + pool(&.{ 0, 0, 0, 0 }, &ys, 50, 1000, 24); + try std.testing.expectEqual(@as(f32, 50), ys[0]); + try std.testing.expectEqual(@as(f32, 122), ys[3]); +} diff --git a/anim/src/source.zig b/anim/src/source.zig index ab49bc0..aedbb3e 100644 --- a/anim/src/source.zig +++ b/anim/src/source.zig @@ -34,6 +34,8 @@ pub const Source = struct { descent: bool = false, /// Which box of its stage it is in: on the map the source may go on in `source_more`. part: @import("stage.zig").Part = .source, + /// Words after the file's name in its tag (a `pair`'s shared source: `both builds`). + tag: []const u8 = "", pub fn draw(p: *const Source, f: *sk.Frame, placed: anim.Placed) void { const box = p.stage.box(placed, p.part); @@ -56,7 +58,13 @@ pub const Source = struct { // The window: where the line it is on has it, and (as the mark // moves on) gliding to where the next one does. It never cuts. const going = now.advancing(); - const windows = [2]f32{ @as(f32, @floatFromInt(rec.shownFirst(span_fit, at[0]))) + skip, @as(f32, @floatFromInt(rec.shownFirst(span_fit, at[1]))) + skip }; + var windows = [2]f32{ @as(f32, @floatFromInt(rec.shownFirst(span_fit, at[0]))) + skip, @as(f32, @floatFromInt(rec.shownFirst(span_fit, at[1]))) + skip }; + // The panel growing or shrinking at rest (a column's change): its window glides + // from the one its old height has to its new one's, never a jump. + if (now.resting()) if (p.stage.resizing(placed, p.part)) |r| { + const ends = [2]f32{ @floatFromInt(rec.shownFirst(@intCast(theme.layout.rowsIn(r.from) + tail), at[1])), @floatFromInt(rec.shownFirst(@intCast(theme.layout.rowsIn(r.to) + tail), at[1])) }; + windows = @splat(std.math.lerp(ends[0], ends[1], r.p) + skip); + }; // Another file: the panel fades through (12 f out, 12 f in), its tag // naming the file it comes to. Farther than its own height in one // file (another function far off): its strip shows where it goes @@ -80,7 +88,7 @@ pub const Source = struct { const side: usize = if (jump) |j| @intFromBool(j.travel >= 0.5) else if (turn) @intFromBool(going >= 0.5) else if (far) @intFromBool(if (ui.mapping) going > 0 else going >= 0.75) else @intFromBool(going >= 0.5); const file = rec.sources[at[side].src]; const text = prepared(file.text, file.path) orelse return; - const first = if (jump) |j| (if (ui.mapping) std.math.lerp(windows[0], windows[1], cursors.glide(j.travel)) else windows[side]) else if (turn or far) windows[side] else std.math.lerp(windows[0], windows[1], cursors.glide(going)); + const first = if (jump) |j| (if (ui.mapping) std.math.lerp(windows[0], windows[1], cursors.glide(j.travel)) else windows[side]) else if (turn or far) windows[side] else std.math.lerp(windows[0], windows[1], cursors.glidePixels(going, now.plan.travel, @abs(windows[1] - windows[0]) * m.row * u.at.scale)); const fade: f32 = if (jump) |j| (if (ui.mapping) 1 else 1 - theme.ease(.glide, j.grow)) else if (turn) @abs(2 * going - 1) else if (far and !ui.mapping) (if (going < 0.5) 1 else @abs(4 * going - 3)) else 1; const lit = u.faded(fade); const from: u32 = @intFromFloat(@floor(first)); @@ -99,7 +107,7 @@ pub const Source = struct { for (now.marks, at, ¬es, lines_notes) |mk, a, *note, lines_note| note.* = if (p.descent and !a.here and a.line != 0) u.print("{s} waits at line {d} \u{00b7} the pc is in {s}", .{ context.frameName(u, rec, rec.register(lastShown(rec, mk), "rip")), a.line, whereIs(u, rec, mk) }) else lines_note; const swap = !std.mem.eql(u8, notes[0], notes[1]) and now.walking(); const titles = [2][]const u8{ rec.sources[at[0].src].name(), rec.sources[at[1].src].name() }; - const title = if (p.part == .source_more) u.print("{s}, continued", .{file.name()}) else file.name(); + const title = if (p.part == .source_more) u.print("{s}, continued", .{file.name()}) else if (p.tag.len > 0) u.print("{s} \u{00b7} {s}", .{ file.name(), p.tag }) else file.name(); const body = u.panel(box.w, box.h, if (turn) "" else title, .{ .focus = p.focus, .note = if (swap) "" else notes[side] }); // Its tag's file and note change with the fade through it; a note otherwise over the 12 f before the advance. if (turn) for (titles, [2]f32{ 1 - 2 * going, 2 * going - 1 }) |t, shows| u.faded(shows).tagTitle(t, p.focus); @@ -162,7 +170,7 @@ pub const Source = struct { if (waits) { // The number ringed: a 2-unit primary frame where the plaque would be, no wash. u.faded(shows).frame(.{ .x = theme.stroke.rule + 1, .y = mark_y + 1, .w = theme.metric.plaque.line + widen - 2, .h = m.row - 2 }, theme.color.text.primary, theme.stroke.rule); - if (!ui.mapping) ties.thread_waits = true; + if (!ui.mapping) ties.of(u.f).thread_waits = true; } else 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 }); diff --git a/anim/src/stage.zig b/anim/src/stage.zig index bbf5887..7b18064 100644 --- a/anim/src/stage.zig +++ b/anim/src/stage.zig @@ -102,6 +102,20 @@ pub const Stage = struct { return false; } + /// A move under way that changes `part`'s height: its height before and + /// after, and how far it has got (eased as the boxes are). Null otherwise. + pub fn resizing(st: *const Stage, at: anim.Placed, part: Part) ?struct { from: f32, to: f32, p: f32 } { + for (st.moves[0..st.count]) |m| { + const p = at.value(m.p); + if (p <= 0 or p >= 1) continue; + const a, const b = switch (part) { + inline else => |tag| .{ @field(m.from, @tagName(tag)).h, @field(m.to, @tagName(tag)).h }, + }; + if (a != b) return .{ .from = a, .to = b, .p = theme.ease(.glide, p) }; + } + return null; + } + pub fn box(st: *const Stage, at: anim.Placed, part: Part) Rect { const split = st.now(at); return switch (part) { diff --git a/anim/src/ties.zig b/anim/src/ties.zig index 1b6a6ed..b5214e3 100644 --- a/anim/src/ties.zig +++ b/anim/src/ties.zig @@ -1,8 +1,15 @@ //! Ties (design/README.md, "4. Ties"): the panes are one machine at //! different levels, and a tie says which thing in one pane a thing in -//! another is. Panels publish the `place`s of their things as they draw -//! (`anchor`); `Ties`, added after them, draws between places, along the -//! channels only, never across a letter or another tie: +//! another is. Every tie is a relation, and the relations are one data +//! problem (`relations.zig`): per frame, a table of the places the panels +//! drew their things at (`anchor`) and of the values they show that could +//! be addresses (`show`), both in the frame's own scratch (`sk.Frame.user`, +//! `of`); `Ties`, added after them, is the resolver: six passes over those +//! tables, each a loop over one (`Ties.draw`): candidates (a join of values +//! with places by address, or the step's own events against places), the +//! knobs (off unless the scene turned the kind on, where its default is +//! off), priority, the budget (the thread always; two active lines across +//! panes, the touch giving way first; one standing), route, draw. The kinds: //! //! - `thread` (standing): the source's current line is these //! instructions. Gold, 3: a bracket on the line, one on each run of its @@ -15,9 +22,10 @@ //! drawing. In the mark's colour, 2 wide: a bracket on the dump's row, //! a line down the gutter's right lane and along the lens's top lane, //! a bracket over the node's address. +//! - `touch`, `carry` (under `tied`; the carry the scene's knob), and +//! `aim` (the scene's knob, off by default): a word holding the address +//! of an instruction whose row is on screen, tied to that row. //! - `echo`: the same mark at the same instant in two panels; no line. -//! -//! Budget: one thread; for a step one link and one projection. const std = @import("std"); const sk = @import("sketch"); const anim = @import("anim"); @@ -27,9 +35,11 @@ const cursors = @import("cursor.zig"); const rows = @import("rows.zig"); const Recording = @import("Recording.zig"); const Stage = @import("stage.zig").Stage; +const relations = @import("relations.zig"); const theme = ui.theme; const time = theme.time; const Rect = ui.Rect; +pub const Pane = relations.Pane; /// A thing with a place on screen. pub const Place = union(enum) { @@ -64,59 +74,106 @@ pub const Place = union(enum) { floor, block: u64, - fn key(p: Place) u64 { - const low = (1 << 56) - 1; + /// Its kind in the key's top byte (`relations.keyOf`), its address or index below. + pub fn key(p: Place) u64 { + return switch (p) { + .register => |i| relations.keyOf(1, i), + .registers => relations.keyOf(2, 0), + .word => |a| relations.keyOf(3, a), + .slot_pin => |a| relations.keyOf(4, a), + .node => |a| relations.keyOf(5, a), + .node_address => |a| relations.keyOf(6, a), + .node_pin => |a| relations.keyOf(7, a), + .node_part => |a| relations.keyOf(8, a), + .dump_run => |a| relations.keyOf(9, a), + .source => relations.keyOf(10, 0), + .pc => relations.keyOf(11, 0), + .run => |k| relations.keyOf(12, k), + .dump_pin => |a| relations.keyOf(13, a), + .row => |a| relations.keyOf(14, a), + .floor => relations.keyOf(15, 0), + .block => |a| relations.keyOf(16, a), + }; + } + + /// The pane it is drawn in. + pub fn pane(p: Place) Pane { return switch (p) { - .register => |i| 1 << 56 | @as(u64, i), - .registers => 2 << 56, - .word => |a| 3 << 56 | (a & low), - .slot_pin => |a| 4 << 56 | (a & low), - .node => |a| 5 << 56 | (a & low), - .node_address => |a| 6 << 56 | (a & low), - .node_pin => |a| 7 << 56 | (a & low), - .node_part => |a| 8 << 56 | (a & low), - .dump_run => |a| 9 << 56 | (a & low), - .source => 10 << 56, - .pc => 11 << 56, - .run => |k| 12 << 56 | @as(u64, k), - .dump_pin => |a| 13 << 56 | (a & low), - .row => |a| 14 << 56 | (a & low), - .floor => 15 << 56, - .block => |a| 16 << 56 | (a & low), + .register, .registers => .registers, + .word, .slot_pin => .stack, + .node, .node_address, .node_pin, .node_part, .block => .drawing, + .dump_run, .dump_pin => .view, + .source => .source, + .pc, .run, .row, .floor => .disasm, }; } }; -/// The stack's window this frame: its first word, how many it shows, and -/// where its pin lane runs (canvas pixels: x, the first row's top, the -/// row's height). A link to a word outside it ends at its edge. -pub var stack_window: ?struct { first: u64, slots: usize, x: f32, top: f32, row: f32 } = null; -/// The disassembly's row the step's `touch` and `carry` leave from or reach, -/// this frame (canvas pixels: its right rule's x, the row's top, that x, its -/// bottom), where it is drawn (`Disasm.insn`). -pub var touch_row: ?[4]f32 = null; -/// The source's line waits (a `descent`: the pc is in code without source): -/// the thread waits with it, primary and 2 units. -pub var thread_waits = false; +/// The kinds of place keys, by number (`Place.key`). +const key_kind = struct { + const node_address = 6; + const node_pin = 7; + const slot_pin = 4; + const dump_pin = 13; + const run = 12; + const row = 14; +}; -/// What this frame's components have said so far, in canvas pixels: left, top, right, bottom. -/// shortcut: one table for the process, emptied by `Ties.draw`; a scene with two players at once wants it on the frame. -var table: [512]struct { key: u64, box: [4]f32 } = undefined; -var said: usize = 0; +/// A frame's relations: its tables (the working frame's, and the map's for +/// what the map's panels say) and the facts the panels publish beside them. +pub const State = struct { + work: relations.Tables = .{}, + map: relations.Tables = .{}, + /// The stack's window this frame: its first word, how many it shows, and + /// where its pin lane runs (canvas pixels: x, the first row's top, the + /// row's height). A link to a word outside it ends at its edge. + stack_window: ?struct { first: u64, slots: usize, x: f32, top: f32, row: f32 } = null, + /// The disassembly's row the step's `touch` and `carry` leave from or reach, + /// this frame (canvas pixels: its right rule's x, the row's top, that x, its + /// bottom), where it is drawn (`Disasm.insn`). + touch_row: ?[4]f32 = null, + /// The source's line waits (a `descent`: the pc is in code without source): + /// the thread waits with it, primary and 2 units. + thread_waits: bool = false, + stats: relations.Stats = .{}, +}; -/// `r` (in `u`'s units) is where `place` is, this frame. +/// The frame's relations, made in its scratch at the first place said. +pub fn of(f: *sk.Frame) *State { + if (f.user) |p| return @ptrCast(@alignCast(p)); + const st = f.scratch.create(State) catch @panic("ties: out of scratch memory"); + st.* = .{}; + f.user = st; + return st; +} + +/// `r` (in `u`'s units) is where `place` is, this frame. On the map (not +/// its strips) into the map's table. pub fn anchor(u: ui.Ui, place: Place, r: Rect) void { - if (said == table.len or ui.mapping) return; + if (ui.mapping and ui.strokes) return; const a = u.at.xf.apply(.{ r.x, r.y }); const b = u.at.xf.apply(.{ r.x + r.w, r.y + r.h }); - table[said] = .{ .key = place.key(), .box = .{ a[0], a[1], b[0], b[1] } }; - said += 1; + const st = of(u.f); + (if (ui.mapping) &st.map else &st.work).add(u.f.scratch, .{ .key = place.key(), .box = .{ a[0], a[1], b[0], b[1] }, .pane = place.pane() }); +} + +/// `value`, which may be an address, is shown at `r` (in `u`'s units) in +/// `pane`, a panel `panel_w` wide from `u`'s origin: `at` the address of +/// the word holding it (0: none), `ref` a register's index. +pub fn show(u: ui.Ui, value: u64, r: Rect, pane: Pane, at: u64, ref: u32, panel_w: f32) void { + if (ui.mapping and ui.strokes) return; + const a = u.at.xf.apply(.{ r.x, r.y }); + const b = u.at.xf.apply(.{ r.x + r.w, r.y + r.h }); + // Its panel's rules: a tie leaves by the one nearer its lane. + const rules = [2]f32{ u.at.xf.apply(.{ 0, 0 })[0], u.at.xf.apply(.{ panel_w, 0 })[0] }; + const st = of(u.f); + (if (ui.mapping) &st.map else &st.work).show(u.f.scratch, .{ .value = value, .box = .{ a[0], a[1], b[0], b[1] }, .pane = pane, .ref = ref, .at = at, .rules = rules }); } /// Where `place` is this frame, in canvas pixels (left, top, right, bottom), if a panel said. -pub fn find(place: Place) ?[4]f32 { - for (table[0..said]) |entry| if (entry.key == place.key()) return entry.box; - return null; +pub fn find(f: *sk.Frame, place: Place) ?[4]f32 { + const st = of(f); + return st.work.find(f.scratch, place.key()); } /// When register `i` strikes in this step: the registers one step wrote @@ -193,6 +250,34 @@ pub fn riseTime(n: usize) f32 { return @as(f32, @floatFromInt(n -| 1)) * apart + time.quick; } +/// What a candidate ties, found in the tables: the boxes (canvas pixels) +/// its kind's route and drawing read, and what it is of. +const Line = struct { + kind: relations.Kind, + /// Its source and target, and a third place its route needs (the + /// registers panel's edge, a slot's pin lane, a node's address). + from: [4]f32 = @splat(0), + to: [4]f32 = @splat(0), + third: [4]f32 = @splat(0), + value: u64 = 0, + /// The register a link or a beat leaves from. + name: []const u8 = "", + /// A link's target: a node's pin, a view's row, a slot's pin, or past the stack's window `words` away. + target: enum { node, row, slot, beyond } = .slot, + words: i64 = 0, + /// A projection: from the stack to a call's node (else from the view to a node's part); a write (else a read). + stacked: bool = false, + write: bool = false, + /// The word a projection, a touch or an aim is of; an aim's value before the step. + word: u64 = 0, + was: u64 = 0, + /// An aim's lanes into its word's panel: its panel's rules. + rules: [2]f32 = .{ 0, 0 }, +}; + +/// The most candidates a frame keeps: a few of each kind. +const max_lines = 64; + pub const Ties = struct { cursor: cursors.Cursor, stage: *const Stage, @@ -204,11 +289,11 @@ pub const Ties = struct { /// A link the scene plays on a beat of its own (`Context.tiesWith`). beat: ?*const Beat = null, + /// The resolver: six passes over the frame's tables, each a loop over one. pub fn draw(g: *const Ties, f: *sk.Frame, at: anim.Placed) void { - defer said = 0; - defer stack_window = null; - defer thread_waits = false; - defer touch_row = null; + const st = of(f); + const began = relations.clock(); + defer report(f, st, began); const now = g.cursor.now(at); // Diving or surfacing, the panels are on their way: no ties; nor while the map alone is looked at. for (@import("context.zig").zoomed) |z| if (z != null) return; @@ -216,16 +301,255 @@ pub const Ties = struct { // In canvas pixels, `k` of them a unit: places come from panels anywhere. var raw: ui.Ui = .{ .f = f, .at = at }; raw.at.xf = .identity; - const k = at.scale; - const split = g.stage.now(at); - if (g.threaded) thread(raw.faded(@import("context.zig").thread_shows), at, k); - if (g.beat) |b| named(raw, at, now, k, split, b); + const cx: Cx = .{ .g = g, .f = f, .st = st, .raw = raw, .at = at, .now = now, .k = at.scale, .split = g.stage.now(at) }; + // 1. Candidates: each kind's join, or the step's events against the places. + var lines: [max_lines]Line = undefined; + var cands: [max_lines]relations.Candidate = undefined; + var n: usize = 0; + cx.candidates(&lines, &cands, &n); + const found = relations.clock(); + // 2. Knobs: a kind whose default is off only where the scene turned it on. + var knobs = relations.Knobs.initOne(.always); + if (g.threaded) knobs.insert(.thread); + if (!g.quiet) knobs.insert(.links); + if (now.plan.carry >= 0) knobs.insert(.carry); + if (now.aim > 0) knobs.insert(.code); + var kept = relations.filter(cands[0..n], knobs); + // 3. Priority, then 4. the budget: it only removes. + relations.byPriority(kept); + kept = relations.cut(kept); + const passed = relations.clock(); + // 5. Route and 6. draw, in priority order: each kind's verb at its frames. + for (kept) |c| cx.drawLine(lines[c.from]); + st.stats.candidates = n; + st.stats.kept = kept.len; + st.stats.ns.candidates = found - began; + st.stats.ns.passes = passed - found; + st.stats.ns.draw = relations.clock() - passed; + } +}; + +/// A frame's resolver at work: the frame, its tables, the step. +const Cx = struct { + g: *const Ties, + f: *sk.Frame, + st: *State, + raw: ui.Ui, + at: anim.Placed, + now: cursors.Now, + k: f32, + split: theme.layout.Split, + + fn find(cx: Cx, place: Place) ?[4]f32 { + return cx.st.work.find(cx.f.scratch, place.key()); + } + + /// The node a field's address belongs to: the drawn node at or below it, within a record. + fn nodeOf(cx: Cx, addr: u64) ?u64 { + return cx.st.work.atOrBelow(cx.f.scratch, key_kind.node_address, addr, 64); + } + + /// Pass 1: every kind's candidates, into `lines` and `cands` (`n` of them). + fn candidates(cx: Cx, lines: *[max_lines]Line, cands: *[max_lines]relations.Candidate, n: *usize) void { + const now = cx.now; + const add = struct { + fn one(ls: *[max_lines]Line, cs: *[max_lines]relations.Candidate, at: *usize, line: Line, rank: u32) void { + if (at.* == max_lines) return; + ls[at.*] = line; + cs[at.*] = .{ .kind = line.kind, .rank = rank, .from = @intCast(at.*) }; + at.* += 1; + } + }.one; + if (cx.find(.source)) |line| add(lines, cands, n, .{ .kind = .thread, .from = line }, 0); + if (cx.g.beat) |b| { + const t = cx.at.value(b.t); + if (t >= 0 and t < b.total()) add(lines, cands, n, .{ .kind = .beat }, 0); + } + // Standing aims, at rest as in a step. + if (now.aim > 0) cx.aims(lines, cands, n, add); if (!now.walking()) return; - const linked = !g.quiet and g.link(raw, at, now, k, split); - const projected = g.projection(raw, at, now, k, split); - // Three lines at most: the touch is the first to give way (to an echo), where a step draws a link and a projection. - if (!(linked and projected)) g.touch(raw, at, now, k, split); - g.carry(raw, at, now, k); + cx.links(lines, cands, n, add); + cx.projections(lines, cands, n, add); + if (cx.touchLine()) |line| add(lines, cands, n, line, 0); + if (now.plan.carry >= 0) add(lines, cands, n, .{ .kind = .carry }, 0); + } + + /// `link`'s join: the registers' values the step struck ⋈ the places + /// with a pin lane at their address (a node's pin, a slot's, a view's + /// row), or past the stack's window; ranked in pwndbg's order. + fn links(cx: Cx, lines: *[max_lines]Line, cands: *[max_lines]relations.Candidate, n: *usize, add: anytype) void { + const t = &cx.st.work; + const gpa = cx.f.scratch; + const values = t.values.items(.value); + const by_value = t.byValue(gpa); + const keys = t.places.items(.key); + const by_key = t.byKey(gpa); + // One merge per kind of target, the nearer first: a node's pin, a slot's, a view's row. + var pairs: std.ArrayList(relations.Pair) = .empty; + const kinds = [3]struct { u8, u64 }{ .{ key_kind.node_pin, ~@as(u64, 0) }, .{ key_kind.slot_pin, ~@as(u64, 0) }, .{ key_kind.dump_pin, ~@as(u64, 15) } }; + var starts: [4]usize = undefined; + for (kinds, 0..) |kind, j| { + starts[j] = pairs.items.len; + relations.join(values, by_value, keys, by_key, kind[0], kind[1], &pairs, gpa); + } + starts[3] = pairs.items.len; + const panes = t.values.items(.pane); + const refs = t.values.items(.ref); + for (theme.metric.all_registers[0..16], 0..) |name, rank| { + const i = @import("context.zig").index(name).?; + if (cx.now.registerAge(i) != 0 or std.mem.eql(u8, name, "rsp")) continue; + // `tied`: rbp's move is its pin's flight in the stack's lane, not a link. + if (i == cursors.bp_index and cx.now.pinGone(1) != null) continue; + const regs = (cx.now.moment().regs(cx.now.rec.tid) catch null) orelse return; + const value = regs.named(name) orelse continue; + var line: Line = .{ .kind = .link, .name = name, .value = value }; + line.from = cx.find(.{ .register = i }) orelse continue; + line.third = cx.find(.registers) orelse continue; + // The value's targets, as the join found them. + const hit: ?struct { usize, u32 } = for (0..3) |j| { + const found = for (pairs.items[starts[j]..starts[j + 1]]) |pr| { + if (panes[pr.value] == .registers and refs[pr.value] == i) break pr.place; + } else null; + if (found) |p| break .{ j, p }; + } else null; + if (hit) |h| { + line.to = t.places.items(.box)[h[1]]; + line.target = switch (h[0]) { + 0 => .node, + 1 => .slot, + else => .row, + }; + } else if (cx.beyond(value)) |b| { + line.to = b.box; + line.target = .beyond; + line.words = b.words; + } else continue; + add(lines, cands, n, line, @intCast(rank)); + } + } + + /// A word of the stack outside its window: the link ends at the + /// window's edge, with a stub and how many words on it is. + fn beyond(cx: Cx, value: u64) ?struct { box: [4]f32, words: i64 } { + const w = cx.st.stack_window orelse return null; + if (value % 8 != 0 or rows.regionOf(cx.now.moment(), value) != .stack) return null; + const words = @as(i64, @bitCast(value -% w.first)) >> 3; + if (words >= 0 and words < w.slots) return null; + if (@abs(words) > 64) return null; + // Its nearest row's pin lane. + const y = if (words < 0) w.top else w.top + @as(f32, @floatFromInt(w.slots - 1)) * w.row; + return .{ .box = .{ w.x, y, w.x + 10 * cx.k, y + w.row }, .words = if (words < 0) words else words - @as(i64, @intCast(w.slots)) + 1 }; + } + + /// `projection`'s join: the step's events (its writes, then its reads) + /// ⋈ the runs of the lens's dump and the parts of the drawing made of + /// them; or a word of the stack ⋈ the call it is the way back of. + fn projections(cx: Cx, lines: *[max_lines]Line, cands: *[max_lines]relations.Candidate, n: *usize, add: anytype) void { + const rec = cx.now.rec; + const events = [2]struct { spans: []const Recording.Span, write: bool }{ + .{ .spans = rec.written(cx.now.stops[1], cx.now.stops[0]), .write = true }, + .{ .spans = rec.read(cx.now.stops[1], cx.now.stops[0]), .write = false }, + }; + var rank: u32 = 0; + for (events) |kind| for (kind.spans) |span| { + defer rank += 1; + // The run that begins where the bytes do (an element of an + // array), else the word they are in (a field of a node). + const word = if (cx.find(.{ .dump_run = span.addr }) != null) span.addr else span.addr & ~@as(u64, 7); + const slot = cx.find(.{ .word = span.addr }); + // (A return draws no line: its node's badge is struck with rax's digits.) + const stacked = kind.write and slot != null and cx.find(.{ .node_address = span.addr }) != null and cx.find(.{ .dump_run = word }) == null; + const run = if (stacked) slot.? else cx.find(.{ .dump_run = word }) orelse continue; + if (!stacked) _ = cx.find(.{ .node_part = word }) orelse continue; + const node_addr = if (stacked) span.addr else cx.nodeOf(word) orelse continue; + const over = cx.find(.{ .node_address = node_addr }) orelse continue; + add(lines, cands, n, .{ .kind = .projection, .from = run, .to = over, .stacked = stacked, .write = kind.write, .word = word }, rank); + }; + } + + /// `touch`: the step's touch event ⋈ the word's slot, from the row it leaves. + fn touchLine(cx: Cx) ?Line { + const now = cx.now; + if (now.plan.touch < 0 or now.time < now.plan.touch) return null; + const row = cx.st.touch_row orelse return null; + const tt = cursors.stackTouch(now.rec, now.stops[1], now.stops[0]) orelse return null; + const word = cx.find(.{ .word = tt.addr & ~@as(u64, 7) }) orelse return null; + const lane_pin = cx.find(.{ .slot_pin = tt.addr & ~@as(u64, 7) }) orelse return null; + return .{ .kind = .touch, .from = row, .to = word, .third = lane_pin, .write = tt.write }; + } + + /// `aim`'s join: the values on screen in memory that are code ⋈ the + /// disassembly's rows by address; standing, every one; for the step, + /// those of the words it writes or reads. Ranked by where they are, top first. + fn aims(cx: Cx, lines: *[max_lines]Line, cands: *[max_lines]relations.Candidate, n: *usize, add: anytype) void { + const t = &cx.st.work; + const gpa = cx.f.scratch; + const values = t.values.items(.value); + var pairs: std.ArrayList(relations.Pair) = .empty; + relations.join(values, t.byValue(gpa), t.places.items(.key), t.byKey(gpa), key_kind.row, ~@as(u64, 0), &pairs, gpa); + const panes = t.values.items(.pane); + const ats = t.values.items(.at); + const boxes = t.values.items(.box); + const step = cx.now.aim > 1.5; + const moment = cx.now.moment(); + // The words whose value was code before the step and is not now: the aim frays from its old row. + for (t.values.items(.value), 0..) |v, j| { + if (ats[j] == 0 or panes[j] == .registers) continue; + const was = (Recording.word(cx.now.before(), ats[j], 8) catch null) orelse continue; + if (was == v) continue; + // (Still code with a row: the join below has it, gliding from its old row.) + if (cx.find(.{ .row = v }) != null) continue; + const row = cx.find(.{ .row = was }) orelse continue; + if (step and !cx.touched(ats[j])) continue; + add(lines, cands, n, .{ .kind = .code, .from = boxes[j], .to = row, .value = v, .was = was, .word = ats[j], .rules = t.values.items(.rules)[j] }, @intFromFloat(@max(boxes[j][1], 0))); + } + for (pairs.items) |pr| { + const j = pr.value; + if (ats[j] == 0 or panes[j] == .registers) continue; + if (rows.regionOf(moment, values[j]) != .code) continue; + if (step and !cx.touched(ats[j])) continue; + const was = (Recording.word(cx.now.before(), ats[j], 8) catch null) orelse values[j]; + add(lines, cands, n, .{ .kind = .code, .from = boxes[j], .to = t.places.items(.box)[pr.place], .value = values[j], .was = was, .word = ats[j], .rules = t.values.items(.rules)[j] }, @intFromFloat(@max(boxes[j][1], 0))); + } + } + + /// Whether the step wrote or read the word at `addr`. + fn touched(cx: Cx, addr: u64) bool { + return cx.now.writeAge(addr, 8) == 0 or cx.now.wasRead(addr, 8); + } + + /// Pass 6 for one relation: its kind's verb at its frames. + fn drawLine(cx: Cx, line: Line) void { + switch (line.kind) { + .thread => cx.thread(line), + .beat => cx.named(), + .link => cx.link(line), + .projection => cx.projection(line), + .touch => cx.touch(line), + .carry => cx.carry(), + .code => cx.aim(line), + } + cx.st.stats.drawn += 1; + } + + /// The gold thread: the current line and its instructions, one mark. + fn thread(cx: Cx, line_box: Line) void { + const raw = cx.raw.faded(@import("context.zig").thread_shows); + const k = cx.k; + const line = line_box.from; + const x = cx.at.xf.apply(.{ theme.metric.tie.thread_x, 0 })[0]; + const gold = if (cx.st.thread_waits) ui.rgb(theme.color.text.primary) else ui.rgb(theme.mark(.current).solid); + const kind = if (cx.st.thread_waits) [2]f32{ theme.metric.bracket.quiet[0] * k, theme.metric.bracket.quiet[1] * k } else [2]f32{ theme.metric.bracket.thread[0] * k, theme.metric.bracket.thread[1] * k }; + raw.bracket(x, line[1] + 2 * k, line[3] - 2 * k, gold, kind, 1, false); + var bottom = line[3] - 2 * k; + var top = line[1] + 2 * k; + var n: usize = 0; + while (cx.find(.{ .run = n })) |run| : (n += 1) { + raw.bracket(x, run[1] + 2 * k, run[3] - 2 * k, gold, kind, 1, false); + bottom = @max(bottom, run[3] - 2 * k); + top = @min(top, run[1] + 2 * k); + } + if (n > 0) raw.fill(.{ .x = x - kind[0] / 2, .y = top, .w = kind[0], .h = bottom - top }, gold); } /// `touch` (design/README.md, "4. Ties"), `tied`, in a walked step: this @@ -236,26 +560,26 @@ pub const Ties = struct { /// rows), `standard`, from `Plan.touch`; held to the advance and drawn /// back into the row with it (12 f), or, a load carried, as the carry /// leaves the word. Only to a word on show: the window is there first. - fn touch(g: *const Ties, raw: ui.Ui, at: anim.Placed, now: cursors.Now, k: f32, split: theme.layout.Split) void { - if (now.plan.touch < 0 or now.time < now.plan.touch) return; - const row = touch_row orelse return; - const tt = cursors.stackTouch(g.cursor.rec, now.stops[1], now.stops[0]) orelse return; - const word = find(.{ .word = tt.addr & ~@as(u64, 7) }) orelse return; - const lane_pin = find(.{ .slot_pin = tt.addr & ~@as(u64, 7) }) orelse return; - const lane = at.xf.apply(.{ theme.metric.tie.touch_lane, 0 })[0]; + fn touch(cx: Cx, line: Line) void { + const now = cx.now; + const k = cx.k; + const row = line.from; + const word = line.to; + const lane_pin = line.third; + const lane = cx.at.xf.apply(.{ theme.metric.tie.touch_lane, 0 })[0]; // Onto the stack's rule nearer the lane: its left in the state column, its right // where it stands under the disassembly (a column's beat), the head pointing back. const left = lane_pin[0] - theme.metric.slot.lane * k; - const rule = if (left > lane) left else at.xf.apply(.{ split.stack.x + split.stack.w, 0 })[0]; + const rule = if (left > lane) left else cx.at.xf.apply(.{ cx.split.stack.x + cx.split.stack.w, 0 })[0]; const ya = (row[1] + row[3]) / 2; const yb = (word[1] + word[3]) / 2; const long = @abs(yb - ya) > 6 * theme.metric.context.row * k; const drawn = cursors.standard(std.math.clamp((now.time - now.plan.touch) / @as(f32, if (long) time.tied.touch_long else time.tied.touch), 0, 1)); - const back_at = if (now.plan.carry >= 0 and !tt.write) now.plan.carry else now.plan.advance; + const back_at = if (now.plan.carry >= 0 and !line.write) now.plan.carry else now.plan.advance; const back = cursors.standard(std.math.clamp((now.time - back_at) / time.quick, 0, 1)); if (back >= 1) return; - const color = theme.mark(if (tt.write) .write else .read).solid; - raw.route(&.{ .{ row[0], ya }, .{ lane, ya }, .{ lane, yb }, .{ rule, yb } }, color, .{ .width = theme.stroke.tie.projection * k, .head = .{ 7 * k, 8 * k }, .progress = @min(drawn, 1 - back), .radius = theme.metric.tie.radius * k }); + const color = theme.mark(if (line.write) .write else .read).solid; + cx.raw.route(&.{ .{ row[0], ya }, .{ lane, ya }, .{ lane, yb }, .{ rule, yb } }, color, .{ .width = theme.stroke.tie.projection * k, .head = .{ 7 * k, 8 * k }, .progress = @min(drawn, 1 - back), .radius = theme.metric.tie.radius * k }); } /// `carry` (design/README.md, "4. Ties"; `Levels.carry`), in a walked @@ -268,16 +592,19 @@ pub const Ties = struct { /// store's register framed as read the 6 f before; drawn back as the /// destination strikes (18 f). With `carry_value` the value's digits ride /// its head on a `raised` chip, landing as the strike. - fn carry(g: *const Ties, raw: ui.Ui, at: anim.Placed, now: cursors.Now, k: f32) void { - if (now.plan.carry < 0) return; - const rec = g.cursor.rec; + fn carry(cx: Cx) void { + const now = cx.now; + const k = cx.k; + const raw = cx.raw; + const at = cx.at; + const rec = now.rec; const tt = cursors.stackTouch(rec, now.stops[1], now.stops[0]) orelse return; const how = cursors.carried(rec, tt) orelse return; const i = @import("context.zig").index(how.reg) orelse return; - const reg = find(.{ .register = i }) orelse return; - const panel = find(.registers) orelse return; - const word = find(.{ .word = tt.addr & ~@as(u64, 7) }) orelse return; - const lane_pin = find(.{ .slot_pin = tt.addr & ~@as(u64, 7) }) orelse return; + const reg = cx.find(.{ .register = i }) orelse return; + const panel = cx.find(.registers) orelse return; + const word = cx.find(.{ .word = tt.addr & ~@as(u64, 7) }) orelse return; + const lane_pin = cx.find(.{ .slot_pin = tt.addr & ~@as(u64, 7) }) orelse return; const stack_rule = lane_pin[0] - theme.metric.slot.lane * k; const lane = at.xf.apply(.{ theme.metric.tie.projection_lane, 0 })[0]; const y_reg = (reg[1] + reg[3]) / 2; @@ -324,132 +651,95 @@ pub const Ties = struct { } } - /// The gold thread: the current line and its instructions, one mark. - fn thread(raw: ui.Ui, at: anim.Placed, k: f32) void { - const line = find(.source) orelse return; - const x = at.xf.apply(.{ theme.metric.tie.thread_x, 0 })[0]; - const gold = if (thread_waits) ui.rgb(theme.color.text.primary) else ui.rgb(theme.mark(.current).solid); - const kind = if (thread_waits) [2]f32{ theme.metric.bracket.quiet[0] * k, theme.metric.bracket.quiet[1] * k } else [2]f32{ theme.metric.bracket.thread[0] * k, theme.metric.bracket.thread[1] * k }; - raw.bracket(x, line[1] + 2 * k, line[3] - 2 * k, gold, kind, 1, false); - var bottom = line[3] - 2 * k; - var top = line[1] + 2 * k; - var n: usize = 0; - while (find(.{ .run = n })) |run| : (n += 1) { - raw.bracket(x, run[1] + 2 * k, run[3] - 2 * k, gold, kind, 1, false); - bottom = @max(bottom, run[3] - 2 * k); - top = @min(top, run[1] + 2 * k); - } - if (n > 0) raw.fill(.{ .x = x - kind[0] / 2, .y = top, .w = kind[0], .h = bottom - top }, gold); - } - /// The step's link: the first register it struck that now holds the /// address of a pinned thing (a stack slot, a node, a view's row). rip /// and rsp are where execution and the stack are, and have none. - fn link(g: *const Ties, raw: ui.Ui, at: anim.Placed, now: cursors.Now, k: f32, split: theme.layout.Split) bool { - const rec = g.cursor.rec; - const regs = (now.moment().regs(rec.tid) catch null) orelse return false; - for (theme.metric.all_registers[0..16]) |name| { - const i = @import("context.zig").index(name).?; - if (now.registerAge(i) != 0 or std.mem.eql(u8, name, "rsp")) continue; - // `tied`: rbp's move is its pin's flight in the stack's lane, not a link. - if (i == cursors.bp_index and now.pinGone(1) != null) continue; - const value = regs.named(name) orelse continue; - const since = linkSince(now, i); - const l = time.link; - const node = find(.{ .node_pin = value }) != null; - const drawn = cursors.standard(std.math.clamp((since - l.after) / linkTime(if (node) .node else .slot), 0, 1)); - const back = std.math.clamp((now.time - now.plan.advance) / l.out, 0, 1); - if (linkTo(raw, at, now, k, split, name, value, drawn, back)) return true; - } - return false; + fn link(cx: Cx, line: Line) void { + const now = cx.now; + const i = @import("context.zig").index(line.name).?; + const since = linkSince(now, i); + const l = time.link; + const drawn = cursors.standard(std.math.clamp((since - l.after) / linkTime(if (line.target == .node) .node else .slot), 0, 1)); + const back = std.math.clamp((now.time - now.plan.advance) / l.out, 0, 1); + cx.linkTo(line, drawn, back); } - /// A link from register `name` to what it points at (`value`): a node's + /// A link from register `line.name` to what it points at: a node's /// pin, a slot's, a view's row, or a slot past the stack's window (a - /// stub and a row count), `drawn` of the way and drawing back `back` of - /// it. False where `value` is no such place. - fn linkTo(raw: ui.Ui, at: anim.Placed, now: cursors.Now, k: f32, split: theme.layout.Split, name: []const u8, value: u64, drawn: f32, back: f32) bool { - const i = @import("context.zig").index(name) orelse return false; - const edge = find(.registers) orelse return false; - const from = find(.{ .register = i }) orelse return false; - const node = find(.{ .node_pin = value }); - // A view's row it points into: up the gutter to the row's left edge. - const row = if (node == null) find(.{ .dump_pin = value & ~@as(u64, 15) }) else null; - // A word of the stack outside its window: the link ends at the - // window's edge, with a stub and how many words on it is. - var beyond: ?i64 = null; - const target = node orelse find(.{ .slot_pin = value }) orelse row orelse edge: { - const w = stack_window orelse return false; - if (value % 8 != 0 or rows.regionOf(now.moment(), value) != .stack) return false; - const words = @as(i64, @bitCast(value -% w.first)) >> 3; - if (words >= 0 and words < w.slots) return false; - if (@abs(words) > 64) return false; - beyond = if (words < 0) words else words - @as(i64, @intCast(w.slots)) + 1; - // Its nearest row's pin lane. - const y = if (words < 0) w.top else w.top + @as(f32, @floatFromInt(w.slots - 1)) * w.row; - break :edge [4]f32{ w.x, y, w.x + 10 * k, y + w.row }; - }; - const l = time.link; - if (drawn <= 0 or back >= 1) return true; - const color = rows.ink(rows.regionOf(now.moment(), value)); + /// stub and a row count), `drawn` of the way and drawing back `back` of it. + fn linkTo(cx: Cx, line: Line, drawn: f32, back: f32) void { + const now = cx.now; + const k = cx.k; + const raw = cx.raw; + const at = cx.at; + const edge = line.third; + const from = line.from; + const target = line.to; + if (drawn <= 0 or back >= 1) return; + const color = rows.ink(rows.regionOf(now.moment(), line.value)); const y = (from[1] + from[3]) / 2; // What climbs into the band takes the gutter's left lane; what // goes down to a slot, the right. - const lane = at.xf.apply(.{ if (node != null or row != null) theme.metric.tie.link_lane else theme.metric.tie.projection_lane, 0 })[0]; + const lane = at.xf.apply(.{ if (line.target == .node or line.target == .row) theme.metric.tie.link_lane else theme.metric.tie.projection_lane, 0 })[0]; var points: [5]ui.Vec = undefined; var n: usize = 0; points[0] = .{ edge[0] + 2 * k, y }; points[1] = .{ lane, y }; - if (node) |pin| { - // Up the gutter, along the lens's bottom lane, up into the pin under the node. - const bottom = at.xf.apply(.{ 0, split.band.y + split.band.h - theme.metric.lens.bottom_lane })[1]; - const cx = (pin[0] + pin[2]) / 2; - points[2] = .{ lane, bottom }; - points[3] = .{ cx, bottom }; - points[4] = .{ cx, pin[1] }; - n = 5; - } else if (beyond) |words| { - // Off the window: to its nearest row, into the pin lane, out - // to the panel's rule, where a head points on. - const mid = (target[1] + target[3]) / 2; - const rule = if (words < 0) target[1] - 6 * k else target[3] + 6 * k; - points[2] = .{ lane, mid }; - points[3] = .{ target[0] + 6 * k, mid }; - points[4] = .{ target[0] + 6 * k, rule }; - n = 5; - } else { - // Along the gutter to the row, and into its pin lane (a view's row: to its edge). - const mid = (target[1] + target[3]) / 2; - points[2] = .{ lane, mid }; - points[3] = .{ target[0] + (if (row != null) @as(f32, 2) else -2) * k, mid }; - n = 4; + switch (line.target) { + .node => { + // Up the gutter, along the lens's bottom lane, up into the pin under the node. + const bottom = at.xf.apply(.{ 0, cx.split.band.y + cx.split.band.h - theme.metric.lens.bottom_lane })[1]; + const cx_ = (target[0] + target[2]) / 2; + points[2] = .{ lane, bottom }; + points[3] = .{ cx_, bottom }; + points[4] = .{ cx_, target[1] }; + n = 5; + }, + .beyond => { + // Off the window: to its nearest row, into the pin lane, out + // to the panel's rule, where a head points on. + const mid = (target[1] + target[3]) / 2; + const rule = if (line.words < 0) target[1] - 6 * k else target[3] + 6 * k; + points[2] = .{ lane, mid }; + points[3] = .{ target[0] + 6 * k, mid }; + points[4] = .{ target[0] + 6 * k, rule }; + n = 5; + }, + .slot, .row => { + // Along the gutter to the row, and into its pin lane (a view's row: to its edge). + const mid = (target[1] + target[3]) / 2; + points[2] = .{ lane, mid }; + points[3] = .{ target[0] + (if (line.target == .row) @as(f32, 2) else -2) * k, mid }; + n = 4; + }, } - raw.route(points[0..n], color, .{ .width = theme.stroke.tie.link * k, .head = if (beyond == null) .{ 10 * k, 10 * k } else .{ 9 * k, 12 * k }, .progress = drawn, .from = cursors.standard(back), .radius = theme.metric.tie.radius * k }); - if (beyond) |words| if (drawn >= 1) { + const past = line.target == .beyond; + raw.route(points[0..n], color, .{ .width = theme.stroke.tie.link * k, .head = if (!past) .{ 10 * k, 10 * k } else .{ 9 * k, 12 * k }, .progress = drawn, .from = cursors.standard(back), .radius = theme.metric.tie.radius * k }); + if (past and drawn >= 1) { // How far the target is, faint, 6 past the head. const v = raw.faded(1 - back); const tip = points[4]; - v.text(.mono, theme.size.mono.context, tip[0] + 12 * k, tip[1] + (if (words < 0) @as(f32, 6) else 14) * k, v.print("{d} rows", .{@abs(words)}), theme.color.text.faint); - }; + v.text(.mono, theme.size.mono.context, tip[0] + 12 * k, tip[1] + (if (line.words < 0) @as(f32, 6) else 14) * k, v.print("{d} rows", .{@abs(line.words)}), theme.color.text.faint); + } // The pin rides the line's head: the register's name beside it. - if (drawn > 0 and drawn < 1 and beyond == null) { + if (drawn > 0 and drawn < 1 and !past) { const tip = along(points[0..n], drawn); - raw.text(.mono_bold, theme.size.mono.context, tip[0] + 8 * k, tip[1] - 6 * k, name, theme.color.text.primary); + raw.text(.mono_bold, theme.size.mono.context, tip[0] + 8 * k, tip[1] - 6 * k, line.name, theme.color.text.primary); } - _ = l; - return true; } /// The scene's `Beat`: its register framed as read, then its link. - fn named(raw: ui.Ui, at: anim.Placed, now: cursors.Now, k: f32, split: theme.layout.Split, b: *const Beat) void { + fn named(cx: Cx) void { + const b = cx.g.beat.?; + const now = cx.now; + const at = cx.at; const t = at.value(b.t); - if (t < 0 or t >= b.total()) return; const i = @import("context.zig").index(b.name) orelse return; - const px = find(.{ .register = i }) orelse return; + const px = cx.find(.{ .register = i }) orelse return; const l = time.link; const back = std.math.clamp((t - (b.total() - l.out)) / l.out, 0, 1); // Its value framed as read, in the panel's units. - const u: ui.Ui = .{ .f = raw.f, .at = at }; + const u: ui.Ui = .{ .f = cx.raw.f, .at = at }; const inv = at.xf.invert(); const a = inv.apply(.{ px[0], px[1] }); const c = inv.apply(.{ px[2], px[3] }); @@ -458,75 +748,182 @@ pub const Ties = struct { const regs = (now.moment().regs(rec.tid) catch null) orelse return; const value = regs.named(b.name) orelse return; const drawn = cursors.standard(std.math.clamp((t - l.after) / l.in_far, 0, 1)); - _ = linkTo(raw, at, now, k, split, b.name, value, drawn, back); + // Its target as a link's: a node's pin, a slot's, a view's row, or past the window. + var line: Line = .{ .kind = .beat, .name = b.name, .value = value, .from = px }; + line.third = cx.find(.registers) orelse return; + if (cx.find(.{ .node_pin = value })) |p| { + line.to = p; + line.target = .node; + } else if (cx.find(.{ .slot_pin = value })) |p| { + line.to = p; + line.target = .slot; + } else if (cx.find(.{ .dump_pin = value & ~@as(u64, 15) })) |p| { + line.to = p; + line.target = .row; + } else if (cx.beyond(value)) |bb| { + line.to = bb.box; + line.target = .beyond; + line.words = bb.words; + } else return; + cx.linkTo(line, drawn, back); } /// The step's projection: the first run of bytes it read or wrote in /// the lens's dump that a part of the drawing is made of. - fn projection(g: *const Ties, raw: ui.Ui, at: anim.Placed, now: cursors.Now, k: f32, split: theme.layout.Split) bool { - const rec = g.cursor.rec; - const kinds = [2]struct { spans: []const @import("Recording.zig").Span, role: theme.Role }{ - .{ .spans = rec.written(now.stops[1], now.stops[0]), .role = .write }, - .{ .spans = rec.read(now.stops[1], now.stops[0]), .role = .read }, - }; - for (kinds) |kind| for (kind.spans) |span| { - // The run that begins where the bytes do (an element of an - // array), else the word they are in (a field of a node). - const word = if (find(.{ .dump_run = span.addr }) != null) span.addr else span.addr & ~@as(u64, 7); - // From the dump's run to the part of the drawing made of it; or - // from a word of the stack to the call it is the way back of. - const slot = find(.{ .word = span.addr }); - // (A return draws no line: its node's badge is struck with rax's digits.) - const stacked = kind.role == .write and slot != null and find(.{ .node_address = span.addr }) != null and find(.{ .dump_run = word }) == null; - const run = if (stacked) slot.? else find(.{ .dump_run = word }) orelse continue; - if (!stacked) _ = find(.{ .node_part = word }) orelse continue; - const node_addr = if (stacked) span.addr else nodeOf(word) orelse continue; - const over = find(.{ .node_address = node_addr }) orelse continue; - const p = time.project; - // Under `tied`, once what made them has shown (a call's push, rsp's pin landed: `Plan.project`). - const since = if (now.plan.project >= 0) now.time - now.plan.project else now.since(.memory, 0); - const bracket = std.math.clamp(since / p.bracket, 0, 1); - const drawn = cursors.standard(std.math.clamp((since - p.bracket) / @as(f32, if (stacked) p.far else p.draw), 0, 1)); - const out = 1 - std.math.clamp((now.time - now.plan.advance) / p.out, 0, 1); - if (bracket <= 0 or out <= 0) return true; - const color = theme.mark(kind.role).solid; - const v = raw.faded(out); - const tie = [2]f32{ theme.metric.bracket.tie[0] * k, theme.metric.bracket.tie[1] * k }; - // The bracket takes the row: x 7 of the dump, the row's height; - // on the stack, the panel's left padding. - const bx = if (stacked) run[0] - (theme.metric.slot.address - 5) * k else run[0] - (rows.byteX(@intCast(word % 16)) - 4 - theme.metric.bytes.bracket) * k; - v.faded(bracket).bracket(bx, run[1] + 2 * k, run[3] - 2 * k, color, tie, 1, false); - const cx = (over[0] + over[2]) / 2; - const y = (run[1] + run[3]) / 2; - if (stacked) { - // A frame's way back to its call's node: up the gutter's - // left lane, along the drawing's bottom lane, up to a - // bracket under the node, serifs up. - const lane = at.xf.apply(.{ theme.metric.tie.link_lane, 0 })[0]; - const bottom = at.xf.apply(.{ 0, split.band.y + split.band.h - theme.metric.lens.bottom_lane })[1]; - v.route(&.{ .{ bx - 1 * k, y }, .{ lane, y }, .{ lane, bottom }, .{ cx, bottom }, .{ cx, over[3] + 5 * k } }, color, .{ .width = theme.stroke.tie.projection * k, .head = null, .progress = drawn, .radius = theme.metric.tie.projection_radius * k }); - if (drawn >= 1) { - v.fill(.{ .x = over[0], .y = over[3] + 2 * k, .w = over[2] - over[0], .h = 3 * k }, color); - v.fill(.{ .x = over[0], .y = over[3] - 3 * k, .w = 3 * k, .h = 8 * k }, color); - v.fill(.{ .x = over[2] - 3 * k, .y = over[3] - 3 * k, .w = 3 * k, .h = 8 * k }, color); - } - return true; - } - const lane = at.xf.apply(.{ theme.metric.tie.projection_lane, 0 })[0]; - const top = at.xf.apply(.{ 0, split.band.y + theme.metric.context.tag + theme.metric.lens.top_lane })[1]; - v.route(&.{ .{ bx - 1 * k, y }, .{ lane, y }, .{ lane, top }, .{ cx, top }, .{ cx, over[1] - 4 * k } }, color, .{ .width = theme.stroke.tie.projection * k, .head = null, .progress = drawn, .radius = theme.metric.tie.projection_radius * k }); - // Over the node's address: a bracket, serifs down. + fn projection(cx: Cx, line: Line) void { + const now = cx.now; + const k = cx.k; + const at = cx.at; + const run = line.from; + const over = line.to; + const stacked = line.stacked; + const word = line.word; + const p = time.project; + // Under `tied`, once what made them has shown (a call's push, rsp's pin landed: `Plan.project`). + const since = if (now.plan.project >= 0) now.time - now.plan.project else now.since(.memory, 0); + const bracket = std.math.clamp(since / p.bracket, 0, 1); + const drawn = cursors.standard(std.math.clamp((since - p.bracket) / @as(f32, if (stacked) p.far else p.draw), 0, 1)); + const out = 1 - std.math.clamp((now.time - now.plan.advance) / p.out, 0, 1); + if (bracket <= 0 or out <= 0) return; + const color = theme.mark(if (line.write) .write else .read).solid; + const v = cx.raw.faded(out); + const tie = [2]f32{ theme.metric.bracket.tie[0] * k, theme.metric.bracket.tie[1] * k }; + // The bracket takes the row: x 7 of the dump, the row's height; + // on the stack, the panel's left padding. + const bx = if (stacked) run[0] - (theme.metric.slot.address - 5) * k else run[0] - (rows.byteX(@intCast(word % 16)) - 4 - theme.metric.bytes.bracket) * k; + v.faded(bracket).bracket(bx, run[1] + 2 * k, run[3] - 2 * k, color, tie, 1, false); + const cx_ = (over[0] + over[2]) / 2; + const y = (run[1] + run[3]) / 2; + if (stacked) { + // A frame's way back to its call's node: up the gutter's + // left lane, along the drawing's bottom lane, up to a + // bracket under the node, serifs up. + const lane = at.xf.apply(.{ theme.metric.tie.link_lane, 0 })[0]; + const bottom = at.xf.apply(.{ 0, cx.split.band.y + cx.split.band.h - theme.metric.lens.bottom_lane })[1]; + v.route(&.{ .{ bx - 1 * k, y }, .{ lane, y }, .{ lane, bottom }, .{ cx_, bottom }, .{ cx_, over[3] + 5 * k } }, color, .{ .width = theme.stroke.tie.projection * k, .head = null, .progress = drawn, .radius = theme.metric.tie.projection_radius * k }); if (drawn >= 1) { - v.fill(.{ .x = over[0], .y = over[1] - 5 * k, .w = over[2] - over[0], .h = 3 * k }, color); - v.fill(.{ .x = over[0], .y = over[1] - 5 * k, .w = 3 * k, .h = 8 * k }, color); - v.fill(.{ .x = over[2] - 3 * k, .y = over[1] - 5 * k, .w = 3 * k, .h = 8 * k }, color); + v.fill(.{ .x = over[0], .y = over[3] + 2 * k, .w = over[2] - over[0], .h = 3 * k }, color); + v.fill(.{ .x = over[0], .y = over[3] - 3 * k, .w = 3 * k, .h = 8 * k }, color); + v.fill(.{ .x = over[2] - 3 * k, .y = over[3] - 3 * k, .w = 3 * k, .h = 8 * k }, color); } - return true; - }; - return false; + return; + } + const lane = at.xf.apply(.{ theme.metric.tie.projection_lane, 0 })[0]; + const top = at.xf.apply(.{ 0, cx.split.band.y + theme.metric.context.tag + theme.metric.lens.top_lane })[1]; + v.route(&.{ .{ bx - 1 * k, y }, .{ lane, y }, .{ lane, top }, .{ cx_, top }, .{ cx_, over[1] - 4 * k } }, color, .{ .width = theme.stroke.tie.projection * k, .head = null, .progress = drawn, .radius = theme.metric.tie.projection_radius * k }); + // Over the node's address: a bracket, serifs down. + if (drawn >= 1) { + v.fill(.{ .x = over[0], .y = over[1] - 5 * k, .w = over[2] - over[0], .h = 3 * k }, color); + v.fill(.{ .x = over[0], .y = over[1] - 5 * k, .w = 3 * k, .h = 8 * k }, color); + v.fill(.{ .x = over[2] - 3 * k, .y = over[1] - 5 * k, .w = 3 * k, .h = 8 * k }, color); + } + } + + /// `aim` (design/README.md, "4. Ties"; the scene's knob, off by default): + /// this word holds the address of that instruction. 2 units in code's + /// ink, a filled head: out of the word's panel's rule nearer the gutter, + /// along its left lane (x 950), onto the disassembly's right rule level + /// with the row, whose address is framed in code's ink as the head lands. + /// Standing, 60% toward the page, in and out with the knob (18 f); for + /// the step, full, after the word's mark (18 f, 24 past ten rows), back + /// with the advance. Written again: still code with its row shown, the + /// head glides to it (24 f) after the strike; no longer code, it frays + /// (dashed over 12 f, gone over 18 more). The disassembly never moves for it. + fn aim(cx: Cx, line: Line) void { + const now = cx.now; + const k = cx.k; + const at = cx.at; + const step = now.aim > 1.5; + const lane = at.xf.apply(.{ theme.metric.tie.link_lane, 0 })[0]; + // Leaves by its panel's rule nearer the lane. + const rule = if (@abs(line.rules[0] - lane) < @abs(line.rules[1] - lane)) line.rules[0] else line.rules[1]; + const y_word = (line.from[1] + line.from[3]) / 2; + // Where the word changed this step: its strike, and the row it held. + const struck: ?f32 = if (line.was != line.value) now.struckAgo(line.word, 8) else null; + const old_row = if (line.was != line.value) cx.find(.{ .row = line.was }) else null; + const code_now = rows.regionOf(now.moment(), line.value) == .code; + const new_row = if (code_now) cx.find(.{ .row = line.value }) else null; + // The head: on the old row until the strike, then gliding to the new one (24 f); fraying where there is none. + var y_row = (line.to[1] + line.to[3]) / 2; + var fray: f32 = 0; + var row_box = line.to; + if (old_row) |o| { + const after = if (struck) |sa| sa else if (now.resting()) std.math.inf(f32) else -1; + if (new_row) |nr| { + const p = cursors.glide(std.math.clamp(after / (24.0 / 60.0), 0, 1)); + y_row = std.math.lerp((o[1] + o[3]) / 2, (nr[1] + nr[3]) / 2, p); + row_box = if (p < 0.5) o else nr; + } else { + y_row = (o[1] + o[3]) / 2; + row_box = o; + fray = std.math.clamp(after / (30.0 / 60.0), 0, 1); + if (fray >= 1) return; + } + } + const right = row_box[2]; + // How much it shows: standing with the knob (18 f in and out), for the step from the word's mark to the advance. + var drawn: f32 = 1; + var shows: f32 = if (step) 1 else @min(now.aim, 1); + if (step) { + if (now.resting()) return; + const from = @max(now.plan.at[1], 0) + time.strike.in; + const long = @abs(y_row - y_word) > 10 * theme.metric.context.row * k; + drawn = cursors.standard(std.math.clamp((now.time - from) / @as(f32, if (long) 24.0 / 60.0 else 18.0 / 60.0), 0, 1)); + shows = 1 - std.math.clamp((now.time - now.plan.advance) / time.quick, 0, 1); + } + if (drawn <= 0 or shows <= 0) return; + // Standing, 60% toward the page; fraying, dashed over its first 12 f, then fading. + const ink = if (step) ui.rgb(theme.color.region.code_) else ui.mix(theme.color.region.code_, theme.color.page, 0.6); + const v = cx.raw.faded(shows * (1 - std.math.clamp((fray - 0.4) / 0.6, 0, 1))); + const points = [4]ui.Vec{ .{ rule, y_word }, .{ lane, y_word }, .{ lane, y_row }, .{ right, y_row } }; + if (fray > 0) { + // Dashed, 12 on 8, the gaps opening over the fray's first 12 f. + const open = std.math.clamp(fray / 0.4, 0, 1); + dashed(v, &points, ink, theme.stroke.rule * k, 12 * k, 8 * k * open); + } else v.route(&points, ink, .{ .width = theme.stroke.rule * k, .head = .{ 8 * k, 8 * k }, .progress = drawn, .radius = theme.metric.tie.radius * k }); + // The row's address framed in code's ink as the head lands. + if (drawn >= 1 and fray == 0) { + const adv = ui.advance(theme.size.mono.context) * k; + const digits: f32 = @floatFromInt(ui.digits(if (row_box[1] == line.to[1]) line.value else line.was)); + const x0 = row_box[0] + (theme.metric.insn.address - 4) * k; + v.frame(.{ .x = x0, .y = row_box[1], .w = digits * adv + 8 * k, .h = row_box[3] - row_box[1] }, ink, theme.stroke.rule * k); + } } }; +/// `points` as dashes `on` long with gaps `off` wide, `width` thick. +fn dashed(u: ui.Ui, points: []const ui.Vec, ink: anytype, width: f32, on: f32, off: f32) void { + for (points[0 .. points.len - 1], points[1..]) |a, b| { + const d = sk.math.distance(a, b); + if (d <= 0) continue; + var s: f32 = 0; + while (s < d) : (s += on + off) { + const e = @min(s + on, d); + u.line(sk.math.mix(a, b, s / d), sk.math.mix(a, b, e / d), ink, width); + } + } +} + +/// The frame's counts and times, on stderr with `CANIM_RELATIONS=1`; and, +/// for the measure, the map's join of its values with its rows. +fn report(f: *sk.Frame, st: *State, began: u64) void { + if (!relations.reporting()) return; + st.stats.places = st.work.places.len; + st.stats.values = st.work.values.len; + st.stats.ns.sort = st.work.sort_ns; + st.stats.map_places = st.map.places.len; + st.stats.map_values = st.map.values.len; + if (st.map.places.len > 0) { + const start = relations.clock(); + var pairs: std.ArrayList(relations.Pair) = .empty; + relations.join(st.map.values.items(.value), st.map.byValue(f.scratch), st.map.places.items(.key), st.map.byKey(f.scratch), key_kind.row, ~@as(u64, 0), &pairs, f.scratch); + st.stats.map_pairs = pairs.items.len; + st.stats.ns.map = relations.clock() - start; + } + const x = st.stats; + std.debug.print("relations frame {d} places {d} values {d} candidates {d} kept {d} drawn {d} ns sort {d} candidates {d} passes {d} draw {d} all {d} map places {d} values {d} pairs {d} ns {d}\n", .{ f.in.frame, x.places, x.values, x.candidates, x.kept, x.drawn, x.ns.sort, x.ns.candidates, x.ns.passes, x.ns.draw, relations.clock() - began, x.map_places, x.map_values, x.map_pairs, x.ns.map }); +} + /// A link the narration plays on a beat the caption names, not a step's: /// register `name` framed as read (6 f), then its link to what it points at /// (6 f after, 36 f, `standard`, the name riding its head), held `hold`, @@ -565,17 +962,6 @@ fn along(points: []const ui.Vec, p: f32) ui.Vec { return points[points.len - 1]; } -/// The node a field's address belongs to: the drawn node at or below it, within a record. -fn nodeOf(addr: u64) ?u64 { - var best: ?u64 = null; - for (table[0..said]) |entry| { - if (entry.key >> 56 != 6) continue; - const a = entry.key & ((1 << 56) - 1); - if (a <= addr and addr - a < 64 and (best == null or a > best.?)) best = a; - } - return best; -} - test "places have keys of their own" { try std.testing.expect((Place{ .word = 0x1000 }).key() != (Place{ .node = 0x1000 }).key()); try std.testing.expect((Place{ .source = {} }).key() != (Place{ .pc = {} }).key()); diff --git a/anim/test/asan.script b/anim/test/asan.script new file mode 100644 index 0000000..db1dc2c --- /dev/null +++ b/anim/test/asan.script @@ -0,0 +1,10 @@ +# The ASan pair, headless: it runs to three instants of its timeline without failing +# (the two runs together, plain alone with ASan stopped on its report, the close). +frames 2 +console set playing false +console set t 20 +screenshot .zig-cache/canim/asan-early.png +console set t 70 +screenshot .zig-cache/canim/asan-mid.png +console set t 999 +screenshot .zig-cache/canim/asan-end.png diff --git a/anim/test/intro_code.script b/anim/test/intro_code.script new file mode 100644 index 0000000..58811a4 --- /dev/null +++ b/anim/test/intro_code.script @@ -0,0 +1,12 @@ +# The introduction's third chapter, headless: it runs to four instants of its +# timeline without failing (the bytes decoded, the two forms, the working frame, the map). +frames 2 +console set playing false +console set t 8 +screenshot .zig-cache/canim/intro_code-decode.png +console set t 20 +screenshot .zig-cache/canim/intro_code-columns.png +console set t 30 +screenshot .zig-cache/canim/intro_code-frame.png +console set t 999 +screenshot .zig-cache/canim/intro_code-end.png diff --git a/anim/test/intro_memory.script b/anim/test/intro_memory.script new file mode 100644 index 0000000..a36d36a --- /dev/null +++ b/anim/test/intro_memory.script @@ -0,0 +1,13 @@ +# The introduction's first chapter, headless: it runs to four instants of its +# timeline without failing (the bytes regrouping, the address space enlarged, +# the dump tied to its place, the close). +frames 2 +console set playing false +console set t 14 +screenshot .zig-cache/canim/intro_memory-words.png +console set t 40 +screenshot .zig-cache/canim/intro_memory-segments.png +console set t 50 +screenshot .zig-cache/canim/intro_memory-place.png +console set t 999 +screenshot .zig-cache/canim/intro_memory-end.png diff --git a/anim/test/intro_stack.script b/anim/test/intro_stack.script new file mode 100644 index 0000000..7bb93ca --- /dev/null +++ b/anim/test/intro_stack.script @@ -0,0 +1,10 @@ +# The introduction's second chapter, headless: it runs to three instants of +# its timeline without failing (the words becoming the stack, the push, the close). +frames 2 +console set playing false +console set t 2 +screenshot .zig-cache/canim/intro_stack-become.png +console set t 6 +screenshot .zig-cache/canim/intro_stack-push.png +console set t 999 +screenshot .zig-cache/canim/intro_stack-end.png diff --git a/anim/test/recordings.zig b/anim/test/recordings.zig index 5f9ceb3..31cefdb 100644 --- a/anim/test/recordings.zig +++ b/anim/test/recordings.zig @@ -341,3 +341,28 @@ test "the source follows the pc into musl's own files and back to main's line" { for (files) |seen| try expect(seen); try expect(back); } + +test "the pair's runs: plain faults at its ret on the letters; ASan stops at the first byte past buf, its shadow f3" { + const plain = canim.open(recordings.overflow); + const asan = canim.open(recordings.overflow_asan); + const report = canim.open(recordings.overflow_report); + var buf: [256]u8 = undefined; + // Plain: the run ends at a `ret` whose return address is all letters (the signal's stop, rip still on it). + var last = plain.end() - 1; + while (last > 0) : (last -= 1) { + const here = plain.instruction(last, plain.register(last, "rip"), &buf) orelse continue; + if (std.mem.eql(u8, here.text, "ret")) break; + } + try expectEqual(@as(?u64, 0x4141414141414141), try canim.Recording.word(plain.moment(last), plain.register(last, "rsp"), 8)); + // ASan: its last moment is the report's first instruction, rdi the byte past buf: f3; buf's last byte addressable. + const at = asan.end() - 1; + const past = asan.register(at, "rdi"); + try expectEqual(@as(?u8, 0xf3), (try canim.ztrace.telescope.shadow(asan.moment(at), past)).?.value); + try expectEqual(@as(?u8, 0), (try canim.ztrace.telescope.shadow(asan.moment(at), past - 1)).?.value); + // Its report, as written to fd 2, names it; the run exits 1. + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const said = canim.pair.Report.stderr(report, arena.allocator()); + try expect(std.mem.indexOf(u8, said, "stack-buffer-overflow") != null); + try expectEqual(@as(?u64, 1), canim.pair.Report.status(report)); +} diff --git a/anim/tools/bench.zig b/anim/tools/bench.zig index ad6fe4b..020a259 100644 --- a/anim/tools/bench.zig +++ b/anim/tools/bench.zig @@ -32,9 +32,75 @@ fn steps(rec: *canim.Recording, by: canim.Recording.Stop, function: ?[]const u8) } } +/// `bench relations`: the relations' passes on tables of a working frame's +/// size and of a map's (design/README.md, "4. Ties", "Cost": some 4,000 +/// places and 6,000 values), against the table they replace (a list +/// searched from the start for each lookup, so a join is places times values). +fn relationsCost(gpa: std.mem.Allocator) !void { + const rel = canim.relations; + std.debug.print("{s:<8} {s:>6} {s:>6} {s:>6} | {s:>10} {s:>10} {s:>10} | {s:>12}\n", .{ "tables", "places", "values", "pairs", "sort ns", "join ns", "passes ns", "old scan ns" }); + for ([_][2]usize{ .{ 300, 120 }, .{ 4000, 6000 } }, [_][]const u8{ "working", "map" }) |size, label| { + var rng: std.Random.DefaultPrng = .init(7); + const r = rng.random(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const rounds = 200; + var took: [4]u64 = @splat(0); + var pairs_n: usize = 0; + for (0..rounds) |_| { + _ = arena.reset(.retain_capacity); + const a = arena.allocator(); + var t: rel.Tables = .{}; + // Places: rows of code (kind 14) and words of the stack (kind 3), and some of every other kind. + for (0..size[0]) |i| { + const kind: u8 = if (i % 3 == 0) 14 else if (i % 3 == 1) 3 else @intCast(1 + r.uintLessThan(u8, 16)); + const addr: u64 = if (kind == 14) 0x401000 + 4 * @as(u64, i) else 0x7fffffffe000 + 8 * @as(u64, i); + t.add(a, .{ .key = rel.keyOf(kind, addr), .box = .{ 0, @floatFromInt(i), 880, @floatFromInt(i + 1) }, .pane = .disasm }); + } + // Values: a third of them code addresses on screen, the rest anything. + for (0..size[1]) |i| { + const v: u64 = if (i % 3 == 0) 0x401000 + 4 * r.uintLessThan(u64, size[0]) else r.int(u64); + t.show(a, .{ .value = v, .box = .{ 0, 0, 0, 0 }, .pane = .stack, .at = 0x7fffffffe000 + 8 * @as(u64, i) }); + } + var clock = rel.clock(); + const by_key = t.byKey(a); + const by_value = t.byValue(a); + took[0] += rel.clock() - clock; + clock = rel.clock(); + var pairs: std.ArrayList(rel.Pair) = .empty; + rel.join(t.values.items(.value), by_value, t.places.items(.key), by_key, 14, ~@as(u64, 0), &pairs, a); + took[1] += rel.clock() - clock; + pairs_n = pairs.items.len; + // The passes over a candidate a pair (the knob on), then cut to the budget. + clock = rel.clock(); + const cands = try a.alloc(rel.Candidate, pairs.items.len); + for (cands, pairs.items) |*c, p| c.* = .{ .kind = .code, .rank = p.value }; + var kept = rel.filter(cands, rel.Knobs.initMany(&.{ .code, .always })); + rel.byPriority(kept); + kept = rel.cut(kept); + took[2] += rel.clock() - clock; + std.mem.doNotOptimizeAway(kept.len); + // The old way: each value's lookup a scan of the places from the start. + clock = rel.clock(); + const keys = t.places.items(.key); + var found: usize = 0; + for (t.values.items(.value)) |v| { + for (keys) |key| if (key == rel.keyOf(14, v)) { + found += 1; + break; + }; + } + std.mem.doNotOptimizeAway(found); + took[3] += rel.clock() - clock; + } + std.debug.print("{s:<8} {d:>6} {d:>6} {d:>6} | {d:>10} {d:>10} {d:>10} | {d:>12}\n", .{ label, size[0], size[1], pairs_n, took[0] / rounds, took[1] / rounds, took[2] / rounds, took[3] / rounds }); + } +} + pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len == 2 and std.mem.eql(u8, args[1], "relations")) return relationsCost(gpa); if (args.len >= 3) { inline for (@typeInfo(recordings).@"struct".decl_names) |name| { if (@TypeOf(@field(recordings, name)) == recordings.Program and std.mem.eql(u8, name, args[1])) diff --git a/anim/tools/chart.py b/anim/tools/chart.py index 0f2894f..aa20e43 100644 --- a/anim/tools/chart.py +++ b/anim/tools/chart.py @@ -77,6 +77,22 @@ motion.REGIONS.update({ "sqlite": {**strips(subject(17), True), **words}, "zoom": {**strips(none(9), False), **words}, "gallery": {**strips(beside(13), True), **words}, + # The pair (src/pair.zig, `split`): the source shared across both columns, then each run's disassembly, + # registers and frame as bytes on its side of the seam; no strips. ASan's stderr comes in over its + # registers and its disassembly's lower rows once it has stopped. + "asan": {"source": (64, 48, 1792, ph(5)), + "plain disasm": (64, 212, 880, ph(9)), "asan disasm": (976, 212, 880, ph(5)), + "plain registers": (64, 472, 880, ph(4)), "asan stderr": (976, 376, 880, ph(6)), + "plain frame": (64, 612, 880, ph(10)), "asan frame": (976, 612, 880, ph(10)), **words}, + # The introduction (motion.md, "A scene: the introduction"), chapter I: the address space in the + # program column, the dump in the state column (the texts beside the address space there while + # the dump is on the shelf); the camera at x2 on the dump for its first three beats. + "intro_memory": {"space": (64, 48, 880, 840), "dump": (976, 48, 880, 840), **words}, + # Chapter II: the texts on the left (the program column, empty), the registers built over the stack. + "intro_stack": {"text": (64, 48, 880, 840), "registers": (976, 48, 880, 236), "stack": (976, 296, 880, 592), **words}, + # Chapter III: the aligned panel across both columns under its text above, then the working frame + # (the nodes lens as the list scene's), then the map. + "intro_code": {"text": (64, 48, 1792, 120), "aligned": (64, 168, 1792, 720), **words}, }) # `cut`: the gallery is the catalogue's pages, cut from one to the next (scenes/gallery.zig: 3, 6, 9.6, 13, 16, # 19.8, 21 and 24 s), not a scene: a page's first frame changes everything at once by design. diff --git a/anim/tools/overflow.c b/anim/tools/overflow.c new file mode 100644 index 0000000..bbd9a73 --- /dev/null +++ b/anim/tools/overflow.c @@ -0,0 +1,10 @@ +// A loop writes 32 bytes into a 16-byte stack buffer. +__attribute__((noinline)) static void fill(void) { + char buf[16]; + for (int i = 0; i < 32; i++) buf[i] = 'A'; +} + +int main(void) { + fill(); + return 0; +} |
