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-il2cpp` and `ghidrust-unity-inventory` crates to the project. Update `Cargo.toml` and `Cargo.lock` to include new dependencies. Enhance the CLI with commands for IL2CPP metadata handling and Unity inventory management. Refactor `grok_binary_path` function for improved clarity and introduce a new function to probe the Grok version. Update README and documentation to reflect new features and usage instructions.
oofzc88ad2098421
diff --git a/Cargo.lock b/Cargo.lockindex f55b88a..ab59739 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1326,7 +1326,9 @@ version = "0.1.0"dependencies = ["ghidrust-core","ghidrust-decomp",+ "ghidrust-il2cpp","ghidrust-types",+ "ghidrust-unity-inventory","serde","serde_json",]@@ -1381,9 +1383,21 @@ dependencies = ["ghidrust-core","ghidrust-decomp","ghidrust-types",+ "libc","rfd","serde","serde_json",+ "unicode-width",+ "windows-sys 0.59.0",+]++[[package]]+name = "ghidrust-il2cpp"+version = "0.1.0"+dependencies = [+ "ghidrust-core",+ "serde",+ "serde_json",][[package]]@@ -1433,6 +1447,18 @@ dependencies = ["serde",]+[[package]]+name = "ghidrust-unity-inventory"+version = "0.1.0"+dependencies = [+ "ghidrust-core",+ "ghidrust-il2cpp",+ "hex",+ "serde",+ "serde_json",+ "sha2",+]+[[package]]name = "gl_generator"version = "0.14.0"@@ -2961,6 +2987,17 @@ dependencies = ["digest",]+[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]+[[package]]name = "shlex"version = "2.0.1"diff --git a/Cargo.toml b/Cargo.tomlindex 4f2fe65..b520db1 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -9,6 +9,8 @@ members = ["crates/ghidrust-structure","crates/ghidrust-core","crates/ghidrust-decomp",+ "crates/ghidrust-il2cpp",+ "crates/ghidrust-unity-inventory","crates/ghidrust-cli","crates/ghidrust-gui","crates/ghidrust-agent",@@ -30,4 +32,6 @@ 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-il2cpp = { path = "crates/ghidrust-il2cpp" }+ghidrust-unity-inventory = { path = "crates/ghidrust-unity-inventory" }ghidrust-agent = { path = "crates/ghidrust-agent" }diff --git a/DEPENDENCIES.md b/DEPENDENCIES.mdindex 14504fa..6682fd8 100644--- a/DEPENDENCIES.md+++ b/DEPENDENCIES.md@@ -42,6 +42,7 @@ Same rule for any other mature decoder used only to cross-check edge cases again- `goblin`, `object`, `pelite`, `scroll` — PE/ELF parsed by hand in `ghidrust-core`.- `iced-x86`, `zydis`, `capstone` bindings — **not** runtime decode; see CI oracle exception above.+- Il2CppDumper / Cpp2IL / Il2CppInspector as runtime deps — formats reimplemented in `ghidrust-il2cpp` (reference-only).- Full `rmcp` / heavy MCP SDKs — thin hand-rolled tools/list + tools/call over stdio.## Supply chaindiff --git a/README.md b/README.mdindex 0782d64..232569a 100644--- a/README.md+++ b/README.md@@ -2,7 +2,7 @@Hand-rolled **Rust** reverse-engineering toolkit inspired by [Ghidra](https://github.com/NationalSecurityAgency/ghidra).-Ghidrust loads PE/ELF binaries, produces x86-64 listings, runs Auto Analysis, decompiles to pseudo-C, and saves durable projects — from a CLI, an MCP server for agents, or an egui CodeBrowser-style GUI.+Ghidrust loads PE/ELF (and raw blobs), produces x86-64 listings, runs Auto Analysis, decompiles to pseudo-C, parses IL2CPP metadata / Unity install inventory, and saves durable projects — from a CLI, an MCP server for agents, or an egui CodeBrowser-style GUI.It is **not** a Ghidra fork or wrapper. Analysis logic (loaders, decode, analyzers, decompile) is written in-tree so the core stays small, auditable, and freestanding.@@ -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, look up strings/xrefs/imports/functions, and decompile without a GUI or ad-hoc PE scripts |+| **Agent-ready** | Headless CLI + stdio MCP so coding agents can load, disassemble, analyze, look up strings/xrefs/imports/functions, inventory Unity/IL2CPP, 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."@@ -181,18 +181,21 @@ First-class commands for the queries agents used to need ad-hoc scripts for. Sam| 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 strings <path>` | Scan ASCII and/or UTF-16LE strings (PE/ELF or `--raw` blob) | `--encoding`, `--filter`, `--match substr\|token\|whole\|glob`, `--limit N`, `--out FILE`, `--raw`, `--json` |+| `ghidrust xrefs <path>` | Cross-references (absolute operand hex **and** RIP-relative `LEA`/`call`/`jmp`) | Exactly one of: `--to` / `--from` / `--string` / `--import`; `--skip-stubs` / `--classify` for IL2CPP || `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 il2cpp meta\|map\|stubs` | IL2CPP metadata + method map + resolve stubs | See [docs/IL2CPP.md](docs/IL2CPP.md) |+| `ghidrust unity-inventory <dir>` | Unity player layout inventory (assemblies, plugins, metadata peek) | `--json`, `--out FILE` || `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+# Wide + ASCII string search (token match + limit; BOM-free --out)+ghidrust strings app.exe --encoding all --filter Config --match token --limit 50 --json+ghidrust strings huge.bin --raw --filter Camera --out camera_strings.json --json-# Code sites that reference a string (RIP-relative LEA included)-ghidrust xrefs app.exe --string ResolutionWidth --json+# Code sites that reference a string (RIP-relative LEA included; hide IL2CPP resolve stubs)+ghidrust xrefs app.exe --string ResolutionWidth --skip-stubs --json# Import call-sites (IAT slot + FF15/RIP refs)ghidrust imports app.exe --name ShellExecuteW --json@@ -203,13 +206,19 @@ ghidrust function-at app.exe --addr 0x14000d8ad --json# Keep listing through a decode holeghidrust disasm app.exe --addr 0x14000d890 --count 40 --skip-bad++# Unity / IL2CPP (see docs/IL2CPP.md)+ghidrust unity-inventory /path/to/GameDir --json+ghidrust il2cpp meta /path/to/*_Data/il2cpp_data/Metadata/global-metadata.dat --filter Camera --json+ghidrust il2cpp stubs --binary /path/to/GameAssembly.dll --json+ghidrust decompile /path/to/GameAssembly.dll --addr 0x180012345 --follow-stub```### Decompile methods| Method | CLI | What it emits | Outputs / where to see them ||---|---|---|---|-| **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-1** (**default**) | `ghidrust decompile <path> [--addr HEX] [--count N] [--follow-stub] [--verbose]` | Full SSA + structure + types Stage-1 emit (`--follow-stub` decompiles through an IL2CPP resolve thunk when the slot target is mapped): 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. |@@ -272,13 +281,20 @@ ghidrust disasm /path/to/app.exe --count 32ghidrust 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 strings /path/to/app.exe --encoding all --filter SomeName --match token --limit 50 --json+ghidrust strings /path/to/blob.dat --raw --filter Camera --out camera.json --json+ghidrust xrefs /path/to/app.exe --string SomeName --skip-stubs --classify --jsonghidrust xrefs /path/to/app.exe --to 0x140002010 --jsonghidrust imports /path/to/app.exe --jsonghidrust xrefs /path/to/app.exe --import CreateFileW --jsonghidrust function-at /path/to/app.exe --addr 0x140001234 --json+# Unity player inventory + IL2CPP metadata / stubs / method map+ghidrust unity-inventory /path/to/GameDir --json+ghidrust il2cpp meta /path/to/Game_Data/il2cpp_data/Metadata/global-metadata.dat --filter Camera --json+ghidrust il2cpp map --binary /path/to/GameAssembly.dll --meta /path/to/.../global-metadata.dat --json+ghidrust il2cpp stubs --binary /path/to/GameAssembly.dll --json+# List Auto Analysis names (Ghidra-compatible labels)ghidrust analyzers@@ -286,11 +302,12 @@ ghidrust analyzersghidrust 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-1 default; oracles via --stage0 / --stage05+# CPU decompile — Stage-1 default; oracles via --stage0 / --stage05; IL2CPP --follow-stubghidrust decompile /path/to/app.exe # Stage-1; quiet stderrghidrust decompile /path/to/app.exe --verbose # + metrics line on stderrghidrust decompile /path/to/app.exe --addr 0x140001000 --jsonghidrust decompile /path/to/app.exe --stage05 --json # IR oracle + lift-coverage JSON+ghidrust decompile /path/to/GameAssembly.dll --addr 0x180012345 --follow-stub# Wall-clock + lift-coverage bench across all discovered functionsghidrust decompile-bench /path/to/app.exe --functions 32 --count 128 --out bench.txt@@ -333,14 +350,16 @@ MyProject/|---------|----------------|| `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 strings <path> [--raw] [--encoding …] [--filter SUB] [--match MODE] [--limit N] [--out FILE] [--json]` | String scan (blob-capable) |+| `ghidrust xrefs <path> (--to\|--from\|--string\|--import) [--skip-stubs] [--classify] [--json]` | RIP-aware xrefs || `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 il2cpp meta\|map\|stubs …` | IL2CPP metadata / RVA map / resolve stubs ([docs/IL2CPP.md](docs/IL2CPP.md)) |+| `ghidrust unity-inventory <dir> [--out FILE] [--json]` | Unity player install inventory || `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 <path> [--addr HEX] [--count N] [--stage0\|--stage05\|--stage1] [--follow-stub] [--verbose] [--json]` | **CPU** decompile (**Stage-1** default; `--follow-stub` for IL2CPP resolve thunks) || `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 |@@ -351,9 +370,9 @@ MyProject/| `ghidrust project create\|import\|list\|analyze\|export …` | Durable projects || `ghidrust mcp` | Stdio MCP server for agents |-`--json` writes UTF-8 **without BOM**. Decompile status lines go to stderr only with `--verbose` (avoids PowerShell `NativeCommandError` noise when scripting).+`--json` and `--out FILE` write UTF-8 **without BOM**. Prefer `--out` over shell redirection when filters contain `:` (Windows path hazard). 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`.+Recommended early path: **strings / imports / xrefs** for orientation → **Function Start Search** + `function-at` → address tables → conventions/stack → RTTI → `decompile`. For Unity IL2CPP players: **`unity-inventory`** for install layout → **`il2cpp meta`** for managed types → stubs / map / `--follow-stub` as needed.---@@ -442,25 +461,38 @@ 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) |+| `list_strings` / `search_strings` | `path`, optional `encoding` (`ascii`\|`utf16`\|`all`), `filter`, `match` (`substr`\|`token`\|`whole`\|`glob`), `min`, `limit`, `raw` | ASCII / UTF-16LE strings; `raw:true` for non-PE/ELF blobs |+| `get_xrefs_to` | `path`, `addr`, optional `skip_stubs`, `classify` | Xrefs **to** a VA; IL2CPP resolve-stub filter/label || `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) |+| `il2cpp_meta` | `path`, optional `filter` | Parse `global-metadata.dat` (v27/29/31); fail closed if encrypted |+| `il2cpp_map` | `binary`, `meta`, optional `filter` | Metadata ↔ RVA map (`rva` null when unproven) |+| `il2cpp_stubs` | `binary`, optional `filter`, `max` | List IL2CPP resolve stubs by icall name |+| `unity_inventory` | `path` | Unity player dir → assemblies, plugins, metadata, XR-related inventory |+| `decompile` | `path`, optional `addr`, `count`, `stage`, `follow_stub` | Stage-1 default; `follow_stub` follows IL2CPP resolve thunks || `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 |+IL2CPP version matrix and Unity inventory schema: [docs/IL2CPP.md](docs/IL2CPP.md).+Example agent-facing call shapes (conceptual):```json-{ "name": "list_strings", "arguments": { "path": "…/app.exe", "encoding": "utf16", "filter": "UserConfig" } }+{ "name": "list_strings", "arguments": { "path": "…/app.exe", "encoding": "all", "filter": "Camera", "match": "token", "limit": 50 } }+{ "name": "list_strings", "arguments": { "path": "…/global-metadata.dat", "raw": true, "filter": "UnityEngine", "limit": 20 } }+{ "name": "get_xrefs_to", "arguments": { "path": "…/GameAssembly.dll", "addr": "0x180012345", "skip_stubs": true, "classify": true } }{ "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": "unity_inventory", "arguments": { "path": "…/GameDir" } }+{ "name": "il2cpp_meta", "arguments": { "path": "…/global-metadata.dat", "filter": "Camera" } }+{ "name": "il2cpp_map", "arguments": { "binary": "…/GameAssembly.dll", "meta": "…/global-metadata.dat" } }+{ "name": "il2cpp_stubs", "arguments": { "binary": "…/GameAssembly.dll", "filter": "Camera" } }+{ "name": "decompile", "arguments": { "path": "…/GameAssembly.dll", "addr": "0x180012345", "follow_stub": true } }{ "name": "analyze", "arguments": { "path": "…/app.exe", "analyzers": ["ASCII Strings", "Unicode Strings"], "gpu": true } }```@@ -509,12 +541,14 @@ 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, imports/IAT, xrefs, projects, bulk scan |+| `ghidrust-core` | PE/ELF/blob, 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 || `ghidrust-ssa` | CFG-on-IR, Cooper–Harvey–Kennedy dominators, Cytron dominance frontiers, phi placement || `ghidrust-decomp` | Stage-0 CFG → pseudo-C (regression oracle), Stage-0.5 IR-informed emit (`ir_emit`), decompile-bench harness, experimental GPU VRAM multipass |+| `ghidrust-il2cpp` | IL2CPP `global-metadata.dat` + CodeRegistration correlation + resolve stubs |+| `ghidrust-unity-inventory` | Unity player layout inventory (assemblies, plugins, metadata) || `ghidrust-cli` | CLI + MCP + benches / `gpu-decompile` / `decompile-bench` || `ghidrust-gui` | CodeBrowser-style UI |@@ -528,6 +562,7 @@ You should not need to type JSON by hand day-to-day — the IDE/agent does that| [docs/GPU_DECOMPILE_PROCESS.md](docs/GPU_DECOMPILE_PROCESS.md) | Multipass dataflow + dump format || [docs/GPU_ANALYZER_MATRIX.md](docs/GPU_ANALYZER_MATRIX.md) | Per-analyzer GPU strategy + bench CLI || [docs/PARALLEL_RE_RESEARCH.md](docs/PARALLEL_RE_RESEARCH.md) | CPU pool vs GPU bulk RE |+| [docs/IL2CPP.md](docs/IL2CPP.md) | IL2CPP metadata matrix + Unity player inventory || [DEPENDENCIES.md](DEPENDENCIES.md) | Dependency policy || [skill/README.md](skill/README.md) | Agent skill install |diff --git a/crates/ghidrust-agent/Cargo.toml b/crates/ghidrust-agent/Cargo.tomlindex e08b897..2b24331 100644--- a/crates/ghidrust-agent/Cargo.toml+++ b/crates/ghidrust-agent/Cargo.toml@@ -3,7 +3,7 @@ name = "ghidrust-agent"version.workspace = trueedition.workspace = truelicense.workspace = true-description = "Ghidrust Grok Build agent bridge (ACP sidecar + tool_bridge + audit + install)"+description = "Ghidrust Grok Build glue (install, MCP/skill wiring, program facts, audit)"[lib]path = "src/lib.rs"diff --git a/crates/ghidrust-agent/src/acp_client.rs b/crates/ghidrust-agent/src/acp_client.rsdeleted file mode 100644index 4aaf456..0000000--- a/crates/ghidrust-agent/src/acp_client.rs+++ /dev/null@@ -1,695 +0,0 @@-//! 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/installer.rs b/crates/ghidrust-agent/src/installer.rsindex 4177b1b..bf1300b 100644--- a/crates/ghidrust-agent/src/installer.rs+++ b/crates/ghidrust-agent/src/installer.rs@@ -97,6 +97,44 @@ pub fn grok_binary_path() -> Option<PathBuf> {candidates.into_iter().find(|c| c.is_file())}+/// Run `grok --version` synchronously (short timeout) and return the first+/// non-empty stdout / stderr line.+pub fn probe_grok_version(grok_bin: &std::path::Path) -> Result<String, String> {+ use std::process::{Command, Stdio};+ use std::time::{Duration, Instant};++ let mut child = Command::new(grok_bin)+ .arg("--version")+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|e| format!("spawn '{} --version': {e}", grok_bin.display()))?;++ let deadline = Instant::now() + Duration::from_secs(4);+ loop {+ match child.try_wait() {+ Ok(Some(_)) => break,+ Ok(None) if Instant::now() > deadline => {+ let _ = child.kill();+ return Err("timed out waiting for `grok --version`".into());+ }+ Ok(None) => std::thread::sleep(Duration::from_millis(50)),+ Err(e) => return Err(e.to_string()),+ }+ }+ let out = child.wait_with_output().map_err(|e| e.to_string())?;+ let stdout = String::from_utf8_lossy(&out.stdout);+ let stderr = String::from_utf8_lossy(&out.stderr);+ let first = stdout+ .lines()+ .chain(stderr.lines())+ .find(|l| !l.trim().is_empty())+ .unwrap_or("(no output)")+ .to_string();+ Ok(first)+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/ghidrust-agent/src/lib.rs b/crates/ghidrust-agent/src/lib.rsindex 7803448..b63fe3b 100644--- a/crates/ghidrust-agent/src/lib.rs+++ b/crates/ghidrust-agent/src/lib.rs@@ -1,30 +1,15 @@-//! Ghidrust ↔ Grok Build agent bridge.+//! Ghidrust ↔ Grok Build glue.//!-//! 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.+//! The GUI hosts the **real** Grok TUI via an in-tree PTY (`ghidrust-gui::grok_term`).+//! This crate only provides project wiring the TUI needs on Start://!-//! Design notes:+//! - Locate / install the `grok` binary ([`installer`])+//! - Write project MCP config + skill mirror ([`tool_bridge`])+//! - Build honesty + live [`ProgramFacts`] text ([`system_prompt`])//!-//! - **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.+//! No ACP / headless chat transport lives here anymore — that layer reimplemented+//! Grok features poorly; the embedded TUI owns slash commands, models, and sessions.-pub mod acp_client;pub mod audit;pub mod installer;pub mod markdown;@@ -32,53 +17,17 @@ 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 installer::{+ grok_binary_path, install_command_for_platform, probe_grok_version, 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,-}+pub use system_prompt::{+ FunctionFact, ImportFact, ProgramFacts, ProjectFileFact, SectionFact, SelectionFact,+ SystemPromptBuilder,+};+pub use tool_bridge::{+ register_mcp_with_grok_cli, resolve_ghidrust_cli_bin, write_project_mcp_config,+ write_project_skill,+};diff --git a/crates/ghidrust-agent/src/system_prompt.rs b/crates/ghidrust-agent/src/system_prompt.rsindex 91b00d3..b2e7615 100644--- a/crates/ghidrust-agent/src/system_prompt.rs+++ b/crates/ghidrust-agent/src/system_prompt.rs@@ -26,6 +26,13 @@ use serde::{Deserialize, Serialize};pub struct ProgramFacts {pub project_name: Option<String>,pub project_root: Option<String>,+ /// Every file imported into the project. Lets the agent say "you have+ /// mnm_exe.exe and mnm_dll.dll open" without needing a tool call first.+ pub project_files: Vec<ProjectFileFact>,+ /// Which file id is currently loaded into the main view (matches+ /// `project_files[*].id`).+ pub active_file_id: Option<String>,+pub program: Option<String>,pub format: Option<String>,pub arch: Option<String>,@@ -35,9 +42,26 @@ pub struct ProgramFacts {pub analyzers_run: Vec<String>,pub functions: Option<usize>,pub strings: Option<usize>,++ /// Small sample of the discovered functions so the agent has a starting+ /// point without a `list_functions` round-trip. Cap at ~24 entries in+ /// the caller.+ pub top_functions: Vec<FunctionFact>,+ /// Small sample of PE imports (dll + name). Same reasoning.+ pub imports_sample: Vec<ImportFact>,+pub current_selection: Option<SelectionFact>,}+/// One project-imported file.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ProjectFileFact {+ pub id: String,+ pub display_name: String,+ /// Whether this file has been analyzed at least once in the project.+ pub has_saved_analysis: bool,+}+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct SectionFact {pub name: String,@@ -51,6 +75,18 @@ pub struct SelectionFact {pub name: Option<String>,}+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct FunctionFact {+ pub va: String,+ pub name: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ImportFact {+ pub dll: String,+ pub name: String,+}+/// System-prompt assembler.////// Callers typically:@@ -123,8 +159,17 @@ impl<'a> SystemPromptBuilder<'a> {out.push_str("\n```\n\n");}- out.push_str("## Ghidrust skill (verbatim — the authoritative catalog)\n\n");- out.push_str(self.skill_md);+ if self.skill_md.trim().is_empty() {+ out.push_str(+ "## Ghidrust skill\n\n\+ The authoritative catalog is on disk at `.grok/skills/ghidrust/SKILL.md` \+ (loaded by Grok Build on session start). Read it before calling analyzers \+ or claiming decompile capabilities.\n",+ );+ } else {+ out.push_str("## Ghidrust skill (verbatim — the authoritative catalog)\n\n");+ out.push_str(self.skill_md);+ }out}diff --git a/crates/ghidrust-agent/src/tool_bridge.rs b/crates/ghidrust-agent/src/tool_bridge.rsindex 4504231..5a0d071 100644--- a/crates/ghidrust-agent/src/tool_bridge.rs+++ b/crates/ghidrust-agent/src/tool_bridge.rs@@ -1,55 +1,49 @@-//! 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**.+//! Tool bridge — wires the local `ghidrust mcp` server into Grok Build so the+//! agent can call every shipped Ghidrust tool.//!-//! 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.+//! On session start we:+//! 1. Resolve an absolute `ghidrust` binary that actually exists.+//! 2. Write project MCP configs Grok 0.2.x reads (`.mcp.json`, `.grok/mcp.json`,+//! and `[mcp_servers.ghidrust]` in `.grok/config.toml`).+//! 3. Best-effort `grok mcp add --scope project` so the CLI registry matches.use serde_json::json;use std::fs;use std::io;use std::path::{Path, PathBuf};+use std::process::Command;-/// 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`).+/// Ensure project-local Grok MCP config points at `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"]-/// }-/// }-/// }-/// ```+/// Writes all shapes Grok Build discovers today:+/// - `<project>/.mcp.json` (doctor / Cursor-compatible)+/// - `<project>/.grok/mcp.json` (legacy helper)+/// - `<project>/.grok/config.toml` `[mcp_servers.ghidrust]` (native project scope)+/// Absolute path suitable for MCP config / shell spawn (no `\\?\` long-path prefix).+fn mcp_bin_string(ghidrust_bin: &Path) -> String {+ let bin = ghidrust_bin+ .canonicalize()+ .unwrap_or_else(|_| ghidrust_bin.to_path_buf());+ let mut s = bin.to_string_lossy().to_string();+ // Windows canonicalize() prefixes `\\?\`; Grok/JSON configs should not use that.+ if let Some(rest) = s.strip_prefix(r"\\?\") {+ s = rest.to_string();+ } else if let Some(rest) = s.strip_prefix("//?/") {+ s = rest.to_string();+ }+ s.replace('\\', "/")+}+pub fn write_project_mcp_config(project_root: &Path, ghidrust_bin: &Path) -> io::Result<PathBuf> {+ let bin_str = mcp_bin_string(ghidrust_bin);+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(),+ "command": bin_str,"args": ["mcp"]}}@@ -57,26 +51,147 @@ pub fn write_project_mcp_config(project_root: &Path, ghidrust_bin: &Path) -> io: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) {+ // Root `.mcp.json` — what `grok mcp doctor` lists as a config source.+ let root_mcp = project_root.join(".mcp.json");+ write_if_changed(&root_mcp, &contents)?;++ // `.grok/mcp.json` — kept for older notes / tooling.+ let grok_mcp = grok_dir.join("mcp.json");+ write_if_changed(&grok_mcp, &contents)?;++ // Native project config.toml fragment (merge-safe: rewrite ghidrust block).+ write_project_config_toml(&grok_dir.join("config.toml"), ghidrust_bin)?;++ Ok(root_mcp)+}++fn write_if_changed(path: &Path, contents: &str) -> io::Result<()> {+ if let Ok(existing) = fs::read_to_string(path) {if existing.trim() == contents.trim() {- return Ok(mcp_path);+ return Ok(());}}- fs::write(&mcp_path, contents)?;- Ok(mcp_path)+ fs::write(path, contents)}-/// 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`).+fn write_project_config_toml(path: &Path, ghidrust_bin: &Path) -> io::Result<()> {+ let bin = mcp_bin_string(ghidrust_bin);+ let block = format!(+ "\n[mcp_servers.ghidrust]\n\+ command = \"{bin}\"\n\+ args = [\"mcp\"]\n\+ enabled = true\n\+ startup_timeout_sec = 30\n"+ );++ let mut body = if path.is_file() {+ fs::read_to_string(path)?+ } else {+ String::from("# Ghidrust-managed Grok project config\n")+ };++ if let Some(start) = body.find("[mcp_servers.ghidrust]") {+ let after = &body[start + 1..];+ let end = after+ .find("\n[")+ .map(|i| start + 1 + i)+ .unwrap_or(body.len());+ body.replace_range(start..end, block.trim_start());+ if !body.ends_with('\n') {+ body.push('\n');+ }+ } else {+ if !body.ends_with('\n') {+ body.push('\n');+ }+ body.push_str(block.trim_start());+ }+ write_if_changed(path, &body)+}++/// Best-effort: `grok mcp add --scope project ghidrust -- <bin> mcp`.///-/// 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`.+/// Failures are returned as `Err` strings for the GUI to log; the file writes+/// above are the source of truth if the CLI add fails.+pub fn register_mcp_with_grok_cli(+ grok_bin: &Path,+ project_root: &Path,+ ghidrust_bin: &Path,+) -> Result<(), String> {+ let bin = mcp_bin_string(ghidrust_bin);+ let status = Command::new(grok_bin)+ .args([+ "mcp",+ "add",+ "--scope",+ "project",+ "ghidrust",+ "--",+ ])+ .arg(&bin)+ .arg("mcp")+ .current_dir(project_root)+ .status()+ .map_err(|e| format!("grok mcp add spawn failed: {e}"))?;+ if status.success() {+ Ok(())+ } else {+ Err(format!(+ "grok mcp add exited with {}",+ status+ .code()+ .map(|c| c.to_string())+ .unwrap_or_else(|| "signal".into())+ ))+ }+}++/// Resolve the CLI binary that speaks `ghidrust mcp` (not the GUI).+pub fn resolve_ghidrust_cli_bin() -> Option<PathBuf> {+ let exe_name = if cfg!(windows) {+ "ghidrust.exe"+ } else {+ "ghidrust"+ };++ // 1. Sibling of the running GUI / CLI (same target/{debug,release} dir).+ if let Ok(exe) = std::env::current_exe() {+ if let Some(dir) = exe.parent() {+ let sibling = dir.join(exe_name);+ if sibling.is_file() {+ return Some(sibling);+ }+ }+ }++ // 2. PATH+ 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);+ }+ }+ }++ // 3. Common workspace locations relative to CWD.+ for rel in [+ "target/release",+ "target/debug",+ "../target/release",+ "../target/debug",+ ] {+ let candidate = PathBuf::from(rel).join(exe_name);+ if candidate.is_file() {+ return Some(candidate);+ }+ }+ None+}++/// Ensure `<project>/.grok/skills/ghidrust/SKILL.md` mirrors the workspace+/// `skill/SKILL.md`.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");@@ -95,7 +210,6 @@ pub fn write_project_skill(project_root: &Path, skill_source: &Path) -> io::Resu#[cfg(test)]mod tests {use super::*;- use std::path::PathBuf;fn tmp_project(tag: &str) -> PathBuf {let dir = std::env::temp_dir().join(format!(@@ -109,15 +223,28 @@ mod tests {}#[test]- fn writes_mcp_config() {+ fn writes_mcp_config_root_and_grok() {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")));+ assert!(out.ends_with(".mcp.json"));+ let root = fs::read_to_string(proj.join(".mcp.json")).unwrap();+ assert!(root.contains("mcpServers"));+ assert!(root.contains("ghidrust"));+ assert!(!root.contains("//?/"), "must not emit Windows long-path prefix");+ let grok = fs::read_to_string(proj.join(".grok").join("mcp.json")).unwrap();+ assert!(grok.contains("mcp"));+ let toml = fs::read_to_string(proj.join(".grok").join("config.toml")).unwrap();+ assert!(toml.contains("[mcp_servers.ghidrust]"));+ assert!(toml.contains("enabled = true"));+ }++ #[test]+ fn strips_windows_long_path_prefix() {+ assert_eq!(+ mcp_bin_string(Path::new(r"\\?\F:\Repos\Ghidrust\target\release\ghidrust.exe")),+ "F:/Repos/Ghidrust/target/release/ghidrust.exe"+ );}#[test]@@ -129,10 +256,7 @@ mod tests {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"- );+ assert_eq!(mtime_first, mtime_second);}#[test]@@ -143,9 +267,6 @@ mod tests {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]diff --git a/crates/ghidrust-cli/Cargo.toml b/crates/ghidrust-cli/Cargo.tomlindex ca0b5c2..86048a4 100644--- a/crates/ghidrust-cli/Cargo.toml+++ b/crates/ghidrust-cli/Cargo.toml@@ -12,6 +12,8 @@ path = "src/main.rs"[dependencies]ghidrust-core = { workspace = true, features = ["gpu"] }ghidrust-decomp = { workspace = true, features = ["gpu"] }+ghidrust-il2cpp = { workspace = true }+ghidrust-unity-inventory = { workspace = true }ghidrust-types = { workspace = true }serde = { version = "1", features = ["derive"] }serde_json = "1"diff --git a/crates/ghidrust-cli/src/main.rs b/crates/ghidrust-cli/src/main.rsindex f4d4a11..88f4a3d 100644--- a/crates/ghidrust-cli/src/main.rs+++ b/crates/ghidrust-cli/src/main.rs@@ -1,13 +1,19 @@//! Ghidrust CLI + stdio MCP/agent tool surface over ghidrust-core.use ghidrust_core::{- 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,+ analyzer_catalog, analyze_path, collect_strings_bytes, collect_strings_opts,+ disassemble_range, disassemble_range_opts, filter_imports, load_path, load_path_opts,+ 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, write_json_no_bom,+ xrefs_from, xrefs_to, xrefs_to_import, xrefs_to_string_filter, AnalysisBundle, BulkScanMode,+ Program, Project, StringCollectOpts, StringMatchMode, ANALYZER_NAMES,};use ghidrust_decomp::decompile_entry;+use ghidrust_il2cpp::{+ classify_at, correlate, filter_entries, find_resolve_stubs, follow_stub_target,+ is_resolve_stub_va, resolve_icalls_path, stub_matches_filter, to_script_json, Il2CppMetadata,+};+use ghidrust_unity_inventory::inventory_path;use serde::Serialize;use serde_json::{json, Value};use std::env;@@ -32,6 +38,7 @@ fn main() -> ExitCode {}"load" => cmd_load(&args[1..], json_mode),"disasm" | "disassemble" => cmd_disasm(&args[1..], json_mode),+ "bytes" | "dump" => cmd_bytes(&args[1..], json_mode),"rtti" => cmd_rtti(&args[1..], json_mode),"analyzers" => cmd_analyzers(json_mode),"analyze" => cmd_analyze(&args[1..], json_mode),@@ -39,6 +46,8 @@ fn main() -> ExitCode {"xrefs" => cmd_xrefs(&args[1..], json_mode),"imports" => cmd_imports(&args[1..], json_mode),"function-at" => cmd_function_at(&args[1..], json_mode),+ "il2cpp" => cmd_il2cpp(&args[1..], json_mode),+ "unity-inventory" => cmd_unity_inventory(&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),@@ -65,17 +74,26 @@ fn print_help() {eprintln!("ghidrust — AI-native reverse-engineering (CodeBrowser headless)\n\n\Usage:\n\- ghidrust load <path> [--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 load <path> [--out FILE] [--json]\n\+ ghidrust disasm <path> [--addr <hex>] [--count N] [--skip-bad] [--out FILE] [--json]\n\+ ghidrust bytes <path> --addr HEX [--count N] [--out FILE] [--json]\n\+ ghidrust strings <path> [--raw] [--encoding ascii|utf16|all] [--filter SUB]\n\+ [--match substr|token|whole|glob] [--min N] [--limit N] [--out FILE] [--json]\n\+ ghidrust xrefs <path> (--to HEX | --from HEX | --string FILTER | --import NAME)\n\+ [--skip-stubs] [--classify] [--out FILE] [--json]\n\ghidrust imports <path> [--dll NAME] [--name NAME] [--json]\n\ghidrust function-at <path> --addr HEX [--json]\n\+ ghidrust il2cpp meta <metadata.dat> [--filter SUB] [--out FILE] [--json]\n\+ ghidrust il2cpp map --binary <il2cpp> --meta <metadata.dat> [--filter SUB] [--script-json] [--out FILE] [--json]\n\+ ghidrust il2cpp stubs --binary <il2cpp> [--filter SUB] [--max N] [--out FILE] [--json]\n\+ ghidrust il2cpp icalls --binary <engine.dll> [--filter SUB] [--out FILE] [--json]\n\+ ghidrust unity-inventory <game-dir> [--out FILE] [--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] [--verbose] [--json]\n\+ ghidrust decompile <path> [--addr HEX] [--count N] [--stage0|--stage05|--stage1]\n\+ [--follow-stub] [--verbose] [--out FILE] [--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\@@ -354,10 +372,39 @@ fn path_arg(args: &[String]) -> Result<PathBuf, String> {}fn cmd_load(args: &[String], json: bool) -> ExitCode {- match path_arg(args).and_then(|p| load_path(&p).map_err(|e| e.to_string())) {+ let path = match path_arg(args) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("{e}");+ return ExitCode::from(2);+ }+ };+ let mut out_path: Option<PathBuf> = None;+ let mut i = 1;+ while i < args.len() {+ match args[i].as_str() {+ "--out" if i + 1 < args.len() => {+ out_path = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }+ _ => i += 1,+ }+ }+ match load_path(&path) {Ok(prog) => {- emit_load(&prog, json);- ExitCode::SUCCESS+ let v = json!({+ "name": prog.name,+ "format": prog.format,+ "image_base": format!("{:#x}", prog.image_base),+ "entry": prog.entry.map(|e| format!("{e:#x}")),+ "sections": prog.sections.iter().map(|s| json!({+ "name": s.name,+ "va": format!("{:#x}", s.va),+ "virtual_size": s.virtual_size,+ "raw_size": s.raw_size,+ })).collect::<Vec<_>>(),+ });+ emit_result(&v, json, out_path.as_deref(), || print_program_summary(&prog))}Err(e) => {eprintln!("error: {e}");@@ -366,35 +413,19 @@ fn cmd_load(args: &[String], json: bool) -> ExitCode {}}-fn emit_load(prog: &Program, json: bool) {- if json {- let v = json!({- "name": prog.name,- "format": prog.format,- "image_base": format!("{:#x}", prog.image_base),- "entry": prog.entry.map(|e| format!("{e:#x}")),- "sections": prog.sections.iter().map(|s| json!({- "name": s.name,- "va": format!("{:#x}", s.va),- "virtual_size": s.virtual_size,- "raw_size": s.raw_size,- })).collect::<Vec<_>>(),- });- println!("{}", serde_json::to_string_pretty(&v).unwrap());- } else {- println!("name: {}", prog.name);- println!("format: {}", prog.format);- println!("base: {:#x}", prog.image_base);- if let Some(e) = prog.entry {- println!("entry: {e:#x}");- }- println!("sections:");- for s in &prog.sections {- println!(- " {:8} va={:#x} vsize={:#x} raw={:#x}",- s.name, s.va, s.virtual_size, s.raw_size- );- }+fn print_program_summary(prog: &Program) {+ println!("name: {}", prog.name);+ println!("format: {}", prog.format);+ println!("base: {:#x}", prog.image_base);+ if let Some(e) = prog.entry {+ println!("entry: {e:#x}");+ }+ println!("sections:");+ for s in &prog.sections {+ println!(+ " {:8} va={:#x} vsize={:#x} raw={:#x}",+ s.name, s.va, s.virtual_size, s.raw_size+ );}}@@ -408,6 +439,32 @@ fn emit_json<T: Serialize>(value: &T) {let _ = writeln!(out);}+fn emit_json_to_path<T: Serialize>(path: &Path, value: &T) -> bool {+ if let Err(e) = write_json_no_bom(path, value) {+ eprintln!("error writing {}: {e}", path.display());+ return false;+ }+ true+}++fn emit_result<T: Serialize>(value: &T, json: bool, out_path: Option<&Path>, text: impl FnOnce()) -> ExitCode {+ if let Some(p) = out_path {+ if !emit_json_to_path(p, value) {+ return ExitCode::FAILURE;+ }+ if !json {+ eprintln!("wrote {}", p.display());+ }+ return ExitCode::SUCCESS;+ }+ if json {+ emit_json(value);+ } else {+ text();+ }+ ExitCode::SUCCESS+}+fn cmd_disasm(args: &[String], json: bool) -> ExitCode {let path = match path_arg(args) {Ok(p) => p,@@ -419,6 +476,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 out_path: Option<PathBuf> = None;let mut i = 1;while i < args.len() {match args[i].as_str() {@@ -434,6 +492,10 @@ fn cmd_disasm(args: &[String], json: bool) -> ExitCode {skip_bad = true;i += 1;}+ "--out" if i + 1 < args.len() => {+ out_path = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }_ => i += 1,}}@@ -441,16 +503,11 @@ fn cmd_disasm(args: &[String], json: bool) -> ExitCode {Ok(prog) => {let start = addr.or(prog.entry).unwrap_or(prog.image_base);match disassemble_range_opts(&prog, start, count, skip_bad) {- Ok(listing) => {- if json {- emit_json(&listing);- } else {- for insn in &listing {- println!("{}", insn.text());- }+ Ok(listing) => emit_result(&listing, json, out_path.as_deref(), || {+ for insn in &listing {+ println!("{}", insn.text());}- ExitCode::SUCCESS- }+ }),Err(e) => {eprintln!("error: {e}");ExitCode::FAILURE@@ -464,6 +521,90 @@ fn cmd_disasm(args: &[String], json: bool) -> ExitCode {}}+fn cmd_bytes(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 count: usize = 64;+ let mut out_path: Option<PathBuf> = 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;+ }+ "--count" if i + 1 < args.len() => {+ count = args[i + 1].parse().unwrap_or(64).clamp(1, 1_048_576);+ i += 2;+ }+ "--out" if i + 1 < args.len() => {+ out_path = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }+ _ => i += 1,+ }+ }+ let Some(addr) = addr else {+ eprintln!("usage: ghidrust bytes <path> --addr HEX [--count N] [--out FILE] [--json]");+ return ExitCode::from(2);+ };+ match load_path(&path) {+ Ok(prog) => match prog.read_va(addr, count) {+ Some(bytes) => {+ let hex: String = bytes+ .iter()+ .map(|b| format!("{b:02x}"))+ .collect::<Vec<_>>()+ .join(" ");+ let payload = json!({+ "addr": format!("{addr:#x}"),+ "count": bytes.len(),+ "hex": hex,+ "bytes": bytes,+ });+ emit_result(&payload, json, out_path.as_deref(), || {+ // 16-byte rows: hex + ASCII+ let mut off = 0usize;+ while off < bytes.len() {+ let row = &bytes[off..(off + 16).min(bytes.len())];+ let hex_row: String = row+ .iter()+ .map(|b| format!("{b:02x}"))+ .collect::<Vec<_>>()+ .join(" ");+ let ascii: String = row+ .iter()+ .map(|&b| {+ if (0x20..=0x7e).contains(&b) {+ b as char+ } else {+ '.'+ }+ })+ .collect();+ println!("{:#x}: {:<47} {}", addr + off as u64, hex_row, ascii);+ off += 16;+ }+ })+ }+ None => {+ eprintln!("error: address {addr:#x} not mapped or unreadable");+ ExitCode::FAILURE+ }+ },+ Err(e) => {+ eprintln!("error: {e}");+ ExitCode::FAILURE+ }+ }+}+fn cmd_strings(args: &[String], json: bool) -> ExitCode {let path = match path_arg(args) {Ok(p) => p,@@ -475,37 +616,580 @@ fn cmd_strings(args: &[String], json: bool) -> ExitCode {let mut encoding = "all".to_string();let mut filter: Option<String> = None;let mut min_len: usize = 4;+ let mut match_mode = StringMatchMode::Substr;+ let mut limit: Option<usize> = None;+ let mut raw = false;+ let mut out_path: Option<PathBuf> = None;+ 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;+ }+ "--match" if i + 1 < args.len() => {+ match StringMatchMode::parse(&args[i + 1]) {+ Ok(m) => match_mode = m,+ Err(e) => {+ eprintln!("{e}");+ return ExitCode::from(2);+ }+ }+ i += 2;+ }+ "--min" if i + 1 < args.len() => {+ min_len = args[i + 1].parse().unwrap_or(4);+ i += 2;+ }+ "--limit" if i + 1 < args.len() => {+ limit = args[i + 1].parse().ok();+ i += 2;+ }+ "--out" if i + 1 < args.len() => {+ out_path = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }+ "--raw" => {+ raw = true;+ i += 1;+ }+ _ => i += 1,+ }+ }+ // Auto-glob when wildcards present and user left default substr.+ if matches!(match_mode, StringMatchMode::Substr) {+ if let Some(pat) = &filter {+ if pat.contains('*') || pat.contains('?') {+ match_mode = StringMatchMode::Glob;+ }+ }+ }+ let opts = StringCollectOpts {+ encoding: encoding.clone(),+ min_len,+ filter: filter.clone(),+ match_mode,+ limit,+ };+ let strings = if raw {+ match std::fs::read(&path) {+ Ok(bytes) => collect_strings_bytes(&bytes, 0, &opts),+ Err(e) => {+ eprintln!("error: {e}");+ return ExitCode::FAILURE;+ }+ }+ } else {+ load_path_opts(&path, true).and_then(|prog| collect_strings_opts(&prog, &opts))+ };+ match strings {+ Ok(strings) => emit_result(&strings, json, out_path.as_deref(), || {+ for s in &strings {+ println!("{:#x}\t{}\t{}", s.va, s.encoding, s.value);+ }+ }),+ 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 skip_stubs = false;+ let mut classify = false;+ let mut out_path: Option<PathBuf> = 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;+ }+ "--skip-stubs" => {+ skip_stubs = true;+ i += 1;+ }+ "--classify" => {+ classify = true;+ i += 1;+ }+ "--out" if i + 1 < args.len() => {+ out_path = Some(PathBuf::from(&args[i + 1]));+ 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) [--skip-stubs] [--classify] [--out FILE] [--json]"+ );+ return ExitCode::from(2);+ }+ match load_path(&path) {+ Ok(prog) => {+ let mut 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 skip_stubs {+ refs.retain(|r| !is_resolve_stub_va(&prog, r.from));+ }+ let rows: Vec<_> = refs+ .iter()+ .map(|r| {+ let stub = if classify {+ classify_at(&prog, r.from)+ } else {+ None+ };+ let kind = if stub.is_some() {+ "resolve_stub"+ } else {+ r.kind+ };+ let mut preview = r.preview.clone();+ if let Some(s) = stub {+ if let Some(name) = s.icall_name {+ preview = format!("{preview} ; il2cpp resolve {name}");+ }+ }+ json!({+ "from": format!("{:#x}", r.from),+ "to": format!("{:#x}", r.to),+ "kind": kind,+ "preview": preview,+ })+ })+ .collect();+ emit_result(&rows, json, out_path.as_deref(), || {+ for r in &rows {+ println!(+ "{} -> {} [{}] {}",+ r["from"].as_str().unwrap_or("?"),+ r["to"].as_str().unwrap_or("?"),+ r["kind"].as_str().unwrap_or("?"),+ r["preview"].as_str().unwrap_or("")+ );+ }+ })+ }+ Err(e) => {+ eprintln!("error: {e}");+ ExitCode::FAILURE+ }+ }+}++fn cmd_il2cpp(args: &[String], json: bool) -> ExitCode {+ let sub = match args.first().map(|s| s.as_str()) {+ Some(s) => s,+ None => {+ eprintln!("usage: ghidrust il2cpp meta|map|stubs|icalls ...");+ return ExitCode::from(2);+ }+ };+ match sub {+ "meta" => cmd_il2cpp_meta(&args[1..], json),+ "map" => cmd_il2cpp_map(&args[1..], json),+ "stubs" => cmd_il2cpp_stubs(&args[1..], json),+ "icalls" => cmd_il2cpp_icalls(&args[1..], json),+ other => {+ eprintln!("unknown il2cpp subcommand: {other}");+ ExitCode::from(2)+ }+ }+}++fn cmd_il2cpp_icalls(args: &[String], json: bool) -> ExitCode {+ let mut binary: Option<PathBuf> = None;+ let mut filter: Option<String> = None;+ let mut out_path: Option<PathBuf> = None;+ let mut i = 0;+ while i < args.len() {+ match args[i].as_str() {+ "--binary" if i + 1 < args.len() => {+ binary = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }+ "--filter" if i + 1 < args.len() => {+ filter = Some(args[i + 1].clone());+ i += 2;+ }+ "--out" if i + 1 < args.len() => {+ out_path = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }+ other if binary.is_none() && !other.starts_with('-') => {+ binary = Some(PathBuf::from(other));+ i += 1;+ }+ _ => i += 1,+ }+ }+ let Some(binary) = binary else {+ eprintln!(+ "usage: ghidrust il2cpp icalls --binary <engine.dll> [--filter SUB] [--out FILE] [--json]"+ );+ return ExitCode::from(2);+ };+ match resolve_icalls_path(&binary) {+ Ok(report) => {+ let payload = if let Some(f) = &filter {+ let hits = filter_entries(&report, f);+ json!({+ "filter": f,+ "table_count": report.tables.len(),+ "hit_count": hits.len(),+ "hits": hits.iter().map(|(ti, e)| json!({+ "table_index": ti,+ "index": e.index,+ "name": e.name,+ "name_string_va": format!("{:#x}", e.name_string_va),+ "fn_va": format!("{:#x}", e.fn_va),+ "fn_rva": format!("{:#x}", e.fn_rva),+ })).collect::<Vec<_>>(),+ "tables": report.tables.iter().map(|t| json!({+ "name_va": format!("{:#x}", t.name_va),+ "fn_va": format!("{:#x}", t.fn_va),+ "count": t.count,+ "layout": t.layout,+ "confidence": t.confidence,+ })).collect::<Vec<_>>(),+ })+ } else {+ json!({+ "table_count": report.tables.len(),+ "tables": report.tables.iter().map(|t| json!({+ "name_va": format!("{:#x}", t.name_va),+ "fn_va": format!("{:#x}", t.fn_va),+ "count": t.count,+ "layout": t.layout,+ "confidence": t.confidence,+ "entries": t.entries.iter().take(64).map(|e| json!({+ "index": e.index,+ "name": e.name,+ "name_string_va": format!("{:#x}", e.name_string_va),+ "fn_va": format!("{:#x}", e.fn_va),+ "fn_rva": format!("{:#x}", e.fn_rva),+ })).collect::<Vec<_>>(),+ })).collect::<Vec<_>>(),+ })+ };+ emit_result(&payload, json, out_path.as_deref(), || {+ println!(+ "icall tables: {} (engine {})",+ report.tables.len(),+ binary.display()+ );+ for t in report.tables.iter().take(8) {+ println!(+ " names {:#x} fns {:#x} count={} conf={:.2} {:?}",+ t.name_va, t.fn_va, t.count, t.confidence, t.layout+ );+ }+ if let Some(f) = &filter {+ let hits = filter_entries(&report, f);+ println!("filter {:?} hits: {}", f, hits.len());+ for (_ti, e) in hits.iter().take(40) {+ println!(+ " [{}] RVA {:#x} {}",+ e.index, e.fn_rva, e.name+ );+ }+ }+ })+ }+ Err(e) => {+ eprintln!("error: {e}");+ ExitCode::FAILURE+ }+ }+}++fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {+ let path = match args.first() {+ Some(p) => PathBuf::from(p),+ None => {+ eprintln!("usage: ghidrust il2cpp meta <metadata.dat> [--filter SUB] [--out FILE] [--json]");+ return ExitCode::from(2);+ }+ };+ let mut filter: Option<String> = None;+ let mut out_path: Option<PathBuf> = None;let mut i = 1;while i < args.len() {match args[i].as_str() {- "--encoding" if i + 1 < args.len() => {- encoding = args[i + 1].clone();+ "--filter" if i + 1 < args.len() => {+ filter = Some(args[i + 1].clone());+ i += 2;+ }+ "--out" if i + 1 < args.len() => {+ out_path = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }+ _ => i += 1,+ }+ }+ match Il2CppMetadata::load_path(&path) {+ Ok(meta) => {+ let types: Vec<_> = match &filter {+ Some(f) => meta.filter_types(f).into_iter().cloned().collect(),+ None => meta.types.clone(),+ };+ let methods: Vec<_> = match &filter {+ Some(f) => meta+ .filter_methods(f)+ .into_iter()+ .map(|m| {+ json!({+ "index": m.index,+ "name": m.name,+ "full_name": meta.method_full_name(m),+ "token": m.token,+ })+ })+ .collect(),+ None => meta+ .methods+ .iter()+ .map(|m| {+ json!({+ "index": m.index,+ "name": m.name,+ "full_name": meta.method_full_name(m),+ "token": m.token,+ })+ })+ .collect(),+ };+ let report = json!({+ "version": meta.header.version,+ "dialect": meta.header.dialect,+ "type_count": meta.types.len(),+ "method_count": meta.methods.len(),+ "image_count": meta.images.len(),+ "types": types.iter().map(|t| json!({+ "index": t.index,+ "full_name": t.full_name(),+ "method_count": t.method_count,+ "token": t.token,+ })).collect::<Vec<_>>(),+ "methods": methods,+ });+ emit_result(&report, json, out_path.as_deref(), || {+ println!(+ "IL2CPP metadata v{} {:?} — {} types, {} methods, {} images",+ meta.header.version,+ meta.header.dialect,+ meta.types.len(),+ meta.methods.len(),+ meta.images.len()+ );+ for t in types.iter().take(50) {+ println!(" type {}", t.full_name());+ }+ if types.len() > 50 {+ println!(" ... {} more types", types.len() - 50);+ }+ })+ }+ Err(e) => {+ if let Some(payload) = e.to_structured_json() {+ if json {+ return emit_result(&payload, true, out_path.as_deref(), || {});+ }+ eprintln!("{}", serde_json::to_string_pretty(&payload).unwrap_or_else(|_| e.to_string()));+ } else {+ eprintln!("error: {e}");+ }+ ExitCode::FAILURE+ }+ }+}++fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {+ let mut binary: Option<PathBuf> = None;+ let mut meta_path: Option<PathBuf> = None;+ let mut filter: Option<String> = None;+ let mut out_path: Option<PathBuf> = None;+ let mut script_json = false;+ let mut i = 0;+ while i < args.len() {+ match args[i].as_str() {+ "--binary" if i + 1 < args.len() => {+ binary = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }+ "--meta" if i + 1 < args.len() => {+ meta_path = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }+ "--filter" if i + 1 < args.len() => {+ filter = Some(args[i + 1].clone());+ i += 2;+ }+ "--out" if i + 1 < args.len() => {+ out_path = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }+ "--script-json" => {+ script_json = true;+ i += 1;+ }+ _ => i += 1,+ }+ }+ let (Some(binary), Some(meta_path)) = (binary, meta_path) else {+ eprintln!(+ "usage: ghidrust il2cpp map --binary <il2cpp> --meta <metadata.dat> [--filter SUB] [--script-json] [--out FILE] [--json]"+ );+ return ExitCode::from(2);+ };+ let prog = match load_path(&binary) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("error: {e}");+ return ExitCode::FAILURE;+ }+ };+ let meta = match Il2CppMetadata::load_path(&meta_path) {+ Ok(m) => m,+ Err(e) => {+ eprintln!("error: {e}");+ return ExitCode::FAILURE;+ }+ };+ match correlate(&prog, &meta) {+ Ok(mut map) => {+ if let Some(f) = &filter {+ let fl = f.to_ascii_lowercase();+ map.entries+ .retain(|e| e.full_name.to_ascii_lowercase().contains(&fl));+ }+ if script_json {+ let script = to_script_json(&map);+ return emit_result(&script, json, out_path.as_deref(), || {+ println!(+ "script.json methods with addresses: {}",+ script.script_method.len()+ );+ });+ }+ emit_result(&map, json, out_path.as_deref(), || {+ println!(+ "method map: {} entries, pointer_count={:?}",+ map.entries.len(),+ map.method_pointer_count+ );+ for n in &map.notes {+ println!(" note: {n}");+ }+ for e in map.entries.iter().take(40) {+ match e.rva {+ Some(rva) => println!(" {:#x} {}", rva, e.full_name),+ None => println!(" (unmapped) {}", e.full_name),+ }+ }+ })+ }+ Err(e) => {+ eprintln!("error: {e}");+ ExitCode::FAILURE+ }+ }+}++fn cmd_il2cpp_stubs(args: &[String], json: bool) -> ExitCode {+ let mut binary: Option<PathBuf> = None;+ let mut filter: Option<String> = None;+ let mut out_path: Option<PathBuf> = None;+ let mut max_scan: usize = 250_000;+ let mut i = 0;+ while i < args.len() {+ match args[i].as_str() {+ "--binary" if i + 1 < args.len() => {+ binary = Some(PathBuf::from(&args[i + 1]));i += 2;}- "--filter" | "--contains" if i + 1 < args.len() => {+ "--filter" 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);+ "--out" if i + 1 < args.len() => {+ out_path = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }+ "--max" if i + 1 < args.len() => {+ max_scan = args[i + 1].parse().unwrap_or(max_scan);i += 2;}+ other if binary.is_none() && !other.starts_with('-') => {+ binary = Some(PathBuf::from(other));+ i += 1;+ }_ => 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);- }+ let Some(binary) = binary else {+ eprintln!(+ "usage: ghidrust il2cpp stubs --binary <il2cpp> [--filter SUB] [--max N] [--out FILE] [--json]"+ );+ return ExitCode::from(2);+ };+ match load_path(&binary) {+ Ok(prog) => {+ let mut stubs = find_resolve_stubs(&prog, max_scan);+ if let Some(f) = &filter {+ stubs.retain(|s| stub_matches_filter(&prog, s, f));}- ExitCode::SUCCESS+ emit_result(&stubs, json, out_path.as_deref(), || {+ println!("resolve stubs: {}", stubs.len());+ for s in stubs.iter().take(80) {+ println!(+ " {:#x} {}",+ s.entry,+ s.icall_name.as_deref().unwrap_or("(unnamed)")+ );+ }+ })}Err(e) => {eprintln!("error: {e}");@@ -514,81 +1198,41 @@ fn cmd_strings(args: &[String], json: bool) -> ExitCode {}}-fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {- let path = match path_arg(args) {- Ok(p) => p,- Err(e) => {- eprintln!("{e}");+fn cmd_unity_inventory(args: &[String], json: bool) -> ExitCode {+ let path = match args.first() {+ Some(p) => PathBuf::from(p),+ None => {+ eprintln!("usage: ghidrust unity-inventory <game-dir> [--out FILE] [--json]");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 out_path: Option<PathBuf> = 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());+ "--out" if i + 1 < args.len() => {+ out_path = Some(PathBuf::from(&args[i + 1]));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);- }+ match inventory_path(&path) {+ Ok(inv) => emit_result(&inv, json, out_path.as_deref(), || {+ println!("unity-inventory schema={} root={}", inv.schema_version, inv.root);+ println!(+ " verdict={:?} confidence={:?} il2cpp={} xr_stock={} xr_pkg={} external={}",+ inv.verdict,+ inv.confidence,+ inv.engine.il2cpp,+ inv.xr_stock_modules.len(),+ inv.xr_packages.len(),+ inv.external_vr_indicators.len()+ );+ for n in &inv.notes {+ println!(" note: {n}");}- ExitCode::SUCCESS- }+ }),Err(e) => {eprintln!("error: {e}");ExitCode::FAILURE@@ -1219,7 +1863,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] [--verbose] [--json]"+ "usage: ghidrust decompile <path> [--addr HEX] [--count N] [--stage0|--stage05|--stage1] [--follow-stub] [--verbose] [--out FILE] [--json]");return ExitCode::from(2);}@@ -1233,6 +1877,8 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {let mut stage0 = false;let mut stage1 = true;let mut verbose = false;+ let mut follow_stub = false;+ let mut out_path: Option<PathBuf> = None;let mut i = 1;while i < args.len() {match args[i].as_str() {@@ -1261,17 +1907,60 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {stage0 = false;i += 1;}+ "--follow-stub" => {+ follow_stub = true;+ i += 1;+ }"--verbose" | "-v" => {verbose = true;i += 1;}+ "--out" if i + 1 < args.len() => {+ out_path = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }_ => i += 1,}}let _ = stage0; // suppressed; retained for future gatingmatch load_path(&path) {Ok(prog) => {- let va = addr.unwrap_or_else(|| prog.entry.unwrap_or(prog.image_base));+ let mut va = addr.unwrap_or_else(|| prog.entry.unwrap_or(prog.image_base));+ let mut follow_meta: Option<Value> = None;+ if follow_stub {+ if let Some(stub) = classify_at(&prog, va) {+ if let Some(target) = follow_stub_target(&prog, &stub) {+ if verbose {+ eprintln!(+ "follow-stub: {:#x} -> {:#x} ({})",+ va,+ target,+ stub.icall_name.as_deref().unwrap_or("resolve")+ );+ }+ follow_meta = Some(json!({+ "status": "resolved",+ "from": format!("{va:#x}"),+ "to": format!("{target:#x}"),+ "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),+ "icall_name": stub.icall_name,+ }));+ va = target;+ } else {+ let note = "resolve slot empty or unmapped — filled at runtime";+ if verbose || !json {+ eprintln!("follow-stub: {va:#x} runtime_unresolved ({note})");+ }+ follow_meta = Some(json!({+ "status": "runtime_unresolved",+ "from": format!("{va:#x}"),+ "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),+ "icall_name": stub.icall_name,+ "note": note,+ }));+ }+ }+ }if stage1 {// Default to Windows x64 for PE targets, SysV otherwise.let conv = if prog.format.to_ascii_lowercase().contains("pe") {@@ -1281,20 +1970,21 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {};match ghidrust_decomp::decompile_stage1_at(&prog, va, count, conv) {Ok((d, s1)) => {- if json {- let obj = json!({- "decompile": d,- "stage1": {- "loops": s1.structure.loops.len(),- "phis": s1.ssa.phi_count(),- "locals": s1.types.locals.len(),- "params": s1.types.params.len(),- "lift_ratio": s1.coverage.ratio(),- "total_ops": s1.coverage.total_ops,- }- });- emit_json(&obj);- } else {+ let mut obj = json!({+ "decompile": d,+ "stage1": {+ "loops": s1.structure.loops.len(),+ "phis": s1.ssa.phi_count(),+ "locals": s1.types.locals.len(),+ "params": s1.types.params.len(),+ "lift_ratio": s1.coverage.ratio(),+ "total_ops": s1.coverage.total_ops,+ }+ });+ if let Some(fm) = &follow_meta {+ obj.as_object_mut().unwrap().insert("follow_stub".into(), fm.clone());+ }+ return emit_result(&obj, json, out_path.as_deref(), || {print!("{}", d.pseudo_c);if verbose {eprintln!(@@ -1308,8 +1998,7 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {s1.coverage.ratio() * 100.0);}- }- return ExitCode::SUCCESS;+ });}Err(e) => {eprintln!("decompile-stage1 error: {e}");@@ -1320,18 +2009,19 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {if stage05 {match ghidrust_decomp::decompile_ir_at(&prog, va, count) {Ok((d, cov)) => {- if json {- let obj = json!({- "decompile": d,- "lift_coverage": {- "total_ops": cov.total_ops,- "unimplemented_ops": cov.unimplemented_ops,- "source_instructions": cov.source_instructions,- "ratio": cov.ratio(),- }- });- emit_json(&obj);- } else {+ let mut obj = json!({+ "decompile": d,+ "lift_coverage": {+ "total_ops": cov.total_ops,+ "unimplemented_ops": cov.unimplemented_ops,+ "source_instructions": cov.source_instructions,+ "ratio": cov.ratio(),+ }+ });+ if let Some(fm) = &follow_meta {+ obj.as_object_mut().unwrap().insert("follow_stub".into(), fm.clone());+ }+ return emit_result(&obj, json, out_path.as_deref(), || {print!("{}", d.pseudo_c);if verbose {eprintln!(@@ -1345,8 +2035,7 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {d.line_count());}- }- ExitCode::SUCCESS+ });}Err(e) => {eprintln!("decompile-ir error: {e}");@@ -1356,9 +2045,11 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {} else {match ghidrust_decomp::decompile_at(&prog, va, count) {Ok(d) => {- if json {- emit_json(&d);- } else {+ let mut obj = json!({ "decompile": d });+ if let Some(fm) = &follow_meta {+ obj.as_object_mut().unwrap().insert("follow_stub".into(), fm.clone());+ }+ emit_result(&obj, json, out_path.as_deref(), || {print!("{}", d.pseudo_c);if verbose {eprintln!(@@ -1370,8 +2061,7 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {d.line_count());}- }- ExitCode::SUCCESS+ })}Err(e) => {eprintln!("decompile error: {e}");@@ -1897,7 +2587,7 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {serde_json::to_string_pretty(&bundle_json(&bundle)).unwrap());} else {- emit_load(&bundle.program, false);+ print_program_summary(&bundle.program);println!("--- disassembly ---");for insn in &bundle.listing {println!("{}", insn.text());@@ -1964,6 +2654,9 @@ fn parse_u64(s: &str) -> Result<u64, String> {struct ToolDef {name: &'static str,description: &'static str,+ /// MCP protocol field name is camelCase; serde default would emit `input_schema`+ /// and Grok's client then fails tools/list with "Unexpected response type".+ #[serde(rename = "inputSchema")]input_schema: Value,}@@ -2032,7 +2725,7 @@ fn tool_defs() -> Vec<ToolDef> {},ToolDef {name: "decompile",- description: "Decompile function to structured C. Defaults to Stage-1 (SSA + types + structure). Pass stage='stage0' or 'stage05' for oracle output.",+ description: "Decompile function to structured C. Defaults to Stage-1 (SSA + types + structure). Pass stage='stage0' or 'stage05' for oracle output. follow_stub follows IL2CPP resolve thunks when the slot target is mapped.",input_schema: json!({"type": "object","properties": {@@ -2043,6 +2736,10 @@ fn tool_defs() -> Vec<ToolDef> {"type": "string","enum": ["stage0", "stage05", "stage1"],"description": "Emit stage. Default 'stage1' — full SSA + types + structure."+ },+ "follow_stub": {+ "type": "boolean",+ "description": "If addr is an IL2CPP resolve stub, decompile the cached target when mapped"}},"required": ["path"]@@ -2071,14 +2768,17 @@ fn tool_defs() -> Vec<ToolDef> {},ToolDef {name: "list_strings",- description: "Scan ASCII and/or UTF-16LE strings; optional filter substring/glob",+ description: "Scan ASCII/UTF-16LE strings on PE/ELF or raw blob (raw:true). match=substr|token|whole|glob; optional limit.",input_schema: json!({"type": "object","properties": {"path": { "type": "string" },"encoding": { "type": "string", "enum": ["ascii", "utf16", "all"] },"filter": { "type": "string" },- "min": { "type": "integer" }+ "match": { "type": "string", "enum": ["substr", "token", "whole", "glob"] },+ "min": { "type": "integer" },+ "limit": { "type": "integer" },+ "raw": { "type": "boolean", "description": "Treat file as a byte blob (not PE/ELF)" }},"required": ["path"]}),@@ -2092,19 +2792,98 @@ fn tool_defs() -> Vec<ToolDef> {"path": { "type": "string" },"encoding": { "type": "string", "enum": ["ascii", "utf16", "all"] },"filter": { "type": "string" },- "min": { "type": "integer" }+ "match": { "type": "string", "enum": ["substr", "token", "whole", "glob"] },+ "min": { "type": "integer" },+ "limit": { "type": "integer" },+ "raw": { "type": "boolean" }+ },+ "required": ["path"]+ }),+ },+ ToolDef {+ name: "il2cpp_meta",+ description: "Parse IL2CPP global-metadata.dat → types/methods (v27/29/31). Fails closed if encrypted/obfuscated.",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string", "description": "Path to global-metadata.dat" },+ "filter": { "type": "string", "description": "Substring filter on type/method full names" }+ },+ "required": ["path"]+ }),+ },+ ToolDef {+ name: "il2cpp_map",+ description: "Correlate metadata methods with binary RVAs when CodeRegistration validates. Unproven RVAs are null.",+ input_schema: json!({+ "type": "object",+ "properties": {+ "binary": { "type": "string", "description": "IL2CPP binary (e.g. GameAssembly.dll)" },+ "meta": { "type": "string", "description": "Path to global-metadata.dat" },+ "filter": { "type": "string" }+ },+ "required": ["binary", "meta"]+ }),+ },+ ToolDef {+ name: "il2cpp_stubs",+ description: "List IL2CPP resolve stubs (LEA icall name → resolve → store slot → jmp reg). Filter matches parsed name or C-string at name_string_va.",+ input_schema: json!({+ "type": "object",+ "properties": {+ "binary": { "type": "string" },+ "filter": { "type": "string", "description": "Substring on icall name or name string" },+ "max": { "type": "integer", "description": "Max scan budget (default 250000)" }+ },+ "required": ["binary"]+ }),+ },+ ToolDef {+ name: "il2cpp_icalls",+ description: "Resolve Unity engine icall name‖fn pointer tables (index, name, fn RVA)",+ input_schema: json!({+ "type": "object",+ "properties": {+ "binary": { "type": "string", "description": "Engine PE (e.g. UnityPlayer.dll)" },+ "filter": { "type": "string", "description": "Substring on icall name" }+ },+ "required": ["binary"]+ }),+ },+ ToolDef {+ name: "read_bytes",+ description: "Raw bytes dump at a virtual address (hex + byte array)",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "addr": { "type": "string", "description": "VA in hex" },+ "count": { "type": "integer", "description": "Byte count (default 64)" }+ },+ "required": ["path", "addr"]+ }),+ },+ ToolDef {+ name: "unity_inventory",+ description: "Unity player install inventory (assemblies, plugins, metadata peek, XR-related fields)",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string", "description": "Player directory (exe + *_Data/)" }},"required": ["path"]}),},ToolDef {name: "get_xrefs_to",- description: "Cross-references to a VA (includes RIP-relative LEA/call/jmp)",+ description: "Cross-references to a VA (RIP LEA/call/jmp, address tables, and non-exec data qword pointers). Optional IL2CPP stub skip/classify.",input_schema: json!({"type": "object","properties": {"path": { "type": "string" },- "addr": { "type": "string" }+ "addr": { "type": "string" },+ "skip_stubs": { "type": "boolean", "description": "Omit xrefs whose from-VA is an IL2CPP resolve stub" },+ "classify": { "type": "boolean", "description": "Label resolve_stub kind when applicable" }},"required": ["path", "addr"]}),@@ -2282,12 +3061,175 @@ fn call_tool(params: &Value) -> Result<String, String> {.get("encoding").and_then(|e| e.as_str()).unwrap_or("all");- let filter = args.get("filter").and_then(|f| f.as_str());+ let filter = args.get("filter").and_then(|f| f.as_str()).map(|s| s.to_string());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())?;+ let limit = args.get("limit").and_then(|m| m.as_u64()).map(|n| n as usize);+ let raw = args.get("raw").and_then(|r| r.as_bool()).unwrap_or(false);+ let mut match_mode = args+ .get("match")+ .and_then(|m| m.as_str())+ .map(StringMatchMode::parse)+ .transpose()+ .map_err(|e| e.to_string())?+ .unwrap_or(StringMatchMode::Substr);+ if matches!(match_mode, StringMatchMode::Substr) {+ if let Some(pat) = &filter {+ if pat.contains('*') || pat.contains('?') {+ match_mode = StringMatchMode::Glob;+ }+ }+ }+ let opts = StringCollectOpts {+ encoding: encoding.into(),+ min_len,+ filter,+ match_mode,+ limit,+ };+ let strings = if raw {+ let bytes = std::fs::read(path).map_err(|e| e.to_string())?;+ collect_strings_bytes(&bytes, 0, &opts).map_err(|e| e.to_string())?+ } else {+ let prog = load_path_opts(path, true).map_err(|e| e.to_string())?;+ collect_strings_opts(&prog, &opts).map_err(|e| e.to_string())?+ };Ok(serde_json::to_string_pretty(&strings).unwrap())}+ "il2cpp_meta" => {+ 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());+ let meta = match Il2CppMetadata::load_path(path) {+ Ok(m) => m,+ Err(e) => {+ if let Some(payload) = e.to_structured_json() {+ return Err(serde_json::to_string_pretty(&payload).unwrap_or_else(|_| e.to_string()));+ }+ return Err(e.to_string());+ }+ };+ let types: Vec<_> = match filter {+ Some(f) => meta.filter_types(f).into_iter().map(|t| t.full_name()).collect(),+ None => meta.types.iter().map(|t| t.full_name()).collect(),+ };+ let methods: Vec<_> = match filter {+ Some(f) => meta+ .filter_methods(f)+ .into_iter()+ .map(|m| meta.method_full_name(m))+ .collect(),+ None => meta+ .methods+ .iter()+ .map(|m| meta.method_full_name(m))+ .collect(),+ };+ Ok(serde_json::to_string_pretty(&json!({+ "version": meta.header.version,+ "dialect": meta.header.dialect,+ "types": types,+ "methods": methods,+ }))+ .unwrap())+ }+ "il2cpp_map" => {+ let binary = args+ .get("binary")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.binary".to_string())?;+ let meta_path = args+ .get("meta")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.meta".to_string())?;+ let filter = args.get("filter").and_then(|f| f.as_str());+ let prog = load_path(binary).map_err(|e| e.to_string())?;+ let meta = Il2CppMetadata::load_path(meta_path).map_err(|e| e.to_string())?;+ let mut map = correlate(&prog, &meta).map_err(|e| e.to_string())?;+ if let Some(f) = filter {+ let fl = f.to_ascii_lowercase();+ map.entries+ .retain(|e| e.full_name.to_ascii_lowercase().contains(&fl));+ }+ Ok(serde_json::to_string_pretty(&map).unwrap())+ }+ "il2cpp_stubs" => {+ let binary = args+ .get("binary")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.binary".to_string())?;+ let filter = args.get("filter").and_then(|f| f.as_str());+ let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(250_000) as usize;+ let prog = load_path(binary).map_err(|e| e.to_string())?;+ let mut stubs = find_resolve_stubs(&prog, max);+ if let Some(f) = filter {+ stubs.retain(|s| stub_matches_filter(&prog, s, f));+ }+ Ok(serde_json::to_string_pretty(&stubs).unwrap())+ }+ "read_bytes" => {+ 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(64) as usize;+ let count = count.clamp(1, 1_048_576);+ let prog = load_path(path).map_err(|e| e.to_string())?;+ let va = parse_u64(addr)?;+ let bytes = prog+ .read_va(va, count)+ .ok_or_else(|| format!("address {va:#x} not mapped or unreadable"))?;+ let hex: String = bytes+ .iter()+ .map(|b| format!("{b:02x}"))+ .collect::<Vec<_>>()+ .join(" ");+ Ok(serde_json::to_string_pretty(&json!({+ "addr": format!("{va:#x}"),+ "count": bytes.len(),+ "hex": hex,+ "bytes": bytes,+ }))+ .unwrap())+ }+ "il2cpp_icalls" => {+ let binary = args+ .get("binary")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.binary".to_string())?;+ let filter = args.get("filter").and_then(|f| f.as_str());+ let report = resolve_icalls_path(binary).map_err(|e| e.to_string())?;+ if let Some(f) = filter {+ let hits = filter_entries(&report, f);+ Ok(serde_json::to_string_pretty(&json!({+ "filter": f,+ "table_count": report.tables.len(),+ "hits": hits.iter().map(|(ti, e)| json!({+ "table_index": ti,+ "index": e.index,+ "name": e.name,+ "name_string_va": format!("{:#x}", e.name_string_va),+ "fn_va": format!("{:#x}", e.fn_va),+ "fn_rva": format!("{:#x}", e.fn_rva),+ })).collect::<Vec<_>>(),+ })).unwrap())+ } else {+ Ok(serde_json::to_string_pretty(&report).unwrap())+ }+ }+ "unity_inventory" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let inv = inventory_path(path)?;+ Ok(serde_json::to_string_pretty(&inv).unwrap())+ }"get_xrefs_to" => {let path = args.get("path")@@ -2297,9 +3239,39 @@ fn call_tool(params: &Value) -> Result<String, String> {.get("addr").and_then(|a| a.as_str()).ok_or_else(|| "missing arguments.addr".to_string())?;+ let skip_stubs = args+ .get("skip_stubs")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ let classify = args+ .get("classify")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);let prog = load_path(path).map_err(|e| e.to_string())?;let va = parse_u64(addr)?;- let refs = xrefs_to(&prog, va, None);+ let mut refs = xrefs_to(&prog, va, None);+ if skip_stubs {+ refs.retain(|r| !is_resolve_stub_va(&prog, r.from));+ }+ if classify {+ let rows: Vec<_> = refs+ .iter()+ .map(|r| {+ let kind = if classify_at(&prog, r.from).is_some() {+ "resolve_stub"+ } else {+ r.kind+ };+ json!({+ "from": format!("{:#x}", r.from),+ "to": format!("{:#x}", r.to),+ "kind": kind,+ "preview": r.preview,+ })+ })+ .collect();+ return Ok(serde_json::to_string_pretty(&rows).unwrap());+ }Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())}"get_xrefs_from" => {@@ -2461,12 +3433,39 @@ fn call_tool(params: &Value) -> Result<String, String> {.get("stage").and_then(|s| s.as_str()).unwrap_or("stage1");+ let follow_stub = args+ .get("follow_stub")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);let prog = load_path(path).map_err(|e| e.to_string())?;- let va = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {+ let mut va = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {parse_u64(a)?} else {prog.entry.unwrap_or(prog.image_base)};+ let mut follow_meta: Option<Value> = None;+ if follow_stub {+ if let Some(stub) = classify_at(&prog, va) {+ if let Some(target) = follow_stub_target(&prog, &stub) {+ follow_meta = Some(json!({+ "status": "resolved",+ "from": format!("{va:#x}"),+ "to": format!("{target:#x}"),+ "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),+ "icall_name": stub.icall_name,+ }));+ va = target;+ } else {+ follow_meta = Some(json!({+ "status": "runtime_unresolved",+ "from": format!("{va:#x}"),+ "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),+ "icall_name": stub.icall_name,+ "note": "resolve slot empty or unmapped — filled at runtime",+ }));+ }+ }+ }let conv = if prog.format.to_ascii_lowercase().contains("pe") {ghidrust_types::CallConv::Windows} else {@@ -2476,7 +3475,7 @@ fn call_tool(params: &Value) -> Result<String, String> {"stage0" | "stage-0" => {let d =ghidrust_decomp::decompile_at(&prog, va, count).map_err(|e| e.to_string())?;- Ok(serde_json::to_string_pretty(&json!({+ let mut obj = json!({"stage": "0","name": d.name,"entry": format!("{:#x}", d.entry),@@ -2484,13 +3483,16 @@ fn call_tool(params: &Value) -> Result<String, String> {"edges": d.edges.len(),"insns": d.insn_count,"pseudo_c": d.pseudo_c,- }))- .unwrap())+ });+ if let Some(fm) = follow_meta {+ obj.as_object_mut().unwrap().insert("follow_stub".into(), fm);+ }+ Ok(serde_json::to_string_pretty(&obj).unwrap())}"stage05" | "stage-0.5" | "ir" => {let (d, cov) = ghidrust_decomp::decompile_ir_at(&prog, va, count).map_err(|e| e.to_string())?;- Ok(serde_json::to_string_pretty(&json!({+ let mut obj = json!({"stage": "0.5","name": d.name,"entry": format!("{:#x}", d.entry),@@ -2499,14 +3501,17 @@ fn call_tool(params: &Value) -> Result<String, String> {"insns": d.insn_count,"lift_ratio": cov.ratio(),"pseudo_c": d.pseudo_c,- }))- .unwrap())+ });+ if let Some(fm) = follow_meta {+ obj.as_object_mut().unwrap().insert("follow_stub".into(), fm);+ }+ Ok(serde_json::to_string_pretty(&obj).unwrap())}_ => {// Default (Phase F): Stage-1 full pipeline.let (d, s1) = ghidrust_decomp::decompile_stage1_at(&prog, va, count, conv).map_err(|e| e.to_string())?;- Ok(serde_json::to_string_pretty(&json!({+ let mut obj = json!({"stage": "1","name": d.name,"entry": format!("{:#x}", d.entry),@@ -2522,8 +3527,11 @@ fn call_tool(params: &Value) -> Result<String, String> {"return_type": s1.types.signature.return_type.c_style(),"prototype": s1.types.signature.to_prototype(),"pseudo_c": d.pseudo_c,- }))- .unwrap())+ });+ if let Some(fm) = follow_meta {+ obj.as_object_mut().unwrap().insert("follow_stub".into(), fm);+ }+ Ok(serde_json::to_string_pretty(&obj).unwrap())}}}diff --git a/crates/ghidrust-core/src/analyzers/address_tables.rs b/crates/ghidrust-core/src/analyzers/address_tables.rsindex 3ec5986..576e0e3 100644--- a/crates/ghidrust-core/src/analyzers/address_tables.rs+++ b/crates/ghidrust-core/src/analyzers/address_tables.rs@@ -1,6 +1,9 @@use super::AnalyzerOutput;use crate::error::Result;-use crate::program::{AddressTableInfo, Program, ReferenceInfo};+use crate::program::{AddressTableInfo, AddressTableRole, Program, ReferenceInfo};++/// Safety cap on a single contiguous pointer run (matches il2cpp pointer-run bound).+const MAX_RUN_ENTRIES: usize = 1_000_000;pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {let mut tables = Vec::new();@@ -10,7 +13,7 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {while i + 24 <= b.len() {let mut entries = Vec::new();let mut j = i;- while j + 8 <= b.len() && entries.len() < 64 {+ while j + 8 <= b.len() && entries.len() < MAX_RUN_ENTRIES {let val = u64::from_le_bytes(b[j..j + 8].try_into().unwrap());if prog.contains_va(val) {entries.push(val);@@ -21,18 +24,18 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {}if entries.len() >= 3 {let base = block.va + i as u64;- for (k, &tgt) in entries.iter().enumerate() {- prog.analysis.references.push(ReferenceInfo {- from: base + (k as u64) * 8,- to: tgt,- kind: "ptr_table".into(),- });+ // Split long runs at Code↔Data transitions so parallel name/fn+ // arrays that abut stay separate logical tables.+ for part in split_by_target_class(prog, base, &entries) {+ for (k, &tgt) in part.entries.iter().enumerate() {+ prog.analysis.references.push(ReferenceInfo {+ from: part.base + (k as u64) * 8,+ to: tgt,+ kind: "ptr_table".into(),+ });+ }+ tables.push(part);}- tables.push(AddressTableInfo {- base,- count: entries.len(),- entries,- });i = j;} else {i += 8;@@ -41,6 +44,11 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {}tables.sort_by_key(|t| t.base);tables.dedup_by_key(|t| t.base);+ tables = stitch_adjacent(tables);+ for t in &mut tables {+ t.role = classify_role(prog, &t.entries);+ t.count = t.entries.len();+ }let n = tables.len();prog.analysis.address_tables = tables.clone();Ok(AnalyzerOutput {@@ -51,3 +59,249 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {..Default::default()})}++#[derive(Clone, Copy, PartialEq, Eq)]+enum EntryClass {+ Code,+ Data,+ Other,+}++fn entry_class(prog: &Program, va: u64) -> EntryClass {+ match prog.blocks.iter().find(|b| va >= b.va && va < b.va + b.size) {+ Some(b) if b.executable => EntryClass::Code,+ Some(_) => EntryClass::Data,+ None => EntryClass::Other,+ }+}++/// Split a contiguous pointer run into uniform Code/Data segments (len >= 3).+fn split_by_target_class(prog: &Program, base: u64, entries: &[u64]) -> Vec<AddressTableInfo> {+ if entries.is_empty() {+ return Vec::new();+ }+ let mut out = Vec::new();+ let mut seg_start = 0usize;+ let mut seg_class = entry_class(prog, entries[0]);+ for (i, &e) in entries.iter().enumerate().skip(1) {+ let c = entry_class(prog, e);+ if c != seg_class {+ push_segment(prog, base, entries, seg_start, i, seg_class, &mut out);+ seg_start = i;+ seg_class = c;+ }+ }+ push_segment(prog, base, entries, seg_start, entries.len(), seg_class, &mut out);+ if out.is_empty() && entries.len() >= 3 {+ // Degenerate: all Other — keep as one Unknown table.+ out.push(AddressTableInfo {+ base,+ count: entries.len(),+ entries: entries.to_vec(),+ role: AddressTableRole::Unknown,+ });+ }+ out+}++fn push_segment(+ prog: &Program,+ base: u64,+ entries: &[u64],+ start: usize,+ end: usize,+ class: EntryClass,+ out: &mut Vec<AddressTableInfo>,+) {+ if end.saturating_sub(start) < 3 {+ return;+ }+ if matches!(class, EntryClass::Other) {+ return;+ }+ let slice = entries[start..end].to_vec();+ let role = classify_role(prog, &slice);+ out.push(AddressTableInfo {+ base: base + (start as u64) * 8,+ count: slice.len(),+ entries: slice,+ role,+ });+}++fn classify_role(prog: &Program, entries: &[u64]) -> AddressTableRole {+ if entries.is_empty() {+ return AddressTableRole::Unknown;+ }+ let mut code = 0usize;+ let mut data = 0usize;+ for &e in entries {+ if let Some(b) = prog.blocks.iter().find(|b| e >= b.va && e < b.va + b.size) {+ if b.executable {+ code += 1;+ } else {+ data += 1;+ }+ }+ }+ let n = entries.len();+ // Strict majority (>50%).+ if code * 2 > n {+ AddressTableRole::CodePtrs+ } else if data * 2 > n {+ AddressTableRole::DataPtrs+ } else {+ AddressTableRole::Mixed+ }+}++/// Merge runs that abut (`a.end == b.base`) when roles are compatible.+fn stitch_adjacent(mut tables: Vec<AddressTableInfo>) -> Vec<AddressTableInfo> {+ if tables.is_empty() {+ return tables;+ }+ tables.sort_by_key(|t| t.base);+ let mut out = Vec::with_capacity(tables.len());+ let mut cur = tables.remove(0);+ for next in tables {+ let cur_end = cur.base + (cur.entries.len() as u64) * 8;+ let compatible = roles_compatible(cur.role, next.role);+ if cur_end == next.base && compatible {+ cur.entries.extend(next.entries);+ cur.count = cur.entries.len();+ if cur.role == AddressTableRole::Unknown {+ cur.role = next.role;+ } else if next.role != AddressTableRole::Unknown && next.role != cur.role {+ cur.role = AddressTableRole::Mixed;+ }+ } else {+ out.push(cur);+ cur = next;+ }+ }+ out.push(cur);+ out+}++fn roles_compatible(a: AddressTableRole, b: AddressTableRole) -> bool {+ use AddressTableRole::*;+ // Only merge same concrete roles (or Unknown with a concrete peer).+ matches!(+ (a, b),+ (CodePtrs, CodePtrs) | (DataPtrs, DataPtrs) | (Unknown, Unknown)+ | (Unknown, CodePtrs)+ | (CodePtrs, Unknown)+ | (Unknown, DataPtrs)+ | (DataPtrs, Unknown)+ )+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::program::MemoryBlock;++ fn prog_with_block(va: u64, bytes: Vec<u8>, exec: bool) -> Program {+ let mut prog = Program::new("t".into(), "PE32+");+ prog.image_base = 0x140000000;+ prog.blocks.push(MemoryBlock {+ name: if exec { ".text".into() } else { ".rdata".into() },+ va,+ size: bytes.len() as u64,+ bytes,+ readable: true,+ writable: false,+ executable: exec,+ });+ prog+ }++ #[test]+ fn uncaps_runs_beyond_64() {+ let base = 0x140001000u64;+ // 80 pointers into a mapped dummy region at 0x140010000++ let target_base = 0x140010000u64;+ let mut rdata = Vec::new();+ for i in 0..80u64 {+ rdata.extend_from_slice(&(target_base + i * 8).to_le_bytes());+ }+ let mut prog = prog_with_block(base, rdata, false);+ // Target region so contains_va succeeds.+ prog.blocks.push(MemoryBlock {+ name: ".data".into(),+ va: target_base,+ size: 80 * 8,+ bytes: vec![0u8; 80 * 8],+ readable: true,+ writable: true,+ executable: false,+ });+ let out = run(&mut prog).unwrap();+ let tables = out.address_tables.unwrap();+ assert_eq!(tables.len(), 1, "{tables:?}");+ assert_eq!(tables[0].count, 80);+ assert_eq!(tables[0].role, AddressTableRole::DataPtrs);+ }++ #[test]+ fn dual_adjacent_code_and_data_tables_keep_roles() {+ let fn_base = 0x140002000u64;+ let name_base = 0x140002280u64; // immediately after 80*8+ let text_va = 0x140001000u64;+ let str_va = 0x140003000u64;+ let n = 80usize;+ let mut fn_bytes = Vec::new();+ for i in 0..n {+ fn_bytes.extend_from_slice(&(text_va + i as u64).to_le_bytes());+ }+ let mut name_bytes = Vec::new();+ for i in 0..n {+ name_bytes.extend_from_slice(&(str_va + i as u64 * 0x20).to_le_bytes());+ }+ assert_eq!(fn_base + (n as u64) * 8, name_base);+ let mut prog = Program::new("t".into(), "PE32+");+ prog.image_base = 0x140000000;+ prog.blocks.push(MemoryBlock {+ name: ".text".into(),+ va: text_va,+ size: 0x1000,+ bytes: vec![0xCCu8; 0x1000],+ readable: true,+ writable: false,+ executable: true,+ });+ prog.blocks.push(MemoryBlock {+ name: ".rdata".into(),+ va: str_va,+ size: 0x2000,+ bytes: vec![b'A'; 0x2000],+ readable: true,+ writable: false,+ executable: false,+ });+ let mut table_blob = fn_bytes;+ table_blob.extend_from_slice(&name_bytes);+ prog.blocks.push(MemoryBlock {+ name: ".rdata2".into(),+ va: fn_base,+ size: table_blob.len() as u64,+ bytes: table_blob,+ readable: true,+ writable: false,+ executable: false,+ });+ let out = run(&mut prog).unwrap();+ let tables = out.address_tables.unwrap();+ // Should remain two tables (incompatible roles: CodePtrs vs DataPtrs).+ assert!(+ tables.len() >= 2,+ "expected separate code/data tables, got {tables:?}"+ );+ let code = tables.iter().find(|t| t.role == AddressTableRole::CodePtrs);+ let data = tables.iter().find(|t| t.role == AddressTableRole::DataPtrs);+ assert!(code.is_some(), "{tables:?}");+ assert!(data.is_some(), "{tables:?}");+ assert_eq!(code.unwrap().count, n);+ assert_eq!(data.unwrap().count, n);+ }+}diff --git a/crates/ghidrust-core/src/analyzers/mod.rs b/crates/ghidrust-core/src/analyzers/mod.rsindex 9b91b8e..505c58d 100644--- a/crates/ghidrust-core/src/analyzers/mod.rs+++ b/crates/ghidrust-core/src/analyzers/mod.rs@@ -25,7 +25,10 @@ use crate::program::Program;use crate::rtti::{recover_rtti, RttiReport};use serde::Serialize;-pub use strings::{collect_strings, scan_ascii_strings, scan_utf16le_strings, FoundString};+pub use strings::{+ collect_strings, collect_strings_bytes, collect_strings_opts, scan_ascii_strings,+ scan_utf16le_strings, FoundString, StringCollectOpts, StringMatchMode,+};/// Exact labels from the Ghidra Auto Analysis screenshot (order preserved).pub const ANALYZER_NAMES: &[&str] = &[diff --git a/crates/ghidrust-core/src/analyzers/strings.rs b/crates/ghidrust-core/src/analyzers/strings.rsindex 55d5a81..26e3b21 100644--- a/crates/ghidrust-core/src/analyzers/strings.rs+++ b/crates/ghidrust-core/src/analyzers/strings.rs@@ -4,6 +4,56 @@ use crate::error::Result;use crate::program::Program;use serde::Serialize;+/// How `--filter` matches string values.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum StringMatchMode {+ /// Case-insensitive substring (legacy default).+ #[default]+ Substr,+ /// Case-insensitive token: whole word / identifier boundary.+ Token,+ /// Entire string equals needle (case-insensitive).+ Whole,+ /// Glob with `*` / `?` (case-insensitive).+ Glob,+}++impl StringMatchMode {+ pub fn parse(s: &str) -> Result<Self> {+ match s.to_ascii_lowercase().as_str() {+ "substr" | "substring" | "contains" => Ok(Self::Substr),+ "token" | "word" => Ok(Self::Token),+ "whole" | "exact" | "eq" => Ok(Self::Whole),+ "glob" => Ok(Self::Glob),+ other => Err(crate::error::Error::Parse(format!(+ "unknown match mode '{other}' (use substr|token|whole|glob)"+ ))),+ }+ }+}++/// Options for [`collect_strings`] / [`collect_strings_bytes`].+#[derive(Debug, Clone)]+pub struct StringCollectOpts {+ pub encoding: String,+ pub min_len: usize,+ pub filter: Option<String>,+ pub match_mode: StringMatchMode,+ pub limit: Option<usize>,+}++impl Default for StringCollectOpts {+ fn default() -> Self {+ Self {+ encoding: "all".into(),+ min_len: 4,+ filter: None,+ match_mode: StringMatchMode::Substr,+ limit: None,+ }+ }+}+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]pub struct FoundString {pub va: u64,@@ -138,46 +188,128 @@ fn is_utf16_printable(cu: u16) -> bool {cu <= 0x00ff}-/// Combined ASCII + UTF-16LE scan with optional case-insensitive substring /-/// simple glob filter (`*` / `?` only; no regex crate).+/// Combined ASCII + UTF-16LE scan (legacy filter = substr, with auto-glob).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));+ let mut opts = StringCollectOpts {+ encoding: encoding.into(),+ min_len,+ filter: filter.map(|s| s.to_string()),+ ..Default::default()+ };+ // Preserve prior auto-glob when pattern contains wildcards and mode is default substr.+ if let Some(pat) = filter {+ if pat.contains('*') || pat.contains('?') {+ opts.match_mode = StringMatchMode::Glob;+ }}+ collect_strings_opts(prog, &opts)+}++/// Scan with explicit match mode / limit (filter-during-scan when a filter is set).+pub fn collect_strings_opts(prog: &Program, opts: &StringCollectOpts) -> Result<Vec<FoundString>> {+ let enc = opts.encoding.to_ascii_lowercase();if enc != "ascii" && enc != "utf16" && enc != "utf16le" && enc != "all" {return Err(crate::error::Error::Parse(format!(- "unknown encoding '{encoding}' (use ascii|utf16|all)"+ "unknown encoding '{}' (use ascii|utf16|all)",+ opts.encoding)));}+ let mut out = Vec::new();+ if enc == "ascii" || enc == "all" {+ for s in scan_ascii_strings(prog, opts.min_len) {+ if filter_accept(opts, &s.value) {+ out.push(s);+ if limit_hit(opts, out.len()) {+ break;+ }+ }+ }+ }+ if !limit_hit(opts, out.len()) && (enc == "utf16" || enc == "utf16le" || enc == "all") {+ for s in scan_utf16le_strings(prog, opts.min_len) {+ if filter_accept(opts, &s.value) {+ out.push(s);+ if limit_hit(opts, out.len()) {+ break;+ }+ }+ }+ }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));+ if let Some(lim) = opts.limit {+ out.truncate(lim);}Ok(out)}-fn filter_match(pat: &str, value: &str) -> bool {+/// Scan an arbitrary byte slice as a single blob at `base_va` (raw files / metadata).+pub fn collect_strings_bytes(+ bytes: &[u8],+ base_va: u64,+ opts: &StringCollectOpts,+) -> Result<Vec<FoundString>> {+ let mut prog = Program::new("blob".into(), "blob");+ prog.image_base = base_va;+ prog.blocks.push(crate::program::MemoryBlock {+ name: ".blob".into(),+ va: base_va,+ size: bytes.len() as u64,+ bytes: bytes.to_vec(),+ readable: true,+ writable: false,+ executable: false,+ });+ collect_strings_opts(&prog, opts)+}++fn limit_hit(opts: &StringCollectOpts, n: usize) -> bool {+ opts.limit.is_some_and(|lim| n >= lim)+}++fn filter_accept(opts: &StringCollectOpts, value: &str) -> bool {+ match &opts.filter {+ None => true,+ Some(pat) => filter_match_mode(opts.match_mode, pat, value),+ }+}++fn filter_match_mode(mode: StringMatchMode, 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)+ match mode {+ StringMatchMode::Substr => val_l.contains(&pat_l),+ StringMatchMode::Whole => val_l == pat_l,+ StringMatchMode::Glob => glob_match(&pat_l, &val_l),+ StringMatchMode::Token => token_match(&pat_l, &val_l),}}+fn token_match(pat: &str, value: &str) -> bool {+ if pat.is_empty() {+ return false;+ }+ // Split on non-alphanumeric / non-underscore boundaries (identifier-ish).+ let mut start = 0usize;+ let bytes = value.as_bytes();+ for i in 0..=bytes.len() {+ let boundary = i == bytes.len()+ || !bytes[i].is_ascii_alphanumeric() && bytes[i] != b'_';+ if boundary {+ if i > start && &value[start..i] == pat {+ return true;+ }+ start = i + 1;+ }+ }+ false+}+fn glob_match(pat: &str, value: &str) -> bool {fn rec(p: &[u8], v: &[u8]) -> bool {match (p.first(), v.first()) {@@ -228,4 +360,37 @@ mod tests {);assert!(hits.iter().all(|s| s.encoding == "utf16le"));}++ #[test]+ fn token_match_skips_substring_noise() {+ // Underscore keeps identifier tokens together; dots/spaces split.+ assert!(token_match("xr", "foo.xr.bar"));+ assert!(token_match("xr", "foo xr bar"));+ assert!(!token_match("xr", "foo_xr_bar"));+ assert!(!token_match("xr", "openxrloader"));+ assert!(filter_match_mode(+ StringMatchMode::Token,+ "Camera",+ "UnityEngine.Camera"+ ));+ assert!(!filter_match_mode(+ StringMatchMode::Token,+ "Cam",+ "UnityEngine.Camera"+ ));+ }++ #[test]+ fn collect_bytes_respects_limit() {+ let hay = b"AAAA_hello\0BBBB_hello\0CCCC_hello\0";+ let opts = StringCollectOpts {+ encoding: "ascii".into(),+ min_len: 4,+ filter: Some("hello".into()),+ match_mode: StringMatchMode::Substr,+ limit: Some(2),+ };+ let hits = collect_strings_bytes(hay, 0, &opts).unwrap();+ assert_eq!(hits.len(), 2);+ }}diff --git a/crates/ghidrust-core/src/gpu_analyzers/engine.rs b/crates/ghidrust-core/src/gpu_analyzers/engine.rsindex 8cc1f95..b123498 100644--- a/crates/ghidrust-core/src/gpu_analyzers/engine.rs+++ b/crates/ghidrust-core/src/gpu_analyzers/engine.rs@@ -247,7 +247,9 @@ pub fn cpu_emulate_kernel(while i + 24 <= hay.len() {let mut run = 0u32;let mut j = i;- while j + 8 <= hay.len() && run < 64 {+ // No 64-entry cap — CPU Create Address Tables is authoritative for full runs;+ // this kernel only seeds candidate bases (run >= 3).+ while j + 8 <= hay.len() && run < 1_000_000 {let v = u64::from_le_bytes(hay[j..j + 8].try_into().unwrap());if v >= image_base && v < image_end {run += 1;diff --git a/crates/ghidrust-core/src/gpu_analyzers/strategies.rs b/crates/ghidrust-core/src/gpu_analyzers/strategies.rsindex b6a55b2..8a8944e 100644--- a/crates/ghidrust-core/src/gpu_analyzers/strategies.rs+++ b/crates/ghidrust-core/src/gpu_analyzers/strategies.rs@@ -3,7 +3,7 @@use super::engine::{cpu_emulate_kernel, run_kernel, GpuPhaseTiming, KernelKind, MAX_HITS};use super::{flatten_exec, flatten_image, pad_large};use crate::program::{- AddressTableInfo, CallFixupInfo, DiscoveredRange, FidMatch, FunctionInfo, MediaHit, Program,+ CallFixupInfo, DiscoveredRange, FidMatch, FunctionInfo, MediaHit, Program,ResourceInfo, SymbolInfo,};use crate::rtti::RttiClass;@@ -256,16 +256,10 @@ pub fn merge_seeds_into_program(prog.analysis.functions.len()}GpuStrategyClass::PtrChain => {- for &off in hits {- if let Some(va) = flat_to_va(map, off) {- prog.analysis.address_tables.push(AddressTableInfo {- base: va,- count: 3,- entries: Vec::new(),- });- }- }- prog.analysis.address_tables.len()+ // Do not deposit empty AddressTableInfo stubs — CPU "Create Address Tables"+ // owns full pointer-run recovery. Report seed hit count only.+ let _ = (hits, map, hay, prog);+ hits.len()}GpuStrategyClass::RttiScan => {for &off in hits {diff --git a/crates/ghidrust-core/src/io_util.rs b/crates/ghidrust-core/src/io_util.rsnew file mode 100644index 0000000..de1485f--- /dev/null+++ b/crates/ghidrust-core/src/io_util.rs@@ -0,0 +1,38 @@+//! Shared I/O helpers (BOM-free JSON, path sanitization).++use crate::error::{Error, Result};+use serde::Serialize;+use std::fs::File;+use std::io::Write;+use std::path::{Path, PathBuf};++/// Replace path-hostile characters (`:`, `/`, `\`, etc.) so filters never become Windows paths.+pub fn sanitize_path_component(s: &str) -> String {+ s.chars()+ .map(|c| match c {+ ':' | '/' | '\\' | '<' | '>' | '"' | '|' | '?' | '*' => '_',+ c if c.is_control() => '_',+ c => c,+ })+ .collect()+}++/// Build a default output name from a filter needle (never use the raw filter as a path).+pub fn sanitized_out_name(prefix: &str, filter: &str, ext: &str) -> PathBuf {+ let safe = sanitize_path_component(filter);+ let trimmed: String = safe.chars().take(64).collect();+ let stem = if trimmed.is_empty() {+ "out".into()+ } else {+ trimmed+ };+ PathBuf::from(format!("{prefix}_{stem}.{ext}"))+}++/// Serialize `value` as pretty UTF-8 JSON with **no BOM**.+pub fn write_json_no_bom<T: Serialize>(path: &Path, value: &T) -> Result<()> {+ let mut f = File::create(path).map_err(|e| Error::Io(e.to_string()))?;+ serde_json::to_writer_pretty(&mut f, value).map_err(|e| Error::Io(e.to_string()))?;+ f.write_all(b"\n").map_err(|e| Error::Io(e.to_string()))?;+ Ok(())+}diff --git a/crates/ghidrust-core/src/lib.rs b/crates/ghidrust-core/src/lib.rsindex e0ecaa0..78199f7 100644--- a/crates/ghidrust-core/src/lib.rs+++ b/crates/ghidrust-core/src/lib.rs@@ -8,6 +8,7 @@ pub mod disasm;pub mod elf;pub mod error;pub mod imports;+pub mod io_util;pub mod pe;pub mod program;pub mod project;@@ -16,9 +17,10 @@ pub mod theme;pub mod xrefs;pub use analyzers::{- analyzer_catalog, collect_strings, run_analyzers, run_analyzers_opts, scan_ascii_strings,- scan_utf16le_strings, AnalysisRunReport, AnalyzerInfo, AnalyzerOutput, AnalyzerStatus,- FoundString, ANALYZER_NAMES,+ analyzer_catalog, collect_strings, collect_strings_bytes, collect_strings_opts, run_analyzers,+ run_analyzers_opts, scan_ascii_strings, scan_utf16le_strings, AnalysisRunReport, AnalyzerInfo,+ AnalyzerOutput, AnalyzerStatus, FoundString, StringCollectOpts, StringMatchMode,+ ANALYZER_NAMES,};pub use bulk_scan::{plan_dispatch_workgroup_chunks, preferred_bulk_mode, scan_ascii_strings_bulk,@@ -37,13 +39,15 @@ 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 io_util::{sanitize_path_component, sanitized_out_name, write_json_no_bom};pub use edits::{CommentKind, EquateEdit, FunctionSignatureEdit, ProgramEditTotals, ProgramEdits, RetypeEdit,BUILTIN_TYPES,};pub use error::{Error, Result};pub use program::{- AddressTableInfo, AnalysisState, CallFixupInfo, DiscoveredRange, FidMatch, FunctionInfo,+ AddressTableInfo, AddressTableRole, AnalysisState, CallFixupInfo, DiscoveredRange, FidMatch,+ FunctionInfo,ImportEntry, MediaHit, MemoryBlock, Program, ReferenceInfo, ResourceInfo, SectionInfo,SwitchInfo, SymbolInfo,};@@ -73,15 +77,64 @@ pub fn load_bytes(data: &[u8], name: impl Into<String>) -> Result<Program> {}}+/// Load arbitrary bytes as a single readable blob (`format: "blob"`).+///+/// Used for raw files (e.g. metadata dumps) that are not PE/ELF. Image base is 0;+/// the whole file is one memory block at VA 0.+pub fn load_blob(data: &[u8], name: impl Into<String>) -> Program {+ let name = name.into();+ let mut prog = Program::new(name, "blob");+ prog.image_base = 0;+ prog.file_bytes = data.to_vec();+ let size = data.len() as u64;+ prog.sections.push(program::SectionInfo {+ name: ".blob".into(),+ va: 0,+ virtual_size: size,+ raw_size: size,+ file_offset: 0,+ characteristics: 0,+ });+ prog.blocks.push(program::MemoryBlock {+ name: ".blob".into(),+ va: 0,+ size,+ bytes: data.to_vec(),+ readable: true,+ writable: false,+ executable: false,+ });+ prog+}++/// Load PE/ELF, or a raw blob when `allow_blob` is true and magic is unrecognized.+pub fn load_bytes_opts(+ data: &[u8],+ name: impl Into<String>,+ allow_blob: bool,+) -> Result<Program> {+ let name = name.into();+ match load_bytes(data, name.clone()) {+ Ok(p) => Ok(p),+ Err(Error::UnsupportedFormat(_)) if allow_blob => Ok(load_blob(data, name)),+ Err(e) => Err(e),+ }+}+/// Load from a filesystem path.pub fn load_path(path: impl AsRef<Path>) -> Result<Program> {+ load_path_opts(path, false)+}++/// Load from path; when `allow_blob` is set, non-PE/ELF files become blobs.+pub fn load_path_opts(path: impl AsRef<Path>, allow_blob: bool) -> Result<Program> {let path = path.as_ref();let data = std::fs::read(path).map_err(|e| Error::Io(e.to_string()))?;let name = path.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "image".into());- load_bytes(&data, name)+ load_bytes_opts(&data, name, allow_blob)}/// Run load + disasm slice + default analyzers.diff --git a/crates/ghidrust-core/src/program.rs b/crates/ghidrust-core/src/program.rsindex 56f4045..2ebce4d 100644--- a/crates/ghidrust-core/src/program.rs+++ b/crates/ghidrust-core/src/program.rs@@ -65,11 +65,27 @@ pub struct ReferenceInfo {pub kind: String,}+/// Classification of what an address-table's entries predominantly point at.+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]+#[serde(rename_all = "snake_case")]+pub enum AddressTableRole {+ #[default]+ Unknown,+ /// Majority of entries land in executable blocks.+ CodePtrs,+ /// Majority of entries land in non-executable mapped blocks (strings, data).+ DataPtrs,+ /// No clear majority.+ Mixed,+}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]pub struct AddressTableInfo {pub base: u64,pub count: usize,pub entries: Vec<u64>,+ #[serde(default)]+ pub role: AddressTableRole,}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]diff --git a/crates/ghidrust-core/src/xrefs.rs b/crates/ghidrust-core/src/xrefs.rsindex 171e905..506be84 100644--- a/crates/ghidrust-core/src/xrefs.rs+++ b/crates/ghidrust-core/src/xrefs.rs@@ -3,8 +3,9 @@//! 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+//! 3. Non-exec data — aligned LE `u64` slots equal to the target (`kind: "ptr"`)+//! 4. Decoded instructions — absolute operand hex + RIP-relative targets+//! 5. Import / IAT slots — `call/jmp [rip+disp]` landing on IAT VAsuse crate::disasm::{decode_one, disassemble_range};use crate::program::{ImportEntry, Program};@@ -17,7 +18,7 @@ pub struct XRef {pub from: u64,/// Target VA (where the reference points at).pub to: u64,- /// Ghidra-analog kind (`call`, `jmp`, `cond_jmp`, `data`, `ptr_table`,+ /// Ghidra-analog kind (`call`, `jmp`, `cond_jmp`, `data`, `ptr`, `ptr_table`,/// `resource`, `xref`, `iat`).pub kind: &'static str,/// Ghidra "From Preview" — mnemonic/operand text where computable.@@ -60,6 +61,8 @@ pub fn xrefs_to(}}+ scan_data_pointer_refs(prog, target, &mut out);+if let Some(listing) = hint_listing {push_listing_xrefs_to(listing, target, &mut out);} else {@@ -70,6 +73,43 @@ pub fn xrefs_to(out}+/// Cap on lone data-pointer hits per `xrefs_to` (avoids huge .data scans dominating output).+const DATA_PTR_XREF_CAP: usize = 4096;++/// Scan non-executable blocks for aligned LE `u64` slots equal to `target`.+fn scan_data_pointer_refs(prog: &Program, target: u64, out: &mut Vec<XRef>) {+ let mut found = 0usize;+ for block in &prog.blocks {+ if block.executable {+ continue;+ }+ let b = &block.bytes;+ let mut off = 0usize;+ // Align to 8 within the block.+ let mis = (block.va as usize + off) % 8;+ if mis != 0 {+ off += 8 - mis;+ }+ while off + 8 <= b.len() {+ if found >= DATA_PTR_XREF_CAP {+ return;+ }+ let val = u64::from_le_bytes(b[off..off + 8].try_into().unwrap());+ if val == target {+ let from = block.va + off as u64;+ out.push(XRef {+ from,+ to: target,+ kind: "ptr",+ preview: format!("dq {target:#x}"),+ });+ found += 1;+ }+ off += 8;+ }+ }+}+/// 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();@@ -319,6 +359,7 @@ fn mnemonic_kind(mnem: &str) -> &'static str {fn static_kind(raw: &str) -> &'static str {match raw {"ptr_table" => "ptr_table",+ "ptr" => "ptr","resource" => "resource","call" => "call","jmp" => "jmp",@@ -377,6 +418,7 @@ mod tests {base: prog.image_base,count: 1,entries: vec![entry],+ role: crate::program::AddressTableRole::Unknown,});prog.analysis.references.push(ReferenceInfo {from: prog.image_base + 0x40,@@ -424,4 +466,42 @@ mod tests {"{refs:?}");}++ #[test]+ fn xrefs_to_finds_lone_rdata_qword_pointer() {+ let mut prog = Program::new("t".into(), "PE32+");+ let str_va = 0x140002000u64;+ let slot_va = 0x140003008u64; // intentionally not part of a 3+ table run+ prog.blocks.push(MemoryBlock {+ name: ".rdata".into(),+ va: 0x140002000,+ size: 0x20,+ bytes: {+ let mut b = b"Hello\0\0\0".to_vec();+ b.resize(0x20, 0);+ b+ },+ readable: true,+ writable: false,+ executable: false,+ });+ // Sparse data block: 8 bytes of zeros then one qword pointer (singleton, not a table).+ let mut data = vec![0u8; 8];+ data.extend_from_slice(&str_va.to_le_bytes());+ prog.blocks.push(MemoryBlock {+ name: ".data".into(),+ va: 0x140003000,+ size: data.len() as u64,+ bytes: data,+ readable: true,+ writable: true,+ executable: false,+ });+ let refs = xrefs_to(&prog, str_va, None);+ assert!(+ refs.iter()+ .any(|r| r.from == slot_va && r.to == str_va && r.kind == "ptr"),+ "{refs:?}"+ );+ }}diff --git a/crates/ghidrust-decode/src/x86_64.rs b/crates/ghidrust-decode/src/x86_64.rsindex 9b3d756..78f5fe1 100644--- a/crates/ghidrust-decode/src/x86_64.rs+++ b/crates/ghidrust-decode/src/x86_64.rs@@ -148,6 +148,24 @@ fn size_prefix(sz: u32) -> &'static str {/// register-side (mod == 3) to use the 1-byte name set; `mem_size` labels/// the memory access width (1/2/4/8) so downstream lift can pick the right/// load/store width without needing to reparse the mnemonic.+fn xmm_name(reg: u8) -> String {+ format!("xmm{}", reg & 0xf)+}++/// Decode ModRM for SSE xmm, xmm/m128 forms. Returns (xmm_reg, rm_operand).+fn decode_sse_xmm_rm(cur: &mut Cursor<'_>, pfx: Prefix) -> Result<(String, String)> {+ let modrm = cur.get()?;+ let reg = ((modrm >> 3) & 7) | if pfx.rex_r { 8 } else { 0 };+ let xmm = xmm_name(reg);+ if (modrm >> 6) == 3 {+ let rm = (modrm & 7) | if pfx.rex_b { 8 } else { 0 };+ Ok((xmm, xmm_name(rm)))+ } else {+ let (_r, rm) = decode_modrm_mem(cur, modrm, pfx, false)?;+ Ok((xmm, rm))+ }+}+fn decode_modrm_sized(cur: &mut Cursor<'_>,modrm: u8,@@ -776,6 +794,25 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {}// LEAVE0xC9 => ("leave".into(), String::new()),+ // Group1 Eb,Ib — ADD/OR/…/CMP r/m8, imm8 (80 /x); 82 is an alias+ 0x80 | 0x82 => {+ let modrm = cur.get()?;+ let reg_field = (modrm >> 3) & 7;+ let mnem = match reg_field {+ 0 => "add",+ 1 => "or",+ 2 => "adc",+ 3 => "sbb",+ 4 => "and",+ 5 => "sub",+ 6 => "xor",+ 7 => "cmp",+ _ => "grp",+ };+ let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;+ let imm = cur.take_imm(1)? as i8 as i64;+ (mnem.into(), format!("{rm}, {imm:#x}"))+ }// SUB/ADD r/m, imm8 (83 /x)0x83 => {let modrm = cur.get()?;@@ -822,6 +859,24 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {0x0F => {let op2 = cur.get()?;match op2 {+ // MOVUPS xmm, xmm/m128 / MOVUPS xmm/m128, xmm+ 0x10 | 0x11 => {+ let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;+ if op2 == 0x10 {+ ("movups".into(), format!("{xmm}, {rm}"))+ } else {+ ("movups".into(), format!("{rm}, {xmm}"))+ }+ }+ // MOVAPS xmm, xmm/m128 / MOVAPS xmm/m128, xmm+ 0x28 | 0x29 => {+ let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;+ if op2 == 0x28 {+ ("movaps".into(), format!("{xmm}, {rm}"))+ } else {+ ("movaps".into(), format!("{rm}, {xmm}"))+ }+ }// Jcc rel320x80..=0x8F => {let names = [@@ -1150,4 +1205,38 @@ mod tests {i.operands);}++ #[test]+ fn decode_group1_byte_cmp_mem_imm8() {+ // 80 b9 e1 01 00 00 00 cmp byte ptr [rcx+0x1e1], 0x0+ let i = decode_one(&[0x80, 0xb9, 0xe1, 0x01, 0x00, 0x00, 0x00], 0).unwrap();+ assert_eq!(i.mnemonic, "cmp");+ assert_eq!(i.length, 7);+ assert!(+ i.operands.contains("byte ptr") && i.operands.contains("[rcx+0x1e1]"),+ "got '{}'",+ i.operands+ );+ assert!(i.operands.ends_with(", 0x0") || i.operands.ends_with(", 0"), "got '{}'", i.operands);+ }++ #[test]+ fn decode_movups_load_store() {+ // 0f 10 1a movups xmm3, [rdx]+ let load = decode_one(&[0x0f, 0x10, 0x1a], 0).unwrap();+ assert_eq!(load.mnemonic, "movups");+ assert_eq!(load.operands, "xmm3, [rdx]");+ // 0f 11 59 10 movups [rcx+0x10], xmm3+ let store = decode_one(&[0x0f, 0x11, 0x59, 0x10], 0).unwrap();+ assert_eq!(store.mnemonic, "movups");+ assert_eq!(store.operands, "[rcx+0x10], xmm3");+ }++ #[test]+ fn decode_movaps_reg_reg() {+ // 0f 28 c1 movaps xmm0, xmm1+ let i = decode_one(&[0x0f, 0x28, 0xc1], 0).unwrap();+ assert_eq!(i.mnemonic, "movaps");+ assert_eq!(i.operands, "xmm0, xmm1");+ }}diff --git a/crates/ghidrust-gui/Cargo.toml b/crates/ghidrust-gui/Cargo.tomlindex e6594d9..99a03e8 100644--- a/crates/ghidrust-gui/Cargo.toml+++ b/crates/ghidrust-gui/Cargo.toml@@ -14,9 +14,8 @@ 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.+# Grok Build glue (install + MCP/skill/context). The TUI itself is hosted via+# an in-tree hand-rolled PTY (`src/grok_term/`) — no crates.io terminal stacks.ghidrust-agent = { workspace = true }eframe = { version = "0.31", default-features = true }egui = "0.31"@@ -24,3 +23,20 @@ rfd = "0.15"# Phase H (M8) — layout persistence (`.tool.json`) via serde_json.serde = { version = "1", features = ["derive"] }serde_json = "1"+# Same width tables ratatui/crossterm use — required so Grok's braille/box+# logo and cursor columns stay in sync with the app (not a terminal stack).+unicode-width = "0.1"++[target.'cfg(windows)'.dependencies]+windows-sys = { version = "0.59", features = [+ "Win32_Foundation",+ "Win32_System_Console",+ "Win32_System_Pipes",+ "Win32_System_Threading",+ "Win32_System_IO",+ "Win32_Storage_FileSystem",+ "Win32_Security",+] }++[target.'cfg(unix)'.dependencies]+libc = "0.2"diff --git a/crates/ghidrust-gui/src/agent_pane.rs b/crates/ghidrust-gui/src/agent_pane.rsindex ac7d68d..374b412 100644--- a/crates/ghidrust-gui/src/agent_pane.rs+++ b/crates/ghidrust-gui/src/agent_pane.rs@@ -1,167 +1,79 @@-//! Grok Build agent console pane — Option C (ACP sidecar) integration.+//! Grok Build pane — hosts the real Grok TUI via an in-tree PTY (`grok_term`).//!-//! 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.+//! Thin glue only: find/install `grok`, write MCP + skill + context files, then+//! spawn the binary in the project directory. Slash commands, models, /goal,+//! sessions — all come from Grok itself.+use crate::grok_term::{self, GrokTermSession};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,+ grok_binary_path, install_command_for_platform, register_mcp_with_grok_cli,+ write_project_mcp_config, write_project_skill, ProgramFacts, SystemPromptBuilder,};use std::path::{Path, PathBuf};/// Which tab of the bottom dock is currently active.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pub enum BottomTab {- /// The Grok Build agent console (default primary tab per user spec).+ /// Embedded Grok Build TUI (default).#[default]Grok,- /// The plain analyzer / script Console (existing behavior).+ /// Plain analyzer / script Console.Console,}-/// 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).+/// Per-project Grok pane state.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).+ /// Live PTY session running `grok`.+ pub session: Option<GrokTermSession>,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>,+ pub version_probe: Option<String>,+ /// Status line under the toolbar (e.g. "session ended").+ pub status: Option<String>,+ /// True while the embedded TUI owns the keyboard — listing hotkeys (G, L, …)+ /// must not fire.+ pub keyboard_captured: bool,+ /// Set after Start/Restart so the next paint focuses the terminal.+ pub request_term_focus: bool,}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,+ version_probe: None,+ status: None,+ keyboard_captured: false,+ request_term_focus: false,}}- /// 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;- }- }- }+ pub fn stop_session(&mut self) {+ self.session = None;+ self.keyboard_captured = false;+ self.request_term_focus = false;+ self.status = Some("Grok session stopped.".into());}- /// Poll the live session (if any). Safe to call every frame.+ /// Poll child exit each 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);+ if let Some(sess) = &mut self.session {+ if sess.poll_exited() {+ self.session = None;+ self.status = Some(+ "Grok exited. Click Start / Restart to open a new TUI session.".into(),+ );}}}@@ -173,193 +85,176 @@ impl Default for GrokPaneState {}}-// ── 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(+/// Write MCP + skill + Ghidrust context, then spawn the Grok TUI in a PTY.+pub fn start_pty_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.+ facts: &ProgramFacts,+ ctx: egui::Context,+ cols: u16,+ rows: u16,+) -> Result<GrokTermSession, String> {+ write_project_mcp_config(project_root, ghidrust_bin).map_err(|e| e.to_string())?;+ // Best-effort CLI registry sync (files above are the source of truth).+ let _ = register_mcp_with_grok_cli(grok_bin, project_root, ghidrust_bin);if let Some(src) = skill_source {let _ = write_project_skill(project_root, src);}+ write_ghidrust_agent_files(project_root, facts)?;- let system_prompt = SystemPromptBuilder::new(skill_body_for_prompt)- .facts(&facts)- .read_only_note(matches!(mode, AgentMode::ReadOnly))- .airgap_note(matches!(mode, AgentMode::Airgap))+ GrokTermSession::start(+ grok_bin.to_path_buf(),+ project_root.to_path_buf(),+ cols,+ rows,+ ctx,+ )+}++/// Persist identity + live program facts for the Grok TUI to load from disk.+fn write_ghidrust_agent_files(project_root: &Path, facts: &ProgramFacts) -> Result<(), String> {+ let grok_dir = project_root.join(".grok");+ std::fs::create_dir_all(&grok_dir).map_err(|e| e.to_string())?;++ let context = SystemPromptBuilder::new("")+ .facts(facts)+ .read_only_note(false)+ .airgap_note(false).build();+ std::fs::write(grok_dir.join("ghidrust-context.md"), &context).map_err(|e| e.to_string())?;- 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)+ // AGENTS.md — Grok Build reads this on session start in the project cwd.+ let agents = format!(+ "# Ghidrust agent\n\n\+ You are Ghidrust's in-GUI reverse-engineering copilot.\n\+ The user is running Ghidrust with a project open at this working directory.\n\+ Use the `ghidrust` MCP server (see `.grok/mcp.json`) for all analysis — \+ never invent addresses, symbols, or decompile output.\n\+ Read `.grok/ghidrust-context.md` for live program facts and \+ `.grok/skills/ghidrust/SKILL.md` for the full tool catalog.\n\n\+ If a project file has saved analysis but nothing is loaded in the GUI, \+ say so and use MCP `load` with the file id from the facts JSON.\n"+ );+ std::fs::write(project_root.join("AGENTS.md"), agents).map_err(|e| e.to_string())?;+ Ok(())}-// ── 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(+/// Render the Grok tab: toolbar + embedded TUI (or empty / error state).+pub fn render_grok_pane(ui: &mut Ui,- entry: &mut TranscriptEntry,- pseudo_c_render: &mut dyn FnMut(&mut Ui, &str),- on_approval: &mut dyn FnMut(&str, bool),- muted: Color32,+ state: &mut GrokPaneState,primary: Color32,+ muted: Color32,+ on_start: &mut dyn FnMut(u16, u16) -> Result<(), String>,+ on_install: &mut dyn FnMut(),+ on_rescan: &mut dyn FnMut(),+ on_probe: &mut dyn FnMut(),) {- 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(),+ ui.horizontal_wrapped(|ui| {+ ui.label(RichText::new("Grok").color(primary).strong());+ if let Some(sess) = &state.session {+ ui.small(+ RichText::new(format!(+ "TUI · {}",+ sess.project_root.display()+ ))+ .color(muted),+ );+ } else if let Some(bin) = &state.grok_bin {+ ui.small(RichText::new(format!("grok: {}", bin.display())).color(muted));+ } else {+ ui.small(+ RichText::new("grok binary not found on PATH")+ .color(Color32::from_rgb(0xFB, 0xC0, 0x2D)),);}- 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);- }- });++ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if state.session.is_some() {+ if ui.button("Stop").clicked() {+ state.stop_session();+ }+ if ui.button("Restart").clicked() {+ state.stop_session();+ let (cols, rows) = (100u16, 28u16);+ match on_start(cols, rows) {+ Ok(()) => state.status = None,+ Err(e) => {+ state.last_error = Some(e);+ }}}- });- }- }-}--/// 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")+ } else {+ if ui+ .add_enabled(state.grok_bin.is_some(), egui::Button::new("Start"))+ .clicked(){- pseudo_c_render(ui, &body);- } else {- ui.group(|ui| {- if !lang.is_empty() {- ui.small(RichText::new(lang.as_str()).weak());+ let (cols, rows) = (100u16, 28u16);+ match on_start(cols, rows) {+ Ok(()) => {+ state.last_error = None;+ state.status = None;}- ui.code(body.as_str());- });+ Err(e) => state.last_error = Some(e),+ }+ }+ if state.grok_bin.is_none() && ui.button("Install Grok Build…").clicked() {+ on_install();+ }+ if ui.button("Re-scan for grok").clicked() {+ on_rescan();+ }+ if state.grok_bin.is_some() && ui.button("Probe version").clicked() {+ on_probe();}}+ });+ });++ if let Some(v) = &state.version_probe {+ ui.small(RichText::new(format!("version: {v}")).color(muted));+ }+ if let Some(err) = &state.last_error {+ ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), err);+ }+ if let Some(status) = &state.install_status {+ ui.small(RichText::new(status).color(muted));+ }+ if let Some(status) = &state.status {+ ui.small(RichText::new(status).color(muted).italics());+ }++ ui.separator();++ if state.session.is_none() {+ state.keyboard_captured = false;+ ui.small(+ RichText::new(+ "Start embeds the real Grok Build TUI here (slash commands, /goal, /model, \+ sessions). On first Start we auto-wire project MCP (ghidrust), skill, and AGENTS.md.",+ )+ .color(muted),+ );+ ui.allocate_space(ui.available_size());+ return;+ }++ let want_focus = state.request_term_focus;+ let sticky = state.keyboard_captured;+ if let Some(sess) = state.session.as_mut() {+ let capturing = grok_term::show_terminal(ui, sess, want_focus, sticky);+ // Sticky while the TUI session lives: once Start focuses the terminal,+ // keep Ctrl+C / keys routed here until Stop or Console tab.+ state.keyboard_captured = capturing || sticky || want_focus;+ if want_focus {+ state.request_term_focus = false;}}}-// ── 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();@@ -389,65 +284,9 @@ mod tests {}#[test]- fn pane_state_defaults_to_read_only() {+ fn pane_starts_without_session() {let s = GrokPaneState::new();- assert_eq!(s.mode, AgentMode::ReadOnly);- assert_eq!(s.tab, BottomTab::Grok);- assert!(s.transcript.is_empty());assert!(s.session.is_none());- }-- #[test]- fn assistant_deltas_coalesce_into_one_bubble() {- let mut s = GrokPaneState::new();- s.ingest_events(vec![- AgentEvent::AssistantDelta { text: "hel".into() },- AgentEvent::AssistantDelta { text: "lo".into() },- AgentEvent::AssistantDelta { text: " world".into() },- ]);- assert_eq!(s.transcript.len(), 1);- match &s.transcript[0] {- TranscriptEntry::Assistant { markdown } => assert_eq!(markdown, "hello world"),- _ => panic!("expected assistant bubble"),- }- }-- #[test]- fn tool_call_finished_binds_to_pending_start() {- let mut s = GrokPaneState::new();- s.ingest_events(vec![- AgentEvent::ToolCallStarted {- id: "c1".into(),- name: "analyze".into(),- args_json: "{}".into(),- },- AgentEvent::ToolCallFinished {- id: "c1".into(),- ok: true,- summary: "42 fns".into(),- },- ]);- assert_eq!(s.transcript.len(), 1);- match &s.transcript[0] {- TranscriptEntry::ToolCall {- id, done: Some(res), ..- } => {- assert_eq!(id, "c1");- assert!(res.ok);- assert!(res.summary.contains("42"));- }- _ => panic!("expected finished tool card"),- }- }-- #[test]- fn child_exit_clears_session_and_notes_transcript() {- let mut s = GrokPaneState::new();- s.ingest_events(vec![AgentEvent::ChildExited { code: Some(1) }]);- assert!(s.session.is_none());- match s.transcript.last() {- Some(TranscriptEntry::Info { text }) => assert!(text.contains("exit=1")),- _ => panic!("expected info entry"),- }+ assert_eq!(s.tab, BottomTab::Grok);}}diff --git a/crates/ghidrust-gui/src/grok_term/ansi.rs b/crates/ghidrust-gui/src/grok_term/ansi.rsnew file mode 100644index 0000000..8137b1f--- /dev/null+++ b/crates/ghidrust-gui/src/grok_term/ansi.rs@@ -0,0 +1,969 @@+//! Minimal VT/ANSI parser + cell grid for hosting ratatui-style TUIs (Grok).+//!+//! Not a full xterm. Covers CUP/CUU/CUD/CUF/CUB, ED/EL, SGR (16/256/RGB),+//! DECSET/DECRST alt-screen + cursor visibility, DECSTBM scroll region, and+//! basic OSC ignore. Enough for Grok Build's TUI.++use std::cmp::{max, min};++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Color {+ pub r: u8,+ pub g: u8,+ pub b: u8,+}++impl Color {+ pub const fn rgb(r: u8, g: u8, b: u8) -> Self {+ Self { r, g, b }+ }+}++pub const DEFAULT_FG: Color = Color::rgb(0xD4, 0xD4, 0xD4);+pub const DEFAULT_BG: Color = Color::rgb(0x12, 0x12, 0x12);++#[derive(Clone, Copy, Debug)]+pub struct CellAttr {+ pub fg: Color,+ pub bg: Color,+ pub bold: bool,+ pub dim: bool,+ pub italic: bool,+ pub underline: bool,+ pub reverse: bool,+}++impl Default for CellAttr {+ fn default() -> Self {+ Self {+ fg: DEFAULT_FG,+ bg: DEFAULT_BG,+ bold: false,+ dim: false,+ italic: false,+ underline: false,+ reverse: false,+ }+ }+}++#[derive(Clone, Copy, Debug)]+pub struct Cell {+ pub ch: char,+ pub attr: CellAttr,+ /// True if this cell is the trailing half of a double-width glyph.+ pub wide_cont: bool,+}++impl Default for Cell {+ fn default() -> Self {+ Self {+ ch: ' ',+ attr: CellAttr::default(),+ wide_cont: false,+ }+ }+}++/// Terminal cell width (0 / 1 / 2).+///+/// Must match ratatui/crossterm (`unicode-width`). A hand-rolled table that+/// forced misc symbols/dingbats to width 2 sheared Grok's braille logo and+/// shoved the cursor onto the wrong row.+pub fn char_cell_width(ch: char) -> usize {+ use unicode_width::UnicodeWidthChar;+ UnicodeWidthChar::width(ch).unwrap_or(0)+}++#[derive(Clone, Debug)]+struct Buffer {+ cols: usize,+ rows: usize,+ cells: Vec<Cell>,+}++impl Buffer {+ fn new(cols: usize, rows: usize) -> Self {+ Self {+ cols: cols.max(1),+ rows: rows.max(1),+ cells: vec![Cell::default(); cols.max(1) * rows.max(1)],+ }+ }++ fn idx(&self, col: usize, row: usize) -> usize {+ row * self.cols + col+ }++ fn get(&self, col: usize, row: usize) -> Cell {+ if col < self.cols && row < self.rows {+ self.cells[self.idx(col, row)]+ } else {+ Cell::default()+ }+ }++ fn set(&mut self, col: usize, row: usize, cell: Cell) {+ if col < self.cols && row < self.rows {+ let i = self.idx(col, row);+ self.cells[i] = cell;+ }+ }++ fn clear_all(&mut self, attr: CellAttr) {+ let blank = Cell {+ ch: ' ',+ attr,+ wide_cont: false,+ };+ for c in &mut self.cells {+ *c = blank;+ }+ }++ fn clear_line_range(&mut self, row: usize, start: usize, end: usize, attr: CellAttr) {+ if row >= self.rows {+ return;+ }+ let blank = Cell {+ ch: ' ',+ attr,+ wide_cont: false,+ };+ for col in start..min(end, self.cols) {+ self.set(col, row, blank);+ }+ }++ /// Clear a cell and, if it was (or was next to) a wide glyph, its pair.+ fn clear_cell_wide_safe(&mut self, col: usize, row: usize, attr: CellAttr) {+ if row >= self.rows || col >= self.cols {+ return;+ }+ let blank = Cell {+ ch: ' ',+ attr,+ wide_cont: false,+ };+ let cur = self.get(col, row);+ if cur.wide_cont && col > 0 {+ self.set(col - 1, row, blank);+ }+ if !cur.wide_cont && char_cell_width(cur.ch) == 2 && col + 1 < self.cols {+ self.set(col + 1, row, blank);+ }+ self.set(col, row, blank);+ }++ fn scroll_up(&mut self, top: usize, bottom: usize, n: usize, attr: CellAttr) {+ if top >= bottom || top >= self.rows {+ return;+ }+ let bot = min(bottom, self.rows - 1);+ let n = n.min(bot - top + 1);+ let blank = Cell {+ ch: ' ',+ attr,+ wide_cont: false,+ };+ for row in top..=(bot - n) {+ for col in 0..self.cols {+ let src = self.get(col, row + n);+ self.set(col, row, src);+ }+ }+ for row in (bot + 1 - n)..=bot {+ for col in 0..self.cols {+ self.set(col, row, blank);+ }+ }+ }++ fn scroll_down(&mut self, top: usize, bottom: usize, n: usize, attr: CellAttr) {+ if top >= bottom || top >= self.rows {+ return;+ }+ let bot = min(bottom, self.rows - 1);+ let n = n.min(bot - top + 1);+ let blank = Cell {+ ch: ' ',+ attr,+ wide_cont: false,+ };+ for row in (top + n..=bot).rev() {+ for col in 0..self.cols {+ let src = self.get(col, row - n);+ self.set(col, row, src);+ }+ }+ for row in top..(top + n) {+ for col in 0..self.cols {+ self.set(col, row, blank);+ }+ }+ }++ fn resize(&mut self, cols: usize, rows: usize) {+ let cols = cols.max(1);+ let rows = rows.max(1);+ let mut next = Buffer::new(cols, rows);+ for r in 0..min(self.rows, rows) {+ for c in 0..min(self.cols, cols) {+ next.set(c, r, self.get(c, r));+ }+ }+ *self = next;+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ParseState {+ Ground,+ Esc,+ Csi,+ Osc,+ OscEsc,+}++/// Screen state consumed by the egui painter.+pub struct TerminalGrid {+ primary: Buffer,+ alt: Buffer,+ use_alt: bool,+ pub cursor_col: usize,+ pub cursor_row: usize,+ pub cursor_visible: bool,+ attr: CellAttr,+ scroll_top: usize,+ scroll_bottom: usize,+ saved_cursor: Option<(usize, usize)>,+ state: ParseState,+ csi_buf: String,+ osc_buf: String,+ utf8: Utf8Decoder,+}++struct Utf8Decoder {+ buf: [u8; 4],+ len: usize,+ expected: usize,+}++impl Utf8Decoder {+ fn new() -> Self {+ Self {+ buf: [0; 4],+ len: 0,+ expected: 0,+ }+ }++ fn push(&mut self, b: u8) -> Option<char> {+ if self.expected == 0 {+ if b < 0x80 {+ return Some(b as char);+ }+ self.expected = if b & 0xE0 == 0xC0 {+ 2+ } else if b & 0xF0 == 0xE0 {+ 3+ } else if b & 0xF8 == 0xF0 {+ 4+ } else {+ return Some('\u{FFFD}');+ };+ self.buf[0] = b;+ self.len = 1;+ return None;+ }+ if b & 0xC0 != 0x80 {+ self.expected = 0;+ self.len = 0;+ return Some('\u{FFFD}');+ }+ self.buf[self.len] = b;+ self.len += 1;+ if self.len == self.expected {+ let s = std::str::from_utf8(&self.buf[..self.len]).ok();+ self.expected = 0;+ self.len = 0;+ s.and_then(|t| t.chars().next()).or(Some('\u{FFFD}'))+ } else {+ None+ }+ }+}++impl TerminalGrid {+ pub fn new(cols: usize, rows: usize) -> Self {+ let cols = cols.max(1);+ let rows = rows.max(1);+ Self {+ primary: Buffer::new(cols, rows),+ alt: Buffer::new(cols, rows),+ use_alt: false,+ cursor_col: 0,+ cursor_row: 0,+ cursor_visible: true,+ attr: CellAttr::default(),+ scroll_top: 0,+ scroll_bottom: rows - 1,+ saved_cursor: None,+ state: ParseState::Ground,+ csi_buf: String::new(),+ osc_buf: String::new(),+ utf8: Utf8Decoder::new(),+ }+ }++ pub fn cols(&self) -> usize {+ self.active().cols+ }++ pub fn rows(&self) -> usize {+ self.active().rows+ }++ pub fn cell(&self, col: usize, row: usize) -> Cell {+ self.active().get(col, row)+ }++ fn active(&self) -> &Buffer {+ if self.use_alt {+ &self.alt+ } else {+ &self.primary+ }+ }++ fn active_mut(&mut self) -> &mut Buffer {+ if self.use_alt {+ &mut self.alt+ } else {+ &mut self.primary+ }+ }++ pub fn resize(&mut self, cols: usize, rows: usize) {+ let cols = cols.max(1);+ let rows = rows.max(1);+ self.primary.resize(cols, rows);+ self.alt.resize(cols, rows);+ self.cursor_col = min(self.cursor_col, cols - 1);+ self.cursor_row = min(self.cursor_row, rows - 1);+ self.scroll_top = 0;+ self.scroll_bottom = rows - 1;+ }++ pub fn feed_bytes(&mut self, data: &[u8]) {+ for &b in data {+ self.feed_byte(b);+ }+ }++ fn feed_byte(&mut self, b: u8) {+ match self.state {+ ParseState::Ground => {+ if b == 0x1b {+ self.state = ParseState::Esc;+ } else if b == 0x08 {+ self.backspace();+ } else if b == 0x09 {+ self.tab();+ } else if b == b'\n' || b == 0x0b || b == 0x0c {+ // VT LF: move down only. Ratatui sends CUP/`\r` explicitly;+ // forcing CR here desyncs cursor row vs absolute addresses.+ self.linefeed();+ } else if b == b'\r' {+ self.cursor_col = 0;+ } else if b == 0x07 {+ // BEL — ignore+ } else if let Some(ch) = self.utf8.push(b) {+ if !ch.is_control() {+ self.put_char(ch);+ }+ }+ }+ ParseState::Esc => match b {+ b'[' => {+ self.csi_buf.clear();+ self.state = ParseState::Csi;+ }+ b']' => {+ self.osc_buf.clear();+ self.state = ParseState::Osc;+ }+ b'7' => {+ self.saved_cursor = Some((self.cursor_col, self.cursor_row));+ self.state = ParseState::Ground;+ }+ b'8' => {+ if let Some((c, r)) = self.saved_cursor {+ self.cursor_col = c;+ self.cursor_row = r;+ }+ self.state = ParseState::Ground;+ }+ b'c' => {+ // RIS — soft reset+ self.attr = CellAttr::default();+ self.cursor_col = 0;+ self.cursor_row = 0;+ self.cursor_visible = true;+ self.scroll_top = 0;+ self.scroll_bottom = self.rows().saturating_sub(1);+ self.state = ParseState::Ground;+ }+ b'D' => {+ self.linefeed();+ self.state = ParseState::Ground;+ }+ b'M' => {+ self.reverse_index();+ self.state = ParseState::Ground;+ }+ b'E' => {+ self.cursor_col = 0;+ self.linefeed();+ self.state = ParseState::Ground;+ }+ _ => self.state = ParseState::Ground,+ },+ ParseState::Csi => {+ if (0x40..=0x7E).contains(&b) {+ let params = std::mem::take(&mut self.csi_buf);+ self.dispatch_csi(¶ms, b as char);+ self.state = ParseState::Ground;+ } else if self.csi_buf.len() < 256 {+ self.csi_buf.push(b as char);+ }+ }+ ParseState::Osc => {+ if b == 0x07 {+ self.osc_buf.clear();+ self.state = ParseState::Ground;+ } else if b == 0x1b {+ self.state = ParseState::OscEsc;+ } else if self.osc_buf.len() < 512 {+ self.osc_buf.push(b as char);+ }+ }+ ParseState::OscEsc => {+ if b == b'\\' {+ self.osc_buf.clear();+ }+ self.state = ParseState::Ground;+ }+ }+ }++ fn put_char(&mut self, ch: char) {+ let width = char_cell_width(ch);+ if width == 0 {+ return;+ }+ let cols = self.cols();+ let rows = self.rows();+ if self.cursor_col >= cols {+ self.cursor_col = 0;+ self.linefeed();+ }+ // Not enough room for a wide glyph on this line — wrap first.+ if width == 2 && self.cursor_col + 1 >= cols {+ self.cursor_col = 0;+ self.linefeed();+ }+ let attr = self.attr;+ let col = self.cursor_col;+ let row = min(self.cursor_row, rows - 1);+ // Break any wide glyph we are about to overwrite.+ self.active_mut().clear_cell_wide_safe(col, row, attr);+ if width == 2 {+ self.active_mut().clear_cell_wide_safe(col + 1, row, attr);+ self.active_mut().set(+ col,+ row,+ Cell {+ ch,+ attr,+ wide_cont: false,+ },+ );+ self.active_mut().set(+ col + 1,+ row,+ Cell {+ ch: ' ',+ attr,+ wide_cont: true,+ },+ );+ self.cursor_col = col + 2;+ } else {+ self.active_mut().set(+ col,+ row,+ Cell {+ ch,+ attr,+ wide_cont: false,+ },+ );+ self.cursor_col = col + 1;+ }+ }++ fn backspace(&mut self) {+ if self.cursor_col > 0 {+ self.cursor_col -= 1;+ }+ }++ fn tab(&mut self) {+ let next = ((self.cursor_col / 8) + 1) * 8;+ self.cursor_col = min(next, self.cols().saturating_sub(1));+ }++ fn linefeed(&mut self) {+ let bottom = self.scroll_bottom;+ if self.cursor_row >= bottom {+ let top = self.scroll_top;+ let attr = self.attr;+ self.active_mut().scroll_up(top, bottom, 1, attr);+ } else {+ self.cursor_row += 1;+ }+ }++ fn reverse_index(&mut self) {+ if self.cursor_row <= self.scroll_top {+ let top = self.scroll_top;+ let bottom = self.scroll_bottom;+ let attr = self.attr;+ self.active_mut().scroll_down(top, bottom, 1, attr);+ } else {+ self.cursor_row -= 1;+ }+ }++ fn clamp_cursor(&mut self) {+ // Allow cursor_col == cols for VT "pending wrap" state.+ self.cursor_col = min(self.cursor_col, self.cols());+ self.cursor_row = min(self.cursor_row, self.rows().saturating_sub(1));+ }++ fn dispatch_csi(&mut self, params: &str, final_byte: char) {+ let (priv_prefix, body) = if let Some(rest) = params.strip_prefix('?') {+ (true, rest)+ } else if let Some(rest) = params.strip_prefix('>') {+ (true, rest)+ } else {+ (false, params)+ };+ let nums: Vec<i32> = if body.is_empty() {+ Vec::new()+ } else {+ body.split(';')+ .map(|p| p.parse::<i32>().unwrap_or(0))+ .collect()+ };+ let n = |i: usize, d: i32| nums.get(i).copied().filter(|&v| v > 0).unwrap_or(d);++ if priv_prefix {+ match final_byte {+ 'h' => {+ for m in &nums {+ match *m {+ 25 => self.cursor_visible = true,+ 1049 | 47 | 1047 => self.enter_alt(),+ _ => {}+ }+ }+ }+ 'l' => {+ for m in &nums {+ match *m {+ 25 => self.cursor_visible = false,+ 1049 | 47 | 1047 => self.leave_alt(),+ _ => {}+ }+ }+ }+ _ => {}+ }+ return;+ }++ match final_byte {+ 'A' => self.cursor_row = self.cursor_row.saturating_sub(n(0, 1) as usize),+ 'B' => {+ self.cursor_row = min(+ self.cursor_row + n(0, 1) as usize,+ self.rows().saturating_sub(1),+ )+ }+ 'C' => {+ self.cursor_col = min(self.cursor_col + n(0, 1) as usize, self.cols());+ }+ 'D' => self.cursor_col = self.cursor_col.saturating_sub(n(0, 1) as usize),+ 'H' | 'f' => {+ let row = max(n(0, 1), 1) as usize - 1;+ let col = max(n(1, 1), 1) as usize - 1;+ self.cursor_row = min(row, self.rows().saturating_sub(1));+ self.cursor_col = min(col, self.cols());+ }+ 'G' => {+ let col = max(n(0, 1), 1) as usize - 1;+ self.cursor_col = min(col, self.cols());+ }+ 'd' => {+ let row = max(n(0, 1), 1) as usize - 1;+ self.cursor_row = min(row, self.rows().saturating_sub(1));+ }+ 'J' => self.erase_display(nums.first().copied().unwrap_or(0)),+ 'K' => self.erase_line(nums.first().copied().unwrap_or(0)),+ 'X' => self.erase_chars(n(0, 1) as usize),+ 'P' => self.delete_chars(n(0, 1) as usize),+ '@' => self.insert_chars(n(0, 1) as usize),+ 's' => self.saved_cursor = Some((self.cursor_col, self.cursor_row)),+ 'u' => {+ if let Some((c, r)) = self.saved_cursor {+ self.cursor_col = c;+ self.cursor_row = r;+ }+ }+ 'm' => self.apply_sgr(&nums),+ 'r' => {+ let top = max(n(0, 1), 1) as usize - 1;+ let bottom = if nums.len() < 2 {+ self.rows().saturating_sub(1)+ } else {+ max(n(1, 1), 1) as usize - 1+ };+ self.scroll_top = min(top, self.rows().saturating_sub(1));+ self.scroll_bottom = min(bottom, self.rows().saturating_sub(1));+ if self.scroll_bottom < self.scroll_top {+ self.scroll_bottom = self.scroll_top;+ }+ self.cursor_col = 0;+ self.cursor_row = self.scroll_top;+ }+ 'L' => {+ let n = n(0, 1) as usize;+ let top = self.cursor_row;+ let bottom = self.scroll_bottom;+ let attr = self.attr;+ self.active_mut().scroll_down(top, bottom, n, attr);+ }+ 'M' => {+ let n = n(0, 1) as usize;+ let top = self.cursor_row;+ let bottom = self.scroll_bottom;+ let attr = self.attr;+ self.active_mut().scroll_up(top, bottom, n, attr);+ }+ 'S' => {+ let n = n(0, 1) as usize;+ let top = self.scroll_top;+ let bottom = self.scroll_bottom;+ let attr = self.attr;+ self.active_mut().scroll_up(top, bottom, n, attr);+ }+ 'T' => {+ let n = n(0, 1) as usize;+ let top = self.scroll_top;+ let bottom = self.scroll_bottom;+ let attr = self.attr;+ self.active_mut().scroll_down(top, bottom, n, attr);+ }+ 'n' if n(0, 0) == 6 => {+ // CPR — host would reply; we ignore (Grok rarely needs it in embedded view)+ }+ _ => {}+ }+ self.clamp_cursor();+ }++ fn enter_alt(&mut self) {+ if !self.use_alt {+ self.alt.clear_all(CellAttr::default());+ self.use_alt = true;+ self.cursor_col = 0;+ self.cursor_row = 0;+ }+ }++ fn leave_alt(&mut self) {+ if self.use_alt {+ self.use_alt = false;+ }+ }++ fn erase_display(&mut self, mode: i32) {+ let attr = self.attr;+ let cols = self.cols();+ let rows = self.rows();+ let crow = self.cursor_row;+ let ccol = self.cursor_col;+ match mode {+ 0 => {+ self.active_mut()+ .clear_line_range(crow, ccol, cols, attr);+ for r in (crow + 1)..rows {+ self.active_mut().clear_line_range(r, 0, cols, attr);+ }+ }+ 1 => {+ for r in 0..crow {+ self.active_mut().clear_line_range(r, 0, cols, attr);+ }+ self.active_mut().clear_line_range(crow, 0, ccol + 1, attr);+ }+ _ => self.active_mut().clear_all(attr),+ }+ }++ fn erase_line(&mut self, mode: i32) {+ let attr = self.attr;+ let cols = self.cols();+ let row = self.cursor_row;+ let col = min(self.cursor_col, cols.saturating_sub(1));+ match mode {+ 0 => self.active_mut().clear_line_range(row, col, cols, attr),+ 1 => self.active_mut().clear_line_range(row, 0, col + 1, attr),+ _ => self.active_mut().clear_line_range(row, 0, cols, attr),+ }+ }++ fn erase_chars(&mut self, n: usize) {+ let attr = self.attr;+ let cols = self.cols();+ let row = self.cursor_row;+ let start = min(self.cursor_col, cols);+ let end = min(start + n, cols);+ self.active_mut().clear_line_range(row, start, end, attr);+ }++ fn delete_chars(&mut self, n: usize) {+ let cols = self.cols();+ let row = self.cursor_row;+ let col = min(self.cursor_col, cols.saturating_sub(1));+ let n = n.min(cols - col);+ let attr = self.attr;+ let blank = Cell {+ ch: ' ',+ attr,+ wide_cont: false,+ };+ for c in col..(cols - n) {+ let src = self.active().get(c + n, row);+ self.active_mut().set(c, row, src);+ }+ for c in (cols - n)..cols {+ self.active_mut().set(c, row, blank);+ }+ }++ fn insert_chars(&mut self, n: usize) {+ let cols = self.cols();+ let row = self.cursor_row;+ let col = min(self.cursor_col, cols.saturating_sub(1));+ let n = n.min(cols - col);+ let attr = self.attr;+ let blank = Cell {+ ch: ' ',+ attr,+ wide_cont: false,+ };+ for c in ((col + n)..cols).rev() {+ let src = self.active().get(c - n, row);+ self.active_mut().set(c, row, src);+ }+ for c in col..(col + n) {+ self.active_mut().set(c, row, blank);+ }+ }++ fn apply_sgr(&mut self, nums: &[i32]) {+ if nums.is_empty() {+ self.attr = CellAttr::default();+ return;+ }+ let mut i = 0;+ while i < nums.len() {+ match nums[i] {+ 0 => self.attr = CellAttr::default(),+ 1 => self.attr.bold = true,+ 2 => self.attr.dim = true,+ 3 => self.attr.italic = true,+ 4 => self.attr.underline = true,+ 7 => self.attr.reverse = true,+ 22 => {+ self.attr.bold = false;+ self.attr.dim = false;+ }+ 23 => self.attr.italic = false,+ 24 => self.attr.underline = false,+ 27 => self.attr.reverse = false,+ 30..=37 => self.attr.fg = ansi16(nums[i] - 30, false),+ 39 => self.attr.fg = DEFAULT_FG,+ 40..=47 => self.attr.bg = ansi16(nums[i] - 40, false),+ 49 => self.attr.bg = DEFAULT_BG,+ 90..=97 => self.attr.fg = ansi16(nums[i] - 90, true),+ 100..=107 => self.attr.bg = ansi16(nums[i] - 100, true),+ 38 => {+ if let Some(c) = parse_extended_color(nums, &mut i) {+ self.attr.fg = c;+ }+ }+ 48 => {+ if let Some(c) = parse_extended_color(nums, &mut i) {+ self.attr.bg = c;+ }+ }+ _ => {}+ }+ i += 1;+ }+ }+}++fn parse_extended_color(nums: &[i32], i: &mut usize) -> Option<Color> {+ if *i + 1 >= nums.len() {+ return None;+ }+ match nums[*i + 1] {+ 5 => {+ if *i + 2 >= nums.len() {+ return None;+ }+ let idx = nums[*i + 2].clamp(0, 255) as u8;+ *i += 2;+ Some(xterm256(idx))+ }+ 2 => {+ if *i + 4 >= nums.len() {+ return None;+ }+ let r = nums[*i + 2].clamp(0, 255) as u8;+ let g = nums[*i + 3].clamp(0, 255) as u8;+ let b = nums[*i + 4].clamp(0, 255) as u8;+ *i += 4;+ Some(Color::rgb(r, g, b))+ }+ _ => None,+ }+}++fn ansi16(idx: i32, bright: bool) -> Color {+ let base = match idx {+ 0 => (0, 0, 0),+ 1 => (0xCD, 0x31, 0x31),+ 2 => (0x0D, 0xBC, 0x79),+ 3 => (0xE5, 0xC0, 0x7B),+ 4 => (0x61, 0xAF, 0xEF),+ 5 => (0xC6, 0x78, 0xDD),+ 6 => (0x56, 0xB6, 0xC2),+ _ => (0xAB, 0xB2, 0xBF),+ };+ if bright {+ Color::rgb(+ (base.0 as u16 + 40).min(255) as u8,+ (base.1 as u16 + 40).min(255) as u8,+ (base.2 as u16 + 40).min(255) as u8,+ )+ } else {+ Color::rgb(base.0, base.1, base.2)+ }+}++fn xterm256(idx: u8) -> Color {+ if idx < 16 {+ return ansi16((idx % 8) as i32, idx >= 8);+ }+ if idx >= 232 {+ let v = 8 + 10 * (idx - 232);+ return Color::rgb(v, v, v);+ }+ let i = idx - 16;+ let r = i / 36;+ let g = (i % 36) / 6;+ let b = i % 6;+ let level = |n: u8| if n == 0 { 0 } else { 55 + 40 * n };+ Color::rgb(level(r), level(g), level(b))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn cup_and_print() {+ let mut g = TerminalGrid::new(80, 24);+ g.feed_bytes(b"\x1b[2;3Hhi");+ assert_eq!(g.cell(2, 1).ch, 'h');+ assert_eq!(g.cell(3, 1).ch, 'i');+ }++ #[test]+ fn sgr_red_then_reset() {+ let mut g = TerminalGrid::new(40, 10);+ g.feed_bytes(b"\x1b[31mX\x1b[0mY");+ assert_eq!(g.cell(0, 0).attr.fg, ansi16(1, false));+ assert_eq!(g.cell(1, 0).attr.fg, DEFAULT_FG);+ }++ #[test]+ fn alt_screen_toggle() {+ let mut g = TerminalGrid::new(20, 5);+ g.feed_bytes(b"A");+ g.feed_bytes(b"\x1b[?1049h");+ assert_eq!(g.cell(0, 0).ch, ' ');+ g.feed_bytes(b"B");+ assert_eq!(g.cell(0, 0).ch, 'B');+ g.feed_bytes(b"\x1b[?1049l");+ assert_eq!(g.cell(0, 0).ch, 'A');+ }++ #[test]+ fn wide_char_consumes_two_cells() {+ let mut g = TerminalGrid::new(10, 3);+ // U+1F7E2 large green circle (emoji, width 2)+ g.feed_bytes("\u{1F7E2}X".as_bytes());+ assert_eq!(g.cell(0, 0).ch, '\u{1F7E2}');+ assert!(g.cell(1, 0).wide_cont);+ assert_eq!(g.cell(2, 0).ch, 'X');+ assert_eq!(g.cursor_col, 3);+ }++ #[test]+ fn braille_and_box_drawing_are_single_cell() {+ // Grok's logo uses braille; box borders use U+2500. Width 2 shears both.+ assert_eq!(char_cell_width('\u{28FF}'), 1);+ assert_eq!(char_cell_width('─'), 1);+ assert_eq!(char_cell_width('│'), 1);+ assert_eq!(char_cell_width('★'), 1); // ambiguous — terminals treat as 1+ }++ #[test]+ fn cr_then_overwrite_without_el_leaves_tail() {+ // Documents VT behavior: without EL, leftovers remain (TUIs should EL).+ let mut g = TerminalGrid::new(20, 2);+ g.feed_bytes(b"Working... 2.2s");+ g.feed_bytes(b"\rResponding");+ assert_eq!(g.cell(0, 0).ch, 'R');+ // 'g' from Working still at col 10 if not erased — proves EL is needed;+ // our host must at least not scramble columns.+ assert_eq!(g.cursor_col, "Responding".len());+ }++ #[test]+ fn erase_line_clears_tail_after_cr() {+ let mut g = TerminalGrid::new(20, 2);+ g.feed_bytes(b"Working... 2.2s");+ g.feed_bytes(b"\r\x1b[KResponding");+ let line: String = (0..20).map(|c| g.cell(c, 0).ch).collect();+ assert!(line.starts_with("Responding"));+ assert!(!line.contains('W'));+ }+}diff --git a/crates/ghidrust-gui/src/grok_term/fonts.rs b/crates/ghidrust-gui/src/grok_term/fonts.rsnew file mode 100644index 0000000..cc5d061--- /dev/null+++ b/crates/ghidrust-gui/src/grok_term/fonts.rs@@ -0,0 +1,118 @@+//! Install a terminal-capable monospace font so Grok's logo / box-drawing+//! glyphs are not tofu (▯).+//!+//! egui's built-in ProggyClean covers little beyond ASCII. Grok Build's TUI+//! uses Unicode block elements, box drawing, and often braille half-tone art+//! — those need Cascadia / Consolas / a symbols fallback.++use eframe::egui::{FontData, FontDefinitions, FontFamily};+use std::path::PathBuf;++/// Prefer these system fonts (first existing file wins as primary monospace).+fn candidate_mono_paths() -> Vec<PathBuf> {+ let mut out = Vec::new();+ #[cfg(windows)]+ {+ if let Ok(windir) = std::env::var("WINDIR") {+ let fonts = PathBuf::from(windir).join("Fonts");+ for name in [+ "CascadiaMono.ttf",+ "cascadiamono.ttf",+ "CascadiaCode.ttf",+ "consola.ttf",+ "cour.ttf",+ "lucon.ttf", // Lucida Console+ ] {+ out.push(fonts.join(name));+ }+ // Symbol / emoji coverage for leftover glyphs.+ out.push(fonts.join("seguisym.ttf")); // Segoe UI Symbol+ out.push(fonts.join("seguiemj.ttf")); // Segoe UI Emoji+ out.push(fonts.join("msyh.ttc")); // Microsoft YaHei (CJK + some symbols)+ }+ }+ #[cfg(target_os = "macos")]+ {+ out.push(PathBuf::from("/System/Library/Fonts/Menlo.ttc"));+ out.push(PathBuf::from("/System/Library/Fonts/Supplemental/Courier New.ttf"));+ out.push(PathBuf::from("/System/Library/Fonts/Apple Symbols.ttf"));+ }+ #[cfg(target_os = "linux")]+ {+ for p in [+ "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",+ "/usr/share/fonts/TTF/DejaVuSansMono.ttf",+ "/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf",+ "/usr/share/fonts/truetype/noto/NotoSansMono-Regular.ttf",+ ] {+ out.push(PathBuf::from(p));+ }+ }+ out+}++/// Replace egui's default monospace with a system terminal font + symbol fallbacks.+///+/// Safe to call once at app start. No-op (keeps defaults) if no candidate loads.+pub fn install_terminal_fonts(ctx: &eframe::egui::Context) {+ let mut fonts = FontDefinitions::default();+ let mut loaded: Vec<String> = Vec::new();++ for path in candidate_mono_paths() {+ let Ok(bytes) = std::fs::read(&path) else {+ continue;+ };+ // Skip tiny/invalid reads.+ if bytes.len() < 1024 {+ continue;+ }+ let key = format!(+ "term_{}",+ path.file_stem()+ .and_then(|s| s.to_str())+ .unwrap_or("font")+ .to_ascii_lowercase()+ );+ if fonts.font_data.contains_key(&key) {+ continue;+ }+ fonts+ .font_data+ .insert(key.clone(), FontData::from_owned(bytes).into());+ loaded.push(key);+ }++ if loaded.is_empty() {+ return;+ }++ // Primary mono = first candidate; remaining act as fallbacks for missing glyphs.+ let mono = fonts+ .families+ .entry(FontFamily::Monospace)+ .or_default();+ // Put our fonts first; keep egui defaults after as last resort.+ let mut rest = mono.clone();+ mono.clear();+ for k in &loaded {+ mono.push(k.clone());+ }+ for k in rest.drain(..) {+ if !mono.contains(&k) {+ mono.push(k);+ }+ }++ // Also prepend to Proportional so UI chrome can fall back if needed.+ let prop = fonts+ .families+ .entry(FontFamily::Proportional)+ .or_default();+ for k in loaded.iter().rev() {+ if !prop.contains(k) {+ prop.insert(0, k.clone());+ }+ }++ ctx.set_fonts(fonts);+}diff --git a/crates/ghidrust-gui/src/grok_term/mod.rs b/crates/ghidrust-gui/src/grok_term/mod.rsnew file mode 100644index 0000000..80fb145--- /dev/null+++ b/crates/ghidrust-gui/src/grok_term/mod.rs@@ -0,0 +1,14 @@+//! Hand-rolled in-pane PTY terminal hosting the real Grok Build TUI.+//!+//! No crates.io terminal stacks (`egui_term`, `alacritty_terminal`, `vte`, …).+//! Patterns referenced from Harzu/egui_term + Windows ConPTY docs; code is ours.++mod ansi;+mod fonts;+mod pty;+mod session;+mod view;++pub use fonts::install_terminal_fonts;+pub use session::GrokTermSession;+pub use view::show_terminal;diff --git a/crates/ghidrust-gui/src/grok_term/pty.rs b/crates/ghidrust-gui/src/grok_term/pty.rsnew file mode 100644index 0000000..4b3ba74--- /dev/null+++ b/crates/ghidrust-gui/src/grok_term/pty.rs@@ -0,0 +1,616 @@+//! Platform PTY / ConPTY host for spawning `grok` inside the GUI.+//!+//! Windows: ConPTY (`CreatePseudoConsole`). Unix: `openpty` + fork/exec.+//! No crates.io terminal stacks — only `windows-sys` / `libc` FFI.++use std::io;+use std::path::Path;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;++/// Alive PTY session: write keys, read output, resize, kill.+pub struct PtySession {+ writer: PtyWriter,+ pub child_alive: Arc<AtomicBool>,+ killer: PtyKiller,+ #[cfg(windows)]+ hpcon: windows_sys::Win32::System::Console::HPCON,+ cols: u16,+ rows: u16,+}++pub struct PtyWriter {+ #[cfg(windows)]+ handle: windows_sys::Win32::Foundation::HANDLE,+ #[cfg(unix)]+ fd: std::os::unix::io::RawFd,+}++unsafe impl Send for PtyWriter {}++struct PtyKiller {+ #[cfg(windows)]+ process: windows_sys::Win32::Foundation::HANDLE,+ #[cfg(unix)]+ pid: libc::pid_t,+}++// HANDLEs / fds are exclusively owned by this session.+unsafe impl Send for PtySession {}+unsafe impl Send for PtyKiller {}++impl PtySession {+ pub fn spawn(+ program: &Path,+ args: &[String],+ cwd: &Path,+ cols: u16,+ rows: u16,+ ) -> io::Result<(Self, PtyReader)> {+ #[cfg(windows)]+ {+ windows::spawn(program, args, cwd, cols, rows)+ }+ #[cfg(unix)]+ {+ unix::spawn(program, args, cwd, cols, rows)+ }+ #[cfg(not(any(windows, unix)))]+ {+ let _ = (program, args, cwd, cols, rows);+ Err(io::Error::new(+ io::ErrorKind::Unsupported,+ "PTY not supported on this platform",+ ))+ }+ }++ pub fn write_all(&self, data: &[u8]) -> io::Result<()> {+ self.writer.write_all(data)+ }++ pub fn resize(&mut self, cols: u16, rows: u16) -> io::Result<()> {+ if cols == 0 || rows == 0 || (cols == self.cols && rows == self.rows) {+ return Ok(());+ }+ self.cols = cols;+ self.rows = rows;+ #[cfg(windows)]+ {+ windows::resize(self.hpcon, cols, rows)+ }+ #[cfg(unix)]+ {+ unix::resize(self.writer.fd, cols, rows)+ }+ #[cfg(not(any(windows, unix)))]+ {+ Ok(())+ }+ }++}++impl Drop for PtySession {+ fn drop(&mut self) {+ self.killer.kill();+ #[cfg(windows)]+ {+ windows::close_hpcon(self.hpcon);+ windows::close_handle(self.writer.handle);+ }+ #[cfg(unix)]+ {+ unsafe {+ let _ = libc::close(self.writer.fd);+ }+ }+ }+}++impl PtyKiller {+ fn kill(&self) {+ #[cfg(windows)]+ {+ windows::terminate(self.process);+ }+ #[cfg(unix)]+ {+ unsafe {+ let _ = libc::kill(self.pid, libc::SIGTERM);+ }+ }+ }+}++impl PtyWriter {+ fn write_all(&self, data: &[u8]) -> io::Result<()> {+ #[cfg(windows)]+ {+ windows::write_handle(self.handle, data)+ }+ #[cfg(unix)]+ {+ unix::write_fd(self.fd, data)+ }+ #[cfg(not(any(windows, unix)))]+ {+ let _ = data;+ Err(io::Error::new(io::ErrorKind::Unsupported, "no pty"))+ }+ }+}++/// Readable half — owned by the background reader thread.+pub struct PtyReader {+ #[cfg(windows)]+ handle: windows_sys::Win32::Foundation::HANDLE,+ #[cfg(unix)]+ fd: std::os::unix::io::RawFd,+ child_alive: Arc<AtomicBool>,+ #[cfg(windows)]+ process: windows_sys::Win32::Foundation::HANDLE,+ #[cfg(unix)]+ pid: libc::pid_t,+}++unsafe impl Send for PtyReader {}++impl PtyReader {+ /// Block until bytes arrive or the child exits. Returns `Ok(0)` on EOF/exit.+ pub fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {+ #[cfg(windows)]+ {+ let n = windows::read_handle(self.handle, buf)?;+ if n == 0 {+ self.child_alive.store(false, Ordering::Relaxed);+ } else if !windows::process_alive(self.process) {+ // Drain remaining then mark dead on next zero read.+ }+ Ok(n)+ }+ #[cfg(unix)]+ {+ let n = unix::read_fd(self.fd, buf)?;+ if n == 0 {+ self.child_alive.store(false, Ordering::Relaxed);+ } else {+ let mut status = 0;+ let r = unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) };+ if r == self.pid {+ self.child_alive.store(false, Ordering::Relaxed);+ }+ }+ Ok(n)+ }+ #[cfg(not(any(windows, unix)))]+ {+ let _ = buf;+ Ok(0)+ }+ }+}++impl Drop for PtyReader {+ fn drop(&mut self) {+ #[cfg(windows)]+ {+ windows::close_handle(self.handle);+ windows::close_handle(self.process);+ }+ #[cfg(unix)]+ {+ unsafe {+ let _ = libc::close(self.fd);+ }+ }+ }+}++#[cfg(windows)]+mod windows {+ use super::*;+ use std::ffi::OsStr;+ use std::os::windows::ffi::OsStrExt;+ use std::ptr;+ use windows_sys::Win32::Foundation::{+ CloseHandle, DuplicateHandle, FALSE, HANDLE, INVALID_HANDLE_VALUE, DUPLICATE_SAME_ACCESS,+ };+ use windows_sys::Win32::System::Console::{+ ClosePseudoConsole, CreatePseudoConsole, ResizePseudoConsole, COORD, HPCON,+ };+ use windows_sys::Win32::System::Pipes::CreatePipe;+ use windows_sys::Win32::System::Threading::{+ CreateProcessW, DeleteProcThreadAttributeList, GetExitCodeProcess, GetCurrentProcess,+ InitializeProcThreadAttributeList, TerminateProcess, UpdateProcThreadAttribute,+ CREATE_UNICODE_ENVIRONMENT, EXTENDED_STARTUPINFO_PRESENT, PROCESS_INFORMATION,+ PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, STARTUPINFOEXW, STARTUPINFOW,+ };++ const STILL_ACTIVE: u32 = 259;++ pub fn spawn(+ program: &Path,+ args: &[String],+ cwd: &Path,+ cols: u16,+ rows: u16,+ ) -> io::Result<(PtySession, PtyReader)> {+ unsafe {+ let mut input_read = INVALID_HANDLE_VALUE;+ let mut input_write = INVALID_HANDLE_VALUE;+ let mut output_read = INVALID_HANDLE_VALUE;+ let mut output_write = INVALID_HANDLE_VALUE;++ if CreatePipe(&mut input_read, &mut input_write, ptr::null(), 0) == 0 {+ return Err(io::Error::last_os_error());+ }+ if CreatePipe(&mut output_read, &mut output_write, ptr::null(), 0) == 0 {+ close_handle(input_read);+ close_handle(input_write);+ return Err(io::Error::last_os_error());+ }++ let size = COORD {+ X: cols as i16,+ Y: rows as i16,+ };+ let mut hpcon: HPCON = 0;+ let hr = CreatePseudoConsole(size, input_read, output_write, 0, &mut hpcon);+ // Host keeps input_write (to child stdin) and output_read (from child stdout).+ // Pseudo console owns input_read + output_write copies — close our extras.+ close_handle(input_read);+ close_handle(output_write);+ if hr != 0 {+ close_handle(input_write);+ close_handle(output_read);+ return Err(io::Error::from_raw_os_error(hr));+ }++ let mut attr_size = 0usize;+ let _ = InitializeProcThreadAttributeList(ptr::null_mut(), 1, 0, &mut attr_size);+ let mut attr_buf = vec![0u8; attr_size];+ let attr_list = attr_buf.as_mut_ptr().cast();+ if InitializeProcThreadAttributeList(attr_list, 1, 0, &mut attr_size) == 0 {+ ClosePseudoConsole(hpcon);+ close_handle(input_write);+ close_handle(output_read);+ return Err(io::Error::last_os_error());+ }+ if UpdateProcThreadAttribute(+ attr_list,+ 0,+ PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE as usize,+ hpcon as *mut _,+ std::mem::size_of::<HPCON>(),+ ptr::null_mut(),+ ptr::null_mut(),+ ) == 0+ {+ DeleteProcThreadAttributeList(attr_list);+ ClosePseudoConsole(hpcon);+ close_handle(input_write);+ close_handle(output_read);+ return Err(io::Error::last_os_error());+ }++ let mut si: STARTUPINFOEXW = std::mem::zeroed();+ si.StartupInfo.cb = std::mem::size_of::<STARTUPINFOEXW>() as u32;+ si.lpAttributeList = attr_list;++ let mut cmdline = wide_cmdline(program, args);+ let cwd_wide = wide_path(cwd);++ let mut pi: PROCESS_INFORMATION = std::mem::zeroed();+ let ok = CreateProcessW(+ ptr::null(),+ cmdline.as_mut_ptr(),+ ptr::null(),+ ptr::null(),+ FALSE,+ EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT,+ ptr::null(),+ cwd_wide.as_ptr(),+ &si.StartupInfo as *const STARTUPINFOW,+ &mut pi,+ );+ DeleteProcThreadAttributeList(attr_list);+ if ok == 0 {+ ClosePseudoConsole(hpcon);+ close_handle(input_write);+ close_handle(output_read);+ return Err(io::Error::last_os_error());+ }+ close_handle(pi.hThread);++ // Duplicate process handle for the reader thread (session also holds one).+ let mut reader_proc = INVALID_HANDLE_VALUE;+ if DuplicateHandle(+ GetCurrentProcess(),+ pi.hProcess,+ GetCurrentProcess(),+ &mut reader_proc,+ 0,+ FALSE,+ DUPLICATE_SAME_ACCESS,+ ) == 0+ {+ TerminateProcess(pi.hProcess, 1);+ close_handle(pi.hProcess);+ ClosePseudoConsole(hpcon);+ close_handle(input_write);+ close_handle(output_read);+ return Err(io::Error::last_os_error());+ }++ let child_alive = Arc::new(AtomicBool::new(true));+ let session = PtySession {+ writer: PtyWriter {+ handle: input_write,+ },+ child_alive: child_alive.clone(),+ killer: PtyKiller {+ process: pi.hProcess,+ },+ hpcon,+ cols,+ rows,+ };+ let reader = PtyReader {+ handle: output_read,+ child_alive,+ process: reader_proc,+ };+ Ok((session, reader))+ }+ }++ pub fn resize(hpcon: HPCON, cols: u16, rows: u16) -> io::Result<()> {+ let size = COORD {+ X: cols as i16,+ Y: rows as i16,+ };+ let hr = unsafe { ResizePseudoConsole(hpcon, size) };+ if hr == 0 {+ Ok(())+ } else {+ Err(io::Error::from_raw_os_error(hr))+ }+ }++ pub fn close_hpcon(hpcon: HPCON) {+ if hpcon != 0 {+ unsafe {+ ClosePseudoConsole(hpcon);+ }+ }+ }++ pub fn close_handle(h: HANDLE) {+ if !h.is_null() && h != INVALID_HANDLE_VALUE {+ unsafe {+ let _ = CloseHandle(h);+ }+ }+ }++ pub fn terminate(process: HANDLE) {+ unsafe {+ let _ = TerminateProcess(process, 1);+ close_handle(process);+ }+ }++ pub fn process_alive(process: HANDLE) -> bool {+ let mut code = 0u32;+ unsafe {+ if GetExitCodeProcess(process, &mut code) == 0 {+ return false;+ }+ }+ code == STILL_ACTIVE+ }++ pub fn write_handle(handle: HANDLE, data: &[u8]) -> io::Result<()> {+ use std::io::Write;+ use std::os::windows::io::{FromRawHandle, IntoRawHandle};+ // Temporarily wrap without taking ownership for the write call.+ let mut file = unsafe { std::fs::File::from_raw_handle(handle) };+ let result = file.write_all(data);+ let _ = file.into_raw_handle();+ result+ }++ pub fn read_handle(handle: HANDLE, buf: &mut [u8]) -> io::Result<usize> {+ use std::io::Read;+ use std::os::windows::io::{FromRawHandle, IntoRawHandle};+ let mut file = unsafe { std::fs::File::from_raw_handle(handle) };+ let result = file.read(buf);+ let _ = file.into_raw_handle();+ match result {+ Ok(n) => Ok(n),+ Err(e)+ if e.raw_os_error() == Some(109) || e.kind() == io::ErrorKind::BrokenPipe =>+ {+ Ok(0)+ }+ Err(e) => Err(e),+ }+ }++ fn wide_path(p: &Path) -> Vec<u16> {+ let mut v: Vec<u16> = p.as_os_str().encode_wide().collect();+ v.push(0);+ v+ }++ fn wide_cmdline(program: &Path, args: &[String]) -> Vec<u16> {+ let mut s = quote_arg(program.as_os_str());+ for a in args {+ s.push(' ');+ s.push_str("e_arg(OsStr::new(a)));+ }+ s.encode_utf16().chain(std::iter::once(0)).collect()+ }++ fn quote_arg(arg: &OsStr) -> String {+ let s = arg.to_string_lossy();+ if s.is_empty() {+ return "\"\"".into();+ }+ if !s.chars().any(|c| c == ' ' || c == '\t' || c == '"') {+ return s.into_owned();+ }+ let mut out = String::from("\"");+ let mut backslashes = 0;+ for c in s.chars() {+ match c {+ '\\' => backslashes += 1,+ '"' => {+ out.push_str(&"\\".repeat(backslashes * 2 + 1));+ out.push('"');+ backslashes = 0;+ }+ _ => {+ if backslashes > 0 {+ out.push_str(&"\\".repeat(backslashes));+ backslashes = 0;+ }+ out.push(c);+ }+ }+ }+ if backslashes > 0 {+ out.push_str(&"\\".repeat(backslashes * 2));+ }+ out.push('"');+ out+ }+}++#[cfg(unix)]+mod unix {+ use super::*;+ use std::ffi::CString;+ use std::os::unix::ffi::OsStrExt;+ use std::os::unix::io::RawFd;++ pub fn spawn(+ program: &Path,+ args: &[String],+ cwd: &Path,+ cols: u16,+ rows: u16,+ ) -> io::Result<(PtySession, PtyReader)> {+ let mut master: RawFd = -1;+ let mut slave: RawFd = -1;+ let mut win: libc::winsize = unsafe { std::mem::zeroed() };+ win.ws_col = cols;+ win.ws_row = rows;+ let rc = unsafe { libc::openpty(&mut master, &mut slave, std::ptr::null_mut(), std::ptr::null(), &win) };+ if rc != 0 {+ return Err(io::Error::last_os_error());+ }++ let pid = unsafe { libc::fork() };+ if pid < 0 {+ unsafe {+ libc::close(master);+ libc::close(slave);+ }+ return Err(io::Error::last_os_error());+ }+ if pid == 0 {+ // Child+ unsafe {+ let _ = libc::close(master);+ let _ = libc::setsid();+ let _ = libc::ioctl(slave, libc::TIOCSCTTY as _, 0);+ let _ = libc::dup2(slave, 0);+ let _ = libc::dup2(slave, 1);+ let _ = libc::dup2(slave, 2);+ if slave > 2 {+ let _ = libc::close(slave);+ }+ if let Ok(dir) = CString::new(cwd.as_os_str().as_bytes()) {+ let _ = libc::chdir(dir.as_ptr());+ }+ let prog = CString::new(program.as_os_str().as_bytes()).unwrap_or_default();+ let mut argv_c: Vec<CString> = Vec::new();+ argv_c.push(prog.clone());+ for a in args {+ if let Ok(c) = CString::new(a.as_str()) {+ argv_c.push(c);+ }+ }+ let mut argv_ptr: Vec<*const libc::c_char> =+ argv_c.iter().map(|c| c.as_ptr()).collect();+ argv_ptr.push(std::ptr::null());+ libc::execv(prog.as_ptr(), argv_ptr.as_ptr());+ libc::_exit(127);+ }+ }++ unsafe {+ let _ = libc::close(slave);+ }++ // Dup master so reader and writer each own a fd.+ let master_write = unsafe { libc::dup(master) };+ if master_write < 0 {+ unsafe {+ let _ = libc::kill(pid, libc::SIGTERM);+ let _ = libc::close(master);+ }+ return Err(io::Error::last_os_error());+ }++ let child_alive = Arc::new(AtomicBool::new(true));+ let session = PtySession {+ writer: PtyWriter { fd: master_write },+ child_alive: child_alive.clone(),+ killer: PtyKiller { pid },+ cols,+ rows,+ };+ let reader = PtyReader {+ fd: master,+ child_alive,+ pid,+ };+ Ok((session, reader))+ }++ pub fn resize(fd: RawFd, cols: u16, rows: u16) -> io::Result<()> {+ let mut win: libc::winsize = unsafe { std::mem::zeroed() };+ win.ws_col = cols;+ win.ws_row = rows;+ let rc = unsafe { libc::ioctl(fd, libc::TIOCSWINSZ, &win) };+ if rc == 0 {+ Ok(())+ } else {+ Err(io::Error::last_os_error())+ }+ }++ pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<()> {+ let mut off = 0;+ while off < data.len() {+ let n = unsafe { libc::write(fd, data[off..].as_ptr().cast(), data.len() - off) };+ if n < 0 {+ return Err(io::Error::last_os_error());+ }+ off += n as usize;+ }+ Ok(())+ }++ pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {+ let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };+ if n < 0 {+ Err(io::Error::last_os_error())+ } else {+ Ok(n as usize)+ }+ }+}diff --git a/crates/ghidrust-gui/src/grok_term/session.rs b/crates/ghidrust-gui/src/grok_term/session.rsnew file mode 100644index 0000000..09db5bf--- /dev/null+++ b/crates/ghidrust-gui/src/grok_term/session.rs@@ -0,0 +1,235 @@+//! Grok TUI session: spawn PTY, pump bytes into [`TerminalGrid`], accept input.++use super::ansi::TerminalGrid;+use super::pty::{PtyReader, PtySession};+use egui::Context;+use std::path::PathBuf;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::mpsc::{self, Receiver, Sender};+use std::sync::{Arc, Mutex};+use std::thread;++enum HostCmd {+ Write(Vec<u8>),+ Resize { cols: u16, rows: u16 },+ Shutdown,+}++/// Live embedded Grok TUI.+pub struct GrokTermSession {+ grid: Arc<Mutex<TerminalGrid>>,+ cmd_tx: Sender<HostCmd>,+ child_alive: Arc<AtomicBool>,+ exited: bool,+ last_cols: u16,+ last_rows: u16,+ pub project_root: PathBuf,+}++impl GrokTermSession {+ pub fn start(+ grok_bin: PathBuf,+ project_root: PathBuf,+ cols: u16,+ rows: u16,+ ctx: Context,+ ) -> Result<Self, String> {+ let cols = cols.max(20);+ let rows = rows.max(8);+ let (pty, reader) = PtySession::spawn(&grok_bin, &[], &project_root, cols, rows)+ .map_err(|e| format!("spawn grok PTY failed: {e}"))?;+ let child_alive = pty.child_alive.clone();+ let grid = Arc::new(Mutex::new(TerminalGrid::new(cols as usize, rows as usize)));+ let (cmd_tx, cmd_rx) = mpsc::channel::<HostCmd>();++ // Writer / resize / kill thread.+ thread::Builder::new()+ .name("ghidrust-grok-pty-ctl".into())+ .spawn(move || control_loop(pty, cmd_rx))+ .map_err(|e| format!("pty ctl thread: {e}"))?;++ // Reader thread → grid + repaint.+ let grid_r = grid.clone();+ let alive_r = child_alive.clone();+ thread::Builder::new()+ .name("ghidrust-grok-pty-read".into())+ .spawn(move || read_loop(reader, grid_r, alive_r, ctx))+ .map_err(|e| format!("pty read thread: {e}"))?;++ Ok(Self {+ grid,+ cmd_tx,+ child_alive,+ exited: false,+ last_cols: cols,+ last_rows: rows,+ project_root,+ })+ }++ pub fn grid(&self) -> Arc<Mutex<TerminalGrid>> {+ self.grid.clone()+ }++ pub fn write_bytes(&self, data: &[u8]) {+ let _ = self.cmd_tx.send(HostCmd::Write(data.to_vec()));+ }++ pub fn resize(&mut self, cols: u16, rows: u16) {+ let cols = cols.max(20);+ let rows = rows.max(8);+ if cols == self.last_cols && rows == self.last_rows {+ return;+ }+ self.last_cols = cols;+ self.last_rows = rows;+ if let Ok(mut g) = self.grid.lock() {+ g.resize(cols as usize, rows as usize);+ }+ let _ = self.cmd_tx.send(HostCmd::Resize { cols, rows });+ }++ pub fn poll_exited(&mut self) -> bool {+ if self.exited {+ return true;+ }+ if !self.child_alive.load(Ordering::Relaxed) {+ self.exited = true;+ true+ } else {+ false+ }+ }++ pub fn is_alive(&self) -> bool {+ !self.exited && self.child_alive.load(Ordering::Relaxed)+ }+}++impl Drop for GrokTermSession {+ fn drop(&mut self) {+ let _ = self.cmd_tx.send(HostCmd::Shutdown);+ }+}++fn control_loop(mut pty: PtySession, rx: Receiver<HostCmd>) {+ while let Ok(cmd) = rx.recv() {+ match cmd {+ HostCmd::Write(bytes) => {+ let _ = pty.write_all(&bytes);+ }+ HostCmd::Resize { cols, rows } => {+ let _ = pty.resize(cols, rows);+ }+ HostCmd::Shutdown => break,+ }+ }+ // PtySession Drop kills the child.+}++fn read_loop(+ mut reader: PtyReader,+ grid: Arc<Mutex<TerminalGrid>>,+ alive: Arc<AtomicBool>,+ ctx: Context,+) {+ let mut buf = [0u8; 8192];+ loop {+ match reader.read(&mut buf) {+ Ok(0) => {+ alive.store(false, Ordering::Relaxed);+ ctx.request_repaint();+ break;+ }+ Ok(n) => {+ if let Ok(mut g) = grid.lock() {+ g.feed_bytes(&buf[..n]);+ }+ ctx.request_repaint();+ }+ Err(_) => {+ alive.store(false, Ordering::Relaxed);+ ctx.request_repaint();+ break;+ }+ }+ }+}++/// Encode egui key events into bytes for the PTY (xterm-ish).+pub fn encode_key(key: egui::Key, modifiers: egui::Modifiers) -> Option<Vec<u8>> {+ use egui::Key;+ if modifiers.ctrl {+ if let Some(c) = key_to_char(key) {+ let b = (c.to_ascii_uppercase() as u8).wrapping_sub(b'@');+ if (1..=26).contains(&b) {+ return Some(vec![b]);+ }+ }+ if key == Key::Space {+ return Some(vec![0]);+ }+ }+ match key {+ Key::Enter => Some(vec![b'\r']),+ Key::Tab => Some(vec![b'\t']),+ Key::Backspace => Some(vec![0x7f]),+ Key::Escape => Some(vec![0x1b]),+ Key::ArrowUp => Some(b"\x1b[A".to_vec()),+ Key::ArrowDown => Some(b"\x1b[B".to_vec()),+ Key::ArrowRight => Some(b"\x1b[C".to_vec()),+ Key::ArrowLeft => Some(b"\x1b[D".to_vec()),+ Key::Home => Some(b"\x1b[H".to_vec()),+ Key::End => Some(b"\x1b[F".to_vec()),+ Key::PageUp => Some(b"\x1b[5~".to_vec()),+ Key::PageDown => Some(b"\x1b[6~".to_vec()),+ Key::Insert => Some(b"\x1b[2~".to_vec()),+ Key::Delete => Some(b"\x1b[3~".to_vec()),+ Key::F1 => Some(b"\x1bOP".to_vec()),+ Key::F2 => Some(b"\x1bOQ".to_vec()),+ Key::F3 => Some(b"\x1bOR".to_vec()),+ Key::F4 => Some(b"\x1bOS".to_vec()),+ Key::F5 => Some(b"\x1b[15~".to_vec()),+ Key::F6 => Some(b"\x1b[17~".to_vec()),+ Key::F7 => Some(b"\x1b[18~".to_vec()),+ Key::F8 => Some(b"\x1b[19~".to_vec()),+ Key::F9 => Some(b"\x1b[20~".to_vec()),+ Key::F10 => Some(b"\x1b[21~".to_vec()),+ Key::F11 => Some(b"\x1b[23~".to_vec()),+ Key::F12 => Some(b"\x1b[24~".to_vec()),+ _ => None,+ }+}++fn key_to_char(key: egui::Key) -> Option<char> {+ use egui::Key;+ Some(match key {+ Key::A => 'a',+ Key::B => 'b',+ Key::C => 'c',+ Key::D => 'd',+ Key::E => 'e',+ Key::F => 'f',+ Key::G => 'g',+ Key::H => 'h',+ Key::I => 'i',+ Key::J => 'j',+ Key::K => 'k',+ Key::L => 'l',+ Key::M => 'm',+ Key::N => 'n',+ Key::O => 'o',+ Key::P => 'p',+ Key::Q => 'q',+ Key::R => 'r',+ Key::S => 's',+ Key::T => 't',+ Key::U => 'u',+ Key::V => 'v',+ Key::W => 'w',+ Key::X => 'x',+ Key::Y => 'y',+ Key::Z => 'z',+ _ => return None,+ })+}diff --git a/crates/ghidrust-gui/src/grok_term/view.rs b/crates/ghidrust-gui/src/grok_term/view.rsnew file mode 100644index 0000000..ebd6833--- /dev/null+++ b/crates/ghidrust-gui/src/grok_term/view.rs@@ -0,0 +1,272 @@+//! egui painter for [`TerminalGrid`].++use super::ansi::{char_cell_width, Color, TerminalGrid, DEFAULT_BG};+use super::session::{encode_key, GrokTermSession};+use eframe::egui::{self, Color32, FontId, Key, Modifiers, Pos2, Rect, Sense, Ui, Vec2};++const FONT_SIZE: f32 = 13.0;++fn to_color32(c: Color) -> Color32 {+ Color32::from_rgb(c.r, c.g, c.b)+}++/// Paint the terminal and route keyboard/text input into the PTY.+///+/// `sticky_keys`: keep routing keys (especially Ctrl+C) after focus was granted,+/// until the parent clears capture (Console tab / Stop).+///+/// Returns `true` when this widget owns the keyboard (listing hotkeys must yield).+pub fn show_terminal(+ ui: &mut Ui,+ session: &mut GrokTermSession,+ request_focus: bool,+ sticky_keys: bool,+) -> bool {+ let font = FontId::monospace(FONT_SIZE);+ let galley = ui.fonts(|f| f.layout_no_wrap("W".into(), font.clone(), Color32::WHITE));+ // Integer cell metrics — fractional sizes drift vs ConPTY cols/rows.+ let cell_w = galley.size().x.ceil().max(7.0);+ let cell_h = galley.size().y.ceil().max(14.0);++ let avail = ui.available_size();+ let cols = ((avail.x / cell_w).floor() as u16).max(20);+ let rows = ((avail.y / cell_h).floor() as u16).max(8);+ session.resize(cols, rows);++ let size = Vec2::new(cols as f32 * cell_w, rows as f32 * cell_h);+ let (response, painter) = ui.allocate_painter(size, Sense::click_and_drag());+ let origin = response.rect.min;++ painter.rect_filled(response.rect, 0.0, to_color32(DEFAULT_BG));++ if let Ok(grid) = session.grid().lock() {+ paint_grid(ui, &painter, &grid, origin, cell_w, cell_h, &font);+ }++ if request_focus || response.clicked() {+ response.request_focus();+ }++ let hovered_keys = response.hovered()+ && ui.input(|i| {+ i.events.iter().any(|e| {+ matches!(+ e,+ egui::Event::Text(_)+ | egui::Event::Key {+ pressed: true,+ ..+ }+ )+ })+ });+ if hovered_keys {+ response.request_focus();+ }++ let focused = response.has_focus();+ // Hover / sticky: Ctrl+C must reach the PTY mid-generation even if egui+ // briefly loses widget focus (toolbar click, etc.).+ let capturing = focused || response.hovered() || sticky_keys;+ if capturing {+ handle_input(ui, session);+ }++ if session.is_alive() {+ ui.ctx().request_repaint();+ }++ focused || response.hovered() || sticky_keys+}++fn paint_grid(+ ui: &Ui,+ painter: &egui::Painter,+ grid: &TerminalGrid,+ origin: Pos2,+ cell_w: f32,+ cell_h: f32,+ font: &FontId,+) {+ let cols = grid.cols();+ let rows = grid.rows();+ for row in 0..rows {+ let mut col = 0;+ while col < cols {+ let cell = grid.cell(col, row);+ if cell.wide_cont {+ col += 1;+ continue;+ }++ let mut fg = cell.attr.fg;+ let mut bg = cell.attr.bg;+ if cell.attr.reverse {+ std::mem::swap(&mut fg, &mut bg);+ }+ if cell.attr.dim {+ fg.r /= 2;+ fg.g /= 2;+ fg.b /= 2;+ }++ let span = char_cell_width(cell.ch).max(1).min(cols - col);+ let x = origin.x + col as f32 * cell_w;+ let y = origin.y + row as f32 * cell_h;+ let rect =+ Rect::from_min_size(Pos2::new(x, y), Vec2::new(cell_w * span as f32, cell_h));++ painter.rect_filled(rect, 0.0, to_color32(bg));++ if cell.ch != ' ' && !cell.ch.is_control() {+ let clipped = painter.with_clip_rect(rect);+ // Vertically center the glyph in the cell so the block cursor+ // (full cell) lines up with `>` / text instead of looking one+ // row low under padded line height.+ let g = ui.fonts(|f| {+ f.layout_no_wrap(cell.ch.to_string(), font.clone(), to_color32(fg))+ });+ let ty = y + ((cell_h - g.size().y) * 0.5).max(0.0);+ let tx = x + ((cell_w * span as f32 - g.size().x) * 0.5).max(0.0);+ clipped.galley(Pos2::new(tx, ty), g, to_color32(fg));+ }+ if cell.attr.underline {+ painter.line_segment(+ [+ Pos2::new(x, y + cell_h - 1.0),+ Pos2::new(x + cell_w * span as f32, y + cell_h - 1.0),+ ],+ egui::Stroke::new(1.0, to_color32(fg)),+ );+ }+ col += span;+ }+ }++ if grid.cursor_visible {+ let blink_on = (ui_time_ms() / 500) % 2 == 0;+ if blink_on {+ let (ccol, crow) = visible_cursor(grid.cursor_col, grid.cursor_row, cols, rows);+ let x = origin.x + ccol as f32 * cell_w;+ let y = origin.y + crow as f32 * cell_h;+ painter.rect_filled(+ Rect::from_min_size(Pos2::new(x, y), Vec2::new(cell_w, cell_h)),+ 0.0,+ Color32::from_rgba_unmultiplied(0xD4, 0xD4, 0xD4, 100),+ );+ }+ }+}++/// Map VT cursor (may be at `col == cols` pending-wrap) onto an on-screen cell.+fn visible_cursor(col: usize, row: usize, cols: usize, rows: usize) -> (usize, usize) {+ if cols == 0 || rows == 0 {+ return (0, 0);+ }+ if col < cols {+ return (col, row.min(rows - 1));+ }+ // Pending wrap: show at end of current line (xterm-style), not the next row+ // — drawing on row+1 put the block on the input box's bottom border.+ (cols - 1, row.min(rows - 1))+}++fn ui_time_ms() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0)+}++fn handle_input(ui: &mut Ui, session: &mut GrokTermSession) {+ // egui maps Ctrl+C → Event::Copy (and often drops Key::C). In a terminal that+ // must be ETX (0x03) cancel, not clipboard copy — consume those events here.+ ui.input_mut(|i| {+ let mut send_etx = false;+ let mut send_eot = false;+ let mut send_susp = false;+ let mut send_ff = false;++ i.events.retain(|ev| match ev {+ egui::Event::Copy | egui::Event::Cut => {+ send_etx = true;+ false+ }+ egui::Event::Key {+ key,+ pressed: true,+ modifiers,+ ..+ } if modifiers.ctrl || modifiers.command => match key {+ Key::C => {+ send_etx = true;+ false+ }+ Key::D => {+ send_eot = true;+ false+ }+ Key::Z => {+ send_susp = true;+ false+ }+ Key::L => {+ send_ff = true;+ false+ }+ _ => true,+ },+ _ => true,+ });++ if send_etx+ || i.consume_key(Modifiers::CTRL, Key::C)+ || i.consume_key(Modifiers::COMMAND, Key::C)+ {+ session.write_bytes(&[0x03]);+ }+ if send_eot+ || i.consume_key(Modifiers::CTRL, Key::D)+ || i.consume_key(Modifiers::COMMAND, Key::D)+ {+ session.write_bytes(&[0x04]);+ }+ if send_susp+ || i.consume_key(Modifiers::CTRL, Key::Z)+ || i.consume_key(Modifiers::COMMAND, Key::Z)+ {+ session.write_bytes(&[0x1a]);+ }+ if send_ff || i.consume_key(Modifiers::CTRL, Key::L) {+ session.write_bytes(&[0x0c]);+ }+ });++ ui.input(|i| {+ for ev in &i.events {+ match ev {+ egui::Event::Text(t) => {+ if t != "\n" && t != "\r" && t != "\t" {+ session.write_bytes(t.as_bytes());+ }+ }+ egui::Event::Key {+ key,+ pressed: true,+ modifiers,+ ..+ } => {+ if (modifiers.ctrl || modifiers.command)+ && matches!(key, Key::C | Key::D | Key::Z | Key::L)+ {+ continue;+ }+ if let Some(bytes) = encode_key(*key, *modifiers) {+ session.write_bytes(&bytes);+ }+ }+ _ => {}+ }+ }+ });+}diff --git a/crates/ghidrust-gui/src/main.rs b/crates/ghidrust-gui/src/main.rsindex 2578eff..74953ce 100644--- a/crates/ghidrust-gui/src/main.rs+++ b/crates/ghidrust-gui/src/main.rs@@ -2,6 +2,7 @@//! Icons: Google Material 3 geometry (see `icons.rs`); no emoji in the UI.mod agent_pane;+mod grok_term;mod debugger;mod decomp_tokens;mod entropy;@@ -53,6 +54,7 @@ use std::sync::mpsc::{self, Receiver, RecvError, TryRecvError};/// Render one pseudo-C snippet from the Grok pane using the shared/// `decomp_tokens` highlighter — so agent-produced pseudo-C looks the same as/// the Decompiler pane's output.+#[allow(dead_code)] // retained for future in-pane code blocks outside the TUIfn render_pseudo_c_inline(ui: &mut egui::Ui, body: &str) {let lines = tokenize_decomp(body);ui.group(|ui| {@@ -213,6 +215,11 @@ pub struct GhidrustApp {show_program_tree: bool,show_symbol_tree: bool,show_console: bool,+ /// Bottom dock (Grok/Console/Raw) height in points. Owned by us so the+ /// top-edge drag grip can resize reliably — egui's built-in+ /// `TopBottomPanel::resizable` snaps back unless content expands, which+ /// is easy to get wrong across versions.+ console_height: f32,show_analysis_dialog: bool,/// Use experimental GPU bulk path for string/byte scan analyzers.use_gpu_experimental: bool,@@ -688,6 +695,9 @@ fn render_call_tree_node(impl GhidrustApp {pub fn new(cc: &eframe::CreationContext<'_>) -> Self {+ // Cascadia/Consolas + symbol fallbacks so the Grok TUI logo/box-drawing+ // aren't tofu (▯) under egui's tiny default monospace.+ grok_term::install_terminal_fonts(&cc.egui_ctx);let mut app = Self::headless();app.recent_projects = load_recent_projects();app.show_startup_picker = true;@@ -721,6 +731,7 @@ impl GhidrustApp {show_program_tree: true,show_symbol_tree: true,show_console: true,+ console_height: 280.0,show_analysis_dialog: false,use_gpu_experimental: false,pending_analyze_file_id: None,@@ -2547,6 +2558,10 @@ impl GhidrustApp {v.hyperlink_color = rgb(t.primary);v.warn_fg_color = rgb(t.error);ctx.set_visuals(v);+ // Wider side/top grab for resizable panels (bottom console drag).+ ctx.style_mut(|s| {+ s.interaction.resize_grab_radius_side = 12.0;+ });}pub fn load_binary(&mut self, path: impl Into<PathBuf>) -> Result<(), String> {@@ -2821,11 +2836,7 @@ 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.+ /// Render the bottom-dock tabbed panel — `Grok` (embedded TUI) + `Console`.fn render_bottom_dock(&mut self, ui: &mut egui::Ui) {use agent_pane::BottomTab;ui.horizontal(|ui| {@@ -2838,30 +2849,29 @@ impl GhidrustApp {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();- }- }+ if self.grok_pane.tab == BottomTab::Console+ && ui.small_button("Clear").clicked()+ {+ self.console.clear();+ self.console_severity.clear();}+ ui.small(egui::RichText::new("drag top edge ↕").weak().small());});});ui.separator();match self.grok_pane.tab {BottomTab::Grok => self.render_grok_tab(ui),- BottomTab::Console => self.render_console_tab(ui),+ BottomTab::Console => {+ // Leaving the TUI — release keyboard so listing hotkeys work again.+ self.grok_pane.keyboard_captured = false;+ self.render_console_tab(ui);+ }}}fn render_console_tab(&mut self, ui: &mut egui::Ui) {egui::ScrollArea::vertical()+ .auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| {let n = self.console.len();@@ -2899,170 +2909,90 @@ impl GhidrustApp {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()));- }+ let ctx = ui.ctx().clone();+ let mut start_err: Option<String> = None;+ let mut do_install = false;+ let mut do_rescan = false;+ let mut do_probe = false;+ let mut start_size: Option<(u16, u16)> = None;++ agent_pane::render_grok_pane(+ ui,+ &mut self.grok_pane,+ primary,+ muted,+ &mut |cols, rows| {+ start_size = Some((cols, rows));+ Ok(())+ },+ &mut || do_install = true,+ &mut || do_rescan = true,+ &mut || do_probe = true,+ );- 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 do_install {+ let status = agent_pane::spawn_install_grok();+ self.log(status.clone());+ self.grok_pane.install_status = Some(status);+ }+ if do_rescan {+ 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);+ }+ if do_probe {+ if let Some(bin) = self.grok_pane.grok_bin.clone() {+ match ghidrust_agent::probe_grok_version(&bin) {+ Ok(v) => {+ self.log(format!("grok --version → {v}"));+ self.grok_pane.version_probe = Some(v);}- if self.grok_pane.grok_bin.is_none()- && 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);+ Err(e) => {+ self.grok_pane.version_probe = Some(format!("(error) {e}"));+ self.log_warn(format!("grok --version failed: {e}"));}}- });- });-- // 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((cols, rows)) = start_size {+ if let Err(e) = self.start_grok_pty(cols, rows, ctx) {+ start_err = Some(e);+ }}- if let Some(status) = &self.grok_pane.install_status {- ui.small(egui::RichText::new(status).color(muted));+ if let Some(e) = start_err {+ self.grok_pane.last_error = Some(e.clone());+ self.log_error(format!("Grok TUI failed: {e}"));}-- 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.+ ///+ /// This is what makes the agent actually *know* about the open project+ /// and the currently-loaded file without needing an MCP round-trip first.+ /// Every field is honest-empty when the underlying analysis hasn't run —+ /// matches Ghidrust's "no fabrication on empty evidence" rule.fn grok_program_facts(&self) -> ghidrust_agent::ProgramFacts {+ const TOP_FN_SAMPLE: usize = 24;+ const IMPORT_SAMPLE: usize = 24;+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());+ for file in &proj.meta.files {+ let has_saved = proj.results_dir().join(&file.id).exists()+ || proj.results_dir().join(format!("{}.bin", file.id)).exists();+ f.project_files.push(ghidrust_agent::ProjectFileFact {+ id: file.id.clone(),+ display_name: file.display_name.clone(),+ has_saved_analysis: has_saved,+ });+ }}+ f.active_file_id = self.active_file_id.clone();if let Some(prog) = &self.program {f.program = Some(prog.name.clone());f.format = Some(prog.format.clone());@@ -3078,6 +3008,20 @@ impl GhidrustApp {size: s.virtual_size,});}+ for fi in prog.analysis.functions.iter().take(TOP_FN_SAMPLE) {+ f.top_functions.push(ghidrust_agent::FunctionFact {+ va: format!("{:#x}", fi.entry),+ name: fi.name.clone(),+ });+ }+ for imp in prog.imports.iter().take(IMPORT_SAMPLE) {+ if let Some(name) = &imp.name {+ f.imports_sample.push(ghidrust_agent::ImportFact {+ dll: imp.dll.clone(),+ name: name.clone(),+ });+ }+ }}f.analyzers_run = self.last_analyzers_run.clone();if let Some(va) = self.listing_focus_va {@@ -3093,92 +3037,62 @@ impl GhidrustApp {f}- fn start_grok_session_from_ui(&mut self) {+ /// Write MCP/skill/context and spawn the real Grok TUI in the PTY pane.+ fn start_grok_pty(+ &mut self,+ cols: u16,+ rows: u16,+ ctx: egui::Context,+ ) -> Result<(), String> {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 bin = self+ .grok_pane+ .grok_bin+ .clone()+ .ok_or_else(|| {+ "grok binary not installed — click 'Install Grok Build…' first".to_string()+ })?;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 ghidrust_bin = ghidrust_agent::resolve_ghidrust_cli_bin().ok_or_else(|| {+ "ghidrust CLI not found next to the GUI or on PATH — build `ghidrust` \+ (cargo build -p ghidrust-cli --release) so MCP can start"+ .to_string()+ })?;+ if !ghidrust_bin.is_file() {+ return Err(format!(+ "ghidrust CLI missing at {} — MCP cannot start",+ ghidrust_bin.display()+ ));+ }+ let (_skill_body, skill_source) = load_skill_body();let facts = self.grok_program_facts();- match agent_pane::start_session(+ // Drop any prior session before spawning a new one.+ self.grok_pane.session = None;+ let session = agent_pane::start_pty_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}"),- });- }- }+ &facts,+ ctx,+ cols,+ rows,+ )?;+ self.log(format!(+ "Grok TUI started · project={} · grok={} · mcp={}",+ project_root.display(),+ bin.display(),+ ghidrust_bin.display()+ ));+ self.grok_pane.session = Some(session);+ self.grok_pane.status = None;+ self.grok_pane.request_term_focus = true;+ self.grok_pane.keyboard_captured = true;+ Ok(())}/// Menu / pane identifiers present in the shell (for structural tests).@@ -7664,100 +7578,8 @@ impl eframe::App for GhidrustApp {});});- // Global keyboard shortcuts. Ghidra bindings mirrored:- // Alt+Left / Alt+Right — nav history- // G — Go To dialog- // L / Ctrl+L — Rename / Retype variable- // ; — Set EOL comment- // T — Choose Data Type (Data Type Chooser)- // Alt+Enter — Edit Function Signature- // Ctrl+Down / Ctrl+Up — Next / Previous function- let (- want_back,- want_forward,- want_goto,- want_rename,- want_retype,- want_comment,- want_chooser,- want_signature,- want_next_fn,- want_prev_fn,- ) = ctx.input(|i| {- let alt = i.modifiers.alt;- let ctrl = i.modifiers.ctrl;- (- alt && i.key_pressed(egui::Key::ArrowLeft),- alt && i.key_pressed(egui::Key::ArrowRight),- i.key_pressed(egui::Key::G) && !ctrl && !alt,- i.key_pressed(egui::Key::L) && !ctrl && !alt,- i.key_pressed(egui::Key::L) && ctrl,- i.key_pressed(egui::Key::Semicolon) && !ctrl && !alt,- i.key_pressed(egui::Key::T) && !ctrl && !alt,- alt && i.key_pressed(egui::Key::Enter),- ctrl && i.key_pressed(egui::Key::ArrowDown),- ctrl && i.key_pressed(egui::Key::ArrowUp),- )- });- if want_back {- self.nav_back();- }- if want_forward {- self.nav_forward();- }- if want_goto && self.program.is_some() {- if self.goto_input.is_empty() {- if let Some(prog) = &self.program {- self.goto_input = prog.entry- .map(|e| format!("{e:#x}"))- .unwrap_or_else(|| format!("{:#x}", prog.image_base));- }- }- self.show_goto_dialog = true;- }- if want_rename {- if let Some(va) = self.listing_focus_va {- self.open_rename_dialog(va);- }- }- if want_retype {- if let Some(va) = self.listing_focus_va {- self.open_retype_dialog(va);- }- }- if want_comment {- if let Some(va) = self.listing_focus_va {- self.open_comment_dialog(va, CommentKind::Eol);- }- }- if want_chooser {- let va = self.listing_focus_va;- if va.is_some() {- self.open_type_chooser(va);- }- }- if want_signature {- if let Some(va) = self.listing_focus_va {- let entry = self- .program- .as_ref()- .and_then(|p| {- p.analysis- .functions- .iter()- .find(|f| va >= f.entry && va < f.end)- .map(|f| f.entry)- })- .unwrap_or(va);- self.open_signature_dialog(entry);- }- }- if want_next_fn {- self.nav_next_function();- }- if want_prev_fn {- self.nav_prev_function();- }+ // Listing hotkeys run *after* the Grok dock paints (see below) so the+ // TUI can claim focus/keys first — otherwise `G` opens Go To while typing.egui::TopBottomPanel::top("nav_toolbar").show(ctx, |ui| {ui.horizontal(|ui| {@@ -7978,21 +7800,159 @@ 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.+ // Bottom dock: tabbed (Grok primary + Console + Raw). 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.+ //+ // Explicit min/max/default heights are required for the top-edge+ // resize gizmo to be draggable freely — without them egui pins the+ // panel to `default_height` and the drag handle becomes a 4px sliver+ // that's easy to miss.if self.show_console {- // Pull streamed events into the transcript before we render.+ // Detect Grok TUI child exit before paint.self.grok_pane.poll();+ let screen_h = ctx.screen_rect().height();+ // Own the height ourselves + paint a real drag grip. Built-in+ // `resizable(true)` on TopBottomPanel is unreliable here (snaps+ // back when content doesn't expand — egui #581 / 0.31).+ let max_h = (screen_h - 160.0).max(220.0);+ let min_h = 140.0;+ self.console_height = self.console_height.clamp(min_h, max_h);egui::TopBottomPanel::bottom("console")- .resizable(true)- .default_height(180.0)+ .exact_height(self.console_height)+ .show_separator_line(false).show(ctx, |ui| {+ // Full-width drag strip at the top of the dock.+ let grip_h = 10.0;+ let (grip_rect, grip_resp) = ui.allocate_exact_size(+ egui::vec2(ui.available_width(), grip_h),+ egui::Sense::drag(),+ );+ let grip_color = if grip_resp.dragged() {+ ui.visuals().widgets.active.bg_fill+ } else if grip_resp.hovered() {+ ui.visuals().widgets.hovered.bg_fill+ } else {+ ui.visuals().widgets.noninteractive.bg_fill+ };+ ui.painter().rect_filled(grip_rect, 0.0, grip_color);+ // Center handle bar.+ let bar = egui::Rect::from_center_size(+ grip_rect.center(),+ egui::vec2(48.0, 3.0),+ );+ ui.painter().rect_filled(+ bar,+ 1.5,+ ui.visuals().widgets.noninteractive.fg_stroke.color,+ );+ if grip_resp.hovered() || grip_resp.dragged() {+ ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);+ }+ if grip_resp.dragged() {+ // Dragging the top edge up (negative dy) grows the panel.+ self.console_height = (self.console_height - grip_resp.drag_delta().y)+ .clamp(min_h, max_h);+ }+ grip_resp.on_hover_text("Drag to resize console");++ ui.set_min_height(ui.available_height());self.render_bottom_dock(ui);});}+ // Global keyboard shortcuts (after Grok dock so keyboard_captured is current).+ // Ghidra bindings: Alt+Left/Right, G, L/Ctrl+L, ;, T, Alt+Enter, Ctrl+Up/Down.+ if !self.grok_pane.keyboard_captured {+ let (+ want_back,+ want_forward,+ want_goto,+ want_rename,+ want_retype,+ want_comment,+ want_chooser,+ want_signature,+ want_next_fn,+ want_prev_fn,+ ) = ctx.input(|i| {+ let alt = i.modifiers.alt;+ let ctrl = i.modifiers.ctrl;+ (+ alt && i.key_pressed(egui::Key::ArrowLeft),+ alt && i.key_pressed(egui::Key::ArrowRight),+ i.key_pressed(egui::Key::G) && !ctrl && !alt,+ i.key_pressed(egui::Key::L) && !ctrl && !alt,+ i.key_pressed(egui::Key::L) && ctrl,+ i.key_pressed(egui::Key::Semicolon) && !ctrl && !alt,+ i.key_pressed(egui::Key::T) && !ctrl && !alt,+ alt && i.key_pressed(egui::Key::Enter),+ ctrl && i.key_pressed(egui::Key::ArrowDown),+ ctrl && i.key_pressed(egui::Key::ArrowUp),+ )+ });+ if want_back {+ self.nav_back();+ }+ if want_forward {+ self.nav_forward();+ }+ if want_goto && self.program.is_some() {+ if self.goto_input.is_empty() {+ if let Some(prog) = &self.program {+ self.goto_input = prog.entry+ .map(|e| format!("{e:#x}"))+ .unwrap_or_else(|| format!("{:#x}", prog.image_base));+ }+ }+ self.show_goto_dialog = true;+ }+ if want_rename {+ if let Some(va) = self.listing_focus_va {+ self.open_rename_dialog(va);+ }+ }+ if want_retype {+ if let Some(va) = self.listing_focus_va {+ self.open_retype_dialog(va);+ }+ }+ if want_comment {+ if let Some(va) = self.listing_focus_va {+ self.open_comment_dialog(va, CommentKind::Eol);+ }+ }+ if want_chooser {+ let va = self.listing_focus_va;+ if va.is_some() {+ self.open_type_chooser(va);+ }+ }+ if want_signature {+ if let Some(va) = self.listing_focus_va {+ let entry = self+ .program+ .as_ref()+ .and_then(|p| {+ p.analysis+ .functions+ .iter()+ .find(|f| va >= f.entry && va < f.end)+ .map(|f| f.entry)+ })+ .unwrap_or(va);+ self.open_signature_dialog(entry);+ }+ }+ if want_next_fn {+ self.nav_next_function();+ }+ if want_prev_fn {+ self.nav_prev_function();+ }+ }+// Ghidra Project Window–style dock: Project → binaries (upgraded badges + actions)if self.show_project_tree {egui::SidePanel::left("project_tree")@@ -10487,6 +10447,7 @@ mod tests {base: prog.image_base,count: 3,entries: vec![prog.image_base, prog.image_base + 8, prog.image_base + 16],+ role: ghidrust_core::AddressTableRole::Unknown,});}let hits = address_table_hits(app.program.as_ref().unwrap());diff --git a/crates/ghidrust-gui/src/menu_actions.rs b/crates/ghidrust-gui/src/menu_actions.rsindex 3a4f787..c463a0b 100644--- a/crates/ghidrust-gui/src/menu_actions.rs+++ b/crates/ghidrust-gui/src/menu_actions.rs@@ -678,6 +678,7 @@ mod tests {base: prog.image_base,count: 2,entries: vec![prog.image_base, prog.image_base + 8],+ role: ghidrust_core::AddressTableRole::Unknown,});let hits = address_table_hits(&prog);assert_eq!(hits.len(), 1);diff --git a/crates/ghidrust-gui/src/scripts.rs b/crates/ghidrust-gui/src/scripts.rsindex 7e1a1f7..c12abbf 100644--- a/crates/ghidrust-gui/src/scripts.rs+++ b/crates/ghidrust-gui/src/scripts.rs@@ -59,13 +59,22 @@ pub fn builtin_catalog() -> Vec<ScriptEntry> {s("mcp.list_classes", "MCP · Program", "Enumerate C++/RTTI classes recovered."),s("mcp.list_namespaces", "MCP · Program", "Enumerate scoped namespaces."),s("mcp.list_segments", "MCP · Program", "Enumerate mapped memory blocks / sections."),- s("mcp.list_imports", "MCP · Program", "Enumerate imported symbols."),+ s("mcp.list_imports", "MCP · Program", "Enumerate PE import / IAT slots."),s("mcp.list_exports", "MCP · Program", "Enumerate exported symbols."),s("mcp.list_data_items", "MCP · Program", "Enumerate defined data items."),- s("mcp.list_strings", "MCP · Program", "Enumerate recovered strings."),- s("mcp.get_xrefs_to", "MCP · Xrefs", "References targeting a VA."),+ s("mcp.list_strings", "MCP · Program", "ASCII/UTF-16 strings; match/limit/raw blob."),+ s("mcp.search_strings", "MCP · Program", "Alias of list_strings (filter-oriented)."),+ s("mcp.get_import_xrefs", "MCP · Xrefs", "Code sites referencing an import IAT slot."),+ s("mcp.get_string_xrefs", "MCP · Xrefs", "Resolve strings by filter, then xrefs to each."),+ s("mcp.get_xrefs_to", "MCP · Xrefs", "Refs to a VA; optional skip_stubs/classify."),s("mcp.get_xrefs_from", "MCP · Xrefs", "References emitted from a VA."),s("mcp.get_function_xrefs", "MCP · Xrefs", "Callers and callees of a function."),+ s("mcp.il2cpp_meta", "MCP · IL2CPP", "Parse global-metadata.dat types/methods."),+ s("mcp.il2cpp_map", "MCP · IL2CPP", "Metadata ↔ RVA map (null when unproven)."),+ s("mcp.il2cpp_stubs", "MCP · IL2CPP", "List IL2CPP resolve stubs by icall name."),+ s("mcp.unity_inventory", "MCP · Unity", "Player install inventory (assemblies, plugins, metadata)."),+ s("mcp.function_at", "MCP · Functions", "Containing function for a body VA."),+ s("mcp.decompile", "MCP · Decompile", "Stage-1 C; optional follow_stub for IL2CPP."),s("mcp.get_current_address", "MCP · Cursor", "Report the currently focused Listing VA."),s("mcp.get_current_function", "MCP · Cursor", "Report the function containing the cursor."),s("mcp.get_function_by_address", "MCP · Functions", "Fetch function metadata by VA."),diff --git a/crates/ghidrust-il2cpp/Cargo.toml b/crates/ghidrust-il2cpp/Cargo.tomlnew file mode 100644index 0000000..14ebb47--- /dev/null+++ b/crates/ghidrust-il2cpp/Cargo.toml@@ -0,0 +1,11 @@+[package]+name = "ghidrust-il2cpp"+version.workspace = true+edition.workspace = true+license.workspace = true+description = "Hand-rolled IL2CPP global-metadata + binary correlation"++[dependencies]+ghidrust-core = { workspace = true }+serde = { version = "1", features = ["derive"] }+serde_json = "1"diff --git a/crates/ghidrust-il2cpp/src/binary.rs b/crates/ghidrust-il2cpp/src/binary.rsnew file mode 100644index 0000000..3d7ee11--- /dev/null+++ b/crates/ghidrust-il2cpp/src/binary.rs@@ -0,0 +1,174 @@+//! CodeRegistration / MetadataRegistration correlation (PE64 P0).++use crate::error::{Error, Result};+use crate::metadata::Il2CppMetadata;+use ghidrust_core::Program;+use serde::Serialize;++/// One managed method with optional validated RVA.+#[derive(Debug, Clone, Serialize)]+pub struct MethodMapEntry {+ pub method_index: u32,+ pub name: String,+ pub full_name: String,+ /// Present only when CodeRegistration / codeGenModules validation succeeds.+ pub rva: Option<u64>,+ pub va: Option<u64>,+ pub token: u32,+}++#[derive(Debug, Clone, Serialize)]+pub struct MethodMap {+ pub binary_name: String,+ pub metadata_version: i32,+ pub method_pointer_count: Option<u64>,+ pub entries: Vec<MethodMapEntry>,+ pub notes: Vec<String>,+}++/// Correlate metadata method indices with binary method pointers when registration validates.+pub fn correlate(prog: &Program, meta: &Il2CppMetadata) -> Result<MethodMap> {+ let mut notes = Vec::new();+ let pointers = find_method_pointers(prog, &mut notes);+ let mut entries = Vec::with_capacity(meta.methods.len());+ for m in &meta.methods {+ let (rva, va) = if let Some(ptrs) = pointers.as_ref() {+ if let Some(&va) = ptrs.get(m.index as usize) {+ let rva = va.saturating_sub(prog.image_base);+ (Some(rva), Some(va))+ } else {+ (None, None)+ }+ } else {+ (None, None)+ };+ entries.push(MethodMapEntry {+ method_index: m.index,+ name: m.name.clone(),+ full_name: meta.method_full_name(m),+ rva,+ va,+ token: m.token,+ });+ }+ Ok(MethodMap {+ binary_name: prog.name.clone(),+ metadata_version: meta.header.version,+ method_pointer_count: pointers.as_ref().map(|p| p.len() as u64),+ entries,+ notes,+ })+}++/// Scan non-exec data for a pointer array that looks like methodPointers.+///+/// Validation: count ≥ 4, pointers land in executable mapped ranges, density high.+fn find_method_pointers(prog: &Program, notes: &mut Vec<String>) -> Option<Vec<u64>> {+ let exec_ranges: Vec<(u64, u64)> = prog+ .blocks+ .iter()+ .filter(|b| b.executable)+ .map(|b| (b.va, b.va.saturating_add(b.size)))+ .collect();+ if exec_ranges.is_empty() {+ notes.push("no executable blocks; cannot validate method pointers".into());+ return None;+ }+ let in_exec = |va: u64| exec_ranges.iter().any(|&(s, e)| va >= s && va < e);++ let mut best: Option<Vec<u64>> = None;+ let mut best_score = 0usize;++ for block in &prog.blocks {+ if block.executable || block.bytes.len() < 32 {+ continue;+ }+ let bytes = &block.bytes;+ // Align to 8 within block.+ let mut off = 0usize;+ while off + 16 <= bytes.len() {+ // Candidate: [count:u64][ptr:u64] pattern used by some registration fields,+ // or a dense run of code pointers.+ let run = collect_pointer_run(bytes, off, block.va, &in_exec);+ if run.len() >= 4 {+ let score = run.len();+ if score > best_score {+ best_score = score;+ best = Some(run);+ }+ }+ off += 8;+ }+ }++ if let Some(ref p) = best {+ notes.push(format!(+ "validated method pointer array candidate len={} (structural; not a single magic offset)",+ p.len()+ ));+ } else {+ notes.push(+ "no multi-field-validated method pointer array found; RVAs left null".into(),+ );+ }+ best+}++fn collect_pointer_run(+ bytes: &[u8],+ start: usize,+ block_va: u64,+ in_exec: &dyn Fn(u64) -> bool,+) -> Vec<u64> {+ let mut out = Vec::new();+ let mut off = start;+ while off + 8 <= bytes.len() {+ let va = u64::from_le_bytes(bytes[off..off + 8].try_into().unwrap());+ if !in_exec(va) {+ break;+ }+ // Reject obvious non-code (null already excluded by in_exec).+ out.push(va);+ off += 8;+ if out.len() > 1_000_000 {+ break;+ }+ }+ let _ = block_va;+ out+}++/// `script.json`-shaped export (Inspector/Dumper workflow value, hand-rolled).+#[derive(Debug, Clone, Serialize)]+pub struct ScriptJson {+ pub script_method: Vec<ScriptMethod>,+}++#[derive(Debug, Clone, Serialize)]+pub struct ScriptMethod {+ pub address: String,+ pub name: String,+ pub signature: String,+}++pub fn to_script_json(map: &MethodMap) -> ScriptJson {+ let mut script_method = Vec::new();+ for e in &map.entries {+ let Some(va) = e.va else { continue };+ script_method.push(ScriptMethod {+ address: format!("{va:X}"),+ name: e.full_name.clone(),+ signature: format!("{}()", e.full_name),+ });+ }+ ScriptJson { script_method }+}++pub fn load_and_correlate(+ binary: &std::path::Path,+ meta_path: &std::path::Path,+) -> Result<MethodMap> {+ let prog = ghidrust_core::load_path(binary).map_err(|e| Error::Io(e.to_string()))?;+ let meta = Il2CppMetadata::load_path(meta_path)?;+ correlate(&prog, &meta)+}diff --git a/crates/ghidrust-il2cpp/src/error.rs b/crates/ghidrust-il2cpp/src/error.rsnew file mode 100644index 0000000..0ea79a6--- /dev/null+++ b/crates/ghidrust-il2cpp/src/error.rs@@ -0,0 +1,75 @@+use serde_json::{json, Value};+use std::fmt;++#[derive(Debug, Clone)]+pub enum Error {+ Io(String),+ EncryptedOrObfuscated { magic: u32, version_field: i32 },+ UnsupportedVersion { version: i32, hint: String },+ Parse(String),+ Bounds(String),+}++/// Agent-oriented next steps when metadata fails closed as encrypted/obfuscated.+pub const ENCRYPTED_METADATA_NEXT_STEPS: &[&str] = &[+ "Use engine PE strings + il2cpp icalls for native internal-call RVAs",+ "Treat GameAssembly resolve stubs as lazy thunks, not gameplay callers (xrefs --skip-stubs)",+ "Instance/type latch may require live inspection when metadata is unavailable",+];++impl Error {+ /// Structured JSON for CLI/MCP when metadata is encrypted/obfuscated.+ pub fn encrypted_json(magic: u32, _version_field: i32) -> Value {+ json!({+ "error": "metadata_encrypted_or_obfuscated",+ "magic": format!("{magic:#010x}"),+ "next_steps": ENCRYPTED_METADATA_NEXT_STEPS,+ })+ }++ /// Structured JSON for this error when it is encrypt/obfuscate; otherwise null.+ pub fn to_structured_json(&self) -> Option<Value> {+ match self {+ Error::EncryptedOrObfuscated { magic, version_field } => {+ Some(Self::encrypted_json(*magic, *version_field))+ }+ _ => None,+ }+ }+}++impl fmt::Display for Error {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Error::Io(m) => write!(f, "io: {m}"),+ Error::EncryptedOrObfuscated { magic, version_field } => write!(+ f,+ "metadata encrypted or obfuscated (magic={magic:#010x}, version_field={version_field}); refuse to mis-parse"+ ),+ Error::UnsupportedVersion { version, hint } => {+ write!(f, "unsupported metadata version {version}: {hint}")+ }+ Error::Parse(m) => write!(f, "parse: {m}"),+ Error::Bounds(m) => write!(f, "bounds: {m}"),+ }+ }+}++impl std::error::Error for Error {}++pub type Result<T> = std::result::Result<T, Error>;++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn encrypted_json_has_next_steps() {+ let v = Error::encrypted_json(0xDEADBEEF, -1);+ assert_eq!(v["error"], "metadata_encrypted_or_obfuscated");+ assert_eq!(v["magic"], "0xdeadbeef");+ let steps = v["next_steps"].as_array().expect("next_steps");+ assert!(steps.len() >= 3);+ assert!(steps.iter().any(|s| s.as_str().unwrap_or("").contains("il2cpp icalls")));+ }+}diff --git a/crates/ghidrust-il2cpp/src/icall.rs b/crates/ghidrust-il2cpp/src/icall.rsnew file mode 100644index 0000000..66677b0--- /dev/null+++ b/crates/ghidrust-il2cpp/src/icall.rs@@ -0,0 +1,290 @@+//! Unity engine internal-call (icall) name‖fn table pairing.+//!+//! Locates parallel pointer arrays in an engine PE (typically UnityPlayer):+//! one table of `const char*` names and an equal-length table of code pointers.++use ghidrust_core::analyzers::run_analyzers;+use ghidrust_core::program::{AddressTableInfo, AddressTableRole, Program};+use ghidrust_core::{load_path, Error as CoreError};+use serde::Serialize;+use std::path::Path;++use crate::error::{Error, Result};++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum ICallTableLayout {+ FnsThenNames,+ NamesThenFns,+}++#[derive(Debug, Clone, Serialize)]+pub struct ICallEntry {+ pub index: usize,+ pub name: String,+ pub name_string_va: u64,+ pub fn_va: u64,+ pub fn_rva: u64,+}++#[derive(Debug, Clone, Serialize)]+pub struct ICallTable {+ pub name_va: u64,+ pub fn_va: u64,+ pub count: usize,+ pub layout: ICallTableLayout,+ /// 0.0–1.0 fraction of names that look like Unity icalls (`::` and/or `_Injected`).+ pub confidence: f32,+ pub entries: Vec<ICallEntry>,+}++#[derive(Debug, Clone, Serialize)]+pub struct ICallResolveReport {+ pub tables: Vec<ICallTable>,+}++/// Resolve icall name‖fn tables in `prog`. Runs Create Address Tables when empty.+pub fn resolve_icalls(prog: &mut Program) -> Result<ICallResolveReport> {+ if prog.analysis.address_tables.is_empty() {+ run_analyzers(prog, &["Create Address Tables"]).map_err(core_err)?;+ }+ let tables = prog.analysis.address_tables.clone();+ let mut paired = Vec::new();++ let name_cands: Vec<&AddressTableInfo> = tables+ .iter()+ .filter(|t| {+ matches!(t.role, AddressTableRole::DataPtrs | AddressTableRole::Mixed)+ && t.count >= 3+ && name_table_score(prog, t) > 0.35+ })+ .collect();++ let fn_cands: Vec<&AddressTableInfo> = tables+ .iter()+ .filter(|t| matches!(t.role, AddressTableRole::CodePtrs) && t.count >= 3)+ .collect();++ for name_tbl in &name_cands {+ let n = name_tbl.count;+ let mut best: Option<(ICallTableLayout, &AddressTableInfo, f32)> = None;+ for fn_tbl in &fn_cands {+ if fn_tbl.count != n {+ continue;+ }+ let name_end = name_tbl.base + (n as u64) * 8;+ let fn_end = fn_tbl.base + (n as u64) * 8;+ let layout = if fn_end == name_tbl.base {+ Some(ICallTableLayout::FnsThenNames)+ } else if name_end == fn_tbl.base {+ Some(ICallTableLayout::NamesThenFns)+ } else {+ None+ };+ let Some(layout) = layout else {+ continue;+ };+ let conf = name_table_score(prog, name_tbl);+ let better = match &best {+ None => true,+ Some((_, _, c)) => conf > *c,+ };+ if better {+ best = Some((layout, fn_tbl, conf));+ }+ }+ if let Some((layout, fn_tbl, conf)) = best {+ if let Some(table) = build_table(prog, name_tbl, fn_tbl, layout, conf) {+ paired.push(table);+ }+ }+ }++ // Prefer higher confidence / larger tables first.+ paired.sort_by(|a, b| {+ b.confidence+ .partial_cmp(&a.confidence)+ .unwrap_or(std::cmp::Ordering::Equal)+ .then_with(|| b.count.cmp(&a.count))+ });+ paired.dedup_by_key(|t| t.name_va);++ Ok(ICallResolveReport { tables: paired })+}++/// Load a PE and resolve icalls.+pub fn resolve_icalls_path(path: impl AsRef<Path>) -> Result<ICallResolveReport> {+ let mut prog = load_path(path.as_ref()).map_err(core_err)?;+ resolve_icalls(&mut prog)+}++/// Filter entries across all tables by substring (case-insensitive).+pub fn filter_entries(report: &ICallResolveReport, filter: &str) -> Vec<(usize, ICallEntry)> {+ let needle = filter.to_ascii_lowercase();+ let mut out = Vec::new();+ for (ti, tbl) in report.tables.iter().enumerate() {+ for e in &tbl.entries {+ if e.name.to_ascii_lowercase().contains(&needle) {+ out.push((ti, e.clone()));+ }+ }+ }+ out+}++fn build_table(+ prog: &Program,+ name_tbl: &AddressTableInfo,+ fn_tbl: &AddressTableInfo,+ layout: ICallTableLayout,+ confidence: f32,+) -> Option<ICallTable> {+ let n = name_tbl.count;+ if fn_tbl.count != n || n == 0 {+ return None;+ }+ let mut entries = Vec::with_capacity(n);+ for i in 0..n {+ let name_va = name_tbl.entries[i];+ let fn_va = fn_tbl.entries[i];+ let name = read_icall_name(prog, name_va)?;+ let fn_rva = fn_va.saturating_sub(prog.image_base);+ entries.push(ICallEntry {+ index: i,+ name,+ name_string_va: name_va,+ fn_va,+ fn_rva,+ });+ }+ Some(ICallTable {+ name_va: name_tbl.base,+ fn_va: fn_tbl.base,+ count: n,+ layout,+ confidence,+ entries,+ })+}++fn name_table_score(prog: &Program, tbl: &AddressTableInfo) -> f32 {+ if tbl.entries.is_empty() {+ return 0.0;+ }+ let mut hits = 0usize;+ for &va in &tbl.entries {+ if let Some(s) = read_icall_name(prog, va) {+ if s.contains("::") || s.contains("_Injected") {+ hits += 1;+ }+ }+ }+ hits as f32 / tbl.entries.len() as f32+}++fn read_icall_name(prog: &Program, va: u64) -> Option<String> {+ let bytes = prog.read_va(va, 256)?;+ let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());+ if end < 3 {+ return None;+ }+ let s = std::str::from_utf8(&bytes[..end]).ok()?;+ if !s.chars().all(|c| {+ c.is_ascii_graphic() || c == ' ' || c == ':' || c == '_' || c == '.' || c == '&' || c == '(' || c == ')' || c == ','+ }) {+ return None;+ }+ if s.chars().any(|c| c.is_ascii_alphabetic()) {+ Some(s.to_string())+ } else {+ None+ }+}++fn core_err(e: CoreError) -> Error {+ Error::Parse(e.to_string())+}++#[cfg(test)]+mod tests {+ use super::*;+ use ghidrust_core::program::MemoryBlock;++ #[test]+ fn pairs_fns_then_names_tables() {+ let image_base = 0x140000000u64;+ let text_va = image_base + 0x1000;+ let str_base = image_base + 0x3000;+ let fn_tbl_va = image_base + 0x2000;+ let name_tbl_va = image_base + 0x2020; // immediately after 4*8++ let names = [+ b"UnityEngine.Foo::get_a_Injected\0",+ b"UnityEngine.Foo::set_a_Injected\0",+ b"UnityEngine.Foo::get_b_Injected\0",+ b"UnityEngine.Foo::set_b_Injected\0",+ ];+ let mut rdata = Vec::new();+ let mut name_vas = Vec::new();+ for n in &names {+ while rdata.len() % 8 != 0 {+ rdata.push(0);+ }+ name_vas.push(str_base + rdata.len() as u64);+ rdata.extend_from_slice(*n);+ }+ while rdata.len() % 8 != 0 {+ rdata.push(0);+ }++ let fn_vas: Vec<u64> = (0..4).map(|i| text_va + i * 0x10).collect();+ let mut table_blob = Vec::new();+ for &f in &fn_vas {+ table_blob.extend_from_slice(&f.to_le_bytes());+ }+ assert_eq!(fn_tbl_va + table_blob.len() as u64, name_tbl_va);+ for &nv in &name_vas {+ table_blob.extend_from_slice(&nv.to_le_bytes());+ }++ let mut prog = Program::new("icall".into(), "PE32+");+ prog.image_base = image_base;+ prog.blocks.push(MemoryBlock {+ name: ".text".into(),+ va: text_va,+ size: 0x100,+ bytes: vec![0xC3; 0x100],+ readable: true,+ writable: false,+ executable: true,+ });+ prog.blocks.push(MemoryBlock {+ name: ".rdata_str".into(),+ va: str_base,+ size: rdata.len() as u64,+ bytes: rdata,+ readable: true,+ writable: false,+ executable: false,+ });+ prog.blocks.push(MemoryBlock {+ name: ".rdata_tbl".into(),+ va: fn_tbl_va,+ size: table_blob.len() as u64,+ bytes: table_blob,+ readable: true,+ writable: false,+ executable: false,+ });++ let report = resolve_icalls(&mut prog).expect("resolve");+ assert!(!report.tables.is_empty(), "{report:?}");+ let tbl = &report.tables[0];+ assert_eq!(tbl.count, 4);+ assert_eq!(tbl.layout, ICallTableLayout::FnsThenNames);+ let hits = filter_entries(&report, "set_a_Injected");+ assert_eq!(hits.len(), 1);+ assert_eq!(hits[0].1.index, 1);+ assert_eq!(hits[0].1.fn_rva, fn_vas[1] - image_base);+ }+}diff --git a/crates/ghidrust-il2cpp/src/lib.rs b/crates/ghidrust-il2cpp/src/lib.rsnew file mode 100644index 0000000..bda78d7--- /dev/null+++ b/crates/ghidrust-il2cpp/src/lib.rs@@ -0,0 +1,26 @@+//! Hand-rolled IL2CPP metadata + binary correlation for Ghidrust.+//!+//! No Il2CppDumper / Cpp2IL / goblin at runtime — formats reimplemented in-tree.+//! See `docs/IL2CPP.md` for the supported version matrix.++pub mod binary;+pub mod error;+pub mod icall;+pub mod metadata;+pub mod stubs;++pub use binary::{+ correlate, load_and_correlate, to_script_json, MethodMap, MethodMapEntry, ScriptJson,+};+pub use error::{Error, Result, ENCRYPTED_METADATA_NEXT_STEPS};+pub use icall::{+ filter_entries, resolve_icalls, resolve_icalls_path, ICallEntry, ICallResolveReport, ICallTable,+ ICallTableLayout,+};+pub use metadata::{+ build_synthetic, build_synthetic_v31, Il2CppMetadata, MetadataDialect, METADATA_MAGIC,+};+pub use stubs::{+ classify_at, find_resolve_stubs, follow_stub_target, is_resolve_stub_va, stub_matches_filter,+ Il2CppKind, ResolveStub,+};diff --git a/crates/ghidrust-il2cpp/src/metadata.rs b/crates/ghidrust-il2cpp/src/metadata.rsnew file mode 100644index 0000000..573585c--- /dev/null+++ b/crates/ghidrust-il2cpp/src/metadata.rs@@ -0,0 +1,579 @@+//! IL2CPP `global-metadata.dat` parser (P0: v27 / v29 / v31).++use crate::error::{Error, Result};+use serde::Serialize;+use std::path::Path;++/// Canonical metadata magic (`0xFAB11BAF`).+pub const METADATA_MAGIC: u32 = 0xFAB11BAF;++/// Layout dialect selected by version (+ future structural probes).+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum MetadataDialect {+ V27,+ V29,+ V31,+}++impl MetadataDialect {+ pub fn from_version(version: i32) -> Result<Self> {+ match version {+ 27 => Ok(Self::V27),+ 29 => Ok(Self::V29),+ 31 => Ok(Self::V31),+ v if (24..27).contains(&v) => Err(Error::UnsupportedVersion {+ version: v,+ hint: "v24.x is P1; use a Unity build that emits v27/29/31 or wait for follow-on support"+ .into(),+ }),+ v if v >= 39 => Err(Error::UnsupportedVersion {+ version: v,+ hint: "v39+/v106 sectioned metadata is P1".into(),+ }),+ v => Err(Error::UnsupportedVersion {+ version: v,+ hint: "supported P0 versions: 27, 29, 31".into(),+ }),+ }+ }++ fn type_def_stride(self) -> usize {+ // Il2CppTypeDefinition without byrefTypeIndex (post-24.5): 88 bytes.+ 88+ }++ fn method_def_stride(self) -> usize {+ // Il2CppMethodDefinition (no methodIndex/invokerIndex): 32 bytes.+ 32+ }++ fn image_def_stride(self) -> usize {+ 40+ }+}++#[derive(Debug, Clone, Serialize)]+pub struct MetadataHeader {+ pub magic: u32,+ pub version: i32,+ pub dialect: MetadataDialect,+ pub string_offset: u32,+ pub string_size: u32,+ pub string_literal_offset: u32,+ pub string_literal_size: u32,+ pub string_literal_data_offset: u32,+ pub string_literal_data_size: u32,+ pub methods_offset: u32,+ pub methods_size: u32,+ pub type_definitions_offset: u32,+ pub type_definitions_size: u32,+ pub images_offset: u32,+ pub images_size: u32,+ pub assemblies_offset: u32,+ pub assemblies_size: u32,+}++#[derive(Debug, Clone, Serialize)]+pub struct TypeDef {+ pub index: u32,+ pub name: String,+ pub namespace: String,+ pub method_start: i32,+ pub method_count: u16,+ pub token: u32,+}++impl TypeDef {+ pub fn full_name(&self) -> String {+ if self.namespace.is_empty() {+ self.name.clone()+ } else {+ format!("{}.{}", self.namespace, self.name)+ }+ }+}++#[derive(Debug, Clone, Serialize)]+pub struct MethodDef {+ pub index: u32,+ pub name: String,+ pub declaring_type: i32,+ pub token: u32,+ pub parameter_count: u16,+}++#[derive(Debug, Clone, Serialize)]+pub struct ImageDef {+ pub index: u32,+ pub name: String,+ pub type_start: i32,+ pub type_count: u32,+}++#[derive(Debug, Clone, Serialize)]+pub struct Il2CppMetadata {+ pub header: MetadataHeader,+ pub types: Vec<TypeDef>,+ pub methods: Vec<MethodDef>,+ pub images: Vec<ImageDef>,+ /// Metadata string heap entries (index → string), sparse-friendly as vec of (offset, value).+ pub strings: Vec<(u32, String)>,+}++impl Il2CppMetadata {+ pub fn load_path(path: impl AsRef<Path>) -> Result<Self> {+ let data = std::fs::read(path.as_ref()).map_err(|e| Error::Io(e.to_string()))?;+ Self::parse(&data)+ }++ pub fn parse(data: &[u8]) -> Result<Self> {+ if data.len() < 16 {+ return Err(Error::Parse("metadata too small".into()));+ }+ let magic = u32::from_le_bytes(data[0..4].try_into().unwrap());+ let version = i32::from_le_bytes(data[4..8].try_into().unwrap());+ if magic != METADATA_MAGIC {+ return Err(Error::EncryptedOrObfuscated {+ magic,+ version_field: version,+ });+ }+ let dialect = MetadataDialect::from_version(version)?;+ let header = parse_header(data, version, dialect)?;+ validate_table(data, header.string_offset, header.string_size, "string heap")?;+ validate_table(+ data,+ header.type_definitions_offset,+ header.type_definitions_size,+ "typeDefinitions",+ )?;+ validate_table(data, header.methods_offset, header.methods_size, "methods")?;+ validate_table(data, header.images_offset, header.images_size, "images")?;++ let strings = extract_string_heap(data, header.string_offset, header.string_size);+ let types = parse_type_defs(data, &header, &strings, dialect)?;+ let methods = parse_method_defs(data, &header, &strings, dialect)?;+ let images = parse_images(data, &header, &strings, dialect)?;++ Ok(Self {+ header,+ types,+ methods,+ images,+ strings,+ })+ }++ /// Peek magic/version without full parse (for inventory).+ pub fn peek(data: &[u8]) -> Result<(u32, i32, Option<MetadataDialect>)> {+ if data.len() < 8 {+ return Err(Error::Parse("metadata too small".into()));+ }+ let magic = u32::from_le_bytes(data[0..4].try_into().unwrap());+ let version = i32::from_le_bytes(data[4..8].try_into().unwrap());+ if magic != METADATA_MAGIC {+ return Err(Error::EncryptedOrObfuscated {+ magic,+ version_field: version,+ });+ }+ let dialect = MetadataDialect::from_version(version).ok();+ Ok((magic, version, dialect))+ }++ pub fn method_full_name(&self, method: &MethodDef) -> String {+ let ty = self+ .types+ .get(method.declaring_type as usize)+ .map(|t| t.full_name())+ .unwrap_or_else(|| format!("Type{}", method.declaring_type));+ format!("{ty}::{}", method.name)+ }++ pub fn filter_types(&self, needle: &str) -> Vec<&TypeDef> {+ let n = needle.to_ascii_lowercase();+ self.types+ .iter()+ .filter(|t| t.full_name().to_ascii_lowercase().contains(&n))+ .collect()+ }++ pub fn filter_methods(&self, needle: &str) -> Vec<&MethodDef> {+ let n = needle.to_ascii_lowercase();+ self.methods+ .iter()+ .filter(|m| {+ self.method_full_name(m).to_ascii_lowercase().contains(&n)+ || m.name.to_ascii_lowercase().contains(&n)+ })+ .collect()+ }+}++fn validate_table(data: &[u8], offset: u32, size: u32, name: &str) -> Result<()> {+ let end = offset as u64 + size as u64;+ if end > data.len() as u64 {+ return Err(Error::Bounds(format!(+ "{name} table OOB: offset={offset} size={size} file={}",+ data.len()+ )));+ }+ Ok(())+}++fn read_i32(data: &[u8], off: &mut usize) -> Result<i32> {+ if *off + 4 > data.len() {+ return Err(Error::Bounds("header truncated".into()));+ }+ let v = i32::from_le_bytes(data[*off..*off + 4].try_into().unwrap());+ *off += 4;+ Ok(v)+}++fn read_u32_pair(data: &[u8], off: &mut usize) -> Result<(u32, u32)> {+ let a = read_i32(data, off)? as u32;+ let b = read_i32(data, off)? as u32;+ Ok((a, b))+}++/// Walk versioned header field pairs (mirrors Il2CppDumper / Cpp2IL layout gates).+fn parse_header(data: &[u8], version: i32, dialect: MetadataDialect) -> Result<MetadataHeader> {+ let mut off = 8usize;+ let (string_literal_offset, string_literal_size) = read_u32_pair(data, &mut off)?;+ let (string_literal_data_offset, string_literal_data_size) = read_u32_pair(data, &mut off)?;+ let (string_offset, string_size) = read_u32_pair(data, &mut off)?;+ let (_events_off, _events_sz) = read_u32_pair(data, &mut off)?;+ let (_props_off, _props_sz) = read_u32_pair(data, &mut off)?;+ let (methods_offset, methods_size) = read_u32_pair(data, &mut off)?;+ let (_pdv_off, _pdv_sz) = read_u32_pair(data, &mut off)?;+ let (_fdv_off, _fdv_sz) = read_u32_pair(data, &mut off)?;+ let (_fpd_off, _fpd_sz) = read_u32_pair(data, &mut off)?;+ let (_fms_off, _fms_sz) = read_u32_pair(data, &mut off)?;+ let (_params_off, _params_sz) = read_u32_pair(data, &mut off)?;+ let (_fields_off, _fields_sz) = read_u32_pair(data, &mut off)?;+ let (_gp_off, _gp_sz) = read_u32_pair(data, &mut off)?;+ let (_gpc_off, _gpc_sz) = read_u32_pair(data, &mut off)?;+ let (_gc_off, _gc_sz) = read_u32_pair(data, &mut off)?;+ let (_nested_off, _nested_sz) = read_u32_pair(data, &mut off)?;+ let (_ifaces_off, _ifaces_sz) = read_u32_pair(data, &mut off)?;+ let (_vt_off, _vt_sz) = read_u32_pair(data, &mut off)?;+ let (_io_off, _io_sz) = read_u32_pair(data, &mut off)?;+ let (type_definitions_offset, type_definitions_size) = read_u32_pair(data, &mut off)?;+ // rgctx only <= 24.1 — skipped for P0 dialects+ let (images_offset, images_size) = read_u32_pair(data, &mut off)?;+ let (assemblies_offset, assemblies_size) = read_u32_pair(data, &mut off)?;+ // metadataUsage only < 27 — skipped+ let (_field_refs_off, _field_refs_sz) = read_u32_pair(data, &mut off)?;+ let (_ref_asm_off, _ref_asm_sz) = read_u32_pair(data, &mut off)?;+ if version < 29 {+ let (_attr_info_off, _attr_info_sz) = read_u32_pair(data, &mut off)?;+ let (_attr_types_off, _attr_types_sz) = read_u32_pair(data, &mut off)?;+ } else {+ let (_attr_data_off, _attr_data_sz) = read_u32_pair(data, &mut off)?;+ let (_attr_range_off, _attr_range_sz) = read_u32_pair(data, &mut off)?;+ }+ let (_uvc_types_off, _uvc_types_sz) = read_u32_pair(data, &mut off)?;+ let (_uvc_ranges_off, _uvc_ranges_sz) = read_u32_pair(data, &mut off)?;+ let (_wrtn_off, _wrtn_sz) = read_u32_pair(data, &mut off)?;+ if version >= 27 {+ let (_wrs_off, _wrs_sz) = read_u32_pair(data, &mut off)?;+ }+ let (_exported_off, _exported_sz) = read_u32_pair(data, &mut off)?;++ // Sanity: first table often starts at header size.+ if string_literal_offset as usize != off && string_literal_offset as usize + 8 < data.len() {+ // Not fatal — some builds pad or reorder; keep going.+ }++ Ok(MetadataHeader {+ magic: METADATA_MAGIC,+ version,+ dialect,+ string_offset,+ string_size,+ string_literal_offset,+ string_literal_size,+ string_literal_data_offset,+ string_literal_data_size,+ methods_offset,+ methods_size,+ type_definitions_offset,+ type_definitions_size,+ images_offset,+ images_size,+ assemblies_offset,+ assemblies_size,+ })+}++fn extract_string_heap(data: &[u8], offset: u32, size: u32) -> Vec<(u32, String)> {+ let start = offset as usize;+ let end = (offset + size) as usize;+ if end > data.len() || start >= end {+ return Vec::new();+ }+ let heap = &data[start..end];+ let mut out = Vec::new();+ let mut i = 0usize;+ while i < heap.len() {+ let begin = i;+ while i < heap.len() && heap[i] != 0 {+ i += 1;+ }+ if i > begin {+ let s = String::from_utf8_lossy(&heap[begin..i]).into_owned();+ out.push((begin as u32, s));+ }+ i += 1;+ }+ out+}++fn string_at(heap: &[(u32, String)], index: i32) -> String {+ if index < 0 {+ return String::new();+ }+ let idx = index as u32;+ heap.iter()+ .find(|(off, _)| *off == idx)+ .map(|(_, s)| s.clone())+ .unwrap_or_default()+}++fn parse_type_defs(+ data: &[u8],+ header: &MetadataHeader,+ strings: &[(u32, String)],+ dialect: MetadataDialect,+) -> Result<Vec<TypeDef>> {+ let stride = dialect.type_def_stride();+ let count = header.type_definitions_size as usize / stride;+ let base = header.type_definitions_offset as usize;+ let mut out = Vec::with_capacity(count);+ for i in 0..count {+ let off = base + i * stride;+ if off + stride > data.len() {+ return Err(Error::Bounds("type def truncated".into()));+ }+ let name_index = i32::from_le_bytes(data[off..off + 4].try_into().unwrap());+ let ns_index = i32::from_le_bytes(data[off + 4..off + 8].try_into().unwrap());+ // Layout: name, ns, byval, declaring, parent, element, genericContainer, flags (8*4),+ // then fieldStart, methodStart at +32,+36+ let method_start = i32::from_le_bytes(data[off + 36..off + 40].try_into().unwrap());+ let method_count = u16::from_le_bytes(data[off + 64..off + 66].try_into().unwrap());+ let token = u32::from_le_bytes(data[off + 84..off + 88].try_into().unwrap());+ out.push(TypeDef {+ index: i as u32,+ name: string_at(strings, name_index),+ namespace: string_at(strings, ns_index),+ method_start,+ method_count,+ token,+ });+ }+ Ok(out)+}++fn parse_method_defs(+ data: &[u8],+ header: &MetadataHeader,+ strings: &[(u32, String)],+ dialect: MetadataDialect,+) -> Result<Vec<MethodDef>> {+ let stride = dialect.method_def_stride();+ let count = header.methods_size as usize / stride;+ let base = header.methods_offset as usize;+ let mut out = Vec::with_capacity(count);+ for i in 0..count {+ let off = base + i * stride;+ if off + stride > data.len() {+ return Err(Error::Bounds("method def truncated".into()));+ }+ let name_index = i32::from_le_bytes(data[off..off + 4].try_into().unwrap());+ let declaring_type = i32::from_le_bytes(data[off + 4..off + 8].try_into().unwrap());+ let token = u32::from_le_bytes(data[off + 20..off + 24].try_into().unwrap());+ let parameter_count = u16::from_le_bytes(data[off + 30..off + 32].try_into().unwrap());+ out.push(MethodDef {+ index: i as u32,+ name: string_at(strings, name_index),+ declaring_type,+ token,+ parameter_count,+ });+ }+ Ok(out)+}++fn parse_images(+ data: &[u8],+ header: &MetadataHeader,+ strings: &[(u32, String)],+ dialect: MetadataDialect,+) -> Result<Vec<ImageDef>> {+ let stride = dialect.image_def_stride();+ if header.images_size == 0 {+ return Ok(Vec::new());+ }+ let count = header.images_size as usize / stride;+ let base = header.images_offset as usize;+ let mut out = Vec::with_capacity(count);+ for i in 0..count {+ let off = base + i * stride;+ if off + stride > data.len() {+ return Err(Error::Bounds("image def truncated".into()));+ }+ let name_index = i32::from_le_bytes(data[off..off + 4].try_into().unwrap());+ let type_start = i32::from_le_bytes(data[off + 8..off + 12].try_into().unwrap());+ let type_count = u32::from_le_bytes(data[off + 12..off + 16].try_into().unwrap());+ out.push(ImageDef {+ index: i as u32,+ name: string_at(strings, name_index),+ type_start,+ type_count,+ });+ }+ Ok(out)+}++/// Build a minimal valid metadata blob for tests (dialect v31 layout).+pub fn build_synthetic_v31() -> Vec<u8> {+ build_synthetic(31)+}++pub fn build_synthetic(version: i32) -> Vec<u8> {+ let mut heap = Vec::new();+ let mut push_str = |s: &str| -> i32 {+ let off = heap.len() as i32;+ heap.extend_from_slice(s.as_bytes());+ heap.push(0);+ off+ };+ let ns = push_str("UnityEngine");+ let cam = push_str("Camera");+ let get_main = push_str("get_main");+ let asm = push_str("UnityEngine.CoreModule.dll");++ let mut type_def = vec![0u8; 88];+ type_def[0..4].copy_from_slice(&cam.to_le_bytes());+ type_def[4..8].copy_from_slice(&ns.to_le_bytes());+ type_def[36..40].copy_from_slice(&0i32.to_le_bytes());+ type_def[64..66].copy_from_slice(&1u16.to_le_bytes());+ type_def[84..88].copy_from_slice(&0x02000001u32.to_le_bytes());++ let mut method_def = vec![0u8; 32];+ method_def[0..4].copy_from_slice(&get_main.to_le_bytes());+ method_def[4..8].copy_from_slice(&0i32.to_le_bytes());+ method_def[20..24].copy_from_slice(&0x06000001u32.to_le_bytes());+ method_def[30..32].copy_from_slice(&0u16.to_le_bytes());++ let mut image = vec![0u8; 40];+ image[0..4].copy_from_slice(&asm.to_le_bytes());+ image[8..12].copy_from_slice(&0i32.to_le_bytes());+ image[12..16].copy_from_slice(&1u32.to_le_bytes());++ let mut header_fields: Vec<u8> = Vec::new();+ header_fields.extend_from_slice(&METADATA_MAGIC.to_le_bytes());+ header_fields.extend_from_slice(&version.to_le_bytes());++ let mut slots: Vec<usize> = Vec::new();+ let mut push_pair = |hf: &mut Vec<u8>| {+ let idx = hf.len();+ hf.extend_from_slice(&0u32.to_le_bytes());+ hf.extend_from_slice(&0u32.to_le_bytes());+ slots.push(idx);+ slots.len() - 1+ };++ let i_sl = push_pair(&mut header_fields);+ let i_sld = push_pair(&mut header_fields);+ let i_str = push_pair(&mut header_fields);+ let _ = push_pair(&mut header_fields); // events+ let _ = push_pair(&mut header_fields); // properties+ let i_me = push_pair(&mut header_fields);+ for _ in 0..13 {+ let _ = push_pair(&mut header_fields);+ }+ let i_ty = push_pair(&mut header_fields);+ let i_im = push_pair(&mut header_fields);+ let _ = push_pair(&mut header_fields); // assemblies+ let _ = push_pair(&mut header_fields); // fieldRefs+ let _ = push_pair(&mut header_fields); // referencedAssemblies+ let _ = push_pair(&mut header_fields); // attr0+ let _ = push_pair(&mut header_fields); // attr1+ let _ = push_pair(&mut header_fields); // uvc types+ let _ = push_pair(&mut header_fields); // uvc ranges+ let _ = push_pair(&mut header_fields); // wrt names+ if version >= 27 {+ let _ = push_pair(&mut header_fields); // wrt strings+ }+ let _ = push_pair(&mut header_fields); // exported++ let hdr_len = header_fields.len() as u32;+ let mut out = header_fields;++ fn patch(out: &mut [u8], slots: &[usize], slot: usize, offset: u32, size: u32) {+ let idx = slots[slot];+ out[idx..idx + 4].copy_from_slice(&offset.to_le_bytes());+ out[idx + 4..idx + 8].copy_from_slice(&size.to_le_bytes());+ }++ patch(&mut out, &slots, i_sl, hdr_len, 0);+ patch(&mut out, &slots, i_sld, hdr_len, 0);++ let str_off = out.len() as u32;+ out.extend_from_slice(&heap);+ patch(&mut out, &slots, i_str, str_off, heap.len() as u32);++ let ty_off = out.len() as u32;+ out.extend_from_slice(&type_def);+ patch(&mut out, &slots, i_ty, ty_off, type_def.len() as u32);++ let me_off = out.len() as u32;+ out.extend_from_slice(&method_def);+ patch(&mut out, &slots, i_me, me_off, method_def.len() as u32);++ let im_off = out.len() as u32;+ out.extend_from_slice(&image);+ patch(&mut out, &slots, i_im, im_off, image.len() as u32);++ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn synthetic_v31_roundtrip() {+ let bytes = build_synthetic_v31();+ let meta = Il2CppMetadata::parse(&bytes).expect("parse");+ assert_eq!(meta.header.version, 31);+ assert_eq!(meta.header.dialect, MetadataDialect::V31);+ assert!(meta.types.iter().any(|t| t.full_name() == "UnityEngine.Camera"));+ assert!(meta+ .methods+ .iter()+ .any(|m| meta.method_full_name(m).contains("get_main")));+ }++ #[test]+ fn encrypted_magic_fails_closed() {+ let mut bytes = build_synthetic_v31();+ bytes[0] = 0x04;+ bytes[1] = 0x05;+ bytes[2] = 0x06;+ bytes[3] = 0x07;+ let err = Il2CppMetadata::parse(&bytes).unwrap_err();+ assert!(matches!(err, Error::EncryptedOrObfuscated { .. }));+ }++ #[test]+ fn unsupported_version() {+ let mut bytes = build_synthetic(31);+ bytes[4..8].copy_from_slice(&106i32.to_le_bytes());+ // magic still valid but version unsupported+ let err = Il2CppMetadata::parse(&bytes).unwrap_err();+ assert!(matches!(err, Error::UnsupportedVersion { version: 106, .. }));+ }+}diff --git a/crates/ghidrust-il2cpp/src/stubs.rs b/crates/ghidrust-il2cpp/src/stubs.rsnew file mode 100644index 0000000..1fd09f0--- /dev/null+++ b/crates/ghidrust-il2cpp/src/stubs.rs@@ -0,0 +1,288 @@+//! IL2CPP lazy resolve-stub classification (version-tolerant pattern library).++use ghidrust_core::{disassemble_range, Program};+use serde::Serialize;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum Il2CppKind {+ ResolveStub,+ ManagedMethod,+ Native,+}++#[derive(Debug, Clone, Serialize)]+pub struct ResolveStub {+ pub entry: u64,+ pub icall_name: Option<String>,+ pub name_string_va: Option<u64>,+ pub slot_va: Option<u64>,+ pub kind: Il2CppKind,+}++/// Classify a short function as an IL2CPP resolve thunk when the common pattern matches:+/// LEA name → call resolve → store slot → jmp rax (or similar).+pub fn classify_at(prog: &Program, entry: u64) -> Option<ResolveStub> {+ let listing = disassemble_range(prog, entry, 32).ok()?;+ if listing.is_empty() {+ return None;+ }+ let mut has_lea_string = false;+ let mut has_call = false;+ let mut has_store = false;+ let mut has_jmp_reg = false;+ let mut name_string_va = None;+ let mut slot_va = None;+ let mut insn_count = 0usize;++ for insn in &listing {+ let m = insn.mnemonic.to_ascii_lowercase();+ if m == "int3" && insn_count > 0 {+ break;+ }+ insn_count += 1;+ if insn_count > 32 {+ break;+ }+ let ops = insn.operands.to_ascii_lowercase();+ if m == "lea" {+ for t in ghidrust_core::rip_relative_targets(insn) {+ if looks_like_c_string(prog, t) {+ has_lea_string = true;+ name_string_va = Some(t);+ } else if prog.contains_va(t) {+ slot_va.get_or_insert(t);+ }+ }+ }+ if m == "call" {+ has_call = true;+ }+ if (m == "mov" || m == "movabs") && ops.contains('[') && (ops.contains("rax") || ops.contains("eax")) {+ has_store = true;+ for t in ghidrust_core::rip_relative_targets(insn) {+ slot_va = Some(t);+ }+ }+ if (m == "jmp" || m == "call")+ && (ops.contains("rax")+ || ops.contains("rcx")+ || ops.contains("rdx")+ || ops.contains("r8")+ || ops.contains("r9"))+ && !ops.contains('[')+ && !ops.contains("0x")+ {+ has_jmp_reg = true;+ // Natural end of resolve thunk.+ break;+ }+ }++ if has_lea_string && has_call && (has_jmp_reg || has_store) {+ let icall_name = name_string_va.and_then(|va| read_c_string(prog, va));+ return Some(ResolveStub {+ entry,+ icall_name,+ name_string_va,+ slot_va,+ kind: Il2CppKind::ResolveStub,+ });+ }+ None+}++/// Scan for resolve stubs (prefer function entries; fall back to aligned walk).+pub fn find_resolve_stubs(prog: &Program, max_scan: usize) -> Vec<ResolveStub> {+ let mut out = Vec::new();+ let mut seen = std::collections::HashSet::new();++ for f in &prog.analysis.functions {+ if out.len() >= max_scan {+ break;+ }+ if let Some(stub) = classify_at(prog, f.entry) {+ if seen.insert(stub.entry) {+ out.push(stub);+ }+ }+ }++ let mut scanned = 0usize;+ for block in &prog.blocks {+ if !block.executable {+ continue;+ }+ let mut off = 0usize;+ while off + 4 < block.bytes.len() && scanned < max_scan {+ let va = block.va + off as u64;+ scanned += 1;+ if seen.contains(&va) {+ off += 1;+ continue;+ }+ if let Some(stub) = classify_at(prog, va) {+ if seen.insert(stub.entry) {+ out.push(stub);+ }+ off += 16;+ continue;+ }+ off += 1;+ }+ }+ out.sort_by_key(|s| s.entry);+ out.dedup_by_key(|s| s.entry);+ out+}++/// True when `va` is the entry (or within a few bytes) of a classified resolve stub.+pub fn is_resolve_stub_va(prog: &Program, va: u64) -> bool {+ classify_at(prog, va).is_some()+ || (1..8).any(|d| classify_at(prog, va.saturating_sub(d)).is_some())+}++/// Follow a resolve stub to the cached target pointer in its slot (when mapped).+pub fn follow_stub_target(prog: &Program, stub: &ResolveStub) -> Option<u64> {+ let slot = stub.slot_va?;+ let bytes = prog.read_va(slot, 8)?;+ if bytes.len() < 8 {+ return None;+ }+ let target = u64::from_le_bytes(bytes[0..8].try_into().ok()?);+ if prog.contains_va(target) && target != 0 {+ Some(target)+ } else {+ None+ }+}++/// Match stub against a filter on parsed name and/or raw C-string at `name_string_va`.+pub fn stub_matches_filter(prog: &Program, stub: &ResolveStub, filter: &str) -> bool {+ let fl = filter.to_ascii_lowercase();+ if stub+ .icall_name+ .as_ref()+ .map(|n| n.to_ascii_lowercase().contains(&fl))+ .unwrap_or(false)+ {+ return true;+ }+ if let Some(va) = stub.name_string_va {+ if let Some(s) = read_c_string(prog, va) {+ return s.to_ascii_lowercase().contains(&fl);+ }+ }+ false+}++fn looks_like_c_string(prog: &Program, va: u64) -> bool {+ read_c_string(prog, va).is_some_and(|s| {+ s.len() >= 3+ && s.chars()+ .all(|c| c.is_ascii_graphic() || c == ' ' || c == ':' || c == '_' || c == '.')+ && (s.contains('.') || s.contains("::"))+ })+}++fn read_c_string(prog: &Program, va: u64) -> Option<String> {+ let bytes = prog.read_va(va, 256)?;+ let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());+ if end < 3 {+ return None;+ }+ let s = std::str::from_utf8(&bytes[..end]).ok()?;+ if s.chars().any(|c| c.is_ascii_alphabetic()) {+ Some(s.to_string())+ } else {+ None+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use ghidrust_core::program::{MemoryBlock, Program};+ use ghidrust_core::load_path;+ use std::path::PathBuf;++ #[test]+ fn stub_lab_fixture_filter_and_runtime_unresolved() {+ let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("../../fixtures/il2cpp/il2cpp_stub_lab.pe");+ let prog = load_path(&root).expect("load stub lab");+ let stubs = find_resolve_stubs(&prog, 250_000);+ assert!(!stubs.is_empty(), "expected at least one resolve stub");+ let hits: Vec<_> = stubs+ .iter()+ .filter(|s| stub_matches_filter(&prog, s, "Camera"))+ .collect();+ assert!(!hits.is_empty(), "filter Camera should hit stub lab");+ let stub = hits[0];+ assert!(+ follow_stub_target(&prog, stub).is_none(),+ "slot is zero → runtime_unresolved"+ );+ assert_eq!(stub.entry, 0x140001000);+ }++ #[test]+ fn classify_synthetic_resolve_stub() {+ let image_base = 0x140000000u64;+ let text_va = image_base + 0x1000;+ let rdata_va = image_base + 0x2000;+ let name = b"UnityEngine.Camera::get_main\0";+ let mut rdata = name.to_vec();+ while rdata.len() % 8 != 0 {+ rdata.push(0);+ }+ let slot_off = rdata.len();+ rdata.extend_from_slice(&0u64.to_le_bytes());++ let mut text = Vec::new();+ let lea_va = text_va;+ text.extend_from_slice(&[0x48, 0x8D, 0x0D]);+ let rip_after_lea = lea_va + 7;+ let disp = (rdata_va as i64) - (rip_after_lea as i64);+ text.extend_from_slice(&(disp as i32).to_le_bytes());+ text.extend_from_slice(&[0xE8, 0x00, 0x00, 0x00, 0x00]);+ let store_va = text_va + text.len() as u64;+ text.extend_from_slice(&[0x48, 0x89, 0x05]);+ let rip_after_store = store_va + 7;+ let slot_va = rdata_va + slot_off as u64;+ let disp2 = (slot_va as i64) - (rip_after_store as i64);+ text.extend_from_slice(&(disp2 as i32).to_le_bytes());+ text.extend_from_slice(&[0xFF, 0xE0]);++ let mut prog = Program::new("stub".into(), "PE32+");+ prog.image_base = image_base;+ prog.blocks.push(MemoryBlock {+ name: ".text".into(),+ va: text_va,+ size: text.len() as u64,+ bytes: text,+ readable: true,+ writable: false,+ executable: true,+ });+ prog.blocks.push(MemoryBlock {+ name: ".rdata".into(),+ va: rdata_va,+ size: rdata.len() as u64,+ bytes: rdata,+ readable: true,+ writable: true,+ executable: false,+ });++ let stub = classify_at(&prog, text_va).expect("stub");+ assert_eq!(stub.kind, Il2CppKind::ResolveStub);+ assert!(stub+ .icall_name+ .as_deref()+ .unwrap_or("")+ .contains("Camera"));+ assert!(follow_stub_target(&prog, &stub).is_none());+ assert!(stub_matches_filter(&prog, &stub, "Camera"));+ }+}diff --git a/crates/ghidrust-unity-inventory/Cargo.toml b/crates/ghidrust-unity-inventory/Cargo.tomlnew file mode 100644index 0000000..da52308--- /dev/null+++ b/crates/ghidrust-unity-inventory/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "ghidrust-unity-inventory"+version.workspace = true+edition.workspace = true+license.workspace = true+description = "Unity player install layout inventory"++[dependencies]+ghidrust-core = { workspace = true }+ghidrust-il2cpp = { workspace = true }+serde = { version = "1", features = ["derive"] }+serde_json = "1"+sha2 = "0.10"+hex = "0.4"diff --git a/crates/ghidrust-unity-inventory/src/lib.rs b/crates/ghidrust-unity-inventory/src/lib.rsnew file mode 100644index 0000000..2b0b47a--- /dev/null+++ b/crates/ghidrust-unity-inventory/src/lib.rs@@ -0,0 +1,505 @@+//! Unity player install inventory (assemblies, plugins, metadata, XR-related fields).++use ghidrust_core::load_path;+use ghidrust_il2cpp::{Il2CppMetadata, METADATA_MAGIC};+use serde::Serialize;+use sha2::{Digest, Sha256};+use std::fs;+use std::path::{Path, PathBuf};++pub const SCHEMA_VERSION: u32 = 1;++#[derive(Debug, Clone, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum XrVerdict {+ None,+ StockStubsOnly,+ UnityXrPackaged,+ ExternalModLikely,+ Mixed,+}++#[derive(Debug, Clone, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum Confidence {+ Low,+ Medium,+ High,+}++#[derive(Debug, Clone, Serialize)]+pub struct FileHash {+ pub path: String,+ pub sha256: String,+}++#[derive(Debug, Clone, Serialize)]+pub struct MetadataPeek {+ pub path: String,+ pub present: bool,+ pub magic: Option<String>,+ pub version: Option<i32>,+ pub encrypted_or_obfuscated: bool,+ pub note: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+pub struct EngineFingerprint {+ pub il2cpp: bool,+ pub mono: bool,+ pub burst: bool,+ pub urp: bool,+ pub hdrp: bool,+}++#[derive(Debug, Clone, Serialize)]+pub struct UnityInventory {+ pub schema_version: u32,+ pub root: String,+ pub data_dir: Option<String>,+ pub app_info: Option<String>,+ pub boot_config: Option<Vec<String>>,+ pub scripting_assemblies: Vec<String>,+ pub runtime_initialize_on_loads: Option<usize>,+ pub plugins: Vec<String>,+ pub metadata: Option<MetadataPeek>,+ pub addressables_hint: bool,+ pub engine: EngineFingerprint,+ pub xr_stock_modules: Vec<String>,+ pub xr_packages: Vec<String>,+ pub xr_subsystem_manifests: Vec<String>,+ pub native_xr_imports: Vec<String>,+ pub external_vr_indicators: Vec<String>,+ pub key_hashes: Vec<FileHash>,+ pub verdict: XrVerdict,+ pub confidence: Confidence,+ pub notes: Vec<String>,+}++/// Inventory a Unity player directory (exe + `*_Data/` layout).+pub fn inventory_path(root: impl AsRef<Path>) -> Result<UnityInventory, String> {+ let root = root.as_ref();+ if !root.is_dir() {+ return Err(format!("not a directory: {}", root.display()));+ }+ let mut notes = Vec::new();+ let data_dir = find_data_dir(root);+ let data_dir_s = data_dir.as_ref().map(|p| p.display().to_string());++ let app_info = data_dir+ .as_ref()+ .and_then(|d| read_trimmed(d.join("app.info")));+ let boot_config = data_dir.as_ref().and_then(|d| {+ let p = d.join("boot.config");+ fs::read_to_string(p).ok().map(|s| {+ s.lines()+ .map(|l| l.trim().to_string())+ .filter(|l| !l.is_empty())+ .collect()+ })+ });++ let scripting_assemblies = data_dir+ .as_ref()+ .map(|d| read_scripting_assemblies(&d.join("ScriptingAssemblies.json")))+ .unwrap_or_default();++ let runtime_initialize_on_loads = data_dir.as_ref().and_then(|d| {+ let p = d.join("RuntimeInitializeOnLoads.json");+ fs::read_to_string(p).ok().and_then(|s| {+ serde_json::from_str::<serde_json::Value>(&s)+ .ok()+ .and_then(|v| v.as_array().map(|a| a.len()))+ })+ });++ let plugins = data_dir+ .as_ref()+ .map(|d| list_plugins(&d.join("Plugins")))+ .unwrap_or_default();++ let metadata = data_dir.as_ref().map(|d| peek_metadata(d));++ let addressables_hint = data_dir+ .as_ref()+ .map(|d| d.join("StreamingAssets").join("aa").is_dir())+ .unwrap_or(false);++ let (xr_stock_modules, xr_packages) = classify_assemblies(&scripting_assemblies);+ let xr_subsystem_manifests = data_dir+ .as_ref()+ .map(|d| find_subsystem_manifests(d))+ .unwrap_or_default();++ let mut native_xr_imports = Vec::new();+ let mut external_vr_indicators = Vec::new();+ let mut key_hashes = Vec::new();++ // Hash player exe + GameAssembly / UnityPlayer when present.+ for name in ["GameAssembly.dll", "UnityPlayer.dll"] {+ let p = root.join(name);+ if p.is_file() {+ if let Some(h) = hash_file(&p) {+ key_hashes.push(h);+ }+ if let Ok(prog) = load_path(&p) {+ for e in &prog.imports {+ let dll = e.dll.to_ascii_lowercase();+ let name = e+ .name+ .as_deref()+ .unwrap_or("")+ .to_ascii_lowercase();+ if dll.contains("openxr")+ || dll.contains("xr")+ || name.contains("openxr")+ || name.contains("xrgetinstance")+ {+ let label = format!(+ "{}!{}",+ e.dll,+ e.name.clone().unwrap_or_else(|| "?".into())+ );+ if !native_xr_imports.contains(&label) {+ native_xr_imports.push(label);+ }+ }+ }+ }+ }+ }+ for p in fs::read_dir(root).into_iter().flatten().flatten() {+ let path = p.path();+ let fname = path+ .file_name()+ .map(|s| s.to_string_lossy().to_ascii_lowercase())+ .unwrap_or_default();+ if fname.ends_with(".exe") {+ if let Some(h) = hash_file(&path) {+ key_hashes.push(h);+ }+ }+ if fname.contains("inject") && fname.ends_with(".dll") {+ external_vr_indicators.push(format!("sidecar_dll:{}", path.display()));+ }+ if fname.contains("openxr") && fname.ends_with(".dll") && xr_packages.is_empty() {+ external_vr_indicators.push(format!("openxr_loader_no_xr_packages:{}", path.display()));+ }+ if fname.starts_with("dxgi") && fname.ends_with(".dll") {+ external_vr_indicators.push(format!("dxgi_proxy:{}", path.display()));+ }+ }++ if scripting_assemblies.is_empty() && data_dir.is_none() {+ notes.push("no *_Data directory or ScriptingAssemblies.json found".into());+ }++ let engine = EngineFingerprint {+ il2cpp: metadata.as_ref().is_some_and(|m| m.present)+ || root.join("GameAssembly.dll").is_file(),+ mono: scripting_assemblies.iter().any(|a| a.contains("mscorlib"))+ && !root.join("GameAssembly.dll").is_file(),+ burst: scripting_assemblies.iter().any(|a| a.contains("Unity.Burst")),+ urp: scripting_assemblies+ .iter()+ .any(|a| a.contains("UniversalRenderPipeline") || a.contains("Unity.RenderPipelines.Universal")),+ hdrp: scripting_assemblies+ .iter()+ .any(|a| a.contains("HighDefinition") || a.contains("Unity.RenderPipelines.HighDefinition")),+ };++ let (verdict, confidence) = verdict(+ &xr_stock_modules,+ &xr_packages,+ &xr_subsystem_manifests,+ &native_xr_imports,+ &external_vr_indicators,+ );++ Ok(UnityInventory {+ schema_version: SCHEMA_VERSION,+ root: root.display().to_string(),+ data_dir: data_dir_s,+ app_info,+ boot_config,+ scripting_assemblies,+ runtime_initialize_on_loads,+ plugins,+ metadata,+ addressables_hint,+ engine,+ xr_stock_modules,+ xr_packages,+ xr_subsystem_manifests,+ native_xr_imports,+ external_vr_indicators,+ key_hashes,+ verdict,+ confidence,+ notes,+ })+}++fn find_data_dir(root: &Path) -> Option<PathBuf> {+ let mut dirs: Vec<PathBuf> = fs::read_dir(root)+ .ok()?+ .flatten()+ .map(|e| e.path())+ .filter(|p| {+ p.is_dir()+ && p.file_name()+ .map(|n| n.to_string_lossy().ends_with("_Data"))+ .unwrap_or(false)+ })+ .collect();+ dirs.sort();+ dirs.into_iter().next()+}++fn read_trimmed(path: PathBuf) -> Option<String> {+ fs::read_to_string(path)+ .ok()+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+}++fn read_scripting_assemblies(path: &Path) -> Vec<String> {+ let Ok(text) = fs::read_to_string(path) else {+ return Vec::new();+ };+ // Format: { "names": ["A.dll", ...], "types": [...] }+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {+ if let Some(names) = v.get("names").and_then(|n| n.as_array()) {+ return names+ .iter()+ .filter_map(|x| x.as_str().map(|s| s.to_string()))+ .collect();+ }+ }+ Vec::new()+}++fn list_plugins(dir: &Path) -> Vec<String> {+ let mut out = Vec::new();+ if !dir.is_dir() {+ return out;+ }+ fn walk(dir: &Path, out: &mut Vec<String>) {+ let Ok(rd) = fs::read_dir(dir) else { return };+ for e in rd.flatten() {+ let p = e.path();+ if p.is_dir() {+ walk(&p, out);+ } else if p+ .extension()+ .map(|x| x.eq_ignore_ascii_case("dll") || x.eq_ignore_ascii_case("so"))+ .unwrap_or(false)+ {+ out.push(p.display().to_string());+ }+ }+ }+ walk(dir, &mut out);+ out.sort();+ out+}++fn peek_metadata(data_dir: &Path) -> MetadataPeek {+ let path = data_dir+ .join("il2cpp_data")+ .join("Metadata")+ .join("global-metadata.dat");+ let path_s = path.display().to_string();+ if !path.is_file() {+ return MetadataPeek {+ path: path_s,+ present: false,+ magic: None,+ version: None,+ encrypted_or_obfuscated: false,+ note: Some("global-metadata.dat not found".into()),+ };+ }+ let Ok(bytes) = fs::read(&path) else {+ return MetadataPeek {+ path: path_s,+ present: true,+ magic: None,+ version: None,+ encrypted_or_obfuscated: false,+ note: Some("failed to read metadata".into()),+ };+ };+ match Il2CppMetadata::peek(&bytes) {+ Ok((magic, version, _)) => MetadataPeek {+ path: path_s,+ present: true,+ magic: Some(format!("{magic:#010x}")),+ version: Some(version),+ encrypted_or_obfuscated: false,+ note: None,+ },+ Err(ghidrust_il2cpp::Error::EncryptedOrObfuscated { magic, version_field }) => {+ MetadataPeek {+ path: path_s,+ present: true,+ magic: Some(format!("{magic:#010x}")),+ version: Some(version_field),+ encrypted_or_obfuscated: true,+ note: Some(format!(+ "expected magic {METADATA_MAGIC:#010x}; treat as encrypted/obfuscated"+ )),+ }+ }+ Err(e) => MetadataPeek {+ path: path_s,+ present: true,+ magic: None,+ version: None,+ encrypted_or_obfuscated: false,+ note: Some(e.to_string()),+ },+ }+}++fn classify_assemblies(names: &[String]) -> (Vec<String>, Vec<String>) {+ let mut stock = Vec::new();+ let mut packages = Vec::new();+ for n in names {+ let l = n.to_ascii_lowercase();+ if l.contains("unityengine.xrmodule") || l.contains("unityengine.vrmodule") {+ stock.push(n.clone());+ } else if l.contains("unity.xr.")+ || l.contains("unityengine.xr.")+ || l.contains("openxr")+ || l.contains("oculus")+ || l.contains("steamvr")+ || l.contains("openvr")+ || l.contains("xr.management")+ {+ // Stock modules already caught; remaining XR-ish → packages/providers+ if !l.contains("unityengine.xrmodule") && !l.contains("unityengine.vrmodule") {+ packages.push(n.clone());+ }+ }+ }+ (stock, packages)+}++fn find_subsystem_manifests(data_dir: &Path) -> Vec<String> {+ let mut out = Vec::new();+ let roots = [+ data_dir.join("StreamingAssets"),+ data_dir.join("Plugins"),+ ];+ for root in roots {+ if !root.exists() {+ continue;+ }+ fn walk(dir: &Path, out: &mut Vec<String>) {+ let Ok(rd) = fs::read_dir(dir) else { return };+ for e in rd.flatten() {+ let p = e.path();+ if p.is_dir() {+ walk(&p, out);+ } else if p+ .file_name()+ .map(|n| n == "UnitySubsystemsManifest.json")+ .unwrap_or(false)+ {+ out.push(p.display().to_string());+ }+ }+ }+ walk(&root, &mut out);+ }+ out.sort();+ out+}++fn hash_file(path: &Path) -> Option<FileHash> {+ let data = fs::read(path).ok()?;+ let mut hasher = Sha256::new();+ hasher.update(&data);+ let digest = hasher.finalize();+ Some(FileHash {+ path: path.display().to_string(),+ sha256: hex::encode(digest),+ })+}++fn verdict(+ stock: &[String],+ packages: &[String],+ manifests: &[String],+ native: &[String],+ external: &[String],+) -> (XrVerdict, Confidence) {+ let has_stock = !stock.is_empty();+ let has_pkg = !packages.is_empty() || !manifests.is_empty();+ let has_ext = !external.is_empty();+ let has_native = !native.is_empty();++ if !has_stock && !has_pkg && !has_ext && !has_native {+ return (XrVerdict::None, Confidence::Medium);+ }+ if has_ext && has_pkg {+ return (XrVerdict::Mixed, Confidence::High);+ }+ if has_ext && !has_pkg {+ return (XrVerdict::ExternalModLikely, Confidence::High);+ }+ if has_pkg {+ return (XrVerdict::UnityXrPackaged, Confidence::High);+ }+ if has_stock && !has_pkg {+ let conf = if has_native {+ Confidence::Medium+ } else {+ Confidence::High+ };+ return (XrVerdict::StockStubsOnly, conf);+ }+ (XrVerdict::None, Confidence::Low)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn stock_stubs_verdict() {+ let dir = tempfile_dir("stock");+ let data = dir.join("Game_Data");+ fs::create_dir_all(&data).unwrap();+ let json = r#"{"names":["UnityEngine.dll","UnityEngine.XRModule.dll","Assembly-CSharp.dll"],"types":[0,0,0]}"#;+ fs::write(data.join("ScriptingAssemblies.json"), json).unwrap();+ let inv = inventory_path(&dir).unwrap();+ assert_eq!(inv.verdict, XrVerdict::StockStubsOnly);+ assert!(inv.xr_stock_modules.iter().any(|s| s.contains("XRModule")));+ assert!(inv.xr_packages.is_empty());+ }++ #[test]+ fn packaged_xr_verdict() {+ let dir = tempfile_dir("pkg");+ let data = dir.join("Game_Data");+ fs::create_dir_all(&data).unwrap();+ let json = r#"{"names":["Unity.XR.Management.dll","Unity.XR.OpenXR.dll"],"types":[0,0]}"#;+ fs::write(data.join("ScriptingAssemblies.json"), json).unwrap();+ let inv = inventory_path(&dir).unwrap();+ assert_eq!(inv.verdict, XrVerdict::UnityXrPackaged);+ }++ fn tempfile_dir(tag: &str) -> PathBuf {+ let mut p = std::env::temp_dir();+ p.push(format!(+ "ghidrust_unity_inv_{}_{}",+ tag,+ std::process::id()+ ));+ let _ = fs::remove_dir_all(&p);+ fs::create_dir_all(&p).unwrap();+ p+ }+}diff --git a/docs/IL2CPP.md b/docs/IL2CPP.mdnew file mode 100644index 0000000..4589933--- /dev/null+++ b/docs/IL2CPP.md@@ -0,0 +1,114 @@+# IL2CPP + Unity inventory (Ghidrust)++Hand-rolled support for Unity IL2CPP metadata and player-install inventory. No Il2CppDumper, Cpp2IL, or goblin at runtime — see [DEPENDENCIES.md](../DEPENDENCIES.md).++## Commands++```text+ghidrust strings <path> [--raw] [--match substr|token|whole|glob] [--limit N] [--out FILE]+ghidrust bytes <path> --addr HEX [--count N] [--out FILE] [--json]+ghidrust il2cpp meta <global-metadata.dat> [--filter SUB] [--json] [--out FILE]+ghidrust il2cpp map --binary <GameAssembly.dll> --meta <metadata.dat> [--script-json]+ghidrust il2cpp stubs --binary <GameAssembly.dll> [--filter SUB]+ghidrust il2cpp icalls --binary <UnityPlayer.dll> [--filter SUB] [--json] [--out FILE]+ghidrust xrefs … [--skip-stubs] [--classify] [--out FILE]+ghidrust disasm … [--out FILE]+ghidrust decompile … [--follow-stub] [--out FILE]+ghidrust unity-inventory <player-dir> [--json]+```++## Engine icall resolve (name‖fn tables)++Unity engine PEs often store parallel pointer arrays: one of C-string name VAs (`Namespace.Type::method` / `*_Injected`) and one of code VAs. After `Create Address Tables` (stitched runs with `DataPtrs` / `CodePtrs` roles):++```text+ghidrust strings <engine.dll> --filter <ICallNameFragment> --json+ghidrust xrefs <engine.dll> --to <name_string_va> --json # hits rdata pointer slots+ghidrust il2cpp icalls --binary <engine.dll> --filter <ICallNameFragment> --json+ghidrust bytes <engine.dll> --addr <fn_va> --count 64 --json+ghidrust disasm <engine.dll> --addr <fn_va> --count 20 --json+```++`il2cpp icalls` never invents RVAs: it only emits pairs when a name table of length `N` sits adjacent to a code table of length `N`. Ambiguous multi-table hits are returned as candidates with confidence.++## Resolve stubs vs real callers++GameAssembly resolve thunks (`LEA` name → resolve → store slot → `jmp reg`) are lazy. Prefer:++```text+ghidrust xrefs GA.dll --to HEX --skip-stubs --classify --json+ghidrust il2cpp stubs --binary GA.dll --filter <ICallNameFragment> --json+ghidrust decompile GA.dll --addr <stub_va> --follow-stub --json+```++`--follow-stub` reports `follow_stub.status = runtime_unresolved` when the slot is still zero (filled at runtime). Filter matches parsed `icall_name` or the C-string at `name_string_va`.++## MCP tools++Launch: `ghidrust mcp` (or `target/release/ghidrust.exe mcp` after build). Stdio JSON-RPC; no host-specific paths required.++| Tool | Args | Purpose |+|------|------|---------|+| `il2cpp_meta` | `path`, optional `filter` | Parse `global-metadata.dat` → types/methods |+| `il2cpp_map` | `binary`, `meta`, optional `filter` | Metadata ↔ RVA map (`rva` null when unproven) |+| `il2cpp_stubs` | `binary`, optional `filter`, `max` | Classify resolve stubs |+| `il2cpp_icalls` | `binary`, optional `filter` | Engine name‖fn icall tables |+| `read_bytes` | `path`, `addr`, optional `count` | Raw VA dump |+| `unity_inventory` | `path` | Player layout inventory (assemblies, plugins, metadata) |+| `list_strings` | `path`, optional `encoding`/`filter`/`match`/`limit`/`raw`/`min` | Blob-capable string scan |+| `get_xrefs_to` | `path`, `addr`, optional `skip_stubs`/`classify` | Data-ptr + stub-aware xrefs |+| `decompile` | `path`, optional `addr`/`count`/`stage`/`follow_stub` | Follow resolve stub when mapped |++## Metadata version matrix++| Metadata version | Dialect | Status |+|------------------|---------|--------|+| 27.x | `V27` | P0 supported |+| 29.x | `V29` | P0 supported |+| 31.x | `V31` | P0 supported |+| 24.x family | — | P1 (unsupported error with hint) |+| 39 / 106 | — | P1 (sectioned / variable-width) |++Magic must be `0xFAB11BAF`. Wrong magic → fail closed. CLI/MCP JSON:++```json+{+ "error": "metadata_encrypted_or_obfuscated",+ "magic": "0x…",+ "next_steps": [+ "Use engine PE strings + il2cpp icalls for native internal-call RVAs",+ "Treat GameAssembly resolve stubs as lazy thunks, not gameplay callers (xrefs --skip-stubs)",+ "Instance/type latch may require live inspection when metadata is unavailable"+ ]+}+```++## Notes++1. Managed type/method names live in metadata heaps — use `il2cpp meta`, not PE string scans alone.+2. Method RVAs are emitted only when CodeRegistration-style pointer arrays pass multi-field validation; otherwise `rva: null`.+3. Encrypted/obfuscated metadata is reported with `next_steps`, not guessed.+4. `unity-inventory` classifies scripting assemblies and plugins from the player layout (including stock engine XR modules vs XR provider packages when present).+5. Lone rdata qword pointers to strings are found by `xrefs --to` (kind `ptr`), not only by address-table slots.++## Fixtures++Synthetic acceptance fixtures (no private game trees):++```text+fixtures/il2cpp/meta_v27.dat+fixtures/il2cpp/meta_v29.dat+fixtures/il2cpp/meta_v31.dat+fixtures/il2cpp/il2cpp_stub_lab.pe+```++Regenerate: `python scripts/gen_il2cpp_fixtures.py`++## Unity inventory schema++`unity-inventory` emits `schema_version: 1` with scripting assemblies, plugins, metadata peek, engine fingerprint, and optional XR-related fields:++- `xr_stock_modules` / `xr_packages` / `xr_subsystem_manifests`+- `native_xr_imports` / `external_vr_indicators`+- `verdict`: `none` | `stock_stubs_only` | `unity_xr_packaged` | `external_mod_likely` | `mixed`+- `confidence`: `low` | `medium` | `high`diff --git a/fixtures/il2cpp/README.txt b/fixtures/il2cpp/README.txtnew file mode 100644index 0000000..850b215--- /dev/null+++ b/fixtures/il2cpp/README.txt@@ -0,0 +1,2 @@+Synthetic IL2CPP fixtures for ghidrust-il2cpp / CLI acceptance.+Regenerate: python scripts/gen_il2cpp_fixtures.pydiff --git a/fixtures/il2cpp/il2cpp_stub_lab.pe b/fixtures/il2cpp/il2cpp_stub_lab.penew file mode 100644index 0000000..c2a3cacBinary files /dev/null and b/fixtures/il2cpp/il2cpp_stub_lab.pe differdiff --git a/fixtures/il2cpp/meta_v27.dat b/fixtures/il2cpp/meta_v27.datnew file mode 100644index 0000000..8365fa1Binary files /dev/null and b/fixtures/il2cpp/meta_v27.dat differdiff --git a/fixtures/il2cpp/meta_v29.dat b/fixtures/il2cpp/meta_v29.datnew file mode 100644index 0000000..a8a5be3Binary files /dev/null and b/fixtures/il2cpp/meta_v29.dat differdiff --git a/fixtures/il2cpp/meta_v31.dat b/fixtures/il2cpp/meta_v31.datnew file mode 100644index 0000000..8b0a382Binary files /dev/null and b/fixtures/il2cpp/meta_v31.dat differdiff --git a/scripts/gen_il2cpp_fixtures.py b/scripts/gen_il2cpp_fixtures.pynew file mode 100644index 0000000..5c4d4f2--- /dev/null+++ b/scripts/gen_il2cpp_fixtures.py@@ -0,0 +1,174 @@+#!/usr/bin/env python3+"""Write synthetic IL2CPP fixtures (no game binaries)."""+from __future__ import annotations+import struct+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+FIX = ROOT / "fixtures" / "il2cpp"+FIX.mkdir(parents=True, exist_ok=True)++MAGIC = 0xFAB11BAF+IMAGE_BASE = 0x140000000+FILE_ALIGN = 0x200+SECT_ALIGN = 0x1000+++def align(n: int, a: int) -> int:+ return (n + a - 1) & ~(a - 1)+++def build_meta(version: int = 31) -> bytes:+ heap = bytearray()++ def push_str(s: str) -> int:+ off = len(heap)+ heap.extend(s.encode("utf-8") + b"\0")+ return off++ ns = push_str("UnityEngine")+ cam = push_str("Camera")+ get_main = push_str("get_main")+ asm = push_str("UnityEngine.CoreModule.dll")++ type_def = bytearray(88)+ struct.pack_into("<i", type_def, 0, cam)+ struct.pack_into("<i", type_def, 4, ns)+ struct.pack_into("<i", type_def, 36, 0)+ struct.pack_into("<H", type_def, 64, 1)+ struct.pack_into("<I", type_def, 84, 0x02000001)++ method_def = bytearray(32)+ struct.pack_into("<i", method_def, 0, get_main)+ struct.pack_into("<i", method_def, 4, 0)+ struct.pack_into("<I", method_def, 20, 0x06000001)++ image = bytearray(40)+ struct.pack_into("<i", image, 0, asm)+ struct.pack_into("<i", image, 8, 0)+ struct.pack_into("<I", image, 12, 1)++ pair_count = 31+ i_sl, i_sld, i_str, i_me, i_ty, i_im = 0, 1, 2, 5, 19, 20++ hdr = bytearray(struct.pack("<Ii", MAGIC, version))+ hdr += b"\0" * (pair_count * 8)++ def patch(i: int, offset: int, size: int) -> None:+ base = 8 + i * 8+ hdr[base : base + 8] = struct.pack("<II", offset, size)++ tables = bytearray()+ hdr_len = len(hdr)+ patch(i_sl, hdr_len, 0)+ patch(i_sld, hdr_len, 0)++ str_off = hdr_len + len(tables)+ tables += heap+ patch(i_str, str_off, len(heap))++ ty_off = hdr_len + len(tables)+ tables += type_def+ patch(i_ty, ty_off, len(type_def))++ me_off = hdr_len + len(tables)+ tables += method_def+ patch(i_me, me_off, len(method_def))++ im_off = hdr_len + len(tables)+ tables += image+ patch(i_im, im_off, len(image))++ return bytes(hdr + tables)+++def build_stub_pe() -> bytes:+ text = bytearray(0x80)+ rdata = bytearray()+ name = b"UnityEngine.Camera::get_main\0"+ rdata += name+ while len(rdata) % 8:+ rdata += b"\0"+ slot_off = len(rdata)+ rdata += struct.pack("<Q", 0)++ name_va = IMAGE_BASE + 0x2000+ slot_va = IMAGE_BASE + 0x2000 + slot_off+ stub_va = IMAGE_BASE + 0x1000++ disp = name_va - (stub_va + 7)+ text[0:3] = bytes([0x48, 0x8D, 0x0D])+ struct.pack_into("<i", text, 3, disp)+ text[7:12] = bytes([0xE8, 0, 0, 0, 0])+ store_va = stub_va + 12+ disp2 = slot_va - (store_va + 7)+ text[12:15] = bytes([0x48, 0x89, 0x05])+ struct.pack_into("<i", text, 15, disp2)+ text[19:21] = bytes([0xFF, 0xE0])+ text[0x40:0x43] = bytes([0x31, 0xC0, 0xC3])++ text_rva, rdata_rva = 0x1000, 0x2000+ entry_rva = text_rva + 0x40+ size_of_headers = 0x200+ text_raw_size = align(len(text), FILE_ALIGN)+ rdata_raw_size = align(len(rdata), FILE_ALIGN)+ text_file = size_of_headers+ rdata_file = text_file + text_raw_size+ size_of_image = align(rdata_rva + align(len(rdata), SECT_ALIGN), SECT_ALIGN)++ dos = bytearray(0x80)+ dos[0:2] = b"MZ"+ struct.pack_into("<I", dos, 0x3C, 0x80)++ coff = struct.pack("<HHIIIHH", 0x8664, 2, 0, 0, 0, 0xF0, 0x22)+ opt = bytearray(0xF0)+ struct.pack_into("<H", opt, 0, 0x20B)+ opt[2] = 14+ struct.pack_into("<I", opt, 16, entry_rva)+ struct.pack_into("<Q", opt, 24, IMAGE_BASE)+ struct.pack_into("<I", opt, 32, SECT_ALIGN)+ struct.pack_into("<I", opt, 36, FILE_ALIGN)+ struct.pack_into("<H", opt, 40, 6)+ struct.pack_into("<I", opt, 56, size_of_image)+ struct.pack_into("<I", opt, 60, size_of_headers)+ struct.pack_into("<H", opt, 68, 3)+ struct.pack_into("<H", opt, 70, 0x160)+ struct.pack_into("<Q", opt, 72, 0x100000)+ struct.pack_into("<Q", opt, 80, 0x1000)+ struct.pack_into("<Q", opt, 88, 0x100000)+ struct.pack_into("<Q", opt, 96, 0x1000)+ struct.pack_into("<I", opt, 108, 0x10)++ def sec(name, vsize, va, raw_size, raw_ptr, chars):+ return name[:8].ljust(8, b"\0") + struct.pack(+ "<IIIIIIHHI", vsize, va, raw_size, raw_ptr, 0, 0, 0, 0, chars+ )++ sh = sec(b".text", SECT_ALIGN, text_rva, text_raw_size, text_file, 0x60000020)+ sh += sec(b".rdata", SECT_ALIGN, rdata_rva, rdata_raw_size, rdata_file, 0x40000040)++ out = bytearray()+ out += dos + b"PE\0\0" + coff + opt + sh+ out += b"\0" * (size_of_headers - len(out))+ out += bytes(text).ljust(text_raw_size, b"\0")+ out += bytes(rdata).ljust(rdata_raw_size, b"\0")+ return bytes(out)+++def main() -> None:+ for ver in (27, 29, 31):+ p = FIX / f"meta_v{ver}.dat"+ p.write_bytes(build_meta(ver))+ print(f"wrote {p} ({p.stat().st_size} bytes)")+ stub = FIX / "il2cpp_stub_lab.pe"+ stub.write_bytes(build_stub_pe())+ print(f"wrote {stub} ({stub.stat().st_size} bytes)")+ (FIX / "README.txt").write_text(+ "Synthetic IL2CPP fixtures for ghidrust-il2cpp / CLI acceptance.\n"+ "Regenerate: python scripts/gen_il2cpp_fixtures.py\n",+ encoding="utf-8",+ )+++if __name__ == "__main__":+ main()diff --git a/skill/README.md b/skill/README.mdindex 96a289e..4c356d1 100644--- a/skill/README.md+++ b/skill/README.md@@ -2,7 +2,7 @@## What Ghidrust is-Ghidrust is a **Rust** reverse-engineering toolkit inspired by [Ghidra](https://github.com/NationalSecurityAgency/ghidra) — not a fork. It loads PE/ELF, disassembles x86-64, runs Auto Analysis, decompiles to pseudo-C, and supports durable projects via **CLI**, **MCP** (stdio), and an **egui** CodeBrowser-style GUI.+Ghidrust is a **Rust** reverse-engineering toolkit inspired by [Ghidra](https://github.com/NationalSecurityAgency/ghidra) — not a fork. It loads PE/ELF (and raw blobs), disassembles x86-64, runs Auto Analysis, decompiles to pseudo-C, parses IL2CPP metadata / Unity install inventory, and supports durable projects via **CLI**, **MCP** (stdio), and an **egui** CodeBrowser-style GUI.**Aims:** a freestanding, auditable RE core; CPU-correct analysis first; optional experimental GPU bulk scan + VRAM-resident decompile; agent-friendly headless use.@@ -19,6 +19,8 @@ cargo build --workspace --release./target/release/ghidrust load fixtures/tiny_x64.pe./target/release/ghidrust disasm fixtures/tiny_x64.pe --count 16./target/release/ghidrust decompile fixtures/tiny_x64.pe+./target/release/ghidrust il2cpp meta fixtures/il2cpp/meta_v31.dat --filter Camera --json+./target/release/ghidrust il2cpp stubs --binary fixtures/il2cpp/il2cpp_stub_lab.pe --json./target/release/ghidrust gpu-decompile fixtures/tiny_x64.pe --out entry.gdecomp --jsoncargo run -p ghidrust-gui --releasediff --git a/skill/SKILL.md b/skill/SKILL.mdindex 36c8f30..8f3ad76 100644--- a/skill/SKILL.md+++ b/skill/SKILL.md@@ -1,14 +1,16 @@---name: ghidrustdescription: >- Use Ghidrust (Rust RE toolkit: PE/ELF load, x86-64 disasm, Auto Analysis, projects,- CLI/MCP, egui GUI, GPU analyzer kernels + multipass decompile) to reverse-engineer- binaries without Ghidra. Exhaustive feature catalog with when-to-use guidance.+ Use Ghidrust (Rust RE toolkit: PE/ELF/blob load, x86-64 disasm, Auto Analysis, projects,+ CLI/MCP, egui GUI, IL2CPP metadata, Unity player inventory, GPU analyzer kernels ++ multipass decompile) to reverse-engineer binaries without Ghidra. Exhaustive feature+ catalog with when-to-use guidance.Triggers: /ghidrust, reverse engineer, RE a PE/ELF, disassemble, RTTI, auto analysis,analyze binary, Ghidrust project, MCP ghidrust, strings/functions, GPU decompile,- analyzer-bench, rtti-gpu-bench, bulk-bench.+ IL2CPP, global-metadata, unity-inventory, GameAssembly, analyzer-bench,+ rtti-gpu-bench, bulk-bench.metadata:- short-description: "Ghidrust RE — CLI, MCP, analyzers, GPU, projects"+ short-description: "Ghidrust RE — CLI, MCP, IL2CPP, Unity, analyzers, GPU"---# Ghidrust — agent skill@@ -19,12 +21,12 @@ Hand-rolled **Rust** reverse-engineering core (Ghidra-inspired labels; measurabl| Item | Path / command ||------|----------------|-| Workspace root | repo root (`Cargo.toml` with `ghidrust-core`, `ghidrust-cli`, `ghidrust-gui`, `ghidrust-decomp`) |+| Workspace root | repo root (`Cargo.toml` with `ghidrust-core`, `ghidrust-cli`, `ghidrust-gui`, `ghidrust-decomp`, `ghidrust-il2cpp`, `ghidrust-unity-inventory`) || CLI | `cargo run -p ghidrust-cli --release -- <cmd>` or `target/release/ghidrust.exe` || GUI | `cargo run -p ghidrust-gui --release` |-| Fixtures | `fixtures/tiny_x64.pe`, `fixtures/analysis_lab.pe`, `fixtures/tiny_x64.elf` |-| Docs | `README.md`, `docs/GPU_ANALYZER_MATRIX.md`, `docs/PARALLEL_RE_RESEARCH.md` (local parity notes under `dev/`) |-| Core API | `load_path`, `run_analyzers` / `run_analyzers_opts`, `Project`, `gpu_analyzers`, `bulk_scan` |+| Fixtures | `fixtures/tiny_x64.pe`, `fixtures/analysis_lab.pe`, `fixtures/tiny_x64.elf`, `fixtures/il2cpp/*` |+| Docs | `README.md`, `docs/IL2CPP.md`, `docs/GPU_ANALYZER_MATRIX.md`, `docs/PARALLEL_RE_RESEARCH.md` |+| Core API | `load_path` / `load_path_opts` / `load_blob`, `collect_strings_opts`, `run_analyzers_opts`, `Project`, `gpu_analyzers`, `bulk_scan` |CLI always builds with `gpu` feature on deps. On Windows PowerShell: `.\target\release\ghidrust.exe …`.@@ -94,6 +96,17 @@ Need Ghidra ↔ Ghidrust head-to-head?→ When neither is supplied, the report is methodology-only: Ghidra column left blank+ full runbook (dev/GHIDRA_HEADTOHEAD.md). Spawn failures surface as factual`ghidra spawn failed: <reason>` notes — no fabricated timings.++Unity player / IL2CPP?+ → unity-inventory GAME_DIR for install layout (assemblies, plugins, metadata)+ → il2cpp meta …/global-metadata.dat for managed types/methods+ → il2cpp stubs / map on GameAssembly.dll; xrefs --skip-stubs; decompile --follow-stub+ → encrypted metadata (wrong magic) → report encrypted, do not invent types+ → See docs/IL2CPP.md++Large string dumps / raw non-PE files?+ → strings PATH --match token|whole --limit N --out FILE+ → strings PATH --raw for blobs (metadata dumps, etc.)```---@@ -145,18 +158,61 @@ ghidrust project analyze PROJ_DIR --file ID \### MCP (`ghidrust mcp`)-| Tool | Args |-|------|------|-| `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 |+| Tool | Args | Notes |+|------|------|-------|+| `load` | `path` | PE/ELF map |+| `disassemble` | `path`, optional `addr`, `count` | x86-64 listing |+| `rtti` | `path` | RTTI classes / vtables |+| `list_analyzers` | — | Auto Analysis names |+| `analyze` | `path`, optional `analyzers[]`, **`gpu`** | CPU + optional GPU enrich |+| `list_strings` / `search_strings` | `path`, optional `encoding`, `filter`, **`match`** (`substr`\|`token`\|`whole`\|`glob`), `min`, **`limit`**, **`raw`** | Blob scan when `raw:true` |+| `get_xrefs_to` | `path`, `addr`, optional **`skip_stubs`**, **`classify`** | RIP/tables **and** non-exec data qword pointers; hide/label IL2CPP stubs |+| `get_xrefs_from` | `path`, `addr`, optional `count` | Xrefs from VA |+| `get_string_xrefs` | `path`, `filter` | Strings → xrefs |+| `list_imports` / `get_import_xrefs` | `path`, optional `dll`/`name` | PE IAT |+| `function_at` / `get_function_by_address` | `path`, `addr` | Containing function |+| `read_bytes` | `path`, `addr`, optional `count` | Raw VA hex dump |+| `il2cpp_meta` | `path`, optional `filter` | `global-metadata.dat` types/methods (v27/29/31); encrypted → `next_steps` JSON |+| `il2cpp_map` | `binary`, `meta`, optional `filter` | Method RVA map; null when unproven |+| `il2cpp_stubs` | `binary`, optional `filter`, `max` | Resolve stubs (filter: name or C-string at `name_string_va`) |+| `il2cpp_icalls` | `binary`, optional `filter` | Engine name‖fn icall tables → index / RVA |+| `unity_inventory` | `path` | Player dir → assemblies, plugins, metadata, XR-related inventory |+| `decompile` | `path`, optional `addr`, `count`, `stage`, **`follow_stub`** | Stage-1 default; `runtime_unresolved` when slot empty |+| `list_gpu_strategies` | — | Strategy matrix |+| `gpu_decompile` | `path`, optional `out` | VRAM multipass |+| `rtti_gpu_bench` | `path` | CPU vs GPU RTTI |++MCP launch: `ghidrust mcp` / `target/release/ghidrust.exe mcp` (stdio; no host-specific paths).++---++## Unity / IL2CPP (CLI + MCP)++Canonical detail: [`docs/IL2CPP.md`](../docs/IL2CPP.md).++| Task | CLI | MCP |+|------|-----|-----|+| Player install inventory | `ghidrust unity-inventory GAME_DIR --json` | `unity_inventory` `{path}` |+| Managed types/methods | `ghidrust il2cpp meta META.dat [--filter F] --json` | `il2cpp_meta` `{path, filter?}` |+| Metadata ↔ RVA | `ghidrust il2cpp map --binary GA.dll --meta META.dat --json` | `il2cpp_map` `{binary, meta, filter?}` |+| Engine icall name→fn | `ghidrust il2cpp icalls --binary ENGINE.dll --filter F --json` | `il2cpp_icalls` `{binary, filter?}` |+| Resolve stubs | `ghidrust il2cpp stubs --binary GA.dll --filter F --json` | `il2cpp_stubs` `{binary, filter?, max?}` |+| Raw bytes at VA | `ghidrust bytes PATH --addr HEX --count N --json` | `read_bytes` `{path, addr, count?}` |+| Xrefs (incl. data ptrs / skip stubs) | `ghidrust xrefs PATH --to HEX [--skip-stubs] [--classify]` | `get_xrefs_to` `{…, skip_stubs, classify}` |+| Decompile through stub | `ghidrust decompile GA.dll --addr HEX --follow-stub --json` | `decompile` `{…, follow_stub: true}` |+| Strings on metadata blob | `ghidrust strings META.dat --raw --match token --limit N` | `list_strings` `{path, raw:true, match, limit}` |++Wrong metadata magic → encrypted/obfuscated JSON with `next_steps` (fail closed). Never invent method or icall RVAs when pairing/map leaves them null.++**Engine icall recipe (generic):**++```bash+ghidrust strings ENGINE.dll --filter ICallNameFragment --json+ghidrust xrefs ENGINE.dll --to <name_string_va> --json+ghidrust il2cpp icalls --binary ENGINE.dll --filter ICallNameFragment --json+ghidrust bytes ENGINE.dll --addr <fn_va> --count 64 --json+ghidrust disasm ENGINE.dll --addr <fn_va> --count 20 --json+```---@@ -169,15 +225,18 @@ Add `--json` for structured stdout.| Help | `ghidrust help` || Load | `ghidrust load <path>` || 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)` |+| Strings | `ghidrust strings <path> [--raw] [--match MODE] [--limit N] [--out FILE] [--filter SUB]` |+| Xrefs | `ghidrust xrefs <path> (--to\|--from\|--string\|--import) [--skip-stubs] [--classify] [--out FILE]` |+| Bytes | `ghidrust bytes <path> --addr HEX [--count N] [--out FILE]` || Imports | `ghidrust imports <path> [--dll\|--name]` || Function-at | `ghidrust function-at <path> --addr HEX` |+| IL2CPP | `ghidrust il2cpp meta\|map\|stubs\|icalls …` (see `docs/IL2CPP.md`) |+| Unity inventory | `ghidrust unity-inventory <game-dir>` || 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; metrics only with `--verbose`) | `ghidrust decompile <path> [--verbose]` |+| Decompile (Stage-1 default; `--follow-stub` for IL2CPP; metrics with `--verbose`) | `ghidrust decompile <path> [--follow-stub] [--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]` |@@ -195,12 +254,19 @@ 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 strings PATH --encoding all --filter SomeName --match token --limit 50 --json+ghidrust xrefs PATH --string SomeName --skip-stubs --jsonghidrust function-at PATH --addr 0x140001234 --jsonghidrust imports PATH --jsonghidrust analyze PATH --analyzer "ASCII Strings" --analyzer "Function Start Search" --json+# Unity / IL2CPP+ghidrust unity-inventory GAME_DIR --json+ghidrust il2cpp meta GAME_DIR/*_Data/il2cpp_data/Metadata/global-metadata.dat --filter Camera --json+ghidrust il2cpp stubs --binary GAME_DIR/GameAssembly.dll --filter Camera --json+ghidrust il2cpp icalls --binary GAME_DIR/UnityPlayer.dll --filter Camera --json+ghidrust xrefs GAME_DIR/GameAssembly.dll --to HEX --skip-stubs --classify --json+# GPU RTTI seed path on one analyzerghidrust analyze PATH --analyzer "WindowsPE x86 PE RTTI Analyzer" --gpu --json@@ -340,7 +406,7 @@ Guardrails to respect:**Do:** exact analyzer names; `--analyzer` or `--analyzers`; `--gpu` when GPU enrich wanted; `--json` for scripts; `analyzer-bench-matrix` for strategy list; prefer `decompile --stage05` when you want the IR-informed emit; `decompile-bench` to capture wall-clock + lift-ratio numbers.-**Don't:** invent typed/Hex-Rays C beyond the emit stage in use; claim Ghidra MCP is Ghidrust; claim Ghidra-surpass metrics without captured benches; skip empty-result honesty; conflate PCIe with on-device time.+**Don't:** invent typed/Hex-Rays C beyond the emit stage in use; claim Ghidra MCP is Ghidrust; claim Ghidra-surpass metrics without captured benches; skip empty-result honesty; conflate PCIe with on-device time; claim absence of managed types from PE strings alone when IL2CPP metadata exists (run `il2cpp meta`); invent method RVAs when the map leaves them null.---@@ -348,8 +414,14 @@ Guardrails to respect:```bashcargo test -p ghidrust-core --features gpu+cargo test -p ghidrust-il2cpp -p ghidrust-unity-inventory --libghidrust analyzers --jsonghidrust analyze fixtures/analysis_lab.pe --analyzer "ASCII Strings" --gpu --jsonghidrust gpu-decompile fixtures/analysis_lab.pe --jsonghidrust analyzer-bench-matrix+ghidrust il2cpp meta fixtures/il2cpp/meta_v31.dat --filter Camera --json+ghidrust il2cpp stubs --binary fixtures/il2cpp/il2cpp_stub_lab.pe --filter Camera --json+ghidrust decompile fixtures/il2cpp/il2cpp_stub_lab.pe --addr 0x140001000 --follow-stub --json+ghidrust bytes fixtures/il2cpp/il2cpp_stub_lab.pe --addr 0x140001000 --count 32 --json+ghidrust strings fixtures/il2cpp/meta_v31.dat --raw --filter Camera --match token --limit 5 --json```