From c3d9f7ba5effd615374b1359ad98ecf801559f83 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 11 Nov 2026 00:06:30 -0300 Subject: canim: a call followed down to the kernel; rows that say what they do; the heap from the inside From the user. The disassembly can descend: the syscalls scene is glibc's hello by instruction, and open is followed from main through its PLT stub, whose jmp reads the GOT, into libc's wrapper to the syscall row, which crosses to the kernel's window under it, and back up. The band keeps the calls so far as strace writes them. Operands lose their size words and show a width as byte cells only where nothing else says it. A compare shows its values and the flags it leaves, a jump the flags it reads, lea its result, an indirect jump its target and the slot it read, a call that has run its C form. The backtrace has its newest frame at the bottom. A new scene shows glibc 2.44's heap from blocks that exist: chunks read by fields (a size with its bits, a protected pointer), the free list as arcs, the tcache in a loupe, the program's list over malloc's own. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016Y9MNCKgYCGiANnEwcEQxa --- anim/README.md | 124 +++++--- anim/build.zig | 37 ++- anim/scenes/gallery.zig | 16 +- anim/scenes/heap.zig | 323 +++++++++++++++++++ anim/scenes/syscalls.zig | 96 ++++-- anim/src/Recording.zig | 16 +- anim/src/calls.zig | 12 +- anim/src/context.zig | 31 +- anim/src/descent.zig | 620 ++++++++++++++++++++++++++++++++++++ anim/src/disasm.zig | 717 +++++++++++++++++++++++++++++++++++------- anim/src/hexdump.zig | 79 ++++- anim/src/loupe.zig | 28 +- anim/src/root.zig | 20 +- anim/src/rows.zig | 12 +- anim/src/source.zig | 37 ++- anim/src/syscalls.zig | 252 +++++---------- anim/src/theme.zig | 10 + anim/src/ties.zig | 8 +- anim/test/gallery/atoms.png | Bin 104371 -> 104341 bytes anim/test/gallery/loupe.png | Bin 242294 -> 237028 bytes anim/test/gallery/none.png | Bin 231981 -> 226452 bytes anim/test/gallery/rest.png | Bin 237262 -> 232319 bytes anim/test/gallery/rows.png | Bin 117065 -> 138579 bytes anim/test/gallery/step.png | Bin 236811 -> 231969 bytes anim/test/gallery/subject.png | Bin 210793 -> 208224 bytes anim/test/heap.script | 11 + anim/test/recordings.zig | 3 +- anim/tools/chart.py | 4 +- anim/tools/heap.c | 31 ++ 29 files changed, 2075 insertions(+), 412 deletions(-) create mode 100644 anim/scenes/heap.zig create mode 100644 anim/src/descent.zig create mode 100644 anim/test/heap.script create mode 100644 anim/tools/heap.c (limited to 'anim') diff --git a/anim/README.md b/anim/README.md index c59630a..3e7c8f4 100644 --- a/anim/README.md +++ b/anim/README.md @@ -90,7 +90,8 @@ through `Cursor.now(at)`. | `fib` | recursion: each call a frame and a node | `subject`, `calls` | `steps` | | `list` | a list reversed: each `next` turned; it opens on the map and dives into the frame; after the first load the pointer loaded opens in a loupe, and the `next` in it one deeper | `subject`, `nodes` | `list` | | `sort` | insertion sort: compares and swaps | `subject`, `array` | `sort` | -| `syscalls` | open, read, close, write: the kernel's side | `subject`, `syscalls` | `hello` | +| `syscalls` | glibc's `hello`, by instruction from main: `open` followed down (main's call ringed, the PLT's stub passed, libc's wrapper, the kernel's window at the floor with the call in C's form and `returns`, and back up), then `read`, `close`, `write` stepped over, each crossing opening under its call | `beside`, `syscalls` (the calls so far, as strace writes them); the disassembly a `descent` (`Context.Options.descent`) | `hello` | +| `heap` | glibc's malloc under a list of three: three pushes, two pops, a push; the chunks by fields (`size`, `protected`, `key`), the program's list over the tcache's free list with its `bin`, the tcache in a loupe hung from its chunk's row | `subject`, the scene's own drawing (`nodes` in two rows) and view | `heap` | | `zoom` | one line of C as its instructions, the call's bytes | `none`, the camera at x2 | `steps` | | `sqlite` | a row's way to disk in SQLite: from `sqlite3_step` to `sqlite3BtreeInsert` (three continues, the row's struct on the stack), the commit's `unixWrite` nine calls under `main`, `pwrite64` of page 2 into the kernel, and the page read as a B-tree leaf | `subject`, `backtrace` (`Context.Options.backtrace`), then `syscalls`; its view a `hexdump.Dump` | `sqlite` | | `gallery` | every block in its states | all three | `gallery` | @@ -107,13 +108,14 @@ every state the code has in the `gallery` scene. | | `byte` | `src/rows.zig` `bytes` | `number`, `pointer`, `text` (a string's ink), `loose` (a byte of no field: the allocator's, padding, past what a dump is of), `unread`; `pad`; `bytesAt` moves the bytes right of a long (stack) address, by the dump's widest | | 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`. `slot`: pins from 16, the offset from rsp ranged right to 172, the address at 184, the chain, its role ranged right where the room ends, from `zt.telescope.slots` (`saved rbx`, a local's name in primary, `argc`, `argv[0]`, `argv end`, `envp end`, `auxv`; nothing for a return address or `.none`). `bytes`: the bracket at 24, the address at 34, the bytes 12 after it and at 132 at least | | | `arc` | `src/rows.zig` (`Arcs`), `src/hexdump.zig` (`pointerArcs`) | a pointer to a row of its own panel: lanes at 4, 10, 16 in a dump or a loupe, 4 and 10 on the stack; longest outermost, a chain in one lane; standing at 60% toward the page, full in the step that writes or reads it and always in a loupe; rewritten: the old dashed with the arm, fading from 6 f after the strike as the new draws (12 f), quieting with the cool; a stub to the rule for a target in the region past the window, only in its step; a saved rbp's only in its step; a dump withholds the arcs an open loupe carries | -| | `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, its tag the first and last word shown (`rsp+20 to rsp+48`), rsp and rbp's pins travelling 18 f after rsp's strike (`time.pin`, keeping their place among the names they leave and join), at rest only where the register points; a window that moves farther than its own height (six or eight slots) fades out and in round memory's strike, and what it brings, and what changed before it, is plain; a frame's name longer than the spans' room shortens the chains beside it; `call` spans and the backtrace (`#n`, name, arguments at 384, file and line) from `zt.telescope.frames`, the frames two stops share sliding to their new depth; the backtrace as a lens's drawing with `Context.Options.backtrace` | +| | `insn` | `src/disasm.zig` | columns at 2, 31, 40, 134, 180, 264, 564; size words dropped from every operand, a `width` of byte cells (`metric.width`) after the `]` where no register outside the brackets has the access's size and the mnemonic does not fix it; `nop` and `endbr64` faint; a PLT target named (`401070 open@plt`); the annotation from 564 or a character after the operands, then the operands give way, never inside `[]`; `current`, `ran` (every instruction of the last three steps), `ahead`, `outside`, `waiting`, `pass`; the jump lane from the jump just before the pc's moment. The row's detail, every value the recording's at that moment: a compare's two values and the flags it leaves as chips (those the conditional after it reads; CF ZF SF OF when none); a conditional's `taken`/`not taken · reads` and its flags, `→ target` when it leaves the window, and while it runs the setting row's chips and rip's framed as read (an echo); `lea`'s `= value`; a call through memory or a register `→ target name · read from open@got, 403fd8` (out of room the slot goes, then the digits); a call through a PLT stub by the function it reaches (`the resolver` while its slot is lazy); `fs:[0x28]` as the stack's canary (`canary` where the row has no room); a `rep`'s count and step; `syscall` with its name and number, its arguments under it by register, typed (`-100 AT_FDCWD`, `O_RDONLY`); a call that has run in C's form with its result (`read(3, …) = 15`: out of room the arguments go from the right, the result stays) | +| | `descent` | `src/descent.zig` (`Descent`, `step`) | the disassembly a call deep: the root's window on top (main), each callee's under the row that called it (that row `waiting`, ringed, its annotation the call in C's form), a PLT stub gone through kept as its `jmp`, `pass`; a head row over each window (the name at 40, Go Medium 18; what it is ranged right: `libc.so.6 · no source`, `the PLT · its jmp reads open@got, 403fd8`, `the PLT, jumped through`); the call lane at x 14; the nearest caller takes the rows the deepest does not use; three code windows at most, the rest one `more` row; each window's addresses its own width; the tag the deepest function and its module (`open · libc.so.6`); at a `syscall` (and the stop after it) the floor's three rows are the kernel's: in a crossing the lane down from the plaque (3, vellum), the window filling down, `the kernel` and `openat, system call 257`, the call in C's form, `returns` struck, `rcx, r11: clobbered`, the answer up the lane, the window drawing back at the advance. A crossing stepped over opens the same window at the floor under the call's line. Every row keyed (an address, a head), so a step is the rows both stops have gliding and the rest leaving or arriving on its verb's timetable: `descend` (2.7 s), on through a stub's `jmp` (2.0 s), `ascend` (2.3 s), `cross` (`syscalls.step`); with it the source's line `waiting` (ringed, the tag `main waits at line 6 · the pc is in libc's open`) and the thread waiting (primary, 2) | +| 3 panel | `registers`, `stack`, `backtrace` | `src/context.zig` | the backtrace newest at the bottom, `#0` last, the oldest dropped from the top (`newest at the bottom · 2 more above`), as a panel, the calls lens's view, the backtrace lens and on the map; the stack's window on `[rsp, rbp+16)` keeping the touched word in view, its tag the first and last word shown (`rsp+20 to rsp+48`), rsp and rbp's pins travelling 18 f after rsp's strike (`time.pin`, keeping their place among the names they leave and join), at rest only where the register points; a window that moves farther than its own height (six or eight slots) fades out and in round memory's strike, and what it brings, and what changed before it, is plain; a frame's name longer than the spans' room shortens the chains beside it; `call` spans and the backtrace (`#n`, name, arguments at 384, file and line) from `zt.telescope.frames`, the frames two stops share sliding to their new depth; the backtrace as a lens's drawing with `Context.Options.backtrace` | | | `source` | `src/source.zig` | the whole file in a window, its middle third; numbers as wide as the program's largest line (SQLite's six digits), the text moved right by as much; a window going farther than its own height fades out and in | | | `disasm` | `src/disasm.zig` | 17 rows (9 as subject), fewer above near a function's start; the line column as wide as the source's; two windows that overlap scroll, others fade out and in | -| | `hexdump` | `src/hexdump.zig` | a lens's view (`hexdump.panel`): `bytes` rows and their reading, veiled at a sprint; one reading for every dump (`hexdump.reading`), a list a character apart, a typed number as its type reads (`char` quoted, `bool` by name); the address room once a dump, by its widest; `Dump`, a view of a region by the fields a scene gives it (`Field`: where, how long, read as a number, big-endian or not, a pointer, text, or left to the eye), the rows that hold a field and a `more` row for each stretch left out, and where those rows outnumber the window, a window kept round the first row a mark or the step is on, the rest folded into `more` rows; marks the scene plays, and the step's only from the stop it came in at (`since`); the bytes a syscall was given as the kernel took them (`given`), and only what the debugger read at the stop (`seen`) | -| | `loupe` | `src/loupe.zig` (`canim.loupe`, `Loupe.open`, `.close`) | five rows round a pointer's target, lifted (`color.lift`, `lift_tag`, `shade` 12 and 16; 20 and 26 deeper), hanging from its pointer (its tag on the row's foot, 92 left of the digits, clamped to the stage), a 4-high bracket under the digits its stem, the target's fields framed bright; from a register, or from a pointer field of a loupe; `open` 36 f (read 6, stem and rise 18 with the shadow, the frame 6 f after), `close` 12 f | -| | lenses: `nodes`, `array`, `calls`, `syscalls`, `backtrace` | `src/nodes.zig`, `src/array.zig`, `src/calls.zig` (`Tree`), `src/syscalls.zig` (`Crossing`), `src/context.zig` (`Backtrace`, `lens`) | the drawing in `band` (over the program column), its view in `view` (over the state column): `nodes` and `array` a dump (`hexdump.panel`), `calls` the backtrace with arguments, `syscalls` the bytes the call is given or fills, `backtrace` (eleven rows as subject, five beside) a `Dump` the scene gives; an `under` pin's names in the order they came, the first left | +| | `hexdump` | `src/hexdump.zig` | malloc's words: a field read as `size` (`0x20 a m P`, the bits as rip's flags) or `protected` (`→ 405050 ^ 405`, `NULL ^ 405`, its arc to the pointer it protects), and a field's `note` (Go 18 faint: `key`, `top`, `slots left`); a lens's view (`hexdump.panel`): `bytes` rows and their reading, veiled at a sprint; one reading for every dump (`hexdump.reading`), a list a character apart, a typed number as its type reads (`char` quoted, `bool` by name); the address room once a dump, by its widest; `Dump`, a view of a region by the fields a scene gives it (`Field`: where, how long, read as a number, big-endian or not, a pointer, text, or left to the eye), the rows that hold a field and a `more` row for each stretch left out, and where those rows outnumber the window, a window kept round the first row a mark or the step is on, the rest folded into `more` rows; marks the scene plays, and the step's only from the stop it came in at (`since`); the bytes a syscall was given as the kernel took them (`given`), and only what the debugger read at the stop (`seen`) | +| | `loupe` | `src/loupe.zig` (`canim.loupe`, `Loupe.open`, `.close`) | from a register, a loupe's field, or a dump's row read by the scene's fields (`.row`: malloc's tcache, `num_slots[0]` and `entries[0]`, the rest `more`); five rows round a pointer's target, lifted (`color.lift`, `lift_tag`, `shade` 12 and 16; 20 and 26 deeper), hanging from its pointer (its tag on the row's foot, 92 left of the digits, clamped to the stage), a 4-high bracket under the digits its stem, the target's fields framed bright; from a register, or from a pointer field of a loupe; `open` 36 f (read 6, stem and rise 18 with the shadow, the frame 6 f after), `close` 12 f | +| | lenses: `nodes`, `array`, `calls`, `syscalls`, `backtrace` | `src/nodes.zig`, `src/array.zig`, `src/calls.zig` (`Tree`), `src/syscalls.zig` (`Crossing`), `src/context.zig` (`Backtrace`, `lens`) | the drawing in `band` (over the program column), its view in `view` (over the state column): `nodes` and `array` a dump (`hexdump.panel`), `calls` the backtrace with arguments, `syscalls` the calls so far as strace writes them (oldest on top, the newest coming in once it is back, held) over the bytes the call is given or fills, `backtrace` (eleven rows as subject, five beside) a `Dump` the scene gives; an `under` pin's names in the order they came, the first left | | 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 | `map`, `minimap`, `dive`, `surface` | `src/map.zig` (`Map`, `split`, `minimap`), `Context.map` | the working frame's panels bound to a stage of 3840 by 2160 (`map.split`: the drawing and the source, the disassembly 69, the view 32, the registers and the backtrace, the stack 69 from 16 words above rsp); its rows published while `ui.mapping`; the working windows outlined (2 `dim`, 4 out); the minimap the same at a twentieth under the clock (text as 1-unit strokes at 45% toward the page, marks as blocks; `ui.strokes`), the count ranged right at 1648; `Map.show`, `.dive` (outlines bright 6 f, veil to 24, each panel from its window to its place 60 f, 6 f apart in reading order, opaque on the way, its rows on the window's rows, its tag and rules in at the end; the map falls to the minimap's rect over 72 f; 120 f and 30 f still), `.surface` (the dive back, 84 f, then 30 f still); per-panel transforms through `context.at` (`context.zoomed`) | | | `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 | @@ -127,7 +129,7 @@ and read (a debugger's `touch` reads count), each moment's `touch` and ## The recordings -`build.zig` records four programs of `tools/` under `ztrace record` (the +`build.zig` records five programs of `tools/` under `ztrace record` (the debugger: registers, the stack, what they point at, the instructions round the pc with their lines and callees' parameter counts, what each stack word is (`zt.telescope.slots`), at every stop: `--stack 1024 --around 256 @@ -142,9 +144,10 @@ and no canary stepped through that the source does not say. | Name | Program | Stops | Moments, bytes | Also | | --- | --- | --- | --- | --- | | `steps` | `fib.c`, static musl, `-O0` | every instruction | 1999, 431 KB (336 KB before) | | -| `hello` | `hello.c`, static musl | every line | 233, 126 KB (101 KB) | reads `tools/note` | -| `sort` | `sort.c`, `ztrace cc --instr vars --only sort,a` | every instruction, `--from main` | 5154, 799 KB (617 KB) | `--ring`: the variables' names and types; each `__zt_var` call is stepped (4 of them); `--stack 256` (below) | -| `list` | `list.c`, `ztrace cc --instr vars --only push,reverse,head` | every instruction, `--from reverse` | 3369, 782 KB (528 KB) | `--alloc --preload` the agent: allocator headers are read; the pushes (the agent's and the runtime's first calls) run through; `--stack 256` (below) | +| `hello` | `hello.c`, the system's clang and glibc, dynamic: `-O0 -g -no-pie -fstack-protector-strong -Wl,-z,now` (a PLT bound at load, no resolver; the canary) | every instruction, `--from main`, `--steps 132` (to main's return) | 166 (30 of them the loader's syscalls before main), 83 KB (233, 126 KB: static musl by line) | reads `tools/note`; PLT stubs and GOT slots named (`open@plt`, `open@got`) | +| `heap` | `heap.c` (design/mock/heap.c), the system's clang and glibc, dynamic, as `hello` | every line, `--from main` | 75, 59 KB | `--heap` (`ztrace.heap.glibc`: chunks, the tcache, bins, the arena); `-w 0x405000,1024` (the chunks' bodies) and `-w head` (the global the list hangs from: unwatched, a recording keeps a global as last seen) | +| `sort` | `sort.c`, `ztrace cc --instr vars --only sort,a` | every instruction, `--from main` | 4396, 751 KB (5154, 799 KB at `--stack 256`) | `--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` | 2913, 742 KB (3369, 782 KB at `--stack 256`) | `--alloc --preload` the agent: allocator headers are read; the pushes (the agent's and the runtime's first calls) run through | | `gallery` | the old `list` by line, kept in `test/gallery/list.ztrace` | | 134, 88 KB | the gallery's pictures depend on the drawing only | | `sqlite` | `sqlite.c` (three rows into a table, committed) with SQLite 3.50.4's amalgamation, system clang `-O2 -g -fno-omit-frame-pointer -no-pie -fno-stack-protector -Wl,-z,now`, glibc | `--by break`: `sqlite3_step`, `sqlite3BtreeInsert`, `unixWrite`, and the instruction after its `pwrite64` (found by objdump); every syscall recorded, `-s 4096` | 181 (42 stops, 138 syscalls), 233 KB (139 KB) | made only with `-Dsqlite=DIR` (default `~/05-genizah/sqlite/sqlite-amalgamation-3500400`), in a new temporary directory each time; `sqlite3.c` is embedded as the source | @@ -153,42 +156,45 @@ 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 (`storedSame`) and counts as assigning a local (and as a name coming to a node's pin). 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, and with a slower stop it -seldom gets out: `list` with `--stack 512` took 27 000 to 42 000 moments, -with 1024 0.3 to 1.6 million (100 MB, minutes), against 3 900 at 256 -(`--around` and `--disasm` matter little). So the two instrumented -programs keep `--stack 256` (48 words with the 128 bytes under rsp): their -map's stack column is shorter. The tracer should run through a call into -the vDSO as `step` runs through code without lines. An address no symbol +call's rsp put back is not struck. A call into the vDSO (the runtime's clock) is one moment, as the tracer +now records it: `list` and `sort` have `--stack 1024` like the rest. 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 in `out/` (the designer's five checks; its regions are the working frame's; the minimap, 1664 to 1856 by -912 to 1020, is in none). Encoded with `-g 600`: x264's keyframe at 10, +912 to 1020, is in none; `syscalls` now has the `beside` split's regions, +`heap` the `subject`'s). Encoded with `-g 600`: x264's keyframe at 10, 20, 30 s is a one-frame fade the instrument sees. "Before" is the last -pass's exports; "after" this pass's: the new marks, the stack's row, arcs, -the minimap, the list's map and dive and its loupes, the recordings remade. +pass's exports; "after" this pass's: operands without size words, the +row's detail, the backtrace newest at the bottom, the syscalls scene +remade on glibc by instruction with the descent, the heap scene new, +`list` and `sort` recorded with `--stack 1024`. -| | fib | list | sort | syscalls | zoom | sqlite | -| --- | --- | --- | --- | --- | --- | --- | -| POP, before / after | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | -| CROWD, before / after | 2 / 2 | 7 / 6 | 5 / 4 | 1 / 1 | 4 / 3 | 0 / 1 | -| RUSH, before / after | 0 / 2 | 2 / 2 | 0 / 0 | 1 / 1 | 0 / 0 | 1 / 2 | -| AIR, before / after | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 1 / 1 | 5 / 5 | -| seconds, after | 41.5 | 70.9 | 42.0 | 37.9 | 32.0 | 64.6 | +| | fib | list | sort | syscalls | zoom | sqlite | heap | +| --- | --- | --- | --- | --- | --- | --- | --- | +| POP, before / after | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 | new / 0 | +| CROWD, before / after | 2 / 2 | 6 / 6 | 4 / 4 | 1 / 5 | 3 / 3 | 1 / 0 | new / 10 | +| RUSH, before / after | 2 / 0 | 2 / 2 | 0 / 0 | 1 / 2 | 0 / 0 | 2 / 2 | new / 3 | +| AIR, before / after | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 2 | 1 / 1 | 5 / 5 | new / 2 | +| METRONOME, after | 0 | 0 | 0 | 9 | 0 | 0 | 0 | +| seconds, after | 41.5 | 70.9 | 42.0 | 75.9 | 32.0 | 64.6 | 100.4 | -New this pass: list's CROWD at 2.52 is the dive (the windows go bright, -then every panel sets off within 0.5 s: by design one move); fib's RUSH at -5.78 and 7.30 is x264 noise in the caption band (30 pixels changing by 6 -to 24 levels under the still caption while the panels move), not a -caption arriving; sqlite's new RUSH at 19.05 is not examined. The rest are -as below. +New this pass, not examined frame by frame: syscalls' METRONOME (30.62 +to 33.00) is the run through libc's `open` to its `syscall`, steps 0.30 s +apart by design (a run); its AIRs at 13.42 (3.9 s) and 20.90 (5.0 s) are +the stage still under a long caption after a `descend` and after the +stub's `jmp`, which wait for the caption before them to be read; its +CROWDs (13.10, 59.80, 62.50, 68.50 and one more) are not examined. The +heap scene's CROWDs (10.00 the keyframe; 15.62, 26.62, 40.22 and six +more), its RUSHes (29.60, 29.93, 69.68) and its AIRs (65.62, 3.9 s; +70.03, 7.2 s: the tcache's loupe open under a caption of 120 +characters) are not examined. fib's two RUSHes of the last pass are gone. -What fires, and why it is left: +What fires, and why it is left (as examined the last pass: the times of +`list` and `sort` moved with their new recordings, and the syscalls scene +named below is the old one): - CROWD: fib 12.05 and 27.20, list 30.62 and 32.18, sort 17.60 are the veil coming over the registers, stack and disassembly at the first @@ -216,12 +222,44 @@ What fires, and why it is left: ## What is not done +- The descent: a caller's three rows glide to the window's top only + where the deepest window leaves the caller no more rows (the nearest + caller keeps the rest round its call row, as mock 16's second panel + does); when the call row's plaque becomes the ring (72 f) its + arguments, which hung under it, go in one frame, as its annotation + turns to the call in C's form. The kernel's three rows are kept at the + floor from the `syscall` to the stop after it, so the rows under the + call move up again a step later. A crossing stepped over opens the + kernel's window at the panel's floor, over its last three rows, not + under the call row; its lane leaves from the pc's plaque. The fold + past three windows (`2 calls: fib fib`), a lazy PLT's resolver row and + the vDSO's window are written but no recording shows them; the descent + on the map is the same component at 69 rows, not checked. `cross` + keeps the crossing's timetable of the last pass (`syscalls.Plan`), + which is motion.md's within a few frames. +- `open("note", O_RDONLY) = 3` does not fit 880 from 564 (27 + characters): the arguments go from the right, `open("note", …) = 3`. + A call's arguments come from as many as the source's call writes, typed + by the system call of the function's name (`open`, `read`): a libc + function with no system call of its name has its arguments in hex. +- The heap scene's drawing and view are the scene's own components + (`Lists`, `Chunks` in `scenes/heap.zig`), not blocks of `src/`. A node + travels between the rows only where both stops have it in a list: the + first free takes 9 out of the program's list (`head = n->next`) a line + before `free(n)` gives it to the tcache, so it leaves the top row and + comes into the bottom one instead of travelling. The bin's box turns + from dashed to raised, and its count changes, at the idea's slot with + no strike; a `size` bit that changes is not struck on its chip. Between + malloc's return and the push's store a chunk taken back is in neither + list and not drawn (mock 18's fifth panel draws it with its old link). + The heap's map shows no arena panel. + - The map is packed into fixed places (`map.split`): a panel longer than its column is a window of what fits; continuing in the next column's free space under `continued`, the key in a column's foot, `memory` in a scene without a lens, and loupes as panels on the map (and as lifted blocks on the minimap) are not built. The sqlite scene's lenses (the - backtrace, the kernel's side) and the zoom scene have no drawing on + backtrace, the calls so far) and the zoom scene have no drawing on their map. A disassembly of 69 rows shows what the recording decoded round the pc, so a small function leaves rows empty. - The minimap draws no thread and no `flash`; its windows are outlined a @@ -278,8 +316,14 @@ What fires, and why it is left: window would put its count over the panel's tag. - 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). +- The `pages` lens is not in the band (`Timeline` is the old far view). +- The map's and minimap's drawing flags (`ui.mapping`, `ui.strokes`, + `ui.chrome`), a dive's per-panel transforms (`context.zoomed`) and the + ties' table and the thread's waiting are process-wide globals, set and + read in one frame's drawing; two players at once would want them on + the frame. The gallery keeps the old recording of the list + (`test/gallery/list.ztrace`), so that its pictures change with the + drawing alone. - A recording holds the bytes it has seen, each as last seen: it cannot tell a byte read again and unchanged from one not read since. Memory nothing watches (SQLite's page cache) is read at a stop only where a @@ -293,7 +337,7 @@ What fires, and why it is left: recording tells (an instrumented program's); at a breakpoint the callee's are in its registers, which the scene's captions name. - The sqlite scene changes what is over the band (the backtrace lens, - then the kernel's side) and its view (the SQL at rbx, the row, the + then the calls so far) and its view (the SQL at rbx, the row, the page) by fades scripted in the scene (12 f out, then 12 f in); the kernel's side does not bring its elements in as at `establish`. - `zig build test` prints "failed command" for each scripted scene: that diff --git a/anim/build.zig b/anim/build.zig index 21abbce..d12912d 100644 --- a/anim/build.zig +++ b/anim/build.zig @@ -16,7 +16,7 @@ const std = @import("std"); const sketchbook = @import("sketchbook"); -const scenes = [_][]const u8{ "title", "fib", "list", "sort", "syscalls", "zoom", "gallery" }; +const scenes = [_][]const u8{ "title", "fib", "list", "sort", "syscalls", "zoom", "heap", "gallery" }; pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); @@ -74,23 +74,34 @@ pub fn build(b: *std.Build) void { alloc: bool = false, /// A file of tools/ it reads, by its bare name. reads: ?[]const u8 = null, - /// Bytes of stack above rsp each stop records. An instrumented - /// program's runtime reads the clock through the vDSO, whose retry - /// loop is stepped: with 512 or more the loop seldom gets through - /// (`list` took 27 000 to 42 000 moments at 512, and 0.3 to 1.6 - /// million at 1024, against 3 900 at 256), so those take 256. + /// Bytes of stack above rsp each stop records. (A call into the + /// vDSO, the runtime's clock, is one moment: its retry loop is not stepped.) stack: []const u8 = "1024", + /// Built by the system's clang against its glibc and linked + /// dynamically, as a C programmer's program is (a PLT, libc's own + /// code to follow down): `-no-pie` for short addresses, bound at + /// load (`-z now`: no resolver), with the canary the compiler puts in. + glibc: bool = false, + /// Stops after `from` before the recording ends: main's return, not the exit's. + steps: ?[]const u8 = null, + /// Also glibc's heap at every stop (`--heap`), and memory watched (`-w`). + heap: bool = false, + watch: []const []const u8 = &.{}, }; for ([_]Recording{ .{ .name = "steps", .source = "fib.c", .by = "insn" }, - .{ .name = "hello", .source = "hello.c", .by = "line", .reads = "note" }, + // By instruction from main, through the PLT and libc's wrappers to + // the kernel and back: the descent; to main's return. + .{ .name = "hello", .source = "hello.c", .by = "insn", .from = "main", .steps = "132", .glibc = true, .reads = "note" }, + // A line a stop, malloc and free run through; glibc's heap at each. + .{ .name = "heap", .source = "heap.c", .by = "line", .from = "main", .glibc = true, .heap = true, .watch = &.{ "0x405000,1024", "head" } }, // 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", .stack = "256" }, - .{ .name = "list", .source = "list.c", .by = "insn", .instr = "vars", .only = "push,reverse,head", .from = "reverse", .alloc = true, .stack = "256" }, + .{ .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; @@ -108,6 +119,11 @@ pub fn build(b: *std.Build) void { cc.addFileArg(source); cc.addArg("-o"); program = cc.addOutputFileArg(r.name); + } else if (r.glibc) { + const cc = b.addSystemCommand(&.{ "clang", "-O0", "-g", "-no-pie", "-fstack-protector-strong", "-Wl,-z,now" }); + cc.addFileArg(source); + cc.addArg("-o"); + program = cc.addOutputFileArg(r.name); } else { const mod = b.createModule(.{ .target = musl, .optimize = .Debug, .link_libc = true, .omit_frame_pointer = false, .sanitize_c = .off, .stack_protector = false }); mod.addCSourceFile(.{ .file = source, .flags = &.{ "-O0", "-g" } }); @@ -127,6 +143,9 @@ pub fn build(b: *std.Build) void { // instructions round the pc. run.addArgs(&.{ "record", "--by", r.by, "--stack", r.stack, "--around", "256", "--disasm", "69", "-s", "64" }); if (r.from) |place| run.addArgs(&.{ "--from", place }); + if (r.steps) |n| run.addArgs(&.{ "--steps", n }); + if (r.heap) run.addArg("--heap"); + for (r.watch) |what| run.addArgs(&.{ "-w", what }); // What an instrumented program tells of itself comes through a ring. if (r.instr != null) run.addArg("--ring"); if (r.alloc) { diff --git a/anim/scenes/gallery.zig b/anim/scenes/gallery.zig index 7c480ec..9852125 100644 --- a/anim/scenes/gallery.zig +++ b/anim/scenes/gallery.zig @@ -230,7 +230,7 @@ fn rowsPage(u: ui.Ui, p: *const Pages) void { _ = rows.reg(panel, row, 880, "rdi", m, regs.rdi, .{ .first = .struck }); _ = rows.reg(panel, 2 * row, 880, "rax", m, regs.rax, .{ .first = .ember }); _ = rows.reg(panel, 3 * row, 880, "rbp", m, regs.rbp, .{ .read = 1, .read_shows = 1 }); - rows.rip(panel, 4 * row, 880, m, regs.rip, regs.eflags, 1 << 6, 1, 0); + rows.rip(panel, 4 * row, 880, m, regs.rip, regs.eflags, 1 << 6, 1, 0, 1 << 6, 1); y = 380; title(u, 64, y, "slot"); @@ -265,6 +265,20 @@ fn rowsPage(u: ui.Ui, p: *const Pages) void { const long = " a line of source longer than the panel has room for, which is cut at its end"; rows.line(panel, 3 * row, 880, 9, 0, long, styles[0..long.len], .plain); + y = 860; + title(u, 64, y, "insn"); + note(u, 140, y, "operands without size words; a width where no register says it; padding faint"); + y += 12; + panel = u.moved(64, y); + const Insn = canim.Disasm.Row; + for ([_]Insn{ + .{ .addr = 0x100191b, .len = 5, .text = "nop dword ptr [rax + rax]" }, + .{ .addr = 0x100192a, .len = 4, .text = "mov qword ptr [rax + 8], rcx" }, + .{ .addr = 0x7ffff7d10f0e, .len = 7, .text = "cmp byte ptr [rip + 0x11018b], 0" }, + .{ .addr = 0x7ffff7d10f94, .len = 7, .text = "mov dword ptr [rbp - 0x60], 0x10" }, + .{ .addr = 0x7ffff7d10f9b, .len = 4, .text = "movsxd r10, dword ptr [rbp - 0x30]" }, + }, 0..) |one, i| canim.disasm.plainRow(panel, one, @as(f32, @floatFromInt(i)) * row); + y = 750; title(u, 64, y, "bytes"); note(u, 160, y, "runs from the types; marks per run: struck, read, held; read as their types: a char, a bool, an int, a pointer"); diff --git a/anim/scenes/heap.zig b/anim/scenes/heap.zig new file mode 100644 index 0000000..e227f17 --- /dev/null +++ b/anim/scenes/heap.zig @@ -0,0 +1,323 @@ +//! libc's heap from the inside (design/motion.md, "A scene: libc's heap +//! from the inside"; mock 18): `tools/heap.c` (three pushes, two pops, a +//! push) under glibc 2.44, a line a stop with malloc and free run through. +//! Not a lens: the blocks the catalogue has, composed. The band's drawing +//! is `nodes` in two rows (the program's list from `head` over the +//! tcache's free list for chunks of 0x20, headed by its `bin`); its view +//! the heap by fields, each size word read as `size`, a node's words as the +//! program's while it has them and as malloc's (`protected`, `key`) while +//! malloc does, both lists as `arc`s; the tcache a loupe hung from the row +//! of the chunk it lives in. Every byte from the recording at the stop +//! shown (`ztrace.heap.glibc`). +const std = @import("std"); +const sk = @import("sketch"); +const anim = @import("anim"); +const canim = @import("canim"); +const recordings = @import("recordings"); +const ui = canim.ui; +const theme = canim.theme; +const zt = canim.ztrace; +const t = theme.color.text; +const cm = theme.metric.context; + +pub const background = canim.background; +pub const scene = anim.Live(frame, struct {}); + +/// The heap's first bytes, the view's seven rows: three chunks of two rows +/// each and the next chunk's header. +const view_base = 0x405000; +const view_len = 0x70; + +/// The heap at a moment, from the recording; null before there is one. +fn heapAt(a: std.mem.Allocator, rec: *canim.Recording, i: u64) ?zt.heap.Heap { + return zt.heap.glibc(a, rec.moment(i), rec.tid) catch null; +} + +/// The chunks of the free list for 0x20, as the tcache holds them, user addresses. +fn freeList(h: zt.heap.Heap) []const zt.heap.Entry { + const tc = h.tcache orelse return &.{}; + for (tc.bins) |bin| if (bin.in.size() == 0x20) return bin.entries; + return &.{}; +} + +/// How many chunks the bin for 0x20 holds (2.44 stores the slots left). +fn holds(h: zt.heap.Heap) ?u16 { + const tc = h.tcache orelse return null; + for (tc.bins) |bin| if (bin.in.size() == 0x20) { + const count = bin.count orelse return @intCast(bin.entries.len); + return if (tc.capacity) |cap| cap - count else count; + }; + return 0; +} + +/// The program's list from `head`: its nodes' addresses, in list order. +fn programList(a: std.mem.Allocator, rec: *canim.Recording, i: u64, head_at: u64) []const u64 { + var out: std.ArrayList(u64) = .empty; + const m = rec.moment(i); + var p = (canim.Recording.word(m, head_at, 8) catch null) orelse return &.{}; + while (p != 0 and out.items.len < 6) { + out.append(a, p) catch break; + p = (canim.Recording.word(m, p + 8, 8) catch null) orelse break; + } + return out.items; +} + +/// A node's place in the drawing at a moment: its row (0 the program's, 1 +/// the free list's) and its index in that row. +const Spot = struct { row: u8, k: usize }; + +fn spotOf(program: []const u64, free: []const zt.heap.Entry, node: u64) ?Spot { + for (program, 0..) |p, k| if (p == node) return .{ .row = 0, .k = k }; + for (free, 0..) |e, k| if (e.chunk + 16 == node) return .{ .row = 1, .k = k }; + return null; +} + +/// The drawing: `nodes` in two rows, the program's list over malloc's free +/// list, the `bin` heading the second; a node travels between the rows +/// when it is freed or taken back (36 f, `glide`, with the idea's slot). +const Lists = struct { + cursor: canim.Cursor, + stage: *const canim.Stage, + head_at: u64, + + const w = 136; + const h = 44; + const apart = 28; + const well = theme.metric.node.pointer_w; + const rows_y = [2]f32{ 72, 182 }; + const row_x = [2]f32{ 160, 12 + 160 + 28 }; + + fn at(s: Spot) ui.Vec { + return .{ row_x[s.row] + @as(f32, @floatFromInt(s.k)) * (w + apart), rows_y[s.row] }; + } + + pub fn draw(l: *const Lists, f: *sk.Frame, placed: anim.Placed) void { + const box = l.stage.box(placed, .band); + if (box.h < cm.tag + 24) return; + const u = canim.ui.Ui{ .f = f, .at = placed }; + const v = u.moved(box.x, box.y).faded(placed.value(l.stage.drawing)); + v.clip(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }); + defer v.unclip(); + const now = l.cursor.now(placed); + const rec = l.cursor.rec; + const a = f.scratch; + _ = v.panel(box.w, box.h, "the chunks of 0x20", .{ .focus = true, .note = "the program's list \u{00b7} malloc's free list" }); + const stops = [2]u64{ now.stops[1], now.stops[0] }; + var program: [2][]const u64 = undefined; + var free: [2][]const zt.heap.Entry = undefined; + var heaps: [2]?zt.heap.Heap = undefined; + for (stops, 0..) |i, side| { + heaps[side] = heapAt(a, rec, i); + program[side] = programList(a, rec, i, l.head_at); + free[side] = if (heaps[side]) |hp| freeList(hp) else &.{}; + } + // The idea reacts after the bytes: a node travels with the idea's slot. + const p = canim.ease.glide(now.moving(.idea, 0, 36.0 / 60.0)); + const shown: usize = if (p >= 0.5) 1 else 0; + v.text(.sans, theme.size.sans.micro, 12, rows_y[0] + 28, "the program's", t.faint); + // The bin: dashed and faint while the thread's tcache is glibc's dummy. + const bin: canim.Rect = .{ .x = 12, .y = rows_y[1], .w = 160, .h = h }; + const hp = heaps[shown]; + if (hp == null or hp.?.tcache == null) { + v.dashedFrame(bin, t.faint, theme.stroke.rule); + v.label(.mono, theme.size.mono.context, bin, .center, "dummy tcache", t.faint); + } else { + v.fill(bin, theme.color.raised); + v.label(.mono, theme.size.mono.context, bin, .center, "tcache 0x20", t.primary); + // How many it holds, on its shoulder. + const badge: canim.Rect = .{ .x = bin.x + bin.w - 24, .y = bin.y - 34, .w = 30, .h = 30 }; + v.fill(badge, theme.color.page); + v.frame(badge, t.faint, theme.stroke.rule); + v.label(.mono, theme.size.mono.small, badge, .center, v.print("{d}", .{holds(hp.?) orelse 0}), t.primary); + if (free[shown].len > 0) v.route(&.{ .{ bin.x + bin.w, bin.y + h / 2 }, .{ row_x[1] - 2, bin.y + h / 2 } }, theme.color.region.heap, .{ .width = theme.stroke.line, .head = theme.metric.node.arrow_head }); + } + // The top: what is left of the arena, its size. + if (hp) |hh| if (hh.chunks.len > 0) { + const top = hh.chunks[hh.chunks.len - 1]; + const r: canim.Rect = .{ .x = box.w - 12 - 160, .y = rows_y[1], .w = 160, .h = h }; + v.dashedFrame(r, t.faint, theme.stroke.rule); + v.label(.mono, theme.size.mono.context, r, .center, v.print("top 0x{x}", .{top.size()}), t.dim); + _ = v.address(r.x + 16, r.y - 8, top.addr, .{ .ink = ui.rgb(theme.color.region.heap) }); + }; + // Every node of either moment, where it was and where it goes. + var nodes: std.ArrayList(u64) = .empty; + for (program) |list| for (list) |n| if (std.mem.indexOfScalar(u64, nodes.items, n) == null) nodes.append(a, n) catch {}; + for (free) |list| for (list) |e| if (std.mem.indexOfScalar(u64, nodes.items, e.chunk + 16) == null) nodes.append(a, e.chunk + 16) catch {}; + const regs = (now.moment().regs(rec.tid) catch null) orelse zt.Regs{}; + for (nodes.items) |node| { + const from = spotOf(program[0], free[0], node); + const to = spotOf(program[1], free[1], node); + const s0 = from orelse to.?; + const s1 = to orelse from.?; + const xy = canim.ui.Vec{ std.math.lerp(at(s0)[0], at(s1)[0], p), std.math.lerp(at(s0)[1], at(s1)[1], p) }; + const shows: f32 = if (from == null) p else if (to == null) 1 - p else 1; + const nv = v.faded(shows); + const freed = (if (p >= 0.5) s1 else s0).row == 1; + const r: canim.Rect = .{ .x = xy[0], .y = xy[1], .w = w, .h = h }; + const m = if (p >= 0.5) now.moment() else now.before(); + _ = nv.address(r.x + 16, r.y - 8, node, .{ .ink = ui.rgb(theme.color.region.heap) }); + if (freed) { + // Freed: dashed, its first word the link (where the value was), the second hatched, `key`. + nv.dashedFrame(r, theme.color.region.heap, theme.stroke.rule); + nv.fill(.{ .x = r.x + 2, .y = r.y + 2, .w = w / 2 - 2, .h = h - 4 }, theme.color.well); + for (0..4) |k| { + const x0 = r.x + w / 2 + 8 + @as(f32, @floatFromInt(k)) * 14; + nv.line(.{ x0, r.y + h - 4 }, .{ x0 + 12, r.y + 4 }, theme.color.rule, theme.stroke.rule); + } + nv.text(.mono, theme.size.mono.context, r.x + w - 40, r.y + 16, "key", t.faint); + } else { + nv.fill(.{ .x = r.x, .y = r.y, .w = w - well, .h = h }, theme.color.raised); + nv.fill(.{ .x = r.x + w - well, .y = r.y, .w = well, .h = h }, theme.color.well); + const value = (canim.Recording.word(m, node, 8) catch null) orelse 0; + const heat = now.written(node, 8, .idea, 0); + const ink = nv.cellWritten(.{ .x = r.x, .y = r.y, .w = w - well, .h = h }, heat, theme.color.raised); + nv.label(ink.face, theme.size.mono.small, .{ .x = r.x, .y = r.y, .w = w - well, .h = h }, .center, nv.print("{d}", .{@as(i64, @bitCast(value))}), if (heat.level >= 1) ink.ink else ui.rgb(t.primary)); + } + // Its link: the next node in its row, as the pointer protects or holds it. + const sq: canim.Rect = .{ .x = if (freed) r.x + 18 else r.x + w - well / 2 - 5, .y = r.y + h / 2 - 5, .w = 10, .h = 10 }; + const word = (canim.Recording.word(m, node + if (freed) @as(u64, 0) else 8, 8) catch null) orelse 0; + const next = if (freed) word ^ (node >> 12) else word; + if (next == 0) { + nv.line(.{ sq.x - 6, sq.y + 16 }, .{ sq.x + 16, sq.y - 6 }, t.dim, theme.stroke.rule); + } else if (spotOf(program[shown], free[shown], next)) |ns| { + nv.fill(sq, theme.color.region.heap); + const nx = at(ns); + if (nx[1] == r.y and nx[0] > r.x) nv.route(&.{ .{ sq.x + 10, r.y + h / 2 }, .{ nx[0] - 2, r.y + h / 2 } }, theme.color.region.heap, .{ .width = theme.stroke.line, .head = theme.metric.node.arrow_head }); + } + // Who points here: `head`, and the registers. + var names: [4][]const u8 = undefined; + var n: usize = 0; + if ((canim.Recording.word(m, l.head_at, 8) catch null) == node) { + names[n] = "head"; + n += 1; + } + for ([_][]const u8{ "rax", "rdi" }) |reg| if (regs.named(reg) == node and n < names.len) { + names[n] = reg; + n += 1; + }; + if (n > 0) nv.pinUnder(r.x + 40, r.y + h + 2, names[0..n], theme.color.region.heap, theme.size.mono.context); + } + } +}; + +/// The heap's bytes by fields at the stop shown: each chunk's size word as +/// `size`, a node's words as the program's (`number`, `pointer`) while it +/// has them, as malloc's (`protected`, `key`) while malloc does. +fn fieldsAt(a: std.mem.Allocator, rec: *canim.Recording, i: u64) []const canim.hexdump.Field { + var out: std.ArrayList(canim.hexdump.Field) = .empty; + const hp = heapAt(a, rec, i) orelse return &.{}; + const m = rec.moment(i); + for (hp.chunks, 0..) |c, k| { + if (c.addr + 8 >= view_base + view_len) break; + const at = c.addr - view_base; + const tcache_chunk = if (hp.tcache) |tc| tc.addr == c.addr + 16 else false; + out.append(a, .{ .at = at + 8, .len = 8, .reads = .size, .note = if (k + 1 == hp.chunks.len) "top" else if (tcache_chunk) "tcache" else "" }) catch {}; + if (c.size() != 0x20 or k + 1 == hp.chunks.len) continue; + if (c.in == .tcache) { + out.append(a, .{ .at = at + 16, .len = 8, .reads = .protected }) catch {}; + out.append(a, .{ .at = at + 24, .len = 8, .reads = .bytes, .note = "key" }) catch {}; + } else { + // Taken back, before the program writes it: the old link is still there. + const value = (canim.Recording.word(m, c.addr + 16, 8) catch null) orelse 0; + const stale = value >> 12 == (c.addr + 16) >> 12; + out.append(a, if (stale) .{ .at = at + 16, .len = 8, .reads = .bytes, .note = "the old link" } else .{ .at = at + 16, .len = 8 }) catch {}; + out.append(a, .{ .at = at + 24, .len = 8, .reads = .pointer }) catch {}; + } + } + return out.items; +} + +const Chunks = struct { + cursor: canim.Cursor, + stage: *const canim.Stage, + + pub fn draw(c: *const Chunks, f: *sk.Frame, placed: anim.Placed) void { + const v = canim.hexdump.panel(f, placed, c.stage, "the heap, 405000 to 40506f", &.{}); + defer v.u.unclip(); + if (v.rows == 0) return; + const now = c.cursor.now(placed); + canim.hexdump.fielded(v, now, cm.tag + cm.pad, .{ .base = view_base, .len = view_len, .fields = fieldsAt(f.scratch, c.cursor.rec, now.stop(.memory)) }); + v.veil(now); + } +}; + +/// The tcache the program ends with: found once (its heap read at the last stop). +var tcache_found: ?zt.heap.Tcache = null; +fn tcacheOf(rec: *canim.Recording) zt.heap.Tcache { + if (tcache_found == null) { + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + const hp = heapAt(arena.allocator(), rec, rec.end()) orelse @panic("heap: no heap in the recording"); + tcache_found = hp.tcache orelse @panic("heap: no tcache at the end"); + tcache_found.?.bins = &.{}; + arena.deinit(); + } + return tcache_found.?; +} + +/// The global the line at moment `i` reads by `[rip + X]` (its first such operand). +fn globalOf(rec: *canim.Recording, i: u64) u64 { + var buf: [256]u8 = undefined; + var addr = rec.register(i, "rip"); + for (0..8) |_| { + const here = rec.instruction(i, addr, &buf) orelse break; + addr += here.len; + const at = std.mem.indexOf(u8, here.text, "[rip + 0x") orelse continue; + const close = std.mem.indexOfScalarPos(u8, here.text, at, ']') orelse continue; + return addr + (std.fmt.parseInt(u64, here.text[at + 9 .. close], 16) catch continue); + } + @panic("heap: the line reads no global"); +} + +/// The moment of the `n`th call of `function`'s line `line`. +fn lineIn(rec: *canim.Recording, function: []const u8, n: usize, line: u32) u64 { + return rec.lineMoment(line, rec.call(function, n).enter); +} + +fn frame(s: *anim.Frame) void { + const rec = canim.open(recordings.heap); + const main = rec.call("main", 0); + var at = canim.cursor(s, rec, main.enter); + at.journey(.line, rec.lineMoment(30, main.enter)); + at.levels = .{ .idea = .data, .source_rows = 10 }; + const ctx = canim.context(s, at, .{ .split = canim.layout.split.subject }); + // `head`, the program's global: where line 13 (`n->next = head;`) reads it, `[rip + X]`. + const head_at = globalOf(rec, lineIn(rec, "push", 0, 13)); + const lists = canim.add(s, Lists{ .cursor = at, .stage = ctx.stage, .head_at = head_at }); + const chunks = canim.add(s, Chunks{ .cursor = at, .stage = ctx.stage }); + // The tcache, once there is one: a loupe from the row of the chunk it lives in. + const tc = tcacheOf(rec); + const tcache = canim.loupe(s, .{ .cursor = at, .stage = ctx.stage, .from = .{ .row = .{ + .at = tc.addr - 8, + .name = "tcache", + .note = "tcache_perthread_struct \u{00b7} 0x2f0 bytes", + .fields = .{ .base = tc.addr, .len = 0x2f0, .fields = &.{ + .{ .at = 0, .len = 2, .note = "slots left" }, + .{ .at = 0x98, .len = 8, .reads = .pointer, .note = "the head of 0x20" }, + } }, + } } }); + var says: canim.Narrator = .{}; + const tm = theme.time; + const joins = ctx.ties(s); + canim.establish(s, .{ ctx.clock, ctx.registers, ctx.stack, ctx.source, ctx.disasm, chunks, lists, joins }); + + says.line(s, "A list of three, pushed and popped: what malloc and free\ndo to the heap under it, a stop after each."); + at.walk(s, .line, lineIn(rec, "push", 0, 12)); + says.line(s, "malloc(16) cut a chunk of 0x20 off the top: its size word,\n0x21, then the 16 bytes rax points at."); + at.walk(s, .line, lineIn(rec, "push", 1, 10)); + at.hurry(s, .line, rec.lineMoment(26, main.enter), .{}); + says.line(s, "Three pushes, three chunks in a row, each with P: the chunk\nbefore it is in use. The next pointers are arcs in the bytes."); + at.walk(s, .line, lineIn(rec, "pop", 0, 21)); + says.line(s, "free gives 9's chunk to the tcache, malloc's bin for 0x20.\nIts first word is the link now: 405, NULL safe-linked."); + at.walk(s, .line, rec.lineMoment(27, main.enter)); + tcache.open(s); + s.wait(tm.phrase_rest); + at.hurry(s, .line, lineIn(rec, "pop", 1, 21), .{}); + says.line(s, "The second chains to the first: 405455 is 405050 xor 405,\nthe chunk's own address shifted 12."); + at.walk(s, .line, rec.lineMoment(28, main.enter)); + s.wait(tm.phrase_rest); + says.line(s, "malloc(16) takes the bin's head back: the tcache points\nat 405050 again, the key is wiped, the old link stays."); + at.walk(s, .line, lineIn(rec, "push", 3, 12)); + at.walk(s, .line, rec.lineMoment(30, main.enter)); + tcache.close(s); + says.close(s); +} diff --git a/anim/scenes/syscalls.zig b/anim/scenes/syscalls.zig index 1c875f3..db67045 100644 --- a/anim/scenes/syscalls.zig +++ b/anim/scenes/syscalls.zig @@ -1,12 +1,17 @@ //! A program that needs the kernel four times: open, read, close, write. -//! The debugger's context, and the kernel's side of each call as the lens. +//! glibc's `hello`, by instruction from main: `open` followed down (the +//! disassembly a `descent`: main's call, the PLT's stub, libc's wrapper, +//! the kernel's window at the floor, and back up), then the other three +//! stepped over, each crossing under its call. The band is the calls so +//! far, as strace writes them. //! -//! How it moves (design/motion.md): no effect before its cause. Each call -//! has its own caption, up a second before the line fires; the registers -//! that carry it are framed one at a time; the arrow goes down through -//! the line, and only then does the kernel's side take the call: its -//! name, its rows, its card. The bytes are copied two frames apart; the -//! arrow comes back; `rax` is struck. A call is as long as what it does. +//! How it moves (design/motion.md, "A call followed down", "A system +//! call"): no effect before its cause. Each beat has its caption first; +//! the call row's plaque becomes a ring and the lane draws down to the +//! callee's head before its rows come; the registers that carry the call +//! are framed one at a time; the crossing lane goes down before the +//! kernel's window opens; `returns` has the value before rax is struck. +const std = @import("std"); const anim = @import("anim"); const canim = @import("canim"); const recordings = @import("recordings"); @@ -14,39 +19,70 @@ const recordings = @import("recordings"); pub const background = canim.background; pub const scene = anim.Live(frame, struct {}); -/// What the narrator says before each of main's calls, in order. -const lines = [_][]const u8{ - "`open`: a name goes down, and a small number comes back.\nThat number is the file from now on.", - "`read`: the kernel copies the file's bytes into `buf`,\nand says how many.", - "`close`: the number is handed back.", - "`write`: the same bytes go the other way,\nfrom `buf` to file number 1, the output.", -}; +/// The first moment from `from` whose pc is named `name` (`open@plt+0`). +fn at(rec: *canim.Recording, from: u64, name: []const u8) u64 { + var i = from; + while (i < rec.end()) : (i += 1) if (std.mem.eql(u8, rec.strings.get(rec.register(i, "rip")) orelse "", name)) return i; + return rec.end(); +} + +/// The first moment from `from` whose instruction is `text`. +fn on(rec: *canim.Recording, from: u64, text: []const u8) u64 { + var buf: [256]u8 = undefined; + var i = from; + while (i < rec.end()) : (i += 1) if (rec.instruction(i, rec.register(i, "rip"), &buf)) |here| if (std.mem.startsWith(u8, here.text, text)) return i; + return rec.end(); +} fn frame(s: *anim.Frame) void { const rec = canim.open(recordings.hello); - // 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 }; - const ctx = canim.context(s, at, .{ .split = split, .syscalls = true }); - // The lens: the kernel's side of each call. - const kernel = canim.crossing(s, .{ .cursor = at, .stage = ctx.stage, .focus = true }); - ctx.map.add(s, canim.Crossing{ .cursor = at, .stage = ctx.map.stage }); + const main = rec.call("main", 0); + var cur = canim.cursor(s, rec, main.enter); + const stub = at(rec, main.enter, "open@plt+0"); + const crossing = on(rec, stub, "syscall"); + const back = on(rec, crossing, "ret"); + const done = rec.lineMoment(10, back); + cur.journey(.moment, done); + cur.levels = .{ .source_rows = 8, .fire = .disasm }; + const ctx = canim.context(s, cur, .{ .split = canim.layout.split.beside, .syscalls = true, .descent = true }); + const log = canim.crossing(s, .{ .cursor = cur, .stage = ctx.stage, .focus = true }); + ctx.map.add(s, canim.Crossing{ .cursor = cur, .stage = ctx.map.stage }); var says: canim.Narrator = .{}; const t = canim.theme.time; - 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)); + canim.establish(s, .{ ctx.clock, ctx.registers, ctx.stack, ctx.source, ctx.disasm, log, joins }); + + says.line(s, "A program cannot open a file itself.\nIt asks the kernel, and waits."); + cur.walk(s, .line, rec.lineMoment(6, main.enter)); + cur.walk(s, .moment, stub - 1); + says.line(s, "`main` calls `open` by its stub in the PLT. The arguments\nare in rdi and rsi: \"note\" and O_RDONLY."); + canim.descent.step(cur, s, .moment); + s.wait(t.phrase_rest); + says.line(s, "The call went down: main's window keeps its call, ringed;\nthe stub's jmp reads the GOT, and goes on to libc."); + canim.descent.step(cur, s, .moment); + s.wait(t.phrase_rest); + says.line(s, "libc's `open` is a wrapper: it puts openat's number in rax\nand its arguments in rdi, rsi, rdx and r10."); + cur.hurry(s, .moment, crossing, .{}); + says.line(s, "`syscall` crosses down. The kernel opens the file\nand answers in rax: 3, the descriptor."); + canim.descent.step(cur, s, .moment); + s.wait(t.phrase_rest); + cur.hurry(s, .moment, back, .{}); + says.line(s, "`open`'s ret comes straight back to main: the stub\nwas a jump, not a call. The windows close up."); + canim.descent.step(cur, s, .moment); + s.wait(t.phrase_rest); - // One call a phrase: its caption while nothing moves, then the crossing. + // The other three, stepped over: each crossing opens under its call. + const lines = [_][]const u8{ + "`read`: the kernel copies the file's bytes into `buf`,\nand says how many.", + "`close`: the number is handed back.", + "`write`: the same bytes go the other way,\nfrom `buf` to file number 1, the output.", + }; + cur.walk(s, .line, rec.lineMoment(7, back)); for (lines) |line| { says.line(s, line); - canim.syscalls.step(at, s, .line); + canim.syscalls.step(cur, s, .line); s.wait(t.phrase_rest); } + cur.walk(s, .line, done); says.close(s); } diff --git a/anim/src/Recording.zig b/anim/src/Recording.zig index 833d17b..1a4d859 100644 --- a/anim/src/Recording.zig +++ b/anim/src/Recording.zig @@ -218,6 +218,14 @@ pub fn ownLine(r: *const Recording, i: u64) ?u32 { return l.line; } +/// Whether the pc at moment `i` is in the program's own source: not in a +/// library's code, a PLT stub, the vDSO (where `own` keeps the last line). +pub fn sourced(r: *const Recording, i: u64) bool { + var buf: [256]u8 = undefined; + const here = r.instruction(i, r.register(i, "rip"), &buf) orelse return r.ownLine(i) != null; + return here.line != null; +} + /// The first line a source panel of `fit` lines shows when the program is /// on `line`: the whole file when it fits; else a window that has the line /// in its middle third, and is the same window for every line of that @@ -425,7 +433,13 @@ fn index(r: *Recording) !void { try touch_list.append(arena, touched); pending = touched; try branch_list.append(arena, branched); - if (ours and regs != null) try code_lines.put(gpa, regs.?.rip, line.line); + // Not where the instruction says it has no line: a library's code (a + // PLT stub, libc) keeps the last line of ours in `lines`, and is not of it. + if (ours and regs != null) { + var text: [256]u8 = undefined; + const here = zt.telescope.instruction(m, regs.?.rip, &text) catch null; + if (here == null or here.?.line != null) try code_lines.put(gpa, regs.?.rip, line.line); + } try registers.append(arena, regs orelse before orelse .{}); if (!told and stepped and regs != null and before != null) { diff --git a/anim/src/calls.zig b/anim/src/calls.zig index 5eef946..d78c26c 100644 --- a/anim/src/calls.zig +++ b/anim/src/calls.zig @@ -127,8 +127,8 @@ pub const Tree = struct { } } - /// Its view: the backtrace, the waiting path read as rows, newest on - /// top, with each call's arguments (`n=4`) and where it is. + /// Its view: the backtrace, the waiting path read as rows, newest at + /// the bottom, 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; @@ -143,10 +143,12 @@ pub const Tree = struct { 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 body = u.panel(box.w, box.h, "backtrace", .{ .note = u.print("the calls waiting \u{00b7} {s}", .{context.newestAtBottom(u, chain.len, room)}) }); 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; + // Newest at the bottom, as the tree grows down beside it; the oldest go from the top. + const shown = @min(chain.len, room); + for (chain[0..shown], 0..) |frame, i| { + const y = body.y + cm.pad + @as(f32, @floatFromInt(shown - 1 - 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. rows.callRow(u, y, box.w, i, name, context.callArguments(u, rec, open, i, frame.pc), context.frameWhere(u, rec, now.marked(), i, frame.pc), i == 0); diff --git a/anim/src/context.zig b/anim/src/context.zig index e5a226a..6123d26 100644 --- a/anim/src/context.zig +++ b/anim/src/context.zig @@ -140,7 +140,9 @@ pub const Registers = struct { if (age) |a| changed = rec.register(now.stops[a], "eflags") ^ rec.register(now.stops[a + 1], "eflags"); const heat = now.register(eflags_index, delay); const held = if (r.quiet) 0 else heat.level * heat.corner; - rows.rip(u, y, w, rec.moment(moment), rec.register(moment, "rip"), flags, changed, held, 0); + // While a conditional jump runs, the flags it reads are framed (an echo of the row that set them). + const reads: u64 = if (now.resting() or now.advancing() >= 0.5) 0 else @import("disasm.zig").readsFlags(rec, now.stops[1]); + rows.rip(u, y, w, rec.moment(moment), rec.register(moment, "rip"), flags, changed, held, 0, reads, now.reading(.cpu, 0)); } 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 { @@ -288,8 +290,10 @@ fn callLine(rec: *const Recording, moment: u64, ret: u64) ?u32 { /// 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}); - if (std.mem.indexOfScalar(u8, name, '!') != null) return ui.symbol(u, name); - return name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len]; + const shown = ui.symbol(u, name); + // A library's symbol (`libc.so.6!open+0`) by its name alone; one with none, `libc+27781`. + if (std.mem.indexOfScalar(u8, name, '!') != null and shown.ptr != name.ptr + std.mem.indexOfScalar(u8, name, '!').? + 1) return shown; + return shown[0 .. std.mem.lastIndexOfScalar(u8, shown, '+') orelse shown.len]; } /// The registers (of the sixteen) that hold `addr` in `regs`. @@ -489,7 +493,7 @@ pub const Stack = struct { for (pointers.items) |p_| { const word, const saved = p_; if (saved and !(now.writeAge(word.addr, 8) == 0 or now.wasRead(word.addr, 8))) continue; - hexdump.pointerArcs(&arcs, now, word.addr, word.y, at_rows.items, 8, .{ top - m.pad, box.h - m.pad }, false); + hexdump.pointerArcs(&arcs, now, word.addr, word.y, at_rows.items, 8, .{ top - m.pad, box.h - m.pad }, false, false); } arcs.draw(v, theme.metric.arc.stack_lanes); // Where the window is, for a link to a word outside it. @@ -659,30 +663,33 @@ pub const Backtrace = struct { const arrive = std.math.clamp((since - time.quick / 2.0 - time.move) / time.quick, 0, 1); const room = rowsOf(box); const total = chains[if (slide >= 0.5) 1 else 0].len; - const body = u.panel(box.w, box.h, "backtrace", .{ .focus = b.focus, .note = if (total > room) u.print("newest on top \u{00b7} {d} more", .{total - room}) else "newest on top" }); + const body = u.panel(box.w, box.h, "backtrace", .{ .focus = b.focus, .note = newestAtBottom(u, total, room) }); clipBody(u, box); defer u.unclip(); const opens = [2][]const Recording.Call{ rec.stack(u.f.scratch, now.stops[1]), rec.stack(u.f.scratch, now.stops[0]) }; const top = body.y + m.pad; + // Newest at the bottom, `#0` last: a frame's row is its place from + // the oldest, less the oldest that do not fit (dropped from the top). + const dropped = [2]usize{ chains[0].len -| room, chains[1].len -| room }; for (chains, 0..) |chain, side| { const shows = if (side == 0) 1 - leave else arrive; - for (chain[0..@min(chain.len, room + shared)], 0..) |frame, i| { + for (chain, 0..) |frame, i| { const from_end = chain.len - 1 - i; const kept = from_end < shared; // A frame both have is drawn once, from the old chain to its place in the new. if (kept and side == 1) continue; - var at_row: f32 = @floatFromInt(i); + var at_row = @as(f32, @floatFromInt(from_end)) - @as(f32, @floatFromInt(dropped[side])); var depth = i; var which = side; if (kept) { const to = chains[1].len - 1 - from_end; - at_row = std.math.lerp(at_row, @as(f32, @floatFromInt(to)), slide); + at_row = std.math.lerp(at_row, @as(f32, @floatFromInt(from_end)) - @as(f32, @floatFromInt(dropped[1])), slide); if (slide >= 0.5) { depth = to; which = 1; } } else if (shows <= 0) continue; - if (at_row >= @as(f32, @floatFromInt(room))) continue; + if (at_row <= -1 or at_row >= @as(f32, @floatFromInt(room))) continue; const v = if (kept) u else u.faded(shows); const name = ui.symbol(u, rec.strings.get(frame.pc) orelse u.print("{x}", .{frame.pc})); rows.callRow(v, top + at_row * m.row, box.w, depth, name, callArguments(u, rec, opens[which], depth, frame.pc), frameWhere(u, rec, if (which == 1) now.marks[1] else now.marks[0], depth, frame.pc), depth == 0); @@ -692,6 +699,12 @@ pub const Backtrace = struct { } }; +/// A backtrace's tag note: `newest at the bottom`, and how many of the +/// oldest a panel of `room` rows leaves out above. +pub fn newestAtBottom(u: ui.Ui, total: usize, room: usize) []const u8 { + return if (total > room) u.print("newest at the bottom \u{00b7} {d} more above", .{total - room}) else "newest at the bottom"; +} + test "the flags' bits" { try std.testing.expectEqual(@as(?usize, 17), index("eflags")); } diff --git a/anim/src/descent.zig b/anim/src/descent.zig new file mode 100644 index 0000000..302de38 --- /dev/null +++ b/anim/src/descent.zig @@ -0,0 +1,620 @@ +//! `descent` (design/README.md, "3. Panels"): the disassembly a level up, +//! a call followed down. The panel is a stack of windows, one a call deep: +//! the scene's function's on top, each callee's under the row that called +//! it (that row `waiting`, ringed; a PLT stub gone through keeps its `jmp`, +//! `pass`), a head row over each, the call lane from ring to head; and +//! under the deepest, while a system call crosses, the kernel on vellum. +//! Down is deeper, and the way back up is drawn. +//! +//! Every row has a key (an instruction's address, a head's function), so +//! the panel at one moment and at the next are two lists of the same +//! rows: a step is the rows both have gliding, and the others leaving or +//! arriving, on the timetable of its verb (`descend`, `ascend`, `cross`; +//! design/motion.md, "A call followed down", "A system call"). +const std = @import("std"); +const sk = @import("sketch"); +const anim = @import("anim"); +const ui = @import("ui.zig"); +const rows = @import("rows.zig"); +const cursors = @import("cursor.zig"); +const Recording = @import("Recording.zig"); +const ties = @import("ties.zig"); +const map = @import("map.zig"); +const context = @import("context.zig"); +const disasm = @import("disasm.zig"); +const syscalls = @import("syscalls.zig"); +const Stage = @import("stage.zig").Stage; +const theme = ui.theme; +const Rect = ui.Rect; +const t = theme.color.text; +const k = theme.color.on_kernel; +const m = theme.metric.context; +const c = theme.metric.insn; +const size = theme.size.mono.context; +const adv = size * 3 / 5; +const Insn = disasm.Insn; + +/// Frames at 60 a second, as motion.md counts them. +fn f(n: f32) f32 { + return n / 60.0; +} + +fn clamp01(v: f32) f32 { + return std.math.clamp(v, 0, 1); +} + +/// One step of `by` from where the cursor is, timed as its verb +/// (design/motion.md, "A call followed down"): into a call (`descend`, 2.7 +/// s), on through a PLT stub's `jmp` (2.0 s), out by a `ret` (`ascend`, 2.3 +/// s), across into the kernel (`cross`: `syscalls.step`); any other walked. +pub fn step(cur: cursors.Cursor, s: *anim.Frame, by: Recording.Stop) void { + const rec = cur.rec; + const from = cur.moment(s); + const to = rec.next(by, from); + for (rec.syscalls) |made| if (made.enter > from and made.enter <= to) return syscalls.step(cur, s, by); + if (to != from + 1) return cur.walk(s, by, to); + const b = rec.insn_branches[from] orelse return cur.walk(s, by, to); + var name_buf: [256]u8 = undefined; + const here = (rec.moment(from).string(rec.register(from, "rip"), &name_buf) catch null) orelse ""; + const plan: cursors.Plan = switch (b.kind) { + .call => .{ .at = .{ f(24), f(60), f(60) }, .advance = f(126), .travel = f(12), .total = f(162) }, + .ret => .{ .at = .{ f(36), f(18), f(36) }, .advance = f(102), .travel = f(12), .total = f(138) }, + .jump => if (std.mem.indexOf(u8, here, "@plt") != null) .{ .at = .{ f(18), f(24), f(24) }, .advance = f(84), .travel = f(12), .total = f(120) } else return cur.walk(s, by, to), + .none => return cur.walk(s, by, to), + }; + cur.step(s, to, plan, plan.total); +} + +/// A row of the panel. +const Item = struct { + key: u64, + row: f32, + /// The window it is in, 0 the top. + window: u8, + what: union(enum) { insn: Insn, head: struct { name: []const u8, note: []const u8 }, more: []const u8 }, + state: enum { plain, waiting, pass, current } = .plain, + /// A waiting or passed row: the moment it ran. + at: u64 = 0, +}; + +/// The panel at a moment. +const Layout = struct { + items: []Item, + /// Windows of code (a fold counts as none). + windows: usize, + /// The bottom three rows are the kernel's (the pc is at, or has just + /// come back from, a `syscall`). + kernel: bool, + /// The deepest function and its module: the panel's tag. + tag: []const u8, + in_stub: bool, +}; + +pub const Descent = struct { + cursor: cursors.Cursor, + stage: *const Stage, + focus: bool = false, + /// The function whose window is on top: where the scene follows from. + root: []const u8 = "main", + + pub fn draw(d: *const Descent, fr: *sk.Frame, placed: anim.Placed) void { + const box = d.stage.box(placed, .disasm); + const u = context.at(fr, placed, box); + const now = d.cursor.now(placed); + const rec = d.cursor.rec; + const room = theme.layout.rowsIn(box.h); + const before = layout(u, rec, now.stops[1], room, d.root); + const after = layout(u, rec, now.stops[0], room, d.root); + const tm = now.time; + const going = now.advancing(); + const kind: enum { same, down, through, up } = if (now.resting() or now.stops[0] == now.stops[1]) .same else if (after.windows > before.windows) (if (before.in_stub) .through else .down) else if (after.windows < before.windows) .up else .same; + const shown = if (going >= 0.5) after else before; + const body = u.panel(box.w, box.h, "disassembly", .{ .focus = d.focus, .note = shown.tag }); + const top = body.y + m.pad; + u.clip(.{ .x = theme.stroke.rule, .y = m.tag, .w = box.w - 2 * theme.stroke.rule, .h = box.h - m.tag - theme.stroke.rule }); + defer u.unclip(); + + // How far the rows both lists have are on their way, and how much + // of each that leaves or comes shows: the verb's timetable. + const move: f32 = switch (kind) { + .same => cursors.glide(going), + .down => cursors.glide(clamp01((tm - f(72)) / f(18))), + .through => cursors.glide(clamp01((tm - f(24)) / f(18))), + .up => cursors.glide(clamp01((tm - f(84)) / f(18))), + }; + const Placed = struct { item: Item, y: f32, shows: f32, rise: f32, old: ?Item, new: ?Item }; + var placed_items: std.ArrayList(Placed) = .empty; + const a = u.f.scratch; + // Leaving: bottom up when a window closes, all at once when a caller gives up rows. + var leaving: usize = 0; + var i = before.items.len; + while (i > 0) { + i -= 1; + const it = before.items[i]; + if (find(after.items, it.key)) |_| continue; + const shows: f32 = switch (kind) { + .same => 1 - clamp01(2 * going), + .down => 1 - clamp01((tm - f(66)) / f(12)), + .through => 1 - clamp01((tm - f(24)) / f(12)), + .up => 1 - clamp01((tm - f(48) - @as(f32, @floatFromInt(leaving)) * f(2)) / f(12)), + }; + leaving += 1; + placed_items.append(a, .{ .item = it, .y = top + it.row * m.row, .shows = shows, .rise = 0, .old = it, .new = null }) catch {}; + } + // Arriving: a head rising, then its rows top down, 2 f apart. + var arriving: usize = 0; + for (after.items) |it| { + if (find(before.items, it.key)) |old| { + const y = top + std.math.lerp(old.row, it.row, move) * m.row; + // Going up the rows keep what they were (the ring) until the advance. + const now_item = switch (kind) { + .same, .up => if (going >= 0.5) it else old, + // The call row is current until its plaque becomes the ring; a stub's jmp until it passes. + .down => if (tm >= f(72)) it else old, + .through => if (tm >= f(24)) it else old, + }; + placed_items.append(a, .{ .item = now_item, .y = y, .shows = 1, .rise = 0, .old = old, .new = it }) catch {}; + continue; + } + const head = it.what == .head; + const shows: f32 = switch (kind) { + .same => clamp01(2 * going - 1), + .down => if (head) clamp01((tm - f(96)) / f(12)) else clamp01((tm - f(102) - @as(f32, @floatFromInt(arriving)) * f(2)) / f(12)), + .through => if (head) clamp01((tm - f(54)) / f(12)) else clamp01((tm - f(60) - @as(f32, @floatFromInt(arriving)) * f(2)) / f(12)), + .up => clamp01((tm - f(84)) / f(18)), + }; + if (!head) arriving += 1; + placed_items.append(a, .{ .item = it, .y = top + it.row * m.row, .shows = shows, .rise = if (head and kind != .same) (1 - cursors.standard(shows)) * theme.time.caption_rise else 0, .old = null, .new = it }) catch {}; + } + std.mem.sort(Placed, placed_items.items, {}, struct { + fn above(_: void, x: Placed, y: Placed) bool { + return x.y < y.y; + } + }.above); + + // The marks: the pc's plaque, leaving the row it was on and landing + // on the next; the ring on a waiting call; a passed stub's bar. + const marked = now.marks[if (going >= 0.5) 1 else 0]; + const plaque = [2]f32{ + // The one it leaves: in a descend it becomes the ring (72 to 84 f), + // through a stub the pass bar (24 to 36), up it closes with its window. + switch (kind) { + .same => 1, + .down => 1 - clamp01((tm - f(72)) / f(12)), + .through => 1 - clamp01((tm - f(24)) / f(12)), + .up => 1 - clamp01((tm - f(48)) / f(12)), + }, + // The one it lands on, with the advance. + if (kind == .same) 1 else clamp01(going * 2), + }; + var pc_y = [2]?f32{ null, null }; + for (placed_items.items) |p| { + if (p.old) |o| if (o.state == .current) { + pc_y[0] = p.y; + }; + if (p.new) |n| if (n.state == .current) { + pc_y[1] = p.y; + }; + } + // In one window the plaque slides from row to row, with the advance. + var mark: ?struct { y: f32, shows: f32 } = null; + if (kind == .same) { + if (pc_y[0] != null and pc_y[1] != null) mark = .{ .y = std.math.lerp(pc_y[0].?, pc_y[1].?, cursors.standard(going)), .shows = 1 } else if (pc_y[1]) |y| { + mark = .{ .y = y, .shows = clamp01(2 * going - 1) }; + } else if (pc_y[0]) |y| { + mark = .{ .y = y, .shows = 1 - clamp01(2 * going) }; + } + } + const fire = now.fires(.disasm); + if (mark) |mk| plaqueAt(u, box.w, mk.y, mk.shows, fire) else { + if (pc_y[0]) |y| if (going < 0.5) plaqueAt(u, box.w, y, plaque[0], fire); + if (pc_y[1]) |y| if (going >= 0.5) plaqueAt(u, box.w, y, plaque[1], 0); + } + + // Which rows ran in the last three steps: the trail. + const ran = recentRows(a, now, if (going >= 0.5) 0 else 1); + const current_line = rec.own[marked]; + const widen0 = rows.numberRoom(rec.line_count); + var covered: usize = 0; + var runs: disasm.Runs = .{}; + var last_line: ?u32 = null; + var last_window: ?u8 = null; + const dd: disasm.Disasm = .{ .cursor = d.cursor, .stage = d.stage }; + const base: usize = if (going >= 0.5) 0 else 1; + for (placed_items.items) |p| { + const v = u.faded(p.shows); + const y = p.y + p.rise; + if (p.shows <= 0) continue; + if (last_window == null or last_window.? != p.item.window) last_line = null; + last_window = p.item.window; + switch (p.item.what) { + .head => |h| { + v.fill(.{ .x = theme.stroke.rule, .y = y, .w = box.w - 2 * theme.stroke.rule, .h = theme.stroke.rule }, theme.color.rule); + v.text(.sans_medium, theme.size.sans.micro, c.address, y + 18, h.name, t.primary); + v.text(.sans, theme.size.sans.micro, box.w - m.side - v.width(.sans, theme.size.sans.micro, h.note), y + 18, h.note, t.faint); + covered -|= 1; + }, + .more => |words| { + _ = v.arrow(c.address, y + m.row / 2, .more); + v.text(.mono, size, c.address + m.arrow_w + adv, rows.baseline(y), words, t.faint); + covered -|= 1; + }, + .insn => |row| { + const window_items = windowOf(placed_items.items, p.item.window); + var addrs: [80]u64 = undefined; + var n: usize = 0; + for (window_items) |w| if (w.item.what == .insn and n < addrs.len) { + addrs[n] = w.item.key; + n += 1; + }; + const lead = ui.shared(addrs[0..n]); + const wide = @as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv; + const line = if (row.outside) null else row.line; + const state: disasm.Disasm.State = switch (p.item.state) { + // The row the plaque has not reached yet is ahead. + .current => if (p.old == null or p.old.?.state != .current) (if (going >= 0.5) .current else .ahead) else if (p.new == null or p.new.?.state != .current) (if (going < 0.5) .current else .ahead) else .current, + .waiting => .{ .waiting = p.item.at }, + .pass => .{ .ran = .{ .k = 0, .at = p.item.at } }, + .plain => if (ranOf(ran, row.addr)) |r| .{ .ran = r } else .ahead, + }; + // The marks at the row's left: the trail, the ring, the pass. + switch (p.item.state) { + .plain => if (ranOf(ran, row.addr)) |r| v.trail(c.mark, y, r.k), + .pass => v.trail(c.mark, y, 0), + .waiting => { + // The ring comes as the plaque leaves; going up it becomes a trail bar. + const ring: f32 = if (p.old != null and p.old.?.state == .waiting) (if (kind == .up) 1 - clamp01((tm - f(102)) / f(12)) else 1) else if (kind == .down) clamp01((tm - f(72)) / f(12)) else 1; + ringAt(v.faded(ring), y); + if (ring < 1) v.faded(1 - ring).trail(c.mark, y, 0); + }, + .current => {}, + } + runs.add(line != null and line.? == current_line, y, y + m.row); + const hangs = dd.insn(v, now, row, y, box.w, widen0 + wide, line, line != last_line, current_line, lead, state, base, covered > 0, .{ addrs[0], addrs[n -| 1] }, null); + covered = @max(covered -| 1, hangs); + last_line = line; + map.row(.disasm, row.addr, u, .{ .x = 0, .y = y, .w = box.w, .h = m.row }); + }, + } + } + runs.add(false, box.h, box.h); + disasm.threadRuns(u, box.w, .{ .{}, runs }, 1); + + // The call lane: from each waiting ring (or passed jmp) down to the + // head of the window under it, turning in to its name. + for (placed_items.items) |p| { + if (p.item.what != .head or p.item.window == 0) continue; + const from = for (placed_items.items) |q| { + if (q.item.window + 1 == p.item.window and (q.item.state == .waiting or q.item.state == .pass)) break q; + } else continue; + const drawn: f32 = if (p.old != null and p.new != null) 1 else if (p.new != null) switch (kind) { + .down => clamp01((tm - f(84)) / f(18)), + .through => clamp01((tm - f(42)) / f(18)), + else => clamp01(2 * going - 1), + } else switch (kind) { + .up => 1 - clamp01((tm - f(72)) / f(12)), + else => 1 - clamp01(2 * going), + }; + if (drawn <= 0) continue; + const ya = from.y + m.row - 3; + const yb = p.y + m.row / 2; + u.route(&.{ .{ 14, ya }, .{ 14, yb }, .{ c.address - 4, yb } }, t.primary, .{ .width = theme.stroke.rule, .head = .{ 7, 8 }, .radius = 4, .progress = cursors.standard(drawn) }); + } + map.window(.disasm, first(shown), last(shown)); + if (pc_y[1] orelse pc_y[0]) |y| ties.anchor(u, .pc, .{ .x = 0, .y = y, .w = theme.metric.plaque.pc, .h = m.row }); + kernel(u, now, box, top, room, pc_y[0] orelse pc_y[1]); + context.veiled(u, box, now.veil); + } +}; + +/// The pc's plaque on the row at `y`. +fn plaqueAt(u: ui.Ui, w: f32, y: f32, shows: f32, fire: f32) void { + if (shows <= 0) return; + const v = u.faded(shows); + v.current(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = m.row }, theme.metric.plaque.pc, fire); + sk.draw.polygon(u.f, &.{ .{ 20, y + m.row / 2 }, .{ 10, y + 6 }, .{ 10, y + m.row - 6 } }, v.at.pen(.{ .fill = ui.rgb(theme.mark(.current).on_solid) })); +} + +/// `waiting`: the plaque's place ringed, a 2-unit primary frame 24 by 24 +/// with a primary head in it, as a waiting call node is; no wash. +fn ringAt(u: ui.Ui, y: f32) void { + u.frame(.{ .x = c.mark + 1, .y = y + 1, .w = 22, .h = 22 }, t.primary, theme.stroke.rule); + sk.draw.polygon(u.f, &.{ .{ 19, y + m.row / 2 }, .{ 10, y + 7 }, .{ 10, y + m.row - 7 } }, u.at.pen(.{ .fill = ui.rgb(t.primary) })); +} + +fn find(items: []const Item, key: u64) ?Item { + for (items) |it| if (it.key == key) return it; + return null; +} + +fn windowOf(items: anytype, window: u8) @TypeOf(items) { + var lo: usize = items.len; + var hi: usize = 0; + for (items, 0..) |p, j| if (p.item.window == window) { + lo = @min(lo, j); + hi = j + 1; + }; + return if (lo < hi) items[lo..hi] else items[0..0]; +} + +fn first(l: Layout) u64 { + for (l.items) |it| if (it.what == .insn) return it.key; + return 0; +} + +fn last(l: Layout) u64 { + var out: u64 = 0; + for (l.items) |it| if (it.what == .insn) { + out = it.key; + }; + return out; +} + +const Ran = disasm.Disasm.Ran; +const RanRow = struct { addr: u64, ran: Ran }; + +/// The rows the last three steps ran (`base`: 1 while the mark is still +/// on the step's first row), the newest step's mark on each. +fn recentRows(a: std.mem.Allocator, now: cursors.Now, base: usize) []const RanRow { + var out: std.ArrayList(RanRow) = .empty; + for (0..3) |s| { + const from = now.stops[@min(base + 1 + s, now.stops.len - 1)]; + const to = now.stops[base + s]; + var at = to; + while (at > from and to - at < 512) { + at -= 1; + const pc = now.rec.register(at, "rip"); + if (ranOf(out.items, pc) == null) out.append(a, .{ .addr = pc, .ran = .{ .k = s, .at = at } }) catch break; + // A return marks the call it comes back from: it has run, with its result. + if (now.rec.insn_branches[at]) |b| if (b.kind == .ret) { + var buf: [256]u8 = undefined; + const after = now.rec.instruction(at, b.to, &buf) orelse continue; + if (after.back == 0) continue; + const call = b.to - after.back; + if (ranOf(out.items, call) == null) out.append(a, .{ .addr = call, .ran = .{ .k = s, .at = madeAt(now.rec, at, call) } }) catch break; + }; + } + } + return out.items; +} + +fn ranOf(list: []const RanRow, addr: u64) ?Ran { + for (list) |r| if (r.addr == addr) return r.ran; + return null; +} + +/// A level of the descent: a function's window. +const Level = struct { at: u64, kind: enum { caller, pass, deepest }, name: []const u8, moment: u64 = 0 }; + +/// The panel at moment `i`, `room` rows: the root's window on top, a +/// window a call deep under it, the deepest round the pc, three at most +/// (a longer chain keeps the first and the last two, the rest one row). +fn layout(u: ui.Ui, rec: *const Recording, i: u64, room: usize, root: []const u8) Layout { + const a = u.f.scratch; + var items: std.ArrayList(Item) = .empty; + const pc = rec.register(i, "rip"); + var buf: [24]context.Frame = undefined; + const chain = context.frames(rec, i, &buf); + var r: usize = 0; + for (chain, 0..) |fr, j| if (std.mem.eql(u8, context.frameName(u, rec, fr.pc), root)) { + r = j; + break; + }; + var levels: [24]Level = undefined; + var n: usize = 0; + var j = r; + while (j > 0 and n + 2 < levels.len) : (j -= 1) { + const call = callBefore(u, rec, i, chain[j].pc) orelse break; + levels[n] = .{ .at = call.addr, .kind = .caller, .name = context.frameName(u, rec, chain[j].pc), .moment = madeAt(rec, i, call.addr) }; + n += 1; + // Through a stub to a function that is not it: the stub's jmp, passed. + if (disasm.target(call)) |to| { + const stub = context.frameName(u, rec, to); + if (std.mem.endsWith(u8, stub, "@plt") and !std.mem.eql(u8, stub, context.frameName(u, rec, chain[j - 1].pc))) { + levels[n] = .{ .at = to, .kind = .pass, .name = stub, .moment = madeAt(rec, i, to) }; + n += 1; + } + } + } + const here = context.frameName(u, rec, pc); + const in_stub = std.mem.endsWith(u8, here, "@plt"); + levels[n] = .{ .at = pc, .kind = .deepest, .name = here }; + n += 1; + // Folded past three windows: the first, then a row of `more`, then the last two. + var fold: []const u8 = ""; + var kept: []const Level = levels[0..n]; + var kept_buf: [3]Level = undefined; + if (n > 3) { + fold = u.print("{d} calls:", .{n - 3}); + for (levels[1 .. n - 2]) |l| fold = u.print("{s} {s}", .{ fold, l.name }); + kept_buf = .{ levels[0], levels[n - 2], levels[n - 1] }; + kept = &kept_buf; + } + // At a `syscall`, or just back from one: the floor is the kernel's. + const at_syscall = isSyscall(rec, i, pc) or (i > 0 and isSyscall(rec, i - 1, rec.register(i - 1, "rip")) and rec.register(i - 1, "rip") + 2 == pc); + var fixed: usize = if (at_syscall and kept.len > 1) 3 else 0; + for (kept, 0..) |l, li| { + if (li > 0) fixed += 1; + fixed += switch (l.kind) { + .caller => 3, + .pass => 1, + .deepest => 0, + }; + } + if (fold.len > 0) fixed += 1; + const remaining = room -| fixed; + const deepest_rows = if (kept.len == 1) room else if (in_stub) @min(remaining, stubRows(rec, i, pc)) else remaining; + const extra = remaining -| deepest_rows; + var row: f32 = 0; + var tag: []const u8 = ""; + for (kept, 0..) |l, li| { + const window: u8 = @intCast(li); + if (li == 1 and fold.len > 0) { + items.append(a, .{ .key = std.hash.Wyhash.hash(1, fold), .row = row, .window = window, .what = .{ .more = fold } }) catch {}; + row += 1; + } + if (li > 0) { + items.append(a, .{ .key = std.hash.Wyhash.hash(0, l.name) | 1 << 63, .row = row, .window = window, .what = .{ .head = .{ .name = l.name, .note = headNote(u, rec, i, l) } } }) catch {}; + row += 1; + } + const nearest = li + 2 == kept.len and l.kind == .caller; + const count: usize = switch (l.kind) { + .caller => 3 + if (nearest) extra else 0, + .pass => 1, + .deepest => deepest_rows, + }; + const above: usize = switch (l.kind) { + .caller => (count - 1) / 2, + .pass => 0, + // Under a `syscall` four rows hold its arguments. + .deepest => if (in_stub) 0 else if (isSyscall(rec, i, pc) and count > 5) count - 5 else (count -| 1) / 2, + }; + const list = disasm.listingAt(u, rec, i, l.at, count, above); + for (list.rows, 0..) |insn, q| { + const on = q == list.pc; + items.append(a, .{ .key = insn.addr, .row = row + @as(f32, @floatFromInt(q)), .window = window, .what = .{ .insn = insn }, .state = if (!on) .plain else switch (l.kind) { + .caller => .waiting, + .pass => .pass, + .deepest => .current, + }, .at = l.moment }) catch {}; + } + row += @floatFromInt(count); + if (l.kind == .deepest) tag = if (kept.len == 1) l.name else u.print("{s} \u{00b7} {s}", .{ l.name, moduleOf(u, rec, i, pc) }); + } + return .{ .items = items.items, .windows = kept.len, .kernel = at_syscall, .tag = tag, .in_stub = in_stub }; +} + +/// The call instruction a return address `ret` comes back after. +fn callBefore(u: ui.Ui, rec: *const Recording, i: u64, ret: u64) ?Insn { + var buf: [256]u8 = undefined; + const after = rec.instruction(i, ret, &buf) orelse return null; + if (after.back == 0) return null; + const at = ret - after.back; + const call = rec.instruction(i, at, &buf) orelse return null; + if (!std.mem.startsWith(u8, call.text, "call")) return null; + return .{ .addr = at, .len = call.len, .text = u.print("{s}", .{call.text}) }; +} + +/// The moment the instruction at `addr` last ran, at or before `i`. +fn madeAt(rec: *const Recording, i: u64, addr: u64) u64 { + var at = i; + while (at > 0 and i - at < 4096) : (at -= 1) if (rec.register(at, "rip") == addr) return at; + return i; +} + +fn isSyscall(rec: *const Recording, i: u64, pc: u64) bool { + var buf: [256]u8 = undefined; + const here = rec.instruction(i, pc, &buf) orelse return false; + return std.mem.eql(u8, here.text, "syscall"); +} + +/// How many instructions a PLT stub at `pc` has (three: its `jmp`, a push, a jmp to the resolver). +fn stubRows(rec: *const Recording, i: u64, pc: u64) usize { + var buf: [256]u8 = undefined; + var at = pc; + var n: usize = 0; + while (n < 4) : (n += 1) { + const one = rec.instruction(i, at, &buf) orelse break; + if (n > 0 and one.back == 0) break; + at += one.len; + } + return @max(n, 1); +} + +/// A window's head note: what the code is (`libc.so.6 · no source`, +/// `the PLT · its jmp reads open@got, 403fd8`, the program's file). +fn headNote(u: ui.Ui, rec: *const Recording, i: u64, l: Level) []const u8 { + if (std.mem.endsWith(u8, l.name, "@plt")) { + if (l.kind == .pass) return "the PLT, jumped through"; + var buf: [256]u8 = undefined; + const jmp = rec.instruction(i, l.at, &buf) orelse return "the PLT"; + const ops = std.mem.trim(u8, jmp.text[(std.mem.indexOfScalar(u8, jmp.text, ' ') orelse jmp.text.len)..], " "); + const at = std.mem.indexOf(u8, ops, "[rip + 0x") orelse return "the PLT"; + const close = std.mem.indexOfScalarPos(u8, ops, at, ']') orelse return "the PLT"; + const slot = l.at + jmp.len + (std.fmt.parseInt(u64, ops[at + 9 .. close], 16) catch return "the PLT"); + const named = ui.symbol(u, rec.strings.get(slot) orelse ""); + return u.print("the PLT \u{00b7} its jmp reads {s}, {x}", .{ named[0 .. std.mem.lastIndexOfScalar(u8, named, '+') orelse named.len], slot }); + } + const module = moduleOf(u, rec, i, l.at); + if (std.mem.eql(u8, module, "[vdso]")) return "vdso \u{00b7} the kernel's code, run here"; + var buf: [256]u8 = undefined; + if ((@import("ztrace").telescope.instruction(rec.moment(i), l.at, &buf) catch null)) |here| if (here.line != null) return rec.file; + return u.print("{s} \u{00b7} no source", .{module}); +} + +/// The file `addr`'s mapping is of, by its base name. +fn moduleOf(u: ui.Ui, rec: *const Recording, i: u64, addr: u64) []const u8 { + var name: []const u8 = ""; + var buf: [256]u8 = undefined; + _ = (rec.moment(i).mapping(addr, &name, &buf) catch null) orelse return ""; + return u.print("{s}", .{std.fs.path.basename(name)}); +} + +/// The kernel's window, at the floor, while a step crosses: the crossing +/// lane down from the pc's plaque, the vellum filling down from its head, +/// the head and the call in C's form, `returns` and what crossed back +/// with what it clobbered; the answer up the lane; and at the advance the +/// window drawing back up into the lane. +fn kernel(u: ui.Ui, now: cursors.Now, box: Rect, top: f32, room: usize, pc_y: ?f32) void { + if (!now.crossings or !now.walking()) return; + const made = syscalls.inStep(now) orelse return; + const rec = now.rec; + const p = syscalls.Plan.of(made); + const tm = now.time; + const y0 = top + @as(f32, @floatFromInt(room -| 3)) * m.row; + const from = (pc_y orelse y0 - m.row) + m.row; + const back_up = clamp01((tm - now.plan.advance) / f(12)); + // The lane: down 24 f from the plaque, 3 units of vellum; back into it after the window. + const down = cursors.standard(clamp01((tm - p.enters) / syscalls.Plan.cross)); + const lane_gone = clamp01((tm - now.plan.advance - f(12)) / f(12)); + if (down > 0 and lane_gone < 1) { + const end = std.math.lerp(from, y0 + 4, down * (1 - lane_gone)); + u.fill(.{ .x = 14 - 1.5, .y = from, .w = 3, .h = @max(end - from, 0) }, theme.color.kernel); + } + // The answer climbs the lane to the `syscall` row: a head of vellum going up it. + const climb = cursors.standard(clamp01((tm - p.back) / syscalls.Plan.cross)); + if (climb > 0 and climb < 1) { + const yh = std.math.lerp(y0, from, climb); + sk.draw.polygon(u.f, &.{ .{ 14, yh - 8 }, .{ 7, yh + 2 }, .{ 21, yh + 2 } }, u.at.pen(.{ .fill = ui.rgb(theme.color.kernel) })); + } + const opens = cursors.standard(clamp01((tm - p.enters - f(18)) / f(12))) * (1 - back_up); + if (opens <= 0) return; + const h = 3 * m.row * opens; + u.fill(.{ .x = theme.stroke.rule, .y = y0, .w = box.w - 2 * theme.stroke.rule, .h = h }, theme.color.kernel); + u.clip(.{ .x = 0, .y = y0, .w = box.w, .h = h }); + defer u.unclip(); + // The lane's head, in ink on the vellum. + sk.draw.polygon(u.f, &.{ .{ 14, y0 + 10 }, .{ 10, y0 + 2 }, .{ 18, y0 + 2 } }, u.at.pen(.{ .fill = ui.rgb(k.ink) })); + const name = @import("ztrace").syscalls.name(made.nr) orelse "syscall"; + const head = u.faded(clamp01((tm - p.enters - f(30)) / f(6))); + head.text(.sans_medium, theme.size.sans.micro, c.address, y0 + 18, "the kernel", k.ink); + const what = u.print("{s}, system call {d}", .{ name, made.nr }); + head.text(.sans, theme.size.sans.micro, box.w - m.side - u.width(.sans, theme.size.sans.micro, what), y0 + 18, what, k.dim); + // The call in C's form, as the kernel took it. + const names = @import("ztrace").syscalls.names(made.nr); + const n = @min(@import("ztrace").syscalls.signature(made.nr).len, 6); + var call: []const u8 = u.print("{s}(", .{name}); + for (0..n) |j| call = u.print("{s}{s}{s}", .{ call, if (j > 0) ", " else "", disasm.argument(u, rec, made.enter, if (j < names.len) names[j] else "", made.args[j]) }); + call = u.print("{s})", .{call}); + u.faded(clamp01((tm - p.enters - f(36)) / f(6))).text(.mono, size, c.address, rows.baseline(y0 + m.row), rows.fitted(u, call, box.w - m.side - c.address), k.ink); + // `returns`: the value, struck as it lands in the kernel's rows. + const ry = y0 + 2 * m.row; + const returns = tm - p.returns; + u.faded(clamp01((tm - p.enters - f(36)) / f(6))).text(.mono, size, c.address, rows.baseline(ry), "returns", k.dim); + if (returns >= 0 and made.exit != null) { + const got: i64 = @bitCast(made.result); + const value = u.print("{d}", .{got}); + const x = c.address + 8 * adv; + const cell: Rect = .{ .x = x, .y = ry, .w = @as(f32, @floatFromInt(value.len)) * adv, .h = m.row }; + const heat = now.heat(0, null, returns); + const ink = u.written(cell, heat) orelse ui.Ink{ .ink = ui.rgb(k.ink) }; + u.text(ink.face, size, x, rows.baseline(ry), value, ink.ink); + var end = x + cell.w + adv; + const on = rec.openOn(u.f.scratch, made.result, made.exit.? + 1); + if (std.mem.eql(u8, name, "openat") or std.mem.eql(u8, name, "open")) if (on.len > 0) { + u.text(.mono, size, end, rows.baseline(ry), on, k.dim); + end += u.width(.mono, size, on) + 2 * adv; + }; + u.text(.mono, size, end + adv, rows.baseline(ry), "rcx, r11: clobbered", k.dim); + } +} diff --git a/anim/src/disasm.zig b/anim/src/disasm.zig index 7f17ed6..0b6f931 100644 --- a/anim/src/disasm.zig +++ b/anim/src/disasm.zig @@ -41,8 +41,18 @@ pub const Insn = struct { /// A direct call's callee's parameter count. params: ?u8 = null, + /// Its mnemonic, with a prefix that is part of it (`rep stosq`). pub fn mnemonic(i: Insn) []const u8 { - return i.text[0 .. std.mem.indexOfScalar(u8, i.text, ' ') orelse i.text.len]; + const first = std.mem.indexOfScalar(u8, i.text, ' ') orelse return i.text; + for ([_][]const u8{ "rep", "repe", "repz", "repne", "repnz", "lock", "notrack", "bnd" }) |prefix| if (std.mem.eql(u8, i.text[0..first], prefix)) { + return i.text[0 .. std.mem.indexOfScalarPos(u8, i.text, first + 1, ' ') orelse i.text.len]; + }; + return i.text[0..first]; + } + + /// Padding, which touches nothing: drawn faint. + pub fn padding(i: Insn) bool { + return std.mem.startsWith(u8, i.mnemonic(), "nop") or std.mem.eql(u8, i.mnemonic(), "endbr64"); } pub fn operands(i: Insn) []const u8 { @@ -51,9 +61,11 @@ pub const Insn = struct { }; /// The window at a moment: the instructions, and which is the pc's. -const Listing = struct { rows: []Insn, pc: usize }; +pub const Listing = struct { rows: []Insn, pc: usize }; pub const Disasm = struct { + /// An instruction, as a row draws it. + pub const Row = Insn; cursor: cursors.Cursor, stage: *const Stage, focus: bool = false, @@ -171,6 +183,9 @@ pub const Disasm = struct { var lanes: [2]?f32 = .{ null, null }; // A call's arguments hang in the annotation column of the rows under it. var covered: usize = 0; + // What the window holds: a jump out of it says where it goes. + const window = [2]u64{ if (merged.len > 0) merged[0].addr else 0, if (merged.len > 0) merged[merged.len - 1].addr else 0 }; + const echo = jumpEcho(now, base); for (merged, 0..) |row, j| { const y = top + (@as(f32, @floatFromInt(j)) - scroll) * m.row; const line = if (row.outside) null else row.line; @@ -188,7 +203,7 @@ pub const Disasm = struct { const is_pc = row.addr == pc[if (going >= 0.5) 1 else 0]; const was = if (is_pc) null else ran[j]; if (was) |r| lit.trail(c.mark, y, r.k); - const hangs = d.insn(lit, now, row, y, box.w, widen, line, line != last_line, current_line, lead, if (is_pc) .current else if (was) |r| .{ .ran = r } else .ahead, base, covered > 0); + const hangs = d.insn(lit, now, row, y, box.w, widen, line, line != last_line, current_line, lead, if (is_pc) .current else if (was) |r| .{ .ran = r } else .ahead, base, covered > 0, window, echo); covered = @max(covered -| 1, hangs); last_line = if (above_body) null else line; if (jumped == row.addr and !is_pc) lanes[0] = y; @@ -205,9 +220,16 @@ pub const Disasm = struct { context.veiled(u, box, now.veil); } - const State = union(enum) { current, ran: Ran, ahead }; + pub const State = union(enum) { + current, + ran: Ran, + ahead, + /// A call whose callee's window is open under it (a `descent`): the + /// moment it was made. + waiting: u64, + }; /// A row that ran `k` steps ago (0 newest), last at moment `at`. - const Ran = struct { k: usize, at: u64 }; + pub const Ran = struct { k: usize, at: u64 }; /// `insn`: an instruction and its annotation, pwndbg's way. Nothing is /// cut that has room: the operands run on to where the annotation must @@ -215,7 +237,7 @@ pub const Disasm = struct { /// where the annotation carries the address they name. `covered`: a /// call's arguments above hang in this row's annotation column. Returns /// how many rows under it its own arguments hang in. - fn insn(d: *const Disasm, at: ui.Ui, now: cursors.Now, row: Insn, y: f32, w: f32, widen: f32, line: ?u32, first_of_line: bool, current_line: u32, lead: usize, state: State, base: usize, covered: bool) usize { + pub fn insn(d: *const Disasm, at: ui.Ui, now: cursors.Now, row: Insn, y: f32, w: f32, widen: f32, line: ?u32, first_of_line: bool, current_line: u32, lead: usize, state: State, base: usize, covered: bool, window: [2]u64, echo: ?Echo) usize { const rec = d.cursor.rec; const base_y = rows.baseline(y); const code_ink = theme.color.region.code_; @@ -228,8 +250,9 @@ pub const Disasm = struct { _ = at.address(c.address, base_y, row.addr, .{ .ink = ui.mix(code_ink, theme.color.page, theme.metric.context.lead_alpha) }); u.text(.mono, size, c.mnemonic, base_y, row.mnemonic(), t.faint); const name = if (rec.strings.get(row.addr)) |n| n[0 .. std.mem.lastIndexOfScalar(u8, n, '+') orelse n.len] else ""; - const x = if (name.len > 0) annotationX(operandsWidth(row, row.operands()), room, @as(f32, @floatFromInt(name.len)) * adv) else room + gap; - u.text(.mono, size, c.operands, base_y, rows.fitted(u, row.operands(), (if (covered) c.annotation else x) - gap - c.operands), t.faint); + const ops = shorn(u, row); + const x = if (name.len > 0) annotationX(operandsWidth(u, row, ops, ""), room, @as(f32, @floatFromInt(name.len)) * adv) else room + gap; + operands(u, row, ops, "", base_y, (if (covered) c.annotation else x) - gap - c.operands, t.faint); u.text(.mono, size, x, base_y, name, t.faint); return 0; } @@ -239,33 +262,31 @@ pub const Disasm = struct { const now_line = l == current_line; 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); + // Padding touches nothing: faint, with its operands. + const pad = row.padding(); + u.text(.mono_bold, size, c.mnemonic, base_y, row.mnemonic(), if (pad) t.faint else theme.color.code.keyword); // 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); + const need = d.annotation(u.faded(0), now, row, y, c.annotation, std.math.inf(f32), state, base, window, echo); // 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(); + // annotation moves left (never past its column), then the operands give way. + const ops = shorn(u, row); + const stub = if (target(row)) |to| pltName(u, rec, to) else ""; 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; + if (need.drawn) x = annotationX(operandsWidth(u, row, ops, stub), room, need.end - c.annotation); + operands(u, row, ops, stub, base_y, (if (covered) @min(x, c.annotation) else x) - gap - c.operands, if (pad) t.faint else theme.color.code.plain); + return if (need.drawn) d.annotation(u, now, row, y, x, room, state, base, window, echo).hangs else 0; } const Note = struct { drawn: bool = false, end: f32 = 0, hangs: usize = 0 }; + /// The row that set the flags a conditional jump reads, while the jump + /// runs: its chips are framed as read with it (an `echo`). + const Echo = struct { addr: u64, shows: f32 }; /// 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 { + fn annotation(d: *const Disasm, u: ui.Ui, now: cursors.Now, row: Insn, y: f32, x: f32, room: f32, state: State, base: usize, window: [2]u64, echo: ?Echo) Note { const rec = d.cursor.rec; const base_y = rows.baseline(y); const code_ink = theme.color.region.code_; @@ -278,33 +299,30 @@ pub const Disasm = struct { }, .ran => |r| .{ r.at, r.at + 1 }, .ahead => .{ now.stops[base], null }, + .waiting => |w| .{ w, null }, }; if (after) |a| if (!alone(rec, moment, a, row)) { after = null; }; 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]; + const mn = row.mnemonic(); + const a: Say = .{ .u = u, .rec = rec, .y = y, .x = x, .room = room }; + // Waiting on its callee: the call in C's form. + if (state == .waiting) if (branch) |b| return a.said(a.cForm(row, b.to, moment, null, a.room - a.x), t.primary); + // A system call: its name and number, its arguments hanging under it. + if (std.mem.eql(u8, mn, "syscall") and state != .ahead) return a.syscall(moment, state == .current); if (branch) |b| switch (b.kind) { .call => { - const callee = rec.strings.get(b.to) orelse ""; - 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 }; + // Through memory or a register: where it went, and where that was read. + if (target(row) == null) return a.went(b.to, touches[0], moment); + // Once it has run: the call in C's form and its result. + if (state == .ran) if (returned(rec, row, moment, now.stops[base])) |back| { + return a.said(a.cForm(row, b.to, moment, rec.register(back, "rax"), a.room - a.x), t.primary); + }; + var note = a.callee(b.to, moment); // Its arguments hang under it, a small `reg` a row, as many as the prototype has. - if (state == .current) { - // 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; - } else 3; - const shown_moment = rec.moment(moment); - const args = [_][]const u8{ "rdi", "rsi", "rdx", "rcx", "r8", "r9" }; - for (args[0..@min(count, 6)], 1..) |reg, k| { - const ry = y + @as(f32, @floatFromInt(k)) * m.row; - 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); - } + if (state == .current) note.hangs = a.arguments(row, b.to, moment); return note; }, .ret => { @@ -312,32 +330,80 @@ pub const Disasm = struct { 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 .{}; - 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 }; + // Through memory or a register: where it goes. Straight: nothing to say. + if (std.mem.eql(u8, mn, "jmp")) return if (target(row) == null) a.went(b.to, touches[0], moment) else .{}; + // A conditional: which way, and the flags it reads; taken out of the window, where to. + var end = a.word(x, if (b.taken) "taken" else "not taken", if (b.taken) t.primary else t.dim); + end = a.word(end + adv, "\u{00b7} reads", t.faint); + end = flags(u, end + adv, y, rec.register(moment, "eflags"), flagsRead(mn), 0); + if (b.taken and (b.to < window[0] or b.to > window[1])) { + end = a.word(end + adv, "\u{2192}", t.faint); + end = u.address(end + adv, base_y, b.to, .{ .ink = ui.rgb(code_ink), .name = ui.symbol(u, rec.strings.get(b.to) orelse "") }); + } + return .{ .drawn = true, .end = end }; }, .none => {}, }; - if (std.mem.eql(u8, row.mnemonic(), "syscall") and state != .ahead) { - const nr = rec.register(moment, "rax"); - 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" }; - 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); - 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, .{}); + if (state == .ahead) { + // Only what is static: a direct call's callee; a jump through the PLT's slot. + if (std.mem.eql(u8, mn, "call")) if (target(row)) |to| if (rec.strings.get(to) != null) return a.callee(to, moment); + if (std.mem.eql(u8, mn, "jmp")) if (ripSlot(row)) |slot| if ((zt.telescope.got(rec.moment(moment), slot) catch null)) |held| return a.went(held.value, .{ .addr = slot, .len = 8, .how = 1 }, moment); + return .{}; + } + // A compare: the two values, then (once it has run) the flags it leaves. + if (std.mem.eql(u8, mn, "cmp") or std.mem.eql(u8, mn, "test")) { + const left = a.compared(row, moment, touches[0]); + var end = a.word(x, left[0], t.primary); + end = a.word(end, " : ", t.faint); + end = a.word(end, left[1], t.primary); + const left_at: ?u64 = switch (state) { + .ran => after, + .current => if (after != null and now.landed(.cpu, 0)) after else null, + .ahead, .waiting => null, }; - return .{ .drawn = true, .end = x + @as(f32, @floatFromInt(name.len)) * adv, .hangs = if (state == .current) n else 0 }; + if (left_at) |l| { + var buf: [256]u8 = undefined; + const next = rec.instruction(moment, row.addr + row.len, &buf); + var mask = if (next) |n| flagsRead((Insn{ .addr = 0, .len = 0, .text = n.text }).mnemonic()) else 0; + if (mask == 0) mask = flag_bits.cf | flag_bits.zf | flag_bits.sf | flag_bits.of; + end = flags(u, end + 2 * adv, y, rec.register(l, "eflags"), mask, if (echo) |e| if (e.addr == row.addr) e.shows else 0 else 0); + } + return .{ .drawn = true, .end = end }; + } + // The rest is what it left behind, or where it reads: by what it is. + const value_at: ?u64 = switch (state) { + .ran => after, + .current => if (after != null and now.landed(.cpu, 0)) after.? else null, + .ahead, .waiting => null, + }; + // A place the C library's layout names: the canary. + if (std.mem.indexOf(u8, row.text, "fs:[0x28]") != null) { + const end = a.word(x, if (x + 35 * adv <= room) "the stack's canary" else "canary", t.dim); + const word_ = if (touches[0]) |touch| Recording.word(rec.moment(value_at orelse moment), touch.addr, 8) catch null else null; + if (word_) |v| return .{ .drawn = true, .end = a.word(end + adv, u.print("{x}", .{v}), t.primary) }; + u.unknown(.{ .x = end + adv, .y = y, .w = 24, .h = m.row }); + return .{ .drawn = true, .end = end + adv + 24 }; + } + // `lea`: `=` and what it made. + if (std.mem.eql(u8, mn, "lea")) { + const at = value_at orelse return .{}; + const reg = written(row) orelse return .{}; + const end = a.word(x, "=", t.faint); + return .{ .drawn = true, .end = rows.chain(u, end + adv, y, rec.moment(at), rec.register(at, reg), room, .{}).end }; + } + // A `rep`: how many times, how wide each, and where it goes. + if (std.mem.startsWith(u8, mn, "rep")) { + const each: u8 = switch (mn[mn.len - 1]) { + 'b' => 1, + 'w' => 2, + 'd' => 4, + else => 8, + }; + var end = a.word(x, "rcx", t.dim); + end = a.word(end + adv, u.print("{d}", .{rec.register(moment, "rcx")}), t.primary); + end = a.word(end + adv, u.print("\u{00b7} {d} bytes each", .{each}), t.faint); + end = a.word(end + adv, "rdi", t.dim); + return .{ .drawn = true, .end = rows.chain(u, end + adv, y, rec.moment(moment), rec.register(moment, "rdi"), room, .{}).end }; } // 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 @@ -354,8 +420,8 @@ pub const Disasm = struct { marks.read = 0; marks.read_shows = now.reading(.memory, 0); } - if (writes) if (after) |a| { - if (state == .ran or now.landed(.memory, 0)) shown = rec.moment(a); + if (writes) if (after) |aa| { + if (state == .ran or now.landed(.memory, 0)) shown = rec.moment(aa); if (in_step) { marks.changed = 1; marks.changed_heat = now.written(touch.addr, touch.len, .memory, 0); @@ -365,27 +431,350 @@ pub const Disasm = struct { } // Only a register: a small `reg` of what it left there. 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 .{}, - }; - const value = rec.register(value_at, reg); + const at = value_at orelse return .{}; + const value = rec.register(at, reg); u.text(.mono, size, x, base_y, reg, t.dim); - return .{ .drawn = true, .end = rows.chain(u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, rec.moment(value_at), value, room, .{}).end }; + return .{ .drawn = true, .end = rows.chain(u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, rec.moment(at), value, room, .{}).end }; + } +}; + +/// What an annotation says, from `x` on the row at `y`, cut where `room` ends. +const Say = struct { + u: ui.Ui, + rec: *const Recording, + y: f32, + x: f32, + room: f32, + + /// `text` at `x` in `ink`; where it ends. + fn word(a: Say, x: f32, text: []const u8, ink: u24) f32 { + a.u.text(.mono, size, x, rows.baseline(a.y), text, ink); + return x + @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(text) catch text.len)) * adv; + } + + /// `text` from the annotation's place, cut at the room's end. + fn said(a: Say, text: []const u8, ink: u24) Disasm.Note { + return .{ .drawn = true, .end = a.word(a.x, if (std.math.isInf(a.room)) text else rows.fitted(a.u, text, a.room - a.x), ink) }; + } + + /// A function's name as a caller knows it: a PLT stub's is the + /// function it reaches (`open`), or the resolver while its slot is lazy. + fn functionName(a: Say, to: u64, moment: u64) []const u8 { + const name = ui.symbol(a.u, a.rec.strings.get(to) orelse return a.u.print("{x}", .{to})); + const bare = name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len]; + if (!std.mem.endsWith(u8, bare, "@plt")) return bare; + var buf: [256]u8 = undefined; + const jmp = a.rec.instruction(moment, to, &buf) orelse return bare[0 .. bare.len - 4]; + if (ripSlot(.{ .addr = to, .len = jmp.len, .text = jmp.text })) |slot| if ((zt.telescope.got(a.rec.moment(moment), slot) catch null)) |held| { + if (held.lazy orelse false) return "the resolver"; + }; + return bare[0 .. bare.len - 4]; + } + + /// A direct call's callee, bright. + fn callee(a: Say, to: u64, moment: u64) Disasm.Note { + return .{ .drawn = true, .end = a.word(a.x, a.functionName(to, moment), t.bright) }; + } + + /// A call's arguments under it, a small `reg` a row: as many as its + /// prototype has (the debug info's, the source's, a system call's of + /// its name), three when none says. How many rows they take. + fn arguments(a: Say, row: Insn, to: u64, moment: u64) usize { + const name = a.functionName(to, moment); + const count = @min(row.params orelse for (a.rec.functions) |fun| { + if (std.mem.eql(u8, fun.name, name)) break fun.params; + } else argumentCount(a.rec, row, name) orelse 3, 6); + const shown = a.rec.moment(moment); + // Flags by name, where a system call of its name says which argument they are. + const nr: ?u64 = if (std.meta.stringToEnum(std.os.linux.SYS, name)) |sys| @intFromEnum(sys) else null; + const names: []const []const u8 = if (nr) |n| zt.syscalls.names(n) else &.{}; + for (carriers[0..count], 1..) |reg, k| { + const ry = a.y + @as(f32, @floatFromInt(k)) * m.row; + a.u.text(.mono, size, a.x, rows.baseline(ry), reg, t.dim); + const v = a.rec.register(moment, reg); + if (k - 1 < names.len and std.mem.eql(u8, names[k - 1], "flags")) { + a.u.text(.mono, size, a.x + 4 * adv, rows.baseline(ry), openFlags(a.u, v), t.primary); + } else _ = rows.chain(a.u, a.x + 4 * adv, ry, shown, v, a.room, .{}); + } + return count; + } + + /// The call at `row` (to `to`, made at `moment`) in C's form, its + /// arguments as the source wrote that many and as the system call of its + /// name types them; with ` = result` when it has returned. + fn cForm(a: Say, row: Insn, to: u64, moment: u64, result: ?u64, width: f32) []const u8 { + const u = a.u; + const name = a.functionName(to, moment); + const nr: ?u64 = if (std.meta.stringToEnum(std.os.linux.SYS, name)) |sys| @intFromEnum(sys) else null; + const names: []const []const u8 = if (nr) |n| zt.syscalls.names(n) else &.{}; + const count = @min(row.params orelse argumentCount(a.rec, row, name) orelse names.len, 6); + // Out of room the arguments go from the right, `…` for them; the result stays. + var shown = count; + while (true) : (shown -= 1) { + var out: []const u8 = u.print("{s}(", .{name}); + for (carriers[0..shown], 0..) |reg, k| { + const v = a.rec.register(moment, reg); + out = u.print("{s}{s}{s}", .{ out, if (k > 0) ", " else "", argument(u, a.rec, moment, if (k < names.len) names[k] else "", v) }); + } + if (shown < count) out = u.print("{s}{s}\u{2026}", .{ out, if (shown > 0) ", " else "" }); + out = u.print("{s})", .{out}); + if (result) |r| out = u.print("{s} = {d}", .{ out, @as(i64, @bitCast(r)) }); + if (shown == 0 or @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(out) catch out.len)) * adv <= width) return out; + } + } + + /// Where a call or a jump through memory or a register went: `→ addr + /// name`, then faint where it was read, `· read from open@got, 403fd8`. + /// Out of room the slot goes first, then the digits; the name stays. + fn went(a: Say, to: u64, slot: ?Recording.Touch, moment: u64) Disasm.Note { + const u = a.u; + const name = a.functionName(to, moment); + const from: []const u8 = if (slot) |s| blk: { + const named = ui.symbol(u, a.rec.strings.get(s.addr) orelse ""); + break :blk u.print("\u{00b7} read from {s}{s}{x}", .{ named[0 .. std.mem.lastIndexOfScalar(u8, named, '+') orelse named.len], if (named.len > 0) ", " else "", s.addr }); + } else ""; + const digits_w = @as(f32, @floatFromInt(ui.digits(to) + 1)) * adv; + const name_w = @as(f32, @floatFromInt(name.len)) * adv; + const from_w = @as(f32, @floatFromInt(std.unicode.utf8CountCodepoints(from) catch from.len)) * adv; + const fits_all = a.x + 2 * adv + digits_w + name_w + adv + from_w <= a.room; + const fits_digits = a.x + 2 * adv + digits_w + name_w <= a.room; + var end = a.word(a.x, "\u{2192}", t.faint) + adv; + if (fits_digits) { + end = u.address(end, rows.baseline(a.y), to, .{ .ink = ui.rgb(theme.color.region.code_), .name = name }); + } else end = a.word(end, name, t.primary); + if (fits_all and from.len > 0) end = a.word(end + adv, from, t.faint); + return .{ .drawn = true, .end = end }; + } + + /// The two values a compare compares, as its operands' size reads them. + fn compared(a: Say, row: Insn, moment: u64, touch: ?Recording.Touch) [2][]const u8 { + const ops = shorn(a.u, row); + var parts = std.mem.splitScalar(u8, ops.text, ','); + var operands_: [2][]const u8 = .{ "", "" }; + for (&operands_) |*o| o.* = std.mem.trim(u8, parts.next() orelse "", " "); + // The size: a register's, else the width's, else a word's. + var bytes: u8 = if (ops.bytes > 0) ops.bytes else 8; + for (operands_) |o| if (registerSize(o)) |n| { + bytes = n; + }; + var out: [2][]const u8 = undefined; + for (operands_, &out) |o, *v| { + const raw: ?u64 = if (std.mem.indexOfScalar(u8, o, '[') != null) + (if (touch) |tt| Recording.word(a.rec.moment(moment), tt.addr, @min(tt.len, 8)) catch null else null) + else if (full(o)) |reg| + a.rec.register(moment, reg) + else + parseImmediate(o); + v.* = if (raw) |r| number(a.u, r, bytes) else ".."; + } + return out; + } + + /// `syscall`: its name and number (`openat nr 257`); its arguments hang + /// under it, a register a row, each read as its name says. + fn syscall(a: Say, moment: u64, current: bool) Disasm.Note { + const u = a.u; + const nr = a.rec.register(moment, "rax"); + var end = a.word(a.x, zt.syscalls.name(nr) orelse "syscall", t.bright); + end = a.word(end + adv, "nr", t.faint); + end = a.word(end + adv, u.print("{d}", .{nr}), t.primary); + const names = zt.syscalls.names(nr); + const n = @min(zt.syscalls.signature(nr).len, 6); + if (!current) return .{ .drawn = true, .end = end }; + for (carriers_sys[0..n], 0..) |reg, k| { + const ry = a.y + @as(f32, @floatFromInt(k + 1)) * m.row; + u.text(.mono, size, a.x, rows.baseline(ry), reg, t.dim); + const v = a.rec.register(moment, reg); + const what = if (k < names.len) names[k] else ""; + const ax = a.x + 4 * adv; + if (std.mem.eql(u8, what, "path") or std.mem.eql(u8, what, "buf")) { + _ = rows.chain(u, ax, ry, a.rec.moment(moment), v, a.room, .{}); + } else if (std.mem.endsWith(u8, what, "fd") and v == fdcwd) { + // The value class `fd`: the number, and faint what it names. + u.text(.mono, size, ax, rows.baseline(ry), "-100", t.primary); + u.text(.mono, size, ax + 5 * adv, rows.baseline(ry), "AT_FDCWD", t.faint); + } else if (std.mem.endsWith(u8, what, "fd")) { + _ = u.typed(ax, rows.baseline(ry), v, .{ .fd = a.rec.openOn(u.f.scratch, v, moment) }, .{}); + } else u.text(.mono, size, ax, rows.baseline(ry), argument(u, a.rec, moment, what, v), t.primary); + } + return .{ .drawn = true, .end = end, .hangs = n }; + } +}; + +/// A call's argument registers, in order; a system call's. +const carriers = [_][]const u8{ "rdi", "rsi", "rdx", "rcx", "r8", "r9" }; +const carriers_sys = [_][]const u8{ "rdi", "rsi", "rdx", "r10", "r8", "r9" }; +/// `AT_FDCWD`, as a register holds it. +const fdcwd: u64 = @bitCast(@as(i64, -100)); + +/// An argument's value as C would write it, by its name: a path as its +/// string, flags by name, a descriptor and a count in decimal, a pointer as +/// its address. +pub fn argument(u: ui.Ui, rec: *const Recording, moment: u64, what: []const u8, v: u64) []const u8 { + if (std.mem.eql(u8, what, "path")) { + var links: [2]zt.telescope.Link = undefined; + var text: [48]u8 = undefined; + const chain = zt.telescope.chase(rec.moment(moment), v, &links, &text) catch &.{}; + if (chain.len > 0 and chain[chain.len - 1].string) return u.print("\"{s}\"", .{chain[chain.len - 1].text}); + } + if (std.mem.eql(u8, what, "flags")) return openFlags(u, v); + if (std.mem.endsWith(u8, what, "fd") and v == fdcwd) return "AT_FDCWD"; + const signed: i64 = @bitCast(v); + if (signed > -4096 and signed < 0x10000) return u.print("{d}", .{signed}); + return u.print("{x}", .{v}); +} + +/// `open`'s flags by name, `O_RDONLY`; bits no name covers as `0x` and their hex. +fn openFlags(u: ui.Ui, v: u64) []const u8 { + var out: []const u8 = switch (v & 3) { + 0 => "O_RDONLY", + 1 => "O_WRONLY", + else => "O_RDWR", + }; + var rest = v & ~@as(u64, 3); + for ([_]struct { []const u8, u64 }{ .{ "O_CREAT", 0o100 }, .{ "O_EXCL", 0o200 }, .{ "O_NOCTTY", 0o400 }, .{ "O_TRUNC", 0o1000 }, .{ "O_APPEND", 0o2000 }, .{ "O_NONBLOCK", 0o4000 }, .{ "O_DIRECTORY", 0o200000 }, .{ "O_NOFOLLOW", 0o400000 }, .{ "O_CLOEXEC", 0o2000000 } }) |f| if (rest & f[1] != 0) { + out = u.print("{s}|{s}", .{ out, f[0] }); + rest &= ~f[1]; + }; + return if (rest != 0) u.print("{s} 0x{x}", .{ out, rest }) else out; +} + +/// How many arguments the program's source gives `name` on the call's line. +fn argumentCount(rec: *const Recording, row: Insn, name: []const u8) ?usize { + const line = row.line orelse return null; + var lines = std.mem.splitScalar(u8, rec.source, '\n'); + var n: u32 = 1; + const text = while (lines.next()) |l| : (n += 1) { + if (n == line) break l; + } else return null; + const open = (std.mem.indexOf(u8, text, name) orelse return null) + name.len; + if (open >= text.len or text[open] != '(') return null; + var depth: usize = 0; + var count: usize = 0; + var any = false; + for (text[open + 1 ..]) |ch| switch (ch) { + '(' => depth += 1, + ')' => { + if (depth == 0) return if (any) count + 1 else 0; + depth -= 1; + }, + ',' => if (depth == 0) { + count += 1; + }, + ' ' => {}, + else => any = true, + }; + return null; +} + +/// The moment a call made at `moment` from `row` came back to the row after +/// it, at or before `until`. +fn returned(rec: *const Recording, row: Insn, moment: u64, until: u64) ?u64 { + const sp = rec.register(moment, "rsp"); + var i = moment + 1; + while (i <= until) : (i += 1) { + if (rec.register(i, "rip") == row.addr + row.len and rec.register(i, "rsp") == sp) return i; } + return null; +} + +/// The slot a `jmp` or `call` through `[rip + X]` reads. +fn ripSlot(row: Insn) ?u64 { + const ops = row.operands(); + const at = std.mem.indexOf(u8, ops, "[rip + 0x") orelse return null; + const close = std.mem.indexOfScalarPos(u8, ops, at, ']') orelse return null; + const disp = std.fmt.parseInt(u64, ops[at + 9 .. close], 16) catch return null; + return row.addr + row.len + disp; +} + +/// An immediate operand's value. +fn parseImmediate(o: []const u8) ?u64 { + const negative = std.mem.startsWith(u8, o, "-"); + const digits_ = if (negative) o[1..] else o; + const v = (if (std.mem.startsWith(u8, digits_, "0x")) std.fmt.parseInt(u64, digits_[2..], 16) else std.fmt.parseInt(u64, digits_, 10)) catch return null; + return if (negative) 0 -% v else v; +} + +/// `v` as a number `bytes` wide: signed and in decimal when small, else hex. +fn number(u: ui.Ui, v: u64, bytes: u8) []const u8 { + const bits: u7 = @as(u7, @min(bytes, 8)) * 8; + const masked = if (bits == 64) v else v & ((@as(u64, 1) << @intCast(bits)) - 1); + const signed: i64 = if (bits == 64) @bitCast(masked) else @as(i64, @bitCast(masked << @intCast(64 - @as(u7, bits)))) >> @intCast(64 - @as(u7, bits)); + if (signed > -0x10000 and signed < 0x10000) return u.print("{d}", .{signed}); + return u.print("{x}", .{masked}); +} + +/// eflags' bits a reader meets. +const flag_bits = struct { + const cf: u16 = 1 << 0; + const pf: u16 = 1 << 2; + const zf: u16 = 1 << 6; + const sf: u16 = 1 << 7; + const of: u16 = 1 << 11; }; +/// The flags a conditional (`jcc`, `setcc`, `cmovcc`) reads; 0 for anything else. +pub fn flagsRead(mn: []const u8) u16 { + const cond = if (std.mem.startsWith(u8, mn, "cmov")) mn[4..] else if (std.mem.startsWith(u8, mn, "set")) mn[3..] else if (mn.len > 1 and mn[0] == 'j' and !std.mem.eql(u8, mn, "jmp")) mn[1..] else return 0; + const f = flag_bits; + const table = [_]struct { []const u8, u16 }{ + .{ "a", f.cf | f.zf }, .{ "nbe", f.cf | f.zf }, .{ "be", f.cf | f.zf }, .{ "na", f.cf | f.zf }, + .{ "ae", f.cf }, .{ "nb", f.cf }, .{ "nc", f.cf }, .{ "b", f.cf }, + .{ "c", f.cf }, .{ "nae", f.cf }, .{ "e", f.zf }, .{ "z", f.zf }, + .{ "ne", f.zf }, .{ "nz", f.zf }, .{ "g", f.zf | f.sf | f.of }, .{ "nle", f.zf | f.sf | f.of }, + .{ "le", f.zf | f.sf | f.of }, .{ "ng", f.zf | f.sf | f.of }, .{ "ge", f.sf | f.of }, .{ "nl", f.sf | f.of }, + .{ "l", f.sf | f.of }, .{ "nge", f.sf | f.of }, .{ "o", f.of }, .{ "no", f.of }, + .{ "s", f.sf }, .{ "ns", f.sf }, .{ "p", f.pf }, .{ "pe", f.pf }, + .{ "np", f.pf }, .{ "po", f.pf }, + }; + for (table) |e| if (std.mem.eql(u8, cond, e[0])) return e[1]; + return 0; +} + +/// The flags of `mask`, as rip's row draws them: set, upper case on a +/// chip; clear, lower case and dim; each framed as read by `read`. Where they end. +fn flags(u: ui.Ui, x: f32, y: f32, eflags: u64, mask: u16, read: f32) f32 { + var at = x; + for (rows.flags) |flag| { + if (@as(u64, mask) >> flag.bit & 1 == 0) continue; + const chip: Rect = .{ .x = at, .y = y + 2, .w = theme.metric.flags.chip[0], .h = theme.metric.flags.chip[1] }; + if (eflags >> flag.bit & 1 != 0) { + u.chip(chip); + u.text(.mono_bold, size, at + 4, rows.baseline(y), flag.name, t.bright); + } else u.text(.mono, size, at + 4, rows.baseline(y), u.print("{c}{c}", .{ std.ascii.toLower(flag.name[0]), std.ascii.toLower(flag.name[1]) }), t.dim); + if (read > 0) u.read(chip, read); + at += chip.w + 4; + } + return at - 4; +} + +/// While a conditional jump runs (the mark on it, its step under way), the +/// row that set the flags it reads: the instruction just before it ran. +fn jumpEcho(now: cursors.Now, base: usize) ?Disasm.Echo { + if (base != 1 or now.resting()) return null; + const flags_ = readsFlags(now.rec, now.stops[1]); + if (flags_ == 0 or now.stops[1] == 0) return null; + return .{ .addr = now.rec.register(now.stops[1] - 1, "rip"), .shows = now.reading(.cpu, 0) }; +} + +/// The flags the instruction at moment `i`'s pc reads, if it is a conditional. +pub fn readsFlags(rec: *const Recording, i: u64) u16 { + var buf: [256]u8 = undefined; + const pc = rec.register(i, "rip"); + const here = rec.instruction(i, pc, &buf) orelse return 0; + return flagsRead((Insn{ .addr = pc, .len = here.len, .text = here.text }).mnemonic()); +} + /// 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 { +pub 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 { + pub 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) { @@ -400,7 +789,7 @@ const Runs = struct { /// 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 { +pub 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) { @@ -445,53 +834,147 @@ fn alone(rec: *const Recording, i: u64, after: u64, row: Insn) bool { } /// A jump's or a call's target, when the disassembler wrote it as one. -fn target(row: Insn) ?u64 { +pub 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; } -/// 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; +/// An `insn` with no state and no annotation: its address, its mnemonic +/// (faint for padding) and its operands as canim draws them, at `y` in `u` +/// (the panel's origin). For the gallery's page of rows. +pub fn plainRow(u: ui.Ui, row: Insn, y: f32) void { + const base_y = rows.baseline(y); + _ = u.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(theme.color.region.code_) }); + // A library's twelve digits move what is right of them, 12 a digit past seven. + const v = u.moved(@as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv, 0); + const pad = row.padding(); + v.text(.mono_bold, size, c.mnemonic, base_y, row.mnemonic(), if (pad) t.faint else theme.color.code.keyword); + operands(v, row, shorn(v, row), "", base_y, c.annotation - gap - c.operands, if (pad) t.faint else theme.color.code.plain); } -/// 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 { +/// Operands as canim draws them (design/README.md, `insn` and `width`): +/// the disassembler's less every size word (`qword ptr `); and where no +/// register outside the brackets has the access's size and the mnemonic +/// does not fix it, how many bytes it touches (`bytes`), drawn as byte +/// cells after the `]` that ends at `after`. +const Operands = struct { text: []const u8, after: usize = 0, bytes: u8 = 0 }; + +fn shorn(u: ui.Ui, row: Insn) Operands { + var ops = row.operands(); + var bytes: u8 = 0; + while (std.mem.indexOf(u8, ops, " ptr ")) |ptr| { + var word = ptr; + while (word > 0 and ops[word - 1] != ' ' and ops[word - 1] != ',') word -= 1; + for ([_]struct { []const u8, u8 }{ .{ "byte", 1 }, .{ "word", 2 }, .{ "dword", 4 }, .{ "qword", 8 }, .{ "tbyte", 10 }, .{ "xmmword", 16 }, .{ "ymmword", 32 }, .{ "zmmword", 64 } }) |w| { + if (std.mem.eql(u8, ops[word..ptr], w[0])) bytes = w[1]; + } + ops = u.print("{s}{s}", .{ ops[0..word], ops[ptr + 5 ..] }); + } + const close = std.mem.indexOfScalar(u8, ops, ']') orelse return .{ .text = ops }; + if (bytes == 0) return .{ .text = ops }; + // Said already: by the mnemonic (a stack op, a branch through memory, + // what touches nothing, a string op's suffix, SSE's scalar ops), or by + // a register outside the brackets of the access's size. const mn = row.mnemonic(); - // 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 ..] }); + for ([_][]const u8{ "push", "pop", "call", "jmp", "lea", "nop", "rep" }) |says| if (std.mem.startsWith(u8, mn, says)) return .{ .text = ops }; + if (mn.len == 0 or mn[0] == 'j') return .{ .text = ops }; + var parts = std.mem.splitScalar(u8, ops, ','); + while (parts.next()) |part| { + const operand = std.mem.trim(u8, part, " "); + if (std.mem.indexOfScalar(u8, operand, '[') != null) continue; + const of = registerSize(operand) orelse continue; + if (of == bytes or of >= 16) return .{ .text = ops }; + } + return .{ .text = ops, .after = close + 1, .bytes = bytes }; +} + +/// How many bytes register `name` is; null for anything else. +fn registerSize(name: []const u8) ?u8 { + if (name.len < 2) return null; + for ([_]struct { []const u8, u8 }{ .{ "xmm", 16 }, .{ "ymm", 32 }, .{ "zmm", 64 } }) |v| if (std.mem.startsWith(u8, name, v[0])) return v[1]; + if (full(name) == null and !(name.len == 3 and name[2] == 'l')) return null; + if (name[0] == 'r' and std.ascii.isDigit(name[1])) return switch (name[name.len - 1]) { + 'd' => 4, + 'w' => 2, + 'b' => 1, + else => 8, + }; + if (name.len == 3) return switch (name[0]) { + 'r' => 8, + 'e' => 4, + else => 1, // sil, dil, bpl, spl + }; + return if (name[1] == 'l' or name[1] == 'h') 1 else 2; +} + +/// How wide `width`'s cells are for an access of `bytes`, with the gaps +/// round them (3 after the `]`, 4 before what follows) and, past eight +/// bytes, the count. +fn cellsWidth(u: ui.Ui, bytes: u8) f32 { + if (bytes == 0) return 0; + const w = theme.metric.width; + const n: f32 = @floatFromInt(@min(bytes, 8)); + const count: f32 = if (bytes > 8) u.width(.mono, size, u.print("{d}", .{bytes})) + w.after else 0; + return w.before + (n - 1) * w.pitch + w.cell[0] + w.after + count; +} + +/// `width`: `bytes` byte cells at `x`, standing on the baseline; a count past eight. +fn cells(u: ui.Ui, x: f32, base_y: f32, bytes: u8) void { + const w = theme.metric.width; + for (0..@min(bytes, 8)) |k| u.fill(.{ .x = x + w.before + @as(f32, @floatFromInt(k)) * w.pitch, .y = base_y - w.cell[1], .w = w.cell[0], .h = w.cell[1] }, t.dim); + if (bytes > 8) u.text(.mono, size, x + w.before + 7 * w.pitch + w.cell[0] + w.after, base_y, u.print("{d}", .{bytes}), t.faint); +} + +/// A PLT stub's name, for a call or a jump to one: `open@plt`; "" otherwise. +fn pltName(u: ui.Ui, rec: *const Recording, to: u64) []const u8 { + const name = ui.symbol(u, rec.strings.get(to) orelse return ""); + const stub = name[0 .. std.mem.lastIndexOfScalar(u8, name, '+') orelse name.len]; + return if (std.mem.endsWith(u8, stub, "@plt")) stub else ""; } -/// 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 { +/// How wide operands `ops` of `row` are, whole (a target with its stub's name `stub`). +fn operandsWidth(u: ui.Ui, row: Insn, ops: Operands, stub: []const u8) f32 { + if (target(row)) |to| return @as(f32, @floatFromInt(ui.digits(to) + if (stub.len > 0) stub.len + 1 else 0)) * adv; + return @as(f32, @floatFromInt(ops.text.len)) * adv + cellsWidth(u, ops.bytes); +} + +/// The operands `ops`, in `width` units, in `ink`; a jump's or a call's +/// target is an `address` in code's ink, a PLT stub's with its name. 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: Operands, stub: []const u8, base_y: f32, width: f32, ink: u24) void { if (target(row)) |to| { - _ = u.address(c.operands, base_y, to, .{ .ink = ui.rgb(theme.color.region.code_) }); + _ = u.address(c.operands, base_y, to, .{ .ink = ui.rgb(theme.color.region.code_), .name = stub }); + return; + } + const text = ops.text; + const extra = cellsWidth(u, ops.bytes); + const at_after = c.operands + @as(f32, @floatFromInt(ops.after)) * adv; + if (@as(f32, @floatFromInt(text.len)) * adv + extra <= width) { + if (ops.bytes == 0) return u.text(.mono, size, c.operands, base_y, text, ink); + u.text(.mono, size, c.operands, base_y, text[0..ops.after], ink); + cells(u, at_after, base_y, ops.bytes); + u.text(.mono, size, at_after + extra, base_y, text[ops.after..], ink); 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; + var chars: usize = @intFromFloat(@max(width / adv, 1)); + if (ops.bytes > 0 and chars > ops.after) chars = @max(@as(usize, @intFromFloat(@max((width - extra) / adv, 1))), ops.after); + var cut = @min(chars - 1, text.len); + if (std.mem.lastIndexOfScalar(u8, text[0..cut], '[')) |open| { + if (std.mem.indexOfScalarPos(u8, text, open, ']') orelse text.len >= cut) cut = open; } - 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); + while (cut > 0 and text[cut - 1] == ' ') cut -= 1; + const shown_cells = ops.bytes > 0 and cut >= ops.after; + u.text(.mono, size, c.operands, base_y, text[0..if (shown_cells) ops.after else cut], ink); + var end = c.operands + @as(f32, @floatFromInt(cut)) * adv; + if (shown_cells) { + cells(u, at_after, base_y, ops.bytes); + u.text(.mono, size, at_after + extra, base_y, text[ops.after..cut], ink); + end += extra; + } + u.text(.mono, size, end, base_y, "\u{2026}", t.faint); } /// The register an instruction leaves a value in, if that is all it does @@ -526,8 +1009,12 @@ fn full(name: []const u8) ?[]const u8 { /// instructions over the pc (fewer near its start), the pc's, and as many /// after it as fill `room`; past the function's end, `outside`. fn listing(u: ui.Ui, rec: *const Recording, i: u64, room: usize, above: usize) Listing { + return listingAt(u, rec, i, rec.register(i, "rip"), room, above); +} + +/// The same round the instruction at `pc` (in the window, `Listing.pc`). +pub fn listingAt(u: ui.Ui, rec: *const Recording, i: u64, pc: u64, room: usize, above: usize) Listing { const out = u.f.scratch.alloc(Insn, room) catch return .{ .rows = &.{}, .pc = 0 }; - const pc = rec.register(i, "rip"); var buf: [256]u8 = undefined; var up: [16]Insn = undefined; var n_up: usize = 0; @@ -570,6 +1057,18 @@ fn merge(u: ui.Ui, a: []const Insn, b: []const Insn) ?struct { rows: []const Ins return .{ .rows = out, .from = if (lo.ptr == a.ptr) 0 else at, .to = if (lo.ptr == b.ptr) 0 else at }; } +test "a register's size, by its name" { + try std.testing.expectEqual(@as(?u8, 8), registerSize("rcx")); + try std.testing.expectEqual(@as(?u8, 4), registerSize("eax")); + try std.testing.expectEqual(@as(?u8, 4), registerSize("r10d")); + try std.testing.expectEqual(@as(?u8, 2), registerSize("ax")); + try std.testing.expectEqual(@as(?u8, 1), registerSize("dil")); + try std.testing.expectEqual(@as(?u8, 1), registerSize("al")); + try std.testing.expectEqual(@as(?u8, 16), registerSize("xmm0")); + try std.testing.expectEqual(@as(?u8, null), registerSize("0x10")); + try std.testing.expectEqual(@as(?u8, null), registerSize("fs:[0x28]")); +} + test "a register is known by any of its widths" { try std.testing.expectEqualStrings("rax", full("eax").?); try std.testing.expectEqualStrings("rdi", full("rdi").?); diff --git a/anim/src/hexdump.zig b/anim/src/hexdump.zig index f1087ab..cbd8f7f 100644 --- a/anim/src/hexdump.zig +++ b/anim/src/hexdump.zig @@ -216,7 +216,7 @@ pub fn drawArcs(u: ui.Ui, now: cursors.Now, x: f32, y: f32, first: u64, count: u } @import("map.zig").row(.view, addr, v, .{ .x = 0, .y = ry, .w = theme.layout.state.w, .h = m.row }); rows.bytesAt(v, ry, addr, &values, &known, runs[0..n], of.region, lead, holds_drawn, moment, shift); - for (runs[0..n]) |run| if (run.kind == .pointer and run.len == 8) pointerArcs(&arcs, now, addr + run.first, ry, shown_rows, 16, rule, loud); + for (runs[0..n]) |run| if (run.kind == .pointer and run.len == 8) pointerArcs(&arcs, now, addr + run.first, ry, shown_rows, 16, rule, loud, false); const end = reading(v, ry, shift, moment, &values, &known, readings[0..n]); // The size word of the chunk after: malloc's, a note after the reading. const last = runs[n - 1]; @@ -239,10 +239,12 @@ pub const RowAt = struct { addr: u64, y: f32 }; /// framed. A target in the same region past the rows shown: a stub to the /// panel's rule (`rule`: its top and bottom), only in the step that /// touches it. `loud`: full ink always (a loupe's, opened to show them). -pub fn pointerArcs(arcs: *rows.Arcs, now: cursors.Now, field: u64, from: f32, shown: []const RowAt, size: u64, rule: [2]f32, loud: bool) void { +pub fn pointerArcs(arcs: *rows.Arcs, now: cursors.Now, field: u64, from: f32, shown: []const RowAt, size: u64, rule: [2]f32, loud: bool, protected: bool) void { const a = time_arc; - const new = (Recording.word(now.moment(), field, 8) catch null) orelse return; - const old = (Recording.word(now.before(), field, 8) catch null) orelse new; + // Safe-linked: to the pointer it protects (a NULL so stored is the mask alone). + const mask: u64 = if (protected) field >> 12 else 0; + const new = ((Recording.word(now.moment(), field, 8) catch null) orelse return) ^ mask; + const old = if (Recording.word(now.before(), field, 8) catch null) |w| w ^ mask else new; const written = now.writeAge(field, 8) == 0 and old != new; const read = now.wasRead(field, 8) and !written; const hot = written or read; @@ -296,7 +298,19 @@ fn chunkAfter(moment: Recording.Moment, word: u64) bool { /// What a field of a region reads as: a number (little-endian, or `big`), /// a pointer, text (in quotes, C's escapes), or bytes the reading leaves /// to the eye. -pub const Reads = enum { number, pointer, text, bytes }; +pub const Reads = enum { + number, + pointer, + text, + bytes, + /// malloc's size word: the size, its three low bits cleared, in hex; + /// then the bits as rip's flags are drawn, `A M P` (`0x20 a m P`). + size, + /// A pointer glibc stores safe-linked (xor its own address shifted + /// right by 12): what it protects, `→ 405050`, or `NULL`, then the + /// mask, faint, `^ 405`. Its arc goes to the pointer it protects. + protected, +}; /// A field of the region a view is about, from the region's first byte. pub const Field = struct { @@ -310,6 +324,11 @@ pub const Field = struct { /// A number's type, where the debug info gives it: read as the lens's /// values are (`objects.reading`: a `char` quoted, a `bool` by name). type: ?Recording.types.Type = null, + /// A note from the scene, Go 18 faint, after the reading (`key`, `slots left`). + note: []const u8 = "", + /// Where the field is: a `protected` word's mask is its address shifted + /// right by 12 (`fieldRow` sets it). + addr: u64 = 0, }; /// What a dump of fields is of, and how it is marked now. @@ -380,9 +399,9 @@ pub fn fielded(v: View, now: cursors.Now, y: f32, of: Fields) void { if (shown[shown.len - 1] < total - 1) more(u, ry, total - 1 - shown[shown.len - 1]); // Its pointers to its own rows: arcs. var arcs: rows.Arcs = .{}; - if (at_rows.items.len > 1) for (of.fields) |field| if (field.reads == .pointer and field.len == 8) { + if (at_rows.items.len > 1) for (of.fields) |field| if ((field.reads == .pointer or field.reads == .protected) and field.len == 8) { const addr = of.base + field.at; - for (at_rows.items) |r| if (addr >= r.addr and addr < r.addr + 16) pointerArcs(&arcs, now, addr, r.y, at_rows.items, 16, .{ y - m.pad, ry + m.pad }, false); + for (at_rows.items) |r| if (addr >= r.addr and addr < r.addr + 16) pointerArcs(&arcs, now, addr, r.y, at_rows.items, 16, .{ y - m.pad, ry + m.pad }, false, field.reads == .protected); }; arcs.draw(u, theme.metric.arc.lanes.len); } @@ -479,7 +498,7 @@ fn fieldRow(u: ui.Ui, now: cursors.Now, y: f32, addr: u64, moment: Recording.Mom if (field) |fl| { run.len = @intCast(@min(of.base + fl.at + fl.len - here, 16 - @as(u64, at))); run.kind = switch (fl.reads) { - .number, .bytes => .number, + .number, .bytes, .size, .protected => .number, .pointer => .pointer, .text => .text, }; @@ -490,7 +509,7 @@ fn fieldRow(u: ui.Ui, now: cursors.Now, y: f32, addr: u64, moment: Recording.Mom }; if (of.watched > 0 and now.wasRead(here, run.len) and now.writeAge(here, run.len) != 0) framed = @max(framed, now.reading(.memory, 0)); run.read = framed; - readings[n] = .{ .at = at, .len = run.len, .reads = fl.reads, .big = fl.big, .type = fl.type }; + readings[n] = .{ .at = at, .len = run.len, .reads = fl.reads, .big = fl.big, .type = fl.type, .note = fl.note, .addr = here }; ties.anchor(u, .{ .dump_run = here }, .{ .x = shift + rows.byteX(run.first) - 4, .y = y, .w = rows.byteX(run.first + run.len - 1) + 28 - rows.byteX(run.first) + 4, .h = m.row }); } else { // Up to the next field, or the row's end. @@ -535,9 +554,45 @@ pub fn reading(u: ui.Ui, y: f32, shift: f32, moment: Recording.Moment, values: * const first: usize = @intCast(fl.at); // A typed number is as wide as its type (an `int` in a word: 4 bytes). const len: usize = @intCast(if (fl.type) |ty| @min(fl.len, ty.size() orelse fl.len) else fl.len); - if (fl.reads == .bytes or len == 0) continue; - if (std.mem.indexOfScalar(bool, known[first..][0..len], false) != null) continue; + if (len == 0 or std.mem.indexOfScalar(bool, known[first..][0..len], false) != null) continue; + defer if (fl.note.len > 0) { + u.text(.sans, theme.size.sans.micro, x, base - 1, fl.note, t.faint); + x += u.width(.sans, theme.size.sans.micro, fl.note) + adv; + }; + if (fl.reads == .bytes) continue; const bytes = values[first..][0..len]; + var word_: u64 = 0; + for (0..@min(len, 8)) |k| word_ |= @as(u64, bytes[k]) << @intCast(8 * k); + switch (fl.reads) { + .size => { + const shown_size = u.print("0x{x}", .{word_ & ~@as(u64, 7)}); + u.text(.mono, size, x, base, shown_size, t.primary); + x += u.width(.mono, size, shown_size) + adv; + // A M P: set on a chip, clear in dim lower case. + for ([_]struct { u8, u6 }{ .{ 'A', 2 }, .{ 'M', 1 }, .{ 'P', 0 } }) |bit| { + const set = word_ >> bit[1] & 1 != 0; + if (set) u.chip(.{ .x = x - 3, .y = y + 2, .w = adv + 6, .h = theme.metric.flags.chip[1] }); + u.text(if (set) .mono_bold else .mono, size, x, base, &.{if (set) bit[0] else std.ascii.toLower(bit[0])}, if (set) t.bright else t.dim); + x += 2 * adv; + } + continue; + }, + .protected => { + const target = word_ ^ (fl.addr >> 12); + if (target == 0) { + u.text(.mono, size, x, base, "NULL", t.dim); + x += 5 * adv; + } else { + x = u.arrow(x, y + m.row / 2, .points); + x = u.address(x, base, target, .{ .ink = ui.rgb(rows.ink(rows.regionOf(moment, target))) }) + adv; + } + const masked = u.print("^ {x}", .{fl.addr >> 12}); + u.text(.mono, size, x, base, masked, t.faint); + x += u.width(.mono, size, masked) + adv; + continue; + }, + else => {}, + } const words: []const u8 = switch (fl.reads) { .number => blk: { var word: u64 = 0; @@ -557,7 +612,7 @@ pub fn reading(u: ui.Ui, y: f32, shift: f32, moment: Recording.Moment, values: * continue; }, .text => quoted(u, bytes), - .bytes => unreachable, + .bytes, .size, .protected => unreachable, }; const w = u.width(.mono, size, words); const fits = x + w <= room; diff --git a/anim/src/loupe.zig b/anim/src/loupe.zig index 99dae71..623e966 100644 --- a/anim/src/loupe.zig +++ b/anim/src/loupe.zig @@ -40,7 +40,14 @@ pub const Loupe = struct { stage: *const Stage, /// What it opens from: a register, by name; or a pointer field (its /// address) of the loupe it hangs under. - from: union(enum) { register: []const u8, field: struct { loupe: *const Loupe, at: u64 } }, + /// Or the bytes of a dump's row (`at`, a field the view publishes as a + /// `dump_run`), opening on `fields` (the region it reads them as): a + /// struct the debug info does not type (malloc's tcache), named `name`. + from: union(enum) { + register: []const u8, + field: struct { loupe: *const Loupe, at: u64 }, + row: struct { at: u64, name: []const u8, note: []const u8, fields: hexdump.Fields }, + }, /// 0 to 1 as it opens (`time.loupe.open`) and as it closes (`close`). opening: anim.Value = undefined, closing: anim.Value = undefined, @@ -85,6 +92,14 @@ pub const Loupe = struct { target = (Recording.word(moment, field.at, 8) catch null) orelse return null; right = parent.box.x + 120; }, + .row => |row| { + const px = ties.find(.{ .dump_run = row.at }) orelse return null; + const back = u.at.xf.invert(); + const a = back.apply(.{ px[0], px[1] }); + const b = back.apply(.{ px[2], px[3] }); + pointer = .{ .x = a[0], .y = a[1], .w = b[0] - a[0], .h = b[1] - a[1] }; + target = row.fields.base; + }, } if (target == 0) return null; // shortcut: it keeps to the stage and does not yet move past the current marks or a changed row; the scene picks a pointer whose loupe covers neither. @@ -135,6 +150,10 @@ pub const Loupe = struct { x += v.width(.mono, size, name) + 6; }, .field => |field| x = v.address(x, base, field.at, .{ .ink = ui.rgb(rows.ink(rows.regionOf(moment, field.at))) }) + 6, + .row => |row| { + v.text(.mono, size, x, base, row.name, t.dim); + x += v.width(.mono, size, row.name) + 6; + }, } x = v.arrow(x, m.tag / 2, .points) + 8; _ = v.address(x, base, p.target, .{ .ink = ui.rgb(p.ink) }); @@ -146,16 +165,17 @@ pub const Loupe = struct { .rodata => "read-only", .none => "", }; - const note = if (object) |o| v.print("{s} \u{00b7} {s}, {d} bytes", .{ region, if (o.name.len > 0) o.name else "a struct", o.type.record.size }) else region; + const note = if (l.from == .row) l.from.row.note else if (object) |o| v.print("{s} \u{00b7} {s}, {d} bytes", .{ region, if (o.name.len > 0) o.name else "a struct", o.type.record.size }) else region; v.text(.sans, theme.size.sans.micro, b.w - 10 - v.width(.sans, theme.size.sans.micro, note), base, note, t.dim); // Its rows, typed where the recording types them, its own pointers as arcs at full ink. const top = m.tag + m.pad; v.clip(.{ .x = 0, .y = m.tag, .w = b.w, .h = b.h - m.tag }); - hexdump.drawArcs(v, now, 0, top, p.first, k.rows, .{ .things = things }, true, .{ m.tag, b.h - m.pad }); + // By the scene's fields: the rows that hold them, the rest `more`. + if (l.from == .row) hexdump.fielded(.{ .u = v, .rows = k.rows, .box = b }, now, top, l.from.row.fields) else hexdump.drawArcs(v, now, 0, top, p.first, k.rows, .{ .things = things }, true, .{ m.tag, b.h - m.pad }); v.unclip(); // Its target, framed bright: each field of the struct, or the word. const framed = std.math.clamp((since - time.stem - time.frame) / time.frame, 0, 1); - if (framed > 0) { + if (framed > 0 and l.from != .row) { const row_y = top + @as(f32, @floatFromInt((p.target - p.first) / 16)) * m.row; const shift = rows.addressRoom(p.first + 16 * (k.rows - 1)); const w = v.faded(framed); diff --git a/anim/src/root.zig b/anim/src/root.zig index d8c2c76..84758f8 100644 --- a/anim/src/root.zig +++ b/anim/src/root.zig @@ -20,6 +20,8 @@ pub const layout = theme.layout; pub const ui = @import("ui.zig"); pub const Rect = theme.Rect; pub const Recording = @import("Recording.zig"); +/// The tracer's reader, for what a scene reads itself (`ztrace.heap.glibc`). +pub const ztrace = @import("ztrace"); const cursors = @import("cursor.zig"); pub const Cursor = cursors.Cursor; pub const Now = cursors.Now; @@ -35,7 +37,9 @@ pub const Stack = contexts.Stack; pub const Backtrace = contexts.Backtrace; /// The registers' tag: what an address's ink says. pub const contextLegend = contexts.legend; -pub const Disasm = @import("disasm.zig").Disasm; +pub const disasm = @import("disasm.zig"); +pub const Disasm = disasm.Disasm; +pub const Descent = @import("descent.zig").Descent; pub const calls = @import("calls.zig"); pub const CallTree = calls.Tree; pub const Nodes = @import("nodes.zig").Nodes; @@ -46,6 +50,7 @@ pub const Place = tying.Place; pub const Array = @import("array.zig").Array; pub const Loupe = @import("loupe.zig").Loupe; pub const syscalls = @import("syscalls.zig"); +pub const descent = @import("descent.zig"); pub const Crossing = syscalls.Crossing; pub const Timeline = syscalls.Timeline; pub const objects = @import("objects.zig"); @@ -235,6 +240,10 @@ pub const Context = struct { /// (eleven rows as subject, five beside), when how the program came /// to be here is the story; the scene adds the drawing's view. backtrace: bool = false, + /// The disassembly as a `descent`: a call followed down opens its + /// callee's window under the call row, and a system call the + /// kernel's under the `syscall` (step with `descent.step`). + descent: bool = false, }; /// The ties between the panes, drawn over everything added before. @@ -268,8 +277,8 @@ pub fn context(s: *anim.Frame, cursor_: Cursor, options: Context.Options) Contex // The map first: while it fills the frame or falls to the minimap it is under the panels diving out of it. const whole = s.new(map.Map{ .stage = Stage.init(s, map.split(at.rec, options.split.band.h > 0)), .frame = stage, .t = s.value(map.diving.land + map.diving.still) }); whole.obj = s.custom(whole, .{ .x = -640, .y = -360, .scale = ui.scale }); - whole.add(s, Source{ .cursor = at, .stage = whole.stage }); - whole.add(s, Disasm{ .cursor = at, .stage = whole.stage }); + whole.add(s, Source{ .cursor = at, .stage = whole.stage, .descent = options.descent }); + if (options.descent) whole.add(s, Descent{ .cursor = at, .stage = whole.stage }) else whole.add(s, Disasm{ .cursor = at, .stage = whole.stage }); whole.add(s, Registers{ .cursor = at, .stage = whole.stage, .syscalls = options.syscalls, .quiet = options.quiet }); whole.add(s, Stack{ .cursor = at, .stage = whole.stage, .above = theme.map.stack_above }); whole.add(s, Backtrace{ .cursor = at, .stage = whole.stage }); @@ -278,8 +287,8 @@ pub fn context(s: *anim.Frame, cursor_: Cursor, options: Context.Options) Contex .map = whole, .cursor = at, .quiet = options.quiet, - .source = add(s, Source{ .cursor = at, .stage = stage }), - .disasm = add(s, Disasm{ .cursor = at, .stage = stage }), + .source = add(s, Source{ .cursor = at, .stage = stage, .descent = options.descent }), + .disasm = if (options.descent) add(s, Descent{ .cursor = at, .stage = stage }) else add(s, Disasm{ .cursor = at, .stage = stage }), .registers = add(s, Registers{ .cursor = at, .stage = stage, .syscalls = options.syscalls, .quiet = options.quiet }), .stack = add(s, Stack{ .cursor = at, .stage = stage }), .backtrace = add(s, Backtrace{ .cursor = at, .stage = stage, .lens = options.backtrace }), @@ -344,6 +353,7 @@ test { _ = rows; _ = contexts; _ = @import("disasm.zig"); + _ = @import("descent.zig"); _ = tying; _ = @import("hexdump.zig"); _ = calls; diff --git a/anim/src/rows.zig b/anim/src/rows.zig index 83064a6..1d097a1 100644 --- a/anim/src/rows.zig +++ b/anim/src/rows.zig @@ -125,8 +125,8 @@ pub fn chain(u: ui.Ui, x: f32, y: f32, moment: Recording.Moment, value: u64, roo if (link.string) { // What a pointer leads to, when it is text: quoted, cut to the room // there is (never under six characters), with `…` and no closing quote. - const fits: usize = @intFromFloat(@max((room - at - m.arrow_w) / adv, 0)); - if (fits < m.string_min + 2) break; + const fits: usize = @intFromFloat(std.math.clamp((room - at - m.arrow_w) / adv, 0, 4096)); + if (fits < @as(usize, @min(m.string_min, link.text.len)) + 2) break; at = v.arrow(at, mid, .holds); const whole = link.text.len + 2 <= fits; const text = if (whole) u.print("\"{s}\"", .{link.text}) else u.print("\"{s}\u{2026}", .{link.text[0 .. fits - 2]}); @@ -167,9 +167,10 @@ pub const flags = [_]Flag{ .{ .name = "CF", .bit = 0 }, .{ .name = "PF", .bit = /// code's ink and its name; never struck. At its right end the `flags`, /// eight names on a pitch of 42: set, upper case on a chip, bold, bright; /// clear, lower case, dim; changed, a turned corner (`changed`: a bit per -/// flag, and how much of the corner shows). The value of eflags is not -/// drawn: the names are the value. -pub fn rip(u: ui.Ui, y: f32, w: f32, moment: Recording.Moment, pc: u64, eflags: u64, changed: u64, held: f32, fire: f32) void { +/// flag, and how much of the corner shows); read, framed (`read`: a bit per +/// flag, while a conditional reads them: an echo of the row that set them, +/// `read_shows` how much). The value of eflags is not drawn: the names are the value. +pub fn rip(u: ui.Ui, y: f32, w: f32, moment: Recording.Moment, pc: u64, eflags: u64, changed: u64, held: f32, fire: f32, read: u64, read_shows: f32) void { const gold = theme.mark(.current); u.current(.{ .x = theme.stroke.rule, .y = y, .w = w - 2 * theme.stroke.rule, .h = row_h }, theme.metric.plaque.rip, fire); u.text(.mono_bold, size, m.side, baseline(y), "rip", gold.on_solid); @@ -183,6 +184,7 @@ pub fn rip(u: ui.Ui, y: f32, w: f32, moment: Recording.Moment, pc: u64, eflags: u.text(.mono_bold, size, x + 4, baseline(y), flag.name, t.bright); } else u.text(.mono, size, x + 4, baseline(y), u.print("{c}{c}", .{ std.ascii.toLower(flag.name[0]), std.ascii.toLower(flag.name[1]) }), ui.mix(t.dim, gold.ember, 0.2)); if (changed >> flag.bit & 1 != 0) u.corner(x, y + 2, m.corner, held); + if (read >> flag.bit & 1 != 0 and read_shows > 0) u.read(.{ .x = x, .y = y + 2, .w = fl.chip[0], .h = fl.chip[1] }, read_shows); x += fl.pitch; } } diff --git a/anim/src/source.zig b/anim/src/source.zig index 58b9df0..bbc985e 100644 --- a/anim/src/source.zig +++ b/anim/src/source.zig @@ -17,6 +17,7 @@ const ties = @import("ties.zig"); const map = @import("map.zig"); const cursors = @import("cursor.zig"); const Stage = @import("stage.zig").Stage; +const Recording = @import("Recording.zig"); const Cursor = cursors.Cursor; const theme = ui.theme; const Rect = ui.Rect; @@ -28,6 +29,9 @@ pub const Source = struct { cursor: Cursor, stage: *const Stage, focus: bool = false, + /// In a `descent`: while the pc is in code without source, the line it + /// called from waits, ringed, and the tag says where the pc is. + descent: bool = false, pub fn draw(p: *const Source, f: *sk.Frame, placed: anim.Placed) void { const box = p.stage.box(placed, .source); @@ -52,7 +56,10 @@ pub const Source = struct { const from: u32 = @intFromFloat(@floor(first)); const last: u32 = @min(from + @as(u32, @intCast(context.rowsOf(box))), rec.line_count); const shown_first: u32 = @intFromFloat(windows[if (going >= 0.5) 1 else 0]); - const body = u.panel(box.w, box.h, rec.file, .{ .focus = p.focus, .note = if (rec.line_count > fit) u.print("lines {d} to {d} of {d}", .{ shown_first, @min(shown_first + fit - 1, rec.line_count), rec.line_count }) else u.print("{d} lines", .{rec.line_count}) }); + // Waiting: the pc is in code with no source, under this line's call. + const waits = p.descent and !rec.sourced(now.marked()) and rec.own[now.marked()] != 0; + const note = if (waits) u.print("{s} waits at line {d} \u{00b7} the pc is in {s}", .{ context.frameName(u, rec, rec.register(firstOwn(rec, now.marked()), "rip")), rec.own[now.marked()], whereIs(u, rec, now.marked()) }) else if (rec.line_count > fit) u.print("lines {d} to {d} of {d}", .{ shown_first, @min(shown_first + fit - 1, rec.line_count), rec.line_count }) else u.print("{d} lines", .{rec.line_count}); + const body = u.panel(box.w, box.h, rec.file, .{ .focus = p.focus, .note = note }); const top = body.y + m.pad; // Where the mark is, and how much of it. @@ -85,7 +92,11 @@ pub const Source = struct { defer u.unclip(); // The plaque over the number. Fire: on the line about to run its // edges go out and come back, once, and nothing else moves. - if (shows > 0) u.faded(shows).current(.{ .x = theme.stroke.rule, .y = mark_y, .w = box.w - 2 * theme.stroke.rule, .h = m.row }, theme.metric.plaque.line + widen, now.fires(.source)); + if (waits) { + // The number ringed: a 2-unit primary frame where the plaque would be, no wash. + u.faded(shows).frame(.{ .x = theme.stroke.rule + 1, .y = mark_y + 1, .w = theme.metric.plaque.line + widen - 2, .h = m.row - 2 }, theme.color.text.primary, theme.stroke.rule); + if (!ui.mapping) ties.thread_waits = true; + } else if (shows > 0) u.faded(shows).current(.{ .x = theme.stroke.rule, .y = mark_y, .w = box.w - 2 * theme.stroke.rule, .h = m.row }, theme.metric.plaque.line + widen, now.fires(.source)); if (shows >= 1 and mark_y >= body.y and mark_y + m.row <= box.h) ties.anchor(u, .source, .{ .x = 0, .y = mark_y, .w = box.w, .h = m.row }); // The trail: the last three other lines it was on. It shifts without animation. @@ -109,13 +120,33 @@ pub const Source = struct { const span = text.lines[line - 1]; const k = std.mem.indexOfScalar(u32, trail[0..found], line); const on = shows >= 0.5 and line == mark_line; - rows.line(lit, y, box.w, line, widen, text.bytes[span[0]..span[1]], text.styles[span[0]..span[1]], if (on) .marked else if (k) |n| .{ .trail = n } else .plain); + rows.line(lit, y, box.w, line, widen, text.bytes[span[0]..span[1]], text.styles[span[0]..span[1]], if (on and !waits) .marked else if (k) |n| .{ .trail = n } else .plain); } // The source is read at a run; at a sprint it is veiled too. context.veiled(u, box, now.sprint_veil); } }; +/// The last moment at or before `i` whose pc was on a line of the program's source. +fn firstOwn(rec: *const Recording, i: u64) u64 { + var at = i; + while (at > 0 and !rec.sourced(at)) at -= 1; + return at; +} + +/// Where the pc is at moment `i`, for the waiting line's tag: `the PLT`, +/// `libc's open`, `the vdso`. +fn whereIs(u: ui.Ui, rec: *const Recording, i: u64) []const u8 { + const name = context.frameName(u, rec, rec.register(i, "rip")); + if (std.mem.endsWith(u8, name, "@plt")) return "the PLT"; + var module: []const u8 = ""; + var buf: [256]u8 = undefined; + _ = (rec.moment(i).mapping(rec.register(i, "rip"), &module, &buf) catch null); + const base = std.fs.path.basename(module); + const short = base[0 .. std.mem.indexOfScalar(u8, base, '.') orelse base.len]; + return u.print("{s}'s {s}", .{ short, name }); +} + /// A source ready to draw: a class for each byte, and where each line is. const Text = struct { bytes: []const u8, diff --git a/anim/src/syscalls.zig b/anim/src/syscalls.zig index e184990..4a46170 100644 --- a/anim/src/syscalls.zig +++ b/anim/src/syscalls.zig @@ -20,7 +20,6 @@ const Stage = @import("stage.zig").Stage; const theme = ui.theme; const time = theme.time; const Rect = ui.Rect; -const k = theme.color.on_kernel; /// A crossing's timetable, in seconds into its step (design/motion.md, "A /// system call"). Staging, one thing at a time and no effect before its @@ -156,11 +155,12 @@ pub fn fills(call: Recording.Syscall) ?Recording.Span { return if (call.nr == @intFromEnum(std.os.linux.SYS.read) and got > 0) .{ .addr = call.args[1], .len = @intCast(got) } else null; } -/// The kernel as a lens: solid vellum, and nothing else on the frame is. -/// The call the step made, decoded (its name, a row an argument by the -/// argument's own name, what came back), the calls before it, the bytes it -/// was given; and the arrow that crosses into it from the registers' -/// side and returns. +/// The `syscalls` lens: the program's conversation with the kernel. Its +/// drawing is the calls so far as strace writes them, a row each, oldest +/// on top and the newest at the bottom (its row comes in once the call is +/// back, with the turned corner); not the kernel, and not on vellum: the +/// kernel is under the program, the floor of the disassembly's `descent`. +/// Its view, the bytes the newest call was given or filled. pub const Crossing = struct { cursor: cursors.Cursor, stage: *const Stage, @@ -182,45 +182,78 @@ pub const Crossing = struct { 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" }); - u.fill(.{ .x = theme.stroke.rule, .y = body.y, .w = body.w - 2 * theme.stroke.rule, .h = body.h - theme.stroke.rule }, theme.color.kernel); + const room = context.rowsOf(box); + // The calls from the scene's first moment: the program's, not its loader's. + var first: usize = 0; + while (first < rec.syscalls.len and rec.syscalls[first].enter < c.cursor.first) first += 1; + var newest = latest(rec, now.stops[0]); + // A crossing's own row comes in once it is back (rax struck), 12 f. + var arrives: f32 = 1; + if (newest) |n| if (inStep(now) != null and now.walking()) { + const p = Plan.of(rec.syscalls[n]); + arrives = std.math.clamp((now.time - p.struck - 6.0 / 60.0) / theme.time.quick, 0, 1); + }; + if (newest) |n| if (n < first) { + newest = null; + }; + const count = if (newest) |n| n + 1 - first else 0; + const body = u.panel(box.w, box.h, "system calls", .{ .focus = c.focus, .note = if (count > room) u.print("as strace writes them \u{00b7} newest at the bottom \u{00b7} {d} more above", .{count - room}) else "as strace writes them \u{00b7} newest at the bottom" }); context.clipBody(u, box); defer u.unclip(); - u.text(.sans, theme.size.sans.micro, 12, body.y + 22, "calls so far", k.dim); - const newest = latest(rec, now.stops[0]) orelse return; - const live = inStep(now) != null and now.walking(); - const p = Plan.of(rec.syscalls[newest]); - const t: f32 = if (live) now.time else std.math.inf(f32); - if (t >= p.enters) arrows(u, body, t, p, rec.syscalls[newest]); - // No effect before its cause: until the arrow is through the - // line the kernel knows nothing of this call, and shows the last. - if (t < p.name) { - if (newest > 0) c.call(u.faded(1 - theme.ease(.exit, std.math.clamp((t - p.leaves) / (p.name - p.leaves), 0, 1))), body, rec.syscalls[newest - 1], .{}, std.math.inf(f32)); - } else c.call(u, body, rec.syscalls[newest], p, t); + const n = newest orelse return; + const top = body.y + theme.metric.context.pad; + const shown = @min(count, room); + for (0..shown) |j| { + const i = n + 1 - shown + j; + const v = if (i == n) u.faded(arrives) else u; + const y = top + @as(f32, @floatFromInt(j)) * row_h; + logRow(v, rec, rec.syscalls[i], y, box.w - theme.metric.context.side); + if (i == n) v.corner(theme.metric.context.side, y + 2, theme.metric.context.corner, 1); + } + } - // The calls so far, newest on top. This one's row pushes in when - // the kernel has taken the call: the others make room first. - const pushed = cursors.standard(std.math.clamp((t - p.card) / theme.time.quick, 0, 1)); - const arrived = std.math.clamp((t - p.card - theme.time.snap) / theme.time.quick, 0, 1); - const top = body.y + 32; - var i = newest + 1; - while (i > 0) { - i -= 1; - const place = @as(f32, @floatFromInt(newest - i)) - (if (i == newest) 0 else 1 - pushed); - const y = top + place * (row_h + 4) - (if (i == newest) (1 - arrived) * 8 else 0); - if (y + row_h > body.y + body.h - 6) continue; - const v = if (i == newest) u.faded(arrived) else u; - const card: Rect = .{ .x = 12, .y = y, .w = 196, .h = row_h }; - const done = rec.syscalls[i]; - const gold = if (i == newest) arrived >= 1 else i + 1 == newest and arrived < 1; - if (gold) v.fill(card, theme.mark(.current).solid); - v.frame(card, k.ink, theme.stroke.rule); - const name = zt.syscalls.name(done.nr) orelse "?"; - // 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) 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); + /// A call as strace writes it, its arguments by name: `read fd 3 + /// "note" buf 7fffffffecd0 count 32 = 15`, cut at `room` with `…`. + fn logRow(u: ui.Ui, rec: *const Recording, made: Recording.Syscall, y: f32, room: f32) void { + const base = theme.baseline(y, row_h, size); + const adv = ui.advance(size); + var x: f32 = theme.metric.context.side; + const name = zt.syscalls.name(made.nr) orelse "syscall"; + u.text(.mono_bold, size, x, base, name, theme.color.text.bright); + x += u.width(.mono_bold, size, name) + adv; + const names = zt.syscalls.names(made.nr); + const n = @min(zt.syscalls.signature(made.nr).len, 6); + const Part = struct { text: []const u8, ink: u24 }; + var parts: [32]Part = undefined; + var np: usize = 0; + for (0..n) |j| { + const what = if (j < names.len) names[j] else ""; + if (what.len > 0) { + parts[np] = .{ .text = what, .ink = theme.color.text.dim }; + np += 1; + } + parts[np] = .{ .text = @import("disasm.zig").argument(u, rec, made.enter, what, made.args[j]), .ink = theme.color.text.primary }; + np += 1; + if (std.mem.endsWith(u8, what, "fd")) { + const on = rec.openOn(u.f.scratch, made.args[j], made.enter); + if (on.len > 0) { + parts[np] = .{ .text = on, .ink = theme.color.text.faint }; + np += 1; + } + } + } + parts[np] = .{ .text = "=", .ink = theme.color.text.faint }; + np += 1; + parts[np] = .{ .text = if (made.exit != null) result(u, made) else "?", .ink = theme.color.text.primary }; + np += 1; + for (parts[0..np]) |part| { + const w = u.width(.mono, size, part.text); + if (x + w > room) { + u.text(.mono, size, x, base, "\u{2026}", theme.color.text.faint); + return; + } + u.text(.mono, size, x, base, part.text, part.ink); + x += w + adv; } } @@ -236,7 +269,8 @@ pub const Crossing = struct { 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 path_at: ?usize = if (made) |given| std.mem.indexOfScalar(u8, zt.syscalls.signature(given.nr), 's') else null; + const span: ?Recording.Span = if (made) |given| bufferRead(given) orelse fills(given) orelse if (given.text.len > 0 and path_at != null) .{ .addr = given.args[path_at.?], .len = given.text.len + 1 } else null else null; 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, &.{}); @@ -259,140 +293,8 @@ pub const Crossing = struct { }); 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 { - 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. - const named = theme.ease(.enter, std.math.clamp((t - p.name) / theme.time.quick, 0, 1)); - const title = u.faded(named); - const rise = (1 - named) * theme.time.caption_rise; - title.text(.mono_bold, theme.size.mono.value, x, body.y + 46 + rise, name, k.ink); - title.text(.sans, theme.size.sans.micro, x + u.width(.mono_bold, theme.size.mono.value, name) + 16, body.y + 44 + rise, u.print("system call {d}", .{made.nr}), k.dim); - const signature = zt.syscalls.signature(made.nr); - var row_y: f32 = body.y + 62; - var text_used = false; - const row = struct { - /// `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); - 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 and made.exit != null; - // What `open` returns is a descriptor: open on the path it was given. - const opened = back and std.mem.eql(u8, zt.syscalls.name(made.nr) orelse "", "open") and @as(i64, @bitCast(made.result)) >= 0; - row(u.faded(std.math.clamp((t - p.rows - @as(f32, @floatFromInt(@min(signature.len, 4))) * Plan.row) / Plan.row, 0, 1)), row_y, "rax", "returns", if (back) result(u, made) else "\u{2014}", if (opened) rec.openOn(u.f.scratch, made.result, made.exit.? + 1) else ""); - - if (made.text.len == 0) return; - const bytes_x = 564; - const framed = u.faded(std.math.clamp((t - p.work) / Plan.row, 0, 1)); - framed.text(.sans, theme.size.sans.micro, bytes_x, body.y + 22, if (std.mem.indexOfScalar(u8, signature, 's') != null) "the path it was given" else "the bytes it was given", k.dim); - const shown = @min(made.text.len, shown_bytes); - const text = for (made.text[0..shown]) |byte| { - if (!std.ascii.isPrint(byte) and byte != '\n') break false; - } else true; - for (made.text[0..shown], 0..) |byte, j| { - const cell: Rect = .{ .x = bytes_x + @as(f32, @floatFromInt(j % per_row)) * 28, .y = body.y + 32 + @as(f32, @floatFromInt(j / per_row)) * 30, .w = 26, .h = 26 }; - // Each fills as it is copied, two frames a byte: struck, then held. - const since = t - p.fills - @as(f32, @floatFromInt(j)) * Plan.byte; - if (since < 0) { - framed.frame(cell, k.rule, theme.stroke.rule); - continue; - } - const in = std.math.clamp(since / theme.time.strike.in, 0, 1); - u.fill(cell, ui.mix(theme.color.kernel, ui.mix(theme.mark(.write).solid, k.held, std.math.clamp((since - theme.time.quick) / theme.time.strike.cool, 0, 1)), in)); - u.frame(cell, k.ink, theme.stroke.rule); - if (in < 0.5) continue; - // Text as its characters; anything else (a page of a file) as hex. - if (!text) { - u.label(.mono, size, cell, .center, u.print("{x:0>2}", .{byte}), k.ink); - } else if (std.ascii.isPrint(byte) and byte != ' ') u.label(.mono, size, cell, .center, &.{byte}, k.ink) else if (byte == '\n') u.label(.mono, size, cell, .center, "\\n", k.dim); - } - } - - /// The crossing itself: in from the side the registers are on as the - /// call enters, and back out as it returns. Vellum outside the - /// kernel, ink inside it. Machines do not lob: straight. - /// The crossing itself: up out of the registers below the band (the - /// ones that carried it), into the kernel, as the call enters; and back - /// down as it returns. Machines do not lob: straight. - fn arrows(u: ui.Ui, body: Rect, t: f32, p: Plan, made: Recording.Syscall) void { - // 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. - const up = cursors.standard(std.math.clamp((t - p.enters) / Plan.cross, 0, 1)); - const gone = std.math.clamp((t - p.struck - theme.time.quick) / theme.time.read.out, 0, 1); - const v = u.faded(1 - gone); - if (t < p.back) along(v, x, bottom, bottom - up * reach); - if (made.exit != null and t > p.back) along(v, x + 40, bottom - reach, bottom - reach + cursors.standard(std.math.clamp((t - p.back) / Plan.cross, 0, 1)) * reach); - } - - /// An arrow down the column at `x` from `from` to `to`, in ink: it is inside the kernel. - fn along(u: ui.Ui, x: f32, from: f32, to: f32) void { - if (@abs(to - from) < 1) return; - const w = theme.stroke.arrow; - const head = theme.stroke.flow_head; - const dir: f32 = if (to > from) 1 else -1; - const neck = to - dir * (head[0] - 2); - if ((neck - from) * dir > 0) u.fill(.{ .x = x - w / 2, .y = @min(from, neck), .w = w, .h = @abs(neck - from) }, k.ink); - if (@abs(to - from) < head[0]) return; - sk.draw.polygon(u.f, &.{ .{ x, to }, .{ x - head[1] / 2, to - dir * head[0] }, .{ x + head[1] / 2, to - dir * head[0] } }, u.at.pen(.{ .fill = ui.rgb(k.ink) })); - } }; -/// What an argument is called: by the call's own names where the tracer's -/// table has them, else from its letter in `zt.syscalls.signature`. -fn what(nr: u16, kind: u8, arg: usize) []const u8 { - const names = zt.syscalls.names(nr); - if (arg < names.len) return names[arg]; - return switch (kind) { - 'i' => "number", - 'd' => "size", - 's' => "path", - 'b' => "buffer", - else => "pointer", - }; -} - -fn value(u: ui.Ui, made: Recording.Syscall, kind: u8, arg: usize, text_used: *bool) []const u8 { - // 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))))}), - 'd' => return u.print("{d}", .{a}), - 's' => if (made.text.len > 0 and !text_used.*) { - text_used.* = true; - const base = std.fs.path.basename(made.text); - // 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 => {}, - } - return u.print("{x}", .{a}); -} - - /// What came back: a count, an address, or an error by name. fn result(u: ui.Ui, made: Recording.Syscall) []const u8 { const ret: i64 = @bitCast(made.result); diff --git a/anim/src/theme.zig b/anim/src/theme.zig index 5a85f50..0c646d8 100644 --- a/anim/src/theme.zig +++ b/anim/src/theme.zig @@ -538,6 +538,16 @@ pub const metric = struct { pub const annotation = 564; }; + /// `width`: an access's size in byte cells, where nothing else in the + /// instruction says it: cells 5 by 10, 7 apart, `dim`, on the baseline 3 + /// after the `]`; what follows 4 after the last cell. + pub const width = struct { + pub const cell = [2]f32{ 5, 10 }; + pub const pitch = 7; + pub const before = 3; + pub const after = 4; + }; + /// `bytes`: a hexdump row, from its panel's left edge (the band's right /// half): its `arc` lanes, the quiet bracket at 24, the address at 34, /// the bytes 12 after it and at 132 at least. diff --git a/anim/src/ties.zig b/anim/src/ties.zig index 323cecf..d3a9ec7 100644 --- a/anim/src/ties.zig +++ b/anim/src/ties.zig @@ -77,6 +77,9 @@ pub const Place = union(enum) { /// where its pin lane runs (canvas pixels: x, the first row's top, the /// row's height). A link to a word outside it ends at its edge. pub var stack_window: ?struct { first: u64, slots: usize, x: f32, top: f32, row: f32 } = null; +/// The source's line waits (a `descent`: the pc is in code without source): +/// the thread waits with it, primary and 2 units. +pub var thread_waits = false; /// 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. @@ -175,6 +178,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; + defer thread_waits = false; const now = g.cursor.now(at); // Diving or surfacing, the panels are on their way: no ties. for (@import("context.zig").zoomed) |z| if (z != null) return; @@ -193,8 +197,8 @@ pub const Ties = struct { fn thread(raw: ui.Ui, at: anim.Placed, k: f32) void { const line = find(.source) orelse return; const x = at.xf.apply(.{ theme.metric.tie.thread_x, 0 })[0]; - const gold = theme.mark(.current).solid; - const kind = [2]f32{ theme.metric.bracket.thread[0] * k, theme.metric.bracket.thread[1] * k }; + const gold = if (thread_waits) ui.rgb(theme.color.text.primary) else ui.rgb(theme.mark(.current).solid); + const kind = if (thread_waits) [2]f32{ theme.metric.bracket.quiet[0] * k, theme.metric.bracket.quiet[1] * k } else [2]f32{ theme.metric.bracket.thread[0] * k, theme.metric.bracket.thread[1] * k }; raw.bracket(x, line[1] + 2 * k, line[3] - 2 * k, gold, kind, 1, false); var bottom = line[3] - 2 * k; var top = line[1] + 2 * k; diff --git a/anim/test/gallery/atoms.png b/anim/test/gallery/atoms.png index 18b3e8e..796c202 100644 Binary files a/anim/test/gallery/atoms.png and b/anim/test/gallery/atoms.png differ diff --git a/anim/test/gallery/loupe.png b/anim/test/gallery/loupe.png index 5a8ca4f..750c6fd 100644 Binary files a/anim/test/gallery/loupe.png and b/anim/test/gallery/loupe.png differ diff --git a/anim/test/gallery/none.png b/anim/test/gallery/none.png index 79ce087..5fed856 100644 Binary files a/anim/test/gallery/none.png and b/anim/test/gallery/none.png differ diff --git a/anim/test/gallery/rest.png b/anim/test/gallery/rest.png index 7cc1ce7..abe30f0 100644 Binary files a/anim/test/gallery/rest.png and b/anim/test/gallery/rest.png differ diff --git a/anim/test/gallery/rows.png b/anim/test/gallery/rows.png index 4ad0d6c..e32d4b4 100644 Binary files a/anim/test/gallery/rows.png and b/anim/test/gallery/rows.png differ diff --git a/anim/test/gallery/step.png b/anim/test/gallery/step.png index 2c07506..ea3c6f1 100644 Binary files a/anim/test/gallery/step.png and b/anim/test/gallery/step.png differ diff --git a/anim/test/gallery/subject.png b/anim/test/gallery/subject.png index 0c6d40e..4524a25 100644 Binary files a/anim/test/gallery/subject.png and b/anim/test/gallery/subject.png differ diff --git a/anim/test/heap.script b/anim/test/heap.script new file mode 100644 index 0000000..9c7e375 --- /dev/null +++ b/anim/test/heap.script @@ -0,0 +1,11 @@ +# The heap scene, headless: it runs to three instants of its timeline without failing. +# (The pixel assertions written for the first layout were dropped when the +# frame became the debugger's context; new ones want a settled design: see anim/README.md.) +frames 2 +console set playing false +console set t 5 +screenshot .zig-cache/canim/heap-early.png +console set t 14 +screenshot .zig-cache/canim/heap-mid.png +console set t 999 +screenshot .zig-cache/canim/heap-end.png diff --git a/anim/test/recordings.zig b/anim/test/recordings.zig index 6d0577f..3634ee9 100644 --- a/anim/test/recordings.zig +++ b/anim/test/recordings.zig @@ -68,7 +68,8 @@ test "the program's four system calls are found, with what each was given" { n += 1; } try expectEqual(@as(usize, 4), n); - try std.testing.expectEqualStrings("open", names[0]); + // glibc's `open` makes `openat`. + try std.testing.expectEqualStrings("openat", names[0]); try std.testing.expectEqualStrings("read", names[1]); try std.testing.expectEqualStrings("close", names[2]); try std.testing.expectEqualStrings("write", names[3]); diff --git a/anim/tools/chart.py b/anim/tools/chart.py index 4f58312..998e704 100644 --- a/anim/tools/chart.py +++ b/anim/tools/chart.py @@ -42,7 +42,9 @@ none, beside, subject = split(0, 0, 14, 17, 8, 4), split(152, 152, 8, 17, 8), sp motion.REGIONS.update({ "fib": {**subject, **words}, "sort": {**subject, **words}, - "syscalls": {**subject, **words}, + # The band is the calls so far; the disassembly a descent. + "syscalls": {**beside, **words}, + "heap": {**subject, **words}, "list": {**subject, **words}, # The band's drawing is the backtrace, then the kernel's side. "sqlite": {**subject, **words}, diff --git a/anim/tools/heap.c b/anim/tools/heap.c new file mode 100644 index 0000000..3c95f07 --- /dev/null +++ b/anim/tools/heap.c @@ -0,0 +1,31 @@ +#include + +typedef struct node { + long value; + struct node *next; +} node; + +node *head; + +void push(long value) { + node *n = malloc(sizeof *n); + n->value = value; + n->next = head; + head = n; +} + +void pop(void) { + node *n = head; + head = n->next; + free(n); +} + +int main(void) { + push(7); + push(12); + push(9); + pop(); + pop(); + push(25); + return 0; +} -- cgit v1.3