diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-12 13:19:32 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-13 00:41:47 -0300 |
| commit | 4b4113a0217ee27c78e7efddb66ff5a455d49083 (patch) | |
| tree | b848dc1e92c3126dec11da8547e8033ff3990140 | |
| parent | eab50d1c040774351f332a1568fa332c377860bd (diff) | |
| download | computeranim-4b4113a0217ee27c78e7efddb66ff5a455d49083.tar.gz computeranim-4b4113a0217ee27c78e7efddb66ff5a455d49083.zip | |
debugger: add a native GUI with live V8 JIT debugging
| -rw-r--r-- | README.md | 4 | ||||
| -rw-r--r-- | anim/src/disasm.zig | 73 | ||||
| -rw-r--r-- | anim/src/ui.zig | 5 | ||||
| -rw-r--r-- | build/debugger.zig | 5 | ||||
| -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 | ||||
| -rw-r--r-- | notes.typ | 2 | ||||
| -rw-r--r-- | src/cli/main.zig | 2 | ||||
| -rw-r--r-- | src/cli/serve.zig | 136 | ||||
| -rw-r--r-- | src/trace/Debugger.zig | 45 | ||||
| -rw-r--r-- | src/trace/control.zig | 29 | ||||
| -rw-r--r-- | src/trace/debugger_test.zig | 32 | ||||
| -rw-r--r-- | src/trace/event.zig | 2 | ||||
| -rw-r--r-- | src/trace/root.zig | 2 | ||||
| -rw-r--r-- | src/trace/store.zig | 23 |
24 files changed, 1285 insertions, 15 deletions
@@ -23,6 +23,9 @@ ztrace probe --dry-run --usdt provider:name -- ./prog # ... with BPF, for ztrace dump fib.ztrace ``` +The separate [native debugger GUI](gui/README.md) uses both libraries for live +breakpoints, stepping, registers, disassembly, stack/telescope and recorded history. + ## The pieces | Where | What | @@ -38,6 +41,7 @@ ztrace dump fib.ztrace | `llvm/pass.cpp`, `src/instr/` | compiler instrumentation: the LLVM pass, the runtime it calls, the type descriptions | | `src/trace/perf.zig`, `bpf.zig`, `usdt.zig` | the kernel's view: perf events for any user, BPF programs for root, the static probes of `<sys/sdt.h>` | | `anim/` | canim, a package of its own (it needs sketchbook and pardes; ztrace does not): the animation library and its scenes | +| `gui/` | the standalone native debugger application; uses ztrace and canim | | `design/` | the visual system the animations follow, with mock frames | | `src/cli/` | the `ztrace` command, a file a subcommand | | `targets/` | programs to trace | diff --git a/anim/src/disasm.zig b/anim/src/disasm.zig index 67b0572..3fbe4ff 100644 --- a/anim/src/disasm.zig +++ b/anim/src/disasm.zig @@ -1218,6 +1218,79 @@ pub fn plainRow(u: ui.Ui, row: Insn, y: f32) void { bareRow(u.moved(@as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv, 0), row, y); } +/// The same instruction atoms for a live debugger: one moment, without +/// indexing an animation's entire recording. Only observed operands are annotated. +pub fn liveRow(at: ui.Ui, row: Insn, y: f32, width: f32, moment: Recording.Moment, regs: zt.Regs, options: struct { + current: bool = false, + executed: bool = false, + lead: usize = 0, + touch: ?Recording.Touch = null, + branch: ?Recording.Branch = null, + heat: ui.Heat = .none, +}) void { + const base_y = rows.baseline(y); + _ = at.address(c.address, base_y, row.addr, .{ .ink = ui.rgb(theme.color.region.code_), .lead = options.lead }); + const shift = @as(f32, @floatFromInt(@max(ui.digits(row.addr), 7) - 7)) * adv; + const u = at.moved(shift, 0); + const room = width - shift - m.side; + const pad = row.padding(); + const mn = row.mnemonic(); + if (row.line) |line| u.text(.mono, size, c.line, base_y, u.print("{d}", .{line}), t.faint); + u.text(.mono_bold, size, c.mnemonic, base_y, mn, if (pad) t.faint else theme.color.code.keyword); + var name_buf: [192]u8 = undefined; + const name = if (target(row)) |to| (moment.string(to, &name_buf) catch null) orelse "" else ""; + const annotated = options.current or options.executed; + operands(u, row, shorn(u, row), name, base_y, (if (annotated) annotationColumn() else room) - gap - c.operands, if (pad) t.faint else t.primary); + if (!annotated) return; + var x = annotationColumn(); + if (options.branch) |branch| { + const label = switch (branch.kind) { + .call => "call", + .ret => "return", + .jump => if (branch.taken) "taken" else "not taken", + .none => "", + }; + u.text(.mono, size, x, base_y, label, if (branch.taken) t.primary else t.dim); + x += u.width(.mono, size, label) + adv; + if (branch.kind == .jump and flagsRead(mn) != 0) { + _ = flags(u, x, y, regs.eflags, flagsRead(mn), if (options.current) 1 else 0); + } else { + _ = rows.chain(u, x, y, moment, branch.to, room, .{ .most = 1 }); + } + return; + } + if (options.touch) |touch| { + const label: []const u8 = if (touch.how == 1) "read" else if (touch.how == 2) "write" else "read/write"; + u.text(.mono, size, x, base_y, label, t.dim); + x += u.width(.mono, size, label) + adv; + const marks: rows.Marks = .{ .read = if (options.current and touch.how & 1 != 0) 0 else null, .read_shows = 1 }; + if (touch.len < 8) _ = rows.narrow(u, x, y, moment, touch.addr, touch.len, room, marks) else _ = rows.chain(u, x, y, moment, touch.addr, room, marks); + return; + } + if (options.executed) { + const reg = written(row) orelse return; + u.text(.mono, size, x, base_y, reg, t.dim); + _ = rows.chain(u, x + @as(f32, @floatFromInt(reg.len + 1)) * adv, y, moment, regs.named(reg).?, room, .{ .first = options.heat }); + return; + } + // Register operands at the current instruction, using their real width. + var words = std.mem.tokenizeAny(u8, row.operands(), " ,[]*+-:"); + var seen: ?[]const u8 = null; + while (words.next()) |word| { + const reg = full(word) orelse continue; + if (seen) |previous| if (std.mem.eql(u8, reg, previous)) continue; + const raw = regs.named(reg) orelse continue; + const value = number(u, if (word.len == 2 and word[1] == 'h') raw >> 8 else raw, registerSize(word) orelse 8); + const text = u.print("{s} {s}", .{ word, value }); + const w = u.width(.mono, size, text); + if (x + w > room) break; + u.text(.mono, size, x, base_y, word, t.dim); + u.text(.mono, size, x + @as(f32, @floatFromInt(word.len + 1)) * adv, base_y, value, t.primary); + x += w + 2 * adv; + seen = reg; + } +} + /// Its mnemonic and operands alone, at their columns (a graph's row, whose head carries the address). pub fn bareRow(u: ui.Ui, row: Insn, y: f32) void { const base_y = rows.baseline(y); diff --git a/anim/src/ui.zig b/anim/src/ui.zig index eeac127..2b697bf 100644 --- a/anim/src/ui.zig +++ b/anim/src/ui.zig @@ -163,6 +163,11 @@ pub const Ui = struct { f: *sk.Frame, at: anim.Placed, + /// Draw the same atoms in a native app, in design units without a scene timeline. + pub fn init(f: *sk.Frame) Ui { + return .{ .f = f, .at = .{ .t = 0, .pose = .{ .visible = true }, .xf = .identity, .scale = 1, .stage = .identity, .values = &.{} } }; + } + /// The same, at `opacity` of what it had: a thing arriving or leaving. pub fn faded(u: Ui, opacity: f32) Ui { var out = u; diff --git a/build/debugger.zig b/build/debugger.zig index f0b0e7c..af6e2e0 100644 --- a/build/debugger.zig +++ b/build/debugger.zig @@ -9,6 +9,8 @@ pub fn add(ctx: Ctx) void { // Position-independent, so the load bias is exercised. const fib = ctx.cTarget("fib", &.{"fib.c"}); fib.pie = true; + const no_lines = b.addExecutable(.{ .name = "fib-nolines", .root_module = b.createModule(.{ .target = ctx.target, .optimize = .Debug, .link_libc = true, .sanitize_c = .off }) }); + no_lines.root_module.addCSourceFile(.{ .file = b.path("targets/fib.c"), .flags = &.{ "-O0", "-g0" } }); const list = ctx.cTarget("list", &.{"list.c"}); const threads = ctx.cTarget("threads", &.{"threads.c"}); const libc_glibc = ctx.cTarget("libc-glibc", &.{"libc.c"}); @@ -51,6 +53,7 @@ pub fn add(ctx: Ctx) void { // The library, driven from Zig: the targets' paths come as options. const paths = b.addOptions(); + paths.addOptionPath("fib_nolines", no_lines.getEmittedBin()); for (targets) |t| paths.addOptionPath(b.dupe(std.mem.replaceOwned(u8, b.allocator, t.name, "-", "_") catch @panic("OOM")), t.getEmittedBin()); const lib_tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/trace/debugger_test.zig"), @@ -174,7 +177,7 @@ pub fn add(ctx: Ctx) void { until.addArg("10"); until.expectStdErrMatch("ended at fib, as --until asked"); const until_show = b.addRunArtifact(ctx.exe); - until_show.addArgs(&.{ "show" }); + until_show.addArgs(&.{"show"}); until_show.addFileArg(until_recording); until_show.addArg("-1"); // WHERE resolves as -b's does: a function's place past its prologue. 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 diff --git a/notes.typ b/notes.typ new file mode 100644 index 0000000..26a84d8 --- /dev/null +++ b/notes.typ @@ -0,0 +1,2 @@ +compatible with rr recordings? +design for realtime comms to a running process
\ No newline at end of file diff --git a/src/cli/main.zig b/src/cli/main.zig index 554efde..635bc25 100644 --- a/src/cli/main.zig +++ b/src/cli/main.zig @@ -6,6 +6,7 @@ const util = @import("util.zig"); const commands = .{ .record = @import("record.zig"), .dbg = @import("dbg.zig"), + .serve = @import("serve.zig"), .run = @import("run.zig"), .perf = @import("perf.zig"), .probe = @import("probe.zig"), @@ -19,6 +20,7 @@ const usage = \\ \\ record run a program under ptrace into a recording \\ dbg debug a program, recording it: step, break, look, go back + \\ serve debugger controller for the native GUI (JSON replies) \\ run record a program that carries a ring producer (agent, instrumentation) \\ perf record what the kernel sees of a program at full speed (perf events) \\ probe ... with BPF programs on syscalls, scheduling, kprobes, uprobes, USDT (root) diff --git a/src/cli/serve.zig b/src/cli/serve.zig new file mode 100644 index 0000000..2361a2f --- /dev/null +++ b/src/cli/serve.zig @@ -0,0 +1,136 @@ +//! A single ptrace owner; std.Io reads commands concurrently into a bounded mailbox. +const std = @import("std"); +const zt = @import("ztrace"); +const util = @import("util.zig"); +const linux = std.os.linux; +pub const usage = "usage: ztrace serve OUTPUT -- PROGRAM [ARGS]\n"; + +const Server = struct { + io: std.Io, + gpa: std.mem.Allocator, + input: std.Io.File, + queue: std.Io.Queue([]u8), + writer: *std.Io.Writer, + rec: *zt.Recorder, + closing: bool = false, + + fn read(s: *Server) void { + defer s.queue.close(s.io); + var buf: [4096]u8 = undefined; + var reader = s.input.readerStreaming(s.io, &buf); + while (true) { + const line = (reader.interface.takeDelimiter('\n') catch return) orelse return; + const owned = s.gpa.dupe(u8, line) catch return; + s.queue.putOne(s.io, owned) catch { + s.gpa.free(owned); + return; + }; + } + } + + fn reply(s: *Server, d: *zt.Debugger, status: zt.control.Status, reason: []const u8, elapsed: u64) !void { + try zt.control.send(s.writer, .{ .status = status, .pid = d.proc.pid, .tid = @intCast(d.proc.tid), .moments = s.rec.moments, .pc = d.regs.rip, .reason = reason, .elapsed_ns = elapsed }); + } + + fn waiting(ctx: *anyopaque, d: *zt.Debugger) !void { + const s: *Server = @ptrCast(@alignCast(ctx)); + var lines: [1][]u8 = undefined; + const n = s.queue.get(s.io, &lines, 0) catch |err| switch (err) { + error.Closed => { + s.closing = true; + try d.interrupt(); + return; + }, + else => return err, + }; + if (n == 0) return; + defer s.gpa.free(lines[0]); + const line = std.mem.trim(u8, lines[0], " \r\t"); + if (std.mem.eql(u8, line, "pause") or std.mem.eql(u8, line, "quit")) { + s.closing = std.mem.eql(u8, line, "quit"); + try d.interrupt(); + } else try s.reply(d, .running, "pause before changing the target", 0); + } +}; + +pub fn run(init: std.process.Init, args: []const [:0]const u8) !void { + if (args.len < 3 or !std.mem.eql(u8, args[1], "--")) util.fail(usage, .{}); + // Keep the protocol off the target's stdio, and close its copies on exec. + const input = try duplicate(0); + defer input.close(init.io); + const output = try duplicate(1); + defer output.close(init.io); + const null_file = try std.Io.Dir.cwd().openFile(init.io, "/dev/null", .{}); + defer null_file.close(init.io); + if (linux.errno(linux.dup2(null_file.handle, 0)) != .SUCCESS or linux.errno(linux.dup2(2, 1)) != .SUCCESS) return error.RedirectFailed; + var outbuf: [4096]u8 = undefined; + var writer = output.writerStreaming(init.io, &outbuf); + var rec = try zt.Recorder.create(init.gpa, init.io, args[0]); + defer rec.close() catch {}; + rec.cut &= ~zt.Kind.line.bit(); + var d = try zt.Debugger.spawn(init.gpa, init.io, try util.resolve(init, args[2]), try util.targetArgv(init.arena.allocator(), args[2..]), init.minimal.environ.block.slice.ptr, rec.sink()); + defer d.deinit(); + d.disasm = @import("disasm.zig").one; + d.syms.demangle = util.demangle; + d.stack_watch = 512; + d.disasm_around = 24; + d.telescope = 2; + var storage: [16][]u8 = undefined; + var server: Server = .{ .io = init.io, .gpa = init.gpa, .input = input, .queue = .init(&storage), .writer = &writer.interface, .rec = &rec }; + var reader = try std.Io.concurrent(init.io, Server.read, .{&server}); + defer { + reader.cancel(init.io); + var remaining: [16][]u8 = undefined; + const n = server.queue.get(init.io, &remaining, 0) catch 0; + for (remaining[0..n]) |line| init.gpa.free(line); + } + d.on_wait = .{ .ctx = &server, .func = Server.waiting }; + try rec.flush(); + try server.reply(&d, .stopped, "entry; set a breakpoint or continue", 0); + while (!server.closing) { + const line = server.queue.getOne(init.io) catch break; + defer init.gpa.free(line); + var words = std.mem.tokenizeAny(u8, line, " \t\r"); + const cmd = words.next() orelse continue; + if (std.mem.eql(u8, cmd, "quit")) break; + const started = std.Io.Clock.awake.now(init.io); + var reason_buf: [128]u8 = undefined; + const reason = execute(&d, &server, cmd, std.mem.trim(u8, words.rest(), " \t\r"), &reason_buf) catch |err| { + try server.reply(&d, if (d.done) .exited else .failed, @errorName(err), 0); + continue; + }; + try rec.flush(); + const elapsed: u64 = @intCast(started.durationTo(std.Io.Clock.awake.now(init.io)).toNanoseconds()); + try server.reply(&d, if (d.done) .exited else .stopped, reason, elapsed); + } +} + +fn execute(d: *zt.Debugger, s: *Server, cmd: []const u8, arg: []const u8, buf: []u8) ![]const u8 { + if (std.mem.eql(u8, cmd, "break")) { + const id = try d.breakAt(try d.resolve(arg), null); + return std.fmt.bufPrint(buf, "breakpoint {d} set", .{id}); + } else if (std.mem.eql(u8, cmd, "clear")) { + d.clear(try std.fmt.parseInt(u32, arg, 0)); + } else if (std.mem.eql(u8, cmd, "signal")) { + const sig = try std.fmt.parseInt(u32, arg, 0); + if (sig > 64) return error.InvalidSignal; + d.proc.resume_signal = sig; + } else if (std.mem.eql(u8, cmd, "continue") or std.mem.eql(u8, cmd, "stepi") or std.mem.eql(u8, cmd, "step")) { + try s.reply(d, .running, cmd, 0); + const stop = if (std.mem.eql(u8, cmd, "continue")) try d.cont() else if (std.mem.eql(u8, cmd, "stepi")) try d.stepi() else try d.step(); + return switch (stop) { + .breakpoint => |id| std.fmt.bufPrint(buf, "breakpoint {d}", .{id}), + .signal => |sig| std.fmt.bufPrint(buf, "signal {t} ({d})", .{ sig, @backingInt(sig) }), + .exited => |code| std.fmt.bufPrint(buf, "exited {d}", .{code}), + .killed => |sig| std.fmt.bufPrint(buf, "killed {t}", .{sig}), + else => @tagName(stop), + }; + } else if (!std.mem.eql(u8, cmd, "pause")) return error.UnknownCommand; + return cmd; +} + +fn duplicate(fd: linux.fd_t) !std.Io.File { + const rc = linux.fcntl(fd, linux.F.DUPFD_CLOEXEC, 3); + if (linux.errno(rc) != .SUCCESS) return error.DuplicateFailed; + return .{ .handle = @intCast(rc), .flags = .{ .nonblocking = false } }; +} diff --git a/src/trace/Debugger.zig b/src/trace/Debugger.zig index 729b93a..9368a42 100644 --- a/src/trace/Debugger.zig +++ b/src/trace/Debugger.zig @@ -51,6 +51,9 @@ syscalls: enum { ignore, record, stop } = .ignore, /// Called at each syscall's entry and exit unless they are ignored; it /// decides whether the target stops there. on_syscall: ?Hook = null, +/// A controller's mailbox, serviced while waiting without moving ptrace to another thread. +on_wait: ?struct { ctx: *anyopaque, func: *const fn (*anyopaque, *Debugger) anyerror!void } = null, +interrupt_sent: bool = false, /// Bytes above the stack pointer watched at every stop. stack_watch: usize = 0, /// The most captured of what a syscall points at: a path, the buffer of a @@ -122,7 +125,7 @@ threads: std.AutoHashMapUnmanaged(linux.pid_t, void) = .empty, /// String ids of source files: by path, and by line-table entry. files: std.StringHashMapUnmanaged(u64) = .empty, file_ids: std.AutoHashMapUnmanaged(usize, u64) = .empty, -last_line: struct { file: u64 = 0, line: u32 = 0 } = .{}, +last_line: struct { file: u64 = 0, line: u32 = 0, tid: linux.pid_t = 0 } = .{}, pub const Stop = union(enum) { /// `stepi` or `step` finished. @@ -259,14 +262,14 @@ fn inVdso(d: *const Debugger, addr: u64) bool { /// To the next source line: instructions until the line is another, a call /// into code without lines (a library) run through as one. pub fn step(d: *Debugger) !Stop { - const from = d.lineAt(d.regs.rip); + const from = d.lineAt(d.regs.rip) orelse return d.stepi(); const tid = d.proc.tid; while (true) { const before = d.regs; var stop = try d.stepOne(); if (stop == .step and d.proc.tid == tid) { if (d.lineAt(d.regs.rip)) |here| { - if (from == null or from.?.key != here.key or from.?.line != here.line or d.breakpointAt(d.regs.rip) != null) return d.report(.step); + if (from.key != here.key or from.line != here.line or d.breakpointAt(d.regs.rip) != null) return d.report(.step); continue; } // In code without lines. A call there from code with lines @@ -324,20 +327,29 @@ fn waitAny(d: *Debugger) !ptrace.Stop { /// The next stop. With a ring it is polled for and the ring drained /// meanwhile: a target waiting for room in a full ring would never stop. fn wait(d: *Debugger, tid: linux.pid_t) !ptrace.Stop { - const ring = d.ring orelse return d.proc.wait(tid); + if (d.ring == null and d.on_wait == null) return d.proc.wait(tid); const tapped: event.Sink = .{ .ctx = d, .emitFn = tap }; var idle: u32 = 0; while (true) { + if (d.on_wait) |hook| try hook.func(hook.ctx, d); if (try d.proc.poll(tid)) |stop| { - _ = try ring.drain(tapped); + if (d.ring) |ring| _ = try ring.drain(tapped); return stop; } // A step is back in microseconds: look again before sleeping. - idle = if (try ring.drain(tapped) > 0) 0 else idle + 1; - if (idle > 64) ring.wait(200 * std.time.ns_per_us); + const drained = if (d.ring) |ring| try ring.drain(tapped) else 0; + idle = if (drained > 0) 0 else idle +| 1; + if (idle > 64) try std.Io.sleep(d.syms.io, .fromMicroseconds(200), .awake); } } +/// Request a stop from the owning controller's wait hook. Our SIGSTOP is not redelivered. +pub fn interrupt(d: *Debugger) !void { + if (d.done or d.interrupt_sent) return; + if (linux.errno(linux.tgkill(d.proc.pid, d.proc.tid, .STOP)) != .SUCCESS) return error.InterruptFailed; + d.interrupt_sent = true; +} + /// What the target says of itself goes to the sink as it is; and a /// variable it declares (`ztrace cc --instr vars`, the agent's /// `ztrace_watch`) is watched from then on, so its bytes are recorded at @@ -424,6 +436,11 @@ fn run(d: *Debugger, request: u32) !Stop { .exited, .killed => unreachable, .clone => |child| try d.emit(.{ .kind = .thread_start, .a = .{ @intCast(child), 0, 0, 0, 0, 0 } }, std.mem.asBytes(&d.regs)), .signal => |sig| { + if (sig == .STOP and d.interrupt_sent) { + d.interrupt_sent = false; + d.proc.resume_signal = 0; + return .{ .signal = sig }; + } // A thread's first stop is the SIGSTOP it is born with under tracing. if (!born or sig != .STOP) return .{ .signal = sig }; d.proc.resume_signal = 0; @@ -518,6 +535,8 @@ fn emit(d: *Debugger, ev: Event, payload: []const u8) !void { fn report(d: *Debugger, stop: Stop) !Stop { if (d.sink == null) return stop; if (!d.done) { + // Code loaded or JIT-compiled while running without syscall stops. + if (d.syms.mappingAt(d.regs.rip) == null) try d.refreshMaps(); try d.emitLine(); if (d.asan and d.asan_shadow == null) try d.findShadow(); // With the 128 bytes under the stack pointer: the red zone, a leaf's locals. @@ -955,11 +974,13 @@ fn fileId(d: *Debugger, l: Symbols.Line) !u64 { } fn emitLine(d: *Debugger) !void { - const l = d.lineAt(d.regs.rip) orelse return; - const file = try d.fileId(l); - if (file == d.last_line.file and l.line == d.last_line.line) return; - d.last_line = .{ .file = file, .line = l.line }; - try d.emit(.{ .kind = .line, .a = .{ file, l.line, l.column, d.regs.rip, 0, 0 } }, ""); + const l = d.lineAt(d.regs.rip); + const file = if (l) |loc| try d.fileId(loc) else 0; + const line = if (l) |loc| loc.line else 0; + if (file == d.last_line.file and line == d.last_line.line and (d.proc.tid == d.last_line.tid or d.last_line.tid == 0)) return; + d.last_line = .{ .file = file, .line = line, .tid = d.proc.tid }; + // File zero clears a native source location when entering code without lines (including JIT code). + try d.emit(.{ .kind = .line, .a = .{ file, line, if (l) |loc| loc.column else 0, d.regs.rip, 0, 0 } }, ""); } /// Reads the target's mappings again: what changed goes out as `map` and diff --git a/src/trace/control.zig b/src/trace/control.zig new file mode 100644 index 0000000..1bfad4c --- /dev/null +++ b/src/trace/control.zig @@ -0,0 +1,29 @@ +//! Small control messages shared by a debugger controller and its clients. +const std = @import("std"); + +pub const Status = enum { stopped, running, exited, failed }; +pub const Reply = struct { + status: Status, + pid: i32, + tid: u32, + moments: u64, + pc: u64, + elapsed_ns: u64 = 0, + reason: []const u8 = "", +}; + +pub fn send(w: *std.Io.Writer, reply: Reply) !void { + try std.json.Stringify.value(reply, .{}, w); + try w.writeByte('\n'); + try w.flush(); +} + +test "control messages preserve 64-bit addresses" { + var buf: [512]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + const value: Reply = .{ .status = .stopped, .pid = 1, .tid = 2, .moments = 3, .pc = 0xffffffffffffffff }; + try send(&w, value); + const parsed = try std.json.parseFromSlice(Reply, std.testing.allocator, w.buffered(), .{}); + defer parsed.deinit(); + try std.testing.expectEqual(value.pc, parsed.value.pc); +} diff --git a/src/trace/debugger_test.zig b/src/trace/debugger_test.zig index 66174fc..22b9718 100644 --- a/src/trace/debugger_test.zig +++ b/src/trace/debugger_test.zig @@ -10,6 +10,38 @@ const gpa = std.testing.allocator; const io = std.testing.io; const no_env = [_:null]?[*:0]const u8{null}; +test "source step without a source location advances one instruction" { + var d = try spawn(targets.fib_nolines, "10", null); + defer d.deinit(); + const id = try d.breakAt(try d.resolve("fib"), null); + try std.testing.expectEqual(id, (try d.cont()).breakpoint); + try std.testing.expect(d.lineAt(d.regs.rip) == null); + const before = d.regs.rip; + try std.testing.expectEqual(Debugger.Stop.step, try d.step()); + try std.testing.expect(d.regs.rip != before); +} + +test "a controller can interrupt a running target and step without redelivering SIGSTOP" { + var d = try spawn(targets.fib, "40", null); + defer d.deinit(); + const id = try d.breakAt(try d.resolve("fib"), null); + try std.testing.expectEqual(id, (try d.cont()).breakpoint); + d.clear(id); + var called = false; + d.on_wait = .{ .ctx = &called, .func = struct { + fn interrupt(ctx: *anyopaque, target: *Debugger) !void { + const flag: *bool = @ptrCast(@alignCast(ctx)); + flag.* = true; + try target.interrupt(); + } + }.interrupt }; + try std.testing.expectEqual(linux.SIG.STOP, (try d.cont()).signal); + try std.testing.expect(called); + try std.testing.expectEqual(@as(u32, 0), d.proc.resume_signal); + d.on_wait = null; + try std.testing.expectEqual(Debugger.Stop.step, try d.stepi()); +} + /// Starts a target with its stdout going nowhere: this process's own is the /// test runner's channel to the build. fn spawn(path: []const u8, arg: ?[*:0]const u8, sink: ?zt.Sink) !Debugger { diff --git a/src/trace/event.zig b/src/trace/event.zig index 2900be7..f56d0f5 100644 --- a/src/trace/event.zig +++ b/src/trace/event.zig @@ -59,7 +59,7 @@ pub const Kind = enum(u16) { /// a0=callee a1=return value. aux: how many bytes of a1 are the value /// (0: none, or not known) ret = 33, - /// a0=file string id a1=line a2=column a3=pc (0: not given) + /// a0=file string id (0 clears the location) a1=line a2=column a3=pc (0: not given) line = 34, /// a0=pc (a coverage edge) edge = 35, diff --git a/src/trace/root.zig b/src/trace/root.zig index ef684db..a64f173 100644 --- a/src/trace/root.zig +++ b/src/trace/root.zig @@ -14,6 +14,7 @@ pub const telescope = @import("telescope.zig"); /// glibc's malloc at a moment: chunks, tcache, bins, the top. pub const heap = @import("heap.zig"); pub const Debugger = @import("Debugger.zig"); +pub const control = @import("control.zig"); pub const Symbols = @import("Symbols.zig"); pub const syscalls = @import("syscalls.zig"); /// Inside the target: the ring it was handed. @@ -35,6 +36,7 @@ test { _ = telescope; _ = heap; _ = Debugger; + _ = control; _ = Symbols; _ = syscalls; _ = client; diff --git a/src/trace/store.zig b/src/trace/store.zig index e4546c2..b40a1fc 100644 --- a/src/trace/store.zig +++ b/src/trace/store.zig @@ -803,7 +803,9 @@ pub const Moment = struct { } pub fn line(m: Moment, tid: u32) !?Line { - return if ((try m.state()).threads.get(tid)) |t| t.line else null; + const t = (try m.state()).threads.get(tid) orelse return null; + const loc = t.line orelse return null; + return if (loc.file == 0) null else loc; } /// The calls a thread is inside, outermost first. @@ -1174,3 +1176,22 @@ test "a region written again costs what changed in it" { try (try trace.moment(1000)).read(0x10000, &back, null); try std.testing.expectEqualSlices(u8, &page, &back); } + +test "a cleared source line stays cleared across keyframes" { + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try testPath(gpa, &tmp); + defer gpa.free(path); + var rec = try Recorder.create(gpa, std.testing.io, path); + rec.batch = 1; + try rec.emit(testEvent(.line, 1, .{ 9, 12, 5, 0, 0, 0 }), ""); + try rec.emit(testEvent(.line, 1, @splat(0)), ""); + try rec.emit(testEvent(.mark, 1, @splat(0)), ""); + try rec.close(); + var trace = try Trace.open(gpa, std.testing.io, path); + defer trace.close(); + try std.testing.expect((try (try trace.moment(2)).line(1)) == null); + try std.testing.expect((try (try trace.moment(1)).line(1)) == null); + try std.testing.expectEqual(Line{ .file = 9, .line = 12, .column = 5 }, (try (try trace.moment(0)).line(1)).?); +} |
