diff options
Diffstat (limited to 'gui')
| -rw-r--r-- | gui/README.md | 124 | ||||
| -rw-r--r-- | gui/bench/RESULTS.md | 102 | ||||
| -rw-r--r-- | gui/bench/steps.py | 126 | ||||
| -rw-r--r-- | gui/build.zig | 44 | ||||
| -rw-r--r-- | gui/build.zig.zon | 12 | ||||
| -rw-r--r-- | gui/src/Client.zig | 94 | ||||
| -rw-r--r-- | gui/src/app.zig | 369 | ||||
| -rw-r--r-- | gui/src/main.zig | 9 | ||||
| -rw-r--r-- | gui/targets/jit.js | 14 | ||||
| -rw-r--r-- | gui/targets/loop.c | 13 | ||||
| -rw-r--r-- | gui/test/basic.script | 33 |
11 files changed, 940 insertions, 0 deletions
diff --git a/gui/README.md b/gui/README.md new file mode 100644 index 0000000..3bd7d3f --- /dev/null +++ b/gui/README.md @@ -0,0 +1,124 @@ +# 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 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. + +Build with the same Zig toolchain as the rest of computeranim; the sibling +`sketchbook` and `pardes` checkouts are the existing renderer dependencies: + +```sh +cd gui +zig build -Doptimize=ReleaseFast +zig build test -Doptimize=ReleaseFast +zig build run -Doptimize=ReleaseFast -- --fresh +``` + +The build installs `ztrace` alongside `ztrace-gui`; keep the two together. +Backtick opens the renderer's console: + +```text +launch /absolute/path/to/program arguments +break main +continue +break *0x12345678 +clear 1 +signal 0 +interrupt +stepi +nextline +``` + +`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. + +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. + +## How it fits + +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. + +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. + +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. + +## Debug V8 + +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. F10 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 +# From the repository root, after building gui/: +python3 gui/bench/steps.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 + +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. diff --git a/gui/bench/RESULTS.md b/gui/bench/RESULTS.md new file mode 100644 index 0000000..d24659b --- /dev/null +++ b/gui/bench/RESULTS.md @@ -0,0 +1,102 @@ +# Debug V8 versus a small C target + +Measured locally on 2026-11-12, 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: + +```sh +python3 gui/bench/steps.py \ + --d8 /tmp/computeranim-v8-debug-remote/d8 \ + --ztrace zig-out/bin/ztrace \ + --out /tmp/ztrace-step-bench-cleared +``` + +| 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 | + +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 +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. + +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. + +The raw records, logs and JSON results are in `/tmp/ztrace-step-bench-cleared`. +The script is the durable reproducer; `/tmp` artifacts are not permanent. + +## V8 provenance + +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. + +- 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. +- `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. + +## 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 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. + +## Rich GUI verification + +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. + +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`. + +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. diff --git a/gui/bench/steps.py b/gui/bench/steps.py new file mode 100644 index 0000000..f97efed --- /dev/null +++ b/gui/bench/steps.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Compare the same controller's recorded instruction steps on C and debug V8.""" +import argparse +import json +import math +import os +from pathlib import Path +import re +import select +import statistics +import subprocess +import time + +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) +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) + + +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], + 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): + 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)) + + +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')])]: + start = time.perf_counter_ns() + c = Controller(name, argv) + 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 + 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)) + print(name, json.dumps(results[name]), flush=True) + finally: + c.close() + 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' +(a.out / 'results.json').write_text(json.dumps(results, indent=2) + '\n') diff --git a/gui/build.zig b/gui/build.zig new file mode 100644 index 0000000..ec8b435 --- /dev/null +++ b/gui/build.zig @@ -0,0 +1,44 @@ +const std = @import("std"); +const sketchbook = @import("sketchbook"); + +pub fn build(b: *std.Build) void { + const target = b.standardTargetOptions(.{}); + const optimize = b.standardOptimizeOption(.{}); + const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize }); + const canim = b.dependency("canim", .{ .target = target, .optimize = optimize }); + const zt = b.dependency("ztrace", .{ .target = target, .optimize = optimize }); + const app = sb.app(.{ .name = "ztrace-gui", .root_source_file = b.path("src/app.zig"), .imports = &.{ + .{ .name = "canim", .module = canim.module("canim") }, + .{ .name = "ztrace", .module = zt.module("ztrace") }, + } }); + b.installArtifact(zt.artifact("ztrace")); + const exe = b.addExecutable(.{ .name = "ztrace-gui", .root_module = b.createModule(.{ + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = optimize, + .imports = &.{ .{ .name = "app", .module = app.module }, .{ .name = "host", .module = sb.modules.host }, .{ .name = "sketch", .module = sb.modules.sketch } }, + }) }); + b.installArtifact(exe); + const run = std.Build.Step.Run.create(b, "ztrace-gui"); + run.addFileArg(b.graph.path(.install_bin, "ztrace-gui")); + run.step.dependOn(b.getInstallStep()); + run.addPassthruArgs(); + b.step("run", "Run the graphical debugger").dependOn(&run.step); + const test_run = std.Build.Step.Run.create(b, "GUI interactions"); + test_run.addFileArg(b.graph.path(.install_bin, "ztrace-gui")); + test_run.step.dependOn(b.getInstallStep()); + test_run.addArgs(&.{ "--headless", "--fresh", "--state" }); + _ = test_run.addOutputFileArg("gui.state"); + test_run.addArg("--script"); + test_run.addFileArg(b.path("test/basic.script")); + const small = b.addExecutable(.{ .name = "gui-target", .root_module = b.createModule(.{ .target = target, .optimize = .Debug, .link_libc = true, .sanitize_c = .off }) }); + small.root_module.addCSourceFile(.{ .file = b.path("targets/loop.c"), .flags = &.{ "-g", "-O0" } }); + test_run.addArg("--define"); + test_run.addPrefixedFileArg("TARGET=", small.getEmittedBin()); + test_run.addArg("--define"); + _ = test_run.addPrefixedOutputFileArg("STRIKE=", "strike.png"); + test_run.addArg("--define"); + _ = test_run.addPrefixedOutputFileArg("SETTLED=", "settled.png"); + test_run.expectExitCode(0); + b.step("test", "Test real debugger interactions through the GUI").dependOn(&test_run.step); +} diff --git a/gui/build.zig.zon b/gui/build.zig.zon new file mode 100644 index 0000000..2df2de0 --- /dev/null +++ b/gui/build.zig.zon @@ -0,0 +1,12 @@ +.{ + .name = .ztrace_gui, + .version = "0.0.1", + .fingerprint = 0x0b782d9588cb8e5b, + .minimum_zig_version = "0.17.0", + .dependencies = .{ + .canim = .{ .path = "../anim" }, + .ztrace = .{ .path = ".." }, + .sketchbook = .{ .path = "../../sketchbook" }, + }, + .paths = .{""}, +} diff --git a/gui/src/Client.zig b/gui/src/Client.zig new file mode 100644 index 0000000..8ced2b6 --- /dev/null +++ b/gui/src/Client.zig @@ -0,0 +1,94 @@ +//! The GUI never waits for ptrace. One std.Io task reads the controller's replies. +const std = @import("std"); +const zt = @import("ztrace"); +const Client = @This(); +io: std.Io, +gpa: std.mem.Allocator, +child: std.process.Child, +reader: ?std.Io.Future(void) = null, +mutex: std.Io.Mutex = .init, +latest: Update = .{}, +path: []const u8, + +pub const Update = struct { + generation: u64 = 0, + status: zt.control.Status = .running, + pid: i32 = 0, + tid: u32 = 0, + moments: u64 = 0, + pc: u64 = 0, + elapsed_ns: u64 = 0, + text: [256]u8 = @splat(0), + len: usize = 0, + + pub fn reason(u: *const Update) []const u8 { + return u.text[0..u.len]; + } +}; + +pub fn start(gpa: std.mem.Allocator, io: std.Io, argv: []const []const u8) !*Client { + const c = try gpa.create(Client); + errdefer gpa.destroy(c); + const path = try std.fmt.allocPrint(gpa, "/tmp/ztrace-gui-{d}-{d}.ztrace", .{ std.os.linux.getpid(), std.Io.Clock.awake.now(io).nanoseconds }); + errdefer gpa.free(path); + var args: std.ArrayList([]const u8) = .empty; + defer args.deinit(gpa); + const exe = try std.process.executablePathAlloc(io, gpa); + defer gpa.free(exe); + const tracer = try std.fs.path.join(gpa, &.{ std.fs.path.dirname(exe).?, "ztrace" }); + defer gpa.free(tracer); + try args.appendSlice(gpa, &.{ tracer, "serve", path, "--" }); + try args.appendSlice(gpa, argv); + c.* = .{ .gpa = gpa, .io = io, .path = path, .child = try std.process.spawn(io, .{ .argv = args.items, .stdin = .pipe, .stdout = .pipe, .stderr = .inherit }) }; + errdefer c.child.kill(io); + c.reader = try std.Io.concurrent(io, read, .{c}); + return c; +} + +pub fn close(c: *Client) void { + c.send("quit") catch {}; + if (c.child.stdin) |pipe| pipe.close(c.io); + c.child.stdin = null; + if (c.reader) |*r| r.await(c.io); + _ = c.child.wait(c.io) catch {}; + c.gpa.free(c.path); + c.gpa.destroy(c); +} + +pub fn send(c: *Client, command: []const u8) !void { + const pipe = c.child.stdin orelse return error.Disconnected; + if (command.len > 2048 or std.mem.indexOfScalar(u8, command, '\n') != null) return error.InvalidCommand; + var buffer: [4096]u8 = undefined; + var writer = pipe.writerStreaming(c.io, &buffer); + try writer.interface.writeAll(command); + try writer.interface.writeByte('\n'); + try writer.interface.flush(); +} + +pub fn poll(c: *Client) ?Update { + if (!c.mutex.tryLock()) return null; + defer c.mutex.unlock(c.io); + return c.latest; +} + +fn read(c: *Client) void { + var buffer: [4096]u8 = undefined; + var reader = c.child.stdout.?.readerStreaming(c.io, &buffer); + while (true) { + const line = (reader.interface.takeDelimiter('\n') catch break) orelse break; + const parsed = std.json.parseFromSlice(zt.control.Reply, c.gpa, line, .{}) catch break; + defer parsed.deinit(); + const reply = parsed.value; + c.mutex.lock(c.io) catch return; + c.latest = .{ .generation = c.latest.generation + 1, .status = reply.status, .pid = reply.pid, .tid = reply.tid, .moments = reply.moments, .pc = reply.pc, .elapsed_ns = reply.elapsed_ns, .len = @min(reply.reason.len, 256) }; + @memcpy(c.latest.text[0..c.latest.len], reply.reason[0..c.latest.len]); + c.mutex.unlock(c.io); + } + c.mutex.lock(c.io) catch return; + defer c.mutex.unlock(c.io); + c.latest.generation += 1; + c.latest.status = .exited; + const ended = "controller disconnected"; + @memcpy(c.latest.text[0..ended.len], ended); + c.latest.len = ended.len; +} diff --git a/gui/src/app.zig b/gui/src/app.zig new file mode 100644 index 0000000..220fc28 --- /dev/null +++ b/gui/src/app.zig @@ -0,0 +1,369 @@ +const std = @import("std"); +const sk = @import("sketch"); +const canim = @import("canim"); +const zt = @import("ztrace"); +const ui = canim.ui; +const Client = @import("Client.zig"); +pub const name = "ztrace debugger"; +pub const width = 1920; +pub const height = 1080; +pub var io: std.Io = undefined; +pub var gpa: std.mem.Allocator = undefined; +var trace: ?zt.Trace = null; +var client: ?*Client = null; +var latest: Client.Update = .{}; +var loaded: u64 = 0; +pub const State = struct { + moment: u64 = 0, + tid: u32 = 0, + following: bool = true, + status: zt.control.Status = .stopped, + stops: u64 = 0, + pc: u64 = 0, + action: sk.Request(Action) = .{}, +}; +pub const Session = struct { + action: sk.Handled = .{}, + shown: ?u64 = null, + tid: u32 = 0, + changed_at: u64 = 0, + changed_regs: u32 = 0, + 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 }; + +pub fn close() void { + if (trace) |*t| t.close(); + trace = null; + if (client) |c| c.close(); + client = null; +} + +pub fn command(s: *State, c: *sk.Console, line: []const u8) !bool { + var words = std.mem.tokenizeScalar(u8, line, ' '); + const cmd = words.next() orelse return false; + if (std.mem.eql(u8, cmd, "launch")) { + if (client != null) return error.AlreadyLaunched; + var argv: std.ArrayList([]const u8) = .empty; + defer argv.deinit(gpa); + // shortcut: whitespace-separated argv; add quoting when launch needs arguments containing spaces. + while (words.next()) |word| try argv.append(gpa, word); + if (argv.items.len == 0) return error.MissingProgram; + client = try Client.start(gpa, io, argv.items); + s.following = true; + s.status = .running; + return true; + } + if (std.mem.eql(u8, cmd, "observed")) { + s.status = latest.status; + s.stops = latest.moments; + s.pc = latest.pc; + if (s.following) { + s.moment = latest.moments -| 1; + s.tid = latest.tid; + } + return true; + } + if (std.mem.eql(u8, cmd, "live")) { + s.following = true; + 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")) { + 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, "open")) return false; + if (client != null) return error.TargetActive; + const path = words.next() orelse return error.MissingPath; + var next = try zt.Trace.open(gpa, io, path); + errdefer next.close(); + if (next.len == 0) return error.EmptyRecording; + var events = try (try next.moment(next.len - 1)).events(gpa); + defer events.deinit(gpa); + if (trace) |*t| t.close(); + trace = next; + s.moment = next.len -| 1; + s.stops = next.len; + s.following = false; + while (events.next()) |e| if (e.ev.tid != 0) { + s.tid = e.ev.tid; + }; + c.print("opened {d} moments", .{next.len}); + return true; +} + +pub fn update(s: *State, in: *const sk.Input) void { + if (in.pressed(sk.Key.left)) { + s.following = false; + s.moment -|= 1; + } + if (in.pressed(sk.Key.right)) { + s.following = false; + s.moment = @min(s.moment +| 1, s.stops -| 1); + } + if (in.pressed(sk.Key.end)) { + s.following = true; + s.moment = s.stops -| 1; + } + 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); + }; +} + +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 (client) |c| if (c.poll()) |update_| if (update_.generation != latest.generation) { + latest = update_; + if (latest.status != .running and latest.moments > loaded) { + if (zt.Trace.open(gpa, io, c.path)) |next| { + if (trace) |*t| t.close(); + trace = next; + loaded = next.len; + } else |err| f.host.print("recording: {t}", .{err}); + } + f.run("observed"); + }; + f.canvas(width, height); + f.clear(ui.theme.color.page); + const u = ui.Ui.init(f); + const ink = ui.theme.color.text; + const gold = ui.theme.mark(.current); + 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.text(.sans, 18, 584, 57, "← / → history End live ` commands", ink.dim); + const t = if (trace) |*t| t else { + _ = u.moved(24, 88).panel(1872, 948, "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(.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); + return; + }; + const m = t.moment(@min(s.moment, t.len -| 1)) catch return; + 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); + 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 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) { + 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; + }; + 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 }); + }; + d.unclip(); + + const r = u.moved(1228, 88); + _ = r.panel(668, 620, "registers", .{ .note = u.print("{d} changed", .{@popCount(ss.changed_regs)}) }); + 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.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); + } + 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 { + @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; + 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); + } + var frame_buf: [10]zt.Debugger.Frame = undefined; + const frames = zt.telescope.frames(m, ®s, &frame_buf) catch &.{}; + for (frames, 0..) |frame, k| { + const from = @max(frame.low, low); + const to = @min(frame.high, low + slots.len * 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); + } + 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); + } + 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 { + const timing = ui.theme.time.strike; + const cool = std.math.clamp((seconds - timing.hold) / timing.cool, 0, 1); + return .{ .level = 1, .solid = 1 - ui.theme.ease(.standard, cool), .in = std.math.clamp(seconds / timing.in, 0, 1), .out = if (seconds < timing.pulse) ui.theme.pulse(seconds / timing.pulse) else 0, .corner = std.math.clamp((seconds - timing.hold - timing.cool + timing.corner) / timing.corner, 0, 1) }; +} + +fn flagsReadAt(m: zt.store.Moment, pc: u64) u16 { + var buf: [1024]u8 = undefined; + const insn = (zt.telescope.instruction(m, pc, &buf) catch null) orelse return 0; + const row: canim.disasm.Insn = .{ .addr = pc, .len = insn.len, .text = insn.text }; + return canim.disasm.flagsRead(row.mnemonic()); +} + +fn rowOf(m: zt.store.Moment, start: u64, address: u64) ?usize { + var pc = start; + for (0..24) |i| { + if (pc == address) return i; + var buf: [1024]u8 = undefined; + const insn = (zt.telescope.instruction(m, pc, &buf) catch null) orelse return null; + pc += insn.len; + } + return null; +} + +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 { + ss.code_start = regs.rip; + for (0..6) |_| { + var buf: [1024]u8 = undefined; + const insn = (zt.telescope.instruction(m, ss.code_start, &buf) catch null) orelse break; + 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; + ss.changed_at = now; + ss.changed_regs = 0; + ss.changed_stack = 0; + ss.changed_flags = 0; + ss.trail = @splat(0); + ss.result_at = null; + for (0..@min(m.index, 3)) |k| { + const previous = t.moment(m.index - 1 - k) catch continue; + const before = (previous.regs(tid) catch null) orelse continue; + ss.trail[k] = before.rip; + if (k != 0) continue; + var code: [1024]u8 = undefined; + if ((zt.telescope.instruction(previous, before.rip, &code) catch null)) |insn| { + if (before.rip + insn.len == regs.rip) ss.result_at = before.rip; + } + for (zt.Regs.names[0..16], 0..) |reg, i| if (regs.named(reg).? != before.named(reg).?) { + ss.changed_regs |= @as(u32, 1) << @intCast(i); + }; + ss.changed_flags = regs.eflags ^ before.eflags; + for (0..11) |i| { + const addr = low + i * 8; + const a = (canim.Recording.word(previous, addr, 8) catch null) orelse continue; + const b = (canim.Recording.word(m, addr, 8) catch null) orelse continue; + if (a != b) ss.changed_stack |= @as(u16, 1) << @intCast(i); + } + } + ss.touch = null; + ss.branch = null; + var events = m.events(gpa) catch return; + defer events.deinit(gpa); + while (events.next()) |event| { + if (event.ev.tid != tid) continue; + const e = event.ev; + if (e.kind == .touch and ss.touch == null) ss.touch = .{ .addr = e.a[0], .len = e.a[1], .how = @intCast(e.aux & 3) }; + if (e.kind == .branch) ss.branch = .{ .to = e.a[0], .taken = e.a[1] != 0, .kind = switch (e.aux) { + 1 => .call, + 2 => .jump, + 3 => .ret, + else => .none, + } }; + } +} diff --git a/gui/src/main.zig b/gui/src/main.zig new file mode 100644 index 0000000..91a2ddf --- /dev/null +++ b/gui/src/main.zig @@ -0,0 +1,9 @@ +const std = @import("std"); +const app = @import("app"); + +pub fn main(init: std.process.Init) !void { + app.io = init.io; + app.gpa = init.gpa; + defer app.close(); + try @import("host").main(init, @import("sketch").sketch(app)); +} diff --git a/gui/targets/jit.js b/gui/targets/jit.js new file mode 100644 index 0000000..254050a --- /dev/null +++ b/gui/targets/jit.js @@ -0,0 +1,14 @@ +// 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; + return sum; +} +%PrepareFunctionForOptimization(jitWork); +jitWork(10); +jitWork(20); +%OptimizeFunctionOnNextCall(jitWork); +jitWork(30); +%SystemBreak(); +print(jitWork(10000)); diff --git a/gui/targets/loop.c b/gui/targets/loop.c new file mode 100644 index 0000000..d95a852 --- /dev/null +++ b/gui/targets/loop.c @@ -0,0 +1,13 @@ +#include <stdint.h> + +__attribute__((noinline)) uint32_t work(uint32_t n) { + uint32_t sum = 0; + for (uint32_t i = 0; i < n; ++i) { + sum += i ^ n; + } + return sum; +} + +int main(void) { + return (int)(work(1000000000) & 0x7f); +} diff --git a/gui/test/basic.script b/gui/test/basic.script new file mode 100644 index 0000000..220eb0b --- /dev/null +++ b/gui/test/basic.script @@ -0,0 +1,33 @@ +console launch {TARGET} +await stops 1 +console break work +console continue +await stops 2 +expect status stopped +key f10 +await stops 3 +frames 6 +screenshot {STRIKE} +frames 60 +screenshot {SETTLED} +expect-different-screenshot {STRIKE} {SETTLED} 24 756 1280 280 +key left +expect following false +expect moment 1 +key end +expect following true +expect moment 2 +console clear 1 +key f5 +await status running +key f5 +await status stopped +click 260 50 +await stops 5 +key f11 +await stops 6 +expect status stopped +expect-no-log InterruptFailed +expect-no-log CommandFailed +key f5 +await status running |
