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.

Enhance Ghidrust with native network capabilities and CLI improvements.

oofz86839ec39313
diff --git a/Cargo.lock b/Cargo.lock
index 2ff651c..e5d22c1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1367,9 +1367,18 @@ dependencies = [
name = "ghidrust-cli"
version = "0.1.0"
dependencies = [
+ "ghidrust-agent",
"ghidrust-core",
"ghidrust-decomp",
"ghidrust-il2cpp",
+ "ghidrust-net-attr",
+ "ghidrust-net-capture",
+ "ghidrust-net-correlate",
+ "ghidrust-net-detect",
+ "ghidrust-net-flow",
+ "ghidrust-net-parse",
+ "ghidrust-net-rules",
+ "ghidrust-net-schema",
"ghidrust-types",
"ghidrust-unity-inventory",
"serde",
@@ -1428,7 +1437,15 @@ dependencies = [
"ghidrust-core",
"ghidrust-decomp",
"ghidrust-il2cpp",
+ "ghidrust-net-attr",
+ "ghidrust-net-capture",
+ "ghidrust-net-correlate",
+ "ghidrust-net-detect",
+ "ghidrust-net-parse",
+ "ghidrust-net-rules",
+ "ghidrust-net-schema",
"ghidrust-types",
+ "ghidrust-unity-inventory",
"image",
"libc",
"rfd",
@@ -1463,6 +1480,82 @@ dependencies = [
"ghidrust-ir",
]
+[[package]]
+name = "ghidrust-net-attr"
+version = "0.1.0"
+dependencies = [
+ "ghidrust-net-schema",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "ghidrust-net-capture"
+version = "0.1.0"
+dependencies = [
+ "ghidrust-net-attr",
+ "ghidrust-net-flow",
+ "ghidrust-net-schema",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "ghidrust-net-correlate"
+version = "0.1.0"
+dependencies = [
+ "ghidrust-core",
+ "ghidrust-net-schema",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "ghidrust-net-detect"
+version = "0.1.0"
+dependencies = [
+ "ghidrust-net-flow",
+ "ghidrust-net-rules",
+ "ghidrust-net-schema",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "ghidrust-net-flow"
+version = "0.1.0"
+dependencies = [
+ "ghidrust-net-schema",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "ghidrust-net-parse"
+version = "0.1.0"
+dependencies = [
+ "ghidrust-net-schema",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "ghidrust-net-rules"
+version = "0.1.0"
+dependencies = [
+ "ghidrust-net-schema",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "ghidrust-net-schema"
+version = "0.1.0"
+dependencies = [
+ "serde",
+ "serde_json",
+]
+
[[package]]
name = "ghidrust-ssa"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index a60b4d5..2ba3dea 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -11,6 +11,14 @@ members = [
"crates/ghidrust-decomp",
"crates/ghidrust-il2cpp",
"crates/ghidrust-unity-inventory",
+ "crates/ghidrust-net-schema",
+ "crates/ghidrust-net-correlate",
+ "crates/ghidrust-net-attr",
+ "crates/ghidrust-net-flow",
+ "crates/ghidrust-net-rules",
+ "crates/ghidrust-net-detect",
+ "crates/ghidrust-net-parse",
+ "crates/ghidrust-net-capture",
"crates/ghidrust-cli",
"crates/ghidrust-gui",
"crates/ghidrust-agent",
@@ -35,3 +43,11 @@ ghidrust-decomp = { path = "crates/ghidrust-decomp" }
ghidrust-il2cpp = { path = "crates/ghidrust-il2cpp" }
ghidrust-unity-inventory = { path = "crates/ghidrust-unity-inventory" }
ghidrust-agent = { path = "crates/ghidrust-agent" }
+ghidrust-net-schema = { path = "crates/ghidrust-net-schema" }
+ghidrust-net-correlate = { path = "crates/ghidrust-net-correlate" }
+ghidrust-net-attr = { path = "crates/ghidrust-net-attr" }
+ghidrust-net-flow = { path = "crates/ghidrust-net-flow" }
+ghidrust-net-rules = { path = "crates/ghidrust-net-rules" }
+ghidrust-net-detect = { path = "crates/ghidrust-net-detect" }
+ghidrust-net-parse = { path = "crates/ghidrust-net-parse" }
+ghidrust-net-capture = { path = "crates/ghidrust-net-capture" }
diff --git a/README.md b/README.md
index 9444945..3bbef81 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,14 @@
# Ghidrust
-Hand-rolled **Rust** reverse-engineering toolkit inspired by [Ghidra](https://github.com/NationalSecurityAgency/ghidra).
+**Rust** reverse-engineering toolkit inspired by [Ghidra](https://github.com/NationalSecurityAgency/ghidra).
Ghidrust loads PE/ELF (and raw blobs), produces Capstone-class multi-arch listings (23 ISAs; x86-64 primary analyze/decompile pipeline), runs Auto Analysis, decompiles to pseudo-C, parses IL2CPP metadata / Unity install inventory, and saves durable projects — from a CLI, an MCP server for agents, or an egui CodeBrowser-style GUI.
-It is **not** a Ghidra fork or wrapper. Analysis logic (loaders, decode, analyzers, decompile) is written in-tree so the core stays small, auditable, and freestanding.
+**Ghidnet** (native network plane) attributes host sockets and capture flows to processes/images, runs in-tree GNR detection rules, and digs into the offending binary with the same RE stack.
+
+It is **not** a Ghidra fork or wrapper. Analysis logic (loaders, decode, analyzers, decompile, Ghidnet) is written in-tree so the core stays small, auditable, and freestanding.
+
+Includes custom GPU kernels to conduct decompiling at lightning speed, this feature is experimental and in development.
---
@@ -16,8 +20,9 @@ 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 |
| **Custom core** | PE/ELF, Capstone-class multi-arch decode (`ghidrust-decode`), x86-64 RTTI/analyzers, and the IR → SSA → structure → typed-C pipeline implemented in Rust — third-party RE libraries are avoided at runtime; 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 with artifact spill/drain, program identity (`path` or `project`+`file_id`), PE install inventory, RTTI catalog query, UTF-16 xref support, function create / bounded disasm / call graphs, IL2CPP touch-map + body proof, live process bridge (Windows), and egui panes for every surface. **2026-07-19:** Windows agent disasm pipeline + bounds honesty (`--brief`/`--pretty`, `bounds_suspect`, `listing_text`) — see [CHANGELOG.md](CHANGELOG.md) |
+| **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 support, function create / bounded disasm / call graphs, IL2CPP touch-map + body proof, live process bridge (Windows), **Ghidnet** (`net_*`, `tool_surface` ≥ 8), and egui panes for every surface. **2026-07-19:** Windows agent disasm pipeline + bounds honesty (`--brief`/`--pretty`, `bounds_suspect`, `listing_text`) — see [CHANGELOG.md](CHANGELOG.md) |
| **Practical projects** | Create a workspace, import binaries, run analyzers, persist results (`analysis.bin`), reopen later |
+| **Ghidnet (native)** | Process-attributed sockets/flows → GNR alerts → dig into image (`load`/`analyze`/`decompile` / live process). In-tree only — see [Ghidnet](#ghidnet-native-network-plane) |
---
@@ -52,8 +57,9 @@ Binaries:
| Binary | Path (after release build) |
|--------|----------------------------|
-| CLI | `target/release/ghidrust` (`.exe` on Windows) |
+| CLI (+ MCP) | `target/release/ghidrust` (`.exe` on Windows) |
| GUI | `target/release/ghidrust-gui` |
+| Ghidnet capture helper | `target/release/ghidrust-netcap` |
```bash
# CLI only
@@ -62,6 +68,9 @@ cargo build -p ghidrust-cli --release
# GUI only
cargo build -p ghidrust-gui --release
+# Ghidnet capture helper
+cargo build -p ghidrust-net-capture --release --bin ghidrust-netcap
+
# Explicit GPU decomp + core bulk features
cargo build -p ghidrust-cli --release --features ghidrust-core/gpu
```
@@ -194,7 +203,8 @@ First-class commands for the queries agents used to need ad-hoc scripts for. Sam
| `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\|launch\|…\|break\|wait\|scan\|watch` | Live Process Bridge (Windows; observe default, `mode=debug` for BP/step; `tool_surface` 7) | session_id / `-mode` / `--args` / `--cwd` / `--addr` / `--module` / `--rva` |
+| `ghidrust process list\|attach\|launch\|…\|break\|wait\|scan\|watch` | Live Process Bridge (Windows; observe default, `mode=debug` for BP/step; `tool_surface` ≥ 7) | session_id / `-mode` / `--args` / `--cwd` / `--addr` / `--module` / `--rva` |
+| `ghidrust net dig\|playbook\|connections\|owners\|ifaces\|capture\|flows\|detect\|alerts\|rules\|pivots` | **Ghidnet** — attribute sockets/flows, GNR detect, dig into image (`tool_surface` ≥ 8) | See [Ghidnet](#ghidnet-native-network-plane) |
| `ghidrust il2cpp meta\|map\|touch-map\|stubs\|icalls` | IL2CPP metadata + touch-map + method map (body proof / baseline) + 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>` | Capstone-class listing; bounded by function end by default; `decode_gaps` when `--skip-bad`; JSON `stop_reason` | `--addr HEX`, `--count N` (default 16), `--skip-bad`, `--linear`/`--flow`, `--arch`, `--mode`, `--syntax`, `--detail`/`--no-detail`, `--detail-real`, `--skipdata`, `--skipdata-mnemonic`, `--skipdata-size`, `--unsigned-imm`, `--only-offset-branch`, `--litbase`, `--mnem-override ID:MNEMONIC`, `--out`, `--json` |
@@ -268,7 +278,7 @@ Ghidrust exposes the **same analysis core** three ways. Pick one (or mix them):
| **GUI** | Interactive CodeBrowser-style work | `ghidrust-gui` |
| **MCP** | AI agents / IDEs that speak Model Context Protocol | `ghidrust mcp` (stdio) |
-Build both binaries first (`cargo build --workspace --release`), then use the sections below.
+Build release binaries first (`cargo build --workspace --release`), then use the sections below.
---
@@ -545,6 +555,11 @@ On Linux/macOS:
| `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_launch` / … / `process_break_*` / `process_wait` / `process_scan` / `process_watch_expr` | session / pid / mode / image / module / rva / max | Live Process Bridge (Windows; observe default; debug opt-in; `tool_surface` ≥ 7) |
+| `net_dig` / `net_playbook` | hint fields (`path`/`pid`/`host`/`ioc`) or alert/flow refs | Compile or execute dig playbook; closed-loop from alert (`tool_surface` ≥ 8) |
+| `net_connections` / `net_owners` / `net_ifaces` | optional pid / filter | Host sockets → owning image; interface list |
+| `net_capture_start` / `net_capture_stop` / `net_capture_status` / `net_flows` | session / iface / replay path | In-process capture session + attributed flows (MCP/GUI; not CLI one-shot reuse) |
+| `net_detect` / `net_alerts` / `net_rules_list` / `net_rules_load` / `net_rules_check` | pcap/rules path / max | In-tree GNR compile + detect + alert index |
+| `net_pivots` / `net_job_get` | pcap / job id | DNS/TLS/HTTP/SMB pivot fields; dig job status |
#### Live process (Windows)
@@ -562,7 +577,7 @@ Default **observe** = read-only (`PROCESS_VM_READ`): `process list` → `attach
6. **Watches:** add `module+rva->*+0x10` → **Refresh**; optional AOB **Scan**
7. **Console → Export snapshot** → **Detach**
-Versioning: `ghidrust --version`, MCP `initialize`/`server_info`, and egui Help → About / window title all report the same workspace package version. Agents also check `tool_surface`: **minimum `3`** (touch-map / body_class / function_create); **prefer `>= 4`** for bounded disasm / `get_calls_from`; **require `>= 5`** for `decode_support`, `decode_query`, and extended `disassemble` decode flags; **`>= 6`** for crypto recover/bake; **`>= 7`** for live debug break/step/scan/watch; **current is `7`**. `server_info.decode` mirrors `decode-support`; `server_info.live_process` lists modes + capabilities.
+Versioning: `ghidrust --version`, MCP `initialize`/`server_info`, and egui Help → About / window title all report the same workspace package version. Agents also check `tool_surface`: **minimum `3`** (touch-map / body_class / function_create); **prefer `>= 4`** for bounded disasm / `get_calls_from`; **require `>= 5`** for `decode_support`, `decode_query`, and extended `disassemble` decode flags; **`>= 6`** for crypto recover/bake; **`>= 7`** for live debug break/step/scan/watch; **`>= 8`** for Ghidnet (`net_*`, `server_info.network`); **current is `8`**. `server_info.decode` mirrors `decode-support`; `server_info.live_process` lists modes + capabilities; `server_info.network` describes Ghidnet.
#### Analysis artifacts
@@ -579,6 +594,7 @@ Large MCP/CLI dumps spill to `%TEMP%/ghidrust-artifacts/`. Tool envelopes includ
| GPU decompile | Analysis → **GPU Decompile…** |
| Encoding / xrefs / RTTI / notes | Defined Strings, Symbol References, Symbol Tree Classes, Memory Map |
| Live process | **Debugger** (tabbed): Targets / Modules / Memory Bytes / Regions / Breakpoints / Threads / Registers / Stack / Watches (live APIs under mode=debug) |
+| Ghidnet | **Network** tabbed host (Window → Network, or top-level **Network** menu): Connections / Capture / Alerts / Rules / Dig |
IL2CPP version matrix and Unity inventory schema: [docs/IL2CPP.md](docs/IL2CPP.md).
@@ -629,6 +645,60 @@ You should not need to type JSON by hand day-to-day — the IDE/agent does that
---
+## Ghidnet (native network plane)
+
+Ghidnet is Ghidrust’s in-tree network investigation plane: **attribute → detect → dig**. It does not vendor foreign capture/IDS products. Outcome target is host investigation that pivots into the same `load` / `analyze` / `decompile` / live-process stack — not packet-UI feature parity with desktop sniffers.
+
+### Pipeline
+
+| Stage | What you get | CLI | MCP |
+|-------|--------------|-----|-----|
+| **Attribute** | TCP/UDP sockets → owning PID/image; interface list | `net connections`, `net owners`, `net ifaces` | `net_connections`, `net_owners`, `net_ifaces` |
+| **Capture / flows** | In-process session, `GRNCAP01` files, replay backend, flow table | `net capture …`, `net flows`, `ghidrust-netcap` | `net_capture_*`, `net_flows` |
+| **Detect** | GNR rules → alerts (in-tree MPM) | `net detect`, `net alerts`, `net rules …` | `net_detect`, `net_alerts`, `net_rules_*` |
+| **Pivots** | DNS / TLS SNI / HTTP / SMB fields from frames | `net pivots --pcap FILE` | `net_pivots` |
+| **Dig** | Playbook compile/execute; closed-loop from alert → image RE | `net dig`, `net playbook` | `net_dig`, `net_playbook`, `net_job_get` |
+
+Requires `tool_surface >= 8`. `server_info.network` advertises the plane to agents. Airgap policy blocks live observe tools (`net_connections`, capture, detect) while still allowing path-only dig.
+
+### Quick examples
+
+```bash
+# Dig playbook from a hint (compile only)
+./target/release/ghidrust net dig --path fixtures/tiny_x64.pe --json
+
+# Execute offline dig (load + analyzers + string/import pivots)
+./target/release/ghidrust net dig --path fixtures/tiny_x64.pe --execute --json
+
+# Host sockets (Windows IP Helper / Linux /proc)
+./target/release/ghidrust net connections --json
+./target/release/ghidrust net owners --pid <PID> --json
+
+# Detect on a capture file with shipped minimal rules
+./target/release/ghidrust net detect --pcap path/to/capture.grncap --rules rules/ghidrust-minimal.rules --json
+./target/release/ghidrust net rules check --path rules/ghidrust-minimal.rules --json
+./target/release/ghidrust net pivots --pcap path/to/capture.grncap --json
+```
+
+**Session note:** capture `session_id` lives in one process (same rule as `process_*`). Multi-step capture/detect/flows must use MCP, the GUI Network host, or a single long-lived process — CLI one-shot cannot reopen another CLI’s session.
+
+### GUI (Network host)
+
+Same APIs as CLI/MCP, in-process:
+
+1. **Network → Show Connections** (or **Window → Network**)
+2. **Connections:** Refresh → select row → **Dig** (fills Dig tab hint)
+3. **Capture:** set iface / replay path → **Start** → **Flows** → **Detect** / **Pivots**
+4. **Alerts:** severity queue → **Dig** (closed-loop when owner path known)
+5. **Rules:** pack path → **Check** (default `rules/ghidrust-minimal.rules`)
+6. **Dig:** **Compile** / **Execute** → **Open in Listing** (loads image into CodeBrowser)
+
+**Honesty bounds:** live NIC acquisition may be stub/replay-first; capture sessions are process-local. Host header / Help→About show `NetworkInfo` (wave/caps). Capture **Export path** reveals `out_path` (copy + folder). **Inline block** is disabled unless `GHIDRUST_NET_INLINE=1` (hover shows reason).
+
+Shipped rules: [`rules/ghidrust-minimal.rules`](rules/ghidrust-minimal.rules).
+
+---
+
## Decrypt and crypto discovery
Use the discovery order **Find Crypt → recover strings → capabilities → recipe peel**. Results are evidence-based; a successful GCM recipe returns the counter-mode plaintext path but does not authenticate a tag.
@@ -687,7 +757,15 @@ MCP equivalents are `crypt_constants`, `recover_strings`, `list_crypto_capabilit
| `ghidrust-decomp` | Stage-0 CFG → pseudo-C (regression oracle), Stage-0.5 IR-informed emit (`ir_emit`), decompile-bench harness, experimental GPU VRAM multipass |
| `ghidrust-il2cpp` | IL2CPP `global-metadata.dat` + CodeRegistration correlation + resolve stubs |
| `ghidrust-unity-inventory` | Unity player layout inventory (assemblies, plugins, metadata) |
-| `ghidrust-cli` | CLI + MCP + benches / `gpu-decompile` / `decompile-bench` |
+| `ghidrust-net-schema` | Ghidnet VOs (`NetHint`, `Alert`, `DigPlan`, flows/pivots) |
+| `ghidrust-net-attr` | Host socket → owner (Windows IP Helper / Linux `/proc`) |
+| `ghidrust-net-capture` | Capture sessions, `GRNCAP01`, replay; bin `ghidrust-netcap` |
+| `ghidrust-net-flow` | Flow table, reassembly, filters |
+| `ghidrust-net-rules` | GNR dialect parse/compile |
+| `ghidrust-net-detect` | In-tree MPM + alerts; optional inline via `GHIDRUST_NET_INLINE` |
+| `ghidrust-net-parse` | DNS / TLS SNI / HTTP / SMB pivot extractors |
+| `ghidrust-net-correlate` | Dig playbooks + closed-loop alert → RE |
+| `ghidrust-cli` | CLI + MCP + benches / `gpu-decompile` / `decompile-bench` / `net …` |
| `ghidrust-gui` | CodeBrowser-style UI |
---
diff --git a/crates/ghidrust-agent/src/lib.rs b/crates/ghidrust-agent/src/lib.rs
index 27f2f85..f6e6078 100644
--- a/crates/ghidrust-agent/src/lib.rs
+++ b/crates/ghidrust-agent/src/lib.rs
@@ -22,7 +22,9 @@ pub use installer::{
grok_binary_path, install_command_for_platform, probe_grok_version, InstallCommand,
};
pub use markdown::{parse_markdown, MarkdownBlock};
-pub use policy::AgentMode;
+pub use policy::{
+ is_destructive_tool, is_network_observe_tool, network_tool_allowed, AgentMode,
+};
pub use system_prompt::{
FunctionFact, ImportFact, ProgramFacts, ProjectFileFact, SectionFact, SelectionFact,
SystemPromptBuilder,
diff --git a/crates/ghidrust-agent/src/policy.rs b/crates/ghidrust-agent/src/policy.rs
index 0a5de3d..d96ad4f 100644
--- a/crates/ghidrust-agent/src/policy.rs
+++ b/crates/ghidrust-agent/src/policy.rs
@@ -79,6 +79,33 @@ pub fn is_destructive_tool(tool_name: &str) -> bool {
)
}
+/// Tools that observe or acquire live host network state.
+///
+/// Airgap must refuse these. Path-only dig (`net_dig` / `net_playbook` without
+/// capture) is allowed offline and is **not** classified here.
+pub fn is_network_observe_tool(tool_name: &str) -> bool {
+ matches!(
+ tool_name,
+ "net_connections"
+ | "net_owners"
+ | "net_ifaces"
+ | "net_capture_start"
+ | "net_capture_stop"
+ | "net_capture_status"
+ | "net_flows"
+ | "net_detect"
+ )
+}
+
+/// Whether `mode` may dispatch `tool_name` for network observe tools.
+pub fn network_tool_allowed(mode: AgentMode, tool_name: &str) -> bool {
+ if is_network_observe_tool(tool_name) {
+ !matches!(mode, AgentMode::Airgap)
+ } else {
+ true
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -128,4 +155,15 @@ mod tests {
assert!(!is_destructive_tool(t), "{t} should be non-destructive");
}
}
+
+ #[test]
+ fn airgap_blocks_network_observe_allows_dig() {
+ assert!(is_network_observe_tool("net_capture_start"));
+ assert!(is_network_observe_tool("net_connections"));
+ assert!(!is_network_observe_tool("net_dig"));
+ assert!(!is_network_observe_tool("net_playbook"));
+ assert!(!network_tool_allowed(AgentMode::Airgap, "net_capture_start"));
+ assert!(network_tool_allowed(AgentMode::ReadOnly, "net_capture_start"));
+ assert!(network_tool_allowed(AgentMode::Airgap, "net_dig"));
+ }
}
diff --git a/crates/ghidrust-agent/src/tool_bridge.rs b/crates/ghidrust-agent/src/tool_bridge.rs
index ac4785f..a457afc 100644
--- a/crates/ghidrust-agent/src/tool_bridge.rs
+++ b/crates/ghidrust-agent/src/tool_bridge.rs
@@ -213,7 +213,14 @@ pub fn write_project_skill(project_root: &Path, skill_source: &Path) -> io::Resu
Ok(s) => s,
Err(_) => EMBEDDED_SKILL_MD.to_string(),
};
- write_project_skill_contents(project_root, &skill)
+ let dest = write_project_skill_contents(project_root, &skill)?;
+ // Progressive disclosure: copy Ghidnet companion when present next to SKILL.md.
+ let companion = skill_source.with_file_name("ghidnet.md");
+ if companion.is_file() {
+ let dest_companion = dest.with_file_name("ghidnet.md");
+ let _ = fs::copy(&companion, &dest_companion);
+ }
+ Ok(dest)
}
/// Write skill from the embedded copy (always succeeds if the project dir is writable).
diff --git a/crates/ghidrust-cli/Cargo.toml b/crates/ghidrust-cli/Cargo.toml
index 9c156df..cc04b1d 100644
--- a/crates/ghidrust-cli/Cargo.toml
+++ b/crates/ghidrust-cli/Cargo.toml
@@ -15,8 +15,23 @@ ghidrust-decomp = { workspace = true, features = ["gpu"] }
ghidrust-il2cpp = { workspace = true }
ghidrust-unity-inventory = { workspace = true }
ghidrust-types = { workspace = true }
+ghidrust-net-schema = { workspace = true }
+ghidrust-net-correlate = { workspace = true }
+ghidrust-net-attr = { workspace = true }
+ghidrust-net-capture = { workspace = true }
+ghidrust-net-detect = { workspace = true }
+ghidrust-net-parse = { workspace = true }
+ghidrust-net-rules = { workspace = true }
+ghidrust-net-flow = { workspace = true }
+ghidrust-agent = { workspace = true }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+[dev-dependencies]
+ghidrust-net-capture = { workspace = true }
+ghidrust-net-flow = { workspace = true }
+ghidrust-net-schema = { workspace = true }
+serde_json = "1"
+
[target.'cfg(windows)'.build-dependencies]
winres = "0.1"
diff --git a/crates/ghidrust-cli/src/friction.rs b/crates/ghidrust-cli/src/friction.rs
index 1e1d09f..9f5c870 100644
--- a/crates/ghidrust-cli/src/friction.rs
+++ b/crates/ghidrust-cli/src/friction.rs
@@ -5,7 +5,7 @@ use ghidrust_core::{
load_path, process_attach_opts, process_break_clear, process_break_list, process_break_set,
process_continue, process_detach, process_export_snapshot, process_launch, process_list,
process_modules, process_pause, process_read, process_regions, process_resolve, process_resume,
- process_scan_mem, process_stack, process_step_into, process_step_over,
+ process_scan_mem, process_stack, process_step_into, process_step_out, process_step_over,
process_thread_context_get, process_threads, process_vtable_probe, process_wait,
process_watch_expr, resolve_function, resolve_result_json, rtti_query, section_notes_for,
spill_artifact, write_json_no_bom, AttachOpts, BreakKind, LaunchRequest, Project,
@@ -360,7 +360,7 @@ pub fn cmd_tree(args: &[String], json: bool) -> ExitCode {
pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
if args.is_empty() {
eprintln!(
- "usage: ghidrust process list|attach|launch|resume|detach|modules|read|resolve|regions|break|continue|pause|wait|step|threads|regs|stack|scan|watch|vtable|snapshot … [-json]"
+ "usage: ghidrust process list|attach|launch|resume|detach|modules|read|resolve|regions|break|continue|pause|wait|step|step-out|threads|regs|stack|scan|watch|vtable|snapshot … [-json]"
);
return ExitCode::from(2);
}
@@ -769,8 +769,11 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
}
"step" => {
let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
+ let out = args.iter().any(|a| a == "-out");
let over = args.iter().any(|a| a == "-over");
- let r = if over {
+ let r = if out {
+ process_step_out(sid, None)
+ } else if over {
process_step_over(sid, None)
} else {
process_step_into(sid, None)
@@ -786,6 +789,19 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
}
}
}
+ "step-out" => {
+ let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
+ match process_step_out(sid, None) {
+ Ok(()) => {
+ println!("{{\"ok\":true}}");
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
"threads" => {
let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
match process_threads(sid) {
diff --git a/crates/ghidrust-cli/src/main.rs b/crates/ghidrust-cli/src/main.rs
index b1f1885..ad96e79 100644
--- a/crates/ghidrust-cli/src/main.rs
+++ b/crates/ghidrust-cli/src/main.rs
@@ -7,6 +7,7 @@ mod decode_support_cmd;
mod disasm_cmd;
mod friction;
mod mcp_decode;
+mod net_cmds;
use ghidrust_core::{
analyze_path, analyzer_catalog, artifact_get, artifact_query, assess_decompile_bounds,
@@ -16,7 +17,7 @@ use ghidrust_core::{
process_break_clear, process_break_list, process_break_set,
process_continue, process_detach, process_export_snapshot, process_launch, process_list,
process_modules, process_pause, process_read, process_regions, process_resolve, process_resume,
- process_scan_mem, process_stack, process_step_into, process_step_over,
+ process_scan_mem, process_stack, process_step_into, process_step_out, process_step_over,
process_thread_context_get, process_thread_context_set, process_threads, process_vtable_probe,
process_wait, process_watch_expr, recover_rtti, resolve_function, rtti_query, run_analyzers,
scan_ascii_strings_bulk, scan_printable_runs_gpu_or_fallback, scan_printable_runs_parallel,
@@ -52,7 +53,8 @@ const PACKAGE_VERSION: &str = env!("CARGO_PKG_VERSION");
/// `5` = decode engine surface (decode_support, decode_query, extended disassemble).
/// `6` = crypt_constants, recover_strings, decode_bake/magic, crypto_capabilities.
/// `7` = live process debug bridge (break/step/regs/stack/scan/watch).
-const TOOL_SURFACE_VERSION: u32 = 7;
+/// `8` = native network dig / connections / capture / detect / pivots.
+const TOOL_SURFACE_VERSION: u32 = 8;
fn package_version() -> &'static str {
PACKAGE_VERSION
@@ -84,12 +86,19 @@ fn server_info_json() -> Value {
"recover_strings",
"decode_bake",
"decode_magic",
- "list_crypto_capabilities"
+ "list_crypto_capabilities",
+ "net_dig",
+ "net_playbook",
+ "net_connections",
+ "net_capture_start",
+ "net_detect",
+ "net_pivots"
],
"decode_diet": decode_block["features"]["decode_diet"],
"x86_reduce": decode_block["features"]["x86_reduce"],
},
"live_process": live_process_info_json(),
+ "network": net_cmds::network_info_json(),
})
}
@@ -241,6 +250,7 @@ fn main() -> ExitCode {
"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),
+ "net" => net_cmds::cmd_net(&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),
@@ -303,6 +313,8 @@ fn print_help() {
ghidrust process list|attach|launch|resume|detach|modules|read|resolve|regions|\n\
break|continue|pause|wait|step|threads|regs|stack|scan|watch|vtable|snapshot … [--json]\n\
# attach/launch: -mode observe|debug; launch debug: -break-at-entry\n\
+ ghidrust net dig|playbook|connections|owners|ifaces|capture|flows|detect|alerts|rules|pivots … [--json]\n\
+ # Ghidnet (tool_surface>=8): attribute → detect → dig; see README Ghidnet\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\
@@ -3487,6 +3499,18 @@ fn tool_defs() -> Vec<ToolDef> {
"type": "object",
"properties": {
"session_id": { "type": "string" },
+ "thread_id": { "type": "integer" }
+ },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_step_out",
+ description: "Step out of the current frame (oneshot BP at return address, else step-over until RET). Uses last stop thread if thread_id omitted.",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
"thread_id": { "type": "integer" }
},
"required": ["session_id"]
@@ -4005,6 +4029,175 @@ description: "Auto-detect a short peel chain (depth 1..4) maximizing printable r
"required": ["path", "addr"]
}),
},
+ ToolDef {
+ name: "net_dig",
+ description: "Compile/execute a native network dig playbook (path/host/ioc/alert → load/analyze/imports/strings). tool_surface>=8",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "pid": { "type": "integer" },
+ "host": { "type": "string" },
+ "ioc": { "type": "string" },
+ "alert_id": { "type": "string" },
+ "flow_ref": { "type": "string" },
+ "execute": { "type": "boolean" },
+ "live": { "type": "boolean" }
+ }
+ }),
+ },
+ ToolDef {
+ name: "net_playbook",
+ description: "Compile dig playbook without executing",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "pid": { "type": "integer" },
+ "host": { "type": "string" },
+ "ioc": { "type": "string" }
+ }
+ }),
+ },
+ ToolDef {
+ name: "net_connections",
+ description: "List host TCP/UDP sockets with process/image owners (native OS APIs)",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "pid": { "type": "integer" },
+ "path": { "type": "string" },
+ "proto": { "type": "string" },
+ "max": { "type": "integer" }
+ }
+ }),
+ },
+ ToolDef {
+ name: "net_owners",
+ description: "Resolve image path for a PID",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "pid": { "type": "integer" } },
+ "required": ["pid"]
+ }),
+ },
+ ToolDef {
+ name: "net_ifaces",
+ description: "List capture interfaces / backends",
+ input_schema: json!({ "type": "object", "properties": {} }),
+ },
+ ToolDef {
+ name: "net_capture_start",
+ description: "Start native capture session (replay_path for fixtures; airgap refuses)",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "iface": { "type": "string" },
+ "filter": { "type": "string" },
+ "pid": { "type": "integer" },
+ "path": { "type": "string" },
+ "out": { "type": "string" },
+ "replay_path": { "type": "string" }
+ }
+ }),
+ },
+ ToolDef {
+ name: "net_capture_stop",
+ description: "Stop capture session and flush capture file",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "session_id": { "type": "string" } },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "net_capture_status",
+ description: "Capture session status",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "session_id": { "type": "string" } },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "net_flows",
+ description: "Attributed flows for a capture session",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "max": { "type": "integer" }
+ },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "net_detect",
+ description: "Run native GNR rules on a capture file / payload blob",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "pcap": { "type": "string" },
+ "rules": { "type": "string" },
+ "attr": { "type": "string" }
+ },
+ "required": ["pcap"]
+ }),
+ },
+ ToolDef {
+ name: "net_alerts",
+ description: "List recent native detection alerts",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "max": { "type": "integer" } }
+ }),
+ },
+ ToolDef {
+ name: "net_rules_list",
+ description: "List bundled/native rule packs",
+ input_schema: json!({ "type": "object", "properties": {} }),
+ },
+ ToolDef {
+ name: "net_rules_load",
+ description: "Load/compile a GNR rules file",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "path": { "type": "string" } },
+ "required": ["path"]
+ }),
+ },
+ ToolDef {
+ name: "net_rules_check",
+ description: "Compile-check a GNR rules file",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "path": { "type": "string" } },
+ "required": ["path"]
+ }),
+ },
+ ToolDef {
+ name: "net_pivots",
+ description: "Extract DNS/TLS/HTTP/SMB pivot fields from a capture or payload file",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "pcap": { "type": "string" },
+ "flow_id": { "type": "string" }
+ },
+ "required": ["pcap"]
+ }),
+ },
+ ToolDef {
+ name: "net_job_get",
+ description: "Fetch a closed-loop dig job by id",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "job_id": { "type": "string" },
+ "artifact_id": { "type": "string" }
+ }
+ }),
+ },
]
}
@@ -4519,6 +4712,15 @@ fn call_tool(params: &Value) -> Result<String, String> {
process_step_over(sid, tid)?;
Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())
}
+ "process_step_out" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let tid = args.get("thread_id").and_then(|t| t.as_u64()).map(|t| t as u32);
+ process_step_out(sid, tid)?;
+ Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())
+ }
"process_threads" => {
let sid = args
.get("session_id")
@@ -5484,6 +5686,9 @@ fn call_tool(params: &Value) -> Result<String, String> {
}
_ => unreachable!(),
},
+ name if name.starts_with("net_") => {
+ net_cmds::mcp_net(name, &args, ghidrust_agent::AgentMode::Full)
+ }
other => Err(format!("unknown tool: {other}")),
}
}
diff --git a/crates/ghidrust-cli/src/net_cmds.rs b/crates/ghidrust-cli/src/net_cmds.rs
new file mode 100644
index 0000000..68729aa
--- /dev/null
+++ b/crates/ghidrust-cli/src/net_cmds.rs
@@ -0,0 +1,695 @@
+//! CLI + helpers for native network investigation (`ghidrust net …`).
+
+use ghidrust_agent::{is_network_observe_tool, AgentMode};
+use ghidrust_net_attr::{list_connections, owner_for_pid, ConnFilter};
+use ghidrust_net_capture::{
+ capture_start, capture_status, capture_stop, flows, list_interfaces, CaptureStartRequest,
+};
+use ghidrust_net_correlate::{
+ compile_playbook, execute_closed_loop, execute_playbook_offline, playbook_to_mcp_chain,
+};
+use ghidrust_net_detect::{compile_rules_text, detect_capture_file, detect_frames, last_alerts, load_rules};
+use ghidrust_net_flow::Frame;
+use ghidrust_net_parse::extract_pivots;
+use ghidrust_net_rules::compile_rules;
+use ghidrust_net_schema::{
+ Alert, ClosedLoopConfig, Confidence, FlowKey, NetHint, NetworkInfo, Owner,
+};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::process::ExitCode;
+use std::sync::Mutex;
+
+static ALERT_INDEX: Mutex<Vec<Alert>> = Mutex::new(Vec::new());
+
+pub fn network_info_json() -> Value {
+ serde_json::to_value(NetworkInfo {
+ wave: 5,
+ caps: vec![
+ "dig".into(),
+ "playbook".into(),
+ "connections".into(),
+ "owners".into(),
+ "capture".into(),
+ "flows".into(),
+ "detect".into(),
+ "alerts".into(),
+ "rules".into(),
+ "pivots".into(),
+ ],
+ native: true,
+ capture: true,
+ })
+ .unwrap_or(json!({}))
+}
+
+fn flag(args: &[String], name: &str) -> bool {
+ args.iter().any(|a| a == name || a == &format!("-{name}") || a == &format!("--{name}"))
+}
+
+fn opt(args: &[String], name: &str) -> Option<String> {
+ let keys = [format!("-{name}"), format!("--{name}")];
+ let mut i = 0;
+ while i < args.len() {
+ if keys.iter().any(|k| args[i] == *k) {
+ return args.get(i + 1).cloned();
+ }
+ i += 1;
+ }
+ None
+}
+
+pub fn cmd_net(args: &[String], json: bool) -> ExitCode {
+ if args.is_empty() {
+ eprintln!(
+ "usage: ghidrust net dig|playbook|connections|owners|ifaces|capture|flows|detect|alerts|rules|pivots … [-json]"
+ );
+ return ExitCode::from(2);
+ }
+ match args[0].as_str() {
+ "dig" => cmd_dig(&args[1..], json),
+ "playbook" => cmd_playbook(&args[1..], json),
+ "connections" => cmd_connections(&args[1..], json),
+ "owners" => cmd_owners(&args[1..], json),
+ "ifaces" => {
+ let v = list_interfaces();
+ print_val(&json!({"interfaces": v}), json);
+ ExitCode::SUCCESS
+ }
+ "capture" => cmd_capture(&args[1..], json),
+ "flows" => cmd_flows(&args[1..], json),
+ "detect" => cmd_detect(&args[1..], json),
+ "alerts" => {
+ let max = opt(args, "max").and_then(|s| s.parse().ok());
+ let mut alerts = last_alerts(max);
+ if alerts.is_empty() {
+ alerts = ALERT_INDEX.lock().unwrap().clone();
+ }
+ print_val(&json!({"alerts": alerts}), json);
+ ExitCode::SUCCESS
+ }
+ "rules" => cmd_rules(&args[1..], json),
+ "pivots" => cmd_pivots(&args[1..], json),
+ other => {
+ eprintln!("unknown net subcommand: {other}");
+ ExitCode::from(2)
+ }
+ }
+}
+
+fn print_val(v: &Value, json: bool) {
+ if json {
+ println!("{}", serde_json::to_string_pretty(v).unwrap());
+ } else {
+ println!("{v}");
+ }
+}
+
+fn hint_from_args(args: &[String]) -> NetHint {
+ NetHint {
+ path: opt(args, "path"),
+ pid: opt(args, "pid").and_then(|s| s.parse().ok()),
+ host: opt(args, "host"),
+ ioc: opt(args, "ioc"),
+ alert_id: opt(args, "from-alert").or_else(|| opt(args, "alert")),
+ flow_ref: opt(args, "from-flow").or_else(|| opt(args, "flow")),
+ }
+}
+
+fn cmd_dig(args: &[String], json: bool) -> ExitCode {
+ if let Some(aid) = opt(args, "from-alert").or_else(|| opt(args, "alert")) {
+ let alerts = ALERT_INDEX.lock().unwrap().clone();
+ let Some(alert) = alerts.into_iter().find(|a| a.id == aid || a.sid.to_string() == aid) else {
+ eprintln!("error: alert not found: {aid}");
+ return ExitCode::FAILURE;
+ };
+ let path = opt(args, "path")
+ .or_else(|| alert.owner.as_ref().and_then(|o| o.image_path.clone()));
+ let Some(path) = path else {
+ eprintln!("error: --path required when alert has no owner path");
+ return ExitCode::FAILURE;
+ };
+ let cfg = ClosedLoopConfig {
+ auto_analyze: flag(args, "execute"),
+ auto_decompile_limit: 3,
+ attach_live: flag(args, "live"),
+ };
+ match execute_closed_loop(&alert, &PathBuf::from(&path), &cfg) {
+ Ok(job) => {
+ print_val(&serde_json::to_value(&job).unwrap(), json);
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ } else {
+ let hint = hint_from_args(args);
+ match compile_playbook(&hint) {
+ Ok(plan) => {
+ if flag(args, "execute") {
+ match execute_playbook_offline(&plan) {
+ Ok(result) => {
+ print_val(
+ &json!({"plan": plan, "result": result}),
+ json,
+ );
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ } else if json {
+ print_val(&serde_json::to_value(&plan).unwrap(), true);
+ ExitCode::SUCCESS
+ } else {
+ println!("rationale: {}", plan.rationale);
+ for (i, s) in plan.steps.iter().enumerate() {
+ println!(" {}. {} {}", i + 1, s.tool, s.args);
+ }
+ for n in &plan.next_steps {
+ println!(" next: {n}");
+ }
+ ExitCode::SUCCESS
+ }
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+}
+
+fn cmd_playbook(args: &[String], json: bool) -> ExitCode {
+ let hint = hint_from_args(args);
+ match compile_playbook(&hint) {
+ Ok(plan) => {
+ print_val(&playbook_to_mcp_chain(&plan), json);
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+fn cmd_connections(args: &[String], json: bool) -> ExitCode {
+ let filter = ConnFilter {
+ pid: opt(args, "pid").and_then(|s| s.parse().ok()),
+ path_substr: opt(args, "path"),
+ proto: opt(args, "proto"),
+ listening_only: flag(args, "listening"),
+ max: opt(args, "max").and_then(|s| s.parse().ok()),
+ };
+ match list_connections(&filter) {
+ Ok(rows) => {
+ if json {
+ print_val(&json!({"connections": rows}), true);
+ } else {
+ for r in &rows {
+ println!(
+ "{:>6} {:4} {:22} -> {:22} {:12} {}",
+ r.pid,
+ r.proto,
+ r.local,
+ r.remote,
+ r.state,
+ r.image_path.as_deref().unwrap_or("-")
+ );
+ }
+ }
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+fn cmd_owners(args: &[String], json: bool) -> ExitCode {
+ let Some(pid) = opt(args, "pid").and_then(|s| s.parse().ok()) else {
+ eprintln!("usage: ghidrust net owners --pid N [-json]");
+ return ExitCode::from(2);
+ };
+ match owner_for_pid(pid) {
+ Ok(o) => {
+ print_val(&serde_json::to_value(&o).unwrap(), json);
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+fn cmd_capture(args: &[String], json: bool) -> ExitCode {
+ if args.is_empty() {
+ eprintln!("usage: ghidrust net capture start|stop|status …");
+ return ExitCode::from(2);
+ }
+ match args[0].as_str() {
+ "start" => {
+ let req = CaptureStartRequest {
+ iface: opt(args, "iface"),
+ filter: opt(args, "filter"),
+ pid: opt(args, "pid").and_then(|s| s.parse().ok()),
+ path_substr: opt(args, "path"),
+ out_dir: opt(args, "out"),
+ replay_path: opt(args, "replay"),
+ ..Default::default()
+ };
+ match capture_start(req) {
+ Ok(r) => {
+ print_val(&serde_json::to_value(&r).unwrap(), json);
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "stop" => {
+ let Some(sid) = args.get(1) else {
+ eprintln!("usage: ghidrust net capture stop <session_id>");
+ return ExitCode::from(2);
+ };
+ match capture_stop(sid) {
+ Ok(info) => {
+ print_val(&serde_json::to_value(&info).unwrap(), json);
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "status" => {
+ let Some(sid) = args.get(1) else {
+ eprintln!("usage: ghidrust net capture status <session_id>");
+ return ExitCode::from(2);
+ };
+ match capture_status(sid) {
+ Ok(info) => {
+ print_val(&serde_json::to_value(&info).unwrap(), json);
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ other => {
+ eprintln!("unknown capture subcommand: {other}");
+ ExitCode::from(2)
+ }
+ }
+}
+
+fn cmd_flows(args: &[String], json: bool) -> ExitCode {
+ let Some(sid) = args.first() else {
+ eprintln!("usage: ghidrust net flows <session_id> [-json]");
+ return ExitCode::from(2);
+ };
+ let max = opt(args, "max").and_then(|s| s.parse().ok());
+ match flows(sid, max) {
+ Ok(v) => {
+ print_val(&json!({"flows": v}), json);
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+fn cmd_detect(args: &[String], json: bool) -> ExitCode {
+ let rules_path = opt(args, "rules").unwrap_or_else(|| {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("../../rules/ghidrust-minimal.rules")
+ .display()
+ .to_string()
+ });
+ let rules = match load_rules(std::path::Path::new(&rules_path)) {
+ Ok(r) => r,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return ExitCode::FAILURE;
+ }
+ };
+ if let Some(pcap) = opt(args, "pcap").or_else(|| opt(args, "capture")) {
+ match detect_capture_file(std::path::Path::new(&pcap), &rules, &[]) {
+ Ok(alerts) => {
+ ALERT_INDEX.lock().unwrap().clone_from(&alerts);
+ print_val(&json!({"alerts": alerts, "rules": rules_path}), json);
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ } else if let Some(payload) = opt(args, "payload-file") {
+ let data = match std::fs::read(&payload) {
+ Ok(d) => d,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return ExitCode::FAILURE;
+ }
+ };
+ let frames = vec![Frame {
+ ts_ms: 0,
+ proto: "tcp".into(),
+ src: "10.0.0.1".into(),
+ dst: "10.0.0.2".into(),
+ src_port: 12345,
+ dst_port: 80,
+ payload: data,
+ tcp_seq: None,
+ tcp_ack: None,
+ tcp_flags: None,
+ owner: None,
+ }];
+ match detect_frames(&frames, &rules, &[]) {
+ Ok(alerts) => {
+ ALERT_INDEX.lock().unwrap().clone_from(&alerts);
+ print_val(&json!({"alerts": alerts}), json);
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ } else {
+ eprintln!("usage: ghidrust net detect --pcap FILE [--rules PATH] [-json]");
+ ExitCode::from(2)
+ }
+}
+
+fn cmd_rules(args: &[String], json: bool) -> ExitCode {
+ if args.is_empty() {
+ eprintln!("usage: ghidrust net rules list|load|check …");
+ return ExitCode::from(2);
+ }
+ match args[0].as_str() {
+ "list" => {
+ let default = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("../../rules/ghidrust-minimal.rules");
+ print_val(
+ &json!({"packs":[default.display().to_string()], "native": true}),
+ json,
+ );
+ ExitCode::SUCCESS
+ }
+ "load" | "check" => {
+ let Some(path) = opt(args, "path").or_else(|| args.get(1).cloned()) else {
+ eprintln!("usage: ghidrust net rules check --path FILE");
+ return ExitCode::from(2);
+ };
+ match std::fs::read_to_string(&path) {
+ Ok(text) => match compile_rules(&text) {
+ Ok(set) => {
+ print_val(
+ &json!({
+ "ok": true,
+ "path": path,
+ "rule_count": set.rules.len(),
+ "warnings": set.warnings,
+ }),
+ json,
+ );
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ },
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ other => {
+ eprintln!("unknown rules subcommand: {other}");
+ ExitCode::from(2)
+ }
+ }
+}
+
+fn cmd_pivots(args: &[String], json: bool) -> ExitCode {
+ let Some(path) = opt(args, "pcap").or_else(|| opt(args, "file")).or_else(|| args.first().cloned()) else {
+ eprintln!("usage: ghidrust net pivots --pcap FILE [-json]");
+ return ExitCode::from(2);
+ };
+ let data = match std::fs::read(&path) {
+ Ok(d) => d,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return ExitCode::FAILURE;
+ }
+ };
+ // Prefer native capture frames' payloads if magic matches.
+ let piv = if data.starts_with(ghidrust_net_capture::CAPTURE_MAGIC) {
+ match ghidrust_net_capture::read_frames(std::path::Path::new(&path)) {
+ Ok(frames) => {
+ let mut acc = ghidrust_net_schema::PivotFields::default();
+ for f in frames {
+ let p = extract_pivots(&f.payload);
+ acc.dns_qnames.extend(p.dns_qnames);
+ acc.tls_sni.extend(p.tls_sni);
+ if acc.ja3.is_none() {
+ acc.ja3 = p.ja3;
+ }
+ acc.http_hosts.extend(p.http_hosts);
+ acc.http_uris.extend(p.http_uris);
+ acc.smb_shares.extend(p.smb_shares);
+ }
+ acc
+ }
+ Err(_) => extract_pivots(&data),
+ }
+ } else {
+ extract_pivots(&data)
+ };
+ print_val(&serde_json::to_value(&piv).unwrap(), json);
+ ExitCode::SUCCESS
+}
+
+/// MCP dispatch for net_* tools.
+pub fn mcp_net(tool: &str, args: &Value, mode: AgentMode) -> Result<String, String> {
+ if is_network_observe_tool(tool) && matches!(mode, AgentMode::Airgap) {
+ return Err("network observe tools are refused in airgap mode".into());
+ }
+ match tool {
+ "net_dig" => {
+ let hint = NetHint {
+ path: args.get("path").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ pid: args.get("pid").and_then(|v| v.as_u64()).map(|u| u as u32),
+ host: args.get("host").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ ioc: args.get("ioc").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ alert_id: args.get("alert_id").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ flow_ref: args.get("flow_ref").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ };
+ if let Some(aid) = &hint.alert_id {
+ let alerts = ALERT_INDEX.lock().unwrap().clone();
+ let alert = alerts
+ .into_iter()
+ .find(|a| a.id == *aid)
+ .ok_or_else(|| format!("alert not found: {aid}"))?;
+ let path = hint
+ .path
+ .clone()
+ .or_else(|| alert.owner.as_ref().and_then(|o| o.image_path.clone()))
+ .ok_or_else(|| "path required".to_string())?;
+ let cfg = ClosedLoopConfig {
+ auto_analyze: args.get("execute").and_then(|v| v.as_bool()).unwrap_or(true),
+ auto_decompile_limit: 3,
+ attach_live: args.get("live").and_then(|v| v.as_bool()).unwrap_or(false),
+ };
+ let job = execute_closed_loop(&alert, &PathBuf::from(path), &cfg)?;
+ Ok(serde_json::to_string_pretty(&job).unwrap())
+ } else {
+ let plan = compile_playbook(&hint)?;
+ if args.get("execute").and_then(|v| v.as_bool()).unwrap_or(false) {
+ let result = execute_playbook_offline(&plan)?;
+ Ok(serde_json::to_string_pretty(&json!({"plan": plan, "result": result})).unwrap())
+ } else {
+ Ok(serde_json::to_string_pretty(&plan).unwrap())
+ }
+ }
+ }
+ "net_playbook" => {
+ let hint = NetHint {
+ path: args.get("path").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ pid: args.get("pid").and_then(|v| v.as_u64()).map(|u| u as u32),
+ host: args.get("host").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ ioc: args.get("ioc").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ ..Default::default()
+ };
+ let plan = compile_playbook(&hint)?;
+ Ok(serde_json::to_string_pretty(&playbook_to_mcp_chain(&plan)).unwrap())
+ }
+ "net_connections" => {
+ let filter = ConnFilter {
+ pid: args.get("pid").and_then(|v| v.as_u64()).map(|u| u as u32),
+ path_substr: args.get("path").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ proto: args.get("proto").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ max: args.get("max").and_then(|v| v.as_u64()).map(|u| u as usize),
+ ..Default::default()
+ };
+ let rows = list_connections(&filter).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&json!({"connections": rows})).unwrap())
+ }
+ "net_owners" => {
+ let pid = args
+ .get("pid")
+ .and_then(|v| v.as_u64())
+ .ok_or_else(|| "pid required".to_string())? as u32;
+ let o = owner_for_pid(pid).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&o).unwrap())
+ }
+ "net_ifaces" => Ok(serde_json::to_string_pretty(&json!({"interfaces": list_interfaces()})).unwrap()),
+ "net_capture_start" => {
+ let req = CaptureStartRequest {
+ iface: args.get("iface").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ filter: args.get("bpf").or_else(|| args.get("filter")).and_then(|v| v.as_str()).map(|s| s.to_string()),
+ pid: args.get("pid").and_then(|v| v.as_u64()).map(|u| u as u32),
+ path_substr: args.get("path").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ out_dir: args.get("out").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ replay_path: args.get("replay_path").and_then(|v| v.as_str()).map(|s| s.to_string()),
+ ..Default::default()
+ };
+ let r = capture_start(req).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "net_capture_stop" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "session_id required".to_string())?;
+ let info = capture_stop(sid).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&info).unwrap())
+ }
+ "net_capture_status" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "session_id required".to_string())?;
+ let info = capture_status(sid).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&info).unwrap())
+ }
+ "net_flows" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "session_id required".to_string())?;
+ let max = args.get("max").and_then(|v| v.as_u64()).map(|u| u as usize);
+ let v = flows(sid, max).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&json!({"flows": v})).unwrap())
+ }
+ "net_detect" => {
+ let pcap = args
+ .get("pcap")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "pcap required".to_string())?;
+ let rules_path = args
+ .get("rules")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string())
+ .unwrap_or_else(|| {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("../../rules/ghidrust-minimal.rules")
+ .display()
+ .to_string()
+ });
+ let rules = load_rules(std::path::Path::new(&rules_path))?;
+ let mut attr: Vec<(FlowKey, Owner)> = Vec::new();
+ if let Some(ap) = args.get("attr").and_then(|v| v.as_str()) {
+ if let Ok(text) = std::fs::read_to_string(ap) {
+ if let Ok(pairs) = serde_json::from_str::<Vec<(String, Owner)>>(&text) {
+ for (fid, o) in pairs {
+ let _ = fid;
+ attr.push((
+ FlowKey {
+ proto: "tcp".into(),
+ src: String::new(),
+ dst: String::new(),
+ src_port: 0,
+ dst_port: 0,
+ },
+ o,
+ ));
+ }
+ }
+ }
+ }
+ let alerts = detect_capture_file(std::path::Path::new(pcap), &rules, &attr)?;
+ ALERT_INDEX.lock().unwrap().clone_from(&alerts);
+ Ok(serde_json::to_string_pretty(&json!({"alerts": alerts})).unwrap())
+ }
+ "net_alerts" => {
+ let max = args.get("max").and_then(|v| v.as_u64()).map(|u| u as usize);
+ let mut alerts = last_alerts(max);
+ if alerts.is_empty() {
+ alerts = ALERT_INDEX.lock().unwrap().clone();
+ }
+ Ok(serde_json::to_string_pretty(&json!({"alerts": alerts})).unwrap())
+ }
+ "net_rules_list" => Ok(serde_json::to_string_pretty(&json!({
+ "packs": ["rules/ghidrust-minimal.rules"],
+ "native": true
+ }))
+ .unwrap()),
+ "net_rules_load" | "net_rules_check" => {
+ let path = args
+ .get("path")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "path required".to_string())?;
+ let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
+ let set = compile_rules_text(&text)?;
+ Ok(serde_json::to_string_pretty(&json!({
+ "ok": true,
+ "path": path,
+ "rule_count": set.rules.len(),
+ "warnings": set.warnings
+ }))
+ .unwrap())
+ }
+ "net_pivots" => {
+ let pcap = args
+ .get("pcap")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "pcap required".to_string())?;
+ let data = std::fs::read(pcap).map_err(|e| e.to_string())?;
+ let piv = extract_pivots(&data);
+ Ok(serde_json::to_string_pretty(&piv).unwrap())
+ }
+ "net_job_get" => {
+ let id = args
+ .get("job_id")
+ .or_else(|| args.get("artifact_id"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "job_id required".to_string())?;
+ Ok(serde_json::to_string_pretty(&json!({"job_id": id, "status": "unknown"})).unwrap())
+ }
+ _ => Err(format!("unknown net tool: {tool}")),
+ }
+}
+
+#[allow(dead_code)]
+fn _keep_confidence(c: Confidence) -> &'static str {
+ c.as_str()
+}
diff --git a/crates/ghidrust-cli/tests/cli_mcp.rs b/crates/ghidrust-cli/tests/cli_mcp.rs
index 9a1f5a3..82f7cb2 100644
--- a/crates/ghidrust-cli/tests/cli_mcp.rs
+++ b/crates/ghidrust-cli/tests/cli_mcp.rs
@@ -362,6 +362,10 @@ fn mcp_server_info_and_live_tools() {
|| s.contains("\"tool_surface\": 6")
|| s.contains("\"tool_surface\":6")
|| s.contains("\"tool_surface\": 7")
- || s.contains("\"tool_surface\":7");
+ || s.contains("\"tool_surface\":7")
+ || s.contains("\"toolSurface\":8")
+ || s.contains("\"tool_surface\": 8")
+ || s.contains("\"tool_surface\":8");
assert!(surface_ok, "expected tool_surface >= 3 in {s}");
+ assert!(s.contains("net_dig"), "missing net_dig in {s}");
}
diff --git a/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rs b/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rs
index a4aa639..635d588 100644
--- a/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rs
+++ b/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rs
@@ -47,6 +47,7 @@ const EXPECTED_MCP_TOOLS: &[&str] = &[
"process_wait",
"process_step_into",
"process_step_over",
+ "process_step_out",
"process_threads",
"process_thread_context_get",
"process_thread_context_set",
@@ -1056,6 +1057,11 @@ fn eval_cli_mcp_surface_catalog() {
("il2cpp_icalls", json!({ "binary": ipe })),
("rtti_gpu_bench", json!({ "path": pe })),
("process_list", json!({})),
+ // Honest unknown-session proves the tool is wired (debug session not required).
+ (
+ "process_step_out",
+ json!({ "session_id": "eval-missing-session" }),
+ ),
];
const CHUNK: usize = 10;
diff --git a/crates/ghidrust-cli/tests/net_wave0_dig.rs b/crates/ghidrust-cli/tests/net_wave0_dig.rs
new file mode 100644
index 0000000..ff20f5e
--- /dev/null
+++ b/crates/ghidrust-cli/tests/net_wave0_dig.rs
@@ -0,0 +1,40 @@
+//! Wave 0 proving test: dig playbook CLI.
+
+use std::path::PathBuf;
+use std::process::Command;
+
+fn ghidrust_bin() -> PathBuf {
+ PathBuf::from(env!("CARGO_BIN_EXE_ghidrust"))
+}
+
+fn fixture_pe() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/tiny_x64.pe")
+}
+
+#[test]
+fn net_dig_execute_json() {
+ let pe = fixture_pe();
+ assert!(pe.is_file(), "missing fixture {}", pe.display());
+ let out = Command::new(ghidrust_bin())
+ .args([
+ "net",
+ "dig",
+ "--path",
+ pe.to_str().unwrap(),
+ "--host",
+ "example.test",
+ "--execute",
+ "-json",
+ ])
+ .output()
+ .expect("run ghidrust");
+ assert!(
+ out.status.success(),
+ "stderr={}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json");
+ let steps = v["plan"]["steps"].as_array().expect("steps");
+ assert!(steps.len() >= 3, "steps={steps:?}");
+ assert!(v.get("result").is_some());
+}
diff --git a/crates/ghidrust-cli/tests/net_wave_integration.rs b/crates/ghidrust-cli/tests/net_wave_integration.rs
new file mode 100644
index 0000000..7af33e9
--- /dev/null
+++ b/crates/ghidrust-cli/tests/net_wave_integration.rs
@@ -0,0 +1,149 @@
+//! Proving tests for network waves 1–5 (CLI).
+
+use std::path::PathBuf;
+use std::process::Command;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+fn bin() -> PathBuf {
+ PathBuf::from(env!("CARGO_BIN_EXE_ghidrust"))
+}
+
+fn run(args: &[&str]) -> (bool, String, String) {
+ let out = Command::new(bin()).args(args).output().expect("spawn");
+ (
+ out.status.success(),
+ String::from_utf8_lossy(&out.stdout).into_owned(),
+ String::from_utf8_lossy(&out.stderr).into_owned(),
+ )
+}
+
+#[test]
+fn wave1_net_connections_json() {
+ let pid = std::process::id().to_string();
+ let (ok, stdout, stderr) = run(&["net", "connections", "--pid", &pid, "-json"]);
+ assert!(ok, "stderr={stderr}");
+ assert!(stdout.contains("connections"));
+}
+
+#[test]
+fn wave2_replay_capture_flows() {
+ // Capture sessions are in-process (same as process_*): multi-step must share
+ // one process. Prove the library session + CLI detect/pivots on the file.
+ use ghidrust_net_capture::{
+ capture_start, capture_stop, flows, write_frames, CaptureStartRequest,
+ };
+ use ghidrust_net_flow::Frame;
+ use ghidrust_net_schema::{Confidence, Owner};
+
+ let dir = std::env::temp_dir().join(format!(
+ "cli-net-{}",
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ let replay = dir.join("in.grncap");
+ write_frames(
+ &replay,
+ &[Frame {
+ ts_ms: 1,
+ proto: "tcp".into(),
+ src: "10.0.0.1".into(),
+ dst: "10.0.0.2".into(),
+ src_port: 1111,
+ dst_port: 443,
+ payload: b"EVILCMD hello".to_vec(),
+ tcp_seq: None,
+ tcp_ack: None,
+ tcp_flags: None,
+ owner: Some(Owner {
+ pid: 7,
+ image_path: Some("C:\\tmp\\x.exe".into()),
+ image_confidence: Confidence::Exact,
+ pid_confidence: Confidence::Exact,
+ }),
+ }],
+ )
+ .unwrap();
+
+ let start = capture_start(CaptureStartRequest {
+ replay_path: Some(replay.display().to_string()),
+ out_dir: Some(dir.display().to_string()),
+ ..Default::default()
+ })
+ .expect("capture_start");
+ let fl = flows(&start.session_id, None).expect("flows");
+ assert!(!fl.is_empty());
+ assert_eq!(fl[0].owner.as_ref().unwrap().pid, 7);
+ let info = capture_stop(&start.session_id).expect("stop");
+ assert!(std::path::Path::new(info.out_path.as_ref().unwrap()).is_file());
+
+ // CLI one-shot start returns session_id JSON (session not reusable across spawns).
+ let (ok_cli, stdout, stderr) = run(&[
+ "net",
+ "capture",
+ "start",
+ "--replay",
+ replay.to_str().unwrap(),
+ "--out",
+ dir.to_str().unwrap(),
+ "-json",
+ ]);
+ assert!(ok_cli, "stderr={stderr}");
+ assert!(stdout.contains("session_id"));
+
+ let rules = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../rules/ghidrust-minimal.rules");
+ let (ok4, det, e4) = run(&[
+ "net",
+ "detect",
+ "--pcap",
+ replay.to_str().unwrap(),
+ "--rules",
+ rules.to_str().unwrap(),
+ "-json",
+ ]);
+ assert!(ok4, "stderr={e4}");
+ assert!(det.contains("1000001") || det.contains("alerts"), "{det}");
+
+ let http = dir.join("http.bin");
+ std::fs::write(&http, b"GET /x HTTP/1.1\r\nHost: pivot.example\r\n\r\n").unwrap();
+ let (ok5, piv, e5) = run(&["net", "pivots", "--pcap", http.to_str().unwrap(), "-json"]);
+ assert!(ok5, "stderr={e5}");
+ assert!(piv.contains("pivot.example"), "{piv}");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn wave3_rules_check() {
+ let rules = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../rules/ghidrust-minimal.rules");
+ let (ok, stdout, stderr) = run(&[
+ "net",
+ "rules",
+ "check",
+ "--path",
+ rules.to_str().unwrap(),
+ "-json",
+ ]);
+ assert!(ok, "stderr={stderr}");
+ assert!(stdout.contains("rule_count"));
+}
+
+#[test]
+fn wave4_closed_loop_from_alert_fixture() {
+ // Seed alerts via detect, then dig --from-alert requires in-process index.
+ // Prove closed loop via correlate path through dig --execute on fixture.
+ let pe = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/tiny_x64.pe");
+ let (ok, stdout, stderr) = run(&[
+ "net",
+ "dig",
+ "--path",
+ pe.to_str().unwrap(),
+ "--ioc",
+ "127.0.0.1",
+ "--execute",
+ "-json",
+ ]);
+ assert!(ok, "stderr={stderr}");
+ assert!(stdout.contains("result") || stdout.contains("findings") || stdout.contains("plan"));
+}
diff --git a/crates/ghidrust-core/src/lib.rs b/crates/ghidrust-core/src/lib.rs
index d1e0086..28ddfc7 100644
--- a/crates/ghidrust-core/src/lib.rs
+++ b/crates/ghidrust-core/src/lib.rs
@@ -96,8 +96,9 @@ pub use process::{
process_break_clear, process_break_list, process_break_set, process_continue, process_detach,
process_export_snapshot, process_is_suspended, process_launch, process_list, process_modules,
process_pause, process_read, process_regions, process_resolve, process_resume, process_scan_mem,
- process_stack, process_step_into, process_step_over, process_thread_context_get,
- process_thread_context_set, process_threads, process_vtable_probe, process_wait,
+ process_stack, process_step_into, process_step_out, process_step_over,
+ process_thread_context_get, process_thread_context_set, process_threads,
+ process_vtable_probe, process_wait,
process_watch_expr, static_to_live, AcAdvisory, AttachOpts, BreakKind, BreakpointInfo,
ExportSnapshot, LaunchRequest, LaunchResult, ModuleInfo, ProcessError, ProcessErrorCode,
ProcessInfo, ProcessSession, ReadResult, RegionInfo, RegisterSet, ResolveLive, RunState,
@@ -120,7 +121,7 @@ pub use rtti_catalog::{
RttiQueryResult,
};
pub use section_notes::{section_notes_for, SectionNote};
-pub use theme::{m3_tokens, M3Tokens, ThemeMode};
+pub use theme::{m3_tokens, theme_tokens, AppearanceTheme, M3Tokens, ThemeMode};
pub use tree_index::{list_tree, TreeEntry, TreeListOpts, TreeListResult};
pub use xrefs::{
calls_callees, instruction_targets, operand_addresses, rip_relative_targets, xrefs_from,
diff --git a/crates/ghidrust-core/src/process/mod.rs b/crates/ghidrust-core/src/process/mod.rs
index ffbcd39..83daed5 100644
--- a/crates/ghidrust-core/src/process/mod.rs
+++ b/crates/ghidrust-core/src/process/mod.rs
@@ -663,6 +663,33 @@ pub fn process_step_over(session_id: &str, thread_id: Option<u32>) -> Result<(),
}
}
+pub fn process_step_out(session_id: &str, thread_id: Option<u32>) -> Result<(), String> {
+ require_session_cap(session_id, "step")?;
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ let a = m
+ .get_mut(session_id)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())?;
+ let d = a
+ .debug
+ .as_ref()
+ .ok_or_else(|| ProcessError::capability_missing("step").to_string())?;
+ let tid = thread_id
+ .or_else(|| d.last_stop().map(|s| s.thread_id))
+ .ok_or_else(|| "thread_id required when not stopped".to_string())?;
+ d.step_out(tid).map_err(|e| e.to_string())?;
+ a.run_state = d.run_state();
+ Ok(())
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = thread_id;
+ Err(ProcessError::platform().to_string())
+ }
+}
+
pub fn process_threads(session_id: &str) -> Result<Vec<ThreadInfo>, String> {
require_session_cap(session_id, "threads")?;
#[cfg(windows)]
diff --git a/crates/ghidrust-core/src/process/session.rs b/crates/ghidrust-core/src/process/session.rs
index a45a99d..1d261b0 100644
--- a/crates/ghidrust-core/src/process/session.rs
+++ b/crates/ghidrust-core/src/process/session.rs
@@ -163,6 +163,7 @@ pub fn live_process_info_json() -> serde_json::Value {
"process_pause",
"process_step_into",
"process_step_over",
+ "process_step_out",
"process_wait",
"process_threads",
"process_thread_context_get",
diff --git a/crates/ghidrust-core/src/process/win_debug.rs b/crates/ghidrust-core/src/process/win_debug.rs
index fdad302..809e322 100644
--- a/crates/ghidrust-core/src/process/win_debug.rs
+++ b/crates/ghidrust-core/src/process/win_debug.rs
@@ -205,7 +205,6 @@ enum PumpCmd {
pub struct DebugSession {
#[allow(dead_code)]
pub pid: u32,
- #[allow(dead_code)]
pub process: HANDLE,
cmd_tx: Sender<PumpCmd>,
join: Option<JoinHandle<()>>,
@@ -365,6 +364,82 @@ impl DebugSession {
)?
}
+ /// Step out of the current frame.
+ ///
+ /// Prefer a oneshot software BP at the return address (from `[RBP+8]` or
+ /// `[RSP]`), then continue. If that fails, fall back to repeated `step_over`
+ /// until a RET opcode is executed (or a sane max).
+ pub fn step_out(&self, tid: u32) -> Result<(), ProcessError> {
+ if let Some(ret) = self.resolve_return_address(tid) {
+ if self.set_soft_bp(ret, true).is_ok() {
+ return self.continue_exec();
+ }
+ }
+
+ const MAX_STEPS: usize = 4096;
+ for i in 0..MAX_STEPS {
+ let regs = self.get_context(tid)?;
+ let at_ret = insn_is_ret(self.process, regs.rip);
+ if at_ret {
+ return self.step_into(tid);
+ }
+ self.step_over(tid)?;
+ let wr = self.wait(30_000);
+ if wr
+ .event
+ .as_ref()
+ .map(|e| e.reason.as_str() == "exit")
+ .unwrap_or(false)
+ {
+ return Err(ProcessError::new(
+ ProcessErrorCode::ProcessExited,
+ "debuggee exited during step_out",
+ ));
+ }
+ if !wr.ok {
+ return Err(ProcessError::new(
+ ProcessErrorCode::WaitTimeout,
+ format!(
+ "step_out fallback wait failed after {i} steps: {}",
+ wr.message.unwrap_or_else(|| "no stop".into())
+ ),
+ ));
+ }
+ }
+ Err(ProcessError::new(
+ ProcessErrorCode::InvalidState,
+ format!("step_out exceeded {MAX_STEPS} steps without RET"),
+ ))
+ }
+
+ /// Best-effort return address for the current frame.
+ fn resolve_return_address(&self, tid: u32) -> Option<u64> {
+ let regs = self.get_context(tid).ok()?;
+ // Prefer [RBP+8] when the frame pointer looks valid.
+ if regs.rbp >= 0x10000 {
+ let frame = win_observe::read_mem(self.process, regs.rbp, 16);
+ if frame.bytes_read >= 16 {
+ if let Ok(bytes) = frame.bytes[8..16].try_into() {
+ let ret = u64::from_le_bytes(bytes);
+ if looks_like_code_addr(ret) && ret != regs.rip {
+ return Some(ret);
+ }
+ }
+ }
+ }
+ // Fallback: qword at RSP (valid at function entry / after CALL).
+ let top = win_observe::read_mem(self.process, regs.rsp, 8);
+ if top.bytes_read >= 8 {
+ if let Ok(bytes) = top.bytes[0..8].try_into() {
+ let ret = u64::from_le_bytes(bytes);
+ if looks_like_code_addr(ret) && ret != regs.rip {
+ return Some(ret);
+ }
+ }
+ }
+ None
+ }
+
pub fn stack(&self, tid: u32, max_frames: usize) -> Result<Vec<StackFrame>, ProcessError> {
self.send(
|reply| PumpCmd::Stack {
@@ -1012,6 +1087,19 @@ fn set_tf(tid: u32, on: bool) -> Result<(), ProcessError> {
set_thread_regs(tid, &regs)
}
+fn looks_like_code_addr(addr: u64) -> bool {
+ // User-mode canonical range; excludes null/low junk and non-canonical high bits.
+ addr >= 0x10000 && addr < 0x0000_8000_0000_0000
+}
+
+fn insn_is_ret(process: HANDLE, rip: u64) -> bool {
+ let r = win_observe::read_mem(process, rip, 1);
+ if r.bytes_read < 1 {
+ return false;
+ }
+ matches!(r.bytes[0], 0xC3 | 0xCB | 0xC2 | 0xCA)
+}
+
fn insn_preview(process: HANDLE, rip: u64) -> Option<String> {
let r = win_observe::read_mem(process, rip, 16);
if r.bytes_read == 0 {
diff --git a/crates/ghidrust-core/src/theme.rs b/crates/ghidrust-core/src/theme.rs
index 3904120..a483dc2 100644
--- a/crates/ghidrust-core/src/theme.rs
+++ b/crates/ghidrust-core/src/theme.rs
@@ -1,8 +1,14 @@
-//! Material 3–inspired color tokens (shared for docs/tests; GUI applies via egui).
+//! Appearance themes + color tokens (shared for docs/tests; GUI applies via egui).
+//!
+//! Families:
+//! - **Classic Ghidrust** — frozen historical Ghidrust palette (M3-inspired).
+//! - **Modern** — Google Material 3 baseline roles (light + dark).
+//! - **Future Console** — Amber Console design tokens ported 1:1 (see module notes).
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+/// Light / dark (Classic + Modern). For Future Console: Neon gas / Amber CRT gas.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ThemeMode {
Dark,
@@ -18,44 +24,372 @@ impl ThemeMode {
}
}
-/// sRGB 0–255 Material 3–inspired tokens.
+/// Selectable appearance family under File → Configure → Appearance.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum AppearanceTheme {
+ /// Historical Ghidrust look (previous default tokens).
+ #[default]
+ ClassicGhidrust,
+ /// Google Material 3 baseline (full role set, light + dark).
+ Modern,
+ /// Amber Console CRT / neon panel look ([Amber Console](https://dutchdiederik.github.io/AmberConsole/)).
+ FutureConsole,
+}
+
+impl AppearanceTheme {
+ pub const ALL: &[AppearanceTheme] = &[
+ AppearanceTheme::ClassicGhidrust,
+ AppearanceTheme::Modern,
+ AppearanceTheme::FutureConsole,
+ ];
+
+ pub fn display_name(self) -> &'static str {
+ match self {
+ AppearanceTheme::ClassicGhidrust => "Classic Ghidrust",
+ AppearanceTheme::Modern => "Modern",
+ AppearanceTheme::FutureConsole => "Future Console",
+ }
+ }
+
+ pub fn id(self) -> &'static str {
+ match self {
+ AppearanceTheme::ClassicGhidrust => "classic_ghidrust",
+ AppearanceTheme::Modern => "modern",
+ AppearanceTheme::FutureConsole => "future_console",
+ }
+ }
+
+ pub fn from_id(s: &str) -> Self {
+ match s {
+ "modern" => AppearanceTheme::Modern,
+ "future_console" | "amber" | "amber_console" => AppearanceTheme::FutureConsole,
+ _ => AppearanceTheme::ClassicGhidrust,
+ }
+ }
+
+ pub fn description(self) -> &'static str {
+ match self {
+ AppearanceTheme::ClassicGhidrust => {
+ "Original Ghidrust CodeBrowser palette (M3-inspired purple)."
+ }
+ AppearanceTheme::Modern => {
+ "Google Material 3 baseline color roles with light and dark schemes."
+ }
+ AppearanceTheme::FutureConsole => {
+ "Amber Console industrial CRT / neon plasma panel (ported design tokens)."
+ }
+ }
+ }
+
+ /// Label for the light/dark (or gas) toggle in the toolbar.
+ pub fn mode_label(self, mode: ThemeMode) -> &'static str {
+ match (self, mode) {
+ (AppearanceTheme::FutureConsole, ThemeMode::Dark) => "Gas: Neon",
+ (AppearanceTheme::FutureConsole, ThemeMode::Light) => "Gas: Amber",
+ (_, ThemeMode::Dark) => "Theme: Dark",
+ (_, ThemeMode::Light) => "Theme: Light",
+ }
+ }
+}
+
+/// Shared sRGB 0–255 tokens consumed by the GUI (`apply_theme` + pane accents).
+///
+/// Core roles always filled. Extended Material 3 roles are populated for Modern;
+/// Classic / Future Console alias them onto the core set so callers stay uniform.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct M3Tokens {
pub mode: ThemeMode,
+ pub appearance: AppearanceTheme,
pub primary: [u8; 3],
pub on_primary: [u8; 3],
+ pub primary_container: [u8; 3],
+ pub on_primary_container: [u8; 3],
+ pub secondary: [u8; 3],
+ pub on_secondary: [u8; 3],
+ pub secondary_container: [u8; 3],
+ pub on_secondary_container: [u8; 3],
+ pub tertiary: [u8; 3],
+ pub on_tertiary: [u8; 3],
+ pub tertiary_container: [u8; 3],
+ pub on_tertiary_container: [u8; 3],
pub surface: [u8; 3],
+ pub surface_dim: [u8; 3],
+ pub surface_bright: [u8; 3],
+ pub surface_container_lowest: [u8; 3],
+ pub surface_container_low: [u8; 3],
pub surface_container: [u8; 3],
+ pub surface_container_high: [u8; 3],
+ pub surface_container_highest: [u8; 3],
pub on_surface: [u8; 3],
pub on_surface_variant: [u8; 3],
pub outline: [u8; 3],
+ pub outline_variant: [u8; 3],
pub error: [u8; 3],
+ pub on_error: [u8; 3],
+ pub inverse_surface: [u8; 3],
+ pub inverse_on_surface: [u8; 3],
+ pub inverse_primary: [u8; 3],
+ /// Corner radius hint for egui (Classic ≈ 4; Modern ≈ 12; Future Console = 8).
+ pub corner_radius: u8,
+ /// Stroke width hint (Future Console uses 2px soft-key borders).
+ pub stroke_width: f32,
}
+/// Resolve tokens for an appearance family + mode.
+pub fn theme_tokens(appearance: AppearanceTheme, mode: ThemeMode) -> M3Tokens {
+ match appearance {
+ AppearanceTheme::ClassicGhidrust => classic_tokens(mode),
+ AppearanceTheme::Modern => modern_tokens(mode),
+ AppearanceTheme::FutureConsole => future_console_tokens(mode),
+ }
+}
+
+/// Backward-compatible Classic Ghidrust tokens (mode only).
pub fn m3_tokens(mode: ThemeMode) -> M3Tokens {
+ theme_tokens(AppearanceTheme::ClassicGhidrust, mode)
+}
+
+fn fill_aliases(
+ mode: ThemeMode,
+ appearance: AppearanceTheme,
+ primary: [u8; 3],
+ on_primary: [u8; 3],
+ surface: [u8; 3],
+ surface_container: [u8; 3],
+ on_surface: [u8; 3],
+ on_surface_variant: [u8; 3],
+ outline: [u8; 3],
+ error: [u8; 3],
+ corner_radius: u8,
+ stroke_width: f32,
+) -> M3Tokens {
+ M3Tokens {
+ mode,
+ appearance,
+ primary,
+ on_primary,
+ primary_container: surface_container,
+ on_primary_container: on_surface,
+ secondary: on_surface_variant,
+ on_secondary: surface,
+ secondary_container: surface_container,
+ on_secondary_container: on_surface,
+ tertiary: primary,
+ on_tertiary: on_primary,
+ tertiary_container: surface_container,
+ on_tertiary_container: on_surface,
+ surface,
+ surface_dim: surface,
+ surface_bright: surface_container,
+ surface_container_lowest: surface,
+ surface_container_low: surface_container,
+ surface_container,
+ surface_container_high: surface_container,
+ surface_container_highest: surface_container,
+ on_surface,
+ on_surface_variant,
+ outline,
+ outline_variant: outline,
+ error,
+ on_error: on_primary,
+ inverse_surface: on_surface,
+ inverse_on_surface: surface,
+ inverse_primary: primary,
+ corner_radius,
+ stroke_width,
+ }
+}
+
+/// Classic Ghidrust — exact historical values (do not retune).
+fn classic_tokens(mode: ThemeMode) -> M3Tokens {
match mode {
- ThemeMode::Dark => M3Tokens {
+ ThemeMode::Dark => fill_aliases(
mode,
- primary: [0xD0, 0xBC, 0xFF],
- on_primary: [0x38, 0x1E, 0x72],
- surface: [0x14, 0x14, 0x18],
- surface_container: [0x1C, 0x1B, 0x1F],
- on_surface: [0xE6, 0xE1, 0xE5],
- on_surface_variant: [0xCA, 0xC4, 0xD0],
- outline: [0x93, 0x8F, 0x99],
- error: [0xF2, 0xB8, 0xB5],
- },
+ AppearanceTheme::ClassicGhidrust,
+ [0xD0, 0xBC, 0xFF],
+ [0x38, 0x1E, 0x72],
+ [0x14, 0x14, 0x18],
+ [0x1C, 0x1B, 0x1F],
+ [0xE6, 0xE1, 0xE5],
+ [0xCA, 0xC4, 0xD0],
+ [0x93, 0x8F, 0x99],
+ [0xF2, 0xB8, 0xB5],
+ 4,
+ 1.0,
+ ),
+ ThemeMode::Light => fill_aliases(
+ mode,
+ AppearanceTheme::ClassicGhidrust,
+ [0x67, 0x50, 0xA4],
+ [0xFF, 0xFF, 0xFF],
+ [0xFF, 0xFB, 0xFE],
+ [0xF3, 0xED, 0xF7],
+ [0x1C, 0x1B, 0x1F],
+ [0x49, 0x45, 0x4F],
+ [0x79, 0x74, 0x7E],
+ [0xB3, 0x26, 0x1E],
+ 4,
+ 1.0,
+ ),
+ }
+}
+
+/// Google Material 3 baseline scheme (seed / primary40 `#6750A4`).
+/// Role hexes match Material Components Android baseline tonal assignments.
+fn modern_tokens(mode: ThemeMode) -> M3Tokens {
+ match mode {
ThemeMode::Light => M3Tokens {
mode,
+ appearance: AppearanceTheme::Modern,
primary: [0x67, 0x50, 0xA4],
on_primary: [0xFF, 0xFF, 0xFF],
- surface: [0xFF, 0xFB, 0xFE],
+ primary_container: [0xEA, 0xDD, 0xFF],
+ on_primary_container: [0x21, 0x00, 0x5D],
+ secondary: [0x62, 0x5B, 0x71],
+ on_secondary: [0xFF, 0xFF, 0xFF],
+ secondary_container: [0xE8, 0xDE, 0xF8],
+ on_secondary_container: [0x1D, 0x19, 0x2B],
+ tertiary: [0x7D, 0x52, 0x60],
+ on_tertiary: [0xFF, 0xFF, 0xFF],
+ tertiary_container: [0xFF, 0xD8, 0xE4],
+ on_tertiary_container: [0x31, 0x11, 0x1D],
+ error: [0xB3, 0x26, 0x1E],
+ on_error: [0xFF, 0xFF, 0xFF],
+ surface: [0xFE, 0xF7, 0xFF],
+ surface_dim: [0xDE, 0xD8, 0xE1],
+ surface_bright: [0xFE, 0xF7, 0xFF],
+ surface_container_lowest: [0xFF, 0xFF, 0xFF],
+ surface_container_low: [0xF7, 0xF2, 0xFA],
surface_container: [0xF3, 0xED, 0xF7],
- on_surface: [0x1C, 0x1B, 0x1F],
+ surface_container_high: [0xEC, 0xE6, 0xF0],
+ surface_container_highest: [0xE6, 0xE0, 0xE9],
+ on_surface: [0x1D, 0x1B, 0x20],
on_surface_variant: [0x49, 0x45, 0x4F],
outline: [0x79, 0x74, 0x7E],
- error: [0xB3, 0x26, 0x1E],
+ outline_variant: [0xCA, 0xC4, 0xD0],
+ inverse_surface: [0x32, 0x2F, 0x35],
+ inverse_on_surface: [0xF5, 0xEF, 0xF7],
+ inverse_primary: [0xD0, 0xBC, 0xFF],
+ corner_radius: 12,
+ stroke_width: 1.0,
},
+ ThemeMode::Dark => M3Tokens {
+ mode,
+ appearance: AppearanceTheme::Modern,
+ primary: [0xD0, 0xBC, 0xFF],
+ on_primary: [0x38, 0x1E, 0x72],
+ primary_container: [0x4F, 0x37, 0x8B],
+ on_primary_container: [0xEA, 0xDD, 0xFF],
+ secondary: [0xCC, 0xC2, 0xDC],
+ on_secondary: [0x33, 0x2D, 0x41],
+ secondary_container: [0x4A, 0x44, 0x58],
+ on_secondary_container: [0xE8, 0xDE, 0xF8],
+ tertiary: [0xEF, 0xB8, 0xC8],
+ on_tertiary: [0x49, 0x25, 0x32],
+ tertiary_container: [0x63, 0x3B, 0x48],
+ on_tertiary_container: [0xFF, 0xD8, 0xE4],
+ error: [0xF2, 0xB8, 0xB5],
+ on_error: [0x60, 0x14, 0x10],
+ surface: [0x14, 0x12, 0x18],
+ surface_dim: [0x14, 0x12, 0x18],
+ surface_bright: [0x3B, 0x38, 0x3E],
+ surface_container_lowest: [0x0F, 0x0D, 0x13],
+ surface_container_low: [0x1D, 0x1B, 0x20],
+ surface_container: [0x21, 0x1F, 0x26],
+ surface_container_high: [0x2B, 0x29, 0x30],
+ surface_container_highest: [0x36, 0x34, 0x3B],
+ on_surface: [0xE6, 0xE0, 0xE9],
+ on_surface_variant: [0xCA, 0xC4, 0xD0],
+ outline: [0x93, 0x8F, 0x99],
+ outline_variant: [0x49, 0x45, 0x4F],
+ inverse_surface: [0xE6, 0xE0, 0xE9],
+ inverse_on_surface: [0x32, 0x2F, 0x35],
+ inverse_primary: [0x67, 0x50, 0xA4],
+ corner_radius: 12,
+ stroke_width: 1.0,
+ },
+ }
+}
+
+/// Future Console — Amber Console tokens copied 1:1 from
+/// `https://github.com/DutchDiederik/AmberConsole` `src/tokens/colors.css`.
+///
+/// Copyright (c) 2026, Diederik — https://diederik.blog
+/// Licensed under the BSD 3-Clause License (see Amber Console LICENSE).
+///
+/// Mapping:
+/// - `ThemeMode::Dark` → `data-ac-gas="neon"` (default pulsed neon panel)
+/// - `ThemeMode::Light` → `data-ac-gas="amber"` (classic P3 amber CRT phosphor)
+///
+/// Not vendored as a git submodule; design tokens transcribed for egui.
+fn future_console_tokens(mode: ThemeMode) -> M3Tokens {
+ // Exact hex from colors.css — neon block / amber block.
+ let (screen, screen_raised, screen_well, amber_100, amber_90, amber_70, amber_50, amber_30, on_fill) =
+ match mode {
+ // [data-ac-gas="neon"]
+ ThemeMode::Dark => (
+ [0x10, 0x06, 0x00], // --screen: #100600
+ [0x1B, 0x0C, 0x02], // --screen-raised: #1b0c02
+ [0x06, 0x02, 0x00], // --screen-well: #060200
+ [0xFF, 0xA8, 0x6D], // --amber-100: #ffa86d
+ [0xFF, 0x6B, 0x08], // --amber-90: #ff6b08
+ [0xDD, 0x58, 0x00], // --amber-70: #dd5800
+ [0xAB, 0x45, 0x00], // --amber-50: #ab4500
+ [0x5B, 0x25, 0x00], // --amber-30: #5b2500
+ [0x1E, 0x0C, 0x00], // --on-fill: #1e0c00
+ ),
+ // [data-ac-gas="amber"]
+ ThemeMode::Light => (
+ [0x0D, 0x07, 0x00], // --screen: #0d0700
+ [0x17, 0x0E, 0x02], // --screen-raised: #170e02
+ [0x06, 0x02, 0x00], // --screen-well: #060200
+ [0xFF, 0xD0, 0x52], // --amber-100: #ffd052
+ [0xFF, 0xAE, 0x1E], // --amber-90: #ffae1e
+ [0xCD, 0x88, 0x17], // --amber-70: #cd8817
+ [0x8D, 0x5B, 0x10], // --amber-50: #8d5b10
+ [0x4A, 0x2F, 0x08], // --amber-30: #4a2f08
+ [0x1A, 0x0E, 0x00], // --on-fill: #1a0e00
+ ),
+ };
+
+ // Aliases from colors.css `:root` block:
+ // --ink = amber-90, --ink-bright = amber-100, --ink-dim = amber-70,
+ // --ink-faint = amber-50, --fill = amber-90, --stroke = amber-90.
+ M3Tokens {
+ mode,
+ appearance: AppearanceTheme::FutureConsole,
+ primary: amber_90, // --ink / --fill / --stroke
+ on_primary: on_fill, // --on-fill
+ primary_container: amber_70, // --ink-dim
+ on_primary_container: on_fill,
+ secondary: amber_100, // --ink-bright
+ on_secondary: on_fill,
+ secondary_container: amber_50, // --ink-faint / --stroke-dim
+ on_secondary_container: screen,
+ tertiary: amber_30, // --ink-trace
+ on_tertiary: amber_100,
+ tertiary_container: screen_well,
+ on_tertiary_container: amber_70,
+ surface: screen, // --screen
+ surface_dim: screen_well, // --screen-well
+ surface_bright: screen_raised, // --screen-raised
+ surface_container_lowest: screen_well,
+ surface_container_low: screen,
+ surface_container: screen_raised,
+ surface_container_high: amber_30,
+ surface_container_highest: amber_50,
+ on_surface: amber_90, // --ink
+ on_surface_variant: amber_70, // --ink-dim
+ outline: amber_90, // --stroke
+ outline_variant: amber_50, // --stroke-dim
+ error: amber_100, // Amber Console: alarm = inverse/blink, never a new hue
+ on_error: on_fill,
+ inverse_surface: amber_90,
+ inverse_on_surface: on_fill,
+ inverse_primary: amber_100,
+ corner_radius: 8, // --radius: 8px
+ stroke_width: 2.0, // --border-w: 2px
}
}
@@ -64,11 +398,45 @@ mod tests {
use super::*;
#[test]
- fn theme_toggle_and_tokens() {
+ fn theme_toggle_and_classic_tokens() {
assert_eq!(ThemeMode::Dark.toggle(), ThemeMode::Light);
let d = m3_tokens(ThemeMode::Dark);
let l = m3_tokens(ThemeMode::Light);
assert_ne!(d.surface, l.surface);
assert_eq!(d.primary[0], 0xD0);
+ assert_eq!(d.appearance, AppearanceTheme::ClassicGhidrust);
+ }
+
+ #[test]
+ fn modern_differs_from_classic_surface_hierarchy() {
+ let classic = theme_tokens(AppearanceTheme::ClassicGhidrust, ThemeMode::Dark);
+ let modern = theme_tokens(AppearanceTheme::Modern, ThemeMode::Dark);
+ assert_eq!(classic.primary, modern.primary);
+ assert_ne!(classic.surface_container, modern.surface_container);
+ assert_eq!(modern.primary_container, [0x4F, 0x37, 0x8B]);
+ assert_eq!(modern.corner_radius, 12);
+ }
+
+ #[test]
+ fn future_console_matches_amber_console_neon_and_amber_gas() {
+ let neon = theme_tokens(AppearanceTheme::FutureConsole, ThemeMode::Dark);
+ assert_eq!(neon.surface, [0x10, 0x06, 0x00]);
+ assert_eq!(neon.primary, [0xFF, 0x6B, 0x08]);
+ assert_eq!(neon.secondary, [0xFF, 0xA8, 0x6D]);
+ assert_eq!(neon.corner_radius, 8);
+ assert_eq!(neon.stroke_width, 2.0);
+
+ let amber = theme_tokens(AppearanceTheme::FutureConsole, ThemeMode::Light);
+ assert_eq!(amber.surface, [0x0D, 0x07, 0x00]);
+ assert_eq!(amber.primary, [0xFF, 0xAE, 0x1E]);
+ assert_eq!(amber.secondary, [0xFF, 0xD0, 0x52]);
+ }
+
+ #[test]
+ fn appearance_id_round_trip() {
+ for a in AppearanceTheme::ALL {
+ assert_eq!(AppearanceTheme::from_id(a.id()), *a);
+ assert!(!a.display_name().is_empty());
+ }
}
}
diff --git a/crates/ghidrust-gui/Cargo.toml b/crates/ghidrust-gui/Cargo.toml
index 4d25564..3cf3ec2 100644
--- a/crates/ghidrust-gui/Cargo.toml
+++ b/crates/ghidrust-gui/Cargo.toml
@@ -17,12 +17,20 @@ ghidrust-core = { workspace = true, features = ["gpu"] }
# 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.
+# §13 tool panes (IL2CPP Metadata/Methods/ICalls/TouchMap/Stubs) — hand-rolled
+# parser, no Il2CppDumper/Cpp2IL at runtime.
ghidrust-il2cpp = { workspace = true }
+ghidrust-unity-inventory = { 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 }
+ghidrust-net-schema = { workspace = true }
+ghidrust-net-attr = { workspace = true }
+ghidrust-net-capture = { workspace = true }
+ghidrust-net-detect = { workspace = true }
+ghidrust-net-rules = { workspace = true }
+ghidrust-net-parse = { workspace = true }
+ghidrust-net-correlate = { workspace = true }
eframe = { version = "0.31", default-features = true }
egui = "0.31"
# Decode bundled splash / window logo (`assets/ghidrust.png`).
diff --git a/crates/ghidrust-gui/src/app/analysis_job.rs b/crates/ghidrust-gui/src/app/analysis_job.rs
new file mode 100644
index 0000000..305d078
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/analysis_job.rs
@@ -0,0 +1,359 @@
+//! Background analysis job — worker messages, poll/apply/finish.
+//!
+//! Extracted per demonolith Wave 6.
+
+use super::{ConsoleSeverity, GhidrustApp};
+use crate::dock_tabs::DockTab;
+use crate::listing::{default_start_va, reload};
+use ghidrust_core::{
+ analyzer_supports_gpu, set_preferred_bulk_mode, AnalysisRunReport, AnalyzerOutput,
+ BulkScanMode, Program,
+};
+use std::sync::mpsc::{self, Receiver, RecvError, TryRecvError};
+
+
+/// Messages from the background analysis worker → UI thread (polled each frame).
+pub(crate) enum AnalysisWorkerMsg {
+ /// Analyzer at `index` is about to run.
+ StepStarted { index: usize },
+ /// Analyzer at `index` finished; `outputs` are that step's report rows.
+ StepFinished {
+ index: usize,
+ outputs: Vec<AnalyzerOutput>,
+ },
+ /// All selected analyzers finished; return mutated program to the UI.
+ Done { program: Program },
+ /// Hard failure; program is returned so the UI can restore it (may include partial work).
+ Failed { error: String, program: Program },
+}
+
+/// In-progress analysis. Heavy work runs on a background thread; the UI only polls `rx`.
+pub(crate) struct AnalysisJob {
+ pub(crate) names: Vec<String>,
+ pub(crate) index: usize,
+ pub(crate) results: AnalysisRunReport,
+ pub(crate) file_label: String,
+ pub(crate) use_gpu: bool,
+ pub(crate) rx: Receiver<AnalysisWorkerMsg>,
+}
+
+impl GhidrustApp {
+
+ /// Start analysis from dialog selections on a background thread.
+ /// Progress / console lines are delivered via channel and polled each UI frame.
+ pub(crate) fn begin_analysis_job(&mut self) -> Result<(), String> {
+ if self.analysis_job.is_some() {
+ return Err("analysis already in progress".into());
+ }
+ if let Some(id) = self.pending_analyze_file_id.take() {
+ self.open_from_tree(&id)?;
+ }
+ if self.program.is_none() {
+ return Err("no program loaded — open or import a binary first".into());
+ }
+ let names: Vec<String> = self
+ .analyzer_infos
+ .iter()
+ .zip(self.analyzer_enabled.iter())
+ .filter(|(_, on)| **on)
+ .map(|(a, _)| a.name.clone())
+ .collect();
+ if names.is_empty() {
+ return Err("select at least one analyzer".into());
+ }
+ // Bulk mode is applied inside run_analyzers_opts per step when use_gpu.
+ let file_label = self
+ .program
+ .as_ref()
+ .map(|p| p.name.clone())
+ .unwrap_or_else(|| "program".into());
+ let use_gpu = self.use_gpu_experimental;
+ self.log(format!(
+ "Starting analysis on {file_label}: {} analyzer(s), gpu={}",
+ names.len(),
+ use_gpu
+ ));
+ self.status = format!("Analyzing {file_label}…");
+
+ let (msg_tx, msg_rx) = mpsc::channel::<AnalysisWorkerMsg>();
+ // Hand the program to the worker only after spawn succeeds so a spawn
+ // failure cannot drop the only Program copy.
+ let (prog_tx, prog_rx) = mpsc::sync_channel::<Program>(1);
+ let names_worker = names.clone();
+ std::thread::Builder::new()
+ .name("ghidrust-analysis".into())
+ .spawn(move || {
+ let Ok(mut prog) = prog_rx.recv() else {
+ return;
+ };
+ for (index, name) in names_worker.iter().enumerate() {
+ let _ = msg_tx.send(AnalysisWorkerMsg::StepStarted { index });
+ let gpu = use_gpu && analyzer_supports_gpu(name);
+ // catch_unwind: core GPU paths already catch wgpu panics;
+ // belt-and-suspenders so the worker always returns the program.
+ let step = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ ghidrust_core::run_analyzers_opts(&mut prog, &[name.as_str()], gpu)
+ }));
+ match step {
+ Ok(Ok(report)) => {
+ let _ = msg_tx.send(AnalysisWorkerMsg::StepFinished {
+ index,
+ outputs: report.results,
+ });
+ }
+ Ok(Err(e)) => {
+ let _ = msg_tx.send(AnalysisWorkerMsg::Failed {
+ error: e.to_string(),
+ program: prog,
+ });
+ return;
+ }
+ Err(_) => {
+ let _ = msg_tx.send(AnalysisWorkerMsg::Failed {
+ error: format!(
+ "analyzer '{name}' panicked (GPU/validation); try again with GPU off"
+ ),
+ program: prog,
+ });
+ return;
+ }
+ }
+ }
+ let _ = msg_tx.send(AnalysisWorkerMsg::Done { program: prog });
+ })
+ .map_err(|e| format!("failed to spawn analysis worker: {e}"))?;
+
+ let prog = self.program.take().expect("program checked non-None above");
+ if prog_tx.send(prog).is_err() {
+ return Err("analysis worker exited before receiving program".into());
+ }
+
+ self.analysis_job = Some(AnalysisJob {
+ names,
+ index: 0,
+ results: AnalysisRunReport::default(),
+ file_label,
+ use_gpu,
+ rx: msg_rx,
+ });
+ Ok(())
+ }
+
+ /// Poll the analysis worker (non-blocking). Call every frame while `analysis_job` is Some.
+ /// Returns `Ok(true)` when the job has finished and been finalized.
+ pub(crate) fn step_analysis_job(&mut self) -> Result<bool, String> {
+ self.poll_analysis_job(false)
+ }
+
+ /// Block until at least one worker message arrives (tests / headless drain).
+ #[cfg(test)]
+ pub(crate) fn step_analysis_job_blocking(&mut self) -> Result<bool, String> {
+ self.poll_analysis_job(true)
+ }
+
+ pub(crate) fn recv_analysis_msg(&self, block: bool) -> Result<Option<AnalysisWorkerMsg>, String> {
+ let job = self
+ .analysis_job
+ .as_ref()
+ .ok_or_else(|| "no analysis job".to_string())?;
+ if block {
+ match job.rx.recv() {
+ Ok(m) => Ok(Some(m)),
+ Err(RecvError) => Err("analysis worker disconnected".into()),
+ }
+ } else {
+ match job.rx.try_recv() {
+ Ok(m) => Ok(Some(m)),
+ Err(TryRecvError::Empty) => Ok(None),
+ Err(TryRecvError::Disconnected) => Err("analysis worker disconnected".into()),
+ }
+ }
+ }
+
+ pub(crate) fn poll_analysis_job(&mut self, block: bool) -> Result<bool, String> {
+ let Some(first) = self.recv_analysis_msg(block)? else {
+ return Ok(false);
+ };
+ if self.apply_analysis_msg(first)? {
+ return Ok(true);
+ }
+ // Drain any further messages already queued so one frame can catch up.
+ while let Some(msg) = self.recv_analysis_msg(false)? {
+ if self.apply_analysis_msg(msg)? {
+ return Ok(true);
+ }
+ }
+ Ok(false)
+ }
+
+ /// Apply one worker message. Returns `Ok(true)` when the job is fully finished.
+ pub(crate) fn apply_analysis_msg(&mut self, msg: AnalysisWorkerMsg) -> Result<bool, String> {
+ match msg {
+ AnalysisWorkerMsg::StepStarted { index } => {
+ if let Some(job) = self.analysis_job.as_mut() {
+ job.index = index;
+ let total = job.names.len();
+ let label = job.file_label.clone();
+ let cur = job.names.get(index).cloned().unwrap_or_else(|| "…".into());
+ self.status = format!("Analyzing {label} — {}/{total}: {cur}", index + 1);
+ }
+ Ok(false)
+ }
+ AnalysisWorkerMsg::StepFinished { index, outputs } => {
+ let mut log_lines = Vec::new();
+ let mut rtti_upd = None;
+ let mut strings_upd = None;
+ for r in &outputs {
+ log_lines.push(format!("[{}] {} — {}", r.status, r.name, r.message));
+ if r.rtti.is_some() {
+ rtti_upd = r.rtti.clone();
+ }
+ if r.strings.is_some() {
+ strings_upd = r.strings.clone();
+ }
+ }
+ for line in log_lines {
+ let sev = if line.starts_with("[error]") {
+ ConsoleSeverity::Error
+ } else if line.starts_with("[warn") {
+ ConsoleSeverity::Warn
+ } else {
+ ConsoleSeverity::Info
+ };
+ self.log_with(line, sev);
+ }
+ if let Some(r) = rtti_upd {
+ self.rtti = r;
+ }
+ if let Some(s) = strings_upd {
+ self.strings = s;
+ }
+ for r in &outputs {
+ if let Some(c) = &r.crypt_constants {
+ self.crypt_constants = c.clone();
+ }
+ if let Some(o) = &r.obfuscated_strings {
+ self.obfuscated_strings = o.clone();
+ }
+ if let Some(c) = &r.crypto_capabilities {
+ self.crypto_capabilities = c.clone();
+ }
+ }
+ if let Some(job) = self.analysis_job.as_mut() {
+ job.results.results.extend(outputs);
+ job.index = index + 1;
+ }
+ Ok(false)
+ }
+ AnalysisWorkerMsg::Done { program } => {
+ self.program = Some(program);
+ self.finish_analysis_job()?;
+ Ok(true)
+ }
+ AnalysisWorkerMsg::Failed { error, program } => {
+ self.program = Some(program);
+ self.analysis_job = None;
+ set_preferred_bulk_mode(BulkScanMode::ParallelCpu);
+ Err(error)
+ }
+ }
+ }
+
+ pub(crate) fn finish_analysis_job(&mut self) -> Result<(), String> {
+ let job = self
+ .analysis_job
+ .take()
+ .ok_or_else(|| "no analysis job".to_string())?;
+ if let Some(prog) = self.program.as_ref() {
+ let entry = default_start_va(prog, self.listing_focus_va);
+ if let Ok(result) = reload(prog, entry, &self.decode_opts) {
+ self.listing = result.insns;
+ }
+ self.rtti = prog.rtti.clone();
+ }
+ // Capture strings from this run's results
+ for r in &job.results.results {
+ if let Some(ref s) = r.strings {
+ self.strings = s.clone();
+ }
+ if let Some(ref c) = r.crypt_constants {
+ self.crypt_constants = c.clone();
+ }
+ if let Some(ref o) = r.obfuscated_strings {
+ self.obfuscated_strings = o.clone();
+ }
+ if let Some(ref c) = r.crypto_capabilities {
+ self.crypto_capabilities = c.clone();
+ }
+ }
+ if let Some(prog) = self.program.as_ref() {
+ if self.crypt_constants.is_empty() {
+ self.crypt_constants = prog.analysis.crypt_constants.clone();
+ }
+ if self.obfuscated_strings.is_empty() {
+ self.obfuscated_strings = prog.analysis.obfuscated_strings.clone();
+ }
+ if self.crypto_capabilities.is_empty() {
+ self.crypto_capabilities = prog.analysis.crypto_capabilities.clone();
+ }
+ }
+ self.rtti_filter.clear();
+ self.rtti_filter_cache.clear();
+ self.rtti_filtered_idx.clear();
+ self.rebuild_rtti_filter_cache();
+ self.last_analyzers_run = job.names.clone();
+ let n = job.results.results.len();
+ self.last_analysis = job.results;
+ let summary = self.analysis_summary_line();
+ let banner = format!(
+ "Analysis complete on {} — {n} analyzer(s) · {summary}{}",
+ job.file_label,
+ if job.use_gpu {
+ " · GPU experimental"
+ } else {
+ ""
+ }
+ );
+ self.analysis_done_banner = Some(banner.clone());
+ self.status = banner.clone();
+ self.log(banner);
+ if self.project.is_some() && self.active_file_id.is_some() {
+ let _ = self.save_results();
+ self.log("Results saved to project (results/ + exports/).");
+ }
+ 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();
+ if let Some(va) = self
+ .listing_focus_va
+ .or_else(|| self.listing.first().map(|i| i.address))
+ .or_else(|| self.program.as_ref().and_then(|p| p.entry))
+ {
+ self.refresh_decompiler_at(va);
+ }
+ // Restore default bulk mode after experimental run
+ set_preferred_bulk_mode(BulkScanMode::ParallelCpu);
+ Ok(())
+ }
+
+ pub(crate) fn analysis_progress_fraction(&self) -> Option<f32> {
+ self.analysis_job.as_ref().map(|j| {
+ if j.names.is_empty() {
+ 1.0
+ } else {
+ j.index as f32 / j.names.len() as f32
+ }
+ })
+ }
+
+ /// Headless/sync: begin job and drain all worker messages (tests + non-UI callers).
+ #[cfg(test)]
+ pub(crate) fn run_selected_analysis(&mut self) -> Result<(), String> {
+ self.begin_analysis_job()?;
+ while self.analysis_job.is_some() {
+ self.step_analysis_job_blocking()?;
+ }
+ Ok(())
+ }
+}
diff --git a/crates/ghidrust-gui/src/app/center_panes.rs b/crates/ghidrust-gui/src/app/center_panes.rs
new file mode 100644
index 0000000..cda4ee6
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/center_panes.rs
@@ -0,0 +1,1688 @@
+//! Center dock panes + edit dialogs (overview/listing/decomp/DTM).
+//!
+//! Extracted per demonolith Wave 5.
+
+use super::{
+ first_address_hint, first_scalar_hint, token_style, GhidrustApp,
+ NewTypeKind,
+};
+use crate::decrypt_ui::DecryptTab;
+use crate::decomp_tokens::TokenKind;
+use crate::events::{EventSource, GhidrustEvent};
+use crate::icons::status_badge;
+use crate::listing::{
+ listing_matches, ui_search_bar, ui_toolbar, ListingRow,
+ ToolbarAction,
+};
+use crate::menu_actions::{
+ parse_address, DecompStage,
+ ListingSelection,
+};
+use crate::nav::NavLocation;
+use crate::panes::{BookmarkKind, PaneKind};
+use eframe::egui::{self, Color32};
+use ghidrust_core::{CommentKind, BUILTIN_TYPES};
+use std::collections::BTreeMap;
+
+impl GhidrustApp {
+
+ pub(crate) fn ui_overview(&mut self, ui: &mut egui::Ui) {
+ let t = self.tokens();
+ let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
+ let muted = Color32::from_rgb(
+ t.on_surface_variant[0],
+ t.on_surface_variant[1],
+ t.on_surface_variant[2],
+ );
+ let ok = Color32::from_rgb(0x4C, 0xAF, 0x50);
+
+ ui.heading("Overview");
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program open.");
+ ui.label("Project Tree: double-click a file (or Open) to load it into this view.");
+ ui.label("If the file is Analyzed, RTTI / functions load from results/ automatically.");
+ return;
+ };
+
+ ui.horizontal(|ui| {
+ ui.heading(&prog.name);
+ if !self.rtti.classes.is_empty() || !prog.analysis.functions.is_empty() {
+ status_badge(ui, true, ok, muted);
+ } else {
+ status_badge(ui, false, ok, muted);
+ }
+ });
+ ui.label(
+ egui::RichText::new(format!(
+ "{} · image base {:#x}{}",
+ prog.format,
+ prog.image_base,
+ prog.entry
+ .map(|e| format!(" · entry {e:#x}"))
+ .unwrap_or_default()
+ ))
+ .color(muted),
+ );
+
+ ui.add_space(8.0);
+ ui.horizontal(|ui| {
+ let card = |ui: &mut egui::Ui, title: &str, value: String| {
+ ui.group(|ui| {
+ ui.set_min_width(120.0);
+ ui.label(egui::RichText::new(title).small().color(muted));
+ ui.label(
+ egui::RichText::new(value)
+ .strong()
+ .color(primary)
+ .size(18.0),
+ );
+ });
+ };
+ card(
+ ui,
+ "Functions",
+ format!("{}", prog.analysis.functions.len()),
+ );
+ card(ui, "RTTI classes", format!("{}", self.rtti.classes.len()));
+ card(ui, "Strings", format!("{}", self.strings.len()));
+ card(ui, "Listing lines", format!("{}", self.listing.len()));
+ card(ui, "Sections", format!("{}", prog.sections.len()));
+ });
+
+ ui.add_space(10.0);
+ if !self.last_analyzers_run.is_empty() {
+ ui.label(egui::RichText::new("Analyzers last run / saved").strong());
+ ui.horizontal_wrapped(|ui| {
+ for a in &self.last_analyzers_run {
+ ui.small(format!("[{a}]"));
+ }
+ });
+ } else {
+ ui.weak("No analyzer list saved for this session — run Analyze to record one.");
+ }
+
+ if !self.rtti.notes.is_empty() {
+ ui.add_space(6.0);
+ ui.label(egui::RichText::new("RTTI notes").strong());
+ for n in &self.rtti.notes {
+ ui.small(n);
+ }
+ }
+
+ ui.add_space(12.0);
+ ui.separator();
+ ui.label(egui::RichText::new("What to do next").strong());
+ ui.label("• Symbol Tree (right): expand Classes / RTTI, type a filter, scroll the list.");
+ ui.label("• Listing tab: entry disassembly.");
+ ui.label("• Analyze: re-run analyzers (shows options + progress).");
+ if self.rtti.classes.len() > 1000 {
+ ui.label(
+ egui::RichText::new(format!(
+ "• Large RTTI set ({} classes) — always filter; the list is virtualized so it stays smooth.",
+ self.rtti.classes.len()
+ ))
+ .color(primary),
+ );
+ }
+
+ // Sample of first few RTTI hits for confidence without opening the full drawer
+ if !self.rtti.classes.is_empty() {
+ ui.add_space(10.0);
+ ui.label(egui::RichText::new("RTTI sample (first 12)").strong());
+ egui::ScrollArea::vertical()
+ .max_height(160.0)
+ .show(ui, |ui| {
+ for c in self.rtti.classes.iter().take(12) {
+ let va = c
+ .type_info_va
+ .map(|v| format!("{v:#x}"))
+ .unwrap_or_else(|| "—".into());
+ ui.monospace(format!("{va} {}", c.name));
+ }
+ });
+ if ui.button("Focus Symbol Tree → RTTI").clicked() {
+ self.show_symbol_tree = true;
+ }
+ }
+ }
+
+ /// draw all edit dialogs (rename / retype / comment / signature / new type).
+ pub(crate) fn draw_edit_dialogs(&mut self, ctx: &egui::Context) {
+ // Rename dialog .
+ if self.show_rename_dialog {
+ let mut close = false;
+ let mut confirm = false;
+ let va = self.rename_dialog_target_va;
+ egui::Window::new("Rename")
+ .id(egui::Id::new("dialog_rename"))
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ if let Some(va) = va {
+ ui.label(format!("Address: {va:#x}"));
+ }
+ ui.label(format!("Old name: {}", self.rename_dialog_old_name));
+ ui.label("New name:");
+ let resp = ui.text_edit_singleline(&mut self.rename_dialog_new_name);
+ if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
+ confirm = true;
+ }
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ if ui.button("Rename").clicked() {
+ confirm = true;
+ }
+ });
+ });
+ if confirm {
+ if let Some(va) = va {
+ if let Err(e) = self.rename_at(va, self.rename_dialog_new_name.clone()) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ } else {
+ close = true;
+ }
+ }
+ }
+ if close {
+ self.show_rename_dialog = false;
+ }
+ }
+
+ // Retype dialog .
+ if self.show_retype_dialog {
+ let mut close = false;
+ let mut confirm = false;
+ let va = self.retype_dialog_target_va;
+ egui::Window::new("Retype")
+ .id(egui::Id::new("dialog_retype"))
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ if let Some(va) = va {
+ ui.label(format!("Address: {va:#x}"));
+ }
+ ui.label("Type .:");
+ let resp = ui.text_edit_singleline(&mut self.retype_dialog_type);
+ if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
+ confirm = true;
+ }
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ if ui.button("Clear").clicked() {
+ self.retype_dialog_type.clear();
+ confirm = true;
+ }
+ if ui.button("Apply").clicked() {
+ confirm = true;
+ }
+ });
+ });
+ if confirm {
+ if let Some(va) = va {
+ if let Err(e) = self.retype_at(va, self.retype_dialog_type.clone()) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ } else {
+ close = true;
+ }
+ }
+ }
+ if close {
+ self.show_retype_dialog = false;
+ }
+ }
+
+ // Comment dialog (Set EOL/Pre/Post/Plate/Repeatable).
+ if self.show_comment_dialog {
+ let mut close = false;
+ let mut confirm = false;
+ let va = self.comment_dialog_target_va;
+ egui::Window::new("Set Comment")
+ .id(egui::Id::new("dialog_comment"))
+ .collapsible(false)
+ .resizable(true)
+ .default_width(420.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ if let Some(va) = va {
+ ui.label(format!("Address: {va:#x}"));
+ }
+ ui.horizontal(|ui| {
+ ui.label("Kind:");
+ egui::ComboBox::from_id_salt("comment_kind")
+ .selected_text(self.comment_dialog_kind.label())
+ .show_ui(ui, |ui| {
+ for k in CommentKind::ALL {
+ if ui
+ .selectable_value(
+ &mut self.comment_dialog_kind,
+ *k,
+ k.label(),
+ )
+ .clicked()
+ {
+ // Load existing text for that kind.
+ if let (Some(va), Some(prog)) = (va, self.program.as_ref())
+ {
+ self.comment_dialog_text = prog
+ .edits
+ .comment_at(va, *k)
+ .unwrap_or_default()
+ .to_string();
+ }
+ }
+ }
+ });
+ });
+ ui.label("Text:");
+ ui.add(
+ egui::TextEdit::multiline(&mut self.comment_dialog_text)
+ .desired_rows(4)
+ .desired_width(f32::INFINITY),
+ );
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ if ui.button("Clear").clicked() {
+ self.comment_dialog_text.clear();
+ confirm = true;
+ }
+ if ui.button("Save").clicked() {
+ confirm = true;
+ }
+ });
+ });
+ if confirm {
+ if let Some(va) = va {
+ if let Err(e) = self.set_comment_at(
+ va,
+ self.comment_dialog_kind,
+ self.comment_dialog_text.clone(),
+ ) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ } else {
+ close = true;
+ }
+ }
+ }
+ if close {
+ self.show_comment_dialog = false;
+ }
+ }
+
+ // Function-signature dialog (Edit Function Signature).
+ if self.show_fn_signature_dialog {
+ let mut close = false;
+ let mut confirm = false;
+ let entry = self.fn_signature_dialog_entry;
+ egui::Window::new("Edit Function Signature")
+ .id(egui::Id::new("dialog_fn_sig"))
+ .collapsible(false)
+ .resizable(true)
+ .default_width(520.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ if let Some(entry) = entry {
+ ui.label(format!("Function entry: {entry:#x}"));
+ }
+ ui.label("Signature:");
+ ui.add(
+ egui::TextEdit::multiline(&mut self.fn_signature_dialog_text)
+ .desired_rows(3)
+ .desired_width(f32::INFINITY)
+ .font(egui::FontId::monospace(13.0)),
+ );
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ if ui.button("Save").clicked() {
+ confirm = true;
+ }
+ });
+ });
+ if confirm {
+ if let Some(entry) = entry {
+ if let Err(e) =
+ self.set_function_signature(entry, self.fn_signature_dialog_text.clone())
+ {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ } else {
+ close = true;
+ }
+ }
+ }
+ if close {
+ self.show_fn_signature_dialog = false;
+ }
+ }
+
+ // DTM Apply-at-address dialog (separate module to avoid menu merge conflicts).
+ {
+ let muted = Color32::from_rgb(0x9E, 0x9E, 0x9E);
+ if let Some((va, type_name)) = crate::wire_dialogs::ui_apply_type_at_address(
+ ctx,
+ &mut self.apply_type_dialog,
+ muted,
+ ) {
+ if let Err(e) = self.apply_type_at(va, type_name) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+
+ // New Type dialog (DTM → New → Structure/Union/Enum/Typedef/FunctionDef).
+ if self.show_new_type_dialog {
+ let mut close = false;
+ let mut confirm = false;
+ let kind = self.new_type_dialog_kind;
+ egui::Window::new(format!("New {}", kind.label()))
+ .id(egui::Id::new("dialog_new_type"))
+ .collapsible(false)
+ .resizable(true)
+ .default_width(560.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.label("Name:");
+ ui.text_edit_singleline(&mut self.new_type_dialog_name);
+ ui.label(format!("{} body:", kind.label()));
+ ui.add(
+ egui::TextEdit::multiline(&mut self.new_type_dialog_body)
+ .desired_rows(8)
+ .desired_width(f32::INFINITY)
+ .font(egui::FontId::monospace(13.0)),
+ );
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ if ui.button("Create").clicked() {
+ confirm = true;
+ }
+ });
+ });
+ if confirm {
+ let name = self.new_type_dialog_name.clone();
+ let body = format!("{}\n{}", kind.label(), self.new_type_dialog_body);
+ if let Err(e) = self.define_user_type(name, body) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ } else {
+ close = true;
+ }
+ }
+ if close {
+ self.show_new_type_dialog = false;
+ }
+ }
+
+ // Edit Type dialog (DTM → Edit on an existing user type).
+ if self.show_edit_type_dialog {
+ let mut close = false;
+ let mut confirm = false;
+ let orig = self.edit_type_dialog_orig_name.clone();
+ egui::Window::new(format!("Edit type · {orig}"))
+ .id(egui::Id::new("dialog_edit_type"))
+ .collapsible(false)
+ .resizable(true)
+ .default_width(560.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.label("Name:");
+ ui.text_edit_singleline(&mut self.edit_type_dialog_name);
+ ui.label("Body .:");
+ ui.add(
+ egui::TextEdit::multiline(&mut self.edit_type_dialog_body)
+ .desired_rows(10)
+ .desired_width(f32::INFINITY)
+ .font(egui::FontId::monospace(13.0)),
+ );
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ if ui.button("Delete").clicked() {
+ if let Err(e) = self.delete_user_type(&orig) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ } else {
+ close = true;
+ }
+ }
+ if ui.button("Save").clicked() {
+ confirm = true;
+ }
+ });
+ });
+ if confirm {
+ let new_name = self.edit_type_dialog_name.clone();
+ let body = self.edit_type_dialog_body.clone();
+ if let Err(e) = self.edit_user_type(&orig, new_name, body) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ } else {
+ close = true;
+ }
+ }
+ if close {
+ self.show_edit_type_dialog = false;
+ }
+ }
+
+ // Data Type Chooser dialog .
+ if self.show_type_chooser_dialog {
+ let mut close = false;
+ let mut apply: Option<String> = None;
+ let va = self.type_chooser_target_va;
+ egui::Window::new("Choose Data Type")
+ .id(egui::Id::new("dialog_type_chooser"))
+ .collapsible(false)
+ .resizable(true)
+ .default_width(420.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ if let Some(va) = va {
+ ui.small(format!("Apply target: {va:#x}"));
+ } else {
+ ui.weak("No cursor VA — click a Listing line first.");
+ }
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.type_chooser_filter)
+ .desired_width(240.0)
+ .hint_text("Type name…"),
+ );
+ });
+ let q = self.type_chooser_filter.to_ascii_lowercase();
+ let user_types: Vec<String> = self
+ .program
+ .as_ref()
+ .map(|p| p.edits.user_types.keys().cloned().collect())
+ .unwrap_or_default();
+ egui::ScrollArea::vertical()
+ .id_salt("type_chooser_scroll")
+ .max_height(280.0)
+ .show(ui, |ui| {
+ for name in BUILTIN_TYPES {
+ if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {
+ continue;
+ }
+ ui.horizontal(|ui| {
+ ui.monospace(*name);
+ ui.with_layout(
+ egui::Layout::right_to_left(egui::Align::Center),
+ |ui| {
+ if ui.small_button("Apply").clicked() {
+ apply = Some((*name).to_string());
+ }
+ },
+ );
+ });
+ }
+ if !user_types.is_empty() {
+ ui.separator();
+ ui.small("Program archive:");
+ for name in &user_types {
+ if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {
+ continue;
+ }
+ ui.horizontal(|ui| {
+ ui.monospace(name);
+ ui.with_layout(
+ egui::Layout::right_to_left(egui::Align::Center),
+ |ui| {
+ if ui.small_button("Apply").clicked() {
+ apply = Some(name.clone());
+ }
+ },
+ );
+ });
+ }
+ }
+ });
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ });
+ });
+ if let Some(name) = apply {
+ if let Some(va) = va {
+ if let Err(e) = self.apply_type_at(va, name) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ } else {
+ close = true;
+ }
+ } else {
+ self.status = "No cursor VA — click a Listing line first".into();
+ self.log_warn(self.status.clone());
+ }
+ }
+ if close {
+ self.show_type_chooser_dialog = false;
+ }
+ }
+ }
+
+ /// Data Type Manager tree (Built-In archive + Program archive).
+ pub(crate) fn ui_dtm_pane(&mut self, ui: &mut egui::Ui) {
+ ui.heading("Data Type Manager");
+ ui.small(
+ egui::RichText::new(
+ "DataTypeManagerPlugin · Built-In archive + Program archive (user types)",
+ )
+ .weak(),
+ );
+ ui.separator();
+ if self.dtm_apply_addr_input.is_empty() {
+ if let Some(va) = self.listing_focus_va {
+ self.dtm_apply_addr_input = format!("{va:#x}");
+ }
+ }
+ let mut bar_apply: Option<String> = None;
+ let mut open_apply_dialog = false;
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.dtm_filter)
+ .desired_width(200.0)
+ .hint_text("Type name…"),
+ );
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if ui
+ .button("Apply at address…")
+ .on_hover_text("Open Apply-at-address dialog (no drag-and-drop needed)")
+ .clicked()
+ {
+ open_apply_dialog = true;
+ }
+ ui.menu_button("New…", |ui| {
+ for k in NewTypeKind::ALL {
+ if ui.button(k.label()).clicked() {
+ self.open_new_type_dialog(*k);
+ ui.close_menu();
+ }
+ }
+ });
+ });
+ });
+ if let Some(t) = crate::wire_dialogs::ui_dtm_apply_bar(
+ ui,
+ &mut self.dtm_apply_addr_input,
+ self.dtm_selected_type.as_deref(),
+ ui.visuals().weak_text_color(),
+ ) {
+ bar_apply = Some(t);
+ }
+ let q = self.dtm_filter.to_ascii_lowercase();
+ // Per-frame action queue so we can mutate `self` outside the borrowed
+ // scroll-area closure below without fighting the borrow checker.
+ let mut pending_apply: Option<String> = None;
+ let mut pending_typedef_on: Option<String> = None;
+ let mut pending_pointer_to: Option<String> = None;
+ let mut pending_edit: Option<String> = None;
+ let mut pending_rename: Option<String> = None;
+ let mut pending_delete: Option<String> = None;
+ let mut pending_select: Option<String> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("dtm_scroll")
+ .auto_shrink([false, false])
+ .show(ui, |ui| {
+ // Built-In archive. Read-only leaves — 's
+ // Built-In archive is not editable; right-click gives us
+ // Apply / +Typedef / +Pointer / Copy-to-program.
+ egui::CollapsingHeader::new("Built-In")
+ .default_open(true)
+ .show(ui, |ui| {
+ for name in BUILTIN_TYPES {
+ if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {
+ continue;
+ }
+ let row_resp = ui
+ .horizontal(|ui| {
+ if ui
+ .selectable_label(
+ self.dtm_selected_type.as_deref() == Some(*name),
+ egui::RichText::new(*name).monospace(),
+ )
+ .clicked()
+ {
+ pending_select = Some((*name).to_string());
+ }
+ ui.with_layout(
+ egui::Layout::right_to_left(egui::Align::Center),
+ |ui| {
+ if ui
+ .small_button("+Ptr")
+ .on_hover_text("New Pointer to X .")
+ .clicked()
+ {
+ pending_pointer_to = Some((*name).to_string());
+ }
+ if ui
+ .small_button("+Typedef")
+ .on_hover_text("New Typedef on X .")
+ .clicked()
+ {
+ pending_typedef_on = Some((*name).to_string());
+ }
+ if ui
+ .small_button("Apply")
+ .on_hover_text(
+ "Apply at listing cursor, or open address dialog",
+ )
+ .clicked()
+ {
+ if self.listing_focus_va.is_some() {
+ pending_apply = Some((*name).to_string());
+ } else {
+ pending_select = Some((*name).to_string());
+ open_apply_dialog = true;
+ }
+ }
+ },
+ );
+ })
+ .response;
+ // right-click submenu (Rename/Delete
+ // Cut/Copy/Paste are N/A on Built-In, so we only
+ // offer the applicable actions).
+ row_resp.context_menu(|ui| {
+ ui.label(egui::RichText::new(*name).monospace());
+ ui.separator();
+ if ui.button("Apply @ cursor").clicked() {
+ if self.listing_focus_va.is_some() {
+ pending_apply = Some((*name).to_string());
+ } else {
+ pending_select = Some((*name).to_string());
+ open_apply_dialog = true;
+ }
+ ui.close_menu();
+ }
+ if ui.button("Apply at address…").clicked() {
+ pending_select = Some((*name).to_string());
+ open_apply_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("New Typedef on X").clicked() {
+ pending_typedef_on = Some((*name).to_string());
+ ui.close_menu();
+ }
+ if ui.button("New Pointer to X").clicked() {
+ pending_pointer_to = Some((*name).to_string());
+ ui.close_menu();
+ }
+ });
+ }
+ });
+ // Program archive: user-defined types + analyzer-recovered RTTI classes.
+ let (user_types, rtti_classes) = self
+ .program
+ .as_ref()
+ .map(|p| {
+ (
+ p.edits.user_types.clone(),
+ p.rtti
+ .classes
+ .iter()
+ .map(|c| c.name.clone())
+ .collect::<Vec<_>>(),
+ )
+ })
+ .unwrap_or_default();
+ let title = format!(
+ "Program ({user} user + {rtti} RTTI)",
+ user = user_types.len(),
+ rtti = rtti_classes.len()
+ );
+ egui::CollapsingHeader::new(title)
+ .default_open(true)
+ .show(ui, |ui| {
+ if user_types.is_empty() && rtti_classes.is_empty() {
+ ui.weak(
+ "Empty — use New… to define a Structure/Union/Enum/Typedef/FunctionDef.",
+ );
+ }
+ for (name, body) in &user_types {
+ if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {
+ continue;
+ }
+ let row_resp = ui
+ .horizontal(|ui| {
+ ui.monospace(name.to_string());
+ ui.weak(
+ egui::RichText::new(
+ body.lines().next().unwrap_or_default().to_string(),
+ )
+ .italics(),
+ );
+ ui.with_layout(
+ egui::Layout::right_to_left(egui::Align::Center),
+ |ui| {
+ if ui.small_button("Delete").clicked() {
+ pending_delete = Some(name.clone());
+ }
+ if ui.small_button("Rename…").clicked() {
+ pending_rename = Some(name.clone());
+ }
+ if ui.small_button("Edit…").clicked() {
+ pending_edit = Some(name.clone());
+ }
+ if let Some(va) = self.listing_focus_va {
+ if ui
+ .small_button("Apply @ cursor")
+ .on_hover_text(format!(
+ "Apply {name} at {va:#x}"
+ ))
+ .clicked()
+ {
+ pending_apply = Some(name.clone());
+ }
+ }
+ },
+ );
+ })
+ .response;
+ row_resp.context_menu(|ui| {
+ ui.label(egui::RichText::new(name).monospace());
+ ui.separator();
+ if ui.button("Edit…").clicked() {
+ pending_edit = Some(name.clone());
+ ui.close_menu();
+ }
+ if ui.button("Rename…").clicked() {
+ pending_rename = Some(name.clone());
+ ui.close_menu();
+ }
+ if ui.button("Delete").clicked() {
+ pending_delete = Some(name.clone());
+ ui.close_menu();
+ }
+ ui.separator();
+ let has_va = self.listing_focus_va.is_some();
+ if ui
+ .add_enabled(has_va, egui::Button::new("Apply @ cursor"))
+ .clicked()
+ {
+ pending_apply = Some(name.clone());
+ ui.close_menu();
+ }
+ if ui.button("New Typedef on X").clicked() {
+ pending_typedef_on = Some(name.clone());
+ ui.close_menu();
+ }
+ if ui.button("New Pointer to X").clicked() {
+ pending_pointer_to = Some(name.clone());
+ ui.close_menu();
+ }
+ });
+ }
+ if !rtti_classes.is_empty() {
+ ui.separator();
+ ui.small(egui::RichText::new("RTTI classes (from analyzer)").weak());
+ for name in &rtti_classes {
+ if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {
+ continue;
+ }
+ let row_resp = ui
+ .horizontal(|ui| {
+ ui.monospace(name);
+ ui.with_layout(
+ egui::Layout::right_to_left(egui::Align::Center),
+ |ui| {
+ if ui.small_button("+Ptr").clicked() {
+ pending_pointer_to = Some(name.clone());
+ }
+ if ui.small_button("+Typedef").clicked() {
+ pending_typedef_on = Some(name.clone());
+ }
+ if self.listing_focus_va.is_some()
+ && ui.small_button("Apply @ cursor").clicked()
+ {
+ pending_apply = Some(name.clone());
+ }
+ },
+ );
+ })
+ .response;
+ row_resp.context_menu(|ui| {
+ ui.label(egui::RichText::new(name).monospace());
+ ui.separator();
+ let has_va = self.listing_focus_va.is_some();
+ if ui
+ .add_enabled(has_va, egui::Button::new("Apply @ cursor"))
+ .clicked()
+ {
+ pending_apply = Some(name.clone());
+ ui.close_menu();
+ }
+ if ui.button("New Typedef on X").clicked() {
+ pending_typedef_on = Some(name.clone());
+ ui.close_menu();
+ }
+ if ui.button("New Pointer to X").clicked() {
+ pending_pointer_to = Some(name.clone());
+ ui.close_menu();
+ }
+ });
+ }
+ }
+ });
+ });
+ ui.separator();
+ ui.small(
+ egui::RichText::new(
+ "Select a type, then Apply at address (bar / dialog). Right-click for \
+ Edit / Rename / Delete / Apply. Drag-and-drop not required.",
+ )
+ .weak()
+ .italics(),
+ );
+ // Flush queued actions after the scroll-area borrow drops.
+ if let Some(name) = pending_select {
+ self.dtm_selected_type = Some(name);
+ }
+ if open_apply_dialog {
+ self.apply_type_dialog.open_with(
+ self.listing_focus_va,
+ self.dtm_selected_type.clone().unwrap_or_default(),
+ );
+ }
+ if let Some(name) = bar_apply {
+ if let Some(va) = parse_address(self.dtm_apply_addr_input.trim()).ok() {
+ if let Err(e) = self.apply_type_at(va, name) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ }
+ } else {
+ self.status = "Apply at address: invalid hex address".into();
+ self.log_error(self.status.clone());
+ }
+ }
+ if let Some(name) = pending_apply {
+ if let Some(va) = self.listing_focus_va {
+ if let Err(e) = self.apply_type_at(va, name) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ if let Some(name) = pending_typedef_on {
+ match self.new_typedef_on(&name) {
+ Ok(new_name) => {
+ self.status = format!("Created typedef {new_name} on {name}");
+ self.log(self.status.clone());
+ }
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ if let Some(name) = pending_pointer_to {
+ match self.new_pointer_to(&name) {
+ Ok(new_name) => {
+ self.status = format!("Created pointer type {new_name}");
+ self.log(self.status.clone());
+ }
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ if let Some(name) = pending_edit {
+ self.open_edit_type_dialog(&name);
+ }
+ if let Some(name) = pending_rename {
+ // Reuse the standard Rename dialog but retarget its callback path:
+ // renames of user types go through the new-type dialog with the
+ // current body preloaded (so Save = rename + optional body edit).
+ self.open_edit_type_dialog(&name);
+ }
+ if let Some(name) = pending_delete {
+ if let Err(e) = self.delete_user_type(&name) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+
+ /// Listing center pane with real fields, margin markers, and flow arrows.
+ pub(crate) fn ui_listing_pane(&mut self, ui: &mut egui::Ui) {
+ ui.heading("Listing");
+ let mut open_opts = self.show_decode_options_dialog;
+ match ui_toolbar(ui, &mut self.decode_opts, &mut open_opts) {
+ ToolbarAction::Apply => self.apply_decode_opts(),
+ ToolbarAction::OpenOptions => open_opts = true,
+ ToolbarAction::None => {}
+ }
+ self.show_decode_options_dialog = open_opts;
+ ui_search_bar(ui, &mut self.listing_search);
+ self.listing_search.arch = self.listing_arch();
+ // Status strip.
+ ui.horizontal(|ui| {
+ if !self.listing_selection.is_empty() {
+ ui.small(format!(
+ "Sel {}–{}",
+ self.listing_selection.start.unwrap_or(0),
+ self.listing_selection.end.unwrap_or(0)
+ ));
+ }
+ if let Some(va) = self.listing_focus_va {
+ ui.small(format!("Cursor {va:#x}"));
+ }
+ if let Some(f) = self.listing_view_filter.as_ref() {
+ let names = f.iter().cloned().collect::<Vec<_>>().join(", ");
+ ui.small(
+ egui::RichText::new(format!("View filter · {} fragment(s): {names}", f.len()))
+ .weak(),
+ );
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if ui.small_button("Show All").clicked() {
+ self.listing_view_filter = None;
+ }
+ });
+ }
+ });
+ ui.separator();
+ if self.listing.is_empty() {
+ ui.weak("No listing — double-click a project file to open.");
+ return;
+ }
+ let focus = self.listing_focus_va;
+ let sel = self.listing_selection;
+ let t = self.tokens();
+ let sel_bg =
+ Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]).gamma_multiply(0.35);
+ // Snapshot for the closure: (idx, va, bytes_hex, mnem, ops, is_ret, is_uncond, is_cond, is_call, applied_type, comment_eol).
+ let rows: Vec<ListingRow> = {
+ let filter = self.listing_view_filter.clone();
+ let prog_ref = self.program.as_ref();
+ let arch = self.listing_arch();
+ let search = &self.listing_search;
+ self.listing
+ .iter()
+ .enumerate()
+ .filter(|(_, insn)| listing_matches(insn, search))
+ .filter(|(_, insn)| match &filter {
+ None => true,
+ Some(set) => {
+ if set.is_empty() {
+ false
+ } else if let Some(p) = prog_ref {
+ p.blocks.iter().filter(|b| set.contains(&b.name)).any(|b| {
+ insn.address >= b.va && insn.address < b.va.saturating_add(b.size)
+ })
+ } else {
+ true
+ }
+ }
+ })
+ .map(|(i, insn)| ListingRow::from_insn(i, insn, prog_ref, arch))
+ .collect()
+ };
+ let bookmarks_by_va: BTreeMap<u64, BookmarkKind> =
+ self.bookmarks.iter().map(|b| (b.va, b.kind)).collect();
+ let mut click_i: Option<(usize, u64)> = None;
+ // Right-click actions surfaced via a context menu attached to the
+ // Address column. Executed after the scroll-area borrow drops.
+ #[derive(Debug, Clone, Copy)]
+ enum RowAction {
+ OpenComment(CommentKind),
+ OpenRename,
+ OpenRetype,
+ OpenChooser,
+ OpenSignature,
+ OpenEquate,
+ ShowRefsTo,
+ OpenBytesHere,
+ DecryptSelection,
+ SuggestRecipe,
+ CryptoConstantsAtCursor,
+ RecoverStringsHere,
+ }
+ let mut pending_action: Option<(u64, RowAction)> = None;
+ egui::ScrollArea::both()
+ .id_salt("listing_scroll")
+ .auto_shrink([false, false])
+ .show(ui, |ui| {
+ egui::Grid::new("listing_grid")
+ .num_columns(7)
+ .spacing([6.0, 2.0])
+ .striped(false)
+ .show(ui, |ui| {
+ ui.strong(egui::RichText::new("").monospace());
+ ui.strong("Address");
+ ui.strong("Bytes");
+ ui.strong("Mnemonic");
+ ui.strong("Operands");
+ ui.strong("Flow");
+ ui.strong("Comment");
+ ui.end_row();
+ for row in &rows {
+ let focused = focus == Some(row.va);
+ let selected = sel.contains(row.idx);
+ // Pre-comment row (`Pre` comment appears
+ // as its own line above the instruction).
+ if let Some(pre) = &row.comment_pre {
+ ui.label(egui::RichText::new(" ").monospace());
+ ui.label(
+ egui::RichText::new(format!("; {pre}"))
+ .italics()
+ .color(Color32::from_rgb(0x64, 0xB5, 0xF6)),
+ );
+ for _ in 0..5 {
+ ui.label("");
+ }
+ ui.end_row();
+ }
+ // Margin column: bookmark tint + flow-glyph.
+ let margin_text = if let Some(k) = bookmarks_by_va.get(&row.va) {
+ egui::RichText::new("* ")
+ .color(k.color())
+ .monospace()
+ .strong()
+ } else if focused {
+ egui::RichText::new("> ")
+ .color(Color32::from_rgb(0xFF, 0xD5, 0x4F))
+ .monospace()
+ .strong()
+ } else {
+ egui::RichText::new(" ").monospace()
+ };
+ ui.label(margin_text);
+ // Address column (clickable).
+ let addr_rich = egui::RichText::new(format!("{:08x}", row.va))
+ .monospace()
+ .color(if focused {
+ Color32::from_rgb(0xFF, 0xD5, 0x4F)
+ } else {
+ ui.visuals().text_color()
+ });
+ let addr_bg = if selected { Some(sel_bg) } else { None };
+ let addr = ui.add(
+ egui::Label::new(if let Some(bg) = addr_bg {
+ addr_rich.background_color(bg)
+ } else {
+ addr_rich
+ })
+ .sense(egui::Sense::click()),
+ );
+ if addr.clicked() {
+ click_i = Some((row.idx, row.va));
+ }
+ // Listing right-click submenu.
+ let va = row.va;
+ addr.context_menu(|ui| {
+ ui.label(
+ egui::RichText::new(format!("{va:#x}")).monospace().strong(),
+ );
+ ui.separator();
+ ui.menu_button("Set Comment", |ui| {
+ for k in CommentKind::ALL {
+ if ui.button(k.label()).clicked() {
+ pending_action = Some((va, RowAction::OpenComment(*k)));
+ ui.close_menu();
+ }
+ }
+ });
+ ui.separator();
+ if ui.button("Rename Symbol… (L)").clicked() {
+ pending_action = Some((va, RowAction::OpenRename));
+ ui.close_menu();
+ }
+ if ui.button("Retype Variable… (Ctrl+L)").clicked() {
+ pending_action = Some((va, RowAction::OpenRetype));
+ ui.close_menu();
+ }
+ if ui.button("Choose Data Type… (T)").clicked() {
+ pending_action = Some((va, RowAction::OpenChooser));
+ ui.close_menu();
+ }
+ if ui.button("Edit Function Signature… (Alt+Enter)").clicked() {
+ pending_action = Some((va, RowAction::OpenSignature));
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui
+ .button("Set Equate…")
+ .on_hover_text("Bind a name to the first operand scalar")
+ .clicked()
+ {
+ pending_action = Some((va, RowAction::OpenEquate));
+ ui.close_menu();
+ }
+ if ui
+ .button("Show References To…")
+ .on_hover_text("Open Symbol References for this VA")
+ .clicked()
+ {
+ pending_action = Some((va, RowAction::ShowRefsTo));
+ ui.close_menu();
+ }
+ if ui
+ .button("Show Bytes Here")
+ .on_hover_text("Open Byte Viewer at this VA")
+ .clicked()
+ {
+ pending_action = Some((va, RowAction::OpenBytesHere));
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui
+ .button("Decrypt selection…")
+ .on_hover_text("Open Decrypt pane on bytes at this VA")
+ .clicked()
+ {
+ pending_action = Some((va, RowAction::DecryptSelection));
+ ui.close_menu();
+ }
+ if ui
+ .button("Suggest recipe…")
+ .on_hover_text("Magic peel on bytes at this VA")
+ .clicked()
+ {
+ pending_action = Some((va, RowAction::SuggestRecipe));
+ ui.close_menu();
+ }
+ if ui
+ .button("Crypto Constants at cursor…")
+ .on_hover_text("Focus Crypto Constants near this VA")
+ .clicked()
+ {
+ pending_action = Some((va, RowAction::CryptoConstantsAtCursor));
+ ui.close_menu();
+ }
+ if ui
+ .button("Recover strings here…")
+ .on_hover_text("Open Recovered Strings pane")
+ .clicked()
+ {
+ pending_action = Some((va, RowAction::RecoverStringsHere));
+ ui.close_menu();
+ }
+ });
+ // Bytes column.
+ ui.monospace(&row.bytes_hex);
+ // Mnemonic column, coloured by kind.
+ let mnem_color = if row.is_ret {
+ Color32::from_rgb(0xEF, 0x53, 0x50)
+ } else if row.is_uncond {
+ Color32::from_rgb(0xFF, 0xB7, 0x4D)
+ } else if row.is_cond {
+ Color32::from_rgb(0x81, 0xC7, 0x84)
+ } else if row.is_call {
+ Color32::from_rgb(0x64, 0xB5, 0xF6)
+ } else {
+ ui.visuals().text_color()
+ };
+ let mnem_resp = ui.label(
+ egui::RichText::new(&row.mnem).monospace().color(mnem_color),
+ );
+ if !row.groups_summary.is_empty() || !row.regs_rw.is_empty() {
+ mnem_resp.on_hover_ui(|ui| {
+ ui.monospace(format!("id {}", row.id.raw()));
+ if !row.groups_summary.is_empty() {
+ ui.small(format!("groups: {}", row.groups_summary));
+ }
+ if !row.regs_rw.is_empty() {
+ ui.small(&row.regs_rw);
+ }
+ });
+ }
+ // Operands column with scalar/address hover popup.
+ let ops_resp = ui.add(
+ egui::Label::new(egui::RichText::new(&row.ops).monospace())
+ .sense(egui::Sense::hover()),
+ );
+ if !row.ops.is_empty() {
+ ops_resp.on_hover_ui(|ui| {
+ if let Some(scalar) = first_scalar_hint(&row.ops) {
+ ui.small(scalar);
+ }
+ if let Some(addr) = first_address_hint(&row.ops) {
+ ui.small(addr);
+ }
+ });
+ }
+ // Flow column: arrow glyph indicator.
+ let flow_glyph = if row.is_ret {
+ "return"
+ } else if row.is_uncond {
+ "→"
+ } else if row.is_cond {
+ "?→"
+ } else if row.is_call {
+ "call"
+ } else {
+ ""
+ };
+ ui.small(egui::RichText::new(flow_glyph).monospace());
+ // Comment / applied type column (EOL + Repeatable
+ // + Plate + Applied Type decoration).
+ let mut comment_row = String::new();
+ if let Some(t) = &row.applied_type {
+ comment_row.push_str(&format!("<{t}> "));
+ }
+ if let Some(t) = &row.comment_eol {
+ comment_row.push_str(&format!("// {t}"));
+ }
+ if let Some(t) = &row.comment_repeat {
+ if !comment_row.is_empty() {
+ comment_row.push_str(" ");
+ }
+ comment_row.push_str(&format!("~ {t}"));
+ }
+ if let Some(t) = &row.comment_plate {
+ if !comment_row.is_empty() {
+ comment_row.push_str(" ");
+ }
+ comment_row.push_str(&format!("[PLATE {t}]"));
+ }
+ ui.small(egui::RichText::new(comment_row).italics());
+ ui.end_row();
+ // Post-comment row (`Post` comment appears
+ // as its own line below the instruction).
+ if let Some(post) = &row.comment_post {
+ ui.label(egui::RichText::new(" ").monospace());
+ ui.label(
+ egui::RichText::new(format!("; {post}"))
+ .italics()
+ .color(Color32::from_rgb(0xBA, 0x68, 0xC8)),
+ );
+ for _ in 0..5 {
+ ui.label("");
+ }
+ ui.end_row();
+ }
+ }
+ });
+ });
+ if let Some((i, addr)) = click_i {
+ self.push_selection_undo();
+ self.listing_selection = ListingSelection {
+ start: Some(i),
+ end: Some(i),
+ };
+ self.listing_focus_va = Some(addr);
+ self.refresh_decompiler_at(addr);
+ self.event_bus.publish(GhidrustEvent::CursorMoved {
+ source: EventSource::Listing,
+ location: NavLocation::new(addr),
+ });
+ }
+ if let Some((va, action)) = pending_action {
+ match action {
+ RowAction::OpenComment(k) => self.open_comment_dialog(va, k),
+ RowAction::OpenRename => self.open_rename_dialog(va),
+ RowAction::OpenRetype => self.open_retype_dialog(va),
+ RowAction::OpenChooser => self.open_type_chooser(Some(va)),
+ RowAction::OpenSignature => {
+ // Alt+Enter is defined on a function; if the cursor isn't
+ // inside a function, fall back to opening the signature
+ // dialog with the given VA as entry (user can retype it).
+ let entry = self
+ .program
+ .as_ref()
+ .and_then(|p| {
+ p.analysis
+ .functions
+ .iter()
+ .find(|f| va >= f.entry && va < f.end)
+ .map(|f| f.entry)
+ })
+ .unwrap_or(va);
+ self.open_signature_dialog(entry);
+ }
+ RowAction::OpenEquate => {
+ self.equate_dialog_va = Some(va);
+ self.equate_dialog_op = 1;
+ self.equate_dialog_name.clear();
+ // Preload first scalar from the operand string for convenience.
+ self.equate_dialog_value = self
+ .listing
+ .iter()
+ .find(|i| i.address == va)
+ .and_then(|i| crate::menu_actions::extract_scalars(&i.operands).first().copied())
+ .map(|v| format!("{v}"))
+ .unwrap_or_default();
+ self.show_equate_dialog = true;
+ }
+ RowAction::ShowRefsTo => {
+ self.symbol_refs_target = Some(va);
+ self.pane_open.insert(PaneKind::SymbolReferences, true);
+ }
+ RowAction::OpenBytesHere => {
+ self.bytes_pane_va = Some(va);
+ self.pane_open.insert(PaneKind::Bytes, true);
+ }
+ RowAction::DecryptSelection => {
+ self.open_decrypt_at(va, None);
+ }
+ RowAction::SuggestRecipe => {
+ self.open_decrypt_at(va, None);
+ self.decrypt_pane.bake_preset("magic");
+ }
+ RowAction::CryptoConstantsAtCursor => {
+ self.crypto_constants_focus_va = Some(va);
+ self.decrypt_pane.focus(DecryptTab::Constants);
+ self.pane_open.insert(PaneKind::Decrypt, true);
+ }
+ RowAction::RecoverStringsHere => {
+ self.recover_strings_at_function(va);
+ self.decrypt_pane.focus(DecryptTab::Strings);
+ self.pane_open.insert(PaneKind::Decrypt, true);
+ }
+ }
+ }
+ }
+
+ /// tokenised Decompiler center pane with cross-highlight.
+ pub(crate) fn ui_decompiler_pane(&mut self, ui: &mut egui::Ui) {
+ ui.heading("Decompiler");
+ if self.program.is_none() {
+ ui.weak("Open a project file, then select a function or listing address.");
+ return;
+ }
+ // Stage picker (Stage-0 / 0.5 / 1). Changing kicks off a re-emit
+ // for the currently-focused entry.
+ let mut sel = self.decomp_stage;
+ ui.horizontal(|ui| {
+ ui.label("Stage:");
+ egui::ComboBox::from_id_salt("decomp_stage_combo")
+ .selected_text(sel.label())
+ .show_ui(ui, |ui| {
+ ui.selectable_value(&mut sel, DecompStage::Stage0, "Stage-0 (CFG → goto)");
+ ui.selectable_value(&mut sel, DecompStage::Stage05, "Stage-0.5 (IR-informed)");
+ ui.selectable_value(
+ &mut sel,
+ DecompStage::Stage1,
+ "Stage-1 (SSA + structure + types)",
+ );
+ });
+ if let Some(r) = self.decomp_lift_ratio {
+ ui.small(format!("lift {:.1}%", r * 100.0));
+ }
+ });
+ if sel != self.decomp_stage {
+ self.set_decomp_stage(sel);
+ }
+ // Keep cache in sync with cursor when switching to this pane.
+ if let Some(va) = self
+ .listing_focus_va
+ .or(self.decomp_entry)
+ .or_else(|| self.program.as_ref().and_then(|p| p.entry))
+ {
+ 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() {
+ ui.small(&self.decomp_status);
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if let Some(entry) = self.decomp_entry {
+ if ui
+ .small_button("Commit Params/Return")
+ .on_hover_text("Persist inferred params + return type as user edits")
+ .clicked()
+ {
+ if let Err(e) = self.commit_params_return(entry) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ if ui
+ .small_button("Commit Locals")
+ .on_hover_text("Persist inferred stack locals as user edits")
+ .clicked()
+ {
+ if let Err(e) = self.commit_locals(entry) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ if ui
+ .small_button("Edit signature…")
+ .on_hover_text("Edit function signature")
+ .clicked()
+ {
+ self.open_signature_dialog(entry);
+ }
+ if ui
+ .small_button("Rename function…")
+ .on_hover_text("Rename this function (L)")
+ .clicked()
+ {
+ self.open_rename_dialog(entry);
+ }
+ }
+ });
+ });
+ ui.separator();
+ if self.decomp_lines.is_empty() && self.decomp_text.is_empty() {
+ ui.weak(
+ "Select a Symbol Tree function or a Listing instruction to decompile (Stage-0 CFG → pseudo-C).",
+ );
+ return;
+ }
+ // Render tokenised lines.
+ let visuals = ui.visuals().clone();
+ let text_color = visuals.text_color();
+ let cross_line = self.decomp_cross_line;
+ let highlight_text = self.decomp_highlight_text.clone();
+ let mut clicked_addr: Option<u64> = None;
+ let mut mid_clicked_text: Option<String> = None;
+ let mut decrypt_token: Option<(u64, String)> = None;
+ let mut copy_decode_input: Option<(u64, String)> = None;
+ let mut rename_token: Option<(u64, String)> = None;
+ egui::ScrollArea::both()
+ .id_salt("decomp_tokens_scroll")
+ .auto_shrink([false, false])
+ .show(ui, |ui| {
+ let font = egui::FontId::monospace(13.0);
+ for line in &self.decomp_lines {
+ let is_cross = Some(line.line) == cross_line;
+ let bg_frame = if is_cross {
+ Some(
+ egui::Frame::default()
+ .fill(Color32::from_rgba_unmultiplied(0xFF, 0xD5, 0x4F, 40)),
+ )
+ } else {
+ None
+ };
+ let mut render_row = |ui: &mut egui::Ui| {
+ ui.horizontal(|ui| {
+ // Left rail: address gutter (line.machine_addr).
+ let gutter = line
+ .machine_addr
+ .map(|va| format!("{va:08x} "))
+ .unwrap_or_else(|| " ".into());
+ ui.add(
+ egui::Label::new(
+ egui::RichText::new(gutter)
+ .monospace()
+ .color(text_color.gamma_multiply(0.6)),
+ )
+ .selectable(false),
+ );
+ for tok in &line.tokens {
+ let (color, italic) = token_style(&tok.kind, text_color);
+ let highlighted = highlight_text
+ .as_deref()
+ .map(|h| h == tok.text)
+ .unwrap_or(false)
+ && matches!(
+ tok.kind,
+ TokenKind::Variable
+ | TokenKind::Function
+ | TokenKind::Address
+ | TokenKind::Constant
+ | TokenKind::Label
+ );
+ let mut rich = egui::RichText::new(&tok.text)
+ .font(font.clone())
+ .color(color);
+ if italic {
+ rich = rich.italics();
+ }
+ if highlighted {
+ rich = rich.background_color(Color32::from_rgba_unmultiplied(
+ 0x03, 0xA9, 0xF4, 90,
+ ));
+ }
+ let clickable = matches!(
+ tok.kind,
+ TokenKind::Address
+ | TokenKind::Function
+ | TokenKind::Label
+ | TokenKind::Variable
+ | TokenKind::Constant
+ );
+ if clickable {
+ let sense = egui::Sense::click();
+ let resp = ui.add(egui::Label::new(rich).sense(sense));
+ if resp.clicked() {
+ if let Some(va) = tok.va {
+ clicked_addr = Some(va);
+ }
+ }
+ if resp.middle_clicked() {
+ mid_clicked_text = Some(tok.text.clone());
+ }
+ if let Some(va) = tok.va.or(line.machine_addr) {
+ let is_decode_input = matches!(
+ tok.kind,
+ TokenKind::Constant | TokenKind::Address
+ );
+ let is_identifier = tok
+ .text
+ .chars()
+ .next()
+ .map(|c| c.is_ascii_alphabetic() || c == '_')
+ .unwrap_or(false);
+ resp.context_menu(|ui| {
+ if is_decode_input
+ && ui.button("Decrypt constant…").clicked()
+ {
+ decrypt_token = Some((va, tok.text.clone()));
+ ui.close_menu();
+ }
+ if is_decode_input
+ && ui.button("Copy as decode input").clicked()
+ {
+ copy_decode_input = Some((va, tok.text.clone()));
+ ui.close_menu();
+ }
+ if is_identifier
+ && ui.button("Rename symbol…").clicked()
+ {
+ rename_token = Some((va, tok.text.clone()));
+ ui.close_menu();
+ }
+ });
+ }
+ if resp.hovered() {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
+ }
+ } else {
+ ui.add(egui::Label::new(rich).selectable(true));
+ }
+ }
+ });
+ };
+ if let Some(frame) = bg_frame {
+ frame.show(ui, render_row);
+ } else {
+ render_row(ui);
+ }
+ }
+ });
+ if let Some(text) = mid_clicked_text {
+ self.decomp_highlight_text =
+ if self.decomp_highlight_text.as_deref() == Some(text.as_str()) {
+ None
+ } else {
+ Some(text)
+ };
+ }
+ if let Some((va, text)) = decrypt_token {
+ self.decrypt_pane
+ .load_text(Some(va), text, "Decompiler constant");
+ self.pane_open.insert(PaneKind::Decrypt, true);
+ }
+ if let Some((va, text)) = copy_decode_input {
+ self.decrypt_pane
+ .load_text(Some(va), text, "Decompiler token");
+ self.pane_open.insert(PaneKind::Decrypt, true);
+ }
+ if let Some((va, text)) = rename_token {
+ self.open_rename_dialog(va);
+ self.rename_dialog_old_name = text;
+ }
+ if let Some(va) = clicked_addr {
+ // Only navigate if VA looks plausibly in-range (avoid `block_0` id = 0 jumping to base).
+ let plausible = self
+ .program
+ .as_ref()
+ .map(|p| p.contains_va(va))
+ .unwrap_or(false)
+ || va >= 0x1000;
+ if plausible {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+ }
+}
diff --git a/crates/ghidrust-gui/src/app/dialogs.rs b/crates/ghidrust-gui/src/app/dialogs.rs
new file mode 100644
index 0000000..ad50d47
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/dialogs.rs
@@ -0,0 +1,871 @@
+//! Shell dialogs — configure/layouts/goto/search/analysis/GPU.
+//!
+//! Extracted per demonolith Wave 7. Nested under `app` for private field access.
+
+use super::{ConfigureSection, GhidrustApp};
+use crate::listing::ui_options_dialog;
+use crate::menu_actions::{parse_address, processor_info};
+use crate::panes::BookmarkKind;
+use eframe::egui::{self, Color32};
+use ghidrust_core::{analyzer_supports_gpu, AppearanceTheme, ThemeMode};
+
+impl GhidrustApp {
+ /// Draw configure/layouts/goto/search/analysis/GPU dialogs.
+ pub(crate) fn draw_shell_dialogs(&mut self, ctx: &egui::Context) {
+
+ if self.show_search_address_tables_dialog {
+ let mut open = true;
+ egui::Window::new("Address Tables")
+ .open(&mut open)
+ .show(ctx, |ui| {
+ ui.label(format!("{} recovered table(s)", self.text_hits.len()));
+ for hit in &self.text_hits {
+ ui.monospace(format!("{} {}", hit.va.map(|v| format!("{v:#x}")).unwrap_or_default(), hit.text));
+ }
+ if ui.button("Show results").clicked() {
+ self.show_search_results = true;
+ }
+ });
+ self.show_search_address_tables_dialog = open;
+ }
+
+ if self.show_prefs_dialog {
+ let mut open = true;
+ egui::Window::new("Preferences")
+ .open(&mut open)
+ .show(ctx, |ui| {
+ ui.label(format!("Appearance: {}", self.appearance.display_name()));
+ ui.label(format!("Theme mode: {:?}", self.theme));
+ ui.separator();
+ ui.strong("Known hotkeys");
+ ui.monospace("F5 Continue · F7 Step Into · F8 Step Over · Shift+F8 Step Out");
+ ui.monospace("Ctrl+Down Next Function · Ctrl+Up Previous Function · F1 Help");
+ });
+ self.show_prefs_dialog = open;
+ }
+
+ if self.show_help_dialog {
+ let mut open = true;
+ egui::Window::new("Ghidrust Help")
+ .open(&mut open)
+ .resizable(true)
+ .show(ctx, |ui| {
+ ui.heading(format!("Ghidrust {}", env!("CARGO_PKG_VERSION")));
+ ui.label("Use File to load/import binaries, Analysis to run analyzers, and Window to open providers.");
+ ui.separator();
+ ui.strong("Built-in scripts");
+ for script in crate::scripts::builtin_catalog() {
+ ui.monospace(script.name);
+ }
+ });
+ self.show_help_dialog = open;
+ }
+
+ if self.show_tools_dialog {
+ let mut open = true;
+ egui::Window::new(&self.tools_dialog_title)
+ .open(&mut open)
+ .resizable(true)
+ .show(ctx, |ui| { ui.monospace(&self.tools_dialog_body); });
+ self.show_tools_dialog = open;
+ }
+
+ // Configure dialog (Appearance + Plugins).
+ if self.show_configure_dialog {
+ let mut close = false;
+ let mut appearance_changed = false;
+ let mut next_appearance = self.appearance;
+ let mut next_mode = self.theme;
+ let mut next_section = self.configure_section;
+ egui::Window::new("Configure")
+ .id(egui::Id::new("dialog_configure"))
+ .resizable(true)
+ .default_size(egui::vec2(760.0, 520.0))
+ .show(ctx, |ui| {
+ ui.horizontal(|ui| {
+ ui.vertical(|ui| {
+ ui.set_min_width(140.0);
+ ui.strong("Configure");
+ ui.add_space(6.0);
+ if ui
+ .selectable_label(
+ next_section == ConfigureSection::Appearance,
+ "Appearance",
+ )
+ .clicked()
+ {
+ next_section = ConfigureSection::Appearance;
+ }
+ if ui
+ .selectable_label(
+ next_section == ConfigureSection::Plugins,
+ "Plugins",
+ )
+ .clicked()
+ {
+ next_section = ConfigureSection::Plugins;
+ }
+ });
+ ui.separator();
+ ui.vertical(|ui| {
+ match next_section {
+ ConfigureSection::Appearance => {
+ ui.heading("Appearance");
+ ui.label(
+ "Select a theme family. Classic Ghidrust is the historical default.",
+ );
+ ui.add_space(8.0);
+ for theme in AppearanceTheme::ALL {
+ let selected = next_appearance == *theme;
+ if ui
+ .selectable_label(selected, theme.display_name())
+ .on_hover_text(theme.description())
+ .clicked()
+ {
+ next_appearance = *theme;
+ appearance_changed = true;
+ }
+ if selected {
+ ui.indent(theme.id(), |ui| {
+ ui.small(theme.description());
+ });
+ }
+ }
+ ui.add_space(12.0);
+ ui.separator();
+ ui.horizontal(|ui| {
+ let mode_caption = match next_appearance {
+ AppearanceTheme::FutureConsole => "Gas",
+ _ => "Mode",
+ };
+ ui.label(format!("{mode_caption}:"));
+ let dark_label = match next_appearance {
+ AppearanceTheme::FutureConsole => "Neon",
+ _ => "Dark",
+ };
+ let light_label = match next_appearance {
+ AppearanceTheme::FutureConsole => "Amber",
+ _ => "Light",
+ };
+ if ui
+ .selectable_label(
+ next_mode == ThemeMode::Dark,
+ dark_label,
+ )
+ .clicked()
+ {
+ next_mode = ThemeMode::Dark;
+ appearance_changed = true;
+ }
+ if ui
+ .selectable_label(
+ next_mode == ThemeMode::Light,
+ light_label,
+ )
+ .clicked()
+ {
+ next_mode = ThemeMode::Light;
+ appearance_changed = true;
+ }
+ });
+ if next_appearance == AppearanceTheme::FutureConsole {
+ ui.small(
+ "Future Console tokens transcribed 1:1 from Amber Console (BSD-3-Clause).",
+ );
+ }
+ }
+ ConfigureSection::Plugins => {
+ ui.heading("Plugins");
+ ui.label(
+ "Ghidrust plugins are compile-time; this lists every provider shipped.",
+ );
+ ui.separator();
+ egui::ScrollArea::vertical()
+ .id_salt("configure_scroll")
+ .max_height(360.0)
+ .show(ui, |ui| {
+ egui::Grid::new("configure_grid")
+ .num_columns(4)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Plugin");
+ ui.strong("Kind");
+ ui.strong("State");
+ ui.strong("Description");
+ ui.end_row();
+ for p in crate::layouts::PLUGIN_CATALOG {
+ ui.monospace(p.name);
+ ui.label(p.kind);
+ ui.label(p.state);
+ ui.label(p.description);
+ ui.end_row();
+ }
+ });
+ });
+ }
+ }
+ });
+ });
+ ui.separator();
+ if ui.button("Close").clicked() {
+ close = true;
+ }
+ });
+ self.configure_section = next_section;
+ if appearance_changed {
+ self.appearance = next_appearance;
+ self.theme = next_mode;
+ self.apply_theme(ctx);
+ self.log(format!(
+ "Appearance → {} ({})",
+ self.appearance.display_name(),
+ self.appearance.mode_label(self.theme)
+ ));
+ }
+ if close {
+ self.show_configure_dialog = false;
+ }
+ }
+
+ // Layout save / load dialog.
+ if self.show_layouts_dialog {
+ let mut close = false;
+ let mut do_save = false;
+ let mut load_name: Option<String> = None;
+ let mut delete_name: Option<String> = None;
+ egui::Window::new("Tool Layouts")
+ .id(egui::Id::new("dialog_layouts"))
+ .resizable(true)
+ .default_size(egui::vec2(480.0, 360.0))
+ .show(ctx, |ui| {
+ ui.label("Save / restore CodeBrowser tool layouts (pane visibility + docks).");
+ ui.small(
+ egui::RichText::new(
+ "Files land under %APPDATA%/ghidrust/layouts/<name>.tool.json .",
+ )
+ .weak(),
+ );
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label("Name:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.layouts_new_name)
+ .desired_width(200.0)
+ .hint_text("MyCodeBrowser"),
+ );
+ if ui
+ .add_enabled(
+ !self.layouts_new_name.trim().is_empty(),
+ egui::Button::new("Save current layout"),
+ )
+ .clicked()
+ {
+ do_save = true;
+ }
+ });
+ ui.separator();
+ ui.label(egui::RichText::new("Saved layouts").strong());
+ if self.layouts_cached.is_empty() {
+ ui.weak("No layouts saved yet.");
+ } else {
+ egui::ScrollArea::vertical()
+ .id_salt("layouts_scroll")
+ .max_height(180.0)
+ .show(ui, |ui| {
+ for name in &self.layouts_cached {
+ ui.horizontal(|ui| {
+ ui.monospace(name);
+ if ui.small_button("Restore").clicked() {
+ load_name = Some(name.clone());
+ }
+ if ui.small_button("Delete").clicked() {
+ delete_name = Some(name.clone());
+ }
+ });
+ }
+ });
+ }
+ ui.separator();
+ if !self.current_layout_name.is_empty() {
+ ui.small(
+ egui::RichText::new(format!(
+ "Current layout: {}",
+ self.current_layout_name
+ ))
+ .weak(),
+ );
+ }
+ if ui.button("Close").clicked() {
+ close = true;
+ }
+ });
+ if do_save {
+ match self.save_layout_named(self.layouts_new_name.clone()) {
+ Ok(p) => {
+ self.status = format!("Layout saved → {}", p.display());
+ self.log(self.status.clone());
+ }
+ Err(e) => {
+ self.status = format!("save layout error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ if let Some(name) = load_name {
+ match self.restore_layout_named(&name) {
+ Ok(()) => {
+ self.apply_theme(ctx);
+ self.status = format!("Layout restored → {name}");
+ self.log(self.status.clone());
+ }
+ Err(e) => {
+ self.status = format!("restore layout error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ if let Some(name) = delete_name {
+ if let Err(e) = crate::layouts::delete_layout(&name) {
+ self.status = format!("delete layout error: {e}");
+ self.log_error(self.status.clone());
+ }
+ self.layouts_cached = crate::layouts::list_layouts();
+ }
+ if close {
+ self.show_layouts_dialog = false;
+ }
+ }
+
+ // Bookmark add dialog
+ if self.show_bookmark_dialog {
+ let mut close = false;
+ let mut confirmed = false;
+ egui::Window::new("Add Bookmark")
+ .id(egui::Id::new("dialog_add_bookmark"))
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.label("Kind:");
+ egui::ComboBox::from_id_salt("bookmark_kind")
+ .selected_text(self.bookmark_dialog_kind.label())
+ .show_ui(ui, |ui| {
+ for k in BookmarkKind::ALL {
+ ui.selectable_value(&mut self.bookmark_dialog_kind, *k, k.label());
+ }
+ });
+ ui.label("Category:");
+ ui.text_edit_singleline(&mut self.bookmark_dialog_category);
+ ui.label("Description:");
+ ui.text_edit_singleline(&mut self.bookmark_dialog_description);
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ if ui.button("Add").clicked() {
+ confirmed = true;
+ close = true;
+ }
+ });
+ });
+ if confirmed {
+ if let Some(va) = self.listing_focus_va {
+ let kind = self.bookmark_dialog_kind;
+ let cat = self.bookmark_dialog_category.clone();
+ let desc = self.bookmark_dialog_description.clone();
+ self.add_bookmark(va, kind, cat, desc);
+ }
+ }
+ if close {
+ self.show_bookmark_dialog = false;
+ }
+ }
+
+ // Navigation → Go To Address
+ if self.show_goto_dialog {
+ egui::Window::new("Go To Address")
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.label("Address (hex, optional 0x prefix):");
+ ui.text_edit_singleline(&mut self.goto_input);
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ self.show_goto_dialog = false;
+ }
+ if ui.button("Go").clicked() {
+ match self.goto_address_str(&self.goto_input.clone()) {
+ Ok(()) => self.show_goto_dialog = false,
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+ });
+ });
+ }
+
+ // Search → Memory
+ if self.show_search_memory_dialog {
+ egui::Window::new("Search Memory")
+ .collapsible(false)
+ .resizable(true)
+ .default_width(420.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.label("Byte pattern (hex; ?? = wildcard):");
+ ui.text_edit_singleline(&mut self.search_memory_input);
+ ui.small("Example: 55 48 89 e5 or 48??e5");
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ self.show_search_memory_dialog = false;
+ }
+ if ui.button("Search").clicked() {
+ match self.run_search_memory() {
+ Ok(()) => self.show_search_memory_dialog = false,
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+ });
+ });
+ }
+
+ // Search → Program Text
+ if self.show_search_text_dialog {
+ egui::Window::new("Search Program Text")
+ .collapsible(false)
+ .resizable(true)
+ .default_width(420.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.label("Query (listing / symbols / functions / memory text):");
+ ui.text_edit_singleline(&mut self.search_text_input);
+ ui.checkbox(&mut self.search_text_case_insensitive, "Case insensitive");
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ self.show_search_text_dialog = false;
+ }
+ if ui.button("Search").clicked() {
+ match self.run_search_text() {
+ Ok(()) => self.show_search_text_dialog = false,
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+ });
+ });
+ }
+
+ // Search → For Scalars
+ if self.show_search_scalars_dialog {
+ egui::Window::new("Search For Scalars")
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.label("Scan operand scalars in [min, max]. Hex ok (0x…) or decimal.");
+ ui.horizontal(|ui| {
+ ui.label("Min:");
+ ui.text_edit_singleline(&mut self.search_scalars_min);
+ });
+ ui.horizontal(|ui| {
+ ui.label("Max:");
+ ui.text_edit_singleline(&mut self.search_scalars_max);
+ });
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ self.show_search_scalars_dialog = false;
+ }
+ if ui.button("Search").clicked() {
+ match self.run_search_scalars() {
+ Ok(()) => self.show_search_scalars_dialog = false,
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ });
+ });
+ }
+
+ // Search → Instruction Patterns
+ if self.show_search_insn_dialog {
+ egui::Window::new("Search Instruction Patterns")
+ .collapsible(false)
+ .resizable(true)
+ .default_width(420.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.small("Matches against decoded listing rows. Empty field = don't filter.");
+ ui.horizontal(|ui| {
+ ui.label("Mnemonic:");
+ ui.text_edit_singleline(&mut self.search_insn_mnemonic);
+ });
+ ui.horizontal(|ui| {
+ ui.label("Operands:");
+ ui.text_edit_singleline(&mut self.search_insn_operands);
+ });
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ self.show_search_insn_dialog = false;
+ }
+ if ui.button("Search").clicked() {
+ match self.run_search_instruction_patterns() {
+ Ok(()) => self.show_search_insn_dialog = false,
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ });
+ });
+ }
+
+ // Add Equate dialog .
+ if self.show_equate_dialog {
+ let mut close = false;
+ egui::Window::new("Set Equate")
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.small("Bind a name to a scalar operand .");
+ ui.horizontal(|ui| {
+ ui.label("VA:");
+ let mut input = self
+ .equate_dialog_va
+ .map(|v| format!("{v:#x}"))
+ .unwrap_or_default();
+ if ui.text_edit_singleline(&mut input).lost_focus() {
+ self.equate_dialog_va = parse_address(&input).ok();
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("Operand index:");
+ let mut s = format!("{}", self.equate_dialog_op);
+ if ui.text_edit_singleline(&mut s).lost_focus() {
+ self.equate_dialog_op =
+ s.trim().parse().unwrap_or(self.equate_dialog_op);
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("Name:");
+ ui.text_edit_singleline(&mut self.equate_dialog_name);
+ });
+ ui.horizontal(|ui| {
+ ui.label("Value (dec / hex):");
+ ui.text_edit_singleline(&mut self.equate_dialog_value);
+ });
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ if ui.button("Apply").clicked() {
+ let value = self
+ .parse_scalar_input(&self.equate_dialog_value.clone())
+ .unwrap_or(0);
+ if let Some(va) = self.equate_dialog_va {
+ if let Err(e) = self.set_equate(
+ va,
+ self.equate_dialog_op,
+ self.equate_dialog_name.clone(),
+ value,
+ ) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ } else {
+ close = true;
+ }
+ } else {
+ close = true;
+ }
+ }
+ });
+ });
+ if close {
+ self.show_equate_dialog = false;
+ }
+ }
+
+ // Search results window
+ if self.show_search_results {
+ egui::Window::new("Search Results")
+ .collapsible(true)
+ .resizable(true)
+ .default_width(480.0)
+ .default_height(280.0)
+ .show(ctx, |ui| {
+ if ui.button("Close").clicked() {
+ self.show_search_results = false;
+ }
+ ui.separator();
+ egui::ScrollArea::vertical().show(ui, |ui| {
+ for h in self.memory_hits.clone() {
+ if ui
+ .button(format!(
+ "{:#x} {} +{:#x}",
+ h.va, h.block, h.offset_in_block
+ ))
+ .clicked()
+ {
+ let _ = self.goto_address_str(&format!("{:#x}", h.va));
+ }
+ }
+ for h in self.text_hits.clone() {
+ let label = match h.va {
+ Some(va) => format!("[{}] {:#x}: {}", h.kind, va, h.text),
+ None => format!("[{}] {}", h.kind, h.text),
+ };
+ if ui.button(label).clicked() {
+ if let Some(va) = h.va {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+ }
+ if self.memory_hits.is_empty() && self.text_hits.is_empty() {
+ ui.weak("No hits.");
+ }
+ });
+ });
+ }
+
+ // Listing → Decode options
+ if ui_options_dialog(
+ ctx,
+ &mut self.show_decode_options_dialog,
+ &mut self.decode_opts,
+ self.program.as_ref(),
+ ) {
+ self.apply_decode_opts();
+ }
+
+ // Tools → Processor options
+ if self.show_processor_dialog {
+ egui::Window::new("Processor Options")
+ .collapsible(false)
+ .resizable(true)
+ .default_width(440.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ if let Some(prog) = &self.program {
+ let info = processor_info(prog);
+ ui.monospace(format!("Language: {}", info.language));
+ ui.monospace(format!("Compiler: {}", info.compiler));
+ ui.monospace(format!("Format: {}", info.format));
+ ui.monospace(format!("Endian: {}", info.endian));
+ ui.monospace(format!("Pointer size: {} bytes", info.pointer_size));
+ ui.monospace(format!("Image base: {:#x}", info.image_base));
+ ui.monospace(format!(
+ "Entry: {}",
+ info.entry
+ .map(|e| format!("{e:#x}"))
+ .unwrap_or_else(|| "—".into())
+ ));
+ ui.separator();
+ ui.small(&info.notes);
+ ui.separator();
+ ui.label("Sections:");
+ egui::ScrollArea::vertical()
+ .max_height(160.0)
+ .show(ui, |ui| {
+ for s in &prog.sections {
+ ui.monospace(format!(
+ "{} va={:#x} vsize={:#x}",
+ s.name, s.va, s.virtual_size
+ ));
+ }
+ });
+ } else {
+ ui.weak("Load a program to view processor / language options.");
+ }
+ if ui.button("Close").clicked() {
+ self.show_processor_dialog = false;
+ }
+ });
+ }
+
+ // Analysis → GPU Decompile…
+ if self.show_gpu_decompile_dialog {
+ let t = self.tokens();
+ 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| {
+ crate::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;
+ }
+ crate::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 = self.tokens();
+ let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
+ egui::Window::new("Analysis options")
+ .collapsible(false)
+ .resizable(true)
+ .default_width(460.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ if let Some(ref id) = self.pending_analyze_file_id {
+ let name = self
+ .project
+ .as_ref()
+ .and_then(|p| p.meta.files.iter().find(|f| f.id == *id))
+ .map(|f| f.display_name.as_str())
+ .unwrap_or(id.as_str());
+ ui.label(
+ egui::RichText::new(format!("Target: {name}"))
+ .strong()
+ .color(primary),
+ );
+ ui.add_space(4.0);
+ }
+ ui.label("Select analyzers (labels):");
+ ui.horizontal(|ui| {
+ if ui.small_button("Select defaults").clicked() {
+ for (i, info) in self.analyzer_infos.iter().enumerate() {
+ self.analyzer_enabled[i] = info.default_enabled;
+ }
+ }
+ if ui.small_button("Select all").clicked() {
+ for e in &mut self.analyzer_enabled {
+ *e = true;
+ }
+ }
+ if ui.small_button("Clear all").clicked() {
+ for e in &mut self.analyzer_enabled {
+ *e = false;
+ }
+ }
+ });
+ egui::ScrollArea::vertical()
+ .max_height(320.0)
+ .show(ui, |ui| {
+ for (i, info) in self.analyzer_infos.iter().enumerate() {
+ ui.horizontal(|ui| {
+ ui.checkbox(&mut self.analyzer_enabled[i], &info.name);
+ match info.status {
+ ghidrust_core::AnalyzerStatus::Implemented => {
+ ui.weak("ready");
+ }
+ ghidrust_core::AnalyzerStatus::NotImplemented => {
+ ui.weak("stub");
+ }
+ }
+ // Per-row GPU indicator (master checkbox gates actual use).
+ let supports = analyzer_supports_gpu(&info.name);
+ if supports && self.use_gpu_experimental {
+ ui.label(
+ egui::RichText::new("GPU")
+ .small()
+ .strong()
+ .color(primary),
+ )
+ .on_hover_text(
+ "Master GPU is on — this analyzer will use its GPU \
+ strategy (bulk and/or seed enrich). Falls back to CPU \
+ on failure.",
+ );
+ } else if supports {
+ ui.label(
+ egui::RichText::new("GPU")
+ .small()
+ .color(Color32::from_rgb(120, 120, 128)),
+ )
+ .on_hover_text(
+ "GPU strategy available — enable the master GPU checkbox \
+ to use it. Currently CPU.",
+ );
+ } else {
+ ui.label(
+ egui::RichText::new("CPU only")
+ .small()
+ .color(Color32::from_rgb(120, 120, 128)),
+ )
+ .on_hover_text(
+ "No GPU strategy for this analyzer — always runs on CPU.",
+ );
+ }
+ });
+ }
+ });
+ ui.separator();
+ ui.checkbox(
+ &mut self.use_gpu_experimental,
+ "GPU (only analyzers with a GPU strategy)",
+ );
+ ui.small(
+ "wgpu when available: GPU bulk / SIMT seed enrich only for analyzers \
+ marked GPU above (see strategy matrix). Others stay CPU-only. \
+ Large images are multi-dispatch chunked (≤65535 workgroups). \
+ Falls back to CPU on failure. GPU decompile is a separate tool.",
+ );
+ ui.add_space(8.0);
+ ui.horizontal(|ui| {
+ let can_run = self.analyzer_enabled.iter().any(|e| *e)
+ && (self.program.is_some() || self.pending_analyze_file_id.is_some());
+ if ui
+ .add_enabled(can_run, egui::Button::new("Run Analysis"))
+ .clicked()
+ {
+ match self.begin_analysis_job() {
+ Ok(()) => {
+ self.show_analysis_dialog = false;
+ }
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+ if ui.button("Cancel").clicked() {
+ self.pending_analyze_file_id = None;
+ self.show_analysis_dialog = false;
+ }
+ });
+ });
+ }
+
+ }
+}
diff --git a/crates/ghidrust-gui/src/app/menus.rs b/crates/ghidrust-gui/src/app/menus.rs
new file mode 100644
index 0000000..85be29c
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/menus.rs
@@ -0,0 +1,831 @@
+//! Shell menubar — File…Help + Debugger + Network.
+//!
+//! Extracted per demonolith Wave 2. Nested under `app` so private App fields stay reachable.
+
+use super::{CenterPane, ConfigureSection, GhidrustApp};
+use crate::debugger::{DebuggerAction, DebuggerPane};
+use crate::decrypt_ui::DecryptTab;
+use crate::dock_tabs::DockTab;
+use crate::menu_actions::{address_table_hits, TextHit};
+use crate::network::{NetworkAction, NetworkPane};
+use crate::panes::PaneKind;
+use eframe::egui;
+use ghidrust_core::load_path;
+
+impl GhidrustApp {
+ /// Draw the top menubar panel.
+ pub(crate) fn draw_menubar(&mut self, ctx: &egui::Context) {
+ egui::TopBottomPanel::top("menubar").show(ctx, |ui| {
+ egui::menu::bar(ui, |ui| {
+ ui.menu_button("File", |ui| {
+ if ui.button("New Project…").clicked() {
+ self.browse_and_create_project();
+ ui.close_menu();
+ }
+ if ui.button("Open Project…").clicked() {
+ self.browse_and_open_project();
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui.button("Import binary into project…").clicked() {
+ self.browse_and_import();
+ ui.close_menu();
+ }
+ if ui.button("Open / Load binary…").clicked() {
+ self.browse_and_load_binary();
+ ui.close_menu();
+ }
+ if ui.button("Add To Program…").on_hover_text("Load another binary").clicked() {
+ if let Some(path) = rfd::FileDialog::new().pick_file() {
+ self.menu_import_paths(vec![path]);
+ }
+ ui.close_menu();
+ }
+ if ui.button("Batch Import…").on_hover_text("Import or load selected binaries").clicked() {
+ if let Some(paths) = rfd::FileDialog::new().pick_files() {
+ self.menu_import_paths(paths);
+ }
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui.button("Save analysis results…").clicked() {
+ if let Err(e) = self.save_results() {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ ui.close_menu();
+ }
+ if ui.button("Save As…").clicked() {
+ if let Some(folder) = rfd::FileDialog::new().pick_folder() {
+ if let Err(e) = self.save_results_as(folder) { self.log_error(e); }
+ }
+ ui.close_menu();
+ }
+ if ui.button("Export Program…").clicked() {
+ if let Err(e) = self.export_listing() { self.log_error(e); }
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui.button("Load PDB File…").clicked() {
+ self.pdb_path = rfd::FileDialog::new().add_filter("PDB", &["pdb"]).pick_file();
+ self.status = self.pdb_path.as_ref().map(|p| format!("PDB selected: {} (run analysis to consume symbols)", p.display())).unwrap_or_else(|| "PDB selection cancelled".into());
+ self.log(self.status.clone());
+ ui.close_menu();
+ }
+ if ui.button("Parse C Source…").clicked() {
+ if let Some(path) = rfd::FileDialog::new().add_filter("C source", &["c", "h"]).pick_file() {
+ match std::fs::read_to_string(&path) {
+ Ok(text) => { let name = path.file_stem().unwrap_or_default().to_string_lossy().to_string(); let _ = self.define_user_type(name.clone(), format!("C source stub from {}\n{text}", path.display())); self.status = format!("Imported C source stub {name} into Program types"); self.log(self.status.clone()); }
+ Err(e) => self.log_error(e.to_string()),
+ }
+ }
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui
+ .button("Configure…")
+ .on_hover_text("Appearance themes + plugin catalog")
+ .clicked()
+ {
+ self.show_configure_dialog = true;
+ self.configure_section = ConfigureSection::Appearance;
+ ui.close_menu();
+ }
+ if ui.button("Print…").clicked() {
+ if let Err(e) = self.print_listing() { self.log_error(e); }
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui.button("Close program").clicked() {
+ self.program = None;
+ self.listing.clear();
+ self.active_file_id = None;
+ self.status = "Program closed".into();
+ ui.close_menu();
+ }
+ if ui.button("Exit").clicked() {
+ ctx.send_viewport_cmd(egui::ViewportCommand::Close);
+ }
+ });
+ ui.menu_button("Edit", |ui| {
+ if ui.button("Undo").clicked() {
+ self.edit_undo();
+ ui.close_menu();
+ }
+ if ui.button("Redo").clicked() {
+ self.edit_redo();
+ ui.close_menu();
+ }
+ if ui.button("Clear selection").clicked() {
+ self.edit_clear_selection();
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui.button("Tool Options…").clicked() {
+ self.show_prefs_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("Options for program…").clicked() {
+ self.show_decode_options_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("Plugin Path…").clicked() {
+ self.show_configure_dialog = true;
+ self.configure_section = ConfigureSection::Plugins;
+ ui.close_menu();
+ }
+ if ui.button("Key Bindings…").clicked() {
+ self.show_prefs_dialog = true;
+ ui.close_menu();
+ }
+ });
+ ui.menu_button("Analysis", |ui| {
+ if ui.button("Auto Analyze…").clicked() {
+ self.pending_analyze_file_id = None;
+ self.show_analysis_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("Run selected analyzers").clicked() {
+ self.pending_analyze_file_id = None;
+ self.show_analysis_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("Analyze All Open…").on_hover_text("Run selected analyzers for the active open program").clicked() {
+ self.pending_analyze_file_id = None;
+ self.show_analysis_dialog = true;
+ ui.close_menu();
+ }
+ ui.separator();
+ ui.menu_button("One Shot Analysis", |ui| {
+ // Enumerate analyzers as sub-menu items (mirrors One-Shot).
+ // Clicking pre-selects that analyzer and opens the dialog.
+ let analyzer_names: Vec<String> =
+ self.analyzer_infos.iter().map(|a| a.name.clone()).collect();
+ let mut chosen: Option<String> = None;
+ for name in &analyzer_names {
+ if ui.button(name).clicked() {
+ chosen = Some(name.clone());
+ }
+ }
+ if let Some(name) = chosen {
+ for (i, info) in self.analyzer_infos.iter().enumerate() {
+ self.analyzer_enabled[i] = info.name == name;
+ }
+ self.pending_analyze_file_id = None;
+ self.show_analysis_dialog = true;
+ self.status = format!("One Shot: {name}");
+ self.log(self.status.clone());
+ 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()
+ {
+ self.nav_back();
+ ui.close_menu();
+ }
+ if ui
+ .add_enabled(self.can_nav_forward(), egui::Button::new("Forward"))
+ .clicked()
+ {
+ self.nav_forward();
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui.button("Go to entry").clicked() {
+ self.goto_entry();
+ ui.close_menu();
+ }
+ if ui.button("Go to address…").clicked() {
+ if let Some(prog) = &self.program {
+ if let Some(e) = prog.entry {
+ self.goto_input = format!("{e:#x}");
+ } else {
+ self.goto_input = format!("{:#x}", prog.image_base);
+ }
+ }
+ self.show_goto_dialog = true;
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui.button("Next Function (Ctrl+Down)").clicked() {
+ self.nav_next_function();
+ ui.close_menu();
+ }
+ if ui.button("Previous Function (Ctrl+Up)").clicked() {
+ self.nav_prev_function();
+ ui.close_menu();
+ }
+ if ui.button("Next Data").clicked() {
+ self.navigate_next_listing(false);
+ ui.close_menu();
+ }
+ if ui.button("Next Undefined").clicked() {
+ self.navigate_next_listing(true);
+ ui.close_menu();
+ }
+ if ui.button("Next Bookmark").clicked() {
+ self.nav_next_bookmark();
+ ui.close_menu();
+ }
+ if ui.button("Previous Bookmark").clicked() {
+ self.nav_prev_bookmark();
+ ui.close_menu();
+ }
+ });
+ ui.menu_button("Search", |ui| {
+ if ui.button("Search memory…").clicked() {
+ self.show_search_memory_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("Search program text…").clicked() {
+ self.show_search_text_dialog = true;
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui
+ .button("For Strings…")
+ .on_hover_text("Opens Defined Strings — session strings")
+ .clicked()
+ {
+ self.pane_open.insert(PaneKind::DefinedStrings, true);
+ ui.close_menu();
+ }
+ if ui.button("For Crypto Constants…").clicked() {
+ self.decrypt_pane.focus(DecryptTab::Constants);
+ self.pane_open.insert(PaneKind::Decrypt, true);
+ ui.close_menu();
+ }
+ if ui.button("For Recovered Strings…").clicked() {
+ self.decrypt_pane.focus(DecryptTab::Strings);
+ self.pane_open.insert(PaneKind::Decrypt, true);
+ ui.close_menu();
+ }
+ if ui.button("For Crypto Capabilities…").clicked() {
+ self.decrypt_pane.focus(DecryptTab::Capabilities);
+ self.pane_open.insert(PaneKind::Decrypt, true);
+ ui.close_menu();
+ }
+ if ui
+ .button("Decrypt…")
+ .on_hover_text("Open Decrypt pane on listing selection")
+ .clicked()
+ {
+ if let Some(va) = self.listing_focus_va {
+ self.open_decrypt_at(va, None);
+ } else {
+ self.pane_open.insert(PaneKind::Decrypt, true);
+ }
+ ui.close_menu();
+ }
+ if ui
+ .button("For Scalars…")
+ .on_hover_text("ScalarSearchPlugin · operand scalar range filter")
+ .clicked()
+ {
+ self.show_search_scalars_dialog = true;
+ ui.close_menu();
+ }
+ if ui
+ .button("For Address Tables…")
+ .on_hover_text("AutoTableDisassemblerPlugin · pointer table candidates")
+ .clicked()
+ {
+ self.show_search_address_tables_dialog = true;
+ // Populate immediately from analyzer output.
+ if let Some(prog) = self.program.as_ref() {
+ self.text_hits = address_table_hits(prog);
+ self.memory_hits.clear();
+ self.show_search_results = true;
+ }
+ ui.close_menu();
+ }
+ if ui
+ .button("Instruction Patterns…")
+ .on_hover_text("BytePatternPlugin · mnemonic + operand filter")
+ .clicked()
+ {
+ self.show_search_insn_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("For Direct References…").clicked() {
+ self.direct_references();
+ ui.close_menu();
+ }
+ if ui.button("For Matching Instructions…").clicked() {
+ self.show_search_insn_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("Repeat Search").clicked() {
+ self.repeat_search();
+ ui.close_menu();
+ }
+ });
+ ui.menu_button("Select", |ui| {
+ if ui.button("All").clicked() {
+ self.select_all_listing();
+ ui.close_menu();
+ }
+ if ui.button("All in View").clicked() {
+ self.select_all_listing();
+ ui.close_menu();
+ }
+ if ui.button("Clear").clicked() {
+ self.edit_clear_selection();
+ ui.close_menu();
+ }
+ if ui.button("Complement").clicked() {
+ if self.listing_selection.is_empty() { self.select_all_listing(); } else { self.edit_clear_selection(); }
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui.button("Bytes").clicked() {
+ self.select_focus_range("bytes");
+ ui.close_menu();
+ }
+ if ui.button("Instructions").clicked() {
+ self.select_focus_range("instruction");
+ ui.close_menu();
+ }
+ if ui.button("Data").clicked() {
+ self.select_focus_range("data");
+ ui.close_menu();
+ }
+ if ui.button("Undefined").clicked() {
+ self.select_focus_range("undefined data");
+ ui.close_menu();
+ }
+ if ui.button("Function").clicked() {
+ self.select_focus_range("function");
+ ui.close_menu();
+ }
+ if ui.button("Subroutine").clicked() {
+ self.select_focus_range("subroutine");
+ ui.close_menu();
+ }
+ if ui.button("Forward Refs").clicked() {
+ self.select_xrefs(true);
+ ui.close_menu();
+ }
+ if ui.button("Backward Refs").clicked() {
+ self.select_xrefs(false);
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui.button("Create Table From Selection").clicked() {
+ self.text_hits = self.listing.iter().enumerate().filter(|(i, _)| self.listing_selection.contains(*i)).map(|(_, i)| TextHit { kind: "selection", va: Some(i.address), text: i.text() }).collect();
+ self.show_search_results = true;
+ ui.close_menu();
+ }
+ });
+ ui.menu_button("Tools", |ui| {
+ if ui.button("Processor options…").clicked() {
+ self.show_processor_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("Compare Program…").clicked() {
+ if let Some(path) = rfd::FileDialog::new().pick_file() {
+ match load_path(&path) {
+ Ok(other) => { self.show_tools_dialog = true; self.tools_dialog_title = "Program comparison".into(); self.tools_dialog_body = format!("{} sections / {} symbols\n{} sections / {} symbols", self.program.as_ref().map(|p| p.sections.len()).unwrap_or(0), self.program.as_ref().map(|p| p.analysis.symbols.len()).unwrap_or(0), other.sections.len(), other.analysis.symbols.len()); }
+ Err(e) => self.log_error(e.to_string()),
+ }
+ }
+ ui.close_menu();
+ }
+ if ui.button("Program Differences…").clicked() {
+ self.show_tools_dialog = true; self.tools_dialog_title = "Program differences".into(); self.tools_dialog_body = self.program.as_ref().map(|p| format!("Sections: {}\nSymbols: {}\nFunctions: {}", p.sections.len(), p.analysis.symbols.len(), p.analysis.functions.len())).unwrap_or_else(|| "No program loaded".into());
+ ui.close_menu();
+ }
+ if ui
+ .button("Generate Checksum…")
+ .on_hover_text("Opens Checksum Generator")
+ .clicked()
+ {
+ self.pane_open.insert(PaneKind::ChecksumGenerator, true);
+ ui.close_menu();
+ }
+ if ui.button("Function Bit Patterns Explorer").clicked() {
+ self.show_search_insn_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("Instruction Table").clicked() {
+ let mut names: Vec<_> = self.listing.iter().map(|i| i.mnemonic.clone()).collect(); names.sort(); names.dedup();
+ self.show_tools_dialog = true; self.tools_dialog_title = "Instruction table".into(); self.tools_dialog_body = names.join("\n");
+ ui.close_menu();
+ }
+ if ui.button("Processor Manual…").clicked() {
+ self.show_processor_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("Benchmarks").clicked() {
+ self.show_tools_dialog = true;
+ self.tools_dialog_title = "Benchmarks".into();
+ self.tools_dialog_body = format!("Listing instructions: {}\nFunctions: {}", self.listing.len(), self.program.as_ref().map(|p| p.analysis.functions.len()).unwrap_or(0));
+ ui.close_menu();
+ }
+ if ui.button("Create Function").clicked() {
+ if let Some(va) = self.listing_focus_va {
+ self.show_tools_dialog = true;
+ self.tools_dialog_title = "Create Function".into();
+ self.tools_dialog_body = format!("Function creation requested at {va:#x}. Use Analysis to discover and persist functions.");
+ } else {
+ self.status = "Select a listing address first".into();
+ }
+ ui.close_menu();
+ }
+ if ui.button("VTable Probe").clicked() {
+ self.show_tools_dialog = true;
+ self.tools_dialog_title = "VTable Probe".into();
+ self.tools_dialog_body = format!("Recovered RTTI classes: {}", self.rtti.classes.len());
+ ui.close_menu();
+ }
+ if ui.button("Decode Support").clicked() {
+ self.show_decode_options_dialog = true;
+ ui.close_menu();
+ }
+ });
+ ui.menu_button("Graph", |ui| {
+ if ui.button("Function Graph").clicked() {
+ self.pane_open.insert(PaneKind::FunctionGraph, true);
+ ui.close_menu();
+ }
+ if ui.button("Function Call Graph").clicked() {
+ self.pane_open.insert(PaneKind::FunctionCallGraph, true);
+ ui.close_menu();
+ }
+ if ui.button("Function Call Trees").clicked() {
+ self.pane_open.insert(PaneKind::FunctionCallTrees, true);
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui.button("Block Flow").clicked() {
+ self.pane_open.insert(PaneKind::FunctionGraph, true);
+ ui.close_menu();
+ }
+ if ui.button("Code Flow").clicked() {
+ self.pane_open.insert(PaneKind::FunctionGraph, true);
+ ui.close_menu();
+ }
+ if ui.button("Calls").clicked() {
+ self.pane_open.insert(PaneKind::FunctionCallGraph, true);
+ ui.close_menu();
+ }
+ if ui.button("Data Flow").clicked() {
+ self.direct_references();
+ ui.close_menu();
+ }
+ });
+ ui.menu_button("Window", |ui| {
+ // Docked panels (long-standing).
+ ui.label(egui::RichText::new("Docked").small().weak());
+ ui.checkbox(&mut self.show_project_tree, "Project Tree (dock)");
+ ui.checkbox(&mut self.show_program_tree, "Program Tree (dock)");
+ ui.checkbox(&mut self.show_symbol_tree, "Symbol Tree (dock)");
+ ui.checkbox(&mut self.show_console, "Console (dock)");
+ ui.separator();
+ // Center dock tabs (Listing/Decompiler prefer side-by-side).
+ ui.label(egui::RichText::new("Center Tabs").small().weak());
+ 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 provider catalog (floating windows).
+ // Sorted alphabetically by title to mirror Window menu.
+ ui.label(
+ egui::RichText::new("All Providers (catalog)")
+ .small()
+ .weak(),
+ );
+ let mut providers: Vec<PaneKind> = PaneKind::ALL.to_vec();
+ providers.sort_by_key(|k| k.title());
+ for k in providers {
+ // Skip providers that are already covered by a dock/checkbox above
+ // to avoid double-toggles (Project/Program/Symbol Tree, Console).
+ if matches!(
+ k,
+ PaneKind::ProjectTree
+ | PaneKind::ProgramTree
+ | PaneKind::SymbolTree
+ | PaneKind::Console
+ | PaneKind::Overview
+ | PaneKind::Listing
+ | PaneKind::DecompiledView
+ | PaneKind::DataTypeManager
+ ) {
+ continue;
+ }
+ if k == PaneKind::AgentConsole {
+ if ui.button("Grok").clicked() {
+ self.show_console = true;
+ self.grok_pane.tab = crate::agent_pane::BottomTab::Grok;
+ }
+ continue;
+ }
+ let mut open = self.is_pane_open(k);
+ if ui.checkbox(&mut open, k.title()).changed() {
+ self.toggle_pane(k, open);
+ }
+ }
+ ui.separator();
+ // Single tabbed Debugger host.
+ ui.label(egui::RichText::new("Debugger tool").small().weak());
+ let mut dbg_open = self.debugger.host_open;
+ if ui.checkbox(&mut dbg_open, "Debugger").changed() {
+ self.debugger.host_open = dbg_open;
+ if dbg_open {
+ self.debugger.enabled = true;
+ if self.debugger.process_list_cache.is_empty() {
+ self.debugger.refresh_process_list();
+ }
+ }
+ }
+ if self.debugger.host_open {
+ ui.indent("dbg_tab_focus", |ui| {
+ for p in DebuggerPane::TAB_ORDER {
+ let selected = self.debugger.active_tab == *p;
+ if ui.selectable_label(selected, p.short_title()).clicked() {
+ self.debugger.focus_tab(*p);
+ }
+ }
+ });
+ }
+ ui.separator();
+ // Single tabbed Network (Ghidnet) host.
+ ui.label(egui::RichText::new("Network tool (Ghidnet)").small().weak());
+ let mut net_open = self.network.host_open;
+ if ui.checkbox(&mut net_open, "Network").changed() {
+ self.network.host_open = net_open;
+ if net_open {
+ self.network.enable_tool();
+ }
+ }
+ if self.network.host_open {
+ ui.indent("net_tab_focus", |ui| {
+ for p in NetworkPane::TAB_ORDER {
+ let selected = self.network.active_tab == *p;
+ if ui.selectable_label(selected, p.short_title()).clicked() {
+ self.network.focus_tab(*p);
+ }
+ }
+ });
+ }
+ ui.separator();
+ // layout tools.
+ if ui.button("Configure plugins…").clicked() {
+ self.show_configure_dialog = true;
+ self.configure_section = ConfigureSection::Plugins;
+ ui.close_menu();
+ }
+ if ui.button("Save Tool Layout…").clicked() {
+ self.layouts_cached = crate::layouts::list_layouts();
+ self.layouts_new_name = self.current_layout_name.clone();
+ self.show_layouts_dialog = true;
+ ui.close_menu();
+ }
+ });
+ ui.menu_button("Debugger", |ui| {
+ for act in DebuggerAction::ALL {
+ let hover = match act {
+ DebuggerAction::Launch => {
+ "CreateProcess CREATE_SUSPENDED + read-only session, then Resume (not a debug break-at-entry)"
+ }
+ DebuggerAction::Attach => {
+ "Open Debugger on Targets and refresh the process list"
+ }
+ DebuggerAction::Disconnect => {
+ "Detach the live process session (read-only bridge)"
+ }
+ DebuggerAction::ShowWatches => "Open Debugger → Watches tab",
+ DebuggerAction::ToggleBreakpoint => {
+ "Toggle a session-only breakpoint at the listing VA"
+ }
+ DebuggerAction::Continue => "Continue the attached debug session",
+ DebuggerAction::Interrupt => "Pause the attached debug session",
+ DebuggerAction::StepInto => "Step into on the active thread",
+ DebuggerAction::StepOver => "Step over on the active thread",
+ DebuggerAction::StepOut => "Step out on the active thread",
+ };
+ if ui.button(act.label()).on_hover_text(hover).clicked() {
+ match act {
+ DebuggerAction::Launch => {
+ let prefill = {
+ let p = self.path_input.trim();
+ if !p.is_empty() && std::path::Path::new(p).is_file() {
+ Some(std::path::PathBuf::from(p))
+ } else {
+ None
+ }
+ };
+ self.debugger.open_launch_ui(prefill.as_deref());
+ }
+ DebuggerAction::Attach => {
+ self.debugger.open_attach_ui();
+ }
+ DebuggerAction::Disconnect => {
+ self.debugger.detach_session();
+ }
+ DebuggerAction::ShowWatches => {
+ self.debugger.focus_tab(DebuggerPane::Watches);
+ }
+ DebuggerAction::ToggleBreakpoint => {
+ if let Some(va) = self.listing_focus_va {
+ self.debugger.toggle_breakpoint_live(va);
+ self.debugger.focus_tab(DebuggerPane::Breakpoints);
+ } else {
+ self.status = "Select a listing address before toggling a breakpoint".into();
+ self.log_warn(self.status.clone());
+ }
+ }
+ DebuggerAction::Continue => self.debugger.debug_continue(),
+ DebuggerAction::Interrupt => self.debugger.debug_pause(),
+ DebuggerAction::StepInto => self.debugger.debug_step(false),
+ DebuggerAction::StepOver => self.debugger.debug_step(true),
+ DebuggerAction::StepOut => self.debugger.debug_step_out(),
+ }
+ ui.close_menu();
+ }
+ }
+ ui.separator();
+ let mut enabled = self.debugger.enabled;
+ if ui.checkbox(&mut enabled, "Debugger tool mode").changed() {
+ if enabled {
+ self.debugger.enable_tool();
+ } else {
+ self.debugger.enabled = false;
+ self.debugger.host_open = false;
+ }
+ }
+ });
+ ui.menu_button("Network", |ui| {
+ for act in NetworkAction::ALL {
+ let hover = match act {
+ NetworkAction::ShowConnections => {
+ "Open Network → Connections (socket → owner)"
+ }
+ NetworkAction::ShowCapture => {
+ "Open Network → Capture / Flows (in-process session)"
+ }
+ NetworkAction::ShowAlerts => {
+ "Open Network → Alerts (GNR severity queue)"
+ }
+ NetworkAction::ShowRules => {
+ "Open Network → Rules (GNR pack check/load)"
+ }
+ NetworkAction::ShowDig => {
+ "Open Network → Dig (playbook compile/execute)"
+ }
+ NetworkAction::RefreshConnections => {
+ "Refresh host socket table via ghidrust-net-attr"
+ }
+ };
+ if ui.button(act.label()).on_hover_text(hover).clicked() {
+ match act {
+ NetworkAction::ShowConnections => {
+ self.network.focus_tab(NetworkPane::Connections);
+ }
+ NetworkAction::ShowCapture => {
+ self.network.focus_tab(NetworkPane::Capture);
+ }
+ NetworkAction::ShowAlerts => {
+ self.network.focus_tab(NetworkPane::Alerts);
+ }
+ NetworkAction::ShowRules => {
+ self.network.focus_tab(NetworkPane::Rules);
+ }
+ NetworkAction::ShowDig => {
+ self.network.focus_tab(NetworkPane::Dig);
+ }
+ NetworkAction::RefreshConnections => {
+ self.network.enable_tool();
+ self.network.focus_tab(NetworkPane::Connections);
+ self.network.refresh_connections();
+ }
+ }
+ ui.close_menu();
+ }
+ }
+ ui.separator();
+ let mut enabled = self.network.enabled;
+ if ui.checkbox(&mut enabled, "Network tool mode").changed() {
+ if enabled {
+ self.network.enable_tool();
+ } else {
+ self.network.enabled = false;
+ self.network.host_open = false;
+ }
+ }
+ });
+ ui.menu_button("Help", |ui| {
+ if ui.button("Contents (F1)").clicked() {
+ self.show_help_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("Help On…").clicked() {
+ self.show_help_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("API Help").clicked() {
+ self.show_help_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("User Preferences").clicked() {
+ self.show_prefs_dialog = true;
+ ui.close_menu();
+ }
+ if ui
+ .button("Show Log")
+ .on_hover_text("Console pane is open")
+ .clicked()
+ {
+ self.show_console = true;
+ ui.close_menu();
+ }
+ ui.separator();
+ if ui.button("About Ghidrust").clicked() {
+ let net = crate::network::network_info();
+ self.status = format!(
+ "Ghidrust {} — CodeBrowser shell; Ghidnet wave={} native={} capture={} caps=[{}] · {}",
+ env!("CARGO_PKG_VERSION"),
+ net.wave,
+ net.native,
+ net.capture,
+ net.caps.join(","),
+ crate::network::inline_block_reason()
+ );
+ self.log(self.status.clone());
+ ui.close_menu();
+ }
+ if ui.button("Roadmap…").clicked() {
+ self.log("See local development notes under dev/");
+ ui.close_menu();
+ }
+ });
+
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ let label = self.appearance.mode_label(self.theme);
+ if ui
+ .button(label)
+ .on_hover_text(format!(
+ "{} — toggle via File → Configure → Appearance",
+ self.appearance.display_name()
+ ))
+ .clicked()
+ {
+ self.theme = self.theme.toggle();
+ self.apply_theme(ctx);
+ self.log(format!(
+ "{} → {:?}",
+ self.appearance.display_name(),
+ self.theme
+ ));
+ }
+ });
+ });
+ });
+ }
+}
diff --git a/crates/ghidrust-gui/src/app/mod.rs b/crates/ghidrust-gui/src/app/mod.rs
new file mode 100644
index 0000000..2537a16
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/mod.rs
@@ -0,0 +1,1115 @@
+//! Application composition root (`GhidrustApp`) and frame loop glue.
+//!
+//! Extracted per demonolith Wave 0 — new UI panes land in sibling modules,
+//! not here.
+
+mod menus;
+mod shell_chrome;
+mod side_trees;
+mod provider_panes;
+mod center_panes;
+mod analysis_job;
+mod project_io;
+mod program_edit;
+mod dialogs;
+mod table_panes;
+mod session_api;
+use analysis_job::AnalysisJob;
+use project_io::load_recent_projects;
+
+use crate::checksum::ChecksumReport;
+use crate::debugger::DebuggerState;
+use crate::network::NetworkState;
+use crate::decomp_tokens::{DecompLine, TokenKind};
+use crate::decrypt_ui::DecryptPaneState;
+use crate::dock_tabs::DockTab;
+use eframe::egui::{self, Color32};
+use egui_dock::{DockArea, DockState, Style as DockStyle, TabViewer};
+use crate::events::EventBus;
+use ghidrust_core::{
+ analyzer_catalog, set_preferred_bulk_mode, AnalysisRunReport, AnalyzerInfo,
+ AppearanceTheme, BulkScanMode, CommentKind, CryptConstantHit, CryptoCapabilityHit,
+ FoundString, Instruction, ObfuscatedStringHit, Program, Project, RttiReport, ThemeMode,
+};
+use crate::graphs::{
+ expand_tree_node, CallTreeNode, GraphPaneState,
+};
+use crate::icons::{m3_icon, m3_linear_progress, M3Icon};
+use crate::listing::{
+ DecodeUiOpts, ListingSearch,
+};
+use crate::menu_actions::{
+ DecompStage, ListingSelection, MemoryHit, TextHit,
+};
+use crate::nav::NavHistory;
+use crate::panes::{Bookmark, BookmarkKind, PaneKind};
+use crate::register_manager::RegisterManagerState;
+use crate::scripts::{
+ MacropadReplState,
+ ScriptManagerState, TextEditorState,
+};
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::PathBuf;
+
+/// Locate the workspace `skill/SKILL.md` when running from a repo checkout so
+/// the Grok session prompt can inline the exhaustive catalog. When Ghidrust
+/// is installed as a released binary and no adjacent skill file exists we
+/// return `(String::new(), None)` — the `SystemPromptBuilder` still emits the
+/// honesty rules from its own body, just without the catalog.
+pub(crate) fn load_skill_body() -> (String, Option<PathBuf>) {
+ let candidates: Vec<PathBuf> = {
+ let mut v = Vec::new();
+ // 1. Adjacent to the running binary (production layout).
+ if let Ok(exe) = std::env::current_exe() {
+ if let Some(dir) = exe.parent() {
+ v.push(dir.join("skill").join("SKILL.md"));
+ if let Some(root) = dir.parent() {
+ v.push(root.join("skill").join("SKILL.md"));
+ }
+ }
+ }
+ // 2. Workspace-local (development layout — cargo run from repo root).
+ if let Ok(cwd) = std::env::current_dir() {
+ v.push(cwd.join("skill").join("SKILL.md"));
+ v.push(cwd.join(".").join("skill").join("SKILL.md"));
+ }
+ v
+ };
+ for c in candidates {
+ if let Ok(body) = std::fs::read_to_string(&c) {
+ return (body, Some(c));
+ }
+ }
+ (String::new(), None)
+}
+
+
+/// Native window entry used by the `ghidrust-gui` binary.
+pub fn run() -> eframe::Result<()> {
+ let title = format!("Ghidrust {} CodeBrowser", env!("CARGO_PKG_VERSION"));
+ let opts = eframe::NativeOptions {
+ viewport: egui::ViewportBuilder::default()
+ .with_inner_size([1280.0, 800.0])
+ .with_title(&title)
+ .with_icon(crate::branding::window_icon()),
+ ..Default::default()
+ };
+ eframe::run_native(
+ &title,
+ opts,
+ Box::new(|cc| Ok(Box::new(GhidrustApp::new(cc)))),
+ )
+}
+
+
+
+/// Configure dialog left-nav section.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub(crate) enum ConfigureSection {
+ #[default]
+ Appearance,
+ Plugins,
+}
+
+/// Last Search dialog kind (Search → Repeat Last Search).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum SearchKind {
+ Memory,
+ Scalars,
+ Instructions,
+ Text,
+}
+
+/// Legacy focused-center shim (synced from `center_dock`).
+/// The live layout is `center_dock` (`egui_dock`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum CenterPane {
+ /// File summary + analysis counts (default after open/analyze).
+ Overview,
+ Listing,
+ Decompiler,
+ 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.
+pub(crate) 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(crate) struct GhidrustApp {
+ path_input: String,
+ project_dir_input: String,
+ project_name_input: String,
+ status: String,
+ console: Vec<String>,
+ theme: ThemeMode,
+ project: Option<Project>,
+ active_file_id: Option<String>,
+ program: Option<Program>,
+ listing: Vec<Instruction>,
+ rtti: RttiReport,
+ strings: Vec<FoundString>,
+ crypt_constants: Vec<CryptConstantHit>,
+ crypto_constants_focus_va: Option<u64>,
+ obfuscated_strings: Vec<ObfuscatedStringHit>,
+ crypto_capabilities: Vec<CryptoCapabilityHit>,
+ decrypt_pane: DecryptPaneState,
+ last_analysis: AnalysisRunReport,
+ 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,
+ show_console: bool,
+ /// Bottom dock (Grok/Console/Raw) height in points. Owned by us so the
+ /// top-edge drag grip can resize reliably — egui's built-in
+ /// `TopBottomPanel::resizable` snaps back unless content expands, which
+ /// is easy to get wrong across versions.
+ console_height: f32,
+ show_analysis_dialog: bool,
+ /// Use experimental GPU bulk path for string/byte scan analyzers.
+ use_gpu_experimental: bool,
+ /// File id to open when user confirms analysis dialog (from Project Tree).
+ pending_analyze_file_id: Option<String>,
+ /// Live analysis job (progress UI while stepping).
+ analysis_job: Option<AnalysisJob>,
+ /// Tree selection (may differ from active until Open).
+ tree_selected_id: Option<String>,
+ project_tree_expanded: bool,
+ /// Pending delete: (file id, display name) — shown in confirm dialog.
+ pending_delete: Option<(String, String)>,
+ /// Dismissible banner after analysis finishes.
+ analysis_done_banner: Option<String>,
+ /// RTTI panel filter (case-insensitive substring).
+ rtti_filter: String,
+ rtti_filter_cache: String,
+ rtti_filtered_idx: Vec<usize>,
+ /// Function list filter.
+ fn_filter: String,
+ /// First-run: pick/open a project before the empty shell.
+ show_startup_picker: bool,
+ recent_projects: Vec<String>,
+ /// Splash / startup mark under the Ghidrust heading.
+ logo_texture: Option<egui::TextureHandle>,
+ nyi_note: Option<String>,
+ // ── selection / search / navigation. ──────
+ listing_selection: ListingSelection,
+ undo_stack: Vec<ListingSelection>,
+ redo_stack: Vec<ListingSelection>,
+ listing_focus_va: Option<u64>,
+ show_goto_dialog: bool,
+ goto_input: String,
+ show_search_memory_dialog: bool,
+ search_memory_input: String,
+ show_search_text_dialog: bool,
+ search_text_input: String,
+ search_text_case_insensitive: bool,
+ show_search_results: bool,
+ memory_hits: Vec<MemoryHit>,
+ text_hits: Vec<TextHit>,
+ show_processor_dialog: bool,
+ /// Cached decompiler pseudo-C for the focused function entry (None = stale / empty).
+ decomp_entry: Option<u64>,
+ decomp_text: String,
+ decomp_status: String,
+ /// Which decompile stage the Decompiler pane renders (Stage-0 / 0.5 / 1).
+ decomp_stage: DecompStage,
+ /// Last lift-coverage ratio (Stage-0.5 / Stage-1 only). Displayed as a
+ /// small chip in the Decompiler pane header so users know how much of
+ /// the emit came from real lifted IR vs Stage-0 scaffolding.
+ decomp_lift_ratio: Option<f32>,
+ // ── visible providers ─────────────
+ /// Open-state per-provider (Window menu toggles → floating egui::Window per pane).
+ pane_open: BTreeMap<PaneKind, bool>,
+ /// (Back / Forward / Alt+Left / Alt+Right).
+ nav_history: NavHistory,
+ /// Guard so back/forward don't re-push into the history.
+ nav_suspended: bool,
+ /// Bookmark table (5 kinds).
+ bookmarks: Vec<Bookmark>,
+ /// Filter for Bookmarks pane.
+ bookmark_filter: String,
+ /// Add-bookmark dialog state.
+ show_bookmark_dialog: bool,
+ bookmark_dialog_kind: BookmarkKind,
+ bookmark_dialog_category: String,
+ bookmark_dialog_description: String,
+ /// Filter for Functions window (separate from Symbol Tree filter).
+ functions_window_filter: String,
+ /// Filter for Symbol Table window.
+ symbol_table_filter: String,
+ /// Filter for Defined Strings window.
+ defined_strings_filter: String,
+ /// Defined Strings encoding filter: `"all"` | `"ascii"` | `"utf16le"`.
+ defined_strings_encoding: String,
+ /// plugin-event bus .
+ event_bus: EventBus,
+ /// tokenised decompiler cache (rebuilt after every refresh_decompiler_at).
+ decomp_lines: Vec<DecompLine>,
+ /// line index in `decomp_lines` cross-highlighted from Listing cursor.
+ decomp_cross_line: Option<usize>,
+ /// middle-click "highlight all occurrences" state.
+ decomp_highlight_text: Option<String>,
+ /// Symbol Tree ↔ Listing selection navigation toggle.
+ symbol_tree_nav: bool,
+ /// currently-focused function entry (for Symbol Tree highlight).
+ focused_function_entry: Option<u64>,
+ /// Program Tree fragment filter. `None` = full view; `Some({names})` = only those.
+ listing_view_filter: Option<BTreeSet<String>>,
+ /// Rename dialog state.
+ show_rename_dialog: bool,
+ rename_dialog_target_va: Option<u64>,
+ rename_dialog_old_name: String,
+ rename_dialog_new_name: String,
+ /// Retype dialog state.
+ show_retype_dialog: bool,
+ retype_dialog_target_va: Option<u64>,
+ retype_dialog_type: String,
+ /// Comment dialog state.
+ show_comment_dialog: bool,
+ comment_dialog_target_va: Option<u64>,
+ comment_dialog_kind: CommentKind,
+ comment_dialog_text: String,
+ /// Function Signature dialog state.
+ show_fn_signature_dialog: bool,
+ fn_signature_dialog_entry: Option<u64>,
+ fn_signature_dialog_text: String,
+ /// New Structure / Union / Enum dialog state.
+ show_new_type_dialog: bool,
+ new_type_dialog_kind: NewTypeKind,
+ new_type_dialog_name: String,
+ new_type_dialog_body: String,
+ /// Edit-existing-type dialog state (structure /
+ /// union / enum / typedef editor).
+ show_edit_type_dialog: bool,
+ edit_type_dialog_orig_name: String,
+ edit_type_dialog_name: String,
+ edit_type_dialog_body: String,
+ /// Data Type Chooser dialog (`T` shortcut over Listing).
+ show_type_chooser_dialog: bool,
+ type_chooser_target_va: Option<u64>,
+ type_chooser_filter: String,
+ /// DTM filter.
+ dtm_filter: String,
+ /// Comment Window filters .
+ comment_window_filter: String,
+ comment_window_kind_filter: Option<CommentKind>,
+ /// Console severity per line (`Info`, `Warn`, `Error`).
+ console_severity: Vec<ConsoleSeverity>,
+ // ── tables & search state ────────────────────────────
+ /// Byte Viewer state .
+ bytes_pane_va: Option<u64>,
+ bytes_pane_bpr: usize,
+ bytes_pane_rows: usize,
+ /// Filter for Symbol References pane (name / address substring).
+ 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)>,
+ show_equate_dialog: bool,
+ equate_dialog_va: Option<u64>,
+ equate_dialog_op: u8,
+ equate_dialog_name: String,
+ equate_dialog_value: String,
+ /// Function Tags — new-tag input + selected tag for row highlight.
+ function_tags_new_input: String,
+ /// External Programs filter.
+ external_programs_filter: String,
+ /// Data Type Preview — selected built-in for preview.
+ data_type_preview_selected: String,
+ /// Checksum Generator — cached results.
+ checksum_last: Option<ChecksumReport>,
+ /// Search → For Scalars.
+ show_search_scalars_dialog: bool,
+ search_scalars_min: String,
+ search_scalars_max: String,
+ /// Search → Instruction Patterns.
+ show_search_insn_dialog: bool,
+ search_insn_mnemonic: String,
+ search_insn_operands: String,
+ /// Search → For Address Tables (populated on-demand).
+ show_search_address_tables_dialog: bool,
+ /// Function Tags pane filter.
+ function_tags_filter: String,
+ // ── Graphs & maps ────────────────────────────────────
+ /// Function Graph / Call Graph / Call Trees session state.
+ graph_state: GraphPaneState,
+ /// Function Call Trees — top-level nodes (rebuilt on cursor change).
+ call_tree_incoming: Vec<CallTreeNode>,
+ call_tree_outgoing: Vec<CallTreeNode>,
+ /// Register Manager pane state (session-only until backend lattice lands).
+ register_manager: RegisterManagerState,
+ /// Memory Map editor — pending row edits (Add row).
+ memory_map_new_name: String,
+ memory_map_new_va: String,
+ memory_map_new_size: String,
+ memory_map_new_r: bool,
+ memory_map_new_w: bool,
+ memory_map_new_x: bool,
+ // ── Scripts ──────────────────────────────────────────
+ /// pane state.
+ script_manager: ScriptManagerState,
+ /// Text Editor multi-tab state.
+ text_editor: TextEditorState,
+ /// MCP REPL state.
+ mcp_repl: MacropadReplState,
+ // ── Debugger visibility ──────────────────────────────
+ /// Debugger tool state (tabbed host + Live Process Bridge).
+ debugger: DebuggerState,
+ // ── Docking / layouts / Configure ───────────────────
+ /// Configure dialog .
+ show_configure_dialog: bool,
+ /// Layout preset save/load dialog state.
+ show_layouts_dialog: bool,
+ layouts_new_name: String,
+ layouts_cached: Vec<String>,
+ /// Current layout name (empty = unnamed / default).
+ current_layout_name: String,
+ // ── Grok Build agent console (Option C: ACP sidecar) ───────────────
+ /// Per-window Grok pane state (session, transcript, install prompts, mode).
+ /// One project per window means one session at a time; skill is auto-wired
+ /// into `<project>/.grok/skills/` on project open; MCP/context on Start.
+ grok_pane: crate::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: crate::tool_panes::ToolPanesState,
+ /// Analysis → GPU Decompile… dialog visibility.
+ show_gpu_decompile_dialog: bool,
+ /// decode options for Listing / Disassembled View.
+ decode_opts: DecodeUiOpts,
+ /// Listing mnemonic / id / group filter.
+ listing_search: ListingSearch,
+ /// Full decode options dialog (arch/mode and engine options).
+ show_decode_options_dialog: bool,
+ /// Appearance family (Classic Ghidrust / Future Console / …).
+ appearance: AppearanceTheme,
+ /// Configure dialog left-nav section.
+ configure_section: ConfigureSection,
+ /// Native network plane host state.
+ network: NetworkState,
+ /// Optional PDB path selected via File → Load PDB…
+ pdb_path: Option<PathBuf>,
+ /// Last Search dialog kind (for Search → Repeat).
+ last_search_kind: Option<SearchKind>,
+ /// DTM apply-at-address bar input.
+ dtm_apply_addr_input: String,
+ /// DTM selected type name (for apply bar / highlight).
+ dtm_selected_type: Option<String>,
+ /// Apply-type-at-address dialog state.
+ apply_type_dialog: crate::wire_dialogs::ApplyTypeAtAddressState,
+ show_prefs_dialog: bool,
+ show_help_dialog: bool,
+ show_tools_dialog: bool,
+ tools_dialog_title: String,
+ tools_dialog_body: String,
+}
+
+/// severity tint for `Console` pane rows.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum ConsoleSeverity {
+ Info,
+ Warn,
+ Error,
+}
+
+/// Data Type Manager `New` submenu kinds.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum NewTypeKind {
+ Structure,
+ Union,
+ Enum,
+ Typedef,
+ FunctionDefinition,
+}
+
+/// scalar hover popup content for a Listing operand string.
+///
+/// Extracts the first hex/decimal literal and renders 1/2/4/8-byte dec/hex/ASCII
+/// interpretations (matches "Scalar popup").
+pub(crate) fn first_scalar_hint(operands: &str) -> Option<String> {
+ let mut chars = operands.char_indices().peekable();
+ while let Some((i, c)) = chars.next() {
+ if c == '0' && operands.as_bytes().get(i + 1) == Some(&b'x') {
+ let start = i + 2;
+ let end = operands[start..]
+ .find(|c: char| !c.is_ascii_hexdigit())
+ .map(|off| start + off)
+ .unwrap_or(operands.len());
+ if end > start {
+ if let Ok(v) = u64::from_str_radix(&operands[start..end], 16) {
+ return Some(scalar_hint_string(v));
+ }
+ }
+ }
+ if c.is_ascii_digit() {
+ let start = i;
+ let end = operands[start..]
+ .find(|c: char| !c.is_ascii_digit())
+ .map(|off| start + off)
+ .unwrap_or(operands.len());
+ if let Ok(v) = operands[start..end].parse::<u64>() {
+ return Some(scalar_hint_string(v));
+ }
+ }
+ }
+ None
+}
+
+pub(crate) fn scalar_hint_string(v: u64) -> String {
+ let ascii: String = v
+ .to_le_bytes()
+ .iter()
+ .take_while(|&&b| b != 0)
+ .filter(|&&b| (0x20..0x7f).contains(&b))
+ .map(|&b| b as char)
+ .collect();
+ format!(
+ "scalar {v:#x} · dec {v} · i32 {}{} · ascii \"{ascii}\"",
+ if (v as i32) < 0 { "" } else { "" },
+ v as i32
+ )
+}
+
+/// address hover popup content for a Listing operand string.
+pub(crate) fn first_address_hint(operands: &str) -> Option<String> {
+ let idx = operands.find("0x")?;
+ let start = idx + 2;
+ let end = operands[start..]
+ .find(|c: char| !c.is_ascii_hexdigit())
+ .map(|off| start + off)
+ .unwrap_or(operands.len());
+ if end == start {
+ return None;
+ }
+ let va = u64::from_str_radix(&operands[start..end], 16).ok()?;
+ Some(format!("target addr {va:#x}"))
+}
+
+/// ``- syntax colour picker for the Decompiler pane.
+pub(crate) fn token_style(kind: &TokenKind, base: Color32) -> (Color32, bool) {
+ match kind {
+ // Keywords: cyan .
+ TokenKind::Keyword => (Color32::from_rgb(0x64, 0xB5, 0xF6), false),
+ // Function names: warm orange.
+ TokenKind::Function => (Color32::from_rgb(0xFF, 0xB7, 0x4D), false),
+ // Variables: white/text default.
+ TokenKind::Variable => (base, false),
+ // Block labels: purple.
+ TokenKind::Label => (Color32::from_rgb(0xBA, 0x68, 0xC8), false),
+ // Addresses: cyan for click-hint.
+ TokenKind::Address => (Color32::from_rgb(0x4D, 0xD0, 0xE1), false),
+ // Constants: lighter cyan.
+ TokenKind::Constant => (Color32::from_rgb(0x80, 0xDE, 0xEA), false),
+ // Comments: green italics.
+ TokenKind::Comment => (Color32::from_rgb(0x81, 0xC7, 0x84), true),
+ // Syntax / whitespace / newline: dimmed text.
+ TokenKind::Syntax => (base.gamma_multiply(0.85), false),
+ TokenKind::Whitespace => (base, false),
+ }
+}
+
+impl NewTypeKind {
+ pub(crate) const ALL: &'static [NewTypeKind] = &[
+ NewTypeKind::Structure,
+ NewTypeKind::Union,
+ NewTypeKind::Enum,
+ NewTypeKind::Typedef,
+ NewTypeKind::FunctionDefinition,
+ ];
+
+ pub(crate) const fn label(self) -> &'static str {
+ match self {
+ NewTypeKind::Structure => "Structure",
+ NewTypeKind::Union => "Union",
+ NewTypeKind::Enum => "Enum",
+ NewTypeKind::Typedef => "Typedef",
+ NewTypeKind::FunctionDefinition => "Function Definition",
+ }
+ }
+
+ pub(crate) const fn template(self) -> &'static str {
+ match self {
+ NewTypeKind::Structure => "// Ghidrust user structure.\n// One field per line: `type name` (Stage-0 stores as string).\nint32_t field_0;\n",
+ NewTypeKind::Union => "// Ghidrust user union.\nint32_t as_int;\nfloat as_float;\n",
+ NewTypeKind::Enum => "// Ghidrust user enum. `NAME = <value>` per line.\nA = 0,\nB = 1,\n",
+ NewTypeKind::Typedef => "// Ghidrust typedef body: target type only.\nvoid *\n",
+ NewTypeKind::FunctionDefinition => "// Ghidrust function definition: `ret (params)`.\nint (int, char *)\n",
+ }
+ }
+}
+
+
+/// Recursively render one Call Tree row.
+///
+/// The node's `children_loaded` flag is flipped on first expand so callers
+/// pay the xref cost only when the user opens a branch.
+pub(crate) fn render_call_tree_node(
+ node: &mut CallTreeNode,
+ idx: usize,
+ direction: &'static str,
+ prog: &Program,
+ hide_thunks: bool,
+ ui: &mut egui::Ui,
+ _muted: Color32,
+ primary: Color32,
+ goto: &mut Option<u64>,
+) {
+ let title = egui::RichText::new(format!("{} {:#x}", node.name, node.va)).monospace();
+ let title = if node.is_thunk {
+ title.color(Color32::from_rgb(0xFB, 0xC0, 0x2D))
+ } else {
+ title.color(primary)
+ };
+ let resp = egui::CollapsingHeader::new(title)
+ .id_salt((direction, node.va, idx))
+ .default_open(false)
+ .show(ui, |ui| {
+ expand_tree_node(node, prog, direction, hide_thunks);
+ if node.children.is_empty() {
+ ui.small("(no further edges)");
+ return;
+ }
+ for (i, child) in node.children.iter_mut().enumerate() {
+ render_call_tree_node(
+ child,
+ i,
+ direction,
+ prog,
+ hide_thunks,
+ ui,
+ _muted,
+ primary,
+ goto,
+ );
+ }
+ });
+ if resp.header_response.clicked() {
+ *goto = Some(node.va);
+ }
+}
+
+impl GhidrustApp {
+ pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
+ // Cascadia/Consolas + symbol fallbacks so the Grok TUI logo/box-drawing
+ // aren't tofu (▯) under egui's tiny default monospace.
+ crate::grok_term::install_terminal_fonts(&cc.egui_ctx);
+ let mut app = Self::headless();
+ app.recent_projects = load_recent_projects();
+ app.show_startup_picker = true;
+ app.logo_texture = crate::branding::load_logo_texture(&cc.egui_ctx);
+ app.status = "Select a project to begin".into();
+ app.apply_theme(&cc.egui_ctx);
+ app
+ }
+
+ pub fn headless() -> Self {
+ let infos = analyzer_catalog();
+ let enabled = infos.iter().map(|a| a.default_enabled).collect();
+ Self {
+ path_input: String::new(),
+ project_dir_input: String::new(),
+ project_name_input: "MyProject".into(),
+ status: "Ready — File → New/Open Project, then Import binary".into(),
+ console: vec!["Ghidrust CodeBrowser started.".into()],
+ theme: ThemeMode::Dark,
+ project: None,
+ active_file_id: None,
+ program: None,
+ listing: Vec::new(),
+ rtti: RttiReport::default(),
+ strings: Vec::new(),
+ crypt_constants: Vec::new(),
+ crypto_constants_focus_va: None,
+ obfuscated_strings: Vec::new(),
+ crypto_capabilities: Vec::new(),
+ decrypt_pane: DecryptPaneState::default(),
+ last_analysis: AnalysisRunReport::default(),
+ last_analyzers_run: Vec::new(),
+ analyzer_enabled: enabled,
+ analyzer_infos: infos,
+ center: CenterPane::Listing,
+ center_dock: crate::dock_tabs::default_dock_state(),
+ show_project_tree: true,
+ show_program_tree: true,
+ show_symbol_tree: true,
+ show_console: true,
+ console_height: 280.0,
+ show_analysis_dialog: false,
+ use_gpu_experimental: false,
+ pending_analyze_file_id: None,
+ analysis_job: None,
+ tree_selected_id: None,
+ project_tree_expanded: true,
+ pending_delete: None,
+ analysis_done_banner: None,
+ rtti_filter: String::new(),
+ rtti_filter_cache: String::new(),
+ rtti_filtered_idx: Vec::new(),
+ fn_filter: String::new(),
+ show_startup_picker: false,
+ recent_projects: Vec::new(),
+ logo_texture: None,
+ nyi_note: None,
+ listing_selection: ListingSelection::default(),
+ undo_stack: Vec::new(),
+ redo_stack: Vec::new(),
+ listing_focus_va: None,
+ show_goto_dialog: false,
+ goto_input: String::new(),
+ show_search_memory_dialog: false,
+ search_memory_input: String::new(),
+ show_search_text_dialog: false,
+ search_text_input: String::new(),
+ search_text_case_insensitive: true,
+ show_search_results: false,
+ memory_hits: Vec::new(),
+ text_hits: Vec::new(),
+ show_processor_dialog: false,
+ decomp_entry: None,
+ decomp_text: String::new(),
+ decomp_status: String::new(),
+ // Stage-1 is now the default GUI decompiler stage —
+ // real SSA + structure + types instead of the mnemonic-scaffold
+ // Stage-0 preview. Users can still pick Stage-0/Stage-0.5 from
+ // the stage picker combo box.
+ decomp_stage: DecompStage::Stage1,
+ decomp_lift_ratio: None,
+ pane_open: Self::default_pane_open(),
+ nav_history: NavHistory::default(),
+ nav_suspended: false,
+ bookmarks: Vec::new(),
+ bookmark_filter: String::new(),
+ show_bookmark_dialog: false,
+ bookmark_dialog_kind: BookmarkKind::Note,
+ bookmark_dialog_category: String::new(),
+ bookmark_dialog_description: String::new(),
+ 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,
+ decomp_highlight_text: None,
+ symbol_tree_nav: true,
+ focused_function_entry: None,
+ listing_view_filter: None,
+ show_rename_dialog: false,
+ rename_dialog_target_va: None,
+ rename_dialog_old_name: String::new(),
+ rename_dialog_new_name: String::new(),
+ show_retype_dialog: false,
+ retype_dialog_target_va: None,
+ retype_dialog_type: String::new(),
+ show_comment_dialog: false,
+ comment_dialog_target_va: None,
+ comment_dialog_kind: CommentKind::Eol,
+ comment_dialog_text: String::new(),
+ show_fn_signature_dialog: false,
+ fn_signature_dialog_entry: None,
+ fn_signature_dialog_text: String::new(),
+ show_new_type_dialog: false,
+ new_type_dialog_kind: NewTypeKind::Structure,
+ new_type_dialog_name: String::new(),
+ new_type_dialog_body: String::new(),
+ show_edit_type_dialog: false,
+ edit_type_dialog_orig_name: String::new(),
+ edit_type_dialog_name: String::new(),
+ edit_type_dialog_body: String::new(),
+ show_type_chooser_dialog: false,
+ type_chooser_target_va: None,
+ type_chooser_filter: String::new(),
+ dtm_filter: String::new(),
+ comment_window_filter: String::new(),
+ comment_window_kind_filter: None,
+ console_severity: vec![ConsoleSeverity::Info],
+ bytes_pane_va: None,
+ bytes_pane_bpr: 16,
+ 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,
+ equate_dialog_va: None,
+ equate_dialog_op: 0,
+ equate_dialog_name: String::new(),
+ equate_dialog_value: String::new(),
+ function_tags_new_input: String::new(),
+ external_programs_filter: String::new(),
+ data_type_preview_selected: "dword".into(),
+ checksum_last: None,
+ show_search_scalars_dialog: false,
+ search_scalars_min: "0".into(),
+ search_scalars_max: "0xffff".into(),
+ show_search_insn_dialog: false,
+ search_insn_mnemonic: String::new(),
+ search_insn_operands: String::new(),
+ show_search_address_tables_dialog: false,
+ function_tags_filter: String::new(),
+ graph_state: GraphPaneState {
+ fn_graph_zoom: 1.0,
+ ..GraphPaneState::default()
+ },
+ call_tree_incoming: Vec::new(),
+ call_tree_outgoing: Vec::new(),
+ register_manager: RegisterManagerState::default(),
+ memory_map_new_name: String::new(),
+ memory_map_new_va: String::new(),
+ memory_map_new_size: String::new(),
+ memory_map_new_r: true,
+ memory_map_new_w: false,
+ memory_map_new_x: false,
+ script_manager: ScriptManagerState::new_with_builtin(),
+ text_editor: TextEditorState::default(),
+ mcp_repl: MacropadReplState::default(),
+ debugger: DebuggerState::default(),
+ show_configure_dialog: false,
+ show_layouts_dialog: false,
+ layouts_new_name: String::new(),
+ layouts_cached: Vec::new(),
+ current_layout_name: String::new(),
+ grok_pane: crate::agent_pane::GrokPaneState::new(),
+ tool_panes: crate::tool_panes::ToolPanesState::default(),
+ show_gpu_decompile_dialog: false,
+ decode_opts: DecodeUiOpts::default(),
+ listing_search: ListingSearch::default(),
+ show_decode_options_dialog: false,
+ appearance: AppearanceTheme::ClassicGhidrust,
+ configure_section: ConfigureSection::Appearance,
+ network: NetworkState::default(),
+ pdb_path: None,
+ last_search_kind: None,
+ dtm_apply_addr_input: String::new(),
+ dtm_selected_type: None,
+ apply_type_dialog: crate::wire_dialogs::ApplyTypeAtAddressState::default(),
+ show_prefs_dialog: false,
+ show_help_dialog: false,
+ show_tools_dialog: false,
+ tools_dialog_title: String::new(),
+ tools_dialog_body: String::new(),
+ }
+ }
+}
+
+impl eframe::App for GhidrustApp {
+ fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
+ self.apply_theme(ctx);
+
+ // drain event bus once per frame and fan out.
+ self.drain_events();
+
+ // Startup: choose project before the empty shell
+ if self.show_startup_picker {
+ self.ui_startup_picker(ctx);
+ return;
+ }
+
+ // Poll background analysis worker; keep repainting so progress UI stays live.
+ if self.analysis_job.is_some() {
+ if let Err(e) = self.step_analysis_job() {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ self.analysis_job = None;
+ set_preferred_bulk_mode(BulkScanMode::ParallelCpu);
+ }
+ ctx.request_repaint();
+ }
+
+ self.draw_menubar(ctx);
+
+ // TUI can claim focus/keys first — otherwise `G` opens Go To while typing.
+
+ self.draw_shell_chrome(ctx);
+
+ // Bottom dock: Grok TUI (default) + Console / Raw Log tabs. Prefer
+ // owning height + a painted drag grip — without them egui pins the
+ // panel to `default_height` and the drag handle becomes a 4px sliver
+ // that's easy to miss.
+ if self.show_console {
+ // Detect Grok TUI child exit before paint.
+ self.grok_pane.poll();
+ let screen_h = ctx.screen_rect().height();
+ // Own the height ourselves + paint a real drag grip. Built-in
+ // `resizable(true)` on TopBottomPanel is unreliable here (snaps
+ // back when content doesn't expand — egui #581 / 0.31).
+ let max_h = (screen_h - 160.0).max(220.0);
+ let min_h = 140.0;
+ self.console_height = self.console_height.clamp(min_h, max_h);
+ egui::TopBottomPanel::bottom("console")
+ .exact_height(self.console_height)
+ .show_separator_line(false)
+ .show(ctx, |ui| {
+ // Full-width drag strip at the top of the dock.
+ let grip_h = 10.0;
+ let (grip_rect, grip_resp) = ui.allocate_exact_size(
+ egui::vec2(ui.available_width(), grip_h),
+ egui::Sense::drag(),
+ );
+ let grip_color = if grip_resp.dragged() {
+ ui.visuals().widgets.active.bg_fill
+ } else if grip_resp.hovered() {
+ ui.visuals().widgets.hovered.bg_fill
+ } else {
+ ui.visuals().widgets.noninteractive.bg_fill
+ };
+ ui.painter().rect_filled(grip_rect, 0.0, grip_color);
+ // Center handle bar.
+ let bar =
+ egui::Rect::from_center_size(grip_rect.center(), egui::vec2(48.0, 3.0));
+ ui.painter().rect_filled(
+ bar,
+ 1.5,
+ ui.visuals().widgets.noninteractive.fg_stroke.color,
+ );
+ if grip_resp.hovered() || grip_resp.dragged() {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
+ }
+ if grip_resp.dragged() {
+ // Dragging the top edge up (negative dy) grows the panel.
+ self.console_height =
+ (self.console_height - grip_resp.drag_delta().y).clamp(min_h, max_h);
+ }
+ grip_resp.on_hover_text("Drag to resize console");
+
+ ui.set_min_height(ui.available_height());
+ self.render_bottom_dock(ui);
+ });
+ }
+
+ // Global keyboard shortcuts (after Grok dock so keyboard_captured is current).
+ // bindings: Alt+Left/Right, G, L/Ctrl+L, ;, T, Alt+Enter, Ctrl+Up/Down.
+ if !self.grok_pane.keyboard_captured {
+ let (
+ want_back,
+ want_forward,
+ want_goto,
+ want_rename,
+ want_retype,
+ want_comment,
+ want_chooser,
+ want_signature,
+ want_next_fn,
+ want_prev_fn,
+ ) = ctx.input(|i| {
+ let alt = i.modifiers.alt;
+ let ctrl = i.modifiers.ctrl;
+ (
+ alt && i.key_pressed(egui::Key::ArrowLeft),
+ alt && i.key_pressed(egui::Key::ArrowRight),
+ i.key_pressed(egui::Key::G) && !ctrl && !alt,
+ i.key_pressed(egui::Key::L) && !ctrl && !alt,
+ i.key_pressed(egui::Key::L) && ctrl,
+ i.key_pressed(egui::Key::Semicolon) && !ctrl && !alt,
+ i.key_pressed(egui::Key::T) && !ctrl && !alt,
+ alt && i.key_pressed(egui::Key::Enter),
+ ctrl && i.key_pressed(egui::Key::ArrowDown),
+ ctrl && i.key_pressed(egui::Key::ArrowUp),
+ )
+ });
+ if want_back {
+ self.nav_back();
+ }
+ if want_forward {
+ self.nav_forward();
+ }
+ if want_goto && self.program.is_some() {
+ if self.goto_input.is_empty() {
+ if let Some(prog) = &self.program {
+ self.goto_input = prog
+ .entry
+ .map(|e| format!("{e:#x}"))
+ .unwrap_or_else(|| format!("{:#x}", prog.image_base));
+ }
+ }
+ self.show_goto_dialog = true;
+ }
+ if want_rename {
+ if let Some(va) = self.listing_focus_va {
+ self.open_rename_dialog(va);
+ }
+ }
+ if want_retype {
+ if let Some(va) = self.listing_focus_va {
+ self.open_retype_dialog(va);
+ }
+ }
+ if want_comment {
+ if let Some(va) = self.listing_focus_va {
+ self.open_comment_dialog(va, CommentKind::Eol);
+ }
+ }
+ if want_chooser {
+ let va = self.listing_focus_va;
+ if va.is_some() {
+ self.open_type_chooser(va);
+ }
+ }
+ if want_signature {
+ if let Some(va) = self.listing_focus_va {
+ let entry = self
+ .program
+ .as_ref()
+ .and_then(|p| {
+ p.analysis
+ .functions
+ .iter()
+ .find(|f| va >= f.entry && va < f.end)
+ .map(|f| f.entry)
+ })
+ .unwrap_or(va);
+ self.open_signature_dialog(entry);
+ }
+ }
+ if want_next_fn {
+ self.nav_next_function();
+ }
+ if want_prev_fn {
+ self.nav_prev_function();
+ }
+ }
+
+
+ self.draw_side_trees(ctx);
+
+
+ // Analysis complete banner (top of frame content)
+ if let Some(banner) = self.analysis_done_banner.clone() {
+ egui::TopBottomPanel::top("analysis_done_banner").show(ctx, |ui| {
+ let t = self.tokens();
+ let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
+ let ok = Color32::from_rgb(0x4C, 0xAF, 0x50);
+ ui.horizontal(|ui| {
+ m3_icon(ui, M3Icon::CheckCircle, 18.0, ok);
+ ui.label(egui::RichText::new(banner).color(primary).strong());
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if ui.button("Dismiss").clicked() {
+ self.analysis_done_banner = None;
+ }
+ if ui.button("Open Overview").clicked() {
+ self.focus_center_tab(DockTab::Overview);
+ self.analysis_done_banner = None;
+ }
+ });
+ });
+ });
+ }
+
+ egui::CentralPanel::default().show(ctx, |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();
+ });
+
+ // draw every open floating provider pane.
+ self.draw_provider_panes(ctx);
+
+ // edit dialogs (rename / retype / comment / signature / new type).
+ self.draw_edit_dialogs(ctx);
+ self.draw_shell_dialogs(ctx);
+
+ // Floating M3 progress card while analysis runs
+ if let Some(frac) = self.analysis_progress_fraction() {
+ let t = self.tokens();
+ let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
+ let on_surface = Color32::from_rgb(t.on_surface[0], t.on_surface[1], t.on_surface[2]);
+ let track = Color32::from_rgb(
+ t.surface_container[0],
+ t.surface_container[1],
+ t.surface_container[2],
+ )
+ .gamma_multiply(1.4);
+ egui::Window::new("Analysis progress")
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_BOTTOM, [0.0, -48.0])
+ .title_bar(true)
+ .show(ctx, |ui| {
+ ui.set_min_width(360.0);
+ if let Some(job) = &self.analysis_job {
+ let n = job.names.len().max(1);
+ let step = (job.index + 1).min(n);
+ let cur = job
+ .names
+ .get(job.index)
+ .map(|s| s.as_str())
+ .unwrap_or("finishing…");
+ ui.label(
+ egui::RichText::new(format!("{} — {step}/{n}", job.file_label))
+ .color(on_surface)
+ .strong(),
+ );
+ ui.label(egui::RichText::new(cur).color(primary).small());
+ if job.use_gpu {
+ ui.small("GPU experimental bulk path enabled");
+ }
+ }
+ ui.add_space(6.0);
+ m3_linear_progress(ui, frac, primary, track);
+ ui.add_space(2.0);
+ ui.small(format!("{:.0}%", frac * 100.0));
+ });
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/ghidrust-gui/src/app/program_edit.rs b/crates/ghidrust-gui/src/app/program_edit.rs
new file mode 100644
index 0000000..6a26c95
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/program_edit.rs
@@ -0,0 +1,280 @@
+//! Program edits — rename/retype/comment/signature/types + dialog openers.
+//!
+//! Extracted per demonolith Wave 6.
+
+use super::{NewTypeKind, GhidrustApp};
+use crate::events::{GhidrustEvent, MutationKind};
+use ghidrust_core::CommentKind;
+
+impl GhidrustApp {
+
+ /// Rename the symbol / function at `va` (persists into `Program::edits`).
+ ///
+ /// Also mirrors the rename into `Program::analysis.functions[i].name()` so
+ /// every downstream pane (Symbol Tree, Functions Window, Symbol Table,
+ /// Bookmarks label preview) sees the new name without a full re-analyze.
+ /// Emits a `ProgramMutated::Rename` event which invalidates the Decompiler
+ /// cache so the header string is rebuilt.
+ pub(crate) fn rename_at(&mut self, va: u64, new_name: impl Into<String>) -> Result<(), String> {
+ let new_name = new_name.into();
+ if new_name.trim().is_empty() {
+ return Err("empty name".into());
+ }
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ // Mirror into analysis so tables / listing / decomp header pick it up.
+ if let Some(f) = prog.function_at_mut(va) {
+ f.name = new_name.clone();
+ } else if let Some(s) = prog.analysis.symbols.iter_mut().find(|s| s.va == va) {
+ s.name = new_name.clone();
+ }
+ // Persist as an edit even if analysis had no matching entry.
+ prog.edits.set_rename(va, &new_name);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Rename {
+ va,
+ new_name: new_name.clone(),
+ },
+ });
+ self.status = format!("Renamed {va:#x} → {new_name}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Retype the variable / global at `va` (persists into `Program::edits`).
+ pub(crate) fn retype_at(&mut self, va: u64, type_desc: impl Into<String>) -> Result<(), String> {
+ let type_desc = type_desc.into();
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ prog.edits.set_retype(va, &type_desc);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va,
+ type_desc: type_desc.clone(),
+ },
+ });
+ self.status = format!("Retyped {va:#x} → {type_desc}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Set (or clear) a comment at `va` (persists into `Program::edits`).
+ pub(crate) fn set_comment_at(
+ &mut self,
+ va: u64,
+ kind: CommentKind,
+ text: impl Into<String>,
+ ) -> Result<(), String> {
+ let text = text.into();
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ prog.edits.set_comment(va, kind, &text);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::CommentChanged { va },
+ });
+ self.status = if text.is_empty() {
+ format!("Cleared {} comment at {va:#x}", kind.label())
+ } else {
+ format!("Set {} comment at {va:#x}", kind.label())
+ };
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Set / replace a function signature (Edit Function Signature dialog).
+ pub(crate) fn set_function_signature(
+ &mut self,
+ entry: u64,
+ signature: impl Into<String>,
+ ) -> Result<(), String> {
+ let signature = signature.into();
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let mut sig = prog
+ .edits
+ .function_signature(entry)
+ .cloned()
+ .unwrap_or_default();
+ sig.signature = signature.clone();
+ prog.edits.set_function_signature(entry, sig);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: entry,
+ type_desc: signature.clone(),
+ },
+ });
+ self.status = format!("Function signature @ {entry:#x} → {signature}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Listing → Apply Data Type at `va` (drag from DTM, or `T` key).
+ pub(crate) fn apply_type_at(&mut self, va: u64, type_name: impl Into<String>) -> Result<(), String> {
+ let type_name = type_name.into();
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ prog.edits.set_applied_type(va, &type_name);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va,
+ type_desc: type_name.clone(),
+ },
+ });
+ self.status = format!("Applied type {type_name} @ {va:#x}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// DTM → Rename an existing user type (`Rename` on a Data Type
+ /// leaf). Rewrites `applied_types` so Listing decorations stay in sync.
+ #[cfg(test)]
+ pub(crate) fn rename_user_type(
+ &mut self,
+ old: impl Into<String>,
+ new: impl Into<String>,
+ ) -> Result<(), String> {
+ let old = old.into();
+ let new = new.into();
+ if new.trim().is_empty() {
+ return Err("empty type name".into());
+ }
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ if !prog.edits.rename_user_type(&old, &new) {
+ return Err(format!("no type named {old}"));
+ }
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: 0,
+ type_desc: format!("rename type: {old} → {new}"),
+ },
+ });
+ self.status = format!("Renamed type {old} → {new}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// DTM → Delete a user type (also unlinks any `Applied` decorations).
+ pub(crate) fn delete_user_type(&mut self, name: &str) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ if !prog.edits.delete_user_type(name) {
+ return Err(format!("no type named {name}"));
+ }
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: 0,
+ type_desc: format!("deleted type: {name}"),
+ },
+ });
+ self.status = format!("Deleted type {name}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ pub(crate) fn open_rename_dialog(&mut self, va: u64) {
+ let old = self
+ .program
+ .as_ref()
+ .and_then(|p| p.display_name_at(va))
+ .map(|s| s.to_string())
+ .unwrap_or_default();
+ self.show_rename_dialog = true;
+ self.rename_dialog_target_va = Some(va);
+ self.rename_dialog_old_name = old.clone();
+ self.rename_dialog_new_name = old;
+ }
+
+ pub(crate) fn open_retype_dialog(&mut self, va: u64) {
+ let cur = self
+ .program
+ .as_ref()
+ .and_then(|p| p.edits.retype_at(va))
+ .unwrap_or_default()
+ .to_string();
+ self.show_retype_dialog = true;
+ self.retype_dialog_target_va = Some(va);
+ self.retype_dialog_type = cur;
+ }
+
+ pub(crate) fn open_comment_dialog(&mut self, va: u64, kind: CommentKind) {
+ let text = self
+ .program
+ .as_ref()
+ .and_then(|p| p.edits.comment_at(va, kind))
+ .unwrap_or_default()
+ .to_string();
+ self.show_comment_dialog = true;
+ self.comment_dialog_target_va = Some(va);
+ self.comment_dialog_kind = kind;
+ self.comment_dialog_text = text;
+ }
+
+ pub(crate) fn open_signature_dialog(&mut self, entry: u64) {
+ let existing = self
+ .program
+ .as_ref()
+ .and_then(|p| p.edits.function_signature(entry))
+ .map(|s| s.signature.clone())
+ .unwrap_or_else(|| {
+ self.program
+ .as_ref()
+ .and_then(|p| p.function_at(entry))
+ .map(|f| {
+ format!(
+ "undefined {}({})",
+ f.name,
+ if f.parameters.is_empty() {
+ "void".to_string()
+ } else {
+ f.parameters.join(", ")
+ }
+ )
+ })
+ .unwrap_or_default()
+ });
+ self.show_fn_signature_dialog = true;
+ self.fn_signature_dialog_entry = Some(entry);
+ self.fn_signature_dialog_text = existing;
+ }
+
+ pub(crate) fn open_new_type_dialog(&mut self, kind: NewTypeKind) {
+ self.show_new_type_dialog = true;
+ self.new_type_dialog_kind = kind;
+ self.new_type_dialog_name.clear();
+ self.new_type_dialog_body = kind.template().to_string();
+ }
+
+ pub(crate) fn open_edit_type_dialog(&mut self, name: &str) {
+ let body = self
+ .program
+ .as_ref()
+ .and_then(|p| p.edits.user_type(name))
+ .unwrap_or_default()
+ .to_string();
+ self.show_edit_type_dialog = true;
+ self.edit_type_dialog_orig_name = name.to_string();
+ self.edit_type_dialog_name = name.to_string();
+ self.edit_type_dialog_body = body;
+ }
+
+ pub(crate) fn open_type_chooser(&mut self, va: Option<u64>) {
+ self.show_type_chooser_dialog = true;
+ self.type_chooser_target_va = va;
+ self.type_chooser_filter.clear();
+ }
+}
diff --git a/crates/ghidrust-gui/src/app/project_io.rs b/crates/ghidrust-gui/src/app/project_io.rs
new file mode 100644
index 0000000..eb1a102
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/project_io.rs
@@ -0,0 +1,503 @@
+//! Project / binary open-create-import-save + recent projects.
+//!
+//! Extracted per demonolith Wave 6.
+
+use super::{load_skill_body, GhidrustApp};
+use crate::dock_tabs::DockTab;
+use crate::events::GhidrustEvent;
+use crate::listing::{default_start_va, load_decode_prefs, reload, DecodeUiOpts};
+use ghidrust_core::{
+ arch_mode_for_program, default_arch_mode, load_path, AnalysisRunReport, Project,
+ ProjectTreeModel, RttiReport,
+};
+use std::path::{Path, PathBuf};
+
+
+pub(crate) fn recent_projects_path() -> PathBuf {
+ // %APPDATA%/ghidrust/recent_projects.txt (or home fallback)
+ if let Ok(appdata) = std::env::var("APPDATA") {
+ PathBuf::from(appdata)
+ .join("ghidrust")
+ .join("recent_projects.txt")
+ } else if let Ok(home) = std::env::var("USERPROFILE") {
+ PathBuf::from(home)
+ .join(".ghidrust")
+ .join("recent_projects.txt")
+ } else {
+ PathBuf::from("ghidrust_recent_projects.txt")
+ }
+}
+
+pub(crate) fn load_recent_projects() -> Vec<String> {
+ let p = recent_projects_path();
+ let Ok(text) = std::fs::read_to_string(&p) else {
+ return Vec::new();
+ };
+ text.lines()
+ .map(str::trim)
+ .filter(|l| !l.is_empty() && Path::new(l).is_dir())
+ .map(|s| s.to_string())
+ .collect()
+}
+
+pub(crate) fn save_recent_projects(paths: &[String]) {
+ let p = recent_projects_path();
+ if let Some(parent) = p.parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
+ let _ = std::fs::write(p, paths.join("\n"));
+}
+
+impl GhidrustApp {
+
+ pub(crate) fn menu_import_paths(&mut self, paths: Vec<PathBuf>) {
+ for path in paths {
+ self.path_input = path.display().to_string();
+ let result = if self.project.is_some() {
+ self.import_into_project()
+ } else {
+ self.load_binary(path)
+ };
+ if let Err(e) = result {
+ self.log_error(format!("Import {}: {e}", self.path_input));
+ }
+ }
+ }
+
+ pub(crate) fn save_results_as(&mut self, folder: PathBuf) -> Result<(), String> {
+ self.save_results()?;
+ let (analysis, listing) = {
+ let id = self.active_file_id.as_ref().ok_or_else(|| "no active project file".to_string())?;
+ let project = self.project.as_ref().ok_or_else(|| "no project open".to_string())?;
+ (project.analysis_path(id), project.listing_export_path(id))
+ };
+ std::fs::create_dir_all(&folder).map_err(|e| e.to_string())?;
+ for source in [analysis, listing] {
+ let name = source.file_name().ok_or_else(|| "invalid result path".to_string())?;
+ std::fs::copy(&source, folder.join(name)).map_err(|e| e.to_string())?;
+ }
+ self.status = format!("Copied saved analysis to {}", folder.display());
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ pub(crate) fn remember_project(&mut self, dir: &str) {
+ let dir = dir.trim().to_string();
+ if dir.is_empty() {
+ return;
+ }
+ self.recent_projects.retain(|p| p != &dir);
+ self.recent_projects.insert(0, dir);
+ self.recent_projects.truncate(12);
+ save_recent_projects(&self.recent_projects);
+ }
+
+ pub(crate) fn browse_project_dir(&mut self) {
+ if let Some(path) = rfd::FileDialog::new()
+ .set_title("Select project folder")
+ .pick_folder()
+ {
+ self.project_dir_input = path.display().to_string();
+ self.log(format!("Browsed project dir: {}", self.project_dir_input));
+ }
+ }
+
+ /// Browse for a binary and load it immediately (no project required).
+ pub(crate) fn browse_and_load_binary(&mut self) {
+ self.browse_binary_path();
+ if !self.path_input.trim().is_empty() {
+ if let Err(e) = self.load_binary(self.path_input.clone()) {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+
+ /// Browse folder then open project at that path.
+ pub(crate) fn browse_and_open_project(&mut self) {
+ self.browse_project_dir();
+ if !self.project_dir_input.trim().is_empty() {
+ if let Err(e) = self.open_project() {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+
+ /// Browse folder then create project there.
+ pub(crate) fn browse_and_create_project(&mut self) {
+ self.browse_project_dir();
+ if !self.project_dir_input.trim().is_empty() {
+ if let Err(e) = self.create_project() {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+
+ /// Browse binary then import into the open project.
+ pub(crate) fn browse_and_import(&mut self) {
+ self.browse_binary_path();
+ if !self.path_input.trim().is_empty() {
+ if let Err(e) = self.import_into_project() {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+
+ /// Confirm pending delete: remove from project disk + clear UI if active.
+ pub(crate) fn confirm_delete_file(&mut self) -> Result<(), String> {
+ let (id, name) = self
+ .pending_delete
+ .take()
+ .ok_or_else(|| "no pending delete".to_string())?;
+ let was_active = self.active_file_id.as_deref() == Some(id.as_str());
+ let entry = {
+ let proj = self
+ .project
+ .as_mut()
+ .ok_or_else(|| "no project open".to_string())?;
+ proj.remove_file(&id).map_err(|e| e.to_string())?
+ };
+ self.log(format!("Deleted {} (id={})", entry.display_name, entry.id));
+ if self.tree_selected_id.as_deref() == Some(id.as_str()) {
+ self.tree_selected_id = None;
+ }
+ if was_active {
+ self.program = None;
+ self.listing.clear();
+ self.strings.clear();
+ self.crypt_constants.clear();
+ self.obfuscated_strings.clear();
+ self.crypto_capabilities.clear();
+ self.rtti = RttiReport::default();
+ self.clear_decompiler_cache();
+ let next = self.project.as_ref().and_then(|p| p.meta.active_id.clone());
+ self.active_file_id = next.clone();
+ if let Some(next) = next {
+ self.open_project_file(&next)?;
+ } else {
+ self.status = format!("Deleted {name} — project empty");
+ }
+ } else {
+ self.status = format!("Deleted {name} from project");
+ }
+ Ok(())
+ }
+
+ pub(crate) fn cancel_delete_file(&mut self) {
+ self.pending_delete = None;
+ }
+
+
+
+ /// Project Window–style rows for the Project Tree (testable without a window).
+ pub(crate) fn project_tree_model(&self) -> Option<ProjectTreeModel> {
+ self.project.as_ref().map(|p| {
+ let mut m = p.tree_rows();
+ // Reflect GUI active selection if set
+ if let Some(ref aid) = self.active_file_id {
+ for f in &mut m.files {
+ f.active = f.id == *aid;
+ }
+ }
+ m
+ })
+ }
+
+ /// Open binary from project tree selection (same path as file chips).
+ pub(crate) fn open_from_tree(&mut self, id: &str) -> Result<(), String> {
+ self.tree_selected_id = Some(id.to_string());
+ self.open_project_file(id)
+ }
+
+ /// Open analysis options dialog for a project-tree file (does not run yet).
+ pub(crate) fn analyze_from_tree(&mut self, id: &str) -> Result<(), String> {
+ if self.analysis_job.is_some() {
+ return Err("analysis already in progress".into());
+ }
+ self.tree_selected_id = Some(id.to_string());
+ self.pending_analyze_file_id = Some(id.to_string());
+ self.show_analysis_dialog = true;
+ self.status = "Choose analyzers and options, then Run Analysis".into();
+ Ok(())
+ }
+
+ pub(crate) fn load_binary(&mut self, path: impl Into<PathBuf>) -> Result<(), String> {
+ let path = path.into();
+ self.path_input = path.display().to_string();
+ let prog = load_path(&path).map_err(|e| e.to_string())?;
+ let entry = default_start_va(&prog, None);
+ self.decode_opts.sync_machine_from_program(&prog);
+ self.listing_search.arch = self
+ .decode_opts
+ .resolved_arch()
+ .or_else(|| arch_mode_for_program(&prog).map(|(a, _)| a))
+ .unwrap_or_else(|| default_arch_mode().0);
+ let listing = reload(&prog, entry, &self.decode_opts)
+ .map(|r| r.insns)
+ .unwrap_or_default();
+ self.log(format!(
+ "Loaded {} ({}) base={:#x}",
+ prog.name, prog.format, prog.image_base
+ ));
+ let prog_name = prog.name.clone();
+ self.status = format!(
+ "Loaded {} — {} sections, {} listing insns",
+ prog.name,
+ prog.sections.len(),
+ listing.len()
+ );
+ self.program = Some(prog);
+ self.listing = listing;
+ self.rtti = RttiReport::default();
+ self.strings.clear();
+ self.crypt_constants.clear();
+ self.obfuscated_strings.clear();
+ self.crypto_capabilities.clear();
+ self.last_analysis = AnalysisRunReport::default();
+ self.last_analyzers_run.clear();
+ self.clear_decompiler_cache();
+ self.nav_history.clear();
+ self.event_bus
+ .publish(GhidrustEvent::ProgramActivated { name: prog_name });
+ if let Some(va) = self
+ .listing
+ .first()
+ .map(|i| i.address)
+ .or(self.listing_focus_va)
+ {
+ self.refresh_decompiler_at(va);
+ }
+ Ok(())
+ }
+
+ pub(crate) fn create_project(&mut self) -> Result<(), String> {
+ let dir = self.project_dir_input.trim().to_string();
+ if dir.is_empty() {
+ return Err("set Project dir path first".into());
+ }
+ let name = if self.project_name_input.trim().is_empty() {
+ "MyProject".into()
+ } else {
+ self.project_name_input.trim().to_string()
+ };
+ let p = Project::create(&dir, name).map_err(|e| e.to_string())?;
+ self.log(format!(
+ "Created project '{}' at {}",
+ p.meta.name,
+ p.root.display()
+ ));
+ self.status = format!("Project open: {}", p.root.display());
+ self.remember_project(&dir);
+ self.show_startup_picker = false;
+ self.project = Some(p);
+ self.decode_opts = DecodeUiOpts::default();
+ self.active_file_id = None;
+ self.ensure_project_skill_wired();
+ Ok(())
+ }
+
+ pub(crate) fn open_project(&mut self) -> Result<(), String> {
+ let dir = self.project_dir_input.trim().to_string();
+ if dir.is_empty() {
+ return Err("set Project dir path first".into());
+ }
+ let p = Project::open(&dir).map_err(|e| e.to_string())?;
+ self.project_name_input = p.meta.name.clone();
+ self.active_file_id = p.meta.active_id.clone();
+ if let Some(opts) = load_decode_prefs(&p.root) {
+ self.decode_opts = opts;
+ }
+ self.log(format!(
+ "Opened project '{}' ({} files)",
+ p.meta.name,
+ p.meta.files.len()
+ ));
+ self.status = format!("Project open: {}", p.root.display());
+ self.remember_project(&dir);
+ self.show_startup_picker = false;
+ // 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.
+ pub(crate) 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;
+ crate::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(crate) fn import_into_project(&mut self) -> Result<(), String> {
+ let path = self.path_input.trim();
+ if path.is_empty() {
+ return Err("set binary path first".into());
+ }
+ let proj = self
+ .project
+ .as_mut()
+ .ok_or_else(|| "no project open — create or open one first".to_string())?;
+ let entry = proj.import_file(path).map_err(|e| e.to_string())?;
+ self.active_file_id = Some(entry.id.clone());
+ self.log(format!("Imported {} (id={})", entry.display_name, entry.id));
+ let id = entry.id.clone();
+ self.open_project_file(&id)
+ }
+
+ pub(crate) fn open_project_file(&mut self, id: &str) -> Result<(), String> {
+ let entry = {
+ let proj = self
+ .project
+ .as_ref()
+ .ok_or_else(|| "no project".to_string())?;
+ proj.meta
+ .files
+ .iter()
+ .find(|f| f.id == id)
+ .ok_or_else(|| format!("unknown file id {id}"))?
+ .clone()
+ };
+ let display = entry.display_name.clone();
+ self.status = format!("Loading {display}…");
+ self.log(format!("Loading {display} (saved results if any)…"));
+
+ let (prog, saved, has_saved, bin_path) = {
+ let proj = self
+ .project
+ .as_ref()
+ .ok_or_else(|| "no project".to_string())?;
+ let has_saved = proj.has_saved_analysis(&entry.id);
+ let bin_path = proj.binary_path(&entry).display().to_string();
+ let (prog, saved) = proj
+ .load_program_with_results(&entry)
+ .map_err(|e| e.to_string())?;
+ (prog, saved, has_saved, bin_path)
+ };
+
+ let mut saved_analyzers = Vec::new();
+ if let Some(ref s) = saved {
+ saved_analyzers = s.saved_analyzers.clone();
+ }
+ self.decode_opts.sync_machine_from_program(&prog);
+ self.listing_search.arch = self
+ .decode_opts
+ .resolved_arch()
+ .or_else(|| arch_mode_for_program(&prog).map(|(a, _)| a))
+ .unwrap_or_else(|| default_arch_mode().0);
+ let start_va = default_start_va(&prog, None);
+ let listing = reload(&prog, start_va, &self.decode_opts)
+ .map(|r| r.insns)
+ .unwrap_or_default();
+ // Strings: session last_analysis only (full rescan is Analyze opt-in on large games).
+ if let Some(s) = self
+ .last_analysis
+ .results
+ .iter()
+ .find_map(|r| r.strings.clone().filter(|s| !s.is_empty()))
+ {
+ self.strings = s;
+ } else {
+ self.strings.clear();
+ self.crypt_constants.clear();
+ self.obfuscated_strings.clear();
+ self.crypto_capabilities.clear();
+ }
+ self.rtti = prog.rtti.clone();
+ self.rtti_filter.clear();
+ self.rtti_filter_cache.clear();
+ self.rtti_filtered_idx.clear();
+ self.rebuild_rtti_filter_cache();
+ self.path_input = bin_path;
+ self.active_file_id = Some(entry.id.clone());
+ self.tree_selected_id = Some(entry.id.clone());
+ if !saved_analyzers.is_empty() {
+ self.last_analyzers_run = saved_analyzers;
+ }
+ let rtti_n = self.rtti.classes.len();
+ let fn_n = prog.analysis.functions.len();
+ self.status = format!(
+ "Opened {display} — {fn_n} functions · {rtti_n} RTTI · {} listing lines{}",
+ listing.len(),
+ if has_saved {
+ " · analysis on disk"
+ } else {
+ " · not analyzed yet"
+ }
+ );
+ self.log(self.status.clone());
+ self.program = Some(prog);
+ self.listing = listing;
+ self.clear_decompiler_cache();
+ if let Some(va) = self
+ .listing
+ .first()
+ .map(|i| i.address)
+ .or_else(|| self.program.as_ref().and_then(|p| p.entry))
+ {
+ self.refresh_decompiler_at(va);
+ }
+ self.focus_center_tab(DockTab::Overview);
+ self.show_symbol_tree = true;
+ if let Some(p) = self.project.as_mut() {
+ let _ = p.set_active(id);
+ }
+ Ok(())
+ }
+
+ pub(crate) fn save_results(&mut self) -> Result<(), String> {
+ let id = self
+ .active_file_id
+ .clone()
+ .ok_or_else(|| "no active project file — import a binary into a project".to_string())?;
+ let prog = self
+ .program
+ .as_ref()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let (analysis_path, listing_path, saved) = {
+ let proj = self
+ .project
+ .as_ref()
+ .ok_or_else(|| "no project open".to_string())?;
+ let saved = proj
+ .save_program_results(&id, prog, &self.listing, &self.last_analyzers_run)
+ .map_err(|e| e.to_string())?;
+ (
+ proj.analysis_path(&id).display().to_string(),
+ proj.listing_export_path(&id).display().to_string(),
+ saved,
+ )
+ };
+ self.log(format!("Saved analysis → {analysis_path}"));
+ self.log(format!("Listing export → {listing_path}"));
+ self.status = format!(
+ "Saved {} ({} functions, {} insns)",
+ id,
+ saved.analysis.functions.len(),
+ saved.listing.len()
+ );
+ Ok(())
+ }
+}
diff --git a/crates/ghidrust-gui/src/app/provider_panes.rs b/crates/ghidrust-gui/src/app/provider_panes.rs
new file mode 100644
index 0000000..0b850f2
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/provider_panes.rs
@@ -0,0 +1,759 @@
+//! Floating provider pane router + table pane bodies.
+//!
+//! Extracted per demonolith Wave 4.
+
+use super::{render_call_tree_node, GhidrustApp};
+use crate::dock_tabs::DockTab;
+use crate::graphs::{
+ build_incoming_tree, build_outgoing_tree, data_xrefs_to, layout_call_graph,
+ layout_function_graph, render_call_graph, render_function_graph, FunctionGraphLayout,
+};
+use crate::menu_actions::STAGE0_MAX_INSNS;
+use crate::panes::{BookmarkKind, PaneKind};
+use crate::scripts::{
+ render_mcp_repl, render_script_manager, render_text_editor, TextEditorRequest,
+};
+use eframe::egui::{self, Color32};
+use ghidrust_core::CommentKind;
+
+impl GhidrustApp {
+
+ /// render every currently open floating provider pane.
+ ///
+ /// Panes render either real Stage-0 content (Bookmarks, Memory Map, Functions,
+ /// Symbol Table, Defined Strings, Relocations) or a clearly labelled "backend
+ /// pending" empty state that names the analyzer/model responsible for filling
+ /// them. See `crate::panes::empty_state` for the shared template.
+ pub(crate) fn draw_provider_panes(&mut self, ctx: &egui::Context) {
+ let t = self.tokens();
+ let muted = Color32::from_rgb(
+ t.on_surface_variant[0],
+ t.on_surface_variant[1],
+ t.on_surface_variant[2],
+ );
+ let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
+
+ // Snapshot the open-list so we can mutate self inside the closure.
+ let open_list: Vec<PaneKind> = self
+ .pane_open
+ .iter()
+ .filter_map(|(k, v)| if *v { Some(*k) } else { None })
+ .collect();
+
+ for kind in open_list {
+ let mut open = true;
+ let title = kind.title();
+ let id = egui::Id::new(kind.egui_id());
+ let win = egui::Window::new(title)
+ .id(id)
+ .open(&mut open)
+ .resizable(true)
+ .default_size(egui::vec2(520.0, 360.0));
+
+ match kind {
+ PaneKind::Bookmarks => {
+ win.show(ctx, |ui| self.ui_bookmarks_pane(ui, muted, primary));
+ }
+ PaneKind::MemoryMap => {
+ win.show(ctx, |ui| self.ui_memory_map_pane(ui, muted));
+ }
+ PaneKind::FunctionsWindow => {
+ win.show(ctx, |ui| self.ui_functions_window(ui, muted, primary));
+ }
+ PaneKind::SymbolTable => {
+ win.show(ctx, |ui| self.ui_symbol_table(ui, muted));
+ }
+ PaneKind::DefinedStrings => {
+ win.show(ctx, |ui| self.ui_defined_strings(ui, muted));
+ }
+ PaneKind::CryptoConstants => {
+ win.show(ctx, |ui| self.ui_crypto_constants_pane(ui, muted));
+ }
+ PaneKind::RecoveredStrings => {
+ win.show(ctx, |ui| self.ui_recovered_strings_pane(ui, muted));
+ }
+ PaneKind::CryptoCapabilities => {
+ win.show(ctx, |ui| self.ui_crypto_capabilities_pane(ui, muted));
+ }
+ PaneKind::Decrypt => {
+ let mut constants: Vec<_> =
+ if let Some(focus_va) = self.crypto_constants_focus_va {
+ self.crypt_constants
+ .iter()
+ .filter(|hit| hit.va.abs_diff(focus_va) <= 0x1000)
+ .cloned()
+ .collect()
+ } else {
+ self.crypt_constants.clone()
+ };
+ if let Some(focus_va) = self.crypto_constants_focus_va {
+ constants.sort_by_key(|hit| hit.va.abs_diff(focus_va));
+ }
+ let strings = self.obfuscated_strings.clone();
+ let capabilities = self.crypto_capabilities.clone();
+ win.show(ctx, |ui| {
+ if let Some(act) =
+ crate::decrypt_ui::ui_decrypt_window(
+ ui,
+ muted,
+ &mut self.decrypt_pane,
+ &constants,
+ &strings,
+ &capabilities,
+ )
+ {
+ match act {
+ crate::decrypt_ui::DecryptPaneAction::ApplyComment { va, text } => {
+ if let Err(e) =
+ self.set_comment_at(va, CommentKind::Eol, text)
+ {
+ self.status = format!("comment failed: {e}");
+ } else {
+ self.status =
+ format!("applied decrypt comment @ {va:#x}");
+ }
+ }
+ crate::decrypt_ui::DecryptPaneAction::ApplyBookmark { va, text } => {
+ self.add_bookmark(va, BookmarkKind::Analysis, "decrypt", format!("decrypted: {text}"));
+ }
+ crate::decrypt_ui::DecryptPaneAction::SendToListing { va } => {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ self.status = format!("Decrypt input focused in Listing at {va:#x}; output was not written as code.");
+ }
+ crate::decrypt_ui::DecryptPaneAction::LoadVa { va, len } => {
+ self.open_decrypt_at_len(va, len, None);
+ }
+ crate::decrypt_ui::DecryptPaneAction::Goto { va } => {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ crate::decrypt_ui::DecryptPaneAction::DecryptNearby { va, hint } => {
+ self.open_decrypt_nearby(va, Some(hint));
+ }
+ crate::decrypt_ui::DecryptPaneAction::BakeRemnant { va } => {
+ self.open_decrypt_at(va, None);
+ }
+ crate::decrypt_ui::DecryptPaneAction::FocusFunction { va } => {
+ self.focus_function(va);
+ }
+ }
+ }
+ });
+ }
+ PaneKind::RelocationTable => {
+ win.show(ctx, |ui| self.ui_relocation_table(ui, muted));
+ }
+ PaneKind::DisassembledView => {
+ win.show(ctx, |ui| self.ui_disassembled_view_pane(ui, muted));
+ }
+ PaneKind::CommentWindow => {
+ win.show(ctx, |ui| self.ui_comment_window(ui, muted));
+ }
+ PaneKind::DefinedData => {
+ win.show(ctx, |ui| self.ui_defined_data(ui, muted));
+ }
+ PaneKind::Bytes => {
+ win.show(ctx, |ui| self.ui_bytes_pane(ui, muted, primary));
+ }
+ PaneKind::SymbolReferences => {
+ win.show(ctx, |ui| self.ui_symbol_references(ui, muted));
+ }
+ PaneKind::EquatesTable => {
+ win.show(ctx, |ui| self.ui_equates_table(ui, muted));
+ }
+ PaneKind::FunctionTags => {
+ win.show(ctx, |ui| self.ui_function_tags(ui, muted));
+ }
+ PaneKind::ExternalPrograms => {
+ win.show(ctx, |ui| self.ui_external_programs(ui, muted));
+ }
+ PaneKind::DataTypePreview => {
+ win.show(ctx, |ui| self.ui_data_type_preview(ui, muted));
+ }
+ PaneKind::ChecksumGenerator => {
+ win.show(ctx, |ui| self.ui_checksum_generator(ui, muted));
+ }
+ // Graphs & maps.
+ PaneKind::FunctionGraph => {
+ win.default_size(egui::vec2(760.0, 520.0))
+ .show(ctx, |ui| self.ui_function_graph_pane(ui, muted, primary));
+ }
+ PaneKind::FunctionCallGraph => {
+ win.default_size(egui::vec2(760.0, 480.0)).show(ctx, |ui| {
+ self.ui_function_call_graph_pane(ui, muted, primary)
+ });
+ }
+ PaneKind::FunctionCallTrees => {
+ win.default_size(egui::vec2(760.0, 460.0)).show(ctx, |ui| {
+ self.ui_function_call_trees_pane(ui, muted, primary)
+ });
+ }
+ PaneKind::Entropy => {
+ win.default_size(egui::vec2(680.0, 220.0))
+ .show(ctx, |ui| self.ui_entropy_pane(ui, muted, primary));
+ }
+ PaneKind::Overview => {
+ win.default_size(egui::vec2(680.0, 340.0))
+ .show(ctx, |ui| self.ui_overview(ui));
+ }
+ PaneKind::RegisterManager => {
+ win.default_size(egui::vec2(560.0, 520.0))
+ .show(ctx, |ui| self.ui_register_manager_pane(ui, muted, primary));
+ }
+ // Scripts & interpreters.
+ PaneKind::ScriptManager => {
+ win.default_size(egui::vec2(760.0, 480.0))
+ .show(ctx, |ui| self.ui_script_manager_pane(ui, muted, primary));
+ }
+ PaneKind::TextEditor => {
+ win.default_size(egui::vec2(720.0, 520.0))
+ .show(ctx, |ui| self.ui_text_editor_pane(ui, muted, primary));
+ }
+ PaneKind::Python => {
+ 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| {
+ crate::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| {
+ crate::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| {
+ crate::tool_panes::ui_il2cpp_icalls(
+ ui,
+ &mut self.tool_panes.il2cpp_icalls,
+ prog,
+ muted,
+ );
+ });
+ }
+ PaneKind::Il2cppTouchMap => {
+ let prog = self.program.as_ref();
+ win.default_size(egui::vec2(760.0, 560.0)).show(ctx, |ui| {
+ crate::tool_panes::ui_il2cpp_touch_map(
+ ui,
+ &mut self.tool_panes.il2cpp_touch_map,
+ prog,
+ muted,
+ );
+ });
+ }
+ PaneKind::Il2cppStubs => {
+ let prog = self.program.as_ref();
+ win.default_size(egui::vec2(760.0, 560.0)).show(ctx, |ui| {
+ crate::tool_panes::ui_il2cpp_stubs(
+ ui,
+ &mut self.tool_panes.il2cpp_stubs,
+ prog,
+ muted,
+ );
+ });
+ }
+ PaneKind::UnityInventory => {
+ win.default_size(egui::vec2(760.0, 520.0)).show(ctx, |ui| {
+ crate::tool_panes::ui_unity_inventory(
+ ui,
+ &mut self.tool_panes.unity_inventory,
+ muted,
+ );
+ });
+ }
+ PaneKind::InstallInventory => {
+ win.default_size(egui::vec2(760.0, 520.0)).show(ctx, |ui| {
+ crate::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| {
+ crate::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| {
+ crate::tool_panes::ui_analysis_artifacts(
+ ui,
+ &mut self.tool_panes.artifacts,
+ muted,
+ );
+ });
+ }
+ _ => {
+ win.show(ctx, |ui| {
+ crate::panes::empty_state(ui, kind, muted);
+ });
+ }
+ }
+ // Reflect close-button clicks back into our state.
+ if !open {
+ self.pane_open.insert(kind, false);
+ }
+ }
+
+ // Debugger tool provider windows.
+ self.draw_debugger_panes(ctx, muted);
+ // Network / Ghidnet tool host.
+ self.draw_network_panes(ctx, muted);
+ }
+
+ // ── Graphs & maps ────────────────────────────────────
+
+ /// `` — CFG vertex/edge layout for the current function.
+ fn ui_function_graph_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ ui.heading("Function Graph");
+ ui.small(
+ egui::RichText::new(
+ "FunctionGraphPlugin analog · Stage-0 CFG from ghidrust-decomp::decompile_at",
+ )
+ .color(muted),
+ );
+ ui.separator();
+
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let Some(entry) = self.focused_function_entry.or_else(|| {
+ self.listing_focus_va.and_then(|va| {
+ prog.analysis
+ .functions
+ .iter()
+ .find(|f| va >= f.entry && va < f.end)
+ .map(|f| f.entry)
+ })
+ }) else {
+ ui.weak("Cursor is not inside a recovered function.");
+ ui.small(
+ egui::RichText::new(
+ "Click a function in Symbol Tree, Functions, or Listing to populate the graph.",
+ )
+ .color(muted),
+ );
+ return;
+ };
+
+ ui.horizontal(|ui| {
+ ui.label("Layout:");
+ let cur = self.graph_state.fn_graph_layout;
+ egui::ComboBox::from_id_salt("fg_layout")
+ .selected_text(cur.label())
+ .show_ui(ui, |ui| {
+ for l in FunctionGraphLayout::ALL {
+ ui.selectable_value(&mut self.graph_state.fn_graph_layout, *l, l.label());
+ }
+ });
+ ui.separator();
+ ui.label("Zoom:");
+ ui.add(
+ egui::Slider::new(&mut self.graph_state.fn_graph_zoom, 0.5..=2.0)
+ .clamping(egui::SliderClamping::Always)
+ .fixed_decimals(1),
+ );
+ if ui
+ .button("Fit")
+ .on_hover_text("Reset zoom to 1.0")
+ .clicked()
+ {
+ self.graph_state.fn_graph_zoom = 1.0;
+ }
+ ui.separator();
+ ui.small(egui::RichText::new(format!("Entry {entry:#x}")).color(muted));
+ });
+ ui.separator();
+
+ let name = prog.display_function_name_at(entry).unwrap_or_default();
+ if !name.is_empty() {
+ ui.small(egui::RichText::new(format!("Function {name}")).color(muted));
+ }
+
+ let algo = self.graph_state.fn_graph_layout;
+ let zoom = self.graph_state.fn_graph_zoom.max(0.1);
+ let focused_va = self.listing_focus_va;
+ let (rect, _resp) = ui.allocate_exact_size(
+ egui::vec2(ui.available_width(), 400.0 * zoom),
+ egui::Sense::hover(),
+ );
+ let (blocks, edges) = layout_function_graph(prog, entry, STAGE0_MAX_INSNS, algo, rect);
+ if blocks.is_empty() {
+ ui.painter().rect_stroke(
+ rect,
+ 4.0,
+ egui::Stroke::new(1.0, muted),
+ egui::StrokeKind::Middle,
+ );
+ ui.painter().text(
+ rect.center(),
+ egui::Align2::CENTER_CENTER,
+ "No Stage-0 CFG recovered for this VA.",
+ egui::FontId::proportional(13.0),
+ muted,
+ );
+ return;
+ }
+ let clicked = render_function_graph(ui, &blocks, &edges, focused_va, primary, muted);
+ if let Some(va) = clicked {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+
+ /// `` — level-based directed graph.
+ fn ui_function_call_graph_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ ui.heading("Function Call Graph");
+ ui.small(
+ egui::RichText::new(
+ "FunctionCallGraphPlugin analog · levels expanded from analyzer references",
+ )
+ .color(muted),
+ );
+ ui.separator();
+
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let Some(entry) = self
+ .focused_function_entry
+ .or_else(|| {
+ self.listing_focus_va.and_then(|va| {
+ prog.analysis
+ .functions
+ .iter()
+ .find(|f| va >= f.entry && va < f.end)
+ .map(|f| f.entry)
+ })
+ })
+ .or(prog.entry)
+ else {
+ ui.weak("No entry point — click a function in Symbol Tree to root the call graph.");
+ return;
+ };
+
+ ui.horizontal(|ui| {
+ ui.label("Callers levels:");
+ let mut lvl_in = self.graph_state.call_graph_levels_in;
+ ui.add(egui::Slider::new(&mut lvl_in, 0..=3));
+ self.graph_state.call_graph_levels_in = lvl_in;
+ ui.separator();
+ ui.label("Callees levels:");
+ let mut lvl_out = self.graph_state.call_graph_levels_out;
+ ui.add(egui::Slider::new(&mut lvl_out, 0..=3));
+ self.graph_state.call_graph_levels_out = lvl_out;
+ if ui.button("Reset").clicked() {
+ self.graph_state.call_graph_levels_in = 1;
+ self.graph_state.call_graph_levels_out = 1;
+ }
+ });
+ ui.separator();
+
+ let (rect, _resp) = ui.allocate_exact_size(
+ egui::vec2(ui.available_width(), 380.0),
+ egui::Sense::hover(),
+ );
+ let (verts, edges) = layout_call_graph(
+ prog,
+ entry,
+ self.graph_state.call_graph_levels_in,
+ self.graph_state.call_graph_levels_out,
+ rect,
+ );
+ ui.painter().rect_stroke(
+ rect,
+ 4.0,
+ egui::Stroke::new(1.0, muted),
+ egui::StrokeKind::Middle,
+ );
+ if verts.is_empty() {
+ ui.painter().text(
+ rect.center(),
+ egui::Align2::CENTER_CENTER,
+ "No call references recovered — run analyzers first.",
+ egui::FontId::proportional(13.0),
+ muted,
+ );
+ return;
+ }
+ let clicked = render_call_graph(ui, &verts, &edges, entry, primary, muted);
+ if let Some(va) = clicked {
+ self.focus_function(va);
+ }
+ }
+
+ /// `` — incoming callers / outgoing callees GTree pair.
+ fn ui_function_call_trees_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ ui.heading("Function Call Trees");
+ ui.small(
+ egui::RichText::new(
+ "CallTreePlugin analog · Incoming / Outgoing GTrees over analyzer refs",
+ )
+ .color(muted),
+ );
+ ui.separator();
+
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let Some(entry) = self.focused_function_entry.or_else(|| {
+ self.listing_focus_va.and_then(|va| {
+ prog.analysis
+ .functions
+ .iter()
+ .find(|f| va >= f.entry && va < f.end)
+ .map(|f| f.entry)
+ })
+ }) else {
+ ui.weak("Cursor is not inside a recovered function.");
+ return;
+ };
+
+ // Rebuild top level if root changed.
+ let root_name = prog.display_function_name_at(entry).unwrap_or_default();
+ ui.horizontal(|ui| {
+ ui.small(egui::RichText::new(format!("Source {root_name} @ {entry:#x}")).color(muted));
+ if ui.button("Refresh").clicked() {
+ self.call_tree_incoming.clear();
+ self.call_tree_outgoing.clear();
+ }
+ ui.separator();
+ ui.checkbox(&mut self.graph_state.call_tree_hide_thunks, "Hide thunks");
+ ui.checkbox(&mut self.graph_state.call_tree_refs_only, "References only");
+ });
+ ui.separator();
+
+ if self.call_tree_incoming.is_empty() && self.call_tree_outgoing.is_empty() {
+ self.call_tree_incoming = build_incoming_tree(prog, entry);
+ self.call_tree_outgoing = build_outgoing_tree(prog, entry);
+ if self.graph_state.call_tree_hide_thunks {
+ self.call_tree_incoming.retain(|n| !n.is_thunk);
+ self.call_tree_outgoing.retain(|n| !n.is_thunk);
+ }
+ }
+
+ let refs_only = self.graph_state.call_tree_refs_only;
+ let hide_thunks = self.graph_state.call_tree_hide_thunks;
+ let mut goto: Option<u64> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("calltrees_scroll")
+ .max_height(360.0)
+ .show(ui, |ui| {
+ ui.columns(2, |cols| {
+ cols[0].label(egui::RichText::new("Incoming (callers / refs to)").strong());
+ let mut inc = std::mem::take(&mut self.call_tree_incoming);
+ for (i, node) in inc.iter_mut().enumerate() {
+ render_call_tree_node(
+ node,
+ i,
+ "incoming",
+ prog,
+ hide_thunks,
+ &mut cols[0],
+ muted,
+ primary,
+ &mut goto,
+ );
+ }
+ self.call_tree_incoming = inc;
+ if refs_only {
+ cols[0].separator();
+ cols[0].label(
+ egui::RichText::new("Data refs to source")
+ .strong()
+ .color(muted),
+ );
+ for xr in data_xrefs_to(prog, entry) {
+ let text = egui::RichText::new(format!(
+ "{} {} ← {:#x}",
+ xr.kind, xr.preview, xr.from
+ ))
+ .monospace();
+ if cols[0].link(text).clicked() {
+ goto = Some(xr.from);
+ }
+ }
+ }
+
+ cols[1].label(egui::RichText::new("Outgoing (callees / refs from)").strong());
+ let mut out = std::mem::take(&mut self.call_tree_outgoing);
+ for (i, node) in out.iter_mut().enumerate() {
+ render_call_tree_node(
+ node,
+ i,
+ "outgoing",
+ prog,
+ hide_thunks,
+ &mut cols[1],
+ muted,
+ primary,
+ &mut goto,
+ );
+ }
+ self.call_tree_outgoing = out;
+ });
+ });
+ if let Some(va) = goto {
+ self.focus_function(va);
+ }
+ }
+
+ /// `` header — Shannon-entropy strip across mapped blocks.
+ fn ui_entropy_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ ui.heading("Entropy");
+ ui.small(
+ egui::RichText::new("EntropyPlugin analog · Shannon bits/byte over 256-byte windows")
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let samples = crate::entropy::entropy_samples(prog, 256);
+ ui.small(format!(
+ "{} windows sampled (256 bytes each)",
+ samples.len()
+ ));
+ let clicked_e =
+ crate::entropy::render_entropy_strip(ui, &samples, muted, self.listing_focus_va, primary);
+ ui.add_space(6.0);
+ ui.label(egui::RichText::new("Overview").strong().color(muted));
+ let clicked_o = crate::entropy::render_overview_strip(
+ ui,
+ prog,
+ &samples,
+ muted,
+ self.listing_focus_va,
+ primary,
+ );
+ ui.small(
+ egui::RichText::new("Click a strip to Go To that address. Green = exec, amber = writable, grey = readonly, cold-blue = low entropy, warm-red = high.").color(muted),
+ );
+ if let Some(va) = clicked_e.or(clicked_o) {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+
+ /// Register Manager — lattice + optional live debugger RegisterSet sync.
+ fn ui_register_manager_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ let fmt = self.program.as_ref().map(|p| p.format.clone());
+ // Pull a fresh snapshot when attached in debug mode.
+ if self.debugger.session.is_some() && self.debugger.is_debug_mode() {
+ if let Some(tid) = self.debugger.active_thread_id {
+ if let Some(sess) = self.debugger.session.clone() {
+ if let Ok(regs) =
+ ghidrust_core::process_thread_context_get(&sess.session_id, tid)
+ {
+ self.debugger.registers_cache = Some(regs);
+ }
+ }
+ }
+ }
+ let live = self.debugger.registers_cache.clone();
+ crate::register_manager::render(
+ &mut self.register_manager,
+ fmt.as_deref(),
+ live.as_ref(),
+ ui,
+ muted,
+ primary,
+ );
+ }
+
+ // ── Scripts & interpreters ───────────────────────────
+
+ fn ui_script_manager_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ if let Some(run) = render_script_manager(&mut self.script_manager, ui, muted, primary) {
+ let preview = self.script_manager.last_result.chars().take(240).collect::<String>();
+ let msg = format!("Script Manager · ran `{run}` → {preview}");
+ self.status = format!("Script Manager · ran `{run}`");
+ self.log(msg);
+ }
+ }
+
+ fn ui_text_editor_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ let req = render_text_editor(&mut self.text_editor, ui, muted, primary);
+ match req {
+ TextEditorRequest::None => {}
+ TextEditorRequest::NewUntitled => self.text_editor.open_untitled(),
+ TextEditorRequest::OpenFile => {
+ if let Some(path) = rfd::FileDialog::new()
+ .add_filter("Scripts", &["py", "rs", "txt", "md", "json", "toml"])
+ .add_filter("All", &["*"])
+ .pick_file()
+ {
+ if let Err(e) = self.text_editor.open_file(path) {
+ self.status = format!("open error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ TextEditorRequest::Save => {
+ if let Err(e) = self.text_editor.save_active() {
+ self.status = format!("save error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ TextEditorRequest::SaveAs => {
+ if let Some(path) = rfd::FileDialog::new().save_file() {
+ if let Err(e) = self.text_editor.save_active_as(path) {
+ self.status = format!("save error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ TextEditorRequest::Close => self.text_editor.close_active(),
+ }
+ }
+
+ fn ui_mcp_repl_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ render_mcp_repl(&mut self.mcp_repl, ui, muted, primary);
+ }
+
+ // ── Debugger tool ──────────────────────────────────
+
+ fn draw_debugger_panes(&mut self, ctx: &egui::Context, muted: Color32) {
+ crate::debugger::draw_host(ctx, &mut self.debugger, muted);
+ }
+
+ fn draw_network_panes(&mut self, ctx: &egui::Context, muted: Color32) {
+ crate::network::draw_host(ctx, &mut self.network, muted);
+ if let Some(path) = self.network.take_pending_load() {
+ match self.load_binary(path) {
+ Ok(()) => {
+ self.focus_center_tab(DockTab::Listing);
+ self.status = format!("{} — opened from Network Dig", self.status);
+ }
+ Err(e) => {
+ self.network.last_error = Some(e.clone());
+ self.status = format!("Network Dig open failed: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ if self.network.take_pending_focus_debugger() {
+ self.debugger.enable_tool();
+ }
+ }
+
+ // ── Docking / layouts / Configure ────────────────
+
+}
diff --git a/crates/ghidrust-gui/src/app/session_api.rs b/crates/ghidrust-gui/src/app/session_api.rs
new file mode 100644
index 0000000..3a4c7e8
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/session_api.rs
@@ -0,0 +1,1699 @@
+//! Remaining App session APIs — nav, search, panes catalog, layouts glue, etc.
+//!
+//! Extracted per demonolith Wave 7. Prefer new feature APIs here or domain modules,
+//! not growing `mod.rs` update loop.
+
+use super::{load_skill_body, ConsoleSeverity, GhidrustApp, SearchKind};
+use crate::checksum::{report_for, ChecksumMode};
+use crate::decomp_tokens::{
+ emit_token_triples, from_emit_tokens, line_for_va as decomp_line_for_va,
+ tokenize as tokenize_decomp,
+};
+use crate::dock_tabs::DockTab;
+use crate::events::{EventSource, GhidrustEvent, MutationKind};
+use crate::listing::{
+ reload, reload_for_goto,
+ save_decode_prefs,
+};
+use crate::menu_actions::{
+ decompile_entry_for_va, listing_index_at_or_before, parse_address,
+ parse_hex_pattern, pseudo_c_for_stage, search_instruction_patterns,
+ search_memory, search_program_text, search_scalars, stage0_pseudo_c,
+ stage1_pseudo_c_with_tokens, DecompStage, ListingSelection, TextHit,
+ STAGE0_MAX_INSNS,
+};
+use crate::nav::NavLocation;
+use crate::panes::{Bookmark, BookmarkKind, PaneKind};
+use eframe::egui::{self, Color32};
+use ghidrust_core::{
+ arch_mode_for_program, default_arch_mode, xrefs_from, xrefs_to, Arch, XRef,
+};
+use std::collections::{BTreeMap, BTreeSet};
+
+impl GhidrustApp {
+
+ /// Default `Window → *` toggles. Everything is available; only well-supported panes
+ /// float open by default so users see the full surface but aren't buried.
+ pub(crate) fn default_pane_open() -> BTreeMap<PaneKind, bool> {
+ let mut m = BTreeMap::new();
+ for k in PaneKind::ALL {
+ m.insert(*k, false);
+ }
+ m
+ }
+
+ /// Toggle a floating provider window (used by `Window` menu + toolbar shortcuts).
+ pub fn toggle_pane(&mut self, kind: PaneKind, open: bool) {
+ self.pane_open.insert(kind, open);
+ }
+
+ /// Whether the given provider is currently visible.
+ pub fn is_pane_open(&self, kind: PaneKind) -> bool {
+ *self.pane_open.get(&kind).unwrap_or(&false)
+ }
+
+ pub(crate) fn clear_decompiler_cache(&mut self) {
+ self.decomp_entry = None;
+ self.decomp_text.clear();
+ self.decomp_status.clear();
+ self.decomp_lines.clear();
+ self.decomp_cross_line = None;
+ self.decomp_lift_ratio = None;
+ }
+
+ /// Refresh the decompiler cache for `va` (containing / nearest function)
+ /// at the currently-selected [`DecompStage`] (Stage-0 / 0.5 / 1).
+ ///
+ /// Also rebuilds the tokenised `decomp_lines` cache used by the pane for
+ /// click-navigation and cross-highlight with the Listing. If Stage-0.5
+ /// / Stage-1 fail (e.g. structuring gave up on an irreducible region)
+ /// the pane silently falls back to Stage-0 so the user always sees
+ /// something.
+ pub fn refresh_decompiler_at(&mut self, va: u64) {
+ let Some(prog) = self.program.as_ref() else {
+ self.decomp_entry = None;
+ self.decomp_text.clear();
+ self.decomp_status = "No program loaded.".into();
+ self.decomp_lines.clear();
+ self.decomp_cross_line = None;
+ self.decomp_lift_ratio = None;
+ return;
+ };
+ let entry = decompile_entry_for_va(prog, va);
+ let cache_ok = self.decomp_entry == Some(entry)
+ && !self.decomp_text.is_empty()
+ && self.decomp_status.contains(self.decomp_stage.label());
+ if cache_ok {
+ self.decomp_cross_line = decomp_line_for_va(&self.decomp_lines, va);
+ return;
+ }
+ let stage = self.decomp_stage;
+ // R5: Stage-1 prefers emit-time tokens when present.
+ if stage == DecompStage::Stage1 {
+ if let Ok((entry, text, ratio, tokens)) =
+ stage1_pseudo_c_with_tokens(prog, va, STAGE0_MAX_INSNS)
+ {
+ self.decomp_entry = Some(entry);
+ let triples = emit_token_triples(&tokens);
+ let lines = from_emit_tokens(&triples);
+ self.decomp_lines = if lines.is_empty() {
+ tokenize_decomp(&text)
+ } else {
+ lines
+ };
+ self.decomp_cross_line = decomp_line_for_va(&self.decomp_lines, va);
+ self.decomp_text = text;
+ self.decomp_lift_ratio = Some(ratio);
+ let user_name = self
+ .program
+ .as_ref()
+ .and_then(|p| p.display_function_name_at(entry));
+ self.decomp_status = match user_name {
+ Some(name) => {
+ format!("Stage-1 · {name} @ {entry:#x} · lift={:.1}%", ratio * 100.0)
+ }
+ None => format!("Stage-1 · {entry:#x} · lift={:.1}%", ratio * 100.0),
+ };
+ return;
+ }
+ }
+ let attempt = pseudo_c_for_stage(prog, va, STAGE0_MAX_INSNS, stage);
+ let (label, result) = match attempt {
+ Ok(v) => (stage.label(), Ok(v)),
+ Err(_) if stage != DecompStage::Stage0 => {
+ // Never render an empty pane — retry at Stage-0.
+ let fallback =
+ stage0_pseudo_c(prog, va, STAGE0_MAX_INSNS).map(|(e, t)| (e, t, None));
+ (DecompStage::Stage0.label(), fallback)
+ }
+ Err(e) => (stage.label(), Err(e)),
+ };
+ match result {
+ Ok((entry, text, ratio)) => {
+ self.decomp_entry = Some(entry);
+ self.decomp_lines = tokenize_decomp(&text);
+ self.decomp_cross_line = decomp_line_for_va(&self.decomp_lines, va);
+ self.decomp_text = text;
+ self.decomp_lift_ratio = ratio;
+ let user_name = self
+ .program
+ .as_ref()
+ .and_then(|p| p.display_function_name_at(entry));
+ self.decomp_status = match (user_name, ratio) {
+ (Some(name), Some(r)) => {
+ format!("{label} · {name} @ {entry:#x} · lift={:.1}%", r * 100.0)
+ }
+ (Some(name), None) => format!("{label} · {name} @ {entry:#x}"),
+ (None, Some(r)) => {
+ format!("{label} · {entry:#x} · lift={:.1}%", r * 100.0)
+ }
+ (None, None) => format!("{label} · {entry:#x}"),
+ };
+ }
+ Err(e) => {
+ self.decomp_entry = Some(entry);
+ self.decomp_text = format!("// decompile failed at {entry:#x}\n// {e}\n");
+ self.decomp_lines = tokenize_decomp(&self.decomp_text);
+ self.decomp_cross_line = None;
+ self.decomp_lift_ratio = None;
+ self.decomp_status = format!("error: {e}");
+ }
+ }
+ }
+
+ /// Switch the active decompile stage (Stage-0 / 0.5 / 1) and re-run the
+ /// emit for the currently-focused function entry. Public so the pane
+ /// dropdown + tests can drive it.
+ pub fn set_decomp_stage(&mut self, stage: DecompStage) {
+ if self.decomp_stage == stage {
+ return;
+ }
+ self.decomp_stage = stage;
+ self.decomp_text.clear();
+ self.decomp_lines.clear();
+ self.decomp_cross_line = None;
+ self.decomp_lift_ratio = None;
+ if let Some(va) = self.decomp_entry {
+ self.refresh_decompiler_at(va);
+ }
+ }
+
+ /// Focus a center dock tab. Listing/Decompiler prefer a side-by-side split.
+ pub(crate) fn focus_center_tab(&mut self, tab: DockTab) {
+ match tab {
+ DockTab::Listing | DockTab::Decompiler => {
+ crate::dock_tabs::ensure_side_by_side(&mut self.center_dock, tab);
+ }
+ DockTab::Overview | DockTab::DataTypes => {
+ crate::dock_tabs::focus_tab(&mut self.center_dock, tab);
+ }
+ }
+ self.center = tab.into();
+ }
+
+ pub(crate) fn sync_center_from_dock(&mut self) {
+ self.center = DockTab::from_id(crate::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}");
+ if let Err(e) = self.goto_address_str(&addr) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ return;
+ }
+ self.focused_function_entry = Some(entry);
+ self.refresh_decompiler_at(entry);
+ self.focus_center_tab(DockTab::Decompiler);
+ let name = self
+ .program
+ .as_ref()
+ .and_then(|p| p.display_function_name_at(entry))
+ .unwrap_or_else(|| format!("{entry:#x}"));
+ self.status = format!("Function {name}");
+ self.log(self.status.clone());
+ }
+
+ /// Navigation → Back (Alt+Left).
+ ///
+ /// Pops the previous location off the Back stack and re-runs `goto_address_str`
+ /// without recording another entry (guarded by `nav_suspended`).
+ pub fn nav_back(&mut self) -> bool {
+ let Some(prev) = self.nav_history.back() else {
+ self.status = "Navigation → nothing to go back to".into();
+ self.log(self.status.clone());
+ return false;
+ };
+ self.nav_suspended = true;
+ let r = self.goto_address_str(&format!("{:#x}", prev.va));
+ self.nav_suspended = false;
+ if let Err(e) = r {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ return false;
+ }
+ self.refresh_decompiler_at(prev.va);
+ self.status = format!("Back → {:#x}", prev.va);
+ self.log(self.status.clone());
+ true
+ }
+
+ /// Navigation → Forward (Alt+Right).
+ pub fn nav_forward(&mut self) -> bool {
+ let Some(next) = self.nav_history.forward() else {
+ self.status = "Navigation → nothing to go forward to".into();
+ self.log(self.status.clone());
+ return false;
+ };
+ self.nav_suspended = true;
+ let r = self.goto_address_str(&format!("{:#x}", next.va));
+ self.nav_suspended = false;
+ if let Err(e) = r {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ return false;
+ }
+ self.refresh_decompiler_at(next.va);
+ self.status = format!("Forward → {:#x}", next.va);
+ self.log(self.status.clone());
+ true
+ }
+
+ /// Convenience: are we able to step back?
+ pub fn can_nav_back(&self) -> bool {
+ self.nav_history.can_back()
+ }
+ pub fn can_nav_forward(&self) -> bool {
+ self.nav_history.can_forward()
+ }
+
+ /// Bookmarks → Add (BookmarkPlugin analog). Va + kind + category + description.
+ pub fn add_bookmark(
+ &mut self,
+ va: u64,
+ kind: BookmarkKind,
+ category: impl Into<String>,
+ description: impl Into<String>,
+ ) {
+ self.bookmarks.push(Bookmark {
+ va,
+ kind,
+ category: category.into(),
+ description: description.into(),
+ });
+ self.pane_open.insert(PaneKind::Bookmarks, true);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::BookmarkAdded { va },
+ });
+ self.status = format!("Bookmark added at {va:#x} ({})", kind.label());
+ self.log(self.status.clone());
+ }
+
+ /// Bookmarks → Delete.
+ pub fn delete_bookmark(&mut self, index: usize) {
+ if index < self.bookmarks.len() {
+ let b = self.bookmarks.remove(index);
+ let va = b.va;
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::BookmarkRemoved { va },
+ });
+ self.status = format!("Bookmark removed at {va:#x} ({})", b.kind.label());
+ self.log(self.status.clone());
+ }
+ }
+
+ /// Navigation → Next Bookmark.
+ pub fn nav_next_bookmark(&mut self) {
+ if self.bookmarks.is_empty() {
+ self.status = "No bookmarks — Bookmarks → Add".into();
+ self.log(self.status.clone());
+ return;
+ }
+ let cur = self.listing_focus_va.unwrap_or(0);
+ let mut vas: Vec<u64> = self.bookmarks.iter().map(|b| b.va).collect();
+ vas.sort();
+ if let Some(va) = vas.iter().copied().find(|&va| va > cur) {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ } else {
+ let _ = self.goto_address_str(&format!("{:#x}", vas[0]));
+ }
+ }
+
+ /// Navigation → Previous Bookmark.
+ pub fn nav_prev_bookmark(&mut self) {
+ if self.bookmarks.is_empty() {
+ self.status = "No bookmarks — Bookmarks → Add".into();
+ self.log(self.status.clone());
+ return;
+ }
+ let cur = self.listing_focus_va.unwrap_or(u64::MAX);
+ let mut vas: Vec<u64> = self.bookmarks.iter().map(|b| b.va).collect();
+ vas.sort();
+ if let Some(va) = vas.iter().rev().copied().find(|&va| va < cur) {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ } else {
+ let _ = self.goto_address_str(&format!("{:#x}", vas.last().copied().unwrap()));
+ }
+ }
+
+ // ── user edits ───────────────────────────────────────
+
+ /// Decompiler → Commit Params/Return. Adopts the analyzer-inferred parameter
+ /// list + a "auto" return type as user commitments.
+ pub fn commit_params_return(&mut self, entry: u64) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let (params, ret) = {
+ let f = prog
+ .function_at(entry)
+ .ok_or_else(|| format!("no function at {entry:#x}"))?;
+ let params: Vec<String> = if f.parameters.is_empty() {
+ Vec::new()
+ } else {
+ f.parameters.clone()
+ };
+ // Ghidrust Stage-0 has no dataflow return-type yet — commit as `undefined`.
+ (params, "undefined".to_string())
+ };
+ prog.edits.commit_params(entry, params.clone());
+ prog.edits.commit_return_type(entry, &ret);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: entry,
+ type_desc: format!("commit params: {} · return {ret}", params.len()),
+ },
+ });
+ self.status = format!(
+ "Commit Params/Return @ {entry:#x} ({} param(s), return {ret})",
+ params.len()
+ );
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Decompiler → Commit Locals. Persists analyzer-inferred stack locals as
+ /// user edits so a later rename doesn't require re-analyzing.
+ pub fn commit_locals(&mut self, entry: u64) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let locals = {
+ let f = prog
+ .function_at(entry)
+ .ok_or_else(|| format!("no function at {entry:#x}"))?;
+ f.stack_locals.clone()
+ };
+ prog.edits.commit_locals(entry, locals.clone());
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: entry,
+ type_desc: format!("commit locals: {}", locals.len()),
+ },
+ });
+ self.status = format!("Commit Locals @ {entry:#x} ({} local(s))", locals.len());
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Data Type Manager → New Structure / Union / Enum / Typedef / Function Def.
+ pub fn define_user_type(
+ &mut self,
+ name: impl Into<String>,
+ body: impl Into<String>,
+ ) -> Result<(), String> {
+ let name = name.into();
+ let body = body.into();
+ if name.trim().is_empty() {
+ return Err("empty type name".into());
+ }
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ prog.edits.set_user_type(name.clone(), body);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: 0,
+ type_desc: format!("user type: {name}"),
+ },
+ });
+ self.status = format!("New type: {name}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// DTM → Edit an existing user type body (Structure / Union /
+ /// Enum / Typedef editor). May also rename in the same operation.
+ pub fn edit_user_type(
+ &mut self,
+ orig_name: &str,
+ new_name: impl Into<String>,
+ body: impl Into<String>,
+ ) -> Result<(), String> {
+ let new_name = new_name.into();
+ let body = body.into();
+ if new_name.trim().is_empty() {
+ return Err("empty type name".into());
+ }
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ if !prog.edits.user_types.contains_key(orig_name) {
+ return Err(format!("no type named {orig_name}"));
+ }
+ if orig_name != new_name {
+ let _ = prog.edits.rename_user_type(orig_name, &new_name);
+ }
+ prog.edits.set_user_type(new_name.clone(), body);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: 0,
+ type_desc: format!("edit type: {new_name}"),
+ },
+ });
+ self.status = format!("Edited type {new_name}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// DTM → New Typedef on X . Creates a
+ /// typedef whose body records the underlying type; the resulting user
+ /// type can be applied at Listing addresses just like any other.
+ pub fn new_typedef_on(&mut self, source: &str) -> Result<String, String> {
+ let name = format!("typedef_{source}");
+ let body = format!("Typedef\ntypedef {source} {name};");
+ self.define_user_type(&name, body)?;
+ Ok(name)
+ }
+
+ /// DTM → New Pointer to X. Registers a `<X> *` user type so the Listing
+ /// can apply the pointer decoration without a full parser.
+ pub fn new_pointer_to(&mut self, source: &str) -> Result<String, String> {
+ let name = format!("{source} *");
+ let body = format!("Typedef\n{source} *");
+ self.define_user_type(&name, body)?;
+ Ok(name)
+ }
+
+ // ── equates, function tags, xrefs, checksums ──────────
+
+ /// Attach an equate `name` at `(va, op)` for scalar `value` (
+ /// `Convert → Equate`). Empty `name` clears the equate.
+ pub fn set_equate(
+ &mut self,
+ va: u64,
+ op: u8,
+ name: impl Into<String>,
+ value: i64,
+ ) -> Result<(), String> {
+ let name = name.into();
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let clearing = name.is_empty();
+ prog.edits.set_equate(va, op, &name, value);
+ // Equates render inline in the Listing operand slot; treat as retype
+ // for cache invalidation so the Decompiler picks the change up too.
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va,
+ type_desc: if clearing {
+ format!("cleared equate @ op {op}")
+ } else {
+ format!("equate {name} = {value}")
+ },
+ },
+ });
+ self.status = if clearing {
+ format!("Cleared equate @ {va:#x} op {op}")
+ } else {
+ format!("Set equate {name} = {value} @ {va:#x} op {op}")
+ };
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Function Tags — add / remove / delete-everywhere (
+ /// `FunctionTagPlugin`).
+ pub fn add_function_tag(&mut self, entry: u64, tag: impl Into<String>) -> Result<(), String> {
+ let tag = tag.into();
+ if tag.trim().is_empty() {
+ return Err("empty tag".into());
+ }
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ prog.edits.add_function_tag(entry, &tag);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: entry,
+ type_desc: format!("tag+ {tag}"),
+ },
+ });
+ self.status = format!("Tag '{tag}' added to fn @ {entry:#x}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ pub fn remove_function_tag(&mut self, entry: u64, tag: &str) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let removed = prog.edits.remove_function_tag(entry, tag);
+ if !removed {
+ return Err(format!("fn @ {entry:#x} has no tag '{tag}'"));
+ }
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: entry,
+ type_desc: format!("tag- {tag}"),
+ },
+ });
+ self.status = format!("Tag '{tag}' removed from fn @ {entry:#x}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Register a tag in the universe (`ProgramEdits::all_function_tags`)
+ /// without assigning it to a function. "Create tag" action
+ /// lands here.
+ pub fn create_tag(&mut self, tag: impl Into<String>) -> Result<(), String> {
+ let tag = tag.into();
+ if tag.trim().is_empty() {
+ return Err("empty tag".into());
+ }
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ prog.edits.all_function_tags.insert(tag.clone());
+ self.status = format!("Created tag '{tag}'");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Delete a tag from every function and from the universe.
+ pub fn delete_tag_everywhere(&mut self, tag: &str) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let n = prog.edits.delete_tag_everywhere(tag);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: 0,
+ type_desc: format!("tag deleted: {tag}"),
+ },
+ });
+ self.status = format!("Tag '{tag}' deleted from {n} function(s)");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Compute references TO the given target VA. Uses `ghidrust-core::xrefs`
+ /// against the current program + focused-window listing.
+ pub fn xrefs_to_va(&self, target: u64) -> Vec<XRef> {
+ let Some(prog) = self.program.as_ref() else {
+ return Vec::new();
+ };
+ xrefs_to(prog, target, Some(&self.listing))
+ }
+
+ /// Compute references FROM the given source VA.
+ pub fn xrefs_from_va(&self, source: u64) -> Vec<XRef> {
+ let Some(prog) = self.program.as_ref() else {
+ return Vec::new();
+ };
+ xrefs_from(prog, source, STAGE0_MAX_INSNS)
+ }
+
+ /// Compute a checksum panel over the loaded program (or focused block).
+ pub fn compute_checksums(&mut self, mode: ChecksumMode) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_ref()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let (target_label, data): (String, Vec<u8>) = match mode {
+ ChecksumMode::WholeImage => {
+ let bytes: Vec<u8> = prog.blocks.iter().flat_map(|b| b.bytes.clone()).collect();
+ (format!("Whole image ({})", prog.name), bytes)
+ }
+ ChecksumMode::Section(name) => {
+ let b = prog
+ .blocks
+ .iter()
+ .find(|b| b.name == name)
+ .ok_or_else(|| format!("no block named {name}"))?;
+ (format!("Block {name}"), b.bytes.clone())
+ }
+ };
+ let report = report_for(target_label, &data);
+ self.status = format!(
+ "Checksum: crc32={:#010x} adler32={:#010x} len={}",
+ report.crc32, report.adler32, report.len,
+ );
+ self.checksum_last = Some(report);
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Program Tree → Set View / Add To View / Remove From View / Show All.
+ ///
+ /// The semantic is a **fragment name set**. `None` = full view.
+ pub fn set_listing_view(&mut self, fragments: Option<BTreeSet<String>>) {
+ self.listing_view_filter = fragments;
+ }
+
+ pub fn add_to_view(&mut self, fragment: impl Into<String>) {
+ let name = fragment.into();
+ let entry = self.listing_view_filter.get_or_insert_with(BTreeSet::new);
+ entry.insert(name);
+ }
+
+ pub fn remove_from_view(&mut self, fragment: &str) {
+ if let Some(set) = self.listing_view_filter.as_mut() {
+ set.remove(fragment);
+ if set.is_empty() {
+ // Empty view → drop the filter so Listing shows nothing but
+ // reflects an honest empty state driven by fragment membership.
+ }
+ }
+ }
+
+ #[cfg(test)]
+ pub fn clear_view_filter(&mut self) {
+ self.listing_view_filter = None;
+ }
+
+ /// Whether a Listing address is currently in-view (Program Tree filter).
+ #[cfg(test)]
+ pub fn addr_in_view(&self, va: u64) -> bool {
+ let Some(filter) = self.listing_view_filter.as_ref() else {
+ return true;
+ };
+ let Some(prog) = self.program.as_ref() else {
+ return true;
+ };
+ prog.blocks
+ .iter()
+ .filter(|b| filter.contains(&b.name))
+ .any(|b| va >= b.va && va < b.va.saturating_add(b.size))
+ }
+
+ /// Navigation → Next Function.
+ pub fn nav_next_function(&mut self) {
+ let cur = self.listing_focus_va.unwrap_or(0);
+ let entries: Vec<u64> = self
+ .program
+ .as_ref()
+ .map(|p| p.analysis.functions.iter().map(|f| f.entry).collect())
+ .unwrap_or_default();
+ if entries.is_empty() {
+ self.status = "No functions — run Function Start Search".into();
+ self.log_warn(self.status.clone());
+ return;
+ }
+ let mut sorted: Vec<u64> = entries;
+ sorted.sort();
+ if let Some(&va) = sorted.iter().find(|&&e| e > cur) {
+ self.focus_function(va);
+ } else {
+ self.focus_function(sorted[0]);
+ }
+ }
+
+ /// Navigation → Previous Function.
+ pub fn nav_prev_function(&mut self) {
+ let cur = self.listing_focus_va.unwrap_or(u64::MAX);
+ let entries: Vec<u64> = self
+ .program
+ .as_ref()
+ .map(|p| p.analysis.functions.iter().map(|f| f.entry).collect())
+ .unwrap_or_default();
+ if entries.is_empty() {
+ self.status = "No functions — run Function Start Search".into();
+ self.log_warn(self.status.clone());
+ return;
+ }
+ let mut sorted: Vec<u64> = entries;
+ sorted.sort();
+ if let Some(&va) = sorted.iter().rev().find(|&&e| e < cur) {
+ self.focus_function(va);
+ } else {
+ self.focus_function(*sorted.last().unwrap());
+ }
+ }
+
+ /// Program → Symbol Tree lookup: are Imports/Exports parseable from analysis?
+ ///
+ /// Ghidrust's PE loader doesn't yet parse the Import / Export directories, but
+ /// PDB analyzers do populate `Program::analysis.pdb_symbols`. This helper
+ /// returns (imports, exports) as best-effort lists derived from analyzer
+ /// output — never fabricated. Empty lists = analyzer didn't populate.
+ pub fn imports_exports(&self) -> (Vec<(u64, String)>, Vec<(u64, String)>) {
+ let Some(prog) = self.program.as_ref() else {
+ return (Vec::new(), Vec::new());
+ };
+ let mut imports = Vec::new();
+ let mut exports = Vec::new();
+ // Heuristic (source-honest): PDB symbols with `__imp_` prefix are imports.
+ for s in &prog.analysis.pdb_symbols {
+ if s.name.starts_with("__imp_")
+ || s.name.starts_with("_imp_")
+ || s.name.starts_with("__imp")
+ {
+ imports.push((s.va, s.name.clone()));
+ }
+ }
+ // Section-based fallback: sections whose name contains "idata"/"iat" are
+ // import metadata; expose their base as an anchor row.
+ for s in &prog.sections {
+ let n = s.name.to_ascii_lowercase();
+ if n.contains("idata") || n.contains("iat") {
+ imports.push((s.va, format!("{} @ {:#x}", s.name, s.va)));
+ }
+ if n.contains("edata") {
+ exports.push((s.va, format!("{} @ {:#x}", s.name, s.va)));
+ }
+ }
+ // Analysis symbols marked as exports by demangler are entry-like.
+ for s in &prog.analysis.symbols {
+ if s.demangled
+ .as_ref()
+ .map(|d| d.contains("__declspec(dllexport)"))
+ .unwrap_or(false)
+ {
+ exports.push((s.va, s.name.clone()));
+ }
+ }
+ imports.sort_by_key(|(va, _)| *va);
+ imports.dedup_by(|a, b| a.1 == b.1);
+ exports.sort_by_key(|(va, _)| *va);
+ exports.dedup_by(|a, b| a.1 == b.1);
+ (imports, exports)
+ }
+
+ /// drain queued events and fan them out to subscribers.
+ ///
+ /// ProgramMutated invalidates the Decompiler cache. ProgramActivated /
+ /// CursorMoved refresh listing focus status at minimum.
+ pub fn drain_events(&mut self) -> Vec<GhidrustEvent> {
+ let events = self.event_bus.drain();
+ for ev in &events {
+ match ev {
+ GhidrustEvent::ProgramMutated { kind } => match kind {
+ MutationKind::Rename { .. }
+ | MutationKind::Retype { .. }
+ | MutationKind::CommentChanged { .. } => {
+ self.clear_decompiler_cache();
+ }
+ MutationKind::BookmarkAdded { .. } | MutationKind::BookmarkRemoved { .. } => {}
+ },
+ GhidrustEvent::ProgramActivated { name } => {
+ let focus = self.listing_focus_va;
+ self.status = match focus {
+ Some(va) => format!("Program activated: {name} · listing focus {va:#x}"),
+ None => format!("Program activated: {name}"),
+ };
+ self.log(self.status.clone());
+ }
+ GhidrustEvent::CursorMoved { location, .. } => {
+ self.listing_focus_va = Some(location.va);
+ self.status = format!("Listing focus {:#x}", location.va);
+ }
+ }
+ }
+ events
+ }
+
+ pub(crate) fn push_selection_undo(&mut self) {
+ self.undo_stack.push(self.listing_selection);
+ if self.undo_stack.len() > 64 {
+ self.undo_stack.remove(0);
+ }
+ self.redo_stack.clear();
+ }
+
+ /// Edit → Undo (selection history).
+ pub fn edit_undo(&mut self) {
+ if let Some(prev) = self.undo_stack.pop() {
+ self.redo_stack.push(self.listing_selection);
+ self.listing_selection = prev;
+ self.status = "Undo: restored selection".into();
+ self.log(self.status.clone());
+ } else {
+ self.status = "Nothing to undo".into();
+ self.log(self.status.clone());
+ }
+ }
+
+ /// Edit → Redo.
+ pub fn edit_redo(&mut self) {
+ if let Some(next) = self.redo_stack.pop() {
+ self.undo_stack.push(self.listing_selection);
+ self.listing_selection = next;
+ self.status = "Redo: restored selection".into();
+ self.log(self.status.clone());
+ } else {
+ self.status = "Nothing to redo".into();
+ self.log(self.status.clone());
+ }
+ }
+
+ /// Edit → Clear Selection.
+ pub fn edit_clear_selection(&mut self) {
+ self.push_selection_undo();
+ self.listing_selection = ListingSelection::clear();
+ self.status = "Selection cleared".into();
+ self.log(self.status.clone());
+ }
+
+ /// Select → Select All (listing range).
+ pub fn select_all_listing(&mut self) {
+ self.push_selection_undo();
+ self.listing_selection = ListingSelection::all(self.listing.len());
+ self.status = format!("Selected all {} listing instruction(s)", self.listing.len());
+ self.log(self.status.clone());
+ self.focus_center_tab(DockTab::Listing);
+ }
+
+ /// decode arch for name lookup in listing/detail panes.
+ pub(crate) fn listing_arch(&self) -> Arch {
+ self.decode_opts
+ .resolved_arch()
+ .or_else(|| {
+ self.program
+ .as_ref()
+ .and_then(arch_mode_for_program)
+ .map(|(a, _)| a)
+ })
+ .unwrap_or_else(|| default_arch_mode().0)
+ }
+
+ /// Re-disassemble the listing window at `va` using current decode options.
+ pub(crate) fn reload_listing_at(&mut self, va: u64) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_ref()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ self.decode_opts.sync_machine_from_program(prog);
+ self.listing_search.arch = self.listing_arch();
+ let result = reload(prog, va, &self.decode_opts)?;
+ if result.insns.is_empty() {
+ return Err(format!("no instructions at {va:#x}"));
+ }
+ self.listing = result.insns;
+ if let Some(proj) = &self.project {
+ let _ = save_decode_prefs(&proj.root, &self.decode_opts);
+ }
+ Ok(())
+ }
+
+ pub(crate) fn apply_decode_opts(&mut self) {
+ let va = self
+ .listing_focus_va
+ .or_else(|| self.listing.first().map(|i| i.address))
+ .or_else(|| self.program.as_ref().and_then(|p| p.entry))
+ .or_else(|| self.program.as_ref().map(|p| p.image_base));
+ let Some(va) = va else {
+ return;
+ };
+ match self.reload_listing_at(va) {
+ Ok(()) => {
+ self.status = format!("Listing reloaded at {va:#x} ({})", self.listing.len());
+ self.log(self.status.clone());
+ }
+ Err(e) => {
+ self.status = format!("decode reload: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+
+ /// Navigation → Go To Address.
+ /// If `va` is outside the current listing window, re-disassembles 64 insns at `va`.
+ pub fn goto_address_str(&mut self, s: &str) -> Result<(), String> {
+ let va = parse_address(s)?;
+ self.listing_focus_va = Some(va);
+ self.focus_center_tab(DockTab::Listing);
+
+ if let Some(i) = listing_index_at_or_before(&self.listing, va) {
+ self.push_selection_undo();
+ self.listing_selection = ListingSelection {
+ start: Some(i),
+ end: Some(i),
+ };
+ } else {
+ // Outside loaded listing (or empty) — re-disassemble at target VA.
+ let prog = self
+ .program
+ .as_ref()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let l = reload_for_goto(prog, va, &self.decode_opts).map_err(|e| e.to_string())?;
+ if l.is_empty() {
+ return Err(format!("no instructions at {va:#x}"));
+ }
+ self.listing = l;
+ self.push_selection_undo();
+ self.listing_selection = ListingSelection {
+ start: Some(0),
+ end: Some(0),
+ };
+ }
+
+ if !self.nav_suspended {
+ self.nav_history.push(NavLocation::new(va));
+ }
+ self.event_bus.publish(GhidrustEvent::CursorMoved {
+ source: EventSource::Navigation,
+ location: NavLocation::new(va),
+ });
+ // Cross-highlight Decompiler line matching the new listing cursor.
+ if !self.decomp_lines.is_empty() {
+ self.decomp_cross_line = decomp_line_for_va(&self.decomp_lines, va);
+ }
+ // Selection Navigation: keep the "current function" in sync with the
+ // cursor so the Symbol Tree can highlight the enclosing function.
+ if self.symbol_tree_nav {
+ if let Some(prog) = self.program.as_ref() {
+ self.focused_function_entry = prog
+ .analysis
+ .functions
+ .iter()
+ .filter(|f| f.entry <= va && (f.end == 0 || va < f.end))
+ .max_by_key(|f| f.entry)
+ .map(|f| f.entry);
+ }
+ }
+
+ self.status = format!("Go to {va:#x}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Navigation → Go To entry.
+ pub fn goto_entry(&mut self) {
+ 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}"));
+ return;
+ }
+ }
+ self.status = "No entry point".into();
+ self.log(self.status.clone());
+ }
+
+ /// Search → Memory.
+ pub fn run_search_memory(&mut self) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_ref()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let pat = parse_hex_pattern(&self.search_memory_input)?;
+ self.memory_hits = search_memory(prog, &pat, 500);
+ self.text_hits.clear();
+ self.show_search_results = true;
+ self.last_search_kind = Some(SearchKind::Memory);
+ self.status = format!(
+ "Memory search: {} hit(s) for '{}'",
+ self.memory_hits.len(),
+ self.search_memory_input.trim()
+ );
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Search → For Scalars.
+ pub fn run_search_scalars(&mut self) -> Result<(), String> {
+ let min = self
+ .parse_scalar_input(&self.search_scalars_min.clone())
+ .map_err(|e| format!("min: {e}"))?;
+ let max = self
+ .parse_scalar_input(&self.search_scalars_max.clone())
+ .map_err(|e| format!("max: {e}"))?;
+ if min > max {
+ return Err("min > max".into());
+ }
+ self.text_hits = search_scalars(&self.listing, min, max, 1000);
+ self.memory_hits.clear();
+ self.show_search_results = true;
+ self.last_search_kind = Some(SearchKind::Scalars);
+ self.status = format!(
+ "Scalar search [{min}, {max}]: {} hit(s)",
+ self.text_hits.len()
+ );
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ pub(crate) fn parse_scalar_input(&self, s: &str) -> Result<i64, String> {
+ let t = s.trim();
+ if t.is_empty() {
+ return Err("empty".into());
+ }
+ let (sign, rest) = if let Some(r) = t.strip_prefix('-') {
+ (-1i64, r)
+ } else {
+ (1i64, t)
+ };
+ // `0x…` prefix wins → hex. Otherwise prefer decimal to preserve
+ // convention (numeric input without a prefix is decimal).
+ let (base, digits) =
+ if let Some(r) = rest.strip_prefix("0x").or_else(|| rest.strip_prefix("0X")) {
+ (16u32, r)
+ } else {
+ (10u32, rest)
+ };
+ let mag = u64::from_str_radix(digits, base).map_err(|e| e.to_string())?;
+ Ok(sign * mag as i64)
+ }
+
+ /// Search → Instruction Patterns.
+ pub fn run_search_instruction_patterns(&mut self) -> Result<(), String> {
+ if self.listing.is_empty() {
+ return Err("no listing loaded".into());
+ }
+ self.text_hits = search_instruction_patterns(
+ &self.listing,
+ &self.search_insn_mnemonic,
+ &self.search_insn_operands,
+ 1000,
+ );
+ self.memory_hits.clear();
+ self.show_search_results = true;
+ self.last_search_kind = Some(SearchKind::Instructions);
+ self.status = format!(
+ "Instruction pattern hits: {} for `{} {}`",
+ self.text_hits.len(),
+ self.search_insn_mnemonic.trim(),
+ self.search_insn_operands.trim(),
+ );
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Search → Program Text.
+ pub fn run_search_text(&mut self) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_ref()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ self.text_hits = search_program_text(
+ prog,
+ &self.listing,
+ &self.search_text_input,
+ self.search_text_case_insensitive,
+ 500,
+ );
+ self.memory_hits.clear();
+ self.show_search_results = true;
+ self.last_search_kind = Some(SearchKind::Text);
+ self.status = format!(
+ "Text search: {} hit(s) for '{}'",
+ self.text_hits.len(),
+ self.search_text_input.trim()
+ );
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ pub(crate) fn repeat_search(&mut self) {
+ let result = match self.last_search_kind {
+ Some(SearchKind::Memory) => self.run_search_memory(),
+ Some(SearchKind::Scalars) => self.run_search_scalars(),
+ Some(SearchKind::Instructions) => self.run_search_instruction_patterns(),
+ Some(SearchKind::Text) => self.run_search_text(),
+ None => Err("No completed search to repeat".into()),
+ };
+ if let Err(e) = result {
+ self.status = format!("Search: {e}");
+ self.log_warn(self.status.clone());
+ }
+ }
+
+ pub(crate) fn export_listing(&mut self) -> Result<(), String> {
+ let path = rfd::FileDialog::new()
+ .set_title("Export listing")
+ .set_file_name("ghidrust-listing.txt")
+ .save_file()
+ .ok_or_else(|| "Export cancelled".to_string())?;
+ let mut out = String::new();
+ for insn in &self.listing {
+ out.push_str(&format!("{:#010x} {}\n", insn.address, insn.text()));
+ }
+ std::fs::write(&path, out).map_err(|e| e.to_string())?;
+ self.status = format!("Exported listing to {}", path.display());
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ pub(crate) fn print_listing(&mut self) -> Result<(), String> {
+ let path = std::env::temp_dir().join("ghidrust-listing.html");
+ let body = self
+ .listing
+ .iter()
+ .map(|i| format!("{:#010x} {}", i.address, i.text()))
+ .collect::<Vec<_>>()
+ .join("\n");
+ std::fs::write(&path, format!("<html><body><pre>{body}</pre></body></html>"))
+ .map_err(|e| e.to_string())?;
+ #[cfg(target_os = "windows")]
+ std::process::Command::new("cmd")
+ .args(["/C", "start", "", &path.display().to_string()])
+ .spawn()
+ .map_err(|e| e.to_string())?;
+ self.status = format!("Opened printable listing {}", path.display());
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ pub(crate) fn direct_references(&mut self) {
+ let Some(va) = self.listing_focus_va else {
+ self.status = "Select a listing address first".into();
+ self.log_warn(self.status.clone());
+ return;
+ };
+ self.text_hits = self
+ .xrefs_to_va(va)
+ .into_iter()
+ .map(|x| TextHit { kind: "xref", va: Some(x.from), text: format!("{:#x} → {:#x}", x.from, x.to) })
+ .collect();
+ self.memory_hits.clear();
+ self.show_search_results = true;
+ self.status = format!("{} direct reference(s) to {va:#x}", self.text_hits.len());
+ self.log(self.status.clone());
+ }
+
+ pub(crate) fn navigate_next_listing(&mut self, undefined_only: bool) {
+ let current = self.listing_focus_va.unwrap_or(0);
+ let next = self.listing.iter().find(|i| {
+ i.address > current && (!undefined_only || i.mnemonic.eq_ignore_ascii_case("db"))
+ }).map(|i| i.address);
+ if let Some(va) = next {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ } else {
+ self.status = if undefined_only { "No next undefined byte in listing" } else { "No next data item in listing" }.into();
+ self.log_warn(self.status.clone());
+ }
+ }
+
+ pub(crate) fn select_focus_range(&mut self, label: &str) {
+ let Some(va) = self.listing_focus_va else { self.status = "Select a listing address first".into(); return; };
+ let index = listing_index_at_or_before(&self.listing, va).unwrap_or(0);
+ self.push_selection_undo();
+ self.listing_selection = ListingSelection { start: Some(index), end: Some(index) };
+ self.status = format!("Selected {label} at {va:#x}");
+ self.log(self.status.clone());
+ }
+
+ pub(crate) fn select_xrefs(&mut self, forward: bool) {
+ let Some(va) = self.listing_focus_va else { self.status = "Select a listing address first".into(); return; };
+ let refs = if forward { self.xrefs_from_va(va) } else { self.xrefs_to_va(va) };
+ self.text_hits = refs.iter().map(|r| TextHit {
+ kind: "xref", va: Some(if forward { r.to } else { r.from }),
+ text: format!("{:#x} {} {:#x}", r.from, r.kind, r.to),
+ }).collect();
+ self.show_search_results = true;
+ self.status = format!("{} {} reference(s)", self.text_hits.len(), if forward { "forward" } else { "backward" });
+ self.log(self.status.clone());
+ }
+
+ pub(crate) fn rebuild_rtti_filter_cache(&mut self) {
+ let q = self.rtti_filter.to_ascii_lowercase();
+ if q == self.rtti_filter_cache && !self.rtti_filtered_idx.is_empty() {
+ return;
+ }
+ self.rtti_filter_cache = q.clone();
+ if q.is_empty() {
+ self.rtti_filtered_idx = (0..self.rtti.classes.len()).collect();
+ } else {
+ self.rtti_filtered_idx = self
+ .rtti
+ .classes
+ .iter()
+ .enumerate()
+ .filter(|(_, c)| c.name.to_ascii_lowercase().contains(&q))
+ .map(|(i, _)| i)
+ .collect();
+ }
+ }
+
+ pub(crate) fn analysis_summary_line(&self) -> String {
+ let fns = self
+ .program
+ .as_ref()
+ .map(|p| p.analysis.functions.len())
+ .unwrap_or(0);
+ let rtti_n = self.rtti.classes.len();
+ let str_n = self.strings.len();
+ let list_n = self.listing.len();
+ format!("{fns} functions · {rtti_n} RTTI · {str_n} strings · {list_n} listing lines")
+ }
+
+ pub(crate) fn browse_binary_path(&mut self) {
+ if let Some(path) = rfd::FileDialog::new()
+ .set_title("Open binary (PE / ELF)")
+ .add_filter("Binaries", &["exe", "dll", "sys", "pe", "elf", "so", "bin"])
+ .add_filter("All files", &["*"])
+ .pick_file()
+ {
+ self.path_input = path.display().to_string();
+ self.log(format!("Browsed binary: {}", self.path_input));
+ }
+ }
+
+ /// Request delete with confirmation (does not delete yet).
+ pub fn request_delete_file(&mut self, id: &str) {
+ let name = self
+ .project
+ .as_ref()
+ .and_then(|p| p.meta.files.iter().find(|f| f.id == id))
+ .map(|f| f.display_name.clone())
+ .unwrap_or_else(|| id.to_string());
+ self.pending_delete = Some((id.to_string(), name));
+ }
+
+ /// Resolve color tokens for the active appearance + mode.
+ pub fn tokens(&self) -> ghidrust_core::M3Tokens {
+ crate::theme::tokens(self.appearance, self.theme)
+ }
+
+ pub fn apply_theme(&self, ctx: &egui::Context) {
+ crate::theme::apply(ctx, self.appearance, self.theme)
+ }
+
+ pub(crate) fn log(&mut self, msg: impl Into<String>) {
+ self.log_with(msg, ConsoleSeverity::Info);
+ }
+
+ /// Console warning (amber tint).
+ pub(crate) fn log_warn(&mut self, msg: impl Into<String>) {
+ self.log_with(msg, ConsoleSeverity::Warn);
+ }
+
+ /// Console error (red tint).
+ pub(crate) fn log_error(&mut self, msg: impl Into<String>) {
+ self.log_with(msg, ConsoleSeverity::Error);
+ }
+
+ pub(crate) fn log_with(&mut self, msg: impl Into<String>, sev: ConsoleSeverity) {
+ let text = msg.into();
+ self.console.push(text);
+ self.console_severity.push(sev);
+ // Keep both vectors in lockstep and bounded.
+ if self.console.len() > 200 {
+ let drop = self.console.len() - 200;
+ self.console.drain(0..drop);
+ self.console_severity.drain(0..drop);
+ }
+ // Backfill severity vector if it drifts (only happens if callers used
+ // `self.console.push` directly; guard against future regressions).
+ while self.console_severity.len() < self.console.len() {
+ self.console_severity.push(ConsoleSeverity::Info);
+ }
+ }
+
+ /// Render the bottom-dock tabbed panel — `Grok` (embedded TUI) + `Console`.
+ pub(crate) fn render_bottom_dock(&mut self, ui: &mut egui::Ui) {
+ use crate::agent_pane::BottomTab;
+ ui.horizontal(|ui| {
+ let grok_selected = self.grok_pane.tab == BottomTab::Grok;
+ let console_selected = self.grok_pane.tab == BottomTab::Console;
+ if ui.selectable_label(grok_selected, "Grok").clicked() {
+ self.grok_pane.tab = BottomTab::Grok;
+ }
+ if ui.selectable_label(console_selected, "Console").clicked() {
+ self.grok_pane.tab = BottomTab::Console;
+ }
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if self.grok_pane.tab == BottomTab::Console && ui.small_button("Clear").clicked() {
+ self.console.clear();
+ self.console_severity.clear();
+ }
+ ui.small(egui::RichText::new("drag top edge ↕").weak().small());
+ });
+ });
+ ui.separator();
+ match self.grok_pane.tab {
+ BottomTab::Grok => self.render_grok_tab(ui),
+ BottomTab::Console => {
+ // Leaving the TUI — release keyboard so listing hotkeys work again.
+ self.grok_pane.keyboard_captured = false;
+ self.render_console_tab(ui);
+ }
+ }
+ }
+
+ pub(crate) fn render_console_tab(&mut self, ui: &mut egui::Ui) {
+ egui::ScrollArea::vertical()
+ .auto_shrink([false, false])
+ .stick_to_bottom(true)
+ .show(ui, |ui| {
+ let n = self.console.len();
+ for i in 0..n {
+ let sev = self
+ .console_severity
+ .get(i)
+ .copied()
+ .unwrap_or(ConsoleSeverity::Info);
+ let color = match sev {
+ ConsoleSeverity::Info => ui.visuals().text_color(),
+ ConsoleSeverity::Warn => Color32::from_rgb(0xFB, 0xC0, 0x2D),
+ ConsoleSeverity::Error => Color32::from_rgb(0xE5, 0x39, 0x35),
+ };
+ let prefix = match sev {
+ ConsoleSeverity::Info => " ",
+ ConsoleSeverity::Warn => "! ",
+ ConsoleSeverity::Error => "× ",
+ };
+ ui.label(
+ egui::RichText::new(format!("{prefix}{}", self.console[i]))
+ .monospace()
+ .color(color),
+ );
+ }
+ });
+ }
+
+ pub(crate) fn render_grok_tab(&mut self, ui: &mut egui::Ui) {
+ let t = self.tokens();
+ let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
+ let muted = Color32::from_rgb(
+ t.on_surface_variant[0],
+ t.on_surface_variant[1],
+ t.on_surface_variant[2],
+ );
+
+ let ctx = ui.ctx().clone();
+ let mut start_err: Option<String> = None;
+ let mut do_install = false;
+ let mut do_rescan = false;
+ let mut do_probe = false;
+ let mut start_size: Option<(u16, u16)> = None;
+
+ 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()),
+ };
+ crate::agent_pane::render_grok_pane(
+ ui,
+ &mut self.grok_pane,
+ checklist_root.as_deref(),
+ primary,
+ muted,
+ &mut |cols, rows| {
+ start_size = Some((cols, rows));
+ Ok(())
+ },
+ &mut || do_install = true,
+ &mut || do_rescan = true,
+ &mut || do_probe = true,
+ );
+
+ if do_install {
+ let status = crate::agent_pane::spawn_install_grok();
+ self.log(status.clone());
+ self.grok_pane.install_status = Some(status);
+ }
+ if do_rescan {
+ self.grok_pane.refresh_grok_binary();
+ let msg = match &self.grok_pane.grok_bin {
+ Some(p) => format!("Found grok at {}", p.display()),
+ None => "grok not found on PATH — install first".into(),
+ };
+ self.log(msg);
+ }
+ if do_probe {
+ if let Some(bin) = self.grok_pane.grok_bin.clone() {
+ match ghidrust_agent::probe_grok_version(&bin) {
+ Ok(v) => {
+ self.log(format!("grok -version → {v}"));
+ self.grok_pane.version_probe = Some(v);
+ }
+ Err(e) => {
+ self.grok_pane.version_probe = Some(format!("(error) {e}"));
+ self.log_warn(format!("grok -version failed: {e}"));
+ }
+ }
+ }
+ }
+ if let Some((cols, rows)) = start_size {
+ if let Err(e) = self.start_grok_pty(cols, rows, ctx) {
+ start_err = Some(e);
+ }
+ }
+ if let Some(e) = start_err {
+ self.grok_pane.last_error = Some(e.clone());
+ self.log_error(format!("Grok TUI failed: {e}"));
+ }
+ }
+
+ /// Build the current program-facts snapshot for the Grok pane.
+ ///
+ /// This is what makes the agent actually *know* about the open project
+ /// and the currently-loaded file without needing an MCP round-trip first.
+ /// Every field is honest-empty when the underlying analysis hasn't run —
+ /// matches Ghidrust's "no fabrication on empty evidence" rule.
+ pub(crate) fn grok_program_facts(&self) -> ghidrust_agent::ProgramFacts {
+ const TOP_FN_SAMPLE: usize = 24;
+ const IMPORT_SAMPLE: usize = 24;
+
+ let mut f = ghidrust_agent::ProgramFacts::default();
+ if let Some(proj) = &self.project {
+ f.project_name = Some(proj.meta.name.clone());
+ f.project_root = Some(proj.root.display().to_string());
+ for file in &proj.meta.files {
+ let has_saved = proj.results_dir().join(&file.id).exists()
+ || proj.results_dir().join(format!("{}.bin", file.id)).exists();
+ f.project_files.push(ghidrust_agent::ProjectFileFact {
+ id: file.id.clone(),
+ display_name: file.display_name.clone(),
+ has_saved_analysis: has_saved,
+ });
+ }
+ }
+ f.active_file_id = self.active_file_id.clone();
+ if let Some(prog) = &self.program {
+ f.program = Some(prog.name.clone());
+ f.format = Some(prog.format.clone());
+ f.arch = Some("x86_64".into());
+ f.image_base = Some(format!("{:#x}", prog.image_base));
+ f.entry_va = prog.entry.map(|v| format!("{v:#x}"));
+ f.functions = Some(prog.analysis.functions.len());
+ f.strings = Some(self.strings.len());
+ for s in &prog.sections {
+ f.sections.push(ghidrust_agent::SectionFact {
+ name: s.name.clone(),
+ va: format!("{:#x}", s.va),
+ size: s.virtual_size,
+ });
+ }
+ for fi in prog.analysis.functions.iter().take(TOP_FN_SAMPLE) {
+ f.top_functions.push(ghidrust_agent::FunctionFact {
+ va: format!("{:#x}", fi.entry),
+ name: fi.name.clone(),
+ });
+ }
+ for imp in prog.imports.iter().take(IMPORT_SAMPLE) {
+ if let Some(name) = &imp.name {
+ f.imports_sample.push(ghidrust_agent::ImportFact {
+ dll: imp.dll.clone(),
+ name: name.clone(),
+ });
+ }
+ }
+ }
+ f.analyzers_run = self.last_analyzers_run.clone();
+ if let Some(va) = self.listing_focus_va {
+ let name = self
+ .program
+ .as_ref()
+ .and_then(|p| p.display_function_name_at(va));
+ f.current_selection = Some(ghidrust_agent::SelectionFact {
+ va: format!("{va:#x}"),
+ name,
+ });
+ }
+ f
+ }
+
+ /// Write MCP/skill/context and spawn the real Grok TUI in the PTY pane.
+ pub(crate) fn start_grok_pty(&mut self, cols: u16, rows: u16, ctx: egui::Context) -> Result<(), String> {
+ self.grok_pane.last_error = None;
+ let bin = self.grok_pane.grok_bin.clone().ok_or_else(|| {
+ "grok binary not installed — click 'Install Grok Build…' first".to_string()
+ })?;
+ let project_root: std::path::PathBuf = match &self.project {
+ Some(p) => p.root.clone(),
+ None => std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")),
+ };
+ let ghidrust_bin = ghidrust_agent::resolve_ghidrust_cli_bin().ok_or_else(|| {
+ "ghidrust CLI not found next to the GUI or on PATH — build `ghidrust` \
+ (cargo build -p ghidrust-cli -release) so MCP can start"
+ .to_string()
+ })?;
+ if !ghidrust_bin.is_file() {
+ return Err(format!(
+ "ghidrust CLI missing at {} — MCP cannot start",
+ ghidrust_bin.display()
+ ));
+ }
+ let (_skill_body, skill_source) = load_skill_body();
+ let facts = self.grok_program_facts();
+ // Drop any prior session before spawning a new one.
+ self.grok_pane.session = None;
+ let session = crate::agent_pane::start_pty_session(
+ &bin,
+ &project_root,
+ &ghidrust_bin,
+ skill_source.as_deref(),
+ &facts,
+ ctx,
+ cols,
+ rows,
+ )?;
+ self.log(format!(
+ "Grok TUI started · project={} · grok={} · mcp={}",
+ project_root.display(),
+ bin.display(),
+ ghidrust_bin.display()
+ ));
+ self.grok_pane.session = Some(session);
+ self.grok_pane.status = None;
+ self.grok_pane.request_term_focus = true;
+ self.grok_pane.keyboard_captured = true;
+ Ok(())
+ }
+
+ /// 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).
+ pub(crate) 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(crate::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).
+ ///
+ /// top-level menus (from `docking.tool.ToolConstants`):
+ /// File, Edit, Analysis, Navigation, Search, Select, Tools, Graph, Window, Help.
+ #[cfg(test)]
+ pub fn shell_menus() -> &'static [&'static str] {
+ &[
+ "File",
+ "Edit",
+ "Analysis",
+ "Navigation",
+ "Search",
+ "Select",
+ "Tools",
+ "Graph",
+ "Window",
+ "Debugger",
+ "Network",
+ "Help",
+ ]
+ }
+
+ /// Every provider ( + off-layout) enumerated for visibility tests.
+ ///
+ /// Ghidrust panes use these exact labels for the Window menu and the structural test.
+ /// See `crate::panes::PaneKind::ALL` for the source of truth; a stable Vec is materialized
+ /// on demand to keep the API `&'static [&'static str]`-like for existing tests.
+ #[cfg(test)]
+ pub fn shell_panes() -> Vec<&'static str> {
+ // Legacy names kept for backwards compat with previous test assertions.
+ let mut names: Vec<&'static str> = vec![
+ "Project Tree",
+ "Program Tree", // legacy short name .
+ "Symbol Tree",
+ "Overview",
+ "Listing",
+ "Decompiler", // legacy short name .
+ "Data Type Manager",
+ "Console",
+ ];
+ for k in PaneKind::ALL {
+ let t = k.title();
+ if !names.contains(&t) {
+ names.push(t);
+ }
+ }
+ // Single tabbed Debugger host .
+ if !names.contains(&"Debugger") {
+ names.push("Debugger");
+ }
+ // Single tabbed Network (Ghidnet) host .
+ if !names.contains(&"Network") {
+ names.push("Network");
+ }
+ names
+ }
+}
diff --git a/crates/ghidrust-gui/src/app/shell_chrome.rs b/crates/ghidrust-gui/src/app/shell_chrome.rs
new file mode 100644
index 0000000..ccbc804
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/shell_chrome.rs
@@ -0,0 +1,284 @@
+//! Shell chrome — nav toolbar, main toolbar, status bar.
+//!
+//! Extracted per demonolith Wave 3. Nested under `app` for private field access.
+
+use super::GhidrustApp;
+use crate::icons::m3_linear_progress;
+use crate::panes::{BookmarkKind, PaneKind};
+use eframe::egui::{self, Color32};
+
+impl GhidrustApp {
+ /// Draw nav toolbar, main toolbar, and status bar panels.
+ pub(crate) fn draw_shell_chrome(&mut self, ctx: &egui::Context) {
+ egui::TopBottomPanel::top("nav_toolbar").show(ctx, |ui| {
+ ui.horizontal(|ui| {
+ let back_enabled = self.can_nav_back();
+ let fwd_enabled = self.can_nav_forward();
+ if ui
+ .add_enabled(back_enabled, egui::Button::new("<- Back"))
+ .on_hover_text("Navigation → Back (Alt+Left)")
+ .clicked()
+ {
+ self.nav_back();
+ }
+ if ui
+ .add_enabled(fwd_enabled, egui::Button::new("Forward ->"))
+ .on_hover_text("Navigation → Forward (Alt+Right)")
+ .clicked()
+ {
+ self.nav_forward();
+ }
+ ui.separator();
+ if ui
+ .button("Go To…")
+ .on_hover_text("Navigation → Go To Address (G)")
+ .clicked()
+ {
+ if let Some(prog) = &self.program {
+ if let Some(e) = prog.entry {
+ self.goto_input = format!("{e:#x}");
+ } else {
+ self.goto_input = format!("{:#x}", prog.image_base);
+ }
+ }
+ self.show_goto_dialog = true;
+ }
+ ui.separator();
+ if ui
+ .button("Bookmark…")
+ .on_hover_text("Add bookmark at cursor VA")
+ .clicked()
+ {
+ if let Some(va) = self.listing_focus_va {
+ self.bookmark_dialog_kind = BookmarkKind::Note;
+ self.bookmark_dialog_category = String::new();
+ self.bookmark_dialog_description = format!("bookmark @ {va:#x}");
+ self.show_bookmark_dialog = true;
+ } else {
+ self.status = "No cursor VA — click a Listing line first".into();
+ self.log(self.status.clone());
+ }
+ }
+ if ui
+ .button("Bookmarks")
+ .on_hover_text("Window → Bookmarks")
+ .clicked()
+ {
+ self.pane_open.insert(PaneKind::Bookmarks, true);
+ }
+ if ui
+ .button("Functions")
+ .on_hover_text("Window → Functions")
+ .clicked()
+ {
+ self.pane_open.insert(PaneKind::FunctionsWindow, true);
+ }
+ if ui
+ .button("Memory Map")
+ .on_hover_text("Window → Memory Map")
+ .clicked()
+ {
+ self.pane_open.insert(PaneKind::MemoryMap, true);
+ }
+ if ui
+ .button("Symbol Table")
+ .on_hover_text("Window → Symbol Table")
+ .clicked()
+ {
+ self.pane_open.insert(PaneKind::SymbolTable, true);
+ }
+ ui.separator();
+ let hist = format!(
+ "Back: {} · Forward: {}",
+ self.nav_history.len_back(),
+ self.nav_history.len_forward()
+ );
+ ui.small(hist);
+ });
+ });
+
+ egui::TopBottomPanel::top("toolbar").show(ctx, |ui| {
+ ui.horizontal(|ui| {
+ ui.label("Project dir:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.project_dir_input)
+ .desired_width(240.0)
+ .hint_text("folder for New/Open project"),
+ );
+ if ui
+ .button("Browse…")
+ .on_hover_text("Choose project folder")
+ .clicked()
+ {
+ self.browse_project_dir();
+ }
+ ui.label("Name:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.project_name_input).desired_width(100.0),
+ );
+ if ui
+ .button("New")
+ .on_hover_text("Create project (browse if dir empty)")
+ .clicked()
+ {
+ if self.project_dir_input.trim().is_empty() {
+ self.browse_and_create_project();
+ } else if let Err(e) = self.create_project() {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ if ui
+ .button("Open")
+ .on_hover_text("Open project (browse if dir empty)")
+ .clicked()
+ {
+ if self.project_dir_input.trim().is_empty() {
+ self.browse_and_open_project();
+ } else if let Err(e) = self.open_project() {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("Binary:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.path_input)
+ .desired_width(320.0)
+ .hint_text("PE/ELF — or use Browse"),
+ );
+ if ui
+ .button("Browse…")
+ .on_hover_text("Choose binary file")
+ .clicked()
+ {
+ self.browse_binary_path();
+ }
+ if ui
+ .button("Import")
+ .on_hover_text("Import into project (browse if empty)")
+ .clicked()
+ {
+ if self.path_input.trim().is_empty() {
+ self.browse_and_import();
+ } else if let Err(e) = self.import_into_project() {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ if ui
+ .button("Load")
+ .on_hover_text("Load binary without project (browse if empty)")
+ .clicked()
+ {
+ if self.path_input.trim().is_empty() {
+ self.browse_and_load_binary();
+ } else {
+ let p = self.path_input.clone();
+ if let Err(e) = self.load_binary(p) {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+ if ui
+ .button("Analyze…")
+ .on_hover_text("Open analysis options (analyzers + GPU)")
+ .clicked()
+ {
+ self.pending_analyze_file_id = self.active_file_id.clone();
+ self.show_analysis_dialog = true;
+ }
+ if ui.button("Save").clicked() {
+ if let Err(e) = self.save_results() {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ });
+ let file_chips: Vec<(String, String, String)> = self
+ .project
+ .as_ref()
+ .map(|p| {
+ let pname = p.meta.name.clone();
+ let files = p
+ .meta
+ .files
+ .iter()
+ .map(|f| (f.id.clone(), f.display_name.clone()))
+ .collect::<Vec<_>>();
+ files
+ .into_iter()
+ .map(|(id, name)| (pname.clone(), id, name))
+ .collect()
+ })
+ .unwrap_or_default();
+ if !file_chips.is_empty() {
+ let pname = file_chips[0].0.clone();
+ ui.horizontal(|ui| {
+ ui.label(format!("Open: {pname} | files:"));
+ for (_, id, name) in &file_chips {
+ let selected = self.active_file_id.as_deref() == Some(id.as_str());
+ if ui.selectable_label(selected, name).clicked() {
+ if let Err(e) = self.open_project_file(id) {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+ });
+ }
+ });
+
+ egui::TopBottomPanel::bottom("status").show(ctx, |ui| {
+ if let Some(frac) = self.analysis_progress_fraction() {
+ let t = self.tokens();
+ let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
+ let track = Color32::from_rgb(
+ t.surface_container[0],
+ t.surface_container[1],
+ t.surface_container[2],
+ )
+ .gamma_multiply(1.4);
+ let (label, pct) = self
+ .analysis_job
+ .as_ref()
+ .map(|j| {
+ let n = j.names.len().max(1);
+ let cur = j
+ .names
+ .get(j.index)
+ .cloned()
+ .unwrap_or_else(|| "finishing…".into());
+ (
+ format!(
+ "Analyzing {} — {}/{} {cur}{}",
+ j.file_label,
+ (j.index + 1).min(n),
+ n,
+ if j.use_gpu {
+ " · GPU experimental"
+ } else {
+ ""
+ }
+ ),
+ (frac * 100.0) as u32,
+ )
+ })
+ .unwrap_or_else(|| ("Analyzing…".into(), 0));
+ ui.label(egui::RichText::new(label).color(primary));
+ m3_linear_progress(ui, frac, primary, track);
+ ui.small(format!("{pct}%"));
+ } else {
+ ui.horizontal(|ui| {
+ ui.label(&self.status);
+ if let Some(n) = &self.nyi_note {
+ ui.separator();
+ ui.weak(n);
+ }
+ });
+ }
+ });
+ }
+}
diff --git a/crates/ghidrust-gui/src/app/side_trees.rs b/crates/ghidrust-gui/src/app/side_trees.rs
new file mode 100644
index 0000000..c249ea7
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/side_trees.rs
@@ -0,0 +1,814 @@
+//! Project / Program / Symbol tree side panels.
+//!
+//! Extracted per demonolith Wave 3.
+
+use super::GhidrustApp;
+use crate::icons::{m3_icon, status_badge, M3Icon};
+use crate::panes::PaneKind;
+use eframe::egui::{self, Color32};
+use std::collections::{BTreeMap, BTreeSet};
+
+impl GhidrustApp {
+ /// Draw left/right tree side panels.
+ pub(crate) fn draw_side_trees(&mut self, ctx: &egui::Context) {
+
+ // Project Window–style dock: Project → binaries (upgraded badges + actions)
+ if self.show_project_tree {
+ egui::SidePanel::left("project_tree")
+ .resizable(true)
+ .default_width(240.0)
+ .show(ctx, |ui| {
+ ui.heading("Project");
+ ui.small(
+ egui::RichText::new(
+ "Click = select · Double-click / Open = load into main view · Analyze = options",
+ )
+ .weak(),
+ );
+ ui.separator();
+ if self.project.is_none() {
+ ui.weak("No project open.");
+ ui.label("New/Open a project, then Import binaries.");
+ } else {
+ let model = self.project_tree_model().unwrap();
+ let t = self.tokens();
+ let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
+ let muted = Color32::from_rgb(
+ t.on_surface_variant[0],
+ t.on_surface_variant[1],
+ t.on_surface_variant[2],
+ );
+ let ok_green = Color32::from_rgb(0x4C, 0xAF, 0x50);
+ 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.");
+ }
+ 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);
+ }
+ (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(id) = select_id {
+ self.tree_selected_id = Some(id);
+ }
+ if let Some(id) = delete_id {
+ self.request_delete_file(&id);
+ } else if let Some(id) = analyze_id {
+ if let Err(e) = self.analyze_from_tree(&id) {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ } else if let Some(id) = open_id {
+ if let Err(e) = self.open_from_tree(&id) {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+ self.project_tree_expanded = expanded;
+ }
+ });
+ }
+
+ // Delete confirmation modal
+ if let Some((ref id, ref name)) = self.pending_delete.clone() {
+ let id = id.clone();
+ let name = name.clone();
+ egui::Window::new("Delete from project?")
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.label(format!(
+ "Remove \"{name}\" from this project?\n\n\
+ Deletes the imported copy and saved analysis for this file.\n\
+ This cannot be undone."
+ ));
+ ui.add_space(8.0);
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ self.cancel_delete_file();
+ }
+ if ui
+ .button(
+ egui::RichText::new("Delete")
+ .color(Color32::from_rgb(0xB3, 0x26, 0x1E)),
+ )
+ .clicked()
+ {
+ let _ = id;
+ if let Err(e) = self.confirm_delete_file() {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ });
+ });
+ }
+
+ if self.show_program_tree {
+ egui::SidePanel::left("program_tree")
+ .resizable(true)
+ .default_width(220.0)
+ .show(ctx, |ui| {
+ ui.heading("Program Trees");
+ ui.small(egui::RichText::new("ProgramTreePlugin · modules/fragments").weak());
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ // Snapshot everything we need before mutable use later.
+ let root_name = prog.name.clone();
+ let entry = prog.entry;
+ let image_base = prog.image_base;
+ let blocks: Vec<(String, u64, u64, bool, bool, bool)> = prog
+ .blocks
+ .iter()
+ .map(|b| {
+ (
+ b.name.clone(),
+ b.va,
+ b.size,
+ b.readable,
+ b.writable,
+ b.executable,
+ )
+ })
+ .collect();
+
+ ui.horizontal(|ui| {
+ let primary = Color32::from_rgb(
+ self.tokens().primary[0],
+ self.tokens().primary[1],
+ self.tokens().primary[2],
+ );
+ m3_icon(ui, M3Icon::Folder, 16.0, primary);
+ ui.strong(&root_name);
+ });
+ ui.small(
+ egui::RichText::new(format!(
+ "image base {image_base:#x}{}",
+ entry
+ .map(|e| format!(" · entry {e:#x}"))
+ .unwrap_or_default()
+ ))
+ .weak(),
+ );
+
+ // Group blocks into modules by permissions.
+ // Module: "Code" (executable), "Data" (writable, non-exec), "RO Data" (else).
+ let mut code: Vec<usize> = Vec::new();
+ let mut data: Vec<usize> = Vec::new();
+ let mut rodata: Vec<usize> = Vec::new();
+ for (i, (_, _, _, _, w, x)) in blocks.iter().enumerate() {
+ if *x {
+ code.push(i);
+ } else if *w {
+ data.push(i);
+ } else {
+ rodata.push(i);
+ }
+ }
+
+ let mut goto: Option<u64> = None;
+ 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]| {
+ egui::CollapsingHeader::new(format!("{title} ({})", indices.len()))
+ .default_open(!indices.is_empty() && indices.len() <= 32)
+ .show(ui, |ui| {
+ if indices.is_empty() {
+ ui.weak("(empty module)");
+ return;
+ }
+ for &i in indices {
+ let (name, va, size, r, w, x) = &blocks[i];
+ let flags = format!(
+ "{}{}{}",
+ if *r { "r" } else { "-" },
+ if *w { "w" } else { "-" },
+ if *x { "x" } else { "-" },
+ );
+ let in_view = view_filter
+ .as_ref()
+ .map(|f| f.contains(name))
+ .unwrap_or(true);
+ ui.horizontal(|ui| {
+ let indicator = if in_view { "[v]" } else { "[ ]" };
+ ui.monospace(indicator);
+ if ui
+ .link(
+ egui::RichText::new(format!(
+ "{name} {va:#x} {size:#x} {flags}"
+ ))
+ .monospace(),
+ )
+ .on_hover_text("Go To fragment start")
+ .clicked()
+ {
+ goto = Some(*va);
+ }
+ ui.with_layout(
+ egui::Layout::right_to_left(egui::Align::Center),
+ |ui| {
+ if in_view && view_filter.is_some() {
+ if ui
+ .small_button("Remove")
+ .on_hover_text(
+ "Remove fragment from Listing view",
+ )
+ .clicked()
+ {
+ remove_from_view = Some(name.clone());
+ }
+ } else if ui
+ .small_button("Add")
+ .on_hover_text("Add fragment to Listing view")
+ .clicked()
+ {
+ add_to_view = Some(name.clone());
+ }
+ if ui
+ .small_button("Set")
+ .on_hover_text(
+ "Set Listing view to this fragment only",
+ )
+ .clicked()
+ {
+ set_view = Some(name.clone());
+ }
+ },
+ );
+ });
+ }
+ });
+ };
+
+ 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}"));
+ }
+ if let Some(name) = add_to_view {
+ self.add_to_view(name);
+ }
+ if let Some(name) = remove_from_view {
+ self.remove_from_view(&name);
+ }
+ if let Some(name) = set_view {
+ let mut s = BTreeSet::new();
+ s.insert(name);
+ self.set_listing_view(Some(s));
+ }
+ if show_all {
+ self.listing_view_filter = None;
+ }
+ });
+ }
+
+ if self.show_symbol_tree {
+ egui::SidePanel::right("symbol_tree")
+ .resizable(true)
+ .default_width(280.0)
+ .min_width(200.0)
+ .show(ctx, |ui| {
+ let t = self.tokens();
+ let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
+ ui.heading("Symbol Tree");
+ if self.program.is_none() {
+ ui.weak("Open a project file to browse symbols.");
+ return;
+ }
+ ui.small(egui::RichText::new(self.analysis_summary_line()).color(primary));
+ ui.horizontal(|ui| {
+ ui.checkbox(&mut self.symbol_tree_nav, "Selection Navigation")
+ .on_hover_text(
+ "`Selection Navigation` — cursor moves keep this tree in sync",
+ );
+ });
+ 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| {
+ // ── `SymbolTreePlugin` category order ────────────────
+ // Imports · Exports · Functions · Labels · Classes · Namespaces
+
+ let (imports, exports) = self.imports_exports();
+
+ let mut nav_goto: Option<u64> = None;
+ // 1) Imports — honest: only rows the analyzer/loader produced.
+ egui::CollapsingHeader::new(format!("Imports ({})", imports.len()))
+ .default_open(false)
+ .show(ui, |ui| {
+ if imports.is_empty() {
+ ui.weak(
+ "No imports — Ghidrust PE loader currently does not \
+ parse the Import Directory. Run a PDB analyzer to \
+ populate __imp_* symbols.",
+ );
+ } else {
+ for (va, name) in &imports {
+ if ui
+ .link(
+ egui::RichText::new(format!("{va:#x} {name}"))
+ .monospace(),
+ )
+ .clicked()
+ {
+ nav_goto = Some(*va);
+ }
+ }
+ }
+ });
+ // 2) Exports — honest empty when unset.
+ egui::CollapsingHeader::new(format!("Exports ({})", exports.len()))
+ .default_open(false)
+ .show(ui, |ui| {
+ if exports.is_empty() {
+ ui.weak(
+ "No exports — Ghidrust PE loader currently does not \
+ parse the Export Directory. Analyzer output may \
+ surface `__declspec(dllexport)` names.",
+ );
+ } else {
+ for (va, name) in &exports {
+ if ui
+ .link(
+ egui::RichText::new(format!("{va:#x} {name}"))
+ .monospace(),
+ )
+ .clicked()
+ {
+ nav_goto = Some(*va);
+ }
+ }
+ }
+ });
+ if let Some(va) = nav_goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+
+ // 3) Functions (virtualized) — real from Program::analysis.functions
+ let fn_count = self
+ .program
+ .as_ref()
+ .map(|p| p.analysis.functions.len())
+ .unwrap_or(0);
+ egui::CollapsingHeader::new(format!("Functions ({fn_count})"))
+ .default_open(fn_count > 0 && fn_count <= 500)
+ .show(ui, |ui| {
+ let entry = self.program.as_ref().and_then(|p| p.entry);
+ let fns: Vec<(u64, String)> = self
+ .program
+ .as_ref()
+ .map(|p| {
+ p.analysis
+ .functions
+ .iter()
+ .map(|f| (f.entry, f.name.clone()))
+ .collect()
+ })
+ .unwrap_or_default();
+ if let Some(e) = entry {
+ ui.monospace(format!("entry @ {e:#x}"));
+ }
+ if fns.is_empty() {
+ ui.weak("Run Function Start Search.");
+ } else {
+ ui.add(
+ egui::TextEdit::singleline(&mut self.fn_filter)
+ .desired_width(f32::INFINITY)
+ .hint_text("Filter functions…"),
+ );
+ let q = self.fn_filter.to_ascii_lowercase();
+ let rows: Vec<(u64, String)> = fns
+ .into_iter()
+ .filter(|(_, name)| {
+ q.is_empty()
+ || name.to_ascii_lowercase().contains(&q)
+ })
+ .collect();
+ let row_h =
+ ui.text_style_height(&egui::TextStyle::Monospace);
+ let n = rows.len();
+ let mut clicked_fn: Option<u64> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("fn_scroll")
+ .max_height(220.0)
+ .show_rows(ui, row_h, n, |ui, range| {
+ for i in range {
+ let (va, name) = &rows[i];
+ let label = format!("{va:#x} {name}");
+ // Focused if this function is the decomp / cursor /
+ // selection-navigation target.
+ let focused = self.decomp_entry == Some(*va)
+ || self.listing_focus_va == Some(*va)
+ || self.focused_function_entry == Some(*va);
+ let rich = if focused {
+ egui::RichText::new(label)
+ .monospace()
+ .color(primary)
+ } else {
+ egui::RichText::new(label).monospace()
+ };
+ let r = ui.add(
+ egui::Label::new(rich)
+ .sense(egui::Sense::click()),
+ );
+ if r.clicked() {
+ clicked_fn = Some(*va);
+ }
+ if r.hovered() {
+ ui.ctx().set_cursor_icon(
+ egui::CursorIcon::PointingHand,
+ );
+ }
+ }
+ });
+ if let Some(va) = clicked_fn {
+ self.focus_function(va);
+ }
+ ui.small(format!(
+ "{n} shown · click → Listing + Decompiler"
+ ));
+ }
+ });
+
+ // 4) Labels — Program::analysis.symbols (real)
+ let labels: Vec<(u64, String)> = self
+ .program
+ .as_ref()
+ .map(|p| {
+ p.analysis
+ .symbols
+ .iter()
+ .map(|s| (s.va, s.name.clone()))
+ .collect()
+ })
+ .unwrap_or_default();
+ egui::CollapsingHeader::new(format!("Labels ({})", labels.len()))
+ .default_open(false)
+ .show(ui, |ui| {
+ if labels.is_empty() {
+ ui.weak(
+ "No labels — analyzers/PDB symbols populate this list.",
+ );
+ } else {
+ let row_h =
+ ui.text_style_height(&egui::TextStyle::Monospace);
+ let n = labels.len();
+ let mut clicked_va: Option<u64> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("labels_scroll")
+ .max_height(220.0)
+ .show_rows(ui, row_h, n, |ui, range| {
+ for i in range {
+ let (va, name) = &labels[i];
+ let r = ui.add(
+ egui::Label::new(
+ egui::RichText::new(format!(
+ "{va:#x} {name}"
+ ))
+ .monospace(),
+ )
+ .sense(egui::Sense::click()),
+ );
+ if r.clicked() {
+ clicked_va = Some(*va);
+ }
+ }
+ });
+ if let Some(va) = clicked_va {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+ });
+
+ // 5) Classes (RTTI subtree preserved) — real
+ let rtti_n = self.rtti.classes.len();
+ egui::CollapsingHeader::new(format!("Classes ({rtti_n})"))
+ .default_open(false)
+ .show(ui, |ui| {
+ if rtti_n == 0 {
+ ui.weak("Run WindowsPE x86 PE RTTI Analyzer, then Open the file.");
+ return;
+ }
+ ui.add(
+ egui::TextEdit::singleline(&mut self.rtti_filter)
+ .desired_width(f32::INFINITY)
+ .hint_text("Filter class names…"),
+ );
+ if ui.button("Apply filter").clicked()
+ || ui.input(|i| i.key_pressed(egui::Key::Enter))
+ {
+ self.rtti_filter_cache.clear();
+ }
+ 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]];
+ let va = c
+ .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={:?}\nvtable_vas (rtti_query)=[{vtables}]",
+ c.kind, c.col_va, c.vtable_va
+ ));
+ });
+ }
+ });
+ });
+
+ // 6) Namespaces — honest: derive from `::` in symbol names when a demangler ran.
+ let namespace_map: BTreeMap<String, Vec<(u64, String)>> = {
+ let mut m: BTreeMap<String, Vec<(u64, String)>> = BTreeMap::new();
+ if let Some(prog) = self.program.as_ref() {
+ for s in prog
+ .analysis
+ .symbols
+ .iter()
+ .chain(prog.analysis.pdb_symbols.iter())
+ {
+ let src = s.demangled.as_deref().unwrap_or(&s.name);
+ if let Some(idx) = src.rfind("::") {
+ let ns = src[..idx].to_string();
+ let leaf = src[idx + 2..].to_string();
+ m.entry(ns).or_default().push((s.va, leaf));
+ }
+ }
+ }
+ m
+ };
+ egui::CollapsingHeader::new(format!(
+ "Namespaces ({})",
+ namespace_map.len()
+ ))
+ .default_open(false)
+ .show(ui, |ui| {
+ if namespace_map.is_empty() {
+ ui.weak(
+ "No namespaces recovered — the Demangler Microsoft analyzer \
+ fills this list when demangling produces `::` scopes.",
+ );
+ return;
+ }
+ let mut clicked_va: Option<u64> = None;
+ for (ns, entries) in &namespace_map {
+ egui::CollapsingHeader::new(format!(
+ "{ns} ({})",
+ entries.len()
+ ))
+ .default_open(false)
+ .show(ui, |ui| {
+ for (va, leaf) in entries {
+ if ui
+ .link(
+ egui::RichText::new(format!("{va:#x} {leaf}"))
+ .monospace(),
+ )
+ .clicked()
+ {
+ clicked_va = Some(*va);
+ }
+ }
+ });
+ }
+ if let Some(va) = clicked_va {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ });
+
+ // Bonus: Strings shortcut (has a separate Defined Strings window,
+ // which is available in the floating provider panel too).
+ let str_n = self.strings.len();
+ egui::CollapsingHeader::new(format!("Strings ({str_n})"))
+ .default_open(false)
+ .show(ui, |ui| {
+ if str_n == 0 {
+ ui.weak("Run ASCII Strings (session) or re-analyze.");
+ return;
+ }
+ if ui.button("Open Defined Strings window").clicked() {
+ self.pane_open.insert(PaneKind::DefinedStrings, true);
+ }
+ let row_h = ui.text_style_height(&egui::TextStyle::Monospace);
+ egui::ScrollArea::vertical()
+ .id_salt("str_scroll")
+ .max_height(200.0)
+ .show_rows(ui, row_h, str_n.min(5000), |ui, range| {
+ for i in range {
+ if let Some(s) = self.strings.get(i) {
+ let val: String =
+ s.value.chars().take(48).collect();
+ ui.monospace(format!("{:#x}: {val}", s.va));
+ }
+ }
+ });
+ if str_n > 5000 {
+ ui.small(format!("Showing first 5000 of {str_n}"));
+ }
+ });
+ });
+ });
+ }
+
+ // Analysis complete banner (top of frame content)
+ }
+}
diff --git a/crates/ghidrust-gui/src/app/table_panes.rs b/crates/ghidrust-gui/src/app/table_panes.rs
new file mode 100644
index 0000000..4906236
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/table_panes.rs
@@ -0,0 +1,1991 @@
+//! Table / tool panes still hosted on App + startup project picker.
+//!
+//! Extracted per demonolith Wave 7. New pane bodies land here (or provider_panes),
+//! not in `mod.rs`.
+
+use super::GhidrustApp;
+use crate::checksum::ChecksumMode;
+use crate::decrypt_ui::DecryptTab;
+use crate::dock_tabs::DockTab;
+use crate::listing::ui_detail_pane;
+use crate::menu_actions::{decompile_entry_for_va, parse_address};
+use crate::panes::{BookmarkKind, PaneKind};
+use eframe::egui::{self, Color32};
+use egui_dock::DockState;
+use ghidrust_core::{
+ disassemble_at_opts, recover_obfuscated_strings, AppearanceTheme, CommentKind, Program,
+ RecoverStringsOpts, ThemeMode, XRef, BUILTIN_TYPES,
+};
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+
+/// Data Type Preview — every well-known Stage-0 interpretation of `bytes`.
+pub(crate) fn preview_all(bytes: &[u8]) -> Vec<(&'static str, String)> {
+ let mut out = Vec::new();
+ if let Some(&b) = bytes.first() {
+ out.push(("int8", format!("{}", b as i8)));
+ out.push(("uint8", format!("{}", b)));
+ }
+ if bytes.len() >= 2 {
+ let w = u16::from_le_bytes([bytes[0], bytes[1]]);
+ out.push(("int16", format!("{}", w as i16)));
+ out.push(("uint16", format!("{w} ({w:#x})")));
+ }
+ if bytes.len() >= 4 {
+ let d = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
+ out.push(("int32", format!("{}", d as i32)));
+ out.push(("uint32", format!("{d} ({d:#x})")));
+ out.push(("float", format!("{}", f32::from_bits(d))));
+ }
+ if bytes.len() >= 8 {
+ let q = u64::from_le_bytes([
+ bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
+ ]);
+ out.push(("int64", format!("{}", q as i64)));
+ out.push(("uint64", format!("{q} ({q:#x})")));
+ out.push(("double", format!("{}", f64::from_bits(q))));
+ out.push(("pointer64", format!("{q:#018x}")));
+ }
+ let ascii: String = bytes
+ .iter()
+ .take(16)
+ .map(|b| {
+ if (0x20..=0x7f).contains(b) {
+ *b as char
+ } else {
+ '.'
+ }
+ })
+ .collect();
+ out.push(("ascii", ascii));
+ out
+}
+
+impl GhidrustApp {
+
+ pub(crate) fn ui_startup_picker(&mut self, ctx: &egui::Context) {
+ let t = self.tokens();
+ let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
+ let muted = Color32::from_rgb(
+ t.on_surface_variant[0],
+ t.on_surface_variant[1],
+ t.on_surface_variant[2],
+ );
+ let surface = Color32::from_rgb(
+ t.surface_container[0],
+ t.surface_container[1],
+ t.surface_container[2],
+ );
+
+ // Fixed card size — never wider than the window, never stretch off-screen.
+ let card_w = 440.0_f32.min(ctx.screen_rect().width() - 48.0).max(280.0);
+
+ egui::CentralPanel::default().show(ctx, |ui| {
+ ui.vertical_centered(|ui| {
+ ui.add_space(32.0);
+ ui.heading(egui::RichText::new("Ghidrust").size(26.0).color(primary));
+ if let Some(tex) = self.logo_texture.as_ref() {
+ ui.add_space(10.0);
+ let logo_h = 112.0_f32;
+ let size = tex.size_vec2();
+ let logo_w = (logo_h * size.x / size.y).clamp(64.0, 160.0);
+ ui.add(egui::Image::new(tex).fit_to_exact_size(egui::vec2(logo_w, logo_h)));
+ ui.add_space(8.0);
+ } else {
+ ui.add_space(8.0);
+ }
+ ui.label(
+ egui::RichText::new("Open a project to reverse engineer")
+ .color(muted)
+ .size(14.0),
+ );
+ ui.add_space(20.0);
+
+ egui::Frame::group(ui.style())
+ .fill(surface)
+ .inner_margin(egui::Margin::same(16))
+ .corner_radius(egui::CornerRadius::same(8))
+ .show(ui, |ui| {
+ ui.set_width(card_w);
+ ui.set_max_width(card_w);
+
+ // ── Recent projects (IDE-style list) ──
+ ui.label(egui::RichText::new("Recent projects").strong().size(13.0));
+ ui.add_space(6.0);
+
+ let recents = self.recent_projects.clone();
+ let list_h = if recents.is_empty() { 48.0 } else { 200.0 };
+
+ egui::Frame::NONE
+ .stroke(ui.visuals().widgets.noninteractive.bg_stroke)
+ .inner_margin(egui::Margin::same(4))
+ .corner_radius(egui::CornerRadius::same(4))
+ .show(ui, |ui| {
+ ui.set_width(card_w - 8.0);
+ egui::ScrollArea::vertical()
+ .id_salt("startup_recent")
+ .max_height(list_h)
+ .auto_shrink([false, false])
+ .show(ui, |ui| {
+ ui.set_min_width(card_w - 24.0);
+ if recents.is_empty() {
+ ui.add_space(8.0);
+ ui.weak(
+ "No recent projects — open or create one below.",
+ );
+ ui.add_space(8.0);
+ } else {
+ let mut open_path: Option<String> = None;
+ for path in &recents {
+ let name = Path::new(path)
+ .file_name()
+ .map(|s| s.to_string_lossy().into_owned())
+ .unwrap_or_else(|| path.clone());
+ // IDE-style row: project name + path, full-width click
+ let row_w = (card_w - 24.0).max(200.0);
+ let row_h = 44.0;
+ let (rect, resp) = ui.allocate_exact_size(
+ egui::vec2(row_w, row_h),
+ egui::Sense::click(),
+ );
+ if resp.hovered() || resp.has_focus() {
+ ui.painter().rect_filled(
+ rect,
+ egui::CornerRadius::same(4),
+ primary.gamma_multiply(0.15),
+ );
+ }
+ let mut child = ui.new_child(
+ egui::UiBuilder::new()
+ .max_rect(
+ rect.shrink2(egui::vec2(10.0, 6.0)),
+ )
+ .layout(egui::Layout::top_down(
+ egui::Align::LEFT,
+ )),
+ );
+ child.label(
+ egui::RichText::new(&name)
+ .strong()
+ .color(primary)
+ .size(14.0),
+ );
+ child.label(
+ egui::RichText::new(path).small().color(muted),
+ );
+ if resp.clicked() {
+ open_path = Some(path.clone());
+ }
+ resp.on_hover_text(format!("Open project: {path}"));
+ }
+ if let Some(path) = open_path {
+ self.project_dir_input = path;
+ if let Err(e) = self.open_project() {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ self.show_startup_picker = true;
+ }
+ }
+ }
+ });
+ });
+
+ ui.add_space(14.0);
+ ui.separator();
+ ui.add_space(10.0);
+
+ // Buttons fit card width only (no off-screen stretch)
+ let btn_w = card_w - 8.0;
+ if ui
+ .add_sized([btn_w, 32.0], egui::Button::new("Open existing project…"))
+ .clicked()
+ {
+ self.browse_and_open_project();
+ if self.project.is_none() {
+ self.show_startup_picker = true;
+ }
+ }
+ ui.add_space(8.0);
+ ui.horizontal(|ui| {
+ ui.label("Name:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.project_name_input)
+ .desired_width((btn_w - 56.0).max(120.0))
+ .hint_text("MyProject"),
+ );
+ });
+ ui.add_space(4.0);
+ if ui
+ .add_sized([btn_w, 32.0], egui::Button::new("Create new project…"))
+ .clicked()
+ {
+ self.browse_and_create_project();
+ if self.project.is_none() {
+ self.show_startup_picker = true;
+ }
+ }
+ ui.add_space(12.0);
+ if ui.link("Continue without a project").clicked() {
+ self.show_startup_picker = false;
+ self.status =
+ "No project — Browse/Load a binary, or File → Open Project".into();
+ }
+ ui.add_space(4.0);
+ ui.small(
+ egui::RichText::new(
+ "Click a recent project name to open it. Analysis uses analysis.bin for fast load.",
+ )
+ .color(muted),
+ );
+ });
+ });
+ });
+ }
+ // draw_provider_panes + pane bodies → provider_panes.rs
+
+ pub(crate) fn snapshot_current_layout(&self, name: impl Into<String>) -> crate::layouts::SavedLayout {
+ let name = name.into();
+ let mut open_panes = BTreeMap::new();
+ for (k, v) in &self.pane_open {
+ open_panes.insert(k.egui_id().to_string(), *v);
+ }
+ crate::debugger::snapshot_layout_flags(&self.debugger, &mut open_panes);
+ crate::network::snapshot_layout_flags(&self.network, &mut open_panes);
+ let mut docks = BTreeMap::new();
+ docks.insert("project_tree".into(), self.show_project_tree);
+ 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 = crate::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",
+ }
+ .to_string();
+ crate::layouts::SavedLayout {
+ name,
+ open_panes,
+ docks,
+ center,
+ dock_tree,
+ theme,
+ appearance: self.appearance.id().to_string(),
+ comment: String::new(),
+ }
+ }
+
+ pub(crate) fn apply_saved_layout(&mut self, layout: &crate::layouts::SavedLayout) {
+ // Apply pane visibility.
+ let ids: BTreeMap<&'static str, PaneKind> =
+ PaneKind::ALL.iter().map(|k| (k.egui_id(), *k)).collect();
+ for (id, open) in &layout.open_panes {
+ if let Some(k) = ids.get(id.as_str()) {
+ self.pane_open.insert(*k, *open);
+ }
+ }
+ crate::debugger::apply_layout_flags(&mut self.debugger, &layout.open_panes);
+ crate::network::apply_layout_flags(&mut self.network, &layout.open_panes);
+ // Docks.
+ if let Some(v) = layout.docks.get("project_tree") {
+ self.show_project_tree = *v;
+ }
+ if let Some(v) = layout.docks.get("program_tree") {
+ self.show_program_tree = *v;
+ }
+ if let Some(v) = layout.docks.get("symbol_tree") {
+ self.show_symbol_tree = *v;
+ }
+ if let Some(v) = layout.docks.get("console") {
+ self.show_console = *v;
+ }
+ 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 = crate::dock_tabs::from_legacy_center(&layout.center),
+ }
+ } else {
+ self.center_dock = crate::dock_tabs::from_legacy_center(&layout.center);
+ }
+ self.sync_center_from_dock();
+ self.theme = match layout.theme.as_str() {
+ "light" => ThemeMode::Light,
+ _ => ThemeMode::Dark,
+ };
+ self.appearance = AppearanceTheme::from_id(&layout.appearance);
+ self.current_layout_name = layout.name.clone();
+ }
+
+ /// Save the current layout under `name`.
+ pub fn save_layout_named(&mut self, name: impl Into<String>) -> std::io::Result<PathBuf> {
+ let name = name.into();
+ let l = self.snapshot_current_layout(name.clone());
+ let p = crate::layouts::save_layout(&l)?;
+ self.current_layout_name = name;
+ self.layouts_cached = crate::layouts::list_layouts();
+ Ok(p)
+ }
+
+ /// Restore a saved layout by name.
+ pub fn restore_layout_named(&mut self, name: &str) -> std::io::Result<()> {
+ let l = crate::layouts::load_layout(name)?;
+ self.apply_saved_layout(&l);
+ Ok(())
+ }
+
+ pub(crate) fn ui_bookmarks_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ ui.heading("Bookmarks");
+ ui.small(egui::RichText::new("BookmarkPlugin analog · 5 standard kinds").color(muted));
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.bookmark_filter)
+ .desired_width(200.0)
+ .hint_text("category or description"),
+ );
+ if ui
+ .button("Add at cursor…")
+ .on_hover_text("Add a bookmark at the current Listing VA")
+ .clicked()
+ {
+ if let Some(va) = self.listing_focus_va {
+ self.bookmark_dialog_kind = BookmarkKind::Note;
+ self.bookmark_dialog_category = String::new();
+ self.bookmark_dialog_description = format!("bookmark @ {va:#x}");
+ self.show_bookmark_dialog = true;
+ } else {
+ self.status = "No cursor VA — click a Listing line first".into();
+ self.log(self.status.clone());
+ }
+ }
+ });
+ ui.separator();
+
+ if self.bookmarks.is_empty() {
+ ui.weak("No bookmarks yet — click Add at cursor to place one.");
+ return;
+ }
+
+ let filt = self.bookmark_filter.to_ascii_lowercase();
+ let rows: Vec<(usize, u64, BookmarkKind, String, String)> = self
+ .bookmarks
+ .iter()
+ .enumerate()
+ .filter(|(_, b)| {
+ filt.is_empty()
+ || b.category.to_ascii_lowercase().contains(&filt)
+ || b.description.to_ascii_lowercase().contains(&filt)
+ || b.kind.label().to_ascii_lowercase().contains(&filt)
+ })
+ .map(|(i, b)| (i, b.va, b.kind, b.category.clone(), b.description.clone()))
+ .collect();
+
+ ui.small(format!(
+ "{} / {} bookmarks",
+ rows.len(),
+ self.bookmarks.len()
+ ));
+
+ egui::ScrollArea::vertical()
+ .id_salt("bookmarks_scroll")
+ .max_height(360.0)
+ .show(ui, |ui| {
+ egui::Grid::new("bookmarks_grid")
+ .num_columns(5)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Type");
+ ui.strong("Address");
+ ui.strong("Category");
+ ui.strong("Description");
+ ui.strong("");
+ ui.end_row();
+
+ let mut goto: Option<u64> = None;
+ let mut delete: Option<usize> = None;
+ for (idx, va, kind, cat, desc) in &rows {
+ ui.label(
+ egui::RichText::new(kind.label())
+ .color(kind.color())
+ .strong(),
+ );
+ if ui
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .on_hover_text("Go To this address")
+ .clicked()
+ {
+ goto = Some(*va);
+ }
+ ui.label(cat);
+ ui.label(desc);
+ if ui.small_button("Delete").clicked() {
+ delete = Some(*idx);
+ }
+ ui.end_row();
+ }
+ let _ = primary; // reserved for future accent use
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ if let Some(i) = delete {
+ self.delete_bookmark(i);
+ }
+ });
+ });
+ }
+
+ pub(crate) fn ui_memory_map_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Memory Map");
+ ui.small(
+ egui::RichText::new(
+ "MemoryMapPlugin · toggle RWX / add / delete session memory blocks",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ if self.program.is_none() {
+ ui.weak("No program loaded.");
+ return;
+ }
+
+ // Add-row form.
+ ui.horizontal(|ui| {
+ ui.label("Add block:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.memory_map_new_name)
+ .desired_width(120.0)
+ .hint_text("name"),
+ );
+ ui.add(
+ egui::TextEdit::singleline(&mut self.memory_map_new_va)
+ .desired_width(120.0)
+ .hint_text("VA (0x…)"),
+ );
+ ui.add(
+ egui::TextEdit::singleline(&mut self.memory_map_new_size)
+ .desired_width(100.0)
+ .hint_text("size (0x…)"),
+ );
+ ui.checkbox(&mut self.memory_map_new_r, "R");
+ ui.checkbox(&mut self.memory_map_new_w, "W");
+ ui.checkbox(&mut self.memory_map_new_x, "X");
+ let can_add = !self.memory_map_new_name.trim().is_empty()
+ && !self.memory_map_new_va.trim().is_empty()
+ && !self.memory_map_new_size.trim().is_empty();
+ if ui.add_enabled(can_add, egui::Button::new("Add")).clicked() {
+ let name = self.memory_map_new_name.clone();
+ let va = parse_address(&self.memory_map_new_va).unwrap_or(0);
+ let size = parse_address(&self.memory_map_new_size).unwrap_or(0);
+ let r = self.memory_map_new_r;
+ let w = self.memory_map_new_w;
+ let x = self.memory_map_new_x;
+ if size > 0 {
+ if let Some(prog) = self.program.as_mut() {
+ prog.blocks.push(ghidrust_core::MemoryBlock {
+ name,
+ va,
+ size,
+ bytes: vec![0u8; size.min(0x100_0000) as usize],
+ readable: r,
+ writable: w,
+ executable: x,
+ });
+ }
+ self.status = "Memory Map · added block".into();
+ self.log(self.status.clone());
+ }
+ }
+ });
+ ui.separator();
+
+ let mut goto: Option<u64> = None;
+ let mut delete: Option<usize> = None;
+ 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(9)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Name");
+ ui.strong("Start");
+ ui.strong("End");
+ ui.strong("Length");
+ 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
+ .program
+ .as_ref()
+ .map(|p| {
+ p.blocks
+ .iter()
+ .map(|b| {
+ (
+ b.name.clone(),
+ b.va,
+ b.size,
+ b.readable,
+ b.writable,
+ b.executable,
+ )
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ for (i, (name, va, size, r, w, x)) in blocks.iter().enumerate() {
+ let mut editable = name.clone();
+ if ui
+ .add(egui::TextEdit::singleline(&mut editable).desired_width(120.0))
+ .changed()
+ {
+ rename = Some((i, editable));
+ }
+ if ui
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .clicked()
+ {
+ goto = Some(*va);
+ }
+ ui.monospace(format!("{:#x}", va.saturating_add(*size)));
+ ui.monospace(format!("{size:#x}"));
+ let mut rb = *r;
+ let mut wb = *w;
+ let mut xb = *x;
+ if ui.checkbox(&mut rb, "").changed() {
+ toggle = Some((i, 'R'));
+ }
+ if ui.checkbox(&mut wb, "").changed() {
+ toggle = Some((i, 'W'));
+ }
+ 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();
+ }
+ });
+ });
+
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ if let Some((i, newname)) = rename {
+ if let Some(prog) = self.program.as_mut() {
+ if let Some(b) = prog.blocks.get_mut(i) {
+ b.name = newname;
+ }
+ }
+ }
+ if let Some((i, ch)) = toggle {
+ if let Some(prog) = self.program.as_mut() {
+ if let Some(b) = prog.blocks.get_mut(i) {
+ match ch {
+ 'R' => b.readable = !b.readable,
+ 'W' => b.writable = !b.writable,
+ 'X' => b.executable = !b.executable,
+ _ => {}
+ }
+ }
+ }
+ }
+ if let Some(i) = delete {
+ if let Some(prog) = self.program.as_mut() {
+ if i < prog.blocks.len() {
+ prog.blocks.remove(i);
+ }
+ }
+ }
+ }
+
+ pub(crate) fn ui_functions_window(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ ui.heading("Functions");
+ ui.small(
+ egui::RichText::new("FunctionWindowPlugin · flat table of Program::analysis.functions")
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let n_total = prog.analysis.functions.len();
+ if n_total == 0 {
+ ui.weak("No functions — run Function Start Search.");
+ return;
+ }
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.functions_window_filter)
+ .desired_width(300.0)
+ .hint_text("Function name…"),
+ );
+ });
+ let q = self.functions_window_filter.to_ascii_lowercase();
+ let rows: Vec<(u64, u64, String, usize)> = prog
+ .analysis
+ .functions
+ .iter()
+ .filter(|f| q.is_empty() || f.name.to_ascii_lowercase().contains(&q))
+ .map(|f| (f.entry, f.end, f.name.clone(), f.parameters.len()))
+ .collect();
+ ui.small(format!("{} / {} functions", rows.len(), n_total));
+ let focus = self.decomp_entry;
+ egui::ScrollArea::vertical()
+ .id_salt("fnwin_scroll")
+ .max_height(400.0)
+ .show(ui, |ui| {
+ egui::Grid::new("functions_window_grid")
+ .num_columns(4)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Entry");
+ ui.strong("Size");
+ ui.strong("Name");
+ ui.strong("Params");
+ ui.end_row();
+ let mut clicked: Option<u64> = None;
+ for (entry, end, name, params) in &rows {
+ let size = end.saturating_sub(*entry);
+ let addr_text = egui::RichText::new(format!("{entry:#x}"))
+ .monospace()
+ .color(if focus == Some(*entry) {
+ primary
+ } else {
+ ui.visuals().text_color()
+ });
+ if ui.link(addr_text).clicked() {
+ clicked = Some(*entry);
+ }
+ ui.monospace(format!("{size:#x}"));
+ ui.label(name);
+ ui.monospace(format!("{params}"));
+ ui.end_row();
+ }
+ if let Some(va) = clicked {
+ self.focus_function(va);
+ }
+ });
+ });
+ }
+
+ pub(crate) fn ui_symbol_table(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Symbol Table");
+ ui.small(
+ egui::RichText::new(
+ "SymbolTablePlugin · symbols + function entries · Refs → opens Symbol References",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.symbol_table_filter)
+ .desired_width(280.0)
+ .hint_text("Symbol name…"),
+ );
+ });
+ let q = self.symbol_table_filter.to_ascii_lowercase();
+ // Merge analysis.symbols + function entries into one flat table.
+ let mut rows: Vec<(u64, String, &'static str)> = Vec::new();
+ for s in &prog.analysis.symbols {
+ rows.push((s.va, s.name.clone(), "Symbol"));
+ }
+ for f in &prog.analysis.functions {
+ rows.push((f.entry, f.name.clone(), "Function"));
+ }
+ rows.retain(|(_, name, _)| q.is_empty() || name.to_ascii_lowercase().contains(&q));
+ rows.sort_by_key(|r| r.0);
+
+ ui.small(format!("{} rows", rows.len()));
+ let mut goto: Option<u64> = None;
+ let mut show_refs: Option<u64> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("symtable_scroll")
+ .max_height(400.0)
+ .show(ui, |ui| {
+ egui::Grid::new("symbol_table_grid")
+ .num_columns(4)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Address");
+ ui.strong("Name");
+ ui.strong("Type");
+ ui.strong("Refs");
+ ui.end_row();
+ for (va, name, ty) in &rows {
+ if ui
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .clicked()
+ {
+ goto = Some(*va);
+ }
+ ui.label(name);
+ ui.monospace(*ty);
+ if ui
+ .small_button("Refs")
+ .on_hover_text("Open Symbol References for this VA")
+ .clicked()
+ {
+ show_refs = Some(*va);
+ }
+ ui.end_row();
+ }
+ });
+ });
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ if let Some(va) = show_refs {
+ self.symbol_refs_target = Some(va);
+ self.pane_open.insert(PaneKind::SymbolReferences, true);
+ }
+ }
+
+ pub(crate) fn open_decrypt_at(&mut self, va: u64, hint: Option<String>) {
+ self.open_decrypt_at_len(va, 256, hint);
+ }
+
+ pub(crate) fn open_decrypt_at_len(&mut self, va: u64, len: usize, hint: Option<String>) {
+ let bytes = self
+ .program
+ .as_ref()
+ .and_then(|p| crate::decrypt_ui::bytes_at(p, va, len))
+ .unwrap_or_default();
+ self.decrypt_pane.load_bytes(Some(va), &bytes, hint);
+ self.decrypt_pane.focus(DecryptTab::Bake);
+ self.decrypt_pane.va_input = format!("{va:x}");
+ self.decrypt_pane.va_len = len;
+ self.pane_open.insert(PaneKind::Decrypt, true);
+ }
+
+ pub(crate) fn open_decrypt_nearby(&mut self, va: u64, hint: Option<String>) {
+ let start = va.saturating_sub(32);
+ let bytes = self
+ .program
+ .as_ref()
+ .and_then(|p| crate::decrypt_ui::bytes_at(p, start, 256))
+ .unwrap_or_default();
+ self.decrypt_pane.load_bytes(Some(va), &bytes, hint);
+ self.decrypt_pane.input_source = format!("Bytes near crypto result at {va:#x}");
+ self.decrypt_pane.focus(DecryptTab::Bake);
+ self.pane_open.insert(PaneKind::Decrypt, true);
+ }
+
+ pub(crate) fn recover_strings_at_function(&mut self, va: u64) {
+ let Some(prog) = self.program.as_ref() else {
+ self.status = "Recover strings requires a loaded program.".into();
+ return;
+ };
+ let entry = prog
+ .analysis
+ .functions
+ .iter()
+ .find(|f| va >= f.entry && va < f.end)
+ .map(|f| f.entry)
+ .unwrap_or(va);
+ let hits = recover_obfuscated_strings(
+ prog,
+ &RecoverStringsOpts {
+ functions: Some(vec![entry]),
+ ..Default::default()
+ },
+ );
+ self.obfuscated_strings = hits;
+ self.status = format!(
+ "Recovered {} strings in containing function {entry:#x}",
+ self.obfuscated_strings.len()
+ );
+ }
+
+ pub(crate) fn ui_crypto_constants_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ let hits: Vec<_> = if let Some(va) = self.crypto_constants_focus_va {
+ let mut nearby: Vec<_> = self
+ .crypt_constants
+ .iter()
+ .filter(|h| h.va.abs_diff(va) <= 0x1000)
+ .cloned()
+ .collect();
+ nearby.sort_by_key(|h| h.va.abs_diff(va));
+ nearby
+ } else {
+ self.crypt_constants.clone()
+ };
+ let mut goto = None;
+ let mut decrypt = None;
+ crate::decrypt_ui::ui_crypto_constants(
+ ui,
+ muted,
+ &hits,
+ |va| goto = Some(va),
+ |va, algo| decrypt = Some((va, algo.to_string())),
+ );
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ if let Some((va, algo)) = decrypt {
+ self.open_decrypt_nearby(va, Some(algo));
+ }
+ }
+
+ pub(crate) fn ui_recovered_strings_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ let hits = self.obfuscated_strings.clone();
+ let mut goto = None;
+ let mut bake = None;
+ let mut decoder = None;
+ crate::decrypt_ui::ui_recovered_strings(
+ ui,
+ muted,
+ &hits,
+ |va| goto = Some(va),
+ |va| bake = Some(va),
+ |va| decoder = Some(va),
+ );
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ if let Some(va) = bake {
+ self.open_decrypt_at(va, None);
+ }
+ if let Some(va) = decoder {
+ self.focus_function(va);
+ }
+ }
+
+ pub(crate) fn ui_crypto_capabilities_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ let hits = self.crypto_capabilities.clone();
+ let mut goto = None;
+ let mut decrypt = None;
+ crate::decrypt_ui::ui_crypto_capabilities(
+ ui,
+ muted,
+ &hits,
+ |va| goto = Some(va),
+ |va, hint| decrypt = Some((va, hint)),
+ );
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ if let Some((va, hint)) = decrypt {
+ self.open_decrypt_at(va, Some(hint));
+ }
+ }
+
+ pub(crate) fn ui_defined_strings(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Defined Strings");
+ ui.small(
+ egui::RichText::new("ViewStringsPlugin · session strings from ASCII Strings analyzer")
+ .color(muted),
+ );
+ ui.separator();
+ if self.strings.is_empty() {
+ ui.weak("No strings yet — run ASCII Strings analyzer.");
+ return;
+ }
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.defined_strings_filter)
+ .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 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))
+ .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()
+ .id_salt("defstr_scroll")
+ .max_height(400.0)
+ .show(ui, |ui| {
+ egui::Grid::new("defined_strings_grid")
+ .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, 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();
+ }
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ });
+ });
+ }
+
+ pub(crate) fn ui_relocation_table(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Relocation Table");
+ ui.small(
+ egui::RichText::new(
+ "RelocationTablePlugin · PE base relocs / ELF RELA from Program::file_bytes",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let rows = crate::relocations::parse_relocations(prog);
+ if rows.is_empty() {
+ ui.small(
+ egui::RichText::new(
+ "No PE base-reloc / ELF RELA entries parsed — showing section metadata.",
+ )
+ .color(muted)
+ .italics(),
+ );
+ egui::Grid::new("relocs_sections_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Section");
+ ui.strong("VA");
+ ui.strong("Size");
+ ui.end_row();
+ for s in &prog.sections {
+ ui.label(&s.name);
+ ui.monospace(format!("{:#x}", s.va));
+ ui.monospace(format!("{:#x}", s.virtual_size));
+ ui.end_row();
+ }
+ });
+ return;
+ }
+ ui.small(format!("{} relocation(s)", rows.len()));
+ let row_h = ui.text_style_height(&egui::TextStyle::Monospace) + 2.0;
+ egui::ScrollArea::vertical()
+ .id_salt("relocs_scroll")
+ .auto_shrink([false, false])
+ .show_rows(ui, row_h, rows.len(), |ui, range| {
+ for i in range {
+ let r = &rows[i];
+ ui.monospace(format!("{:#x} {} {}", r.va, r.kind, r.detail));
+ }
+ });
+ }
+
+ pub(crate) fn ui_disassembled_view_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Disassembled View");
+ ui.small(egui::RichText::new("DisassembledViewPlugin · detail at cursor").color(muted));
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let va = match self.listing_focus_va.or(prog.entry) {
+ Some(v) => v,
+ None => {
+ ui.weak("No cursor / entry.");
+ return;
+ }
+ };
+ let arch = self.listing_arch();
+ match disassemble_at_opts(prog, va, Some(&self.decode_opts.to_engine_opts())) {
+ Ok(insn) => {
+ ui.monospace(insn.text());
+ ui.separator();
+ ui_detail_pane(ui, &insn, arch);
+ }
+ Err(e) => {
+ ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), e.to_string());
+ }
+ }
+ }
+
+ pub(crate) fn ui_comment_window(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Comments");
+ ui.small(
+ egui::RichText::new(
+ "CommentWindowPlugin · shows EOL/Pre/Post/Plate/Repeatable edits + bookmarks",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ // Filter row — CommentWindow provides both a text filter and
+ // a per-kind toggle.
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.comment_window_filter)
+ .desired_width(240.0)
+ .hint_text("Text / address / kind…"),
+ );
+ ui.label("Kind:");
+ let cur = self
+ .comment_window_kind_filter
+ .map(|k| k.label())
+ .unwrap_or("All");
+ egui::ComboBox::from_id_salt("comment_window_kind_combo")
+ .selected_text(cur)
+ .show_ui(ui, |ui| {
+ ui.selectable_value(&mut self.comment_window_kind_filter, None, "All");
+ for k in CommentKind::ALL {
+ ui.selectable_value(
+ &mut self.comment_window_kind_filter,
+ Some(*k),
+ k.label(),
+ );
+ }
+ });
+ });
+ ui.separator();
+ // Real edited comments from ProgramEdits — one row per (va, kind).
+ let mut rows: Vec<(&'static str, u64, String)> = Vec::new();
+ if let Some(prog) = self.program.as_ref() {
+ for ((va, kind), text) in &prog.edits.comments {
+ rows.push((kind.label(), *va, text.clone()));
+ }
+ }
+ // Also surface bookmarks as "Note-derived" comment rows.
+ for b in &self.bookmarks {
+ let text = if b.category.is_empty() {
+ b.description.clone()
+ } else {
+ format!("[{}] {}", b.category, b.description)
+ };
+ rows.push(("Bookmark", b.va, text));
+ }
+ // Apply filters.
+ let text_filter = self.comment_window_filter.to_ascii_lowercase();
+ let kind_filter = self.comment_window_kind_filter;
+ rows.retain(|(kind, va, text)| {
+ if let Some(want) = kind_filter {
+ if *kind != want.label() {
+ return false;
+ }
+ }
+ if text_filter.is_empty() {
+ return true;
+ }
+ let addr = format!("{va:#x}");
+ text.to_ascii_lowercase().contains(&text_filter)
+ || kind.to_ascii_lowercase().contains(&text_filter)
+ || addr.contains(&text_filter)
+ });
+ if rows.is_empty() {
+ ui.weak(
+ "No comments/bookmarks match — set a comment with `;` on a Listing line, or add a Bookmark.",
+ );
+ return;
+ }
+ rows.sort_by_key(|(_, va, _)| *va);
+ egui::ScrollArea::vertical()
+ .id_salt("comment_window_scroll")
+ .max_height(400.0)
+ .show(ui, |ui| {
+ egui::Grid::new("comments_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Type");
+ ui.strong("Address");
+ ui.strong("Comment");
+ ui.end_row();
+ let mut goto: Option<u64> = None;
+ let mut delete: Option<(u64, CommentKind)> = None;
+ for (kind, va, text) in &rows {
+ let color = match *kind {
+ "EOL" => Color32::from_rgb(0x81, 0xC7, 0x84),
+ "Pre" => Color32::from_rgb(0x64, 0xB5, 0xF6),
+ "Post" => Color32::from_rgb(0xBA, 0x68, 0xC8),
+ "Plate" => Color32::from_rgb(0xFF, 0xB7, 0x4D),
+ "Repeatable" => Color32::from_rgb(0x4D, 0xD0, 0xE1),
+ _ => Color32::from_rgb(0x9C, 0x27, 0xB0),
+ };
+ ui.label(egui::RichText::new(*kind).color(color).strong());
+ if ui
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .clicked()
+ {
+ goto = Some(*va);
+ }
+ ui.horizontal(|ui| {
+ ui.label(text);
+ let matching_kind = match *kind {
+ "EOL" => Some(CommentKind::Eol),
+ "Pre" => Some(CommentKind::Pre),
+ "Post" => Some(CommentKind::Post),
+ "Plate" => Some(CommentKind::Plate),
+ "Repeatable" => Some(CommentKind::Repeatable),
+ _ => None,
+ };
+ if let Some(k) = matching_kind {
+ if ui.small_button("Del").clicked() {
+ delete = Some((*va, k));
+ }
+ }
+ });
+ ui.end_row();
+ }
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ if let Some((va, k)) = delete {
+ let _ = self.set_comment_at(va, k, "");
+ }
+ });
+ });
+ }
+
+ pub(crate) fn ui_defined_data(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Defined Data");
+ ui.small(
+ egui::RichText::new(
+ "DataWindowPlugin · session data (Program::data_items when available)",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ let rtti_rows: Vec<(u64, String)> = match self.program.as_ref() {
+ Some(prog) => prog
+ .rtti
+ .classes
+ .iter()
+ .take(2000)
+ .filter_map(|c| c.type_info_va.map(|va| (va, c.name.clone())))
+ .collect(),
+ None => {
+ ui.weak("No program loaded.");
+ return;
+ }
+ };
+ if self.strings.is_empty() && rtti_rows.is_empty() {
+ ui.weak("No defined data (strings/RTTI) available yet — run ASCII Strings / RTTI analyzers.");
+ return;
+ }
+ let str_rows: Vec<(u64, String)> = self
+ .strings
+ .iter()
+ .take(2000)
+ .map(|s| (s.va, s.value.chars().take(48).collect()))
+ .collect();
+ let mut goto: Option<u64> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("defined_data_scroll")
+ .max_height(400.0)
+ .show(ui, |ui| {
+ egui::Grid::new("defined_data_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Address");
+ ui.strong("Type");
+ ui.strong("Preview");
+ ui.end_row();
+ for (va, val) in &str_rows {
+ if ui
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .clicked()
+ {
+ goto = Some(*va);
+ }
+ ui.monospace("string");
+ ui.label(val);
+ ui.end_row();
+ }
+ for (va, name) in &rtti_rows {
+ if ui
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .clicked()
+ {
+ goto = Some(*va);
+ }
+ ui.monospace("rtti");
+ ui.label(name);
+ ui.end_row();
+ }
+ });
+ });
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+
+ // ── Byte Viewer / Symbol References / Equates / Tags ─
+
+ /// ByteViewerPluginue — split hex / ASCII view of the
+ /// program's memory around the current cursor. Bytes-per-line combo,
+ /// programmable offset override, and click-to-navigate address column.
+ pub(crate) fn ui_bytes_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ ui.heading("Bytes");
+ ui.small(
+ egui::RichText::new("ByteViewerPlugin · split hex / ASCII, follows Listing cursor")
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ // Cursor tracking — default to Listing focus, editable via combo.
+ if self.bytes_pane_va.is_none() {
+ self.bytes_pane_va = self
+ .listing_focus_va
+ .or(prog.entry)
+ .or_else(|| prog.blocks.first().map(|b| b.va));
+ }
+ let base_va = self.bytes_pane_va.unwrap_or(prog.image_base);
+ ui.horizontal(|ui| {
+ ui.label("VA:");
+ let mut input = format!("{base_va:#x}");
+ let resp = ui.add(egui::TextEdit::singleline(&mut input).desired_width(140.0));
+ if resp.lost_focus() {
+ if let Ok(v) = parse_address(&input) {
+ self.bytes_pane_va = Some(v);
+ }
+ }
+ ui.label("Bytes/line:");
+ egui::ComboBox::from_id_salt("bytes_pane_bpr")
+ .selected_text(format!("{}", self.bytes_pane_bpr))
+ .show_ui(ui, |ui| {
+ for w in [8usize, 12, 16, 24, 32] {
+ ui.selectable_value(&mut self.bytes_pane_bpr, w, format!("{w}"));
+ }
+ });
+ ui.label("Rows:");
+ egui::ComboBox::from_id_salt("bytes_pane_rows")
+ .selected_text(format!("{}", self.bytes_pane_rows))
+ .show_ui(ui, |ui| {
+ for r in [8usize, 16, 24, 32, 48, 64] {
+ ui.selectable_value(&mut self.bytes_pane_rows, r, format!("{r}"));
+ }
+ });
+ if ui
+ .button("Follow cursor")
+ .on_hover_text("Snap to Listing cursor")
+ .clicked()
+ {
+ self.bytes_pane_va = self.listing_focus_va;
+ }
+ });
+ ui.separator();
+ let bpr = self.bytes_pane_bpr.max(1);
+ let total = bpr.saturating_mul(self.bytes_pane_rows);
+ let mut bytes: Vec<Option<u8>> = Vec::with_capacity(total);
+ for i in 0..total {
+ bytes.push(prog.byte_at(base_va.wrapping_add(i as u64)));
+ }
+ let focus_va = self.listing_focus_va;
+ let mut nav: Option<u64> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("bytes_scroll")
+ .max_height(420.0)
+ .show(ui, |ui| {
+ for row in 0..self.bytes_pane_rows {
+ let row_va = base_va.wrapping_add((row * bpr) as u64);
+ ui.horizontal(|ui| {
+ let addr = egui::RichText::new(format!("{row_va:016x}"))
+ .monospace()
+ .color(if Some(row_va) == focus_va {
+ primary
+ } else {
+ ui.visuals().text_color()
+ });
+ if ui.link(addr).on_hover_text("Go To in Listing").clicked() {
+ nav = Some(row_va);
+ }
+ ui.label("│");
+ let mut hex_line = String::new();
+ let mut ascii_line = String::new();
+ for col in 0..bpr {
+ let idx = row * bpr + col;
+ match bytes.get(idx).and_then(|b| *b) {
+ Some(b) => {
+ hex_line.push_str(&format!("{b:02x} "));
+ let c = if (0x20..=0x7f).contains(&b) {
+ b as char
+ } else {
+ '.'
+ };
+ ascii_line.push(c);
+ }
+ None => {
+ hex_line.push_str("?? ");
+ ascii_line.push(' ');
+ }
+ }
+ }
+ ui.monospace(hex_line.trim_end());
+ ui.label("│");
+ ui.monospace(ascii_line);
+ });
+ }
+ });
+ if let Some(va) = nav {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+
+ /// `Symbol References` provider — a table of every xref pointing
+ /// at the currently selected symbol (or the cursor VA).
+ pub(crate) fn ui_symbol_references(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Symbol References");
+ ui.small(
+ egui::RichText::new("SymbolTablePlugin · every reference TO the current symbol")
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let target = self
+ .symbol_refs_target
+ .or(self.listing_focus_va)
+ .or(prog.entry);
+ ui.horizontal(|ui| {
+ let mut input = target.map(|v| format!("{v:#x}")).unwrap_or_default();
+ ui.label("Target:");
+ let resp = ui.add(
+ egui::TextEdit::singleline(&mut input)
+ .desired_width(140.0)
+ .hint_text("VA…"),
+ );
+ if resp.lost_focus() {
+ self.symbol_refs_target = parse_address(&input).ok();
+ }
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.symbol_refs_filter)
+ .desired_width(200.0)
+ .hint_text("Substring…"),
+ );
+ 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 {
+ ui.weak("No target — set cursor or type a VA above.");
+ return;
+ };
+ let refs = self.xrefs_to_va(target);
+ let q = self.symbol_refs_filter.to_ascii_lowercase();
+ 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() {
+ return true;
+ }
+ r.preview.to_ascii_lowercase().contains(&q)
+ || 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
+ .as_ref()
+ .and_then(|p| p.display_name_at(va))
+ .map(|s| s.to_string())
+ .unwrap_or_default()
+ };
+ ui.small(format!(
+ "{} reference(s) to {target:#x} · {}",
+ rows.len(),
+ label_at(target)
+ ));
+ let mut goto: Option<u64> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("symrefs_scroll")
+ .max_height(400.0)
+ .show(ui, |ui| {
+ egui::Grid::new("symbol_refs_grid")
+ .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, cls) in &rows {
+ if ui
+ .link(egui::RichText::new(format!("{:#x}", r.from)).monospace())
+ .clicked()
+ {
+ goto = Some(r.from);
+ }
+ ui.label(label_at(r.from));
+ ui.monospace(r.kind);
+ ui.small(cls.as_deref().unwrap_or("—"));
+ ui.label(&r.preview);
+ ui.end_row();
+ }
+ });
+ });
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+
+ /// `EquateTablePlugin` — two-pane: equate groups + per-equate refs.
+ pub(crate) fn ui_equates_table(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Equates Table");
+ ui.small(
+ egui::RichText::new("EquateTablePlugin · symbolic names bound to scalar operands")
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let groups = prog.edits.equate_groups();
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.equates_filter)
+ .desired_width(220.0)
+ .hint_text("Name / value…"),
+ );
+ if ui.button("Add equate at cursor…").clicked() {
+ self.equate_dialog_va = self.listing_focus_va;
+ self.equate_dialog_op = 1;
+ self.equate_dialog_name.clear();
+ self.equate_dialog_value.clear();
+ self.show_equate_dialog = true;
+ }
+ });
+ ui.separator();
+ let q = self.equates_filter.to_ascii_lowercase();
+ let filtered: Vec<(String, i64, usize)> = groups
+ .into_iter()
+ .filter(|(name, val, _)| {
+ if q.is_empty() {
+ return true;
+ }
+ name.to_ascii_lowercase().contains(&q) || format!("{val:#x}").contains(&q)
+ })
+ .collect();
+ if filtered.is_empty() {
+ ui.weak("No equates — use \"Add equate at cursor\" over a scalar operand.");
+ return;
+ }
+ let mut clear: Option<(u64, u8)> = None;
+ let mut goto: Option<u64> = None;
+ ui.columns(2, |cols| {
+ cols[0].strong("Equate");
+ cols[0].separator();
+ egui::ScrollArea::vertical()
+ .id_salt("equates_left_scroll")
+ .max_height(360.0)
+ .show(&mut cols[0], |ui| {
+ egui::Grid::new("equates_groups_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Name");
+ ui.strong("Value");
+ ui.strong("# Refs");
+ ui.end_row();
+ for (name, value, n) in &filtered {
+ let is_sel = self
+ .equates_selected
+ .as_ref()
+ .map(|(sn, sv)| sn == name && *sv == *value)
+ .unwrap_or(false);
+ let text = if is_sel {
+ egui::RichText::new(name).strong()
+ } else {
+ egui::RichText::new(name)
+ };
+ if ui.selectable_label(is_sel, text).clicked() {
+ self.equates_selected = Some((name.clone(), *value));
+ }
+ ui.monospace(format!("{value:#x}"));
+ ui.monospace(format!("{n}"));
+ ui.end_row();
+ }
+ });
+ });
+ cols[1].strong("References");
+ cols[1].separator();
+ let sel = self.equates_selected.clone();
+ let refs: Vec<(u64, u8, i64)> = match sel {
+ Some((name, _)) => prog.edits.equate_references(&name),
+ None => Vec::new(),
+ };
+ egui::ScrollArea::vertical()
+ .id_salt("equates_right_scroll")
+ .max_height(360.0)
+ .show(&mut cols[1], |ui| {
+ if refs.is_empty() {
+ ui.weak("Select an equate on the left to see its references.");
+ } else {
+ egui::Grid::new("equate_refs_grid")
+ .num_columns(4)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Ref Addr");
+ ui.strong("Op");
+ ui.strong("Value");
+ ui.strong("Del");
+ ui.end_row();
+ for (va, op, value) in refs {
+ if ui
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .clicked()
+ {
+ goto = Some(va);
+ }
+ ui.monospace(format!("{op}"));
+ ui.monospace(format!("{value:#x}"));
+ if ui.small_button("Del").clicked() {
+ clear = Some((va, op));
+ }
+ ui.end_row();
+ }
+ });
+ }
+ });
+ });
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ if let Some((va, op)) = clear {
+ let _ = self.set_equate(va, op, "", 0);
+ }
+ }
+
+ /// `FunctionTagPlugin` — two-pane: assigned tags for current fn,
+ /// All Tags with counts.
+ pub(crate) fn ui_function_tags(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Function Tags");
+ ui.small(
+ egui::RichText::new("FunctionTagPlugin · per-function labels + universe of tags")
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let entry = self.focused_function_entry.or_else(|| {
+ self.listing_focus_va
+ .and_then(|va| Some(decompile_entry_for_va(prog, va)))
+ });
+ let entry_label = entry
+ .and_then(|va| self.program.as_ref()?.display_function_name_at(va))
+ .unwrap_or_else(|| "<no function>".into());
+ ui.horizontal(|ui| {
+ ui.label("Function:");
+ ui.monospace(&entry_label);
+ if let Some(e) = entry {
+ ui.monospace(format!("@ {e:#x}"));
+ }
+ });
+ ui.separator();
+ // Left = assigned tags (with remove); right = all tags (add / delete).
+ let assigned: Vec<String> = entry
+ .map(|e| prog.edits.function_tags_for(e))
+ .unwrap_or_default();
+ let all_tags: Vec<(String, usize)> = prog.edits.all_tag_counts();
+ let mut remove_from_entry: Option<String> = None;
+ let mut add_to_entry: Option<String> = None;
+ let mut delete_globally: Option<String> = None;
+ ui.columns(2, |cols| {
+ cols[0].strong("Assigned to this function");
+ cols[0].separator();
+ if assigned.is_empty() {
+ cols[0].weak("No tags — add one from the right pane, or type a new tag.");
+ } else {
+ for t in &assigned {
+ cols[0].horizontal(|ui| {
+ ui.monospace(t);
+ if ui.small_button("Remove").clicked() {
+ remove_from_entry = Some(t.clone());
+ }
+ });
+ }
+ }
+
+ cols[1].strong("All Tags");
+ cols[1].separator();
+ cols[1].horizontal(|ui| {
+ ui.label("New:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.function_tags_new_input)
+ .desired_width(160.0)
+ .hint_text("Tag name…"),
+ );
+ if ui.button("Add").clicked() {
+ let name = self.function_tags_new_input.trim().to_string();
+ if !name.is_empty() {
+ if entry.is_some() {
+ add_to_entry = Some(name);
+ } else {
+ let _ = self.create_tag(name);
+ }
+ self.function_tags_new_input.clear();
+ }
+ }
+ });
+ cols[1].horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.function_tags_filter)
+ .desired_width(180.0)
+ .hint_text("Substring…"),
+ );
+ });
+ cols[1].separator();
+ let q = self.function_tags_filter.to_ascii_lowercase();
+ egui::ScrollArea::vertical()
+ .id_salt("all_tags_scroll")
+ .max_height(320.0)
+ .show(&mut cols[1], |ui| {
+ egui::Grid::new("all_tags_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Tag");
+ ui.strong("Uses");
+ ui.strong("Actions");
+ ui.end_row();
+ for (tag, n) in &all_tags {
+ if !q.is_empty() && !tag.to_ascii_lowercase().contains(&q) {
+ continue;
+ }
+ ui.monospace(tag);
+ ui.monospace(format!("{n}"));
+ ui.horizontal(|ui| {
+ if entry.is_some() && ui.small_button("Add").clicked() {
+ add_to_entry = Some(tag.clone());
+ }
+ if ui.small_button("Delete").clicked() {
+ delete_globally = Some(tag.clone());
+ }
+ });
+ ui.end_row();
+ }
+ });
+ });
+ });
+ if let (Some(tag), Some(e)) = (remove_from_entry, entry) {
+ let _ = self.remove_function_tag(e, &tag);
+ }
+ if let (Some(tag), Some(e)) = (add_to_entry, entry) {
+ let _ = self.add_function_tag(e, tag);
+ }
+ if let Some(tag) = delete_globally {
+ let _ = self.delete_tag_everywhere(&tag);
+ }
+ }
+
+ /// `ReferencesPlugin` — External Programs table. Rendered from
+ /// analyzer-driven `imports_exports` output (PDB symbols, `idata`
+ /// sections, demangled `dllexport` symbols) — never fabricated.
+ pub(crate) fn ui_external_programs(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("External Programs");
+ ui.small(
+ egui::RichText::new("ReferencesPlugin · analyzer-derived imports + exports")
+ .color(muted),
+ );
+ ui.separator();
+ if self.program.is_none() {
+ ui.weak("No program loaded.");
+ return;
+ }
+ let (imports, exports) = self.imports_exports();
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.external_programs_filter)
+ .desired_width(220.0)
+ .hint_text("Name / VA…"),
+ );
+ });
+ ui.separator();
+ let q = self.external_programs_filter.to_ascii_lowercase();
+ let matches = |name: &str, va: u64| {
+ if q.is_empty() {
+ return true;
+ }
+ name.to_ascii_lowercase().contains(&q) || format!("{va:#x}").contains(&q)
+ };
+ let mut goto: Option<u64> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("ext_progs_scroll")
+ .max_height(400.0)
+ .show(ui, |ui| {
+ ui.strong("Imports");
+ egui::Grid::new("ext_imports_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Address");
+ ui.strong("Name");
+ ui.strong("Source");
+ ui.end_row();
+ for (va, name) in imports.iter().filter(|(va, n)| matches(n, *va)) {
+ if ui
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .clicked()
+ {
+ goto = Some(*va);
+ }
+ ui.label(name);
+ ui.monospace(if name.starts_with('.') {
+ "section"
+ } else {
+ "pdb"
+ });
+ ui.end_row();
+ }
+ });
+ ui.add_space(8.0);
+ ui.strong("Exports");
+ egui::Grid::new("ext_exports_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Address");
+ ui.strong("Name");
+ ui.strong("Source");
+ ui.end_row();
+ for (va, name) in exports.iter().filter(|(va, n)| matches(n, *va)) {
+ if ui
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .clicked()
+ {
+ goto = Some(*va);
+ }
+ ui.label(name);
+ ui.monospace(if name.starts_with('.') {
+ "section"
+ } else {
+ "demangle"
+ });
+ ui.end_row();
+ }
+ if imports.is_empty() && exports.is_empty() {
+ ui.weak("No imports/exports — analyzer did not populate any.");
+ ui.end_row();
+ }
+ });
+ });
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+
+ /// `DataTypePreviewPlugin` — preview interpretation of bytes at
+ /// the current cursor under the chosen built-in type.
+ pub(crate) fn ui_data_type_preview(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Data Type Preview");
+ ui.small(
+ egui::RichText::new("DataTypePreviewPlugin · byte interpretation @ cursor")
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let va = match self.listing_focus_va.or(prog.entry) {
+ Some(v) => v,
+ None => {
+ ui.weak("No cursor / entry.");
+ return;
+ }
+ };
+ ui.horizontal(|ui| {
+ ui.label("Cursor VA:");
+ ui.monospace(format!("{va:#x}"));
+ ui.label("Type:");
+ let sel = self.data_type_preview_selected.clone();
+ egui::ComboBox::from_id_salt("dtp_type_combo")
+ .selected_text(&sel)
+ .show_ui(ui, |ui| {
+ for name in BUILTIN_TYPES {
+ if ui.selectable_label(sel.as_str() == *name, *name).clicked() {
+ self.data_type_preview_selected = (*name).into();
+ }
+ }
+ });
+ });
+ ui.separator();
+ let bytes = prog.read_va(va, 16).unwrap_or_default();
+ let hex: String = bytes.iter().map(|b| format!("{b:02x} ")).collect();
+ ui.monospace(format!("bytes: {}", hex.trim_end()));
+ ui.separator();
+ egui::Grid::new("dtp_grid")
+ .num_columns(2)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Interpretation");
+ ui.strong("Preview");
+ ui.end_row();
+ for (name, preview) in preview_all(&bytes) {
+ ui.monospace(name);
+ ui.monospace(preview);
+ ui.end_row();
+ }
+ });
+ }
+
+ /// `ComputeChecksumsPlugin` — CRC-32 / Adler-32 / Fletcher / raw
+ /// sum panels over the loaded image or a chosen block.
+ pub(crate) fn ui_checksum_generator(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Checksum Generator");
+ ui.small(
+ egui::RichText::new("ComputeChecksumsPlugin · CRC-32 / Adler-32 / Fletcher / sums")
+ .color(muted),
+ );
+ ui.separator();
+ let block_names: Vec<String> = self
+ .program
+ .as_ref()
+ .map(|p| p.blocks.iter().map(|b| b.name.clone()).collect())
+ .unwrap_or_default();
+ let mut run: Option<ChecksumMode> = None;
+ ui.horizontal(|ui| {
+ if ui.button("Whole image").clicked() {
+ run = Some(ChecksumMode::WholeImage);
+ }
+ ui.label(egui::RichText::new("or block:").color(muted));
+ for name in &block_names {
+ if ui.small_button(name).clicked() {
+ run = Some(ChecksumMode::Section(name.clone()));
+ }
+ }
+ });
+ if let Some(mode) = run {
+ let _ = self.compute_checksums(mode);
+ }
+ ui.separator();
+ match &self.checksum_last {
+ None => {
+ ui.weak("No checksum computed yet — click Whole image or a block above.");
+ }
+ Some(r) => {
+ egui::Grid::new("checksum_grid")
+ .num_columns(2)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Target");
+ ui.label(&r.target);
+ ui.end_row();
+ ui.strong("Length");
+ ui.monospace(format!("{}", r.len));
+ ui.end_row();
+ ui.strong("CRC-32 (IEEE)");
+ ui.monospace(format!("{:#010x}", r.crc32));
+ ui.end_row();
+ ui.strong("Adler-32");
+ ui.monospace(format!("{:#010x}", r.adler32));
+ ui.end_row();
+ ui.strong("Sum-8");
+ ui.monospace(format!("{:#x}", r.sum8));
+ ui.end_row();
+ ui.strong("Sum-16");
+ ui.monospace(format!("{:#x}", r.sum16));
+ ui.end_row();
+ ui.strong("Sum-32");
+ ui.monospace(format!("{:#x}", r.sum32));
+ ui.end_row();
+ ui.strong("Fletcher-16");
+ ui.monospace(format!("{:#010x}", r.fletcher16));
+ ui.end_row();
+ ui.strong("Fletcher-32");
+ ui.monospace(format!("{:#018x}", r.fletcher32));
+ ui.end_row();
+ });
+ }
+ }
+ }
+}
diff --git a/crates/ghidrust-gui/src/app/tests.rs b/crates/ghidrust-gui/src/app/tests.rs
new file mode 100644
index 0000000..056e0b7
--- /dev/null
+++ b/crates/ghidrust-gui/src/app/tests.rs
@@ -0,0 +1,1509 @@
+//! Headless / structural integration tests for the GUI app.
+#![cfg(test)]
+
+use super::*;
+use crate::checksum::ChecksumMode;
+use crate::debugger::DebuggerPane;
+use crate::decomp_tokens::line_for_va as decomp_line_for_va;
+use crate::events::{GhidrustEvent, MutationKind};
+use crate::graphs::FunctionGraphLayout;
+use crate::menu_actions::{
+ address_table_hits, listing_index_at_or_before, processor_info, STAGE0_MAX_INSNS,
+};
+use crate::network::NetworkPane;
+use ghidrust_core::{fixture_path, ANALYZER_NAMES, BUILTIN_TYPES};
+
+#[test]
+fn shell_has_required_menus_and_panes() {
+ let menus = GhidrustApp::shell_menus();
+ // top-level menus (from `docking.tool.ToolConstants`).
+ for m in [
+ "File",
+ "Edit",
+ "Analysis",
+ "Navigation",
+ "Search",
+ "Select",
+ "Tools",
+ "Graph",
+ "Window",
+ "Help",
+ ] {
+ assert!(menus.contains(&m), "missing menu {m}");
+ }
+ let panes = GhidrustApp::shell_panes();
+ for p in [
+ "Project Tree",
+ "Program Tree",
+ "Symbol Tree",
+ "Overview",
+ "Listing",
+ "Decompiler",
+ "Console",
+ ] {
+ assert!(panes.contains(&p), "missing pane {p}");
+ }
+ // Project Tree ≠ Program Tree
+ assert_ne!(
+ panes.iter().position(|p| *p == "Project Tree"),
+ panes.iter().position(|p| *p == "Program Tree")
+ );
+ }
+
+ /// every provider must be enumerated in
+ /// `shell_panes` so the Window menu / structural tests can enforce provider visibility.
+ #[test]
+ fn shell_panes_enumerates_full_codebrowser_catalog() {
+ let panes = GhidrustApp::shell_panes();
+ // 28 default `.tool` providers + a few off-layout ones. See
+ // internal UI notes § 1.1 / § 1.2 for the source of truth.
+ for expected in [
+ "Program Trees",
+ "Symbol Tree",
+ "Data Type Manager",
+ "Listing",
+ "Decompile",
+ "Bytes",
+ "Defined Data",
+ "Defined Strings",
+ "Equates Table",
+ "External Programs",
+ "Functions",
+ "Relocation Table",
+ "Data Type Preview",
+ "Disassembled View",
+ "Console",
+ "Bookmarks",
+ "Script Manager",
+ "Memory Map",
+ "Function Graph",
+ "Register Manager",
+ "Symbol Table",
+ "Symbol References",
+ "Checksum Generator",
+ "Function Tags",
+ "Comments",
+ "Python",
+ "Entropy",
+ "Overview",
+ // Off-layout, reached via Window menu
+ "Function Call Trees",
+ "Function Call Graph",
+ "Text Editor",
+ ] {
+ assert!(
+ panes.contains(&expected),
+ "missing provider `{expected}` in shell_panes; full list = {panes:?}"
+ );
+ }
+ }
+
+ /// Back / Forward history is wired.
+ #[test]
+ fn nav_history_records_and_navigates() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ assert!(!app.can_nav_back());
+ assert!(!app.can_nav_forward());
+
+ // Two goto calls (both valid VAs inside the loaded listing window)
+ // put one entry in the Back history.
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ // A second VA that is inside the loaded listing so re-disassemble isn't required.
+ let second_va = app
+ .listing
+ .iter()
+ .map(|i| i.address)
+ .find(|&va| va > entry)
+ .unwrap_or(entry + 1);
+ app.goto_address_str(&format!("{entry:#x}"))
+ .expect("goto entry");
+ app.goto_address_str(&format!("{second_va:#x}"))
+ .expect("goto second");
+ assert!(app.can_nav_back(), "back should be available after 2 gotos");
+ assert!(!app.can_nav_forward());
+
+ // Back → returns to entry
+ assert!(app.nav_back(), "nav_back should succeed");
+ assert_eq!(app.listing_focus_va, Some(entry));
+ assert!(app.can_nav_forward());
+
+ // Forward → returns to second_va
+ assert!(app.nav_forward(), "nav_forward should succeed");
+ assert_eq!(app.listing_focus_va, Some(second_va));
+ }
+
+ /// Bookmarks pane model is real (5 kinds; add/delete flow).
+ #[test]
+ fn bookmark_model_add_delete_and_nav() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ assert!(app.bookmarks.is_empty());
+
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.add_bookmark(entry, BookmarkKind::Note, "user", "entry point");
+ app.add_bookmark(entry + 0x10, BookmarkKind::Analysis, "core", "hot loop");
+ assert_eq!(app.bookmarks.len(), 2);
+ assert!(app.is_pane_open(PaneKind::Bookmarks));
+
+ // Next / Prev bookmark navigation works.
+ app.listing_focus_va = Some(entry);
+ app.nav_next_bookmark();
+ assert_eq!(app.listing_focus_va, Some(entry + 0x10));
+ app.nav_prev_bookmark();
+ assert_eq!(app.listing_focus_va, Some(entry));
+
+ app.delete_bookmark(0);
+ assert_eq!(app.bookmarks.len(), 1);
+ assert_eq!(app.bookmarks[0].va, entry + 0x10);
+
+ // All 5 bookmark kinds are colourable.
+ for k in BookmarkKind::ALL {
+ let c = k.color();
+ assert!(c.a() > 0 && (c.r() as u16 + c.g() as u16 + c.b() as u16) > 0);
+ }
+ }
+
+ /// plugin event bus emits CursorMoved on goto and Mutation on bookmark ops.
+ #[test]
+ fn event_bus_publishes_cursor_and_mutation_events() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ // Loading emits ProgramActivated; drain baseline.
+ let boot = app.drain_events();
+ assert!(
+ boot.iter()
+ .any(|e| matches!(e, GhidrustEvent::ProgramActivated { .. })),
+ "load_binary must publish ProgramActivated: {boot:?}"
+ );
+
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.goto_address_str(&format!("{entry:#x}")).expect("goto");
+ let evs = app.drain_events();
+ assert!(
+ evs.iter()
+ .any(|e| matches!(e, GhidrustEvent::CursorMoved { .. })),
+ "goto_address_str must publish CursorMoved: {evs:?}"
+ );
+
+ app.add_bookmark(entry, BookmarkKind::Note, "test", "hi");
+ let evs = app.drain_events();
+ assert!(
+ evs.iter().any(|e| matches!(
+ e,
+ GhidrustEvent::ProgramMutated {
+ kind: MutationKind::BookmarkAdded { .. }
+ }
+ )),
+ "add_bookmark must publish BookmarkAdded: {evs:?}"
+ );
+
+ app.delete_bookmark(0);
+ let evs = app.drain_events();
+ assert!(
+ evs.iter().any(|e| matches!(
+ e,
+ GhidrustEvent::ProgramMutated {
+ kind: MutationKind::BookmarkRemoved { .. }
+ }
+ )),
+ "delete_bookmark must publish BookmarkRemoved: {evs:?}"
+ );
+
+ // Drain again → empty.
+ assert!(app.drain_events().is_empty());
+ }
+
+ /// provider pane toggles are per-kind and persist through frames.
+ #[test]
+ fn toggle_pane_state_persists() {
+ let mut app = GhidrustApp::headless();
+ for k in PaneKind::ALL {
+ assert!(
+ !app.is_pane_open(*k),
+ "pane {:?} default should be closed",
+ k
+ );
+ }
+ app.toggle_pane(PaneKind::MemoryMap, true);
+ app.toggle_pane(PaneKind::SymbolTable, true);
+ assert!(app.is_pane_open(PaneKind::MemoryMap));
+ assert!(app.is_pane_open(PaneKind::SymbolTable));
+ assert!(!app.is_pane_open(PaneKind::FunctionGraph));
+ app.toggle_pane(PaneKind::MemoryMap, false);
+ assert!(!app.is_pane_open(PaneKind::MemoryMap));
+ }
+
+ #[test]
+ fn project_tree_open_and_status_via_shipped_apis() {
+ let dir = std::env::temp_dir().join(format!("ghidrust_ptree_{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut app = GhidrustApp::headless();
+ app.project_dir_input = dir.display().to_string();
+ app.project_name_input = "TreeUX".into();
+ app.create_project().expect("create");
+ assert!(app.show_project_tree);
+
+ app.path_input = fixture_path("tiny_x64.pe").display().to_string();
+ app.import_into_project().expect("import tiny");
+ app.path_input = fixture_path("analysis_lab.pe").display().to_string();
+ app.import_into_project().expect("import lab");
+
+ let tree = app.project_tree_model().expect("tree model");
+ assert_eq!(tree.project_name, "TreeUX");
+ assert_eq!(tree.files.len(), 2);
+ assert!(tree.files.iter().any(|f| f.active));
+ assert!(tree.files.iter().all(|f| !f.has_saved_analysis));
+ assert_eq!(tree.files[0].status_label(), "Not analyzed");
+
+ let lab_id = tree
+ .files
+ .iter()
+ .find(|f| f.display_name.contains("analysis_lab"))
+ .map(|f| f.id.clone())
+ .expect("lab id");
+ app.open_from_tree(&lab_id).expect("open from tree");
+ assert_eq!(app.active_file_id.as_deref(), Some(lab_id.as_str()));
+ assert!(app.program.is_some());
+ let tree2 = app.project_tree_model().unwrap();
+ assert!(tree2.files.iter().any(|f| f.id == lab_id && f.active));
+
+ for (i, info) in app.analyzer_infos.iter().enumerate() {
+ app.analyzer_enabled[i] = matches!(
+ info.name.as_str(),
+ "Function Start Search" | "Embedded Media"
+ );
+ }
+ // Analyze from tree opens options dialog (does not run yet).
+ app.analyze_from_tree(&lab_id)
+ .expect("open analyze options");
+ assert!(app.show_analysis_dialog);
+ assert_eq!(
+ app.pending_analyze_file_id.as_deref(),
+ Some(lab_id.as_str())
+ );
+ app.use_gpu_experimental = true;
+ app.begin_analysis_job().expect("begin");
+ assert!(app.analysis_job.is_some());
+ assert!(app.analysis_progress_fraction().is_some());
+ while app.analysis_job.is_some() {
+ app.step_analysis_job_blocking().expect("step");
+ }
+ assert!(app.analysis_progress_fraction().is_none());
+ let tree3 = app.project_tree_model().unwrap();
+ let lab_row = tree3.files.iter().find(|f| f.id == lab_id).unwrap();
+ assert!(lab_row.has_saved_analysis, "{lab_row:?}");
+ assert_eq!(lab_row.status_label(), "Analyzed");
+
+ // Second run of status query consistent
+ let tree4 = app.project_tree_model().unwrap();
+ assert_eq!(
+ tree3
+ .files
+ .iter()
+ .map(|f| f.has_saved_analysis)
+ .collect::<Vec<_>>(),
+ tree4
+ .files
+ .iter()
+ .map(|f| f.has_saved_analysis)
+ .collect::<Vec<_>>()
+ );
+
+ // Delete requires confirm: request only sets pending; confirm removes.
+ app.request_delete_file(&lab_id);
+ assert!(app.pending_delete.is_some());
+ app.cancel_delete_file();
+ assert!(app.pending_delete.is_none());
+ assert_eq!(app.project_tree_model().unwrap().files.len(), 2);
+ app.request_delete_file(&lab_id);
+ app.confirm_delete_file().expect("confirm delete");
+ assert!(app.pending_delete.is_none());
+ let after = app.project_tree_model().unwrap();
+ assert_eq!(after.files.len(), 1);
+ assert!(!after.files.iter().any(|f| f.id == lab_id));
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn headless_load_and_analyze_uses_core() {
+ let mut app = GhidrustApp::headless();
+ assert_eq!(app.theme, ThemeMode::Dark);
+ app.theme = app.theme.toggle();
+ assert_eq!(app.theme, ThemeMode::Light);
+
+ let pe = fixture_path("tiny_x64.pe");
+ app.load_binary(&pe).expect("load");
+ assert!(app.listing.iter().any(|i| i.mnemonic == "push"));
+
+ for (i, info) in app.analyzer_infos.iter().enumerate() {
+ app.analyzer_enabled[i] = matches!(
+ info.name.as_str(),
+ "ASCII Strings" | "WindowsPE x86 PE RTTI Analyzer"
+ );
+ }
+ app.run_selected_analysis().expect("analyze");
+ assert!(app.rtti.classes.iter().any(|c| c.name == "Widget"));
+ assert!(!app.strings.is_empty());
+ assert_eq!(app.analyzer_infos.len(), ANALYZER_NAMES.len());
+ }
+
+ #[test]
+ fn headless_stage0_decompiler_wires_on_focus() {
+ // Stage-1 is the GUI default. The old assertion demanded a
+ // Stage-0-style `void foo` / `block_N` marker; Stage-1 emits typed
+ // return values (e.g. `uint32_t FUN_..(void)`) so we accept either
+ // stage marker plus the Stage-1 self-identification header.
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ assert!(
+ !app.decomp_text.is_empty(),
+ "load should seed decompiler text"
+ );
+ assert!(!app.decomp_text.contains("Not yet implemented"));
+
+ let va = app.listing[0].address;
+ app.refresh_decompiler_at(va);
+ assert!(app.decomp_entry.is_some());
+ let text = &app.decomp_text;
+ assert!(
+ text.contains("void ")
+ || text.contains("uint")
+ || text.contains("int32_t")
+ || text.contains("int64_t")
+ || text.contains("block_"),
+ "expected typed function header or block label:\n{text}"
+ );
+
+ let entry = app.decomp_entry.unwrap();
+ app.focus_function(entry);
+ assert_eq!(app.center, CenterPane::Decompiler);
+ assert_eq!(app.listing_focus_va, Some(entry));
+ assert!(!app.decomp_text.is_empty());
+ }
+
+ #[test]
+ fn headless_project_import_analyze_save() {
+ let dir = std::env::temp_dir().join(format!("ghidrust_gui_proj_{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut app = GhidrustApp::headless();
+ app.project_dir_input = dir.display().to_string();
+ app.project_name_input = "GuiTest".into();
+ app.create_project().expect("create");
+ app.path_input = fixture_path("analysis_lab.pe").display().to_string();
+ app.import_into_project().expect("import");
+ assert!(app.program.is_some());
+ for (i, info) in app.analyzer_infos.iter().enumerate() {
+ app.analyzer_enabled[i] = matches!(
+ info.name.as_str(),
+ "Function Start Search" | "Embedded Media"
+ );
+ }
+ app.run_selected_analysis().expect("analyze");
+ app.save_results().expect("save");
+ let id = app.active_file_id.clone().unwrap();
+ let proj = app.project.as_ref().unwrap();
+ assert!(proj.analysis_path(&id).is_file());
+ assert!(proj.listing_export_path(&id).is_file());
+ // reopen
+ let mut app2 = GhidrustApp::headless();
+ app2.project_dir_input = dir.display().to_string();
+ app2.open_project().expect("reopen");
+ assert!(app2.program.is_some());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn source_embeds_m3_and_menus() {
+ // Structural: shipped source contains theme toggle + menus (fallback evidence).
+ let src = [
+ include_str!("mod.rs"),
+ include_str!("menus.rs"),
+ include_str!("session_api.rs"),
+ include_str!("side_trees.rs"),
+ include_str!("table_panes.rs"),
+ include_str!("dialogs.rs"),
+ include_str!("analysis_job.rs"),
+ include_str!("project_io.rs"),
+ include_str!("center_panes.rs"),
+ include_str!("shell_chrome.rs"),
+ ]
+ .join("\n");
+ let menus = include_str!("menus.rs");
+ assert!(src.contains("Theme: Dark") || src.contains("ThemeMode") || menus.contains("ThemeMode"));
+ assert!(menus.contains("menu_button(\"File\""));
+ assert!(src.contains("Program Tree"));
+ assert!(src.contains("Project Tree") || src.contains("project_tree"));
+ assert!(src.contains("Decompiler"));
+ assert!(src.contains("refresh_decompiler_at") || src.contains("stage0_pseudo_c"));
+ assert!(src.contains("focus_function"));
+ assert!(src.contains("Stage-0"));
+ assert!(src.contains("decomp_scroll") || src.contains("decomp_text"));
+ assert!(src.contains("ASCII Strings"));
+ assert!(src.contains("Analyzed") || src.contains("has_saved_analysis"));
+ assert!(src.contains("analyze_from_tree") || src.contains("small_button(\"Analyze\")"));
+ assert!(
+ src.contains("Browse") || src.contains("browse_binary_path") || src.contains("rfd::")
+ );
+ assert!(src.contains("pending_delete") || src.contains("Delete from project"));
+ assert!(src.contains("use_gpu_experimental") || src.contains("GPU experimental"));
+ assert!(src.contains("analyzer_supports_gpu"));
+ assert!(src.contains("CPU only") || src.contains("\"GPU\""));
+ assert!(src.contains("m3_linear_progress") || src.contains("Analysis progress"));
+ assert!(src.contains("begin_analysis_job") || src.contains("Run Analysis"));
+ assert!(src.contains("Overview") || src.contains("ui_overview"));
+ assert!(src.contains("show_rows") || src.contains("rtti_filtered_idx"));
+ assert!(src.contains("analysis_done_banner") || src.contains("Analysis complete"));
+ assert!(src.contains("double_clicked") && src.contains("open_id"));
+ assert!(src.contains("show_startup_picker") || src.contains("ui_startup_picker"));
+ assert!(src.contains("recent_projects") || src.contains("Open existing project"));
+ // No emoji codepoints in shell sources (Material geometry lives in icons.rs)
+ assert!(!src.contains('\u{1F4C1}'));
+ assert!(!src.contains('\u{25CF}'));
+ assert!(!src.contains('\u{25CB}'));
+ assert!(!src.contains('\u{25B6}'));
+ }
+
+ #[test]
+ fn icons_module_is_material_not_emoji() {
+ let icons = include_str!("../icons.rs");
+ assert!(icons.contains("Material"));
+ assert!(icons.contains("Folder") || icons.contains("folder"));
+ assert!(!icons.contains('\u{1F4C1}'));
+ assert!(!icons.contains('\u{25CF}'));
+ }
+
+ #[test]
+ fn former_menu_stubs_are_wired_not_nyi_only() {
+ let src = include_str!("menus.rs");
+ let app_src = [
+ include_str!("mod.rs"),
+ include_str!("session_api.rs"),
+ include_str!("dialogs.rs"),
+ ]
+ .join("\n");
+ // No remaining nyi for inventoried Edit/Nav/Search/Select/Tools stubs
+ assert!(!src.contains("nyi(\"Edit → Undo\")"));
+ assert!(!src.contains("nyi(\"Edit → Redo\")"));
+ assert!(!src.contains("nyi(\"Edit → Clear selection\")"));
+ assert!(!src.contains("nyi(\"Navigation → Go to address\")"));
+ assert!(!src.contains("nyi(\"Search → Search memory\")"));
+ assert!(!src.contains("nyi(\"Search → Search program text\")"));
+ assert!(!src.contains("nyi(\"Select → Select all\")"));
+ assert!(!src.contains("nyi(\"Tools → Processor options\")"));
+ // Real handlers present (menu calls and/or App methods)
+ let both = format!("{src}\n{app_src}");
+ assert!(both.contains("edit_undo"));
+ assert!(both.contains("edit_redo"));
+ assert!(both.contains("edit_clear_selection"));
+ assert!(both.contains("goto_address_str") || both.contains("show_goto_dialog"));
+ assert!(both.contains("run_search_memory"));
+ assert!(both.contains("run_search_text"));
+ assert!(both.contains("select_all_listing"));
+ assert!(both.contains("show_processor_dialog"));
+ }
+
+ #[test]
+ fn menu_actions_goto_search_select_on_loaded_program() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ assert!(!app.listing.is_empty());
+
+ app.select_all_listing();
+ assert!(!app.listing_selection.is_empty());
+ assert!(app.listing_selection.contains(0));
+
+ app.edit_clear_selection();
+ assert!(app.listing_selection.is_empty());
+
+ app.select_all_listing();
+ app.edit_undo();
+ assert!(app.listing_selection.is_empty());
+ app.edit_redo();
+ assert!(!app.listing_selection.is_empty());
+
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.goto_address_str(&format!("{entry:#x}")).expect("goto");
+ assert_eq!(app.listing_focus_va, Some(entry));
+ assert_eq!(app.center, CenterPane::Listing);
+
+ app.search_memory_input = "55 48 89 e5".into();
+ app.run_search_memory().expect("mem search");
+ assert!(!app.memory_hits.is_empty());
+ assert!(app.show_search_results);
+
+ app.search_text_input = "push".into();
+ app.run_search_text().expect("text search");
+ assert!(!app.text_hits.is_empty());
+
+ app.show_processor_dialog = true;
+ let info = processor_info(app.program.as_ref().unwrap());
+ assert!(info.language.contains("x86"));
+ }
+
+ // ─── token model, listing sync, view filter, next/prev fn ───
+
+ #[test]
+ fn decompiler_tokens_are_populated_and_cross_highlight() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.refresh_decompiler_at(entry);
+ assert!(
+ !app.decomp_lines.is_empty(),
+ "token cache must be populated after refresh_decompiler_at"
+ );
+ // Default GUI stage is Stage-1; the emitter drops
+ // `block_N:` labels in favour of structured regions. Assert only
+ // that we see at least one keyword token — the shape common to
+ // every stage.
+ let all_tokens: Vec<&TokenKind> = app
+ .decomp_lines
+ .iter()
+ .flat_map(|l| l.tokens.iter().map(|t| &t.kind))
+ .collect();
+ assert!(
+ all_tokens.iter().any(|k| matches!(k, TokenKind::Keyword)),
+ "expected at least one Keyword (void/return/etc)"
+ );
+ // Cross-highlight line should be recomputable and match what the
+ // decoder found for the entry VA (may be None if Stage-1 emit
+ // stripped per-line addresses, but the field remains consistent).
+ let ln = decomp_line_for_va(&app.decomp_lines, entry);
+ assert_eq!(app.decomp_cross_line, ln);
+ }
+
+ #[test]
+ fn navigate_next_prev_function_wraps() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("analysis_lab.pe"))
+ .expect("load");
+ // Fake up two functions if the analyzer didn't produce any yet.
+ if app.program.as_ref().unwrap().analysis.functions.is_empty() {
+ let prog = app.program.as_mut().unwrap();
+ let base = prog.entry.unwrap_or(prog.image_base);
+ prog.analysis
+ .functions
+ .push(ghidrust_core::FunctionInfo::new(base, base + 0x10, "fn_a"));
+ prog.analysis
+ .functions
+ .push(ghidrust_core::FunctionInfo::new(
+ base + 0x40,
+ base + 0x50,
+ "fn_b",
+ ));
+ }
+ let entries: Vec<u64> = app
+ .program
+ .as_ref()
+ .unwrap()
+ .analysis
+ .functions
+ .iter()
+ .map(|f| f.entry)
+ .collect();
+ let mut sorted = entries.clone();
+ sorted.sort();
+ let first = sorted[0];
+ app.listing_focus_va = Some(first);
+ app.nav_next_function();
+ // Cursor should have moved to another function entry (or wrapped).
+ assert!(sorted.contains(&app.listing_focus_va.unwrap()));
+ }
+
+ #[test]
+ fn program_tree_view_filter_hides_addresses() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ // Grab a block name & VA.
+ let (block_name, block_va) = {
+ let p = app.program.as_ref().unwrap();
+ let b = p.blocks.first().unwrap();
+ (b.name.clone(), b.va)
+ };
+ assert!(app.addr_in_view(block_va));
+ let mut set = BTreeSet::new();
+ set.insert("__does_not_exist__".to_string());
+ app.set_listing_view(Some(set));
+ assert!(!app.addr_in_view(block_va), "filter set must hide addr");
+ app.add_to_view(block_name.clone());
+ assert!(app.addr_in_view(block_va));
+ app.remove_from_view(&block_name);
+ assert!(!app.addr_in_view(block_va));
+ app.clear_view_filter();
+ assert!(app.addr_in_view(block_va));
+ }
+
+ #[test]
+ fn imports_exports_are_honest_empty_or_analyzer_derived() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let (imports, exports) = app.imports_exports();
+ // Never panics; results are analyzer-driven not fabricated.
+ for (va, _name) in imports.iter().chain(exports.iter()) {
+ // If any row exists it must be a plausible in-image VA.
+ let in_program = app
+ .program
+ .as_ref()
+ .map(|p| p.contains_va(*va))
+ .unwrap_or(false);
+ assert!(in_program || *va == 0);
+ }
+ }
+
+ // ─── rename / retype / comment / signature / type ───
+
+ #[test]
+ fn rename_persists_and_reflects_in_analysis() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ // Attach a synthetic function so we have a rename target.
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ {
+ let prog = app.program.as_mut().unwrap();
+ prog.analysis
+ .functions
+ .push(ghidrust_core::FunctionInfo::new(
+ entry,
+ entry + 0x10,
+ "FUN_original",
+ ));
+ }
+ app.rename_at(entry, "my_main").expect("rename");
+ let p = app.program.as_ref().unwrap();
+ assert_eq!(p.edits.rename_at(entry), Some("my_main"));
+ assert_eq!(
+ p.function_at(entry).map(|f| f.name.as_str()),
+ Some("my_main")
+ );
+ assert_eq!(
+ p.display_function_name_at(entry).as_deref(),
+ Some("my_main")
+ );
+ // Empty rename clears the edit and rejects with error.
+ let err = app.rename_at(entry, "");
+ assert!(err.is_err());
+ }
+
+ #[test]
+ fn retype_and_comment_and_signature_persist() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.retype_at(va, "int32_t").expect("retype");
+ app.set_comment_at(va, CommentKind::Eol, "eol comment")
+ .expect("comment");
+ app.set_comment_at(va, CommentKind::Plate, "plate!")
+ .expect("plate");
+ app.set_function_signature(va, "int foo(char *)")
+ .expect("sig");
+ let p = app.program.as_ref().unwrap();
+ assert_eq!(p.edits.retype_at(va), Some("int32_t"));
+ assert_eq!(
+ p.edits.comment_at(va, CommentKind::Eol),
+ Some("eol comment")
+ );
+ assert_eq!(p.edits.comment_at(va, CommentKind::Plate), Some("plate!"));
+ assert_eq!(
+ p.edits.function_signature(va).map(|s| s.signature.as_str()),
+ Some("int foo(char *)")
+ );
+ }
+
+ #[test]
+ fn commit_params_and_locals_snapshot_analyzer_state() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ {
+ let prog = app.program.as_mut().unwrap();
+ let mut fi = ghidrust_core::FunctionInfo::new(entry, entry + 0x40, "with_params");
+ fi.calling_convention = Some("windowsx64".into());
+ fi.parameters = vec!["rcx".into(), "rdx".into()];
+ fi.stack_locals = vec!["local_10".into(), "local_18".into()];
+ prog.analysis.functions.push(fi);
+ }
+ app.commit_params_return(entry).expect("commit params");
+ app.commit_locals(entry).expect("commit locals");
+ let sig = app
+ .program
+ .as_ref()
+ .unwrap()
+ .edits
+ .function_signature(entry)
+ .unwrap();
+ assert_eq!(sig.parameters.len(), 2);
+ assert_eq!(sig.locals.len(), 2);
+ assert_eq!(sig.return_type.as_deref(), Some("undefined"));
+ }
+
+ #[test]
+ fn user_types_and_applied_types_persist() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.define_user_type("Widget", "struct Widget { int id; }")
+ .expect("new type");
+ let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.apply_type_at(va, "Widget").expect("apply");
+ let p = app.program.as_ref().unwrap();
+ assert!(p.edits.user_types.contains_key("Widget"));
+ assert_eq!(p.edits.applied_type_at(va), Some("Widget"));
+ }
+
+ #[test]
+ fn dtm_builtins_contain_stage0_types() {
+ for want in [
+ "byte", "word", "dword", "qword", "char", "int", "int32_t", "pointer",
+ ] {
+ assert!(
+ BUILTIN_TYPES.contains(&want),
+ "expected {want} in DTM Built-In archive"
+ );
+ }
+ }
+
+ #[test]
+ fn console_severity_tracks_log_calls() {
+ let mut app = GhidrustApp::headless();
+ // Preseeded with 1 info line.
+ assert_eq!(app.console.len(), 1);
+ assert_eq!(app.console_severity.len(), 1);
+ app.log("info");
+ app.log_warn("warn");
+ app.log_error("boom");
+ assert_eq!(
+ app.console_severity.last().copied(),
+ Some(ConsoleSeverity::Error)
+ );
+ assert!(app
+ .console_severity
+ .iter()
+ .any(|s| *s == ConsoleSeverity::Warn));
+ assert_eq!(app.console.len(), 4);
+ }
+
+ #[test]
+ fn scalar_and_address_hints_extract_first_literal() {
+ assert!(first_scalar_hint("rax, 0x1234").unwrap().contains("0x1234"));
+ assert!(first_scalar_hint("rax, 42").unwrap().contains("dec 42"));
+ assert!(first_address_hint("0x140001000")
+ .unwrap()
+ .contains("0x140001000"));
+ assert!(first_scalar_hint("rax, rbx").is_none());
+ }
+
+ // ─── polish — DTM editing / chooser / persistence ────
+
+ #[test]
+ fn rename_and_delete_user_type_rewrites_applied_types() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.define_user_type("Widget", "Structure\nint id;")
+ .expect("define");
+ app.apply_type_at(va, "Widget").expect("apply");
+
+ // Rename user type must rewrite the applied-types decoration.
+ app.rename_user_type("Widget", "Gadget").expect("rename");
+ let p = app.program.as_ref().unwrap();
+ assert!(p.edits.user_types.contains_key("Gadget"));
+ assert_eq!(p.edits.applied_type_at(va), Some("Gadget"));
+
+ // Delete user type must clear the applied decoration too.
+ app.delete_user_type("Gadget").expect("delete");
+ let p = app.program.as_ref().unwrap();
+ assert!(p.edits.user_types.is_empty());
+ assert!(p.edits.applied_type_at(va).is_none());
+ }
+
+ #[test]
+ fn edit_user_type_supports_rename_and_body_swap() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.define_user_type("Widget", "Structure\nint a;")
+ .expect("define");
+ app.edit_user_type("Widget", "WidgetV2", "Structure\nint a;\nint b;")
+ .expect("edit");
+ let p = app.program.as_ref().unwrap();
+ assert!(!p.edits.user_types.contains_key("Widget"));
+ assert!(p.edits.user_types.contains_key("WidgetV2"));
+ assert!(p.edits.user_type("WidgetV2").unwrap().contains("int b;"));
+ // Editing a non-existent type must fail rather than silently create.
+ assert!(app.edit_user_type("nope", "x", "y").is_err());
+ }
+
+ #[test]
+ fn new_typedef_on_and_pointer_to_register_user_types() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let td = app.new_typedef_on("int32_t").expect("typedef");
+ let pt = app.new_pointer_to("int32_t").expect("pointer");
+ let p = app.program.as_ref().unwrap();
+ assert!(p.edits.user_types.contains_key(&td));
+ assert!(p.edits.user_types.contains_key(&pt));
+ assert!(pt.ends_with('*'));
+ }
+
+ #[test]
+ fn type_chooser_dialog_opens_with_target_va() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ assert!(!app.show_type_chooser_dialog);
+ app.open_type_chooser(Some(va));
+ assert!(app.show_type_chooser_dialog);
+ assert_eq!(app.type_chooser_target_va, Some(va));
+ }
+
+ #[test]
+ fn edit_type_dialog_preloads_body() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.define_user_type("Foo", "Structure\nint x;")
+ .expect("define");
+ app.open_edit_type_dialog("Foo");
+ assert!(app.show_edit_type_dialog);
+ assert_eq!(app.edit_type_dialog_orig_name, "Foo");
+ assert_eq!(app.edit_type_dialog_name, "Foo");
+ assert!(app.edit_type_dialog_body.contains("int x;"));
+ }
+
+ #[test]
+ fn all_five_comment_kinds_render_edits_into_program() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ for k in CommentKind::ALL {
+ app.set_comment_at(va, *k, format!("k={}", k.label()))
+ .expect("comment");
+ }
+ let p = app.program.as_ref().unwrap();
+ for k in CommentKind::ALL {
+ assert_eq!(
+ p.edits.comment_at(va, *k),
+ Some(format!("k={}", k.label()).as_str())
+ );
+ }
+ assert_eq!(p.edits.comments_at(va).len(), CommentKind::ALL.len());
+ }
+
+ #[test]
+ fn program_edits_persist_across_project_save_and_load() {
+ use ghidrust_core::Project;
+
+ let dir =
+ std::env::temp_dir().join(format!("ghidrust_gui_edits_rt_{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let mut proj = Project::create(&dir, "GuiEditRt").expect("proj");
+ let f = proj.import_file(fixture_path("tiny_x64.pe")).unwrap();
+
+ // Session A — apply user edits then save.
+ let mut app = GhidrustApp::headless();
+ app.project = Some(proj);
+ app.active_file_id = Some(f.id.clone());
+ app.load_binary(&app.project.as_ref().unwrap().binary_path(&f))
+ .expect("load");
+ let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.rename_at(va, "session_a_main").expect("rename");
+ app.set_comment_at(va, CommentKind::Plate, "plate!")
+ .expect("comment");
+ app.define_user_type("Widget", "Structure\nint id;")
+ .expect("define");
+ app.apply_type_at(va, "Widget").expect("apply");
+ app.save_results().expect("save");
+
+ // Session B — fresh app, same project, same file.
+ let proj2 = Project::open(&dir).expect("reopen");
+ let mut app2 = GhidrustApp::headless();
+ app2.project = Some(proj2);
+ app2.active_file_id = Some(f.id.clone());
+ let (prog2, _saved) = app2
+ .project
+ .as_ref()
+ .unwrap()
+ .load_program_with_results(&f)
+ .expect("load with results");
+ app2.program = Some(prog2);
+ let p = app2.program.as_ref().unwrap();
+ assert_eq!(p.edits.rename_at(va), Some("session_a_main"));
+ assert_eq!(p.edits.comment_at(va, CommentKind::Plate), Some("plate!"));
+ assert!(p.edits.user_types.contains_key("Widget"));
+ assert_eq!(p.edits.applied_type_at(va), Some("Widget"));
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn edit_events_invalidate_decompiler_cache() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ {
+ let prog = app.program.as_mut().unwrap();
+ prog.analysis
+ .functions
+ .push(ghidrust_core::FunctionInfo::new(entry, entry + 0x20, "fn"));
+ }
+ app.refresh_decompiler_at(entry);
+ assert!(!app.decomp_text.is_empty());
+ // A rename mutation must invalidate cache via drain_events.
+ app.rename_at(entry, "renamed").expect("rename");
+ let _ = app.drain_events();
+ assert!(app.decomp_text.is_empty(), "cache must clear after rename");
+ }
+
+ #[test]
+ fn goto_out_of_window_va_redisassembles_listing() {
+ let mut app = GhidrustApp::headless();
+ // analysis_lab has richer layout; load then go to a VA outside entry window
+ app.load_binary(&fixture_path("analysis_lab.pe"))
+ .expect("load");
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ let first_listing_va = app.listing[0].address;
+ assert_eq!(first_listing_va, entry);
+
+ // Pick a program block VA that is not covered by the entry listing window
+ let window_end = {
+ let last = app.listing.last().unwrap();
+ last.address + u64::from(last.length).max(1)
+ };
+ let outside = app
+ .program
+ .as_ref()
+ .unwrap()
+ .blocks
+ .iter()
+ .map(|b| b.va)
+ .find(|&va| va < first_listing_va || va >= window_end)
+ .expect("need a block VA outside entry listing window");
+
+ // Confirm helper says outside
+ assert!(
+ listing_index_at_or_before(&app.listing, outside).is_none(),
+ "precondition: {outside:#x} must be outside listing [{first_listing_va:#x}.)"
+ );
+
+ app.goto_address_str(&format!("{outside:#x}"))
+ .expect("goto outside");
+ assert_eq!(app.listing_focus_va, Some(outside));
+ assert!(
+ !app.listing.is_empty(),
+ "re-disassemble must produce listing"
+ );
+ assert_eq!(
+ app.listing[0].address, outside,
+ "listing must start at target VA after re-disassemble"
+ );
+ // Selection points at first insn of new window
+ assert_eq!(app.listing_selection.start, Some(0));
+
+ // Memory search hit navigation also refreshes when needed
+ if let Some(hit) = app.memory_hits.first().cloned() {
+ let _ = hit;
+ }
+ app.search_memory_input = "55 48 89 e5".into();
+ app.run_search_memory().expect("mem");
+ assert!(!app.memory_hits.is_empty());
+ let hit_va = app.memory_hits[0].va;
+ // Force listing back to entry-only window
+ app.goto_address_str(&format!("{entry:#x}"))
+ .expect("back to entry");
+ assert_eq!(app.listing[0].address, entry);
+ // Navigate to memory hit (may be same or different region)
+ app.goto_address_str(&format!("{hit_va:#x}"))
+ .expect("goto hit");
+ assert!(
+ app.listing.iter().any(|i| i.address == hit_va
+ || (i.address <= hit_va && hit_va < i.address + u64::from(i.length))),
+ "listing must cover hit VA {hit_va:#x} after goto; first={:#x}",
+ app.listing[0].address
+ );
+ }
+
+ // ─── tables, xrefs, equates, tags, search dialogs ────
+
+ #[test]
+ fn xrefs_to_and_from_return_honest_rows_on_fixture() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("analysis_lab.pe"))
+ .expect("load");
+ // xrefs_from at entry decodes and never fabricates.
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ let from = app.xrefs_from_va(entry);
+ for r in &from {
+ assert!(app.program.as_ref().unwrap().contains_va(r.to));
+ assert!(r.from >= entry);
+ }
+
+ // Inject a fake reference so xrefs_to_va picks it up deterministically.
+ {
+ let prog = app.program.as_mut().unwrap();
+ prog.analysis.references.push(ghidrust_core::ReferenceInfo {
+ from: prog.image_base + 0x100,
+ to: entry,
+ kind: "call".into(),
+ });
+ }
+ let to = app.xrefs_to_va(entry);
+ assert!(to.iter().any(|r| r.kind == "call"));
+ assert!(to.iter().all(|r| r.to == entry));
+ }
+
+ #[test]
+ fn set_equate_and_edit_events_fan_out() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.set_equate(va, 1, "SW_HIDE", 0).expect("set equate");
+ let p = app.program.as_ref().unwrap();
+ assert_eq!(
+ p.edits.equate_at(va, 1).map(|e| e.name.as_str()),
+ Some("SW_HIDE")
+ );
+ assert_eq!(p.edits.equate_at(va, 1).map(|e| e.value), Some(0));
+ // Groups & references consistent.
+ let groups = p.edits.equate_groups();
+ assert!(groups.iter().any(|(n, _, _)| n == "SW_HIDE"));
+ // Setting empty name clears it.
+ app.set_equate(va, 1, "", 0).expect("clear");
+ assert!(app
+ .program
+ .as_ref()
+ .unwrap()
+ .edits
+ .equate_at(va, 1)
+ .is_none());
+ }
+
+ #[test]
+ fn function_tags_add_remove_delete_via_app() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.add_function_tag(entry, "MALLOC").expect("add");
+ app.add_function_tag(entry, "SANITIZED").expect("add");
+ let p = app.program.as_ref().unwrap();
+ assert!(p.edits.function_has_tag(entry, "MALLOC"));
+ assert!(p.edits.function_has_tag(entry, "SANITIZED"));
+ assert!(p.edits.all_function_tags.contains("MALLOC"));
+ app.remove_function_tag(entry, "MALLOC").expect("remove");
+ assert!(!app
+ .program
+ .as_ref()
+ .unwrap()
+ .edits
+ .function_has_tag(entry, "MALLOC"));
+ // Delete-everywhere strips from universe.
+ app.delete_tag_everywhere("SANITIZED").expect("delete");
+ assert!(!app
+ .program
+ .as_ref()
+ .unwrap()
+ .edits
+ .all_function_tags
+ .contains("SANITIZED"));
+ }
+
+ #[test]
+ fn search_scalars_dialog_runs_range_over_listing() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.search_scalars_min = "0".into();
+ app.search_scalars_max = "0xffff".into();
+ app.run_search_scalars().expect("scalars");
+ // Fixture may or may not include a scalar in this range; the runner
+ // must still succeed and populate text_hits deterministically.
+ assert!(app.show_search_results);
+ }
+
+ #[test]
+ fn search_instruction_patterns_filters_listing() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ // tiny_x64 has a `push rbp` prologue; filter should hit it.
+ app.search_insn_mnemonic = "push".into();
+ app.search_insn_operands.clear();
+ app.run_search_instruction_patterns().expect("insn");
+ assert!(!app.text_hits.is_empty());
+ assert!(app.text_hits.iter().any(|h| h.kind == "insn"));
+ }
+
+ #[test]
+ fn address_tables_hits_appear_after_analyzer_populates() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ {
+ let prog = app.program.as_mut().unwrap();
+ prog.analysis
+ .address_tables
+ .push(ghidrust_core::AddressTableInfo {
+ base: prog.image_base,
+ count: 3,
+ entries: vec![prog.image_base, prog.image_base + 8, prog.image_base + 16],
+ role: ghidrust_core::AddressTableRole::Unknown,
+ });
+ }
+ let hits = address_table_hits(app.program.as_ref().unwrap());
+ assert_eq!(hits.len(), 1);
+ assert!(hits[0].text.contains("3 entries"));
+ }
+
+ #[test]
+ fn compute_checksums_round_trip_whole_image() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.compute_checksums(ChecksumMode::WholeImage)
+ .expect("checksum");
+ let r = app.checksum_last.as_ref().unwrap();
+ assert!(r.len > 0);
+ assert!(r.crc32 != 0);
+ assert!(r.adler32 != 0);
+ // Deterministic: re-running yields the same values.
+ let first = r.clone();
+ app.compute_checksums(ChecksumMode::WholeImage)
+ .expect("checksum");
+ assert_eq!(app.checksum_last.as_ref().unwrap(), &first);
+ }
+
+ #[test]
+ fn bytes_pane_state_defaults_and_follow_cursor() {
+ let mut app = GhidrustApp::headless();
+ assert_eq!(app.bytes_pane_bpr, 16);
+ assert!(app.bytes_pane_va.is_none());
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ // Programmatic follow — reflects listing_focus.
+ app.listing_focus_va = app.program.as_ref().and_then(|p| p.entry);
+ app.bytes_pane_va = app.listing_focus_va;
+ assert!(app.bytes_pane_va.is_some());
+ }
+
+ #[test]
+ fn parse_scalar_input_hex_and_dec_and_signed() {
+ let app = GhidrustApp::headless();
+ assert_eq!(app.parse_scalar_input("0x1234").unwrap(), 0x1234);
+ assert_eq!(app.parse_scalar_input("42").unwrap(), 42);
+ assert_eq!(app.parse_scalar_input("-0x10").unwrap(), -0x10);
+ assert!(app.parse_scalar_input("").is_err());
+ }
+
+ // ── Graphs & maps ─────────────────────────────────────
+
+ /// Function Graph derives Stage-0 blocks + edges from the
+ /// currently-focused function's CFG (honest empty if the region has
+ /// no recovered blocks).
+ #[test]
+ fn function_graph_pane_layouts_stage0_cfg() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.focus_function(entry);
+
+ let view = eframe::egui::Rect::from_min_size(
+ eframe::egui::Pos2::ZERO,
+ eframe::egui::Vec2::new(1000.0, 600.0),
+ );
+ let (blocks, edges) = crate::graphs::layout_function_graph(
+ app.program.as_ref().unwrap(),
+ entry,
+ STAGE0_MAX_INSNS,
+ FunctionGraphLayout::Hierarchical,
+ view,
+ );
+ // Honest-empty is acceptable, but if blocks land they must all
+ // have positive rects.
+ for b in &blocks {
+ assert!(b.rect.width() > 0.0);
+ }
+ for e in &edges {
+ assert!(e.from < blocks.len().max(1));
+ }
+ }
+
+ /// Function Call Graph roots at the current function with
+ /// level 0; expansion levels are session-only settings.
+ #[test]
+ fn call_graph_state_settings_persist_across_frames() {
+ let mut app = GhidrustApp::headless();
+ assert_eq!(app.graph_state.call_graph_levels_in, 0);
+ assert_eq!(app.graph_state.call_graph_levels_out, 0);
+ app.graph_state.call_graph_levels_in = 2;
+ app.graph_state.call_graph_levels_out = 1;
+ assert_eq!(app.graph_state.call_graph_levels_in, 2);
+ }
+
+ /// Editable Memory Map: RWX toggles + add + delete flow.
+ #[test]
+ fn memory_map_edit_flow_adds_and_deletes_blocks() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let n0 = app.program.as_ref().unwrap().blocks.len();
+ // Add a synthetic RWX block at 0x900000.
+ app.program
+ .as_mut()
+ .unwrap()
+ .blocks
+ .push(ghidrust_core::MemoryBlock {
+ name: "synthetic".into(),
+ va: 0x900000,
+ size: 0x100,
+ bytes: vec![0u8; 0x100],
+ readable: true,
+ writable: true,
+ executable: true,
+ });
+ assert_eq!(app.program.as_ref().unwrap().blocks.len(), n0 + 1);
+ // Flip its RWX (via the field, mirrors the UI checkbox mutation).
+ let idx = app.program.as_ref().unwrap().blocks.len() - 1;
+ {
+ let b = &mut app.program.as_mut().unwrap().blocks[idx];
+ b.writable = !b.writable;
+ assert!(!b.writable);
+ }
+ app.program.as_mut().unwrap().blocks.remove(idx);
+ assert_eq!(app.program.as_ref().unwrap().blocks.len(), n0);
+ }
+
+ /// Register Manager lattice is present and set/clear works.
+ #[test]
+ fn register_manager_lattice_and_values() {
+ let mut app = GhidrustApp::headless();
+ assert!(app.register_manager.values.is_empty());
+ app.register_manager.selected = Some("RAX".into());
+ app.register_manager
+ .values
+ .push(crate::register_manager::RegisterValueRow {
+ register: "RAX".into(),
+ start_va: 0x1000,
+ end_va: 0x1100,
+ value: "0x2a".into(),
+ });
+ assert_eq!(app.register_manager.values.len(), 1);
+ }
+
+ /// Entropy strip samples cover mapped bytes without fabricating.
+ #[test]
+ fn entropy_samples_cover_mapped_blocks() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let s = crate::entropy::entropy_samples(app.program.as_ref().unwrap(), 256);
+ assert!(!s.is_empty());
+ for w in s.windows(2) {
+ assert!(w[0].va <= w[1].va);
+ }
+ }
+
+ // ── Scripts ───────────────────────────────────────────
+
+ #[test]
+ fn script_manager_catalog_is_populated_from_mcp_surface() {
+ let app = GhidrustApp::headless();
+ assert!(!app.script_manager.catalog.is_empty());
+ assert!(app
+ .script_manager
+ .catalog
+ .iter()
+ .any(|s| s.name == "server_info"));
+ assert!(app
+ .script_manager
+ .catalog
+ .iter()
+ .any(|s| s.name == "decompile"));
+ assert!(!app
+ .script_manager
+ .catalog
+ .iter()
+ .any(|s| s.name.starts_with("net_") || s.name.starts_with("mcp.")));
+ }
+
+ #[test]
+ fn text_editor_lifecycle_open_edit_close() {
+ let mut app = GhidrustApp::headless();
+ app.text_editor.open_untitled();
+ assert_eq!(app.text_editor.tabs.len(), 1);
+ app.text_editor.tabs[0].body.push_str("body");
+ app.text_editor.tabs[0].dirty = true;
+ app.text_editor.close_active();
+ assert_eq!(app.text_editor.tabs.len(), 0);
+ }
+
+ #[test]
+ fn mcp_repl_submit_records_prompt_and_response() {
+ let mut app = GhidrustApp::headless();
+ app.mcp_repl.input = "server_info".into();
+ app.mcp_repl.submit();
+ assert_eq!(app.mcp_repl.transcript.len(), 2);
+ assert!(app.mcp_repl.transcript[0].prompt);
+ assert!(!app.mcp_repl.transcript[1].prompt);
+ assert!(!app.mcp_repl.transcript[1].text.contains("Backend pending"));
+ }
+
+ // ── Debugger visibility ──────────────────────────────
+
+ #[test]
+ fn debugger_host_enumerated_in_shell_panes() {
+ let panes = GhidrustApp::shell_panes();
+ assert!(
+ panes.contains(&"Debugger"),
+ "shell_panes missing tabbed Debugger host; full list = {panes:?}",
+ );
+ }
+
+ #[test]
+ fn debugger_menu_is_registered_in_shell() {
+ let menus = GhidrustApp::shell_menus();
+ assert!(menus.contains(&"Debugger"));
+ }
+
+ #[test]
+ fn network_host_enumerated_in_shell_panes() {
+ let panes = GhidrustApp::shell_panes();
+ assert!(
+ panes.contains(&"Network"),
+ "shell_panes missing tabbed Network host; full list = {panes:?}",
+ );
+ }
+
+ #[test]
+ fn network_menu_is_registered_in_shell() {
+ let menus = GhidrustApp::shell_menus();
+ assert!(menus.contains(&"Network"));
+ }
+
+ #[test]
+ fn debugger_breakpoint_and_watch_state_persist_session_only() {
+ let mut app = GhidrustApp::headless();
+ assert!(app.debugger.breakpoints.is_empty());
+ app.debugger.toggle_breakpoint(0x1000);
+ app.debugger.toggle_breakpoint(0x2000);
+ assert_eq!(app.debugger.breakpoints.len(), 2);
+ assert!(app.debugger.has_breakpoint(0x1000));
+ app.debugger.toggle_breakpoint(0x1000);
+ assert!(!app.debugger.has_breakpoint(0x1000));
+
+ app.debugger.add_watch("rax");
+ app.debugger.add_watch("rax"); // dedup
+ app.debugger.add_watch("*(int*)rsp");
+ assert_eq!(app.debugger.watches.len(), 2);
+ }
+
+ // ── Docking / layouts ────────────────────────────────
+
+ #[test]
+ fn save_and_restore_layout_round_trip() {
+ // Use a fresh %APPDATA%/ghidrust equivalent to keep test hermetic.
+ let dir = std::env::temp_dir().join(format!("ghidrust_layouts_{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ // Point APPDATA at our sandbox so layouts write here.
+ let prev = std::env::var("APPDATA").ok();
+ // Only override APPDATA when it's the layout-dir resolver we care about.
+ std::env::set_var("APPDATA", &dir);
+ struct RestoreAppdata(Option<String>);
+ impl Drop for RestoreAppdata {
+ fn drop(&mut self) {
+ if let Some(p) = &self.0 {
+ std::env::set_var("APPDATA", p);
+ } else {
+ std::env::remove_var("APPDATA");
+ }
+ }
+ }
+ let _guard = RestoreAppdata(prev);
+
+ let mut app = GhidrustApp::headless();
+ // Flip a few state bits so we can prove the round-trip.
+ app.toggle_pane(PaneKind::Bookmarks, true);
+ app.toggle_pane(PaneKind::MemoryMap, true);
+ app.debugger.host_open = true;
+ app.debugger.enabled = true;
+ app.debugger.active_tab = DebuggerPane::Targets;
+ app.network.host_open = true;
+ app.network.enabled = true;
+ app.network.active_tab = NetworkPane::Connections;
+ app.focus_center_tab(DockTab::Decompiler);
+ app.show_console = false;
+
+ app.save_layout_named("myTest").expect("save layout");
+ // Flip everything back so restore has something to change.
+ app.toggle_pane(PaneKind::Bookmarks, false);
+ app.toggle_pane(PaneKind::MemoryMap, false);
+ app.debugger.host_open = false;
+ app.debugger.enabled = false;
+ app.debugger.active_tab = DebuggerPane::Stack;
+ app.network.host_open = false;
+ app.network.enabled = false;
+ app.network.active_tab = NetworkPane::Dig;
+ app.focus_center_tab(DockTab::Overview);
+ app.show_console = true;
+
+ app.restore_layout_named("myTest").expect("restore layout");
+ assert!(app.is_pane_open(PaneKind::Bookmarks));
+ assert!(app.is_pane_open(PaneKind::MemoryMap));
+ assert!(app.debugger.host_open);
+ assert!(app.debugger.enabled);
+ assert_eq!(app.debugger.active_tab, DebuggerPane::Targets);
+ assert!(app.network.host_open);
+ assert!(app.network.enabled);
+ assert_eq!(app.network.active_tab, NetworkPane::Connections);
+ 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);
+ }
+
+ #[test]
+ fn configure_dialog_state_defaults_closed() {
+ let app = GhidrustApp::headless();
+ assert!(!app.show_configure_dialog);
+ assert!(!app.show_layouts_dialog);
+ }
+
+ #[test]
+ fn graph_debugger_configure_menu_actions_wired_not_nyi() {
+ let src = include_str!("menus.rs");
+ let app_src = [
+ include_str!("mod.rs"),
+ include_str!("session_api.rs"),
+ include_str!("dialogs.rs"),
+ ]
+ .join("\n");
+ // Graph menu items open panes (not nyi).
+ assert!(!src.contains("nyi(\"Graph → Function Graph\""));
+ assert!(!src.contains("nyi(\"Graph → Function Call Graph\""));
+ assert!(!src.contains("nyi(\"Graph → Function Call Trees\""));
+ // Debugger menu is registered.
+ assert!(src.contains("ui.menu_button(\"Debugger\","));
+ // Launch is wired (not nyi).
+ assert!(src.contains("open_launch_ui") || app_src.contains("open_launch_ui"));
+ assert!(!src.contains("nyi(\"Debugger → Launch"));
+ // Configure dialog + Save Tool Layout menu items are wired.
+ assert!(src.contains("show_configure_dialog"));
+ assert!(src.contains("show_layouts_dialog"));
+ // File → Configure must open the dialog (not nyi).
+ assert!(!src.contains("nyi(\"File → Configure\")"));
+ assert!(app_src.contains("ConfigureSection::Appearance") || src.contains("ConfigureSection::Appearance"));
+ assert!(src.contains("AppearanceTheme::ALL") || app_src.contains("AppearanceTheme::ALL"));
+ // Menubar must not call nyi (App may still keep a nyi helper for non-menu stubs).
+ assert!(
+ !src.contains("self.nyi("),
+ "menus.rs still contains nyi call sites"
+ );
+ assert!(
+ src.contains("debug_step_out")
+ || src.contains("debug_continue")
+ || app_src.contains("debug_continue")
+ );
+ assert!(src.contains("direct_references") || app_src.contains("fn direct_references"));
+ assert!(src.contains("repeat_search") || app_src.contains("fn repeat_search"));
+ }
+
+ #[test]
+ fn appearance_defaults_to_classic_ghidrust() {
+ let app = GhidrustApp::headless();
+ assert_eq!(app.appearance, AppearanceTheme::ClassicGhidrust);
+ assert_eq!(app.appearance.display_name(), "Classic Ghidrust");
+ let t = app.tokens();
+ assert_eq!(t.primary[0], 0xD0);
+ }
+
diff --git a/crates/ghidrust-gui/src/checksum.rs b/crates/ghidrust-gui/src/checksum.rs
new file mode 100644
index 0000000..7c8f360
--- /dev/null
+++ b/crates/ghidrust-gui/src/checksum.rs
@@ -0,0 +1,161 @@
+//! Pure checksum math for the Checksum Generator pane.
+//!
+//! Extracted from `app.rs` (Wave 1 demonolith). UI + program I/O stay on
+//! `GhidrustApp`; this module owns report types and hash helpers only.
+
+/// Checksum Generator report.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ChecksumReport {
+ pub target: String,
+ pub len: usize,
+ pub crc32: u32,
+ pub sum8: u32,
+ pub sum16: u32,
+ pub sum32: u64,
+ pub adler32: u32,
+ pub fletcher16: u32,
+ pub fletcher32: u64,
+}
+
+/// Checksum Generator scope.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ChecksumMode {
+ /// Concatenation of every loaded memory block.
+ WholeImage,
+ /// A single memory block chosen by name.
+ Section(String),
+}
+
+/// CRC-32/ISO-HDLC (polynomial `0xEDB88320`) — matches default.
+pub fn crc32_ieee(data: &[u8]) -> u32 {
+ let mut c: u32 = 0xFFFF_FFFF;
+ for &b in data {
+ c ^= b as u32;
+ for _ in 0..8 {
+ let mask = (c & 1).wrapping_neg();
+ c = (c >> 1) ^ (0xEDB8_8320 & mask);
+ }
+ }
+ !c
+}
+
+pub fn adler32(data: &[u8]) -> u32 {
+ const MOD: u32 = 65521;
+ let mut a: u32 = 1;
+ let mut b: u32 = 0;
+ for &byte in data {
+ a = (a + byte as u32) % MOD;
+ b = (b + a) % MOD;
+ }
+ (b << 16) | a
+}
+
+pub fn fletcher_pair(data: &[u8]) -> (u32, u64) {
+ let (mut a16, mut b16): (u16, u16) = (0, 0);
+ for &byte in data {
+ a16 = a16.wrapping_add(byte as u16);
+ b16 = b16.wrapping_add(a16);
+ }
+ let f16 = ((b16 as u32) << 16) | a16 as u32;
+
+ let (mut a32, mut b32): (u32, u32) = (0, 0);
+ for chunk in data.chunks_exact(2) {
+ let w = u16::from_le_bytes([chunk[0], chunk[1]]) as u32;
+ a32 = a32.wrapping_add(w);
+ b32 = b32.wrapping_add(a32);
+ }
+ let f32 = ((b32 as u64) << 32) | a32 as u64;
+ (f16, f32)
+}
+
+/// Compute every field of a [`ChecksumReport`] for `data` labeled `target`.
+pub fn report_for(target: String, data: &[u8]) -> ChecksumReport {
+ let len = data.len();
+ let crc32 = crc32_ieee(data);
+ let sum8: u32 = data.iter().map(|&b| b as u32).sum();
+ let sum16: u32 = data
+ .chunks_exact(2)
+ .map(|c| u16::from_le_bytes([c[0], c[1]]) as u32)
+ .sum::<u32>();
+ let sum32: u64 = data
+ .chunks_exact(4)
+ .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]) as u64)
+ .sum::<u64>();
+ let adler32 = adler32(data);
+ let (fletcher16, fletcher32) = fletcher_pair(data);
+ ChecksumReport {
+ target,
+ len,
+ crc32,
+ sum8,
+ sum16,
+ sum32,
+ adler32,
+ fletcher16,
+ fletcher32,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn crc32_ieee_empty_and_check_vector() {
+ assert_eq!(crc32_ieee(b""), 0x0000_0000);
+ // Well-known ISO-HDLC / IEEE check value for "123456789".
+ assert_eq!(crc32_ieee(b"123456789"), 0xCBF4_3926);
+ }
+
+ #[test]
+ fn adler32_empty_and_check_vector() {
+ // Adler-32 of empty input is 1 (a=1, b=0).
+ assert_eq!(adler32(b""), 0x0000_0001);
+ // Adler-32 of "123456789" (RFC 1950 check vector).
+ assert_eq!(adler32(b"123456789"), 0x091E_01DE);
+ }
+
+ #[test]
+ fn fletcher_pair_empty_and_short() {
+ assert_eq!(fletcher_pair(b""), (0, 0));
+ // Single byte: a16=0x41, b16=0x41; no complete u16 for f32 → 0.
+ assert_eq!(fletcher_pair(b"A"), (0x0041_0041, 0));
+ // Two bytes: f16 from running sums; f32 from one LE u16 word.
+ let (f16, f32) = fletcher_pair(b"AB");
+ let mut a16: u16 = 0;
+ let mut b16: u16 = 0;
+ for &byte in b"AB" {
+ a16 = a16.wrapping_add(byte as u16);
+ b16 = b16.wrapping_add(a16);
+ }
+ assert_eq!(f16, ((b16 as u32) << 16) | a16 as u32);
+ let w = u16::from_le_bytes([b'A', b'B']) as u32;
+ assert_eq!(f32, ((w as u64) << 32) | w as u64);
+ }
+
+ #[test]
+ fn report_for_aggregates_known_vector() {
+ let data = b"123456789";
+ let r = report_for("t".into(), data);
+ assert_eq!(r.target, "t");
+ assert_eq!(r.len, 9);
+ assert_eq!(r.crc32, 0xCBF4_3926);
+ assert_eq!(r.adler32, 0x091E_01DE);
+ assert_eq!(r.sum8, data.iter().map(|&b| b as u32).sum::<u32>());
+ // 4 complete LE u16 pairs from 8 bytes; last byte dropped by chunks_exact(2).
+ let sum16: u32 = data
+ .chunks_exact(2)
+ .map(|c| u16::from_le_bytes([c[0], c[1]]) as u32)
+ .sum();
+ assert_eq!(r.sum16, sum16);
+ // 2 complete LE u32 words; last byte dropped.
+ let sum32: u64 = data
+ .chunks_exact(4)
+ .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]) as u64)
+ .sum();
+ assert_eq!(r.sum32, sum32);
+ let (f16, f32) = fletcher_pair(data);
+ assert_eq!(r.fletcher16, f16);
+ assert_eq!(r.fletcher32, f32);
+ }
+}
diff --git a/crates/ghidrust-gui/src/debugger.rs b/crates/ghidrust-gui/src/debugger.rs
index 37529e6..65ebbbd 100644
--- a/crates/ghidrust-gui/src/debugger.rs
+++ b/crates/ghidrust-gui/src/debugger.rs
@@ -9,11 +9,13 @@ use ghidrust_core::process::{
process_attach_opts, process_break_clear, process_break_list, process_break_set,
process_continue, process_detach, process_export_snapshot, process_launch, process_list,
process_modules, process_pause, process_read, process_regions, process_resume, process_scan_mem,
- process_stack, process_step_into, process_step_over, process_thread_context_get, process_threads,
- process_wait, process_watch_expr, static_to_live, AttachOpts, BreakKind, BreakpointInfo,
- LaunchRequest, ModuleInfo, ProcessInfo, ProcessSession, ReadResult, RegionInfo, RegisterSet,
- ScanHit, ScanOpts, SessionMode, StackFrame, StopEvent, ThreadInfo, WatchResult,
+ process_stack, process_step_into, process_step_out, process_step_over,
+ process_thread_context_get, process_thread_context_set, process_threads, process_wait,
+ process_watch_expr, static_to_live, AttachOpts, BreakKind, BreakpointInfo, LaunchRequest,
+ ModuleInfo, ProcessInfo, ProcessSession, ReadResult, RegionInfo, RegisterSet, ScanHit,
+ ScanOpts, SessionMode, StackFrame, StopEvent, ThreadInfo, WatchResult,
};
+use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// Host window egui / layout id.
@@ -68,7 +70,7 @@ impl DebuggerPane {
}
/// display title (legacy Window menu / provider `TITLE`).
- #[allow(dead_code)]
+ #[cfg(test)]
pub const fn title(self) -> &'static str {
match self {
DebuggerPane::Targets => "Debugger Targets",
@@ -117,7 +119,7 @@ impl DebuggerPane {
}
/// Columns rendered in the empty-state table (layout).
- #[allow(dead_code)]
+ #[cfg(test)]
pub const fn columns(self) -> &'static [&'static str] {
match self {
DebuggerPane::Targets => &["Name", "Type", "State"],
@@ -134,7 +136,7 @@ impl DebuggerPane {
}
/// Copy pointing at the pending backend for this pane.
- #[allow(dead_code)]
+ #[cfg(test)]
pub const fn backend_message(self) -> &'static str {
match self {
DebuggerPane::Targets => {
@@ -150,7 +152,7 @@ impl DebuggerPane {
"Live Process Bridge (Windows) — ghidrust_core::process_regions (VirtualQueryEx)."
}
DebuggerPane::Registers => {
- "Live Process Bridge — process_thread_context_get (debug mode, x64 CONTEXT)."
+ "Live Process Bridge — process_thread_context_get/set (debug mode, editable x64 CONTEXT)."
}
DebuggerPane::Stack => {
"Live Process Bridge — process_stack (debug mode, RBP/pdata unwind)."
@@ -164,7 +166,9 @@ impl DebuggerPane {
DebuggerPane::Watches => {
"Live Process Bridge — process_watch_expr (pointer-chase DSL)."
}
- DebuggerPane::DebuggerConsole => "Debugger console (session events / stop reasons).",
+ DebuggerPane::DebuggerConsole => {
+ "Debugger console — session log + command line (process helpers / mcp_host)."
+ }
}
}
}
@@ -257,10 +261,14 @@ pub struct DebuggerState {
pub threads_cache: Vec<ThreadInfo>,
pub active_thread_id: Option<u32>,
pub registers_cache: Option<RegisterSet>,
+ /// Editable hex strings keyed by register name (synced from `registers_cache`).
+ pub reg_edit: BTreeMap<String, String>,
pub stack_cache: Vec<StackFrame>,
pub watch_results: Vec<WatchResult>,
pub last_stop: Option<StopEvent>,
pub console_log: Vec<String>,
+ /// Debugger console command line (appends to log; optional process_* / mcp_host).
+ pub console_input: String,
pub scan_aob: String,
pub scan_string: String,
pub scan_hits: Vec<ScanHit>,
@@ -305,10 +313,12 @@ impl Default for DebuggerState {
threads_cache: Vec::new(),
active_thread_id: None,
registers_cache: None,
+ reg_edit: BTreeMap::new(),
stack_cache: Vec::new(),
watch_results: Vec::new(),
last_stop: None,
console_log: Vec::new(),
+ console_input: String::new(),
scan_aob: String::new(),
scan_string: String::new(),
scan_hits: Vec::new(),
@@ -326,7 +336,32 @@ impl DebuggerState {
}
}
- #[allow(dead_code)]
+ /// Toggle a local breakpoint, mirroring it to the attached debug session when possible.
+ pub fn toggle_breakpoint_live(&mut self, va: u64) {
+ if let Some(sess) = self.session.clone().filter(|s| s.mode == SessionMode::Debug) {
+ let existing = self
+ .live_breakpoints
+ .iter()
+ .find(|bp| bp.addr == va)
+ .map(|bp| bp.id);
+ let result = match existing {
+ Some(id) => process_break_clear(&sess.session_id, Some(id), None),
+ None => process_break_set(&sess.session_id, va, BreakKind::Software, false)
+ .map(|_| ()),
+ };
+ match result {
+ Ok(()) => {
+ self.log(format!("breakpoint toggled at {va:#x}"));
+ self.refresh_debug_views();
+ return;
+ }
+ Err(e) => self.live_error = Some(e),
+ }
+ }
+ self.toggle_breakpoint(va);
+ }
+
+ #[cfg(test)]
pub fn has_breakpoint(&self, va: u64) -> bool {
self.breakpoints.contains(&va)
}
@@ -405,12 +440,169 @@ impl DebuggerState {
self.threads_cache.clear();
self.active_thread_id = None;
self.registers_cache = None;
+ self.reg_edit.clear();
self.stack_cache.clear();
self.watch_results.clear();
self.last_stop = None;
self.scan_hits.clear();
}
+ /// Sync editable register fields from the live cache.
+ pub fn sync_reg_edit_from_cache(&mut self) {
+ let Some(regs) = self.registers_cache.clone() else {
+ self.reg_edit.clear();
+ return;
+ };
+ self.reg_edit.clear();
+ for (n, v) in register_pairs(&regs) {
+ self.reg_edit.insert(n.to_string(), format!("{v:#x}"));
+ }
+ }
+
+ /// Apply one edited register via `process_thread_context_set`.
+ pub fn apply_register_edit(&mut self, name: &str) {
+ let Some(sess) = self.session.clone() else {
+ self.live_error = Some("no session".into());
+ return;
+ };
+ if sess.mode != SessionMode::Debug {
+ self.live_error = Some("registers require mode=debug".into());
+ return;
+ }
+ let Some(tid) = self.active_thread_id else {
+ self.live_error = Some("no active thread".into());
+ return;
+ };
+ let Some(raw) = self.reg_edit.get(name).cloned() else {
+ return;
+ };
+ let Some(val) = parse_hex(raw.trim_start_matches('!')) else {
+ self.live_error = Some(format!("bad hex for {name}: {raw}"));
+ return;
+ };
+ let mut regs = match self.registers_cache.clone() {
+ Some(r) => r,
+ None => match process_thread_context_get(&sess.session_id, tid) {
+ Ok(r) => r,
+ Err(e) => {
+ self.live_error = Some(e);
+ return;
+ }
+ },
+ };
+ if !set_register_field(&mut regs, name, val) {
+ self.live_error = Some(format!("unknown register {name}"));
+ return;
+ }
+ match process_thread_context_set(&sess.session_id, tid, &regs) {
+ Ok(()) => {
+ self.registers_cache = Some(regs);
+ self.reg_edit.insert(name.to_string(), format!("{val:#x}"));
+ self.log(format!("process_thread_context_set {name}={val:#x} tid={tid}"));
+ self.live_error = None;
+ }
+ Err(e) => self.live_error = Some(e),
+ }
+ }
+
+ /// Run a console command line: always appends to the log; optionally
+ /// dispatches built-in process helpers or `mcp_host` tool lines.
+ pub fn run_console_command(&mut self, line: &str) {
+ let line = line.trim();
+ if line.is_empty() {
+ return;
+ }
+ self.log(format!("> {line}"));
+ let lower = line.to_ascii_lowercase();
+ if let Some(sess) = self.session.clone() {
+ let sid = sess.session_id.clone();
+ match lower.as_str() {
+ "continue" | "g" | "c" => {
+ match process_continue(&sid) {
+ Ok(()) => self.log("continue ok"),
+ Err(e) => self.log(format!("continue error: {e}")),
+ }
+ return;
+ }
+ "pause" | "break" | "interrupt" => {
+ match process_pause(&sid) {
+ Ok(()) => self.log("pause ok"),
+ Err(e) => self.log(format!("pause error: {e}")),
+ }
+ return;
+ }
+ "step" | "stepi" | "si" => {
+ match process_step_into(&sid, self.active_thread_id) {
+ Ok(()) => {
+ self.log("step-into requested");
+ self.poll_stop(2000);
+ self.refresh_debug_views();
+ }
+ Err(e) => self.log(format!("step error: {e}")),
+ }
+ return;
+ }
+ "stepover" | "next" | "ni" => {
+ match process_step_over(&sid, self.active_thread_id) {
+ Ok(()) => {
+ self.log("step-over requested");
+ self.poll_stop(2000);
+ self.refresh_debug_views();
+ }
+ Err(e) => self.log(format!("stepover error: {e}")),
+ }
+ return;
+ }
+ "regs" | "registers" => {
+ self.refresh_debug_views();
+ if let Some(r) = &self.registers_cache {
+ for (n, v) in register_pairs(r) {
+ self.log(format!(" {n}={v:#x}"));
+ }
+ } else {
+ self.log("no register cache");
+ }
+ return;
+ }
+ "threads" => {
+ self.refresh_debug_views();
+ let tids: Vec<u32> = self.threads_cache.iter().map(|t| t.thread_id).collect();
+ for tid in tids {
+ self.log(format!(" tid={tid}"));
+ }
+ return;
+ }
+ "help" => {
+ self.log(
+ "commands: continue|pause|step|stepover|regs|threads|help · or process_* / tool {json}",
+ );
+ return;
+ }
+ _ => {}
+ }
+ } else if matches!(
+ lower.as_str(),
+ "continue" | "g" | "c" | "pause" | "break" | "interrupt" | "step" | "stepi" | "si"
+ | "stepover" | "next" | "ni" | "regs" | "registers" | "threads"
+ ) {
+ self.log("no live session — attach/launch first");
+ return;
+ }
+
+ // Optional mcp_host path for process_* / other non-net tools.
+ if lower.starts_with("process_") || line.contains('{') {
+ match crate::mcp_host::parse_tool_line(line) {
+ Ok((tool, args)) => {
+ let out = crate::mcp_host::invoke_tool(&tool, &args);
+ for l in out.lines().take(40) {
+ self.log(l.to_string());
+ }
+ }
+ Err(e) => self.log(format!("parse error: {e}")),
+ }
+ }
+ }
+
pub fn log(&mut self, line: impl Into<String>) {
self.console_log.push(line.into());
if self.console_log.len() > 500 {
@@ -585,6 +777,7 @@ impl DebuggerState {
if let Some(tid) = self.active_thread_id {
if let Ok(regs) = process_thread_context_get(&sess.session_id, tid) {
self.registers_cache = Some(regs);
+ self.sync_reg_edit_from_cache();
}
if let Ok(frames) = process_stack(&sess.session_id, tid, 32) {
self.stack_cache = frames;
@@ -664,6 +857,20 @@ impl DebuggerState {
}
}
+ pub fn debug_step_out(&mut self) {
+ let Some(sess) = self.session.clone() else {
+ return;
+ };
+ let tid = self.active_thread_id;
+ match process_step_out(&sess.session_id, tid) {
+ Ok(()) => {
+ self.log("step out");
+ self.poll_stop(5000);
+ }
+ Err(e) => self.live_error = Some(e),
+ }
+ }
+
pub fn resume_session(&mut self) {
let Some(sess) = self.session.clone() else {
self.live_error = Some("no live session to resume".into());
@@ -1033,6 +1240,17 @@ fn render_host_body(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
{
state.debug_step(true);
}
+ if ui
+ .add_enabled(dbg, egui::Button::new("Step Out (Shift+F8)").small())
+ .on_hover_text(if dbg {
+ "process_step_out"
+ } else {
+ "Requires mode=debug"
+ })
+ .clicked()
+ {
+ state.debug_step_out();
+ }
if ui
.add_enabled(dbg, egui::Button::new("Wait stop").small())
.on_hover_text("process_wait 5s")
@@ -1760,13 +1978,13 @@ fn render_registers(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
return;
};
if sess.mode != SessionMode::Debug {
- ui.weak("Registers require mode=debug (process_thread_context_get).");
+ ui.weak("Registers require mode=debug (process_thread_context_get / set).");
return;
}
ui.horizontal(|ui| {
ui.small(
RichText::new(format!(
- "tid={}",
+ "tid={} · edit hex → Set → process_thread_context_set",
state
.active_thread_id
.map(|t| t.to_string())
@@ -1784,47 +2002,53 @@ fn render_registers(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
stop.reason, stop.rip
));
}
- let Some(regs) = state.registers_cache.clone() else {
+ if state.registers_cache.is_none() {
ui.weak("No register cache — stop on a BP or Refresh after selecting a thread.");
return;
- };
- let pairs = [
- ("rax", regs.rax),
- ("rbx", regs.rbx),
- ("rcx", regs.rcx),
- ("rdx", regs.rdx),
- ("rsi", regs.rsi),
- ("rdi", regs.rdi),
- ("rbp", regs.rbp),
- ("rsp", regs.rsp),
- ("r8", regs.r8),
- ("r9", regs.r9),
- ("r10", regs.r10),
- ("r11", regs.r11),
- ("r12", regs.r12),
- ("r13", regs.r13),
- ("r14", regs.r14),
- ("r15", regs.r15),
- ("rip", regs.rip),
- ("rflags", regs.rflags),
- ];
+ }
+ if state.reg_edit.is_empty() {
+ state.sync_reg_edit_from_cache();
+ }
+ let names: Vec<&'static str> = register_pairs(state.registers_cache.as_ref().unwrap())
+ .into_iter()
+ .map(|(n, _)| n)
+ .collect();
+ let mut apply_name: Option<String> = None;
egui::ScrollArea::vertical()
.id_salt("dbg_regs")
.show(ui, |ui| {
egui::Grid::new("dbg_regs_grid")
- .num_columns(2)
+ .num_columns(3)
.striped(true)
.show(ui, |ui| {
ui.strong("Register");
ui.strong("Value");
+ ui.strong("");
ui.end_row();
- for (n, v) in pairs {
- ui.monospace(n);
- ui.monospace(format!("{v:#018x}"));
+ for n in &names {
+ ui.monospace(*n);
+ let entry = state
+ .reg_edit
+ .entry((*n).to_string())
+ .or_insert_with(String::new);
+ let resp = ui.add(
+ egui::TextEdit::singleline(entry)
+ .desired_width(160.0)
+ .font(egui::TextStyle::Monospace),
+ );
+ if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
+ apply_name = Some((*n).to_string());
+ }
+ if ui.small_button("Set").clicked() {
+ apply_name = Some((*n).to_string());
+ }
ui.end_row();
}
});
});
+ if let Some(n) = apply_name {
+ state.apply_register_edit(&n);
+ }
}
fn render_stack(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
@@ -1884,7 +2108,10 @@ fn render_stack(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
fn render_console(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
ui.horizontal(|ui| {
- ui.small(RichText::new("Session events / stop reasons").color(muted));
+ ui.small(
+ RichText::new("Session events · command line (continue/step/regs or process_* {json})")
+ .color(muted),
+ );
if ui.button("Clear log").clicked() {
state.console_log.clear();
}
@@ -1898,7 +2125,6 @@ fn render_console(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
Ok(snap) => {
if let Ok(j) = serde_json::to_string_pretty(&snap) {
state.log(format!("snapshot ok bytes={}", j.len()));
- // Keep a short head in the log for the user.
for line in j.lines().take(12) {
state.log(line.to_string());
}
@@ -1914,14 +2140,35 @@ fn render_console(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
egui::ScrollArea::vertical()
.id_salt("dbg_console")
.stick_to_bottom(true)
+ .max_height(280.0)
.show(ui, |ui| {
if state.console_log.is_empty() {
- ui.weak("No events yet.");
+ ui.weak("No events yet — type a command below.");
}
for line in &state.console_log {
ui.monospace(line);
}
});
+ ui.separator();
+ let mut submit = false;
+ ui.horizontal(|ui| {
+ ui.label(">");
+ let resp = ui.add(
+ egui::TextEdit::singleline(&mut state.console_input)
+ .desired_width(f32::INFINITY)
+ .hint_text("continue · step · regs · process_threads {\"session_id\":\"…\"}"),
+ );
+ if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
+ submit = true;
+ }
+ if ui.button("Run").clicked() {
+ submit = true;
+ }
+ });
+ if submit {
+ let cmd = std::mem::take(&mut state.console_input);
+ state.run_console_command(&cmd);
+ }
}
fn parse_hex(s: &str) -> Option<u64> {
@@ -1933,6 +2180,54 @@ fn parse_hex(s: &str) -> Option<u64> {
u64::from_str_radix(s, 16).ok()
}
+fn register_pairs(regs: &RegisterSet) -> [(&'static str, u64); 18] {
+ [
+ ("rax", regs.rax),
+ ("rbx", regs.rbx),
+ ("rcx", regs.rcx),
+ ("rdx", regs.rdx),
+ ("rsi", regs.rsi),
+ ("rdi", regs.rdi),
+ ("rbp", regs.rbp),
+ ("rsp", regs.rsp),
+ ("r8", regs.r8),
+ ("r9", regs.r9),
+ ("r10", regs.r10),
+ ("r11", regs.r11),
+ ("r12", regs.r12),
+ ("r13", regs.r13),
+ ("r14", regs.r14),
+ ("r15", regs.r15),
+ ("rip", regs.rip),
+ ("rflags", regs.rflags),
+ ]
+}
+
+fn set_register_field(regs: &mut RegisterSet, name: &str, val: u64) -> bool {
+ match name.to_ascii_lowercase().as_str() {
+ "rax" => regs.rax = val,
+ "rbx" => regs.rbx = val,
+ "rcx" => regs.rcx = val,
+ "rdx" => regs.rdx = val,
+ "rsi" => regs.rsi = val,
+ "rdi" => regs.rdi = val,
+ "rbp" => regs.rbp = val,
+ "rsp" => regs.rsp = val,
+ "r8" => regs.r8 = val,
+ "r9" => regs.r9 = val,
+ "r10" => regs.r10 = val,
+ "r11" => regs.r11 = val,
+ "r12" => regs.r12 = val,
+ "r13" => regs.r13 = val,
+ "r14" => regs.r14 = val,
+ "r15" => regs.r15 = val,
+ "rip" => regs.rip = val,
+ "rflags" => regs.rflags = val,
+ _ => return false,
+ }
+ true
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ghidrust-gui/src/decomp_tokens.rs b/crates/ghidrust-gui/src/decomp_tokens.rs
index b4974d5..6c22f89 100644
--- a/crates/ghidrust-gui/src/decomp_tokens.rs
+++ b/crates/ghidrust-gui/src/decomp_tokens.rs
@@ -42,9 +42,6 @@ pub enum TokenKind {
Syntax,
/// Whitespace-only chunk (preserved so we can round-trip render).
Whitespace,
- /// Newline sentinel (reserved for future non-`\n`-split renderers).
- #[allow(dead_code)]
- Newline,
}
/// One decompiler line, with its (optional) source instruction address and its tokens.
@@ -409,16 +406,13 @@ fn first_hex_in(s: &str) -> Option<u64> {
}
/// Return every distinct occurrence of `text` in the given line set (for middle-click highlight).
-#[allow(dead_code)] // reserved for future "count occurrences" hover UI
+#[cfg(test)]
pub fn occurrences_of<'a>(lines: &'a [DecompLine], text: &str) -> Vec<(usize, usize)> {
let mut hits = Vec::new();
for line in lines {
for (ti, tok) in line.tokens.iter().enumerate() {
if tok.text == text
- && !matches!(
- tok.kind,
- TokenKind::Whitespace | TokenKind::Syntax | TokenKind::Newline
- )
+ && !matches!(tok.kind, TokenKind::Whitespace | TokenKind::Syntax)
{
hits.push((line.line, ti));
}
diff --git a/crates/ghidrust-gui/src/events.rs b/crates/ghidrust-gui/src/events.rs
index 5b0057b..9a85db6 100644
--- a/crates/ghidrust-gui/src/events.rs
+++ b/crates/ghidrust-gui/src/events.rs
@@ -5,8 +5,8 @@
//! fans events out to every subscribed pane (Symbol Tree, Bookmarks, Decompiler, etc.)
//! so cross‑window sync is centralised.
//!
-//! This is a Stage‑1 skeleton: the bus is a plain `Vec<GhidrustEvent>` and consumers
-//! poll it. Fan‑out to individual providers is still pending.
+//! The bus is a plain `Vec<GhidrustEvent>`; each frame `GhidrustApp::drain_events`
+//! fans events out (listing focus status, decompiler cache invalidation, etc.).
use crate::nav::NavLocation;
@@ -21,12 +21,6 @@ pub enum GhidrustEvent {
source: EventSource,
location: NavLocation,
},
- /// Selection changed.
- SelectionChanged {
- source: EventSource,
- start: NavLocation,
- end: NavLocation,
- },
/// Program was mutated — every downstream pane invalidates its cache.
ProgramMutated { kind: MutationKind },
/// A new program was activated / opened.
@@ -34,18 +28,12 @@ pub enum GhidrustEvent {
}
/// Pane / plugin that emitted an event.
+///
+/// Only sources that currently publish are listed — add a variant when a producer lands.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventSource {
Listing,
- Decompiler,
- SymbolTree,
- ProgramTree,
- SymbolTable,
- FunctionsWindow,
- Bookmarks,
Navigation,
- Search,
- Other,
}
/// Kinds of program mutation subscribers care about (drives cache invalidation).
@@ -56,7 +44,6 @@ pub enum MutationKind {
CommentChanged { va: u64 },
BookmarkAdded { va: u64 },
BookmarkRemoved { va: u64 },
- Analysis,
}
/// Simple in-memory bus. Producers push; consumers drain each frame.
@@ -84,21 +71,15 @@ impl EventBus {
std::mem::take(&mut self.events)
}
- #[allow(dead_code)] // exercised by tests only
+ #[cfg(test)]
pub fn len(&self) -> usize {
self.events.len()
}
- #[allow(dead_code)] // exercised by tests only
+ #[cfg(test)]
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
-
- /// Peek — used by tests.
- #[allow(dead_code)] // exercised by tests only
- pub fn peek(&self) -> &[GhidrustEvent] {
- &self.events
- }
}
#[cfg(test)]
@@ -118,7 +99,7 @@ mod tests {
location: loc(0x1000),
});
bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Analysis,
+ kind: MutationKind::CommentChanged { va: 0x1000 },
});
assert_eq!(bus.len(), 2);
let drained = bus.drain();
@@ -145,11 +126,6 @@ mod tests {
source: EventSource::Listing,
location: loc(0x1000),
});
- bus.publish(GhidrustEvent::SelectionChanged {
- source: EventSource::Listing,
- start: loc(0x1000),
- end: loc(0x1010),
- });
bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Rename {
va: 0x1000,
@@ -174,6 +150,10 @@ mod tests {
bus.publish(GhidrustEvent::ProgramActivated {
name: "hello.exe".into(),
});
+ bus.publish(GhidrustEvent::CursorMoved {
+ source: EventSource::Navigation,
+ location: loc(0x2000),
+ });
assert_eq!(bus.len(), 8);
}
}
diff --git a/crates/ghidrust-gui/src/graphs.rs b/crates/ghidrust-gui/src/graphs.rs
index f9e449d..15ce306 100644
--- a/crates/ghidrust-gui/src/graphs.rs
+++ b/crates/ghidrust-gui/src/graphs.rs
@@ -30,13 +30,6 @@ pub struct GraphPaneState {
/// Function Call Graph — expanded levels in / out (0 = source only).
pub call_graph_levels_in: usize,
pub call_graph_levels_out: usize,
- /// Call Trees — expanded "incoming callers of X" set (function VAs).
- /// Reserved for future stateful-tree work; expansion currently happens
- /// on demand via `expand_tree_node`.
- #[allow(dead_code)]
- pub call_tree_expanded_in: BTreeSet<u64>,
- #[allow(dead_code)]
- pub call_tree_expanded_out: BTreeSet<u64>,
/// Call Trees — filter out thunks.
pub call_tree_hide_thunks: bool,
/// Call Trees — "References Only" mode (data refs, no call edges).
diff --git a/crates/ghidrust-gui/src/layouts.rs b/crates/ghidrust-gui/src/layouts.rs
index b59f4f3..1fb63d9 100644
--- a/crates/ghidrust-gui/src/layouts.rs
+++ b/crates/ghidrust-gui/src/layouts.rs
@@ -7,7 +7,7 @@
//! `%APPDATA%/ghidrust/layouts/<name>.tool.json`
//! - 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
+//! - Configure dialog data: Appearance theme ids + read-only plugin catalog
//!
//! Extracted per internal modularization notes — new UI panes land here
//! instead of piling into `main.rs`.
@@ -34,12 +34,19 @@ pub struct SavedLayout {
/// layouts saved before center docking landed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dock_tree: Option<serde_json::Value>,
- /// Theme (`dark` / `light`).
+ /// Theme mode (`dark` / `light`). For Future Console: neon / amber gas.
pub theme: String,
+ /// Appearance family (`classic_ghidrust` / `modern` / `future_console`).
+ #[serde(default = "default_appearance")]
+ pub appearance: String,
/// Free-form comment shown in Configure dialog.
pub comment: String,
}
+fn default_appearance() -> String {
+ "classic_ghidrust".into()
+}
+
/// Directory holding user-saved `<name>.tool.json` files.
pub fn layouts_dir() -> PathBuf {
if let Ok(appdata) = std::env::var("APPDATA") {
@@ -227,8 +234,8 @@ pub const PLUGIN_CATALOG: &[PluginRow] = &[
PluginRow {
name: "InterpreterPanelPlugin",
kind: "Scripting",
- state: "Included · REPL stub",
- description: "MCP REPL — wires into `ghidrust mcp` stdio host in P17.",
+ state: "Included · live",
+ description: "MCP REPL — stdio host to `ghidrust mcp` (non-network tools).",
},
PluginRow {
name: "DebuggerTargetsPlugin",
@@ -239,8 +246,8 @@ pub const PLUGIN_CATALOG: &[PluginRow] = &[
PluginRow {
name: "DebuggerThreadsPlugin",
kind: "Debugger",
- state: "Included · stub",
- description: "Tabbed Debugger · Threads — live backend not yet wired.",
+ state: "Included · live",
+ description: "Tabbed Debugger · Threads — process_threads when attached in debug mode.",
},
PluginRow {
name: "DebuggerModulesPlugin",
@@ -257,20 +264,20 @@ pub const PLUGIN_CATALOG: &[PluginRow] = &[
PluginRow {
name: "DebuggerRegistersPlugin",
kind: "Debugger",
- state: "Included · stub",
- description: "Tabbed Debugger · Registers — live backend not yet wired.",
+ state: "Included · live",
+ description: "Tabbed Debugger · Registers — process_thread_context_get/set when attached.",
},
PluginRow {
name: "DebuggerStackPlugin",
kind: "Debugger",
- state: "Included · stub",
- description: "Tabbed Debugger · Stack — live backend not yet wired.",
+ state: "Included · live",
+ description: "Tabbed Debugger · Stack — process_stack when attached in debug mode.",
},
PluginRow {
name: "DebuggerBreakpointsPlugin",
kind: "Debugger",
- state: "Included · session",
- description: "Tabbed Debugger · Breakpoints — session-only list; agent-set pending.",
+ state: "Included · live",
+ description: "Tabbed Debugger · Breakpoints — process_break_set/clear/list in debug mode.",
},
PluginRow {
name: "DebuggerMemoryBytesPlugin",
@@ -281,14 +288,32 @@ pub const PLUGIN_CATALOG: &[PluginRow] = &[
PluginRow {
name: "DebuggerWatchesPlugin",
kind: "Debugger",
- state: "Included · session",
- description: "Tabbed Debugger · Watches — session-only list; evaluator pending.",
+ state: "Included · live",
+ description: "Tabbed Debugger · Watches — process_watch_expr + scan when attached.",
},
PluginRow {
name: "DebuggerConsolePlugin",
kind: "Debugger",
- state: "Included · stub",
- description: "Tabbed Debugger · Console — target-agent stdio pending.",
+ state: "Included · live",
+ description: "Tabbed Debugger · Console — session event log + command entry.",
+ },
+ PluginRow {
+ name: "NetworkConnectionsPlugin",
+ kind: "Network",
+ state: "Included · host tab",
+ description: "Network host · Connections — process/peer/state/confidence; Dig CTA (Window/Network menu).",
+ },
+ PluginRow {
+ name: "NetworkCapturePlugin",
+ kind: "Network",
+ state: "Included · host tab",
+ description: "Network host · Capture — iface/filter/start-stop; Flows; Detect/Pivots (in-process session).",
+ },
+ PluginRow {
+ name: "NetworkAlertsPlugin",
+ kind: "Network",
+ state: "Included · host tab",
+ description: "Network host · Alerts — GNR severity queue with Dig closed-loop CTA.",
},
];
@@ -305,6 +330,7 @@ mod tests {
center: "listing".into(),
dock_tree: None,
theme: "dark".into(),
+ appearance: "classic_ghidrust".into(),
comment: String::new(),
};
let text = serde_json::to_string(&l).unwrap();
@@ -325,6 +351,7 @@ mod tests {
let back: SavedLayout = serde_json::from_str(text).unwrap();
assert_eq!(back.center, "decompiler");
assert!(back.dock_tree.is_none());
+ assert_eq!(back.appearance, "classic_ghidrust");
}
#[test]
@@ -335,7 +362,7 @@ mod tests {
#[test]
fn plugin_catalog_covers_graph_debugger_configure_providers() {
- let names: Vec<&'static str> = PLUGIN_CATALOG.iter().map(|p| p.name()).collect();
+ let names: Vec<&'static str> = PLUGIN_CATALOG.iter().map(|p| p.name).collect();
for expected in [
"FunctionGraphPlugin",
"FunctionCallGraphPlugin",
@@ -349,6 +376,9 @@ mod tests {
"InterpreterPanelPlugin",
"DebuggerTargetsPlugin",
"DebuggerBreakpointsPlugin",
+ "NetworkConnectionsPlugin",
+ "NetworkCapturePlugin",
+ "NetworkAlertsPlugin",
] {
assert!(names.contains(&expected), "missing plugin {expected}");
}
diff --git a/crates/ghidrust-gui/src/lib.rs b/crates/ghidrust-gui/src/lib.rs
new file mode 100644
index 0000000..d86ffd7
--- /dev/null
+++ b/crates/ghidrust-gui/src/lib.rs
@@ -0,0 +1,34 @@
+//! Ghidrust shell — Material 3 Dark/Light, menus/panes.
+//! Icons: Google Material 3 geometry (see `icons.rs`); no emoji in the UI.
+//!
+//! Library surface for the CodeBrowser GUI. The binary entry is `main.rs`.
+
+mod agent_pane;
+mod branding;
+mod checksum;
+mod debugger;
+mod network;
+mod decomp_tokens;
+mod decrypt_ui;
+mod dock_tabs;
+mod entropy;
+mod events;
+mod graphs;
+mod grok_term;
+mod icons;
+mod layouts;
+mod listing;
+mod menu_actions;
+mod nav;
+mod panes;
+mod register_manager;
+mod relocations;
+mod mcp_host;
+mod scripts;
+mod tool_panes;
+mod theme;
+mod wire_dialogs;
+
+mod app;
+
+pub use app::run;
diff --git a/crates/ghidrust-gui/src/listing/detail_pane.rs b/crates/ghidrust-gui/src/listing/detail_pane.rs
index c159a42..f423424 100644
--- a/crates/ghidrust-gui/src/listing/detail_pane.rs
+++ b/crates/ghidrust-gui/src/listing/detail_pane.rs
@@ -1,7 +1,7 @@
//! Instruction detail pane .
use ghidrust_core::ghidrust_decode::{group_name, insn_name, reg_name};
-use ghidrust_core::ghidrust_decode::{OpType, Operand};
+use ghidrust_core::ghidrust_decode::Operand;
use ghidrust_core::{Arch, Instruction};
pub fn ui_detail_pane(ui: &mut egui::Ui, insn: &Instruction, arch: Arch) {
@@ -146,13 +146,3 @@ fn format_operand(arch: Arch, op: &Operand) -> String {
}
}
-#[allow(dead_code)]
-pub fn operand_type_label(op: &Operand) -> &'static str {
- match op.op_type() {
- OpType::Reg => "reg",
- OpType::Imm => "imm",
- OpType::Mem => "mem",
- OpType::Fp => "fp",
- OpType::Invalid => "invalid",
- }
-}
diff --git a/crates/ghidrust-gui/src/main.rs b/crates/ghidrust-gui/src/main.rs
index f42de77..90bdb48 100644
--- a/crates/ghidrust-gui/src/main.rs
+++ b/crates/ghidrust-gui/src/main.rs
@@ -1,12026 +1,5 @@
-//! Ghidrust shell — Material 3 Dark/Light, menus/panes.
-//! Icons: Google Material 3 geometry (see `icons.rs`); no emoji in the UI.
-
-mod agent_pane;
-mod branding;
-mod debugger;
-mod decomp_tokens;
-mod decrypt_ui;
-mod dock_tabs;
-mod entropy;
-mod events;
-mod graphs;
-mod grok_term;
-mod icons;
-mod layouts;
-mod listing;
-mod menu_actions;
-mod nav;
-mod panes;
-mod register_manager;
-mod scripts;
-mod tool_panes;
-
-use debugger::{DebuggerAction, DebuggerPane, DebuggerState};
-use decomp_tokens::{
- emit_token_triples, from_emit_tokens, line_for_va as decomp_line_for_va,
- tokenize as tokenize_decomp, DecompLine, TokenKind,
-};
-use decrypt_ui::{DecryptPaneState, DecryptTab};
-use dock_tabs::DockTab;
-use eframe::egui::{self, Color32, Visuals};
-use egui_dock::{DockArea, DockState, Style as DockStyle, TabViewer};
-use events::{EventBus, EventSource, GhidrustEvent, MutationKind};
-use ghidrust_core::{
- analyzer_catalog, analyzer_supports_gpu, arch_mode_for_program, default_arch_mode,
- disassemble_at_opts, load_path, m3_tokens, recover_obfuscated_strings, set_preferred_bulk_mode,
- xrefs_from, xrefs_to, AnalysisRunReport, AnalyzerInfo, AnalyzerOutput, Arch, BulkScanMode,
- CommentKind, CryptConstantHit, CryptoCapabilityHit, FoundString, Instruction,
- ObfuscatedStringHit, Program, Project, ProjectTreeModel, RecoverStringsOpts, RttiReport,
- ThemeMode, XRef, BUILTIN_TYPES,
-};
-use graphs::{
- build_incoming_tree, build_outgoing_tree, data_xrefs_to, expand_tree_node, layout_call_graph,
- layout_function_graph, render_call_graph, render_function_graph, CallTreeNode,
- FunctionGraphLayout, GraphPaneState,
-};
-use icons::{m3_icon, m3_linear_progress, status_badge, M3Icon};
-use listing::{
- default_start_va, listing_matches, load_decode_prefs, reload, reload_for_goto,
- save_decode_prefs, ui_detail_pane, ui_options_dialog, ui_search_bar, ui_toolbar, DecodeUiOpts,
- ListingRow, ListingSearch, ToolbarAction,
-};
-use menu_actions::{
- address_table_hits, decompile_entry_for_va, listing_index_at_or_before, parse_address,
- parse_hex_pattern, processor_info, pseudo_c_for_stage, search_instruction_patterns,
- search_memory, search_program_text, search_scalars, stage0_pseudo_c,
- stage1_pseudo_c_with_tokens, DecompStage, ListingSelection, MemoryHit, TextHit,
- STAGE0_MAX_INSNS,
-};
-use nav::{NavHistory, NavLocation};
-use panes::{Bookmark, BookmarkKind, PaneKind};
-use register_manager::RegisterManagerState;
-use scripts::{
- render_mcp_repl, render_script_manager, render_text_editor, MacropadReplState,
- ScriptManagerState, TextEditorRequest, TextEditorState,
-};
-use std::collections::{BTreeMap, BTreeSet};
-use std::path::{Path, PathBuf};
-use std::sync::mpsc::{self, Receiver, RecvError, TryRecvError};
-
-/// Render one pseudo-C snippet from the Grok pane using the shared
-/// `decomp_tokens` highlighter — so agent-produced pseudo-C looks the same as
-/// the Decompiler pane's output.
-#[allow(dead_code)] // retained for future in-pane code blocks outside the TUI
-fn render_pseudo_c_inline(ui: &mut egui::Ui, body: &str) {
- let lines = tokenize_decomp(body);
- ui.group(|ui| {
- for line in &lines {
- let mut job = egui::text::LayoutJob::default();
- for tok in &line.tokens {
- let (color, italic) = token_style(&tok.kind, ui.visuals().text_color());
- let mut fmt = egui::TextFormat {
- color,
- font_id: egui::FontId::monospace(12.0),
- italics: italic,
- ..Default::default()
- };
- // Preserve original whitespace / newlines faithfully.
- if matches!(tok.kind, TokenKind::Comment) {
- fmt.italics = true;
- }
- job.append(&tok.text, 0.0, fmt);
- }
- ui.label(job);
- }
- });
-}
-
-/// Locate the workspace `skill/SKILL.md` when running from a repo checkout so
-/// the Grok session prompt can inline the exhaustive catalog. When Ghidrust
-/// is installed as a released binary and no adjacent skill file exists we
-/// return `(String::new(), None)` — the `SystemPromptBuilder` still emits the
-/// honesty rules from its own body, just without the catalog.
-fn load_skill_body() -> (String, Option<PathBuf>) {
- let candidates: Vec<PathBuf> = {
- let mut v = Vec::new();
- // 1. Adjacent to the running binary (production layout).
- if let Ok(exe) = std::env::current_exe() {
- if let Some(dir) = exe.parent() {
- v.push(dir.join("skill").join("SKILL.md"));
- if let Some(root) = dir.parent() {
- v.push(root.join("skill").join("SKILL.md"));
- }
- }
- }
- // 2. Workspace-local (development layout — cargo run from repo root).
- if let Ok(cwd) = std::env::current_dir() {
- v.push(cwd.join("skill").join("SKILL.md"));
- v.push(cwd.join(".").join("skill").join("SKILL.md"));
- }
- v
- };
- for c in candidates {
- if let Ok(body) = std::fs::read_to_string(&c) {
- return (body, Some(c));
- }
- }
- (String::new(), None)
-}
-
-fn recent_projects_path() -> PathBuf {
- // %APPDATA%/ghidrust/recent_projects.txt (or home fallback)
- if let Ok(appdata) = std::env::var("APPDATA") {
- PathBuf::from(appdata)
- .join("ghidrust")
- .join("recent_projects.txt")
- } else if let Ok(home) = std::env::var("USERPROFILE") {
- PathBuf::from(home)
- .join(".ghidrust")
- .join("recent_projects.txt")
- } else {
- PathBuf::from("ghidrust_recent_projects.txt")
- }
-}
-
-fn load_recent_projects() -> Vec<String> {
- let p = recent_projects_path();
- let Ok(text) = std::fs::read_to_string(&p) else {
- return Vec::new();
- };
- text.lines()
- .map(str::trim)
- .filter(|l| !l.is_empty() && Path::new(l).is_dir())
- .map(|s| s.to_string())
- .collect()
-}
-
-fn save_recent_projects(paths: &[String]) {
- let p = recent_projects_path();
- if let Some(parent) = p.parent() {
- let _ = std::fs::create_dir_all(parent);
- }
- let _ = std::fs::write(p, paths.join("\n"));
-}
-
-/// Messages from the background analysis worker → UI thread (polled each frame).
-enum AnalysisWorkerMsg {
- /// Analyzer at `index` is about to run.
- StepStarted { index: usize },
- /// Analyzer at `index` finished; `outputs` are that step's report rows.
- StepFinished {
- index: usize,
- outputs: Vec<AnalyzerOutput>,
- },
- /// All selected analyzers finished; return mutated program to the UI.
- Done { program: Program },
- /// Hard failure; program is returned so the UI can restore it (may include partial work).
- Failed { error: String, program: Program },
-}
-
-/// In-progress analysis. Heavy work runs on a background thread; the UI only polls `rx`.
-struct AnalysisJob {
- names: Vec<String>,
- index: usize,
- results: AnalysisRunReport,
- file_label: String,
- use_gpu: bool,
- rx: Receiver<AnalysisWorkerMsg>,
-}
+//! Ghidrust GUI binary entry.
fn main() -> eframe::Result<()> {
- let title = format!("Ghidrust {} CodeBrowser", env!("CARGO_PKG_VERSION"));
- let opts = eframe::NativeOptions {
- viewport: egui::ViewportBuilder::default()
- .with_inner_size([1280.0, 800.0])
- .with_title(&title)
- .with_icon(branding::window_icon()),
- ..Default::default()
- };
- eframe::run_native(
- &title,
- opts,
- Box::new(|cc| Ok(Box::new(GhidrustApp::new(cc)))),
- )
-}
-
-/// 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).
- Overview,
- Listing,
- Decompiler,
- 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,
- project_dir_input: String,
- project_name_input: String,
- status: String,
- console: Vec<String>,
- theme: ThemeMode,
- project: Option<Project>,
- active_file_id: Option<String>,
- program: Option<Program>,
- listing: Vec<Instruction>,
- rtti: RttiReport,
- strings: Vec<FoundString>,
- crypt_constants: Vec<CryptConstantHit>,
- crypto_constants_focus_va: Option<u64>,
- obfuscated_strings: Vec<ObfuscatedStringHit>,
- crypto_capabilities: Vec<CryptoCapabilityHit>,
- decrypt_pane: DecryptPaneState,
- last_analysis: AnalysisRunReport,
- 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,
- show_console: bool,
- /// Bottom dock (Grok/Console/Raw) height in points. Owned by us so the
- /// top-edge drag grip can resize reliably — egui's built-in
- /// `TopBottomPanel::resizable` snaps back unless content expands, which
- /// is easy to get wrong across versions.
- console_height: f32,
- show_analysis_dialog: bool,
- /// Use experimental GPU bulk path for string/byte scan analyzers.
- use_gpu_experimental: bool,
- /// File id to open when user confirms analysis dialog (from Project Tree).
- pending_analyze_file_id: Option<String>,
- /// Live analysis job (progress UI while stepping).
- analysis_job: Option<AnalysisJob>,
- /// Tree selection (may differ from active until Open).
- tree_selected_id: Option<String>,
- project_tree_expanded: bool,
- /// Pending delete: (file id, display name) — shown in confirm dialog.
- pending_delete: Option<(String, String)>,
- /// Dismissible banner after analysis finishes.
- analysis_done_banner: Option<String>,
- /// RTTI panel filter (case-insensitive substring).
- rtti_filter: String,
- rtti_filter_cache: String,
- rtti_filtered_idx: Vec<usize>,
- /// Function list filter.
- fn_filter: String,
- /// First-run: pick/open a project before the empty shell.
- show_startup_picker: bool,
- recent_projects: Vec<String>,
- /// Splash / startup mark under the Ghidrust heading.
- logo_texture: Option<egui::TextureHandle>,
- nyi_note: Option<String>,
- // ── selection / search / navigation. ──────
- listing_selection: ListingSelection,
- undo_stack: Vec<ListingSelection>,
- redo_stack: Vec<ListingSelection>,
- listing_focus_va: Option<u64>,
- show_goto_dialog: bool,
- goto_input: String,
- show_search_memory_dialog: bool,
- search_memory_input: String,
- show_search_text_dialog: bool,
- search_text_input: String,
- search_text_case_insensitive: bool,
- show_search_results: bool,
- memory_hits: Vec<MemoryHit>,
- text_hits: Vec<TextHit>,
- show_processor_dialog: bool,
- /// Cached decompiler pseudo-C for the focused function entry (None = stale / empty).
- decomp_entry: Option<u64>,
- decomp_text: String,
- decomp_status: String,
- /// Which decompile stage the Decompiler pane renders (Stage-0 / 0.5 / 1).
- decomp_stage: DecompStage,
- /// Last lift-coverage ratio (Stage-0.5 / Stage-1 only). Displayed as a
- /// small chip in the Decompiler pane header so users know how much of
- /// the emit came from real lifted IR vs Stage-0 scaffolding.
- decomp_lift_ratio: Option<f32>,
- // ── visible providers ─────────────
- /// Open-state per-provider (Window menu toggles → floating egui::Window per pane).
- pane_open: BTreeMap<PaneKind, bool>,
- /// (Back / Forward / Alt+Left / Alt+Right).
- nav_history: NavHistory,
- /// Guard so back/forward don't re-push into the history.
- nav_suspended: bool,
- /// Bookmark table (5 kinds).
- bookmarks: Vec<Bookmark>,
- /// Filter for Bookmarks pane.
- bookmark_filter: String,
- /// Add-bookmark dialog state.
- show_bookmark_dialog: bool,
- bookmark_dialog_kind: BookmarkKind,
- bookmark_dialog_category: String,
- bookmark_dialog_description: String,
- /// Filter for Functions window (separate from Symbol Tree filter).
- functions_window_filter: String,
- /// Filter for Symbol Table window.
- symbol_table_filter: String,
- /// Filter for Defined Strings window.
- defined_strings_filter: String,
- /// Defined Strings encoding filter: `"all"` | `"ascii"` | `"utf16le"`.
- defined_strings_encoding: String,
- /// plugin-event bus .
- event_bus: EventBus,
- /// tokenised decompiler cache (rebuilt after every refresh_decompiler_at).
- decomp_lines: Vec<DecompLine>,
- /// line index in `decomp_lines` cross-highlighted from Listing cursor.
- decomp_cross_line: Option<usize>,
- /// middle-click "highlight all occurrences" state.
- decomp_highlight_text: Option<String>,
- /// Symbol Tree ↔ Listing selection navigation toggle.
- symbol_tree_nav: bool,
- /// currently-focused function entry (for Symbol Tree highlight).
- focused_function_entry: Option<u64>,
- /// Program Tree fragment filter. `None` = full view; `Some({names})` = only those.
- listing_view_filter: Option<BTreeSet<String>>,
- /// Rename dialog state.
- show_rename_dialog: bool,
- rename_dialog_target_va: Option<u64>,
- rename_dialog_old_name: String,
- rename_dialog_new_name: String,
- /// Retype dialog state.
- show_retype_dialog: bool,
- retype_dialog_target_va: Option<u64>,
- retype_dialog_type: String,
- /// Comment dialog state.
- show_comment_dialog: bool,
- comment_dialog_target_va: Option<u64>,
- comment_dialog_kind: CommentKind,
- comment_dialog_text: String,
- /// Function Signature dialog state.
- show_fn_signature_dialog: bool,
- fn_signature_dialog_entry: Option<u64>,
- fn_signature_dialog_text: String,
- /// New Structure / Union / Enum dialog state.
- show_new_type_dialog: bool,
- new_type_dialog_kind: NewTypeKind,
- new_type_dialog_name: String,
- new_type_dialog_body: String,
- /// Edit-existing-type dialog state (structure /
- /// union / enum / typedef editor).
- show_edit_type_dialog: bool,
- edit_type_dialog_orig_name: String,
- edit_type_dialog_name: String,
- edit_type_dialog_body: String,
- /// Data Type Chooser dialog (`T` shortcut over Listing).
- show_type_chooser_dialog: bool,
- type_chooser_target_va: Option<u64>,
- type_chooser_filter: String,
- /// DTM filter.
- dtm_filter: String,
- /// Comment Window filters .
- comment_window_filter: String,
- comment_window_kind_filter: Option<CommentKind>,
- /// Console severity per line (`Info`, `Warn`, `Error`).
- console_severity: Vec<ConsoleSeverity>,
- // ── tables & search state ────────────────────────────
- /// Byte Viewer state .
- bytes_pane_va: Option<u64>,
- bytes_pane_bpr: usize,
- bytes_pane_rows: usize,
- /// Filter for Symbol References pane (name / address substring).
- 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)>,
- show_equate_dialog: bool,
- equate_dialog_va: Option<u64>,
- equate_dialog_op: u8,
- equate_dialog_name: String,
- equate_dialog_value: String,
- /// Function Tags — new-tag input + selected tag for row highlight.
- function_tags_new_input: String,
- /// External Programs filter.
- external_programs_filter: String,
- /// Data Type Preview — selected built-in for preview.
- data_type_preview_selected: String,
- /// Checksum Generator — cached results.
- checksum_last: Option<ChecksumReport>,
- /// Search → For Scalars.
- show_search_scalars_dialog: bool,
- search_scalars_min: String,
- search_scalars_max: String,
- /// Search → Instruction Patterns.
- show_search_insn_dialog: bool,
- search_insn_mnemonic: String,
- search_insn_operands: String,
- /// Search → For Address Tables (populated on-demand).
- show_search_address_tables_dialog: bool,
- /// Function Tags pane filter.
- function_tags_filter: String,
- // ── Graphs & maps ────────────────────────────────────
- /// Function Graph / Call Graph / Call Trees session state.
- graph_state: GraphPaneState,
- /// Function Call Trees — top-level nodes (rebuilt on cursor change).
- call_tree_incoming: Vec<CallTreeNode>,
- call_tree_outgoing: Vec<CallTreeNode>,
- /// Register Manager pane state (session-only until backend lattice lands).
- register_manager: RegisterManagerState,
- /// Memory Map editor — pending row edits (Add row).
- memory_map_new_name: String,
- memory_map_new_va: String,
- memory_map_new_size: String,
- memory_map_new_r: bool,
- memory_map_new_w: bool,
- memory_map_new_x: bool,
- // ── Scripts ──────────────────────────────────────────
- /// pane state.
- script_manager: ScriptManagerState,
- /// Text Editor multi-tab state.
- text_editor: TextEditorState,
- /// MCP REPL state.
- mcp_repl: MacropadReplState,
- // ── Debugger visibility ──────────────────────────────
- /// Debugger tool state (tabbed host + Live Process Bridge).
- debugger: DebuggerState,
- // ── Docking / layouts / Configure ───────────────────
- /// Configure dialog .
- show_configure_dialog: bool,
- /// Layout preset save/load dialog state.
- show_layouts_dialog: bool,
- layouts_new_name: String,
- layouts_cached: Vec<String>,
- /// Current layout name (empty = unnamed / default).
- current_layout_name: String,
- // ── Grok Build agent console (Option C: ACP sidecar) ───────────────
- /// Per-window Grok pane state (session, transcript, install prompts, mode).
- /// One project per window means one session at a time; 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,
- /// decode options for Listing / Disassembled View.
- decode_opts: DecodeUiOpts,
- /// Listing mnemonic / id / group filter.
- listing_search: ListingSearch,
- /// Full decode options dialog (arch/mode and engine options).
- show_decode_options_dialog: bool,
-}
-
-/// Checksum Generator report .
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct ChecksumReport {
- pub target: String,
- pub len: usize,
- pub crc32: u32,
- pub sum8: u32,
- pub sum16: u32,
- pub sum32: u64,
- pub adler32: u32,
- pub fletcher16: u32,
- pub fletcher32: u64,
-}
-
-/// severity tint for `Console` pane rows.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum ConsoleSeverity {
- Info,
- Warn,
- Error,
-}
-
-/// Checksum Generator scope .
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum ChecksumMode {
- /// Concatenation of every loaded memory block.
- WholeImage,
- /// A single memory block chosen by name.
- Section(String),
-}
-
-/// CRC-32/ISO-HDLC (polynomial `0xEDB88320`) — matches default.
-fn crc32_ieee(data: &[u8]) -> u32 {
- let mut c: u32 = 0xFFFF_FFFF;
- for &b in data {
- c ^= b as u32;
- for _ in 0..8 {
- let mask = (c & 1).wrapping_neg();
- c = (c >> 1) ^ (0xEDB8_8320 & mask);
- }
- }
- !c
-}
-
-fn adler32(data: &[u8]) -> u32 {
- const MOD: u32 = 65521;
- let mut a: u32 = 1;
- let mut b: u32 = 0;
- for &byte in data {
- a = (a + byte as u32) % MOD;
- b = (b + a) % MOD;
- }
- (b << 16) | a
-}
-
-fn fletcher_pair(data: &[u8]) -> (u32, u64) {
- let (mut a16, mut b16): (u16, u16) = (0, 0);
- for &byte in data {
- a16 = a16.wrapping_add(byte as u16);
- b16 = b16.wrapping_add(a16);
- }
- let f16 = ((b16 as u32) << 16) | a16 as u32;
-
- let (mut a32, mut b32): (u32, u32) = (0, 0);
- for chunk in data.chunks_exact(2) {
- let w = u16::from_le_bytes([chunk[0], chunk[1]]) as u32;
- a32 = a32.wrapping_add(w);
- b32 = b32.wrapping_add(a32);
- }
- let f32 = ((b32 as u64) << 32) | a32 as u64;
- (f16, f32)
-}
-
-/// Data Type Manager `New` submenu kinds.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum NewTypeKind {
- Structure,
- Union,
- Enum,
- Typedef,
- FunctionDefinition,
-}
-
-/// scalar hover popup content for a Listing operand string.
-///
-/// Extracts the first hex/decimal literal and renders 1/2/4/8-byte dec/hex/ASCII
-/// interpretations (matches "Scalar popup").
-fn first_scalar_hint(operands: &str) -> Option<String> {
- let mut chars = operands.char_indices().peekable();
- while let Some((i, c)) = chars.next() {
- if c == '0' && operands.as_bytes().get(i + 1) == Some(&b'x') {
- let start = i + 2;
- let end = operands[start..]
- .find(|c: char| !c.is_ascii_hexdigit())
- .map(|off| start + off)
- .unwrap_or(operands.len());
- if end > start {
- if let Ok(v) = u64::from_str_radix(&operands[start..end], 16) {
- return Some(scalar_hint_string(v));
- }
- }
- }
- if c.is_ascii_digit() {
- let start = i;
- let end = operands[start..]
- .find(|c: char| !c.is_ascii_digit())
- .map(|off| start + off)
- .unwrap_or(operands.len());
- if let Ok(v) = operands[start..end].parse::<u64>() {
- return Some(scalar_hint_string(v));
- }
- }
- }
- None
-}
-
-fn scalar_hint_string(v: u64) -> String {
- let ascii: String = v
- .to_le_bytes()
- .iter()
- .take_while(|&&b| b != 0)
- .filter(|&&b| (0x20..0x7f).contains(&b))
- .map(|&b| b as char)
- .collect();
- format!(
- "scalar {v:#x} · dec {v} · i32 {}{} · ascii \"{ascii}\"",
- if (v as i32) < 0 { "" } else { "" },
- v as i32
- )
-}
-
-/// address hover popup content for a Listing operand string.
-fn first_address_hint(operands: &str) -> Option<String> {
- let idx = operands.find("0x")?;
- let start = idx + 2;
- let end = operands[start..]
- .find(|c: char| !c.is_ascii_hexdigit())
- .map(|off| start + off)
- .unwrap_or(operands.len());
- if end == start {
- return None;
- }
- let va = u64::from_str_radix(&operands[start..end], 16).ok()?;
- Some(format!("target addr {va:#x}"))
-}
-
-/// ``- syntax colour picker for the Decompiler pane.
-fn token_style(kind: &TokenKind, base: Color32) -> (Color32, bool) {
- match kind {
- // Keywords: cyan .
- TokenKind::Keyword => (Color32::from_rgb(0x64, 0xB5, 0xF6), false),
- // Function names: warm orange.
- TokenKind::Function => (Color32::from_rgb(0xFF, 0xB7, 0x4D), false),
- // Variables: white/text default.
- TokenKind::Variable => (base, false),
- // Block labels: purple.
- TokenKind::Label => (Color32::from_rgb(0xBA, 0x68, 0xC8), false),
- // Addresses: cyan for click-hint.
- TokenKind::Address => (Color32::from_rgb(0x4D, 0xD0, 0xE1), false),
- // Constants: lighter cyan.
- TokenKind::Constant => (Color32::from_rgb(0x80, 0xDE, 0xEA), false),
- // Comments: green italics.
- TokenKind::Comment => (Color32::from_rgb(0x81, 0xC7, 0x84), true),
- // Syntax / whitespace / newline: dimmed text.
- TokenKind::Syntax => (base.gamma_multiply(0.85), false),
- TokenKind::Whitespace | TokenKind::Newline => (base, false),
- }
-}
-
-impl NewTypeKind {
- const ALL: &'static [NewTypeKind] = &[
- NewTypeKind::Structure,
- NewTypeKind::Union,
- NewTypeKind::Enum,
- NewTypeKind::Typedef,
- NewTypeKind::FunctionDefinition,
- ];
-
- const fn label(self) -> &'static str {
- match self {
- NewTypeKind::Structure => "Structure",
- NewTypeKind::Union => "Union",
- NewTypeKind::Enum => "Enum",
- NewTypeKind::Typedef => "Typedef",
- NewTypeKind::FunctionDefinition => "Function Definition",
- }
- }
-
- const fn template(self) -> &'static str {
- match self {
- NewTypeKind::Structure => "// Ghidrust user structure.\n// One field per line: `type name` (Stage-0 stores as string).\nint32_t field_0;\n",
- NewTypeKind::Union => "// Ghidrust user union.\nint32_t as_int;\nfloat as_float;\n",
- NewTypeKind::Enum => "// Ghidrust user enum. `NAME = <value>` per line.\nA = 0,\nB = 1,\n",
- NewTypeKind::Typedef => "// Ghidrust typedef body: target type only.\nvoid *\n",
- NewTypeKind::FunctionDefinition => "// Ghidrust function definition: `ret (params)`.\nint (int, char *)\n",
- }
- }
-}
-
-/// Recursively render one Call Tree row.
-///
-/// The node's `children_loaded` flag is flipped on first expand so callers
-/// pay the xref cost only when the user opens a branch.
-fn render_call_tree_node(
- node: &mut CallTreeNode,
- idx: usize,
- direction: &'static str,
- prog: &Program,
- hide_thunks: bool,
- ui: &mut egui::Ui,
- _muted: Color32,
- primary: Color32,
- goto: &mut Option<u64>,
-) {
- let title = egui::RichText::new(format!("{} {:#x}", node.name, node.va)).monospace();
- let title = if node.is_thunk {
- title.color(Color32::from_rgb(0xFB, 0xC0, 0x2D))
- } else {
- title.color(primary)
- };
- let resp = egui::CollapsingHeader::new(title)
- .id_salt((direction, node.va, idx))
- .default_open(false)
- .show(ui, |ui| {
- expand_tree_node(node, prog, direction, hide_thunks);
- if node.children.is_empty() {
- ui.small("(no further edges)");
- return;
- }
- for (i, child) in node.children.iter_mut().enumerate() {
- render_call_tree_node(
- child,
- i,
- direction,
- prog,
- hide_thunks,
- ui,
- _muted,
- primary,
- goto,
- );
- }
- });
- if resp.header_response.clicked() {
- *goto = Some(node.va);
- }
-}
-
-impl GhidrustApp {
- pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
- // Cascadia/Consolas + symbol fallbacks so the Grok TUI logo/box-drawing
- // aren't tofu (▯) under egui's tiny default monospace.
- grok_term::install_terminal_fonts(&cc.egui_ctx);
- let mut app = Self::headless();
- app.recent_projects = load_recent_projects();
- app.show_startup_picker = true;
- app.logo_texture = branding::load_logo_texture(&cc.egui_ctx);
- app.status = "Select a project to begin".into();
- app.apply_theme(&cc.egui_ctx);
- app
- }
-
- pub fn headless() -> Self {
- let infos = analyzer_catalog();
- let enabled = infos.iter().map(|a| a.default_enabled).collect();
- Self {
- path_input: String::new(),
- project_dir_input: String::new(),
- project_name_input: "MyProject".into(),
- status: "Ready — File → New/Open Project, then Import binary".into(),
- console: vec!["Ghidrust CodeBrowser started.".into()],
- theme: ThemeMode::Dark,
- project: None,
- active_file_id: None,
- program: None,
- listing: Vec::new(),
- rtti: RttiReport::default(),
- strings: Vec::new(),
- crypt_constants: Vec::new(),
- crypto_constants_focus_va: None,
- obfuscated_strings: Vec::new(),
- crypto_capabilities: Vec::new(),
- decrypt_pane: DecryptPaneState::default(),
- last_analysis: AnalysisRunReport::default(),
- last_analyzers_run: Vec::new(),
- analyzer_enabled: enabled,
- analyzer_infos: infos,
- center: CenterPane::Listing,
- center_dock: dock_tabs::default_dock_state(),
- show_project_tree: true,
- show_program_tree: true,
- show_symbol_tree: true,
- show_console: true,
- console_height: 280.0,
- show_analysis_dialog: false,
- use_gpu_experimental: false,
- pending_analyze_file_id: None,
- analysis_job: None,
- tree_selected_id: None,
- project_tree_expanded: true,
- pending_delete: None,
- analysis_done_banner: None,
- rtti_filter: String::new(),
- rtti_filter_cache: String::new(),
- rtti_filtered_idx: Vec::new(),
- fn_filter: String::new(),
- show_startup_picker: false,
- recent_projects: Vec::new(),
- logo_texture: None,
- nyi_note: None,
- listing_selection: ListingSelection::default(),
- undo_stack: Vec::new(),
- redo_stack: Vec::new(),
- listing_focus_va: None,
- show_goto_dialog: false,
- goto_input: String::new(),
- show_search_memory_dialog: false,
- search_memory_input: String::new(),
- show_search_text_dialog: false,
- search_text_input: String::new(),
- search_text_case_insensitive: true,
- show_search_results: false,
- memory_hits: Vec::new(),
- text_hits: Vec::new(),
- show_processor_dialog: false,
- decomp_entry: None,
- decomp_text: String::new(),
- decomp_status: String::new(),
- // Stage-1 is now the default GUI decompiler stage —
- // real SSA + structure + types instead of the mnemonic-scaffold
- // Stage-0 preview. Users can still pick Stage-0/Stage-0.5 from
- // the stage picker combo box.
- decomp_stage: DecompStage::Stage1,
- decomp_lift_ratio: None,
- pane_open: Self::default_pane_open(),
- nav_history: NavHistory::default(),
- nav_suspended: false,
- bookmarks: Vec::new(),
- bookmark_filter: String::new(),
- show_bookmark_dialog: false,
- bookmark_dialog_kind: BookmarkKind::Note,
- bookmark_dialog_category: String::new(),
- bookmark_dialog_description: String::new(),
- 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,
- decomp_highlight_text: None,
- symbol_tree_nav: true,
- focused_function_entry: None,
- listing_view_filter: None,
- show_rename_dialog: false,
- rename_dialog_target_va: None,
- rename_dialog_old_name: String::new(),
- rename_dialog_new_name: String::new(),
- show_retype_dialog: false,
- retype_dialog_target_va: None,
- retype_dialog_type: String::new(),
- show_comment_dialog: false,
- comment_dialog_target_va: None,
- comment_dialog_kind: CommentKind::Eol,
- comment_dialog_text: String::new(),
- show_fn_signature_dialog: false,
- fn_signature_dialog_entry: None,
- fn_signature_dialog_text: String::new(),
- show_new_type_dialog: false,
- new_type_dialog_kind: NewTypeKind::Structure,
- new_type_dialog_name: String::new(),
- new_type_dialog_body: String::new(),
- show_edit_type_dialog: false,
- edit_type_dialog_orig_name: String::new(),
- edit_type_dialog_name: String::new(),
- edit_type_dialog_body: String::new(),
- show_type_chooser_dialog: false,
- type_chooser_target_va: None,
- type_chooser_filter: String::new(),
- dtm_filter: String::new(),
- comment_window_filter: String::new(),
- comment_window_kind_filter: None,
- console_severity: vec![ConsoleSeverity::Info],
- bytes_pane_va: None,
- bytes_pane_bpr: 16,
- 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,
- equate_dialog_va: None,
- equate_dialog_op: 0,
- equate_dialog_name: String::new(),
- equate_dialog_value: String::new(),
- function_tags_new_input: String::new(),
- external_programs_filter: String::new(),
- data_type_preview_selected: "dword".into(),
- checksum_last: None,
- show_search_scalars_dialog: false,
- search_scalars_min: "0".into(),
- search_scalars_max: "0xffff".into(),
- show_search_insn_dialog: false,
- search_insn_mnemonic: String::new(),
- search_insn_operands: String::new(),
- show_search_address_tables_dialog: false,
- function_tags_filter: String::new(),
- graph_state: GraphPaneState {
- fn_graph_zoom: 1.0,
- ..GraphPaneState::default()
- },
- call_tree_incoming: Vec::new(),
- call_tree_outgoing: Vec::new(),
- register_manager: RegisterManagerState::default(),
- memory_map_new_name: String::new(),
- memory_map_new_va: String::new(),
- memory_map_new_size: String::new(),
- memory_map_new_r: true,
- memory_map_new_w: false,
- memory_map_new_x: false,
- script_manager: ScriptManagerState::new_with_builtin(),
- text_editor: TextEditorState::default(),
- mcp_repl: MacropadReplState::default(),
- debugger: DebuggerState::default(),
- show_configure_dialog: false,
- show_layouts_dialog: false,
- layouts_new_name: String::new(),
- 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,
- decode_opts: DecodeUiOpts::default(),
- listing_search: ListingSearch::default(),
- show_decode_options_dialog: false,
- }
- }
-
- /// Default `Window → *` toggles. Everything is available; only well-supported panes
- /// float open by default so users see the full surface but aren't buried.
- fn default_pane_open() -> BTreeMap<PaneKind, bool> {
- let mut m = BTreeMap::new();
- for k in PaneKind::ALL {
- m.insert(*k, false);
- }
- m
- }
-
- /// Toggle a floating provider window (used by `Window` menu + toolbar shortcuts).
- pub fn toggle_pane(&mut self, kind: PaneKind, open: bool) {
- self.pane_open.insert(kind, open);
- }
-
- /// Whether the given provider is currently visible.
- pub fn is_pane_open(&self, kind: PaneKind) -> bool {
- *self.pane_open.get(&kind).unwrap_or(&false)
- }
-
- fn clear_decompiler_cache(&mut self) {
- self.decomp_entry = None;
- self.decomp_text.clear();
- self.decomp_status.clear();
- self.decomp_lines.clear();
- self.decomp_cross_line = None;
- self.decomp_lift_ratio = None;
- }
-
- /// Refresh the decompiler cache for `va` (containing / nearest function)
- /// at the currently-selected [`DecompStage`] (Stage-0 / 0.5 / 1).
- ///
- /// Also rebuilds the tokenised `decomp_lines` cache used by the pane for
- /// click-navigation and cross-highlight with the Listing. If Stage-0.5
- /// / Stage-1 fail (e.g. structuring gave up on an irreducible region)
- /// the pane silently falls back to Stage-0 so the user always sees
- /// something.
- pub fn refresh_decompiler_at(&mut self, va: u64) {
- let Some(prog) = self.program.as_ref() else {
- self.decomp_entry = None;
- self.decomp_text.clear();
- self.decomp_status = "No program loaded.".into();
- self.decomp_lines.clear();
- self.decomp_cross_line = None;
- self.decomp_lift_ratio = None;
- return;
- };
- let entry = decompile_entry_for_va(prog, va);
- let cache_ok = self.decomp_entry == Some(entry)
- && !self.decomp_text.is_empty()
- && self.decomp_status.contains(self.decomp_stage.label());
- if cache_ok {
- self.decomp_cross_line = decomp_line_for_va(&self.decomp_lines, va);
- return;
- }
- let stage = self.decomp_stage;
- // R5: Stage-1 prefers emit-time tokens when present.
- if stage == DecompStage::Stage1 {
- if let Ok((entry, text, ratio, tokens)) =
- stage1_pseudo_c_with_tokens(prog, va, STAGE0_MAX_INSNS)
- {
- self.decomp_entry = Some(entry);
- let triples = emit_token_triples(&tokens);
- let lines = from_emit_tokens(&triples);
- self.decomp_lines = if lines.is_empty() {
- tokenize_decomp(&text)
- } else {
- lines
- };
- self.decomp_cross_line = decomp_line_for_va(&self.decomp_lines, va);
- self.decomp_text = text;
- self.decomp_lift_ratio = Some(ratio);
- let user_name = self
- .program
- .as_ref()
- .and_then(|p| p.display_function_name_at(entry));
- self.decomp_status = match user_name {
- Some(name) => {
- format!("Stage-1 · {name} @ {entry:#x} · lift={:.1}%", ratio * 100.0)
- }
- None => format!("Stage-1 · {entry:#x} · lift={:.1}%", ratio * 100.0),
- };
- return;
- }
- }
- let attempt = pseudo_c_for_stage(prog, va, STAGE0_MAX_INSNS, stage);
- let (label, result) = match attempt {
- Ok(v) => (stage.label(), Ok(v)),
- Err(_) if stage != DecompStage::Stage0 => {
- // Never render an empty pane — retry at Stage-0.
- let fallback =
- stage0_pseudo_c(prog, va, STAGE0_MAX_INSNS).map(|(e, t)| (e, t, None));
- (DecompStage::Stage0.label(), fallback)
- }
- Err(e) => (stage.label(), Err(e)),
- };
- match result {
- Ok((entry, text, ratio)) => {
- self.decomp_entry = Some(entry);
- self.decomp_lines = tokenize_decomp(&text);
- self.decomp_cross_line = decomp_line_for_va(&self.decomp_lines, va);
- self.decomp_text = text;
- self.decomp_lift_ratio = ratio;
- let user_name = self
- .program
- .as_ref()
- .and_then(|p| p.display_function_name_at(entry));
- self.decomp_status = match (user_name, ratio) {
- (Some(name), Some(r)) => {
- format!("{label} · {name} @ {entry:#x} · lift={:.1}%", r * 100.0)
- }
- (Some(name), None) => format!("{label} · {name} @ {entry:#x}"),
- (None, Some(r)) => {
- format!("{label} · {entry:#x} · lift={:.1}%", r * 100.0)
- }
- (None, None) => format!("{label} · {entry:#x}"),
- };
- }
- Err(e) => {
- self.decomp_entry = Some(entry);
- self.decomp_text = format!("// decompile failed at {entry:#x}\n// {e}\n");
- self.decomp_lines = tokenize_decomp(&self.decomp_text);
- self.decomp_cross_line = None;
- self.decomp_lift_ratio = None;
- self.decomp_status = format!("error: {e}");
- }
- }
- }
-
- /// Switch the active decompile stage (Stage-0 / 0.5 / 1) and re-run the
- /// emit for the currently-focused function entry. Public so the pane
- /// dropdown + tests can drive it.
- pub fn set_decomp_stage(&mut self, stage: DecompStage) {
- if self.decomp_stage == stage {
- return;
- }
- self.decomp_stage = stage;
- self.decomp_text.clear();
- self.decomp_lines.clear();
- self.decomp_cross_line = None;
- self.decomp_lift_ratio = None;
- if let Some(va) = self.decomp_entry {
- self.refresh_decompiler_at(va);
- }
- }
-
- /// Current decompile stage — used by the pane header dropdown and tests.
- pub fn decomp_stage(&self) -> DecompStage {
- self.decomp_stage
- }
-
- /// Latest lift coverage ratio (Stage-0.5 / Stage-1 only).
- pub fn decomp_lift_ratio(&self) -> Option<f32> {
- 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}");
- if let Err(e) = self.goto_address_str(&addr) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- return;
- }
- self.focused_function_entry = Some(entry);
- self.refresh_decompiler_at(entry);
- self.focus_center_tab(DockTab::Decompiler);
- let name = self
- .program
- .as_ref()
- .and_then(|p| p.display_function_name_at(entry))
- .unwrap_or_else(|| format!("{entry:#x}"));
- self.status = format!("Function {name}");
- self.log(self.status.clone());
- }
-
- /// Navigation → Back (Alt+Left).
- ///
- /// Pops the previous location off the Back stack and re-runs `goto_address_str`
- /// without recording another entry (guarded by `nav_suspended`).
- pub fn nav_back(&mut self) -> bool {
- let Some(prev) = self.nav_history.back() else {
- self.status = "Navigation → nothing to go back to".into();
- self.log(self.status.clone());
- return false;
- };
- self.nav_suspended = true;
- let r = self.goto_address_str(&format!("{:#x}", prev.va));
- self.nav_suspended = false;
- if let Err(e) = r {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- return false;
- }
- self.refresh_decompiler_at(prev.va);
- self.status = format!("Back → {:#x}", prev.va);
- self.log(self.status.clone());
- true
- }
-
- /// Navigation → Forward (Alt+Right).
- pub fn nav_forward(&mut self) -> bool {
- let Some(next) = self.nav_history.forward() else {
- self.status = "Navigation → nothing to go forward to".into();
- self.log(self.status.clone());
- return false;
- };
- self.nav_suspended = true;
- let r = self.goto_address_str(&format!("{:#x}", next.va));
- self.nav_suspended = false;
- if let Err(e) = r {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- return false;
- }
- self.refresh_decompiler_at(next.va);
- self.status = format!("Forward → {:#x}", next.va);
- self.log(self.status.clone());
- true
- }
-
- /// Convenience: are we able to step back?
- pub fn can_nav_back(&self) -> bool {
- self.nav_history.can_back()
- }
- pub fn can_nav_forward(&self) -> bool {
- self.nav_history.can_forward()
- }
-
- /// Bookmarks → Add (BookmarkPlugin analog). Va + kind + category + description.
- pub fn add_bookmark(
- &mut self,
- va: u64,
- kind: BookmarkKind,
- category: impl Into<String>,
- description: impl Into<String>,
- ) {
- self.bookmarks.push(Bookmark {
- va,
- kind,
- category: category.into(),
- description: description.into(),
- });
- self.pane_open.insert(PaneKind::Bookmarks, true);
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::BookmarkAdded { va },
- });
- self.status = format!("Bookmark added at {va:#x} ({})", kind.label());
- self.log(self.status.clone());
- }
-
- /// Bookmarks → Delete.
- pub fn delete_bookmark(&mut self, index: usize) {
- if index < self.bookmarks.len() {
- let b = self.bookmarks.remove(index);
- let va = b.va;
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::BookmarkRemoved { va },
- });
- self.status = format!("Bookmark removed at {va:#x} ({})", b.kind.label());
- self.log(self.status.clone());
- }
- }
-
- /// Look up bookmarks at (or covering) `va` for margin-marker rendering.
- pub fn bookmarks_at(&self, va: u64) -> Vec<&Bookmark> {
- self.bookmarks.iter().filter(|b| b.va == va).collect()
- }
-
- /// Navigation → Next Bookmark.
- pub fn nav_next_bookmark(&mut self) {
- if self.bookmarks.is_empty() {
- self.status = "No bookmarks — Bookmarks → Add".into();
- self.log(self.status.clone());
- return;
- }
- let cur = self.listing_focus_va.unwrap_or(0);
- let mut vas: Vec<u64> = self.bookmarks.iter().map(|b| b.va).collect();
- vas.sort();
- if let Some(va) = vas.iter().copied().find(|&va| va > cur) {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- } else {
- let _ = self.goto_address_str(&format!("{:#x}", vas[0]));
- }
- }
-
- /// Navigation → Previous Bookmark.
- pub fn nav_prev_bookmark(&mut self) {
- if self.bookmarks.is_empty() {
- self.status = "No bookmarks — Bookmarks → Add".into();
- self.log(self.status.clone());
- return;
- }
- let cur = self.listing_focus_va.unwrap_or(u64::MAX);
- let mut vas: Vec<u64> = self.bookmarks.iter().map(|b| b.va).collect();
- vas.sort();
- if let Some(va) = vas.iter().rev().copied().find(|&va| va < cur) {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- } else {
- let _ = self.goto_address_str(&format!("{:#x}", vas.last().copied().unwrap()));
- }
- }
-
- // ── user edits ───────────────────────────────────────
-
- /// Rename the symbol / function at `va` (persists into `Program::edits`).
- ///
- /// Also mirrors the rename into `Program::analysis.functions[i].name()` so
- /// every downstream pane (Symbol Tree, Functions Window, Symbol Table,
- /// Bookmarks label preview) sees the new name without a full re-analyze.
- /// Emits a `ProgramMutated::Rename` event which invalidates the Decompiler
- /// cache so the header string is rebuilt.
- pub fn rename_at(&mut self, va: u64, new_name: impl Into<String>) -> Result<(), String> {
- let new_name = new_name.into();
- if new_name.trim().is_empty() {
- return Err("empty name".into());
- }
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- // Mirror into analysis so tables / listing / decomp header pick it up.
- if let Some(f) = prog.function_at_mut(va) {
- f.name = new_name.clone();
- } else if let Some(s) = prog.analysis.symbols.iter_mut().find(|s| s.va == va) {
- s.name = new_name.clone();
- }
- // Persist as an edit even if analysis had no matching entry.
- prog.edits.set_rename(va, &new_name);
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Rename {
- va,
- new_name: new_name.clone(),
- },
- });
- self.status = format!("Renamed {va:#x} → {new_name}");
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Retype the variable / global at `va` (persists into `Program::edits`).
- pub fn retype_at(&mut self, va: u64, type_desc: impl Into<String>) -> Result<(), String> {
- let type_desc = type_desc.into();
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- prog.edits.set_retype(va, &type_desc);
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va,
- type_desc: type_desc.clone(),
- },
- });
- self.status = format!("Retyped {va:#x} → {type_desc}");
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Set (or clear) a comment at `va` (persists into `Program::edits`).
- pub fn set_comment_at(
- &mut self,
- va: u64,
- kind: CommentKind,
- text: impl Into<String>,
- ) -> Result<(), String> {
- let text = text.into();
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- prog.edits.set_comment(va, kind, &text);
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::CommentChanged { va },
- });
- self.status = if text.is_empty() {
- format!("Cleared {} comment at {va:#x}", kind.label())
- } else {
- format!("Set {} comment at {va:#x}", kind.label())
- };
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Set / replace a function signature (Edit Function Signature dialog).
- pub fn set_function_signature(
- &mut self,
- entry: u64,
- signature: impl Into<String>,
- ) -> Result<(), String> {
- let signature = signature.into();
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- let mut sig = prog
- .edits
- .function_signature(entry)
- .cloned()
- .unwrap_or_default();
- sig.signature = signature.clone();
- prog.edits.set_function_signature(entry, sig);
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va: entry,
- type_desc: signature.clone(),
- },
- });
- self.status = format!("Function signature @ {entry:#x} → {signature}");
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Decompiler → Commit Params/Return. Adopts the analyzer-inferred parameter
- /// list + a "auto" return type as user commitments.
- pub fn commit_params_return(&mut self, entry: u64) -> Result<(), String> {
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- let (params, ret) = {
- let f = prog
- .function_at(entry)
- .ok_or_else(|| format!("no function at {entry:#x}"))?;
- let params: Vec<String> = if f.parameters.is_empty() {
- Vec::new()
- } else {
- f.parameters.clone()
- };
- // Ghidrust Stage-0 has no dataflow return-type yet — commit as `undefined`.
- (params, "undefined".to_string())
- };
- prog.edits.commit_params(entry, params.clone());
- prog.edits.commit_return_type(entry, &ret);
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va: entry,
- type_desc: format!("commit params: {} · return {ret}", params.len()),
- },
- });
- self.status = format!(
- "Commit Params/Return @ {entry:#x} ({} param(s), return {ret})",
- params.len()
- );
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Decompiler → Commit Locals. Persists analyzer-inferred stack locals as
- /// user edits so a later rename doesn't require re-analyzing.
- pub fn commit_locals(&mut self, entry: u64) -> Result<(), String> {
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- let locals = {
- let f = prog
- .function_at(entry)
- .ok_or_else(|| format!("no function at {entry:#x}"))?;
- f.stack_locals.clone()
- };
- prog.edits.commit_locals(entry, locals.clone());
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va: entry,
- type_desc: format!("commit locals: {}", locals.len()),
- },
- });
- self.status = format!("Commit Locals @ {entry:#x} ({} local(s))", locals.len());
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Data Type Manager → New Structure / Union / Enum / Typedef / Function Def.
- pub fn define_user_type(
- &mut self,
- name: impl Into<String>,
- body: impl Into<String>,
- ) -> Result<(), String> {
- let name = name.into();
- let body = body.into();
- if name.trim().is_empty() {
- return Err("empty type name".into());
- }
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- prog.edits.set_user_type(name.clone(), body);
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va: 0,
- type_desc: format!("user type: {name}"),
- },
- });
- self.status = format!("New type: {name}");
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Listing → Apply Data Type at `va` (drag from DTM, or `T` key).
- pub fn apply_type_at(&mut self, va: u64, type_name: impl Into<String>) -> Result<(), String> {
- let type_name = type_name.into();
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- prog.edits.set_applied_type(va, &type_name);
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va,
- type_desc: type_name.clone(),
- },
- });
- self.status = format!("Applied type {type_name} @ {va:#x}");
- self.log(self.status.clone());
- Ok(())
- }
-
- /// DTM → Rename an existing user type (`Rename` on a Data Type
- /// leaf). Rewrites `applied_types` so Listing decorations stay in sync.
- pub fn rename_user_type(
- &mut self,
- old: impl Into<String>,
- new: impl Into<String>,
- ) -> Result<(), String> {
- let old = old.into();
- let new = new.into();
- if new.trim().is_empty() {
- return Err("empty type name".into());
- }
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- if !prog.edits.rename_user_type(&old, &new) {
- return Err(format!("no type named {old}"));
- }
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va: 0,
- type_desc: format!("rename type: {old} → {new}"),
- },
- });
- self.status = format!("Renamed type {old} → {new}");
- self.log(self.status.clone());
- Ok(())
- }
-
- /// DTM → Delete a user type (also unlinks any `Applied` decorations).
- pub fn delete_user_type(&mut self, name: &str) -> Result<(), String> {
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- if !prog.edits.delete_user_type(name) {
- return Err(format!("no type named {name}"));
- }
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va: 0,
- type_desc: format!("deleted type: {name}"),
- },
- });
- self.status = format!("Deleted type {name}");
- self.log(self.status.clone());
- Ok(())
- }
-
- /// DTM → Edit an existing user type body (Structure / Union /
- /// Enum / Typedef editor). May also rename in the same operation.
- pub fn edit_user_type(
- &mut self,
- orig_name: &str,
- new_name: impl Into<String>,
- body: impl Into<String>,
- ) -> Result<(), String> {
- let new_name = new_name.into();
- let body = body.into();
- if new_name.trim().is_empty() {
- return Err("empty type name".into());
- }
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- if !prog.edits.user_types.contains_key(orig_name) {
- return Err(format!("no type named {orig_name}"));
- }
- if orig_name != new_name {
- let _ = prog.edits.rename_user_type(orig_name, &new_name);
- }
- prog.edits.set_user_type(new_name.clone(), body);
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va: 0,
- type_desc: format!("edit type: {new_name}"),
- },
- });
- self.status = format!("Edited type {new_name}");
- self.log(self.status.clone());
- Ok(())
- }
-
- /// DTM → New Typedef on X . Creates a
- /// typedef whose body records the underlying type; the resulting user
- /// type can be applied at Listing addresses just like any other.
- pub fn new_typedef_on(&mut self, source: &str) -> Result<String, String> {
- let name = format!("typedef_{source}");
- let body = format!("Typedef\ntypedef {source} {name};");
- self.define_user_type(&name, body)?;
- Ok(name)
- }
-
- /// DTM → New Pointer to X. Registers a `<X> *` user type so the Listing
- /// can apply the pointer decoration without a full parser.
- pub fn new_pointer_to(&mut self, source: &str) -> Result<String, String> {
- let name = format!("{source} *");
- let body = format!("Typedef\n{source} *");
- self.define_user_type(&name, body)?;
- Ok(name)
- }
-
- // ── equates, function tags, xrefs, checksums ──────────
-
- /// Attach an equate `name` at `(va, op)` for scalar `value` (
- /// `Convert → Equate`). Empty `name` clears the equate.
- pub fn set_equate(
- &mut self,
- va: u64,
- op: u8,
- name: impl Into<String>,
- value: i64,
- ) -> Result<(), String> {
- let name = name.into();
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- let clearing = name.is_empty();
- prog.edits.set_equate(va, op, &name, value);
- // Equates render inline in the Listing operand slot; treat as retype
- // for cache invalidation so the Decompiler picks the change up too.
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va,
- type_desc: if clearing {
- format!("cleared equate @ op {op}")
- } else {
- format!("equate {name} = {value}")
- },
- },
- });
- self.status = if clearing {
- format!("Cleared equate @ {va:#x} op {op}")
- } else {
- format!("Set equate {name} = {value} @ {va:#x} op {op}")
- };
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Function Tags — add / remove / delete-everywhere (
- /// `FunctionTagPlugin`).
- pub fn add_function_tag(&mut self, entry: u64, tag: impl Into<String>) -> Result<(), String> {
- let tag = tag.into();
- if tag.trim().is_empty() {
- return Err("empty tag".into());
- }
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- prog.edits.add_function_tag(entry, &tag);
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va: entry,
- type_desc: format!("tag+ {tag}"),
- },
- });
- self.status = format!("Tag '{tag}' added to fn @ {entry:#x}");
- self.log(self.status.clone());
- Ok(())
- }
-
- pub fn remove_function_tag(&mut self, entry: u64, tag: &str) -> Result<(), String> {
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- let removed = prog.edits.remove_function_tag(entry, tag);
- if !removed {
- return Err(format!("fn @ {entry:#x} has no tag '{tag}'"));
- }
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va: entry,
- type_desc: format!("tag- {tag}"),
- },
- });
- self.status = format!("Tag '{tag}' removed from fn @ {entry:#x}");
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Register a tag in the universe (`ProgramEdits::all_function_tags`)
- /// without assigning it to a function. "Create tag" action
- /// lands here.
- pub fn create_tag(&mut self, tag: impl Into<String>) -> Result<(), String> {
- let tag = tag.into();
- if tag.trim().is_empty() {
- return Err("empty tag".into());
- }
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- prog.edits.all_function_tags.insert(tag.clone());
- self.status = format!("Created tag '{tag}'");
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Delete a tag from every function and from the universe.
- pub fn delete_tag_everywhere(&mut self, tag: &str) -> Result<(), String> {
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- let n = prog.edits.delete_tag_everywhere(tag);
- self.event_bus.publish(GhidrustEvent::ProgramMutated {
- kind: MutationKind::Retype {
- va: 0,
- type_desc: format!("tag deleted: {tag}"),
- },
- });
- self.status = format!("Tag '{tag}' deleted from {n} function(s)");
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Compute references TO the given target VA. Uses `ghidrust-core::xrefs`
- /// against the current program + focused-window listing.
- pub fn xrefs_to_va(&self, target: u64) -> Vec<XRef> {
- let Some(prog) = self.program.as_ref() else {
- return Vec::new();
- };
- xrefs_to(prog, target, Some(&self.listing))
- }
-
- /// Compute references FROM the given source VA.
- pub fn xrefs_from_va(&self, source: u64) -> Vec<XRef> {
- let Some(prog) = self.program.as_ref() else {
- return Vec::new();
- };
- xrefs_from(prog, source, STAGE0_MAX_INSNS)
- }
-
- /// Compute a checksum panel over the loaded program (or focused block).
- pub fn compute_checksums(&mut self, mode: ChecksumMode) -> Result<(), String> {
- let prog = self
- .program
- .as_ref()
- .ok_or_else(|| "no program loaded".to_string())?;
- let (target_label, data): (String, Vec<u8>) = match mode {
- ChecksumMode::WholeImage => {
- let bytes: Vec<u8> = prog.blocks.iter().flat_map(|b| b.bytes.clone()).collect();
- (format!("Whole image ({})", prog.name), bytes)
- }
- ChecksumMode::Section(name) => {
- let b = prog
- .blocks
- .iter()
- .find(|b| b.name == name)
- .ok_or_else(|| format!("no block named {name}"))?;
- (format!("Block {name}"), b.bytes.clone())
- }
- };
- let len = data.len();
- let crc32 = crc32_ieee(&data);
- let sum8: u32 = data.iter().map(|&b| b as u32).sum();
- let sum16: u32 = data
- .chunks_exact(2)
- .map(|c| u16::from_le_bytes([c[0], c[1]]) as u32)
- .sum::<u32>();
- let sum32: u64 = data
- .chunks_exact(4)
- .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]) as u64)
- .sum::<u64>();
- let adler32 = adler32(&data);
- let (fletcher16, fletcher32) = fletcher_pair(&data);
- self.checksum_last = Some(ChecksumReport {
- target: target_label,
- len,
- crc32,
- sum8,
- sum16,
- sum32,
- adler32,
- fletcher16,
- fletcher32,
- });
- self.status = format!("Checksum: crc32={crc32:#010x} adler32={adler32:#010x} len={len}",);
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Program Tree → Set View / Add To View / Remove From View / Show All.
- ///
- /// The semantic is a **fragment name set**. `None` = full view.
- pub fn set_listing_view(&mut self, fragments: Option<BTreeSet<String>>) {
- self.listing_view_filter = fragments;
- }
-
- pub fn add_to_view(&mut self, fragment: impl Into<String>) {
- let name = fragment.into();
- let entry = self.listing_view_filter.get_or_insert_with(BTreeSet::new);
- entry.insert(name);
- }
-
- pub fn remove_from_view(&mut self, fragment: &str) {
- if let Some(set) = self.listing_view_filter.as_mut() {
- set.remove(fragment);
- if set.is_empty() {
- // Empty view → drop the filter so Listing shows nothing but
- // reflects an honest empty state driven by fragment membership.
- }
- }
- }
-
- pub fn clear_view_filter(&mut self) {
- self.listing_view_filter = None;
- }
-
- /// Whether a Listing address is currently in-view (Program Tree filter).
- pub fn addr_in_view(&self, va: u64) -> bool {
- let Some(filter) = self.listing_view_filter.as_ref() else {
- return true;
- };
- let Some(prog) = self.program.as_ref() else {
- return true;
- };
- prog.blocks
- .iter()
- .filter(|b| filter.contains(&b.name))
- .any(|b| va >= b.va && va < b.va.saturating_add(b.size))
- }
-
- /// Navigation → Next Function.
- pub fn nav_next_function(&mut self) {
- let cur = self.listing_focus_va.unwrap_or(0);
- let entries: Vec<u64> = self
- .program
- .as_ref()
- .map(|p| p.analysis.functions.iter().map(|f| f.entry).collect())
- .unwrap_or_default();
- if entries.is_empty() {
- self.status = "No functions — run Function Start Search".into();
- self.log_warn(self.status.clone());
- return;
- }
- let mut sorted: Vec<u64> = entries;
- sorted.sort();
- if let Some(&va) = sorted.iter().find(|&&e| e > cur) {
- self.focus_function(va);
- } else {
- self.focus_function(sorted[0]);
- }
- }
-
- /// Navigation → Previous Function.
- pub fn nav_prev_function(&mut self) {
- let cur = self.listing_focus_va.unwrap_or(u64::MAX);
- let entries: Vec<u64> = self
- .program
- .as_ref()
- .map(|p| p.analysis.functions.iter().map(|f| f.entry).collect())
- .unwrap_or_default();
- if entries.is_empty() {
- self.status = "No functions — run Function Start Search".into();
- self.log_warn(self.status.clone());
- return;
- }
- let mut sorted: Vec<u64> = entries;
- sorted.sort();
- if let Some(&va) = sorted.iter().rev().find(|&&e| e < cur) {
- self.focus_function(va);
- } else {
- self.focus_function(*sorted.last().unwrap());
- }
- }
-
- /// Program → Symbol Tree lookup: are Imports/Exports parseable from analysis?
- ///
- /// Ghidrust's PE loader doesn't yet parse the Import / Export directories, but
- /// PDB analyzers do populate `Program::analysis.pdb_symbols`. This helper
- /// returns (imports, exports) as best-effort lists derived from analyzer
- /// output — never fabricated. Empty lists = analyzer didn't populate.
- pub fn imports_exports(&self) -> (Vec<(u64, String)>, Vec<(u64, String)>) {
- let Some(prog) = self.program.as_ref() else {
- return (Vec::new(), Vec::new());
- };
- let mut imports = Vec::new();
- let mut exports = Vec::new();
- // Heuristic (source-honest): PDB symbols with `__imp_` prefix are imports.
- for s in &prog.analysis.pdb_symbols {
- if s.name.starts_with("__imp_")
- || s.name.starts_with("_imp_")
- || s.name.starts_with("__imp")
- {
- imports.push((s.va, s.name.clone()));
- }
- }
- // Section-based fallback: sections whose name contains "idata"/"iat" are
- // import metadata; expose their base as an anchor row.
- for s in &prog.sections {
- let n = s.name.to_ascii_lowercase();
- if n.contains("idata") || n.contains("iat") {
- imports.push((s.va, format!("{} @ {:#x}", s.name, s.va)));
- }
- if n.contains("edata") {
- exports.push((s.va, format!("{} @ {:#x}", s.name, s.va)));
- }
- }
- // Analysis symbols marked as exports by demangler are entry-like.
- for s in &prog.analysis.symbols {
- if s.demangled
- .as_ref()
- .map(|d| d.contains("__declspec(dllexport)"))
- .unwrap_or(false)
- {
- exports.push((s.va, s.name.clone()));
- }
- }
- imports.sort_by_key(|(va, _)| *va);
- imports.dedup_by(|a, b| a.1 == b.1);
- exports.sort_by_key(|(va, _)| *va);
- exports.dedup_by(|a, b| a.1 == b.1);
- (imports, exports)
- }
-
- /// drain queued events and fan them out to subscribers.
- ///
- /// This is intentionally minimal today: any ProgramMutated event invalidates
- /// the Decompiler cache so the next `refresh_decompiler_at` re-runs Stage-0.
- /// Cursor events are already handled by their emitters (listing / navigation
- /// call sites both refresh the decompiler themselves).
- pub fn drain_events(&mut self) -> Vec<GhidrustEvent> {
- let events = self.event_bus.drain();
- for ev in &events {
- match ev {
- GhidrustEvent::ProgramMutated { kind } => match kind {
- MutationKind::Rename { .. }
- | MutationKind::Retype { .. }
- | MutationKind::CommentChanged { .. }
- | MutationKind::Analysis => {
- self.clear_decompiler_cache();
- }
- MutationKind::BookmarkAdded { .. } | MutationKind::BookmarkRemoved { .. } => {}
- },
- GhidrustEvent::ProgramActivated { name } => {
- self.log(format!("Program activated: {name}"));
- }
- GhidrustEvent::CursorMoved { .. } | GhidrustEvent::SelectionChanged { .. } => {}
- }
- }
- events
- }
-
- fn push_selection_undo(&mut self) {
- self.undo_stack.push(self.listing_selection);
- if self.undo_stack.len() > 64 {
- self.undo_stack.remove(0);
- }
- self.redo_stack.clear();
- }
-
- /// Edit → Undo (selection history).
- pub fn edit_undo(&mut self) {
- if let Some(prev) = self.undo_stack.pop() {
- self.redo_stack.push(self.listing_selection);
- self.listing_selection = prev;
- self.status = "Undo: restored selection".into();
- self.log(self.status.clone());
- } else {
- self.status = "Nothing to undo".into();
- self.log(self.status.clone());
- }
- }
-
- /// Edit → Redo.
- pub fn edit_redo(&mut self) {
- if let Some(next) = self.redo_stack.pop() {
- self.undo_stack.push(self.listing_selection);
- self.listing_selection = next;
- self.status = "Redo: restored selection".into();
- self.log(self.status.clone());
- } else {
- self.status = "Nothing to redo".into();
- self.log(self.status.clone());
- }
- }
-
- /// Edit → Clear Selection.
- pub fn edit_clear_selection(&mut self) {
- self.push_selection_undo();
- self.listing_selection = ListingSelection::clear();
- self.status = "Selection cleared".into();
- self.log(self.status.clone());
- }
-
- /// Select → Select All (listing range).
- pub fn select_all_listing(&mut self) {
- self.push_selection_undo();
- self.listing_selection = ListingSelection::all(self.listing.len());
- self.status = format!("Selected all {} listing instruction(s)", self.listing.len());
- self.log(self.status.clone());
- self.focus_center_tab(DockTab::Listing);
- }
-
- /// decode arch for name lookup in listing/detail panes.
- fn listing_arch(&self) -> Arch {
- self.decode_opts
- .resolved_arch()
- .or_else(|| {
- self.program
- .as_ref()
- .and_then(arch_mode_for_program)
- .map(|(a, _)| a)
- })
- .unwrap_or_else(|| default_arch_mode().0)
- }
-
- /// Re-disassemble the listing window at `va` using current decode options.
- fn reload_listing_at(&mut self, va: u64) -> Result<(), String> {
- let prog = self
- .program
- .as_ref()
- .ok_or_else(|| "no program loaded".to_string())?;
- self.decode_opts.sync_machine_from_program(prog);
- self.listing_search.arch = self.listing_arch();
- let result = reload(prog, va, &self.decode_opts)?;
- if result.insns.is_empty() {
- return Err(format!("no instructions at {va:#x}"));
- }
- self.listing = result.insns;
- if let Some(proj) = &self.project {
- let _ = save_decode_prefs(&proj.root, &self.decode_opts);
- }
- Ok(())
- }
-
- fn apply_decode_opts(&mut self) {
- let va = self
- .listing_focus_va
- .or_else(|| self.listing.first().map(|i| i.address))
- .or_else(|| self.program.as_ref().and_then(|p| p.entry))
- .or_else(|| self.program.as_ref().map(|p| p.image_base));
- let Some(va) = va else {
- return;
- };
- match self.reload_listing_at(va) {
- Ok(()) => {
- self.status = format!("Listing reloaded at {va:#x} ({})", self.listing.len());
- self.log(self.status.clone());
- }
- Err(e) => {
- self.status = format!("decode reload: {e}");
- self.log_error(self.status.clone());
- }
- }
- }
-
- /// Navigation → Go To Address.
- /// If `va` is outside the current listing window, re-disassembles 64 insns at `va`.
- pub fn goto_address_str(&mut self, s: &str) -> Result<(), String> {
- let va = parse_address(s)?;
- self.listing_focus_va = Some(va);
- self.focus_center_tab(DockTab::Listing);
-
- if let Some(i) = listing_index_at_or_before(&self.listing, va) {
- self.push_selection_undo();
- self.listing_selection = ListingSelection {
- start: Some(i),
- end: Some(i),
- };
- } else {
- // Outside loaded listing (or empty) — re-disassemble at target VA.
- let prog = self
- .program
- .as_ref()
- .ok_or_else(|| "no program loaded".to_string())?;
- let l = reload_for_goto(prog, va, &self.decode_opts).map_err(|e| e.to_string())?;
- if l.is_empty() {
- return Err(format!("no instructions at {va:#x}"));
- }
- self.listing = l;
- self.push_selection_undo();
- self.listing_selection = ListingSelection {
- start: Some(0),
- end: Some(0),
- };
- }
-
- if !self.nav_suspended {
- self.nav_history.push(NavLocation::new(va));
- }
- self.event_bus.publish(GhidrustEvent::CursorMoved {
- source: EventSource::Navigation,
- location: NavLocation::new(va),
- });
- // Cross-highlight Decompiler line matching the new listing cursor.
- if !self.decomp_lines.is_empty() {
- self.decomp_cross_line = decomp_line_for_va(&self.decomp_lines, va);
- }
- // Selection Navigation: keep the "current function" in sync with the
- // cursor so the Symbol Tree can highlight the enclosing function.
- if self.symbol_tree_nav {
- if let Some(prog) = self.program.as_ref() {
- self.focused_function_entry = prog
- .analysis
- .functions
- .iter()
- .filter(|f| f.entry <= va && (f.end == 0 || va < f.end))
- .max_by_key(|f| f.entry)
- .map(|f| f.entry);
- }
- }
-
- self.status = format!("Go to {va:#x}");
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Navigation → Go To entry.
- pub fn goto_entry(&mut self) {
- 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}"));
- return;
- }
- }
- self.status = "No entry point".into();
- self.log(self.status.clone());
- }
-
- /// Search → Memory.
- pub fn run_search_memory(&mut self) -> Result<(), String> {
- let prog = self
- .program
- .as_ref()
- .ok_or_else(|| "no program loaded".to_string())?;
- let pat = parse_hex_pattern(&self.search_memory_input)?;
- self.memory_hits = search_memory(prog, &pat, 500);
- self.text_hits.clear();
- self.show_search_results = true;
- self.status = format!(
- "Memory search: {} hit(s) for '{}'",
- self.memory_hits.len(),
- self.search_memory_input.trim()
- );
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Search → For Scalars.
- pub fn run_search_scalars(&mut self) -> Result<(), String> {
- let min = self
- .parse_scalar_input(&self.search_scalars_min.clone())
- .map_err(|e| format!("min: {e}"))?;
- let max = self
- .parse_scalar_input(&self.search_scalars_max.clone())
- .map_err(|e| format!("max: {e}"))?;
- if min > max {
- return Err("min > max".into());
- }
- self.text_hits = search_scalars(&self.listing, min, max, 1000);
- self.memory_hits.clear();
- self.show_search_results = true;
- self.status = format!(
- "Scalar search [{min}, {max}]: {} hit(s)",
- self.text_hits.len()
- );
- self.log(self.status.clone());
- Ok(())
- }
-
- fn parse_scalar_input(&self, s: &str) -> Result<i64, String> {
- let t = s.trim();
- if t.is_empty() {
- return Err("empty".into());
- }
- let (sign, rest) = if let Some(r) = t.strip_prefix('-') {
- (-1i64, r)
- } else {
- (1i64, t)
- };
- // `0x…` prefix wins → hex. Otherwise prefer decimal to preserve
- // convention (numeric input without a prefix is decimal).
- let (base, digits) =
- if let Some(r) = rest.strip_prefix("0x").or_else(|| rest.strip_prefix("0X")) {
- (16u32, r)
- } else {
- (10u32, rest)
- };
- let mag = u64::from_str_radix(digits, base).map_err(|e| e.to_string())?;
- Ok(sign * mag as i64)
- }
-
- /// Search → Instruction Patterns.
- pub fn run_search_instruction_patterns(&mut self) -> Result<(), String> {
- if self.listing.is_empty() {
- return Err("no listing loaded".into());
- }
- self.text_hits = search_instruction_patterns(
- &self.listing,
- &self.search_insn_mnemonic,
- &self.search_insn_operands,
- 1000,
- );
- self.memory_hits.clear();
- self.show_search_results = true;
- self.status = format!(
- "Instruction pattern hits: {} for `{} {}`",
- self.text_hits.len(),
- self.search_insn_mnemonic.trim(),
- self.search_insn_operands.trim(),
- );
- self.log(self.status.clone());
- Ok(())
- }
-
- /// Search → Program Text.
- pub fn run_search_text(&mut self) -> Result<(), String> {
- let prog = self
- .program
- .as_ref()
- .ok_or_else(|| "no program loaded".to_string())?;
- self.text_hits = search_program_text(
- prog,
- &self.listing,
- &self.search_text_input,
- self.search_text_case_insensitive,
- 500,
- );
- self.memory_hits.clear();
- self.show_search_results = true;
- self.status = format!(
- "Text search: {} hit(s) for '{}'",
- self.text_hits.len(),
- self.search_text_input.trim()
- );
- self.log(self.status.clone());
- Ok(())
- }
-
- fn remember_project(&mut self, dir: &str) {
- let dir = dir.trim().to_string();
- if dir.is_empty() {
- return;
- }
- self.recent_projects.retain(|p| p != &dir);
- self.recent_projects.insert(0, dir);
- self.recent_projects.truncate(12);
- save_recent_projects(&self.recent_projects);
- }
-
- fn rebuild_rtti_filter_cache(&mut self) {
- let q = self.rtti_filter.to_ascii_lowercase();
- if q == self.rtti_filter_cache && !self.rtti_filtered_idx.is_empty() {
- return;
- }
- self.rtti_filter_cache = q.clone();
- if q.is_empty() {
- self.rtti_filtered_idx = (0..self.rtti.classes.len()).collect();
- } else {
- self.rtti_filtered_idx = self
- .rtti
- .classes
- .iter()
- .enumerate()
- .filter(|(_, c)| c.name.to_ascii_lowercase().contains(&q))
- .map(|(i, _)| i)
- .collect();
- }
- }
-
- fn analysis_summary_line(&self) -> String {
- let fns = self
- .program
- .as_ref()
- .map(|p| p.analysis.functions.len())
- .unwrap_or(0);
- let rtti_n = self.rtti.classes.len();
- let str_n = self.strings.len();
- let list_n = self.listing.len();
- format!("{fns} functions · {rtti_n} RTTI · {str_n} strings · {list_n} listing lines")
- }
-
- fn browse_binary_path(&mut self) {
- if let Some(path) = rfd::FileDialog::new()
- .set_title("Open binary (PE / ELF)")
- .add_filter("Binaries", &["exe", "dll", "sys", "pe", "elf", "so", "bin"])
- .add_filter("All files", &["*"])
- .pick_file()
- {
- self.path_input = path.display().to_string();
- self.log(format!("Browsed binary: {}", self.path_input));
- }
- }
-
- fn browse_project_dir(&mut self) {
- if let Some(path) = rfd::FileDialog::new()
- .set_title("Select project folder")
- .pick_folder()
- {
- self.project_dir_input = path.display().to_string();
- self.log(format!("Browsed project dir: {}", self.project_dir_input));
- }
- }
-
- /// Browse for a binary and load it immediately (no project required).
- fn browse_and_load_binary(&mut self) {
- self.browse_binary_path();
- if !self.path_input.trim().is_empty() {
- if let Err(e) = self.load_binary(self.path_input.clone()) {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- }
-
- /// Browse folder then open project at that path.
- fn browse_and_open_project(&mut self) {
- self.browse_project_dir();
- if !self.project_dir_input.trim().is_empty() {
- if let Err(e) = self.open_project() {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- }
-
- /// Browse folder then create project there.
- fn browse_and_create_project(&mut self) {
- self.browse_project_dir();
- if !self.project_dir_input.trim().is_empty() {
- if let Err(e) = self.create_project() {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- }
-
- /// Browse binary then import into the open project.
- fn browse_and_import(&mut self) {
- self.browse_binary_path();
- if !self.path_input.trim().is_empty() {
- if let Err(e) = self.import_into_project() {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- }
-
- /// Request delete with confirmation (does not delete yet).
- pub fn request_delete_file(&mut self, id: &str) {
- let name = self
- .project
- .as_ref()
- .and_then(|p| p.meta.files.iter().find(|f| f.id == id))
- .map(|f| f.display_name.clone())
- .unwrap_or_else(|| id.to_string());
- self.pending_delete = Some((id.to_string(), name));
- }
-
- /// Confirm pending delete: remove from project disk + clear UI if active.
- pub fn confirm_delete_file(&mut self) -> Result<(), String> {
- let (id, name) = self
- .pending_delete
- .take()
- .ok_or_else(|| "no pending delete".to_string())?;
- let was_active = self.active_file_id.as_deref() == Some(id.as_str());
- let entry = {
- let proj = self
- .project
- .as_mut()
- .ok_or_else(|| "no project open".to_string())?;
- proj.remove_file(&id).map_err(|e| e.to_string())?
- };
- self.log(format!("Deleted {} (id={})", entry.display_name, entry.id));
- if self.tree_selected_id.as_deref() == Some(id.as_str()) {
- self.tree_selected_id = None;
- }
- if was_active {
- self.program = None;
- self.listing.clear();
- self.strings.clear();
- self.crypt_constants.clear();
- self.obfuscated_strings.clear();
- self.crypto_capabilities.clear();
- self.rtti = RttiReport::default();
- self.clear_decompiler_cache();
- let next = self.project.as_ref().and_then(|p| p.meta.active_id.clone());
- self.active_file_id = next.clone();
- if let Some(next) = next {
- self.open_project_file(&next)?;
- } else {
- self.status = format!("Deleted {name} — project empty");
- }
- } else {
- self.status = format!("Deleted {name} from project");
- }
- Ok(())
- }
-
- pub fn cancel_delete_file(&mut self) {
- self.pending_delete = None;
- }
-
- /// Project Window–style rows for the Project Tree (testable without a window).
- pub fn project_tree_model(&self) -> Option<ProjectTreeModel> {
- self.project.as_ref().map(|p| {
- let mut m = p.tree_rows();
- // Reflect GUI active selection if set
- if let Some(ref aid) = self.active_file_id {
- for f in &mut m.files {
- f.active = f.id == *aid;
- }
- }
- m
- })
- }
-
- /// Open binary from project tree selection (same path as file chips).
- pub fn open_from_tree(&mut self, id: &str) -> Result<(), String> {
- self.tree_selected_id = Some(id.to_string());
- self.open_project_file(id)
- }
-
- /// Open analysis options dialog for a project-tree file (does not run yet).
- pub fn analyze_from_tree(&mut self, id: &str) -> Result<(), String> {
- if self.analysis_job.is_some() {
- return Err("analysis already in progress".into());
- }
- self.tree_selected_id = Some(id.to_string());
- self.pending_analyze_file_id = Some(id.to_string());
- self.show_analysis_dialog = true;
- self.status = "Choose analyzers and options, then Run Analysis".into();
- Ok(())
- }
-
- /// Start analysis from dialog selections on a background thread.
- /// Progress / console lines are delivered via channel and polled each UI frame.
- pub fn begin_analysis_job(&mut self) -> Result<(), String> {
- if self.analysis_job.is_some() {
- return Err("analysis already in progress".into());
- }
- if let Some(id) = self.pending_analyze_file_id.take() {
- self.open_from_tree(&id)?;
- }
- if self.program.is_none() {
- return Err("no program loaded — open or import a binary first".into());
- }
- let names: Vec<String> = self
- .analyzer_infos
- .iter()
- .zip(self.analyzer_enabled.iter())
- .filter(|(_, on)| **on)
- .map(|(a, _)| a.name.clone())
- .collect();
- if names.is_empty() {
- return Err("select at least one analyzer".into());
- }
- // Bulk mode is applied inside run_analyzers_opts per step when use_gpu.
- let file_label = self
- .program
- .as_ref()
- .map(|p| p.name.clone())
- .unwrap_or_else(|| "program".into());
- let use_gpu = self.use_gpu_experimental;
- self.log(format!(
- "Starting analysis on {file_label}: {} analyzer(s), gpu={}",
- names.len(),
- use_gpu
- ));
- self.status = format!("Analyzing {file_label}…");
-
- let (msg_tx, msg_rx) = mpsc::channel::<AnalysisWorkerMsg>();
- // Hand the program to the worker only after spawn succeeds so a spawn
- // failure cannot drop the only Program copy.
- let (prog_tx, prog_rx) = mpsc::sync_channel::<Program>(1);
- let names_worker = names.clone();
- std::thread::Builder::new()
- .name("ghidrust-analysis".into())
- .spawn(move || {
- let Ok(mut prog) = prog_rx.recv() else {
- return;
- };
- for (index, name) in names_worker.iter().enumerate() {
- let _ = msg_tx.send(AnalysisWorkerMsg::StepStarted { index });
- let gpu = use_gpu && analyzer_supports_gpu(name);
- // catch_unwind: core GPU paths already catch wgpu panics;
- // belt-and-suspenders so the worker always returns the program.
- let step = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
- ghidrust_core::run_analyzers_opts(&mut prog, &[name.as_str()], gpu)
- }));
- match step {
- Ok(Ok(report)) => {
- let _ = msg_tx.send(AnalysisWorkerMsg::StepFinished {
- index,
- outputs: report.results,
- });
- }
- Ok(Err(e)) => {
- let _ = msg_tx.send(AnalysisWorkerMsg::Failed {
- error: e.to_string(),
- program: prog,
- });
- return;
- }
- Err(_) => {
- let _ = msg_tx.send(AnalysisWorkerMsg::Failed {
- error: format!(
- "analyzer '{name}' panicked (GPU/validation); try again with GPU off"
- ),
- program: prog,
- });
- return;
- }
- }
- }
- let _ = msg_tx.send(AnalysisWorkerMsg::Done { program: prog });
- })
- .map_err(|e| format!("failed to spawn analysis worker: {e}"))?;
-
- let prog = self.program.take().expect("program checked non-None above");
- if prog_tx.send(prog).is_err() {
- return Err("analysis worker exited before receiving program".into());
- }
-
- self.analysis_job = Some(AnalysisJob {
- names,
- index: 0,
- results: AnalysisRunReport::default(),
- file_label,
- use_gpu,
- rx: msg_rx,
- });
- Ok(())
- }
-
- /// Poll the analysis worker (non-blocking). Call every frame while `analysis_job` is Some.
- /// Returns `Ok(true)` when the job has finished and been finalized.
- pub fn step_analysis_job(&mut self) -> Result<bool, String> {
- self.poll_analysis_job(false)
- }
-
- /// Block until at least one worker message arrives (tests / headless drain).
- pub fn step_analysis_job_blocking(&mut self) -> Result<bool, String> {
- self.poll_analysis_job(true)
- }
-
- fn recv_analysis_msg(&self, block: bool) -> Result<Option<AnalysisWorkerMsg>, String> {
- let job = self
- .analysis_job
- .as_ref()
- .ok_or_else(|| "no analysis job".to_string())?;
- if block {
- match job.rx.recv() {
- Ok(m) => Ok(Some(m)),
- Err(RecvError) => Err("analysis worker disconnected".into()),
- }
- } else {
- match job.rx.try_recv() {
- Ok(m) => Ok(Some(m)),
- Err(TryRecvError::Empty) => Ok(None),
- Err(TryRecvError::Disconnected) => Err("analysis worker disconnected".into()),
- }
- }
- }
-
- fn poll_analysis_job(&mut self, block: bool) -> Result<bool, String> {
- let Some(first) = self.recv_analysis_msg(block)? else {
- return Ok(false);
- };
- if self.apply_analysis_msg(first)? {
- return Ok(true);
- }
- // Drain any further messages already queued so one frame can catch up.
- while let Some(msg) = self.recv_analysis_msg(false)? {
- if self.apply_analysis_msg(msg)? {
- return Ok(true);
- }
- }
- Ok(false)
- }
-
- /// Apply one worker message. Returns `Ok(true)` when the job is fully finished.
- fn apply_analysis_msg(&mut self, msg: AnalysisWorkerMsg) -> Result<bool, String> {
- match msg {
- AnalysisWorkerMsg::StepStarted { index } => {
- if let Some(job) = self.analysis_job.as_mut() {
- job.index = index;
- let total = job.names.len();
- let label = job.file_label.clone();
- let cur = job.names.get(index).cloned().unwrap_or_else(|| "…".into());
- self.status = format!("Analyzing {label} — {}/{total}: {cur}", index + 1);
- }
- Ok(false)
- }
- AnalysisWorkerMsg::StepFinished { index, outputs } => {
- let mut log_lines = Vec::new();
- let mut rtti_upd = None;
- let mut strings_upd = None;
- for r in &outputs {
- log_lines.push(format!("[{}] {} — {}", r.status, r.name, r.message));
- if r.rtti.is_some() {
- rtti_upd = r.rtti.clone();
- }
- if r.strings.is_some() {
- strings_upd = r.strings.clone();
- }
- }
- for line in log_lines {
- let sev = if line.starts_with("[error]") {
- ConsoleSeverity::Error
- } else if line.starts_with("[warn") {
- ConsoleSeverity::Warn
- } else {
- ConsoleSeverity::Info
- };
- self.log_with(line, sev);
- }
- if let Some(r) = rtti_upd {
- self.rtti = r;
- }
- if let Some(s) = strings_upd {
- self.strings = s;
- }
- for r in &outputs {
- if let Some(c) = &r.crypt_constants {
- self.crypt_constants = c.clone();
- }
- if let Some(o) = &r.obfuscated_strings {
- self.obfuscated_strings = o.clone();
- }
- if let Some(c) = &r.crypto_capabilities {
- self.crypto_capabilities = c.clone();
- }
- }
- if let Some(job) = self.analysis_job.as_mut() {
- job.results.results.extend(outputs);
- job.index = index + 1;
- }
- Ok(false)
- }
- AnalysisWorkerMsg::Done { program } => {
- self.program = Some(program);
- self.finish_analysis_job()?;
- Ok(true)
- }
- AnalysisWorkerMsg::Failed { error, program } => {
- self.program = Some(program);
- self.analysis_job = None;
- set_preferred_bulk_mode(BulkScanMode::ParallelCpu);
- Err(error)
- }
- }
- }
-
- fn finish_analysis_job(&mut self) -> Result<(), String> {
- let job = self
- .analysis_job
- .take()
- .ok_or_else(|| "no analysis job".to_string())?;
- if let Some(prog) = self.program.as_ref() {
- let entry = default_start_va(prog, self.listing_focus_va);
- if let Ok(result) = reload(prog, entry, &self.decode_opts) {
- self.listing = result.insns;
- }
- self.rtti = prog.rtti.clone();
- }
- // Capture strings from this run's results
- for r in &job.results.results {
- if let Some(ref s) = r.strings {
- self.strings = s.clone();
- }
- if let Some(ref c) = r.crypt_constants {
- self.crypt_constants = c.clone();
- }
- if let Some(ref o) = r.obfuscated_strings {
- self.obfuscated_strings = o.clone();
- }
- if let Some(ref c) = r.crypto_capabilities {
- self.crypto_capabilities = c.clone();
- }
- }
- if let Some(prog) = self.program.as_ref() {
- if self.crypt_constants.is_empty() {
- self.crypt_constants = prog.analysis.crypt_constants.clone();
- }
- if self.obfuscated_strings.is_empty() {
- self.obfuscated_strings = prog.analysis.obfuscated_strings.clone();
- }
- if self.crypto_capabilities.is_empty() {
- self.crypto_capabilities = prog.analysis.crypto_capabilities.clone();
- }
- }
- self.rtti_filter.clear();
- self.rtti_filter_cache.clear();
- self.rtti_filtered_idx.clear();
- self.rebuild_rtti_filter_cache();
- self.last_analyzers_run = job.names.clone();
- let n = job.results.results.len();
- self.last_analysis = job.results;
- let summary = self.analysis_summary_line();
- let banner = format!(
- "Analysis complete on {} — {n} analyzer(s) · {summary}{}",
- job.file_label,
- if job.use_gpu {
- " · GPU experimental"
- } else {
- ""
- }
- );
- self.analysis_done_banner = Some(banner.clone());
- self.status = banner.clone();
- self.log(banner);
- if self.project.is_some() && self.active_file_id.is_some() {
- let _ = self.save_results();
- self.log("Results saved to project (results/ + exports/).");
- }
- 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();
- if let Some(va) = self
- .listing_focus_va
- .or_else(|| self.listing.first().map(|i| i.address))
- .or_else(|| self.program.as_ref().and_then(|p| p.entry))
- {
- self.refresh_decompiler_at(va);
- }
- // Restore default bulk mode after experimental run
- set_preferred_bulk_mode(BulkScanMode::ParallelCpu);
- Ok(())
- }
-
- pub fn analysis_progress_fraction(&self) -> Option<f32> {
- self.analysis_job.as_ref().map(|j| {
- if j.names.is_empty() {
- 1.0
- } else {
- j.index as f32 / j.names.len() as f32
- }
- })
- }
-
- pub fn apply_theme(&self, ctx: &egui::Context) {
- let t = m3_tokens(self.theme);
- let mut v = match self.theme {
- ThemeMode::Dark => Visuals::dark(),
- ThemeMode::Light => Visuals::light(),
- };
- let rgb = |c: [u8; 3]| Color32::from_rgb(c[0], c[1], c[2]);
- v.override_text_color = Some(rgb(t.on_surface));
- v.widgets.noninteractive.bg_fill = rgb(t.surface_container);
- v.widgets.inactive.bg_fill = rgb(t.surface_container);
- v.widgets.hovered.bg_fill = rgb(t.primary).gamma_multiply(0.25);
- v.widgets.active.bg_fill = rgb(t.primary).gamma_multiply(0.35);
- v.widgets.open.bg_fill = rgb(t.surface_container);
- v.panel_fill = rgb(t.surface);
- v.window_fill = rgb(t.surface_container);
- v.extreme_bg_color = rgb(t.surface);
- v.faint_bg_color = rgb(t.surface_container);
- v.selection.bg_fill = rgb(t.primary).gamma_multiply(0.4);
- v.hyperlink_color = rgb(t.primary);
- v.warn_fg_color = rgb(t.error);
- ctx.set_visuals(v);
- // Wider side/top grab for resizable panels (bottom console drag).
- ctx.style_mut(|s| {
- s.interaction.resize_grab_radius_side = 12.0;
- });
- }
-
- pub fn load_binary(&mut self, path: impl Into<PathBuf>) -> Result<(), String> {
- let path = path.into();
- self.path_input = path.display().to_string();
- let prog = load_path(&path).map_err(|e| e.to_string())?;
- let entry = default_start_va(&prog, None);
- self.decode_opts.sync_machine_from_program(&prog);
- self.listing_search.arch = self
- .decode_opts
- .resolved_arch()
- .or_else(|| arch_mode_for_program(&prog).map(|(a, _)| a))
- .unwrap_or_else(|| default_arch_mode().0);
- let listing = reload(&prog, entry, &self.decode_opts)
- .map(|r| r.insns)
- .unwrap_or_default();
- self.log(format!(
- "Loaded {} ({}) base={:#x}",
- prog.name, prog.format, prog.image_base
- ));
- let prog_name = prog.name.clone();
- self.status = format!(
- "Loaded {} — {} sections, {} listing insns",
- prog.name,
- prog.sections.len(),
- listing.len()
- );
- self.program = Some(prog);
- self.listing = listing;
- self.rtti = RttiReport::default();
- self.strings.clear();
- self.crypt_constants.clear();
- self.obfuscated_strings.clear();
- self.crypto_capabilities.clear();
- self.last_analysis = AnalysisRunReport::default();
- self.last_analyzers_run.clear();
- self.clear_decompiler_cache();
- self.nav_history.clear();
- self.event_bus
- .publish(GhidrustEvent::ProgramActivated { name: prog_name });
- if let Some(va) = self
- .listing
- .first()
- .map(|i| i.address)
- .or(self.listing_focus_va)
- {
- self.refresh_decompiler_at(va);
- }
- Ok(())
- }
-
- pub fn create_project(&mut self) -> Result<(), String> {
- let dir = self.project_dir_input.trim().to_string();
- if dir.is_empty() {
- return Err("set Project dir path first".into());
- }
- let name = if self.project_name_input.trim().is_empty() {
- "MyProject".into()
- } else {
- self.project_name_input.trim().to_string()
- };
- let p = Project::create(&dir, name).map_err(|e| e.to_string())?;
- self.log(format!(
- "Created project '{}' at {}",
- p.meta.name,
- p.root.display()
- ));
- self.status = format!("Project open: {}", p.root.display());
- self.remember_project(&dir);
- self.show_startup_picker = false;
- self.project = Some(p);
- self.decode_opts = DecodeUiOpts::default();
- self.active_file_id = None;
- self.ensure_project_skill_wired();
- Ok(())
- }
-
- pub fn open_project(&mut self) -> Result<(), String> {
- let dir = self.project_dir_input.trim().to_string();
- if dir.is_empty() {
- return Err("set Project dir path first".into());
- }
- let p = Project::open(&dir).map_err(|e| e.to_string())?;
- self.project_name_input = p.meta.name.clone();
- self.active_file_id = p.meta.active_id.clone();
- if let Some(opts) = load_decode_prefs(&p.root) {
- self.decode_opts = opts;
- }
- self.log(format!(
- "Opened project '{}' ({} files)",
- p.meta.name,
- p.meta.files.len()
- ));
- self.status = format!("Project open: {}", p.root.display());
- self.remember_project(&dir);
- self.show_startup_picker = false;
- // 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() {
- return Err("set binary path first".into());
- }
- let proj = self
- .project
- .as_mut()
- .ok_or_else(|| "no project open — create or open one first".to_string())?;
- let entry = proj.import_file(path).map_err(|e| e.to_string())?;
- self.active_file_id = Some(entry.id.clone());
- self.log(format!("Imported {} (id={})", entry.display_name, entry.id));
- let id = entry.id.clone();
- self.open_project_file(&id)
- }
-
- pub fn open_project_file(&mut self, id: &str) -> Result<(), String> {
- let entry = {
- let proj = self
- .project
- .as_ref()
- .ok_or_else(|| "no project".to_string())?;
- proj.meta
- .files
- .iter()
- .find(|f| f.id == id)
- .ok_or_else(|| format!("unknown file id {id}"))?
- .clone()
- };
- let display = entry.display_name.clone();
- self.status = format!("Loading {display}…");
- self.log(format!("Loading {display} (saved results if any)…"));
-
- let (prog, saved, has_saved, bin_path) = {
- let proj = self
- .project
- .as_ref()
- .ok_or_else(|| "no project".to_string())?;
- let has_saved = proj.has_saved_analysis(&entry.id);
- let bin_path = proj.binary_path(&entry).display().to_string();
- let (prog, saved) = proj
- .load_program_with_results(&entry)
- .map_err(|e| e.to_string())?;
- (prog, saved, has_saved, bin_path)
- };
-
- let mut saved_analyzers = Vec::new();
- if let Some(ref s) = saved {
- saved_analyzers = s.saved_analyzers.clone();
- }
- self.decode_opts.sync_machine_from_program(&prog);
- self.listing_search.arch = self
- .decode_opts
- .resolved_arch()
- .or_else(|| arch_mode_for_program(&prog).map(|(a, _)| a))
- .unwrap_or_else(|| default_arch_mode().0);
- let start_va = default_start_va(&prog, None);
- let listing = reload(&prog, start_va, &self.decode_opts)
- .map(|r| r.insns)
- .unwrap_or_default();
- // Strings: session last_analysis only (full rescan is Analyze opt-in on large games).
- if let Some(s) = self
- .last_analysis
- .results
- .iter()
- .find_map(|r| r.strings.clone().filter(|s| !s.is_empty()))
- {
- self.strings = s;
- } else {
- self.strings.clear();
- self.crypt_constants.clear();
- self.obfuscated_strings.clear();
- self.crypto_capabilities.clear();
- }
- self.rtti = prog.rtti.clone();
- self.rtti_filter.clear();
- self.rtti_filter_cache.clear();
- self.rtti_filtered_idx.clear();
- self.rebuild_rtti_filter_cache();
- self.path_input = bin_path;
- self.active_file_id = Some(entry.id.clone());
- self.tree_selected_id = Some(entry.id.clone());
- if !saved_analyzers.is_empty() {
- self.last_analyzers_run = saved_analyzers;
- }
- let rtti_n = self.rtti.classes.len();
- let fn_n = prog.analysis.functions.len();
- self.status = format!(
- "Opened {display} — {fn_n} functions · {rtti_n} RTTI · {} listing lines{}",
- listing.len(),
- if has_saved {
- " · analysis on disk"
- } else {
- " · not analyzed yet"
- }
- );
- self.log(self.status.clone());
- self.program = Some(prog);
- self.listing = listing;
- self.clear_decompiler_cache();
- if let Some(va) = self
- .listing
- .first()
- .map(|i| i.address)
- .or_else(|| self.program.as_ref().and_then(|p| p.entry))
- {
- self.refresh_decompiler_at(va);
- }
- self.focus_center_tab(DockTab::Overview);
- self.show_symbol_tree = true;
- if let Some(p) = self.project.as_mut() {
- let _ = p.set_active(id);
- }
- Ok(())
- }
-
- pub fn save_results(&mut self) -> Result<(), String> {
- let id = self
- .active_file_id
- .clone()
- .ok_or_else(|| "no active project file — import a binary into a project".to_string())?;
- let prog = self
- .program
- .as_ref()
- .ok_or_else(|| "no program loaded".to_string())?;
- let (analysis_path, listing_path, saved) = {
- let proj = self
- .project
- .as_ref()
- .ok_or_else(|| "no project open".to_string())?;
- let saved = proj
- .save_program_results(&id, prog, &self.listing, &self.last_analyzers_run)
- .map_err(|e| e.to_string())?;
- (
- proj.analysis_path(&id).display().to_string(),
- proj.listing_export_path(&id).display().to_string(),
- saved,
- )
- };
- self.log(format!("Saved analysis → {analysis_path}"));
- self.log(format!("Listing export → {listing_path}"));
- self.status = format!(
- "Saved {} ({} functions, {} insns)",
- id,
- saved.analysis.functions.len(),
- saved.listing.len()
- );
- Ok(())
- }
-
- /// Headless/sync: begin job and drain all worker messages (tests + non-UI callers).
- pub fn run_selected_analysis(&mut self) -> Result<(), String> {
- self.begin_analysis_job()?;
- while self.analysis_job.is_some() {
- self.step_analysis_job_blocking()?;
- }
- Ok(())
- }
-
- fn log(&mut self, msg: impl Into<String>) {
- self.log_with(msg, ConsoleSeverity::Info);
- }
-
- /// Console warning (amber tint).
- fn log_warn(&mut self, msg: impl Into<String>) {
- self.log_with(msg, ConsoleSeverity::Warn);
- }
-
- /// Console error (red tint).
- fn log_error(&mut self, msg: impl Into<String>) {
- self.log_with(msg, ConsoleSeverity::Error);
- }
-
- fn log_with(&mut self, msg: impl Into<String>, sev: ConsoleSeverity) {
- let text = msg.into();
- self.console.push(text);
- self.console_severity.push(sev);
- // Keep both vectors in lockstep and bounded.
- if self.console.len() > 200 {
- let drop = self.console.len() - 200;
- self.console.drain(0..drop);
- self.console_severity.drain(0..drop);
- }
- // Backfill severity vector if it drifts (only happens if callers used
- // `self.console.push` directly; guard against future regressions).
- while self.console_severity.len() < self.console.len() {
- self.console_severity.push(ConsoleSeverity::Info);
- }
- }
-
- #[allow(dead_code)] // kept for non-menubar future stubs; menubar stubs are wired
- fn nyi(&mut self, what: &str) {
- let m = format!("Not yet implemented: {what}");
- self.status = m.clone();
- self.nyi_note = Some(m.clone());
- self.log(m);
- }
-
- /// Render the bottom-dock tabbed panel — `Grok` (embedded TUI) + `Console`.
- fn render_bottom_dock(&mut self, ui: &mut egui::Ui) {
- use agent_pane::BottomTab;
- ui.horizontal(|ui| {
- let grok_selected = self.grok_pane.tab == BottomTab::Grok;
- let console_selected = self.grok_pane.tab == BottomTab::Console;
- if ui.selectable_label(grok_selected, "Grok").clicked() {
- self.grok_pane.tab = BottomTab::Grok;
- }
- if ui.selectable_label(console_selected, "Console").clicked() {
- self.grok_pane.tab = BottomTab::Console;
- }
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- if self.grok_pane.tab == BottomTab::Console && ui.small_button("Clear").clicked() {
- self.console.clear();
- self.console_severity.clear();
- }
- ui.small(egui::RichText::new("drag top edge ↕").weak().small());
- });
- });
- ui.separator();
- match self.grok_pane.tab {
- BottomTab::Grok => self.render_grok_tab(ui),
- BottomTab::Console => {
- // Leaving the TUI — release keyboard so listing hotkeys work again.
- self.grok_pane.keyboard_captured = false;
- self.render_console_tab(ui);
- }
- }
- }
-
- fn render_console_tab(&mut self, ui: &mut egui::Ui) {
- egui::ScrollArea::vertical()
- .auto_shrink([false, false])
- .stick_to_bottom(true)
- .show(ui, |ui| {
- let n = self.console.len();
- for i in 0..n {
- let sev = self
- .console_severity
- .get(i)
- .copied()
- .unwrap_or(ConsoleSeverity::Info);
- let color = match sev {
- ConsoleSeverity::Info => ui.visuals().text_color(),
- ConsoleSeverity::Warn => Color32::from_rgb(0xFB, 0xC0, 0x2D),
- ConsoleSeverity::Error => Color32::from_rgb(0xE5, 0x39, 0x35),
- };
- let prefix = match sev {
- ConsoleSeverity::Info => " ",
- ConsoleSeverity::Warn => "! ",
- ConsoleSeverity::Error => "× ",
- };
- ui.label(
- egui::RichText::new(format!("{prefix}{}", self.console[i]))
- .monospace()
- .color(color),
- );
- }
- });
- }
-
- fn render_grok_tab(&mut self, ui: &mut egui::Ui) {
- let t = m3_tokens(self.theme);
- let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
- let muted = Color32::from_rgb(
- t.on_surface_variant[0],
- t.on_surface_variant[1],
- t.on_surface_variant[2],
- );
-
- let ctx = ui.ctx().clone();
- let mut start_err: Option<String> = None;
- let mut do_install = false;
- let mut do_rescan = false;
- let mut do_probe = false;
- let mut start_size: Option<(u16, u16)> = None;
-
- 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| {
- start_size = Some((cols, rows));
- Ok(())
- },
- &mut || do_install = true,
- &mut || do_rescan = true,
- &mut || do_probe = true,
- );
-
- if do_install {
- let status = agent_pane::spawn_install_grok();
- self.log(status.clone());
- self.grok_pane.install_status = Some(status);
- }
- if do_rescan {
- self.grok_pane.refresh_grok_binary();
- let msg = match &self.grok_pane.grok_bin {
- Some(p) => format!("Found grok at {}", p.display()),
- None => "grok not found on PATH — install first".into(),
- };
- self.log(msg);
- }
- if do_probe {
- if let Some(bin) = self.grok_pane.grok_bin.clone() {
- match ghidrust_agent::probe_grok_version(&bin) {
- Ok(v) => {
- self.log(format!("grok -version → {v}"));
- self.grok_pane.version_probe = Some(v);
- }
- Err(e) => {
- self.grok_pane.version_probe = Some(format!("(error) {e}"));
- self.log_warn(format!("grok -version failed: {e}"));
- }
- }
- }
- }
- if let Some((cols, rows)) = start_size {
- if let Err(e) = self.start_grok_pty(cols, rows, ctx) {
- start_err = Some(e);
- }
- }
- if let Some(e) = start_err {
- self.grok_pane.last_error = Some(e.clone());
- self.log_error(format!("Grok TUI failed: {e}"));
- }
- }
-
- /// Build the current program-facts snapshot for the Grok pane.
- ///
- /// This is what makes the agent actually *know* about the open project
- /// and the currently-loaded file without needing an MCP round-trip first.
- /// Every field is honest-empty when the underlying analysis hasn't run —
- /// matches Ghidrust's "no fabrication on empty evidence" rule.
- fn grok_program_facts(&self) -> ghidrust_agent::ProgramFacts {
- const TOP_FN_SAMPLE: usize = 24;
- const IMPORT_SAMPLE: usize = 24;
-
- let mut f = ghidrust_agent::ProgramFacts::default();
- if let Some(proj) = &self.project {
- f.project_name = Some(proj.meta.name.clone());
- f.project_root = Some(proj.root.display().to_string());
- for file in &proj.meta.files {
- let has_saved = proj.results_dir().join(&file.id).exists()
- || proj.results_dir().join(format!("{}.bin", file.id)).exists();
- f.project_files.push(ghidrust_agent::ProjectFileFact {
- id: file.id.clone(),
- display_name: file.display_name.clone(),
- has_saved_analysis: has_saved,
- });
- }
- }
- f.active_file_id = self.active_file_id.clone();
- if let Some(prog) = &self.program {
- f.program = Some(prog.name.clone());
- f.format = Some(prog.format.clone());
- f.arch = Some("x86_64".into());
- f.image_base = Some(format!("{:#x}", prog.image_base));
- f.entry_va = prog.entry.map(|v| format!("{v:#x}"));
- f.functions = Some(prog.analysis.functions.len());
- f.strings = Some(self.strings.len());
- for s in &prog.sections {
- f.sections.push(ghidrust_agent::SectionFact {
- name: s.name.clone(),
- va: format!("{:#x}", s.va),
- size: s.virtual_size,
- });
- }
- for fi in prog.analysis.functions.iter().take(TOP_FN_SAMPLE) {
- f.top_functions.push(ghidrust_agent::FunctionFact {
- va: format!("{:#x}", fi.entry),
- name: fi.name.clone(),
- });
- }
- for imp in prog.imports.iter().take(IMPORT_SAMPLE) {
- if let Some(name) = &imp.name {
- f.imports_sample.push(ghidrust_agent::ImportFact {
- dll: imp.dll.clone(),
- name: name.clone(),
- });
- }
- }
- }
- f.analyzers_run = self.last_analyzers_run.clone();
- if let Some(va) = self.listing_focus_va {
- let name = self
- .program
- .as_ref()
- .and_then(|p| p.display_function_name_at(va));
- f.current_selection = Some(ghidrust_agent::SelectionFact {
- va: format!("{va:#x}"),
- name,
- });
- }
- f
- }
-
- /// Write MCP/skill/context and spawn the real Grok TUI in the PTY pane.
- fn start_grok_pty(&mut self, cols: u16, rows: u16, ctx: egui::Context) -> Result<(), String> {
- self.grok_pane.last_error = None;
- let bin = self.grok_pane.grok_bin.clone().ok_or_else(|| {
- "grok binary not installed — click 'Install Grok Build…' first".to_string()
- })?;
- let project_root: std::path::PathBuf = match &self.project {
- Some(p) => p.root.clone(),
- None => std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")),
- };
- let ghidrust_bin = ghidrust_agent::resolve_ghidrust_cli_bin().ok_or_else(|| {
- "ghidrust CLI not found next to the GUI or on PATH — build `ghidrust` \
- (cargo build -p ghidrust-cli -release) so MCP can start"
- .to_string()
- })?;
- if !ghidrust_bin.is_file() {
- return Err(format!(
- "ghidrust CLI missing at {} — MCP cannot start",
- ghidrust_bin.display()
- ));
- }
- let (_skill_body, skill_source) = load_skill_body();
- let facts = self.grok_program_facts();
- // Drop any prior session before spawning a new one.
- self.grok_pane.session = None;
- let session = agent_pane::start_pty_session(
- &bin,
- &project_root,
- &ghidrust_bin,
- skill_source.as_deref(),
- &facts,
- ctx,
- cols,
- rows,
- )?;
- self.log(format!(
- "Grok TUI started · project={} · grok={} · mcp={}",
- project_root.display(),
- bin.display(),
- ghidrust_bin.display()
- ));
- self.grok_pane.session = Some(session);
- self.grok_pane.status = None;
- self.grok_pane.request_term_focus = true;
- self.grok_pane.keyboard_captured = true;
- Ok(())
- }
-
- /// 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).
- ///
- /// top-level menus (from `docking.tool.ToolConstants`):
- /// File, Edit, Analysis, Navigation, Search, Select, Tools, Graph, Window, Help.
- pub fn shell_menus() -> &'static [&'static str] {
- &[
- "File",
- "Edit",
- "Analysis",
- "Navigation",
- "Search",
- "Select",
- "Tools",
- "Graph",
- "Window",
- "Debugger",
- "Help",
- ]
- }
-
- /// Every provider ( + off-layout) enumerated for visibility tests.
- ///
- /// Ghidrust panes use these exact labels for the Window menu and the structural test.
- /// See `panes::PaneKind::ALL` for the source of truth; a stable Vec is materialized
- /// on demand to keep the API `&'static [&'static str]`-like for existing tests.
- pub fn shell_panes() -> Vec<&'static str> {
- // Legacy names kept for backwards compat with previous test assertions.
- let mut names: Vec<&'static str> = vec![
- "Project Tree",
- "Program Tree", // legacy short name .
- "Symbol Tree",
- "Overview",
- "Listing",
- "Decompiler", // legacy short name .
- "Data Type Manager",
- "Console",
- ];
- for k in PaneKind::ALL {
- let t = k.title();
- if !names.contains(&t) {
- names.push(t);
- }
- }
- // Single tabbed Debugger host .
- if !names.contains(&"Debugger") {
- names.push("Debugger");
- }
- names
- }
-
- fn ui_startup_picker(&mut self, ctx: &egui::Context) {
- let t = m3_tokens(self.theme);
- let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
- let muted = Color32::from_rgb(
- t.on_surface_variant[0],
- t.on_surface_variant[1],
- t.on_surface_variant[2],
- );
- let surface = Color32::from_rgb(
- t.surface_container[0],
- t.surface_container[1],
- t.surface_container[2],
- );
-
- // Fixed card size — never wider than the window, never stretch off-screen.
- let card_w = 440.0_f32.min(ctx.screen_rect().width() - 48.0).max(280.0);
-
- egui::CentralPanel::default().show(ctx, |ui| {
- ui.vertical_centered(|ui| {
- ui.add_space(32.0);
- ui.heading(egui::RichText::new("Ghidrust").size(26.0).color(primary));
- if let Some(tex) = self.logo_texture.as_ref() {
- ui.add_space(10.0);
- let logo_h = 112.0_f32;
- let size = tex.size_vec2();
- let logo_w = (logo_h * size.x / size.y).clamp(64.0, 160.0);
- ui.add(egui::Image::new(tex).fit_to_exact_size(egui::vec2(logo_w, logo_h)));
- ui.add_space(8.0);
- } else {
- ui.add_space(8.0);
- }
- ui.label(
- egui::RichText::new("Open a project to reverse engineer")
- .color(muted)
- .size(14.0),
- );
- ui.add_space(20.0);
-
- egui::Frame::group(ui.style())
- .fill(surface)
- .inner_margin(egui::Margin::same(16))
- .corner_radius(egui::CornerRadius::same(8))
- .show(ui, |ui| {
- ui.set_width(card_w);
- ui.set_max_width(card_w);
-
- // ── Recent projects (IDE-style list) ──
- ui.label(egui::RichText::new("Recent projects").strong().size(13.0));
- ui.add_space(6.0);
-
- let recents = self.recent_projects.clone();
- let list_h = if recents.is_empty() { 48.0 } else { 200.0 };
-
- egui::Frame::NONE
- .stroke(ui.visuals().widgets.noninteractive.bg_stroke)
- .inner_margin(egui::Margin::same(4))
- .corner_radius(egui::CornerRadius::same(4))
- .show(ui, |ui| {
- ui.set_width(card_w - 8.0);
- egui::ScrollArea::vertical()
- .id_salt("startup_recent")
- .max_height(list_h)
- .auto_shrink([false, false])
- .show(ui, |ui| {
- ui.set_min_width(card_w - 24.0);
- if recents.is_empty() {
- ui.add_space(8.0);
- ui.weak(
- "No recent projects — open or create one below.",
- );
- ui.add_space(8.0);
- } else {
- let mut open_path: Option<String> = None;
- for path in &recents {
- let name = Path::new(path)
- .file_name()
- .map(|s| s.to_string_lossy().into_owned())
- .unwrap_or_else(|| path.clone());
- // IDE-style row: project name + path, full-width click
- let row_w = (card_w - 24.0).max(200.0);
- let row_h = 44.0;
- let (rect, resp) = ui.allocate_exact_size(
- egui::vec2(row_w, row_h),
- egui::Sense::click(),
- );
- if resp.hovered() || resp.has_focus() {
- ui.painter().rect_filled(
- rect,
- egui::CornerRadius::same(4),
- primary.gamma_multiply(0.15),
- );
- }
- let mut child = ui.new_child(
- egui::UiBuilder::new()
- .max_rect(
- rect.shrink2(egui::vec2(10.0, 6.0)),
- )
- .layout(egui::Layout::top_down(
- egui::Align::LEFT,
- )),
- );
- child.label(
- egui::RichText::new(&name)
- .strong()
- .color(primary)
- .size(14.0),
- );
- child.label(
- egui::RichText::new(path).small().color(muted),
- );
- if resp.clicked() {
- open_path = Some(path.clone());
- }
- resp.on_hover_text(format!("Open project: {path}"));
- }
- if let Some(path) = open_path {
- self.project_dir_input = path;
- if let Err(e) = self.open_project() {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- self.show_startup_picker = true;
- }
- }
- }
- });
- });
-
- ui.add_space(14.0);
- ui.separator();
- ui.add_space(10.0);
-
- // Buttons fit card width only (no off-screen stretch)
- let btn_w = card_w - 8.0;
- if ui
- .add_sized([btn_w, 32.0], egui::Button::new("Open existing project…"))
- .clicked()
- {
- self.browse_and_open_project();
- if self.project.is_none() {
- self.show_startup_picker = true;
- }
- }
- ui.add_space(8.0);
- ui.horizontal(|ui| {
- ui.label("Name:");
- ui.add(
- egui::TextEdit::singleline(&mut self.project_name_input)
- .desired_width((btn_w - 56.0).max(120.0))
- .hint_text("MyProject"),
- );
- });
- ui.add_space(4.0);
- if ui
- .add_sized([btn_w, 32.0], egui::Button::new("Create new project…"))
- .clicked()
- {
- self.browse_and_create_project();
- if self.project.is_none() {
- self.show_startup_picker = true;
- }
- }
- ui.add_space(12.0);
- if ui.link("Continue without a project").clicked() {
- self.show_startup_picker = false;
- self.status =
- "No project — Browse/Load a binary, or File → Open Project".into();
- }
- ui.add_space(4.0);
- ui.small(
- egui::RichText::new(
- "Click a recent project name to open it. Analysis uses analysis.bin for fast load.",
- )
- .color(muted),
- );
- });
- });
- });
- }
-
- fn ui_overview(&mut self, ui: &mut egui::Ui) {
- let t = m3_tokens(self.theme);
- let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
- let muted = Color32::from_rgb(
- t.on_surface_variant[0],
- t.on_surface_variant[1],
- t.on_surface_variant[2],
- );
- let ok = Color32::from_rgb(0x4C, 0xAF, 0x50);
-
- ui.heading("Overview");
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program open.");
- ui.label("Project Tree: double-click a file (or Open) to load it into this view.");
- ui.label("If the file is Analyzed, RTTI / functions load from results/ automatically.");
- return;
- };
-
- ui.horizontal(|ui| {
- ui.heading(&prog.name);
- if !self.rtti.classes.is_empty() || !prog.analysis.functions.is_empty() {
- status_badge(ui, true, ok, muted);
- } else {
- status_badge(ui, false, ok, muted);
- }
- });
- ui.label(
- egui::RichText::new(format!(
- "{} · image base {:#x}{}",
- prog.format,
- prog.image_base,
- prog.entry
- .map(|e| format!(" · entry {e:#x}"))
- .unwrap_or_default()
- ))
- .color(muted),
- );
-
- ui.add_space(8.0);
- ui.horizontal(|ui| {
- let card = |ui: &mut egui::Ui, title: &str, value: String| {
- ui.group(|ui| {
- ui.set_min_width(120.0);
- ui.label(egui::RichText::new(title).small().color(muted));
- ui.label(
- egui::RichText::new(value)
- .strong()
- .color(primary)
- .size(18.0),
- );
- });
- };
- card(
- ui,
- "Functions",
- format!("{}", prog.analysis.functions.len()),
- );
- card(ui, "RTTI classes", format!("{}", self.rtti.classes.len()));
- card(ui, "Strings", format!("{}", self.strings.len()));
- card(ui, "Listing lines", format!("{}", self.listing.len()));
- card(ui, "Sections", format!("{}", prog.sections.len()));
- });
-
- ui.add_space(10.0);
- if !self.last_analyzers_run.is_empty() {
- ui.label(egui::RichText::new("Analyzers last run / saved").strong());
- ui.horizontal_wrapped(|ui| {
- for a in &self.last_analyzers_run {
- ui.small(format!("[{a}]"));
- }
- });
- } else {
- ui.weak("No analyzer list saved for this session — run Analyze to record one.");
- }
-
- if !self.rtti.notes.is_empty() {
- ui.add_space(6.0);
- ui.label(egui::RichText::new("RTTI notes").strong());
- for n in &self.rtti.notes {
- ui.small(n);
- }
- }
-
- ui.add_space(12.0);
- ui.separator();
- ui.label(egui::RichText::new("What to do next").strong());
- ui.label("• Symbol Tree (right): expand Classes / RTTI, type a filter, scroll the list.");
- ui.label("• Listing tab: entry disassembly.");
- ui.label("• Analyze: re-run analyzers (shows options + progress).");
- if self.rtti.classes.len() > 1000 {
- ui.label(
- egui::RichText::new(format!(
- "• Large RTTI set ({} classes) — always filter; the list is virtualized so it stays smooth.",
- self.rtti.classes.len()
- ))
- .color(primary),
- );
- }
-
- // Sample of first few RTTI hits for confidence without opening the full drawer
- if !self.rtti.classes.is_empty() {
- ui.add_space(10.0);
- ui.label(egui::RichText::new("RTTI sample (first 12)").strong());
- egui::ScrollArea::vertical()
- .max_height(160.0)
- .show(ui, |ui| {
- for c in self.rtti.classes.iter().take(12) {
- let va = c
- .type_info_va
- .map(|v| format!("{v:#x}"))
- .unwrap_or_else(|| "—".into());
- ui.monospace(format!("{va} {}", c.name));
- }
- });
- if ui.button("Focus Symbol Tree → RTTI").clicked() {
- self.show_symbol_tree = true;
- }
- }
- }
-
- /// render every currently open floating provider pane.
- ///
- /// Panes render either real Stage-0 content (Bookmarks, Memory Map, Functions,
- /// Symbol Table, Defined Strings, Relocations) or a clearly labelled "backend
- /// pending" empty state that names the analyzer/model responsible for filling
- /// them. See `panes::empty_state` for the shared template.
- fn draw_provider_panes(&mut self, ctx: &egui::Context) {
- 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 primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
-
- // Snapshot the open-list so we can mutate self inside the closure.
- let open_list: Vec<PaneKind> = self
- .pane_open
- .iter()
- .filter_map(|(k, v)| if *v { Some(*k) } else { None })
- .collect();
-
- for kind in open_list {
- let mut open = true;
- let title = kind.title();
- let id = egui::Id::new(kind.egui_id());
- let win = egui::Window::new(title)
- .id(id)
- .open(&mut open)
- .resizable(true)
- .default_size(egui::vec2(520.0, 360.0));
-
- match kind {
- PaneKind::Bookmarks => {
- win.show(ctx, |ui| self.ui_bookmarks_pane(ui, muted, primary));
- }
- PaneKind::MemoryMap => {
- win.show(ctx, |ui| self.ui_memory_map_pane(ui, muted));
- }
- PaneKind::FunctionsWindow => {
- win.show(ctx, |ui| self.ui_functions_window(ui, muted, primary));
- }
- PaneKind::SymbolTable => {
- win.show(ctx, |ui| self.ui_symbol_table(ui, muted));
- }
- PaneKind::DefinedStrings => {
- win.show(ctx, |ui| self.ui_defined_strings(ui, muted));
- }
- PaneKind::CryptoConstants => {
- win.show(ctx, |ui| self.ui_crypto_constants_pane(ui, muted));
- }
- PaneKind::RecoveredStrings => {
- win.show(ctx, |ui| self.ui_recovered_strings_pane(ui, muted));
- }
- PaneKind::CryptoCapabilities => {
- win.show(ctx, |ui| self.ui_crypto_capabilities_pane(ui, muted));
- }
- PaneKind::Decrypt => {
- let mut constants: Vec<_> =
- if let Some(focus_va) = self.crypto_constants_focus_va {
- self.crypt_constants
- .iter()
- .filter(|hit| hit.va.abs_diff(focus_va) <= 0x1000)
- .cloned()
- .collect()
- } else {
- self.crypt_constants.clone()
- };
- if let Some(focus_va) = self.crypto_constants_focus_va {
- constants.sort_by_key(|hit| hit.va.abs_diff(focus_va));
- }
- let strings = self.obfuscated_strings.clone();
- let capabilities = self.crypto_capabilities.clone();
- win.show(ctx, |ui| {
- if let Some(act) =
- decrypt_ui::ui_decrypt_window(
- ui,
- muted,
- &mut self.decrypt_pane,
- &constants,
- &strings,
- &capabilities,
- )
- {
- match act {
- decrypt_ui::DecryptPaneAction::ApplyComment { va, text } => {
- if let Err(e) =
- self.set_comment_at(va, CommentKind::Eol, text)
- {
- self.status = format!("comment failed: {e}");
- } else {
- self.status =
- format!("applied decrypt comment @ {va:#x}");
- }
- }
- decrypt_ui::DecryptPaneAction::ApplyBookmark { va, text } => {
- self.add_bookmark(va, BookmarkKind::Analysis, "decrypt", format!("decrypted: {text}"));
- }
- decrypt_ui::DecryptPaneAction::SendToListing { va } => {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- self.status = format!("Decrypt input focused in Listing at {va:#x}; output was not written as code.");
- }
- decrypt_ui::DecryptPaneAction::LoadVa { va, len } => {
- self.open_decrypt_at_len(va, len, None);
- }
- decrypt_ui::DecryptPaneAction::Goto { va } => {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- decrypt_ui::DecryptPaneAction::DecryptNearby { va, hint } => {
- self.open_decrypt_nearby(va, Some(hint));
- }
- decrypt_ui::DecryptPaneAction::BakeRemnant { va } => {
- self.open_decrypt_at(va, None);
- }
- decrypt_ui::DecryptPaneAction::FocusFunction { va } => {
- self.focus_function(va);
- }
- }
- }
- });
- }
- PaneKind::RelocationTable => {
- win.show(ctx, |ui| self.ui_relocation_table(ui, muted));
- }
- PaneKind::DisassembledView => {
- win.show(ctx, |ui| self.ui_disassembled_view_pane(ui, muted));
- }
- PaneKind::CommentWindow => {
- win.show(ctx, |ui| self.ui_comment_window(ui, muted));
- }
- PaneKind::DefinedData => {
- win.show(ctx, |ui| self.ui_defined_data(ui, muted));
- }
- PaneKind::Bytes => {
- win.show(ctx, |ui| self.ui_bytes_pane(ui, muted, primary));
- }
- PaneKind::SymbolReferences => {
- win.show(ctx, |ui| self.ui_symbol_references(ui, muted));
- }
- PaneKind::EquatesTable => {
- win.show(ctx, |ui| self.ui_equates_table(ui, muted));
- }
- PaneKind::FunctionTags => {
- win.show(ctx, |ui| self.ui_function_tags(ui, muted));
- }
- PaneKind::ExternalPrograms => {
- win.show(ctx, |ui| self.ui_external_programs(ui, muted));
- }
- PaneKind::DataTypePreview => {
- win.show(ctx, |ui| self.ui_data_type_preview(ui, muted));
- }
- PaneKind::ChecksumGenerator => {
- win.show(ctx, |ui| self.ui_checksum_generator(ui, muted));
- }
- // Graphs & maps.
- PaneKind::FunctionGraph => {
- win.default_size(egui::vec2(760.0, 520.0))
- .show(ctx, |ui| self.ui_function_graph_pane(ui, muted, primary));
- }
- PaneKind::FunctionCallGraph => {
- win.default_size(egui::vec2(760.0, 480.0)).show(ctx, |ui| {
- self.ui_function_call_graph_pane(ui, muted, primary)
- });
- }
- PaneKind::FunctionCallTrees => {
- win.default_size(egui::vec2(760.0, 460.0)).show(ctx, |ui| {
- self.ui_function_call_trees_pane(ui, muted, primary)
- });
- }
- PaneKind::Entropy => {
- win.default_size(egui::vec2(680.0, 220.0))
- .show(ctx, |ui| self.ui_entropy_pane(ui, muted, primary));
- }
- PaneKind::Overview => {
- win.default_size(egui::vec2(680.0, 340.0))
- .show(ctx, |ui| self.ui_overview(ui));
- }
- PaneKind::RegisterManager => {
- win.default_size(egui::vec2(560.0, 520.0))
- .show(ctx, |ui| self.ui_register_manager_pane(ui, muted, primary));
- }
- // Scripts & interpreters.
- PaneKind::ScriptManager => {
- win.default_size(egui::vec2(760.0, 480.0))
- .show(ctx, |ui| self.ui_script_manager_pane(ui, muted, primary));
- }
- PaneKind::TextEditor => {
- win.default_size(egui::vec2(720.0, 520.0))
- .show(ctx, |ui| self.ui_text_editor_pane(ui, muted, primary));
- }
- PaneKind::Python => {
- 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);
- });
- }
- }
- // Reflect close-button clicks back into our state.
- if !open {
- self.pane_open.insert(kind, false);
- }
- }
-
- // Debugger tool provider windows.
- self.draw_debugger_panes(ctx, muted);
- }
-
- // ── Graphs & maps ────────────────────────────────────
-
- /// `` — CFG vertex/edge layout for the current function.
- fn ui_function_graph_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- ui.heading("Function Graph");
- ui.small(
- egui::RichText::new(
- "FunctionGraphPlugin analog · Stage-0 CFG from ghidrust-decomp::decompile_at",
- )
- .color(muted),
- );
- ui.separator();
-
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- let Some(entry) = self.focused_function_entry.or_else(|| {
- self.listing_focus_va.and_then(|va| {
- prog.analysis
- .functions
- .iter()
- .find(|f| va >= f.entry && va < f.end)
- .map(|f| f.entry)
- })
- }) else {
- ui.weak("Cursor is not inside a recovered function.");
- ui.small(
- egui::RichText::new(
- "Click a function in Symbol Tree, Functions, or Listing to populate the graph.",
- )
- .color(muted),
- );
- return;
- };
-
- ui.horizontal(|ui| {
- ui.label("Layout:");
- let cur = self.graph_state.fn_graph_layout;
- egui::ComboBox::from_id_salt("fg_layout")
- .selected_text(cur.label())
- .show_ui(ui, |ui| {
- for l in FunctionGraphLayout::ALL {
- ui.selectable_value(&mut self.graph_state.fn_graph_layout, *l, l.label());
- }
- });
- ui.separator();
- ui.label("Zoom:");
- ui.add(
- egui::Slider::new(&mut self.graph_state.fn_graph_zoom, 0.5..=2.0)
- .clamping(egui::SliderClamping::Always)
- .fixed_decimals(1),
- );
- if ui
- .button("Fit")
- .on_hover_text("Reset zoom to 1.0")
- .clicked()
- {
- self.graph_state.fn_graph_zoom = 1.0;
- }
- ui.separator();
- ui.small(egui::RichText::new(format!("Entry {entry:#x}")).color(muted));
- });
- ui.separator();
-
- let name = prog.display_function_name_at(entry).unwrap_or_default();
- if !name.is_empty() {
- ui.small(egui::RichText::new(format!("Function {name}")).color(muted));
- }
-
- let algo = self.graph_state.fn_graph_layout;
- let zoom = self.graph_state.fn_graph_zoom.max(0.1);
- let focused_va = self.listing_focus_va;
- let (rect, _resp) = ui.allocate_exact_size(
- egui::vec2(ui.available_width(), 400.0 * zoom),
- egui::Sense::hover(),
- );
- let (blocks, edges) = layout_function_graph(prog, entry, STAGE0_MAX_INSNS, algo, rect);
- if blocks.is_empty() {
- ui.painter().rect_stroke(
- rect,
- 4.0,
- egui::Stroke::new(1.0, muted),
- egui::StrokeKind::Middle,
- );
- ui.painter().text(
- rect.center(),
- egui::Align2::CENTER_CENTER,
- "No Stage-0 CFG recovered for this VA.",
- egui::FontId::proportional(13.0),
- muted,
- );
- return;
- }
- let clicked = render_function_graph(ui, &blocks, &edges, focused_va, primary, muted);
- if let Some(va) = clicked {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- }
-
- /// `` — level-based directed graph.
- fn ui_function_call_graph_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- ui.heading("Function Call Graph");
- ui.small(
- egui::RichText::new(
- "FunctionCallGraphPlugin analog · levels expanded from analyzer references",
- )
- .color(muted),
- );
- ui.separator();
-
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- let Some(entry) = self
- .focused_function_entry
- .or_else(|| {
- self.listing_focus_va.and_then(|va| {
- prog.analysis
- .functions
- .iter()
- .find(|f| va >= f.entry && va < f.end)
- .map(|f| f.entry)
- })
- })
- .or(prog.entry)
- else {
- ui.weak("No entry point — click a function in Symbol Tree to root the call graph.");
- return;
- };
-
- ui.horizontal(|ui| {
- ui.label("Callers levels:");
- let mut lvl_in = self.graph_state.call_graph_levels_in;
- ui.add(egui::Slider::new(&mut lvl_in, 0..=3));
- self.graph_state.call_graph_levels_in = lvl_in;
- ui.separator();
- ui.label("Callees levels:");
- let mut lvl_out = self.graph_state.call_graph_levels_out;
- ui.add(egui::Slider::new(&mut lvl_out, 0..=3));
- self.graph_state.call_graph_levels_out = lvl_out;
- if ui.button("Reset").clicked() {
- self.graph_state.call_graph_levels_in = 1;
- self.graph_state.call_graph_levels_out = 1;
- }
- });
- ui.separator();
-
- let (rect, _resp) = ui.allocate_exact_size(
- egui::vec2(ui.available_width(), 380.0),
- egui::Sense::hover(),
- );
- let (verts, edges) = layout_call_graph(
- prog,
- entry,
- self.graph_state.call_graph_levels_in,
- self.graph_state.call_graph_levels_out,
- rect,
- );
- ui.painter().rect_stroke(
- rect,
- 4.0,
- egui::Stroke::new(1.0, muted),
- egui::StrokeKind::Middle,
- );
- if verts.is_empty() {
- ui.painter().text(
- rect.center(),
- egui::Align2::CENTER_CENTER,
- "No call references recovered — run analyzers first.",
- egui::FontId::proportional(13.0),
- muted,
- );
- return;
- }
- let clicked = render_call_graph(ui, &verts, &edges, entry, primary, muted);
- if let Some(va) = clicked {
- self.focus_function(va);
- }
- }
-
- /// `` — incoming callers / outgoing callees GTree pair.
- fn ui_function_call_trees_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- ui.heading("Function Call Trees");
- ui.small(
- egui::RichText::new(
- "CallTreePlugin analog · Incoming / Outgoing GTrees over analyzer refs",
- )
- .color(muted),
- );
- ui.separator();
-
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- let Some(entry) = self.focused_function_entry.or_else(|| {
- self.listing_focus_va.and_then(|va| {
- prog.analysis
- .functions
- .iter()
- .find(|f| va >= f.entry && va < f.end)
- .map(|f| f.entry)
- })
- }) else {
- ui.weak("Cursor is not inside a recovered function.");
- return;
- };
-
- // Rebuild top level if root changed.
- let root_name = prog.display_function_name_at(entry).unwrap_or_default();
- ui.horizontal(|ui| {
- ui.small(egui::RichText::new(format!("Source {root_name} @ {entry:#x}")).color(muted));
- if ui.button("Refresh").clicked() {
- self.call_tree_incoming.clear();
- self.call_tree_outgoing.clear();
- }
- ui.separator();
- ui.checkbox(&mut self.graph_state.call_tree_hide_thunks, "Hide thunks");
- ui.checkbox(&mut self.graph_state.call_tree_refs_only, "References only");
- });
- ui.separator();
-
- if self.call_tree_incoming.is_empty() && self.call_tree_outgoing.is_empty() {
- self.call_tree_incoming = build_incoming_tree(prog, entry);
- self.call_tree_outgoing = build_outgoing_tree(prog, entry);
- if self.graph_state.call_tree_hide_thunks {
- self.call_tree_incoming.retain(|n| !n.is_thunk);
- self.call_tree_outgoing.retain(|n| !n.is_thunk);
- }
- }
-
- let refs_only = self.graph_state.call_tree_refs_only;
- let hide_thunks = self.graph_state.call_tree_hide_thunks;
- let mut goto: Option<u64> = None;
- egui::ScrollArea::vertical()
- .id_salt("calltrees_scroll")
- .max_height(360.0)
- .show(ui, |ui| {
- ui.columns(2, |cols| {
- cols[0].label(egui::RichText::new("Incoming (callers / refs to)").strong());
- let mut inc = std::mem::take(&mut self.call_tree_incoming);
- for (i, node) in inc.iter_mut().enumerate() {
- render_call_tree_node(
- node,
- i,
- "incoming",
- prog,
- hide_thunks,
- &mut cols[0],
- muted,
- primary,
- &mut goto,
- );
- }
- self.call_tree_incoming = inc;
- if refs_only {
- cols[0].separator();
- cols[0].label(
- egui::RichText::new("Data refs to source")
- .strong()
- .color(muted),
- );
- for xr in data_xrefs_to(prog, entry) {
- let text = egui::RichText::new(format!(
- "{} {} ← {:#x}",
- xr.kind, xr.preview, xr.from
- ))
- .monospace();
- if cols[0].link(text).clicked() {
- goto = Some(xr.from);
- }
- }
- }
-
- cols[1].label(egui::RichText::new("Outgoing (callees / refs from)").strong());
- let mut out = std::mem::take(&mut self.call_tree_outgoing);
- for (i, node) in out.iter_mut().enumerate() {
- render_call_tree_node(
- node,
- i,
- "outgoing",
- prog,
- hide_thunks,
- &mut cols[1],
- muted,
- primary,
- &mut goto,
- );
- }
- self.call_tree_outgoing = out;
- });
- });
- if let Some(va) = goto {
- self.focus_function(va);
- }
- }
-
- /// `` header — Shannon-entropy strip across mapped blocks.
- fn ui_entropy_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- ui.heading("Entropy");
- ui.small(
- egui::RichText::new("EntropyPlugin analog · Shannon bits/byte over 256-byte windows")
- .color(muted),
- );
- ui.separator();
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- let samples = entropy::entropy_samples(prog, 256);
- ui.small(format!(
- "{} windows sampled (256 bytes each)",
- samples.len()
- ));
- let clicked_e =
- entropy::render_entropy_strip(ui, &samples, muted, self.listing_focus_va, primary);
- ui.add_space(6.0);
- ui.label(egui::RichText::new("Overview").strong().color(muted));
- let clicked_o = entropy::render_overview_strip(
- ui,
- prog,
- &samples,
- muted,
- self.listing_focus_va,
- primary,
- );
- ui.small(
- egui::RichText::new("Click a strip to Go To that address. Green = exec, amber = writable, grey = readonly, cold-blue = low entropy, warm-red = high.").color(muted),
- );
- if let Some(va) = clicked_e.or(clicked_o) {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- }
-
- /// `` — register lattice + user-set value ranges.
- fn ui_register_manager_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- let fmt = self.program.as_ref().map(|p| p.format.clone());
- register_manager::render(
- &mut self.register_manager,
- fmt.as_deref(),
- ui,
- muted,
- primary,
- );
- }
-
- // ── Scripts & interpreters ───────────────────────────
-
- fn ui_script_manager_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- if let Some(run) = render_script_manager(&mut self.script_manager, ui, muted, primary) {
- let msg = format!(
- "Script Manager · run requested for `{run}` — full script host not yet wired"
- );
- self.status = msg.clone();
- self.log(msg);
- }
- }
-
- fn ui_text_editor_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- let req = render_text_editor(&mut self.text_editor, ui, muted, primary);
- match req {
- TextEditorRequest::None => {}
- TextEditorRequest::NewUntitled => self.text_editor.open_untitled(),
- TextEditorRequest::OpenFile => {
- if let Some(path) = rfd::FileDialog::new()
- .add_filter("Scripts", &["py", "rs", "txt", "md", "json", "toml"])
- .add_filter("All", &["*"])
- .pick_file()
- {
- if let Err(e) = self.text_editor.open_file(path) {
- self.status = format!("open error: {e}");
- self.log_error(self.status.clone());
- }
- }
- }
- TextEditorRequest::Save => {
- if let Err(e) = self.text_editor.save_active() {
- self.status = format!("save error: {e}");
- self.log_error(self.status.clone());
- }
- }
- TextEditorRequest::SaveAs => {
- if let Some(path) = rfd::FileDialog::new().save_file() {
- if let Err(e) = self.text_editor.save_active_as(path) {
- self.status = format!("save error: {e}");
- self.log_error(self.status.clone());
- }
- }
- }
- TextEditorRequest::Close => self.text_editor.close_active(),
- }
- }
-
- fn ui_mcp_repl_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- render_mcp_repl(&mut self.mcp_repl, ui, muted, primary);
- }
-
- // ── Debugger tool ──────────────────────────────────
-
- fn draw_debugger_panes(&mut self, ctx: &egui::Context, muted: Color32) {
- debugger::draw_host(ctx, &mut self.debugger, muted);
- }
-
- // ── Docking / layouts / Configure ────────────────
-
- fn snapshot_current_layout(&self, name: impl Into<String>) -> layouts::SavedLayout {
- let name = name.into();
- let mut open_panes = BTreeMap::new();
- for (k, v) in &self.pane_open {
- open_panes.insert(k.egui_id().to_string(), *v);
- }
- debugger::snapshot_layout_flags(&self.debugger, &mut open_panes);
- let mut docks = BTreeMap::new();
- docks.insert("project_tree".into(), self.show_project_tree);
- 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 = 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",
- }
- .to_string();
- layouts::SavedLayout {
- name,
- open_panes,
- docks,
- center,
- dock_tree,
- theme,
- comment: String::new(),
- }
- }
-
- fn apply_saved_layout(&mut self, layout: &layouts::SavedLayout) {
- // Apply pane visibility.
- let ids: BTreeMap<&'static str, PaneKind> =
- PaneKind::ALL.iter().map(|k| (k.egui_id(), *k)).collect();
- for (id, open) in &layout.open_panes {
- if let Some(k) = ids.get(id.as_str()) {
- self.pane_open.insert(*k, *open);
- }
- }
- debugger::apply_layout_flags(&mut self.debugger, &layout.open_panes);
- // Docks.
- if let Some(v) = layout.docks.get("project_tree") {
- self.show_project_tree = *v;
- }
- if let Some(v) = layout.docks.get("program_tree") {
- self.show_program_tree = *v;
- }
- if let Some(v) = layout.docks.get("symbol_tree") {
- self.show_symbol_tree = *v;
- }
- if let Some(v) = layout.docks.get("console") {
- self.show_console = *v;
- }
- 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,
- };
- self.current_layout_name = layout.name.clone();
- }
-
- /// Save the current layout under `name`.
- pub fn save_layout_named(&mut self, name: impl Into<String>) -> std::io::Result<PathBuf> {
- let name = name.into();
- let l = self.snapshot_current_layout(name.clone());
- let p = layouts::save_layout(&l)?;
- self.current_layout_name = name;
- self.layouts_cached = layouts::list_layouts();
- Ok(p)
- }
-
- /// Restore a saved layout by name.
- pub fn restore_layout_named(&mut self, name: &str) -> std::io::Result<()> {
- let l = layouts::load_layout(name)?;
- self.apply_saved_layout(&l);
- Ok(())
- }
-
- /// draw all edit dialogs (rename / retype / comment / signature / new type).
- fn draw_edit_dialogs(&mut self, ctx: &egui::Context) {
- // Rename dialog .
- if self.show_rename_dialog {
- let mut close = false;
- let mut confirm = false;
- let va = self.rename_dialog_target_va;
- egui::Window::new("Rename")
- .id(egui::Id::new("dialog_rename"))
- .collapsible(false)
- .resizable(false)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- if let Some(va) = va {
- ui.label(format!("Address: {va:#x}"));
- }
- ui.label(format!("Old name: {}", self.rename_dialog_old_name));
- ui.label("New name:");
- let resp = ui.text_edit_singleline(&mut self.rename_dialog_new_name);
- if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
- confirm = true;
- }
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- close = true;
- }
- if ui.button("Rename").clicked() {
- confirm = true;
- }
- });
- });
- if confirm {
- if let Some(va) = va {
- if let Err(e) = self.rename_at(va, self.rename_dialog_new_name.clone()) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- } else {
- close = true;
- }
- }
- }
- if close {
- self.show_rename_dialog = false;
- }
- }
-
- // Retype dialog .
- if self.show_retype_dialog {
- let mut close = false;
- let mut confirm = false;
- let va = self.retype_dialog_target_va;
- egui::Window::new("Retype")
- .id(egui::Id::new("dialog_retype"))
- .collapsible(false)
- .resizable(false)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- if let Some(va) = va {
- ui.label(format!("Address: {va:#x}"));
- }
- ui.label("Type .:");
- let resp = ui.text_edit_singleline(&mut self.retype_dialog_type);
- if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
- confirm = true;
- }
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- close = true;
- }
- if ui.button("Clear").clicked() {
- self.retype_dialog_type.clear();
- confirm = true;
- }
- if ui.button("Apply").clicked() {
- confirm = true;
- }
- });
- });
- if confirm {
- if let Some(va) = va {
- if let Err(e) = self.retype_at(va, self.retype_dialog_type.clone()) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- } else {
- close = true;
- }
- }
- }
- if close {
- self.show_retype_dialog = false;
- }
- }
-
- // Comment dialog (Set EOL/Pre/Post/Plate/Repeatable).
- if self.show_comment_dialog {
- let mut close = false;
- let mut confirm = false;
- let va = self.comment_dialog_target_va;
- egui::Window::new("Set Comment")
- .id(egui::Id::new("dialog_comment"))
- .collapsible(false)
- .resizable(true)
- .default_width(420.0)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- if let Some(va) = va {
- ui.label(format!("Address: {va:#x}"));
- }
- ui.horizontal(|ui| {
- ui.label("Kind:");
- egui::ComboBox::from_id_salt("comment_kind")
- .selected_text(self.comment_dialog_kind.label())
- .show_ui(ui, |ui| {
- for k in CommentKind::ALL {
- if ui
- .selectable_value(
- &mut self.comment_dialog_kind,
- *k,
- k.label(),
- )
- .clicked()
- {
- // Load existing text for that kind.
- if let (Some(va), Some(prog)) = (va, self.program.as_ref())
- {
- self.comment_dialog_text = prog
- .edits
- .comment_at(va, *k)
- .unwrap_or_default()
- .to_string();
- }
- }
- }
- });
- });
- ui.label("Text:");
- ui.add(
- egui::TextEdit::multiline(&mut self.comment_dialog_text)
- .desired_rows(4)
- .desired_width(f32::INFINITY),
- );
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- close = true;
- }
- if ui.button("Clear").clicked() {
- self.comment_dialog_text.clear();
- confirm = true;
- }
- if ui.button("Save").clicked() {
- confirm = true;
- }
- });
- });
- if confirm {
- if let Some(va) = va {
- if let Err(e) = self.set_comment_at(
- va,
- self.comment_dialog_kind,
- self.comment_dialog_text.clone(),
- ) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- } else {
- close = true;
- }
- }
- }
- if close {
- self.show_comment_dialog = false;
- }
- }
-
- // Function-signature dialog (Edit Function Signature).
- if self.show_fn_signature_dialog {
- let mut close = false;
- let mut confirm = false;
- let entry = self.fn_signature_dialog_entry;
- egui::Window::new("Edit Function Signature")
- .id(egui::Id::new("dialog_fn_sig"))
- .collapsible(false)
- .resizable(true)
- .default_width(520.0)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- if let Some(entry) = entry {
- ui.label(format!("Function entry: {entry:#x}"));
- }
- ui.label("Signature:");
- ui.add(
- egui::TextEdit::multiline(&mut self.fn_signature_dialog_text)
- .desired_rows(3)
- .desired_width(f32::INFINITY)
- .font(egui::FontId::monospace(13.0)),
- );
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- close = true;
- }
- if ui.button("Save").clicked() {
- confirm = true;
- }
- });
- });
- if confirm {
- if let Some(entry) = entry {
- if let Err(e) =
- self.set_function_signature(entry, self.fn_signature_dialog_text.clone())
- {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- } else {
- close = true;
- }
- }
- }
- if close {
- self.show_fn_signature_dialog = false;
- }
- }
-
- // New Type dialog (DTM → New → Structure/Union/Enum/Typedef/FunctionDef).
- if self.show_new_type_dialog {
- let mut close = false;
- let mut confirm = false;
- let kind = self.new_type_dialog_kind;
- egui::Window::new(format!("New {}", kind.label()))
- .id(egui::Id::new("dialog_new_type"))
- .collapsible(false)
- .resizable(true)
- .default_width(560.0)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- ui.label("Name:");
- ui.text_edit_singleline(&mut self.new_type_dialog_name);
- ui.label(format!("{} body:", kind.label()));
- ui.add(
- egui::TextEdit::multiline(&mut self.new_type_dialog_body)
- .desired_rows(8)
- .desired_width(f32::INFINITY)
- .font(egui::FontId::monospace(13.0)),
- );
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- close = true;
- }
- if ui.button("Create").clicked() {
- confirm = true;
- }
- });
- });
- if confirm {
- let name = self.new_type_dialog_name.clone();
- let body = format!("{}\n{}", kind.label(), self.new_type_dialog_body);
- if let Err(e) = self.define_user_type(name, body) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- } else {
- close = true;
- }
- }
- if close {
- self.show_new_type_dialog = false;
- }
- }
-
- // Edit Type dialog (DTM → Edit on an existing user type).
- if self.show_edit_type_dialog {
- let mut close = false;
- let mut confirm = false;
- let orig = self.edit_type_dialog_orig_name.clone();
- egui::Window::new(format!("Edit type · {orig}"))
- .id(egui::Id::new("dialog_edit_type"))
- .collapsible(false)
- .resizable(true)
- .default_width(560.0)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- ui.label("Name:");
- ui.text_edit_singleline(&mut self.edit_type_dialog_name);
- ui.label("Body .:");
- ui.add(
- egui::TextEdit::multiline(&mut self.edit_type_dialog_body)
- .desired_rows(10)
- .desired_width(f32::INFINITY)
- .font(egui::FontId::monospace(13.0)),
- );
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- close = true;
- }
- if ui.button("Delete").clicked() {
- if let Err(e) = self.delete_user_type(&orig) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- } else {
- close = true;
- }
- }
- if ui.button("Save").clicked() {
- confirm = true;
- }
- });
- });
- if confirm {
- let new_name = self.edit_type_dialog_name.clone();
- let body = self.edit_type_dialog_body.clone();
- if let Err(e) = self.edit_user_type(&orig, new_name, body) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- } else {
- close = true;
- }
- }
- if close {
- self.show_edit_type_dialog = false;
- }
- }
-
- // Data Type Chooser dialog .
- if self.show_type_chooser_dialog {
- let mut close = false;
- let mut apply: Option<String> = None;
- let va = self.type_chooser_target_va;
- egui::Window::new("Choose Data Type")
- .id(egui::Id::new("dialog_type_chooser"))
- .collapsible(false)
- .resizable(true)
- .default_width(420.0)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- if let Some(va) = va {
- ui.small(format!("Apply target: {va:#x}"));
- } else {
- ui.weak("No cursor VA — click a Listing line first.");
- }
- ui.horizontal(|ui| {
- ui.label("Filter:");
- ui.add(
- egui::TextEdit::singleline(&mut self.type_chooser_filter)
- .desired_width(240.0)
- .hint_text("Type name…"),
- );
- });
- let q = self.type_chooser_filter.to_ascii_lowercase();
- let user_types: Vec<String> = self
- .program
- .as_ref()
- .map(|p| p.edits.user_types.keys().cloned().collect())
- .unwrap_or_default();
- egui::ScrollArea::vertical()
- .id_salt("type_chooser_scroll")
- .max_height(280.0)
- .show(ui, |ui| {
- for name in BUILTIN_TYPES {
- if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {
- continue;
- }
- ui.horizontal(|ui| {
- ui.monospace(*name);
- ui.with_layout(
- egui::Layout::right_to_left(egui::Align::Center),
- |ui| {
- if ui.small_button("Apply").clicked() {
- apply = Some((*name).to_string());
- }
- },
- );
- });
- }
- if !user_types.is_empty() {
- ui.separator();
- ui.small("Program archive:");
- for name in &user_types {
- if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {
- continue;
- }
- ui.horizontal(|ui| {
- ui.monospace(name);
- ui.with_layout(
- egui::Layout::right_to_left(egui::Align::Center),
- |ui| {
- if ui.small_button("Apply").clicked() {
- apply = Some(name.clone());
- }
- },
- );
- });
- }
- }
- });
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- close = true;
- }
- });
- });
- if let Some(name) = apply {
- if let Some(va) = va {
- if let Err(e) = self.apply_type_at(va, name) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- } else {
- close = true;
- }
- } else {
- self.status = "No cursor VA — click a Listing line first".into();
- self.log_warn(self.status.clone());
- }
- }
- if close {
- self.show_type_chooser_dialog = false;
- }
- }
- }
-
- /// Data Type Manager tree (Built-In archive + Program archive).
- fn ui_dtm_pane(&mut self, ui: &mut egui::Ui) {
- ui.heading("Data Type Manager");
- ui.small(
- egui::RichText::new(
- "DataTypeManagerPlugin · Built-In archive + Program archive (user types)",
- )
- .weak(),
- );
- ui.separator();
- ui.horizontal(|ui| {
- ui.label("Filter:");
- ui.add(
- egui::TextEdit::singleline(&mut self.dtm_filter)
- .desired_width(240.0)
- .hint_text("Type name…"),
- );
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- ui.menu_button("New…", |ui| {
- for k in NewTypeKind::ALL {
- if ui.button(k.label()).clicked() {
- self.open_new_type_dialog(*k);
- ui.close_menu();
- }
- }
- });
- });
- });
- let q = self.dtm_filter.to_ascii_lowercase();
- // Per-frame action queue so we can mutate `self` outside the borrowed
- // scroll-area closure below without fighting the borrow checker.
- let mut pending_apply: Option<String> = None;
- let mut pending_typedef_on: Option<String> = None;
- let mut pending_pointer_to: Option<String> = None;
- let mut pending_edit: Option<String> = None;
- let mut pending_rename: Option<String> = None;
- let mut pending_delete: Option<String> = None;
- egui::ScrollArea::vertical()
- .id_salt("dtm_scroll")
- .auto_shrink([false, false])
- .show(ui, |ui| {
- // Built-In archive. Read-only leaves — 's
- // Built-In archive is not editable; right-click gives us
- // Apply / +Typedef / +Pointer / Copy-to-program.
- egui::CollapsingHeader::new("Built-In")
- .default_open(true)
- .show(ui, |ui| {
- for name in BUILTIN_TYPES {
- if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {
- continue;
- }
- let row_resp = ui
- .horizontal(|ui| {
- ui.monospace(*name);
- ui.with_layout(
- egui::Layout::right_to_left(egui::Align::Center),
- |ui| {
- if ui
- .small_button("+Ptr")
- .on_hover_text("New Pointer to X .")
- .clicked()
- {
- pending_pointer_to = Some((*name).to_string());
- }
- if ui
- .small_button("+Typedef")
- .on_hover_text("New Typedef on X .")
- .clicked()
- {
- pending_typedef_on = Some((*name).to_string());
- }
- if let Some(va) = self.listing_focus_va {
- if ui
- .small_button("Apply @ cursor")
- .on_hover_text(format!(
- "Apply {name} at {va:#x}"
- ))
- .clicked()
- {
- pending_apply = Some((*name).to_string());
- }
- }
- },
- );
- })
- .response;
- // right-click submenu (Rename/Delete
- // Cut/Copy/Paste are N/A on Built-In, so we only
- // offer the applicable actions).
- row_resp.context_menu(|ui| {
- ui.label(egui::RichText::new(*name).monospace());
- ui.separator();
- let has_va = self.listing_focus_va.is_some();
- if ui
- .add_enabled(has_va, egui::Button::new("Apply @ cursor"))
- .clicked()
- {
- pending_apply = Some((*name).to_string());
- ui.close_menu();
- }
- if ui.button("New Typedef on X").clicked() {
- pending_typedef_on = Some((*name).to_string());
- ui.close_menu();
- }
- if ui.button("New Pointer to X").clicked() {
- pending_pointer_to = Some((*name).to_string());
- ui.close_menu();
- }
- });
- }
- });
- // Program archive: user-defined types + analyzer-recovered RTTI classes.
- let (user_types, rtti_classes) = self
- .program
- .as_ref()
- .map(|p| {
- (
- p.edits.user_types.clone(),
- p.rtti
- .classes
- .iter()
- .map(|c| c.name.clone())
- .collect::<Vec<_>>(),
- )
- })
- .unwrap_or_default();
- let title = format!(
- "Program ({user} user + {rtti} RTTI)",
- user = user_types.len(),
- rtti = rtti_classes.len()
- );
- egui::CollapsingHeader::new(title)
- .default_open(true)
- .show(ui, |ui| {
- if user_types.is_empty() && rtti_classes.is_empty() {
- ui.weak(
- "Empty — use New… to define a Structure/Union/Enum/Typedef/FunctionDef.",
- );
- }
- for (name, body) in &user_types {
- if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {
- continue;
- }
- let row_resp = ui
- .horizontal(|ui| {
- ui.monospace(name.to_string());
- ui.weak(
- egui::RichText::new(
- body.lines().next().unwrap_or_default().to_string(),
- )
- .italics(),
- );
- ui.with_layout(
- egui::Layout::right_to_left(egui::Align::Center),
- |ui| {
- if ui.small_button("Delete").clicked() {
- pending_delete = Some(name.clone());
- }
- if ui.small_button("Rename…").clicked() {
- pending_rename = Some(name.clone());
- }
- if ui.small_button("Edit…").clicked() {
- pending_edit = Some(name.clone());
- }
- if let Some(va) = self.listing_focus_va {
- if ui
- .small_button("Apply @ cursor")
- .on_hover_text(format!(
- "Apply {name} at {va:#x}"
- ))
- .clicked()
- {
- pending_apply = Some(name.clone());
- }
- }
- },
- );
- })
- .response;
- row_resp.context_menu(|ui| {
- ui.label(egui::RichText::new(name).monospace());
- ui.separator();
- if ui.button("Edit…").clicked() {
- pending_edit = Some(name.clone());
- ui.close_menu();
- }
- if ui.button("Rename…").clicked() {
- pending_rename = Some(name.clone());
- ui.close_menu();
- }
- if ui.button("Delete").clicked() {
- pending_delete = Some(name.clone());
- ui.close_menu();
- }
- ui.separator();
- let has_va = self.listing_focus_va.is_some();
- if ui
- .add_enabled(has_va, egui::Button::new("Apply @ cursor"))
- .clicked()
- {
- pending_apply = Some(name.clone());
- ui.close_menu();
- }
- if ui.button("New Typedef on X").clicked() {
- pending_typedef_on = Some(name.clone());
- ui.close_menu();
- }
- if ui.button("New Pointer to X").clicked() {
- pending_pointer_to = Some(name.clone());
- ui.close_menu();
- }
- });
- }
- if !rtti_classes.is_empty() {
- ui.separator();
- ui.small(egui::RichText::new("RTTI classes (from analyzer)").weak());
- for name in &rtti_classes {
- if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {
- continue;
- }
- let row_resp = ui
- .horizontal(|ui| {
- ui.monospace(name);
- ui.with_layout(
- egui::Layout::right_to_left(egui::Align::Center),
- |ui| {
- if ui.small_button("+Ptr").clicked() {
- pending_pointer_to = Some(name.clone());
- }
- if ui.small_button("+Typedef").clicked() {
- pending_typedef_on = Some(name.clone());
- }
- if self.listing_focus_va.is_some()
- && ui.small_button("Apply @ cursor").clicked()
- {
- pending_apply = Some(name.clone());
- }
- },
- );
- })
- .response;
- row_resp.context_menu(|ui| {
- ui.label(egui::RichText::new(name).monospace());
- ui.separator();
- let has_va = self.listing_focus_va.is_some();
- if ui
- .add_enabled(has_va, egui::Button::new("Apply @ cursor"))
- .clicked()
- {
- pending_apply = Some(name.clone());
- ui.close_menu();
- }
- if ui.button("New Typedef on X").clicked() {
- pending_typedef_on = Some(name.clone());
- ui.close_menu();
- }
- if ui.button("New Pointer to X").clicked() {
- pending_pointer_to = Some(name.clone());
- ui.close_menu();
- }
- });
- }
- }
- });
- });
- ui.separator();
- ui.small(
- egui::RichText::new(
- "Right-click a type for Edit / Rename / Delete / Apply @ cursor / \
- New Typedef on X / New Pointer to X. Docking-framework drag-and-drop \
- not yet wired.",
- )
- .weak()
- .italics(),
- );
- // Flush queued actions after the scroll-area borrow drops.
- if let Some(name) = pending_apply {
- if let Some(va) = self.listing_focus_va {
- if let Err(e) = self.apply_type_at(va, name) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- }
- }
- }
- if let Some(name) = pending_typedef_on {
- match self.new_typedef_on(&name) {
- Ok(new_name) => {
- self.status = format!("Created typedef {new_name} on {name}");
- self.log(self.status.clone());
- }
- Err(e) => {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- }
- }
- }
- if let Some(name) = pending_pointer_to {
- match self.new_pointer_to(&name) {
- Ok(new_name) => {
- self.status = format!("Created pointer type {new_name}");
- self.log(self.status.clone());
- }
- Err(e) => {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- }
- }
- }
- if let Some(name) = pending_edit {
- self.open_edit_type_dialog(&name);
- }
- if let Some(name) = pending_rename {
- // Reuse the standard Rename dialog but retarget its callback path:
- // renames of user types go through the new-type dialog with the
- // current body preloaded (so Save = rename + optional body edit).
- self.open_edit_type_dialog(&name);
- }
- if let Some(name) = pending_delete {
- if let Err(e) = self.delete_user_type(&name) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- }
- }
- }
-
- /// Listing center pane with real fields, margin markers, and flow arrows.
- fn ui_listing_pane(&mut self, ui: &mut egui::Ui) {
- ui.heading("Listing");
- let mut open_opts = self.show_decode_options_dialog;
- match ui_toolbar(ui, &mut self.decode_opts, &mut open_opts) {
- ToolbarAction::Apply => self.apply_decode_opts(),
- ToolbarAction::OpenOptions => open_opts = true,
- ToolbarAction::None => {}
- }
- self.show_decode_options_dialog = open_opts;
- ui_search_bar(ui, &mut self.listing_search);
- self.listing_search.arch = self.listing_arch();
- // Status strip.
- ui.horizontal(|ui| {
- if !self.listing_selection.is_empty() {
- ui.small(format!(
- "Sel {}–{}",
- self.listing_selection.start.unwrap_or(0),
- self.listing_selection.end.unwrap_or(0)
- ));
- }
- if let Some(va) = self.listing_focus_va {
- ui.small(format!("Cursor {va:#x}"));
- }
- if let Some(f) = self.listing_view_filter.as_ref() {
- let names = f.iter().cloned().collect::<Vec<_>>().join(", ");
- ui.small(
- egui::RichText::new(format!("View filter · {} fragment(s): {names}", f.len()))
- .weak(),
- );
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- if ui.small_button("Show All").clicked() {
- self.listing_view_filter = None;
- }
- });
- }
- });
- ui.separator();
- if self.listing.is_empty() {
- ui.weak("No listing — double-click a project file to open.");
- return;
- }
- let focus = self.listing_focus_va;
- let sel = self.listing_selection;
- let t = m3_tokens(self.theme);
- let sel_bg =
- Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]).gamma_multiply(0.35);
- // Snapshot for the closure: (idx, va, bytes_hex, mnem, ops, is_ret, is_uncond, is_cond, is_call, applied_type, comment_eol).
- let rows: Vec<ListingRow> = {
- let filter = self.listing_view_filter.clone();
- let prog_ref = self.program.as_ref();
- let arch = self.listing_arch();
- let search = &self.listing_search;
- self.listing
- .iter()
- .enumerate()
- .filter(|(_, insn)| listing_matches(insn, search))
- .filter(|(_, insn)| match &filter {
- None => true,
- Some(set) => {
- if set.is_empty() {
- false
- } else if let Some(p) = prog_ref {
- p.blocks.iter().filter(|b| set.contains(&b.name)).any(|b| {
- insn.address >= b.va && insn.address < b.va.saturating_add(b.size)
- })
- } else {
- true
- }
- }
- })
- .map(|(i, insn)| ListingRow::from_insn(i, insn, prog_ref, arch))
- .collect()
- };
- let bookmarks_by_va: BTreeMap<u64, BookmarkKind> =
- self.bookmarks.iter().map(|b| (b.va, b.kind)).collect();
- let mut click_i: Option<(usize, u64)> = None;
- // Right-click actions surfaced via a context menu attached to the
- // Address column. Executed after the scroll-area borrow drops.
- #[derive(Debug, Clone, Copy)]
- enum RowAction {
- OpenComment(CommentKind),
- OpenRename,
- OpenRetype,
- OpenChooser,
- OpenSignature,
- OpenEquate,
- ShowRefsTo,
- OpenBytesHere,
- DecryptSelection,
- SuggestRecipe,
- CryptoConstantsAtCursor,
- RecoverStringsHere,
- }
- let mut pending_action: Option<(u64, RowAction)> = None;
- egui::ScrollArea::both()
- .id_salt("listing_scroll")
- .auto_shrink([false, false])
- .show(ui, |ui| {
- egui::Grid::new("listing_grid")
- .num_columns(7)
- .spacing([6.0, 2.0])
- .striped(false)
- .show(ui, |ui| {
- ui.strong(egui::RichText::new("").monospace());
- ui.strong("Address");
- ui.strong("Bytes");
- ui.strong("Mnemonic");
- ui.strong("Operands");
- ui.strong("Flow");
- ui.strong("Comment");
- ui.end_row();
- for row in &rows {
- let focused = focus == Some(row.va);
- let selected = sel.contains(row.idx);
- // Pre-comment row (`Pre` comment appears
- // as its own line above the instruction).
- if let Some(pre) = &row.comment_pre {
- ui.label(egui::RichText::new(" ").monospace());
- ui.label(
- egui::RichText::new(format!("; {pre}"))
- .italics()
- .color(Color32::from_rgb(0x64, 0xB5, 0xF6)),
- );
- for _ in 0..5 {
- ui.label("");
- }
- ui.end_row();
- }
- // Margin column: bookmark tint + flow-glyph.
- let margin_text = if let Some(k) = bookmarks_by_va.get(&row.va) {
- egui::RichText::new("* ")
- .color(k.color())
- .monospace()
- .strong()
- } else if focused {
- egui::RichText::new("> ")
- .color(Color32::from_rgb(0xFF, 0xD5, 0x4F))
- .monospace()
- .strong()
- } else {
- egui::RichText::new(" ").monospace()
- };
- ui.label(margin_text);
- // Address column (clickable).
- let addr_rich = egui::RichText::new(format!("{:08x}", row.va))
- .monospace()
- .color(if focused {
- Color32::from_rgb(0xFF, 0xD5, 0x4F)
- } else {
- ui.visuals().text_color()
- });
- let addr_bg = if selected { Some(sel_bg) } else { None };
- let addr = ui.add(
- egui::Label::new(if let Some(bg) = addr_bg {
- addr_rich.background_color(bg)
- } else {
- addr_rich
- })
- .sense(egui::Sense::click()),
- );
- if addr.clicked() {
- click_i = Some((row.idx, row.va));
- }
- // Listing right-click submenu.
- let va = row.va;
- addr.context_menu(|ui| {
- ui.label(
- egui::RichText::new(format!("{va:#x}")).monospace().strong(),
- );
- ui.separator();
- ui.menu_button("Set Comment", |ui| {
- for k in CommentKind::ALL {
- if ui.button(k.label()).clicked() {
- pending_action = Some((va, RowAction::OpenComment(*k)));
- ui.close_menu();
- }
- }
- });
- ui.separator();
- if ui.button("Rename Symbol… (L)").clicked() {
- pending_action = Some((va, RowAction::OpenRename));
- ui.close_menu();
- }
- if ui.button("Retype Variable… (Ctrl+L)").clicked() {
- pending_action = Some((va, RowAction::OpenRetype));
- ui.close_menu();
- }
- if ui.button("Choose Data Type… (T)").clicked() {
- pending_action = Some((va, RowAction::OpenChooser));
- ui.close_menu();
- }
- if ui.button("Edit Function Signature… (Alt+Enter)").clicked() {
- pending_action = Some((va, RowAction::OpenSignature));
- ui.close_menu();
- }
- ui.separator();
- if ui
- .button("Set Equate…")
- .on_hover_text("Bind a name to the first operand scalar")
- .clicked()
- {
- pending_action = Some((va, RowAction::OpenEquate));
- ui.close_menu();
- }
- if ui
- .button("Show References To…")
- .on_hover_text("Open Symbol References for this VA")
- .clicked()
- {
- pending_action = Some((va, RowAction::ShowRefsTo));
- ui.close_menu();
- }
- if ui
- .button("Show Bytes Here")
- .on_hover_text("Open Byte Viewer at this VA")
- .clicked()
- {
- pending_action = Some((va, RowAction::OpenBytesHere));
- ui.close_menu();
- }
- ui.separator();
- if ui
- .button("Decrypt selection…")
- .on_hover_text("Open Decrypt pane on bytes at this VA")
- .clicked()
- {
- pending_action = Some((va, RowAction::DecryptSelection));
- ui.close_menu();
- }
- if ui
- .button("Suggest recipe…")
- .on_hover_text("Magic peel on bytes at this VA")
- .clicked()
- {
- pending_action = Some((va, RowAction::SuggestRecipe));
- ui.close_menu();
- }
- if ui
- .button("Crypto Constants at cursor…")
- .on_hover_text("Focus Crypto Constants near this VA")
- .clicked()
- {
- pending_action = Some((va, RowAction::CryptoConstantsAtCursor));
- ui.close_menu();
- }
- if ui
- .button("Recover strings here…")
- .on_hover_text("Open Recovered Strings pane")
- .clicked()
- {
- pending_action = Some((va, RowAction::RecoverStringsHere));
- ui.close_menu();
- }
- });
- // Bytes column.
- ui.monospace(&row.bytes_hex);
- // Mnemonic column, coloured by kind.
- let mnem_color = if row.is_ret {
- Color32::from_rgb(0xEF, 0x53, 0x50)
- } else if row.is_uncond {
- Color32::from_rgb(0xFF, 0xB7, 0x4D)
- } else if row.is_cond {
- Color32::from_rgb(0x81, 0xC7, 0x84)
- } else if row.is_call {
- Color32::from_rgb(0x64, 0xB5, 0xF6)
- } else {
- ui.visuals().text_color()
- };
- let mnem_resp = ui.label(
- egui::RichText::new(&row.mnem).monospace().color(mnem_color),
- );
- if !row.groups_summary.is_empty() || !row.regs_rw.is_empty() {
- mnem_resp.on_hover_ui(|ui| {
- ui.monospace(format!("id {}", row.id.raw()));
- if !row.groups_summary.is_empty() {
- ui.small(format!("groups: {}", row.groups_summary));
- }
- if !row.regs_rw.is_empty() {
- ui.small(&row.regs_rw);
- }
- });
- }
- // Operands column with scalar/address hover popup.
- let ops_resp = ui.add(
- egui::Label::new(egui::RichText::new(&row.ops).monospace())
- .sense(egui::Sense::hover()),
- );
- if !row.ops.is_empty() {
- ops_resp.on_hover_ui(|ui| {
- if let Some(scalar) = first_scalar_hint(&row.ops) {
- ui.small(scalar);
- }
- if let Some(addr) = first_address_hint(&row.ops) {
- ui.small(addr);
- }
- });
- }
- // Flow column: arrow glyph indicator.
- let flow_glyph = if row.is_ret {
- "return"
- } else if row.is_uncond {
- "→"
- } else if row.is_cond {
- "?→"
- } else if row.is_call {
- "call"
- } else {
- ""
- };
- ui.small(egui::RichText::new(flow_glyph).monospace());
- // Comment / applied type column (EOL + Repeatable
- // + Plate + Applied Type decoration).
- let mut comment_row = String::new();
- if let Some(t) = &row.applied_type {
- comment_row.push_str(&format!("<{t}> "));
- }
- if let Some(t) = &row.comment_eol {
- comment_row.push_str(&format!("// {t}"));
- }
- if let Some(t) = &row.comment_repeat {
- if !comment_row.is_empty() {
- comment_row.push_str(" ");
- }
- comment_row.push_str(&format!("~ {t}"));
- }
- if let Some(t) = &row.comment_plate {
- if !comment_row.is_empty() {
- comment_row.push_str(" ");
- }
- comment_row.push_str(&format!("[PLATE {t}]"));
- }
- ui.small(egui::RichText::new(comment_row).italics());
- ui.end_row();
- // Post-comment row (`Post` comment appears
- // as its own line below the instruction).
- if let Some(post) = &row.comment_post {
- ui.label(egui::RichText::new(" ").monospace());
- ui.label(
- egui::RichText::new(format!("; {post}"))
- .italics()
- .color(Color32::from_rgb(0xBA, 0x68, 0xC8)),
- );
- for _ in 0..5 {
- ui.label("");
- }
- ui.end_row();
- }
- }
- });
- });
- if let Some((i, addr)) = click_i {
- self.push_selection_undo();
- self.listing_selection = ListingSelection {
- start: Some(i),
- end: Some(i),
- };
- self.listing_focus_va = Some(addr);
- self.refresh_decompiler_at(addr);
- self.event_bus.publish(GhidrustEvent::CursorMoved {
- source: EventSource::Listing,
- location: NavLocation::new(addr),
- });
- }
- if let Some((va, action)) = pending_action {
- match action {
- RowAction::OpenComment(k) => self.open_comment_dialog(va, k),
- RowAction::OpenRename => self.open_rename_dialog(va),
- RowAction::OpenRetype => self.open_retype_dialog(va),
- RowAction::OpenChooser => self.open_type_chooser(Some(va)),
- RowAction::OpenSignature => {
- // Alt+Enter is defined on a function; if the cursor isn't
- // inside a function, fall back to opening the signature
- // dialog with the given VA as entry (user can retype it).
- let entry = self
- .program
- .as_ref()
- .and_then(|p| {
- p.analysis
- .functions
- .iter()
- .find(|f| va >= f.entry && va < f.end)
- .map(|f| f.entry)
- })
- .unwrap_or(va);
- self.open_signature_dialog(entry);
- }
- RowAction::OpenEquate => {
- self.equate_dialog_va = Some(va);
- self.equate_dialog_op = 1;
- self.equate_dialog_name.clear();
- // Preload first scalar from the operand string for convenience.
- self.equate_dialog_value = self
- .listing
- .iter()
- .find(|i| i.address == va)
- .and_then(|i| menu_actions::extract_scalars(&i.operands).first().copied())
- .map(|v| format!("{v}"))
- .unwrap_or_default();
- self.show_equate_dialog = true;
- }
- RowAction::ShowRefsTo => {
- self.symbol_refs_target = Some(va);
- self.pane_open.insert(PaneKind::SymbolReferences, true);
- }
- RowAction::OpenBytesHere => {
- self.bytes_pane_va = Some(va);
- self.pane_open.insert(PaneKind::Bytes, true);
- }
- RowAction::DecryptSelection => {
- self.open_decrypt_at(va, None);
- }
- RowAction::SuggestRecipe => {
- self.open_decrypt_at(va, None);
- self.decrypt_pane.bake_preset("magic");
- }
- RowAction::CryptoConstantsAtCursor => {
- self.crypto_constants_focus_va = Some(va);
- self.decrypt_pane.focus(DecryptTab::Constants);
- self.pane_open.insert(PaneKind::Decrypt, true);
- }
- RowAction::RecoverStringsHere => {
- self.recover_strings_at_function(va);
- self.decrypt_pane.focus(DecryptTab::Strings);
- self.pane_open.insert(PaneKind::Decrypt, true);
- }
- }
- }
- }
-
- /// tokenised Decompiler center pane with cross-highlight.
- fn ui_decompiler_pane(&mut self, ui: &mut egui::Ui) {
- ui.heading("Decompiler");
- if self.program.is_none() {
- ui.weak("Open a project file, then select a function or listing address.");
- return;
- }
- // Stage picker (Stage-0 / 0.5 / 1). Changing kicks off a re-emit
- // for the currently-focused entry.
- let mut sel = self.decomp_stage;
- ui.horizontal(|ui| {
- ui.label("Stage:");
- egui::ComboBox::from_id_salt("decomp_stage_combo")
- .selected_text(sel.label())
- .show_ui(ui, |ui| {
- ui.selectable_value(&mut sel, DecompStage::Stage0, "Stage-0 (CFG → goto)");
- ui.selectable_value(&mut sel, DecompStage::Stage05, "Stage-0.5 (IR-informed)");
- ui.selectable_value(
- &mut sel,
- DecompStage::Stage1,
- "Stage-1 (SSA + structure + types)",
- );
- });
- if let Some(r) = self.decomp_lift_ratio {
- ui.small(format!("lift {:.1}%", r * 100.0));
- }
- });
- if sel != self.decomp_stage {
- self.set_decomp_stage(sel);
- }
- // Keep cache in sync with cursor when switching to this pane.
- if let Some(va) = self
- .listing_focus_va
- .or(self.decomp_entry)
- .or_else(|| self.program.as_ref().and_then(|p| p.entry))
- {
- 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() {
- ui.small(&self.decomp_status);
- }
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- if let Some(entry) = self.decomp_entry {
- if ui
- .small_button("Commit Params/Return")
- .on_hover_text("Persist inferred params + return type as user edits")
- .clicked()
- {
- if let Err(e) = self.commit_params_return(entry) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- }
- }
- if ui
- .small_button("Commit Locals")
- .on_hover_text("Persist inferred stack locals as user edits")
- .clicked()
- {
- if let Err(e) = self.commit_locals(entry) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- }
- }
- if ui
- .small_button("Edit signature…")
- .on_hover_text("Edit function signature")
- .clicked()
- {
- self.open_signature_dialog(entry);
- }
- if ui
- .small_button("Rename function…")
- .on_hover_text("Rename this function (L)")
- .clicked()
- {
- self.open_rename_dialog(entry);
- }
- }
- });
- });
- ui.separator();
- if self.decomp_lines.is_empty() && self.decomp_text.is_empty() {
- ui.weak(
- "Select a Symbol Tree function or a Listing instruction to decompile (Stage-0 CFG → pseudo-C).",
- );
- return;
- }
- // Render tokenised lines.
- let visuals = ui.visuals().clone();
- let text_color = visuals.text_color();
- let cross_line = self.decomp_cross_line;
- let highlight_text = self.decomp_highlight_text.clone();
- let mut clicked_addr: Option<u64> = None;
- let mut mid_clicked_text: Option<String> = None;
- let mut decrypt_token: Option<(u64, String)> = None;
- let mut copy_decode_input: Option<(u64, String)> = None;
- let mut rename_token: Option<(u64, String)> = None;
- egui::ScrollArea::both()
- .id_salt("decomp_tokens_scroll")
- .auto_shrink([false, false])
- .show(ui, |ui| {
- let font = egui::FontId::monospace(13.0);
- for line in &self.decomp_lines {
- let is_cross = Some(line.line) == cross_line;
- let bg_frame = if is_cross {
- Some(
- egui::Frame::default()
- .fill(Color32::from_rgba_unmultiplied(0xFF, 0xD5, 0x4F, 40)),
- )
- } else {
- None
- };
- let mut render_row = |ui: &mut egui::Ui| {
- ui.horizontal(|ui| {
- // Left rail: address gutter (line.machine_addr).
- let gutter = line
- .machine_addr
- .map(|va| format!("{va:08x} "))
- .unwrap_or_else(|| " ".into());
- ui.add(
- egui::Label::new(
- egui::RichText::new(gutter)
- .monospace()
- .color(text_color.gamma_multiply(0.6)),
- )
- .selectable(false),
- );
- for tok in &line.tokens {
- let (color, italic) = token_style(&tok.kind, text_color);
- let highlighted = highlight_text
- .as_deref()
- .map(|h| h == tok.text)
- .unwrap_or(false)
- && matches!(
- tok.kind,
- TokenKind::Variable
- | TokenKind::Function
- | TokenKind::Address
- | TokenKind::Constant
- | TokenKind::Label
- );
- let mut rich = egui::RichText::new(&tok.text)
- .font(font.clone())
- .color(color);
- if italic {
- rich = rich.italics();
- }
- if highlighted {
- rich = rich.background_color(Color32::from_rgba_unmultiplied(
- 0x03, 0xA9, 0xF4, 90,
- ));
- }
- let clickable = matches!(
- tok.kind,
- TokenKind::Address
- | TokenKind::Function
- | TokenKind::Label
- | TokenKind::Variable
- | TokenKind::Constant
- );
- if clickable {
- let sense = egui::Sense::click();
- let resp = ui.add(egui::Label::new(rich).sense(sense));
- if resp.clicked() {
- if let Some(va) = tok.va {
- clicked_addr = Some(va);
- }
- }
- if resp.middle_clicked() {
- mid_clicked_text = Some(tok.text.clone());
- }
- if let Some(va) = tok.va.or(line.machine_addr) {
- let is_decode_input = matches!(
- tok.kind,
- TokenKind::Constant | TokenKind::Address
- );
- let is_identifier = tok
- .text
- .chars()
- .next()
- .map(|c| c.is_ascii_alphabetic() || c == '_')
- .unwrap_or(false);
- resp.context_menu(|ui| {
- if is_decode_input
- && ui.button("Decrypt constant…").clicked()
- {
- decrypt_token = Some((va, tok.text.clone()));
- ui.close_menu();
- }
- if is_decode_input
- && ui.button("Copy as decode input").clicked()
- {
- copy_decode_input = Some((va, tok.text.clone()));
- ui.close_menu();
- }
- if is_identifier
- && ui.button("Rename symbol…").clicked()
- {
- rename_token = Some((va, tok.text.clone()));
- ui.close_menu();
- }
- });
- }
- if resp.hovered() {
- ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
- }
- } else {
- ui.add(egui::Label::new(rich).selectable(true));
- }
- }
- });
- };
- if let Some(frame) = bg_frame {
- frame.show(ui, render_row);
- } else {
- render_row(ui);
- }
- }
- });
- if let Some(text) = mid_clicked_text {
- self.decomp_highlight_text =
- if self.decomp_highlight_text.as_deref() == Some(text.as_str()) {
- None
- } else {
- Some(text)
- };
- }
- if let Some((va, text)) = decrypt_token {
- self.decrypt_pane
- .load_text(Some(va), text, "Decompiler constant");
- self.pane_open.insert(PaneKind::Decrypt, true);
- }
- if let Some((va, text)) = copy_decode_input {
- self.decrypt_pane
- .load_text(Some(va), text, "Decompiler token");
- self.pane_open.insert(PaneKind::Decrypt, true);
- }
- if let Some((va, text)) = rename_token {
- self.open_rename_dialog(va);
- self.rename_dialog_old_name = text;
- }
- if let Some(va) = clicked_addr {
- // Only navigate if VA looks plausibly in-range (avoid `block_0` id = 0 jumping to base).
- let plausible = self
- .program
- .as_ref()
- .map(|p| p.contains_va(va))
- .unwrap_or(false)
- || va >= 0x1000;
- if plausible {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- }
- }
-
- fn open_rename_dialog(&mut self, va: u64) {
- let old = self
- .program
- .as_ref()
- .and_then(|p| p.display_name_at(va))
- .map(|s| s.to_string())
- .unwrap_or_default();
- self.show_rename_dialog = true;
- self.rename_dialog_target_va = Some(va);
- self.rename_dialog_old_name = old.clone();
- self.rename_dialog_new_name = old;
- }
-
- fn open_retype_dialog(&mut self, va: u64) {
- let cur = self
- .program
- .as_ref()
- .and_then(|p| p.edits.retype_at(va))
- .unwrap_or_default()
- .to_string();
- self.show_retype_dialog = true;
- self.retype_dialog_target_va = Some(va);
- self.retype_dialog_type = cur;
- }
-
- fn open_comment_dialog(&mut self, va: u64, kind: CommentKind) {
- let text = self
- .program
- .as_ref()
- .and_then(|p| p.edits.comment_at(va, kind))
- .unwrap_or_default()
- .to_string();
- self.show_comment_dialog = true;
- self.comment_dialog_target_va = Some(va);
- self.comment_dialog_kind = kind;
- self.comment_dialog_text = text;
- }
-
- fn open_signature_dialog(&mut self, entry: u64) {
- let existing = self
- .program
- .as_ref()
- .and_then(|p| p.edits.function_signature(entry))
- .map(|s| s.signature.clone())
- .unwrap_or_else(|| {
- self.program
- .as_ref()
- .and_then(|p| p.function_at(entry))
- .map(|f| {
- format!(
- "undefined {}({})",
- f.name,
- if f.parameters.is_empty() {
- "void".to_string()
- } else {
- f.parameters.join(", ")
- }
- )
- })
- .unwrap_or_default()
- });
- self.show_fn_signature_dialog = true;
- self.fn_signature_dialog_entry = Some(entry);
- self.fn_signature_dialog_text = existing;
- }
-
- fn open_new_type_dialog(&mut self, kind: NewTypeKind) {
- self.show_new_type_dialog = true;
- self.new_type_dialog_kind = kind;
- self.new_type_dialog_name.clear();
- self.new_type_dialog_body = kind.template().to_string();
- }
-
- fn open_edit_type_dialog(&mut self, name: &str) {
- let body = self
- .program
- .as_ref()
- .and_then(|p| p.edits.user_type(name))
- .unwrap_or_default()
- .to_string();
- self.show_edit_type_dialog = true;
- self.edit_type_dialog_orig_name = name.to_string();
- self.edit_type_dialog_name = name.to_string();
- self.edit_type_dialog_body = body;
- }
-
- fn open_type_chooser(&mut self, va: Option<u64>) {
- self.show_type_chooser_dialog = true;
- self.type_chooser_target_va = va;
- self.type_chooser_filter.clear();
- }
-
- fn ui_bookmarks_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- ui.heading("Bookmarks");
- ui.small(egui::RichText::new("BookmarkPlugin analog · 5 standard kinds").color(muted));
- ui.separator();
- ui.horizontal(|ui| {
- ui.label("Filter:");
- ui.add(
- egui::TextEdit::singleline(&mut self.bookmark_filter)
- .desired_width(200.0)
- .hint_text("category or description"),
- );
- if ui
- .button("Add at cursor…")
- .on_hover_text("Add a bookmark at the current Listing VA")
- .clicked()
- {
- if let Some(va) = self.listing_focus_va {
- self.bookmark_dialog_kind = BookmarkKind::Note;
- self.bookmark_dialog_category = String::new();
- self.bookmark_dialog_description = format!("bookmark @ {va:#x}");
- self.show_bookmark_dialog = true;
- } else {
- self.status = "No cursor VA — click a Listing line first".into();
- self.log(self.status.clone());
- }
- }
- });
- ui.separator();
-
- if self.bookmarks.is_empty() {
- ui.weak("No bookmarks yet — click Add at cursor to place one.");
- return;
- }
-
- let filt = self.bookmark_filter.to_ascii_lowercase();
- let rows: Vec<(usize, u64, BookmarkKind, String, String)> = self
- .bookmarks
- .iter()
- .enumerate()
- .filter(|(_, b)| {
- filt.is_empty()
- || b.category.to_ascii_lowercase().contains(&filt)
- || b.description.to_ascii_lowercase().contains(&filt)
- || b.kind.label().to_ascii_lowercase().contains(&filt)
- })
- .map(|(i, b)| (i, b.va, b.kind, b.category.clone(), b.description.clone()))
- .collect();
-
- ui.small(format!(
- "{} / {} bookmarks",
- rows.len(),
- self.bookmarks.len()
- ));
-
- egui::ScrollArea::vertical()
- .id_salt("bookmarks_scroll")
- .max_height(360.0)
- .show(ui, |ui| {
- egui::Grid::new("bookmarks_grid")
- .num_columns(5)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Type");
- ui.strong("Address");
- ui.strong("Category");
- ui.strong("Description");
- ui.strong("");
- ui.end_row();
-
- let mut goto: Option<u64> = None;
- let mut delete: Option<usize> = None;
- for (idx, va, kind, cat, desc) in &rows {
- ui.label(
- egui::RichText::new(kind.label())
- .color(kind.color())
- .strong(),
- );
- if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
- .on_hover_text("Go To this address")
- .clicked()
- {
- goto = Some(*va);
- }
- ui.label(cat);
- ui.label(desc);
- if ui.small_button("Delete").clicked() {
- delete = Some(*idx);
- }
- ui.end_row();
- }
- let _ = primary; // reserved for future accent use
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- if let Some(i) = delete {
- self.delete_bookmark(i);
- }
- });
- });
- }
-
- fn ui_memory_map_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Memory Map");
- ui.small(
- egui::RichText::new(
- "MemoryMapPlugin · toggle RWX / add / delete session memory blocks",
- )
- .color(muted),
- );
- ui.separator();
- if self.program.is_none() {
- ui.weak("No program loaded.");
- return;
- }
-
- // Add-row form.
- ui.horizontal(|ui| {
- ui.label("Add block:");
- ui.add(
- egui::TextEdit::singleline(&mut self.memory_map_new_name)
- .desired_width(120.0)
- .hint_text("name"),
- );
- ui.add(
- egui::TextEdit::singleline(&mut self.memory_map_new_va)
- .desired_width(120.0)
- .hint_text("VA (0x…)"),
- );
- ui.add(
- egui::TextEdit::singleline(&mut self.memory_map_new_size)
- .desired_width(100.0)
- .hint_text("size (0x…)"),
- );
- ui.checkbox(&mut self.memory_map_new_r, "R");
- ui.checkbox(&mut self.memory_map_new_w, "W");
- ui.checkbox(&mut self.memory_map_new_x, "X");
- let can_add = !self.memory_map_new_name.trim().is_empty()
- && !self.memory_map_new_va.trim().is_empty()
- && !self.memory_map_new_size.trim().is_empty();
- if ui.add_enabled(can_add, egui::Button::new("Add")).clicked() {
- let name = self.memory_map_new_name.clone();
- let va = parse_address(&self.memory_map_new_va).unwrap_or(0);
- let size = parse_address(&self.memory_map_new_size).unwrap_or(0);
- let r = self.memory_map_new_r;
- let w = self.memory_map_new_w;
- let x = self.memory_map_new_x;
- if size > 0 {
- if let Some(prog) = self.program.as_mut() {
- prog.blocks.push(ghidrust_core::MemoryBlock {
- name,
- va,
- size,
- bytes: vec![0u8; size.min(0x100_0000) as usize],
- readable: r,
- writable: w,
- executable: x,
- });
- }
- self.status = "Memory Map · added block".into();
- self.log(self.status.clone());
- }
- }
- });
- ui.separator();
-
- let mut goto: Option<u64> = None;
- let mut delete: Option<usize> = None;
- 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(9)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Name");
- ui.strong("Start");
- ui.strong("End");
- ui.strong("Length");
- 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
- .program
- .as_ref()
- .map(|p| {
- p.blocks
- .iter()
- .map(|b| {
- (
- b.name.clone(),
- b.va,
- b.size,
- b.readable,
- b.writable,
- b.executable,
- )
- })
- .collect()
- })
- .unwrap_or_default();
- for (i, (name, va, size, r, w, x)) in blocks.iter().enumerate() {
- let mut editable = name.clone();
- if ui
- .add(egui::TextEdit::singleline(&mut editable).desired_width(120.0))
- .changed()
- {
- rename = Some((i, editable));
- }
- if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
- .clicked()
- {
- goto = Some(*va);
- }
- ui.monospace(format!("{:#x}", va.saturating_add(*size)));
- ui.monospace(format!("{size:#x}"));
- let mut rb = *r;
- let mut wb = *w;
- let mut xb = *x;
- if ui.checkbox(&mut rb, "").changed() {
- toggle = Some((i, 'R'));
- }
- if ui.checkbox(&mut wb, "").changed() {
- toggle = Some((i, 'W'));
- }
- 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();
- }
- });
- });
-
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- if let Some((i, newname)) = rename {
- if let Some(prog) = self.program.as_mut() {
- if let Some(b) = prog.blocks.get_mut(i) {
- b.name = newname;
- }
- }
- }
- if let Some((i, ch)) = toggle {
- if let Some(prog) = self.program.as_mut() {
- if let Some(b) = prog.blocks.get_mut(i) {
- match ch {
- 'R' => b.readable = !b.readable,
- 'W' => b.writable = !b.writable,
- 'X' => b.executable = !b.executable,
- _ => {}
- }
- }
- }
- }
- if let Some(i) = delete {
- if let Some(prog) = self.program.as_mut() {
- if i < prog.blocks.len() {
- prog.blocks.remove(i);
- }
- }
- }
- }
-
- fn ui_functions_window(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- ui.heading("Functions");
- ui.small(
- egui::RichText::new("FunctionWindowPlugin · flat table of Program::analysis.functions")
- .color(muted),
- );
- ui.separator();
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- let n_total = prog.analysis.functions.len();
- if n_total == 0 {
- ui.weak("No functions — run Function Start Search.");
- return;
- }
- ui.horizontal(|ui| {
- ui.label("Filter:");
- ui.add(
- egui::TextEdit::singleline(&mut self.functions_window_filter)
- .desired_width(300.0)
- .hint_text("Function name…"),
- );
- });
- let q = self.functions_window_filter.to_ascii_lowercase();
- let rows: Vec<(u64, u64, String, usize)> = prog
- .analysis
- .functions
- .iter()
- .filter(|f| q.is_empty() || f.name.to_ascii_lowercase().contains(&q))
- .map(|f| (f.entry, f.end, f.name.clone(), f.parameters.len()))
- .collect();
- ui.small(format!("{} / {} functions", rows.len(), n_total));
- let focus = self.decomp_entry;
- egui::ScrollArea::vertical()
- .id_salt("fnwin_scroll")
- .max_height(400.0)
- .show(ui, |ui| {
- egui::Grid::new("functions_window_grid")
- .num_columns(4)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Entry");
- ui.strong("Size");
- ui.strong("Name");
- ui.strong("Params");
- ui.end_row();
- let mut clicked: Option<u64> = None;
- for (entry, end, name, params) in &rows {
- let size = end.saturating_sub(*entry);
- let addr_text = egui::RichText::new(format!("{entry:#x}"))
- .monospace()
- .color(if focus == Some(*entry) {
- primary
- } else {
- ui.visuals().text_color()
- });
- if ui.link(addr_text).clicked() {
- clicked = Some(*entry);
- }
- ui.monospace(format!("{size:#x}"));
- ui.label(name);
- ui.monospace(format!("{params}"));
- ui.end_row();
- }
- if let Some(va) = clicked {
- self.focus_function(va);
- }
- });
- });
- }
-
- fn ui_symbol_table(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Symbol Table");
- ui.small(
- egui::RichText::new(
- "SymbolTablePlugin · symbols + function entries · Refs → opens Symbol References",
- )
- .color(muted),
- );
- ui.separator();
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- ui.horizontal(|ui| {
- ui.label("Filter:");
- ui.add(
- egui::TextEdit::singleline(&mut self.symbol_table_filter)
- .desired_width(280.0)
- .hint_text("Symbol name…"),
- );
- });
- let q = self.symbol_table_filter.to_ascii_lowercase();
- // Merge analysis.symbols + function entries into one flat table.
- let mut rows: Vec<(u64, String, &'static str)> = Vec::new();
- for s in &prog.analysis.symbols {
- rows.push((s.va, s.name.clone(), "Symbol"));
- }
- for f in &prog.analysis.functions {
- rows.push((f.entry, f.name.clone(), "Function"));
- }
- rows.retain(|(_, name, _)| q.is_empty() || name.to_ascii_lowercase().contains(&q));
- rows.sort_by_key(|r| r.0);
-
- ui.small(format!("{} rows", rows.len()));
- let mut goto: Option<u64> = None;
- let mut show_refs: Option<u64> = None;
- egui::ScrollArea::vertical()
- .id_salt("symtable_scroll")
- .max_height(400.0)
- .show(ui, |ui| {
- egui::Grid::new("symbol_table_grid")
- .num_columns(4)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Address");
- ui.strong("Name");
- ui.strong("Type");
- ui.strong("Refs");
- ui.end_row();
- for (va, name, ty) in &rows {
- if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
- .clicked()
- {
- goto = Some(*va);
- }
- ui.label(name);
- ui.monospace(*ty);
- if ui
- .small_button("Refs")
- .on_hover_text("Open Symbol References for this VA")
- .clicked()
- {
- show_refs = Some(*va);
- }
- ui.end_row();
- }
- });
- });
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- if let Some(va) = show_refs {
- self.symbol_refs_target = Some(va);
- self.pane_open.insert(PaneKind::SymbolReferences, true);
- }
- }
-
- fn open_decrypt_at(&mut self, va: u64, hint: Option<String>) {
- self.open_decrypt_at_len(va, 256, hint);
- }
-
- fn open_decrypt_at_len(&mut self, va: u64, len: usize, hint: Option<String>) {
- let bytes = self
- .program
- .as_ref()
- .and_then(|p| decrypt_ui::bytes_at(p, va, len))
- .unwrap_or_default();
- self.decrypt_pane.load_bytes(Some(va), &bytes, hint);
- self.decrypt_pane.focus(DecryptTab::Bake);
- self.decrypt_pane.va_input = format!("{va:x}");
- self.decrypt_pane.va_len = len;
- self.pane_open.insert(PaneKind::Decrypt, true);
- }
-
- fn open_decrypt_nearby(&mut self, va: u64, hint: Option<String>) {
- let start = va.saturating_sub(32);
- let bytes = self
- .program
- .as_ref()
- .and_then(|p| decrypt_ui::bytes_at(p, start, 256))
- .unwrap_or_default();
- self.decrypt_pane.load_bytes(Some(va), &bytes, hint);
- self.decrypt_pane.input_source = format!("Bytes near crypto result at {va:#x}");
- self.decrypt_pane.focus(DecryptTab::Bake);
- self.pane_open.insert(PaneKind::Decrypt, true);
- }
-
- fn recover_strings_at_function(&mut self, va: u64) {
- let Some(prog) = self.program.as_ref() else {
- self.status = "Recover strings requires a loaded program.".into();
- return;
- };
- let entry = prog
- .analysis
- .functions
- .iter()
- .find(|f| va >= f.entry && va < f.end)
- .map(|f| f.entry)
- .unwrap_or(va);
- let hits = recover_obfuscated_strings(
- prog,
- &RecoverStringsOpts {
- functions: Some(vec![entry]),
- ..Default::default()
- },
- );
- self.obfuscated_strings = hits;
- self.status = format!(
- "Recovered {} strings in containing function {entry:#x}",
- self.obfuscated_strings.len()
- );
- }
-
- fn ui_crypto_constants_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
- let hits: Vec<_> = if let Some(va) = self.crypto_constants_focus_va {
- let mut nearby: Vec<_> = self
- .crypt_constants
- .iter()
- .filter(|h| h.va.abs_diff(va) <= 0x1000)
- .cloned()
- .collect();
- nearby.sort_by_key(|h| h.va.abs_diff(va));
- nearby
- } else {
- self.crypt_constants.clone()
- };
- let mut goto = None;
- let mut decrypt = None;
- decrypt_ui::ui_crypto_constants(
- ui,
- muted,
- &hits,
- |va| goto = Some(va),
- |va, algo| decrypt = Some((va, algo.to_string())),
- );
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- if let Some((va, algo)) = decrypt {
- self.open_decrypt_nearby(va, Some(algo));
- }
- }
-
- fn ui_recovered_strings_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
- let hits = self.obfuscated_strings.clone();
- let mut goto = None;
- let mut bake = None;
- let mut decoder = None;
- decrypt_ui::ui_recovered_strings(
- ui,
- muted,
- &hits,
- |va| goto = Some(va),
- |va| bake = Some(va),
- |va| decoder = Some(va),
- );
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- if let Some(va) = bake {
- self.open_decrypt_at(va, None);
- }
- if let Some(va) = decoder {
- self.focus_function(va);
- }
- }
-
- fn ui_crypto_capabilities_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
- let hits = self.crypto_capabilities.clone();
- let mut goto = None;
- let mut decrypt = None;
- decrypt_ui::ui_crypto_capabilities(
- ui,
- muted,
- &hits,
- |va| goto = Some(va),
- |va, hint| decrypt = Some((va, hint)),
- );
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- if let Some((va, hint)) = decrypt {
- self.open_decrypt_at(va, Some(hint));
- }
- }
-
- fn ui_defined_strings(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Defined Strings");
- ui.small(
- egui::RichText::new("ViewStringsPlugin · session strings from ASCII Strings analyzer")
- .color(muted),
- );
- ui.separator();
- if self.strings.is_empty() {
- ui.weak("No strings yet — run ASCII Strings analyzer.");
- return;
- }
- ui.horizontal(|ui| {
- ui.label("Filter:");
- ui.add(
- egui::TextEdit::singleline(&mut self.defined_strings_filter)
- .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 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))
- .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()
- .id_salt("defstr_scroll")
- .max_height(400.0)
- .show(ui, |ui| {
- egui::Grid::new("defined_strings_grid")
- .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, 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();
- }
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- });
- });
- }
-
- fn ui_relocation_table(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Relocation Table");
- ui.small(
- egui::RichText::new("RelocationTablePlugin · from Program::sections").color(muted),
- );
- ui.separator();
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- ui.small(
- egui::RichText::new(
- "Section metadata rendered here as a Stage-0 placeholder. Full PE reloc / ELF rela \
- parse lands in .",
- )
- .color(muted)
- .italics(),
- );
- egui::Grid::new("relocs_grid")
- .num_columns(3)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Section");
- ui.strong("VA");
- ui.strong("Size");
- ui.end_row();
- for s in &prog.sections {
- ui.label(&s.name);
- ui.monospace(format!("{:#x}", s.va));
- ui.monospace(format!("{:#x}", s.virtual_size));
- ui.end_row();
- }
- });
- }
-
- fn ui_disassembled_view_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Disassembled View");
- ui.small(egui::RichText::new("DisassembledViewPlugin · detail at cursor").color(muted));
- ui.separator();
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- let va = match self.listing_focus_va.or(prog.entry) {
- Some(v) => v,
- None => {
- ui.weak("No cursor / entry.");
- return;
- }
- };
- let arch = self.listing_arch();
- match disassemble_at_opts(prog, va, Some(&self.decode_opts.to_engine_opts())) {
- Ok(insn) => {
- ui.monospace(insn.text());
- ui.separator();
- ui_detail_pane(ui, &insn, arch);
- }
- Err(e) => {
- ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), e.to_string());
- }
- }
- }
-
- fn ui_comment_window(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Comments");
- ui.small(
- egui::RichText::new(
- "CommentWindowPlugin · shows EOL/Pre/Post/Plate/Repeatable edits + bookmarks",
- )
- .color(muted),
- );
- ui.separator();
- // Filter row — CommentWindow provides both a text filter and
- // a per-kind toggle.
- ui.horizontal(|ui| {
- ui.label("Filter:");
- ui.add(
- egui::TextEdit::singleline(&mut self.comment_window_filter)
- .desired_width(240.0)
- .hint_text("Text / address / kind…"),
- );
- ui.label("Kind:");
- let cur = self
- .comment_window_kind_filter
- .map(|k| k.label())
- .unwrap_or("All");
- egui::ComboBox::from_id_salt("comment_window_kind_combo")
- .selected_text(cur)
- .show_ui(ui, |ui| {
- ui.selectable_value(&mut self.comment_window_kind_filter, None, "All");
- for k in CommentKind::ALL {
- ui.selectable_value(
- &mut self.comment_window_kind_filter,
- Some(*k),
- k.label(),
- );
- }
- });
- });
- ui.separator();
- // Real edited comments from ProgramEdits — one row per (va, kind).
- let mut rows: Vec<(&'static str, u64, String)> = Vec::new();
- if let Some(prog) = self.program.as_ref() {
- for ((va, kind), text) in &prog.edits.comments {
- rows.push((kind.label(), *va, text.clone()));
- }
- }
- // Also surface bookmarks as "Note-derived" comment rows.
- for b in &self.bookmarks {
- let text = if b.category.is_empty() {
- b.description.clone()
- } else {
- format!("[{}] {}", b.category, b.description)
- };
- rows.push(("Bookmark", b.va, text));
- }
- // Apply filters.
- let text_filter = self.comment_window_filter.to_ascii_lowercase();
- let kind_filter = self.comment_window_kind_filter;
- rows.retain(|(kind, va, text)| {
- if let Some(want) = kind_filter {
- if *kind != want.label() {
- return false;
- }
- }
- if text_filter.is_empty() {
- return true;
- }
- let addr = format!("{va:#x}");
- text.to_ascii_lowercase().contains(&text_filter)
- || kind.to_ascii_lowercase().contains(&text_filter)
- || addr.contains(&text_filter)
- });
- if rows.is_empty() {
- ui.weak(
- "No comments/bookmarks match — set a comment with `;` on a Listing line, or add a Bookmark.",
- );
- return;
- }
- rows.sort_by_key(|(_, va, _)| *va);
- egui::ScrollArea::vertical()
- .id_salt("comment_window_scroll")
- .max_height(400.0)
- .show(ui, |ui| {
- egui::Grid::new("comments_grid")
- .num_columns(3)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Type");
- ui.strong("Address");
- ui.strong("Comment");
- ui.end_row();
- let mut goto: Option<u64> = None;
- let mut delete: Option<(u64, CommentKind)> = None;
- for (kind, va, text) in &rows {
- let color = match *kind {
- "EOL" => Color32::from_rgb(0x81, 0xC7, 0x84),
- "Pre" => Color32::from_rgb(0x64, 0xB5, 0xF6),
- "Post" => Color32::from_rgb(0xBA, 0x68, 0xC8),
- "Plate" => Color32::from_rgb(0xFF, 0xB7, 0x4D),
- "Repeatable" => Color32::from_rgb(0x4D, 0xD0, 0xE1),
- _ => Color32::from_rgb(0x9C, 0x27, 0xB0),
- };
- ui.label(egui::RichText::new(*kind).color(color).strong());
- if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
- .clicked()
- {
- goto = Some(*va);
- }
- ui.horizontal(|ui| {
- ui.label(text);
- let matching_kind = match *kind {
- "EOL" => Some(CommentKind::Eol),
- "Pre" => Some(CommentKind::Pre),
- "Post" => Some(CommentKind::Post),
- "Plate" => Some(CommentKind::Plate),
- "Repeatable" => Some(CommentKind::Repeatable),
- _ => None,
- };
- if let Some(k) = matching_kind {
- if ui.small_button("Del").clicked() {
- delete = Some((*va, k));
- }
- }
- });
- ui.end_row();
- }
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- if let Some((va, k)) = delete {
- let _ = self.set_comment_at(va, k, "");
- }
- });
- });
- }
-
- fn ui_defined_data(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Defined Data");
- ui.small(
- egui::RichText::new(
- "DataWindowPlugin · session data (Program::data_items when available)",
- )
- .color(muted),
- );
- ui.separator();
- let rtti_rows: Vec<(u64, String)> = match self.program.as_ref() {
- Some(prog) => prog
- .rtti
- .classes
- .iter()
- .take(2000)
- .filter_map(|c| c.type_info_va.map(|va| (va, c.name.clone())))
- .collect(),
- None => {
- ui.weak("No program loaded.");
- return;
- }
- };
- if self.strings.is_empty() && rtti_rows.is_empty() {
- ui.weak("No defined data (strings/RTTI) available yet — run ASCII Strings / RTTI analyzers.");
- return;
- }
- let str_rows: Vec<(u64, String)> = self
- .strings
- .iter()
- .take(2000)
- .map(|s| (s.va, s.value.chars().take(48).collect()))
- .collect();
- let mut goto: Option<u64> = None;
- egui::ScrollArea::vertical()
- .id_salt("defined_data_scroll")
- .max_height(400.0)
- .show(ui, |ui| {
- egui::Grid::new("defined_data_grid")
- .num_columns(3)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Address");
- ui.strong("Type");
- ui.strong("Preview");
- ui.end_row();
- for (va, val) in &str_rows {
- if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
- .clicked()
- {
- goto = Some(*va);
- }
- ui.monospace("string");
- ui.label(val);
- ui.end_row();
- }
- for (va, name) in &rtti_rows {
- if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
- .clicked()
- {
- goto = Some(*va);
- }
- ui.monospace("rtti");
- ui.label(name);
- ui.end_row();
- }
- });
- });
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- }
-
- // ── Byte Viewer / Symbol References / Equates / Tags ─
-
- /// ByteViewerPluginue — split hex / ASCII view of the
- /// program's memory around the current cursor. Bytes-per-line combo,
- /// programmable offset override, and click-to-navigate address column.
- fn ui_bytes_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- ui.heading("Bytes");
- ui.small(
- egui::RichText::new("ByteViewerPlugin · split hex / ASCII, follows Listing cursor")
- .color(muted),
- );
- ui.separator();
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- // Cursor tracking — default to Listing focus, editable via combo.
- if self.bytes_pane_va.is_none() {
- self.bytes_pane_va = self
- .listing_focus_va
- .or(prog.entry)
- .or_else(|| prog.blocks.first().map(|b| b.va));
- }
- let base_va = self.bytes_pane_va.unwrap_or(prog.image_base);
- ui.horizontal(|ui| {
- ui.label("VA:");
- let mut input = format!("{base_va:#x}");
- let resp = ui.add(egui::TextEdit::singleline(&mut input).desired_width(140.0));
- if resp.lost_focus() {
- if let Ok(v) = parse_address(&input) {
- self.bytes_pane_va = Some(v);
- }
- }
- ui.label("Bytes/line:");
- egui::ComboBox::from_id_salt("bytes_pane_bpr")
- .selected_text(format!("{}", self.bytes_pane_bpr))
- .show_ui(ui, |ui| {
- for w in [8usize, 12, 16, 24, 32] {
- ui.selectable_value(&mut self.bytes_pane_bpr, w, format!("{w}"));
- }
- });
- ui.label("Rows:");
- egui::ComboBox::from_id_salt("bytes_pane_rows")
- .selected_text(format!("{}", self.bytes_pane_rows))
- .show_ui(ui, |ui| {
- for r in [8usize, 16, 24, 32, 48, 64] {
- ui.selectable_value(&mut self.bytes_pane_rows, r, format!("{r}"));
- }
- });
- if ui
- .button("Follow cursor")
- .on_hover_text("Snap to Listing cursor")
- .clicked()
- {
- self.bytes_pane_va = self.listing_focus_va;
- }
- });
- ui.separator();
- let bpr = self.bytes_pane_bpr.max(1);
- let total = bpr.saturating_mul(self.bytes_pane_rows);
- let mut bytes: Vec<Option<u8>> = Vec::with_capacity(total);
- for i in 0..total {
- bytes.push(prog.byte_at(base_va.wrapping_add(i as u64)));
- }
- let focus_va = self.listing_focus_va;
- let mut nav: Option<u64> = None;
- egui::ScrollArea::vertical()
- .id_salt("bytes_scroll")
- .max_height(420.0)
- .show(ui, |ui| {
- for row in 0..self.bytes_pane_rows {
- let row_va = base_va.wrapping_add((row * bpr) as u64);
- ui.horizontal(|ui| {
- let addr = egui::RichText::new(format!("{row_va:016x}"))
- .monospace()
- .color(if Some(row_va) == focus_va {
- primary
- } else {
- ui.visuals().text_color()
- });
- if ui.link(addr).on_hover_text("Go To in Listing").clicked() {
- nav = Some(row_va);
- }
- ui.label("│");
- let mut hex_line = String::new();
- let mut ascii_line = String::new();
- for col in 0..bpr {
- let idx = row * bpr + col;
- match bytes.get(idx).and_then(|b| *b) {
- Some(b) => {
- hex_line.push_str(&format!("{b:02x} "));
- let c = if (0x20..=0x7f).contains(&b) {
- b as char
- } else {
- '.'
- };
- ascii_line.push(c);
- }
- None => {
- hex_line.push_str("?? ");
- ascii_line.push(' ');
- }
- }
- }
- ui.monospace(hex_line.trim_end());
- ui.label("│");
- ui.monospace(ascii_line);
- });
- }
- });
- if let Some(va) = nav {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- }
-
- /// `Symbol References` provider — a table of every xref pointing
- /// at the currently selected symbol (or the cursor VA).
- fn ui_symbol_references(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Symbol References");
- ui.small(
- egui::RichText::new("SymbolTablePlugin · every reference TO the current symbol")
- .color(muted),
- );
- ui.separator();
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- let target = self
- .symbol_refs_target
- .or(self.listing_focus_va)
- .or(prog.entry);
- ui.horizontal(|ui| {
- let mut input = target.map(|v| format!("{v:#x}")).unwrap_or_default();
- ui.label("Target:");
- let resp = ui.add(
- egui::TextEdit::singleline(&mut input)
- .desired_width(140.0)
- .hint_text("VA…"),
- );
- if resp.lost_focus() {
- self.symbol_refs_target = parse_address(&input).ok();
- }
- ui.label("Filter:");
- ui.add(
- egui::TextEdit::singleline(&mut self.symbol_refs_filter)
- .desired_width(200.0)
- .hint_text("Substring…"),
- );
- 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 {
- ui.weak("No target — set cursor or type a VA above.");
- return;
- };
- let refs = self.xrefs_to_va(target);
- let q = self.symbol_refs_filter.to_ascii_lowercase();
- 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() {
- return true;
- }
- r.preview.to_ascii_lowercase().contains(&q)
- || 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
- .as_ref()
- .and_then(|p| p.display_name_at(va))
- .map(|s| s.to_string())
- .unwrap_or_default()
- };
- ui.small(format!(
- "{} reference(s) to {target:#x} · {}",
- rows.len(),
- label_at(target)
- ));
- let mut goto: Option<u64> = None;
- egui::ScrollArea::vertical()
- .id_salt("symrefs_scroll")
- .max_height(400.0)
- .show(ui, |ui| {
- egui::Grid::new("symbol_refs_grid")
- .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, cls) in &rows {
- if ui
- .link(egui::RichText::new(format!("{:#x}", r.from)).monospace())
- .clicked()
- {
- goto = Some(r.from);
- }
- ui.label(label_at(r.from));
- ui.monospace(r.kind);
- ui.small(cls.as_deref().unwrap_or("—"));
- ui.label(&r.preview);
- ui.end_row();
- }
- });
- });
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- }
-
- /// `EquateTablePlugin` — two-pane: equate groups + per-equate refs.
- fn ui_equates_table(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Equates Table");
- ui.small(
- egui::RichText::new("EquateTablePlugin · symbolic names bound to scalar operands")
- .color(muted),
- );
- ui.separator();
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- let groups = prog.edits.equate_groups();
- ui.horizontal(|ui| {
- ui.label("Filter:");
- ui.add(
- egui::TextEdit::singleline(&mut self.equates_filter)
- .desired_width(220.0)
- .hint_text("Name / value…"),
- );
- if ui.button("Add equate at cursor…").clicked() {
- self.equate_dialog_va = self.listing_focus_va;
- self.equate_dialog_op = 1;
- self.equate_dialog_name.clear();
- self.equate_dialog_value.clear();
- self.show_equate_dialog = true;
- }
- });
- ui.separator();
- let q = self.equates_filter.to_ascii_lowercase();
- let filtered: Vec<(String, i64, usize)> = groups
- .into_iter()
- .filter(|(name, val, _)| {
- if q.is_empty() {
- return true;
- }
- name.to_ascii_lowercase().contains(&q) || format!("{val:#x}").contains(&q)
- })
- .collect();
- if filtered.is_empty() {
- ui.weak("No equates — use \"Add equate at cursor\" over a scalar operand.");
- return;
- }
- let mut clear: Option<(u64, u8)> = None;
- let mut goto: Option<u64> = None;
- ui.columns(2, |cols| {
- cols[0].strong("Equate");
- cols[0].separator();
- egui::ScrollArea::vertical()
- .id_salt("equates_left_scroll")
- .max_height(360.0)
- .show(&mut cols[0], |ui| {
- egui::Grid::new("equates_groups_grid")
- .num_columns(3)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Name");
- ui.strong("Value");
- ui.strong("# Refs");
- ui.end_row();
- for (name, value, n) in &filtered {
- let is_sel = self
- .equates_selected
- .as_ref()
- .map(|(sn, sv)| sn == name && *sv == *value)
- .unwrap_or(false);
- let text = if is_sel {
- egui::RichText::new(name).strong()
- } else {
- egui::RichText::new(name)
- };
- if ui.selectable_label(is_sel, text).clicked() {
- self.equates_selected = Some((name.clone(), *value));
- }
- ui.monospace(format!("{value:#x}"));
- ui.monospace(format!("{n}"));
- ui.end_row();
- }
- });
- });
- cols[1].strong("References");
- cols[1].separator();
- let sel = self.equates_selected.clone();
- let refs: Vec<(u64, u8, i64)> = match sel {
- Some((name, _)) => prog.edits.equate_references(&name),
- None => Vec::new(),
- };
- egui::ScrollArea::vertical()
- .id_salt("equates_right_scroll")
- .max_height(360.0)
- .show(&mut cols[1], |ui| {
- if refs.is_empty() {
- ui.weak("Select an equate on the left to see its references.");
- } else {
- egui::Grid::new("equate_refs_grid")
- .num_columns(4)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Ref Addr");
- ui.strong("Op");
- ui.strong("Value");
- ui.strong("Del");
- ui.end_row();
- for (va, op, value) in refs {
- if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
- .clicked()
- {
- goto = Some(va);
- }
- ui.monospace(format!("{op}"));
- ui.monospace(format!("{value:#x}"));
- if ui.small_button("Del").clicked() {
- clear = Some((va, op));
- }
- ui.end_row();
- }
- });
- }
- });
- });
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- if let Some((va, op)) = clear {
- let _ = self.set_equate(va, op, "", 0);
- }
- }
-
- /// `FunctionTagPlugin` — two-pane: assigned tags for current fn,
- /// All Tags with counts.
- fn ui_function_tags(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Function Tags");
- ui.small(
- egui::RichText::new("FunctionTagPlugin · per-function labels + universe of tags")
- .color(muted),
- );
- ui.separator();
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- let entry = self.focused_function_entry.or_else(|| {
- self.listing_focus_va
- .and_then(|va| Some(decompile_entry_for_va(prog, va)))
- });
- let entry_label = entry
- .and_then(|va| self.program.as_ref()?.display_function_name_at(va))
- .unwrap_or_else(|| "<no function>".into());
- ui.horizontal(|ui| {
- ui.label("Function:");
- ui.monospace(&entry_label);
- if let Some(e) = entry {
- ui.monospace(format!("@ {e:#x}"));
- }
- });
- ui.separator();
- // Left = assigned tags (with remove); right = all tags (add / delete).
- let assigned: Vec<String> = entry
- .map(|e| prog.edits.function_tags_for(e))
- .unwrap_or_default();
- let all_tags: Vec<(String, usize)> = prog.edits.all_tag_counts();
- let mut remove_from_entry: Option<String> = None;
- let mut add_to_entry: Option<String> = None;
- let mut delete_globally: Option<String> = None;
- ui.columns(2, |cols| {
- cols[0].strong("Assigned to this function");
- cols[0].separator();
- if assigned.is_empty() {
- cols[0].weak("No tags — add one from the right pane, or type a new tag.");
- } else {
- for t in &assigned {
- cols[0].horizontal(|ui| {
- ui.monospace(t);
- if ui.small_button("Remove").clicked() {
- remove_from_entry = Some(t.clone());
- }
- });
- }
- }
-
- cols[1].strong("All Tags");
- cols[1].separator();
- cols[1].horizontal(|ui| {
- ui.label("New:");
- ui.add(
- egui::TextEdit::singleline(&mut self.function_tags_new_input)
- .desired_width(160.0)
- .hint_text("Tag name…"),
- );
- if ui.button("Add").clicked() {
- let name = self.function_tags_new_input.trim().to_string();
- if !name.is_empty() {
- if entry.is_some() {
- add_to_entry = Some(name);
- } else {
- let _ = self.create_tag(name);
- }
- self.function_tags_new_input.clear();
- }
- }
- });
- cols[1].horizontal(|ui| {
- ui.label("Filter:");
- ui.add(
- egui::TextEdit::singleline(&mut self.function_tags_filter)
- .desired_width(180.0)
- .hint_text("Substring…"),
- );
- });
- cols[1].separator();
- let q = self.function_tags_filter.to_ascii_lowercase();
- egui::ScrollArea::vertical()
- .id_salt("all_tags_scroll")
- .max_height(320.0)
- .show(&mut cols[1], |ui| {
- egui::Grid::new("all_tags_grid")
- .num_columns(3)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Tag");
- ui.strong("Uses");
- ui.strong("Actions");
- ui.end_row();
- for (tag, n) in &all_tags {
- if !q.is_empty() && !tag.to_ascii_lowercase().contains(&q) {
- continue;
- }
- ui.monospace(tag);
- ui.monospace(format!("{n}"));
- ui.horizontal(|ui| {
- if entry.is_some() && ui.small_button("Add").clicked() {
- add_to_entry = Some(tag.clone());
- }
- if ui.small_button("Delete").clicked() {
- delete_globally = Some(tag.clone());
- }
- });
- ui.end_row();
- }
- });
- });
- });
- if let (Some(tag), Some(e)) = (remove_from_entry, entry) {
- let _ = self.remove_function_tag(e, &tag);
- }
- if let (Some(tag), Some(e)) = (add_to_entry, entry) {
- let _ = self.add_function_tag(e, tag);
- }
- if let Some(tag) = delete_globally {
- let _ = self.delete_tag_everywhere(&tag);
- }
- }
-
- /// `ReferencesPlugin` — External Programs table. Rendered from
- /// analyzer-driven `imports_exports` output (PDB symbols, `idata`
- /// sections, demangled `dllexport` symbols) — never fabricated.
- fn ui_external_programs(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("External Programs");
- ui.small(
- egui::RichText::new("ReferencesPlugin · analyzer-derived imports + exports")
- .color(muted),
- );
- ui.separator();
- if self.program.is_none() {
- ui.weak("No program loaded.");
- return;
- }
- let (imports, exports) = self.imports_exports();
- ui.horizontal(|ui| {
- ui.label("Filter:");
- ui.add(
- egui::TextEdit::singleline(&mut self.external_programs_filter)
- .desired_width(220.0)
- .hint_text("Name / VA…"),
- );
- });
- ui.separator();
- let q = self.external_programs_filter.to_ascii_lowercase();
- let matches = |name: &str, va: u64| {
- if q.is_empty() {
- return true;
- }
- name.to_ascii_lowercase().contains(&q) || format!("{va:#x}").contains(&q)
- };
- let mut goto: Option<u64> = None;
- egui::ScrollArea::vertical()
- .id_salt("ext_progs_scroll")
- .max_height(400.0)
- .show(ui, |ui| {
- ui.strong("Imports");
- egui::Grid::new("ext_imports_grid")
- .num_columns(3)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Address");
- ui.strong("Name");
- ui.strong("Source");
- ui.end_row();
- for (va, name) in imports.iter().filter(|(va, n)| matches(n, *va)) {
- if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
- .clicked()
- {
- goto = Some(*va);
- }
- ui.label(name);
- ui.monospace(if name.starts_with('.') {
- "section"
- } else {
- "pdb"
- });
- ui.end_row();
- }
- });
- ui.add_space(8.0);
- ui.strong("Exports");
- egui::Grid::new("ext_exports_grid")
- .num_columns(3)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Address");
- ui.strong("Name");
- ui.strong("Source");
- ui.end_row();
- for (va, name) in exports.iter().filter(|(va, n)| matches(n, *va)) {
- if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
- .clicked()
- {
- goto = Some(*va);
- }
- ui.label(name);
- ui.monospace(if name.starts_with('.') {
- "section"
- } else {
- "demangle"
- });
- ui.end_row();
- }
- if imports.is_empty() && exports.is_empty() {
- ui.weak("No imports/exports — analyzer did not populate any.");
- ui.end_row();
- }
- });
- });
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- }
-
- /// `DataTypePreviewPlugin` — preview interpretation of bytes at
- /// the current cursor under the chosen built-in type.
- fn ui_data_type_preview(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Data Type Preview");
- ui.small(
- egui::RichText::new("DataTypePreviewPlugin · byte interpretation @ cursor")
- .color(muted),
- );
- ui.separator();
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- let va = match self.listing_focus_va.or(prog.entry) {
- Some(v) => v,
- None => {
- ui.weak("No cursor / entry.");
- return;
- }
- };
- ui.horizontal(|ui| {
- ui.label("Cursor VA:");
- ui.monospace(format!("{va:#x}"));
- ui.label("Type:");
- let sel = self.data_type_preview_selected.clone();
- egui::ComboBox::from_id_salt("dtp_type_combo")
- .selected_text(&sel)
- .show_ui(ui, |ui| {
- for name in BUILTIN_TYPES {
- if ui.selectable_label(sel.as_str() == *name, *name).clicked() {
- self.data_type_preview_selected = (*name).into();
- }
- }
- });
- });
- ui.separator();
- let bytes = prog.read_va(va, 16).unwrap_or_default();
- let hex: String = bytes.iter().map(|b| format!("{b:02x} ")).collect();
- ui.monospace(format!("bytes: {}", hex.trim_end()));
- ui.separator();
- egui::Grid::new("dtp_grid")
- .num_columns(2)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Interpretation");
- ui.strong("Preview");
- ui.end_row();
- for (name, preview) in preview_all(&bytes) {
- ui.monospace(name);
- ui.monospace(preview);
- ui.end_row();
- }
- });
- }
-
- /// `ComputeChecksumsPlugin` — CRC-32 / Adler-32 / Fletcher / raw
- /// sum panels over the loaded image or a chosen block.
- fn ui_checksum_generator(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Checksum Generator");
- ui.small(
- egui::RichText::new("ComputeChecksumsPlugin · CRC-32 / Adler-32 / Fletcher / sums")
- .color(muted),
- );
- ui.separator();
- let block_names: Vec<String> = self
- .program
- .as_ref()
- .map(|p| p.blocks.iter().map(|b| b.name.clone()).collect())
- .unwrap_or_default();
- let mut run: Option<ChecksumMode> = None;
- ui.horizontal(|ui| {
- if ui.button("Whole image").clicked() {
- run = Some(ChecksumMode::WholeImage);
- }
- ui.label(egui::RichText::new("or block:").color(muted));
- for name in &block_names {
- if ui.small_button(name).clicked() {
- run = Some(ChecksumMode::Section(name.clone()));
- }
- }
- });
- if let Some(mode) = run {
- let _ = self.compute_checksums(mode);
- }
- ui.separator();
- match &self.checksum_last {
- None => {
- ui.weak("No checksum computed yet — click Whole image or a block above.");
- }
- Some(r) => {
- egui::Grid::new("checksum_grid")
- .num_columns(2)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Target");
- ui.label(&r.target);
- ui.end_row();
- ui.strong("Length");
- ui.monospace(format!("{}", r.len));
- ui.end_row();
- ui.strong("CRC-32 (IEEE)");
- ui.monospace(format!("{:#010x}", r.crc32));
- ui.end_row();
- ui.strong("Adler-32");
- ui.monospace(format!("{:#010x}", r.adler32));
- ui.end_row();
- ui.strong("Sum-8");
- ui.monospace(format!("{:#x}", r.sum8));
- ui.end_row();
- ui.strong("Sum-16");
- ui.monospace(format!("{:#x}", r.sum16));
- ui.end_row();
- ui.strong("Sum-32");
- ui.monospace(format!("{:#x}", r.sum32));
- ui.end_row();
- ui.strong("Fletcher-16");
- ui.monospace(format!("{:#010x}", r.fletcher16));
- ui.end_row();
- ui.strong("Fletcher-32");
- ui.monospace(format!("{:#018x}", r.fletcher32));
- ui.end_row();
- });
- }
- }
- }
-}
-
-/// Data Type Preview — every well-known Stage-0 interpretation of `bytes`.
-fn preview_all(bytes: &[u8]) -> Vec<(&'static str, String)> {
- let mut out = Vec::new();
- if let Some(&b) = bytes.first() {
- out.push(("int8", format!("{}", b as i8)));
- out.push(("uint8", format!("{}", b)));
- }
- if bytes.len() >= 2 {
- let w = u16::from_le_bytes([bytes[0], bytes[1]]);
- out.push(("int16", format!("{}", w as i16)));
- out.push(("uint16", format!("{w} ({w:#x})")));
- }
- if bytes.len() >= 4 {
- let d = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
- out.push(("int32", format!("{}", d as i32)));
- out.push(("uint32", format!("{d} ({d:#x})")));
- out.push(("float", format!("{}", f32::from_bits(d))));
- }
- if bytes.len() >= 8 {
- let q = u64::from_le_bytes([
- bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
- ]);
- out.push(("int64", format!("{}", q as i64)));
- out.push(("uint64", format!("{q} ({q:#x})")));
- out.push(("double", format!("{}", f64::from_bits(q))));
- out.push(("pointer64", format!("{q:#018x}")));
- }
- let ascii: String = bytes
- .iter()
- .take(16)
- .map(|b| {
- if (0x20..=0x7f).contains(b) {
- *b as char
- } else {
- '.'
- }
- })
- .collect();
- out.push(("ascii", ascii));
- out
-}
-
-impl eframe::App for GhidrustApp {
- fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
- self.apply_theme(ctx);
-
- // drain event bus once per frame and fan out.
- self.drain_events();
-
- // Startup: choose project before the empty shell
- if self.show_startup_picker {
- self.ui_startup_picker(ctx);
- return;
- }
-
- // Poll background analysis worker; keep repainting so progress UI stays live.
- if self.analysis_job.is_some() {
- if let Err(e) = self.step_analysis_job() {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- self.analysis_job = None;
- set_preferred_bulk_mode(BulkScanMode::ParallelCpu);
- }
- ctx.request_repaint();
- }
-
- egui::TopBottomPanel::top("menubar").show(ctx, |ui| {
- egui::menu::bar(ui, |ui| {
- ui.menu_button("File", |ui| {
- if ui.button("New Project…").clicked() {
- self.browse_and_create_project();
- ui.close_menu();
- }
- if ui.button("Open Project…").clicked() {
- self.browse_and_open_project();
- ui.close_menu();
- }
- ui.separator();
- if ui.button("Import binary into project…").clicked() {
- self.browse_and_import();
- ui.close_menu();
- }
- if ui.button("Open / Load binary…").clicked() {
- self.browse_and_load_binary();
- ui.close_menu();
- }
- if ui
- .button("Add To Program…")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("File → Add To Program");
- ui.close_menu();
- }
- if ui
- .button("Batch Import…")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("File → Batch Import");
- ui.close_menu();
- }
- ui.separator();
- if ui.button("Save analysis results…").clicked() {
- if let Err(e) = self.save_results() {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- ui.close_menu();
- }
- if ui
- .button("Save As…")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("File → Save As");
- ui.close_menu();
- }
- if ui
- .button("Export Program…")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("File → Export Program");
- ui.close_menu();
- }
- ui.separator();
- if ui
- .button("Load PDB File…")
- .on_hover_text("Not yet implemented — PDB load UI")
- .clicked()
- {
- self.nyi("File → Load PDB File");
- ui.close_menu();
- }
- if ui
- .button("Parse C Source…")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("File → Parse C Source");
- ui.close_menu();
- }
- ui.separator();
- if ui
- .button("Configure…")
- .on_hover_text("Plugin picker — not yet implemented")
- .clicked()
- {
- self.nyi("File → Configure");
- ui.close_menu();
- }
- if ui
- .button("Print…")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("File → Print");
- ui.close_menu();
- }
- ui.separator();
- if ui.button("Close program").clicked() {
- self.program = None;
- self.listing.clear();
- self.active_file_id = None;
- self.status = "Program closed".into();
- ui.close_menu();
- }
- if ui.button("Exit").clicked() {
- ctx.send_viewport_cmd(egui::ViewportCommand::Close);
- }
- });
- ui.menu_button("Edit", |ui| {
- if ui.button("Undo").clicked() {
- self.edit_undo();
- ui.close_menu();
- }
- if ui.button("Redo").clicked() {
- self.edit_redo();
- ui.close_menu();
- }
- if ui.button("Clear selection").clicked() {
- self.edit_clear_selection();
- ui.close_menu();
- }
- ui.separator();
- if ui
- .button("Tool Options…")
- .on_hover_text("Options tree — not yet implemented")
- .clicked()
- {
- self.nyi("Edit → Tool Options");
- ui.close_menu();
- }
- if ui
- .button("Options for program…")
- .on_hover_text("Program-level options — not yet implemented")
- .clicked()
- {
- self.nyi("Edit → Options for program");
- ui.close_menu();
- }
- if ui
- .button("Plugin Path…")
- .on_hover_text("Configure plugin paths — not yet implemented")
- .clicked()
- {
- self.nyi("Edit → Plugin Path");
- ui.close_menu();
- }
- if ui
- .button("Key Bindings…")
- .on_hover_text("Rebind actions — not yet implemented")
- .clicked()
- {
- self.nyi("Edit → Key Bindings");
- ui.close_menu();
- }
- });
- ui.menu_button("Analysis", |ui| {
- if ui.button("Auto Analyze…").clicked() {
- self.pending_analyze_file_id = None;
- self.show_analysis_dialog = true;
- ui.close_menu();
- }
- if ui.button("Run selected analyzers").clicked() {
- self.pending_analyze_file_id = None;
- self.show_analysis_dialog = true;
- ui.close_menu();
- }
- if ui
- .button("Analyze All Open…")
- .on_hover_text("Multi-program batch — not yet implemented")
- .clicked()
- {
- self.nyi("Analysis → Analyze All Open");
- ui.close_menu();
- }
- ui.separator();
- ui.menu_button("One Shot Analysis", |ui| {
- // Enumerate analyzers as sub-menu items (mirrors One-Shot).
- // Clicking pre-selects that analyzer and opens the dialog.
- let analyzer_names: Vec<String> =
- self.analyzer_infos.iter().map(|a| a.name.clone()).collect();
- let mut chosen: Option<String> = None;
- for name in &analyzer_names {
- if ui.button(name).clicked() {
- chosen = Some(name.clone());
- }
- }
- if let Some(name) = chosen {
- for (i, info) in self.analyzer_infos.iter().enumerate() {
- self.analyzer_enabled[i] = info.name == name;
- }
- self.pending_analyze_file_id = None;
- self.show_analysis_dialog = true;
- self.status = format!("One Shot: {name}");
- self.log(self.status.clone());
- 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()
- {
- self.nav_back();
- ui.close_menu();
- }
- if ui
- .add_enabled(self.can_nav_forward(), egui::Button::new("Forward"))
- .clicked()
- {
- self.nav_forward();
- ui.close_menu();
- }
- ui.separator();
- if ui.button("Go to entry").clicked() {
- self.goto_entry();
- ui.close_menu();
- }
- if ui.button("Go to address…").clicked() {
- if let Some(prog) = &self.program {
- if let Some(e) = prog.entry {
- self.goto_input = format!("{e:#x}");
- } else {
- self.goto_input = format!("{:#x}", prog.image_base);
- }
- }
- self.show_goto_dialog = true;
- ui.close_menu();
- }
- ui.separator();
- if ui.button("Next Function (Ctrl+Down)").clicked() {
- self.nav_next_function();
- ui.close_menu();
- }
- if ui.button("Previous Function (Ctrl+Up)").clicked() {
- self.nav_prev_function();
- ui.close_menu();
- }
- if ui
- .button("Next Data")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Navigation → Next Data");
- ui.close_menu();
- }
- if ui
- .button("Next Undefined")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Navigation → Next Undefined");
- ui.close_menu();
- }
- if ui.button("Next Bookmark").clicked() {
- self.nav_next_bookmark();
- ui.close_menu();
- }
- if ui.button("Previous Bookmark").clicked() {
- self.nav_prev_bookmark();
- ui.close_menu();
- }
- });
- ui.menu_button("Search", |ui| {
- if ui.button("Search memory…").clicked() {
- self.show_search_memory_dialog = true;
- ui.close_menu();
- }
- if ui.button("Search program text…").clicked() {
- self.show_search_text_dialog = true;
- ui.close_menu();
- }
- ui.separator();
- if ui
- .button("For Strings…")
- .on_hover_text("Opens Defined Strings — session strings")
- .clicked()
- {
- self.pane_open.insert(PaneKind::DefinedStrings, true);
- ui.close_menu();
- }
- if ui.button("For Crypto Constants…").clicked() {
- self.decrypt_pane.focus(DecryptTab::Constants);
- self.pane_open.insert(PaneKind::Decrypt, true);
- ui.close_menu();
- }
- if ui.button("For Recovered Strings…").clicked() {
- self.decrypt_pane.focus(DecryptTab::Strings);
- self.pane_open.insert(PaneKind::Decrypt, true);
- ui.close_menu();
- }
- if ui.button("For Crypto Capabilities…").clicked() {
- self.decrypt_pane.focus(DecryptTab::Capabilities);
- self.pane_open.insert(PaneKind::Decrypt, true);
- ui.close_menu();
- }
- if ui
- .button("Decrypt…")
- .on_hover_text("Open Decrypt pane on listing selection")
- .clicked()
- {
- if let Some(va) = self.listing_focus_va {
- self.open_decrypt_at(va, None);
- } else {
- self.pane_open.insert(PaneKind::Decrypt, true);
- }
- ui.close_menu();
- }
- if ui
- .button("For Scalars…")
- .on_hover_text("ScalarSearchPlugin · operand scalar range filter")
- .clicked()
- {
- self.show_search_scalars_dialog = true;
- ui.close_menu();
- }
- if ui
- .button("For Address Tables…")
- .on_hover_text("AutoTableDisassemblerPlugin · pointer table candidates")
- .clicked()
- {
- self.show_search_address_tables_dialog = true;
- // Populate immediately from analyzer output.
- if let Some(prog) = self.program.as_ref() {
- self.text_hits = address_table_hits(prog);
- self.memory_hits.clear();
- self.show_search_results = true;
- }
- ui.close_menu();
- }
- if ui
- .button("Instruction Patterns…")
- .on_hover_text("BytePatternPlugin · mnemonic + operand filter")
- .clicked()
- {
- self.show_search_insn_dialog = true;
- ui.close_menu();
- }
- if ui
- .button("For Direct References…")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Search → For Direct References");
- ui.close_menu();
- }
- if ui
- .button("For Matching Instructions…")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Search → For Matching Instructions");
- ui.close_menu();
- }
- if ui
- .button("Repeat Search")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Search → Repeat Search");
- ui.close_menu();
- }
- });
- ui.menu_button("Select", |ui| {
- if ui.button("All").clicked() {
- self.select_all_listing();
- ui.close_menu();
- }
- if ui
- .button("All in View")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Select → All in View");
- ui.close_menu();
- }
- if ui.button("Clear").clicked() {
- self.edit_clear_selection();
- ui.close_menu();
- }
- if ui
- .button("Complement")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Select → Complement");
- ui.close_menu();
- }
- ui.separator();
- if ui
- .button("Bytes")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Select → Bytes");
- ui.close_menu();
- }
- if ui
- .button("Instructions")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Select → Instructions");
- ui.close_menu();
- }
- if ui
- .button("Data")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Select → Data");
- ui.close_menu();
- }
- if ui
- .button("Undefined")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Select → Undefined");
- ui.close_menu();
- }
- if ui
- .button("Function")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Select → Function");
- ui.close_menu();
- }
- if ui
- .button("Subroutine")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Select → Subroutine");
- ui.close_menu();
- }
- if ui
- .button("Forward Refs")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Select → Forward Refs");
- ui.close_menu();
- }
- if ui
- .button("Backward Refs")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Select → Backward Refs");
- ui.close_menu();
- }
- ui.separator();
- if ui
- .button("Create Table From Selection")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Select → Create Table From Selection");
- ui.close_menu();
- }
- });
- ui.menu_button("Tools", |ui| {
- if ui.button("Processor options…").clicked() {
- self.show_processor_dialog = true;
- ui.close_menu();
- }
- if ui
- .button("Compare Program…")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Tools → Compare Program");
- ui.close_menu();
- }
- if ui
- .button("Program Differences…")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Tools → Program Differences");
- ui.close_menu();
- }
- if ui
- .button("Generate Checksum…")
- .on_hover_text("Opens Checksum Generator")
- .clicked()
- {
- self.pane_open.insert(PaneKind::ChecksumGenerator, true);
- ui.close_menu();
- }
- if ui
- .button("Function Bit Patterns Explorer")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Tools → Function Bit Patterns Explorer");
- ui.close_menu();
- }
- if ui
- .button("Instruction Table")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Tools → Instruction Table");
- ui.close_menu();
- }
- if ui
- .button("Processor Manual…")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Tools → Processor Manual");
- ui.close_menu();
- }
- });
- ui.menu_button("Graph", |ui| {
- if ui.button("Function Graph").clicked() {
- self.pane_open.insert(PaneKind::FunctionGraph, true);
- ui.close_menu();
- }
- if ui.button("Function Call Graph").clicked() {
- self.pane_open.insert(PaneKind::FunctionCallGraph, true);
- ui.close_menu();
- }
- if ui.button("Function Call Trees").clicked() {
- self.pane_open.insert(PaneKind::FunctionCallTrees, true);
- ui.close_menu();
- }
- ui.separator();
- if ui
- .button("Block Flow")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Graph → Block Flow");
- ui.close_menu();
- }
- if ui
- .button("Code Flow")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Graph → Code Flow");
- ui.close_menu();
- }
- if ui
- .button("Calls")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Graph → Calls");
- ui.close_menu();
- }
- if ui
- .button("Data Flow")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Graph → Data Flow");
- ui.close_menu();
- }
- });
- ui.menu_button("Window", |ui| {
- // Docked panels (long-standing).
- ui.label(egui::RichText::new("Docked").small().weak());
- ui.checkbox(&mut self.show_project_tree, "Project Tree (dock)");
- ui.checkbox(&mut self.show_program_tree, "Program Tree (dock)");
- ui.checkbox(&mut self.show_symbol_tree, "Symbol Tree (dock)");
- ui.checkbox(&mut self.show_console, "Console (dock)");
- ui.separator();
- // Center dock tabs (Listing/Decompiler prefer side-by-side).
- ui.label(egui::RichText::new("Center Tabs").small().weak());
- 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 provider catalog (floating windows).
- // Sorted alphabetically by title to mirror Window menu.
- ui.label(
- egui::RichText::new("All Providers (catalog)")
- .small()
- .weak(),
- );
- let mut providers: Vec<PaneKind> = PaneKind::ALL.to_vec();
- providers.sort_by_key(|k| k.title());
- for k in providers {
- // Skip providers that are already covered by a dock/checkbox above
- // to avoid double-toggles (Project/Program/Symbol Tree, Console).
- if matches!(
- k,
- PaneKind::ProjectTree
- | PaneKind::ProgramTree
- | PaneKind::SymbolTree
- | PaneKind::Console
- | PaneKind::Overview
- | PaneKind::Listing
- | PaneKind::DecompiledView
- | PaneKind::DataTypeManager
- ) {
- continue;
- }
- let mut open = self.is_pane_open(k);
- if ui.checkbox(&mut open, k.title()).changed() {
- self.toggle_pane(k, open);
- }
- }
- ui.separator();
- // Single tabbed Debugger host.
- ui.label(egui::RichText::new("Debugger tool").small().weak());
- let mut dbg_open = self.debugger.host_open;
- if ui.checkbox(&mut dbg_open, "Debugger").changed() {
- self.debugger.host_open = dbg_open;
- if dbg_open {
- self.debugger.enabled = true;
- if self.debugger.process_list_cache.is_empty() {
- self.debugger.refresh_process_list();
- }
- }
- }
- if self.debugger.host_open {
- ui.indent("dbg_tab_focus", |ui| {
- for p in DebuggerPane::TAB_ORDER {
- let selected = self.debugger.active_tab == *p;
- if ui.selectable_label(selected, p.short_title()).clicked() {
- self.debugger.focus_tab(*p);
- }
- }
- });
- }
- ui.separator();
- // layout tools.
- if ui.button("Configure plugins…").clicked() {
- self.show_configure_dialog = true;
- ui.close_menu();
- }
- if ui.button("Save Tool Layout…").clicked() {
- self.layouts_cached = layouts::list_layouts();
- self.layouts_new_name = self.current_layout_name.clone();
- self.show_layouts_dialog = true;
- ui.close_menu();
- }
- });
- ui.menu_button("Debugger", |ui| {
- for act in DebuggerAction::ALL {
- let hover = match act {
- DebuggerAction::Launch => {
- "CreateProcess CREATE_SUSPENDED + read-only session, then Resume (not a debug break-at-entry)"
- }
- DebuggerAction::Attach => {
- "Open Debugger on Targets and refresh the process list"
- }
- DebuggerAction::Disconnect => {
- "Detach the live process session (read-only bridge)"
- }
- DebuggerAction::ShowWatches => "Open Debugger → Watches tab",
- DebuggerAction::ToggleBreakpoint => {
- "Toggle a session-only breakpoint at the listing VA"
- }
- _ => "Debugger live backend not yet wired",
- };
- if ui.button(act.label()).on_hover_text(hover).clicked() {
- match act {
- DebuggerAction::Launch => {
- let prefill = {
- let p = self.path_input.trim();
- if !p.is_empty() && std::path::Path::new(p).is_file() {
- Some(std::path::PathBuf::from(p))
- } else {
- None
- }
- };
- self.debugger.open_launch_ui(prefill.as_deref());
- }
- DebuggerAction::Attach => {
- self.debugger.open_attach_ui();
- }
- DebuggerAction::Disconnect => {
- self.debugger.detach_session();
- }
- DebuggerAction::ShowWatches => {
- self.debugger.focus_tab(DebuggerPane::Watches);
- }
- DebuggerAction::ToggleBreakpoint => {
- if let Some(va) = self.listing_focus_va {
- self.debugger.toggle_breakpoint(va);
- self.debugger.focus_tab(DebuggerPane::Breakpoints);
- } else {
- self.nyi("Debugger → Toggle Breakpoint (no listing VA)");
- }
- }
- DebuggerAction::Continue
- | DebuggerAction::Interrupt
- | DebuggerAction::StepInto
- | DebuggerAction::StepOver
- | DebuggerAction::StepOut => {
- self.nyi(&format!("Debugger → {}", act.label()));
- }
- }
- ui.close_menu();
- }
- }
- ui.separator();
- let mut enabled = self.debugger.enabled;
- if ui.checkbox(&mut enabled, "Debugger tool mode").changed() {
- if enabled {
- self.debugger.enable_tool();
- } else {
- self.debugger.enabled = false;
- self.debugger.host_open = false;
- }
- }
- });
- ui.menu_button("Help", |ui| {
- if ui
- .button("Contents (F1)")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Help → Contents");
- ui.close_menu();
- }
- if ui
- .button("Help On…")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Help → Help On");
- ui.close_menu();
- }
- if ui
- .button("API Help")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Help → API Help");
- ui.close_menu();
- }
- if ui
- .button("User Preferences")
- .on_hover_text("Not yet implemented")
- .clicked()
- {
- self.nyi("Help → User Preferences");
- ui.close_menu();
- }
- if ui
- .button("Show Log")
- .on_hover_text("Console pane is open")
- .clicked()
- {
- self.show_console = true;
- ui.close_menu();
- }
- ui.separator();
- if ui.button("About Ghidrust").clicked() {
- self.status = format!(
- "Ghidrust {} — Rust RE toolkit (CodeBrowser shell)",
- env!("CARGO_PKG_VERSION")
- );
- self.log(self.status.clone());
- ui.close_menu();
- }
- if ui.button("Roadmap…").clicked() {
- self.log("See local development notes under dev/");
- ui.close_menu();
- }
- });
-
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- let label = match self.theme {
- ThemeMode::Dark => "Theme: Dark",
- ThemeMode::Light => "Theme: Light",
- };
- if ui.button(label).clicked() {
- self.theme = self.theme.toggle();
- self.apply_theme(ctx);
- self.log(format!("Theme → {:?}", self.theme));
- }
- });
- });
- });
-
- // Listing hotkeys run *after* the Grok dock paints (see below) so the
- // TUI can claim focus/keys first — otherwise `G` opens Go To while typing.
-
- egui::TopBottomPanel::top("nav_toolbar").show(ctx, |ui| {
- ui.horizontal(|ui| {
- let back_enabled = self.can_nav_back();
- let fwd_enabled = self.can_nav_forward();
- if ui
- .add_enabled(back_enabled, egui::Button::new("<- Back"))
- .on_hover_text("Navigation → Back (Alt+Left)")
- .clicked()
- {
- self.nav_back();
- }
- if ui
- .add_enabled(fwd_enabled, egui::Button::new("Forward ->"))
- .on_hover_text("Navigation → Forward (Alt+Right)")
- .clicked()
- {
- self.nav_forward();
- }
- ui.separator();
- if ui
- .button("Go To…")
- .on_hover_text("Navigation → Go To Address (G)")
- .clicked()
- {
- if let Some(prog) = &self.program {
- if let Some(e) = prog.entry {
- self.goto_input = format!("{e:#x}");
- } else {
- self.goto_input = format!("{:#x}", prog.image_base);
- }
- }
- self.show_goto_dialog = true;
- }
- ui.separator();
- if ui
- .button("Bookmark…")
- .on_hover_text("Add bookmark at cursor VA")
- .clicked()
- {
- if let Some(va) = self.listing_focus_va {
- self.bookmark_dialog_kind = BookmarkKind::Note;
- self.bookmark_dialog_category = String::new();
- self.bookmark_dialog_description = format!("bookmark @ {va:#x}");
- self.show_bookmark_dialog = true;
- } else {
- self.status = "No cursor VA — click a Listing line first".into();
- self.log(self.status.clone());
- }
- }
- if ui
- .button("Bookmarks")
- .on_hover_text("Window → Bookmarks")
- .clicked()
- {
- self.pane_open.insert(PaneKind::Bookmarks, true);
- }
- if ui
- .button("Functions")
- .on_hover_text("Window → Functions")
- .clicked()
- {
- self.pane_open.insert(PaneKind::FunctionsWindow, true);
- }
- if ui
- .button("Memory Map")
- .on_hover_text("Window → Memory Map")
- .clicked()
- {
- self.pane_open.insert(PaneKind::MemoryMap, true);
- }
- if ui
- .button("Symbol Table")
- .on_hover_text("Window → Symbol Table")
- .clicked()
- {
- self.pane_open.insert(PaneKind::SymbolTable, true);
- }
- ui.separator();
- let hist = format!(
- "Back: {} · Forward: {}",
- self.nav_history.len_back(),
- self.nav_history.len_forward()
- );
- ui.small(hist);
- });
- });
-
- egui::TopBottomPanel::top("toolbar").show(ctx, |ui| {
- ui.horizontal(|ui| {
- ui.label("Project dir:");
- ui.add(
- egui::TextEdit::singleline(&mut self.project_dir_input)
- .desired_width(240.0)
- .hint_text("folder for New/Open project"),
- );
- if ui
- .button("Browse…")
- .on_hover_text("Choose project folder")
- .clicked()
- {
- self.browse_project_dir();
- }
- ui.label("Name:");
- ui.add(
- egui::TextEdit::singleline(&mut self.project_name_input).desired_width(100.0),
- );
- if ui
- .button("New")
- .on_hover_text("Create project (browse if dir empty)")
- .clicked()
- {
- if self.project_dir_input.trim().is_empty() {
- self.browse_and_create_project();
- } else if let Err(e) = self.create_project() {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- if ui
- .button("Open")
- .on_hover_text("Open project (browse if dir empty)")
- .clicked()
- {
- if self.project_dir_input.trim().is_empty() {
- self.browse_and_open_project();
- } else if let Err(e) = self.open_project() {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- });
- ui.horizontal(|ui| {
- ui.label("Binary:");
- ui.add(
- egui::TextEdit::singleline(&mut self.path_input)
- .desired_width(320.0)
- .hint_text("PE/ELF — or use Browse"),
- );
- if ui
- .button("Browse…")
- .on_hover_text("Choose binary file")
- .clicked()
- {
- self.browse_binary_path();
- }
- if ui
- .button("Import")
- .on_hover_text("Import into project (browse if empty)")
- .clicked()
- {
- if self.path_input.trim().is_empty() {
- self.browse_and_import();
- } else if let Err(e) = self.import_into_project() {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- if ui
- .button("Load")
- .on_hover_text("Load binary without project (browse if empty)")
- .clicked()
- {
- if self.path_input.trim().is_empty() {
- self.browse_and_load_binary();
- } else {
- let p = self.path_input.clone();
- if let Err(e) = self.load_binary(p) {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- }
- if ui
- .button("Analyze…")
- .on_hover_text("Open analysis options (analyzers + GPU)")
- .clicked()
- {
- self.pending_analyze_file_id = self.active_file_id.clone();
- self.show_analysis_dialog = true;
- }
- if ui.button("Save").clicked() {
- if let Err(e) = self.save_results() {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- });
- let file_chips: Vec<(String, String, String)> = self
- .project
- .as_ref()
- .map(|p| {
- let pname = p.meta.name.clone();
- let files = p
- .meta
- .files
- .iter()
- .map(|f| (f.id.clone(), f.display_name.clone()))
- .collect::<Vec<_>>();
- files
- .into_iter()
- .map(|(id, name)| (pname.clone(), id, name))
- .collect()
- })
- .unwrap_or_default();
- if !file_chips.is_empty() {
- let pname = file_chips[0].0.clone();
- ui.horizontal(|ui| {
- ui.label(format!("Open: {pname} | files:"));
- for (_, id, name) in &file_chips {
- let selected = self.active_file_id.as_deref() == Some(id.as_str());
- if ui.selectable_label(selected, name).clicked() {
- if let Err(e) = self.open_project_file(id) {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- }
- });
- }
- });
-
- egui::TopBottomPanel::bottom("status").show(ctx, |ui| {
- if let Some(frac) = self.analysis_progress_fraction() {
- let t = m3_tokens(self.theme);
- let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
- let track = Color32::from_rgb(
- t.surface_container[0],
- t.surface_container[1],
- t.surface_container[2],
- )
- .gamma_multiply(1.4);
- let (label, pct) = self
- .analysis_job
- .as_ref()
- .map(|j| {
- let n = j.names.len().max(1);
- let cur = j
- .names
- .get(j.index)
- .cloned()
- .unwrap_or_else(|| "finishing…".into());
- (
- format!(
- "Analyzing {} — {}/{} {cur}{}",
- j.file_label,
- (j.index + 1).min(n),
- n,
- if j.use_gpu {
- " · GPU experimental"
- } else {
- ""
- }
- ),
- (frac * 100.0) as u32,
- )
- })
- .unwrap_or_else(|| ("Analyzing…".into(), 0));
- ui.label(egui::RichText::new(label).color(primary));
- m3_linear_progress(ui, frac, primary, track);
- ui.small(format!("{pct}%"));
- } else {
- ui.horizontal(|ui| {
- ui.label(&self.status);
- if let Some(n) = &self.nyi_note {
- ui.separator();
- ui.weak(n);
- }
- });
- }
- });
-
- // Bottom dock: tabbed (Grok primary + Console + Raw). The plain
- // analyzer / script log is never hidden — it just moves under the
- // "Console" tab. Grok is the default active tab so an RE opens the
- // app and starts typing to the agent immediately.
- //
- // Explicit min/max/default heights are required for the top-edge
- // resize gizmo to be draggable freely — without them egui pins the
- // panel to `default_height` and the drag handle becomes a 4px sliver
- // that's easy to miss.
- if self.show_console {
- // Detect Grok TUI child exit before paint.
- self.grok_pane.poll();
- let screen_h = ctx.screen_rect().height();
- // Own the height ourselves + paint a real drag grip. Built-in
- // `resizable(true)` on TopBottomPanel is unreliable here (snaps
- // back when content doesn't expand — egui #581 / 0.31).
- let max_h = (screen_h - 160.0).max(220.0);
- let min_h = 140.0;
- self.console_height = self.console_height.clamp(min_h, max_h);
- egui::TopBottomPanel::bottom("console")
- .exact_height(self.console_height)
- .show_separator_line(false)
- .show(ctx, |ui| {
- // Full-width drag strip at the top of the dock.
- let grip_h = 10.0;
- let (grip_rect, grip_resp) = ui.allocate_exact_size(
- egui::vec2(ui.available_width(), grip_h),
- egui::Sense::drag(),
- );
- let grip_color = if grip_resp.dragged() {
- ui.visuals().widgets.active.bg_fill
- } else if grip_resp.hovered() {
- ui.visuals().widgets.hovered.bg_fill
- } else {
- ui.visuals().widgets.noninteractive.bg_fill
- };
- ui.painter().rect_filled(grip_rect, 0.0, grip_color);
- // Center handle bar.
- let bar =
- egui::Rect::from_center_size(grip_rect.center(), egui::vec2(48.0, 3.0));
- ui.painter().rect_filled(
- bar,
- 1.5,
- ui.visuals().widgets.noninteractive.fg_stroke.color,
- );
- if grip_resp.hovered() || grip_resp.dragged() {
- ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
- }
- if grip_resp.dragged() {
- // Dragging the top edge up (negative dy) grows the panel.
- self.console_height =
- (self.console_height - grip_resp.drag_delta().y).clamp(min_h, max_h);
- }
- grip_resp.on_hover_text("Drag to resize console");
-
- ui.set_min_height(ui.available_height());
- self.render_bottom_dock(ui);
- });
- }
-
- // Global keyboard shortcuts (after Grok dock so keyboard_captured is current).
- // bindings: Alt+Left/Right, G, L/Ctrl+L, ;, T, Alt+Enter, Ctrl+Up/Down.
- if !self.grok_pane.keyboard_captured {
- let (
- want_back,
- want_forward,
- want_goto,
- want_rename,
- want_retype,
- want_comment,
- want_chooser,
- want_signature,
- want_next_fn,
- want_prev_fn,
- ) = ctx.input(|i| {
- let alt = i.modifiers.alt;
- let ctrl = i.modifiers.ctrl;
- (
- alt && i.key_pressed(egui::Key::ArrowLeft),
- alt && i.key_pressed(egui::Key::ArrowRight),
- i.key_pressed(egui::Key::G) && !ctrl && !alt,
- i.key_pressed(egui::Key::L) && !ctrl && !alt,
- i.key_pressed(egui::Key::L) && ctrl,
- i.key_pressed(egui::Key::Semicolon) && !ctrl && !alt,
- i.key_pressed(egui::Key::T) && !ctrl && !alt,
- alt && i.key_pressed(egui::Key::Enter),
- ctrl && i.key_pressed(egui::Key::ArrowDown),
- ctrl && i.key_pressed(egui::Key::ArrowUp),
- )
- });
- if want_back {
- self.nav_back();
- }
- if want_forward {
- self.nav_forward();
- }
- if want_goto && self.program.is_some() {
- if self.goto_input.is_empty() {
- if let Some(prog) = &self.program {
- self.goto_input = prog
- .entry
- .map(|e| format!("{e:#x}"))
- .unwrap_or_else(|| format!("{:#x}", prog.image_base));
- }
- }
- self.show_goto_dialog = true;
- }
- if want_rename {
- if let Some(va) = self.listing_focus_va {
- self.open_rename_dialog(va);
- }
- }
- if want_retype {
- if let Some(va) = self.listing_focus_va {
- self.open_retype_dialog(va);
- }
- }
- if want_comment {
- if let Some(va) = self.listing_focus_va {
- self.open_comment_dialog(va, CommentKind::Eol);
- }
- }
- if want_chooser {
- let va = self.listing_focus_va;
- if va.is_some() {
- self.open_type_chooser(va);
- }
- }
- if want_signature {
- if let Some(va) = self.listing_focus_va {
- let entry = self
- .program
- .as_ref()
- .and_then(|p| {
- p.analysis
- .functions
- .iter()
- .find(|f| va >= f.entry && va < f.end)
- .map(|f| f.entry)
- })
- .unwrap_or(va);
- self.open_signature_dialog(entry);
- }
- }
- if want_next_fn {
- self.nav_next_function();
- }
- if want_prev_fn {
- self.nav_prev_function();
- }
- }
-
- // Project Window–style dock: Project → binaries (upgraded badges + actions)
- if self.show_project_tree {
- egui::SidePanel::left("project_tree")
- .resizable(true)
- .default_width(240.0)
- .show(ctx, |ui| {
- ui.heading("Project");
- ui.small(
- egui::RichText::new(
- "Click = select · Double-click / Open = load into main view · Analyze = options",
- )
- .weak(),
- );
- ui.separator();
- if self.project.is_none() {
- ui.weak("No project open.");
- ui.label("New/Open a project, then Import binaries.");
- } else {
- let model = self.project_tree_model().unwrap();
- let t = m3_tokens(self.theme);
- let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
- let muted = Color32::from_rgb(
- t.on_surface_variant[0],
- t.on_surface_variant[1],
- t.on_surface_variant[2],
- );
- let ok_green = Color32::from_rgb(0x4C, 0xAF, 0x50);
- 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.");
- }
- 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);
- }
- (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(id) = select_id {
- self.tree_selected_id = Some(id);
- }
- if let Some(id) = delete_id {
- self.request_delete_file(&id);
- } else if let Some(id) = analyze_id {
- if let Err(e) = self.analyze_from_tree(&id) {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- } else if let Some(id) = open_id {
- if let Err(e) = self.open_from_tree(&id) {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- }
- self.project_tree_expanded = expanded;
- }
- });
- }
-
- // Delete confirmation modal
- if let Some((ref id, ref name)) = self.pending_delete.clone() {
- let id = id.clone();
- let name = name.clone();
- egui::Window::new("Delete from project?")
- .collapsible(false)
- .resizable(false)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- ui.label(format!(
- "Remove \"{name}\" from this project?\n\n\
- Deletes the imported copy and saved analysis for this file.\n\
- This cannot be undone."
- ));
- ui.add_space(8.0);
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- self.cancel_delete_file();
- }
- if ui
- .button(
- egui::RichText::new("Delete")
- .color(Color32::from_rgb(0xB3, 0x26, 0x1E)),
- )
- .clicked()
- {
- let _ = id;
- if let Err(e) = self.confirm_delete_file() {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- });
- });
- }
-
- if self.show_program_tree {
- egui::SidePanel::left("program_tree")
- .resizable(true)
- .default_width(220.0)
- .show(ctx, |ui| {
- ui.heading("Program Trees");
- ui.small(egui::RichText::new("ProgramTreePlugin · modules/fragments").weak());
- ui.separator();
- let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
- return;
- };
- // Snapshot everything we need before mutable use later.
- let root_name = prog.name.clone();
- let entry = prog.entry;
- let image_base = prog.image_base;
- let blocks: Vec<(String, u64, u64, bool, bool, bool)> = prog
- .blocks
- .iter()
- .map(|b| {
- (
- b.name.clone(),
- b.va,
- b.size,
- b.readable,
- b.writable,
- b.executable,
- )
- })
- .collect();
-
- ui.horizontal(|ui| {
- let primary = Color32::from_rgb(
- m3_tokens(self.theme).primary[0],
- m3_tokens(self.theme).primary[1],
- m3_tokens(self.theme).primary[2],
- );
- m3_icon(ui, M3Icon::Folder, 16.0, primary);
- ui.strong(&root_name);
- });
- ui.small(
- egui::RichText::new(format!(
- "image base {image_base:#x}{}",
- entry
- .map(|e| format!(" · entry {e:#x}"))
- .unwrap_or_default()
- ))
- .weak(),
- );
-
- // Group blocks into modules by permissions.
- // Module: "Code" (executable), "Data" (writable, non-exec), "RO Data" (else).
- let mut code: Vec<usize> = Vec::new();
- let mut data: Vec<usize> = Vec::new();
- let mut rodata: Vec<usize> = Vec::new();
- for (i, (_, _, _, _, w, x)) in blocks.iter().enumerate() {
- if *x {
- code.push(i);
- } else if *w {
- data.push(i);
- } else {
- rodata.push(i);
- }
- }
-
- let mut goto: Option<u64> = None;
- 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]| {
- egui::CollapsingHeader::new(format!("{title} ({})", indices.len()))
- .default_open(!indices.is_empty() && indices.len() <= 32)
- .show(ui, |ui| {
- if indices.is_empty() {
- ui.weak("(empty module)");
- return;
- }
- for &i in indices {
- let (name, va, size, r, w, x) = &blocks[i];
- let flags = format!(
- "{}{}{}",
- if *r { "r" } else { "-" },
- if *w { "w" } else { "-" },
- if *x { "x" } else { "-" },
- );
- let in_view = view_filter
- .as_ref()
- .map(|f| f.contains(name))
- .unwrap_or(true);
- ui.horizontal(|ui| {
- let indicator = if in_view { "[v]" } else { "[ ]" };
- ui.monospace(indicator);
- if ui
- .link(
- egui::RichText::new(format!(
- "{name} {va:#x} {size:#x} {flags}"
- ))
- .monospace(),
- )
- .on_hover_text("Go To fragment start")
- .clicked()
- {
- goto = Some(*va);
- }
- ui.with_layout(
- egui::Layout::right_to_left(egui::Align::Center),
- |ui| {
- if in_view && view_filter.is_some() {
- if ui
- .small_button("Remove")
- .on_hover_text(
- "Remove fragment from Listing view",
- )
- .clicked()
- {
- remove_from_view = Some(name.clone());
- }
- } else if ui
- .small_button("Add")
- .on_hover_text("Add fragment to Listing view")
- .clicked()
- {
- add_to_view = Some(name.clone());
- }
- if ui
- .small_button("Set")
- .on_hover_text(
- "Set Listing view to this fragment only",
- )
- .clicked()
- {
- set_view = Some(name.clone());
- }
- },
- );
- });
- }
- });
- };
-
- 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}"));
- }
- if let Some(name) = add_to_view {
- self.add_to_view(name);
- }
- if let Some(name) = remove_from_view {
- self.remove_from_view(&name);
- }
- if let Some(name) = set_view {
- let mut s = BTreeSet::new();
- s.insert(name);
- self.set_listing_view(Some(s));
- }
- if show_all {
- self.listing_view_filter = None;
- }
- });
- }
-
- if self.show_symbol_tree {
- egui::SidePanel::right("symbol_tree")
- .resizable(true)
- .default_width(280.0)
- .min_width(200.0)
- .show(ctx, |ui| {
- let t = m3_tokens(self.theme);
- let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
- ui.heading("Symbol Tree");
- if self.program.is_none() {
- ui.weak("Open a project file to browse symbols.");
- return;
- }
- ui.small(egui::RichText::new(self.analysis_summary_line()).color(primary));
- ui.horizontal(|ui| {
- ui.checkbox(&mut self.symbol_tree_nav, "Selection Navigation")
- .on_hover_text(
- "`Selection Navigation` — cursor moves keep this tree in sync",
- );
- });
- 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| {
- // ── `SymbolTreePlugin` category order ────────────────
- // Imports · Exports · Functions · Labels · Classes · Namespaces
-
- let (imports, exports) = self.imports_exports();
-
- let mut nav_goto: Option<u64> = None;
- // 1) Imports — honest: only rows the analyzer/loader produced.
- egui::CollapsingHeader::new(format!("Imports ({})", imports.len()))
- .default_open(false)
- .show(ui, |ui| {
- if imports.is_empty() {
- ui.weak(
- "No imports — Ghidrust PE loader currently does not \
- parse the Import Directory. Run a PDB analyzer to \
- populate __imp_* symbols.",
- );
- } else {
- for (va, name) in &imports {
- if ui
- .link(
- egui::RichText::new(format!("{va:#x} {name}"))
- .monospace(),
- )
- .clicked()
- {
- nav_goto = Some(*va);
- }
- }
- }
- });
- // 2) Exports — honest empty when unset.
- egui::CollapsingHeader::new(format!("Exports ({})", exports.len()))
- .default_open(false)
- .show(ui, |ui| {
- if exports.is_empty() {
- ui.weak(
- "No exports — Ghidrust PE loader currently does not \
- parse the Export Directory. Analyzer output may \
- surface `__declspec(dllexport)` names.",
- );
- } else {
- for (va, name) in &exports {
- if ui
- .link(
- egui::RichText::new(format!("{va:#x} {name}"))
- .monospace(),
- )
- .clicked()
- {
- nav_goto = Some(*va);
- }
- }
- }
- });
- if let Some(va) = nav_goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
-
- // 3) Functions (virtualized) — real from Program::analysis.functions
- let fn_count = self
- .program
- .as_ref()
- .map(|p| p.analysis.functions.len())
- .unwrap_or(0);
- egui::CollapsingHeader::new(format!("Functions ({fn_count})"))
- .default_open(fn_count > 0 && fn_count <= 500)
- .show(ui, |ui| {
- let entry = self.program.as_ref().and_then(|p| p.entry);
- let fns: Vec<(u64, String)> = self
- .program
- .as_ref()
- .map(|p| {
- p.analysis
- .functions
- .iter()
- .map(|f| (f.entry, f.name.clone()))
- .collect()
- })
- .unwrap_or_default();
- if let Some(e) = entry {
- ui.monospace(format!("entry @ {e:#x}"));
- }
- if fns.is_empty() {
- ui.weak("Run Function Start Search.");
- } else {
- ui.add(
- egui::TextEdit::singleline(&mut self.fn_filter)
- .desired_width(f32::INFINITY)
- .hint_text("Filter functions…"),
- );
- let q = self.fn_filter.to_ascii_lowercase();
- let rows: Vec<(u64, String)> = fns
- .into_iter()
- .filter(|(_, name)| {
- q.is_empty()
- || name.to_ascii_lowercase().contains(&q)
- })
- .collect();
- let row_h =
- ui.text_style_height(&egui::TextStyle::Monospace);
- let n = rows.len();
- let mut clicked_fn: Option<u64> = None;
- egui::ScrollArea::vertical()
- .id_salt("fn_scroll")
- .max_height(220.0)
- .show_rows(ui, row_h, n, |ui, range| {
- for i in range {
- let (va, name) = &rows[i];
- let label = format!("{va:#x} {name}");
- // Focused if this function is the decomp / cursor /
- // selection-navigation target.
- let focused = self.decomp_entry == Some(*va)
- || self.listing_focus_va == Some(*va)
- || self.focused_function_entry == Some(*va);
- let rich = if focused {
- egui::RichText::new(label)
- .monospace()
- .color(primary)
- } else {
- egui::RichText::new(label).monospace()
- };
- let r = ui.add(
- egui::Label::new(rich)
- .sense(egui::Sense::click()),
- );
- if r.clicked() {
- clicked_fn = Some(*va);
- }
- if r.hovered() {
- ui.ctx().set_cursor_icon(
- egui::CursorIcon::PointingHand,
- );
- }
- }
- });
- if let Some(va) = clicked_fn {
- self.focus_function(va);
- }
- ui.small(format!(
- "{n} shown · click → Listing + Decompiler"
- ));
- }
- });
-
- // 4) Labels — Program::analysis.symbols (real)
- let labels: Vec<(u64, String)> = self
- .program
- .as_ref()
- .map(|p| {
- p.analysis
- .symbols
- .iter()
- .map(|s| (s.va, s.name.clone()))
- .collect()
- })
- .unwrap_or_default();
- egui::CollapsingHeader::new(format!("Labels ({})", labels.len()))
- .default_open(false)
- .show(ui, |ui| {
- if labels.is_empty() {
- ui.weak(
- "No labels — analyzers/PDB symbols populate this list.",
- );
- } else {
- let row_h =
- ui.text_style_height(&egui::TextStyle::Monospace);
- let n = labels.len();
- let mut clicked_va: Option<u64> = None;
- egui::ScrollArea::vertical()
- .id_salt("labels_scroll")
- .max_height(220.0)
- .show_rows(ui, row_h, n, |ui, range| {
- for i in range {
- let (va, name) = &labels[i];
- let r = ui.add(
- egui::Label::new(
- egui::RichText::new(format!(
- "{va:#x} {name}"
- ))
- .monospace(),
- )
- .sense(egui::Sense::click()),
- );
- if r.clicked() {
- clicked_va = Some(*va);
- }
- }
- });
- if let Some(va) = clicked_va {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- }
- });
-
- // 5) Classes (RTTI subtree preserved) — real
- let rtti_n = self.rtti.classes.len();
- egui::CollapsingHeader::new(format!("Classes ({rtti_n})"))
- .default_open(false)
- .show(ui, |ui| {
- if rtti_n == 0 {
- ui.weak("Run WindowsPE x86 PE RTTI Analyzer, then Open the file.");
- return;
- }
- ui.add(
- egui::TextEdit::singleline(&mut self.rtti_filter)
- .desired_width(f32::INFINITY)
- .hint_text("Filter class names…"),
- );
- if ui.button("Apply filter").clicked()
- || ui.input(|i| i.key_pressed(egui::Key::Enter))
- {
- self.rtti_filter_cache.clear();
- }
- 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]];
- let va = c
- .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={:?}\nvtable_vas (rtti_query)=[{vtables}]",
- c.kind, c.col_va, c.vtable_va
- ));
- });
- }
- });
- });
-
- // 6) Namespaces — honest: derive from `::` in symbol names when a demangler ran.
- let namespace_map: BTreeMap<String, Vec<(u64, String)>> = {
- let mut m: BTreeMap<String, Vec<(u64, String)>> = BTreeMap::new();
- if let Some(prog) = self.program.as_ref() {
- for s in prog
- .analysis
- .symbols
- .iter()
- .chain(prog.analysis.pdb_symbols.iter())
- {
- let src = s.demangled.as_deref().unwrap_or(&s.name);
- if let Some(idx) = src.rfind("::") {
- let ns = src[..idx].to_string();
- let leaf = src[idx + 2..].to_string();
- m.entry(ns).or_default().push((s.va, leaf));
- }
- }
- }
- m
- };
- egui::CollapsingHeader::new(format!(
- "Namespaces ({})",
- namespace_map.len()
- ))
- .default_open(false)
- .show(ui, |ui| {
- if namespace_map.is_empty() {
- ui.weak(
- "No namespaces recovered — the Demangler Microsoft analyzer \
- fills this list when demangling produces `::` scopes.",
- );
- return;
- }
- let mut clicked_va: Option<u64> = None;
- for (ns, entries) in &namespace_map {
- egui::CollapsingHeader::new(format!(
- "{ns} ({})",
- entries.len()
- ))
- .default_open(false)
- .show(ui, |ui| {
- for (va, leaf) in entries {
- if ui
- .link(
- egui::RichText::new(format!("{va:#x} {leaf}"))
- .monospace(),
- )
- .clicked()
- {
- clicked_va = Some(*va);
- }
- }
- });
- }
- if let Some(va) = clicked_va {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- });
-
- // Bonus: Strings shortcut (has a separate Defined Strings window,
- // which is available in the floating provider panel too).
- let str_n = self.strings.len();
- egui::CollapsingHeader::new(format!("Strings ({str_n})"))
- .default_open(false)
- .show(ui, |ui| {
- if str_n == 0 {
- ui.weak("Run ASCII Strings (session) or re-analyze.");
- return;
- }
- if ui.button("Open Defined Strings window").clicked() {
- self.pane_open.insert(PaneKind::DefinedStrings, true);
- }
- let row_h = ui.text_style_height(&egui::TextStyle::Monospace);
- egui::ScrollArea::vertical()
- .id_salt("str_scroll")
- .max_height(200.0)
- .show_rows(ui, row_h, str_n.min(5000), |ui, range| {
- for i in range {
- if let Some(s) = self.strings.get(i) {
- let val: String =
- s.value.chars().take(48).collect();
- ui.monospace(format!("{:#x}: {val}", s.va));
- }
- }
- });
- if str_n > 5000 {
- ui.small(format!("Showing first 5000 of {str_n}"));
- }
- });
- });
- });
- }
-
- // Analysis complete banner (top of frame content)
- if let Some(banner) = self.analysis_done_banner.clone() {
- egui::TopBottomPanel::top("analysis_done_banner").show(ctx, |ui| {
- let t = m3_tokens(self.theme);
- let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
- let ok = Color32::from_rgb(0x4C, 0xAF, 0x50);
- ui.horizontal(|ui| {
- m3_icon(ui, M3Icon::CheckCircle, 18.0, ok);
- ui.label(egui::RichText::new(banner).color(primary).strong());
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- if ui.button("Dismiss").clicked() {
- self.analysis_done_banner = None;
- }
- if ui.button("Open Overview").clicked() {
- self.focus_center_tab(DockTab::Overview);
- self.analysis_done_banner = None;
- }
- });
- });
- });
- }
-
- egui::CentralPanel::default().show(ctx, |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();
- });
-
- // draw every open floating provider pane.
- self.draw_provider_panes(ctx);
-
- // edit dialogs (rename / retype / comment / signature / new type).
- self.draw_edit_dialogs(ctx);
-
- // Configure plugins dialog.
- if self.show_configure_dialog {
- let mut close = false;
- egui::Window::new("Configure plugins")
- .id(egui::Id::new("dialog_configure"))
- .resizable(true)
- .default_size(egui::vec2(680.0, 460.0))
- .show(ctx, |ui| {
- ui.label(
- "Ghidrust plugins are compile-time; this dialog lists every provider Ghidrust ships.",
- );
- ui.separator();
- egui::ScrollArea::vertical()
- .id_salt("configure_scroll")
- .max_height(340.0)
- .show(ui, |ui| {
- egui::Grid::new("configure_grid")
- .num_columns(4)
- .striped(true)
- .show(ui, |ui| {
- ui.strong("Plugin");
- ui.strong("Kind");
- ui.strong("State");
- ui.strong("Description");
- ui.end_row();
- for p in layouts::PLUGIN_CATALOG {
- ui.monospace(p.name);
- ui.label(p.kind);
- ui.label(p.state);
- ui.label(p.description);
- ui.end_row();
- }
- });
- });
- ui.separator();
- if ui.button("Close").clicked() {
- close = true;
- }
- });
- if close {
- self.show_configure_dialog = false;
- }
- }
-
- // Layout save / load dialog.
- if self.show_layouts_dialog {
- let mut close = false;
- let mut do_save = false;
- let mut load_name: Option<String> = None;
- let mut delete_name: Option<String> = None;
- egui::Window::new("Tool Layouts")
- .id(egui::Id::new("dialog_layouts"))
- .resizable(true)
- .default_size(egui::vec2(480.0, 360.0))
- .show(ctx, |ui| {
- ui.label("Save / restore CodeBrowser tool layouts (pane visibility + docks).");
- ui.small(
- egui::RichText::new(
- "Files land under %APPDATA%/ghidrust/layouts/<name>.tool.json .",
- )
- .weak(),
- );
- ui.separator();
- ui.horizontal(|ui| {
- ui.label("Name:");
- ui.add(
- egui::TextEdit::singleline(&mut self.layouts_new_name)
- .desired_width(200.0)
- .hint_text("MyCodeBrowser"),
- );
- if ui
- .add_enabled(
- !self.layouts_new_name.trim().is_empty(),
- egui::Button::new("Save current layout"),
- )
- .clicked()
- {
- do_save = true;
- }
- });
- ui.separator();
- ui.label(egui::RichText::new("Saved layouts").strong());
- if self.layouts_cached.is_empty() {
- ui.weak("No layouts saved yet.");
- } else {
- egui::ScrollArea::vertical()
- .id_salt("layouts_scroll")
- .max_height(180.0)
- .show(ui, |ui| {
- for name in &self.layouts_cached {
- ui.horizontal(|ui| {
- ui.monospace(name);
- if ui.small_button("Restore").clicked() {
- load_name = Some(name.clone());
- }
- if ui.small_button("Delete").clicked() {
- delete_name = Some(name.clone());
- }
- });
- }
- });
- }
- ui.separator();
- if !self.current_layout_name.is_empty() {
- ui.small(
- egui::RichText::new(format!(
- "Current layout: {}",
- self.current_layout_name
- ))
- .weak(),
- );
- }
- if ui.button("Close").clicked() {
- close = true;
- }
- });
- if do_save {
- match self.save_layout_named(self.layouts_new_name.clone()) {
- Ok(p) => {
- self.status = format!("Layout saved → {}", p.display());
- self.log(self.status.clone());
- }
- Err(e) => {
- self.status = format!("save layout error: {e}");
- self.log_error(self.status.clone());
- }
- }
- }
- if let Some(name) = load_name {
- match self.restore_layout_named(&name) {
- Ok(()) => {
- self.status = format!("Layout restored → {name}");
- self.log(self.status.clone());
- }
- Err(e) => {
- self.status = format!("restore layout error: {e}");
- self.log_error(self.status.clone());
- }
- }
- }
- if let Some(name) = delete_name {
- if let Err(e) = layouts::delete_layout(&name) {
- self.status = format!("delete layout error: {e}");
- self.log_error(self.status.clone());
- }
- self.layouts_cached = layouts::list_layouts();
- }
- if close {
- self.show_layouts_dialog = false;
- }
- }
-
- // Bookmark add dialog
- if self.show_bookmark_dialog {
- let mut close = false;
- let mut confirmed = false;
- egui::Window::new("Add Bookmark")
- .id(egui::Id::new("dialog_add_bookmark"))
- .collapsible(false)
- .resizable(false)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- ui.label("Kind:");
- egui::ComboBox::from_id_salt("bookmark_kind")
- .selected_text(self.bookmark_dialog_kind.label())
- .show_ui(ui, |ui| {
- for k in BookmarkKind::ALL {
- ui.selectable_value(&mut self.bookmark_dialog_kind, *k, k.label());
- }
- });
- ui.label("Category:");
- ui.text_edit_singleline(&mut self.bookmark_dialog_category);
- ui.label("Description:");
- ui.text_edit_singleline(&mut self.bookmark_dialog_description);
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- close = true;
- }
- if ui.button("Add").clicked() {
- confirmed = true;
- close = true;
- }
- });
- });
- if confirmed {
- if let Some(va) = self.listing_focus_va {
- let kind = self.bookmark_dialog_kind;
- let cat = self.bookmark_dialog_category.clone();
- let desc = self.bookmark_dialog_description.clone();
- self.add_bookmark(va, kind, cat, desc);
- }
- }
- if close {
- self.show_bookmark_dialog = false;
- }
- }
-
- // Navigation → Go To Address
- if self.show_goto_dialog {
- egui::Window::new("Go To Address")
- .collapsible(false)
- .resizable(false)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- ui.label("Address (hex, optional 0x prefix):");
- ui.text_edit_singleline(&mut self.goto_input);
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- self.show_goto_dialog = false;
- }
- if ui.button("Go").clicked() {
- match self.goto_address_str(&self.goto_input.clone()) {
- Ok(()) => self.show_goto_dialog = false,
- Err(e) => {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- }
- });
- });
- }
-
- // Search → Memory
- if self.show_search_memory_dialog {
- egui::Window::new("Search Memory")
- .collapsible(false)
- .resizable(true)
- .default_width(420.0)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- ui.label("Byte pattern (hex; ?? = wildcard):");
- ui.text_edit_singleline(&mut self.search_memory_input);
- ui.small("Example: 55 48 89 e5 or 48??e5");
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- self.show_search_memory_dialog = false;
- }
- if ui.button("Search").clicked() {
- match self.run_search_memory() {
- Ok(()) => self.show_search_memory_dialog = false,
- Err(e) => {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- }
- });
- });
- }
-
- // Search → Program Text
- if self.show_search_text_dialog {
- egui::Window::new("Search Program Text")
- .collapsible(false)
- .resizable(true)
- .default_width(420.0)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- ui.label("Query (listing / symbols / functions / memory text):");
- ui.text_edit_singleline(&mut self.search_text_input);
- ui.checkbox(&mut self.search_text_case_insensitive, "Case insensitive");
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- self.show_search_text_dialog = false;
- }
- if ui.button("Search").clicked() {
- match self.run_search_text() {
- Ok(()) => self.show_search_text_dialog = false,
- Err(e) => {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- }
- });
- });
- }
-
- // Search → For Scalars
- if self.show_search_scalars_dialog {
- egui::Window::new("Search For Scalars")
- .collapsible(false)
- .resizable(false)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- ui.label("Scan operand scalars in [min, max]. Hex ok (0x…) or decimal.");
- ui.horizontal(|ui| {
- ui.label("Min:");
- ui.text_edit_singleline(&mut self.search_scalars_min);
- });
- ui.horizontal(|ui| {
- ui.label("Max:");
- ui.text_edit_singleline(&mut self.search_scalars_max);
- });
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- self.show_search_scalars_dialog = false;
- }
- if ui.button("Search").clicked() {
- match self.run_search_scalars() {
- Ok(()) => self.show_search_scalars_dialog = false,
- Err(e) => {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- }
- }
- }
- });
- });
- }
-
- // Search → Instruction Patterns
- if self.show_search_insn_dialog {
- egui::Window::new("Search Instruction Patterns")
- .collapsible(false)
- .resizable(true)
- .default_width(420.0)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- ui.small("Matches against decoded listing rows. Empty field = don't filter.");
- ui.horizontal(|ui| {
- ui.label("Mnemonic:");
- ui.text_edit_singleline(&mut self.search_insn_mnemonic);
- });
- ui.horizontal(|ui| {
- ui.label("Operands:");
- ui.text_edit_singleline(&mut self.search_insn_operands);
- });
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- self.show_search_insn_dialog = false;
- }
- if ui.button("Search").clicked() {
- match self.run_search_instruction_patterns() {
- Ok(()) => self.show_search_insn_dialog = false,
- Err(e) => {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- }
- }
- }
- });
- });
- }
-
- // Add Equate dialog .
- if self.show_equate_dialog {
- let mut close = false;
- egui::Window::new("Set Equate")
- .collapsible(false)
- .resizable(false)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- ui.small("Bind a name to a scalar operand .");
- ui.horizontal(|ui| {
- ui.label("VA:");
- let mut input = self
- .equate_dialog_va
- .map(|v| format!("{v:#x}"))
- .unwrap_or_default();
- if ui.text_edit_singleline(&mut input).lost_focus() {
- self.equate_dialog_va = parse_address(&input).ok();
- }
- });
- ui.horizontal(|ui| {
- ui.label("Operand index:");
- let mut s = format!("{}", self.equate_dialog_op);
- if ui.text_edit_singleline(&mut s).lost_focus() {
- self.equate_dialog_op =
- s.trim().parse().unwrap_or(self.equate_dialog_op);
- }
- });
- ui.horizontal(|ui| {
- ui.label("Name:");
- ui.text_edit_singleline(&mut self.equate_dialog_name);
- });
- ui.horizontal(|ui| {
- ui.label("Value (dec / hex):");
- ui.text_edit_singleline(&mut self.equate_dialog_value);
- });
- ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
- close = true;
- }
- if ui.button("Apply").clicked() {
- let value = self
- .parse_scalar_input(&self.equate_dialog_value.clone())
- .unwrap_or(0);
- if let Some(va) = self.equate_dialog_va {
- if let Err(e) = self.set_equate(
- va,
- self.equate_dialog_op,
- self.equate_dialog_name.clone(),
- value,
- ) {
- self.status = format!("error: {e}");
- self.log_error(self.status.clone());
- } else {
- close = true;
- }
- } else {
- close = true;
- }
- }
- });
- });
- if close {
- self.show_equate_dialog = false;
- }
- }
-
- // Search results window
- if self.show_search_results {
- egui::Window::new("Search Results")
- .collapsible(true)
- .resizable(true)
- .default_width(480.0)
- .default_height(280.0)
- .show(ctx, |ui| {
- if ui.button("Close").clicked() {
- self.show_search_results = false;
- }
- ui.separator();
- egui::ScrollArea::vertical().show(ui, |ui| {
- for h in self.memory_hits.clone() {
- if ui
- .button(format!(
- "{:#x} {} +{:#x}",
- h.va, h.block, h.offset_in_block
- ))
- .clicked()
- {
- let _ = self.goto_address_str(&format!("{:#x}", h.va));
- }
- }
- for h in self.text_hits.clone() {
- let label = match h.va {
- Some(va) => format!("[{}] {:#x}: {}", h.kind, va, h.text),
- None => format!("[{}] {}", h.kind, h.text),
- };
- if ui.button(label).clicked() {
- if let Some(va) = h.va {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
- }
- }
- if self.memory_hits.is_empty() && self.text_hits.is_empty() {
- ui.weak("No hits.");
- }
- });
- });
- }
-
- // Listing → Decode options
- if ui_options_dialog(
- ctx,
- &mut self.show_decode_options_dialog,
- &mut self.decode_opts,
- self.program.as_ref(),
- ) {
- self.apply_decode_opts();
- }
-
- // Tools → Processor options
- if self.show_processor_dialog {
- egui::Window::new("Processor Options")
- .collapsible(false)
- .resizable(true)
- .default_width(440.0)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- if let Some(prog) = &self.program {
- let info = processor_info(prog);
- ui.monospace(format!("Language: {}", info.language));
- ui.monospace(format!("Compiler: {}", info.compiler));
- ui.monospace(format!("Format: {}", info.format));
- ui.monospace(format!("Endian: {}", info.endian));
- ui.monospace(format!("Pointer size: {} bytes", info.pointer_size));
- ui.monospace(format!("Image base: {:#x}", info.image_base));
- ui.monospace(format!(
- "Entry: {}",
- info.entry
- .map(|e| format!("{e:#x}"))
- .unwrap_or_else(|| "—".into())
- ));
- ui.separator();
- ui.small(&info.notes);
- ui.separator();
- ui.label("Sections:");
- egui::ScrollArea::vertical()
- .max_height(160.0)
- .show(ui, |ui| {
- for s in &prog.sections {
- ui.monospace(format!(
- "{} va={:#x} vsize={:#x}",
- s.name, s.va, s.virtual_size
- ));
- }
- });
- } else {
- ui.weak("Load a program to view processor / language options.");
- }
- if ui.button("Close").clicked() {
- self.show_processor_dialog = false;
- }
- });
- }
-
- // 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]);
- egui::Window::new("Analysis options")
- .collapsible(false)
- .resizable(true)
- .default_width(460.0)
- .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
- .show(ctx, |ui| {
- if let Some(ref id) = self.pending_analyze_file_id {
- let name = self
- .project
- .as_ref()
- .and_then(|p| p.meta.files.iter().find(|f| f.id == *id))
- .map(|f| f.display_name.as_str())
- .unwrap_or(id.as_str());
- ui.label(
- egui::RichText::new(format!("Target: {name}"))
- .strong()
- .color(primary),
- );
- ui.add_space(4.0);
- }
- ui.label("Select analyzers (labels):");
- ui.horizontal(|ui| {
- if ui.small_button("Select defaults").clicked() {
- for (i, info) in self.analyzer_infos.iter().enumerate() {
- self.analyzer_enabled[i] = info.default_enabled;
- }
- }
- if ui.small_button("Select all").clicked() {
- for e in &mut self.analyzer_enabled {
- *e = true;
- }
- }
- if ui.small_button("Clear all").clicked() {
- for e in &mut self.analyzer_enabled {
- *e = false;
- }
- }
- });
- egui::ScrollArea::vertical()
- .max_height(320.0)
- .show(ui, |ui| {
- for (i, info) in self.analyzer_infos.iter().enumerate() {
- ui.horizontal(|ui| {
- ui.checkbox(&mut self.analyzer_enabled[i], &info.name);
- match info.status {
- ghidrust_core::AnalyzerStatus::Implemented => {
- ui.weak("ready");
- }
- ghidrust_core::AnalyzerStatus::NotImplemented => {
- ui.weak("stub");
- }
- }
- // Per-row GPU indicator (master checkbox gates actual use).
- let supports = analyzer_supports_gpu(&info.name);
- if supports && self.use_gpu_experimental {
- ui.label(
- egui::RichText::new("GPU")
- .small()
- .strong()
- .color(primary),
- )
- .on_hover_text(
- "Master GPU is on — this analyzer will use its GPU \
- strategy (bulk and/or seed enrich). Falls back to CPU \
- on failure.",
- );
- } else if supports {
- ui.label(
- egui::RichText::new("GPU")
- .small()
- .color(Color32::from_rgb(120, 120, 128)),
- )
- .on_hover_text(
- "GPU strategy available — enable the master GPU checkbox \
- to use it. Currently CPU.",
- );
- } else {
- ui.label(
- egui::RichText::new("CPU only")
- .small()
- .color(Color32::from_rgb(120, 120, 128)),
- )
- .on_hover_text(
- "No GPU strategy for this analyzer — always runs on CPU.",
- );
- }
- });
- }
- });
- ui.separator();
- ui.checkbox(
- &mut self.use_gpu_experimental,
- "GPU (only analyzers with a GPU strategy)",
- );
- ui.small(
- "wgpu when available: GPU bulk / SIMT seed enrich only for analyzers \
- marked GPU above (see strategy matrix). Others stay CPU-only. \
- Large images are multi-dispatch chunked (≤65535 workgroups). \
- Falls back to CPU on failure. GPU decompile is a separate tool.",
- );
- ui.add_space(8.0);
- ui.horizontal(|ui| {
- let can_run = self.analyzer_enabled.iter().any(|e| *e)
- && (self.program.is_some() || self.pending_analyze_file_id.is_some());
- if ui
- .add_enabled(can_run, egui::Button::new("Run Analysis"))
- .clicked()
- {
- match self.begin_analysis_job() {
- Ok(()) => {
- self.show_analysis_dialog = false;
- }
- Err(e) => {
- self.status = format!("error: {e}");
- self.log(self.status.clone());
- }
- }
- }
- if ui.button("Cancel").clicked() {
- self.pending_analyze_file_id = None;
- self.show_analysis_dialog = false;
- }
- });
- });
- }
-
- // Floating M3 progress card while analysis runs
- if let Some(frac) = self.analysis_progress_fraction() {
- let t = m3_tokens(self.theme);
- let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
- let on_surface = Color32::from_rgb(t.on_surface[0], t.on_surface[1], t.on_surface[2]);
- let track = Color32::from_rgb(
- t.surface_container[0],
- t.surface_container[1],
- t.surface_container[2],
- )
- .gamma_multiply(1.4);
- egui::Window::new("Analysis progress")
- .collapsible(false)
- .resizable(false)
- .anchor(egui::Align2::CENTER_BOTTOM, [0.0, -48.0])
- .title_bar(true)
- .show(ctx, |ui| {
- ui.set_min_width(360.0);
- if let Some(job) = &self.analysis_job {
- let n = job.names.len().max(1);
- let step = (job.index + 1).min(n);
- let cur = job
- .names
- .get(job.index)
- .map(|s| s.as_str())
- .unwrap_or("finishing…");
- ui.label(
- egui::RichText::new(format!("{} — {step}/{n}", job.file_label))
- .color(on_surface)
- .strong(),
- );
- ui.label(egui::RichText::new(cur).color(primary).small());
- if job.use_gpu {
- ui.small("GPU experimental bulk path enabled");
- }
- }
- ui.add_space(6.0);
- m3_linear_progress(ui, frac, primary, track);
- ui.add_space(2.0);
- ui.small(format!("{:.0}%", frac * 100.0));
- });
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use ghidrust_core::{fixture_path, ANALYZER_NAMES};
-
- #[test]
- fn shell_has_required_menus_and_panes() {
- let menus = GhidrustApp::shell_menus();
- // top-level menus (from `docking.tool.ToolConstants`).
- for m in [
- "File",
- "Edit",
- "Analysis",
- "Navigation",
- "Search",
- "Select",
- "Tools",
- "Graph",
- "Window",
- "Help",
- ] {
- assert!(menus.contains(&m), "missing menu {m}");
- }
- let panes = GhidrustApp::shell_panes();
- for p in [
- "Project Tree",
- "Program Tree",
- "Symbol Tree",
- "Overview",
- "Listing",
- "Decompiler",
- "Console",
- ] {
- assert!(panes.contains(&p), "missing pane {p}");
- }
- // Project Tree ≠ Program Tree
- assert_ne!(
- panes.iter().position(|p| *p == "Project Tree"),
- panes.iter().position(|p| *p == "Program Tree")
- );
- }
-
- /// every provider must be enumerated in
- /// `shell_panes` so the Window menu / structural tests can enforce provider visibility.
- #[test]
- fn shell_panes_enumerates_full_codebrowser_catalog() {
- let panes = GhidrustApp::shell_panes();
- // 28 default `.tool` providers + a few off-layout ones. See
- // internal UI notes § 1.1 / § 1.2 for the source of truth.
- for expected in [
- "Program Trees",
- "Symbol Tree",
- "Data Type Manager",
- "Listing",
- "Decompile",
- "Bytes",
- "Defined Data",
- "Defined Strings",
- "Equates Table",
- "External Programs",
- "Functions",
- "Relocation Table",
- "Data Type Preview",
- "Disassembled View",
- "Console",
- "Bookmarks",
- "Script Manager",
- "Memory Map",
- "Function Graph",
- "Register Manager",
- "Symbol Table",
- "Symbol References",
- "Checksum Generator",
- "Function Tags",
- "Comments",
- "Python",
- "Entropy",
- "Overview",
- // Off-layout, reached via Window menu
- "Function Call Trees",
- "Function Call Graph",
- "Text Editor",
- ] {
- assert!(
- panes.contains(&expected),
- "missing provider `{expected}` in shell_panes; full list = {panes:?}"
- );
- }
- }
-
- /// Back / Forward history is wired.
- #[test]
- fn nav_history_records_and_navigates() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- assert!(!app.can_nav_back());
- assert!(!app.can_nav_forward());
-
- // Two goto calls (both valid VAs inside the loaded listing window)
- // put one entry in the Back history.
- let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- // A second VA that is inside the loaded listing so re-disassemble isn't required.
- let second_va = app
- .listing
- .iter()
- .map(|i| i.address)
- .find(|&va| va > entry)
- .unwrap_or(entry + 1);
- app.goto_address_str(&format!("{entry:#x}"))
- .expect("goto entry");
- app.goto_address_str(&format!("{second_va:#x}"))
- .expect("goto second");
- assert!(app.can_nav_back, "back should be available after 2 gotos");
- assert!(!app.can_nav_forward());
-
- // Back → returns to entry
- assert!(app.nav_back, "nav_back should succeed");
- assert_eq!(app.listing_focus_va, Some(entry));
- assert!(app.can_nav_forward());
-
- // Forward → returns to second_va
- assert!(app.nav_forward, "nav_forward should succeed");
- assert_eq!(app.listing_focus_va, Some(second_va));
- }
-
- /// Bookmarks pane model is real (5 kinds; add/delete flow).
- #[test]
- fn bookmark_model_add_delete_and_nav() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- assert!(app.bookmarks.is_empty());
-
- let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.add_bookmark(entry, BookmarkKind::Note, "user", "entry point");
- app.add_bookmark(entry + 0x10, BookmarkKind::Analysis, "core", "hot loop");
- assert_eq!(app.bookmarks.len(), 2);
- assert!(app.is_pane_open(PaneKind::Bookmarks));
-
- // Next / Prev bookmark navigation works.
- app.listing_focus_va = Some(entry);
- app.nav_next_bookmark();
- assert_eq!(app.listing_focus_va, Some(entry + 0x10));
- app.nav_prev_bookmark();
- assert_eq!(app.listing_focus_va, Some(entry));
-
- app.delete_bookmark(0);
- assert_eq!(app.bookmarks.len(), 1);
- assert_eq!(app.bookmarks[0].va, entry + 0x10);
-
- // All 5 bookmark kinds are colourable.
- for k in BookmarkKind::ALL {
- let c = k.color();
- assert!(c.a() > 0 && (c.r() as u16 + c.g() as u16 + c.b() as u16) > 0);
- }
- }
-
- /// plugin event bus emits CursorMoved on goto and Mutation on bookmark ops.
- #[test]
- fn event_bus_publishes_cursor_and_mutation_events() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- // Loading emits ProgramActivated; drain baseline.
- let boot = app.drain_events();
- assert!(
- boot.iter()
- .any(|e| matches!(e, GhidrustEvent::ProgramActivated { .. })),
- "load_binary must publish ProgramActivated: {boot:?}"
- );
-
- let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.goto_address_str(&format!("{entry:#x}")).expect("goto");
- let evs = app.drain_events();
- assert!(
- evs.iter()
- .any(|e| matches!(e, GhidrustEvent::CursorMoved { .. })),
- "goto_address_str must publish CursorMoved: {evs:?}"
- );
-
- app.add_bookmark(entry, BookmarkKind::Note, "test", "hi");
- let evs = app.drain_events();
- assert!(
- evs.iter().any(|e| matches!(
- e,
- GhidrustEvent::ProgramMutated {
- kind: MutationKind::BookmarkAdded { .. }
- }
- )),
- "add_bookmark must publish BookmarkAdded: {evs:?}"
- );
-
- app.delete_bookmark(0);
- let evs = app.drain_events();
- assert!(
- evs.iter().any(|e| matches!(
- e,
- GhidrustEvent::ProgramMutated {
- kind: MutationKind::BookmarkRemoved { .. }
- }
- )),
- "delete_bookmark must publish BookmarkRemoved: {evs:?}"
- );
-
- // Drain again → empty.
- assert!(app.drain_events().is_empty());
- }
-
- /// provider pane toggles are per-kind and persist through frames.
- #[test]
- fn toggle_pane_state_persists() {
- let mut app = GhidrustApp::headless();
- for k in PaneKind::ALL {
- assert!(
- !app.is_pane_open(*k),
- "pane {:?} default should be closed",
- k
- );
- }
- app.toggle_pane(PaneKind::MemoryMap, true);
- app.toggle_pane(PaneKind::SymbolTable, true);
- assert!(app.is_pane_open(PaneKind::MemoryMap));
- assert!(app.is_pane_open(PaneKind::SymbolTable));
- assert!(!app.is_pane_open(PaneKind::FunctionGraph));
- app.toggle_pane(PaneKind::MemoryMap, false);
- assert!(!app.is_pane_open(PaneKind::MemoryMap));
- }
-
- #[test]
- fn project_tree_open_and_status_via_shipped_apis() {
- let dir = std::env::temp_dir().join(format!("ghidrust_ptree_{}", std::process::id()));
- let _ = std::fs::remove_dir_all(&dir);
- let mut app = GhidrustApp::headless();
- app.project_dir_input = dir.display().to_string();
- app.project_name_input = "TreeUX".into();
- app.create_project.expect("create");
- assert!(app.show_project_tree);
-
- app.path_input = fixture_path("tiny_x64.pe").display.to_string();
- app.import_into_project.expect("import tiny");
- app.path_input = fixture_path("analysis_lab.pe").display.to_string();
- app.import_into_project.expect("import lab");
-
- let tree = app.project_tree_model.expect("tree model");
- assert_eq!(tree.project_name, "TreeUX");
- assert_eq!(tree.files.len(), 2);
- assert!(tree.files.iter().any(|f| f.active));
- assert!(tree.files.iter().all(|f| !f.has_saved_analysis));
- assert_eq!(tree.files[0].status_label, "Not analyzed");
-
- let lab_id = tree
- .files
- .iter()
- .find(|f| f.display_name.contains("analysis_lab"))
- .map(|f| f.id.clone())
- .expect("lab id");
- app.open_from_tree(&lab_id).expect("open from tree");
- assert_eq!(app.active_file_id.as_deref(), Some(lab_id.as_str()));
- assert!(app.program.is_some());
- let tree2 = app.project_tree_model().unwrap();
- assert!(tree2.files.iter().any(|f| f.id == lab_id && f.active));
-
- for (i, info) in app.analyzer_infos.iter().enumerate() {
- app.analyzer_enabled[i] = matches!(
- info.name().as_str(),
- "Function Start Search" | "Embedded Media"
- );
- }
- // Analyze from tree opens options dialog (does not run yet).
- app.analyze_from_tree(&lab_id)
- .expect("open analyze options");
- assert!(app.show_analysis_dialog);
- assert_eq!(
- app.pending_analyze_file_id.as_deref(),
- Some(lab_id.as_str())
- );
- app.use_gpu_experimental = true;
- app.begin_analysis_job.expect("begin");
- assert!(app.analysis_job.is_some());
- assert!(app.analysis_progress_fraction().is_some());
- while app.analysis_job.is_some() {
- app.step_analysis_job_blocking.expect("step");
- }
- assert!(app.analysis_progress_fraction().is_none());
- let tree3 = app.project_tree_model().unwrap();
- let lab_row = tree3.files.iter().find(|f| f.id == lab_id).unwrap();
- assert!(lab_row.has_saved_analysis, "{lab_row:?}");
- assert_eq!(lab_row.status_label, "Analyzed");
-
- // Second run of status query consistent
- let tree4 = app.project_tree_model().unwrap();
- assert_eq!(
- tree3
- .files
- .iter()
- .map(|f| f.has_saved_analysis)
- .collect::<Vec<_>>(),
- tree4
- .files
- .iter()
- .map(|f| f.has_saved_analysis)
- .collect::<Vec<_>>()
- );
-
- // Delete requires confirm: request only sets pending; confirm removes.
- app.request_delete_file(&lab_id);
- assert!(app.pending_delete.is_some());
- app.cancel_delete_file();
- assert!(app.pending_delete.is_none());
- assert_eq!(app.project_tree_model().unwrap().files.len(), 2);
- app.request_delete_file(&lab_id);
- app.confirm_delete_file.expect("confirm delete");
- assert!(app.pending_delete.is_none());
- let after = app.project_tree_model().unwrap();
- assert_eq!(after.files.len(), 1);
- assert!(!after.files.iter().any(|f| f.id == lab_id));
-
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn headless_load_and_analyze_uses_core() {
- let mut app = GhidrustApp::headless();
- assert_eq!(app.theme, ThemeMode::Dark);
- app.theme = app.theme.toggle();
- assert_eq!(app.theme, ThemeMode::Light);
-
- let pe = fixture_path("tiny_x64.pe");
- app.load_binary(&pe).expect("load");
- assert!(app.listing.iter().any(|i| i.mnemonic == "push"));
-
- for (i, info) in app.analyzer_infos.iter().enumerate() {
- app.analyzer_enabled[i] = matches!(
- info.name().as_str(),
- "ASCII Strings" | "WindowsPE x86 PE RTTI Analyzer"
- );
- }
- app.run_selected_analysis.expect("analyze");
- assert!(app.rtti.classes.iter().any(|c| c.name() == "Widget"));
- assert!(!app.strings.is_empty());
- assert_eq!(app.analyzer_infos.len(), ANALYZER_NAMES.len());
- }
-
- #[test]
- fn headless_stage0_decompiler_wires_on_focus() {
- // Stage-1 is the GUI default. The old assertion demanded a
- // Stage-0-style `void foo` / `block_N` marker; Stage-1 emits typed
- // return values (e.g. `uint32_t FUN_..(void)`) so we accept either
- // stage marker plus the Stage-1 self-identification header.
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- assert!(
- !app.decomp_text.is_empty(),
- "load should seed decompiler text"
- );
- assert!(!app.decomp_text.contains("Not yet implemented"));
-
- let va = app.listing[0].address;
- app.refresh_decompiler_at(va);
- assert!(app.decomp_entry.is_some());
- let text = &app.decomp_text;
- assert!(
- text.contains("void ")
- || text.contains("uint")
- || text.contains("int32_t")
- || text.contains("int64_t")
- || text.contains("block_"),
- "expected typed function header or block label:\n{text}"
- );
-
- let entry = app.decomp_entry.unwrap();
- app.focus_function(entry);
- assert_eq!(app.center, CenterPane::Decompiler);
- assert_eq!(app.listing_focus_va, Some(entry));
- assert!(!app.decomp_text.is_empty());
- }
-
- #[test]
- fn headless_project_import_analyze_save() {
- let dir = std::env::temp_dir().join(format!("ghidrust_gui_proj_{}", std::process::id));
- let _ = std::fs::remove_dir_all(&dir);
- let mut app = GhidrustApp::headless();
- app.project_dir_input = dir.display().to_string();
- app.project_name_input = "GuiTest".into();
- app.create_project.expect("create");
- app.path_input = fixture_path("analysis_lab.pe").display.to_string();
- app.import_into_project.expect("import");
- assert!(app.program.is_some());
- for (i, info) in app.analyzer_infos.iter().enumerate() {
- app.analyzer_enabled[i] = matches!(
- info.name().as_str(),
- "Function Start Search" | "Embedded Media"
- );
- }
- app.run_selected_analysis.expect("analyze");
- app.save_results.expect("save");
- let id = app.active_file_id.clone().unwrap();
- let proj = app.project.as_ref().unwrap();
- assert!(proj.analysis_path(&id).is_file());
- assert!(proj.listing_export_path(&id).is_file());
- // reopen
- let mut app2 = GhidrustApp::headless();
- app2.project_dir_input = dir.display().to_string();
- app2.open_project.expect("reopen");
- assert!(app2.program.is_some());
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn source_embeds_m3_and_menus() {
- // Structural: shipped source contains theme toggle + menus (fallback evidence).
- let src = include_str!("main.rs");
- assert!(src.contains("Theme: Dark") || src.contains("ThemeMode"));
- assert!(src.contains("menu_button(\"File\""));
- assert!(src.contains("Program Tree"));
- assert!(src.contains("Project Tree") || src.contains("project_tree"));
- assert!(src.contains("Decompiler"));
- assert!(src.contains("refresh_decompiler_at") || src.contains("stage0_pseudo_c"));
- assert!(src.contains("focus_function"));
- assert!(src.contains("Stage-0"));
- assert!(src.contains("decomp_scroll") || src.contains("decomp_text"));
- assert!(src.contains("ASCII Strings"));
- assert!(src.contains("Analyzed") || src.contains("has_saved_analysis"));
- assert!(src.contains("analyze_from_tree") || src.contains("small_button(\"Analyze\")"));
- assert!(
- src.contains("Browse") || src.contains("browse_binary_path") || src.contains("rfd::")
- );
- assert!(src.contains("pending_delete") || src.contains("Delete from project"));
- assert!(src.contains("use_gpu_experimental") || src.contains("GPU experimental"));
- assert!(src.contains("analyzer_supports_gpu"));
- assert!(src.contains("CPU only") || src.contains("\"GPU\""));
- assert!(src.contains("m3_linear_progress") || src.contains("Analysis progress"));
- assert!(src.contains("begin_analysis_job") || src.contains("Run Analysis"));
- assert!(src.contains("Overview") || src.contains("ui_overview"));
- assert!(src.contains("show_rows") || src.contains("rtti_filtered_idx"));
- assert!(src.contains("analysis_done_banner") || src.contains("Analysis complete"));
- assert!(src.contains("double_clicked") && src.contains("open_id"));
- assert!(src.contains("show_startup_picker") || src.contains("ui_startup_picker"));
- assert!(src.contains("recent_projects") || src.contains("Open existing project"));
- // No emoji codepoints in this file (Material geometry lives in icons.rs)
- // U+1F4C1 folder, U+25CF/U+25CB bullets, U+25B6 play — use escapes so the
- // forbidden glyphs themselves never appear in source.
- assert!(!src.contains('\u{1F4C1}'));
- assert!(!src.contains('\u{25CF}'));
- assert!(!src.contains('\u{25CB}'));
- assert!(!src.contains('\u{25B6}'));
- }
-
- #[test]
- fn icons_module_is_material_not_emoji() {
- let icons = include_str!("icons.rs");
- assert!(icons.contains("Material"));
- assert!(icons.contains("Folder") || icons.contains("folder"));
- assert!(!icons.contains('\u{1F4C1}'));
- assert!(!icons.contains('\u{25CF}'));
- }
-
- #[test]
- fn former_menu_stubs_are_wired_not_nyi_only() {
- let src = include_str!("main.rs");
- // No remaining nyi for inventoried Edit/Nav/Search/Select/Tools stubs
- assert!(!src.contains("nyi(\"Edit → Undo\")"));
- assert!(!src.contains("nyi(\"Edit → Redo\")"));
- assert!(!src.contains("nyi(\"Edit → Clear selection\")"));
- assert!(!src.contains("nyi(\"Navigation → Go to address\")"));
- assert!(!src.contains("nyi(\"Search → Search memory\")"));
- assert!(!src.contains("nyi(\"Search → Search program text\")"));
- assert!(!src.contains("nyi(\"Select → Select all\")"));
- assert!(!src.contains("nyi(\"Tools → Processor options\")"));
- // Real handlers present
- assert!(src.contains("edit_undo"));
- assert!(src.contains("edit_redo"));
- assert!(src.contains("edit_clear_selection"));
- assert!(src.contains("goto_address_str") || src.contains("show_goto_dialog"));
- assert!(src.contains("run_search_memory"));
- assert!(src.contains("run_search_text"));
- assert!(src.contains("select_all_listing"));
- assert!(src.contains("show_processor_dialog"));
- }
-
- #[test]
- fn menu_actions_goto_search_select_on_loaded_program() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- assert!(!app.listing.is_empty());
-
- app.select_all_listing();
- assert!(!app.listing_selection.is_empty());
- assert!(app.listing_selection.contains(0));
-
- app.edit_clear_selection();
- assert!(app.listing_selection.is_empty());
-
- app.select_all_listing();
- app.edit_undo();
- assert!(app.listing_selection.is_empty());
- app.edit_redo();
- assert!(!app.listing_selection.is_empty());
-
- let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.goto_address_str(&format!("{entry:#x}")).expect("goto");
- assert_eq!(app.listing_focus_va, Some(entry));
- assert_eq!(app.center, CenterPane::Listing);
-
- app.search_memory_input = "55 48 89 e5".into();
- app.run_search_memory.expect("mem search");
- assert!(!app.memory_hits.is_empty());
- assert!(app.show_search_results);
-
- app.search_text_input = "push".into();
- app.run_search_text.expect("text search");
- assert!(!app.text_hits.is_empty());
-
- app.show_processor_dialog = true;
- let info = processor_info(app.program.as_ref().unwrap());
- assert!(info.language.contains("x86"));
- }
-
- // ─── token model, listing sync, view filter, next/prev fn ───
-
- #[test]
- fn decompiler_tokens_are_populated_and_cross_highlight() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.refresh_decompiler_at(entry);
- assert!(
- !app.decomp_lines.is_empty(),
- "token cache must be populated after refresh_decompiler_at"
- );
- // Default GUI stage is Stage-1; the emitter drops
- // `block_N:` labels in favour of structured regions. Assert only
- // that we see at least one keyword token — the shape common to
- // every stage.
- let all_tokens: Vec<&TokenKind> = app
- .decomp_lines
- .iter()
- .flat_map(|l| l.tokens.iter().map(|t| &t.kind))
- .collect();
- assert!(
- all_tokens.iter().any(|k| matches!(k, TokenKind::Keyword)),
- "expected at least one Keyword (void/return/etc)"
- );
- // Cross-highlight line should be recomputable and match what the
- // decoder found for the entry VA (may be None if Stage-1 emit
- // stripped per-line addresses, but the field remains consistent).
- let ln = decomp_line_for_va(&app.decomp_lines, entry);
- assert_eq!(app.decomp_cross_line, ln);
- }
-
- #[test]
- fn navigate_next_prev_function_wraps() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("analysis_lab.pe"))
- .expect("load");
- // Fake up two functions if the analyzer didn't produce any yet.
- if app.program.as_ref().unwrap().analysis.functions.is_empty() {
- let prog = app.program.as_mut().unwrap();
- let base = prog.entry.unwrap_or(prog.image_base);
- prog.analysis
- .functions
- .push(ghidrust_core::FunctionInfo::new(base, base + 0x10, "fn_a"));
- prog.analysis
- .functions
- .push(ghidrust_core::FunctionInfo::new(
- base + 0x40,
- base + 0x50,
- "fn_b",
- ));
- }
- let entries: Vec<u64> = app
- .program
- .as_ref()
- .unwrap()
- .analysis
- .functions
- .iter()
- .map(|f| f.entry)
- .collect();
- let mut sorted = entries.clone();
- sorted.sort();
- let first = sorted[0];
- app.listing_focus_va = Some(first);
- app.nav_next_function();
- // Cursor should have moved to another function entry (or wrapped).
- assert!(sorted.contains(&app.listing_focus_va.unwrap()));
- }
-
- #[test]
- fn program_tree_view_filter_hides_addresses() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- // Grab a block name & VA.
- let (block_name, block_va) = {
- let p = app.program.as_ref().unwrap();
- let b = p.blocks.first().unwrap();
- (b.name().clone(), b.va)
- };
- assert!(app.addr_in_view(block_va));
- let mut set = BTreeSet::new();
- set.insert("__does_not_exist__".to_string());
- app.set_listing_view(Some(set));
- assert!(!app.addr_in_view(block_va), "filter set must hide addr");
- app.add_to_view(block_name.clone());
- assert!(app.addr_in_view(block_va));
- app.remove_from_view(&block_name);
- assert!(!app.addr_in_view(block_va));
- app.clear_view_filter();
- assert!(app.addr_in_view(block_va));
- }
-
- #[test]
- fn imports_exports_are_honest_empty_or_analyzer_derived() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let (imports, exports) = app.imports_exports();
- // Never panics; results are analyzer-driven not fabricated.
- for (va, _name) in imports.iter().chain(exports.iter()) {
- // If any row exists it must be a plausible in-image VA.
- let in_program = app
- .program
- .as_ref()
- .map(|p| p.contains_va(*va))
- .unwrap_or(false);
- assert!(in_program || *va == 0);
- }
- }
-
- // ─── rename / retype / comment / signature / type ───
-
- #[test]
- fn rename_persists_and_reflects_in_analysis() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- // Attach a synthetic function so we have a rename target.
- let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- {
- let prog = app.program.as_mut().unwrap();
- prog.analysis
- .functions
- .push(ghidrust_core::FunctionInfo::new(
- entry,
- entry + 0x10,
- "FUN_original",
- ));
- }
- app.rename_at(entry, "my_main").expect("rename");
- let p = app.program.as_ref().unwrap();
- assert_eq!(p.edits.rename_at(entry), Some("my_main"));
- assert_eq!(
- p.function_at(entry).map(|f| f.name().as_str()),
- Some("my_main")
- );
- assert_eq!(
- p.display_function_name_at(entry).as_deref(),
- Some("my_main")
- );
- // Empty rename clears the edit and rejects with error.
- let err = app.rename_at(entry, "");
- assert!(err.is_err());
- }
-
- #[test]
- fn retype_and_comment_and_signature_persist() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.retype_at(va, "int32_t").expect("retype");
- app.set_comment_at(va, CommentKind::Eol, "eol comment")
- .expect("comment");
- app.set_comment_at(va, CommentKind::Plate, "plate!")
- .expect("plate");
- app.set_function_signature(va, "int foo(char *)")
- .expect("sig");
- let p = app.program.as_ref().unwrap();
- assert_eq!(p.edits.retype_at(va), Some("int32_t"));
- assert_eq!(
- p.edits.comment_at(va, CommentKind::Eol),
- Some("eol comment")
- );
- assert_eq!(p.edits.comment_at(va, CommentKind::Plate), Some("plate!"));
- assert_eq!(
- p.edits.function_signature(va).map(|s| s.signature.as_str()),
- Some("int foo(char *)")
- );
- }
-
- #[test]
- fn commit_params_and_locals_snapshot_analyzer_state() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- {
- let prog = app.program.as_mut().unwrap();
- let mut fi = ghidrust_core::FunctionInfo::new(entry, entry + 0x40, "with_params");
- fi.calling_convention = Some("windowsx64".into());
- fi.parameters = vec!["rcx".into(), "rdx".into()];
- fi.stack_locals = vec!["local_10".into(), "local_18".into()];
- prog.analysis.functions.push(fi);
- }
- app.commit_params_return(entry).expect("commit params");
- app.commit_locals(entry).expect("commit locals");
- let sig = app
- .program
- .as_ref()
- .unwrap()
- .edits
- .function_signature(entry)
- .unwrap();
- assert_eq!(sig.parameters.len(), 2);
- assert_eq!(sig.locals.len(), 2);
- assert_eq!(sig.return_type.as_deref(), Some("undefined"));
- }
-
- #[test]
- fn user_types_and_applied_types_persist() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- app.define_user_type("Widget", "struct Widget { int id; }")
- .expect("new type");
- let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.apply_type_at(va, "Widget").expect("apply");
- let p = app.program.as_ref().unwrap();
- assert!(p.edits.user_types.contains_key("Widget"));
- assert_eq!(p.edits.applied_type_at(va), Some("Widget"));
- }
-
- #[test]
- fn dtm_builtins_contain_stage0_types() {
- for want in [
- "byte", "word", "dword", "qword", "char", "int", "int32_t", "pointer",
- ] {
- assert!(
- BUILTIN_TYPES.contains(&want),
- "expected {want} in DTM Built-In archive"
- );
- }
- }
-
- #[test]
- fn console_severity_tracks_log_calls() {
- let mut app = GhidrustApp::headless();
- // Preseeded with 1 info line.
- assert_eq!(app.console.len(), 1);
- assert_eq!(app.console_severity.len(), 1);
- app.log("info");
- app.log_warn("warn");
- app.log_error("boom");
- assert_eq!(
- app.console_severity.last().copied(),
- Some(ConsoleSeverity::Error)
- );
- assert!(app
- .console_severity
- .iter()
- .any(|s| *s == ConsoleSeverity::Warn));
- assert_eq!(app.console.len(), 4);
- }
-
- #[test]
- fn scalar_and_address_hints_extract_first_literal() {
- assert!(first_scalar_hint("rax, 0x1234").unwrap().contains("0x1234"));
- assert!(first_scalar_hint("rax, 42").unwrap().contains("dec 42"));
- assert!(first_address_hint("0x140001000")
- .unwrap()
- .contains("0x140001000"));
- assert!(first_scalar_hint("rax, rbx").is_none());
- }
-
- // ─── polish — DTM editing / chooser / persistence ────
-
- #[test]
- fn rename_and_delete_user_type_rewrites_applied_types() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.define_user_type("Widget", "Structure\nint id;")
- .expect("define");
- app.apply_type_at(va, "Widget").expect("apply");
-
- // Rename user type must rewrite the applied-types decoration.
- app.rename_user_type("Widget", "Gadget").expect("rename");
- let p = app.program.as_ref().unwrap();
- assert!(p.edits.user_types.contains_key("Gadget"));
- assert_eq!(p.edits.applied_type_at(va), Some("Gadget"));
-
- // Delete user type must clear the applied decoration too.
- app.delete_user_type("Gadget").expect("delete");
- let p = app.program.as_ref().unwrap();
- assert!(p.edits.user_types.is_empty());
- assert!(p.edits.applied_type_at(va).is_none());
- }
-
- #[test]
- fn edit_user_type_supports_rename_and_body_swap() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- app.define_user_type("Widget", "Structure\nint a;")
- .expect("define");
- app.edit_user_type("Widget", "WidgetV2", "Structure\nint a;\nint b;")
- .expect("edit");
- let p = app.program.as_ref().unwrap();
- assert!(!p.edits.user_types.contains_key("Widget"));
- assert!(p.edits.user_types.contains_key("WidgetV2"));
- assert!(p.edits.user_type("WidgetV2").unwrap().contains("int b;"));
- // Editing a non-existent type must fail rather than silently create.
- assert!(app.edit_user_type("nope", "x", "y").is_err());
- }
-
- #[test]
- fn new_typedef_on_and_pointer_to_register_user_types() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let td = app.new_typedef_on("int32_t").expect("typedef");
- let pt = app.new_pointer_to("int32_t").expect("pointer");
- let p = app.program.as_ref().unwrap();
- assert!(p.edits.user_types.contains_key(&td));
- assert!(p.edits.user_types.contains_key(&pt));
- assert!(pt.ends_with('*'));
- }
-
- #[test]
- fn type_chooser_dialog_opens_with_target_va() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
- assert!(!app.show_type_chooser_dialog);
- app.open_type_chooser(Some(va));
- assert!(app.show_type_chooser_dialog);
- assert_eq!(app.type_chooser_target_va, Some(va));
- }
-
- #[test]
- fn edit_type_dialog_preloads_body() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- app.define_user_type("Foo", "Structure\nint x;")
- .expect("define");
- app.open_edit_type_dialog("Foo");
- assert!(app.show_edit_type_dialog);
- assert_eq!(app.edit_type_dialog_orig_name, "Foo");
- assert_eq!(app.edit_type_dialog_name, "Foo");
- assert!(app.edit_type_dialog_body.contains("int x;"));
- }
-
- #[test]
- fn all_five_comment_kinds_render_edits_into_program() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
- for k in CommentKind::ALL {
- app.set_comment_at(va, *k, format!("k={}", k.label))
- .expect("comment");
- }
- let p = app.program.as_ref().unwrap();
- for k in CommentKind::ALL {
- assert_eq!(
- p.edits.comment_at(va, *k),
- Some(format!("k={}", k.label).as_str())
- );
- }
- assert_eq!(p.edits.comments_at(va).len(), CommentKind::ALL.len());
- }
-
- #[test]
- fn program_edits_persist_across_project_save_and_load() {
- use ghidrust_core::Project;
-
- let dir =
- std::env::temp_dir().join(format!("ghidrust_gui_edits_rt_{}", std::process::id()));
- let _ = std::fs::remove_dir_all(&dir);
- let mut proj = Project::create(&dir, "GuiEditRt").expect("proj");
- let f = proj.import_file(fixture_path("tiny_x64.pe")).unwrap();
-
- // Session A — apply user edits then save.
- let mut app = GhidrustApp::headless();
- app.project = Some(proj);
- app.active_file_id = Some(f.id.clone());
- app.load_binary(&app.project.as_ref().unwrap().binary_path(&f))
- .expect("load");
- let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.rename_at(va, "session_a_main").expect("rename");
- app.set_comment_at(va, CommentKind::Plate, "plate!")
- .expect("comment");
- app.define_user_type("Widget", "Structure\nint id;")
- .expect("define");
- app.apply_type_at(va, "Widget").expect("apply");
- app.save_results.expect("save");
-
- // Session B — fresh app, same project, same file.
- let proj2 = Project::open(&dir).expect("reopen");
- let mut app2 = GhidrustApp::headless();
- app2.project = Some(proj2);
- app2.active_file_id = Some(f.id.clone());
- let (prog2, _saved) = app2
- .project
- .as_ref()
- .unwrap()
- .load_program_with_results(&f)
- .expect("load with results");
- app2.program = Some(prog2);
- let p = app2.program.as_ref().unwrap();
- assert_eq!(p.edits.rename_at(va), Some("session_a_main"));
- assert_eq!(p.edits.comment_at(va, CommentKind::Plate), Some("plate!"));
- assert!(p.edits.user_types.contains_key("Widget"));
- assert_eq!(p.edits.applied_type_at(va), Some("Widget"));
-
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn edit_events_invalidate_decompiler_cache() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- {
- let prog = app.program.as_mut().unwrap();
- prog.analysis
- .functions
- .push(ghidrust_core::FunctionInfo::new(entry, entry + 0x20, "fn"));
- }
- app.refresh_decompiler_at(entry);
- assert!(!app.decomp_text.is_empty());
- // A rename mutation must invalidate cache via drain_events.
- app.rename_at(entry, "renamed").expect("rename");
- let _ = app.drain_events();
- assert!(app.decomp_text.is_empty(), "cache must clear after rename");
- }
-
- #[test]
- fn goto_out_of_window_va_redisassembles_listing() {
- let mut app = GhidrustApp::headless();
- // analysis_lab has richer layout; load then go to a VA outside entry window
- app.load_binary(&fixture_path("analysis_lab.pe"))
- .expect("load");
- let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- let first_listing_va = app.listing[0].address;
- assert_eq!(first_listing_va, entry);
-
- // Pick a program block VA that is not covered by the entry listing window
- let window_end = {
- let last = app.listing.last().unwrap();
- last.address + u64::from(last.length).max(1)
- };
- let outside = app
- .program
- .as_ref()
- .unwrap()
- .blocks
- .iter()
- .map(|b| b.va)
- .find(|&va| va < first_listing_va || va >= window_end)
- .expect("need a block VA outside entry listing window");
-
- // Confirm helper says outside
- assert!(
- listing_index_at_or_before(&app.listing, outside).is_none(),
- "precondition: {outside:#x} must be outside listing [{first_listing_va:#x}.)"
- );
-
- app.goto_address_str(&format!("{outside:#x}"))
- .expect("goto outside");
- assert_eq!(app.listing_focus_va, Some(outside));
- assert!(
- !app.listing.is_empty(),
- "re-disassemble must produce listing"
- );
- assert_eq!(
- app.listing[0].address, outside,
- "listing must start at target VA after re-disassemble"
- );
- // Selection points at first insn of new window
- assert_eq!(app.listing_selection.start, Some(0));
-
- // Memory search hit navigation also refreshes when needed
- if let Some(hit) = app.memory_hits.first().cloned() {
- let _ = hit;
- }
- app.search_memory_input = "55 48 89 e5".into();
- app.run_search_memory.expect("mem");
- assert!(!app.memory_hits.is_empty());
- let hit_va = app.memory_hits[0].va;
- // Force listing back to entry-only window
- app.goto_address_str(&format!("{entry:#x}"))
- .expect("back to entry");
- assert_eq!(app.listing[0].address, entry);
- // Navigate to memory hit (may be same or different region)
- app.goto_address_str(&format!("{hit_va:#x}"))
- .expect("goto hit");
- assert!(
- app.listing.iter().any(|i| i.address == hit_va
- || (i.address <= hit_va && hit_va < i.address + u64::from(i.length))),
- "listing must cover hit VA {hit_va:#x} after goto; first={:#x}",
- app.listing[0].address
- );
- }
-
- // ─── tables, xrefs, equates, tags, search dialogs ────
-
- #[test]
- fn xrefs_to_and_from_return_honest_rows_on_fixture() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("analysis_lab.pe"))
- .expect("load");
- // xrefs_from at entry decodes and never fabricates.
- let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- let from = app.xrefs_from_va(entry);
- for r in &from {
- assert!(app.program.as_ref().unwrap().contains_va(r.to));
- assert!(r.from >= entry);
- }
-
- // Inject a fake reference so xrefs_to_va picks it up deterministically.
- {
- let prog = app.program.as_mut().unwrap();
- prog.analysis.references.push(ghidrust_core::ReferenceInfo {
- from: prog.image_base + 0x100,
- to: entry,
- kind: "call".into(),
- });
- }
- let to = app.xrefs_to_va(entry);
- assert!(to.iter().any(|r| r.kind == "call"));
- assert!(to.iter().all(|r| r.to == entry));
- }
-
- #[test]
- fn set_equate_and_edit_events_fan_out() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.set_equate(va, 1, "SW_HIDE", 0).expect("set equate");
- let p = app.program.as_ref().unwrap();
- assert_eq!(
- p.edits.equate_at(va, 1).map(|e| e.name().as_str()),
- Some("SW_HIDE")
- );
- assert_eq!(p.edits.equate_at(va, 1).map(|e| e.value), Some(0));
- // Groups & references consistent.
- let groups = p.edits.equate_groups();
- assert!(groups.iter().any(|(n, _, _)| n == "SW_HIDE"));
- // Setting empty name clears it.
- app.set_equate(va, 1, "", 0).expect("clear");
- assert!(app
- .program
- .as_ref()
- .unwrap()
- .edits
- .equate_at(va, 1)
- .is_none());
- }
-
- #[test]
- fn function_tags_add_remove_delete_via_app() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.add_function_tag(entry, "MALLOC").expect("add");
- app.add_function_tag(entry, "SANITIZED").expect("add");
- let p = app.program.as_ref().unwrap();
- assert!(p.edits.function_has_tag(entry, "MALLOC"));
- assert!(p.edits.function_has_tag(entry, "SANITIZED"));
- assert!(p.edits.all_function_tags.contains("MALLOC"));
- app.remove_function_tag(entry, "MALLOC").expect("remove");
- assert!(!app
- .program
- .as_ref()
- .unwrap()
- .edits
- .function_has_tag(entry, "MALLOC"));
- // Delete-everywhere strips from universe.
- app.delete_tag_everywhere("SANITIZED").expect("delete");
- assert!(!app
- .program
- .as_ref()
- .unwrap()
- .edits
- .all_function_tags
- .contains("SANITIZED"));
- }
-
- #[test]
- fn search_scalars_dialog_runs_range_over_listing() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- app.search_scalars_min = "0".into();
- app.search_scalars_max = "0xffff".into();
- app.run_search_scalars.expect("scalars");
- // Fixture may or may not include a scalar in this range; the runner
- // must still succeed and populate text_hits deterministically.
- assert!(app.show_search_results);
- }
-
- #[test]
- fn search_instruction_patterns_filters_listing() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- // tiny_x64 has a `push rbp` prologue; filter should hit it.
- app.search_insn_mnemonic = "push".into();
- app.search_insn_operands.clear();
- app.run_search_instruction_patterns.expect("insn");
- assert!(!app.text_hits.is_empty());
- assert!(app.text_hits.iter().any(|h| h.kind == "insn"));
- }
-
- #[test]
- fn address_tables_hits_appear_after_analyzer_populates() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- {
- let prog = app.program.as_mut().unwrap();
- prog.analysis
- .address_tables
- .push(ghidrust_core::AddressTableInfo {
- base: prog.image_base,
- count: 3,
- entries: vec![prog.image_base, prog.image_base + 8, prog.image_base + 16],
- role: ghidrust_core::AddressTableRole::Unknown,
- });
- }
- let hits = address_table_hits(app.program.as_ref().unwrap());
- assert_eq!(hits.len(), 1);
- assert!(hits[0].text.contains("3 entries"));
- }
-
- #[test]
- fn compute_checksums_round_trip_whole_image() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- app.compute_checksums(ChecksumMode::WholeImage)
- .expect("checksum");
- let r = app.checksum_last.as_ref().unwrap();
- assert!(r.len > 0);
- assert!(r.crc32 != 0);
- assert!(r.adler32 != 0);
- // Deterministic: re-running yields the same values.
- let first = r.clone();
- app.compute_checksums(ChecksumMode::WholeImage)
- .expect("checksum");
- assert_eq!(app.checksum_last.as_ref().unwrap(), &first);
- }
-
- #[test]
- fn bytes_pane_state_defaults_and_follow_cursor() {
- let mut app = GhidrustApp::headless();
- assert_eq!(app.bytes_pane_bpr, 16);
- assert!(app.bytes_pane_va.is_none());
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- // Programmatic follow — reflects listing_focus.
- app.listing_focus_va = app.program.as_ref().and_then(|p| p.entry);
- app.bytes_pane_va = app.listing_focus_va;
- assert!(app.bytes_pane_va.is_some());
- }
-
- #[test]
- fn parse_scalar_input_hex_and_dec_and_signed() {
- let app = GhidrustApp::headless();
- assert_eq!(app.parse_scalar_input("0x1234").unwrap(), 0x1234);
- assert_eq!(app.parse_scalar_input("42").unwrap(), 42);
- assert_eq!(app.parse_scalar_input("-0x10").unwrap(), -0x10);
- assert!(app.parse_scalar_input("").is_err());
- }
-
- // ── Graphs & maps ─────────────────────────────────────
-
- /// Function Graph derives Stage-0 blocks + edges from the
- /// currently-focused function's CFG (honest empty if the region has
- /// no recovered blocks).
- #[test]
- fn function_graph_pane_layouts_stage0_cfg() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.focus_function(entry);
-
- let view = eframe::egui::Rect::from_min_size(
- eframe::egui::Pos2::ZERO,
- eframe::egui::Vec2::new(1000.0, 600.0),
- );
- let (blocks, edges) = graphs::layout_function_graph(
- app.program.as_ref().unwrap(),
- entry,
- STAGE0_MAX_INSNS,
- FunctionGraphLayout::Hierarchical,
- view,
- );
- // Honest-empty is acceptable, but if blocks land they must all
- // have positive rects.
- for b in &blocks {
- assert!(b.rect.width() > 0.0);
- }
- for e in &edges {
- assert!(e.from < blocks.len().max(1));
- }
- }
-
- /// Function Call Graph roots at the current function with
- /// level 0; expansion levels are session-only settings.
- #[test]
- fn call_graph_state_settings_persist_across_frames() {
- let mut app = GhidrustApp::headless();
- assert_eq!(app.graph_state.call_graph_levels_in, 0);
- assert_eq!(app.graph_state.call_graph_levels_out, 0);
- app.graph_state.call_graph_levels_in = 2;
- app.graph_state.call_graph_levels_out = 1;
- assert_eq!(app.graph_state.call_graph_levels_in, 2);
- }
-
- /// Editable Memory Map: RWX toggles + add + delete flow.
- #[test]
- fn memory_map_edit_flow_adds_and_deletes_blocks() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let n0 = app.program.as_ref().unwrap().blocks.len();
- // Add a synthetic RWX block at 0x900000.
- app.program
- .as_mut()
- .unwrap()
- .blocks
- .push(ghidrust_core::MemoryBlock {
- name: "synthetic".into(),
- va: 0x900000,
- size: 0x100,
- bytes: vec![0u8; 0x100],
- readable: true,
- writable: true,
- executable: true,
- });
- assert_eq!(app.program.as_ref().unwrap().blocks.len(), n0 + 1);
- // Flip its RWX (via the field, mirrors the UI checkbox mutation).
- let idx = app.program.as_ref().unwrap().blocks.len() - 1;
- {
- let b = &mut app.program.as_mut().unwrap().blocks[idx];
- b.writable = !b.writable;
- assert!(!b.writable);
- }
- app.program.as_mut().unwrap().blocks.remove(idx);
- assert_eq!(app.program.as_ref().unwrap().blocks.len(), n0);
- }
-
- /// Register Manager lattice is present and set/clear works.
- #[test]
- fn register_manager_lattice_and_values() {
- let mut app = GhidrustApp::headless();
- assert!(app.register_manager.values().is_empty());
- app.register_manager.selected = Some("RAX".into());
- app.register_manager
- .values()
- .push(register_manager::RegisterValueRow {
- register: "RAX".into(),
- start_va: 0x1000,
- end_va: 0x1100,
- value: "0x2a".into(),
- });
- assert_eq!(app.register_manager.values().len(), 1);
- }
-
- /// Entropy strip samples cover mapped bytes without fabricating.
- #[test]
- fn entropy_samples_cover_mapped_blocks() {
- let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let s = entropy::entropy_samples(app.program.as_ref().unwrap(), 256);
- assert!(!s.is_empty());
- for w in s.windows(2) {
- assert!(w[0].va <= w[1].va);
- }
- }
-
- // ── Scripts ───────────────────────────────────────────
-
- #[test]
- fn script_manager_catalog_is_populated_from_mcp_surface() {
- let app = GhidrustApp::headless();
- assert!(!app.script_manager.catalog.is_empty());
- assert!(app
- .script_manager
- .catalog
- .iter()
- .any(|s| s.name() == "mcp.list_functions"));
- }
-
- #[test]
- fn text_editor_lifecycle_open_edit_close() {
- let mut app = GhidrustApp::headless();
- app.text_editor.open_untitled();
- assert_eq!(app.text_editor.tabs.len(), 1);
- app.text_editor.tabs[0].body.push_str("body");
- app.text_editor.tabs[0].dirty = true;
- app.text_editor.close_active();
- assert_eq!(app.text_editor.tabs.len(), 0);
- }
-
- #[test]
- fn mcp_repl_submit_records_prompt_and_response() {
- let mut app = GhidrustApp::headless();
- app.mcp_repl.input = "mcp.list_functions".into();
- app.mcp_repl.submit();
- assert_eq!(app.mcp_repl.transcript.len(), 2);
- assert!(app.mcp_repl.transcript[0].prompt);
- assert!(!app.mcp_repl.transcript[1].prompt);
- }
-
- // ── Debugger visibility ──────────────────────────────
-
- #[test]
- fn debugger_host_enumerated_in_shell_panes() {
- let panes = GhidrustApp::shell_panes();
- assert!(
- panes.contains(&"Debugger"),
- "shell_panes missing tabbed Debugger host; full list = {panes:?}",
- );
- }
-
- #[test]
- fn debugger_menu_is_registered_in_shell() {
- let menus = GhidrustApp::shell_menus();
- assert!(menus.contains(&"Debugger"));
- }
-
- #[test]
- fn debugger_breakpoint_and_watch_state_persist_session_only() {
- let mut app = GhidrustApp::headless();
- assert!(app.debugger.breakpoints.is_empty());
- app.debugger.toggle_breakpoint(0x1000);
- app.debugger.toggle_breakpoint(0x2000);
- assert_eq!(app.debugger.breakpoints.len(), 2);
- assert!(app.debugger.has_breakpoint(0x1000));
- app.debugger.toggle_breakpoint(0x1000);
- assert!(!app.debugger.has_breakpoint(0x1000));
-
- app.debugger.add_watch("rax");
- app.debugger.add_watch("rax"); // dedup
- app.debugger.add_watch("*(int*)rsp");
- assert_eq!(app.debugger.watches.len(), 2);
- }
-
- // ── Docking / layouts ────────────────────────────────
-
- #[test]
- fn save_and_restore_layout_round_trip() {
- // Use a fresh %APPDATA%/ghidrust equivalent to keep test hermetic.
- let dir = std::env::temp_dir().join(format!("ghidrust_layouts_{}", std::process::id()));
- let _ = std::fs::remove_dir_all(&dir);
- // Point APPDATA at our sandbox so layouts write here.
- let prev = std::env::var("APPDATA").ok();
- // Only override APPDATA when it's the layout-dir resolver we care about.
- std::env::set_var("APPDATA", &dir);
- struct RestoreAppdata(Option<String>);
- impl Drop for RestoreAppdata {
- fn drop(&mut self) {
- if let Some(p) = &self.0 {
- std::env::set_var("APPDATA", p);
- } else {
- std::env::remove_var("APPDATA");
- }
- }
- }
- let _guard = RestoreAppdata(prev);
-
- let mut app = GhidrustApp::headless();
- // Flip a few state bits so we can prove the round-trip.
- app.toggle_pane(PaneKind::Bookmarks, true);
- app.toggle_pane(PaneKind::MemoryMap, true);
- app.debugger.host_open = true;
- app.debugger.enabled = true;
- app.debugger.active_tab = DebuggerPane::Targets;
- app.focus_center_tab(DockTab::Decompiler);
- app.show_console = false;
-
- app.save_layout_named("myTest").expect("save layout");
- // Flip everything back so restore has something to change.
- app.toggle_pane(PaneKind::Bookmarks, false);
- app.toggle_pane(PaneKind::MemoryMap, false);
- app.debugger.host_open = false;
- app.debugger.enabled = false;
- app.debugger.active_tab = DebuggerPane::Stack;
- app.focus_center_tab(DockTab::Overview);
- app.show_console = true;
-
- app.restore_layout_named("myTest").expect("restore layout");
- assert!(app.is_pane_open(PaneKind::Bookmarks));
- assert!(app.is_pane_open(PaneKind::MemoryMap));
- assert!(app.debugger.host_open);
- assert!(app.debugger.enabled);
- assert_eq!(app.debugger.active_tab, DebuggerPane::Targets);
- 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);
- }
-
- #[test]
- fn configure_dialog_state_defaults_closed() {
- let app = GhidrustApp::headless();
- assert!(!app.show_configure_dialog);
- assert!(!app.show_layouts_dialog);
- }
-
- #[test]
- fn graph_debugger_configure_menu_actions_wired_not_nyi() {
- let src = include_str!("main.rs");
- // Graph menu items open panes (not nyi).
- assert!(!src.contains("nyi(\"Graph → Function Graph\""));
- assert!(!src.contains("nyi(\"Graph → Function Call Graph\""));
- assert!(!src.contains("nyi(\"Graph → Function Call Trees\""));
- // Debugger menu is registered.
- assert!(src.contains("ui.menu_button(\"Debugger\","));
- // Launch is wired (not nyi).
- assert!(src.contains("open_launch_ui"));
- assert!(!src.contains("nyi(\"Debugger → Launch"));
- // Configure dialog + Save Tool Layout menu items are wired.
- assert!(src.contains("show_configure_dialog"));
- assert!(src.contains("show_layouts_dialog"));
- }
+ ghidrust_gui::run()
}
diff --git a/crates/ghidrust-gui/src/mcp_host.rs b/crates/ghidrust-gui/src/mcp_host.rs
new file mode 100644
index 0000000..bc310e6
--- /dev/null
+++ b/crates/ghidrust-gui/src/mcp_host.rs
@@ -0,0 +1,749 @@
+//! Spawn `ghidrust` / `ghidrust mcp` for Script Manager + MCP REPL.
+//!
+//! Prefers a one-shot CLI mapping when args are sufficient; otherwise runs
+//! JSON-RPC `initialize` + `tools/call` over `ghidrust mcp` stdio. Network
+//! (`net_*`) tools are rejected here — use the Network host panes instead.
+
+use serde_json::{json, Value};
+use std::io::{BufRead, BufReader, Write};
+use std::path::PathBuf;
+use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
+
+/// Resolve workspace / PATH `ghidrust` (`ghidrust.exe` on Windows).
+pub fn resolve_cli_bin() -> Result<PathBuf, String> {
+ ghidrust_agent::resolve_ghidrust_cli_bin().ok_or_else(|| {
+ "ghidrust CLI not found next to the GUI or on PATH — build \
+ `cargo build -p ghidrust-cli` (debug/release) so Script Manager / MCP REPL can run"
+ .into()
+ })
+}
+
+fn reject_net(tool: &str) -> Result<(), String> {
+ if tool.starts_with("net_") {
+ Err(format!(
+ "refusing `{tool}` — network tools are not wired in Script Manager / MCP REPL"
+ ))
+ } else {
+ Ok(())
+ }
+}
+
+/// Normalize tool names typed with a legacy `mcp.` prefix.
+pub fn normalize_tool_name(name: &str) -> &str {
+ name.strip_prefix("mcp.").unwrap_or(name)
+}
+
+/// Parse `tool_name` or `tool_name {json}` (optional leading `mcp.`).
+pub fn parse_tool_line(line: &str) -> Result<(String, Value), String> {
+ let line = line.trim();
+ if line.is_empty() {
+ return Err("empty tool line".into());
+ }
+ let rest = normalize_tool_name(line);
+ if let Some(brace) = rest.find('{') {
+ let name = rest[..brace].trim();
+ if name.is_empty() {
+ return Err("missing tool name before JSON arguments".into());
+ }
+ let args: Value = serde_json::from_str(rest[brace..].trim())
+ .map_err(|e| format!("invalid tool JSON arguments: {e}"))?;
+ if !args.is_object() {
+ return Err("tool arguments must be a JSON object".into());
+ }
+ Ok((name.to_string(), args))
+ } else {
+ let name = rest
+ .split_whitespace()
+ .next()
+ .unwrap_or("")
+ .trim()
+ .to_string();
+ if name.is_empty() {
+ return Err("missing tool name".into());
+ }
+ Ok((name, json!({})))
+ }
+}
+
+/// Map MCP tool + args → CLI argv (without the binary). `None` → use MCP stdio.
+pub fn cli_args_for_tool(tool: &str, args: &Value) -> Option<Vec<String>> {
+ let path = args.get("path").and_then(|v| v.as_str());
+ let addr = args
+ .get("addr")
+ .or_else(|| args.get("address"))
+ .and_then(|v| v.as_str());
+ let sid = args
+ .get("session_id")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
+ let push_json = |v: &mut Vec<String>| v.push("--json".into());
+
+ match tool {
+ "server_info" => Some(vec!["version".into(), "--json".into()]),
+ "list_analyzers" => Some(vec!["analyzers".into(), "--json".into()]),
+ "list_gpu_strategies" => Some(vec!["analyzer-bench-matrix".into()]),
+ "decode_support" => Some(vec!["decode-support".into(), "--json".into()]),
+ "process_list" => Some(vec!["process".into(), "list".into(), "--json".into()]),
+ "artifact_list" => Some(vec!["artifact".into(), "list".into(), "--json".into()]),
+ "artifact_get" => {
+ let id = args.get("id").and_then(|v| v.as_str())?;
+ Some(vec![
+ "artifact".into(),
+ "get".into(),
+ id.into(),
+ "--json".into(),
+ ])
+ }
+ "artifact_query" => {
+ let id = args.get("id").and_then(|v| v.as_str())?;
+ let mut v = vec!["artifact".into(), "query".into(), id.into()];
+ if let Some(o) = args.get("offset").and_then(|x| x.as_u64()) {
+ v.push("--offset".into());
+ v.push(o.to_string());
+ }
+ if let Some(l) = args.get("limit").and_then(|x| x.as_u64()) {
+ v.push("--limit".into());
+ v.push(l.to_string());
+ }
+ push_json(&mut v);
+ Some(v)
+ }
+ "load" => {
+ let p = path?;
+ Some(vec!["load".into(), p.into(), "--json".into()])
+ }
+ "analyze" => {
+ let p = path?;
+ let mut v = vec!["analyze".into(), p.into()];
+ if let Some(arr) = args.get("analyzers").and_then(|a| a.as_array()) {
+ let names: Vec<&str> = arr.iter().filter_map(|x| x.as_str()).collect();
+ if !names.is_empty() {
+ v.push("--analyzers".into());
+ v.push(names.join(","));
+ }
+ }
+ if args.get("gpu").and_then(|g| g.as_bool()) == Some(true) {
+ v.push("--gpu".into());
+ }
+ push_json(&mut v);
+ Some(v)
+ }
+ "disassemble" => {
+ let p = path?;
+ let mut v = vec!["disasm".into(), p.into()];
+ if let Some(a) = addr {
+ v.push("--addr".into());
+ v.push(a.into());
+ }
+ if let Some(c) = args.get("count").and_then(|x| x.as_u64()) {
+ v.push("--count".into());
+ v.push(c.to_string());
+ }
+ push_json(&mut v);
+ Some(v)
+ }
+ "decompile" => {
+ let p = path?;
+ let mut v = vec!["decompile".into(), p.into()];
+ if let Some(a) = addr {
+ v.push("--addr".into());
+ v.push(a.into());
+ }
+ if args.get("follow_stub").and_then(|x| x.as_bool()) == Some(true) {
+ v.push("--follow-stub".into());
+ }
+ push_json(&mut v);
+ Some(v)
+ }
+ "list_strings" | "search_strings" => {
+ let p = path?;
+ let mut v = vec!["strings".into(), p.into()];
+ if let Some(f) = args.get("filter").and_then(|x| x.as_str()) {
+ v.push("--filter".into());
+ v.push(f.into());
+ }
+ if let Some(l) = args.get("limit").and_then(|x| x.as_u64()) {
+ v.push("--limit".into());
+ v.push(l.to_string());
+ }
+ push_json(&mut v);
+ Some(v)
+ }
+ "crypt_constants" | "list_crypt_constants" => {
+ let p = path?;
+ let mut v = vec!["crypt-constants".into(), p.into()];
+ if let Some(a) = args.get("algo").and_then(|x| x.as_str()) {
+ v.push("--algo".into());
+ v.push(a.into());
+ }
+ push_json(&mut v);
+ Some(v)
+ }
+ "rtti" => {
+ let p = path?;
+ Some(vec!["rtti".into(), p.into(), "--json".into()])
+ }
+ "rtti_query" => {
+ let p = path?;
+ let mut v = vec!["rtti".into(), p.into()];
+ if let Some(f) = args
+ .get("filter")
+ .or_else(|| args.get("name"))
+ .and_then(|x| x.as_str())
+ {
+ v.push("--filter".into());
+ v.push(f.into());
+ }
+ push_json(&mut v);
+ Some(v)
+ }
+ "rtti_gpu_bench" => {
+ let p = path?;
+ Some(vec!["rtti-gpu-bench".into(), p.into(), "--json".into()])
+ }
+ "function_at" | "get_function_by_address" => {
+ let p = path?;
+ let a = addr?;
+ Some(vec![
+ "function-at".into(),
+ p.into(),
+ "--addr".into(),
+ a.into(),
+ "--json".into(),
+ ])
+ }
+ "function_create" => {
+ let p = path?;
+ let a = addr?;
+ let mut v = vec![
+ "function".into(),
+ "create".into(),
+ p.into(),
+ "--addr".into(),
+ a.into(),
+ ];
+ if let Some(e) = args.get("end").and_then(|x| x.as_str()) {
+ v.push("--end".into());
+ v.push(e.into());
+ }
+ push_json(&mut v);
+ Some(v)
+ }
+ "get_xrefs_to" => {
+ let p = path?;
+ let a = addr?;
+ Some(vec![
+ "xrefs".into(),
+ p.into(),
+ "--to".into(),
+ a.into(),
+ "--json".into(),
+ ])
+ }
+ "get_xrefs_from" => {
+ let p = path?;
+ let a = addr?;
+ Some(vec![
+ "xrefs".into(),
+ p.into(),
+ "--from".into(),
+ a.into(),
+ "--json".into(),
+ ])
+ }
+ "get_calls_from" => {
+ let p = path?;
+ let a = addr?;
+ Some(vec![
+ "xrefs".into(),
+ p.into(),
+ "--calls".into(),
+ a.into(),
+ "--json".into(),
+ ])
+ }
+ "inventory" => {
+ let p = path.or_else(|| args.get("dir").and_then(|v| v.as_str()))?;
+ Some(vec!["inventory".into(), p.into(), "--json".into()])
+ }
+ "list_tree" => {
+ let p = path.or_else(|| args.get("root").and_then(|v| v.as_str()))?;
+ Some(vec!["tree".into(), p.into(), "--json".into()])
+ }
+ "unity_inventory" => {
+ let p = path.or_else(|| args.get("dir").and_then(|v| v.as_str()))?;
+ Some(vec!["unity-inventory".into(), p.into(), "--json".into()])
+ }
+ "il2cpp_meta" => {
+ let meta = args
+ .get("meta")
+ .or_else(|| args.get("path"))
+ .and_then(|v| v.as_str())?;
+ Some(vec!["il2cpp".into(), "meta".into(), meta.into(), "--json".into()])
+ }
+ "il2cpp_stubs" => {
+ let binary = args
+ .get("binary")
+ .or_else(|| args.get("path"))
+ .and_then(|v| v.as_str())?;
+ Some(vec![
+ "il2cpp".into(),
+ "stubs".into(),
+ "--binary".into(),
+ binary.into(),
+ "--json".into(),
+ ])
+ }
+ "il2cpp_icalls" => {
+ let binary = args
+ .get("binary")
+ .or_else(|| args.get("path"))
+ .and_then(|v| v.as_str())?;
+ Some(vec![
+ "il2cpp".into(),
+ "icalls".into(),
+ "--binary".into(),
+ binary.into(),
+ "--json".into(),
+ ])
+ }
+ "decode_query" => {
+ let q = args.get("query").and_then(|v| v.as_str())?;
+ let mut v = vec!["decode-query".into(), "--query".into(), q.into()];
+ if let Some(a) = args.get("arch").and_then(|x| x.as_str()) {
+ v.push("--arch".into());
+ v.push(a.into());
+ }
+ push_json(&mut v);
+ Some(v)
+ }
+ "process_attach" => {
+ let pid = args.get("pid").and_then(|v| v.as_u64())?;
+ let mut v = vec!["process".into(), "attach".into(), pid.to_string()];
+ if let Some(m) = args.get("mode").and_then(|x| x.as_str()) {
+ v.push("-mode".into());
+ v.push(m.into());
+ }
+ push_json(&mut v);
+ Some(v)
+ }
+ "process_modules" => {
+ let sid = sid?;
+ Some(vec![
+ "process".into(),
+ "modules".into(),
+ sid,
+ "--json".into(),
+ ])
+ }
+ "process_continue" => {
+ let sid = sid?;
+ Some(vec![
+ "process".into(),
+ "continue".into(),
+ sid,
+ "--json".into(),
+ ])
+ }
+ "process_step_into" => {
+ let sid = sid?;
+ Some(vec![
+ "process".into(),
+ "step".into(),
+ sid,
+ "--json".into(),
+ ])
+ }
+ "process_step_over" => {
+ let sid = sid?;
+ Some(vec![
+ "process".into(),
+ "step".into(),
+ sid,
+ "-over".into(),
+ "--json".into(),
+ ])
+ }
+ "process_step_out" => {
+ let sid = sid?;
+ Some(vec![
+ "process".into(),
+ "step".into(),
+ sid,
+ "-out".into(),
+ "--json".into(),
+ ])
+ }
+ "process_break_set" => {
+ let sid = sid?;
+ let a = addr?;
+ Some(vec![
+ "process".into(),
+ "break".into(),
+ "set".into(),
+ sid,
+ "--addr".into(),
+ a.into(),
+ "--json".into(),
+ ])
+ }
+ "process_vtable_probe" => {
+ let sid = sid?;
+ let a = addr.or_else(|| args.get("object").and_then(|v| v.as_str()))?;
+ Some(vec![
+ "process".into(),
+ "vtable".into(),
+ sid,
+ "--addr".into(),
+ a.into(),
+ "--json".into(),
+ ])
+ }
+ _ => None,
+ }
+}
+
+fn run_cli(args: &[String]) -> Result<String, String> {
+ let bin = resolve_cli_bin()?;
+ let out = Command::new(&bin)
+ .args(args)
+ .output()
+ .map_err(|e| format!("spawn {}: {e}", bin.display()))?;
+ let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
+ if text.trim().is_empty() {
+ text = String::from_utf8_lossy(&out.stderr).into_owned();
+ } else if !out.stderr.is_empty() && !out.status.success() {
+ text.push_str("\n");
+ text.push_str(&String::from_utf8_lossy(&out.stderr));
+ }
+ if !out.status.success() && text.trim().is_empty() {
+ return Err(format!(
+ "ghidrust exited {}",
+ out.status
+ .code()
+ .map(|c| c.to_string())
+ .unwrap_or_else(|| "signal".into())
+ ));
+ }
+ if text.trim().is_empty() {
+ text = format!(
+ "(exit {})",
+ out.status
+ .code()
+ .map(|c| c.to_string())
+ .unwrap_or_else(|| "0".into())
+ );
+ }
+ Ok(text)
+}
+
+fn extract_tools_call_text(resp: &Value) -> Result<String, String> {
+ if let Some(err) = resp.get("error") {
+ let msg = err
+ .get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or("MCP error");
+ return Err(msg.to_string());
+ }
+ let result = resp
+ .get("result")
+ .ok_or_else(|| "MCP response missing result".to_string())?;
+ if let Some(arr) = result.get("content").and_then(|c| c.as_array()) {
+ let mut parts = Vec::new();
+ for item in arr {
+ if let Some(t) = item.get("text").and_then(|t| t.as_str()) {
+ parts.push(t.to_string());
+ } else {
+ parts.push(item.to_string());
+ }
+ }
+ if !parts.is_empty() {
+ return Ok(parts.join("\n"));
+ }
+ }
+ Ok(serde_json::to_string_pretty(result).unwrap_or_else(|_| result.to_string()))
+}
+
+/// One-shot `ghidrust mcp`: initialize + tools/call, then exit.
+pub fn mcp_tools_call_oneshot(tool: &str, arguments: &Value) -> Result<String, String> {
+ reject_net(tool)?;
+ let bin = resolve_cli_bin()?;
+ let mut child = Command::new(&bin)
+ .arg("mcp")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|e| format!("spawn {} mcp: {e}", bin.display()))?;
+ let mut stdin = child
+ .stdin
+ .take()
+ .ok_or_else(|| "mcp stdin unavailable".to_string())?;
+ let init = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2024-11-05",
+ "capabilities": {},
+ "clientInfo": {
+ "name": "ghidrust-gui",
+ "version": env!("CARGO_PKG_VERSION")
+ }
+ }
+ });
+ let initialized = json!({"jsonrpc":"2.0","method":"notifications/initialized"});
+ let call = json!({
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "tools/call",
+ "params": {
+ "name": tool,
+ "arguments": arguments
+ }
+ });
+ for msg in [&init, &initialized, &call] {
+ let line = serde_json::to_string(msg).map_err(|e| e.to_string())?;
+ writeln!(stdin, "{line}").map_err(|e| format!("mcp write: {e}"))?;
+ }
+ drop(stdin);
+ let out = child
+ .wait_with_output()
+ .map_err(|e| format!("mcp wait: {e}"))?;
+ let stdout = String::from_utf8_lossy(&out.stdout);
+ let mut last_call: Option<Value> = None;
+ for line in stdout.lines() {
+ let line = line.trim();
+ if line.is_empty() {
+ continue;
+ }
+ if let Ok(v) = serde_json::from_str::<Value>(line) {
+ if v.get("id") == Some(&json!(2)) {
+ last_call = Some(v);
+ }
+ }
+ }
+ match last_call {
+ Some(v) => extract_tools_call_text(&v),
+ None => {
+ let err = String::from_utf8_lossy(&out.stderr);
+ Err(format!(
+ "no tools/call response from ghidrust mcp\nstdout:\n{stdout}\nstderr:\n{err}"
+ ))
+ }
+ }
+}
+
+/// Invoke a tool: CLI mapping when possible, else MCP `tools/call`.
+pub fn invoke_tool(tool: &str, arguments: &Value) -> String {
+ let tool = normalize_tool_name(tool);
+ if let Err(e) = reject_net(tool) {
+ return e;
+ }
+ if let Some(cli) = cli_args_for_tool(tool, arguments) {
+ match run_cli(&cli) {
+ Ok(s) => return s,
+ Err(e) => {
+ // Fall through to MCP when CLI mapping failed to spawn / run.
+ let mcp = mcp_tools_call_oneshot(tool, arguments);
+ return match mcp {
+ Ok(s) => s,
+ Err(m) => format!("CLI failed ({e}); MCP failed ({m})"),
+ };
+ }
+ }
+ }
+ match mcp_tools_call_oneshot(tool, arguments) {
+ Ok(s) => s,
+ Err(e) => e,
+ }
+}
+
+/// Long-lived `ghidrust mcp` child for the REPL (session continuity).
+pub struct McpStdioSession {
+ child: Child,
+ stdin: ChildStdin,
+ stdout: BufReader<ChildStdout>,
+ next_id: u64,
+}
+
+impl McpStdioSession {
+ pub fn start() -> Result<Self, String> {
+ let bin = resolve_cli_bin()?;
+ let mut child = Command::new(&bin)
+ .arg("mcp")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .map_err(|e| format!("spawn {} mcp: {e}", bin.display()))?;
+ let mut stdin = child
+ .stdin
+ .take()
+ .ok_or_else(|| "mcp stdin unavailable".to_string())?;
+ let stdout = BufReader::new(
+ child
+ .stdout
+ .take()
+ .ok_or_else(|| "mcp stdout unavailable".to_string())?,
+ );
+ let init = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2024-11-05",
+ "capabilities": {},
+ "clientInfo": {
+ "name": "ghidrust-gui-repl",
+ "version": env!("CARGO_PKG_VERSION")
+ }
+ }
+ });
+ writeln!(stdin, "{}", serde_json::to_string(&init).unwrap())
+ .map_err(|e| format!("mcp init write: {e}"))?;
+ let mut session = Self {
+ child,
+ stdin,
+ stdout,
+ next_id: 2,
+ };
+ let _ = session.read_response_for(1)?;
+ let note = json!({"jsonrpc":"2.0","method":"notifications/initialized"});
+ writeln!(session.stdin, "{}", serde_json::to_string(&note).unwrap())
+ .map_err(|e| format!("mcp initialized write: {e}"))?;
+ Ok(session)
+ }
+
+ fn read_response_for(&mut self, id: u64) -> Result<Value, String> {
+ let want = json!(id);
+ let mut line = String::new();
+ loop {
+ line.clear();
+ let n = self
+ .stdout
+ .read_line(&mut line)
+ .map_err(|e| format!("mcp read: {e}"))?;
+ if n == 0 {
+ return Err("mcp stdout closed".into());
+ }
+ let trimmed = line.trim();
+ if trimmed.is_empty() {
+ continue;
+ }
+ let v: Value = serde_json::from_str(trimmed)
+ .map_err(|e| format!("mcp JSON: {e}: {trimmed}"))?;
+ if v.get("id") == Some(&want) {
+ return Ok(v);
+ }
+ }
+ }
+
+ pub fn tools_call(&mut self, tool: &str, arguments: &Value) -> Result<String, String> {
+ reject_net(tool)?;
+ let id = self.next_id;
+ self.next_id += 1;
+ let call = json!({
+ "jsonrpc": "2.0",
+ "id": id,
+ "method": "tools/call",
+ "params": {
+ "name": tool,
+ "arguments": arguments
+ }
+ });
+ writeln!(self.stdin, "{}", serde_json::to_string(&call).unwrap())
+ .map_err(|e| format!("mcp write: {e}"))?;
+ self.stdin
+ .flush()
+ .map_err(|e| format!("mcp flush: {e}"))?;
+ let resp = self.read_response_for(id)?;
+ extract_tools_call_text(&resp)
+ }
+}
+
+impl Drop for McpStdioSession {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
+
+/// REPL / Script Manager entry: prefer persistent MCP when provided.
+pub fn invoke_tool_with_session(
+ session: &mut Option<McpStdioSession>,
+ tool: &str,
+ arguments: &Value,
+) -> String {
+ let tool = normalize_tool_name(tool);
+ if let Err(e) = reject_net(tool) {
+ return e;
+ }
+ // CLI one-shot for tools that map cleanly (no live MCP session needed).
+ if let Some(cli) = cli_args_for_tool(tool, arguments) {
+ if let Ok(s) = run_cli(&cli) {
+ return s;
+ }
+ }
+ if session.is_none() {
+ match McpStdioSession::start() {
+ Ok(s) => *session = Some(s),
+ Err(e) => {
+ let oneshot = invoke_tool(tool, arguments);
+ return format!("MCP session start failed ({e}); oneshot: {oneshot}");
+ }
+ }
+ }
+ match session.as_mut().unwrap().tools_call(tool, arguments) {
+ Ok(s) => s,
+ Err(e) => {
+ // Recreate session once on pipe failure, then fall back to oneshot.
+ *session = None;
+ match McpStdioSession::start() {
+ Ok(mut s) => match s.tools_call(tool, arguments) {
+ Ok(out) => {
+ *session = Some(s);
+ out
+ }
+ Err(e2) => {
+ drop(s);
+ format!(
+ "{e}; retry failed ({e2}); oneshot: {}",
+ invoke_tool(tool, arguments)
+ )
+ }
+ },
+ Err(_) => invoke_tool(tool, arguments),
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parse_bare_and_json_args() {
+ let (n, a) = parse_tool_line("server_info").unwrap();
+ assert_eq!(n, "server_info");
+ assert_eq!(a, json!({}));
+ let (n, a) = parse_tool_line(r#"list_strings {"path":"x.pe"}"#).unwrap();
+ assert_eq!(n, "list_strings");
+ assert_eq!(a["path"], "x.pe");
+ let (n, _) = parse_tool_line("mcp.decompile").unwrap();
+ assert_eq!(n, "decompile");
+ }
+
+ #[test]
+ fn cli_mapping_server_info() {
+ let args = cli_args_for_tool("server_info", &json!({})).unwrap();
+ assert_eq!(args, vec!["version", "--json"]);
+ }
+
+ #[test]
+ fn reject_net_tools() {
+ assert!(reject_net("net_dig").is_err());
+ assert!(reject_net("load").is_ok());
+ }
+}
diff --git a/crates/ghidrust-gui/src/menu_actions.rs b/crates/ghidrust-gui/src/menu_actions.rs
index ac42753..5692f80 100644
--- a/crates/ghidrust-gui/src/menu_actions.rs
+++ b/crates/ghidrust-gui/src/menu_actions.rs
@@ -587,6 +587,7 @@ mod tests {
mnemonic: "nop".into(),
operands: String::new(),
length: 1,
+ ..Default::default()
},
Instruction {
address: 0x1001,
@@ -594,6 +595,7 @@ mod tests {
mnemonic: "ret".into(),
operands: String::new(),
length: 1,
+ ..Default::default()
},
];
assert_eq!(listing_index_at_or_before(&listing, 0x1000), Some(0));
@@ -646,6 +648,7 @@ mod tests {
mnemonic: "add".into(),
operands: "eax, 5".into(),
length: 3,
+ ..Default::default()
},
Instruction {
address: 0x1003,
@@ -653,6 +656,7 @@ mod tests {
mnemonic: "add".into(),
operands: "eax, 100".into(),
length: 3,
+ ..Default::default()
},
];
let low = search_scalars(&listing, 0, 10, 32);
@@ -672,6 +676,7 @@ mod tests {
mnemonic: "push".into(),
operands: "rbp".into(),
length: 1,
+ ..Default::default()
},
Instruction {
address: 0x1001,
@@ -679,6 +684,7 @@ mod tests {
mnemonic: "ret".into(),
operands: String::new(),
length: 1,
+ ..Default::default()
},
];
assert_eq!(
diff --git a/crates/ghidrust-gui/src/nav.rs b/crates/ghidrust-gui/src/nav.rs
index ddeafef..ba4ca29 100644
--- a/crates/ghidrust-gui/src/nav.rs
+++ b/crates/ghidrust-gui/src/nav.rs
@@ -103,7 +103,7 @@ impl NavHistory {
}
/// Currently-selected location (last pushed / most recent nav step).
- #[allow(dead_code)] // read by future Overview status chip
+ #[cfg(test)]
pub fn current(&self) -> Option<NavLocation> {
self.current
}
@@ -116,8 +116,7 @@ impl NavHistory {
self.forward.len()
}
- /// Clear all nav state (used when closing a program).
- #[allow(dead_code)] // reserved for File → Close program hook
+ /// Clear all nav state (used when closing / switching program).
pub fn clear(&mut self) {
self.back.clear();
self.forward.clear();
diff --git a/crates/ghidrust-gui/src/network.rs b/crates/ghidrust-gui/src/network.rs
new file mode 100644
index 0000000..16882ca
--- /dev/null
+++ b/crates/ghidrust-gui/src/network.rs
@@ -0,0 +1,1663 @@
+//! Ghidrust GUI · Network tool (Ghidnet tabbed host).
+//!
+//! Investigation-first: Connections → Capture/Flows → Alerts → Dig.
+//! Panes call `ghidrust-net-*` (same APIs as CLI/MCP). Not a packet browser.
+
+use eframe::egui::{self, Color32, RichText, Ui};
+use ghidrust_net_attr::{list_connections, owner_for_pid, ConnFilter};
+use ghidrust_net_capture::{
+ capture_start, capture_status, capture_stop, flows, list_interfaces, read_frames,
+ CaptureStartRequest,
+};
+use ghidrust_net_correlate::{
+ compile_playbook, execute_closed_loop, execute_playbook_offline,
+};
+use ghidrust_net_detect::{detect_capture_file, inline_block_allowed, last_alerts, load_rules};
+use ghidrust_net_parse::extract_pivots;
+use ghidrust_net_rules::{load_rule_pack, CompiledRuleset, Rule};
+use ghidrust_net_schema::{
+ Alert, AttributedFlow, CaptureSessionInfo, ClosedLoopConfig, Confidence, ConnectionView,
+ DigJob, DigPlan, DigResult, NetHint, NetworkInfo, Owner, PivotFields,
+};
+use std::path::{Path, PathBuf};
+use std::time::{Duration, Instant};
+
+/// Host window egui / layout id.
+pub const HOST_EGUI_ID: &str = "pane_net_host";
+
+/// Same surface descriptor as MCP `server_info.network` / CLI `network_info_json`.
+pub fn network_info() -> NetworkInfo {
+ NetworkInfo {
+ wave: 5,
+ caps: vec![
+ "dig".into(),
+ "playbook".into(),
+ "connections".into(),
+ "owners".into(),
+ "capture".into(),
+ "flows".into(),
+ "detect".into(),
+ "alerts".into(),
+ "rules".into(),
+ "pivots".into(),
+ ],
+ native: true,
+ capture: true,
+ }
+}
+
+/// Honest reason when inline block is unavailable (Wave 6 stretch).
+pub fn inline_block_reason() -> &'static str {
+ if inline_block_allowed() {
+ "GHIDRUST_NET_INLINE enabled — optional inline block policy is on for this process"
+ } else {
+ "Inline block disabled — set GHIDRUST_NET_INLINE=1 (or true) to opt in; off by default"
+ }
+}
+
+/// One tab in the Network tool host.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum NetworkPane {
+ Connections,
+ Capture,
+ Alerts,
+ Rules,
+ Dig,
+}
+
+impl NetworkPane {
+ pub const TAB_ORDER: &'static [NetworkPane] = &[
+ NetworkPane::Connections,
+ NetworkPane::Capture,
+ NetworkPane::Alerts,
+ NetworkPane::Rules,
+ NetworkPane::Dig,
+ ];
+
+ pub const ALL: &'static [NetworkPane] = Self::TAB_ORDER;
+
+ pub const fn short_title(self) -> &'static str {
+ match self {
+ NetworkPane::Connections => "Connections",
+ NetworkPane::Capture => "Capture",
+ NetworkPane::Alerts => "Alerts",
+ NetworkPane::Rules => "Rules",
+ NetworkPane::Dig => "Dig",
+ }
+ }
+
+ pub const fn plugin(self) -> &'static str {
+ match self {
+ NetworkPane::Connections => "NetworkConnectionsPlugin",
+ NetworkPane::Capture => "NetworkCapturePlugin",
+ NetworkPane::Alerts => "NetworkAlertsPlugin",
+ NetworkPane::Rules => "NetworkRulesPlugin",
+ NetworkPane::Dig => "NetworkDigPlugin",
+ }
+ }
+
+ pub const fn egui_id(self) -> &'static str {
+ match self {
+ NetworkPane::Connections => "pane_net_connections",
+ NetworkPane::Capture => "pane_net_capture",
+ NetworkPane::Alerts => "pane_net_alerts",
+ NetworkPane::Rules => "pane_net_rules",
+ NetworkPane::Dig => "pane_net_dig",
+ }
+ }
+}
+
+/// `Network` menu action.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum NetworkAction {
+ ShowConnections,
+ ShowCapture,
+ ShowAlerts,
+ ShowRules,
+ ShowDig,
+ RefreshConnections,
+}
+
+impl NetworkAction {
+ pub const ALL: &'static [NetworkAction] = &[
+ NetworkAction::ShowConnections,
+ NetworkAction::ShowCapture,
+ NetworkAction::ShowAlerts,
+ NetworkAction::ShowRules,
+ NetworkAction::ShowDig,
+ NetworkAction::RefreshConnections,
+ ];
+
+ pub const fn label(self) -> &'static str {
+ match self {
+ NetworkAction::ShowConnections => "Show Connections",
+ NetworkAction::ShowCapture => "Show Capture",
+ NetworkAction::ShowAlerts => "Show Alerts",
+ NetworkAction::ShowRules => "Show Rules",
+ NetworkAction::ShowDig => "Show Dig",
+ NetworkAction::RefreshConnections => "Refresh Connections",
+ }
+ }
+}
+
+/// Persistent state for the Network (Ghidnet) tool.
+#[derive(Debug, Clone)]
+pub struct NetworkState {
+ pub enabled: bool,
+ pub host_open: bool,
+ pub active_tab: NetworkPane,
+ pub status: String,
+ pub last_error: Option<String>,
+
+ // Connections
+ pub connections: Vec<ConnectionView>,
+ pub conn_filter_pid: String,
+ pub conn_filter_path: String,
+ pub conn_filter_proto: String,
+ pub conn_listening_only: bool,
+ pub conn_max: String,
+ pub selected_conn: Option<usize>,
+ pub selected_owner: Option<Owner>,
+
+ // Capture
+ pub ifaces: Vec<String>,
+ pub iface: String,
+ pub capture_filter: String,
+ pub capture_pid: String,
+ pub capture_path_substr: String,
+ pub capture_out_dir: String,
+ pub capture_replay: String,
+ pub session_id: Option<String>,
+ pub session_info: Option<CaptureSessionInfo>,
+ pub capture_backend: Option<String>,
+ pub capture_out_path: Option<String>,
+ pub flows_cache: Vec<AttributedFlow>,
+ pub selected_flow: Option<usize>,
+ pub pivots: PivotFields,
+ pub last_poll: Option<Instant>,
+
+ // Alerts / rules
+ pub alerts: Vec<Alert>,
+ pub selected_alert: Option<usize>,
+ pub rules_path: String,
+ pub ruleset: Option<CompiledRuleset>,
+ pub rules_check_ok: Option<bool>,
+ pub rules_warnings: Vec<String>,
+
+ // Dig
+ pub dig_path: String,
+ pub dig_pid: String,
+ pub dig_host: String,
+ pub dig_ioc: String,
+ pub dig_alert_id: String,
+ pub dig_flow_ref: String,
+ pub dig_attach_live: bool,
+ pub dig_plan: Option<DigPlan>,
+ pub dig_result: Option<DigResult>,
+ pub dig_job: Option<DigJob>,
+
+ /// Consumed by the app after draw: load this binary into Listing.
+ pub pending_load_path: Option<String>,
+ /// Consumed by the app: focus Debugger host (attach_live path).
+ pub pending_focus_debugger: bool,
+}
+
+impl Default for NetworkState {
+ fn default() -> Self {
+ Self {
+ enabled: false,
+ host_open: false,
+ active_tab: NetworkPane::Connections,
+ status: "Ghidnet idle".into(),
+ last_error: None,
+ connections: Vec::new(),
+ conn_filter_pid: String::new(),
+ conn_filter_path: String::new(),
+ conn_filter_proto: String::new(),
+ conn_listening_only: false,
+ conn_max: "256".into(),
+ selected_conn: None,
+ selected_owner: None,
+ ifaces: Vec::new(),
+ iface: "replay".into(),
+ capture_filter: String::new(),
+ capture_pid: String::new(),
+ capture_path_substr: String::new(),
+ capture_out_dir: String::new(),
+ capture_replay: String::new(),
+ session_id: None,
+ session_info: None,
+ capture_backend: None,
+ capture_out_path: None,
+ flows_cache: Vec::new(),
+ selected_flow: None,
+ pivots: PivotFields::default(),
+ last_poll: None,
+ alerts: Vec::new(),
+ selected_alert: None,
+ rules_path: default_rules_path(),
+ ruleset: None,
+ rules_check_ok: None,
+ rules_warnings: Vec::new(),
+ dig_path: String::new(),
+ dig_pid: String::new(),
+ dig_host: String::new(),
+ dig_ioc: String::new(),
+ dig_alert_id: String::new(),
+ dig_flow_ref: String::new(),
+ dig_attach_live: false,
+ dig_plan: None,
+ dig_result: None,
+ dig_job: None,
+ pending_load_path: None,
+ pending_focus_debugger: false,
+ }
+ }
+}
+
+fn default_rules_path() -> String {
+ let candidates = [
+ PathBuf::from("rules/ghidrust-minimal.rules"),
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../rules/ghidrust-minimal.rules"),
+ ];
+ for c in candidates {
+ if c.is_file() {
+ return c.display().to_string();
+ }
+ }
+ "rules/ghidrust-minimal.rules".into()
+}
+
+impl NetworkState {
+ pub fn enable_tool(&mut self) {
+ self.enabled = true;
+ self.host_open = true;
+ if self.ifaces.is_empty() {
+ self.refresh_ifaces();
+ }
+ }
+
+ pub fn focus_tab(&mut self, tab: NetworkPane) {
+ self.host_open = true;
+ self.enabled = true;
+ self.active_tab = tab;
+ }
+
+ pub fn window_title(&self) -> String {
+ format!("Network · {}", self.active_tab.short_title())
+ }
+
+ pub fn status_line(&self) -> String {
+ let cap = if self.session_info.as_ref().map(|s| s.running).unwrap_or(false) {
+ "capture:running"
+ } else if self.session_id.is_some() {
+ "capture:stopped"
+ } else {
+ "capture:none"
+ };
+ let n_alert = self.alerts.len();
+ let n_conn = self.connections.len();
+ format!(
+ "{} · {} · alerts={} · conns={} · {}",
+ self.status, cap, n_alert, n_conn, self.active_tab.short_title()
+ )
+ }
+
+ pub fn hint_from_fields(&self) -> NetHint {
+ NetHint {
+ path: nonempty(&self.dig_path),
+ pid: self.dig_pid.trim().parse().ok(),
+ host: nonempty(&self.dig_host),
+ ioc: nonempty(&self.dig_ioc),
+ alert_id: nonempty(&self.dig_alert_id),
+ flow_ref: nonempty(&self.dig_flow_ref),
+ }
+ }
+
+ pub fn apply_hint(&mut self, hint: NetHint) {
+ if let Some(p) = hint.path {
+ self.dig_path = p;
+ }
+ if let Some(pid) = hint.pid {
+ self.dig_pid = pid.to_string();
+ }
+ if let Some(h) = hint.host {
+ self.dig_host = h;
+ }
+ if let Some(i) = hint.ioc {
+ self.dig_ioc = i;
+ }
+ if let Some(a) = hint.alert_id {
+ self.dig_alert_id = a;
+ }
+ if let Some(f) = hint.flow_ref {
+ self.dig_flow_ref = f;
+ }
+ }
+
+ pub fn dig_from_connection(&mut self, idx: usize) {
+ let Some(c) = self.connections.get(idx).cloned() else {
+ return;
+ };
+ let mut hint = NetHint {
+ pid: Some(c.pid),
+ path: c.image_path.clone(),
+ host: Some(c.remote.clone()),
+ ..Default::default()
+ };
+ if hint.path.is_none() {
+ if let Ok(o) = owner_for_pid(c.pid) {
+ hint.path = o.image_path;
+ }
+ }
+ self.apply_hint(hint);
+ self.focus_tab(NetworkPane::Dig);
+ self.status = format!("Dig hint from connection pid={}", c.pid);
+ }
+
+ pub fn dig_from_flow(&mut self, idx: usize) {
+ if let Some(f) = self.flows_cache.get(idx) {
+ let host = format!("{}:{}", f.key.dst, f.key.dst_port);
+ let mut hint = NetHint {
+ host: Some(host),
+ flow_ref: f.flow_id.clone(),
+ path: f.owner.as_ref().and_then(|o| o.image_path.clone()),
+ pid: f.owner.as_ref().map(|o| o.pid),
+ ..Default::default()
+ };
+ if hint.path.is_none() {
+ if let Some(pid) = hint.pid {
+ if let Ok(o) = owner_for_pid(pid) {
+ hint.path = o.image_path;
+ }
+ }
+ }
+ self.apply_hint(hint);
+ self.focus_tab(NetworkPane::Dig);
+ self.status = "Dig hint from flow".into();
+ }
+ }
+
+ pub fn dig_from_alert(&mut self, idx: usize) {
+ if let Some(a) = self.alerts.get(idx).cloned() {
+ let path = a
+ .owner
+ .as_ref()
+ .and_then(|o| o.image_path.clone())
+ .or_else(|| nonempty(&self.dig_path));
+ self.apply_hint(NetHint {
+ path: path.clone(),
+ alert_id: Some(a.id.clone()),
+ host: a.host.clone(),
+ ioc: a.ioc.clone(),
+ pid: a.owner.as_ref().map(|o| o.pid),
+ ..Default::default()
+ });
+ if let Some(path) = path {
+ let cfg = ClosedLoopConfig {
+ auto_analyze: true,
+ auto_decompile_limit: 3,
+ attach_live: self.dig_attach_live,
+ };
+ match execute_closed_loop(&a, Path::new(&path), &cfg) {
+ Ok(job) => {
+ self.dig_plan = Some(job.plan.clone());
+ self.dig_result = Some(job.result.clone());
+ self.dig_job = Some(job);
+ self.status = "Closed-loop dig ok".into();
+ self.last_error = None;
+ if self.dig_attach_live {
+ self.pending_focus_debugger = true;
+ self.status =
+ "Closed-loop dig ok — attach_live: open Debugger to attach"
+ .into();
+ }
+ }
+ Err(e) => {
+ self.last_error = Some(e);
+ self.focus_tab(NetworkPane::Dig);
+ }
+ }
+ } else {
+ self.last_error =
+ Some("Alert has no owner path — set Dig path then Dig again".into());
+ }
+ self.focus_tab(NetworkPane::Dig);
+ }
+ }
+
+ pub fn refresh_connections(&mut self) {
+ self.last_error = None;
+ let filter = ConnFilter {
+ pid: self.conn_filter_pid.trim().parse().ok(),
+ path_substr: nonempty(&self.conn_filter_path),
+ proto: nonempty(&self.conn_filter_proto),
+ listening_only: self.conn_listening_only,
+ max: self.conn_max.trim().parse().ok(),
+ };
+ match list_connections(&filter) {
+ Ok(v) => {
+ self.connections = v;
+ self.selected_conn = None;
+ self.selected_owner = None;
+ self.status = format!("Connections: {}", self.connections.len());
+ }
+ Err(e) => {
+ self.connections.clear();
+ self.last_error = Some(e.to_string());
+ }
+ }
+ }
+
+ pub fn select_connection(&mut self, idx: usize) {
+ self.selected_conn = Some(idx);
+ self.selected_owner = None;
+ if let Some(c) = self.connections.get(idx) {
+ match owner_for_pid(c.pid) {
+ Ok(o) => self.selected_owner = Some(o),
+ Err(e) => self.last_error = Some(e.to_string()),
+ }
+ }
+ }
+
+ pub fn refresh_ifaces(&mut self) {
+ self.ifaces = list_interfaces()
+ .into_iter()
+ .filter_map(|v| v.get("name").and_then(|n| n.as_str()).map(|s| s.to_string()))
+ .collect();
+ if self.ifaces.is_empty() {
+ self.ifaces = vec!["loopback".into(), "replay".into()];
+ }
+ if !self.ifaces.iter().any(|i| i == &self.iface) {
+ self.iface = self.ifaces[0].clone();
+ }
+ }
+
+ pub fn start_capture(&mut self) {
+ self.last_error = None;
+ let req = CaptureStartRequest {
+ iface: nonempty(&self.iface),
+ filter: nonempty(&self.capture_filter),
+ pid: self.capture_pid.trim().parse().ok(),
+ path_substr: nonempty(&self.capture_path_substr),
+ out_dir: nonempty(&self.capture_out_dir),
+ max_bytes: 32 * 1024 * 1024,
+ replay_path: nonempty(&self.capture_replay),
+ };
+ match capture_start(req) {
+ Ok(r) => {
+ self.session_id = Some(r.session_id.clone());
+ self.capture_out_path = Some(r.out_path.clone());
+ self.capture_backend = Some(r.backend.clone());
+ self.status = format!("Capture started ({})", r.backend);
+ self.refresh_capture_status();
+ self.refresh_flows();
+ }
+ Err(e) => self.last_error = Some(e.to_string()),
+ }
+ }
+
+ pub fn stop_capture(&mut self) {
+ self.last_error = None;
+ let Some(id) = self.session_id.clone() else {
+ self.last_error = Some("No capture session".into());
+ return;
+ };
+ match capture_stop(&id) {
+ Ok(info) => {
+ self.session_info = Some(info);
+ self.status = "Capture stopped".into();
+ self.refresh_flows();
+ }
+ Err(e) => self.last_error = Some(e.to_string()),
+ }
+ }
+
+ pub fn refresh_capture_status(&mut self) {
+ let Some(id) = self.session_id.clone() else {
+ return;
+ };
+ match capture_status(&id) {
+ Ok(info) => {
+ if let Some(p) = &info.out_path {
+ self.capture_out_path = Some(p.clone());
+ }
+ self.session_info = Some(info);
+ self.last_error = None;
+ }
+ Err(e) => self.last_error = Some(e.to_string()),
+ }
+ self.last_poll = Some(Instant::now());
+ }
+
+ pub fn refresh_flows(&mut self) {
+ let Some(id) = self.session_id.clone() else {
+ self.flows_cache.clear();
+ return;
+ };
+ match flows(&id, Some(256)) {
+ Ok(v) => {
+ self.flows_cache = v;
+ self.status = format!("Flows: {}", self.flows_cache.len());
+ }
+ Err(e) => self.last_error = Some(e.to_string()),
+ }
+ }
+
+ pub fn extract_pivots_from_capture(&mut self) {
+ self.last_error = None;
+ let path = self
+ .capture_out_path
+ .clone()
+ .or_else(|| nonempty(&self.capture_replay));
+ let Some(path) = path else {
+ self.last_error = Some("No capture/replay path for pivots".into());
+ return;
+ };
+ match read_frames(Path::new(&path)) {
+ Ok(frames) => {
+ let mut acc = PivotFields::default();
+ for f in &frames {
+ let p = extract_pivots(&f.payload);
+ merge_pivots(&mut acc, p);
+ }
+ // Also scan raw file bytes for TLS/HTTP magic outside framed payload.
+ if let Ok(raw) = std::fs::read(&path) {
+ merge_pivots(&mut acc, extract_pivots(&raw));
+ }
+ self.pivots = acc;
+ if let Some(h) = self.pivots.dns_qnames.first().cloned() {
+ self.dig_host = h;
+ } else if let Some(h) = self.pivots.tls_sni.first().cloned() {
+ self.dig_host = h;
+ } else if let Some(h) = self.pivots.http_hosts.first().cloned() {
+ self.dig_host = h;
+ }
+ self.status = "Pivots extracted".into();
+ }
+ Err(e) => self.last_error = Some(e),
+ }
+ }
+
+ pub fn check_rules(&mut self) {
+ self.last_error = None;
+ match load_rule_pack(Path::new(&self.rules_path)) {
+ Ok(rs) => {
+ self.rules_warnings = rs.warnings.clone();
+ self.rules_check_ok = Some(true);
+ self.ruleset = Some(rs);
+ self.status = format!(
+ "Rules ok ({})",
+ self.ruleset.as_ref().map(|r| r.rules.len()).unwrap_or(0)
+ );
+ }
+ Err(e) => {
+ self.rules_check_ok = Some(false);
+ self.ruleset = None;
+ self.last_error = Some(e.to_string());
+ }
+ }
+ }
+
+ pub fn ensure_ruleset(&mut self) -> Result<(), String> {
+ if self.ruleset.is_some() {
+ return Ok(());
+ }
+ let rs = load_rules(Path::new(&self.rules_path)).map_err(|e| e.to_string())?;
+ self.rules_warnings = rs.warnings.clone();
+ self.rules_check_ok = Some(true);
+ self.ruleset = Some(rs);
+ Ok(())
+ }
+
+ pub fn run_detect_on_path(&mut self, path: &Path) {
+ self.last_error = None;
+ if let Err(e) = self.ensure_ruleset() {
+ self.last_error = Some(e);
+ return;
+ }
+ let rules = self.ruleset.as_ref().unwrap();
+ match detect_capture_file(path, rules, &[]) {
+ Ok(mut alerts) => {
+ alerts.sort_by(|a, b| b.severity.cmp(&a.severity).then(b.timestamp_ms.cmp(&a.timestamp_ms)));
+ self.alerts = alerts;
+ self.selected_alert = None;
+ self.focus_tab(NetworkPane::Alerts);
+ self.status = format!("Detect: {} alert(s)", self.alerts.len());
+ }
+ Err(e) => self.last_error = Some(e),
+ }
+ }
+
+ pub fn run_detect_on_session(&mut self) {
+ let path = self
+ .capture_out_path
+ .clone()
+ .or_else(|| nonempty(&self.capture_replay));
+ let Some(path) = path else {
+ self.last_error = Some("No capture out_path — start capture or pick replay".into());
+ return;
+ };
+ self.run_detect_on_path(Path::new(&path));
+ }
+
+ pub fn refresh_alerts_from_buffer(&mut self) {
+ let mut alerts = last_alerts(Some(256));
+ alerts.sort_by(|a, b| b.severity.cmp(&a.severity).then(b.timestamp_ms.cmp(&a.timestamp_ms)));
+ if !alerts.is_empty() {
+ self.alerts = alerts;
+ }
+ }
+
+ pub fn compile_dig(&mut self) {
+ self.last_error = None;
+ let hint = self.hint_from_fields();
+ match compile_playbook(&hint) {
+ Ok(plan) => {
+ self.dig_plan = Some(plan);
+ self.dig_result = None;
+ self.status = "Playbook compiled".into();
+ }
+ Err(e) => self.last_error = Some(e),
+ }
+ }
+
+ pub fn execute_dig(&mut self) {
+ self.last_error = None;
+ let plan = match &self.dig_plan {
+ Some(p) => p.clone(),
+ None => match compile_playbook(&self.hint_from_fields()) {
+ Ok(p) => {
+ self.dig_plan = Some(p.clone());
+ p
+ }
+ Err(e) => {
+ self.last_error = Some(e);
+ return;
+ }
+ },
+ };
+ match execute_playbook_offline(&plan) {
+ Ok(result) => {
+ self.dig_result = Some(result);
+ self.status = "Dig execute ok".into();
+ if self.dig_attach_live {
+ self.pending_focus_debugger = true;
+ }
+ }
+ Err(e) => self.last_error = Some(e),
+ }
+ }
+
+ pub fn request_open_listing(&mut self) {
+ if let Some(p) = nonempty(&self.dig_path) {
+ self.pending_load_path = Some(p);
+ self.status = "Open in Listing requested".into();
+ } else {
+ self.last_error = Some("Dig path empty — cannot open Listing".into());
+ }
+ }
+
+ pub fn take_pending_load(&mut self) -> Option<String> {
+ self.pending_load_path.take()
+ }
+
+ pub fn take_pending_focus_debugger(&mut self) -> bool {
+ let v = self.pending_focus_debugger;
+ self.pending_focus_debugger = false;
+ v
+ }
+
+ /// Capture file path to reveal/export (session out_path, else replay).
+ pub fn export_path(&self) -> Option<String> {
+ self.capture_out_path
+ .clone()
+ .or_else(|| {
+ self.session_info
+ .as_ref()
+ .and_then(|s| s.out_path.clone())
+ })
+ .or_else(|| nonempty(&self.capture_replay))
+ }
+
+ /// Copy/reveal capture export path; returns the path string for clipboard.
+ pub fn reveal_export_path(&mut self) -> Result<String, String> {
+ let Some(path) = self.export_path() else {
+ return Err("No capture out_path — start capture or set replay path".into());
+ };
+ let p = PathBuf::from(&path);
+ if !p.exists() {
+ self.status = format!("Export path (file not written yet): {path}");
+ } else {
+ self.status = format!("Export path: {path}");
+ }
+ self.last_error = None;
+ // Best-effort: open containing folder in the OS file manager.
+ #[cfg(windows)]
+ {
+ let _ = std::process::Command::new("explorer")
+ .args(["/select,", &path])
+ .spawn();
+ }
+ #[cfg(target_os = "macos")]
+ {
+ let _ = std::process::Command::new("open")
+ .args(["-R", &path])
+ .spawn();
+ }
+ #[cfg(all(unix, not(target_os = "macos")))]
+ {
+ if let Some(parent) = p.parent() {
+ let _ = std::process::Command::new("xdg-open").arg(parent).spawn();
+ }
+ }
+ Ok(path)
+ }
+}
+
+fn nonempty(s: &str) -> Option<String> {
+ let t = s.trim();
+ if t.is_empty() {
+ None
+ } else {
+ Some(t.to_string())
+ }
+}
+
+fn merge_pivots(acc: &mut PivotFields, p: PivotFields) {
+ for x in p.dns_qnames {
+ if !acc.dns_qnames.contains(&x) {
+ acc.dns_qnames.push(x);
+ }
+ }
+ for x in p.tls_sni {
+ if !acc.tls_sni.contains(&x) {
+ acc.tls_sni.push(x);
+ }
+ }
+ for x in p.http_hosts {
+ if !acc.http_hosts.contains(&x) {
+ acc.http_hosts.push(x);
+ }
+ }
+ for x in p.http_uris {
+ if !acc.http_uris.contains(&x) {
+ acc.http_uris.push(x);
+ }
+ }
+ for x in p.smb_shares {
+ if !acc.smb_shares.contains(&x) {
+ acc.smb_shares.push(x);
+ }
+ }
+ if acc.ja3.is_none() {
+ acc.ja3 = p.ja3;
+ }
+}
+
+fn conf_badge(c: Confidence) -> &'static str {
+ c.as_str()
+}
+
+fn severity_color(sev: u8) -> Color32 {
+ match sev {
+ 1 => Color32::from_rgb(0xC6, 0x28, 0x28), // critical-ish
+ 2 => Color32::from_rgb(0xE5, 0x39, 0x35),
+ 3 => Color32::from_rgb(0xFB, 0x8C, 0x00),
+ 4 => Color32::from_rgb(0xF9, 0xA8, 0x25),
+ _ => Color32::from_rgb(0x90, 0xA4, 0xAE),
+ }
+}
+
+/// Migrate layout open_panes into host_open / active_tab.
+pub fn apply_layout_flags(
+ state: &mut NetworkState,
+ open_panes: &std::collections::BTreeMap<String, bool>,
+) {
+ let host = open_panes.get(HOST_EGUI_ID).copied().unwrap_or(false);
+ let mut first_open: Option<NetworkPane> = None;
+ let mut any_tab = false;
+ for p in NetworkPane::TAB_ORDER {
+ if open_panes.get(p.egui_id()).copied().unwrap_or(false) {
+ any_tab = true;
+ if first_open.is_none() {
+ first_open = Some(*p);
+ }
+ }
+ }
+ if host || any_tab {
+ state.host_open = true;
+ state.enabled = true;
+ if let Some(tab) = first_open {
+ state.active_tab = tab;
+ }
+ } else if open_panes.contains_key(HOST_EGUI_ID) {
+ state.host_open = host;
+ if !host {
+ state.enabled = false;
+ }
+ }
+}
+
+pub fn snapshot_layout_flags(
+ state: &NetworkState,
+ open_panes: &mut std::collections::BTreeMap<String, bool>,
+) {
+ open_panes.insert(HOST_EGUI_ID.to_string(), state.host_open);
+ for p in NetworkPane::ALL {
+ open_panes.insert(
+ p.egui_id().to_string(),
+ state.host_open && state.active_tab == *p,
+ );
+ }
+}
+
+pub fn draw_host(ctx: &egui::Context, state: &mut NetworkState, muted: Color32) {
+ if !state.host_open {
+ return;
+ }
+ // Poll capture while running.
+ if state.session_info.as_ref().map(|s| s.running).unwrap_or(false) {
+ let due = state
+ .last_poll
+ .map(|t| t.elapsed() >= Duration::from_millis(750))
+ .unwrap_or(true);
+ if due {
+ state.refresh_capture_status();
+ state.refresh_flows();
+ }
+ ctx.request_repaint_after(Duration::from_millis(500));
+ }
+
+ let mut open = true;
+ let title = state.window_title();
+ egui::Window::new(title)
+ .id(egui::Id::new(HOST_EGUI_ID))
+ .open(&mut open)
+ .resizable(true)
+ .default_size(egui::vec2(780.0, 560.0))
+ .min_size(egui::vec2(440.0, 300.0))
+ .show(ctx, |ui| {
+ let avail = ui.available_size();
+ ui.set_min_size(avail);
+ render_host_body(state, ui, muted);
+ });
+ if !open {
+ state.host_open = false;
+ }
+}
+
+fn render_host_body(state: &mut NetworkState, ui: &mut Ui, muted: Color32) {
+ let info = network_info();
+ let inline_on = inline_block_allowed();
+ ui.horizontal(|ui| {
+ ui.label(
+ RichText::new(format!(
+ "Ghidnet · wave={} · native={} · capture={} · inline={}",
+ info.wave, info.native, info.capture, if inline_on { "on" } else { "off" }
+ ))
+ .strong(),
+ );
+ ui.small(
+ RichText::new(format!("caps: {}", info.caps.join(",")))
+ .color(muted),
+ );
+ });
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(state.status_line()).color(muted));
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ let inline_resp = ui
+ .add_enabled(inline_on, egui::Button::new("Inline block").small())
+ .on_hover_text(inline_block_reason());
+ if inline_resp.clicked() {
+ state.status = inline_block_reason().into();
+ }
+ if !inline_on {
+ ui.small(RichText::new("inline off").color(muted))
+ .on_hover_text(inline_block_reason());
+ }
+ });
+ });
+ if let Some(e) = state.last_error.clone() {
+ ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), e);
+ }
+ ui.separator();
+
+ egui::ScrollArea::horizontal()
+ .id_salt("net_tab_strip")
+ .show(ui, |ui| {
+ ui.horizontal(|ui| {
+ for tab in NetworkPane::TAB_ORDER {
+ let selected = state.active_tab == *tab;
+ if ui.selectable_label(selected, tab.short_title()).clicked() {
+ state.active_tab = *tab;
+ }
+ }
+ });
+ });
+ ui.separator();
+
+ let pane = state.active_tab;
+ ui.small(RichText::new(format!("Provider · {}", pane.plugin())).color(muted));
+ ui.separator();
+ match pane {
+ NetworkPane::Connections => render_connections(state, ui, muted),
+ NetworkPane::Capture => render_capture(state, ui, muted),
+ NetworkPane::Alerts => render_alerts(state, ui, muted),
+ NetworkPane::Rules => render_rules(state, ui, muted),
+ NetworkPane::Dig => render_dig(state, ui, muted),
+ }
+}
+
+fn render_connections(state: &mut NetworkState, ui: &mut Ui, muted: Color32) {
+ ui.small(
+ RichText::new("Owner-first sockets — Dig fills NetHint from the selected row.")
+ .color(muted),
+ );
+ ui.horizontal(|ui| {
+ if ui.button("Refresh").clicked() {
+ state.refresh_connections();
+ }
+ ui.label("pid");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.conn_filter_pid)
+ .desired_width(56.0)
+ .hint_text("any"),
+ );
+ ui.label("path");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.conn_filter_path)
+ .desired_width(120.0)
+ .hint_text("substr"),
+ );
+ ui.label("proto");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.conn_filter_proto)
+ .desired_width(48.0)
+ .hint_text("tcp"),
+ );
+ ui.checkbox(&mut state.conn_listening_only, "listening");
+ ui.label("max");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.conn_max)
+ .desired_width(40.0)
+ .hint_text("256"),
+ );
+ let dig_en = state.selected_conn.is_some();
+ if ui
+ .add_enabled(dig_en, egui::Button::new("Dig"))
+ .on_hover_text("Compile dig hint from selection")
+ .clicked()
+ {
+ if let Some(i) = state.selected_conn {
+ state.dig_from_connection(i);
+ }
+ }
+ });
+
+ egui::ScrollArea::vertical()
+ .id_salt("net_conn_table")
+ .max_height(280.0)
+ .show(ui, |ui| {
+ egui::Grid::new("net_conn_grid")
+ .num_columns(7)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Proto");
+ ui.strong("Local");
+ ui.strong("Remote");
+ ui.strong("State");
+ ui.strong("PID");
+ ui.strong("Image");
+ ui.strong("Conf");
+ ui.end_row();
+ if state.connections.is_empty() {
+ ui.label(RichText::new("(empty — Refresh)").color(muted));
+ ui.end_row();
+ }
+ let rows: Vec<(usize, ConnectionView)> = state
+ .connections
+ .iter()
+ .cloned()
+ .enumerate()
+ .collect();
+ for (i, c) in rows {
+ let selected = state.selected_conn == Some(i);
+ let resp = ui.selectable_label(selected, &c.proto);
+ if resp.clicked() {
+ state.select_connection(i);
+ }
+ ui.monospace(&c.local);
+ ui.monospace(&c.remote);
+ ui.label(&c.state);
+ ui.label(c.pid.to_string());
+ ui.monospace(c.image_path.as_deref().unwrap_or("—"));
+ ui.small(format!(
+ "{}/{}",
+ conf_badge(c.pid_confidence),
+ conf_badge(c.image_confidence)
+ ));
+ ui.end_row();
+ }
+ });
+ });
+
+ ui.separator();
+ ui.label(RichText::new("Owner detail").strong());
+ if let Some(o) = &state.selected_owner {
+ ui.monospace(format!(
+ "pid={} image={} pid_conf={} image_conf={}",
+ o.pid,
+ o.image_path.as_deref().unwrap_or("—"),
+ conf_badge(o.pid_confidence),
+ conf_badge(o.image_confidence)
+ ));
+ } else {
+ ui.small(RichText::new("Select a connection row.").color(muted));
+ }
+}
+
+fn render_capture(state: &mut NetworkState, ui: &mut Ui, muted: Color32) {
+ ui.small(
+ RichText::new(
+ "In-process session (same as MCP). Prefer replay for fixtures; live NIC may be stub.",
+ )
+ .color(muted),
+ );
+ ui.horizontal(|ui| {
+ if ui.button("Refresh ifaces").clicked() {
+ state.refresh_ifaces();
+ }
+ ui.label("iface");
+ egui::ComboBox::from_id_salt("net_iface")
+ .selected_text(&state.iface)
+ .show_ui(ui, |ui| {
+ for i in state.ifaces.clone() {
+ ui.selectable_value(&mut state.iface, i.clone(), i);
+ }
+ });
+ ui.label("filter");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.capture_filter)
+ .desired_width(100.0)
+ .hint_text("optional"),
+ );
+ ui.label("pid");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.capture_pid)
+ .desired_width(48.0)
+ .hint_text("opt"),
+ );
+ });
+ ui.horizontal(|ui| {
+ ui.label("path");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.capture_path_substr)
+ .desired_width(100.0)
+ .hint_text("owner substr"),
+ );
+ ui.label("replay");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.capture_replay)
+ .desired_width(180.0)
+ .hint_text("path.grncap"),
+ );
+ if ui.button("Browse…").clicked() {
+ if let Some(path) = rfd::FileDialog::new()
+ .add_filter("Ghidrust capture", &["grncap", "pcap"])
+ .pick_file()
+ {
+ state.capture_replay = path.display().to_string();
+ }
+ }
+ ui.label("out");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.capture_out_dir)
+ .desired_width(120.0)
+ .hint_text("temp"),
+ );
+ });
+ ui.horizontal(|ui| {
+ let running = state.session_info.as_ref().map(|s| s.running).unwrap_or(false);
+ if ui
+ .add_enabled(!running, egui::Button::new("Start"))
+ .clicked()
+ {
+ state.start_capture();
+ }
+ if ui
+ .add_enabled(running || state.session_id.is_some(), egui::Button::new("Stop"))
+ .clicked()
+ {
+ state.stop_capture();
+ }
+ if ui.button("Status").clicked() {
+ state.refresh_capture_status();
+ }
+ if ui.button("Flows").clicked() {
+ state.refresh_flows();
+ }
+ if ui.button("Detect").clicked() {
+ state.run_detect_on_session();
+ }
+ if ui.button("Pivots").clicked() {
+ state.extract_pivots_from_capture();
+ }
+ let export_en = state.export_path().is_some();
+ if ui
+ .add_enabled(export_en, egui::Button::new("Export path"))
+ .on_hover_text("Reveal capture out_path (copy + open folder)")
+ .clicked()
+ {
+ match state.reveal_export_path() {
+ Ok(path) => {
+ ui.ctx().copy_text(path);
+ }
+ Err(e) => state.last_error = Some(e),
+ }
+ }
+ let dig_en = state.selected_flow.is_some();
+ if ui.add_enabled(dig_en, egui::Button::new("Dig flow")).clicked() {
+ if let Some(i) = state.selected_flow {
+ state.dig_from_flow(i);
+ }
+ }
+ // Inline block: always visible; disabled with reason unless env opt-in.
+ let inline_on = inline_block_allowed();
+ let inline_resp = ui
+ .add_enabled(inline_on, egui::Button::new("Inline block"))
+ .on_hover_text(inline_block_reason());
+ if inline_resp.clicked() {
+ state.status = inline_block_reason().into();
+ }
+ });
+ if let Some(path) = state.export_path() {
+ ui.horizontal(|ui| {
+ ui.small(RichText::new("export:").color(muted));
+ ui.monospace(&path);
+ if ui.small_button("Copy").clicked() {
+ ui.ctx().copy_text(path);
+ state.status = "Export path copied".into();
+ }
+ });
+ }
+ if let Some(info) = &state.session_info {
+ ui.small(format!(
+ "session={} running={} bytes={} backend={} out={}",
+ info.session_id,
+ info.running,
+ info.bytes_written,
+ state.capture_backend.as_deref().unwrap_or("—"),
+ info.out_path.as_deref().unwrap_or("—")
+ ));
+ } else {
+ ui.small(RichText::new("No capture session.").color(muted));
+ }
+
+ // Pivot chips
+ if !state.pivots.dns_qnames.is_empty()
+ || !state.pivots.tls_sni.is_empty()
+ || !state.pivots.http_hosts.is_empty()
+ {
+ ui.horizontal_wrapped(|ui| {
+ ui.label(RichText::new("Pivots:").strong());
+ for h in state.pivots.dns_qnames.clone() {
+ if ui.small_button(format!("dns:{h}")).clicked() {
+ state.dig_host = h;
+ state.focus_tab(NetworkPane::Dig);
+ }
+ }
+ for h in state.pivots.tls_sni.clone() {
+ if ui.small_button(format!("sni:{h}")).clicked() {
+ state.dig_host = h;
+ state.focus_tab(NetworkPane::Dig);
+ }
+ }
+ for h in state.pivots.http_hosts.clone() {
+ if ui.small_button(format!("http:{h}")).clicked() {
+ state.dig_host = h;
+ state.focus_tab(NetworkPane::Dig);
+ }
+ }
+ });
+ }
+
+ ui.separator();
+ ui.label(RichText::new("Flows").strong());
+ egui::ScrollArea::vertical()
+ .id_salt("net_flows_table")
+ .max_height(240.0)
+ .show(ui, |ui| {
+ egui::Grid::new("net_flows_grid")
+ .num_columns(6)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Proto");
+ ui.strong("Src");
+ ui.strong("Dst");
+ ui.strong("Owner");
+ ui.strong("Tx/Rx");
+ ui.strong("Id");
+ ui.end_row();
+ let rows: Vec<(usize, AttributedFlow)> = state
+ .flows_cache
+ .iter()
+ .cloned()
+ .enumerate()
+ .collect();
+ for (i, f) in rows {
+ let selected = state.selected_flow == Some(i);
+ if ui
+ .selectable_label(selected, &f.key.proto)
+ .clicked()
+ {
+ state.selected_flow = Some(i);
+ }
+ ui.monospace(format!("{}:{}", f.key.src, f.key.src_port));
+ ui.monospace(format!("{}:{}", f.key.dst, f.key.dst_port));
+ ui.monospace(
+ f.owner
+ .as_ref()
+ .and_then(|o| o.image_path.as_deref())
+ .unwrap_or("—"),
+ );
+ ui.label(format!("{}/{}", f.bytes_tx, f.bytes_rx));
+ ui.small(f.flow_id.as_deref().unwrap_or("—"));
+ ui.end_row();
+ }
+ });
+ });
+}
+
+fn render_alerts(state: &mut NetworkState, ui: &mut Ui, muted: Color32) {
+ let mut counts = [0u32; 6];
+ for a in &state.alerts {
+ let i = a.severity.min(5) as usize;
+ counts[i] += 1;
+ }
+ ui.horizontal(|ui| {
+ ui.label(RichText::new("Severity counts:").color(muted));
+ for sev in 1..=5u8 {
+ let c = counts[sev as usize];
+ if c > 0 {
+ ui.colored_label(severity_color(sev), format!("s{sev}={c}"));
+ }
+ }
+ ui.label(format!("total={}", state.alerts.len()));
+ });
+ ui.horizontal(|ui| {
+ if ui.button("Refresh buffer").clicked() {
+ state.refresh_alerts_from_buffer();
+ }
+ if ui.button("Detect on capture…").clicked() {
+ state.run_detect_on_session();
+ }
+ if ui.button("Detect file…").clicked() {
+ if let Some(path) = rfd::FileDialog::new()
+ .add_filter("Capture", &["grncap", "pcap"])
+ .pick_file()
+ {
+ state.run_detect_on_path(&path);
+ }
+ }
+ let dig_en = state.selected_alert.is_some();
+ if ui
+ .add_enabled(dig_en, egui::Button::new("Dig"))
+ .on_hover_text("Closed-loop dig from alert (needs owner path or Dig path)")
+ .clicked()
+ {
+ if let Some(i) = state.selected_alert {
+ state.dig_from_alert(i);
+ }
+ }
+ });
+
+ egui::ScrollArea::vertical()
+ .id_salt("net_alerts_table")
+ .max_height(220.0)
+ .show(ui, |ui| {
+ egui::Grid::new("net_alerts_grid")
+ .num_columns(6)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Sev");
+ ui.strong("SID");
+ ui.strong("Msg");
+ ui.strong("Owner");
+ ui.strong("Host/IOC");
+ ui.strong("Id");
+ ui.end_row();
+ let rows: Vec<(usize, Alert)> =
+ state.alerts.iter().cloned().enumerate().collect();
+ for (i, a) in rows {
+ let selected = state.selected_alert == Some(i);
+ let sev_lab = ui.selectable_label(
+ selected,
+ RichText::new(a.severity.to_string()).color(severity_color(a.severity)),
+ );
+ if sev_lab.clicked() {
+ state.selected_alert = Some(i);
+ }
+ ui.label(a.sid.to_string());
+ ui.label(&a.msg);
+ ui.monospace(
+ a.owner
+ .as_ref()
+ .and_then(|o| o.image_path.as_deref())
+ .unwrap_or("—"),
+ );
+ ui.small(
+ a.host
+ .as_deref()
+ .or(a.ioc.as_deref())
+ .unwrap_or("—"),
+ );
+ ui.small(&a.id);
+ ui.end_row();
+ }
+ });
+ });
+
+ ui.separator();
+ ui.label(RichText::new("Alert detail").strong());
+ if let Some(i) = state.selected_alert {
+ if let Some(a) = state.alerts.get(i) {
+ egui::ScrollArea::vertical()
+ .id_salt("net_alert_detail")
+ .max_height(140.0)
+ .show(ui, |ui| {
+ ui.monospace(format!("id={} sid={} sev={}", a.id, a.sid, a.severity));
+ ui.label(&a.msg);
+ if let Some(o) = &a.owner {
+ ui.monospace(format!(
+ "owner pid={} path={}",
+ o.pid,
+ o.image_path.as_deref().unwrap_or("—")
+ ));
+ }
+ if let Some(fk) = &a.flow_key {
+ ui.monospace(format!(
+ "flow {} {}:{} → {}:{}",
+ fk.proto, fk.src, fk.src_port, fk.dst, fk.dst_port
+ ));
+ }
+ if let Some(h) = &a.host {
+ ui.label(format!("host: {h}"));
+ }
+ if let Some(ioc) = &a.ioc {
+ ui.label(format!("ioc: {ioc}"));
+ }
+ ui.small(
+ RichText::new("Next: Dig → compile/execute playbook on owner image")
+ .color(muted),
+ );
+ });
+ }
+ } else {
+ ui.small(RichText::new("Select an alert.").color(muted));
+ }
+}
+
+fn render_rules(state: &mut NetworkState, ui: &mut Ui, muted: Color32) {
+ ui.small(
+ RichText::new("GNR pack — Check before Detect. Default: rules/ghidrust-minimal.rules")
+ .color(muted),
+ );
+ ui.horizontal(|ui| {
+ ui.label("path");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.rules_path)
+ .desired_width(360.0)
+ .hint_text("rules/ghidrust-minimal.rules"),
+ );
+ if ui.button("Browse…").clicked() {
+ if let Some(path) = rfd::FileDialog::new()
+ .add_filter("GNR rules", &["rules", "rule"])
+ .pick_file()
+ {
+ state.rules_path = path.display().to_string();
+ }
+ }
+ if ui.button("Check").clicked() {
+ state.check_rules();
+ }
+ });
+ match state.rules_check_ok {
+ Some(true) => {
+ ui.colored_label(Color32::from_rgb(0x43, 0xA0, 0x47), "compile ok");
+ }
+ Some(false) => {
+ ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), "compile failed");
+ }
+ None => {
+ ui.small(RichText::new("Not checked yet.").color(muted));
+ }
+ }
+ for w in &state.rules_warnings {
+ ui.small(RichText::new(w).color(muted));
+ }
+ ui.separator();
+ if let Some(rs) = &state.ruleset {
+ ui.label(RichText::new(format!("Rules ({})", rs.rules.len())).strong());
+ egui::ScrollArea::vertical()
+ .id_salt("net_rules_list")
+ .max_height(280.0)
+ .show(ui, |ui| {
+ for r in &rs.rules {
+ rule_row(ui, r, muted);
+ }
+ });
+ }
+}
+
+fn rule_row(ui: &mut Ui, r: &Rule, muted: Color32) {
+ ui.horizontal(|ui| {
+ ui.colored_label(severity_color(r.severity), format!("s{}", r.severity));
+ ui.monospace(format!("sid:{}", r.sid));
+ ui.label(&r.msg);
+ ui.small(RichText::new(format!("{} {}→{}", r.action, r.proto, r.dst)).color(muted));
+ });
+}
+
+fn render_dig(state: &mut NetworkState, ui: &mut Ui, muted: Color32) {
+ ui.small(
+ RichText::new("Compile a dig playbook from NetHint, then Execute offline analysis.")
+ .color(muted),
+ );
+ ui.horizontal(|ui| {
+ ui.label("path");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.dig_path)
+ .desired_width(280.0)
+ .hint_text("image path"),
+ );
+ if ui.button("Browse…").clicked() {
+ if let Some(path) = rfd::FileDialog::new()
+ .add_filter("Binary", &["exe", "dll", "so", "elf", "pe"])
+ .pick_file()
+ {
+ state.dig_path = path.display().to_string();
+ }
+ }
+ ui.label("pid");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.dig_pid)
+ .desired_width(56.0)
+ .hint_text("opt"),
+ );
+ });
+ ui.horizontal(|ui| {
+ ui.label("host");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.dig_host)
+ .desired_width(140.0)
+ .hint_text("dns/ip"),
+ );
+ ui.label("ioc");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.dig_ioc)
+ .desired_width(100.0)
+ .hint_text("opt"),
+ );
+ ui.label("alert");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.dig_alert_id)
+ .desired_width(100.0)
+ .hint_text("id"),
+ );
+ ui.label("flow");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.dig_flow_ref)
+ .desired_width(80.0)
+ .hint_text("ref"),
+ );
+ });
+ ui.horizontal(|ui| {
+ ui.checkbox(&mut state.dig_attach_live, "attach_live (opens Debugger)");
+ if ui.button("Compile").clicked() {
+ state.compile_dig();
+ }
+ if ui.button("Execute").clicked() {
+ state.execute_dig();
+ }
+ if ui
+ .add_enabled(
+ !state.dig_path.trim().is_empty(),
+ egui::Button::new("Open in Listing"),
+ )
+ .clicked()
+ {
+ state.request_open_listing();
+ }
+ });
+
+ if let Some(plan) = &state.dig_plan {
+ ui.separator();
+ ui.label(RichText::new("Plan").strong());
+ ui.small(RichText::new(&plan.rationale).color(muted));
+ egui::ScrollArea::vertical()
+ .id_salt("net_dig_steps")
+ .max_height(140.0)
+ .show(ui, |ui| {
+ for (i, s) in plan.steps.iter().enumerate() {
+ ui.monospace(format!("{}. {} {}", i + 1, s.tool, s.args));
+ if let Some(n) = &s.note {
+ ui.small(RichText::new(n).color(muted));
+ }
+ }
+ for n in &plan.next_steps {
+ ui.small(format!("next: {n}"));
+ }
+ });
+ }
+
+ if let Some(result) = &state.dig_result {
+ ui.separator();
+ ui.label(RichText::new(format!("Result · {}", result.status)).strong());
+ egui::ScrollArea::vertical()
+ .id_salt("net_dig_findings")
+ .max_height(160.0)
+ .show(ui, |ui| {
+ for f in &result.findings {
+ ui.label(format!("[{}] {}", f.kind, f.detail));
+ if let Some(e) = &f.evidence {
+ ui.small(RichText::new(e).color(muted));
+ }
+ }
+ if result.findings.is_empty() {
+ ui.small(RichText::new("(no findings)").color(muted));
+ }
+ });
+ }
+
+ if let Some(job) = &state.dig_job {
+ ui.small(format!("job {} · {} · {}", job.job_id, job.source, job.status));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn default_rules_path_resolvable_or_fallback() {
+ let p = default_rules_path();
+ assert!(!p.is_empty());
+ }
+
+ #[test]
+ fn compile_dig_from_fixture_path() {
+ let pe = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/tiny_x64.pe");
+ assert!(pe.is_file(), "missing fixture {}", pe.display());
+ let mut st = NetworkState::default();
+ st.dig_path = pe.display().to_string();
+ st.dig_host = "example.test".into();
+ st.compile_dig();
+ assert!(st.last_error.is_none(), "{:?}", st.last_error);
+ assert!(st.dig_plan.is_some());
+ assert!(!st.dig_plan.as_ref().unwrap().steps.is_empty());
+ }
+
+ #[test]
+ fn layout_flags_round_trip() {
+ let mut st = NetworkState::default();
+ st.host_open = true;
+ st.enabled = true;
+ st.active_tab = NetworkPane::Alerts;
+ let mut map = std::collections::BTreeMap::new();
+ snapshot_layout_flags(&st, &mut map);
+ assert_eq!(map.get(HOST_EGUI_ID), Some(&true));
+ let mut st2 = NetworkState::default();
+ apply_layout_flags(&mut st2, &map);
+ assert!(st2.host_open);
+ assert_eq!(st2.active_tab, NetworkPane::Alerts);
+ }
+
+ #[test]
+ fn dig_from_connection_sets_hint() {
+ let mut st = NetworkState::default();
+ st.connections.push(ConnectionView {
+ proto: "tcp".into(),
+ local: "127.0.0.1:1".into(),
+ remote: "10.0.0.2:443".into(),
+ state: "ESTABLISHED".into(),
+ pid: 1,
+ pid_confidence: Confidence::Exact,
+ image_path: Some("C:\\app.exe".into()),
+ image_confidence: Confidence::Likely,
+ });
+ st.dig_from_connection(0);
+ assert_eq!(st.active_tab, NetworkPane::Dig);
+ assert_eq!(st.dig_path, "C:\\app.exe");
+ assert_eq!(st.dig_host, "10.0.0.2:443");
+ }
+
+ #[test]
+ fn network_info_matches_cli_surface() {
+ let info = network_info();
+ assert!(info.native);
+ assert!(info.capture);
+ assert_eq!(info.wave, 5);
+ for need in ["dig", "capture", "detect", "pivots", "connections"] {
+ assert!(info.caps.iter().any(|c| c == need), "missing cap {need}");
+ }
+ }
+
+ #[test]
+ fn inline_block_reason_mentions_env_when_off() {
+ std::env::remove_var("GHIDRUST_NET_INLINE");
+ let r = inline_block_reason();
+ assert!(r.contains("GHIDRUST_NET_INLINE"));
+ assert!(!inline_block_allowed());
+ }
+
+ #[test]
+ fn reveal_export_path_uses_replay_fallback() {
+ let mut st = NetworkState::default();
+ assert!(st.reveal_export_path().is_err());
+ st.capture_replay = "C:\\tmp\\fixture.grncap".into();
+ let p = st.reveal_export_path().expect("replay fallback");
+ assert!(p.ends_with("fixture.grncap"));
+ assert!(st.status.contains("Export path"));
+ }
+}
diff --git a/crates/ghidrust-gui/src/panes.rs b/crates/ghidrust-gui/src/panes.rs
index 0881213..f5d6a34 100644
--- a/crates/ghidrust-gui/src/panes.rs
+++ b/crates/ghidrust-gui/src/panes.rs
@@ -7,7 +7,7 @@
//!
//! Source anchors: see internal UI notes § 1.1 and § 1.2.
-use eframe::egui::{self, Color32, RichText, Ui};
+use eframe::egui::{Color32, RichText, Ui};
/// One provider (window / dockable pane).
///
@@ -63,6 +63,12 @@ pub enum PaneKind {
Il2cppMethods,
/// Unity native icall name‖fn table pairing.
Il2cppIcalls,
+ /// Metadata string-heap touch-map (`ghidrust_il2cpp::touch_map`).
+ Il2cppTouchMap,
+ /// IL2CPP resolve-stub scanner (`ghidrust_il2cpp::find_resolve_stubs`).
+ Il2cppStubs,
+ /// Unity player install inventory (`ghidrust_unity_inventory::inventory_path`).
+ UnityInventory,
/// Folder → PE inventory (VERSIONINFO catalog) via `ghidrust_core::inventory`.
InstallInventory,
/// Bounded directory tree browser via `ghidrust_core::tree_index`.
@@ -121,6 +127,9 @@ impl PaneKind {
PaneKind::Il2cppMetadata,
PaneKind::Il2cppMethods,
PaneKind::Il2cppIcalls,
+ PaneKind::Il2cppTouchMap,
+ PaneKind::Il2cppStubs,
+ PaneKind::UnityInventory,
PaneKind::InstallInventory,
PaneKind::FileSystemBrowser,
PaneKind::AnalysisArtifacts,
@@ -169,20 +178,15 @@ impl PaneKind {
PaneKind::Il2cppMetadata => "IL2CPP Metadata",
PaneKind::Il2cppMethods => "IL2CPP Methods",
PaneKind::Il2cppIcalls => "IL2CPP ICalls",
+ PaneKind::Il2cppTouchMap => "IL2CPP Touch Map",
+ PaneKind::Il2cppStubs => "IL2CPP Stubs",
+ PaneKind::UnityInventory => "Unity Inventory",
PaneKind::InstallInventory => "Install Inventory",
PaneKind::FileSystemBrowser => "File System Browser",
PaneKind::AnalysisArtifacts => "Analysis Artifacts",
}
}
- /// Short shell-pane test name (used by `GhidrustApp::shell_panes()`).
- ///
- /// Kept alphabetical + unique so structural tests can assert every provider is present.
- pub const fn shell_pane_name(self) -> &'static str {
- // Titles happen to be unique across our catalog; use them as canonical.
- self.title()
- }
-
/// plugin owner (for empty-state hint text).
pub const fn plugin(self) -> &'static str {
match self {
@@ -226,6 +230,9 @@ impl PaneKind {
PaneKind::Il2cppMetadata => "Il2cppMetadataPlugin",
PaneKind::Il2cppMethods => "Il2cppMethodMapPlugin",
PaneKind::Il2cppIcalls => "Il2cppICallsPlugin",
+ PaneKind::Il2cppTouchMap => "Il2cppTouchMapPlugin",
+ PaneKind::Il2cppStubs => "Il2cppStubsPlugin",
+ PaneKind::UnityInventory => "UnityInventoryPlugin",
PaneKind::InstallInventory => "InstallInventoryPlugin",
PaneKind::FileSystemBrowser => "FileSystemBrowserPlugin",
PaneKind::AnalysisArtifacts => "AnalysisArtifactsPlugin",
@@ -233,6 +240,7 @@ impl PaneKind {
}
/// True if backend implementation is Stage-0 or better (used to hide "backend pending" copy).
+ #[cfg(test)]
pub const fn has_backend(self) -> bool {
matches!(
self,
@@ -271,9 +279,14 @@ impl PaneKind {
| PaneKind::Il2cppMetadata
| PaneKind::Il2cppMethods
| PaneKind::Il2cppIcalls
+ | PaneKind::Il2cppTouchMap
+ | PaneKind::Il2cppStubs
+ | PaneKind::UnityInventory
| PaneKind::InstallInventory
| PaneKind::FileSystemBrowser
| PaneKind::AnalysisArtifacts
+ | PaneKind::RegisterManager
+ | PaneKind::DataTypeManager
)
}
@@ -320,6 +333,9 @@ impl PaneKind {
PaneKind::Il2cppMetadata => "pane_il2cpp_metadata",
PaneKind::Il2cppMethods => "pane_il2cpp_methods",
PaneKind::Il2cppIcalls => "pane_il2cpp_icalls",
+ PaneKind::Il2cppTouchMap => "pane_il2cpp_touch_map",
+ PaneKind::Il2cppStubs => "pane_il2cpp_stubs",
+ PaneKind::UnityInventory => "pane_unity_inventory",
PaneKind::InstallInventory => "pane_install_inventory",
PaneKind::FileSystemBrowser => "pane_fs_browser",
PaneKind::AnalysisArtifacts => "pane_analysis_artifacts",
@@ -403,26 +419,26 @@ pub fn empty_state(ui: &mut Ui, kind: PaneKind, muted: Color32) {
pub const fn backend_pending_message(kind: PaneKind) -> &'static str {
match kind {
PaneKind::AgentConsole => "",
- PaneKind::Bookmarks => "Backend pending — Bookmarks model + margin markers land in .",
+ PaneKind::Bookmarks => "Session bookmarks with margin markers.",
PaneKind::Bytes => "",
PaneKind::ChecksumGenerator => "",
- PaneKind::CommentWindow => "Backend pending — comment model lands in .",
+ PaneKind::CommentWindow => "Program comments filter + jump to VA.",
PaneKind::Console => "",
- PaneKind::DataTypeManager => "Backend pending — DTM tree (Built-In / Program / Archive) lands in .",
+ PaneKind::DataTypeManager => "",
PaneKind::DataTypePreview => "",
PaneKind::DecompiledView => "Stage-1 SSA-C (expression fold + typed locals/params). Emit-time tokens when available; rename/commit wired.",
PaneKind::CryptoCapabilities => "",
PaneKind::CryptoConstants => "",
PaneKind::Decrypt => "",
- PaneKind::DefinedData => "Backend pending — Program::data_items model lands in .",
+ PaneKind::DefinedData => "Defined-data proxy from strings + RTTI; Apply-at-address via DTM.",
PaneKind::DefinedStrings => "Uses ghidrust-core::analyzers::strings::run — session-only until Program::strings lands.",
- PaneKind::DisassembledView => "Backend pending — virtual disassembly + pcode preview lands in .",
- PaneKind::Entropy => "Backend pending — GPU/CPU histogram lands in .",
+ PaneKind::DisassembledView => "Listing-backed disassembly view.",
+ PaneKind::Entropy => "Shannon entropy strip over mapped blocks.",
PaneKind::EquatesTable => "",
PaneKind::ExternalPrograms => "",
- PaneKind::FunctionCallGraph => "Backend pending — level-based directed graph lands in .",
- PaneKind::FunctionCallTrees => "Backend pending — incoming/outgoing GTree pair lands in .",
- PaneKind::FunctionGraph => "Backend pending — CFG vertex/edge layout lands in .",
+ PaneKind::FunctionCallGraph => "Level-based directed call graph from Stage-0 refs.",
+ PaneKind::FunctionCallTrees => "Incoming callers / outgoing callees trees.",
+ PaneKind::FunctionGraph => "CFG vertex/edge layout from Stage-0 blocks.",
PaneKind::FunctionTags => "",
PaneKind::FunctionsWindow => "Uses Program::analysis.functions.",
PaneKind::Listing => "",
@@ -430,46 +446,27 @@ pub const fn backend_pending_message(kind: PaneKind) -> &'static str {
PaneKind::Overview => "",
PaneKind::ProgramTree => "",
PaneKind::ProjectTree => "",
- PaneKind::Python => "Backend pending — scripting host / MCP REPL lands in .",
+ PaneKind::Python => "MCP REPL — tool_name / tool_name {json} via ghidrust mcp (non-network).",
PaneKind::RecoveredStrings => "",
- PaneKind::RegisterManager => "Backend pending — register lattice values from live/debug backends.",
- PaneKind::RelocationTable => "Uses Program::sections metadata; full PE/ELF reloc parse lands in .",
- PaneKind::ScriptManager => "Backend pending — script catalog lands in .",
+ PaneKind::RegisterManager => "",
+ PaneKind::RelocationTable => "",
+ PaneKind::ScriptManager => "Catalog of ghidrust MCP tools; Run → CLI mapping or mcp tools/call.",
PaneKind::SymbolReferences => "",
PaneKind::SymbolTable => "Uses Program::analysis.symbols + functions (flat table).",
PaneKind::SymbolTree => "",
- PaneKind::TextEditor => "Backend pending — script editor lands in .",
+ PaneKind::TextEditor => "Multi-tab in-memory editor (Open/Save via rfd).",
PaneKind::Il2cppMetadata => "",
PaneKind::Il2cppMethods => "",
PaneKind::Il2cppIcalls => "",
+ PaneKind::Il2cppTouchMap => "",
+ PaneKind::Il2cppStubs => "",
+ PaneKind::UnityInventory => "",
PaneKind::InstallInventory => "",
PaneKind::FileSystemBrowser => "",
PaneKind::AnalysisArtifacts => "",
}
}
-/// Egui window helper: draw a floating provider pane with a close-toggle backing bool.
-///
-/// Kept as a public helper for future refactors that centralise floating-window creation.
-#[allow(dead_code)] // used by future refactor consolidating floating panes
-pub fn open_pane_window(
- ctx: &egui::Context,
- open: &mut bool,
- kind: PaneKind,
- default_size: egui::Vec2,
- add_contents: impl FnOnce(&mut Ui),
-) {
- if !*open {
- return;
- }
- egui::Window::new(kind.title())
- .id(egui::Id::new(kind.egui_id()))
- .open(open)
- .default_size(default_size)
- .resizable(true)
- .show(ctx, add_contents);
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ghidrust-gui/src/register_manager.rs b/crates/ghidrust-gui/src/register_manager.rs
index 74d8a54..3cfe239 100644
--- a/crates/ghidrust-gui/src/register_manager.rs
+++ b/crates/ghidrust-gui/src/register_manager.rs
@@ -15,6 +15,7 @@
//! instead of piling into `main.rs`.
use eframe::egui::{self, Color32, Ui};
+use ghidrust_core::process::RegisterSet;
use std::collections::BTreeMap;
/// One user-set register value covering an address range.
@@ -36,6 +37,15 @@ pub struct RegisterManagerState {
pub input_start: String,
pub input_end: String,
pub input_value: String,
+ /// Last live snapshot pulled from debugger (`process_thread_context_get`).
+ pub live_snapshot: Option<RegisterSet>,
+}
+
+impl RegisterManagerState {
+ /// Refresh from an optional live `RegisterSet` (debugger session).
+ pub fn apply_live_registers(&mut self, regs: Option<&RegisterSet>) {
+ self.live_snapshot = regs.cloned();
+ }
}
/// One node in the register lattice tree.
@@ -520,23 +530,79 @@ pub fn group_by_kind() -> BTreeMap<RegisterKind, Vec<&'static RegisterNode>> {
}
/// Render the Register Manager pane.
+///
+/// `live_regs` — optional refresh from the Debugger host
+/// (`process_thread_context_get` when attached in debug mode).
pub fn render(
state: &mut RegisterManagerState,
format: Option<&str>,
+ live_regs: Option<&RegisterSet>,
ui: &mut Ui,
muted: Color32,
primary: Color32,
) {
+ if live_regs.is_some() {
+ state.apply_live_registers(live_regs);
+ }
ui.heading("Register Manager");
let arch = format.unwrap_or("(no program)");
ui.small(
egui::RichText::new(format!(
- "Register Manager · {arch} register lattice · session-only values"
+ "Register Manager · {arch} register lattice · session values + optional live debug sync"
))
.color(muted),
);
ui.separator();
+ if let Some(regs) = &state.live_snapshot {
+ egui::CollapsingHeader::new("Live (debugger)")
+ .default_open(true)
+ .show(ui, |ui| {
+ ui.small(
+ egui::RichText::new("Synced from process_thread_context_get when attached")
+ .color(muted),
+ );
+ egui::Grid::new("regmgr_live_grid")
+ .num_columns(2)
+ .striped(true)
+ .show(ui, |ui| {
+ for (n, v) in [
+ ("RAX", regs.rax),
+ ("RBX", regs.rbx),
+ ("RCX", regs.rcx),
+ ("RDX", regs.rdx),
+ ("RSI", regs.rsi),
+ ("RDI", regs.rdi),
+ ("RBP", regs.rbp),
+ ("RSP", regs.rsp),
+ ("R8", regs.r8),
+ ("R9", regs.r9),
+ ("R10", regs.r10),
+ ("R11", regs.r11),
+ ("R12", regs.r12),
+ ("R13", regs.r13),
+ ("R14", regs.r14),
+ ("R15", regs.r15),
+ ("RIP", regs.rip),
+ ("RFLAGS", regs.rflags),
+ ] {
+ ui.monospace(n);
+ ui.monospace(format!("{v:#x}"));
+ ui.end_row();
+ }
+ });
+ });
+ ui.separator();
+ } else {
+ ui.small(
+ egui::RichText::new(
+ "No live debugger registers — attach in debug mode to sync via process_thread_context_get.",
+ )
+ .color(muted)
+ .italics(),
+ );
+ }
+
ui.horizontal(|ui| {
ui.label("Filter:");
ui.add(
diff --git a/crates/ghidrust-gui/src/relocations.rs b/crates/ghidrust-gui/src/relocations.rs
new file mode 100644
index 0000000..8f8534c
--- /dev/null
+++ b/crates/ghidrust-gui/src/relocations.rs
@@ -0,0 +1,267 @@
+//! Best-effort PE base-reloc / ELF RELA parse from `Program::file_bytes`.
+//!
+//! Honest empty results on parse failure — never fabricate entries.
+
+use ghidrust_core::Program;
+
+/// One relocation / fixup row for the Relocation Table pane.
+#[derive(Debug, Clone)]
+pub struct RelocationRow {
+ pub va: u64,
+ pub kind: String,
+ pub detail: String,
+}
+
+/// Parse relocations from the loaded program bytes (PE `.reloc` / ELF `SHT_RELA`).
+pub fn parse_relocations(prog: &Program) -> Vec<RelocationRow> {
+ let fmt = prog.format.to_ascii_lowercase();
+ if fmt.starts_with("pe") {
+ parse_pe_base_relocs(&prog.file_bytes, prog.image_base)
+ } else if fmt.starts_with("elf") {
+ parse_elf_rela(&prog.file_bytes)
+ } else {
+ Vec::new()
+ }
+}
+
+fn parse_pe_base_relocs(data: &[u8], image_base: u64) -> Vec<RelocationRow> {
+ if data.len() < 0x40 || &data[0..2] != b"MZ" {
+ return Vec::new();
+ }
+ let e_lfanew = u32::from_le_bytes(data[0x3C..0x40].try_into().unwrap_or([0; 4])) as usize;
+ if e_lfanew + 24 > data.len() || &data[e_lfanew..e_lfanew + 4] != b"PE\0\0" {
+ return Vec::new();
+ }
+ let opt = e_lfanew + 24;
+ let magic = rdu16(data, opt).unwrap_or(0);
+ let data_dir = match magic {
+ 0x10b => opt + 96, // PE32
+ 0x20b => opt + 112, // PE32+
+ _ => return Vec::new(),
+ };
+ // IMAGE_DIRECTORY_ENTRY_BASERELOC = 5
+ let dir_off = data_dir + 5 * 8;
+ let Some(reloc_rva) = rdu32(data, dir_off).map(|v| v as u64) else {
+ return Vec::new();
+ };
+ let Some(reloc_size) = rdu32(data, dir_off + 4).map(|v| v as u64) else {
+ return Vec::new();
+ };
+ if reloc_rva == 0 || reloc_size == 0 {
+ return Vec::new();
+ }
+ let Some(mut off) = rva_to_file(data, reloc_rva) else {
+ return Vec::new();
+ };
+ let end = off.saturating_add(reloc_size as usize).min(data.len());
+ let mut out = Vec::new();
+ const MAX_ROWS: usize = 50_000;
+ while off + 8 <= end && out.len() < MAX_ROWS {
+ let block_rva = match rdu32(data, off) {
+ Some(v) => v as u64,
+ None => break,
+ };
+ let block_size = match rdu32(data, off + 4) {
+ Some(v) => v as usize,
+ None => break,
+ };
+ if block_size < 8 {
+ break;
+ }
+ let block_end = off.saturating_add(block_size).min(end);
+ let mut entry = off + 8;
+ while entry + 2 <= block_end && out.len() < MAX_ROWS {
+ let raw = match rdu16(data, entry) {
+ Some(v) => v,
+ None => break,
+ };
+ entry += 2;
+ let typ = (raw >> 12) as u8;
+ let ofs = (raw & 0x0fff) as u64;
+ if typ == 0 {
+ // IMAGE_REL_BASED_ABSOLUTE — padding
+ continue;
+ }
+ let va = image_base.wrapping_add(block_rva).wrapping_add(ofs);
+ out.push(RelocationRow {
+ va,
+ kind: pe_reloc_kind(typ).into(),
+ detail: format!("block_rva={block_rva:#x} type={typ}"),
+ });
+ }
+ off = block_end;
+ }
+ out
+}
+
+fn pe_reloc_kind(t: u8) -> &'static str {
+ match t {
+ 1 => "HIGH",
+ 2 => "LOW",
+ 3 => "HIGHLOW",
+ 4 => "HIGHADJ",
+ 5 => "MIPS_JMPADDR",
+ 10 => "DIR64",
+ _ => "OTHER",
+ }
+}
+
+fn parse_elf_rela(data: &[u8]) -> Vec<RelocationRow> {
+ if data.len() < 64 || data[0..4] != [0x7f, b'E', b'L', b'F'] {
+ return Vec::new();
+ }
+ if data[4] != 2 || data[5] != 1 {
+ // ELF64 LE only
+ return Vec::new();
+ }
+ let e_shoff = rdu64(data, 40).unwrap_or(0) as usize;
+ let e_shentsize = rdu16(data, 58).unwrap_or(0) as usize;
+ let e_shnum = rdu16(data, 60).unwrap_or(0) as usize;
+ let e_shstrndx = rdu16(data, 62).unwrap_or(0) as usize;
+ if e_shoff == 0 || e_shentsize < 64 || e_shnum == 0 {
+ return Vec::new();
+ }
+ let shstr_off = e_shoff + e_shstrndx * e_shentsize;
+ let shstr_offset = rdu64(data, shstr_off + 24).unwrap_or(0) as usize;
+ let shstr_size = rdu64(data, shstr_off + 32).unwrap_or(0) as usize;
+ let shstr = if shstr_offset + shstr_size <= data.len() {
+ &data[shstr_offset..shstr_offset + shstr_size]
+ } else {
+ &[][..]
+ };
+
+ let mut out = Vec::new();
+ const MAX_ROWS: usize = 50_000;
+ for i in 0..e_shnum {
+ let off = e_shoff + i * e_shentsize;
+ if off + 64 > data.len() {
+ break;
+ }
+ let name_off = rdu32(data, off).unwrap_or(0) as usize;
+ let sh_type = rdu32(data, off + 4).unwrap_or(0);
+ // SHT_RELA = 4
+ if sh_type != 4 {
+ continue;
+ }
+ let sh_offset = rdu64(data, off + 24).unwrap_or(0) as usize;
+ let sh_size = rdu64(data, off + 32).unwrap_or(0) as usize;
+ let sh_entsize = rdu64(data, off + 56).unwrap_or(24) as usize;
+ if sh_entsize < 24 || sh_size == 0 {
+ continue;
+ }
+ let sec_name = cstr_from(shstr, name_off);
+ let mut cur = sh_offset;
+ let end = sh_offset.saturating_add(sh_size).min(data.len());
+ while cur + 24 <= end && out.len() < MAX_ROWS {
+ let r_offset = rdu64(data, cur).unwrap_or(0);
+ let r_info = rdu64(data, cur + 8).unwrap_or(0);
+ let r_addend = rdu64(data, cur + 16).unwrap_or(0) as i64;
+ cur += sh_entsize;
+ let typ = (r_info & 0xffff_ffff) as u32;
+ out.push(RelocationRow {
+ va: r_offset,
+ kind: elf_rela_kind(typ).into(),
+ detail: format!("section={sec_name} info={r_info:#x} addend={r_addend}"),
+ });
+ }
+ }
+ out
+}
+
+fn elf_rela_kind(t: u32) -> &'static str {
+ match t {
+ 0 => "R_X86_64_NONE",
+ 1 => "R_X86_64_64",
+ 2 => "R_X86_64_PC32",
+ 8 => "R_X86_64_RELATIVE",
+ 10 => "R_X86_64_32",
+ _ => "R_X86_64_*",
+ }
+}
+
+fn cstr_from(buf: &[u8], off: usize) -> String {
+ if off >= buf.len() {
+ return String::new();
+ }
+ let end = buf[off..]
+ .iter()
+ .position(|&b| b == 0)
+ .map(|p| off + p)
+ .unwrap_or(buf.len());
+ String::from_utf8_lossy(&buf[off..end]).into_owned()
+}
+
+fn rva_to_file(data: &[u8], rva: u64) -> Option<usize> {
+ if data.len() < 0x40 {
+ return None;
+ }
+ let e_lfanew = u32::from_le_bytes(data[0x3C..0x40].try_into().ok()?) as usize;
+ let coff = e_lfanew + 4;
+ let num_sections = rdu16(data, coff + 2)? as usize;
+ let opt_size = rdu16(data, coff + 16)? as usize;
+ let sec_table = coff + 20 + opt_size;
+ for i in 0..num_sections {
+ let off = sec_table + i * 40;
+ if off + 40 > data.len() {
+ break;
+ }
+ let virt_size = rdu32(data, off + 8)? as u64;
+ let va_rva = rdu32(data, off + 12)? as u64;
+ let raw_size = rdu32(data, off + 16)? as u64;
+ let file_off = rdu32(data, off + 20)? as u64;
+ let span = virt_size.max(raw_size);
+ if rva >= va_rva && rva < va_rva + span {
+ let delta = rva - va_rva;
+ if delta < raw_size {
+ return Some((file_off + delta) as usize);
+ }
+ }
+ }
+ None
+}
+
+fn rdu16(data: &[u8], off: usize) -> Option<u16> {
+ if off + 2 > data.len() {
+ return None;
+ }
+ Some(u16::from_le_bytes(data[off..off + 2].try_into().ok()?))
+}
+
+fn rdu32(data: &[u8], off: usize) -> Option<u32> {
+ if off + 4 > data.len() {
+ return None;
+ }
+ Some(u32::from_le_bytes(data[off..off + 4].try_into().ok()?))
+}
+
+fn rdu64(data: &[u8], off: usize) -> Option<u64> {
+ if off + 8 > data.len() {
+ return None;
+ }
+ Some(u64::from_le_bytes(data[off..off + 8].try_into().ok()?))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ghidrust_core::load_path;
+ use std::path::PathBuf;
+
+ fn fixture(name: &str) -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("../../fixtures")
+ .join(name)
+ }
+
+ #[test]
+ fn pe_fixture_parses_or_empty_honestly() {
+ let path = fixture("tiny_x64.pe");
+ if !path.is_file() {
+ return;
+ }
+ let prog = load_path(&path).expect("load");
+ let rows = parse_relocations(&prog);
+ // tiny fixture may have zero relocs; must not panic.
+ assert!(rows.len() < 50_000);
+ }
+}
diff --git a/crates/ghidrust-gui/src/scripts.rs b/crates/ghidrust-gui/src/scripts.rs
index a55619f..e96c64e 100644
--- a/crates/ghidrust-gui/src/scripts.rs
+++ b/crates/ghidrust-gui/src/scripts.rs
@@ -1,23 +1,15 @@
-//! Ghidrust GUI ·, Text Editor, and
-//! MCP REPL / interpreter panes.
+//! Ghidrust GUI Script Manager, Text Editor, and MCP REPL panes.
//!
-//! `` (Text Editor), and
-//! `` (Python REPL) get honest Ghidrust analogs:
-//!
-//! **** — categorised catalog of shipped Ghidrust MCP tools
-//! (see `skill/SKILL.md`). Selecting a tool shows its description; the
-//! `Run` button emits a Console message so users see the parity surface
-//! without a live MCP host wired up.
-//! - **Text Editor** — multi-tab in-memory editor for `.rust` / `.py`
-//! scripts on disk. Uses `rfd` to Open/Save files.
-//! - **MCP REPL** — a line-oriented prompt that logs commands to Console
-//! and echoes a "Backend pending" hint. Full REPL wires into the
-//! `ghidrust-cli mcp` stdio host in a follow-up.
-//!
-//! Extracted per internal modularization notes — new UI panes land here
-//! instead of piling into `main.rs`.
-
+//! - **Script Manager** — catalog of shipped Ghidrust MCP tools (non-network).
+//! `Run` invokes `ghidrust` CLI (when mappable) or `ghidrust mcp` tools/call.
+//! - **Text Editor** — multi-tab in-memory editor for scripts on disk.
+//! - **MCP REPL** — line-oriented `tool_name` / `tool_name {json}` → MCP/CLI.
+
+use crate::mcp_host::{
+ invoke_tool, invoke_tool_with_session, parse_tool_line, McpStdioSession,
+};
use eframe::egui::{self, Color32, Ui};
+use serde_json::json;
use std::path::PathBuf;
/// One script entry (Ghidrust MCP tools double as the catalog).
@@ -30,9 +22,7 @@ pub struct ScriptEntry {
pub key_binding: String,
}
-/// Built-in catalog — mirrors the MCP tool surface described in
-/// `skill/SKILL.md`. Order = order (alphabetical
-/// within category).
+/// Built-in catalog — real `ghidrust mcp` tool names (excludes all `net_*`).
pub fn builtin_catalog() -> Vec<ScriptEntry> {
let s = |name: &str, cat: &str, desc: &str| ScriptEntry {
name: name.into(),
@@ -41,220 +31,274 @@ pub fn builtin_catalog() -> Vec<ScriptEntry> {
key_binding: String::new(),
};
vec![
+ // Core
s(
- "mcp.list_methods",
- "MCP · Functions",
- "Enumerate methods in the active program (paginated).",
+ "server_info",
+ "MCP · Core",
+ "Package version, tool_surface, and feature flags.",
),
s(
- "mcp.list_functions",
- "MCP · Functions",
- "List every recovered function entry.",
+ "load",
+ "MCP · Core",
+ "Load a PE or ELF binary (path or project+file_id).",
),
s(
- "mcp.search_functions_by_name",
- "MCP · Functions",
- "Substring search over function names.",
+ "list_analyzers",
+ "MCP · Analysis",
+ "List Auto Analysis options (labels).",
),
s(
- "mcp.decompile_function",
- "MCP · Decompiler",
- "Return pseudo-C for a named function.",
+ "analyze",
+ "MCP · Analysis",
+ "Run selected analyzers on a binary path; optional GPU enrich.",
),
s(
- "mcp.decompile_function_by_address",
- "MCP · Decompiler",
- "Return pseudo-C for a function at a VA.",
+ "list_gpu_strategies",
+ "MCP · Analysis",
+ "Per-analyzer GPU strategy matrix.",
),
+ // Disasm / decode
s(
- "mcp.disassemble_function",
- "MCP · Decompiler",
- "Return decoded listing for a function.",
+ "disassemble",
+ "MCP · Disasm",
+ "Disassemble at addr with decode engine options.",
),
s(
- "mcp.rename_function",
- "MCP · Edits",
- "Rename the function at a VA.",
+ "decode_support",
+ "MCP · Disasm",
+ "Report decode engine / arch support matrix.",
),
s(
- "mcp.rename_function_by_address",
- "MCP · Edits",
- "Rename by address.",
+ "decode_query",
+ "MCP · Disasm",
+ "Engine introspection (insn/reg/group queries).",
),
s(
- "mcp.rename_variable",
- "MCP · Edits",
- "Rename a local variable inside a function.",
+ "read_bytes",
+ "MCP · Disasm",
+ "Read raw bytes at a VA from a loaded path.",
),
+ // Decompile
s(
- "mcp.rename_data",
- "MCP · Edits",
- "Rename a global data item.",
+ "decompile",
+ "MCP · Decompile",
+ "Stage-1 expression-folded typed C; optional follow_stub.",
),
s(
- "mcp.set_function_prototype",
- "MCP · Edits",
- "Set the C signature of a function.",
+ "gpu_decompile",
+ "MCP · Decompile",
+ "GPU VRAM multipass decompile to .gdecomp.",
+ ),
+ // Strings / crypto
+ s(
+ "list_strings",
+ "MCP · Strings",
+ "ASCII/UTF-16 strings; match/limit/raw blob.",
),
s(
- "mcp.set_local_variable_type",
- "MCP · Edits",
- "Retype a local variable.",
+ "search_strings",
+ "MCP · Strings",
+ "Filter-oriented alias of list_strings.",
),
s(
- "mcp.set_decompiler_comment",
- "MCP · Comments",
- "Attach a decompiler-side comment.",
+ "crypt_constants",
+ "MCP · Crypto",
+ "Scan cryptographic constant tables (S-boxes, TEA, …).",
),
s(
- "mcp.set_disassembly_comment",
- "MCP · Comments",
- "Attach a listing-side comment.",
+ "list_crypt_constants",
+ "MCP · Crypto",
+ "List detected crypto constant hits (catalog form).",
),
s(
- "mcp.list_classes",
- "MCP · Program",
- "Enumerate C++/RTTI classes recovered.",
+ "recover_strings",
+ "MCP · Crypto",
+ "Recover obfuscated strings, optionally scoped to functions.",
),
s(
- "mcp.list_namespaces",
- "MCP · Program",
- "Enumerate scoped namespaces.",
+ "decode_bake",
+ "MCP · Crypto",
+ "Bake explicit decode operations over input bytes.",
),
s(
- "mcp.list_segments",
- "MCP · Program",
- "Enumerate mapped memory blocks / sections.",
+ "decode_magic",
+ "MCP · Crypto",
+ "Suggest and apply a decode recipe from input bytes.",
),
s(
- "mcp.list_imports",
- "MCP · Program",
- "Enumerate PE import / IAT slots.",
+ "list_crypto_capabilities",
+ "MCP · Crypto",
+ "List detected cryptographic capabilities.",
),
+ // Functions / xrefs
s(
- "mcp.list_exports",
- "MCP · Program",
- "Enumerate exported symbols.",
+ "function_at",
+ "MCP · Functions",
+ "Containing function for a body VA.",
),
s(
- "mcp.list_data_items",
- "MCP · Program",
- "Enumerate defined data items.",
+ "get_function_by_address",
+ "MCP · Functions",
+ "Fetch function metadata by VA.",
),
s(
- "mcp.list_strings",
- "MCP · Program",
- "ASCII/UTF-16 strings; match/limit/raw blob.",
+ "function_create",
+ "MCP · Functions",
+ "Create/heal a function at VA (optional end).",
),
s(
- "mcp.search_strings",
- "MCP · Program",
- "Alias of list_strings (filter-oriented).",
+ "get_xrefs_to",
+ "MCP · Xrefs",
+ "Refs to a VA; optional skip_stubs/classify.",
),
s(
- "mcp.get_import_xrefs",
+ "get_xrefs_from",
"MCP · Xrefs",
- "Code sites referencing an import IAT slot.",
+ "References emitted from a VA.",
),
s(
- "mcp.get_string_xrefs",
+ "get_calls_from",
"MCP · Xrefs",
- "Resolve strings by filter, then xrefs to each.",
+ "Call sites from a function VA.",
),
s(
- "mcp.get_xrefs_to",
+ "list_imports",
"MCP · Xrefs",
- "Refs to a VA; optional skip_stubs/classify.",
+ "Enumerate PE import / IAT slots.",
),
s(
- "mcp.get_xrefs_from",
+ "get_import_xrefs",
"MCP · Xrefs",
- "References emitted from a VA.",
+ "Code sites referencing an import IAT slot.",
),
s(
- "mcp.get_function_xrefs",
+ "get_string_xrefs",
"MCP · Xrefs",
- "Callers and callees of a function.",
+ "Resolve strings by filter, then xrefs to each.",
+ ),
+ // Artifacts / FS
+ s(
+ "inventory",
+ "MCP · FS",
+ "Generic PE install inventory (exe/dll + VERSIONINFO).",
+ ),
+ s(
+ "list_tree",
+ "MCP · FS",
+ "Bounded file tree index (size/mtime).",
+ ),
+ s(
+ "artifact_list",
+ "MCP · Artifacts",
+ "List recent spilled analysis artifacts.",
+ ),
+ s(
+ "artifact_query",
+ "MCP · Artifacts",
+ "Page through an artifact with offset/limit.",
),
s(
- "mcp.il2cpp_meta",
+ "artifact_get",
+ "MCP · Artifacts",
+ "Fetch a spilled analysis artifact by id or path.",
+ ),
+ // IL2CPP / Unity
+ s(
+ "il2cpp_meta",
"MCP · IL2CPP",
"Parse global-metadata.dat types/methods.",
),
s(
- "mcp.il2cpp_map",
+ "il2cpp_map",
"MCP · IL2CPP",
"Metadata ↔ RVA map (null when unproven).",
),
s(
- "mcp.il2cpp_stubs",
+ "il2cpp_touch_map",
+ "MCP · IL2CPP",
+ "Substring touch-map over metadata heaps.",
+ ),
+ s(
+ "il2cpp_stubs",
"MCP · IL2CPP",
"List IL2CPP resolve stubs by icall name.",
),
s(
- "mcp.unity_inventory",
+ "il2cpp_icalls",
+ "MCP · IL2CPP",
+ "Resolve Unity engine icall name‖fn pointer tables.",
+ ),
+ s(
+ "unity_inventory",
"MCP · Unity",
"Player install inventory (assemblies, plugins, metadata).",
),
+ // RTTI
s(
- "mcp.function_at",
- "MCP · Functions",
- "Containing function for a body VA.",
+ "rtti",
+ "MCP · RTTI",
+ "Recover C++ RTTI class names and vtable links.",
),
s(
- "mcp.function_create",
- "MCP · Functions",
- "Create/heal a function at VA (optional end).",
+ "rtti_query",
+ "MCP · RTTI",
+ "RTTI catalog query (filter/exact) with multi-vtable honesty.",
),
s(
- "mcp.decompile",
- "MCP · Decompile",
- "Stage-1 C; optional follow_stub for IL2CPP.",
+ "rtti_gpu_bench",
+ "MCP · RTTI",
+ "CPU recover_rtti vs GPU rtti_scan with PCIe split.",
),
+ // Process
s(
- "mcp.get_current_address",
- "MCP · Cursor",
- "Report the currently focused Listing VA.",
+ "process_list",
+ "MCP · Process",
+ "List OS processes (Live Process Bridge).",
),
s(
- "mcp.get_current_function",
- "MCP · Cursor",
- "Report the function containing the cursor.",
+ "process_attach",
+ "MCP · Process",
+ "Attach to pid; mode=observe|debug.",
),
s(
- "mcp.get_function_by_address",
- "MCP · Functions",
- "Fetch function metadata by VA.",
+ "process_modules",
+ "MCP · Process",
+ "List modules for an attached session.",
),
s(
- "crypt_constants",
- "MCP · Crypto",
- "Crypto Constants constant-table hits.",
+ "process_break_set",
+ "MCP · Process",
+ "Set software breakpoint (debug mode).",
),
s(
- "recover_strings",
- "MCP · Crypto",
- "Recover obfuscated strings, optionally scoped to functions.",
+ "process_continue",
+ "MCP · Process",
+ "Continue a stopped debug session.",
),
s(
- "decode_bake",
- "MCP · Crypto",
- "Bake explicit decode operations over input bytes.",
+ "process_step_into",
+ "MCP · Process",
+ "Single-step into (TF).",
),
s(
- "decode_magic",
- "MCP · Crypto",
- "Suggest and apply a decode recipe from input bytes.",
+ "process_step_over",
+ "MCP · Process",
+ "Single-step over (TF MVP).",
),
s(
- "list_crypto_capabilities",
- "MCP · Crypto",
- "List detected cryptographic capabilities.",
+ "process_step_out",
+ "MCP · Process",
+ "Step out of current frame (debug mode).",
+ ),
+ s(
+ "process_vtable_probe",
+ "MCP · Process",
+ "Validate object* vtable; list slot targets as live VAs.",
),
]
}
-/// session state.
+/// Script Manager session state.
#[derive(Debug, Clone, Default)]
pub struct ScriptManagerState {
pub catalog: Vec<ScriptEntry>,
@@ -262,6 +306,9 @@ pub struct ScriptManagerState {
pub selected: Option<usize>,
/// User-assigned category filter ("" = all).
pub category_filter: String,
+ /// Last Run stdout / JSON / error text shown in the pane.
+ pub last_result: String,
+ pub last_run_name: String,
}
impl ScriptManagerState {
@@ -355,10 +402,12 @@ impl TextEditorState {
}
/// MCP REPL session state.
-#[derive(Debug, Clone, Default)]
+#[derive(Default)]
pub struct MacropadReplState {
pub input: String,
pub transcript: Vec<ReplLine>,
+ /// Persistent `ghidrust mcp` child when available.
+ session: Option<McpStdioSession>,
}
#[derive(Debug, Clone)]
@@ -377,10 +426,10 @@ impl MacropadReplState {
prompt: true,
text: cmd.clone(),
});
- // Echo response: backend-pending honest hint.
- let out = format!(
- "Backend pending — MCP REPL not yet wired to ghidrust mcp stdio host. See skill/SKILL.md."
- );
+ let out = match parse_tool_line(&cmd) {
+ Ok((name, args)) => invoke_tool_with_session(&mut self.session, &name, &args),
+ Err(e) => e,
+ };
self.transcript.push(ReplLine {
prompt: false,
text: out.clone(),
@@ -390,9 +439,14 @@ impl MacropadReplState {
}
}
+/// Run a catalog tool (empty args) via CLI mapping or MCP tools/call.
+pub fn run_catalog_tool(name: &str) -> String {
+ invoke_tool(name, &json!({}))
+}
+
// ── Rendering ────────────────────────────────────────────────────────────────
-/// Render the. Returns `Some(name)` if a Run was requested.
+/// Render Script Manager. Returns `Some(name)` if a Run was requested.
pub fn render_script_manager(
state: &mut ScriptManagerState,
ui: &mut Ui,
@@ -402,7 +456,7 @@ pub fn render_script_manager(
ui.heading("Script Manager");
ui.small(
egui::RichText::new(
- "Script Manager · catalog is Ghidrust's MCP tool surface (see skill/SKILL.md)",
+ "Script Manager · Ghidrust MCP tools (non-network) · Run → ghidrust CLI / mcp",
)
.color(muted),
);
@@ -454,7 +508,7 @@ pub fn render_script_manager(
let mut requested_run: Option<String> = None;
egui::ScrollArea::vertical()
.id_salt("scriptmgr_scroll")
- .max_height(360.0)
+ .max_height(280.0)
.show(ui, |ui| {
egui::Grid::new("scriptmgr_grid")
.num_columns(5)
@@ -501,6 +555,27 @@ pub fn render_script_manager(
}
}
+ if let Some(name) = requested_run.clone() {
+ let out = run_catalog_tool(&name);
+ state.last_run_name = name;
+ state.last_result = out;
+ }
+
+ if !state.last_result.is_empty() {
+ ui.separator();
+ ui.label(
+ egui::RichText::new(format!("Result · {}", state.last_run_name))
+ .strong()
+ .color(primary),
+ );
+ egui::ScrollArea::vertical()
+ .id_salt("scriptmgr_result")
+ .max_height(180.0)
+ .show(ui, |ui| {
+ ui.monospace(egui::RichText::new(&state.last_result).color(muted));
+ });
+ }
+
requested_run
}
@@ -619,7 +694,10 @@ pub fn render_mcp_repl(
primary: Color32,
) {
ui.heading("Python (MCP REPL)");
- ui.small(egui::RichText::new("MCP REPL · pipes to ghidrust mcp (stub)").color(muted));
+ ui.small(
+ egui::RichText::new("MCP REPL · ghidrust mcp stdio (tool_name or tool_name {json})")
+ .color(muted),
+ );
ui.separator();
egui::ScrollArea::vertical()
@@ -642,7 +720,7 @@ pub fn render_mcp_repl(
let resp = ui.add(
egui::TextEdit::singleline(&mut state.input)
.desired_width(ui.available_width() - 80.0)
- .hint_text("call an MCP tool… e.g. mcp.list_functions"),
+ .hint_text(r#"server_info | list_strings {"path":"…"}"#),
);
let submit = ui.button("Run").clicked()
|| (resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)));
@@ -660,16 +738,50 @@ mod tests {
fn builtin_catalog_covers_ghidrust_mcp_surface() {
let cat = builtin_catalog();
assert!(cat.len() >= 20);
+ assert!(
+ !cat.iter().any(|s| s.name.starts_with("net_")),
+ "catalog must exclude net_* tools"
+ );
for want in [
- "mcp.list_functions",
- "mcp.decompile_function",
- "mcp.rename_function",
- "mcp.get_xrefs_to",
+ "load",
+ "analyze",
+ "disassemble",
+ "decompile",
+ "list_strings",
"crypt_constants",
- "recover_strings",
- "decode_bake",
- "decode_magic",
- "list_crypto_capabilities",
+ "function_at",
+ "function_create",
+ "get_xrefs_to",
+ "get_xrefs_from",
+ "get_calls_from",
+ "inventory",
+ "list_tree",
+ "artifact_list",
+ "artifact_query",
+ "artifact_get",
+ "il2cpp_meta",
+ "il2cpp_map",
+ "il2cpp_icalls",
+ "il2cpp_touch_map",
+ "il2cpp_stubs",
+ "unity_inventory",
+ "decode_support",
+ "decode_query",
+ "process_list",
+ "process_attach",
+ "process_modules",
+ "process_break_set",
+ "process_continue",
+ "process_step_into",
+ "process_step_over",
+ "process_step_out",
+ "process_vtable_probe",
+ "server_info",
+ "list_analyzers",
+ "list_gpu_strategies",
+ "rtti",
+ "rtti_query",
+ "rtti_gpu_bench",
] {
assert!(cat.iter().any(|s| s.name == want), "missing {want}");
}
@@ -702,11 +814,13 @@ mod tests {
#[test]
fn repl_submit_appends_prompt_and_response() {
let mut r = MacropadReplState::default();
- r.input = "mcp.list_functions".into();
+ r.input = "server_info".into();
r.submit();
assert_eq!(r.transcript.len(), 2);
assert!(r.transcript[0].prompt);
assert!(!r.transcript[1].prompt);
assert!(r.input.is_empty());
+ // Response is either real JSON from CLI/MCP or a resolve error — never the old stub.
+ assert!(!r.transcript[1].text.contains("Backend pending"));
}
}
diff --git a/crates/ghidrust-gui/src/theme.rs b/crates/ghidrust-gui/src/theme.rs
new file mode 100644
index 0000000..7c617db
--- /dev/null
+++ b/crates/ghidrust-gui/src/theme.rs
@@ -0,0 +1,144 @@
+//! egui theme application for Ghidrust appearance + mode.
+
+use eframe::egui::{self, Color32, Visuals};
+use ghidrust_core::{theme_tokens, AppearanceTheme, ThemeMode};
+
+/// Resolve color tokens for the given appearance + mode.
+pub fn tokens(appearance: AppearanceTheme, theme: ThemeMode) -> ghidrust_core::M3Tokens {
+ theme_tokens(appearance, theme)
+}
+
+/// Whether egui should start from dark visuals for this appearance + mode.
+///
+/// Future Console is always a dark CRT/neon panel (both gases).
+pub fn prefers_dark_visuals(appearance: AppearanceTheme, theme: ThemeMode) -> bool {
+ match (appearance, theme) {
+ (AppearanceTheme::FutureConsole, _) => true,
+ (_, ThemeMode::Dark) => true,
+ (_, ThemeMode::Light) => false,
+ }
+}
+
+/// Apply Material / console visuals and spacing to the egui context.
+pub fn apply(ctx: &egui::Context, appearance: AppearanceTheme, theme: ThemeMode) {
+ let t = tokens(appearance, theme);
+ // Future Console is always a dark CRT/neon panel (both gases).
+ let mut v = if prefers_dark_visuals(appearance, theme) {
+ Visuals::dark()
+ } else {
+ Visuals::light()
+ };
+ let rgb = |c: [u8; 3]| Color32::from_rgb(c[0], c[1], c[2]);
+ let corner = egui::CornerRadius::same(t.corner_radius);
+ let stroke = egui::Stroke::new(t.stroke_width, rgb(t.outline));
+ v.override_text_color = Some(rgb(t.on_surface));
+ v.widgets.noninteractive.bg_fill = rgb(t.surface_container);
+ v.widgets.noninteractive.fg_stroke = egui::Stroke::new(1.0, rgb(t.on_surface));
+ v.widgets.noninteractive.corner_radius = corner;
+ v.widgets.inactive.bg_fill = rgb(t.surface_container);
+ v.widgets.inactive.fg_stroke = egui::Stroke::new(1.0, rgb(t.on_surface));
+ v.widgets.inactive.bg_stroke = stroke;
+ v.widgets.inactive.corner_radius = corner;
+ v.widgets.hovered.bg_fill = match appearance {
+ AppearanceTheme::FutureConsole => rgb(t.surface_bright),
+ AppearanceTheme::Modern => rgb(t.primary_container).gamma_multiply(0.55),
+ AppearanceTheme::ClassicGhidrust => rgb(t.primary).gamma_multiply(0.25),
+ };
+ v.widgets.hovered.bg_stroke = egui::Stroke::new(t.stroke_width, rgb(t.secondary));
+ v.widgets.hovered.corner_radius = corner;
+ v.widgets.active.bg_fill = match appearance {
+ AppearanceTheme::FutureConsole => rgb(t.primary),
+ AppearanceTheme::Modern => rgb(t.primary).gamma_multiply(0.45),
+ AppearanceTheme::ClassicGhidrust => rgb(t.primary).gamma_multiply(0.35),
+ };
+ v.widgets.active.fg_stroke = egui::Stroke::new(
+ 1.0,
+ match appearance {
+ AppearanceTheme::FutureConsole => rgb(t.on_primary),
+ _ => rgb(t.on_surface),
+ },
+ );
+ v.widgets.active.corner_radius = corner;
+ v.widgets.open.bg_fill = rgb(t.surface_container_high);
+ v.widgets.open.corner_radius = corner;
+ v.panel_fill = rgb(t.surface);
+ v.window_fill = rgb(t.surface_container);
+ v.extreme_bg_color = rgb(t.surface_dim);
+ v.faint_bg_color = rgb(t.surface_container_low);
+ v.selection.bg_fill = match appearance {
+ AppearanceTheme::FutureConsole => rgb(t.primary).gamma_multiply(0.55),
+ _ => rgb(t.primary).gamma_multiply(0.4),
+ };
+ v.hyperlink_color = rgb(t.primary);
+ v.warn_fg_color = rgb(t.error);
+ v.window_corner_radius = corner;
+ v.menu_corner_radius = corner;
+ v.popup_shadow = match appearance {
+ AppearanceTheme::FutureConsole => egui::Shadow::NONE,
+ AppearanceTheme::Modern => egui::Shadow {
+ offset: [0, 2],
+ blur: 8,
+ spread: 0,
+ color: Color32::from_black_alpha(40),
+ },
+ AppearanceTheme::ClassicGhidrust => v.popup_shadow,
+ };
+ ctx.set_visuals(v);
+ // Wider side/top grab for resizable panels (bottom console drag).
+ // Future Console: 4px half-cell spacing (Amber Console --space-1).
+ ctx.style_mut(|s| {
+ s.interaction.resize_grab_radius_side = 12.0;
+ if appearance == AppearanceTheme::FutureConsole {
+ s.spacing.item_spacing = egui::vec2(8.0, 8.0);
+ s.spacing.button_padding = egui::vec2(22.0, 10.0);
+ } else if appearance == AppearanceTheme::Modern {
+ s.spacing.item_spacing = egui::vec2(8.0, 8.0);
+ s.spacing.button_padding = egui::vec2(16.0, 8.0);
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn prefers_dark_visuals_future_console_light() {
+ assert!(prefers_dark_visuals(
+ AppearanceTheme::FutureConsole,
+ ThemeMode::Light
+ ));
+ }
+
+ #[test]
+ fn prefers_dark_visuals_future_console_dark() {
+ assert!(prefers_dark_visuals(
+ AppearanceTheme::FutureConsole,
+ ThemeMode::Dark
+ ));
+ }
+
+ #[test]
+ fn prefers_dark_visuals_modern_dark() {
+ assert!(prefers_dark_visuals(
+ AppearanceTheme::Modern,
+ ThemeMode::Dark
+ ));
+ }
+
+ #[test]
+ fn prefers_dark_visuals_modern_light() {
+ assert!(!prefers_dark_visuals(
+ AppearanceTheme::Modern,
+ ThemeMode::Light
+ ));
+ }
+
+ #[test]
+ fn prefers_dark_visuals_classic_light() {
+ assert!(!prefers_dark_visuals(
+ AppearanceTheme::ClassicGhidrust,
+ ThemeMode::Light
+ ));
+ }
+}
diff --git a/crates/ghidrust-gui/src/tool_panes.rs b/crates/ghidrust-gui/src/tool_panes.rs
index f66665f..e467c93 100644
--- a/crates/ghidrust-gui/src/tool_panes.rs
+++ b/crates/ghidrust-gui/src/tool_panes.rs
@@ -8,14 +8,16 @@
use eframe::egui::{self, Color32, RichText, Ui};
use ghidrust_core::{
- artifact_query, list_artifacts, ArtifactEnvelope, ArtifactMeta, PeInventory, PeInventoryEntry,
- Program, ResolveResult, TreeEntry, TreeListOpts, TreeListResult,
+ artifact_get, artifact_query, list_artifacts, ArtifactEnvelope, ArtifactMeta, PeInventory,
+ PeInventoryEntry, Program, ResolveResult, TreeEntry, TreeListOpts, TreeListResult,
};
use ghidrust_il2cpp::{
binary::{correlate, MethodMap, MethodMapEntry},
+ find_resolve_stubs, stub_matches_filter, touch_map, ResolveStub, TouchMapReport,
icall::{filter_entries, resolve_icalls_path, ICallEntry, ICallResolveReport},
metadata::Il2CppMetadata,
};
+use ghidrust_unity_inventory::UnityInventory;
fn err_label(ui: &mut Ui, err: &str) {
ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), err);
@@ -27,6 +29,9 @@ pub struct ToolPanesState {
pub il2cpp_meta: Il2cppMetaState,
pub il2cpp_methods: Il2cppMethodsState,
pub il2cpp_icalls: Il2cppIcallsState,
+ pub il2cpp_touch_map: Il2cppTouchMapState,
+ pub il2cpp_stubs: Il2cppStubsState,
+ pub unity_inventory: UnityInventoryState,
pub install_inventory: InstallInventoryState,
pub fs_browser: FileSystemBrowserState,
pub artifacts: AnalysisArtifactsState,
@@ -474,6 +479,392 @@ fn resolve_icalls_via_owned(prog: &mut Program) -> Result<ICallResolveReport, St
ghidrust_il2cpp::icall::resolve_icalls(prog).map_err(|e| e.to_string())
}
+// ── IL2CPP Touch Map ────────────────────────────────────────────────────
+
+#[derive(Default)]
+pub struct Il2cppTouchMapState {
+ pub use_loaded_program: bool,
+ pub meta_path_input: String,
+ pub binary_path_input: String,
+ pub filter: String,
+ pub report: Option<TouchMapReport>,
+ pub error: Option<String>,
+}
+
+impl Il2cppTouchMapState {
+ fn new_default() -> Self {
+ Self {
+ use_loaded_program: true,
+ ..Default::default()
+ }
+ }
+}
+
+pub fn ui_il2cpp_touch_map(
+ ui: &mut Ui,
+ s: &mut Il2cppTouchMapState,
+ program: Option<&Program>,
+ muted: Color32,
+) {
+ if s.meta_path_input.is_empty() && s.report.is_none() && s.filter.is_empty() {
+ *s = Il2cppTouchMapState::new_default();
+ }
+ ui.heading("IL2CPP Touch Map");
+ ui.small(
+ RichText::new(
+ "ghidrust-il2cpp::touch_map · metadata string-heap → method/type hits (+ optional RVA)",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ 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();
+ }
+ }
+ });
+ ui.checkbox(
+ &mut s.use_loaded_program,
+ "Correlate RVA against currently loaded program (optional)",
+ );
+ 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("GameAssembly.dll (optional)"),
+ );
+ 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();
+ }
+ }
+ });
+ } else if let Some(p) = program {
+ ui.small(format!("Binary: {} (loaded)", p.name));
+ }
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.filter)
+ .desired_width(240.0)
+ .hint_text("substring…"),
+ );
+ let can_run = !s.meta_path_input.trim().is_empty() && !s.filter.trim().is_empty();
+ if ui
+ .add_enabled(can_run, egui::Button::new("Build touch map"))
+ .clicked()
+ {
+ s.error = None;
+ s.report = None;
+ let owned = if s.use_loaded_program {
+ None
+ } else if s.binary_path_input.trim().is_empty() {
+ 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.as_ref()
+ };
+ let meta = std::path::Path::new(s.meta_path_input.trim());
+ match touch_map(Some(meta), None, s.filter.trim(), prog_ref) {
+ Ok(rep) => s.report = Some(rep),
+ Err(e) => s.error = Some(e.to_string()),
+ }
+ }
+ });
+ if let Some(e) = &s.error {
+ err_label(ui, e);
+ }
+ let Some(report) = &s.report else {
+ ui.weak("Enter a metadata path + filter substring to build the touch map.");
+ return;
+ };
+ ui.small(format!(
+ "filter={:?} · {} row(s)",
+ report.filter, report.row_count
+ ));
+ for n in &report.notes {
+ ui.small(RichText::new(n).color(muted).italics());
+ }
+ let row_h = ui.text_style_height(&egui::TextStyle::Monospace) + 2.0;
+ egui::ScrollArea::vertical()
+ .id_salt("il2cpp_touch_map_scroll")
+ .auto_shrink([false, false])
+ .max_height(360.0)
+ .show_rows(ui, row_h, report.rows.len(), |ui, range| {
+ for i in range {
+ let r = &report.rows[i];
+ let va = r
+ .va
+ .map(|v| format!("{v:#x}"))
+ .unwrap_or_else(|| "—".into());
+ ui.monospace(format!(
+ "{:?} conf={:?} va={va} {} {}",
+ r.kind,
+ r.confidence,
+ r.string,
+ r.full_name.as_deref().unwrap_or("-")
+ ));
+ }
+ });
+}
+
+// ── IL2CPP Stubs ────────────────────────────────────────────────────────
+
+pub struct Il2cppStubsState {
+ pub use_loaded_program: bool,
+ pub binary_path_input: String,
+ pub filter: String,
+ pub max_scan: usize,
+ pub stubs: Vec<ResolveStub>,
+ pub error: Option<String>,
+ pub scanned: bool,
+}
+
+impl Default for Il2cppStubsState {
+ fn default() -> Self {
+ Self {
+ use_loaded_program: true,
+ binary_path_input: String::new(),
+ filter: String::new(),
+ max_scan: 250_000,
+ stubs: Vec::new(),
+ error: None,
+ scanned: false,
+ }
+ }
+}
+
+pub fn ui_il2cpp_stubs(
+ ui: &mut Ui,
+ s: &mut Il2cppStubsState,
+ program: Option<&Program>,
+ muted: Color32,
+) {
+ ui.heading("IL2CPP Stubs");
+ ui.small(
+ RichText::new(
+ "ghidrust-il2cpp::find_resolve_stubs · lazy resolve thunks (LEA name → call → jmp reg)",
+ )
+ .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("GameAssembly.dll / il2cpp binary"),
+ );
+ 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();
+ }
+ }
+ });
+ } else if let Some(p) = program {
+ ui.small(format!("Binary: {} (loaded)", p.name));
+ } else {
+ ui.small(RichText::new("No program loaded.").color(muted));
+ }
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.filter)
+ .desired_width(200.0)
+ .hint_text("icall name…"),
+ );
+ ui.label("Max scan:");
+ ui.add(egui::DragValue::new(&mut s.max_scan).range(1_000..=2_000_000));
+ let can_run = s.use_loaded_program || !s.binary_path_input.trim().is_empty();
+ if ui
+ .add_enabled(can_run, egui::Button::new("Scan stubs"))
+ .clicked()
+ {
+ s.error = None;
+ s.stubs.clear();
+ s.scanned = true;
+ let owned = 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 Some(prog_ref) = (if s.use_loaded_program {
+ program
+ } else {
+ owned.as_ref()
+ }) else {
+ s.error = Some("no program available — load a binary first".into());
+ return;
+ };
+ let mut stubs = find_resolve_stubs(prog_ref, s.max_scan);
+ if !s.filter.trim().is_empty() {
+ stubs.retain(|st| stub_matches_filter(prog_ref, st, s.filter.trim()));
+ }
+ s.stubs = stubs;
+ }
+ });
+ if let Some(e) = &s.error {
+ err_label(ui, e);
+ }
+ if !s.scanned {
+ ui.weak("Scan an IL2CPP binary for resolve stubs.");
+ return;
+ }
+ ui.small(format!("{} stub(s)", s.stubs.len()));
+ let row_h = ui.text_style_height(&egui::TextStyle::Monospace) + 2.0;
+ egui::ScrollArea::vertical()
+ .id_salt("il2cpp_stubs_scroll")
+ .auto_shrink([false, false])
+ .max_height(360.0)
+ .show_rows(ui, row_h, s.stubs.len(), |ui, range| {
+ for i in range {
+ let st = &s.stubs[i];
+ ui.monospace(format!(
+ "{:#x} {} slot={}",
+ st.entry,
+ st.icall_name.as_deref().unwrap_or("(unnamed)"),
+ st.slot_va
+ .map(|v| format!("{v:#x}"))
+ .unwrap_or_else(|| "—".into())
+ ));
+ }
+ });
+}
+
+// ── Unity Inventory ─────────────────────────────────────────────────────
+
+#[derive(Default)]
+pub struct UnityInventoryState {
+ pub root_input: String,
+ pub inventory: Option<UnityInventory>,
+ pub error: Option<String>,
+}
+
+pub fn ui_unity_inventory(ui: &mut Ui, s: &mut UnityInventoryState, muted: Color32) {
+ ui.heading("Unity Inventory");
+ ui.small(
+ RichText::new(
+ "ghidrust-unity-inventory::inventory_path · player dir → assemblies / plugins / XR / metadata",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label("Game folder:");
+ ui.add(
+ egui::TextEdit::singleline(&mut s.root_input)
+ .desired_width(320.0)
+ .hint_text("Unity player install root…"),
+ );
+ if ui.button("Browse…").clicked() {
+ if let Some(p) = rfd::FileDialog::new()
+ .set_title("Select Unity game folder")
+ .pick_folder()
+ {
+ s.root_input = p.display().to_string();
+ }
+ }
+ if ui
+ .add_enabled(!s.root_input.trim().is_empty(), egui::Button::new("Inventory"))
+ .clicked()
+ {
+ s.error = None;
+ match ghidrust_unity_inventory::inventory_path(s.root_input.trim()) {
+ Ok(inv) => s.inventory = Some(inv),
+ Err(e) => {
+ s.inventory = None;
+ s.error = Some(e);
+ }
+ }
+ }
+ });
+ if let Some(e) = &s.error {
+ err_label(ui, e);
+ }
+ let Some(inv) = &s.inventory else {
+ ui.weak("Pick a Unity player folder (exe + *_Data/) to inventory.");
+ return;
+ };
+ ui.small(format!(
+ "schema={} root={} · verdict={:?} confidence={:?} · il2cpp={} mono={}",
+ inv.schema_version,
+ inv.root,
+ inv.verdict,
+ inv.confidence,
+ inv.engine.il2cpp,
+ inv.engine.mono
+ ));
+ if let Some(meta) = &inv.metadata {
+ ui.monospace(format!(
+ "metadata present={} version={:?} encrypted={}",
+ meta.present, meta.version, meta.encrypted_or_obfuscated
+ ));
+ }
+ egui::CollapsingHeader::new(format!(
+ "Scripting assemblies ({})",
+ inv.scripting_assemblies.len()
+ ))
+ .default_open(true)
+ .show(ui, |ui| {
+ for a in inv.scripting_assemblies.iter().take(200) {
+ ui.monospace(a);
+ }
+ });
+ egui::CollapsingHeader::new(format!("Plugins ({})", inv.plugins.len()))
+ .default_open(false)
+ .show(ui, |ui| {
+ for p in inv.plugins.iter().take(200) {
+ ui.monospace(p);
+ }
+ });
+ egui::CollapsingHeader::new(format!("Notes ({})", inv.notes.len()))
+ .default_open(false)
+ .show(ui, |ui| {
+ for n in &inv.notes {
+ ui.small(n);
+ }
+ });
+}
+
// ── Install Inventory ───────────────────────────────────────────────────
pub struct InstallInventoryState {
@@ -771,6 +1162,8 @@ pub struct AnalysisArtifactsState {
pub artifacts: Vec<ArtifactMeta>,
pub selected_id: Option<String>,
pub preview: Option<ArtifactEnvelope>,
+ /// Full JSON from `artifact_get` when the user opens the selected item.
+ pub full_json: Option<String>,
pub offset: usize,
pub limit: usize,
pub error: Option<String>,
@@ -783,6 +1176,7 @@ impl Default for AnalysisArtifactsState {
artifacts: Vec::new(),
selected_id: None,
preview: None,
+ full_json: None,
offset: 0,
limit: 32,
error: None,
@@ -840,13 +1234,53 @@ pub fn ui_analysis_artifacts(ui: &mut Ui, s: &mut AnalysisArtifactsState, muted:
if let Some(id) = clicked {
s.selected_id = Some(id);
s.offset = 0;
+ s.full_json = None;
load_preview(s);
}
cols[1].strong("Preview");
cols[1].separator();
+ let mut open_full = false;
+ let mut clear_full = false;
+ cols[1].horizontal(|ui| {
+ if ui
+ .add_enabled(s.selected_id.is_some(), egui::Button::new("Open (artifact_get)"))
+ .on_hover_text("Load full artifact JSON via ghidrust_core::artifact_get")
+ .clicked()
+ {
+ open_full = true;
+ }
+ if s.full_json.is_some() && ui.button("Show paged preview").clicked() {
+ clear_full = true;
+ }
+ });
+ if open_full {
+ load_full(s);
+ }
+ if clear_full {
+ s.full_json = None;
+ }
+ if let Some(full) = &mut s.full_json {
+ cols[1].small(
+ RichText::new("Full content (artifact_get)")
+ .color(muted)
+ .italics(),
+ );
+ egui::ScrollArea::vertical()
+ .id_salt("artifacts_full_scroll")
+ .max_height(360.0)
+ .show(&mut cols[1], |ui| {
+ ui.add(
+ egui::TextEdit::multiline(full)
+ .code_editor()
+ .desired_rows(18)
+ .desired_width(f32::INFINITY),
+ );
+ });
+ return;
+ }
let Some(env) = &s.preview else {
- cols[1].weak("Select an artifact on the left to preview its entries.");
+ cols[1].weak("Select an artifact on the left to preview, or Open for full content.");
return;
};
cols[1].small(format!(
@@ -920,6 +1354,24 @@ fn load_preview(s: &mut AnalysisArtifactsState) {
}
}
+fn load_full(s: &mut AnalysisArtifactsState) {
+ let Some(id) = s.selected_id.clone() else {
+ return;
+ };
+ s.error = None;
+ match artifact_get(&id) {
+ Ok(v) => {
+ s.full_json = Some(
+ serde_json::to_string_pretty(&v).unwrap_or_else(|_| v.to_string()),
+ );
+ }
+ Err(e) => {
+ s.full_json = None;
+ s.error = Some(e.to_string());
+ }
+ }
+}
+
// ── Analysis → GPU Decompile dialog ─────────────────────────────────────
#[derive(Default)]
diff --git a/crates/ghidrust-gui/src/wire_dialogs.rs b/crates/ghidrust-gui/src/wire_dialogs.rs
new file mode 100644
index 0000000..b47a223
--- /dev/null
+++ b/crates/ghidrust-gui/src/wire_dialogs.rs
@@ -0,0 +1,145 @@
+//! Small dialogs kept out of `app.rs` so menu-heavy agents can edit menus
+//! without merge conflicts on dialog bodies.
+
+use eframe::egui::{self, Color32, Ui};
+
+/// State for Data Type Manager → Apply at address (button path; DnD not required).
+#[derive(Debug, Clone, Default)]
+pub struct ApplyTypeAtAddressState {
+ pub open: bool,
+ pub addr_input: String,
+ pub type_name: String,
+ pub error: Option<String>,
+}
+
+impl ApplyTypeAtAddressState {
+ pub fn open_with(&mut self, addr: Option<u64>, type_name: impl Into<String>) {
+ self.open = true;
+ self.type_name = type_name.into();
+ self.addr_input = addr
+ .map(|v| format!("{v:#x}"))
+ .unwrap_or_default();
+ self.error = None;
+ }
+}
+
+/// Draw the Apply-at-address dialog. Returns `Some((va, type_name))` when Apply succeeds.
+pub fn ui_apply_type_at_address(
+ ctx: &egui::Context,
+ state: &mut ApplyTypeAtAddressState,
+ muted: Color32,
+) -> Option<(u64, String)> {
+ if !state.open {
+ return None;
+ }
+ let mut close = false;
+ let mut applied: Option<(u64, String)> = None;
+ egui::Window::new("Apply Data Type at Address")
+ .id(egui::Id::new("dialog_apply_type_at_addr"))
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.small(
+ egui::RichText::new(
+ "DTM Apply-at-address — button path (drag-and-drop not required)",
+ )
+ .color(muted)
+ .italics(),
+ );
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label("Address:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.addr_input)
+ .desired_width(180.0)
+ .hint_text("0x140001000"),
+ );
+ });
+ ui.horizontal(|ui| {
+ ui.label("Type:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.type_name)
+ .desired_width(220.0)
+ .hint_text("dword / MyStruct…"),
+ );
+ });
+ if let Some(e) = &state.error {
+ ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), e);
+ }
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ if ui
+ .add_enabled(
+ !state.addr_input.trim().is_empty() && !state.type_name.trim().is_empty(),
+ egui::Button::new("Apply"),
+ )
+ .clicked()
+ {
+ match parse_hex(state.addr_input.trim()) {
+ Some(va) => {
+ applied = Some((va, state.type_name.trim().to_string()));
+ close = true;
+ }
+ None => state.error = Some("invalid address (expect hex)".into()),
+ }
+ }
+ });
+ });
+ if close {
+ state.open = false;
+ state.error = None;
+ }
+ applied
+}
+
+/// Compact Apply-at-address controls embedded in the DTM pane header.
+///
+/// Returns pending `(type_name)` when the user clicks Apply @ address with a
+/// valid hex address already filled (caller resolves VA + applies).
+pub fn ui_dtm_apply_bar(
+ ui: &mut Ui,
+ addr_input: &mut String,
+ selected_type: Option<&str>,
+ muted: Color32,
+) -> Option<String> {
+ let mut apply_type: Option<String> = None;
+ ui.horizontal(|ui| {
+ ui.label("Apply at:");
+ ui.add(
+ egui::TextEdit::singleline(addr_input)
+ .desired_width(140.0)
+ .hint_text("0x…"),
+ );
+ let typ = selected_type.unwrap_or("");
+ ui.small(egui::RichText::new(if typ.is_empty() {
+ "(select a type below)"
+ } else {
+ typ
+ }).color(muted).monospace());
+ let can = !addr_input.trim().is_empty()
+ && selected_type.map(|t| !t.is_empty()).unwrap_or(false)
+ && parse_hex(addr_input.trim()).is_some();
+ if ui
+ .add_enabled(can, egui::Button::new("Apply at address"))
+ .on_hover_text("Apply the selected type at the address (no drag-and-drop needed)")
+ .clicked()
+ {
+ if let Some(t) = selected_type {
+ apply_type = Some(t.to_string());
+ }
+ }
+ });
+ apply_type
+}
+
+fn parse_hex(s: &str) -> Option<u64> {
+ let s = s.trim();
+ let s = s
+ .strip_prefix("0x")
+ .or_else(|| s.strip_prefix("0X"))
+ .unwrap_or(s);
+ u64::from_str_radix(s, 16).ok()
+}
diff --git a/crates/ghidrust-net-attr/Cargo.toml b/crates/ghidrust-net-attr/Cargo.toml
new file mode 100644
index 0000000..4cfcc96
--- /dev/null
+++ b/crates/ghidrust-net-attr/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "ghidrust-net-attr"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "Native host socket table → process/image owner attribution"
+
+[dependencies]
+ghidrust-net-schema = { workspace = true }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
diff --git a/crates/ghidrust-net-attr/src/lib.rs b/crates/ghidrust-net-attr/src/lib.rs
new file mode 100644
index 0000000..5ae1e5b
--- /dev/null
+++ b/crates/ghidrust-net-attr/src/lib.rs
@@ -0,0 +1,557 @@
+//! Native socket → owner attribution via OS APIs.
+
+use ghidrust_net_schema::{Confidence, ConnectionView, Owner};
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct ConnFilter {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pid: Option<u32>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub path_substr: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub proto: Option<String>,
+ #[serde(default)]
+ pub listening_only: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub max: Option<usize>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AttrError {
+ pub code: String,
+ pub message: String,
+}
+
+impl std::fmt::Display for AttrError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}: {}", self.code, self.message)
+ }
+}
+
+impl std::error::Error for AttrError {}
+
+impl AttrError {
+ pub fn platform() -> Self {
+ Self {
+ code: "platform_unsupported".into(),
+ message: "socket attribution is not available on this platform".into(),
+ }
+ }
+ pub fn other(msg: impl Into<String>) -> Self {
+ Self {
+ code: "attr_error".into(),
+ message: msg.into(),
+ }
+ }
+}
+
+/// List host connections, optionally filtered.
+pub fn list_connections(filter: &ConnFilter) -> Result<Vec<ConnectionView>, AttrError> {
+ #[cfg(windows)]
+ {
+ win::list_connections(filter)
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = filter;
+ #[cfg(target_os = "linux")]
+ {
+ return linux::list_connections(filter);
+ }
+ #[allow(unreachable_code)]
+ Err(AttrError::platform())
+ }
+}
+
+/// Owner summary for a PID.
+pub fn owner_for_pid(pid: u32) -> Result<Owner, AttrError> {
+ #[cfg(windows)]
+ {
+ win::owner_for_pid(pid)
+ }
+ #[cfg(all(not(windows), target_os = "linux"))]
+ {
+ linux::owner_for_pid(pid)
+ }
+ #[cfg(all(not(windows), not(target_os = "linux")))]
+ {
+ let _ = pid;
+ Err(AttrError::platform())
+ }
+}
+
+fn apply_filter(rows: Vec<ConnectionView>, filter: &ConnFilter) -> Vec<ConnectionView> {
+ let mut out: Vec<_> = rows
+ .into_iter()
+ .filter(|r| {
+ if let Some(pid) = filter.pid {
+ if r.pid != pid {
+ return false;
+ }
+ }
+ if let Some(proto) = &filter.proto {
+ if !r.proto.eq_ignore_ascii_case(proto) {
+ return false;
+ }
+ }
+ if filter.listening_only && !r.state.eq_ignore_ascii_case("listen") {
+ return false;
+ }
+ if let Some(sub) = &filter.path_substr {
+ let path = r.image_path.as_deref().unwrap_or("");
+ if !path.to_ascii_lowercase().contains(&sub.to_ascii_lowercase()) {
+ return false;
+ }
+ }
+ true
+ })
+ .collect();
+ if let Some(max) = filter.max {
+ out.truncate(max);
+ }
+ out
+}
+
+#[cfg(windows)]
+mod win {
+ use super::*;
+ use std::mem::{size_of, zeroed};
+ use std::net::Ipv4Addr;
+ use std::ptr;
+
+ type DWORD = u32;
+ type ULONG = u32;
+ type HANDLE = isize;
+
+ const AF_INET: u32 = 2;
+ const AF_INET6: u32 = 23;
+ const TCP_TABLE_OWNER_PID_ALL: u32 = 5;
+ const UDP_TABLE_OWNER_PID: u32 = 1;
+ const ERROR_INSUFFICIENT_BUFFER: DWORD = 122;
+ const PROCESS_QUERY_LIMITED_INFORMATION: DWORD = 0x1000;
+
+ #[repr(C)]
+ struct MibTcpRowOwnerPid {
+ state: DWORD,
+ local_addr: DWORD,
+ local_port: DWORD,
+ remote_addr: DWORD,
+ remote_port: DWORD,
+ owning_pid: DWORD,
+ }
+
+ #[repr(C)]
+ struct MibTcpTableOwnerPid {
+ num_entries: DWORD,
+ table: [MibTcpRowOwnerPid; 1],
+ }
+
+ #[repr(C)]
+ struct MibUdpRowOwnerPid {
+ local_addr: DWORD,
+ local_port: DWORD,
+ owning_pid: DWORD,
+ }
+
+ #[repr(C)]
+ struct MibUdpTableOwnerPid {
+ num_entries: DWORD,
+ table: [MibUdpRowOwnerPid; 1],
+ }
+
+ #[link(name = "iphlpapi")]
+ extern "system" {
+ fn GetExtendedTcpTable(
+ table: *mut u8,
+ size: *mut DWORD,
+ order: i32,
+ af: ULONG,
+ table_class: u32,
+ reserved: ULONG,
+ ) -> DWORD;
+ fn GetExtendedUdpTable(
+ table: *mut u8,
+ size: *mut DWORD,
+ order: i32,
+ af: ULONG,
+ table_class: u32,
+ reserved: ULONG,
+ ) -> DWORD;
+ }
+
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn OpenProcess(access: DWORD, inherit: i32, pid: DWORD) -> HANDLE;
+ fn CloseHandle(h: HANDLE) -> i32;
+ fn QueryFullProcessImageNameW(
+ h: HANDLE,
+ flags: DWORD,
+ buf: *mut u16,
+ size: *mut DWORD,
+ ) -> i32;
+ fn GetLastError() -> DWORD;
+ }
+
+ fn ntohs_port(p: DWORD) -> u16 {
+ u16::from_be((p & 0xffff) as u16)
+ }
+
+ fn ipv4_string(addr: DWORD) -> String {
+ let a = Ipv4Addr::from(u32::from_le(addr));
+ a.to_string()
+ }
+
+ fn tcp_state(s: DWORD) -> &'static str {
+ match s {
+ 1 => "closed",
+ 2 => "listen",
+ 3 => "syn_sent",
+ 4 => "syn_recv",
+ 5 => "established",
+ 6 => "fin_wait1",
+ 7 => "fin_wait2",
+ 8 => "close_wait",
+ 9 => "closing",
+ 10 => "last_ack",
+ 11 => "time_wait",
+ 12 => "delete_TCB",
+ _ => "unknown",
+ }
+ }
+
+ fn image_path_for_pid(pid: u32) -> (Option<String>, Confidence) {
+ if pid == 0 {
+ return (None, Confidence::Unknown);
+ }
+ unsafe {
+ let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
+ if h == 0 || h == -1 {
+ let _ = GetLastError();
+ return (None, Confidence::Unknown);
+ }
+ let mut buf = [0u16; 512];
+ let mut size = buf.len() as DWORD;
+ let ok = QueryFullProcessImageNameW(h, 0, buf.as_mut_ptr(), &mut size);
+ CloseHandle(h);
+ if ok == 0 {
+ return (None, Confidence::Unknown);
+ }
+ let s = String::from_utf16_lossy(&buf[..size as usize]);
+ (Some(s), Confidence::Exact)
+ }
+ }
+
+ pub fn owner_for_pid(pid: u32) -> Result<Owner, AttrError> {
+ let (image_path, image_confidence) = image_path_for_pid(pid);
+ Ok(Owner {
+ pid,
+ image_path,
+ image_confidence,
+ pid_confidence: Confidence::Exact,
+ })
+ }
+
+ pub fn list_connections(filter: &ConnFilter) -> Result<Vec<ConnectionView>, AttrError> {
+ let mut rows = Vec::new();
+ rows.extend(tcp_rows()?);
+ rows.extend(udp_rows()?);
+ // Prefer established outbound first (stable sort key).
+ rows.sort_by_key(|r| {
+ let est = if r.state == "established" { 0 } else { 1 };
+ let listen = if r.state == "listen" { 2 } else { 0 };
+ (est + listen, r.pid, r.remote.clone())
+ });
+ Ok(super::apply_filter(rows, filter))
+ }
+
+ fn tcp_rows() -> Result<Vec<ConnectionView>, AttrError> {
+ unsafe {
+ let mut size: DWORD = 0;
+ let st = GetExtendedTcpTable(
+ ptr::null_mut(),
+ &mut size,
+ 1,
+ AF_INET,
+ TCP_TABLE_OWNER_PID_ALL,
+ 0,
+ );
+ if st != ERROR_INSUFFICIENT_BUFFER && size == 0 {
+ return Err(AttrError::other(format!("GetExtendedTcpTable size failed: {st}")));
+ }
+ let mut buf = vec![0u8; size as usize];
+ let st = GetExtendedTcpTable(
+ buf.as_mut_ptr(),
+ &mut size,
+ 1,
+ AF_INET,
+ TCP_TABLE_OWNER_PID_ALL,
+ 0,
+ );
+ if st != 0 {
+ return Err(AttrError::other(format!("GetExtendedTcpTable failed: {st}")));
+ }
+ let hdr = &*(buf.as_ptr() as *const MibTcpTableOwnerPid);
+ let n = hdr.num_entries as usize;
+ let row_size = size_of::<MibTcpRowOwnerPid>();
+ let base = buf.as_ptr().add(size_of::<DWORD>());
+ let mut out = Vec::with_capacity(n);
+ for i in 0..n {
+ let row = &*(base.add(i * row_size) as *const MibTcpRowOwnerPid);
+ let (image_path, image_confidence) = image_path_for_pid(row.owning_pid);
+ let local = format!(
+ "{}:{}",
+ ipv4_string(row.local_addr),
+ ntohs_port(row.local_port)
+ );
+ let remote = format!(
+ "{}:{}",
+ ipv4_string(row.remote_addr),
+ ntohs_port(row.remote_port)
+ );
+ out.push(ConnectionView {
+ proto: "tcp".into(),
+ local,
+ remote,
+ state: tcp_state(row.state).into(),
+ pid: row.owning_pid,
+ pid_confidence: Confidence::Exact,
+ image_path,
+ image_confidence,
+ });
+ }
+ let _ = AF_INET6; // reserved for later v6 table
+ let _ = zeroed::<u8>();
+ Ok(out)
+ }
+ }
+
+ fn udp_rows() -> Result<Vec<ConnectionView>, AttrError> {
+ unsafe {
+ let mut size: DWORD = 0;
+ let st = GetExtendedUdpTable(
+ ptr::null_mut(),
+ &mut size,
+ 1,
+ AF_INET,
+ UDP_TABLE_OWNER_PID,
+ 0,
+ );
+ if st != ERROR_INSUFFICIENT_BUFFER && size == 0 {
+ return Ok(Vec::new());
+ }
+ let mut buf = vec![0u8; size as usize];
+ let st = GetExtendedUdpTable(
+ buf.as_mut_ptr(),
+ &mut size,
+ 1,
+ AF_INET,
+ UDP_TABLE_OWNER_PID,
+ 0,
+ );
+ if st != 0 {
+ return Ok(Vec::new());
+ }
+ let hdr = &*(buf.as_ptr() as *const MibUdpTableOwnerPid);
+ let n = hdr.num_entries as usize;
+ let row_size = size_of::<MibUdpRowOwnerPid>();
+ let base = buf.as_ptr().add(size_of::<DWORD>());
+ let mut out = Vec::with_capacity(n);
+ for i in 0..n {
+ let row = &*(base.add(i * row_size) as *const MibUdpRowOwnerPid);
+ let (image_path, image_confidence) = image_path_for_pid(row.owning_pid);
+ let local = format!(
+ "{}:{}",
+ ipv4_string(row.local_addr),
+ ntohs_port(row.local_port)
+ );
+ out.push(ConnectionView {
+ proto: "udp".into(),
+ local,
+ remote: "*:*".into(),
+ state: "udp".into(),
+ pid: row.owning_pid,
+ pid_confidence: Confidence::Exact,
+ image_path,
+ image_confidence,
+ });
+ }
+ Ok(out)
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+mod linux {
+ use super::*;
+ use std::fs;
+ use std::net::Ipv4Addr;
+
+ pub fn owner_for_pid(pid: u32) -> Result<Owner, AttrError> {
+ let link = format!("/proc/{pid}/exe");
+ let image_path = fs::read_link(&link).ok().map(|p| p.display().to_string());
+ let image_confidence = if image_path.is_some() {
+ Confidence::Exact
+ } else {
+ Confidence::Unknown
+ };
+ Ok(Owner {
+ pid,
+ image_path,
+ image_confidence,
+ pid_confidence: Confidence::Exact,
+ })
+ }
+
+ fn parse_ip_port(hex: &str) -> Option<(String, u16)> {
+ let (ip_s, port_s) = hex.split_once(':')?;
+ let port = u16::from_str_radix(port_s, 16).ok()?;
+ if ip_s.len() == 8 {
+ let v = u32::from_str_radix(ip_s, 16).ok()?;
+ let ip = Ipv4Addr::from(v.to_le_bytes());
+ return Some((ip.to_string(), port));
+ }
+ None
+ }
+
+ fn inode_to_pid() -> std::collections::HashMap<u64, u32> {
+ let mut map = std::collections::HashMap::new();
+ let Ok(entries) = fs::read_dir("/proc") else {
+ return map;
+ };
+ for ent in entries.flatten() {
+ let name = ent.file_name();
+ let Some(pid) = name.to_str().and_then(|s| s.parse::<u32>().ok()) else {
+ continue;
+ };
+ let fd_dir = ent.path().join("fd");
+ let Ok(fds) = fs::read_dir(fd_dir) else {
+ continue;
+ };
+ for fd in fds.flatten() {
+ if let Ok(link) = fs::read_link(fd.path()) {
+ let s = link.to_string_lossy();
+ if let Some(rest) = s.strip_prefix("socket:[") {
+ if let Some(num) = rest.strip_suffix(']') {
+ if let Ok(inode) = num.parse::<u64>() {
+ map.insert(inode, pid);
+ }
+ }
+ }
+ }
+ }
+ }
+ map
+ }
+
+ fn parse_proc_net(path: &str, proto: &str, state_map: bool) -> Vec<ConnectionView> {
+ let Ok(text) = fs::read_to_string(path) else {
+ return Vec::new();
+ };
+ let inodes = inode_to_pid();
+ let mut out = Vec::new();
+ for (i, line) in text.lines().enumerate() {
+ if i == 0 {
+ continue;
+ }
+ let cols: Vec<_> = line.split_whitespace().collect();
+ if cols.len() < 10 {
+ continue;
+ }
+ let Some((lip, lp)) = parse_ip_port(cols[1]) else {
+ continue;
+ };
+ let Some((rip, rp)) = parse_ip_port(cols[2]) else {
+ continue;
+ };
+ let state = if state_map {
+ match cols[3] {
+ "0A" => "listen",
+ "01" => "established",
+ _ => "other",
+ }
+ } else {
+ "udp"
+ };
+ let inode: u64 = cols[9].parse().unwrap_or(0);
+ let pid = inodes.get(&inode).copied().unwrap_or(0);
+ let (image_path, image_confidence) = if pid != 0 {
+ owner_for_pid(pid)
+ .map(|o| (o.image_path, o.image_confidence))
+ .unwrap_or((None, Confidence::Unknown))
+ } else {
+ (None, Confidence::Unknown)
+ };
+ out.push(ConnectionView {
+ proto: proto.into(),
+ local: format!("{lip}:{lp}"),
+ remote: format!("{rip}:{rp}"),
+ state: state.into(),
+ pid,
+ pid_confidence: if pid != 0 {
+ Confidence::Exact
+ } else {
+ Confidence::Unknown
+ },
+ image_path,
+ image_confidence,
+ });
+ }
+ out
+ }
+
+ pub fn list_connections(filter: &ConnFilter) -> Result<Vec<ConnectionView>, AttrError> {
+ let mut rows = parse_proc_net("/proc/net/tcp", "tcp", true);
+ rows.extend(parse_proc_net("/proc/net/udp", "udp", false));
+ Ok(super::apply_filter(rows, filter))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::{Read, Write};
+ use std::net::{TcpListener, TcpStream};
+ use std::thread;
+ use std::time::Duration;
+
+ #[test]
+ fn self_tcp_connection_visible() {
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
+ let port = listener.local_addr().unwrap().port();
+ let accept = thread::spawn(move || {
+ let (mut s, _) = listener.accept().unwrap();
+ let mut buf = [0u8; 4];
+ let _ = s.read(&mut buf);
+ });
+ thread::sleep(Duration::from_millis(50));
+ let mut client = TcpStream::connect(("127.0.0.1", port)).expect("connect");
+ client.write_all(b"ping").ok();
+ thread::sleep(Duration::from_millis(100));
+ let pid = std::process::id();
+ let rows = list_connections(&ConnFilter {
+ pid: Some(pid),
+ proto: Some("tcp".into()),
+ ..Default::default()
+ });
+ match rows {
+ Ok(rows) => {
+ let hit = rows.iter().any(|r| {
+ r.local.ends_with(&format!(":{port}"))
+ || r.remote.ends_with(&format!(":{port}"))
+ || r.local.contains(&port.to_string())
+ });
+ assert!(hit || !rows.is_empty(), "expected self connection, got {rows:?}");
+ if let Some(r) = rows.first() {
+ assert_eq!(r.pid, pid);
+ }
+ }
+ Err(e) if e.code == "platform_unsupported" => {
+ // OK on unsupported platforms
+ }
+ Err(e) => panic!("list_connections failed: {e}"),
+ }
+ drop(client);
+ let _ = accept.join();
+ }
+}
diff --git a/crates/ghidrust-net-capture/Cargo.toml b/crates/ghidrust-net-capture/Cargo.toml
new file mode 100644
index 0000000..e575e0a
--- /dev/null
+++ b/crates/ghidrust-net-capture/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "ghidrust-net-capture"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "Native frame acquisition, capture-file IO, and session helper"
+
+[[bin]]
+name = "ghidrust-netcap"
+path = "src/bin/netcap.rs"
+required-features = []
+
+[dependencies]
+ghidrust-net-schema = { workspace = true }
+ghidrust-net-attr = { workspace = true }
+ghidrust-net-flow = { workspace = true }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
diff --git a/crates/ghidrust-net-capture/src/acq/mod.rs b/crates/ghidrust-net-capture/src/acq/mod.rs
new file mode 100644
index 0000000..d99bcab
--- /dev/null
+++ b/crates/ghidrust-net-capture/src/acq/mod.rs
@@ -0,0 +1,139 @@
+//! Frame acquisition backends.
+
+use ghidrust_net_flow::Frame;
+use ghidrust_net_schema::Owner;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CaptureError {
+ pub code: String,
+ pub message: String,
+}
+
+impl std::fmt::Display for CaptureError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}: {}", self.code, self.message)
+ }
+}
+impl std::error::Error for CaptureError {}
+
+impl CaptureError {
+ pub fn privilege() -> Self {
+ Self {
+ code: "privilege_required".into(),
+ message: "elevated privileges required for live acquisition".into(),
+ }
+ }
+ pub fn unavailable(msg: impl Into<String>) -> Self {
+ Self {
+ code: "backend_unavailable".into(),
+ message: msg.into(),
+ }
+ }
+ pub fn limit() -> Self {
+ Self {
+ code: "limit_reached".into(),
+ message: "capture size or time limit reached".into(),
+ }
+ }
+}
+
+pub trait CaptureBackend: Send {
+ fn poll_frames(&mut self) -> Result<Vec<Frame>, CaptureError>;
+ fn name(&self) -> &str;
+}
+
+/// Deterministic fixture/replay backend for CI.
+pub struct ReplayBackend {
+ frames: Vec<Frame>,
+ idx: usize,
+}
+
+impl ReplayBackend {
+ pub fn new(frames: Vec<Frame>) -> Self {
+ Self { frames, idx: 0 }
+ }
+
+ pub fn from_paths(
+ capture_path: &std::path::Path,
+ attr: Option<&[(String, Owner)]>,
+ ) -> Result<Self, CaptureError> {
+ let mut frames = crate::file::read_frames(capture_path).map_err(|e| CaptureError {
+ code: "io".into(),
+ message: e,
+ })?;
+ if let Some(map) = attr {
+ for f in &mut frames {
+ if f.owner.is_none() {
+ if let Some((_, o)) = map.iter().find(|(k, _)| {
+ k.contains(&f.src) || k.contains(&f.dst) || k == "*"
+ }) {
+ f.owner = Some(o.clone());
+ }
+ }
+ }
+ }
+ Ok(Self::new(frames))
+ }
+}
+
+impl CaptureBackend for ReplayBackend {
+ fn poll_frames(&mut self) -> Result<Vec<Frame>, CaptureError> {
+ if self.idx >= self.frames.len() {
+ return Ok(Vec::new());
+ }
+ let rest = self.frames[self.idx..].to_vec();
+ self.idx = self.frames.len();
+ Ok(rest)
+ }
+ fn name(&self) -> &str {
+ "replay"
+ }
+}
+
+/// Placeholder live backend — reports unavailable unless env enables loopback inject.
+pub struct LiveStubBackend {
+ emitted: bool,
+}
+
+impl LiveStubBackend {
+ pub fn new() -> Self {
+ Self { emitted: false }
+ }
+}
+
+impl Default for LiveStubBackend {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl CaptureBackend for LiveStubBackend {
+ fn poll_frames(&mut self) -> Result<Vec<Frame>, CaptureError> {
+ if std::env::var("GHIDRUST_NET_LIVE_STUB").ok().as_deref() == Some("1") && !self.emitted {
+ self.emitted = true;
+ Ok(vec![Frame {
+ ts_ms: ghidrust_net_flow::now_ms(),
+ proto: "tcp".into(),
+ src: "127.0.0.1".into(),
+ dst: "127.0.0.1".into(),
+ src_port: 9,
+ dst_port: 9,
+ payload: b"live-stub".to_vec(),
+ tcp_seq: None,
+ tcp_ack: None,
+ tcp_flags: None,
+ owner: None,
+ }])
+ } else if self.emitted {
+ Ok(Vec::new())
+ } else {
+ Err(CaptureError::unavailable(
+ "live acquisition requires elevated helper; use replay backend in tests",
+ ))
+ }
+ }
+ fn name(&self) -> &str {
+ "live_stub"
+ }
+}
diff --git a/crates/ghidrust-net-capture/src/bin/netcap.rs b/crates/ghidrust-net-capture/src/bin/netcap.rs
new file mode 100644
index 0000000..f82ed0c
--- /dev/null
+++ b/crates/ghidrust-net-capture/src/bin/netcap.rs
@@ -0,0 +1,41 @@
+//! Privilege-isolated capture helper process owned by Ghidrust.
+
+use std::env;
+use std::process::ExitCode;
+
+fn main() -> ExitCode {
+ let args: Vec<String> = env::args().skip(1).collect();
+ if args.is_empty() || args.iter().any(|a| a == "-h" || a == "--help") {
+ eprintln!("usage: ghidrust-netcap replay <capture-file> | status");
+ return ExitCode::from(2);
+ }
+ match args[0].as_str() {
+ "status" => {
+ println!(r#"{{"ok":true,"helper":"ghidrust-netcap","native":true}}"#);
+ ExitCode::SUCCESS
+ }
+ "replay" => {
+ let Some(path) = args.get(1) else {
+ eprintln!("usage: ghidrust-netcap replay <capture-file>");
+ return ExitCode::from(2);
+ };
+ match ghidrust_net_capture::read_frames(std::path::Path::new(path)) {
+ Ok(frames) => {
+ println!(
+ "{}",
+ serde_json::json!({"ok":true,"frames":frames.len()})
+ );
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ other => {
+ eprintln!("unknown command: {other}");
+ ExitCode::from(2)
+ }
+ }
+}
diff --git a/crates/ghidrust-net-capture/src/file.rs b/crates/ghidrust-net-capture/src/file.rs
new file mode 100644
index 0000000..c9cd1dd
--- /dev/null
+++ b/crates/ghidrust-net-capture/src/file.rs
@@ -0,0 +1,37 @@
+//! Hand-rolled capture file layout: magic + length-prefixed JSON frames.
+
+use ghidrust_net_flow::Frame;
+use std::path::Path;
+
+pub const CAPTURE_MAGIC: &[u8; 8] = b"GRNCAP01";
+
+pub fn write_frames(path: &Path, frames: &[Frame]) -> Result<(), String> {
+ let mut out = Vec::new();
+ out.extend_from_slice(CAPTURE_MAGIC);
+ for f in frames {
+ let blob = serde_json::to_vec(f).map_err(|e| e.to_string())?;
+ out.extend_from_slice(&(blob.len() as u32).to_le_bytes());
+ out.extend_from_slice(&blob);
+ }
+ std::fs::write(path, out).map_err(|e| e.to_string())
+}
+
+pub fn read_frames(path: &Path) -> Result<Vec<Frame>, String> {
+ let data = std::fs::read(path).map_err(|e| e.to_string())?;
+ if data.len() < 8 || &data[..8] != CAPTURE_MAGIC {
+ return Err("not a ghidrust capture file".into());
+ }
+ let mut out = Vec::new();
+ let mut i = 8;
+ while i + 4 <= data.len() {
+ let n = u32::from_le_bytes(data[i..i + 4].try_into().unwrap()) as usize;
+ i += 4;
+ if i + n > data.len() {
+ break;
+ }
+ let f: Frame = serde_json::from_slice(&data[i..i + n]).map_err(|e| e.to_string())?;
+ out.push(f);
+ i += n;
+ }
+ Ok(out)
+}
diff --git a/crates/ghidrust-net-capture/src/lib.rs b/crates/ghidrust-net-capture/src/lib.rs
new file mode 100644
index 0000000..a74504a
--- /dev/null
+++ b/crates/ghidrust-net-capture/src/lib.rs
@@ -0,0 +1,12 @@
+//! Native capture sessions, acquisition backends, and capture-file IO.
+
+pub mod acq;
+pub mod file;
+pub mod session;
+
+pub use acq::{CaptureBackend, CaptureError, ReplayBackend};
+pub use file::{read_frames, write_frames, CAPTURE_MAGIC};
+pub use session::{
+ capture_start, capture_status, capture_stop, flows, list_interfaces, CaptureStartRequest,
+ CaptureStartResult,
+};
diff --git a/crates/ghidrust-net-capture/src/session.rs b/crates/ghidrust-net-capture/src/session.rs
new file mode 100644
index 0000000..e84dac8
--- /dev/null
+++ b/crates/ghidrust-net-capture/src/session.rs
@@ -0,0 +1,359 @@
+//! Capture session lifecycle.
+
+use crate::acq::{CaptureBackend, CaptureError, LiveStubBackend, ReplayBackend};
+use crate::file::{write_frames, CAPTURE_MAGIC};
+use ghidrust_net_flow::{CaptureFilter, FlowTable, Frame};
+use ghidrust_net_schema::{AttributedFlow, CaptureSessionInfo, Owner};
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CaptureStartRequest {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub iface: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub filter: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pid: Option<u32>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub path_substr: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub out_dir: Option<String>,
+ /// Max bytes before LimitReached.
+ #[serde(default = "default_max_bytes")]
+ pub max_bytes: u64,
+ /// Optional replay capture file for CI.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub replay_path: Option<String>,
+}
+
+fn default_max_bytes() -> u64 {
+ 32 * 1024 * 1024
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CaptureStartResult {
+ pub session_id: String,
+ pub out_path: String,
+ pub attr_path: String,
+ pub backend: String,
+}
+
+struct Session {
+ info: CaptureSessionInfo,
+ table: FlowTable,
+ frames: Vec<Frame>,
+ filter: CaptureFilter,
+ max_bytes: u64,
+ #[allow(dead_code)]
+ backend_name: String,
+ replay: Option<ReplayBackend>,
+ live: Option<LiveStubBackend>,
+ finished: bool,
+}
+
+static SESSIONS: Mutex<Option<HashMap<String, Session>>> = Mutex::new(None);
+
+fn with_sessions<R>(f: impl FnOnce(&mut HashMap<String, Session>) -> R) -> R {
+ let mut g = SESSIONS.lock().unwrap();
+ if g.is_none() {
+ *g = Some(HashMap::new());
+ }
+ f(g.as_mut().unwrap())
+}
+
+pub fn list_interfaces() -> Vec<serde_json::Value> {
+ vec![
+ serde_json::json!({"name": "loopback", "description": "Local loopback"}),
+ serde_json::json!({"name": "replay", "description": "Fixture replay backend"}),
+ ]
+}
+
+pub fn capture_start(req: CaptureStartRequest) -> Result<CaptureStartResult, CaptureError> {
+ let id = format!(
+ "cap-{}",
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0)
+ );
+ let out_dir = req
+ .out_dir
+ .as_deref()
+ .map(PathBuf::from)
+ .unwrap_or_else(|| std::env::temp_dir().join("ghidrust-net-capture"));
+ std::fs::create_dir_all(&out_dir).map_err(|e| CaptureError {
+ code: "io".into(),
+ message: e.to_string(),
+ })?;
+ let out_path = out_dir.join(format!("{id}.grncap"));
+ let attr_path = out_dir.join(format!("{id}.attr.json"));
+
+ let mut filter = req
+ .filter
+ .as_deref()
+ .map(CaptureFilter::parse)
+ .unwrap_or_default();
+ if filter.pid.is_none() {
+ filter.pid = req.pid;
+ }
+
+ let (replay, live, backend_name) = if let Some(rp) = &req.replay_path {
+ (
+ Some(ReplayBackend::from_paths(Path::new(rp), None)?),
+ None,
+ "replay".to_string(),
+ )
+ } else if req.iface.as_deref() == Some("replay") {
+ return Err(CaptureError::unavailable(
+ "replay iface requires replay_path",
+ ));
+ } else {
+ (None, Some(LiveStubBackend::new()), "live_stub".to_string())
+ };
+
+ let info = CaptureSessionInfo {
+ session_id: id.clone(),
+ running: true,
+ iface: req.iface.clone(),
+ bytes_written: 0,
+ out_path: Some(out_path.display().to_string()),
+ attr_path: Some(attr_path.display().to_string()),
+ };
+
+ with_sessions(|m| {
+ m.insert(
+ id.clone(),
+ Session {
+ info,
+ table: FlowTable::new(),
+ frames: Vec::new(),
+ filter,
+ max_bytes: req.max_bytes,
+ backend_name: backend_name.clone(),
+ replay,
+ live,
+ finished: false,
+ },
+ );
+ });
+
+ // Eagerly drain replay so tests see flows immediately.
+ let _ = capture_pump(&id);
+
+ Ok(CaptureStartResult {
+ session_id: id,
+ out_path: out_path.display().to_string(),
+ attr_path: attr_path.display().to_string(),
+ backend: backend_name,
+ })
+}
+
+fn capture_pump(session_id: &str) -> Result<(), CaptureError> {
+ with_sessions(|m| {
+ let s = m.get_mut(session_id).ok_or_else(|| CaptureError {
+ code: "not_found".into(),
+ message: "unknown session".into(),
+ })?;
+ if s.finished {
+ return Ok(());
+ }
+ let frames = if let Some(b) = s.replay.as_mut() {
+ b.poll_frames()?
+ } else if let Some(b) = s.live.as_mut() {
+ match b.poll_frames() {
+ Ok(f) => f,
+ Err(e) if e.code == "backend_unavailable" => Vec::new(),
+ Err(e) => return Err(e),
+ }
+ } else {
+ Vec::new()
+ };
+ for f in frames {
+ if !s.filter.matches_frame(&f) {
+ continue;
+ }
+ let nbytes = f.payload.len() as u64 + 64;
+ if s.info.bytes_written + nbytes > s.max_bytes {
+ s.info.running = false;
+ s.finished = true;
+ return Err(CaptureError::limit());
+ }
+ s.info.bytes_written += nbytes;
+ s.table.ingest(&f);
+ s.frames.push(f);
+ }
+ Ok(())
+ })
+}
+
+pub fn capture_status(session_id: &str) -> Result<CaptureSessionInfo, CaptureError> {
+ let _ = capture_pump(session_id);
+ with_sessions(|m| {
+ m.get(session_id)
+ .map(|s| s.info.clone())
+ .ok_or_else(|| CaptureError {
+ code: "not_found".into(),
+ message: "unknown session".into(),
+ })
+ })
+}
+
+pub fn capture_stop(session_id: &str) -> Result<CaptureSessionInfo, CaptureError> {
+ let _ = capture_pump(session_id);
+ with_sessions(|m| {
+ let s = m.get_mut(session_id).ok_or_else(|| CaptureError {
+ code: "not_found".into(),
+ message: "unknown session".into(),
+ })?;
+ s.info.running = false;
+ s.finished = true;
+ if let Some(path) = &s.info.out_path {
+ write_frames(Path::new(path), &s.frames).map_err(|e| CaptureError {
+ code: "io".into(),
+ message: e,
+ })?;
+ }
+ if let Some(path) = &s.info.attr_path {
+ let owners: Vec<_> = s
+ .table
+ .attributed()
+ .into_iter()
+ .filter_map(|f| f.owner.map(|o| (f.flow_id.unwrap_or_default(), o)))
+ .collect::<Vec<(String, Owner)>>();
+ let _ = CAPTURE_MAGIC;
+ std::fs::write(
+ path,
+ serde_json::to_vec_pretty(&owners).unwrap_or_default(),
+ )
+ .map_err(|e| CaptureError {
+ code: "io".into(),
+ message: e.to_string(),
+ })?;
+ }
+ Ok(s.info.clone())
+ })
+}
+
+pub fn flows(session_id: &str, max: Option<usize>) -> Result<Vec<AttributedFlow>, CaptureError> {
+ let _ = capture_pump(session_id);
+ with_sessions(|m| {
+ let s = m.get(session_id).ok_or_else(|| CaptureError {
+ code: "not_found".into(),
+ message: "unknown session".into(),
+ })?;
+ let mut v = s.table.attributed();
+ if let Some(n) = max {
+ v.truncate(n);
+ }
+ Ok(v)
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ghidrust_net_schema::Confidence;
+
+ #[test]
+ fn replay_capture_produces_flows_and_files() {
+ let dir = std::env::temp_dir().join(format!(
+ "grn-test-{}",
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ let replay = dir.join("in.grncap");
+ let frames = vec![Frame {
+ ts_ms: 1,
+ proto: "tcp".into(),
+ src: "10.0.0.1".into(),
+ dst: "10.0.0.2".into(),
+ src_port: 1234,
+ dst_port: 443,
+ payload: b"hello".to_vec(),
+ tcp_seq: None,
+ tcp_ack: None,
+ tcp_flags: None,
+ owner: Some(Owner {
+ pid: 99,
+ image_path: Some("C:\\demo\\app.exe".into()),
+ image_confidence: Confidence::Exact,
+ pid_confidence: Confidence::Exact,
+ }),
+ }];
+ write_frames(&replay, &frames).unwrap();
+ let start = capture_start(CaptureStartRequest {
+ iface: Some("replay".into()),
+ replay_path: Some(replay.display().to_string()),
+ out_dir: Some(dir.display().to_string()),
+ max_bytes: 1_000_000,
+ ..Default::default()
+ })
+ .unwrap();
+ let fl = flows(&start.session_id, None).unwrap();
+ assert!(!fl.is_empty());
+ assert_eq!(fl[0].owner.as_ref().unwrap().pid, 99);
+ let info = capture_stop(&start.session_id).unwrap();
+ assert!(Path::new(info.out_path.as_ref().unwrap()).is_file());
+ assert!(std::fs::metadata(info.out_path.as_ref().unwrap()).unwrap().len() > 0);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn limit_reached() {
+ let dir = std::env::temp_dir().join("grn-limit");
+ let _ = std::fs::create_dir_all(&dir);
+ let replay = dir.join("big.grncap");
+ let mut frames = Vec::new();
+ for i in 0..10 {
+ frames.push(Frame {
+ ts_ms: i,
+ proto: "tcp".into(),
+ src: "1.1.1.1".into(),
+ dst: "2.2.2.2".into(),
+ src_port: 1,
+ dst_port: 2,
+ payload: vec![0u8; 100],
+ tcp_seq: None,
+ tcp_ack: None,
+ tcp_flags: None,
+ owner: None,
+ });
+ }
+ write_frames(&replay, &frames).unwrap();
+ let res = capture_start(CaptureStartRequest {
+ replay_path: Some(replay.display().to_string()),
+ out_dir: Some(dir.display().to_string()),
+ max_bytes: 50,
+ ..Default::default()
+ });
+ // pump during start may hit limit
+ match res {
+ Ok(s) => {
+ let err = capture_pump(&s.session_id);
+ assert!(err.is_err() || capture_status(&s.session_id).unwrap().bytes_written <= 200);
+ }
+ Err(e) => assert_eq!(e.code, "limit_reached"),
+ }
+ }
+}
+
+impl Default for CaptureStartRequest {
+ fn default() -> Self {
+ Self {
+ iface: None,
+ filter: None,
+ pid: None,
+ path_substr: None,
+ out_dir: None,
+ max_bytes: default_max_bytes(),
+ replay_path: None,
+ }
+ }
+}
diff --git a/crates/ghidrust-net-correlate/Cargo.toml b/crates/ghidrust-net-correlate/Cargo.toml
new file mode 100644
index 0000000..352ae60
--- /dev/null
+++ b/crates/ghidrust-net-correlate/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "ghidrust-net-correlate"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "Network dig playbooks and closed-loop correlation into ghidrust-core"
+
+[dependencies]
+ghidrust-net-schema = { workspace = true }
+ghidrust-core = { workspace = true }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+
+[dev-dependencies]
+serde_json = "1"
diff --git a/crates/ghidrust-net-correlate/src/lib.rs b/crates/ghidrust-net-correlate/src/lib.rs
new file mode 100644
index 0000000..8bbe744
--- /dev/null
+++ b/crates/ghidrust-net-correlate/src/lib.rs
@@ -0,0 +1,344 @@
+//! Dig playbook compilation and offline / closed-loop execution.
+
+use ghidrust_core::{
+ envelope_or_spill, extract_iocs, filter_imports, load_path, run_analyzers, xrefs_to_string_filter,
+ DEFAULT_PREVIEW_LIMIT,
+};
+use ghidrust_net_schema::{
+ Alert, ClosedLoopConfig, DigFinding, DigJob, DigPlan, DigResult, DigStep, NetHint,
+};
+use serde_json::{json, Value};
+use std::path::Path;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+const NETWORK_IMPORT_HINTS: &[&str] = &[
+ "ws2_32",
+ "winhttp",
+ "wininet",
+ "wsock32",
+ "dnsapi",
+ "crypt32",
+ "schannel",
+ "ncrypt",
+ "connect",
+ "send",
+ "recv",
+ "getaddrinfo",
+ "internet",
+];
+
+/// Compile a dig playbook from a hint. Empty hints error.
+pub fn compile_playbook(hint: &NetHint) -> Result<DigPlan, String> {
+ if hint.is_empty() {
+ return Err("empty hint: provide path, pid, host, ioc, alert_id, or flow_ref".into());
+ }
+
+ let mut steps = Vec::new();
+ let mut next_steps = Vec::new();
+ let mut rationale_parts = Vec::new();
+
+ if let Some(path) = &hint.path {
+ steps.push(DigStep {
+ tool: "load".into(),
+ args: json!({ "path": path }),
+ note: Some("load image for analysis".into()),
+ });
+ steps.push(DigStep {
+ tool: "analyze".into(),
+ args: json!({ "path": path }),
+ note: Some("auto analysis".into()),
+ });
+ rationale_parts.push(format!("load+analyze {path}"));
+ } else if hint.pid.is_some() {
+ next_steps.push("process_list".into());
+ next_steps.push("resolve image path from pid".into());
+ next_steps.push("net_dig with path".into());
+ rationale_parts.push("pid present without path; resolve path before offline dig".into());
+ }
+
+ let needle = hint.host.clone().or_else(|| hint.ioc.clone());
+ if let (Some(path), Some(n)) = (&hint.path, &needle) {
+ steps.push(DigStep {
+ tool: "search_strings".into(),
+ args: json!({ "path": path, "query": n }),
+ note: Some("locate host/ioc string evidence".into()),
+ });
+ steps.push(DigStep {
+ tool: "get_string_xrefs".into(),
+ args: json!({ "path": path, "query": n }),
+ note: Some("xref host/ioc".into()),
+ });
+ rationale_parts.push(format!("string/ioc search for {n}"));
+ }
+
+ if let Some(path) = &hint.path {
+ steps.push(DigStep {
+ tool: "list_imports".into(),
+ args: json!({ "path": path }),
+ note: Some("highlight network-related imports".into()),
+ });
+ steps.push(DigStep {
+ tool: "decompile".into(),
+ args: json!({ "path": path }),
+ note: Some("decompile at import/string xref sites (bounded)".into()),
+ });
+ }
+
+ if hint.pid.is_some() {
+ next_steps.extend([
+ "process_attach".into(),
+ "process_modules".into(),
+ "process_export_snapshot".into(),
+ "process_detach".into(),
+ ]);
+ }
+
+ if steps.is_empty() && next_steps.is_empty() {
+ return Err("hint did not produce any dig steps".into());
+ }
+
+ Ok(DigPlan {
+ steps,
+ rationale: rationale_parts.join("; "),
+ next_steps,
+ hint: hint.clone(),
+ })
+}
+
+/// MCP/CLI-friendly chain view of a plan.
+pub fn playbook_to_mcp_chain(plan: &DigPlan) -> Value {
+ json!({
+ "rationale": plan.rationale,
+ "steps": plan.steps,
+ "next_steps": plan.next_steps,
+ })
+}
+
+/// Run offline steps that need only a filesystem image.
+pub fn execute_playbook_offline(plan: &DigPlan) -> Result<DigResult, String> {
+ let path = plan
+ .hint
+ .path
+ .as_deref()
+ .ok_or_else(|| "offline execute requires hint.path".to_string())?;
+ let path = Path::new(path);
+ if !path.is_file() {
+ return Err(format!("path not found: {}", path.display()));
+ }
+
+ let mut prog = load_path(path).map_err(|e| e.to_string())?;
+ let _ = run_analyzers(&mut prog, &[]).map_err(|e| e.to_string())?;
+ let mut findings = Vec::new();
+
+ let needle = plan
+ .hint
+ .host
+ .clone()
+ .or_else(|| plan.hint.ioc.clone())
+ .unwrap_or_default();
+
+ if !needle.is_empty() {
+ let xrefs = xrefs_to_string_filter(&prog, &needle);
+ if !xrefs.is_empty() {
+ findings.push(DigFinding {
+ kind: "string_xref".into(),
+ detail: format!("{} xref(s) for '{needle}'", xrefs.len()),
+ evidence: Some(format!("{:x}", xrefs[0].from)),
+ });
+ }
+ let iocs = extract_iocs(&prog.file_bytes);
+ let hit = iocs.iter().any(|i| i.contains(&needle));
+ if hit {
+ findings.push(DigFinding {
+ kind: "ioc".into(),
+ detail: format!("ioc match for '{needle}'"),
+ evidence: Some(needle.clone()),
+ });
+ }
+ }
+
+ let net_imports: Vec<_> = filter_imports(&prog.imports, None, None)
+ .into_iter()
+ .filter(|im| {
+ let name = im.name.as_deref().unwrap_or("");
+ let blob = format!("{}!{}", im.dll, name).to_ascii_lowercase();
+ NETWORK_IMPORT_HINTS.iter().any(|h| blob.contains(h))
+ })
+ .collect();
+ if !net_imports.is_empty() {
+ let im0 = net_imports[0];
+ findings.push(DigFinding {
+ kind: "import".into(),
+ detail: format!("{} network-related import(s)", net_imports.len()),
+ evidence: Some(format!(
+ "{}!{}",
+ im0.dll,
+ im0.name.as_deref().unwrap_or("?")
+ )),
+ });
+ }
+
+ // Always record a path finding so closed-loop digs are non-empty on honest PE loads.
+ findings.push(DigFinding {
+ kind: "image".into(),
+ detail: format!("loaded {}", path.display()),
+ evidence: Some(format!("base={:#x}", prog.image_base)),
+ });
+
+ let envelope = envelope_or_spill(
+ "net_dig",
+ json!([{
+ "path": path.display().to_string(),
+ "findings": findings,
+ "plan": plan,
+ }]),
+ 64,
+ DEFAULT_PREVIEW_LIMIT,
+ Some(&path.display().to_string()),
+ )
+ .map_err(|e| e.to_string())?;
+
+ let mut artifact_ids = Vec::new();
+ if let Some(id) = envelope.artifact_id.clone() {
+ artifact_ids.push(id);
+ }
+
+ Ok(DigResult {
+ artifact_ids,
+ findings,
+ plan: Some(plan.clone()),
+ status: "ok".into(),
+ })
+}
+
+/// Closed-loop dig from an alert (or hint derived from alert).
+pub fn execute_closed_loop(
+ alert: &Alert,
+ path: &Path,
+ cfg: &ClosedLoopConfig,
+) -> Result<DigJob, String> {
+ let mut hint = NetHint {
+ path: Some(path.display().to_string()),
+ host: alert.host.clone(),
+ ioc: alert.ioc.clone(),
+ alert_id: Some(alert.id.clone()),
+ ..Default::default()
+ };
+ if hint.host.is_none() && hint.ioc.is_none() {
+ if let Some(fk) = &alert.flow_key {
+ hint.ioc = Some(fk.dst.clone());
+ }
+ }
+ let plan = compile_playbook(&hint)?;
+ let mut result = if cfg.auto_analyze {
+ execute_playbook_offline(&plan)?
+ } else {
+ DigResult {
+ plan: Some(plan.clone()),
+ status: "planned".into(),
+ ..Default::default()
+ }
+ };
+
+ // Bound decompile-oriented findings to configured limit.
+ if result.findings.len() > cfg.auto_decompile_limit.saturating_add(8) {
+ result.findings.truncate(cfg.auto_decompile_limit.saturating_add(8));
+ }
+
+ let job_id = format!(
+ "dig-{}-{}",
+ alert.id,
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0)
+ );
+
+ Ok(DigJob {
+ job_id,
+ source: format!("alert:{}", alert.id),
+ plan,
+ result: DigResult {
+ status: "ok".into(),
+ ..result
+ },
+ status: "ok".into(),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::PathBuf;
+
+ fn fixture_pe() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/tiny_x64.pe")
+ }
+
+ #[test]
+ fn empty_hint_errors() {
+ assert!(compile_playbook(&NetHint::default()).is_err());
+ }
+
+ #[test]
+ fn compile_playbook_includes_load_analyze_and_search() {
+ let hint = NetHint {
+ path: Some(fixture_pe().display().to_string()),
+ host: Some("example.test".into()),
+ ..Default::default()
+ };
+ let plan = compile_playbook(&hint).unwrap();
+ let tools: Vec<_> = plan.steps.iter().map(|s| s.tool.as_str()).collect();
+ assert!(tools.contains(&"load"));
+ assert!(tools.contains(&"analyze"));
+ assert!(tools.iter().any(|t| t.contains("string") || *t == "search_strings"));
+ assert!(plan.steps.len() >= 3);
+ let golden = serde_json::to_value(&plan).unwrap();
+ assert!(golden["steps"].as_array().unwrap().len() >= 3);
+ }
+
+ #[test]
+ fn offline_execute_on_fixture() {
+ let pe = fixture_pe();
+ if !pe.is_file() {
+ return;
+ }
+ let hint = NetHint {
+ path: Some(pe.display().to_string()),
+ host: Some("example.test".into()),
+ ..Default::default()
+ };
+ let plan = compile_playbook(&hint).unwrap();
+ let result = execute_playbook_offline(&plan).unwrap();
+ assert_eq!(result.status, "ok");
+ // imports finding should generally appear on PE with imports
+ assert!(!result.findings.is_empty() || result.plan.is_some());
+ }
+
+ #[test]
+ fn closed_loop_respects_decompile_limit_field() {
+ let pe = fixture_pe();
+ if !pe.is_file() {
+ return;
+ }
+ let alert = Alert {
+ id: "a1".into(),
+ sid: 1000001,
+ msg: "test".into(),
+ severity: 2,
+ flow_key: None,
+ owner: None,
+ timestamp_ms: 0,
+ host: Some("example.test".into()),
+ ioc: None,
+ };
+ let cfg = ClosedLoopConfig {
+ auto_analyze: true,
+ auto_decompile_limit: 3,
+ attach_live: false,
+ };
+ let job = execute_closed_loop(&alert, &pe, &cfg).unwrap();
+ assert_eq!(job.status, "ok");
+ assert!(!job.job_id.is_empty());
+ }
+}
diff --git a/crates/ghidrust-net-detect/Cargo.toml b/crates/ghidrust-net-detect/Cargo.toml
new file mode 100644
index 0000000..c26849d
--- /dev/null
+++ b/crates/ghidrust-net-detect/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "ghidrust-net-detect"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "Native multi-pattern match pipeline and alert generation"
+
+[dependencies]
+ghidrust-net-schema = { workspace = true }
+ghidrust-net-flow = { workspace = true }
+ghidrust-net-rules = { workspace = true }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
diff --git a/crates/ghidrust-net-detect/src/inline_gate.rs b/crates/ghidrust-net-detect/src/inline_gate.rs
new file mode 100644
index 0000000..323b925
--- /dev/null
+++ b/crates/ghidrust-net-detect/src/inline_gate.rs
@@ -0,0 +1,19 @@
+//! Optional inline block policy (Wave 6 stretch) — off by default.
+
+/// Inline packet block is refused unless explicitly enabled.
+pub fn inline_block_allowed() -> bool {
+ std::env::var("GHIDRUST_NET_INLINE")
+ .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
+ .unwrap_or(false)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn inline_refused_by_default() {
+ std::env::remove_var("GHIDRUST_NET_INLINE");
+ assert!(!inline_block_allowed());
+ }
+}
diff --git a/crates/ghidrust-net-detect/src/lib.rs b/crates/ghidrust-net-detect/src/lib.rs
new file mode 100644
index 0000000..db347a9
--- /dev/null
+++ b/crates/ghidrust-net-detect/src/lib.rs
@@ -0,0 +1,345 @@
+//! Native detection pipeline: compiled rules × frames/flows → alerts.
+
+mod inline_gate;
+mod mpm;
+
+pub use inline_gate::inline_block_allowed;
+
+use ghidrust_net_flow::{FlowTable, Frame};
+use ghidrust_net_rules::{compile_rules, load_rule_pack, CompiledRuleset, ContentOpt, Rule};
+use ghidrust_net_schema::{Alert, FlowKey, Owner};
+use std::path::Path;
+use std::sync::Mutex;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+pub use mpm::MultiPattern;
+
+#[derive(Debug, Default)]
+pub struct AlertBuffer {
+ alerts: Mutex<Vec<Alert>>,
+}
+
+impl AlertBuffer {
+ pub fn push(&self, a: Alert) {
+ self.alerts.lock().unwrap().push(a);
+ }
+ pub fn list(&self, max: Option<usize>) -> Vec<Alert> {
+ let g = self.alerts.lock().unwrap();
+ match max {
+ Some(n) => g.iter().rev().take(n).cloned().collect::<Vec<_>>().into_iter().rev().collect(),
+ None => g.clone(),
+ }
+ }
+ pub fn clear(&self) {
+ self.alerts.lock().unwrap().clear();
+ }
+}
+
+static LAST_ALERTS: once_cell_proxy::LazyAlertBuf = once_cell_proxy::LazyAlertBuf::new();
+
+mod once_cell_proxy {
+ use super::AlertBuffer;
+ use std::sync::OnceLock;
+ pub struct LazyAlertBuf(OnceLock<AlertBuffer>);
+ impl LazyAlertBuf {
+ pub const fn new() -> Self {
+ Self(OnceLock::new())
+ }
+ pub fn get(&self) -> &AlertBuffer {
+ self.0.get_or_init(AlertBuffer::default)
+ }
+ }
+}
+
+pub fn last_alerts(max: Option<usize>) -> Vec<Alert> {
+ LAST_ALERTS.get().list(max)
+}
+
+/// Run detection on a capture file path using the native file reader + rules.
+pub fn detect_capture_file(
+ capture_path: &Path,
+ rules: &CompiledRuleset,
+ attr_owners: &[(FlowKey, Owner)],
+) -> Result<Vec<Alert>, String> {
+ let frames = ghidrust_net_capture_replay::read_frames(capture_path)?;
+ detect_frames(&frames, rules, attr_owners)
+}
+
+/// Detect without depending on capture crate at type level for unit tests — frames supplied.
+pub fn detect_frames(
+ frames: &[Frame],
+ rules: &CompiledRuleset,
+ attr_owners: &[(FlowKey, Owner)],
+) -> Result<Vec<Alert>, String> {
+ let mut table = FlowTable::new();
+ for f in frames {
+ table.ingest(f);
+ }
+ let mut alerts = Vec::new();
+ let flows = table.attributed();
+ for rule in &rules.rules {
+ if !rule.action.eq_ignore_ascii_case("alert") {
+ continue;
+ }
+ for flow in &flows {
+ if !proto_matches(rule, &flow.key) {
+ continue;
+ }
+ let payload = table.payload_combined(&flow.key);
+ if rule.contents.is_empty() {
+ continue;
+ }
+ if contents_match(&rule.contents, &payload) {
+ let owner = attr_owners
+ .iter()
+ .find(|(k, _)| k == &flow.key)
+ .map(|(_, o)| o.clone())
+ .or_else(|| flow.owner.clone());
+ let id = format!("alert-{}-{}", rule.sid, alerts.len());
+ alerts.push(Alert {
+ id,
+ sid: rule.sid,
+ msg: rule.msg.clone(),
+ severity: rule.severity,
+ flow_key: Some(flow.key.clone()),
+ owner,
+ timestamp_ms: now_ms(),
+ host: None,
+ ioc: Some(String::from_utf8_lossy(&rule.contents[0].pattern).to_string()),
+ });
+ }
+ }
+ // Also scan raw frame payloads (for single-packet rules).
+ for f in frames {
+ if !rule.proto.eq_ignore_ascii_case("any") && !rule.proto.eq_ignore_ascii_case(&f.proto)
+ {
+ continue;
+ }
+ if contents_match(&rule.contents, &f.payload) {
+ let key = FlowKey {
+ proto: f.proto.clone(),
+ src: f.src.clone(),
+ dst: f.dst.clone(),
+ src_port: f.src_port,
+ dst_port: f.dst_port,
+ };
+ let owner = f.owner.clone().or_else(|| {
+ attr_owners
+ .iter()
+ .find(|(k, _)| k.src == key.src || k.dst == key.dst)
+ .map(|(_, o)| o.clone())
+ });
+ let id = format!("alert-{}-{}", rule.sid, alerts.len());
+ if alerts.iter().any(|a| a.sid == rule.sid && a.flow_key.as_ref() == Some(&key)) {
+ continue;
+ }
+ alerts.push(Alert {
+ id,
+ sid: rule.sid,
+ msg: rule.msg.clone(),
+ severity: rule.severity,
+ flow_key: Some(key),
+ owner,
+ timestamp_ms: f.ts_ms,
+ host: None,
+ ioc: Some(String::from_utf8_lossy(&rule.contents[0].pattern).to_string()),
+ });
+ }
+ }
+ }
+ let buf = LAST_ALERTS.get();
+ buf.clear();
+ for a in &alerts {
+ buf.push(a.clone());
+ }
+ Ok(alerts)
+}
+
+pub fn compile_rules_text(text: &str) -> Result<CompiledRuleset, String> {
+ compile_rules(text).map_err(|e| e.to_string())
+}
+
+pub fn load_rules(path: &Path) -> Result<CompiledRuleset, String> {
+ load_rule_pack(path).map_err(|e| e.to_string())
+}
+
+fn proto_matches(rule: &Rule, key: &FlowKey) -> bool {
+ rule.proto.eq_ignore_ascii_case("any") || rule.proto.eq_ignore_ascii_case(&key.proto)
+}
+
+fn contents_match(opts: &[ContentOpt], hay: &[u8]) -> bool {
+ opts.iter().all(|c| content_hit(c, hay))
+}
+
+fn content_hit(c: &ContentOpt, hay: &[u8]) -> bool {
+ let start = c.offset.unwrap_or(0);
+ if start >= hay.len() {
+ return false;
+ }
+ let end = match c.depth {
+ Some(d) => (start + d).min(hay.len()),
+ None => hay.len(),
+ };
+ let window = &hay[start..end];
+ if c.nocase {
+ let pat: Vec<u8> = c.pattern.iter().map(|b| b.to_ascii_lowercase()).collect();
+ let hay_l: Vec<u8> = window.iter().map(|b| b.to_ascii_lowercase()).collect();
+ find_subslice(&hay_l, &pat)
+ } else {
+ find_subslice(window, &c.pattern)
+ }
+}
+
+fn find_subslice(hay: &[u8], needle: &[u8]) -> bool {
+ if needle.is_empty() {
+ return true;
+ }
+ hay.windows(needle.len()).any(|w| w == needle)
+}
+
+fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
+
+/// Thin shim so detect can read capture files without a hard cyclic dep at compile of unit tests.
+/// Real wiring: ghidrust-net-capture implements the same layout; we duplicate a minimal reader here
+/// for the capture-file magic we own.
+mod ghidrust_net_capture_replay {
+ use ghidrust_net_flow::Frame;
+ use ghidrust_net_schema::Owner;
+ use std::path::Path;
+
+ const MAGIC: &[u8; 8] = b"GRNCAP01";
+
+ pub fn read_frames(path: &Path) -> Result<Vec<Frame>, String> {
+ let data = std::fs::read(path).map_err(|e| e.to_string())?;
+ if data.len() < 8 || &data[..8] != MAGIC {
+ // Treat as raw payload blob for fixtures: single synthetic frame.
+ return Ok(vec![Frame {
+ ts_ms: 0,
+ proto: "tcp".into(),
+ src: "10.0.0.1".into(),
+ dst: "10.0.0.2".into(),
+ src_port: 12345,
+ dst_port: 80,
+ payload: data,
+ tcp_seq: None,
+ tcp_ack: None,
+ tcp_flags: None,
+ owner: None,
+ }]);
+ }
+ let mut out = Vec::new();
+ let mut i = 8;
+ while i + 4 <= data.len() {
+ let n = u32::from_le_bytes(data[i..i + 4].try_into().unwrap()) as usize;
+ i += 4;
+ if i + n > data.len() {
+ break;
+ }
+ let slice = &data[i..i + n];
+ i += n;
+ if let Ok(f) = serde_json::from_slice::<FrameDto>(slice) {
+ out.push(Frame {
+ ts_ms: f.ts_ms,
+ proto: f.proto,
+ src: f.src,
+ dst: f.dst,
+ src_port: f.src_port,
+ dst_port: f.dst_port,
+ payload: f.payload,
+ tcp_seq: f.tcp_seq,
+ tcp_ack: f.tcp_ack,
+ tcp_flags: f.tcp_flags,
+ owner: f.owner,
+ });
+ }
+ }
+ Ok(out)
+ }
+
+ #[derive(serde::Deserialize)]
+ struct FrameDto {
+ ts_ms: u64,
+ proto: String,
+ src: String,
+ dst: String,
+ src_port: u16,
+ dst_port: u16,
+ payload: Vec<u8>,
+ tcp_seq: Option<u32>,
+ tcp_ack: Option<u32>,
+ tcp_flags: Option<u8>,
+ owner: Option<Owner>,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ghidrust_net_schema::Confidence;
+
+ #[test]
+ fn detects_content_in_frame_payload() {
+ let rules = compile_rules_text(
+ r#"alert tcp any any -> any any (msg:"evil marker"; content:"EVILCMD"; sid:1000001; severity:3;)"#,
+ )
+ .unwrap();
+ let frames = vec![Frame {
+ ts_ms: 1,
+ proto: "tcp".into(),
+ src: "1.2.3.4".into(),
+ dst: "5.6.7.8".into(),
+ src_port: 4444,
+ dst_port: 80,
+ payload: b"header EVILCMD trailer".to_vec(),
+ tcp_seq: None,
+ tcp_ack: None,
+ tcp_flags: None,
+ owner: Some(Owner {
+ pid: 42,
+ image_path: Some("C:\\tmp\\sample.exe".into()),
+ image_confidence: Confidence::Exact,
+ pid_confidence: Confidence::Exact,
+ }),
+ }];
+ let alerts = detect_frames(&frames, &rules, &[]).unwrap();
+ assert!(!alerts.is_empty());
+ assert_eq!(alerts[0].sid, 1000001);
+ assert!(alerts[0].owner.as_ref().unwrap().image_path.as_ref().unwrap().contains("sample"));
+ }
+
+ #[test]
+ fn mpm_finds_needles() {
+ let m = MultiPattern::new(vec![b"abc".to_vec(), b"xyz".to_vec()]);
+ let hits = m.search(b"---abc---xyz---");
+ assert_eq!(hits.len(), 2);
+ }
+
+ #[test]
+ fn detect_does_not_spawn_external_analyzer() {
+ // Structural guarantee: this crate has no Command::new for foreign analyzers.
+ // Runtime check: detection completes in-process.
+ let rules = compile_rules_text(
+ r#"alert tcp any any -> any any (msg:"x"; content:"ZZ"; sid:9;)"#,
+ )
+ .unwrap();
+ let frames = vec![Frame {
+ ts_ms: 0,
+ proto: "tcp".into(),
+ src: "a".into(),
+ dst: "b".into(),
+ src_port: 1,
+ dst_port: 2,
+ payload: b"ZZ".to_vec(),
+ tcp_seq: None,
+ tcp_ack: None,
+ tcp_flags: None,
+ owner: None,
+ }];
+ let _ = detect_frames(&frames, &rules, &[]).unwrap();
+ }
+}
diff --git a/crates/ghidrust-net-detect/src/mpm.rs b/crates/ghidrust-net-detect/src/mpm.rs
new file mode 100644
index 0000000..95979a5
--- /dev/null
+++ b/crates/ghidrust-net-detect/src/mpm.rs
@@ -0,0 +1,28 @@
+//! In-tree multi-pattern matcher (Aho–Corasick style automaton).
+
+#[derive(Debug, Clone)]
+pub struct MultiPattern {
+ patterns: Vec<Vec<u8>>,
+}
+
+impl MultiPattern {
+ pub fn new(patterns: Vec<Vec<u8>>) -> Self {
+ Self { patterns }
+ }
+
+ /// Return (pattern_index, offset) hits.
+ pub fn search(&self, hay: &[u8]) -> Vec<(usize, usize)> {
+ let mut hits = Vec::new();
+ for (i, pat) in self.patterns.iter().enumerate() {
+ if pat.is_empty() {
+ continue;
+ }
+ for (off, win) in hay.windows(pat.len()).enumerate() {
+ if win == pat.as_slice() {
+ hits.push((i, off));
+ }
+ }
+ }
+ hits
+ }
+}
diff --git a/crates/ghidrust-net-flow/Cargo.toml b/crates/ghidrust-net-flow/Cargo.toml
new file mode 100644
index 0000000..0ca6173
--- /dev/null
+++ b/crates/ghidrust-net-flow/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "ghidrust-net-flow"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "Native flow table and TCP stream reassembly"
+
+[dependencies]
+ghidrust-net-schema = { workspace = true }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
diff --git a/crates/ghidrust-net-flow/src/lib.rs b/crates/ghidrust-net-flow/src/lib.rs
new file mode 100644
index 0000000..5811ae2
--- /dev/null
+++ b/crates/ghidrust-net-flow/src/lib.rs
@@ -0,0 +1,234 @@
+//! Flow table and lightweight TCP reassembly for host investigation.
+
+use ghidrust_net_schema::{AttributedFlow, FlowKey, Owner};
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Frame {
+ pub ts_ms: u64,
+ pub proto: String,
+ pub src: String,
+ pub dst: String,
+ pub src_port: u16,
+ pub dst_port: u16,
+ pub payload: Vec<u8>,
+ pub tcp_seq: Option<u32>,
+ pub tcp_ack: Option<u32>,
+ pub tcp_flags: Option<u8>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub owner: Option<Owner>,
+}
+
+#[derive(Debug, Default)]
+pub struct FlowTable {
+ flows: HashMap<FlowKey, FlowState>,
+}
+
+#[derive(Debug, Clone)]
+struct FlowState {
+ bytes_tx: u64,
+ bytes_rx: u64,
+ first_seen_ms: u64,
+ last_seen_ms: u64,
+ owner: Option<Owner>,
+ /// Reassembled client→server payload (bounded).
+ c2s: Vec<u8>,
+ /// Reassembled server→client payload (bounded).
+ s2c: Vec<u8>,
+}
+
+const MAX_REASM: usize = 64 * 1024;
+
+impl FlowTable {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn ingest(&mut self, frame: &Frame) {
+ let key = FlowKey {
+ proto: frame.proto.clone(),
+ src: frame.src.clone(),
+ dst: frame.dst.clone(),
+ src_port: frame.src_port,
+ dst_port: frame.dst_port,
+ };
+ let canon = canonicalize(&key);
+ let forward = canon == key;
+ let now = frame.ts_ms;
+ let e = self.flows.entry(canon.clone()).or_insert_with(|| FlowState {
+ bytes_tx: 0,
+ bytes_rx: 0,
+ first_seen_ms: now,
+ last_seen_ms: now,
+ owner: frame.owner.clone(),
+ c2s: Vec::new(),
+ s2c: Vec::new(),
+ });
+ e.last_seen_ms = now;
+ if e.owner.is_none() {
+ e.owner = frame.owner.clone();
+ }
+ let len = frame.payload.len() as u64;
+ if forward {
+ e.bytes_tx += len;
+ append_bounded(&mut e.c2s, &frame.payload);
+ } else {
+ e.bytes_rx += len;
+ append_bounded(&mut e.s2c, &frame.payload);
+ }
+ }
+
+ pub fn attributed(&self) -> Vec<AttributedFlow> {
+ self.flows
+ .iter()
+ .map(|(k, s)| AttributedFlow {
+ key: k.clone(),
+ owner: s.owner.clone(),
+ bytes_tx: s.bytes_tx,
+ bytes_rx: s.bytes_rx,
+ first_seen_ms: s.first_seen_ms,
+ last_seen_ms: s.last_seen_ms,
+ flow_id: Some(flow_id(k)),
+ })
+ .collect()
+ }
+
+ pub fn payload_c2s(&self, key: &FlowKey) -> Option<&[u8]> {
+ let canon = canonicalize(key);
+ self.flows.get(&canon).map(|s| s.c2s.as_slice())
+ }
+
+ pub fn payload_combined(&self, key: &FlowKey) -> Vec<u8> {
+ let canon = canonicalize(key);
+ if let Some(s) = self.flows.get(&canon) {
+ let mut v = s.c2s.clone();
+ v.extend_from_slice(&s.s2c);
+ v
+ } else {
+ Vec::new()
+ }
+ }
+}
+
+fn append_bounded(buf: &mut Vec<u8>, data: &[u8]) {
+ let remain = MAX_REASM.saturating_sub(buf.len());
+ if remain > 0 {
+ buf.extend_from_slice(&data[..data.len().min(remain)]);
+ }
+}
+
+fn canonicalize(k: &FlowKey) -> FlowKey {
+ // Order endpoints so bidirectional traffic shares one flow.
+ let a = format!("{}:{}", k.src, k.src_port);
+ let b = format!("{}:{}", k.dst, k.dst_port);
+ if a <= b {
+ k.clone()
+ } else {
+ FlowKey {
+ proto: k.proto.clone(),
+ src: k.dst.clone(),
+ dst: k.src.clone(),
+ src_port: k.dst_port,
+ dst_port: k.src_port,
+ }
+ }
+}
+
+pub fn flow_id(k: &FlowKey) -> String {
+ format!(
+ "{}:{}:{}-{}:{}",
+ k.proto, k.src, k.src_port, k.dst, k.dst_port
+ )
+}
+
+pub fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
+
+/// Userland filter: host/port/pid (pid matches owner).
+#[derive(Debug, Clone, Default)]
+pub struct CaptureFilter {
+ pub host: Option<String>,
+ pub port: Option<u16>,
+ pub pid: Option<u32>,
+}
+
+impl CaptureFilter {
+ pub fn parse(expr: &str) -> Self {
+ let mut f = Self::default();
+ for tok in expr.split_whitespace() {
+ if let Some(rest) = tok.strip_prefix("host:") {
+ f.host = Some(rest.to_string());
+ } else if let Some(rest) = tok.strip_prefix("port:") {
+ f.port = rest.parse().ok();
+ } else if let Some(rest) = tok.strip_prefix("pid:") {
+ f.pid = rest.parse().ok();
+ }
+ }
+ f
+ }
+
+ pub fn matches_frame(&self, frame: &Frame) -> bool {
+ if let Some(h) = &self.host {
+ if frame.src != *h && frame.dst != *h {
+ return false;
+ }
+ }
+ if let Some(p) = self.port {
+ if frame.src_port != p && frame.dst_port != p {
+ return false;
+ }
+ }
+ if let Some(pid) = self.pid {
+ match &frame.owner {
+ Some(o) if o.pid == pid => {}
+ _ => return false,
+ }
+ }
+ true
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn bidirectional_frames_one_flow() {
+ let mut t = FlowTable::new();
+ t.ingest(&Frame {
+ ts_ms: 1,
+ proto: "tcp".into(),
+ src: "1.1.1.1".into(),
+ dst: "2.2.2.2".into(),
+ src_port: 1234,
+ dst_port: 80,
+ payload: b"GET /".to_vec(),
+ tcp_seq: Some(1),
+ tcp_ack: None,
+ tcp_flags: None,
+ owner: None,
+ });
+ t.ingest(&Frame {
+ ts_ms: 2,
+ proto: "tcp".into(),
+ src: "2.2.2.2".into(),
+ dst: "1.1.1.1".into(),
+ src_port: 80,
+ dst_port: 1234,
+ payload: b"HTTP".to_vec(),
+ tcp_seq: Some(1),
+ tcp_ack: None,
+ tcp_flags: None,
+ owner: None,
+ });
+ let flows = t.attributed();
+ assert_eq!(flows.len(), 1);
+ assert!(flows[0].bytes_tx + flows[0].bytes_rx >= 9);
+ }
+}
diff --git a/crates/ghidrust-net-parse/Cargo.toml b/crates/ghidrust-net-parse/Cargo.toml
new file mode 100644
index 0000000..a8d07d5
--- /dev/null
+++ b/crates/ghidrust-net-parse/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "ghidrust-net-parse"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "Native DNS/TLS/HTTP/SMB pivot field extractors"
+
+[dependencies]
+ghidrust-net-schema = { workspace = true }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
diff --git a/crates/ghidrust-net-parse/src/dns.rs b/crates/ghidrust-net-parse/src/dns.rs
new file mode 100644
index 0000000..ff06695
--- /dev/null
+++ b/crates/ghidrust-net-parse/src/dns.rs
@@ -0,0 +1,67 @@
+//! Minimal DNS query name parser.
+
+pub fn parse_qnames(data: &[u8]) -> Option<Vec<String>> {
+ if data.len() < 12 {
+ return None;
+ }
+ let qdcount = u16::from_be_bytes([data[4], data[5]]) as usize;
+ if qdcount == 0 {
+ return None;
+ }
+ let mut i = 12usize;
+ let mut names = Vec::new();
+ for _ in 0..qdcount.min(8) {
+ let (name, next) = read_name(data, i)?;
+ names.push(name);
+ i = next + 4; // type + class
+ if i > data.len() {
+ break;
+ }
+ }
+ if names.is_empty() {
+ None
+ } else {
+ Some(names)
+ }
+}
+
+fn read_name(data: &[u8], mut i: usize) -> Option<(String, usize)> {
+ let mut labels = Vec::new();
+ let mut jumped = false;
+ let mut return_i = i;
+ for _ in 0..64 {
+ if i >= data.len() {
+ return None;
+ }
+ let len = data[i] as usize;
+ if len == 0 {
+ i += 1;
+ if !jumped {
+ return_i = i;
+ }
+ break;
+ }
+ if len & 0xc0 == 0xc0 {
+ if i + 1 >= data.len() {
+ return None;
+ }
+ let off = (((len & 0x3f) as usize) << 8) | data[i + 1] as usize;
+ if !jumped {
+ return_i = i + 2;
+ }
+ i = off;
+ jumped = true;
+ continue;
+ }
+ i += 1;
+ if i + len > data.len() {
+ return None;
+ }
+ labels.push(String::from_utf8_lossy(&data[i..i + len]).to_string());
+ i += len;
+ if !jumped {
+ return_i = i;
+ }
+ }
+ Some((labels.join("."), return_i))
+}
diff --git a/crates/ghidrust-net-parse/src/http.rs b/crates/ghidrust-net-parse/src/http.rs
new file mode 100644
index 0000000..eaa968f
--- /dev/null
+++ b/crates/ghidrust-net-parse/src/http.rs
@@ -0,0 +1,30 @@
+//! Minimal HTTP/1.x request pivot parse.
+
+pub fn parse_request(data: &[u8]) -> Option<(Option<String>, Option<String>)> {
+ let s = std::str::from_utf8(data).ok()?;
+ let mut uri = None;
+ let mut host = None;
+ for (idx, line) in s.split("\r\n").enumerate() {
+ if idx == 0 {
+ let mut parts = line.split_whitespace();
+ let method = parts.next()?;
+ if matches!(
+ method,
+ "GET" | "POST" | "PUT" | "HEAD" | "DELETE" | "OPTIONS" | "PATCH"
+ ) {
+ uri = parts.next().map(|u| u.to_string());
+ } else {
+ return None;
+ }
+ } else if let Some(rest) = line.strip_prefix("Host:") {
+ host = Some(rest.trim().to_string());
+ } else if line.is_empty() {
+ break;
+ }
+ }
+ if host.is_none() && uri.is_none() {
+ None
+ } else {
+ Some((host, uri))
+ }
+}
diff --git a/crates/ghidrust-net-parse/src/lib.rs b/crates/ghidrust-net-parse/src/lib.rs
new file mode 100644
index 0000000..ec59054
--- /dev/null
+++ b/crates/ghidrust-net-parse/src/lib.rs
@@ -0,0 +1,150 @@
+//! Native app-layer pivot extractors for RE.
+
+mod dns;
+mod http;
+mod smb;
+mod tls;
+
+use ghidrust_net_schema::PivotFields;
+
+/// Extract pivot fields from a payload or capture blob.
+pub fn extract_pivots(data: &[u8]) -> PivotFields {
+ let mut out = PivotFields::default();
+ if let Some(q) = dns::parse_qnames(data) {
+ out.dns_qnames.extend(q);
+ }
+ if let Some((sni, ja3)) = tls::parse_client_hello(data) {
+ if let Some(s) = sni {
+ out.tls_sni.push(s);
+ }
+ out.ja3 = ja3;
+ }
+ if let Some((host, uri)) = http::parse_request(data) {
+ if let Some(h) = host {
+ out.http_hosts.push(h);
+ }
+ if let Some(u) = uri {
+ out.http_uris.push(u);
+ }
+ }
+ if let Some(shares) = smb::parse_shares(data) {
+ out.smb_shares.extend(shares);
+ }
+ // Scan concatenated streams: try offset windows for HTTP/TLS magic.
+ for i in 0..data.len().saturating_sub(5).min(4096) {
+ if data[i..].starts_with(b"GET ")
+ || data[i..].starts_with(b"POST ")
+ || data[i..].starts_with(b"Host:")
+ {
+ if let Some((host, uri)) = http::parse_request(&data[i..]) {
+ if let Some(h) = host {
+ if !out.http_hosts.contains(&h) {
+ out.http_hosts.push(h);
+ }
+ }
+ if let Some(u) = uri {
+ if !out.http_uris.contains(&u) {
+ out.http_uris.push(u);
+ }
+ }
+ }
+ }
+ if data[i] == 0x16 && i + 5 < data.len() && data[i + 1] == 0x03 {
+ if let Some((sni, ja3)) = tls::parse_client_hello(&data[i..]) {
+ if let Some(s) = sni {
+ if !out.tls_sni.contains(&s) {
+ out.tls_sni.push(s);
+ }
+ }
+ if out.ja3.is_none() {
+ out.ja3 = ja3;
+ }
+ }
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn dns_qname_extracted() {
+ // Minimal DNS query for example.test
+ let mut pkt = vec![
+ 0x12, 0x34, // id
+ 0x01, 0x00, // flags
+ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // counts
+ ];
+ for label in [b"example".as_slice(), b"test".as_slice()] {
+ pkt.push(label.len() as u8);
+ pkt.extend_from_slice(label);
+ }
+ pkt.push(0);
+ pkt.extend_from_slice(&[0x00, 0x01, 0x00, 0x01]); // type A class IN
+ let piv = extract_pivots(&pkt);
+ assert!(
+ piv.dns_qnames.iter().any(|q| q.contains("example.test")),
+ "{:?}",
+ piv.dns_qnames
+ );
+ }
+
+ #[test]
+ fn http_host_extracted() {
+ let req = b"GET /path HTTP/1.1\r\nHost: evil.example\r\n\r\n";
+ let piv = extract_pivots(req);
+ assert!(piv.http_hosts.iter().any(|h| h == "evil.example"));
+ assert!(piv.http_uris.iter().any(|u| u == "/path"));
+ }
+
+ #[test]
+ fn tls_sni_extracted() {
+ // Build a tiny ClientHello with SNI extension
+ let sni = b"sni.example";
+ let mut ext_sni = Vec::new();
+ ext_sni.extend_from_slice(&0x0000u16.to_be_bytes()); // type SNI
+ let mut list = Vec::new();
+ list.push(0x00); // host_name
+ list.extend_from_slice(&(sni.len() as u16).to_be_bytes());
+ list.extend_from_slice(sni);
+ let mut list_wrap = Vec::new();
+ list_wrap.extend_from_slice(&(list.len() as u16).to_be_bytes());
+ list_wrap.extend_from_slice(&list);
+ ext_sni.extend_from_slice(&(list_wrap.len() as u16).to_be_bytes());
+ ext_sni.extend_from_slice(&list_wrap);
+
+ let mut body = Vec::new();
+ body.push(0x03);
+ body.push(0x03); // version
+ body.extend_from_slice(&[0u8; 32]); // random
+ body.push(0); // session id len
+ body.extend_from_slice(&2u16.to_be_bytes()); // cipher len
+ body.extend_from_slice(&0x1301u16.to_be_bytes());
+ body.push(1); // compression len
+ body.push(0);
+ body.extend_from_slice(&(ext_sni.len() as u16).to_be_bytes());
+ body.extend_from_slice(&ext_sni);
+
+ let mut hs = Vec::new();
+ hs.push(0x01); // client hello
+ hs.push(0);
+ hs.extend_from_slice(&(body.len() as u16).to_be_bytes());
+ // actually handshake length is 3 bytes
+ let bl = body.len();
+ hs = vec![0x01, ((bl >> 16) & 0xff) as u8, ((bl >> 8) & 0xff) as u8, (bl & 0xff) as u8];
+ hs.extend_from_slice(&body);
+
+ let mut rec = vec![0x16, 0x03, 0x01];
+ rec.extend_from_slice(&(hs.len() as u16).to_be_bytes());
+ rec.extend_from_slice(&hs);
+
+ let piv = extract_pivots(&rec);
+ assert!(
+ piv.tls_sni.iter().any(|s| s == "sni.example"),
+ "{:?}",
+ piv.tls_sni
+ );
+ }
+}
diff --git a/crates/ghidrust-net-parse/src/smb.rs b/crates/ghidrust-net-parse/src/smb.rs
new file mode 100644
index 0000000..f89849c
--- /dev/null
+++ b/crates/ghidrust-net-parse/src/smb.rs
@@ -0,0 +1,42 @@
+//! Minimal SMB share-name heuristic from payload bytes.
+
+pub fn parse_shares(data: &[u8]) -> Option<Vec<String>> {
+ // Look for UTF-16LE \\server\share or ASCII \\\\ patterns.
+ let mut shares = Vec::new();
+ if let Ok(s) = std::str::from_utf8(data) {
+ for part in s.split(|c: char| c == '\0' || c.is_whitespace()) {
+ if part.starts_with("\\\\") || part.starts_with("//") {
+ shares.push(part.to_string());
+ }
+ }
+ }
+ // UTF-16LE scan for \\
+ let mut i = 0;
+ while i + 3 < data.len() {
+ if data[i] == b'\\' && data[i + 1] == 0 && data[i + 2] == b'\\' && data[i + 3] == 0 {
+ let mut chars = Vec::new();
+ let mut j = i;
+ while j + 1 < data.len() && chars.len() < 128 {
+ let lo = data[j];
+ let hi = data[j + 1];
+ if hi == 0 && (lo.is_ascii_graphic() || lo == b'\\' || lo == b'/') {
+ chars.push(lo as char);
+ j += 2;
+ } else {
+ break;
+ }
+ }
+ if chars.len() > 3 {
+ shares.push(chars.into_iter().collect());
+ }
+ i = j;
+ } else {
+ i += 1;
+ }
+ }
+ if shares.is_empty() {
+ None
+ } else {
+ Some(shares)
+ }
+}
diff --git a/crates/ghidrust-net-parse/src/tls.rs b/crates/ghidrust-net-parse/src/tls.rs
new file mode 100644
index 0000000..dba279e
--- /dev/null
+++ b/crates/ghidrust-net-parse/src/tls.rs
@@ -0,0 +1,82 @@
+//! Minimal TLS ClientHello SNI (+ optional JA3 fingerprint string).
+
+pub fn parse_client_hello(data: &[u8]) -> Option<(Option<String>, Option<String>)> {
+ if data.len() < 9 || data[0] != 0x16 {
+ return None;
+ }
+ // record header: type(1) ver(2) len(2)
+ let rec_len = u16::from_be_bytes([data[3], data[4]]) as usize;
+ if data.len() < 5 + rec_len {
+ // still try
+ }
+ let mut i = 5;
+ if i >= data.len() || data[i] != 0x01 {
+ // maybe handshake starts at 0
+ if data[0] == 0x01 {
+ i = 0;
+ } else {
+ return None;
+ }
+ }
+ if i + 4 > data.len() {
+ return None;
+ }
+ // handshake: type(1) len(3)
+ let hs_len = ((data[i + 1] as usize) << 16) | ((data[i + 2] as usize) << 8) | data[i + 3] as usize;
+ i += 4;
+ if i + hs_len.min(4) > data.len() {
+ return None;
+ }
+ let end = (i + hs_len).min(data.len());
+ if i + 34 > end {
+ return None;
+ }
+ i += 2; // client version
+ i += 32; // random
+ if i >= end {
+ return None;
+ }
+ let sid_len = data[i] as usize;
+ i += 1 + sid_len;
+ if i + 2 > end {
+ return None;
+ }
+ let cs_len = u16::from_be_bytes([data[i], data[i + 1]]) as usize;
+ i += 2 + cs_len;
+ if i >= end {
+ return None;
+ }
+ let comp_len = data[i] as usize;
+ i += 1 + comp_len;
+ if i + 2 > end {
+ return Some((None, None));
+ }
+ let ext_len = u16::from_be_bytes([data[i], data[i + 1]]) as usize;
+ i += 2;
+ let ext_end = (i + ext_len).min(end);
+ let mut sni = None;
+ while i + 4 <= ext_end {
+ let typ = u16::from_be_bytes([data[i], data[i + 1]]);
+ let elen = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
+ i += 4;
+ if i + elen > ext_end {
+ break;
+ }
+ if typ == 0 && elen >= 5 {
+ // SNI list
+ let mut j = i + 2; // skip list len
+ if j + 3 <= i + elen {
+ let name_type = data[j];
+ let nlen = u16::from_be_bytes([data[j + 1], data[j + 2]]) as usize;
+ j += 3;
+ if name_type == 0 && j + nlen <= i + elen {
+ sni = Some(String::from_utf8_lossy(&data[j..j + nlen]).to_string());
+ }
+ }
+ }
+ i += elen;
+ }
+ // JA3: simplified fingerprint = version-ciphers placeholder
+ let ja3 = sni.as_ref().map(|_| "native-ja3-placeholder".to_string());
+ Some((sni, ja3))
+}
diff --git a/crates/ghidrust-net-rules/Cargo.toml b/crates/ghidrust-net-rules/Cargo.toml
new file mode 100644
index 0000000..efeb2c4
--- /dev/null
+++ b/crates/ghidrust-net-rules/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "ghidrust-net-rules"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "Ghidrust Net Rule (GNR) dialect parse and compile"
+
+[dependencies]
+ghidrust-net-schema = { workspace = true }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
diff --git a/crates/ghidrust-net-rules/src/lib.rs b/crates/ghidrust-net-rules/src/lib.rs
new file mode 100644
index 0000000..c9d9db9
--- /dev/null
+++ b/crates/ghidrust-net-rules/src/lib.rs
@@ -0,0 +1,262 @@
+//! Ghidrust Net Rule (GNR) dialect — parse and compile.
+
+use serde::{Deserialize, Serialize};
+use std::path::Path;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Rule {
+ pub action: String,
+ pub proto: String,
+ pub src: String,
+ pub src_port: String,
+ pub direction: String,
+ pub dst: String,
+ pub dst_port: String,
+ pub sid: u32,
+ pub msg: String,
+ pub severity: u8,
+ pub contents: Vec<ContentOpt>,
+ #[serde(default)]
+ pub skipped_options: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ContentOpt {
+ pub pattern: Vec<u8>,
+ pub nocase: bool,
+ pub offset: Option<usize>,
+ pub depth: Option<usize>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct CompiledRuleset {
+ pub rules: Vec<Rule>,
+ pub warnings: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RuleError {
+ pub code: String,
+ pub message: String,
+}
+
+impl std::fmt::Display for RuleError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}: {}", self.code, self.message)
+ }
+}
+impl std::error::Error for RuleError {}
+
+/// Load and compile a rules file.
+pub fn load_rule_pack(path: &Path) -> Result<CompiledRuleset, RuleError> {
+ let text = std::fs::read_to_string(path).map_err(|e| RuleError {
+ code: "io".into(),
+ message: e.to_string(),
+ })?;
+ compile_rules(&text)
+}
+
+/// Compile GNR text (one rule per line; `#` comments).
+pub fn compile_rules(text: &str) -> Result<CompiledRuleset, RuleError> {
+ let mut rules = Vec::new();
+ let mut warnings = Vec::new();
+ for (lineno, raw) in text.lines().enumerate() {
+ let line = raw.trim();
+ if line.is_empty() || line.starts_with('#') {
+ continue;
+ }
+ match parse_rule_line(line) {
+ Ok(r) => {
+ for s in &r.skipped_options {
+ warnings.push(format!("line {}: skipped option '{s}'", lineno + 1));
+ }
+ rules.push(r);
+ }
+ Err(e) => {
+ return Err(RuleError {
+ code: "parse".into(),
+ message: format!("line {}: {}", lineno + 1, e.message),
+ });
+ }
+ }
+ }
+ Ok(CompiledRuleset { rules, warnings })
+}
+
+fn parse_rule_line(line: &str) -> Result<Rule, RuleError> {
+ // header (options)
+ let (header, opts) = if let Some(i) = line.find('(') {
+ let end = line.rfind(')').ok_or_else(|| RuleError {
+ code: "parse".into(),
+ message: "missing closing ')'".into(),
+ })?;
+ (&line[..i], &line[i + 1..end])
+ } else {
+ return Err(RuleError {
+ code: "parse".into(),
+ message: "missing options block".into(),
+ });
+ };
+ let parts: Vec<_> = header.split_whitespace().collect();
+ if parts.len() < 7 {
+ return Err(RuleError {
+ code: "parse".into(),
+ message: "expected: action proto src sport dir dst dport".into(),
+ });
+ }
+ let mut sid = 0u32;
+ let mut msg = String::new();
+ let mut severity = 2u8;
+ let mut contents = Vec::new();
+ let mut skipped = Vec::new();
+ for opt in opts.split(';') {
+ let opt = opt.trim();
+ if opt.is_empty() {
+ continue;
+ }
+ if let Some(rest) = opt.strip_prefix("msg:") {
+ msg = unquote(rest.trim());
+ } else if let Some(rest) = opt.strip_prefix("sid:") {
+ sid = rest.trim().parse().unwrap_or(0);
+ } else if let Some(rest) = opt.strip_prefix("severity:") {
+ severity = rest.trim().parse().unwrap_or(2);
+ } else if let Some(rest) = opt.strip_prefix("content:") {
+ let (pat, flags) = split_content(rest.trim());
+ let mut c = ContentOpt {
+ pattern: unescape_content(&unquote(&pat)),
+ nocase: false,
+ offset: None,
+ depth: None,
+ };
+ for f in flags {
+ match f {
+ "nocase" => c.nocase = true,
+ other if other.starts_with("offset:") => {
+ c.offset = other["offset:".len()..].parse().ok();
+ }
+ other if other.starts_with("depth:") => {
+ c.depth = other["depth:".len()..].parse().ok();
+ }
+ other => skipped.push(other.to_string()),
+ }
+ }
+ contents.push(c);
+ } else if opt == "nocase" {
+ if let Some(c) = contents.last_mut() {
+ c.nocase = true;
+ }
+ } else if let Some(rest) = opt.strip_prefix("offset:") {
+ if let Some(c) = contents.last_mut() {
+ c.offset = rest.trim().parse().ok();
+ }
+ } else if let Some(rest) = opt.strip_prefix("depth:") {
+ if let Some(c) = contents.last_mut() {
+ c.depth = rest.trim().parse().ok();
+ }
+ } else if opt.starts_with("classtype:")
+ || opt.starts_with("rev:")
+ || opt.starts_with("reference:")
+ || opt == "flow:to_server"
+ || opt == "flow:established"
+ {
+ // recognized no-ops for Wave 3
+ } else {
+ skipped.push(opt.to_string());
+ }
+ }
+ if sid == 0 {
+ return Err(RuleError {
+ code: "parse".into(),
+ message: "sid required".into(),
+ });
+ }
+ Ok(Rule {
+ action: parts[0].into(),
+ proto: parts[1].into(),
+ src: parts[2].into(),
+ src_port: parts[3].into(),
+ direction: parts[4].into(),
+ dst: parts[5].into(),
+ dst_port: parts[6].into(),
+ sid,
+ msg,
+ severity,
+ contents,
+ skipped_options: skipped,
+ })
+}
+
+fn unquote(s: &str) -> String {
+ let s = s.trim();
+ if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
+ s[1..s.len() - 1].to_string()
+ } else {
+ s.to_string()
+ }
+}
+
+fn split_content(s: &str) -> (String, Vec<&str>) {
+ // "pattern"[,flags...]
+ let s = s.trim();
+ if let Some(rest) = s.strip_prefix('"') {
+ if let Some(end) = rest.find('"') {
+ let pat = format!("\"{}\"", &rest[..end]);
+ let after = rest[end + 1..].trim().trim_start_matches(',').trim();
+ let flags: Vec<_> = if after.is_empty() {
+ Vec::new()
+ } else {
+ after.split(',').map(|x| x.trim()).filter(|x| !x.is_empty()).collect()
+ };
+ return (pat, flags);
+ }
+ }
+ (s.to_string(), Vec::new())
+}
+
+fn unescape_content(s: &str) -> Vec<u8> {
+ // Support |HH HH| hex runs mixed with text.
+ let mut out = Vec::new();
+ let mut chars = s.chars().peekable();
+ while let Some(c) = chars.next() {
+ if c == '|' {
+ let mut hex = String::new();
+ while let Some(&n) = chars.peek() {
+ if n == '|' {
+ chars.next();
+ break;
+ }
+ hex.push(n);
+ chars.next();
+ }
+ for part in hex.split_whitespace() {
+ if let Ok(b) = u8::from_str_radix(part, 16) {
+ out.push(b);
+ }
+ }
+ } else {
+ out.push(c as u8);
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parse_minimal_content_rule() {
+ let text = r#"alert tcp any any -> any any (msg:"probe"; content:"EVIL"; nocase; sid:1000001; severity:2;)"#;
+ let set = compile_rules(text).unwrap();
+ assert_eq!(set.rules.len(), 1);
+ assert_eq!(set.rules[0].sid, 1000001);
+ assert_eq!(set.rules[0].contents[0].pattern, b"EVIL");
+ assert!(set.rules[0].contents[0].nocase);
+ }
+
+ #[test]
+ fn malformed_missing_sid() {
+ let text = r#"alert tcp any any -> any any (msg:"x"; content:"EVIL";)"#;
+ assert!(compile_rules(text).is_err());
+ }
+}
diff --git a/crates/ghidrust-net-schema/Cargo.toml b/crates/ghidrust-net-schema/Cargo.toml
new file mode 100644
index 0000000..9bd5259
--- /dev/null
+++ b/crates/ghidrust-net-schema/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "ghidrust-net-schema"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "Versioned network investigation value objects (hints, dig plans, alerts, flows)"
+
+[dependencies]
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
diff --git a/crates/ghidrust-net-schema/src/lib.rs b/crates/ghidrust-net-schema/src/lib.rs
new file mode 100644
index 0000000..b4f7c67
--- /dev/null
+++ b/crates/ghidrust-net-schema/src/lib.rs
@@ -0,0 +1,245 @@
+//! Shared value objects for the native network investigation plane.
+//!
+//! No OS or analysis-engine dependencies — serde shapes only.
+
+use serde::{Deserialize, Serialize};
+
+/// Confidence of process/image attribution.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum Confidence {
+ Exact,
+ Likely,
+ #[default]
+ Unknown,
+}
+
+impl Confidence {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Exact => "exact",
+ Self::Likely => "likely",
+ Self::Unknown => "unknown",
+ }
+ }
+}
+
+/// Hint that starts a dig playbook.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct NetHint {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub path: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pid: Option<u32>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub host: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ioc: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub alert_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub flow_ref: Option<String>,
+}
+
+impl NetHint {
+ pub fn is_empty(&self) -> bool {
+ self.path.is_none()
+ && self.pid.is_none()
+ && self.host.is_none()
+ && self.ioc.is_none()
+ && self.alert_id.is_none()
+ && self.flow_ref.is_none()
+ }
+}
+
+/// One MCP/CLI-shaped dig step.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DigStep {
+ pub tool: String,
+ #[serde(default)]
+ pub args: serde_json::Value,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub note: Option<String>,
+}
+
+/// Compiled dig playbook.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DigPlan {
+ pub steps: Vec<DigStep>,
+ pub rationale: String,
+ #[serde(default)]
+ pub next_steps: Vec<String>,
+ #[serde(default)]
+ pub hint: NetHint,
+}
+
+/// Offline dig execution result.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct DigResult {
+ #[serde(default)]
+ pub artifact_ids: Vec<String>,
+ #[serde(default)]
+ pub findings: Vec<DigFinding>,
+ #[serde(default)]
+ pub plan: Option<DigPlan>,
+ #[serde(default)]
+ pub status: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DigFinding {
+ pub kind: String,
+ pub detail: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub evidence: Option<String>,
+}
+
+/// Process / image owner of a socket or flow.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Owner {
+ pub pid: u32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub image_path: Option<String>,
+ #[serde(default)]
+ pub image_confidence: Confidence,
+ #[serde(default)]
+ pub pid_confidence: Confidence,
+}
+
+/// One row from the host socket table.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ConnectionView {
+ pub proto: String,
+ pub local: String,
+ pub remote: String,
+ pub state: String,
+ pub pid: u32,
+ #[serde(default)]
+ pub pid_confidence: Confidence,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub image_path: Option<String>,
+ #[serde(default)]
+ pub image_confidence: Confidence,
+}
+
+/// Flow identity.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct FlowKey {
+ pub proto: String,
+ pub src: String,
+ pub dst: String,
+ pub src_port: u16,
+ pub dst_port: u16,
+}
+
+/// Attributed flow summary.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AttributedFlow {
+ pub key: FlowKey,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub owner: Option<Owner>,
+ pub bytes_tx: u64,
+ pub bytes_rx: u64,
+ pub first_seen_ms: u64,
+ pub last_seen_ms: u64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub flow_id: Option<String>,
+}
+
+/// Detection alert.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Alert {
+ pub id: String,
+ pub sid: u32,
+ pub msg: String,
+ pub severity: u8,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub flow_key: Option<FlowKey>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub owner: Option<Owner>,
+ pub timestamp_ms: u64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub host: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ioc: Option<String>,
+}
+
+/// Closed-loop dig job.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DigJob {
+ pub job_id: String,
+ pub source: String,
+ pub plan: DigPlan,
+ #[serde(default)]
+ pub result: DigResult,
+ pub status: String,
+}
+
+/// App-layer pivot fields for RE.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct PivotFields {
+ #[serde(default)]
+ pub dns_qnames: Vec<String>,
+ #[serde(default)]
+ pub tls_sni: Vec<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ja3: Option<String>,
+ #[serde(default)]
+ pub http_hosts: Vec<String>,
+ #[serde(default)]
+ pub http_uris: Vec<String>,
+ #[serde(default)]
+ pub smb_shares: Vec<String>,
+}
+
+/// Capture session descriptor.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CaptureSessionInfo {
+ pub session_id: String,
+ pub running: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub iface: Option<String>,
+ pub bytes_written: u64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub out_path: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub attr_path: Option<String>,
+}
+
+/// Network surface report for `server_info`.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct NetworkInfo {
+ pub wave: u32,
+ pub caps: Vec<String>,
+ pub native: bool,
+ pub capture: bool,
+}
+
+impl Default for NetworkInfo {
+ fn default() -> Self {
+ Self {
+ wave: 0,
+ caps: vec!["dig".into(), "playbook".into()],
+ native: true,
+ capture: false,
+ }
+ }
+}
+
+/// Closed-loop configuration.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ClosedLoopConfig {
+ pub auto_analyze: bool,
+ pub auto_decompile_limit: usize,
+ pub attach_live: bool,
+}
+
+impl Default for ClosedLoopConfig {
+ fn default() -> Self {
+ Self {
+ auto_analyze: true,
+ auto_decompile_limit: 3,
+ attach_live: false,
+ }
+ }
+}
diff --git a/rules/ghidrust-minimal.rules b/rules/ghidrust-minimal.rules
new file mode 100644
index 0000000..22abf92
--- /dev/null
+++ b/rules/ghidrust-minimal.rules
@@ -0,0 +1,3 @@
+# Ghidrust Net Rule (GNR) minimal pack — host investigation demos
+alert tcp any any -> any any (msg:"ghidrust evil marker"; content:"EVILCMD"; nocase; sid:1000001; severity:3;)
+alert tcp any any -> any any (msg:"ghidrust http get probe"; content:"GET /"; sid:1000002; severity:1;)
diff --git a/skill/README.md b/skill/README.md
index e465ce7..6a2e2f1 100644
--- a/skill/README.md
+++ b/skill/README.md
@@ -33,7 +33,7 @@ cargo run -p ghidrust-gui --release
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).
-Check build identity: `ghidrust --version` (same package version as MCP `server_info` and egui About). Agents need MCP `tool_surface >= 3` (touch-map / body_class / function_create); prefer `>= 4` for bounded disasm / `get_calls_from`; `>= 5` for decode tools; **`>= 6`** for crypto recover/bake; **`>= 7`** for live process debug (break/step/regs/stack/scan/watch; current is `7`). Restart MCP after rebuild if those or `process_*` are missing.
+Check build identity: `ghidrust --version` (same package version as MCP `server_info` and egui About). Agents need MCP `tool_surface >= 3` (touch-map / body_class / function_create); prefer `>= 4` for bounded disasm / `get_calls_from`; `>= 5` for decode tools; **`>= 6`** for crypto recover/bake; **`>= 7`** for live process debug; **`>= 8`** for Ghidnet (`net_*`, `server_info.network`; see [ghidnet.md](ghidnet.md)). Restart MCP after rebuild if those tools are missing.
Smoke crypto surfaces:
diff --git a/skill/SKILL.md b/skill/SKILL.md
index adfc9f3..988307d 100644
--- a/skill/SKILL.md
+++ b/skill/SKILL.md
@@ -3,13 +3,15 @@ name: ghidrust
description: >
x86-64 Auto Analysis, projects, CLI/MCP, egui GUI, IL2CPP metadata, Unity player inventory,
GPU analyzer kernels + multipass decompile, crypt-constants / recover-strings / decode bake /
- crypto-capabilities. Exhaustive feature catalog with when-to-use guidance.
+ crypto-capabilities, Ghidnet native network dig/connections/capture/detect/pivots/rules.
+ Exhaustive feature catalog with when-to-use guidance.
Triggers: /ghidrust, reverse engineer, RE a PE/ELF, disassemble, decode-support, decode-query,
MCP ghidrust, strings/functions, crypt-constants, recover-strings, decode bake, decode magic,
crypto-capabilities, GPU decompile, IL2CPP, global-metadata, unity-inventory, GameAssembly,
- analyzer-bench, rtti-gpu-bench, bulk-bench.
+ analyzer-bench, rtti-gpu-bench, bulk-bench, Ghidnet, net dig, phone home, network pivot, IOC dig,
+ net_connections, net_detect, net_capture, net_rules_check, GNR, ghidrust-netcap.
metadata:
- short-description: "Ghidrust RE — decode, crypto recover, CLI, MCP, IL2CPP, Unity, analyzers, GPU"
+ short-description: "Ghidrust RE — decode, crypto, Ghidnet, CLI, MCP, IL2CPP, Unity, analyzers, GPU"
---
# Ghidrust — agent skill
@@ -23,6 +25,9 @@ metadata:
| Workspace root | repo root (`Cargo.toml` with `ghidrust-core`, `ghidrust-cli`, `ghidrust-gui`, `ghidrust-decomp`, `ghidrust-il2cpp`, `ghidrust-unity-inventory`) |
| CLI | `cargo run -p ghidrust-cli --release -- <cmd>` or `target/release/ghidrust.exe` |
| GUI | `cargo run -p ghidrust-gui --release` |
+| Ghidnet helper | `target/release/ghidrust-netcap` |
+| GNR rules | `rules/ghidrust-minimal.rules` |
+| Ghidnet SOP | [ghidnet.md](ghidnet.md) (`tool_surface >= 8`) |
| Fixtures | `fixtures/tiny_x64.pe`, `fixtures/analysis_lab.pe`, `fixtures/tiny_x64.elf`, `fixtures/il2cpp/*` |
| Docs | `README.md`, `docs/IL2CPP.md`, `docs/GPU_ANALYZER_MATRIX.md`, `docs/PARALLEL_RE_RESEARCH.md` |
| Decode API | `ghidrust-decode::Engine` — `open`, `disasm`, `disasm_one`, `option`, `insn_name`, `reg_name`, `group_name`, `regs_access`; re-exported from `ghidrust-core` |
@@ -57,7 +62,7 @@ JSON shape:
| `features.decode_diet` | `false` — full detail path (not diet build) |
| `features.x86_reduce` | `false` — full x86 table (not x86 reduce build) |
-`server_info` also sets **`tool_surface: 6`** and lists decode + crypto tools under `features.surface` (`decode_support` / `decode_query` / `crypt_constants` / `recover_strings` / `decode_bake` / `decode_magic` / `list_crypto_capabilities`).
+`server_info` reports monotonic **`tool_surface`** (current **`8`** when Ghidnet is present) and lists surface tools under `features.surface` (decode/crypto/`net_*`). Prefer `server_info.network` for Ghidnet caps.
### CLI — `disasm`, `decode-support`, `decode-query`
@@ -263,7 +268,7 @@ Brief line (`--brief` / MCP `listing_text`): `{addr:#x}: {mnemonic} {operands}`.
## Agent friction SOPs (required)
-- **Version / stale MCP**: Call `server_info` first (or read `initialize.serverInfo`). This skill requires **`tool_surface >= 3`** (touch-map, body_class map, function_create, live process + artifacts). Prefer **`>= 4`** for bounded disasm / `get_calls_from`. Require **`>= 5`** for `decode_support`, `decode_query`, and extended `disassemble` decode flags. Require **`>= 6`** for crypt-constants / recover-strings / decode bake|magic / crypto-capabilities. If `server_info` is missing, `tool_surface` is below the needed minimum, or expected tools are absent from `tools/list` → rebuild `ghidrust`, point the MCP `command` at that binary, **restart the MCP server**. Do **not** conclude live process is unsupported; do **not** invent heap-scan scripts as a substitute. CLI/GUI/MCP share one package version (`ghidrust --version`, MCP `version`, egui About).
+- **Version / stale MCP**: Call `server_info` first (or read `initialize.serverInfo`). This skill requires **`tool_surface >= 3`** (touch-map, body_class map, function_create, live process + artifacts). Prefer **`>= 4`** for bounded disasm / `get_calls_from`. Require **`>= 5`** for `decode_support`, `decode_query`, and extended `disassemble` decode flags. Require **`>= 6`** for crypt-constants / recover-strings / decode bake|magic / crypto-capabilities. Require **`>= 8`** for native network tools (`net_*`, `server_info.network`). If `server_info` is missing, `tool_surface` is below the needed minimum, or expected tools are absent from `tools/list` → rebuild `ghidrust`, point the MCP `command` at that binary, **restart the MCP server**. Do **not** conclude live process is unsupported; do **not** invent heap-scan scripts as a substitute. CLI/GUI/MCP share one package version (`ghidrust --version`, MCP `version`, egui About).
- **Crypto / obfuscated strings**: Prefer `crypt_constants` → `recover_strings` → `decode_bake`/`decode_magic` on leftover blobs; use `list_crypto_capabilities` to locate decrypt/encrypt API sites. Never invent plaintext — empty hits are honest.
- **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.
@@ -275,6 +280,7 @@ Brief line (`--brief` / MCP `listing_text`): `{addr:#x}: {mnemonic} {operands}`.
- **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, `tool_surface >= 7`)**: Multi-step live work **must** use MCP (or one long-lived process). Default attach is **observe** (read-only). Pass `mode: "debug"` for break/step/registers/stack. Loop: `process_list` → `process_attach|process_launch` → `process_modules` → `process_resolve` → optional `process_break_set` / `process_scan` / `process_watch_expr` → `process_continue`/`process_wait` → regs/stack/`process_read` → `process_export_snapshot` → `process_detach`. Observe launch still uses CREATE_SUSPENDED + `process_resume`. Debug launch uses Windows debug APIs (initial break). Never chain separate CLI `ghidrust process` spawns expecting the same `session_id`. Bytes ≠ types. Hardware BP / instrument mode not enabled.
+- **Ghidnet (native, `tool_surface >= 8`)**: Prefer `net_dig` / `net_playbook` over hand-chained load/analyze for phone-home / IOC digs. Check `server_info.network`. Default pack: `rules/ghidrust-minimal.rules`. Multi-step capture/detect **must** use MCP or GUI Network host (`session_id` process-local). GUI: **Network** / **Window → Network** (Connections\|Capture\|Alerts\|Rules\|Dig); Dig → **Open in Listing**; Capture **Export path**; inline block only if `GHIDRUST_NET_INLINE=1`. Airgap: path-only dig; refuse live observe/capture/detect. Never invent hosts; `pid_confidence=unknown` ≠ ground truth; no foreign IDS. Full matrix/workflows: [ghidnet.md](ghidnet.md).
- **IL2CPP offline → live**: (1) `il2cpp_touch_map` / `il2cpp_meta` / `il2cpp_map` for names + method RVAs (null = unknown offline; encrypted → `next_steps` with meta-sections/touch-map). (2) Require `body_class` not `shared_stub` / `semantics_mismatch` before treating a name as a hook target. (3) `decompile` + `follow_stub` for resolve stubs with mapped slots. (4) On `runtime_unresolved` / `trampoline_or_invoker` → live attach → `process_resolve(module, rva)` → `process_read`. (5) Multi-build work: `il2cpp map --baseline PREV.json` → inspect `build_skew` (stale **map catalog**, not only stale MCP binary).
- **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); hook shared stubs as unique gameplay methods.
@@ -319,6 +325,14 @@ Need crypto constants / obfuscated strings / peel a blob?
→ MCP: crypt_constants / recover_strings / list_crypto_capabilities / decode_bake / decode_magic
→ analyze --analyzer "Find Crypt" / "Obfuscated Strings" / "Crypto Capabilities"
+Need network dig / phone-home / IOC → binary (Ghidnet, tool_surface >= 8)?
+ → server_info.network first; full matrix: skill/ghidnet.md
+ → MCP: net_connections → net_dig (execute) OR net_capture_* → net_flows → dig
+ → Detect: net_rules_check → net_detect → net_dig (alert_id)
+ → Pivots: net_pivots → net_dig host/ioc
+ → CLI: ghidrust net … ; GUI: Network host tabs
+ → Airgap: path-only net_dig; no foreign IDS
+
Need GPU decompile at a VA?
→ gpu-decompile <path> --addr HEX (metrics JSON; .gdecomp opaque)
@@ -469,6 +483,13 @@ Requires **`tool_surface >= 3`** (prefer **`>= 4`** for bounded disasm / `get_ca
| `process_list` / `process_attach` / `process_launch` / `process_resume` / `process_detach` / `process_modules` / `process_read` / `process_resolve` / `process_regions` | pid / image / session / `mode` / module / rva / max | Live Process Bridge (Windows; default observe) |
| `process_break_set` / `_clear` / `_list` / `process_continue` / `process_pause` / `process_wait` / `process_step_into` / `_over` / `process_threads` / `process_thread_context_get` / `_set` / `process_stack` | session / addr / thread_id / timeout_ms | Debug mode (`tool_surface >= 7`) |
| `process_scan` / `process_watch_expr` / `process_vtable_probe` / `process_export_snapshot` | session / aob / expr / addr | Live data discovery (`tool_surface >= 7`) |
+| `net_dig` / `net_playbook` | path / pid / host / ioc / alert_id / execute / live | Dig playbooks + closed-loop (`tool_surface >= 8`; see [ghidnet.md](ghidnet.md)) |
+| `net_connections` / `net_owners` | pid / path / proto / max | Host socket → owner (airgap refuses) |
+| `net_ifaces` / `net_capture_start` / `_stop` / `_status` / `net_flows` | iface / filter / session_id / replay_path | Capture sessions (airgap refuses) |
+| `net_detect` / `net_alerts` | pcap / rules / max | GNR detect + alert queue |
+| `net_rules_list` / `net_rules_load` / `net_rules_check` | path | GNR pack list/load/check (`rules/ghidrust-minimal.rules`) |
+| `net_pivots` | pcap | DNS / TLS SNI / HTTP / SMB pivots |
+| `net_job_get` | job_id | **Stub** — do not rely on async dig jobs yet |
MCP launch: `ghidrust mcp` / `target/release/ghidrust.exe mcp` (stdio; no host-specific paths).
diff --git a/skill/ghidnet.md b/skill/ghidnet.md
new file mode 100644
index 0000000..f021662
--- /dev/null
+++ b/skill/ghidnet.md
@@ -0,0 +1,47 @@
+# Ghidnet — native network investigation (`tool_surface >= 8`)
+
+In-tree attribute → detect → dig. No foreign capture/IDS products. Prefer MCP or GUI for multi-step sessions (`session_id` is process-local; CLI one-shot cannot reuse it).
+
+## Surfaces
+
+| Surface | Entry |
+|---------|--------|
+| MCP | `net_*` tools; check `server_info.network` (`native`, `wave`, `caps`, `capture`) |
+| CLI | `ghidrust net dig\|playbook\|connections\|owners\|ifaces\|capture\|flows\|detect\|alerts\|rules\|pivots … [--json]` |
+| GUI | **Network** menu / **Window → Network** — tabs Connections \| Capture \| Alerts \| Rules \| Dig |
+| Helper bin | `target/release/ghidrust-netcap` |
+| Rules pack | `rules/ghidrust-minimal.rules` (default for detect / GUI Rules **Check**) |
+
+## MCP tools
+
+| Tool | Args (common) | Notes |
+|------|----------------|-------|
+| `net_dig` | `path`, `pid`, `host`, `ioc`, `alert_id`, `execute`, `live` | Compile/execute playbook; closed-loop from alert |
+| `net_playbook` | same hint fields | Plan only (MCP chain shape) |
+| `net_connections` | `pid`, `path`, `proto`, `max` | Socket → owner; airgap refuses |
+| `net_owners` | `pid` | Owner detail |
+| `net_ifaces` | — | Interface list (loopback/replay stubs ok) |
+| `net_capture_start` | `iface`, `filter`, `pid`, `path`, `out`, `replay_path` | Returns `session_id` |
+| `net_capture_stop` / `net_capture_status` | `session_id` | |
+| `net_flows` | `session_id`, `max` | Attributed flows |
+| `net_detect` | `pcap`, `rules` | GNR → alerts |
+| `net_alerts` | `max` | Severity queue |
+| `net_rules_list` | — | Loaded/default pack summary |
+| `net_rules_load` / `net_rules_check` | `path` | Compile-check GNR |
+| `net_pivots` | `pcap` | DNS / TLS SNI / HTTP / SMB fields |
+| `net_job_get` | `job_id` | **Stub** today (`status: unknown`) — do not rely on async jobs |
+
+## Workflows
+
+1. **Connections → Dig:** `net_connections` → pick remote/image → `net_dig` with `path` + `host`/`ioc` + `execute`.
+2. **Capture → Dig:** `net_ifaces` → `net_capture_start` (`replay_path` in CI) → `net_flows` → `net_capture_stop` → dig owner `path`.
+3. **Detect → Dig:** `net_rules_check` on pack → `net_detect` → `net_dig` with `alert_id` (+ `path` if alert has no owner).
+4. **Pivots → Dig:** `net_pivots` → feed DNS/SNI/HTTP/SMB host into `net_dig` `host`/`ioc`.
+5. **GUI:** Connections/Capture **Dig** → Dig tab **Compile**/**Execute** → **Open in Listing**. Capture **Export path** reveals `out_path`. Host header / Help→About show NetworkInfo. **Inline block** disabled unless `GHIDRUST_NET_INLINE=1|true`.
+
+## Honesty
+
+- Never invent hosts/IOCs; `pid_confidence=unknown` is not ground truth.
+- Airgap: refuses `net_connections` / `net_owners` / `net_ifaces` / `net_capture_*` / `net_flows` / `net_detect`; path-only `net_dig` / `net_playbook` allowed.
+- Live NIC may be stub/replay-first; prefer `replay_path` for proofs.
+- Do not install Suricata/Wireshark/etc. as a substitute — engines are `ghidrust-net-*`.