Ghidrust provides a hyper fast, AI native reverse engineering platform built in Rust, inspired by Ghidra. Includes experimental GPU kernels to rapidly decompile large files, a decryption suite, and network monitor for packet to binary reverse engineering.
Add `ghidrust-agent` crate and enhance CLI with new commands for string lookups, cross-references, and imports. Update README for improved clarity on agent capabilities. Modify `.gitignore` to exclude cursor files. Enhance JSON output for string and function queries, ensuring BOM-free output. Update tests to validate new functionality.
oofz4b2dd134d2bf
diff --git a/.gitignore b/.gitignoreindex d8ef8a2..1ddea20 100644--- a/.gitignore+++ b/.gitignore@@ -7,6 +7,7 @@.idea/.vscode/.grok/+.cursor/terminals/mcps/diff --git a/Cargo.lock b/Cargo.lockindex 427cf5c..ad501d9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1312,6 +1312,14 @@ dependencies = ["r-efi 6.0.0",]+[[package]]+name = "ghidrust-agent"+version = "0.1.0"+dependencies = [+ "serde",+ "serde_json",+]+[[package]]name = "ghidrust-cli"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 58f6530..4f2fe65 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -11,6 +11,7 @@ members = ["crates/ghidrust-decomp","crates/ghidrust-cli","crates/ghidrust-gui",+ "crates/ghidrust-agent",]default-members = ["crates/ghidrust-cli"]@@ -29,3 +30,4 @@ ghidrust-types = { path = "crates/ghidrust-types" }ghidrust-structure = { path = "crates/ghidrust-structure" }ghidrust-core = { path = "crates/ghidrust-core" }ghidrust-decomp = { path = "crates/ghidrust-decomp" }+ghidrust-agent = { path = "crates/ghidrust-agent" }diff --git a/README.md b/README.mdindex e5db9c1..0782d64 100644--- a/README.md+++ b/README.md@@ -16,7 +16,7 @@ It is **not** a Ghidra fork or wrapper. Analysis logic (loaders, decode, analyze| **Ghidra-shaped workflow** | Familiar labels and surfaces (Auto Analysis names, project import/analyze/export, listing + click FUN → decompile) without depending on the Ghidra JVM stack || **Hand-rolled core** | PE/ELF, x86-64 decode, RTTI, analyzers, and the IR → SSA → structure → typed-C pipeline implemented in Rust — third-party RE libraries are avoided at runtime ([DEPENDENCIES.md](DEPENDENCIES.md)); Ghidra sources are reference-only || **CPU-correct first** | CPU paths are the oracle; optional GPU paths must match or enrich them, not replace honesty with speed claims |-| **Agent-ready** | Headless CLI + stdio MCP so coding agents can load, disassemble, analyze, and decompile without a GUI |+| **Agent-ready** | Headless CLI + stdio MCP so coding agents can load, disassemble, analyze, look up strings/xrefs/imports/functions, and decompile without a GUI or ad-hoc PE scripts || **Practical projects** | Create a workspace, import binaries, run analyzers, persist results (`analysis.bin`), reopen later |**Current maturity (Phase F, pcode-parity plan):** **Stage-1 is the product default** on CLI, GUI, and MCP. It runs the full hand-rolled pipeline: `ghidrust-ssa` builds CFG + dominators + Cytron phi placement + rename + copy/const/load-store propagation + DCE; `ghidrust-structure` recovers gotoless `if`/`while`/`do-while`/`loop`/`switch`/short-circuit regions with `break;` / `continue;` inside natural loops (goto rate <0.15 on lab fixture); `ghidrust-types` supplies a lattice covering `Bool` / `IntN` / `IntSigned` / `Ptr` / `StructPtr` / `ArrayPtr` / `Void` / `Any`, recovers return type + Windows/SysV prototypes (register + stack params), stack locals, and struct/array pointer seeds from load/store patterns rendered as `p->field_<off>` / `p[i]`. **Stage-0** (`decompile --stage0`) and **Stage-0.5** (`--stage05`) remain as regression oracles; the Phase-E head-to-head oracle enforces a shared-entry set and Stage-1-vs-Ghidra normalized-token similarity metric so no unfair comparison ships. **Never fabricates C**: irreducible regions or lift ratios <50% — again, no fabricated C. Head-to-head timings against Ghidra headless are captured (never fabricated) via `ghidrust ghidra-headtohead` and [`docs/GHIDRA_HEADTOHEAD.md`](docs/GHIDRA_HEADTOHEAD.md). Hex-Rays-class quality remains a later phase after the Ghidra bar is met. **Non-goals (today):** multi-ISA SLEIGH runtime, switch-statement structuring, debugger integration, or "GPU is always faster."@@ -92,11 +92,17 @@ cargo run -p ghidrust-cli --release -- help./target/release/ghidrust load fixtures/tiny_x64.pe./target/release/ghidrust disasm fixtures/tiny_x64.pe --count 16+# Lookups (no helper scripts required)+./target/release/ghidrust strings fixtures/analysis_lab.pe --encoding all --filter WideLab --json+./target/release/ghidrust xrefs fixtures/analysis_lab.pe --string ExitProcess --json+./target/release/ghidrust imports fixtures/analysis_lab.pe --json+./target/release/ghidrust function-at fixtures/analysis_lab.pe --addr 0x140001004 --json+# Auto Analysis./target/release/ghidrust analyzers./target/release/ghidrust analyze fixtures/analysis_lab.pe --analyzers "Function ID,Stack" --json-# CPU vs experimental GPU decompile+# CPU (Stage-1 default) vs experimental GPU decompile./target/release/ghidrust decompile fixtures/tiny_x64.pe./target/release/ghidrust gpu-decompile fixtures/tiny_x64.pe --out entry.gdecomp --metrics metrics.log --json@@ -104,9 +110,9 @@ cargo run -p ghidrust-cli --release -- helpcargo run -p ghidrust-gui --release```-Windows PowerShell: use `.\target\release\ghidrust.exe` and `.\target\release\ghidrust-gui.exe`.+Windows PowerShell: use `.\target\release\ghidrust.exe` and `.\target\release\ghidrust-gui.exe`. `--json` stdout is UTF-8 **without BOM** (safe for `ConvertFrom-Json`).-Fixtures live under [`fixtures/`](fixtures/) (`tiny_x64.pe`, `analysis_lab.pe`, `tiny_x64.elf`).+Fixtures live under [`fixtures/`](fixtures/) (`tiny_x64.pe`, `analysis_lab.pe`, `tiny_x64.elf`, plus `decode_continuity.bin` for disasm `--skip-bad` tests). They are **committed test corpus** — keep them in git; put large private samples under gitignored `dev/`.---@@ -126,7 +132,7 @@ Auto Analysis screenshot Ghidra ships with. Outputs are honest: no fabricatedsymbols, no Hex-Rays / Ghidra C mimicry — you get structured JSON fields plusone human-readable status line per analyzer.-### Auto Analysis (20)+### Auto Analysis (21)Common invocation shapes:@@ -140,41 +146,72 @@ inside `analysis.results[*]` in `--json` output).| # | Name (exact) | What it does | `--json` output fields | Human message ||---|---|---|---|---|-| 1 | `ASCII Strings` | Bulk scan of executable + data blocks for ≥4-char printable ASCII runs using the preferred bulk backend (Sequential / ParallelCpu / GpuOrFallback). | `strings: [{va, value, length}]` | `found N ASCII string(s) [BulkScanMode…]` |-| 2 | `Aggressive Instruction Finder` | Fills real code gaps (bytes not covered by any known function): validates a decodable prologue-shaped run, adds new `FunctionInfo` and a `DiscoveredRange`. Never fabricates when there is no gap. | `recovered_ranges: [{start, end}]` (+ new entries in `functions`) | `found N recovered code range(s)` |-| 3 | `Call Convention ID` | Tags every discovered function with a calling-convention heuristic (Win64 x64 default, cdecl / stdcall / thiscall fallbacks). | `conventions: [[va, name], …]` (+ `functions[*].calling_convention`) | `identified N calling convention(s)` |-| 4 | `Call-Fixup Installer` | Detects Windows security cookie / import-thunk stubs and records a fixup entry with the stub VA. | `call_fixups: [{fixup_name, call_va}]` | `installed N call fixup(s)` |-| 5 | `Create Address Tables` | Recovers jump/vtable-style contiguous VA tables inside `.rdata`/data and lists their entries. | `address_tables: [{base, count, entries: [va,…]}]` | `found N address table(s)` |-| 6 | `Decompiler Parameter ID` | Scans each function for arg-register spills (`mov [rbp+…], rcx/rdx/…`) and attaches typed `arg0:rcx` / `arg1:rdx` slots — no invented parameters on bare bodies. | `functions: [{entry, parameters: ["arg0:rcx", …]}]` | `recovered parameters for N function(s)` |-| 7 | `Decompiler Switch Analysis` | Turns jump-table address tables into switch structures with `(case_value, target_va)` pairs. | `switches: [{jump_va, cases: [[val, target], …]}]` | `recovered N switch table(s)` |-| 8 | `Demangler Microsoft` | Parses PE symbols in the MSVC (`?...@@`) mangling scheme, records demangled name alongside the raw symbol. | `symbols: [{name, va, demangled?}]` | `demangled N symbol(s)` |-| 9 | `Embedded Media` | Scans data for well-known magic prefixes (PNG, JPG, GIF, WAV, …) and records their VA + kind. | `media: [{kind, va}]` | `found N media signature(s)` |-| 10 | `Function ID` | Hashes each function's prologue window and matches it against the shipped FID catalog (`fid_*` names). | `fid_matches: [{entry, matched_name}]` | `matched N FID signature(s)` |-| 11 | `Function Start Search` | Seeds functions from entry, symbol table, exact `55 48 89 e5` prologues, and orphan `sub rsp, imm8` starts. Grows each until `ret`/`int3`. Drops mid-body seeds. | `functions: [{entry, end, name}]` | `identified N function start(s)` |-| 12 | `Non-Returning Functions - Discovered` | Marks functions ending in `int3` without a `ret`, plus known no-return imports (`ExitProcess`, `abort`, …). | `noreturn_entries: [va, …]` (+ `functions[*].noreturn`) | `marked N noreturn function(s)` |-| 13 | `PDB MSDIA` | Portable PDB (MSF7) reader tuned to the MSDIA symbol shapes (`S_PUB32`, `S_GPROC32` names). | `symbols: [{name, va}]` | `parsed N PDB symbol(s) (msdia→universal)` |-| 14 | `PDB Universal` | Same MSF7 reader without MSDIA-specific filtering — surfaces every stream symbol it can find (`MSF7` marker included as a sentinel symbol). | `symbols: [{name, va}]` | `parsed N PDB symbol(s) (universal)` |-| 15 | `Shared Return Calls` | Finds sites where multiple callers reuse the same epilogue block (tail-call / shared-return pattern). | `shared_returns: [va, …]` | `marked N shared return site(s)` |-| 16 | `Stack` | Per-function frame recovery: reads `sub rsp, imm` / `push rbp; mov rbp, rsp` to compute `frame_size=0x…`, then attaches `param_…` slots. Won't pollute functions that have no real frame. | `stack_frames: [[va, ["frame_size=0x20", "param_rcx@0x8", …]], …]` | `recovered N stack frame(s)` |-| 17 | `Variadic Function Signature Override` | Ensures API symbols matching `printf` / `sprintf` / `scanf` families exist, tags them `varargs=true` cdecl and gives them a `format` param. | `varargs_entries: [va, …]` (+ `functions[*].varargs`) | `applied varargs to N function(s)` |-| 18 | `WindowsPE x86 PE RTTI Analyzer` | MSVC C++ RTTI recovery: locates COL / class-hierarchy / type-info descriptors, links them to vtables, extracts demangled class names. | `rtti: {classes: [{name, type_info_va, vtable_va, col_va, kind}], notes: [str,…]}` | `recovered N RTTI class record(s)` |-| 19 | `Windows x86 Propagate External Parameters` | Applies known prototypes to imported Windows APIs (`ExitProcess(UINT)`, `GetProcAddress`, …) so calls resolve typed args. | `external_params: [[va, prototype], …]` | `applied N external parameter prototype(s)` |-| 20 | `WindowsResourceReference` | Parses `.rsrc` and records resource records (`VERSION`, `RT_ICON`, …) with their VA. | `resources: [{name, va}]` | `parsed N resource record(s)` |--Defaults (empty `--analyzer` list): **ASCII Strings**, **WindowsPE x86 PE RTTI Analyzer**, **Function Start Search**, **Create Address Tables**, **Embedded Media**, **Demangler Microsoft**.+| 1 | `ASCII Strings` | Bulk scan of executable + data blocks for ≥4-char printable ASCII runs using the preferred bulk backend (Sequential / ParallelCpu / GpuOrFallback). | `strings: [{va, value, length, encoding: "ascii"}]` | `found N ASCII string(s) [BulkScanMode…]` |+| 2 | `Unicode Strings` | UTF-16LE printable runs across mapped blocks (even-aligned, NUL-terminated, mostly-ASCII wide strings). Also available via `ghidrust strings --encoding utf16`. | `strings: [{va, value, length, encoding: "utf16le"}]` | `found N UTF-16LE string(s)` |+| 3 | `Aggressive Instruction Finder` | Fills real code gaps (bytes not covered by any known function): validates a decodable prologue-shaped run, adds new `FunctionInfo` and a `DiscoveredRange`. Never fabricates when there is no gap. | `recovered_ranges: [{start, end}]` (+ new entries in `functions`) | `found N recovered code range(s)` |+| 4 | `Call Convention ID` | Tags every discovered function with a calling-convention heuristic (Win64 x64 default, cdecl / stdcall / thiscall fallbacks). | `conventions: [[va, name], …]` (+ `functions[*].calling_convention`) | `identified N calling convention(s)` |+| 5 | `Call-Fixup Installer` | Detects Windows security cookie / import-thunk stubs and records a fixup entry with the stub VA. | `call_fixups: [{fixup_name, call_va}]` | `installed N call fixup(s)` |+| 6 | `Create Address Tables` | Recovers jump/vtable-style contiguous VA tables inside `.rdata`/data and lists their entries. | `address_tables: [{base, count, entries: [va,…]}]` | `found N address table(s)` |+| 7 | `Decompiler Parameter ID` | Scans each function for arg-register spills (`mov [rbp+…], rcx/rdx/…`) and attaches typed `arg0:rcx` / `arg1:rdx` slots — no invented parameters on bare bodies. | `functions: [{entry, parameters: ["arg0:rcx", …]}]` | `recovered parameters for N function(s)` |+| 8 | `Decompiler Switch Analysis` | Turns jump-table address tables into switch structures with `(case_value, target_va)` pairs. | `switches: [{jump_va, cases: [[val, target], …]}]` | `recovered N switch table(s)` |+| 9 | `Demangler Microsoft` | Parses PE symbols in the MSVC (`?...@@`) mangling scheme, records demangled name alongside the raw symbol. | `symbols: [{name, va, demangled?}]` | `demangled N symbol(s)` |+| 10 | `Embedded Media` | Scans data for well-known magic prefixes (PNG, JPG, GIF, WAV, …) and records their VA + kind. | `media: [{kind, va}]` | `found N media signature(s)` |+| 11 | `Function ID` | Hashes each function's prologue window and matches it against the shipped FID catalog (`fid_*` names). | `fid_matches: [{entry, matched_name}]` | `matched N FID signature(s)` |+| 12 | `Function Start Search` | Seeds functions from entry, symbol table, exact `55 48 89 e5` prologues, and orphan `sub rsp, imm8` starts. Grows each body (skips small decode holes) until `ret`. Drops mid-body seeds. Prefer `ghidrust function-at` to map a VA → containing function. | `functions: [{entry, end, name}]` | `identified N function start(s)` |+| 13 | `Non-Returning Functions - Discovered` | Marks functions ending in `int3` without a `ret`, plus known no-return imports (`ExitProcess`, `abort`, …). | `noreturn_entries: [va, …]` (+ `functions[*].noreturn`) | `marked N noreturn function(s)` |+| 14 | `PDB MSDIA` | Portable PDB (MSF7) reader tuned to the MSDIA symbol shapes (`S_PUB32`, `S_GPROC32` names). | `symbols: [{name, va}]` | `parsed N PDB symbol(s) (msdia→universal)` |+| 15 | `PDB Universal` | Same MSF7 reader without MSDIA-specific filtering — surfaces every stream symbol it can find (`MSF7` marker included as a sentinel symbol). | `symbols: [{name, va}]` | `parsed N PDB symbol(s) (universal)` |+| 16 | `Shared Return Calls` | Finds sites where multiple callers reuse the same epilogue block (tail-call / shared-return pattern). | `shared_returns: [va, …]` | `marked N shared return site(s)` |+| 17 | `Stack` | Per-function frame recovery: reads `sub rsp, imm` / `push rbp; mov rbp, rsp` to compute `frame_size=0x…`, then attaches `param_…` slots. Won't pollute functions that have no real frame. | `stack_frames: [[va, ["frame_size=0x20", "param_rcx@0x8", …]], …]` | `recovered N stack frame(s)` |+| 18 | `Variadic Function Signature Override` | Ensures API symbols matching `printf` / `sprintf` / `scanf` families exist, tags them `varargs=true` cdecl and gives them a `format` param. | `varargs_entries: [va, …]` (+ `functions[*].varargs`) | `applied varargs to N function(s)` |+| 19 | `WindowsPE x86 PE RTTI Analyzer` | MSVC C++ RTTI recovery: locates COL / class-hierarchy / type-info descriptors, links them to vtables, extracts demangled class names. | `rtti: {classes: [{name, type_info_va, vtable_va, col_va, kind}], notes: [str,…]}` | `recovered N RTTI class record(s)` |+| 20 | `Windows x86 Propagate External Parameters` | Applies known prototypes to imported Windows APIs (`ExitProcess(UINT)`, `GetProcAddress`, …) so calls resolve typed args. | `external_params: [[va, prototype], …]` | `applied N external parameter prototype(s)` |+| 21 | `WindowsResourceReference` | Parses `.rsrc` and records resource records (`VERSION`, `RT_ICON`, …) with their VA. | `resources: [{name, va}]` | `parsed N resource record(s)` |++Defaults (empty `--analyzer` list): **ASCII Strings**, **Unicode Strings**, **WindowsPE x86 PE RTTI Analyzer**, **Function Start Search**, **Create Address Tables**, **Embedded Media**, **Demangler Microsoft**.Notes:- `--gpu` on `analyze` runs each selected CPU analyzer, then per-analyzer GPU seed kernels; the CPU output above is unchanged, but the human message is appended with `gpu_enrich hits_merged=… backend=…`.-- Every entry above is a **PASS** in [`dev/EVAL_ANALYSIS_DECOMPILE_REPORT.md`](dev/EVAL_ANALYSIS_DECOMPILE_REPORT.md); the `analysis_lab.pe` / `tiny_x64.pe` fixtures pin known VAs (e.g. `printf@0x140002010`, `PNG@0x140002050`, `VERSION@0x140002090`, `Widget` RTTI class).+- Every entry above is a **PASS** in [`dev/EVAL_ANALYSIS_DECOMPILE_REPORT.md`](dev/EVAL_ANALYSIS_DECOMPILE_REPORT.md); the `analysis_lab.pe` / `tiny_x64.pe` fixtures pin known VAs (e.g. `printf@0x140002010`, `PNG@0x140002050`, `VERSION@0x140002090`, `WideLabString` UTF-16, `Widget` RTTI class).++### Lookups (CLI + MCP)++First-class commands for the queries agents used to need ad-hoc scripts for. Same capabilities are exposed as MCP tools (see [MCP tools](#3-tools-the-server-exposes)).++| Command | Purpose | Key flags |+|---------|---------|-----------|+| `ghidrust strings <path>` | Scan ASCII and/or UTF-16LE strings | `--encoding ascii\|utf16\|all` (default `all`), `--filter SUB` (substring or `*`/`?` glob), `--min N`, `--json` |+| `ghidrust xrefs <path>` | Cross-references (absolute operand hex **and** RIP-relative `LEA`/`call`/`jmp`) | Exactly one of: `--to HEX`, `--from HEX`, `--string FILTER`, `--import NAME` |+| `ghidrust imports <path>` | PE import directory → DLL + symbol + IAT VA | `--dll NAME`, `--name NAME`, `--json` |+| `ghidrust function-at <path> --addr HEX` | Containing analyzed function for a body VA (runs Function Start Search if needed) | `--json` |+| `ghidrust disasm <path>` | Listing; optional continuity across undecodable bytes | `--addr HEX`, `--count N`, `--skip-bad`, `--json` |++```bash+# Wide + ASCII string search+ghidrust strings app.exe --encoding all --filter Config --json++# Code sites that reference a string (RIP-relative LEA included)+ghidrust xrefs app.exe --string ResolutionWidth --json++# Import call-sites (IAT slot + FF15/RIP refs)+ghidrust imports app.exe --name ShellExecuteW --json+ghidrust xrefs app.exe --import ShellExecuteW --json++# Body VA → function interval+ghidrust function-at app.exe --addr 0x14000d8ad --json++# Keep listing through a decode hole+ghidrust disasm app.exe --addr 0x14000d890 --count 40 --skip-bad+```### Decompile methods| Method | CLI | What it emits | Outputs / where to see them ||---|---|---|---|-| **Stage-1** (**default**) | `ghidrust decompile <path> [--addr HEX] [--count N]` | Full SSA + structure + types Stage-1 emit: recovered return type / SysV or Windows __fastcall prototype, `local_<off>: T` stack locals, `struct s_<key>{ field_<off>: T; }` seeds from load/store patterns rendered as `p->field_<off>` / `p[i]`, `switch { case … }` regions from Decompiler Switch Analysis, compound `&&` / `\|\|` short-circuits, and `break;` / `continue;` inside natural loops (goto rate <0.15 on lab). | stdout: `pseudo_c`. stderr status: `[name] stage=1 blocks=… phis=… loops=… locals=… params=… lift=…%`. `--json`: `{decompile: …, stage1: {loops, phis, locals, params, structs, lift_ratio, goto_rate, return_type, prototype, total_ops}}`. |-| **Stage-0** (oracle) | `ghidrust decompile <path> --stage0 [--addr HEX] [--count N]` | CFG-driven pseudo-C: `void FUN_<va>() { block_0: … goto/return; }` — mnemonic-style scaffolding, no fabricated locals or types. Kept as regression oracle only. | stdout: `pseudo_c`. stderr status: `[name] stage=0 blocks=… edges=… insns=… lines=…`. `--json`: full `Decompile { name, blocks[], edges[], insn_count, pseudo_c }`. |-| **Stage-0.5 IR** (oracle) | `ghidrust decompile <path> --stage05 [--addr HEX] [--count N]` | IR-informed emit from the hand-rolled x86-64 lifter → `ghidrust-ir`: `xor a,a → a=0`, `add/sub/or/and/xor/shl/shr` augmented-assign, `push`/`pop`, direct `call`, flag-driven `jcc`. Falls back to Stage-0 scaffolding for uncovered ops. | stdout: `pseudo_c`. stderr adds `ir_ops=… lift=…%`. `--json`: `{decompile: …, lift_coverage: {total_ops, unimplemented_ops, source_instructions, ratio}}`. |+| **Stage-1** (**default**) | `ghidrust decompile <path> [--addr HEX] [--count N] [--verbose]` | Full SSA + structure + types Stage-1 emit: recovered return type / SysV or Windows __fastcall prototype, `local_<off>: T` stack locals, `struct s_<key>{ field_<off>: T; }` seeds from load/store patterns rendered as `p->field_<off>` / `p[i]`, `switch { case … }` regions from Decompiler Switch Analysis, compound `&&` / `\|\|` short-circuits, and `break;` / `continue;` inside natural loops (goto rate <0.15 on lab). | stdout: `pseudo_c` only (script-friendly). Optional stderr metrics with `--verbose` / `-v`: `[name] stage=1 blocks=…`. `--json`: UTF-8 no BOM `{decompile: …, stage1: {loops, phis, locals, params, lift_ratio, total_ops, …}}`. |+| **Stage-0** (oracle) | `ghidrust decompile <path> --stage0 [--addr HEX] [--count N] [--verbose]` | CFG-driven pseudo-C: `void FUN_<va>() { block_0: … goto/return; }` — mnemonic-style scaffolding, no fabricated locals or types. Kept as regression oracle only. | stdout: `pseudo_c`. Metrics on stderr only with `--verbose`. `--json`: full `Decompile { name, blocks[], edges[], insn_count, pseudo_c }`. |+| **Stage-0.5 IR** (oracle) | `ghidrust decompile <path> --stage05 [--addr HEX] [--count N] [--verbose]` | IR-informed emit from the hand-rolled x86-64 lifter → `ghidrust-ir`: `xor a,a → a=0`, `add/sub/or/and/xor/shl/shr` augmented-assign, `push`/`pop`, direct `call`, flag-driven `jcc`. Falls back to Stage-0 scaffolding for uncovered ops. | stdout: `pseudo_c`. Metrics on stderr only with `--verbose`. `--json`: `{decompile: …, lift_coverage: {total_ops, unimplemented_ops, source_instructions, ratio}}`. || **decompile-bench** | `ghidrust decompile-bench <path> [--functions N] [--count N] [--stage1] [--parallel] [--out FILE]` | Runs default analyzers, then benches Stage-0/0.5 (default) or Stage-1 (`--stage1`) across every discovered function; `--parallel` fans out per-entry Stage-1 across a rayon thread pool. | Text table (or JSON via `--json`); optional `--out FILE`. Report carries per-function `stage0_us`, `stage05_us`, `stage1_us`, `stage1_goto_count`, `stage1_leaf_count`, and per-function `pseudo_c` when Stage-1 is on. || **ghidra-headtohead** (Phase E, fair) | `ghidrust ghidra-headtohead <path> [--functions N] [--count N] [--ghidra DIR] [--captured JSON] [--out FILE]` | Fair Ghidra oracle: shared-entry intersection with Ghidra `DecompInterface` output, per-row Stage-1 vs Ghidra normalized-token similarity, per-entry Stage-1 wall time. Without `--ghidra` / `--captured` the report is methodology-only. | Text or JSON; each row carries `token_similarity`, `ghidrust_stage1_us`, `ghidra_wall_us`. See [`docs/GHIDRA_HEADTOHEAD.md`](docs/GHIDRA_HEADTOHEAD.md). || **gpu-decompile** | `ghidrust gpu-decompile <path> [--out FILE] [--metrics FILE]` | Full **GPU-resident** VRAM multipass decompile of the entry function: decode → leaders → blocks → emit kernels; single final download; asserts `mid_pipeline_host_reads == 0` and multipass-CPU equivalence. | `.gdecomp` binary dump at `--out`. stdout: pseudo-C. `--json` / `--metrics FILE` produces `{gpu_backend, gpu_device, gpu_ms, mid_pipeline_host_reads, kernels, dump_path, dump_bytes, gpu_ir_count, gpu_block_count, gpu_edge_count, equivalence_multipass, pseudo_c_head}`. Non-zero exit if equivalence fails or a mid-pipeline host read is observed. |@@ -184,16 +221,17 @@ Two more benches are shipped and callable from the CLI even though they are not| Method | CLI | Purpose ||---|---|---|-| `analyzer-bench` | `ghidrust analyzer-bench <path> [--large] [--out FILE] [--json]` | All 20 analyzers + a GPU-decompile row: CPU wall-time vs GPU `pcie_upload` / `device_ms` / `pcie_download` split, with a per-analyzer `equal` correctness flag. |-| `analyzer-bench-matrix` | `ghidrust analyzer-bench-matrix` | Print the static analyzer → GPU-strategy matrix (e.g. `ASCII Strings → printable_run`, `WindowsPE x86 PE RTTI Analyzer → rtti_scan`). |+| `analyzer-bench` | `ghidrust analyzer-bench <path> [--large] [--out FILE] [--json]` | All analyzers + a GPU-decompile row: CPU wall-time vs GPU `pcie_upload` / `device_ms` / `pcie_download` split, with a per-analyzer `equal` correctness flag. |+| `analyzer-bench-matrix` | `ghidrust analyzer-bench-matrix` | Print the static analyzer → GPU-strategy matrix (e.g. `ASCII Strings → printable_run`, `Unicode Strings → cstr_multi`, `WindowsPE x86 PE RTTI Analyzer → rtti_scan`). || `bulk-bench` | `ghidrust bulk-bench <path> [--json]` | Sequential vs parallel-CPU vs GPU/fallback bulk-string timings on the program's own bytes + a padded haystack. || `rtti-gpu-bench` | `ghidrust rtti-gpu-bench <path> [--out FILE] [--json]` | CPU `recover_rtti` vs GPU `rtti_scan` seed with `pcie_upload / device_ms / pcie_download` split and a plain-English performance-model note. |Honesty guardrails (mirrored in the eval report):-- Decompile output is Stage-0 (CFG + gotos + mnemonic-style lines) or Stage-0.5 (IR-informed statements). It is **not** Hex-Rays-quality C; the roadmap is SSA-C → typed C.+- Product decompile default is **Stage-1** (SSA + structure + types). Stage-0 / Stage-0.5 remain oracles. Output is **not** Hex-Rays-quality C; deeper typed-C quality is still a later phase.- `gpu-decompile` exits non-zero if it observes a mid-pipeline host read or if its output disagrees with the CPU multipass oracle — GPU wall-clock is not privileged over correctness.- On small fixtures the GPU path is often correct but slower than CPU because of adapter init + PCIe upload; the `pcie_*` / `device_ms` split in every bench makes that explicit.+- Lookups never invent xrefs or imports: empty results mean “no evidence in the image / decode,” not a fabricated hit.---@@ -229,21 +267,30 @@ The CLI is the `ghidrust` binary from `ghidrust-cli`. Prefer **absolute paths**# Map a binaryghidrust load /path/to/app.exe --json-# Listing+# Listing (optional --skip-bad for undecodable holes)ghidrust disasm /path/to/app.exe --count 32-ghidrust disasm /path/to/app.exe --addr 0x140001000 --count 64+ghidrust disasm /path/to/app.exe --addr 0x140001000 --count 64 --skip-bad++# Strings / xrefs / imports / containing function+ghidrust strings /path/to/app.exe --encoding all --filter SomeName --json+ghidrust xrefs /path/to/app.exe --string SomeName --json+ghidrust xrefs /path/to/app.exe --to 0x140002010 --json+ghidrust imports /path/to/app.exe --json+ghidrust xrefs /path/to/app.exe --import CreateFileW --json+ghidrust function-at /path/to/app.exe --addr 0x140001234 --json# List Auto Analysis names (Ghidra-compatible labels)ghidrust analyzers# Run analyzers (comma list or repeatable --analyzer)-ghidrust analyze /path/to/app.exe --analyzers "Function Start Search,ASCII Strings" --json+ghidrust analyze /path/to/app.exe --analyzers "Function Start Search,ASCII Strings,Unicode Strings" --jsonghidrust analyze /path/to/app.exe --analyzer "Stack" --analyzer "Function ID" --gpu --json-# CPU decompile — Stage-0 (default) or Stage-0.5 IR-informed-ghidrust decompile /path/to/app.exe-ghidrust decompile /path/to/app.exe --addr 0x140001000-ghidrust decompile /path/to/app.exe --stage05 --json # IR-informed emit + lift-coverage JSON+# CPU decompile — Stage-1 default; oracles via --stage0 / --stage05+ghidrust decompile /path/to/app.exe # Stage-1; quiet stderr+ghidrust decompile /path/to/app.exe --verbose # + metrics line on stderr+ghidrust decompile /path/to/app.exe --addr 0x140001000 --json+ghidrust decompile /path/to/app.exe --stage05 --json # IR oracle + lift-coverage JSON# Wall-clock + lift-coverage bench across all discovered functionsghidrust decompile-bench /path/to/app.exe --functions 32 --count 128 --out bench.txt@@ -284,13 +331,17 @@ MyProject/| Command | What it does ||---------|----------------|-| `ghidrust load <path> [--json]` | Load PE/ELF, show map |-| `ghidrust disasm <path> [--addr HEX] [--count N]` | x86-64 listing |-| `ghidrust rtti <path>` | RTTI recovery only |-| `ghidrust analyzers` | List Auto Analysis names |-| `ghidrust analyze <path> [--analyzers a,b \| --analyzer NAME …] [--gpu]` | Run analyzers; `--gpu` = bulk strings + seed enrich |-| `ghidrust decompile <path> [--addr HEX] [--stage05]` | **CPU** decompile (Stage-0 default; `--stage05` for IR-informed emit) |-| `ghidrust decompile-bench <path> [--functions N] [--count N] [--out F]` | Per-function wall-clock + lift-coverage: Stage-0 vs Stage-0.5 |+| `ghidrust load <path> [--json]` | Load PE/ELF, show map (PE also parses import/IAT directory into the program model) |+| `ghidrust disasm <path> [--addr HEX] [--count N] [--skip-bad] [--json]` | x86-64 listing; `--skip-bad` advances one byte on decode failure |+| `ghidrust strings <path> [--encoding ascii\|utf16\|all] [--filter SUB] [--min N] [--json]` | ASCII + UTF-16LE string scan / filter |+| `ghidrust xrefs <path> (--to HEX \| --from HEX \| --string F \| --import N) [--json]` | RIP-aware xrefs (string / IAT / arbitrary VA) |+| `ghidrust imports <path> [--dll NAME] [--name NAME] [--json]` | PE import / IAT slots |+| `ghidrust function-at <path> --addr HEX [--json]` | Containing function for a body VA |+| `ghidrust rtti <path> [--json]` | RTTI recovery only |+| `ghidrust analyzers [--json]` | List Auto Analysis names |+| `ghidrust analyze <path> [--analyzers a,b \| --analyzer NAME …] [--gpu] [--json]` | Run analyzers; `--gpu` = bulk strings + seed enrich |+| `ghidrust decompile <path> [--addr HEX] [--count N] [--stage0\|--stage05\|--stage1] [--verbose] [--json]` | **CPU** decompile (**Stage-1** default; oracles via `--stage0` / `--stage05`) |+| `ghidrust decompile-bench <path> [--functions N] [--count N] [--stage1] [--parallel] [--out F]` | Per-function wall-clock + lift-coverage across stages || `ghidrust gpu-decompile <path> [--out FILE] [--metrics FILE]` | **GPU-resident** multipass → `.gdecomp` || `ghidrust bulk-bench <path>` | Seq / parallel CPU / GPU bulk string timings || `ghidrust re-bench <path> [--out FILE]` | CPU decompile + bulk CPU then GPU metrics |@@ -300,7 +351,9 @@ MyProject/| `ghidrust project create\|import\|list\|analyze\|export …` | Durable projects || `ghidrust mcp` | Stdio MCP server for agents |-Recommended early analyzer order: **Function Start Search** → address tables → conventions/stack → strings/RTTI.+`--json` writes UTF-8 **without BOM**. Decompile status lines go to stderr only with `--verbose` (avoids PowerShell `NativeCommandError` noise when scripting).++Recommended early path: **strings / imports / xrefs** for orientation → **Function Start Search** + `function-at` → address tables → conventions/stack → RTTI → `decompile`.---@@ -339,7 +392,7 @@ Note the absolute path to the binary, e.g. `F:\Repos\Ghidrust\target\release\ghi### 2. Register it in your client-**Cursor** — project or user MCP config (e.g. `.cursor/mcp.json`):+**Cursor** — user or project MCP config (e.g. `~/.cursor/mcp.json` or a local `.cursor/mcp.json`). Keep project-local `.cursor/` gitignored — it is machine-specific IDE config, not product source:```json{@@ -389,11 +442,27 @@ On Linux/macOS you can use a shell wrapper if needed:| `rtti` | `path` | Recover RTTI class names / vtables || `list_analyzers` | — | Auto Analysis option names || `analyze` | `path`, optional `analyzers[]`, optional `gpu` | Run analyzers (+ GPU enrich if `gpu: true`) |+| `list_strings` / `search_strings` | `path`, optional `encoding` (`ascii`\|`utf16`\|`all`), `filter`, `min` | ASCII / UTF-16LE strings |+| `get_xrefs_to` | `path`, `addr` | Xrefs **to** a VA (RIP-relative LEA/call/jmp included) |+| `get_xrefs_from` | `path`, `addr`, optional `count` | Xrefs **from** a VA |+| `get_string_xrefs` | `path`, `filter` | Resolve matching strings, then xrefs to each |+| `list_imports` | `path`, optional `dll` / `name` | PE IAT slots |+| `get_import_xrefs` | `path`, `name` | Code sites that reference an import IAT slot |+| `function_at` / `get_function_by_address` | `path`, `addr` | Containing function for a body VA |+| `decompile` | `path`, optional `addr`, `count`, `stage` | Stage-1 default (`stage0` / `stage05` oracles) || `list_gpu_strategies` | — | Per-analyzer GPU strategy matrix || `gpu_decompile` | `path`, optional `out` | GPU-resident multipass decompile || `rtti_gpu_bench` | `path` | CPU vs GPU RTTI with PCIe/device split |-Example agent-facing call shape (conceptual): `analyze` with `{ "path": "…/app.exe", "analyzers": ["ASCII Strings"], "gpu": true }`.+Example agent-facing call shapes (conceptual):++```json+{ "name": "list_strings", "arguments": { "path": "…/app.exe", "encoding": "utf16", "filter": "UserConfig" } }+{ "name": "get_string_xrefs", "arguments": { "path": "…/app.exe", "filter": "ResolutionWidth" } }+{ "name": "get_import_xrefs", "arguments": { "path": "…/app.exe", "name": "ShellExecuteW" } }+{ "name": "function_at", "arguments": { "path": "…/app.exe", "addr": "0x14000d8ad" } }+{ "name": "analyze", "arguments": { "path": "…/app.exe", "analyzers": ["ASCII Strings", "Unicode Strings"], "gpu": true } }+```### 4. Optional: agent skill@@ -440,7 +509,7 @@ You should not need to type JSON by hand day-to-day — the IDE/agent does that| Crate | Role ||-------|------|-| `ghidrust-core` | PE/ELF, x86-64, analyzers, projects, bulk scan |+| `ghidrust-core` | PE/ELF, x86-64, analyzers, imports/IAT, xrefs, projects, bulk scan || `ghidrust-decode` | Hand-rolled x86-64 length-disasm + mnemonic/operand strings || `ghidrust-ir` | Architecture-neutral pcode-like IR (varnodes, ops, tagged blocks, address spaces) || `ghidrust-lift` | x86-64 → IR semantics with flag model + `LiftCoverage` reporting |diff --git a/crates/ghidrust-agent/Cargo.toml b/crates/ghidrust-agent/Cargo.tomlnew file mode 100644index 0000000..e08b897--- /dev/null+++ b/crates/ghidrust-agent/Cargo.toml@@ -0,0 +1,13 @@+[package]+name = "ghidrust-agent"+version.workspace = true+edition.workspace = true+license.workspace = true+description = "Ghidrust Grok Build agent bridge (ACP sidecar + tool_bridge + audit + install)"++[lib]+path = "src/lib.rs"++[dependencies]+serde = { version = "1", features = ["derive"] }+serde_json = "1"diff --git a/crates/ghidrust-agent/src/acp_client.rs b/crates/ghidrust-agent/src/acp_client.rsnew file mode 100644index 0000000..4aaf456--- /dev/null+++ b/crates/ghidrust-agent/src/acp_client.rs@@ -0,0 +1,695 @@+//! ACP-sidecar transport for Grok Build (Option C in the plan).+//!+//! # Two transports, one API+//!+//! Grok Build ships two embedding surfaces upstream:+//!+//! - **ACP JSON-RPC** — `grok agent stdio`, persistent, session-based. Preferred+//! for a chat pane because turns share memory and streamed deltas are+//! surfaced as `session/update` notifications.+//! - **Headless one-shot** — `grok -p "…" --output-format streaming-json`,+//! fire-and-forget, one child process per prompt. Safe fallback when the+//! installed ACP binary version isn't known to match this bridge.+//!+//! Both are exposed behind the same [`AgentSession`] API. The GUI does not+//! know which one is running; it just polls [`AgentSession::poll_events`] each+//! frame and pushes prompts with [`AgentSession::send_prompt`].+//!+//! # Threading model+//!+//! One `std::thread` per session reads the child's stdout, parses JSON lines,+//! and forwards [`crate::AgentEvent`]s over a `mpsc::Sender` back to the GUI.+//! The GUI is UI-thread only and never blocks on the child — polling is+//! `try_recv` based.++use crate::policy::AgentMode;+use crate::AgentEvent;+use serde_json::{json, Value};+use std::io::{BufRead, BufReader, Write};+use std::path::PathBuf;+use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};+use std::sync::Arc;+use std::thread;++/// Which upstream Grok Build entry point the session uses.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum TransportKind {+ /// `grok agent stdio` (persistent JSON-RPC).+ Acp,+ /// `grok -p "<prompt>" --output-format streaming-json` (per-turn).+ Headless,+}++impl TransportKind {+ pub const fn label(self) -> &'static str {+ match self {+ TransportKind::Acp => "acp",+ TransportKind::Headless => "headless",+ }+ }+}++/// Selects a transport at session-start time.+#[derive(Debug, Clone)]+pub enum AgentTransport {+ /// Try ACP first; if the binary doesn't understand `agent stdio`, fall+ /// back to Headless. This is the recommended default.+ Auto,+ /// Force ACP JSON-RPC. Session start fails if unsupported.+ Acp,+ /// Force per-prompt headless (`-p …`). Always available.+ Headless,+}++/// Configuration for one project-scoped agent session.+#[derive(Debug, Clone)]+pub struct AgentSessionConfig {+ /// Absolute path to `grok` (from [`crate::installer::grok_binary_path`]).+ pub grok_bin: PathBuf,+ /// The project directory the child is spawned in (cwd). MCP config ++ /// audit log live here.+ pub project_root: PathBuf,+ /// Session mode. `Airgap` will fail session start immediately.+ pub mode: AgentMode,+ /// System prompt / context. Sent as the first system message.+ pub system_prompt: String,+ /// Which transport to try.+ pub transport: AgentTransport,+ /// Optional model override (e.g. `grok-4.5`, `ollama/llama3.2`). `None`+ /// = whatever the child's `~/.grok/config.toml` selects.+ pub model: Option<String>,+}++/// Internal: pipes the session uses to talk to whatever transport is live.+enum Pipe {+ Acp {+ child: Option<Child>,+ stdin: ChildStdin,+ },+ Headless {+ /// The worker thread reads prompts from here and spawns `grok -p` per+ /// prompt. Drop = worker exits after its current turn.+ prompt_tx: Sender<String>,+ },+}++/// A live agent session, backed by a child `grok` process.+///+/// Drop = signal stop + kill child. The reader thread exits cleanly when+/// stdout closes.+pub struct AgentSession {+ kind: TransportKind,+ pipe: Pipe,+ events_rx: Receiver<AgentEvent>,+ stop_flag: Arc<AtomicBool>,+ config: AgentSessionConfig,+ next_request_id: u64,+}++impl AgentSession {+ /// Spawn a session. Returns an error if the binary can't be spawned or the+ /// mode is `Airgap`.+ pub fn spawn(config: AgentSessionConfig) -> Result<Self, String> {+ if !config.mode.is_enabled() {+ return Err(+ "airgap mode: agent pane disabled, no child spawned, no network permitted"+ .to_string(),+ );+ }++ match config.transport {+ AgentTransport::Acp => spawn_acp(config),+ AgentTransport::Headless => Ok(spawn_headless(config)),+ AgentTransport::Auto => {+ // Cheap acp probe: try ACP; on any failure, fall back to+ // headless. We consider "spawn failed", "handshake failed",+ // or "immediate exit" as reasons to retry as headless.+ let cfg_clone = config.clone();+ match spawn_acp(config) {+ Ok(s) => Ok(s),+ Err(_) => Ok(spawn_headless(cfg_clone)),+ }+ }+ }+ }++ pub fn transport_kind(&self) -> TransportKind {+ self.kind+ }++ pub fn mode(&self) -> AgentMode {+ self.config.mode+ }++ pub fn model(&self) -> Option<&str> {+ self.config.model.as_deref()+ }++ /// Drain everything the reader thread queued since the last poll.+ pub fn poll_events(&self) -> Vec<AgentEvent> {+ let mut out = Vec::new();+ loop {+ match self.events_rx.try_recv() {+ Ok(ev) => out.push(ev),+ Err(TryRecvError::Empty) => break,+ Err(TryRecvError::Disconnected) => {+ out.push(AgentEvent::ChildExited { code: None });+ break;+ }+ }+ }+ out+ }++ /// Send a user prompt. Non-blocking — response comes in via+ /// [`Self::poll_events`].+ ///+ /// - ACP: writes a `session/prompt` JSON-RPC request to the persistent+ /// child.+ /// - Headless: enqueues the prompt into the worker channel; the worker+ /// spawns `grok -p "<prompt>"` per turn.+ pub fn send_prompt(&mut self, prompt: &str, context: &str) -> Result<(), String> {+ let payload = if context.is_empty() {+ prompt.to_string()+ } else {+ format!("{context}\n\n---\n\n{prompt}")+ };++ match &mut self.pipe {+ Pipe::Acp { stdin, .. } => {+ let id = self.next_request_id;+ self.next_request_id += 1;+ let req = json!({+ "jsonrpc": "2.0",+ "id": id,+ "method": "session/prompt",+ "params": { "text": payload }+ });+ write_line(stdin, &req.to_string())+ }+ Pipe::Headless { prompt_tx } => prompt_tx+ .send(payload)+ .map_err(|_| "headless worker exited".to_string()),+ }+ }++ /// Ask the agent to cancel the current turn (ACP `session/cancel` /+ /// headless best-effort — worker checks stop_flag between turns).+ pub fn cancel_turn(&mut self) -> Result<(), String> {+ match &mut self.pipe {+ Pipe::Acp { stdin, .. } => {+ let id = self.next_request_id;+ self.next_request_id += 1;+ let req = json!({+ "jsonrpc": "2.0",+ "id": id,+ "method": "session/cancel",+ });+ write_line(stdin, &req.to_string())+ }+ Pipe::Headless { .. } => {+ self.stop_flag.store(true, Ordering::Relaxed);+ Ok(())+ }+ }+ }+}++impl Drop for AgentSession {+ fn drop(&mut self) {+ self.stop_flag.store(true, Ordering::Relaxed);+ if let Pipe::Acp { child, .. } = &mut self.pipe {+ if let Some(mut ch) = child.take() {+ let _ = ch.kill();+ let _ = ch.wait();+ }+ }+ // Headless: dropping prompt_tx causes the worker to exit after its+ // current turn (Receiver::iter loops until disconnect).+ }+}++fn write_line(stdin: &mut ChildStdin, line: &str) -> Result<(), String> {+ stdin+ .write_all(line.as_bytes())+ .and_then(|_| stdin.write_all(b"\n"))+ .and_then(|_| stdin.flush())+ .map_err(|e| e.to_string())+}++// ── ACP transport ────────────────────────────────────────────────────────────++fn spawn_acp(cfg: AgentSessionConfig) -> Result<AgentSession, String> {+ let mut cmd = Command::new(&cfg.grok_bin);+ cmd.arg("agent")+ .arg("stdio")+ .current_dir(&cfg.project_root)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ if let Some(model) = &cfg.model {+ cmd.arg("--model").arg(model);+ }++ let mut child = cmd+ .spawn()+ .map_err(|e| format!("spawn grok agent stdio failed: {e}"))?;++ let mut stdin = child+ .stdin+ .take()+ .ok_or_else(|| "grok stdin missing".to_string())?;+ let stdout = child+ .stdout+ .take()+ .ok_or_else(|| "grok stdout missing".to_string())?;+ let stderr = child.stderr.take();++ let init = json!({+ "jsonrpc": "2.0",+ "id": 0,+ "method": "initialize",+ "params": {+ "protocolVersion": "2024-11-05",+ "clientInfo": {"name": "ghidrust-gui", "version": env!("CARGO_PKG_VERSION")},+ "capabilities": {}+ }+ });+ let session_new = json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "session/new",+ "params": {+ "system_prompt": cfg.system_prompt,+ }+ });++ if let Err(e) = write_line(&mut stdin, &init.to_string())+ .and_then(|_| write_line(&mut stdin, &session_new.to_string()))+ {+ let _ = child.kill();+ let _ = child.wait();+ return Err(format!("acp handshake failed: {e}"));+ }++ // Drain stderr so it doesn't stall the child's pipe buffer.+ if let Some(mut se) = stderr {+ thread::spawn(move || {+ let mut sink = Vec::with_capacity(4096);+ let _ = std::io::copy(&mut se, &mut sink);+ });+ }++ let stop = Arc::new(AtomicBool::new(false));+ let stop_thread = stop.clone();+ let (tx, rx) = mpsc::channel();+ thread::spawn(move || acp_reader_thread(stdout, tx, stop_thread));++ Ok(AgentSession {+ kind: TransportKind::Acp,+ pipe: Pipe::Acp {+ child: Some(child),+ stdin,+ },+ events_rx: rx,+ stop_flag: stop,+ config: cfg,+ next_request_id: 2,+ })+}++fn acp_reader_thread(stdout: ChildStdout, tx: Sender<AgentEvent>, stop: Arc<AtomicBool>) {+ let reader = BufReader::new(stdout);+ for line in reader.lines() {+ if stop.load(Ordering::Relaxed) {+ break;+ }+ let line = match line {+ Ok(l) => l,+ Err(_) => break,+ };+ let trimmed = line.trim();+ if trimmed.is_empty() {+ continue;+ }+ let Ok(val) = serde_json::from_str::<Value>(trimmed) else {+ let _ = tx.send(AgentEvent::AssistantDelta { text: line });+ continue;+ };+ for ev in acp_events_from_value(val) {+ if tx.send(ev).is_err() {+ return;+ }+ }+ }+ let _ = tx.send(AgentEvent::ChildExited { code: None });+}++/// Translate one ACP JSON message into zero or more [`AgentEvent`]s.+///+/// Kept as a free function so it can be unit-tested with static fixtures.+pub(crate) fn acp_events_from_value(val: Value) -> Vec<AgentEvent> {+ let mut out = Vec::new();+ let method = val.get("method").and_then(|m| m.as_str()).unwrap_or("");+ let params = val.get("params").cloned().unwrap_or(Value::Null);++ match method {+ "session/update" => {+ if let Some(update) = params.get("update") {+ emit_from_update(update, &mut out);+ }+ }+ "assistant_text_delta" | "text_delta" => {+ if let Some(t) = params.get("text").and_then(|v| v.as_str()) {+ out.push(AgentEvent::AssistantDelta {+ text: t.to_string(),+ });+ }+ }+ "turn_finished" | "final" => out.push(AgentEvent::TurnFinished),+ _ => {}+ }+ out+}++fn emit_from_update(update: &Value, out: &mut Vec<AgentEvent>) {+ let kind = update+ .get("type")+ .or_else(|| update.get("kind"))+ .and_then(|k| k.as_str())+ .unwrap_or("");+ match kind {+ "assistant_text_delta" | "text_delta" | "assistant_message" | "assistant_delta" => {+ if let Some(t) = update+ .get("text")+ .or_else(|| update.get("delta"))+ .and_then(|v| v.as_str())+ {+ out.push(AgentEvent::AssistantDelta {+ text: t.to_string(),+ });+ }+ }+ "tool_call" | "tool_call_start" => {+ let id = update+ .get("id")+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .to_string();+ let name = update+ .get("name")+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .to_string();+ let args_json = update+ .get("arguments")+ .or_else(|| update.get("args"))+ .map(|v| serde_json::to_string(v).unwrap_or_default())+ .unwrap_or_default();+ out.push(AgentEvent::ToolCallStarted {+ id,+ name,+ args_json,+ });+ }+ "tool_call_result" | "tool_result" | "tool_call_finished" => {+ let id = update+ .get("id")+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .to_string();+ let ok = update+ .get("ok")+ .and_then(|v| v.as_bool())+ .unwrap_or(true);+ let summary = update+ .get("summary")+ .and_then(|v| v.as_str())+ .map(String::from)+ .or_else(|| {+ update+ .get("result")+ .map(|v| serde_json::to_string(v).unwrap_or_default())+ })+ .unwrap_or_default();+ out.push(AgentEvent::ToolCallFinished { id, ok, summary });+ }+ "approval_request" | "approval_requested" => {+ let id = update+ .get("id")+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .to_string();+ let tool = update+ .get("tool")+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .to_string();+ let preview = update+ .get("preview")+ .and_then(|v| v.as_str())+ .map(String::from)+ .unwrap_or_default();+ out.push(AgentEvent::ApprovalRequested { id, tool, preview });+ }+ "turn_finished" | "end" | "final" => out.push(AgentEvent::TurnFinished),+ "error" => {+ let message = update+ .get("message")+ .and_then(|v| v.as_str())+ .unwrap_or("agent error")+ .to_string();+ out.push(AgentEvent::Error { message });+ }+ _ => {}+ }+}++// ── Headless transport ──────────────────────────────────────────────────────++fn spawn_headless(cfg: AgentSessionConfig) -> AgentSession {+ let (prompt_tx, prompt_rx) = mpsc::channel::<String>();+ let (out_tx, out_rx) = mpsc::channel::<AgentEvent>();+ let stop = Arc::new(AtomicBool::new(false));+ let stop_thread = stop.clone();++ let bin = cfg.grok_bin.clone();+ let cwd = cfg.project_root.clone();+ let model = cfg.model.clone();+ let system_prompt = cfg.system_prompt.clone();++ thread::spawn(move || {+ headless_worker(prompt_rx, out_tx, stop_thread, bin, cwd, model, system_prompt);+ });++ AgentSession {+ kind: TransportKind::Headless,+ pipe: Pipe::Headless { prompt_tx },+ events_rx: out_rx,+ stop_flag: stop,+ config: cfg,+ next_request_id: 1,+ }+}++fn headless_worker(+ prompts: Receiver<String>,+ out: Sender<AgentEvent>,+ stop: Arc<AtomicBool>,+ bin: PathBuf,+ cwd: PathBuf,+ model: Option<String>,+ system_prompt: String,+) {+ for prompt in prompts.iter() {+ if stop.load(Ordering::Relaxed) {+ break;+ }+ let full = if system_prompt.is_empty() {+ prompt.clone()+ } else {+ format!("{system_prompt}\n\n---\n\n{prompt}")+ };++ let mut cmd = Command::new(&bin);+ cmd.arg("-p")+ .arg(&full)+ .arg("--output-format")+ .arg("streaming-json")+ .current_dir(&cwd)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ if let Some(m) = &model {+ cmd.arg("--model").arg(m);+ }++ let mut child = match cmd.spawn() {+ Ok(c) => c,+ Err(e) => {+ let _ = out.send(AgentEvent::Error {+ message: format!("spawn grok -p failed: {e}"),+ });+ continue;+ }+ };+ let Some(stdout) = child.stdout.take() else {+ let _ = out.send(AgentEvent::Error {+ message: "grok stdout missing".into(),+ });+ let _ = child.wait();+ continue;+ };+ let reader = BufReader::new(stdout);+ for line in reader.lines() {+ if stop.load(Ordering::Relaxed) {+ let _ = child.kill();+ break;+ }+ let line = match line {+ Ok(l) => l,+ Err(_) => break,+ };+ let trimmed = line.trim();+ if trimmed.is_empty() {+ continue;+ }+ if let Ok(val) = serde_json::from_str::<Value>(trimmed) {+ for ev in acp_events_from_value(val) {+ if out.send(ev).is_err() {+ return;+ }+ }+ } else {+ let _ = out.send(AgentEvent::AssistantDelta { text: line });+ }+ }+ let _ = child.wait();+ let _ = out.send(AgentEvent::TurnFinished);+ }+ let _ = out.send(AgentEvent::ChildExited { code: None });+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn assistant_text_delta_parses() {+ let msg = json!({+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": { "update": { "type": "assistant_text_delta", "text": "hi" } }+ });+ let evs = acp_events_from_value(msg);+ assert_eq!(evs.len(), 1);+ match &evs[0] {+ AgentEvent::AssistantDelta { text } => assert_eq!(text, "hi"),+ _ => panic!("expected delta"),+ }+ }++ #[test]+ fn tool_call_started_parses() {+ let msg = json!({+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "update": {+ "type": "tool_call",+ "id": "call_1",+ "name": "analyze",+ "arguments": {"path": "a.exe"}+ }+ }+ });+ let evs = acp_events_from_value(msg);+ assert_eq!(evs.len(), 1);+ match &evs[0] {+ AgentEvent::ToolCallStarted {+ id, name, args_json,+ } => {+ assert_eq!(id, "call_1");+ assert_eq!(name, "analyze");+ assert!(args_json.contains("\"path\":\"a.exe\""));+ }+ _ => panic!("expected tool_call"),+ }+ }++ #[test]+ fn tool_call_finished_parses() {+ let msg = json!({+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "update": {+ "type": "tool_call_result",+ "id": "call_1",+ "ok": true,+ "summary": "42 functions"+ }+ }+ });+ let evs = acp_events_from_value(msg);+ match &evs[0] {+ AgentEvent::ToolCallFinished { id, ok, summary } => {+ assert_eq!(id, "call_1");+ assert!(*ok);+ assert_eq!(summary, "42 functions");+ }+ _ => panic!("expected finished"),+ }+ }++ #[test]+ fn turn_finished_parses() {+ let msg = json!({+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": { "update": { "type": "turn_finished" } }+ });+ let evs = acp_events_from_value(msg);+ assert!(matches!(evs.as_slice(), [AgentEvent::TurnFinished]));+ }++ #[test]+ fn approval_request_parses() {+ let msg = json!({+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {+ "update": {+ "type": "approval_request",+ "id": "call_1",+ "tool": "rename_function",+ "preview": "FUN_140001040 → main"+ }+ }+ });+ let evs = acp_events_from_value(msg);+ match &evs[0] {+ AgentEvent::ApprovalRequested { id, tool, preview } => {+ assert_eq!(id, "call_1");+ assert_eq!(tool, "rename_function");+ assert!(preview.contains("main"));+ }+ _ => panic!("expected approval"),+ }+ }++ #[test]+ fn airgap_rejects_spawn() {+ let cfg = AgentSessionConfig {+ grok_bin: PathBuf::from("/nonexistent/grok"),+ project_root: std::env::temp_dir(),+ mode: AgentMode::Airgap,+ system_prompt: String::new(),+ transport: AgentTransport::Auto,+ model: None,+ };+ assert!(AgentSession::spawn(cfg).is_err());+ }+}diff --git a/crates/ghidrust-agent/src/audit.rs b/crates/ghidrust-agent/src/audit.rsnew file mode 100644index 0000000..3a1f8fd--- /dev/null+++ b/crates/ghidrust-agent/src/audit.rs@@ -0,0 +1,202 @@+//! NDJSON audit log — every tool call the agent performs (approved or denied)+//! is persisted to `<project>/agent-audit.ndjson`.+//!+//! Fields per record are stable and grep-friendly. The file is append-only so+//! it can be tailed while the GUI is running. Rotation is intentionally left+//! to the user (RE cases don't produce enough traffic to need built-in+//! rotation, and truncating would drop provenance).++use serde::{Deserialize, Serialize};+use std::fs::OpenOptions;+use std::io::{self, Write};+use std::path::{Path, PathBuf};++/// Verdict for a single tool call.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub enum AuditVerdict {+ /// User (or policy) allowed the tool to run; result was captured.+ Approved,+ /// User denied the tool call before dispatch.+ Denied,+ /// Policy (`ReadOnly` mode) blocked a destructive call.+ Blocked,+ /// Non-destructive; no user prompt needed.+ Auto,+}++/// One append-only audit record.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AuditRecord {+ pub ts_unix_ms: u128,+ pub session_id: String,+ pub tool: String,+ /// SHA-agnostic short hash (16 hex chars) of the arg JSON so the log stays+ /// small but arguments are still identifiable.+ pub args_hash: String,+ /// First 512 bytes of the arg JSON — enough to eyeball, small enough to+ /// keep the audit file readable.+ pub args_preview: String,+ pub verdict: AuditVerdict,+ /// First 512 bytes of the tool result (only populated for Approved / Auto).+ pub result_preview: Option<String>,+ /// Wall-clock ms from dispatch to result (None if not run).+ pub wall_ms: Option<u64>,+}++/// Append-only audit log bound to a project directory.+#[derive(Debug, Clone)]+pub struct AuditLog {+ path: PathBuf,+ session_id: String,+}++impl AuditLog {+ /// Open (or create) `<project>/agent-audit.ndjson`.+ pub fn open_in_project(project_root: &Path, session_id: impl Into<String>) -> io::Result<Self> {+ let path = project_root.join("agent-audit.ndjson");+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)?;+ }+ // Touch the file so subsequent tails succeed even before the first record.+ OpenOptions::new().create(true).append(true).open(&path)?;+ Ok(Self {+ path,+ session_id: session_id.into(),+ })+ }++ pub fn path(&self) -> &Path {+ &self.path+ }++ pub fn session_id(&self) -> &str {+ &self.session_id+ }++ /// Append one record. Best-effort: never panics, returns the io error so+ /// callers can surface it in the pane.+ pub fn append(&self, mut record: AuditRecord) -> io::Result<()> {+ record.session_id = self.session_id.clone();+ let mut f = OpenOptions::new().create(true).append(true).open(&self.path)?;+ let line = serde_json::to_string(&record)+ .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;+ writeln!(f, "{line}")?;+ Ok(())+ }++ /// Convenience: build + append a record for a tool call.+ pub fn record_call(+ &self,+ tool: &str,+ args_json: &str,+ verdict: AuditVerdict,+ result_preview: Option<&str>,+ wall_ms: Option<u64>,+ ) -> io::Result<()> {+ let record = AuditRecord {+ ts_unix_ms: now_unix_ms(),+ session_id: self.session_id.clone(),+ tool: tool.to_string(),+ args_hash: short_hash(args_json),+ args_preview: truncate_bytes(args_json, 512),+ verdict,+ result_preview: result_preview.map(|s| truncate_bytes(s, 512)),+ wall_ms,+ };+ self.append(record)+ }+}++fn now_unix_ms() -> u128 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis())+ .unwrap_or(0)+}++/// FNV-1a 64-bit → 16 hex chars. Not cryptographic; only for correlation.+fn short_hash(s: &str) -> String {+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;+ for &b in s.as_bytes() {+ h ^= b as u64;+ h = h.wrapping_mul(0x0000_0100_0000_01b3);+ }+ format!("{h:016x}")+}++fn truncate_bytes(s: &str, max: usize) -> String {+ if s.len() <= max {+ return s.to_string();+ }+ // Find a UTF-8 boundary at or before `max`.+ let mut end = max;+ while end > 0 && !s.is_char_boundary(end) {+ end -= 1;+ }+ format!("{}…[+{}]", &s[..end], s.len() - end)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn tmp_dir(tag: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "ghidrust-audit-test-{}-{}",+ std::process::id(),+ tag+ ));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ dir+ }++ #[test]+ fn opens_and_creates_log_file() {+ let dir = tmp_dir("open");+ let log = AuditLog::open_in_project(&dir, "sess1").unwrap();+ assert!(log.path().exists());+ assert!(log.path().ends_with("agent-audit.ndjson"));+ assert_eq!(log.session_id(), "sess1");+ }++ #[test]+ fn appends_ndjson_line() {+ let dir = tmp_dir("append");+ let log = AuditLog::open_in_project(&dir, "s").unwrap();+ log.record_call(+ "analyze",+ r#"{"path":"a","analyzers":["ASCII Strings"]}"#,+ AuditVerdict::Auto,+ Some(r#"{"functions":10}"#),+ Some(42),+ )+ .unwrap();+ let contents = std::fs::read_to_string(log.path()).unwrap();+ assert!(contents.trim_end().lines().count() == 1);+ assert!(contents.contains("\"tool\":\"analyze\""));+ assert!(contents.contains("\"verdict\":\"Auto\""));+ assert!(contents.contains("\"wall_ms\":42"));+ }++ #[test]+ fn truncates_long_args_preview() {+ let big = "x".repeat(2000);+ let dir = tmp_dir("trunc");+ let log = AuditLog::open_in_project(&dir, "s").unwrap();+ log.record_call("t", &big, AuditVerdict::Auto, None, None)+ .unwrap();+ let contents = std::fs::read_to_string(log.path()).unwrap();+ // The record is truncated with an ellipsis.+ assert!(contents.contains("…[+"));+ }++ #[test]+ fn short_hash_is_stable_and_hex() {+ let h = short_hash("abc");+ assert_eq!(h.len(), 16);+ assert!(h.chars().all(|c| c.is_ascii_hexdigit()));+ assert_eq!(h, short_hash("abc"));+ assert_ne!(h, short_hash("abd"));+ }+}diff --git a/crates/ghidrust-agent/src/installer.rs b/crates/ghidrust-agent/src/installer.rsnew file mode 100644index 0000000..75921f2--- /dev/null+++ b/crates/ghidrust-agent/src/installer.rs@@ -0,0 +1,134 @@+//! Grok Build "one-click install" helper.+//!+//! Ghidrust does **not** vendor the `grok` binary. Instead this module builds+//! the exact command the user needs to run so the GUI can spawn a terminal (or+//! run it internally with user consent) that installs Grok Build via xAI's+//! official installer. After install, we also make sure the project has the+//! integration files (`.grok/mcp.json`, `.grok/skills/ghidrust/SKILL.md`) —+//! that step is the responsibility of [`crate::tool_bridge`], not this module.+//!+//! References:+//! - [Grok Build install docs](https://github.com/xai-org/grok-build/blob/main/README.md)+//! - Install commands mirror the upstream instructions verbatim so users can+//! copy-paste the same line into their own shell if they don't trust an+//! automated install click.++use std::path::PathBuf;++/// One installer command as an argv the GUI can spawn.+#[derive(Debug, Clone)]+pub struct InstallCommand {+ /// Program to execute (`sh`, `pwsh`, `cmd`).+ pub program: String,+ /// Arguments (already shell-quoted where needed).+ pub args: Vec<String>,+ /// Copy-paste-friendly one-liner shown to the user before we spawn it.+ /// This is the exact command a distrustful user could run themselves.+ pub display: String,+ /// Short docs anchor for the pane ("upstream install docs at …").+ pub docs_url: &'static str,+}++/// Pick the right installer for the current OS.+///+/// - Windows: PowerShell `iwr … -useb | iex`+/// - Linux / macOS: `curl -fsSL … | bash`+/// - Anything else: returns `None` (user must install manually).+pub fn install_command_for_platform() -> Option<InstallCommand> {+ #[cfg(target_os = "windows")]+ {+ let one_liner = "iwr https://x.ai/cli/install.ps1 -useb | iex".to_string();+ Some(InstallCommand {+ program: "powershell".into(),+ args: vec![+ "-NoProfile".into(),+ "-ExecutionPolicy".into(),+ "Bypass".into(),+ "-Command".into(),+ one_liner.clone(),+ ],+ display: format!("powershell -NoProfile -ExecutionPolicy Bypass -Command \"{one_liner}\""),+ docs_url: "https://github.com/xai-org/grok-build/blob/main/README.md",+ })+ }+ #[cfg(any(target_os = "linux", target_os = "macos"))]+ {+ let one_liner = "curl -fsSL https://x.ai/cli/install.sh | bash".to_string();+ Some(InstallCommand {+ program: "sh".into(),+ args: vec!["-c".into(), one_liner.clone()],+ display: one_liner,+ docs_url: "https://github.com/xai-org/grok-build/blob/main/README.md",+ })+ }+ #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]+ {+ None+ }+}++/// Resolve the `grok` binary path from `PATH` (and common install locations).+///+/// Returns `None` if the binary isn't found — the GUI should render the+/// `Install Grok Build…` prompt in that case.+pub fn grok_binary_path() -> Option<PathBuf> {+ // 1. Walk $PATH for `grok` / `grok.exe`.+ let exe_name = if cfg!(windows) { "grok.exe" } else { "grok" };+ if let Ok(path_var) = std::env::var("PATH") {+ let sep = if cfg!(windows) { ';' } else { ':' };+ for dir in path_var.split(sep) {+ let candidate = PathBuf::from(dir).join(exe_name);+ if candidate.is_file() {+ return Some(candidate);+ }+ }+ }++ // 2. Common upstream install locations (from Grok Build install script).+ let mut candidates: Vec<PathBuf> = Vec::new();+ if let Ok(home) = std::env::var("HOME") {+ candidates.push(PathBuf::from(&home).join(".local/bin").join(exe_name));+ candidates.push(PathBuf::from(&home).join(".grok/bin").join(exe_name));+ }+ if let Ok(userprofile) = std::env::var("USERPROFILE") {+ candidates.push(PathBuf::from(&userprofile).join(".grok").join("bin").join(exe_name));+ candidates.push(PathBuf::from(&userprofile).join("AppData").join("Local").join("Programs").join("grok").join(exe_name));+ }+ for c in candidates {+ if c.is_file() {+ return Some(c);+ }+ }+ None+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn install_command_available_on_supported_platforms() {+ // On any platform this crate can be compiled on, we ship an install+ // command. This is a canary — if a new platform is added, add a case.+ #[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]+ assert!(install_command_for_platform().is_some());+ }++ #[test]+ fn install_display_mentions_xai_endpoint() {+ if let Some(cmd) = install_command_for_platform() {+ assert!(+ cmd.display.contains("x.ai/cli/install"),+ "installer must point at official xAI endpoint, got: {}",+ cmd.display+ );+ }+ }++ #[test]+ fn docs_url_points_at_upstream_readme() {+ if let Some(cmd) = install_command_for_platform() {+ assert!(cmd.docs_url.contains("xai-org/grok-build"));+ }+ }+}diff --git a/crates/ghidrust-agent/src/lib.rs b/crates/ghidrust-agent/src/lib.rsnew file mode 100644index 0000000..7803448--- /dev/null+++ b/crates/ghidrust-agent/src/lib.rs@@ -0,0 +1,84 @@+//! Ghidrust ↔ Grok Build agent bridge.+//!+//! Option C of [`dev/GROK_BUILD_AGENT_CONSOLE_PLAN.md`]: embed Grok Build via an+//! **ACP sidecar** — the GUI spawns a `grok` child process per Ghidrust project+//! and talks to it over stdio. The GUI's own MCP server (`ghidrust mcp`) is+//! wired into the child via a project-local `.grok/mcp.json` so the agent can+//! call every shipped Ghidrust tool with zero new Rust surface.+//!+//! Design notes:+//!+//! - **Per-project isolation.** Every [`AgentSession`] is bound to one project+//! root. Conversation state, audit log, MCP config, and skill files live under+//! `<project>/.grok/`. Two Ghidrust windows on two projects = two independent+//! agents.+//! - **No forced runtime.** This crate has no `wgpu`, no `eframe`, no `tokio`.+//! It uses plain `std::process::Command` + an mpsc reader thread so the GUI+//! can poll for streamed messages each frame without stalling.+//! - **Two transports.** [`AgentTransport::Acp`] speaks Grok Build's ACP+//! JSON-RPC (`grok agent stdio`, persistent). [`AgentTransport::Headless`]+//! uses the fire-and-forget `grok -p "…" --output-format streaming-json`+//! entry point and is the always-safe fallback when the ACP binary version+//! is unknown.+//! - **Determinism envelope.** [`policy::AgentMode`] gates destructive tool+//! calls; [`audit::AuditLog`] persists every request+result. The GUI still+//! owns the approval UI — this crate only records verdicts.++pub mod acp_client;+pub mod audit;+pub mod installer;+pub mod markdown;+pub mod policy;+pub mod system_prompt;+pub mod tool_bridge;++pub use acp_client::{AgentSession, AgentSessionConfig, AgentTransport, TransportKind};+pub use audit::{AuditLog, AuditRecord, AuditVerdict};+pub use installer::{grok_binary_path, install_command_for_platform, InstallCommand};+pub use markdown::{parse_markdown, MarkdownBlock};+pub use policy::AgentMode;+pub use system_prompt::{ProgramFacts, SectionFact, SelectionFact, SystemPromptBuilder};+pub use tool_bridge::{write_project_mcp_config, write_project_skill};++/// One streamed message from the agent runtime, delivered to the GUI via mpsc.+///+/// The GUI polls for these each frame and folds them into a rendered transcript.+#[derive(Debug, Clone)]+pub enum AgentEvent {+ /// A chunk of assistant text (streamed token delta or a full line).+ AssistantDelta { text: String },+ /// A tool the agent is about to call — GUI shows a collapsible card.+ ToolCallStarted {+ id: String,+ name: String,+ args_json: String,+ },+ /// Result of a tool call (whether or not it succeeded).+ ToolCallFinished {+ id: String,+ ok: bool,+ summary: String,+ },+ /// Agent produced a final answer for this turn.+ TurnFinished,+ /// Agent asked for approval before executing a destructive tool.+ ApprovalRequested {+ id: String,+ tool: String,+ preview: String,+ },+ /// Transport / model / installer error to surface in the pane.+ Error { message: String },+ /// Grok child exited (unexpected). GUI shows a "reconnect" button.+ ChildExited { code: Option<i32> },+}++/// One user prompt turn queued for the agent.+#[derive(Debug, Clone)]+pub struct AgentPrompt {+ /// User text, verbatim.+ pub text: String,+ /// Any extra program-facts snapshot the GUI wants injected on this turn+ /// (e.g. current selection). Empty string means "no extra context".+ pub context: String,+}diff --git a/crates/ghidrust-agent/src/markdown.rs b/crates/ghidrust-agent/src/markdown.rsnew file mode 100644index 0000000..4bba112--- /dev/null+++ b/crates/ghidrust-agent/src/markdown.rs@@ -0,0 +1,207 @@+//! Minimal fenced-code-block extractor for the Grok pane renderer.+//!+//! The pane needs to render streamed assistant output as Markdown *with* the+//! ability to hand fenced code blocks (`` ``` ``) to specialised renderers:+//!+//! - Pseudo-C / C blocks go through the existing `decomp_tokens` highlighter+//! in the GUI, so agent-produced pseudo-C looks exactly like the Decompiler+//! pane's output.+//! - JSON blocks (tool call results) get a monospace box with a "Copy" button.+//! - Everything else falls back to plain monospace.+//!+//! We deliberately don't pull `pulldown-cmark` in P1; a fenced-block splitter+//! is enough for the pane, keeps the dep footprint minimal, and doesn't drag+//! CommonMark tables into the airgap build. Full Markdown rendering is a+//! Phase-2 stretch (behind a `markdown-full` feature) when the pane needs+//! bulleted lists / headings / links.++use serde::{Deserialize, Serialize};++/// One parsed segment of streamed assistant text.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub enum MarkdownBlock {+ /// Prose (no fence). Rendered as wrapping label text.+ Prose(String),+ /// Fenced code block; `lang` may be empty. Common langs we treat specially+ /// in the GUI: `c`, `cpp`, `pseudo-c`, `pseudoc`, `json`, `rust`, `sh`.+ Code { lang: String, body: String },+}++impl MarkdownBlock {+ /// True if the block is a code fence whose language should be highlighted+ /// with the Decompiler pane's `decomp_tokens` highlighter.+ pub fn is_pseudo_c(&self) -> bool {+ match self {+ MarkdownBlock::Code { lang, .. } => {+ matches!(+ lang.to_ascii_lowercase().as_str(),+ "c" | "cpp" | "c++" | "pseudo-c" | "pseudoc" | "pseudo_c"+ )+ }+ _ => false,+ }+ }++ /// True if the block is a code fence with `json` — GUI renders with a+ /// monospace box + copy button.+ pub fn is_json(&self) -> bool {+ matches!(+ self,+ MarkdownBlock::Code { lang, .. } if lang.eq_ignore_ascii_case("json")+ )+ }+}++/// Split streamed Markdown into alternating prose / code blocks.+///+/// Rules:+///+/// - A line whose *stripped* content begins with ` ``` ` opens or closes a+/// fence; the tail after the backticks (up to whitespace) is the language.+/// - Unterminated fences are still emitted as a code block (truncated+/// streaming input renders sensibly).+/// - Empty inputs return an empty vec.+/// - Consecutive prose lines coalesce into a single [`MarkdownBlock::Prose`].+pub fn parse_markdown(input: &str) -> Vec<MarkdownBlock> {+ let mut out: Vec<MarkdownBlock> = Vec::new();+ let mut prose_buf = String::new();+ let mut code_buf = String::new();+ let mut code_lang = String::new();+ let mut in_code = false;++ for line in input.split_inclusive('\n') {+ let stripped = line.trim_end_matches('\n').trim_end_matches('\r');+ let s = stripped.trim_start();+ if s.starts_with("```") {+ if in_code {+ push_code(&mut out, std::mem::take(&mut code_lang), std::mem::take(&mut code_buf));+ in_code = false;+ } else {+ push_prose(&mut out, std::mem::take(&mut prose_buf));+ let after = s.trim_start_matches('`').trim();+ let lang: String = after+ .split(|c: char| c.is_whitespace())+ .next()+ .unwrap_or("")+ .to_string();+ code_lang = lang;+ in_code = true;+ }+ continue;+ }+ if in_code {+ code_buf.push_str(line);+ } else {+ prose_buf.push_str(line);+ }+ }+ if in_code {+ // Streaming truncation: flush the partial code block so the pane still+ // renders something monospace instead of eating half the stream.+ push_code(&mut out, code_lang, code_buf);+ } else {+ push_prose(&mut out, prose_buf);+ }+ out+}++fn push_prose(out: &mut Vec<MarkdownBlock>, buf: String) {+ if buf.is_empty() {+ return;+ }+ if let Some(MarkdownBlock::Prose(last)) = out.last_mut() {+ last.push_str(&buf);+ return;+ }+ out.push(MarkdownBlock::Prose(buf));+}++fn push_code(out: &mut Vec<MarkdownBlock>, lang: String, body: String) {+ out.push(MarkdownBlock::Code { lang, body });+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn empty_input() {+ assert!(parse_markdown("").is_empty());+ }++ #[test]+ fn plain_prose_is_single_block() {+ let bs = parse_markdown("hello\nworld\n");+ assert_eq!(bs.len(), 1);+ assert!(matches!(bs[0], MarkdownBlock::Prose(_)));+ }++ #[test]+ fn splits_fenced_code_with_language() {+ let src = "before\n```c\nint x = 0;\n```\nafter\n";+ let bs = parse_markdown(src);+ assert_eq!(bs.len(), 3);+ assert!(matches!(&bs[0], MarkdownBlock::Prose(p) if p.trim() == "before"));+ match &bs[1] {+ MarkdownBlock::Code { lang, body } => {+ assert_eq!(lang, "c");+ assert!(body.contains("int x = 0;"));+ }+ _ => panic!("expected code"),+ }+ assert!(matches!(&bs[2], MarkdownBlock::Prose(p) if p.trim() == "after"));+ }++ #[test]+ fn unterminated_fence_still_flushes() {+ let src = "prose\n```json\n{\"a\":1}\n";+ let bs = parse_markdown(src);+ assert_eq!(bs.len(), 2);+ match &bs[1] {+ MarkdownBlock::Code { lang, body } => {+ assert_eq!(lang, "json");+ assert!(body.contains("\"a\":1"));+ }+ _ => panic!("expected code fallback"),+ }+ }++ #[test]+ fn language_variants_map_to_pseudo_c() {+ for l in ["c", "C", "cpp", "c++", "pseudo-c", "pseudoc", "PSEUDO_C"] {+ let b = MarkdownBlock::Code {+ lang: l.into(),+ body: "x;".into(),+ };+ assert!(b.is_pseudo_c(), "{l} should be pseudo-c");+ }+ assert!(!MarkdownBlock::Code {+ lang: "rust".into(),+ body: "x;".into()+ }+ .is_pseudo_c());+ }++ #[test]+ fn json_language_flag() {+ let b = MarkdownBlock::Code {+ lang: "JSON".into(),+ body: "{}".into(),+ };+ assert!(b.is_json());+ }++ #[test]+ fn indented_fence_still_matches() {+ let src = " ```c\nint a;\n ```\n";+ let bs = parse_markdown(src);+ assert_eq!(bs.len(), 1);+ match &bs[0] {+ MarkdownBlock::Code { lang, body } => {+ assert_eq!(lang, "c");+ assert!(body.contains("int a;"));+ }+ _ => panic!("expected code"),+ }+ }+}diff --git a/crates/ghidrust-agent/src/policy.rs b/crates/ghidrust-agent/src/policy.rsnew file mode 100644index 0000000..0a5de3d--- /dev/null+++ b/crates/ghidrust-agent/src/policy.rs@@ -0,0 +1,131 @@+//! Agent execution mode — enforced in the tool bridge, not the prompt.+//!+//! The mode is a hard gate on which Ghidrust tools the sidecar is allowed to+//! call. A rogue LLM cannot bypass it because [`AgentMode::is_destructive_allowed`]+//! is checked before the child's `tools/call` is dispatched to the local MCP+//! server. `airgap` mode disables the pane entirely so no child is spawned and+//! no network traffic can leave the process — matching Ghidrust's airgap-safe+//! CLI baseline.++use serde::{Deserialize, Serialize};++/// Session-wide policy — persisted per project alongside the audit log.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub enum AgentMode {+ /// Pane disabled; no `grok` child spawned; no network traffic possible.+ Airgap,+ /// Non-destructive tools only (`load`, `disassemble`, `list_*`, `decompile`,+ /// `get_xrefs_*`, `rtti`, `analyze` — all read-only).+ ReadOnly,+ /// All tools allowed but destructive calls (`rename_*`, `set_comment`,+ /// `apply_patch`, `project_*` writes) go through the GUI approval strip.+ Full,+}++impl AgentMode {+ /// Human-readable badge for the session header.+ pub const fn label(self) -> &'static str {+ match self {+ AgentMode::Airgap => "airgap",+ AgentMode::ReadOnly => "read-only",+ AgentMode::Full => "full",+ }+ }++ /// True if the pane should be enabled and a child may be spawned.+ pub const fn is_enabled(self) -> bool {+ !matches!(self, AgentMode::Airgap)+ }++ /// True if destructive tools are dispatchable **after** user approval.+ pub const fn is_destructive_allowed(self) -> bool {+ matches!(self, AgentMode::Full)+ }++ /// Default mode for a fresh session — read-only so nothing is written+ /// without the user opting up to `Full`.+ pub const fn default_session() -> Self {+ AgentMode::ReadOnly+ }+}++impl Default for AgentMode {+ fn default() -> Self {+ Self::default_session()+ }+}++/// Classify a tool name as destructive (mutates the on-disk analysis / project).+///+/// The list is intentionally conservative: anything that renames, comments,+/// retypes, patches, or writes project artifacts is destructive. Bench /+/// decode-only tools are non-destructive.+pub fn is_destructive_tool(tool_name: &str) -> bool {+ matches!(+ tool_name,+ "rename_function"+ | "rename_data"+ | "rename_variable"+ | "set_comment"+ | "set_decompiler_comment"+ | "set_disassembly_comment"+ | "set_function_prototype"+ | "set_local_variable_type"+ | "apply_patch"+ | "project_analyze"+ | "project_import"+ | "project_export"+ | "write"+ )+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn mode_labels_are_stable() {+ assert_eq!(AgentMode::Airgap.label(), "airgap");+ assert_eq!(AgentMode::ReadOnly.label(), "read-only");+ assert_eq!(AgentMode::Full.label(), "full");+ }++ #[test]+ fn airgap_disables_pane() {+ assert!(!AgentMode::Airgap.is_enabled());+ assert!(AgentMode::ReadOnly.is_enabled());+ assert!(AgentMode::Full.is_enabled());+ }++ #[test]+ fn only_full_allows_destructive() {+ assert!(!AgentMode::Airgap.is_destructive_allowed());+ assert!(!AgentMode::ReadOnly.is_destructive_allowed());+ assert!(AgentMode::Full.is_destructive_allowed());+ }++ #[test]+ fn destructive_tool_classification() {+ for t in [+ "rename_function",+ "rename_variable",+ "set_comment",+ "set_function_prototype",+ "apply_patch",+ "write",+ ] {+ assert!(is_destructive_tool(t), "{t} should be destructive");+ }+ for t in [+ "load",+ "disassemble",+ "list_analyzers",+ "decompile",+ "get_xrefs_to",+ "list_strings",+ "analyze",+ ] {+ assert!(!is_destructive_tool(t), "{t} should be non-destructive");+ }+ }+}diff --git a/crates/ghidrust-agent/src/system_prompt.rs b/crates/ghidrust-agent/src/system_prompt.rsnew file mode 100644index 0000000..91b00d3--- /dev/null+++ b/crates/ghidrust-agent/src/system_prompt.rs@@ -0,0 +1,175 @@+//! System prompt builder — assembles the initial context the agent sees on+//! session start plus a small delta at each new binary load.+//!+//! The prompt is a single string composed of three parts:+//!+//! 1. **Ghidrust honesty envelope** — verbatim `SKILL.md` "agent rules"+//! (no-fabrication, exact analyzer names, staged decompile guardrails).+//! 2. **Program facts** — live JSON snapshot the agent can reference when+//! naming addresses / sections / functions. Never fabricated — the GUI+//! fills this in from `Program` state, so if a field is unknown it stays+//! unknown (empty).+//! 3. **User-facing guidance** — tells the agent to jump the pane / listing+//! on tool results and remind the user about `airgap` / `read-only` mode.+//!+//! This module is intentionally UI-free — the GUI passes a+//! [`ProgramFacts`] snapshot and gets back a plain `String` it can hand to the+//! `AgentSession`.++use serde::{Deserialize, Serialize};++/// Live program-facts snapshot the GUI passes on each session start / activate.+///+/// Everything is optional so the agent doesn't see fabricated fields when a+/// program isn't loaded (mirrors Ghidrust's "empty on no evidence" rule).+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct ProgramFacts {+ pub project_name: Option<String>,+ pub project_root: Option<String>,+ pub program: Option<String>,+ pub format: Option<String>,+ pub arch: Option<String>,+ pub image_base: Option<String>,+ pub entry_va: Option<String>,+ pub sections: Vec<SectionFact>,+ pub analyzers_run: Vec<String>,+ pub functions: Option<usize>,+ pub strings: Option<usize>,+ pub current_selection: Option<SelectionFact>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SectionFact {+ pub name: String,+ pub va: String,+ pub size: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SelectionFact {+ pub va: String,+ pub name: Option<String>,+}++/// System-prompt assembler.+///+/// Callers typically:+///+/// ```ignore+/// let prompt = SystemPromptBuilder::new(skill_md_contents)+/// .facts(facts)+/// .airgap_note(false)+/// .build();+/// ```+pub struct SystemPromptBuilder<'a> {+ skill_md: &'a str,+ facts: Option<&'a ProgramFacts>,+ airgap_note: bool,+ read_only_note: bool,+}++impl<'a> SystemPromptBuilder<'a> {+ pub fn new(skill_md: &'a str) -> Self {+ Self {+ skill_md,+ facts: None,+ airgap_note: false,+ read_only_note: true,+ }+ }++ pub fn facts(mut self, facts: &'a ProgramFacts) -> Self {+ self.facts = Some(facts);+ self+ }++ pub fn airgap_note(mut self, on: bool) -> Self {+ self.airgap_note = on;+ self+ }++ pub fn read_only_note(mut self, on: bool) -> Self {+ self.read_only_note = on;+ self+ }++ pub fn build(self) -> String {+ let mut out = String::with_capacity(self.skill_md.len() + 1024);+ out.push_str("You are Ghidrust's in-GUI reverse-engineering copilot.\n");+ out.push_str("The user is running Ghidrust (Rust RE toolkit) with a project open.\n");+ out.push_str("You have MCP access to every shipped Ghidrust tool via the `ghidrust` server.\n\n");++ out.push_str("## Non-negotiable rules\n\n");+ out.push_str("- Never invent analysis. If a binary hasn't been loaded, say so — do not fabricate addresses, symbols, or decompile output.\n");+ out.push_str("- Always acquire addresses through a tool call (`load`, `analyze`, `function_at`, `get_xrefs_*`). Never guess a VA.\n");+ out.push_str("- Use exact analyzer names from `list_analyzers` when calling `analyze` — no abbreviations.\n");+ out.push_str("- Emit decompile output at the stage the tool returned. Do not claim Hex-Rays / Ghidra parity.\n");+ out.push_str("- Do not conflate Ghidra MCP with Ghidrust MCP — this is Ghidrust.\n");++ if self.read_only_note {+ out.push_str("- Session mode is currently **read-only**. Destructive tools (rename_*, set_comment, apply_patch, project_*) will be rejected. Ask the user to switch to `full` mode if you need them, and always show the intended change first.\n");+ }+ if self.airgap_note {+ out.push_str("- Session mode is currently **airgap**. Do not attempt any outbound network call or tool that would require one.\n");+ }+ out.push('\n');++ if let Some(f) = self.facts {+ out.push_str("## Live program facts (from Ghidrust GUI state)\n\n");+ out.push_str("```json\n");+ let json =+ serde_json::to_string_pretty(f).unwrap_or_else(|_| "{}".to_string());+ out.push_str(&json);+ out.push_str("\n```\n\n");+ }++ out.push_str("## Ghidrust skill (verbatim — the authoritative catalog)\n\n");+ out.push_str(self.skill_md);++ out+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn build_includes_skill_and_rules() {+ let prompt = SystemPromptBuilder::new("# skill body\ncontent")+ .read_only_note(true)+ .build();+ assert!(prompt.contains("Ghidrust"));+ assert!(prompt.contains("Never invent analysis"));+ assert!(prompt.contains("skill body"));+ assert!(prompt.contains("read-only"));+ }++ #[test]+ fn build_with_facts_embeds_json_block() {+ let facts = ProgramFacts {+ project_name: Some("MyCase".into()),+ program: Some("app.exe".into()),+ format: Some("PE".into()),+ arch: Some("x86_64".into()),+ entry_va: Some("0x140001000".into()),+ functions: Some(42),+ ..ProgramFacts::default()+ };+ let prompt = SystemPromptBuilder::new("skill").facts(&facts).build();+ assert!(prompt.contains("Live program facts"));+ assert!(prompt.contains("app.exe"));+ assert!(prompt.contains("0x140001000"));+ assert!(prompt.contains("\"functions\": 42"));+ }++ #[test]+ fn airgap_note_appended_when_enabled() {+ let prompt = SystemPromptBuilder::new("skill")+ .airgap_note(true)+ .read_only_note(false)+ .build();+ assert!(prompt.contains("airgap"));+ assert!(!prompt.contains("read-only"));+ }+}diff --git a/crates/ghidrust-agent/src/tool_bridge.rs b/crates/ghidrust-agent/src/tool_bridge.rsnew file mode 100644index 0000000..4504231--- /dev/null+++ b/crates/ghidrust-agent/src/tool_bridge.rs@@ -0,0 +1,157 @@+//! Tool bridge — wires the local `ghidrust mcp` server into the Grok Build+//! child so the agent can call every shipped Ghidrust tool with **zero new+//! Rust surface**.+//!+//! What this module does:+//!+//! 1. Writes `<project>/.grok/mcp.json` pointing at the user's `ghidrust`+//! binary (`ghidrust mcp` stdio). Grok Build reads this on session start and+//! exposes each tool with its upstream schema, matching what+//! [`crate::ProgramFacts`] and the pane-level system prompt reference.+//! 2. Copies the workspace `skill/SKILL.md` to+//! `<project>/.grok/skills/ghidrust/SKILL.md` so the agent has the full+//! exhaustive Ghidrust catalog + decision tree + "no fabrication" rules+//! in-context.+//!+//! Both are idempotent — call them on every session start. Users may hand-edit+//! either file; we don't overwrite if the content matches.++use serde_json::json;+use std::fs;+use std::io;+use std::path::{Path, PathBuf};++/// Ensure `<project>/.grok/mcp.json` exists and references the Ghidrust MCP+/// stdio server.+///+/// - `project_root` is the directory the agent will run in.+/// - `ghidrust_bin` is the absolute path to the `ghidrust` binary the agent+/// should spawn as its MCP server (`ghidrust mcp`).+///+/// The written file uses Grok Build's `mcpServers` shape (also compatible with+/// Claude Desktop / Cursor MCP config):+///+/// ```json+/// {+/// "mcpServers": {+/// "ghidrust": {+/// "command": "…/ghidrust(.exe)",+/// "args": ["mcp"]+/// }+/// }+/// }+/// ```+pub fn write_project_mcp_config(project_root: &Path, ghidrust_bin: &Path) -> io::Result<PathBuf> {+ let grok_dir = project_root.join(".grok");+ fs::create_dir_all(&grok_dir)?;+ let mcp_path = grok_dir.join("mcp.json");++ let payload = json!({+ "mcpServers": {+ "ghidrust": {+ "command": ghidrust_bin.to_string_lossy(),+ "args": ["mcp"]+ }+ }+ });+ let contents = serde_json::to_string_pretty(&payload)+ .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;++ if let Ok(existing) = fs::read_to_string(&mcp_path) {+ if existing.trim() == contents.trim() {+ return Ok(mcp_path);+ }+ }+ fs::write(&mcp_path, contents)?;+ Ok(mcp_path)+}++/// Ensure `<project>/.grok/skills/ghidrust/SKILL.md` mirrors the workspace+/// `skill/SKILL.md` — so a fresh `grok` install on this project immediately+/// gets the full Ghidrust decision tree and honest catalog on session start.+///+/// - `project_root` is the project directory.+/// - `skill_source` is the workspace-relative source of truth+/// (`<repo>/skill/SKILL.md`).+///+/// If `skill_source` doesn't exist (e.g. Ghidrust was installed as a binary+/// with no bundled skill file), this is a no-op that returns+/// `io::ErrorKind::NotFound`.+pub fn write_project_skill(project_root: &Path, skill_source: &Path) -> io::Result<PathBuf> {+ let skill = fs::read_to_string(skill_source)?;+ let dest_dir = project_root.join(".grok").join("skills").join("ghidrust");+ fs::create_dir_all(&dest_dir)?;+ let dest = dest_dir.join("SKILL.md");++ if let Ok(existing) = fs::read_to_string(&dest) {+ if existing == skill {+ return Ok(dest);+ }+ }+ fs::write(&dest, skill)?;+ Ok(dest)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::PathBuf;++ fn tmp_project(tag: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "ghidrust-agent-test-{}-{}",+ std::process::id(),+ tag+ ));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).unwrap();+ dir+ }++ #[test]+ fn writes_mcp_config() {+ let proj = tmp_project("mcp");+ let bin = PathBuf::from("/opt/ghidrust/ghidrust");+ let out = write_project_mcp_config(&proj, &bin).unwrap();+ let contents = fs::read_to_string(&out).unwrap();+ assert!(contents.contains("mcpServers"));+ assert!(contents.contains("ghidrust"));+ assert!(contents.contains("mcp"));+ assert!(out.ends_with(PathBuf::from(".grok").join("mcp.json")));+ }++ #[test]+ fn mcp_config_is_idempotent() {+ let proj = tmp_project("idem");+ let bin = PathBuf::from("/opt/ghidrust/ghidrust");+ let first = write_project_mcp_config(&proj, &bin).unwrap();+ let mtime_first = fs::metadata(&first).unwrap().modified().unwrap();+ std::thread::sleep(std::time::Duration::from_millis(10));+ let _ = write_project_mcp_config(&proj, &bin).unwrap();+ let mtime_second = fs::metadata(&first).unwrap().modified().unwrap();+ assert_eq!(+ mtime_first, mtime_second,+ "idempotent write must not touch mtime when contents match"+ );+ }++ #[test]+ fn writes_skill_copy() {+ let proj = tmp_project("skill");+ let skill_src = proj.join("_source_skill.md");+ fs::write(&skill_src, "# fake skill\n").unwrap();+ let out = write_project_skill(&proj, &skill_src).unwrap();+ let contents = fs::read_to_string(&out).unwrap();+ assert!(contents.contains("fake skill"));+ assert!(out.ends_with(+ PathBuf::from(".grok").join("skills").join("ghidrust").join("SKILL.md")+ ));+ }++ #[test]+ fn missing_skill_source_is_error() {+ let proj = tmp_project("miss");+ let err = write_project_skill(&proj, &proj.join("nope.md")).unwrap_err();+ assert_eq!(err.kind(), io::ErrorKind::NotFound);+ }+}diff --git a/crates/ghidrust-cli/src/main.rs b/crates/ghidrust-cli/src/main.rsindex 04444d7..f4d4a11 100644--- a/crates/ghidrust-cli/src/main.rs+++ b/crates/ghidrust-cli/src/main.rs@@ -1,10 +1,11 @@//! Ghidrust CLI + stdio MCP/agent tool surface over ghidrust-core.use ghidrust_core::{- analyzer_catalog, analyze_path, disassemble_range, load_path, recover_rtti,- scan_ascii_strings_bulk, scan_printable_runs_gpu_or_fallback, scan_printable_runs_parallel,- scan_printable_runs_seq, time_bulk_printable, AnalysisBundle, BulkScanMode, Program, Project,- ANALYZER_NAMES,+ analyzer_catalog, analyze_path, collect_strings, disassemble_range, disassemble_range_opts,+ filter_imports, load_path, recover_rtti, run_analyzers, scan_ascii_strings_bulk,+ scan_printable_runs_gpu_or_fallback, scan_printable_runs_parallel, scan_printable_runs_seq,+ time_bulk_printable, xrefs_from, xrefs_to, xrefs_to_import, xrefs_to_string_filter,+ AnalysisBundle, BulkScanMode, Program, Project, ANALYZER_NAMES,};use ghidrust_decomp::decompile_entry;use serde::Serialize;@@ -34,6 +35,10 @@ fn main() -> ExitCode {"rtti" => cmd_rtti(&args[1..], json_mode),"analyzers" => cmd_analyzers(json_mode),"analyze" => cmd_analyze(&args[1..], json_mode),+ "strings" => cmd_strings(&args[1..], json_mode),+ "xrefs" => cmd_xrefs(&args[1..], json_mode),+ "imports" => cmd_imports(&args[1..], json_mode),+ "function-at" => cmd_function_at(&args[1..], json_mode),"bulk-bench" => cmd_bulk_bench(&args[1..], json_mode),"decompile" => cmd_decompile(&args[1..], json_mode),"decompile-bench" => cmd_decompile_bench(&args[1..], json_mode),@@ -61,12 +66,16 @@ fn print_help() {"ghidrust — AI-native reverse-engineering (CodeBrowser headless)\n\n\Usage:\n\ghidrust load <path> [--json]\n\- ghidrust disasm <path> [--addr <hex>] [--count N] [--json]\n\+ ghidrust disasm <path> [--addr <hex>] [--count N] [--skip-bad] [--json]\n\+ ghidrust strings <path> [--encoding ascii|utf16|all] [--filter SUB] [--min N] [--json]\n\+ ghidrust xrefs <path> (--to HEX | --from HEX | --string FILTER | --import NAME) [--json]\n\+ ghidrust imports <path> [--dll NAME] [--name NAME] [--json]\n\+ ghidrust function-at <path> --addr HEX [--json]\n\ghidrust rtti <path> [--json]\n\ghidrust analyzers [--json]\n\ghidrust analyze <path> [--analyzers a,b | --analyzer NAME ...] [--gpu] [--json]\n\ghidrust bulk-bench <path> [--json] # seq vs parallel vs GPU/fallback timings\n\- ghidrust decompile <path> [--addr HEX] [--count N] [--stage0|--stage05|--stage1 (default)] [--json]\n\+ ghidrust decompile <path> [--addr HEX] [--count N] [--stage0|--stage05|--stage1] [--verbose] [--json]\n\ghidrust decompile-bench <path> [--functions N] [--count N] [--out FILE] [--stage1] [--parallel] [--json]\n\ghidrust ghidra-headtohead <path> [--functions N] [--count N] [--ghidra DIR] [--captured JSON] [--out FILE] [--spawn-timeout SECS] [--ghidra-fn-cap N] [--json]\n\ghidrust gpu-decompile <path> [--out FILE] [--metrics FILE] [--json]\n\@@ -389,6 +398,16 @@ fn emit_load(prog: &Program, json: bool) {}}+fn emit_json<T: Serialize>(value: &T) {+ // UTF-8 without BOM — suitable for piping / PowerShell ConvertFrom-Json.+ let mut out = io::stdout().lock();+ if let Err(e) = serde_json::to_writer_pretty(&mut out, value) {+ eprintln!("json write error: {e}");+ return;+ }+ let _ = writeln!(out);+}+fn cmd_disasm(args: &[String], json: bool) -> ExitCode {let path = match path_arg(args) {Ok(p) => p,@@ -399,6 +418,7 @@ fn cmd_disasm(args: &[String], json: bool) -> ExitCode {};let mut addr: Option<u64> = None;let mut count: usize = 16;+ let mut skip_bad = false;let mut i = 1;while i < args.len() {match args[i].as_str() {@@ -410,16 +430,20 @@ fn cmd_disasm(args: &[String], json: bool) -> ExitCode {count = args[i + 1].parse().unwrap_or(16);i += 2;}+ "--skip-bad" => {+ skip_bad = true;+ i += 1;+ }_ => i += 1,}}match load_path(&path) {Ok(prog) => {let start = addr.or(prog.entry).unwrap_or(prog.image_base);- match disassemble_range(&prog, start, count) {+ match disassemble_range_opts(&prog, start, count, skip_bad) {Ok(listing) => {if json {- println!("{}", serde_json::to_string_pretty(&listing).unwrap());+ emit_json(&listing);} else {for insn in &listing {println!("{}", insn.text());@@ -440,6 +464,260 @@ fn cmd_disasm(args: &[String], json: bool) -> ExitCode {}}+fn cmd_strings(args: &[String], json: bool) -> ExitCode {+ let path = match path_arg(args) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("{e}");+ return ExitCode::from(2);+ }+ };+ let mut encoding = "all".to_string();+ let mut filter: Option<String> = None;+ let mut min_len: usize = 4;+ let mut i = 1;+ while i < args.len() {+ match args[i].as_str() {+ "--encoding" if i + 1 < args.len() => {+ encoding = args[i + 1].clone();+ i += 2;+ }+ "--filter" | "--contains" if i + 1 < args.len() => {+ filter = Some(args[i + 1].clone());+ i += 2;+ }+ "--min" if i + 1 < args.len() => {+ min_len = args[i + 1].parse().unwrap_or(4);+ i += 2;+ }+ _ => i += 1,+ }+ }+ match load_path(&path).and_then(|prog| {+ collect_strings(&prog, &encoding, min_len, filter.as_deref())+ .map(|s| (prog, s))+ }) {+ Ok((_prog, strings)) => {+ if json {+ emit_json(&strings);+ } else {+ for s in &strings {+ println!("{:#x}\t{}\t{}", s.va, s.encoding, s.value);+ }+ }+ ExitCode::SUCCESS+ }+ Err(e) => {+ eprintln!("error: {e}");+ ExitCode::FAILURE+ }+ }+}++fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {+ let path = match path_arg(args) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("{e}");+ return ExitCode::from(2);+ }+ };+ let mut to: Option<u64> = None;+ let mut from: Option<u64> = None;+ let mut string_filter: Option<String> = None;+ let mut import_name: Option<String> = None;+ let mut i = 1;+ while i < args.len() {+ match args[i].as_str() {+ "--to" if i + 1 < args.len() => {+ to = parse_u64(&args[i + 1]).ok();+ i += 2;+ }+ "--from" if i + 1 < args.len() => {+ from = parse_u64(&args[i + 1]).ok();+ i += 2;+ }+ "--string" if i + 1 < args.len() => {+ string_filter = Some(args[i + 1].clone());+ i += 2;+ }+ "--import" if i + 1 < args.len() => {+ import_name = Some(args[i + 1].clone());+ i += 2;+ }+ _ => i += 1,+ }+ }+ let modes = [to.is_some(), from.is_some(), string_filter.is_some(), import_name.is_some()]+ .iter()+ .filter(|&&b| b)+ .count();+ if modes != 1 {+ eprintln!(+ "usage: ghidrust xrefs <path> (--to HEX | --from HEX | --string FILTER | --import NAME) [--json]"+ );+ return ExitCode::from(2);+ }+ match load_path(&path) {+ Ok(prog) => {+ let refs = if let Some(t) = to {+ xrefs_to(&prog, t, None)+ } else if let Some(f) = from {+ xrefs_from(&prog, f, 256)+ } else if let Some(s) = string_filter {+ xrefs_to_string_filter(&prog, &s)+ } else {+ xrefs_to_import(&prog, import_name.as_deref().unwrap())+ };+ if json {+ let rows: Vec<_> = refs+ .iter()+ .map(|r| {+ json!({+ "from": format!("{:#x}", r.from),+ "to": format!("{:#x}", r.to),+ "kind": r.kind,+ "preview": r.preview,+ })+ })+ .collect();+ emit_json(&rows);+ } else {+ for r in &refs {+ println!("{:#x} -> {:#x} [{}] {}", r.from, r.to, r.kind, r.preview);+ }+ }+ ExitCode::SUCCESS+ }+ Err(e) => {+ eprintln!("error: {e}");+ ExitCode::FAILURE+ }+ }+}++fn cmd_imports(args: &[String], json: bool) -> ExitCode {+ let path = match path_arg(args) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("{e}");+ return ExitCode::from(2);+ }+ };+ let mut dll: Option<String> = None;+ let mut name: Option<String> = None;+ let mut i = 1;+ while i < args.len() {+ match args[i].as_str() {+ "--dll" if i + 1 < args.len() => {+ dll = Some(args[i + 1].clone());+ i += 2;+ }+ "--name" if i + 1 < args.len() => {+ name = Some(args[i + 1].clone());+ i += 2;+ }+ _ => i += 1,+ }+ }+ match load_path(&path) {+ Ok(prog) => {+ let filtered: Vec<_> = filter_imports(&prog.imports, dll.as_deref(), name.as_deref())+ .into_iter()+ .cloned()+ .collect();+ if json {+ emit_json(&filtered);+ } else {+ for e in &filtered {+ let sym = e+ .name+ .clone()+ .unwrap_or_else(|| format!("ord_{}", e.ordinal.unwrap_or(0)));+ println!(+ "{:#x}\t{}!{}",+ e.iat_va, e.dll, sym+ );+ }+ }+ ExitCode::SUCCESS+ }+ Err(e) => {+ eprintln!("error: {e}");+ ExitCode::FAILURE+ }+ }+}++fn cmd_function_at(args: &[String], json: bool) -> ExitCode {+ let path = match path_arg(args) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("{e}");+ return ExitCode::from(2);+ }+ };+ let mut addr: Option<u64> = None;+ let mut i = 1;+ while i < args.len() {+ match args[i].as_str() {+ "--addr" if i + 1 < args.len() => {+ addr = parse_u64(&args[i + 1]).ok();+ i += 2;+ }+ _ => i += 1,+ }+ }+ let Some(va) = addr else {+ eprintln!("usage: ghidrust function-at <path> --addr HEX [--json]");+ return ExitCode::from(2);+ };+ match load_path(&path).and_then(|mut prog| {+ if prog.analysis.functions.is_empty() {+ let _ = run_analyzers(&mut prog, &["Function Start Search"])?;+ }+ Ok(prog)+ }) {+ Ok(prog) => match prog.function_containing(va) {+ Some(f) => {+ if json {+ emit_json(&json!({+ "addr": format!("{va:#x}"),+ "entry": format!("{:#x}", f.entry),+ "end": format!("{:#x}", f.end),+ "name": f.name,+ "calling_convention": f.calling_convention,+ "noreturn": f.noreturn,+ "parameters": f.parameters,+ }));+ } else {+ println!(+ "{:#x} in {} [{:#x}, {:#x})",+ va, f.name, f.entry, f.end+ );+ }+ ExitCode::SUCCESS+ }+ None => {+ if json {+ emit_json(&json!({+ "addr": format!("{va:#x}"),+ "function": null,+ }));+ ExitCode::SUCCESS+ } else {+ eprintln!("no function contains {va:#x}");+ ExitCode::FAILURE+ }+ }+ },+ Err(e) => {+ eprintln!("error: {e}");+ ExitCode::FAILURE+ }+ }+}+fn cmd_rtti(args: &[String], json: bool) -> ExitCode {let path = match path_arg(args) {Ok(p) => p,@@ -941,7 +1219,7 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {Some(p) => PathBuf::from(p),None => {eprintln!(- "usage: ghidrust decompile <path> [--addr HEX] [--count N] [--stage0|--stage05|--stage1] [--json]"+ "usage: ghidrust decompile <path> [--addr HEX] [--count N] [--stage0|--stage05|--stage1] [--verbose] [--json]");return ExitCode::from(2);}@@ -954,6 +1232,7 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {let mut stage05 = false;let mut stage0 = false;let mut stage1 = true;+ let mut verbose = false;let mut i = 1;while i < args.len() {match args[i].as_str() {@@ -982,6 +1261,10 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {stage0 = false;i += 1;}+ "--verbose" | "-v" => {+ verbose = true;+ i += 1;+ }_ => i += 1,}}@@ -1010,19 +1293,21 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {"total_ops": s1.coverage.total_ops,}});- println!("{}", serde_json::to_string_pretty(&obj).unwrap());+ emit_json(&obj);} else {print!("{}", d.pseudo_c);- eprintln!(- "[{}] stage=1 blocks={} phis={} loops={} locals={} params={} lift={:.1}%",- d.name,- d.blocks.len(),- s1.ssa.phi_count(),- s1.structure.loops.len(),- s1.types.locals.len(),- s1.types.params.len(),- s1.coverage.ratio() * 100.0- );+ if verbose {+ eprintln!(+ "[{}] stage=1 blocks={} phis={} loops={} locals={} params={} lift={:.1}%",+ d.name,+ d.blocks.len(),+ s1.ssa.phi_count(),+ s1.structure.loops.len(),+ s1.types.locals.len(),+ s1.types.params.len(),+ s1.coverage.ratio() * 100.0+ );+ }}return ExitCode::SUCCESS;}@@ -1045,19 +1330,21 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {"ratio": cov.ratio(),}});- println!("{}", serde_json::to_string_pretty(&obj).unwrap());+ emit_json(&obj);} else {print!("{}", d.pseudo_c);- eprintln!(- "[{}] stage=0.5 blocks={} edges={} insns={} ir_ops={} lift={:.1}% lines={}",- d.name,- d.blocks.len(),- d.edges.len(),- d.insn_count,- cov.total_ops,- cov.ratio() * 100.0,- d.line_count()- );+ if verbose {+ eprintln!(+ "[{}] stage=0.5 blocks={} edges={} insns={} ir_ops={} lift={:.1}% lines={}",+ d.name,+ d.blocks.len(),+ d.edges.len(),+ d.insn_count,+ cov.total_ops,+ cov.ratio() * 100.0,+ d.line_count()+ );+ }}ExitCode::SUCCESS}@@ -1070,17 +1357,19 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {match ghidrust_decomp::decompile_at(&prog, va, count) {Ok(d) => {if json {- println!("{}", serde_json::to_string_pretty(&d).unwrap());+ emit_json(&d);} else {print!("{}", d.pseudo_c);- eprintln!(- "[{}] stage=0 blocks={} edges={} insns={} lines={}",- d.name,- d.blocks.len(),- d.edges.len(),- d.insn_count,- d.line_count()- );+ if verbose {+ eprintln!(+ "[{}] stage=0 blocks={} edges={} insns={} lines={}",+ d.name,+ d.blocks.len(),+ d.edges.len(),+ d.insn_count,+ d.line_count()+ );+ }}ExitCode::SUCCESS}@@ -1649,6 +1938,21 @@ fn fmt_opt_va(v: Option<u64>) -> String {v.map(|x| format!("{x:#x}")).unwrap_or_else(|| "-".into())}+fn refs_json(refs: &[ghidrust_core::XRef]) -> Value {+ Value::Array(+ refs.iter()+ .map(|r| {+ json!({+ "from": format!("{:#x}", r.from),+ "to": format!("{:#x}", r.to),+ "kind": r.kind,+ "preview": r.preview,+ })+ })+ .collect(),+ )+}+fn parse_u64(s: &str) -> Result<u64, String> {let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");u64::from_str_radix(t, 16)@@ -1765,6 +2069,120 @@ fn tool_defs() -> Vec<ToolDef> {"required": ["path"]}),},+ ToolDef {+ name: "list_strings",+ description: "Scan ASCII and/or UTF-16LE strings; optional filter substring/glob",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "encoding": { "type": "string", "enum": ["ascii", "utf16", "all"] },+ "filter": { "type": "string" },+ "min": { "type": "integer" }+ },+ "required": ["path"]+ }),+ },+ ToolDef {+ name: "search_strings",+ description: "Alias of list_strings (filter-oriented)",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "encoding": { "type": "string", "enum": ["ascii", "utf16", "all"] },+ "filter": { "type": "string" },+ "min": { "type": "integer" }+ },+ "required": ["path"]+ }),+ },+ ToolDef {+ name: "get_xrefs_to",+ description: "Cross-references to a VA (includes RIP-relative LEA/call/jmp)",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "addr": { "type": "string" }+ },+ "required": ["path", "addr"]+ }),+ },+ ToolDef {+ name: "get_xrefs_from",+ description: "Cross-references from a VA (disassemble forward)",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "addr": { "type": "string" },+ "count": { "type": "integer" }+ },+ "required": ["path", "addr"]+ }),+ },+ ToolDef {+ name: "get_string_xrefs",+ description: "Find strings by filter, then xrefs to each string VA",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "filter": { "type": "string" }+ },+ "required": ["path", "filter"]+ }),+ },+ ToolDef {+ name: "list_imports",+ description: "List PE import / IAT slots (optional dll/name filter)",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "dll": { "type": "string" },+ "name": { "type": "string" }+ },+ "required": ["path"]+ }),+ },+ ToolDef {+ name: "get_import_xrefs",+ description: "Code sites that reference an import IAT slot (e.g. ShellExecuteW)",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "name": { "type": "string" }+ },+ "required": ["path", "name"]+ }),+ },+ ToolDef {+ name: "function_at",+ description: "Containing function for a VA (runs Function Start Search if needed)",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "addr": { "type": "string" }+ },+ "required": ["path", "addr"]+ }),+ },+ ToolDef {+ name: "get_function_by_address",+ description: "Alias of function_at",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "addr": { "type": "string" }+ },+ "required": ["path", "addr"]+ }),+ },]}@@ -1855,6 +2273,122 @@ fn call_tool(params: &Value) -> Result<String, String> {let args = params.get("arguments").cloned().unwrap_or(json!({}));match name {+ "list_strings" | "search_strings" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let encoding = args+ .get("encoding")+ .and_then(|e| e.as_str())+ .unwrap_or("all");+ let filter = args.get("filter").and_then(|f| f.as_str());+ let min_len = args.get("min").and_then(|m| m.as_u64()).unwrap_or(4) as usize;+ let prog = load_path(path).map_err(|e| e.to_string())?;+ let strings = collect_strings(&prog, encoding, min_len, filter).map_err(|e| e.to_string())?;+ Ok(serde_json::to_string_pretty(&strings).unwrap())+ }+ "get_xrefs_to" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let addr = args+ .get("addr")+ .and_then(|a| a.as_str())+ .ok_or_else(|| "missing arguments.addr".to_string())?;+ let prog = load_path(path).map_err(|e| e.to_string())?;+ let va = parse_u64(addr)?;+ let refs = xrefs_to(&prog, va, None);+ Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())+ }+ "get_xrefs_from" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let addr = args+ .get("addr")+ .and_then(|a| a.as_str())+ .ok_or_else(|| "missing arguments.addr".to_string())?;+ let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(256) as usize;+ let prog = load_path(path).map_err(|e| e.to_string())?;+ let va = parse_u64(addr)?;+ let refs = xrefs_from(&prog, va, count);+ Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())+ }+ "get_string_xrefs" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let filter = args+ .get("filter")+ .and_then(|f| f.as_str())+ .ok_or_else(|| "missing arguments.filter".to_string())?;+ let prog = load_path(path).map_err(|e| e.to_string())?;+ let refs = xrefs_to_string_filter(&prog, filter);+ Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())+ }+ "list_imports" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let dll = args.get("dll").and_then(|d| d.as_str());+ let name_f = args.get("name").and_then(|n| n.as_str());+ let prog = load_path(path).map_err(|e| e.to_string())?;+ let filtered: Vec<_> = filter_imports(&prog.imports, dll, name_f)+ .into_iter()+ .cloned()+ .collect();+ Ok(serde_json::to_string_pretty(&filtered).unwrap())+ }+ "get_import_xrefs" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let iname = args+ .get("name")+ .and_then(|n| n.as_str())+ .ok_or_else(|| "missing arguments.name".to_string())?;+ let prog = load_path(path).map_err(|e| e.to_string())?;+ let refs = xrefs_to_import(&prog, iname);+ Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())+ }+ "function_at" | "get_function_by_address" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let addr = args+ .get("addr")+ .and_then(|a| a.as_str())+ .ok_or_else(|| "missing arguments.addr".to_string())?;+ let mut prog = load_path(path).map_err(|e| e.to_string())?;+ if prog.analysis.functions.is_empty() {+ let _ = run_analyzers(&mut prog, &["Function Start Search"]).map_err(|e| e.to_string())?;+ }+ let va = parse_u64(addr)?;+ match prog.function_containing(va) {+ Some(f) => Ok(serde_json::to_string_pretty(&json!({+ "addr": format!("{va:#x}"),+ "entry": format!("{:#x}", f.entry),+ "end": format!("{:#x}", f.end),+ "name": f.name,+ "calling_convention": f.calling_convention,+ "noreturn": f.noreturn,+ "parameters": f.parameters,+ }))+ .unwrap()),+ None => Ok(serde_json::to_string_pretty(&json!({+ "addr": format!("{va:#x}"),+ "function": null,+ }))+ .unwrap()),+ }+ }"list_analyzers" => {let cat = analyzer_catalog();Ok(serde_json::to_string_pretty(&cat).unwrap())diff --git a/crates/ghidrust-cli/tests/cli_mcp.rs b/crates/ghidrust-cli/tests/cli_mcp.rsindex 1368906..f7b4087 100644--- a/crates/ghidrust-cli/tests/cli_mcp.rs+++ b/crates/ghidrust-cli/tests/cli_mcp.rs@@ -93,3 +93,88 @@ fn mcp_list_and_analyze() {let s = String::from_utf8_lossy(&out.stdout);assert!(s.contains("Widget") || s.contains("ok"), "{s}");}++#[test]+fn cli_strings_utf16_and_json_no_bom() {+ let pe = fixture_path("analysis_lab.pe");+ let out = bin()+ .args([+ "strings",+ pe.to_str().unwrap(),+ "--encoding",+ "utf16",+ "--filter",+ "WideLabString",+ "--json",+ ])+ .output()+ .expect("strings");+ assert!(out.status.success(), "stderr={}", String::from_utf8_lossy(&out.stderr));+ assert!(!out.stdout.starts_with(&[0xEF, 0xBB, 0xBF]), "JSON must be BOM-free");+ assert_eq!(out.stdout.first().copied(), Some(b'['));+ let s = String::from_utf8_lossy(&out.stdout);+ assert!(s.contains("WideLabString"), "{s}");+ assert!(s.contains("utf16le"), "{s}");+}++#[test]+fn cli_function_at_entry() {+ let pe = fixture_path("analysis_lab.pe");+ let out = bin()+ .args([+ "function-at",+ pe.to_str().unwrap(),+ "--addr",+ "0x140001000",+ "--json",+ ])+ .output()+ .expect("function-at");+ assert!(out.status.success(), "stderr={}", String::from_utf8_lossy(&out.stderr));+ let s = String::from_utf8_lossy(&out.stdout);+ assert!(s.contains("0x140001000"), "{s}");+}++#[test]+fn cli_imports_lists_slots() {+ let pe = fixture_path("analysis_lab.pe");+ let out = bin()+ .args(["imports", pe.to_str().unwrap(), "--json"])+ .output()+ .expect("imports");+ assert!(out.status.success(), "stderr={}", String::from_utf8_lossy(&out.stderr));+ let s = String::from_utf8_lossy(&out.stdout);+ // Lab fixture imports at least one named symbol when the PE directory is present.+ assert!(s.starts_with('[') || s.contains("iat_va"), "{s}");+}++#[test]+fn mcp_lists_new_lookup_tools() {+ let mut child = bin()+ .arg("mcp")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .expect("spawn mcp");+ let mut stdin = child.stdin.take().unwrap();+ let req = format!(+ "{}\n",+ json!({"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}})+ );+ stdin.write_all(req.as_bytes()).unwrap();+ drop(stdin);+ let out = child.wait_with_output().unwrap();+ assert!(out.status.success());+ let s = String::from_utf8_lossy(&out.stdout);+ for tool in [+ "list_strings",+ "get_xrefs_to",+ "get_string_xrefs",+ "list_imports",+ "get_import_xrefs",+ "function_at",+ ] {+ assert!(s.contains(tool), "missing {tool} in {s}");+ }+}diff --git a/crates/ghidrust-cli/tests/eval_analysis_decompile.rs b/crates/ghidrust-cli/tests/eval_analysis_decompile.rsindex 65d73f9..4a50e7b 100644--- a/crates/ghidrust-cli/tests/eval_analysis_decompile.rs+++ b/crates/ghidrust-cli/tests/eval_analysis_decompile.rs@@ -115,6 +115,19 @@ fn oracle_ascii_strings(v: &Value) -> (bool, String, Value) {)}+fn oracle_unicode_strings(v: &Value) -> (bool, String, Value) {+ let s = v["strings"].as_array().cloned().unwrap_or_default();+ let has_wide = s.iter().any(|x| {+ x["value"].as_str().unwrap_or("").contains("WideLabString")+ && x["encoding"].as_str().unwrap_or("") == "utf16le"+ });+ (+ has_wide,+ format!("{} utf16 strings; WideLabString={}", s.len(), has_wide),+ json!({ "count": s.len(), "has_wide_lab": has_wide }),+ )+}+fn oracle_function_start(v: &Value) -> (bool, String, Value) {let fns = v["functions"].as_array().cloned().unwrap_or_default();let hex = |x: &Value| x["entry"].as_u64().unwrap_or(0);@@ -393,6 +406,7 @@ fn oracle_resources(v: &Value) -> (bool, String, Value) {fn analyzer_checks() -> Vec<AnalyzerCheck> {vec![AnalyzerCheck { name: "ASCII Strings", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_ascii_strings },+ AnalyzerCheck { name: "Unicode Strings", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_unicode_strings },AnalyzerCheck { name: "Aggressive Instruction Finder", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_aggressive },AnalyzerCheck { name: "Call Convention ID", fixture: "analysis_lab.pe", prereqs: &["Function Start Search"], target_is_last: true, oracle: oracle_call_convention },AnalyzerCheck { name: "Call-Fixup Installer", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_call_fixup },diff --git a/crates/ghidrust-core/src/analyzers/function_start.rs b/crates/ghidrust-core/src/analyzers/function_start.rsindex 60c0fa7..54b0774 100644--- a/crates/ghidrust-core/src/analyzers/function_start.rs+++ b/crates/ghidrust-core/src/analyzers/function_start.rs@@ -122,18 +122,31 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {fn grow_function(prog: &Program, entry: u64) -> u64 {let mut va = entry;let mut end = entry;- for _ in 0..64 {+ let mut skipped = 0u32;+ // Grow generously so mid-body VAs fall inside [entry, end).+ for _ in 0..4096 {let Some(bytes) = prog.read_va(va, 15) else {break;};- let Ok(insn) = decode_one(&bytes, va) else {- break;- };- end = va + insn.length as u64;- if insn.mnemonic == "ret" || insn.mnemonic == "int3" {- break;+ match decode_one(&bytes, va) {+ Ok(insn) => {+ skipped = 0;+ end = va + insn.length as u64;+ if insn.mnemonic == "ret" {+ break;+ }+ va = end;+ }+ Err(_) => {+ // Skip bad bytes to keep extent continuous across decode holes.+ skipped += 1;+ if skipped > 16 {+ break;+ }+ va = va.wrapping_add(1);+ end = end.max(va);+ }}- va = end;}end.max(entry + 1)}diff --git a/crates/ghidrust-core/src/analyzers/mod.rs b/crates/ghidrust-core/src/analyzers/mod.rsindex 29e3179..9b91b8e 100644--- a/crates/ghidrust-core/src/analyzers/mod.rs+++ b/crates/ghidrust-core/src/analyzers/mod.rs@@ -25,11 +25,12 @@ use crate::program::Program;use crate::rtti::{recover_rtti, RttiReport};use serde::Serialize;-pub use strings::{scan_ascii_strings, FoundString};+pub use strings::{collect_strings, scan_ascii_strings, scan_utf16le_strings, FoundString};/// Exact labels from the Ghidra Auto Analysis screenshot (order preserved).pub const ANALYZER_NAMES: &[&str] = &["ASCII Strings",+ "Unicode Strings","Aggressive Instruction Finder","Call Convention ID","Call-Fixup Installer",@@ -120,6 +121,7 @@ pub fn analyzer_catalog() -> Vec<AnalyzerInfo> {default_enabled: matches!(*name,"ASCII Strings"+ | "Unicode Strings"| "WindowsPE x86 PE RTTI Analyzer"| "Function Start Search"| "Create Address Tables"@@ -204,6 +206,7 @@ pub fn run_analyzers_opts(fn run_one(prog: &mut Program, name: &str) -> Result<AnalyzerOutput> {match name {"ASCII Strings" => strings::run(prog),+ "Unicode Strings" => strings::run_unicode(prog),"Aggressive Instruction Finder" => aggressive::run(prog),"Call Convention ID" => call_convention::run(prog),"Call-Fixup Installer" => call_fixup::run(prog),@@ -251,7 +254,7 @@ mod tests {#[test]fn catalog_all_implemented() {let cat = analyzer_catalog();- assert_eq!(cat.len(), 20);+ assert_eq!(cat.len(), 21);assert!(cat.iter().all(|c| c.status == AnalyzerStatus::Implemented));diff --git a/crates/ghidrust-core/src/analyzers/strings.rs b/crates/ghidrust-core/src/analyzers/strings.rsindex d387c3b..55d5a81 100644--- a/crates/ghidrust-core/src/analyzers/strings.rs+++ b/crates/ghidrust-core/src/analyzers/strings.rs@@ -9,6 +9,29 @@ pub struct FoundString {pub va: u64,pub value: String,pub length: usize,+ /// `"ascii"` or `"utf16le"`.+ #[serde(default)]+ pub encoding: String,+}++impl FoundString {+ pub fn ascii(va: u64, value: String, length: usize) -> Self {+ Self {+ va,+ value,+ length,+ encoding: "ascii".into(),+ }+ }++ pub fn utf16le(va: u64, value: String, char_len: usize) -> Self {+ Self {+ va,+ value,+ length: char_len,+ encoding: "utf16le".into(),+ }+ }}/// Uses process preferred bulk mode (parallel CPU or GPU experimental).@@ -25,7 +48,184 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {})}+/// UTF-16LE printable runs across all mapped blocks.+pub fn run_unicode(prog: &mut Program) -> Result<AnalyzerOutput> {+ let strings = scan_utf16le_strings(prog, 4);+ let n = strings.len();+ Ok(AnalyzerOutput {+ name: "Unicode Strings".into(),+ status: "ok".into(),+ message: format!("found {n} UTF-16LE string(s)"),+ strings: Some(strings),+ ..Default::default()+ })+}+/// Sequential oracle (tests / comparison). Parallel via [`scan_ascii_strings_bulk`].pub fn scan_ascii_strings(prog: &Program, min_len: usize) -> Vec<FoundString> {scan_ascii_strings_bulk(prog, min_len, BulkScanMode::Sequential).0}++/// Scan UTF-16LE nul-terminated (or long) printable runs.+///+/// `min_len` is the minimum number of UTF-16 code units (characters).+pub fn scan_utf16le_strings(prog: &Program, min_len: usize) -> Vec<FoundString> {+ let mut out = Vec::new();+ for block in &prog.blocks {+ out.extend(scan_utf16le_in_bytes(block.va, &block.bytes, min_len));+ }+ out.sort_by_key(|s| s.va);+ out.dedup_by(|a, b| a.va == b.va && a.value == b.value);+ out+}++fn scan_utf16le_in_bytes(base_va: u64, bytes: &[u8], min_len: usize) -> Vec<FoundString> {+ let mut out = Vec::new();+ // Even offsets only — UTF-16LE in PE images is 2-aligned; odd starts false-positive+ // on ASCII data (high bytes of 0).+ let mut i = 0usize;+ while i + 1 < bytes.len() {+ let start = i;+ let mut chars = Vec::new();+ let mut j = i;+ let mut nul_terminated = false;+ while j + 1 < bytes.len() {+ let cu = u16::from_le_bytes([bytes[j], bytes[j + 1]]);+ if cu == 0 {+ nul_terminated = true;+ break;+ }+ if !is_utf16_printable(cu) {+ chars.clear();+ break;+ }+ // Prefer mostly-ASCII / Latin wide strings for RE triage; reject CJK-heavy+ // noise from misaligned ASCII reinterpretation (high byte often non-zero).+ if bytes[j + 1] != 0 && cu > 0x00ff {+ // Allow a small fraction of non-Latin later via ratio check.+ }+ if let Some(c) = char::from_u32(cu as u32) {+ chars.push(c);+ } else {+ chars.clear();+ break;+ }+ j += 2;+ }+ if nul_terminated && chars.len() >= min_len {+ let value: String = chars.iter().collect();+ let asciiish = value.chars().filter(|c| c.is_ascii()).count();+ let ratio = asciiish as f64 / value.len() as f64;+ if value.chars().any(|c| c.is_ascii_alphabetic()) && ratio >= 0.85 {+ out.push(FoundString::utf16le(base_va + start as u64, value, chars.len()));+ }+ i = j + 2;+ continue;+ }+ i += 2;+ }+ out+}++fn is_utf16_printable(cu: u16) -> bool {+ // Typical Windows wide C-string: ASCII BMP + tab/newline.+ if cu < 0x20 {+ return matches!(cu, 0x09 | 0x0a | 0x0d);+ }+ if cu == 0x7f {+ return false;+ }+ cu <= 0x00ff+}++/// Combined ASCII + UTF-16LE scan with optional case-insensitive substring /+/// simple glob filter (`*` / `?` only; no regex crate).+pub fn collect_strings(+ prog: &Program,+ encoding: &str,+ min_len: usize,+ filter: Option<&str>,+) -> Result<Vec<FoundString>> {+ let enc = encoding.to_ascii_lowercase();+ let mut out = Vec::new();+ if enc == "ascii" || enc == "all" {+ out.extend(scan_ascii_strings(prog, min_len));+ }+ if enc == "utf16" || enc == "utf16le" || enc == "all" {+ out.extend(scan_utf16le_strings(prog, min_len));+ }+ if enc != "ascii" && enc != "utf16" && enc != "utf16le" && enc != "all" {+ return Err(crate::error::Error::Parse(format!(+ "unknown encoding '{encoding}' (use ascii|utf16|all)"+ )));+ }+ out.sort_by_key(|s| s.va);+ out.dedup_by(|a, b| a.va == b.va && a.encoding == b.encoding);++ if let Some(pat) = filter {+ out.retain(|s| filter_match(pat, &s.value));+ }+ Ok(out)+}++fn filter_match(pat: &str, value: &str) -> bool {+ let pat_l = pat.to_ascii_lowercase();+ let val_l = value.to_ascii_lowercase();+ if pat_l.contains('*') || pat_l.contains('?') {+ glob_match(&pat_l, &val_l)+ } else {+ val_l.contains(&pat_l)+ }+}++fn glob_match(pat: &str, value: &str) -> bool {+ fn rec(p: &[u8], v: &[u8]) -> bool {+ match (p.first(), v.first()) {+ (None, None) => true,+ (Some(b'*'), _) => {+ if rec(&p[1..], v) {+ return true;+ }+ if v.is_empty() {+ return false;+ }+ rec(p, &v[1..])+ }+ (Some(b'?'), Some(_)) => rec(&p[1..], &v[1..]),+ (Some(a), Some(b)) if a == b => rec(&p[1..], &v[1..]),+ _ => false,+ }+ }+ rec(pat.as_bytes(), value.as_bytes())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::program::{MemoryBlock, Program};++ #[test]+ fn utf16le_finds_wide_path() {+ let mut prog = Program::new("t".into(), "PE32+");+ let mut bytes = Vec::new();+ for c in "UserConfigSelections".encode_utf16() {+ bytes.extend_from_slice(&c.to_le_bytes());+ }+ bytes.extend_from_slice(&[0, 0]);+ prog.blocks.push(MemoryBlock {+ name: ".rdata".into(),+ va: 0x140002000,+ size: bytes.len() as u64,+ bytes,+ readable: true,+ writable: false,+ executable: false,+ });+ let hits = scan_utf16le_strings(&prog, 4);+ assert!(+ hits.iter().any(|s| s.value.contains("UserConfigSelections")),+ "{hits:?}"+ );+ assert!(hits.iter().all(|s| s.encoding == "utf16le"));+ }+}diff --git a/crates/ghidrust-core/src/bulk_scan.rs b/crates/ghidrust-core/src/bulk_scan.rsindex aeb1a7f..a798f52 100644--- a/crates/ghidrust-core/src/bulk_scan.rs+++ b/crates/ghidrust-core/src/bulk_scan.rs@@ -693,11 +693,11 @@ pub fn scan_ascii_strings_bulk(let value =String::from_utf8_lossy(&block.bytes[h.offset..h.offset + h.length]).into_owned();if value.chars().any(|c| c.is_ascii_alphabetic()) {- out.push(FoundString {- va: block.va + h.offset as u64,+ out.push(FoundString::ascii(+ block.va + h.offset as u64,value,- length: h.length,- });+ h.length,+ ));}}}diff --git a/crates/ghidrust-core/src/disasm.rs b/crates/ghidrust-core/src/disasm.rsindex 7a9a0b3..fa92766 100644--- a/crates/ghidrust-core/src/disasm.rs+++ b/crates/ghidrust-core/src/disasm.rs@@ -15,16 +15,42 @@ pub fn disassemble_at(prog: &Program, va: u64) -> Result<Instruction> {}pub fn disassemble_range(prog: &Program, start: u64, max_insns: usize) -> Result<Vec<Instruction>> {+ disassemble_range_opts(prog, start, max_insns, false)+}++/// Disassemble up to `max_insns` instructions from `start`.+///+/// When `skip_bad` is true, undecodable bytes advance by one and continue+/// (listing continuity across sparse decode holes).+pub fn disassemble_range_opts(+ prog: &Program,+ start: u64,+ max_insns: usize,+ skip_bad: bool,+) -> Result<Vec<Instruction>> {let mut out = Vec::new();let mut va = start;- for _ in 0..max_insns {+ let mut steps = 0usize;+ let max_steps = if skip_bad {+ max_insns.saturating_mul(8).max(max_insns)+ } else {+ max_insns+ };+ while out.len() < max_insns && steps < max_steps {+ steps += 1;match disassemble_at(prog, va) {Ok(insn) => {- let len = insn.length as u64;- out.push(insn);+ let len = insn.length.max(1) as u64;va = va.wrapping_add(len);+ out.push(insn);+ }+ Err(_) => {+ if skip_bad {+ va = va.wrapping_add(1);+ continue;+ }+ break;}- Err(_) => break,}}if out.is_empty() {@@ -36,6 +62,7 @@ pub fn disassemble_range(prog: &Program, start: u64, max_insns: usize) -> Result#[cfg(test)]mod tests {use super::*;+ use crate::program::{MemoryBlock, Program};#[test]fn decode_push_rbp_mov_rbp_rsp() {@@ -58,4 +85,23 @@ mod tests {let i1 = decode_one(&b[2..], 2).unwrap();assert_eq!(i1.mnemonic, "ret");}++ #[test]+ fn skip_bad_continues_after_hole() {+ let mut prog = Program::new("t".into(), "PE32+");+ // 0x06 is invalid in long mode; then xor eax,eax; ret+ let bytes = vec![0x06, 0x31, 0xc0, 0xc3];+ prog.blocks.push(MemoryBlock {+ name: ".text".into(),+ va: 0x1000,+ size: bytes.len() as u64,+ bytes,+ readable: true,+ writable: false,+ executable: true,+ });+ let listing = disassemble_range_opts(&prog, 0x1000, 8, true).unwrap();+ assert!(listing.iter().any(|i| i.mnemonic == "xor"), "{listing:?}");+ assert!(listing.iter().any(|i| i.mnemonic == "ret"));+ }}diff --git a/crates/ghidrust-core/src/gpu_analyzers/mod.rs b/crates/ghidrust-core/src/gpu_analyzers/mod.rsindex 15815c9..90bf27c 100644--- a/crates/ghidrust-core/src/gpu_analyzers/mod.rs+++ b/crates/ghidrust-core/src/gpu_analyzers/mod.rs@@ -201,7 +201,7 @@ pub fn bench_analyzer(prog: &Program, name: &str, large_min: Option<usize>) -> A}}-/// Bench all 20 analyzers (+ optional large pad).+/// Bench all registered analyzers (+ optional large pad).pub fn bench_all_analyzers(prog: &Program, large_min: Option<usize>) -> Vec<AnalyzerBenchRow> {ANALYZER_NAMES.iter()@@ -270,7 +270,7 @@ mod tests {#[test]fn matrix_covers_all_twenty_analyzers() {let m = strategy_matrix();- assert_eq!(m.len(), 20);+ assert_eq!(m.len(), ANALYZER_NAMES.len());for &name in ANALYZER_NAMES {assert!(m.iter().any(|(n, _)| *n == name),diff --git a/crates/ghidrust-core/src/gpu_analyzers/strategies.rs b/crates/ghidrust-core/src/gpu_analyzers/strategies.rsindex 7baad11..b6a55b2 100644--- a/crates/ghidrust-core/src/gpu_analyzers/strategies.rs+++ b/crates/ghidrust-core/src/gpu_analyzers/strategies.rs@@ -53,6 +53,7 @@ impl GpuStrategyClass {pub fn gpu_strategy_for(name: &str) -> GpuStrategyClass {match name {"ASCII Strings" => GpuStrategyClass::PrintableRun,+ "Unicode Strings" => GpuStrategyClass::CstrMulti,"Aggressive Instruction Finder" => GpuStrategyClass::CodeDensity,"Call Convention ID" => GpuStrategyClass::PrologueAbi,"Call-Fixup Installer" => GpuStrategyClass::CstrMulti,@@ -106,6 +107,7 @@ pub struct GpuAnalyzerRun {fn needles_for(name: &str) -> Vec<&'static [u8]> {match name {+ "Unicode Strings" => Vec::new(), // host UTF-16LE scan is authoritative"Call-Fixup Installer" => vec![b"__security_check_cookie", b"security_cookie"],"Demangler Microsoft" => vec![b".?AV", b".?AU", b"??_"],"Non-Returning Functions - Discovered" => {@@ -499,10 +501,14 @@ pub fn run_gpu_for_analyzer(if strategy == GpuStrategyClass::CstrMulti {let mut all_hits = Vec::new();let mut timing = GpuPhaseTiming::default();- let mut backend = String::new();+ let mut backend = String::from("cpu_empty_needles");let mut device = String::new();let mut note = String::from("multi-needle: ");- for n in needles_for(name) {+ let needles = needles_for(name);+ if needles.is_empty() {+ note.push_str("(none)");+ }+ for n in needles {let r = run_kernel(&hay, KernelKind::Cstr, Some(n), image_base, image_end);all_hits.extend(r.hits.iter().copied());timing.pcie_upload_ms += r.timing.pcie_upload_ms;diff --git a/crates/ghidrust-core/src/imports.rs b/crates/ghidrust-core/src/imports.rsnew file mode 100644index 0000000..0ffc285--- /dev/null+++ b/crates/ghidrust-core/src/imports.rs@@ -0,0 +1,213 @@+//! PE import directory → named IAT slots.++use crate::error::{Error, Result};+use crate::program::{ImportEntry, Program};++/// Parse PE import descriptors into [`Program::imports`] (no-op for non-PE).+pub fn load_imports(prog: &mut Program) -> Result<()> {+ if !prog.format.to_ascii_lowercase().starts_with("pe") {+ prog.imports.clear();+ return Ok(());+ }+ let data = prog.file_bytes.clone();+ prog.imports = parse_pe_imports(&data, prog.image_base)?;+ Ok(())+}++pub fn parse_pe_imports(data: &[u8], image_base: u64) -> Result<Vec<ImportEntry>> {+ if data.len() < 0x40 || &data[0..2] != b"MZ" {+ return Ok(Vec::new());+ }+ let e_lfanew = u32::from_le_bytes(data[0x3C..0x40].try_into().unwrap()) as usize;+ if e_lfanew + 24 > data.len() || &data[e_lfanew..e_lfanew + 4] != b"PE\0\0" {+ return Ok(Vec::new());+ }+ let opt = e_lfanew + 24;+ let magic = rdu16(data, opt)?;+ let (is_pe32plus, data_dir) = match magic {+ 0x10b => (false, opt + 96),+ 0x20b => (true, opt + 112),+ _ => return Ok(Vec::new()),+ };+ if data_dir + 16 > data.len() {+ return Ok(Vec::new());+ }+ let import_rva = rdu32(data, data_dir + 8)? as u64;+ let import_size = rdu32(data, data_dir + 12)? as u64;+ if import_rva == 0 || import_size == 0 {+ return Ok(Vec::new());+ }++ let mut out = Vec::new();+ let mut desc_off = match rva_to_file(data, import_rva) {+ Some(o) => o,+ None => return Ok(Vec::new()),+ };+ loop {+ if desc_off + 20 > data.len() {+ break;+ }+ let oft = rdu32(data, desc_off)? as u64;+ let name_rva = rdu32(data, desc_off + 12)? as u64;+ let ft = rdu32(data, desc_off + 16)? as u64;+ if oft == 0 && name_rva == 0 && ft == 0 {+ break;+ }+ let dll = read_cstr_rva(data, name_rva).unwrap_or_else(|| "unknown.dll".into());+ let thunk_rva = if oft != 0 { oft } else { ft };+ let mut thunk_file = match rva_to_file(data, thunk_rva) {+ Some(o) => o,+ None => {+ desc_off += 20;+ continue;+ }+ };+ let entry_size = if is_pe32plus { 8usize } else { 4usize };+ let mut idx = 0u64;+ loop {+ if thunk_file + entry_size > data.len() {+ break;+ }+ let raw = if is_pe32plus {+ rdu64(data, thunk_file)?+ } else {+ rdu32(data, thunk_file)? as u64+ };+ if raw == 0 {+ break;+ }+ let ordinal_flag = if is_pe32plus {+ 1u64 << 63+ } else {+ 1u64 << 31+ };+ let (name, ordinal) = if raw & ordinal_flag != 0 {+ (None, Some((raw & 0xffff) as u16))+ } else {+ let hint_rva = raw & 0xffff_ffff;+ let n = read_import_name(data, hint_rva);+ (n, None)+ };+ let slot = idx * entry_size as u64;+ out.push(ImportEntry {+ dll: dll.clone(),+ name,+ ordinal,+ iat_va: image_base.wrapping_add(ft + slot),+ ilt_va: Some(image_base.wrapping_add(thunk_rva + slot)),+ });+ thunk_file += entry_size;+ idx += 1;+ }+ desc_off += 20;+ }+ Ok(out)+}++/// Filter imports by optional DLL / symbol name (case-insensitive substring).+pub fn filter_imports<'a>(+ imports: &'a [ImportEntry],+ dll: Option<&str>,+ name: Option<&str>,+) -> Vec<&'a ImportEntry> {+ imports+ .iter()+ .filter(|e| {+ if let Some(d) = dll {+ if !e.dll.to_ascii_lowercase().contains(&d.to_ascii_lowercase()) {+ return false;+ }+ }+ if let Some(n) = name {+ let nl = n.to_ascii_lowercase();+ let hit = e+ .name+ .as_ref()+ .map(|s| s.to_ascii_lowercase().contains(&nl))+ .unwrap_or(false)+ || e.ordinal+ .map(|o| format!("ord_{o}").contains(&nl) || o.to_string() == n)+ .unwrap_or(false);+ if !hit {+ return false;+ }+ }+ true+ })+ .collect()+}++fn read_import_name(data: &[u8], hint_rva: u64) -> Option<String> {+ let off = rva_to_file(data, hint_rva)? + 2; // skip Hint+ read_cstr_at(data, off)+}++fn read_cstr_rva(data: &[u8], rva: u64) -> Option<String> {+ let off = rva_to_file(data, rva)?;+ read_cstr_at(data, off)+}++fn read_cstr_at(data: &[u8], off: usize) -> Option<String> {+ if off >= data.len() {+ return None;+ }+ let end = data[off..]+ .iter()+ .position(|&b| b == 0)+ .map(|p| off + p)+ .unwrap_or(data.len());+ if end == off {+ return None;+ }+ Some(String::from_utf8_lossy(&data[off..end]).into_owned())+}++fn rva_to_file(data: &[u8], rva: u64) -> Option<usize> {+ if data.len() < 0x40 {+ return None;+ }+ let e_lfanew = u32::from_le_bytes(data[0x3C..0x40].try_into().ok()?) as usize;+ let coff = e_lfanew + 4;+ let num_sections = rdu16(data, coff + 2).ok()? as usize;+ let opt_size = rdu16(data, coff + 16).ok()? as usize;+ let sec_table = coff + 20 + opt_size;+ for i in 0..num_sections {+ let off = sec_table + i * 40;+ if off + 40 > data.len() {+ break;+ }+ let virt_size = rdu32(data, off + 8).ok()? as u64;+ let va_rva = rdu32(data, off + 12).ok()? as u64;+ let raw_size = rdu32(data, off + 16).ok()? as u64;+ let file_off = rdu32(data, off + 20).ok()? as u64;+ let span = virt_size.max(raw_size);+ if rva >= va_rva && rva < va_rva + span {+ let delta = rva - va_rva;+ if delta < raw_size {+ return Some((file_off + delta) as usize);+ }+ }+ }+ None+}++fn rdu16(data: &[u8], off: usize) -> Result<u16> {+ if off + 2 > data.len() {+ return Err(Error::Parse("pe trunc u16".into()));+ }+ Ok(u16::from_le_bytes(data[off..off + 2].try_into().unwrap()))+}++fn rdu32(data: &[u8], off: usize) -> Result<u32> {+ if off + 4 > data.len() {+ return Err(Error::Parse("pe trunc u32".into()));+ }+ Ok(u32::from_le_bytes(data[off..off + 4].try_into().unwrap()))+}++fn rdu64(data: &[u8], off: usize) -> Result<u64> {+ if off + 8 > data.len() {+ return Err(Error::Parse("pe trunc u64".into()));+ }+ Ok(u64::from_le_bytes(data[off..off + 8].try_into().unwrap()))+}diff --git a/crates/ghidrust-core/src/lib.rs b/crates/ghidrust-core/src/lib.rsindex 4ad5005..e0ecaa0 100644--- a/crates/ghidrust-core/src/lib.rs+++ b/crates/ghidrust-core/src/lib.rs@@ -7,6 +7,7 @@ pub mod gpu_analyzers;pub mod disasm;pub mod elf;pub mod error;+pub mod imports;pub mod pe;pub mod program;pub mod project;@@ -15,8 +16,9 @@ pub mod theme;pub mod xrefs;pub use analyzers::{- analyzer_catalog, run_analyzers, run_analyzers_opts, scan_ascii_strings, AnalysisRunReport,- AnalyzerInfo, AnalyzerOutput, AnalyzerStatus, FoundString, ANALYZER_NAMES,+ analyzer_catalog, collect_strings, run_analyzers, run_analyzers_opts, scan_ascii_strings,+ scan_utf16le_strings, AnalysisRunReport, AnalyzerInfo, AnalyzerOutput, AnalyzerStatus,+ FoundString, ANALYZER_NAMES,};pub use bulk_scan::{plan_dispatch_workgroup_chunks, preferred_bulk_mode, scan_ascii_strings_bulk,@@ -31,7 +33,10 @@ pub use gpu_analyzers::{merge_seeds_into_program, pad_large, seeds_equal, strategy_matrix, AnalyzerBenchRow,GpuStrategyClass,};-pub use disasm::{decode_one, disassemble_at, disassemble_range, Instruction};+pub use disasm::{+ decode_one, disassemble_at, disassemble_range, disassemble_range_opts, Instruction,+};+pub use imports::{filter_imports, load_imports, parse_pe_imports};pub use edits::{CommentKind, EquateEdit, FunctionSignatureEdit, ProgramEditTotals, ProgramEdits, RetypeEdit,BUILTIN_TYPES,@@ -39,8 +44,8 @@ pub use edits::{pub use error::{Error, Result};pub use program::{AddressTableInfo, AnalysisState, CallFixupInfo, DiscoveredRange, FidMatch, FunctionInfo,- MediaHit, MemoryBlock, Program, ReferenceInfo, ResourceInfo, SectionInfo, SwitchInfo,- SymbolInfo,+ ImportEntry, MediaHit, MemoryBlock, Program, ReferenceInfo, ResourceInfo, SectionInfo,+ SwitchInfo, SymbolInfo,};pub use project::{AnalysisSummary, Project, ProjectFileEntry, ProjectMeta, ProjectTreeModel, ProjectTreeRow,@@ -48,7 +53,10 @@ pub use project::{};pub use rtti::{recover_rtti, RttiClass, RttiReport};pub use theme::{m3_tokens, ThemeMode, M3Tokens};-pub use xrefs::{operand_addresses, xrefs_from, xrefs_to, XRef};+pub use xrefs::{+ instruction_targets, operand_addresses, rip_relative_targets, xrefs_from, xrefs_to,+ xrefs_to_import, xrefs_to_string_filter, XRef,+};use std::path::{Path, PathBuf};diff --git a/crates/ghidrust-core/src/pe.rs b/crates/ghidrust-core/src/pe.rsindex db02057..e49ab38 100644--- a/crates/ghidrust-core/src/pe.rs+++ b/crates/ghidrust-core/src/pe.rs@@ -113,6 +113,11 @@ pub fn load_pe(data: &[u8], name: impl Into<String>) -> Result<Program> {});}+ // Best-effort import directory (empty on parse failure — never fabricate).+ if let Ok(imports) = crate::imports::parse_pe_imports(data, image_base) {+ prog.imports = imports;+ }+Ok(prog)}diff --git a/crates/ghidrust-core/src/program.rs b/crates/ghidrust-core/src/program.rsindex 9e32fab..56f4045 100644--- a/crates/ghidrust-core/src/program.rs+++ b/crates/ghidrust-core/src/program.rs@@ -39,6 +39,18 @@ pub struct FunctionInfo {pub stack_locals: Vec<String>,}+/// One PE import / IAT slot (ELF imports may be added later).+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+pub struct ImportEntry {+ pub dll: String,+ pub name: Option<String>,+ pub ordinal: Option<u16>,+ /// VA of the IAT slot (pointer that calls resolve through).+ pub iat_va: u64,+ /// VA of the matching ILT slot when present.+ pub ilt_va: Option<u64>,+}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]pub struct SymbolInfo {pub va: u64,@@ -130,6 +142,9 @@ pub struct Program {pub file_bytes: Vec<u8>,pub rtti: RttiReport,pub analysis: AnalysisState,+ /// PE import directory entries (IAT VAs + names). Empty for ELF until wired.+ #[serde(default)]+ pub imports: Vec<ImportEntry>,/// User-facing edits (renames, comments, retypes, function signatures, user types)./// Stored side-car so analyzer output remains "honest / never fabricated".#[serde(default)]@@ -148,6 +163,7 @@ impl Program {file_bytes: Vec::new(),rtti: RttiReport::default(),analysis: AnalysisState::default(),+ imports: Vec::new(),edits: ProgramEdits::default(),}}@@ -202,4 +218,14 @@ impl Program {pub fn function_at_mut(&mut self, entry: u64) -> Option<&mut FunctionInfo> {self.analysis.functions.iter_mut().find(|f| f.entry == entry)}++ /// Tightest analyzed function whose `[entry, end)` contains `va`.+ /// Prefers the greatest `entry` ≤ `va` among covering intervals.+ pub fn function_containing(&self, va: u64) -> Option<&FunctionInfo> {+ self.analysis+ .functions+ .iter()+ .filter(|f| va >= f.entry && va < f.end.max(f.entry.saturating_add(1)))+ .max_by_key(|f| f.entry)+ }}diff --git a/crates/ghidrust-core/src/xrefs.rs b/crates/ghidrust-core/src/xrefs.rsindex 5da47a4..171e905 100644--- a/crates/ghidrust-core/src/xrefs.rs+++ b/crates/ghidrust-core/src/xrefs.rs@@ -1,42 +1,33 @@//! Program cross-references (Ghidra `Symbol References` provider).//!-//! Ghidrust does not (yet) run a full flow analyzer that populates every-//! `to`/`from` reference the way Ghidra does. This module rebuilds an-//! approximate xref graph on demand from three honest sources:-//!-//! 1. `Program::analysis.references` — real refs deposited by the address-table-//! and resource analyzers.-//! 2. `Program::analysis.address_tables` — pointer tables where every entry is-//! a load-time reference.-//! 3. Decoded x86-64 instructions in a supplied listing — any operand hex-//! literal that lands inside a mapped memory block is treated as a-//! reference of kind `data`/`code`/`call`/`jmp` inferred from the mnemonic.-//!-//! No refs are ever fabricated: if the source disagrees, the source wins.+//! Sources:+//! 1. `Program::analysis.references` — analyzer-deposited refs+//! 2. `Program::analysis.address_tables` — pointer tables+//! 3. Decoded instructions — absolute operand hex + RIP-relative targets+//! 4. Import / IAT slots — `call/jmp [rip+disp]` landing on IAT VAs-use crate::disasm::disassemble_range;-use crate::program::Program;+use crate::disasm::{decode_one, disassemble_range};+use crate::program::{ImportEntry, Program};+use serde::Serialize;/// One cross-reference row rendered by the GUI's Symbol References pane.-#[derive(Debug, Clone, PartialEq, Eq)]+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct XRef {/// Source VA (where the reference originates).pub from: u64,/// Target VA (where the reference points at).pub to: u64,/// Ghidra-analog kind (`call`, `jmp`, `cond_jmp`, `data`, `ptr_table`,- /// `resource`, `xref`).+ /// `resource`, `xref`, `iat`).pub kind: &'static str,/// Ghidra "From Preview" — mnemonic/operand text where computable.pub preview: String,}-/// Compute references **to** `target` from three honest sources.+/// Compute references **to** `target`.///-/// `hint_listing` is an optional pre-computed instruction slice used to-/// enrich results with mnemonic-derived kinds; when `None`, only analyzer-/// output is consulted. The caller is expected to pass a listing that spans-/// the executable blocks of interest (typically the whole loaded window).+/// When `hint_listing` is `None`, executable blocks are scanned for RIP-relative+/// and absolute operand refs (honest decode; no fabricated edges).pub fn xrefs_to(prog: &Program,target: u64,@@ -70,33 +61,23 @@ pub fn xrefs_to(}if let Some(listing) = hint_listing {- for insn in listing {- if operand_addresses(&insn.operands).contains(&target) {- out.push(XRef {- from: insn.address,- to: target,- kind: mnemonic_kind(&insn.mnemonic),- preview: format!("{} {}", insn.mnemonic, insn.operands),- });- }- }+ push_listing_xrefs_to(listing, target, &mut out);+ } else {+ scan_exec_xrefs_to(prog, target, &mut out);}- out.sort_by_key(|r| (r.from, r.kind));- out.dedup_by(|a, b| a.from == b.from && a.to == b.to && a.kind == b.kind);+ finalize(&mut out);out}-/// Compute references **from** `source` (typically a function entry) by-/// disassembling `max_insns` instructions from that VA and collecting every-/// operand hex address that lands inside a mapped memory block.+/// Compute references **from** `source` (disassemble up to `max_insns`).pub fn xrefs_from(prog: &Program, source: u64, max_insns: usize) -> Vec<XRef> {let mut out = Vec::new();let Ok(listing) = disassemble_range(prog, source, max_insns) else {return out;};for insn in &listing {- for tgt in operand_addresses(&insn.operands) {+ for tgt in instruction_targets(insn) {if prog.contains_va(tgt) {out.push(XRef {from: insn.address,@@ -107,16 +88,69 @@ pub fn xrefs_from(prog: &Program, source: u64, max_insns: usize) -> Vec<XRef> {}}}- out.sort_by_key(|r| (r.from, r.to));- out.dedup_by(|a, b| a.from == b.from && a.to == b.to && a.kind == b.kind);+ finalize(&mut out);+ out+}++/// Xrefs to every IAT slot matching an import name (substring, case-insensitive).+pub fn xrefs_to_import(prog: &Program, import_name: &str) -> Vec<XRef> {+ let needle = import_name.to_ascii_lowercase();+ let slots: Vec<&ImportEntry> = prog+ .imports+ .iter()+ .filter(|e| {+ e.name+ .as_ref()+ .map(|n| n.to_ascii_lowercase().contains(&needle))+ .unwrap_or(false)+ })+ .collect();+ let mut out = Vec::new();+ for slot in slots {+ let mut refs = xrefs_to(prog, slot.iat_va, None);+ for r in &mut refs {+ if r.kind == "call" || r.kind == "jmp" || r.kind == "data" {+ r.kind = "iat";+ }+ let label = slot+ .name+ .clone()+ .unwrap_or_else(|| format!("ord_{}", slot.ordinal.unwrap_or(0)));+ r.preview = format!("{} ; {}!{}", r.preview, slot.dll, label);+ }+ out.extend(refs);+ }+ finalize(&mut out);+ out+}++/// Resolve string VA(s) by filter, then gather xrefs to each.+pub fn xrefs_to_string_filter(prog: &Program, filter: &str) -> Vec<XRef> {+ let Ok(strings) = crate::analyzers::collect_strings(prog, "all", 4, Some(filter)) else {+ return Vec::new();+ };+ let mut out = Vec::new();+ for s in strings {+ let mut refs = xrefs_to(prog, s.va, None);+ for r in &mut refs {+ r.preview = format!("{} ; \"{}\"", r.preview, truncate(&s.value, 48));+ }+ out.extend(refs);+ }+ finalize(&mut out);+ out+}++/// Absolute hex literals in operands plus RIP-relative effective addresses.+pub fn instruction_targets(insn: &crate::disasm::Instruction) -> Vec<u64> {+ let mut out = operand_addresses(&insn.operands);+ out.extend(rip_relative_targets(insn));+ out.sort_unstable();+ out.dedup();out}/// Every hex-literal address that appears in `operands`.-///-/// Recognises `0x1234`, `0x1234abcd`, and anywhere they appear inside memory-/// operands like `qword ptr [0x140001234]`. Decimal-only literals are not-/// treated as addresses — Ghidra behaves the same way.pub fn operand_addresses(operands: &str) -> Vec<u64> {let mut out = Vec::new();let bytes = operands.as_bytes();@@ -141,14 +175,143 @@ pub fn operand_addresses(operands: &str) -> Vec<u64> {out}+/// Parse `[rip+disp]` / `[rip-disp]` / `[rip+-disp]` forms → absolute VA.+pub fn rip_relative_targets(insn: &crate::disasm::Instruction) -> Vec<u64> {+ let mut out = Vec::new();+ let ops = &insn.operands;+ let bytes = ops.as_bytes();+ let mut i = 0;+ while i + 5 < bytes.len() {+ // look for "[rip"+ if bytes[i] == b'['+ && i + 4 < bytes.len()+ && &ops[i..i + 4] == "[rip"+ {+ let after = i + 4;+ let rest = &ops[after..];+ if let Some((disp, consumed)) = parse_rip_disp(rest) {+ let next_ip = insn.address.wrapping_add(insn.length as u64);+ out.push(next_ip.wrapping_add(disp as u64));+ i = after + consumed;+ continue;+ }+ }+ i += 1;+ }+ out+}++fn parse_rip_disp(rest: &str) -> Option<(i64, usize)> {+ let b = rest.as_bytes();+ if b.is_empty() {+ return None;+ }+ let mut idx = 0;+ let mut sign: i64 = 1;+ // +disp, -disp, +-disp (decoder quirk), or bare ]+ if b[idx] == b'+' {+ idx += 1;+ if idx < b.len() && b[idx] == b'-' {+ sign = -1;+ idx += 1;+ }+ } else if b[idx] == b'-' {+ sign = -1;+ idx += 1;+ } else if b[idx] == b']' {+ return Some((0, 1));+ } else {+ return None;+ }+ if idx + 2 < b.len() && b[idx] == b'0' && (b[idx + 1] == b'x' || b[idx + 1] == b'X') {+ idx += 2;+ let start = idx;+ while idx < b.len() && (b[idx] as char).is_ascii_hexdigit() {+ idx += 1;+ }+ let mag = u64::from_str_radix(&rest[start..idx], 16).ok()? as i64;+ if idx < b.len() && b[idx] == b']' {+ idx += 1;+ }+ return Some((sign * mag, idx));+ }+ // decimal+ let start = idx;+ while idx < b.len() && b[idx].is_ascii_digit() {+ idx += 1;+ }+ if start == idx {+ return None;+ }+ let mag: i64 = rest[start..idx].parse().ok()?;+ if idx < b.len() && b[idx] == b']' {+ idx += 1;+ }+ Some((sign * mag, idx))+}++fn scan_exec_xrefs_to(prog: &Program, target: u64, out: &mut Vec<XRef>) {+ for block in prog.exec_blocks() {+ let mut off = 0usize;+ while off < block.bytes.len() {+ let va = block.va + off as u64;+ let slice = &block.bytes[off..];+ match decode_one(slice, va) {+ Ok(insn) => {+ if instruction_targets(&insn).contains(&target) {+ out.push(XRef {+ from: insn.address,+ to: target,+ kind: mnemonic_kind(&insn.mnemonic),+ preview: format!("{} {}", insn.mnemonic, insn.operands),+ });+ }+ off += insn.length.max(1) as usize;+ }+ Err(_) => off += 1,+ }+ }+ }+}++fn push_listing_xrefs_to(+ listing: &[crate::disasm::Instruction],+ target: u64,+ out: &mut Vec<XRef>,+) {+ for insn in listing {+ if instruction_targets(insn).contains(&target) {+ out.push(XRef {+ from: insn.address,+ to: target,+ kind: mnemonic_kind(&insn.mnemonic),+ preview: format!("{} {}", insn.mnemonic, insn.operands),+ });+ }+ }+}++fn finalize(out: &mut Vec<XRef>) {+ out.sort_by_key(|r| (r.from, r.to, r.kind));+ out.dedup_by(|a, b| a.from == b.from && a.to == b.to && a.kind == b.kind);+}++fn truncate(s: &str, n: usize) -> String {+ if s.len() <= n {+ s.to_string()+ } else {+ format!("{}…", &s[..n])+ }+}+fn mnemonic_kind(mnem: &str) -> &'static str {match mnem {"call" | "callq" => "call","jmp" | "jmpq" => "jmp",- // x86 conditional jumps."je" | "jne" | "jz" | "jnz" | "jl" | "jle" | "jg" | "jge" | "ja" | "jae" | "jb" | "jbe"| "jo" | "jno" | "js" | "jns" | "jp" | "jnp" | "jcxz" | "jecxz" | "jrcxz" | "loop"| "loope" | "loopne" => "cond_jmp",+ "lea" => "data",_ => "data",}}@@ -161,6 +324,7 @@ fn static_kind(raw: &str) -> &'static str {"jmp" => "jmp","cond_jmp" => "cond_jmp","data" => "data",+ "iat" => "iat",_ => "xref",}}@@ -168,7 +332,9 @@ fn static_kind(raw: &str) -> &'static str {#[cfg(test)]mod tests {use super::*;- use crate::{fixture_path, load_path, program::ReferenceInfo};+ use crate::program::{MemoryBlock, Program, ReferenceInfo};+ use crate::{fixture_path, load_path};+ use ghidrust_decode::decode_one;#[test]fn operand_addresses_picks_hex_literals() {@@ -178,16 +344,24 @@ mod tests {vec![0x140001234]);assert!(operand_addresses("rax, 42").is_empty());- // Multiple literals in one operand string.let v = operand_addresses("mov qword ptr [0x1000], 0xdead");assert_eq!(v, vec![0x1000, 0xdead]);}+ #[test]+ fn rip_relative_lea_resolves() {+ // lea rcx, [rip+0x10] at 0x1000, length 7 → target 0x1017+ let bytes = [0x48, 0x8d, 0x0d, 0x10, 0x00, 0x00, 0x00];+ let insn = decode_one(&bytes, 0x1000).unwrap();+ assert_eq!(insn.mnemonic, "lea");+ let tgts = instruction_targets(&insn);+ assert!(tgts.contains(&0x1017), "targets={tgts:?} ops={}", insn.operands);+ }+#[test]fn xrefs_from_entry_finds_own_addresses() {let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();let entry = prog.entry.unwrap();- // xrefs_from just decodes and never fabricates.let refs = xrefs_from(&prog, entry, 32);for r in &refs {assert!(prog.contains_va(r.to));@@ -198,8 +372,6 @@ mod tests {#[test]fn xrefs_to_returns_analysis_and_ptr_table_refs() {let mut prog = load_path(fixture_path("analysis_lab.pe")).unwrap();- // Fake an address table containing entry so we can verify xrefs_to- // reflects the analyzer-populated pool.let entry = prog.entry.unwrap();prog.analysis.address_tables.push(crate::program::AddressTableInfo {base: prog.image_base,@@ -215,4 +387,41 @@ mod tests {assert!(refs.iter().any(|r| r.kind == "ptr_table"));assert!(refs.iter().any(|r| r.kind == "call"));}++ #[test]+ fn xrefs_to_finds_rip_lea_in_exec_block() {+ let mut prog = Program::new("t".into(), "PE32+");+ let str_va = 0x140002000u64;+ // lea rax, [rip+disp] targeting str_va; place insn at 0x140001000+ let insn_va = 0x140001000u64;+ let next = insn_va + 7;+ let disp = (str_va as i64) - (next as i64);+ let disp_bytes = (disp as i32).to_le_bytes();+ let mut code = vec![0x48, 0x8d, 0x05];+ code.extend_from_slice(&disp_bytes);+ code.push(0xc3); // ret+ prog.blocks.push(MemoryBlock {+ name: ".text".into(),+ va: insn_va,+ size: code.len() as u64,+ bytes: code,+ readable: true,+ writable: false,+ executable: true,+ });+ prog.blocks.push(MemoryBlock {+ name: ".rdata".into(),+ va: str_va,+ size: 8,+ bytes: b"Hello\0\0\0".to_vec(),+ readable: true,+ writable: false,+ executable: false,+ });+ let refs = xrefs_to(&prog, str_va, None);+ assert!(+ refs.iter().any(|r| r.from == insn_va && r.to == str_va),+ "{refs:?}"+ );+ }}diff --git a/crates/ghidrust-decode/src/x86_64.rs b/crates/ghidrust-decode/src/x86_64.rsindex 5075893..9b3d756 100644--- a/crates/ghidrust-decode/src/x86_64.rs+++ b/crates/ghidrust-decode/src/x86_64.rs@@ -235,7 +235,11 @@ fn decode_modrm_mem(} else if mod_ == 0 && rm_enc == 5 {// RIP-relativelet disp = cur.take_imm(4)? as i32 as i64;- parts = format!("[rip+{}]", sign_hex(disp));+ parts = if disp < 0 {+ format!("[rip{}]", sign_hex(disp))+ } else {+ format!("[rip+{}]", sign_hex(disp))+ };} else {let base = REGS64[rm as usize];match mod_ {diff --git a/crates/ghidrust-gui/Cargo.toml b/crates/ghidrust-gui/Cargo.tomlindex 34039c8..e6594d9 100644--- a/crates/ghidrust-gui/Cargo.toml+++ b/crates/ghidrust-gui/Cargo.toml@@ -14,6 +14,10 @@ ghidrust-core = { workspace = true, features = ["gpu"] }# CPU Stage-0 (CFG → pseudo-C); do not call GPU decompile APIs from the GUI.ghidrust-decomp = { path = "../ghidrust-decomp" }ghidrust-types = { workspace = true }+# Grok Build agent bridge (Option C — ACP sidecar). Ships default-on; the+# runtime child (`grok`) is user-installed via the pane's one-click Install+# button, so this dep only adds ~120 KB of Rust code, no binary vendoring.+ghidrust-agent = { workspace = true }eframe = { version = "0.31", default-features = true }egui = "0.31"rfd = "0.15"diff --git a/crates/ghidrust-gui/src/agent_pane.rs b/crates/ghidrust-gui/src/agent_pane.rsnew file mode 100644index 0000000..9bbf9d3--- /dev/null+++ b/crates/ghidrust-gui/src/agent_pane.rs@@ -0,0 +1,385 @@+//! Grok Build agent console pane — Option C (ACP sidecar) integration.+//!+//! This module owns:+//!+//! - Per-project [`GrokPaneState`] (transcript, input buffer, mode, session).+//! - Rendering of the bottom-dock tabbed panel (`Grok` primary, `Console`+//! sibling) shared with the plain analyzer console.+//! - Wiring the "Install Grok Build…" one-click flow.+//!+//! It intentionally does **not** own the console log itself — that stays in+//! `GhidrustApp::{console, console_severity}` so nothing about the Grok pane+//! can drop / hide script-and-analyzer log messages.++use eframe::egui::{self, Color32, RichText, Ui};+use ghidrust_agent::{+ grok_binary_path, install_command_for_platform, parse_markdown, write_project_mcp_config,+ write_project_skill, AgentEvent, AgentMode, AgentSession, AgentSessionConfig, AgentTransport,+ MarkdownBlock, ProgramFacts, SystemPromptBuilder,+};+use std::path::{Path, PathBuf};++/// Which tab of the bottom dock is currently active.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum BottomTab {+ /// The Grok Build agent console (default primary tab per user spec).+ Grok,+ /// The plain analyzer / script Console (existing behavior).+ Console,+}++impl Default for BottomTab {+ fn default() -> Self {+ BottomTab::Grok+ }+}++/// One transcript entry the pane renders.+#[derive(Debug, Clone)]+pub enum TranscriptEntry {+ User { text: String },+ Assistant { markdown: String },+ ToolCall { id: String, name: String, args_json: String, done: Option<ToolResult> },+ Info { text: String },+ Approval { id: String, tool: String, preview: String, resolved: Option<bool> },+ Error { text: String },+}++#[derive(Debug, Clone)]+pub struct ToolResult {+ pub ok: bool,+ pub summary: String,+}++/// Per-project pane state (one instance per Ghidrust window because we ship+/// one project per window).+pub struct GrokPaneState {+ pub tab: BottomTab,+ pub mode: AgentMode,+ pub input: String,+ pub transcript: Vec<TranscriptEntry>,+ /// The live agent session, `None` until the user clicks "Start Session".+ pub session: Option<AgentSession>,+ /// Path to the discovered `grok` binary (None until user installs).+ pub grok_bin: Option<PathBuf>,+ /// Set when a "start session" attempt failed; shown as an error banner.+ pub last_error: Option<String>,+ /// Optional installer subprocess we spawned via "Install Grok Build".+ /// We don't wait on it — user closes their terminal, then clicks+ /// "Re-scan for grok" or "Start Session" to pick it up.+ pub install_status: Option<String>,+ /// The last-seen program facts snapshot that was injected into system prompt.+ pub last_facts_snapshot: Option<String>,+}++impl GrokPaneState {+ pub fn new() -> Self {+ Self {+ tab: BottomTab::Grok,+ mode: AgentMode::default_session(),+ input: String::new(),+ transcript: Vec::new(),+ session: None,+ grok_bin: grok_binary_path(),+ last_error: None,+ install_status: None,+ last_facts_snapshot: None,+ }+ }++ /// Called on app init and again after the "Re-scan for grok" button.+ pub fn refresh_grok_binary(&mut self) {+ self.grok_bin = grok_binary_path();+ }++ /// Fold streamed events into the transcript. Merges consecutive assistant+ /// deltas so streamed text renders as a single growing bubble instead of+ /// one bubble per token.+ pub fn ingest_events(&mut self, events: Vec<AgentEvent>) {+ for ev in events {+ match ev {+ AgentEvent::AssistantDelta { text } => {+ if let Some(TranscriptEntry::Assistant { markdown }) =+ self.transcript.last_mut()+ {+ markdown.push_str(&text);+ } else {+ self.transcript+ .push(TranscriptEntry::Assistant { markdown: text });+ }+ }+ AgentEvent::ToolCallStarted { id, name, args_json } => {+ self.transcript.push(TranscriptEntry::ToolCall {+ id,+ name,+ args_json,+ done: None,+ });+ }+ AgentEvent::ToolCallFinished { id, ok, summary } => {+ for entry in self.transcript.iter_mut().rev() {+ if let TranscriptEntry::ToolCall {+ id: eid,+ done,+ ..+ } = entry+ {+ if *eid == id {+ *done = Some(ToolResult { ok, summary });+ break;+ }+ }+ }+ }+ AgentEvent::ApprovalRequested { id, tool, preview } => {+ self.transcript.push(TranscriptEntry::Approval {+ id,+ tool,+ preview,+ resolved: None,+ });+ }+ AgentEvent::TurnFinished => {+ self.transcript.push(TranscriptEntry::Info {+ text: "— turn complete —".into(),+ });+ }+ AgentEvent::Error { message } => {+ self.transcript+ .push(TranscriptEntry::Error { text: message });+ }+ AgentEvent::ChildExited { code } => {+ self.transcript.push(TranscriptEntry::Info {+ text: format!(+ "Grok session ended (exit={}). Click 'Start Session' to reconnect.",+ code.map(|c| c.to_string()).unwrap_or_else(|| "?".into())+ ),+ });+ self.session = None;+ }+ }+ }+ }++ /// Poll the live session (if any). Safe to call every frame.+ pub fn poll(&mut self) {+ if let Some(sess) = &self.session {+ let evs = sess.poll_events();+ if !evs.is_empty() {+ self.ingest_events(evs);+ }+ }+ }+}++impl Default for GrokPaneState {+ fn default() -> Self {+ Self::new()+ }+}++// ── Session lifecycle helpers ────────────────────────────────────────────────++/// Try to spawn a per-project agent session, wiring up MCP + skill files.+///+/// Returns `Err(msg)` if the binary isn't installed, or the child failed to+/// spawn. The pane is expected to surface this via `last_error`.+pub fn start_session(+ grok_bin: &Path,+ project_root: &Path,+ ghidrust_bin: &Path,+ skill_source: Option<&Path>,+ mode: AgentMode,+ facts: ProgramFacts,+ skill_body_for_prompt: &str,+) -> Result<AgentSession, String> {+ // (1) Write the project-local MCP config so Grok Build can call `ghidrust mcp`.+ let _ = write_project_mcp_config(project_root, ghidrust_bin).map_err(|e| e.to_string())?;+ // (2) Mirror SKILL.md into `<project>/.grok/skills/ghidrust/` — best-effort;+ // if the workspace skill file isn't shipped alongside the binary we just+ // rely on the system_prompt to inline it.+ if let Some(src) = skill_source {+ let _ = write_project_skill(project_root, src);+ }++ let system_prompt = SystemPromptBuilder::new(skill_body_for_prompt)+ .facts(&facts)+ .read_only_note(matches!(mode, AgentMode::ReadOnly))+ .airgap_note(matches!(mode, AgentMode::Airgap))+ .build();++ let cfg = AgentSessionConfig {+ grok_bin: grok_bin.to_path_buf(),+ project_root: project_root.to_path_buf(),+ mode,+ system_prompt,+ transport: AgentTransport::Auto,+ model: None,+ };+ AgentSession::spawn(cfg)+}++// ── Rendering ────────────────────────────────────────────────────────────────++/// Render one entry — split so both the plain and highlighted paths share.+///+/// `pseudo_c_render` is called for `c` / `pseudo-c` fenced blocks so the+/// caller can plug in the existing `decomp_tokens` highlighter without this+/// module having to depend on it. `None` = fall back to plain monospace.+pub fn render_transcript_entry(+ ui: &mut Ui,+ entry: &mut TranscriptEntry,+ pseudo_c_render: &mut dyn FnMut(&mut Ui, &str),+ on_approval: &mut dyn FnMut(&str, bool),+ muted: Color32,+ primary: Color32,+) {+ match entry {+ TranscriptEntry::User { text } => {+ ui.horizontal(|ui| {+ ui.label(RichText::new("you").color(muted).small());+ ui.separator();+ ui.strong(text.as_str());+ });+ }+ TranscriptEntry::Assistant { markdown } => {+ ui.label(RichText::new("grok").color(primary).small());+ render_markdown(ui, markdown, pseudo_c_render);+ }+ TranscriptEntry::ToolCall {+ id: _,+ name,+ args_json,+ done,+ } => {+ let header = if let Some(res) = done {+ if res.ok {+ format!("tool · {name} ✓")+ } else {+ format!("tool · {name} ✗")+ }+ } else {+ format!("tool · {name} …")+ };+ egui::CollapsingHeader::new(RichText::new(header).monospace())+ .default_open(false)+ .show(ui, |ui| {+ ui.small(RichText::new("args").color(muted));+ ui.code(args_json.as_str());+ if let Some(res) = done {+ ui.small(+ RichText::new(if res.ok { "result" } else { "error" })+ .color(if res.ok { primary } else { Color32::from_rgb(0xE5, 0x39, 0x35) }),+ );+ ui.code(res.summary.as_str());+ } else {+ ui.small(RichText::new("running…").color(muted));+ }+ });+ }+ TranscriptEntry::Info { text } => {+ ui.small(RichText::new(text.as_str()).color(muted).italics());+ }+ TranscriptEntry::Error { text } => {+ ui.label(+ RichText::new(format!("error: {text}"))+ .color(Color32::from_rgb(0xE5, 0x39, 0x35))+ .monospace(),+ );+ }+ TranscriptEntry::Approval {+ id,+ tool,+ preview,+ resolved,+ } => {+ ui.group(|ui| {+ ui.label(RichText::new(format!("approval · {tool}")).color(primary).strong());+ ui.small(preview.as_str());+ match resolved {+ Some(true) => {+ ui.small(RichText::new("approved").color(primary));+ }+ Some(false) => {+ ui.small(+ RichText::new("denied").color(Color32::from_rgb(0xE5, 0x39, 0x35)),+ );+ }+ None => {+ ui.horizontal(|ui| {+ if ui.button("Approve").clicked() {+ *resolved = Some(true);+ on_approval(id, true);+ }+ if ui.button("Deny").clicked() {+ *resolved = Some(false);+ on_approval(id, false);+ }+ });+ }+ }+ });+ }+ }+}++/// Render Markdown with fenced code-block extraction — pseudo-C blocks defer+/// to the caller's `decomp_tokens`-backed renderer.+pub fn render_markdown(+ ui: &mut Ui,+ markdown: &str,+ pseudo_c_render: &mut dyn FnMut(&mut Ui, &str),+) {+ let blocks = parse_markdown(markdown);+ for block in blocks {+ match block {+ MarkdownBlock::Prose(p) => {+ ui.label(p.as_str());+ }+ MarkdownBlock::Code { lang, body } => {+ if lang.eq_ignore_ascii_case("c")+ || lang.eq_ignore_ascii_case("cpp")+ || lang.eq_ignore_ascii_case("c++")+ || lang.eq_ignore_ascii_case("pseudo-c")+ || lang.eq_ignore_ascii_case("pseudoc")+ || lang.eq_ignore_ascii_case("pseudo_c")+ {+ pseudo_c_render(ui, &body);+ } else {+ ui.group(|ui| {+ if !lang.is_empty() {+ ui.small(RichText::new(lang.as_str()).weak());+ }+ ui.code(body.as_str());+ });+ }+ }+ }+ }+}++// ── Install-Grok-Build one-click ─────────────────────────────────────────────++/// Attempt to spawn the platform's official Grok Build installer.+///+/// Returns a status string (either the copy-paste one-liner, or the spawn+/// error). This function **does not wait** for the installer to finish —+/// installers on all three platforms run interactively in their own terminal.+pub fn spawn_install_grok() -> String {+ let Some(cmd) = install_command_for_platform() else {+ return "Install: unsupported platform. See https://github.com/xai-org/grok-build".into();+ };+ match std::process::Command::new(&cmd.program)+ .args(&cmd.args)+ .spawn()+ {+ Ok(_child) => format!(+ "Started installer: {}\nWhen it finishes, click 'Re-scan for grok'.",+ cmd.display+ ),+ Err(e) => format!(+ "Failed to spawn installer ({e}).\nRun manually: {}\nDocs: {}",+ cmd.display, cmd.docs_url+ ),+ }+}diff --git a/crates/ghidrust-gui/src/main.rs b/crates/ghidrust-gui/src/main.rsindex c64c3c0..1ea5e22 100644--- a/crates/ghidrust-gui/src/main.rs+++ b/crates/ghidrust-gui/src/main.rs@@ -1,6 +1,7 @@//! Ghidrust CodeBrowser shell — Material 3 Dark/Light, Ghidra-like menus/panes.//! Icons: Google Material 3 geometry (see `icons.rs`); no emoji in the UI.+mod agent_pane;mod debugger;mod decomp_tokens;mod entropy;@@ -352,6 +353,11 @@ pub struct GhidrustApp {layouts_cached: Vec<String>,/// Current layout name (empty = unnamed / default).current_layout_name: String,+ // ── Grok Build agent console (Option C: ACP sidecar) ───────────────+ /// Per-window Grok pane state (session, transcript, install prompts, mode).+ /// One project per window means one session at a time; audit + MCP config+ /// are written to `<project>/.grok/` on session start.+ grok_pane: agent_pane::GrokPaneState,}/// Phase D (M4) — Checksum Generator report (Ghidra `ComputeChecksumsPlugin`).@@ -796,6 +802,7 @@ impl GhidrustApp {layouts_new_name: String::new(),layouts_cached: Vec::new(),current_layout_name: String::new(),+ grok_pane: agent_pane::GrokPaneState::new(),}}@@ -2755,6 +2762,366 @@ impl GhidrustApp {self.log(m);}+ /// Render the bottom-dock tabbed panel — `Grok` (primary) + `Console`.+ ///+ /// The old plain `Console` panel is preserved verbatim under the second+ /// tab; the Grok tab hosts the agent chat + tool-call cards + install+ /// prompt.+ fn render_bottom_dock(&mut self, ui: &mut egui::Ui) {+ use agent_pane::BottomTab;+ ui.horizontal(|ui| {+ let grok_selected = self.grok_pane.tab == BottomTab::Grok;+ let console_selected = self.grok_pane.tab == BottomTab::Console;+ if ui.selectable_label(grok_selected, "Grok").clicked() {+ self.grok_pane.tab = BottomTab::Grok;+ }+ if ui.selectable_label(console_selected, "Console").clicked() {+ self.grok_pane.tab = BottomTab::Console;+ }+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ match self.grok_pane.tab {+ BottomTab::Grok => {+ if ui.small_button("Clear chat").clicked() {+ self.grok_pane.transcript.clear();+ }+ }+ BottomTab::Console => {+ if ui.small_button("Clear").clicked() {+ self.console.clear();+ self.console_severity.clear();+ }+ }+ }+ });+ });+ ui.separator();+ match self.grok_pane.tab {+ BottomTab::Grok => self.render_grok_tab(ui),+ BottomTab::Console => self.render_console_tab(ui),+ }+ }++ fn render_console_tab(&mut self, ui: &mut egui::Ui) {+ egui::ScrollArea::vertical()+ .stick_to_bottom(true)+ .show(ui, |ui| {+ let n = self.console.len();+ for i in 0..n {+ let sev = self+ .console_severity+ .get(i)+ .copied()+ .unwrap_or(ConsoleSeverity::Info);+ let color = match sev {+ ConsoleSeverity::Info => ui.visuals().text_color(),+ ConsoleSeverity::Warn => Color32::from_rgb(0xFB, 0xC0, 0x2D),+ ConsoleSeverity::Error => Color32::from_rgb(0xE5, 0x39, 0x35),+ };+ let prefix = match sev {+ ConsoleSeverity::Info => " ",+ ConsoleSeverity::Warn => "! ",+ ConsoleSeverity::Error => "× ",+ };+ ui.label(+ egui::RichText::new(format!("{prefix}{}", self.console[i]))+ .monospace()+ .color(color),+ );+ }+ });+ }++ fn render_grok_tab(&mut self, ui: &mut egui::Ui) {+ let t = m3_tokens(self.theme);+ let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);+ let muted = Color32::from_rgb(+ t.on_surface_variant[0],+ t.on_surface_variant[1],+ t.on_surface_variant[2],+ );++ // Session header.+ ui.horizontal_wrapped(|ui| {+ let mode_label = self.grok_pane.mode.label();+ ui.label(egui::RichText::new(format!("Grok · {mode_label}")).color(primary).strong());+ if let Some(sess) = &self.grok_pane.session {+ ui.small(+ egui::RichText::new(format!(+ "transport={} · model={}",+ sess.transport_kind().label(),+ sess.model().unwrap_or("(user default)")+ ))+ .color(muted),+ );+ } else if let Some(bin) = &self.grok_pane.grok_bin {+ ui.small(+ egui::RichText::new(format!("grok bin: {}", bin.display())).color(muted),+ );+ } else {+ ui.small(+ egui::RichText::new("grok binary not found on PATH")+ .color(Color32::from_rgb(0xFB, 0xC0, 0x2D)),+ );+ }++ // Mode picker.+ ui.separator();+ let mut mode = self.grok_pane.mode;+ egui::ComboBox::new("grok_mode_combo", "mode")+ .selected_text(mode.label())+ .show_ui(ui, |ui| {+ ui.selectable_value(&mut mode, ghidrust_agent::AgentMode::Airgap, "airgap");+ ui.selectable_value(+ &mut mode,+ ghidrust_agent::AgentMode::ReadOnly,+ "read-only",+ );+ ui.selectable_value(&mut mode, ghidrust_agent::AgentMode::Full, "full");+ });+ if mode != self.grok_pane.mode {+ self.grok_pane.mode = mode;+ self.log(format!("Grok mode → {}", mode.label()));+ }++ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if self.grok_pane.session.is_some() {+ if ui.button("Stop").clicked() {+ self.grok_pane.session = None;+ self.log("Grok session stopped.");+ }+ } else {+ if ui.button("Start Session").clicked() {+ self.start_grok_session_from_ui();+ }+ if self.grok_pane.grok_bin.is_none() {+ if ui.button("Install Grok Build…").clicked() {+ let status = agent_pane::spawn_install_grok();+ self.log(status.clone());+ self.grok_pane.install_status = Some(status);+ }+ }+ if ui.button("Re-scan for grok").clicked() {+ self.grok_pane.refresh_grok_binary();+ let msg = match &self.grok_pane.grok_bin {+ Some(p) => format!("Found grok at {}", p.display()),+ None => "grok not found on PATH — install first".into(),+ };+ self.log(msg);+ }+ }+ });+ });++ // Value proposition + honest banner when no session is live.+ if self.grok_pane.session.is_none() && self.grok_pane.transcript.is_empty() {+ ui.small(+ egui::RichText::new(+ "Direct RE control via semantic search and chat — lower barrier to entry \+ to reverse engineering. Grok speaks the full Ghidrust MCP tool surface \+ (analyze, decompile Stage-0/0.5/1, xrefs, imports, strings, RTTI). \+ Read-only mode is safe by default; switch to Full for renames + comments.",+ )+ .color(muted),+ );+ }+ if let Some(err) = &self.grok_pane.last_error {+ ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), err);+ }+ if let Some(status) = &self.grok_pane.install_status {+ ui.small(egui::RichText::new(status).color(muted));+ }++ ui.separator();++ // Transcript.+ let mut pending_approvals: Vec<(String, bool)> = Vec::new();+ egui::ScrollArea::vertical()+ .id_salt("grok_transcript")+ .stick_to_bottom(true)+ .min_scrolled_height(120.0)+ .show(ui, |ui| {+ let transcript_len = self.grok_pane.transcript.len();+ for i in 0..transcript_len {+ let entry = &mut self.grok_pane.transcript[i];+ let mut pseudo_c_render =+ |ui: &mut egui::Ui, body: &str| render_pseudo_c_inline(ui, body);+ let mut on_approval = |id: &str, ok: bool| {+ pending_approvals.push((id.to_string(), ok));+ };+ agent_pane::render_transcript_entry(+ ui,+ entry,+ &mut pseudo_c_render,+ &mut on_approval,+ muted,+ primary,+ );+ ui.add_space(2.0);+ }+ if transcript_len == 0 && self.grok_pane.session.is_some() {+ ui.small(+ egui::RichText::new("Session started. Type a prompt below and press Ctrl+Enter.")+ .color(muted),+ );+ }+ });+ for (id, ok) in pending_approvals {+ self.log(format!("Grok approval · {id} · {}", if ok { "approve" } else { "deny" }));+ // The ACP transport doesn't yet accept approval verdicts back —+ // when it does, forward via `session.send_approval(id, ok)`.+ // For now the transcript reflects the user's decision locally.+ }++ ui.separator();++ // Input row.+ ui.horizontal(|ui| {+ let sink = egui::TextEdit::multiline(&mut self.grok_pane.input)+ .desired_rows(2)+ .desired_width(ui.available_width() - 96.0)+ .hint_text(if self.grok_pane.session.is_some() {+ "Ask about the current binary — Ctrl+Enter to send"+ } else {+ "Start a session to chat with Grok"+ });+ let resp = ui.add(sink);+ let ctrl_enter =+ resp.has_focus() && ui.input(|i| i.modifiers.ctrl && i.key_pressed(egui::Key::Enter));+ let clicked = ui.button("Send").clicked();+ if (ctrl_enter || clicked)+ && !self.grok_pane.input.trim().is_empty()+ && self.grok_pane.session.is_some()+ {+ self.dispatch_grok_prompt();+ }+ });+ }++ /// Build the current program-facts snapshot for the Grok pane.+ fn grok_program_facts(&self) -> ghidrust_agent::ProgramFacts {+ let mut f = ghidrust_agent::ProgramFacts::default();+ if let Some(proj) = &self.project {+ f.project_name = Some(proj.meta.name.clone());+ f.project_root = Some(proj.root.display().to_string());+ }+ if let Some(prog) = &self.program {+ f.program = Some(prog.name.clone());+ f.format = Some(prog.format.clone());+ f.arch = Some("x86_64".into());+ f.image_base = Some(format!("{:#x}", prog.image_base));+ f.entry_va = prog.entry.map(|v| format!("{v:#x}"));+ f.functions = Some(prog.analysis.functions.len());+ f.strings = Some(self.strings.len());+ for s in &prog.sections {+ f.sections.push(ghidrust_agent::SectionFact {+ name: s.name.clone(),+ va: format!("{:#x}", s.va),+ size: s.virtual_size as u64,+ });+ }+ }+ f.analyzers_run = self.last_analyzers_run.clone();+ if let Some(va) = self.listing_focus_va {+ let name = self+ .program+ .as_ref()+ .and_then(|p| p.display_function_name_at(va));+ f.current_selection = Some(ghidrust_agent::SelectionFact {+ va: format!("{va:#x}"),+ name,+ });+ }+ f+ }++ fn start_grok_session_from_ui(&mut self) {+ self.grok_pane.last_error = None;+ let Some(bin) = self.grok_pane.grok_bin.clone() else {+ let msg = "grok binary not installed — click 'Install Grok Build…' first";+ self.grok_pane.last_error = Some(msg.into());+ self.log_warn(msg);+ return;+ };+ // Per user spec: one grok per project. Prefer the open project root;+ // fall back to the current working directory when running ad-hoc.+ let project_root: std::path::PathBuf = match &self.project {+ Some(p) => p.root.clone(),+ None => std::env::current_dir()+ .unwrap_or_else(|_| std::path::PathBuf::from(".")),+ };+ let ghidrust_bin = std::env::current_exe()+ .ok()+ .and_then(|exe| exe.parent().map(|d| d.join(if cfg!(windows) { "ghidrust.exe" } else { "ghidrust" })))+ .or_else(|| Some(std::path::PathBuf::from(if cfg!(windows) { "ghidrust.exe" } else { "ghidrust" })))+ .unwrap();+ // Skill body: prefer the workspace `skill/SKILL.md` if we're running+ // from a repo, else pass an empty body (system_prompt still emits the+ // honesty rules).+ let (skill_body, skill_source) = load_skill_body();++ let facts = self.grok_program_facts();+ match agent_pane::start_session(+ &bin,+ &project_root,+ &ghidrust_bin,+ skill_source.as_deref(),+ self.grok_pane.mode,+ facts,+ &skill_body,+ ) {+ Ok(session) => {+ self.log(format!(+ "Grok session started · project={} · transport={} · mode={}",+ project_root.display(),+ session.transport_kind().label(),+ session.mode().label()+ ));+ self.grok_pane.session = Some(session);+ self.grok_pane.transcript.push(agent_pane::TranscriptEntry::Info {+ text: format!(+ "Session started for project {} — ghidrust MCP wired at .grok/mcp.json.",+ project_root.display()+ ),+ });+ }+ Err(e) => {+ self.grok_pane.last_error = Some(e.clone());+ self.log_error(format!("Grok session failed: {e}"));+ }+ }+ }++ fn dispatch_grok_prompt(&mut self) {+ let prompt = std::mem::take(&mut self.grok_pane.input).trim().to_string();+ if prompt.is_empty() {+ return;+ }+ let facts = self.grok_program_facts();+ let context = serde_json::to_string_pretty(&facts).unwrap_or_default();+ let facts_key = context.clone();+ // Only re-inject facts when they actually changed since the last turn —+ // keeps token cost down and matches SKILL.md's "no fabricated context" rule.+ let context_to_send =+ if self.grok_pane.last_facts_snapshot.as_deref() == Some(&facts_key) {+ String::new()+ } else {+ self.grok_pane.last_facts_snapshot = Some(facts_key);+ format!("Live program facts JSON:\n```json\n{context}\n```")+ };+ self.grok_pane+ .transcript+ .push(agent_pane::TranscriptEntry::User { text: prompt.clone() });+ if let Some(sess) = self.grok_pane.session.as_mut() {+ if let Err(e) = sess.send_prompt(&prompt, &context_to_send) {+ self.grok_pane+ .transcript+ .push(agent_pane::TranscriptEntry::Error {+ text: format!("send failed: {e}"),+ });+ }+ }+ }+/// Menu / pane identifiers present in the shell (for structural tests).////// Ghidra top-level menus (from `docking.tool.ToolConstants`):@@ -7552,47 +7919,18 @@ impl eframe::App for GhidrustApp {}});+ // Bottom dock: tabbed (Grok primary + Console). The plain analyzer /+ // script log is never hidden — it just moves under the "Console" tab.+ // Grok is the default active tab so an RE opens the app and starts+ // typing to the agent immediately.if self.show_console {+ // Pull streamed events into the transcript before we render.+ self.grok_pane.poll();egui::TopBottomPanel::bottom("console").resizable(true)- .default_height(120.0)+ .default_height(180.0).show(ctx, |ui| {- ui.horizontal(|ui| {- ui.heading("Console");- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if ui.small_button("Clear").clicked() {- self.console.clear();- self.console_severity.clear();- }- });- });- egui::ScrollArea::vertical()- .stick_to_bottom(true)- .show(ui, |ui| {- let n = self.console.len();- for i in 0..n {- let sev = self- .console_severity- .get(i)- .copied()- .unwrap_or(ConsoleSeverity::Info);- let color = match sev {- ConsoleSeverity::Info => ui.visuals().text_color(),- ConsoleSeverity::Warn => Color32::from_rgb(0xFB, 0xC0, 0x2D),- ConsoleSeverity::Error => Color32::from_rgb(0xE5, 0x39, 0x35),- };- let prefix = match sev {- ConsoleSeverity::Info => " ",- ConsoleSeverity::Warn => "! ",- ConsoleSeverity::Error => "× ",- };- ui.label(- egui::RichText::new(format!("{prefix}{}", self.console[i]))- .monospace()- .color(color),- );- }- });+ self.render_bottom_dock(ui);});}diff --git a/crates/ghidrust-gui/src/panes.rs b/crates/ghidrust-gui/src/panes.rsindex cedb49a..e624d6c 100644--- a/crates/ghidrust-gui/src/panes.rs+++ b/crates/ghidrust-gui/src/panes.rs@@ -15,6 +15,11 @@ use eframe::egui::{self, Color32, RichText, Ui};/// exact strings Ghidra uses so the Window menu is a drop-in mental map.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]pub enum PaneKind {+ /// Ghidrust addition (not present in Ghidra): the Grok Build agent+ /// console. Rendered as the primary tab in the bottom dock (next to the+ /// plain `Console`) so RE users can chat with an agent that already+ /// speaks the full Ghidrust MCP tool surface.+ AgentConsole,Bookmarks,Bytes,ChecksumGenerator,@@ -63,6 +68,8 @@ impl PaneKind {PaneKind::Overview,PaneKind::Listing,PaneKind::DecompiledView,+ // Ghidrust-specific (bottom dock primary tab).+ PaneKind::AgentConsole,// Alphabetical from here (Ghidra Window menu order)PaneKind::Bookmarks,PaneKind::Bytes,@@ -94,6 +101,7 @@ impl PaneKind {/// Ghidra display title (Window menu label / provider `TITLE`).pub const fn title(self) -> &'static str {match self {+ PaneKind::AgentConsole => "Grok",PaneKind::Bookmarks => "Bookmarks",PaneKind::Bytes => "Bytes",PaneKind::ChecksumGenerator => "Checksum Generator",@@ -140,6 +148,7 @@ impl PaneKind {/// Ghidra plugin owner (for empty-state hint text).pub const fn plugin(self) -> &'static str {match self {+ PaneKind::AgentConsole => "GhidrustAgentConsole",PaneKind::Bookmarks => "BookmarkPlugin",PaneKind::Bytes => "ByteViewerPlugin",PaneKind::ChecksumGenerator => "ComputeChecksumsPlugin",@@ -203,12 +212,15 @@ impl PaneKind {| PaneKind::ExternalPrograms| PaneKind::DataTypePreview| PaneKind::ChecksumGenerator+ // Grok agent console (ghidrust-agent crate).+ | PaneKind::AgentConsole)}/// Optional stable id used for egui window ids (must be unique).pub const fn egui_id(self) -> &'static str {match self {+ PaneKind::AgentConsole => "pane_agent_console",PaneKind::Bookmarks => "pane_bookmarks",PaneKind::Bytes => "pane_bytes",PaneKind::ChecksumGenerator => "pane_checksum",@@ -317,6 +329,7 @@ pub fn empty_state(ui: &mut Ui, kind: PaneKind, muted: Color32) {/// One-liner hint pointing at which analyzer/model would fill this pane.pub const fn backend_pending_message(kind: PaneKind) -> &'static str {match kind {+ PaneKind::AgentConsole => "",PaneKind::Bookmarks => "Backend pending — Bookmarks model + margin markers land in Phase B (M2).",PaneKind::Bytes => "",PaneKind::ChecksumGenerator => "",diff --git a/docs/GPU_ANALYZER_MATRIX.md b/docs/GPU_ANALYZER_MATRIX.mdindex d4c2d5b..e2b5370 100644--- a/docs/GPU_ANALYZER_MATRIX.md+++ b/docs/GPU_ANALYZER_MATRIX.md@@ -8,6 +8,7 @@ CPU remains the correctness oracle. Timing always splits **PCIe** (upload+downlo| Analyzer | Strategy class | GPU method (novel kernel / multipass) ||----------|----------------|----------------------------------------|| ASCII Strings | `printable_run` | Parallel printable-byte mark + host run compact |+| Unicode Strings | `cstr_multi` | Host UTF-16LE scan; GPU seed uses multi-needle cstr family || Aggressive Instruction Finder | `code_density` | Non-int3 / code-like density windows over exec image || Call Convention ID | `prologue_abi` | Scan push/mov/sub-rsp / ret patterns → ABI hint seeds || Call-Fixup Installer | `cstr_multi` | Multi-needle cstr for security_cookie / known fixups |diff --git a/fixtures/analysis_lab.pe b/fixtures/analysis_lab.peindex 5c4081a..44077e3 100644Binary files a/fixtures/analysis_lab.pe and b/fixtures/analysis_lab.pe differdiff --git a/fixtures/decode_continuity.bin b/fixtures/decode_continuity.binnew file mode 100644index 0000000..c90f49f--- /dev/null+++ b/fixtures/decode_continuity.bin@@ -0,0 +1 @@+UH���1��\ No newline at end of filediff --git a/fixtures/decode_continuity.meta.txt b/fixtures/decode_continuity.meta.txtnew file mode 100644index 0000000..c1da96c--- /dev/null+++ b/fixtures/decode_continuity.meta.txt@@ -0,0 +1,2 @@+Synthetic undecodable hole (0x06) between prologue and xor/ret.+Used by disasm --skip-bad continuity tests (raw bytes, not a PE).diff --git a/skill/SKILL.md b/skill/SKILL.mdindex eef65a9..36c8f30 100644--- a/skill/SKILL.md+++ b/skill/SKILL.md@@ -150,6 +150,10 @@ ghidrust project analyze PROJ_DIR --file ID \| `list_analyzers` | — || `list_gpu_strategies` | — (name → strategy matrix) || `analyze` | `path`, optional `analyzers[]`, optional **`gpu`: bool** |+| `list_strings` / `search_strings` | `path`, optional `encoding`/`filter`/`min` |+| `get_xrefs_to` / `get_xrefs_from` / `get_string_xrefs` | RIP-aware xrefs |+| `list_imports` / `get_import_xrefs` | PE IAT + call-sites |+| `function_at` / `get_function_by_address` | containing function for a VA || `gpu_decompile` | `path`, optional `out` || `rtti_gpu_bench` | `path` || `load` / `disassemble` / `rtti` | as before |@@ -164,12 +168,16 @@ Add `--json` for structured stdout.|---------|---------|| Help | `ghidrust help` || Load | `ghidrust load <path>` |-| Disasm | `ghidrust disasm <path> [--addr HEX] [--count N]` |+| Disasm | `ghidrust disasm <path> [--addr HEX] [--count N] [--skip-bad]` |+| Strings | `ghidrust strings <path> [--encoding ascii\|utf16\|all] [--filter SUB]` |+| Xrefs | `ghidrust xrefs <path> (--to HEX \| --from HEX \| --string F \| --import N)` |+| Imports | `ghidrust imports <path> [--dll\|--name]` |+| Function-at | `ghidrust function-at <path> --addr HEX` || RTTI only | `ghidrust rtti <path>` || List analyzers | `ghidrust analyzers` || **Analyze** | `ghidrust analyze <path> [--analyzers a,b \| --analyzer NAME …] [--gpu]` || Bulk bench | `ghidrust bulk-bench <path>` |-| Decompile (Stage-1 default, SSA + structure + types) | `ghidrust decompile <path>` |+| Decompile (Stage-1 default; metrics only with `--verbose`) | `ghidrust decompile <path> [--verbose]` || Decompile (Stage-0 CFG scaffolding, oracle) | `ghidrust decompile <path> --stage0` || Decompile (Stage-0.5 IR-informed, oracle) | `ghidrust decompile <path> --stage05` || Decompile bench (Stage-0 vs Stage-0.5 vs Stage-1) | `ghidrust decompile-bench <path> [--functions N] [--count N] [--out F]` |@@ -187,6 +195,10 @@ Add `--json` for structured stdout.```bash# Quick triageghidrust load PATH --json+ghidrust strings PATH --encoding all --filter SomeName --json+ghidrust xrefs PATH --string SomeName --json+ghidrust function-at PATH --addr 0x140001234 --json+ghidrust imports PATH --jsonghidrust analyze PATH --analyzer "ASCII Strings" --analyzer "Function Start Search" --json# GPU RTTI seed path on one analyzer@@ -206,13 +218,14 @@ ghidrust gpu-decompile PATH --metrics gdec.json----## GPU strategy matrix (all 20 + decompile)+## GPU strategy matrix (all analyzers + decompile)See `docs/GPU_ANALYZER_MATRIX.md`. Every Auto Analysis name has a dedicated strategy class (not one printable kernel rebranded). Examples:| Analyzer | Strategy ||----------|----------|| ASCII Strings | `printable_run` |+| Unicode Strings | `cstr_multi` (host UTF-16LE authoritative) || Function Start Search | `prologue_seed` || WindowsPE x86 PE RTTI Analyzer | `rtti_scan` || Embedded Media | `magic_media` |@@ -237,7 +250,7 @@ Timing model: **pcie_upload / device_ms / pcie_download** split. On large binari----## Auto Analysis — exhaustive catalog (20)+## Auto Analysis — exhaustive catalog (21)Exact names, honest outputs. Use the `Name` column verbatim in`--analyzer "…"` / `--analyzers "a,b"`. Every row is a **PASS** in the shipped@@ -251,7 +264,8 @@ Output column names the field on `AnalyzerOutput` you get in `--json`| # | Name | What it does | Output field(s) | Message ||---|---|---|---|---|-| 1 | `ASCII Strings` | Bulk ≥4-char printable scan (Sequential / ParallelCpu / GpuOrFallback backend). | `strings: [{va, value, length}]` | `found N ASCII string(s) [BulkScanMode…]` |+| 1 | `ASCII Strings` | Bulk ≥4-char printable scan (Sequential / ParallelCpu / GpuOrFallback backend). | `strings: [{va, value, length, encoding}]` | `found N ASCII string(s) [BulkScanMode…]` |+| 1b | `Unicode Strings` | UTF-16LE printable runs across mapped blocks. | `strings: [{va, value, length, encoding: utf16le}]` | `found N UTF-16LE string(s)` || 2 | `Aggressive Instruction Finder` | Fills real code gaps only; adds new `FunctionInfo` + a `DiscoveredRange`. No fabrication if the fixture has no gap. | `recovered_ranges: [{start, end}]` (+ `functions[]`) | `found N recovered code range(s)` || 3 | `Call Convention ID` | Tags each function with Win64/cdecl/stdcall/thiscall. | `conventions: [[va, name], …]` (+ `functions[*].calling_convention`) | `identified N calling convention(s)` || 4 | `Call-Fixup Installer` | Security-cookie / thunk stub detection. | `call_fixups: [{fixup_name, call_va}]` | `installed N call fixup(s)` |@@ -272,7 +286,7 @@ Output column names the field on `AnalyzerOutput` you get in `--json`| 19 | `Windows x86 Propagate External Parameters` | Known Win32 API prototypes attached to import call sites. | `external_params: [[va, prototype], …]` | `applied N external parameter prototype(s)` || 20 | `WindowsResourceReference` | `.rsrc` records (`VERSION`, `RT_ICON`, …). | `resources: [{name, va}]` | `parsed N resource record(s)` |-**Defaults** (empty selection): `ASCII Strings`, `WindowsPE x86 PE RTTI Analyzer`, `Function Start Search`, `Create Address Tables`, `Embedded Media`, `Demangler Microsoft`.+**Defaults** (empty selection): `ASCII Strings`, `Unicode Strings`, `WindowsPE x86 PE RTTI Analyzer`, `Function Start Search`, `Create Address Tables`, `Embedded Media`, `Demangler Microsoft`.With `--gpu`: same CPU output plus a `| gpu_enrich hits_merged=… backend=…` suffix on the human message. Not a replacement for `gpu-decompile`.@@ -297,7 +311,7 @@ Related GPU / matrix benches (shipped, callable, **not** part of the eval sweep)| Method | CLI | Purpose ||---|---|---|-| `analyzer-bench` | `ghidrust analyzer-bench PATH [--large] [--out F] [--json]` | All 20 analyzers + a GPU-decompile row: CPU wall-time vs `pcie_upload / device_ms / pcie_download` split, per-analyzer `equal` correctness flag. |+| `analyzer-bench` | `ghidrust analyzer-bench PATH [--large] [--out F] [--json]` | All analyzers + a GPU-decompile row: CPU wall-time vs `pcie_upload / device_ms / pcie_download` split, per-analyzer `equal` correctness flag. || `analyzer-bench-matrix` | `ghidrust analyzer-bench-matrix` | Static analyzer → GPU-strategy matrix (e.g. `ASCII Strings → printable_run`, `WindowsPE x86 PE RTTI Analyzer → rtti_scan`). || `bulk-bench` | `ghidrust bulk-bench PATH [--json]` | Seq / parallel-CPU / GPU-or-fallback bulk-string timings. || `rtti-gpu-bench` | `ghidrust rtti-gpu-bench PATH [--out F] [--json]` | CPU `recover_rtti` vs GPU `rtti_scan` seed with PCIe / device split. |