diff options
35 files changed, 1583 insertions, 453 deletions
diff --git a/anim/README.md b/anim/README.md index 74596bb..57beeb5 100644 --- a/anim/README.md +++ b/anim/README.md @@ -63,9 +63,10 @@ a later one (`Recording.Stop`: `.moment`, `.line`, `.over`, `.call`, `.syscall`). For each step it writes a timetable, a `Plan`: the cascade. The line fires (12 f); each level the step touched strikes 18 f after the one before, in the order CPU, memory, idea (a level the scene does not show, or -the step did not touch, gives up its slot; a drawing made of bytes strikes -when the projection from them arrives, 24 f after them, and its write 12 f -later still); the writes of one step strike 6 f apart; a hold to read; the +the step did not touch, or touched nothing drawn, gives up its slot; a +drawing made of bytes strikes when the projection from them arrives, 24 f +after them, and its write 12 f later still; a call's node when the +projection from its return address does, 36 f after); the writes of one step strike 6 f apart; a hold to read; the mark advances last; a rest. `walk` plays steps in full, `hurry` ramps the pace down and up again (each step 0.6 of the one before) to a run (0.30 s a step) or a sprint, `step` takes an explicit `Plan` (`Array.swap`, @@ -79,19 +80,19 @@ every state the code has in the `gallery` scene. | Layer | Block | Where | Notes | | --- | --- | --- | --- | | 0 tokens | grid, colour, type, the splits | `src/theme.zig` | per "Token changes"; JetBrains Mono NL (`.code*` faces) for all mono, Medium under 30 | -| 1 atom | `address` (`lead`, `name`, `rwx`), `value`, `arrow` (`points`, `holds`, `more`), `mark`s, `plaque` (`chip`), `pin` (`row`, `under`), `bracket` (`quiet`, `tie`, `thread`), `tag` | `src/ui.zig` (`Ui.address`, `.value`, `.arrow`, `.written`, `.read`, `.cellWritten`, `.cellRead`, `.current`, `.trail`, `.unknown`, `.chip`, `.pinRow`, `.pinUnder`, `.bracket`, `.panel`) | marks in the context: `armed`, `struck`, `held` (a tick), `read`; in a lens's cell the same with a bar | +| 1 atom | `address` (`lead`, `name`, `rwx`), `value` (and `Ui.typed`: `fd`, `bool`, `char`), `arrow` (`points`, `holds`, `more`), `mark`s, `plaque` (`chip`), `pin` (`row`, `under`), `bracket` (`quiet`, `tie`, `thread`), `tag` | `src/ui.zig` (`Ui.address`, `.value`, `.arrow`, `.written`, `.read`, `.cellWritten`, `.cellRead`, `.current`, `.trail`, `.unknown`, `.chip`, `.pinRow`, `.pinUnder`, `.bracket`, `.panel`) | marks in the context: `armed`, `struck`, `held` (a tick), `read`; in a lens's cell the same with a bar | | | `byte` | `src/rows.zig` `bytes` | `number`, `pointer`, `allocator`, `unread`; `pad` | | 2 row | `chain`, `reg` (and `rip` with the flags), `slot`, `line`, `bytes`, `call` (`span`, `callRow`) | `src/rows.zig` | `chain` follows `zt.telescope.chase`; cut at its far end, `more` | -| | `insn` | `src/disasm.zig` | columns at 2, 31, 40, 134, 180, 264, 564; `current`, `ran`, `ahead`, `outside`; the annotation from the moment's `touch` and `branch` | -| 3 panel | `registers`, `stack`, `backtrace` | `src/context.zig` | the stack's `call` spans and the backtrace from `zt.telescope.frames` | +| | `insn` | `src/disasm.zig` | columns at 2, 31, 40, 134, 180, 264, 564; operands whole, the annotation from 564 or a character after them; then a size word goes, then the operands give way, never inside `[]`; `current`, `ran` (every instruction of the last three steps), `ahead`, `outside`; the jump lane from the jump just before the pc's moment | +| 3 panel | `registers`, `stack`, `backtrace` | `src/context.zig` | the stack's window on `[rsp, rbp+16)` keeping the touched word in view, rsp and rbp's pins travelling; `call` spans and the backtrace (`#n`, name, arguments at 384, file and line) from `zt.telescope.frames` | | | `source` | `src/source.zig` | the whole file in a window, its middle third | -| | `disasm` | `src/disasm.zig` | 17 rows (11 as subject), fewer above near a function's start | -| | `hexdump` | `src/hexdump.zig` | a lens's right half: `bytes` rows and their reading | -| | lenses: `nodes`, `array`, `calls`, `syscalls` | `src/nodes.zig`, `src/array.zig`, `src/calls.zig` (`Tree`), `src/syscalls.zig` (`Crossing`) | in the band; `nodes` and `array` with their dump | -| 4 tie | `thread`, `link` (and its `pin`), `projection`, `echo` | `src/ties.zig` | panels publish places (`anchor`); `Ties`, added last, draws in the channels | -| 5 frame | `stage` and `relayout` | `src/stage.zig` | splits `none`, `beside`, `subject` (`theme.layout.split`) | -| | `clock`, `caption`, `veil`, `card` | `src/words.zig`, `src/root.zig` (`Narrator`, `Camera`) | the title card is `scenes/title.zig` | -| 6 verb | `fire`, `arm`, `strike`, `cool`, `read`, `extend`, `link`, `project`, `advance`, `cascade`, `run`, `sprint`, `establish`, `scroll`, `relayout`, `visit`, `say` | `src/cursor.zig` (the timetable), the blocks (each draws its state at the instant) | tokens in `theme.time` | +| | `disasm` | `src/disasm.zig` | 17 rows (9 as subject), fewer above near a function's start | +| | `hexdump` | `src/hexdump.zig` | a lens's view (`hexdump.panel`): `bytes` rows and their reading, veiled at a sprint | +| | lenses: `nodes`, `array`, `calls`, `syscalls` | `src/nodes.zig`, `src/array.zig`, `src/calls.zig` (`Tree`), `src/syscalls.zig` (`Crossing`) | the drawing in `band` (over the program column), its view in `view` (over the state column): `nodes` and `array` a dump (`hexdump.panel`), `calls` the backtrace with arguments, `syscalls` the bytes the call is given or fills | +| 4 tie | `thread`, `link` (and its `pin`), `projection`, `echo` | `src/ties.zig` | panels publish places (`anchor`); `Ties`, added last, draws in the channels: a link climbs to a node by the gutter's left lane and goes down to a slot by the right, its name riding its head, a target past the stack's window a stub and a row count; a projection from the view's bytes, or from a frame's return address to its call's node | +| 5 frame | `stage` and `relayout` | `src/stage.zig` | splits `none`, `beside`, `subject` (`theme.layout.split`): the band is `band` (the drawing) and `view`; `relayout` fades the drawing round its move; `holdStack` holds the stack's window for the camera, with `free` slots | +| | `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`, `run`, `sprint`, `establish` (`Context.establish`: a drawing's elements fade in rising, no lines), `scroll`, `relayout`, `visit`, `say` | `src/cursor.zig` (the timetable), 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`) | `Recording` (`src/Recording.zig`) is the index every block reads: lines, calls, syscalls, allocations, which registers and bytes each moment changed @@ -104,58 +105,81 @@ and read (a debugger's `touch` reads count), each moment's `touch` and debugger: registers, the stack, what they point at, the instructions round the pc with their lines and callees' parameter counts, at every stop), each by a bare name in a directory of its own with an empty environment, without -address randomisation. The instrumented ones are built `-no-pie`, so their -code and heap have short addresses as the design's columns expect. +address randomisation, with the tools built `ReleaseFast` (a step through +the agent's or the runtime's code is a moment, and a slow tracer stretches +the clock's retry loops it steps through). The instrumented ones are built +`-no-pie -fno-stack-protector -Wl,-z,now`: short addresses, no resolver +and no canary stepped through that the source does not say. -| Name | Program | Stops | Also | -| --- | --- | --- | --- | -| `steps` | `fib.c`, static musl, `-O0` | every instruction | | -| `hello` | `hello.c`, static musl | every line | reads `tools/note` | -| `sort` | `sort.c` built by `ztrace cc` (`calls,vars,stores,loads`) | every line | `--ring` | -| `list` | `list.c` built by `ztrace cc` (`calls,vars,stores,loads`) | every line | `--alloc --preload` the agent: allocator headers are read | -| `gallery` | a copy of `list`, kept in `test/gallery/list.ztrace` | | the gallery's pictures depend on the drawing only | +| Name | Program | Stops | Moments, bytes | Also | +| --- | --- | --- | --- | --- | +| `steps` | `fib.c`, static musl, `-O0` | every instruction | 1999, 336 KB | | +| `hello` | `hello.c`, static musl | every line | 233, 101 KB | reads `tools/note` | +| `sort` | `sort.c`, `ztrace cc --instr vars --only sort,a` | every instruction, `--from main` | 5076, 617 KB | `--ring`: the variables' names and types; each `__zt_var` call is stepped (4 of them) | +| `list` | `list.c`, `ztrace cc --instr vars --only push,reverse,head` | every instruction, `--from reverse` | 3421, 528 KB | `--alloc --preload` the agent: allocator headers are read; the pushes (the agent's and the runtime's first calls) run through | +| `gallery` | the old `list` by line, kept in `test/gallery/list.ztrace` | | 134, 88 KB | the gallery's pictures depend on the drawing only | + +A recording that begins inside a call (`--from`) has that call open from +its first stop (`Recording.index`, from the frame chain). Writes are the +bytes whose value changed, to the element the instruction stored (its +`touch`); a store of the same value is kept apart (`store_spans`) and +counts as assigning a local. A register's change over a step is net: a +call's rsp put back is not struck. The vDSO's `clock_gettime` is stepped +through under the runtime and the agent: its retry loop makes the counts +vary a little from one recording to the next. An address no symbol +holds is named from its module's first mapping (`list+2c89`). ## Motion, as measured -`tools/chart.py chart` on the 1080p exports (the designer's five checks; the -baseline is `design/motion.md`'s table, measured before the frame changed): +`tools/chart.py chart` on the 1080p exports in `out/` (the designer's five +checks; its regions follow the two-panel band now). Encoded with `-g 600`: +x264's keyframe at 10, 20, 30 s is a one-frame fade the instrument sees. | | fib | list | sort | syscalls | zoom | | --- | --- | --- | --- | --- | --- | -| POP, before / now | 68 / 0 | 40 / 0 | 35 / 0 | 0 / 0 | 1 / 0 | -| CROWD, before / now | 75 / 7 | 43 / 2 | 44 / 10 | 4 / 5 | 5 / 4 | -| METRONOME, before / now | 68 steps / none | 15 / none | 36 / none | 4 / none | none | -| RUSH, now | 0 | 0 | 2 | 1 | 0 | -| seconds | 40.6 | 59.3 | 39.5 | 34.8 | 30.2 | +| POP, round 2 / 3 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | +| CROWD, round 2 / 3 | 7 / 2 | 2 / 7 | 10 / 5 | 5 / 1 | 4 / 3 | +| RUSH, round 2 / 3 | 0 / 0 | 0 / 2 | 2 / 0 | 1 / 2 | 0 / 0 | +| AIR, round 3 | 0 | 0 | 1 | 0 | 1 | +| seconds, round 3 | 41.5 | 60.5 | 46.7 | 38.2 | 32.0 | -What still fires, and why it is left: +What fires, and why it is left: -- CROWD at each `advance` that crosses a function (source, disassembly and - rip move together: the catalogue's `advance` says they are one mark), - inside `run` and `sprint` stretches (steps that are not to be read), and - in fib at 22.25 s: a one-frame change in the disassembly and the stack on - a step's first frame, beside the fire, not yet found. -- AIR at each scene's opening: the designed stillness, 1 s and 0.5 s a panel. -- RUSH in sort and syscalls at the last caption: the last step's cool and - ticks still settle under it. +- CROWD: fib 12.05 and 27.20, list 30.62 and 32.18, sort 22.28 are the + veil coming over the registers, stack and disassembly at the first + shortened step (one veil over three panels); sort 9.60 and zoom 9.65 + and 21.55 the camera (the regions are fixed on the screen); zoom 11.75 + the stack's window scrolling to its hold under the camera (the stack + fills every region there). The rest (list 15.92, 19.32 and the others + like them, sort 31.82 and 34.12, syscalls 35.05) are an `advance`: the + thread, the plaques and rip move as one mark, the source and the + disassembly scroll with it, and a link or projection goes back into its + pin, all on the catalogue's one frame. +- RUSH: list 29.20 and 29.55, syscalls 29.17 and 29.52: a caption + arrives, and the next change the instrument sees is the keyframe at + 30.00 (a fade of every region over one frame, 0.00% at its peak). +- AIR: the last caption's reading time and the 2 s on the finished + picture (sort 42.17, 4.6 s; zoom 26.88, 3.1 s). ## What is not done -- The instrumented recordings (`list`, `sort`) clobber registers between - lines, so their registers are `quiet` (no strikes, no links) and their - pins name variables. A `--by insn` recording of `list` with only `vars` - is 1.6 M moments (the loader and libc start-up): too many. So `link`, and - `ran` rows with the jump lane, are seen in the scenes of `steps` (fib, - zoom) only; a recording by line knows no instructions between its stops. -- `establish` for a lens (its elements rising from their rows by - projection) is not drawn: lenses fade in with the panels. -- The `thread`'s brackets on the disassembly change runs at the middle of - the advance; only the source's slides. -- `value` classes `fd`, `flags` (other than rip's), `bool`, `char` are not drawn. -- Back pointers between nodes run under the nodes and can cross a pin's stub. -- `heap` and `pages` lenses are not in the band (`Timeline` is the old far view). -- The camera rests at x2 in `zoom` (the stack of the `none` split fills it); - x1.5 is supported (`theme.camera.scales`) but no scene uses it. -- `zig build test` prints "failed command" for each scripted scene: that is - the run echoing its stderr (the Vulkan headless warning), not a failure; - the summary line is the verdict. +- Back pointers between nodes still run under the nodes: a page keyline + round each pin's stub and head shows them passing behind it (there is + no lane for them in `beside`). +- Names keep their side when one of two leaves a pin and when a pin's + name travels; a name that arrives where another already is takes the + right, and once it has landed the pin's own order (variables, then + registers) may put it on the other side. +- The hexdump's reading of a `char` or `bool` field (the lens's values + and cells read them by type; the dump's reading column does not). +- A link to a slot past the stack's window ends in its stub and row count + (`12 rows`); no scene's link has such a target, so it is drawn in no + export. +- The calls tree's leaf spacing holds for fib(5); past about ten leaves + nodes and badges collide (the catalogue's known case). +- `heap` and `pages` lenses are not in the band (`Timeline` is the old + far view). +- SQLite (the next rung) is not started. +- `zig build test` prints "failed command" for each scripted scene: that + is the run echoing its stderr (the Vulkan headless warning), not a + failure; the summary line is the verdict. diff --git a/anim/build.zig b/anim/build.zig index 2f50e4a..5646f1a 100644 --- a/anim/build.zig +++ b/anim/build.zig @@ -25,7 +25,11 @@ pub fn build(b: *std.Build) void { const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize }); const zt = b.dependency("ztrace", .{ .target = target, .optimize = optimize }); const pardes = b.dependency("pardes", .{ .target = target, .optimize = optimize, .@"tree-sitter" = .minimal }); - const ztrace = zt.artifact("ztrace"); + // The tools a recording is made with, always optimized: a step through + // the agent's or the runtime's code is a moment of the recording, and + // a slow tracer stretches the clock's retry loops it steps through. + const tools = b.dependency("ztrace", .{ .target = target, .optimize = .ReleaseFast }); + const ztrace = tools.artifact("ztrace"); const imports: []const std.Build.Module.Import = &.{ .{ .name = "anim", .module = sb.modules.anim }, @@ -44,8 +48,8 @@ pub fn build(b: *std.Build) void { var table: std.ArrayList(u8) = .empty; // The pass and the agent to preload, as ztrace's own build makes and names them. - const plugin = zt.namedLazyPath("ztrace-pass"); - const agent = zt.namedLazyPath("ztrace-agent"); + const plugin = tools.namedLazyPath("ztrace-pass"); + const agent = tools.namedLazyPath("ztrace-agent"); const musl = b.resolveTargetQuery(.{ .cpu_arch = .x86_64, .os_tag = .linux, .abi = .musl }); const Recording = struct { @@ -56,10 +60,15 @@ pub fn build(b: *std.Build) void { /// they point at, and the instructions at the pc. by: []const u8, /// Compiled by `ztrace cc` to tell these of itself as well (its - /// calls, its variables with their types, every store and load); - /// null for the program as the compiler alone makes it (static, - /// unoptimised), whose instructions are then all its own. + /// variables with their types), for the functions and globals + /// `only` names: everything else is the compiler's alone. Null for + /// the program as the compiler alone makes it (static, unoptimised), + /// whose instructions are then all its own. instr: ?[]const u8 = null, + only: []const u8 = "*", + /// Run through to here before the first stop: the loader, the C + /// library's start, and what the scene does not show. + from: ?[]const u8 = null, /// With the agent preloaded: `malloc` and `free` too. alloc: bool = false, /// A file of tools/ it reads, by its bare name. @@ -68,20 +77,27 @@ pub fn build(b: *std.Build) void { for ([_]Recording{ .{ .name = "steps", .source = "fib.c", .by = "insn" }, .{ .name = "hello", .source = "hello.c", .by = "line", .reads = "note" }, - .{ .name = "sort", .source = "sort.c", .by = "line", .instr = "calls,vars,stores,loads" }, - .{ .name = "list", .source = "list.c", .by = "line", .instr = "calls,vars,stores,loads", .alloc = true }, + // By instruction, as `steps` is: the registers are the program's + // own, so they strike and link. Only the variables the scenes name + // are told by the instrumentation (each a call into its runtime, + // stepped like any other); `list` starts at `reverse`, its pushes + // (the agent's and the runtime's first calls) run through. + .{ .name = "sort", .source = "sort.c", .by = "insn", .instr = "vars", .only = "sort,a", .from = "main" }, + .{ .name = "list", .source = "list.c", .by = "insn", .instr = "vars", .only = "push,reverse,head", .from = "reverse", .alloc = true }, }) |r| { const source = b.path(b.fmt("tools/{s}", .{r.source})); var program: std.Build.LazyPath = undefined; if (r.instr) |instr| { const cc = b.addRunArtifact(ztrace); - cc.addArgs(&.{ "cc", "--instr", instr, "--plugin" }); + cc.addArgs(&.{ "cc", "--instr", instr, "--only", r.only, "--plugin" }); cc.addFileArg(plugin); cc.addArg("--rt"); - cc.addArtifactArg(zt.artifact("ztrace-rt")); + cc.addArtifactArg(tools.artifact("ztrace-rt")); // Not position-independent: code and heap at short addresses, as // the design's columns are drawn for (seven digits, not twelve). - cc.addArgs(&.{ "--", "clang", "-O0", "-g", "-no-pie" }); + // Bound at load and with no canary: no resolver and no check is + // stepped through that the source does not say. + cc.addArgs(&.{ "--", "clang", "-O0", "-g", "-no-pie", "-fno-stack-protector", "-Wl,-z,now" }); cc.addFileArg(source); cc.addArg("-o"); program = cc.addOutputFileArg(r.name); @@ -99,6 +115,7 @@ pub fn build(b: *std.Build) void { const run = b.addSystemCommand(&.{ "env", "-i", "setarch", "-R" }); run.addArtifactArg(ztrace); run.addArgs(&.{ "record", "--by", r.by, "--stack", "256", "-s", "64" }); + if (r.from) |place| run.addArgs(&.{ "--from", place }); // What an instrumented program tells of itself comes through a ring. if (r.instr != null) run.addArg("--ring"); if (r.alloc) { @@ -205,7 +222,7 @@ pub fn build(b: *std.Build) void { \\mkdir -p out \\"$0" --state "$1" --export - --size "$2" --fps 60 | \\ ffmpeg -loglevel error -y -f rawvideo -pix_fmt rgba -s "$2" -r 60 -i - \ - \\ -c:v libx264 -crf 14 -preset slow -pix_fmt yuv420p \ + \\ -c:v libx264 -crf 14 -preset slow -g 600 -pix_fmt yuv420p \ \\ -colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv "$3" }); video.addArtifactArg(exe); diff --git a/anim/scenes/fib.zig b/anim/scenes/fib.zig index 27d959f..214f768 100644 --- a/anim/scenes/fib.zig +++ b/anim/scenes/fib.zig @@ -44,6 +44,7 @@ fn frame(s: *anim.Frame) void { // Pacing: the same three lines three times more. Seen once, so // hurried: down the first branch at a run, to the call that does not call. + says.line(s, "Down the first branch: each call the same three lines,\none frame deeper, `n` one less."); at.hurry(s, .line, rec.lineMoment(5, call(rec, 4).enter), .{}); says.line(s, "`fib(1)` needs no other call. Its answer leaves in `rax`,\nand its frame goes."); @@ -54,6 +55,7 @@ fn frame(s: *anim.Frame) void { // The pattern is known: the rest of the tree at a sprint, the tree its // subject, slowing into the last answers. at.hurry(s, .line, call(rec, 10).exit.?, .{ .pace = canim.theme.time.sprint }); + says.line(s, "The last answers come back up, each added to the one\nbefore it: `fib(5)` is 5, in `rax`, back in `main`."); at.walk(s, .line, call(rec, 0).exit.?); - s.wait(canim.theme.time.before_cut); + says.close(s); } diff --git a/anim/scenes/gallery.zig b/anim/scenes/gallery.zig index 12a592f..3b66a24 100644 --- a/anim/scenes/gallery.zig +++ b/anim/scenes/gallery.zig @@ -74,13 +74,17 @@ fn atoms(u: ui.Ui, p: *const Pages) void { // value y = 196; title(u, 64, y, "value"); - note(u, 200, y, "digit, small number, large number, small negative, string, unknown"); + note(u, 200, y, "digit, small number, large number, small negative, string, unknown; by a signature or a type: fd, bool, char"); y += 12; x = 64; for ([_]u64{ 4, 0x21, 0x8dea2ff80214, std.math.maxInt(u64) }) |v| x = u.value(x, rows.baseline(y), v, false, .{}) + 60; u.text(.mono, theme.size.mono.context, x, rows.baseline(y), "\"./list\"", theme.color.string); x += 140; u.unknown(.{ .x = x, .y = y, .w = 24, .h = row }); + x += 84; + x = u.typed(x, rows.baseline(y), 3, .{ .fd = "\"note\"" }, .{}) + 60; + x = u.typed(x, rows.baseline(y), 1, .boolean, .{}) + 60; + _ = u.typed(x, rows.baseline(y), 'A', .character, .{}); // arrow y = 270; @@ -242,8 +246,8 @@ fn rowsPage(u: ui.Ui, p: *const Pages) void { note(u, 140, y, "row, in a backtrace"); y += 12; panel = u.moved(64, y); - rows.callRow(panel, 0, 880, 0, "reverse+225", "list.c:22", true); - rows.callRow(panel, row, 880, 1, "main+42", "", false); + rows.callRow(panel, 0, 880, 0, "reverse+225", "", "list.c:22", true); + rows.callRow(panel, row, 880, 1, "main+42", "", "list.c:40", false); y = 600; title(u, 64, y, "line"); diff --git a/anim/scenes/list.zig b/anim/scenes/list.zig index 53df4d5..d6f1a76 100644 --- a/anim/scenes/list.zig +++ b/anim/scenes/list.zig @@ -15,8 +15,8 @@ const recordings = @import("recordings"); pub const background = canim.background; pub const scene = anim.Live(frame, struct {}); -/// Each a pigment, the same on its tag in the list and in the table. -const tracked = [_][]const u8{ "prev", "cur", "next" }; +/// The variables whose tags the nodes carry: the three the loop moves, and `head`. +const tracked = [_][]const u8{ "prev", "cur", "next", "head" }; fn frame(s: *anim.Frame) void { const rec = canim.open(recordings.list); @@ -25,26 +25,34 @@ fn frame(s: *anim.Frame) void { // From reverse's first line (the list of three is built) to its last. var at = canim.cursor(s, rec, rec.lineMoment(18, reverse.enter)); // The nodes are the idea; a tag slides and an arrow grows after its strike. - at.levels = .{ .cpu = false, .idea = .data, .follow = t.move, .source_rows = 5 }; + at.levels = .{ .idea = .data, .follow = t.move, .source_rows = 10 }; const end = rec.lineMoment(27, reverse.enter); at.journey(.line, end); // The idea is the subject: the lens a size up, the nodes over the bytes they are. const split = canim.layout.split.subject; - const ctx = canim.context(s, at, .{ .split = split, .quiet = true }); - const list = canim.nodes(s, .{ .cursor = at, .stage = ctx.stage, .root = "head", .track = &tracked, .quiet = true }); + const ctx = canim.context(s, at, .{ .split = split }); + const list = canim.nodes(s, .{ .cursor = at, .stage = ctx.stage, .root = "head", .track = &tracked }); var says: canim.Narrator = .{}; const joins = ctx.ties(s); - canim.establish(s, .{ ctx.clock, ctx.registers, ctx.stack, ctx.source, ctx.disasm, list, joins }); + // The nodes come in beside their bytes, one by one: three of them. + ctx.establish(s, .{ ctx.clock, ctx.registers, ctx.stack, ctx.source, ctx.disasm, list, joins }, 3); says.line(s, "A list is nodes on the heap, each holding the address of the next.\nReversing it moves no node: it rewrites every `next`."); - // Three names are set up, then the first trip round the loop, in full. - at.walk(s, .line, rec.lineMoment(20, rec.lineMoment(24, reverse.enter))); + // Three names are set up. + const first_trip = rec.lineMoment(21, reverse.enter); + at.walk(s, .line, first_trip); + // The loop's caption leads the loop. says.line(s, "`next` remembers the way on, `cur->next` is turned round,\nand `prev` and `cur` each step along."); + const second_trip = rec.lineMoment(21, rec.lineMoment(24, first_trip)); + at.walk(s, .line, second_trip); // Pacing: the second trip is the same, so hurried; it keeps its rest. - at.hurry(s, .line, rec.lineMoment(20, rec.lineMoment(24, at.moment(s))), .{}); + 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)); + at.hurry(s, .line, third_trip, .{}); // The third in full again: the last `next` turns, and `cur` runs off the end. - at.walk(s, .line, rec.lineMoment(26, at.moment(s))); + says.line(s, "The last node: its `next` turns too,\nand `cur` runs off the end of the list."); + at.walk(s, .line, rec.lineMoment(26, third_trip)); 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); - s.wait(t.before_cut); + says.close(s); } diff --git a/anim/scenes/sort.zig b/anim/scenes/sort.zig index 6ad41f9..06b35a9 100644 --- a/anim/scenes/sort.zig +++ b/anim/scenes/sort.zig @@ -22,14 +22,14 @@ fn frame(s: *anim.Frame) void { while (rec.next(.over, rec.next(.over, start)) < rec.call("swap", 0).enter) start = rec.next(.over, start); var at = canim.cursor(s, rec, start); // The array is the idea; `i` and `j` are memory, and strike a beat before their tags slide. - at.levels = .{ .cpu = false, .idea = .data, .follow = t.quick, .source_rows = 10 }; + at.levels = .{ .idea = .data, .follow = t.quick, .source_rows = 10 }; // Its last compare: nothing larger is left of 20. const last = rec.call("swap", 9); const end = rec.next(.over, rec.next(.over, last.exit.?)); at.journey(.over, end); // The context is the instrumented program's: its registers are unmarked. const split = canim.layout.split.subject; - const ctx = canim.context(s, at, .{ .split = split, .quiet = true }); + const ctx = canim.context(s, at, .{ .split = split }); // The lens: the array as cells, and the two indices that walk it. const cells = canim.array(s, .{ .cursor = at, .stage = ctx.stage, .variable = "a", .indices = &.{ "i", "j" }, .focus = true }); var says: canim.Narrator = .{}; @@ -41,23 +41,40 @@ fn frame(s: *anim.Frame) void { }.step; const joins = ctx.ties(s); - canim.establish(s, .{ ctx.clock, ctx.registers, ctx.stack, ctx.source, ctx.disasm, cells, joins }); + // The cells come in beside their bytes, one by one. + ctx.establish(s, .{ ctx.clock, ctx.registers, ctx.stack, ctx.source, ctx.disasm, cells, joins }, 8); says.line(s, "`i` walks right. Everything left of it is in order,\nand 12 is not yet in its place."); // The compare: both cells framed. It is the swap's anticipation. at.walk(s, .over, rec.next(.over, start)); says.line(s, "While the one on the left is larger, they trade places,\nand `j` follows the smaller value down."); - // The caption of the step the scene is about stands a second longer. - s.wait(t.caption_lead); + // Nearer, for the swap: the cells at x1.5, the rest of the stage cleared. + var cam: canim.Camera = .{}; + const others = .{ ctx.source, ctx.disasm, ctx.registers, ctx.stack }; + // The drawing's view is cleared with the rest (it is not the subject). + const going = s.cursor; + s.cursor = going + t.quick; + s.play(.{ctx.stage.view.to(0)}, .{ .seconds = t.camera_clear, .ease = anim.ease.linear }); + s.cursor = going; + cam.go(s, split.band, 1.5, others); // Arcs: the two values fly past each other, one over, one under. swap(at, s, rec); at.walk(s, .over, rec.next(.over, at.moment(s))); + const coming = s.cursor; + cam.back(s, others); + const back_at = s.cursor; + s.cursor = coming + t.camera; + s.play(.{ctx.stage.view.to(1)}, .{ .seconds = t.cascade, .ease = anim.ease.linear }); + s.cursor = @max(s.cursor, back_at); // Pacing: the same again, so at a run; then the long way 5 has to go, // at a sprint; slowing for the last swap. + says.line(s, "And so on: each value is carried left\nuntil the one before it is not larger."); at.hurry(s, .over, rec.call("swap", 3).enter - 1, .{ .to = t.run, .settle = false }); at.hurry(s, .over, last.enter - 1, .{ .pace = t.sprint, .from = t.run }); + says.line(s, "The last swap: 20 goes one place left, past 26."); swap(at, s, rec); at.walk(s, .over, end); says.line(s, "Nothing larger is left of 20. The array is sorted."); - s.wait(t.before_cut - t.caption_lead); + says.close(s); + cam.apply(s); } diff --git a/anim/scenes/syscalls.zig b/anim/scenes/syscalls.zig index c981e58..6e2f0b9 100644 --- a/anim/scenes/syscalls.zig +++ b/anim/scenes/syscalls.zig @@ -24,8 +24,9 @@ const lines = [_][]const u8{ fn frame(s: *anim.Frame) void { const rec = canim.open(recordings.hello); - // From main's first call to its last line. - var at = canim.cursor(s, rec, rec.lineMoment(6, rec.call("main", 0).enter)); + // From main's first line to its last: its first lines walked under the + // first caption, then a call a phrase. + var at = canim.cursor(s, rec, rec.call("main", 0).enter); at.journey(.line, rec.lineMoment(10, at.first)); const split = canim.layout.split.subject; at.levels = .{ .source_rows = 10 }; @@ -38,6 +39,7 @@ fn frame(s: *anim.Frame) void { const joins = ctx.ties(s); canim.establish(s, .{ ctx.clock, ctx.registers, ctx.stack, ctx.source, ctx.disasm, kernel, joins }); says.line(s, "A program cannot open a file or reach the screen itself.\nIt asks the kernel, and waits."); + at.walk(s, .line, rec.lineMoment(6, at.first)); // One call a phrase: its caption while nothing moves, then the crossing. for (lines) |line| { @@ -45,5 +47,5 @@ fn frame(s: *anim.Frame) void { canim.syscalls.step(at, s, .line); s.wait(t.phrase_rest); } - s.wait(t.before_cut - t.phrase_rest); + says.close(s); } diff --git a/anim/scenes/title.zig b/anim/scenes/title.zig index 3646da4..d5af819 100644 --- a/anim/scenes/title.zig +++ b/anim/scenes/title.zig @@ -10,7 +10,7 @@ fn frame(s: *anim.Frame) void { const size = canim.theme.size.sans; const text = canim.theme.color.text; const series = canim.label(s, .{ .text = "How programs really run", .box = .{ .x = 64, .y = 138, .w = 900, .h = 48 }, .size = size.kicker, .color = text.dim }); - const title = canim.label(s, .{ .text = "Five small programs,\none step at a time", .box = .{ .x = 64, .y = 220, .w = 1792, .h = size.title_leading }, .face = .sans_bold, .size = size.title, .color = text.bright }); + const title = canim.label(s, .{ .text = "Four small programs,\none step at a time", .box = .{ .x = 64, .y = 220, .w = 1792, .h = size.title_leading }, .face = .sans_bold, .size = size.title, .color = text.bright }); const under = canim.label(s, .{ .text = "recorded as they ran: every line, register and byte", .box = .{ .x = 64, .y = 500, .w = 1792, .h = 60 }, .face = .sans, .size = size.subtitle, .color = text.dim }); const marks = canim.legend(s, .{ .box = canim.theme.cols(0, 12, 512, 256) }); const t = canim.theme.time; @@ -18,5 +18,6 @@ fn frame(s: *anim.Frame) void { s.play(.{under.fadeIn()}, .{ .seconds = t.move }); s.wait(t.beat); s.play(.{marks.fadeIn()}, .{ .seconds = t.travel }); - s.wait(4); + // Ten marks to learn: long enough to read them all. + s.wait(8); } diff --git a/anim/scenes/zoom.zig b/anim/scenes/zoom.zig index 5ea2346..ee24e7d 100644 --- a/anim/scenes/zoom.zig +++ b/anim/scenes/zoom.zig @@ -18,7 +18,6 @@ pub const scene = anim.Live(frame, struct {}); fn frame(s: *anim.Frame) void { const rec = canim.open(recordings.steps); - const t = canim.theme.time; // fib(5), about to run line 6: `return fib(n-1) + fib(n-2);`. Its first call is fib(4). const call = rec.call("fib", 1); var at = canim.cursor(s, rec, rec.lineMoment(6, rec.call("fib", 0).enter)); @@ -40,11 +39,15 @@ fn frame(s: *anim.Frame) void { says.line(s, "`call` writes eight bytes on the stack: the way back.\nThe new frame saves `rbp` under them, then its own `n`."); // Nearer, for the bytes: the stack alone, twice the size. cam.go(s, split.stack, 2, .{ ctx.source, ctx.disasm, ctx.registers, ctx.backtrace }); + // Under the camera the stack holds still: six free words above rsp for the new frame. + ctx.stage.holdStack(s, at.moment(s), 6); at.walk(s, .moment, call.enter + 4); + s.wait(canim.theme.time.beat); + ctx.stage.releaseStack(s); cam.back(s, .{ ctx.source, ctx.disasm, ctx.registers, ctx.backtrace }); - says.line(s, "Eleven instructions and three words of stack later\n`fib(4)` begins: the same lines, one call deeper."); + says.line(s, "Nine instructions and three words of stack later\n`fib(4)` begins: the same lines, one call deeper."); at.walk(s, .line, end); - s.wait(t.before_cut); + says.close(s); cam.apply(s); } diff --git a/anim/src/Recording.zig b/anim/src/Recording.zig index 92bb917..280d14a 100644 --- a/anim/src/Recording.zig +++ b/anim/src/Recording.zig @@ -75,6 +75,9 @@ pub const Branch = struct { to: u64, taken: bool, kind: enum(u8) { none, call, j /// the program stopped there. pub const CodeLine = struct { addr: u64, line: u32 }; +/// A variable on the stack, declared at a moment. +pub const Declared = struct { moment: u64, addr: u64 }; + /// Where a cursor's step may end. pub const Stop = enum { /// The next moment, whatever the recorder made one: an instruction, a line. @@ -113,9 +116,11 @@ calls: []Call = &.{}, syscalls: []Syscall = &.{}, marks: []Mark = &.{}, allocations: []Born = &.{}, -/// For each moment, a bit for each register of `Regs.names` it changed. -registers: []u32 = &.{}, +/// The registers of `tid` after each moment (the last known, before any). +registers: []zt.Regs = &.{}, write_spans: Spans = .{}, +/// What instructions stored, changed or not (a recording by instruction). +store_spans: Spans = .{}, read_spans: Spans = .{}, /// For each moment, what the instruction at its pc touches and where it branches. insn_touches: [][2]?Touch = &.{}, @@ -123,6 +128,11 @@ insn_branches: []?Branch = &.{}, /// Every instruction address the program stopped at in its own source, /// with that line, in address order. code_lines: []CodeLine = &.{}, +/// Each local variable's declaration, in the order they came: in a +/// recording that tells no calls, what says when a local began. +locals: []Declared = &.{}, +/// The variables declared outside the stack (globals): bytes a lens draws. +globals: []Span = &.{}, strings: std.AutoHashMapUnmanaged(u64, []const u8) = .empty, arena: std.heap.ArenaAllocator, @@ -237,14 +247,18 @@ fn index(r: *Recording) !void { var syscalls: std.ArrayList(Syscall) = .empty; var marks: std.ArrayList(Mark) = .empty; var allocations: std.ArrayList(Born) = .empty; - var registers: std.ArrayList(u32) = .empty; + var registers: std.ArrayList(zt.Regs) = .empty; var writes: std.ArrayList(Span) = .empty; var write_ends: std.ArrayList(u32) = .empty; + var stores: std.ArrayList(Span) = .empty; + var store_ends: std.ArrayList(u32) = .empty; var reads: std.ArrayList(Span) = .empty; var read_ends: std.ArrayList(u32) = .empty; var touch_list: std.ArrayList([2]?Touch) = .empty; + var locals: std.ArrayList(Declared) = .empty; + var globals: std.ArrayList(Span) = .empty; // What the instruction at a stop is about to read is read by the step after it. - var pending_reads: [2]?Touch = .{ null, null }; + var pending: [2]?Touch = .{ null, null }; var branch_list: std.ArrayList(?Branch) = .empty; var code_lines: std.AutoHashMapUnmanaged(u64, u32) = .empty; defer code_lines.deinit(gpa); @@ -274,6 +288,7 @@ fn index(r: *Recording) !void { var line_at: ?u64 = null; var line_file: ?u64 = null; var stepped = false; + var broke = false; var takes_nothing = false; // An instrumented program's own events are drained before the // debugger reports its stop: what follows its line is the debugger's. @@ -281,7 +296,7 @@ fn index(r: *Recording) !void { var touched: [2]?Touch = .{ null, null }; var branched: ?Branch = null; snapshots.clearRetainingCapacity(); - for (pending_reads) |p| if (p) |read_by| if (read_by.how & 1 != 0) try reads.append(arena, .{ .addr = read_by.addr, .len = read_by.len }); + for (pending) |p| if (p) |read_by| if (read_by.how & 1 != 0) try reads.append(arena, .{ .addr = read_by.addr, .len = read_by.len }); while (events.next()) |item| { const ev = item.ev; count += 1; @@ -315,14 +330,17 @@ fn index(r: *Recording) !void { try snapshots.append(gpa, !told or debugger_spoke); }, .mem_read => if (ev.a[1] > 0) try reads.append(arena, .{ .addr = ev.a[0], .len = ev.a[1] }), - .variable => if (open_calls.getLastOrNull()) |c| { + .variable => { + if ((zt.telescope.region(m, ev.a[0]) catch .none) == .stack) try locals.append(arena, .{ .moment = i, .addr = ev.a[0] }) else try globals.append(arena, .{ .addr = ev.a[0], .len = ev.a[1] }); // The first variable of a function that takes something is what it was given. - const takes = for (r.functions) |f| { - if (std.mem.eql(u8, f.name, r.name(calls.items[c].function))) break f.takes; - } else true; - if (takes and calls.items[c].parameter == null and ev.a[1] <= 8) { - calls.items[c].parameter = .{ .addr = ev.a[0], .len = ev.a[1] }; - calls.items[c].parameter_name = ev.a[2]; + if (open_calls.getLastOrNull()) |c| { + const takes = for (r.functions) |f| { + if (std.mem.eql(u8, f.name, r.name(calls.items[c].function))) break f.takes; + } else true; + if (takes and calls.items[c].parameter == null and ev.a[1] <= 8) { + calls.items[c].parameter = .{ .addr = ev.a[0], .len = ev.a[1] }; + calls.items[c].parameter_name = ev.a[2]; + } } }, .line => { @@ -331,7 +349,11 @@ fn index(r: *Recording) !void { // The pass counts its strings from 1; the debugger's ids are hashes with the top bit set. if (ev.a[0] >> 63 != 0) debugger_spoke = true; }, - .step, .breakpoint => stepped = true, + .step => stepped = true, + .breakpoint => { + stepped = true; + broke = true; + }, .touch => { const slot: usize = if (touched[0] == null) 0 else 1; if (touched[slot] == null) touched[slot] = .{ .addr = ev.a[0], .len = ev.a[1], .how = @intCast(ev.aux & 3) }; @@ -350,6 +372,7 @@ fn index(r: *Recording) !void { // stores: bytes seen for the first time were not written by this // step, unless it pushed them (the stack pointer went down a word). var kept = first_write; + var changed_by_store = false; for (writes.items[first_write..], snapshots.items) |span, snapshot| { var fresh = true; for (0..span.len) |b| { @@ -364,13 +387,27 @@ fn index(r: *Recording) !void { const pushed = regs != null and before != null and regs.?.rsp + 8 == before.?.rsp and span.addr <= regs.?.rsp and span.addr + span.len >= regs.?.rsp + 8; keep = if (pushed) .{ .addr = regs.?.rsp, .len = 8 } else null; } + // The store the instruction made says it to the element: below. + if (!told and stepped and stored(pending, span)) { + keep = null; + changed_by_store = true; + } if (keep) |span_kept| { writes.items[kept] = span_kept; kept += 1; } } writes.shrinkRetainingCapacity(kept); + // What the instruction at the stop before said it would store, it + // stored, the bytes it named: a write where the value changed (a + // debugger sees words change, the instruction says which element); + // a store all the same, even of the value that was there. + if (!told and stepped) for (pending) |p| if (p) |w| if (w.how & 2 != 0) { + try stores.append(arena, .{ .addr = w.addr, .len = w.len }); + if (changed_by_store) try writes.append(arena, .{ .addr = w.addr, .len = w.len }); + }; try write_ends.append(arena, @intCast(writes.items.len)); + try store_ends.append(arena, @intCast(stores.items.len)); try read_ends.append(arena, @intCast(reads.items.len)); const line = (try m.line(r.tid)) orelse store.Line{}; try lines.append(arena, line); @@ -378,10 +415,10 @@ fn index(r: *Recording) !void { try own.append(arena, if (ours) line.line else if (own.items.len > 0) own.items[own.items.len - 1] else 0); try reached.append(arena, ours and line_file != null); try touch_list.append(arena, touched); - pending_reads = touched; + pending = touched; try branch_list.append(arena, branched); if (ours and regs != null) try code_lines.put(gpa, regs.?.rip, line.line); - try registers.append(arena, if (regs != null and before != null) changedRegisters(before.?, regs.?) else 0); + try registers.append(arena, regs orelse before orelse .{}); if (!told and stepped and regs != null and before != null) { const now = regs.?; @@ -407,6 +444,19 @@ fn index(r: *Recording) !void { }; } } + // A recording that begins inside a call (`record --from`): the call + // it first stops in was made before it, and is open. + if (!told and broke and ours and calls.items.len == 0) if (regs) |now| { + var found: [2]zt.Debugger.Frame = undefined; + const frames = zt.telescope.frames(m, &now, &found) catch found[0..0]; + if (frames.len == 2 and frames[0].high > frames[0].low) { + const function = r.functionAt(line.line); + takes_nothing = function != null and !function.?.takes; + try calls.append(arena, .{ .function = try r.intern(if (function) |fun| fun.name else "?"), .parent = null, .depth = 0, .sp = frames[0].high - 8, .enter = i }); + try open_calls.append(gpa, 0); + try derived.append(gpa, frames[1].pc); + } + }; if (regs) |g| before = g; try depths.append(arena, @intCast(open_calls.items.len)); @@ -445,6 +495,7 @@ fn index(r: *Recording) !void { r.allocations = allocations.items; r.registers = registers.items; r.write_spans = .{ .all = writes.items, .ends = write_ends.items }; + r.store_spans = .{ .all = stores.items, .ends = store_ends.items }; r.insn_touches = touch_list.items; r.insn_branches = branch_list.items; r.code_lines = try arena.alloc(CodeLine, code_lines.count()); @@ -457,6 +508,8 @@ fn index(r: *Recording) !void { } }.less); r.read_spans = .{ .all = reads.items, .ends = read_ends.items }; + r.locals = locals.items; + r.globals = globals.items; } /// A string id for `text`, for names the recording did not define itself. @@ -471,6 +524,8 @@ pub const Function = struct { /// Whether it has parameters: `main(void)` has none; and how many. takes: bool, params: usize = 0, + /// Its first parameter's name ("" when it takes none). + param: []const u8 = "", /// Its declaration's first line (from 1) and last. first: u32, last: u32, @@ -490,7 +545,10 @@ pub fn outline(arena: std.mem.Allocator, source: []const u8, file: []const u8) ! if (from == paren) continue; const close = std.mem.indexOfScalarPos(u8, header, paren, ')') orelse header.len; const params = std.mem.trim(u8, header[paren + 1 .. close], " "); - try found.append(arena, .{ .name = header[from..paren], .takes = params.len > 0 and !std.mem.eql(u8, params, "void"), .params = if (params.len > 0 and !std.mem.eql(u8, params, "void")) std.mem.count(u8, params, ",") + 1 else 0, .first = @intCast(d.start_line + 1), .last = @intCast(d.end_line + 1) }); + const first_param = std.mem.trim(u8, params[0 .. std.mem.indexOfScalar(u8, params, ',') orelse params.len], " "); + var name_from = first_param.len; + while (name_from > 0 and (std.ascii.isAlphanumeric(first_param[name_from - 1]) or first_param[name_from - 1] == '_')) name_from -= 1; + try found.append(arena, .{ .name = header[from..paren], .takes = params.len > 0 and !std.mem.eql(u8, params, "void"), .params = if (params.len > 0 and !std.mem.eql(u8, params, "void")) std.mem.count(u8, params, ",") + 1 else 0, .param = first_param[name_from..], .first = @intCast(d.start_line + 1), .last = @intCast(d.end_line + 1) }); } return found.items; } @@ -531,8 +589,7 @@ pub fn moment(r: *const Recording, i: u64) Moment { /// Register `reg` of the thread shown at moment `i`; 0 when the recording /// has no registers there. pub fn register(r: *const Recording, i: u64, reg: []const u8) u64 { - const regs = (r.moment(i).regs(r.tid) catch null) orelse return 0; - return regs.named(reg) orelse 0; + return r.registers[@min(i, r.end())].named(reg) orelse 0; } /// A string id's text; "?" for one the recording never defined. @@ -572,7 +629,17 @@ pub fn resolve(r: *const Recording, scratch: std.mem.Allocator, t: types.Type) ? /// began: until then its bytes are whatever that stretch of stack held /// before, and a picture should not show them as its value. pub fn assigned(r: *const Recording, v: Variable, i: u64) bool { - if (v.depth == 0) return true; + if (v.depth == 0) { + // A recording that tells no calls: a local is its value once + // written after it was declared; a global always is. + var k = r.locals.len; + while (k > 0) { + k -= 1; + const d = r.locals[k]; + if (d.moment <= i and d.addr == v.addr) return touches(r.written(d.moment, i), v.addr, v.size) or touches(r.store_spans.of(d.moment, i), v.addr, v.size); + } + return true; + } var enter: u64 = 0; for (r.calls) |c| { if (c.enter > i) break; @@ -589,6 +656,32 @@ pub fn identity(r: *const Recording, m: Moment, addr: u64) ?usize { return null; } +/// What file descriptor `fd` is open on at moment `i`, as the `value` +/// class `fd` says it: the path the call that returned it was given, +/// quoted; the three a program starts with by name; "" when not known. +pub fn openOn(r: *const Recording, scratch: std.mem.Allocator, fd: u64, i: u64) []const u8 { + var on: []const u8 = switch (fd) { + 0 => "stdin", + 1 => "stdout", + 2 => "stderr", + else => "", + }; + const SYS = std.os.linux.SYS; + for (r.syscalls) |s| { + if (s.enter >= i) break; + switch (std.enums.fromInt(SYS, s.nr) orelse continue) { + .open, .openat, .creat => if (s.exit != null and s.exit.? <= i and s.result == fd) { + on = if (s.text.len > 0) std.fmt.allocPrint(scratch, "\"{s}\"", .{std.fs.path.basename(s.text)}) catch "" else ""; + }, + .close => if (s.args[0] == fd) { + on = ""; + }, + else => {}, + } + } + return on; +} + /// The calls open at moment `i`, outermost first, in `scratch`. /// shortcut: looks at every call made by then; a recording of a million calls wants each call's stack kept as a chain of parents. pub fn stack(r: *const Recording, scratch: std.mem.Allocator, i: u64) []const Call { @@ -676,13 +769,26 @@ pub fn read(r: *const Recording, from: u64, to: u64) []const Span { return r.read_spans.of(from, to); } -/// A bit for each register of `Regs.names` they changed. +/// A bit for each register of `Regs.names` that is not what it was: +/// a register a step changed and put back (a call's rsp) is not changed. pub fn registersChanged(r: *const Recording, from: u64, to: u64) u32 { - var mask: u32 = 0; - if (to < r.registers.len and from < to) for (r.registers[from + 1 .. to + 1]) |m| { - mask |= m; - }; - return mask; + if (to >= r.registers.len or from >= to) return 0; + return changedRegisters(r.registers[from], r.registers[to]); +} + +/// Whether bytes `span` are drawn somewhere for the step from `from` to +/// `to`: in the stack's frame round either stop's rsp and rbp, in an +/// allocation, or in a global (an array's cells). Elsewhere (the library's +/// own memory) a step's memory level has nothing to show. +pub fn drawn(r: *const Recording, span: Span, from: u64, to: u64) bool { + for ([_]u64{ from, to }) |i| { + const regs = r.registers[@min(i, r.end())]; + const low = regs.rsp -| 8; + const high = @max(regs.rbp, regs.rsp) + 16 + 8 * 8; + if (span.addr < high and span.addr + span.len > low) return true; + } + for (r.allocations) |a| if (span.addr < a.ptr + a.size and span.addr + span.len > a.ptr -| 16) return true; + return touches(r.globals, span.addr, span.len); } pub fn touches(list: []const Span, addr: u64, size: u64) bool { @@ -690,6 +796,12 @@ pub fn touches(list: []const Span, addr: u64, size: u64) bool { return false; } +/// Whether one of `by` (an instruction's touches) stores into `span`. +fn stored(by: [2]?Touch, span: Span) bool { + for (by) |p| if (p) |w| if (w.how & 2 != 0 and w.addr < span.addr + span.len and w.addr + w.len > span.addr) return true; + return false; +} + /// A bit for each register of `Regs.names` that differs between `a` and `b`. pub fn changedRegisters(a: zt.Regs, b: zt.Regs) u32 { var mask: u32 = 0; diff --git a/anim/src/array.zig b/anim/src/array.zig index b4472e7..9adc132 100644 --- a/anim/src/array.zig +++ b/anim/src/array.zig @@ -38,19 +38,26 @@ pub const Array = struct { focus: bool = false, /// The timetable of a step that swaps two neighbouring cells (give it - /// to `Cursor.step`): the line fires, the first value lifts and - /// flies, the second a little behind it; each lands with a strike; - /// then the hold, and the mark moves on. 2.1 s. + /// to `Cursor.step`): the line fires; the registers strike; the two + /// runs of bytes strike, 6 f apart, and the projection draws from + /// them; only then does the first value lift and fly, the second a + /// little behind it; each lands with a strike; then the hold, and the + /// mark moves on. 2.9 s. pub const swap: cursors.Plan = blk: { - const lands = time.fire + fl.lift + fl.near; + const bytes = 2 * time.cascade; + const lands = bytes + time.project.bracket + time.project.draw + fl.lift + fl.near; const advance = lands + fl.second + time.read_value; - break :blk .{ .at = .{ time.cascade, time.cascade, lands }, .advance = advance, .travel = time.step, .total = advance + time.step + time.rest }; + break :blk .{ .at = .{ time.cascade, bytes, lands }, .advance = advance, .travel = time.step, .total = advance + time.step + time.rest }; }; pub fn draw(g: *const Array, f: *sk.Frame, at: anim.Placed) void { const box = g.stage.box(at, .band); if (box.h < theme.metric.context.tag + 24) return; - const u = context.at(f, at, box); + const u = context.at(f, at, box).faded(at.value(g.stage.drawing)); + // A relayout moves the band: what is drawn in it stays inside it + // (its view, drawn below, clips itself and hands the clip back). + u.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }); + defer u.unclip(); const now = g.cursor.now(at); const rec = g.cursor.rec; const moment = now.shown(.idea); @@ -59,21 +66,23 @@ pub const Array = struct { return; }; const kind = rec.typeOf(f.scratch, v.type); - // Its declaration in the tag, and in the right half its bytes. + // Its declaration in the tag, and in its view its bytes. _ = u.panel(box.w, box.h, objects.declare(f.scratch, rec, v), .{ .focus = g.focus }); const m = theme.metric.context; - const half = theme.layout.state.x - theme.layout.program.x; // An array of numbers; anything else is read as 4-byte ones. const elem: u64 = if (kind != null and kind.? == .array) kind.?.array.elem.size() orelse 4 else 4; const signed = kind == null or kind.? != .array or kind.?.array.elem.* != .scalar or kind.?.array.elem.scalar.kind == .int; + // An element is read as its type says: a character quoted, a boolean by name. + const elem_type: Recording.types.Type = if (kind != null and kind.? == .array) kind.?.array.elem.* else .{ .scalar = .{ .kind = .int, .bits = 32 } }; const count: usize = @intCast(@min(v.size / elem, 32)); if (count == 0) return; { const first = v.addr & ~@as(u64, 15); - const rows_n = @min(theme.layout.rowsIn(box.h), (v.addr + v.size - first + 15) / 16); - u.text(.sans_medium, theme.size.sans.tag, half + 12, m.tag - 6, "its bytes", t.primary); - u.text(.sans, theme.size.sans.micro, half + 12 + u.width(.sans_medium, theme.size.sans.tag, "its bytes") + 12, m.tag - 6, u.print("{x} to {x}, an element a run", .{ v.addr, v.addr + v.size - 1 }), t.faint); - hexdump.draw(u, now, half, m.tag + m.pad, first, rows_n, .{ .array = .{ .addr = v.addr, .len = v.size, .elem = @intCast(elem) }, .region = context.ink(context.regionOf(moment, v.addr)) }); + const dump = hexdump.panel(f, at, g.stage, u.print("{x} to {x}, an element a run", .{ v.addr, v.addr + v.size - 1 }), &.{}); + const rows_n = @min(dump.rows, (v.addr + v.size - first + 15) / 16); + if (rows_n > 0) hexdump.draw(dump.u, now, 0, m.tag + m.pad, first, rows_n, .{ .array = .{ .addr = v.addr, .len = v.size, .elem = @intCast(elem) }, .region = context.ink(context.regionOf(moment, v.addr)) }); + dump.veil(now); + u.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }); } // The cells, in the left half: a size up as the subject. @@ -82,8 +91,8 @@ pub const Array = struct { const cell: [2]f32 = if (subject) .{ 96, 72 } else .{ 80, 44 }; const size: f32 = if (subject) theme.size.mono.flight else theme.size.mono.small; const label: f32 = if (subject) theme.size.mono.small else theme.size.mono.context; - const left = (half - 32 - @as(f32, @floatFromInt(count)) * cell[0]) / 2; - const top = m.tag + @as(f32, if (subject) 44 else 16) + label * 1.2 + 4; + const left = (box.w - @as(f32, @floatFromInt(count)) * cell[0]) / 2; + const top = m.tag + @as(f32, if (subject) 72 else 16) + label * 1.2 + 4; const walking = now.walking(); // What moved: a cell written with what another cell held, which this step read. @@ -105,7 +114,11 @@ pub const Array = struct { } }; + // Each cell as much as it has risen from its bytes (`establish`). + const rising = at.value(g.stage.rise); for (0..count) |i| { + const risen = ties.rise(rising, i, count); + const cu = u.faded(risen.element).moved(0, risen.below); const r: Rect = .{ .x = left + @as(f32, @floatFromInt(i)) * cell[0], .y = top, .w = cell[0] - 2, .h = cell[1] }; const addr = v.addr + i * elem; // The cell a value is flying to is struck when it lands: the second a little after the first. @@ -117,13 +130,13 @@ pub const Array = struct { var heat = now.written(addr, elem, .idea, delay); // The value on its way is the anticipation: no frame as well. if (flown != null) heat.arm = 0; - const ink = u.cellWritten(r, heat, theme.color.raised); + const ink = cu.cellWritten(r, heat, theme.color.raised); // Staging: the compare is seen (framed as read) before anything moves. - if (now.wasRead(addr, elem) and now.writeAge(addr, elem) != 0) u.cellRead(r, now.reading(.idea, 0)); + if (now.wasRead(addr, elem) and now.writeAge(addr, elem) != 0) cu.cellRead(r, now.reading(.idea, 0)); // Its index over it, where a node has its address: the projection lands there. const index_text = u.print("{d}", .{i}); const ly = r.y - 4 - label * 1.2; - u.text(.mono, label, r.x + (r.w - @as(f32, @floatFromInt(index_text.len)) * label * 3 / 5) / 2, ly + label * 0.96, index_text, t.faint); + cu.text(.mono, label, r.x + (r.w - @as(f32, @floatFromInt(index_text.len)) * label * 3 / 5) / 2, ly + label * 0.96, index_text, t.faint); ties.anchor(u, .{ .node_address = addr }, .{ .x = r.x, .y = ly, .w = r.w, .h = label * 1.2 }); ties.anchor(u, .{ .node_part = addr }, r); // Until its new value lands a cell keeps the old one, faint once @@ -131,31 +144,10 @@ pub const Array = struct { const shown = if (pending) old[i] else values[i]; const digits = r; const leaving = pending and flown != null and (!walking or now.since(.idea, delay) >= -(flightTime(cell[0]) + fl.lift)); - if (shown) |n| u.label(ink.face, size, digits, .center, u.print("{d}", .{n}), if (leaving) ui.rgb(t.faint) else ink.ink) else u.unknown(digits); + if (shown) |n| cu.label(ink.face, size, digits, .center, objects.reading(u.f.scratch, n, elem_type), if (leaving) ui.rgb(t.faint) else ink.ink) else cu.unknown(digits); } - // Index variables: pins under the cell they index, sliding from - // cell to cell as the idea strikes; two in one cell share its pin. - var at_cell: [32]std.ArrayList([]const u8) = @splat(.empty); - var slide: [32]?f32 = @splat(null); - for (g.indices) |name| { - const iv = rec.variable(f.scratch, now.moment(), name) orelse continue; - const here = number(now.moment(), iv.addr, @min(iv.size, 8), true) orelse continue; - if (here < 0 or here >= count) continue; - const k: usize = @intCast(here); - at_cell[k].append(f.scratch, name) catch {}; - if (number(now.before(), iv.addr, @min(iv.size, 8), true)) |was| if (was != here and was >= 0 and was < count) { - slide[k] = @floatFromInt(was); - }; - } - for (at_cell, 0..) |names, k| { - if (names.items.len == 0) continue; - var x = left + (@as(f32, @floatFromInt(k)) + 0.5) * cell[0]; - if (slide[k]) |was| x = std.math.lerp(left + (was + 0.5) * cell[0], x, cursors.standard(now.moving(.idea, 0, time.move))); - u.pinUnder(x, top + cell[1], names.items, t.primary, label); - } - - // Values in flight, over everything: one over, the next under. + // Values in flight, over the cells and under every name and pin: one over, the next under. for (flights.items, 0..) |flight, k| { const from = ui.Vec{ left + (@as(f32, @floatFromInt(flight.from)) + 0.5) * cell[0], top + cell[1] / 2 + 9 }; const to = ui.Vec{ left + (@as(f32, @floatFromInt(flight.to)) + 0.5) * cell[0], top + cell[1] / 2 + 9 }; @@ -179,7 +171,10 @@ pub const Array = struct { } // Arcs: an idea moves on a curve, slow out of one cell and into the other, quickest over the top. const eased = cursors.glide(along); - const rise = std.math.clamp(fl.arc * far, fl.arc_min, fl.arc_max) + cell[1] / 2; + // As high as a quarter of the way, clear of the row, and never out of the band. + const card_half = (cell[1] + 4) * fl.lift_scale / 2; + const room = @min(from[1] - card_half - m.tag - 2, box.h - 4 - card_half - from[1]); + const rise = @min(std.math.clamp(fl.arc * far, fl.arc_min, fl.arc_max) + cell[1] / 2, room); const way: f32 = if (k % 2 == 0) -1 else 1; const c = sk.math.mix(from, to, eased) + ui.Vec{ 0, way * rise * @sin(std.math.pi * eased) }; const grown = std.math.lerp(1, fl.lift_scale, lifted); @@ -188,9 +183,53 @@ pub const Array = struct { const card: Rect = .{ .x = c[0] - w / 2, .y = c[1] - h / 2, .w = w, .h = h }; u.fill(card, theme.color.page); u.frame(card, t.bright, theme.stroke.line); - if (values[flight.to]) |n| u.label(.mono_bold, size, card, .center, u.print("{d}", .{n}), t.bright); + if (values[flight.to]) |n| u.label(.mono_bold, size, card, .center, objects.reading(u.f.scratch, n, elem_type), t.bright); _ = compact; } + // Under the cards in flight: index variables, pins under the cell they index, sliding from + // cell to cell as the idea strikes; two in one cell share its pin. + var at_cell: [32]std.ArrayList([]const u8) = @splat(.empty); + var slide: [32]?f32 = @splat(null); + for (g.indices) |name| { + const iv = rec.variable(f.scratch, now.moment(), name) orelse continue; + const here = number(now.moment(), iv.addr, @min(iv.size, 8), true) orelse continue; + if (here < 0 or here >= count) continue; + const k: usize = @intCast(here); + at_cell[k].append(f.scratch, name) catch {}; + if (number(now.before(), iv.addr, @min(iv.size, 8), true)) |was| if (was != here and was >= 0 and was < count) { + slide[k] = @floatFromInt(was); + }; + } + // And the registers that hold a cell's address: a pin, where a link lands. + const is = (now.moment().regs(rec.tid) catch null) orelse @import("ztrace").Regs{}; + const was_regs = (now.before().regs(rec.tid) catch null) orelse is; + const ink = context.ink(context.regionOf(moment, v.addr)); + for (&at_cell, 0..) |*names, k| { + const addr = v.addr + k * elem; + const cx = left + (@as(f32, @floatFromInt(k)) + 0.5) * cell[0]; + ties.anchor(u, .{ .node_pin = addr }, .{ .x = cx - 1, .y = top + cell[1], .w = 2, .h = label + 10 }); + const indices = names.items.len; + var shows: f32 = 1; + for (theme.metric.all_registers[0..16]) |name| { + const i = context.index(name).?; + const before = was_regs.named(name) == addr; + const after = is.named(name) == addr; + if (!before and !after) continue; + const s = ties.pinShows(now, i, .node); + const this = if (before and after) 1 else if (after) s.new else s.old; + if (this < 0.5) continue; + names.append(f.scratch, name) catch {}; + if (indices == 0) shows = @min(shows, this); + } + if (names.items.len == 0) continue; + var x = cx; + if (slide[k]) |from| x = std.math.lerp(left + (from + 0.5) * cell[0], x, cursors.standard(now.moving(.idea, 0, time.move))); + // An index lives on the stack: its name in stack's ink; a register's primary. + var inks: [8]u24 = @splat(t.primary); + for (inks[0..@min(indices, inks.len)]) |*i_ink| i_ink.* = theme.color.region.stack; + u.faded(shows * ties.rise(rising, k, count).element).pinUnderInked(x, top + cell[1], names.items, inks[0..@min(names.items.len, inks.len)], if (names.items.len > indices) ink else t.primary, label); + } + } }; @@ -203,7 +242,8 @@ fn number(moment: Recording.Moment, addr: u64, bytes: u64, signed: bool) ?i64 { return @as(i64, @bitCast(raw << shift)) >> shift; } -test "a swap of neighbours is 2.1 seconds" { - try std.testing.expectApproxEqAbs(@as(f32, 2.1), Array.swap.total, 1e-3); +test "a swap of neighbours is 2.9 seconds, its bytes before its flights" { + try std.testing.expectApproxEqAbs(@as(f32, 2.9), Array.swap.total, 1e-3); + try std.testing.expect(Array.swap.at[2] - fl.near - fl.lift > Array.swap.at[1]); try std.testing.expect(flightTime(168) == fl.near and flightTime(336) == fl.mid and flightTime(900) == fl.far); } diff --git a/anim/src/calls.zig b/anim/src/calls.zig index 88bca71..e66da1a 100644 --- a/anim/src/calls.zig +++ b/anim/src/calls.zig @@ -13,6 +13,8 @@ const Cursor = cursors.Cursor; const Recording = @import("Recording.zig"); const context = @import("context.zig"); const Stage = @import("stage.zig").Stage; +const ties = @import("ties.zig"); +const rows = @import("rows.zig"); const theme = ui.theme; const time = theme.time; const Rect = ui.Rect; @@ -30,80 +32,159 @@ pub const Tree = struct { focus: bool = false, pub fn draw(k: *const Tree, f: *sk.Frame, at: anim.Placed) void { + k.backtrace(f, at); const box = k.stage.box(at, .band); if (box.h < theme.metric.context.tag + 24) return; - const u = context.at(f, at, box); + const u = context.at(f, at, box).faded(at.value(k.stage.drawing)); + // A relayout moves the band: what is drawn in it stays inside it. + u.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }); + defer u.unclip(); const now = k.cursor.now(at); const rec = k.cursor.rec; - const m = struct { - const radius = 18; - const level = 44; - const badge = 24; - }; - const body = u.panel(box.w, box.h, u.print("calls of {s}", .{k.function}), .{ .focus = k.focus, .note = "each call a node \u{00b7} its result on the shoulder \u{00b7} the frames are the stack's" }); + const m = metric; + const body = u.panel(box.w, box.h, u.print("calls of {s}", .{k.function}), .{ .focus = k.focus, .note = "each call a node \u{00b7} its result on its shoulder" }); const nodes = layout(f.scratch, rec, k.function) catch return; if (nodes.len == 0) return; var leaves: f32 = 0; for (nodes) |n| leaves = @max(leaves, n.x + 1); - const pitch = @min(4.5 * m.radius, (body.w - 2 * theme.metric.panel.pad_x - 2 * m.radius) / @max(leaves - 1, 1)); - const left = (body.w - (leaves - 1) * pitch) / 2; - const top = body.y + m.radius + 12; - var deepest_level: f32 = 1; - for (nodes) |n| deepest_level = @max(deepest_level, @as(f32, @floatFromInt(n.level))); - const level_h = @min(m.level, (body.h - 2 * m.radius - 24) / deepest_level); - // A call: its edge draws from the caller's node, then the node - // fades in, gold, and the caller's goes from gold to a waiting - // ring. A return: the badge is struck a little after the card's - // result, and the node goes from gold to done. + // The caller's box left of the root on its level; the leaves spread over the rest. + const caller_room = m.caller[0] + 48; + const pitch = (body.w - 2 * theme.metric.panel.pad_x - 2 * m.radius - caller_room) / @max(leaves - 1, 1); + const left = theme.metric.panel.pad_x + caller_room + m.radius; + const top = body.y + m.root; const since = now.since(.idea, 0); const returned = now.walking() and rec.depths[now.stops[0]] < rec.depths[now.stops[1]]; const moment = if (now.plan.gait == .sprint or since >= (if (returned) @as(f32, badge_after) else 0)) now.stops[0] else now.stops[1]; const edge = cursors.standard(now.moving(.idea, time.quick, time.quick)); const appears = now.moving(.idea, 0, time.snap); + const at_of = struct { + fn c(lf: f32, p: f32, tp: f32, n: Node) ui.Vec { + return .{ lf + n.x * p, tp + @as(f32, @floatFromInt(n.level)) * metric.level }; + } + }.c; - // Edges under nodes: the waiting path in vellum. + // The caller: gold until the first call, then waiting, ringed; an edge into the root. + if (nodes[0].call.parent) |p| { + const caller = rec.calls[p]; + const root_c = at_of(left, pitch, top, nodes[0]); + const r: Rect = .{ .x = theme.metric.panel.pad_x, .y = root_c[1] - m.caller[1] / 2, .w = m.caller[0], .h = m.caller[1] }; + const called = nodes[0].call.enter <= moment; + if (nodes[0].call.enter <= now.stops[0]) { + const to = ui.Vec{ root_c[0] - m.radius, root_c[1] }; + const from = ui.Vec{ r.x + r.w, root_c[1] }; + const live = nodes[0].call.active(moment) or nodes[0].call.enter > moment; + u.line(from, if (nodes[0].call.enter > now.stops[1]) sk.math.mix(from, to, edge) else to, if (live) ui.rgb(t.primary) else ui.rgb(theme.color.rule), theme.stroke.line); + } + if (!called) { + u.fill(r, theme.mark(.current).solid); + u.label(.mono_bold, theme.size.mono.context, r, .center, rec.name(caller.function), theme.mark(.current).on_solid); + } else { + u.fill(r, theme.color.page); + u.frame(r, t.primary, theme.stroke.line); + u.label(.mono, theme.size.mono.context, r, .center, rec.name(caller.function), t.primary); + } + } + // Edges under nodes: the waiting path in primary. for (nodes) |n| { const parent = n.parent orelse continue; if (n.call.enter > now.stops[0]) continue; - const from = ui.Vec{ left + nodes[parent].x * pitch, top + @as(f32, @floatFromInt(nodes[parent].level)) * level_h }; - var to = ui.Vec{ left + n.x * pitch, top + @as(f32, @floatFromInt(n.level)) * level_h }; + const from = at_of(left, pitch, top, nodes[parent]); + var to = at_of(left, pitch, top, n); if (n.call.enter > now.stops[1]) to = sk.math.mix(from, to, edge); const live = n.call.active(moment); - u.line(from, to, if (live or n.call.enter > moment) ui.rgb(t.primary) else ui.rgb(theme.color.rule), if (live or n.call.enter > moment) theme.stroke.arrow else theme.stroke.line); + u.line(from, to, if (live or n.call.enter > moment) ui.rgb(t.primary) else ui.rgb(theme.color.rule), theme.stroke.line); } const deepest = deepestActive(nodes, moment); for (nodes, 0..) |n, i| { + const c = at_of(left, pitch, top, n); + // Where a projection from its frame's way back (the word its + // call pushed, at the call's stack pointer) lands: under it, + // there before the node, which comes when it arrives. + if (n.call.enter <= now.stops[0]) ties.anchor(u, .{ .node_address = n.call.sp }, .{ .x = c[0] - m.radius, .y = c[1] - m.radius, .w = 2 * m.radius, .h = 2 * m.radius }); if (n.call.enter > moment) continue; - const c = ui.Vec{ left + n.x * pitch, top + @as(f32, @floatFromInt(n.level)) * level_h }; const v = if (n.call.enter > now.stops[1]) u.faded(appears) else u; if (deepest == i) { v.disc(c, m.radius, ui.rgb(theme.mark(.current).solid), null, 0); } else if (n.call.active(moment)) { - v.disc(c, m.radius - theme.stroke.arrow / 2, ui.rgb(theme.color.page), ui.rgb(t.primary), theme.stroke.arrow); + v.disc(c, m.radius - theme.stroke.line / 2, ui.rgb(theme.color.page), ui.rgb(t.primary), theme.stroke.line); } else v.disc(c, m.radius, ui.rgb(theme.color.raised), null, 0); } // Then the words, so shapes and text each go in one run. - const size = theme.size.mono.context; + const size = theme.size.mono.small; for (nodes, 0..) |n, i| { if (n.call.enter > moment) continue; - const cx = left + n.x * pitch; - const cy = top + @as(f32, @floatFromInt(n.level)) * level_h; + const c = at_of(left, pitch, top, n); const active = n.call.active(moment); const words = if (n.call.arg) |arg| u.print("{d}", .{@as(i64, @bitCast(arg))}) else "?"; - const cell: Rect = .{ .x = cx - m.radius, .y = cy - m.radius, .w = 2 * m.radius, .h = 2 * m.radius }; + const cell: Rect = .{ .x = c[0] - m.radius, .y = c[1] - m.radius, .w = 2 * m.radius, .h = 2 * m.radius }; const v = if (n.call.enter > now.stops[1]) u.faded(appears) else u; if (deepest == i) { v.label(.mono_bold, size, cell, .center, words, theme.mark(.current).on_solid); - } else v.label(.mono, size, cell, .center, words, if (active) t.primary else t.dim); + } else v.label(.mono, size, cell, .center, words, t.primary); if (active) continue; // Done: what it returned, on its shoulder; struck as it lands. - const badge: Rect = .{ .x = cx + 10, .y = cy - m.radius - 12, .w = m.badge, .h = m.badge }; + const badge: Rect = .{ .x = c[0] + m.badge_at[0], .y = c[1] - m.badge_at[1], .w = m.badge, .h = m.badge }; const heat: ui.Heat = if (n.call.exit.? > now.stops[1]) now.heat(0, null, since - badge_after) else .none; const ink = u.cellWritten(badge, heat, theme.color.page); if (heat.level < 1) u.frame(badge, t.faint, theme.stroke.rule); u.label(ink.face, size, badge, .center, u.print("{d}", .{@as(i64, @bitCast(n.call.result))}), if (heat.level >= 1) ink.ink else ui.rgb(t.primary)); } } + + /// Its view: the backtrace, the waiting path read as rows, newest on + /// top, with each call's arguments (`n=4`) and where it is. + fn backtrace(k: *const Tree, f: *sk.Frame, at: anim.Placed) void { + const box = k.stage.box(at, .view); + const cm = theme.metric.context; + if (box.h < cm.tag + cm.row) return; + const u = context.at(f, at, box).faded(at.value(k.stage.view)); + u.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }); + defer u.unclip(); + const now = k.cursor.now(at); + const rec = k.cursor.rec; + // A frame is its words on the stack: the view changes with memory. + const moment = now.stop(.memory); + var buf: [24]context.Frame = undefined; + const chain = context.frames(rec, moment, &buf); + const room = theme.layout.rowsIn(box.h); + const body = u.panel(box.w, box.h, "backtrace", .{ .note = if (chain.len > room) u.print("the calls waiting \u{00b7} newest on top \u{00b7} {d} more", .{chain.len - room}) else "the calls waiting \u{00b7} newest on top" }); + const open = rec.stack(f.scratch, moment); + for (chain[0..@min(chain.len, room)], 0..) |frame, i| { + const y = body.y + cm.pad + @as(f32, @floatFromInt(i)) * cm.row; + const name = ui.symbol(u, rec.strings.get(frame.pc) orelse u.print("{x}", .{frame.pc})); + // The call this frame is, by its place on the chain: its arguments. + const call: ?Recording.Call = if (i < open.len) open[open.len - 1 - i] else null; + const args = if (call) |c| arguments(u, rec, c) else ""; + const line = if (i == 0) rec.own[now.marked()] else rec.lineOf(frame.pc) orelse 0; + const where = if (line > 0 and (i == 0 or rec.lineOf(frame.pc) != null)) u.print("{s}:{d}", .{ rec.file, line }) else ""; + rows.callRow(u, y, box.w, i, name, args, where, i == 0); + } + context.veiled(u, box, now.sprint_veil); + } +}; + +/// A call's arguments as its backtrace row and its span say them: its +/// parameter's name and value, `n=4`; "" for one that takes nothing. +pub fn arguments(u: ui.Ui, rec: *const Recording, c: Recording.Call) []const u8 { + const f = for (rec.functions) |fun| { + if (std.mem.eql(u8, fun.name, rec.name(c.function))) break fun; + } else return ""; + if (!f.takes) return ""; + const arg = c.arg orelse return ""; + const name = if (c.parameter_name) |id| rec.name(id) else f.param; + return u.print("{s}={d}", .{ name, @as(i64, @bitCast(arg)) }); +} + +/// The tree's measures (design/README.md, `calls`): a disc 48 across, +/// levels 46 apart, the root 48 under the tag; the result's square of 30 +/// on the shoulder, 12 right of the centre and 42 up; the caller's box. +const metric = struct { + const radius = 24; + const level = 46; + const root = 48; + const badge = 30; + const badge_at = [2]f32{ 12, 42 }; + const caller = [2]f32{ 64, 28 }; }; pub const Node = struct { diff --git a/anim/src/context.zig b/anim/src/context.zig index 092d76a..b3591fc 100644 --- a/anim/src/context.zig +++ b/anim/src/context.zig @@ -76,14 +76,8 @@ pub const Registers = struct { const u = at(f, placed, box); const now = r.cursor.now(placed); const rec = r.cursor.rec; - var is: Shown = .{ .regs = (now.moment().regs(rec.tid) catch null) orelse zt.Regs{}, .moment = now.moment() }; - var was: Shown = .{ .regs = (now.before().regs(rec.tid) catch null) orelse is.regs, .moment = now.before() }; - if (r.syscalls) { - // The registers as the newest call crossed with them: the - // library's own use of them after it returns is not the story. - if (syscalls.latest(rec, now.stops[0])) |n| is = shownAt(rec, rec.syscalls[n].enter) orelse is; - if (syscalls.latest(rec, now.stops[1])) |n| was = shownAt(rec, rec.syscalls[n].enter) orelse was; - } + const is: Shown = .{ .regs = (now.moment().regs(rec.tid) catch null) orelse zt.Regs{}, .moment = now.moment() }; + const was: Shown = .{ .regs = (now.before().regs(rec.tid) catch null) orelse is.regs, .moment = now.before() }; const body = u.panel(box.w, box.h, "registers", .{ .focus = r.focus, .legend = &legend }); // A link leaves from the panel's edge, not through a name. ties.anchor(u, .registers, .{ .x = 0, .y = 0, .w = box.w, .h = box.h }); @@ -112,7 +106,8 @@ pub const Registers = struct { fn rip(r: *const Registers, u: ui.Ui, now: cursors.Now, y: f32, w: f32, is: Shown, was: Shown) void { const rec = r.cursor.rec; const moment = now.marks[if (now.advancing() >= 0.5) 1 else 0]; - const landed = now.landed(.cpu, 0); + // The flags' ticks are secondary: 6 f after the registers strike, not with them. + const landed = now.landed(.cpu, cursors.write_apart); const flags = (if (landed) is else was).regs.eflags; // The flags a step changed are ticked, for three steps. const eflags_index = comptime index("eflags").?; @@ -120,21 +115,34 @@ pub const Registers = struct { const age = if (landed) now.registerAge(eflags_index) else now.registerAgeFrom(eflags_index, 1); var changed: u64 = 0; if (age) |a| changed = rec.register(now.stops[a], "eflags") ^ rec.register(now.stops[a + 1], "eflags"); - const held = if (r.quiet) 0 else now.register(eflags_index, 0).level; + const held = if (r.quiet) 0 else now.register(eflags_index, cursors.write_apart).level; rows.rip(u, y, w, rec.moment(moment), rec.register(moment, "rip"), flags, changed, held, 0); } - fn row(r: *const Registers, u: ui.Ui, now: cursors.Now, is: Shown, was: Shown, name: []const u8, y: f32, w: f32) void { + fn row(r: *const Registers, u: ui.Ui, now: cursors.Now, line_is: Shown, line_was: Shown, name: []const u8, y: f32, w: f32) void { + const rec = r.cursor.rec; const i = index(name) orelse return; + // Every register is the program's, at its line stops, as every + // other panel is: what crossed into the kernel is the crossing's + // to show, and a register is framed as carrying it only where it + // still holds what crossed. + const is = line_is; + const was = line_was; const value_now = is.regs.named(name) orelse return; const value_was = was.regs.named(name) orelse value_now; var marks: rows.Marks = .{}; var landed = now.landed(.cpu, 0); - if (if (r.syscalls) syscalls.inStep(now) else null) |made| { + var note: []const u8 = ""; + const crossing: ?Recording.Syscall = if (r.syscalls) syscalls.inStep(now) else null; + // A register the call neither carries nor answers in is any register. + const takes_part = if (crossing) |made| std.mem.eql(u8, name, "rax") or for (syscalls.carried(made), 0..) |carried, k| { + if (std.mem.eql(u8, carried, name) and value_now == made.args[k]) break true; + } else false else false; + if (if (takes_part) crossing else null) |made| { const plan = syscalls.Plan.of(made); const is_rax = std.mem.eql(u8, name, "rax"); - const carrier: ?usize = if (is_rax) 0 else for (syscalls.carried(made), 1..) |carried, k| { - if (std.mem.eql(u8, carried, name)) break k; + const carrier: ?usize = if (is_rax) null else for (syscalls.carried(made), 1..) |carried, k| { + if (std.mem.eql(u8, carried, name) and value_now == made.args[k - 1]) break k; } else null; // What carries the call is framed as read, one register at a // time: they are what crosses the line. @@ -143,25 +151,37 @@ pub const Registers = struct { if (carrier != null) { marks.read = 0; marks.read_shows = @min(std.math.clamp(framed / time.read.in, 0, 1), now.reading(.cpu, 0)); + // A descriptor says what it is open on: the `value` class `fd`. + const names = zt.syscalls.names(made.nr); + if (landed and carrier.? >= 1 and carrier.? <= names.len and std.mem.endsWith(u8, names[carrier.? - 1], "fd")) note = rec.openOn(u.f.scratch, value_now, made.enter); } if (is_rax) { - // rax: the call's number going in, the result coming back. + // rax: what was there, then the result coming back (the + // call's number is the crossing's: it went in at the wrapper). const back = now.time - plan.returns; const result = back >= time.strike.in / 2.0; - const value: u64 = if (result) value_now else if (landed) made.nr else value_was; + const value: u64 = if (result) value_now else value_was; if (back >= -time.strike.arm) { marks = .{ .first = now.heat(0, null, back) }; if (back >= 0 and now.walking()) marks.extend = back; } const hops = rows.reg(u, y, w, name, if (result) is.moment else was.moment, value, marks); + // What `open` gave back is a descriptor: the `value` class + // `fd`, this call's once it is back, the last one's before. + const gave = if (result) made else if (syscalls.latest(rec, now.stops[1])) |n| rec.syscalls[n] else null; + if (gave) |g| if (g.exit != null and g.result == value and std.mem.eql(u8, zt.syscalls.name(g.nr) orelse "", "open")) fdNote(u, hops, y, rec.openOn(u.f.scratch, value, g.exit.? + 1)); return anchor(u, i, hops, y); } + } else if (r.quiet) { // Unmarked: the values change as the mark moves on. landed = now.advancing() >= 0.5; } else { const age = now.registerAge(i); - const delay = if (age == 0) ties.strikeDelay(now, i) else 0; + // In a step that crosses into the kernel, what else the line + // changed is seen after the call is back. + const after_call: f32 = if (crossing) |made| syscalls.Plan.of(made).returns - syscalls.Plan.of(made).registers else 0; + const delay = (if (age == 0) ties.strikeDelay(now, i) else 0) + after_call; landed = now.landed(.cpu, delay); marks.first = now.register(i, delay); // A register written: the rest of its chain is followed again. @@ -169,9 +189,15 @@ pub const Registers = struct { if (age == 0 and now.walking() and since >= 0) marks.extend = since; } const hops = rows.reg(u, y, w, name, if (landed) is.moment else was.moment, if (landed) value_now else value_was, marks); + fdNote(u, hops, y, note); anchor(u, i, hops, y); } + /// The `fd` class's note after a register's value: faint, what it is open on. + fn fdNote(u: ui.Ui, hops: rows.Hops, y: f32, on: []const u8) void { + if (hops.n > 0 and on.len > 0) u.text(.mono, theme.size.mono.context, hops.end + 8, rows.baseline(y), on, t.faint); + } + fn anchor(u: ui.Ui, i: usize, hops: rows.Hops, y: f32) void { if (hops.n > 0) ties.anchor(u, .{ .register = i }, .{ .x = hops.x[0], .y = y, .w = hops.w[0], .h = m.row }); } @@ -199,6 +225,23 @@ pub fn frames(rec: *const Recording, i: u64, out: []Frame) []Frame { return out[0..found.len]; } +/// A frame's span on the stack: its function's name, and as a call its +/// argument where it takes one (`fib(4)`): the digits on its node. +fn spanName(u: ui.Ui, rec: *const Recording, open: []const Recording.Call, i: usize, pc: u64) []const u8 { + const name = frameName(u, rec, pc); + if (i >= open.len) return name; + const call = open[open.len - 1 - i]; + if (!std.mem.eql(u8, rec.name(call.function), name)) return name; + const takes = for (rec.functions) |f| { + if (std.mem.eql(u8, f.name, name)) break f.takes; + } else false; + const arg = call.arg orelse return name; + if (!takes) return name; + const v = ui.Value.of(arg, rows.regionOf(rec.moment(call.enter), arg) != .none); + // A small number in decimal, as on the node; anything else as its class has it. + return if (v.decimal) u.print("{s}({d})", .{ name, arg }) else u.print("{s}({s}{s})", .{ name, v.prefix, v.digits() }); +} + /// A frame's name: its function's (no offset), or its module's and offset where there is no symbol. pub fn frameName(u: ui.Ui, rec: *const Recording, pc: u64) []const u8 { const name = rec.strings.get(pc) orelse return u.print("{x}", .{pc}); @@ -226,37 +269,76 @@ pub const Stack = struct { const now = k.cursor.now(placed); const rec = k.cursor.rec; const slots = rowsOf(box); - const body = u.panel(box.w, box.h, "stack", .{ .focus = k.focus, .note = u.print("{s} words from rsp \u{00b7} the frames they belong to", .{switch (slots) { - 4 => "four", - 8 => "eight", - else => u.print("{d}", .{slots}), - }}) }); const is = (now.moment().regs(rec.tid) catch null) orelse return; const was = (now.before().regs(rec.tid) catch null) orelse is; - // The window is rsp's: when a step moves it the rows slide, with the - // stack's words, a level after the registers (one onset at a time). + // The window: from rsp, or further into the frame ([rsp, rbp+16)) + // when that is longer than the panel, so that the word the last + // steps touched is in its middle. When a step moves it the rows + // slide, with the stack's words, a level after the registers. + // Under the camera the window holds still, `free` words above the + // rsp it was held at: pushes fill them, and rsp's pin climbs. + const hold = placed.value(k.stage.hold); + const held = hold >= 0; + const held_at: u64 = if (held) rec.register(@intFromFloat(hold), "rsp") -% 8 * @as(u64, @intFromFloat(placed.value(k.stage.hold_free))) else 0; + const window = if (held) [2]u64{ held_at, held_at } else [2]u64{ windowAt(now, is, slots, 0), windowAt(now, was, slots, 1) }; + // Going to the hold and coming from it, the rows scroll: the + // remaining way, in rows, from where the window would be. + const natural = windowAt(now, is, slots, 0); + const hold_scroll: f32 = if (held) @as(f32, @floatFromInt(@as(i64, @bitCast(held_at -% natural)))) / 8 * (1 - cursors.glide(placed.value(k.stage.hold_in))) else 0; const landed = now.landed(.memory, 0); + // From rsp, or the range shown when the window is elsewhere: in + // bytes from rsp, as the catalogue writes it (`rsp+20 to rsp+48`). + const from_rsp: i64 = if (landed) @bitCast(window[0] -% is.rsp) else @bitCast(window[1] -% was.rsp); + const offset = struct { + fn of(u_: ui.Ui, d: i64) []const u8 { + return if (d == 0) "rsp" else if (d > 0) u_.print("rsp+{x}", .{@as(u64, @intCast(d))}) else u_.print("rsp-{x}", .{@as(u64, @intCast(-d))}); + } + }.of; + const words = switch (slots) { + 4 => "four", + 6 => "six", + 8 => "eight", + else => u.print("{d}", .{slots}), + }; + const range = if (from_rsp == 0) u.print("{s} words from rsp", .{words}) else u.print("{s} to {s}", .{ offset(u, from_rsp), offset(u, from_rsp + 8 * @as(i64, @intCast(slots))) }); + const body = u.panel(box.w, box.h, "stack", .{ .focus = k.focus, .note = u.print("{s} \u{00b7} the frames they belong to", .{range}) }); const p = cursors.glide(now.moving(.memory, 0, time.move)); - const moved = @as(f32, @floatFromInt(@as(i64, @bitCast(is.rsp -% was.rsp)))) / 8; - const slide: f32 = if (@abs(moved) > 16) 0 else moved * (1 - p); + const moved = @as(f32, @floatFromInt(@as(i64, @bitCast(window[0] -% window[1])))) / 8; + const slide: f32 = (if (@abs(moved) > 16) 0 else moved * (1 - p)) + hold_scroll; const top = body.y + m.pad; clipBody(u, box); defer u.unclip(); - // The addresses' shared digits: the rows read by their ends. - const lead = ui.shared(&.{ is.rsp, is.rsp + 8 * @as(u64, slots) }); + // The addresses' shared digits: the rows read by their ends, of the + // window shown (it changes with the slide, not before it). + const shown_at = if (landed) window[0] else window[1]; + const lead = ui.shared(&.{ shown_at, shown_at + 8 * @as(u64, slots) }); const memory = now.shown(.memory); + // rsp and rbp, moved by the step with no link to land: their tags + // travel down the lane from the old word to the new, with the slide. + var travel_buf: [2][]const u8 = undefined; + var travelling: usize = 0; + for ([_][]const u8{ "rsp", "rbp" }) |name| if (!now.resting() and was.named(name) != is.named(name)) { + travel_buf[travelling] = name; + travelling += 1; + }; + const travel = travel_buf[0..travelling]; var n: i64 = @as(i64, @intFromFloat(@floor(-slide))) - 1; while (n <= @as(i64, @intCast(slots)) - @as(i64, @intFromFloat(@floor(slide)))) : (n += 1) { const y = top + (@as(f32, @floatFromInt(n)) + slide) * m.row; if (y + m.row < body.y or y > box.h) continue; - const addr = is.rsp +% @as(u64, @bitCast(n * 8)); + const addr = window[0] +% @as(u64, @bitCast(n * 8)); // Who points here: a pin in the lane, landing with its link. - const names = pins(u, now, is, was, addr); + const names = pins(u, now, is, was, addr, travel); var marks: rows.Marks = .{ .lead = lead, .first = now.written(addr, 8, .memory, 0) }; if (now.wasRead(addr, 8) and now.writeAge(addr, 8) != 0) { marks.read = 0; marks.read_shows = now.reading(.memory, 0); } + // `free`: above rsp, not yet reached: its address at 60%, its word faint. + if (held and addr < (if (landed) is.rsp else was.rsp)) { + rows.free(u, y, memory, addr, lead); + continue; + } const hops = rows.slot(u, y, box.w, memory, addr, names.names, names.shows, marks); // Only a row on show is a place a tie can land. if (y >= top - 1 and y + m.row <= box.h - m.pad + 1) { @@ -264,30 +346,89 @@ pub const Stack = struct { 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 backtrace, drawn on the words that are each frame: it changes with the CPU. + // Where the window is, for a link to a word outside it. + const lane_at = u.at.xf.apply(.{ theme.metric.slot.lane, top }); + const row_px = u.at.xf.apply(.{ 0, top + m.row })[1] - lane_at[1]; + ties.stack_window = .{ .first = window[0], .slots = slots, .x = lane_at[0], .top = lane_at[1], .row = row_px }; + // The travelling tags: both of them at one word share a pin. + const going = cursors.standard(if (now.resting()) 1 else std.math.clamp(now.since(.cpu, 0) / time.move, 0, 1)); + var places: [2]f32 = undefined; + for (travel, places[0..travel.len]) |name, *place| { + const at_old = @as(f32, @floatFromInt(@as(i64, @bitCast((was.named(name) orelse 0) -% window[0])))) / 8 + slide; + const at_new = @as(f32, @floatFromInt(@as(i64, @bitCast((is.named(name) orelse 0) -% window[0])))) / 8 + slide; + place.* = std.math.lerp(at_old, at_new, going); + } + for (travel, places[0..travel.len], 0..) |name, place, i| { + if (i == 1 and @abs(places[0] - place) < 0.05) continue; + if (place < -0.5 or place > @as(f32, @floatFromInt(slots)) - 0.5) continue; + const both = i == 0 and travel.len == 2 and @abs(places[1] - place) < 0.05; + u.pinRow(theme.metric.slot.lane, top + place * m.row, if (both) &.{ "rsp", "rbp" } else &.{name}, theme.color.region.stack); + } + // The backtrace, drawn on the words that are each frame: each span + // glides from the frame's old extent to its new one with the slide. var buf: [16]Frame = undefined; - const chain = frames(rec, if (landed) now.stops[0] else now.stops[1], &buf); - // Placed as the rows are: against rsp after the step, and slid. - const rsp = is.rsp; + var old_buf: [16]Frame = undefined; + const chain = frames(rec, now.stops[0], &buf); + const old_chain = frames(rec, now.stops[1], &old_buf); + // Placed as the rows are: against the window after the step, and slid. + const open_calls = rec.stack(u.f.scratch, if (landed) now.stops[0] else now.stops[1]); + const named = if (landed) chain else old_chain; + const rows_of = struct { + fn at(addr: u64, base: u64) f32 { + return @as(f32, @floatFromInt(@as(i64, @bitCast(addr -% base)))) / 8; + } + }.at; for (chain, 0..) |frame, i| { - const first = @as(f32, @floatFromInt(@as(i64, @bitCast(frame.lo -% rsp)))) / 8 + slide; + const old_frame = if (i < old_chain.len) old_chain[i] else frame; + const first = std.math.lerp(rows_of(old_frame.lo, window[0]), rows_of(frame.lo, window[0]), p) + slide; if (first >= @as(f32, @floatFromInt(slots))) break; - const last = if (frame.hi) |hi| @as(f32, @floatFromInt(@as(i64, @bitCast(hi -% rsp)))) / 8 + slide else std.math.inf(f32); + const last = if (frame.hi) |hi| std.math.lerp(if (old_frame.hi) |oh| rows_of(oh, window[0]) else rows_of(hi, window[0]), rows_of(hi, window[0]), p) + slide else std.math.inf(f32); + if (last < 0) continue; const open = last >= @as(f32, @floatFromInt(slots)); const y1 = top + (@min(last, @as(f32, @floatFromInt(slots)) - 1) + 1) * m.row; - rows.span(u, box.w, top + @max(first, 0) * m.row, y1, frameName(u, rec, frame.pc), i == 0, open); + rows.span(u, box.w, top + @max(first, 0) * m.row, y1, spanName(u, rec, open_calls, i, if (i < named.len) named[i].pc else frame.pc), i == 0, open); } veiled(u, box, now.veil); } + /// The first word a window of `slots` shows, `skip` steps back: rsp, + /// or within [rsp, rbp+16) (the frame, with its saved rbp and its way + /// back) so that the word the newest of the last three steps wrote or + /// read there is in the window's middle. + fn windowAt(now: cursors.Now, regs: zt.Regs, slots: usize, skip: usize) u64 { + const frame_end = regs.rbp +% 16; + if (frame_end <= regs.rsp or frame_end - regs.rsp > 8 * 64) return regs.rsp; + const words = (frame_end - regs.rsp) / 8; + if (words <= slots) return regs.rsp; + for (skip..skip + 3) |age| { + if (age + 1 >= now.stops.len) break; + for ([_][]const Recording.Span{ now.rec.written(now.stops[age + 1], now.stops[age]), now.rec.read(now.stops[age + 1], now.stops[age]) }) |spans| { + var k = spans.len; + while (k > 0) { + k -= 1; + const a = spans[k].addr; + if (a < regs.rsp or a >= frame_end) continue; + const word = (a - regs.rsp) / 8; + const first = @min(word -| (slots - 1) / 2, words - slots); + return regs.rsp + 8 * first; + } + } + } + return regs.rsp; + } + const Pins = struct { names: []const []const u8, shows: f32 }; /// The registers whose value is `addr`: before the step, and after it /// once their link has landed (`ties.pinShows`). - fn pins(u: ui.Ui, now: cursors.Now, is: zt.Regs, was: zt.Regs, addr: u64) Pins { + fn pins(u: ui.Ui, now: cursors.Now, is: zt.Regs, was: zt.Regs, addr: u64, apart: []const []const u8) Pins { var out: std.ArrayList([]const u8) = .empty; var shows: f32 = 0; for (theme.metric.all_registers[0..16]) |name| { + // Those drawn apart, travelling. + if (for (apart) |a| { + if (std.mem.eql(u8, a, name)) break true; + } else false) continue; const i = index(name).?; const before = was.named(name) == addr; const after = is.named(name) == addr; @@ -323,8 +464,10 @@ pub const Backtrace = struct { const y = body.y + m.pad + @as(f32, @floatFromInt(i)) * m.row; const name = ui.symbol(u, rec.strings.get(frame.pc) orelse u.print("{x}", .{frame.pc})); // The program's own frame says where in its source it is. - const where = if (i == 0) u.print("{s}:{d}", .{ rec.file, rec.own[now.marked()] }) else ""; - rows.callRow(u, y, box.w, i, name, where, i == 0); + const where = if (i == 0) u.print("{s}:{d}", .{ rec.file, rec.own[now.marked()] }) else if (rec.lineOf(frame.pc)) |l| u.print("{s}:{d}", .{ rec.file, l }) else ""; + const open = rec.stack(u.f.scratch, now.stop(.cpu)); + const args = if (i < open.len) @import("calls.zig").arguments(u, rec, open[open.len - 1 - i]) else ""; + rows.callRow(u, y, box.w, i, name, args, where, i == 0); } veiled(u, box, now.veil); } diff --git a/anim/src/cursor.zig b/anim/src/cursor.zig index 2f7be1a..6e3a5b7 100644 --- a/anim/src/cursor.zig +++ b/anim/src/cursor.zig @@ -109,6 +109,8 @@ pub const Cursor = struct { /// cannot be read at that pace is veiled. hurried: anim.Value, veil: anim.Value, + /// The veil over what a sprint also cannot show: the source and the band's view. + sprint_veil: anim.Value, /// Steps taken. count: anim.Value, /// The levels the scene shows: set before the first step. @@ -130,6 +132,7 @@ pub const Cursor = struct { .marks = .{ s.value(here), s.value(here) }, .hurried = s.value(0), .veil = s.value(0), + .sprint_veil = s.value(0), .count = s.value(0), .first = start, .last = start, @@ -202,8 +205,13 @@ pub const Cursor = struct { pub fn reading(c: Cursor, from: u64, to: u64) Plan { const rec = c.rec; const regs: f32 = @floatFromInt(@popCount(rec.registersChanged(from, to) & ~quiet)); - const wrote: f32 = @floatFromInt(rec.written(from, to).len); - const touched = wrote > 0 or rec.read(from, to).len > 0; + // Memory gives up its slot when nothing it touched is drawn. + var wrote_n: usize = 0; + for (rec.written(from, to)) |span| wrote_n += @intFromBool(rec.drawn(span, from, to)); + var read_n: usize = 0; + for (rec.read(from, to)) |span| read_n += @intFromBool(rec.drawn(span, from, to)); + const wrote: f32 = @floatFromInt(wrote_n); + const touched = wrote_n > 0 or read_n > 0; const deeper = rec.depths[to] > rec.depths[from]; const back = rec.depths[to] < rec.depths[from]; const levels = [3]bool{ @@ -221,8 +229,8 @@ pub const Cursor = struct { // A drawing made of the bytes reacts when the projection from // them arrives: its bracket and its line after their strike, and // for a write its own arm. - const projected = level == 2 and is and levels[1] and c.levels.idea == .data; - if (projected) slot += time.project.bracket + time.project.draw + @as(f32, if (wrote > 0) time.strike.arm else 0) else if (is) slot += time.cascade; + const projected = level == 2 and is and levels[1] and (c.levels.idea == .data or deeper); + if (projected) slot += time.project.bracket + @as(f32, if (c.levels.idea == .data) time.project.draw else time.project.far) + @as(f32, if (wrote > 0 and c.levels.idea == .data) time.strike.arm else 0) else if (is) slot += time.cascade; strikes.* = @max(slot, time.cascade); } // The writes of one step strike 6 f apart: the last is later. @@ -288,9 +296,10 @@ pub const Cursor = struct { const n: f32 = @floatFromInt(c.steps(by, here, until)); if (n == 0) return; // Anticipation: the veil and the counter come with the first shortened step. - const veiled = options.veil orelse (options.pace < time.run); + // What changes faster than it can be read is veiled at a run too. + const veiled = options.veil orelse true; const start = s.cursor; - s.play(.{ c.hurried.to(1), c.veil.to(if (veiled) 1 else 0) }, .{ .seconds = time.veil, .ease = anim.ease.linear }); + s.play(.{ c.hurried.to(1), c.veil.to(if (veiled) 1 else 0), c.sprint_veil.to(if (options.pace < time.run) 1 else 0) }, .{ .seconds = time.veil, .ease = anim.ease.linear }); s.cursor = start; var k: f32 = 0; while (here < until) : (k += 1) { @@ -306,7 +315,7 @@ pub const Cursor = struct { here = next; } if (!options.settle) return; - s.play(.{ c.hurried.to(0), c.veil.to(0) }, .{ .seconds = time.veil, .ease = anim.ease.linear }); + s.play(.{ c.hurried.to(0), c.veil.to(0), c.sprint_veil.to(0) }, .{ .seconds = time.veil, .ease = anim.ease.linear }); s.wait(time.beat); } @@ -337,6 +346,7 @@ pub const Cursor = struct { .marks = .{ whole(rec, placed.value(c.marks[0])), whole(rec, placed.value(c.marks[1])) }, .hurried = placed.value(c.hurried), .veil = placed.value(c.veil), + .sprint_veil = placed.value(c.sprint_veil), .count = @intFromFloat(@max(placed.value(c.count), 0)), .of = c.of, .place = 0, @@ -385,6 +395,7 @@ pub const Now = struct { /// 0 to 1: steps are hurried; what cannot be read is veiled. hurried: f32, veil: f32, + sprint_veil: f32 = 0, /// Steps taken, of how many in the scene (0: not told). count: u32, of: u32, diff --git a/anim/src/disasm.zig b/anim/src/disasm.zig index e429643..efdb80e 100644 --- a/anim/src/disasm.zig +++ b/anim/src/disasm.zig @@ -109,10 +109,12 @@ pub const Disasm = struct { // Which moment the current mark stands for, and the three steps before it. const base: usize = if (going >= 0.5) 0 else 1; const current_line = rec.own[now.marks[if (going >= 0.5) 1 else 0]]; + // The addresses' shared digits, of the window the mark is in: they + // change with the advance, not before it. const lead = blk: { var addrs: [24]u64 = undefined; var n: usize = 0; - for (shown.rows) |row| if (!row.outside and n < addrs.len) { + for ((if (going >= 0.5) to else from).rows) |row| if (!row.outside and n < addrs.len) { addrs[n] = row.addr; n += 1; }; @@ -129,45 +131,66 @@ pub const Disasm = struct { ties.anchor(u, .pc, .{ .x = 0, .y = mark_y, .w = theme.metric.plaque.pc, .h = m.row }); } + // `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 }; + } + } + // The jump that brought control here: the instruction just before + // the pc's moment, a jump taken to it. + const jumped: ?u64 = blk: { + const at = now.stops[base]; + if (at == 0 or at <= now.stops[base + 1]) break :blk null; + const b = rec.insn_branches[at - 1] orelse break :blk null; + if (b.kind != .jump or !b.taken or b.to != rec.register(at, "rip")) break :blk null; + break :blk rec.register(at - 1, "rip"); + }; + var last_line: ?u32 = null; - var run: usize = 0; - var run_start: ?f32 = null; + // The thread's runs: of the line the mark leaves and of the one it + // goes to, each a span of rows; published sliding from the one to + // the other with the advance (`threadRuns`). + var runs: [2]Runs = .{ .{}, .{} }; + const lines_of = [2]u32{ rec.own[now.marks[0]], rec.own[now.marks[1]] }; var lanes: [2]?f32 = .{ null, null }; + // A call's arguments hang in the annotation column of the rows under it. + var covered: usize = 0; for (merged, 0..) |row, j| { const y = top + (@as(f32, @floatFromInt(j)) - scroll) * m.row; const line = if (row.outside) null else row.line; // The thread: the current line's runs of instructions. - const on_line = line != null and line.? == current_line and mark_shows >= 1; - if (on_line and run_start == null) run_start = @max(y, top); - if (!on_line and run_start != null) { - ties.anchor(u, .{ .run = run }, .{ .x = 0, .y = run_start.?, .w = box.w, .h = @min(y, box.h - m.pad) - run_start.? }); - run += 1; - run_start = null; - } + for (&runs, lines_of) |*r, of| r.add(line != null and line.? == of and mark_shows >= 1, @max(y, top), @min(y, box.h - m.pad)); + // A row wholly above the body (the window it scrolls from or to) + // does not take the line number from the first row shown. + const above_body = y + m.row <= top + 0.5; if (y + m.row < m.tag or y > box.h) { - last_line = line; + last_line = if (above_body) null else line; + covered -|= 1; continue; } - // `ran`: it ran in one of the last three steps. - var ran: ?usize = null; - for (0..3) |k| { - const at_k = now.stops[@min(base + 1 + k, now.stops.len - 1)]; - if (at_k != now.stops[base] and rec.register(at_k, "rip") == row.addr) { - ran = k; - break; - } - } const is_pc = row.addr == pc[if (going >= 0.5) 1 else 0]; - if (ran != null and !is_pc) lit.trail(c.mark, y, ran.?); - d.insn(lit, now, row, y, box.w, line, line != last_line, current_line, lead, if (is_pc) .current else if (ran) |k| .{ .ran = k } else .ahead, base); - last_line = line; - // The jump that brought control here: from its row, up or down the lane. - if (ran == 0 and !is_pc) if (rec.insn_branches[now.stops[base + 1]]) |b| if (b.kind == .jump and b.taken) { - lanes[0] = y; - }; + const was = if (is_pc) null else ran[j]; + if (was) |r| lit.trail(c.mark, y, r.k); + const hangs = d.insn(lit, now, row, y, box.w, line, line != last_line, current_line, lead, if (is_pc) .current else if (was) |r| .{ .ran = r } else .ahead, base, covered > 0); + covered = @max(covered -| 1, hangs); + last_line = if (above_body) null else line; + if (jumped == row.addr and !is_pc) lanes[0] = y; if (is_pc) lanes[1] = y; } - if (run_start) |y0| ties.anchor(u, .{ .run = run }, .{ .x = 0, .y = y0, .w = box.w, .h = @min(top + (@as(f32, @floatFromInt(merged.len)) - scroll) * m.row, box.h - m.pad) - y0 }); + const end_y = @min(top + (@as(f32, @floatFromInt(merged.len)) - scroll) * m.row, box.h - m.pad); + for (&runs) |*r| r.add(false, end_y, end_y); + threadRuns(u, box.w, runs, if (lines_of[0] == lines_of[1]) 1 else cursors.standard(going)); if (lanes[0] != null and lanes[1] != null and lanes[0].? != lanes[1].?) { const ya = lanes[0].? + m.row / 2; const yb = lanes[1].? + m.row / 2; @@ -176,23 +199,32 @@ pub const Disasm = struct { context.veiled(u, box, now.veil); } - const State = union(enum) { current, ran: usize, ahead }; + const State = union(enum) { current, ran: Ran, ahead }; + /// A row that ran `k` steps ago (0 newest), last at moment `at`. + const Ran = struct { k: usize, at: u64 }; - /// `insn`: an instruction and its annotation, pwndbg's way. - fn insn(d: *const Disasm, u: ui.Ui, now: cursors.Now, row: Insn, y: f32, w: f32, line: ?u32, first_of_line: bool, current_line: u32, lead: usize, state: State, base: usize) void { + /// `insn`: an instruction and its annotation, pwndbg's way. Nothing is + /// cut that has room: the operands run on to where the annotation must + /// begin to fit (never left of its column), and are cut only there, + /// where the annotation carries the address they name. `covered`: a + /// call's arguments above hang in this row's annotation column. Returns + /// how many rows under it its own arguments hang in. + fn insn(d: *const Disasm, u: ui.Ui, now: cursors.Now, row: Insn, y: f32, w: f32, line: ?u32, first_of_line: bool, current_line: u32, lead: usize, state: State, base: usize, covered: bool) usize { const rec = d.cursor.rec; const base_y = rows.baseline(y); const code_ink = theme.color.region.code_; + const room = w - m.side; if (row.outside) { // The function ends: a rule, and the next one's name. u.fill(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = theme.stroke.rule }, theme.color.rule); _ = u.address(c.address, base_y, row.addr, .{ .ink = ui.mix(code_ink, theme.color.page, theme.metric.context.lead_alpha) }); u.text(.mono, size, c.mnemonic, base_y, row.mnemonic(), t.faint); - u.text(.mono, size, c.operands, base_y, clipText(u, row.operands(), c.operand_chars), t.faint); - if (rec.strings.get(row.addr)) |name| u.text(.mono, size, c.annotation, base_y, name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len], t.faint); - return; + const name = if (rec.strings.get(row.addr)) |n| n[0 .. std.mem.lastIndexOfScalar(u8, n, '+') orelse n.len] else ""; + const x = if (name.len > 0) annotationX(operandsWidth(row, row.operands()), room, @as(f32, @floatFromInt(name.len)) * adv) else room + gap; + u.text(.mono, size, c.operands, base_y, rows.fitted(u, row.operands(), (if (covered) c.annotation else x) - gap - c.operands), t.faint); + u.text(.mono, size, x, base_y, name, t.faint); + return 0; } - const on = state == .current; _ = u.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(code_ink), .lead = lead }); if (first_of_line) if (line) |l| { const num = u.print("{d}", .{l}); @@ -200,31 +232,58 @@ pub const Disasm = struct { u.text(if (now_line) .mono_bold else .mono, size, c.line + 3 * adv - @as(f32, @floatFromInt(num.len)) * adv, base_y, num, if (now_line) theme.mark(.current).solid else t.faint); }; u.text(.mono_bold, size, c.mnemonic, base_y, row.mnemonic(), theme.color.code.keyword); - operands(u, row, base_y); + // How wide the annotation is, drawn where nothing shows; then where it goes. + const need = d.annotation(u.faded(0), now, row, y, c.annotation, std.math.inf(f32), state, base); + // When the operands and the annotation do not both fit: the + // annotation moves left (never past its column), then a size word + // a register already gives goes, then the operands give way. + var ops = row.operands(); + var x = room + gap; + if (need.drawn) { + const wide = need.end - c.annotation; + x = annotationX(operandsWidth(row, ops), room, wide); + if (c.operands + operandsWidth(row, ops) + gap > x) if (lean(u, row)) |shorter| { + ops = shorter; + x = annotationX(operandsWidth(row, ops), room, wide); + }; + } + operands(u, row, ops, base_y, (if (covered) @min(x, c.annotation) else x) - gap - c.operands); + return if (need.drawn) d.annotation(u, now, row, y, x, room, state, base).hangs else 0; + } + + const Note = struct { drawn: bool = false, end: f32 = 0, hangs: usize = 0 }; - // The annotation: what it does, now. What it left behind is shown - // only where the step ran this instruction alone: a step by line - // runs others after it, and the state after them is not its doing. + /// The annotation: what it does, now, from `x`, cut where `room` ends. + /// What it left behind is shown only where the step ran this + /// instruction alone: a step by line runs others after it, and the + /// state after them is not its doing. + fn annotation(d: *const Disasm, u: ui.Ui, now: cursors.Now, row: Insn, y: f32, x: f32, room: f32, state: State, base: usize) Note { + const rec = d.cursor.rec; + const base_y = rows.baseline(y); + const code_ink = theme.color.region.code_; const moment, var after = switch (state) { - .current => .{ now.stops[base], if (base == 1) now.stops[0] else null }, - .ran => |k| .{ now.stops[base + 1 + k], now.stops[base + k] }, + // The moment the mark stands for (at a sprint it waits at a + // phrase's end while the steps go on): the pc's row is its. + .current => blk: { + const marked = now.marks[if (base == 0) 1 else 0]; + break :blk .{ marked, if (base == 1 and marked == now.stops[1]) now.stops[0] else null }; + }, + .ran => |r| .{ r.at, r.at + 1 }, .ahead => .{ now.stops[base], null }, }; if (after) |a| if (!alone(rec, moment, a, row)) { after = null; }; - const room = w - m.side; - const x: f32 = c.annotation; const branch = if (state == .ahead) null else rec.insn_branches[moment]; const touches = if (state == .ahead) [2]?Recording.Touch{ null, null } else rec.insn_touches[moment]; - _ = on; if (branch) |b| switch (b.kind) { .call => { const callee = rec.strings.get(b.to) orelse ""; - u.text(.mono, size, x, base_y, callee[0 .. std.mem.lastIndexOfScalar(u8, callee, '+') orelse callee.len], t.bright); + const callee_name = callee[0 .. std.mem.lastIndexOfScalar(u8, callee, '+') orelse callee.len]; + u.text(.mono, size, x, base_y, callee_name, t.bright); + var note: Note = .{ .drawn = true, .end = x + @as(f32, @floatFromInt(callee_name.len)) * adv }; // Its arguments hang under it, a small `reg` a row, as many as the prototype has. if (state == .current) { - const callee_name = callee[0 .. std.mem.lastIndexOfScalar(u8, callee, '+') orelse callee.len]; // As many as the callee's prototype has (the debug info's, else the source's), three when neither says. const count: usize = row.params orelse for (rec.functions) |fun| { if (std.mem.eql(u8, fun.name, callee_name)) break fun.params; @@ -236,34 +295,41 @@ pub const Disasm = struct { u.text(.mono, size, x, rows.baseline(ry), reg, t.dim); _ = rows.chain(u, x + 4 * adv, ry, shown_moment, rec.register(moment, reg), room, .{}); } + note.hangs = @min(count, 6); } - return; + return note; }, .ret => { u.text(.mono, size, x, base_y, "\u{2192}", t.faint); - _ = u.address(x + 2 * adv, base_y, b.to, .{ .ink = ui.rgb(code_ink), .name = rec.strings.get(b.to) orelse "" }); - return; + return .{ .drawn = true, .end = u.address(x + 2 * adv, base_y, b.to, .{ .ink = ui.rgb(code_ink), .name = rec.strings.get(b.to) orelse "" }) }; }, .jump => { // A jump always taken says nothing; a conditional one, which way. - if (std.mem.eql(u8, row.mnemonic(), "jmp")) return; - if (!b.taken) return u.text(.mono, size, x, base_y, "not taken", t.dim); - u.text(.mono, size, x, base_y, "taken", t.primary); - return; + if (std.mem.eql(u8, row.mnemonic(), "jmp")) return .{}; + const said = if (b.taken) "taken" else "not taken"; + u.text(.mono, size, x, base_y, said, if (b.taken) t.primary else t.dim); + return .{ .drawn = true, .end = x + @as(f32, @floatFromInt(said.len)) * adv }; }, .none => {}, }; if (std.mem.eql(u8, row.mnemonic(), "syscall") and state != .ahead) { const nr = rec.register(moment, "rax"); - u.text(.mono, size, x, base_y, zt.syscalls.name(nr) orelse "syscall", t.bright); + const name = zt.syscalls.name(nr) orelse "syscall"; + u.text(.mono, size, x, base_y, name, t.bright); const names = zt.syscalls.names(nr); const carriers = [_][]const u8{ "rdi", "rsi", "rdx" }; - if (state == .current) for (names[0..@min(names.len, 3)], carriers[0..@min(names.len, 3)], 1..) |arg, reg, k| { + const n = @min(names.len, 3); + if (state == .current) for (names[0..n], carriers[0..n], 1..) |arg, reg, k| { const ry = y + @as(f32, @floatFromInt(k)) * m.row; u.text(.mono, size, x, rows.baseline(ry), arg, t.dim); - _ = rows.chain(u, x + @as(f32, @floatFromInt(arg.len + 1)) * adv, ry, rec.moment(moment), rec.register(moment, reg), room, .{}); + const ax = x + @as(f32, @floatFromInt(arg.len + 1)) * adv; + const value = rec.register(moment, reg); + // A descriptor is the `value` class `fd`: what it is open on. + if (std.mem.endsWith(u8, arg, "fd")) { + _ = u.typed(ax, rows.baseline(ry), value, .{ .fd = rec.openOn(u.f.scratch, value, moment) }, .{}); + } else _ = rows.chain(u, ax, ry, rec.moment(moment), value, room, .{}); }; - return; + return .{ .drawn = true, .end = x + @as(f32, @floatFromInt(name.len)) * adv, .hangs = if (state == .current) n else 0 }; } // Memory: a chain from the address it computes. Before the step, // where it will look; in the step its first hop is read (with the @@ -287,22 +353,79 @@ pub const Disasm = struct { marks.changed_heat = now.written(touch.addr, touch.len, .memory, 0); } }; - _ = rows.chain(u, x, y, shown, touch.addr, room, marks); - return; + return .{ .drawn = true, .end = rows.chain(u, x, y, shown, touch.addr, room, marks).end }; } // Only a register: a small `reg` of what it left there. - const reg = written(row) orelse return; + const reg = written(row) orelse return .{}; const value_at = switch (state) { - .ran => after orelse return, - .current => if (after != null and now.landed(.cpu, 0)) after.? else return, - .ahead => return, + .ran => after orelse return .{}, + .current => if (after != null and now.landed(.cpu, 0)) after.? else return .{}, + .ahead => return .{}, }; const value = rec.register(value_at, reg); u.text(.mono, size, x, base_y, reg, t.dim); - _ = rows.chain(u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, rec.moment(value_at), value, room, .{}); + return .{ .drawn = true, .end = rows.chain(u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, rec.moment(value_at), value, room, .{}).end }; } }; +/// The gap between the operands and the annotation: a character. +const gap = adv; + +/// The runs of rows of one line, top and bottom of each, as the rows go by. +const Runs = struct { + spans: [8][2]f32 = undefined, + n: usize = 0, + open: ?f32 = null, + + fn add(r: *Runs, on: bool, y: f32, end: f32) void { + if (on and r.open == null) r.open = y; + if (!on) if (r.open) |y0| { + if (r.n < r.spans.len and end > y0) { + r.spans[r.n] = .{ y0, end }; + r.n += 1; + } + r.open = null; + }; + } +}; + +/// The thread's runs, `p` of the way from the line the mark leaves to the +/// one it goes to: each slides to its partner (by order, the last of the +/// fewer standing in for the rest), as the source's bracket slides. +fn threadRuns(u: ui.Ui, w: f32, runs: [2]Runs, p: f32) void { + const from = runs[0]; + const to = runs[1]; + if (to.n == 0 or p >= 1 or from.n == 0) { + const shown = if (p >= 0.5 or from.n == 0) to else from; + for (shown.spans[0..shown.n], 0..) |span, k| ties.anchor(u, .{ .run = k }, .{ .x = 0, .y = span[0], .w = w, .h = span[1] - span[0] }); + return; + } + for (0..@max(from.n, to.n)) |k| { + const a = from.spans[@min(k, from.n - 1)]; + const b = to.spans[@min(k, to.n - 1)]; + const y0 = std.math.lerp(a[0], b[0], p); + ties.anchor(u, .{ .run = k }, .{ .x = 0, .y = y0, .w = w, .h = std.math.lerp(a[1], b[1], p) - y0 }); + } +} + +/// Where an annotation `need` wide goes in a row that ends at `room`, +/// after operands `width` wide: at its column, or a character after the +/// operands, or (when both do not fit) where it just fits. +fn annotationX(width: f32, room: f32, need: f32) f32 { + return @max(c.annotation, @min(c.operands + width + gap, room - need)); +} + +/// The row in `rows` (in address order) of the instruction at `addr`. +fn rowOf(list: []const Insn, addr: u64) ?usize { + var lo: usize = 0; + var hi: usize = list.len; + while (lo < hi) { + const mid = (lo + hi) / 2; + if (list[mid].addr < addr) lo = mid + 1 else hi = mid; + } + return if (lo < list.len and list[lo].addr == addr) lo else null; +} + /// Whether the step from moment `i` to `after` ran the instruction `row` /// alone: the moment after it is at the next instruction, or where it jumped. fn alone(rec: *const Recording, i: u64, after: u64, row: Insn) bool { @@ -313,25 +436,54 @@ fn alone(rec: *const Recording, i: u64, after: u64, row: Insn) bool { return false; } -/// `text` in `chars` characters: cut at its far end, and saying so. -fn clipText(u: ui.Ui, text: []const u8, chars: usize) []const u8 { - if (text.len <= chars) return text; - return u.print("{s}\u{2026}", .{text[0 .. chars - 1]}); +/// A jump's or a call's target, when the disassembler wrote it as one. +fn target(row: Insn) ?u64 { + const ops = row.operands(); + const mn = row.mnemonic(); + if (!(mn[0] == 'j' or std.mem.eql(u8, mn, "call")) or !std.mem.startsWith(u8, ops, "0x")) return null; + return std.fmt.parseInt(u64, ops[2..], 16) catch null; } -/// The operands, as the disassembler writes them, 24 characters; a jump's -/// or a call's target is an `address` in code's ink. -fn operands(u: ui.Ui, row: Insn, base_y: f32) void { - const ops = row.operands(); +/// How wide operands `ops` of `row` are, whole. +fn operandsWidth(row: Insn, ops: []const u8) f32 { + if (target(row)) |to| return @as(f32, @floatFromInt(ui.digits(to))) * adv; + return @as(f32, @floatFromInt(ops.len)) * adv; +} + +/// The operands without the size word of a memory operand whose size a +/// register operand gives (`mov rax, [rbp - 0x28]`): nothing is lost. +/// Null where there is none to drop. +fn lean(u: ui.Ui, row: Insn) ?[]const u8 { const mn = row.mnemonic(); - const branches = mn[0] == 'j' or std.mem.eql(u8, mn, "call"); - if (branches and std.mem.startsWith(u8, ops, "0x")) { - if (std.fmt.parseInt(u64, ops[2..], 16)) |target| { - _ = u.address(c.operands, base_y, target, .{ .ink = ui.rgb(theme.color.region.code_) }); - return; - } else |_| {} + // These widen or convert: the register does not give the memory's size. + for ([_][]const u8{ "movzx", "movsx", "movsxd", "cvt" }) |w| if (std.mem.startsWith(u8, mn, w)) return null; + const ops = row.operands(); + const ptr = std.mem.indexOf(u8, ops, " ptr ") orelse return null; + var word = ptr; + while (word > 0 and ops[word - 1] != ' ' and ops[word - 1] != ',') word -= 1; + const comma = std.mem.indexOfScalar(u8, ops, ',') orelse return null; + const other = std.mem.trim(u8, if (comma < word) ops[0..comma] else ops[comma + 1 ..], " "); + if (full(other) == null) return null; + return u.print("{s}{s}", .{ ops[0..word], ops[ptr + 5 ..] }); +} + +/// The operands `ops`, in `width` units; a jump's or a call's target is +/// an `address` in code's ink. Cut only at their far end, saying so, and +/// never inside `[]`: a cut that would fall there falls before the `[`. +fn operands(u: ui.Ui, row: Insn, ops: []const u8, base_y: f32, width: f32) void { + if (target(row)) |to| { + _ = u.address(c.operands, base_y, to, .{ .ink = ui.rgb(theme.color.region.code_) }); + return; + } + const chars: usize = @intFromFloat(@max(width / adv, 1)); + if (ops.len <= chars) return u.text(.mono, size, c.operands, base_y, ops, theme.color.code.plain); + var cut = chars - 1; + if (std.mem.lastIndexOfScalar(u8, ops[0..cut], '[')) |open| { + if (std.mem.indexOfScalarPos(u8, ops, open, ']') orelse ops.len >= cut) cut = open; } - u.text(.mono, size, c.operands, base_y, clipText(u, ops, c.operand_chars), theme.color.code.plain); + while (cut > 0 and ops[cut - 1] == ' ') cut -= 1; + u.text(.mono, size, c.operands, base_y, ops[0..cut], theme.color.code.plain); + u.text(.mono, size, c.operands + @as(f32, @floatFromInt(cut)) * adv, base_y, "\u{2026}", t.faint); } /// The register an instruction leaves a value in, if that is all it does diff --git a/anim/src/hexdump.zig b/anim/src/hexdump.zig index 165f241..bd76150 100644 --- a/anim/src/hexdump.zig +++ b/anim/src/hexdump.zig @@ -64,9 +64,36 @@ pub const Of = struct { region: u24 = theme.color.region.heap, }; -/// The dump: `count` rows from `first`, at `x` (its panel's left edge -/// is the band's middle), the rows from `y`. The rows of what the drawing -/// draws have quiet brackets. +/// The band's view of bytes: its own panel over the state column, the +/// tag `its bytes` with the range shown (`about`) and the legend of runs. +/// Returns its `Ui` (the panel's origin) and how many rows it holds. +pub fn panel(f: *@import("sketch").Frame, placed: @import("anim").Placed, stage: *const @import("stage.zig").Stage, about: []const u8, legend: []const ui.Legend) View { + const box = stage.box(placed, .view); + const u = @import("context.zig").at(f, placed, box).faded(placed.value(stage.view)); + if (box.h < m.tag + m.row) return .{ .u = u, .rows = 0, .box = box }; + // Its own box, as it moves; the drawing's panel clips itself again after. + u.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }); + _ = u.panel(box.w, box.h, "its bytes", .{ .legend = legend }); + const tag = theme.size.sans.tag; + u.text(.sans, theme.size.sans.micro, 28 + u.width(.sans_medium, tag, "its bytes") + 12, m.tag - 6, about, t.faint); + return .{ .u = u, .rows = theme.layout.rowsIn(box.h), .box = box }; +} + +/// The view's panel as drawn: its `Ui`, how many rows it holds, its box. +pub const View = struct { + u: ui.Ui, + rows: usize, + box: Rect, + + /// What a sprint cannot show: veiled, over its rows. + pub fn veil(v: View, now: cursors.Now) void { + @import("context.zig").veiled(v.u, v.box, now.sprint_veil); + } +}; + +/// The dump: `count` rows from `first`, at `x` in `u` (the view's +/// panel), the rows from `y`. The rows of what the drawing draws have +/// quiet brackets. pub fn draw(u: ui.Ui, now: cursors.Now, x: f32, y: f32, first: u64, count: usize, of: Of) void { const v = u.moved(x, 0); const moment = now.shown(.memory); diff --git a/anim/src/nodes.zig b/anim/src/nodes.zig index e6ba663..1f8acec 100644 --- a/anim/src/nodes.zig +++ b/anim/src/nodes.zig @@ -44,7 +44,11 @@ pub const Nodes = struct { pub fn draw(g: *const Nodes, f: *sk.Frame, placed: anim.Placed) void { const box = g.stage.box(placed, .band); if (box.h < m.tag + m.row) return; - const u = context.at(f, placed, box); + const u = context.at(f, placed, box).faded(placed.value(g.stage.drawing)); + // A relayout moves the band: what is drawn in it stays inside it + // (its view, drawn below, clips itself and hands the clip back). + u.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }); + defer u.unclip(); const now = g.cursor.now(placed); const rec = g.cursor.rec; const heap = theme.color.region.heap; @@ -54,27 +58,26 @@ pub const Nodes = struct { .{ .text = "malloc's", .ink = ui.rgb(t.dim) }, .{ .text = "never read", .ink = ui.rgb(t.faint) }, }; - _ = u.panel(box.w, box.h, g.title, .{ .focus = g.focus, .legend = &legend }); - const half = theme.layout.state.x - theme.layout.program.x; + _ = u.panel(box.w, box.h, g.title, .{ .focus = g.focus }); const moment = now.shown(.idea); const things = objects.reach(f.scratch, rec, moment, null); const before = objects.reach(f.scratch, rec, now.before(), null); - // The dump: the heap the nodes are in, from the first one's chunk to the last's. + // Its view: the heap the nodes are in, from the first one's chunk to the last's. var lo: u64 = std.math.maxInt(u64); var hi: u64 = 0; for (rec.allocations) |a| if (things.len > 0 and a.size == things[0].type.record.size) { lo = @min(lo, (a.ptr - 16) & ~@as(u64, 15)); hi = @max(hi, (a.ptr + a.size + 15) & ~@as(u64, 15)); }; - const count = theme.layout.rowsIn(box.h); if (lo < hi) { + const count = theme.layout.rowsIn(g.stage.box(placed, .view).h); const first = hexdump.window(now, lo, hi, count); const shown = @min(count, (hi - first) / 16); - const base = theme.size.sans.tag; - u.text(.sans_medium, base, half + 12, m.tag - 6, "its bytes", t.primary); - u.text(.sans, theme.size.sans.micro, half + 12 + u.width(.sans_medium, base, "its bytes") + 12, m.tag - 6, u.print("the heap, {x} to {x}", .{ first, first + 16 * shown - 1 }), t.faint); - hexdump.draw(u, now, half, m.tag + m.pad, first, shown, .{ .things = things }); + 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 }); + v.veil(now); + u.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }); } if (things.len == 0) { const root = rec.variable(f.scratch, moment, g.root); @@ -93,8 +96,8 @@ pub const Nodes = struct { for (rec.allocations) |a| slots += @intFromBool(a.size == things[0].type.record.size); slots = @max(slots, 1); const n: f32 = @floatFromInt(slots); - const x0 = (half - 32 - n * size[0] - (n - 1) * size[2]) / 2; - const ly = m.tag + @as(f32, if (subject) 44 else 16); + const x0 = (box.w - n * size[0] - (n - 1) * size[2]) / 2; + const ly = m.tag + @as(f32, if (subject) 72 else 16); const ny = ly + label * 1.2 + 4; const places = f.scratch.alloc(Rect, things.len) catch return; for (things, places, 0..) |o, *place, i| { @@ -102,19 +105,39 @@ pub const Nodes = struct { ties.anchor(u, .{ .node = o.addr }, place.*); } + // Each node as much as it has risen from its bytes (`establish`): by address. + const rising = placed.value(g.stage.rise); + const shows = f.scratch.alloc(f32, things.len) catch return; + const belows = f.scratch.alloc(f32, things.len) catch return; + for (things, shows, belows) |o, *show, *below| { + var k: usize = 0; + for (things) |other| k += @intFromBool(other.addr < o.addr); + const r = ties.rise(rising, k, things.len); + show.* = r.element; + below.* = r.below; + } + // Arrows first, under the nodes' edges. const since = now.since(.idea, 0); - for (things, places) |o, place| for (o.type.record.fields) |field| { + const whole = u; + for (things, places, shows) |o, place, show| for (o.type.record.fields) |field| { if (field.type != .pointer) continue; const from_addr = o.addr + field.offset; const start = ui.Vec{ place.x + place.w - theme.metric.node.pointer_w / 2 + 6, place.y + place.h / 2 }; const new = if (Recording.word(now.moment(), from_addr, 8) catch null) |target| placeOf(things, places, target) else null; const old = if (Recording.word(now.before(), from_addr, 8) catch null) |target| placeOf(things, places, target) else null; + // An arrow is there once both its ends are. + var reach = show; + if (Recording.word(now.moment(), from_addr, 8) catch null) |target| for (things, shows) |other, other_show| { + if (other.addr == target) reach = @min(reach, other_show); + }; + if (reach <= 0) continue; + const v = if (reach < 1) whole.faded(reach) else whole; const fresh = now.writeAge(from_addr, 8) == 0; const ink = ui.rgb(heap); const head = theme.metric.node.arrow_head; if (!fresh or !now.walking()) { - if (if (now.landed(.idea, 0)) new else old) |to| u.route(route(u, start, place, to), ink, .{ .width = theme.stroke.line, .head = head, .progress = if (fresh) cursors.standard(now.moving(.idea, 0, time.redirect.head)) else 1 }); + if (if (now.landed(.idea, 0)) new else old) |to| v.route(route(v, start, place, to), ink, .{ .width = theme.stroke.line, .head = head, .progress = if (fresh) cursors.standard(now.moving(.idea, 0, time.redirect.head)) else 1 }); continue; } // A pointer rewritten. Anticipation: as its half is armed the @@ -123,24 +146,25 @@ pub const Nodes = struct { // answers with a bright frame. The old one lingers, then goes. const armed = since >= -time.strike.arm; if (old) |to| { - const ghost = if (armed) u.faded(1 - std.math.clamp((since - time.redirect.ghost_hold) / time.redirect.ghost_out, 0, 1)) else u; - ghost.route(route(u, start, place, to), if (armed) ui.rgb(t.faint) else ink, .{ .dashed = armed, .head = if (armed) null else head, .width = if (armed) theme.stroke.rule else theme.stroke.line }); + const ghost = if (armed) v.faded(1 - std.math.clamp((since - time.redirect.ghost_hold) / time.redirect.ghost_out, 0, 1)) else v; + ghost.route(route(v, start, place, to), if (armed) ui.rgb(t.faint) else ink, .{ .dashed = armed, .head = if (armed) null else head, .width = if (armed) theme.stroke.rule else theme.stroke.line }); } if (new) |to| { - u.route(route(u, start, place, to), ink, .{ .width = theme.stroke.line, .head = head, .progress = cursors.standard(std.math.clamp((since - time.snap) / time.redirect.head, 0, 1)) }); + v.route(route(v, start, place, to), ink, .{ .width = theme.stroke.line, .head = head, .progress = cursors.standard(std.math.clamp((since - time.snap) / time.redirect.head, 0, 1)) }); const landed = since - time.snap - time.redirect.head; const out = 4; - if (landed >= 0 and landed < time.redirect.landing) u.faded(1 - landed / time.redirect.landing).frame(.{ .x = to.x - out, .y = to.y - out, .w = to.w + 2 * out, .h = to.h + 2 * out }, theme.mark(.attention).solid, theme.stroke.rule); + if (landed >= 0 and landed < time.redirect.landing) v.faded(1 - landed / time.redirect.landing).frame(.{ .x = to.x - out, .y = to.y - out, .w = to.w + 2 * out, .h = to.h + 2 * out }, theme.mark(.attention).solid, theme.stroke.rule); } }; - for (things, places) |o, place| { + for (things, places, shows, belows) |o, place, show, below| { const new = for (before) |was| { if (was.addr == o.addr) break false; } else true; // What begins fades in; it does not pop. - g.node(if (new) u.faded(now.moving(.idea, 0, time.quick)) else u, now, o, place, label, value_size); + if (show > 0) g.node(u.faded(show * (if (new) now.moving(.idea, 0, time.quick) else 1)).moved(0, below), now, o, place, label, value_size); } + g.tags(u, now, things, places, label); } fn node(g: *const Nodes, u: ui.Ui, now: cursors.Now, o: objects.Object, r: Rect, label: f32, value_size: f32) void { @@ -172,7 +196,7 @@ pub const Nodes = struct { if (Recording.word(moment, at, bytes) catch null) |n| { const shift: u6 = @intCast(64 - 8 * bytes); const signed = @as(i64, @bitCast(n << shift)) >> shift; - u.label(ink.face, value_size, value, .center, u.print("{d}", .{signed}), if (o.freed) ui.rgb(t.faint) else ink.ink); + u.label(ink.face, value_size, value, .center, objects.reading(u.f.scratch, signed, field.type), if (o.freed) ui.rgb(t.faint) else ink.ink); } else u.unknown(value); } // The first pointer field: the square its arrow leaves from, or a slash for null. @@ -195,26 +219,85 @@ pub const Nodes = struct { const names = g.pins(u, now, o.addr); const cx = r.x + r.w / 2; ties.anchor(u, .{ .node_pin = o.addr }, .{ .x = cx - 1, .y = r.y + r.h, .w = 2, .h = label + 10 }); - if (names.names.len > 0 and names.shows > 0) u.faded(names.shows).pinUnder(cx, r.y + r.h, names.names, heap, label); + if (names.names.len > 0 and names.shows > 0) u.faded(names.shows).pinUnderInked(cx, r.y + r.h, names.names, names.inks, heap, label); } - const Pins = struct { names: []const []const u8, shows: f32 }; + /// Where variable `name`'s tag is: it travels from node to node in the + /// drawing's slot, after its word has been struck (`glide`, 30 f to the + /// next node, 36 f further); it does not jump. + fn tagOf(g: *const Nodes, u: ui.Ui, now: cursors.Now, name: []const u8) Tag { + const rec = g.cursor.rec; + const at = struct { + fn value(r: *Recording, scratch: std.mem.Allocator, then: Recording.Moment, n: []const u8) u64 { + const v = r.variable(scratch, then, n) orelse return 0; + if (!r.assigned(v, then.index)) return 0; + return (Recording.word(then, v.addr, 8) catch null) orelse 0; + } + }; + const to = at.value(rec, u.f.scratch, now.moment(), name); + const from = at.value(rec, u.f.scratch, now.before(), name); + if (from == to or now.resting()) return .{ .from = from, .to = to, .p = 1 }; + const far: f32 = if (from != 0 and to != 0 and @abs(@as(i64, @bitCast(to -% from))) > 0x30) time.flight.mid else time.flight.near; + const p = switch (now.plan.gait) { + .walk => std.math.clamp(now.since(.idea, 0) / far, 0, 1), + .run => now.moving(.idea, 0, time.run_ease), + .sprint => 1, + }; + return .{ .from = from, .to = to, .p = p }; + } + + /// The tags on their way: from node to node along the band's bottom, + /// or arriving where there was none (fading in, rising 8), or leaving + /// for none (fading out). + fn tags(g: *const Nodes, u: ui.Ui, now: cursors.Now, things: []const objects.Object, places: []const Rect, label: f32) void { + const heap = theme.color.region.heap; + for (g.track) |name| { + const tag = g.tagOf(u, now, name); + if (!tag.moving() or tag.p <= 0) continue; + const a = placeOf(things, places, tag.from); + const b = placeOf(things, places, tag.to); + // It keeps the side it had where it leaves; one that comes to + // names already there goes on the stub's right. + const was_regs = (now.before().regs(g.cursor.rec.tid) catch null) orelse zt.Regs{}; + const left_from = g.namesBefore(u, now, tag.from, was_regs); + const was_right = left_from.len >= 2 and !std.mem.eql(u8, left_from[0], name); + const crowded = was_right or (a == null and g.pins(u, now, tag.to).names.len > 0); + const names: []const []const u8 = if (crowded) &.{ "", name } else &.{name}; + const ink = g.home(u, now, name); + const inks: []const u24 = if (crowded) &.{ t.primary, ink } else &.{ink}; + if (a != null and b != null) { + const x = std.math.lerp(a.?.x + a.?.w / 2, b.?.x + b.?.w / 2, cursors.glide(tag.p)); + u.pinUnderInked(x, a.?.y + a.?.h, names, inks, heap, label); + } else if (b) |r| { + const p = std.math.clamp(tag.p / (time.quick / time.flight.near), 0, 1); + u.faded(p).pinUnderInked(r.x + r.w / 2, r.y + r.h + (1 - p) * theme.time.caption_rise, names, inks, heap, label); + } else if (a) |r| { + u.faded(1 - std.math.clamp(tag.p / (time.quick / time.flight.near), 0, 1)).pinUnderInked(r.x + r.w / 2, r.y + r.h, names, inks, heap, label); + } + } + } + + const Pins = struct { names: []const []const u8, inks: []const u24, shows: f32 }; /// The registers that hold `addr` (before this step, and after it once /// their link has landed), then the scene's variables that do. fn pins(g: *const Nodes, u: ui.Ui, now: cursors.Now, addr: u64) Pins { const rec = g.cursor.rec; var out: std.ArrayList([]const u8) = .empty; + var inks: std.ArrayList(u24) = .empty; var shows: f32 = 0; const is = (now.moment().regs(rec.tid) catch null) orelse zt.Regs{}; const was = (now.before().regs(rec.tid) catch null) orelse is; - // The scene's variables first: what the narration names. - const moment = now.shown(.idea); + // The scene's variables first: what the narration names, in the ink + // of where each lives. One on its way from another node is drawn + // apart (`tags`). for (g.track) |name| { - const v = rec.variable(u.f.scratch, moment, name) orelse continue; - if (!rec.assigned(v, moment.index)) continue; - if ((Recording.word(moment, v.addr, 8) catch null) != addr) continue; + const tag = g.tagOf(u, now, name); + // Where it is: at the node it leaves until it sets off. + const here = if (tag.p <= 0) tag.from else tag.to; + if ((tag.moving() and tag.p > 0) or here != addr) continue; out.append(u.f.scratch, name) catch break; + inks.append(u.f.scratch, g.home(u, now, name)) catch break; shows = 1; } if (!g.quiet) for (theme.metric.all_registers[0..16]) |name| { @@ -226,9 +309,58 @@ pub const Nodes = struct { const this = if (before and after) 1 else if (after) s.new else s.old; if (this < 0.5) continue; out.append(u.f.scratch, name) catch break; + inks.append(u.f.scratch, t.primary) catch break; shows = @max(shows, this); }; - return .{ .names = out.items, .shows = shows }; + // Names keep their side: one left alone where it was on the right stays there. + 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])) { + out.insert(u.f.scratch, 0, "") catch {}; + inks.insert(u.f.scratch, 0, t.primary) catch {}; + } + } + return .{ .names = out.items, .inks = inks.items, .shows = shows }; + } + + /// The first name on `addr`'s pin before this step, if another name was beside it. + fn firstBefore(g: *const Nodes, u: ui.Ui, now: cursors.Now, addr: u64, was: zt.Regs) ?[]const u8 { + const names = g.namesBefore(u, now, addr, was); + return if (names.len >= 2) names[0] else null; + } + + /// The names on `addr`'s pin before this step, in their order (the first left). + fn namesBefore(g: *const Nodes, u: ui.Ui, now: cursors.Now, addr: u64, was: zt.Regs) []const []const u8 { + const rec = g.cursor.rec; + var out: std.ArrayList([]const u8) = .empty; + for (g.track) |name| { + const v = rec.variable(u.f.scratch, now.before(), name) orelse continue; + if (!rec.assigned(v, now.before().index)) continue; + if ((Recording.word(now.before(), v.addr, 8) catch null) != addr) continue; + out.append(u.f.scratch, name) catch break; + } + if (!g.quiet) for (theme.metric.all_registers[0..16]) |name| if (was.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; + return rows.ink(rows.regionOf(now.moment(), v.addr)); + } +}; + +/// A variable's tag: the node it was under before the step and the one +/// it is under after it (0: none), and how far it has gone. +const Tag = struct { + from: u64, + to: u64, + p: f32, + + fn moving(tag: Tag) bool { + return tag.from != tag.to and tag.p < 1; } }; diff --git a/anim/src/objects.zig b/anim/src/objects.zig index 57e2b11..0c4f48a 100644 --- a/anim/src/objects.zig +++ b/anim/src/objects.zig @@ -122,6 +122,20 @@ pub fn spell(scratch: std.mem.Allocator, t: types.Type) []const u8 { }; } +/// A number as its type says to read it (the `value` classes a type +/// gives): a boolean `true`, a character quoted, else its decimal. +pub fn reading(scratch: std.mem.Allocator, n: i64, t: types.Type) []const u8 { + if (t == .scalar) switch (t.scalar.kind) { + .bool => return if (n != 0) "true" else "false", + .char => { + const c: u8 = @truncate(@as(u64, @bitCast(n))); + return if (std.ascii.isPrint(c) and c != '\'' and c != '\\') std.fmt.allocPrint(scratch, "'{c}'", .{c}) catch "?" else std.fmt.allocPrint(scratch, "'\\x{x:0>2}'", .{c}) catch "?"; + }, + else => {}, + }; + return std.fmt.allocPrint(scratch, "{d}", .{n}) catch "?"; +} + /// A variable as C declares it: `int a[8]`, `node *prev`, `long n`. pub fn declare(scratch: std.mem.Allocator, rec: *const Recording, v: Recording.Variable) []const u8 { const name = rec.name(v.name); diff --git a/anim/src/root.zig b/anim/src/root.zig index a69cda9..6aa47de 100644 --- a/anim/src/root.zig +++ b/anim/src/root.zig @@ -99,8 +99,10 @@ pub fn enter(s: *anim.Frame, views: anytype) void { /// then the picture is still long enough to be read, a second and half a /// second for each panel, before a word is said about it. pub fn establish(s: *anim.Frame, views: anytype) void { + const start = s.cursor; enter(s, views); - s.wait(time.establish + time.establish_per_panel * @as(f32, @floatFromInt(views.len - 1))); + // The first caption at a second: the picture is read under it. + s.wait(@max(start + time.establish - s.cursor, 0)); } /// And takes them away: quicker than they came. @@ -117,17 +119,28 @@ pub fn leave(s: *anim.Frame, views: anytype) void { /// it, longer after a scene's first: the eye reads, then is shown. pub const Narrator = struct { current: ?anim.Obj = null, + /// When the caption on screen has been up long enough to be read. + read_by: f32 = 0, pub fn line(n: *Narrator, s: *anim.Frame, text: []const u8) void { const next = add(s, Caption{ .text = text }); if (n.current) |old| { + // Not before the one up has been read: what follows waits. + s.wait(@max(n.read_by - s.cursor, 0)); s.play(.{old.fadeOut()}, .{ .seconds = time.caption_out, .ease = ease.exit }); s.wait(time.caption_gap); } s.play(.{next.fadeIn()}, .{ .seconds = time.caption_in, .ease = ease.enter }); + n.read_by = s.cursor + time.caption(@intCast(std.unicode.utf8CountCodepoints(text) catch text.len)); s.wait(if (n.current == null) time.caption_lead_first else time.caption_lead); n.current = next; } + + /// A scene's close: the last picture still, and the last caption read. + pub fn close(n: *Narrator, s: *anim.Frame) void { + s.wait(time.before_cut); + s.wait(@max(n.read_by - s.cursor, 0)); + } }; /// The camera, directed: a way of reading the context, not a place to be @@ -218,6 +231,24 @@ pub const Context = struct { pub fn ties(c: Context, s: *anim.Frame) anim.Obj { return add(s, Ties{ .cursor = c.cursor, .stage = c.stage, .quiet = c.quiet }); } + + /// A scene's opening with a lens drawn from bytes (`nodes`, `array`): + /// as `establish`, and from half a second in the drawing's + /// `elements` come in, each rising 8 units, 2 f apart in address + /// order (`ties.rise`), beside their rows' quiet brackets; no lines. + pub fn establish(c: Context, s: *anim.Frame, views: anytype, elements: usize) void { + const start = s.cursor; + s.play(.{c.stage.rise.to(0)}, .{ .seconds = 0 }); + s.cursor = start; + enter(s, views); + const done = s.cursor; + s.cursor = start + time.establish_rise; + const rising = tying.riseTime(elements); + s.play(.{c.stage.rise.to(rising)}, .{ .seconds = rising, .ease = anim.ease.linear }); + s.cursor = @max(s.cursor, done); + // The first caption at a second. + s.wait(@max(start + time.establish - s.cursor, 0)); + } }; pub fn context(s: *anim.Frame, at: Cursor, options: Context.Options) Context { diff --git a/anim/src/rows.zig b/anim/src/rows.zig index 063301a..4d8a42b 100644 --- a/anim/src/rows.zig +++ b/anim/src/rows.zig @@ -138,10 +138,10 @@ pub fn chain(u: ui.Ui, x: f32, y: f32, moment: Recording.Moment, value: u64, roo } else { // A code address's name. const name = ui.symbol(u, link.text); - const fits: usize = @intFromFloat(@max((room - at - 10) / adv, 0)); - if (fits >= 3) { - v.text(.mono, size, at + 10, base, name[0..@min(name.len, fits)], t.primary); - at += 10 + @as(f32, @floatFromInt(@min(name.len, fits))) * adv; + if (room - at - 10 >= 3 * adv) { + const cut = fitted(u, name, room - at - 10); + v.text(.mono, size, at + 10, base, cut, t.primary); + at += 10 + u.width(.mono, size, cut); } } break; @@ -214,6 +214,17 @@ pub fn slot(u: ui.Ui, y: f32, w: f32, moment: Recording.Moment, addr: u64, pins: return chain(u, at, y, moment, held, w - s.room, lead); } +/// `slot` `free`: a word above rsp the stack has not reached, shown while +/// the window is held for the camera: its address at 60%, its word +/// faint, no chain, no pin. +pub fn free(u: ui.Ui, y: f32, moment: Recording.Moment, addr: u64, lead: usize) void { + const s = theme.metric.slot; + const base = baseline(y); + const end = u.address(s.chain, base, addr, .{ .ink = ui.mix(theme.color.region.stack, theme.color.page, theme.metric.context.lead_alpha), .lead = lead }); + const word = (Recording.word(moment, addr, 8) catch null) orelse return u.unknown(.{ .x = end + m.arrow_w, .y = y, .w = 24, .h = row_h }); + u.text(.mono, size, end + m.arrow_w, base, u.print("{x}", .{word}), t.faint); +} + /// `call` `span`: one frame of the call chain on the stack, a bracket 14 /// in from the panel's right edge `w` down the slots `y0 .. y1` that are /// the frame, and the function's name left of it (Go Medium 18). `newest` @@ -227,14 +238,27 @@ pub fn span(u: ui.Ui, w: f32, y0: f32, y1: f32, name: []const u8, newest: bool, u.text(.sans_medium, micro, x - 14 - u.width(.sans_medium, micro, name), mid, name, if (newest) t.bright else t.dim); } -/// `call` `row`: `#n` (a gold plaque on the newest), the name and offset -/// in primary at 60, file and line in dim at 276. -pub fn callRow(u: ui.Ui, y: f32, w: f32, n: usize, name: []const u8, where: []const u8, newest: bool) void { +/// `call` `row`: `#n` at 12 (a gold plaque 40 wide on the newest), the +/// name and offset in primary at 60, the arguments at 384 (`n=4`, +/// primary), file and line ranged right, dim. A name cut only where the +/// arguments begin, saying so. +pub fn callRow(u: ui.Ui, y: f32, w: f32, n: usize, name: []const u8, args: []const u8, where: []const u8, newest: bool) void { const gold = theme.mark(.current); - if (newest) u.current(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = row_h }, 44, 0); + if (newest) u.current(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = row_h }, 40, 0); u.text(if (newest) .mono_bold else .mono, size, m.side, baseline(y), u.print("#{d}", .{n}), if (newest) gold.on_solid else t.faint); - u.text(.mono, size, 60, baseline(y), name[0..@min(name.len, 17)], t.primary); - u.text(.mono, size, 276, baseline(y), where, t.dim); + const where_x = w - m.side - u.width(.mono, size, where); + const args_x: f32 = 384; + const shown = fitted(u, name, (if (args.len > 0) args_x else where_x) - 60 - adv); + u.text(.mono, size, 60, baseline(y), shown, t.primary); + u.text(.mono, size, @max(args_x, 60 + u.width(.mono, size, shown) + adv), baseline(y), args, t.primary); + u.text(.mono, size, where_x, baseline(y), where, t.dim); +} + +/// `text` in `width` units of mono 20: whole, or cut at its far end with `…`. +pub fn fitted(u: ui.Ui, text: []const u8, width: f32) []const u8 { + const chars: usize = @intFromFloat(@max(width / adv, 1)); + if (text.len <= chars) return text; + return u.print("{s}\u{2026}", .{text[0 .. chars - 1]}); } /// `line`: a line of source, its number ranged right in three characters diff --git a/anim/src/source.zig b/anim/src/source.zig index 51059a7..0bba714 100644 --- a/anim/src/source.zig +++ b/anim/src/source.zig @@ -101,7 +101,8 @@ pub const Source = struct { const on = shows >= 0.5 and line == mark_line; rows.line(u, y, box.w, line, text.bytes[span[0]..span[1]], text.styles[span[0]..span[1]], if (on) .marked else if (k) |n| .{ .trail = n } else .plain); } - context.veiled(u, box, now.veil); + // The source is read at a run; at a sprint it is veiled too. + context.veiled(u, box, now.sprint_veil); } }; diff --git a/anim/src/stage.zig b/anim/src/stage.zig index 31a149a..595b9f5 100644 --- a/anim/src/stage.zig +++ b/anim/src/stage.zig @@ -10,18 +10,31 @@ const theme = ui.theme; const Split = theme.layout.Split; const Rect = theme.Rect; -pub const Part = enum { band, source, disasm, registers, stack, backtrace }; +pub const Part = enum { band, view, source, disasm, registers, stack, backtrace }; pub const Stage = struct { first: Split, moves: [8]Move = undefined, count: usize = 0, + /// Seconds into the band's lens rising from its bytes (`Context.establish`, + /// `ties.rise`); far past it, for a scene that does not raise one. + rise: anim.Value, + /// 1, or less while a relayout fades the drawing out and in round its move. + drawing: anim.Value, + /// 1, or less while the camera visits the drawing and its view is cleared. + view: anim.Value, + /// While the camera visits the stack: the moment whose window it holds + /// still (negative: none), and how many `free` words above its rsp it shows. + hold: anim.Value, + hold_free: anim.Value, + /// 0 to 1 as the window goes from where it was to where it is held (and back). + hold_in: anim.Value, const Move = struct { from: Split, to: Split, p: anim.Value }; /// A stage at `split`, made where a scene's components can keep a pointer to it. pub fn init(s: *anim.Frame, split: Split) *Stage { - return s.new(Stage{ .first = split }); + return s.new(Stage{ .first = split, .rise = s.value(std.math.floatMax(f32)), .drawing = s.value(1), .view = s.value(1), .hold = s.value(-1), .hold_free = s.value(0), .hold_in = s.value(0) }); } /// The split the stage ends in, after every move so far. @@ -34,7 +47,23 @@ pub const Stage = struct { const p = s.value(0); st.moves[st.count] = .{ .from = st.last(), .to = to, .p = p }; st.count += 1; + // The drawing fades out (12 f), the panels move, it fades in at its new size. + s.play(.{st.drawing.to(0)}, .{ .seconds = theme.time.quick, .ease = anim.ease.linear }); s.play(.{p.to(1)}, .{ .seconds = theme.time.relayout, .ease = anim.ease.linear }); + s.play(.{st.drawing.to(1)}, .{ .seconds = theme.time.quick, .ease = anim.ease.linear }); + } + + /// Holds the stack's window still as it is at moment `at`, with `free` + /// words above its rsp for pushes to fill: for the camera's visit. + pub fn holdStack(st: *Stage, s: *anim.Frame, at: u64, free: u32) void { + s.play(.{ st.hold.to(@floatFromInt(at)), st.hold_free.to(@floatFromInt(free)) }, .{ .seconds = 0 }); + // It scrolls there by whole rows, as a window does. + s.play(.{st.hold_in.to(1)}, .{ .seconds = theme.time.move, .ease = anim.ease.linear }); + } + + pub fn releaseStack(st: *Stage, s: *anim.Frame) void { + s.play(.{st.hold_in.to(0)}, .{ .seconds = theme.time.move, .ease = anim.ease.linear }); + s.play(.{st.hold.to(-1)}, .{ .seconds = 0 }); } /// The split as it stands at this instant. @@ -67,7 +96,7 @@ pub const Stage = struct { fn between(a: Split, b: Split, p: f32) Split { var out = b; - inline for (.{ "band", "source", "disasm", "registers", "stack", "backtrace" }) |name| { + inline for (.{ "band", "view", "source", "disasm", "registers", "stack", "backtrace" }) |name| { const x = @field(a, name); const y = @field(b, name); @field(out, name) = .{ .x = std.math.lerp(x.x, y.x, p), .y = std.math.lerp(x.y, y.y, p), .w = std.math.lerp(x.w, y.w, p), .h = std.math.lerp(x.h, y.h, p) }; @@ -79,6 +108,6 @@ fn between(a: Split, b: Split, p: f32) Split { test "a relayout passes through the splits it joins" { const sp = theme.layout.split; const half = between(sp.beside, sp.subject, 0.5); - try std.testing.expectEqual(@as(f32, 200), half.band.h); + try std.testing.expectEqual(@as(f32, 224), half.band.h); try std.testing.expectEqual(sp.subject.stack, between(sp.beside, sp.subject, 1).stack); } diff --git a/anim/src/syscalls.zig b/anim/src/syscalls.zig index a19324f..67085c2 100644 --- a/anim/src/syscalls.zig +++ b/anim/src/syscalls.zig @@ -11,9 +11,11 @@ const sk = @import("sketch"); const anim = @import("anim"); const zt = @import("ztrace"); const ui = @import("ui.zig"); +const rows = @import("rows.zig"); const cursors = @import("cursor.zig"); const Recording = @import("Recording.zig"); const context = @import("context.zig"); +const hexdump = @import("hexdump.zig"); const Stage = @import("stage.zig").Stage; const theme = ui.theme; const time = theme.time; @@ -27,8 +29,8 @@ const k = theme.color.on_kernel; /// kernel's side change, the last call giving way to this one, its name, /// its rows, its card; the work is done a byte at a time (a call with /// none skips it); the arrow comes back, and what came back strikes rax. -/// So a call is as long as what it does: `close` 3.7 s, a `read` of -/// fifteen bytes 4.8. +/// So a call is as long as what it does: `close` 4.0 s, a `read` of +/// fifteen bytes 5.1. pub const Plan = struct { registers: f32 = time.cascade, enters: f32 = 0.80, @@ -43,11 +45,14 @@ pub const Plan = struct { work: f32 = 2.00, fills: f32 = 2.40, bytes: f32 = 0, - /// The arrow back sets off; rax is struck; the mark moves on. + /// The arrow back sets off; rax is struck; the `returns` row takes the + /// value; the program stores what came back (memory, after its + /// cause); the mark moves on. back: f32 = 2.00, returns: f32 = 2.40, - advance: f32 = 3.10, - total: f32 = 3.70, + stored: f32 = 2.80, + advance: f32 = 3.40, + total: f32 = 4.00, pub const cross = 0.40; pub const row = 0.10; @@ -61,7 +66,8 @@ pub const Plan = struct { p.bytes = @floatFromInt(@max(down, @min(up, 32))); if (p.bytes > 0) p.back = p.fills + p.bytes * byte + 10.0 / 60.0; p.returns = p.back + cross; - p.advance = p.returns + row + time.read_value; + p.stored = p.returns + row + time.cascade; + p.advance = p.stored + time.read_value; p.total = p.advance + time.step + time.rest; return p; } @@ -69,12 +75,14 @@ pub const Plan = struct { /// The same as the cursor's plan: the registers are the CPU's level, /// the bytes memory's. pub fn step(p: Plan) cursors.Plan { - return .{ .at = .{ p.registers, p.fills, p.fills }, .advance = p.advance, .travel = time.step, .total = p.total }; + return .{ .at = .{ p.registers, p.stored, p.stored }, .advance = p.advance, .travel = time.step, .total = p.total }; } }; /// How many of the bytes a call was given the kernel's side shows. -const shown_bytes = 2 * 11; +/// Ten a row, two rows, in the drawing's 880 beside the arrows. +const per_row = 10; +const shown_bytes = 2 * per_row; /// One line of the program and the call into the kernel it makes, as one /// step of the cursor, timed by the crossing. A line that makes no call @@ -144,9 +152,13 @@ pub const Crossing = struct { const size = theme.size.mono.context; pub fn draw(c: *const Crossing, f: *sk.Frame, placed: anim.Placed) void { + c.view(f, placed); const box = c.stage.box(placed, .band); if (box.h < theme.metric.context.tag + 24) return; - const u = context.at(f, placed, box); + const u = context.at(f, placed, box).faded(placed.value(c.stage.drawing)); + // A relayout moves the band: what is drawn in it stays inside it. + u.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }); + defer u.unclip(); const now = c.cursor.now(placed); const rec = c.cursor.rec; const body = u.panel(box.w, box.h, "kernel", .{ .focus = c.focus, .note = "the other side of a system call" }); @@ -183,19 +195,44 @@ pub const Crossing = struct { if (gold) v.fill(card, theme.mark(.current).solid); v.frame(card, k.ink, theme.stroke.rule); const name = zt.syscalls.name(done.nr) orelse "?"; - v.text(if (gold) .mono_bold else .mono, size, card.x + 8, theme.baseline(card.y, card.h, size), name[0..@min(name.len, 11)], k.ink); - if ((i != newest or t >= p.returns + Plan.row) and done.exit != null) { - const words = result(u, done); - if (words.len <= 4) v.text(.mono, size, card.x + card.w - 8 - u.width(.mono, size, words), theme.baseline(card.y, card.h, size), words, k.dim); - } + // The result ranged right, when it is short; the name has the rest, and is cut only there. + const words = if ((i != newest or t >= p.returns + Plan.row) and done.exit != null) result(u, done) else ""; + const said = if (words.len > 0 and words.len <= 4) words else ""; + if (said.len > 0) v.text(.mono, size, card.x + card.w - 8 - u.width(.mono, size, said), theme.baseline(card.y, card.h, size), said, k.dim); + v.text(if (gold) .mono_bold else .mono, size, card.x + 8, theme.baseline(card.y, card.h, size), rows.fitted(u, name, card.w - 16 - (if (said.len > 0) u.width(.mono, size, said) + 12 else 0)), k.ink); } } + /// Its view: the bytes the newest call is given or fills (its path, a + /// buffer), as a dump over the state column; struck as the kernel + /// fills them. + fn view(c: *const Crossing, f: *sk.Frame, placed: anim.Placed) void { + const rec = c.cursor.rec; + const now = c.cursor.now(placed); + var newest = latest(rec, now.stops[0]); + // No effect before its cause: until the kernel has taken the call, the last one's bytes. + if (newest) |n| if (rec.syscalls[n].enter > now.stops[1] and now.walking() and now.time < Plan.of(rec.syscalls[n]).name) { + newest = if (n > 0) n - 1 else null; + }; + const made: ?Recording.Syscall = if (newest) |n| rec.syscalls[n] else null; + const span: ?Recording.Span = if (made) |given| bufferRead(given) orelse fills(given) orelse if (given.text.len > 0 and std.mem.indexOfScalar(u8, zt.syscalls.signature(given.nr), 's') != null) .{ .addr = given.args[0], .len = given.text.len + 1 } else null else null; + const scratch = context.at(f, placed, c.stage.box(placed, .view)); + const about = if (span) |sp| scratch.print("the {s}, {x} to {x}", .{ if (bufferRead(made.?) != null) "buffer given" else if (fills(made.?) != null) "buffer filled" else "path given", sp.addr, sp.addr + sp.len - 1 }) else "the call names no bytes"; + const v = hexdump.panel(f, placed, c.stage, about, &.{}); + defer v.u.unclip(); + const sp = span orelse return; + if (v.rows == 0) return; + const first = sp.addr & ~@as(u64, 15); + const n = @min(v.rows, (sp.addr + sp.len - first + 15) / 16); + hexdump.draw(v.u, now, 0, theme.metric.context.tag + theme.metric.context.pad, first, n, .{ .region = context.ink(context.regionOf(now.moment(), sp.addr)) }); + v.veil(now); + } + /// A call, decoded: its name, a row for each argument, what came /// back; and to the right the bytes it was given, as the kernel /// copies them. fn call(c: *const Crossing, u: ui.Ui, body: Rect, made: Recording.Syscall, p: Plan, t: f32) void { - _ = c; + const rec = c.cursor.rec; const x = 236; const name = zt.syscalls.name(made.nr) orelse "syscall"; // The name arrives rising, as a caption does. @@ -208,22 +245,28 @@ pub const Crossing = struct { var row_y: f32 = body.y + 62; var text_used = false; const row = struct { - fn draw(v: ui.Ui, y: f32, register: []const u8, meaning: []const u8, words: []const u8) void { + /// `note`: faint after the words, what a descriptor is open on (the `value` class `fd`). + fn draw(v: ui.Ui, y: f32, register: []const u8, meaning: []const u8, words: []const u8, note: []const u8) void { v.fill(.{ .x = x, .y = y, .w = 300, .h = theme.stroke.rule }, k.rule); const base = theme.baseline(y, row_h + 4, size); v.text(.mono, size, x, base, register, k.dim); v.text(.sans_medium, theme.size.sans.tag, x + 52, base, meaning, k.ink); v.text(.mono, size, x + 130, base, words, k.ink); + v.text(.mono, size, x + 130 + v.width(.mono, size, words) + 8, base, note, k.dim); } }.draw; for (signature, 0..) |kind, arg| { if (arg >= 4) break; const shows = std.math.clamp((t - p.rows - @as(f32, @floatFromInt(arg)) * Plan.row) / Plan.row, 0, 1); - row(u.faded(shows), row_y, carriers[arg], what(made.nr, kind, arg), value(u, made, kind, arg, &text_used)); + const meaning = what(made.nr, kind, arg); + const note = if (std.mem.eql(u8, meaning, "fd")) rec.openOn(u.f.scratch, made.args[arg], made.enter) else ""; + row(u.faded(shows), row_y, carriers[arg], meaning, value(u, made, kind, arg, &text_used), note); row_y += row_h + 4; } const back = t >= p.returns + Plan.row and made.exit != null; - row(u.faded(std.math.clamp((t - p.rows - @as(f32, @floatFromInt(@min(signature.len, 4))) * Plan.row) / Plan.row, 0, 1)), row_y, "rax", "returns", if (back) result(u, made) else "\u{2014}"); + // What `open` returns is a descriptor: open on the path it was given. + const opened = back and std.mem.eql(u8, zt.syscalls.name(made.nr) orelse "", "open") and @as(i64, @bitCast(made.result)) >= 0; + row(u.faded(std.math.clamp((t - p.rows - @as(f32, @floatFromInt(@min(signature.len, 4))) * Plan.row) / Plan.row, 0, 1)), row_y, "rax", "returns", if (back) result(u, made) else "\u{2014}", if (opened) rec.openOn(u.f.scratch, made.result, made.exit.? + 1) else ""); if (made.text.len == 0) return; const bytes_x = 564; @@ -231,7 +274,7 @@ pub const Crossing = struct { framed.text(.sans, theme.size.sans.micro, bytes_x, body.y + 22, if (std.mem.indexOfScalar(u8, signature, 's') != null) "the path it was given" else "the bytes it was given", k.dim); const shown = @min(made.text.len, shown_bytes); for (made.text[0..shown], 0..) |byte, j| { - const cell: Rect = .{ .x = bytes_x + @as(f32, @floatFromInt(j % 11)) * 28, .y = body.y + 32 + @as(f32, @floatFromInt(j / 11)) * 30, .w = 26, .h = 26 }; + const cell: Rect = .{ .x = bytes_x + @as(f32, @floatFromInt(j % per_row)) * 28, .y = body.y + 32 + @as(f32, @floatFromInt(j / per_row)) * 30, .w = 26, .h = 26 }; // Each fills as it is copied, two frames a byte: struck, then held. const since = t - p.fills - @as(f32, @floatFromInt(j)) * Plan.byte; if (since < 0) { @@ -253,7 +296,8 @@ pub const Crossing = struct { /// ones that carried it), into the kernel, as the call enters; and back /// down as it returns. Machines do not lob: straight. fn arrows(u: ui.Ui, body: Rect, t: f32, p: Plan, made: Recording.Syscall) void { - const x = theme.layout.state.x - theme.layout.program.x + 40; + // At the drawing's right, where it meets the state column the call leaves from. + const x = body.w - 56; const bottom = body.y + body.h; const reach = 64; // Off promptly, and settling in the kernel. @@ -298,6 +342,9 @@ fn what(nr: u16, kind: u8, arg: usize) []const u8 { } fn value(u: ui.Ui, made: Recording.Syscall, kind: u8, arg: usize, text_used: *bool) []const u8 { + // Flags and a mode are bits: hex, said so. + const meaning = what(made.nr, kind, arg); + if (std.mem.eql(u8, meaning, "flags") or std.mem.eql(u8, meaning, "mode")) return u.print("0x{x}", .{made.args[arg]}); const a = made.args[arg]; switch (kind) { 'i' => return u.print("{d}", .{@as(i32, @bitCast(@as(u32, @truncate(a))))}), @@ -305,7 +352,8 @@ fn value(u: ui.Ui, made: Recording.Syscall, kind: u8, arg: usize, text_used: *bo 's' => if (made.text.len > 0 and !text_used.*) { text_used.* = true; const base = std.fs.path.basename(made.text); - return u.print("\"{s}\"", .{base[0..@min(base.len, 14)]}); + // A string cut says so: `…` and no closing quote. + return if (base.len <= 14) u.print("\"{s}\"", .{base}) else u.print("\"{s}\u{2026}", .{base[0..13]}); }, else => {}, } @@ -373,10 +421,12 @@ pub const Timeline = struct { }; test "a crossing is as long as what the call does" { - // A call with no work: 3.7 s. Fifteen bytes copied up: 4.8. - try std.testing.expectApproxEqAbs(@as(f32, 3.70), Plan.of(.{ .nr = 3, .args = @splat(0), .enter = 0 }).total, 1e-3); + // A call with no work: 4.0 s. Fifteen bytes copied up: 5.1. + try std.testing.expectApproxEqAbs(@as(f32, 4.00), Plan.of(.{ .nr = 3, .args = @splat(0), .enter = 0 }).total, 1e-3); const read = Plan.of(.{ .nr = 0, .args = .{ 3, 0x1000, 32, 0, 0, 0 }, .enter = 0, .exit = 0, .result = 15 }); - try std.testing.expectApproxEqAbs(@as(f32, 4.77), read.total, 1e-2); + try std.testing.expectApproxEqAbs(@as(f32, 5.07), read.total, 1e-2); + // What came back is stored after it came back. + try std.testing.expect(read.stored > read.returns); // Nothing on the kernel's side before the arrow is through the line. try std.testing.expect(read.leaves >= read.enters and read.name >= read.enters + Plan.cross); try std.testing.expect(read.fills > read.name and read.returns > read.fills + 15 * Plan.byte); diff --git a/anim/src/theme.zig b/anim/src/theme.zig index ac01bd7..a96d79c 100644 --- a/anim/src/theme.zig +++ b/anim/src/theme.zig @@ -69,11 +69,14 @@ pub const layout = struct { pub const program = cols(0, 6, 0, canvas.stage.h); pub const state = cols(6, 6, 0, canvas.stage.h); - /// Where every panel is in one split. `band` (the lens: a drawing and - /// the bytes it is drawn from, across both columns) and `backtrace` - /// have no height where the split has none. + /// Where every panel is in one split. The band is the lens, two + /// panels: `band`, its drawing, over the program column, and `view`, + /// the pane the drawing is a view of (a dump, the backtrace), over the + /// state column. They and `backtrace` have no height where the split + /// has none. pub const Split = struct { band: Rect, + view: Rect, source: Rect, disasm: Rect, registers: Rect, @@ -88,22 +91,23 @@ pub const layout = struct { pub const none: Split = blk: { const registers = rows(state, 0, 17); const stack = below(registers, 8); - break :blk .{ .band = .{ .x = canvas.stage.x, .y = canvas.stage.y, .w = canvas.stage.w, .h = 0 }, .source = rows(program, 0, 14), .disasm = below(rows(program, 0, 14), 17), .registers = registers, .stack = stack, .backtrace = below(stack, 4), .dump_rows = 0 }; + break :blk .{ .band = .{ .x = program.x, .y = canvas.stage.y, .w = program.w, .h = 0 }, .view = .{ .x = state.x, .y = canvas.stage.y, .w = state.w, .h = 0 }, .source = rows(program, 0, 14), .disasm = below(rows(program, 0, 14), 17), .registers = registers, .stack = stack, .backtrace = below(stack, 4), .dump_rows = 0 }; }; - /// The machine is the subject and the lens beside it: a band of - /// 152 and a dump of five rows; eight lines over seventeen - /// instructions; the registers over eight words. - pub const beside: Split = shared(152, 8, 17, 8, 5); - /// The idea is the subject: a band of 248, the drawing a size up - /// and a dump of nine; ten lines over eleven instructions; four words. - pub const subject: Split = shared(248, 10, 11, 4, 9); + /// The machine is the subject and the lens beside it: a drawing + /// and its view of 152 (a dump of five); eight lines over + /// seventeen instructions; the registers over eight words. + pub const beside: Split = shared(152, 152, 8, 17, 8, 5); + /// The idea is the subject: the drawing 296 high and a size up, + /// its view 200 (a dump of seven); ten lines over nine + /// instructions; the registers over six words, a small frame whole. + pub const subject: Split = shared(296, 200, 10, 9, 6, 7); - fn shared(band_h: f32, source_rows: f32, disasm_rows: f32, slots: f32, dump_rows: u32) Split { - const band: Rect = .{ .x = canvas.stage.x, .y = canvas.stage.y, .w = canvas.stage.w, .h = band_h }; - const top = band.y + band.h + canvas.row_gap; - const source: Rect = .{ .x = program.x, .y = top, .w = program.w, .h = panelH(source_rows) }; - const registers: Rect = .{ .x = state.x, .y = top, .w = state.w, .h = panelH(17) }; - return .{ .band = band, .source = source, .disasm = below(source, disasm_rows), .registers = registers, .stack = below(registers, slots), .backtrace = .{ .x = state.x, .y = canvas.stage.y + canvas.stage.h, .w = state.w, .h = 0 }, .dump_rows = dump_rows }; + fn shared(drawing_h: f32, view_h: f32, source_rows: f32, disasm_rows: f32, slots: f32, dump_rows: u32) Split { + const band: Rect = .{ .x = program.x, .y = canvas.stage.y, .w = program.w, .h = drawing_h }; + const view: Rect = .{ .x = state.x, .y = canvas.stage.y, .w = state.w, .h = view_h }; + const source: Rect = .{ .x = program.x, .y = band.y + band.h + canvas.row_gap, .w = program.w, .h = panelH(source_rows) }; + const registers: Rect = .{ .x = state.x, .y = view.y + view.h + canvas.row_gap, .w = state.w, .h = panelH(17) }; + return .{ .band = band, .view = view, .source = source, .disasm = below(source, disasm_rows), .registers = registers, .stack = below(registers, slots), .backtrace = .{ .x = state.x, .y = canvas.stage.y + canvas.stage.h, .w = state.w, .h = 0 }, .dump_rows = dump_rows }; } }; @@ -770,10 +774,12 @@ pub const time = struct { pub const project = struct { pub const bracket = 0.10; pub const draw = 0.30; + /// Over 600 units: a frame's way back to its call's node. + pub const far = 0.50; pub const out = 0.30; }; - /// `establish`, for a lens: its elements rise from their rows this far apart. - pub const establish_rise = 0.10; + /// `establish`, for a lens: its elements come in from this far into the opening. + pub const establish_rise = 0.50; /// `relayout`: a change of split. pub const relayout = 0.80; /// A caption leaves, then nothing, then the next arrives rising this @@ -824,10 +830,9 @@ pub const time = struct { /// A change of pace is never a switch: each step of it is this much /// of the one before. pub const ramp = 0.6; - /// Stillness at a scene's opening, for the picture to be read: - /// `establish` and `establish_per_panel` for each panel. + /// A scene's opening: its first caption this long after the panels + /// begin to come in (and after a lens has risen from its bytes). pub const establish = 1.00; - pub const establish_per_panel = 0.50; /// Stillness after the stage is rearranged, and on the last picture. pub const settle = 0.80; pub const before_cut = 2.00; @@ -916,11 +921,13 @@ test "the splits fill the stage, panels 12 apart" { // design/README.md, "5. The frame". try expect(sp.none.source.h == 368 and sp.none.disasm.y == 428 and sp.none.disasm.y + sp.none.disasm.h == 868); try expect(sp.none.registers.h == 440 and sp.none.stack.y == 500 and sp.none.backtrace.y == 736 and sp.none.backtrace.y + sp.none.backtrace.h == 864); - try expect(sp.beside.band.h == 152 and sp.beside.source.y == 212 and sp.beside.disasm.y == 448 and sp.beside.disasm.y + sp.beside.disasm.h == bottom); + try expect(sp.beside.band.h == 152 and sp.beside.view.h == 152 and sp.beside.source.y == 212 and sp.beside.disasm.y == 448 and sp.beside.disasm.y + sp.beside.disasm.h == bottom); try expect(sp.beside.registers.y == 212 and sp.beside.stack.y == 664 and sp.beside.stack.y + sp.beside.stack.h == bottom); - try expect(sp.subject.band.h == 248 and sp.subject.source.y == 308 and sp.subject.disasm.y == 592 and sp.subject.disasm.y + sp.subject.disasm.h == bottom); - try expect(sp.subject.stack.y == 760 and sp.subject.stack.y + sp.subject.stack.h == bottom); - try expect(layout.rowsIn(sp.beside.disasm.h) == 17 and layout.rowsIn(sp.subject.disasm.h) == 11 and layout.rowsIn(sp.subject.stack.h) == 4); + try expect(sp.subject.band.h == 296 and sp.subject.view.h == 200 and sp.subject.source.y == 356 and sp.subject.disasm.y == 640 and sp.subject.disasm.y + sp.subject.disasm.h == bottom); + try expect(sp.subject.registers.y == 260 and sp.subject.stack.y == 712 and sp.subject.stack.y + sp.subject.stack.h == bottom); + try expect(layout.rowsIn(sp.beside.disasm.h) == 17 and layout.rowsIn(sp.subject.disasm.h) == 9 and layout.rowsIn(sp.subject.stack.h) == 6 and layout.rowsIn(sp.subject.view.h) == 7); + // The band's two panels are the columns' width, the gutter between them the ties'. + try expect(sp.subject.band.x == layout.program.x and sp.subject.band.w == 880 and sp.subject.view.x == layout.state.x); } test "easing runs from 0 to 1 without turning back" { diff --git a/anim/src/ties.zig b/anim/src/ties.zig index d18b996..3968d23 100644 --- a/anim/src/ties.zig +++ b/anim/src/ties.zig @@ -73,6 +73,11 @@ pub const Place = union(enum) { } }; +/// 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; + /// 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; @@ -128,6 +133,24 @@ pub fn pinShows(now: cursors.Now, i: usize, target: enum { slot, node }) struct }; } +/// `establish` for a lens: its element `k` (in address order), `r` +/// seconds into its elements' coming in: each fades in rising 8 units +/// over 12 f, 2 f after the one before (all begun by 12 f after the +/// first), with its row's quiet bracket beside it; no lines. How much of +/// it shows, and how far below its place it is. +pub fn rise(r: f32, k: usize, n: usize) struct { element: f32, below: f32 } { + const apart = @min(time.stagger, time.quick / @as(f32, @floatFromInt(@max(n, 2) - 1))); + const p = std.math.clamp((r - @as(f32, @floatFromInt(k)) * apart) / time.quick, 0, 1); + const eased = theme.ease(.enter, p); + return .{ .element = p, .below = (1 - eased) * time.caption_rise }; +} + +/// How long `n` elements take to come in. +pub fn riseTime(n: usize) f32 { + const apart = @min(time.stagger, time.quick / @as(f32, @floatFromInt(@max(n, 2) - 1))); + return @as(f32, @floatFromInt(n -| 1)) * apart + time.quick; +} + pub const Ties = struct { cursor: cursors.Cursor, stage: *const Stage, @@ -139,6 +162,7 @@ pub const Ties = struct { pub fn draw(g: *const Ties, f: *sk.Frame, at: anim.Placed) void { defer said = 0; + defer stack_window = null; const now = g.cursor.now(at); // In canvas pixels, `k` of them a unit: places come from panels anywhere. var raw: ui.Ui = .{ .f = f, .at = at }; @@ -182,7 +206,20 @@ pub const Ties = struct { const value = regs.named(name) orelse continue; const from = find(.{ .register = i }) orelse continue; const node = find(.{ .node_pin = value }); - const target = node orelse find(.{ .slot_pin = value }) orelse continue; + // 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 edge: { + const w = stack_window orelse continue; + if (value % 8 != 0 or rows.regionOf(now.moment(), value) != .stack) continue; + const words = @as(i64, @bitCast(value -% w.first)) >> 3; + if (words >= 0 and words < w.slots) continue; + if (@abs(words) > 64) continue; + 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 since = now.since(.cpu, strikeDelay(now, i)); const l = time.link; const drawn = cursors.standard(std.math.clamp((since - l.after) / linkTime(if (node != null) .node else .slot), 0, 1)); @@ -190,7 +227,9 @@ pub const Ties = struct { if (drawn <= 0 or back >= 1) return; const color = rows.ink(rows.regionOf(now.moment(), value)); const y = (from[1] + from[3]) / 2; - const lane = at.xf.apply(.{ theme.metric.tie.link_lane, 0 })[0]; + // 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) 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 }; @@ -203,6 +242,15 @@ pub const Ties = struct { 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 slot's row, and into its pin lane. const mid = (target[1] + target[3]) / 2; @@ -210,7 +258,18 @@ pub const Ties = struct { points[3] = .{ target[0] - 2 * k, mid }; n = 4; } - raw.route(points[0..n], color, .{ .width = theme.stroke.tie.link * k, .head = .{ 10 * k, 10 * k }, .progress = drawn, .from = cursors.standard(back), .radius = theme.metric.tie.radius * k }); + 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) { + // How far the target is, faint, 6 past the head. + const v = raw.faded(1 - std.math.clamp((now.time - now.plan.advance) / l.out, 0, 1)); + 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); + }; + // The pin rides the line's head: the register's name beside it. + if (drawn > 0 and drawn < 1 and beyond == null) { + 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); + } return; } } @@ -224,27 +283,49 @@ pub const Ties = struct { .{ .spans = rec.read(now.stops[1], now.stops[0]), .role = .read }, }; for (kinds) |kind| for (kind.spans) |span| { - const word = span.addr & ~@as(u64, 7); - const run = find(.{ .dump_run = word }) orelse continue; - const part = find(.{ .node_part = word }) orelse continue; - const node_addr = nodeOf(word) orelse continue; + // 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; const since = now.since(.memory, 0); const bracket = std.math.clamp(since / p.bracket, 0, 1); - const drawn = cursors.standard(std.math.clamp((since - p.bracket) / p.draw, 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(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. - const bx = run[0] - (rows.byteX(@intCast(word % 16)) - 4 - theme.metric.bytes.bracket) * 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.chain - 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 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]; 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; + } + 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. if (drawn >= 1) { @@ -252,12 +333,24 @@ pub const Ties = struct { 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); } - _ = part; return; }; } }; +/// The point `p` of the way along the straight path through `points`. +fn along(points: []const ui.Vec, p: f32) ui.Vec { + var total: f32 = 0; + for (points[0 .. points.len - 1], points[1..]) |a, b| total += sk.math.distance(a, b); + var left = total * p; + for (points[0 .. points.len - 1], points[1..]) |a, b| { + const d = sk.math.distance(a, b); + if (left <= d and d > 0) return sk.math.mix(a, b, left / d); + left -= d; + } + 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; diff --git a/anim/src/ui.zig b/anim/src/ui.zig index 48d2f64..6120bbb 100644 --- a/anim/src/ui.zig +++ b/anim/src/ui.zig @@ -281,6 +281,40 @@ pub const Ui = struct { return end; } + /// `value` of a class a type or a signature gives, from `x` at mono + /// 20: `fd`, the number and faint what it is open on (`3 "note"`); + /// `boolean`, `true` or `false`; `character`, its code as a small + /// number and faint the character quoted (`0x41 'A'`). Returns where + /// it ends. + pub fn typed(u: Ui, x: f32, baseline: f32, v: u64, class: Class, ink: Ink) f32 { + const size = theme.size.mono.context; + const adv = advance(size); + const t = theme.color.text; + switch (class) { + .fd => |on| { + const number = u.print("{d}", .{@as(i32, @bitCast(@as(u32, @truncate(v))))}); + u.text(ink.face, size, x, baseline, number, ink.ink); + const end = x + @as(f32, @floatFromInt(number.len)) * adv; + if (on.len == 0) return end; + u.text(.mono, size, end + 8, baseline, on, t.faint); + return end + 8 + u.width(.mono, size, on); + }, + .boolean => { + const word = if (v != 0) "true" else "false"; + u.text(ink.face, size, x, baseline, word, ink.ink); + return x + @as(f32, @floatFromInt(word.len)) * adv; + }, + .character => { + const code = u.print("0x{x:0>2}", .{v & 0xff}); + u.text(ink.face, size, x, baseline, code, ink.ink); + const end = x + @as(f32, @floatFromInt(code.len)) * adv; + const quoted = quote(u, @truncate(v)); + u.text(.mono, size, end + 8, baseline, quoted, t.faint); + return end + 8 + u.width(.mono, size, quoted); + }, + } + } + /// `arrow`: the sign between two things in a chain, 30 wide from `x` /// on the row whose middle is `mid`, faint: grammar, not data. /// Returns where it ends. @@ -403,15 +437,41 @@ pub const Ui = struct { /// edge at (`cx`, `y`), a head 10 by 10 on it, the first name left of /// the stub and the others right, bold, primary. pub fn pinUnder(u: Ui, cx: f32, y: f32, names: []const []const u8, ink: anytype, size: f32) void { + u.pinUnderInked(cx, y, names, &.{}, ink, size); + } + + /// The same, each name in its own ink (`pinNames`). + pub fn pinUnderInked(u: Ui, cx: f32, y: f32, names: []const []const u8, inks: []const u24, ink: anytype, size: f32) void { const p = theme.metric.pin; const rise = size + 10; + // A keyline of page round the stub and its head: an arrow between + // nodes that runs under it is seen to pass behind, not to join it. + const key = theme.stroke.rule; + u.fill(.{ .x = cx - p.stub / 2 - key, .y = y + p.under_head[0] - 1, .w = p.stub + 2 * key, .h = rise - p.under_head[0] + 1 }, theme.color.page); + sk.draw.polygon(u.f, &.{ .{ cx, y }, .{ cx - p.under_head[1] / 2 - key - 1, y + 1 + p.under_head[0] + key }, .{ cx + p.under_head[1] / 2 + key + 1, y + 1 + p.under_head[0] + key } }, u.at.pen(.{ .fill = rgb(theme.color.page) })); u.fill(.{ .x = cx - p.stub / 2, .y = y + p.under_head[0] - 1, .w = p.stub, .h = rise - p.under_head[0] + 1 }, ink); sk.draw.polygon(u.f, &.{ .{ cx, y + 1 }, .{ cx - p.under_head[1] / 2, y + 1 + p.under_head[0] }, .{ cx + p.under_head[1] / 2, y + 1 + p.under_head[0] } }, u.at.pen(.{ .fill = rgb(ink) })); if (names.len == 0) return; + u.pinNames(cx, y, names, inks, size); + } + + /// The names of a `pin` `under`: the first left of the stub, the + /// second right of it ("" for a side kept free), the rest a count; + /// each bold in `inks` (a variable's: where it lives) or primary. + pub fn pinNames(u: Ui, cx: f32, y: f32, names: []const []const u8, inks: []const u24, size: f32) void { + const p = theme.metric.pin; const by = y + 8 + size * 0.86; - u.text(.mono_bold, size, cx - p.under_names - u.width(.mono, size, names[0]), by, names[0], theme.color.text.primary); + const ink = struct { + fn of(all: []const u24, i: usize) u24 { + return if (i < all.len) all[i] else theme.color.text.primary; + } + }.of; + u.text(.mono_bold, size, cx - p.under_names - u.width(.mono, size, names[0]), by, names[0], ink(inks, 0)); // One name a side: a node's neighbour has its own. The rest are a count. - if (names.len > 1) u.text(.mono_bold, size, cx + p.under_names, by, if (names.len > 2) u.print("{s} +{d}", .{ names[1], names.len - 2 }) else names[1], theme.color.text.primary); + if (names.len > 1) { + u.text(.mono_bold, size, cx + p.under_names, by, names[1], ink(inks, 1)); + if (names.len > 2) u.text(.mono_bold, size, cx + p.under_names + u.width(.mono, size, names[1]) + advance(size) / 2, by, u.print("+{d}", .{names.len - 2}), theme.color.text.primary); + } } /// `bracket`: a span marked at its edge, a stroke down `y0 .. y1` at @@ -557,6 +617,23 @@ pub const Value = struct { } }; +/// The classes of `value` a type or a signature gives (`Ui.typed`); `fd` +/// carries what the descriptor is open on. +pub const Class = union(enum) { fd: []const u8, boolean, character }; + +/// A character as C writes it, quoted: `'A'`, `'\n'`, `'\x00'`. +pub fn quote(u: Ui, c: u8) []const u8 { + return switch (c) { + '\n' => "'\\n'", + '\t' => "'\\t'", + '\r' => "'\\r'", + 0 => "'\\0'", + '\'' => "'\\''", + '\\' => "'\\\\'", + else => if (std.ascii.isPrint(c)) u.print("'{c}'", .{c}) else u.print("'\\x{x:0>2}'", .{c}), + }; +} + /// `address`'s options. pub const Address = struct { ink: Color = rgb(theme.color.region.code_), diff --git a/anim/src/words.zig b/anim/src/words.zig index 5601156..bec5116 100644 --- a/anim/src/words.zig +++ b/anim/src/words.zig @@ -7,6 +7,7 @@ const sk = @import("sketch"); const anim = @import("anim"); const ui = @import("ui.zig"); const Cursor = @import("cursor.zig").Cursor; +const cursors = @import("cursor.zig"); const theme = ui.theme; const Rect = ui.Rect; const t = theme.color.text; @@ -33,11 +34,30 @@ pub const Clock = struct { u.fill(.{ .x = -c.width, .y = 0, .w = c.width + stage.x - 8, .h = c.height }, theme.color.page); u.fill(.{ .x = stage.x + stage.w + 8, .y = 0, .w = c.width, .h = c.height }, theme.color.page); u.fill(.{ .x = stage.x, .y = c.clock_y - 1, .w = stage.w, .h = theme.stroke.rule }, theme.color.rule); - u.fill(.{ .x = stage.x, .y = c.clock_y - 2, .w = stage.w * now.place, .h = 4 }, theme.mark(.current).solid); + // Time itself: still while a step plays at a walk or a run; once its + // mark has landed, the step's piece fades in (12 f, 8 at a run) and + // the count changes as it starts. At a sprint it grows with the recording. + const gold = theme.mark(.current).solid; + const at_stop = struct { + fn of(n: cursors.Now, m: u64) f32 { + return std.math.clamp(@as(f32, @floatFromInt(m -| n.way[0])) / @as(f32, @floatFromInt(@max(n.way[1] -| n.way[0], 1))), 0, 1); + } + }.of; + var counted = now.marked(); + 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 = at_stop(now, now.stops[1]); + const to = at_stop(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)); + counted = if (now.time >= landed) now.stops[0] else now.stops[1]; + } const size = theme.size.mono.context; const base = c.clock_y + 28; - // The count is where the current mark is: it changes as the mark moves on. - const count = u.print("moment {d} of {d}", .{ now.marked() -| now.way[0], now.way[1] -| now.way[0] }); + const count = u.print("moment {d} of {d}", .{ counted -| now.way[0], now.way[1] -| now.way[0] }); const count_x = stage.x + stage.w - u.width(.mono, size, count); u.text(.mono, size, count_x, base, count, t.faint); // Secondary action: the pace, said quietly. It only fades. diff --git a/anim/test/gallery/atoms.png b/anim/test/gallery/atoms.png Binary files differindex 7458689..025176c 100644 --- a/anim/test/gallery/atoms.png +++ b/anim/test/gallery/atoms.png diff --git a/anim/test/gallery/none.png b/anim/test/gallery/none.png Binary files differindex 8116b10..098b50a 100644 --- a/anim/test/gallery/none.png +++ b/anim/test/gallery/none.png diff --git a/anim/test/gallery/rest.png b/anim/test/gallery/rest.png Binary files differindex fa7ee53..92c50ab 100644 --- a/anim/test/gallery/rest.png +++ b/anim/test/gallery/rest.png diff --git a/anim/test/gallery/rows.png b/anim/test/gallery/rows.png Binary files differindex 97a8fd9..9f6c095 100644 --- a/anim/test/gallery/rows.png +++ b/anim/test/gallery/rows.png diff --git a/anim/test/gallery/step.png b/anim/test/gallery/step.png Binary files differindex 9678e91..1ca6f8a 100644 --- a/anim/test/gallery/step.png +++ b/anim/test/gallery/step.png diff --git a/anim/test/gallery/subject.png b/anim/test/gallery/subject.png Binary files differindex e7f10ef..b579083 100644 --- a/anim/test/gallery/subject.png +++ b/anim/test/gallery/subject.png diff --git a/anim/test/recordings.zig b/anim/test/recordings.zig index d853285..6d0577f 100644 --- a/anim/test/recordings.zig +++ b/anim/test/recordings.zig @@ -13,7 +13,8 @@ const expectEqual = std.testing.expectEqual; test "steps by line stop on lines of the program's own source, and no step stands still" { inline for (.{ recordings.steps, recordings.hello, recordings.sort, recordings.list }) |program| { const rec = canim.open(program); - var at = rec.call("main", 0).enter; + // From the first call it shows: main, or the one a recording begins in. + var at = rec.calls[0].enter; var stops: usize = 0; while (at < rec.end() and stops < 400) : (stops += 1) { const next = rec.next(.line, at); @@ -38,13 +39,13 @@ test "calls are a tree: fib(5) makes fifteen, each with what it was given and ga for (nodes) |n| if (n.parent) |p| try expect(nodes[p].level + 1 == n.level); } -test "an instrumented program under the debugger tells its calls, variables and stores" { +test "a program recorded by instruction, its variables told: calls, locals, and what they reach" { const rec = canim.open(recordings.list); var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const reverse = rec.call("reverse", 0); try expectEqual(@as(usize, 3), rec.allocations.len); - // The call begins where the debugger stopped on entering it: the line of its header, or its first. + // The recording begins in it (`--from reverse`): the call is open from the first stop. try expect(rec.own[reverse.enter] == 17 or rec.own[reverse.enter] == 18); // A local is not its value until its call has stored to it. const first = rec.lineMoment(18, reverse.enter); @@ -88,11 +89,13 @@ test "a walked step is as long as what it changed: fire, a slot a level, the hol var frame: anim.Frame = .{ .t = 0, .clock = 0, .in = undefined, .pointer = .{ 0, 0 }, .arena = arena.allocator() }; scene.frame(&frame); const t = canim.theme.time; - // main's line calls fib(5): registers, the stack, the call. Three levels, 0.30 s apart. + // main's line calls fib(5): registers, the stack, the call, 0.30 s + // apart; the call's node when the projection from its way back arrives. const from = rec.lineMoment(10, rec.call("main", 0).enter); const call = scene.at.reading(from, rec.next(.line, from)); - try std.testing.expectApproxEqAbs(@as(f32, 3 * t.cascade), call.at[2], 1e-4); - try expect(call.total > 2.0 and call.total < 3.0); + try std.testing.expectApproxEqAbs(@as(f32, 2 * t.cascade), call.at[1], 1e-4); + try std.testing.expectApproxEqAbs(@as(f32, 2 * t.cascade + t.project.bracket + t.project.far), call.at[2], 1e-4); + try expect(call.total > 2.0 and call.total < 3.5); // A line that changes nothing shown: fire, advance, rest. var quiet = scene.at; quiet.levels = .{ .cpu = false, .memory = false }; diff --git a/anim/tools/chart.py b/anim/tools/chart.py index 9dd1314..78ba34d 100644 --- a/anim/tools/chart.py +++ b/anim/tools/chart.py @@ -12,26 +12,31 @@ import motion W = motion.W # The stage (design/README.md, "5. The frame"; theme.layout.split): the lens band across the -# top, the program column (source over disassembly) and the state column (registers over -# stack). A panel of n rows is 32 + 24 n. The clock is over the caption. +# top as two panels, its drawing over the program column and its view over the state column; +# the program column (source over disassembly) and the state column (registers over stack). +# A panel of n rows is 32 + 24 n. The clock is over the caption. def ph(rows): return 32 + 24 * rows -def split(band, source, disasm, slots, backtrace=0): - top = 48 + (band + 12 if band else 0) - out = {"band": (64, 48, 1792, band)} if band else {} - out["source"] = (64, top, 880, ph(source)) - out["disasm"] = (64, top + ph(source) + 12, 880, ph(disasm)) - out["registers"] = (976, top, 880, ph(17)) - out["stack"] = (976, top + ph(17) + 12, 880, ph(slots)) +def split(drawing, view, source, disasm, slots, backtrace=0): + out = {} + if drawing: + out["drawing"] = (64, 48, 880, drawing) + out["view"] = (976, 48, 880, view) + left = 48 + (drawing + 12 if drawing else 0) + right = 48 + (view + 12 if view else 0) + out["source"] = (64, left, 880, ph(source)) + out["disasm"] = (64, left + ph(source) + 12, 880, ph(disasm)) + out["registers"] = (976, right, 880, ph(17)) + out["stack"] = (976, right + ph(17) + 12, 880, ph(slots)) if backtrace: - out["backtrace"] = (976, top + ph(17) + 12 + ph(slots) + 12, 880, ph(backtrace)) + out["backtrace"] = (976, right + ph(17) + 12 + ph(slots) + 12, 880, ph(backtrace)) return out # The clock is under the name the instrument gives to words that are not panels ("head"): # its progress line moves with every step and must not count as a panel starting. words = {"head": (0, 888, W, 46), "caption": (0, 934, W, 146)} -none, beside, subject = split(0, 14, 17, 8, 4), split(152, 8, 17, 8), split(248, 10, 11, 4) +none, beside, subject = split(0, 0, 14, 17, 8, 4), split(152, 152, 8, 17, 8), split(296, 200, 10, 9, 6) motion.REGIONS.update({ "fib": {**subject, **words}, "sort": {**subject, **words}, |
