summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-13 09:28:38 -0300
committerGabriel Schneider <[email protected]>2026-11-13 09:28:38 -0300
commit5c0230ea5a77f85de77ad4354788cd6c27aa1ef6 (patch)
treee01a903bdee092965b86e118dfaab85c3bd60004
parent5a40dca5adb6e9e650f55f3ec6f254a13bf50493 (diff)
downloadcomputeranim-5c0230ea5a77f85de77ad4354788cd6c27aa1ef6.tar.gz
computeranim-5c0230ea5a77f85de77ad4354788cd6c27aa1ef6.zip
debugger: follow natural V8 deoptimization with adaptive live views
-rw-r--r--anim/src/disasm.zig10
-rw-r--r--anim/src/graph.zig41
-rw-r--r--gui/README.md241
-rw-r--r--gui/bench/RESULTS.md210
-rw-r--r--gui/bench/control.py180
-rw-r--r--gui/bench/steps.py177
-rw-r--r--gui/build.zig8
-rw-r--r--gui/src/Geometry.zig57
-rw-r--r--gui/src/Navigation.zig14
-rw-r--r--gui/src/Sources.zig17
-rw-r--r--gui/src/app.zig830
-rw-r--r--gui/targets/jit.js25
-rw-r--r--gui/targets/segments.c25
-rw-r--r--gui/test/adaptive.py114
-rw-r--r--gui/test/basic.script28
-rw-r--r--gui/test/inspection.py132
-rw-r--r--src/cli/dbg.zig6
-rw-r--r--src/cli/serve.zig14
-rw-r--r--src/trace/Debugger.zig22
-rw-r--r--src/trace/Symbols.zig59
-rw-r--r--src/trace/control.zig1
21 files changed, 1497 insertions, 714 deletions
diff --git a/anim/src/disasm.zig b/anim/src/disasm.zig
index afeef1b..b3049f1 100644
--- a/anim/src/disasm.zig
+++ b/anim/src/disasm.zig
@@ -1221,6 +1221,7 @@ pub fn plainRow(u: ui.Ui, row: Insn, y: f32) void {
/// The same instruction atoms for a live debugger: one moment, without
/// indexing an animation's entire recording. Only observed operands are annotated.
pub fn liveRow(at: ui.Ui, row: Insn, y: f32, width: f32, moment: Recording.Moment, regs: zt.Regs, options: struct {
+ compact: bool = false,
current: bool = false,
executed: bool = false,
lead: usize = 0,
@@ -1229,13 +1230,16 @@ pub fn liveRow(at: ui.Ui, row: Insn, y: f32, width: f32, moment: Recording.Momen
heat: ui.Heat = .none,
}) void {
const base_y = rows.baseline(y);
- _ = at.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(theme.color.region.code_), .lead = options.lead });
- const shift = @as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv;
+ if (options.compact) {
+ at.text(.mono, size, c.address, base_y, at.print("…{x:0>4}", .{row.addr & 0xffff}), theme.color.region.code_);
+ at.hitAddress(row.addr, .{ .x = c.address, .y = y, .w = 5 * adv, .h = 24 });
+ } else _ = at.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(theme.color.region.code_), .lead = options.lead });
+ const shift: f32 = if (options.compact) -64 else @as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv;
const u = at.moved(shift, 0);
const room = width - shift - m.side;
const pad = row.padding();
const mn = row.mnemonic();
- if (row.line) |line| u.text(.mono, size, c.line, base_y, u.print("{d}", .{line}), t.faint);
+ if (!options.compact) if (row.line) |line| u.text(.mono, size, c.line, base_y, u.print("{d}", .{line}), t.faint);
u.text(.mono_bold, size, c.mnemonic, base_y, mn, if (pad) t.faint else theme.color.code.keyword);
var name_buf: [192]u8 = undefined;
const name = if (target(row)) |to| (moment.string(to, &name_buf) catch null) orelse "" else "";
diff --git a/anim/src/graph.zig b/anim/src/graph.zig
index 9eb6f2d..03d8fc8 100644
--- a/anim/src/graph.zig
+++ b/anim/src/graph.zig
@@ -109,7 +109,7 @@ pub const Edge = struct {
/// Its length along its way.
pub fn length(e: *const Edge) f32 {
var total: f32 = 0;
- for (e.path()[0 .. e.n -| 1], e.path()[@min(1, e.n)..]) |a, b| total += dist(a, b);
+ for (e.path()[0..e.n -| 1], e.path()[@min(1, e.n)..]) |a, b| total += dist(a, b);
return total;
}
@@ -2007,6 +2007,45 @@ fn drawMark(u: ui.Ui, v: Instant) void {
/// its size: over the program column the function's graph in the form
/// the scene names (`rings`; `layers` where it has no loop), centred in
/// its pane, a block a pill. Its rows are the disassembly under the source.
+/// Bounded live-stop graph: blocks and observations only, never inferred execution counts.
+pub fn live(u: ui.Ui, m: zt.store.Moment, pc: u64, observed: [3]u64, opacity: f32) f32 {
+ const arena = u.f.scratch;
+ const probe = zt.telescope.blocks(m, pc, &.{}) orelse {
+ u.text(.sans, 20, 20, 38, "Control-flow blocks were not captured here", t.dim);
+ return 64;
+ };
+ const raw = arena.alloc(zt.telescope.Block, @min(probe.count, 4096)) catch return 0;
+ const found = zt.telescope.blocks(m, pc, raw) orelse return 0;
+ const nodes = arena.alloc(Node, found.blocks.len) catch return 0;
+ const spans = arena.alloc(Span, nodes.len) catch return 0;
+ for (found.blocks, nodes, spans, 0..) |b, *n, *span, k| {
+ n.* = .{ .start = b.start, .len = b.len, .end = b.end, .w = 270, .h = 64 };
+ span.* = .{ .start = b.start, .len = b.len, .node = @intCast(k) };
+ }
+ var edges: std.ArrayList(Edge) = .empty;
+ for (found.blocks, 0..) |b, k| {
+ if (b.to) |to| if (blockAt(nodes, to)) |at| edges.append(arena, .{ .from = @intCast(k), .to = at, .kind = if (b.end == .branch) .taken else .jump }) catch return 0;
+ if (b.falls) |to| if (blockAt(nodes, to)) |at| edges.append(arena, .{ .from = @intCast(k), .to = at, .kind = .fall }) catch return 0;
+ }
+ var g: Graph = .{ .start = found.start, .len = found.len, .nodes = nodes, .spans = spans, .edges = edges.items, .here = blockAt(nodes, pc), .text = found.text, .exact = false };
+ place(arena, &g, .layers) catch return 0;
+ const v = u.moved(16, 16);
+ var path: [most]ui.Vec = undefined;
+ for (g.edges) |edge| v.route(vecs(&path, edge.path()), if (edge.kind == .fall) t.faint else theme.color.rule, .{ .width = 1.5, .head = gm.head, .radius = 0 });
+ for (g.nodes) |node| {
+ const current = node.contains(pc);
+ const seen = for (observed) |addr| {
+ if (node.contains(addr)) break true;
+ } else false;
+ const ink = if (current) theme.mark(.current).solid else t.dim;
+ const n = v.faded(if (current or seen) 1 else @max(0.15, opacity));
+ pill(n, .{ .x = node.x, .y = node.y, .w = node.w, .h = node.h }, ui.rgb(theme.color.raised), ui.rgb(ink), if (current) 2 else 1, false);
+ _ = n.address(node.x + 16, node.y + 26, node.start, .{});
+ n.text(.mono, 16, node.x + 16, node.y + 49, n.print("{s} · {d} bytes", .{ @tagName(node.end), node.len }), ink);
+ }
+ return g.h + 32;
+}
+
pub const Blocks = struct {
cursor: cursors.Cursor,
stage: *const Stage,
diff --git a/gui/README.md b/gui/README.md
index 20fe292..83e4678 100644
--- a/gui/README.md
+++ b/gui/README.md
@@ -1,19 +1,10 @@
# ztrace GUI
-A separate native application using **ztrace** for control and recordings and
-**canim / Sketchbook** for the view. The libraries stay where they are. It launches
-a real Linux x86-64 process, stops at breakpoints, steps, and browses recorded
-machine state. No gdb subprocess or browser frontend.
-
-The fixed, dense view uses the animation library's source syntax colors, aligned
-instruction cells, operand values, flag marks, pointer colors, telescope chains,
-stack roles, frame spans, byte rows, and minimap strokes. Source runs line up with
-their machine instructions; the gold thread connects the active run to the PC.
-Changed registers, stack words and bytes strike, cool, and retain a corner mark.
-Click an address for an animated memory lens; right-click to follow its meaning.
-
-Build with the same Zig toolchain as the rest of computeranim; the sibling
-`sketchbook` and `pardes` checkouts are the existing renderer dependencies:
+A native, live Linux x86-64 debugger using **ztrace** for process control and
+recordings and **canim / Sketchbook** for rendering. Continue, pause, instruction
+step and source step operate on the running process. Each stop records a snapshot;
+browsing that history does not rewind execution. There is no gdb subprocess,
+browser frontend, or continuous instruction trace.
```sh
cd gui
@@ -22,8 +13,12 @@ zig build test -Doptimize=ReleaseFast
zig build run -Doptimize=ReleaseFast -- --fresh
```
-The build installs `ztrace` alongside `ztrace-gui`; keep the two together.
-Colon opens the debugger command bar; backtick opens the renderer's console:
+Use the repository's Zig toolchain and existing sibling `sketchbook` and `pardes`
+checkouts. Keep the installed `ztrace` beside `ztrace-gui`.
+
+## Controls
+
+Colon opens the debugger command bar; backtick opens the renderer console.
```text
launch /absolute/path/to/program arguments
@@ -31,154 +26,128 @@ break main
continue
break *0x12345678
clear 1
-signal 0
interrupt
stepi
nextline
+goto code 0x12345678
+goto stack 0x12345678
goto memory 0x12345678
+source-map /remote/build/source /local/source
+symbols /tmp/current-jit-object.o
+origin 0x12345678
```
-`break` accepts the library's function, file:line and `*address` forms. Its reply
-includes the breakpoint ID. The icon buttons have hover labels and keys; pane
-headers hold history, follow, minimap and interpretation controls.
+`break` accepts function, file:line and `*address` forms. `origin` retains the
+recorded source location of an originating JS instruction during a native
+transition. `source-map` resolves the longest matching directory prefix in the
+shared symbol library, both for live control and offline GUI source loading.
+Relative prefixes resolve against the debugger's working directory.
| Keys | Action |
| --- | --- |
-| `s`, `n` | One instruction / next source line (enters calls) |
+| `s`, `n` | Instruction / next source line (enters calls) |
| `c`, `Esc` or `Ctrl-c` | Continue / pause |
-| `j` / `k`, `Ctrl-d` / `Ctrl-u`, `gg` / `G` | Smooth scroll, half page, first / last row |
-| `h` / `l` | Inspect long source lines horizontally |
-| `Ctrl-w h/j/k/l`, `Tab` | Focus a pane |
-| `Ctrl-o` / `Ctrl-i`, Mouse4 / Mouse5 | Back / forward in the hovered or focused pane |
+| `Ctrl-+` / `Ctrl-=` / `Ctrl--`, `Ctrl-0` | Font scale in 10% steps, 60–200%; reset |
+| `j` / `k`, `Ctrl-d` / `Ctrl-u`, `gg` / `G` | Scroll, half page, segment start / end |
+| `PageUp` / `PageDown` | Scroll the stacked page |
+| `h` / `l`, `Shift-h` / `Shift-l` | Source horizontal scroll / pane horizontal scroll |
+| `Tab`, `Ctrl-w h/j/k/l` | Focus pane |
+| `Ctrl-o` / `Ctrl-i`, Mouse4 / Mouse5 | Pane address history |
| `[` / `]`, `Shift-f` | Recorded stop history / latest live stop |
-| `f` | Follow the live address in the focused pane |
-| `v`, `m`, `a` | Source columns, minimap, operand annotations |
-| `b`, `z`, `?`, `:` | Break at PC, address lens, help, command line |
-
-Scrolling accepts fractional wheel deltas. Click or drag the actual-content
-minimap to move its viewport. Each pane's bounded jump history remembers address
-and scroll, and a new jump discards its forward branch. Browsing recorded state
-never rewinds the process. Continuing returns the moment selection to live.
-Source stepping may stay in a loop on one source line; pause with Esc / Ctrl-c.
-
-A right-click follows executable memory (including RWX) into disassembly, stack
-memory or a pointer-bearing word into the telescope, and other memory into the
-hex view. Unknown bytes stay unknown. At a live stop this requests a bounded
-read-only capture; it never writes RIP or resumes the target. `goto code|stack|memory
-ADDRESS` selects a specific view. The first pass bounds views to 256 decoded
-instructions, 128 stack slots, and 128 hex rows; jump to another address to inspect
-further. A lens shows five real rows and follows further pointers when clicked.
-
-The renderer already uses `pause` and `step` for its own timeline. The debugger's
-console names are `interrupt` and `nextline` to keep those separate. Do not use
-renderer playback to replay debugger commands.
-
-Without a launched target, `open /path/to/file.ztrace` views an existing recording.
-Live recordings remain at `/tmp/ztrace-gui-PID-TIMESTAMP.ztrace` after closing.
-Closing the GUI terminates the target it launched. Target stdin is `/dev/null`;
-its stdout and stderr go to the GUI's stderr. There is no terminal emulation.
+| `f` | Follow current live address in focused pane |
+| `p` | Search mapping names, addresses and permissions for the active pane |
+| `t`, `d` | Control-flow graph / unobserved opacity (25%, 50%, 75%, 100%) |
+| `v`, `m`, `a` | Source, minimap, operand annotations |
+| `b`, `z`, `?`, `:` | Break at PC, lens, help, command bar |
-## How it fits
+Wide windows keep code beside registers and memory beside stack. Smaller windows
+stack these panes; wheel over a header/gutter or use PageUp/PageDown to reach them.
+Font scaling recomputes geometry, visible rows and pointer hit regions. Every new
+execution stop reveals PC and its source group. Manual scrolling lasts until the
+next stop; an explicit address jump stays pinned until Follow is enabled.
-The GUI starts `ztrace serve RECORDING -- PROGRAM [ARGS]` with private pipes.
-A single controller thread owns every ptrace operation. A `std.Io.concurrent`
-reader feeds a bounded `std.Io.Queue`; `Debugger.on_wait` services that mailbox
-while the target runs. `Debugger.interrupt` requests SIGSTOP and suppresses its
-redelivery. Idle waits use `std.Io.sleep`, while fast steps briefly poll.
-Existing synchronous debugger callers retain their blocking wait.
+Stack, memory and disassembly navigation span the **entire selected mapping**.
+The thin right minimap rail maps its full address range. The adjacent content
+minimap compresses source-only gaps and unknown memory rows. `p` selects any
+mapping from the selected recording moment and adds the jump to that pane's
+history. At a live stop, navigation fetches only a bounded window (128 instructions
+or 2 KiB), without resuming the target or changing RIP. Historical views use
+recorded bytes only: uncaptured data remains unknown. Arbitrary x86 address jumps
+start decoding at the requested byte; instruction boundaries are only certain
+when supplied by recorded code, symbols or a known entry point.
-Replies are small newline-delimited JSON values (`src/trace/control.zig`). A
-`std.Io` task in the GUI reads replies into one mutex-protected latest snapshot.
-The draw loop never waits for ptrace. Each completed command flushes the existing
-recorder before publishing its stop; the GUI reopens that committed snapshot and
-queries `Trace.moment`. File I/O, subprocesses, queues, tasks, locks and timing use
-`std.Io`. Raw Linux calls remain at the ptrace/signal and descriptor boundaries.
+Click an address to open a connected lens. Further pointers keep their ancestors;
+a different pointer in a parent replaces its descendants. Each close button closes
+that lens and its children. Cycles, unreadable addresses and uncaptured historical
+bytes are labeled. Long chains scroll within the overlay. Right-click routes an
+address to disassembly, stack telescope or memory according to its mapping/value.
-New executable mappings are refreshed when a stop's PC is previously unknown,
-so code produced by a JIT is recorded without tracing every syscall. Entering
-code without source lines clears the previous source location in the recording. The GUI
-uses bounded moment queries rather than indexing an entire animation recording.
-It draws the existing canim components without requiring an animation timeline.
+The graph uses recorded basic blocks and shared graph layout. It is scoped to
+captured code, not a complete static analysis of an entire executable. Gold marks
+PC; recent observed PCs are bright. Branch-target annotation is a prediction from
+the current flags. Dimming means **unobserved**, not proof an instruction was
+skipped: Continue does not record all intermediate execution.
-## Debug V8
+## Natural V8 deoptimization
-Build V8 on `chaincli-box`, using the `v8-remote-build` skill. Copy d8 together
-with its shared libraries, data/snapshots and build flags to the workstation.
-See [the measured run](bench/RESULTS.md) for the exact revision and limitations.
-
-For the deterministic JIT fixture:
-
-```sh
-./zig-out/bin/ztrace-gui --fresh \
- --console 'launch /tmp/computeranim-v8-debug-remote/d8 --allow-natives-syntax --no-concurrent-recompilation --no-maglev --print-opt-code --print-opt-code-filter=jitWork /absolute/path/to/computeranim/gui/targets/jit.js' \
- --console continue 2>/tmp/ztrace-jit.log
-```
-
-`%SystemBreak()` first stops in V8's native runtime after optimizing `jitWork`.
-Find the address of `addl r8,r11` in its printed TurboFan loop body. In the GUI
-console, enter `signal 0`, `break *ADDRESS`, then `continue`. This second stop is
-a software breakpoint inside the generated JavaScript code, not the runtime
-trap. `s` steps through that machine code. Addresses change on each launch.
-The benchmark checks both RIP and that it belongs to an anonymous executable map.
+Use the existing debug build on `chaincli-box`; see [results and provenance](bench/RESULTS.md).
+`targets/jit.js` warms `jitWork` with one object shape, then supplies another.
+It uses no optimization intrinsics, traps, engine patches or tier-disabling flags.
```sh
# From the repository root, after building gui/:
-python3 gui/bench/steps.py --d8 /tmp/computeranim-v8-debug-remote/d8
+python3 gui/bench/steps.py --d8 /tmp/computeranim-v8-debug-remote/d8 \
+ --source /tmp/computeranim-v8-source --out /tmp/ztrace-natural-bench
+python3 gui/test/inspection.py --d8 /tmp/computeranim-v8-debug-remote/d8
```
-The script builds a small C control, tests the JIT breakpoint, steps each target
-1,000 times with identical capture settings, and writes recordings, target logs
-and `results.json` under `/tmp/ztrace-step-bench`. `capture` includes ptrace,
-register/stack/telescope/disassembly capture and recording flush; `roundtrip`
-also includes pipe transport and the Python driver. Neither measures display
-presentation latency. First-break timing includes target startup and initial
-symbol work. Debugger builds use ReleaseFast; target builds remain Debug.
-
-## First-pass boundaries
+The harness waits for natural TurboFan code, imports the matching V8 GDB JIT ELF,
+stops at its wrong-map guard exit, verifies the originating return address at
+`v8::internal::Deoptimizer::New`, continues to
+`v8::internal::Runtime_NotifyDeoptimized`, and identifies the actual fallback by
+stepping into its dispatch handler. This revision resumed Ignition; another build
+may resume a different tier. The harness fails instead of relabeling it.
-Fixed layout, one launched target, selected stopped thread, address/function
-breakpoints, and machine-state history. There is no attach UI, thread picker,
-expression evaluator, reverse execution or JavaScript source-map integration.
-Launch arguments are whitespace-separated (no shell quoting). V8 JIT names/code
-movement are not registered automatically: this fixture obtains the address from
-V8's own disassembly and stops before using it. Breakpoints are not relocated if
-V8 moves or discards generated code.
-
-Split DWARF files and V8 source must be retrieved separately for full C++ local
-inspection. The current renderer is a canvas with keyboard controls; it does not
-yet expose debugger rows through a native accessibility tree.
-
-
-### JavaScript source beside JIT code
-
-V8 can emit GDB JIT ELF objects containing actual line tables. Run the fixture
-from its directory, using its **basename** (V8's dump filename embeds the script
-name and cannot contain directory separators):
+For the interactive session, run from `gui/targets` with the script basename
+(V8 embeds that name in its JIT ELF dump filename):
```text
-launch /tmp/computeranim-v8-debug-remote/d8 --allow-natives-syntax --no-concurrent-recompilation --no-maglev --gdbjit --gdbjit-dump --gdbjit-dump-filter=jitWork --print-opt-code --print-opt-code-filter=jitWork jit.js
+launch /tmp/computeranim-v8-debug-remote/d8 --trace-opt --trace-deopt --trace-deopt-verbose --print-opt-code --print-opt-code-filter=jitWork --gdbjit --gdbjit-dump --gdbjit-dump-filter=jitWork jit.js
+break main
+continue
+clear 1
+source-map ../../src /tmp/computeranim-v8-source/src
+break v8::internal::Deoptimizer::New
+break v8::internal::Runtime_NotifyDeoptimized
+continue
```
-After reaching the generated-code breakpoint, import the emitted object:
-
-```text
-symbols /tmp/elfdumpjitWork jit.js:3:170.o
-```
+Ignore unrelated outer-loop deoptimizations. Use the printed `jitWork` TurboFan
+block containing the `wrong map` relocation to locate the generated exit and its
+guard. Import the dumped ELF whose executable section covers that exact code
+address using `symbols PATH` (multiple compilations produce multiple objects).
+Break at the exit, inspect the guard's code, set `origin GUARD_ADDRESS`, and continue
+to Deoptimizer::New. Its x86-64 `rdx` must equal that exit's recorded return PC.
+The guard maps to JS property access line 3; the shared exit stub's own line table
+can instead name the return statement. Addresses change each run. The harness
+in `bench/control.py` is the executable version of these checks.
-Use the actual emitted filename. The shared debugger validates its executable
-sections against the stopped target and reuses the ELF/DWARF reader; inline
-DWARF strings do not require `.debug_str`. The import is committed as an
-inspection moment without moving the target. Source files are loaded with
-`std.Io` and cached with owned syntax data. Missing source is explicitly labeled.
+## Recording and boundaries
-This is an explicit import of the current JIT object, not a watcher of the GDB
-JIT registration protocol. Import a fresh object after code regeneration; it
-must belong to the current process. No fabricated JS-to-instruction mapping is
-used. Split native V8 `.dwo` files are still needed for complete C++ debug info.
+`open PATH.ztrace` opens history without launching a target. Live recordings stay
+at `/tmp/ztrace-gui-PID-TIMESTAMP.ztrace` after closing. Closing the GUI terminates
+its launched target. Target stdin is `/dev/null`; stdout/stderr go to GUI stderr.
+Launch arguments are whitespace-separated, without shell quoting.
-Read-only capture and JIT source integration checks:
+A single controller thread owns ptrace; a mailbox services commands while the
+process runs. Stop replies follow recording flush; drawing reads committed
+snapshots without blocking on ptrace. Mappings refresh at each stop, including
+new non-code mappings. Inspection commits metadata/bytes without executing.
+`capture_ns` measures stop capture and flush separately from total command time.
-```sh
-python3 gui/test/inspection.py --d8 /tmp/computeranim-v8-debug-remote/d8
-python3 gui/bench/steps.py --d8 /tmp/computeranim-v8-debug-remote/d8 --jit-source --out /tmp/ztrace-step-bench-source
-```
+One launched process and selected stopped thread are supported. There is no
+attach UI, thread picker, expression evaluator or reverse execution. JIT ELF
+imports are explicit; breakpoints do not relocate when generated code moves.
+Retrieved split DWARF artifacts are available, but complete split-DWARF C++ local
+variable inspection is not implemented. The canvas has keyboard controls but
+still lacks a native accessibility tree for debugger rows.
diff --git a/gui/bench/RESULTS.md b/gui/bench/RESULTS.md
index 89f0d78..0426dce 100644
--- a/gui/bench/RESULTS.md
+++ b/gui/bench/RESULTS.md
@@ -1,134 +1,134 @@
-# Debug V8 versus a small C target
+# Natural V8 deoptimization and stepping measurements
-Measured locally on 2026-11-13, Linux 7.2.11-arch1-1, Intel i7-11700,
-Zig 0.17.0, ReleaseFast controller. The targets were a `cc -g -O0` C loop
-and **unoptimized debug V8**, not release d8. Both used the same controller:
-512 stack bytes, 24 disassembled instructions and telescope depth 2, with a
-recording flush at every stop. No syscall tracing and no continuous stepping
-while the user has selected Continue.
-
-Final controller run:
+Measured 2026-11-13 on Linux 7.2.11-arch1-1, Intel i7-11700, Zig 0.17.0,
+ReleaseFast debugger; targets are `cc -g -O0` C and unoptimized debug V8.
+Source is loaded for both. Capture settings are 512 stack bytes, 24 instructions,
+telescope depth 2, mapping refresh and recording flush at every stop. Continue
+runs normally between breakpoints; no continuous instruction tracing occurs.
```sh
-python3 gui/bench/steps.py \
- --d8 /tmp/computeranim-v8-debug-remote/d8 \
- --ztrace zig-out/bin/ztrace \
- --out /tmp/ztrace-step-bench-ui
+python3 gui/bench/steps.py --d8 /tmp/computeranim-v8-debug-remote/d8 \
+ --source /tmp/computeranim-v8-source --out /tmp/ztrace-natural-bench-final
```
-| 1,000 instruction steps | C | Debug V8 / generated JS |
+| 1,000 steady instruction steps | C | Debug V8 / TurboFan JS |
| --- | ---: | ---: |
-| Capture + flush, median | 37.48 µs | 38.43 µs |
-| Capture + flush, p95 | 54.37 µs | 52.48 µs |
-| Controller round trip, median | 49.49 µs | 49.48 µs |
-| Controller round trip, p95 | 72.46 µs | 68.31 µs |
-| Controller round trip, maximum | 553.21 µs | 364.10 µs |
-| Launch through first requested breakpoint | 5.98 ms | 938.49 ms |
-
-This supports comparable steady instruction-step cost for these workloads.
-It does not claim that V8 starts as quickly as a small program, or that all C++
-source/DWARF operations have this cost. The previous 1,000-step run measured
-35.73 / 38.47 µs capture medians and 46.94 / 49.53 µs round-trip medians for
-C / V8. Scheduling and cache state affect these microsecond measurements; no
-CPU isolation or filesystem-cache dropping was used. GUI presentation is not
-included in the controller timings.
+| Capture + flush, median | 48.16 µs | 133.16 µs |
+| Capture + flush, p95 | 75.98 µs | 153.33 µs |
+| Entire command, median | 55.00 µs | 140.00 µs |
+| Controller round trip, median | 68.88 µs | 154.44 µs |
+| Controller round trip, p95 | 105.64 µs | 208.51 µs |
+| Controller round trip, maximum | 567.93 µs | 539.92 µs |
-The V8 fixture compiles `jitWork` with TurboFan, traps in the native runtime,
-then installs an actual software breakpoint at `addl r8,r11` inside the
-optimized loop. The harness asserts the returned RIP equals that address and
-lies in an anonymous executable mapping. It then tests source-step fallback
-without JIT source lines, records the instruction-step sample, and checks that
-the recording no longer reports the previous native source line. The loop
-address is read from V8's own output; the harness fails rather than guesses if
-a different V8 compiler allocates different registers.
+`capture_ns` covers reporting state plus recording flush. `elapsed_ns` covers the
+whole command, including execution/wait and capture. Round trip additionally
+includes pipes and the Python driver. Neither includes GUI presentation.
+Launch through first generated stop and JIT source import took 1,288.73 ms.
+No CPU isolation or filesystem-cache dropping was used. These are workload
+measurements, not a release-V8 performance comparison. Per-stop mapping refresh
+and natural tiering differ from the earlier forced-optimization demonstration;
+its old figures are not directly comparable.
-The raw records, logs and JSON results are in `/tmp/ztrace-step-bench-ui`.
-The script is the durable reproducer; `/tmp` artifacts are not permanent.
+## Verified transition
-With JIT source information loaded, the final 1,000-step run remained comparable:
+The ordinary fixture naturally compiled through Maglev and TurboFan. After
+warming `jitWork` on `{value:7}`, `{extra:1,value:9}` hit its TurboFan wrong-map
+guard. The generated exit's return PC matched the `rdx` origin argument at
+`Deoptimizer::New`; unrelated outer-loop bailouts were ignored. Native source
+resolved at both Deoptimizer::New (`deoptimizer.cc:290`) and
+Runtime_NotifyDeoptimized (`runtime-compiler.cc`). The guard mapped to JS line 3,
+`let sum = object.value`. Its shared exit stub mapped to a different JS line, so
+origin context deliberately uses the guard.
-| Source-enabled run | C | Debug V8 / generated JS |
+| Transition stop | Capture + flush | Entire command |
| --- | ---: | ---: |
-| Capture + flush, median | 36.60 µs | 37.76 µs |
-| Capture + flush, p95 | 46.78 µs | 46.35 µs |
-| Controller round trip, median | 48.04 µs | 48.84 µs |
-| Controller round trip, p95 | 60.97 µs | 63.83 µs |
+| generated wrong-map exit | 372.09 µs | 1192.34 µs |
+| Deoptimizer::New | 202.01 µs | 214.16 µs |
+| Runtime_NotifyDeoptimized | 265.13 µs | 1086.31 µs |
+| InterpreterEnterAtBytecode | 445.40 µs | 752.09 µs |
+| Ignition property bytecode handler | 15163.99 µs | 15474.67 µs |
-Reproduce with `--jit-source --out /tmp/ztrace-step-bench-source` added to the
-command above. This run imports the real JIT ELF before sampling and checks the
-final recording retains JavaScript source information. The initial import is
-excluded from steady stepping, just as executable startup is excluded.
+The immediate fallback was **Ignition**, confirmed by stopping at
+`Builtins_InterpreterEnterAtBytecode` and stepping into
+`Builtins_GetNamedPropertyHandler`. This is actual interpreter dispatch,
+not an inference from the deoptimizer's frame-reconstruction log. The first
+handler capture incurred additional symbol/function work, which is why transition
+costs are reported separately from warmed stepping. The script completed with
+`mismatch 499509` and `fallback 499507`. Default tiers remain enabled; this does
+not imply that other V8 builds always resume Ignition.
-## V8 provenance
+Raw logs, recordings and JSON are in `/tmp/ztrace-natural-bench-final`; the
+checked-in scripts are the durable reproducer. Addresses/PIDs in those files are
+session-specific and `/tmp` artifacts are not permanent.
-The user's remote Arch build host (`chaincli-box`) has the existing checkout at
-`/home/goblin/v8-research/v8`. Ninja verified the compatible debug build up to date
-(`ninja: no work to do`). No V8 compilation was performed on the workstation.
-The complete runtime artifacts were copied to `/tmp/computeranim-v8-debug-remote`
-and smoke-tested locally.
+## Source and build provenance
+- Remote: `chaincli-box`, `/home/goblin/v8-research/v8`.
- Revision: `84703f702dca525edd469f3a98d784faa46a02f8`.
-- d8 version: `15.2.0 (candidate)`.
-- Output: `out/x64.debug-vuln` (historical directory name).
-- Existing unrelated local `BUILD.gn` change to the `v8_fuzzer` source list was
- preserved; the checkout was not reset or updated.
+- d8: `15.2.0 (candidate)`, existing `out/x64.debug-vuln`.
- `is_debug=true`, `v8_optimized_debug=false`, `symbol_level=2`,
`v8_symbol_level=2`, `use_debug_fission=true`, `target_cpu="x64"`.
- Disassembler, object printing, heap verification, slow DCHECKs and backtraces
enabled; `use_remoteexec=false`, `use_siso=false`.
-- Component build: d8 plus its shared libraries (including the large debug
- libv8.so), snapshots and ICU data. Split `.dwo` files were not copied, so this
- run is not a validation of complete C++ local-variable/source debugging.
+- Existing remote `BUILD.gn` edits and untracked files were preserved. No engine
+ patch, rebuild, checkout reset or workstation V8 compilation was needed.
+
+The component runtime (d8, shared libraries, snapshots and ICU data) is at
+`/tmp/computeranim-v8-debug-remote`. Matching `src/` and all 2,328 `.dwo` files
+were copied from the same checkout to `/tmp/computeranim-v8-source` (about 1.9 GiB
+combined). To retrieve again after verifying the same revision:
+
+```sh
+rsync -a -e 'ssh -F ~/.ssh/config -o BatchMode=yes' \
+ chaincli-box:/home/goblin/v8-research/v8/src/ /tmp/computeranim-v8-source/src/
+rsync -a --include='*/' --include='*.dwo' --exclude='*' \
+ -e 'ssh -F ~/.ssh/config -o BatchMode=yes' \
+ chaincli-box:/home/goblin/v8-research/v8/out/x64.debug-vuln/obj/ \
+ /tmp/computeranim-v8-source/out/x64.debug-vuln/obj/
+```
-## Checks
+This build's skeleton line tables use comp_dir `.` and stripped `../../src`
+paths. `source-map ../../src /tmp/computeranim-v8-source/src` resolves them
+through the shared debugger source-prefix interface. Native line resolution was
+verified; full split-DWARF C++ local-variable inspection was not implemented.
-The GUI's real-target script exercises launch, a named breakpoint through the
-Vim command bar, continue, keyboard and mouse instruction stepping, source
-stepping, pause during execution and browsing history back to live. It also
-checks fractional scrolling, pane histories, Mouse4/5 through the actual
-pointer handler, semantic right-clicks, minimap dragging and animated lenses.
-Native-window checks cover keyboard stepping, pane focus, scrolling and command
-entry. Raw hardware Mouse4/5 injection was not performed.
+## Verification
-`gui/test/inspection.py` checks bounded read-only code/memory inspection against
-C and debug V8: RIP stays unchanged, invalid counts are rejected, and subsequent
-stepping still works. With `--d8`, it imports V8's real GDB JIT ELF and asserts
-that source line 6 of the JavaScript fixture appears in the recorded instruction
-metadata. The line mapping comes from V8's DWARF line program.
+`gui/test/inspection.py --d8 /tmp/computeranim-v8-debug-remote/d8` passes bounded
+read-only inspection, unchanged RIP, invalid-count rejection, source-prefix
+replacement, natural optimization, matching JIT ELF import, native deoptimization
+stops and actual fallback dispatch.
-The root suite had two failures before this work; they remain in the existing
-loader/syscall formatting and watch/string assertions. The new debugger tests
-pass (86/88 in the full root suite; 25/27 debugger tests, with those same two
-failures). No assertion was
-weakened to hide them.
+GUI tests cover live stepping/pause/history, source stepping, semantic address
+navigation, minimap dragging, changed-state animation and lenses. Adaptive tests
+use 2240×1260, 1440×900 and 800×700 at 60%, 100% and 200%: full 4 GiB mapping
+navigation with single-row precision, per-pane segment history, pinned refresh at
+repeated same-PC stops, graph/dim controls and font reset. Independent visual
+review additionally checks PC/source alignment, pointer hit targets, compact
+minimaps, lens cycles/collapse and native interaction.
-## Rich GUI verification
+The shared renderer/gallery suite passes. The root suite has 87/89 passing tests;
+the same two pre-existing loader/syscall-format and watch/string assertions fail
+(25/27 debugger tests). No assertions were weakened. The canvas still lacks a
+native accessibility tree, and raw hardware Mouse4/5 injection was not tested.
-A separate UI agent compared rendered C and V8 frames against the existing
-animation design, checked strike/highlight/settled frames, and approved the
-final native window. The checked-in GUI test asserts that the stack highlight
-changes between strike and settled screenshots, as well as exercising controls.
+## Final interactive stop
-At 2240×1260, an approximate headless redraw measurement was **3.55 ms/frame
-for C and 4.28 ms/frame for V8**, including source/disassembly, registers,
-stack, memory and cached content minimaps. `gui/bench/redraw.py` subtracts the
-median elapsed time of 30-frame runs from 330-frame runs (three repeats each),
-then divides by 300. Both opened their corresponding source-enabled 1,000-step recording;
-this is a whole-view cost, not an equal-row renderer comparison. It excludes
-live trace reopening and display presentation latency. Raw timings are in
-`/tmp/ztrace-gui-redraw-source.json`. The previous, smaller 1920×1080 view measured
-1.23 / 2.41 ms/frame for C / V8.
+The native GUI remains open with d8 PID 2639255 in Linux tracing-stop state at
+`Deoptimizer::New+4`, RIP `0x7fa19dbe3f74`, on native source line 290.
+Its `rdx = 0x7fa1e0000ffa` matches the normal `jitWork` TurboFan wrong-map exit's
+return PC exactly. The retained JS context is the guard at `0x7fa1e0000c14`,
+`jit.js:3`, not the shared exit stub's line 5.
-The complete animation gallery and shared renderer tests passed after the
-library changes. Existing applications retain their organization: the GUI uses
-shared source preparation/alignment, row drawing, address hit geometry and
-minimap drawing instead of maintaining a second renderer.
+GUI PID 2639214; recording
+`/tmp/ztrace-gui-2639214-392301809642450.ztrace`, moment 8.
+This session used ordinary default tiering and symbolic native breakpoints.
+The complete fallback transition was verified separately by the benchmark above,
+so the interactive target can remain at the requested deoptimization entry.
-The final native window was independently approved with debug d8 PID 2536162
-in Linux tracing-stop state at breakpoint 1, RIP `0x7f6ee00001a2`: `jbe`, offset
-`0x162` inside TurboFan-generated `jitWork`, mapped by V8's line table to the
-body at `gui/targets/jit.js:6`. Both the source-to-PC and branch-to-target arrows
-are visible. The GUI remains open. The recording is
-`/tmp/ztrace-gui-2536121-364024192152453.ztrace`; the screenshot is
-`/tmp/ztrace-v8-final-reviewed.png`. Addresses and PIDs identify this session
-only. Other test windows were closed.
+The independent native review passed after exercising graph/source toggling,
+all four opacity settings, and Follow. It restored source/live/follow at 100%
+without executing the target. Screenshot:
+`/tmp/ztrace-ui-review/native-final-reviewed.jpg`. Native font-shortcut injection
+was unavailable through the automation tool's punctuation grammar; the actual
+headless key handler passed the nine size/zoom combinations.
diff --git a/gui/bench/control.py b/gui/bench/control.py
new file mode 100644
index 0000000..eb3ff92
--- /dev/null
+++ b/gui/bench/control.py
@@ -0,0 +1,180 @@
+"""Small driver for the live controller; no tracing between requested stops."""
+import json
+import os
+from pathlib import Path
+import re
+import select
+import struct
+import subprocess
+import time
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+class Controller:
+ def __init__(self, ztrace, out, name, argv):
+ self.ztrace = Path(ztrace).resolve()
+ self.recording = out / (name + '.ztrace')
+ self.log = (out / (name + '.log')).open('w+')
+ self.process = subprocess.Popen([str(self.ztrace), 'serve', str(self.recording), '--', *argv],
+ cwd=out, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, bufsize=0)
+ self.pending = b''
+
+ def read(self):
+ deadline = time.monotonic() + 60
+ while b'\n' not in self.pending:
+ if not select.select([self.process.stdout], [], [], max(0, deadline - time.monotonic()))[0]:
+ raise TimeoutError('controller timeout: ' + self.log.name)
+ data = os.read(self.process.stdout.fileno(), 4096)
+ if not data:
+ raise RuntimeError('controller exited: ' + self.log.name)
+ self.pending += data
+ line, self.pending = self.pending.split(b'\n', 1)
+ return json.loads(line)
+
+ def command(self, command, status='stopped'):
+ self.process.stdin.write((command + '\n').encode())
+ while True:
+ reply = self.read()
+ if reply['status'] != 'running':
+ assert reply['status'] == status, (command, reply)
+ return reply
+
+ def output(self):
+ self.log.seek(0)
+ return self.log.read()
+
+ def show(self):
+ return subprocess.check_output([str(self.ztrace), 'show', str(self.recording), '-1'], text=True)
+
+ def regs(self):
+ return {name: int(value, 16) for name, value in re.findall(r'^ (\w+)\s+([0-9a-f]+)', self.show(), re.M)}
+
+ def close(self):
+ try:
+ if self.process.poll() is None:
+ self.process.stdin.write(b'quit\n')
+ self.process.wait(timeout=30)
+ finally:
+ if self.process.poll() is None:
+ self.process.kill()
+ self.process.wait()
+ self.process.stdin.close()
+ self.process.stdout.close()
+ self.log.close()
+
+
+def natural(ztrace, d8, out, source):
+ js = out / f'natural-{os.getpid()}.js'
+ js.write_bytes((ROOT / 'gui/targets/jit.js').read_bytes())
+ c = Controller(ztrace, out, 'v8', [str(Path(d8).resolve()), '--trace-opt', '--trace-deopt',
+ '--trace-deopt-verbose', '--print-opt-code', '--print-opt-code-filter=jitWork',
+ '--gdbjit', '--gdbjit-dump', '--gdbjit-dump-filter=jitWork', js.name])
+ try:
+ assert c.read()['status'] == 'stopped'
+ c.command('break main')
+ c.command('continue')
+ c.command('clear 1')
+ c.command('source-map ../../src ' + str(source / 'src'))
+ c.command('break v8::internal::Deoptimizer::New')
+ c.command('break v8::internal::Runtime_NotifyDeoptimized')
+ # Stop on an unrelated outer-loop bailout after natural compilation.
+ for _ in range(30):
+ stop = c.command('continue')
+ code = c.output()
+ if 'kind = TURBOFAN_JS' in code and "deopt reason 'wrong map'" in code:
+ break
+ else:
+ raise AssertionError('jitWork did not naturally reach TurboFan')
+ assert 'target MAGLEV' in code and 'target TURBOFAN_JS' in code
+ # The optimized-code block belongs to jitWork, selected by V8's own filter.
+ block = next(b.split('--- End code ---')[0] for b in reversed(code.split('--- Optimized code ---')) if 'kind = TURBOFAN_JS' in b and "deopt reason 'wrong map'" in b)
+ instructions = re.findall(r'^(0x[0-9a-f]+)\s+[0-9a-f]+\s+[0-9a-f]+\s+(.+)$', block, re.M)
+ assert instructions
+ start = int(instructions[0][0], 16)
+ end = int(instructions[-1][0], 16) + 16
+ c.command('break *' + hex(start))
+ for _ in range(30):
+ stop = c.command('continue')
+ if stop['pc'] == start:
+ break
+ else:
+ raise AssertionError('optimized warm call was not reached')
+ c.command('clear 4')
+ candidates = list(Path('/tmp').glob('elfdumpjitWork ' + js.name + ':*.o'))
+ def owns_start(path):
+ data = path.read_bytes()
+ shoff = struct.unpack_from('<Q', data, 40)[0]
+ size, count = struct.unpack_from('<HH', data, 58)
+ return any((lambda sh: sh[2] & 4 and sh[3] <= start < sh[3] + sh[5])(
+ struct.unpack_from('<IIQQQQIIQQ', data, shoff + i * size)) for i in range(count))
+ elf, = [path for path in candidates if owns_start(path)]
+ c.command('symbols ' + str(elf))
+ c.command(f'inspect code {start} 128')
+ return c, js, elf, (start, end), instructions, stop
+ except BaseException:
+ c.close()
+ raise
+
+
+def deoptimization(c, bounds, instructions, source):
+ transition = []
+ wrong_return = int(re.search(r'^(0x[0-9a-f]+)\s+deopt reason\s+\(wrong map\)', c.output(), re.M)[1], 16)
+ exit_call = max(int(a, 16) for a, _ in instructions if int(a, 16) < wrong_return)
+ guard = next(int(a, 16) for a, text in instructions if re.match(r'j\w+ ' + hex(exit_call) + r'\b', text))
+ c.command('break *' + hex(exit_call))
+ for _ in range(30):
+ generated = c.command('continue')
+ if generated['pc'] == exit_call:
+ break
+ else:
+ raise AssertionError('wrong-map generated exit not reached')
+ transition.append(dict(stage='generated wrong-map exit', guard_pc=guard, **generated))
+ c.command('clear 5')
+ # Deoptimizer::New receives the originating generated return PC in rdx.
+ for _ in range(30):
+ stop = c.command('continue')
+ if stop['reason'] == 'breakpoint 2':
+ regs = c.regs()
+ if bounds[0] <= regs['rdx'] < bounds[1]:
+ entry = stop
+ origin = regs['rdx']
+ break
+ else:
+ raise AssertionError('no deoptimization originating in jitWork')
+ shown = c.show()
+ assert str(source / 'src/deoptimizer/deoptimizer.cc') in shown, shown[:1000]
+ assert (source / 'src/deoptimizer/deoptimizer.cc').exists()
+ transition.append(dict(stage='Deoptimizer::New', **entry))
+ origin_instruction = guard
+ c.command(f'inspect code {origin_instruction} 16')
+ notify = c.command('continue')
+ assert notify['reason'] == 'breakpoint 3', notify
+ log = c.output()
+ wrong_maps = [int(pc, 16) for pc in re.findall(r'^(0x[0-9a-f]+)\s+deopt reason\s+\(wrong map\)', log, re.M)]
+ assert origin in wrong_maps, (hex(origin), [hex(pc) for pc in wrong_maps])
+ assert str(source / 'src/runtime/runtime-compiler.cc') in c.show()
+ transition.append(dict(stage='Runtime_NotifyDeoptimized', **notify))
+ c.command('break Builtins_InterpreterEnterAtBytecode')
+ fallback = c.command('continue')
+ assert fallback['reason'] == 'breakpoint 6', fallback
+ transition.append(dict(stage='InterpreterEnterAtBytecode', **fallback))
+ # Prove dispatch into the bytecode handler, not just the frame-reconstruction log.
+ dispatch = None
+ for _ in range(300):
+ step = c.command('stepi')
+ shown = c.show()
+ rip = next(line for line in shown.splitlines() if line.startswith(' rip '))
+ if 'Builtins_InterpreterEntryTrampoline' not in rip and 'Builtins_InterpreterEnterAtBytecode' not in rip and re.search(r'Builtins_(GetNamedProperty|LdaNamedProperty|GetNamedPropertyFromSuper)', rip):
+ dispatch = dict(stage='Ignition property bytecode handler', symbol=rip.strip(), **step)
+ break
+ assert dispatch, c.show()[:1600]
+ transition.append(dispatch)
+ for bp in (2, 3, 6):
+ c.command(f'clear {bp}')
+ c.command('continue', status='exited')
+ log = c.output()
+ assert re.search(r'reason: wrong map.*<JSFunction jitWork', log), log[-6000:]
+ assert 'mismatch 499509' in log and 'fallback 499507' in log
+ return dict(reason='wrong map', function='jitWork', optimized_tier='TurboFan', fallback_tier='Ignition',
+ origin_return_pc=origin, origin_instruction=origin_instruction, deopt_call=exit_call, stops=transition)
diff --git a/gui/bench/steps.py b/gui/bench/steps.py
index 166fa90..2906759 100644
--- a/gui/bench/steps.py
+++ b/gui/bench/steps.py
@@ -1,143 +1,70 @@
#!/usr/bin/env python3
-"""Compare the same controller's recorded instruction steps on C and debug V8."""
+"""Compare source-enabled C/V8 steps; verify a natural wrong-map deoptimization separately."""
import argparse
import json
import math
-import os
from pathlib import Path
-import re
-import select
import statistics
import subprocess
import time
+from control import ROOT, Controller, natural, deoptimization
-ROOT = Path(__file__).resolve().parents[2]
-p = argparse.ArgumentParser(description=__doc__)
-p.add_argument('--d8', type=Path, required=True)
-p.add_argument('--ztrace', type=Path, default=ROOT / 'gui/zig-out/bin/ztrace')
-p.add_argument('--out', type=Path, default=Path('/tmp/ztrace-step-bench'))
-p.add_argument('--steps', type=int, default=1000)
-p.add_argument('--jit-source', action='store_true', help='Measure with V8 JIT symbols and source lines loaded')
-a = p.parse_args()
-assert a.steps > 0
-a.out.mkdir(parents=True, exist_ok=True)
-a.out = a.out.resolve()
-a.d8 = a.d8.resolve()
-small = a.out / 'loop'
-subprocess.run(['cc', '-g', '-O0', str(ROOT / 'gui/targets/loop.c'), '-o', str(small)], check=True)
-js = a.out / f'bench-jit-{os.getpid()}.js'
-if a.jit_source:
- js.write_bytes((ROOT / 'gui/targets/jit.js').read_bytes())
-
-class Controller:
- def __init__(self, name, argv):
- self.log = (a.out / (name + '.log')).open('w+')
- self.process = subprocess.Popen(
- [str(a.ztrace.resolve()), 'serve', str(a.out / (name + '.ztrace')), '--', *argv],
- cwd=a.out, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, bufsize=0)
- self.pending = b''
-
- def read(self):
- deadline = time.monotonic() + 30
- while b'\n' not in self.pending:
- if not select.select([self.process.stdout], [], [], max(0, deadline - time.monotonic()))[0]:
- raise TimeoutError('controller did not reply within 30 seconds')
- data = os.read(self.process.stdout.fileno(), 4096)
- if not data:
- raise RuntimeError('controller exited; see ' + self.log.name)
- self.pending += data
- line, self.pending = self.pending.split(b'\n', 1)
- return json.loads(line)
-
- def command(self, command):
- self.process.stdin.write((command + '\n').encode())
- while True:
- reply = self.read()
- assert reply['status'] not in ('failed', 'exited'), reply
- if reply['status'] == 'stopped':
- return reply
-
- def close(self):
- try:
- if self.process.poll() is None:
- self.process.stdin.write(b'quit\n')
- self.process.wait(timeout=30)
- finally:
- if self.process.poll() is None:
- self.process.kill()
- self.process.wait()
- self.process.stdin.close()
- self.process.stdout.close()
- self.log.close()
+def summary(ns):
+ values = sorted(v / 1000 for v in ns)
+ return dict(median_us=statistics.median(values), p95_us=values[math.ceil(len(values) * .95) - 1], max_us=max(values))
-def summary(ns):
- ordered = sorted(v / 1000 for v in ns)
- return dict(median_us=statistics.median(ordered), p95_us=ordered[math.ceil(len(ns) * .95) - 1], max_us=max(ordered))
+def measure(c, count):
+ core, wall, command = [], [], []
+ for _ in range(count):
+ started = time.perf_counter_ns()
+ reply = c.command('stepi')
+ wall.append(time.perf_counter_ns() - started)
+ core.append(reply['capture_ns'])
+ command.append(reply['elapsed_ns'])
+ assert reply['reason'] == 'step', reply
+ return dict(steps=count, capture=summary(core), command=summary(command), roundtrip=summary(wall))
-results = {}
-for name, argv in [('c', [str(small)]), ('v8', [str(a.d8), '--allow-natives-syntax',
- '--no-concurrent-recompilation', '--no-maglev', '--print-opt-code',
- '--print-opt-code-filter=jitWork', *(['--gdbjit', '--gdbjit-dump', '--gdbjit-dump-filter=jitWork', js.name]
- if a.jit_source else [str(ROOT / 'gui/targets/jit.js')])])]:
+def main():
+ p = argparse.ArgumentParser(description=__doc__)
+ p.add_argument('--d8', type=Path, required=True)
+ p.add_argument('--source', type=Path, default=Path('/tmp/computeranim-v8-source'))
+ p.add_argument('--ztrace', type=Path, default=ROOT / 'gui/zig-out/bin/ztrace')
+ p.add_argument('--out', type=Path, default=Path('/tmp/ztrace-natural-bench'))
+ p.add_argument('--steps', type=int, default=1000)
+ p.add_argument('--jit-source', action='store_true', help='Compatibility: source is always enabled')
+ a = p.parse_args()
+ assert 0 < a.steps <= 4000, 'sample must stay in the warmed loop'
+ a.out = a.out.resolve()
+ a.source = a.source.resolve()
+ a.out.mkdir(parents=True, exist_ok=True)
+ small = a.out / 'loop'
+ subprocess.run(['cc', '-g', '-O0', str(ROOT / 'gui/targets/loop.c'), '-o', str(small)], check=True)
+ c = Controller(a.ztrace, a.out, 'c', [str(small)])
+ results = {}
+ try:
+ c.read()
+ c.command('break work')
+ c.command('continue')
+ results['c'] = measure(c, a.steps)
+ finally:
+ c.close()
start = time.perf_counter_ns()
- c = Controller(name, argv)
- elf = None
+ c, js, elf, bounds, instructions, stop = natural(a.ztrace, a.d8, a.out, a.source)
try:
- assert c.read()['status'] == 'stopped'
- entry_ns = time.perf_counter_ns() - start
- if name == 'c':
- c.command('break work')
- else:
- stopped = c.command('continue') # Native %SystemBreak, before the final JS call.
- assert stopped['reason'].startswith('signal TRAP'), stopped
- c.log.seek(0)
- assembly = c.log.read()
- assert 'kind = TURBOFAN_JS' in assembly
- # shortcut: this fixture's x64 loop instruction; fail loudly if V8 changes its register allocation.
- match = re.search(r'^(0x[0-9a-f]+)\s+[0-9a-f]+\s+[0-9a-f]+\s+addl r8,r11', assembly, re.M)
- assert match, 'could not find jitWork loop body; inspect ' + c.log.name
- address = int(match[1], 16)
- c.command('signal 0')
- c.command('break *' + hex(address))
- hit = c.command('continue')
- assert hit['reason'].startswith('breakpoint '), hit
- if name == 'v8':
- assert hit['pc'] == address, hit
- maps = Path(f"/proc/{hit['pid']}/maps").read_text().splitlines()
- mapping = next(line for line in maps if int(line.split('-')[0], 16) <= address < int(line.split('-')[1].split()[0], 16))
- assert 'x' in mapping.split()[1] and len(mapping.split()) == 5, mapping
- first_break_ns = time.perf_counter_ns() - start
- if name == 'v8':
- stepped = c.command('step')
- assert stepped['reason'] == 'step' and stepped['pc'] != address, stepped
- if a.jit_source:
- elf, = Path('/tmp').glob('elfdumpjitWork ' + js.name + ':*.o')
- imported = c.command('symbols ' + str(elf))
- assert imported['pc'] == stepped['pc'], imported
- core, wall = [], []
- for _ in range(a.steps):
- start_step = time.perf_counter_ns()
- reply = c.command('stepi')
- wall.append(time.perf_counter_ns() - start_step)
- core.append(reply['elapsed_ns'])
- assert reply['reason'] == 'step', reply
- results[name] = dict(steps=a.steps, entry_ms=entry_ns / 1e6, first_break_ms=first_break_ns / 1e6,
- capture=summary(core), roundtrip=summary(wall))
- if name == 'v8':
- results[name]['jit_source'] = a.jit_source
- print(name, json.dumps(results[name]), flush=True)
+ results['v8'] = dict(first_generated_stop_ms=(time.perf_counter_ns() - start) / 1e6, **measure(c, a.steps))
+ regs = c.regs()
+ assert bounds[0] <= regs['rip'] < bounds[1], 'steady sample left optimized jitWork'
+ assert str(js) + ':' in c.show(), 'generated source mapping missing'
+ results['transition'] = deoptimization(c, bounds, instructions, a.source)
+ (a.out / 'results.json').write_text(json.dumps(results, indent=2) + '\n')
+ print(json.dumps(results, indent=2))
finally:
c.close()
- if elf is not None:
- elf.unlink(missing_ok=True)
- if name == 'v8':
- shown = subprocess.run([str(a.ztrace.resolve()), 'show', str(a.out / 'v8.ztrace'), '-1'],
- check=True, capture_output=True, text=True)
- if a.jit_source:
- assert str(js) + ':' in shown.stdout, 'JIT source line missing'
- else:
- assert f"thread {reply['tid']}" in shown.stdout.splitlines(), 'JIT stop inherited a stale native source line'
-(a.out / 'results.json').write_text(json.dumps(results, indent=2) + '\n')
+ elf.unlink(missing_ok=True)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/gui/build.zig b/gui/build.zig
index 98d9c44..3e09631 100644
--- a/gui/build.zig
+++ b/gui/build.zig
@@ -50,10 +50,18 @@ pub fn build(b: *std.Build) void {
tests.dependOn(&test_run.step);
const navigation = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/Navigation.zig"), .target = target, .optimize = optimize }) });
tests.dependOn(&b.addRunArtifact(navigation).step);
+ const geometry = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/Geometry.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "sketch", .module = sb.modules.sketch }} }) });
+ tests.dependOn(&b.addRunArtifact(geometry).step);
const inspection = b.addSystemCommand(&.{"python3"});
inspection.addFileArg(b.path("test/inspection.py"));
inspection.addArg("--ztrace");
inspection.addFileArg(b.graph.path(.install_bin, "ztrace"));
inspection.step.dependOn(b.getInstallStep());
tests.dependOn(&inspection.step);
+ const adaptive = b.addSystemCommand(&.{"python3"});
+ adaptive.addFileArg(b.path("test/adaptive.py"));
+ adaptive.addArg("--gui");
+ adaptive.addFileArg(b.graph.path(.install_bin, "ztrace-gui"));
+ adaptive.step.dependOn(b.getInstallStep());
+ tests.dependOn(&adaptive.step);
}
diff --git a/gui/src/Geometry.zig b/gui/src/Geometry.zig
new file mode 100644
index 0000000..3ebdf4e
--- /dev/null
+++ b/gui/src/Geometry.zig
@@ -0,0 +1,57 @@
+//! All pane and minimap geometry is in font-sized canvas units.
+const std = @import("std");
+const Rect = @import("sketch").Rect;
+const Geometry = @This();
+w: f32,
+h: f32,
+content: f32,
+top: f32,
+columns: usize,
+panes: [3]Rect,
+registers: Rect,
+
+pub fn init(w: f32, h: f32, scroll: f32) Geometry {
+ const margin: f32 = 24;
+ const gap: f32 = 16;
+ const room = @max(240, w - 2 * margin);
+ const columns: usize = @intFromFloat(@max(1, @floor((w - 48) / 42)));
+ const top: f32 = 78 + @as(f32, @floatFromInt((16 + columns - 1) / columns)) * 34;
+ const tall = @max(320, (h - top - 64) * 0.64);
+ const bottom = @max(240, h - top - tall - gap - 48);
+ var code: Rect = .{ .x = margin, .y = top, .w = room, .h = tall };
+ var regs: Rect = .{ .x = margin, .y = top + tall + gap, .w = room, .h = 320 };
+ if (w >= 1500) {
+ regs = .{ .x = margin + room * 0.72 + gap, .y = top, .w = room * 0.28 - gap, .h = tall };
+ code.w = room * 0.72;
+ }
+ const y = @max(code.y + code.h, regs.y + regs.h) + gap;
+ var stack: Rect = .{ .x = margin, .y = y, .w = room, .h = bottom };
+ var mem: Rect = .{ .x = margin, .y = y + bottom + gap, .w = room, .h = bottom };
+ if (w >= 1500) {
+ stack.w = (room - gap) / 2;
+ mem = .{ .x = margin + stack.w + gap, .y = y, .w = stack.w, .h = bottom };
+ }
+ const content = mem.y + mem.h + 48;
+ for ([_]*Rect{ &code, &regs, &stack, &mem }) |r| r.y -= std.math.clamp(scroll, 0, @max(0, content - h));
+ return .{ .w = w, .h = h, .content = content, .top = top, .columns = columns, .panes = .{ code, stack, mem }, .registers = regs };
+}
+pub fn visible(r: Rect) f32 {
+ return @max(1, @floor((r.h - 40) / 24));
+}
+pub fn mini(r: Rect) Rect {
+ return .{ .x = r.w - 52, .y = 32, .w = 46, .h = r.h - 40 };
+}
+pub fn seam(r: Rect) f32 {
+ return @min(536, r.w * 0.34);
+}
+
+test "wide panes sit beside each other; narrow panes stack without overlap at every font scale" {
+ for ([_][2]f32{ .{ 2240, 1260 }, .{ 1440, 900 }, .{ 800, 700 } }) |size| {
+ for ([_]f32{ 0.6, 1, 2 }) |scale| {
+ const g = init(size[0] / scale, size[1] / scale, 0);
+ for (g.panes) |p| try std.testing.expect(p.w > 0 and p.h > 0 and p.x + p.w <= g.w);
+ try std.testing.expect(g.registers.x >= g.panes[0].x + g.panes[0].w or g.registers.y >= g.panes[0].y + g.panes[0].h);
+ try std.testing.expect(g.panes[2].x >= g.panes[1].x + g.panes[1].w or g.panes[2].y >= g.panes[1].y + g.panes[1].h);
+ }
+ }
+}
diff --git a/gui/src/Navigation.zig b/gui/src/Navigation.zig
index f9ae34a..7edd4d9 100644
--- a/gui/src/Navigation.zig
+++ b/gui/src/Navigation.zig
@@ -1,7 +1,7 @@
//! Bounded per-pane jump history. Scrolling changes the current location, not the target.
const std = @import("std");
const Navigation = @This();
-pub const Location = struct { address: u64 = 0, row: f32 = 0, follow: bool = true };
+pub const Location = struct { address: u64 = 0, row: f64 = 0, follow: bool = true, manual: bool = false };
place: Location = .{},
history: [32]Location = @splat(.{}),
len: u8 = 0,
@@ -45,7 +45,7 @@ test "pane jumps retain scroll and discard the abandoned forward branch" {
n.place.row = 3;
n.visit(0x2000);
n.back();
- try std.testing.expectEqual(@as(f32, 3), n.place.row);
+ try std.testing.expectEqual(@as(f64, 3), n.place.row);
n.visit(0x3000);
n.forward();
try std.testing.expectEqual(@as(u64, 0x3000), n.place.address);
@@ -54,3 +54,13 @@ test "pane jumps retain scroll and discard the abandoned forward branch" {
for (0..40) |_| n.back();
try std.testing.expectEqual(@as(u64, 0x4008), n.place.address);
}
+
+test "large mapping row history keeps individual words reachable" {
+ var n: Navigation = .{};
+ n.visit(0x100000000);
+ n.place.row = 268435455;
+ n.place.row -= 1;
+ n.visit(0x200000000);
+ n.back();
+ try std.testing.expectEqual(@as(f64, 268435454), n.place.row);
+}
diff --git a/gui/src/Sources.zig b/gui/src/Sources.zig
index 33268c5..3bd4cbf 100644
--- a/gui/src/Sources.zig
+++ b/gui/src/Sources.zig
@@ -5,15 +5,28 @@ const zt = @import("ztrace");
const Sources = @This();
const File = struct { id: u64, path: []const u8, bytes: []const u8, text: ?canim.source.Text };
files: std.ArrayList(File) = .empty,
+paths: ?zt.Symbols = null,
pub fn close(s: *Sources, gpa: std.mem.Allocator) void {
+ s.clear(gpa);
+ if (s.paths) |*paths| paths.deinit();
+ s.* = .{};
+}
+
+pub fn map(s: *Sources, gpa: std.mem.Allocator, io: std.Io, from: []const u8, to: []const u8) !void {
+ if (s.paths == null) s.paths = .{ .gpa = gpa, .io = io };
+ try s.paths.?.mapSource(from, to);
+ s.clear(gpa);
+}
+
+fn clear(s: *Sources, gpa: std.mem.Allocator) void {
for (s.files.items) |file| {
if (file.text) |t| t.deinit();
gpa.free(file.path);
gpa.free(file.bytes);
}
s.files.deinit(gpa);
- s.* = .{};
+ s.files = .empty;
}
pub fn get(s: *Sources, gpa: std.mem.Allocator, io: std.Io, m: zt.store.Moment, id: u64) ?*const File {
@@ -21,7 +34,7 @@ pub fn get(s: *Sources, gpa: std.mem.Allocator, io: std.Io, m: zt.store.Moment,
if (s.files.items.len == 32) return null;
var buffer: [4096]u8 = undefined;
const name = (m.string(id, &buffer) catch null) orelse return null;
- const path = gpa.dupe(u8, name) catch return null;
+ const path = (if (s.paths) |*paths| paths.sourcePath(.{ .key = 0, .dir = "", .name = name, .line = 0, .column = 0 }) else gpa.dupe(u8, name)) catch return null;
const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(8 * 1024 * 1024)) catch &.{};
const text = if (bytes.len > 0) canim.source.prepare(bytes, path) catch null else null;
s.files.append(gpa, .{ .id = id, .path = path, .bytes = bytes, .text = text }) catch {
diff --git a/gui/src/app.zig b/gui/src/app.zig
index dfa0d0a..e334b0b 100644
--- a/gui/src/app.zig
+++ b/gui/src/app.zig
@@ -5,6 +5,7 @@ const zt = @import("ztrace");
const ui = canim.ui;
const Client = @import("Client.zig");
const Navigation = @import("Navigation.zig");
+const Geometry = @import("Geometry.zig");
const Sources = @import("Sources.zig");
var sources: Sources = .{};
pub const name = "ztrace debugger";
@@ -22,6 +23,7 @@ pub const State = struct {
following: bool = true,
status: zt.control.Status = .stopped,
stops: u64 = 0,
+ execution: u64 = 0,
pc: u64 = 0,
action: sk.Request(Action) = .{},
nav: [3]Navigation = @splat(.{}),
@@ -32,6 +34,20 @@ pub const State = struct {
annotations: bool = true,
depth: u8 = 4,
ascii: bool = true,
+ zoom: u16 = 100,
+ page_scroll: f32 = 0,
+ register_scroll: f32 = 0,
+ horizontal: [3]f32 = @splat(0),
+ graph: bool = false,
+ dim: u8 = 75,
+ segments: bool = false,
+ segment_query: [128]u8 = @splat(0),
+ segment_len: u8 = 0,
+ segment_row: u32 = 0,
+ origin: u64 = 0,
+ lenses: [32]Lens = @splat(.{}),
+ lens_count: u8 = 0,
+ lens_scroll: f32 = 0,
lens: bool = false,
lens_address: u64 = 0,
lens_origin: Box = .{},
@@ -41,10 +57,12 @@ pub const State = struct {
command_text: [512]u8 = @splat(0),
command_len: u16 = 0,
drag_map: ?Pane = null,
+ drag_content: bool = false,
};
pub const Session = struct {
action: sk.Handled = .{},
- scroll: [3]f32 = @splat(0),
+ graph: bool = false,
+ scroll: [3]f64 = @splat(0),
base: [3]u64 = @splat(0),
mini: [3]ui.Collected = @splat(.{}),
mini_key: [3]u64 = @splat(0),
@@ -62,6 +80,9 @@ pub const Session = struct {
marker_to: f32 = 0,
marker_shown: f32 = 0,
marker_at: u64 = 0,
+ inspected: [3]u64 = @splat(0),
+ capture_stop: u64 = 0,
+ origin_line: ?zt.store.Line = null,
lens_at: u64 = 0,
lens_previous: u64 = 0,
@@ -78,25 +99,39 @@ pub const Session = struct {
branch: ?canim.Recording.Branch = null,
};
const Pane = enum { code, stack, memory };
-const Kind = enum { cont, pause, stepi, step, previous, next, live, follow, back, forward, source, map, annotate, shallower, deeper, ascii, lens, close_lens, help, breakpoint, command, go, submit };
-const Action = struct { kind: Kind, pane: Pane = .code, address: u64 = 0 };
+const Lens = struct { address: u64 = 0, origin: Box = .{}, cycle: bool = false };
+const Kind = enum { graph, dim, segments, select_segment, cont, pause, stepi, step, previous, next, live, follow, back, forward, source, map, annotate, shallower, deeper, ascii, lens, close_lens, help, breakpoint, command, go, submit };
+const Action = struct { kind: Kind, pane: Pane = .code, address: u64 = 0, manual: bool = false };
const Box = sk.Rect;
-const panes = [3]Box{
- .{ .x = 24, .y = 88, .w = 1580, .h = 708 },
- .{ .x = 24, .y = 812, .w = 1072, .h = 400 },
- .{ .x = 1120, .y = 812, .w = 1096, .h = 400 },
-};
-const Hit = struct { address: u64, box: Box };
+var geometry = Geometry.init(width, height, 0);
+var panes = Geometry.init(width, height, 0).panes;
+var ranges: [3]zt.store.Mapping = @splat(.{ .addr = 0, .len = 2048, .prot = 0, .offset = 0 });
+var code_after: u64 = 0;
+var code_before: u64 = 0;
+var code_top: f32 = 32;
+var origin_height: f32 = 72;
+var source_height: f32 = 48;
+var compact_rows: [256]usize = undefined;
+var compact_count: usize = 0;
+var compact_addresses: [3][128]u64 = undefined;
+var compact_counts: [3]usize = @splat(0);
+var current_lens: ?u8 = null;
+var lens_boxes: [32]Box = undefined;
+var segment_hits: [64]struct { box: Box, address: u64 } = undefined;
+var segment_hit_count: usize = 0;
+var segment_total: u32 = 0;
+const Hit = struct { address: u64, box: Box, lens: ?u8 };
const Button = struct { action: Action, box: Box, label: []const u8, enabled: bool };
var hits: [2048]Hit = undefined;
var hit_count: usize = 0;
-var buttons: [64]Button = undefined;
+var buttons: [128]Button = undefined;
var button_count: usize = 0;
-var extents: [3]f32 = @splat(0);
+var extents: [3]f64 = @splat(0);
var bases: [3]u64 = @splat(0);
+var shown_scroll: [3]f64 = @splat(0);
var tooltip: ?Button = null;
var lens_box: ?Box = null;
-var lens_hits: usize = 0;
+var drawn_lenses: usize = 0;
pub fn close() void {
sources.close(gpa);
@@ -122,6 +157,13 @@ pub fn command(s: *State, c: *sk.Console, line: []const u8) !bool {
return true;
}
if (std.mem.eql(u8, cmd, "observed")) {
+ if (latest.moments != s.stops and (std.mem.eql(u8, latest.reason(), "step") or std.mem.startsWith(u8, latest.reason(), "signal ") or (std.mem.startsWith(u8, latest.reason(), "breakpoint ") and !std.mem.endsWith(u8, latest.reason(), " set")))) {
+ s.execution += 1;
+ if (s.nav[0].place.follow) s.page_scroll = 0;
+ for (&s.nav) |*n| if (n.place.follow) {
+ n.place.manual = false;
+ };
+ }
s.status = latest.status;
s.stops = latest.moments;
s.pc = latest.pc;
@@ -136,16 +178,32 @@ pub fn command(s: *State, c: *sk.Console, line: []const u8) !bool {
s.moment = latest.moments -| 1;
return true;
}
- if (std.mem.eql(u8, cmd, "symbols") or std.mem.eql(u8, cmd, "break") or std.mem.eql(u8, cmd, "clear") or std.mem.eql(u8, cmd, "signal") or std.mem.eql(u8, cmd, "continue") or std.mem.eql(u8, cmd, "interrupt") or std.mem.eql(u8, cmd, "stepi") or std.mem.eql(u8, cmd, "nextline")) {
+ if (std.mem.eql(u8, cmd, "source-map")) {
+ const from = words.next() orelse return error.MissingPrefix;
+ const to = words.next() orelse return error.MissingPath;
+ if (words.next() != null) return error.InvalidSourceMap;
+ try sources.map(gpa, io, from, to);
+ if (client) |target| try target.send(line);
+ return true;
+ }
+ if (std.mem.eql(u8, cmd, "inspect") or std.mem.eql(u8, cmd, "symbols") or std.mem.eql(u8, cmd, "break") or std.mem.eql(u8, cmd, "clear") or std.mem.eql(u8, cmd, "signal") or std.mem.eql(u8, cmd, "continue") or std.mem.eql(u8, cmd, "interrupt") or std.mem.eql(u8, cmd, "stepi") or std.mem.eql(u8, cmd, "nextline")) {
try (client orelse return error.NoTarget).send(if (std.mem.eql(u8, cmd, "interrupt")) "pause" else if (std.mem.eql(u8, cmd, "nextline")) "step" else line);
if (std.mem.eql(u8, cmd, "continue") or (std.mem.eql(u8, cmd, "stepi") or std.mem.eql(u8, cmd, "nextline"))) s.following = true;
return true;
}
- if (std.mem.eql(u8, cmd, "goto")) {
+ if (std.mem.eql(u8, cmd, "origin")) {
+ s.origin = try std.fmt.parseInt(u64, words.next() orelse return error.MissingAddress, 0);
+ return true;
+ }
+ if (std.mem.eql(u8, cmd, "goto") or std.mem.eql(u8, cmd, "browse")) {
const which = words.next() orelse return error.MissingPane;
const pane = std.meta.stringToEnum(Pane, which) orelse return error.InvalidPane;
const address = try std.fmt.parseInt(u64, words.next() orelse return error.MissingAddress, 0);
- s.nav[@backingInt(pane)].visit(address);
+ if (std.mem.eql(u8, cmd, "goto")) s.nav[@backingInt(pane)].visit(address) else {
+ s.nav[@backingInt(pane)].place.address = address;
+ s.nav[@backingInt(pane)].place.row = 0;
+ s.nav[@backingInt(pane)].place.manual = true;
+ }
s.focus = pane;
if (client != null and s.status == .stopped and s.following) {
var buf: [96]u8 = undefined;
@@ -191,30 +249,58 @@ fn paneAt(x: f32, y: f32) ?Pane {
}
fn addressAt(x: f32, y: f32) ?Hit {
var i = hit_count;
- const floor = if (lens_box) |box| if (contains(box, x, y)) lens_hits else 0 else 0;
+ var owner: ?u8 = null;
+ for (lens_boxes[0..drawn_lenses], 0..) |box, k| if (lens_box != null and contains(lens_box.?, x, y) and contains(box, x, y)) {
+ owner = @intCast(k);
+ };
+ const floor: usize = 0;
while (i > floor) {
i -= 1;
- if (contains(hits[i].box, x, y)) return hits[i];
+ if (hits[i].lens == owner and contains(hits[i].box, x, y)) return hits[i];
}
return null;
}
fn collectAddress(_: *anyopaque, address: u64, box: Box) void {
if (hit_count == hits.len) return;
- hits[hit_count] = .{ .address = address, .box = box };
+ hits[hit_count] = .{ .address = address, .box = box, .lens = current_lens };
hit_count += 1;
}
-fn scroll(s: *State, pane: Pane, delta: f32) void {
+fn scroll(s: *State, pane: Pane, delta: f64) void {
const p = @backingInt(pane);
const n = &s.nav[p];
- if (n.place.follow) {
- n.place.address = bases[p];
- n.place.follow = false;
+ if (!n.place.manual) n.place.row = shown_scroll[p];
+ n.place.manual = true;
+ const next = n.place.row + delta;
+ if (pane == .code and !s.graph and (next < 0 or next > extents[0])) {
+ const address = if (next < 0) code_before else code_after;
+ if (address >= ranges[0].addr and address < ranges[0].addr +| ranges[0].len) {
+ n.place.address = address;
+ n.place.row = 0;
+ s.action.send(.{ .kind = .go, .pane = .code, .address = address, .manual = true });
+ return;
+ }
}
- n.place.row = std.math.clamp(n.place.row + delta, 0, extents[p]);
+ n.place.row = std.math.clamp(next, 0, extents[p]);
}
fn act(s: *State, a: Action) void {
const p = @backingInt(a.pane);
switch (a.kind) {
+ .graph => {
+ s.graph = !s.graph;
+ s.nav[0].place.row = 0;
+ s.nav[0].place.manual = s.graph;
+ s.horizontal[0] = 0;
+ },
+ .dim => s.dim = if (s.dim >= 100) 25 else s.dim + 25 - s.dim % 25,
+ .segments => {
+ s.segments = !s.segments;
+ s.segment_len = 0;
+ s.segment_row = 0;
+ },
+ .select_segment => {
+ s.segments = false;
+ s.action.send(.{ .kind = .go, .pane = a.pane, .address = a.address });
+ },
.previous => {
s.following = false;
s.moment -|= 1;
@@ -239,16 +325,16 @@ fn act(s: *State, a: Action) void {
.deeper => s.depth = @min(6, s.depth + 1),
.ascii => s.ascii = !s.ascii,
.lens => {
- s.lens = !s.lens;
- if (a.address != 0) {
- s.lens_address = a.address;
- for (hits[0..hit_count]) |hit| if (hit.address == a.address) {
- s.lens_origin = hit.box;
- break;
- };
- }
+ if (s.lens) {
+ s.lens = false;
+ s.lens_count = 0;
+ } else openLens(s, .{ .address = a.address, .box = .{}, .lens = null });
+ },
+ .close_lens => {
+ s.lens_count = @intCast(@min(a.address, s.lens_count));
+ s.lens = s.lens_count > 0;
+ s.lens_scroll = @min(s.lens_scroll, @max(0, @as(f32, @floatFromInt(s.lens_count)) * 204 - (geometry.h - 180)));
},
- .close_lens => s.lens = false,
.help => s.help = !s.help,
.command => {
s.command_open = true;
@@ -276,9 +362,39 @@ fn semantic(s: *State, address: u64) void {
fn mapDrag(s: *State, pane: Pane, y: f32) void {
const p = @backingInt(pane);
const box = panes[p];
- const visible = (box.h - 40) / 24;
- const row = std.math.clamp((y - box.y - 32) / (box.h - 40), 0, 1) * (extents[p] + visible) - visible / 2;
- scroll(s, pane, row - s.nav[p].place.row);
+ const ratio = std.math.clamp((y - box.y - 32) / (box.h - 40), 0, 1);
+ if (pane == .code and s.drag_content and compact_count > 0) {
+ const index: usize = @min(compact_count - 1, @as(usize, @intFromFloat(ratio * @as(f32, @floatFromInt(compact_count)))));
+ s.nav[0].place.manual = true;
+ s.nav[0].place.row = @min(extents[0], @as(f64, @floatFromInt(compact_rows[index])));
+ } else if (pane != .code and s.drag_content and compact_counts[p] > 0) {
+ const index: usize = @min(compact_counts[p] - 1, @as(usize, @intFromFloat(ratio * @as(f32, @floatFromInt(compact_counts[p])))));
+ s.nav[p].place.manual = true;
+ s.nav[p].place.row = @floatFromInt((compact_addresses[p][index] - ranges[p].addr) / (if (p == 1) @as(u64, 8) else 16));
+ } else if (pane == .code) {
+ const address = ranges[p].addr + @as(u64, @intFromFloat(ratio * @as(f64, @floatFromInt(ranges[p].len -| 1))));
+ s.action.send(.{ .kind = .go, .pane = pane, .address = address, .manual = true });
+ } else {
+ s.nav[p].place.manual = true;
+ s.nav[p].place.row = ratio * extents[p];
+ }
+}
+fn openLens(s: *State, hit: Hit) void {
+ const at: u8 = if (hit.lens) |i| i + 1 else 0;
+ if (at == s.lenses.len) return;
+ var cycle = false;
+ for (s.lenses[0..at]) |lens| if (lens.address == hit.address) {
+ cycle = true;
+ };
+ s.lenses[at] = .{ .address = hit.address, .origin = hit.box, .cycle = cycle };
+ s.lens_count = at + 1;
+ s.lens = true;
+ s.lens_address = hit.address;
+ s.lens_scroll = @max(0, @as(f32, @floatFromInt(s.lens_count)) * 204 - (geometry.h - 160));
+ if (client != null and s.status == .stopped and s.following and !cycle) {
+ var buf: [96]u8 = undefined;
+ client.?.send(std.fmt.bufPrint(&buf, "inspect memory 0x{x} 128", .{(hit.address & ~@as(u64, 15)) -| 32}) catch return) catch {};
+ }
}
fn enabled(s: *const State, a: Action) bool {
return switch (a.kind) {
@@ -291,6 +407,13 @@ fn enabled(s: *const State, a: Action) bool {
}
fn pointer(s: *State, mouse_button: u16, x: f32, y: f32) void {
if (s.help) return;
+ if (s.segments) {
+ if (mouse_button == 1) for (segment_hits[0..segment_hit_count]) |hit| if (contains(hit.box, x, y)) {
+ act(s, .{ .kind = .select_segment, .pane = s.focus, .address = hit.address });
+ return;
+ };
+ return;
+ }
if (paneAt(x, y)) |pane| s.focus = pane;
if (mouse_button == 4 or mouse_button == 5) {
act(s, .{ .kind = if (mouse_button == 4) .back else .forward, .pane = s.focus });
@@ -309,32 +432,49 @@ fn pointer(s: *State, mouse_button: u16, x: f32, y: f32) void {
return;
}
}
- if (lens_box) |box| if (contains(box, x, y)) {
- if (addressAt(x, y)) |hit| {
- s.lens_address = hit.address;
- s.lens_origin = hit.box;
- s.lens = true;
- }
+ for (lens_boxes[0..drawn_lenses]) |box| if (lens_box != null and contains(lens_box.?, x, y) and contains(box, x, y)) {
+ if (addressAt(x, y)) |hit| openLens(s, hit);
return;
};
if (paneAt(x, y)) |pane| {
const p = @backingInt(pane);
if (s.maps[p] and x >= panes[p].x + panes[p].w - 54 and y >= panes[p].y + 32) {
s.drag_map = pane;
+ s.drag_content = (pane != .code or !s.graph) and x < panes[p].x + panes[p].w - 18;
mapDrag(s, pane, y);
return;
}
}
- if (addressAt(x, y)) |hit| {
- s.lens_address = hit.address;
- s.lens_origin = hit.box;
- s.lens = true;
- }
+ if (addressAt(x, y)) |hit| openLens(s, hit);
}
pub fn update(s: *State, in: *const sk.Input) void {
if (in.console) return;
+ s.page_scroll = std.math.clamp(s.page_scroll, 0, @max(0, geometry.content - geometry.h));
for (in.events) |e| {
+ if (s.segments) {
+ if (e.kind == .text and e.value >= 32 and e.value < 127 and s.segment_len < s.segment_query.len) {
+ s.segment_query[s.segment_len] = @intCast(e.value);
+ s.segment_len += 1;
+ s.segment_row = 0;
+ }
+ if (e.kind == .wheel) s.segment_row = @intFromFloat(std.math.clamp(@as(f32, @floatFromInt(s.segment_row)) - e.wheel() * 3, 0, @as(f32, @floatFromInt(segment_total -| 1))));
+ if (e.kind == .mouse_down) pointer(s, e.code, e.x, e.y);
+ if (e.kind == .key_down) switch (@as(sk.Key, @fromBackingInt(@intCast(e.code)))) {
+ .escape => s.segments = false,
+ .backspace => {
+ s.segment_len -|= 1;
+ s.segment_row = 0;
+ },
+ .down => s.segment_row = @min(s.segment_row + 1, segment_total -| 1),
+ .up => s.segment_row -|= 1,
+ .@"return" => if (segment_hit_count > 0) {
+ act(s, .{ .kind = .select_segment, .pane = s.focus, .address = segment_hits[0].address });
+ },
+ else => {},
+ };
+ continue;
+ }
if (s.command_open) {
if (e.kind == .text and e.value >= 32 and e.value < 127 and s.command_len < s.command_text.len) {
if (s.command_len != 0 or e.value != ':') {
@@ -364,9 +504,15 @@ pub fn update(s: *State, in: *const sk.Input) void {
.mouse_move => if (s.drag_map) |pane| {
mapDrag(s, pane, e.y);
},
- .wheel => if (paneAt(e.x, e.y)) |pane| {
- s.focus = pane;
- scroll(s, pane, -e.wheel() * 3);
+ .wheel => {
+ if (s.lens and lens_box != null and contains(lens_box.?, e.x, e.y)) {
+ s.lens_scroll = std.math.clamp(s.lens_scroll - e.wheel() * 48, 0, @max(0, @as(f32, @floatFromInt(s.lens_count)) * 204 - (geometry.h - 160)));
+ } else if (contains(geometry.registers, e.x, e.y) and e.y >= geometry.registers.y + 30) {
+ s.register_scroll = std.math.clamp(s.register_scroll - e.wheel() * 3, 0, @max(0, 29 - Geometry.visible(geometry.registers)));
+ } else if (paneAt(e.x, e.y)) |pane| {
+ s.focus = pane;
+ if (e.y < panes[@backingInt(pane)].y + 30) s.page_scroll = std.math.clamp(s.page_scroll - e.wheel() * 80, 0, @max(0, geometry.content - geometry.h)) else scroll(s, pane, -e.wheel() * 3);
+ } else s.page_scroll = std.math.clamp(s.page_scroll - e.wheel() * 80, 0, @max(0, geometry.content - geometry.h));
},
.key_down => {
const key: sk.Key = @fromBackingInt(@intCast(@as(u8, @intCast(e.code))));
@@ -374,8 +520,11 @@ pub fn update(s: *State, in: *const sk.Input) void {
const shift = e.value & sk.Key.Mod.shift != 0 or in.held(sk.Key.left_shift) or in.held(sk.Key.right_shift);
if (ctrl) {
switch (key) {
- .d => scroll(s, s.focus, (panes[@backingInt(s.focus)].h - 40) / 48),
- .u => scroll(s, s.focus, -(panes[@backingInt(s.focus)].h - 40) / 48),
+ .equals => s.zoom = @min(200, s.zoom + 10),
+ .minus => s.zoom = @max(60, s.zoom -| 10),
+ .@"0" => s.zoom = 100,
+ .d => scroll(s, s.focus, Geometry.visible(panes[@backingInt(s.focus)]) / 2),
+ .u => scroll(s, s.focus, -Geometry.visible(panes[@backingInt(s.focus)]) / 2),
.o => act(s, .{ .kind = .back, .pane = s.focus }),
.i => act(s, .{ .kind = .forward, .pane = s.focus }),
.w => s.prefix = 'w',
@@ -400,8 +549,21 @@ pub fn update(s: *State, in: *const sk.Input) void {
const was_g = s.prefix == 'g';
s.prefix = 0;
switch (key) {
- .h => s.source_column -|= 4,
- .l => s.source_column = @min(s.source_column +| 4, 4096),
+ .h => if (s.focus == .code and s.source and !s.graph and !shift) {
+ s.source_column -|= 4;
+ } else {
+ s.horizontal[@backingInt(s.focus)] = @max(0, s.horizontal[@backingInt(s.focus)] - 48);
+ },
+ .l => if (s.focus == .code and s.source and !s.graph and !shift) {
+ s.source_column = @min(s.source_column +| 4, 4096);
+ } else {
+ s.horizontal[@backingInt(s.focus)] = @min(1600, s.horizontal[@backingInt(s.focus)] + 48);
+ },
+ .page_down => s.page_scroll = @min(@max(0, geometry.content - geometry.h), s.page_scroll + geometry.h * 0.7),
+ .page_up => s.page_scroll = @max(0, s.page_scroll - geometry.h * 0.7),
+ .p => act(s, .{ .kind = .segments, .pane = s.focus }),
+ .t => act(s, .{ .kind = .graph }),
+ .d => act(s, .{ .kind = .dim }),
.j => scroll(s, s.focus, 1),
.k => scroll(s, s.focus, -1),
.g => if (shift) {
@@ -422,6 +584,7 @@ pub fn update(s: *State, in: *const sk.Input) void {
},
.escape => if (s.lens or s.help) {
s.lens = false;
+ s.lens_count = 0;
s.help = false;
} else if (s.status == .running) {
act(s, .{ .kind = .pause });
@@ -503,6 +666,13 @@ fn icon(u: ui.Ui, kind: Kind, active: bool) void {
v.line(.{ 8, 14 }, .{ 20, 14 }, c, 2);
v.line(.{ 8, 19 }, .{ 17, 19 }, c, 2);
},
+ .segments => v.text(.mono_bold, 20, 1, 19, "≡", c),
+ .graph => {
+ v.frame(.{ .x = 1, .y = 1, .w = 8, .h = 7 }, c, 1);
+ v.frame(.{ .x = 13, .y = 14, .w = 8, .h = 7 }, c, 1);
+ v.line(.{ 5, 8 }, .{ 17, 14 }, c, 1);
+ },
+ .dim => v.text(.mono_bold, 19, 1, 19, "◐", c),
.ascii => v.text(.mono_bold, 20, 1, 19, "Aa", c),
.close_lens => {
v.line(.{ 3, 3 }, .{ 19, 19 }, c, 2);
@@ -518,9 +688,14 @@ fn icon(u: ui.Ui, kind: Kind, active: bool) void {
}
fn button(u: ui.Ui, x: f32, y: f32, action: Action, label: []const u8, available: bool, active: bool) void {
const a = u.at.xf.apply(.{ x, y });
- const box: Box = .{ .x = a[0], .y = a[1], .w = 34, .h = 32 };
+ var box: Box = .{ .x = a[0], .y = a[1], .w = 34, .h = 32 };
+ if (ui.bound) |clip| {
+ const x0 = @max(box.x, clip.x);
+ const y0 = @max(box.y, clip.y);
+ box = .{ .x = x0, .y = y0, .w = @max(0, @min(box.x + box.w, clip.x + clip.w) - x0), .h = @max(0, @min(box.y + box.h, clip.y + clip.h) - y0) };
+ }
const b: Button = .{ .action = action, .box = box, .label = label, .enabled = available };
- if (button_count < buttons.len) {
+ if (box.w > 0 and box.h > 0 and button_count < buttons.len) {
buttons[button_count] = b;
button_count += 1;
}
@@ -535,10 +710,15 @@ fn paneButtons(u: ui.Ui, s: *const State, pane: Pane) void {
const p = @backingInt(pane);
const n = s.nav[p];
const w = panes[p].w;
+ if (w < 600) {
+ button(u, w - 78, -3, .{ .kind = .follow, .pane = pane }, "Follow live address · f", true, n.place.follow);
+ button(u, w - 40, -3, .{ .kind = .map, .pane = pane }, "Minimap · right rail spans whole segment · m", true, s.maps[p]);
+ return;
+ }
button(u, w - 230, -3, .{ .kind = .back, .pane = pane }, "Back · Ctrl-o / Mouse4", n.cursor > 0, false);
button(u, w - 192, -3, .{ .kind = .forward, .pane = pane }, "Forward · Ctrl-i / Mouse5", n.cursor + 1 < n.len, false);
button(u, w - 154, -3, .{ .kind = .follow, .pane = pane }, "Follow live address · f", true, n.place.follow);
- button(u, w - 116, -3, .{ .kind = .map, .pane = pane }, "Toggle content minimap · m", true, s.maps[p]);
+ button(u, w - 116, -3, .{ .kind = .map, .pane = pane }, "Minimap · right rail spans whole segment · m", true, s.maps[p]);
button(u, w - 78, -3, .{ .kind = if (pane == .code) .source else if (pane == .stack) .shallower else .ascii, .pane = pane }, if (pane == .code) "Aligned source · v" else if (pane == .stack) "Fewer pointer hops" else "ASCII / pointer words", true, if (pane == .code) s.source else if (pane == .memory) s.ascii else false);
button(u, w - 40, -3, .{ .kind = if (pane == .stack) .deeper else .annotate, .pane = pane }, if (pane == .stack) "More pointer hops" else "Read / result annotations · a", true, if (pane == .stack) false else s.annotations);
}
@@ -549,7 +729,7 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
.pause => f.run("interrupt"),
.stepi => f.run("stepi"),
.step => f.run("nextline"),
- .go => f.run(ui.Ui.init(f).print("goto {s} 0x{x}", .{ @tagName(action.pane), action.address })),
+ .go => f.run(ui.Ui.init(f).print("{s} {s} 0x{x}", .{ if (action.manual) "browse" else "goto", @tagName(action.pane), action.address })),
.breakpoint => f.run(ui.Ui.init(f).print("break *0x{x}", .{action.address})),
.submit => f.run(s.command_text[0..s.command_len]),
else => {},
@@ -565,7 +745,18 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
}
f.run("observed");
};
- f.canvas(width, height);
+ const scale = @as(f32, @floatFromInt(s.zoom)) / 100;
+ const w = @max(1, @round(f.in.window_width / scale));
+ const h = @max(1, @round(f.in.window_height / scale));
+ f.canvas(@intFromFloat(w), @intFromFloat(h));
+ const next_geometry = Geometry.init(w, h, s.page_scroll);
+ if (geometry.w != w or geometry.h != h) {
+ ss.mini_key = @splat(0);
+ ss.marker_key = 0;
+ ss.marker_base = 0;
+ }
+ geometry = next_geometry;
+ panes = geometry.panes;
f.clear(ui.theme.color.page);
const u = ui.Ui.init(f);
const ink = ui.theme.color.text;
@@ -574,22 +765,24 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
button_count = 0;
tooltip = null;
lens_box = null;
+ drawn_lenses = 0;
+ current_lens = null;
ui.address_hit = .{ .ctx = ss, .emit = collectAddress };
defer ui.address_hit = null;
- u.text(.sans_medium, 24, 24, 28, "ztrace / debugger", ink.primary);
+ u.text(.sans_medium, 24, 24, 28, if (geometry.w < 700) "ztrace" else "ztrace / debugger", ink.primary);
const status = if (client == null) (if (trace == null) "READY" else "RECORDING") else @tagName(s.status);
- u.fill(.{ .x = 300, .y = 9, .w = 118, .h = 24 }, ui.theme.color.raised);
- u.text(.mono_bold, 17, 312, 27, status, if (s.status == .failed) ui.theme.mark(.write).solid else gold.solid);
- u.text(.sans, 18, 434, 27, latest.reason(), ink.dim);
- if (client != null) u.text(.mono, 17, 1904, 27, u.print("command {d:.3} ms", .{@as(f64, @floatFromInt(latest.elapsed_ns)) / 1e6}), ink.dim);
- const kinds = [_]Kind{ if (s.status == .running) .pause else .cont, .stepi, .step, .breakpoint, .previous, .next, .live, .source, .map, .annotate, .lens, .command, .help };
- const labels = [_][]const u8{ if (s.status == .running) "Pause · Esc / Ctrl-c" else "Continue · c", "Single instruction · s", "Next source line (enters calls) · n", "Breakpoint at PC · b", "Previous recorded stop · [", "Next recorded stop · ]", "Live stop · F (Shift-f)", "Aligned source · v", "Focused pane minimap · m", "Operand annotations · a", "Address lens · z", "Command line · :", "Keyboard help · ?" };
+ u.fill(.{ .x = if (geometry.w < 700) 150 else 300, .y = 9, .w = 118, .h = 24 }, ui.theme.color.raised);
+ u.text(.mono_bold, 17, if (geometry.w < 700) 162 else 312, 27, status, if (s.status == .failed) ui.theme.mark(.write).solid else gold.solid);
+ if (geometry.w > 850) u.text(.sans, 18, 434, 27, canim.rows.fitted(u, latest.reason(), geometry.w - 740), ink.dim);
+ if (client != null and geometry.w > 1200) u.text(.mono, 17, geometry.w - 310, 27, u.print("command {d:.3} ms", .{@as(f64, @floatFromInt(latest.elapsed_ns)) / 1e6}), ink.dim);
+ const kinds = [_]Kind{ if (s.status == .running) .pause else .cont, .stepi, .step, .breakpoint, .previous, .next, .live, .source, .map, .annotate, .lens, .segments, .graph, .dim, .command, .help };
+ const labels = [_][]const u8{ if (s.status == .running) "Pause · Esc / Ctrl-c" else "Continue · c", "Single instruction · s", "Next source line (enters calls) · n", "Breakpoint at PC · b", "Previous recorded stop · [", "Next recorded stop · ]", "Live stop · F (Shift-f)", "Aligned source · v", "Focused pane minimap · m", "Operand annotations · a", "Address lens · z", "Memory segments · p (active pane)", "Control-flow graph · t", "Unobserved instruction opacity · d", "Command line · :", "Keyboard help · ?" };
for (kinds, labels, 0..) |kind, label, i| {
const available = switch (kind) {
.cont, .pause, .stepi, .step, .breakpoint => client != null and s.status != .exited and (kind == .pause or s.status == .stopped),
else => true,
};
- button(u, 24 + @as(f32, @floatFromInt(i)) * 42, 42, .{ .kind = kind, .pane = s.focus, .address = s.pc }, label, available, switch (kind) {
+ button(u, 24 + @as(f32, @floatFromInt(i % geometry.columns)) * 42, 42 + @as(f32, @floatFromInt(i / geometry.columns)) * 34, .{ .kind = kind, .pane = s.focus, .address = s.pc }, label, available, switch (kind) {
.source => s.source,
.map => s.maps[@backingInt(s.focus)],
.annotate => s.annotations,
@@ -598,9 +791,9 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
else => false,
});
}
- u.text(.sans, 17, 600, 63, "j k scroll s instruction n source c run : command ? help", ink.dim);
+ if (geometry.w > 1500) u.text(.sans, 17, 740, 63, u.print("t graph · d unobserved {d}% · p segments · Ctrl +/− {d}%", .{ s.dim, s.zoom }), ink.dim);
const t = if (trace) |*t| t else {
- _ = u.moved(24, 88).panel(2192, 1124, "session", .{ .focus = true });
+ _ = u.moved(24, 112).panel(geometry.w - 48, geometry.h - 160, "session", .{ .focus = true });
u.text(.sans_medium, 34, 72, 174, "Start with a real process.", ink.primary);
u.text(.mono, 22, 72, 226, "launch PROGRAM [ARGS]", gold.solid);
u.text(.sans, 22, 72, 268, "Open commands with : or backtick, then set a breakpoint and continue.", ink.dim);
@@ -612,37 +805,69 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
const regs = (m.regs(s.tid) catch null) orelse return;
const low = (regs.rsp -| 24) & ~@as(u64, 7);
if (ss.shown != m.index or ss.tid != s.tid) selected(ss, t, m, regs, s.tid, low, f.in.now);
+ if (ss.graph != s.graph) {
+ ss.graph = s.graph;
+ ss.scroll[0] = 0;
+ }
const seconds = @as(f32, @floatFromInt(f.in.now -| ss.changed_at)) / 1e9;
const heat = changedHeat(seconds);
const fire = if (seconds < ui.theme.time.fire) ui.theme.pulse(seconds / ui.theme.time.fire) else 0;
const travel = ui.theme.ease(.standard, std.math.clamp(seconds / ui.theme.time.step, 0, 1));
const mode = if (!s.following) "HISTORY" else if (s.status == .running) "LAST STOP" else "LIVE";
- u.text(.mono_bold, 18, 1650, 63, mode, gold.solid);
- u.text(.mono, 18, 1770, 63, u.print("moment {d}/{d} · tid {d}", .{ m.index, t.len -| 1, s.tid }), ink.dim);
+ u.text(.mono_bold, 17, 24, geometry.top - 12, mode, gold.solid);
+ u.text(.mono, 17, 150, geometry.top - 12, canim.rows.fitted(u, u.print("moment {d}/{d} · tid {d}", .{ m.index, t.len -| 1, s.tid }), geometry.w - 174), ink.dim);
const live_bases = [3]u64{ ss.code_start, low, (ss.touch orelse canim.Recording.Touch{ .addr = regs.rsp, .len = 8, .how = 1 }).addr & ~@as(u64, 15) };
for (0..3) |p| {
- bases[p] = if (s.nav[p].place.follow) live_bases[p] else s.nav[p].place.address;
+ const nav = s.nav[p].place;
+ const address = if (nav.follow and !nav.manual) live_bases[p] else if (nav.address != 0) nav.address else live_bases[p];
+ ranges[p] = (m.mapping(address, null, &.{}) catch null) orelse .{ .addr = address, .len = 2048, .prot = 0, .offset = 0 };
+ bases[p] = if (p == 0) address else ranges[p].addr;
if (ss.base[p] != bases[p]) {
ss.scroll[p] = 0;
ss.base[p] = bases[p];
}
- const target = if (s.nav[p].place.follow) 0 else s.nav[p].place.row;
+ if (p > 0) extents[p] = @max(0, @as(f64, @floatFromInt(ranges[p].len / (if (p == 1) @as(u64, 8) else 16))) - Geometry.visible(panes[p]));
+ const target = if (nav.manual) nav.row else if (p == 0) @as(f64, 0) else @as(f64, @floatFromInt((address -| bases[p]) / (if (p == 1) @as(u64, 8) else 16)));
const dt = @as(f32, @floatFromInt(f.in.dt)) / 1e9;
- ss.scroll[p] = std.math.lerp(ss.scroll[p], target, 1 - @exp(-dt * 18));
- if (@abs(ss.scroll[p] - target) < 0.001) ss.scroll[p] = target;
+ // Avoid animating across millions of uncaptured rows after an address jump.
+ if (p == 0 and nav.follow and !nav.manual) continue;
+ if (@abs(ss.scroll[p] - target) > Geometry.visible(panes[p]) * 2) ss.scroll[p] = target else ss.scroll[p] = std.math.lerp(ss.scroll[p], target, 1 - @exp(-dt * 18));
+ shown_scroll[p] = ss.scroll[p];
}
listing(ss, m, bases[0]);
- drawCode(u.moved(24, 88), s, ss, m, regs, heat, fire, travel);
- drawRegisters(u.moved(1628, 88), s, ss, m, regs, heat, seconds, fire);
- drawStack(u.moved(24, 812), s, ss, m, regs, heat, seconds);
- drawMemory(u.moved(1120, 812), s, ss, m, heat);
+ if (s.origin != 0) {
+ var buf: [1024]u8 = undefined;
+ if ((zt.telescope.instruction(m, s.origin, &buf) catch null)) |insn| ss.origin_line = insn.line;
+ }
+ if (ss.capture_stop != s.execution) {
+ ss.capture_stop = s.execution;
+ ss.inspected = @splat(0);
+ }
+ // Captures are bounded and only requested from the selected live stop.
+ if (client != null and s.following and s.status == .stopped) for (0..3) |p| {
+ const address = bases[p] +| (if (p == 0) @as(u64, 0) else @as(u64, @intFromFloat(@floor(if (s.nav[p].place.manual) s.nav[p].place.row else ss.scroll[p]))) * (if (p == 1) @as(u64, 8) else 16));
+ const key = address ^ (s.pc *% 0x9e3779b97f4a7c15);
+ if (ss.inspected[p] != key and (s.nav[p].place.manual or !s.nav[p].place.follow) and (p != 0 or ss.code_count == 0)) {
+ ss.inspected[p] = key;
+ f.run(u.print("inspect {s} 0x{x} {d}", .{ if (p == 0) "code" else "memory", address, @as(u32, if (p == 0) 128 else 2048) }));
+ break;
+ }
+ };
+ ui.bound = .{ .x = 0, .y = geometry.top, .w = geometry.w, .h = @max(0, geometry.h - geometry.top - 40) };
+ u.clip(.{ .x = ui.bound.?.x, .y = ui.bound.?.y, .w = ui.bound.?.w, .h = ui.bound.?.h });
+ drawCode(u.moved(panes[0].x, panes[0].y), s, ss, m, regs, heat, fire, travel);
+ drawRegisters(u.moved(geometry.registers.x, geometry.registers.y), s, ss, m, regs, heat, seconds, fire);
+ drawStack(u.moved(panes[1].x, panes[1].y), s, ss, m, regs, heat, seconds);
+ drawMemory(u.moved(panes[2].x, panes[2].y), s, ss, m, heat);
+ ui.bound = null;
+ u.unclip();
ties(u, s, ss, m, travel);
const place = if (t.len <= 1) 1 else @as(f32, @floatFromInt(m.index)) / @as(f32, @floatFromInt(t.len - 1));
- u.fill(.{ .x = 24, .y = 1226, .w = 2192, .h = 2 }, ui.theme.color.rule);
- u.fill(.{ .x = 24, .y = 1226, .w = 2192 * place, .h = 2 }, gold.solid);
- u.fill(.{ .x = 22 + 2192 * place, .y = 1223, .w = 4, .h = 8 }, gold.solid);
- u.text(.sans, 17, 24, 1251, if (s.following) "Live stop · right-click an address to follow its meaning · click for a lens" else "Recorded state · inspecting and navigating leave the target unchanged", ink.dim);
- u.text(.sans, 17, 1730, 1251, "gold: execution vermilion: changed", ink.dim);
+ u.fill(.{ .x = 24, .y = geometry.h - 34, .w = geometry.w - 48, .h = 2 }, ui.theme.color.rule);
+ u.fill(.{ .x = 24, .y = geometry.h - 34, .w = (geometry.w - 48) * place, .h = 2 }, gold.solid);
+ u.fill(.{ .x = 22 + (geometry.w - 48) * place, .y = geometry.h - 37, .w = 4, .h = 8 }, gold.solid);
+ if (geometry.w >= 1200 and geometry.content <= geometry.h + 1) u.text(.sans, 17, 24, geometry.h - 9, if (s.following) "Live stop · right-click an address to follow its meaning · click for a lens" else "Recorded state · inspecting and navigating leave the target unchanged", ink.dim);
+ if (geometry.content > geometry.h) u.text(.sans, 16, 24, geometry.h - 9, "PgUp/PgDn · scroll pane headers", ink.dim);
overlays(u, s, ss, m);
}
fn listing(ss: *Session, m: zt.store.Moment, base: u64) void {
@@ -653,17 +878,35 @@ fn listing(ss: *Session, m: zt.store.Moment, base: u64) void {
var pc = base;
for (&ss.code, &ss.code_text, &ss.code_lines) |*row, *buf, *line| {
const insn = (zt.telescope.instruction(m, pc, buf) catch null) orelse break;
+ var bytes: [15]u8 = undefined;
+ var known: [15]bool = @splat(false);
+ if (insn.len == 0 or insn.len > bytes.len) break;
+ m.read(pc, bytes[0..insn.len], known[0..insn.len]) catch break;
+ if (std.mem.indexOfScalar(bool, known[0..insn.len], false) != null) break;
row.* = .{ .addr = pc, .len = insn.len, .text = insn.text, .line = if (insn.line) |l| l.line else null, .params = insn.params };
line.* = insn.line;
ss.code_count += 1;
pc +|= insn.len;
}
- ss.aligned_count = canim.aligned.livePlan(ss.code_lines[0..ss.code_count], &ss.aligned).len;
+ code_after = if (pc > base) pc else base +| 128;
+ code_before = base -| 128;
+ if (ss.code_count > 0) {
+ var previous: [1024]u8 = undefined;
+ if ((zt.telescope.instruction(m, base, &previous) catch null)) |insn| if (insn.back > 0) {
+ code_before = base -| insn.back;
+ };
+ }
+ var prefix: usize = 0;
+ if (ss.code_count > 0) if (ss.code_lines[0]) |first| {
+ prefix = @min(2, first.line -| 1);
+ for (0..prefix) |i| ss.aligned[i] = .{ .instruction = null, .source = .{ .file = first.file, .line = first.line - @as(u32, @intCast(prefix - i)) } };
+ };
+ ss.aligned_count = prefix + canim.aligned.livePlan(ss.code_lines[0..ss.code_count], ss.aligned[prefix..]).len;
}
fn sourceLine(u: ui.Ui, column: usize, m: zt.store.Moment, line: zt.store.Line, y: f32, w: f32, current: bool, fire: f32, again: bool) void {
const file = sources.get(gpa, io, m, line.file) orelse return;
const text = file.text orelse {
- u.text(.mono, 18, 64, y + 18, "source file unavailable", ui.theme.color.text.faint);
+ u.text(.mono, 18, 64, y + 18, canim.rows.fitted(u, "source file unavailable", @max(0, w - 64)), ui.theme.color.text.faint);
return;
};
if (line.line == 0 or line.line > text.lines.len) return;
@@ -671,10 +914,16 @@ fn sourceLine(u: ui.Ui, column: usize, m: zt.store.Moment, line: zt.store.Line,
canim.rows.line(u, y, w, line.line, canim.rows.numberRoom(@intCast(text.lines.len)), text.bytes[@min(range[0] + column, range[1])..range[1]], text.styles[@min(range[0] + column, range[1])..range[1]], if (current) .{ .current = fire } else .plain);
if (again) u.text(.mono, 18, 3, y + 19, "↻", ui.theme.color.text.dim);
}
+fn codeVisible() f32 {
+ return @max(1, @floor((@min(panes[0].y + panes[0].h, geometry.h - 40) - @max(panes[0].y + code_top, geometry.top)) / 24));
+}
+fn columns(s: *const State) bool {
+ return s.source and panes[0].w >= 900;
+}
fn codeRows(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: zt.Regs, first: f32, heat: ui.Heat, fire: f32, travel: f32, miniature: bool) void {
- const seam: f32 = if (s.source) 536 else 0;
- const room: f32 = 1580 - seam - if (s.maps[0]) @as(f32, 58) else 6;
- const count = if (s.source) ss.aligned_count else ss.code_count;
+ const seam: f32 = if (columns(s)) Geometry.seam(panes[0]) else 0;
+ const room: f32 = panes[0].w - seam - if (s.maps[0]) @as(f32, 58) else 6;
+ const count = if (columns(s)) ss.aligned_count else ss.code_count;
var current_group: ?usize = null;
var group_start: usize = 0;
for (ss.aligned[0..ss.aligned_count], 0..) |row, i| {
@@ -686,20 +935,22 @@ fn codeRows(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: z
var pc_row: ?f32 = null;
var branch_row: ?f32 = null;
for (0..count) |i| {
- const r: canim.aligned.LiveRow = if (s.source) ss.aligned[i] else .{ .instruction = i };
- const y = (if (miniature) @as(f32, 0) else 32) + (@as(f32, @floatFromInt(i)) - first) * 24;
- if (!miniature and (y < 8 or y >= 706)) continue;
- if (s.source) if (r.source) |line| {
+ const r: canim.aligned.LiveRow = if (columns(s)) ss.aligned[i] else .{ .instruction = i };
+ const y = (if (miniature) @as(f32, 0) else code_top) + @as(f32, @floatCast((@as(f64, @floatFromInt(i)) - first) * 24));
+ if (!miniature and (y < code_top - 24 or y >= panes[0].h - 2)) continue;
+ if (columns(s)) if (r.source) |line| {
const current = current_group == i;
sourceLine(if (r.instruction == null) u.faded(0.45) else u, if (miniature) 0 else s.source_column, m, line, y, seam - 32, current, fire, r.again);
if (r.instruction != null) u.route(&.{ .{ seam - 30, y + 12 }, .{ seam - 8, y + 12 }, .{ seam + 2, y + 12 } }, if (current) ui.theme.mark(.current).solid else ui.theme.color.rule, .{ .width = 1.5, .head = .{ 5, 6 }, .progress = if (current) travel else 1 });
};
const index = r.instruction orelse continue;
const row = ss.code[index];
- const d = u.moved(seam, 0);
+ const observed = std.mem.indexOfScalar(u64, &ss.trail, row.addr) != null;
+ const predicted = if (ss.branch) |branch| (branch.kind == .jump and branch.taken and branch.to == row.addr) else false;
+ const d = u.moved(seam, 0).faded(if (row.addr == regs.rip or observed or predicted) 1 else @max(0.15, @as(f32, @floatFromInt(s.dim)) / 100));
const current = row.addr == regs.rip;
if (current) {
- const marker_y = if (miniature) y else 32 + (ss.marker_shown - first) * 24;
+ const marker_y = if (miniature) y else code_top + (ss.marker_shown - first) * 24;
pc_row = marker_y;
d.current(.{ .x = 2, .y = marker_y, .w = room - 4, .h = 24 }, ui.theme.metric.plaque.pc, fire);
sk.draw.polygon(u.f, &.{ .{ 20, marker_y + 12 }, .{ 10, marker_y + 6 }, .{ 10, marker_y + 18 } }, d.at.pen(.{ .fill = ui.rgb(ui.theme.mark(.current).on_solid) }));
@@ -708,13 +959,13 @@ fn codeRows(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: z
d.trail(2, y, k);
break;
};
- canim.disasm.liveRow(d, row, y, room, m, regs, .{ .current = current and s.annotations, .executed = ss.result_at == row.addr and s.annotations, .heat = heat, .lead = ui.shared(&.{ bases[0], bases[0] +| 512 }), .touch = if (current and s.annotations) ss.touch else null, .branch = if (current and s.annotations) ss.branch else null });
+ canim.disasm.liveRow(d, row, y, room, m, regs, .{ .compact = room < 520, .current = current and s.annotations, .executed = ss.result_at == row.addr and s.annotations, .heat = heat, .lead = ui.shared(&.{ bases[0], bases[0] +| 512 }), .touch = if (current and s.annotations) ss.touch else null, .branch = if (current and s.annotations) ss.branch else null });
if (ss.branch) |branch| if (branch.to == row.addr) {
branch_row = y;
};
}
- if (!miniature and s.source and pc_row != null and current_group != null) {
- const from = 32 + (@as(f32, @floatFromInt(current_group.?)) - first) * 24 + 12;
+ if (!miniature and columns(s) and pc_row != null and current_group != null) {
+ const from = code_top + (@as(f32, @floatFromInt(current_group.?)) - first) * 24 + 12;
if (@abs(from - pc_row.? - 12) > 1) u.route(&.{ .{ seam - 30, from }, .{ seam - 12, from }, .{ seam - 12, pc_row.? + 12 }, .{ seam + 2, pc_row.? + 12 } }, ui.theme.mark(.current).solid, .{ .width = 2, .head = .{ 6, 7 }, .progress = travel });
}
if (!miniature and pc_row != null and branch_row != null) if (ss.branch) |branch| if (branch.kind == .jump) {
@@ -722,11 +973,20 @@ fn codeRows(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: z
};
}
fn drawCode(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: zt.Regs, heat: ui.Heat, fire: f32, travel: f32) void {
- const count = if (s.source) ss.aligned_count else ss.code_count;
- const marker_key = (m.index + 1) *% 0x9e3779b97f4a7c15 ^ bases[0] ^ @as(u64, @intFromBool(s.source));
+ code_top = 32;
+ const actual_height = @min(panes[0].h, geometry.h - 40 - panes[0].y);
+ origin_height = if (actual_height < 250) 48 else 72;
+ source_height = if (actual_height < 250) 24 else 48;
+ const native_line = m.line(s.tid) catch null;
+ if (!s.graph) if (ss.origin_line) |origin| if (native_line == null or native_line.?.file != origin.file) {
+ code_top += origin_height;
+ };
+ if (!columns(s) and s.source and !s.graph) code_top += source_height;
+ const count = if (columns(s)) ss.aligned_count else ss.code_count;
+ const marker_key = (m.index + 1) *% 0x9e3779b97f4a7c15 ^ bases[0] ^ @as(u64, @intFromBool(columns(s)));
if (ss.marker_key != marker_key) {
for (0..count) |i| {
- const index = if (s.source) ss.aligned[i].instruction else i;
+ const index = if (columns(s)) ss.aligned[i].instruction else i;
if (index) |j| if (ss.code[j].addr == regs.rip) {
ss.marker_to = @floatFromInt(i);
ss.marker_from = if (ss.marker_base == bases[0]) ss.marker_shown else ss.marker_to;
@@ -736,124 +996,157 @@ fn drawCode(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: z
ss.marker_base = bases[0];
ss.marker_at = u.f.in.now;
}
+ if (!s.graph and s.nav[0].place.follow and !s.nav[0].place.manual) {
+ var start: f32 = ss.marker_to;
+ if (columns(s)) {
+ var group: usize = 0;
+ for (ss.aligned[0..ss.aligned_count], 0..) |r, k| {
+ if (r.source != null) group = k;
+ if (r.instruction) |j| if (ss.code[j].addr == regs.rip) {
+ start = @floatFromInt(group);
+ break;
+ };
+ }
+ }
+ const visible = codeVisible();
+ const target = @max(0, @max(start - 2, ss.marker_to - visible + @min(3, visible)));
+ const dt = @as(f32, @floatFromInt(u.f.in.dt)) / 1e9;
+ ss.scroll[0] = std.math.lerp(ss.scroll[0], target, 1 - @exp(-dt * 18));
+ shown_scroll[0] = ss.scroll[0];
+ }
const marker_time = @as(f32, @floatFromInt(u.f.in.now -| ss.marker_at)) / 1e9;
ss.marker_shown = std.math.lerp(ss.marker_from, ss.marker_to, ui.theme.ease(.standard, std.math.clamp(marker_time / ui.theme.time.step, 0, 1)));
- extents[0] = @max(0, @as(f32, @floatFromInt(count)) - 27);
- _ = u.panel(1580, 708, if (s.source) "source / disassembly" else "disassembly", .{ .focus = s.focus == .code });
+ extents[0] = @max(0, @as(f32, @floatFromInt(count)) - codeVisible());
+ _ = u.panel(panes[0].w, panes[0].h, if (s.graph) "control flow" else if (panes[0].w < 600) "code" else if (s.source) "source / disassembly" else "disassembly", .{ .focus = s.focus == .code });
var file_name: []const u8 = "no recorded source mapping";
for (ss.code_lines[0..ss.code_count]) |line| if (line) |l| {
if (sources.get(gpa, io, m, l.file)) |file| file_name = file.path;
break;
};
- u.text(.sans, 17, 250, 19, canim.rows.fitted(u, file_name, 1050), ui.theme.color.text.dim);
+ u.text(.sans, 17, 250, 19, canim.rows.fitted(u, file_name, @max(0, panes[0].w - 500)), ui.theme.color.text.dim);
paneButtons(u, s, .code);
- u.clip(.{ .x = 2, .y = 30, .w = 1576 - if (s.maps[0]) @as(f32, 56) else 0, .h = 676 });
- if (s.source) u.line(.{ 530, 30 }, .{ 530, 706 }, ui.theme.color.rule, 1);
- codeRows(u, s, ss, m, regs, ss.scroll[0], heat, fire, travel, false);
- if (ss.code_count == 0) u.text(.sans, 20, if (s.source) 550 else 24, 64, "Code not captured · use goto code ADDRESS at a live stop", ui.theme.color.text.dim);
- if (s.source and std.mem.eql(u8, file_name, "no recorded source mapping")) {
+ if (!s.graph and code_top >= 32 + origin_height) if (ss.origin_line) |origin| {
+ if (sources.get(gpa, io, m, origin.file)) |file| {
+ u.text(.sans, 17, 12, 50, canim.rows.fitted(u, u.print("Originating JS · {s}:{d}", .{ std.fs.path.basename(file.path), origin.line }), panes[0].w - 30), ui.theme.mark(.current).solid);
+ sourceLine(u, 0, m, origin, if (origin_height < 72) 52 else 58, panes[0].w - 64, false, 0, false);
+ u.line(.{ 8, 32 + origin_height - 4 }, .{ panes[0].w - 60, 32 + origin_height - 4 }, ui.theme.color.rule, 1);
+ }
+ };
+ if (!columns(s) and s.source and !s.graph) {
+ const line = if (s.nav[0].place.follow and !s.nav[0].place.manual) native_line else if (ss.code_count > 0) ss.code_lines[0] else null;
+ if (line) |l| sourceLine(u, s.source_column, m, l, code_top - source_height, panes[0].w - 64, true, 0, false);
+ }
+ u.clip(.{ .x = 2, .y = code_top, .w = panes[0].w - 4 - if (s.maps[0]) @as(f32, 56) else 0, .h = panes[0].h - code_top - 2 });
+ if (columns(s) and !s.graph) u.line(.{ Geometry.seam(panes[0]) - 6, 30 }, .{ Geometry.seam(panes[0]) - 6, panes[0].h - 2 }, ui.theme.color.rule, 1);
+ if (s.graph) {
+ const size = canim.graph.live(u.moved(-s.horizontal[0], 32 - @as(f32, @floatCast(ss.scroll[0] * 24))), m, regs.rip, ss.trail, @as(f32, @floatFromInt(s.dim)) / 100);
+ extents[0] = @max(0, (size - panes[0].h + 40) / 24);
+ } else codeRows(u.moved(-s.horizontal[0], 0), s, ss, m, regs, @floatCast(ss.scroll[0]), heat, fire, travel, false);
+ if (!s.graph and ss.code_count == 0) u.text(.sans, 20, if (columns(s)) Geometry.seam(panes[0]) + 14 else 24, 64, "Code not captured · use goto code ADDRESS at a live stop", ui.theme.color.text.dim);
+ if (!s.graph and columns(s) and std.mem.eql(u8, file_name, "no recorded source mapping")) {
u.text(.sans_medium, 22, 28, 72, "Source mapping unavailable", ui.theme.color.text.dim);
u.text(.sans, 18, 28, 106, "This code has no recorded file / line table.", ui.theme.color.text.faint);
u.text(.sans, 18, 28, 136, "Machine instructions remain fully inspectable.", ui.theme.color.text.faint);
}
u.unclip();
if (s.maps[0]) {
- const key = (m.index + 1) *% 0x9e3779b97f4a7c15 ^ bases[0] ^ (@as(u64, s.depth) << 32) ^ (@as(u64, @intFromBool(s.source)) << 40) ^ (@as(u64, @intFromBool(s.ascii)) << 41);
+ segmentMini(u, 0, bases[0], @max(1, code_after -| bases[0]), regs.rip);
+ compact_count = ss.code_count;
+ for (ss.code[0..ss.code_count], 0..) |_, j| {
+ compact_rows[j] = j;
+ if (columns(s)) for (ss.aligned[0..ss.aligned_count], 0..) |r, k| if (r.instruction == j) {
+ compact_rows[j] = k;
+ break;
+ };
+ }
+ const key = (m.index + 1) *% 0x9e3779b97f4a7c15 ^ bases[0];
if (ss.mini_key[0] != key) {
ui.collected.reset();
ui.strokes = true;
u.clip(.{ .x = 0, .y = 0, .w = 0, .h = 0 });
- // Identity coordinates keep the collected miniature local to its pane.
- codeRows(ui.Ui.init(u.f), s, ss, m, regs, 0, .none, 0, 1, true);
+ const v = ui.Ui.init(u.f);
+ for (ss.code[0..ss.code_count], 0..) |row, i| {
+ v.text(.mono, 20, 0, @as(f32, @floatFromInt(i)) * 24 + 20, row.text, ui.theme.color.text.dim);
+ }
ui.strokes = false;
u.unclip();
ss.mini[0] = ui.collected;
ss.mini_key[0] = key;
}
- var current: ?f32 = null;
- for (0..count) |i| {
- const index = if (s.source) ss.aligned[i].instruction else i;
- if (index) |j| if (ss.code[j].addr == regs.rip) {
- current = @floatFromInt(i);
- };
- }
- canim.minimap.liveStrip(u, ss.mini[0].runs[0..ss.mini[0].n_runs], .{ .x = 1528, .y = 32, .w = 46, .h = 668 }, 1520, count, ss.scroll[0], 27, current);
+ var mini = Geometry.mini(panes[0]);
+ mini.w -= 16;
+ var first: f32 = 0;
+ for (compact_rows[0..compact_count], 0..) |row, i| if (@as(f64, @floatFromInt(row)) <= ss.scroll[0]) {
+ first = @floatFromInt(i);
+ };
+ const shown = ui.Rect{ .x = mini.x, .y = mini.y, .w = mini.w, .h = mini.h };
+ canim.minimap.liveStrip(u, ss.mini[0].runs[0..ss.mini[0].n_runs], shown, 900, ss.code_count, first, Geometry.visible(panes[0]), null);
}
}
fn drawRegisters(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: zt.Regs, heat: ui.Heat, seconds: f32, fire: f32) void {
- _ = u.panel(588, 708, "registers / call stack", .{ .note = u.print("{d} changed", .{@popCount(ss.changed_regs)}) });
- u.clip(.{ .x = 2, .y = 30, .w = 584, .h = 674 });
+ _ = u.panel(geometry.registers.w, geometry.registers.h, "registers / call stack", .{ .note = u.print("{d} changed", .{@popCount(ss.changed_regs)}) });
+ u.clip(.{ .x = 2, .y = 30, .w = geometry.registers.w - 4, .h = geometry.registers.h - 34 });
+ const v = u.moved(0, -s.register_scroll * 24);
for (zt.Regs.names[0..16], 0..) |reg, i| {
const changed = ss.changed_regs & (@as(u32, 1) << @intCast(i)) != 0;
- _ = canim.rows.reg(u, 34 + @as(f32, @floatFromInt(i)) * 24, 588, reg, m, regs.named(reg).?, .{ .first = if (changed) heat else .none, .extend = if (changed) seconds else null, .most = s.depth });
+ _ = canim.rows.reg(v, 34 + @as(f32, @floatFromInt(i)) * 24, geometry.registers.w, reg, m, regs.named(reg).?, .{ .first = if (changed) heat else .none, .extend = if (changed) seconds else null, .most = s.depth });
}
- u.current(.{ .x = 1, .y = 430, .w = 586, .h = 24 }, ui.theme.metric.plaque.rip, fire);
- u.text(.mono_bold, 20, 14, canim.rows.baseline(430), "rip", ui.theme.mark(.current).on_solid);
- _ = canim.rows.chain(u, 74, 430, m, regs.rip, 576, .{});
- canim.rows.ripFlags(u, 224, 458, regs.eflags, ss.changed_flags, heat.corner, if (ss.branch != null) flagsReadAt(m, regs.rip) else 0, 1, .{ .moment = m, .pc = regs.rip, .eflags = regs.eflags });
- u.line(.{ 12, 484 }, .{ 576, 484 }, ui.theme.color.rule, 1);
- u.text(.sans_medium, 18, 14, 510, "call stack", ui.theme.color.text.primary);
+ v.current(.{ .x = 1, .y = 430, .w = geometry.registers.w - 2, .h = 24 }, ui.theme.metric.plaque.rip, fire);
+ v.text(.mono_bold, 20, 14, canim.rows.baseline(430), "rip", ui.theme.mark(.current).on_solid);
+ _ = canim.rows.chain(v, 74, 430, m, regs.rip, geometry.registers.w - 12, .{});
+ canim.rows.ripFlags(v, 224, 458, regs.eflags, ss.changed_flags, heat.corner, if (ss.branch != null) flagsReadAt(m, regs.rip) else 0, 1, .{ .moment = m, .pc = regs.rip, .eflags = regs.eflags });
+ v.line(.{ 12, 484 }, .{ geometry.registers.w - 12, 484 }, ui.theme.color.rule, 1);
+ v.text(.sans_medium, 18, 14, 510, "call stack", ui.theme.color.text.primary);
var frame_buf: [10]zt.Debugger.Frame = undefined;
const frames = zt.telescope.frames(m, &regs, &frame_buf) catch &.{};
for (frames[0..@min(frames.len, 3)], 0..) |frame, i| {
const y = 522 + @as(f32, @floatFromInt(i)) * 52;
- if (i == 0) canim.rows.callCurrent(u, y, 588);
- u.text(.mono, 20, 12, canim.rows.baseline(y), u.print("{d}", .{i}), if (i == 0) ui.theme.mark(.current).on_solid else ui.theme.color.text.dim);
- _ = u.address(60, canim.rows.baseline(y), frame.pc, .{ .ink = ui.rgb(ui.theme.color.region.code_) });
+ if (i == 0) canim.rows.callCurrent(v, y, geometry.registers.w);
+ v.text(.mono, 20, 12, canim.rows.baseline(y), v.print("{d}", .{i}), if (i == 0) ui.theme.mark(.current).on_solid else ui.theme.color.text.dim);
+ _ = v.address(60, canim.rows.baseline(y), frame.pc, .{ .ink = ui.rgb(ui.theme.color.region.code_) });
var buf: [256]u8 = undefined;
const name_ = (m.string(frame.pc, &buf) catch null) orelse "anonymous code";
- u.text(.mono, 18, 60, y + 44, canim.rows.fitted(u, ui.symbol(u, name_), 510), ui.theme.color.text.dim);
+ v.text(.mono, 18, 60, y + 44, canim.rows.fitted(v, ui.symbol(v, name_), geometry.registers.w - 72), ui.theme.color.text.dim);
}
u.unclip();
}
-fn stackRows(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: zt.Regs, first: f32, heat: ui.Heat, seconds: f32, miniature: bool) void {
+fn stackRows(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: zt.Regs, first: f64, heat: ui.Heat, seconds: f32, miniature: bool) void {
const start: usize = if (miniature) 0 else @intFromFloat(@floor(@max(0, first)));
- const count: usize = if (miniature) 128 else 17;
+ const count: usize = if (miniature) 128 else @intFromFloat(Geometry.visible(panes[1]) + 2);
const base = bases[1] & ~@as(u64, 7);
var slots: [128]zt.telescope.Slot = undefined;
- _ = zt.telescope.slots(m, &regs, base +| start * 8, slots[0..@min(count, 128 - start)]) catch {
+ _ = zt.telescope.slots(m, &regs, base +| start * 8, slots[0..@min(count, 128)]) catch {
@memset(&slots, .{});
};
- for (start..@min(start + count, 128)) |i| {
+ for (start..@min(start + @min(count, 128), @as(usize, @intCast(ranges[1].len / 8)))) |i| {
const addr = base +| i * 8;
- const y = (if (miniature) @as(f32, 0) else 32) + (@as(f32, @floatFromInt(i)) - first) * 24;
- const changed = addr >= regs.rsp -| 24 and i < 11 and base == ((regs.rsp -| 24) & ~@as(u64, 7)) and ss.changed_stack & (@as(u16, 1) << @as(u4, @intCast(i))) != 0;
+ const y = (if (miniature) @as(f32, 0) else 32) + @as(f32, @floatCast((@as(f64, @floatFromInt(i)) - first) * 24));
+ const changed = addr >= regs.rsp -| 24 and addr < (regs.rsp -| 24) + 88 and ss.changed_stack & (@as(u16, 1) << @as(u4, @intCast((addr - (regs.rsp -| 24)) / 8))) != 0;
const touched = if (ss.touch) |touch| touch.how & 1 != 0 and addr < touch.addr +| touch.len and addr +| 8 > touch.addr else false;
const pins: []const []const u8 = if (addr == regs.rsp and addr == regs.rbp) &.{ "rsp", "rbp" } else if (addr == regs.rsp) &.{"rsp"} else if (addr == regs.rbp) &.{"rbp"} else &.{};
const role = canim.Stack.slotName(u, slots[i - start], (canim.Recording.word(m, addr, 8) catch null) orelse 0);
- _ = canim.rows.slot(u, y, if (s.maps[1]) 1012 else 1072, m, addr, @bitCast(addr -% regs.rsp), pins, 1, .{ .first = if (changed) heat else .none, .read = if (touched) 1 else null, .read_shows = 1, .lead = ui.shared(&.{ base, base +| 1024 }), .extend = if (changed) seconds else null, .most = s.depth }, role.name, role.local, null);
+ _ = canim.rows.slot(u, y, panes[1].w - if (s.maps[1]) @as(f32, 60) else 0, m, addr, @bitCast(addr -% regs.rsp), pins, 1, .{ .first = if (changed) heat else .none, .read = if (touched) 1 else null, .read_shows = 1, .lead = ui.shared(&.{ base, base +| 1024 }), .extend = if (changed) seconds else null, .most = s.depth }, role.name, role.local, null);
}
}
fn drawStack(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, regs: zt.Regs, heat: ui.Heat, seconds: f32) void {
- extents[1] = 113;
- _ = u.panel(1072, 400, "stack / telescope", .{ .focus = s.focus == .stack });
- u.text(.sans, 17, 235, 19, u.print("{d} pointer hops", .{s.depth}), ui.theme.color.text.dim);
+ _ = u.panel(panes[1].w, panes[1].h, if (panes[1].w < 600) "stack" else "stack / telescope", .{ .focus = s.focus == .stack });
+ if (panes[1].w > 800) u.text(.sans, 17, 235, 19, u.print("{d} pointer hops", .{s.depth}), ui.theme.color.text.dim);
paneButtons(u, s, .stack);
- u.clip(.{ .x = 2, .y = 30, .w = if (s.maps[1]) 1012 else 1068, .h = 362 });
- stackRows(u, s, ss, m, regs, ss.scroll[1], heat, seconds, false);
+ u.clip(.{ .x = 2, .y = 30, .w = panes[1].w - if (s.maps[1]) @as(f32, 60) else 4, .h = panes[1].h - 38 });
+ stackRows(u.moved(-s.horizontal[1], 0), s, ss, m, regs, ss.scroll[1], heat, seconds, false);
var frame_buf: [10]zt.Debugger.Frame = undefined;
const frames = zt.telescope.frames(m, &regs, &frame_buf) catch &.{};
const low = (bases[1] & ~@as(u64, 7)) + @as(u64, @intFromFloat(ss.scroll[1])) * 8;
for (frames, 0..) |frame, k| {
const from = @max(frame.low, low);
- const to = @min(frame.high, low + 15 * 8);
+ const to = @min(frame.high, low + @as(u64, @intFromFloat(Geometry.visible(panes[1]))) * 8);
if (from >= to) continue;
- canim.rows.span(u, if (s.maps[1]) 1012 else 1072, 32 + @as(f32, @floatFromInt((from - low) / 8)) * 24, 32 + @as(f32, @floatFromInt((to - low) / 8)) * 24, u.print("#{d}", .{k}), k == 0, frame.high > low + 15 * 8);
+ canim.rows.span(u, panes[1].w - if (s.maps[1]) @as(f32, 60) else 0, 32 + @as(f32, @floatFromInt((from - low) / 8)) * 24, 32 + @as(f32, @floatFromInt((to - low) / 8)) * 24, u.print("#{d}", .{k}), k == 0, frame.high > low + @as(u64, @intFromFloat(Geometry.visible(panes[1]))) * 8);
}
u.unclip();
if (s.maps[1]) {
- const key = (m.index + 1) *% 0x9e3779b97f4a7c15 ^ bases[1] ^ (@as(u64, s.depth) << 32) ^ (@as(u64, @intFromBool(s.source)) << 40) ^ (@as(u64, @intFromBool(s.ascii)) << 41);
- if (ss.mini_key[1] != key) {
- ui.collected.reset();
- ui.strokes = true;
- u.clip(.{ .x = 0, .y = 0, .w = 0, .h = 0 });
- stackRows(ui.Ui.init(u.f), s, ss, m, regs, 0, .none, seconds, true);
- ui.strokes = false;
- u.unclip();
- ss.mini[1] = ui.collected;
- ss.mini_key[1] = key;
- }
- canim.minimap.liveStrip(u, ss.mini[1].runs[0..ss.mini[1].n_runs], .{ .x = 1020, .y = 32, .w = 46, .h = 360 }, 1012, 128, ss.scroll[1], 15, if (regs.rsp >= bases[1] and regs.rsp < bases[1] +| 1024) @as(f32, @floatFromInt((regs.rsp - bases[1]) / 8)) else null);
+ segmentMini(u, 1, bases[1] + @as(u64, @intFromFloat(ss.scroll[1])) * 8, @as(u64, @intFromFloat(Geometry.visible(panes[1]))) * 8, regs.rsp);
+ memoryMini(u, ss, m, 1);
}
}
fn memoryRow(u: ui.Ui, m: zt.store.Moment, addr: u64, y: f32, room: f32, ascii: bool, touch: ?canim.Recording.Touch, heat: ui.Heat, before: ?zt.store.Moment) void {
@@ -885,36 +1178,78 @@ fn memoryRow(u: ui.Ui, m: zt.store.Moment, addr: u64, y: f32, room: f32, ascii:
_ = canim.hexdump.readingIn(u, y, shift, m, &values, &known, &fields, room);
}
}
-fn memoryRows(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, first: f32, heat: ui.Heat, miniature: bool) void {
+fn memoryRows(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, first: f64, heat: ui.Heat, miniature: bool) void {
const start: usize = if (miniature) 0 else @intFromFloat(@floor(@max(0, first)));
- const count: usize = if (miniature) 128 else 17;
+ const count: usize = if (miniature) 128 else @intFromFloat(Geometry.visible(panes[2]) + 2);
const before = if (m.index > 0) trace.?.moment(m.index - 1) catch null else null;
- for (start..@min(start + count, 128)) |i| {
- const y = (if (miniature) @as(f32, 0) else 32) + (@as(f32, @floatFromInt(i)) - first) * 24;
- memoryRow(u, m, bases[2] +| i * 16, y, if (s.maps[2]) 1036 else 1096, s.ascii, ss.touch, heat, if (miniature) null else before);
+ for (start..@min(start + count, @as(usize, @intCast(ranges[2].len / 16)))) |i| {
+ const y = (if (miniature) @as(f32, 0) else 32) + @as(f32, @floatCast((@as(f64, @floatFromInt(i)) - first) * 24));
+ memoryRow(u, m, bases[2] +| i * 16, y, panes[2].w - if (s.maps[2]) @as(f32, 60) else 0, s.ascii, ss.touch, heat, if (miniature) null else before);
}
}
fn drawMemory(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, heat: ui.Heat) void {
- extents[2] = 113;
- _ = u.panel(1096, 400, "memory / bytes", .{ .focus = s.focus == .memory });
- u.text(.sans, 17, 220, 19, if (s.ascii) "hex · ASCII" else "hex · pointer words", ui.theme.color.text.dim);
+ _ = u.panel(panes[2].w, panes[2].h, if (panes[2].w < 600) "memory" else "memory / bytes", .{ .focus = s.focus == .memory });
+ if (panes[2].w > 800) u.text(.sans, 17, 220, 19, if (s.ascii) "hex · ASCII" else "hex · pointer words", ui.theme.color.text.dim);
paneButtons(u, s, .memory);
- u.clip(.{ .x = 2, .y = 30, .w = if (s.maps[2]) 1036 else 1092, .h = 362 });
- memoryRows(u, s, ss, m, ss.scroll[2], heat, false);
+ u.clip(.{ .x = 2, .y = 30, .w = panes[2].w - if (s.maps[2]) @as(f32, 60) else 4, .h = panes[2].h - 38 });
+ memoryRows(u.moved(-s.horizontal[2], 0), s, ss, m, ss.scroll[2], heat, false);
u.unclip();
if (s.maps[2]) {
- const key = (m.index + 1) *% 0x9e3779b97f4a7c15 ^ bases[2] ^ (@as(u64, s.depth) << 32) ^ (@as(u64, @intFromBool(s.source)) << 40) ^ (@as(u64, @intFromBool(s.ascii)) << 41);
- if (ss.mini_key[2] != key) {
- ui.collected.reset();
- ui.strokes = true;
- u.clip(.{ .x = 0, .y = 0, .w = 0, .h = 0 });
- memoryRows(ui.Ui.init(u.f), s, ss, m, 0, .none, true);
- ui.strokes = false;
- u.unclip();
- ss.mini[2] = ui.collected;
- ss.mini_key[2] = key;
+ segmentMini(u, 2, bases[2] + @as(u64, @intFromFloat(ss.scroll[2])) * 16, @as(u64, @intFromFloat(Geometry.visible(panes[2]))) * 16, if (ss.touch) |t| t.addr else bases[2]);
+ memoryMini(u, ss, m, 2);
+ }
+}
+fn memoryMini(u: ui.Ui, ss: *Session, m: zt.store.Moment, p: usize) void {
+ const stride: u64 = if (p == 1) 8 else 16;
+ const current = bases[p] + @as(u64, @intFromFloat(ss.scroll[p])) * stride;
+ const first = @max(bases[p], current -| 32 * stride);
+ const key = (m.index + 1) *% 0x9e3779b97f4a7c15 ^ first;
+ if (ss.mini_key[p] != key) {
+ compact_counts[p] = 0;
+ ui.collected.reset();
+ ui.strokes = true;
+ u.clip(.{ .x = 0, .y = 0, .w = 0, .h = 0 });
+ const v = ui.Ui.init(u.f);
+ for (0..128) |i| {
+ const address = first +| i * stride;
+ if (address >= ranges[p].addr +| ranges[p].len) break;
+ var bytes: [16]u8 = undefined;
+ var known: [16]bool = @splat(false);
+ m.read(address, bytes[0..stride], known[0..stride]) catch continue;
+ if (std.mem.indexOfScalar(bool, known[0..stride], true) == null) continue;
+ const row = compact_counts[p];
+ compact_addresses[p][row] = address;
+ compact_counts[p] += 1;
+ const y = @as(f32, @floatFromInt(row)) * 24;
+ if (p == 1) {
+ _ = canim.rows.slot(v, y, panes[p].w - 60, m, address, 0, &.{}, 0, .{ .most = 2 }, "", false, null);
+ } else memoryRow(v, m, address, y, panes[p].w - 60, true, null, .none, null);
}
- canim.minimap.liveStrip(u, ss.mini[2].runs[0..ss.mini[2].n_runs], .{ .x = 1044, .y = 32, .w = 46, .h = 360 }, 1036, 128, ss.scroll[2], 15, if (ss.touch) |t| if (t.addr >= bases[2] and t.addr < bases[2] +| 2048) @as(f32, @floatFromInt((t.addr - bases[2]) / 16)) else null else null);
+ ui.strokes = false;
+ u.unclip();
+ ss.mini[p] = ui.collected;
+ ss.mini_key[p] = key;
+ }
+ var mini = Geometry.mini(panes[p]);
+ mini.w -= 16;
+ var first_row: f32 = 0;
+ for (compact_addresses[p][0..compact_counts[p]], 0..) |addr, i| if (addr <= current) {
+ first_row = @floatFromInt(i);
+ };
+ canim.minimap.liveStrip(u, ss.mini[p].runs[0..ss.mini[p].n_runs], .{ .x = mini.x, .y = mini.y, .w = mini.w, .h = mini.h }, panes[p].w - 60, compact_counts[p], first_row, Geometry.visible(panes[p]), null);
+}
+fn segmentMini(u: ui.Ui, p: usize, first: u64, len: u64, current: u64) void {
+ var box = Geometry.mini(panes[p]);
+ box.x += 34;
+ box.w -= 34;
+ u.fill(.{ .x = box.x, .y = box.y, .w = box.w, .h = box.h }, ui.theme.color.raised);
+ const total: f64 = @floatFromInt(@max(1, ranges[p].len));
+ const at: f32 = @floatCast(@as(f64, @floatFromInt(first -| ranges[p].addr)) / total);
+ const size: f32 = @floatCast(@as(f64, @floatFromInt(len)) / total);
+ u.frame(.{ .x = box.x, .y = box.y + at * (box.h - 3), .w = box.w, .h = @max(3, @min(box.h, size * box.h)) }, ui.theme.color.text.dim, 1);
+ if (current >= ranges[p].addr and current - ranges[p].addr < ranges[p].len) {
+ const y = box.y + @as(f32, @floatCast(@as(f64, @floatFromInt(current - ranges[p].addr)) / total)) * (box.h - 2);
+ u.line(.{ box.x, y }, .{ box.x + box.w, y }, ui.theme.mark(.current).solid, 2);
}
}
fn ties(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, travel: f32) void {
@@ -931,9 +1266,9 @@ fn ties(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, travel: f32
const b = hit.box;
if (a.x == b.x and a.y == b.y) continue;
u.read(.{ .x = b.x, .y = b.y, .w = b.w, .h = b.h }, 1);
- if (s.annotations and a.y < 796 and b.y > 812) {
- const lane: f32 = 804;
- u.route(&.{ .{ a.x + a.w, a.y + a.h / 2 }, .{ 1616, a.y + a.h / 2 }, .{ 1616, lane }, .{ if (b.x < 1100) 16 else 1112, lane }, .{ if (b.x < 1100) 16 else 1112, b.y + b.h / 2 }, .{ if (b.x < 1100) 26 else 1122, b.y + b.h / 2 } }, ui.theme.mark(.read).solid, .{ .width = 1.5, .head = .{ 6, 6 }, .progress = if (hovered != null) 1 else travel });
+ if (s.annotations) {
+ const lane = @min(geometry.w - 12, @max(a.x + a.w, b.x + b.w) + 12);
+ u.route(&.{ .{ a.x + a.w, a.y + a.h / 2 }, .{ lane, a.y + a.h / 2 }, .{ lane, b.y + b.h / 2 }, .{ b.x + b.w, b.y + b.h / 2 } }, ui.theme.mark(.read).solid, .{ .width = 1.5, .head = .{ 6, 6 }, .progress = if (hovered != null) 1 else travel });
break;
}
};
@@ -943,64 +1278,97 @@ fn overlays(u: ui.Ui, s: *const State, ss: *Session, moment: ?zt.store.Moment) v
const ink = ui.theme.color.text;
if (!s.lens) ss.lens_previous = 0;
if (s.lens and moment != null) {
- const address = if (s.lens_address != 0) s.lens_address else s.pc;
- if (ss.lens_previous != address) {
+ const overlay: Box = .{ .x = @max(24, geometry.w - 1132), .y = 140, .w = @min(1108, geometry.w - 48), .h = @max(0, geometry.h - 180) };
+ lens_box = overlay;
+ const previous_bound = ui.bound;
+ ui.bound = overlay;
+ u.clip(.{ .x = overlay.x, .y = overlay.y, .w = overlay.w, .h = overlay.h });
+ if (ss.lens_previous != s.lens_address) {
ss.lens_at = u.f.in.now;
- ss.lens_previous = address;
+ ss.lens_previous = s.lens_address;
}
const seconds = @as(f32, @floatFromInt(u.f.in.now -| ss.lens_at)) / 1e9;
const amount = ui.theme.ease(.standard, std.math.clamp(seconds / 0.2, 0, 1));
- const resting_y: f32 = if (s.lens_origin.y >= 592 and s.lens_origin.y < 780 and s.lens_origin.x + s.lens_origin.w > 1090) 300 else 592;
- const box: Box = .{ .x = 1090, .y = resting_y + 8 * (1 - amount), .w = 1108, .h = 188 };
- lens_box = box;
- lens_hits = hit_count;
- const v = u.moved(box.x, box.y).faded(amount);
- v.fill(.{ .x = 14 * amount, .y = 18 * amount, .w = box.w, .h = box.h }, ui.mix(ui.theme.color.page, 0x000000, 0.2));
- v.fill(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }, ui.theme.color.lift);
- v.fill(.{ .x = 0, .y = 0, .w = box.w, .h = 28 }, ui.theme.color.lift_tag);
- v.frame(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }, ui.theme.color.rule, 1);
- v.text(.sans_medium, 18, 14, 21, "address lens", ink.primary);
- _ = v.address(158, 21, address, .{ .ink = ui.rgb(canim.rows.ink(canim.rows.regionOf(moment.?, address))) });
- const first = (address & ~@as(u64, 15)) -| 32;
- var bytes: [80]u8 = undefined;
- var known: [80]bool = @splat(false);
- moment.?.read(first, &bytes, &known) catch {};
- v.text(.sans, 17, 370, 21, if (std.mem.indexOfScalar(bool, &known, true) == null) "Bytes were not captured at this stop · Esc closes" else "click a pointer to follow · right-click to navigate · Esc closes", ink.dim);
- button(v, box.w - 40, -2, .{ .kind = .close_lens }, "Close address lens · Esc / z", true, true);
- v.clip(.{ .x = 2, .y = 30, .w = box.w - 4, .h = box.h - 32 });
- for (0..5) |i| memoryRow(v, moment.?, first +| i * 16, 34 + @as(f32, @floatFromInt(i)) * 24, box.w - 12, false, null, .none, null);
- const row_y = 34 + @as(f32, @floatFromInt((address - first) / 16)) * 24;
- const shift = canim.rows.addressRoom(address);
- v.read(.{ .x = canim.rows.byteX(@intCast(address % 16)) + shift - 3, .y = row_y, .w = 28, .h = 24 }, amount);
- v.unclip();
- for (hits[0..hit_count]) |hit| if (hit.address == address and !contains(box, hit.box.x, hit.box.y)) {
- u.read(.{ .x = hit.box.x, .y = hit.box.y, .w = hit.box.w, .h = hit.box.h }, amount);
- if (hit.box.y > box.y + box.h and hit.box.y < 796) {
- u.route(&.{ .{ hit.box.x, hit.box.y + hit.box.h }, .{ 1616, hit.box.y + hit.box.h }, .{ 1616, box.y + box.h } }, ui.theme.mark(.read).solid, .{ .width = 2, .head = null, .progress = amount });
- } else if (hit.box.y > box.y + box.h) {
- const lane: f32 = if (hit.box.x < 1100) 16 else 1112;
- u.route(&.{ .{ hit.box.x, hit.box.y + hit.box.h }, .{ lane, hit.box.y + hit.box.h }, .{ lane, 804 }, .{ box.x + 176, 804 }, .{ box.x + 176, box.y + box.h } }, ui.theme.mark(.read).solid, .{ .width = 2, .head = null, .progress = amount });
+ for (s.lenses[0..s.lens_count], 0..) |lens, k| {
+ const box: Box = .{ .x = overlay.x, .y = overlay.y + @as(f32, @floatFromInt(k)) * 204 - s.lens_scroll + (if (k + 1 == s.lens_count) 8 * (1 - amount) else 0), .w = overlay.w, .h = 188 };
+ lens_boxes[k] = box;
+ drawn_lenses = k + 1;
+ current_lens = @intCast(k);
+ const v = u.moved(box.x, box.y);
+ v.fill(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }, ui.theme.color.lift);
+ _ = v.panel(box.w, box.h, v.print("lens {d}", .{k + 1}), .{});
+ _ = v.address(90, 21, lens.address, .{ .ink = ui.rgb(canim.rows.ink(canim.rows.regionOf(moment.?, lens.address))) });
+ button(v, box.w - 40, -2, .{ .kind = .close_lens, .address = k }, "Close lens and descendants", true, false);
+ v.clip(.{ .x = 2, .y = 30, .w = box.w - 4, .h = box.h - 32 });
+ if (lens.cycle) {
+ v.text(.sans_medium, 20, 16, 65, "Cycle · this address is already an ancestor", ui.theme.mark(.current).solid);
} else {
- const lane: f32 = if (hit.box.x >= 1628) 2228 else 1616;
- u.route(&.{ .{ hit.box.x + hit.box.w, hit.box.y + hit.box.h }, .{ lane, hit.box.y + hit.box.h }, .{ lane, box.y - 8 }, .{ box.x + box.w - 24, box.y - 8 }, .{ box.x + box.w - 24, box.y } }, ui.theme.mark(.read).solid, .{ .width = 2, .head = null, .progress = amount });
+ const first = (lens.address & ~@as(u64, 15)) -| 32;
+ var bytes: [80]u8 = undefined;
+ var known: [80]bool = @splat(false);
+ moment.?.read(first, &bytes, &known) catch {};
+ if (std.mem.indexOfScalar(bool, &known, true) == null) {
+ v.text(.sans, 18, 16, 62, if (s.following and s.status == .stopped) "Unreadable pointer · no bytes captured" else "Uncaptured at this recorded stop", ink.dim);
+ } else for (0..5) |i| memoryRow(v, moment.?, first +| i * 16, 34 + @as(f32, @floatFromInt(i)) * 24, box.w - 12, false, null, .none, null);
}
- break;
- };
+ v.unclip();
+ current_lens = null;
+ const from = if (k > 0) lens_boxes[k - 1] else lens.origin;
+ const lane = overlay.x + 8;
+ u.route(&.{ .{ from.x + @min(from.w, 40), from.y + from.h }, .{ lane, from.y + from.h + 8 }, .{ lane, box.y - 8 }, .{ box.x + 40, box.y } }, ui.theme.mark(.read).solid, .{ .width = 2, .head = .{ 6, 6 }, .progress = amount });
+ }
+ ui.bound = previous_bound;
+ u.unclip();
+ }
+ if (s.segments and moment != null) {
+ const box: Box = .{ .x = 24, .y = 112, .w = geometry.w - 48, .h = geometry.h - 160 };
+ const v = u.moved(box.x, box.y);
+ v.fill(.{ .x = 0, .y = 0, .w = box.w, .h = box.h }, ui.theme.color.lift);
+ _ = v.panel(box.w, box.h, v.print("segments → {s}", .{@tagName(s.focus)}), .{ .focus = true });
+ v.text(.mono, 19, 12, 53, v.print("/ {s}▏", .{s.segment_query[0..s.segment_len]}), ink.primary);
+ v.text(.sans, 15, 12, 76, "Enter opens · Esc closes · type to search", ink.dim);
+ segment_hit_count = 0;
+ segment_total = 0;
+ const maps = moment.?.mappings(u.f.scratch) catch &.{};
+ v.clip(.{ .x = 2, .y = 64, .w = box.w - 4, .h = box.h - 66 });
+ for (maps) |map| {
+ var buf: [4096]u8 = undefined;
+ var path: []const u8 = "";
+ _ = moment.?.mapping(map.addr, &path, &buf) catch null;
+ const title = v.print("{s} 0x{x}–0x{x} {d} KiB {c}{c}{c}", .{ if (path.len == 0) "[anonymous]" else path, map.addr, map.addr +| map.len, map.len / 1024, @as(u8, if (map.prot & 1 != 0) 'r' else '-'), @as(u8, if (map.prot & 2 != 0) 'w' else '-'), @as(u8, if (map.prot & 4 != 0) 'x' else '-') });
+ if (std.ascii.findIgnoreCase(title, s.segment_query[0..s.segment_len]) == null) continue;
+ const row = segment_total;
+ segment_total += 1;
+ if (row < s.segment_row) continue;
+ const y = 90 + @as(f32, @floatFromInt(row - s.segment_row)) * 78;
+ if (y + 74 > box.h or segment_hit_count == segment_hits.len) continue;
+ if (row == s.segment_row) v.fill(.{ .x = 2, .y = y, .w = box.w - 4, .h = 76 }, ui.theme.color.raised);
+ v.text(.mono, 15, 12, y + 18, v.print("{x}–{x}", .{ map.addr, map.addr +| map.len }), ink.primary);
+ v.text(.mono, 15, 12, y + 40, v.print("{c}{c}{c} · {d} KiB", .{ @as(u8, if (map.prot & 1 != 0) 'r' else '-'), @as(u8, if (map.prot & 2 != 0) 'w' else '-'), @as(u8, if (map.prot & 4 != 0) 'x' else '-'), map.len / 1024 }), ink.primary);
+ v.text(.sans, 15, 12, y + 62, canim.rows.fitted(v, if (path.len == 0) "[anonymous]" else path, box.w - 24), ink.dim);
+ segment_hits[segment_hit_count] = .{ .box = .{ .x = box.x, .y = box.y + y, .w = box.w, .h = 76 }, .address = map.addr };
+ segment_hit_count += 1;
+ }
+ if (segment_total == 0) v.text(.sans, 20, 12, 90, "No matching mappings", ink.dim);
+ v.unclip();
}
if (s.help) {
- const v = u.moved(690, 190);
- v.fill(.{ .x = 0, .y = 0, .w = 860, .h = 480 }, ui.theme.color.lift);
- _ = v.panel(860, 480, "Vim keys / debugger", .{ .focus = true });
- const lines = [_][]const u8{ "s single machine instruction n next source line", "c continue Esc / Ctrl-c pause", "j / k scroll h / l source columns gg / G ends", "Ctrl-d / u half page Ctrl-w h/j/k/l focus pane", "Ctrl-o / i address history Mouse4 / 5 back / forward", "[ / ] recorded stops Shift-f live stop f follow pane", "v source columns m minimap a operand annotations", "b breakpoint at PC z address lens Esc close lens", "Click address: lens Right-click: code / telescope / hex", ": commands goto code|stack|memory ADDRESS", "break FUNCTION break *ADDRESS clear ID signal 0" };
- for (lines, 0..) |line, i| v.text(.mono, 18, 22, 64 + @as(f32, @floatFromInt(i)) * 36, line, ink.primary);
+ const w = @min(860, geometry.w - 48);
+ const v = u.moved((geometry.w - w) / 2, 112);
+ v.fill(.{ .x = 0, .y = 0, .w = w, .h = @min(560, geometry.h - 160) }, ui.theme.color.lift);
+ _ = v.panel(w, @min(560, geometry.h - 160), "Keys · Esc closes", .{ .focus = true });
+ v.clip(.{ .x = 0, .y = 32, .w = w, .h = @max(0, geometry.h - 192) });
+ const lines = [_][]const u8{ "s instruction · n source · c run", "Esc / Ctrl-c pause", "Ctrl +/− font · Ctrl-0 reset", "j/k scroll · PgUp/PgDn page", "h/l source · Shift-h/l horizontal", "Ctrl-d/u half page · Tab focus", "Ctrl-o/i address history", "[ / ] stops · F live · f follow", "t graph · d unobserved opacity", "p segments · v source · m minimap", "click: lens · right-click: navigate", "z lens · : command · ? help", "Gold current · bright observed", "Branch target: prediction only", "Dim: unknown between live stops" };
+ for (lines, 0..) |line, i| v.text(.mono, 16, 12, 58 + @as(f32, @floatFromInt(i)) * 30, canim.rows.fitted(v, line, w - 24), ink.primary);
+ v.unclip();
}
if (s.command_open) {
- u.fill(.{ .x = 24, .y = 1218, .w = 2192, .h = 40 }, ui.theme.color.lift);
- u.text(.mono, 22, 36, 1247, u.print(":{s}▏", .{s.command_text[0..s.command_len]}), ink.primary);
+ u.fill(.{ .x = 24, .y = geometry.h - 42, .w = geometry.w - 48, .h = 40 }, ui.theme.color.lift);
+ u.text(.mono, 22, 36, geometry.h - 11, u.print(":{s}▏", .{s.command_text[0..s.command_len]}), ink.primary);
}
if (tooltip) |b| {
- u.fill(.{ .x = 596, .y = 42, .w = 1020, .h = 32 }, ui.theme.color.page);
- u.text(.sans_medium, 18, 608, 64, u.print("{s}{s}", .{ b.label, if (b.enabled) "" else " · unavailable in this state" }), if (b.enabled) ink.primary else ink.dim);
+ u.fill(.{ .x = 24, .y = geometry.h - 40, .w = geometry.w - 48, .h = 32 }, ui.theme.color.page);
+ u.text(.sans_medium, 18, 36, geometry.h - 17, u.print("{s}{s}", .{ b.label, if (b.enabled) "" else " · unavailable in this state" }), if (b.enabled) ink.primary else ink.dim);
}
}
@@ -1038,6 +1406,12 @@ fn selected(ss: *Session, t: *zt.Trace, m: zt.store.Moment, regs: zt.Regs, tid:
ss.code_start -|= insn.back;
}
}
+ if (ss.shown) |old| if (old != m.index) {
+ const prior = t.moment(old) catch m;
+ if ((prior.line(ss.tid) catch null)) |line| if (sources.get(gpa, io, prior, line.file)) |file| {
+ if (std.mem.endsWith(u8, file.path, ".js")) ss.origin_line = line;
+ };
+ };
ss.shown = m.index;
ss.tid = tid;
ss.changed_at = now;
diff --git a/gui/targets/jit.js b/gui/targets/jit.js
index 57a1218..b0ea360 100644
--- a/gui/targets/jit.js
+++ b/gui/targets/jit.js
@@ -1,16 +1,13 @@
-// Print the optimized function's machine code, then let the native debugger
-// install a breakpoint before the next invocation. No V8 inspector required.
-function jitWork(n) {
- let sum = 0;
- for (let i = 0; i < n; i++) {
- sum = (sum + (i ^ n)) | 0;
- }
+// Ordinary warmup: V8 chooses its tiers and schedules optimization itself.
+function jitWork(object) {
+ let sum = object.value;
+ for (let i = 0; i < 1000; i++) sum = (sum + i) | 0;
return sum;
}
-%PrepareFunctionForOptimization(jitWork);
-jitWork(10);
-jitWork(20);
-%OptimizeFunctionOnNextCall(jitWork);
-jitWork(30);
-%SystemBreak();
-print(jitWork(10000));
+const same = {value: 7};
+let total = 0;
+for (let i = 0; i < 200000; i++) total = (total + jitWork(same)) | 0;
+print('warm', total, jitWork(same));
+// A second shape invalidates the optimized property access's map guard.
+print('mismatch', jitWork({extra: 1, value: 9}));
+print('fallback', jitWork(same));
diff --git a/gui/targets/segments.c b/gui/targets/segments.c
new file mode 100644
index 0000000..0fdc25f
--- /dev/null
+++ b/gui/targets/segments.c
@@ -0,0 +1,25 @@
+#define _GNU_SOURCE
+#include <assert.h>
+#include <stdint.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
+struct node { struct node *next; uint64_t value; };
+struct node head, middle, tail;
+volatile uint64_t counter;
+__attribute__((noinline)) void checkpoint(void) { __asm__ volatile("" ::: "memory"); }
+
+int main(void) {
+ const size_t size = (size_t)1 << 32;
+ int fd = memfd_create("ztrace-test-segment", 0);
+ assert(fd >= 0 && ftruncate(fd, size) == 0);
+ unsigned char *bytes = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+ assert(bytes != MAP_FAILED);
+ close(fd);
+ bytes[0] = 'A';
+ bytes[size - 1] = 'Z';
+ head = (struct node){&middle, 1};
+ middle = (struct node){&tail, 2};
+ tail = (struct node){&head, 3};
+ for (;;) { ++counter; checkpoint(); }
+}
diff --git a/gui/test/adaptive.py b/gui/test/adaptive.py
new file mode 100644
index 0000000..89ce49a
--- /dev/null
+++ b/gui/test/adaptive.py
@@ -0,0 +1,114 @@
+#!/usr/bin/env python3
+"""Real GUI checks for geometry, large mappings, pointer hit targets and repeated live stops."""
+import argparse
+from pathlib import Path
+import re
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[2]
+p = argparse.ArgumentParser(description=__doc__)
+p.add_argument('--gui', type=Path, default=ROOT / 'gui/zig-out/bin/ztrace-gui')
+a = p.parse_args()
+a.gui = a.gui.resolve()
+with tempfile.TemporaryDirectory(prefix='ztrace-adaptive-') as directory:
+ out = Path(directory)
+ target = out / 'segments'
+ subprocess.run(['cc', '-g', '-O0', '-no-pie', str(ROOT / 'gui/targets/segments.c'), '-o', str(target)], check=True)
+ symbols = {name: int(address, 16) for address, name in re.findall(r'^([0-9a-f]+) \w (\w+)$', subprocess.check_output(['nm', '-n', str(target)], text=True), re.M)}
+ for size in ('2240x1260', '1440x900', '800x700'):
+ for zoom in (60, 100, 200):
+ script = out / 'check.script'
+ script.write_text(f'''console launch {target}
+await stops 1
+console break checkpoint
+console continue
+await execution 1
+console goto memory {hex(symbols['counter'])}
+frames 40
+key c
+await execution 2
+frames 40
+expect nav[2].place.follow false
+# An inspection reply doesn't resume execution or unpin a pane.
+expect execution 2
+# Font controls, actual key routing and bounds.
+console set zoom {zoom}
+hold left_ctrl
+key equals
+release left_ctrl
+expect zoom {min(200, zoom + 10)}
+hold left_ctrl
+key minus
+release left_ctrl
+expect zoom {max(60, min(200, zoom + 10) - 10)}
+console set zoom {zoom}
+frames 10
+# All four GiB are navigable. A single row still changes the address at the end.
+key p
+type ztrace-test-segment
+key return
+frames 20
+key g
+key g
+expect nav[2].place.row 0
+hold left_shift
+key g
+release left_shift
+print nav[2].place.row
+key k
+print nav[2].place.row
+# The same selector routes into code and preserves its jump history.
+console set focus code
+key p
+type ztrace-test-segment
+key return
+expect nav[0].place.follow false
+hold left_ctrl
+key o
+release left_ctrl
+expect nav[0].place.follow true
+key t
+expect graph true
+key l
+expect horizontal[0] 48
+key t
+key d
+expect dim 100
+# Historical inspection does not fetch memory or execute the target.
+key left_bracket
+expect following false
+console goto memory 0xffffffffffff0000
+frames 20
+expect execution 2
+key p
+type no-such-segment
+key escape
+expect segments false
+# Lens closure and a rendered header hit remain accurate at every zoom.
+console set pc {symbols['head']}
+key z
+expect lens_count 1
+frames 30
+screenshot {out / 'lens.png'}
+key escape
+expect lens_count 0
+hold left_ctrl
+key 0
+release left_ctrl
+expect zoom 100
+expect-no-log CommandFailed
+expect-no-log InvalidCount
+''')
+ run = subprocess.Popen([str(a.gui), '--headless', '--fresh', '--state', str(out / f'{size}-{zoom}.state'), '--size', size, '--script', str(script)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ stdout, stderr = run.communicate(timeout=90)
+ assert run.returncode == 0, (size, zoom, stdout, stderr)
+ rows = [float(v) for v in re.findall(r'nav\[2\].place.row = ([\d.]+)', stderr)]
+ assert len(rows) == 2 and rows[0] > 268000000 and rows[0] - rows[1] == 1, rows
+ recordings = list(Path('/tmp').glob(f'ztrace-gui-{run.pid}-*.ztrace'))
+ assert len(recordings) == 1
+ dump = subprocess.check_output([str(a.gui.parent / 'ztrace'), 'dump', str(recordings[0])], text=True)
+ writes = [(int(addr, 16), int(length, 16)) for addr, length in re.findall(r'mem_write\s+.*?a=([0-9a-f]+) ([0-9a-f]+)', dump)]
+ assert sum(addr <= symbols['counter'] < addr + length for addr, length in writes) >= 2, 'same-PC live stop did not refresh pinned bytes'
+ recordings[0].unlink()
+ print(f'{size} at {zoom}%: live refresh, mapping ends, history, graph, lenses and zoom passed')
diff --git a/gui/test/basic.script b/gui/test/basic.script
index cf23a47..be2034f 100644
--- a/gui/test/basic.script
+++ b/gui/test/basic.script
@@ -46,16 +46,16 @@ expect nav[2].place.row 0
hold left_ctrl
key d
release left_ctrl
-expect nav[2].place.row 7.5
+expect nav[2].place.row 7
key f
expect nav[2].place.follow true
# Rendered code addresses route to disassembly, including source-aligned rows.
-console mouse-button 3 650 122
+console mouse-button 3 650 204
expect focus code
expect nav[0].place.follow false
-console mouse-button 4 650 122
+console mouse-button 4 650 204
expect nav[0].place.follow true
-console mouse-button 5 650 122
+console mouse-button 5 650 204
expect nav[0].place.follow false
key f
# Stack storage addresses route to telescope.
@@ -77,11 +77,27 @@ frames 6
screenshot {LENS}
frames 30
screenshot {LENS_SETTLED}
-expect-different-screenshot {LENS} {LENS_SETTLED} 1090 580 1120 230
+expect-different-screenshot {LENS} {LENS_SETTLED} 1090 130 1120 230
+# Header addresses use the same pointer hits as rows. Keep ancestors, mark cycles,
+# replace descendants from a parent, and close one branch at a time.
+click 1230 161
+expect lens_count 2
+expect lenses[1].cycle true
+frames 30
+click 1230 365
+expect lens_count 3
+frames 30
+click 1230 161
+expect lens_count 2
+frames 30
+click 2180 350
+expect lens_count 1
+click 2180 146
+expect lens_count 0
key escape
expect lens false
# Opening from a call-frame address keeps its origin visible.
-click 1700 726
+click 1700 750
expect lens true
frames 30
screenshot {FRAME_LENS}
diff --git a/gui/test/inspection.py b/gui/test/inspection.py
index 368b6aa..bdb90da 100644
--- a/gui/test/inspection.py
+++ b/gui/test/inspection.py
@@ -1,92 +1,58 @@
#!/usr/bin/env python3
-"""Real-target checks for read-only inspection and explicit GDB JIT ELF import."""
+"""Real-target checks for bounded read-only inspection, source maps, and natural deoptimization."""
import argparse
-import json
-import os
from pathlib import Path
-import re
-import select
import subprocess
+import sys
import tempfile
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'bench'))
+from control import ROOT, Controller, natural, deoptimization
-ROOT = Path(__file__).resolve().parents[2]
-p = argparse.ArgumentParser(description=__doc__)
-p.add_argument('--ztrace', type=Path, default=ROOT / 'gui/zig-out/bin/ztrace')
-p.add_argument('--d8', type=Path)
-a = p.parse_args()
-a.ztrace = a.ztrace.resolve()
-with tempfile.TemporaryDirectory(prefix='ztrace-inspect-') as directory:
- work = Path(directory)
- small = work / 'loop'
- subprocess.run(['cc', '-g', '-O0', str(ROOT / 'gui/targets/loop.c'), '-o', str(small)], check=True)
- programs = [('c', [str(small)])]
- js = work / f'gui-inspect-{os.getpid()}.js'
- if a.d8:
- js.write_bytes((ROOT / 'gui/targets/jit.js').read_bytes())
- programs.append(('v8', [str(a.d8.resolve()), '--allow-natives-syntax', '--no-concurrent-recompilation',
- '--no-maglev', '--gdbjit', '--gdbjit-dump', '--gdbjit-dump-filter=jitWork',
- '--print-opt-code', '--print-opt-code-filter=jitWork', js.name]))
- for name, argv in programs:
- recording = work / (name + '.ztrace')
- with (work / (name + '.log')).open('w+') as log:
- target = subprocess.Popen([str(a.ztrace), 'serve', str(recording), '--', *argv],
- cwd=work, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log, bufsize=0)
- pending = b''
- def read():
- global pending
- while b'\n' not in pending:
- assert select.select([target.stdout], [], [], 30)[0], 'controller timeout'
- data = os.read(target.stdout.fileno(), 4096)
- assert data, 'controller exited'
- pending += data
- line, pending = pending.split(b'\n', 1)
- return json.loads(line)
- def command(text, status='stopped'):
- target.stdin.write((text + '\n').encode())
- while True:
- answer = read()
- if answer['status'] != 'running':
- assert answer['status'] == status, answer
- return answer
- elf = None
+def inspect(c, stopped):
+ for kind, count in [('code', 128), ('memory', 256)]:
+ assert c.command(f'inspect {kind} {stopped["pc"]} {count}')['pc'] == stopped['pc']
+ for request in ['inspect code 0 0', 'inspect code 0 257', 'inspect memory 0 4097', 'inspect cheese 0 8', 'source-map /tmp']:
+ assert c.command(request, 'failed')['pc'] == stopped['pc']
+ assert c.command('inspect memory 0 16')['pc'] == stopped['pc']
+ assert 'State:\tt' in Path(f'/proc/{stopped["pid"]}/status').read_text()
+ assert c.command('stepi')['pc'] != stopped['pc']
+
+
+def main():
+ p = argparse.ArgumentParser(description=__doc__)
+ p.add_argument('--ztrace', type=Path, default=ROOT / 'gui/zig-out/bin/ztrace')
+ p.add_argument('--d8', type=Path)
+ p.add_argument('--source', type=Path, default=Path('/tmp/computeranim-v8-source'))
+ a = p.parse_args()
+ with tempfile.TemporaryDirectory(prefix='ztrace-inspect-') as directory:
+ out = Path(directory)
+ small = out / 'loop'
+ subprocess.run(['cc', '-g', '-O0', str(ROOT / 'gui/targets/loop.c'), '-o', str(small)], check=True)
+ c = Controller(a.ztrace, out, 'c', [str(small)])
+ try:
+ c.read()
+ c.command('break work')
+ stopped = c.command('continue')
+ inspect(c, stopped)
+ c.command('source-map ' + str(ROOT / 'gui/targets') + ' /mapped-source')
+ assert '/mapped-source/loop.c:' in c.show()
+ c.command('source-map ' + str(ROOT / 'gui/targets') + ' ' + str(ROOT / 'gui/targets'))
+ assert str(ROOT / 'gui/targets/loop.c') in c.show()
+ print('C: bounded inspection preserved PC; source prefix replacement and stepping passed')
+ finally:
+ c.close()
+ if a.d8:
+ c, js, elf, bounds, instructions, stopped = natural(a.ztrace, a.d8, out, a.source)
try:
- assert read()['status'] == 'stopped'
- if name == 'c':
- command('break work')
- stopped = command('continue')
- else:
- command('continue')
- log.seek(0)
- assembly = log.read()
- address = int(re.search(r'^(0x[0-9a-f]+)\s+[0-9a-f]+\s+[0-9a-f]+\s+addl r8,r11', assembly, re.M)[1], 16)
- command('signal 0')
- command('break *' + hex(address))
- stopped = command('continue')
- assert stopped['pc'] == address
- elf, = Path('/tmp').glob('elfdumpjitWork ' + js.name + ':*.o')
- loaded = command('symbols ' + str(elf))
- assert loaded['pc'] == stopped['pc'], loaded
- show = subprocess.check_output([str(a.ztrace), 'show', str(recording), '-1'], text=True)
- assert str(js) + ':6:' in show, show[:2000]
- assert '(gui-inspect-' in show, 'instruction source metadata missing'
- for kind, count in [('code', 128), ('memory', 256)]:
- seen = command(f'inspect {kind} {stopped["pc"]} {count}')
- assert seen['pc'] == stopped['pc'], seen
- for request in ['inspect code 0 0', 'inspect code 0 257', 'inspect memory 0 4097', 'inspect cheese 0 8']:
- failed = command(request, 'failed')
- assert failed['pc'] == stopped['pc']
- seen = command('inspect memory 0 16')
- assert seen['pc'] == stopped['pc']
- assert 'State:\tt' in Path(f'/proc/{stopped["pid"]}/status').read_text()
- moved = command('stepi')
- assert moved['pc'] != stopped['pc']
- print(name + ': inspection preserved PC; bounds rejected; stepping still works' + ('; real JIT source line recorded' if name == 'v8' else ''))
+ inspect(c, stopped)
+ result = deoptimization(c, bounds, instructions, a.source)
+ assert result['reason'] == 'wrong map'
+ print('V8: natural optimization, generated exit, native source, wrong map and ' + result['fallback_tier'] + ' dispatch verified')
finally:
- if target.poll() is None:
- target.stdin.write(b'quit\n')
- target.wait(timeout=30)
- target.stdin.close()
- target.stdout.close()
- if elf is not None:
- elf.unlink(missing_ok=True)
+ c.close()
+ elf.unlink(missing_ok=True)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/src/cli/dbg.zig b/src/cli/dbg.zig
index c60bff2..77ca40a 100644
--- a/src/cli/dbg.zig
+++ b/src/cli/dbg.zig
@@ -174,6 +174,12 @@ const Session = struct {
s.view = null;
_ = try if (is(cmd, "step", "s")) s.d.step() else if (is(cmd, "stepi", "si")) s.d.stepi() else s.d.cont();
try s.showStop();
+ } else if (std.mem.eql(u8, cmd, "source-map")) {
+ const from = arg orelse return error.MissingArgument;
+ const to = words.next() orelse return error.MissingArgument;
+ if (words.next() != null) return error.InvalidSourceMap;
+ try s.d.mapSource(from, to);
+ try s.rec.flush();
} else if (is(cmd, "break", "b")) {
const where = arg orelse return error.MissingArgument;
if (std.mem.startsWith(u8, where, "usdt:")) {
diff --git a/src/cli/serve.zig b/src/cli/serve.zig
index 47ec1ed..23d307b 100644
--- a/src/cli/serve.zig
+++ b/src/cli/serve.zig
@@ -29,7 +29,7 @@ const Server = struct {
}
fn reply(s: *Server, d: *zt.Debugger, status: zt.control.Status, reason: []const u8, elapsed: u64) !void {
- try zt.control.send(s.writer, .{ .status = status, .pid = d.proc.pid, .tid = @intCast(d.proc.tid), .moments = s.rec.moments, .pc = d.regs.rip, .reason = reason, .elapsed_ns = elapsed });
+ try zt.control.send(s.writer, .{ .status = status, .pid = d.proc.pid, .tid = @intCast(d.proc.tid), .moments = s.rec.moments, .pc = d.regs.rip, .reason = reason, .elapsed_ns = elapsed, .capture_ns = if (status == .running) 0 else d.capture_ns });
}
fn waiting(ctx: *anyopaque, d: *zt.Debugger) !void {
@@ -94,13 +94,16 @@ pub fn run(init: std.process.Init, args: []const [:0]const u8) !void {
const cmd = words.next() orelse continue;
if (std.mem.eql(u8, cmd, "quit")) break;
const started = std.Io.Clock.awake.now(init.io);
+ d.capture_ns = 0;
var reason_buf: [128]u8 = undefined;
const reason = execute(&d, &server, cmd, std.mem.trim(u8, words.rest(), " \t\r"), &reason_buf) catch |err| {
try server.reply(&d, if (d.done) .exited else .failed, @errorName(err), 0);
continue;
};
- if ((std.mem.eql(u8, cmd, "inspect") or std.mem.eql(u8, cmd, "symbols")) and rec.delta.items.len > 0) try rec.commit();
+ if ((std.mem.eql(u8, cmd, "inspect") or std.mem.eql(u8, cmd, "symbols") or std.mem.eql(u8, cmd, "source-map")) and rec.delta.items.len > 0) try rec.commit();
+ const flush_started = std.Io.Clock.awake.now(init.io);
try rec.flush();
+ if (d.capture_ns != 0) d.capture_ns += @intCast(flush_started.durationTo(std.Io.Clock.awake.now(init.io)).toNanoseconds());
const elapsed: u64 = @intCast(started.durationTo(std.Io.Clock.awake.now(init.io)).toNanoseconds());
try server.reply(&d, if (d.done) .exited else .stopped, reason, elapsed);
}
@@ -116,6 +119,13 @@ fn execute(d: *zt.Debugger, s: *Server, cmd: []const u8, arg: []const u8, buf: [
const sig = try std.fmt.parseInt(u32, arg, 0);
if (sig > 64) return error.InvalidSignal;
d.proc.resume_signal = sig;
+ } else if (std.mem.eql(u8, cmd, "source-map")) {
+ var words = std.mem.tokenizeScalar(u8, arg, ' ');
+ const from = words.next() orelse return error.MissingPrefix;
+ const to = words.next() orelse return error.MissingPath;
+ if (words.next() != null) return error.InvalidSourceMap;
+ try d.mapSource(from, to);
+ return "source prefix mapped; target unchanged";
} else if (std.mem.eql(u8, cmd, "symbols")) {
if (arg.len == 0) return error.MissingPath;
try d.loadJit(arg);
diff --git a/src/trace/Debugger.zig b/src/trace/Debugger.zig
index 55f9cd1..08d3b30 100644
--- a/src/trace/Debugger.zig
+++ b/src/trace/Debugger.zig
@@ -77,6 +77,8 @@ asan_shadow: ?u64 = null,
/// glibc's heap, recorded at every stop as `heap.zig` reads it (`--heap`): null for not at all.
heap: ?@import("heap.zig").Watch = null,
breakpoints: std.ArrayList(Breakpoint) = .empty,
+/// Stop-state capture only; excludes waiting for the target and flushing a recorder.
+capture_ns: u64 = 0,
/// The current thread's registers at its last stop.
regs: Regs = .{},
/// The target has exited.
@@ -534,9 +536,11 @@ fn emit(d: *Debugger, ev: Event, payload: []const u8) !void {
/// the watched memory that changed, then the stop.
fn report(d: *Debugger, stop: Stop) !Stop {
if (d.sink == null) return stop;
+ const started = std.Io.Clock.awake.now(d.syms.io);
+ defer d.capture_ns = @intCast(started.durationTo(std.Io.Clock.awake.now(d.syms.io)).toNanoseconds());
if (!d.done) {
- // Code loaded or JIT-compiled while running without syscall stops.
- if (d.syms.mappingAt(d.regs.rip) == null) try d.refreshMaps();
+ // Every stop owns its mapping snapshot, including data mapped while PC stayed in known code.
+ try d.refreshMaps();
try d.emitLine();
if (d.asan and d.asan_shadow == null) try d.findShadow();
// With the 128 bytes under the stack pointer: the red zone, a leaf's locals.
@@ -653,6 +657,14 @@ pub fn inspectCode(d: *Debugger, addr: u64, count: usize) !void {
}
}
+pub fn mapSource(d: *Debugger, from: []const u8, to: []const u8) !void {
+ try d.syms.mapSource(from, to);
+ d.file_ids.clearRetainingCapacity();
+ d.code_len.clearRetainingCapacity();
+ try d.emitLine();
+ try d.emitCode();
+}
+
pub fn loadJit(d: *Debugger, path: []const u8) !void {
try d.refreshMaps();
try d.syms.loadJit(path);
@@ -983,11 +995,7 @@ pub fn decode(d: *Debugger, nr: u16) ![]const u8 {
/// The string id of a line's file: its path, recorded the first time.
fn fileId(d: *Debugger, l: Symbols.Line) !u64 {
if (d.file_ids.get(l.key)) |id| return id;
- // As the compilation saw it: its directory, the file's, its name, each
- // relative to the one before (glibc's: /usr/src/debug/glibc/glibc/csu/../sysdeps/...).
- var cwd: [4096]u8 = undefined;
- const cwd_len = if (std.fs.path.isAbsolute(l.base) or std.fs.path.isAbsolute(l.dir) or std.fs.path.isAbsolute(l.name)) 0 else try std.Io.Dir.cwd().realPath(d.syms.io, &cwd);
- const path = try std.fs.path.resolveAlloc(d.gpa, &.{ cwd[0..cwd_len], l.base, l.dir, l.name });
+ const path = try d.syms.sourcePath(l);
const named = d.files.getOrPut(d.gpa, path) catch |err| {
d.gpa.free(path);
return err;
diff --git a/src/trace/Symbols.zig b/src/trace/Symbols.zig
index f7e53ef..a7df35e 100644
--- a/src/trace/Symbols.zig
+++ b/src/trace/Symbols.zig
@@ -11,6 +11,7 @@ const Dwarf = std.debug.Dwarf;
gpa: std.mem.Allocator,
io: std.Io,
maps: Maps = .{},
+source_maps: std.ArrayList(SourceMap) = .empty,
modules: std.ArrayList(Module) = .empty,
/// The line-table row `lineAt` answered from last, as target addresses.
row: struct { start: u64 = 0, len: u64 = 0, line: ?Line = null } = .{},
@@ -23,6 +24,8 @@ demangle: ?*const fn (name: []const u8, buf: []u8) ?[]const u8 = null,
/// function that has several (`open`, not `__open64`).
imported: std.StringHashMapUnmanaged(void) = .empty,
+pub const SourceMap = struct { from: []const u8, to: []const u8 };
+
pub const Mapping = struct {
start: u64,
end: u64,
@@ -212,11 +215,67 @@ fn deinitModule(m: *Module, gpa: std.mem.Allocator) void {
gpa.free(m.path);
}
+/// Map a build-machine source prefix to its local checkout. Longest prefix wins.
+pub fn mapSource(s: *Symbols, from: []const u8, to: []const u8) !void {
+ if (from.len == 0 or to.len == 0) return error.InvalidSourceMap;
+ var cwd: [4096]u8 = undefined;
+ const n = if (std.fs.path.isAbsolute(from) and std.fs.path.isAbsolute(to)) 0 else try std.Io.Dir.cwd().realPath(s.io, &cwd);
+ const a = try std.fs.path.resolveAlloc(s.gpa, &.{ cwd[0..n], from });
+ errdefer s.gpa.free(a);
+ const b = try std.fs.path.resolveAlloc(s.gpa, &.{ cwd[0..n], to });
+ errdefer s.gpa.free(b);
+ for (s.source_maps.items) |*map| if (std.mem.eql(u8, map.from, a)) {
+ s.gpa.free(map.from);
+ s.gpa.free(map.to);
+ map.* = .{ .from = a, .to = b };
+ return;
+ };
+ try s.source_maps.append(s.gpa, .{ .from = a, .to = b });
+}
+
+/// Owned canonical source path, shared by debugger clients and recorded metadata.
+pub fn sourcePath(s: *Symbols, l: Line) ![]u8 {
+ var cwd: [4096]u8 = undefined;
+ const n = if (std.fs.path.isAbsolute(l.base) or std.fs.path.isAbsolute(l.dir) or std.fs.path.isAbsolute(l.name)) 0 else try std.Io.Dir.cwd().realPath(s.io, &cwd);
+ const path = try std.fs.path.resolveAlloc(s.gpa, &.{ cwd[0..n], l.base, l.dir, l.name });
+ errdefer s.gpa.free(path);
+ var best: ?SourceMap = null;
+ for (s.source_maps.items) |map| {
+ if (!std.mem.startsWith(u8, path, map.from)) continue;
+ if (path.len > map.from.len and path[map.from.len] != '/' and !std.mem.eql(u8, map.from, "/")) continue;
+ if (best == null or map.from.len > best.?.from.len) best = map;
+ }
+ if (best) |map| {
+ const result = try std.fs.path.join(s.gpa, &.{ map.to, std.mem.trimStart(u8, path[map.from.len..], "/") });
+ s.gpa.free(path);
+ return result;
+ }
+ return path;
+}
+
+test "source prefixes respect boundaries, normalize paths and choose the longest" {
+ var s: Symbols = .{ .gpa = std.testing.allocator, .io = undefined };
+ defer s.deinit();
+ try s.mapSource("/remote", "/local");
+ try s.mapSource("/remote/v8", "/checkout");
+ const a = try s.sourcePath(.{ .key = 0, .base = "/remote/v8/out/debug", .dir = "../../src", .name = "deoptimizer.cc", .line = 1, .column = 0 });
+ defer s.gpa.free(a);
+ try std.testing.expectEqualStrings("/checkout/src/deoptimizer.cc", a);
+ const b = try s.sourcePath(.{ .key = 0, .dir = "/remote-other", .name = "a.cc", .line = 1, .column = 0 });
+ defer s.gpa.free(b);
+ try std.testing.expectEqualStrings("/remote-other/a.cc", b);
+}
+
pub fn deinit(s: *Symbols) void {
for (s.modules.items) |*m| deinitModule(m, s.gpa);
s.modules.deinit(s.gpa);
s.imported.deinit(s.gpa);
s.free(s.maps);
+ for (s.source_maps.items) |map| {
+ s.gpa.free(map.from);
+ s.gpa.free(map.to);
+ }
+ s.source_maps.deinit(s.gpa);
}
/// Reads the process's mappings again and loads the modules that are new.
diff --git a/src/trace/control.zig b/src/trace/control.zig
index 1bfad4c..c0a7906 100644
--- a/src/trace/control.zig
+++ b/src/trace/control.zig
@@ -9,6 +9,7 @@ pub const Reply = struct {
moments: u64,
pc: u64,
elapsed_ns: u64 = 0,
+ capture_ns: u64 = 0,
reason: []const u8 = "",
};