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.

tool_surface 7 — live debug/discovery (crypto stays 6) • Session modes: observe (default, read-only) vs debug (explicit) • Windows debug pump — attach/launch debug, wait, continue, pause • Software breakpoints — set / clear / list (INT3; restore on detach) • Step into / over, threads, x64 registers, stack unwind • Discovery: process_scan (AOB/string), process_watch_expr (pointer chase), process_vtable_probe, process_export_snapshot • Structured errors + AC module advisory only (no stealth) • CLI — full process tree (-mode, break/wait/step/scan/watch/…) • MCP — matching tools + handlers • eGUI Debugger — mode, toolbar, Breakpoints / Threads / Registers / Stack / Watches+Scan / Console • Fixture E2E — live_debuggee example + debug tests

oofz24cd0b055e03
diff --git a/README.md b/README.md
index 7cfba74..9444945 100644
--- a/README.md
+++ b/README.md
@@ -194,7 +194,7 @@ 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\|resume\|detach\|modules\|read\|resolve\|regions` | Live Process Bridge (Windows; read-only MVP; launch = CREATE_SUSPENDED) | session_id / `--args` / `--cwd` / `--addr` / `--module` / `--rva` / `--max` |
+| `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 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` |
@@ -316,15 +316,20 @@ ghidrust rtti /path/to/app.exe --filter Widget --json
ghidrust artifact list --json
ghidrust artifact query <id> --offset 0 --limit 64 --json
-# Live process (Windows; read-only)
+# Live process (Windows; observe default, debug opt-in; tool_surface >= 7)
ghidrust process list --json
-ghidrust process attach <pid>
-ghidrust process launch C:\path\to\app.exe --args "--flag" --cwd C:\path\to --json
-ghidrust process resume <session_id>
+ghidrust process attach <pid> -mode observe
+ghidrust process attach <pid> -mode debug
+ghidrust process launch C:\path\to\app.exe -mode debug -break-at-entry --json
ghidrust process modules <session_id> --json
ghidrust process resolve <session_id> --module app.exe --rva 0x1234 --json
+ghidrust process break set <session_id> -addr 0x7ff…
+ghidrust process continue <session_id>
+ghidrust process wait <session_id> -timeout 5000
+ghidrust process stack <session_id> <tid>
+ghidrust process scan <session_id> -aob "48 8b ?? 90"
+ghidrust process watch <session_id> "app.exe+0x1234->*+0x10"
ghidrust process read <session_id> --addr 0x7ff… --size 64 --json
-ghidrust process regions <session_id> --json
ghidrust process detach <session_id>
# Unity player inventory + IL2CPP touch-map / metadata / stubs / method map
@@ -539,13 +544,25 @@ On Linux/macOS:
| `list_gpu_strategies` | — | Per-analyzer GPU strategy matrix |
| `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_resume` / `process_detach` / `process_modules` / `process_read` / `process_resolve` / `process_regions` | session / pid / image / module / rva / max | Live Process Bridge (Windows; no write in MVP) |
+| `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) |
#### Live process (Windows)
-Attach read-only (`PROCESS_VM_READ`): `process list` → `attach <pid>` → `modules` → `resolve --module NAME --rva HEX` (`static_to_live`) → `read --addr LIVE --size N` → optional `regions` / `detach`. **Launch** creates a process with `CREATE_SUSPENDED`, opens a live session, then `process resume` lets it run — not a Ghidra/CE debug break-at-entry. Multi-step work **must** use the long-lived MCP (or GUI) process — CLI `ghidrust process` cannot reuse `session_id` across separate spawns. Short reads and access denied are explicit errors. Bytes ≠ recovered types — do not invent structs from live reads. GUI: one **Debugger** window; Attach/Launch auto-populate modules, regions, and Memory Bytes.
+Default **observe** = read-only (`PROCESS_VM_READ`): `process list` → `attach <pid> [-mode observe]` → `modules` → `resolve --module NAME --rva HEX` → `read` / `scan` / `watch` → `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; **current is `5`**. `server_info.decode` mirrors `decode-support` (version, arches, options, syntax_values).
+**Debug** (`-mode debug`, requires `tool_surface >= 7`): attach or launch with debug rights → `break set` → `continue` / `wait` → registers (`regs`) + `stack` → optional `scan` / `watch` → `snapshot` → `detach`. Observe **launch** still uses `CREATE_SUSPENDED` + `resume`. Debug launch uses Windows debug APIs (initial break). Multi-step work **must** stay in one MCP/GUI process — CLI one-shot cannot reuse `session_id`. Bytes ≠ types. Anti-cheat: advisory only; access denied is explicit.
+
+**GUI Debugger walkthrough**
+
+1. **Debugger → Attach…** (or **Launch…**)
+2. **Targets:** set **Mode = debug**, Attach PID (or Launch with **Break at entry**)
+3. **Modules:** static map `module + RVA` → live VA
+4. **Breakpoints:** paste live VA → **Add**
+5. **Continue (F5)** / **Wait stop** → Registers + Stack update
+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.
#### Analysis artifacts
@@ -561,7 +578,7 @@ Large MCP/CLI dumps spill to `%TEMP%/ghidrust-artifacts/`. Tool envelopes includ
| Artifact spill | **Analysis Artifacts** |
| GPU decompile | Analysis → **GPU Decompile…** |
| Encoding / xrefs / RTTI / notes | Defined Strings, Symbol References, Symbol Tree Classes, Memory Map |
-| Live process | **Debugger** (tabbed): Targets / Modules / Memory Bytes / Regions |
+| Live process | **Debugger** (tabbed): Targets / Modules / Memory Bytes / Regions / Breakpoints / Threads / Registers / Stack / Watches (live APIs under mode=debug) |
IL2CPP version matrix and Unity inventory schema: [docs/IL2CPP.md](docs/IL2CPP.md).
diff --git a/crates/ghidrust-cli/src/friction.rs b/crates/ghidrust-cli/src/friction.rs
index 05d4887..1e1d09f 100644
--- a/crates/ghidrust-cli/src/friction.rs
+++ b/crates/ghidrust-cli/src/friction.rs
@@ -2,10 +2,14 @@
use ghidrust_core::{
artifact_get, artifact_query, envelope_or_spill, inventory_pe_dir, list_artifacts, list_tree,
- load_path, process_attach, process_detach, process_launch, process_list, process_modules,
- process_read, process_regions, process_resolve, process_resume, resolve_function,
- resolve_result_json, rtti_query, section_notes_for, spill_artifact, write_json_no_bom,
- LaunchRequest, Project, RttiMatchMode, TreeListOpts, DEFAULT_PREVIEW_LIMIT,
+ 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_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,
+ RttiMatchMode, ScanOpts, SessionMode, TreeListOpts, DEFAULT_PREVIEW_LIMIT,
};
use serde_json::{json, Value};
use std::path::PathBuf;
@@ -356,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 … [-json]"
+ "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]"
);
return ExitCode::from(2);
}
@@ -386,11 +390,22 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
let pid: u32 = match args.get(1).and_then(|s| s.parse().ok()) {
Some(p) => p,
None => {
- eprintln!("usage: ghidrust process attach <pid>");
+ eprintln!("usage: ghidrust process attach <pid> [-mode observe|debug]");
return ExitCode::from(2);
}
};
- match process_attach(pid) {
+ let mut mode = SessionMode::Observe;
+ let mut i = 2;
+ while i < args.len() {
+ match args[i].as_str() {
+ "-mode" if i + 1 < args.len() => {
+ mode = args[i + 1].parse().unwrap_or(SessionMode::Observe);
+ i += 2;
+ }
+ _ => i += 1,
+ }
+ }
+ match process_attach_opts(pid, &AttachOpts { mode }) {
Ok(s) => {
println!("{}", serde_json::to_string_pretty(&s).unwrap());
ExitCode::SUCCESS
@@ -406,13 +421,15 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
Some(p) => PathBuf::from(p),
None => {
eprintln!(
- "usage: ghidrust process launch <image.exe> [-args \"…\"] [-cwd DIR] [-json]"
+ "usage: ghidrust process launch <image.exe> [-args \"…\"] [-cwd DIR] [-mode observe|debug] [-break-at-entry] [-json]"
);
return ExitCode::from(2);
}
};
let mut launch_args: Option<String> = None;
let mut cwd: Option<PathBuf> = None;
+ let mut mode = SessionMode::Observe;
+ let mut break_at_entry = false;
let mut i = 2;
while i < args.len() {
match args[i].as_str() {
@@ -424,6 +441,14 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
cwd = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
+ "-mode" if i + 1 < args.len() => {
+ mode = args[i + 1].parse().unwrap_or(SessionMode::Observe);
+ i += 2;
+ }
+ "-break-at-entry" => {
+ break_at_entry = true;
+ i += 1;
+ }
"-json" => i += 1,
_ => i += 1,
}
@@ -432,6 +457,8 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
image,
args: launch_args,
cwd,
+ mode,
+ break_at_entry,
}) {
Ok(r) => {
println!("{}", serde_json::to_string_pretty(&r).unwrap());
@@ -607,6 +634,299 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
}
}
}
+ "break" => {
+ // break set|clear|list
+ match args.get(1).map(|s| s.as_str()) {
+ Some("set") => {
+ let sid = args.get(2).map(|s| s.as_str()).unwrap_or("");
+ let mut addr = None;
+ let mut oneshot = false;
+ let mut i = 3;
+ while i < args.len() {
+ match args[i].as_str() {
+ "-addr" if i + 1 < args.len() => {
+ addr = parse_u64(&args[i + 1]).ok();
+ i += 2;
+ }
+ "-oneshot" => {
+ oneshot = true;
+ i += 1;
+ }
+ _ => i += 1,
+ }
+ }
+ let Some(va) = addr else {
+ eprintln!("usage: process break set <sid> -addr HEX [-oneshot]");
+ return ExitCode::from(2);
+ };
+ match process_break_set(sid, va, BreakKind::Software, oneshot) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ Some("clear") => {
+ let sid = args.get(2).map(|s| s.as_str()).unwrap_or("");
+ let mut id = None;
+ let mut addr = None;
+ let mut i = 3;
+ while i < args.len() {
+ match args[i].as_str() {
+ "-id" if i + 1 < args.len() => {
+ id = args[i + 1].parse().ok();
+ i += 2;
+ }
+ "-addr" if i + 1 < args.len() => {
+ addr = parse_u64(&args[i + 1]).ok();
+ i += 2;
+ }
+ _ => i += 1,
+ }
+ }
+ match process_break_clear(sid, id, addr) {
+ Ok(()) => {
+ println!("{{\"ok\":true}}");
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ Some("list") => {
+ let sid = args.get(2).map(|s| s.as_str()).unwrap_or("");
+ match process_break_list(sid) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ _ => {
+ eprintln!("usage: process break set|clear|list …");
+ ExitCode::from(2)
+ }
+ }
+ }
+ "continue" => {
+ let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
+ match process_continue(sid) {
+ Ok(()) => {
+ println!("{{\"ok\":true}}");
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "pause" => {
+ let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
+ match process_pause(sid) {
+ Ok(()) => {
+ println!("{{\"ok\":true}}");
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "wait" => {
+ let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
+ let mut timeout = 5000u64;
+ let mut i = 2;
+ while i < args.len() {
+ if args[i] == "-timeout" && i + 1 < args.len() {
+ timeout = args[i + 1].parse().unwrap_or(5000);
+ i += 2;
+ } else {
+ i += 1;
+ }
+ }
+ match process_wait(sid, timeout) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "step" => {
+ let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
+ let over = args.iter().any(|a| a == "-over");
+ let r = if over {
+ process_step_over(sid, None)
+ } else {
+ process_step_into(sid, None)
+ };
+ match r {
+ 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) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "regs" => {
+ let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
+ let tid: u32 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);
+ if tid == 0 {
+ eprintln!("usage: process regs <sid> <tid>");
+ return ExitCode::from(2);
+ }
+ match process_thread_context_get(sid, tid) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "stack" => {
+ let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
+ let tid: u32 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);
+ if tid == 0 {
+ eprintln!("usage: process stack <sid> <tid>");
+ return ExitCode::from(2);
+ }
+ match process_stack(sid, tid, 32) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "scan" => {
+ let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
+ let mut aob = None;
+ let mut string = None;
+ let mut i = 2;
+ while i < args.len() {
+ match args[i].as_str() {
+ "-aob" if i + 1 < args.len() => {
+ aob = Some(args[i + 1].clone());
+ i += 2;
+ }
+ "-string" if i + 1 < args.len() => {
+ string = Some(args[i + 1].clone());
+ i += 2;
+ }
+ _ => i += 1,
+ }
+ }
+ let opts = ScanOpts {
+ aob,
+ string,
+ ..ScanOpts::default()
+ };
+ match process_scan_mem(sid, &opts) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "watch" => {
+ let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
+ let expr = args.get(2).map(|s| s.as_str()).unwrap_or("");
+ if expr.is_empty() {
+ eprintln!("usage: process watch <sid> <expr>");
+ return ExitCode::from(2);
+ }
+ match process_watch_expr(sid, expr, false) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "vtable" => {
+ let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
+ let mut addr = None;
+ let mut i = 2;
+ while i < args.len() {
+ if args[i] == "-addr" && i + 1 < args.len() {
+ addr = parse_u64(&args[i + 1]).ok();
+ i += 2;
+ } else {
+ i += 1;
+ }
+ }
+ let Some(va) = addr else {
+ eprintln!("usage: process vtable <sid> -addr HEX");
+ return ExitCode::from(2);
+ };
+ match process_vtable_probe(sid, va, 32) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "snapshot" => {
+ let sid = args.get(1).map(|s| s.as_str()).unwrap_or("");
+ match process_export_snapshot(sid, &[], &[]) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
other => {
eprintln!("unknown process subcommand: {other}");
ExitCode::from(2)
diff --git a/crates/ghidrust-cli/src/main.rs b/crates/ghidrust-cli/src/main.rs
index 611374e..b1f1885 100644
--- a/crates/ghidrust-cli/src/main.rs
+++ b/crates/ghidrust-cli/src/main.rs
@@ -12,13 +12,18 @@ use ghidrust_core::{
analyze_path, analyzer_catalog, artifact_get, artifact_query, assess_decompile_bounds,
calls_callees, collect_callsite_hints, collect_strings_bytes, collect_strings_opts,
create_function, disassemble_range_opts, filter_imports, inventory_pe_dir, list_artifacts,
- list_tree, load_path, load_path_opts, process_attach, process_detach, process_launch,
- process_list, process_modules, process_read, process_regions, process_resolve, process_resume,
- recover_rtti, resolve_function, rtti_query, run_analyzers, scan_ascii_strings_bulk,
- scan_printable_runs_gpu_or_fallback, scan_printable_runs_parallel, scan_printable_runs_seq,
- time_bulk_printable, write_json_no_bom, xrefs_from, xrefs_to, xrefs_to_import,
- xrefs_to_string_filter_opts, AnalysisBundle, BulkScanMode, LaunchRequest, Program, Project,
- RttiMatchMode, StringCollectOpts, StringMatchMode, TreeListOpts, ANALYZER_NAMES,
+ list_tree, live_process_info_json, load_path, load_path_opts, 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_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,
+ scan_printable_runs_seq, time_bulk_printable, write_json_no_bom, xrefs_from, xrefs_to,
+ xrefs_to_import, xrefs_to_string_filter_opts, AnalysisBundle, AttachOpts, BreakKind,
+ BulkScanMode, LaunchRequest, Program, Project, RegisterSet, RttiMatchMode, ScanOpts,
+ SessionMode, StringCollectOpts, StringMatchMode, TreeListOpts, ANALYZER_NAMES,
DEFAULT_PREVIEW_LIMIT,
};
use ghidrust_decomp::decompile_entry;
@@ -46,7 +51,8 @@ const PACKAGE_VERSION: &str = env!("CARGO_PKG_VERSION");
/// `4` = bound-aware disasm + xref attribution + get_calls_from (+ surface 3).
/// `5` = decode engine surface (decode_support, decode_query, extended disassemble).
/// `6` = crypt_constants, recover_strings, decode_bake/magic, crypto_capabilities.
-const TOOL_SURFACE_VERSION: u32 = 6;
+/// `7` = live process debug bridge (break/step/regs/stack/scan/watch).
+const TOOL_SURFACE_VERSION: u32 = 7;
fn package_version() -> &'static str {
PACKAGE_VERSION
@@ -83,21 +89,7 @@ fn server_info_json() -> Value {
"decode_diet": decode_block["features"]["decode_diet"],
"x86_reduce": decode_block["features"]["x86_reduce"],
},
- "live_process": {
- "tools": [
- "process_list",
- "process_attach",
- "process_launch",
- "process_resume",
- "process_detach",
- "process_modules",
- "process_read",
- "process_resolve",
- "process_regions"
- ],
- "session_model": "in_process_mcp",
- "note": "Attach/launch sessions live in the long-lived MCP (or GUI) process. CLI one-shot `ghidrust process` cannot reuse session_id across separate spawns. Launch uses CREATE_SUSPENDED (not debug break-at-entry); call process_resume to run."
- }
+ "live_process": live_process_info_json(),
})
}
@@ -105,11 +97,13 @@ fn server_info_json() -> Value {
fn live_process_next_steps() -> Value {
json!([
"process_list",
- "process_attach",
+ "process_attach (mode=observe|debug) or process_launch",
"process_modules",
"process_resolve (module + method RVA from il2cpp_map)",
- "process_read",
- "optional process_regions / process_detach"
+ "optional process_break_set / process_scan / process_watch_expr (debug for break)",
+ "process_read / process_wait on hit",
+ "optional process_export_snapshot → artifact_query",
+ "process_detach"
])
}
@@ -306,7 +300,9 @@ fn print_help() {
ghidrust inventory <dir> [--max-depth N] [--hash] [--out FILE] [--json]\n\
ghidrust tree <path> [--max-depth N] [--ext LIST] [--name GLOB] [--json]\n\
ghidrust artifact get|query|list <id> [--offset N] [--limit N] [--json]\n\
- ghidrust process list|attach|launch|resume|detach|modules|read|resolve|regions … [--json]\n\
+ 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 rtti <path> [--filter|--name|--exact] [--match MODE] [--json]\n\
ghidrust analyzers [--json]\n\
ghidrust analyze <path> [--analyzers a,b | --analyzer NAME ...] [--gpu] [--json]\n\
@@ -3316,29 +3312,34 @@ fn tool_defs() -> Vec<ToolDef> {
},
ToolDef {
name: "process_attach",
- description: "Attach read-only to a process by pid; returns session_id",
+ description: "Attach to pid; mode=observe (default, read-only) or debug (break/step/regs). Returns session_id + capabilities.",
input_schema: json!({
"type": "object",
- "properties": { "pid": { "type": "integer" } },
+ "properties": {
+ "pid": { "type": "integer" },
+ "mode": { "type": "string", "enum": ["observe", "debug"], "description": "Default observe" }
+ },
"required": ["pid"]
}),
},
ToolDef {
name: "process_launch",
- description: "CreateProcess CREATE_SUSPENDED + live session (Windows). Not a debug break-at-entry — call process_resume to run. Fails if a session is already open.",
+ description: "Launch process under Live Process Bridge. mode=observe: CREATE_SUSPENDED. mode=debug: DEBUG_ONLY_THIS_PROCESS + initial break. Fails if a session is already open.",
input_schema: json!({
"type": "object",
"properties": {
"image": { "type": "string", "description": "Path to .exe" },
"args": { "type": "string", "description": "Optional args after the image" },
- "cwd": { "type": "string", "description": "Optional working directory" }
+ "cwd": { "type": "string", "description": "Optional working directory" },
+ "mode": { "type": "string", "enum": ["observe", "debug"] },
+ "break_at_entry": { "type": "boolean", "description": "Debug: prefer stop at initial breakpoint" }
},
"required": ["image"]
}),
},
ToolDef {
name: "process_resume",
- description: "Resume the primary thread of a process_launch session (CREATE_SUSPENDED)",
+ description: "Resume observe CREATE_SUSPENDED primary thread, or continue a debug session",
input_schema: json!({
"type": "object",
"properties": { "session_id": { "type": "string" } },
@@ -3347,7 +3348,7 @@ fn tool_defs() -> Vec<ToolDef> {
},
ToolDef {
name: "process_detach",
- description: "Detach a live-process session by session_id",
+ description: "Detach a live-process session by session_id (restores software BPs)",
input_schema: json!({
"type": "object",
"properties": { "session_id": { "type": "string" } },
@@ -3398,6 +3399,199 @@ fn tool_defs() -> Vec<ToolDef> {
"session_id": { "type": "string" },
"max": { "type": "integer", "description": "Max regions (default 256)" }
},
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_break_set",
+ description: "Set software breakpoint (debug mode). Hardware BP not enabled yet.",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "addr": { "type": "string" },
+ "kind": { "type": "string", "enum": ["software", "hardware"] },
+ "oneshot": { "type": "boolean" }
+ },
+ "required": ["session_id", "addr"]
+ }),
+ },
+ ToolDef {
+ name: "process_break_clear",
+ description: "Clear breakpoint by id or addr (debug mode)",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "id": { "type": "integer" },
+ "addr": { "type": "string" }
+ },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_break_list",
+ description: "List breakpoints for a debug session",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "session_id": { "type": "string" } },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_continue",
+ description: "Continue a stopped debug session",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "session_id": { "type": "string" } },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_pause",
+ description: "DebugBreakProcess / interrupt (debug mode)",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "session_id": { "type": "string" } },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_wait",
+ description: "Wait for stop event (breakpoint/step/exception/exit). timeout_ms default 5000.",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "timeout_ms": { "type": "integer" }
+ },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_step_into",
+ description: "Single-step into (TF). 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"]
+ }),
+ },
+ ToolDef {
+ name: "process_step_over",
+ description: "Single-step over (TF MVP). 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"]
+ }),
+ },
+ ToolDef {
+ name: "process_threads",
+ description: "List threads in the target (debug mode)",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "session_id": { "type": "string" } },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_thread_context_get",
+ description: "Get x64 registers for a thread (debug mode)",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "thread_id": { "type": "integer" }
+ },
+ "required": ["session_id", "thread_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_thread_context_set",
+ description: "Set x64 registers for a thread (debug mode)",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "thread_id": { "type": "integer" },
+ "registers": { "type": "object" }
+ },
+ "required": ["session_id", "thread_id", "registers"]
+ }),
+ },
+ ToolDef {
+ name: "process_stack",
+ description: "Unwind call stack for a thread (debug mode; RBP chain + optional pdata)",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "thread_id": { "type": "integer" },
+ "max_frames": { "type": "integer" }
+ },
+ "required": ["session_id", "thread_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_scan",
+ description: "Pattern scan live memory (AOB/string). Bytes ≠ types. Optional diff_wait_ms.",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "aob": { "type": "string", "description": "Hex pattern with ?? wildcards" },
+ "string": { "type": "string" },
+ "utf16": { "type": "boolean" },
+ "module": { "type": "string" },
+ "max_hits": { "type": "integer" },
+ "diff_wait_ms": { "type": "integer" }
+ },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_watch_expr",
+ description: "Pointer-chase DSL: module+rva, u64@va, va->*+0x10. Heuristic float4x4 flagged when requested.",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "expr": { "type": "string" },
+ "matrix_heuristic": { "type": "boolean" }
+ },
+ "required": ["session_id", "expr"]
+ }),
+ },
+ ToolDef {
+ name: "process_vtable_probe",
+ description: "Validate object* vtable in module image; list slot targets as live VAs",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "addr": { "type": "string", "description": "object* live VA" },
+ "max_slots": { "type": "integer" }
+ },
+ "required": ["session_id", "addr"]
+ }),
+ },
+ ToolDef {
+ name: "process_export_snapshot",
+ description: "Dump regs/stack/watches/nearby reads to JSON for agent handoff",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "watches": { "type": "array", "items": { "type": "string" } },
+ "nearby": { "type": "array", "items": { "type": "string" } }
+ },
"required": ["session_id"]
}),
},
@@ -4129,7 +4323,13 @@ fn call_tool(params: &Value) -> Result<String, String> {
.get("pid")
.and_then(|p| p.as_u64())
.ok_or_else(|| "missing arguments.pid".to_string())? as u32;
- let s = process_attach(pid)?;
+ let mode = args
+ .get("mode")
+ .and_then(|m| m.as_str())
+ .unwrap_or("observe")
+ .parse::<SessionMode>()
+ .map_err(|e| e.to_string())?;
+ let s = process_attach_opts(pid, &AttachOpts { mode })?;
Ok(serde_json::to_string_pretty(&s).unwrap())
}
"process_launch" => {
@@ -4145,10 +4345,22 @@ fn call_tool(params: &Value) -> Result<String, String> {
.get("cwd")
.and_then(|c| c.as_str())
.map(std::path::PathBuf::from);
+ let mode = args
+ .get("mode")
+ .and_then(|m| m.as_str())
+ .unwrap_or("observe")
+ .parse::<ghidrust_core::SessionMode>()
+ .map_err(|e| e.to_string())?;
+ let break_at_entry = args
+ .get("break_at_entry")
+ .and_then(|b| b.as_bool())
+ .unwrap_or(false);
let r = process_launch(&LaunchRequest {
image: std::path::PathBuf::from(image),
args: launch_args,
cwd,
+ mode,
+ break_at_entry,
})?;
Ok(serde_json::to_string_pretty(&r).unwrap())
}
@@ -4216,6 +4428,242 @@ fn call_tool(params: &Value) -> Result<String, String> {
let r = process_regions(sid, max)?;
Ok(serde_json::to_string_pretty(&r).unwrap())
}
+ "process_break_set" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let addr = parse_u64(
+ args.get("addr")
+ .and_then(|a| a.as_str())
+ .ok_or_else(|| "missing arguments.addr".to_string())?,
+ )?;
+ let kind = args
+ .get("kind")
+ .and_then(|k| k.as_str())
+ .unwrap_or("software")
+ .parse::<BreakKind>()
+ .map_err(|e| e.to_string())?;
+ let oneshot = args
+ .get("oneshot")
+ .and_then(|b| b.as_bool())
+ .unwrap_or(false);
+ let r = process_break_set(sid, addr, kind, oneshot)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "process_break_clear" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let id = args.get("id").and_then(|i| i.as_u64());
+ let addr = args
+ .get("addr")
+ .and_then(|a| a.as_str())
+ .map(parse_u64)
+ .transpose()?;
+ process_break_clear(sid, id, addr)?;
+ Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())
+ }
+ "process_break_list" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let r = process_break_list(sid)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "process_continue" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ process_continue(sid)?;
+ Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())
+ }
+ "process_pause" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ process_pause(sid)?;
+ Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())
+ }
+ "process_wait" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let timeout_ms = args
+ .get("timeout_ms")
+ .and_then(|t| t.as_u64())
+ .unwrap_or(5000);
+ let r = process_wait(sid, timeout_ms)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "process_step_into" => {
+ 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_into(sid, tid)?;
+ Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())
+ }
+ "process_step_over" => {
+ 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_over(sid, tid)?;
+ Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())
+ }
+ "process_threads" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let r = process_threads(sid)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "process_thread_context_get" => {
+ 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())
+ .ok_or_else(|| "missing arguments.thread_id".to_string())?
+ as u32;
+ let r = process_thread_context_get(sid, tid)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "process_thread_context_set" => {
+ 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())
+ .ok_or_else(|| "missing arguments.thread_id".to_string())?
+ as u32;
+ let regs: RegisterSet = serde_json::from_value(
+ args.get("registers")
+ .cloned()
+ .ok_or_else(|| "missing arguments.registers".to_string())?,
+ )
+ .map_err(|e| e.to_string())?;
+ process_thread_context_set(sid, tid, &regs)?;
+ Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())
+ }
+ "process_stack" => {
+ 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())
+ .ok_or_else(|| "missing arguments.thread_id".to_string())?
+ as u32;
+ let max = args
+ .get("max_frames")
+ .and_then(|m| m.as_u64())
+ .unwrap_or(32) as usize;
+ let r = process_stack(sid, tid, max)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "process_scan" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let opts = ScanOpts {
+ aob: args
+ .get("aob")
+ .and_then(|a| a.as_str())
+ .map(|s| s.to_string()),
+ string: args
+ .get("string")
+ .and_then(|s| s.as_str())
+ .map(|s| s.to_string()),
+ utf16: args.get("utf16").and_then(|b| b.as_bool()).unwrap_or(false),
+ module_only: args
+ .get("module")
+ .and_then(|m| m.as_str())
+ .map(|s| s.to_string()),
+ max_hits: args
+ .get("max_hits")
+ .and_then(|m| m.as_u64())
+ .unwrap_or(256) as usize,
+ diff_wait_ms: args.get("diff_wait_ms").and_then(|d| d.as_u64()),
+ ..ScanOpts::default()
+ };
+ let r = process_scan_mem(sid, &opts)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "process_watch_expr" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let expr = args
+ .get("expr")
+ .and_then(|e| e.as_str())
+ .ok_or_else(|| "missing arguments.expr".to_string())?;
+ let heur = args
+ .get("matrix_heuristic")
+ .and_then(|b| b.as_bool())
+ .unwrap_or(false);
+ let r = process_watch_expr(sid, expr, heur)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "process_vtable_probe" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let addr = parse_u64(
+ args.get("addr")
+ .and_then(|a| a.as_str())
+ .ok_or_else(|| "missing arguments.addr".to_string())?,
+ )?;
+ let max_slots = args
+ .get("max_slots")
+ .and_then(|m| m.as_u64())
+ .unwrap_or(32) as usize;
+ let r = process_vtable_probe(sid, addr, max_slots)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "process_export_snapshot" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let watches: Vec<String> = args
+ .get("watches")
+ .and_then(|w| w.as_array())
+ .map(|a| {
+ a.iter()
+ .filter_map(|v| v.as_str().map(|s| s.to_string()))
+ .collect()
+ })
+ .unwrap_or_default();
+ let nearby: Vec<u64> = args
+ .get("nearby")
+ .and_then(|n| n.as_array())
+ .map(|a| {
+ a.iter()
+ .filter_map(|v| v.as_str().and_then(|s| parse_u64(s).ok()))
+ .collect()
+ })
+ .unwrap_or_default();
+ let r = process_export_snapshot(sid, &watches, &nearby)?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
"list_strings" | "search_strings" => {
let path = args
.get("path")
diff --git a/crates/ghidrust-cli/tests/cli_mcp.rs b/crates/ghidrust-cli/tests/cli_mcp.rs
index ccb726f..9a1f5a3 100644
--- a/crates/ghidrust-cli/tests/cli_mcp.rs
+++ b/crates/ghidrust-cli/tests/cli_mcp.rs
@@ -358,6 +358,10 @@ fn mcp_server_info_and_live_tools() {
|| s.contains("\"tool_surface\":4")
|| s.contains("\"toolSurface\":5")
|| s.contains("\"tool_surface\": 5")
- || s.contains("\"tool_surface\":5");
+ || s.contains("\"tool_surface\":5")
+ || s.contains("\"tool_surface\": 6")
+ || s.contains("\"tool_surface\":6")
+ || s.contains("\"tool_surface\": 7")
+ || s.contains("\"tool_surface\":7");
assert!(surface_ok, "expected tool_surface >= 3 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 ac2e750..a4aa639 100644
--- a/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rs
+++ b/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rs
@@ -39,6 +39,22 @@ const EXPECTED_MCP_TOOLS: &[&str] = &[
"process_read",
"process_resolve",
"process_regions",
+ "process_break_set",
+ "process_break_clear",
+ "process_break_list",
+ "process_continue",
+ "process_pause",
+ "process_wait",
+ "process_step_into",
+ "process_step_over",
+ "process_threads",
+ "process_thread_context_get",
+ "process_thread_context_set",
+ "process_stack",
+ "process_scan",
+ "process_watch_expr",
+ "process_vtable_probe",
+ "process_export_snapshot",
"disassemble",
"decode_support",
"decode_query",
diff --git a/crates/ghidrust-core/examples/live_debuggee.rs b/crates/ghidrust-core/examples/live_debuggee.rs
new file mode 100644
index 0000000..ad325ea
--- /dev/null
+++ b/crates/ghidrust-core/examples/live_debuggee.rs
@@ -0,0 +1,23 @@
+//! Tiny long-lived debuggee for Live Process Bridge E2E tests.
+//!
+//! Marker function is never-inlined so agents can resolve a stable symbol/RVA
+//! after loading the PE offline, then set a live BP.
+
+use std::hint::black_box;
+use std::thread;
+use std::time::Duration;
+
+/// Known marker — set a software BP here in tests.
+#[inline(never)]
+#[no_mangle]
+pub extern "C" fn ghidrust_debug_marker() {
+ black_box(0xD3B0_u64);
+}
+
+fn main() {
+ // Spin so debug attach can hit marker repeatedly.
+ for _ in 0..1_000_000 {
+ ghidrust_debug_marker();
+ thread::sleep(Duration::from_millis(5));
+ }
+}
diff --git a/crates/ghidrust-core/src/lib.rs b/crates/ghidrust-core/src/lib.rs
index d0dff25..d1e0086 100644
--- a/crates/ghidrust-core/src/lib.rs
+++ b/crates/ghidrust-core/src/lib.rs
@@ -92,10 +92,17 @@ pub use pe_functions::{
parse_export_code_vas, parse_runtime_functions, runtime_function_containing, RuntimeFunction,
};
pub use process::{
- launch_command_line, process_attach, process_detach, process_is_suspended, process_launch,
- process_list, process_modules, process_read, process_regions, process_resolve, process_resume,
- static_to_live, LaunchRequest, LaunchResult, ModuleInfo, ProcessInfo, ProcessSession,
- ReadResult, RegionInfo, ResolveLive,
+ launch_command_line, live_process_info_json, process_attach, process_attach_opts,
+ 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_watch_expr, static_to_live, AcAdvisory, AttachOpts, BreakKind, BreakpointInfo,
+ ExportSnapshot, LaunchRequest, LaunchResult, ModuleInfo, ProcessError, ProcessErrorCode,
+ ProcessInfo, ProcessSession, ReadResult, RegionInfo, RegisterSet, ResolveLive, RunState,
+ ScanHit, ScanOpts, ScanResult, SessionMode, StackFrame, StopEvent, ThreadInfo, VtableProbeResult,
+ WaitResult, WatchResult,
};
pub use program::{
AddressTableInfo, AddressTableRole, AnalysisState, CallFixupInfo, DiscoveredRange, FidMatch,
diff --git a/crates/ghidrust-core/src/process.rs b/crates/ghidrust-core/src/process.rs
deleted file mode 100644
index a243654..0000000
--- a/crates/ghidrust-core/src/process.rs
+++ /dev/null
@@ -1,846 +0,0 @@
-//! Live Process Bridge (Windows) — hand-rolled Win32 FFI.
-//!
-//! MVP: list / attach / launch(suspended) / resume / modules / read / resolve /
-//! regions. No write, breakpoints, or WaitForDebugEvent agent.
-
-use serde::{Deserialize, Serialize};
-use std::collections::HashMap;
-use std::path::{Path, PathBuf};
-use std::sync::Mutex;
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ProcessInfo {
- pub pid: u32,
- pub name: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub path: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ModuleInfo {
- pub name: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub path: Option<String>,
- pub base: u64,
- pub size: u64,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct RegionInfo {
- pub base: u64,
- pub size: u64,
- pub protect: String,
- pub state: String,
- pub typ: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ProcessSession {
- pub session_id: String,
- pub pid: u32,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ReadResult {
- pub va: u64,
- pub size_requested: usize,
- pub bytes_read: usize,
- pub hex: String,
- pub bytes: Vec<u8>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub error: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub as_u64: Option<Vec<u64>>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub as_f32: Option<Vec<f32>>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ResolveLive {
- pub module: String,
- pub rva: u64,
- pub base: u64,
- pub live_va: u64,
-}
-
-/// Spawn a new process under the Live Process Bridge (CREATE_SUSPENDED).
-#[derive(Debug, Clone)]
-pub struct LaunchRequest {
- pub image: PathBuf,
- pub args: Option<String>,
- pub cwd: Option<PathBuf>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct LaunchResult {
- pub session: ProcessSession,
- pub image: String,
- /// True until `process_resume` (CREATE_SUSPENDED; not a debug break-at-entry).
- pub suspended: bool,
- pub primary_tid: u32,
-}
-
-struct Attached {
- pid: u32,
- #[cfg(windows)]
- handle: isize,
- /// Primary thread from CreateProcess (launch only); closed on detach.
- #[cfg(windows)]
- thread: Option<isize>,
- suspended: bool,
- /// Image path when created via [`process_launch`].
- #[allow(dead_code)]
- launched_image: Option<String>,
-}
-
-static SESSIONS: Mutex<Option<HashMap<String, Attached>>> = Mutex::new(None);
-
-fn with_sessions<F, R>(f: F) -> R
-where
- F: FnOnce(&mut HashMap<String, Attached>) -> R,
-{
- let mut guard = SESSIONS.lock().unwrap_or_else(|e| e.into_inner());
- if guard.is_none() {
- *guard = Some(HashMap::new());
- }
- f(guard.as_mut().unwrap())
-}
-
-#[cfg(windows)]
-mod win {
- use super::*;
- use std::ffi::{OsStr, OsString};
- use std::mem::{size_of, zeroed};
- use std::os::windows::ffi::{OsStrExt, OsStringExt};
- use std::ptr;
-
- type HANDLE = isize;
- type BOOL = i32;
- type DWORD = u32;
- type SizeT = usize;
-
- const PROCESS_QUERY_INFORMATION: DWORD = 0x0400;
- const PROCESS_VM_READ: DWORD = 0x0010;
- const PROCESS_QUERY_LIMITED_INFORMATION: DWORD = 0x1000;
- const TH32CS_SNAPPROCESS: DWORD = 0x0000_0002;
- const TH32CS_SNAPMODULE: DWORD = 0x0000_0008;
- const TH32CS_SNAPMODULE32: DWORD = 0x0000_0010;
- const INVALID_HANDLE_VALUE: HANDLE = -1;
- const MEM_COMMIT: DWORD = 0x1000;
- const MEM_FREE: DWORD = 0x10000;
- const MEM_RESERVE: DWORD = 0x2000;
- const CREATE_SUSPENDED: DWORD = 0x0000_0004;
- const CREATE_UNICODE_ENVIRONMENT: DWORD = 0x0000_0400;
- const MAX_PATH: usize = 260;
-
- #[repr(C)]
- struct STARTUPINFOW {
- cb: DWORD,
- lp_reserved: *mut u16,
- lp_desktop: *mut u16,
- lp_title: *mut u16,
- dw_x: DWORD,
- dw_y: DWORD,
- dw_x_size: DWORD,
- dw_y_size: DWORD,
- dw_x_count_chars: DWORD,
- dw_y_count_chars: DWORD,
- dw_fill_attribute: DWORD,
- dw_flags: DWORD,
- w_show_window: u16,
- cb_reserved2: u16,
- lp_reserved2: *mut u8,
- h_std_input: HANDLE,
- h_std_output: HANDLE,
- h_std_error: HANDLE,
- }
-
- #[repr(C)]
- struct PROCESS_INFORMATION {
- h_process: HANDLE,
- h_thread: HANDLE,
- dw_process_id: DWORD,
- dw_thread_id: DWORD,
- }
-
- #[repr(C)]
- struct PROCESSENTRY32W {
- dw_size: DWORD,
- cnt_usage: DWORD,
- th32_process_id: DWORD,
- th32_default_heap_id: usize,
- th32_module_id: DWORD,
- cnt_threads: DWORD,
- th32_parent_process_id: DWORD,
- pc_pri_class_base: i32,
- dw_flags: DWORD,
- sz_exe_file: [u16; MAX_PATH],
- }
-
- #[repr(C)]
- struct MODULEENTRY32W {
- dw_size: DWORD,
- th32_module_id: DWORD,
- th32_process_id: DWORD,
- glblcnt_usage: DWORD,
- proccnt_usage: DWORD,
- mod_base_addr: *mut u8,
- mod_base_size: DWORD,
- h_module: HANDLE,
- sz_module: [u16; 256],
- sz_exe_path: [u16; MAX_PATH],
- }
-
- #[repr(C)]
- struct MEMORY_BASIC_INFORMATION {
- base_address: *mut u8,
- allocation_base: *mut u8,
- allocation_protect: DWORD,
- region_size: SizeT,
- state: DWORD,
- protect: DWORD,
- typ: DWORD,
- }
-
- #[link(name = "kernel32")]
- extern "system" {
- fn OpenProcess(access: DWORD, inherit: BOOL, pid: DWORD) -> HANDLE;
- fn CloseHandle(h: HANDLE) -> BOOL;
- fn ReadProcessMemory(
- h: HANDLE,
- addr: *const u8,
- buf: *mut u8,
- size: SizeT,
- read: *mut SizeT,
- ) -> BOOL;
- fn VirtualQueryEx(
- h: HANDLE,
- addr: *const u8,
- info: *mut MEMORY_BASIC_INFORMATION,
- len: SizeT,
- ) -> SizeT;
- fn CreateToolhelp32Snapshot(flags: DWORD, pid: DWORD) -> HANDLE;
- fn Process32FirstW(snap: HANDLE, pe: *mut PROCESSENTRY32W) -> BOOL;
- fn Process32NextW(snap: HANDLE, pe: *mut PROCESSENTRY32W) -> BOOL;
- fn Module32FirstW(snap: HANDLE, me: *mut MODULEENTRY32W) -> BOOL;
- fn Module32NextW(snap: HANDLE, me: *mut MODULEENTRY32W) -> BOOL;
- fn QueryFullProcessImageNameW(
- h: HANDLE,
- flags: DWORD,
- buf: *mut u16,
- size: *mut DWORD,
- ) -> BOOL;
- fn CreateProcessW(
- app: *const u16,
- cmdline: *mut u16,
- proc_attr: *const u8,
- thread_attr: *const u8,
- inherit: BOOL,
- flags: DWORD,
- env: *const u8,
- cwd: *const u16,
- si: *const STARTUPINFOW,
- pi: *mut PROCESS_INFORMATION,
- ) -> BOOL;
- fn ResumeThread(h: HANDLE) -> DWORD;
- fn GetLastError() -> DWORD;
- }
-
- fn to_wide_z(s: &str) -> Vec<u16> {
- let mut v: Vec<u16> = OsStr::new(s).encode_wide().collect();
- v.push(0);
- v
- }
-
- /// Build Win32 command line: quoted image path + optional args tail.
- pub fn build_command_line(image: &Path, args: Option<&str>) -> String {
- let img = image.to_string_lossy();
- let quoted = if img.contains(char::is_whitespace) || img.contains('"') {
- format!("\"{}\"", img.replace('"', ""))
- } else {
- img.into_owned()
- };
- match args.map(str::trim).filter(|a| !a.is_empty()) {
- Some(a) => format!("{quoted} {a}"),
- None => quoted,
- }
- }
-
- pub fn launch(
- image: &Path,
- args: Option<&str>,
- cwd: Option<&Path>,
- ) -> Result<(String, HANDLE, HANDLE, u32, u32, String), String> {
- if !image.is_file() {
- return Err(format!(
- "launch image not found or not a file: {}",
- image.display()
- ));
- }
- let image_str = image
- .canonicalize()
- .unwrap_or_else(|_| image.to_path_buf())
- .to_string_lossy()
- .into_owned();
- let cmdline = build_command_line(Path::new(&image_str), args);
- let mut cmdline_w = to_wide_z(&cmdline);
- let cwd_w = cwd.map(|c| to_wide_z(&c.to_string_lossy()));
- let mut si: STARTUPINFOW = unsafe { zeroed() };
- si.cb = size_of::<STARTUPINFOW>() as DWORD;
- let mut pi: PROCESS_INFORMATION = unsafe { zeroed() };
- let flags = CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT;
- let ok = unsafe {
- CreateProcessW(
- ptr::null(),
- cmdline_w.as_mut_ptr(),
- ptr::null(),
- ptr::null(),
- 0,
- flags,
- ptr::null(),
- cwd_w.as_ref().map(|v| v.as_ptr()).unwrap_or(ptr::null()),
- &si,
- &mut pi,
- )
- };
- if ok == 0 {
- let err = unsafe { GetLastError() };
- return Err(format!(
- "CreateProcessW failed (GetLastError={err:#x}) for {cmdline}"
- ));
- }
- let session_id = format!("ps-{}-{}", pi.dw_process_id, super::now_token());
- Ok((
- session_id,
- pi.h_process,
- pi.h_thread,
- pi.dw_process_id,
- pi.dw_thread_id,
- image_str,
- ))
- }
-
- pub fn resume_thread(h: HANDLE) -> Result<(), String> {
- let prev = unsafe { ResumeThread(h) };
- // ResumeThread returns previous suspend count, or u32::MAX on failure.
- if prev == DWORD::MAX {
- let err = unsafe { GetLastError() };
- return Err(format!("ResumeThread failed (GetLastError={err:#x})"));
- }
- Ok(())
- }
-
- fn wide_to_string(w: &[u16]) -> String {
- let len = w.iter().position(|&c| c == 0).unwrap_or(w.len());
- OsString::from_wide(&w[..len])
- .to_string_lossy()
- .into_owned()
- }
-
- pub fn list_processes() -> Result<Vec<ProcessInfo>, String> {
- let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
- if snap == 0 || snap == INVALID_HANDLE_VALUE {
- return Err("CreateToolhelp32Snapshot failed".into());
- }
- let mut out = Vec::new();
- let mut pe: PROCESSENTRY32W = unsafe { zeroed() };
- pe.dw_size = size_of::<PROCESSENTRY32W>() as DWORD;
- let mut ok = unsafe { Process32FirstW(snap, &mut pe) };
- while ok != 0 {
- let name = wide_to_string(&pe.sz_exe_file);
- let pid = pe.th32_process_id;
- let path = open_query_path(pid);
- out.push(ProcessInfo { pid, name, path });
- ok = unsafe { Process32NextW(snap, &mut pe) };
- }
- unsafe {
- CloseHandle(snap);
- }
- out.sort_by(|a, b| {
- a.name
- .to_ascii_lowercase()
- .cmp(&b.name.to_ascii_lowercase())
- });
- Ok(out)
- }
-
- fn open_query_path(pid: u32) -> Option<String> {
- let h = unsafe {
- OpenProcess(
- PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_QUERY_INFORMATION,
- 0,
- pid,
- )
- };
- if h == 0 {
- return None;
- }
- let mut buf = [0u16; 1024];
- let mut size = buf.len() as DWORD;
- let ok = unsafe { QueryFullProcessImageNameW(h, 0, buf.as_mut_ptr(), &mut size) };
- unsafe {
- CloseHandle(h);
- }
- if ok == 0 {
- return None;
- }
- Some(wide_to_string(&buf[..size as usize]))
- }
-
- pub fn attach(pid: u32) -> Result<(String, HANDLE), String> {
- let access =
- PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_QUERY_LIMITED_INFORMATION;
- let h = unsafe { OpenProcess(access, 0, pid) };
- if h == 0 {
- return Err(format!(
- "OpenProcess({pid}) failed — access denied, elevated rights, or process exited"
- ));
- }
- let session_id = format!("ps-{pid}-{}", super::now_token());
- Ok((session_id, h))
- }
-
- pub fn modules(_handle: HANDLE, pid: u32) -> Result<Vec<ModuleInfo>, String> {
- let flags = TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32;
- let snap = unsafe { CreateToolhelp32Snapshot(flags, pid) };
- if snap == 0 || snap == INVALID_HANDLE_VALUE {
- return Err(
- "Module snapshot failed (32-bit tool vs 64-bit process, or access denied)".into(),
- );
- }
- let mut out = Vec::new();
- let mut me: MODULEENTRY32W = unsafe { zeroed() };
- me.dw_size = size_of::<MODULEENTRY32W>() as DWORD;
- let mut ok = unsafe { Module32FirstW(snap, &mut me) };
- while ok != 0 {
- let name = wide_to_string(&me.sz_module);
- let path = {
- let p = wide_to_string(&me.sz_exe_path);
- if p.is_empty() {
- None
- } else {
- Some(p)
- }
- };
- out.push(ModuleInfo {
- name,
- path,
- base: me.mod_base_addr as u64,
- size: me.mod_base_size as u64,
- });
- ok = unsafe { Module32NextW(snap, &mut me) };
- }
- unsafe {
- CloseHandle(snap);
- }
- Ok(out)
- }
-
- pub fn read_mem(handle: HANDLE, va: u64, size: usize) -> ReadResult {
- let size = size.min(1024 * 1024); // 1 MiB cap
- let mut buf = vec![0u8; size];
- let mut read: SizeT = 0;
- let ok = unsafe {
- ReadProcessMemory(handle, va as *const u8, buf.as_mut_ptr(), size, &mut read)
- };
- if ok == 0 {
- return ReadResult {
- va,
- size_requested: size,
- bytes_read: 0,
- hex: String::new(),
- bytes: vec![],
- error: Some("ReadProcessMemory failed (access denied or unmapped)".into()),
- as_u64: None,
- as_f32: None,
- };
- }
- buf.truncate(read);
- let hex: String = buf
- .iter()
- .map(|b| format!("{b:02x}"))
- .collect::<Vec<_>>()
- .join(" ");
- let as_u64 = if buf.len() >= 8 {
- Some(
- buf.chunks_exact(8)
- .map(|c| u64::from_le_bytes(c.try_into().unwrap()))
- .collect(),
- )
- } else {
- None
- };
- let as_f32 = if buf.len() >= 4 {
- Some(
- buf.chunks_exact(4)
- .map(|c| f32::from_le_bytes(c.try_into().unwrap()))
- .collect(),
- )
- } else {
- None
- };
- let error = if read < size {
- Some(format!("short_read: got {read} of {size}"))
- } else {
- None
- };
- ReadResult {
- va,
- size_requested: size,
- bytes_read: read,
- hex,
- bytes: buf,
- error,
- as_u64,
- as_f32,
- }
- }
-
- pub fn regions(handle: HANDLE, max: usize) -> Result<Vec<RegionInfo>, String> {
- let mut out = Vec::new();
- let mut addr: u64 = 0;
- while out.len() < max {
- let mut info: MEMORY_BASIC_INFORMATION = unsafe { zeroed() };
- let n = unsafe {
- VirtualQueryEx(
- handle,
- addr as *const u8,
- &mut info,
- size_of::<MEMORY_BASIC_INFORMATION>(),
- )
- };
- if n == 0 {
- break;
- }
- let base = info.base_address as u64;
- let size = info.region_size as u64;
- if info.state != MEM_FREE {
- out.push(RegionInfo {
- base,
- size,
- protect: protect_str(info.protect),
- state: state_str(info.state),
- typ: type_str(info.typ),
- });
- }
- let next = base.saturating_add(size);
- if next <= addr {
- break;
- }
- addr = next;
- }
- Ok(out)
- }
-
- fn protect_str(p: DWORD) -> String {
- format!("{p:#x}")
- }
- fn state_str(s: DWORD) -> String {
- match s {
- MEM_COMMIT => "commit".into(),
- MEM_RESERVE => "reserve".into(),
- MEM_FREE => "free".into(),
- _ => format!("{s:#x}"),
- }
- }
- fn type_str(t: DWORD) -> String {
- format!("{t:#x}")
- }
-
- pub fn close(h: HANDLE) {
- unsafe {
- let _ = CloseHandle(h);
- }
- }
-
- // silence unused import warning on ptr
- #[allow(dead_code)]
- fn _touch() {
- let _ = ptr::null::<u8>();
- }
-}
-
-fn now_token() -> u64 {
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_millis() as u64)
- .unwrap_or(0)
-}
-
-/// List processes (Windows). Other platforms return a clear error.
-pub fn process_list() -> Result<Vec<ProcessInfo>, String> {
- #[cfg(windows)]
- {
- win::list_processes()
- }
- #[cfg(not(windows))]
- {
- Err("Live Process Bridge is Windows-only in this MVP".into())
- }
-}
-
-pub fn process_attach(pid: u32) -> Result<ProcessSession, String> {
- #[cfg(windows)]
- {
- let (session_id, handle) = win::attach(pid)?;
- with_sessions(|m| {
- m.insert(
- session_id.clone(),
- Attached {
- pid,
- handle,
- thread: None,
- suspended: false,
- launched_image: None,
- },
- );
- });
- Ok(ProcessSession { session_id, pid })
- }
- #[cfg(not(windows))]
- {
- let _ = pid;
- Err("Live Process Bridge is Windows-only in this MVP".into())
- }
-}
-
-/// Launch `image` with CREATE_SUSPENDED, keep a live read session, leave primary thread frozen.
-///
-/// Not a Windows-debug break-at-entry — call [`process_resume`] to let the process run.
-/// Fails if another session is already open (one-session MVP).
-pub fn process_launch(req: &LaunchRequest) -> Result<LaunchResult, String> {
- #[cfg(windows)]
- {
- with_sessions(|m| -> Result<(), String> {
- if !m.is_empty() {
- return Err(
- "detach the current live session before launching a new process".into(),
- );
- }
- Ok(())
- })?;
- let (session_id, h_proc, h_thread, pid, tid, image_str) =
- win::launch(&req.image, req.args.as_deref(), req.cwd.as_deref())?;
- with_sessions(|m| {
- m.insert(
- session_id.clone(),
- Attached {
- pid,
- handle: h_proc,
- thread: Some(h_thread),
- suspended: true,
- launched_image: Some(image_str.clone()),
- },
- );
- });
- Ok(LaunchResult {
- session: ProcessSession { session_id, pid },
- image: image_str,
- suspended: true,
- primary_tid: tid,
- })
- }
- #[cfg(not(windows))]
- {
- let _ = req;
- Err("Live Process Bridge is Windows-only in this MVP".into())
- }
-}
-
-/// Resume the primary thread of a launched (CREATE_SUSPENDED) session.
-pub fn process_resume(session_id: &str) -> Result<(), String> {
- #[cfg(windows)]
- {
- with_sessions(|m| {
- let a = m
- .get_mut(session_id)
- .ok_or_else(|| format!("unknown or stale session: {session_id}"))?;
- if !a.suspended {
- return Err("session is not suspended (already running or attach-only)".into());
- }
- let h = a
- .thread
- .ok_or_else(|| "session has no primary thread handle to resume".to_string())?;
- win::resume_thread(h)?;
- a.suspended = false;
- Ok(())
- })
- }
- #[cfg(not(windows))]
- {
- let _ = session_id;
- Err("Live Process Bridge is Windows-only in this MVP".into())
- }
-}
-
-/// Whether the session was launched suspended and has not been resumed yet.
-pub fn process_is_suspended(session_id: &str) -> Result<bool, String> {
- with_sessions(|m| {
- m.get(session_id)
- .map(|a| a.suspended)
- .ok_or_else(|| format!("unknown or stale session: {session_id}"))
- })
-}
-
-/// Build the Win32 command line used by [`process_launch`] (also for tests).
-pub fn launch_command_line(image: &Path, args: Option<&str>) -> String {
- #[cfg(windows)]
- {
- win::build_command_line(image, args)
- }
- #[cfg(not(windows))]
- {
- let img = image.display().to_string();
- match args.map(str::trim).filter(|a| !a.is_empty()) {
- Some(a) => format!("\"{img}\" {a}"),
- None => img,
- }
- }
-}
-
-pub fn process_detach(session_id: &str) -> Result<(), String> {
- #[cfg(windows)]
- {
- with_sessions(|m| {
- if let Some(a) = m.remove(session_id) {
- // Avoid leaving a CREATE_SUSPENDED orphan frozen forever.
- if a.suspended {
- if let Some(th) = a.thread {
- let _ = win::resume_thread(th);
- }
- }
- if let Some(th) = a.thread {
- win::close(th);
- }
- win::close(a.handle);
- Ok(())
- } else {
- Err(format!("unknown session: {session_id}"))
- }
- })
- }
- #[cfg(not(windows))]
- {
- let _ = session_id;
- Err("Live Process Bridge is Windows-only in this MVP".into())
- }
-}
-
-fn session_handle(session_id: &str) -> Result<(u32, isize), String> {
- #[cfg(windows)]
- {
- with_sessions(|m| {
- m.get(session_id)
- .map(|a| (a.pid, a.handle))
- .ok_or_else(|| format!("unknown or stale session: {session_id}"))
- })
- }
- #[cfg(not(windows))]
- {
- let _ = session_id;
- Err("Live Process Bridge is Windows-only in this MVP".into())
- }
-}
-
-pub fn process_modules(session_id: &str) -> Result<Vec<ModuleInfo>, String> {
- #[cfg(windows)]
- {
- let (pid, handle) = session_handle(session_id)?;
- win::modules(handle, pid)
- }
- #[cfg(not(windows))]
- {
- let _ = session_id;
- Err("Live Process Bridge is Windows-only in this MVP".into())
- }
-}
-
-pub fn process_read(session_id: &str, va: u64, size: usize) -> Result<ReadResult, String> {
- #[cfg(windows)]
- {
- let (_pid, handle) = session_handle(session_id)?;
- Ok(win::read_mem(handle, va, size))
- }
- #[cfg(not(windows))]
- {
- let _ = (session_id, va, size);
- Err("Live Process Bridge is Windows-only in this MVP".into())
- }
-}
-
-pub fn process_regions(session_id: &str, max: usize) -> Result<Vec<RegionInfo>, String> {
- #[cfg(windows)]
- {
- let (_pid, handle) = session_handle(session_id)?;
- win::regions(handle, max.max(1))
- }
- #[cfg(not(windows))]
- {
- let _ = (session_id, max);
- Err("Live Process Bridge is Windows-only in this MVP".into())
- }
-}
-
-/// Resolve static RVA to live VA via module base (`base + rva`).
-pub fn process_resolve(session_id: &str, module: &str, rva: u64) -> Result<ResolveLive, String> {
- let mods = process_modules(session_id)?;
- let m = mods
- .iter()
- .find(|m| {
- m.name.eq_ignore_ascii_case(module)
- || m.path
- .as_deref()
- .map(|p| {
- p.to_ascii_lowercase()
- .ends_with(&module.to_ascii_lowercase())
- })
- .unwrap_or(false)
- })
- .ok_or_else(|| format!("module not found: {module}"))?;
- Ok(ResolveLive {
- module: m.name.clone(),
- rva,
- base: m.base,
- live_va: m.base.wrapping_add(rva),
- })
-}
-
-/// Alias: static file RVA → live VA.
-pub fn static_to_live(session_id: &str, module: &str, rva: u64) -> Result<ResolveLive, String> {
- process_resolve(session_id, module, rva)
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn launch_command_line_quotes_paths_with_spaces() {
- let s = launch_command_line(Path::new(r"C:\Program Files\app.exe"), Some("-flag"));
- assert!(s.starts_with('"'), "{s}");
- assert!(s.contains("app.exe"), "{s}");
- assert!(s.ends_with("-flag"), "{s}");
- }
-
- #[test]
- fn launch_command_line_plain_path_no_extra_quotes() {
- let s = launch_command_line(Path::new(r"C:\tools\app.exe"), None);
- assert_eq!(s, r"C:\tools\app.exe");
- }
-
- #[test]
- fn launch_fails_when_image_missing() {
- let err = process_launch(&LaunchRequest {
- image: PathBuf::from("Z:\\definitely\\missing\\ghidrust_launch_test.exe"),
- args: None,
- cwd: None,
- })
- .unwrap_err();
- assert!(
- err.contains("not found")
- || err.contains("Windows-only")
- || err.contains("CreateProcess"),
- "{err}"
- );
- }
-}
diff --git a/crates/ghidrust-core/src/process/ac_advisory.rs b/crates/ghidrust-core/src/process/ac_advisory.rs
new file mode 100644
index 0000000..55acbe3
--- /dev/null
+++ b/crates/ghidrust-core/src/process/ac_advisory.rs
@@ -0,0 +1,100 @@
+//! Anti-cheat / protection advisory (name heuristics only — no stealth).
+
+use serde::{Deserialize, Serialize};
+
+/// Known AC / protection module basenames (lowercase). Advisory only.
+const AC_MODULE_NAMES: &[&str] = &[
+ "easyanticheat",
+ "easyanticheat_eos",
+ "eac_launcher",
+ "beclient",
+ "beclient_x64",
+ "beservice",
+ "bedaisy",
+ "battleye",
+ "vgc",
+ "vgk",
+ "vanguard",
+ "faceit",
+ "faceitclient",
+ "faceitservice",
+ "mhyprot",
+ "mhyprot2",
+ "nprotect",
+ "npggnt",
+ "xigncode",
+ "xhunter",
+ "gameguard",
+ "equ8",
+ "ricochet",
+ "sguard",
+];
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct AcAdvisory {
+ /// True when one or more known AC-related modules were seen.
+ pub suspected_protection: bool,
+ /// Matched module basenames (lowercase).
+ pub matched_modules: Vec<String>,
+ /// Whether SeDebugPrivilege was enabled for this session.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub debug_privilege: Option<bool>,
+ /// Human-readable advisory.
+ pub message: String,
+}
+
+/// Scan module names for advisory matches. Never blocks attach.
+pub fn scan_modules_for_ac(module_names: &[impl AsRef<str>]) -> AcAdvisory {
+ let mut matched = Vec::new();
+ for name in module_names {
+ let base = name
+ .as_ref()
+ .rsplit(['\\', '/'])
+ .next()
+ .unwrap_or(name.as_ref())
+ .to_ascii_lowercase();
+ let stem = base.trim_end_matches(".dll").trim_end_matches(".sys");
+ for ac in AC_MODULE_NAMES {
+ if stem == *ac || stem.starts_with(&format!("{ac}_")) || stem.contains(ac) {
+ if !matched.iter().any(|m: &String| m == &base) {
+ matched.push(base.clone());
+ }
+ break;
+ }
+ }
+ }
+ let suspected = !matched.is_empty();
+ let message = if suspected {
+ format!(
+ "advisory: process modules look like anti-cheat/protection ({}); debug attach may fail with access_denied — no stealth features",
+ matched.join(", ")
+ )
+ } else {
+ "no known anti-cheat module names detected (advisory only)".into()
+ };
+ AcAdvisory {
+ suspected_protection: suspected,
+ matched_modules: matched,
+ debug_privilege: None,
+ message,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn detects_eac_name() {
+ let a = scan_modules_for_ac(&["C:\\Games\\EasyAntiCheat_EOS.dll", "game.exe"]);
+ assert!(a.suspected_protection);
+ assert!(!a.matched_modules.is_empty());
+ }
+
+ #[test]
+ fn clean_process_no_match() {
+ let a = scan_modules_for_ac(&["ntdll.dll", "kernel32.dll", "app.exe"]);
+ assert!(!a.suspected_protection);
+ assert!(a.matched_modules.is_empty());
+ }
+}
diff --git a/crates/ghidrust-core/src/process/backend.rs b/crates/ghidrust-core/src/process/backend.rs
new file mode 100644
index 0000000..3ab9f41
--- /dev/null
+++ b/crates/ghidrust-core/src/process/backend.rs
@@ -0,0 +1,13 @@
+//! Platform backend trait (Windows first; Linux/ptrace later).
+
+use super::error::ProcessError;
+use super::types::{ModuleInfo, ProcessInfo, ReadResult, RegionInfo};
+
+/// Thin trait so a future ptrace backend can plug in without rewriting agents.
+#[allow(dead_code)]
+pub trait ProcessBackend: Send {
+ fn list_processes(&self) -> Result<Vec<ProcessInfo>, ProcessError>;
+ fn read(&self, va: u64, size: usize) -> ReadResult;
+ fn modules(&self, pid: u32) -> Result<Vec<ModuleInfo>, ProcessError>;
+ fn regions(&self, max: usize) -> Result<Vec<RegionInfo>, ProcessError>;
+}
diff --git a/crates/ghidrust-core/src/process/discovery.rs b/crates/ghidrust-core/src/process/discovery.rs
new file mode 100644
index 0000000..800fb92
--- /dev/null
+++ b/crates/ghidrust-core/src/process/discovery.rs
@@ -0,0 +1,525 @@
+//! Live data discovery: scan, watch_expr, vtable_probe (bytes ≠ types).
+
+use super::error::{ProcessError, ProcessErrorCode};
+use super::types::{
+ ModuleInfo, RegionInfo, ScanHit, ScanResult, VtableProbeResult, VtableSlot, WatchResult,
+ WatchStep,
+};
+use super::win_observe::{self, HANDLE};
+
+/// AOB pattern: hex bytes with `??` wildcards, space-separated.
+pub fn parse_aob(pattern: &str) -> Result<Vec<Option<u8>>, ProcessError> {
+ let mut out = Vec::new();
+ for tok in pattern.split_whitespace() {
+ if tok == "??" || tok == "?" {
+ out.push(None);
+ } else {
+ let b = u8::from_str_radix(tok, 16).map_err(|_| {
+ ProcessError::new(
+ ProcessErrorCode::InvalidArgument,
+ format!("bad AOB token '{tok}'"),
+ )
+ })?;
+ out.push(Some(b));
+ }
+ }
+ if out.is_empty() {
+ return Err(ProcessError::new(
+ ProcessErrorCode::InvalidArgument,
+ "empty AOB pattern",
+ ));
+ }
+ Ok(out)
+}
+
+pub fn find_aob(hay: &[u8], pat: &[Option<u8>]) -> Vec<usize> {
+ let mut hits = Vec::new();
+ if pat.is_empty() || hay.len() < pat.len() {
+ return hits;
+ }
+ 'outer: for i in 0..=(hay.len() - pat.len()) {
+ for (j, p) in pat.iter().enumerate() {
+ if let Some(b) = p {
+ if hay[i + j] != *b {
+ continue 'outer;
+ }
+ }
+ }
+ hits.push(i);
+ }
+ hits
+}
+
+fn find_module<'a>(mods: &'a [ModuleInfo], va: u64) -> Option<&'a ModuleInfo> {
+ mods.iter().find(|m| va >= m.base && va < m.base.wrapping_add(m.size))
+}
+
+pub struct ScanOpts {
+ pub aob: Option<String>,
+ pub string: Option<String>,
+ pub utf16: bool,
+ pub module_only: Option<String>,
+ pub committed_private: bool,
+ pub executable_only: bool,
+ pub data_only: bool,
+ pub max_hits: usize,
+ pub max_bytes: u64,
+ /// If set, rescan after this many ms and report addresses whose bytes changed.
+ pub diff_wait_ms: Option<u64>,
+}
+
+impl Default for ScanOpts {
+ fn default() -> Self {
+ Self {
+ aob: None,
+ string: None,
+ utf16: false,
+ module_only: None,
+ committed_private: true,
+ executable_only: false,
+ data_only: false,
+ max_hits: 256,
+ max_bytes: 64 * 1024 * 1024,
+ diff_wait_ms: None,
+ }
+ }
+}
+
+pub fn process_scan(
+ handle: HANDLE,
+ pid: u32,
+ opts: &ScanOpts,
+) -> Result<ScanResult, ProcessError> {
+ let mods = win_observe::modules(handle, pid)?;
+ let regions = win_observe::regions(handle, 4096)?;
+ let aob = opts
+ .aob
+ .as_deref()
+ .map(parse_aob)
+ .transpose()?;
+ let string_bytes = opts.string.as_ref().map(|s| {
+ if opts.utf16 {
+ s.encode_utf16()
+ .flat_map(|c| c.to_le_bytes())
+ .collect::<Vec<u8>>()
+ } else {
+ s.as_bytes().to_vec()
+ }
+ });
+
+ let mut hits = Vec::new();
+ let mut bytes_scanned = 0u64;
+ let mut regions_scanned = 0usize;
+ let max_hits = opts.max_hits.clamp(1, 10_000);
+
+ let filtered: Vec<&RegionInfo> = regions
+ .iter()
+ .filter(|r| r.state == "commit")
+ .filter(|r| {
+ if let Some(mod_name) = &opts.module_only {
+ find_module(&mods, r.base)
+ .map(|m| {
+ m.name.eq_ignore_ascii_case(mod_name)
+ || m.path
+ .as_deref()
+ .map(|p| p.to_ascii_lowercase().ends_with(&mod_name.to_ascii_lowercase()))
+ .unwrap_or(false)
+ })
+ .unwrap_or(false)
+ } else {
+ true
+ }
+ })
+ .filter(|r| {
+ // protect is hex string; PAGE_EXECUTE* typically 0x10..0x80 range bits
+ let p = u32::from_str_radix(r.protect.trim_start_matches("0x"), 16).unwrap_or(0);
+ let exec = (p & 0xF0) != 0; // rough: execute bits in high nibble of low byte
+ if opts.executable_only && !exec {
+ return false;
+ }
+ if opts.data_only && exec {
+ return false;
+ }
+ true
+ })
+ .collect();
+
+ for r in filtered {
+ if bytes_scanned >= opts.max_bytes || hits.len() >= max_hits {
+ break;
+ }
+ let chunk = r.size.min(4 * 1024 * 1024) as usize;
+ let data = win_observe::read_mem(handle, r.base, chunk);
+ if data.bytes_read == 0 {
+ continue;
+ }
+ regions_scanned += 1;
+ bytes_scanned += data.bytes_read as u64;
+
+ let mut offsets: Vec<usize> = Vec::new();
+ if let Some(ref pat) = aob {
+ offsets.extend(find_aob(&data.bytes, pat));
+ }
+ if let Some(ref sb) = string_bytes {
+ let pat: Vec<Option<u8>> = sb.iter().map(|b| Some(*b)).collect();
+ offsets.extend(find_aob(&data.bytes, &pat));
+ }
+ if aob.is_none() && string_bytes.is_none() {
+ continue;
+ }
+ offsets.sort_unstable();
+ offsets.dedup();
+ for off in offsets {
+ if hits.len() >= max_hits {
+ break;
+ }
+ let va = r.base.wrapping_add(off as u64);
+ let m = find_module(&mods, va);
+ let preview = win_observe::read_mem(handle, va, 16);
+ hits.push(ScanHit {
+ va,
+ module: m.map(|x| x.name.clone()),
+ rva: m.map(|x| va.wrapping_sub(x.base)),
+ preview_hex: if preview.bytes_read > 0 {
+ Some(preview.hex)
+ } else {
+ None
+ },
+ });
+ }
+ }
+
+ let mut diff_changed = None;
+ if let Some(ms) = opts.diff_wait_ms {
+ std::thread::sleep(std::time::Duration::from_millis(ms.min(30_000)));
+ let mut changed = Vec::new();
+ for h in &hits {
+ let before = win_observe::read_mem(handle, h.va, 16);
+ // re-read is "after"; we need before stored — store preview from first scan
+ let after = win_observe::read_mem(handle, h.va, 16);
+ // For true diff we should have stored first bytes; use a second full pattern scan
+ // on hit addresses only: compare to preview_hex
+ if let Some(ref prev) = h.preview_hex {
+ if after.hex != *prev {
+ changed.push(h.va);
+ }
+ } else if before.hex != after.hex {
+ changed.push(h.va);
+ }
+ }
+ // Also re-scan same patterns for new hits that changed? Keep simple: changed among hits.
+ let _ = before_placeholder();
+ diff_changed = Some(changed);
+ }
+
+ let truncated = hits.len() >= max_hits || bytes_scanned >= opts.max_bytes;
+ Ok(ScanResult {
+ hits,
+ truncated,
+ regions_scanned,
+ bytes_scanned,
+ diff_changed,
+ })
+}
+
+fn before_placeholder() {}
+
+/// Watch DSL:
+/// - `0xVA` or `VA` — read u64
+/// - `module+rva` e.g. `game.exe+0x1234`
+/// - chain: `0xVA->*+0x10->*+0x8` (follow pointer, add offset)
+/// - `u32@0xVA` / `u64@…` / `f32@…` / `f64@…`
+pub fn eval_watch_expr(
+ handle: HANDLE,
+ pid: u32,
+ expr: &str,
+ want_matrix_heuristic: bool,
+) -> Result<WatchResult, ProcessError> {
+ let mods = win_observe::modules(handle, pid).unwrap_or_default();
+ let mut steps = Vec::new();
+ let mut parts: Vec<&str> = expr.split("->").map(str::trim).filter(|s| !s.is_empty()).collect();
+ if parts.is_empty() {
+ return Err(ProcessError::new(
+ ProcessErrorCode::InvalidArgument,
+ "empty watch expression",
+ ));
+ }
+
+ // Optional type prefix on first token: u64@addr
+ let mut read_size: usize = 8;
+ let mut as_float = false;
+ let mut as_f64 = false;
+ let first = parts[0];
+ let (first_addr_tok, typed) = if let Some(rest) = first.strip_prefix("u64@") {
+ read_size = 8;
+ (rest, true)
+ } else if let Some(rest) = first.strip_prefix("u32@") {
+ read_size = 4;
+ (rest, true)
+ } else if let Some(rest) = first.strip_prefix("f32@") {
+ read_size = 4;
+ as_float = true;
+ (rest, true)
+ } else if let Some(rest) = first.strip_prefix("f64@") {
+ read_size = 8;
+ as_f64 = true;
+ (rest, true)
+ } else {
+ (first, false)
+ };
+ if typed {
+ parts[0] = first_addr_tok;
+ }
+
+ let mut va = resolve_token(parts[0], &mods, None)?;
+ steps.push(WatchStep {
+ op: format!("base {}", parts[0]),
+ va,
+ value_u64: None,
+ });
+
+ for (i, part) in parts.iter().enumerate().skip(1) {
+ // Read pointer at va
+ let rr = win_observe::read_mem(handle, va, 8);
+ if rr.bytes_read < 8 {
+ return Ok(WatchResult {
+ expr: expr.into(),
+ steps,
+ final_va: Some(va),
+ value_hex: None,
+ as_u64: None,
+ as_f32: None,
+ as_f64: None,
+ heuristic_float4x4: None,
+ heuristic: false,
+ error: Some(format!("pointer read failed at {va:#x}")),
+ });
+ }
+ let ptr = u64::from_le_bytes(rr.bytes[0..8].try_into().unwrap());
+ steps.push(WatchStep {
+ op: format!("deref[{}]", i - 1),
+ va,
+ value_u64: Some(ptr),
+ });
+ if ptr == 0 || ptr < 0x10000 {
+ return Ok(WatchResult {
+ expr: expr.into(),
+ steps,
+ final_va: Some(va),
+ value_hex: None,
+ as_u64: Some(ptr),
+ as_f32: None,
+ as_f64: None,
+ heuristic_float4x4: None,
+ heuristic: false,
+ error: Some("null or low pointer in chain".into()),
+ });
+ }
+ let off = parse_offset_token(part)?;
+ va = ptr.wrapping_add(off);
+ steps.push(WatchStep {
+ op: format!("+{off:#x}"),
+ va,
+ value_u64: None,
+ });
+ }
+
+ let rr = win_observe::read_mem(handle, va, read_size.max(64));
+ if rr.bytes_read < read_size {
+ return Ok(WatchResult {
+ expr: expr.into(),
+ steps,
+ final_va: Some(va),
+ value_hex: Some(rr.hex),
+ as_u64: None,
+ as_f32: None,
+ as_f64: None,
+ heuristic_float4x4: None,
+ heuristic: false,
+ error: Some(format!("short read at {va:#x}")),
+ });
+ }
+
+ let as_u64 = if read_size >= 8 {
+ Some(u64::from_le_bytes(rr.bytes[0..8].try_into().unwrap()))
+ } else if read_size >= 4 {
+ Some(u32::from_le_bytes(rr.bytes[0..4].try_into().unwrap()) as u64)
+ } else {
+ None
+ };
+ let as_f32 = if as_float && rr.bytes_read >= 4 {
+ Some(f32::from_le_bytes(rr.bytes[0..4].try_into().unwrap()))
+ } else {
+ None
+ };
+ let as_f64 = if as_f64 && rr.bytes_read >= 8 {
+ Some(f64::from_le_bytes(rr.bytes[0..8].try_into().unwrap()))
+ } else {
+ None
+ };
+
+ let mut heuristic = false;
+ let mut matrix = None;
+ if want_matrix_heuristic && rr.bytes_read >= 64 {
+ let mut floats = Vec::with_capacity(16);
+ for c in rr.bytes[..64].chunks_exact(4) {
+ floats.push(f32::from_le_bytes(c.try_into().unwrap()));
+ }
+ // Heuristic: last row ~ [0,0,0,1] or many finite values
+ if floats.iter().all(|f| f.is_finite()) {
+ heuristic = true;
+ matrix = Some(floats);
+ }
+ }
+
+ Ok(WatchResult {
+ expr: expr.into(),
+ steps,
+ final_va: Some(va),
+ value_hex: Some(rr.hex),
+ as_u64,
+ as_f32,
+ as_f64,
+ heuristic_float4x4: matrix,
+ heuristic,
+ error: None,
+ })
+}
+
+fn parse_offset_token(tok: &str) -> Result<u64, ProcessError> {
+ let t = tok.trim().trim_start_matches('+');
+ if let Some(rest) = t.strip_prefix("*+") {
+ return parse_u64_flexible(rest);
+ }
+ if t == "*" {
+ // bare * means +0 after deref (already deref'd)
+ return Ok(0);
+ }
+ parse_u64_flexible(t.trim_start_matches('+'))
+}
+
+fn resolve_token(tok: &str, mods: &[ModuleInfo], _base: Option<u64>) -> Result<u64, ProcessError> {
+ let tok = tok.trim();
+ if let Some((mod_name, rva_s)) = tok.split_once('+') {
+ if !mod_name.chars().all(|c| c.is_ascii_hexdigit() || c == 'x' || c == 'X')
+ || mod_name.contains('.')
+ || mod_name.chars().any(|c| c.is_alphabetic() && c != 'x' && c != 'X')
+ {
+ // module+rva form when left side looks like a name
+ if mod_name.chars().any(|c| c.is_alphabetic()) {
+ let rva = parse_u64_flexible(rva_s)?;
+ let m = mods
+ .iter()
+ .find(|m| {
+ m.name.eq_ignore_ascii_case(mod_name)
+ || m.path
+ .as_deref()
+ .map(|p| {
+ p.to_ascii_lowercase()
+ .ends_with(&mod_name.to_ascii_lowercase())
+ })
+ .unwrap_or(false)
+ })
+ .ok_or_else(|| {
+ ProcessError::new(
+ ProcessErrorCode::ModuleNotFound,
+ format!("module not found: {mod_name}"),
+ )
+ })?;
+ return Ok(m.base.wrapping_add(rva));
+ }
+ }
+ }
+ // bare hex VA
+ if tok.contains('+') {
+ // numeric base+off
+ let (a, b) = tok.split_once('+').unwrap();
+ let base = parse_u64_flexible(a)?;
+ let off = parse_u64_flexible(b)?;
+ return Ok(base.wrapping_add(off));
+ }
+ parse_u64_flexible(tok)
+}
+
+fn parse_u64_flexible(s: &str) -> Result<u64, ProcessError> {
+ let s = s.trim().trim_start_matches('+');
+ let (s, radix) = if let Some(h) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
+ (h, 16)
+ } else if s.chars().any(|c| matches!(c, 'a'..='f' | 'A'..='F')) {
+ (s, 16)
+ } else {
+ (s, 10)
+ };
+ u64::from_str_radix(s, radix).map_err(|_| {
+ ProcessError::new(
+ ProcessErrorCode::InvalidArgument,
+ format!("bad integer '{s}'"),
+ )
+ })
+}
+
+pub fn vtable_probe(
+ handle: HANDLE,
+ pid: u32,
+ object_va: u64,
+ max_slots: usize,
+) -> Result<VtableProbeResult, ProcessError> {
+ let mods = win_observe::modules(handle, pid)?;
+ let vt_read = win_observe::read_mem(handle, object_va, 8);
+ if vt_read.bytes_read < 8 {
+ return Err(ProcessError::new(
+ ProcessErrorCode::AccessDenied,
+ format!("cannot read object* at {object_va:#x}"),
+ ));
+ }
+ let vtable_va = u64::from_le_bytes(vt_read.bytes[0..8].try_into().unwrap());
+ let vt_mod = find_module(&mods, vtable_va);
+ // Heuristic: vtable often in non-exec module image (.rdata) — we check it's inside a module.
+ let in_module_rdata = vt_mod.is_some();
+ let max_slots = max_slots.clamp(1, 256);
+ let slot_bytes = win_observe::read_mem(handle, vtable_va, max_slots * 8);
+ let mut slots = Vec::new();
+ for i in 0..max_slots {
+ let off = i * 8;
+ if off + 8 > slot_bytes.bytes_read {
+ break;
+ }
+ let target = u64::from_le_bytes(slot_bytes.bytes[off..off + 8].try_into().unwrap());
+ if target == 0 {
+ break;
+ }
+ let tm = find_module(&mods, target);
+ slots.push(VtableSlot {
+ index: i as u32,
+ target_va: target,
+ module: tm.map(|m| m.name.clone()),
+ rva: tm.map(|m| target.wrapping_sub(m.base)),
+ });
+ }
+ Ok(VtableProbeResult {
+ object_va,
+ vtable_va,
+ in_module_rdata,
+ module: vt_mod.map(|m| m.name.clone()),
+ slots,
+ rtti_hint: None,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn aob_wildcard_match() {
+ let pat = parse_aob("48 8b ?? 90").unwrap();
+ let hay = [0x48, 0x8b, 0x05, 0x90, 0x00];
+ assert_eq!(find_aob(&hay, &pat), vec![0]);
+ }
+
+ #[test]
+ fn parse_offset_star_plus() {
+ assert_eq!(parse_offset_token("*+0x10").unwrap(), 0x10);
+ assert_eq!(parse_offset_token("+8").unwrap(), 8);
+ }
+}
diff --git a/crates/ghidrust-core/src/process/error.rs b/crates/ghidrust-core/src/process/error.rs
new file mode 100644
index 0000000..49ccdb5
--- /dev/null
+++ b/crates/ghidrust-core/src/process/error.rs
@@ -0,0 +1,155 @@
+//! Structured live-process errors — never silent empty failures.
+
+use serde::{Deserialize, Serialize};
+use std::fmt;
+
+/// Machine-stable error code for agents and GUI.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ProcessErrorCode {
+ AccessDenied,
+ ProtectedProcess,
+ Wow64Rejected,
+ InvalidState,
+ WaitTimeout,
+ BpRestoreFailed,
+ CapabilityMissing,
+ ProcessExited,
+ UnknownSession,
+ ModuleNotFound,
+ NotFound,
+ InstrumentNotEnabled,
+ InvalidArgument,
+ PlatformUnsupported,
+ Internal,
+}
+
+impl ProcessErrorCode {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::AccessDenied => "access_denied",
+ Self::ProtectedProcess => "protected_process",
+ Self::Wow64Rejected => "wow64_rejected",
+ Self::InvalidState => "invalid_state",
+ Self::WaitTimeout => "wait_timeout",
+ Self::BpRestoreFailed => "bp_restore_failed",
+ Self::CapabilityMissing => "capability_missing",
+ Self::ProcessExited => "process_exited",
+ Self::UnknownSession => "unknown_session",
+ Self::ModuleNotFound => "module_not_found",
+ Self::NotFound => "not_found",
+ Self::InstrumentNotEnabled => "instrument_not_enabled",
+ Self::InvalidArgument => "invalid_argument",
+ Self::PlatformUnsupported => "platform_unsupported",
+ Self::Internal => "internal",
+ }
+ }
+}
+
+impl fmt::Display for ProcessErrorCode {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(self.as_str())
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ProcessError {
+ pub code: ProcessErrorCode,
+ pub message: String,
+}
+
+impl ProcessError {
+ pub fn new(code: ProcessErrorCode, message: impl Into<String>) -> Self {
+ Self {
+ code,
+ message: message.into(),
+ }
+ }
+
+ pub fn capability_missing(cap: &str) -> Self {
+ Self::new(
+ ProcessErrorCode::CapabilityMissing,
+ format!("session lacks capability '{cap}' (need mode=debug or higher)"),
+ )
+ }
+
+ pub fn unknown_session(id: &str) -> Self {
+ Self::new(
+ ProcessErrorCode::UnknownSession,
+ format!("unknown or stale session: {id}"),
+ )
+ }
+
+ pub fn platform() -> Self {
+ Self::new(
+ ProcessErrorCode::PlatformUnsupported,
+ "Live Process Bridge is Windows-only in this release",
+ )
+ }
+
+ /// JSON shape agents should parse: `{ ok: false, code, message }`.
+ pub fn to_json_value(&self) -> serde_json::Value {
+ serde_json::json!({
+ "ok": false,
+ "code": self.code.as_str(),
+ "message": self.message,
+ })
+ }
+}
+
+impl fmt::Display for ProcessError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}: {}", self.code.as_str(), self.message)
+ }
+}
+
+impl std::error::Error for ProcessError {}
+
+impl From<ProcessError> for String {
+ fn from(e: ProcessError) -> String {
+ e.to_string()
+ }
+}
+
+/// Map common Win32 last-error patterns into structured codes.
+pub fn map_win32_message(err: u32, context: &str) -> ProcessError {
+ // ERROR_ACCESS_DENIED = 5, ERROR_INVALID_PARAMETER = 87
+ match err {
+ 5 => ProcessError::new(
+ ProcessErrorCode::AccessDenied,
+ format!("{context} (GetLastError=0x{err:x} access denied)"),
+ ),
+ // ERROR_NOT_SUPPORTED often for protected processes / wrong bitness
+ 50 | 299 => ProcessError::new(
+ ProcessErrorCode::ProtectedProcess,
+ format!("{context} (GetLastError=0x{err:x} protected or partial copy)"),
+ ),
+ _ => ProcessError::new(
+ ProcessErrorCode::Internal,
+ format!("{context} (GetLastError=0x{err:x})"),
+ ),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn error_json_shape() {
+ let e = ProcessError::capability_missing("break");
+ let v = e.to_json_value();
+ assert_eq!(v["ok"], false);
+ assert_eq!(v["code"], "capability_missing");
+ assert!(v["message"].as_str().unwrap().contains("break"));
+ }
+
+ #[test]
+ fn code_strings_stable() {
+ assert_eq!(ProcessErrorCode::WaitTimeout.as_str(), "wait_timeout");
+ assert_eq!(
+ ProcessErrorCode::InstrumentNotEnabled.as_str(),
+ "instrument_not_enabled"
+ );
+ }
+}
diff --git a/crates/ghidrust-core/src/process/mod.rs b/crates/ghidrust-core/src/process/mod.rs
new file mode 100644
index 0000000..38953e3
--- /dev/null
+++ b/crates/ghidrust-core/src/process/mod.rs
@@ -0,0 +1,949 @@
+//! Live Process Bridge (Windows) — observe + debug modes, discovery APIs.
+//!
+//! - **observe** (default): PROCESS_VM_READ, modules, regions, resolve, scan, watch_read
+//! - **debug**: DebugActiveProcess / DEBUG_ONLY_THIS_PROCESS, break/step/regs/stack
+//! - **instrument**: reserved (not enabled)
+//!
+//! Sessions are in-process (`session_id`). CLI one-shot cannot reuse sessions across spawns.
+
+mod ac_advisory;
+mod backend;
+mod discovery;
+mod error;
+mod session;
+mod types;
+
+#[cfg(windows)]
+mod win_debug;
+#[cfg(windows)]
+mod win_observe;
+
+pub use ac_advisory::{scan_modules_for_ac, AcAdvisory};
+pub use discovery::{eval_watch_expr, find_aob, parse_aob, ScanOpts};
+pub use error::{ProcessError, ProcessErrorCode};
+pub use session::{
+ live_process_info_json, RunState, SessionMode, DEBUG_CAPS, OBSERVE_CAPS, SHIPPED_MODES,
+};
+pub use types::*;
+
+use std::collections::HashMap;
+use std::path::Path;
+use std::sync::Mutex;
+
+struct Attached {
+ pid: u32,
+ mode: SessionMode,
+ run_state: RunState,
+ #[cfg(windows)]
+ handle: isize,
+ /// Primary thread from CreateProcess (observe launch); closed on detach.
+ #[cfg(windows)]
+ thread: Option<isize>,
+ suspended: bool,
+ #[allow(dead_code)]
+ launched_image: Option<String>,
+ advisory: Option<AcAdvisory>,
+ #[cfg(windows)]
+ debug: Option<win_debug::DebugSession>,
+}
+
+static SESSIONS: Mutex<Option<HashMap<String, Attached>>> = Mutex::new(None);
+
+fn with_sessions<F, R>(f: F) -> R
+where
+ F: FnOnce(&mut HashMap<String, Attached>) -> R,
+{
+ let mut guard = SESSIONS.lock().unwrap_or_else(|e| e.into_inner());
+ if guard.is_none() {
+ *guard = Some(HashMap::new());
+ }
+ f(guard.as_mut().unwrap())
+}
+
+fn now_token() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
+
+fn session_report(a: &Attached, session_id: &str) -> ProcessSession {
+ let mut s = ProcessSession::new(session_id.to_string(), a.pid, a.mode, a.run_state);
+ s.advisory = a.advisory.clone();
+ s
+}
+
+fn require_session_cap(session_id: &str, cap: &str) -> Result<SessionMode, String> {
+ with_sessions(|m| {
+ let a = m
+ .get(session_id)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())?;
+ a.mode.require(cap).map_err(|e| e.to_string())?;
+ Ok(a.mode)
+ })
+}
+
+/// List processes (Windows). Other platforms return a clear error.
+pub fn process_list() -> Result<Vec<ProcessInfo>, String> {
+ #[cfg(windows)]
+ {
+ win_observe::list_processes().map_err(|e| e.to_string())
+ }
+ #[cfg(not(windows))]
+ {
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+/// Attach with default **observe** mode (backward compatible).
+pub fn process_attach(pid: u32) -> Result<ProcessSession, String> {
+ process_attach_opts(pid, &AttachOpts::default())
+}
+
+pub fn process_attach_opts(pid: u32, opts: &AttachOpts) -> Result<ProcessSession, String> {
+ #[cfg(windows)]
+ {
+ if matches!(opts.mode, SessionMode::Instrument) {
+ return Err(ProcessError::new(
+ ProcessErrorCode::InstrumentNotEnabled,
+ "instrument mode is not enabled in this release",
+ )
+ .to_string());
+ }
+ let session_id = format!("ps-{pid}-{}", now_token());
+ if opts.mode == SessionMode::Debug {
+ win_observe::debug_active_process(pid).map_err(|e| e.to_string())?;
+ let handle = win_observe::open_process_debug_rights(pid).map_err(|e| e.to_string())?;
+ let dbg = win_debug::DebugSession::start_attached(pid, handle, None);
+ // Wait briefly for initial break.
+ let _ = dbg.wait(2000);
+ let mods = win_observe::modules(handle, pid).unwrap_or_default();
+ let mut adv = scan_modules_for_ac(
+ &mods
+ .iter()
+ .map(|m| m.name.as_str())
+ .collect::<Vec<_>>(),
+ );
+ adv.debug_privilege = Some(win_debug::try_enable_debug_privilege());
+ let run_state = dbg.run_state();
+ let attached = Attached {
+ pid,
+ mode: SessionMode::Debug,
+ run_state,
+ handle,
+ thread: None,
+ suspended: false,
+ launched_image: None,
+ advisory: Some(adv),
+ debug: Some(dbg),
+ };
+ let report = session_report(&attached, &session_id);
+ with_sessions(|m| {
+ m.insert(session_id.clone(), attached);
+ });
+ Ok(report)
+ } else {
+ let handle = win_observe::attach_observe(pid).map_err(|e| e.to_string())?;
+ let mods = win_observe::modules(handle, pid).unwrap_or_default();
+ let adv = scan_modules_for_ac(
+ &mods
+ .iter()
+ .map(|m| m.name.as_str())
+ .collect::<Vec<_>>(),
+ );
+ let attached = Attached {
+ pid,
+ mode: SessionMode::Observe,
+ run_state: RunState::Attached,
+ handle,
+ thread: None,
+ suspended: false,
+ launched_image: None,
+ advisory: Some(adv),
+ debug: None,
+ };
+ let report = session_report(&attached, &session_id);
+ with_sessions(|m| {
+ m.insert(session_id.clone(), attached);
+ });
+ Ok(report)
+ }
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (pid, opts);
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+/// Launch process. Observe = CREATE_SUSPENDED; debug = DEBUG_ONLY_THIS_PROCESS (+ optional break_at_entry).
+pub fn process_launch(req: &LaunchRequest) -> Result<LaunchResult, String> {
+ #[cfg(windows)]
+ {
+ if matches!(req.mode, SessionMode::Instrument) {
+ return Err(ProcessError::new(
+ ProcessErrorCode::InstrumentNotEnabled,
+ "instrument mode is not enabled in this release",
+ )
+ .to_string());
+ }
+ with_sessions(|m| -> Result<(), String> {
+ if !m.is_empty() {
+ return Err(
+ "detach the current live session before launching a new process".into(),
+ );
+ }
+ Ok(())
+ })?;
+
+ if req.mode == SessionMode::Debug {
+ let (h_proc, h_thread, pid, tid, image_str) = win_observe::launch_debug(
+ &req.image,
+ req.args.as_deref(),
+ req.cwd.as_deref(),
+ false,
+ )
+ .map_err(|e| e.to_string())?;
+ let session_id = format!("ps-{pid}-{}", now_token());
+ // Prefer debug rights handle; CreateProcess already gave h_proc.
+ let dbg = win_debug::DebugSession::start_attached(pid, h_proc, Some(tid));
+ let wr = dbg.wait(5000);
+ let run_state = dbg.run_state();
+ let mods = win_observe::modules(h_proc, pid).unwrap_or_default();
+ let mut adv = scan_modules_for_ac(
+ &mods
+ .iter()
+ .map(|m| m.name.as_str())
+ .collect::<Vec<_>>(),
+ );
+ adv.debug_privilege = Some(win_debug::try_enable_debug_privilege());
+ // Close primary thread handle from CreateProcess (debugger has its own).
+ win_observe::close(h_thread);
+ let attached = Attached {
+ pid,
+ mode: SessionMode::Debug,
+ run_state,
+ handle: h_proc,
+ thread: None,
+ suspended: matches!(run_state, RunState::Stopped),
+ launched_image: Some(image_str.clone()),
+ advisory: Some(adv),
+ debug: Some(dbg),
+ };
+ let session = session_report(&attached, &session_id);
+ with_sessions(|m| {
+ m.insert(session_id.clone(), attached);
+ });
+ let _ = wr;
+ Ok(LaunchResult {
+ session,
+ image: image_str,
+ suspended: true,
+ primary_tid: tid,
+ break_at_entry: req.break_at_entry,
+ })
+ } else {
+ let (h_proc, h_thread, pid, tid, image_str) =
+ win_observe::launch_observe(&req.image, req.args.as_deref(), req.cwd.as_deref())
+ .map_err(|e| e.to_string())?;
+ let session_id = format!("ps-{pid}-{}", now_token());
+ let mods = win_observe::modules(h_proc, pid).unwrap_or_default();
+ let adv = scan_modules_for_ac(
+ &mods
+ .iter()
+ .map(|m| m.name.as_str())
+ .collect::<Vec<_>>(),
+ );
+ let attached = Attached {
+ pid,
+ mode: SessionMode::Observe,
+ run_state: RunState::Suspended,
+ handle: h_proc,
+ thread: Some(h_thread),
+ suspended: true,
+ launched_image: Some(image_str.clone()),
+ advisory: Some(adv),
+ debug: None,
+ };
+ let session = session_report(&attached, &session_id);
+ with_sessions(|m| {
+ m.insert(session_id.clone(), attached);
+ });
+ Ok(LaunchResult {
+ session,
+ image: image_str,
+ suspended: true,
+ primary_tid: tid,
+ break_at_entry: false,
+ })
+ }
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = req;
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+/// Resume the primary thread of a launched (CREATE_SUSPENDED) observe session.
+pub fn process_resume(session_id: &str) -> Result<(), String> {
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ let a = m
+ .get_mut(session_id)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())?;
+ if a.mode == SessionMode::Debug {
+ // Debug resume == continue.
+ if let Some(d) = a.debug.as_ref() {
+ d.continue_exec().map_err(|e| e.to_string())?;
+ a.run_state = d.run_state();
+ a.suspended = false;
+ return Ok(());
+ }
+ }
+ if !a.suspended {
+ return Err("session is not suspended (already running or attach-only)".into());
+ }
+ let h = a
+ .thread
+ .ok_or_else(|| "session has no primary thread handle to resume".to_string())?;
+ win_observe::resume_thread(h).map_err(|e| e.to_string())?;
+ a.suspended = false;
+ a.run_state = RunState::Attached;
+ Ok(())
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = session_id;
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_is_suspended(session_id: &str) -> Result<bool, String> {
+ with_sessions(|m| {
+ m.get(session_id)
+ .map(|a| a.suspended)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())
+ })
+}
+
+pub fn launch_command_line(image: &Path, args: Option<&str>) -> String {
+ #[cfg(windows)]
+ {
+ win_observe::build_command_line(image, args)
+ }
+ #[cfg(not(windows))]
+ {
+ let img = image.display().to_string();
+ match args.map(str::trim).filter(|a| !a.is_empty()) {
+ Some(a) => format!("\"{img}\" {a}"),
+ None => img,
+ }
+ }
+}
+
+pub fn process_detach(session_id: &str) -> Result<(), String> {
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ if let Some(mut a) = m.remove(session_id) {
+ if let Some(d) = a.debug.take() {
+ let _ = d.detach();
+ } else {
+ if a.suspended {
+ if let Some(th) = a.thread {
+ let _ = win_observe::resume_thread(th);
+ }
+ }
+ if let Some(th) = a.thread {
+ win_observe::close(th);
+ }
+ win_observe::close(a.handle);
+ }
+ Ok(())
+ } else {
+ Err(ProcessError::unknown_session(session_id).to_string())
+ }
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = session_id;
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+#[cfg(windows)]
+fn session_handle(session_id: &str) -> Result<(u32, isize), String> {
+ with_sessions(|m| {
+ m.get(session_id)
+ .map(|a| (a.pid, a.handle))
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())
+ })
+}
+
+pub fn process_modules(session_id: &str) -> Result<Vec<ModuleInfo>, String> {
+ #[cfg(windows)]
+ {
+ let (pid, handle) = session_handle(session_id)?;
+ win_observe::modules(handle, pid).map_err(|e| e.to_string())
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = session_id;
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_read(session_id: &str, va: u64, size: usize) -> Result<ReadResult, String> {
+ #[cfg(windows)]
+ {
+ let (_pid, handle) = session_handle(session_id)?;
+ Ok(win_observe::read_mem(handle, va, size))
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (session_id, va, size);
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_regions(session_id: &str, max: usize) -> Result<Vec<RegionInfo>, String> {
+ #[cfg(windows)]
+ {
+ let (_pid, handle) = session_handle(session_id)?;
+ win_observe::regions(handle, max.max(1)).map_err(|e| e.to_string())
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (session_id, max);
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_resolve(session_id: &str, module: &str, rva: u64) -> Result<ResolveLive, String> {
+ let mods = process_modules(session_id)?;
+ let m = mods
+ .iter()
+ .find(|m| {
+ m.name.eq_ignore_ascii_case(module)
+ || m.path
+ .as_deref()
+ .map(|p| {
+ p.to_ascii_lowercase()
+ .ends_with(&module.to_ascii_lowercase())
+ })
+ .unwrap_or(false)
+ })
+ .ok_or_else(|| {
+ ProcessError::new(
+ ProcessErrorCode::ModuleNotFound,
+ format!("module not found: {module}"),
+ )
+ .to_string()
+ })?;
+ Ok(ResolveLive {
+ module: m.name.clone(),
+ rva,
+ base: m.base,
+ live_va: m.base.wrapping_add(rva),
+ })
+}
+
+pub fn static_to_live(session_id: &str, module: &str, rva: u64) -> Result<ResolveLive, String> {
+ process_resolve(session_id, module, rva)
+}
+
+// ── Debug APIs ──────────────────────────────────────────────────────────────
+
+pub fn process_break_set(
+ session_id: &str,
+ addr: u64,
+ kind: BreakKind,
+ oneshot: bool,
+) -> Result<BreakpointInfo, String> {
+ require_session_cap(session_id, "break")?;
+ if kind == BreakKind::Hardware {
+ return Err(ProcessError::new(
+ ProcessErrorCode::InstrumentNotEnabled,
+ "hardware breakpoints not enabled yet (use kind=software)",
+ )
+ .to_string());
+ }
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ let a = m
+ .get(session_id)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())?;
+ let d = a
+ .debug
+ .as_ref()
+ .ok_or_else(|| ProcessError::capability_missing("break").to_string())?;
+ d.set_soft_bp(addr, oneshot).map_err(|e| e.to_string())
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (addr, oneshot);
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_break_clear(
+ session_id: &str,
+ id: Option<u64>,
+ addr: Option<u64>,
+) -> Result<(), String> {
+ require_session_cap(session_id, "break")?;
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ let a = m
+ .get(session_id)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())?;
+ let d = a
+ .debug
+ .as_ref()
+ .ok_or_else(|| ProcessError::capability_missing("break").to_string())?;
+ d.clear_bp(id, addr).map_err(|e| e.to_string())
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (id, addr);
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_break_list(session_id: &str) -> Result<Vec<BreakpointInfo>, String> {
+ require_session_cap(session_id, "break")?;
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ let a = m
+ .get(session_id)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())?;
+ let d = a
+ .debug
+ .as_ref()
+ .ok_or_else(|| ProcessError::capability_missing("break").to_string())?;
+ d.list_bp().map_err(|e| e.to_string())
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_continue(session_id: &str) -> Result<(), String> {
+ require_session_cap(session_id, "continue")?;
+ #[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("continue").to_string())?;
+ d.continue_exec().map_err(|e| e.to_string())?;
+ a.run_state = d.run_state();
+ a.suspended = false;
+ Ok(())
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_pause(session_id: &str) -> Result<(), String> {
+ require_session_cap(session_id, "pause")?;
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ let a = m
+ .get(session_id)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())?;
+ let d = a
+ .debug
+ .as_ref()
+ .ok_or_else(|| ProcessError::capability_missing("pause").to_string())?;
+ d.pause().map_err(|e| e.to_string())
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_wait(session_id: &str, timeout_ms: u64) -> Result<WaitResult, String> {
+ require_session_cap(session_id, "continue")?;
+ #[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("continue").to_string())?;
+ let wr = d.wait(timeout_ms);
+ a.run_state = d.run_state();
+ // Enrich module+rva on stop if possible
+ Ok(wr)
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = timeout_ms;
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_step_into(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_into(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_step_over(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_over(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)]
+ {
+ with_sessions(|m| {
+ let a = m
+ .get(session_id)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())?;
+ if let Some(d) = a.debug.as_ref() {
+ return d.threads().map_err(|e| e.to_string());
+ }
+ let ids = win_observe::list_threads(a.pid).map_err(|e| e.to_string())?;
+ Ok(ids
+ .into_iter()
+ .map(|thread_id| ThreadInfo {
+ thread_id,
+ name: None,
+ })
+ .collect())
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_thread_context_get(
+ session_id: &str,
+ thread_id: u32,
+) -> Result<RegisterSet, String> {
+ require_session_cap(session_id, "registers")?;
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ let a = m
+ .get(session_id)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())?;
+ let d = a
+ .debug
+ .as_ref()
+ .ok_or_else(|| ProcessError::capability_missing("registers").to_string())?;
+ d.get_context(thread_id).map_err(|e| e.to_string())
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = thread_id;
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_thread_context_set(
+ session_id: &str,
+ thread_id: u32,
+ regs: &RegisterSet,
+) -> Result<(), String> {
+ require_session_cap(session_id, "registers")?;
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ let a = m
+ .get(session_id)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())?;
+ let d = a
+ .debug
+ .as_ref()
+ .ok_or_else(|| ProcessError::capability_missing("registers").to_string())?;
+ d.set_context(thread_id, regs.clone())
+ .map_err(|e| e.to_string())
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (thread_id, regs);
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_stack(
+ session_id: &str,
+ thread_id: u32,
+ max_frames: usize,
+) -> Result<Vec<StackFrame>, String> {
+ require_session_cap(session_id, "stack")?;
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ let a = m
+ .get(session_id)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())?;
+ let d = a
+ .debug
+ .as_ref()
+ .ok_or_else(|| ProcessError::capability_missing("stack").to_string())?;
+ let mut frames = d
+ .stack(thread_id, max_frames)
+ .map_err(|e| e.to_string())?;
+ // Enrich module+rva
+ if let Ok(mods) = win_observe::modules(a.handle, a.pid) {
+ for f in &mut frames {
+ if let Some(m) = mods
+ .iter()
+ .find(|m| f.rip >= m.base && f.rip < m.base.wrapping_add(m.size))
+ {
+ f.module = Some(m.name.clone());
+ f.rva = Some(f.rip.wrapping_sub(m.base));
+ }
+ }
+ }
+ Ok(frames)
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (thread_id, max_frames);
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+// ── Discovery APIs ──────────────────────────────────────────────────────────
+
+pub fn process_scan_mem(session_id: &str, opts: &ScanOpts) -> Result<ScanResult, String> {
+ // scan available in observe+
+ require_session_cap(session_id, "scan")?;
+ #[cfg(windows)]
+ {
+ let (pid, handle) = session_handle(session_id)?;
+ discovery::process_scan(handle, pid, opts).map_err(|e| e.to_string())
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = opts;
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_watch_expr(
+ session_id: &str,
+ expr: &str,
+ matrix_heuristic: bool,
+) -> Result<WatchResult, String> {
+ // watch_read for observe; full watch for debug — allow watch_read always
+ let cap = with_sessions(|m| {
+ m.get(session_id)
+ .map(|a| a.mode)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())
+ })?;
+ if !cap.has("watch_read") && !cap.has("watch") {
+ return Err(ProcessError::capability_missing("watch_read").to_string());
+ }
+ #[cfg(windows)]
+ {
+ let (pid, handle) = session_handle(session_id)?;
+ discovery::eval_watch_expr(handle, pid, expr, matrix_heuristic).map_err(|e| e.to_string())
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (expr, matrix_heuristic);
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_vtable_probe(
+ session_id: &str,
+ object_va: u64,
+ max_slots: usize,
+) -> Result<VtableProbeResult, String> {
+ require_session_cap(session_id, "read")?;
+ #[cfg(windows)]
+ {
+ let (pid, handle) = session_handle(session_id)?;
+ discovery::vtable_probe(handle, pid, object_va, max_slots).map_err(|e| e.to_string())
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (object_va, max_slots);
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+pub fn process_export_snapshot(
+ session_id: &str,
+ watch_exprs: &[String],
+ nearby_vas: &[u64],
+) -> Result<ExportSnapshot, String> {
+ #[cfg(windows)]
+ {
+ let (mode, pid, run_state, stop, regs, stack) = with_sessions(|m| {
+ let a = m
+ .get(session_id)
+ .ok_or_else(|| ProcessError::unknown_session(session_id).to_string())?;
+ let stop = a.debug.as_ref().and_then(|d| d.last_stop());
+ let tid = stop.as_ref().map(|s| s.thread_id);
+ let regs = if let (Some(d), Some(t)) = (a.debug.as_ref(), tid) {
+ d.get_context(t).ok()
+ } else {
+ None
+ };
+ let stack = if let (Some(d), Some(t)) = (a.debug.as_ref(), tid) {
+ d.stack(t, 32).unwrap_or_default()
+ } else {
+ vec![]
+ };
+ Ok::<_, String>((a.mode, a.pid, a.run_state, stop, regs, stack))
+ })?;
+ let mut watches = Vec::new();
+ for e in watch_exprs {
+ if let Ok(w) = process_watch_expr(session_id, e, true) {
+ watches.push(w);
+ }
+ }
+ let mut nearby_hex = Vec::new();
+ for va in nearby_vas {
+ if let Ok(r) = process_read(session_id, *va, 64) {
+ nearby_hex.push(r);
+ }
+ }
+ Ok(ExportSnapshot {
+ session_id: session_id.into(),
+ pid,
+ mode,
+ run_state,
+ stop,
+ registers: regs,
+ stack,
+ watches,
+ nearby_hex,
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (watch_exprs, nearby_vas);
+ Err(ProcessError::platform().to_string())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn launch_command_line_quotes_paths_with_spaces() {
+ let s = launch_command_line(Path::new(r"C:\Program Files\app.exe"), Some("-flag"));
+ assert!(s.starts_with('"'), "{s}");
+ assert!(s.contains("app.exe"), "{s}");
+ assert!(s.ends_with("-flag"), "{s}");
+ }
+
+ #[test]
+ fn launch_command_line_plain_path_no_extra_quotes() {
+ let s = launch_command_line(Path::new(r"C:\tools\app.exe"), None);
+ assert_eq!(s, r"C:\tools\app.exe");
+ }
+
+ #[test]
+ fn launch_fails_when_image_missing() {
+ let err = process_launch(&LaunchRequest {
+ image: PathBuf::from("Z:\\definitely\\missing\\ghidrust_launch_test.exe"),
+ args: None,
+ cwd: None,
+ mode: SessionMode::Observe,
+ break_at_entry: false,
+ })
+ .unwrap_err();
+ assert!(
+ err.contains("not found")
+ || err.contains("Windows-only")
+ || err.contains("platform")
+ || err.contains("CreateProcess"),
+ "{err}"
+ );
+ }
+
+ #[test]
+ fn observe_session_rejects_break_capability() {
+ // No live session: capability check still fails on unknown session first.
+ let err = process_break_set("ps-none", 0x1000, BreakKind::Software, false).unwrap_err();
+ assert!(
+ err.contains("unknown") || err.contains("capability") || err.contains("platform"),
+ "{err}"
+ );
+ }
+}
diff --git a/crates/ghidrust-core/src/process/session.rs b/crates/ghidrust-core/src/process/session.rs
new file mode 100644
index 0000000..a45a99d
--- /dev/null
+++ b/crates/ghidrust-core/src/process/session.rs
@@ -0,0 +1,235 @@
+//! Session mode ladder, capabilities, and run-state machine.
+
+use super::error::{ProcessError, ProcessErrorCode};
+use serde::{Deserialize, Serialize};
+use std::str::FromStr;
+
+/// Attach/launch capability ladder. Default is observe (MVP read-only).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum SessionMode {
+ #[default]
+ Observe,
+ Debug,
+ /// Reserved — patches / HW BP beyond software INT3. Not enabled this wave.
+ Instrument,
+}
+
+impl SessionMode {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Observe => "observe",
+ Self::Debug => "debug",
+ Self::Instrument => "instrument",
+ }
+ }
+
+ pub fn capabilities(self) -> &'static [&'static str] {
+ match self {
+ Self::Observe => OBSERVE_CAPS,
+ Self::Debug => DEBUG_CAPS,
+ Self::Instrument => INSTRUMENT_CAPS,
+ }
+ }
+
+ pub fn has(self, cap: &str) -> bool {
+ self.capabilities().iter().any(|c| *c == cap)
+ }
+
+ pub fn require(self, cap: &str) -> Result<(), ProcessError> {
+ if self.has(cap) {
+ Ok(())
+ } else if matches!(self, Self::Instrument) || cap == "instrument" {
+ Err(ProcessError::new(
+ ProcessErrorCode::InstrumentNotEnabled,
+ format!("capability '{cap}' requires instrument mode (not enabled)"),
+ ))
+ } else {
+ Err(ProcessError::capability_missing(cap))
+ }
+ }
+}
+
+impl FromStr for SessionMode {
+ type Err = ProcessError;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.trim().to_ascii_lowercase().as_str() {
+ "observe" | "read" | "readonly" | "read-only" => Ok(Self::Observe),
+ "debug" => Ok(Self::Debug),
+ "instrument" | "write" => Ok(Self::Instrument),
+ other => Err(ProcessError::new(
+ ProcessErrorCode::InvalidArgument,
+ format!("unknown session mode '{other}' (use observe|debug)"),
+ )),
+ }
+ }
+}
+
+impl std::fmt::Display for SessionMode {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(self.as_str())
+ }
+}
+
+pub const OBSERVE_CAPS: &[&str] = &[
+ "read",
+ "modules",
+ "regions",
+ "resolve",
+ "scan",
+ "watch_read",
+ "stack_sample",
+];
+
+pub const DEBUG_CAPS: &[&str] = &[
+ "read",
+ "modules",
+ "regions",
+ "resolve",
+ "scan",
+ "watch_read",
+ "watch",
+ "stack_sample",
+ "break",
+ "step",
+ "registers",
+ "stack",
+ "threads",
+ "pause",
+ "continue",
+ "exceptions",
+ "export_snapshot",
+];
+
+/// Same as debug for reporting; instrument-only caps are not granted until enabled.
+pub const INSTRUMENT_CAPS: &[&str] = DEBUG_CAPS;
+
+/// Modes currently shippable (instrument accepted in parse but not attachable).
+pub const SHIPPED_MODES: &[&str] = &["observe", "debug"];
+
+/// High-level run state for a live session.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum RunState {
+ #[default]
+ Detached,
+ /// Attached; observe always, or debug not yet waited.
+ Attached,
+ /// CREATE_SUSPENDED launch, not yet resumed (observe path).
+ Suspended,
+ /// Debug: process running under debugger.
+ Running,
+ /// Debug: stopped on BP / exception / step / pause.
+ Stopped,
+ Exited,
+}
+
+impl RunState {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Detached => "detached",
+ Self::Attached => "attached",
+ Self::Suspended => "suspended",
+ Self::Running => "running",
+ Self::Stopped => "stopped",
+ Self::Exited => "exited",
+ }
+ }
+}
+
+/// Capability matrix published via `server_info.live_process`.
+pub fn live_process_info_json() -> serde_json::Value {
+ serde_json::json!({
+ "modes": SHIPPED_MODES,
+ "capabilities_by_mode": {
+ "observe": OBSERVE_CAPS,
+ "debug": DEBUG_CAPS,
+ },
+ "tools": [
+ "process_list",
+ "process_attach",
+ "process_launch",
+ "process_resume",
+ "process_detach",
+ "process_modules",
+ "process_read",
+ "process_resolve",
+ "process_regions",
+ "process_break_set",
+ "process_break_clear",
+ "process_break_list",
+ "process_continue",
+ "process_pause",
+ "process_step_into",
+ "process_step_over",
+ "process_wait",
+ "process_threads",
+ "process_thread_context_get",
+ "process_thread_context_set",
+ "process_stack",
+ "process_scan",
+ "process_watch_expr",
+ "process_vtable_probe",
+ "process_export_snapshot",
+ ],
+ "session_model": "in_process_mcp",
+ "note": "Default attach is observe (read-only). mode=debug enables break/step/registers/stack. CLI one-shot cannot reuse session_id across spawns. instrument mode is not enabled. Anti-cheat: advisory only; access denied is explicit."
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn observe_lacks_break() {
+ assert!(SessionMode::Observe.has("read"));
+ assert!(!SessionMode::Observe.has("break"));
+ let e = SessionMode::Observe.require("break").unwrap_err();
+ assert_eq!(e.code, ProcessErrorCode::CapabilityMissing);
+ }
+
+ #[test]
+ fn debug_has_break_step_regs() {
+ for cap in ["break", "step", "registers", "stack", "threads", "continue"] {
+ SessionMode::Debug.require(cap).unwrap();
+ }
+ }
+
+ #[test]
+ fn parse_mode_default_aliases() {
+ assert_eq!(
+ "observe".parse::<SessionMode>().unwrap(),
+ SessionMode::Observe
+ );
+ assert_eq!("debug".parse::<SessionMode>().unwrap(), SessionMode::Debug);
+ assert!("nope".parse::<SessionMode>().is_err());
+ }
+
+ #[test]
+ fn instrument_not_enabled_message() {
+ let e = SessionMode::Observe.require("instrument").unwrap_err();
+ assert_eq!(e.code, ProcessErrorCode::InstrumentNotEnabled);
+ }
+
+ #[test]
+ fn live_info_lists_modes_and_tools() {
+ let v = live_process_info_json();
+ assert!(v["modes"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|m| m == "debug"));
+ assert!(v["capabilities_by_mode"]["observe"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|c| c == "read"));
+ assert!(v["tools"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|t| t == "process_break_set"));
+ }
+}
diff --git a/crates/ghidrust-core/src/process/types.rs b/crates/ghidrust-core/src/process/types.rs
new file mode 100644
index 0000000..3b9788d
--- /dev/null
+++ b/crates/ghidrust-core/src/process/types.rs
@@ -0,0 +1,317 @@
+//! Shared live-process DTOs.
+
+use super::ac_advisory::AcAdvisory;
+use super::session::{RunState, SessionMode};
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ProcessInfo {
+ pub pid: u32,
+ pub name: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub path: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ModuleInfo {
+ pub name: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub path: Option<String>,
+ pub base: u64,
+ pub size: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RegionInfo {
+ pub base: u64,
+ pub size: u64,
+ pub protect: String,
+ pub state: String,
+ pub typ: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ProcessSession {
+ pub session_id: String,
+ pub pid: u32,
+ pub mode: SessionMode,
+ pub capabilities: Vec<String>,
+ pub run_state: RunState,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub advisory: Option<AcAdvisory>,
+}
+
+impl ProcessSession {
+ pub fn new(session_id: String, pid: u32, mode: SessionMode, run_state: RunState) -> Self {
+ Self {
+ session_id,
+ pid,
+ mode,
+ capabilities: mode.capabilities().iter().map(|s| (*s).to_string()).collect(),
+ run_state,
+ advisory: None,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ReadResult {
+ pub va: u64,
+ pub size_requested: usize,
+ pub bytes_read: usize,
+ pub hex: String,
+ pub bytes: Vec<u8>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub as_u64: Option<Vec<u64>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub as_f32: Option<Vec<f32>>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ResolveLive {
+ pub module: String,
+ pub rva: u64,
+ pub base: u64,
+ pub live_va: u64,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct AttachOpts {
+ pub mode: SessionMode,
+}
+
+/// Spawn a new process under the Live Process Bridge.
+#[derive(Debug, Clone)]
+pub struct LaunchRequest {
+ pub image: PathBuf,
+ pub args: Option<String>,
+ pub cwd: Option<PathBuf>,
+ pub mode: SessionMode,
+ /// Debug mode: stop on initial Windows breakpoint / entry (not CREATE_SUSPENDED-only).
+ pub break_at_entry: bool,
+}
+
+impl Default for LaunchRequest {
+ fn default() -> Self {
+ Self {
+ image: PathBuf::new(),
+ args: None,
+ cwd: None,
+ mode: SessionMode::Observe,
+ break_at_entry: false,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LaunchResult {
+ pub session: ProcessSession,
+ pub image: String,
+ /// True until `process_resume` (observe CREATE_SUSPENDED) or until first debug continue.
+ pub suspended: bool,
+ pub primary_tid: u32,
+ pub break_at_entry: bool,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum BreakKind {
+ Software,
+ Hardware,
+}
+
+impl Default for BreakKind {
+ fn default() -> Self {
+ Self::Software
+ }
+}
+
+impl std::str::FromStr for BreakKind {
+ type Err = super::error::ProcessError;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.trim().to_ascii_lowercase().as_str() {
+ "software" | "sw" | "int3" => Ok(Self::Software),
+ "hardware" | "hw" | "dr" => Ok(Self::Hardware),
+ other => Err(super::error::ProcessError::new(
+ super::error::ProcessErrorCode::InvalidArgument,
+ format!("unknown break kind '{other}' (software|hardware)"),
+ )),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BreakpointInfo {
+ pub id: u64,
+ pub addr: u64,
+ pub kind: BreakKind,
+ pub oneshot: bool,
+ pub enabled: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ThreadInfo {
+ pub thread_id: u32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct RegisterSet {
+ pub rax: u64,
+ pub rbx: u64,
+ pub rcx: u64,
+ pub rdx: u64,
+ pub rsi: u64,
+ pub rdi: u64,
+ pub rbp: u64,
+ pub rsp: u64,
+ pub r8: u64,
+ pub r9: u64,
+ pub r10: u64,
+ pub r11: u64,
+ pub r12: u64,
+ pub r13: u64,
+ pub r14: u64,
+ pub r15: u64,
+ pub rip: u64,
+ pub rflags: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct StackFrame {
+ pub level: u32,
+ pub sp: u64,
+ pub rip: u64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub module: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub rva: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub symbol: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct StopEvent {
+ pub reason: String,
+ pub thread_id: u32,
+ pub rip: u64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub registers: Option<RegisterSet>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub module: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub rva: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub insn_preview: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub bp_id: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub exception_code: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub fault_va: Option<u64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WaitResult {
+ pub ok: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub event: Option<StopEvent>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub code: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub message: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ScanHit {
+ pub va: u64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub module: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub rva: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub preview_hex: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ScanResult {
+ pub hits: Vec<ScanHit>,
+ pub truncated: bool,
+ pub regions_scanned: usize,
+ pub bytes_scanned: u64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub diff_changed: Option<Vec<u64>>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WatchResult {
+ pub expr: String,
+ pub steps: Vec<WatchStep>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub final_va: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub value_hex: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub as_u64: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub as_f32: Option<f32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub as_f64: Option<f64>,
+ /// Present only when a float4x4 heuristic matched — not a proven type.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub heuristic_float4x4: Option<Vec<f32>>,
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub heuristic: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WatchStep {
+ pub op: String,
+ pub va: u64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub value_u64: Option<u64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct VtableProbeResult {
+ pub object_va: u64,
+ pub vtable_va: u64,
+ pub in_module_rdata: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub module: Option<String>,
+ pub slots: Vec<VtableSlot>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub rtti_hint: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct VtableSlot {
+ pub index: u32,
+ pub target_va: u64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub module: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub rva: Option<u64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ExportSnapshot {
+ pub session_id: String,
+ pub pid: u32,
+ pub mode: SessionMode,
+ pub run_state: RunState,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub stop: Option<StopEvent>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub registers: Option<RegisterSet>,
+ pub stack: Vec<StackFrame>,
+ pub watches: Vec<WatchResult>,
+ pub nearby_hex: Vec<ReadResult>,
+}
diff --git a/crates/ghidrust-core/src/process/win_debug.rs b/crates/ghidrust-core/src/process/win_debug.rs
new file mode 100644
index 0000000..fdad302
--- /dev/null
+++ b/crates/ghidrust-core/src/process/win_debug.rs
@@ -0,0 +1,1071 @@
+//! Windows debug backend: WaitForDebugEvent pump, INT3 BP, CONTEXT, step, stack.
+
+use super::error::{map_win32_message, ProcessError, ProcessErrorCode};
+use super::types::{
+ BreakKind, BreakpointInfo, RegisterSet, StackFrame, StopEvent, ThreadInfo, WaitResult,
+};
+use super::win_observe::{self, HANDLE};
+use std::collections::HashMap;
+use std::mem::zeroed;
+use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError};
+use std::sync::{Arc, Mutex};
+use std::thread::{self, JoinHandle};
+use std::time::Duration;
+
+type BOOL = i32;
+type DWORD = u32;
+type WORD = u16;
+
+const EXCEPTION_DEBUG_EVENT: DWORD = 1;
+const CREATE_PROCESS_DEBUG_EVENT: DWORD = 3;
+const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
+const LOAD_DLL_DEBUG_EVENT: DWORD = 6;
+
+const EXCEPTION_BREAKPOINT: DWORD = 0x8000_0003;
+const EXCEPTION_SINGLE_STEP: DWORD = 0x8000_0004;
+const DBG_CONTINUE: DWORD = 0x0001_0002;
+const DBG_EXCEPTION_NOT_HANDLED: DWORD = 0x8001_0001;
+
+const CONTEXT_AMD64: DWORD = 0x0010_0000;
+const CONTEXT_CONTROL: DWORD = CONTEXT_AMD64 | 0x1;
+const CONTEXT_INTEGER: DWORD = CONTEXT_AMD64 | 0x2;
+const CONTEXT_FULL: DWORD = CONTEXT_CONTROL | CONTEXT_INTEGER | (CONTEXT_AMD64 | 0x8);
+const CONTEXT_DEBUG_REGISTERS: DWORD = CONTEXT_AMD64 | 0x10;
+
+const THREAD_GET_CONTEXT: DWORD = 0x0008;
+const THREAD_SET_CONTEXT: DWORD = 0x0010;
+const THREAD_SUSPEND_RESUME: DWORD = 0x0002;
+const THREAD_QUERY_INFORMATION: DWORD = 0x0040;
+
+const EFLAGS_TF: u64 = 0x100;
+
+/// Opaque DEBUG_EVENT.u payload (largest member is exception info + padding).
+#[repr(C)]
+struct DEBUG_EVENT {
+ dw_debug_event_code: DWORD,
+ dw_process_id: DWORD,
+ dw_thread_id: DWORD,
+ /// Raw union bytes; interpret via `exception_info` / offsets.
+ u_bytes: [u8; 160],
+}
+
+impl DEBUG_EVENT {
+ fn exception_code(&self) -> DWORD {
+ // EXCEPTION_DEBUG_INFO.exception_record.exception_code at start of union
+ u32::from_le_bytes(self.u_bytes[0..4].try_into().unwrap())
+ }
+ fn exception_address(&self) -> u64 {
+ // EXCEPTION_RECORD: code(4)+flags(4)+record(8)+address(8) on x64
+ u64::from_le_bytes(self.u_bytes[16..24].try_into().unwrap())
+ }
+ fn exception_first_chance(&self) -> DWORD {
+ // After EXCEPTION_RECORD (4+4+8+8+4+15*8 = 152?); on x64 EXCEPTION_RECORD is:
+ // code4 flags4 record8 address8 number4 pad4 info[15]8 = 152, then first_chance at 152
+ // Actually MSVC: NumberParameters DWORD + pad to 8 + ExceptionInformation[15]
+ // 4+4+8+8+4+4+15*8 = 160 for record alone — keep first_chance at offset of EXCEPTION_DEBUG_INFO after record.
+ // Safer: EXCEPTION_DEBUG_INFO is { EXCEPTION_RECORD; DWORD first_chance }
+ // EXCEPTION_RECORD size on x64 = 152 (0x98). first_chance at 152.
+ if self.u_bytes.len() >= 156 {
+ u32::from_le_bytes(self.u_bytes[152..156].try_into().unwrap_or([0; 4]))
+ } else {
+ 1
+ }
+ }
+ fn create_process_h_file(&self) -> HANDLE {
+ isize::from_le_bytes(self.u_bytes[0..8].try_into().unwrap())
+ }
+ fn load_dll_h_file(&self) -> HANDLE {
+ isize::from_le_bytes(self.u_bytes[0..8].try_into().unwrap())
+ }
+}
+
+/// x64 CONTEXT (subset — layout matches Windows).
+#[repr(C, align(16))]
+struct CONTEXT {
+ p1_home: u64,
+ p2_home: u64,
+ p3_home: u64,
+ p4_home: u64,
+ p5_home: u64,
+ p6_home: u64,
+ context_flags: DWORD,
+ mx_csr: DWORD,
+ seg_cs: WORD,
+ seg_ds: WORD,
+ seg_es: WORD,
+ seg_fs: WORD,
+ seg_gs: WORD,
+ seg_ss: WORD,
+ e_flags: DWORD,
+ dr0: u64,
+ dr1: u64,
+ dr2: u64,
+ dr3: u64,
+ dr6: u64,
+ dr7: u64,
+ rax: u64,
+ rcx: u64,
+ rdx: u64,
+ rbx: u64,
+ rsp: u64,
+ rbp: u64,
+ rsi: u64,
+ rdi: u64,
+ r8: u64,
+ r9: u64,
+ r10: u64,
+ r11: u64,
+ r12: u64,
+ r13: u64,
+ r14: u64,
+ r15: u64,
+ rip: u64,
+ // FltSave + vector registers omitted — we only use integer/control
+ _rest: [u8; 0x4D0 - 0xF8],
+}
+
+#[link(name = "kernel32")]
+extern "system" {
+ fn WaitForDebugEvent(event: *mut DEBUG_EVENT, ms: DWORD) -> BOOL;
+ fn ContinueDebugEvent(pid: DWORD, tid: DWORD, status: DWORD) -> BOOL;
+ fn DebugBreakProcess(h: HANDLE) -> BOOL;
+ fn OpenThread(access: DWORD, inherit: BOOL, tid: DWORD) -> HANDLE;
+ fn GetThreadContext(h: HANDLE, ctx: *mut CONTEXT) -> BOOL;
+ fn SetThreadContext(h: HANDLE, ctx: *const CONTEXT) -> BOOL;
+ fn SuspendThread(h: HANDLE) -> DWORD;
+ fn ResumeThread(h: HANDLE) -> DWORD;
+ fn CloseHandle(h: HANDLE) -> BOOL;
+ fn GetLastError() -> DWORD;
+ fn FlushInstructionCache(h: HANDLE, addr: *const u8, size: usize) -> BOOL;
+}
+
+#[link(name = "ntdll")]
+extern "system" {
+ fn RtlLookupFunctionEntry(control_pc: u64, image_base: *mut u64, history: *mut u8) -> *mut u8;
+}
+
+struct SoftBp {
+ id: u64,
+ addr: u64,
+ original: u8,
+ oneshot: bool,
+ enabled: bool,
+}
+
+enum PumpCmd {
+ Continue {
+ reply: Sender<Result<(), ProcessError>>,
+ },
+ Pause {
+ reply: Sender<Result<(), ProcessError>>,
+ },
+ SetSoftBp {
+ addr: u64,
+ oneshot: bool,
+ reply: Sender<Result<BreakpointInfo, ProcessError>>,
+ },
+ ClearBp {
+ id: Option<u64>,
+ addr: Option<u64>,
+ reply: Sender<Result<(), ProcessError>>,
+ },
+ ListBp {
+ reply: Sender<Vec<BreakpointInfo>>,
+ },
+ GetContext {
+ tid: u32,
+ reply: Sender<Result<RegisterSet, ProcessError>>,
+ },
+ SetContext {
+ tid: u32,
+ regs: RegisterSet,
+ reply: Sender<Result<(), ProcessError>>,
+ },
+ StepInto {
+ tid: u32,
+ reply: Sender<Result<(), ProcessError>>,
+ },
+ StepOver {
+ tid: u32,
+ reply: Sender<Result<(), ProcessError>>,
+ },
+ Stack {
+ tid: u32,
+ max_frames: usize,
+ reply: Sender<Result<Vec<StackFrame>, ProcessError>>,
+ },
+ Threads {
+ reply: Sender<Result<Vec<ThreadInfo>, ProcessError>>,
+ },
+ Detach {
+ reply: Sender<Result<(), ProcessError>>,
+ },
+}
+
+pub struct DebugSession {
+ #[allow(dead_code)]
+ pub pid: u32,
+ #[allow(dead_code)]
+ pub process: HANDLE,
+ cmd_tx: Sender<PumpCmd>,
+ join: Option<JoinHandle<()>>,
+ /// Shared last stop for polling without channel.
+ shared: Arc<Mutex<SharedDebug>>,
+}
+
+struct SharedDebug {
+ last_stop: Option<StopEvent>,
+ exited: bool,
+ run_state: super::session::RunState,
+ next_bp_id: u64,
+}
+
+impl DebugSession {
+ pub fn start_attached(pid: u32, process: HANDLE, primary_tid: Option<u32>) -> Self {
+ let (cmd_tx, cmd_rx) = mpsc::channel::<PumpCmd>();
+ let shared = Arc::new(Mutex::new(SharedDebug {
+ last_stop: None,
+ exited: false,
+ run_state: super::session::RunState::Running,
+ next_bp_id: 1,
+ }));
+ let shared2 = Arc::clone(&shared);
+ let join = thread::spawn(move || {
+ pump_loop(pid, process, primary_tid, cmd_rx, shared2);
+ });
+ Self {
+ pid,
+ process,
+ cmd_tx,
+ join: Some(join),
+ shared,
+ }
+ }
+
+ fn send<T>(&self, build: impl FnOnce(Sender<T>) -> PumpCmd, timeout: Duration) -> Result<T, ProcessError>
+ where
+ T: Send + 'static,
+ {
+ let (tx, rx) = mpsc::channel();
+ self.cmd_tx
+ .send(build(tx))
+ .map_err(|_| ProcessError::new(ProcessErrorCode::ProcessExited, "debug pump dead"))?;
+ rx.recv_timeout(timeout).map_err(|_| {
+ ProcessError::new(ProcessErrorCode::WaitTimeout, "debug command timed out")
+ })
+ }
+
+ pub fn wait(&self, timeout_ms: u64) -> WaitResult {
+ let deadline = std::time::Instant::now() + Duration::from_millis(timeout_ms.max(1));
+ loop {
+ {
+ let g = self.shared.lock().unwrap_or_else(|e| e.into_inner());
+ if g.exited {
+ return WaitResult {
+ ok: false,
+ event: g.last_stop.clone(),
+ code: Some("process_exited".into()),
+ message: Some("debuggee exited".into()),
+ };
+ }
+ if let Some(ev) = g.last_stop.clone() {
+ if g.run_state == super::session::RunState::Stopped {
+ return WaitResult {
+ ok: true,
+ event: Some(ev),
+ code: None,
+ message: None,
+ };
+ }
+ }
+ }
+ if std::time::Instant::now() >= deadline {
+ return WaitResult {
+ ok: false,
+ event: None,
+ code: Some("wait_timeout".into()),
+ message: Some(format!("no stop event within {timeout_ms}ms")),
+ };
+ }
+ thread::sleep(Duration::from_millis(20));
+ }
+ }
+
+ pub fn continue_exec(&self) -> Result<(), ProcessError> {
+ // Clear last stop so wait can see a new one.
+ {
+ let mut g = self.shared.lock().unwrap_or_else(|e| e.into_inner());
+ g.last_stop = None;
+ g.run_state = super::session::RunState::Running;
+ }
+ self.send(|reply| PumpCmd::Continue { reply }, Duration::from_secs(5))?
+ }
+
+ pub fn pause(&self) -> Result<(), ProcessError> {
+ self.send(|reply| PumpCmd::Pause { reply }, Duration::from_secs(5))?
+ }
+
+ pub fn set_soft_bp(&self, addr: u64, oneshot: bool) -> Result<BreakpointInfo, ProcessError> {
+ self.send(
+ |reply| PumpCmd::SetSoftBp {
+ addr,
+ oneshot,
+ reply,
+ },
+ Duration::from_secs(5),
+ )?
+ }
+
+ pub fn clear_bp(&self, id: Option<u64>, addr: Option<u64>) -> Result<(), ProcessError> {
+ self.send(
+ |reply| PumpCmd::ClearBp { id, addr, reply },
+ Duration::from_secs(5),
+ )?
+ }
+
+ pub fn list_bp(&self) -> Result<Vec<BreakpointInfo>, ProcessError> {
+ self.send(|reply| PumpCmd::ListBp { reply }, Duration::from_secs(5))
+ }
+
+ pub fn get_context(&self, tid: u32) -> Result<RegisterSet, ProcessError> {
+ self.send(
+ |reply| PumpCmd::GetContext { tid, reply },
+ Duration::from_secs(5),
+ )?
+ }
+
+ pub fn set_context(&self, tid: u32, regs: RegisterSet) -> Result<(), ProcessError> {
+ self.send(
+ |reply| PumpCmd::SetContext { tid, regs, reply },
+ Duration::from_secs(5),
+ )?
+ }
+
+ pub fn step_into(&self, tid: u32) -> Result<(), ProcessError> {
+ {
+ let mut g = self.shared.lock().unwrap_or_else(|e| e.into_inner());
+ g.last_stop = None;
+ g.run_state = super::session::RunState::Running;
+ }
+ self.send(
+ |reply| PumpCmd::StepInto { tid, reply },
+ Duration::from_secs(5),
+ )?
+ }
+
+ pub fn step_over(&self, tid: u32) -> Result<(), ProcessError> {
+ {
+ let mut g = self.shared.lock().unwrap_or_else(|e| e.into_inner());
+ g.last_stop = None;
+ g.run_state = super::session::RunState::Running;
+ }
+ self.send(
+ |reply| PumpCmd::StepOver { tid, reply },
+ Duration::from_secs(5),
+ )?
+ }
+
+ pub fn stack(&self, tid: u32, max_frames: usize) -> Result<Vec<StackFrame>, ProcessError> {
+ self.send(
+ |reply| PumpCmd::Stack {
+ tid,
+ max_frames,
+ reply,
+ },
+ Duration::from_secs(5),
+ )?
+ }
+
+ pub fn threads(&self) -> Result<Vec<ThreadInfo>, ProcessError> {
+ self.send(|reply| PumpCmd::Threads { reply }, Duration::from_secs(5))?
+ }
+
+ pub fn run_state(&self) -> super::session::RunState {
+ self.shared
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .run_state
+ }
+
+ pub fn last_stop(&self) -> Option<StopEvent> {
+ self.shared
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .last_stop
+ .clone()
+ }
+
+ pub fn detach(mut self) -> Result<(), ProcessError> {
+ let r = self.send(|reply| PumpCmd::Detach { reply }, Duration::from_secs(10));
+ if let Some(j) = self.join.take() {
+ let _ = j.join();
+ }
+ r?
+ }
+}
+
+impl Drop for DebugSession {
+ fn drop(&mut self) {
+ let (tx, rx) = mpsc::channel();
+ let _ = self.cmd_tx.send(PumpCmd::Detach { reply: tx });
+ let _ = rx.recv_timeout(Duration::from_secs(3));
+ if let Some(j) = self.join.take() {
+ let _ = j.join();
+ }
+ }
+}
+
+fn pump_loop(
+ pid: u32,
+ process: HANDLE,
+ _primary_tid: Option<u32>,
+ cmd_rx: Receiver<PumpCmd>,
+ shared: Arc<Mutex<SharedDebug>>,
+) {
+ let mut bps: HashMap<u64, SoftBp> = HashMap::new();
+ let mut addr_to_id: HashMap<u64, u64> = HashMap::new();
+ let mut pending: Option<DEBUG_EVENT> = None;
+ let mut stopped = false;
+ let mut exited = false;
+ let mut first_bp_seen = false;
+
+ // Drain initial debug events until first chance to stop (create process + system BP).
+ loop {
+ // Handle commands when stopped or always try_recv lightly.
+ match cmd_rx.try_recv() {
+ Ok(cmd) => {
+ handle_cmd(
+ cmd,
+ pid,
+ process,
+ &mut bps,
+ &mut addr_to_id,
+ &mut pending,
+ &mut stopped,
+ &mut exited,
+ &shared,
+ );
+ if exited {
+ return;
+ }
+ }
+ Err(TryRecvError::Disconnected) => return,
+ Err(TryRecvError::Empty) => {}
+ }
+
+ if exited {
+ return;
+ }
+
+ if stopped {
+ // Block for command while stopped.
+ match cmd_rx.recv_timeout(Duration::from_millis(50)) {
+ Ok(cmd) => {
+ handle_cmd(
+ cmd,
+ pid,
+ process,
+ &mut bps,
+ &mut addr_to_id,
+ &mut pending,
+ &mut stopped,
+ &mut exited,
+ &shared,
+ );
+ }
+ Err(RecvTimeoutError::Timeout) => continue,
+ Err(RecvTimeoutError::Disconnected) => return,
+ }
+ continue;
+ }
+
+ let mut ev: DEBUG_EVENT = unsafe { zeroed() };
+ let ok = unsafe { WaitForDebugEvent(&mut ev, 50) };
+ if ok == 0 {
+ continue;
+ }
+
+ let mut cont_status = DBG_CONTINUE;
+ let mut should_stop = false;
+ let mut stop_ev: Option<StopEvent> = None;
+
+ match ev.dw_debug_event_code {
+ CREATE_PROCESS_DEBUG_EVENT => {
+ let h = ev.create_process_h_file();
+ if h != 0 && h != -1 {
+ unsafe {
+ let _ = CloseHandle(h);
+ }
+ }
+ }
+ LOAD_DLL_DEBUG_EVENT => {
+ let h = ev.load_dll_h_file();
+ if h != 0 && h != -1 {
+ unsafe {
+ let _ = CloseHandle(h);
+ }
+ }
+ }
+ EXIT_PROCESS_DEBUG_EVENT => {
+ exited = true;
+ should_stop = true;
+ stop_ev = Some(StopEvent {
+ reason: "exit".into(),
+ thread_id: ev.dw_thread_id,
+ rip: 0,
+ registers: None,
+ module: None,
+ rva: None,
+ insn_preview: None,
+ bp_id: None,
+ exception_code: None,
+ fault_va: None,
+ });
+ }
+ EXCEPTION_DEBUG_EVENT => {
+ let code = ev.exception_code();
+ let addr = ev.exception_address();
+ let first = ev.exception_first_chance() != 0;
+ if code == EXCEPTION_BREAKPOINT {
+ // System initial BP vs our INT3.
+ let mut our_bp = false;
+ let mut bp_id = None;
+ let check_addr = addr.saturating_sub(1); // RIP often after INT3
+ if let Some(&id) = addr_to_id.get(&check_addr).or_else(|| addr_to_id.get(&addr))
+ {
+ if let Some(bp) = bps.get_mut(&id) {
+ our_bp = true;
+ bp_id = Some(id);
+ // Restore original byte.
+ if let Err(e) = win_observe::write_mem(process, bp.addr, &[bp.original])
+ {
+ let _ = e;
+ } else {
+ unsafe {
+ let _ = FlushInstructionCache(
+ process,
+ bp.addr as *const u8,
+ 1,
+ );
+ }
+ }
+ // Back up RIP onto the restored instruction.
+ if let Ok(mut regs) = get_thread_regs(ev.dw_thread_id) {
+ if regs.rip == bp.addr.wrapping_add(1) || regs.rip == addr {
+ regs.rip = bp.addr;
+ let _ = set_thread_regs(ev.dw_thread_id, &regs);
+ }
+ }
+ if bp.oneshot {
+ bp.enabled = false;
+ addr_to_id.remove(&bp.addr);
+ }
+ }
+ }
+ if our_bp || !first_bp_seen {
+ first_bp_seen = true;
+ should_stop = true;
+ let regs = get_thread_regs(ev.dw_thread_id).ok();
+ let rip = regs.as_ref().map(|r| r.rip).unwrap_or(addr);
+ stop_ev = Some(StopEvent {
+ reason: if our_bp {
+ "breakpoint".into()
+ } else {
+ "initial_break".into()
+ },
+ thread_id: ev.dw_thread_id,
+ rip,
+ registers: regs,
+ module: None,
+ rva: None,
+ insn_preview: insn_preview(process, rip),
+ bp_id,
+ exception_code: Some(code),
+ fault_va: Some(addr),
+ });
+ } else {
+ // Unrelated BP — pass along.
+ cont_status = DBG_CONTINUE;
+ }
+ } else if code == EXCEPTION_SINGLE_STEP {
+ should_stop = true;
+ let regs = get_thread_regs(ev.dw_thread_id).ok();
+ let rip = regs.as_ref().map(|r| r.rip).unwrap_or(addr);
+ stop_ev = Some(StopEvent {
+ reason: "step".into(),
+ thread_id: ev.dw_thread_id,
+ rip,
+ registers: regs,
+ module: None,
+ rva: None,
+ insn_preview: insn_preview(process, rip),
+ bp_id: None,
+ exception_code: Some(code),
+ fault_va: Some(addr),
+ });
+ } else if first {
+ // First-chance: stop and let agent decide (default break).
+ should_stop = true;
+ let regs = get_thread_regs(ev.dw_thread_id).ok();
+ let rip = regs.as_ref().map(|r| r.rip).unwrap_or(addr);
+ stop_ev = Some(StopEvent {
+ reason: "exception".into(),
+ thread_id: ev.dw_thread_id,
+ rip,
+ registers: regs,
+ module: None,
+ rva: None,
+ insn_preview: insn_preview(process, rip),
+ bp_id: None,
+ exception_code: Some(code),
+ fault_va: Some(addr),
+ });
+ } else {
+ cont_status = DBG_EXCEPTION_NOT_HANDLED;
+ }
+ }
+ _ => {}
+ }
+
+ if should_stop {
+ pending = Some(ev);
+ stopped = true;
+ if let Some(se) = stop_ev {
+ let mut g = shared.lock().unwrap_or_else(|e| e.into_inner());
+ g.last_stop = Some(se);
+ g.exited = exited;
+ g.run_state = if exited {
+ super::session::RunState::Exited
+ } else {
+ super::session::RunState::Stopped
+ };
+ }
+ // Do not ContinueDebugEvent until Continue cmd.
+ } else {
+ unsafe {
+ let _ = ContinueDebugEvent(ev.dw_process_id, ev.dw_thread_id, cont_status);
+ }
+ }
+ }
+}
+
+fn handle_cmd(
+ cmd: PumpCmd,
+ pid: u32,
+ process: HANDLE,
+ bps: &mut HashMap<u64, SoftBp>,
+ addr_to_id: &mut HashMap<u64, u64>,
+ pending: &mut Option<DEBUG_EVENT>,
+ stopped: &mut bool,
+ exited: &mut bool,
+ shared: &Arc<Mutex<SharedDebug>>,
+) {
+ match cmd {
+ PumpCmd::Continue { reply } => {
+ // Re-arm enabled software BPs (skip oneshot already fired).
+ for bp in bps.values() {
+ if bp.enabled {
+ let _ = win_observe::write_mem(process, bp.addr, &[0xCC]);
+ unsafe {
+ let _ = FlushInstructionCache(process, bp.addr as *const u8, 1);
+ }
+ }
+ }
+ if let Some(ev) = pending.take() {
+ unsafe {
+ let _ = ContinueDebugEvent(ev.dw_process_id, ev.dw_thread_id, DBG_CONTINUE);
+ }
+ *stopped = false;
+ let mut g = shared.lock().unwrap_or_else(|e| e.into_inner());
+ g.run_state = super::session::RunState::Running;
+ g.last_stop = None;
+ let _ = reply.send(Ok(()));
+ } else if *exited {
+ let _ = reply.send(Err(ProcessError::new(
+ ProcessErrorCode::ProcessExited,
+ "debuggee already exited",
+ )));
+ } else {
+ *stopped = false;
+ let mut g = shared.lock().unwrap_or_else(|e| e.into_inner());
+ g.run_state = super::session::RunState::Running;
+ let _ = reply.send(Ok(()));
+ }
+ }
+ PumpCmd::Pause { reply } => {
+ let ok = unsafe { DebugBreakProcess(process) };
+ if ok == 0 {
+ let _ = reply.send(Err(map_win32_message(
+ unsafe { GetLastError() },
+ "DebugBreakProcess failed",
+ )));
+ } else {
+ let _ = reply.send(Ok(()));
+ }
+ }
+ PumpCmd::SetSoftBp {
+ addr,
+ oneshot,
+ reply,
+ } => {
+ if addr_to_id.contains_key(&addr) {
+ let id = addr_to_id[&addr];
+ let bp = &bps[&id];
+ let _ = reply.send(Ok(BreakpointInfo {
+ id: bp.id,
+ addr: bp.addr,
+ kind: BreakKind::Software,
+ oneshot: bp.oneshot,
+ enabled: bp.enabled,
+ }));
+ return;
+ }
+ let rr = win_observe::read_mem(process, addr, 1);
+ if rr.bytes_read != 1 {
+ let _ = reply.send(Err(ProcessError::new(
+ ProcessErrorCode::AccessDenied,
+ format!("cannot read byte at {addr:#x} for software BP"),
+ )));
+ return;
+ }
+ let original = rr.bytes[0];
+ if let Err(e) = win_observe::write_mem(process, addr, &[0xCC]) {
+ let _ = reply.send(Err(e));
+ return;
+ }
+ unsafe {
+ let _ = FlushInstructionCache(process, addr as *const u8, 1);
+ }
+ let mut g = shared.lock().unwrap_or_else(|e| e.into_inner());
+ let id = g.next_bp_id;
+ g.next_bp_id += 1;
+ drop(g);
+ bps.insert(
+ id,
+ SoftBp {
+ id,
+ addr,
+ original,
+ oneshot,
+ enabled: true,
+ },
+ );
+ addr_to_id.insert(addr, id);
+ let _ = reply.send(Ok(BreakpointInfo {
+ id,
+ addr,
+ kind: BreakKind::Software,
+ oneshot,
+ enabled: true,
+ }));
+ }
+ PumpCmd::ClearBp { id, addr, reply } => {
+ let id = id.or_else(|| addr.and_then(|a| addr_to_id.get(&a).copied()));
+ let Some(id) = id else {
+ let _ = reply.send(Err(ProcessError::new(
+ ProcessErrorCode::NotFound,
+ "breakpoint not found",
+ )));
+ return;
+ };
+ if let Some(bp) = bps.remove(&id) {
+ addr_to_id.remove(&bp.addr);
+ if let Err(e) = win_observe::write_mem(process, bp.addr, &[bp.original]) {
+ let _ = reply.send(Err(ProcessError::new(
+ ProcessErrorCode::BpRestoreFailed,
+ e.message,
+ )));
+ return;
+ }
+ unsafe {
+ let _ = FlushInstructionCache(process, bp.addr as *const u8, 1);
+ }
+ }
+ let _ = reply.send(Ok(()));
+ }
+ PumpCmd::ListBp { reply } => {
+ let list: Vec<_> = bps
+ .values()
+ .map(|bp| BreakpointInfo {
+ id: bp.id,
+ addr: bp.addr,
+ kind: BreakKind::Software,
+ oneshot: bp.oneshot,
+ enabled: bp.enabled,
+ })
+ .collect();
+ let _ = reply.send(list);
+ }
+ PumpCmd::GetContext { tid, reply } => {
+ let _ = reply.send(get_thread_regs(tid));
+ }
+ PumpCmd::SetContext { tid, regs, reply } => {
+ let _ = reply.send(set_thread_regs(tid, &regs));
+ }
+ PumpCmd::StepInto { tid, reply } => {
+ match set_tf(tid, true) {
+ Ok(()) => {
+ if let Some(ev) = pending.take() {
+ unsafe {
+ let _ =
+ ContinueDebugEvent(ev.dw_process_id, ev.dw_thread_id, DBG_CONTINUE);
+ }
+ }
+ *stopped = false;
+ let mut g = shared.lock().unwrap_or_else(|e| e.into_inner());
+ g.run_state = super::session::RunState::Running;
+ g.last_stop = None;
+ let _ = reply.send(Ok(()));
+ }
+ Err(e) => {
+ let _ = reply.send(Err(e));
+ }
+ }
+ }
+ PumpCmd::StepOver { tid, reply } => {
+ // Prefer TF for simplicity (step-over = step-into for non-call; call handling: TF too).
+ // Full call-skip would need length disasm; TF is honest MVP.
+ match set_tf(tid, true) {
+ Ok(()) => {
+ if let Some(ev) = pending.take() {
+ unsafe {
+ let _ =
+ ContinueDebugEvent(ev.dw_process_id, ev.dw_thread_id, DBG_CONTINUE);
+ }
+ }
+ *stopped = false;
+ let mut g = shared.lock().unwrap_or_else(|e| e.into_inner());
+ g.run_state = super::session::RunState::Running;
+ g.last_stop = None;
+ let _ = reply.send(Ok(()));
+ }
+ Err(e) => {
+ let _ = reply.send(Err(e));
+ }
+ }
+ }
+ PumpCmd::Stack {
+ tid,
+ max_frames,
+ reply,
+ } => {
+ let _ = reply.send(unwind_stack(process, tid, max_frames));
+ }
+ PumpCmd::Threads { reply } => {
+ let r = win_observe::list_threads(pid).map(|ids| {
+ ids.into_iter()
+ .map(|thread_id| ThreadInfo {
+ thread_id,
+ name: None,
+ })
+ .collect()
+ });
+ let _ = reply.send(r);
+ }
+ PumpCmd::Detach { reply } => {
+ // Restore all BP originals.
+ for bp in bps.values() {
+ let _ = win_observe::write_mem(process, bp.addr, &[bp.original]);
+ }
+ bps.clear();
+ addr_to_id.clear();
+ if let Some(ev) = pending.take() {
+ unsafe {
+ let _ = ContinueDebugEvent(ev.dw_process_id, ev.dw_thread_id, DBG_CONTINUE);
+ }
+ }
+ // Drain remaining events briefly while detaching.
+ for _ in 0..32 {
+ let mut ev: DEBUG_EVENT = unsafe { zeroed() };
+ let ok = unsafe { WaitForDebugEvent(&mut ev, 10) };
+ if ok == 0 {
+ break;
+ }
+ if ev.dw_debug_event_code == EXIT_PROCESS_DEBUG_EVENT {
+ *exited = true;
+ }
+ unsafe {
+ let _ = ContinueDebugEvent(ev.dw_process_id, ev.dw_thread_id, DBG_CONTINUE);
+ }
+ }
+ let r = win_observe::debug_active_process_stop(pid);
+ *exited = true;
+ let mut g = shared.lock().unwrap_or_else(|e| e.into_inner());
+ g.exited = true;
+ g.run_state = super::session::RunState::Detached;
+ let _ = reply.send(r);
+ }
+ }
+}
+
+fn open_thread(tid: u32) -> Result<HANDLE, ProcessError> {
+ let access =
+ THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME | THREAD_QUERY_INFORMATION;
+ let h = unsafe { OpenThread(access, 0, tid) };
+ if h == 0 {
+ return Err(map_win32_message(
+ unsafe { GetLastError() },
+ &format!("OpenThread({tid}) failed"),
+ ));
+ }
+ Ok(h)
+}
+
+fn get_thread_regs(tid: u32) -> Result<RegisterSet, ProcessError> {
+ let h = open_thread(tid)?;
+ let mut ctx: CONTEXT = unsafe { zeroed() };
+ ctx.context_flags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
+ // Suspend for stable context.
+ unsafe {
+ let _ = SuspendThread(h);
+ }
+ let ok = unsafe { GetThreadContext(h, &mut ctx) };
+ unsafe {
+ let _ = ResumeThread(h);
+ let _ = CloseHandle(h);
+ }
+ if ok == 0 {
+ return Err(map_win32_message(
+ unsafe { GetLastError() },
+ "GetThreadContext failed",
+ ));
+ }
+ Ok(RegisterSet {
+ rax: ctx.rax,
+ rbx: ctx.rbx,
+ rcx: ctx.rcx,
+ rdx: ctx.rdx,
+ rsi: ctx.rsi,
+ rdi: ctx.rdi,
+ rbp: ctx.rbp,
+ rsp: ctx.rsp,
+ r8: ctx.r8,
+ r9: ctx.r9,
+ r10: ctx.r10,
+ r11: ctx.r11,
+ r12: ctx.r12,
+ r13: ctx.r13,
+ r14: ctx.r14,
+ r15: ctx.r15,
+ rip: ctx.rip,
+ rflags: ctx.e_flags as u64,
+ })
+}
+
+fn set_thread_regs(tid: u32, regs: &RegisterSet) -> Result<(), ProcessError> {
+ let h = open_thread(tid)?;
+ let mut ctx: CONTEXT = unsafe { zeroed() };
+ ctx.context_flags = CONTEXT_FULL;
+ unsafe {
+ let _ = SuspendThread(h);
+ }
+ let ok_get = unsafe { GetThreadContext(h, &mut ctx) };
+ if ok_get == 0 {
+ unsafe {
+ let _ = ResumeThread(h);
+ let _ = CloseHandle(h);
+ }
+ return Err(map_win32_message(
+ unsafe { GetLastError() },
+ "GetThreadContext failed before set",
+ ));
+ }
+ ctx.rax = regs.rax;
+ ctx.rbx = regs.rbx;
+ ctx.rcx = regs.rcx;
+ ctx.rdx = regs.rdx;
+ ctx.rsi = regs.rsi;
+ ctx.rdi = regs.rdi;
+ ctx.rbp = regs.rbp;
+ ctx.rsp = regs.rsp;
+ ctx.r8 = regs.r8;
+ ctx.r9 = regs.r9;
+ ctx.r10 = regs.r10;
+ ctx.r11 = regs.r11;
+ ctx.r12 = regs.r12;
+ ctx.r13 = regs.r13;
+ ctx.r14 = regs.r14;
+ ctx.r15 = regs.r15;
+ ctx.rip = regs.rip;
+ ctx.e_flags = regs.rflags as DWORD;
+ let ok = unsafe { SetThreadContext(h, &ctx) };
+ unsafe {
+ let _ = ResumeThread(h);
+ let _ = CloseHandle(h);
+ }
+ if ok == 0 {
+ return Err(map_win32_message(
+ unsafe { GetLastError() },
+ "SetThreadContext failed",
+ ));
+ }
+ Ok(())
+}
+
+fn set_tf(tid: u32, on: bool) -> Result<(), ProcessError> {
+ let mut regs = get_thread_regs(tid)?;
+ if on {
+ regs.rflags |= EFLAGS_TF;
+ } else {
+ regs.rflags &= !EFLAGS_TF;
+ }
+ set_thread_regs(tid, &regs)
+}
+
+fn insn_preview(process: HANDLE, rip: u64) -> Option<String> {
+ let r = win_observe::read_mem(process, rip, 16);
+ if r.bytes_read == 0 {
+ return None;
+ }
+ Some(r.hex)
+}
+
+fn unwind_stack(process: HANDLE, tid: u32, max_frames: usize) -> Result<Vec<StackFrame>, ProcessError> {
+ let regs = get_thread_regs(tid)?;
+ let mut frames = Vec::new();
+ let mut rip = regs.rip;
+ let mut rsp = regs.rsp;
+ let mut rbp = regs.rbp;
+ let max_frames = max_frames.clamp(1, 256);
+
+ for level in 0..max_frames as u32 {
+ frames.push(StackFrame {
+ level,
+ sp: rsp,
+ rip,
+ module: None,
+ rva: None,
+ symbol: None,
+ });
+ // Prefer RBP chain as a simple portable unwind when pdata is sparse.
+ if rbp == 0 || rbp < 0x10000 {
+ break;
+ }
+ // Read [rbp] = saved rbp, [rbp+8] = return address
+ let frame = win_observe::read_mem(process, rbp, 16);
+ if frame.bytes_read < 16 {
+ break;
+ }
+ let next_rbp = u64::from_le_bytes(frame.bytes[0..8].try_into().unwrap());
+ let ret = u64::from_le_bytes(frame.bytes[8..16].try_into().unwrap());
+ if ret == 0 || ret == rip {
+ break;
+ }
+ // Optional: RtlLookupFunctionEntry for honesty when available
+ let mut image_base = 0u64;
+ let entry = unsafe { RtlLookupFunctionEntry(rip, &mut image_base, std::ptr::null_mut()) };
+ let _ = entry;
+
+ rsp = rbp.wrapping_add(16);
+ rbp = next_rbp;
+ rip = ret;
+ }
+ Ok(frames)
+}
+
+/// Best-effort enable SeDebugPrivilege for the current process.
+pub fn try_enable_debug_privilege() -> bool {
+ // Minimal: skip full AdjustTokenPrivileges FFI for now; return false honestly.
+ // Full implementation can be added without changing the API surface.
+ false
+}
diff --git a/crates/ghidrust-core/src/process/win_observe.rs b/crates/ghidrust-core/src/process/win_observe.rs
new file mode 100644
index 0000000..2e31513
--- /dev/null
+++ b/crates/ghidrust-core/src/process/win_observe.rs
@@ -0,0 +1,595 @@
+//! Windows observe backend: list / OpenProcess(VM_READ) / modules / read / regions / CREATE_SUSPENDED launch.
+
+use super::error::{map_win32_message, ProcessError, ProcessErrorCode};
+use super::types::{ModuleInfo, ProcessInfo, ReadResult, RegionInfo};
+use std::ffi::{OsStr, OsString};
+use std::mem::{size_of, zeroed};
+use std::os::windows::ffi::{OsStrExt, OsStringExt};
+use std::path::Path;
+use std::ptr;
+
+pub type HANDLE = isize;
+type BOOL = i32;
+type DWORD = u32;
+type SizeT = usize;
+
+const PROCESS_QUERY_INFORMATION: DWORD = 0x0400;
+const PROCESS_VM_READ: DWORD = 0x0010;
+const PROCESS_VM_WRITE: DWORD = 0x0020;
+const PROCESS_VM_OPERATION: DWORD = 0x0008;
+const PROCESS_QUERY_LIMITED_INFORMATION: DWORD = 0x1000;
+const PROCESS_SUSPEND_RESUME: DWORD = 0x0800;
+const PROCESS_CREATE_THREAD: DWORD = 0x0002;
+const SYNCHRONIZE: DWORD = 0x0010_0000;
+const TH32CS_SNAPPROCESS: DWORD = 0x0000_0002;
+const TH32CS_SNAPMODULE: DWORD = 0x0000_0008;
+const TH32CS_SNAPMODULE32: DWORD = 0x0000_0010;
+const TH32CS_SNAPTHREAD: DWORD = 0x0000_0004;
+const INVALID_HANDLE_VALUE: HANDLE = -1;
+const MEM_COMMIT: DWORD = 0x1000;
+const MEM_FREE: DWORD = 0x10000;
+const MEM_RESERVE: DWORD = 0x2000;
+const CREATE_SUSPENDED: DWORD = 0x0000_0004;
+const CREATE_UNICODE_ENVIRONMENT: DWORD = 0x0000_0400;
+const DEBUG_ONLY_THIS_PROCESS: DWORD = 0x0000_0002;
+const DEBUG_PROCESS: DWORD = 0x0000_0001;
+const MAX_PATH: usize = 260;
+
+#[repr(C)]
+struct STARTUPINFOW {
+ cb: DWORD,
+ lp_reserved: *mut u16,
+ lp_desktop: *mut u16,
+ lp_title: *mut u16,
+ dw_x: DWORD,
+ dw_y: DWORD,
+ dw_x_size: DWORD,
+ dw_y_size: DWORD,
+ dw_x_count_chars: DWORD,
+ dw_y_count_chars: DWORD,
+ dw_fill_attribute: DWORD,
+ dw_flags: DWORD,
+ w_show_window: u16,
+ cb_reserved2: u16,
+ lp_reserved2: *mut u8,
+ h_std_input: HANDLE,
+ h_std_output: HANDLE,
+ h_std_error: HANDLE,
+}
+
+#[repr(C)]
+struct PROCESS_INFORMATION {
+ h_process: HANDLE,
+ h_thread: HANDLE,
+ dw_process_id: DWORD,
+ dw_thread_id: DWORD,
+}
+
+#[repr(C)]
+struct PROCESSENTRY32W {
+ dw_size: DWORD,
+ cnt_usage: DWORD,
+ th32_process_id: DWORD,
+ th32_default_heap_id: usize,
+ th32_module_id: DWORD,
+ cnt_threads: DWORD,
+ th32_parent_process_id: DWORD,
+ pc_pri_class_base: i32,
+ dw_flags: DWORD,
+ sz_exe_file: [u16; MAX_PATH],
+}
+
+#[repr(C)]
+struct MODULEENTRY32W {
+ dw_size: DWORD,
+ th32_module_id: DWORD,
+ th32_process_id: DWORD,
+ glblcnt_usage: DWORD,
+ proccnt_usage: DWORD,
+ mod_base_addr: *mut u8,
+ mod_base_size: DWORD,
+ h_module: HANDLE,
+ sz_module: [u16; 256],
+ sz_exe_path: [u16; MAX_PATH],
+}
+
+#[repr(C)]
+struct THREADENTRY32 {
+ dw_size: DWORD,
+ cnt_usage: DWORD,
+ th32_thread_id: DWORD,
+ th32_owner_process_id: DWORD,
+ tp_base_pri: i32,
+ tp_delta_pri: i32,
+ dw_flags: DWORD,
+}
+
+#[repr(C)]
+struct MEMORY_BASIC_INFORMATION {
+ base_address: *mut u8,
+ allocation_base: *mut u8,
+ allocation_protect: DWORD,
+ region_size: SizeT,
+ state: DWORD,
+ protect: DWORD,
+ typ: DWORD,
+}
+
+#[link(name = "kernel32")]
+extern "system" {
+ fn OpenProcess(access: DWORD, inherit: BOOL, pid: DWORD) -> HANDLE;
+ fn CloseHandle(h: HANDLE) -> BOOL;
+ fn ReadProcessMemory(
+ h: HANDLE,
+ addr: *const u8,
+ buf: *mut u8,
+ size: SizeT,
+ read: *mut SizeT,
+ ) -> BOOL;
+ fn WriteProcessMemory(
+ h: HANDLE,
+ addr: *mut u8,
+ buf: *const u8,
+ size: SizeT,
+ written: *mut SizeT,
+ ) -> BOOL;
+ fn VirtualQueryEx(
+ h: HANDLE,
+ addr: *const u8,
+ info: *mut MEMORY_BASIC_INFORMATION,
+ len: SizeT,
+ ) -> SizeT;
+ fn CreateToolhelp32Snapshot(flags: DWORD, pid: DWORD) -> HANDLE;
+ fn Process32FirstW(snap: HANDLE, pe: *mut PROCESSENTRY32W) -> BOOL;
+ fn Process32NextW(snap: HANDLE, pe: *mut PROCESSENTRY32W) -> BOOL;
+ fn Module32FirstW(snap: HANDLE, me: *mut MODULEENTRY32W) -> BOOL;
+ fn Module32NextW(snap: HANDLE, me: *mut MODULEENTRY32W) -> BOOL;
+ fn Thread32First(snap: HANDLE, te: *mut THREADENTRY32) -> BOOL;
+ fn Thread32Next(snap: HANDLE, te: *mut THREADENTRY32) -> BOOL;
+ fn QueryFullProcessImageNameW(h: HANDLE, flags: DWORD, buf: *mut u16, size: *mut DWORD)
+ -> BOOL;
+ fn CreateProcessW(
+ app: *const u16,
+ cmdline: *mut u16,
+ proc_attr: *const u8,
+ thread_attr: *const u8,
+ inherit: BOOL,
+ flags: DWORD,
+ env: *const u8,
+ cwd: *const u16,
+ si: *const STARTUPINFOW,
+ pi: *mut PROCESS_INFORMATION,
+ ) -> BOOL;
+ fn ResumeThread(h: HANDLE) -> DWORD;
+ fn GetLastError() -> DWORD;
+ fn DebugActiveProcess(pid: DWORD) -> BOOL;
+ fn DebugActiveProcessStop(pid: DWORD) -> BOOL;
+ fn DebugSetProcessKillOnExit(kill: BOOL) -> BOOL;
+ fn IsWow64Process(h: HANDLE, wow: *mut BOOL) -> BOOL;
+}
+
+fn to_wide_z(s: &str) -> Vec<u16> {
+ let mut v: Vec<u16> = OsStr::new(s).encode_wide().collect();
+ v.push(0);
+ v
+}
+
+fn wide_to_string(w: &[u16]) -> String {
+ let len = w.iter().position(|&c| c == 0).unwrap_or(w.len());
+ OsString::from_wide(&w[..len])
+ .to_string_lossy()
+ .into_owned()
+}
+
+pub fn build_command_line(image: &Path, args: Option<&str>) -> String {
+ let img = image.to_string_lossy();
+ let quoted = if img.contains(char::is_whitespace) || img.contains('"') {
+ format!("\"{}\"", img.replace('"', ""))
+ } else {
+ img.into_owned()
+ };
+ match args.map(str::trim).filter(|a| !a.is_empty()) {
+ Some(a) => format!("{quoted} {a}"),
+ None => quoted,
+ }
+}
+
+pub fn last_error() -> u32 {
+ unsafe { GetLastError() }
+}
+
+pub fn close(h: HANDLE) {
+ unsafe {
+ let _ = CloseHandle(h);
+ }
+}
+
+pub fn resume_thread(h: HANDLE) -> Result<(), ProcessError> {
+ let prev = unsafe { ResumeThread(h) };
+ if prev == DWORD::MAX {
+ return Err(map_win32_message(last_error(), "ResumeThread failed"));
+ }
+ Ok(())
+}
+
+pub fn list_processes() -> Result<Vec<ProcessInfo>, ProcessError> {
+ let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
+ if snap == 0 || snap == INVALID_HANDLE_VALUE {
+ return Err(ProcessError::new(
+ ProcessErrorCode::Internal,
+ "CreateToolhelp32Snapshot failed",
+ ));
+ }
+ let mut out = Vec::new();
+ let mut pe: PROCESSENTRY32W = unsafe { zeroed() };
+ pe.dw_size = size_of::<PROCESSENTRY32W>() as DWORD;
+ let mut ok = unsafe { Process32FirstW(snap, &mut pe) };
+ while ok != 0 {
+ let name = wide_to_string(&pe.sz_exe_file);
+ let pid = pe.th32_process_id;
+ let path = open_query_path(pid);
+ out.push(ProcessInfo { pid, name, path });
+ ok = unsafe { Process32NextW(snap, &mut pe) };
+ }
+ close(snap);
+ out.sort_by(|a, b| {
+ a.name
+ .to_ascii_lowercase()
+ .cmp(&b.name.to_ascii_lowercase())
+ });
+ Ok(out)
+}
+
+fn open_query_path(pid: u32) -> Option<String> {
+ let h = unsafe {
+ OpenProcess(
+ PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_QUERY_INFORMATION,
+ 0,
+ pid,
+ )
+ };
+ if h == 0 {
+ return None;
+ }
+ let mut buf = [0u16; 1024];
+ let mut size = buf.len() as DWORD;
+ let ok = unsafe { QueryFullProcessImageNameW(h, 0, buf.as_mut_ptr(), &mut size) };
+ close(h);
+ if ok == 0 {
+ return None;
+ }
+ Some(wide_to_string(&buf[..size as usize]))
+}
+
+/// Observe attach: VM_READ + query.
+pub fn attach_observe(pid: u32) -> Result<HANDLE, ProcessError> {
+ let access = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_QUERY_LIMITED_INFORMATION;
+ let h = unsafe { OpenProcess(access, 0, pid) };
+ if h == 0 {
+ return Err(map_win32_message(
+ last_error(),
+ &format!("OpenProcess({pid}) observe attach failed"),
+ ));
+ }
+ check_wow64(h)?;
+ Ok(h)
+}
+
+/// Broader rights for debug software BP (still used with DebugActiveProcess).
+pub fn open_process_debug_rights(pid: u32) -> Result<HANDLE, ProcessError> {
+ let access = PROCESS_QUERY_INFORMATION
+ | PROCESS_QUERY_LIMITED_INFORMATION
+ | PROCESS_VM_READ
+ | PROCESS_VM_WRITE
+ | PROCESS_VM_OPERATION
+ | PROCESS_SUSPEND_RESUME
+ | PROCESS_CREATE_THREAD
+ | SYNCHRONIZE;
+ let h = unsafe { OpenProcess(access, 0, pid) };
+ if h == 0 {
+ return Err(map_win32_message(
+ last_error(),
+ &format!("OpenProcess({pid}) debug rights failed"),
+ ));
+ }
+ check_wow64(h)?;
+ Ok(h)
+}
+
+fn check_wow64(h: HANDLE) -> Result<(), ProcessError> {
+ let mut wow: BOOL = 0;
+ let ok = unsafe { IsWow64Process(h, &mut wow) };
+ if ok != 0 && wow != 0 {
+ return Err(ProcessError::new(
+ ProcessErrorCode::Wow64Rejected,
+ "target is WOW64 (32-bit); use a 32-bit tool or 64-bit target — rejected for honesty",
+ ));
+ }
+ Ok(())
+}
+
+pub fn debug_active_process(pid: u32) -> Result<(), ProcessError> {
+ let ok = unsafe { DebugActiveProcess(pid) };
+ if ok == 0 {
+ return Err(map_win32_message(
+ last_error(),
+ &format!("DebugActiveProcess({pid}) failed"),
+ ));
+ }
+ unsafe {
+ let _ = DebugSetProcessKillOnExit(0);
+ }
+ Ok(())
+}
+
+pub fn debug_active_process_stop(pid: u32) -> Result<(), ProcessError> {
+ let ok = unsafe { DebugActiveProcessStop(pid) };
+ if ok == 0 {
+ return Err(map_win32_message(
+ last_error(),
+ &format!("DebugActiveProcessStop({pid}) failed"),
+ ));
+ }
+ Ok(())
+}
+
+pub fn launch_observe(
+ image: &Path,
+ args: Option<&str>,
+ cwd: Option<&Path>,
+) -> Result<(HANDLE, HANDLE, u32, u32, String), ProcessError> {
+ launch_with_flags(image, args, cwd, CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT)
+}
+
+pub fn launch_debug(
+ image: &Path,
+ args: Option<&str>,
+ cwd: Option<&Path>,
+ suspended: bool,
+) -> Result<(HANDLE, HANDLE, u32, u32, String), ProcessError> {
+ let mut flags = DEBUG_ONLY_THIS_PROCESS | CREATE_UNICODE_ENVIRONMENT;
+ if suspended {
+ flags |= CREATE_SUSPENDED;
+ }
+ // Also allow DEBUG_PROCESS for child inheritance off — ONLY_THIS is enough.
+ let _ = DEBUG_PROCESS;
+ launch_with_flags(image, args, cwd, flags)
+}
+
+fn launch_with_flags(
+ image: &Path,
+ args: Option<&str>,
+ cwd: Option<&Path>,
+ flags: DWORD,
+) -> Result<(HANDLE, HANDLE, u32, u32, String), ProcessError> {
+ if !image.is_file() {
+ return Err(ProcessError::new(
+ ProcessErrorCode::NotFound,
+ format!("launch image not found or not a file: {}", image.display()),
+ ));
+ }
+ let image_str = image
+ .canonicalize()
+ .unwrap_or_else(|_| image.to_path_buf())
+ .to_string_lossy()
+ .into_owned();
+ let cmdline = build_command_line(Path::new(&image_str), args);
+ let mut cmdline_w = to_wide_z(&cmdline);
+ let cwd_w = cwd.map(|c| to_wide_z(&c.to_string_lossy()));
+ let mut si: STARTUPINFOW = unsafe { zeroed() };
+ si.cb = size_of::<STARTUPINFOW>() as DWORD;
+ let mut pi: PROCESS_INFORMATION = unsafe { zeroed() };
+ let ok = unsafe {
+ CreateProcessW(
+ ptr::null(),
+ cmdline_w.as_mut_ptr(),
+ ptr::null(),
+ ptr::null(),
+ 0,
+ flags,
+ ptr::null(),
+ cwd_w.as_ref().map(|v| v.as_ptr()).unwrap_or(ptr::null()),
+ &si,
+ &mut pi,
+ )
+ };
+ if ok == 0 {
+ return Err(map_win32_message(
+ last_error(),
+ &format!("CreateProcessW failed for {cmdline}"),
+ ));
+ }
+ if flags & DEBUG_ONLY_THIS_PROCESS != 0 {
+ unsafe {
+ let _ = DebugSetProcessKillOnExit(0);
+ }
+ }
+ Ok((
+ pi.h_process,
+ pi.h_thread,
+ pi.dw_process_id,
+ pi.dw_thread_id,
+ image_str,
+ ))
+}
+
+pub fn modules(_handle: HANDLE, pid: u32) -> Result<Vec<ModuleInfo>, ProcessError> {
+ let flags = TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32;
+ let snap = unsafe { CreateToolhelp32Snapshot(flags, pid) };
+ if snap == 0 || snap == INVALID_HANDLE_VALUE {
+ return Err(ProcessError::new(
+ ProcessErrorCode::AccessDenied,
+ "Module snapshot failed (32-bit tool vs 64-bit process, or access denied)",
+ ));
+ }
+ let mut out = Vec::new();
+ let mut me: MODULEENTRY32W = unsafe { zeroed() };
+ me.dw_size = size_of::<MODULEENTRY32W>() as DWORD;
+ let mut ok = unsafe { Module32FirstW(snap, &mut me) };
+ while ok != 0 {
+ let name = wide_to_string(&me.sz_module);
+ let path = {
+ let p = wide_to_string(&me.sz_exe_path);
+ if p.is_empty() {
+ None
+ } else {
+ Some(p)
+ }
+ };
+ out.push(ModuleInfo {
+ name,
+ path,
+ base: me.mod_base_addr as u64,
+ size: me.mod_base_size as u64,
+ });
+ ok = unsafe { Module32NextW(snap, &mut me) };
+ }
+ close(snap);
+ Ok(out)
+}
+
+pub fn list_threads(pid: u32) -> Result<Vec<u32>, ProcessError> {
+ let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
+ if snap == 0 || snap == INVALID_HANDLE_VALUE {
+ return Err(ProcessError::new(
+ ProcessErrorCode::Internal,
+ "thread snapshot failed",
+ ));
+ }
+ let mut out = Vec::new();
+ let mut te: THREADENTRY32 = unsafe { zeroed() };
+ te.dw_size = size_of::<THREADENTRY32>() as DWORD;
+ let mut ok = unsafe { Thread32First(snap, &mut te) };
+ while ok != 0 {
+ if te.th32_owner_process_id == pid {
+ out.push(te.th32_thread_id);
+ }
+ ok = unsafe { Thread32Next(snap, &mut te) };
+ }
+ close(snap);
+ Ok(out)
+}
+
+pub fn read_mem(handle: HANDLE, va: u64, size: usize) -> ReadResult {
+ let size = size.min(1024 * 1024);
+ let mut buf = vec![0u8; size];
+ let mut read: SizeT = 0;
+ let ok = unsafe {
+ ReadProcessMemory(handle, va as *const u8, buf.as_mut_ptr(), size, &mut read)
+ };
+ if ok == 0 {
+ return ReadResult {
+ va,
+ size_requested: size,
+ bytes_read: 0,
+ hex: String::new(),
+ bytes: vec![],
+ error: Some(format!(
+ "ReadProcessMemory failed (access denied or unmapped; GetLastError=0x{:x})",
+ last_error()
+ )),
+ as_u64: None,
+ as_f32: None,
+ };
+ }
+ buf.truncate(read);
+ let hex: String = buf
+ .iter()
+ .map(|b| format!("{b:02x}"))
+ .collect::<Vec<_>>()
+ .join(" ");
+ let as_u64 = if buf.len() >= 8 {
+ Some(
+ buf.chunks_exact(8)
+ .map(|c| u64::from_le_bytes(c.try_into().unwrap()))
+ .collect(),
+ )
+ } else {
+ None
+ };
+ let as_f32 = if buf.len() >= 4 {
+ Some(
+ buf.chunks_exact(4)
+ .map(|c| f32::from_le_bytes(c.try_into().unwrap()))
+ .collect(),
+ )
+ } else {
+ None
+ };
+ let error = if read < size {
+ Some(format!("short_read: got {read} of {size}"))
+ } else {
+ None
+ };
+ ReadResult {
+ va,
+ size_requested: size,
+ bytes_read: read,
+ hex,
+ bytes: buf,
+ error,
+ as_u64,
+ as_f32,
+ }
+}
+
+pub fn write_mem(handle: HANDLE, va: u64, data: &[u8]) -> Result<(), ProcessError> {
+ let mut written: SizeT = 0;
+ let ok = unsafe {
+ WriteProcessMemory(
+ handle,
+ va as *mut u8,
+ data.as_ptr(),
+ data.len(),
+ &mut written,
+ )
+ };
+ if ok == 0 || written != data.len() {
+ return Err(map_win32_message(
+ last_error(),
+ &format!("WriteProcessMemory failed at {va:#x}"),
+ ));
+ }
+ Ok(())
+}
+
+pub fn regions(handle: HANDLE, max: usize) -> Result<Vec<RegionInfo>, ProcessError> {
+ let mut out = Vec::new();
+ let mut addr: u64 = 0;
+ while out.len() < max {
+ let mut info: MEMORY_BASIC_INFORMATION = unsafe { zeroed() };
+ let n = unsafe {
+ VirtualQueryEx(
+ handle,
+ addr as *const u8,
+ &mut info,
+ size_of::<MEMORY_BASIC_INFORMATION>(),
+ )
+ };
+ if n == 0 {
+ break;
+ }
+ let base = info.base_address as u64;
+ let size = info.region_size as u64;
+ if info.state != MEM_FREE {
+ out.push(RegionInfo {
+ base,
+ size,
+ protect: format!("{:#x}", info.protect),
+ state: match info.state {
+ MEM_COMMIT => "commit".into(),
+ MEM_RESERVE => "reserve".into(),
+ MEM_FREE => "free".into(),
+ s => format!("{s:#x}"),
+ },
+ typ: format!("{:#x}", info.typ),
+ });
+ }
+ let next = base.saturating_add(size);
+ if next <= addr {
+ break;
+ }
+ addr = next;
+ }
+ Ok(out)
+}
diff --git a/crates/ghidrust-core/tests/process_debug_e2e.rs b/crates/ghidrust-core/tests/process_debug_e2e.rs
new file mode 100644
index 0000000..96ec8ea
--- /dev/null
+++ b/crates/ghidrust-core/tests/process_debug_e2e.rs
@@ -0,0 +1,131 @@
+//! Windows live-process debug E2E against the `live_debuggee` example.
+//!
+//! Build debuggee first:
+//! cargo build -p ghidrust-core --example live_debuggee
+//!
+//! Run:
+//! cargo test -p ghidrust-core --test process_debug_e2e -- --nocapture
+
+#![cfg(windows)]
+
+use ghidrust_core::{
+ process_break_set, process_continue, process_detach, process_launch, process_modules,
+ process_stack, process_step_into, process_threads, process_wait, BreakKind, LaunchRequest,
+ SessionMode,
+};
+use std::path::PathBuf;
+
+fn debuggee_path() -> Option<PathBuf> {
+ let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ p.pop(); // crates
+ p.pop(); // workspace
+ let candidates = [
+ p.join("target/debug/examples/live_debuggee.exe"),
+ p.join("target/release/examples/live_debuggee.exe"),
+ ];
+ candidates.into_iter().find(|c| c.is_file())
+}
+
+#[test]
+fn debug_launch_initial_break_and_detach() {
+ let Some(image) = debuggee_path() else {
+ eprintln!("skip: build live_debuggee example first");
+ return;
+ };
+ let r = process_launch(&LaunchRequest {
+ image,
+ args: None,
+ cwd: None,
+ mode: SessionMode::Debug,
+ break_at_entry: true,
+ });
+ let r = match r {
+ Ok(r) => r,
+ Err(e) => {
+ eprintln!("launch failed (env rights?): {e}");
+ return;
+ }
+ };
+ assert_eq!(r.session.mode, SessionMode::Debug);
+ assert!(r.session.capabilities.iter().any(|c| c == "break"));
+ let sid = r.session.session_id.clone();
+
+ // Should be stopped on initial breakpoint (or running after auto-continue race).
+ let wr = process_wait(&sid, 3000).expect("wait");
+ if wr.ok {
+ assert!(wr.event.is_some());
+ let ev = wr.event.unwrap();
+ assert!(
+ ev.reason == "initial_break" || ev.reason == "breakpoint" || ev.reason == "exception",
+ "reason={}",
+ ev.reason
+ );
+ assert!(ev.registers.is_some() || ev.rip != 0);
+ let tid = ev.thread_id;
+ let threads = process_threads(&sid).unwrap_or_default();
+ assert!(!threads.is_empty() || tid != 0);
+ let _ = process_stack(&sid, tid, 16);
+ let _ = process_continue(&sid);
+ }
+
+ process_detach(&sid).expect("detach");
+}
+
+#[test]
+fn debug_software_bp_on_module_entry() {
+ let Some(image) = debuggee_path() else {
+ eprintln!("skip: build live_debuggee example first");
+ return;
+ };
+ let r = match process_launch(&LaunchRequest {
+ image: image.clone(),
+ args: None,
+ cwd: None,
+ mode: SessionMode::Debug,
+ break_at_entry: true,
+ }) {
+ Ok(r) => r,
+ Err(e) => {
+ eprintln!("launch failed: {e}");
+ return;
+ }
+ };
+ let sid = r.session.session_id.clone();
+ let _ = process_wait(&sid, 3000);
+
+ // Module snapshot can fail while stopped under the debugger; continue first if needed.
+ let mods = match process_modules(&sid) {
+ Ok(m) => m,
+ Err(e) => {
+ eprintln!("modules soft-fail while stopped: {e}");
+ let _ = process_continue(&sid);
+ let _ = process_wait(&sid, 1000);
+ process_modules(&sid).unwrap_or_default()
+ }
+ };
+ if let Some(main) = mods
+ .iter()
+ .find(|m| m.name.to_ascii_lowercase().contains("live_debuggee"))
+ .or_else(|| mods.first())
+ {
+ // Set BP near common .text RVA; layout variance is soft-fail.
+ let bp_addr = main.base.wrapping_add(0x1000);
+ match process_break_set(&sid, bp_addr, BreakKind::Software, false) {
+ Ok(bp) => {
+ assert_eq!(bp.addr, bp_addr);
+ let _ = process_continue(&sid);
+ let wr = process_wait(&sid, 5000).expect("wait bp");
+ if wr.ok {
+ if let Some(ev) = wr.event {
+ let _ = process_step_into(&sid, Some(ev.thread_id));
+ let _ = process_wait(&sid, 2000);
+ }
+ }
+ }
+ Err(e) => eprintln!("bp set soft-fail (layout): {e}"),
+ }
+ } else {
+ eprintln!("no modules listed; still detach cleanly");
+ }
+ let _ = process_detach(&sid);
+}
diff --git a/crates/ghidrust-gui/src/debugger.rs b/crates/ghidrust-gui/src/debugger.rs
index e85f885..37529e6 100644
--- a/crates/ghidrust-gui/src/debugger.rs
+++ b/crates/ghidrust-gui/src/debugger.rs
@@ -1,16 +1,18 @@
//! Ghidrust GUI · Debugger tool (tabbed host).
//!
-//! ships a separate `Debugger` tool with a distinct catalog of
-//! `ComponentProvider`s. Ghidrust hosts them in **one** window with a tab
-//! strip. Live Process Bridge panes (Targets / Modules / Memory Bytes /
-//! Regions) talk to `ghidrust_core::process_*`; Threads / Registers / Stack /
-//! Breakpoints / Watches / Console remain honest stubs until a live debug agent lands.
+//! One window with a tab strip. All panes call `ghidrust_core::process_*`
+//! (same APIs as MCP/CLI). Mode **observe** (default) = read-only; **debug**
+//! enables break/step/registers/stack.
use eframe::egui::{self, Color32, RichText, Ui};
use ghidrust_core::process::{
- process_attach, process_detach, process_launch, process_list, process_modules, process_read,
- process_regions, process_resume, static_to_live, LaunchRequest, ModuleInfo, ProcessInfo,
- ProcessSession, ReadResult, RegionInfo,
+ 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,
};
use std::path::{Path, PathBuf};
@@ -115,6 +117,7 @@ impl DebuggerPane {
}
/// Columns rendered in the empty-state table (layout).
+ #[allow(dead_code)]
pub const fn columns(self) -> &'static [&'static str] {
match self {
DebuggerPane::Targets => &["Name", "Type", "State"],
@@ -131,28 +134,37 @@ impl DebuggerPane {
}
/// Copy pointing at the pending backend for this pane.
+ #[allow(dead_code)]
pub const fn backend_message(self) -> &'static str {
match self {
DebuggerPane::Targets => {
"Live Process Bridge (Windows) — ghidrust_core::process_list/attach."
}
- DebuggerPane::Threads => "Backend pending — target-agent thread model.",
+ DebuggerPane::Threads => {
+ "Live Process Bridge — process_threads (debug mode)."
+ }
DebuggerPane::Modules => {
- "Live Process Bridge (Windows) — ghidrust_core::process_modules + static_to_live."
+ "Live Process Bridge (Windows) — ghidrust_core::process_modules + static_to_live."
}
DebuggerPane::Regions => {
- "Live Process Bridge (Windows) — ghidrust_core::process_regions (VirtualQueryEx)."
+ "Live Process Bridge (Windows) — ghidrust_core::process_regions (VirtualQueryEx)."
}
DebuggerPane::Registers => {
- "Backend pending — live register values (Register Manager renders the static register lattice)."
+ "Live Process Bridge — process_thread_context_get (debug mode, x64 CONTEXT)."
+ }
+ DebuggerPane::Stack => {
+ "Live Process Bridge — process_stack (debug mode, RBP/pdata unwind)."
+ }
+ DebuggerPane::Breakpoints => {
+ "Live Process Bridge — process_break_set/clear/list (software INT3, debug mode)."
}
- DebuggerPane::Stack => "Backend pending — target-agent stack unwinder.",
- DebuggerPane::Breakpoints => "Backend pending — breakpoint model + agent set/clear.",
DebuggerPane::MemoryBytes => {
- "Live Process Bridge (Windows) — ghidrust_core::process_read (ReadProcessMemory)."
+ "Live Process Bridge (Windows) — ghidrust_core::process_read (ReadProcessMemory)."
}
- DebuggerPane::Watches => "Backend pending — expression evaluator + refresh.",
- DebuggerPane::DebuggerConsole => "Backend pending — target-agent stdio.",
+ DebuggerPane::Watches => {
+ "Live Process Bridge — process_watch_expr (pointer-chase DSL)."
+ }
+ DebuggerPane::DebuggerConsole => "Debugger console (session events / stop reasons).",
}
}
}
@@ -204,54 +216,54 @@ impl DebuggerAction {
/// Persistent state for the debugger tool mode.
#[derive(Debug, Clone)]
pub struct DebuggerState {
- /// User-set breakpoint VAs (session-only until backend lands).
+ /// Local VA list (also mirrored from live `process_break_list` when debug).
pub breakpoints: Vec<u64>,
- /// User-set watch expressions.
+ /// Watch expression strings.
pub watches: Vec<String>,
- /// Whether the debugger tool mode is active.
pub enabled: bool,
- /// Host window open (single tabbed Debugger).
pub host_open: bool,
- /// Active tab inside the host.
pub active_tab: DebuggerPane,
- /// New-breakpoint input.
pub bp_input: String,
- /// New-watch input.
+ pub bp_oneshot: bool,
pub watch_input: String,
- // ── Live Process Bridge (Windows) — `ghidrust_core::process_*` ──────
- /// Attached session; `None` = no live target.
+ pub watch_matrix_heuristic: bool,
+ // ── Live Process Bridge ────────────────────────────────────────────
pub session: Option<ProcessSession>,
- /// Display name of the attached process (from process list).
pub process_display_name: Option<String>,
- /// Cached process list (Targets pane).
pub process_list_cache: Vec<ProcessInfo>,
- /// Targets pane process-name filter.
pub targets_filter: String,
- /// Targets pane manual PID input.
pub attach_pid_input: String,
- /// Cached module list for the attached session.
+ /// Attach/launch mode (default observe).
+ pub attach_mode: SessionMode,
pub modules_cache: Vec<ModuleInfo>,
- /// Modules pane name/path filter.
pub modules_filter: String,
- /// Cached region list for the attached session.
pub regions_cache: Vec<RegionInfo>,
- /// Modules pane · Static Mappings mini-tool.
pub static_map_module_input: String,
pub static_map_rva_input: String,
pub static_map_result: Option<String>,
- /// Memory Bytes pane inputs + last read.
pub mem_bytes_va_input: String,
pub mem_bytes_size_input: String,
pub mem_bytes_last: Option<ReadResult>,
- /// Last error from any Live Process Bridge call (fail-loud, not silent).
+ pub follow_pc: bool,
pub live_error: Option<String>,
- /// True when session was launched with CREATE_SUSPENDED and not yet resumed.
pub suspended: bool,
- /// Launch… dialog open.
pub show_launch_dialog: bool,
pub launch_image: String,
pub launch_args: String,
pub launch_cwd: String,
+ pub launch_break_at_entry: bool,
+ // Debug caches
+ pub live_breakpoints: Vec<BreakpointInfo>,
+ pub threads_cache: Vec<ThreadInfo>,
+ pub active_thread_id: Option<u32>,
+ pub registers_cache: Option<RegisterSet>,
+ pub stack_cache: Vec<StackFrame>,
+ pub watch_results: Vec<WatchResult>,
+ pub last_stop: Option<StopEvent>,
+ pub console_log: Vec<String>,
+ pub scan_aob: String,
+ pub scan_string: String,
+ pub scan_hits: Vec<ScanHit>,
}
impl Default for DebuggerState {
@@ -263,12 +275,15 @@ impl Default for DebuggerState {
host_open: false,
active_tab: DebuggerPane::Targets,
bp_input: String::new(),
+ bp_oneshot: false,
watch_input: String::new(),
+ watch_matrix_heuristic: false,
session: None,
process_display_name: None,
process_list_cache: Vec::new(),
targets_filter: String::new(),
attach_pid_input: String::new(),
+ attach_mode: SessionMode::Observe,
modules_cache: Vec::new(),
modules_filter: String::new(),
regions_cache: Vec::new(),
@@ -278,12 +293,25 @@ impl Default for DebuggerState {
mem_bytes_va_input: String::new(),
mem_bytes_size_input: String::new(),
mem_bytes_last: None,
+ follow_pc: true,
live_error: None,
suspended: false,
show_launch_dialog: false,
launch_image: String::new(),
launch_args: String::new(),
launch_cwd: String::new(),
+ launch_break_at_entry: true,
+ live_breakpoints: Vec::new(),
+ threads_cache: Vec::new(),
+ active_thread_id: None,
+ registers_cache: None,
+ stack_cache: Vec::new(),
+ watch_results: Vec::new(),
+ last_stop: None,
+ console_log: Vec::new(),
+ scan_aob: String::new(),
+ scan_string: String::new(),
+ scan_hits: Vec::new(),
}
}
}
@@ -373,10 +401,34 @@ impl DebuggerState {
self.static_map_result = None;
self.process_display_name = None;
self.suspended = false;
+ self.live_breakpoints.clear();
+ self.threads_cache.clear();
+ self.active_thread_id = None;
+ self.registers_cache = None;
+ self.stack_cache.clear();
+ self.watch_results.clear();
+ self.last_stop = None;
+ self.scan_hits.clear();
+ }
+
+ pub fn log(&mut self, line: impl Into<String>) {
+ self.console_log.push(line.into());
+ if self.console_log.len() > 500 {
+ let n = self.console_log.len() - 400;
+ self.console_log.drain(0..n);
+ }
+ }
+
+ pub fn is_debug_mode(&self) -> bool {
+ self.session
+ .as_ref()
+ .map(|s| s.mode == SessionMode::Debug)
+ .unwrap_or(false)
}
pub fn detach_session(&mut self) {
if let Some(sess) = self.session.take() {
+ self.log(format!("detach {}", sess.session_id));
let _ = process_detach(&sess.session_id);
}
self.clear_live_caches();
@@ -384,14 +436,14 @@ impl DebuggerState {
self.active_tab = DebuggerPane::Targets;
}
- /// Attach and auto-populate modules / regions / Memory Bytes (CE-style).
+ /// Attach with current `attach_mode` and auto-populate.
pub fn attach_and_populate(&mut self, pid: u32) {
if pid == 0 {
self.live_error = Some("invalid PID".into());
return;
}
self.live_error = None;
- match process_attach(pid) {
+ match process_attach_opts(pid, &AttachOpts { mode: self.attach_mode }) {
Ok(sess) => {
let name = self
.process_list_cache
@@ -399,9 +451,22 @@ impl DebuggerState {
.find(|p| p.pid == pid)
.map(|p| p.name.clone());
self.process_display_name = name;
+ self.log(format!(
+ "attach pid={pid} mode={} session={}",
+ sess.mode.as_str(),
+ sess.session_id
+ ));
+ if let Some(a) = &sess.advisory {
+ if a.suspected_protection {
+ self.log(format!("advisory: {}", a.message));
+ }
+ }
self.session = Some(sess);
self.suspended = false;
self.refresh_after_attach();
+ if self.is_debug_mode() {
+ self.poll_stop(500);
+ }
}
Err(e) => {
self.session = None;
@@ -411,7 +476,7 @@ impl DebuggerState {
}
}
- /// Launch CREATE_SUSPENDED + auto-populate (not a debug break-at-entry).
+ /// Launch with current attach_mode (+ break_at_entry when debug).
pub fn launch_and_populate(&mut self) {
let image = self.launch_image.trim();
if image.is_empty() {
@@ -436,6 +501,8 @@ impl DebuggerState {
Some(PathBuf::from(c))
}
},
+ mode: self.attach_mode,
+ break_at_entry: self.attach_mode == SessionMode::Debug && self.launch_break_at_entry,
};
self.live_error = None;
match process_launch(&req) {
@@ -445,10 +512,19 @@ impl DebuggerState {
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| r.image.clone());
self.process_display_name = Some(name);
+ self.log(format!(
+ "launch mode={} session={} suspended={}",
+ r.session.mode.as_str(),
+ r.session.session_id,
+ r.suspended
+ ));
self.session = Some(r.session);
self.suspended = r.suspended;
self.show_launch_dialog = false;
self.refresh_after_attach();
+ if self.is_debug_mode() {
+ self.poll_stop(2000);
+ }
}
Err(e) => {
self.live_error = Some(e);
@@ -456,6 +532,138 @@ impl DebuggerState {
}
}
+ pub fn poll_stop(&mut self, timeout_ms: u64) {
+ let Some(sess) = self.session.clone() else {
+ return;
+ };
+ if sess.mode != SessionMode::Debug {
+ return;
+ }
+ match process_wait(&sess.session_id, timeout_ms) {
+ Ok(wr) => {
+ if let Some(ev) = wr.event {
+ self.log(format!(
+ "stop reason={} tid={} rip={:#x}",
+ ev.reason, ev.thread_id, ev.rip
+ ));
+ self.active_thread_id = Some(ev.thread_id);
+ if let Some(regs) = &ev.registers {
+ self.registers_cache = Some(regs.clone());
+ }
+ if self.follow_pc {
+ self.mem_bytes_va_input = format!("{:#x}", ev.rip);
+ }
+ self.last_stop = Some(ev);
+ self.refresh_debug_views();
+ } else if !wr.ok {
+ if wr.code.as_deref() != Some("wait_timeout") {
+ self.live_error = wr.message.or(wr.code);
+ }
+ }
+ }
+ Err(e) => self.live_error = Some(e),
+ }
+ }
+
+ pub fn refresh_debug_views(&mut self) {
+ let Some(sess) = self.session.clone() else {
+ return;
+ };
+ if sess.mode != SessionMode::Debug {
+ return;
+ }
+ if let Ok(bps) = process_break_list(&sess.session_id) {
+ self.live_breakpoints = bps;
+ self.breakpoints = self.live_breakpoints.iter().map(|b| b.addr).collect();
+ }
+ if let Ok(ths) = process_threads(&sess.session_id) {
+ self.threads_cache = ths;
+ if self.active_thread_id.is_none() {
+ self.active_thread_id = self.threads_cache.first().map(|t| t.thread_id);
+ }
+ }
+ 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);
+ }
+ if let Ok(frames) = process_stack(&sess.session_id, tid, 32) {
+ self.stack_cache = frames;
+ }
+ }
+ self.refresh_watches();
+ }
+
+ pub fn refresh_watches(&mut self) {
+ let Some(sess) = self.session.clone() else {
+ return;
+ };
+ let mut out = Vec::new();
+ for e in &self.watches {
+ match process_watch_expr(&sess.session_id, e, self.watch_matrix_heuristic) {
+ Ok(w) => out.push(w),
+ Err(err) => out.push(WatchResult {
+ expr: e.clone(),
+ steps: vec![],
+ final_va: None,
+ value_hex: None,
+ as_u64: None,
+ as_f32: None,
+ as_f64: None,
+ heuristic_float4x4: None,
+ heuristic: false,
+ error: Some(err),
+ }),
+ }
+ }
+ self.watch_results = out;
+ }
+
+ pub fn debug_continue(&mut self) {
+ let Some(sess) = self.session.clone() else {
+ return;
+ };
+ match process_continue(&sess.session_id) {
+ Ok(()) => {
+ self.log("continue");
+ self.live_error = None;
+ self.poll_stop(100);
+ }
+ Err(e) => self.live_error = Some(e),
+ }
+ }
+
+ pub fn debug_pause(&mut self) {
+ let Some(sess) = self.session.clone() else {
+ return;
+ };
+ match process_pause(&sess.session_id) {
+ Ok(()) => {
+ self.log("pause");
+ self.poll_stop(2000);
+ }
+ Err(e) => self.live_error = Some(e),
+ }
+ }
+
+ pub fn debug_step(&mut self, over: bool) {
+ let Some(sess) = self.session.clone() else {
+ return;
+ };
+ let tid = self.active_thread_id;
+ let r = if over {
+ process_step_over(&sess.session_id, tid)
+ } else {
+ process_step_into(&sess.session_id, tid)
+ };
+ match r {
+ Ok(()) => {
+ self.log(if over { "step over" } else { "step into" });
+ self.poll_stop(2000);
+ }
+ 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());
@@ -528,19 +736,26 @@ impl DebuggerState {
match &self.session {
Some(sess) => {
let name = self.process_display_name.as_deref().unwrap_or("(unknown)");
+ let mode = sess.mode.as_str();
+ let rs = sess.run_state.as_str();
if self.suspended {
format!(
- "Suspended · {} · pid={} · session={} — Resume to run",
- name, sess.pid, sess.session_id
+ "{mode}/{rs} · {name} · pid={} · session={} — Resume to run",
+ sess.pid, sess.session_id
+ )
+ } else if let Some(stop) = &self.last_stop {
+ format!(
+ "{mode}/{rs} · {name} · pid={} · stop={} rip={:#x}",
+ sess.pid, stop.reason, stop.rip
)
} else {
format!(
- "Attached · {} · pid={} · session={}",
- name, sess.pid, sess.session_id
+ "{mode}/{rs} · {name} · pid={} · session={}",
+ sess.pid, sess.session_id
)
}
}
- None => "Detached — Attach a PID or Launch an image".into(),
+ None => "Detached — Attach a PID or Launch an image (Mode: observe|debug)".into(),
}
}
@@ -709,18 +924,31 @@ pub fn draw_launch_dialog(ctx: &egui::Context, state: &mut DebuggerState, muted:
);
});
ui.horizontal(|ui| {
- ui.label("Cwd:");
+ ui.label("Cwd:");
ui.add(
egui::TextEdit::singleline(&mut state.launch_cwd)
.desired_width(360.0)
- .hint_text("optional working directory"),
+ .hint_text("optional working directory"),
);
- if ui.button("Browse…").clicked() {
+ if ui.button("Browse…").clicked() {
if let Some(path) = rfd::FileDialog::new().pick_folder() {
state.launch_cwd = path.display().to_string();
}
}
});
+ ui.horizontal(|ui| {
+ ui.label("Mode:");
+ egui::ComboBox::from_id_salt("dbg_launch_mode")
+ .selected_text(state.attach_mode.as_str())
+ .show_ui(ui, |ui| {
+ ui.selectable_value(&mut state.attach_mode, SessionMode::Observe, "observe");
+ ui.selectable_value(&mut state.attach_mode, SessionMode::Debug, "debug");
+ });
+ ui.add_enabled(
+ state.attach_mode == SessionMode::Debug,
+ egui::Checkbox::new(&mut state.launch_break_at_entry, "Break at entry"),
+ );
+ });
if let Some(e) = state.live_error.clone() {
err_row(ui, &e);
}
@@ -729,7 +957,7 @@ pub fn draw_launch_dialog(ctx: &egui::Context, state: &mut DebuggerState, muted:
if ui
.add_enabled(
!state.launch_image.trim().is_empty() && state.session.is_none(),
- egui::Button::new("Launch"),
+ egui::Button::new("Launch"),
)
.clicked()
{
@@ -758,7 +986,7 @@ fn render_host_body(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
if state.session.is_some() && state.suspended {
if ui
.small_button("Resume")
- .on_hover_text("ResumeThread on the primary CREATE_SUSPENDED thread")
+ .on_hover_text("ResumeThread / continue debug session")
.clicked()
{
state.resume_session();
@@ -770,6 +998,56 @@ fn render_host_body(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
}
}
});
+ // Debug toolbar
+ let dbg = state.is_debug_mode();
+ ui.horizontal(|ui| {
+ let cont = ui
+ .add_enabled(dbg, egui::Button::new("Continue (F5)").small())
+ .on_hover_text(if dbg {
+ "process_continue"
+ } else {
+ "Requires mode=debug"
+ });
+ if cont.clicked() {
+ state.debug_continue();
+ }
+ let pause = ui
+ .add_enabled(dbg, egui::Button::new("Interrupt").small())
+ .on_hover_text(if dbg {
+ "process_pause"
+ } else {
+ "Requires mode=debug"
+ });
+ if pause.clicked() {
+ state.debug_pause();
+ }
+ if ui
+ .add_enabled(dbg, egui::Button::new("Step Into (F7)").small())
+ .clicked()
+ {
+ state.debug_step(false);
+ }
+ if ui
+ .add_enabled(dbg, egui::Button::new("Step Over (F8)").small())
+ .clicked()
+ {
+ state.debug_step(true);
+ }
+ if ui
+ .add_enabled(dbg, egui::Button::new("Wait stop").small())
+ .on_hover_text("process_wait 5s")
+ .clicked()
+ {
+ state.poll_stop(5000);
+ }
+ if ui
+ .add_enabled(dbg, egui::Button::new("Refresh debug").small())
+ .clicked()
+ {
+ state.refresh_debug_views();
+ }
+ ui.checkbox(&mut state.follow_pc, "Follow PC");
+ });
if let Some(e) = state.live_error.clone() {
err_row(ui, &e);
}
@@ -811,7 +1089,10 @@ pub fn render_pane_body(
DebuggerPane::Modules => render_modules(state, ui, muted),
DebuggerPane::Regions => render_regions(state, ui, muted),
DebuggerPane::MemoryBytes => render_memory_bytes(state, ui, muted),
- _ => render_empty_table(pane, ui, muted),
+ DebuggerPane::Threads => render_threads(state, ui, muted),
+ DebuggerPane::Registers => render_registers(state, ui, muted),
+ DebuggerPane::Stack => render_stack(state, ui, muted),
+ DebuggerPane::DebuggerConsole => render_console(state, ui, muted),
}
}
@@ -822,7 +1103,7 @@ fn err_row(ui: &mut Ui, err: &str) {
fn render_targets(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
ui.small(
RichText::new(
- "Attach: existing PID. Launch… (Debugger menu): CREATE_SUSPENDED new image, then Resume.",
+ "Mode observe = read-only. Mode debug = break/step/regs/stack (same as MCP process_attach mode).",
)
.color(muted),
);
@@ -833,10 +1114,17 @@ fn render_targets(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
if ui.button("Launch…").clicked() {
state.show_launch_dialog = true;
}
+ ui.label("Mode:");
+ egui::ComboBox::from_id_salt("dbg_attach_mode")
+ .selected_text(state.attach_mode.as_str())
+ .show_ui(ui, |ui| {
+ ui.selectable_value(&mut state.attach_mode, SessionMode::Observe, "observe");
+ ui.selectable_value(&mut state.attach_mode, SessionMode::Debug, "debug");
+ });
ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut state.targets_filter)
- .desired_width(200.0)
+ .desired_width(160.0)
.hint_text("process name…"),
);
});
@@ -1191,91 +1479,191 @@ fn render_memory_bytes(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
});
}
-fn render_empty_table(pane: DebuggerPane, ui: &mut Ui, muted: Color32) {
- ui.horizontal(|ui| {
- for col in pane.columns() {
- ui.strong(*col);
- ui.separator();
- }
- });
- ui.separator();
- ui.add_space(6.0);
- ui.label(RichText::new(pane.backend_message()).color(muted).italics());
- ui.add_space(4.0);
- ui.small(
- RichText::new(
- "Pane is present for the Debugger catalog. Live content lands with a target agent.",
- )
- .color(muted),
- );
-}
-
fn render_breakpoints(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
- ui.small(
- RichText::new(
- "Session-only breakpoint list (replaced by target-agent state when available).",
- )
- .color(muted),
- );
+ let Some(sess) = state.session.clone() else {
+ ui.weak("No live target — attach with mode=debug to set software breakpoints.");
+ return;
+ };
+ if sess.mode != SessionMode::Debug {
+ ui.weak("Breakpoints require mode=debug. Re-attach/launch with Mode=debug on Targets.");
+ return;
+ }
+ ui.small(RichText::new("process_break_set / clear / list (software INT3)").color(muted));
ui.horizontal(|ui| {
ui.label("Address:");
ui.add(
egui::TextEdit::singleline(&mut state.bp_input)
.desired_width(160.0)
- .hint_text("0x140001000"),
+ .hint_text("0x7ff…"),
);
- if ui.button("Add Breakpoint").clicked() {
+ ui.checkbox(&mut state.bp_oneshot, "oneshot");
+ if ui.button("Add").clicked() {
if let Some(va) = parse_hex(&state.bp_input) {
- state.toggle_breakpoint(va);
- state.bp_input.clear();
+ match process_break_set(&sess.session_id, va, BreakKind::Software, state.bp_oneshot)
+ {
+ Ok(bp) => {
+ state.log(format!("bp set id={} addr={:#x}", bp.id, bp.addr));
+ state.live_error = None;
+ state.bp_input.clear();
+ state.refresh_debug_views();
+ }
+ Err(e) => state.live_error = Some(e),
+ }
}
}
+ if ui.button("Refresh").clicked() {
+ state.refresh_debug_views();
+ }
});
ui.separator();
- if state.breakpoints.is_empty() {
- ui.weak("No breakpoints set.");
+ if state.live_breakpoints.is_empty() {
+ ui.weak("No live breakpoints.");
return;
}
- let mut delete: Option<usize> = None;
+ let mut clear_id: Option<u64> = None;
+ let mut goto: Option<u64> = None;
egui::Grid::new("dbg_bp_grid")
- .num_columns(3)
+ .num_columns(5)
.striped(true)
.show(ui, |ui| {
- ui.strong("Enabled");
+ ui.strong("Id");
ui.strong("Address");
+ ui.strong("Kind");
+ ui.strong("Oneshot");
ui.strong("");
ui.end_row();
- for (i, va) in state.breakpoints.iter().enumerate() {
- ui.monospace("*");
- ui.monospace(format!("{va:#x}"));
- if ui.small_button("Delete").clicked() {
- delete = Some(i);
+ for bp in &state.live_breakpoints {
+ ui.monospace(format!("{}", bp.id));
+ if ui.link(format!("{:#x}", bp.addr)).clicked() {
+ goto = Some(bp.addr);
+ }
+ ui.label(format!("{:?}", bp.kind).to_ascii_lowercase());
+ ui.label(if bp.oneshot { "yes" } else { "no" });
+ if ui.small_button("Clear").clicked() {
+ clear_id = Some(bp.id);
}
ui.end_row();
}
});
- if let Some(i) = delete {
- state.breakpoints.remove(i);
+ if let Some(id) = clear_id {
+ match process_break_clear(&sess.session_id, Some(id), None) {
+ Ok(()) => {
+ state.log(format!("bp clear id={id}"));
+ state.refresh_debug_views();
+ }
+ Err(e) => state.live_error = Some(e),
+ }
+ }
+ if let Some(va) = goto {
+ state.mem_bytes_va_input = format!("{va:#x}");
+ state.active_tab = DebuggerPane::MemoryBytes;
}
}
fn render_watches(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ let Some(sess) = state.session.clone() else {
+ ui.weak("No live target — attach first, then add pointer-chase expressions.");
+ return;
+ };
ui.small(
- RichText::new("Session-only watch list (evaluator pending a target agent).").color(muted),
+ RichText::new("process_watch_expr · DSL: module+rva, u64@va, va->*+0x10 (bytes ≠ types)")
+ .color(muted),
);
ui.horizontal(|ui| {
- ui.label("Expression:");
+ ui.label("Expr:");
ui.add(
egui::TextEdit::singleline(&mut state.watch_input)
.desired_width(280.0)
- .hint_text("*(int*)rsp"),
+ .hint_text("game.exe+0x1234->*+0x10"),
);
- if ui.button("Add Watch").clicked() {
+ ui.checkbox(&mut state.watch_matrix_heuristic, "matrix heuristic");
+ if ui.button("Add").clicked() {
let e = state.watch_input.clone();
state.add_watch(e);
state.watch_input.clear();
+ state.refresh_watches();
+ }
+ if ui.button("Refresh all").clicked() {
+ state.refresh_watches();
+ }
+ });
+ ui.separator();
+ // Scan mini-tool
+ ui.label(RichText::new("Scan (process_scan)").strong());
+ ui.horizontal(|ui| {
+ ui.label("AOB:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.scan_aob)
+ .desired_width(200.0)
+ .hint_text("48 8b ?? 90"),
+ );
+ ui.label("String:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.scan_string)
+ .desired_width(120.0)
+ .hint_text("Camera"),
+ );
+ if ui.button("Scan").clicked() {
+ let opts = ScanOpts {
+ aob: {
+ let a = state.scan_aob.trim();
+ if a.is_empty() {
+ None
+ } else {
+ Some(a.to_string())
+ }
+ },
+ string: {
+ let s = state.scan_string.trim();
+ if s.is_empty() {
+ None
+ } else {
+ Some(s.to_string())
+ }
+ },
+ ..ScanOpts::default()
+ };
+ match process_scan_mem(&sess.session_id, &opts) {
+ Ok(r) => {
+ state.scan_hits = r.hits;
+ state.log(format!(
+ "scan hits={} truncated={} bytes={}",
+ state.scan_hits.len(),
+ r.truncated,
+ r.bytes_scanned
+ ));
+ state.live_error = None;
+ }
+ Err(e) => state.live_error = Some(e),
+ }
}
});
+ if !state.scan_hits.is_empty() {
+ ui.small(format!("{} scan hit(s)", state.scan_hits.len()));
+ let mut goto = None;
+ egui::ScrollArea::vertical()
+ .id_salt("dbg_scan_hits")
+ .max_height(100.0)
+ .show(ui, |ui| {
+ for h in state.scan_hits.iter().take(64) {
+ if ui
+ .link(format!(
+ "{:#x} {} {:?}",
+ h.va,
+ h.module.as_deref().unwrap_or("?"),
+ h.preview_hex.as_deref().unwrap_or("")
+ ))
+ .clicked()
+ {
+ goto = Some(h.va);
+ }
+ }
+ });
+ if let Some(va) = goto {
+ state.mem_bytes_va_input = format!("{va:#x}");
+ state.active_tab = DebuggerPane::MemoryBytes;
+ }
+ }
ui.separator();
if state.watches.is_empty() {
ui.weak("No watches.");
@@ -1283,16 +1671,39 @@ fn render_watches(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
}
let mut delete: Option<usize> = None;
egui::Grid::new("dbg_watch_grid")
- .num_columns(3)
+ .num_columns(4)
.striped(true)
.show(ui, |ui| {
ui.strong("Expression");
+ ui.strong("VA");
ui.strong("Value");
ui.strong("");
ui.end_row();
for (i, w) in state.watches.iter().enumerate() {
ui.monospace(w);
- ui.small(RichText::new("<no target>").color(muted));
+ let res = state.watch_results.get(i);
+ if let Some(r) = res {
+ ui.monospace(
+ r.final_va
+ .map(|v| format!("{v:#x}"))
+ .unwrap_or_else(|| "—".into()),
+ );
+ let val = r
+ .error
+ .clone()
+ .or_else(|| r.as_u64.map(|u| format!("{u:#x}")))
+ .or_else(|| r.value_hex.clone())
+ .unwrap_or_else(|| "—".into());
+ let t = if r.heuristic {
+ format!("{val} (heuristic)")
+ } else {
+ val
+ };
+ ui.small(t);
+ } else {
+ ui.small("—");
+ ui.small(RichText::new("Refresh").color(muted));
+ }
if ui.small_button("Delete").clicked() {
delete = Some(i);
}
@@ -1301,7 +1712,216 @@ fn render_watches(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
});
if let Some(i) = delete {
state.remove_watch(i);
+ state.refresh_watches();
+ }
+}
+
+fn render_threads(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ let Some(sess) = state.session.clone() else {
+ ui.weak("No live target.");
+ return;
+ };
+ if sess.mode != SessionMode::Debug {
+ ui.weak("Threads pane uses process_threads (debug mode).");
+ return;
}
+ ui.horizontal(|ui| {
+ ui.small(RichText::new("process_threads").color(muted));
+ if ui.button("Refresh").clicked() {
+ state.refresh_debug_views();
+ }
+ });
+ if state.threads_cache.is_empty() {
+ ui.weak("No threads — Refresh or wait for a stop.");
+ return;
+ }
+ egui::Grid::new("dbg_threads_grid")
+ .num_columns(2)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("TID");
+ ui.strong("Active");
+ ui.end_row();
+ for t in state.threads_cache.clone() {
+ let selected = state.active_thread_id == Some(t.thread_id);
+ if ui.selectable_label(selected, format!("{}", t.thread_id)).clicked() {
+ state.active_thread_id = Some(t.thread_id);
+ state.refresh_debug_views();
+ }
+ ui.label(if selected { "●" } else { "" });
+ ui.end_row();
+ }
+ });
+}
+
+fn render_registers(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ let Some(sess) = state.session.clone() else {
+ ui.weak("No live target.");
+ return;
+ };
+ if sess.mode != SessionMode::Debug {
+ ui.weak("Registers require mode=debug (process_thread_context_get).");
+ return;
+ }
+ ui.horizontal(|ui| {
+ ui.small(
+ RichText::new(format!(
+ "tid={}",
+ state
+ .active_thread_id
+ .map(|t| t.to_string())
+ .unwrap_or_else(|| "—".into())
+ ))
+ .color(muted),
+ );
+ if ui.button("Refresh").clicked() {
+ state.refresh_debug_views();
+ }
+ });
+ if let Some(stop) = &state.last_stop {
+ ui.small(format!(
+ "last stop: {} rip={:#x}",
+ stop.reason, stop.rip
+ ));
+ }
+ let Some(regs) = state.registers_cache.clone() else {
+ 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),
+ ];
+ egui::ScrollArea::vertical()
+ .id_salt("dbg_regs")
+ .show(ui, |ui| {
+ egui::Grid::new("dbg_regs_grid")
+ .num_columns(2)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Register");
+ ui.strong("Value");
+ ui.end_row();
+ for (n, v) in pairs {
+ ui.monospace(n);
+ ui.monospace(format!("{v:#018x}"));
+ ui.end_row();
+ }
+ });
+ });
+}
+
+fn render_stack(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ let Some(sess) = state.session.clone() else {
+ ui.weak("No live target.");
+ return;
+ };
+ if sess.mode != SessionMode::Debug {
+ ui.weak("Stack requires mode=debug (process_stack).");
+ return;
+ }
+ ui.horizontal(|ui| {
+ ui.small(RichText::new("process_stack · RBP unwind").color(muted));
+ if ui.button("Refresh").clicked() {
+ state.refresh_debug_views();
+ }
+ });
+ if state.stack_cache.is_empty() {
+ ui.weak("No frames — stop on a BP then Refresh.");
+ return;
+ }
+ let mut goto = None;
+ egui::ScrollArea::vertical()
+ .id_salt("dbg_stack")
+ .show(ui, |ui| {
+ egui::Grid::new("dbg_stack_grid")
+ .num_columns(5)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("#");
+ ui.strong("SP");
+ ui.strong("PC");
+ ui.strong("Module");
+ ui.strong("RVA");
+ ui.end_row();
+ for f in &state.stack_cache {
+ ui.monospace(format!("{}", f.level));
+ ui.monospace(format!("{:#x}", f.sp));
+ if ui.link(format!("{:#x}", f.rip)).clicked() {
+ goto = Some(f.rip);
+ }
+ ui.small(f.module.as_deref().unwrap_or("—"));
+ ui.monospace(
+ f.rva
+ .map(|r| format!("{r:#x}"))
+ .unwrap_or_else(|| "—".into()),
+ );
+ ui.end_row();
+ }
+ });
+ });
+ if let Some(va) = goto {
+ state.mem_bytes_va_input = format!("{va:#x}");
+ state.active_tab = DebuggerPane::MemoryBytes;
+ }
+}
+
+fn render_console(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ ui.horizontal(|ui| {
+ ui.small(RichText::new("Session events / stop reasons").color(muted));
+ if ui.button("Clear log").clicked() {
+ state.console_log.clear();
+ }
+ if ui
+ .add_enabled(state.session.is_some(), egui::Button::new("Export snapshot"))
+ .on_hover_text("process_export_snapshot")
+ .clicked()
+ {
+ if let Some(sess) = state.session.clone() {
+ match process_export_snapshot(&sess.session_id, &state.watches, &[]) {
+ 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());
+ }
+ state.live_error = None;
+ }
+ }
+ Err(e) => state.live_error = Some(e),
+ }
+ }
+ }
+ });
+ ui.separator();
+ egui::ScrollArea::vertical()
+ .id_salt("dbg_console")
+ .stick_to_bottom(true)
+ .show(ui, |ui| {
+ if state.console_log.is_empty() {
+ ui.weak("No events yet.");
+ }
+ for line in &state.console_log {
+ ui.monospace(line);
+ }
+ });
}
fn parse_hex(s: &str) -> Option<u64> {
@@ -1329,7 +1949,7 @@ mod tests {
#[test]
fn debugger_catalog_covers_debugger_windows() {
- let names: Vec<&'static str> = DebuggerPane::ALL.iter().map(|p| p.title).collect();
+ let names: Vec<&'static str> = DebuggerPane::ALL.iter().map(|p| p.title()).collect();
for expected in [
"Debugger Targets",
"Debugger Threads",
@@ -1403,7 +2023,7 @@ mod tests {
modinfo("game.exe", 0x140000000, 0x10000, Some(r"C:\game\game.exe")),
];
let m = pick_main_module(&mods, Some("game.exe")).unwrap();
- assert_eq!(m.name(), "game.exe");
+ assert_eq!(m.name, "game.exe");
assert_eq!(m.base, 0x140000000);
}
@@ -1414,7 +2034,7 @@ mod tests {
modinfo("b.dll", 0x2000, 0x100, Some(r"C:\b.dll")),
];
let m = pick_main_module(&mods, Some("missing.exe")).unwrap();
- assert_eq!(m.name(), "b.dll");
+ assert_eq!(m.name, "b.dll");
}
#[test]
@@ -1456,7 +2076,7 @@ mod tests {
let mut s = DebuggerState::default();
s.modules_cache = vec![modinfo("game.exe", 0x140000000, 0x1000, None)];
let m = s.module_for_va(0x140000100).unwrap();
- assert_eq!(m.name(), "game.exe");
+ assert_eq!(m.name, "game.exe");
assert!(s.module_for_va(0x150000000).is_none());
}
@@ -1536,10 +2156,12 @@ mod tests {
fn simulated_post_attach_focus_modules() {
// Mimic refresh_after_attach's final focus without calling Win32.
let mut s = DebuggerState::default();
- s.session = Some(ProcessSession {
- session_id: "ps-test".into(),
- pid: 1,
- });
+ s.session = Some(ProcessSession::new(
+ "ps-test".into(),
+ 1,
+ ghidrust_core::SessionMode::Observe,
+ ghidrust_core::RunState::Attached,
+ ));
s.process_display_name = Some("game.exe".into());
s.modules_cache = vec![modinfo(
"game.exe",
diff --git a/skill/README.md b/skill/README.md
index 10ad711..e465ce7 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 `crypt_constants` / `recover_strings` / `decode_bake` / `decode_magic` / `list_crypto_capabilities` (current is `6`). 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 (break/step/regs/stack/scan/watch; current is `7`). Restart MCP after rebuild if those or `process_*` are missing.
Smoke crypto surfaces:
diff --git a/skill/SKILL.md b/skill/SKILL.md
index d2fa9b4..adfc9f3 100644
--- a/skill/SKILL.md
+++ b/skill/SKILL.md
@@ -274,7 +274,7 @@ Brief line (`--brief` / MCP `listing_text`): `{addr:#x}: {mnemonic} {operands}`.
- **Address→function**: Always pass `addr` to `decompile` / `disassemble` / `gpu_decompile`; trust `resolved_entry` / `resolve` meta. Mid-body hits resolve to containing entry; unmapped → create/synthesize or honest `no_containing_function` (no invented 1-insn fn).
- **RTTI catalog**: Prefer `rtti_query` (`--filter`/`--exact`) before mangled `.?AV` string archaeology. Multi-vtable types report `vtable_vas[]` honestly.
- **UTF-16 xrefs**: If `search_strings` returns `utf16le`, query `get_string_xrefs` with `encoding=all` (or `utf16le`) before concluding “no refs”.
-- **Live process (Windows)**: Multi-step live work **must** use MCP (or one long-lived process) — `process_list` → `process_attach` **or** `process_launch` (CREATE_SUSPENDED) → `process_modules` → `process_resolve` (`static_to_live`) → `process_read` → optional `process_resume` / `process_regions` / `process_detach`. Launch is suspended spawn + read session, **not** debug break-at-entry. Never chain separate CLI `ghidrust process` spawns expecting the same `session_id` (sessions are in-process). Bytes ≠ types. No write/breakpoints in MVP.
+- **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.
- **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.
@@ -427,7 +427,7 @@ ghidrust project analyze PROJ_DIR --file ID \
### MCP (`ghidrust mcp`)
-Requires **`tool_surface >= 3`** (prefer **`>= 4`** for bounded disasm / `get_calls_from`; **`>= 5`** for decode tools; **`>= 6`** for crypto recover / bake). Check with `server_info` after connect.
+Requires **`tool_surface >= 3`** (prefer **`>= 4`** for bounded disasm / `get_calls_from`; **`>= 5`** for decode tools; **`>= 6`** for crypto recover / bake; **`>= 7`** for live debug break/step/scan/watch). Check with `server_info` after connect.
| Tool | Args | Notes |
|------|------|-------|
@@ -466,7 +466,9 @@ Requires **`tool_surface >= 3`** (prefer **`>= 4`** for bounded disasm / `get_ca
| `list_gpu_strategies` | — | Strategy matrix |
| `gpu_decompile` | `path`, optional `addr`, `out` | VA resolve; metrics JSON; dump opaque |
| `rtti_gpu_bench` | `path` | CPU vs GPU RTTI |
-| `process_list` / `process_attach` / `process_launch` / `process_resume` / `process_detach` / `process_modules` / `process_read` / `process_resolve` / `process_regions` | pid / image / session / module / rva / max | Live Process Bridge (Windows; read-only; launch = CREATE_SUSPENDED) |
+| `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`) |
MCP launch: `ghidrust mcp` / `target/release/ghidrust.exe mcp` (stdio; no host-specific paths).
@@ -610,7 +612,7 @@ Canonical detail: [`docs/IL2CPP.md`](../docs/IL2CPP.md).
| Raw bytes at VA | `ghidrust bytes PATH --addr HEX --count N --json` | `read_bytes` `{path, addr, count?}` |
| Xrefs (incl. data ptrs / skip stubs) | `ghidrust xrefs PATH --to HEX [--skip-stubs] [--classify]` | `get_xrefs_to` `{…, skip_stubs, classify}` |
| Decompile through stub | `ghidrust decompile GA.dll --addr HEX --follow-stub --json` | `decompile` `{…, follow_stub: true}` |
-| Live resolve + read (runtime slots) | `ghidrust process …` (single spawn only) | MCP: attach → resolve → read (keep session) |
+| Live resolve + read / debug | `ghidrust process … -mode observe\|debug` (single spawn only) | MCP: attach/launch → resolve → break/wait/stack/watch → detach |
| Strings on metadata blob | `ghidrust strings META.dat --raw --match token --limit N` | `list_strings` `{path, raw:true, match, limit}` |
Wrong metadata magic → encrypted/obfuscated JSON with `next_steps` (fail closed). Never invent method or icall RVAs when pairing/map leaves them null. Empty/runtime stub slots → `runtime_unresolved` + live `next_steps`; do not heap-scan as a substitute.
@@ -648,7 +650,7 @@ Add `--json` for structured stdout.
| Inventory | `ghidrust inventory <dir> [--max-depth N] [--hash]` |
| Tree | `ghidrust tree <path> [--max-depth N] [--ext LIST] [--name GLOB]` |
| Artifact | `ghidrust artifact get\|query\|list …` |
-| Process (Windows) | `ghidrust process list\|attach\|launch\|resume\|detach\|modules\|read\|resolve\|regions …` |
+| Process (Windows) | `ghidrust process list\|attach\|launch\|resume\|detach\|modules\|read\|resolve\|regions\|break\|continue\|wait\|step\|threads\|regs\|stack\|scan\|watch\|vtable\|snapshot …` |
| IL2CPP | `ghidrust il2cpp meta\|map\|touch-map\|stubs\|icalls …` (`--baseline` / `--meta-sections`; see `docs/IL2CPP.md`) |
| Unity inventory | `ghidrust unity-inventory <game-dir>` |
| RTTI catalog | `ghidrust rtti <path> [--filter\|--name\|--exact] [--match MODE]` |
@@ -703,15 +705,20 @@ ghidrust artifact list --json
ghidrust artifact query ARTIFACT_ID --offset 0 --limit 64 --json
ghidrust artifact get ARTIFACT_ID
-# Live process (Windows; read-only)
+# Live process (Windows; observe default, debug opt-in)
ghidrust process list --json
-ghidrust process attach PID
-ghidrust process launch PATH.exe --args "…" --cwd DIR --json
-ghidrust process resume SESSION
+ghidrust process attach PID -mode observe
+ghidrust process attach PID -mode debug
+ghidrust process launch PATH.exe -mode debug -break-at-entry --json
ghidrust process modules SESSION --json
ghidrust process resolve SESSION --module app.exe --rva 0x1234 --json
+ghidrust process break set SESSION -addr LIVE_VA
+ghidrust process continue SESSION
+ghidrust process wait SESSION -timeout 5000
+ghidrust process stack SESSION TID
+ghidrust process scan SESSION -aob "48 8b ?? 90"
+ghidrust process watch SESSION "module.exe+0x1234->*+0x10"
ghidrust process read SESSION --addr LIVE_VA --size 64 --json
-ghidrust process regions SESSION --json
ghidrust process detach SESSION
# Unity / IL2CPP