Skip to content

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.

Refactor `ghidrust-agent` functions for improved skill management and checklist validation. Update `README.md` to clarify CLI commands and improve documentation on project structure and usage.

oofz85290f341614
diff --git a/.gitignore b/.gitignore
index 1ddea20..35e1868 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,7 +7,9 @@
.idea/
.vscode/
.grok/
-.cursor/
+.cursor/*
+!.cursor/rules/*
+!.cursor/rules/**
terminals/
mcps/
diff --git a/Cargo.lock b/Cargo.lock
index ab59739..af0774a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -23,6 +23,10 @@ name = "accesskit"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3d3b8f9bae46a948369bc4a03e815d4ed6d616bd00de4051133a5019dc31c5a"
+dependencies = [
+ "enumn",
+ "serde",
+]
[[package]]
name = "accesskit_atspi_common"
@@ -125,6 +129,7 @@ dependencies = [
"cfg-if",
"getrandom 0.3.4",
"once_cell",
+ "serde",
"version_check",
"zerocopy",
]
@@ -877,6 +882,17 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
+[[package]]
+name = "duplicate"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e92f10a49176cbffacaedabfaa11d51db1ea0f80a83c26e1873b43cd1742c24"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "proc-macro2-diagnostics",
+]
+
[[package]]
name = "ecolor"
version = "0.31.1"
@@ -885,6 +901,7 @@ checksum = "bc4feb366740ded31a004a0e4452fbf84e80ef432ecf8314c485210229672fd1"
dependencies = [
"bytemuck",
"emath",
+ "serde",
]
[[package]]
@@ -937,6 +954,7 @@ dependencies = [
"log",
"nohash-hasher",
"profiling",
+ "serde",
]
[[package]]
@@ -979,6 +997,18 @@ dependencies = [
"winit",
]
+[[package]]
+name = "egui_dock"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ea7536fb0243aea55c1ca123a41a18253e16520d427a7213da584b9e2cb3973"
+dependencies = [
+ "duplicate",
+ "egui",
+ "paste",
+ "serde",
+]
+
[[package]]
name = "egui_glow"
version = "0.31.1"
@@ -1010,6 +1040,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e4cadcff7a5353ba72b7fea76bf2122b5ebdbc68e8155aa56dfdea90083fe1b"
dependencies = [
"bytemuck",
+ "serde",
]
[[package]]
@@ -1039,6 +1070,17 @@ dependencies = [
"syn",
]
+[[package]]
+name = "enumn"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "epaint"
version = "0.31.1"
@@ -1055,6 +1097,7 @@ dependencies = [
"nohash-hasher",
"parking_lot",
"profiling",
+ "serde",
]
[[package]]
@@ -1379,9 +1422,11 @@ version = "0.1.0"
dependencies = [
"eframe",
"egui",
+ "egui_dock",
"ghidrust-agent",
"ghidrust-core",
"ghidrust-decomp",
+ "ghidrust-il2cpp",
"ghidrust-types",
"libc",
"rfd",
@@ -2623,6 +2668,18 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "proc-macro2-diagnostics"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "version_check",
+]
+
[[package]]
name = "profiling"
version = "1.0.18"
diff --git a/DEPENDENCIES.md b/DEPENDENCIES.md
index 6682fd8..9569075 100644
--- a/DEPENDENCIES.md
+++ b/DEPENDENCIES.md
@@ -24,6 +24,7 @@ Open-source RE sources (Ghidra Decompiler / SLEIGH, iced-x86, academic papers) m
| Crate | Why |
|-------|-----|
| **egui / eframe** (and their transitive deps) | Interactive CodeBrowser shell with Material 3–inspired Dark/Light chrome (not a full Material library). |
+| **egui_dock** `0.16` (feature `serde`) | IDE-style tab docking for the CodeBrowser center panes. Pin matches **egui 0.31 ↔ egui_dock 0.16** (newer egui_dock tracks newer egui; do not bump egui solely for docking). |
| **serde / serde_json** | Minimal JSON for CLI `--json` and MCP JSON-RPC framing (stdio agent protocol). |
| **rayon** | Work-stealing CPU pool for bulk RE scans and parallel analyze/decomp. |
| **bincode** | Fast binary analysis persistence (`analysis.bin`) — multi-100MB pretty JSON is not viable for UI reopen. |
diff --git a/README.md b/README.md
index 232569a..06d5cb9 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,7 @@ It is **not** a Ghidra fork or wrapper. Analysis logic (loaders, decode, analyze
| **Ghidra-shaped workflow** | Familiar labels and surfaces (Auto Analysis names, project import/analyze/export, listing + click FUN → decompile) without depending on the Ghidra JVM stack |
| **Hand-rolled core** | PE/ELF, x86-64 decode, RTTI, analyzers, and the IR → SSA → structure → typed-C pipeline implemented in Rust — third-party RE libraries are avoided at runtime ([DEPENDENCIES.md](DEPENDENCIES.md)); Ghidra sources are reference-only |
| **CPU-correct first** | CPU paths are the oracle; optional GPU paths must match or enrich them, not replace honesty with speed claims |
-| **Agent-ready** | Headless CLI + stdio MCP so coding agents can load, disassemble, analyze, look up strings/xrefs/imports/functions, inventory Unity/IL2CPP, and decompile without a GUI or ad-hoc PE scripts |
+| **Agent-ready** | Headless CLI + stdio MCP with artifact spill/drain, program identity (`path` or `project`+`file_id`), PE install inventory, RTTI catalog query, UTF-16 xref parity, live process bridge (Windows), and egui panes for every surface |
| **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,13 +181,21 @@ First-class commands for the queries agents used to need ad-hoc scripts for. Sam
| Command | Purpose | Key flags |
|---------|---------|-----------|
+| `ghidrust load <path\|--project DIR --file-id ID>` | Load PE/ELF; JSON includes `resolved_path`, `sections`, informational `section_notes` | `--json`, `--out` |
| `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 xrefs <path>` | Cross-references (absolute + RIP-relative; string encoding parity) | Exactly one of: `--to` / `--from` / `--string` / `--import`; `--encoding ascii\|utf16le\|all`; `--skip-stubs` / `--classify` |
| `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` |
+| `ghidrust decompile <path>` | Containing-fn resolve + Stage-1 pseudo-C | `--addr` (mid-body ok), `--follow-stub`, `--json` |
+| `ghidrust gpu-decompile <path>` | GPU multipass at resolved entry; metrics JSON primary; `.gdecomp` opaque | `--addr`, `--metrics`, `--json` |
+| `ghidrust rtti <path>` | RTTI catalog (filter/exact/match; multi-vtable honest) | `--filter`/`--name`/`--exact`, `--match`, `--json` |
+| `ghidrust inventory <dir>` | Generic PE install inventory (exe/dll + VERSIONINFO; artifact if large) | `--max-depth`, `--hash`, `--json` |
+| `ghidrust tree <path>` | Bounded file tree index (existence/size; no unpack) | `--max-depth`, `--ext`, `--name`, `--json` |
+| `ghidrust artifact get\|query\|list` | Drain spilled analysis artifacts (`next_offset`) | `--offset`, `--limit`, `--json` |
+| `ghidrust process list\|attach\|detach\|modules\|read\|resolve\|regions` | Live Process Bridge (Windows; read-only MVP) | session_id / `--addr` / `--module` / `--rva` / `--max` |
+| `ghidrust il2cpp meta\|map\|stubs\|icalls` | IL2CPP metadata + method map + resolve stubs + icalls | See [docs/IL2CPP.md](docs/IL2CPP.md) |
+| `ghidrust unity-inventory <dir>` | Unity player layout (reuses PE VERSIONINFO helpers) | `--json`, `--out FILE` |
+| `ghidrust disasm <path>` | Listing; `decode_gaps` when `--skip-bad` | `--addr HEX`, `--count N`, `--skip-bad`, `--json` |
```bash
# Wide + ASCII string search (token match + limit; BOM-free --out)
@@ -223,7 +231,7 @@ ghidrust decompile /path/to/GameAssembly.dll --addr 0x180012345 --follow-stub
| **Stage-0.5 IR** (oracle) | `ghidrust decompile <path> --stage05 [--addr HEX] [--count N] [--verbose]` | IR-informed emit from the hand-rolled x86-64 lifter → `ghidrust-ir`: `xor a,a → a=0`, `add/sub/or/and/xor/shl/shr` augmented-assign, `push`/`pop`, direct `call`, flag-driven `jcc`. Falls back to Stage-0 scaffolding for uncovered ops. | stdout: `pseudo_c`. Metrics on stderr only with `--verbose`. `--json`: `{decompile: …, lift_coverage: {total_ops, unimplemented_ops, source_instructions, ratio}}`. |
| **decompile-bench** | `ghidrust decompile-bench <path> [--functions N] [--count N] [--stage1] [--parallel] [--out FILE]` | Runs default analyzers, then benches Stage-0/0.5 (default) or Stage-1 (`--stage1`) across every discovered function; `--parallel` fans out per-entry Stage-1 across a rayon thread pool. | Text table (or JSON via `--json`); optional `--out FILE`. Report carries per-function `stage0_us`, `stage05_us`, `stage1_us`, `stage1_goto_count`, `stage1_leaf_count`, and per-function `pseudo_c` when Stage-1 is on. |
| **ghidra-headtohead** (Phase E, fair) | `ghidrust ghidra-headtohead <path> [--functions N] [--count N] [--ghidra DIR] [--captured JSON] [--out FILE]` | Fair Ghidra oracle: shared-entry intersection with Ghidra `DecompInterface` output, per-row Stage-1 vs Ghidra normalized-token similarity, per-entry Stage-1 wall time. Without `--ghidra` / `--captured` the report is methodology-only. | Text or JSON; each row carries `token_similarity`, `ghidrust_stage1_us`, `ghidra_wall_us`. See [`docs/GHIDRA_HEADTOHEAD.md`](docs/GHIDRA_HEADTOHEAD.md). |
-| **gpu-decompile** | `ghidrust gpu-decompile <path> [--out FILE] [--metrics FILE]` | Full **GPU-resident** VRAM multipass decompile of the entry function: decode → leaders → blocks → emit kernels; single final download; asserts `mid_pipeline_host_reads == 0` and multipass-CPU equivalence. | `.gdecomp` binary dump at `--out`. stdout: pseudo-C. `--json` / `--metrics FILE` produces `{gpu_backend, gpu_device, gpu_ms, mid_pipeline_host_reads, kernels, dump_path, dump_bytes, gpu_ir_count, gpu_block_count, gpu_edge_count, equivalence_multipass, pseudo_c_head}`. Non-zero exit if equivalence fails or a mid-pipeline host read is observed. |
+| **gpu-decompile** | `ghidrust gpu-decompile <path> [--addr HEX] [--out FILE] [--metrics FILE]` | Full **GPU-resident** VRAM multipass decompile at containing-fn resolve (mid-body `addr` ok): decode → leaders → blocks → emit kernels; single final download; asserts `mid_pipeline_host_reads == 0` and multipass-CPU equivalence. Metrics JSON is primary; `.gdecomp` is opaque. | `.gdecomp` binary dump at `--out`. stdout: pseudo-C. `--json` / `--metrics FILE` produces `{resolve, resolved_entry, gpu_backend, gpu_device, gpu_ms, mid_pipeline_host_reads, kernels, dump_path, dump_bytes, gpu_ir_count, gpu_block_count, gpu_edge_count, equivalence_multipass, pseudo_c_head}`. Non-zero exit if equivalence fails or a mid-pipeline host read is observed. |
| **re-bench** | `ghidrust re-bench <path> [--out FILE]` | CPU decompile of the entry + bulk RE on a padded haystack, once on CPU (parallel) and once on GPU / fallback; asserts equal bulk hit counts. | Text report to stdout (or JSON with `--json` / `--out`). Fields: `decompile_cpu {backend, ms, entry, name, blocks, edges, insns, lines, chars, pseudo_c_head}`, `bulk_cpu`, `bulk_gpu` (each: `mode, backend, ms, hits, haystack_bytes`), plus `note` explaining that decompile stays on CPU. |
Two more benches are shipped and callable from the CLI even though they are not part of the analyzer/decompile eval sweep — they measure how the analyzer and RTTI GPU strategies compare against their CPU oracles:
@@ -273,8 +281,13 @@ The CLI is the `ghidrust` binary from `ghidrust-cli`. Prefer **absolute paths**
### Everyday commands
```bash
-# Map a binary
+# Map a binary (path OR project + file_id)
ghidrust load /path/to/app.exe --json
+ghidrust load --project ./MyProject --file-id <id> --json
+
+# Install / tree inventory (no OS shell needed)
+ghidrust inventory /path/to/InstallRoot --max-depth 8 --json
+ghidrust tree /path/to/GameDir --ext dll,dat --name "*meta*" --json
# Listing (optional --skip-bad for undecodable holes)
ghidrust disasm /path/to/app.exe --count 32
@@ -283,17 +296,32 @@ ghidrust disasm /path/to/app.exe --addr 0x140001000 --count 64 --skip-bad
# Strings / xrefs / imports / containing function
ghidrust strings /path/to/app.exe --encoding all --filter SomeName --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 --json
+ghidrust xrefs /path/to/app.exe --string SomeName --encoding all --skip-stubs --classify --json
ghidrust xrefs /path/to/app.exe --to 0x140002010 --json
ghidrust imports /path/to/app.exe --json
ghidrust xrefs /path/to/app.exe --import CreateFileW --json
ghidrust function-at /path/to/app.exe --addr 0x140001234 --json
+ghidrust rtti /path/to/app.exe --filter Widget --json
+
+# Artifacts (drain large spilled dumps)
+ghidrust artifact list --json
+ghidrust artifact query <id> --offset 0 --limit 64 --json
+
+# Live process (Windows; read-only)
+ghidrust process list --json
+ghidrust process attach <pid>
+ghidrust process modules <session_id> --json
+ghidrust process resolve <session_id> --module app.exe --rva 0x1234 --json
+ghidrust process read <session_id> --addr 0x7ff… --size 64 --json
+ghidrust process regions <session_id> --json
+ghidrust process detach <session_id>
# 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
+ghidrust il2cpp icalls --binary /path/to/UnityPlayer.dll --filter Camera --json
# List Auto Analysis names (Ghidra-compatible labels)
ghidrust analyzers
@@ -312,8 +340,8 @@ ghidrust decompile /path/to/GameAssembly.dll --addr 0x180012345 --follow-stub
# Wall-clock + lift-coverage bench across all discovered functions
ghidrust decompile-bench /path/to/app.exe --functions 32 --count 128 --out bench.txt
-# Experimental GPU decompile → greppable dump
-ghidrust gpu-decompile /path/to/app.exe --out entry.gdecomp --metrics metrics.log --json
+# Experimental GPU decompile (mid-body addr resolves to containing entry)
+ghidrust gpu-decompile /path/to/app.exe --addr 0x140001234 --out entry.gdecomp --metrics metrics.log --json
```
**`--gpu` on `analyze`** turns on GPU bulk strings (when available) and per-analyzer GPU seed enrichment. It is **not** the same as `gpu-decompile` (full VRAM multipass decompile).
@@ -348,20 +376,25 @@ MyProject/
| Command | What it does |
|---------|----------------|
-| `ghidrust load <path> [--json]` | Load PE/ELF, show map (PE also parses import/IAT directory into the program model) |
+| `ghidrust load <path\|--project DIR --file-id ID> [--json]` | Load PE/ELF; JSON includes `resolved_path`, `sections`, informational `section_notes` |
| `ghidrust disasm <path> [--addr HEX] [--count N] [--skip-bad] [--json]` | x86-64 listing; `--skip-bad` advances one byte on decode failure |
+| `ghidrust bytes <path> --addr HEX [--count N] [--json]` | Raw VA hex dump |
| `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 xrefs <path> (--to\|--from\|--string\|--import) [--encoding ascii\|utf16le\|all] [--skip-stubs] [--classify] [--json]` | RIP-aware xrefs; string encoding parity |
| `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 inventory <dir> [--max-depth N] [--hash] [--json]` | Generic PE install inventory (exe/dll + VERSIONINFO) |
+| `ghidrust tree <path> [--max-depth N] [--ext LIST] [--name GLOB] [--json]` | Bounded file tree index (existence/size; no unpack) |
+| `ghidrust artifact get\|query\|list …` | Drain / list spilled analysis artifacts (`next_offset`) |
+| `ghidrust process list\|attach\|detach\|modules\|read\|resolve\|regions …` | Live Process Bridge (Windows; read-only MVP) |
+| `ghidrust il2cpp meta\|map\|stubs\|icalls …` | IL2CPP metadata / RVA map / resolve stubs / engine icalls ([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 rtti <path> [--filter\|--name\|--exact] [--match MODE] [--json]` | RTTI catalog (filter/exact; multi-vtable honest) |
| `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] [--follow-stub] [--verbose] [--json]` | **CPU** decompile (**Stage-1** default; `--follow-stub` for IL2CPP resolve thunks) |
+| `ghidrust decompile <path> [--addr HEX] [--count N] [--stage0\|--stage05\|--stage1] [--follow-stub] [--verbose] [--json]` | **CPU** decompile (**Stage-1** default; containing-fn resolve; `--follow-stub` for IL2CPP) |
| `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 gpu-decompile <path> [--addr HEX] [--out FILE] [--metrics FILE]` | **GPU-resident** multipass at resolved entry; metrics JSON; `.gdecomp` opaque |
| `ghidrust bulk-bench <path>` | Seq / parallel CPU / GPU bulk string timings |
| `ghidrust re-bench <path> [--out FILE]` | CPU decompile + bulk CPU then GPU metrics |
| `ghidrust analyzer-bench <path> [--large] [--out FILE]` | All analyzers + decompile: CPU vs GPU |
@@ -407,7 +440,7 @@ The GUI is for humans. Agents should use the **CLI** or **MCP**, not drive the U
cargo build -p ghidrust-cli --release
```
-Note the absolute path to the binary, e.g. `F:\Repos\Ghidrust\target\release\ghidrust.exe` on Windows or `/home/you/Ghidrust/target/release/ghidrust` on Linux/macOS.
+Note the absolute path to the binary, e.g. `C:\path\to\Ghidrust\target\release\ghidrust.exe` on Windows or `/path/to/Ghidrust/target/release/ghidrust` on Linux/macOS.
### 2. Register it in your client
@@ -417,7 +450,7 @@ Note the absolute path to the binary, e.g. `F:\Repos\Ghidrust\target\release\ghi
{
"mcpServers": {
"ghidrust": {
- "command": "F:/Repos/Ghidrust/target/release/ghidrust.exe",
+ "command": "C:/path/to/Ghidrust/target/release/ghidrust.exe",
"args": ["mcp"]
}
}
@@ -430,7 +463,7 @@ Note the absolute path to the binary, e.g. `F:\Repos\Ghidrust\target\release\ghi
{
"mcpServers": {
"ghidrust": {
- "command": "F:/Repos/Ghidrust/target/release/ghidrust.exe",
+ "command": "C:/path/to/Ghidrust/target/release/ghidrust.exe",
"args": ["mcp"]
}
}
@@ -439,13 +472,13 @@ Note the absolute path to the binary, e.g. `F:\Repos\Ghidrust\target\release\ghi
**Other MCP clients** — same pattern: command = absolute path to `ghidrust` / `ghidrust.exe`, args = `["mcp"]`. Restart the client after editing config.
-On Linux/macOS you can use a shell wrapper if needed:
+On Linux/macOS:
```json
{
"mcpServers": {
"ghidrust": {
- "command": "/home/you/Ghidrust/target/release/ghidrust",
+ "command": "/path/to/Ghidrust/target/release/ghidrust",
"args": ["mcp"]
}
}
@@ -456,26 +489,53 @@ On Linux/macOS you can use a shell wrapper if needed:
| Tool | Args | Purpose |
|------|------|---------|
-| `load` | `path` | Load PE/ELF, return map / sections |
-| `disassemble` | `path`, optional `addr`, `count` | x86-64 listing |
-| `rtti` | `path` | Recover RTTI class names / vtables |
+| `load` | `path` **or** `project`+`file_id` | Load PE/ELF; `resolved_path`, `sections`, `section_notes` |
+| `disassemble` | `path`, optional `addr`, `count` | Listing + containing-fn resolve + `decode_gaps` |
+| `rtti` | `path` | Full RTTI recover dump |
+| `rtti_query` | `path`, optional `filter`, `exact`, `match` | Catalog query; multi-vtable; artifact if large |
+| `artifact_get` / `artifact_query` / `artifact_list` | `id` / optional `offset`/`limit` / optional `max` | Drain or list spilled results (`next_offset`) |
+| `inventory` | `path`, optional `max_depth`, `hash` | Generic PE dir inventory + VERSIONINFO |
+| `list_tree` | `path`, optional `max_depth`, `extensions`, `name_glob` | Bounded tree index |
| `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`, `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 |
+| `get_string_xrefs` | `path`, `filter`, optional `encoding` | String xrefs with `ascii`\|`utf16le`\|`all` |
| `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 |
+| `read_bytes` | `path`, `addr`, optional `count` | Raw VA hex dump |
| `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 |
+| `il2cpp_icalls` | `binary`, optional `filter` | Engine icall name↔fn tables |
+| `unity_inventory` | `path` | Unity player dir → assemblies, plugins, metadata, PE versions |
+| `decompile` | `path`, optional `addr`, `count`, `stage`, `follow_stub` | Containing-fn resolve + Stage-1; returns `resolve` meta |
| `list_gpu_strategies` | — | Per-analyzer GPU strategy matrix |
-| `gpu_decompile` | `path`, optional `out` | GPU-resident multipass decompile |
+| `gpu_decompile` | `path`, optional `addr`, `out` | GPU decompile at VA; metrics JSON; dump opaque |
| `rtti_gpu_bench` | `path` | CPU vs GPU RTTI with PCIe/device split |
+| `process_list` / `process_attach` / `process_detach` / `process_modules` / `process_read` / `process_resolve` / `process_regions` | session / pid / module / rva / max | Live Process Bridge (Windows; no write in MVP) |
+
+#### Live process (Windows)
+
+Attach read-only (`PROCESS_VM_READ`): `process list` → `attach <pid>` → `modules` → `resolve --module NAME --rva HEX` (`static_to_live`) → `read --addr LIVE --size N` → optional `regions` / `detach`. Short reads and access denied are explicit errors. Bytes ≠ recovered types — do not invent structs from live reads. GUI: Debugger → Targets / Modules / Memory Bytes / Regions / Static Mappings.
+
+#### Analysis artifacts
+
+Large MCP/CLI dumps spill to `%TEMP%/ghidrust-artifacts/`. Tool envelopes include `entry_count`, preview, `artifact_id`, and `next_offset`. Drain with `artifact_query` until `next_offset` is null — never treat truncated host UI text as complete.
+
+#### GUI Window homes (§13)
+
+| Capability | Window / pane |
+|---|---|
+| IL2CPP meta / methods / icalls | **IL2CPP Metadata**, **IL2CPP Methods**, **IL2CPP ICalls** |
+| PE / Unity inventory | **Install Inventory** |
+| Tree index | **File System Browser** |
+| Artifact spill | **Analysis Artifacts** |
+| GPU decompile | Analysis → **GPU Decompile…** |
+| Encoding / xrefs / RTTI / notes | Defined Strings, Symbol References, Symbol Tree Classes, Memory Map |
+| Live process | Debugger Targets / Modules / Memory Bytes / Regions |
IL2CPP version matrix and Unity inventory schema: [docs/IL2CPP.md](docs/IL2CPP.md).
@@ -494,6 +554,13 @@ Example agent-facing call shapes (conceptual):
{ "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 } }
+{ "name": "inventory", "arguments": { "path": "…/InstallRoot", "max_depth": 8 } }
+{ "name": "list_tree", "arguments": { "path": "…/GameDir", "extensions": "dll,dat" } }
+{ "name": "rtti_query", "arguments": { "path": "…/app.exe", "filter": "Widget" } }
+{ "name": "artifact_query", "arguments": { "id": "<artifact_id>", "offset": 0, "limit": 64 } }
+{ "name": "process_list", "arguments": {} }
+{ "name": "process_attach", "arguments": { "pid": 1234 } }
+{ "name": "process_resolve", "arguments": { "session_id": "…", "module": "app.exe", "rva": "0x1234" } }
```
### 4. Optional: agent skill
diff --git a/crates/ghidrust-agent/src/lib.rs b/crates/ghidrust-agent/src/lib.rs
index b63fe3b..abadd2a 100644
--- a/crates/ghidrust-agent/src/lib.rs
+++ b/crates/ghidrust-agent/src/lib.rs
@@ -28,6 +28,7 @@ pub use system_prompt::{
SystemPromptBuilder,
};
pub use tool_bridge::{
- register_mcp_with_grok_cli, resolve_ghidrust_cli_bin, write_project_mcp_config,
- write_project_skill,
+ ensure_project_skill, project_skill_path, register_mcp_with_grok_cli,
+ resolve_ghidrust_cli_bin, skill_content_hash, start_checklist, write_project_mcp_config,
+ write_project_skill, write_project_skill_embedded, StartChecklistItem, EMBEDDED_SKILL_MD,
};
diff --git a/crates/ghidrust-agent/src/tool_bridge.rs b/crates/ghidrust-agent/src/tool_bridge.rs
index 5a0d071..9f0d484 100644
--- a/crates/ghidrust-agent/src/tool_bridge.rs
+++ b/crates/ghidrust-agent/src/tool_bridge.rs
@@ -190,23 +190,197 @@ pub fn resolve_ghidrust_cli_bin() -> Option<PathBuf> {
None
}
-/// Ensure `<project>/.grok/skills/ghidrust/SKILL.md` mirrors the workspace
-/// `skill/SKILL.md`.
+/// Embedded skill body shipped with the agent crate (release installs without source tree).
+pub const EMBEDDED_SKILL_MD: &str = include_str!("../../../skill/SKILL.md");
+
+/// Fingerprint of the embedded skill (first 16 hex of FNV-1a 64) for stale-skill detection.
+pub fn skill_content_hash(skill: &str) -> String {
+ let mut h: u64 = 0xcbf29ce484222325;
+ for b in skill.as_bytes() {
+ h ^= u64::from(*b);
+ h = h.wrapping_mul(0x100000001b3);
+ }
+ format!("{h:016x}")
+}
+
+/// Canonical on-disk skill path Start / checklist expect:
+/// `<project>/.grok/skills/ghidrust/SKILL.md`.
+pub fn project_skill_path(project_root: &Path) -> PathBuf {
+ project_root
+ .join(".grok")
+ .join("skills")
+ .join("ghidrust")
+ .join("SKILL.md")
+}
+
+/// Ensure `<project>/.grok/skills/ghidrust/SKILL.md` mirrors the workspace skill
+/// or the embedded fallback when `skill_source` is missing.
pub fn write_project_skill(project_root: &Path, skill_source: &Path) -> io::Result<PathBuf> {
- let skill = fs::read_to_string(skill_source)?;
+ let skill = match fs::read_to_string(skill_source) {
+ Ok(s) => s,
+ Err(_) => EMBEDDED_SKILL_MD.to_string(),
+ };
+ write_project_skill_contents(project_root, &skill)
+}
+
+/// Write skill from the embedded copy (always succeeds if the project dir is writable).
+pub fn write_project_skill_embedded(project_root: &Path) -> io::Result<PathBuf> {
+ write_project_skill_contents(project_root, EMBEDDED_SKILL_MD)
+}
+
+/// Ensure the project skill file exists: prefer optional disk source, else embed.
+///
+/// This is the Agent Context Bundle skill half — safe to call on project open
+/// (before Start) so the Grok checklist is green without a silent skip.
+pub fn ensure_project_skill(
+ project_root: &Path,
+ skill_source: Option<&Path>,
+) -> io::Result<PathBuf> {
+ match skill_source {
+ Some(src) => write_project_skill(project_root, src),
+ None => write_project_skill_embedded(project_root),
+ }
+}
+
+fn write_project_skill_contents(project_root: &Path, skill: &str) -> io::Result<PathBuf> {
let dest_dir = project_root.join(".grok").join("skills").join("ghidrust");
fs::create_dir_all(&dest_dir)?;
let dest = dest_dir.join("SKILL.md");
+ let hash_path = dest_dir.join("SKILL.hash");
+ let hash = skill_content_hash(skill);
+ let hash_body = format!("{hash}\n");
- if let Ok(existing) = fs::read_to_string(&dest) {
- if existing == skill {
- return Ok(dest);
+ let skill_ok = match fs::read_to_string(&dest) {
+ Ok(existing) if existing == skill => true,
+ _ => {
+ fs::write(&dest, skill)?;
+ true
+ }
+ };
+ // Always ensure the hash sidecar (even when SKILL.md was already current).
+ if skill_ok {
+ match fs::read_to_string(&hash_path) {
+ Ok(existing) if existing == hash_body || existing.trim() == hash => {}
+ _ => fs::write(&hash_path, &hash_body)?,
}
}
- fs::write(&dest, skill)?;
Ok(dest)
}
+/// Fail-loud Start checklist rows: mcp / skill / agents / context (+ skill hash).
+#[derive(Debug, Clone)]
+pub struct StartChecklistItem {
+ pub id: &'static str,
+ pub ok: bool,
+ pub detail: String,
+}
+
+pub fn start_checklist(project_root: &Path) -> Vec<StartChecklistItem> {
+ let mut items = Vec::new();
+ let mcp_root = project_root.join(".mcp.json");
+ items.push(StartChecklistItem {
+ id: "mcp",
+ ok: mcp_root.is_file(),
+ detail: if mcp_root.is_file() {
+ mcp_root.display().to_string()
+ } else {
+ format!(
+ "missing — looked for {} (written on Start when ghidrust CLI is resolvable)",
+ mcp_root.display()
+ )
+ },
+ });
+ let mcp_grok = project_root.join(".grok").join("mcp.json");
+ items.push(StartChecklistItem {
+ id: "mcp_grok",
+ ok: mcp_grok.is_file(),
+ detail: if mcp_grok.is_file() {
+ mcp_grok.display().to_string()
+ } else {
+ format!(
+ "missing — looked for {} (written on Start with MCP config)",
+ mcp_grok.display()
+ )
+ },
+ });
+ let skill = project_skill_path(project_root);
+ let hash_path = skill.with_extension("hash");
+ let (skill_ok, skill_detail) = if skill.is_file() {
+ let body = fs::read_to_string(&skill).unwrap_or_default();
+ let live = skill_content_hash(&body);
+ let embedded = skill_content_hash(EMBEDDED_SKILL_MD);
+ let note = if live == embedded {
+ format!("{} · hash={live}", skill.display())
+ } else {
+ format!(
+ "{} · hash={live} (differs from embedded={embedded})",
+ skill.display()
+ )
+ };
+ (true, note)
+ } else {
+ (
+ false,
+ format!(
+ "missing — looked for {} (auto-written from embedded skill on project open / Start)",
+ skill.display()
+ ),
+ )
+ };
+ items.push(StartChecklistItem {
+ id: "skill",
+ ok: skill_ok,
+ detail: skill_detail,
+ });
+ items.push(StartChecklistItem {
+ id: "skill_hash",
+ ok: hash_path.is_file() || skill_ok,
+ detail: if hash_path.is_file() {
+ format!(
+ "{} · {}",
+ hash_path.display(),
+ fs::read_to_string(&hash_path)
+ .unwrap_or_default()
+ .trim()
+ )
+ } else if skill_ok {
+ format!(
+ "missing sidecar {} (skill body present — re-open project or Start to refresh)",
+ hash_path.display()
+ )
+ } else {
+ format!("missing — looked for {}", hash_path.display())
+ },
+ });
+ let agents = project_root.join("AGENTS.md");
+ items.push(StartChecklistItem {
+ id: "agents",
+ ok: agents.is_file(),
+ detail: if agents.is_file() {
+ agents.display().to_string()
+ } else {
+ format!(
+ "missing — looked for {} (written on Start)",
+ agents.display()
+ )
+ },
+ });
+ let context = project_root.join(".grok").join("ghidrust-context.md");
+ items.push(StartChecklistItem {
+ id: "context",
+ ok: context.is_file(),
+ detail: if context.is_file() {
+ context.display().to_string()
+ } else {
+ format!(
+ "missing — looked for {} (written on Start)",
+ context.display()
+ )
+ },
+ });
+ items
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -242,8 +416,8 @@ mod tests {
#[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"
+ mcp_bin_string(Path::new(r"\\?\C:\path\to\Ghidrust\target\release\ghidrust.exe")),
+ "C:/path/to/Ghidrust/target/release/ghidrust.exe"
);
}
@@ -270,9 +444,44 @@ mod tests {
}
#[test]
- fn missing_skill_source_is_error() {
+ fn missing_skill_source_uses_embedded() {
let proj = tmp_project("miss");
- let err = write_project_skill(&proj, &proj.join("nope.md")).unwrap_err();
- assert_eq!(err.kind(), io::ErrorKind::NotFound);
+ let out = write_project_skill(&proj, &proj.join("nope.md")).unwrap();
+ let contents = fs::read_to_string(&out).unwrap();
+ assert!(contents.contains("Ghidrust") || contents.len() > 100);
+ assert!(!start_checklist(&proj).is_empty());
+ }
+
+ #[test]
+ fn embedded_skill_hash_stable() {
+ let h1 = skill_content_hash(EMBEDDED_SKILL_MD);
+ let h2 = skill_content_hash(EMBEDDED_SKILL_MD);
+ assert_eq!(h1, h2);
+ assert_eq!(h1.len(), 16);
+ }
+
+ #[test]
+ fn ensure_project_skill_makes_checklist_skill_ok() {
+ let proj = tmp_project("ensure");
+ let out = ensure_project_skill(&proj, None).unwrap();
+ assert_eq!(out, project_skill_path(&proj));
+ assert!(out.is_file());
+ assert!(out.with_extension("hash").is_file());
+ let skill = start_checklist(&proj)
+ .into_iter()
+ .find(|i| i.id == "skill")
+ .expect("skill row");
+ assert!(skill.ok, "detail={}", skill.detail);
+ }
+
+ #[test]
+ fn skill_hash_sidecar_written_when_body_already_matches() {
+ let proj = tmp_project("hash-sidecar");
+ let dest = ensure_project_skill(&proj, None).unwrap();
+ let hash_path = dest.with_extension("hash");
+ fs::remove_file(&hash_path).unwrap();
+ // Idempotent rewrite with same body must restore the sidecar.
+ let _ = ensure_project_skill(&proj, None).unwrap();
+ assert!(hash_path.is_file());
}
}
diff --git a/crates/ghidrust-cli/src/friction.rs b/crates/ghidrust-cli/src/friction.rs
new file mode 100644
index 0000000..f64375f
--- /dev/null
+++ b/crates/ghidrust-cli/src/friction.rs
@@ -0,0 +1,661 @@
+//! Agent friction closure — CLI helpers for artifacts, inventory, tree, process, identity.
+
+use ghidrust_core::{
+ artifact_get, artifact_query, envelope_or_spill, inventory_pe_dir, list_artifacts, list_tree,
+ load_path, process_attach, process_detach, process_list, process_modules, process_read,
+ process_regions, process_resolve, resolve_function, resolve_result_json, rtti_query,
+ section_notes_for, spill_artifact, write_json_no_bom, Project, RttiMatchMode, TreeListOpts,
+ DEFAULT_PREVIEW_LIMIT,
+};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::process::ExitCode;
+
+pub fn parse_u64(s: &str) -> Result<u64, String> {
+ let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");
+ u64::from_str_radix(t, 16)
+ .or_else(|_| s.parse::<u64>())
+ .map_err(|e| e.to_string())
+}
+
+/// Resolve binary path from `--path` or `--project` + `--file-id`.
+pub fn resolve_program_path(args: &[String]) -> Result<(PathBuf, Value), String> {
+ let mut path: Option<PathBuf> = None;
+ let mut project: Option<PathBuf> = None;
+ let mut file_id: Option<String> = None;
+ let mut i = 0;
+ while i < args.len() {
+ match args[i].as_str() {
+ "--path" if i + 1 < args.len() => {
+ path = Some(PathBuf::from(&args[i + 1]));
+ i += 2;
+ }
+ "--project" if i + 1 < args.len() => {
+ project = Some(PathBuf::from(&args[i + 1]));
+ i += 2;
+ }
+ "--file-id" | "--file" if i + 1 < args.len() => {
+ file_id = Some(args[i + 1].clone());
+ i += 2;
+ }
+ other if !other.starts_with('-') && path.is_none() && project.is_none() => {
+ path = Some(PathBuf::from(other));
+ i += 1;
+ }
+ _ => i += 1,
+ }
+ }
+ if let Some(p) = path {
+ let facts = json!({
+ "path": p.display().to_string(),
+ "project": Value::Null,
+ "file_id": Value::Null,
+ "resolved_path": p.display().to_string(),
+ });
+ return Ok((p, facts));
+ }
+ let Some(proj) = project else {
+ return Err("provide <path> or --project DIR --file-id ID".into());
+ };
+ let Some(fid) = file_id else {
+ return Err("load with --project requires --file-id".into());
+ };
+ let project = Project::open(&proj).map_err(|e| e.to_string())?;
+ let entry = project
+ .list_files()
+ .into_iter()
+ .find(|f| f.id == fid)
+ .ok_or_else(|| format!("file_id not found: {fid}"))?;
+ let resolved = project.root.join(&entry.imported_rel);
+ if !resolved.is_file() {
+ return Err(format!(
+ "resolved path missing: {} (file_id={fid})",
+ resolved.display()
+ ));
+ }
+ let facts = json!({
+ "path": Value::Null,
+ "project": proj.display().to_string(),
+ "file_id": fid,
+ "resolved_path": resolved.display().to_string(),
+ "display_name": entry.display_name,
+ });
+ Ok((resolved, facts))
+}
+
+pub fn load_json_for_prog(prog: &ghidrust_core::Program, identity: &Value) -> Value {
+ let notes = section_notes_for(prog);
+ json!({
+ "name": prog.name,
+ "format": prog.format,
+ "image_base": format!("{:#x}", prog.image_base),
+ "entry": prog.entry.map(|e| format!("{e:#x}")),
+ "identity": identity,
+ "resolved_path": identity.get("resolved_path").cloned().unwrap_or(Value::Null),
+ "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,
+ "characteristics": format!("{:#x}", s.characteristics),
+ })).collect::<Vec<_>>(),
+ "section_notes": notes,
+ })
+}
+
+pub fn cmd_artifact(args: &[String], json: bool) -> ExitCode {
+ if args.is_empty() {
+ eprintln!("usage: ghidrust artifact get|query|list <id> [--offset N] [--limit N] [--json]");
+ return ExitCode::from(2);
+ }
+ match args[0].as_str() {
+ "list" => match list_artifacts(64) {
+ Ok(m) => {
+ if json {
+ println!("{}", serde_json::to_string_pretty(&m).unwrap());
+ } else {
+ for a in m {
+ println!(
+ "{} kind={} entries={} {}",
+ a.id, a.kind, a.entry_count, a.path
+ );
+ }
+ }
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ },
+ "get" => {
+ let id = match args.get(1) {
+ Some(i) => i.as_str(),
+ None => {
+ eprintln!("usage: ghidrust artifact get <id|path>");
+ return ExitCode::from(2);
+ }
+ };
+ match artifact_get(id) {
+ Ok(v) => {
+ println!("{}", serde_json::to_string_pretty(&v).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "query" => {
+ let id = match args.get(1) {
+ Some(i) => i.as_str(),
+ None => {
+ eprintln!("usage: ghidrust artifact query <id|path> [--offset N] [--limit N]");
+ return ExitCode::from(2);
+ }
+ };
+ let mut offset = 0usize;
+ let mut limit = DEFAULT_PREVIEW_LIMIT;
+ let mut i = 2;
+ while i < args.len() {
+ match args[i].as_str() {
+ "--offset" if i + 1 < args.len() => {
+ offset = args[i + 1].parse().unwrap_or(0);
+ i += 2;
+ }
+ "--limit" if i + 1 < args.len() => {
+ limit = args[i + 1].parse().unwrap_or(DEFAULT_PREVIEW_LIMIT);
+ i += 2;
+ }
+ _ => i += 1,
+ }
+ }
+ match artifact_query(id, offset, limit) {
+ Ok(env) => {
+ println!("{}", serde_json::to_string_pretty(&env).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ other => {
+ eprintln!("unknown artifact subcommand: {other}");
+ ExitCode::from(2)
+ }
+ }
+}
+
+pub fn cmd_inventory(args: &[String], json: bool) -> ExitCode {
+ let dir = match args.first() {
+ Some(d) => PathBuf::from(d),
+ None => {
+ eprintln!("usage: ghidrust inventory <dir> [--max-depth N] [--hash] [--out FILE] [--json]");
+ return ExitCode::from(2);
+ }
+ };
+ let mut max_depth = 8usize;
+ let mut with_hash = false;
+ let mut out_path: Option<PathBuf> = None;
+ let mut i = 1;
+ while i < args.len() {
+ match args[i].as_str() {
+ "--max-depth" if i + 1 < args.len() => {
+ max_depth = args[i + 1].parse().unwrap_or(8);
+ i += 2;
+ }
+ "--hash" => {
+ with_hash = true;
+ i += 1;
+ }
+ "--out" if i + 1 < args.len() => {
+ out_path = Some(PathBuf::from(&args[i + 1]));
+ i += 2;
+ }
+ _ => i += 1,
+ }
+ }
+ match inventory_pe_dir(&dir, max_depth, with_hash) {
+ Ok(inv) => {
+ let entries = serde_json::to_value(&inv.entries).unwrap();
+ let env = match envelope_or_spill(
+ "inventory",
+ entries,
+ 64,
+ DEFAULT_PREVIEW_LIMIT,
+ Some(&inv.root),
+ ) {
+ Ok(e) => e,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return ExitCode::FAILURE;
+ }
+ };
+ let body = json!({
+ "schema_version": inv.schema_version,
+ "root": inv.root,
+ "notes": inv.notes,
+ "envelope": env,
+ "entries": if inv.entries.len() <= 64 { Value::Array(inv.entries.iter().map(|e| serde_json::to_value(e).unwrap()).collect()) } else { Value::Null },
+ });
+ if let Some(p) = out_path {
+ if let Err(e) = write_json_no_bom(&p, &body) {
+ eprintln!("error: {e}");
+ return ExitCode::FAILURE;
+ }
+ }
+ if json {
+ println!("{}", serde_json::to_string_pretty(&body).unwrap());
+ } else {
+ println!("inventory root={} entries={}", inv.root, inv.entries.len());
+ for e in inv.entries.iter().take(32) {
+ println!(
+ " {} size={} file_ver={:?} product_ver={:?}",
+ e.path,
+ e.size,
+ e.version.file_version,
+ e.version.product_version
+ );
+ }
+ if inv.entries.len() > 32 {
+ println!(
+ " … {} more (use --json / artifact envelope)",
+ inv.entries.len() - 32
+ );
+ }
+ }
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+pub fn cmd_tree(args: &[String], json: bool) -> ExitCode {
+ let dir = match args.first() {
+ Some(d) => PathBuf::from(d),
+ None => {
+ eprintln!(
+ "usage: ghidrust tree <path> [--max-depth N] [--ext LIST] [--name GLOB] [--json]"
+ );
+ return ExitCode::from(2);
+ }
+ };
+ let mut opts = TreeListOpts::default();
+ let mut i = 1;
+ while i < args.len() {
+ match args[i].as_str() {
+ "--max-depth" if i + 1 < args.len() => {
+ opts.max_depth = args[i + 1].parse().unwrap_or(6);
+ i += 2;
+ }
+ "--ext" if i + 1 < args.len() => {
+ opts.extensions = Some(
+ args[i + 1]
+ .split(',')
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ .collect(),
+ );
+ i += 2;
+ }
+ "--name" if i + 1 < args.len() => {
+ opts.name_glob = Some(args[i + 1].clone());
+ i += 2;
+ }
+ _ => i += 1,
+ }
+ }
+ let res = list_tree(&dir, opts);
+ let entries_v = serde_json::to_value(&res.entries).unwrap();
+ let env = envelope_or_spill(
+ "tree",
+ entries_v,
+ 128,
+ DEFAULT_PREVIEW_LIMIT,
+ Some(&res.root),
+ );
+ let env = match env {
+ Ok(e) => e,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return ExitCode::FAILURE;
+ }
+ };
+ let body = json!({
+ "root": res.root,
+ "truncated": res.truncated,
+ "envelope": env,
+ "entries": if res.entries.len() <= 128 {
+ serde_json::to_value(&res.entries).unwrap()
+ } else {
+ Value::Null
+ },
+ });
+ if json {
+ println!("{}", serde_json::to_string_pretty(&body).unwrap());
+ } else {
+ for e in res.entries.iter().take(64) {
+ if let Some(err) = &e.error {
+ println!("ERR {} ({err})", e.path);
+ } else if e.is_dir {
+ println!("DIR {}", e.path);
+ } else {
+ println!("FILE {} size={:?}", e.path, e.size);
+ }
+ }
+ if res.truncated || res.entries.len() > 64 {
+ println!("… truncated; drain via artifact envelope");
+ }
+ }
+ ExitCode::SUCCESS
+}
+
+pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
+ if args.is_empty() {
+ eprintln!(
+ "usage: ghidrust process list|attach|detach|modules|read|resolve|regions … [--json]"
+ );
+ return ExitCode::from(2);
+ }
+ match args[0].as_str() {
+ "list" => match process_list() {
+ Ok(list) => {
+ if json {
+ println!("{}", serde_json::to_string_pretty(&list).unwrap());
+ } else {
+ for p in list.iter().take(200) {
+ println!(
+ "{:>8} {} {}",
+ p.pid,
+ p.name,
+ p.path.as_deref().unwrap_or("-")
+ );
+ }
+ }
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ },
+ "attach" => {
+ let pid: u32 = match args.get(1).and_then(|s| s.parse().ok()) {
+ Some(p) => p,
+ None => {
+ eprintln!("usage: ghidrust process attach <pid>");
+ return ExitCode::from(2);
+ }
+ };
+ match process_attach(pid) {
+ Ok(s) => {
+ println!("{}", serde_json::to_string_pretty(&s).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "detach" => {
+ let sid = match args.get(1) {
+ Some(s) => s.as_str(),
+ None => {
+ eprintln!("usage: ghidrust process detach <session_id>");
+ return ExitCode::from(2);
+ }
+ };
+ match process_detach(sid) {
+ Ok(()) => {
+ println!("{{\"ok\":true}}");
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "modules" => {
+ let sid = match args.get(1) {
+ Some(s) => s.as_str(),
+ None => {
+ eprintln!("usage: ghidrust process modules <session_id>");
+ return ExitCode::from(2);
+ }
+ };
+ match process_modules(sid) {
+ Ok(m) => {
+ println!("{}", serde_json::to_string_pretty(&m).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "read" => {
+ let sid = match args.get(1) {
+ Some(s) => s.as_str(),
+ None => {
+ eprintln!("usage: ghidrust process read <session_id> --addr HEX --size N");
+ return ExitCode::from(2);
+ }
+ };
+ let mut addr = None;
+ let mut size = 64usize;
+ let mut i = 2;
+ while i < args.len() {
+ match args[i].as_str() {
+ "--addr" if i + 1 < args.len() => {
+ addr = parse_u64(&args[i + 1]).ok();
+ i += 2;
+ }
+ "--size" if i + 1 < args.len() => {
+ size = args[i + 1].parse().unwrap_or(64);
+ i += 2;
+ }
+ _ => i += 1,
+ }
+ }
+ let Some(va) = addr else {
+ eprintln!("missing --addr");
+ return ExitCode::from(2);
+ };
+ match process_read(sid, va, size) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "resolve" => {
+ let sid = match args.get(1) {
+ Some(s) => s.as_str(),
+ None => {
+ eprintln!(
+ "usage: ghidrust process resolve <session_id> --module NAME --rva HEX"
+ );
+ return ExitCode::from(2);
+ }
+ };
+ let mut module = None;
+ let mut rva = None;
+ let mut i = 2;
+ while i < args.len() {
+ match args[i].as_str() {
+ "--module" if i + 1 < args.len() => {
+ module = Some(args[i + 1].clone());
+ i += 2;
+ }
+ "--rva" if i + 1 < args.len() => {
+ rva = parse_u64(&args[i + 1]).ok();
+ i += 2;
+ }
+ _ => i += 1,
+ }
+ }
+ let (Some(m), Some(r)) = (module, rva) else {
+ eprintln!("need --module and --rva");
+ return ExitCode::from(2);
+ };
+ match process_resolve(sid, &m, r) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "regions" => {
+ let sid = match args.get(1) {
+ Some(s) => s.as_str(),
+ None => {
+ eprintln!("usage: ghidrust process regions <session_id> [--max N]");
+ return ExitCode::from(2);
+ }
+ };
+ let mut max = 256usize;
+ let mut i = 2;
+ while i < args.len() {
+ if args[i] == "--max" && i + 1 < args.len() {
+ max = args[i + 1].parse().unwrap_or(256);
+ i += 2;
+ } else {
+ i += 1;
+ }
+ }
+ match process_regions(sid, max) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ other => {
+ eprintln!("unknown process subcommand: {other}");
+ ExitCode::from(2)
+ }
+ }
+}
+
+pub fn cmd_rtti_query_cli(args: &[String], json: bool) -> ExitCode {
+ let path = match args.first() {
+ Some(p) if !p.starts_with('-') => PathBuf::from(p),
+ _ => {
+ eprintln!(
+ "usage: ghidrust rtti <path> [--filter SUB|--name NAME|--exact] [--match MODE] [--json]"
+ );
+ return ExitCode::from(2);
+ }
+ };
+ let mut filter: Option<String> = None;
+ let mut exact = false;
+ let mut mode = RttiMatchMode::Substr;
+ let mut i = 1;
+ while i < args.len() {
+ match args[i].as_str() {
+ "--filter" | "--name" if i + 1 < args.len() => {
+ filter = Some(args[i + 1].clone());
+ i += 2;
+ }
+ "--exact" => {
+ exact = true;
+ i += 1;
+ }
+ "--match" if i + 1 < args.len() => {
+ mode = RttiMatchMode::parse(&args[i + 1]);
+ i += 2;
+ }
+ _ => {
+ i += 1;
+ }
+ }
+ }
+ let prog = match load_path(&path) {
+ Ok(p) => p,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return ExitCode::FAILURE;
+ }
+ };
+ match rtti_query(&prog, filter.as_deref(), exact, mode) {
+ Ok(q) => {
+ let entries = serde_json::to_value(&q.classes).unwrap();
+ let env = spill_if_large("rtti", entries, q.entry_count);
+ let body = json!({
+ "entry_count": q.entry_count,
+ "cache_hit": q.cache_hit,
+ "notes": q.notes,
+ "envelope": env,
+ "classes": if q.entry_count <= 64 {
+ serde_json::to_value(&q.classes).unwrap()
+ } else {
+ Value::Null
+ },
+ });
+ if json {
+ println!("{}", serde_json::to_string_pretty(&body).unwrap());
+ } else {
+ for c in q.classes.iter().take(64) {
+ println!(
+ "{} vtables={:?} col={:?} conf={} {:?}",
+ c.name, c.vtable_vas, c.col_va, c.confidence, c.reason
+ );
+ }
+ }
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+fn spill_if_large(kind: &str, entries: Value, count: usize) -> Option<Value> {
+ if count <= 64 {
+ return None;
+ }
+ match spill_artifact(kind, entries, DEFAULT_PREVIEW_LIMIT, None) {
+ Ok(e) => Some(serde_json::to_value(e).unwrap()),
+ Err(_) => None,
+ }
+}
+
+pub fn resolve_and_entry(
+ prog: &mut ghidrust_core::Program,
+ addr: Option<u64>,
+) -> Result<(u64, Value), String> {
+ let requested = addr.unwrap_or_else(|| prog.entry.unwrap_or(prog.image_base));
+ let r = resolve_function(prog, requested).map_err(|e| e.to_string())?;
+ let meta = resolve_result_json(&r);
+ if !r.ok {
+ return Err(format!(
+ "resolve failed: {} ({})",
+ r.reason.as_deref().unwrap_or("unknown"),
+ meta
+ ));
+ }
+ Ok((r.resolved_entry.unwrap(), meta))
+}
+
diff --git a/crates/ghidrust-cli/src/main.rs b/crates/ghidrust-cli/src/main.rs
index 88f4a3d..4d7f736 100644
--- a/crates/ghidrust-cli/src/main.rs
+++ b/crates/ghidrust-cli/src/main.rs
@@ -1,12 +1,17 @@
//! Ghidrust CLI + stdio MCP/agent tool surface over ghidrust-core.
+mod friction;
+
use ghidrust_core::{
- 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,
+ analyzer_catalog, analyze_path, artifact_get, artifact_query, collect_strings_bytes,
+ collect_strings_opts, disassemble_range_opts, filter_imports, inventory_pe_dir, list_artifacts,
+ list_tree, load_path, load_path_opts, process_attach, process_detach, process_list,
+ process_modules, process_read, process_regions, process_resolve, recover_rtti, rtti_query,
+ 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,
+ xrefs_from, xrefs_to, xrefs_to_import, xrefs_to_string_filter_opts, AnalysisBundle, BulkScanMode,
+ Program, Project, RttiMatchMode, StringCollectOpts, StringMatchMode, TreeListOpts,
+ ANALYZER_NAMES, DEFAULT_PREVIEW_LIMIT,
};
use ghidrust_decomp::decompile_entry;
use ghidrust_il2cpp::{
@@ -39,7 +44,21 @@ 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),
+ "rtti" => {
+ let rest = &args[1..];
+ if rest.iter().any(|a| {
+ matches!(a.as_str(), "--filter" | "--name" | "--exact" | "query")
+ }) {
+ let rest = if rest.first().map(|s| s.as_str()) == Some("query") {
+ &rest[1..]
+ } else {
+ rest
+ };
+ friction::cmd_rtti_query_cli(rest, json_mode)
+ } else {
+ cmd_rtti(rest, json_mode)
+ }
+ }
"analyzers" => cmd_analyzers(json_mode),
"analyze" => cmd_analyze(&args[1..], json_mode),
"strings" => cmd_strings(&args[1..], json_mode),
@@ -48,6 +67,10 @@ fn main() -> ExitCode {
"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),
+ "inventory" | "pe-inventory" => friction::cmd_inventory(&args[1..], json_mode),
+ "tree" | "list-tree" => friction::cmd_tree(&args[1..], json_mode),
+ "artifact" => friction::cmd_artifact(&args[1..], json_mode),
+ "process" => friction::cmd_process(&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),
@@ -74,13 +97,13 @@ fn print_help() {
eprintln!(
"ghidrust — AI-native reverse-engineering (CodeBrowser headless)\n\n\
Usage:\n\
- ghidrust load <path> [--out FILE] [--json]\n\
+ ghidrust load <path|--project DIR --file-id ID> [--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\
+ [--encoding ascii|utf16le|all] [--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\
@@ -88,7 +111,11 @@ fn print_help() {
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 inventory <dir> [--max-depth N] [--hash] [--out FILE] [--json]\n\
+ ghidrust tree <path> [--max-depth N] [--ext LIST] [--name GLOB] [--json]\n\
+ ghidrust artifact get|query|list <id> [--offset N] [--limit N] [--json]\n\
+ ghidrust process list|attach|detach|modules|read|resolve|regions … [--json]\n\
+ ghidrust rtti <path> [--filter|--name|--exact] [--match MODE] [--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\
@@ -96,7 +123,7 @@ fn print_help() {
[--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\
+ ghidrust gpu-decompile <path> [--addr HEX] [--out FILE] [--metrics FILE] [--json]\n\
ghidrust re-bench <path> [--out FILE] [--json] # CPU then GPU metrics (decomp+bulk)\n\
ghidrust analyzer-bench <path> [--large] [--out FILE] [--json]\n\
ghidrust analyzer-bench-matrix\n\
@@ -372,15 +399,29 @@ fn path_arg(args: &[String]) -> Result<PathBuf, String> {
}
fn cmd_load(args: &[String], json: bool) -> ExitCode {
- let path = match path_arg(args) {
- Ok(p) => p,
+ let (path, identity) = match friction::resolve_program_path(args) {
+ Ok(v) => v,
Err(e) => {
- eprintln!("{e}");
- return ExitCode::from(2);
+ // Fall back to positional path for backward compatibility.
+ match path_arg(args) {
+ Ok(p) => (
+ p.clone(),
+ json!({
+ "path": p.display().to_string(),
+ "project": Value::Null,
+ "file_id": Value::Null,
+ "resolved_path": p.display().to_string(),
+ }),
+ ),
+ Err(_) => {
+ eprintln!("{e}");
+ return ExitCode::from(2);
+ }
+ }
}
};
let mut out_path: Option<PathBuf> = None;
- let mut i = 1;
+ let mut i = 0;
while i < args.len() {
match args[i].as_str() {
"--out" if i + 1 < args.len() => {
@@ -392,18 +433,7 @@ fn cmd_load(args: &[String], json: bool) -> ExitCode {
}
match load_path(&path) {
Ok(prog) => {
- 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<_>>(),
- });
+ let v = friction::load_json_for_prog(&prog, &identity);
emit_result(&v, json, out_path.as_deref(), || print_program_summary(&prog))
}
Err(e) => {
@@ -503,11 +533,29 @@ 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) => emit_result(&listing, json, out_path.as_deref(), || {
- for insn in &listing {
- println!("{}", insn.text());
+ Ok(result) => {
+ if json {
+ let body = json!({
+ "insns": result.insns,
+ "decode_gaps": result.decode_gaps,
+ "first_gap_va": result.first_gap_va.map(|v| format!("{v:#x}")),
+ });
+ emit_result(&body, true, out_path.as_deref(), || {})
+ } else {
+ emit_result(&result.insns, false, out_path.as_deref(), || {
+ for insn in &result.insns {
+ println!("{}", insn.text());
+ }
+ if result.decode_gaps > 0 {
+ println!(
+ "; decode_gaps={} first_gap={:?}",
+ result.decode_gaps,
+ result.first_gap_va.map(|v| format!("{v:#x}"))
+ );
+ }
+ })
}
- }),
+ }
Err(e) => {
eprintln!("error: {e}");
ExitCode::FAILURE
@@ -713,6 +761,7 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
let mut import_name: Option<String> = None;
let mut skip_stubs = false;
let mut classify = false;
+ let mut encoding = "all".to_string();
let mut out_path: Option<PathBuf> = None;
let mut i = 1;
while i < args.len() {
@@ -733,6 +782,10 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
import_name = Some(args[i + 1].clone());
i += 2;
}
+ "--encoding" if i + 1 < args.len() => {
+ encoding = args[i + 1].clone();
+ i += 2;
+ }
"--skip-stubs" => {
skip_stubs = true;
i += 1;
@@ -754,7 +807,7 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
.count();
if modes != 1 {
eprintln!(
- "usage: ghidrust xrefs <path> (--to HEX | --from HEX | --string FILTER | --import NAME) [--skip-stubs] [--classify] [--out FILE] [--json]"
+ "usage: ghidrust xrefs <path> (--to HEX | --from HEX | --string FILTER | --import NAME) [--encoding ascii|utf16le|all] [--skip-stubs] [--classify] [--out FILE] [--json]"
);
return ExitCode::from(2);
}
@@ -765,7 +818,7 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
} else if let Some(f) = from {
xrefs_from(&prog, f, 256)
} else if let Some(s) = string_filter {
- xrefs_to_string_filter(&prog, &s)
+ xrefs_to_string_filter_opts(&prog, &s, &encoding, true)
} else {
xrefs_to_import(&prog, import_name.as_deref().unwrap())
};
@@ -796,6 +849,7 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
"to": format!("{:#x}", r.to),
"kind": kind,
"preview": preview,
+ "encoding": r.encoding,
})
})
.collect();
@@ -1722,13 +1776,14 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {
Some(p) => PathBuf::from(p),
None => {
eprintln!(
- "usage: ghidrust gpu-decompile <path> [--out FILE] [--metrics FILE] [--json]"
+ "usage: ghidrust gpu-decompile <path> [--addr HEX] [--out FILE] [--metrics FILE] [--json]"
);
return ExitCode::from(2);
}
};
let mut out_path = PathBuf::from("ghidrust_gpu_decompile.gdecomp");
let mut metrics_path: Option<PathBuf> = None;
+ let mut addr: Option<u64> = None;
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
@@ -1740,18 +1795,29 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {
metrics_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
+ "--addr" if i + 1 < args.len() => {
+ addr = parse_u64(&args[i + 1]).ok();
+ i += 2;
+ }
_ => i += 1,
}
}
- let prog = match load_path(&path) {
+ let mut prog = match load_path(&path) {
Ok(p) => p,
Err(e) => {
eprintln!("load error: {e}");
return ExitCode::FAILURE;
}
};
+ let (entry_va, resolve_meta) = match friction::resolve_and_entry(&mut prog, addr) {
+ Ok(v) => v,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return ExitCode::FAILURE;
+ }
+ };
let t_cpu = Instant::now();
- let cpu = match ghidrust_decomp::decompile_entry(&prog, 64) {
+ let cpu = match ghidrust_decomp::decompile_at(&prog, entry_va, 64) {
Ok(d) => d,
Err(e) => {
eprintln!("cpu decompile: {e}");
@@ -1760,7 +1826,7 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {
};
let cpu_ms = t_cpu.elapsed().as_secs_f64() * 1000.0;
- let rep = match ghidrust_decomp::gpu_decompile_to_file(&prog, None, &out_path, 128) {
+ let rep = match ghidrust_decomp::gpu_decompile_to_file(&prog, Some(entry_va), &out_path, 128) {
Ok(r) => r,
Err(e) => {
eprintln!("gpu-decompile error: {e}");
@@ -1783,6 +1849,11 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {
let metrics = json!({
"file": path.display().to_string(),
+ "resolve": resolve_meta,
+ "requested_addr": addr.map(|a| format!("{a:#x}")),
+ "resolved_entry": format!("{entry_va:#x}"),
+ "dump_path": out_path.display().to_string(),
+ "note": ".gdecomp is opaque binary dump — use metrics JSON, not dump-as-text",
"cpu_decompile_ms": cpu_ms,
"cpu_blocks": cpu.blocks.len(),
"cpu_chars": cpu.char_count(),
@@ -1924,8 +1995,25 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
}
let _ = stage0; // suppressed; retained for future gating
match load_path(&path) {
- Ok(prog) => {
- let mut va = addr.unwrap_or_else(|| prog.entry.unwrap_or(prog.image_base));
+ Ok(mut prog) => {
+ let (mut va, resolve_meta) = match friction::resolve_and_entry(&mut prog, addr) {
+ Ok(v) => v,
+ Err(e) => {
+ if json {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&json!({
+ "ok": false,
+ "error": e,
+ }))
+ .unwrap()
+ );
+ } else {
+ eprintln!("error: {e}");
+ }
+ return ExitCode::FAILURE;
+ }
+ };
let mut follow_meta: Option<Value> = None;
if follow_stub {
if let Some(stub) = classify_at(&prog, va) {
@@ -1972,6 +2060,7 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
Ok((d, s1)) => {
let mut obj = json!({
"decompile": d,
+ "resolve": resolve_meta,
"stage1": {
"loops": s1.structure.loops.len(),
"phis": s1.ssa.phi_count(),
@@ -2637,6 +2726,7 @@ fn refs_json(refs: &[ghidrust_core::XRef]) -> Value {
"to": format!("{:#x}", r.to),
"kind": r.kind,
"preview": r.preview,
+ "encoding": r.encoding,
})
})
.collect(),
@@ -2664,13 +2754,159 @@ fn tool_defs() -> Vec<ToolDef> {
vec![
ToolDef {
name: "load",
- description: "Load a PE or ELF binary and return memory map / sections",
+ description: "Load a PE or ELF binary (path OR project+file_id) and return sections + section_notes",
input_schema: json!({
"type": "object",
- "properties": { "path": { "type": "string" } },
+ "properties": {
+ "path": { "type": "string" },
+ "project": { "type": "string", "description": "Project directory" },
+ "file_id": { "type": "string", "description": "Imported file id within project" }
+ }
+ }),
+ },
+ ToolDef {
+ name: "artifact_get",
+ description: "Fetch a spilled analysis artifact by id or path (full JSON)",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "id": { "type": "string" } },
+ "required": ["id"]
+ }),
+ },
+ ToolDef {
+ name: "artifact_query",
+ description: "Page through an artifact with offset/limit; returns next_offset",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "id": { "type": "string" },
+ "offset": { "type": "integer" },
+ "limit": { "type": "integer" }
+ },
+ "required": ["id"]
+ }),
+ },
+ ToolDef {
+ name: "artifact_list",
+ description: "List recent spilled analysis artifacts (id/kind/path/entry_count)",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "max": { "type": "integer", "description": "Max artifacts to list (default 64)" }
+ }
+ }),
+ },
+ ToolDef {
+ name: "inventory",
+ description: "Generic PE install inventory (exe/dll catalog + VERSIONINFO)",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "path": { "type": "string", "description": "Install / directory root" },
+ "max_depth": { "type": "integer" },
+ "hash": { "type": "boolean" }
+ },
"required": ["path"]
}),
},
+ ToolDef {
+ name: "list_tree",
+ description: "Bounded file tree index (size/mtime; no unpack; errors as rows)",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "max_depth": { "type": "integer" },
+ "extensions": { "type": "string", "description": "Comma-separated extensions" },
+ "name_glob": { "type": "string" }
+ },
+ "required": ["path"]
+ }),
+ },
+ ToolDef {
+ name: "rtti_query",
+ description: "RTTI catalog query (filter/exact) with multi-vtable honesty + cache",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "filter": { "type": "string" },
+ "exact": { "type": "boolean" },
+ "match": { "type": "string", "enum": ["substr", "token", "whole", "glob", "exact"] }
+ },
+ "required": ["path"]
+ }),
+ },
+ ToolDef {
+ name: "process_list",
+ description: "List OS processes (Windows Live Process Bridge)",
+ input_schema: json!({ "type": "object", "properties": {} }),
+ },
+ ToolDef {
+ name: "process_attach",
+ description: "Attach read-only to a process by pid; returns session_id",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "pid": { "type": "integer" } },
+ "required": ["pid"]
+ }),
+ },
+ ToolDef {
+ name: "process_detach",
+ description: "Detach a live-process session by session_id",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "session_id": { "type": "string" } },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_modules",
+ description: "List modules (base/size/path) for an attached session",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "session_id": { "type": "string" } },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_read",
+ description: "Read process memory at VA (capped); short reads are explicit errors",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "addr": { "type": "string" },
+ "size": { "type": "integer" }
+ },
+ "required": ["session_id", "addr"]
+ }),
+ },
+ ToolDef {
+ name: "process_resolve",
+ description: "static_to_live: module + RVA → live VA (ASLR)",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "module": { "type": "string" },
+ "rva": { "type": "string" }
+ },
+ "required": ["session_id", "module", "rva"]
+ }),
+ },
+ ToolDef {
+ name: "process_regions",
+ description: "List memory regions for an attached session (capped)",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "max": { "type": "integer", "description": "Max regions (default 256)" }
+ },
+ "required": ["session_id"]
+ }),
+ },
ToolDef {
name: "disassemble",
description: "Disassemble x86-64 at entry or given address",
@@ -2747,11 +2983,12 @@ fn tool_defs() -> Vec<ToolDef> {
},
ToolDef {
name: "gpu_decompile",
- description: "GPU-resident multipass decompile of entry; returns dump metrics (PCIe/device when available)",
+ description: "GPU multipass decompile at addr (containing-fn resolve); returns metrics JSON path; .gdecomp is opaque",
input_schema: json!({
"type": "object",
"properties": {
"path": { "type": "string" },
+ "addr": { "type": "string", "description": "VA (mid-body ok; resolved to containing entry)" },
"out": { "type": "string", "description": "optional dump path" }
},
"required": ["path"]
@@ -2903,12 +3140,13 @@ fn tool_defs() -> Vec<ToolDef> {
},
ToolDef {
name: "get_string_xrefs",
- description: "Find strings by filter, then xrefs to each string VA",
+ description: "Find strings by filter, then xrefs (encoding ascii|utf16le|all; interior LEA supported)",
input_schema: json!({
"type": "object",
"properties": {
"path": { "type": "string" },
- "filter": { "type": "string" }
+ "filter": { "type": "string" },
+ "encoding": { "type": "string", "enum": ["ascii", "utf16", "utf16le", "all"] }
},
"required": ["path", "filter"]
}),
@@ -3052,6 +3290,205 @@ fn call_tool(params: &Value) -> Result<String, String> {
let args = params.get("arguments").cloned().unwrap_or(json!({}));
match name {
+ "artifact_get" => {
+ let id = args
+ .get("id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.id".to_string())?;
+ let v = artifact_get(id).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&v).unwrap())
+ }
+ "artifact_query" => {
+ let id = args
+ .get("id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.id".to_string())?;
+ let offset = args.get("offset").and_then(|o| o.as_u64()).unwrap_or(0) as usize;
+ let limit = args
+ .get("limit")
+ .and_then(|o| o.as_u64())
+ .unwrap_or(DEFAULT_PREVIEW_LIMIT as u64) as usize;
+ let env = artifact_query(id, offset, limit).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&env).unwrap())
+ }
+ "artifact_list" => {
+ let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(64) as usize;
+ let m = list_artifacts(max).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&m).unwrap())
+ }
+ "inventory" => {
+ let path = args
+ .get("path")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ let max_depth = args.get("max_depth").and_then(|m| m.as_u64()).unwrap_or(8) as usize;
+ let with_hash = args.get("hash").and_then(|h| h.as_bool()).unwrap_or(false);
+ let inv = inventory_pe_dir(path, max_depth, with_hash).map_err(|e| e.to_string())?;
+ let entries = serde_json::to_value(&inv.entries).unwrap();
+ let env = ghidrust_core::envelope_or_spill(
+ "inventory",
+ entries,
+ 64,
+ DEFAULT_PREVIEW_LIMIT,
+ Some(&inv.root),
+ )
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&json!({
+ "schema_version": inv.schema_version,
+ "root": inv.root,
+ "notes": inv.notes,
+ "entry_count": inv.entries.len(),
+ "envelope": env,
+ "entries": if inv.entries.len() <= 64 {
+ serde_json::to_value(&inv.entries).unwrap()
+ } else {
+ Value::Null
+ },
+ }))
+ .unwrap())
+ }
+ "list_tree" => {
+ let path = args
+ .get("path")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ let mut opts = TreeListOpts::default();
+ if let Some(d) = args.get("max_depth").and_then(|m| m.as_u64()) {
+ opts.max_depth = d as usize;
+ }
+ if let Some(ext) = args.get("extensions").and_then(|e| e.as_str()) {
+ opts.extensions = Some(
+ ext.split(',')
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ .collect(),
+ );
+ }
+ if let Some(g) = args.get("name_glob").and_then(|e| e.as_str()) {
+ opts.name_glob = Some(g.to_string());
+ }
+ let res = list_tree(path, opts);
+ let entries = serde_json::to_value(&res.entries).unwrap();
+ let env = ghidrust_core::envelope_or_spill(
+ "tree",
+ entries,
+ 128,
+ DEFAULT_PREVIEW_LIMIT,
+ Some(&res.root),
+ )
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&json!({
+ "root": res.root,
+ "truncated": res.truncated,
+ "entry_count": res.entries.len(),
+ "envelope": env,
+ }))
+ .unwrap())
+ }
+ "rtti_query" => {
+ 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 exact = args.get("exact").and_then(|e| e.as_bool()).unwrap_or(false);
+ let mode = args
+ .get("match")
+ .and_then(|m| m.as_str())
+ .map(RttiMatchMode::parse)
+ .unwrap_or(RttiMatchMode::Substr);
+ let prog = load_path(path).map_err(|e| e.to_string())?;
+ let q = rtti_query(&prog, filter, exact, mode).map_err(|e| e.to_string())?;
+ let entries = serde_json::to_value(&q.classes).unwrap();
+ let env = if q.entry_count > 64 {
+ Some(
+ ghidrust_core::spill_artifact("rtti", entries, DEFAULT_PREVIEW_LIMIT, Some(path))
+ .map_err(|e| e.to_string())?,
+ )
+ } else {
+ None
+ };
+ Ok(serde_json::to_string_pretty(&json!({
+ "entry_count": q.entry_count,
+ "cache_hit": q.cache_hit,
+ "notes": q.notes,
+ "envelope": env,
+ "classes": if q.entry_count <= 64 {
+ serde_json::to_value(&q.classes).unwrap()
+ } else {
+ Value::Null
+ },
+ }))
+ .unwrap())
+ }
+ "process_list" => {
+ let list = process_list()?;
+ Ok(serde_json::to_string_pretty(&list).unwrap())
+ }
+ "process_attach" => {
+ let pid = args
+ .get("pid")
+ .and_then(|p| p.as_u64())
+ .ok_or_else(|| "missing arguments.pid".to_string())? as u32;
+ let s = process_attach(pid)?;
+ Ok(serde_json::to_string_pretty(&s).unwrap())
+ }
+ "process_detach" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ process_detach(sid)?;
+ Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())
+ }
+ "process_modules" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let m = process_modules(sid)?;
+ Ok(serde_json::to_string_pretty(&m).unwrap())
+ }
+ "process_read" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let addr = args
+ .get("addr")
+ .and_then(|a| a.as_str())
+ .ok_or_else(|| "missing arguments.addr".to_string())?;
+ let size = args.get("size").and_then(|s| s.as_u64()).unwrap_or(64) as usize;
+ let va = parse_u64(addr)?;
+ let r = process_read(sid, va, size)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "process_resolve" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let module = args
+ .get("module")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.module".to_string())?;
+ let rva = args
+ .get("rva")
+ .and_then(|a| a.as_str())
+ .ok_or_else(|| "missing arguments.rva".to_string())?;
+ let rva = parse_u64(rva)?;
+ let r = process_resolve(sid, module, rva)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "process_regions" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(256) as usize;
+ let r = process_regions(sid, max)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
"list_strings" | "search_strings" => {
let path = args
.get("path")
@@ -3298,8 +3735,12 @@ fn call_tool(params: &Value) -> Result<String, String> {
.get("filter")
.and_then(|f| f.as_str())
.ok_or_else(|| "missing arguments.filter".to_string())?;
+ let encoding = args
+ .get("encoding")
+ .and_then(|e| e.as_str())
+ .unwrap_or("all");
let prog = load_path(path).map_err(|e| e.to_string())?;
- let refs = xrefs_to_string_filter(&prog, filter);
+ let refs = xrefs_to_string_filter_opts(&prog, filter, encoding, true);
Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())
}
"list_imports" => {
@@ -3376,10 +3817,19 @@ fn call_tool(params: &Value) -> Result<String, String> {
.and_then(|p| p.as_str())
.map(PathBuf::from)
.unwrap_or_else(|| std::env::temp_dir().join("mcp_gpu_decompile.gdecomp"));
- let prog = load_path(path).map_err(|e| e.to_string())?;
- let rep = ghidrust_decomp::gpu_decompile_to_file(&prog, None, &out, 256)
+ let mut prog = load_path(path).map_err(|e| e.to_string())?;
+ let addr = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {
+ Some(parse_u64(a)?)
+ } else {
+ None
+ };
+ let (entry, resolve_meta) = friction::resolve_and_entry(&mut prog, addr)?;
+ let rep = ghidrust_decomp::gpu_decompile_to_file(&prog, Some(entry), &out, 256)
.map_err(|e| e.to_string())?;
Ok(serde_json::to_string_pretty(&json!({
+ "resolve": resolve_meta,
+ "requested_addr": addr.map(|a| format!("{a:#x}")),
+ "resolved_entry": format!("{entry:#x}"),
"backend": rep.backend,
"device": rep.device,
"ms": rep.ms,
@@ -3391,6 +3841,7 @@ fn call_tool(params: &Value) -> Result<String, String> {
"block_count": rep.block_count,
"dump_path": rep.dump_path,
"dump_bytes": rep.dump_bytes,
+ "note": ".gdecomp is opaque — use metrics fields, do not read dump as text",
"pseudo_c_head": rep.pseudo_c.lines().take(8).collect::<Vec<_>>().join("\n"),
}))
.unwrap())
@@ -3437,12 +3888,13 @@ fn call_tool(params: &Value) -> Result<String, String> {
.get("follow_stub")
.and_then(|v| v.as_bool())
.unwrap_or(false);
- let prog = load_path(path).map_err(|e| e.to_string())?;
- let mut va = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {
- parse_u64(a)?
+ let mut prog = load_path(path).map_err(|e| e.to_string())?;
+ let addr_opt = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {
+ Some(parse_u64(a)?)
} else {
- prog.entry.unwrap_or(prog.image_base)
+ None
};
+ let (mut va, resolve_meta) = friction::resolve_and_entry(&mut prog, addr_opt)?;
let mut follow_meta: Option<Value> = None;
if follow_stub {
if let Some(stub) = classify_at(&prog, va) {
@@ -3477,6 +3929,7 @@ fn call_tool(params: &Value) -> Result<String, String> {
ghidrust_decomp::decompile_at(&prog, va, count).map_err(|e| e.to_string())?;
let mut obj = json!({
"stage": "0",
+ "resolve": resolve_meta,
"name": d.name,
"entry": format!("{:#x}", d.entry),
"blocks": d.blocks.len(),
@@ -3494,6 +3947,7 @@ fn call_tool(params: &Value) -> Result<String, String> {
.map_err(|e| e.to_string())?;
let mut obj = json!({
"stage": "0.5",
+ "resolve": resolve_meta,
"name": d.name,
"entry": format!("{:#x}", d.entry),
"blocks": d.blocks.len(),
@@ -3513,6 +3967,7 @@ fn call_tool(params: &Value) -> Result<String, String> {
.map_err(|e| e.to_string())?;
let mut obj = json!({
"stage": "1",
+ "resolve": resolve_meta,
"name": d.name,
"entry": format!("{:#x}", d.entry),
"blocks": d.blocks.len(),
@@ -3536,44 +3991,77 @@ fn call_tool(params: &Value) -> Result<String, String> {
}
}
"load" | "disassemble" | "rtti" | "analyze" => {
- let path = args
- .get("path")
- .and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
match name {
"load" => {
- let prog = load_path(path).map_err(|e| e.to_string())?;
- Ok(serde_json::to_string_pretty(&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,
- })).collect::<Vec<_>>(),
- }))
+ let path = if let Some(p) = args.get("path").and_then(|p| p.as_str()) {
+ p.to_string()
+ } else if let (Some(proj), Some(fid)) = (
+ args.get("project").and_then(|p| p.as_str()),
+ args.get("file_id").and_then(|p| p.as_str()),
+ ) {
+ let project = Project::open(proj).map_err(|e| e.to_string())?;
+ let entry = project
+ .list_files()
+ .into_iter()
+ .find(|f| f.id == fid)
+ .ok_or_else(|| format!("file_id not found: {fid}"))?;
+ project
+ .root
+ .join(&entry.imported_rel)
+ .display()
+ .to_string()
+ } else {
+ return Err("load requires path or project+file_id".into());
+ };
+ let prog = load_path(&path).map_err(|e| e.to_string())?;
+ let identity = json!({
+ "path": args.get("path").and_then(|p| p.as_str()),
+ "project": args.get("project").and_then(|p| p.as_str()),
+ "file_id": args.get("file_id").and_then(|p| p.as_str()),
+ "resolved_path": path,
+ });
+ Ok(serde_json::to_string_pretty(&friction::load_json_for_prog(
+ &prog, &identity,
+ ))
.unwrap())
}
"disassemble" => {
- let prog = load_path(path).map_err(|e| e.to_string())?;
+ let path = args
+ .get("path")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ let mut prog = load_path(path).map_err(|e| e.to_string())?;
let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(16) as usize;
- let start = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {
- parse_u64(a)?
+ let addr_opt = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {
+ Some(parse_u64(a)?)
} else {
- prog.entry.unwrap_or(prog.image_base)
+ None
};
- let listing =
- disassemble_range(&prog, start, count).map_err(|e| e.to_string())?;
- Ok(serde_json::to_string_pretty(&listing).unwrap())
+ let (start, resolve_meta) = friction::resolve_and_entry(&mut prog, addr_opt)?;
+ let result = disassemble_range_opts(&prog, start, count, true)
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&json!({
+ "resolve": resolve_meta,
+ "decode_gaps": result.decode_gaps,
+ "first_gap_va": result.first_gap_va.map(|v| format!("{v:#x}")),
+ "insns": result.insns,
+ }))
+ .unwrap())
}
"rtti" => {
+ let path = args
+ .get("path")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let prog = load_path(path).map_err(|e| e.to_string())?;
let report = recover_rtti(&prog).map_err(|e| e.to_string())?;
Ok(serde_json::to_string_pretty(&report).unwrap())
}
"analyze" => {
+ let path = args
+ .get("path")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let mut prog = load_path(path).map_err(|e| e.to_string())?;
let names_owned: Vec<String> = args
.get("analyzers")
diff --git a/crates/ghidrust-cli/tests/eval_analysis_decompile.rs b/crates/ghidrust-cli/tests/eval_analysis_decompile.rs
index 4a50e7b..d83ca95 100644
--- a/crates/ghidrust-cli/tests/eval_analysis_decompile.rs
+++ b/crates/ghidrust-cli/tests/eval_analysis_decompile.rs
@@ -905,7 +905,7 @@ fn write_report(rows: &[EvalRow], env: &Value, report_md: &Path, report_json: &P
md.push_str("## How to re-run\n\n");
md.push_str("```powershell\n");
- md.push_str("cd F:/Repos/Ghidrust\n");
+ md.push_str("cd /path/to/Ghidrust\n");
md.push_str("cargo test -p ghidrust-cli --test eval_analysis_decompile -- --nocapture\n");
md.push_str("# release profile (honest timings):\n");
md.push_str("cargo test -p ghidrust-cli --test eval_analysis_decompile --release -- --nocapture\n");
diff --git a/crates/ghidrust-core/src/artifacts.rs b/crates/ghidrust-core/src/artifacts.rs
new file mode 100644
index 0000000..5c3b203
--- /dev/null
+++ b/crates/ghidrust-core/src/artifacts.rs
@@ -0,0 +1,298 @@
+//! Analysis Artifact Protocol — durable full JSON results with RPC envelopes.
+//!
+//! Large MCP/CLI payloads spill to disk; tool responses carry envelopes with
+//! `entry_count`, preview, and `artifact_id` for `artifact_get` / `artifact_query`.
+
+use crate::error::{Error, Result};
+use crate::io_util::write_json_no_bom;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+/// Default preview rows returned in an envelope (never silently truncates the spill).
+pub const DEFAULT_PREVIEW_LIMIT: usize = 32;
+
+/// Directory under the process temp dir for spilled artifacts.
+pub fn artifact_dir() -> PathBuf {
+ std::env::temp_dir().join("ghidrust-artifacts")
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ArtifactMeta {
+ pub id: String,
+ pub kind: String,
+ pub path: String,
+ pub entry_count: usize,
+ pub created_unix_ms: u64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub source: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ArtifactEnvelope {
+ pub ok: bool,
+ pub kind: String,
+ pub entry_count: usize,
+ pub preview: Value,
+ pub preview_count: usize,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub artifact_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub artifact_path: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub next_offset: Option<usize>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub note: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct ArtifactFile {
+ meta: ArtifactMeta,
+ entries: Value,
+}
+
+static LAST_IDS: Mutex<Vec<String>> = Mutex::new(Vec::new());
+
+fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
+
+fn new_id(kind: &str) -> String {
+ let ms = now_ms();
+ let n = LAST_IDS
+ .lock()
+ .map(|g| g.len())
+ .unwrap_or(0);
+ format!("{kind}-{ms}-{n}")
+}
+
+fn remember_id(id: &str) {
+ if let Ok(mut g) = LAST_IDS.lock() {
+ g.push(id.to_string());
+ if g.len() > 256 {
+ let drain = g.len() - 256;
+ g.drain(0..drain);
+ }
+ }
+}
+
+fn meta_path(id: &str) -> PathBuf {
+ artifact_dir().join(format!("{id}.json"))
+}
+
+/// Spill `entries` (array or object) to disk and return an envelope with a preview page.
+pub fn spill_artifact(
+ kind: &str,
+ entries: Value,
+ preview_limit: usize,
+ source: Option<&str>,
+) -> Result<ArtifactEnvelope> {
+ let entry_count = match &entries {
+ Value::Array(a) => a.len(),
+ Value::Object(o) => o
+ .get("entries")
+ .and_then(|e| e.as_array())
+ .map(|a| a.len())
+ .unwrap_or(1),
+ _ => 1,
+ };
+ let id = new_id(kind);
+ let dir = artifact_dir();
+ fs::create_dir_all(&dir).map_err(|e| Error::Io(e.to_string()))?;
+ let path = meta_path(&id);
+ let meta = ArtifactMeta {
+ id: id.clone(),
+ kind: kind.into(),
+ path: path.display().to_string(),
+ entry_count,
+ created_unix_ms: now_ms(),
+ source: source.map(|s| s.to_string()),
+ };
+ let file = ArtifactFile {
+ meta: meta.clone(),
+ entries: entries.clone(),
+ };
+ write_json_no_bom(&path, &file)?;
+ remember_id(&id);
+
+ let (preview, preview_count, next_offset) = preview_slice(&entries, 0, preview_limit);
+ Ok(ArtifactEnvelope {
+ ok: true,
+ kind: kind.into(),
+ entry_count,
+ preview,
+ preview_count,
+ artifact_id: Some(id),
+ artifact_path: Some(meta.path),
+ next_offset,
+ note: Some(
+ "Full results spilled to artifact_path. Use artifact_get/artifact_query to drain."
+ .into(),
+ ),
+ })
+}
+
+/// Spill when `entry_count` exceeds `threshold`; otherwise return inline envelope (no disk).
+pub fn envelope_or_spill(
+ kind: &str,
+ entries: Value,
+ threshold: usize,
+ preview_limit: usize,
+ source: Option<&str>,
+) -> Result<ArtifactEnvelope> {
+ let entry_count = match &entries {
+ Value::Array(a) => a.len(),
+ _ => 1,
+ };
+ if entry_count > threshold {
+ return spill_artifact(kind, entries, preview_limit, source);
+ }
+ let (preview, preview_count, next_offset) = preview_slice(&entries, 0, preview_limit.max(entry_count));
+ Ok(ArtifactEnvelope {
+ ok: true,
+ kind: kind.into(),
+ entry_count,
+ preview,
+ preview_count,
+ artifact_id: None,
+ artifact_path: None,
+ next_offset,
+ note: None,
+ })
+}
+
+fn preview_slice(entries: &Value, offset: usize, limit: usize) -> (Value, usize, Option<usize>) {
+ match entries {
+ Value::Array(a) => {
+ if offset >= a.len() {
+ return (Value::Array(vec![]), 0, None);
+ }
+ let end = (offset + limit).min(a.len());
+ let page: Vec<Value> = a[offset..end].to_vec();
+ let next = if end < a.len() { Some(end) } else { None };
+ (Value::Array(page.clone()), page.len(), next)
+ }
+ other => (other.clone(), 1, None),
+ }
+}
+
+fn load_file(id: &str) -> Result<ArtifactFile> {
+ let path = resolve_artifact_path(id)?;
+ let data = fs::read_to_string(&path).map_err(|e| Error::Io(e.to_string()))?;
+ serde_json::from_str(&data).map_err(|e| Error::Io(format!("artifact parse: {e}")))
+}
+
+/// Resolve artifact id or absolute path to the JSON file.
+pub fn resolve_artifact_path(id_or_path: &str) -> Result<PathBuf> {
+ let p = PathBuf::from(id_or_path);
+ if p.is_file() {
+ return Ok(p);
+ }
+ let by_id = meta_path(id_or_path);
+ if by_id.is_file() {
+ return Ok(by_id);
+ }
+ // Allow bare id without .json when stored under artifact_dir
+ let with_json = artifact_dir().join(format!("{id_or_path}.json"));
+ if with_json.is_file() {
+ return Ok(with_json);
+ }
+ Err(Error::Io(format!("artifact not found: {id_or_path}")))
+}
+
+/// Return full artifact JSON (meta + entries).
+pub fn artifact_get(id_or_path: &str) -> Result<Value> {
+ let file = load_file(id_or_path)?;
+ Ok(serde_json::to_value(file).map_err(|e| Error::Io(e.to_string()))?)
+}
+
+/// Page through artifact entries with `offset` / `limit`. Returns envelope with `next_offset`.
+pub fn artifact_query(
+ id_or_path: &str,
+ offset: usize,
+ limit: usize,
+) -> Result<ArtifactEnvelope> {
+ let file = load_file(id_or_path)?;
+ let limit = if limit == 0 { DEFAULT_PREVIEW_LIMIT } else { limit };
+ let (preview, preview_count, next_offset) = preview_slice(&file.entries, offset, limit);
+ Ok(ArtifactEnvelope {
+ ok: true,
+ kind: file.meta.kind,
+ entry_count: file.meta.entry_count,
+ preview,
+ preview_count,
+ artifact_id: Some(file.meta.id),
+ artifact_path: Some(file.meta.path),
+ next_offset,
+ note: None,
+ })
+}
+
+/// List known artifacts in the spill directory (newest first, capped).
+pub fn list_artifacts(max: usize) -> Result<Vec<ArtifactMeta>> {
+ let dir = artifact_dir();
+ if !dir.is_dir() {
+ return Ok(vec![]);
+ }
+ let mut metas = Vec::new();
+ let rd = fs::read_dir(&dir).map_err(|e| Error::Io(e.to_string()))?;
+ for ent in rd.flatten() {
+ let path = ent.path();
+ if path.extension().and_then(|e| e.to_str()) != Some("json") {
+ continue;
+ }
+ if let Ok(data) = fs::read_to_string(&path) {
+ if let Ok(file) = serde_json::from_str::<ArtifactFile>(&data) {
+ metas.push(file.meta);
+ }
+ }
+ }
+ metas.sort_by(|a, b| b.created_unix_ms.cmp(&a.created_unix_ms));
+ metas.truncate(max.max(1));
+ Ok(metas)
+}
+
+/// Ensure parent exists; used by CLI `--out` spill helpers.
+pub fn ensure_parent(path: &Path) -> Result<()> {
+ if let Some(parent) = path.parent() {
+ if !parent.as_os_str().is_empty() {
+ fs::create_dir_all(parent).map_err(|e| Error::Io(e.to_string()))?;
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn spill_and_query_pages() {
+ let entries = json!((0..100).map(|i| json!({"i": i})).collect::<Vec<_>>());
+ let env = spill_artifact("test", entries, 10, Some("unit")).unwrap();
+ assert_eq!(env.entry_count, 100);
+ assert_eq!(env.preview_count, 10);
+ assert_eq!(env.next_offset, Some(10));
+ let id = env.artifact_id.unwrap();
+ let page2 = artifact_query(&id, 10, 10).unwrap();
+ assert_eq!(page2.preview_count, 10);
+ assert_eq!(page2.next_offset, Some(20));
+ let full = artifact_get(&id).unwrap();
+ assert_eq!(full["meta"]["entry_count"], 100);
+ }
+
+ #[test]
+ fn inline_below_threshold() {
+ let entries = json!([1, 2, 3]);
+ let env = envelope_or_spill("tiny", entries, 10, 32, None).unwrap();
+ assert!(env.artifact_id.is_none());
+ assert_eq!(env.entry_count, 3);
+ }
+}
diff --git a/crates/ghidrust-core/src/disasm.rs b/crates/ghidrust-core/src/disasm.rs
index fa92766..f9f3e50 100644
--- a/crates/ghidrust-core/src/disasm.rs
+++ b/crates/ghidrust-core/src/disasm.rs
@@ -15,22 +15,34 @@ pub fn disassemble_at(prog: &Program, va: u64) -> Result<Instruction> {
}
pub fn disassemble_range(prog: &Program, start: u64, max_insns: usize) -> Result<Vec<Instruction>> {
- disassemble_range_opts(prog, start, max_insns, false)
+ disassemble_range_opts(prog, start, max_insns, false).map(|r| r.insns)
+}
+
+/// Result of a continuity-aware disassembly pass.
+#[derive(Debug, Clone)]
+pub struct DisasmRangeResult {
+ pub insns: Vec<Instruction>,
+ /// Number of undecodable byte positions skipped (soft-fail holes).
+ pub decode_gaps: usize,
+ /// First gap VA when any gaps were skipped.
+ pub first_gap_va: Option<u64>,
}
/// Disassemble up to `max_insns` instructions from `start`.
///
/// When `skip_bad` is true, undecodable bytes advance by one and continue
-/// (listing continuity across sparse decode holes).
+/// (listing continuity across sparse decode holes). `decode_gaps` counts skips.
pub fn disassemble_range_opts(
prog: &Program,
start: u64,
max_insns: usize,
skip_bad: bool,
-) -> Result<Vec<Instruction>> {
+) -> Result<DisasmRangeResult> {
let mut out = Vec::new();
let mut va = start;
let mut steps = 0usize;
+ let mut decode_gaps = 0usize;
+ let mut first_gap_va = None;
let max_steps = if skip_bad {
max_insns.saturating_mul(8).max(max_insns)
} else {
@@ -46,6 +58,10 @@ pub fn disassemble_range_opts(
}
Err(_) => {
if skip_bad {
+ if first_gap_va.is_none() {
+ first_gap_va = Some(va);
+ }
+ decode_gaps += 1;
va = va.wrapping_add(1);
continue;
}
@@ -56,7 +72,11 @@ pub fn disassemble_range_opts(
if out.is_empty() {
return Err(Error::Decode(format!("no instructions at {start:#x}")));
}
- Ok(out)
+ Ok(DisasmRangeResult {
+ insns: out,
+ decode_gaps,
+ first_gap_va,
+ })
}
#[cfg(test)]
@@ -101,7 +121,13 @@ mod tests {
executable: true,
});
let listing = disassemble_range_opts(&prog, 0x1000, 8, true).unwrap();
- assert!(listing.iter().any(|i| i.mnemonic == "xor"), "{listing:?}");
- assert!(listing.iter().any(|i| i.mnemonic == "ret"));
+ assert!(listing.decode_gaps >= 1);
+ assert_eq!(listing.first_gap_va, Some(0x1000));
+ assert!(
+ listing.insns.iter().any(|i| i.mnemonic == "xor"),
+ "{:?}",
+ listing.insns
+ );
+ assert!(listing.insns.iter().any(|i| i.mnemonic == "ret"));
}
}
diff --git a/crates/ghidrust-core/src/inventory.rs b/crates/ghidrust-core/src/inventory.rs
new file mode 100644
index 0000000..72f7517
--- /dev/null
+++ b/crates/ghidrust-core/src/inventory.rs
@@ -0,0 +1,362 @@
+//! Generic PE install inventory: VERSIONINFO + exe/dll catalog (hand-rolled).
+
+use crate::error::{Error, Result};
+use crate::pe;
+use serde::{Deserialize, Serialize};
+use std::fs;
+use std::path::Path;
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+pub struct VersionInfo {
+ pub file_version: Option<String>,
+ pub product_version: Option<String>,
+ pub product_name: Option<String>,
+ pub file_description: Option<String>,
+ pub company_name: Option<String>,
+ pub original_filename: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PeInventoryEntry {
+ pub path: String,
+ pub size: u64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sha256: Option<String>,
+ #[serde(default)]
+ pub version: VersionInfo,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PeInventory {
+ pub schema_version: u32,
+ pub root: String,
+ pub entries: Vec<PeInventoryEntry>,
+ pub notes: Vec<String>,
+}
+
+pub const PE_INVENTORY_SCHEMA: u32 = 1;
+
+/// Parse VS_VERSION_INFO string-file-info from PE bytes (best-effort).
+pub fn parse_version_info(data: &[u8]) -> VersionInfo {
+ let mut info = VersionInfo::default();
+ if !pe::is_pe(data) {
+ return info;
+ }
+ // Locate UTF-16LE "VS_VERSION_INFO"
+ let needle = wide("VS_VERSION_INFO");
+ let Some(pos) = find_bytes(data, &needle) else {
+ return info;
+ };
+ // Search a window after the marker for StringFileInfo key/value pairs.
+ let window_end = (pos + 0x4000).min(data.len());
+ let window = &data[pos..window_end];
+ info.file_version = find_version_string(window, "FileVersion");
+ info.product_version = find_version_string(window, "ProductVersion");
+ info.product_name = find_version_string(window, "ProductName");
+ info.file_description = find_version_string(window, "FileDescription");
+ info.company_name = find_version_string(window, "CompanyName");
+ info.original_filename = find_version_string(window, "OriginalFilename");
+ info
+}
+
+/// Read VERSIONINFO from a PE path.
+pub fn version_info_path(path: impl AsRef<Path>) -> Result<VersionInfo> {
+ let data = fs::read(path.as_ref()).map_err(|e| Error::Io(e.to_string()))?;
+ Ok(parse_version_info(&data))
+}
+
+fn wide(s: &str) -> Vec<u8> {
+ let mut out = Vec::with_capacity(s.len() * 2);
+ for c in s.encode_utf16() {
+ out.extend_from_slice(&c.to_le_bytes());
+ }
+ out
+}
+
+fn find_bytes(hay: &[u8], needle: &[u8]) -> Option<usize> {
+ if needle.is_empty() || hay.len() < needle.len() {
+ return None;
+ }
+ hay.windows(needle.len()).position(|w| w == needle)
+}
+
+fn find_version_string(window: &[u8], key: &str) -> Option<String> {
+ let key_w = wide(key);
+ let mut search_from = 0;
+ while let Some(rel) = find_bytes(&window[search_from..], &key_w) {
+ let abs = search_from + rel;
+ // Value typically follows key + NUL + padding to DWORD, as UTF-16LE.
+ let after_key = abs + key_w.len();
+ // Skip UTF-16 NUL
+ let mut p = after_key;
+ if p + 2 <= window.len() && window[p] == 0 && window[p + 1] == 0 {
+ p += 2;
+ }
+ // Align to 4
+ while p % 4 != 0 && p < window.len() {
+ p += 1;
+ }
+ if let Some(val) = read_utf16_z(window, p) {
+ if !val.is_empty() && val.len() < 512 {
+ return Some(val);
+ }
+ }
+ search_from = abs + 2;
+ }
+ None
+}
+
+fn read_utf16_z(data: &[u8], off: usize) -> Option<String> {
+ if off >= data.len() {
+ return None;
+ }
+ let mut units = Vec::new();
+ let mut i = off;
+ while i + 1 < data.len() {
+ let u = u16::from_le_bytes([data[i], data[i + 1]]);
+ i += 2;
+ if u == 0 {
+ break;
+ }
+ if units.len() > 512 {
+ return None;
+ }
+ units.push(u);
+ }
+ if units.is_empty() {
+ return None;
+ }
+ String::from_utf16(&units).ok()
+}
+
+fn is_pe_name(path: &Path) -> bool {
+ path.extension()
+ .and_then(|e| e.to_str())
+ .map(|e| {
+ let el = e.to_ascii_lowercase();
+ el == "exe" || el == "dll" || el == "sys" || el == "scr"
+ })
+ .unwrap_or(false)
+}
+
+/// Walk `root` for exe/dll (and friends); attach VERSIONINFO when parseable.
+/// Optional `hash` computes sha256 (slow on large trees — off by default).
+pub fn inventory_pe_dir(
+ root: impl AsRef<Path>,
+ max_depth: usize,
+ with_hash: bool,
+) -> Result<PeInventory> {
+ let root = root.as_ref();
+ if !root.is_dir() {
+ return Err(Error::Io(format!("not a directory: {}", root.display())));
+ }
+ let mut entries = Vec::new();
+ let mut notes = Vec::new();
+ walk_pe(root, root, 0, max_depth, with_hash, &mut entries, &mut notes);
+ entries.sort_by(|a, b| a.path.cmp(&b.path));
+ Ok(PeInventory {
+ schema_version: PE_INVENTORY_SCHEMA,
+ root: root.display().to_string(),
+ entries,
+ notes,
+ })
+}
+
+fn walk_pe(
+ root: &Path,
+ dir: &Path,
+ depth: usize,
+ max_depth: usize,
+ with_hash: bool,
+ out: &mut Vec<PeInventoryEntry>,
+ notes: &mut Vec<String>,
+) {
+ if depth > max_depth {
+ return;
+ }
+ let rd = match fs::read_dir(dir) {
+ Ok(rd) => rd,
+ Err(e) => {
+ notes.push(format!("skip {}: {e}", dir.display()));
+ return;
+ }
+ };
+ for ent in rd.flatten() {
+ let path = ent.path();
+ let meta = match ent.metadata() {
+ Ok(m) => m,
+ Err(e) => {
+ notes.push(format!("stat {}: {e}", path.display()));
+ continue;
+ }
+ };
+ if meta.file_type().is_symlink() {
+ continue;
+ }
+ if meta.is_dir() {
+ walk_pe(root, &path, depth + 1, max_depth, with_hash, out, notes);
+ continue;
+ }
+ if !is_pe_name(&path) {
+ continue;
+ }
+ let size = meta.len();
+ let mut version = VersionInfo::default();
+ let mut error = None;
+ let mut sha256 = None;
+ match fs::read(&path) {
+ Ok(data) => {
+ if pe::is_pe(&data) {
+ version = parse_version_info(&data);
+ if with_hash {
+ sha256 = Some(simple_sha256_hex(&data));
+ }
+ } else {
+ error = Some("not_pe".into());
+ }
+ }
+ Err(e) => error = Some(format!("io:{e}")),
+ }
+ out.push(PeInventoryEntry {
+ path: path.display().to_string(),
+ size,
+ sha256,
+ version,
+ error,
+ });
+ }
+}
+
+/// Minimal FNV-independent hex digest without extra crates — use std only via a tiny hasher.
+/// Prefer real sha2 when available from callers; here we ship a hand-rolled SHA-256.
+fn simple_sha256_hex(data: &[u8]) -> String {
+ sha256_hex(data)
+}
+
+// --- Hand-rolled SHA-256 (no external crate) ---
+
+fn sha256_hex(data: &[u8]) -> String {
+ let dig = sha256(data);
+ let mut s = String::with_capacity(64);
+ for b in dig {
+ s.push_str(&format!("{b:02x}"));
+ }
+ s
+}
+
+fn sha256(msg: &[u8]) -> [u8; 32] {
+ // Standard SHA-256
+ let mut h: [u32; 8] = [
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
+ 0x5be0cd19,
+ ];
+ const K: [u32; 64] = [
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
+ 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
+ 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
+ 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
+ 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
+ 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
+ 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
+ 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
+ 0xc67178f2,
+ ];
+ let bit_len = (msg.len() as u64).saturating_mul(8);
+ let mut buf = msg.to_vec();
+ buf.push(0x80);
+ while (buf.len() % 64) != 56 {
+ buf.push(0);
+ }
+ buf.extend_from_slice(&bit_len.to_be_bytes());
+ for chunk in buf.chunks_exact(64) {
+ let mut w = [0u32; 64];
+ for i in 0..16 {
+ w[i] = u32::from_be_bytes([
+ chunk[i * 4],
+ chunk[i * 4 + 1],
+ chunk[i * 4 + 2],
+ chunk[i * 4 + 3],
+ ]);
+ }
+ for i in 16..64 {
+ let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
+ let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
+ w[i] = w[i - 16]
+ .wrapping_add(s0)
+ .wrapping_add(w[i - 7])
+ .wrapping_add(s1);
+ }
+ let (mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh) =
+ (h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]);
+ for i in 0..64 {
+ let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
+ let ch = (e & f) ^ ((!e) & g);
+ let t1 = hh
+ .wrapping_add(s1)
+ .wrapping_add(ch)
+ .wrapping_add(K[i])
+ .wrapping_add(w[i]);
+ let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
+ let maj = (a & b) ^ (a & c) ^ (b & c);
+ let t2 = s0.wrapping_add(maj);
+ hh = g;
+ g = f;
+ f = e;
+ e = d.wrapping_add(t1);
+ d = c;
+ c = b;
+ b = a;
+ a = t1.wrapping_add(t2);
+ }
+ h[0] = h[0].wrapping_add(a);
+ h[1] = h[1].wrapping_add(b);
+ h[2] = h[2].wrapping_add(c);
+ h[3] = h[3].wrapping_add(d);
+ h[4] = h[4].wrapping_add(e);
+ h[5] = h[5].wrapping_add(f);
+ h[6] = h[6].wrapping_add(g);
+ h[7] = h[7].wrapping_add(hh);
+ }
+ let mut out = [0u8; 32];
+ for (i, v) in h.iter().enumerate() {
+ out[i * 4..i * 4 + 4].copy_from_slice(&v.to_be_bytes());
+ }
+ out
+}
+
+/// Helper for Unity inventory: VERSIONINFO for a single path (best-effort).
+pub fn version_info_for_file(path: &Path) -> VersionInfo {
+ version_info_path(path).unwrap_or_default()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::fixture_path;
+
+ #[test]
+ fn version_info_on_fixture_does_not_panic() {
+ let path = fixture_path("tiny_x64.pe");
+ let _ = version_info_path(&path).unwrap();
+ }
+
+ #[test]
+ fn inventory_finds_pe_in_dir() {
+ let dir = std::env::temp_dir().join(format!(
+ "ghidrust-inv-{}",
+ std::process::id()
+ ));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ let pe = fixture_path("tiny_x64.pe");
+ let dest = dir.join("tiny.exe");
+ fs::copy(&pe, &dest).unwrap();
+ let inv = inventory_pe_dir(&dir, 2, false).unwrap();
+ assert_eq!(inv.entries.len(), 1);
+ assert!(inv.entries[0].path.ends_with("tiny.exe"));
+ let _ = fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/ghidrust-core/src/lib.rs b/crates/ghidrust-core/src/lib.rs
index 78199f7..267036d 100644
--- a/crates/ghidrust-core/src/lib.rs
+++ b/crates/ghidrust-core/src/lib.rs
@@ -1,6 +1,7 @@
//! Ghidrust analysis core — program model, PE/ELF, x86-64, RTTI, analyzer registry.
pub mod analyzers;
+pub mod artifacts;
pub mod bulk_scan;
pub mod edits;
pub mod gpu_analyzers;
@@ -8,12 +9,18 @@ pub mod disasm;
pub mod elf;
pub mod error;
pub mod imports;
+pub mod inventory;
pub mod io_util;
pub mod pe;
+pub mod process;
pub mod program;
pub mod project;
+pub mod resolve;
pub mod rtti;
+pub mod rtti_catalog;
+pub mod section_notes;
pub mod theme;
+pub mod tree_index;
pub mod xrefs;
pub use analyzers::{
@@ -35,11 +42,32 @@ pub use gpu_analyzers::{
merge_seeds_into_program, pad_large, seeds_equal, strategy_matrix, AnalyzerBenchRow,
GpuStrategyClass,
};
+pub use artifacts::{
+ artifact_get, artifact_query, envelope_or_spill, list_artifacts, spill_artifact,
+ ArtifactEnvelope, ArtifactMeta, DEFAULT_PREVIEW_LIMIT,
+};
pub use disasm::{
- decode_one, disassemble_at, disassemble_range, disassemble_range_opts, Instruction,
+ decode_one, disassemble_at, disassemble_range, disassemble_range_opts, DisasmRangeResult,
+ Instruction,
};
pub use imports::{filter_imports, load_imports, parse_pe_imports};
+pub use inventory::{
+ inventory_pe_dir, parse_version_info, version_info_for_file, version_info_path, PeInventory,
+ PeInventoryEntry, VersionInfo, PE_INVENTORY_SCHEMA,
+};
pub use io_util::{sanitize_path_component, sanitized_out_name, write_json_no_bom};
+pub use process::{
+ process_attach, process_detach, process_list, process_modules, process_read, process_regions,
+ process_resolve, static_to_live, ModuleInfo, ProcessInfo, ProcessSession, ReadResult,
+ RegionInfo, ResolveLive,
+};
+pub use resolve::{resolve_function, resolve_result_json, ResolveResult, ResolveStatus};
+pub use rtti_catalog::{
+ clear_rtti_cache, enrich_class, rtti_catalog, rtti_query, RttiCatalogEntry, RttiMatchMode,
+ RttiQueryResult,
+};
+pub use section_notes::{section_notes_for, SectionNote};
+pub use tree_index::{list_tree, TreeEntry, TreeListOpts, TreeListResult};
pub use edits::{
CommentKind, EquateEdit, FunctionSignatureEdit, ProgramEditTotals, ProgramEdits, RetypeEdit,
BUILTIN_TYPES,
@@ -59,7 +87,7 @@ pub use rtti::{recover_rtti, RttiClass, RttiReport};
pub use theme::{m3_tokens, ThemeMode, M3Tokens};
pub use xrefs::{
instruction_targets, operand_addresses, rip_relative_targets, xrefs_from, xrefs_to,
- xrefs_to_import, xrefs_to_string_filter, XRef,
+ xrefs_to_import, xrefs_to_string_filter, xrefs_to_string_filter_opts, XRef,
};
use std::path::{Path, PathBuf};
diff --git a/crates/ghidrust-core/src/process.rs b/crates/ghidrust-core/src/process.rs
new file mode 100644
index 0000000..4f676f9
--- /dev/null
+++ b/crates/ghidrust-core/src/process.rs
@@ -0,0 +1,545 @@
+//! Live Process Bridge (Windows) — hand-rolled Win32 FFI.
+//!
+//! MVP: list / attach / modules / read / resolve / regions. No write or breakpoints.
+
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::sync::Mutex;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ProcessInfo {
+ pub pid: u32,
+ pub name: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub path: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ModuleInfo {
+ pub name: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub path: Option<String>,
+ pub base: u64,
+ pub size: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RegionInfo {
+ pub base: u64,
+ pub size: u64,
+ pub protect: String,
+ pub state: String,
+ pub typ: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ProcessSession {
+ pub session_id: String,
+ pub pid: u32,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ReadResult {
+ pub va: u64,
+ pub size_requested: usize,
+ pub bytes_read: usize,
+ pub hex: String,
+ pub bytes: Vec<u8>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub as_u64: Option<Vec<u64>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub as_f32: Option<Vec<f32>>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ResolveLive {
+ pub module: String,
+ pub rva: u64,
+ pub base: u64,
+ pub live_va: u64,
+}
+
+struct Attached {
+ pid: u32,
+ #[cfg(windows)]
+ handle: isize,
+}
+
+static SESSIONS: Mutex<Option<HashMap<String, Attached>>> = Mutex::new(None);
+
+fn with_sessions<F, R>(f: F) -> R
+where
+ F: FnOnce(&mut HashMap<String, Attached>) -> R,
+{
+ let mut guard = SESSIONS.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.is_none() {
+ *guard = Some(HashMap::new());
+ }
+ f(guard.as_mut().unwrap())
+}
+
+#[cfg(windows)]
+mod win {
+ use super::*;
+ use std::ffi::OsString;
+ use std::mem::{size_of, zeroed};
+ use std::os::windows::ffi::OsStringExt;
+ use std::ptr;
+
+ type HANDLE = isize;
+ type BOOL = i32;
+ type DWORD = u32;
+ type SizeT = usize;
+
+ const PROCESS_QUERY_INFORMATION: DWORD = 0x0400;
+ const PROCESS_VM_READ: DWORD = 0x0010;
+ const PROCESS_QUERY_LIMITED_INFORMATION: DWORD = 0x1000;
+ const TH32CS_SNAPPROCESS: DWORD = 0x0000_0002;
+ const TH32CS_SNAPMODULE: DWORD = 0x0000_0008;
+ const TH32CS_SNAPMODULE32: DWORD = 0x0000_0010;
+ const INVALID_HANDLE_VALUE: HANDLE = -1;
+ const MEM_COMMIT: DWORD = 0x1000;
+ const MEM_FREE: DWORD = 0x10000;
+ const MEM_RESERVE: DWORD = 0x2000;
+ const MAX_PATH: usize = 260;
+
+ #[repr(C)]
+ struct PROCESSENTRY32W {
+ dw_size: DWORD,
+ cnt_usage: DWORD,
+ th32_process_id: DWORD,
+ th32_default_heap_id: usize,
+ th32_module_id: DWORD,
+ cnt_threads: DWORD,
+ th32_parent_process_id: DWORD,
+ pc_pri_class_base: i32,
+ dw_flags: DWORD,
+ sz_exe_file: [u16; MAX_PATH],
+ }
+
+ #[repr(C)]
+ struct MODULEENTRY32W {
+ dw_size: DWORD,
+ th32_module_id: DWORD,
+ th32_process_id: DWORD,
+ glblcnt_usage: DWORD,
+ proccnt_usage: DWORD,
+ mod_base_addr: *mut u8,
+ mod_base_size: DWORD,
+ h_module: HANDLE,
+ sz_module: [u16; 256],
+ sz_exe_path: [u16; MAX_PATH],
+ }
+
+ #[repr(C)]
+ struct MEMORY_BASIC_INFORMATION {
+ base_address: *mut u8,
+ allocation_base: *mut u8,
+ allocation_protect: DWORD,
+ region_size: SizeT,
+ state: DWORD,
+ protect: DWORD,
+ typ: DWORD,
+ }
+
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn OpenProcess(access: DWORD, inherit: BOOL, pid: DWORD) -> HANDLE;
+ fn CloseHandle(h: HANDLE) -> BOOL;
+ fn ReadProcessMemory(
+ h: HANDLE,
+ addr: *const u8,
+ buf: *mut u8,
+ size: SizeT,
+ read: *mut SizeT,
+ ) -> BOOL;
+ fn VirtualQueryEx(
+ h: HANDLE,
+ addr: *const u8,
+ info: *mut MEMORY_BASIC_INFORMATION,
+ len: SizeT,
+ ) -> SizeT;
+ fn CreateToolhelp32Snapshot(flags: DWORD, pid: DWORD) -> HANDLE;
+ fn Process32FirstW(snap: HANDLE, pe: *mut PROCESSENTRY32W) -> BOOL;
+ fn Process32NextW(snap: HANDLE, pe: *mut PROCESSENTRY32W) -> BOOL;
+ fn Module32FirstW(snap: HANDLE, me: *mut MODULEENTRY32W) -> BOOL;
+ fn Module32NextW(snap: HANDLE, me: *mut MODULEENTRY32W) -> BOOL;
+ fn QueryFullProcessImageNameW(
+ h: HANDLE,
+ flags: DWORD,
+ buf: *mut u16,
+ size: *mut DWORD,
+ ) -> BOOL;
+ }
+
+ fn wide_to_string(w: &[u16]) -> String {
+ let len = w.iter().position(|&c| c == 0).unwrap_or(w.len());
+ OsString::from_wide(&w[..len])
+ .to_string_lossy()
+ .into_owned()
+ }
+
+ pub fn list_processes() -> Result<Vec<ProcessInfo>, String> {
+ let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
+ if snap == 0 || snap == INVALID_HANDLE_VALUE {
+ return Err("CreateToolhelp32Snapshot failed".into());
+ }
+ let mut out = Vec::new();
+ let mut pe: PROCESSENTRY32W = unsafe { zeroed() };
+ pe.dw_size = size_of::<PROCESSENTRY32W>() as DWORD;
+ let mut ok = unsafe { Process32FirstW(snap, &mut pe) };
+ while ok != 0 {
+ let name = wide_to_string(&pe.sz_exe_file);
+ let pid = pe.th32_process_id;
+ let path = open_query_path(pid);
+ out.push(ProcessInfo { pid, name, path });
+ ok = unsafe { Process32NextW(snap, &mut pe) };
+ }
+ unsafe {
+ CloseHandle(snap);
+ }
+ out.sort_by(|a, b| a.name.to_ascii_lowercase().cmp(&b.name.to_ascii_lowercase()));
+ Ok(out)
+ }
+
+ fn open_query_path(pid: u32) -> Option<String> {
+ let h = unsafe {
+ OpenProcess(
+ PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_QUERY_INFORMATION,
+ 0,
+ pid,
+ )
+ };
+ if h == 0 {
+ return None;
+ }
+ let mut buf = [0u16; 1024];
+ let mut size = buf.len() as DWORD;
+ let ok = unsafe { QueryFullProcessImageNameW(h, 0, buf.as_mut_ptr(), &mut size) };
+ unsafe {
+ CloseHandle(h);
+ }
+ if ok == 0 {
+ return None;
+ }
+ Some(wide_to_string(&buf[..size as usize]))
+ }
+
+ pub fn attach(pid: u32) -> Result<(String, HANDLE), String> {
+ let access = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_QUERY_LIMITED_INFORMATION;
+ let h = unsafe { OpenProcess(access, 0, pid) };
+ if h == 0 {
+ return Err(format!(
+ "OpenProcess({pid}) failed — access denied, elevated rights, or process exited"
+ ));
+ }
+ let session_id = format!("ps-{pid}-{}", super::now_token());
+ Ok((session_id, h))
+ }
+
+ pub fn modules(_handle: HANDLE, pid: u32) -> Result<Vec<ModuleInfo>, String> {
+ let flags = TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32;
+ let snap = unsafe { CreateToolhelp32Snapshot(flags, pid) };
+ if snap == 0 || snap == INVALID_HANDLE_VALUE {
+ return Err(
+ "Module snapshot failed (32-bit tool vs 64-bit process, or access denied)".into(),
+ );
+ }
+ let mut out = Vec::new();
+ let mut me: MODULEENTRY32W = unsafe { zeroed() };
+ me.dw_size = size_of::<MODULEENTRY32W>() as DWORD;
+ let mut ok = unsafe { Module32FirstW(snap, &mut me) };
+ while ok != 0 {
+ let name = wide_to_string(&me.sz_module);
+ let path = {
+ let p = wide_to_string(&me.sz_exe_path);
+ if p.is_empty() {
+ None
+ } else {
+ Some(p)
+ }
+ };
+ out.push(ModuleInfo {
+ name,
+ path,
+ base: me.mod_base_addr as u64,
+ size: me.mod_base_size as u64,
+ });
+ ok = unsafe { Module32NextW(snap, &mut me) };
+ }
+ unsafe {
+ CloseHandle(snap);
+ }
+ Ok(out)
+ }
+
+ pub fn read_mem(handle: HANDLE, va: u64, size: usize) -> ReadResult {
+ let size = size.min(1024 * 1024); // 1 MiB cap
+ let mut buf = vec![0u8; size];
+ let mut read: SizeT = 0;
+ let ok = unsafe {
+ ReadProcessMemory(
+ handle,
+ va as *const u8,
+ buf.as_mut_ptr(),
+ size,
+ &mut read,
+ )
+ };
+ if ok == 0 {
+ return ReadResult {
+ va,
+ size_requested: size,
+ bytes_read: 0,
+ hex: String::new(),
+ bytes: vec![],
+ error: Some("ReadProcessMemory failed (access denied or unmapped)".into()),
+ as_u64: None,
+ as_f32: None,
+ };
+ }
+ buf.truncate(read);
+ let hex: String = buf.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join(" ");
+ let as_u64 = if buf.len() >= 8 {
+ Some(
+ buf.chunks_exact(8)
+ .map(|c| u64::from_le_bytes(c.try_into().unwrap()))
+ .collect(),
+ )
+ } else {
+ None
+ };
+ let as_f32 = if buf.len() >= 4 {
+ Some(
+ buf.chunks_exact(4)
+ .map(|c| f32::from_le_bytes(c.try_into().unwrap()))
+ .collect(),
+ )
+ } else {
+ None
+ };
+ let error = if read < size {
+ Some(format!("short_read: got {read} of {size}"))
+ } else {
+ None
+ };
+ ReadResult {
+ va,
+ size_requested: size,
+ bytes_read: read,
+ hex,
+ bytes: buf,
+ error,
+ as_u64,
+ as_f32,
+ }
+ }
+
+ pub fn regions(handle: HANDLE, max: usize) -> Result<Vec<RegionInfo>, String> {
+ let mut out = Vec::new();
+ let mut addr: u64 = 0;
+ while out.len() < max {
+ let mut info: MEMORY_BASIC_INFORMATION = unsafe { zeroed() };
+ let n = unsafe {
+ VirtualQueryEx(
+ handle,
+ addr as *const u8,
+ &mut info,
+ size_of::<MEMORY_BASIC_INFORMATION>(),
+ )
+ };
+ if n == 0 {
+ break;
+ }
+ let base = info.base_address as u64;
+ let size = info.region_size as u64;
+ if info.state != MEM_FREE {
+ out.push(RegionInfo {
+ base,
+ size,
+ protect: protect_str(info.protect),
+ state: state_str(info.state),
+ typ: type_str(info.typ),
+ });
+ }
+ let next = base.saturating_add(size);
+ if next <= addr {
+ break;
+ }
+ addr = next;
+ }
+ Ok(out)
+ }
+
+ fn protect_str(p: DWORD) -> String {
+ format!("{p:#x}")
+ }
+ fn state_str(s: DWORD) -> String {
+ match s {
+ MEM_COMMIT => "commit".into(),
+ MEM_RESERVE => "reserve".into(),
+ MEM_FREE => "free".into(),
+ _ => format!("{s:#x}"),
+ }
+ }
+ fn type_str(t: DWORD) -> String {
+ format!("{t:#x}")
+ }
+
+ pub fn close(h: HANDLE) {
+ unsafe {
+ let _ = CloseHandle(h);
+ }
+ }
+
+ // silence unused import warning on ptr
+ #[allow(dead_code)]
+ fn _touch() {
+ let _ = ptr::null::<u8>();
+ }
+}
+
+fn now_token() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
+
+/// List processes (Windows). Other platforms return a clear error.
+pub fn process_list() -> Result<Vec<ProcessInfo>, String> {
+ #[cfg(windows)]
+ {
+ win::list_processes()
+ }
+ #[cfg(not(windows))]
+ {
+ Err("Live Process Bridge is Windows-only in this MVP".into())
+ }
+}
+
+pub fn process_attach(pid: u32) -> Result<ProcessSession, String> {
+ #[cfg(windows)]
+ {
+ let (session_id, handle) = win::attach(pid)?;
+ with_sessions(|m| {
+ m.insert(
+ session_id.clone(),
+ Attached {
+ pid,
+ handle,
+ },
+ );
+ });
+ Ok(ProcessSession { session_id, pid })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = pid;
+ Err("Live Process Bridge is Windows-only in this MVP".into())
+ }
+}
+
+pub fn process_detach(session_id: &str) -> Result<(), String> {
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ if let Some(a) = m.remove(session_id) {
+ win::close(a.handle);
+ Ok(())
+ } else {
+ Err(format!("unknown session: {session_id}"))
+ }
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = session_id;
+ Err("Live Process Bridge is Windows-only in this MVP".into())
+ }
+}
+
+fn session_handle(session_id: &str) -> Result<(u32, isize), String> {
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ m.get(session_id)
+ .map(|a| (a.pid, a.handle))
+ .ok_or_else(|| format!("unknown or stale session: {session_id}"))
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = session_id;
+ Err("Live Process Bridge is Windows-only in this MVP".into())
+ }
+}
+
+pub fn process_modules(session_id: &str) -> Result<Vec<ModuleInfo>, String> {
+ #[cfg(windows)]
+ {
+ let (pid, handle) = session_handle(session_id)?;
+ win::modules(handle, pid)
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = session_id;
+ Err("Live Process Bridge is Windows-only in this MVP".into())
+ }
+}
+
+pub fn process_read(session_id: &str, va: u64, size: usize) -> Result<ReadResult, String> {
+ #[cfg(windows)]
+ {
+ let (_pid, handle) = session_handle(session_id)?;
+ Ok(win::read_mem(handle, va, size))
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (session_id, va, size);
+ Err("Live Process Bridge is Windows-only in this MVP".into())
+ }
+}
+
+pub fn process_regions(session_id: &str, max: usize) -> Result<Vec<RegionInfo>, String> {
+ #[cfg(windows)]
+ {
+ let (_pid, handle) = session_handle(session_id)?;
+ win::regions(handle, max.max(1))
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (session_id, max);
+ Err("Live Process Bridge is Windows-only in this MVP".into())
+ }
+}
+
+/// Resolve static RVA to live VA via module base (`base + rva`).
+pub fn process_resolve(
+ session_id: &str,
+ module: &str,
+ rva: u64,
+) -> Result<ResolveLive, String> {
+ let mods = process_modules(session_id)?;
+ let m = mods
+ .iter()
+ .find(|m| m.name.eq_ignore_ascii_case(module)
+ || m.path
+ .as_deref()
+ .map(|p| p.to_ascii_lowercase().ends_with(&module.to_ascii_lowercase()))
+ .unwrap_or(false))
+ .ok_or_else(|| format!("module not found: {module}"))?;
+ Ok(ResolveLive {
+ module: m.name.clone(),
+ rva,
+ base: m.base,
+ live_va: m.base.wrapping_add(rva),
+ })
+}
+
+/// Alias: static file RVA → live VA.
+pub fn static_to_live(session_id: &str, module: &str, rva: u64) -> Result<ResolveLive, String> {
+ process_resolve(session_id, module, rva)
+}
diff --git a/crates/ghidrust-core/src/resolve.rs b/crates/ghidrust-core/src/resolve.rs
new file mode 100644
index 0000000..f3d1171
--- /dev/null
+++ b/crates/ghidrust-core/src/resolve.rs
@@ -0,0 +1,241 @@
+//! Address → Function resolution (containing-function layer).
+//!
+//! Shared by CLI, MCP, GPU decompile, and GUI. Never invents a 1-insn function
+//! at a mid-body hit; returns honest `no_containing_function` instead.
+
+use crate::analyzers::run_analyzers;
+use crate::error::Result;
+use crate::program::{FunctionInfo, Program};
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ResolveStatus {
+ ExactEntry,
+ Containing,
+ Ambiguous,
+ NoContainingFunction,
+ NotExecutable,
+ Unmapped,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ResolveResult {
+ pub ok: bool,
+ pub resolve_status: ResolveStatus,
+ pub requested_addr: u64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub resolved_entry: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub function_name: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub function_end: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub offset_in_function: Option<u64>,
+ #[serde(default)]
+ pub ambiguous: bool,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub candidates: Vec<ResolveCandidate>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub reason: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ResolveCandidate {
+ pub entry: u64,
+ pub end: u64,
+ pub name: String,
+}
+
+fn fail(addr: u64, status: ResolveStatus, reason: &str) -> ResolveResult {
+ ResolveResult {
+ ok: false,
+ resolve_status: status,
+ requested_addr: addr,
+ resolved_entry: None,
+ function_name: None,
+ function_end: None,
+ offset_in_function: None,
+ ambiguous: false,
+ candidates: vec![],
+ reason: Some(reason.into()),
+ }
+}
+
+fn ok_from(addr: u64, f: &FunctionInfo, status: ResolveStatus, ambiguous: bool, candidates: Vec<ResolveCandidate>) -> ResolveResult {
+ ResolveResult {
+ ok: true,
+ resolve_status: status,
+ requested_addr: addr,
+ resolved_entry: Some(f.entry),
+ function_name: Some(f.name.clone()),
+ function_end: Some(f.end),
+ offset_in_function: Some(addr.saturating_sub(f.entry)),
+ ambiguous,
+ candidates,
+ reason: None,
+ }
+}
+
+/// Resolve `addr` to a function entry. Auto-runs Function Start Search once when empty.
+pub fn resolve_function(prog: &mut Program, addr: u64) -> Result<ResolveResult> {
+ if !prog.contains_va(addr) {
+ return Ok(fail(addr, ResolveStatus::Unmapped, "unmapped"));
+ }
+ let in_exec = prog
+ .blocks
+ .iter()
+ .any(|b| b.executable && addr >= b.va && addr < b.va.saturating_add(b.size));
+ if !in_exec {
+ // Still allow exact function entry hits on non-exec (rare); otherwise honest.
+ if prog.function_at(addr).is_none() {
+ return Ok(fail(addr, ResolveStatus::NotExecutable, "not_executable"));
+ }
+ }
+
+ if prog.analysis.functions.is_empty() {
+ let _ = run_analyzers(prog, &["Function Start Search"])?;
+ }
+
+ if let Some(f) = prog.function_at(addr) {
+ return Ok(ok_from(addr, f, ResolveStatus::ExactEntry, false, vec![]));
+ }
+
+ let covering: Vec<&FunctionInfo> = prog
+ .analysis
+ .functions
+ .iter()
+ .filter(|f| addr >= f.entry && addr < f.end.max(f.entry.saturating_add(1)))
+ .collect();
+
+ if covering.is_empty() {
+ return Ok(fail(
+ addr,
+ ResolveStatus::NoContainingFunction,
+ "no_containing_function",
+ ));
+ }
+
+ // Primary = smallest containing range; tie-break greatest entry.
+ let primary = covering
+ .iter()
+ .copied()
+ .min_by_key(|f| {
+ let span = f.end.saturating_sub(f.entry);
+ (span, u64::MAX - f.entry)
+ })
+ .expect("non-empty");
+
+ let ambiguous = covering.len() > 1;
+ let candidates: Vec<ResolveCandidate> = covering
+ .iter()
+ .map(|f| ResolveCandidate {
+ entry: f.entry,
+ end: f.end,
+ name: f.name.clone(),
+ })
+ .collect();
+
+ let status = if ambiguous {
+ ResolveStatus::Ambiguous
+ } else {
+ ResolveStatus::Containing
+ };
+ Ok(ok_from(addr, primary, status, ambiguous, candidates))
+}
+
+/// JSON-friendly hex fields for agent responses.
+pub fn resolve_result_json(r: &ResolveResult) -> serde_json::Value {
+ serde_json::json!({
+ "ok": r.ok,
+ "resolve_status": r.resolve_status,
+ "requested_addr": format!("{:#x}", r.requested_addr),
+ "resolved_entry": r.resolved_entry.map(|e| format!("{e:#x}")),
+ "function_name": r.function_name,
+ "function_end": r.function_end.map(|e| format!("{e:#x}")),
+ "offset_in_function": r.offset_in_function,
+ "ambiguous": r.ambiguous,
+ "candidates": r.candidates.iter().map(|c| serde_json::json!({
+ "entry": format!("{:#x}", c.entry),
+ "end": format!("{:#x}", c.end),
+ "name": c.name,
+ })).collect::<Vec<_>>(),
+ "reason": r.reason,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::program::{FunctionInfo, MemoryBlock, Program};
+
+ fn prog_with_fn(entry: u64, end: u64) -> Program {
+ let mut prog = Program::new("t".into(), "PE32+");
+ prog.blocks.push(MemoryBlock {
+ name: ".text".into(),
+ va: entry,
+ size: end - entry,
+ bytes: vec![0x90; (end - entry) as usize],
+ readable: true,
+ writable: false,
+ executable: true,
+ });
+ prog.analysis.functions.push(FunctionInfo {
+ entry,
+ end,
+ name: "f".into(),
+ calling_convention: None,
+ noreturn: false,
+ varargs: false,
+ parameters: vec![],
+ stack_locals: vec![],
+ });
+ prog
+ }
+
+ #[test]
+ fn mid_body_resolves_containing() {
+ let mut prog = prog_with_fn(0x1000, 0x1100);
+ let r = resolve_function(&mut prog, 0x1050).unwrap();
+ assert!(r.ok);
+ assert_eq!(r.resolved_entry, Some(0x1000));
+ assert_eq!(r.offset_in_function, Some(0x50));
+ assert_eq!(r.resolve_status, ResolveStatus::Containing);
+ }
+
+ #[test]
+ fn unmapped_is_honest() {
+ let mut prog = prog_with_fn(0x1000, 0x1100);
+ let r = resolve_function(&mut prog, 0x9999).unwrap();
+ assert!(!r.ok);
+ assert_eq!(r.resolve_status, ResolveStatus::Unmapped);
+ }
+
+ #[test]
+ fn no_fn_honest() {
+ let mut prog = Program::new("t".into(), "PE32+");
+ prog.blocks.push(MemoryBlock {
+ name: ".text".into(),
+ va: 0x1000,
+ size: 0x100,
+ bytes: vec![0x90; 0x100],
+ readable: true,
+ writable: false,
+ executable: true,
+ });
+ // Non-empty functions list so we don't auto-run FSS on empty image heuristics.
+ prog.analysis.functions.push(FunctionInfo {
+ entry: 0x2000,
+ end: 0x2100,
+ name: "elsewhere".into(),
+ calling_convention: None,
+ noreturn: false,
+ varargs: false,
+ parameters: vec![],
+ stack_locals: vec![],
+ });
+ let r = resolve_function(&mut prog, 0x1050).unwrap();
+ assert!(!r.ok);
+ assert_eq!(r.resolve_status, ResolveStatus::NoContainingFunction);
+ }
+}
diff --git a/crates/ghidrust-core/src/rtti_catalog.rs b/crates/ghidrust-core/src/rtti_catalog.rs
new file mode 100644
index 0000000..31906c6
--- /dev/null
+++ b/crates/ghidrust-core/src/rtti_catalog.rs
@@ -0,0 +1,266 @@
+//! RTTI Catalog API — filter/exact query, multi-vtable honesty, program-scoped cache.
+
+use crate::error::Result;
+use crate::program::Program;
+use crate::rtti::{recover_rtti, RttiClass, RttiReport};
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::sync::Mutex;
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct RttiCatalogEntry {
+ pub name: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mangled: Option<String>,
+ pub type_info_va: Option<u64>,
+ pub col_va: Option<u64>,
+ /// All recovered vtable VAs (MI / multiple COL). Empty when incomplete.
+ pub vtable_vas: Vec<u64>,
+ /// Backward-compat single VA (= first of vtable_vas when present).
+ pub vtable_va: Option<u64>,
+ pub confidence: String,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub notes: Vec<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub reason: Option<String>,
+ pub kind: String,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum RttiMatchMode {
+ Substr,
+ Token,
+ Whole,
+ Glob,
+ Exact,
+}
+
+impl RttiMatchMode {
+ pub fn parse(s: &str) -> Self {
+ match s.to_ascii_lowercase().as_str() {
+ "token" => Self::Token,
+ "whole" => Self::Whole,
+ "glob" => Self::Glob,
+ "exact" => Self::Exact,
+ _ => Self::Substr,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RttiQueryResult {
+ pub entry_count: usize,
+ pub classes: Vec<RttiCatalogEntry>,
+ pub cache_hit: bool,
+ pub notes: Vec<String>,
+}
+
+#[derive(Clone)]
+struct CacheEntry {
+ identity: String,
+ report: RttiReport,
+}
+
+static CACHE: Mutex<Option<CacheEntry>> = Mutex::new(None);
+
+fn program_identity(prog: &Program) -> String {
+ format!(
+ "{}|{:#x}|{}|{}",
+ prog.name,
+ prog.image_base,
+ prog.file_bytes.len(),
+ prog.sections.len()
+ )
+}
+
+/// Convert recovered report into catalog entries (multi-vtable via grouping).
+pub fn catalog_from_report(report: &RttiReport) -> Vec<RttiCatalogEntry> {
+ // Group by demangled name; collect all vtables/COLs.
+ let mut by_name: HashMap<String, RttiCatalogEntry> = HashMap::new();
+ for c in &report.classes {
+ let e = by_name.entry(c.name.clone()).or_insert_with(|| RttiCatalogEntry {
+ name: c.name.clone(),
+ mangled: None,
+ type_info_va: c.type_info_va,
+ col_va: c.col_va,
+ vtable_vas: vec![],
+ vtable_va: None,
+ confidence: "medium".into(),
+ notes: vec![],
+ reason: None,
+ kind: c.kind.clone(),
+ });
+ if e.type_info_va.is_none() {
+ e.type_info_va = c.type_info_va;
+ }
+ if e.col_va.is_none() {
+ e.col_va = c.col_va;
+ }
+ if let Some(v) = c.vtable_va {
+ if !e.vtable_vas.contains(&v) {
+ e.vtable_vas.push(v);
+ }
+ }
+ if c.kind.contains("col") {
+ e.kind = c.kind.clone();
+ }
+ }
+ let mut out: Vec<_> = by_name.into_values().collect();
+ for e in &mut out {
+ e.vtable_va = e.vtable_vas.first().copied();
+ if e.vtable_vas.is_empty() {
+ e.reason = Some("col_incomplete_or_no_vtable_link".into());
+ e.confidence = "low".into();
+ e.notes
+ .push("vtable_vas empty — COL incomplete or link failed (not inventing RVA)".into());
+ } else if e.vtable_vas.len() > 1 {
+ e.notes.push(format!(
+ "multiple vtables ({}) — MI / multiple COL; do not assume single VA",
+ e.vtable_vas.len()
+ ));
+ e.confidence = "medium".into();
+ } else {
+ e.confidence = "high".into();
+ }
+ }
+ out.sort_by(|a, b| a.name.cmp(&b.name));
+ out
+}
+
+fn matches(name: &str, needle: &str, mode: RttiMatchMode) -> bool {
+ let n = name.to_ascii_lowercase();
+ let q = needle.to_ascii_lowercase();
+ match mode {
+ RttiMatchMode::Exact | RttiMatchMode::Whole => n == q,
+ RttiMatchMode::Token => n.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').any(|t| t == q),
+ RttiMatchMode::Glob => glob_match(&n, &q),
+ RttiMatchMode::Substr => n.contains(&q),
+ }
+}
+
+fn glob_match(name: &str, pat: &str) -> bool {
+ if !pat.contains('*') {
+ return name == pat;
+ }
+ let parts: Vec<&str> = pat.split('*').collect();
+ if parts.len() == 2 {
+ return name.starts_with(parts[0]) && name.ends_with(parts[1]);
+ }
+ name.contains(&pat.replace('*', ""))
+}
+
+/// Recover (or reuse cache) full RTTI catalog for a program.
+pub fn rtti_catalog(prog: &Program) -> Result<(Vec<RttiCatalogEntry>, bool, Vec<String>)> {
+ let id = program_identity(prog);
+ {
+ let guard = CACHE.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(c) = guard.as_ref() {
+ if c.identity == id {
+ let entries = catalog_from_report(&c.report);
+ return Ok((entries, true, c.report.notes.clone()));
+ }
+ }
+ }
+ let report = recover_rtti(prog)?;
+ let notes = report.notes.clone();
+ let entries = catalog_from_report(&report);
+ {
+ let mut guard = CACHE.lock().unwrap_or_else(|e| e.into_inner());
+ *guard = Some(CacheEntry {
+ identity: id,
+ report,
+ });
+ }
+ Ok((entries, false, notes))
+}
+
+/// Query catalog with filter/exact. When `filter_during` and needle set, filter after recover
+/// (full recover still required for correctness; early-out skips unrelated names in result).
+pub fn rtti_query(
+ prog: &Program,
+ filter: Option<&str>,
+ exact: bool,
+ match_mode: RttiMatchMode,
+) -> Result<RttiQueryResult> {
+ let mode = if exact {
+ RttiMatchMode::Exact
+ } else {
+ match_mode
+ };
+ let (entries, cache_hit, notes) = rtti_catalog(prog)?;
+ let classes = if let Some(f) = filter {
+ if f.is_empty() {
+ entries
+ } else {
+ entries
+ .into_iter()
+ .filter(|e| matches(&e.name, f, mode))
+ .collect()
+ }
+ } else {
+ entries
+ };
+ Ok(RttiQueryResult {
+ entry_count: classes.len(),
+ classes,
+ cache_hit,
+ notes,
+ })
+}
+
+/// Clear program-scoped cache (tests / binary change).
+pub fn clear_rtti_cache() {
+ let mut guard = CACHE.lock().unwrap_or_else(|e| e.into_inner());
+ *guard = None;
+}
+
+/// Enrich legacy RttiClass with vtable_vas for JSON dumps.
+pub fn enrich_class(c: &RttiClass) -> RttiCatalogEntry {
+ let mut vas = Vec::new();
+ if let Some(v) = c.vtable_va {
+ vas.push(v);
+ }
+ let mut e = RttiCatalogEntry {
+ name: c.name.clone(),
+ mangled: None,
+ type_info_va: c.type_info_va,
+ col_va: c.col_va,
+ vtable_vas: vas.clone(),
+ vtable_va: c.vtable_va,
+ confidence: if c.vtable_va.is_some() {
+ "high".into()
+ } else {
+ "low".into()
+ },
+ notes: vec![],
+ reason: if c.vtable_va.is_none() {
+ Some("col_incomplete_or_no_vtable_link".into())
+ } else {
+ None
+ },
+ kind: c.kind.clone(),
+ };
+ if e.vtable_vas.is_empty() {
+ e.notes
+ .push("vtable_vas empty — not inventing RVA".into());
+ }
+ e
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::fixture_path;
+ use crate::load_path;
+
+ #[test]
+ fn query_widget_from_fixture() {
+ clear_rtti_cache();
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let q = rtti_query(&prog, Some("Widget"), true, RttiMatchMode::Exact).unwrap();
+ assert!(q.entry_count >= 1);
+ assert!(q.classes.iter().any(|c| c.name == "Widget"));
+ let q2 = rtti_query(&prog, Some("Widget"), true, RttiMatchMode::Exact).unwrap();
+ assert!(q2.cache_hit);
+ }
+}
diff --git a/crates/ghidrust-core/src/section_notes.rs b/crates/ghidrust-core/src/section_notes.rs
new file mode 100644
index 0000000..e4e6e05
--- /dev/null
+++ b/crates/ghidrust-core/src/section_notes.rs
@@ -0,0 +1,136 @@
+//! Informational PE/ELF section heuristics (never claim hooks/packing certainty).
+
+use crate::program::{Program, SectionInfo};
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct SectionNote {
+ pub section: String,
+ /// Heuristic kind: `nonstandard_name`, `rwx`, `tiny_high_entropy_tip`, etc.
+ pub kind: String,
+ pub message: String,
+}
+
+/// Well-known PE section names (informational allowlist).
+const STANDARD_PE_NAMES: &[&str] = &[
+ ".text", ".rdata", ".data", ".pdata", ".xdata", ".bss", ".edata", ".idata",
+ ".rsrc", ".reloc", ".tls", ".debug", ".didat", ".gfids", ".00cfg", ".CRT",
+ ".code", ".idata", "CODE", "DATA", "BSS", ".rodata",
+];
+
+fn is_standard_name(name: &str) -> bool {
+ let n = name.trim_end_matches('\0');
+ STANDARD_PE_NAMES.iter().any(|s| s.eq_ignore_ascii_case(n))
+ || n.starts_with(".debug")
+ || n.starts_with(".note")
+}
+
+/// IMAGE_SCN_MEM_EXECUTE | WRITE | READ roughly: characteristics bits.
+const IMAGE_SCN_MEM_EXECUTE: u32 = 0x2000_0000;
+const IMAGE_SCN_MEM_READ: u32 = 0x4000_0000;
+const IMAGE_SCN_MEM_WRITE: u32 = 0x8000_0000;
+
+fn sample_entropy(bytes: &[u8]) -> f64 {
+ if bytes.is_empty() {
+ return 0.0;
+ }
+ let mut hist = [0u64; 256];
+ for &b in bytes {
+ hist[b as usize] += 1;
+ }
+ let n = bytes.len() as f64;
+ let mut h = 0.0;
+ for c in hist {
+ if c == 0 {
+ continue;
+ }
+ let p = c as f64 / n;
+ h -= p * p.log2();
+ }
+ h
+}
+
+/// Emit informational notes for unusual section layout. Low-confidence wording only.
+pub fn section_notes_for(prog: &Program) -> Vec<SectionNote> {
+ let mut notes = Vec::new();
+ for s in &prog.sections {
+ notes.extend(notes_for_section(prog, s));
+ }
+ notes
+}
+
+fn notes_for_section(prog: &Program, s: &SectionInfo) -> Vec<SectionNote> {
+ let mut out = Vec::new();
+ let name = s.name.trim_end_matches('\0').to_string();
+ if !is_standard_name(&name) && !name.is_empty() {
+ out.push(SectionNote {
+ section: name.clone(),
+ kind: "nonstandard_name".into(),
+ message: format!(
+ "unusual section name '{name}' (informational; not proof of packing or hooks)"
+ ),
+ });
+ }
+ let rwx = (s.characteristics & IMAGE_SCN_MEM_EXECUTE) != 0
+ && (s.characteristics & IMAGE_SCN_MEM_WRITE) != 0
+ && (s.characteristics & IMAGE_SCN_MEM_READ) != 0;
+ if rwx {
+ out.push(SectionNote {
+ section: name.clone(),
+ kind: "rwx".into(),
+ message: format!(
+ "section '{name}' has read+write+execute characteristics (unusual; not proof of hooks)"
+ ),
+ });
+ }
+ // Tiny high-entropy tip: small section with high byte entropy in mapped bytes.
+ if s.virtual_size > 0 && s.virtual_size <= 0x1000 {
+ if let Some(block) = prog.blocks.iter().find(|b| b.name == s.name || b.va == s.va) {
+ let sample_len = (block.bytes.len()).min(256);
+ if sample_len >= 32 {
+ let ent = sample_entropy(&block.bytes[..sample_len]);
+ if ent >= 7.2 {
+ out.push(SectionNote {
+ section: name.clone(),
+ kind: "tiny_high_entropy_tip".into(),
+ message: format!(
+ "section '{name}' is small with high sample entropy (~{ent:.2}; tip only, not packing proof)"
+ ),
+ });
+ }
+ }
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::program::{MemoryBlock, Program, SectionInfo};
+
+ #[test]
+ fn flags_nonstandard_and_rwx() {
+ let mut prog = Program::new("t".into(), "PE32+");
+ prog.sections.push(SectionInfo {
+ name: ".foo".into(),
+ va: 0x1000,
+ virtual_size: 0x100,
+ raw_size: 0x100,
+ file_offset: 0x400,
+ characteristics: IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE,
+ });
+ prog.blocks.push(MemoryBlock {
+ name: ".foo".into(),
+ va: 0x1000,
+ size: 0x100,
+ bytes: (0..0x100).map(|i| (i * 37) as u8).collect(),
+ readable: true,
+ writable: true,
+ executable: true,
+ });
+ let notes = section_notes_for(&prog);
+ assert!(notes.iter().any(|n| n.kind == "nonstandard_name"));
+ assert!(notes.iter().any(|n| n.kind == "rwx"));
+ }
+}
diff --git a/crates/ghidrust-core/src/tree_index.rs b/crates/ghidrust-core/src/tree_index.rs
new file mode 100644
index 0000000..14a0bfb
--- /dev/null
+++ b/crates/ghidrust-core/src/tree_index.rs
@@ -0,0 +1,251 @@
+//! Hand-rolled install / workspace tree index (`std::fs` only — no walkdir/globset).
+
+use serde::{Deserialize, Serialize};
+use std::fs;
+use std::path::Path;
+use std::time::SystemTime;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TreeEntry {
+ pub path: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub size: Option<u64>,
+ pub is_dir: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mtime_unix: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Clone)]
+pub struct TreeListOpts {
+ pub max_depth: usize,
+ pub extensions: Option<Vec<String>>,
+ pub name_glob: Option<String>,
+ pub follow_symlinks: bool,
+ pub max_entries: usize,
+}
+
+impl Default for TreeListOpts {
+ fn default() -> Self {
+ Self {
+ max_depth: 6,
+ extensions: None,
+ name_glob: None,
+ follow_symlinks: false,
+ max_entries: 10_000,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TreeListResult {
+ pub root: String,
+ pub entries: Vec<TreeEntry>,
+ pub truncated: bool,
+}
+
+/// Simple glob: `*` matches within one path component; `**` not fully recursive beyond depth.
+fn name_matches(name: &str, pattern: &str) -> bool {
+ if pattern == "*" || pattern.is_empty() {
+ return true;
+ }
+ if !pattern.contains('*') {
+ return name.eq_ignore_ascii_case(pattern);
+ }
+ // Prefix*suffix
+ let parts: Vec<&str> = pattern.split('*').collect();
+ if parts.len() == 2 {
+ let (pre, suf) = (parts[0], parts[1]);
+ let lower = name.to_ascii_lowercase();
+ return lower.starts_with(&pre.to_ascii_lowercase())
+ && lower.ends_with(&suf.to_ascii_lowercase());
+ }
+ // Fallback: substring of pattern without stars
+ let needle: String = pattern.chars().filter(|c| *c != '*').collect();
+ name.to_ascii_lowercase()
+ .contains(&needle.to_ascii_lowercase())
+}
+
+fn ext_allowed(path: &Path, exts: &Option<Vec<String>>) -> bool {
+ let Some(exts) = exts else {
+ return true;
+ };
+ if exts.is_empty() {
+ return true;
+ }
+ let Some(ext) = path.extension().and_then(|e| e.to_str()) else {
+ return false;
+ };
+ let el = ext.to_ascii_lowercase();
+ exts.iter()
+ .any(|e| e.trim_start_matches('.').eq_ignore_ascii_case(&el))
+}
+
+fn mtime_unix(meta: &fs::Metadata) -> Option<u64> {
+ meta.modified()
+ .ok()
+ .and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
+ .map(|d| d.as_secs())
+}
+
+/// Bounded directory walk. Symlinks are not followed by default. Errors become rows.
+pub fn list_tree(root: impl AsRef<Path>, opts: TreeListOpts) -> TreeListResult {
+ let root = root.as_ref();
+ let mut entries = Vec::new();
+ let mut truncated = false;
+ walk(
+ root,
+ root,
+ 0,
+ &opts,
+ &mut entries,
+ &mut truncated,
+ );
+ TreeListResult {
+ root: root.display().to_string(),
+ entries,
+ truncated,
+ }
+}
+
+fn walk(
+ root: &Path,
+ dir: &Path,
+ depth: usize,
+ opts: &TreeListOpts,
+ out: &mut Vec<TreeEntry>,
+ truncated: &mut bool,
+) {
+ if out.len() >= opts.max_entries {
+ *truncated = true;
+ return;
+ }
+ if depth > opts.max_depth {
+ return;
+ }
+ let rd = match fs::read_dir(dir) {
+ Ok(rd) => rd,
+ Err(e) => {
+ let kind = if e.kind() == std::io::ErrorKind::PermissionDenied {
+ "permission_denied"
+ } else {
+ "io"
+ };
+ out.push(TreeEntry {
+ path: dir.display().to_string(),
+ size: None,
+ is_dir: true,
+ mtime_unix: None,
+ error: Some(kind.into()),
+ });
+ return;
+ }
+ };
+ for ent in rd.flatten() {
+ if out.len() >= opts.max_entries {
+ *truncated = true;
+ return;
+ }
+ let path = ent.path();
+ let meta = match ent.metadata() {
+ Ok(m) => m,
+ Err(e) => {
+ let kind = if e.kind() == std::io::ErrorKind::PermissionDenied {
+ "permission_denied"
+ } else {
+ "io"
+ };
+ out.push(TreeEntry {
+ path: path.display().to_string(),
+ size: None,
+ is_dir: false,
+ mtime_unix: None,
+ error: Some(kind.into()),
+ });
+ continue;
+ }
+ };
+ if meta.file_type().is_symlink() && !opts.follow_symlinks {
+ // Record symlink as a leaf row; do not descend.
+ let name = path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("");
+ if let Some(g) = &opts.name_glob {
+ if !name_matches(name, g) {
+ continue;
+ }
+ }
+ out.push(TreeEntry {
+ path: path.display().to_string(),
+ size: None,
+ is_dir: false,
+ mtime_unix: mtime_unix(&meta),
+ error: Some("symlink_skipped".into()),
+ });
+ continue;
+ }
+ let is_dir = meta.is_dir();
+ let name = path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("");
+ if let Some(g) = &opts.name_glob {
+ if !is_dir && !name_matches(name, g) {
+ continue;
+ }
+ }
+ if !is_dir && !ext_allowed(&path, &opts.extensions) {
+ continue;
+ }
+ out.push(TreeEntry {
+ path: path.display().to_string(),
+ size: if is_dir { None } else { Some(meta.len()) },
+ is_dir,
+ mtime_unix: mtime_unix(&meta),
+ error: None,
+ });
+ if is_dir && depth < opts.max_depth {
+ walk(root, &path, depth + 1, opts, out, truncated);
+ }
+ }
+}
+
+/// Normalize a relative display path under root (for tests / agents).
+pub fn rel_display(root: &Path, path: &Path) -> String {
+ path.strip_prefix(root)
+ .map(|p| p.display().to_string())
+ .unwrap_or_else(|_| path.display().to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn lists_files_with_ext_filter() {
+ let dir = std::env::temp_dir().join(format!(
+ "ghidrust-tree-{}-{}",
+ std::process::id(),
+ "t"
+ ));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(dir.join("sub")).unwrap();
+ fs::write(dir.join("a.exe"), b"x").unwrap();
+ fs::write(dir.join("b.txt"), b"y").unwrap();
+ fs::write(dir.join("sub").join("c.dll"), b"z").unwrap();
+ let res = list_tree(
+ &dir,
+ TreeListOpts {
+ max_depth: 4,
+ extensions: Some(vec!["exe".into(), "dll".into()]),
+ ..Default::default()
+ },
+ );
+ assert!(res.entries.iter().any(|e| e.path.ends_with("a.exe")));
+ assert!(res.entries.iter().any(|e| e.path.ends_with("c.dll")));
+ assert!(!res.entries.iter().any(|e| e.path.ends_with("b.txt")));
+ let _ = fs::remove_dir_all(&dir);
+ }
+}
diff --git a/crates/ghidrust-core/src/xrefs.rs b/crates/ghidrust-core/src/xrefs.rs
index 506be84..0d3e9f3 100644
--- a/crates/ghidrust-core/src/xrefs.rs
+++ b/crates/ghidrust-core/src/xrefs.rs
@@ -23,6 +23,9 @@ pub struct XRef {
pub kind: &'static str,
/// Ghidra "From Preview" — mnemonic/operand text where computable.
pub preview: String,
+ /// String encoding when this xref targets a string (`ascii`, `utf16le`); omitted otherwise.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub encoding: Option<String>,
}
/// Compute references **to** `target`.
@@ -43,6 +46,7 @@ pub fn xrefs_to(
to: r.to,
kind: static_kind(&r.kind),
preview: r.kind.clone(),
+ encoding: None,
});
}
}
@@ -56,6 +60,7 @@ pub fn xrefs_to(
to: target,
kind: "ptr_table",
preview: format!("[{}] {:#x}", i, target),
+ encoding: None,
});
}
}
@@ -102,6 +107,7 @@ fn scan_data_pointer_refs(prog: &Program, target: u64, out: &mut Vec<XRef>) {
to: target,
kind: "ptr",
preview: format!("dq {target:#x}"),
+ encoding: None,
});
found += 1;
}
@@ -124,6 +130,7 @@ pub fn xrefs_from(prog: &Program, source: u64, max_insns: usize) -> Vec<XRef> {
to: tgt,
kind: mnemonic_kind(&insn.mnemonic),
preview: format!("{} {}", insn.mnemonic, insn.operands),
+ encoding: None,
});
}
}
@@ -166,21 +173,79 @@ pub fn xrefs_to_import(prog: &Program, import_name: &str) -> Vec<XRef> {
/// Resolve string VA(s) by filter, then gather xrefs to each.
pub fn xrefs_to_string_filter(prog: &Program, filter: &str) -> Vec<XRef> {
- let Ok(strings) = crate::analyzers::collect_strings(prog, "all", 4, Some(filter)) else {
+ xrefs_to_string_filter_opts(prog, filter, "all", true)
+}
+
+/// String xrefs with encoding filter: `ascii` | `utf16` | `utf16le` | `all`.
+/// When `include_interior` is true, also match pointers into `[va, end_va)`.
+pub fn xrefs_to_string_filter_opts(
+ prog: &Program,
+ filter: &str,
+ encoding: &str,
+ include_interior: bool,
+) -> Vec<XRef> {
+ let enc = match encoding.to_ascii_lowercase().as_str() {
+ "ascii" => "ascii",
+ "utf16" | "utf16le" => "utf16",
+ _ => "all",
+ };
+ let Ok(strings) = crate::analyzers::collect_strings(prog, enc, 4, Some(filter)) else {
return Vec::new();
};
let mut out = Vec::new();
for s in strings {
+ let enc_tag = normalize_encoding_tag(&s.encoding);
+ // Primary: xrefs to string start.
let mut refs = xrefs_to(prog, s.va, None);
for r in &mut refs {
r.preview = format!("{} ; \"{}\"", r.preview, truncate(&s.value, 48));
+ r.encoding = Some(enc_tag.clone());
}
out.extend(refs);
+ // Interior: code may LEA into mid-string (wide concatenation).
+ if include_interior {
+ let byte_len = if enc_tag == "utf16le" {
+ (s.length as u64).saturating_mul(2)
+ } else {
+ s.length as u64
+ };
+ let end = s.va.saturating_add(byte_len);
+ if end > s.va.saturating_add(1) {
+ // Sample a few interior VAs (every 2 bytes for utf16, else every 4).
+ let step = if enc_tag == "utf16le" { 2u64 } else { 4u64 };
+ let mut va = s.va.saturating_add(step);
+ let mut n = 0usize;
+ while va < end && n < 8 {
+ let mut refs = xrefs_to(prog, va, None);
+ for r in &mut refs {
+ r.preview = format!(
+ "{} ; \"{}\" +{:#x}",
+ r.preview,
+ truncate(&s.value, 32),
+ va - s.va
+ );
+ r.encoding = Some(enc_tag.clone());
+ r.to = s.va; // normalize to string start for agent UX
+ }
+ out.extend(refs);
+ va = va.saturating_add(step);
+ n += 1;
+ }
+ }
+ }
}
finalize(&mut out);
out
}
+fn normalize_encoding_tag(raw: &str) -> String {
+ match raw.to_ascii_lowercase().as_str() {
+ "utf16" | "utf-16" | "utf16le" | "utf-16le" => "utf16le".into(),
+ "ascii" | "utf8" | "utf-8" => "ascii".into(),
+ other => other.to_string(),
+ }
+}
+
/// Absolute hex literals in operands plus RIP-relative effective addresses.
pub fn instruction_targets(insn: &crate::disasm::Instruction) -> Vec<u64> {
let mut out = operand_addresses(&insn.operands);
@@ -304,6 +369,7 @@ fn scan_exec_xrefs_to(prog: &Program, target: u64, out: &mut Vec<XRef>) {
to: target,
kind: mnemonic_kind(&insn.mnemonic),
preview: format!("{} {}", insn.mnemonic, insn.operands),
+ encoding: None,
});
}
off += insn.length.max(1) as usize;
@@ -326,6 +392,7 @@ fn push_listing_xrefs_to(
to: target,
kind: mnemonic_kind(&insn.mnemonic),
preview: format!("{} {}", insn.mnemonic, insn.operands),
+ encoding: None,
});
}
}
@@ -430,6 +497,56 @@ mod tests {
assert!(refs.iter().any(|r| r.kind == "call"));
}
+ #[test]
+ fn utf16_string_xrefs_tagged_encoding() {
+ let mut prog = Program::new("t".into(), "PE32+");
+ // UTF-16LE "WideLab\0" (min scan length is 4 code units)
+ let str_va = 0x140002000u64;
+ let mut wide = Vec::new();
+ for c in "WideLab".encode_utf16() {
+ wide.extend_from_slice(&c.to_le_bytes());
+ }
+ wide.extend_from_slice(&[0, 0]);
+ let insn_va = 0x140001000u64;
+ let next = insn_va + 7;
+ let disp = (str_va as i64) - (next as i64);
+ let disp_bytes = (disp as i32).to_le_bytes();
+ let mut code = vec![0x48, 0x8d, 0x05];
+ code.extend_from_slice(&disp_bytes);
+ code.push(0xc3);
+ prog.blocks.push(MemoryBlock {
+ name: ".text".into(),
+ va: insn_va,
+ size: code.len() as u64,
+ bytes: code,
+ readable: true,
+ writable: false,
+ executable: true,
+ });
+ prog.blocks.push(MemoryBlock {
+ name: ".rdata".into(),
+ va: str_va,
+ size: wide.len() as u64,
+ bytes: wide,
+ readable: true,
+ writable: false,
+ executable: false,
+ });
+ let refs = xrefs_to_string_filter_opts(&prog, "WideLab", "utf16le", false);
+ assert!(
+ refs.iter().any(|r| {
+ r.from == insn_va
+ && r.encoding.as_deref() == Some("utf16le")
+ }),
+ "{refs:?}"
+ );
+ let ascii_only = xrefs_to_string_filter_opts(&prog, "WideLab", "ascii", false);
+ assert!(
+ ascii_only.is_empty(),
+ "ascii filter should not match wide-only literal: {ascii_only:?}"
+ );
+ }
+
#[test]
fn xrefs_to_finds_rip_lea_in_exec_block() {
let mut prog = Program::new("t".into(), "PE32+");
diff --git a/crates/ghidrust-decode/src/x86_64.rs b/crates/ghidrust-decode/src/x86_64.rs
index 78f5fe1..bd1d809 100644
--- a/crates/ghidrust-decode/src/x86_64.rs
+++ b/crates/ghidrust-decode/src/x86_64.rs
@@ -877,6 +877,25 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
("movaps".into(), format!("{rm}, {xmm}"))
}
}
+ // MOVDQA xmm, xmm/m128 / MOVDQA xmm/m128, xmm (66 0F 6F / 7F)
+ 0x6F | 0x7F if pfx.op_size => {
+ let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;
+ if op2 == 0x6F {
+ ("movdqa".into(), format!("{xmm}, {rm}"))
+ } else {
+ ("movdqa".into(), format!("{rm}, {xmm}"))
+ }
+ }
+ // XORPS xmm, xmm/m128
+ 0x57 => {
+ let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;
+ ("xorps".into(), format!("{xmm}, {rm}"))
+ }
+ // PXOR xmm, xmm/m128 (66 0F EF)
+ 0xEF if pfx.op_size => {
+ let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;
+ ("pxor".into(), format!("{xmm}, {rm}"))
+ }
// Jcc rel32
0x80..=0x8F => {
let names = [
@@ -1239,4 +1258,24 @@ mod tests {
assert_eq!(i.mnemonic, "movaps");
assert_eq!(i.operands, "xmm0, xmm1");
}
+
+ #[test]
+ fn decode_xorps_zeroing() {
+ // 0f 57 c0 xorps xmm0, xmm0
+ let i = decode_one(&[0x0f, 0x57, 0xc0], 0).unwrap();
+ assert_eq!(i.mnemonic, "xorps");
+ assert_eq!(i.operands, "xmm0, xmm0");
+ }
+
+ #[test]
+ fn decode_pxor_and_movdqa() {
+ // 66 0f ef c9 pxor xmm1, xmm1
+ let i = decode_one(&[0x66, 0x0f, 0xef, 0xc9], 0).unwrap();
+ assert_eq!(i.mnemonic, "pxor");
+ assert_eq!(i.operands, "xmm1, xmm1");
+ // 66 0f 6f c1 movdqa xmm0, xmm1
+ let m = decode_one(&[0x66, 0x0f, 0x6f, 0xc1], 0).unwrap();
+ assert_eq!(m.mnemonic, "movdqa");
+ assert_eq!(m.operands, "xmm0, xmm1");
+ }
}
diff --git a/crates/ghidrust-gui/Cargo.toml b/crates/ghidrust-gui/Cargo.toml
index 99a03e8..da9ad15 100644
--- a/crates/ghidrust-gui/Cargo.toml
+++ b/crates/ghidrust-gui/Cargo.toml
@@ -11,14 +11,22 @@ path = "src/main.rs"
[dependencies]
ghidrust-core = { workspace = true, features = ["gpu"] }
-# CPU Stage-0 (CFG → pseudo-C); do not call GPU decompile APIs from the GUI.
+# CPU Stage-0 (CFG → pseudo-C) is the default GUI decompiler. `gpu_decompile_to_file`
+# is also used by the Analysis → GPU Decompile dialog; it falls back to the CPU
+# multipass pipeline here because ghidrust-decomp's own `gpu` feature is not enabled
+# for this crate (no wgpu device requirement in the GUI process).
ghidrust-decomp = { path = "../ghidrust-decomp" }
ghidrust-types = { workspace = true }
+# §13 tool panes (IL2CPP Metadata/Methods/ICalls) — hand-rolled parser, no
+# Il2CppDumper/Cpp2IL at runtime.
+ghidrust-il2cpp = { workspace = true }
# 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"
+# Pin: egui 0.31 ↔ egui_dock 0.16 (do not bump egui just for newer egui_dock).
+egui_dock = { version = "0.16", features = ["serde"] }
rfd = "0.15"
# Phase H (M8) — layout persistence (`.tool.json`) via serde_json.
serde = { version = "1", features = ["derive"] }
diff --git a/crates/ghidrust-gui/src/agent_pane.rs b/crates/ghidrust-gui/src/agent_pane.rs
index 374b412..6122300 100644
--- a/crates/ghidrust-gui/src/agent_pane.rs
+++ b/crates/ghidrust-gui/src/agent_pane.rs
@@ -7,8 +7,9 @@
use crate::grok_term::{self, GrokTermSession};
use eframe::egui::{self, Color32, RichText, Ui};
use ghidrust_agent::{
- grok_binary_path, install_command_for_platform, register_mcp_with_grok_cli,
- write_project_mcp_config, write_project_skill, ProgramFacts, SystemPromptBuilder,
+ ensure_project_skill, grok_binary_path, install_command_for_platform,
+ register_mcp_with_grok_cli, start_checklist, write_project_mcp_config, ProgramFacts,
+ SystemPromptBuilder,
};
use std::path::{Path, PathBuf};
@@ -38,6 +39,10 @@ pub struct GrokPaneState {
pub keyboard_captured: bool,
/// Set after Start/Restart so the next paint focuses the terminal.
pub request_term_focus: bool,
+ /// Project root we last attempted to auto-wire skill for (avoids per-frame retries).
+ pub skill_wired_root: Option<PathBuf>,
+ /// Fail-loud skill wire error (shown above the checklist when auto-install fails).
+ pub skill_wire_error: Option<String>,
}
impl GrokPaneState {
@@ -52,6 +57,8 @@ impl GrokPaneState {
status: None,
keyboard_captured: false,
request_term_focus: false,
+ skill_wired_root: None,
+ skill_wire_error: None,
}
}
@@ -99,10 +106,18 @@ pub fn start_pty_session(
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);
- }
+ // Fail-loud skill: prefer disk source, else embedded SKILL.md (release installs).
+ ensure_project_skill(project_root, skill_source).map_err(|e| {
+ let dest = ghidrust_agent::project_skill_path(project_root);
+ format!(
+ "skill write failed ({e}); expected destination {}",
+ dest.display()
+ )
+ })?;
write_ghidrust_agent_files(project_root, facts)?;
+ // Checklist is fail-loud in the Grok pane UI (red rows); do not abort Start
+ // after files were written — agents still need the TUI.
+ let _ = start_checklist(project_root);
GrokTermSession::start(
grok_bin.to_path_buf(),
@@ -135,7 +150,8 @@ fn write_ghidrust_agent_files(project_root: &Path, facts: &ProgramFacts) -> Resu
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"
+ say so and use MCP `load` with `project` + `file_id` (or absolute `path`) \
+ from the facts JSON — never invent addresses.\n"
);
std::fs::write(project_root.join("AGENTS.md"), agents).map_err(|e| e.to_string())?;
Ok(())
@@ -145,6 +161,7 @@ fn write_ghidrust_agent_files(project_root: &Path, facts: &ProgramFacts) -> Resu
pub fn render_grok_pane(
ui: &mut Ui,
state: &mut GrokPaneState,
+ project_root: Option<&Path>,
primary: Color32,
muted: Color32,
on_start: &mut dyn FnMut(u16, u16) -> Result<(), String>,
@@ -228,12 +245,26 @@ pub fn render_grok_pane(
ui.separator();
+ // Start checklist — fail-loud rows for mcp/skill/agents/context so a
+ // broken setup is visible immediately instead of a silently toolless agent.
+ if let Some(root) = project_root {
+ // Auto-place embedded skill as soon as a project is visible in the Grok
+ // pane (not only on Start). Idempotent; fail-loud on write errors.
+ ensure_skill_for_project(state, root, None);
+ if let Some(err) = &state.skill_wire_error {
+ ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), err);
+ }
+ render_start_checklist(ui, root, muted);
+ 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.",
+ sessions). Opening a project auto-installs `.grok/skills/ghidrust/SKILL.md` \
+ from the embedded skill; Start also wires MCP, AGENTS.md, and context.",
)
.color(muted),
);
@@ -254,6 +285,89 @@ pub fn render_grok_pane(
}
}
+/// One fail-loud row in the Start checklist (mcp / skill / agents / context).
+pub struct StartChecklistRow {
+ pub label: String,
+ pub ok: bool,
+ pub detail: String,
+}
+
+fn checklist_label(id: &str) -> &'static str {
+ match id {
+ "mcp" => "MCP config",
+ "mcp_grok" => "MCP config (.grok)",
+ "skill" => "Skill",
+ "skill_hash" => "Skill hash",
+ "agents" => "Agents (AGENTS.md)",
+ "context" => "Context",
+ _ => "Check",
+ }
+}
+
+/// Verify the on-disk artifacts project-open / Start write actually exist —
+/// fail-loud rather than silently trusting that wiring succeeded.
+pub fn pane_start_checklist(project_root: &Path) -> Vec<StartChecklistRow> {
+ start_checklist(project_root)
+ .into_iter()
+ // Hash is included in the Skill detail string; skip the extra row.
+ .filter(|item| item.id != "skill_hash")
+ .map(|item| StartChecklistRow {
+ label: checklist_label(item.id).into(),
+ ok: item.ok,
+ detail: item.detail,
+ })
+ .collect()
+}
+
+/// Ensure `.grok/skills/ghidrust/SKILL.md` exists for `project_root`.
+///
+/// Called on project open and again from the Grok pane (once per root) so the
+/// Skill checklist row turns green without requiring Start first.
+pub fn ensure_skill_for_project(
+ state: &mut GrokPaneState,
+ project_root: &Path,
+ skill_source: Option<&Path>,
+) {
+ // One attempt per project root (success or fail-loud). Re-open clears this.
+ if state.skill_wired_root.as_deref() == Some(project_root) {
+ return;
+ }
+ match ensure_project_skill(project_root, skill_source) {
+ Ok(path) => {
+ state.skill_wired_root = Some(project_root.to_path_buf());
+ state.skill_wire_error = None;
+ let _ = path;
+ }
+ Err(e) => {
+ state.skill_wired_root = Some(project_root.to_path_buf());
+ let dest = ghidrust_agent::project_skill_path(project_root);
+ state.skill_wire_error = Some(format!(
+ "Skill auto-install failed ({e}); looked/wrote {}",
+ dest.display()
+ ));
+ }
+ }
+}
+
+/// Render the Start checklist as fail-loud rows (red text + actionable detail
+/// on failure) so a broken Grok session setup is visible before the user
+/// wonders why the agent has no MCP tools.
+pub fn render_start_checklist(ui: &mut Ui, project_root: &Path, muted: Color32) {
+ ui.small(RichText::new("Start checklist").color(muted).strong());
+ for row in pane_start_checklist(project_root) {
+ let color = if row.ok {
+ Color32::from_rgb(0x66, 0xBB, 0x6A)
+ } else {
+ Color32::from_rgb(0xE5, 0x39, 0x35)
+ };
+ ui.horizontal(|ui| {
+ ui.label(if row.ok { "✓" } else { "✗" });
+ ui.label(RichText::new(&row.label).color(color));
+ ui.small(RichText::new(&row.detail).color(muted));
+ });
+ }
+}
+
/// Attempt to spawn the platform's official Grok Build installer.
pub fn spawn_install_grok() -> String {
let Some(cmd) = install_command_for_platform() else {
@@ -289,4 +403,23 @@ mod tests {
assert!(s.session.is_none());
assert_eq!(s.tab, BottomTab::Grok);
}
+
+ #[test]
+ fn ensure_skill_turns_checklist_skill_green() {
+ let dir = std::env::temp_dir().join(format!(
+ "ghidrust-gui-skill-{}",
+ std::process::id()
+ ));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let mut state = GrokPaneState::new();
+ ensure_skill_for_project(&mut state, &dir, None);
+ assert!(state.skill_wire_error.is_none(), "{:?}", state.skill_wire_error);
+ let skill = pane_start_checklist(&dir)
+ .into_iter()
+ .find(|r| r.label == "Skill")
+ .expect("Skill row");
+ assert!(skill.ok, "detail={}", skill.detail);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
}
diff --git a/crates/ghidrust-gui/src/debugger.rs b/crates/ghidrust-gui/src/debugger.rs
index f0e466e..474041b 100644
--- a/crates/ghidrust-gui/src/debugger.rs
+++ b/crates/ghidrust-gui/src/debugger.rs
@@ -12,6 +12,11 @@
//! instead of piling into `main.rs`.
use eframe::egui::{self, Color32, RichText, Ui};
+use ghidrust_core::process::{
+ process_attach, process_detach, process_list, process_modules, process_read,
+ process_regions, static_to_live, ModuleInfo, ProcessInfo, ProcessSession, ReadResult,
+ RegionInfo,
+};
/// One provider in Ghidra's Debugger tool catalog.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -109,14 +114,14 @@ impl DebuggerPane {
/// Copy pointing at the pending backend for this pane.
pub const fn backend_message(self) -> &'static str {
match self {
- DebuggerPane::Targets => "Backend pending — no live target agents yet (Phase P12 in GHIDRA_PARITY_PHASE_PLANS.md).",
+ DebuggerPane::Targets => "Live Process Bridge (Windows) — ghidrust_core::process_list/attach.",
DebuggerPane::Threads => "Backend pending — target-agent thread model.",
- DebuggerPane::Modules => "Backend pending — target-agent module list.",
- DebuggerPane::Regions => "Backend pending — target-agent memory regions.",
+ DebuggerPane::Modules => "Live Process Bridge (Windows) — ghidrust_core::process_modules + static_to_live.",
+ DebuggerPane::Regions => "Live Process Bridge (Windows) — ghidrust_core::process_regions (VirtualQueryEx).",
DebuggerPane::Registers => "Backend pending — live register values (Register Manager renders the static register lattice).",
DebuggerPane::Stack => "Backend pending — target-agent stack unwinder.",
DebuggerPane::Breakpoints => "Backend pending — breakpoint model + agent set/clear.",
- DebuggerPane::MemoryBytes => "Backend pending — live memory reads (Bytes pane renders static Program bytes).",
+ DebuggerPane::MemoryBytes => "Live Process Bridge (Windows) — ghidrust_core::process_read (ReadProcessMemory).",
DebuggerPane::Watches => "Backend pending — expression evaluator + refresh.",
DebuggerPane::DebuggerConsole => "Backend pending — target-agent stdio.",
}
@@ -181,6 +186,29 @@ pub struct DebuggerState {
pub bp_input: String,
/// New-watch input.
pub watch_input: String,
+ // ── Live Process Bridge (Windows) — `ghidrust_core::process_*` ──────
+ /// Attached session (Targets pane "Attach"); `None` = no live target.
+ pub session: Option<ProcessSession>,
+ /// Cached process list (Targets pane; refreshed on demand).
+ pub process_list_cache: Vec<ProcessInfo>,
+ /// Targets pane process-name filter.
+ pub targets_filter: String,
+ /// Targets pane manual PID input (attach without scanning the list).
+ pub attach_pid_input: String,
+ /// Cached module list for the attached session (Modules pane).
+ pub modules_cache: Vec<ModuleInfo>,
+ /// Cached region list for the attached session (Regions pane).
+ pub regions_cache: Vec<RegionInfo>,
+ /// Modules pane · Static Mappings mini-tool: module name + static RVA.
+ pub static_map_module_input: String,
+ pub static_map_rva_input: String,
+ pub static_map_result: Option<String>,
+ /// Memory Bytes pane inputs + last read.
+ pub mem_bytes_va_input: String,
+ pub mem_bytes_size_input: String,
+ pub mem_bytes_last: Option<ReadResult>,
+ /// Last error from any Live Process Bridge call (fail-loud, not silent).
+ pub live_error: Option<String>,
}
impl DebuggerState {
@@ -224,10 +252,328 @@ pub fn render(pane: DebuggerPane, state: &mut DebuggerState, ui: &mut Ui, muted:
match pane {
DebuggerPane::Breakpoints => render_breakpoints(state, ui, muted),
DebuggerPane::Watches => render_watches(state, ui, muted),
+ DebuggerPane::Targets => render_targets(state, ui, muted),
+ DebuggerPane::Modules => render_modules(state, ui, muted),
+ DebuggerPane::Regions => render_regions(state, ui, muted),
+ DebuggerPane::MemoryBytes => render_memory_bytes(state, ui, muted),
_ => render_empty_table(pane, ui, muted),
}
}
+fn err_row(ui: &mut Ui, err: &str) {
+ ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), err);
+}
+
+/// Ghidra `DebuggerTargetsPlugin` analog — process list (Windows Toolhelp32
+/// snapshot) + Attach. Attaching stores a `ProcessSession` other panes read.
+fn render_targets(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ ui.horizontal(|ui| {
+ if ui.button("Refresh process list").clicked() {
+ state.live_error = None;
+ match process_list() {
+ Ok(v) => state.process_list_cache = v,
+ Err(e) => {
+ state.process_list_cache.clear();
+ state.live_error = Some(e);
+ }
+ }
+ }
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.targets_filter)
+ .desired_width(200.0)
+ .hint_text("process name…"),
+ );
+ });
+ if let Some(sess) = state.session.clone() {
+ let mut do_detach = false;
+ ui.horizontal(|ui| {
+ ui.small(RichText::new(format!("Attached · pid={} session={}", sess.pid, sess.session_id)).color(muted));
+ if ui.button("Detach").clicked() {
+ do_detach = true;
+ }
+ });
+ if do_detach {
+ let _ = process_detach(&sess.session_id);
+ state.session = None;
+ state.modules_cache.clear();
+ state.regions_cache.clear();
+ }
+ }
+ if let Some(e) = &state.live_error {
+ err_row(ui, e);
+ }
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label("PID:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.attach_pid_input)
+ .desired_width(100.0)
+ .hint_text("1234"),
+ );
+ if ui
+ .add_enabled(!state.attach_pid_input.trim().is_empty(), egui::Button::new("Attach by PID"))
+ .clicked()
+ {
+ attach(state, state.attach_pid_input.trim().parse().unwrap_or(0));
+ }
+ });
+ if state.process_list_cache.is_empty() {
+ ui.weak("No process list loaded — click Refresh (Windows Toolhelp32 snapshot).");
+ return;
+ }
+ let q = state.targets_filter.to_ascii_lowercase();
+ let rows: Vec<&ProcessInfo> = state
+ .process_list_cache
+ .iter()
+ .filter(|p| q.is_empty() || p.name.to_ascii_lowercase().contains(&q))
+ .collect();
+ ui.small(format!("{} / {} processes", rows.len(), state.process_list_cache.len()));
+ let mut attach_pid: Option<u32> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("dbg_targets_scroll")
+ .max_height(320.0)
+ .show(ui, |ui| {
+ egui::Grid::new("dbg_targets_grid")
+ .num_columns(4)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("PID");
+ ui.strong("Name");
+ ui.strong("Path");
+ ui.strong("");
+ ui.end_row();
+ for p in &rows {
+ ui.monospace(format!("{}", p.pid));
+ ui.label(&p.name);
+ ui.small(p.path.as_deref().unwrap_or("—"));
+ if ui.small_button("Attach").clicked() {
+ attach_pid = Some(p.pid);
+ }
+ ui.end_row();
+ }
+ });
+ });
+ if let Some(pid) = attach_pid {
+ attach(state, pid);
+ }
+}
+
+fn attach(state: &mut DebuggerState, pid: u32) {
+ if pid == 0 {
+ state.live_error = Some("invalid PID".into());
+ return;
+ }
+ state.live_error = None;
+ match process_attach(pid) {
+ Ok(sess) => {
+ state.session = Some(sess);
+ state.modules_cache.clear();
+ state.regions_cache.clear();
+ }
+ Err(e) => state.live_error = Some(e),
+ }
+}
+
+/// Ghidra `DebuggerModulesPlugin` analog — module list for the attached
+/// session, plus a Static Mappings mini-tool (`static_to_live`: module + RVA
+/// → live VA via the loaded module base).
+fn render_modules(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ let Some(sess) = state.session.clone() else {
+ ui.weak("No live target — attach one from Debugger Targets first.");
+ return;
+ };
+ ui.horizontal(|ui| {
+ ui.small(RichText::new(format!("pid={}", sess.pid)).color(muted));
+ if ui.button("Refresh modules").clicked() {
+ state.live_error = None;
+ match process_modules(&sess.session_id) {
+ Ok(v) => state.modules_cache = v,
+ Err(e) => {
+ state.modules_cache.clear();
+ state.live_error = Some(e);
+ }
+ }
+ }
+ });
+ if let Some(e) = &state.live_error {
+ err_row(ui, e);
+ }
+ if !state.modules_cache.is_empty() {
+ ui.small(format!("{} module(s)", state.modules_cache.len()));
+ egui::ScrollArea::vertical()
+ .id_salt("dbg_modules_scroll")
+ .max_height(260.0)
+ .show(ui, |ui| {
+ egui::Grid::new("dbg_modules_grid")
+ .num_columns(4)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Base");
+ ui.strong("Size");
+ ui.strong("Name");
+ ui.strong("Path");
+ ui.end_row();
+ for m in &state.modules_cache {
+ ui.monospace(format!("{:#x}", m.base));
+ ui.monospace(format!("{:#x}", m.size));
+ ui.label(&m.name);
+ ui.small(m.path.as_deref().unwrap_or("—"));
+ ui.end_row();
+ }
+ });
+ });
+ } else {
+ ui.weak("No modules cached — click Refresh modules.");
+ }
+ ui.separator();
+ ui.label(RichText::new("Static Mappings").strong());
+ ui.small(
+ RichText::new("ghidrust_core::process::static_to_live · static file RVA → live VA via module base")
+ .color(muted),
+ );
+ ui.horizontal(|ui| {
+ ui.label("Module:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.static_map_module_input)
+ .desired_width(160.0)
+ .hint_text("game.exe"),
+ );
+ ui.label("RVA:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.static_map_rva_input)
+ .desired_width(120.0)
+ .hint_text("0x1000"),
+ );
+ if ui.button("Resolve").clicked() {
+ let rva = parse_hex(&state.static_map_rva_input).unwrap_or(0);
+ match static_to_live(&sess.session_id, state.static_map_module_input.trim(), rva) {
+ Ok(r) => {
+ state.static_map_result = Some(format!(
+ "{} base={:#x} rva={:#x} → live_va={:#x}",
+ r.module, r.base, r.rva, r.live_va
+ ));
+ state.live_error = None;
+ }
+ Err(e) => {
+ state.static_map_result = None;
+ state.live_error = Some(e);
+ }
+ }
+ }
+ });
+ if let Some(res) = &state.static_map_result {
+ ui.monospace(res);
+ }
+}
+
+/// Ghidra `DebuggerRegionsPlugin` analog — `VirtualQueryEx` region walk.
+fn render_regions(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ let Some(sess) = state.session.clone() else {
+ ui.weak("No live target — attach one from Debugger Targets first.");
+ return;
+ };
+ ui.horizontal(|ui| {
+ ui.small(RichText::new(format!("pid={}", sess.pid)).color(muted));
+ if ui.button("Refresh regions").clicked() {
+ state.live_error = None;
+ match process_regions(&sess.session_id, 4096) {
+ Ok(v) => state.regions_cache = v,
+ Err(e) => {
+ state.regions_cache.clear();
+ state.live_error = Some(e);
+ }
+ }
+ }
+ });
+ if let Some(e) = &state.live_error {
+ err_row(ui, e);
+ }
+ if state.regions_cache.is_empty() {
+ ui.weak("No regions cached — click Refresh regions.");
+ return;
+ }
+ ui.small(format!("{} region(s)", state.regions_cache.len()));
+ let row_h = ui.text_style_height(&egui::TextStyle::Monospace) + 2.0;
+ let regions = state.regions_cache.clone();
+ egui::ScrollArea::vertical()
+ .id_salt("dbg_regions_scroll")
+ .auto_shrink([false, false])
+ .max_height(320.0)
+ .show_rows(ui, row_h, regions.len(), |ui, range| {
+ for i in range {
+ let r: &RegionInfo = &regions[i];
+ ui.monospace(format!(
+ "{:#018x} +{:#x} protect={} state={} type={}",
+ r.base, r.size, r.protect, r.state, r.typ
+ ));
+ }
+ });
+}
+
+/// Ghidra `DebuggerMemoryBytesPlugin` analog — live `ReadProcessMemory` hex
+/// dump for the attached session.
+fn render_memory_bytes(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ let Some(sess) = state.session.clone() else {
+ ui.weak("No live target — attach one from Debugger Targets first.");
+ return;
+ };
+ ui.small(RichText::new(format!("pid={} · live ReadProcessMemory", sess.pid)).color(muted));
+ ui.horizontal(|ui| {
+ ui.label("VA:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.mem_bytes_va_input)
+ .desired_width(160.0)
+ .hint_text("0x140001000"),
+ );
+ ui.label("Size:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.mem_bytes_size_input)
+ .desired_width(100.0)
+ .hint_text("256"),
+ );
+ if ui.button("Read").clicked() {
+ let va = parse_hex(&state.mem_bytes_va_input).unwrap_or(0);
+ let size: usize = state.mem_bytes_size_input.trim().parse().unwrap_or(256).max(1);
+ match process_read(&sess.session_id, va, size) {
+ Ok(r) => {
+ state.live_error = r.error.clone();
+ state.mem_bytes_last = Some(r);
+ }
+ Err(e) => {
+ state.mem_bytes_last = None;
+ state.live_error = Some(e);
+ }
+ }
+ }
+ });
+ if let Some(e) = &state.live_error {
+ err_row(ui, e);
+ }
+ let Some(read) = &state.mem_bytes_last else {
+ ui.weak("No read yet — enter a VA + size and click Read.");
+ return;
+ };
+ ui.small(format!(
+ "va={:#x} requested={} read={}",
+ read.va, read.size_requested, read.bytes_read
+ ));
+ egui::ScrollArea::vertical()
+ .id_salt("dbg_membytes_scroll")
+ .max_height(320.0)
+ .show(ui, |ui| {
+ for (row, chunk) in read.bytes.chunks(16).enumerate() {
+ let addr = read.va + (row as u64) * 16;
+ let hex: String = chunk.iter().map(|b| format!("{b:02x} ")).collect();
+ let ascii: String = chunk
+ .iter()
+ .map(|&b| if (0x20..0x7f).contains(&b) { b as char } else { '.' })
+ .collect();
+ ui.monospace(format!("{addr:#018x} {hex:<48} {ascii}"));
+ }
+ });
+}
+
fn render_empty_table(pane: DebuggerPane, ui: &mut Ui, muted: Color32) {
ui.horizontal(|ui| {
for col in pane.columns() {
diff --git a/crates/ghidrust-gui/src/dock_tabs.rs b/crates/ghidrust-gui/src/dock_tabs.rs
new file mode 100644
index 0000000..121d75b
--- /dev/null
+++ b/crates/ghidrust-gui/src/dock_tabs.rs
@@ -0,0 +1,165 @@
+//! Center-pane docking via `egui_dock` (Phase H+).
+//!
+//! Default layout: horizontal split (~55% | ~45%) with Listing+Overview on the
+//! left and Decompiler on the right. Data Type Manager can be docked into
+//! either leaf. Project / Symbol side panels and the bottom Grok dock stay
+//! outside this tree for v1.
+
+use egui_dock::{DockState, Node, NodeIndex, SurfaceIndex, TabIndex};
+
+/// Tabs hosted in the central `DockArea`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
+pub enum DockTab {
+ Overview,
+ Listing,
+ Decompiler,
+ DataTypes,
+}
+
+impl DockTab {
+ pub fn title(self) -> &'static str {
+ match self {
+ DockTab::Overview => "Overview",
+ DockTab::Listing => "Listing",
+ DockTab::Decompiler => "Decompiler",
+ DockTab::DataTypes => "Data Type Manager",
+ }
+ }
+
+ pub fn id(self) -> &'static str {
+ match self {
+ DockTab::Overview => "overview",
+ DockTab::Listing => "listing",
+ DockTab::Decompiler => "decompiler",
+ DockTab::DataTypes => "datatypes",
+ }
+ }
+
+ pub fn from_id(s: &str) -> Option<Self> {
+ match s {
+ "overview" => Some(DockTab::Overview),
+ "listing" => Some(DockTab::Listing),
+ "decompiler" => Some(DockTab::Decompiler),
+ "datatypes" => Some(DockTab::DataTypes),
+ _ => None,
+ }
+ }
+}
+
+/// Default IDE-style center dock:
+/// - Left leaf (~55%): Listing (active), Overview
+/// - Right leaf (~45%): Decompiler (active)
+pub fn default_dock_state() -> DockState<DockTab> {
+ let mut dock = DockState::new(vec![DockTab::Listing, DockTab::Overview]);
+ // `fraction` is the share retained by the *old* (left) node after the split.
+ let [left, right] =
+ dock.main_surface_mut()
+ .split_right(NodeIndex::root(), 0.55, vec![DockTab::Decompiler]);
+ dock.main_surface_mut()
+ .set_active_tab(left, TabIndex(0)); // Listing
+ dock.main_surface_mut()
+ .set_active_tab(right, TabIndex(0)); // Decompiler
+ dock.set_focused_node_and_surface((SurfaceIndex::main(), left));
+ dock
+}
+
+/// Focus `tab` if present; otherwise open it on the focused leaf.
+pub fn focus_tab(dock: &mut DockState<DockTab>, tab: DockTab) {
+ if let Some(loc) = dock.find_tab(&tab) {
+ dock.set_active_tab(loc);
+ dock.set_focused_node_and_surface((loc.0, loc.1));
+ } else {
+ dock.main_surface_mut().push_to_focused_leaf(tab);
+ if let Some(loc) = dock.find_tab(&tab) {
+ dock.set_active_tab(loc);
+ dock.set_focused_node_and_surface((loc.0, loc.1));
+ }
+ }
+}
+
+/// Ensure Listing and Decompiler sit in different leaves (side-by-side), then
+/// focus `prefer`. Preserves Overview / DataTypes when rebuilding.
+pub fn ensure_side_by_side(dock: &mut DockState<DockTab>, prefer: DockTab) {
+ let listing = dock.find_tab(&DockTab::Listing);
+ let decomp = dock.find_tab(&DockTab::Decompiler);
+ let already_split = match (listing, decomp) {
+ (Some((s1, n1, _)), Some((s2, n2, _))) => s1 != s2 || n1 != n2,
+ _ => false,
+ };
+ if !already_split {
+ let had_overview = dock.find_tab(&DockTab::Overview).is_some();
+ let had_dtm = dock.find_tab(&DockTab::DataTypes).is_some();
+ *dock = default_dock_state();
+ // default_dock_state already includes Overview on the left leaf.
+ if !had_overview {
+ if let Some(loc) = dock.find_tab(&DockTab::Overview) {
+ let _ = dock.remove_tab(loc);
+ }
+ }
+ if had_dtm {
+ focus_tab(dock, DockTab::DataTypes);
+ }
+ }
+ focus_tab(dock, prefer);
+}
+
+/// Legacy `center` shim string for `.tool.json` compatibility.
+pub fn active_center_id(dock: &DockState<DockTab>) -> &'static str {
+ if let Some(node) = dock.main_surface().focused_leaf() {
+ if let Node::Leaf { tabs, active, .. } = &dock.main_surface()[node] {
+ if let Some(tab) = tabs.get(active.0) {
+ return tab.id();
+ }
+ }
+ }
+ for tab in [
+ DockTab::Listing,
+ DockTab::Decompiler,
+ DockTab::Overview,
+ DockTab::DataTypes,
+ ] {
+ if dock.find_tab(&tab).is_some() {
+ return tab.id();
+ }
+ }
+ "overview"
+}
+
+/// Build a dock tree from a legacy `center` field (pre-docking layouts).
+pub fn from_legacy_center(center: &str) -> DockState<DockTab> {
+ let mut dock = default_dock_state();
+ if let Some(tab) = DockTab::from_id(center) {
+ match tab {
+ DockTab::Listing | DockTab::Decompiler => ensure_side_by_side(&mut dock, tab),
+ DockTab::Overview | DockTab::DataTypes => focus_tab(&mut dock, tab),
+ }
+ }
+ dock
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn default_layout_is_side_by_side() {
+ let dock = default_dock_state();
+ let listing = dock.find_tab(&DockTab::Listing).expect("listing");
+ let decomp = dock.find_tab(&DockTab::Decompiler).expect("decompiler");
+ assert!(
+ listing.0 != decomp.0 || listing.1 != decomp.1,
+ "Listing and Decompiler should be in different leaves"
+ );
+ assert!(dock.find_tab(&DockTab::Overview).is_some());
+ assert!(dock.find_tab(&DockTab::DataTypes).is_none());
+ }
+
+ #[test]
+ fn ensure_side_by_side_rebuilds_collapsed_tree() {
+ let mut dock = DockState::new(vec![DockTab::Listing, DockTab::Decompiler]);
+ ensure_side_by_side(&mut dock, DockTab::Decompiler);
+ let listing = dock.find_tab(&DockTab::Listing).unwrap();
+ let decomp = dock.find_tab(&DockTab::Decompiler).unwrap();
+ assert!(listing.1 != decomp.1 || listing.0 != decomp.0);
+ }
+}
diff --git a/crates/ghidrust-gui/src/grok_term/ansi.rs b/crates/ghidrust-gui/src/grok_term/ansi.rs
index 8137b1f..cb0bb3b 100644
--- a/crates/ghidrust-gui/src/grok_term/ansi.rs
+++ b/crates/ghidrust-gui/src/grok_term/ansi.rs
@@ -328,6 +328,53 @@ impl TerminalGrid {
self.active().get(col, row)
}
+ /// Extract visible text from an inclusive cell range (row-major).
+ ///
+ /// Skips wide-glyph continuations; trims trailing spaces per line.
+ pub fn text_in_range(
+ &self,
+ start: (usize, usize),
+ end: (usize, usize),
+ ) -> String {
+ let cols = self.cols();
+ let rows = self.rows();
+ if cols == 0 || rows == 0 {
+ return String::new();
+ }
+ let (c0, r0) = start;
+ let (c1, r1) = end;
+ let (sc, sr, ec, er) = if (r0, c0) <= (r1, c1) {
+ (c0.min(cols - 1), r0.min(rows - 1), c1.min(cols - 1), r1.min(rows - 1))
+ } else {
+ (c1.min(cols - 1), r1.min(rows - 1), c0.min(cols - 1), r0.min(rows - 1))
+ };
+
+ let mut out = String::new();
+ for row in sr..=er {
+ let col_start = if row == sr { sc } else { 0 };
+ let col_end = if row == er { ec } else { cols - 1 };
+ let mut line = String::new();
+ let mut col = col_start;
+ while col <= col_end {
+ let cell = self.cell(col, row);
+ if !cell.wide_cont {
+ if cell.ch != '\0' {
+ line.push(cell.ch);
+ }
+ }
+ col += 1;
+ }
+ while line.ends_with(' ') {
+ line.pop();
+ }
+ out.push_str(&line);
+ if row != er {
+ out.push('\n');
+ }
+ }
+ out
+ }
+
fn active(&self) -> &Buffer {
if self.use_alt {
&self.alt
diff --git a/crates/ghidrust-gui/src/grok_term/session.rs b/crates/ghidrust-gui/src/grok_term/session.rs
index 09db5bf..d8bdce5 100644
--- a/crates/ghidrust-gui/src/grok_term/session.rs
+++ b/crates/ghidrust-gui/src/grok_term/session.rs
@@ -15,6 +15,46 @@ enum HostCmd {
Shutdown,
}
+/// Host-side drag selection over the painted grid (for clipboard copy).
+#[derive(Debug, Clone, Copy)]
+pub struct TermSelection {
+ pub anchor: (usize, usize),
+ pub focus: (usize, usize),
+}
+
+impl TermSelection {
+ pub fn normalized(&self) -> ((usize, usize), (usize, usize)) {
+ let a = self.anchor;
+ let b = self.focus;
+ if (a.1, a.0) <= (b.1, b.0) {
+ (a, b)
+ } else {
+ (b, a)
+ }
+ }
+
+ pub fn contains(&self, col: usize, row: usize) -> bool {
+ let ((c0, r0), (c1, r1)) = self.normalized();
+ if row < r0 || row > r1 {
+ return false;
+ }
+ if r0 == r1 {
+ return col >= c0 && col <= c1;
+ }
+ if row == r0 {
+ return col >= c0;
+ }
+ if row == r1 {
+ return col <= c1;
+ }
+ true
+ }
+
+ pub fn is_empty_cell(&self) -> bool {
+ self.anchor == self.focus
+ }
+}
+
/// Live embedded Grok TUI.
pub struct GrokTermSession {
grid: Arc<Mutex<TerminalGrid>>,
@@ -24,6 +64,11 @@ pub struct GrokTermSession {
last_cols: u16,
last_rows: u16,
pub project_root: PathBuf,
+ /// Active click-drag selection for copy-to-clipboard.
+ pub selection: Option<TermSelection>,
+ selecting: bool,
+ /// egui time until which we show a brief "Copied" toast on the terminal.
+ copied_flash_until: Option<f64>,
}
impl GrokTermSession {
@@ -64,6 +109,9 @@ impl GrokTermSession {
last_cols: cols,
last_rows: rows,
project_root,
+ selection: None,
+ selecting: false,
+ copied_flash_until: None,
})
}
@@ -75,6 +123,83 @@ impl GrokTermSession {
let _ = self.cmd_tx.send(HostCmd::Write(data.to_vec()));
}
+ /// Copy current host selection to the system clipboard. Returns `true` if
+ /// non-empty text was copied.
+ pub fn copy_selection_to_clipboard(&self, ctx: &Context) -> bool {
+ let Some(sel) = self.selection else {
+ return false;
+ };
+ if sel.is_empty_cell() {
+ return false;
+ }
+ let (start, end) = sel.normalized();
+ let text = match self.grid.lock() {
+ Ok(g) => g.text_in_range(start, end),
+ Err(_) => return false,
+ };
+ if text.is_empty() {
+ return false;
+ }
+ ctx.copy_text(text);
+ true
+ }
+
+ /// Copy selection, show "Copied", and clear the highlight so it cannot
+ /// stick to the wrong cells after the TUI scrolls.
+ pub fn copy_selection_and_clear(&mut self, ctx: &Context) -> bool {
+ if !self.copy_selection_to_clipboard(ctx) {
+ self.clear_selection();
+ return false;
+ }
+ self.flash_copied(ctx);
+ self.clear_selection();
+ true
+ }
+
+ pub fn flash_copied(&mut self, ctx: &Context) {
+ self.copied_flash_until = Some(ctx.input(|i| i.time) + 1.25);
+ ctx.request_repaint();
+ }
+
+ pub fn copied_flash_visible(&self, ctx: &Context) -> bool {
+ let Some(until) = self.copied_flash_until else {
+ return false;
+ };
+ ctx.input(|i| i.time) < until
+ }
+
+ pub fn clear_selection(&mut self) {
+ self.selection = None;
+ self.selecting = false;
+ }
+
+ pub fn begin_selection(&mut self, col: usize, row: usize) {
+ self.selecting = true;
+ self.selection = Some(TermSelection {
+ anchor: (col, row),
+ focus: (col, row),
+ });
+ }
+
+ pub fn update_selection(&mut self, col: usize, row: usize) {
+ if let Some(sel) = &mut self.selection {
+ sel.focus = (col, row);
+ }
+ }
+
+ pub fn end_selection(&mut self) {
+ self.selecting = false;
+ if let Some(sel) = self.selection {
+ if sel.is_empty_cell() {
+ self.selection = None;
+ }
+ }
+ }
+
+ pub fn is_selecting(&self) -> bool {
+ self.selecting
+ }
+
pub fn resize(&mut self, cols: u16, rows: u16) {
let cols = cols.max(20);
let rows = rows.max(8);
@@ -157,9 +282,45 @@ fn read_loop(
}
/// Encode egui key events into bytes for the PTY (xterm-ish).
+///
+/// Tuned for Grok Build TUI chords (`Ctrl+P/C/D/L/V…`, `Shift+Arrow`, `Alt+V`,
+/// `Ctrl+Enter`, `Shift+Tab`) — see grok-build `03-keyboard-shortcuts.md`.
+/// Plain printable characters are left to [`egui::Event::Text`].
pub fn encode_key(key: egui::Key, modifiers: egui::Modifiers) -> Option<Vec<u8>> {
use egui::Key;
- if modifiers.ctrl {
+ let ctrl = modifiers.ctrl || modifiers.command;
+ let alt = modifiers.alt;
+ let shift = modifiers.shift;
+
+ match key {
+ Key::Enter => {
+ if ctrl {
+ // modifyOtherKeys-style Ctrl+Enter (Grok send-now)
+ return Some(b"\x1b[27;5;13~".to_vec());
+ }
+ if alt || shift {
+ // Shift/Alt+Enter — newline / multiline send in Grok
+ return Some(b"\x1b\r".to_vec());
+ }
+ return Some(vec![b'\r']);
+ }
+ Key::Tab => {
+ if shift {
+ return Some(b"\x1b[Z".to_vec()); // Backtab — cycle mode
+ }
+ return Some(vec![b'\t']);
+ }
+ Key::Backspace => return Some(vec![0x7f]),
+ Key::Escape => return Some(vec![0x1b]),
+ _ => {}
+ }
+
+ if let Some(bytes) = encode_nav_key(key, ctrl, alt, shift) {
+ return Some(bytes);
+ }
+
+ // Ctrl+letter → classic C0 (Grok: Ctrl+P palette, Ctrl+C cancel, Ctrl+D scroll, …)
+ if ctrl && !alt {
if let Some(c) = key_to_char(key) {
let b = (c.to_ascii_uppercase() as u8).wrapping_sub(b'@');
if (1..=26).contains(&b) {
@@ -170,34 +331,76 @@ pub fn encode_key(key: egui::Key, modifiers: egui::Modifiers) -> Option<Vec<u8>>
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,
+
+ // Alt+letter → ESC + char (Grok Windows image paste: Alt+V)
+ if alt && !ctrl {
+ if let Some(c) = key_to_char(key) {
+ let ch = if shift {
+ c.to_ascii_uppercase()
+ } else {
+ c
+ };
+ return Some(vec![0x1b, ch as u8]);
+ }
+ }
+
+ // Function keys (optionally with modifiers via CSI)
+ encode_fn_key(key, ctrl, alt, shift)
+}
+
+fn xterm_mod_param(ctrl: bool, alt: bool, shift: bool) -> u8 {
+ // xterm: 1 + shift(1) + alt(2) + ctrl(4)
+ 1 + (u8::from(shift)) + (u8::from(alt) * 2) + (u8::from(ctrl) * 4)
+}
+
+fn encode_nav_key(key: egui::Key, ctrl: bool, alt: bool, shift: bool) -> Option<Vec<u8>> {
+ use egui::Key;
+ let mod_n = xterm_mod_param(ctrl, alt, shift);
+ let (plain, final_ch, tilde_code): (&[u8], Option<char>, Option<u8>) = match key {
+ Key::ArrowUp => (b"\x1b[A", Some('A'), None),
+ Key::ArrowDown => (b"\x1b[B", Some('B'), None),
+ Key::ArrowRight => (b"\x1b[C", Some('C'), None),
+ Key::ArrowLeft => (b"\x1b[D", Some('D'), None),
+ Key::Home => (b"\x1b[H", Some('H'), None),
+ Key::End => (b"\x1b[F", Some('F'), None),
+ Key::PageUp => (b"\x1b[5~", None, Some(5)),
+ Key::PageDown => (b"\x1b[6~", None, Some(6)),
+ Key::Insert => (b"\x1b[2~", None, Some(2)),
+ Key::Delete => (b"\x1b[3~", None, Some(3)),
+ _ => return None,
+ };
+ if mod_n == 1 {
+ return Some(plain.to_vec());
+ }
+ if let Some(code) = tilde_code {
+ return Some(format!("\x1b[{code};{mod_n}~").into_bytes());
+ }
+ let ch = final_ch?;
+ Some(format!("\x1b[1;{mod_n}{ch}").into_bytes())
+}
+
+fn encode_fn_key(key: egui::Key, ctrl: bool, alt: bool, shift: bool) -> Option<Vec<u8>> {
+ use egui::Key;
+ let mod_n = xterm_mod_param(ctrl, alt, shift);
+ let (plain, code): (&[u8], u8) = match key {
+ Key::F1 => (b"\x1bOP", 11),
+ Key::F2 => (b"\x1bOQ", 12),
+ Key::F3 => (b"\x1bOR", 13),
+ Key::F4 => (b"\x1bOS", 14),
+ Key::F5 => (b"\x1b[15~", 15),
+ Key::F6 => (b"\x1b[17~", 17),
+ Key::F7 => (b"\x1b[18~", 18),
+ Key::F8 => (b"\x1b[19~", 19),
+ Key::F9 => (b"\x1b[20~", 20),
+ Key::F10 => (b"\x1b[21~", 21),
+ Key::F11 => (b"\x1b[23~", 23),
+ Key::F12 => (b"\x1b[24~", 24),
+ _ => return None,
+ };
+ if mod_n == 1 {
+ Some(plain.to_vec())
+ } else {
+ Some(format!("\x1b[{code};{mod_n}~").into_bytes())
}
}
@@ -233,3 +436,49 @@ fn key_to_char(key: egui::Key) -> Option<char> {
_ => return None,
})
}
+
+#[cfg(test)]
+mod encode_tests {
+ use super::*;
+ use egui::{Key, Modifiers};
+
+ #[test]
+ fn ctrl_letters_are_c0() {
+ let m = Modifiers {
+ ctrl: true,
+ ..Default::default()
+ };
+ assert_eq!(encode_key(Key::P, m), Some(vec![0x10])); // Ctrl+P palette
+ assert_eq!(encode_key(Key::C, m), Some(vec![0x03]));
+ assert_eq!(encode_key(Key::D, m), Some(vec![0x04])); // scroll, not "signal"
+ assert_eq!(encode_key(Key::L, m), Some(vec![0x0c]));
+ assert_eq!(encode_key(Key::V, m), Some(vec![0x16])); // paste chord
+ }
+
+ #[test]
+ fn shift_arrow_uses_xterm_modifier() {
+ let m = Modifiers {
+ shift: true,
+ ..Default::default()
+ };
+ assert_eq!(encode_key(Key::ArrowRight, m), Some(b"\x1b[1;2C".to_vec()));
+ }
+
+ #[test]
+ fn alt_v_is_esc_v() {
+ let m = Modifiers {
+ alt: true,
+ ..Default::default()
+ };
+ assert_eq!(encode_key(Key::V, m), Some(b"\x1bv".to_vec()));
+ }
+
+ #[test]
+ fn shift_tab_is_backtab() {
+ let m = Modifiers {
+ shift: true,
+ ..Default::default()
+ };
+ assert_eq!(encode_key(Key::Tab, m), Some(b"\x1b[Z".to_vec()));
+ }
+}
diff --git a/crates/ghidrust-gui/src/grok_term/view.rs b/crates/ghidrust-gui/src/grok_term/view.rs
index ebd6833..2aee4f8 100644
--- a/crates/ghidrust-gui/src/grok_term/view.rs
+++ b/crates/ghidrust-gui/src/grok_term/view.rs
@@ -2,7 +2,7 @@
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};
+use eframe::egui::{self, Color32, FontId, Key, Modifiers, PointerButton, Pos2, Rect, Sense, Ui, Vec2};
const FONT_SIZE: f32 = 13.0;
@@ -10,10 +10,10 @@ 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.
+/// Paint the terminal and route keyboard/text/mouse input into the PTY.
///
-/// `sticky_keys`: keep routing keys (especially Ctrl+C) after focus was granted,
-/// until the parent clears capture (Console tab / Stop).
+/// `sticky_keys`: keep routing keys 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(
@@ -39,8 +39,25 @@ pub fn show_terminal(
painter.rect_filled(response.rect, 0.0, to_color32(DEFAULT_BG));
+ let selection = session.selection;
if let Ok(grid) = session.grid().lock() {
- paint_grid(ui, &painter, &grid, origin, cell_w, cell_h, &font);
+ paint_grid(
+ ui,
+ &painter,
+ &grid,
+ origin,
+ cell_w,
+ cell_h,
+ &font,
+ selection.as_ref(),
+ );
+ }
+
+ handle_pointer(ui, &response, session, origin, cell_w, cell_h, cols, rows);
+
+ if session.copied_flash_visible(ui.ctx()) {
+ paint_copied_toast(&painter, response.rect);
+ ui.ctx().request_repaint();
}
if request_focus || response.clicked() {
@@ -65,8 +82,6 @@ pub fn show_terminal(
}
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);
@@ -79,6 +94,119 @@ pub fn show_terminal(
focused || response.hovered() || sticky_keys
}
+fn pos_to_cell(
+ pos: Pos2,
+ origin: Pos2,
+ cell_w: f32,
+ cell_h: f32,
+ cols: u16,
+ rows: u16,
+) -> (usize, usize) {
+ let col = ((pos.x - origin.x) / cell_w).floor() as i32;
+ let row = ((pos.y - origin.y) / cell_h).floor() as i32;
+ (
+ col.clamp(0, cols as i32 - 1) as usize,
+ row.clamp(0, rows as i32 - 1) as usize,
+ )
+}
+
+fn handle_pointer(
+ ui: &mut Ui,
+ response: &egui::Response,
+ session: &mut GrokTermSession,
+ origin: Pos2,
+ cell_w: f32,
+ cell_h: f32,
+ cols: u16,
+ rows: u16,
+) {
+ // Scroll wheel → clear stale host highlight, then Grok scrollback.
+ if response.hovered() {
+ let scroll = ui.input(|i| i.smooth_scroll_delta.y);
+ if scroll.abs() > 0.5 {
+ session.clear_selection();
+ let steps = (scroll.abs() / cell_h).ceil().max(1.0) as usize;
+ let up = scroll > 0.0;
+ for _ in 0..steps.min(12) {
+ let btn = if up { 64 } else { 65 };
+ let (c, r) = ui
+ .input(|i| i.pointer.hover_pos())
+ .map(|p| pos_to_cell(p, origin, cell_w, cell_h, cols, rows))
+ .unwrap_or((0, 0));
+ session.write_bytes(
+ format!("\x1b[<{};{};{}M", btn, c + 1, r + 1).as_bytes(),
+ );
+ }
+ }
+ }
+
+ let Some(pointer) = response.interact_pointer_pos() else {
+ if session.is_selecting() && !ui.input(|i| i.pointer.any_down()) {
+ finish_host_selection(ui, session);
+ }
+ return;
+ };
+ let cell = pos_to_cell(pointer, origin, cell_w, cell_h, cols, rows);
+
+ // Right-click: copy+clear selection if any, else Ctrl+V paste into Grok.
+ if response.secondary_clicked() {
+ if !session.copy_selection_and_clear(ui.ctx()) {
+ session.write_bytes(&[0x16]);
+ }
+ return;
+ }
+
+ if response.drag_started_by(PointerButton::Primary) {
+ session.begin_selection(cell.0, cell.1);
+ }
+ if session.is_selecting() && response.dragged_by(PointerButton::Primary) {
+ session.update_selection(cell.0, cell.1);
+ }
+ if response.drag_stopped_by(PointerButton::Primary) {
+ let was_drag = session
+ .selection
+ .is_some_and(|s| !s.is_empty_cell());
+ if was_drag {
+ finish_host_selection(ui, session);
+ } else {
+ // Plain click elsewhere — drop highlight; forward click to Grok.
+ session.clear_selection();
+ let (c, r) = (cell.0 + 1, cell.1 + 1);
+ session.write_bytes(format!("\x1b[<0;{c};{r}M").as_bytes());
+ session.write_bytes(format!("\x1b[<0;{c};{r}m").as_bytes());
+ }
+ }
+}
+
+fn finish_host_selection(ui: &mut Ui, session: &mut GrokTermSession) {
+ session.end_selection();
+ // Auto-copy on release, flash "Copied", clear highlight.
+ let _ = session.copy_selection_and_clear(ui.ctx());
+}
+
+fn paint_copied_toast(painter: &egui::Painter, term_rect: Rect) {
+ let label = "Copied";
+ let pad = Vec2::new(10.0, 6.0);
+ let font = FontId::proportional(13.0);
+ let galley = painter.layout_no_wrap(label.to_owned(), font, Color32::WHITE);
+ let size = galley.size() + pad * 2.0;
+ let origin = Pos2::new(
+ term_rect.max.x - size.x - 10.0,
+ term_rect.min.y + 10.0,
+ );
+ let rect = Rect::from_min_size(origin, size);
+ painter.rect_filled(
+ rect,
+ 4.0,
+ Color32::from_rgba_unmultiplied(0x1B, 0x5E, 0x20, 220),
+ );
+ painter.galley(
+ origin + pad,
+ galley,
+ Color32::WHITE,
+ );
+}
+
fn paint_grid(
ui: &Ui,
painter: &egui::Painter,
@@ -87,6 +215,7 @@ fn paint_grid(
cell_w: f32,
cell_h: f32,
font: &FontId,
+ selection: Option<&super::session::TermSelection>,
) {
let cols = grid.cols();
let rows = grid.rows();
@@ -117,12 +246,16 @@ fn paint_grid(
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 selection.is_some_and(|s| s.contains(col, row)) {
+ painter.rect_filled(
+ rect,
+ 0.0,
+ Color32::from_rgba_unmultiplied(0x26, 0x4F, 0x78, 160),
+ );
+ }
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))
});
@@ -166,8 +299,6 @@ fn visible_cursor(col: usize, row: usize, cols: usize, rows: usize) -> (usize, u
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))
}
@@ -179,74 +310,93 @@ fn ui_time_ms() -> u64 {
}
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;
+ // egui remaps Ctrl+C → Copy and Ctrl+V → Paste. When a host selection
+ // exists, Copy means clipboard; otherwise Copy is Grok's Ctrl+C (0x03).
+ let mut paste: Option<String> = None;
+ let mut copy_event = false;
+ let has_sel = session
+ .selection
+ .is_some_and(|s| !s.is_empty_cell());
+ ui.input_mut(|i| {
i.events.retain(|ev| match ev {
+ egui::Event::Paste(s) => {
+ paste = Some(s.clone());
+ false
+ }
egui::Event::Copy | egui::Event::Cut => {
- send_etx = true;
+ copy_event = 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]);
+ let ctrl_shift = Modifiers {
+ ctrl: true,
+ shift: true,
+ ..Modifiers::NONE
+ };
+ for key in [
+ Key::C,
+ Key::V,
+ Key::D,
+ Key::L,
+ Key::P,
+ Key::M,
+ Key::O,
+ Key::S,
+ Key::G,
+ Key::T,
+ Key::B,
+ Key::E,
+ Key::F,
+ Key::J,
+ Key::K,
+ Key::U,
+ Key::X,
+ Key::I,
+ Key::A,
+ Key::Z,
+ Key::Enter,
+ Key::Tab,
+ Key::Insert,
+ ] {
+ let _ = i.consume_key(Modifiers::CTRL, key);
+ let _ = i.consume_key(Modifiers::COMMAND, key);
+ let _ = i.consume_key(Modifiers::ALT, key);
+ let _ = i.consume_key(ctrl_shift, key);
}
});
+ if let Some(text) = paste.as_ref().filter(|t| !t.is_empty()) {
+ session.write_bytes(text.as_bytes());
+ session.clear_selection();
+ }
+
+ // Ctrl+Shift+C or Copy with selection → clipboard (do not interrupt Grok).
+ let force_clipboard = ui.input(|i| {
+ (i.modifiers.ctrl || i.modifiers.command)
+ && i.modifiers.shift
+ && i.key_pressed(Key::C)
+ });
+ if (copy_event && has_sel) || force_clipboard {
+ if session.copy_selection_and_clear(ui.ctx()) {
+ return;
+ }
+ }
+ if copy_event {
+ session.write_bytes(&[0x03]);
+ }
+
+ let pasted = paste.as_ref().is_some_and(|t| !t.is_empty());
ui.input(|i| {
for ev in &i.events {
match ev {
egui::Event::Text(t) => {
if t != "\n" && t != "\r" && t != "\t" {
+ // Typing / Grok keyscroll must not leave a floating highlight.
+ if !session.is_selecting() {
+ session.clear_selection();
+ }
session.write_bytes(t.as_bytes());
}
}
@@ -256,12 +406,31 @@ fn handle_input(ui: &mut Ui, session: &mut GrokTermSession) {
modifiers,
..
} => {
- if (modifiers.ctrl || modifiers.command)
- && matches!(key, Key::C | Key::D | Key::Z | Key::L)
- {
+ let ctrl = modifiers.ctrl || modifiers.command;
+ if copy_event && ctrl && *key == Key::C {
+ continue;
+ }
+ if force_clipboard && ctrl && *key == Key::C {
+ continue;
+ }
+ if pasted && ctrl && *key == Key::V {
+ continue;
+ }
+ // Ctrl+Insert → copy selection
+ if ctrl && *key == Key::Insert && has_sel {
+ let _ = session.copy_selection_and_clear(ui.ctx());
+ continue;
+ }
+ // Shift+Insert → paste (terminal classic)
+ if modifiers.shift && *key == Key::Insert {
+ session.clear_selection();
+ session.write_bytes(&[0x16]);
continue;
}
if let Some(bytes) = encode_key(*key, *modifiers) {
+ if !session.is_selecting() {
+ session.clear_selection();
+ }
session.write_bytes(&bytes);
}
}
diff --git a/crates/ghidrust-gui/src/layouts.rs b/crates/ghidrust-gui/src/layouts.rs
index 57bf6e0..f7de12b 100644
--- a/crates/ghidrust-gui/src/layouts.rs
+++ b/crates/ghidrust-gui/src/layouts.rs
@@ -1,18 +1,13 @@
//! Ghidrust GUI · Phase H (M8) — layout persistence + Configure dialog.
//!
//! Ghidra's `docking` framework lets users move / tab / float providers
-//! and save the result as a `.tool` XML preset. Ghidrust ships with
-//! floating `egui::Window` panes today (full `egui_dock` docking is a
-//! separate Phase H+ landing); this module gives users maximum-visible
-//! parity by:
+//! and save the result as a `.tool` XML preset. Ghidrust persists:
//!
-//! - persisting per-pane visibility + tool preferences to
+//! - per-pane visibility + tool preferences to
//! `%APPDATA%/ghidrust/layouts/<name>.tool.json`
-//! - listing every plugin (all compile-time in Ghidrust) in a Configure
-//! dialog so users can see the parity surface
-//!
-//! Full drag-tabbed-floating docking arrives with `egui_dock` — the plan
-//! documents that as the residual deferral for M8.
+//! - the center `egui_dock` tree (`dock_tree`) plus a legacy `center`
+//! shim string for older layouts
+//! - a read-only Configure dialog listing every compile-time plugin
//!
//! Extracted per `dev/MODULARIZATION_PLAN.md` — new UI panes land here
//! instead of piling into `main.rs`.
@@ -25,15 +20,20 @@ use std::path::PathBuf;
///
/// `open_panes` uses pane ids (short strings) so old snapshots decode after
/// panes are renamed (unknown ids are ignored on load).
-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct SavedLayout {
pub name: String,
/// Pane-id → open bit.
pub open_panes: BTreeMap<String, bool>,
/// Dock checkbox states (`project_tree`, `program_tree`, `symbol_tree`, `console`).
pub docks: BTreeMap<String, bool>,
- /// Center tab (`overview` / `listing` / `decompiler` / `datatypes`).
+ /// Legacy center-tab shim (`overview` / `listing` / `decompiler` / `datatypes`).
+ /// Still written so older readers / tests keep working; prefer `dock_tree`.
pub center: String,
+ /// Serialized `egui_dock::DockState<DockTab>` (serde feature). Absent on
+ /// layouts saved before center docking landed.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub dock_tree: Option<serde_json::Value>,
/// Theme (`dark` / `light`).
pub theme: String,
/// Free-form comment shown in Configure dialog.
@@ -305,6 +305,7 @@ mod tests {
open_panes: [("pane_bookmarks".to_string(), true)].into_iter().collect(),
docks: [("console".to_string(), true)].into_iter().collect(),
center: "listing".into(),
+ dock_tree: None,
theme: "dark".into(),
comment: String::new(),
};
@@ -313,6 +314,21 @@ mod tests {
assert_eq!(back, l);
}
+ #[test]
+ fn legacy_layout_without_dock_tree_still_deserializes() {
+ let text = r#"{
+ "name": "old",
+ "open_panes": {},
+ "docks": {},
+ "center": "decompiler",
+ "theme": "dark",
+ "comment": ""
+ }"#;
+ let back: SavedLayout = serde_json::from_str(text).unwrap();
+ assert_eq!(back.center, "decompiler");
+ assert!(back.dock_tree.is_none());
+ }
+
#[test]
fn sanitize_strips_path_seps() {
assert_eq!(sanitize("a/b\\c*d"), "a_b_c_d");
diff --git a/crates/ghidrust-gui/src/main.rs b/crates/ghidrust-gui/src/main.rs
index 74953ce..886b158 100644
--- a/crates/ghidrust-gui/src/main.rs
+++ b/crates/ghidrust-gui/src/main.rs
@@ -2,12 +2,13 @@
//! 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 dock_tabs;
mod entropy;
mod events;
mod graphs;
+mod grok_term;
mod icons;
mod layouts;
mod menu_actions;
@@ -15,8 +16,11 @@ mod nav;
mod panes;
mod register_manager;
mod scripts;
+mod tool_panes;
+use dock_tabs::DockTab;
use eframe::egui::{self, Color32, Visuals};
+use egui_dock::{DockArea, DockState, Style as DockStyle, TabViewer};
use ghidrust_core::{
analyzer_catalog, analyzer_supports_gpu, disassemble_range, load_path, m3_tokens,
set_preferred_bulk_mode, xrefs_from, xrefs_to, AnalysisRunReport, AnalyzerInfo, AnalyzerOutput,
@@ -183,6 +187,8 @@ fn main() -> eframe::Result<()> {
)
}
+/// Legacy focused-center shim (kept for tests + `.tool.json` `center` field).
+/// The live layout is `center_dock` (`egui_dock`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CenterPane {
/// File summary + analysis counts (default after open/analyze).
@@ -192,6 +198,50 @@ enum CenterPane {
DataTypes,
}
+impl From<DockTab> for CenterPane {
+ fn from(tab: DockTab) -> Self {
+ match tab {
+ DockTab::Overview => CenterPane::Overview,
+ DockTab::Listing => CenterPane::Listing,
+ DockTab::Decompiler => CenterPane::Decompiler,
+ DockTab::DataTypes => CenterPane::DataTypes,
+ }
+ }
+}
+
+impl From<CenterPane> for DockTab {
+ fn from(pane: CenterPane) -> Self {
+ match pane {
+ CenterPane::Overview => DockTab::Overview,
+ CenterPane::Listing => DockTab::Listing,
+ CenterPane::Decompiler => DockTab::Decompiler,
+ CenterPane::DataTypes => DockTab::DataTypes,
+ }
+ }
+}
+
+/// Renders center dock tabs by forwarding into `GhidrustApp` pane UIs.
+struct CenterTabViewer<'a> {
+ app: &'a mut GhidrustApp,
+}
+
+impl TabViewer for CenterTabViewer<'_> {
+ type Tab = DockTab;
+
+ fn title(&mut self, tab: &mut Self::Tab) -> egui::WidgetText {
+ tab.title().into()
+ }
+
+ fn ui(&mut self, ui: &mut egui::Ui, tab: &mut Self::Tab) {
+ match *tab {
+ DockTab::Overview => self.app.ui_overview(ui),
+ DockTab::Listing => self.app.ui_listing_pane(ui),
+ DockTab::Decompiler => self.app.ui_decompiler_pane(ui),
+ DockTab::DataTypes => self.app.ui_dtm_pane(ui),
+ }
+ }
+}
+
/// Root UI state bound to real analysis core (not a mock dataset).
pub struct GhidrustApp {
path_input: String,
@@ -210,7 +260,10 @@ pub struct GhidrustApp {
last_analyzers_run: Vec<String>,
analyzer_enabled: Vec<bool>,
analyzer_infos: Vec<AnalyzerInfo>,
+ /// Legacy focused-center shim (synced from `center_dock`).
center: CenterPane,
+ /// IDE-style dock tree for Listing / Overview / Decompiler / DTM.
+ center_dock: DockState<DockTab>,
show_project_tree: bool,
show_program_tree: bool,
show_symbol_tree: bool,
@@ -292,6 +345,8 @@ pub struct GhidrustApp {
symbol_table_filter: String,
/// Filter for Defined Strings window.
defined_strings_filter: String,
+ /// Defined Strings encoding filter: `"all"` | `"ascii"` | `"utf16le"`.
+ defined_strings_encoding: String,
/// Phase B (M2) — plugin-event bus (Ghidra `PluginEvent` analog).
event_bus: EventBus,
/// Phase B (M2) — tokenised decompiler cache (rebuilt after every refresh_decompiler_at).
@@ -355,6 +410,8 @@ pub struct GhidrustApp {
symbol_refs_filter: String,
/// Symbol References focus (target VA) — set from Symbol Table row.
symbol_refs_target: Option<u64>,
+ /// Hide IL2CPP resolve-stub source rows (`ghidrust_il2cpp::is_resolve_stub_va`).
+ symbol_refs_hide_stubs: bool,
/// Equates Table filters + edit dialog.
equates_filter: String,
equates_selected: Option<(String, i64)>,
@@ -421,9 +478,15 @@ pub struct GhidrustApp {
current_layout_name: String,
// ── Grok Build agent console (Option C: ACP sidecar) ───────────────
/// Per-window Grok pane state (session, transcript, install prompts, mode).
- /// One project per window means one session at a time; audit + MCP config
- /// are written to `<project>/.grok/` on session start.
+ /// One project per window means one session at a time; skill is auto-wired
+ /// into `<project>/.grok/skills/` on project open; MCP/context on Start.
grok_pane: agent_pane::GrokPaneState,
+ // ── Agent Friction Closure §13 — tool panes ─────────────────────────
+ /// Session state for IL2CPP Metadata/Methods/ICalls, Install Inventory,
+ /// File System Browser, Analysis Artifacts, and the GPU Decompile dialog.
+ tool_panes: tool_panes::ToolPanesState,
+ /// Analysis → GPU Decompile… dialog visibility.
+ show_gpu_decompile_dialog: bool,
}
/// Phase D (M4) — Checksum Generator report (Ghidra `ComputeChecksumsPlugin`).
@@ -726,7 +789,8 @@ impl GhidrustApp {
last_analyzers_run: Vec::new(),
analyzer_enabled: enabled,
analyzer_infos: infos,
- center: CenterPane::Overview,
+ center: CenterPane::Listing,
+ center_dock: dock_tabs::default_dock_state(),
show_project_tree: true,
show_program_tree: true,
show_symbol_tree: true,
@@ -783,6 +847,7 @@ impl GhidrustApp {
functions_window_filter: String::new(),
symbol_table_filter: String::new(),
defined_strings_filter: String::new(),
+ defined_strings_encoding: "all".into(),
event_bus: EventBus::new(),
decomp_lines: Vec::new(),
decomp_cross_line: None,
@@ -824,6 +889,7 @@ impl GhidrustApp {
bytes_pane_rows: 24,
symbol_refs_filter: String::new(),
symbol_refs_target: None,
+ symbol_refs_hide_stubs: false,
equates_filter: String::new(),
equates_selected: None,
show_equate_dialog: false,
@@ -873,6 +939,8 @@ impl GhidrustApp {
layouts_cached: Vec::new(),
current_layout_name: String::new(),
grok_pane: agent_pane::GrokPaneState::new(),
+ tool_panes: tool_panes::ToolPanesState::default(),
+ show_gpu_decompile_dialog: false,
}
}
@@ -1004,6 +1072,25 @@ impl GhidrustApp {
self.decomp_lift_ratio
}
+ /// Focus a center dock tab. Listing/Decompiler prefer a side-by-side split.
+ fn focus_center_tab(&mut self, tab: DockTab) {
+ match tab {
+ DockTab::Listing | DockTab::Decompiler => {
+ dock_tabs::ensure_side_by_side(&mut self.center_dock, tab);
+ }
+ DockTab::Overview | DockTab::DataTypes => {
+ dock_tabs::focus_tab(&mut self.center_dock, tab);
+ }
+ }
+ self.center = tab.into();
+ }
+
+ fn sync_center_from_dock(&mut self) {
+ self.center = DockTab::from_id(dock_tabs::active_center_id(&self.center_dock))
+ .unwrap_or(DockTab::Overview)
+ .into();
+ }
+
/// Symbol Tree / Navigation: focus a function entry in Listing and update Decompiler.
pub fn focus_function(&mut self, entry: u64) {
let addr = format!("{entry:#x}");
@@ -1014,7 +1101,7 @@ impl GhidrustApp {
}
self.focused_function_entry = Some(entry);
self.refresh_decompiler_at(entry);
- self.center = CenterPane::Decompiler;
+ self.focus_center_tab(DockTab::Decompiler);
let name = self
.program
.as_ref()
@@ -1872,7 +1959,7 @@ impl GhidrustApp {
self.listing.len()
);
self.log(self.status.clone());
- self.center = CenterPane::Listing;
+ self.focus_center_tab(DockTab::Listing);
}
/// Navigation → Go To Address.
@@ -1880,7 +1967,7 @@ impl GhidrustApp {
pub fn goto_address_str(&mut self, s: &str) -> Result<(), String> {
let va = parse_address(s)?;
self.listing_focus_va = Some(va);
- self.center = CenterPane::Listing;
+ self.focus_center_tab(DockTab::Listing);
if let Some(i) = listing_index_at_or_before(&self.listing, va) {
self.push_selection_undo();
@@ -1938,7 +2025,7 @@ impl GhidrustApp {
/// Navigation → Go To entry.
pub fn goto_entry(&mut self) {
- self.center = CenterPane::Listing;
+ self.focus_center_tab(DockTab::Listing);
if let Some(prog) = &self.program {
if let Some(e) = prog.entry {
let _ = self.goto_address_str(&format!("{e:#x}"));
@@ -2511,7 +2598,7 @@ impl GhidrustApp {
let _ = self.save_results();
self.log("Results saved to project (results/ + exports/).");
}
- self.center = CenterPane::Overview;
+ self.focus_center_tab(DockTab::Overview);
self.show_symbol_tree = true;
// Function list / names may have changed — drop cache and re-seed Stage-0.
self.clear_decompiler_cache();
@@ -2613,6 +2700,7 @@ impl GhidrustApp {
self.show_startup_picker = false;
self.project = Some(p);
self.active_file_id = None;
+ self.ensure_project_skill_wired();
Ok(())
}
@@ -2635,13 +2723,40 @@ impl GhidrustApp {
// Auto-open active file if any
if let Some(id) = p.meta.active_id.clone() {
self.project = Some(p);
+ self.ensure_project_skill_wired();
let _ = self.open_project_file(&id);
} else {
self.project = Some(p);
+ self.ensure_project_skill_wired();
}
Ok(())
}
+ /// Auto-install embedded (or workspace) skill into the open project so the
+ /// Grok Start checklist Skill row is green before the user clicks Start.
+ fn ensure_project_skill_wired(&mut self) {
+ let Some(root) = self.project.as_ref().map(|p| p.root.clone()) else {
+ return;
+ };
+ let (_body, skill_source) = load_skill_body();
+ // Reset so a new project root always re-attempts wire.
+ self.grok_pane.skill_wired_root = None;
+ agent_pane::ensure_skill_for_project(
+ &mut self.grok_pane,
+ &root,
+ skill_source.as_deref(),
+ );
+ if let Some(err) = &self.grok_pane.skill_wire_error {
+ self.log_error(err.clone());
+ } else if let Some(path) = self
+ .project
+ .as_ref()
+ .map(|p| ghidrust_agent::project_skill_path(&p.root))
+ {
+ self.log(format!("Agent skill ready at {}", path.display()));
+ }
+ }
+
pub fn import_into_project(&mut self) -> Result<(), String> {
let path = self.path_input.trim();
if path.is_empty() {
@@ -2746,7 +2861,7 @@ impl GhidrustApp {
{
self.refresh_decompiler_at(va);
}
- self.center = CenterPane::Overview;
+ self.focus_center_tab(DockTab::Overview);
self.show_symbol_tree = true;
if let Some(p) = self.project.as_mut() {
let _ = p.set_active(id);
@@ -2916,9 +3031,18 @@ impl GhidrustApp {
let mut do_probe = false;
let mut start_size: Option<(u16, u16)> = None;
+ let checklist_root: Option<std::path::PathBuf> = match &self.project {
+ Some(p) => Some(p.root.clone()),
+ None => self
+ .grok_pane
+ .session
+ .as_ref()
+ .map(|s| s.project_root.clone()),
+ };
agent_pane::render_grok_pane(
ui,
&mut self.grok_pane,
+ checklist_root.as_deref(),
primary,
muted,
&mut |cols, rows| {
@@ -3095,6 +3219,79 @@ impl GhidrustApp {
Ok(())
}
+ /// Analysis → GPU Decompile… — resolve the dialog's address (containing
+ /// function honesty via `resolve_function`) then run
+ /// `ghidrust_decomp::gpu_decompile_to_file` (GPU pipeline with automatic
+ /// CPU multipass fallback outside the `gpu` feature).
+ fn run_gpu_decompile_dialog(&mut self) {
+ let dialog = &mut self.tool_panes.gpu_decompile;
+ dialog.error = None;
+ dialog.resolve = None;
+ dialog.summary = None;
+ let max_bytes: usize = dialog.max_bytes_input.trim().parse().unwrap_or(256).max(32);
+ let addr_input = dialog.addr_input.trim().to_string();
+ let Some(prog) = self.program.as_mut() else {
+ self.tool_panes.gpu_decompile.error = Some("no program loaded".into());
+ return;
+ };
+ let addr = if addr_input.is_empty() {
+ prog.entry.unwrap_or(prog.image_base)
+ } else {
+ match parse_address(&addr_input) {
+ Ok(a) => a,
+ Err(e) => {
+ self.tool_panes.gpu_decompile.error = Some(format!("bad address: {e}"));
+ return;
+ }
+ }
+ };
+ let resolve = match ghidrust_core::resolve_function(prog, addr) {
+ Ok(r) => r,
+ Err(e) => {
+ self.tool_panes.gpu_decompile.error = Some(format!("resolve_function: {e}"));
+ return;
+ }
+ };
+ if !resolve.ok {
+ self.tool_panes.gpu_decompile.resolve = Some(resolve);
+ self.tool_panes.gpu_decompile.error =
+ Some("address did not resolve to a function — see resolve_status above".into());
+ return;
+ }
+ let entry = resolve.resolved_entry.unwrap_or(addr);
+ let dump_path = std::env::temp_dir().join(format!("ghidrust-gpu-decompile-{entry:016x}.txt"));
+ match ghidrust_decomp::gpu_decompile_to_file(prog, Some(entry), &dump_path, max_bytes) {
+ Ok(rep) => {
+ let preview: String = rep.pseudo_c.chars().take(4000).collect();
+ self.tool_panes.gpu_decompile.summary = Some(tool_panes::GpuDecompileSummary {
+ backend: rep.backend,
+ device: rep.device,
+ entry: rep.entry,
+ name: rep.name,
+ ms: rep.ms,
+ device_ms: rep.device_ms,
+ pcie_upload_ms: rep.pcie_upload_ms,
+ pcie_download_ms: rep.pcie_download_ms,
+ mid_pipeline_host_reads: rep.mid_pipeline_host_reads,
+ dump_path: rep.dump_path,
+ dump_bytes: rep.dump_bytes,
+ ir_count: rep.ir_count,
+ block_count: rep.block_count,
+ pseudo_c_preview: preview,
+ });
+ self.tool_panes.gpu_decompile.resolve = Some(resolve);
+ self.log(format!(
+ "GPU Decompile · {:#x} · backend={}",
+ entry, self.tool_panes.gpu_decompile.summary.as_ref().unwrap().backend
+ ));
+ }
+ Err(e) => {
+ self.tool_panes.gpu_decompile.resolve = Some(resolve);
+ self.tool_panes.gpu_decompile.error = Some(format!("gpu_decompile_to_file: {e}"));
+ }
+ }
+ }
+
/// Menu / pane identifiers present in the shell (for structural tests).
///
/// Ghidra top-level menus (from `docking.tool.ToolConstants`):
@@ -3531,6 +3728,39 @@ impl GhidrustApp {
win.default_size(egui::vec2(640.0, 420.0))
.show(ctx, |ui| self.ui_mcp_repl_pane(ui, muted, primary));
}
+ // Agent Friction Closure §13 — tool panes (real backends).
+ PaneKind::Il2cppMetadata => {
+ win.default_size(egui::vec2(720.0, 560.0)).show(ctx, |ui| {
+ tool_panes::ui_il2cpp_metadata(ui, &mut self.tool_panes.il2cpp_meta, muted);
+ });
+ }
+ PaneKind::Il2cppMethods => {
+ let prog = self.program.as_ref();
+ win.default_size(egui::vec2(760.0, 560.0)).show(ctx, |ui| {
+ tool_panes::ui_il2cpp_methods(ui, &mut self.tool_panes.il2cpp_methods, prog, muted);
+ });
+ }
+ PaneKind::Il2cppIcalls => {
+ let prog = self.program.as_ref();
+ win.default_size(egui::vec2(760.0, 560.0)).show(ctx, |ui| {
+ tool_panes::ui_il2cpp_icalls(ui, &mut self.tool_panes.il2cpp_icalls, prog, muted);
+ });
+ }
+ PaneKind::InstallInventory => {
+ win.default_size(egui::vec2(760.0, 520.0)).show(ctx, |ui| {
+ tool_panes::ui_install_inventory(ui, &mut self.tool_panes.install_inventory, muted);
+ });
+ }
+ PaneKind::FileSystemBrowser => {
+ win.default_size(egui::vec2(720.0, 520.0)).show(ctx, |ui| {
+ tool_panes::ui_file_system_browser(ui, &mut self.tool_panes.fs_browser, muted);
+ });
+ }
+ PaneKind::AnalysisArtifacts => {
+ win.default_size(egui::vec2(820.0, 520.0)).show(ctx, |ui| {
+ tool_panes::ui_analysis_artifacts(ui, &mut self.tool_panes.artifacts, muted);
+ });
+ }
_ => {
win.show(ctx, |ui| {
panes::empty_state(ui, kind, muted);
@@ -3992,13 +4222,8 @@ impl GhidrustApp {
docks.insert("program_tree".into(), self.show_program_tree);
docks.insert("symbol_tree".into(), self.show_symbol_tree);
docks.insert("console".into(), self.show_console);
- let center = match self.center {
- CenterPane::Overview => "overview",
- CenterPane::Listing => "listing",
- CenterPane::Decompiler => "decompiler",
- CenterPane::DataTypes => "datatypes",
- }
- .to_string();
+ let center = dock_tabs::active_center_id(&self.center_dock).to_string();
+ let dock_tree = serde_json::to_value(&self.center_dock).ok();
let theme = match self.theme {
ThemeMode::Dark => "dark",
ThemeMode::Light => "light",
@@ -4009,6 +4234,7 @@ impl GhidrustApp {
open_panes,
docks,
center,
+ dock_tree,
theme,
comment: String::new(),
}
@@ -4047,12 +4273,15 @@ impl GhidrustApp {
if let Some(v) = layout.docks.get("console") {
self.show_console = *v;
}
- self.center = match layout.center.as_str() {
- "listing" => CenterPane::Listing,
- "decompiler" => CenterPane::Decompiler,
- "datatypes" => CenterPane::DataTypes,
- _ => CenterPane::Overview,
- };
+ if let Some(value) = &layout.dock_tree {
+ match serde_json::from_value::<DockState<DockTab>>(value.clone()) {
+ Ok(dock) => self.center_dock = dock,
+ Err(_) => self.center_dock = dock_tabs::from_legacy_center(&layout.center),
+ }
+ } else {
+ self.center_dock = dock_tabs::from_legacy_center(&layout.center);
+ }
+ self.sync_center_from_dock();
self.theme = match layout.theme.as_str() {
"light" => ThemeMode::Light,
_ => ThemeMode::Dark,
@@ -5294,6 +5523,40 @@ impl GhidrustApp {
{
self.refresh_decompiler_at(va);
}
+ // requested_addr vs resolved_entry (honest containing-function resolve)
+ // plus an IL2CPP `follow_stub` chip when the resolved entry classifies
+ // as a lazy resolve thunk with a populated slot.
+ if let Some(va) = self.listing_focus_va.or(self.decomp_entry) {
+ if let Some(prog) = self.program.as_mut() {
+ if let Ok(resolve) = ghidrust_core::resolve_function(prog, va) {
+ let stub_target = resolve.resolved_entry.and_then(|entry| {
+ ghidrust_il2cpp::classify_at(prog, entry)
+ .and_then(|stub| ghidrust_il2cpp::follow_stub_target(prog, &stub))
+ });
+ ui.horizontal(|ui| {
+ ui.small(format!(
+ "resolve: requested={:#x} → resolved_entry={} [{:?}]{}",
+ resolve.requested_addr,
+ resolve
+ .resolved_entry
+ .map(|e| format!("{e:#x}"))
+ .unwrap_or_else(|| "—".into()),
+ resolve.resolve_status,
+ if resolve.ambiguous { " (ambiguous)" } else { "" },
+ ));
+ if let Some(target) = stub_target {
+ ui.small(
+ egui::RichText::new(format!("follow_stub → {target:#x}"))
+ .color(Color32::from_rgb(0xFB, 0xC0, 0x2D)),
+ )
+ .on_hover_text(
+ "ghidrust_il2cpp::follow_stub_target — cached slot for this IL2CPP resolve thunk",
+ );
+ }
+ });
+ }
+ }
+ }
// Header row: stage + entry + Commit/Rename right-click hints.
ui.horizontal(|ui| {
if !self.decomp_status.is_empty() {
@@ -5747,11 +6010,23 @@ impl GhidrustApp {
let mut rename: Option<(usize, String)> = None;
let mut toggle: Option<(usize, char)> = None;
+ let notes_by_section: BTreeMap<String, Vec<String>> = self
+ .program
+ .as_ref()
+ .map(|p| {
+ let mut m: BTreeMap<String, Vec<String>> = BTreeMap::new();
+ for n in ghidrust_core::section_notes_for(p) {
+ m.entry(n.section.clone()).or_default().push(n.message);
+ }
+ m
+ })
+ .unwrap_or_default();
+
egui::ScrollArea::both()
.id_salt("memmap_scroll")
.show(ui, |ui| {
egui::Grid::new("memory_map_grid")
- .num_columns(8)
+ .num_columns(9)
.striped(true)
.show(ui, |ui| {
ui.strong("Name");
@@ -5761,6 +6036,7 @@ impl GhidrustApp {
ui.strong("R");
ui.strong("W");
ui.strong("X");
+ ui.strong("Notes");
ui.strong("");
ui.end_row();
let blocks: Vec<(String, u64, u64, bool, bool, bool)> = self
@@ -5813,12 +6089,22 @@ impl GhidrustApp {
if ui.checkbox(&mut xb, "").changed() {
toggle = Some((i, 'X'));
}
+ let notes = notes_by_section.get(name.trim_end_matches('\0'));
+ match notes {
+ Some(msgs) => {
+ let joined = msgs.join(" · ");
+ ui.small(egui::RichText::new("⚠ notes").color(muted))
+ .on_hover_text(joined);
+ }
+ None => {
+ ui.small(egui::RichText::new("—").color(muted));
+ }
+ }
if ui.small_button("Delete").clicked() {
delete = Some(i);
}
ui.end_row();
}
- let _ = muted;
});
});
@@ -6013,13 +6299,23 @@ impl GhidrustApp {
.desired_width(280.0)
.hint_text("Substring…"),
);
+ ui.label("Encoding:");
+ egui::ComboBox::from_id_salt("defined_strings_encoding_combo")
+ .selected_text(self.defined_strings_encoding.clone())
+ .show_ui(ui, |ui| {
+ for enc in ["all", "ascii", "utf16le"] {
+ ui.selectable_value(&mut self.defined_strings_encoding, enc.into(), enc);
+ }
+ });
});
let q = self.defined_strings_filter.to_ascii_lowercase();
- let rows: Vec<(u64, String)> = self
+ let enc_filter = self.defined_strings_encoding.clone();
+ let rows: Vec<(u64, String, String)> = self
.strings
.iter()
.filter(|s| q.is_empty() || s.value.to_ascii_lowercase().contains(&q))
- .map(|s| (s.va, s.value.clone()))
+ .filter(|s| enc_filter == "all" || s.encoding == enc_filter)
+ .map(|s| (s.va, s.value.clone(), s.encoding.clone()))
.collect();
ui.small(format!("{} / {} strings", rows.len(), self.strings.len()));
egui::ScrollArea::vertical()
@@ -6027,20 +6323,22 @@ impl GhidrustApp {
.max_height(400.0)
.show(ui, |ui| {
egui::Grid::new("defined_strings_grid")
- .num_columns(2)
+ .num_columns(3)
.striped(true)
.show(ui, |ui| {
ui.strong("Address");
+ ui.strong("Encoding");
ui.strong("String");
ui.end_row();
let mut goto: Option<u64> = None;
- for (va, s) in &rows {
+ for (va, s, enc) in &rows {
if ui
.link(egui::RichText::new(format!("{va:#x}")).monospace())
.clicked()
{
goto = Some(*va);
}
+ ui.monospace(enc.clone());
let val: String = s.chars().take(80).collect();
ui.monospace(val);
ui.end_row();
@@ -6468,6 +6766,8 @@ impl GhidrustApp {
if ui.button("Use cursor").clicked() {
self.symbol_refs_target = self.listing_focus_va;
}
+ ui.checkbox(&mut self.symbol_refs_hide_stubs, "Hide resolve stubs")
+ .on_hover_text("ghidrust_il2cpp::is_resolve_stub_va — hide IL2CPP lazy resolve thunks");
});
ui.separator();
let Some(target) = target else {
@@ -6476,7 +6776,17 @@ impl GhidrustApp {
};
let refs = self.xrefs_to_va(target);
let q = self.symbol_refs_filter.to_ascii_lowercase();
- let rows: Vec<XRef> = refs
+ let hide_stubs = self.symbol_refs_hide_stubs;
+ let classify = |prog: &Program, va: u64| -> Option<String> {
+ ghidrust_il2cpp::classify_at(prog, va).map(|stub| {
+ stub.icall_name
+ .clone()
+ .map(|n| format!("il2cpp_stub: {n}"))
+ .unwrap_or_else(|| "il2cpp_stub".into())
+ })
+ };
+ let prog_ref = self.program.as_ref();
+ let rows: Vec<(XRef, Option<String>)> = refs
.into_iter()
.filter(|r| {
if q.is_empty() {
@@ -6486,6 +6796,18 @@ impl GhidrustApp {
|| format!("{:#x}", r.from).contains(&q)
|| r.kind.contains(&q)
})
+ .filter_map(|r| {
+ let cls = prog_ref.and_then(|p| classify(p, r.from));
+ let is_stub = cls.is_some()
+ || prog_ref
+ .map(|p| ghidrust_il2cpp::is_resolve_stub_va(p, r.from))
+ .unwrap_or(false);
+ if hide_stubs && is_stub {
+ None
+ } else {
+ Some((r, cls))
+ }
+ })
.collect();
let label_at = |va: u64| {
self.program
@@ -6501,15 +6823,16 @@ impl GhidrustApp {
.max_height(400.0)
.show(ui, |ui| {
egui::Grid::new("symbol_refs_grid")
- .num_columns(4)
+ .num_columns(5)
.striped(true)
.show(ui, |ui| {
ui.strong("From");
ui.strong("Label");
ui.strong("Kind");
+ ui.strong("Classify");
ui.strong("Preview");
ui.end_row();
- for r in &rows {
+ for (r, cls) in &rows {
if ui
.link(egui::RichText::new(format!("{:#x}", r.from)).monospace())
.clicked()
@@ -6518,6 +6841,7 @@ impl GhidrustApp {
}
ui.label(label_at(r.from));
ui.monospace(r.kind);
+ ui.small(cls.as_deref().unwrap_or("—"));
ui.label(&r.preview);
ui.end_row();
}
@@ -7211,6 +7535,27 @@ impl eframe::App for GhidrustApp {
ui.close_menu();
}
});
+ ui.separator();
+ if ui
+ .button("GPU Decompile…")
+ .on_hover_text(
+ "ghidrust_decomp::gpu_decompile_to_file · GPU pipeline with CPU multipass fallback",
+ )
+ .clicked()
+ {
+ if self.tool_panes.gpu_decompile.addr_input.trim().is_empty() {
+ if let Some(prog) = &self.program {
+ if let Some(e) = self.listing_focus_va.or(prog.entry) {
+ self.tool_panes.gpu_decompile.addr_input = format!("{e:#x}");
+ }
+ }
+ }
+ if self.tool_panes.gpu_decompile.max_bytes_input.trim().is_empty() {
+ self.tool_panes.gpu_decompile.max_bytes_input = "256".into();
+ }
+ self.show_gpu_decompile_dialog = true;
+ ui.close_menu();
+ }
});
ui.menu_button("Navigation", |ui| {
if ui.add_enabled(self.can_nav_back(), egui::Button::new("Back")).clicked() {
@@ -7433,12 +7778,35 @@ impl eframe::App for GhidrustApp {
ui.checkbox(&mut self.show_symbol_tree, "Symbol Tree (dock)");
ui.checkbox(&mut self.show_console, "Console (dock)");
ui.separator();
- // Center tabs.
+ // Center dock tabs (Listing/Decompiler prefer side-by-side).
ui.label(egui::RichText::new("Center Tabs").small().weak());
- ui.selectable_value(&mut self.center, CenterPane::Overview, "Overview");
- ui.selectable_value(&mut self.center, CenterPane::Listing, "Listing");
- ui.selectable_value(&mut self.center, CenterPane::Decompiler, "Decompiler");
- ui.selectable_value(&mut self.center, CenterPane::DataTypes, "Data Type Manager");
+ if ui
+ .selectable_label(self.center == CenterPane::Overview, "Overview")
+ .clicked()
+ {
+ self.focus_center_tab(DockTab::Overview);
+ }
+ if ui
+ .selectable_label(self.center == CenterPane::Listing, "Listing")
+ .clicked()
+ {
+ self.focus_center_tab(DockTab::Listing);
+ }
+ if ui
+ .selectable_label(self.center == CenterPane::Decompiler, "Decompiler")
+ .clicked()
+ {
+ self.focus_center_tab(DockTab::Decompiler);
+ }
+ if ui
+ .selectable_label(
+ self.center == CenterPane::DataTypes,
+ "Data Type Manager",
+ )
+ .clicked()
+ {
+ self.focus_center_tab(DockTab::DataTypes);
+ }
ui.separator();
// Full Ghidra CodeBrowser provider catalog (floating windows).
// Sorted alphabetically by title to mirror Ghidra's Window menu.
@@ -7977,90 +8345,118 @@ impl eframe::App for GhidrustApp {
let muted =
Color32::from_rgb(t.on_surface_variant[0], t.on_surface_variant[1], t.on_surface_variant[2]);
let ok_green = Color32::from_rgb(0x4C, 0xAF, 0x50);
- let root_open = {
- ui.horizontal(|ui| {
- m3_icon(ui, M3Icon::Folder, 18.0, primary);
- ui.strong(&model.project_name);
- });
- egui::CollapsingHeader::new("Project files")
- .default_open(self.project_tree_expanded)
- .show(ui, |ui| {
- ui.small(egui::RichText::new(&model.project_root).weak());
- ui.add_space(4.0);
- if model.files.is_empty() {
- ui.weak("Empty — Import a binary.");
- }
- let mut open_id: Option<String> = None;
- let mut analyze_id: Option<String> = None;
- let mut delete_id: Option<String> = None;
- let mut select_id: Option<String> = None;
- for row in &model.files {
- let selected = self.tree_selected_id.as_deref() == Some(row.id.as_str());
- let viewing = self.active_file_id.as_deref() == Some(row.id.as_str())
- && self.program.is_some();
- ui.group(|ui| {
- ui.horizontal(|ui| {
- if viewing {
- m3_icon(ui, M3Icon::PlayArrow, 14.0, primary);
- } else {
- ui.add_space(14.0);
- }
- let resp = ui.selectable_label(selected || viewing, &row.display_name);
- if resp.double_clicked() {
- open_id = Some(row.id.clone());
- } else if resp.clicked() {
- select_id = Some(row.id.clone());
+ ui.horizontal(|ui| {
+ m3_icon(ui, M3Icon::Folder, 18.0, primary);
+ ui.strong(&model.project_name);
+ });
+ // Fill remaining panel height and scroll when files overflow
+ // (same idiom as Console / working list panes).
+ let root_open = egui::ScrollArea::vertical()
+ .id_salt("project_tree_scroll")
+ .auto_shrink([false, false])
+ .show(ui, |ui| {
+ egui::CollapsingHeader::new("Project files")
+ .default_open(self.project_tree_expanded)
+ .show(ui, |ui| {
+ ui.small(egui::RichText::new(&model.project_root).weak());
+ ui.add_space(4.0);
+ if model.files.is_empty() {
+ ui.weak("Empty — Import a binary.");
}
- });
- ui.horizontal(|ui| {
- status_badge(ui, row.has_saved_analysis, ok_green, muted);
- if viewing {
- ui.small(egui::RichText::new("viewing").color(primary));
- } else if row.has_saved_analysis {
- ui.small(egui::RichText::new("double-click to open").weak());
+ let mut open_id: Option<String> = None;
+ let mut analyze_id: Option<String> = None;
+ let mut delete_id: Option<String> = None;
+ let mut select_id: Option<String> = None;
+ for row in &model.files {
+ let selected =
+ self.tree_selected_id.as_deref() == Some(row.id.as_str());
+ let viewing = self.active_file_id.as_deref()
+ == Some(row.id.as_str())
+ && self.program.is_some();
+ ui.group(|ui| {
+ ui.horizontal(|ui| {
+ if viewing {
+ m3_icon(ui, M3Icon::PlayArrow, 14.0, primary);
+ } else {
+ ui.add_space(14.0);
+ }
+ let resp = ui.selectable_label(
+ selected || viewing,
+ &row.display_name,
+ );
+ if resp.double_clicked() {
+ open_id = Some(row.id.clone());
+ } else if resp.clicked() {
+ select_id = Some(row.id.clone());
+ }
+ });
+ ui.horizontal(|ui| {
+ status_badge(
+ ui,
+ row.has_saved_analysis,
+ ok_green,
+ muted,
+ );
+ if viewing {
+ ui.small(
+ egui::RichText::new("viewing").color(primary),
+ );
+ } else if row.has_saved_analysis {
+ ui.small(
+ egui::RichText::new("double-click to open")
+ .weak(),
+ );
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.with_layout(
+ egui::Layout::right_to_left(egui::Align::Center),
+ |ui| {
+ if ui
+ .small_button("Delete")
+ .on_hover_text(
+ "Remove from project (confirmation)",
+ )
+ .clicked()
+ {
+ delete_id = Some(row.id.clone());
+ }
+ if ui
+ .small_button("Analyze")
+ .on_hover_text(
+ "Analysis options (analyzers + GPU)",
+ )
+ .clicked()
+ {
+ analyze_id = Some(row.id.clone());
+ }
+ if ui
+ .small_button("Open")
+ .on_hover_text(
+ "Load into Overview / Listing / Symbol Tree",
+ )
+ .clicked()
+ {
+ open_id = Some(row.id.clone());
+ }
+ },
+ );
+ });
+ ui.small(
+ egui::RichText::new(&row.imported_rel)
+ .weak()
+ .italics(),
+ );
+ });
+ ui.add_space(2.0);
}
- });
- ui.horizontal(|ui| {
- ui.with_layout(
- egui::Layout::right_to_left(egui::Align::Center),
- |ui| {
- if ui
- .small_button("Delete")
- .on_hover_text("Remove from project (confirmation)")
- .clicked()
- {
- delete_id = Some(row.id.clone());
- }
- if ui
- .small_button("Analyze")
- .on_hover_text("Analysis options (analyzers + GPU)")
- .clicked()
- {
- analyze_id = Some(row.id.clone());
- }
- if ui
- .small_button("Open")
- .on_hover_text("Load into Overview / Listing / Symbol Tree")
- .clicked()
- {
- open_id = Some(row.id.clone());
- }
- },
- );
- });
- ui.small(
- egui::RichText::new(&row.imported_rel)
- .weak()
- .italics(),
- );
- });
- ui.add_space(2.0);
- }
- (open_id, analyze_id, delete_id, select_id)
- })
- };
+ (open_id, analyze_id, delete_id, select_id)
+ })
+ })
+ .inner;
let expanded = root_open.fully_open();
- if let Some((open_id, analyze_id, delete_id, select_id)) = root_open.body_returned {
+ if let Some((open_id, analyze_id, delete_id, select_id)) = root_open.body_returned
+ {
if let Some(id) = select_id {
self.tree_selected_id = Some(id);
}
@@ -8188,6 +8584,7 @@ impl eframe::App for GhidrustApp {
let mut add_to_view: Option<String> = None;
let mut remove_from_view: Option<String> = None;
let mut set_view: Option<String> = None;
+ let mut show_all = false;
let view_filter = self.listing_view_filter.clone();
let mut render_module =
|ui: &mut egui::Ui, title: &str, indices: &[usize]| {
@@ -8266,9 +8663,37 @@ impl eframe::App for GhidrustApp {
});
};
- render_module(ui, "Code (X)", &code);
- render_module(ui, "Data (RW)", &data);
- render_module(ui, "Read‑only (R)", &rodata);
+ egui::ScrollArea::vertical()
+ .id_salt("program_tree_scroll")
+ .auto_shrink([false, false])
+ .show(ui, |ui| {
+ render_module(ui, "Code (X)", &code);
+ render_module(ui, "Data (RW)", &data);
+ render_module(ui, "Read‑only (R)", &rodata);
+
+ ui.separator();
+ ui.horizontal(|ui| {
+ if ui
+ .small_button("Show All")
+ .on_hover_text("Clear the Listing view filter")
+ .clicked()
+ {
+ show_all = true;
+ }
+ if let Some(f) = view_filter.as_ref() {
+ ui.small(format!(
+ "View filter · {} fragment(s) in view",
+ f.len()
+ ));
+ } else {
+ ui.small(
+ egui::RichText::new("View filter · full program")
+ .weak()
+ .italics(),
+ );
+ }
+ });
+ });
if let Some(va) = goto {
let _ = self.goto_address_str(&format!("{va:#x}"));
@@ -8284,29 +8709,9 @@ impl eframe::App for GhidrustApp {
s.insert(name);
self.set_listing_view(Some(s));
}
-
- ui.separator();
- ui.horizontal(|ui| {
- if ui
- .small_button("Show All")
- .on_hover_text("Clear the Listing view filter")
- .clicked()
- {
- self.listing_view_filter = None;
- }
- if let Some(f) = self.listing_view_filter.as_ref() {
- ui.small(format!(
- "View filter · {} fragment(s) in view",
- f.len()
- ));
- } else {
- ui.small(
- egui::RichText::new("View filter · full program")
- .weak()
- .italics(),
- );
- }
- });
+ if show_all {
+ self.listing_view_filter = None;
+ }
});
}
@@ -8335,6 +8740,13 @@ impl eframe::App for GhidrustApp {
});
ui.separator();
+ // Outer scroll so category headers + expanded sections aren't clipped
+ // when they exceed the dock height. Per-list ScrollAreas keep max_height
+ // so nested wheel scrolling still targets the open list.
+ egui::ScrollArea::vertical()
+ .id_salt("symbol_tree_scroll")
+ .auto_shrink([false, false])
+ .show(ui, |ui| {
// ── Ghidra `SymbolTreePlugin` category order ────────────────
// Imports · Exports · Functions · Labels · Classes · Namespaces
@@ -8543,11 +8955,35 @@ impl eframe::App for GhidrustApp {
self.rebuild_rtti_filter_cache();
let n_show = self.rtti_filtered_idx.len();
ui.small(format!("{n_show} / {rtti_n} classes (RTTI)"));
+ // `ghidrust_core::rtti_query` gives the catalog (deduped,
+ // grouped by name) view with every recovered vtable VA —
+ // `self.rtti` is the raw per-class report used for the
+ // filter cache above, so we join on name for the tooltip.
+ let vtable_vas: BTreeMap<String, Vec<u64>> = self
+ .program
+ .as_ref()
+ .and_then(|p| {
+ ghidrust_core::rtti_query(
+ p,
+ None,
+ false,
+ ghidrust_core::RttiMatchMode::Substr,
+ )
+ .ok()
+ })
+ .map(|q| {
+ q.classes
+ .into_iter()
+ .map(|c| (c.name, c.vtable_vas))
+ .collect()
+ })
+ .unwrap_or_default();
let row_h = ui.text_style_height(&egui::TextStyle::Body) + 2.0;
let idxs = self.rtti_filtered_idx.clone();
egui::ScrollArea::vertical()
.id_salt("rtti_scroll")
.auto_shrink([false, false])
+ .max_height(220.0)
.show_rows(ui, row_h, idxs.len(), |ui, range| {
for i in range {
let c = &self.rtti.classes[idxs[i]];
@@ -8555,11 +8991,20 @@ impl eframe::App for GhidrustApp {
.type_info_va
.map(|v| format!("{v:#x}"))
.unwrap_or_else(|| "—".into());
+ let vtables = vtable_vas
+ .get(&c.name)
+ .map(|vs| {
+ vs.iter()
+ .map(|v| format!("{v:#x}"))
+ .collect::<Vec<_>>()
+ .join(", ")
+ })
+ .unwrap_or_else(|| "—".into());
ui.horizontal(|ui| {
ui.monospace(&va);
ui.label(&c.name)
.on_hover_text(format!(
- "kind={} col={:?} vtable={:?}",
+ "kind={} col={:?} vtable={:?}\nvtable_vas (rtti_query)=[{vtables}]",
c.kind, c.col_va, c.vtable_va
));
});
@@ -8655,6 +9100,7 @@ impl eframe::App for GhidrustApp {
ui.small(format!("Showing first 5000 of {str_n}"));
}
});
+ });
});
}
@@ -8672,7 +9118,7 @@ impl eframe::App for GhidrustApp {
self.analysis_done_banner = None;
}
if ui.button("Open Overview").clicked() {
- self.center = CenterPane::Overview;
+ self.focus_center_tab(DockTab::Overview);
self.analysis_done_banner = None;
}
});
@@ -8681,27 +9127,16 @@ impl eframe::App for GhidrustApp {
}
egui::CentralPanel::default().show(ctx, |ui| {
- ui.horizontal(|ui| {
- ui.selectable_value(&mut self.center, CenterPane::Overview, "Overview");
- ui.selectable_value(&mut self.center, CenterPane::Listing, "Listing");
- ui.selectable_value(&mut self.center, CenterPane::Decompiler, "Decompiler");
- ui.selectable_value(&mut self.center, CenterPane::DataTypes, "Data Type Manager");
- });
- ui.separator();
- match self.center {
- CenterPane::Overview => {
- self.ui_overview(ui);
- }
- CenterPane::Listing => {
- self.ui_listing_pane(ui);
- }
- CenterPane::Decompiler => {
- self.ui_decompiler_pane(ui);
- }
- CenterPane::DataTypes => {
- self.ui_dtm_pane(ui);
- }
- }
+ // `DockArea` and the tab viewer both need `&mut self` fields — take
+ // the dock tree out so the viewer can borrow the rest of the app.
+ let mut dock = std::mem::replace(&mut self.center_dock, DockState::new(vec![]));
+ DockArea::new(&mut dock)
+ .style(DockStyle::from_egui(ui.style().as_ref()))
+ .show_close_buttons(true)
+ .show_add_buttons(false)
+ .show_inside(ui, &mut CenterTabViewer { app: self });
+ self.center_dock = dock;
+ self.sync_center_from_dock();
});
// Phase A (M1) — draw every open floating provider pane.
@@ -9203,6 +9638,51 @@ impl eframe::App for GhidrustApp {
});
}
+ // Analysis → GPU Decompile…
+ if self.show_gpu_decompile_dialog {
+ let t = m3_tokens(self.theme);
+ let muted = Color32::from_rgb(
+ t.on_surface_variant[0],
+ t.on_surface_variant[1],
+ t.on_surface_variant[2],
+ );
+ let mut close = false;
+ let mut run_clicked = false;
+ let has_program = self.program.is_some();
+ egui::Window::new("GPU Decompile")
+ .collapsible(false)
+ .resizable(true)
+ .default_width(560.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ tool_panes::ui_gpu_decompile_dialog_header(
+ ui,
+ &mut self.tool_panes.gpu_decompile,
+ muted,
+ );
+ if !has_program {
+ ui.weak("No program loaded.");
+ } else if ui.button("Resolve + Decompile").clicked() {
+ run_clicked = true;
+ }
+ tool_panes::ui_gpu_decompile_dialog_result(
+ ui,
+ &self.tool_panes.gpu_decompile,
+ muted,
+ );
+ ui.separator();
+ if ui.button("Close").clicked() {
+ close = true;
+ }
+ });
+ if run_clicked {
+ self.run_gpu_decompile_dialog();
+ }
+ if close {
+ self.show_gpu_decompile_dialog = false;
+ }
+ }
+
if self.show_analysis_dialog && self.analysis_job.is_none() {
let t = m3_tokens(self.theme);
let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
@@ -10703,7 +11183,7 @@ mod tests {
app.toggle_pane(PaneKind::Bookmarks, true);
app.toggle_pane(PaneKind::MemoryMap, true);
app.debugger_open.insert(DebuggerPane::Targets, true);
- app.center = CenterPane::Decompiler;
+ app.focus_center_tab(DockTab::Decompiler);
app.show_console = false;
app.save_layout_named("myTest").expect("save layout");
@@ -10711,7 +11191,7 @@ mod tests {
app.toggle_pane(PaneKind::Bookmarks, false);
app.toggle_pane(PaneKind::MemoryMap, false);
app.debugger_open.insert(DebuggerPane::Targets, false);
- app.center = CenterPane::Overview;
+ app.focus_center_tab(DockTab::Overview);
app.show_console = true;
app.restore_layout_named("myTest").expect("restore layout");
@@ -10719,6 +11199,7 @@ mod tests {
assert!(app.is_pane_open(PaneKind::MemoryMap));
assert_eq!(app.debugger_open.get(&DebuggerPane::Targets), Some(&true));
assert_eq!(app.center, CenterPane::Decompiler);
+ assert!(app.center_dock.find_tab(&DockTab::Decompiler).is_some());
assert!(!app.show_console);
let _ = std::fs::remove_dir_all(&dir);
diff --git a/crates/ghidrust-gui/src/panes.rs b/crates/ghidrust-gui/src/panes.rs
index e624d6c..825747d 100644
--- a/crates/ghidrust-gui/src/panes.rs
+++ b/crates/ghidrust-gui/src/panes.rs
@@ -53,6 +53,19 @@ pub enum PaneKind {
TextEditor,
// Project Window providers (Ghidrust fuses Project + CodeBrowser today).
ProjectTree,
+ // ── Agent Friction Closure §13 — tool panes (real backends, no stubs) ──
+ /// `global-metadata.dat` parser (ghidrust-il2cpp) — types / methods / images.
+ Il2cppMetadata,
+ /// CodeRegistration correlation (metadata method index → binary VA).
+ Il2cppMethods,
+ /// Unity native icall name‖fn table pairing.
+ Il2cppIcalls,
+ /// Folder → PE inventory (VERSIONINFO catalog) via `ghidrust_core::inventory`.
+ InstallInventory,
+ /// Bounded directory tree browser via `ghidrust_core::tree_index`.
+ FileSystemBrowser,
+ /// Spilled analysis artifact catalog + preview via `ghidrust_core::artifacts`.
+ AnalysisArtifacts,
}
impl PaneKind {
@@ -96,6 +109,13 @@ impl PaneKind {
PaneKind::SymbolReferences,
PaneKind::SymbolTable,
PaneKind::TextEditor,
+ // Agent Friction Closure §13 — tool panes.
+ PaneKind::Il2cppMetadata,
+ PaneKind::Il2cppMethods,
+ PaneKind::Il2cppIcalls,
+ PaneKind::InstallInventory,
+ PaneKind::FileSystemBrowser,
+ PaneKind::AnalysisArtifacts,
];
/// Ghidra display title (Window menu label / provider `TITLE`).
@@ -134,6 +154,12 @@ impl PaneKind {
PaneKind::SymbolTable => "Symbol Table",
PaneKind::SymbolTree => "Symbol Tree",
PaneKind::TextEditor => "Text Editor",
+ PaneKind::Il2cppMetadata => "IL2CPP Metadata",
+ PaneKind::Il2cppMethods => "IL2CPP Methods",
+ PaneKind::Il2cppIcalls => "IL2CPP ICalls",
+ PaneKind::InstallInventory => "Install Inventory",
+ PaneKind::FileSystemBrowser => "File System Browser",
+ PaneKind::AnalysisArtifacts => "Analysis Artifacts",
}
}
@@ -181,6 +207,12 @@ impl PaneKind {
PaneKind::SymbolTable => "SymbolTablePlugin",
PaneKind::SymbolTree => "SymbolTreePlugin",
PaneKind::TextEditor => "TextEditorManagerPlugin",
+ PaneKind::Il2cppMetadata => "Il2cppMetadataPlugin",
+ PaneKind::Il2cppMethods => "Il2cppMethodMapPlugin",
+ PaneKind::Il2cppIcalls => "Il2cppICallsPlugin",
+ PaneKind::InstallInventory => "InstallInventoryPlugin",
+ PaneKind::FileSystemBrowser => "FileSystemBrowserPlugin",
+ PaneKind::AnalysisArtifacts => "AnalysisArtifactsPlugin",
}
}
@@ -214,6 +246,14 @@ impl PaneKind {
| PaneKind::ChecksumGenerator
// Grok agent console (ghidrust-agent crate).
| PaneKind::AgentConsole
+ // Agent Friction Closure §13 — real backends via ghidrust-core /
+ // ghidrust-il2cpp (no empty stubs).
+ | PaneKind::Il2cppMetadata
+ | PaneKind::Il2cppMethods
+ | PaneKind::Il2cppIcalls
+ | PaneKind::InstallInventory
+ | PaneKind::FileSystemBrowser
+ | PaneKind::AnalysisArtifacts
)
}
@@ -253,6 +293,12 @@ impl PaneKind {
PaneKind::SymbolTable => "pane_symbol_table",
PaneKind::SymbolTree => "pane_symbol_tree_win",
PaneKind::TextEditor => "pane_text_editor",
+ PaneKind::Il2cppMetadata => "pane_il2cpp_metadata",
+ PaneKind::Il2cppMethods => "pane_il2cpp_methods",
+ PaneKind::Il2cppIcalls => "pane_il2cpp_icalls",
+ PaneKind::InstallInventory => "pane_install_inventory",
+ PaneKind::FileSystemBrowser => "pane_fs_browser",
+ PaneKind::AnalysisArtifacts => "pane_analysis_artifacts",
}
}
}
@@ -362,6 +408,12 @@ pub const fn backend_pending_message(kind: PaneKind) -> &'static str {
PaneKind::SymbolTable => "Uses Program::analysis.symbols + functions (flat table).",
PaneKind::SymbolTree => "",
PaneKind::TextEditor => "Backend pending — script editor lands in Phase F (M6).",
+ PaneKind::Il2cppMetadata => "",
+ PaneKind::Il2cppMethods => "",
+ PaneKind::Il2cppIcalls => "",
+ PaneKind::InstallInventory => "",
+ PaneKind::FileSystemBrowser => "",
+ PaneKind::AnalysisArtifacts => "",
}
}
diff --git a/crates/ghidrust-gui/src/tool_panes.rs b/crates/ghidrust-gui/src/tool_panes.rs
new file mode 100644
index 0000000..fb66673
--- /dev/null
+++ b/crates/ghidrust-gui/src/tool_panes.rs
@@ -0,0 +1,1012 @@
+//! Agent Friction Closure §13 — tool panes backed by real `ghidrust-core` /
+//! `ghidrust-il2cpp` APIs (no empty stubs where a backend already exists).
+//!
+//! Each pane owns its own session state (path inputs, last result, filter)
+//! so it works standalone — a project/program does not have to be open,
+//! though IL2CPP Methods / ICalls prefer the currently-loaded `Program`
+//! when the user hasn't pointed at a separate binary.
+
+use eframe::egui::{self, Color32, RichText, Ui};
+use ghidrust_core::{
+ artifact_query, list_artifacts, ArtifactEnvelope, ArtifactMeta, PeInventory, PeInventoryEntry,
+ Program, ResolveResult, TreeEntry, TreeListOpts, TreeListResult,
+};
+use ghidrust_il2cpp::{
+ binary::{correlate, MethodMap, MethodMapEntry},
+ icall::{filter_entries, resolve_icalls_path, ICallEntry, ICallResolveReport},
+ metadata::Il2CppMetadata,
+};
+
+fn err_label(ui: &mut Ui, err: &str) {
+ ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), err);
+}
+
+/// Aggregate session state for every §13 tool pane + the GPU Decompile dialog.
+#[derive(Default)]
+pub struct ToolPanesState {
+ pub il2cpp_meta: Il2cppMetaState,
+ pub il2cpp_methods: Il2cppMethodsState,
+ pub il2cpp_icalls: Il2cppIcallsState,
+ pub install_inventory: InstallInventoryState,
+ pub fs_browser: FileSystemBrowserState,
+ pub artifacts: AnalysisArtifactsState,
+ pub gpu_decompile: GpuDecompileDialogState,
+}
+
+// ── IL2CPP Metadata ─────────────────────────────────────────────────────
+
+#[derive(Default)]
+pub struct Il2cppMetaState {
+ pub path_input: String,
+ pub loaded: Option<Il2CppMetadata>,
+ pub type_filter: String,
+ pub method_filter: String,
+ pub error: Option<String>,
+}
+
+pub fn ui_il2cpp_metadata(ui: &mut Ui, s: &mut Il2cppMetaState, muted: Color32) {
+ ui.heading("IL2CPP Metadata");
+ ui.small(
+ RichText::new(
+ "ghidrust-il2cpp::metadata · hand-rolled global-metadata.dat parser (v27/v29/v31)",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label("Path:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.path_input)
+ .desired_width(360.0)
+ .hint_text("global-metadata.dat"),
+ );
+ if ui.button("Browse…").clicked() {
+ if let Some(p) = rfd::FileDialog::new()
+ .set_title("Select global-metadata.dat")
+ .pick_file()
+ {
+ s.path_input = p.display().to_string();
+ }
+ }
+ if ui
+ .add_enabled(!s.path_input.trim().is_empty(), egui::Button::new("Load"))
+ .clicked()
+ {
+ s.error = None;
+ match Il2CppMetadata::load_path(s.path_input.trim()) {
+ Ok(m) => s.loaded = Some(m),
+ Err(e) => {
+ s.loaded = None;
+ s.error = Some(e.to_string());
+ }
+ }
+ }
+ });
+ if let Some(e) = &s.error {
+ err_label(ui, e);
+ }
+ let Some(meta) = &s.loaded else {
+ ui.weak("Load a global-metadata.dat to inspect types / methods / images / string heap.");
+ return;
+ };
+ ui.small(format!(
+ "dialect={:?} version={} · types={} · methods={} · images={} · string heap entries={}",
+ meta.header.dialect,
+ meta.header.version,
+ meta.types.len(),
+ meta.methods.len(),
+ meta.images.len(),
+ meta.strings.len(),
+ ));
+ egui::CollapsingHeader::new(format!("Types ({})", meta.types.len()))
+ .default_open(true)
+ .show(ui, |ui| {
+ ui.add(
+ egui::TextEdit::singleline(&mut s.type_filter)
+ .desired_width(280.0)
+ .hint_text("filter Namespace.Type…"),
+ );
+ let rows = meta.filter_types(&s.type_filter);
+ ui.small(format!("{} / {} types", rows.len(), meta.types.len()));
+ egui::ScrollArea::vertical()
+ .id_salt("il2cpp_types_scroll")
+ .max_height(220.0)
+ .show(ui, |ui| {
+ for t in rows.iter().take(2000) {
+ ui.monospace(format!(
+ "tok={:#x} methods[{}..+{}] {}",
+ t.token,
+ t.method_start,
+ t.method_count,
+ t.full_name()
+ ));
+ }
+ });
+ });
+ egui::CollapsingHeader::new(format!("Methods ({})", meta.methods.len()))
+ .default_open(false)
+ .show(ui, |ui| {
+ ui.add(
+ egui::TextEdit::singleline(&mut s.method_filter)
+ .desired_width(280.0)
+ .hint_text("filter method name…"),
+ );
+ let rows = meta.filter_methods(&s.method_filter);
+ ui.small(format!("{} / {} methods", rows.len(), meta.methods.len()));
+ egui::ScrollArea::vertical()
+ .id_salt("il2cpp_methods_scroll_meta")
+ .max_height(220.0)
+ .show(ui, |ui| {
+ for m in rows.iter().take(2000) {
+ ui.monospace(format!(
+ "idx={} tok={:#x} params={} {}",
+ m.index,
+ m.token,
+ m.parameter_count,
+ meta.method_full_name(m)
+ ));
+ }
+ });
+ });
+ egui::CollapsingHeader::new(format!("Images ({})", meta.images.len()))
+ .default_open(false)
+ .show(ui, |ui| {
+ for img in &meta.images {
+ ui.monospace(format!(
+ "[{}] {} types[{}..+{}]",
+ img.index, img.name, img.type_start, img.type_count
+ ));
+ }
+ });
+}
+
+// ── IL2CPP Methods (CodeRegistration correlation) ───────────────────────
+
+#[derive(Default)]
+pub struct Il2cppMethodsState {
+ pub use_loaded_program: bool,
+ pub binary_path_input: String,
+ pub meta_path_input: String,
+ pub map: Option<MethodMap>,
+ pub filter: String,
+ pub error: Option<String>,
+}
+
+impl Il2cppMethodsState {
+ fn new_default() -> Self {
+ Self {
+ use_loaded_program: true,
+ ..Default::default()
+ }
+ }
+}
+
+pub fn ui_il2cpp_methods(
+ ui: &mut Ui,
+ s: &mut Il2cppMethodsState,
+ program: Option<&Program>,
+ muted: Color32,
+) {
+ if s.binary_path_input.is_empty() && s.meta_path_input.is_empty() && s.map.is_none() {
+ *s = Il2cppMethodsState::new_default();
+ }
+ ui.heading("IL2CPP Methods");
+ ui.small(
+ RichText::new(
+ "ghidrust-il2cpp::binary::correlate · metadata method index ↔ CodeRegistration binary VA",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ ui.checkbox(
+ &mut s.use_loaded_program,
+ "Use currently loaded program as the binary",
+ );
+ if s.use_loaded_program {
+ match program {
+ Some(p) => ui.small(format!("Binary: {} (loaded)", p.name)),
+ None => ui.small(
+ RichText::new("No program loaded — open a binary first or untick this box.")
+ .color(muted),
+ ),
+ };
+ } else {
+ ui.horizontal(|ui| {
+ ui.label("Binary:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.binary_path_input)
+ .desired_width(320.0)
+ .hint_text("GameAssembly.dll / binary path"),
+ );
+ if ui.button("Browse…").clicked() {
+ if let Some(p) = rfd::FileDialog::new()
+ .set_title("Select binary")
+ .pick_file()
+ {
+ s.binary_path_input = p.display().to_string();
+ }
+ }
+ });
+ }
+ ui.horizontal(|ui| {
+ ui.label("Metadata:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.meta_path_input)
+ .desired_width(320.0)
+ .hint_text("global-metadata.dat"),
+ );
+ if ui.button("Browse…").clicked() {
+ if let Some(p) = rfd::FileDialog::new()
+ .set_title("Select global-metadata.dat")
+ .pick_file()
+ {
+ s.meta_path_input = p.display().to_string();
+ }
+ }
+ });
+ let can_run = !s.meta_path_input.trim().is_empty()
+ && (s.use_loaded_program || !s.binary_path_input.trim().is_empty());
+ if ui
+ .add_enabled(can_run, egui::Button::new("Correlate"))
+ .clicked()
+ {
+ s.error = None;
+ s.map = None;
+ let meta = match Il2CppMetadata::load_path(s.meta_path_input.trim()) {
+ Ok(m) => m,
+ Err(e) => {
+ s.error = Some(format!("metadata: {e}"));
+ return;
+ }
+ };
+ let owned_binary = if s.use_loaded_program {
+ None
+ } else {
+ match ghidrust_core::load_path(s.binary_path_input.trim()) {
+ Ok(p) => Some(p),
+ Err(e) => {
+ s.error = Some(format!("binary: {e}"));
+ return;
+ }
+ }
+ };
+ let prog_ref = if s.use_loaded_program {
+ program
+ } else {
+ owned_binary.as_ref()
+ };
+ let Some(prog_ref) = prog_ref else {
+ s.error = Some("no program available — load a binary first".into());
+ return;
+ };
+ match correlate(prog_ref, &meta) {
+ Ok(map) => s.map = Some(map),
+ Err(e) => s.error = Some(e.to_string()),
+ }
+ }
+ if let Some(e) = &s.error {
+ err_label(ui, e);
+ }
+ let Some(map) = &s.map else {
+ ui.weak("Correlate a binary + global-metadata.dat to see the method map.");
+ return;
+ };
+ let resolved = map.entries.iter().filter(|e| e.va.is_some()).count();
+ ui.small(format!(
+ "binary={} metadata_version={} · {} entries · {} resolved VA · method_pointer_count={}",
+ map.binary_name,
+ map.metadata_version,
+ map.entries.len(),
+ resolved,
+ map.method_pointer_count
+ .map(|c| c.to_string())
+ .unwrap_or_else(|| "?".into()),
+ ));
+ if !map.notes.is_empty() {
+ for n in &map.notes {
+ ui.small(RichText::new(n).color(muted).italics());
+ }
+ }
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.filter)
+ .desired_width(280.0)
+ .hint_text("method name…"),
+ );
+ });
+ let q = s.filter.to_ascii_lowercase();
+ let rows: Vec<&MethodMapEntry> = map
+ .entries
+ .iter()
+ .filter(|e| q.is_empty() || e.full_name.to_ascii_lowercase().contains(&q))
+ .collect();
+ ui.small(format!("{} / {} entries", rows.len(), map.entries.len()));
+ let row_h = ui.text_style_height(&egui::TextStyle::Monospace) + 2.0;
+ egui::ScrollArea::vertical()
+ .id_salt("il2cpp_methods_scroll")
+ .auto_shrink([false, false])
+ .max_height(360.0)
+ .show_rows(ui, row_h, rows.len(), |ui, range| {
+ for i in range {
+ let e = rows[i];
+ let va = e
+ .va
+ .map(|v| format!("{v:#x}"))
+ .unwrap_or_else(|| "unresolved".into());
+ ui.monospace(format!("idx={} tok={:#x} va={va} {}", e.method_index, e.token, e.full_name));
+ }
+ });
+}
+
+// ── IL2CPP ICalls ────────────────────────────────────────────────────────
+
+#[derive(Default)]
+pub struct Il2cppIcallsState {
+ pub use_loaded_program: bool,
+ pub binary_path_input: String,
+ pub report: Option<ICallResolveReport>,
+ pub filter: String,
+ pub error: Option<String>,
+}
+
+impl Il2cppIcallsState {
+ fn new_default() -> Self {
+ Self {
+ use_loaded_program: true,
+ ..Default::default()
+ }
+ }
+}
+
+pub fn ui_il2cpp_icalls(
+ ui: &mut Ui,
+ s: &mut Il2cppIcallsState,
+ program: Option<&Program>,
+ muted: Color32,
+) {
+ if s.binary_path_input.is_empty() && s.report.is_none() {
+ *s = Il2cppIcallsState::new_default();
+ }
+ ui.heading("IL2CPP ICalls");
+ ui.small(
+ RichText::new(
+ "ghidrust-il2cpp::icall · parallel name‖fn table pairing (Create Address Tables)",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ ui.checkbox(
+ &mut s.use_loaded_program,
+ "Use currently loaded program as the binary",
+ );
+ if !s.use_loaded_program {
+ ui.horizontal(|ui| {
+ ui.label("Binary:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.binary_path_input)
+ .desired_width(320.0)
+ .hint_text("UnityPlayer.dll / engine binary path"),
+ );
+ if ui.button("Browse…").clicked() {
+ if let Some(p) = rfd::FileDialog::new()
+ .set_title("Select engine binary")
+ .pick_file()
+ {
+ s.binary_path_input = p.display().to_string();
+ }
+ }
+ });
+ } else if let Some(p) = program {
+ ui.small(format!("Binary: {} (loaded)", p.name));
+ } else {
+ ui.small(RichText::new("No program loaded.").color(muted));
+ }
+ let can_run = s.use_loaded_program || !s.binary_path_input.trim().is_empty();
+ if ui
+ .add_enabled(can_run, egui::Button::new("Resolve ICalls"))
+ .clicked()
+ {
+ s.error = None;
+ s.report = None;
+ let result = if s.use_loaded_program {
+ match program.cloned() {
+ Some(mut p) => resolve_icalls_via_owned(&mut p),
+ None => {
+ s.error = Some("no program loaded".into());
+ return;
+ }
+ }
+ } else {
+ resolve_icalls_path(s.binary_path_input.trim()).map_err(|e| e.to_string())
+ };
+ match result {
+ Ok(rep) => s.report = Some(rep),
+ Err(e) => s.error = Some(e),
+ }
+ }
+ if let Some(e) = &s.error {
+ err_label(ui, e);
+ }
+ let Some(report) = &s.report else {
+ ui.weak("Resolve a Unity engine binary to pair icall name‖fn tables.");
+ return;
+ };
+ ui.small(format!("{} icall table(s)", report.tables.len()));
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.filter)
+ .desired_width(280.0)
+ .hint_text("icall name…"),
+ );
+ });
+ let hits: Vec<(usize, ICallEntry)> = filter_entries(report, &s.filter);
+ ui.small(format!("{} matching entries", hits.len()));
+ let row_h = ui.text_style_height(&egui::TextStyle::Monospace) + 2.0;
+ egui::ScrollArea::vertical()
+ .id_salt("il2cpp_icalls_scroll")
+ .auto_shrink([false, false])
+ .max_height(360.0)
+ .show_rows(ui, row_h, hits.len(), |ui, range| {
+ for i in range {
+ let (ti, e) = &hits[i];
+ ui.monospace(format!(
+ "[table {ti}] fn={:#x} {}",
+ e.fn_va, e.name
+ ));
+ }
+ });
+ if !report.tables.is_empty() {
+ egui::CollapsingHeader::new("Tables").default_open(false).show(ui, |ui| {
+ for (i, t) in report.tables.iter().enumerate() {
+ ui.monospace(format!(
+ "[{i}] name_va={:#x} fn_va={:#x} count={} layout={:?} confidence={:.2}",
+ t.name_va, t.fn_va, t.count, t.layout, t.confidence
+ ));
+ }
+ });
+ }
+}
+
+fn resolve_icalls_via_owned(prog: &mut Program) -> Result<ICallResolveReport, String> {
+ ghidrust_il2cpp::icall::resolve_icalls(prog).map_err(|e| e.to_string())
+}
+
+// ── Install Inventory ───────────────────────────────────────────────────
+
+pub struct InstallInventoryState {
+ pub root_input: String,
+ pub max_depth: usize,
+ pub with_hash: bool,
+ pub inventory: Option<PeInventory>,
+ pub filter: String,
+ pub error: Option<String>,
+}
+
+impl Default for InstallInventoryState {
+ fn default() -> Self {
+ Self {
+ root_input: String::new(),
+ max_depth: 4,
+ with_hash: false,
+ inventory: None,
+ filter: String::new(),
+ error: None,
+ }
+ }
+}
+
+pub fn ui_install_inventory(ui: &mut Ui, s: &mut InstallInventoryState, muted: Color32) {
+ ui.heading("Install Inventory");
+ ui.small(
+ RichText::new(
+ "ghidrust-core::inventory::inventory_pe_dir · exe/dll/sys/scr + VERSIONINFO catalog",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label("Folder:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.root_input)
+ .desired_width(320.0)
+ .hint_text("install folder…"),
+ );
+ if ui.button("Browse…").clicked() {
+ if let Some(p) = rfd::FileDialog::new()
+ .set_title("Select install folder")
+ .pick_folder()
+ {
+ s.root_input = p.display().to_string();
+ }
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("Max depth:");
+ ui.add(egui::DragValue::new(&mut s.max_depth).range(0..=32));
+ ui.checkbox(&mut s.with_hash, "Compute sha256 (slow on large trees)");
+ if ui
+ .add_enabled(!s.root_input.trim().is_empty(), egui::Button::new("Scan"))
+ .clicked()
+ {
+ s.error = None;
+ match ghidrust_core::inventory_pe_dir(s.root_input.trim(), s.max_depth, s.with_hash) {
+ Ok(inv) => s.inventory = Some(inv),
+ Err(e) => {
+ s.inventory = None;
+ s.error = Some(e.to_string());
+ }
+ }
+ }
+ });
+ if let Some(e) = &s.error {
+ err_label(ui, e);
+ }
+ let Some(inv) = &s.inventory else {
+ ui.weak("Scan a folder to catalog exe/dll/sys/scr files + VERSIONINFO.");
+ return;
+ };
+ ui.small(format!(
+ "root={} · {} file(s) · {} note(s)",
+ inv.root,
+ inv.entries.len(),
+ inv.notes.len()
+ ));
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.filter)
+ .desired_width(260.0)
+ .hint_text("path / product name…"),
+ );
+ });
+ let q = s.filter.to_ascii_lowercase();
+ let rows: Vec<&PeInventoryEntry> = inv
+ .entries
+ .iter()
+ .filter(|e| {
+ q.is_empty()
+ || e.path.to_ascii_lowercase().contains(&q)
+ || e.version
+ .product_name
+ .as_deref()
+ .unwrap_or("")
+ .to_ascii_lowercase()
+ .contains(&q)
+ })
+ .collect();
+ ui.small(format!("{} / {} shown", rows.len(), inv.entries.len()));
+ egui::ScrollArea::vertical()
+ .id_salt("install_inventory_scroll")
+ .max_height(360.0)
+ .show(ui, |ui| {
+ egui::Grid::new("install_inventory_grid")
+ .num_columns(5)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Path");
+ ui.strong("Size");
+ ui.strong("Product");
+ ui.strong("File version");
+ ui.strong("Company");
+ ui.end_row();
+ for e in &rows {
+ ui.label(&e.path);
+ ui.monospace(format!("{}", e.size));
+ ui.label(e.version.product_name.as_deref().unwrap_or("—"));
+ ui.label(e.version.file_version.as_deref().unwrap_or("—"));
+ ui.label(e.version.company_name.as_deref().unwrap_or("—"));
+ ui.end_row();
+ }
+ });
+ });
+ if !inv.notes.is_empty() {
+ egui::CollapsingHeader::new(format!("Notes ({})", inv.notes.len()))
+ .default_open(false)
+ .show(ui, |ui| {
+ for n in &inv.notes {
+ ui.small(n);
+ }
+ });
+ }
+}
+
+// ── File System Browser ─────────────────────────────────────────────────
+
+pub struct FileSystemBrowserState {
+ pub root_input: String,
+ pub extensions_input: String,
+ pub name_glob_input: String,
+ pub max_depth: usize,
+ pub result: Option<TreeListResult>,
+ pub filter: String,
+ pub error: Option<String>,
+}
+
+impl Default for FileSystemBrowserState {
+ fn default() -> Self {
+ Self {
+ root_input: String::new(),
+ extensions_input: String::new(),
+ name_glob_input: String::new(),
+ max_depth: 6,
+ result: None,
+ filter: String::new(),
+ error: None,
+ }
+ }
+}
+
+pub fn ui_file_system_browser(ui: &mut Ui, s: &mut FileSystemBrowserState, muted: Color32) {
+ ui.heading("File System Browser");
+ ui.small(
+ RichText::new("ghidrust-core::tree_index::list_tree · bounded std::fs walk (no walkdir)")
+ .color(muted),
+ );
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label("Folder:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.root_input)
+ .desired_width(320.0)
+ .hint_text("folder to browse…"),
+ );
+ if ui.button("Browse…").clicked() {
+ if let Some(p) = rfd::FileDialog::new().set_title("Select folder").pick_folder() {
+ s.root_input = p.display().to_string();
+ }
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("Extensions:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.extensions_input)
+ .desired_width(160.0)
+ .hint_text("exe,dll (blank = all)"),
+ );
+ ui.label("Name glob:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.name_glob_input)
+ .desired_width(140.0)
+ .hint_text("*.dll"),
+ );
+ ui.label("Max depth:");
+ ui.add(egui::DragValue::new(&mut s.max_depth).range(0..=64));
+ if ui
+ .add_enabled(!s.root_input.trim().is_empty(), egui::Button::new("List"))
+ .clicked()
+ {
+ s.error = None;
+ let extensions = {
+ let list: Vec<String> = s
+ .extensions_input
+ .split(',')
+ .map(|e| e.trim().to_string())
+ .filter(|e| !e.is_empty())
+ .collect();
+ if list.is_empty() { None } else { Some(list) }
+ };
+ let name_glob = if s.name_glob_input.trim().is_empty() {
+ None
+ } else {
+ Some(s.name_glob_input.trim().to_string())
+ };
+ let opts = TreeListOpts {
+ max_depth: s.max_depth,
+ extensions,
+ name_glob,
+ follow_symlinks: false,
+ max_entries: 20_000,
+ };
+ let root = s.root_input.trim().to_string();
+ if std::path::Path::new(&root).is_dir() {
+ s.result = Some(ghidrust_core::list_tree(&root, opts));
+ } else {
+ s.result = None;
+ s.error = Some(format!("not a directory: {root}"));
+ }
+ }
+ });
+ if let Some(e) = &s.error {
+ err_label(ui, e);
+ }
+ let Some(res) = &s.result else {
+ ui.weak("List a folder to browse its files/directories (bounded depth + entry cap).");
+ return;
+ };
+ ui.small(format!(
+ "root={} · {} entr{} · truncated={}",
+ res.root,
+ res.entries.len(),
+ if res.entries.len() == 1 { "y" } else { "ies" },
+ res.truncated
+ ));
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.filter)
+ .desired_width(260.0)
+ .hint_text("path substring…"),
+ );
+ });
+ let q = s.filter.to_ascii_lowercase();
+ let rows: Vec<&TreeEntry> = res
+ .entries
+ .iter()
+ .filter(|e| q.is_empty() || e.path.to_ascii_lowercase().contains(&q))
+ .collect();
+ ui.small(format!("{} / {} shown", rows.len(), res.entries.len()));
+ let row_h = ui.text_style_height(&egui::TextStyle::Monospace) + 2.0;
+ egui::ScrollArea::vertical()
+ .id_salt("fs_browser_scroll")
+ .auto_shrink([false, false])
+ .max_height(380.0)
+ .show_rows(ui, row_h, rows.len(), |ui, range| {
+ for i in range {
+ let e = rows[i];
+ let kind = if e.is_dir { "DIR " } else { "FILE" };
+ let size = e
+ .size
+ .map(|n| format!("{n}"))
+ .unwrap_or_else(|| "-".into());
+ let err = e
+ .error
+ .as_deref()
+ .map(|x| format!(" [{x}]"))
+ .unwrap_or_default();
+ ui.monospace(format!("{kind} {size:>10} {}{err}", e.path));
+ }
+ });
+}
+
+// ── Analysis Artifacts ───────────────────────────────────────────────────
+
+pub struct AnalysisArtifactsState {
+ pub artifacts: Vec<ArtifactMeta>,
+ pub selected_id: Option<String>,
+ pub preview: Option<ArtifactEnvelope>,
+ pub offset: usize,
+ pub limit: usize,
+ pub error: Option<String>,
+ pub loaded_once: bool,
+}
+
+impl Default for AnalysisArtifactsState {
+ fn default() -> Self {
+ Self {
+ artifacts: Vec::new(),
+ selected_id: None,
+ preview: None,
+ offset: 0,
+ limit: 32,
+ error: None,
+ loaded_once: false,
+ }
+ }
+}
+
+pub fn ui_analysis_artifacts(ui: &mut Ui, s: &mut AnalysisArtifactsState, muted: Color32) {
+ ui.heading("Analysis Artifacts");
+ ui.small(
+ RichText::new(
+ "ghidrust-core::artifacts · spilled MCP/CLI result catalog + paged preview",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ if !s.loaded_once {
+ s.loaded_once = true;
+ refresh_artifacts(s);
+ }
+ ui.horizontal(|ui| {
+ if ui.button("Refresh").clicked() {
+ refresh_artifacts(s);
+ }
+ ui.small(
+ RichText::new(format!(
+ "spill dir: {}",
+ ghidrust_core::artifacts::artifact_dir().display()
+ ))
+ .color(muted),
+ );
+ });
+ if let Some(e) = &s.error {
+ err_label(ui, e);
+ }
+ if s.artifacts.is_empty() {
+ ui.weak("No spilled artifacts yet — large MCP/CLI results spill here.");
+ return;
+ }
+ ui.columns(2, |cols| {
+ cols[0].strong(format!("Artifacts ({})", s.artifacts.len()));
+ cols[0].separator();
+ let mut clicked: Option<String> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("artifacts_left_scroll")
+ .max_height(380.0)
+ .show(&mut cols[0], |ui| {
+ for a in &s.artifacts {
+ let sel = s.selected_id.as_deref() == Some(a.id.as_str());
+ let label = format!("{} ({} entries)", a.kind, a.entry_count);
+ if ui.selectable_label(sel, label).clicked() {
+ clicked = Some(a.id.clone());
+ }
+ }
+ });
+ if let Some(id) = clicked {
+ s.selected_id = Some(id);
+ s.offset = 0;
+ load_preview(s);
+ }
+
+ cols[1].strong("Preview");
+ cols[1].separator();
+ let Some(env) = &s.preview else {
+ cols[1].weak("Select an artifact on the left to preview its entries.");
+ return;
+ };
+ cols[1].small(format!(
+ "kind={} entry_count={} preview_count={} offset={}",
+ env.kind, env.entry_count, env.preview_count, s.offset
+ ));
+ let can_prev = s.offset >= s.limit;
+ let next_offset = env.next_offset;
+ let mut pretty = serde_json::to_string_pretty(&env.preview)
+ .unwrap_or_else(|_| "<unprintable>".into());
+ let mut go_prev = false;
+ let mut go_next = false;
+ cols[1].horizontal(|ui| {
+ if ui.add_enabled(can_prev, egui::Button::new("← Prev page")).clicked() {
+ go_prev = true;
+ }
+ if ui.add_enabled(next_offset.is_some(), egui::Button::new("Next page →")).clicked() {
+ go_next = true;
+ }
+ });
+ if go_prev {
+ s.offset = s.offset.saturating_sub(s.limit);
+ load_preview(s);
+ } else if go_next {
+ if let Some(n) = next_offset {
+ s.offset = n;
+ load_preview(s);
+ }
+ }
+ egui::ScrollArea::vertical()
+ .id_salt("artifacts_right_scroll")
+ .max_height(320.0)
+ .show(&mut cols[1], |ui| {
+ ui.add(
+ egui::TextEdit::multiline(&mut pretty)
+ .code_editor()
+ .desired_rows(16)
+ .desired_width(f32::INFINITY),
+ );
+ });
+ });
+}
+
+fn refresh_artifacts(s: &mut AnalysisArtifactsState) {
+ s.error = None;
+ match list_artifacts(200) {
+ Ok(v) => s.artifacts = v,
+ Err(e) => {
+ s.artifacts.clear();
+ s.error = Some(e.to_string());
+ }
+ }
+}
+
+fn load_preview(s: &mut AnalysisArtifactsState) {
+ let Some(id) = s.selected_id.clone() else {
+ return;
+ };
+ match artifact_query(&id, s.offset, s.limit) {
+ Ok(env) => s.preview = Some(env),
+ Err(e) => {
+ s.preview = None;
+ s.error = Some(e.to_string());
+ }
+ }
+}
+
+// ── Analysis → GPU Decompile dialog ─────────────────────────────────────
+
+#[derive(Default)]
+pub struct GpuDecompileDialogState {
+ pub addr_input: String,
+ pub max_bytes_input: String,
+ pub resolve: Option<ResolveResult>,
+ pub summary: Option<GpuDecompileSummary>,
+ pub error: Option<String>,
+}
+
+/// Small copy of the fields we render (the full report also carries the
+/// pseudo-C dump text, kept separately so the dialog struct stays `Clone`-cheap).
+pub struct GpuDecompileSummary {
+ pub backend: String,
+ pub device: String,
+ pub entry: u64,
+ pub name: String,
+ pub ms: f64,
+ pub device_ms: f64,
+ pub pcie_upload_ms: f64,
+ pub pcie_download_ms: f64,
+ pub mid_pipeline_host_reads: u32,
+ pub dump_path: String,
+ pub dump_bytes: usize,
+ pub ir_count: usize,
+ pub block_count: usize,
+ pub pseudo_c_preview: String,
+}
+
+/// Render the GPU Decompile dialog body (window chrome + the resolve/decompile
+/// call itself are owned by the caller in `main.rs`, since both need a mutable
+/// borrow of the live `Program` that this module does not hold).
+pub fn ui_gpu_decompile_dialog_header(ui: &mut Ui, s: &mut GpuDecompileDialogState, muted: Color32) {
+ ui.small(
+ RichText::new(
+ "ghidrust_decomp::gpu_decompile_to_file · GPU pipeline with automatic CPU multipass fallback",
+ )
+ .color(muted),
+ );
+ ui.horizontal(|ui| {
+ ui.label("Address:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.addr_input)
+ .desired_width(160.0)
+ .hint_text("0x140001000 (blank = entry)"),
+ );
+ ui.label("Max bytes:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.max_bytes_input)
+ .desired_width(100.0)
+ .hint_text("256"),
+ );
+ });
+}
+
+/// Render the resolve/report portion once `s.resolve` / `s.summary` are populated.
+pub fn ui_gpu_decompile_dialog_result(ui: &mut Ui, s: &GpuDecompileDialogState, muted: Color32) {
+ if let Some(e) = &s.error {
+ err_label(ui, e);
+ }
+ if let Some(r) = &s.resolve {
+ ui.separator();
+ ui.small(format!(
+ "resolve_status={:?} requested={:#x} resolved_entry={} ambiguous={}",
+ r.resolve_status,
+ r.requested_addr,
+ r.resolved_entry
+ .map(|e| format!("{e:#x}"))
+ .unwrap_or_else(|| "—".into()),
+ r.ambiguous,
+ ));
+ if let Some(reason) = &r.reason {
+ ui.small(RichText::new(reason).color(muted).italics());
+ }
+ }
+ if let Some(sum) = &s.summary {
+ ui.separator();
+ ui.monospace(format!("backend={} device={}", sum.backend, sum.device));
+ ui.monospace(format!(
+ "{} @ {:#x} · total={:.2}ms device={:.2}ms upload={:.2}ms download={:.2}ms",
+ sum.name, sum.entry, sum.ms, sum.device_ms, sum.pcie_upload_ms, sum.pcie_download_ms
+ ));
+ ui.monospace(format!(
+ "mid_pipeline_host_reads={} ir_count={} block_count={} dump_bytes={}",
+ sum.mid_pipeline_host_reads, sum.ir_count, sum.block_count, sum.dump_bytes
+ ));
+ ui.small(format!("dump: {}", sum.dump_path));
+ egui::CollapsingHeader::new("Pseudo-C preview")
+ .default_open(true)
+ .show(ui, |ui| {
+ egui::ScrollArea::vertical()
+ .max_height(220.0)
+ .show(ui, |ui| {
+ ui.monospace(&sum.pseudo_c_preview);
+ });
+ });
+ }
+}
diff --git a/crates/ghidrust-lift/src/lib.rs b/crates/ghidrust-lift/src/lib.rs
index 2797236..86fd11c 100644
--- a/crates/ghidrust-lift/src/lib.rs
+++ b/crates/ghidrust-lift/src/lib.rs
@@ -767,6 +767,13 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {
return ops;
}
}
+ // SSE moves / zeroing — continuity for XMM paths (16-byte unique slots).
+ "movups" | "movaps" | "movdqa" if parts.len() == 2 => {
+ return lift_xmm_move(ctx, parts[0], parts[1], addr, len, mnem, &insn.operands);
+ }
+ "xorps" | "pxor" if parts.len() == 2 => {
+ return lift_xmm_xor(ctx, parts[0], parts[1], mnem, &insn.operands);
+ }
"lea" if parts.len() == 2 => {
if let Some((dst, dsz)) = parse_reg(parts[0]) {
if let Some(mem) = parse_mem(parts[1]) {
@@ -1136,6 +1143,102 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {
))]
}
+fn xmm_slot(ctx: &mut LiftCtx, name: &str) -> Varnode {
+ // Stable-ish unique per xmm name within a lift session.
+ let id = match name.trim() {
+ "xmm0" => 0x100,
+ "xmm1" => 0x101,
+ "xmm2" => 0x102,
+ "xmm3" => 0x103,
+ "xmm4" => 0x104,
+ "xmm5" => 0x105,
+ "xmm6" => 0x106,
+ "xmm7" => 0x107,
+ "xmm8" => 0x108,
+ "xmm9" => 0x109,
+ "xmm10" => 0x10a,
+ "xmm11" => 0x10b,
+ "xmm12" => 0x10c,
+ "xmm13" => 0x10d,
+ "xmm14" => 0x10e,
+ "xmm15" => 0x10f,
+ _ => {
+ let u = ctx.take_unique(16);
+ return u;
+ }
+ };
+ Varnode {
+ space: AddrSpace::Unique,
+ offset: id,
+ size: 16,
+ }
+}
+
+fn is_xmm_name(s: &str) -> bool {
+ let t = s.trim();
+ t.starts_with("xmm") && t.len() <= 5
+}
+
+fn lift_xmm_move(
+ ctx: &mut LiftCtx,
+ dst: &str,
+ src: &str,
+ addr: u64,
+ len: u8,
+ mnem: &str,
+ raw: &str,
+) -> Vec<PcodeOp> {
+ if is_xmm_name(dst) && is_xmm_name(src) {
+ let d = xmm_slot(ctx, dst);
+ let s = xmm_slot(ctx, src);
+ return vec![PcodeOp::new(OpCode::Copy, Some(d), vec![s]).with_note(format!("{mnem} {raw}"))];
+ }
+ if is_xmm_name(dst) {
+ if let Some(mem) = parse_mem(src) {
+ let (mut ops, val) = load_from(ctx, &mem, 16, addr, len);
+ let d = xmm_slot(ctx, dst);
+ ops.push(PcodeOp::new(OpCode::Copy, Some(d), vec![val]).with_note(format!("{mnem} {raw}")));
+ return ops;
+ }
+ }
+ if is_xmm_name(src) {
+ if let Some(mem) = parse_mem(dst) {
+ let s = xmm_slot(ctx, src);
+ return store_to(ctx, &mem, s, addr, len)
+ .into_iter()
+ .map(|op| op.with_note(format!("{mnem} {raw}")))
+ .collect();
+ }
+ }
+ vec![PcodeOp::unimplemented(format!("{mnem} {raw}"))]
+}
+
+fn lift_xmm_xor(
+ ctx: &mut LiftCtx,
+ dst: &str,
+ src: &str,
+ mnem: &str,
+ raw: &str,
+) -> Vec<PcodeOp> {
+ if is_xmm_name(dst) && dst.trim() == src.trim() {
+ // xorps/pxor same reg → zero
+ let d = xmm_slot(ctx, dst);
+ return vec![PcodeOp::new(
+ OpCode::Copy,
+ Some(d),
+ vec![Varnode::constant(0, 16)],
+ )
+ .with_note(format!("{mnem} {raw} ; zero"))];
+ }
+ if is_xmm_name(dst) && is_xmm_name(src) {
+ let d = xmm_slot(ctx, dst);
+ let s = xmm_slot(ctx, src);
+ return vec![PcodeOp::new(OpCode::IntXor, Some(d.clone()), vec![d, s])
+ .with_note(format!("{mnem} {raw}"))];
+ }
+ vec![PcodeOp::unimplemented(format!("{mnem} {raw}"))]
+}
+
fn lift_mov(
ctx: &mut LiftCtx,
dst: &str,
diff --git a/crates/ghidrust-unity-inventory/src/lib.rs b/crates/ghidrust-unity-inventory/src/lib.rs
index 2b0b47a..6bd957e 100644
--- a/crates/ghidrust-unity-inventory/src/lib.rs
+++ b/crates/ghidrust-unity-inventory/src/lib.rs
@@ -1,6 +1,6 @@
//! Unity player install inventory (assemblies, plugins, metadata, XR-related fields).
-use ghidrust_core::load_path;
+use ghidrust_core::{load_path, version_info_for_file, VersionInfo};
use ghidrust_il2cpp::{Il2CppMetadata, METADATA_MAGIC};
use serde::Serialize;
use sha2::{Digest, Sha256};
@@ -71,11 +71,20 @@ pub struct UnityInventory {
pub native_xr_imports: Vec<String>,
pub external_vr_indicators: Vec<String>,
pub key_hashes: Vec<FileHash>,
+ /// PE VERSIONINFO for player exe / key native modules (shared inventory helpers).
+ #[serde(default)]
+ pub pe_versions: Vec<PeVersionRow>,
pub verdict: XrVerdict,
pub confidence: Confidence,
pub notes: Vec<String>,
}
+#[derive(Debug, Clone, Serialize)]
+pub struct PeVersionRow {
+ pub path: String,
+ pub version: VersionInfo,
+}
+
/// Inventory a Unity player directory (exe + `*_Data/` layout).
pub fn inventory_path(root: impl AsRef<Path>) -> Result<UnityInventory, String> {
let root = root.as_ref();
@@ -134,6 +143,7 @@ pub fn inventory_path(root: impl AsRef<Path>) -> Result<UnityInventory, String>
let mut native_xr_imports = Vec::new();
let mut external_vr_indicators = Vec::new();
let mut key_hashes = Vec::new();
+ let mut pe_versions = Vec::new();
// Hash player exe + GameAssembly / UnityPlayer when present.
for name in ["GameAssembly.dll", "UnityPlayer.dll"] {
@@ -142,6 +152,10 @@ pub fn inventory_path(root: impl AsRef<Path>) -> Result<UnityInventory, String>
if let Some(h) = hash_file(&p) {
key_hashes.push(h);
}
+ pe_versions.push(PeVersionRow {
+ path: p.display().to_string(),
+ version: version_info_for_file(&p),
+ });
if let Ok(prog) = load_path(&p) {
for e in &prog.imports {
let dll = e.dll.to_ascii_lowercase();
@@ -178,6 +192,10 @@ pub fn inventory_path(root: impl AsRef<Path>) -> Result<UnityInventory, String>
if let Some(h) = hash_file(&path) {
key_hashes.push(h);
}
+ pe_versions.push(PeVersionRow {
+ path: path.display().to_string(),
+ version: version_info_for_file(&path),
+ });
}
if fname.contains("inject") && fname.ends_with(".dll") {
external_vr_indicators.push(format!("sidecar_dll:{}", path.display()));
@@ -234,6 +252,7 @@ pub fn inventory_path(root: impl AsRef<Path>) -> Result<UnityInventory, String>
native_xr_imports,
external_vr_indicators,
key_hashes,
+ pe_versions,
verdict,
confidence,
notes,
diff --git a/docs/GHIDRA_HEADTOHEAD.md b/docs/GHIDRA_HEADTOHEAD.md
index 63bc588..e5c8858 100644
--- a/docs/GHIDRA_HEADTOHEAD.md
+++ b/docs/GHIDRA_HEADTOHEAD.md
@@ -5,9 +5,8 @@
This document is the runbook for the `ghidrust ghidra-headtohead` subcommand
and the underlying [`ghidrust_decomp::ghidra_oracle`] library API. It aligns
-with the decompiler pcode-parity plan
-(`.cursor/plans/decompiler_pcode_parity_9377412d.plan.md`) — specifically
-**Phase E** ("Fair Ghidra parity measurement"), which replaced the earlier
+with the decompiler pcode-parity plan (Phase F / Stage-1 product default) —
+specifically **Phase E** ("Fair Ghidra parity measurement"), which replaced the earlier
brace-count proxy and stage-mismatched comparison with a shared-entry,
Stage-1-vs-`DecompInterface`, normalized-token metric.
diff --git a/skill/README.md b/skill/README.md
index 4c356d1..163cdcb 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 (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.
+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, spills large analysis artifacts, inventories PE installs, queries RTTI catalogs, and (on Windows) attaches read-only to live processes — via **CLI**, **MCP** (stdio), and an **egui** CodeBrowser-style GUI. The skill file is also **embedded** in the agent crate so Start works without a source-tree checkout.
**Aims:** a freestanding, auditable RE core; CPU-correct analysis first; optional experimental GPU bulk scan + VRAM-resident decompile; agent-friendly headless use.
@@ -18,7 +18,10 @@ cargo build --workspace --release
./target/release/ghidrust help
./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 decompile fixtures/tiny_x64.pe --addr 0x140001000 --json
+./target/release/ghidrust inventory fixtures --max-depth 2 --json
+./target/release/ghidrust tree fixtures --ext pe,dat --json
+./target/release/ghidrust artifact list --json
./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 --json
@@ -26,7 +29,7 @@ cargo build --workspace --release
cargo run -p ghidrust-gui --release
```
-Windows: `.\target\release\ghidrust.exe` / `.\target\release\ghidrust-gui.exe`.
+Windows: `.\target\release\ghidrust.exe` / `.\target\release\ghidrust-gui.exe`. Friction surfaces (`inventory`, `tree`, `artifact`, `process`, `rtti --filter`) match MCP tool names in `tool_defs()` — see [`SKILL.md`](SKILL.md).
MCP for agents (register in Cursor / Claude Desktop / other MCP clients — see root README):
@@ -41,7 +44,8 @@ Canonical skill file: [`SKILL.md`](SKILL.md). Point any skill-aware agent at it,
| Agent / tool | Typical location |
|--------------|------------------|
| Cursor | project or user skills / rules (see Cursor docs) |
-| Grok | `~/.grok/skills/ghidrust/` or `<repo>/.grok/skills/ghidrust/` |
+| Grok (GUI Start / project open) | `<project>/.grok/skills/ghidrust/SKILL.md` (auto-written from embedded skill) |
+| Grok (manual / user-global) | `~/.grok/skills/ghidrust/` |
| MCP clients | register `ghidrust mcp` as a stdio server |
```bash
diff --git a/skill/SKILL.md b/skill/SKILL.md
index 8f3ad76..16df953 100644
--- a/skill/SKILL.md
+++ b/skill/SKILL.md
@@ -37,6 +37,18 @@ cargo build -p ghidrust-gui --release
---
+## Agent friction SOPs (required)
+
+- **Artifacts**: When envelope `entry_count` > preview or the host truncates tool text, drain via `artifact_query` / `artifact get` until `next_offset` is null. Never assume truncated MCP text is complete.
+- **Program identity**: Prefer `load` with absolute `path`, or `project` + `file_id`. Facts always include `resolved_path` or honest null — resolve before analyze/decompile.
+- **Inventory / tree**: Use `inventory <dir>` (PE VERSIONINFO + exe/dll) before OS `dir`/`Get-Item`. Use `tree` / `list_tree` for non-PE sidecars (existence/size only; no unpack).
+- **Address→function**: Always pass `addr` to `decompile` / `disassemble` / `gpu_decompile`; trust `resolved_entry` / `resolve` meta. Mid-body hits resolve to containing entry; unmapped → `no_containing_function` (no invented 1-insn fn).
+- **RTTI catalog**: Prefer `rtti_query` (`--filter`/`--exact`) before mangled `.?AV` string archaeology. Multi-vtable types report `vtable_vas[]` honestly.
+- **UTF-16 xrefs**: If `search_strings` returns `utf16le`, query `get_string_xrefs` with `encoding=all` (or `utf16le`) before concluding “no refs”.
+- **Live process (Windows)**: `process_list` → `process_attach` → `process_modules` → `process_resolve` (`static_to_live`) → `process_read` → optional `process_regions` / `process_detach`. Bytes ≠ types. No write/breakpoints in MVP.
+- **Skill bootstrap**: GUI project open / Start writes `.grok/skills/ghidrust/SKILL.md` (disk or embedded fallback) and shows a fail-loud checklist (mcp/skill/agents/context + hash).
+- **Do not**: invent enum ordinals; treat `section_notes` as proof of hooks; read `.gdecomp` dumps as text (metrics JSON only).
+
## Decision tree
```
@@ -46,13 +58,18 @@ Need durable workspace?
Need machine-readable?
→ --json OR ghidrust mcp
+ → large dumps → artifact spill + artifact_query drain
+
+Need install layout without shell?
+ → inventory DIR (PE versions + exe/dll)
+ → tree DIR (sidecars / media existence)
Need GPU for selected analyzers (not just bench)?
→ analyze … --gpu OR GUI checkbox OR MCP analyze gpu:true
→ bulk mode for ASCII Strings + SIMT seed enrich per selected name
-Need GPU decompile dump?
- → gpu-decompile <path>
+Need GPU decompile at a VA?
+ → gpu-decompile <path> --addr HEX (metrics JSON; .gdecomp opaque)
Need RTTI CPU vs GPU timings (PCIe split)?
→ rtti-gpu-bench <path>
@@ -160,15 +177,18 @@ ghidrust project analyze PROJ_DIR --file ID \
| Tool | Args | Notes |
|------|------|-------|
-| `load` | `path` | PE/ELF map |
-| `disassemble` | `path`, optional `addr`, `count` | x86-64 listing |
-| `rtti` | `path` | RTTI classes / vtables |
+| `load` | `path` **or** `project`+`file_id` | Map + `section_notes` + `resolved_path` |
+| `disassemble` | `path`, optional `addr`, `count` | Containing-fn resolve + `decode_gaps` |
+| `rtti` / `rtti_query` | `path`, optional `filter`/`exact`/`match` | Catalog; multi-vtable; artifact if large |
+| `artifact_get` / `artifact_query` / `artifact_list` | `id` / optional `offset`/`limit` / optional `max` | Drain or list spilled results |
+| `inventory` | `path`, optional `max_depth`/`hash` | PE VERSIONINFO + exe/dll catalog |
+| `list_tree` | `path`, optional depth/ext/glob | Bounded tree; errors as rows |
| `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 |
+| `list_strings` / `search_strings` | `path`, optional `encoding`, `filter`, **`match`**, `min`, **`limit`**, **`raw`** | Blob scan when `raw:true` |
+| `get_xrefs_to` | `path`, `addr`, optional **`skip_stubs`**, **`classify`** | RIP/tables + data ptrs; IL2CPP stubs |
| `get_xrefs_from` | `path`, `addr`, optional `count` | Xrefs from VA |
-| `get_string_xrefs` | `path`, `filter` | Strings → xrefs |
+| `get_string_xrefs` | `path`, `filter`, optional `encoding` | UTF-16LE parity (`ascii`\|`utf16le`\|`all`) |
| `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 |
@@ -176,11 +196,12 @@ ghidrust project analyze PROJ_DIR --file ID \
| `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 |
+| `unity_inventory` | `path` | Player dir + PE VERSIONINFO helpers |
+| `decompile` | `path`, optional `addr`, `count`, `stage`, **`follow_stub`** | Resolve meta + Stage-1; `runtime_unresolved` when slot empty |
| `list_gpu_strategies` | — | Strategy matrix |
-| `gpu_decompile` | `path`, optional `out` | VRAM multipass |
+| `gpu_decompile` | `path`, optional `addr`, `out` | VA resolve; metrics JSON; dump opaque |
| `rtti_gpu_bench` | `path` | CPU vs GPU RTTI |
+| `process_list` / `process_attach` / `process_detach` / `process_modules` / `process_read` / `process_resolve` / `process_regions` | pid / session / module / rva / max | Live Process Bridge (Windows; read-only) |
MCP launch: `ghidrust mcp` / `target/release/ghidrust.exe mcp` (stdio; no host-specific paths).
@@ -223,25 +244,29 @@ Add `--json` for structured stdout.
| Feature | Command |
|---------|---------|
| Help | `ghidrust help` |
-| Load | `ghidrust load <path>` |
+| Load | `ghidrust load <path\|--project DIR --file-id ID>` |
| Disasm | `ghidrust disasm <path> [--addr HEX] [--count N] [--skip-bad]` |
-| 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]` |
+| Strings | `ghidrust strings <path> [--raw] [--encoding …] [--match MODE] [--limit N] [--out FILE] [--filter SUB]` |
+| Xrefs | `ghidrust xrefs <path> (--to\|--from\|--string\|--import) [--encoding ascii\|utf16le\|all] [--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` |
+| Inventory | `ghidrust inventory <dir> [--max-depth N] [--hash]` |
+| Tree | `ghidrust tree <path> [--max-depth N] [--ext LIST] [--name GLOB]` |
+| Artifact | `ghidrust artifact get\|query\|list …` |
+| Process (Windows) | `ghidrust process list\|attach\|detach\|modules\|read\|resolve\|regions …` |
| IL2CPP | `ghidrust il2cpp meta\|map\|stubs\|icalls …` (see `docs/IL2CPP.md`) |
| Unity inventory | `ghidrust unity-inventory <game-dir>` |
-| RTTI only | `ghidrust rtti <path>` |
+| RTTI catalog | `ghidrust rtti <path> [--filter\|--name\|--exact] [--match MODE]` |
| List analyzers | `ghidrust analyzers` |
| **Analyze** | `ghidrust analyze <path> [--analyzers a,b \| --analyzer NAME …] [--gpu]` |
| Bulk bench | `ghidrust bulk-bench <path>` |
-| Decompile (Stage-1 default; `--follow-stub` for IL2CPP; metrics with `--verbose`) | `ghidrust decompile <path> [--follow-stub] [--verbose]` |
+| Decompile (Stage-1 default; `--follow-stub` for IL2CPP; metrics with `--verbose`) | `ghidrust decompile <path> [--addr HEX] [--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]` |
| Ghidra head-to-head (Phase E, shared-entry, Stage-1) | `ghidrust ghidra-headtohead <path> [--ghidra DIR] [--captured JSON] [--out F]` |
-| **GPU decompile** | `ghidrust gpu-decompile <path> [--out F] [--metrics F]` |
+| **GPU decompile** | `ghidrust gpu-decompile <path> [--addr HEX] [--out F] [--metrics F]` |
| RE bench | `ghidrust re-bench <path>` |
| Analyzer CPU/GPU matrix bench | `ghidrust analyzer-bench <path> [--large] [--out F]` |
| Strategy matrix | `ghidrust analyzer-bench-matrix` |
@@ -254,11 +279,33 @@ Add `--json` for structured stdout.
```bash
# Quick triage
ghidrust load PATH --json
+ghidrust load --project PROJ --file-id ID --json
ghidrust strings PATH --encoding all --filter SomeName --match token --limit 50 --json
-ghidrust xrefs PATH --string SomeName --skip-stubs --json
+ghidrust xrefs PATH --string SomeName --encoding all --skip-stubs --json
ghidrust function-at PATH --addr 0x140001234 --json
ghidrust imports PATH --json
+ghidrust rtti PATH --filter Widget --json
ghidrust analyze PATH --analyzer "ASCII Strings" --analyzer "Function Start Search" --json
+ghidrust decompile PATH --addr 0x140001234 --json
+ghidrust gpu-decompile PATH --addr 0x140001234 --metrics gdec.json --json
+
+# Install / tree without OS shell
+ghidrust inventory INSTALL_DIR --max-depth 8 --json
+ghidrust tree GAME_DIR --ext dll,dat --name "*meta*" --json
+
+# Artifact drain (when envelope entry_count > preview)
+ghidrust artifact list --json
+ghidrust artifact query ARTIFACT_ID --offset 0 --limit 64 --json
+ghidrust artifact get ARTIFACT_ID
+
+# Live process (Windows; read-only)
+ghidrust process list --json
+ghidrust process attach PID
+ghidrust process modules SESSION --json
+ghidrust process resolve SESSION --module app.exe --rva 0x1234 --json
+ghidrust process read SESSION --addr LIVE_VA --size 64 --json
+ghidrust process regions SESSION --json
+ghidrust process detach SESSION
# Unity / IL2CPP
ghidrust unity-inventory GAME_DIR --json
@@ -279,7 +326,6 @@ ghidrust project analyze PROJ --analyzers "Function Start Search,ASCII Strings,W
ghidrust bulk-bench PATH --json
ghidrust analyzer-bench PATH --large --out metrics.txt
ghidrust rtti-gpu-bench PATH --out rtti_metrics.txt --json
-ghidrust gpu-decompile PATH --metrics gdec.json
```
---