diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-13 01:24:16 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-13 01:34:46 -0300 |
| commit | 5a40dca5adb6e9e650f55f3ec6f254a13bf50493 (patch) | |
| tree | 5fdffebd75ed3fbac1eae5dec0a3f2d491450342 /gui | |
| parent | 4b4113a0217ee27c78e7efddb66ff5a455d49083 (diff) | |
| download | computeranim-5a40dca5adb6e9e650f55f3ec6f254a13bf50493.tar.gz computeranim-5a40dca5adb6e9e650f55f3ec6f254a13bf50493.zip | |
debugger: align source and add rich Vim-style navigation
Diffstat (limited to 'gui')
| -rw-r--r-- | gui/README.md | 86 | ||||
| -rw-r--r-- | gui/bench/RESULTS.md | 88 | ||||
| -rw-r--r-- | gui/bench/redraw.py | 34 | ||||
| -rw-r--r-- | gui/bench/steps.py | 23 | ||||
| -rw-r--r-- | gui/build.zig | 17 | ||||
| -rw-r--r-- | gui/src/Navigation.zig | 56 | ||||
| -rw-r--r-- | gui/src/Sources.zig | 34 | ||||
| -rw-r--r-- | gui/src/app.zig | 977 | ||||
| -rw-r--r-- | gui/targets/jit.js | 4 | ||||
| -rw-r--r-- | gui/test/basic.script | 103 | ||||
| -rw-r--r-- | gui/test/inspection.py | 92 |
11 files changed, 1327 insertions, 187 deletions
diff --git a/gui/README.md b/gui/README.md index 3bd7d3f..20fe292 100644 --- a/gui/README.md +++ b/gui/README.md @@ -5,11 +5,12 @@ A separate native application using **ztrace** for control and recordings and a real Linux x86-64 process, stops at breakpoints, steps, and browses recorded machine state. No gdb subprocess or browser frontend. -The fixed view uses the animation library's instruction cells, operand values, -flag marks, pointer colors, telescope chains, stack roles and frame spans. -The current-instruction marker moves between rows; changed registers and stack -words strike in vermilion, cool, then retain a corner marker. Those changes are -computed from adjacent recorded moments. +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: @@ -22,7 +23,7 @@ zig build run -Doptimize=ReleaseFast -- --fresh ``` The build installs `ztrace` alongside `ztrace-gui`; keep the two together. -Backtick opens the renderer's console: +Colon opens the debugger command bar; backtick opens the renderer's console: ```text launch /absolute/path/to/program arguments @@ -34,15 +35,39 @@ signal 0 interrupt stepi nextline +goto memory 0x12345678 ``` `break` accepts the library's function, file:line and `*address` forms. Its reply -includes the breakpoint ID. F5 toggles continue/pause, F10 steps one instruction, -F11 steps to another source line (one instruction when source is unavailable). -The corresponding buttons work with the mouse. Left/right browse recorded -moments; End returns to the latest stop. Browsing history does not rewind the -process. Continuing returns the view to live state. Source stepping can stay in -a loop on one source line; F5 interrupts it. +includes the breakpoint ID. The icon buttons have hover labels and keys; pane +headers hold history, follow, minimap and interpretation controls. + +| Keys | Action | +| --- | --- | +| `s`, `n` | One 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 | +| `[` / `]`, `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 @@ -93,7 +118,7 @@ For the deterministic JIT fixture: 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. F10 steps through that machine code. Addresses change on each launch. +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. ```sh @@ -122,3 +147,38 @@ 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): + +```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 +``` + +After reaching the generated-code breakpoint, import the emitted object: + +```text +symbols /tmp/elfdumpjitWork jit.js:3:170.o +``` + +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. + +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. + +Read-only capture and JIT source integration checks: + +```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 +``` diff --git a/gui/bench/RESULTS.md b/gui/bench/RESULTS.md index d24659b..89f0d78 100644 --- a/gui/bench/RESULTS.md +++ b/gui/bench/RESULTS.md @@ -1,6 +1,6 @@ # Debug V8 versus a small C target -Measured locally on 2026-11-12, Linux 7.2.11-arch1-1, Intel i7-11700, +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 @@ -13,22 +13,22 @@ Final controller run: python3 gui/bench/steps.py \ --d8 /tmp/computeranim-v8-debug-remote/d8 \ --ztrace zig-out/bin/ztrace \ - --out /tmp/ztrace-step-bench-cleared + --out /tmp/ztrace-step-bench-ui ``` | 1,000 instruction steps | C | Debug V8 / generated JS | | --- | ---: | ---: | -| Capture + flush, median | 35.73 µs | 38.47 µs | -| Capture + flush, p95 | 45.13 µs | 59.18 µs | -| Controller round trip, median | 46.94 µs | 49.53 µs | -| Controller round trip, p95 | 59.23 µs | 73.00 µs | -| Controller round trip, maximum | 310.72 µs | 381.48 µs | -| Launch through first requested breakpoint | 9.50 ms | 901.84 ms | +| 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 earlier 1,000-step run measured -39.09 / 44.42 µs capture medians and 53.69 / 60.57 µs round-trip medians for +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. @@ -42,9 +42,23 @@ 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. -The raw records, logs and JSON results are in `/tmp/ztrace-step-bench-cleared`. +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. +With JIT source information loaded, the final 1,000-step run remained comparable: + +| Source-enabled run | C | Debug V8 / generated JS | +| --- | ---: | ---: | +| 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 | + +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. + ## V8 provenance The user's remote Arch build host (`chaincli-box`) has the existing checkout at @@ -68,10 +82,19 @@ and smoke-tested locally. ## Checks -The GUI's real-target script exercises launch, a named breakpoint, continue, -keyboard and mouse instruction stepping, source stepping, pause during execution, -and browsing history back to live. The core tests additionally check pause -signal suppression and source stepping without line information. +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. + +`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. 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 @@ -86,17 +109,26 @@ 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. -At 1920×1080, an approximate headless redraw measurement was **1.23 ms/frame -for C and 2.41 ms/frame for V8**. This subtracts the median elapsed time of -30-frame runs from 330-frame runs (three repeats each), then divides by 300. -Both opened the corresponding 1,000-step recording. V8 displayed 24 instruction -rows while C displayed 10; 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-results.json`. +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 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. -The final native session was verified with d8 PID 2502490 in Linux tracing-stop -state and recorded RIP `0x7f09921c0196`: breakpoint 2 on `add r8d, r9d`, offset -`0x156` inside TurboFan-generated `jitWork`. It is left open in the GUI. The -recording is `/tmp/ztrace-gui-2502452-357545622054931.ztrace`; the screenshot is -`/tmp/ztrace-v8-live-final.png`. These addresses and PIDs describe this session -only. The complete animation gallery was not re-rendered. +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. diff --git a/gui/bench/redraw.py b/gui/bench/redraw.py new file mode 100644 index 0000000..84c1314 --- /dev/null +++ b/gui/bench/redraw.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Estimate steady GUI redraw cost by subtracting matched short and long runs.""" +import argparse +import json +from pathlib import Path +import statistics +import subprocess +import tempfile +import time + +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') +p.add_argument('--c', type=Path, required=True) +p.add_argument('--v8', type=Path, required=True) +p.add_argument('--out', type=Path, default=Path('/tmp/ztrace-gui-redraw-ui.json')) +a = p.parse_args() +results = {} +with tempfile.TemporaryDirectory(prefix='ztrace-redraw-') as directory: + work = Path(directory) + for name, recording in [('c', a.c), ('v8', a.v8)]: + samples = {30: [], 330: []} + for _ in range(3): + for count in samples: + script = work / 'draw.script' + script.write_text(f'console open {recording.resolve()}\nframes {count}\n') + start = time.perf_counter_ns() + subprocess.run([str(a.gui.resolve()), '--headless', '--fresh', '--state', str(work / 'draw.state'), + '--script', str(script)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, check=True) + samples[count].append((time.perf_counter_ns() - start) / 1e6) + results[name] = dict(elapsed_ms=samples, + incremental_frame_ms=(statistics.median(samples[330]) - statistics.median(samples[30])) / 300) + print(name, json.dumps(results[name]), flush=True) +a.out.write_text(json.dumps(results, indent=2) + '\n') diff --git a/gui/bench/steps.py b/gui/bench/steps.py index f97efed..166fa90 100644 --- a/gui/bench/steps.py +++ b/gui/bench/steps.py @@ -17,6 +17,7 @@ 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) @@ -24,6 +25,9 @@ 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: @@ -31,7 +35,7 @@ class Controller: self.log = (a.out / (name + '.log')).open('w+') self.process = subprocess.Popen( [str(a.ztrace.resolve()), 'serve', str(a.out / (name + '.ztrace')), '--', *argv], - stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, bufsize=0) + cwd=a.out, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, bufsize=0) self.pending = b'' def read(self): @@ -76,9 +80,11 @@ def summary(ns): 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', str(ROOT / 'gui/targets/jit.js')])]: + '--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')])])]: start = time.perf_counter_ns() c = Controller(name, argv) + elf = None try: assert c.read()['status'] == 'stopped' entry_ns = time.perf_counter_ns() - start @@ -107,6 +113,10 @@ for name, argv in [('c', [str(small)]), ('v8', [str(a.d8), '--allow-natives-synt 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() @@ -116,11 +126,18 @@ for name, argv in [('c', [str(small)]), ('v8', [str(a.d8), '--allow-natives-synt 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) 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) - assert f"thread {reply['tid']}" in shown.stdout.splitlines(), 'JIT stop inherited a stale native source line' + 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') diff --git a/gui/build.zig b/gui/build.zig index ec8b435..98d9c44 100644 --- a/gui/build.zig +++ b/gui/build.zig @@ -39,6 +39,21 @@ pub fn build(b: *std.Build) void { _ = test_run.addPrefixedOutputFileArg("STRIKE=", "strike.png"); test_run.addArg("--define"); _ = test_run.addPrefixedOutputFileArg("SETTLED=", "settled.png"); + test_run.addArg("--define"); + _ = test_run.addPrefixedOutputFileArg("LENS=", "lens.png"); + test_run.addArg("--define"); + _ = test_run.addPrefixedOutputFileArg("LENS_SETTLED=", "lens-settled.png"); + test_run.addArg("--define"); + _ = test_run.addPrefixedOutputFileArg("FRAME_LENS=", "frame-lens.png"); test_run.expectExitCode(0); - b.step("test", "Test real debugger interactions through the GUI").dependOn(&test_run.step); + const tests = b.step("test", "Test real debugger interactions through the GUI"); + 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 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); } diff --git a/gui/src/Navigation.zig b/gui/src/Navigation.zig new file mode 100644 index 0000000..f9ae34a --- /dev/null +++ b/gui/src/Navigation.zig @@ -0,0 +1,56 @@ +//! 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 }; +place: Location = .{}, +history: [32]Location = @splat(.{}), +len: u8 = 0, +cursor: u8 = 0, + +pub fn visit(n: *Navigation, address: u64) void { + if (n.place.address == address and !n.place.follow) return; + if (n.len == 0) { + n.history[0] = n.place; + n.len = 1; + } + n.history[n.cursor] = n.place; + n.len = n.cursor + 1; + if (n.len == n.history.len) { + std.mem.copyForwards(Location, n.history[0..31], n.history[1..]); + n.len -= 1; + } + n.cursor = n.len; + n.place = .{ .address = address, .follow = false }; + n.history[n.len] = n.place; + n.len += 1; +} + +pub fn back(n: *Navigation) void { + if (n.len == 0 or n.cursor == 0) return; + n.history[n.cursor] = n.place; + n.cursor -= 1; + n.place = n.history[n.cursor]; +} + +pub fn forward(n: *Navigation) void { + if (n.cursor + 1 >= n.len) return; + n.history[n.cursor] = n.place; + n.cursor += 1; + n.place = n.history[n.cursor]; +} + +test "pane jumps retain scroll and discard the abandoned forward branch" { + var n: Navigation = .{}; + n.visit(0x1000); + n.place.row = 3; + n.visit(0x2000); + n.back(); + try std.testing.expectEqual(@as(f32, 3), n.place.row); + n.visit(0x3000); + n.forward(); + try std.testing.expectEqual(@as(u64, 0x3000), n.place.address); + for (0..40) |i| n.visit(0x4000 + i); + try std.testing.expectEqual(@as(u8, 32), n.len); + for (0..40) |_| n.back(); + try std.testing.expectEqual(@as(u64, 0x4008), n.place.address); +} diff --git a/gui/src/Sources.zig b/gui/src/Sources.zig new file mode 100644 index 0000000..33268c5 --- /dev/null +++ b/gui/src/Sources.zig @@ -0,0 +1,34 @@ +//! Owned, bounded source cache. No animation-global cache can outlive these bytes. +const std = @import("std"); +const canim = @import("canim"); +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, + +pub fn close(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.* = .{}; +} + +pub fn get(s: *Sources, gpa: std.mem.Allocator, io: std.Io, m: zt.store.Moment, id: u64) ?*const File { + for (s.files.items) |*file| if (file.id == id) return file; + 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 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 { + if (text) |t| t.deinit(); + gpa.free(path); + gpa.free(bytes); + return null; + }; + return &s.files.items[s.files.items.len - 1]; +} diff --git a/gui/src/app.zig b/gui/src/app.zig index 220fc28..dfa0d0a 100644 --- a/gui/src/app.zig +++ b/gui/src/app.zig @@ -4,9 +4,12 @@ const canim = @import("canim"); const zt = @import("ztrace"); const ui = canim.ui; const Client = @import("Client.zig"); +const Navigation = @import("Navigation.zig"); +const Sources = @import("Sources.zig"); +var sources: Sources = .{}; pub const name = "ztrace debugger"; -pub const width = 1920; -pub const height = 1080; +pub const width = 2240; +pub const height = 1260; pub var io: std.Io = undefined; pub var gpa: std.mem.Allocator = undefined; var trace: ?zt.Trace = null; @@ -21,9 +24,47 @@ pub const State = struct { stops: u64 = 0, pc: u64 = 0, action: sk.Request(Action) = .{}, + nav: [3]Navigation = @splat(.{}), + focus: Pane = .code, + maps: [3]bool = @splat(true), + source: bool = true, + source_column: u16 = 0, + annotations: bool = true, + depth: u8 = 4, + ascii: bool = true, + lens: bool = false, + lens_address: u64 = 0, + lens_origin: Box = .{}, + help: bool = false, + prefix: u8 = 0, + command_open: bool = false, + command_text: [512]u8 = @splat(0), + command_len: u16 = 0, + drag_map: ?Pane = null, }; pub const Session = struct { action: sk.Handled = .{}, + scroll: [3]f32 = @splat(0), + base: [3]u64 = @splat(0), + mini: [3]ui.Collected = @splat(.{}), + mini_key: [3]u64 = @splat(0), + listing_at: ?u64 = null, + listing_base: u64 = 0, + code: [256]canim.disasm.Insn = undefined, + code_text: [256][1024]u8 = undefined, + code_lines: [256]?zt.store.Line = undefined, + code_count: usize = 0, + aligned: [512]canim.aligned.LiveRow = undefined, + aligned_count: usize = 0, + marker_key: u64 = 0, + marker_base: u64 = 0, + marker_from: f32 = 0, + marker_to: f32 = 0, + marker_shown: f32 = 0, + marker_at: u64 = 0, + lens_at: u64 = 0, + lens_previous: u64 = 0, + shown: ?u64 = null, tid: u32 = 0, changed_at: u64 = 0, @@ -31,16 +72,34 @@ pub const Session = struct { changed_stack: u16 = 0, changed_flags: u64 = 0, code_start: u64 = 0, - mark_from: f32 = 0, - mark_to: f32 = 0, trail: [3]u64 = @splat(0), result_at: ?u64 = null, touch: ?canim.Recording.Touch = null, branch: ?canim.Recording.Branch = null, }; -const Action = enum { cont, pause, stepi, step }; +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 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 }; +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 button_count: usize = 0; +var extents: [3]f32 = @splat(0); +var bases: [3]u64 = @splat(0); +var tooltip: ?Button = null; +var lens_box: ?Box = null; +var lens_hits: usize = 0; pub fn close() void { + sources.close(gpa); if (trace) |*t| t.close(); trace = null; if (client) |c| c.close(); @@ -77,11 +136,31 @@ 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, "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, "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")) { + 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); + s.focus = pane; + if (client != null and s.status == .stopped and s.following) { + var buf: [96]u8 = undefined; + try client.?.send(try std.fmt.bufPrint(&buf, "inspect {s} 0x{x} {d}", .{ if (pane == .code) "code" else "memory", address, @as(u32, if (pane == .code) 128 else 2048) })); + } + return true; + } + if (std.mem.eql(u8, cmd, "mouse-button")) { + // The headless host has no non-left click syntax; exercise the actual handler. + const code = try std.fmt.parseInt(u16, words.next() orelse return error.MissingButton, 10); + const x = try std.fmt.parseFloat(f32, words.next() orelse return error.MissingX); + const y = try std.fmt.parseFloat(f32, words.next() orelse return error.MissingY); + pointer(s, code, x, y); + return true; + } if (!std.mem.eql(u8, cmd, "open")) return false; if (client != null) return error.TargetActive; const path = words.next() orelse return error.MissingPath; @@ -91,6 +170,7 @@ pub fn command(s: *State, c: *sk.Console, line: []const u8) !bool { var events = try (try next.moment(next.len - 1)).events(gpa); defer events.deinit(gpa); if (trace) |*t| t.close(); + sources.close(gpa); trace = next; s.moment = next.len -| 1; s.stops = next.len; @@ -102,37 +182,378 @@ pub fn command(s: *State, c: *sk.Console, line: []const u8) !bool { return true; } -pub fn update(s: *State, in: *const sk.Input) void { - if (in.pressed(sk.Key.left)) { - s.following = false; - s.moment -|= 1; +fn contains(r: Box, x: f32, y: f32) bool { + return x >= r.x and y >= r.y and x < r.x + r.w and y < r.y + r.h; +} +fn paneAt(x: f32, y: f32) ?Pane { + for (panes, 0..) |box, i| if (contains(box, x, y)) return @fromBackingInt(@intCast(i)); + return null; +} +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; + while (i > floor) { + i -= 1; + if (contains(hits[i].box, x, y)) return hits[i]; } - if (in.pressed(sk.Key.right)) { - s.following = false; - s.moment = @min(s.moment +| 1, s.stops -| 1); + return null; +} +fn collectAddress(_: *anyopaque, address: u64, box: Box) void { + if (hit_count == hits.len) return; + hits[hit_count] = .{ .address = address, .box = box }; + hit_count += 1; +} +fn scroll(s: *State, pane: Pane, delta: f32) void { + const p = @backingInt(pane); + const n = &s.nav[p]; + if (n.place.follow) { + n.place.address = bases[p]; + n.place.follow = false; } - if (in.pressed(sk.Key.end)) { - s.following = true; - s.moment = s.stops -| 1; + n.place.row = std.math.clamp(n.place.row + delta, 0, extents[p]); +} +fn act(s: *State, a: Action) void { + const p = @backingInt(a.pane); + switch (a.kind) { + .previous => { + s.following = false; + s.moment -|= 1; + }, + .next => { + s.following = false; + s.moment = @min(s.moment +| 1, s.stops -| 1); + }, + .live => { + s.following = true; + s.moment = s.stops -| 1; + }, + .follow => { + s.nav[p].place = .{}; + }, + .back => s.nav[p].back(), + .forward => s.nav[p].forward(), + .source => s.source = !s.source, + .map => s.maps[p] = !s.maps[p], + .annotate => s.annotations = !s.annotations, + .shallower => s.depth = @max(1, s.depth -| 1), + .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; + }; + } + }, + .close_lens => s.lens = false, + .help => s.help = !s.help, + .command => { + s.command_open = true; + s.command_len = 0; + }, + else => s.action.send(a), } - if (client == null or s.status == .exited) return; - if (in.pressed(sk.Key.f5)) s.action.send(if (s.status == .running) .pause else .cont); - if (in.pressed(sk.Key.f10) and s.status != .running) s.action.send(.stepi); - if (in.pressed(sk.Key.f11) and s.status != .running) s.action.send(.step); - if (in.mousePressed(.left)) |e| if (e.y >= 38 and e.y < 64) { - if (e.x >= 24 and e.x < 190) s.action.send(if (s.status == .running) .pause else .cont); - if (e.x >= 204 and e.x < 370 and s.status != .running) s.action.send(.stepi); - if (e.x >= 384 and e.x < 550 and s.status != .running) s.action.send(.step); +} +fn semantic(s: *State, address: u64) void { + const t = if (trace) |*t| t else return; + const m = t.moment(@min(s.moment, t.len -| 1)) catch return; + const region = canim.rows.regionOf(m, address); + const pane: Pane = switch (region) { + .code, .rwx => .code, + .stack => .stack, + else => blk: { + const value = (canim.Recording.word(m, address, 8) catch null) orelse break :blk .memory; + break :blk if (canim.rows.regionOf(m, value) != .none) .stack else .memory; + }, }; + s.lens_address = address; + s.focus = pane; + s.action.send(.{ .kind = .go, .pane = pane, .address = address }); +} +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); +} +fn enabled(s: *const State, a: Action) bool { + return switch (a.kind) { + .cont, .stepi, .step, .breakpoint => client != null and s.status == .stopped, + .pause => client != null and s.status == .running, + .back => s.nav[@backingInt(a.pane)].cursor > 0, + .forward => s.nav[@backingInt(a.pane)].cursor + 1 < s.nav[@backingInt(a.pane)].len, + else => true, + }; +} +fn pointer(s: *State, mouse_button: u16, x: f32, y: f32) void { + if (s.help) 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 }); + return; + } + if (mouse_button == 3) { + if (addressAt(x, y)) |hit| semantic(s, hit.address); + return; + } + if (mouse_button != 1) return; + var b = button_count; + while (b > 0) { + b -= 1; + if (contains(buttons[b].box, x, y)) { + if (enabled(s, buttons[b].action)) act(s, buttons[b].action); + 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; + } + 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; + mapDrag(s, pane, y); + return; + } + } + if (addressAt(x, y)) |hit| { + s.lens_address = hit.address; + s.lens_origin = hit.box; + s.lens = true; + } +} + +pub fn update(s: *State, in: *const sk.Input) void { + if (in.console) return; + for (in.events) |e| { + 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 != ':') { + s.command_text[s.command_len] = @intCast(e.value); + s.command_len += 1; + } + } + if (e.kind == .key_down) switch (@as(sk.Key, @fromBackingInt(@intCast(@as(u8, @intCast(e.code)))))) { + .escape => s.command_open = false, + .backspace => s.command_len -|= 1, + .@"return" => { + s.command_open = false; + s.action.send(.{ .kind = .submit }); + }, + else => {}, + }; + continue; + } + switch (e.kind) { + .text => switch (e.value) { + ':' => act(s, .{ .kind = .command }), + '?' => act(s, .{ .kind = .help }), + else => {}, + }, + .mouse_down => pointer(s, e.code, e.x, e.y), + .mouse_up, .cancel => s.drag_map = null, + .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); + }, + .key_down => { + const key: sk.Key = @fromBackingInt(@intCast(@as(u8, @intCast(e.code)))); + const ctrl = e.value & sk.Key.Mod.ctrl != 0 or in.held(sk.Key.left_ctrl) or in.held(sk.Key.right_ctrl); + 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), + .o => act(s, .{ .kind = .back, .pane = s.focus }), + .i => act(s, .{ .kind = .forward, .pane = s.focus }), + .w => s.prefix = 'w', + .c => if (s.status == .running) { + act(s, .{ .kind = .pause }); + }, + else => {}, + } + continue; + } + if (s.prefix == 'w') { + s.focus = switch (key) { + .h => .stack, + .l => .memory, + .k => .code, + .j => .stack, + else => s.focus, + }; + s.prefix = 0; + continue; + } + 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), + .j => scroll(s, s.focus, 1), + .k => scroll(s, s.focus, -1), + .g => if (shift) { + scroll(s, s.focus, extents[@backingInt(s.focus)]); + } else if (was_g) { + scroll(s, s.focus, -extents[@backingInt(s.focus)]); + } else { + s.prefix = 'g'; + }, + .s => if (s.status == .stopped) { + act(s, .{ .kind = .stepi }); + }, + .n => if (s.status == .stopped) { + act(s, .{ .kind = .step }); + }, + .c => if (s.status == .stopped) { + act(s, .{ .kind = .cont }); + }, + .escape => if (s.lens or s.help) { + s.lens = false; + s.help = false; + } else if (s.status == .running) { + act(s, .{ .kind = .pause }); + }, + .left_bracket => act(s, .{ .kind = .previous }), + .right_bracket => act(s, .{ .kind = .next }), + .f => if (shift) { + act(s, .{ .kind = .live }); + } else { + act(s, .{ .kind = .follow, .pane = s.focus }); + }, + .b => act(s, .{ .kind = .breakpoint, .address = s.pc }), + .m => act(s, .{ .kind = .map, .pane = s.focus }), + .v => act(s, .{ .kind = .source }), + .a => act(s, .{ .kind = .annotate }), + .z => act(s, .{ .kind = .lens, .address = if (addressAt(in.mouse_x, in.mouse_y)) |h| h.address else s.pc }), + .tab => s.focus = @fromBackingInt(@intCast((@backingInt(s.focus) + 1) % 3)), + else => {}, + } + }, + else => {}, + } + } +} + +fn icon(u: ui.Ui, kind: Kind, active: bool) void { + const c = if (active) ui.theme.mark(.current).solid else ui.theme.color.text.primary; + const v = u.moved(6, 5); + switch (kind) { + .cont => sk.draw.polygon(u.f, &.{ .{ 3, 2 }, .{ 3, 20 }, .{ 18, 11 } }, v.at.pen(.{ .fill = ui.rgb(c) })), + .pause => { + v.fill(.{ .x = 4, .y = 3, .w = 4, .h = 16 }, c); + v.fill(.{ .x = 13, .y = 3, .w = 4, .h = 16 }, c); + }, + .stepi, .step => { + v.route(&.{ .{ 2, 11 }, .{ 18, 11 } }, c, .{ .width = 2, .head = .{ 6, 6 } }); + v.line(.{ 20, 3 }, .{ 20, 19 }, c, 2); + if (kind == .step) { + v.line(.{ 2, 2 }, .{ 12, 2 }, c, 2); + v.line(.{ 2, 20 }, .{ 12, 20 }, c, 2); + } + }, + .previous, .back, .next, .forward => { + const left = kind == .previous or kind == .back; + v.route(&.{ .{ if (left) 19 else 3, 11 }, .{ if (left) 3 else 19, 11 } }, c, .{ .width = 2, .head = .{ 6, 7 } }); + if (kind == .previous or kind == .next) v.disc(.{ if (left) 21 else 1, 11 }, 2, ui.rgb(c), null, 0); + }, + .live, .follow => { + v.disc(.{ 11, 11 }, 7, null, ui.rgb(c), 2); + v.disc(.{ 11, 11 }, 2, ui.rgb(c), null, 0); + v.line(.{ 11, 0 }, .{ 11, 5 }, c, 1); + v.line(.{ 11, 17 }, .{ 11, 22 }, c, 1); + }, + .breakpoint => v.disc(.{ 11, 11 }, 7, ui.rgb(ui.theme.mark(.write).solid), null, 0), + .source => { + v.line(.{ 10, 3 }, .{ 4, 11 }, c, 2); + v.line(.{ 4, 11 }, .{ 10, 19 }, c, 2); + v.line(.{ 14, 3 }, .{ 20, 11 }, c, 2); + v.line(.{ 20, 11 }, .{ 14, 19 }, c, 2); + }, + .map => { + v.frame(.{ .x = 1, .y = 1, .w = 20, .h = 20 }, c, 1); + for (0..5) |i| { + const y = 4 + @as(f32, @floatFromInt(i)) * 3; + v.line(.{ 4, y }, .{ if (i % 2 == 0) 18 else 13, y }, c, 1); + } + v.frame(.{ .x = 2, .y = 8, .w = 18, .h = 7 }, c, 1); + }, + .lens => { + v.disc(.{ 9, 9 }, 7, null, ui.rgb(c), 2); + v.line(.{ 14, 14 }, .{ 21, 21 }, c, 3); + }, + .shallower, .deeper => { + v.line(.{ 3, 11 }, .{ 19, 11 }, c, 2); + if (kind == .deeper) v.line(.{ 11, 3 }, .{ 11, 19 }, c, 2); + }, + .annotate => { + v.route(&.{ .{ 2, 18 }, .{ 2, 5 }, .{ 20, 5 } }, c, .{ .width = 2, .head = .{ 6, 6 } }); + v.line(.{ 8, 14 }, .{ 20, 14 }, c, 2); + v.line(.{ 8, 19 }, .{ 17, 19 }, c, 2); + }, + .ascii => v.text(.mono_bold, 20, 1, 19, "Aa", c), + .close_lens => { + v.line(.{ 3, 3 }, .{ 19, 19 }, c, 2); + v.line(.{ 19, 3 }, .{ 3, 19 }, c, 2); + }, + .help => v.text(.mono_bold, 22, 5, 19, "?", c), + .command => { + v.route(&.{ .{ 2, 4 }, .{ 10, 11 }, .{ 2, 18 } }, c, .{ .width = 2, .head = null }); + v.line(.{ 12, 18 }, .{ 21, 18 }, c, 2); + }, + else => {}, + } +} +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 }; + const b: Button = .{ .action = action, .box = box, .label = label, .enabled = available }; + if (button_count < buttons.len) { + buttons[button_count] = b; + button_count += 1; + } + const hover = !u.f.in.console and contains(box, u.f.in.mouse_x, u.f.in.mouse_y); + if (hover) tooltip = b; + const v = (if (available) u else u.faded(0.32)).moved(x, y); + v.fill(.{ .x = 0, .y = 0, .w = 34, .h = 32 }, if (hover or active) ui.theme.color.rule else ui.theme.color.raised); + if (hover or active) v.frame(.{ .x = 0, .y = 0, .w = 34, .h = 32 }, if (active) ui.theme.mark(.current).solid else ui.theme.color.text.dim, 1); + icon(v, action.kind, active); +} +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; + 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 - 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); } pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { - if (ss.action.take(s.action)) |action| f.run(switch (action) { - .cont => "continue", - .pause => "interrupt", - .stepi => "stepi", - .step => "nextline", - }); + if (ss.action.take(s.action)) |action| switch (action.kind) { + .cont => f.run("continue"), + .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 })), + .breakpoint => f.run(ui.Ui.init(f).print("break *0x{x}", .{action.address})), + .submit => f.run(s.command_text[0..s.command_len]), + else => {}, + }; if (client) |c| if (c.poll()) |update_| if (update_.generation != latest.generation) { latest = update_; if (latest.status != .running and latest.moments > loaded) { @@ -149,30 +570,42 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { const u = ui.Ui.init(f); const ink = ui.theme.color.text; const gold = ui.theme.mark(.current); + hit_count = 0; + button_count = 0; + tooltip = null; + lens_box = null; + ui.address_hit = .{ .ctx = ss, .emit = collectAddress }; + defer ui.address_hit = null; u.text(.sans_medium, 24, 24, 28, "ztrace / debugger", ink.primary); - const status_ink = if (s.status == .failed) ui.theme.mark(.write).solid else gold.solid; const status = if (client == null) (if (trace == null) "READY" else "RECORDING") else @tagName(s.status); - u.fill(.{ .x = 332, .y = 9, .w = 118, .h = 24 }, ui.theme.color.raised); - u.text(.mono_bold, 17, 344, 27, status, status_ink); - u.text(.sans, 18, 468, 27, latest.reason(), ink.dim); - if (client != null) u.text(.mono, 17, 1610, 27, u.print("last command {d:.3} ms", .{@as(f64, @floatFromInt(latest.elapsed_ns)) / 1e6}), ink.dim); - for ([_][]const u8{ if (s.status == .running) "F5 Pause" else "F5 Continue", "F10 Instruction", "F11 Source line" }, 0..) |label, i| { - const x = 24 + @as(f32, @floatFromInt(i)) * 180; - const enabled = client != null and s.status != .exited and (i == 0 or s.status != .running); - const hover = enabled and !f.in.console and f.in.mouse_x >= x and f.in.mouse_x < x + 166 and f.in.mouse_y >= 38 and f.in.mouse_y < 64; - const v = if (enabled) u else u.faded(0.45); - v.fill(.{ .x = x, .y = 38, .w = 166, .h = 26 }, if (hover) ui.theme.color.rule else ui.theme.color.raised); - v.frame(.{ .x = x, .y = 38, .w = 166, .h = 26 }, if (hover) gold.solid else ui.theme.color.rule, 1); - v.text(.sans_medium, 17, x + 8, 57, label, ink.primary); + 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 · ?" }; + 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) { + .source => s.source, + .map => s.maps[@backingInt(s.focus)], + .annotate => s.annotations, + .lens => s.lens, + .live => s.following, + else => false, + }); } - u.text(.sans, 18, 584, 57, "← / → history End live ` commands", ink.dim); + u.text(.sans, 17, 600, 63, "j k scroll s instruction n source c run : command ? help", ink.dim); const t = if (trace) |*t| t else { - _ = u.moved(24, 88).panel(1872, 948, "session", .{ .focus = true }); + _ = u.moved(24, 88).panel(2192, 1124, "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 the command line with backtick, then set a breakpoint and continue.", ink.dim); + u.text(.sans, 22, 72, 268, "Open commands with : or backtick, then set a breakpoint and continue.", ink.dim); u.text(.mono, 20, 72, 328, "break FUNCTION break *ADDRESS clear ID", ink.primary); - u.text(.sans, 22, 72, 396, "Or inspect a recording with open PATH.", ink.dim); + overlays(u, s, ss, null); return; }; const m = t.moment(@min(s.moment, t.len -| 1)) catch return; @@ -181,106 +614,394 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { if (ss.shown != m.index or ss.tid != s.tid) selected(ss, t, m, regs, s.tid, low, f.in.now); const seconds = @as(f32, @floatFromInt(f.in.now -| ss.changed_at)) / 1e9; const heat = changedHeat(seconds); - const travel = ui.theme.ease(.standard, std.math.clamp(seconds / ui.theme.time.step, 0, 1)); 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, 1360, 57, mode, gold.solid); - u.text(.mono, 18, 1492, 57, u.print("moment {d}/{d} · tid {d}", .{ m.index, t.len -| 1, s.tid }), ink.dim); - - const d = u.moved(24, 88); - var symbol_buf: [256]u8 = undefined; - const symbol = (m.string(regs.rip, &symbol_buf) catch null) orelse "source unavailable"; - _ = d.panel(1180, 620, "disassembly", .{ .focus = true, .note = canim.rows.fitted(d, symbol, 820) }); - d.clip(.{ .x = 2, .y = 26, .w = 1176, .h = 590 }); - const marker = 32 + std.math.lerp(ss.mark_from, ss.mark_to, travel) * 24; - d.current(.{ .x = 2, .y = marker, .w = 1176, .h = 24 }, ui.theme.metric.plaque.pc, fire); - sk.draw.polygon(f, &.{ .{ 20, marker + 12 }, .{ 10, marker + 6 }, .{ 10, marker + 18 } }, d.at.pen(.{ .fill = ui.rgb(gold.on_solid) })); - var pc = ss.code_start; - var target_y: ?f32 = null; - for (0..24) |i| { - var buf: [1024]u8 = undefined; - const insn = (zt.telescope.instruction(m, pc, &buf) catch null) orelse break; - const y = 32 + @as(f32, @floatFromInt(i)) * 24; - for (ss.trail, 0..) |old, k| if (old == pc and pc != regs.rip) { + 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); + 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; + 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; + 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; + } + 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); + 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); + overlays(u, s, ss, m); +} +fn listing(ss: *Session, m: zt.store.Moment, base: u64) void { + if (ss.listing_at == m.index and ss.listing_base == base) return; + ss.listing_at = m.index; + ss.listing_base = base; + ss.code_count = 0; + 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; + 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; +} +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); + return; + }; + if (line.line == 0 or line.line > text.lines.len) return; + const range = text.lines[line.line - 1]; + 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 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; + var current_group: ?usize = null; + var group_start: usize = 0; + for (ss.aligned[0..ss.aligned_count], 0..) |row, i| { + if (row.source != null) group_start = i; + if (row.instruction) |j| if (ss.code[j].addr == regs.rip) { + current_group = group_start; + }; + } + 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 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 current = row.addr == regs.rip; + if (current) { + const marker_y = if (miniature) y else 32 + (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) })); + } + for (ss.trail, 0..) |old, k| if (old == row.addr and !current) { d.trail(2, y, k); break; }; - const current = pc == regs.rip; - const row: canim.disasm.Insn = .{ .addr = pc, .len = insn.len, .text = insn.text, .line = if (insn.line) |line| line.line else null, .params = insn.params }; - canim.disasm.liveRow(d, row, y, 1180, m, regs, .{ - .current = current, - .executed = ss.result_at == pc, - .heat = heat, - .lead = ui.shared(&.{ ss.code_start, ss.code_start + 256 }), - .touch = if (current) ss.touch else null, - .branch = if (current) ss.branch else null, - }); - if (ss.branch) |branch| if (branch.to == pc) { - target_y = y; + 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 }); + if (ss.branch) |branch| if (branch.to == row.addr) { + branch_row = y; }; - pc += insn.len; } - if (ss.branch) |branch| if (target_y) |to| if (branch.kind == .jump and to != marker) { - d.route(&.{ .{ 38, marker + 12 }, .{ 31, marker + 12 }, .{ 31, to + 12 }, .{ 39, to + 12 } }, if (branch.taken) gold.solid else ink.faint, .{ .width = 2, .head = .{ 7, 8 }, .radius = 4, .dashed = !branch.taken, .progress = travel }); + 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 (@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) { + u.route(&.{ .{ seam + 37, pc_row.? + 12 }, .{ seam + 28, pc_row.? + 12 }, .{ seam + 28, branch_row.? + 12 }, .{ seam + 38, branch_row.? + 12 } }, if (branch.taken) ui.theme.mark(.current).solid else ui.theme.color.text.faint, .{ .width = 2, .head = .{ 7, 8 }, .radius = 4, .dashed = !branch.taken, .progress = travel }); }; - d.unclip(); - - const r = u.moved(1228, 88); - _ = r.panel(668, 620, "registers", .{ .note = u.print("{d} changed", .{@popCount(ss.changed_regs)}) }); +} +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)); + if (ss.marker_key != marker_key) { + 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) { + ss.marker_to = @floatFromInt(i); + ss.marker_from = if (ss.marker_base == bases[0]) ss.marker_shown else ss.marker_to; + }; + } + ss.marker_key = marker_key; + ss.marker_base = bases[0]; + ss.marker_at = u.f.in.now; + } + 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 }); + 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); + 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")) { + 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); + 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); + 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); + } +} +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 }); for (zt.Regs.names[0..16], 0..) |reg, i| { const changed = ss.changed_regs & (@as(u32, 1) << @intCast(i)) != 0; - _ = canim.rows.reg(r, 34 + @as(f32, @floatFromInt(i)) * 24, 668, reg, m, regs.named(reg).?, .{ .first = if (changed) heat else .none, .extend = if (changed) seconds else null }); + _ = 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.rip(r, 430, 668, m, regs.rip, regs.eflags, ss.changed_flags, heat.corner, fire, if (ss.branch != null) flagsReadAt(m, regs.rip) else 0, 1, null); - r.text(.sans, 17, 14, 492, "Pointers keep the ink of the memory they reach", ink.dim); - for ([_][]const u8{ "stack", "heap", "code", "data" }, [_]u24{ ui.theme.color.region.stack, ui.theme.color.region.heap, ui.theme.color.region.code_, ui.theme.color.region.data }, 0..) |label, color, i| { - r.text(.mono, 18, 14 + @as(f32, @floatFromInt(i)) * 132, 524, label, color); + 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); + var frame_buf: [10]zt.Debugger.Frame = undefined; + const frames = zt.telescope.frames(m, ®s, &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_) }); + 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); } - r.corner(14, 548, 8, 1); - r.text(.sans, 17, 32, 562, "changed since previous stop", ink.dim); - r.frame(.{ .x = 14, .y = 578, .w = 12, .h = 14 }, ui.theme.mark(.read).solid, 2); - r.text(.sans, 17, 32, 592, "read by the current instruction", ink.dim); - - const stack = u.moved(24, 724); - _ = stack.panel(1280, 312, "stack / telescope", .{ .note = "addresses · pointers · values · frame roles" }); - var slots: [11]zt.telescope.Slot = undefined; - _ = zt.telescope.slots(m, ®s, low, &slots) catch { + 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 { + const start: usize = if (miniature) 0 else @intFromFloat(@floor(@max(0, first))); + const count: usize = if (miniature) 128 else 17; + const base = bases[1] & ~@as(u64, 7); + var slots: [128]zt.telescope.Slot = undefined; + _ = zt.telescope.slots(m, ®s, base +| start * 8, slots[0..@min(count, 128 - start)]) catch { @memset(&slots, .{}); }; - for (&slots, 0..) |*slot, i| { - const addr = low + i * 8; - const y = 32 + @as(f32, @floatFromInt(i)) * 24; - const changed = ss.changed_stack & (@as(u16, 1) << @intCast(i)) != 0; - const touched = if (ss.touch) |touch| touch.how & 1 != 0 and addr < touch.addr + touch.len and addr + 8 > touch.addr else false; + for (start..@min(start + count, 128)) |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 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, slot.*, (canim.Recording.word(m, addr, 8) catch null) orelse 0); - _ = canim.rows.slot(stack, y, 1280, 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(&.{ low, low + 80 }), .extend = if (changed) seconds else null }, role.name, role.local, null); + 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); } +} +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); + 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); var frame_buf: [10]zt.Debugger.Frame = undefined; const frames = zt.telescope.frames(m, ®s, &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 + slots.len * 8); + const to = @min(frame.high, low + 15 * 8); if (from >= to) continue; - canim.rows.span(stack, 1280, 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 + slots.len * 8); + 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); } - const back = u.moved(1328, 724); - _ = back.panel(568, 312, "call stack", .{ .note = "observed frames" }); - for (frames[0..@min(frames.len, 5)], 0..) |frame, i| { - const y = 32 + @as(f32, @floatFromInt(i)) * 52; - if (i == 0) canim.rows.callCurrent(back, y, 568); - back.text(.mono, 20, 12, canim.rows.baseline(y), u.print("{d}", .{i}), if (i == 0) gold.on_solid else ink.dim); - _ = back.address(60, canim.rows.baseline(y), frame.pc, .{ .ink = ui.rgb(ui.theme.color.region.code_) }); - var buf: [256]u8 = undefined; - const frame_name = (m.string(frame.pc, &buf) catch null) orelse "anonymous code"; - back.text(.mono, 18, 60, y + 44, canim.rows.fitted(back, ui.symbol(u, frame_name), 470), ink.dim); + 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); + } +} +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 { + var values: [16]u8 = @splat(0); + var known: [16]bool = @splat(false); + m.read(addr, &values, &known) catch {}; + var previous: [16]u8 = @splat(0); + var was_known: [16]bool = @splat(false); + if (before) |b| b.read(addr, &previous, &was_known) catch {}; + var runs: [2]canim.rows.Run = undefined; + for (&runs, 0..) |*run, i| { + const offset = i * 8; + const word = std.mem.readInt(u64, values[offset..][0..8], .little); + var changed: ?[2]u8 = null; + for (offset..offset + 8) |j| if (known[j] and was_known[j] and values[j] != previous[j]) { + if (changed == null) changed = .{ @intCast(j - offset), @intCast(j - offset) } else changed.?[1] = @intCast(j - offset); + }; + const read: f32 = if (touch) |t| if (t.addr < addr +| offset +| 8 and t.addr +| t.len > addr +| offset) 1 else 0 else 0; + run.* = .{ .first = @intCast(offset), .len = 8, .kind = if (canim.rows.regionOf(m, word) != .none) .pointer else .number, .read = read, .heat = if (changed != null) heat else .none, .changed = changed }; + } + const shift = canim.rows.addressRoom(addr); + canim.rows.bytesAt(u, y, addr, &values, &known, &runs, canim.rows.ink(canim.rows.regionOf(m, addr)), 0, false, m, shift); + if (ascii) { + var chars: [16]u8 = undefined; + for (&chars, values, known) |*c, v, k| c.* = if (!k) '?' else if (v >= 32 and v < 127) v else '.'; + u.text(.mono, 20, 640 + shift, canim.rows.baseline(y), &chars, ui.theme.color.text.dim); + } else { + const fields = [_]canim.hexdump.Field{ .{ .at = 0, .len = 8, .reads = if (runs[0].kind == .pointer) .pointer else .number }, .{ .at = 8, .len = 8, .reads = if (runs[1].kind == .pointer) .pointer else .number } }; + _ = 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 { + const start: usize = if (miniature) 0 else @intFromFloat(@floor(@max(0, first))); + const count: usize = if (miniature) 128 else 17; + 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); + } +} +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); + 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.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; + } + 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); + } +} +fn ties(u: ui.Ui, s: *const State, ss: *Session, m: zt.store.Moment, travel: f32) void { + _ = m; + const hovered = addressAt(u.f.in.mouse_x, u.f.in.mouse_y); + const address = if (hovered) |hit| hit.address else if (ss.touch) |touch| touch.addr else return; + var from: ?Box = if (hovered) |hit| hit.box else null; + for (hits[0..hit_count]) |hit| if (hit.address == address) { + if (from == null) { + from = hit.box; + continue; + } + const a = from.?; + 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 }); + break; + } + }; + if (hovered) |h| u.read(.{ .x = h.box.x, .y = h.box.y, .w = h.box.w, .h = h.box.h }, 1); +} +fn overlays(u: ui.Ui, s: *const State, ss: *Session, moment: ?zt.store.Moment) void { + 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) { + ss.lens_at = u.f.in.now; + ss.lens_previous = 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 }); + } 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 }); + } + break; + }; + } + 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); + } + 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); + } + 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); } - const place = if (t.len <= 1) 1 else @as(f32, @floatFromInt(m.index)) / @as(f32, @floatFromInt(t.len - 1)); - u.fill(.{ .x = 24, .y = 1050, .w = 1872, .h = 2 }, ui.theme.color.rule); - u.fill(.{ .x = 24, .y = 1050, .w = 1872 * place, .h = 2 }, gold.solid); - u.fill(.{ .x = 22 + 1872 * place, .y = 1047, .w = 4, .h = 8 }, gold.solid); - u.text(.sans, 17, 24, 1075, if (s.following) "Inspecting the live stop" else "Inspecting recorded state · target is unchanged", ink.dim); - u.text(.sans, 17, 1400, 1075, "gold: execution vermilion: changed", ink.dim); } fn changedHeat(seconds: f32) ui.Heat { @@ -308,11 +1029,7 @@ fn rowOf(m: zt.store.Moment, start: u64, address: u64) ?usize { } fn selected(ss: *Session, t: *zt.Trace, m: zt.store.Moment, regs: zt.Regs, tid: u32, low: u64, now: u64) void { - const seconds = @as(f32, @floatFromInt(now -| ss.changed_at)) / 1e9; - ss.mark_from = std.math.lerp(ss.mark_from, ss.mark_to, ui.theme.ease(.standard, std.math.clamp(seconds / ui.theme.time.step, 0, 1))); - if (rowOf(m, ss.code_start, regs.rip)) |row| { - ss.mark_to = @floatFromInt(row); - } else { + if (rowOf(m, ss.code_start, regs.rip) == null) { ss.code_start = regs.rip; for (0..6) |_| { var buf: [1024]u8 = undefined; @@ -320,8 +1037,6 @@ fn selected(ss: *Session, t: *zt.Trace, m: zt.store.Moment, regs: zt.Regs, tid: if (insn.back == 0) break; ss.code_start -|= insn.back; } - ss.mark_to = @floatFromInt(rowOf(m, ss.code_start, regs.rip) orelse 0); - ss.mark_from = ss.mark_to; } ss.shown = m.index; ss.tid = tid; diff --git a/gui/targets/jit.js b/gui/targets/jit.js index 254050a..57a1218 100644 --- a/gui/targets/jit.js +++ b/gui/targets/jit.js @@ -2,7 +2,9 @@ // 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; + for (let i = 0; i < n; i++) { + sum = (sum + (i ^ n)) | 0; + } return sum; } %PrepareFunctionForOptimization(jitWork); diff --git a/gui/test/basic.script b/gui/test/basic.script index 220eb0b..cf23a47 100644 --- a/gui/test/basic.script +++ b/gui/test/basic.script @@ -1,33 +1,116 @@ console launch {TARGET} await stops 1 -console break work +type :break work +expect command_open true +key return +expect command_open false +type ? +expect help true +key escape +expect help false console continue await stops 2 expect status stopped -key f10 +key s await stops 3 frames 6 screenshot {STRIKE} frames 60 screenshot {SETTLED} -expect-different-screenshot {STRIKE} {SETTLED} 24 756 1280 280 -key left +expect-different-screenshot {STRIKE} {SETTLED} 24 844 1072 360 +key left_bracket expect following false expect moment 1 -key end +# Browsing and per-pane history do not execute the target. +console goto memory 0x1000 +wheel 1500 1000 -0.5 +expect nav[2].place.row 1.5 +console goto memory 0x2000 +console mouse-button 4 1500 1000 +expect nav[2].place.address 4096 +expect nav[2].place.row 1.5 +console mouse-button 5 1500 1000 +expect nav[2].place.address 8192 +hold left_ctrl +key o +release left_ctrl +expect nav[2].place.address 4096 +console goto memory 0x3000 +console mouse-button 5 1500 1000 +expect nav[2].place.address 12288 +key j +expect nav[2].place.row 1 +key g +key g +expect nav[2].place.row 0 +hold left_ctrl +key d +release left_ctrl +expect nav[2].place.row 7.5 +key f +expect nav[2].place.follow true +# Rendered code addresses route to disassembly, including source-aligned rows. +console mouse-button 3 650 122 +expect focus code +expect nav[0].place.follow false +console mouse-button 4 650 122 +expect nav[0].place.follow true +console mouse-button 5 650 122 +expect nav[0].place.follow false +key f +# Stack storage addresses route to telescope. +console mouse-button 3 250 855 +expect focus stack +expect nav[1].place.follow false +console mouse-button 4 250 855 +expect nav[1].place.follow true +console mouse-button 5 250 855 +expect nav[1].place.follow false +key f +expect status stopped +expect stops 3 +expect moment 1 +# A real address lens, with an animated rise and real recorded bytes. +click 250 855 +expect lens true +frames 6 +screenshot {LENS} +frames 30 +screenshot {LENS_SETTLED} +expect-different-screenshot {LENS} {LENS_SETTLED} 1090 580 1120 230 +key escape +expect lens false +# Opening from a call-frame address keeps its origin visible. +click 1700 726 +expect lens true +frames 30 +screenshot {FRAME_LENS} +key escape +expect lens false +# Minimap dragging moves the viewport without changing the target. +down 2175 950 +move 2175 1100 +up 2175 1100 +expect focus memory +key f +expect nav[2].place.follow true +expect stops 3 +hold left_shift +key f +release left_shift expect following true expect moment 2 console clear 1 -key f5 +key c await status running -key f5 +key escape await status stopped -click 260 50 +click 80 54 await stops 5 -key f11 +key n await stops 6 expect status stopped expect-no-log InterruptFailed expect-no-log CommandFailed -key f5 +key c await status running diff --git a/gui/test/inspection.py b/gui/test/inspection.py new file mode 100644 index 0000000..368b6aa --- /dev/null +++ b/gui/test/inspection.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Real-target checks for read-only inspection and explicit GDB JIT ELF import.""" +import argparse +import json +import os +from pathlib import Path +import re +import select +import subprocess +import tempfile + +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 + 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 '')) + 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) |
