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.
Discover Find Crypt — constant-table scan (AES/TEA/hashes/stream/block/SM4/…), CRYPT_* labels, comments, xrefs CLI/MCP: crypt-constants / crypt_constants Recover Obfuscated Strings — stack / tight / decoded (+ static hints, light emu, seed from crypto sites) CLI/MCP: recover-strings / recover_strings Transform decode bake — Base64/Hex/charcode/URL/HTML, XOR(+brute), RC4, AES (CBC/ECB/CTR/CFB/OFB/GCM plaintext), DES/3DES, Blowfish, ChaCha20, Gunzip/Inflate, ROT13/Reverse/UTF-16LE, IOC extract decode magic — auto peel + crib CLI/MCP: decode bake|magic / decode_bake / decode_magic Classify Crypto Capabilities — WinCrypt/BCrypt/DPAPI/SSPI/OpenSSL-style imports, AES-NI, CALG, Base64/XOR/TEA/RC4 idioms, packing context, ATT&CK/MBC, recipe suggestions CLI/MCP: crypto-capabilities / list_crypto_capabilities Surfaces Pipeline — Find Crypt → Obfuscated Strings → Crypto Capabilities seeding GUI — single Decrypt window (tabs: Bake / Constants / Strings / Capabilities); listing click-to-decrypt
oofz856e0aa047b2
diff --git a/README.md b/README.mdindex 485c29a..7cfba74 100644--- a/README.md+++ b/README.md@@ -612,6 +612,26 @@ You should not need to type JSON by hand day-to-day — the IDE/agent does that---+## Decrypt and crypto discovery++Use the discovery order **Find Crypt → recover strings → capabilities → recipe peel**. Results are evidence-based; a successful GCM recipe returns the counter-mode plaintext path but does not authenticate a tag.++```bash+# Locate known cryptographic tables and likely decrypt/encoding sites+ghidrust crypt-constants PATH --algo AES --json+ghidrust recover-strings PATH --only stack,tight,decoded --json+ghidrust crypto-capabilities PATH --tag decrypt --json++# Peel explicit data or ask the bounded heuristic to try common transforms+ghidrust decode bake -b64 SGVsbG8= -op FromBase64 --json+ghidrust decode bake -hex CIPHERTEXT -op AESDecrypt -key-hex KEY -iv-hex IV -mode cbc --json+ghidrust decode magic -b64 SGVsbG8= -depth 3 -crib Hello --json+```++MCP equivalents are `crypt_constants`, `recover_strings`, `list_crypto_capabilities`, `decode_bake`, and `decode_magic`. See [skill/decrypt-feature-test-log.md](skill/decrypt-feature-test-log.md) for the tested feature matrix.++---+## Architecture```diff --git a/crates/ghidrust-agent/src/audit.rs b/crates/ghidrust-agent/src/audit.rsindex 3a1f8fd..7efc75c 100644--- a/crates/ghidrust-agent/src/audit.rs+++ b/crates/ghidrust-agent/src/audit.rs@@ -77,7 +77,10 @@ impl AuditLog {/// callers can surface it in the pane.pub fn append(&self, mut record: AuditRecord) -> io::Result<()> {record.session_id = self.session_id.clone();- let mut f = OpenOptions::new().create(true).append(true).open(&self.path)?;+ let mut f = OpenOptions::new()+ .create(true)+ .append(true)+ .open(&self.path)?;let line = serde_json::to_string(&record).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;writeln!(f, "{line}")?;diff --git a/crates/ghidrust-agent/src/installer.rs b/crates/ghidrust-agent/src/installer.rsindex bf1300b..d74de8a 100644--- a/crates/ghidrust-agent/src/installer.rs+++ b/crates/ghidrust-agent/src/installer.rs@@ -47,7 +47,9 @@ pub fn install_command_for_platform() -> Option<InstallCommand> {"-Command".into(),one_liner.clone(),],- display: format!("powershell -NoProfile -ExecutionPolicy Bypass -Command \"{one_liner}\""),+ display: format!(+ "powershell -NoProfile -ExecutionPolicy Bypass -Command \"{one_liner}\""+ ),docs_url: "https://github.com/xai-org/grok-build/blob/main/README.md",})}@@ -91,8 +93,20 @@ pub fn grok_binary_path() -> Option<PathBuf> {candidates.push(PathBuf::from(&home).join(".grok/bin").join(exe_name));}if let Ok(userprofile) = std::env::var("USERPROFILE") {- candidates.push(PathBuf::from(&userprofile).join(".grok").join("bin").join(exe_name));- candidates.push(PathBuf::from(&userprofile).join("AppData").join("Local").join("Programs").join("grok").join(exe_name));+ candidates.push(+ PathBuf::from(&userprofile)+ .join(".grok")+ .join("bin")+ .join(exe_name),+ );+ candidates.push(+ PathBuf::from(&userprofile)+ .join("AppData")+ .join("Local")+ .join("Programs")+ .join("grok")+ .join(exe_name),+ );}candidates.into_iter().find(|c| c.is_file())}diff --git a/crates/ghidrust-agent/src/lib.rs b/crates/ghidrust-agent/src/lib.rsindex abadd2a..27f2f85 100644--- a/crates/ghidrust-agent/src/lib.rs+++ b/crates/ghidrust-agent/src/lib.rs@@ -28,7 +28,7 @@ pub use system_prompt::{SystemPromptBuilder,};pub use tool_bridge::{- ensure_project_skill, project_skill_path, register_mcp_with_grok_cli,- resolve_ghidrust_cli_bin, skill_content_hash, start_checklist, write_project_mcp_config,- write_project_skill, write_project_skill_embedded, StartChecklistItem, EMBEDDED_SKILL_MD,+ ensure_project_skill, project_skill_path, register_mcp_with_grok_cli, resolve_ghidrust_cli_bin,+ skill_content_hash, start_checklist, write_project_mcp_config, write_project_skill,+ write_project_skill_embedded, StartChecklistItem, EMBEDDED_SKILL_MD,};diff --git a/crates/ghidrust-agent/src/markdown.rs b/crates/ghidrust-agent/src/markdown.rsindex 4bba112..95aeef6 100644--- a/crates/ghidrust-agent/src/markdown.rs+++ b/crates/ghidrust-agent/src/markdown.rs@@ -74,7 +74,11 @@ pub fn parse_markdown(input: &str) -> Vec<MarkdownBlock> {let s = stripped.trim_start();if s.starts_with("```") {if in_code {- push_code(&mut out, std::mem::take(&mut code_lang), std::mem::take(&mut code_buf));+ push_code(+ &mut out,+ std::mem::take(&mut code_lang),+ std::mem::take(&mut code_buf),+ );in_code = false;} else {push_prose(&mut out, std::mem::take(&mut prose_buf));diff --git a/crates/ghidrust-agent/src/system_prompt.rs b/crates/ghidrust-agent/src/system_prompt.rsindex beaf4c5..244bb7f 100644--- a/crates/ghidrust-agent/src/system_prompt.rs+++ b/crates/ghidrust-agent/src/system_prompt.rs@@ -133,7 +133,9 @@ impl<'a> SystemPromptBuilder<'a> {let mut out = String::with_capacity(self.skill_md.len() + 1024);out.push_str("You are Ghidrust's in-GUI reverse-engineering copilot.\n");out.push_str("The user is running Ghidrust (Rust RE toolkit) with a project open.\n");- out.push_str("You have MCP access to every shipped Ghidrust tool via the `ghidrust` server.\n\n");+ out.push_str(+ "You have MCP access to every shipped Ghidrust tool via the `ghidrust` server.\n\n",+ );out.push_str("## Non-negotiable rules\n\n");out.push_str("- Never invent analysis. If a binary hasn't been loaded, say so — do not fabricate addresses, symbols, or decompile output.\n");@@ -153,8 +155,7 @@ impl<'a> SystemPromptBuilder<'a> {if let Some(f) = self.facts {out.push_str("## Live program facts (from Ghidrust GUI state)\n\n");out.push_str("```json\n");- let json =- serde_json::to_string_pretty(f).unwrap_or_else(|_| "{}".to_string());+ let json = serde_json::to_string_pretty(f).unwrap_or_else(|_| "{}".to_string());out.push_str(&json);out.push_str("\n```\n\n");}diff --git a/crates/ghidrust-agent/src/tool_bridge.rs b/crates/ghidrust-agent/src/tool_bridge.rsindex 9f0d484..ac4785f 100644--- a/crates/ghidrust-agent/src/tool_bridge.rs+++ b/crates/ghidrust-agent/src/tool_bridge.rs@@ -120,14 +120,7 @@ pub fn register_mcp_with_grok_cli() -> Result<(), String> {let bin = mcp_bin_string(ghidrust_bin);let status = Command::new(grok_bin)- .args([- "mcp",- "add",- "--scope",- "project",- "ghidrust",- "--",- ])+ .args(["mcp", "add", "--scope", "project", "ghidrust", "--"]).arg(&bin).arg("mcp").current_dir(project_root)@@ -339,9 +332,7 @@ pub fn start_checklist(project_root: &Path) -> Vec<StartChecklistItem> {format!("{} · {}",hash_path.display(),- fs::read_to_string(&hash_path)- .unwrap_or_default()- .trim()+ fs::read_to_string(&hash_path).unwrap_or_default().trim())} else if skill_ok {format!(@@ -405,7 +396,10 @@ mod tests {let root = fs::read_to_string(proj.join(".mcp.json")).unwrap();assert!(root.contains("mcpServers"));assert!(root.contains("ghidrust"));- assert!(!root.contains("//?/"), "must not emit Windows long-path prefix");+ assert!(+ !root.contains("//?/"),+ "must not emit Windows long-path prefix"+ );let grok = fs::read_to_string(proj.join(".grok").join("mcp.json")).unwrap();assert!(grok.contains("mcp"));let toml = fs::read_to_string(proj.join(".grok").join("config.toml")).unwrap();@@ -416,7 +410,9 @@ mod tests {#[test]fn strips_windows_long_path_prefix() {assert_eq!(- mcp_bin_string(Path::new(r"\\?\C:\path\to\Ghidrust\target\release\ghidrust.exe")),+ mcp_bin_string(Path::new(+ r"\\?\C:\path\to\Ghidrust\target\release\ghidrust.exe"+ )),"C:/path/to/Ghidrust/target/release/ghidrust.exe");}diff --git a/crates/ghidrust-cli/src/crypto_cmds.rs b/crates/ghidrust-cli/src/crypto_cmds.rsnew file mode 100644index 0000000..fcc08cf--- /dev/null+++ b/crates/ghidrust-cli/src/crypto_cmds.rs@@ -0,0 +1,510 @@+//! CLI commands for crypt-constants, recover-strings, decode bake/magic, crypto-capabilities.++use ghidrust_core::{+ bake, extract_iocs, load_path, load_path_opts, magic_with_crib, recover_obfuscated_strings, run_analyzers,+ run_crypto_pipeline, scan_crypt_constants, scan_crypto_capabilities, BakeOp,+ RecoverStringsOpts,+};+use serde_json::json;+use std::path::PathBuf;+use std::process::ExitCode;++fn persisted_or_scanned_crypt_constants(+ prog: &ghidrust_core::Program,+) -> Vec<ghidrust_core::CryptConstantHit> {+ if prog.analysis.crypt_constants.is_empty() {+ scan_crypt_constants(prog)+ } else {+ prog.analysis.crypt_constants.clone()+ }+}++fn path_arg(args: &[String]) -> Result<PathBuf, String> {+ args.first()+ .map(PathBuf::from)+ .ok_or_else(|| "missing path".into())+}++pub fn cmd_crypt_constants(args: &[String], json: bool) -> ExitCode {+ let path = match path_arg(args) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("{e}");+ return ExitCode::from(2);+ }+ };+ let mut algo: Option<String> = None;+ let mut limit: Option<usize> = None;+ let mut i = 1;+ while i < args.len() {+ match args[i].as_str() {+ "-algo" if i + 1 < args.len() => {+ algo = Some(args[i + 1].clone());+ i += 2;+ }+ "-limit" if i + 1 < args.len() => {+ limit = args[i + 1].parse().ok();+ i += 2;+ }+ _ => i += 1,+ }+ }+ let prog = match load_path_opts(&path, true) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("load error: {e}");+ return ExitCode::FAILURE;+ }+ };+ let mut hits = persisted_or_scanned_crypt_constants(&prog);+ if let Some(a) = algo {+ hits.retain(|h| h.algorithm.eq_ignore_ascii_case(&a));+ }+ if let Some(l) = limit {+ hits.truncate(l);+ }+ if json {+ println!("{}", serde_json::to_string_pretty(&hits).unwrap());+ } else {+ for h in &hits {+ println!(+ "{:#x} {} {} size={}",+ h.va, h.algorithm, h.constant, h.size+ );+ }+ eprintln!("{} hit(s)", hits.len());+ }+ ExitCode::SUCCESS+}++pub fn cmd_recover_strings(args: &[String], json: bool) -> ExitCode {+ let path = match path_arg(args) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("{e}");+ return ExitCode::from(2);+ }+ };+ let mut opts = RecoverStringsOpts::default();+ let mut i = 1;+ while i < args.len() {+ match args[i].as_str() {+ "-only" if i + 1 < args.len() => {+ opts.only = Some(+ args[i + 1]+ .split(',')+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+ .collect(),+ );+ i += 2;+ }+ "-no" if i + 1 < args.len() => {+ opts.no = Some(+ args[i + 1]+ .split(',')+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+ .collect(),+ );+ i += 2;+ }+ "-functions" if i + 1 < args.len() => {+ let mut fns = Vec::new();+ for part in args[i + 1].split(',') {+ let t = part.trim().trim_start_matches("0x");+ if let Ok(v) = u64::from_str_radix(t, 16) {+ fns.push(v);+ }+ }+ opts.functions = Some(fns);+ i += 2;+ }+ "-limit" if i + 1 < args.len() => {+ opts.limit = args[i + 1].parse().ok();+ i += 2;+ }+ _ => i += 1,+ }+ }+ let mut prog = match load_path_opts(&path, true) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("load error: {e}");+ return ExitCode::FAILURE;+ }+ };+ // Seed Find Crypt xrefs so decoder heuristics prefer crypto sites.+ let _ = run_analyzers(&mut prog, &["Find Crypt"]);+ if opts.functions.is_none() {+ let seeds = ghidrust_core::recover_function_seeds(&prog);+ if !seeds.is_empty() {+ opts.functions = Some(seeds);+ }+ }+ let hits = recover_obfuscated_strings(&prog, &opts);+ if json {+ println!("{}", serde_json::to_string_pretty(&hits).unwrap());+ } else {+ for h in &hits {+ println!(+ "{:#x} {:?} {}",+ h.va,+ h.kind,+ h.value.chars().take(120).collect::<String>()+ );+ }+ eprintln!("{} string(s)", hits.len());+ }+ ExitCode::SUCCESS+}++pub fn cmd_crypto_capabilities(args: &[String], json: bool) -> ExitCode {+ let path = match path_arg(args) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("{e}");+ return ExitCode::from(2);+ }+ };+ let mut tag: Option<String> = None;+ let mut i = 1;+ while i < args.len() {+ match args[i].as_str() {+ "-tag" if i + 1 < args.len() => {+ tag = Some(args[i + 1].clone());+ i += 2;+ }+ _ => i += 1,+ }+ }+ let mut prog = match load_path_opts(&path, true) {+ Ok(p) => p,+ Err(e) => {+ eprintln!("load error: {e}");+ return ExitCode::FAILURE;+ }+ };+ // Full discover pipeline so capability rules see constants + recovered strings.+ let _ = run_crypto_pipeline(&mut prog);+ let hits = scan_crypto_capabilities(&prog, tag.as_deref());+ if json {+ let hits: Vec<_> = hits+ .iter()+ .map(|hit| {+ json!({+ "function_va": hit.function_va,+ "capability": hit.capability,+ "tag": hit.tag,+ "evidence": hit.evidence,+ "attack": hit.attack,+ "mbc": hit.mbc,+ "suggested_ops": ghidrust_core::suggest_recipe_for_hint(&hit.capability)+ .into_iter()+ .map(|op| op.op)+ .collect::<Vec<_>>(),+ })+ })+ .collect();+ println!("{}", serde_json::to_string_pretty(&hits).unwrap());+ } else {+ for h in &hits {+ let va = h+ .function_va+ .map(|v| format!("{v:#x}"))+ .unwrap_or_else(|| "-".into());+ println!("{va} [{}] {} ({})", h.tag, h.capability, h.evidence);+ }+ eprintln!("{} capability hit(s)", hits.len());+ }+ ExitCode::SUCCESS+}++fn parse_input_bytes(args: &[String]) -> Result<(Vec<u8>, Option<PathBuf>), String> {+ let mut hex: Option<String> = None;+ let mut b64: Option<String> = None;+ let mut raw: Option<String> = None;+ let mut file: Option<PathBuf> = None;+ let mut path: Option<PathBuf> = None;+ let mut addr: Option<u64> = None;+ let mut count: usize = 256;+ let mut i = 0;+ while i < args.len() {+ match args[i].as_str() {+ "-hex" if i + 1 < args.len() => {+ hex = Some(args[i + 1].clone());+ i += 2;+ }+ "-b64" | "-base64" if i + 1 < args.len() => {+ b64 = Some(args[i + 1].clone());+ i += 2;+ }+ "-raw" if i + 1 < args.len() => {+ raw = Some(args[i + 1].clone());+ i += 2;+ }+ "-in" if i + 1 < args.len() => {+ file = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }+ "-path" if i + 1 < args.len() => {+ path = Some(PathBuf::from(&args[i + 1]));+ i += 2;+ }+ "-addr" if i + 1 < args.len() => {+ let t = args[i + 1].trim_start_matches("0x");+ addr = Some(u64::from_str_radix(t, 16).map_err(|e| e.to_string())?);+ i += 2;+ }+ "-count" if i + 1 < args.len() => {+ count = args[i + 1].parse().unwrap_or(256);+ i += 2;+ }+ _ => i += 1,+ }+ }+ if let Some(h) = hex {+ let clean: String = h.chars().filter(|c| !c.is_whitespace()).collect();+ let mut out = Vec::new();+ for i in (0..clean.len()).step_by(2) {+ out.push(u8::from_str_radix(&clean[i..i + 2], 16).map_err(|e| e.to_string())?);+ }+ return Ok((out, path));+ }+ if let Some(b) = b64 {+ // Input bytes are the Base64 text itself; peel with a FromBase64 recipe op.+ return Ok((b.into_bytes(), path));+ }+ if let Some(r) = raw {+ return Ok((r.into_bytes(), path));+ }+ if let Some(f) = file {+ return Ok((std::fs::read(&f).map_err(|e| e.to_string())?, path));+ }+ if let (Some(p), Some(a)) = (path.clone(), addr) {+ let prog = load_path(&p).map_err(|e| e.to_string())?;+ let bytes = prog+ .read_va(a, count)+ .ok_or_else(|| format!("cannot read {count} bytes at {a:#x}"))?;+ return Ok((bytes, Some(p)));+ }+ Err("provide -hex, -b64, -raw, -in FILE, or -path + -addr".into())+}++pub fn cmd_decode(args: &[String], json: bool) -> ExitCode {+ if args.is_empty() {+ eprintln!("usage: ghidrust decode bake|magic [opts]");+ return ExitCode::from(2);+ }+ match args[0].as_str() {+ "bake" => cmd_decode_bake(&args[1..], json),+ "magic" => cmd_decode_magic(&args[1..], json),+ other => {+ eprintln!("unknown decode subcommand: {other}");+ ExitCode::from(2)+ }+ }+}++fn cmd_decode_bake(args: &[String], json: bool) -> ExitCode {+ let (input, program_path) = match parse_input_bytes(args) {+ Ok(v) => v,+ Err(e) => {+ eprintln!("{e}");+ return ExitCode::from(2);+ }+ };+ let mut ops: Vec<BakeOp> = Vec::new();+ let mut recipe_json: Option<String> = None;+ let mut annotate_va: Option<u64> = None;+ let mut i = 0;+ while i < args.len() {+ match args[i].as_str() {+ "-annotate-va" if i + 1 < args.len() => {+ let text = args[i + 1].trim_start_matches("0x");+ match u64::from_str_radix(text, 16) {+ Ok(va) => annotate_va = Some(va),+ Err(e) => {+ eprintln!("annotate VA: {e}");+ return ExitCode::from(2);+ }+ }+ i += 2;+ }+ "-recipe" if i + 1 < args.len() => {+ recipe_json = Some(args[i + 1].clone());+ i += 2;+ }+ "-op" if i + 1 < args.len() => {+ let name = args[i + 1].clone();+ i += 2;+ let mut args_obj = json!({});+ while i + 1 < args.len() && args[i].starts_with("--") {+ let k = args[i].trim_start_matches('-').replace('-', "_");+ args_obj[k] = json!(args[i + 1]);+ i += 2;+ }+ // CLI recipe arguments map directly to the core BakeOp JSON arguments.+ // Keep these separate from command/input flags so multiple `-op` stages+ // can be composed predictably.+ while i + 1 < args.len()+ && matches!(+ args[i].as_str(),+ "-key"+ | "-key-hex"+ | "-key_hex"+ | "-key-format"+ | "-key_format"+ | "-iv"+ | "-iv-hex"+ | "-iv_hex"+ | "-nonce"+ | "-nonce-hex"+ | "-nonce_hex"+ | "-counter"+ | "-mode"+ | "-encoding"+ )+ {+ let k = args[i].trim_start_matches('-').replace('-', "_");+ args_obj[k] = if k == "counter" {+ match args[i + 1].parse::<u64>() {+ Ok(value) => json!(value),+ Err(_) => {+ eprintln!("counter must be an unsigned integer");+ return ExitCode::from(2);+ }+ }+ } else {+ json!(args[i + 1])+ };+ i += 2;+ }+ ops.push(BakeOp {+ op: name,+ args: args_obj,+ });+ }+ _ => i += 1,+ }+ }+ if let Some(rj) = recipe_json {+ match serde_json::from_str::<Vec<BakeOp>>(&rj) {+ Ok(r) => ops = r,+ Err(e) => {+ eprintln!("recipe JSON: {e}");+ return ExitCode::from(2);+ }+ }+ }+ if ops.is_empty() {+ eprintln!("provide -recipe JSON or -op NAME [-key-hex …]");+ return ExitCode::from(2);+ }+ let result = bake(&input, &ops);+ let annotation = if result.ok {+ match (program_path, annotate_va) {+ (Some(path), Some(va)) => match load_path(&path) {+ Ok(mut prog) => {+ prog.edits.set_comment(+ va,+ ghidrust_core::CommentKind::Eol,+ format!("decode bake: {}", result.recipe_applied.join(" -> ")),+ );+ Some(json!({+ "va": format!("{va:#x}"),+ "applied": true,+ "persisted": false,+ "note": "comment applied in memory only; a plain path load has no project save target"+ }))+ }+ Err(e) => Some(json!({+ "va": format!("{va:#x}"),+ "applied": false,+ "persisted": false,+ "note": format!("could not load annotation path: {e}")+ })),+ },+ (None, Some(va)) => Some(json!({+ "va": format!("{va:#x}"),+ "applied": false,+ "persisted": false,+ "note": "--annotate-va requires -path PATH"+ })),+ _ => None,+ }+ } else {+ None+ };+ let iocs = if result.ok {+ let bytes: Vec<u8> = (0..result.output_hex.len())+ .step_by(2)+ .filter_map(|i| u8::from_str_radix(&result.output_hex[i..i + 2], 16).ok())+ .collect();+ extract_iocs(&bytes)+ } else {+ vec![]+ };+ if json {+ println!(+ "{}",+ serde_json::to_string_pretty(&json!({+ "result": result,+ "iocs": iocs,+ "annotation": annotation,+ }))+ .unwrap()+ );+ } else if result.ok {+ if let Some(s) = &result.output_utf8 {+ println!("{s}");+ } else {+ println!("{}", result.output_hex);+ }+ for ioc in iocs {+ eprintln!("ioc: {ioc}");+ }+ if let Some(annotation) = annotation {+ eprintln!("{}", annotation["note"].as_str().unwrap_or_default());+ }+ } else {+ eprintln!("{}", result.message);+ return ExitCode::FAILURE;+ }+ ExitCode::SUCCESS+}++fn cmd_decode_magic(args: &[String], json: bool) -> ExitCode {+ let (input, _) = match parse_input_bytes(args) {+ Ok(v) => v,+ Err(e) => {+ eprintln!("{e}");+ return ExitCode::from(2);+ }+ };+ let mut depth = 3usize;+ let mut crib: Option<String> = None;+ let mut i = 0;+ while i < args.len() {+ if args[i] == "-depth" && i + 1 < args.len() {+ depth = args[i + 1].parse().unwrap_or(3);+ i += 2;+ } else if args[i] == "-crib" && i + 1 < args.len() {+ crib = Some(args[i + 1].clone());+ i += 2;+ } else {+ i += 1;+ }+ }+ let result = magic_with_crib(&input, depth, crib.as_deref());+ if json {+ println!("{}", serde_json::to_string_pretty(&result).unwrap());+ } else if let Some(s) = &result.output_utf8 {+ println!("{s}");+ eprintln!("{} — {:?}", result.message, result.recipe_applied);+ } else {+ println!("{}", result.output_hex);+ eprintln!("{} — {:?}", result.message, result.recipe_applied);+ }+ ExitCode::SUCCESS+}diff --git a/crates/ghidrust-cli/src/decode_opts.rs b/crates/ghidrust-cli/src/decode_opts.rsindex 002173f..5d93d7c 100644--- a/crates/ghidrust-cli/src/decode_opts.rs+++ b/crates/ghidrust-cli/src/decode_opts.rs@@ -44,171 +44,174 @@ impl DecodeOpts {let mut i = 0;while i < args.len() {match args[i].as_str() {- "-arch" if i + 1 < args.len() => {+ "-arch" if i + 1 < args.len() => {opts.arch = Some(parse_arch(&args[i + 1])?);i += 2;}- "-mode" if i + 1 < args.len() => {+ "-mode" if i + 1 < args.len() => {opts.mode = Some(parse_mode(&args[i + 1])?);i += 2;}- "-syntax" if i + 1 < args.len() => {+ "-syntax" if i + 1 < args.len() => {opts.syntax = Some(parse_syntax(&args[i + 1])?);i += 2;}- "-detail" => {+ "-detail" => {opts.detail = Some(true);i += 1;}- "-no-detail" => {+ "-no-detail" => {opts.detail = Some(false);i += 1;}- "-detail-real" => {+ "-detail-real" => {opts.detail_real = Some(true);i += 1;}- "-skipdata" => {+ "-skipdata" => {opts.skipdata = Some(true);i += 1;}- "-skipdata-mnemonic" if i + 1 < args.len() => {+ "-skipdata-mnemonic" if i + 1 < args.len() => {opts.skipdata_mnemonic = Some(args[i + 1].clone());i += 2;}- "-skipdata-size" if i + 1 < args.len() => {+ "-skipdata-size" if i + 1 < args.len() => {opts.skipdata_size = Some(args[i + 1].parse()- .map_err(|e| format!("invalid skipdata-size: {e}"))?,+ .map_err(|e| format!("invalid skipdata-size: {e}"))?,);i += 2;}- "-unsigned-imm" => {+ "-unsigned-imm" => {opts.unsigned_imm = Some(true);i += 1;}- "-only-offset-branch" => {+ "-only-offset-branch" => {opts.only_offset_branch = Some(true);i += 1;}- "-litbase" if i + 1 < args.len() => {+ "-litbase" if i + 1 < args.len() => {opts.litbase = Some(parse_u32(&args[i + 1])?);i += 2;}- "-mnem-override" if i + 1 < args.len() => {+ "-mnem-override" if i + 1 < args.len() => {opts.mnem_overrides.push(parse_mnem_override(&args[i + 1])?);i += 2;}- "-addr" if i + 1 < args.len() => {+ "-addr" if i + 1 < args.len() => {opts.addr = Some(parse_u64(&args[i + 1])?);i += 2;}- "-count" if i + 1 < args.len() => {+ "-count" if i + 1 < args.len() => {opts.count = args[i + 1].parse().unwrap_or(Self::default_count());i += 2;}- "-skip-bad" => {+ "-skip-bad" => {opts.skip_bad = true;i += 1;}- "-linear" => {+ "-linear" => {opts.linear = true;i += 1;}- "-flow" => {+ "-flow" => {opts.flow = true;i += 1;}- "-brief" => {+ "-brief" => {opts.brief = true;i += 1;}- "-pretty" => {+ "-pretty" => {opts.pretty = true;i += 1;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {opts.out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}- other if !other.starts_with('-') && path.is_none() => {+ other if !other.starts_with('-') && path.is_none() => {path = Some(PathBuf::from(other));i += 1;}_ => i += 1,}}- let path = path.ok_or_else(|| "missing path".to_string())?;+ let path = path.ok_or_else(|| "missing path".to_string())?;Ok((path, opts))}pub fn from_json(args: &Value) -> Result<Self, String> {let mut opts = Self {count: args- .get("count")+ .get("count").and_then(|c| c.as_u64()).unwrap_or(Self::default_count() as u64) as usize,skip_bad: args- .get("skip_bad")+ .get("skip_bad").and_then(|v| v.as_bool()).unwrap_or(false),..Default::default()};- if let Some(a) = args.get("arch").and_then(|v| v.as_str()) {+ if let Some(a) = args.get("arch").and_then(|v| v.as_str()) {opts.arch = Some(parse_arch(a)?);}- if let Some(m) = args.get("mode") {+ if let Some(m) = args.get("mode") {opts.mode = Some(parse_mode_value(m)?);}- if let Some(s) = args.get("syntax").and_then(|v| v.as_str()) {+ if let Some(s) = args.get("syntax").and_then(|v| v.as_str()) {opts.syntax = Some(parse_syntax(s)?);}- if let Some(v) = args.get("detail").and_then(|v| v.as_bool()) {+ if let Some(v) = args.get("detail").and_then(|v| v.as_bool()) {opts.detail = Some(v);}- if let Some(v) = args.get("detail_real").and_then(|v| v.as_bool()) {+ if let Some(v) = args.get("detail_real").and_then(|v| v.as_bool()) {opts.detail_real = Some(v);}- if let Some(v) = args.get("skipdata").and_then(|v| v.as_bool()) {+ if let Some(v) = args.get("skipdata").and_then(|v| v.as_bool()) {opts.skipdata = Some(v);}- if let Some(v) = args.get("skipdata_mnemonic").and_then(|v| v.as_str()) {+ if let Some(v) = args.get("skipdata_mnemonic").and_then(|v| v.as_str()) {opts.skipdata_mnemonic = Some(v.to_string());}- if let Some(v) = args.get("skipdata_size").and_then(|v| v.as_u64()) {+ if let Some(v) = args.get("skipdata_size").and_then(|v| v.as_u64()) {opts.skipdata_size = Some(v as usize);}- if let Some(v) = args.get("unsigned_imm").and_then(|v| v.as_bool()) {+ if let Some(v) = args.get("unsigned_imm").and_then(|v| v.as_bool()) {opts.unsigned_imm = Some(v);}- if let Some(v) = args.get("only_offset_branch").and_then(|v| v.as_bool()) {+ if let Some(v) = args.get("only_offset_branch").and_then(|v| v.as_bool()) {opts.only_offset_branch = Some(v);}- if let Some(v) = args.get("litbase") {+ if let Some(v) = args.get("litbase") {opts.litbase = Some(parse_u32_value(v)?);}- if let Some(arr) = args.get("mnem_overrides").and_then(|v| v.as_array()) {+ if let Some(arr) = args.get("mnem_overrides").and_then(|v| v.as_array()) {for item in arr {if let Some(pair) = item.as_str() {opts.mnem_overrides.push(parse_mnem_override(pair)?);} else if let Some(obj) = item.as_object() {let id = obj- .get("id")- .ok_or_else(|| "mnem_overrides entry missing id".to_string())+ .get("id")+ .ok_or_else(|| "mnem_overrides entry missing id".to_string()).and_then(parse_u32_value)?;let mnemonic = obj- .get("mnemonic")+ .get("mnemonic").and_then(|v| v.as_str())- .ok_or_else(|| "mnem_overrides entry missing mnemonic".to_string())?+ .ok_or_else(|| "mnem_overrides entry missing mnemonic".to_string())?.to_string();opts.mnem_overrides.push((id, mnemonic));}}}- opts.linear = args.get("linear").and_then(|v| v.as_bool()).unwrap_or(false);- opts.flow = args.get("flow").and_then(|v| v.as_bool()).unwrap_or(false);- if let Some(a) = args.get("addr").and_then(|v| v.as_str()) {+ opts.linear = args+ .get("linear")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ opts.flow = args.get("flow").and_then(|v| v.as_bool()).unwrap_or(false);+ if let Some(a) = args.get("addr").and_then(|v| v.as_str()) {opts.addr = Some(parse_u64(a)?);}Ok(opts)@@ -254,14 +257,14 @@ pub fn normalize_cli_flags(args: &[String]) -> Vec<String> {}pub fn parse_u64(s: &str) -> Result<u64, String> {- let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");+ let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");u64::from_str_radix(t, 16).or_else(|_| s.parse::<u64>()).map_err(|e| e.to_string())}pub fn parse_u32(s: &str) -> Result<u32, String> {- let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");+ let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");u32::from_str_radix(t, 16).or_else(|_| s.parse::<u32>()).map_err(|e| e.to_string())@@ -274,35 +277,35 @@ fn parse_u32_value(v: &Value) -> Result<u32, String> {if let Some(s) = v.as_str() {return parse_u32(s);}- Err("expected u32".into())+ Err("expected u32".into())}pub fn parse_arch(s: &str) -> Result<Arch, String> {match s.trim().to_ascii_lowercase().as_str() {- "arm" => Ok(Arch::Arm),- "arm64" | "aarch64" => Ok(Arch::Arm64),- "mips" => Ok(Arch::Mips),- "x86" | "x86_64" | "x64" | "amd64" => Ok(Arch::X86),- "ppc" | "powerpc" => Ok(Arch::Ppc),- "sparc" => Ok(Arch::Sparc),- "sysz" | "systemz" | "s390" | "s390x" => Ok(Arch::Sysz),- "xcore" => Ok(Arch::Xcore),- "m68k" | "68k" => Ok(Arch::M68k),- "tms320c64x" | "tms320" | "c64x" => Ok(Arch::Tms320c64x),- "m680x" | "6800" | "6809" => Ok(Arch::M680x),- "evm" => Ok(Arch::Evm),- "mos65xx" | "6502" | "65c02" => Ok(Arch::Mos65xx),- "wasm" | "webassembly" => Ok(Arch::Wasm),- "bpf" | "ebpf" => Ok(Arch::Bpf),- "riscv" | "riscv64" | "riscv32" => Ok(Arch::Riscv),- "sh" | "superh" => Ok(Arch::Sh),- "tricore" => Ok(Arch::Tricore),- "alpha" => Ok(Arch::Alpha),- "hppa" | "parisc" | "pa-risc" => Ok(Arch::Hppa),- "loongarch" | "loongarch64" => Ok(Arch::Loongarch),- "xtensa" => Ok(Arch::Xtensa),- "arc" => Ok(Arch::Arc),- other => Err(format!("unknown arch: {other}")),+ "arm" => Ok(Arch::Arm),+ "arm64" | "aarch64" => Ok(Arch::Arm64),+ "mips" => Ok(Arch::Mips),+ "x86" | "x86_64" | "x64" | "amd64" => Ok(Arch::X86),+ "ppc" | "powerpc" => Ok(Arch::Ppc),+ "sparc" => Ok(Arch::Sparc),+ "sysz" | "systemz" | "s390" | "s390x" => Ok(Arch::Sysz),+ "xcore" => Ok(Arch::Xcore),+ "m68k" | "68k" => Ok(Arch::M68k),+ "tms320c64x" | "tms320" | "c64x" => Ok(Arch::Tms320c64x),+ "m680x" | "6800" | "6809" => Ok(Arch::M680x),+ "evm" => Ok(Arch::Evm),+ "mos65xx" | "6502" | "65c02" => Ok(Arch::Mos65xx),+ "wasm" | "webassembly" => Ok(Arch::Wasm),+ "bpf" | "ebpf" => Ok(Arch::Bpf),+ "riscv" | "riscv64" | "riscv32" => Ok(Arch::Riscv),+ "sh" | "superh" => Ok(Arch::Sh),+ "tricore" => Ok(Arch::Tricore),+ "alpha" => Ok(Arch::Alpha),+ "hppa" | "parisc" | "pa-risc" => Ok(Arch::Hppa),+ "loongarch" | "loongarch64" => Ok(Arch::Loongarch),+ "xtensa" => Ok(Arch::Xtensa),+ "arc" => Ok(Arch::Arc),+ other => Err(format!("unknown arch: {other}")),}}@@ -316,72 +319,71 @@ pub fn parse_mode_value(v: &Value) -> Result<Mode, String> {}let s = v.as_str()- .ok_or_else(|| "mode must be string or integer".to_string())?;+ .ok_or_else(|| "mode must be string or integer".to_string())?;let t = s.trim().to_ascii_lowercase();if let Ok(n) = parse_u32(&t) {return Ok(Mode(n));}Ok(match t.as_str() {- "16" | "mode16" => Mode::MODE_16,- "32" | "mode32" | "i386" => Mode::MODE_32,- "64" | "mode64" | "amd64" | "x64" => Mode::MODE_64,- "thumb" => Mode::THUMB,- "mclass" => Mode::MCLASS,- "v8" => Mode::V8,- "mips32" => Mode::MIPS32,- "mips64" => Mode::MIPS64,- "ppc32" => Mode::PPC32,- "ppc64" => Mode::PPC64,- "riscv32" => Mode::RISCV32,- "riscv64" => Mode::RISCV64,- "riscv_c" | "rvc" => Mode::RISCV_C,- "le" | "little" | "little_endian" => Mode::LITTLE_ENDIAN,- "be" | "big" | "big_endian" => Mode::BIG_ENDIAN,- "bpf_classic" => Mode::BPF_CLASSIC,- "bpf_extended" => Mode::BPF_EXTENDED,- "6502" => Mode::MOS65XX_6502,- "65c02" => Mode::MOS65XX_65C02,- other => return Err(format!("unknown mode: {other}")),+ "16" | "mode16" => Mode::MODE_16,+ "32" | "mode32" | "i386" => Mode::MODE_32,+ "64" | "mode64" | "amd64" | "x64" => Mode::MODE_64,+ "thumb" => Mode::THUMB,+ "mclass" => Mode::MCLASS,+ "v8" => Mode::V8,+ "mips32" => Mode::MIPS32,+ "mips64" => Mode::MIPS64,+ "ppc32" => Mode::PPC32,+ "ppc64" => Mode::PPC64,+ "riscv32" => Mode::RISCV32,+ "riscv64" => Mode::RISCV64,+ "riscv_c" | "rvc" => Mode::RISCV_C,+ "le" | "little" | "little_endian" => Mode::LITTLE_ENDIAN,+ "be" | "big" | "big_endian" => Mode::BIG_ENDIAN,+ "bpf_classic" => Mode::BPF_CLASSIC,+ "bpf_extended" => Mode::BPF_EXTENDED,+ "6502" => Mode::MOS65XX_6502,+ "65c02" => Mode::MOS65XX_65C02,+ other => return Err(format!("unknown mode: {other}")),})}pub fn parse_syntax(s: &str) -> Result<Syntax, String> {Ok(match s.trim().to_ascii_lowercase().as_str() {- "default" => Syntax::Default,- "intel" => Syntax::Intel,- "att" => Syntax::Att,- "noregname" | "no_reg_name" => Syntax::NoRegName,- "masm" => Syntax::Masm,- "motorola" => Syntax::Motorola,- "cs_reg_alias" | "reg_alias" => Syntax::CsRegAlias,- "percent" => Syntax::Percent,- "no_dollar" | "nodollar" => Syntax::NoDollar,- "no_alias_text" => Syntax::NoAliasText,- "no_alias_text_compressed" => Syntax::NoAliasTextCompressed,- other => return Err(format!("unknown syntax: {other}")),+ "default" => Syntax::Default,+ "intel" => Syntax::Intel,+ "att" => Syntax::Att,+ "noregname" | "no_reg_name" => Syntax::NoRegName,+ "masm" => Syntax::Masm,+ "motorola" => Syntax::Motorola,+ "cs_reg_alias" | "reg_alias" => Syntax::CsRegAlias,+ "percent" => Syntax::Percent,+ "no_dollar" | "nodollar" => Syntax::NoDollar,+ "no_alias_text" => Syntax::NoAliasText,+ "no_alias_text_compressed" => Syntax::NoAliasTextCompressed,+ other => return Err(format!("unknown syntax: {other}")),})}fn parse_mnem_override(s: &str) -> Result<(u32, String), String> {let (id_s, mnem) = s- .split_once(':')- .ok_or_else(|| "mnem-override must be ID:MNEMONIC".to_string())?;+ .split_once(':')+ .ok_or_else(|| "mnem-override must be ID:MNEMONIC".to_string())?;Ok((parse_u32(id_s)?, mnem.to_string()))}pub fn parse_hex_bytes(s: &str) -> Result<Vec<u8>, String> {- let t = s.trim().trim_start_matches("0x");+ let t = s.trim().trim_start_matches("0x");if t.is_empty() {return Ok(Vec::new());}if t.len() % 2 != 0 {- return Err("hex bytes must have even length".into());+ return Err("hex bytes must have even length".into());}(0..t.len()).step_by(2).map(|i| {- u8::from_str_radix(&t[i..i + 2], 16)- .map_err(|e| format!("invalid hex at {i}: {e}"))+ u8::from_str_radix(&t[i..i + 2], 16).map_err(|e| format!("invalid hex at {i}: {e}"))}).collect()}diff --git a/crates/ghidrust-cli/src/decode_query_cmd.rs b/crates/ghidrust-cli/src/decode_query_cmd.rsindex 60e67cf..5e4f6c1 100644--- a/crates/ghidrust-cli/src/decode_query_cmd.rs+++ b/crates/ghidrust-cli/src/decode_query_cmd.rs@@ -20,50 +20,50 @@ pub fn cmd_decode_query(args: &[String], json: bool) -> ExitCode {let mut i = 0;while i < args.len() {match args[i].as_str() {- "-query" if i + 1 < args.len() => {+ "-query" if i + 1 < args.len() => {query = Some(args[i + 1].clone());i += 2;}- "-arch" if i + 1 < args.len() => {+ "-arch" if i + 1 < args.len() => {arch = Some(parse_arch(&args[i + 1]).unwrap_or_else(|e| {- eprintln!("{e}");+ eprintln!("{e}");std::process::exit(2);}));i += 2;}- "-mode" if i + 1 < args.len() => {- mode = Some(parse_mode_value(&Value::String(args[i + 1].clone())).unwrap_or_else(- |e| {- eprintln!("{e}");+ "-mode" if i + 1 < args.len() => {+ mode = Some(+ parse_mode_value(&Value::String(args[i + 1].clone())).unwrap_or_else(|e| {+ eprintln!("{e}");std::process::exit(2);- },- ));+ }),+ );i += 2;}- "-id" if i + 1 < args.len() => {+ "-id" if i + 1 < args.len() => {id = args[i + 1].parse().ok();i += 2;}- "-index" if i + 1 < args.len() => {+ "-index" if i + 1 < args.len() => {index = args[i + 1].parse().ok();i += 2;}- "-bytes" if i + 1 < args.len() => {+ "-bytes" if i + 1 < args.len() => {bytes = Some(parse_hex_bytes(&args[i + 1]).unwrap_or_else(|e| {- eprintln!("{e}");+ eprintln!("{e}");std::process::exit(2);}));i += 2;}- "-addr" if i + 1 < args.len() => {+ "-addr" if i + 1 < args.len() => {addr = parse_u64(&args[i + 1]).unwrap_or(0);i += 2;}- "-detail" => {+ "-detail" => {detail = true;i += 1;}- other if !other.starts_with('-') && query.is_none() => {+ other if !other.starts_with('-') && query.is_none() => {query = Some(other.to_string());i += 1;}@@ -72,28 +72,28 @@ pub fn cmd_decode_query(args: &[String], json: bool) -> ExitCode {}if detail {- json_args["detail"] = json!(true);+ json_args["detail"] = json!(true);}if let Some(a) = arch {- json_args["arch"] = json!(a.name());+ json_args["arch"] = json!(a.name());}if let Some(m) = mode {- json_args["mode"] = json!(m.bits());+ json_args["mode"] = json!(m.bits());}if let Some(v) = id {- json_args["id"] = json!(v);+ json_args["id"] = json!(v);}if let Some(v) = index {- json_args["index"] = json!(v);+ json_args["index"] = json!(v);}if let Some(b) = &bytes {- json_args["bytes"] = json!(hex::encode(b));+ json_args["bytes"] = json!(hex::encode(b));}- json_args["addr"] = json!(format!("{addr:#x}"));+ json_args["addr"] = json!(format!("{addr:#x}"));if let Some(q) = query {- json_args["query"] = json!(q);+ json_args["query"] = json!(q);} else {- eprintln!("missing -query");+ eprintln!("missing -query");return ExitCode::from(2);}@@ -102,12 +102,12 @@ pub fn cmd_decode_query(args: &[String], json: bool) -> ExitCode {if json {super::emit_json_helper(&body);} else {- println!("{}", serde_json::to_string_pretty(&body).unwrap());+ println!("{}", serde_json::to_string_pretty(&body).unwrap());}ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -115,15 +115,15 @@ pub fn cmd_decode_query(args: &[String], json: bool) -> ExitCode {pub fn run_decode_query(args: &Value) -> Result<Value, String> {let query = args- .get("query")+ .get("query").and_then(|v| v.as_str())- .ok_or_else(|| "missing query".to_string())?;- let arch = if let Some(a) = args.get("arch").and_then(|v| v.as_str()) {+ .ok_or_else(|| "missing query".to_string())?;+ let arch = if let Some(a) = args.get("arch").and_then(|v| v.as_str()) {parse_arch(a)?} else {Arch::X86};- let mode = if let Some(m) = args.get("mode") {+ let mode = if let Some(m) = args.get("mode") {parse_mode_value(m)?} else if arch == Arch::X86 {Mode::MODE_64@@ -135,116 +135,118 @@ pub fn run_decode_query(args: &Value) -> Result<Value, String> {apply_detail_from_json(&mut engine, args)?;match query {- "insn_name" => {+ "insn_name" => {let id = args- .get("id")+ .get("id").and_then(|v| v.as_u64())- .ok_or_else(|| "insn_name requires id".to_string())? as u32;+ .ok_or_else(|| "insn_name requires id".to_string())? as u32;let name = engine.insn_name(InsnId(id))- .ok_or_else(|| format!("unknown insn id {id}"))?;- Ok(json!({ "query": query, "id": id, "name": name }))+ .ok_or_else(|| format!("unknown insn id {id}"))?;+ Ok(json!({ "query": query, "id": id, "name": name }))}- "reg_name" => {+ "reg_name" => {let id = args- .get("id")+ .get("id").and_then(|v| v.as_u64())- .ok_or_else(|| "reg_name requires id".to_string())? as u32;+ .ok_or_else(|| "reg_name requires id".to_string())? as u32;let name = engine.reg_name(RegId(id))- .ok_or_else(|| format!("unknown reg id {id}"))?;- Ok(json!({ "query": query, "id": id, "name": name }))+ .ok_or_else(|| format!("unknown reg id {id}"))?;+ Ok(json!({ "query": query, "id": id, "name": name }))}- "group_name" => {+ "group_name" => {let id = args- .get("id")+ .get("id").and_then(|v| v.as_u64())- .ok_or_else(|| "group_name requires id".to_string())? as u16;+ .ok_or_else(|| "group_name requires id".to_string())? as u16;let name = engine.group_name(ghidrust_core::GroupId::from_raw(id))- .ok_or_else(|| format!("unknown group id {id}"))?;- Ok(json!({ "query": query, "id": id, "name": name }))+ .ok_or_else(|| format!("unknown group id {id}"))?;+ Ok(json!({ "query": query, "id": id, "name": name }))}- q @ ("insn_group" | "reg_read" | "reg_write" | "op_count" | "op_index" | "regs_access") => {+ q @ ("insn_group" | "reg_read" | "reg_write" | "op_count" | "op_index" | "regs_access") => {let insn = decode_insn_arg(&mut engine, args)?;- let idx = args- .get("index")- .and_then(|v| v.as_u64())- .unwrap_or(0) as usize;+ let idx = args.get("index").and_then(|v| v.as_u64()).unwrap_or(0) as usize;match q {- "insn_group" => {+ "insn_group" => {let group = engine.insn_group(&insn, idx)- .ok_or_else(|| format!("no group at index {idx}"))?;+ .ok_or_else(|| format!("no group at index {idx}"))?;Ok(json!({- "query": query,- "index": idx,- "group": group,- }))+ "query": query,+ "index": idx,+ "group": group,+ }))}- "reg_read" => {+ "reg_read" => {let reg = engine.reg_read(&insn, idx)- .ok_or_else(|| format!("no reg_read at index {idx}"))?;+ .ok_or_else(|| format!("no reg_read at index {idx}"))?;let name = engine.reg_name(reg);- Ok(json!({ "query": query, "index": idx, "reg": reg, "name": name }))+ Ok(json!({ "query": query, "index": idx, "reg": reg, "name": name }))}- "reg_write" => {+ "reg_write" => {let reg = engine.reg_write(&insn, idx)- .ok_or_else(|| format!("no reg_write at index {idx}"))?;+ .ok_or_else(|| format!("no reg_write at index {idx}"))?;let name = engine.reg_name(reg);- Ok(json!({ "query": query, "index": idx, "reg": reg, "name": name }))+ Ok(json!({ "query": query, "index": idx, "reg": reg, "name": name }))}- "op_count" => Ok(json!({- "query": query,- "count": engine.op_count(&insn),- })),- "op_index" => {+ "op_count" => Ok(json!({+ "query": query,+ "count": engine.op_count(&insn),+ })),+ "op_index" => {let op = engine.op_index(&insn, idx)- .ok_or_else(|| format!("no operand at index {idx}"))?;- Ok(json!({ "query": query, "index": idx, "operand": op }))+ .ok_or_else(|| format!("no operand at index {idx}"))?;+ Ok(json!({ "query": query, "index": idx, "operand": op }))}- "regs_access" => {+ "regs_access" => {let access = engine.regs_access(&insn)- .ok_or_else(|| "detail required for regs_access".to_string())?;+ .ok_or_else(|| "detail required for regs_access".to_string())?;Ok(json!({- "query": query,- "read": access.read,- "write": access.write,- "implicit_read": access.implicit_read,- "implicit_write": access.implicit_write,- }))+ "query": query,+ "read": access.read,+ "write": access.write,+ "implicit_read": access.implicit_read,+ "implicit_write": access.implicit_write,+ }))}_ => unreachable!(),}}- other => Err(format!("unknown query: {other}")),+ other => Err(format!("unknown query: {other}")),}}-fn decode_insn_arg(engine: &mut Engine, args: &Value) -> Result<ghidrust_core::Instruction, String> {+fn decode_insn_arg(+ engine: &mut Engine,+ args: &Value,+) -> Result<ghidrust_core::Instruction, String> {let bytes_hex = args- .get("bytes")+ .get("bytes").and_then(|v| v.as_str())- .ok_or_else(|| "instruction queries require bytes".to_string())?;+ .ok_or_else(|| "instruction queries require bytes".to_string())?;let bytes = parse_hex_bytes(bytes_hex)?;let addr = args- .get("addr")+ .get("addr").and_then(|v| v.as_str()).map(parse_u64).transpose()?.unwrap_or(0);- if args.get("detail").and_then(|v| v.as_bool()) == Some(true) {- engine.option(Opt::Detail(true)).map_err(|e| e.to_string())?;+ if args.get("detail").and_then(|v| v.as_bool()) == Some(true) {+ engine+ .option(Opt::Detail(true))+ .map_err(|e| e.to_string())?;}engine.disasm_one(&bytes, addr).map_err(|e| e.to_string())}mod hex {pub fn encode(bytes: &[u8]) -> String {- bytes.iter().map(|b| format!("{b:02x}")).collect()+ bytes.iter().map(|b| format!("{b:02x}")).collect()}}diff --git a/crates/ghidrust-cli/src/decode_support_cmd.rs b/crates/ghidrust-cli/src/decode_support_cmd.rsindex f58bd89..945e8ca 100644--- a/crates/ghidrust-cli/src/decode_support_cmd.rs+++ b/crates/ghidrust-cli/src/decode_support_cmd.rs@@ -1,6 +1,6 @@//! `decode-support` CLI command and shared JSON surface.-use ghidrust_core::{support, Arch, DECODE_VERSION, SupportQuery};+use ghidrust_core::{support, Arch, SupportQuery, DECODE_VERSION};use serde_json::{json, Value};pub fn decode_support_json() -> Value {@@ -8,51 +8,51 @@ pub fn decode_support_json() -> Value {.iter().map(|a| {json!({- "name": a.name(),- "supported": support(SupportQuery::Arch(*a)),- })+ "name": a.name(),+ "supported": support(SupportQuery::Arch(*a)),+ })}).collect();json!({- "version": DECODE_VERSION,- "arches": arches,- "options": [- "syntax",- "detail",- "detail_real",- "mode",- "skipdata",- "skipdata_setup",- "mnemonic",- "unsigned",- "only_offset_branch",- "litbase",- ],- "syntax_values()": syntax_values(),- "features": decode_features(),- })+ "version": DECODE_VERSION,+ "arches": arches,+ "options": [+ "syntax",+ "detail",+ "detail_real",+ "mode",+ "skipdata",+ "skipdata_setup",+ "mnemonic",+ "unsigned",+ "only_offset_branch",+ "litbase",+ ],+ "syntax_values()": syntax_values(),+ "features": decode_features(),+ })}pub fn decode_features() -> Value {json!({- "decode_diet": support(SupportQuery::Diet),- "x86_reduce": support(SupportQuery::X86Reduce),- })+ "decode_diet": support(SupportQuery::Diet),+ "x86_reduce": support(SupportQuery::X86Reduce),+ })}pub fn syntax_values() -> Vec<&'static str> {vec![- "default",- "intel",- "att",- "noregname",- "masm",- "motorola",- "cs_reg_alias",- "percent",- "no_dollar",- "no_alias_text",- "no_alias_text_compressed",+ "default",+ "intel",+ "att",+ "noregname",+ "masm",+ "motorola",+ "cs_reg_alias",+ "percent",+ "no_dollar",+ "no_alias_text",+ "no_alias_text_compressed",]}@@ -61,16 +61,21 @@ pub fn cmd_decode_support(_args: &[String], json: bool) -> std::process::ExitCodif json {super::emit_json_helper(&body);} else {- println!("{}", serde_json::to_string_pretty(&body).unwrap());+ println!("{}", serde_json::to_string_pretty(&body).unwrap());}std::process::ExitCode::SUCCESS}/// Apply engine options from JSON for decode-query (detail flag only here).-pub fn apply_detail_from_json(engine: &mut ghidrust_core::Engine, args: &Value) -> Result<(), String> {+pub fn apply_detail_from_json(+ engine: &mut ghidrust_core::Engine,+ args: &Value,+) -> Result<(), String> {use ghidrust_core::Opt;- if args.get("detail").and_then(|v| v.as_bool()) == Some(true) {- engine.option(Opt::Detail(true)).map_err(|e| e.to_string())?;+ if args.get("detail").and_then(|v| v.as_bool()) == Some(true) {+ engine+ .option(Opt::Detail(true))+ .map_err(|e| e.to_string())?;}Ok(())}diff --git a/crates/ghidrust-cli/src/disasm_cmd.rs b/crates/ghidrust-cli/src/disasm_cmd.rsindex 8d38530..75015c6 100644--- a/crates/ghidrust-cli/src/disasm_cmd.rs+++ b/crates/ghidrust-cli/src/disasm_cmd.rs@@ -114,11 +114,7 @@ fn disasm_raw_blob(prog: &Program, opts: &DecodeOpts, json: bool) -> ExitCode {}};let start = opts.addr.unwrap_or(0);- let bytes: Vec<u8> = prog- .blocks- .iter()- .flat_map(|b| b.bytes.clone())- .collect();+ let bytes: Vec<u8> = prog.blocks.iter().flat_map(|b| b.bytes.clone()).collect();let offset = start.min(bytes.len() as u64) as usize;let slice = &bytes[offset..];match engine.disasm(slice, start, opts.count) {diff --git a/crates/ghidrust-cli/src/friction.rs b/crates/ghidrust-cli/src/friction.rsindex 6ed993b..05d4887 100644--- a/crates/ghidrust-cli/src/friction.rs+++ b/crates/ghidrust-cli/src/friction.rs@@ -3,17 +3,16 @@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_resume, LaunchRequest,- process_regions, process_resolve, resolve_function, resolve_result_json, rtti_query,- section_notes_for, spill_artifact, write_json_no_bom, Project, RttiMatchMode, TreeListOpts,- DEFAULT_PREVIEW_LIMIT,+ 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,};use serde_json::{json, Value};use std::path::PathBuf;use std::process::ExitCode;pub fn parse_u64(s: &str) -> Result<u64, String> {- let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");+ let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");u64::from_str_radix(t, 16).or_else(|_| s.parse::<u64>()).map_err(|e| e.to_string())@@ -27,19 +26,19 @@ pub fn resolve_program_path(args: &[String]) -> Result<(PathBuf, Value), String>let mut i = 0;while i < args.len() {match args[i].as_str() {- "-path" if i + 1 < args.len() => {+ "-path" if i + 1 < args.len() => {path = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-project" if i + 1 < args.len() => {+ "-project" if i + 1 < args.len() => {project = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-file-id" | "-file" if i + 1 < args.len() => {+ "-file-id" | "-file" if i + 1 < args.len() => {file_id = Some(args[i + 1].clone());i += 2;}- other if !other.starts_with('-') && path.is_none() && project.is_none() => {+ other if !other.starts_with('-') && path.is_none() && project.is_none() => {path = Some(PathBuf::from(other));i += 1;}@@ -48,76 +47,76 @@ pub fn resolve_program_path(args: &[String]) -> Result<(PathBuf, Value), String>}if let Some(p) = path {let facts = json!({- "path": p.display().to_string(),- "project": Value::Null,- "file_id": Value::Null,- "resolved_path": p.display().to_string(),- });+ "path": p.display().to_string(),+ "project": Value::Null,+ "file_id": Value::Null,+ "resolved_path": p.display().to_string(),+ });return Ok((p, facts));}let Some(proj) = project else {- return Err("provide <path> or -project DIR -file-id ID".into());+ return Err("provide <path> or -project DIR -file-id ID".into());};let Some(fid) = file_id else {- return Err("load with -project requires -file-id".into());+ return Err("load with -project requires -file-id".into());};let project = Project::open(&proj).map_err(|e| e.to_string())?;let entry = project.list_files().into_iter().find(|f| f.id == fid)- .ok_or_else(|| format!("file_id not found: {fid}"))?;+ .ok_or_else(|| format!("file_id not found: {fid}"))?;let resolved = project.root.join(&entry.imported_rel);if !resolved.is_file() {return Err(format!(- "resolved path missing: {} (file_id={fid})",+ "resolved path missing: {} (file_id={fid})",resolved.display()));}let facts = json!({- "path": Value::Null,- "project": proj.display().to_string(),- "file_id": fid,- "resolved_path": resolved.display().to_string(),- "display_name": entry.display_name,- });+ "path": Value::Null,+ "project": proj.display().to_string(),+ "file_id": fid,+ "resolved_path": resolved.display().to_string(),+ "display_name": entry.display_name,+ });Ok((resolved, facts))}pub fn load_json_for_prog(prog: &ghidrust_core::Program, identity: &Value) -> Value {let notes = section_notes_for(prog);json!({- "name": prog.name,- "format": prog.format,- "image_base": format!("{:#x}", prog.image_base),- "entry": prog.entry.map(|e| format!("{e:#x}")),- "identity": identity,- "resolved_path": identity.get("resolved_path").cloned().unwrap_or(Value::Null),- "sections": prog.sections.iter().map(|s| json!({- "name": s.name,- "va": format!("{:#x}", s.va),- "virtual_size": s.virtual_size,- "raw_size": s.raw_size,- "characteristics": format!("{:#x}", s.characteristics),- })).collect::<Vec<_>>(),- "section_notes": notes,- })+ "name": prog.name,+ "format": prog.format,+ "image_base": format!("{:#x}", prog.image_base),+ "entry": prog.entry.map(|e| format!("{e:#x}")),+ "identity": identity,+ "resolved_path": identity.get("resolved_path").cloned().unwrap_or(Value::Null),+ "sections": prog.sections.iter().map(|s| json!({+ "name": s.name,+ "va": format!("{:#x}", s.va),+ "virtual_size": s.virtual_size,+ "raw_size": s.raw_size,+ "characteristics": format!("{:#x}", s.characteristics),+ })).collect::<Vec<_>>(),+ "section_notes": notes,+ })}pub fn cmd_artifact(args: &[String], json: bool) -> ExitCode {if args.is_empty() {- eprintln!("usage: ghidrust artifact get|query|list <id> [-offset N] [-limit N] [-json]");+ eprintln!("usage: ghidrust artifact get|query|list <id> [-offset N] [-limit N] [-json]");return ExitCode::from(2);}match args[0].as_str() {- "list" => match list_artifacts(64) {+ "list" => match list_artifacts(64) {Ok(m) => {if json {- println!("{}", serde_json::to_string_pretty(&m).unwrap());+ println!("{}", serde_json::to_string_pretty(&m).unwrap());} else {for a in m {println!(- "{} kind={} entries={} {}",+ "{} kind={} entries={} {}",a.id, a.kind, a.entry_count, a.path);}@@ -125,34 +124,34 @@ pub fn cmd_artifact(args: &[String], json: bool) -> ExitCode {ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}},- "get" => {+ "get" => {let id = match args.get(1) {Some(i) => i.as_str(),None => {- eprintln!("usage: ghidrust artifact get <id|path>");+ eprintln!("usage: ghidrust artifact get <id|path>");return ExitCode::from(2);}};match artifact_get(id) {Ok(v) => {- println!("{}", serde_json::to_string_pretty(&v).unwrap());+ println!("{}", serde_json::to_string_pretty(&v).unwrap());ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}- "query" => {+ "query" => {let id = match args.get(1) {Some(i) => i.as_str(),None => {- eprintln!("usage: ghidrust artifact query <id|path> [-offset N] [-limit N]");+ eprintln!("usage: ghidrust artifact query <id|path> [-offset N] [-limit N]");return ExitCode::from(2);}};@@ -161,11 +160,11 @@ pub fn cmd_artifact(args: &[String], json: bool) -> ExitCode {let mut i = 2;while i < args.len() {match args[i].as_str() {- "-offset" if i + 1 < args.len() => {+ "-offset" if i + 1 < args.len() => {offset = args[i + 1].parse().unwrap_or(0);i += 2;}- "-limit" if i + 1 < args.len() => {+ "-limit" if i + 1 < args.len() => {limit = args[i + 1].parse().unwrap_or(DEFAULT_PREVIEW_LIMIT);i += 2;}@@ -174,17 +173,17 @@ pub fn cmd_artifact(args: &[String], json: bool) -> ExitCode {}match artifact_query(id, offset, limit) {Ok(env) => {- println!("{}", serde_json::to_string_pretty(&env).unwrap());+ println!("{}", serde_json::to_string_pretty(&env).unwrap());ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}other => {- eprintln!("unknown artifact subcommand: {other}");+ eprintln!("unknown artifact subcommand: {other}");ExitCode::from(2)}}@@ -194,7 +193,7 @@ pub fn cmd_inventory(args: &[String], json: bool) -> ExitCode {let dir = match args.first() {Some(d) => PathBuf::from(d),None => {- eprintln!("usage: ghidrust inventory <dir> [-max-depth N] [-hash] [-out FILE] [-json]");+ eprintln!("usage: ghidrust inventory <dir> [-max-depth N] [-hash] [-out FILE] [-json]");return ExitCode::from(2);}};@@ -204,15 +203,15 @@ pub fn cmd_inventory(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-max-depth" if i + 1 < args.len() => {+ "-max-depth" if i + 1 < args.len() => {max_depth = args[i + 1].parse().unwrap_or(8);i += 2;}- "-hash" => {+ "-hash" => {with_hash = true;i += 1;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}@@ -223,7 +222,7 @@ pub fn cmd_inventory(args: &[String], json: bool) -> ExitCode {Ok(inv) => {let entries = serde_json::to_value(&inv.entries).unwrap();let env = match envelope_or_spill(- "inventory",+ "inventory",entries,64,DEFAULT_PREVIEW_LIMIT,@@ -231,39 +230,36 @@ pub fn cmd_inventory(args: &[String], json: bool) -> ExitCode {) {Ok(e) => e,Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");return ExitCode::FAILURE;}};let body = json!({- "schema_version": inv.schema_version,- "root": inv.root,- "notes": inv.notes,- "envelope": env,- "entries": if inv.entries.len() <= 64 { Value::Array(inv.entries.iter().map(|e| serde_json::to_value(e).unwrap()).collect()) } else { Value::Null },- });+ "schema_version": inv.schema_version,+ "root": inv.root,+ "notes": inv.notes,+ "envelope": env,+ "entries": if inv.entries.len() <= 64 { Value::Array(inv.entries.iter().map(|e| serde_json::to_value(e).unwrap()).collect()) } else { Value::Null },+ });if let Some(p) = out_path {if let Err(e) = write_json_no_bom(&p, &body) {- eprintln!("error: {e}");+ eprintln!("error: {e}");return ExitCode::FAILURE;}}if json {- println!("{}", serde_json::to_string_pretty(&body).unwrap());+ println!("{}", serde_json::to_string_pretty(&body).unwrap());} else {- println!("inventory root={} entries={}", inv.root, inv.entries.len());+ println!("inventory root={} entries={}", inv.root, inv.entries.len());for e in inv.entries.iter().take(32) {println!(- " {} size={} file_ver={:?} product_ver={:?}",- e.path,- e.size,- e.version.file_version,- e.version.product_version+ " {} size={} file_ver={:?} product_ver={:?}",+ e.path, e.size, e.version.file_version, e.version.product_version);}if inv.entries.len() > 32 {println!(- " … {} more (use -json / artifact envelope)",+ " … {} more (use -json / artifact envelope)",inv.entries.len() - 32);}@@ -271,7 +267,7 @@ pub fn cmd_inventory(args: &[String], json: bool) -> ExitCode {ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -282,7 +278,7 @@ pub fn cmd_tree(args: &[String], json: bool) -> ExitCode {Some(d) => PathBuf::from(d),None => {eprintln!(- "usage: ghidrust tree <path> [-max-depth N] [-ext LIST] [-name GLOB] [-json]"+ "usage: ghidrust tree <path> [-max-depth N] [-ext LIST] [-name GLOB] [-json]");return ExitCode::from(2);}@@ -291,21 +287,21 @@ pub fn cmd_tree(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-max-depth" if i + 1 < args.len() => {+ "-max-depth" if i + 1 < args.len() => {opts.max_depth = args[i + 1].parse().unwrap_or(6);i += 2;}- "-ext" if i + 1 < args.len() => {+ "-ext" if i + 1 < args.len() => {opts.extensions = Some(args[i + 1]- .split(',')+ .split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(),);i += 2;}- "-name" if i + 1 < args.len() => {+ "-name" if i + 1 < args.len() => {opts.name_glob = Some(args[i + 1].clone());i += 2;}@@ -315,7 +311,7 @@ pub fn cmd_tree(args: &[String], json: bool) -> ExitCode {let res = list_tree(&dir, opts);let entries_v = serde_json::to_value(&res.entries).unwrap();let env = envelope_or_spill(- "tree",+ "tree",entries_v,128,DEFAULT_PREVIEW_LIMIT,@@ -324,34 +320,34 @@ pub fn cmd_tree(args: &[String], json: bool) -> ExitCode {let env = match env {Ok(e) => e,Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");return ExitCode::FAILURE;}};let body = json!({- "root": res.root,- "truncated": res.truncated,- "envelope": env,- "entries": if res.entries.len() <= 128 {- serde_json::to_value(&res.entries).unwrap()- } else {- Value::Null- },- });+ "root": res.root,+ "truncated": res.truncated,+ "envelope": env,+ "entries": if res.entries.len() <= 128 {+ serde_json::to_value(&res.entries).unwrap()+ } else {+ Value::Null+ },+ });if json {- println!("{}", serde_json::to_string_pretty(&body).unwrap());+ println!("{}", serde_json::to_string_pretty(&body).unwrap());} else {for e in res.entries.iter().take(64) {if let Some(err) = &e.error {- println!("ERR {} ({err})", e.path);+ println!("ERR {} ({err})", e.path);} else if e.is_dir {- println!("DIR {}", e.path);+ println!("DIR {}", e.path);} else {- println!("FILE {} size={:?}", e.path, e.size);+ println!("FILE {} size={:?}", e.path, e.size);}}if res.truncated || res.entries.len() > 64 {- println!("… truncated; drain via artifact envelope");+ println!("… truncated; drain via artifact envelope");}}ExitCode::SUCCESS@@ -365,14 +361,14 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {return ExitCode::from(2);}match args[0].as_str() {- "list" => match process_list() {+ "list" => match process_list() {Ok(list) => {if json {- println!("{}", serde_json::to_string_pretty(&list).unwrap());+ println!("{}", serde_json::to_string_pretty(&list).unwrap());} else {for p in list.iter().take(200) {println!(- "{:>8} {} {}",+ "{:>8} {} {}",p.pid,p.name,p.path.as_deref().unwrap_or("-")@@ -382,31 +378,31 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}},- "attach" => {+ "attach" => {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>");return ExitCode::from(2);}};match process_attach(pid) {Ok(s) => {- println!("{}", serde_json::to_string_pretty(&s).unwrap());+ println!("{}", serde_json::to_string_pretty(&s).unwrap());ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}- "launch" => {- let image = match args.get(1).filter(|s| !s.starts_with('-')) {+ "launch" => {+ let image = match args.get(1).filter(|s| !s.starts_with('-')) {Some(p) => PathBuf::from(p),None => {eprintln!(@@ -420,15 +416,15 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {let mut i = 2;while i < args.len() {match args[i].as_str() {- "-args" if i + 1 < args.len() => {+ "-args" if i + 1 < args.len() => {launch_args = Some(args[i + 1].clone());i += 2;}- "-cwd" if i + 1 < args.len() => {+ "-cwd" if i + 1 < args.len() => {cwd = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-json" => i += 1,+ "-json" => i += 1,_ => i += 1,}}@@ -438,77 +434,77 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {cwd,}) {Ok(r) => {- println!("{}", serde_json::to_string_pretty(&r).unwrap());+ println!("{}", serde_json::to_string_pretty(&r).unwrap());ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}- "resume" => {+ "resume" => {let sid = match args.get(1) {Some(s) => s.as_str(),None => {- eprintln!("usage: ghidrust process resume <session_id>");+ eprintln!("usage: ghidrust process resume <session_id>");return ExitCode::from(2);}};match process_resume(sid) {Ok(()) => {- println!("{{\"ok\":true,\"resumed\":true}}");+ println!("{{\"ok\":true,\"resumed\":true}}");ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}- "detach" => {+ "detach" => {let sid = match args.get(1) {Some(s) => s.as_str(),None => {- eprintln!("usage: ghidrust process detach <session_id>");+ eprintln!("usage: ghidrust process detach <session_id>");return ExitCode::from(2);}};match process_detach(sid) {Ok(()) => {- println!("{{\"ok\":true}}");+ println!("{{\"ok\":true}}");ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}- "modules" => {+ "modules" => {let sid = match args.get(1) {Some(s) => s.as_str(),None => {- eprintln!("usage: ghidrust process modules <session_id>");+ eprintln!("usage: ghidrust process modules <session_id>");return ExitCode::from(2);}};match process_modules(sid) {Ok(m) => {- println!("{}", serde_json::to_string_pretty(&m).unwrap());+ println!("{}", serde_json::to_string_pretty(&m).unwrap());ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}- "read" => {+ "read" => {let sid = match args.get(1) {Some(s) => s.as_str(),None => {- eprintln!("usage: ghidrust process read <session_id> -addr HEX -size N");+ eprintln!("usage: ghidrust process read <session_id> -addr HEX -size N");return ExitCode::from(2);}};@@ -517,11 +513,11 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {let mut i = 2;while i < args.len() {match args[i].as_str() {- "-addr" if i + 1 < args.len() => {+ "-addr" if i + 1 < args.len() => {addr = parse_u64(&args[i + 1]).ok();i += 2;}- "-size" if i + 1 < args.len() => {+ "-size" if i + 1 < args.len() => {size = args[i + 1].parse().unwrap_or(64);i += 2;}@@ -529,27 +525,25 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {}}let Some(va) = addr else {- eprintln!("missing -addr");+ eprintln!("missing -addr");return ExitCode::from(2);};match process_read(sid, va, size) {Ok(r) => {- println!("{}", serde_json::to_string_pretty(&r).unwrap());+ println!("{}", serde_json::to_string_pretty(&r).unwrap());ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}- "resolve" => {+ "resolve" => {let sid = match args.get(1) {Some(s) => s.as_str(),None => {- eprintln!(- "usage: ghidrust process resolve <session_id> -module NAME -rva HEX"- );+ eprintln!("usage: ghidrust process resolve <session_id> -module NAME -rva HEX");return ExitCode::from(2);}};@@ -558,11 +552,11 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {let mut i = 2;while i < args.len() {match args[i].as_str() {- "-module" if i + 1 < args.len() => {+ "-module" if i + 1 < args.len() => {module = Some(args[i + 1].clone());i += 2;}- "-rva" if i + 1 < args.len() => {+ "-rva" if i + 1 < args.len() => {rva = parse_u64(&args[i + 1]).ok();i += 2;}@@ -570,32 +564,32 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {}}let (Some(m), Some(r)) = (module, rva) else {- eprintln!("need -module and -rva");+ eprintln!("need -module and -rva");return ExitCode::from(2);};match process_resolve(sid, &m, r) {Ok(r) => {- println!("{}", serde_json::to_string_pretty(&r).unwrap());+ println!("{}", serde_json::to_string_pretty(&r).unwrap());ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}- "regions" => {+ "regions" => {let sid = match args.get(1) {Some(s) => s.as_str(),None => {- eprintln!("usage: ghidrust process regions <session_id> [-max N]");+ eprintln!("usage: ghidrust process regions <session_id> [-max N]");return ExitCode::from(2);}};let mut max = 256usize;let mut i = 2;while i < args.len() {- if args[i] == "-max" && i + 1 < args.len() {+ if args[i] == "-max" && i + 1 < args.len() {max = args[i + 1].parse().unwrap_or(256);i += 2;} else {@@ -604,17 +598,17 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {}match process_regions(sid, max) {Ok(r) => {- println!("{}", serde_json::to_string_pretty(&r).unwrap());+ println!("{}", serde_json::to_string_pretty(&r).unwrap());ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}other => {- eprintln!("unknown process subcommand: {other}");+ eprintln!("unknown process subcommand: {other}");ExitCode::from(2)}}@@ -622,10 +616,10 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {pub fn cmd_rtti_query_cli(args: &[String], json: bool) -> ExitCode {let path = match args.first() {- Some(p) if !p.starts_with('-') => PathBuf::from(p),+ Some(p) if !p.starts_with('-') => PathBuf::from(p),_ => {eprintln!(- "usage: ghidrust rtti <path> [-filter SUB|-name NAME|-exact] [-match MODE] [-json]"+ "usage: ghidrust rtti <path> [-filter SUB|-name NAME|-exact] [-match MODE] [-json]");return ExitCode::from(2);}@@ -636,15 +630,15 @@ pub fn cmd_rtti_query_cli(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-filter" | "-name" if i + 1 < args.len() => {+ "-filter" | "-name" if i + 1 < args.len() => {filter = Some(args[i + 1].clone());i += 2;}- "-exact" => {+ "-exact" => {exact = true;i += 1;}- "-match" if i + 1 < args.len() => {+ "-match" if i + 1 < args.len() => {mode = RttiMatchMode::parse(&args[i + 1]);i += 2;}@@ -656,31 +650,31 @@ pub fn cmd_rtti_query_cli(args: &[String], json: bool) -> ExitCode {let prog = match load_path(&path) {Ok(p) => p,Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");return ExitCode::FAILURE;}};match rtti_query(&prog, filter.as_deref(), exact, mode) {Ok(q) => {let entries = serde_json::to_value(&q.classes).unwrap();- let env = spill_if_large("rtti", entries, q.entry_count);+ let env = spill_if_large("rtti", entries, q.entry_count);let body = json!({- "entry_count": q.entry_count,- "cache_hit": q.cache_hit,- "notes": q.notes,- "envelope": env,- "classes": if q.entry_count <= 64 {- serde_json::to_value(&q.classes).unwrap()- } else {- Value::Null- },- });+ "entry_count": q.entry_count,+ "cache_hit": q.cache_hit,+ "notes": q.notes,+ "envelope": env,+ "classes": if q.entry_count <= 64 {+ serde_json::to_value(&q.classes).unwrap()+ } else {+ Value::Null+ },+ });if json {- println!("{}", serde_json::to_string_pretty(&body).unwrap());+ println!("{}", serde_json::to_string_pretty(&body).unwrap());} else {for c in q.classes.iter().take(64) {println!(- "{} vtables={:?} col={:?} conf={} {:?}",+ "{} vtables={:?} col={:?} conf={} {:?}",c.name, c.vtable_vas, c.col_va, c.confidence, c.reason);}@@ -688,7 +682,7 @@ pub fn cmd_rtti_query_cli(args: &[String], json: bool) -> ExitCode {ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -709,17 +703,16 @@ pub fn resolve_and_entry(addr: Option<u64>,) -> Result<(u64, Value), String> {let requested = addr.unwrap_or_else(|| prog.entry.unwrap_or(prog.image_base));- // Synthesize/heal orphans so decompile and other agent paths do not hard-fail- // on executable VAs outside analyzed function ranges.+ // Synthesize/heal orphans so decompile and other agent paths do not hard-fail+ // on executable VAs outside analyzed function ranges.let r = resolve_function(prog, requested).map_err(|e| e.to_string())?;let meta = resolve_result_json(&r);if !r.ok {return Err(format!(- "resolve failed: {} ({})",- r.reason.as_deref().unwrap_or("unknown"),+ "resolve failed: {} ({})",+ r.reason.as_deref().unwrap_or("unknown"),meta));}Ok((r.resolved_entry.unwrap(), meta))}-diff --git a/crates/ghidrust-cli/src/main.rs b/crates/ghidrust-cli/src/main.rsindex f8551f2..611374e 100644--- a/crates/ghidrust-cli/src/main.rs+++ b/crates/ghidrust-cli/src/main.rs@@ -1,18 +1,19 @@//! Ghidrust CLI + stdio MCP/agent tool surface over ghidrust-core.-mod friction;+mod crypto_cmds;mod decode_opts;-mod disasm_cmd;-mod decode_support_cmd;mod decode_query_cmd;+mod decode_support_cmd;+mod disasm_cmd;+mod friction;mod mcp_decode;use ghidrust_core::{- analyzer_catalog, analyze_path, artifact_get, artifact_query, assess_decompile_bounds,+ 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_resume, process_resolve,+ 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,@@ -44,7 +45,8 @@ const PACKAGE_VERSION: &str = env!("CARGO_PKG_VERSION");/// `3` = touch-map + body_class map + baseline build_skew + function_create./// `4` = bound-aware disasm + xref attribution + get_calls_from (+ surface 3)./// `5` = decode engine surface (decode_support, decode_query, extended disassemble).-const TOOL_SURFACE_VERSION: u32 = 5;+/// `6` = crypt_constants, recover_strings, decode_bake/magic, crypto_capabilities.+const TOOL_SURFACE_VERSION: u32 = 6;fn package_version() -> &'static str {PACKAGE_VERSION@@ -53,56 +55,61 @@ fn package_version() -> &'static str {fn server_info_json() -> Value {let decode_block = mcp_decode::server_info_decode_section();json!({- "name": "ghidrust",- "version": package_version(),- "tool_surface": TOOL_SURFACE_VERSION,- "decode": decode_block["decode"],- "features": {- "surface": [- "live_process",- "artifacts",- "il2cpp",- "inventory",- "rtti_query",- "list_tree",- "decompile_stage1",- "function_create",- "il2cpp_touch_map",- "bound_disasm",- "get_calls_from",- "decode_support",- "decode_query"- ],- "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."- }- })+ "name": "ghidrust",+ "version": package_version(),+ "tool_surface": TOOL_SURFACE_VERSION,+ "decode": decode_block["decode"],+ "features": {+ "surface": [+ "live_process",+ "artifacts",+ "il2cpp",+ "inventory",+ "rtti_query",+ "list_tree",+ "decompile_stage1",+ "function_create",+ "il2cpp_touch_map",+ "bound_disasm",+ "get_calls_from",+ "decode_support",+ "decode_query",+ "crypt_constants",+ "recover_strings",+ "decode_bake",+ "decode_magic",+ "list_crypto_capabilities"+ ],+ "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."+ }+ })}/// Structured escalation when offline `follow_stub` cannot yield a real method body.fn live_process_next_steps() -> Value {json!([- "process_list",- "process_attach",- "process_modules",- "process_resolve (module + method RVA from il2cpp_map)",- "process_read",- "optional process_regions / process_detach"+ "process_list",+ "process_attach",+ "process_modules",+ "process_resolve (module + method RVA from il2cpp_map)",+ "process_read",+ "optional process_regions / process_detach"])}@@ -122,8 +129,8 @@ fn looks_like_trampoline(prog: &Program, target: u64) -> bool {.iter().map(|i| i.mnemonic.to_ascii_lowercase()).collect::<Vec<_>>()- .join(" ");- text.contains("jmp") || text.contains("ret") || insns.len() <= 3+ .join(" ");+ text.contains("jmp") || text.contains("ret") || insns.len() <= 3} else {false}@@ -138,38 +145,38 @@ fn build_follow_stub_meta(prog: &Program, from: u64, stub: &ResolveStub) -> (Opt(Some(target),json!({- "status": "trampoline_or_invoker",- "from": format!("{from:#x}"),- "to": format!("{target:#x}"),- "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),- "icall_name": stub.icall_name,- "note": "followed target looks like a trampoline/invoker — not a full managed body; use live process for runtime fields",- "next_steps": live_process_next_steps(),- }),+ "status": "trampoline_or_invoker",+ "from": format!("{from:#x}"),+ "to": format!("{target:#x}"),+ "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),+ "icall_name": stub.icall_name,+ "note": "followed target looks like a trampoline/invoker — not a full managed body; use live process for runtime fields",+ "next_steps": live_process_next_steps(),+ }),)} else {(Some(target),json!({- "status": "resolved",- "from": format!("{from:#x}"),- "to": format!("{target:#x}"),- "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),- "icall_name": stub.icall_name,- }),+ "status": "resolved",+ "from": format!("{from:#x}"),+ "to": format!("{target:#x}"),+ "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),+ "icall_name": stub.icall_name,+ }),)}} else {(None,json!({- "status": "runtime_unresolved",- "from": format!("{from:#x}"),- "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),- "icall_name": stub.icall_name,- "note": "empty/runtime slot; offline follow_stub cannot yield method body",- "next_steps": live_process_next_steps(),- }),+ "status": "runtime_unresolved",+ "from": format!("{from:#x}"),+ "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),+ "icall_name": stub.icall_name,+ "note": "empty/runtime slot; offline follow_stub cannot yield method body",+ "next_steps": live_process_next_steps(),+ }),)}}@@ -186,33 +193,34 @@ fn main() -> ExitCode {args.retain(|a| a != "-json");match args[0].as_str() {- "help" | "-h" | "-help" => {+ "help" | "-h" | "-help" => {print_help();ExitCode::SUCCESS}- "version" | "-version" | "-V" => {+ "version" | "-version" | "-V" => {if json_mode {println!(- "{}",+ "{}",serde_json::to_string_pretty(&server_info_json()).unwrap());} else {- println!("ghidrust {}", package_version());- println!("tool_surface={}", TOOL_SURFACE_VERSION);+ println!("ghidrust {}", package_version());+ println!("tool_surface={}", TOOL_SURFACE_VERSION);}ExitCode::SUCCESS}- "load" => cmd_load(&args[1..], json_mode),- "disasm" | "disassemble" => disasm_cmd::cmd_disasm(&args[1..], json_mode),- "decode-support" => decode_support_cmd::cmd_decode_support(&args[1..], json_mode),- "decode-query" => decode_query_cmd::cmd_decode_query(&args[1..], json_mode),- "bytes" | "dump" => cmd_bytes(&args[1..], json_mode),- "rtti" => {+ "load" => cmd_load(&args[1..], json_mode),+ "disasm" | "disassemble" => disasm_cmd::cmd_disasm(&args[1..], json_mode),+ "decode-support" => decode_support_cmd::cmd_decode_support(&args[1..], json_mode),+ "decode-query" => decode_query_cmd::cmd_decode_query(&args[1..], json_mode),+ "bytes" | "dump" => cmd_bytes(&args[1..], json_mode),+ "rtti" => {let rest = &args[1..];- if rest.iter().any(|a| {- matches!(a.as_str(), "-filter" | "-name" | "-exact" | "query")- }) {- let rest = if rest.first().map(|s| s.as_str()) == Some("query") {+ if rest+ .iter()+ .any(|a| matches!(a.as_str(), "-filter" | "-name" | "-exact" | "query"))+ {+ let rest = if rest.first().map(|s| s.as_str()) == Some("query") {&rest[1..]} else {rest@@ -222,35 +230,39 @@ fn main() -> ExitCode {cmd_rtti(rest, json_mode)}}- "analyzers" => cmd_analyzers(json_mode),- "analyze" => cmd_analyze(&args[1..], json_mode),- "strings" => cmd_strings(&args[1..], json_mode),- "xrefs" => cmd_xrefs(&args[1..], json_mode),- "imports" => cmd_imports(&args[1..], json_mode),- "function-at" => cmd_function_at(&args[1..], json_mode),- "function" => cmd_function(&args[1..], json_mode),- "il2cpp" => cmd_il2cpp(&args[1..], json_mode),- "unity-inventory" => cmd_unity_inventory(&args[1..], json_mode),- "inventory" | "pe-inventory" => friction::cmd_inventory(&args[1..], json_mode),- "tree" | "list-tree" => friction::cmd_tree(&args[1..], json_mode),- "artifact" => friction::cmd_artifact(&args[1..], json_mode),- "process" => friction::cmd_process(&args[1..], json_mode),- "bulk-bench" => cmd_bulk_bench(&args[1..], json_mode),- "decompile" => cmd_decompile(&args[1..], json_mode),- "decompile-bench" => cmd_decompile_bench(&args[1..], json_mode),- "ghidra-headtohead" => cmd_ghidra_headtohead(&args[1..], json_mode),- "gpu-decompile" => cmd_gpu_decompile(&args[1..], json_mode),- "re-bench" => cmd_re_bench(&args[1..], json_mode),- "analyzer-bench" => cmd_analyzer_bench(&args[1..], json_mode),- "analyzer-bench-matrix" => {- print!("{}", ghidrust_core::format_matrix_table());+ "analyzers" => cmd_analyzers(json_mode),+ "analyze" => cmd_analyze(&args[1..], json_mode),+ "strings" => cmd_strings(&args[1..], json_mode),+ "crypt-constants" => crypto_cmds::cmd_crypt_constants(&args[1..], json_mode),+ "recover-strings" => crypto_cmds::cmd_recover_strings(&args[1..], json_mode),+ "crypto-capabilities" => crypto_cmds::cmd_crypto_capabilities(&args[1..], json_mode),+ "decode" => crypto_cmds::cmd_decode(&args[1..], json_mode),+ "xrefs" => cmd_xrefs(&args[1..], json_mode),+ "imports" => cmd_imports(&args[1..], json_mode),+ "function-at" => cmd_function_at(&args[1..], json_mode),+ "function" => cmd_function(&args[1..], json_mode),+ "il2cpp" => cmd_il2cpp(&args[1..], json_mode),+ "unity-inventory" => cmd_unity_inventory(&args[1..], json_mode),+ "inventory" | "pe-inventory" => friction::cmd_inventory(&args[1..], json_mode),+ "tree" | "list-tree" => friction::cmd_tree(&args[1..], json_mode),+ "artifact" => friction::cmd_artifact(&args[1..], json_mode),+ "process" => friction::cmd_process(&args[1..], json_mode),+ "bulk-bench" => cmd_bulk_bench(&args[1..], json_mode),+ "decompile" => cmd_decompile(&args[1..], json_mode),+ "decompile-bench" => cmd_decompile_bench(&args[1..], json_mode),+ "ghidra-headtohead" => cmd_ghidra_headtohead(&args[1..], json_mode),+ "gpu-decompile" => cmd_gpu_decompile(&args[1..], json_mode),+ "re-bench" => cmd_re_bench(&args[1..], json_mode),+ "analyzer-bench" => cmd_analyzer_bench(&args[1..], json_mode),+ "analyzer-bench-matrix" => {+ print!("{}", ghidrust_core::format_matrix_table());ExitCode::SUCCESS}- "rtti-gpu-bench" => cmd_rtti_gpu_bench(&args[1..], json_mode),- "project" => cmd_project(&args[1..], json_mode),- "mcp" => run_mcp_stdio(),+ "rtti-gpu-bench" => cmd_rtti_gpu_bench(&args[1..], json_mode),+ "project" => cmd_project(&args[1..], json_mode),+ "mcp" => run_mcp_stdio(),other => {- eprintln!("unknown command: {other}");+ eprintln!("unknown command: {other}");print_help();ExitCode::from(2)}@@ -271,6 +283,13 @@ fn print_help() {ghidrust bytes <path> --addr HEX [--count N] [--out FILE] [--json]\n\ghidrust strings <path> [--raw] [--encoding ascii|utf16|all] [--filter SUB]\n\[--match substr|token|whole|glob] [--min N] [--limit N] [--out FILE] [--json]\n\+ ghidrust crypt-constants <path> [--algo NAME] [--limit N] [--json]\n\+ ghidrust recover-strings <path> [--only stack,tight,decoded] [--no static]\n\+ [--functions HEX[,HEX…]] [--limit N] [--json]\n\+ ghidrust crypto-capabilities <path> [--tag decrypt|encrypt|encoding] [--json]\n\+ ghidrust decode bake [-recipe JSON | -op NAME [-key|-key-hex|-iv|-iv-hex|-nonce|-nonce-hex|-counter|-mode|-encoding VALUE]…]\n\+ (-hex|-b64|-raw|-in|-path+-addr) [--annotate-va HEX with -path]\n\+ ghidrust decode magic [-depth N] [--crib TEXT] (-hex|-b64|-raw|-in|-path+-addr) [--json]\n\ghidrust xrefs <path> (--to HEX | --from HEX | --string FILTER | --import NAME | --calls HEX)\n\[--encoding ascii|utf16le|all] [--skip-stubs] [--classify] [--out FILE] [--json]\n\ghidrust imports <path> [--dll NAME] [--name NAME] [--json]\n\@@ -315,25 +334,25 @@ fn print_help() {fn cmd_project(args: &[String], json: bool) -> ExitCode {if args.is_empty() {- eprintln!("project subcommand required: create|open|import|list|analyze|export");+ eprintln!("project subcommand required: create|open|import|list|analyze|export");return ExitCode::from(2);}match args[0].as_str() {- "create" => {+ "create" => {let dir = match args.get(1) {Some(d) => PathBuf::from(d),None => {- eprintln!("usage: ghidrust project create <dir> [-name NAME]");+ eprintln!("usage: ghidrust project create <dir> [-name NAME]");return ExitCode::from(2);}};let mut name = dir.file_name().map(|s| s.to_string_lossy().into_owned())- .unwrap_or_else(|| "GhidrustProject".into());+ .unwrap_or_else(|| "GhidrustProject".into());let mut i = 2;while i < args.len() {- if args[i] == "-name" && i + 1 < args.len() {+ if args[i] == "-name" && i + 1 < args.len() {name = args[i + 1].clone();i += 2;} else {@@ -343,44 +362,41 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {match Project::create(&dir, name) {Ok(p) => {if json {- println!(- "{}",- serde_json::to_string_pretty(&p.meta).unwrap()- );+ println!("{}", serde_json::to_string_pretty(&p.meta).unwrap());} else {- println!("created project '{}' at {}", p.meta.name, p.root.display());+ println!("created project '{}' at {}", p.meta.name, p.root.display());}ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}- "open" | "list" => {+ "open" | "list" => {let dir = match args.get(1) {Some(d) => PathBuf::from(d),None => {- eprintln!("usage: ghidrust project list <dir>");+ eprintln!("usage: ghidrust project list <dir>");return ExitCode::from(2);}};match Project::open(&dir) {Ok(p) => {if json {- println!("{}", serde_json::to_string_pretty(&p.meta).unwrap());+ println!("{}", serde_json::to_string_pretty(&p.meta).unwrap());} else {- println!("project: {} ({})", p.meta.name, p.root.display());- println!("files:");+ println!("project: {} ({})", p.meta.name, p.root.display());+ println!("files:");for f in p.list_files() {let mark = if p.meta.active_id.as_deref() == Some(&f.id) {- "*"+ "*"} else {- " "+ " "};println!(- " {mark} id={} {} ({})",+ " {mark} id={} {} ({})",f.id, f.display_name, f.imported_rel);}@@ -388,14 +404,14 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}- "import" => {+ "import" => {if args.len() < 3 {- eprintln!("usage: ghidrust project import <project-dir> <binary>");+ eprintln!("usage: ghidrust project import <project-dir> <binary>");return ExitCode::from(2);}let dir = PathBuf::from(&args[1]);@@ -406,10 +422,10 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {}) {Ok((p, e)) => {if json {- println!("{}", serde_json::to_string_pretty(&e).unwrap());+ println!("{}", serde_json::to_string_pretty(&e).unwrap());} else {println!(- "imported {} as id={} -> {}",+ "imported {} as id={} -> {}",e.display_name,e.id,p.binary_path(&e).display()@@ -418,12 +434,12 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}- "analyze" => {+ "analyze" => {if args.len() < 2 {eprintln!("usage: ghidrust project analyze <dir> [-file ID] [-analyzers a,b | -analyzer NAME ..] [-gpu]"@@ -437,12 +453,12 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {let mut i = 2;while i < args.len() {match args[i].as_str() {- "-file" if i + 1 < args.len() => {+ "-file" if i + 1 < args.len() => {file_id = Some(args[i + 1].clone());i += 2;}- "-analyzers" if i + 1 < args.len() => {- for s in args[i + 1].split(',') {+ "-analyzers" if i + 1 < args.len() => {+ for s in args[i + 1].split(',') {let t = s.trim();if !t.is_empty() {analyzers.push(t.to_string());@@ -450,11 +466,11 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {}i += 2;}- "-analyzer" if i + 1 < args.len() => {+ "-analyzer" if i + 1 < args.len() => {analyzers.push(args[i + 1].clone());i += 2;}- "-gpu" => {+ "-gpu" => {use_gpu = true;i += 1;}@@ -466,10 +482,12 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {let entry = if let Some(id) = file_id {p.meta.files.iter().find(|f| f.id == id).cloned()} else {- p.active_file().cloned().or_else(|| p.meta.files.first().cloned())+ p.active_file()+ .cloned()+ .or_else(|| p.meta.files.first().cloned())};let Some(entry) = entry else {- eprintln!("no files in project — import a binary first");+ eprintln!("no files in project — import a binary first");return ExitCode::FAILURE;};let names: Vec<&str> = if analyzers.is_empty() {@@ -480,42 +498,42 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {match p.analyze_file_opts(&entry, &names, use_gpu) {Ok((_prog, saved)) => {if json {- println!("{}", serde_json::to_string_pretty(&saved).unwrap());+ println!("{}", serde_json::to_string_pretty(&saved).unwrap());} else {println!(- "analyzed {} — {} functions, {} listing lines",+ "analyzed {} — {} functions, {} listing lines",entry.display_name,saved.analysis.functions.len(),saved.listing.len());- println!("results: {}", p.analysis_path(&entry.id).display());- println!("listing: {}", p.listing_export_path(&entry.id).display());- println!("export: {}", p.analysis_export_path(&entry.id).display());+ println!("results: {}", p.analysis_path(&entry.id).display());+ println!("listing: {}", p.listing_export_path(&entry.id).display());+ println!("export: {}", p.analysis_export_path(&entry.id).display());}ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}- "export" => {+ "export" => {if args.len() < 2 {- eprintln!("usage: ghidrust project export <dir> [-file ID]");+ eprintln!("usage: ghidrust project export <dir> [-file ID]");return ExitCode::from(2);}let dir = PathBuf::from(&args[1]);let mut file_id: Option<String> = None;let mut i = 2;while i < args.len() {- if args[i] == "-file" && i + 1 < args.len() {+ if args[i] == "-file" && i + 1 < args.len() {file_id = Some(args[i + 1].clone());i += 2;} else {@@ -530,7 +548,7 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {p.active_file().or_else(|| p.meta.files.first())};let Some(entry) = entry else {- eprintln!("no files");+ eprintln!("no files");return ExitCode::FAILURE;};let a = p.analysis_path(&entry.id);@@ -538,29 +556,45 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {let e = p.analysis_export_path(&entry.id);if json {println!(- "{}",+ "{}",json!({- "analysis": a.display().to_string(),- "listing": l.display().to_string(),- "export": e.display().to_string(),- "exists": a.is_file(),- })+ "analysis": a.display().to_string(),+ "listing": l.display().to_string(),+ "export": e.display().to_string(),+ "exists": a.is_file(),+ }));} else {- println!("analysis: {} ({})", a.display(), if a.is_file() { "ok" } else { "missing — run project analyze" });- println!("listing: {} ({})", l.display(), if l.is_file() { "ok" } else { "missing" });- println!("export: {} ({})", e.display(), if e.is_file() { "ok" } else { "missing" });+ println!(+ "analysis: {} ({})",+ a.display(),+ if a.is_file() {+ "ok"+ } else {+ "missing — run project analyze"+ }+ );+ println!(+ "listing: {} ({})",+ l.display(),+ if l.is_file() { "ok" } else { "missing" }+ );+ println!(+ "export: {} ({})",+ e.display(),+ if e.is_file() { "ok" } else { "missing" }+ );}ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}other => {- eprintln!("unknown project subcommand: {other}");+ eprintln!("unknown project subcommand: {other}");ExitCode::from(2)}}@@ -569,26 +603,26 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {fn path_arg(args: &[String]) -> Result<PathBuf, String> {args.first().map(PathBuf::from)- .ok_or_else(|| "missing path".into())+ .ok_or_else(|| "missing path".into())}fn cmd_load(args: &[String], json: bool) -> ExitCode {let (path, identity) = match friction::resolve_program_path(args) {Ok(v) => v,Err(e) => {- // Fall back to positional path for backward compatibility.+ // Fall back to positional path for backward compatibility.match path_arg(args) {Ok(p) => (p.clone(),json!({- "path": p.display().to_string(),- "project": Value::Null,- "file_id": Value::Null,- "resolved_path": p.display().to_string(),- }),+ "path": p.display().to_string(),+ "project": Value::Null,+ "file_id": Value::Null,+ "resolved_path": p.display().to_string(),+ }),),Err(_) => {- eprintln!("{e}");+ eprintln!("{e}");return ExitCode::from(2);}}@@ -598,7 +632,7 @@ fn cmd_load(args: &[String], json: bool) -> ExitCode {let mut i = 0;while i < args.len() {match args[i].as_str() {- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}@@ -608,36 +642,38 @@ fn cmd_load(args: &[String], json: bool) -> ExitCode {match load_path(&path) {Ok(prog) => {let v = friction::load_json_for_prog(&prog, &identity);- emit_result(&v, json, out_path.as_deref(), || print_program_summary(&prog))+ emit_result(&v, json, out_path.as_deref(), || {+ print_program_summary(&prog)+ })}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}fn print_program_summary(prog: &Program) {- println!("name: {}", prog.name);- println!("format: {}", prog.format);- println!("base: {:#x}", prog.image_base);+ println!("name: {}", prog.name);+ println!("format: {}", prog.format);+ println!("base: {:#x}", prog.image_base);if let Some(e) = prog.entry {- println!("entry: {e:#x}");+ println!("entry: {e:#x}");}- println!("sections:");+ println!("sections:");for s in &prog.sections {println!(- " {:8} va={:#x} vsize={:#x} raw={:#x}",+ " {:8} va={:#x} vsize={:#x} raw={:#x}",s.name, s.va, s.virtual_size, s.raw_size);}}fn emit_json<T: Serialize>(value: &T) {- // UTF-8 without BOM — suitable for piping / PowerShell ConvertFrom-Json.+ // UTF-8 without BOM — suitable for piping / PowerShell ConvertFrom-Json.let mut out = io::stdout().lock();if let Err(e) = serde_json::to_writer_pretty(&mut out, value) {- eprintln!("json write error: {e}");+ eprintln!("json write error: {e}");return;}let _ = writeln!(out);@@ -645,19 +681,24 @@ fn emit_json<T: Serialize>(value: &T) {fn emit_json_to_path<T: Serialize>(path: &Path, value: &T) -> bool {if let Err(e) = write_json_no_bom(path, value) {- eprintln!("error writing {}: {e}", path.display());+ eprintln!("error writing {}: {e}", path.display());return false;}true}-fn emit_result<T: Serialize>(value: &T, json: bool, out_path: Option<&Path>, text: impl FnOnce()) -> ExitCode {+fn emit_result<T: Serialize>(+ value: &T,+ json: bool,+ out_path: Option<&Path>,+ text: impl FnOnce(),+) -> ExitCode {if let Some(p) = out_path {if !emit_json_to_path(p, value) {return ExitCode::FAILURE;}if !json {- eprintln!("wrote {}", p.display());+ eprintln!("wrote {}", p.display());}return ExitCode::SUCCESS;}@@ -686,7 +727,7 @@ fn cmd_bytes(args: &[String], json: bool) -> ExitCode {let path = match path_arg(args) {Ok(p) => p,Err(e) => {- eprintln!("{e}");+ eprintln!("{e}");return ExitCode::from(2);}};@@ -696,15 +737,15 @@ fn cmd_bytes(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-addr" if i + 1 < args.len() => {+ "-addr" if i + 1 < args.len() => {addr = parse_u64(&args[i + 1]).ok();i += 2;}- "-count" if i + 1 < args.len() => {+ "-count" if i + 1 < args.len() => {count = args[i + 1].parse().unwrap_or(64).clamp(1, 1_048_576);i += 2;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}@@ -712,7 +753,7 @@ fn cmd_bytes(args: &[String], json: bool) -> ExitCode {}}let Some(addr) = addr else {- eprintln!("usage: ghidrust bytes <path> -addr HEX [-count N] [-out FILE] [-json]");+ eprintln!("usage: ghidrust bytes <path> -addr HEX [-count N] [-out FILE] [-json]");return ExitCode::from(2);};match load_path(&path) {@@ -720,47 +761,47 @@ fn cmd_bytes(args: &[String], json: bool) -> ExitCode {Some(bytes) => {let hex: String = bytes.iter()- .map(|b| format!("{b:02x}"))+ .map(|b| format!("{b:02x}")).collect::<Vec<_>>()- .join(" ");+ .join(" ");let payload = json!({- "addr": format!("{addr:#x}"),- "count": bytes.len(),- "hex": hex,- "bytes": bytes,- });+ "addr": format!("{addr:#x}"),+ "count": bytes.len(),+ "hex": hex,+ "bytes": bytes,+ });emit_result(&payload, json, out_path.as_deref(), || {- // 16-byte rows: hex + ASCII+ // 16-byte rows: hex + ASCIIlet mut off = 0usize;while off < bytes.len() {let row = &bytes[off..(off + 16).min(bytes.len())];let hex_row: String = row.iter()- .map(|b| format!("{b:02x}"))+ .map(|b| format!("{b:02x}")).collect::<Vec<_>>()- .join(" ");+ .join(" ");let ascii: String = row.iter().map(|&b| {if (0x20..=0x7e).contains(&b) {b as char} else {- '.'+ '.'}}).collect();- println!("{:#x}: {:<47} {}", addr + off as u64, hex_row, ascii);+ println!("{:#x}: {:<47} {}", addr + off as u64, hex_row, ascii);off += 16;}})}None => {- eprintln!("error: address {addr:#x} not mapped or unreadable");+ eprintln!("error: address {addr:#x} not mapped or unreadable");ExitCode::FAILURE}},Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -770,11 +811,11 @@ fn cmd_strings(args: &[String], json: bool) -> ExitCode {let path = match path_arg(args) {Ok(p) => p,Err(e) => {- eprintln!("{e}");+ eprintln!("{e}");return ExitCode::from(2);}};- let mut encoding = "all".to_string();+ let mut encoding = "all".to_string();let mut filter: Option<String> = None;let mut min_len: usize = 4;let mut match_mode = StringMatchMode::Substr;@@ -784,47 +825,47 @@ fn cmd_strings(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-encoding" if i + 1 < args.len() => {+ "-encoding" if i + 1 < args.len() => {encoding = args[i + 1].clone();i += 2;}- "-filter" | "-contains" if i + 1 < args.len() => {+ "-filter" | "-contains" if i + 1 < args.len() => {filter = Some(args[i + 1].clone());i += 2;}- "-match" if i + 1 < args.len() => {+ "-match" if i + 1 < args.len() => {match StringMatchMode::parse(&args[i + 1]) {Ok(m) => match_mode = m,Err(e) => {- eprintln!("{e}");+ eprintln!("{e}");return ExitCode::from(2);}}i += 2;}- "-min" if i + 1 < args.len() => {+ "-min" if i + 1 < args.len() => {min_len = args[i + 1].parse().unwrap_or(4);i += 2;}- "-limit" if i + 1 < args.len() => {+ "-limit" if i + 1 < args.len() => {limit = args[i + 1].parse().ok();i += 2;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-raw" => {+ "-raw" => {raw = true;i += 1;}_ => i += 1,}}- // Auto-glob when wildcards present and user left default substr.+ // Auto-glob when wildcards present and user left default substr.if matches!(match_mode, StringMatchMode::Substr) {if let Some(pat) = &filter {- if pat.contains('*') || pat.contains('?') {+ if pat.contains('*') || pat.contains('?') {match_mode = StringMatchMode::Glob;}}@@ -840,7 +881,7 @@ fn cmd_strings(args: &[String], json: bool) -> ExitCode {match std::fs::read(&path) {Ok(bytes) => collect_strings_bytes(&bytes, 0, &opts),Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");return ExitCode::FAILURE;}}@@ -850,11 +891,11 @@ fn cmd_strings(args: &[String], json: bool) -> ExitCode {match strings {Ok(strings) => emit_result(&strings, json, out_path.as_deref(), || {for s in &strings {- println!("{:#x}\t{}\t{}", s.va, s.encoding, s.value);+ println!("{:#x}\t{}\t{}", s.va, s.encoding, s.value);}}),Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -864,7 +905,7 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {let path = match path_arg(args) {Ok(p) => p,Err(e) => {- eprintln!("{e}");+ eprintln!("{e}");return ExitCode::from(2);}};@@ -875,44 +916,44 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {let mut import_name: Option<String> = None;let mut skip_stubs = false;let mut classify = false;- let mut encoding = "all".to_string();+ let mut encoding = "all".to_string();let mut out_path: Option<PathBuf> = None;let mut i = 1;while i < args.len() {match args[i].as_str() {- "-to" if i + 1 < args.len() => {+ "-to" if i + 1 < args.len() => {to = parse_u64(&args[i + 1]).ok();i += 2;}- "-from" if i + 1 < args.len() => {+ "-from" if i + 1 < args.len() => {from = parse_u64(&args[i + 1]).ok();i += 2;}- "-calls" if i + 1 < args.len() => {+ "-calls" if i + 1 < args.len() => {calls = parse_u64(&args[i + 1]).ok();i += 2;}- "-string" if i + 1 < args.len() => {+ "-string" if i + 1 < args.len() => {string_filter = Some(args[i + 1].clone());i += 2;}- "-import" if i + 1 < args.len() => {+ "-import" if i + 1 < args.len() => {import_name = Some(args[i + 1].clone());i += 2;}- "-encoding" if i + 1 < args.len() => {+ "-encoding" if i + 1 < args.len() => {encoding = args[i + 1].clone();i += 2;}- "-skip-stubs" => {+ "-skip-stubs" => {skip_stubs = true;i += 1;}- "-classify" => {+ "-classify" => {classify = true;i += 1;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}@@ -938,7 +979,7 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {match load_path(&path) {Ok(mut prog) => {if let Some(entry) = calls {- let _ = run_analyzers(&mut prog, &["Function Start Search"]);+ let _ = run_analyzers(&mut prog, &["Function Start Search"]);let entry = resolve_function(&mut prog, entry).ok().and_then(|r| r.resolved_entry)@@ -948,22 +989,22 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {.iter().map(|e| {json!({- "from": format!("{:#x}", e.from),- "to": format!("{:#x}", e.to),- "kind": e.kind,- "to_entry": e.to_entry.map(|v| format!("{v:#x}")),- "to_function": e.to_function,- })+ "from": format!("{:#x}", e.from),+ "to": format!("{:#x}", e.to),+ "kind": e.kind,+ "to_entry": e.to_entry.map(|v| format!("{v:#x}")),+ "to_function": e.to_function,+ })}).collect();return emit_result(&rows, json, out_path.as_deref(), || {for r in &rows {println!(- "{} -> {} [{}] to_entry={}",- r["from"].as_str().unwrap_or("?"),- r["to"].as_str().unwrap_or("?"),- r["kind"].as_str().unwrap_or("?"),- r["to_entry"].as_str().unwrap_or("-")+ "{} -> {} [{}] to_entry={}",+ r["from"].as_str().unwrap_or("?"),+ r["to"].as_str().unwrap_or("?"),+ r["kind"].as_str().unwrap_or("?"),+ r["to_entry"].as_str().unwrap_or("-"));}});@@ -980,21 +1021,24 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {if skip_stubs {refs.retain(|r| !is_resolve_stub_va(&prog, r.from));}- let rows: Vec<_> = refs.iter().map(|r| xref_row_json(r, &prog, classify)).collect();+ let rows: Vec<_> = refs+ .iter()+ .map(|r| xref_row_json(r, &prog, classify))+ .collect();emit_result(&rows, json, out_path.as_deref(), || {for r in &rows {println!(- "{} -> {} [{}] {}",- r["from"].as_str().unwrap_or("?"),- r["to"].as_str().unwrap_or("?"),- r["kind"].as_str().unwrap_or("?"),- r["preview"].as_str().unwrap_or("")+ "{} -> {} [{}] {}",+ r["from"].as_str().unwrap_or("?"),+ r["to"].as_str().unwrap_or("?"),+ r["kind"].as_str().unwrap_or("?"),+ r["preview"].as_str().unwrap_or(""));}})}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -1004,18 +1048,18 @@ fn cmd_il2cpp(args: &[String], json: bool) -> ExitCode {let sub = match args.first().map(|s| s.as_str()) {Some(s) => s,None => {- eprintln!("usage: ghidrust il2cpp meta|map|touch-map|stubs|icalls ..");+ eprintln!("usage: ghidrust il2cpp meta|map|touch-map|stubs|icalls ..");return ExitCode::from(2);}};match sub {- "meta" => cmd_il2cpp_meta(&args[1..], json),- "map" => cmd_il2cpp_map(&args[1..], json),- "touch-map" => cmd_il2cpp_touch_map(&args[1..], json),- "stubs" => cmd_il2cpp_stubs(&args[1..], json),- "icalls" => cmd_il2cpp_icalls(&args[1..], json),+ "meta" => cmd_il2cpp_meta(&args[1..], json),+ "map" => cmd_il2cpp_map(&args[1..], json),+ "touch-map" => cmd_il2cpp_touch_map(&args[1..], json),+ "stubs" => cmd_il2cpp_stubs(&args[1..], json),+ "icalls" => cmd_il2cpp_icalls(&args[1..], json),other => {- eprintln!("unknown il2cpp subcommand: {other}");+ eprintln!("unknown il2cpp subcommand: {other}");ExitCode::from(2)}}@@ -1028,19 +1072,19 @@ fn cmd_il2cpp_icalls(args: &[String], json: bool) -> ExitCode {let mut i = 0;while i < args.len() {match args[i].as_str() {- "-binary" if i + 1 < args.len() => {+ "-binary" if i + 1 < args.len() => {binary = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-filter" if i + 1 < args.len() => {+ "-filter" if i + 1 < args.len() => {filter = Some(args[i + 1].clone());i += 2;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}- other if binary.is_none() && !other.starts_with('-') => {+ other if binary.is_none() && !other.starts_with('-') => {binary = Some(PathBuf::from(other));i += 1;}@@ -1049,7 +1093,7 @@ fn cmd_il2cpp_icalls(args: &[String], json: bool) -> ExitCode {}let Some(binary) = binary else {eprintln!(- "usage: ghidrust il2cpp icalls -binary <engine.dll> [-filter SUB] [-out FILE] [-json]"+ "usage: ghidrust il2cpp icalls -binary <engine.dll> [-filter SUB] [-out FILE] [-json]");return ExitCode::from(2);};@@ -1058,70 +1102,67 @@ fn cmd_il2cpp_icalls(args: &[String], json: bool) -> ExitCode {let payload = if let Some(f) = &filter {let hits = filter_entries(&report, f);json!({- "filter": f,- "table_count": report.tables.len(),- "hit_count": hits.len(),- "hits": hits.iter().map(|(ti, e)| json!({- "table_index": ti,- "index": e.index,- "name": e.name,- "name_string_va": format!("{:#x}", e.name_string_va),- "fn_va": format!("{:#x}", e.fn_va),- "fn_rva": format!("{:#x}", e.fn_rva),- })).collect::<Vec<_>>(),- "tables": report.tables.iter().map(|t| json!({- "name_va": format!("{:#x}", t.name_va),- "fn_va": format!("{:#x}", t.fn_va),- "count": t.count,- "layout": t.layout,- "confidence": t.confidence,- })).collect::<Vec<_>>(),- })+ "filter": f,+ "table_count": report.tables.len(),+ "hit_count": hits.len(),+ "hits": hits.iter().map(|(ti, e)| json!({+ "table_index": ti,+ "index": e.index,+ "name": e.name,+ "name_string_va": format!("{:#x}", e.name_string_va),+ "fn_va": format!("{:#x}", e.fn_va),+ "fn_rva": format!("{:#x}", e.fn_rva),+ })).collect::<Vec<_>>(),+ "tables": report.tables.iter().map(|t| json!({+ "name_va": format!("{:#x}", t.name_va),+ "fn_va": format!("{:#x}", t.fn_va),+ "count": t.count,+ "layout": t.layout,+ "confidence": t.confidence,+ })).collect::<Vec<_>>(),+ })} else {json!({- "table_count": report.tables.len(),- "tables": report.tables.iter().map(|t| json!({- "name_va": format!("{:#x}", t.name_va),- "fn_va": format!("{:#x}", t.fn_va),- "count": t.count,- "layout": t.layout,- "confidence": t.confidence,- "entries": t.entries.iter().take(64).map(|e| json!({- "index": e.index,- "name": e.name,- "name_string_va": format!("{:#x}", e.name_string_va),- "fn_va": format!("{:#x}", e.fn_va),- "fn_rva": format!("{:#x}", e.fn_rva),- })).collect::<Vec<_>>(),- })).collect::<Vec<_>>(),- })+ "table_count": report.tables.len(),+ "tables": report.tables.iter().map(|t| json!({+ "name_va": format!("{:#x}", t.name_va),+ "fn_va": format!("{:#x}", t.fn_va),+ "count": t.count,+ "layout": t.layout,+ "confidence": t.confidence,+ "entries": t.entries.iter().take(64).map(|e| json!({+ "index": e.index,+ "name": e.name,+ "name_string_va": format!("{:#x}", e.name_string_va),+ "fn_va": format!("{:#x}", e.fn_va),+ "fn_rva": format!("{:#x}", e.fn_rva),+ })).collect::<Vec<_>>(),+ })).collect::<Vec<_>>(),+ })};emit_result(&payload, json, out_path.as_deref(), || {println!(- "icall tables: {} (engine {})",+ "icall tables: {} (engine {})",report.tables.len(),binary.display());for t in report.tables.iter().take(8) {println!(- " names {:#x} fns {:#x} count={} conf={:.2} {:?}",+ " names {:#x} fns {:#x} count={} conf={:.2} {:?}",t.name_va, t.fn_va, t.count, t.confidence, t.layout);}if let Some(f) = &filter {let hits = filter_entries(&report, f);- println!("filter {:?} hits: {}", f, hits.len());+ println!("filter {:?} hits: {}", f, hits.len());for (_ti, e) in hits.iter().take(40) {- println!(- " [{}] RVA {:#x} {}",- e.index, e.fn_rva, e.name- );+ println!(" [{}] RVA {:#x} {}", e.index, e.fn_rva, e.name);}}})}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -1131,7 +1172,9 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {let path = match args.first() {Some(p) => PathBuf::from(p),None => {- eprintln!("usage: ghidrust il2cpp meta <metadata.dat> [-filter SUB] [-out FILE] [-json]");+ eprintln!(+ "usage: ghidrust il2cpp meta <metadata.dat> [-filter SUB] [-out FILE] [-json]"+ );return ExitCode::from(2);}};@@ -1140,11 +1183,11 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-filter" if i + 1 < args.len() => {+ "-filter" if i + 1 < args.len() => {filter = Some(args[i + 1].clone());i += 2;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}@@ -1163,11 +1206,11 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {.into_iter().map(|m| {json!({- "index": m.index,- "name": m.name,- "full_name": meta.method_full_name(m),- "token": m.token,- })+ "index": m.index,+ "name": m.name,+ "full_name": meta.method_full_name(m),+ "token": m.token,+ })}).collect(),None => meta@@ -1175,31 +1218,31 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {.iter().map(|m| {json!({- "index": m.index,- "name": m.name,- "full_name": meta.method_full_name(m),- "token": m.token,- })+ "index": m.index,+ "name": m.name,+ "full_name": meta.method_full_name(m),+ "token": m.token,+ })}).collect(),};let report = json!({- "version": meta.header.version,- "dialect": meta.header.dialect,- "type_count": meta.types.len(),- "method_count": meta.methods.len(),- "image_count": meta.images.len(),- "types": types.iter().map(|t| json!({- "index": t.index,- "full_name": t.full_name(),- "method_count": t.method_count,- "token": t.token,- })).collect::<Vec<_>>(),- "methods": methods,- });+ "version": meta.header.version,+ "dialect": meta.header.dialect,+ "type_count": meta.types.len(),+ "method_count": meta.methods.len(),+ "image_count": meta.images.len(),+ "types": types.iter().map(|t| json!({+ "index": t.index,+ "full_name": t.full_name(),+ "method_count": t.method_count,+ "token": t.token,+ })).collect::<Vec<_>>(),+ "methods": methods,+ });emit_result(&report, json, out_path.as_deref(), || {println!(- "IL2CPP metadata v{} {:?} — {} types, {} methods, {} images",+ "IL2CPP metadata v{} {:?} — {} types, {} methods, {} images",meta.header.version,meta.header.dialect,meta.types.len(),@@ -1207,10 +1250,10 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {meta.images.len());for t in types.iter().take(50) {- println!(" type {}", t.full_name());+ println!(" type {}", t.full_name());}if types.len() > 50 {- println!(" .. {} more types", types.len() - 50);+ println!(" .. {} more types", types.len() - 50);}})}@@ -1219,9 +1262,12 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {if json {return emit_result(&payload, true, out_path.as_deref(), || {});}- eprintln!("{}", serde_json::to_string_pretty(&payload).unwrap_or_else(|_| e.to_string()));+ eprintln!(+ "{}",+ serde_json::to_string_pretty(&payload).unwrap_or_else(|_| e.to_string())+ );} else {- eprintln!("error: {e}");+ eprintln!("error: {e}");}ExitCode::FAILURE}@@ -1240,35 +1286,35 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {let mut i = 0;while i < args.len() {match args[i].as_str() {- "-binary" if i + 1 < args.len() => {+ "-binary" if i + 1 < args.len() => {binary = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-meta" if i + 1 < args.len() => {+ "-meta" if i + 1 < args.len() => {meta_path = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-meta-sections" if i + 1 < args.len() => {+ "-meta-sections" if i + 1 < args.len() => {meta_sections = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-filter" if i + 1 < args.len() => {+ "-filter" if i + 1 < args.len() => {filter = Some(args[i + 1].clone());i += 2;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-baseline" if i + 1 < args.len() => {+ "-baseline" if i + 1 < args.len() => {baseline_path = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-baseline-strict" => {+ "-baseline-strict" => {baseline_strict = true;i += 1;}- "-script-json" => {+ "-script-json" => {script_json = true;i += 1;}@@ -1277,19 +1323,19 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {}let Some(binary) = binary else {eprintln!(- "usage: ghidrust il2cpp map -binary <il2cpp> -meta <metadata.dat>|-meta-sections DIR\n\+ "usage: ghidrust il2cpp map -binary <il2cpp> -meta <metadata.dat>|-meta-sections DIR\n\[-filter SUB] [-baseline PREV.json] [-baseline-strict] [-script-json] [-out FILE] [-json]");return ExitCode::from(2);};if meta_path.is_none() && meta_sections.is_none() {- eprintln!("error: provide -meta PATH or -meta-sections DIR");+ eprintln!("error: provide -meta PATH or -meta-sections DIR");return ExitCode::from(2);}let prog = match load_path(&binary) {Ok(p) => p,Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");return ExitCode::FAILURE;}};@@ -1301,11 +1347,11 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {return emit_result(&payload, true, out_path.as_deref(), || {});}eprintln!(- "{}",+ "{}",serde_json::to_string_pretty(&payload).unwrap_or_else(|_| e.to_string()));} else {- eprintln!("error: {e}");+ eprintln!("error: {e}");}return ExitCode::FAILURE;}@@ -1323,7 +1369,7 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {map.build_skew = Some(compare_baseline(&map, &prev));}Err(e) => {- eprintln!("error loading baseline: {e}");+ eprintln!("error loading baseline: {e}");return ExitCode::FAILURE;}}@@ -1332,7 +1378,7 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {let script = to_script_json(&map);return emit_result(&script, json, out_path.as_deref(), || {println!(- "script.json methods with addresses: {}",+ "script.json methods with addresses: {}",script.script_method.len());});@@ -1345,17 +1391,17 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {.unwrap_or(false);let code = emit_result(&map, json, out_path.as_deref(), || {println!(- "method map: {} entries, pointer_count={:?}, shared_stubs={}",+ "method map: {} entries, pointer_count={:?}, shared_stubs={}",map.entries.len(),map.method_pointer_count,map.shared_stubs.len());for n in &map.notes {- println!(" note: {n}");+ println!(" note: {n}");}if let Some(skew) = &map.build_skew {println!(- " build_skew: moved={} missing={} appeared={}",+ " build_skew: moved={} missing={} appeared={}",skew.moved.len(),skew.missing.len(),skew.appeared.len()@@ -1366,23 +1412,26 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {Some(rva) => {let bc = e.body_class- .map(|c| format!(" [{c:?}]"))+ .map(|c| format!(" [{c:?}]")).unwrap_or_default();- println!(" {:#x} {}{bc}", rva, e.full_name);+ println!(" {:#x} {}{bc}", rva, e.full_name);}- None => println!(" (unmapped) {}", e.full_name),+ None => println!(" (unmapped) {}", e.full_name),}}});if strict_fail {- eprintln!("baseline-strict: {} moved RVAs", map.build_skew.as_ref().map(|s| s.moved.len()).unwrap_or(0));+ eprintln!(+ "baseline-strict: {} moved RVAs",+ map.build_skew.as_ref().map(|s| s.moved.len()).unwrap_or(0)+ );ExitCode::FAILURE} else {code}}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -1397,23 +1446,23 @@ fn cmd_il2cpp_touch_map(args: &[String], json: bool) -> ExitCode {let mut i = 0;while i < args.len() {match args[i].as_str() {- "-meta" if i + 1 < args.len() => {+ "-meta" if i + 1 < args.len() => {meta_path = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-meta-sections" if i + 1 < args.len() => {+ "-meta-sections" if i + 1 < args.len() => {meta_sections = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-filter" if i + 1 < args.len() => {+ "-filter" if i + 1 < args.len() => {filter = Some(args[i + 1].clone());i += 2;}- "-binary" if i + 1 < args.len() => {+ "-binary" if i + 1 < args.len() => {binary = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}@@ -1427,14 +1476,14 @@ fn cmd_il2cpp_touch_map(args: &[String], json: bool) -> ExitCode {return ExitCode::from(2);};if meta_path.is_none() && meta_sections.is_none() {- eprintln!("error: provide -meta PATH or -meta-sections DIR");+ eprintln!("error: provide -meta PATH or -meta-sections DIR");return ExitCode::from(2);}let prog = match &binary {Some(b) => match load_path(b) {Ok(p) => Some(p),Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");return ExitCode::FAILURE;}},@@ -1448,16 +1497,16 @@ fn cmd_il2cpp_touch_map(args: &[String], json: bool) -> ExitCode {) {Ok(report) => emit_result(&report, json, out_path.as_deref(), || {println!(- "touch-map filter={:?} rows={}",+ "touch-map filter={:?} rows={}",report.filter, report.row_count);for r in report.rows.iter().take(40) {println!(- " {:?} {} conf={:?} {}",+ " {:?} {} conf={:?} {}",r.kind,r.string,r.confidence,- r.full_name.as_deref().unwrap_or("-")+ r.full_name.as_deref().unwrap_or("-"));}}),@@ -1467,11 +1516,11 @@ fn cmd_il2cpp_touch_map(args: &[String], json: bool) -> ExitCode {return emit_result(&payload, true, out_path.as_deref(), || {});}eprintln!(- "{}",+ "{}",serde_json::to_string_pretty(&payload).unwrap_or_else(|_| e.to_string()));} else {- eprintln!("error: {e}");+ eprintln!("error: {e}");}ExitCode::FAILURE}@@ -1486,23 +1535,23 @@ fn cmd_il2cpp_stubs(args: &[String], json: bool) -> ExitCode {let mut i = 0;while i < args.len() {match args[i].as_str() {- "-binary" if i + 1 < args.len() => {+ "-binary" if i + 1 < args.len() => {binary = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-filter" if i + 1 < args.len() => {+ "-filter" if i + 1 < args.len() => {filter = Some(args[i + 1].clone());i += 2;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-max" if i + 1 < args.len() => {+ "-max" if i + 1 < args.len() => {max_scan = args[i + 1].parse().unwrap_or(max_scan);i += 2;}- other if binary.is_none() && !other.starts_with('-') => {+ other if binary.is_none() && !other.starts_with('-') => {binary = Some(PathBuf::from(other));i += 1;}@@ -1522,18 +1571,18 @@ fn cmd_il2cpp_stubs(args: &[String], json: bool) -> ExitCode {stubs.retain(|s| stub_matches_filter(&prog, s, f));}emit_result(&stubs, json, out_path.as_deref(), || {- println!("resolve stubs: {}", stubs.len());+ println!("resolve stubs: {}", stubs.len());for s in stubs.iter().take(80) {println!(- " {:#x} {}",+ " {:#x} {}",s.entry,- s.icall_name.as_deref().unwrap_or("(unnamed)")+ s.icall_name.as_deref().unwrap_or("(unnamed)"));}})}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -1543,7 +1592,7 @@ fn cmd_unity_inventory(args: &[String], json: bool) -> ExitCode {let path = match args.first() {Some(p) => PathBuf::from(p),None => {- eprintln!("usage: ghidrust unity-inventory <game-dir> [-out FILE] [-json]");+ eprintln!("usage: ghidrust unity-inventory <game-dir> [-out FILE] [-json]");return ExitCode::from(2);}};@@ -1551,7 +1600,7 @@ fn cmd_unity_inventory(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}@@ -1560,9 +1609,12 @@ fn cmd_unity_inventory(args: &[String], json: bool) -> ExitCode {}match inventory_path(&path) {Ok(inv) => emit_result(&inv, json, out_path.as_deref(), || {- println!("unity-inventory schema={} root={}", inv.schema_version, inv.root);println!(- " verdict={:?} confidence={:?} il2cpp={} xr_stock={} xr_pkg={} external={}",+ "unity-inventory schema={} root={}",+ inv.schema_version, inv.root+ );+ println!(+ " verdict={:?} confidence={:?} il2cpp={} xr_stock={} xr_pkg={} external={}",inv.verdict,inv.confidence,inv.engine.il2cpp,@@ -1571,11 +1623,11 @@ fn cmd_unity_inventory(args: &[String], json: bool) -> ExitCode {inv.external_vr_indicators.len());for n in &inv.notes {- println!(" note: {n}");+ println!(" note: {n}");}}),Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -1585,7 +1637,7 @@ fn cmd_imports(args: &[String], json: bool) -> ExitCode {let path = match path_arg(args) {Ok(p) => p,Err(e) => {- eprintln!("{e}");+ eprintln!("{e}");return ExitCode::from(2);}};@@ -1594,11 +1646,11 @@ fn cmd_imports(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-dll" if i + 1 < args.len() => {+ "-dll" if i + 1 < args.len() => {dll = Some(args[i + 1].clone());i += 2;}- "-name" if i + 1 < args.len() => {+ "-name" if i + 1 < args.len() => {name = Some(args[i + 1].clone());i += 2;}@@ -1618,28 +1670,25 @@ fn cmd_imports(args: &[String], json: bool) -> ExitCode {let sym = e.name.clone()- .unwrap_or_else(|| format!("ord_{}", e.ordinal.unwrap_or(0)));- println!(- "{:#x}\t{}!{}",- e.iat_va, e.dll, sym- );+ .unwrap_or_else(|| format!("ord_{}", e.ordinal.unwrap_or(0)));+ println!("{:#x}\t{}!{}", e.iat_va, e.dll, sym);}}ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}}fn cmd_function(args: &[String], json: bool) -> ExitCode {- let sub = args.first().map(|s| s.as_str()).unwrap_or("");+ let sub = args.first().map(|s| s.as_str()).unwrap_or("");match sub {- "create" => cmd_function_create(&args[1..], json),+ "create" => cmd_function_create(&args[1..], json),_ => {- eprintln!("usage: ghidrust function create <path> -addr HEX [-end HEX] [-json]");+ eprintln!("usage: ghidrust function create <path> -addr HEX [-end HEX] [-json]");ExitCode::from(2)}}@@ -1649,7 +1698,7 @@ fn cmd_function_create(args: &[String], json: bool) -> ExitCode {let path = match path_arg(args) {Ok(p) => p,Err(e) => {- eprintln!("{e}");+ eprintln!("{e}");return ExitCode::from(2);}};@@ -1658,11 +1707,11 @@ fn cmd_function_create(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-addr" if i + 1 < args.len() => {+ "-addr" if i + 1 < args.len() => {addr = parse_u64(&args[i + 1]).ok();i += 2;}- "-end" if i + 1 < args.len() => {+ "-end" if i + 1 < args.len() => {end = parse_u64(&args[i + 1]).ok();i += 2;}@@ -1670,7 +1719,7 @@ fn cmd_function_create(args: &[String], json: bool) -> ExitCode {}}let Some(va) = addr else {- eprintln!("usage: ghidrust function create <path> -addr HEX [-end HEX] [-json]");+ eprintln!("usage: ghidrust function create <path> -addr HEX [-end HEX] [-json]");return ExitCode::from(2);};match load_path(&path) {@@ -1678,21 +1727,21 @@ fn cmd_function_create(args: &[String], json: bool) -> ExitCode {let f = create_function(&mut prog, va, end);if json {emit_json(&json!({- "entry": format!("{:#x}", f.entry),- "end": format!("{:#x}", f.end),- "name": f.name,- "seed_kind": f.seed_kind,- }));+ "entry": format!("{:#x}", f.entry),+ "end": format!("{:#x}", f.end),+ "name": f.name,+ "seed_kind": f.seed_kind,+ }));} else {println!(- "created {} [{:#x}, {:#x}) seed_kind={:?}",+ "created {} [{:#x}, {:#x}) seed_kind={:?}",f.name, f.entry, f.end, f.seed_kind);}ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -1702,7 +1751,7 @@ fn cmd_function_at(args: &[String], json: bool) -> ExitCode {let path = match path_arg(args) {Ok(p) => p,Err(e) => {- eprintln!("{e}");+ eprintln!("{e}");return ExitCode::from(2);}};@@ -1710,7 +1759,7 @@ fn cmd_function_at(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-addr" if i + 1 < args.len() => {+ "-addr" if i + 1 < args.len() => {addr = parse_u64(&args[i + 1]).ok();i += 2;}@@ -1718,12 +1767,12 @@ fn cmd_function_at(args: &[String], json: bool) -> ExitCode {}}let Some(va) = addr else {- eprintln!("usage: ghidrust function-at <path> -addr HEX [-json]");+ eprintln!("usage: ghidrust function-at <path> -addr HEX [-json]");return ExitCode::from(2);};match load_path(&path).and_then(|mut prog| {if prog.analysis.functions.is_empty() {- let _ = run_analyzers(&mut prog, &["Function Start Search"])?;+ let _ = run_analyzers(&mut prog, &["Function Start Search"])?;}Ok(prog)}) {@@ -1731,37 +1780,34 @@ fn cmd_function_at(args: &[String], json: bool) -> ExitCode {Some(f) => {if json {emit_json(&json!({- "addr": format!("{va:#x}"),- "entry": format!("{:#x}", f.entry),- "end": format!("{:#x}", f.end),- "name": f.name,- "calling_convention": f.calling_convention,- "noreturn": f.noreturn,- "parameters": f.parameters,- }));+ "addr": format!("{va:#x}"),+ "entry": format!("{:#x}", f.entry),+ "end": format!("{:#x}", f.end),+ "name": f.name,+ "calling_convention": f.calling_convention,+ "noreturn": f.noreturn,+ "parameters": f.parameters,+ }));} else {- println!(- "{:#x} in {} [{:#x}, {:#x})",- va, f.name, f.entry, f.end- );+ println!("{:#x} in {} [{:#x}, {:#x})", va, f.name, f.entry, f.end);}ExitCode::SUCCESS}None => {if json {emit_json(&json!({- "addr": format!("{va:#x}"),- "function": null,- }));+ "addr": format!("{va:#x}"),+ "function": null,+ }));ExitCode::SUCCESS} else {- eprintln!("no function contains {va:#x}");+ eprintln!("no function contains {va:#x}");ExitCode::FAILURE}}},Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -1771,18 +1817,18 @@ fn cmd_rtti(args: &[String], json: bool) -> ExitCode {let path = match path_arg(args) {Ok(p) => p,Err(e) => {- eprintln!("{e}");+ eprintln!("{e}");return ExitCode::from(2);}};match load_path(&path).and_then(|p| recover_rtti(&p).map(|r| (p, r))) {Ok((_prog, report)) => {if json {- println!("{}", serde_json::to_string_pretty(&report).unwrap());+ println!("{}", serde_json::to_string_pretty(&report).unwrap());} else {for c in &report.classes {println!(- "class {} type_info={} vtable={} col={} ({})",+ "class {} type_info={} vtable={} col={} ({})",c.name,fmt_opt_va(c.type_info_va),fmt_opt_va(c.vtable_va),@@ -1791,13 +1837,13 @@ fn cmd_rtti(args: &[String], json: bool) -> ExitCode {);}for n in &report.notes {- println!("note: {n}");+ println!("note: {n}");}}ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -1807,23 +1853,23 @@ fn cmd_bulk_bench(args: &[String], json: bool) -> ExitCode {let path = match args.first() {Some(p) => PathBuf::from(p),None => {- eprintln!("usage: ghidrust bulk-bench <path> [-json]");+ eprintln!("usage: ghidrust bulk-bench <path> [-json]");return ExitCode::from(2);}};let prog = match load_path(&path) {Ok(p) => p,Err(e) => {- eprintln!("load error: {e}");+ eprintln!("load error: {e}");return ExitCode::from(1);}};- // Concatenate all blocks for a single bulk haystack (transfer-style bulk RE).+ // Concatenate all blocks for a single bulk haystack (transfer-style bulk RE).let mut hay = Vec::new();for b in &prog.blocks {hay.extend_from_slice(&b.bytes);}- // Pad synthetic bulk so PCIe/thread overhead is measurable without fake wins.+ // Pad synthetic bulk so PCIe/thread overhead is measurable without fake wins.if hay.len() < 2 * 1024 * 1024 {let mut big = hay.clone();while big.len() < 4 * 1024 * 1024 {@@ -1841,7 +1887,7 @@ fn cmd_bulk_bench(args: &[String], json: bool) -> ExitCode {let (gpu_s, gpu_b) = scan_ascii_strings_bulk(&prog, 4, BulkScanMode::GpuOrFallback);if seq_s != par_s || seq_s != gpu_s {eprintln!(- "correctness fail: seq={} par={} gpu={}",+ "correctness fail: seq={} par={} gpu={}",seq_s.len(),par_s.len(),gpu_s.len()@@ -1850,15 +1896,15 @@ fn cmd_bulk_bench(args: &[String], json: bool) -> ExitCode {}if json {let v = json!({- "timing": timing,- "program_strings": seq_s.len(),- "program_par_backend": format!("{par_b:?}"),- "program_gpu_backend": format!("{gpu_b:?}"),- });- println!("{}", serde_json::to_string_pretty(&v).unwrap());+ "timing": timing,+ "program_strings": seq_s.len(),+ "program_par_backend": format!("{par_b:?}"),+ "program_gpu_backend": format!("{gpu_b:?}"),+ });+ println!("{}", serde_json::to_string_pretty(&v).unwrap());} else {println!(- "bulk-bench {} bytes threads={} seq_ms={:.3} par_ms={:.3} gpu_ms={:.3} hits={}",+ "bulk-bench {} bytes threads={} seq_ms={:.3} par_ms={:.3} gpu_ms={:.3} hits={}",timing.bytes,timing.threads,timing.seq_ms,@@ -1866,10 +1912,10 @@ fn cmd_bulk_bench(args: &[String], json: bool) -> ExitCode {timing.gpu_ms,timing.seq_hits);- println!("par_backend={:?}", timing.par_backend);- println!("gpu_backend={:?}", timing.gpu_backend);+ println!("par_backend={:?}", timing.par_backend);+ println!("gpu_backend={:?}", timing.gpu_backend);println!(- "program ASCII strings: {} (seq/par/gpu equal) par={:?} gpu={:?}",+ "program ASCII strings: {} (seq/par/gpu equal) par={:?} gpu={:?}",seq_s.len(),par_b,gpu_b@@ -1882,15 +1928,15 @@ fn cmd_analyzer_bench(args: &[String], json: bool) -> ExitCode {let path = match args.first() {Some(p) => PathBuf::from(p),None => {- eprintln!("usage: ghidrust analyzer-bench <path> [-large] [-out FILE] [-json]");+ eprintln!("usage: ghidrust analyzer-bench <path> [-large] [-out FILE] [-json]");return ExitCode::from(2);}};- let large = args.iter().any(|a| a == "-large");+ let large = args.iter().any(|a| a == "-large");let mut out_path: Option<PathBuf> = None;let mut i = 1;while i < args.len() {- if args[i] == "-out" && i + 1 < args.len() {+ if args[i] == "-out" && i + 1 < args.len() {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;} else {@@ -1900,16 +1946,16 @@ fn cmd_analyzer_bench(args: &[String], json: bool) -> ExitCode {let prog = match load_path(&path) {Ok(p) => p,Err(e) => {- eprintln!("load error: {e}");+ eprintln!("load error: {e}");return ExitCode::FAILURE;}};let large_min = if large { Some(8 * 1024 * 1024) } else { None };let mut rows = ghidrust_core::bench_all_analyzers(&prog, large_min);rows.push(ghidrust_core::bench_gpu_decompile_row(&prog));- // Full GPU decompile multipass via shipped bench API (CPU wall + multipass oracle).+ // Full GPU decompile multipass via shipped bench API (CPU wall + multipass oracle).{- let tmp = std::env::temp_dir().join("ghidrust_ab_decomp.gdecomp");+ let tmp = std::env::temp_dir().join("ghidrust_ab_decomp.gdecomp");if let Ok(b) = ghidrust_decomp::bench_vram_decompile_vs_cpu(&prog, &tmp, 256) {rows.push(ghidrust_core::AnalyzerBenchRow {name: "GPU Decompile VRAM multipass".into(),@@ -1942,17 +1988,17 @@ fn cmd_analyzer_bench(args: &[String], json: bool) -> ExitCode {}}- let mut log = String::from("=== analyzer CPU vs GPU bench ===\n");+ let mut log = String::from("=== analyzer CPU vs GPU bench ===\n");log.push_str(&format!(- "file={} large={} analyzers={}\n",+ "file={} large={} analyzers={}\n",path.display(),large,rows.len()));- log.push_str("name\tstrategy\tcpu_ms\tcpu_n\tpcie_up\tdevice_ms\tpcie_dn\tpcie_ms\tgpu_wall\tgpu_n\tequal\tbackend\tdevice\n");+ log.push_str("name\tstrategy\tcpu_ms\tcpu_n\tpcie_up\tdevice_ms\tpcie_dn\tpcie_ms\tgpu_wall\tgpu_n\tequal\tbackend\tdevice\n");for r in &rows {log.push_str(&format!(- "{}\t{}\t{:.3}\t{}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{}\t{}\t{}\t{}\n",+ "{}\t{}\t{:.3}\t{}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{}\t{}\t{}\t{}\n",r.name,r.strategy,r.cpu_ms,@@ -1971,15 +2017,15 @@ fn cmd_analyzer_bench(args: &[String], json: bool) -> ExitCode {if let Some(p) = out_path {let _ = std::fs::write(&p, &log);let _ = std::fs::write(- p.with_extension("json"),+ p.with_extension("json"),serde_json::to_string_pretty(&rows).unwrap_or_default(),);- eprintln!("wrote {}", p.display());+ eprintln!("wrote {}", p.display());}if json {- println!("{}", serde_json::to_string_pretty(&rows).unwrap());+ println!("{}", serde_json::to_string_pretty(&rows).unwrap());} else {- print!("{log}");+ print!("{log}");}ExitCode::SUCCESS}@@ -1990,14 +2036,14 @@ fn cmd_rtti_gpu_bench(args: &[String], json: bool) -> ExitCode {let path = match args.first() {Some(p) => PathBuf::from(p),None => {- eprintln!("usage: ghidrust rtti-gpu-bench <path> [-out FILE] [-json]");+ eprintln!("usage: ghidrust rtti-gpu-bench <path> [-out FILE] [-json]");return ExitCode::from(2);}};let mut out_path: Option<PathBuf> = None;let mut i = 1;while i < args.len() {- if args[i] == "-out" && i + 1 < args.len() {+ if args[i] == "-out" && i + 1 < args.len() {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;} else {@@ -2009,7 +2055,7 @@ fn cmd_rtti_gpu_bench(args: &[String], json: bool) -> ExitCode {let prog = match load_path(&path) {Ok(p) => p,Err(e) => {- eprintln!("load error: {e}");+ eprintln!("load error: {e}");return ExitCode::FAILURE;}};@@ -2017,68 +2063,68 @@ fn cmd_rtti_gpu_bench(args: &[String], json: bool) -> ExitCode {let file_bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);let image_bytes: usize = prog.blocks.iter().map(|b| b.bytes.len()).sum();- // CPU full RTTI recovery (oracle / product path)+ // CPU full RTTI recovery (oracle / product path)let t_cpu = Instant::now();let rtti = match recover_rtti(&prog) {Ok(r) => r,Err(e) => {- eprintln!("cpu rtti error: {e}");+ eprintln!("cpu rtti error: {e}");return ExitCode::FAILURE;}};let cpu_rtti_ms = t_cpu.elapsed().as_secs_f64() * 1000.0;- // Analyzer-shaped primary (same name as Auto Analysis option)- let name = "WindowsPE x86 PE RTTI Analyzer";+ // Analyzer-shaped primary (same name as Auto Analysis option)+ let name = "WindowsPE x86 PE RTTI Analyzer";let row = ghidrust_core::bench_analyzer(&prog, name, None);let report = json!({- "file": path.display().to_string(),- "file_bytes": file_bytes,- "file_mb": (file_bytes as f64) / (1024.0 * 1024.0),- "image_bytes": image_bytes,- "load_ms": load_ms,- "cpu_rtti_recover_ms": cpu_rtti_ms,- "cpu_rtti_classes": rtti.classes.len(),- "gpu_strategy": row.strategy,- "gpu_seed_cpu_ms": row.cpu_ms,- "gpu_seed_cpu_hits": row.cpu_primary,- "gpu_pcie_upload_ms": row.gpu_pcie_upload_ms,- "gpu_device_ms": row.gpu_device_ms,- "gpu_pcie_download_ms": row.gpu_pcie_download_ms,- "gpu_pcie_ms": row.gpu_pcie_ms,- "gpu_wall_ms": row.gpu_wall_ms,- "gpu_seed_hits": row.gpu_primary,- "seed_equal": row.equal,- "merged_primary": row.merged_primary,- "backend": row.backend,- "device": row.device,- "note": row.note,- "performance_model": {- "on_device_vs_seed_cpu": if row.cpu_ms > 0.0 {- row.cpu_ms / row.gpu_device_ms.max(1e-9)- } else { 0.0 },- "pcie_vs_device": row.gpu_pcie_ms / row.gpu_device_ms.max(1e-9),- "summary": "On-device SIMT is often much faster than the CPU seed scan; PCIe upload of the image + cold GPU setup usually dominate wall time. A ~170MB PE does not make GPU compute slow — transfer cost scales with size."- }- });+ "file": path.display().to_string(),+ "file_bytes": file_bytes,+ "file_mb": (file_bytes as f64) / (1024.0 * 1024.0),+ "image_bytes": image_bytes,+ "load_ms": load_ms,+ "cpu_rtti_recover_ms": cpu_rtti_ms,+ "cpu_rtti_classes": rtti.classes.len(),+ "gpu_strategy": row.strategy,+ "gpu_seed_cpu_ms": row.cpu_ms,+ "gpu_seed_cpu_hits": row.cpu_primary,+ "gpu_pcie_upload_ms": row.gpu_pcie_upload_ms,+ "gpu_device_ms": row.gpu_device_ms,+ "gpu_pcie_download_ms": row.gpu_pcie_download_ms,+ "gpu_pcie_ms": row.gpu_pcie_ms,+ "gpu_wall_ms": row.gpu_wall_ms,+ "gpu_seed_hits": row.gpu_primary,+ "seed_equal": row.equal,+ "merged_primary": row.merged_primary,+ "backend": row.backend,+ "device": row.device,+ "note": row.note,+ "performance_model": {+ "on_device_vs_seed_cpu": if row.cpu_ms > 0.0 {+ row.cpu_ms / row.gpu_device_ms.max(1e-9)+ } else { 0.0 },+ "pcie_vs_device": row.gpu_pcie_ms / row.gpu_device_ms.max(1e-9),+ "summary": "On-device SIMT is often much faster than the CPU seed scan; PCIe upload of the image + cold GPU setup usually dominate wall time. A ~170MB PE does not make GPU compute slow — transfer cost scales with size."+ }+ });let mut log = String::new();- log.push_str("=== RTTI CPU vs GPU bench ===\n");+ log.push_str("=== RTTI CPU vs GPU bench ===\n");log.push_str(&format!(- "file={} size_mb={:.2} image_bytes={}\n",+ "file={} size_mb={:.2} image_bytes={}\n",path.display(),(file_bytes as f64) / (1024.0 * 1024.0),image_bytes));log.push_str(&format!(- "load_ms={:.3} cpu_rtti_recover_ms={:.3} cpu_classes={}\n",+ "load_ms={:.3} cpu_rtti_recover_ms={:.3} cpu_classes={}\n",load_ms,cpu_rtti_ms,rtti.classes.len()));log.push_str(&format!(- "gpu_strategy={} backend={} device={}\n",+ "gpu_strategy={} backend={} device={}\n",row.strategy, row.backend, row.device));log.push_str(&format!(@@ -2094,7 +2140,7 @@ fn cmd_rtti_gpu_bench(args: &[String], json: bool) -> ExitCode {row.equal));log.push_str(&format!(- "on_device_speedup_vs_seed_cpu={:.1}x pcie/device={:.1}x\n",+ "on_device_speedup_vs_seed_cpu={:.1}x pcie/device={:.1}x\n",if row.cpu_ms > 0.0 {row.cpu_ms / row.gpu_device_ms.max(1e-9)} else {@@ -2109,15 +2155,15 @@ fn cmd_rtti_gpu_bench(args: &[String], json: bool) -> ExitCode {if let Some(p) = out_path {let _ = std::fs::write(&p, &log);let _ = std::fs::write(- p.with_extension("json"),+ p.with_extension("json"),serde_json::to_string_pretty(&report).unwrap_or_default(),);- eprintln!("wrote {}", p.display());+ eprintln!("wrote {}", p.display());}if json {- println!("{}", serde_json::to_string_pretty(&report).unwrap());+ println!("{}", serde_json::to_string_pretty(&report).unwrap());} else {- print!("{log}");+ print!("{log}");}ExitCode::SUCCESS}@@ -2132,21 +2178,21 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {return ExitCode::from(2);}};- let mut out_path = PathBuf::from("ghidrust_gpu_decompile.gdecomp");+ let mut out_path = PathBuf::from("ghidrust_gpu_decompile.gdecomp");let mut metrics_path: Option<PathBuf> = None;let mut addr: Option<u64> = None;let mut i = 1;while i < args.len() {match args[i].as_str() {- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = PathBuf::from(&args[i + 1]);i += 2;}- "-metrics" if i + 1 < args.len() => {+ "-metrics" if i + 1 < args.len() => {metrics_path = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-addr" if i + 1 < args.len() => {+ "-addr" if i + 1 < args.len() => {addr = parse_u64(&args[i + 1]).ok();i += 2;}@@ -2156,14 +2202,14 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {let mut prog = match load_path(&path) {Ok(p) => p,Err(e) => {- eprintln!("load error: {e}");+ eprintln!("load error: {e}");return ExitCode::FAILURE;}};let (entry_va, resolve_meta) = match friction::resolve_and_entry(&mut prog, addr) {Ok(v) => v,Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");return ExitCode::FAILURE;}};@@ -2171,7 +2217,7 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {let cpu = match ghidrust_decomp::decompile_at(&prog, entry_va, 64) {Ok(d) => d,Err(e) => {- eprintln!("cpu decompile: {e}");+ eprintln!("cpu decompile: {e}");return ExitCode::FAILURE;}};@@ -2180,17 +2226,17 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {let rep = match ghidrust_decomp::gpu_decompile_to_file(&prog, Some(entry_va), &out_path, 128) {Ok(r) => r,Err(e) => {- eprintln!("gpu-decompile error: {e}");+ eprintln!("gpu-decompile error: {e}");return ExitCode::FAILURE;}};- // Equivalence: multipass algorithm (GPU dump vs CPU multipass on same code)+ // Equivalence: multipass algorithm (GPU dump vs CPU multipass on same code)let entry = rep.entry;let (code, _) = match ghidrust_decomp::region_bytes(&prog, entry, 128) {Ok(v) => v,Err(e) => {- eprintln!("region: {e}");+ eprintln!("region: {e}");return ExitCode::FAILURE;}};@@ -2199,32 +2245,32 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {== ghidrust_decomp::normalize_pseudo(&multi.pseudo_c);let metrics = json!({- "file": path.display().to_string(),- "resolve": resolve_meta,- "requested_addr": addr.map(|a| format!("{a:#x}")),- "resolved_entry": format!("{entry_va:#x}"),- "dump_path": out_path.display().to_string(),- "note": ".gdecomp is opaque binary dump — use metrics JSON, not dump-as-text",- "cpu_decompile_ms": cpu_ms,- "cpu_blocks": cpu.blocks.len(),- "cpu_chars": cpu.char_count(),- "gpu_backend": rep.backend,- "gpu_device": rep.device,- "gpu_ms": rep.ms,- "mid_pipeline_host_reads": rep.mid_pipeline_host_reads,- "kernels": rep.kernels_dispatched,- "dump_path": rep.dump_path,- "dump_bytes": rep.dump_bytes,- "gpu_ir_count": rep.ir_count,- "gpu_block_count": rep.block_count,- "gpu_edge_count": rep.edge_count,- "equivalence_multipass": equal,- "pseudo_c_head": rep.pseudo_c.lines().take(6).collect::<Vec<_>>().join("\n"),- });+ "file": path.display().to_string(),+ "resolve": resolve_meta,+ "requested_addr": addr.map(|a| format!("{a:#x}")),+ "resolved_entry": format!("{entry_va:#x}"),+ "dump_path": out_path.display().to_string(),+ "note": ".gdecomp is opaque binary dump — use metrics JSON, not dump-as-text",+ "cpu_decompile_ms": cpu_ms,+ "cpu_blocks": cpu.blocks.len(),+ "cpu_chars": cpu.char_count(),+ "gpu_backend": rep.backend,+ "gpu_device": rep.device,+ "gpu_ms": rep.ms,+ "mid_pipeline_host_reads": rep.mid_pipeline_host_reads,+ "kernels": rep.kernels_dispatched,+ "dump_path": rep.dump_path,+ "dump_bytes": rep.dump_bytes,+ "gpu_ir_count": rep.ir_count,+ "gpu_block_count": rep.block_count,+ "gpu_edge_count": rep.edge_count,+ "equivalence_multipass": equal,+ "pseudo_c_head": rep.pseudo_c.lines().take(6).collect::<Vec<_>>().join("\n"),+ });if let Some(mp) = metrics_path {let text = format!(- "=== GPU-resident full decompile metrics ===\n\+ "=== GPU-resident full decompile metrics ===\n\file: {}\n\cpu_decompile_ms: {:.3}\n\gpu_backend: {}\n\@@ -2253,28 +2299,28 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {);let _ = std::fs::write(&mp, &text);let _ = std::fs::write(- mp.with_extension("json"),+ mp.with_extension("json"),serde_json::to_string_pretty(&metrics).unwrap(),);- eprintln!("metrics → {}", mp.display());+ eprintln!("metrics → {}", mp.display());}if json {- println!("{}", serde_json::to_string_pretty(&metrics).unwrap());+ println!("{}", serde_json::to_string_pretty(&metrics).unwrap());} else {- println!("GPU decompile dump → {}", out_path.display());+ println!("GPU decompile dump → {}", out_path.display());println!(- "backend={} device={} ms={:.3} mid_reads={} equal={}",+ "backend={} device={} ms={:.3} mid_reads={} equal={}",rep.backend, rep.device, rep.ms, rep.mid_pipeline_host_reads, equal);- print!("{}", rep.pseudo_c);+ print!("{}", rep.pseudo_c);}if !equal {- eprintln!("warning: multipass equivalence failed (see dump vs CPU multipass)");+ eprintln!("warning: multipass equivalence failed (see dump vs CPU multipass)");return ExitCode::FAILURE;}if rep.mid_pipeline_host_reads != 0 {- eprintln!("warning: mid-pipeline host IR reads != 0");+ eprintln!("warning: mid-pipeline host IR reads != 0");return ExitCode::FAILURE;}ExitCode::SUCCESS@@ -2292,9 +2338,9 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {};let mut addr: Option<u64> = None;let mut count: usize = 64;- // Stage-1 is the product default. `-stage0` / `-stage05`- // opt out for oracle / regression comparisons; explicit `-stage1`- // is accepted for symmetry.+ // Stage-1 is the product default. `-stage0` / `-stage05`+ // opt out for oracle / regression comparisons; explicit `-stage1`+ // is accepted for symmetry.let mut stage05 = false;let mut stage0 = false;let mut stage1 = true;@@ -2304,40 +2350,40 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-addr" if i + 1 < args.len() => {+ "-addr" if i + 1 < args.len() => {addr = parse_u64(&args[i + 1]).ok();i += 2;}- "-count" if i + 1 < args.len() => {+ "-count" if i + 1 < args.len() => {count = args[i + 1].parse().unwrap_or(64);i += 2;}- "-stage0" | "-stage-0" | "-legacy" => {+ "-stage0" | "-stage-0" | "-legacy" => {stage0 = true;stage1 = false;stage05 = false;i += 1;}- "-stage05" | "-stage-0.5" | "-ir" => {+ "-stage05" | "-stage-0.5" | "-ir" => {stage05 = true;stage1 = false;i += 1;}- "-stage1" | "-stage-1" | "-ssa" => {+ "-stage1" | "-stage-1" | "-ssa" => {stage1 = true;stage05 = false;stage0 = false;i += 1;}- "-follow-stub" => {+ "-follow-stub" => {follow_stub = true;i += 1;}- "-verbose" | "-v" => {+ "-verbose" | "-v" => {verbose = true;i += 1;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}@@ -2352,15 +2398,15 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {Err(e) => {if json {println!(- "{}",+ "{}",serde_json::to_string_pretty(&json!({- "ok": false,- "error": e,- }))+ "ok": false,+ "error": e,+ })).unwrap());} else {- eprintln!("error: {e}");+ eprintln!("error: {e}");}return ExitCode::FAILURE;}@@ -2369,13 +2415,13 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {if follow_stub {if let Some(stub) = classify_at(&prog, va) {let (new_va, fm) = build_follow_stub_meta(&prog, va, &stub);- if let Some(status) = fm.get("status").and_then(|s| s.as_str()) {- if verbose || (!json && status != "resolved") {+ if let Some(status) = fm.get("status").and_then(|s| s.as_str()) {+ if verbose || (!json && status != "resolved") {eprintln!(- "follow-stub: {va:#x} {status}{}",- fm.get("to")+ "follow-stub: {va:#x} {status}{}",+ fm.get("to").and_then(|t| t.as_str())- .map(|t| format!(" -> {t}"))+ .map(|t| format!(" -> {t}")).unwrap_or_default());}@@ -2387,8 +2433,8 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {}}if stage1 {- // Default to Windows x64 for PE targets, SysV otherwise.- let conv = if prog.format.to_ascii_lowercase().contains("pe") {+ // Default to Windows x64 for PE targets, SysV otherwise.+ let conv = if prog.format.to_ascii_lowercase().contains("pe") {ghidrust_types::CallConv::Windows} else {ghidrust_types::CallConv::SystemV@@ -2397,36 +2443,31 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {Ok((d, s1)) => {let sum = s1.summary();let stored_end = prog.function_at(va).map(|f| f.end);- let decoded_end = d- .blocks- .iter()- .map(|b| b.end)- .max()- .unwrap_or(va);+ let decoded_end = d.blocks.iter().map(|b| b.end).max().unwrap_or(va);let honesty = assess_decompile_bounds(&prog, va, stored_end, decoded_end);let linear = disassemble_range_opts(&prog, va, count, true).map(|r| r.insns).unwrap_or_default();let callsite_hints = collect_callsite_hints(&linear);let mut obj = json!({- "decompile": d,- "resolve": resolve_meta,- "stage1": {- "loops": sum.loops,- "phis": sum.phis,- "locals": sum.locals,- "params": sum.params,- "structs": sum.structs,- "lift_ratio": sum.lift_ratio,- "goto_rate": sum.goto_rate,- "folded_temps": s1.folded_temps,- "token_count": s1.tokens.len(),- "total_ops": s1.coverage.total_ops,- "return_type": s1.types.signature.return_type.c_style(),- "prototype": s1.types.signature.to_prototype(),- },- "callsite_hints": callsite_hints,- });+ "decompile": d,+ "resolve": resolve_meta,+ "stage1": {+ "loops": sum.loops,+ "phis": sum.phis,+ "locals": sum.locals,+ "params": sum.params,+ "structs": sum.structs,+ "lift_ratio": sum.lift_ratio,+ "goto_rate": sum.goto_rate,+ "folded_temps": s1.folded_temps,+ "token_count": s1.tokens.len(),+ "total_ops": s1.coverage.total_ops,+ "return_type": s1.types.signature.return_type.c_style(),+ "prototype": s1.types.signature.to_prototype(),+ },+ "callsite_hints": callsite_hints,+ });if let Some(m) = obj.as_object_mut() {if let Some(hf) = honesty.to_json_fields().as_object() {for (k, v) in hf {@@ -2435,10 +2476,12 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {}}if let Some(fm) = &follow_meta {- obj.as_object_mut().unwrap().insert("follow_stub".into(), fm.clone());+ obj.as_object_mut()+ .unwrap()+ .insert("follow_stub".into(), fm.clone());}return emit_result(&obj, json, out_path.as_deref(), || {- print!("{}", d.pseudo_c);+ print!("{}", d.pseudo_c);if verbose {eprintln!("[{}] stage=1 blocks={} phis={} loops={} locals={} params={} structs={} fold={} tokens={} goto={:.2} lift={:.1}%",@@ -2458,7 +2501,7 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {});}Err(e) => {- eprintln!("decompile-stage1 error: {e}");+ eprintln!("decompile-stage1 error: {e}");return ExitCode::FAILURE;}}@@ -2467,19 +2510,21 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {match ghidrust_decomp::decompile_ir_at(&prog, va, count) {Ok((d, cov)) => {let mut obj = json!({- "decompile": d,- "lift_coverage": {- "total_ops": cov.total_ops,- "unimplemented_ops": cov.unimplemented_ops,- "source_instructions": cov.source_instructions,- "ratio": cov.ratio(),- }- });+ "decompile": d,+ "lift_coverage": {+ "total_ops": cov.total_ops,+ "unimplemented_ops": cov.unimplemented_ops,+ "source_instructions": cov.source_instructions,+ "ratio": cov.ratio(),+ }+ });if let Some(fm) = &follow_meta {- obj.as_object_mut().unwrap().insert("follow_stub".into(), fm.clone());+ obj.as_object_mut()+ .unwrap()+ .insert("follow_stub".into(), fm.clone());}return emit_result(&obj, json, out_path.as_deref(), || {- print!("{}", d.pseudo_c);+ print!("{}", d.pseudo_c);if verbose {eprintln!("[{}] stage=0.5 blocks={} edges={} insns={} ir_ops={} lift={:.1}% lines={}",@@ -2495,22 +2540,24 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {});}Err(e) => {- eprintln!("decompile-ir error: {e}");+ eprintln!("decompile-ir error: {e}");ExitCode::FAILURE}}} else {match ghidrust_decomp::decompile_at(&prog, va, count) {Ok(d) => {- let mut obj = json!({ "decompile": d });+ let mut obj = json!({ "decompile": d });if let Some(fm) = &follow_meta {- obj.as_object_mut().unwrap().insert("follow_stub".into(), fm.clone());+ obj.as_object_mut()+ .unwrap()+ .insert("follow_stub".into(), fm.clone());}emit_result(&obj, json, out_path.as_deref(), || {- print!("{}", d.pseudo_c);+ print!("{}", d.pseudo_c);if verbose {eprintln!(- "[{}] stage=0 blocks={} edges={} insns={} lines={}",+ "[{}] stage=0 blocks={} edges={} insns={} lines={}",d.name,d.blocks.len(),d.edges.len(),@@ -2521,14 +2568,14 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {})}Err(e) => {- eprintln!("decompile error: {e}");+ eprintln!("decompile error: {e}");ExitCode::FAILURE}}}}Err(e) => {- eprintln!("load error: {e}");+ eprintln!("load error: {e}");ExitCode::FAILURE}}@@ -2547,32 +2594,32 @@ fn cmd_decompile_bench(args: &[String], json: bool) -> ExitCode {let mut max_functions: usize = 32;let mut count: usize = 128;let mut out_path: Option<PathBuf> = None;- // `-stage1` opts into the Stage-1 bench (SSA + structure +- // types) with per-entry pseudo-C text captured. `-parallel` runs the- // per-entry Stage-1 pipeline across a rayon thread pool. Both default- // off to keep back-compat with the shipped decompile-bench numbers.+ // `-stage1` opts into the Stage-1 bench (SSA + structure ++ // types) with per-entry pseudo-C text captured. `-parallel` runs the+ // per-entry Stage-1 pipeline across a rayon thread pool. Both default+ // off to keep back-compat with the shipped decompile-bench numbers.let mut stage1 = false;let mut parallel = false;let mut i = 1;while i < args.len() {match args[i].as_str() {- "-functions" if i + 1 < args.len() => {+ "-functions" if i + 1 < args.len() => {max_functions = args[i + 1].parse().unwrap_or(max_functions);i += 2;}- "-count" if i + 1 < args.len() => {+ "-count" if i + 1 < args.len() => {count = args[i + 1].parse().unwrap_or(count);i += 2;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-stage1" | "-stage-1" => {+ "-stage1" | "-stage-1" => {stage1 = true;i += 1;}- "-parallel" | "-rayon" => {+ "-parallel" | "-rayon" => {parallel = true;stage1 = true;i += 1;@@ -2583,12 +2630,12 @@ fn cmd_decompile_bench(args: &[String], json: bool) -> ExitCode {let mut prog = match load_path(&path) {Ok(p) => p,Err(e) => {- eprintln!("load error: {e}");+ eprintln!("load error: {e}");return ExitCode::FAILURE;}};let _ = ghidrust_core::run_analyzers(&mut prog, &[]);- let conv = if prog.format.to_ascii_lowercase().contains("pe") {+ let conv = if prog.format.to_ascii_lowercase().contains("pe") {ghidrust_types::CallConv::Windows} else {ghidrust_types::CallConv::SystemV@@ -2600,15 +2647,19 @@ fn cmd_decompile_bench(args: &[String], json: bool) -> ExitCode {} else {ghidrust_decomp::bench_program(&prog, max_functions, count)};- let output = if json { report.to_json() } else { report.to_text() };+ let output = if json {+ report.to_json()+ } else {+ report.to_text()+ };if let Some(path) = out_path {if let Err(e) = std::fs::write(&path, &output) {- eprintln!("write error: {e}");+ eprintln!("write error: {e}");return ExitCode::FAILURE;}}- print!("{}", output);- if !output.ends_with('\n') {+ print!("{}", output);+ if !output.ends_with('\n') {println!();}ExitCode::SUCCESS@@ -2634,31 +2685,31 @@ fn cmd_ghidra_headtohead(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-functions" if i + 1 < args.len() => {+ "-functions" if i + 1 < args.len() => {max_functions = args[i + 1].parse().unwrap_or(max_functions);i += 2;}- "-count" if i + 1 < args.len() => {+ "-count" if i + 1 < args.len() => {count = args[i + 1].parse().unwrap_or(count);i += 2;}- "-out" if i + 1 < args.len() => {+ "-out" if i + 1 < args.len() => {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-ghidra" if i + 1 < args.len() => {+ "-ghidra" if i + 1 < args.len() => {ghidra_dir = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-captured" if i + 1 < args.len() => {+ "-captured" if i + 1 < args.len() => {captured_path = Some(PathBuf::from(&args[i + 1]));i += 2;}- "-spawn-timeout" if i + 1 < args.len() => {+ "-spawn-timeout" if i + 1 < args.len() => {spawn_timeout_secs = args[i + 1].parse().ok();i += 2;}- "-ghidra-fn-cap" if i + 1 < args.len() => {+ "-ghidra-fn-cap" if i + 1 < args.len() => {ghidra_fn_cap = args[i + 1].parse().ok();i += 2;}@@ -2668,7 +2719,7 @@ fn cmd_ghidra_headtohead(args: &[String], json: bool) -> ExitCode {let mut prog = match load_path(&path) {Ok(p) => p,Err(e) => {- eprintln!("load error: {e}");+ eprintln!("load error: {e}");return ExitCode::FAILURE;}};@@ -2676,22 +2727,24 @@ fn cmd_ghidra_headtohead(args: &[String], json: bool) -> ExitCode {let captured = match captured_path {Some(cp) => match std::fs::read_to_string(&cp) {- Ok(text) => match serde_json::from_str::<Vec<ghidrust_decomp::CapturedGhidraDecompile>>(&text) {- Ok(v) => Some(v),- Err(e) => {- eprintln!("-captured parse error: {e}");- return ExitCode::FAILURE;+ Ok(text) => {+ match serde_json::from_str::<Vec<ghidrust_decomp::CapturedGhidraDecompile>>(&text) {+ Ok(v) => Some(v),+ Err(e) => {+ eprintln!("-captured parse error: {e}");+ return ExitCode::FAILURE;+ }}- },+ }Err(e) => {- eprintln!("read -captured: {e}");+ eprintln!("read -captured: {e}");return ExitCode::FAILURE;}},None => None,};- let cfg = ghidrust_decomp::GhidraOracleConfig {+ let cfg = ghidrust_decomp::GhidraOracleConfig {ghidra_install_dir: ghidra_dir,max_functions,max_insns_per_fn: count,@@ -2702,15 +2755,19 @@ fn cmd_ghidra_headtohead(args: &[String], json: bool) -> ExitCode {..Default::default()};let report = ghidrust_decomp::ghidra_headtohead(&prog, &cfg);- let output = if json { report.to_json() } else { report.to_text() };+ let output = if json {+ report.to_json()+ } else {+ report.to_text()+ };if let Some(p) = out_path {if let Err(e) = std::fs::write(&p, &output) {- eprintln!("write error: {e}");+ eprintln!("write error: {e}");return ExitCode::FAILURE;}}- print!("{}", output);- if !output.ends_with('\n') {+ print!("{}", output);+ if !output.ends_with('\n') {println!();}ExitCode::SUCCESS@@ -2721,14 +2778,14 @@ fn cmd_re_bench(args: &[String], json: bool) -> ExitCode {let path = match args.first() {Some(p) => PathBuf::from(p),None => {- eprintln!("usage: ghidrust re-bench <path> [-out FILE] [-json]");+ eprintln!("usage: ghidrust re-bench <path> [-out FILE] [-json]");return ExitCode::from(2);}};let mut out_path: Option<PathBuf> = None;let mut i = 1;while i < args.len() {- if args[i] == "-out" && i + 1 < args.len() {+ if args[i] == "-out" && i + 1 < args.len() {out_path = Some(PathBuf::from(&args[i + 1]));i += 2;} else {@@ -2739,7 +2796,7 @@ fn cmd_re_bench(args: &[String], json: bool) -> ExitCode {let metrics = match run_re_bench(&path) {Ok(m) => m,Err(e) => {- eprintln!("re-bench error: {e}");+ eprintln!("re-bench error: {e}");return ExitCode::FAILURE;}};@@ -2747,15 +2804,15 @@ fn cmd_re_bench(args: &[String], json: bool) -> ExitCode {let text = format_metrics_log(&metrics);if let Some(ref p) = out_path {if let Err(e) = std::fs::write(p, &text) {- eprintln!("write metrics: {e}");+ eprintln!("write metrics: {e}");return ExitCode::FAILURE;}- eprintln!("wrote metrics → {}", p.display());+ eprintln!("wrote metrics → {}", p.display());}if json {- println!("{}", serde_json::to_string_pretty(&metrics).unwrap());+ println!("{}", serde_json::to_string_pretty(&metrics).unwrap());} else {- print!("{text}");+ print!("{text}");}ExitCode::SUCCESS}@@ -2780,7 +2837,7 @@ struct DecompileMetrics {insns: usize,lines: usize,chars: usize,- /// First line of pseudo-C for identity check (not empty placeholder).+ /// First line of pseudo-C for identity check (not empty placeholder).pseudo_c_head: String,}@@ -2797,16 +2854,21 @@ fn run_re_bench(path: &Path) -> Result<ReBenchMetrics, String> {let prog = load_path(path).map_err(|e| e.to_string())?;let entry = prog.entry.unwrap_or(prog.image_base);- // -- CPU decompile (structure recovery always on CPU) --+ // -- CPU decompile (structure recovery always on CPU) --let t0 = Instant::now();let decomp = decompile_entry(&prog, 64).map_err(|e| e.to_string())?;let decomp_ms = t0.elapsed().as_secs_f64() * 1000.0;- let head: String = decomp.pseudo_c.lines().take(4).collect::<Vec<_>>().join("\n");+ let head: String = decomp+ .pseudo_c+ .lines()+ .take(4)+ .collect::<Vec<_>>()+ .join("\n");if decomp.pseudo_c.trim().is_empty() || decomp.blocks.is_empty() {- return Err("decompile produced empty structure".into());+ return Err("decompile produced empty structure".into());}- // -- Bulk haystack (pad for meaningful bulk timing) --+ // -- Bulk haystack (pad for meaningful bulk timing) --let mut hay = Vec::new();for b in &prog.blocks {hay.extend_from_slice(&b.bytes);@@ -2825,26 +2887,26 @@ fn run_re_bench(path: &Path) -> Result<ReBenchMetrics, String> {}}- // CPU bulk (parallel)+ // CPU bulk (parallel)let t1 = Instant::now();let (cpu_hits, cpu_backend) = scan_printable_runs_parallel(&hay, 4);let cpu_ms = t1.elapsed().as_secs_f64() * 1000.0;let seq = scan_printable_runs_seq(&hay, 4);if seq != cpu_hits {return Err(format!(- "CPU parallel bulk != sequential ({} vs {})",+ "CPU parallel bulk != sequential ({} vs {})",cpu_hits.len(),seq.len()));}- // GPU or fallback bulk+ // GPU or fallback bulklet t2 = Instant::now();let gpu_rep = scan_printable_runs_gpu_or_fallback(&hay, 4);let gpu_ms = t2.elapsed().as_secs_f64() * 1000.0;if gpu_rep.hits != seq {return Err(format!(- "GPU/fallback bulk != sequential ({} vs {})",+ "GPU/fallback bulk != sequential ({} vs {})",gpu_rep.hits.len(),seq.len()));@@ -2889,53 +2951,50 @@ fn run_re_bench(path: &Path) -> Result<ReBenchMetrics, String> {fn format_metrics_log(m: &ReBenchMetrics) -> String {let mut s = String::new();- s.push_str("=== Ghidrust RE bench: CPU then GPU/fallback ===\n");- s.push_str(&format!("file: {}\n", m.file));- s.push_str(&format!("note: {}\n\n", m.note));- s.push_str("-- DECOMPILE (CPU) --\n");+ s.push_str("=== Ghidrust RE bench: CPU then GPU/fallback ===\n");+ s.push_str(&format!("file: {}\n", m.file));+ s.push_str(&format!("note: {}\n\n", m.note));+ s.push_str("-- DECOMPILE (CPU) --\n");s.push_str(&format!(- "backend={} ms={:.3} entry={:#x} name={}\n",- m.decompile_cpu.backend,- m.decompile_cpu.ms,- m.decompile_cpu.entry,- m.decompile_cpu.name+ "backend={} ms={:.3} entry={:#x} name={}\n",+ m.decompile_cpu.backend, m.decompile_cpu.ms, m.decompile_cpu.entry, m.decompile_cpu.name));s.push_str(&format!(- "blocks={} edges={} insns={} lines={} chars={}\n",+ "blocks={} edges={} insns={} lines={} chars={}\n",m.decompile_cpu.blocks,m.decompile_cpu.edges,m.decompile_cpu.insns,m.decompile_cpu.lines,m.decompile_cpu.chars));- s.push_str("pseudo_c_head:\n");+ s.push_str("pseudo_c_head:\n");s.push_str(&m.decompile_cpu.pseudo_c_head);- s.push_str("\n\n");- s.push_str("-- BULK RE (CPU parallel) --\n");+ s.push_str("\n\n");+ s.push_str("-- BULK RE (CPU parallel) --\n");s.push_str(&format!(- "mode={} backend={} ms={:.3} hits={} haystack_bytes={}\n\n",+ "mode={} backend={} ms={:.3} hits={} haystack_bytes={}\n\n",m.bulk_cpu.mode,m.bulk_cpu.backend,m.bulk_cpu.ms,m.bulk_cpu.hits,m.bulk_cpu.haystack_bytes));- s.push_str("-- BULK RE (GPU or fallback) --\n");+ s.push_str("-- BULK RE (GPU or fallback) --\n");s.push_str(&format!(- "mode={} backend={} ms={:.3} hits={} haystack_bytes={}\n\n",+ "mode={} backend={} ms={:.3} hits={} haystack_bytes={}\n\n",m.bulk_gpu.mode,m.bulk_gpu.backend,m.bulk_gpu.ms,m.bulk_gpu.hits,m.bulk_gpu.haystack_bytes));- s.push_str("-- COMPARISON --\n");+ s.push_str("-- COMPARISON --\n");s.push_str(&format!(- "bulk_hit_equal={}\n",+ "bulk_hit_equal={}\n",m.bulk_cpu.hits == m.bulk_gpu.hits));s.push_str(&format!(- "bulk_cpu_ms={:.3} bulk_gpu_ms={:.3} ratio_gpu_over_cpu={:.3}\n",+ "bulk_cpu_ms={:.3} bulk_gpu_ms={:.3} ratio_gpu_over_cpu={:.3}\n",m.bulk_cpu.ms,m.bulk_gpu.ms,if m.bulk_cpu.ms > 0.0 {@@ -2945,7 +3004,7 @@ fn format_metrics_log(m: &ReBenchMetrics) -> String {}));s.push_str(&format!(- "decompile_cpu_ms={:.3} (structure recovery not offloaded to GPU)\n",+ "decompile_cpu_ms={:.3} (structure recovery not offloaded to GPU)\n",m.decompile_cpu.ms));s@@ -2954,11 +3013,11 @@ fn format_metrics_log(m: &ReBenchMetrics) -> String {fn cmd_analyzers(json: bool) -> ExitCode {let cat = analyzer_catalog();if json {- println!("{}", serde_json::to_string_pretty(&cat).unwrap());+ println!("{}", serde_json::to_string_pretty(&cat).unwrap());} else {for a in &cat {println!(- "[{:?}] {} (default_enabled={})",+ "[{:?}] {} (default_enabled={})",a.status, a.name, a.default_enabled);}@@ -2970,7 +3029,7 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {let path = match path_arg(args) {Ok(p) => p,Err(e) => {- eprintln!("{e}");+ eprintln!("{e}");return ExitCode::from(2);}};@@ -2979,8 +3038,8 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {let mut i = 1;while i < args.len() {match args[i].as_str() {- "-analyzers" if i + 1 < args.len() => {- for s in args[i + 1].split(',') {+ "-analyzers" if i + 1 < args.len() => {+ for s in args[i + 1].split(',') {let t = s.trim();if !t.is_empty() {names.push(t.to_string());@@ -2988,11 +3047,11 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {}i += 2;}- "-analyzer" if i + 1 < args.len() => {+ "-analyzer" if i + 1 < args.len() => {names.push(args[i + 1].clone());i += 2;}- "-gpu" => {+ "-gpu" => {use_gpu = true;i += 1;}@@ -3000,7 +3059,7 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {}}- // Selective analyzers and/or -gpu (empty names → defaults via run_analyzers_opts)+ // Selective analyzers and/or -gpu (empty names → defaults via run_analyzers_opts)if !names.is_empty() || use_gpu {let name_refs: Vec<&str> = names.iter().map(|s| s.as_str()).collect();return match load_path(&path)@@ -3008,21 +3067,21 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {{Ok(report) => {if json {- println!("{}", serde_json::to_string_pretty(&report).unwrap());+ println!("{}", serde_json::to_string_pretty(&report).unwrap());} else {if use_gpu {- println!("gpu=true (bulk strings + per-analyzer GPU seed enrich)");+ println!("gpu=true (bulk strings + per-analyzer GPU seed enrich)");}for r in &report.results {- println!("[{}] {} — {}", r.status, r.name, r.message);+ println!("[{}] {} — {}", r.status, r.name, r.message);if let Some(ref rtti) = r.rtti {for c in &rtti.classes {- println!(" class {}", c.name);+ println!(" class {}", c.name);}}if let Some(ref strings) = r.strings {for s in strings.iter().take(20) {- println!(" str {:#x}: {}", s.va, s.value);+ println!(" str {:#x}: {}", s.va, s.value);}}}@@ -3030,7 +3089,7 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}};@@ -3040,28 +3099,28 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {Ok(bundle) => {if json {println!(- "{}",+ "{}",serde_json::to_string_pretty(&bundle_json(&bundle)).unwrap());} else {print_program_summary(&bundle.program);- println!("-- disassembly --");+ println!("-- disassembly --");for insn in &bundle.listing {- println!("{}", insn.text());+ println!("{}", insn.text());}- println!("-- analysis --");+ println!("-- analysis --");for r in &bundle.analysis.results {- println!("[{}] {} — {}", r.status, r.name, r.message);+ println!("[{}] {} — {}", r.status, r.name, r.message);}- println!("-- rtti --");+ println!("-- rtti --");for c in &bundle.rtti.classes {- println!("class {}", c.name);+ println!("class {}", c.name);}}ExitCode::SUCCESS}Err(e) => {- eprintln!("error: {e}");+ eprintln!("error: {e}");ExitCode::FAILURE}}@@ -3069,20 +3128,20 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {fn bundle_json(b: &AnalysisBundle) -> Value {json!({- "format": b.program.format,- "entry": b.program.entry.map(|e| format!("{e:#x}")),- "sections": b.program.sections.iter().map(|s| json!({- "name": s.name,- "va": format!("{:#x}", s.va),- })).collect::<Vec<_>>(),- "listing": b.listing,- "rtti": b.rtti,- "analysis": b.analysis,- })+ "format": b.program.format,+ "entry": b.program.entry.map(|e| format!("{e:#x}")),+ "sections": b.program.sections.iter().map(|s| json!({+ "name": s.name,+ "va": format!("{:#x}", s.va),+ })).collect::<Vec<_>>(),+ "listing": b.listing,+ "rtti": b.rtti,+ "analysis": b.analysis,+ })}fn fmt_opt_va(v: Option<u64>) -> String {- v.map(|x| format!("{x:#x}")).unwrap_or_else(|| "-".into())+ v.map(|x| format!("{x:#x}")).unwrap_or_else(|| "-".into())}fn xref_row_json(r: &ghidrust_core::XRef, prog: &Program, classify: bool) -> Value {@@ -3092,26 +3151,26 @@ fn xref_row_json(r: &ghidrust_core::XRef, prog: &Program, classify: bool) -> ValNone};let kind = if stub.is_some() {- "resolve_stub"+ "resolve_stub"} else {r.kind};let mut preview = r.preview.clone();if let Some(s) = stub {if let Some(name) = s.icall_name {- preview = format!("{preview} ; il2cpp resolve {name}");+ preview = format!("{preview} ; il2cpp resolve {name}");}}json!({- "from": format!("{:#x}", r.from),- "to": format!("{:#x}", r.to),- "kind": kind,- "preview": preview,- "encoding": r.encoding,- "from_entry": r.from_entry.map(|v| format!("{v:#x}")),- "from_function": r.from_function,- "to_entry": r.to_entry.map(|v| format!("{v:#x}")),- })+ "from": format!("{:#x}", r.from),+ "to": format!("{:#x}", r.to),+ "kind": kind,+ "preview": preview,+ "encoding": r.encoding,+ "from_entry": r.from_entry.map(|v| format!("{v:#x}")),+ "from_function": r.from_function,+ "to_entry": r.to_entry.map(|v| format!("{v:#x}")),+ })}fn refs_json(refs: &[ghidrust_core::XRef]) -> Value {@@ -3119,22 +3178,22 @@ fn refs_json(refs: &[ghidrust_core::XRef]) -> Value {refs.iter().map(|r| {json!({- "from": format!("{:#x}", r.from),- "to": format!("{:#x}", r.to),- "kind": r.kind,- "preview": r.preview,- "encoding": r.encoding,- "from_entry": r.from_entry.map(|v| format!("{v:#x}")),- "from_function": r.from_function,- "to_entry": r.to_entry.map(|v| format!("{v:#x}")),- })+ "from": format!("{:#x}", r.from),+ "to": format!("{:#x}", r.to),+ "kind": r.kind,+ "preview": r.preview,+ "encoding": r.encoding,+ "from_entry": r.from_entry.map(|v| format!("{v:#x}")),+ "from_function": r.from_function,+ "to_entry": r.to_entry.map(|v| format!("{v:#x}")),+ })}).collect(),)}fn parse_u64(s: &str) -> Result<u64, String> {- let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");+ let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");u64::from_str_radix(t, 16).or_else(|_| s.parse::<u64>()).map_err(|e| e.to_string())@@ -3142,11 +3201,11 @@ fn parse_u64(s: &str) -> Result<u64, String> {#[derive(Serialize)]struct ToolDef {- name: &'static str,- description: &'static str,- /// MCP protocol field name is camelCase; serde default would emit `input_schema`- /// and Grok's client then fails tools/list with "Unexpected response type".- #[serde(rename = "inputSchema")]+ name: &'static str,+ description: &'static str,+ /// MCP protocol field name is camelCase; serde default would emit `input_schema`+ /// and Grok's client then fails tools/list with "Unexpected response type".+ #[serde(rename = "inputSchema")]input_schema: Value,}@@ -3463,6 +3522,92 @@ fn tool_defs() -> Vec<ToolDef> {}),},ToolDef {+ name: "crypt_constants",+ description: "Scan for cryptographic constant tables (S-boxes, TEA delta, hash K, stream sigma). Optional algo filter.",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "algo": { "type": "string" },+ "limit": { "type": "integer" }+ },+ "required": ["path"]+ }),+ },+ ToolDef {+ name: "list_crypt_constants",+ description: "Alias of crypt_constants",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "algo": { "type": "string" },+ "limit": { "type": "integer" }+ },+ "required": ["path"]+ }),+ },+ ToolDef {+ name: "recover_strings",+ description: "Recover stack/tight/decoded obfuscated strings. only/no: static|stack|tight|decoded.",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "only": { "type": "array", "items": { "type": "string" } },+ "no": { "type": "array", "items": { "type": "string" } },+ "functions": { "type": "array", "items": { "type": "string" }, "description": "hex VAs" },+ "limit": { "type": "integer" }+ },+ "required": ["path"]+ }),+ },+ ToolDef {+ name: "decode_bake",+description: "Apply a byte-transform recipe (FromBase64, FromHex, XOR, XORBrute, RC4, ChaCha20Decrypt, AESDecrypt modes cbc/ecb/ctr/gcm/cfb/ofb, DESDecrypt, TripleDESDecrypt, BlowfishDecrypt, Gunzip, Inflate, ROT13, Reverse, DecodeUTF16LE).",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string", "description": "Required when reading via addr" },+ "addr": { "type": "string" },+ "count": { "type": "integer" },+ "input_hex": { "type": "string" },+ "input_b64": { "type": "string" },+ "recipe": { "type": "array", "description": "[{op, args}]" },+"ops": { "type": "array" },+"annotate_va": { "type": "string", "description": "EOL-comment VA; requires path and is in-memory only for a plain path load" }+ }+ }),+ },+ ToolDef {+ name: "decode_magic",+description: "Auto-detect a short peel chain (depth 1..4) maximizing printable ratio; crib filters the selected output.",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "addr": { "type": "string" },+ "count": { "type": "integer" },+ "input_hex": { "type": "string" },+ "input_b64": { "type": "string" },+"depth": { "type": "integer" },+"crib": { "type": "string" }+ }+ }),+ },+ ToolDef {+ name: "list_crypto_capabilities",+ description: "Match encrypt/decrypt/encoding capabilities (imports, AES-NI, constant seeds).",+ input_schema: json!({+ "type": "object",+ "properties": {+ "path": { "type": "string" },+ "tag": { "type": "string", "enum": ["decrypt", "encrypt", "encoding", "hashing"] }+ },+ "required": ["path"]+ }),+ },+ ToolDef {name: "il2cpp_meta",description: "Parse IL2CPP global-metadata.dat → types/methods (v27/29/31). Fails closed if encrypted/obfuscated.",input_schema: json!({@@ -3670,11 +3815,11 @@ fn tool_defs() -> Vec<ToolDef> {}fn mcp_write(stdout: &mut impl Write, resp: &Value) -> bool {- // MCP stdio: one compact JSON object per line (no embedded newlines).+ // MCP stdio: one compact JSON object per line (no embedded newlines).let Ok(line) = serde_json::to_string(resp) else {return false;};- if writeln!(stdout, "{line}").is_err() {+ if writeln!(stdout, "{line}").is_err() {return false;}stdout.flush().ok();@@ -3688,7 +3833,7 @@ fn run_mcp_stdio() -> ExitCode {let line = match line {Ok(l) => l,Err(e) => {- eprintln!("mcp read error: {e}");+ eprintln!("mcp read error: {e}");return ExitCode::FAILURE;}};@@ -3698,86 +3843,90 @@ fn run_mcp_stdio() -> ExitCode {let req: Value = match serde_json::from_str(&line) {Ok(v) => v,Err(e) => {- let err = json!({"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":e.to_string()}});+ let err = json!({"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":e.to_string()}});if !mcp_write(&mut stdout, &err) {return ExitCode::FAILURE;}continue;}};- let id = req.get("id").cloned().unwrap_or(Value::Null);- let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("");- let params = req.get("params").cloned().unwrap_or(json!({}));+ let id = req.get("id").cloned().unwrap_or(Value::Null);+ let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("");+ let params = req.get("params").cloned().unwrap_or(json!({}));let resp = match method {- "initialize" => {- // Echo a client-requested protocol version when present; Cursor- // currently sends 2025-11-25. Fall back to a stable baseline.+ "initialize" => {+ // Echo a client-requested protocol version when present; Cursor+ // currently sends 2025-11-25. Fall back to a stable baseline.let client_proto = params- .get("protocolVersion")+ .get("protocolVersion").and_then(|v| v.as_str())- .unwrap_or("2024-11-05");+ .unwrap_or("2024-11-05");let proto = match client_proto {- "2025-11-25" | "2025-06-18" | "2025-03-26" | "2024-11-05" => client_proto,- _ => "2024-11-05",+ "2025-11-25" | "2025-06-18" | "2025-03-26" | "2024-11-05" => client_proto,+ _ => "2024-11-05",};json!({- "jsonrpc": "2.0",- "id": id,- "result": {- "protocolVersion": proto,- "capabilities": { "tools": { "listChanged": false } },- "serverInfo": {- "name": "ghidrust",- "version": package_version(),- "toolSurface": TOOL_SURFACE_VERSION- }- }- })- }- "tools/list" | "list_tools" => {- // Serialize tools explicitly so the line stays compact and- // schema field names match MCP (inputSchema).+ "jsonrpc": "2.0",+ "id": id,+ "result": {+ "protocolVersion": proto,+ "capabilities": { "tools": { "listChanged": false } },+ "serverInfo": {+ "name": "ghidrust",+ "version": package_version(),+ "toolSurface": TOOL_SURFACE_VERSION+ }+ }+ })+ }+ "tools/list" | "list_tools" => {+ // Serialize tools explicitly so the line stays compact and+ // schema field names match MCP (inputSchema).let tools: Vec<Value> = tool_defs().into_iter().filter_map(|t| serde_json::to_value(t).ok()).collect();- eprintln!("mcp tools/list → {} tools (tool_surface={})", tools.len(), TOOL_SURFACE_VERSION);+ eprintln!(+ "mcp tools/list → {} tools (tool_surface={})",+ tools.len(),+ TOOL_SURFACE_VERSION+ );json!({- "jsonrpc": "2.0",- "id": id,- "result": { "tools": tools }- })+ "jsonrpc": "2.0",+ "id": id,+ "result": { "tools": tools }+ })}- "tools/call" | "call_tool" => match call_tool(¶ms) {+ "tools/call" | "call_tool" => match call_tool(¶ms) {Ok(content) => json!({- "jsonrpc": "2.0",- "id": id,- "result": {- "content": [{ "type": "text", "text": content }],- "isError": false- }- }),+ "jsonrpc": "2.0",+ "id": id,+ "result": {+ "content": [{ "type": "text", "text": content }],+ "isError": false+ }+ }),Err(e) => json!({- "jsonrpc": "2.0",- "id": id,- "result": {- "content": [{ "type": "text", "text": e }],- "isError": true- }- }),+ "jsonrpc": "2.0",+ "id": id,+ "result": {+ "content": [{ "type": "text", "text": e }],+ "isError": true+ }+ }),},- "notifications/initialized" | "initialized" => {+ "notifications/initialized" | "initialized" => {if id.is_null() {continue;}- json!({"jsonrpc":"2.0","id":id,"result":{}})+ json!({"jsonrpc":"2.0","id":id,"result":{}})}_ => json!({- "jsonrpc": "2.0",- "id": id,- "error": { "code": -32601, "message": format!("method not found: {method}") }- }),+ "jsonrpc": "2.0",+ "id": id,+ "error": { "code": -32601, "message": format!("method not found: {method}") }+ }),};if !mcp_write(&mut stdout, &resp) {return ExitCode::FAILURE;@@ -3786,52 +3935,92 @@ fn run_mcp_stdio() -> ExitCode {ExitCode::SUCCESS}+fn mcp_decode_input_bytes(args: &Value) -> Result<Vec<u8>, String> {+ if let Some(h) = args.get("input_hex").and_then(|v| v.as_str()) {+ let clean: String = h.chars().filter(|c| !c.is_whitespace()).collect();+ let mut out = Vec::new();+ for i in (0..clean.len()).step_by(2) {+ out.push(u8::from_str_radix(&clean[i..i + 2], 16).map_err(|e| e.to_string())?);+ }+ return Ok(out);+ }+ if let Some(b) = args.get("input_b64").and_then(|v| v.as_str()) {+ let r = ghidrust_core::bake(+ b.as_bytes(),+ &[ghidrust_core::BakeOp {+ op: "FromBase64".into(),+ args: json!({}),+ }],+ );+ if !r.ok {+ return Err(r.message);+ }+ return Ok((0..r.output_hex.len())+ .step_by(2)+ .map(|i| u8::from_str_radix(&r.output_hex[i..i + 2], 16).unwrap())+ .collect());+ }+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "provide input_hex, input_b64, or path+addr".to_string())?;+ let addr = args+ .get("addr")+ .and_then(|a| a.as_str())+ .ok_or_else(|| "missing arguments.addr when using path".to_string())?;+ let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(256) as usize;+ let prog = load_path_opts(path, true).map_err(|e| e.to_string())?;+ let va = parse_u64(addr)?;+ prog.read_va(va, count)+ .ok_or_else(|| format!("cannot read {count} bytes at {va:#x}"))+}+fn call_tool(params: &Value) -> Result<String, String> {let name = params- .get("name")+ .get("name").and_then(|n| n.as_str())- .ok_or_else(|| "missing tool name".to_string())?;- let args = params.get("arguments").cloned().unwrap_or(json!({}));+ .ok_or_else(|| "missing tool name".to_string())?;+ let args = params.get("arguments").cloned().unwrap_or(json!({}));match name {- "server_info" => Ok(serde_json::to_string_pretty(&server_info_json()).unwrap()),- "artifact_get" => {+ "server_info" => Ok(serde_json::to_string_pretty(&server_info_json()).unwrap()),+ "artifact_get" => {let id = args- .get("id")+ .get("id").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.id".to_string())?;+ .ok_or_else(|| "missing arguments.id".to_string())?;let v = artifact_get(id).map_err(|e| e.to_string())?;Ok(serde_json::to_string_pretty(&v).unwrap())}- "artifact_query" => {+ "artifact_query" => {let id = args- .get("id")+ .get("id").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.id".to_string())?;- let offset = args.get("offset").and_then(|o| o.as_u64()).unwrap_or(0) as usize;+ .ok_or_else(|| "missing arguments.id".to_string())?;+ let offset = args.get("offset").and_then(|o| o.as_u64()).unwrap_or(0) as usize;let limit = args- .get("limit")+ .get("limit").and_then(|o| o.as_u64()).unwrap_or(DEFAULT_PREVIEW_LIMIT as u64) as usize;let env = artifact_query(id, offset, limit).map_err(|e| e.to_string())?;Ok(serde_json::to_string_pretty(&env).unwrap())}- "artifact_list" => {- let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(64) as usize;+ "artifact_list" => {+ let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(64) as usize;let m = list_artifacts(max).map_err(|e| e.to_string())?;Ok(serde_json::to_string_pretty(&m).unwrap())}- "inventory" => {+ "inventory" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;- let max_depth = args.get("max_depth").and_then(|m| m.as_u64()).unwrap_or(8) as usize;- let with_hash = args.get("hash").and_then(|h| h.as_bool()).unwrap_or(false);+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let max_depth = args.get("max_depth").and_then(|m| m.as_u64()).unwrap_or(8) as usize;+ let with_hash = args.get("hash").and_then(|h| h.as_bool()).unwrap_or(false);let inv = inventory_pe_dir(path, max_depth, with_hash).map_err(|e| e.to_string())?;let entries = serde_json::to_value(&inv.entries).unwrap();let env = ghidrust_core::envelope_or_spill(- "inventory",+ "inventory",entries,64,DEFAULT_PREVIEW_LIMIT,@@ -3839,43 +4028,43 @@ fn call_tool(params: &Value) -> Result<String, String> {).map_err(|e| e.to_string())?;Ok(serde_json::to_string_pretty(&json!({- "schema_version": inv.schema_version,- "root": inv.root,- "notes": inv.notes,- "entry_count": inv.entries.len(),- "envelope": env,- "entries": if inv.entries.len() <= 64 {- serde_json::to_value(&inv.entries).unwrap()- } else {- Value::Null- },- }))+ "schema_version": inv.schema_version,+ "root": inv.root,+ "notes": inv.notes,+ "entry_count": inv.entries.len(),+ "envelope": env,+ "entries": if inv.entries.len() <= 64 {+ serde_json::to_value(&inv.entries).unwrap()+ } else {+ Value::Null+ },+ })).unwrap())}- "list_tree" => {+ "list_tree" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;+ .ok_or_else(|| "missing arguments.path".to_string())?;let mut opts = TreeListOpts::default();- if let Some(d) = args.get("max_depth").and_then(|m| m.as_u64()) {+ if let Some(d) = args.get("max_depth").and_then(|m| m.as_u64()) {opts.max_depth = d as usize;}- if let Some(ext) = args.get("extensions").and_then(|e| e.as_str()) {+ if let Some(ext) = args.get("extensions").and_then(|e| e.as_str()) {opts.extensions = Some(- ext.split(',')+ ext.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(),);}- if let Some(g) = args.get("name_glob").and_then(|e| e.as_str()) {+ if let Some(g) = args.get("name_glob").and_then(|e| e.as_str()) {opts.name_glob = Some(g.to_string());}let res = list_tree(path, opts);let entries = serde_json::to_value(&res.entries).unwrap();let env = ghidrust_core::envelope_or_spill(- "tree",+ "tree",entries,128,DEFAULT_PREVIEW_LIMIT,@@ -3883,22 +4072,22 @@ fn call_tool(params: &Value) -> Result<String, String> {).map_err(|e| e.to_string())?;Ok(serde_json::to_string_pretty(&json!({- "root": res.root,- "truncated": res.truncated,- "entry_count": res.entries.len(),- "envelope": env,- }))+ "root": res.root,+ "truncated": res.truncated,+ "entry_count": res.entries.len(),+ "envelope": env,+ })).unwrap())}- "rtti_query" => {+ "rtti_query" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;- let filter = args.get("filter").and_then(|f| f.as_str());- let exact = args.get("exact").and_then(|e| e.as_bool()).unwrap_or(false);+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let filter = args.get("filter").and_then(|f| f.as_str());+ let exact = args.get("exact").and_then(|e| e.as_bool()).unwrap_or(false);let mode = args- .get("match")+ .get("match").and_then(|m| m.as_str()).map(RttiMatchMode::parse).unwrap_or(RttiMatchMode::Substr);@@ -3907,48 +4096,53 @@ fn call_tool(params: &Value) -> Result<String, String> {let entries = serde_json::to_value(&q.classes).unwrap();let env = if q.entry_count > 64 {Some(- ghidrust_core::spill_artifact("rtti", entries, DEFAULT_PREVIEW_LIMIT, Some(path))- .map_err(|e| e.to_string())?,+ ghidrust_core::spill_artifact(+ "rtti",+ entries,+ DEFAULT_PREVIEW_LIMIT,+ Some(path),+ )+ .map_err(|e| e.to_string())?,)} else {None};Ok(serde_json::to_string_pretty(&json!({- "entry_count": q.entry_count,- "cache_hit": q.cache_hit,- "notes": q.notes,- "envelope": env,- "classes": if q.entry_count <= 64 {- serde_json::to_value(&q.classes).unwrap()- } else {- Value::Null- },- }))+ "entry_count": q.entry_count,+ "cache_hit": q.cache_hit,+ "notes": q.notes,+ "envelope": env,+ "classes": if q.entry_count <= 64 {+ serde_json::to_value(&q.classes).unwrap()+ } else {+ Value::Null+ },+ })).unwrap())}- "process_list" => {+ "process_list" => {let list = process_list()?;Ok(serde_json::to_string_pretty(&list).unwrap())}- "process_attach" => {+ "process_attach" => {let pid = args- .get("pid")+ .get("pid").and_then(|p| p.as_u64())- .ok_or_else(|| "missing arguments.pid".to_string())? as u32;+ .ok_or_else(|| "missing arguments.pid".to_string())? as u32;let s = process_attach(pid)?;Ok(serde_json::to_string_pretty(&s).unwrap())}- "process_launch" => {+ "process_launch" => {let image = args- .get("image")+ .get("image").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.image".to_string())?;+ .ok_or_else(|| "missing arguments.image".to_string())?;let launch_args = args- .get("args")+ .get("args").and_then(|a| a.as_str()).map(|s| s.to_string());let cwd = args- .get("cwd")+ .get("cwd").and_then(|c| c.as_str()).map(std::path::PathBuf::from);let r = process_launch(&LaunchRequest {@@ -3958,85 +4152,91 @@ fn call_tool(params: &Value) -> Result<String, String> {})?;Ok(serde_json::to_string_pretty(&r).unwrap())}- "process_resume" => {+ "process_resume" => {let sid = args- .get("session_id")+ .get("session_id").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.session_id".to_string())?;+ .ok_or_else(|| "missing arguments.session_id".to_string())?;process_resume(sid)?;- Ok(serde_json::to_string_pretty(&json!({"ok": true, "resumed": true})).unwrap())+ Ok(serde_json::to_string_pretty(&json!({"ok": true, "resumed": true})).unwrap())}- "process_detach" => {+ "process_detach" => {let sid = args- .get("session_id")+ .get("session_id").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.session_id".to_string())?;+ .ok_or_else(|| "missing arguments.session_id".to_string())?;process_detach(sid)?;- Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())+ Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())}- "process_modules" => {+ "process_modules" => {let sid = args- .get("session_id")+ .get("session_id").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.session_id".to_string())?;+ .ok_or_else(|| "missing arguments.session_id".to_string())?;let m = process_modules(sid)?;Ok(serde_json::to_string_pretty(&m).unwrap())}- "process_read" => {+ "process_read" => {let sid = args- .get("session_id")+ .get("session_id").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.session_id".to_string())?;+ .ok_or_else(|| "missing arguments.session_id".to_string())?;let addr = args- .get("addr")+ .get("addr").and_then(|a| a.as_str())- .ok_or_else(|| "missing arguments.addr".to_string())?;- let size = args.get("size").and_then(|s| s.as_u64()).unwrap_or(64) as usize;+ .ok_or_else(|| "missing arguments.addr".to_string())?;+ let size = args.get("size").and_then(|s| s.as_u64()).unwrap_or(64) as usize;let va = parse_u64(addr)?;let r = process_read(sid, va, size)?;Ok(serde_json::to_string_pretty(&r).unwrap())}- "process_resolve" => {+ "process_resolve" => {let sid = args- .get("session_id")+ .get("session_id").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.session_id".to_string())?;+ .ok_or_else(|| "missing arguments.session_id".to_string())?;let module = args- .get("module")+ .get("module").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.module".to_string())?;+ .ok_or_else(|| "missing arguments.module".to_string())?;let rva = args- .get("rva")+ .get("rva").and_then(|a| a.as_str())- .ok_or_else(|| "missing arguments.rva".to_string())?;+ .ok_or_else(|| "missing arguments.rva".to_string())?;let rva = parse_u64(rva)?;let r = process_resolve(sid, module, rva)?;Ok(serde_json::to_string_pretty(&r).unwrap())}- "process_regions" => {+ "process_regions" => {let sid = args- .get("session_id")+ .get("session_id").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.session_id".to_string())?;- let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(256) as usize;+ .ok_or_else(|| "missing arguments.session_id".to_string())?;+ let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(256) as usize;let r = process_regions(sid, max)?;Ok(serde_json::to_string_pretty(&r).unwrap())}- "list_strings" | "search_strings" => {+ "list_strings" | "search_strings" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;+ .ok_or_else(|| "missing arguments.path".to_string())?;let encoding = args- .get("encoding")+ .get("encoding").and_then(|e| e.as_str())- .unwrap_or("all");- let filter = args.get("filter").and_then(|f| f.as_str()).map(|s| s.to_string());- let min_len = args.get("min").and_then(|m| m.as_u64()).unwrap_or(4) as usize;- let limit = args.get("limit").and_then(|m| m.as_u64()).map(|n| n as usize);- let raw = args.get("raw").and_then(|r| r.as_bool()).unwrap_or(false);+ .unwrap_or("all");+ let filter = args+ .get("filter")+ .and_then(|f| f.as_str())+ .map(|s| s.to_string());+ let min_len = args.get("min").and_then(|m| m.as_u64()).unwrap_or(4) as usize;+ let limit = args+ .get("limit")+ .and_then(|m| m.as_u64())+ .map(|n| n as usize);+ let raw = args.get("raw").and_then(|r| r.as_bool()).unwrap_or(false);let mut match_mode = args- .get("match")+ .get("match").and_then(|m| m.as_str()).map(StringMatchMode::parse).transpose()@@ -4044,7 +4244,7 @@ fn call_tool(params: &Value) -> Result<String, String> {.unwrap_or(StringMatchMode::Substr);if matches!(match_mode, StringMatchMode::Substr) {if let Some(pat) = &filter {- if pat.contains('*') || pat.contains('?') {+ if pat.contains('*') || pat.contains('?') {match_mode = StringMatchMode::Glob;}}@@ -4060,28 +4260,186 @@ fn call_tool(params: &Value) -> Result<String, String> {let bytes = std::fs::read(path).map_err(|e| e.to_string())?;collect_strings_bytes(&bytes, 0, &opts).map_err(|e| e.to_string())?} else {- let prog = load_path_opts(path, true).map_err(|e| e.to_string())?;+ let prog = load_path(path).map_err(|e| e.to_string())?;collect_strings_opts(&prog, &opts).map_err(|e| e.to_string())?};Ok(serde_json::to_string_pretty(&strings).unwrap())}- "il2cpp_meta" => {+ "crypt_constants" | "list_crypt_constants" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;- let filter = args.get("filter").and_then(|f| f.as_str());+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let prog = load_path_opts(path, true).map_err(|e| e.to_string())?;+ let mut hits = if prog.analysis.crypt_constants.is_empty() {+ ghidrust_core::scan_crypt_constants(&prog)+ } else {+ prog.analysis.crypt_constants.clone()+ };+ if let Some(a) = args.get("algo").and_then(|v| v.as_str()) {+ hits.retain(|h| h.algorithm.eq_ignore_ascii_case(a));+ }+ if let Some(l) = args.get("limit").and_then(|v| v.as_u64()) {+ hits.truncate(l as usize);+ }+ Ok(serde_json::to_string_pretty(&hits).unwrap())+ }+ "recover_strings" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let mut prog = load_path_opts(path, true).map_err(|e| e.to_string())?;+ let mut opts = ghidrust_core::RecoverStringsOpts::default();+ if let Some(arr) = args.get("only").and_then(|v| v.as_array()) {+ opts.only = Some(+ arr.iter()+ .filter_map(|v| v.as_str().map(|s| s.to_string()))+ .collect(),+ );+ }+ if let Some(arr) = args.get("no").and_then(|v| v.as_array()) {+ opts.no = Some(+ arr.iter()+ .filter_map(|v| v.as_str().map(|s| s.to_string()))+ .collect(),+ );+ }+ if let Some(arr) = args.get("functions").and_then(|v| v.as_array()) {+ let mut fns = Vec::new();+ for v in arr {+ if let Some(s) = v.as_str() {+ let t = s.trim_start_matches("0x");+ if let Ok(n) = u64::from_str_radix(t, 16) {+ fns.push(n);+ }+ } else if let Some(n) = v.as_u64() {+ fns.push(n);+ }+ }+ opts.functions = Some(fns);+ }+ opts.limit = args+ .get("limit")+ .and_then(|v| v.as_u64())+ .map(|n| n as usize);+ let _ = ghidrust_core::run_analyzers(&mut prog, &["Find Crypt"]);+ if opts.functions.is_none() {+ let seeds = ghidrust_core::recover_function_seeds(&prog);+ if !seeds.is_empty() {+ opts.functions = Some(seeds);+ }+ }+ let hits = ghidrust_core::recover_obfuscated_strings(&prog, &opts);+ Ok(serde_json::to_string_pretty(&hits).unwrap())+ }+ "decode_bake" | "decode_magic" => {+ let input = mcp_decode_input_bytes(&args)?;+ if name == "decode_magic" {+ let depth = args.get("depth").and_then(|v| v.as_u64()).unwrap_or(3) as usize;+ let crib = args.get("crib").and_then(|v| v.as_str());+ let result = ghidrust_core::magic_with_crib(&input, depth, crib);+ return Ok(serde_json::to_string_pretty(&result).unwrap());+ }+ let recipe = args+ .get("recipe")+ .or_else(|| args.get("ops"))+ .cloned()+ .ok_or_else(|| "missing arguments.recipe or arguments.ops".to_string())?;+ let ops: Vec<ghidrust_core::BakeOp> =+ serde_json::from_value(recipe).map_err(|e| e.to_string())?;+ let result = ghidrust_core::bake(&input, &ops);+ let bytes: Vec<u8> = (0..result.output_hex.len())+ .step_by(2)+ .filter_map(|i| u8::from_str_radix(&result.output_hex[i..i + 2], 16).ok())+ .collect();+ let iocs = ghidrust_core::extract_iocs(&bytes);+ let annotation = if result.ok {+ match (+ args.get("path").and_then(|v| v.as_str()),+ args.get("annotate_va").and_then(|v| v.as_str()),+ ) {+ (Some(path), Some(va)) => {+ let va = parse_u64(va)?;+ let mut prog = load_path(path).map_err(|e| e.to_string())?;+ prog.edits.set_comment(+ va,+ ghidrust_core::CommentKind::Eol,+ format!("decode bake: {}", result.recipe_applied.join(" -> ")),+ );+ Some(json!({+ "va": format!("{va:#x}"),+ "applied": true,+ "persisted": false,+ "note": "comment applied in memory only; a plain path load has no project save target"+ }))+ }+ (None, Some(va)) => Some(json!({+ "va": va,+ "applied": false,+ "persisted": false,+ "note": "annotate_va requires path"+ })),+ _ => None,+ }+ } else {+ None+ };+ Ok(serde_json::to_string_pretty(&json!({+ "result": result,+ "iocs": iocs,+ "annotation": annotation+ }))+ .unwrap())+ }+ "list_crypto_capabilities" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let mut prog = load_path_opts(path, true).map_err(|e| e.to_string())?;+ let _ = ghidrust_core::run_crypto_pipeline(&mut prog);+ let tag = args.get("tag").and_then(|v| v.as_str());+ let hits = ghidrust_core::scan_crypto_capabilities(&prog, tag);+ let hits: Vec<Value> = hits+ .iter()+ .map(|hit| {+ let mut value = serde_json::to_value(hit).unwrap_or(Value::Null);+ let suggested_ops: Vec<String> =+ ghidrust_core::suggest_recipe_for_hint(&hit.capability)+ .into_iter()+ .map(|op| op.op)+ .collect();+ if let Some(object) = value.as_object_mut() {+ object.insert("suggested_ops".into(), json!(suggested_ops));+ }+ value+ })+ .collect();+ Ok(serde_json::to_string_pretty(&hits).unwrap())+ }+ "il2cpp_meta" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let filter = args.get("filter").and_then(|f| f.as_str());let meta = match Il2CppMetadata::load_path(path) {Ok(m) => m,Err(e) => {if let Some(payload) = e.to_structured_json() {- return Err(serde_json::to_string_pretty(&payload).unwrap_or_else(|_| e.to_string()));+ return Err(serde_json::to_string_pretty(&payload)+ .unwrap_or_else(|_| e.to_string()));}return Err(e.to_string());}};let types: Vec<_> = match filter {- Some(f) => meta.filter_types(f).into_iter().map(|t| t.full_name()).collect(),+ Some(f) => meta+ .filter_types(f)+ .into_iter()+ .map(|t| t.full_name())+ .collect(),None => meta.types.iter().map(|t| t.full_name()).collect(),};let methods: Vec<_> = match filter {@@ -4097,28 +4455,28 @@ fn call_tool(params: &Value) -> Result<String, String> {.collect(),};Ok(serde_json::to_string_pretty(&json!({- "version": meta.header.version,- "dialect": meta.header.dialect,- "types": types,- "methods": methods,- }))+ "version": meta.header.version,+ "dialect": meta.header.dialect,+ "types": types,+ "methods": methods,+ })).unwrap())}- "il2cpp_map" => {+ "il2cpp_map" => {let binary = args- .get("binary")+ .get("binary").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.binary".to_string())?;- let meta = args.get("meta").and_then(|p| p.as_str()).map(Path::new);+ .ok_or_else(|| "missing arguments.binary".to_string())?;+ let meta = args.get("meta").and_then(|p| p.as_str()).map(Path::new);let meta_sections = args- .get("meta_sections")+ .get("meta_sections").and_then(|p| p.as_str()).map(Path::new);if meta.is_none() && meta_sections.is_none() {- return Err("missing arguments.meta or arguments.meta_sections".into());+ return Err("missing arguments.meta or arguments.meta_sections".into());}- let filter = args.get("filter").and_then(|f| f.as_str());- let baseline = args.get("baseline").and_then(|p| p.as_str());+ let filter = args.get("filter").and_then(|f| f.as_str());+ let baseline = args.get("baseline").and_then(|p| p.as_str());let prog = load_path(binary).map_err(|e| e.to_string())?;let meta = load_metadata_flexible(meta, meta_sections).map_err(|e| {e.to_structured_json()@@ -4137,20 +4495,20 @@ fn call_tool(params: &Value) -> Result<String, String> {}Ok(serde_json::to_string_pretty(&map).unwrap())}- "il2cpp_touch_map" => {- let meta = args.get("meta").and_then(|p| p.as_str()).map(Path::new);+ "il2cpp_touch_map" => {+ let meta = args.get("meta").and_then(|p| p.as_str()).map(Path::new);let meta_sections = args- .get("meta_sections")+ .get("meta_sections").and_then(|p| p.as_str()).map(Path::new);let filter = args- .get("filter")+ .get("filter").and_then(|f| f.as_str())- .ok_or_else(|| "missing arguments.filter".to_string())?;+ .ok_or_else(|| "missing arguments.filter".to_string())?;if meta.is_none() && meta_sections.is_none() {- return Err("missing arguments.meta or arguments.meta_sections".into());+ return Err("missing arguments.meta or arguments.meta_sections".into());}- let prog = match args.get("binary").and_then(|p| p.as_str()) {+ let prog = match args.get("binary").and_then(|p| p.as_str()) {Some(b) => Some(load_path(b).map_err(|e| e.to_string())?),None => None,};@@ -4161,13 +4519,13 @@ fn call_tool(params: &Value) -> Result<String, String> {})?;Ok(serde_json::to_string_pretty(&report).unwrap())}- "il2cpp_stubs" => {+ "il2cpp_stubs" => {let binary = args- .get("binary")+ .get("binary").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.binary".to_string())?;- let filter = args.get("filter").and_then(|f| f.as_str());- let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(250_000) as usize;+ .ok_or_else(|| "missing arguments.binary".to_string())?;+ let filter = args.get("filter").and_then(|f| f.as_str());+ let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(250_000) as usize;let prog = load_path(binary).map_err(|e| e.to_string())?;let mut stubs = find_resolve_stubs(&prog, max);if let Some(f) = filter {@@ -4175,83 +4533,84 @@ fn call_tool(params: &Value) -> Result<String, String> {}Ok(serde_json::to_string_pretty(&stubs).unwrap())}- "read_bytes" => {+ "read_bytes" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;+ .ok_or_else(|| "missing arguments.path".to_string())?;let addr = args- .get("addr")+ .get("addr").and_then(|a| a.as_str())- .ok_or_else(|| "missing arguments.addr".to_string())?;- let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(64) as usize;+ .ok_or_else(|| "missing arguments.addr".to_string())?;+ let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(64) as usize;let count = count.clamp(1, 1_048_576);let prog = load_path(path).map_err(|e| e.to_string())?;let va = parse_u64(addr)?;let bytes = prog.read_va(va, count)- .ok_or_else(|| format!("address {va:#x} not mapped or unreadable"))?;+ .ok_or_else(|| format!("address {va:#x} not mapped or unreadable"))?;let hex: String = bytes.iter()- .map(|b| format!("{b:02x}"))+ .map(|b| format!("{b:02x}")).collect::<Vec<_>>()- .join(" ");+ .join(" ");Ok(serde_json::to_string_pretty(&json!({- "addr": format!("{va:#x}"),- "count": bytes.len(),- "hex": hex,- "bytes": bytes,- }))+ "addr": format!("{va:#x}"),+ "count": bytes.len(),+ "hex": hex,+ "bytes": bytes,+ })).unwrap())}- "il2cpp_icalls" => {+ "il2cpp_icalls" => {let binary = args- .get("binary")+ .get("binary").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.binary".to_string())?;- let filter = args.get("filter").and_then(|f| f.as_str());+ .ok_or_else(|| "missing arguments.binary".to_string())?;+ let filter = args.get("filter").and_then(|f| f.as_str());let report = resolve_icalls_path(binary).map_err(|e| e.to_string())?;if let Some(f) = filter {let hits = filter_entries(&report, f);Ok(serde_json::to_string_pretty(&json!({- "filter": f,- "table_count": report.tables.len(),- "hits": hits.iter().map(|(ti, e)| json!({- "table_index": ti,- "index": e.index,- "name": e.name,- "name_string_va": format!("{:#x}", e.name_string_va),- "fn_va": format!("{:#x}", e.fn_va),- "fn_rva": format!("{:#x}", e.fn_rva),- })).collect::<Vec<_>>(),- })).unwrap())+ "filter": f,+ "table_count": report.tables.len(),+ "hits": hits.iter().map(|(ti, e)| json!({+ "table_index": ti,+ "index": e.index,+ "name": e.name,+ "name_string_va": format!("{:#x}", e.name_string_va),+ "fn_va": format!("{:#x}", e.fn_va),+ "fn_rva": format!("{:#x}", e.fn_rva),+ })).collect::<Vec<_>>(),+ }))+ .unwrap())} else {Ok(serde_json::to_string_pretty(&report).unwrap())}}- "unity_inventory" => {+ "unity_inventory" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;+ .ok_or_else(|| "missing arguments.path".to_string())?;let inv = inventory_path(path)?;Ok(serde_json::to_string_pretty(&inv).unwrap())}- "get_xrefs_to" => {+ "get_xrefs_to" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;+ .ok_or_else(|| "missing arguments.path".to_string())?;let addr = args- .get("addr")+ .get("addr").and_then(|a| a.as_str())- .ok_or_else(|| "missing arguments.addr".to_string())?;+ .ok_or_else(|| "missing arguments.addr".to_string())?;let skip_stubs = args- .get("skip_stubs")+ .get("skip_stubs").and_then(|v| v.as_bool()).unwrap_or(false);let classify = args- .get("classify")+ .get("classify").and_then(|v| v.as_bool()).unwrap_or(false);let prog = load_path(path).map_err(|e| e.to_string())?;@@ -4266,30 +4625,30 @@ fn call_tool(params: &Value) -> Result<String, String> {}Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())}- "get_xrefs_from" => {+ "get_xrefs_from" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;+ .ok_or_else(|| "missing arguments.path".to_string())?;let addr = args- .get("addr")+ .get("addr").and_then(|a| a.as_str())- .ok_or_else(|| "missing arguments.addr".to_string())?;- let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(256) as usize;+ .ok_or_else(|| "missing arguments.addr".to_string())?;+ let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(256) as usize;let prog = load_path(path).map_err(|e| e.to_string())?;let va = parse_u64(addr)?;let refs = xrefs_from(&prog, va, count);Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())}- "get_calls_from" => {+ "get_calls_from" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;+ .ok_or_else(|| "missing arguments.path".to_string())?;let addr = args- .get("addr")+ .get("addr").and_then(|a| a.as_str())- .ok_or_else(|| "missing arguments.addr".to_string())?;+ .ok_or_else(|| "missing arguments.addr".to_string())?;let mut prog = load_path(path).map_err(|e| e.to_string())?;let va = parse_u64(addr)?;let (entry, resolve_meta) = friction::resolve_and_entry(&mut prog, Some(va))?;@@ -4298,44 +4657,44 @@ fn call_tool(params: &Value) -> Result<String, String> {.iter().map(|e| {json!({- "from": format!("{:#x}", e.from),- "to": format!("{:#x}", e.to),- "kind": e.kind,- "to_entry": e.to_entry.map(|v| format!("{v:#x}")),- "to_function": e.to_function,- })+ "from": format!("{:#x}", e.from),+ "to": format!("{:#x}", e.to),+ "kind": e.kind,+ "to_entry": e.to_entry.map(|v| format!("{v:#x}")),+ "to_function": e.to_function,+ })}).collect();Ok(serde_json::to_string_pretty(&json!({- "resolve": resolve_meta,- "calls": rows,- }))+ "resolve": resolve_meta,+ "calls": rows,+ })).unwrap())}- "get_string_xrefs" => {+ "get_string_xrefs" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;+ .ok_or_else(|| "missing arguments.path".to_string())?;let filter = args- .get("filter")+ .get("filter").and_then(|f| f.as_str())- .ok_or_else(|| "missing arguments.filter".to_string())?;+ .ok_or_else(|| "missing arguments.filter".to_string())?;let encoding = args- .get("encoding")+ .get("encoding").and_then(|e| e.as_str())- .unwrap_or("all");+ .unwrap_or("all");let prog = load_path(path).map_err(|e| e.to_string())?;let refs = xrefs_to_string_filter_opts(&prog, filter, encoding, true);Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())}- "list_imports" => {+ "list_imports" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;- let dll = args.get("dll").and_then(|d| d.as_str());- let name_f = args.get("name").and_then(|n| n.as_str());+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let dll = args.get("dll").and_then(|d| d.as_str());+ let name_f = args.get("name").and_then(|n| n.as_str());let prog = load_path(path).map_err(|e| e.to_string())?;let filtered: Vec<_> = filter_imports(&prog.imports, dll, name_f).into_iter()@@ -4343,62 +4702,63 @@ fn call_tool(params: &Value) -> Result<String, String> {.collect();Ok(serde_json::to_string_pretty(&filtered).unwrap())}- "get_import_xrefs" => {+ "get_import_xrefs" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;+ .ok_or_else(|| "missing arguments.path".to_string())?;let iname = args- .get("name")+ .get("name").and_then(|n| n.as_str())- .ok_or_else(|| "missing arguments.name()".to_string())?;+ .ok_or_else(|| "missing arguments.name()".to_string())?;let prog = load_path(path).map_err(|e| e.to_string())?;let refs = xrefs_to_import(&prog, iname);Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())}- "function_at" | "get_function_by_address" => {+ "function_at" | "get_function_by_address" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;+ .ok_or_else(|| "missing arguments.path".to_string())?;let addr = args- .get("addr")+ .get("addr").and_then(|a| a.as_str())- .ok_or_else(|| "missing arguments.addr".to_string())?;+ .ok_or_else(|| "missing arguments.addr".to_string())?;let mut prog = load_path(path).map_err(|e| e.to_string())?;if prog.analysis.functions.is_empty() {- let _ = run_analyzers(&mut prog, &["Function Start Search"]).map_err(|e| e.to_string())?;+ let _ = run_analyzers(&mut prog, &["Function Start Search"])+ .map_err(|e| e.to_string())?;}let va = parse_u64(addr)?;match prog.function_containing(va) {Some(f) => Ok(serde_json::to_string_pretty(&json!({- "addr": format!("{va:#x}"),- "entry": format!("{:#x}", f.entry),- "end": format!("{:#x}", f.end),- "name": f.name,- "calling_convention": f.calling_convention,- "noreturn": f.noreturn,- "parameters": f.parameters,- "seed_kind": f.seed_kind,- }))+ "addr": format!("{va:#x}"),+ "entry": format!("{:#x}", f.entry),+ "end": format!("{:#x}", f.end),+ "name": f.name,+ "calling_convention": f.calling_convention,+ "noreturn": f.noreturn,+ "parameters": f.parameters,+ "seed_kind": f.seed_kind,+ })).unwrap()),None => Ok(serde_json::to_string_pretty(&json!({- "addr": format!("{va:#x}"),- "function": null,- }))+ "addr": format!("{va:#x}"),+ "function": null,+ })).unwrap()),}}- "function_create" => {+ "function_create" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;+ .ok_or_else(|| "missing arguments.path".to_string())?;let addr = args- .get("addr")+ .get("addr").and_then(|a| a.as_str())- .ok_or_else(|| "missing arguments.addr".to_string())?;- let end = match args.get("end").and_then(|e| e.as_str()) {+ .ok_or_else(|| "missing arguments.addr".to_string())?;+ let end = match args.get("end").and_then(|e| e.as_str()) {Some(e) => Some(parse_u64(e)?),None => None,};@@ -4406,30 +4766,30 @@ fn call_tool(params: &Value) -> Result<String, String> {let va = parse_u64(addr)?;let f = create_function(&mut prog, va, end);Ok(serde_json::to_string_pretty(&json!({- "entry": format!("{:#x}", f.entry),- "end": format!("{:#x}", f.end),- "name": f.name,- "seed_kind": f.seed_kind,- }))+ "entry": format!("{:#x}", f.entry),+ "end": format!("{:#x}", f.end),+ "name": f.name,+ "seed_kind": f.seed_kind,+ })).unwrap())}- "list_analyzers" => {+ "list_analyzers" => {let cat = analyzer_catalog();Ok(serde_json::to_string_pretty(&cat).unwrap())}- "list_gpu_strategies" => Ok(ghidrust_core::format_matrix_table()),- "gpu_decompile" => {+ "list_gpu_strategies" => Ok(ghidrust_core::format_matrix_table()),+ "gpu_decompile" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;+ .ok_or_else(|| "missing arguments.path".to_string())?;let out = args- .get("out")+ .get("out").and_then(|p| p.as_str()).map(PathBuf::from)- .unwrap_or_else(|| std::env::temp_dir().join("mcp_gpu_decompile.gdecomp"));+ .unwrap_or_else(|| std::env::temp_dir().join("mcp_gpu_decompile.gdecomp"));let mut prog = load_path(path).map_err(|e| e.to_string())?;- let addr = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {+ let addr = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {Some(parse_u64(a)?)} else {None@@ -4438,69 +4798,69 @@ fn call_tool(params: &Value) -> Result<String, String> {let rep = ghidrust_decomp::gpu_decompile_to_file(&prog, Some(entry), &out, 256).map_err(|e| e.to_string())?;Ok(serde_json::to_string_pretty(&json!({- "resolve": resolve_meta,- "requested_addr": addr.map(|a| format!("{a:#x}")),- "resolved_entry": format!("{entry:#x}"),- "backend": rep.backend,- "device": rep.device,- "ms": rep.ms,- "pcie_upload_ms": rep.pcie_upload_ms,- "device_ms": rep.device_ms,- "pcie_download_ms": rep.pcie_download_ms,- "mid_pipeline_host_reads": rep.mid_pipeline_host_reads,- "ir_count": rep.ir_count,- "block_count": rep.block_count,- "dump_path": rep.dump_path,- "dump_bytes": rep.dump_bytes,- "note": ".gdecomp is opaque — use metrics fields, do not read dump as text",- "pseudo_c_head": rep.pseudo_c.lines().take(8).collect::<Vec<_>>().join("\n"),- }))+ "resolve": resolve_meta,+ "requested_addr": addr.map(|a| format!("{a:#x}")),+ "resolved_entry": format!("{entry:#x}"),+ "backend": rep.backend,+ "device": rep.device,+ "ms": rep.ms,+ "pcie_upload_ms": rep.pcie_upload_ms,+ "device_ms": rep.device_ms,+ "pcie_download_ms": rep.pcie_download_ms,+ "mid_pipeline_host_reads": rep.mid_pipeline_host_reads,+ "ir_count": rep.ir_count,+ "block_count": rep.block_count,+ "dump_path": rep.dump_path,+ "dump_bytes": rep.dump_bytes,+ "note": ".gdecomp is opaque — use metrics fields, do not read dump as text",+ "pseudo_c_head": rep.pseudo_c.lines().take(8).collect::<Vec<_>>().join("\n"),+ })).unwrap())}- "rtti_gpu_bench" => {+ "rtti_gpu_bench" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;- // Reuse CLI logic via load + bench (same shipped paths)+ .ok_or_else(|| "missing arguments.path".to_string())?;+ // Reuse CLI logic via load + bench (same shipped paths)let prog = load_path(path).map_err(|e| e.to_string())?;let t0 = std::time::Instant::now();let rtti = recover_rtti(&prog).map_err(|e| e.to_string())?;let cpu_rtti_ms = t0.elapsed().as_secs_f64() * 1000.0;- let row = ghidrust_core::bench_analyzer(&prog, "WindowsPE x86 PE RTTI Analyzer", None);+ let row = ghidrust_core::bench_analyzer(&prog, "WindowsPE x86 PE RTTI Analyzer", None);Ok(serde_json::to_string_pretty(&json!({- "cpu_rtti_recover_ms": cpu_rtti_ms,- "cpu_rtti_classes": rtti.classes.len(),- "gpu_strategy": row.strategy,- "gpu_pcie_upload_ms": row.gpu_pcie_upload_ms,- "gpu_device_ms": row.gpu_device_ms,- "gpu_pcie_download_ms": row.gpu_pcie_download_ms,- "gpu_pcie_ms": row.gpu_pcie_ms,- "gpu_wall_ms": row.gpu_wall_ms,- "gpu_seed_hits": row.gpu_primary,- "seed_cpu_hits": row.cpu_primary,- "seed_equal": row.equal,- "backend": row.backend,- "device": row.device,- }))+ "cpu_rtti_recover_ms": cpu_rtti_ms,+ "cpu_rtti_classes": rtti.classes.len(),+ "gpu_strategy": row.strategy,+ "gpu_pcie_upload_ms": row.gpu_pcie_upload_ms,+ "gpu_device_ms": row.gpu_device_ms,+ "gpu_pcie_download_ms": row.gpu_pcie_download_ms,+ "gpu_pcie_ms": row.gpu_pcie_ms,+ "gpu_wall_ms": row.gpu_wall_ms,+ "gpu_seed_hits": row.gpu_primary,+ "seed_cpu_hits": row.cpu_primary,+ "seed_equal": row.equal,+ "backend": row.backend,+ "device": row.device,+ })).unwrap())}- "decompile" => {+ "decompile" => {let path = args- .get("path")+ .get("path").and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;- let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(64) as usize;+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(64) as usize;let stage = args- .get("stage")+ .get("stage").and_then(|s| s.as_str())- .unwrap_or("stage1");+ .unwrap_or("stage1");let follow_stub = args- .get("follow_stub")+ .get("follow_stub").and_then(|v| v.as_bool()).unwrap_or(false);let mut prog = load_path(path).map_err(|e| e.to_string())?;- let addr_opt = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {+ let addr_opt = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {Some(parse_u64(a)?)} else {None@@ -4516,51 +4876,55 @@ fn call_tool(params: &Value) -> Result<String, String> {follow_meta = Some(fm);}}- let conv = if prog.format.to_ascii_lowercase().contains("pe") {+ let conv = if prog.format.to_ascii_lowercase().contains("pe") {ghidrust_types::CallConv::Windows} else {ghidrust_types::CallConv::SystemV};match stage {- "stage0" | "stage-0" => {- let d =- ghidrust_decomp::decompile_at(&prog, va, count).map_err(|e| e.to_string())?;+ "stage0" | "stage-0" => {+ let d = ghidrust_decomp::decompile_at(&prog, va, count)+ .map_err(|e| e.to_string())?;let mut obj = json!({- "stage": "0",- "resolve": resolve_meta,- "name": d.name,- "entry": format!("{:#x}", d.entry),- "blocks": d.blocks.len(),- "edges": d.edges.len(),- "insns": d.insn_count,- "pseudo_c": d.pseudo_c,- });+ "stage": "0",+ "resolve": resolve_meta,+ "name": d.name,+ "entry": format!("{:#x}", d.entry),+ "blocks": d.blocks.len(),+ "edges": d.edges.len(),+ "insns": d.insn_count,+ "pseudo_c": d.pseudo_c,+ });if let Some(fm) = follow_meta {- obj.as_object_mut().unwrap().insert("follow_stub".into(), fm);+ obj.as_object_mut()+ .unwrap()+ .insert("follow_stub".into(), fm);}Ok(serde_json::to_string_pretty(&obj).unwrap())}- "stage05" | "stage-0.5" | "ir" => {+ "stage05" | "stage-0.5" | "ir" => {let (d, cov) = ghidrust_decomp::decompile_ir_at(&prog, va, count).map_err(|e| e.to_string())?;let mut obj = json!({- "stage": "0.5",- "resolve": resolve_meta,- "name": d.name,- "entry": format!("{:#x}", d.entry),- "blocks": d.blocks.len(),- "edges": d.edges.len(),- "insns": d.insn_count,- "lift_ratio": cov.ratio(),- "pseudo_c": d.pseudo_c,- });+ "stage": "0.5",+ "resolve": resolve_meta,+ "name": d.name,+ "entry": format!("{:#x}", d.entry),+ "blocks": d.blocks.len(),+ "edges": d.edges.len(),+ "insns": d.insn_count,+ "lift_ratio": cov.ratio(),+ "pseudo_c": d.pseudo_c,+ });if let Some(fm) = follow_meta {- obj.as_object_mut().unwrap().insert("follow_stub".into(), fm);+ obj.as_object_mut()+ .unwrap()+ .insert("follow_stub".into(), fm);}Ok(serde_json::to_string_pretty(&obj).unwrap())}_ => {- // Default: Stage-1 full pipeline.+ // Default: Stage-1 full pipeline.let (d, s1) = ghidrust_decomp::decompile_stage1_at(&prog, va, count, conv).map_err(|e| e.to_string())?;let stored_end = prog.function_at(va).map(|f| f.end);@@ -4571,26 +4935,26 @@ fn call_tool(params: &Value) -> Result<String, String> {.unwrap_or_default();let callsite_hints = collect_callsite_hints(&linear);let mut obj = json!({- "stage": "1",- "resolve": resolve_meta,- "name": d.name,- "entry": format!("{:#x}", d.entry),- "blocks": d.blocks.len(),- "insns": d.insn_count,- "loops": s1.structure.loops.len(),- "phis": s1.ssa.phi_count(),- "locals": s1.types.locals.len(),- "params": s1.types.params.len(),- "structs": s1.types.structs.len(),- "lift_ratio": s1.coverage.ratio(),- "goto_rate": s1.summary().goto_rate,- "folded_temps": s1.folded_temps,- "token_count": s1.tokens.len(),- "return_type": s1.types.signature.return_type.c_style(),- "prototype": s1.types.signature.to_prototype(),- "pseudo_c": d.pseudo_c,- "callsite_hints": callsite_hints,- });+ "stage": "1",+ "resolve": resolve_meta,+ "name": d.name,+ "entry": format!("{:#x}", d.entry),+ "blocks": d.blocks.len(),+ "insns": d.insn_count,+ "loops": s1.structure.loops.len(),+ "phis": s1.ssa.phi_count(),+ "locals": s1.types.locals.len(),+ "params": s1.types.params.len(),+ "structs": s1.types.structs.len(),+ "lift_ratio": s1.coverage.ratio(),+ "goto_rate": s1.summary().goto_rate,+ "folded_temps": s1.folded_temps,+ "token_count": s1.tokens.len(),+ "return_type": s1.types.signature.return_type.c_style(),+ "prototype": s1.types.signature.to_prototype(),+ "pseudo_c": d.pseudo_c,+ "callsite_hints": callsite_hints,+ });if let Some(m) = obj.as_object_mut() {if let Some(hf) = honesty.to_json_fields().as_object() {for (k, v) in hf {@@ -4599,86 +4963,79 @@ fn call_tool(params: &Value) -> Result<String, String> {}}if let Some(fm) = follow_meta {- obj.as_object_mut().unwrap().insert("follow_stub".into(), fm);+ obj.as_object_mut()+ .unwrap()+ .insert("follow_stub".into(), fm);}Ok(serde_json::to_string_pretty(&obj).unwrap())}}}- "decode_support" => mcp_decode::handle_decode_support(&args),- "decode_query" => mcp_decode::handle_decode_query(&args),- "disassemble" => mcp_decode::handle_disassemble(&args),- "load" | "rtti" | "analyze" => {- match name {- "load" => {- let path = if let Some(p) = args.get("path").and_then(|p| p.as_str()) {- p.to_string()- } else if let (Some(proj), Some(fid)) = (- args.get("project").and_then(|p| p.as_str()),- args.get("file_id").and_then(|p| p.as_str()),- ) {- let project = Project::open(proj).map_err(|e| e.to_string())?;- let entry = project- .list_files()- .into_iter()- .find(|f| f.id == fid)- .ok_or_else(|| format!("file_id not found: {fid}"))?;- project- .root- .join(&entry.imported_rel)- .display()- .to_string()- } else {- return Err("load requires path or project+file_id".into());- };- let prog = load_path(&path).map_err(|e| e.to_string())?;- let identity = json!({- "path": args.get("path").and_then(|p| p.as_str()),- "project": args.get("project").and_then(|p| p.as_str()),- "file_id": args.get("file_id").and_then(|p| p.as_str()),- "resolved_path": path,- });- Ok(serde_json::to_string_pretty(&friction::load_json_for_prog(- &prog, &identity,- ))- .unwrap())- }- "rtti" => {- let path = args- .get("path")- .and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;- let prog = load_path(path).map_err(|e| e.to_string())?;- let report = recover_rtti(&prog).map_err(|e| e.to_string())?;- Ok(serde_json::to_string_pretty(&report).unwrap())- }- "analyze" => {- let path = args- .get("path")- .and_then(|p| p.as_str())- .ok_or_else(|| "missing arguments.path".to_string())?;- let mut prog = load_path(path).map_err(|e| e.to_string())?;- let names_owned: Vec<String> = args- .get("analyzers")- .and_then(|a| a.as_array())- .map(|arr| {- arr.iter()- .filter_map(|v| v.as_str().map(|s| s.to_string()))- .collect()- })- .unwrap_or_default();- let name_refs: Vec<&str> = names_owned.iter().map(|s| s.as_str()).collect();- let use_gpu = args- .get("gpu")- .and_then(|g| g.as_bool())- .unwrap_or(false);- let report = ghidrust_core::run_analyzers_opts(&mut prog, &name_refs, use_gpu)- .map_err(|e| e.to_string())?;- Ok(serde_json::to_string_pretty(&report).unwrap())- }- _ => unreachable!(),+ "decode_support" => mcp_decode::handle_decode_support(&args),+ "decode_query" => mcp_decode::handle_decode_query(&args),+ "disassemble" => mcp_decode::handle_disassemble(&args),+ "load" | "rtti" | "analyze" => match name {+ "load" => {+ let path = if let Some(p) = args.get("path").and_then(|p| p.as_str()) {+ p.to_string()+ } else if let (Some(proj), Some(fid)) = (+ args.get("project").and_then(|p| p.as_str()),+ args.get("file_id").and_then(|p| p.as_str()),+ ) {+ let project = Project::open(proj).map_err(|e| e.to_string())?;+ let entry = project+ .list_files()+ .into_iter()+ .find(|f| f.id == fid)+ .ok_or_else(|| format!("file_id not found: {fid}"))?;+ project.root.join(&entry.imported_rel).display().to_string()+ } else {+ return Err("load requires path or project+file_id".into());+ };+ let prog = load_path(&path).map_err(|e| e.to_string())?;+ let identity = json!({+ "path": args.get("path").and_then(|p| p.as_str()),+ "project": args.get("project").and_then(|p| p.as_str()),+ "file_id": args.get("file_id").and_then(|p| p.as_str()),+ "resolved_path": path,+ });+ Ok(+ serde_json::to_string_pretty(&friction::load_json_for_prog(&prog, &identity))+ .unwrap(),+ )}- }- other => Err(format!("unknown tool: {other}")),+ "rtti" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let prog = load_path(path).map_err(|e| e.to_string())?;+ let report = recover_rtti(&prog).map_err(|e| e.to_string())?;+ Ok(serde_json::to_string_pretty(&report).unwrap())+ }+ "analyze" => {+ let path = args+ .get("path")+ .and_then(|p| p.as_str())+ .ok_or_else(|| "missing arguments.path".to_string())?;+ let mut prog = load_path(path).map_err(|e| e.to_string())?;+ let names_owned: Vec<String> = args+ .get("analyzers")+ .and_then(|a| a.as_array())+ .map(|arr| {+ arr.iter()+ .filter_map(|v| v.as_str().map(|s| s.to_string()))+ .collect()+ })+ .unwrap_or_default();+ let name_refs: Vec<&str> = names_owned.iter().map(|s| s.as_str()).collect();+ let use_gpu = args.get("gpu").and_then(|g| g.as_bool()).unwrap_or(false);+ let report = ghidrust_core::run_analyzers_opts(&mut prog, &name_refs, use_gpu)+ .map_err(|e| e.to_string())?;+ Ok(serde_json::to_string_pretty(&report).unwrap())+ }+ _ => unreachable!(),+ },+ other => Err(format!("unknown tool: {other}")),}}diff --git a/crates/ghidrust-cli/src/mcp_decode.rs b/crates/ghidrust-cli/src/mcp_decode.rsindex 6ff1960..995616e 100644--- a/crates/ghidrust-cli/src/mcp_decode.rs+++ b/crates/ghidrust-cli/src/mcp_decode.rs@@ -69,7 +69,8 @@ pub fn disassemble_tool_def() -> McpToolDef {pub fn decode_support_tool_def() -> McpToolDef {McpToolDef {name: "decode_support",- description: "Decode engine version, supported arches, options, syntax values, and compile features",+ description:+ "Decode engine version, supported arches, options, syntax values, and compile features",input_schema: json!({ "type": "object", "properties": {} }),}}diff --git a/crates/ghidrust-cli/tests/cli_mcp.rs b/crates/ghidrust-cli/tests/cli_mcp.rsindex e25d723..ccb726f 100644--- a/crates/ghidrust-cli/tests/cli_mcp.rs+++ b/crates/ghidrust-cli/tests/cli_mcp.rs@@ -53,7 +53,10 @@ fn cli_disasm_pretty_brief_and_text_out() {);let pretty_s = String::from_utf8_lossy(&pretty.stdout);assert!(pretty_s.contains("; entry="), "{pretty_s}");- assert!(pretty_s.contains("push") || pretty_s.contains("ret"), "{pretty_s}");+ assert!(+ pretty_s.contains("push") || pretty_s.contains("ret"),+ "{pretty_s}"+ );let brief = bin().args(["disasm", pe_s, "-count", "5", "-brief"])@@ -83,7 +86,10 @@ fn cli_disasm_pretty_brief_and_text_out() {String::from_utf8_lossy(&out.stderr));let file = std::fs::read_to_string(&tmp).expect("read text out");- assert!(file.contains(':') && !file.trim_start().starts_with('{'), "{file}");+ assert!(+ file.contains(':') && !file.trim_start().starts_with('{'),+ "{file}"+ );let _ = std::fs::remove_file(&tmp);let json = bin()diff --git a/crates/ghidrust-cli/tests/eval_analysis_decompile.rs b/crates/ghidrust-cli/tests/eval_analysis_decompile.rsindex fbc9566..bedaf96 100644--- a/crates/ghidrust-cli/tests/eval_analysis_decompile.rs+++ b/crates/ghidrust-cli/tests/eval_analysis_decompile.rs@@ -658,7 +658,10 @@ fn eval_one_analyzer(check: &AnalyzerCheck) -> EvalRow {Some(v) => v,None => {row.error = Some("stdout is not JSON".into());- row.evidence = format!("stdout head: {}", stdout.chars.take(200).collect::<String>());+ row.evidence = format!(+ "stdout head: {}",+ stdout.chars.take(200).collect::<String>()+ );return row;}};@@ -1233,7 +1236,10 @@ fn eval_analysis_decompile() {let row = eval_one_analyzer(&check);eprintln!("[analyzer] {:<45} fixture={:<20} status={:<4} — {}",- row.name(), row.fixture, row.status, row.evidence+ row.name(),+ row.fixture,+ row.status,+ row.evidence);rows.push(row);}@@ -1244,32 +1250,47 @@ fn eval_analysis_decompile() {let r = eval_decompile_stage0(fx);eprintln!("[decomp ] {:<45} fixture={:<20} status={:<4} — {}",- r.name(), r.fixture, r.status, r.evidence+ r.name(),+ r.fixture,+ r.status,+ r.evidence);rows.push(r);let r = eval_decompile_stage05(fx);eprintln!("[decomp ] {:<45} fixture={:<20} status={:<4} — {}",- r.name(), r.fixture, r.status, r.evidence+ r.name(),+ r.fixture,+ r.status,+ r.evidence);rows.push(r);}let r = eval_decompile_bench("analysis_lab.pe");eprintln!("[decomp ] {:<45} fixture={:<20} status={:<4} — {}",- r.name(), r.fixture, r.status, r.evidence+ r.name(),+ r.fixture,+ r.status,+ r.evidence);rows.push(r);let r = eval_re_bench("analysis_lab.pe");eprintln!("[decomp ] {:<45} fixture={:<20} status={:<4} — {}",- r.name(), r.fixture, r.status, r.evidence+ r.name(),+ r.fixture,+ r.status,+ r.evidence);rows.push(r);let r = eval_gpu_decompile("tiny_x64.pe");eprintln!("[decomp ] {:<45} fixture={:<20} status={:<4} — {}",- r.name(), r.fixture, r.status, r.evidence+ r.name(),+ r.fixture,+ r.status,+ r.evidence);rows.push(r);diff --git a/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rs b/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rsindex 3fa505d..ac2e750 100644--- a/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rs+++ b/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rs@@ -51,6 +51,12 @@ const EXPECTED_MCP_TOOLS: &[&str] = &["rtti_gpu_bench","list_strings","search_strings",+ "crypt_constants",+ "list_crypt_constants",+ "recover_strings",+ "decode_bake",+ "decode_magic",+ "list_crypto_capabilities","il2cpp_meta","il2cpp_map","il2cpp_touch_map",@@ -81,6 +87,10 @@ const EXPECTED_CLI_COMMANDS: &[&str] = &["analyzers","analyze","strings",+ "crypt-constants",+ "recover-strings",+ "crypto-capabilities",+ "decode","xrefs","imports","function-at",@@ -127,22 +137,28 @@ fn workspace_root() -> PathBuf {}fn fixture(name: &str) -> PathBuf {- workspace_root.join("fixtures").join(name)+ workspace_root().join("fixtures").join(name)}fn pe() -> String {- fixture("tiny_x64.pe").to_string_lossy().into_owned()}+ fixture("tiny_x64.pe").to_string_lossy().into_owned()+}fn lab() -> String {- fixture("analysis_lab.pe").to_string_lossy().into_owned()}+ fixture("analysis_lab.pe").to_string_lossy().into_owned()+}fn elf() -> String {- fixture("tiny_x64.elf").to_string_lossy().into_owned()}+ fixture("tiny_x64.elf").to_string_lossy().into_owned()+}fn il2cpp_pe() -> String {fixture("il2cpp/il2cpp_stub_lab.pe").to_string_lossy().into_owned()}fn il2cpp_meta() -> String {- fixture("il2cpp/meta_v31.dat").to_string_lossy().into_owned()}+ fixture("il2cpp/meta_v31.dat")+ .to_string_lossy()+ .into_owned()+}fn truncate(s: &str, n: usize) -> String {s.chars().take(n).collect()@@ -150,7 +166,10 @@ fn truncate(s: &str, n: usize) -> String {fn run_cli(args: &[&str]) -> (bool, i32, String, String, f64) {let t = Instant::now();- let out = Command::new(bin).args(args).output.expect("spawn ghidrust");+ let out = Command::new(bin())+ .args(args)+ .output()+ .expect("spawn ghidrust");let code = out.status.code().unwrap_or(-1);(out.status.success(),@@ -237,7 +256,7 @@ fn expect_cli_honest(name: &str, args: &[&str], markers: &[&str]) -> EvalRow {let (ok, code, stdout, stderr, ms) = run_cli(args);let blob = format!("{stdout}{stderr}");let marked = markers.is_empty() || markers.iter().any(|m| blob.contains(m));- let honest = (ok || code == 1 || code == 2) && marked && !blob.to_lowercase.contains("panic");+ let honest = (ok || code == 1 || code == 2) && marked && !blob.to_lowercase().contains("panic");if honest {row_pass("cli", name, ms, format!("exit={code}"))} else {@@ -256,7 +275,7 @@ fn expect_cli_json(name: &str, args: &[&str]) -> EvalRow {let (ok, code, stdout, stderr, ms) = run_cli(args);let t = stdout.trim_start();if ok && (t.starts_with('{') || t.starts_with('[')) {- row_pass("cli", name, ms, format!("json len={}", stdout.len))+ row_pass("cli", name, ms, format!("json len={}", stdout.len()))} else {row_fail("cli",@@ -269,7 +288,7 @@ fn expect_cli_json(name: &str, args: &[&str]) -> EvalRow {}fn write_reports(rows: &[EvalRow]) {- let dev = workspace_root.join("dev");+ let dev = workspace_root().join("dev");let _ = std::fs::create_dir_all(&dev);let pass = rows.iter().filter(|r| r.status == "PASS").count();let fail = rows.iter().filter(|r| r.status == "FAIL").count();@@ -278,12 +297,12 @@ fn write_reports(rows: &[EvalRow]) {let json_path = dev.join("eval_cli_mcp_surface.json");let report = json!({"environment": {- "cli": bin.display.to_string(),+ "cli": bin().display().to_string(),"package_version()": env!("CARGO_PKG_VERSION"),- "expected_mcp_tools": EXPECTED_MCP_TOOLS.len,- "expected_cli_commands": EXPECTED_CLI_COMMANDS.len,+ "expected_mcp_tools": EXPECTED_MCP_TOOLS.len(),+ "expected_cli_commands": EXPECTED_CLI_COMMANDS.len(),},- "summary": { "pass": pass, "fail": fail, "skip": skip, "total": rows.len },+ "summary": { "pass": pass, "fail": fail, "skip": skip, "total": rows.len() },"rows": rows,});std::fs::write(&json_path, serde_json::to_string_pretty(&report).unwrap()).unwrap();@@ -304,7 +323,7 @@ fn write_reports(rows: &[EvalRow]) {md.push_str(&format!("| {} | `{}` | {} | {:.1} | {} |\n",r.kind,- r.name().replace('|', "\\|"),+ r.name.as_str().replace('|', "\\|"),r.status,r.elapsed_ms,r.evidence.replace('|', "\\|").replace('\n', " ")@@ -315,7 +334,7 @@ fn write_reports(rows: &[EvalRow]) {for r in rows.iter().filter(|r| r.status == "FAIL") {md.push_str(&format!("### `{}`\n```\n{}\n```\n\n",- r.name(),+ r.name.as_str(),r.error.as_deref().unwrap_or("(no detail)")));}@@ -323,7 +342,7 @@ fn write_reports(rows: &[EvalRow]) {std::fs::write(dev.join("EVAL_CLI_MCP_SURFACE_REPORT.md"), md).unwrap();eprintln!("=== CLI/MCP SURFACE EVAL PASS={pass} FAIL={fail} SKIP={skip} ===\nreport: {}\njson : {}",- dev.join("EVAL_CLI_MCP_SURFACE_REPORT.md").display,+ dev.join("EVAL_CLI_MCP_SURFACE_REPORT.md").display(),json_path.display());}@@ -369,7 +388,7 @@ fn mcp_response_for(stdout: &str, id: u64) -> Option<Value> {let Ok(v) = serde_json::from_str::<Value>(line) else {continue;};- if v.get("id").and_then(|x| x.as_u64) == Some(id) {+ if v.get("id").and_then(|x| x.as_u64()) == Some(id) {return Some(v);}}@@ -460,7 +479,7 @@ fn mcp_process_chain(image: &str) -> (bool, String, f64, Vec<(&'static str, bool}all.push_str(line);if let Ok(v) = serde_json::from_str::<Value>(line) {- if v.get("id").and_then(|x| x.as_u64) == Some(want) {+ if v.get("id").and_then(|x| x.as_u64()) == Some(want) {return v.get("result").is_some() || v.get("error").is_some();}}@@ -488,7 +507,8 @@ fn mcp_process_chain(image: &str) -> (bool, String, f64, Vec<(&'static str, boollet launch_ok = read_id(&mut reader, &mut all, &mut line, 2);let sid = extract_session_id(&all);- let mut results: Vec<(&'static str, bool)> = vec![("process_launch", launch_ok && sid.is_some())];+ let mut results: Vec<(&'static str, bool)> =+ vec![("process_launch", launch_ok && sid.is_some())];if let Some(session) = sid {let steps: Vec<(&str, Value)> = vec![@@ -539,7 +559,7 @@ fn mcp_process_chain(image: &str) -> (bool, String, f64, Vec<(&'static str, bool}fn tempfile_dir() -> PathBuf {- let p = std::env::temp_dir.join(format!("ghidrust_eval_surface_{}", std::process::id));+ let p = std::env::temp_dir().join(format!("ghidrust_eval_surface_{}", std::process::id()));let _ = std::fs::create_dir_all(&p);// Drop a tiny file so inventory/tree have something to list.let _ = std::fs::write(p.join("marker.txt"), b"ghidrust-eval\n");@@ -669,6 +689,31 @@ fn eval_cli_mcp_surface_catalog() {&["strings", &lab, "-filter", "ExitProcess", "-json"],&["ExitProcess"],));+ rows.push(expect_cli_json(+ "cli:crypt-constants",+ &["crypt-constants", &lab, "-json"],+ ));+ rows.push(expect_cli_json(+ "cli:recover-strings",+ &["recover-strings", &lab, "-json"],+ ));+ rows.push(expect_cli_json(+ "cli:crypto-capabilities",+ &["crypto-capabilities", &lab, "-json"],+ ));+ rows.push(expect_cli_ok(+ "cli:decode",+ &[+ "decode",+ "bake",+ "-b64",+ "SGVsbG8=",+ "-op",+ "FromBase64",+ "-json",+ ],+ &["Hello"],+ ));// Empty arrays are valid when the fixture has no code refs / import table.rows.push(expect_cli_json("cli:xrefs",@@ -812,7 +857,7 @@ fn eval_cli_mcp_surface_catalog() {// Project lifecyclerows.push(expect_cli_json("cli:project_create",- &["project", "create", proj.to_str.unwrap(), "-json"],+ &["project", "create", proj.to_str().unwrap(), "-json"],));rows.push(expect_cli_json("cli:project_import",@@ -820,12 +865,12 @@ fn eval_cli_mcp_surface_catalog() {));rows.push(expect_cli_honest("cli:project_list",- &["project", "list", proj.to_str.unwrap(), "-json"],+ &["project", "list", proj.to_str().unwrap(), "-json"],&["{", "[", "files", "name", "error"],));rows.push(expect_cli_honest("cli:project_open",- &["project", "open", proj.to_str.unwrap(), "-json"],+ &["project", "open", proj.to_str().unwrap(), "-json"],&["{", "[", "name", "files", "error"],));rows.push(expect_cli_honest(@@ -842,7 +887,7 @@ fn eval_cli_mcp_surface_catalog() {));rows.push(expect_cli_honest("cli:project_export",- &["project", "export", proj.to_str.unwrap(), "-json"],+ &["project", "export", proj.to_str().unwrap(), "-json"],&["{", "[", "export", "listing", "analysis", "error", "ok"],));@@ -886,7 +931,7 @@ fn eval_cli_mcp_surface_catalog() {"catalog","mcp_tools_list_complete",ms,- format!("all {} tools listed", EXPECTED_MCP_TOOLS.len),+ format!("all {} tools listed", EXPECTED_MCP_TOOLS.len()),));} else {rows.push(row_fail(@@ -928,6 +973,21 @@ fn eval_cli_mcp_surface_catalog() {"search_strings",json!({ "path": lab, "filter": "ExitProcess" }),),+ ("crypt_constants", json!({ "path": lab })),+ ("list_crypt_constants", json!({ "path": lab, "limit": 8 })),+ ("recover_strings", json!({ "path": lab, "limit": 32 })),+ (+ "decode_bake",+ json!({+ "input_b64": "SGVsbG8=",+ "recipe": [{ "op": "FromBase64", "args": {} }]+ }),+ ),+ (+ "decode_magic",+ json!({ "input_b64": "SGVsbG8=", "depth": 2 }),+ ),+ ("list_crypto_capabilities", json!({ "path": lab })),("list_imports", json!({ "path": lab })),("function_at", json!({ "path": lab, "addr": "0x140001000" })),(@@ -1000,7 +1060,9 @@ fn eval_cli_mcp_surface_catalog() {let (ok, stdout, stderr, ms_total) = mcp_exchange(&reqs);let per = ms_total / id_names.len().max(1) as f64;for (cid, name) in id_names {- let wired = ok && mcp_tool_wired(&stdout, cid);+ let wired = ok+ && mcp_tool_wired(&stdout, cid)+ && (name != "decode_bake" || stdout.contains("Hello"));if wired {rows.push(row_pass("mcp",@@ -1050,7 +1112,7 @@ fn eval_cli_mcp_surface_catalog() {// Every expected MCP tool must have a rowfor tool in EXPECTED_MCP_TOOLS {let key = format!("mcp:{tool}");- if !rows.iter().any(|r| r.name() == key) {+ if !rows.iter().any(|r| r.name.as_str() == key) {rows.push(row_fail("mcp",key,@@ -1065,16 +1127,17 @@ fn eval_cli_mcp_surface_catalog() {for cmd in EXPECTED_CLI_COMMANDS {let covered = rows.iter().any(|r| {r.kind == "cli"- && (r.name() == format!("cli:{cmd}")- || r.name().starts_with(&format!("cli:{cmd}_"))- || (*cmd == "mcp" && r.name() == "cli:mcp_stdio_boots")- || (*cmd == "function" && r.name().starts_with("cli:function"))- || (*cmd == "il2cpp" && r.name().starts_with("cli:il2cpp"))- || (*cmd == "artifact" && r.name().starts_with("cli:artifact"))- || (*cmd == "process" && r.name().starts_with("cli:process"))- || (*cmd == "project" && r.name().starts_with("cli:project"))+ && (r.name.as_str() == format!("cli:{cmd}")+ || r.name.as_str().starts_with(&format!("cli:{cmd}_"))+ || (*cmd == "mcp" && r.name.as_str() == "cli:mcp_stdio_boots")+ || (*cmd == "function" && r.name.as_str().starts_with("cli:function"))+ || (*cmd == "il2cpp" && r.name.as_str().starts_with("cli:il2cpp"))+ || (*cmd == "artifact" && r.name.as_str().starts_with("cli:artifact"))+ || (*cmd == "process" && r.name.as_str().starts_with("cli:process"))+ || (*cmd == "project" && r.name.as_str().starts_with("cli:project"))|| (*cmd == "disasm"- && (r.name() == "cli:disasm" || r.name() == "cli:disassemble_alias")))+ && (r.name.as_str() == "cli:disasm"+ || r.name.as_str() == "cli:disassemble_alias")))});if covered {rows.push(row_pass(diff --git a/crates/ghidrust-cli/tests/eval_crypto_fixtures.rs b/crates/ghidrust-cli/tests/eval_crypto_fixtures.rsnew file mode 100644index 0000000..4eb3883--- /dev/null+++ b/crates/ghidrust-cli/tests/eval_crypto_fixtures.rs@@ -0,0 +1,236 @@+//! Focused CLI smoke tests for the crypto discovery and recipe surface.++use ghidrust_core::fixture_path;+use serde_json::Value;+use std::path::PathBuf;+use std::process::{Command, Output};++fn bin() -> Command {+ Command::new(env!("CARGO_BIN_EXE_ghidrust"))+}++fn temp_blob(name: &str, bytes: &[u8]) -> PathBuf {+ let path = std::env::temp_dir().join(format!(+ "ghidrust_crypto_{name}_{}_{}.bin",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .expect("system time after epoch")+ .as_nanos()+ ));+ std::fs::write(&path, bytes).expect("write synthetic crypto blob");+ path+}++fn run(args: &[&str]) -> Output {+ bin().args(args).output().expect("run ghidrust")+}++fn json_stdout(output: &Output) -> Value {+ assert!(+ output.status.success(),+ "status={:?}\nstderr={}",+ output.status.code(),+ String::from_utf8_lossy(&output.stderr)+ );+ serde_json::from_slice(&output.stdout).unwrap_or_else(|error| {+ panic!(+ "invalid JSON: {error}\nstdout={}",+ String::from_utf8_lossy(&output.stdout)+ )+ })+}++#[test]+fn crypto_discovery_accepts_raw_blob_and_filters() {+ let blob = temp_blob("tea", &[0, 0, 0, 0xb9, 0x79, 0x37, 0x9e, 0]);+ let blob_s = blob.to_str().expect("UTF-8 temp path");++ let constants = json_stdout(&run(&[+ "crypt-constants",+ blob_s,+ "--algo",+ "TEA",+ "--json",+ ]));+ let hits = constants.as_array().expect("constant hits array");+ assert!(+ hits.iter().any(|hit| {+ hit.get("algorithm").and_then(Value::as_str) == Some("TEA")+ && hit.get("constant").and_then(Value::as_str) == Some("DELTA")+ }),+ "expected TEA delta hit: {constants}"+ );++ let recovered = json_stdout(&run(&[+ "recover-strings",+ blob_s,+ "--only",+ "static",+ "--json",+ ]));+ assert!(recovered.is_array(), "expected recovered string array");++ let capabilities = json_stdout(&run(&[+ "crypto-capabilities",+ blob_s,+ "--tag",+ "decrypt",+ "--json",+ ]));+ assert!(capabilities.is_array(), "expected capability array");+ let _ = std::fs::remove_file(blob);+}++#[test]+fn find_crypt_analyzer_keeps_its_cli_identity() {+ let catalog = json_stdout(&run(&["analyzers", "--json"]));+ assert!(+ catalog.to_string().contains("Find Crypt"),+ "Find Crypt missing from analyzer catalog: {catalog}"+ );++ let pe = fixture_path("analysis_lab.pe");+ let analyzed = json_stdout(&run(&[+ "analyze",+ pe.to_str().expect("UTF-8 fixture path"),+ "--analyzer",+ "Find Crypt",+ "--json",+ ]));+ assert!(+ analyzed.to_string().contains("Find Crypt"),+ "Find Crypt missing from analysis result: {analyzed}"+ );+}++#[test]+fn decode_bake_and_magic_recipe_smokes() {+ let base64 = json_stdout(&run(&[+ "decode",+ "bake",+ "-b64",+ "SGVsbG8=",+ "-op",+ "FromBase64",+ "--json",+ ]));+ assert_eq!(base64["result"]["output_utf8"], "Hello");++ let nested = json_stdout(&run(&[+ "decode",+ "bake",+ "-b64",+ "H4sIAAAAAAAC/+NXMTJVUU1U09NVVdEHAARoRhcNAAAA",+ "-op",+ "FromBase64",+ "-op",+ "Gunzip",+ "-op",+ "XOR",+ "-key-hex",+ "41",+ "--json",+ ]));+ assert_eq!(nested["result"]["output_utf8"], "Nested golden");++ let magic = json_stdout(&run(&[+ "decode",+ "magic",+ "-b64",+ "U2VjcmV0IGNyaWI=",+ "-depth",+ "2",+ "-crib",+ "crib",+ "--json",+ ]));+ assert_eq!(magic["output_utf8"], "Secret crib");+}++#[test]+fn decode_bake_cipher_known_answers() {+ let rc4 = json_stdout(&run(&[+ "decode",+ "bake",+ "-hex",+ "bbf316e8d940af0ad3",+ "-op",+ "RC4",+ "-key-hex",+ "4b6579",+ "--json",+ ]));+ assert_eq!(rc4["result"]["output_utf8"], "Plaintext");++ let des = json_stdout(&run(&[+ "decode",+ "bake",+ "-hex",+ "85e813540f0ab405",+ "-op",+ "DESDecrypt",+ "-key-hex",+ "133457799bbcdff1",+ "-mode",+ "ecb",+ "--json",+ ]));+ assert_eq!(des["result"]["output_hex"], "0123456789abcdef");++ let blowfish = json_stdout(&run(&[+ "decode",+ "bake",+ "-hex",+ "324ed0fef413a203",+ "-op",+ "BlowfishDecrypt",+ "-key-hex",+ "6162636465666768696a6b6c6d6e6f707172737475767778797a",+ "-mode",+ "ecb",+ "--json",+ ]));+ assert_eq!(blowfish["result"]["output_utf8"], "BLOWFISH");++ let triple_des = json_stdout(&run(&[+ "decode",+ "bake",+ "-hex",+ "3fe301c962ac01d02213763c1cbd4cdc799657c064ecf5d41c673812cfde9675",+ "-op",+ "TripleDESDecrypt",+ "-key-hex",+ "0123456789abcdeff1e0d3c2b5a49786fedcba9876543210",+ "-iv-hex",+ "fedcba9876543210",+ "-mode",+ "cbc",+ "--json",+ ]));+ assert_eq!(+ triple_des["result"]["output_hex"],+ "37363534333231204e6f77206973207468652074696d6520666f722000000000"+ );+}++#[test]+fn decode_bake_annotation_reports_in_memory_result() {+ let pe = fixture_path("tiny_x64.pe");+ let output = json_stdout(&run(&[+ "decode",+ "bake",+ "-b64",+ "SGVsbG8=",+ "-path",+ pe.to_str().expect("UTF-8 fixture path"),+ "-op",+ "FromBase64",+ "--annotate-va",+ "0x140001000",+ "--json",+ ]));+ assert_eq!(output["result"]["output_utf8"], "Hello");+ assert_eq!(output["annotation"]["applied"], true);+ assert_eq!(output["annotation"]["persisted"], false);+}diff --git a/crates/ghidrust-core/src/analyzers/address_tables.rs b/crates/ghidrust-core/src/analyzers/address_tables.rsindex 576e0e3..bc5d4ed 100644--- a/crates/ghidrust-core/src/analyzers/address_tables.rs+++ b/crates/ghidrust-core/src/analyzers/address_tables.rs@@ -68,7 +68,11 @@ enum EntryClass {}fn entry_class(prog: &Program, va: u64) -> EntryClass {- match prog.blocks.iter().find(|b| va >= b.va && va < b.va + b.size) {+ match prog+ .blocks+ .iter()+ .find(|b| va >= b.va && va < b.va + b.size)+ {Some(b) if b.executable => EntryClass::Code,Some(_) => EntryClass::Data,None => EntryClass::Other,@@ -91,7 +95,15 @@ fn split_by_target_class(prog: &Program, base: u64, entries: &[u64]) -> Vec<Addrseg_class = c;}}- push_segment(prog, base, entries, seg_start, entries.len(), seg_class, &mut out);+ push_segment(+ prog,+ base,+ entries,+ seg_start,+ entries.len(),+ seg_class,+ &mut out,+ );if out.is_empty() && entries.len() >= 3 {// Degenerate: all Other — keep as one Unknown table.out.push(AddressTableInfo {@@ -188,7 +200,9 @@ fn roles_compatible(a: AddressTableRole, b: AddressTableRole) -> bool {// Only merge same concrete roles (or Unknown with a concrete peer).matches!((a, b),- (CodePtrs, CodePtrs) | (DataPtrs, DataPtrs) | (Unknown, Unknown)+ (CodePtrs, CodePtrs)+ | (DataPtrs, DataPtrs)+ | (Unknown, Unknown)| (Unknown, CodePtrs)| (CodePtrs, Unknown)| (Unknown, DataPtrs)@@ -205,7 +219,11 @@ mod tests {let mut prog = Program::new("t".into(), "PE32+");prog.image_base = 0x140000000;prog.blocks.push(MemoryBlock {- name: if exec { ".text".into() } else { ".rdata".into() },+ name: if exec {+ ".text".into()+ } else {+ ".rdata".into()+ },va,size: bytes.len() as u64,bytes,diff --git a/crates/ghidrust-core/src/analyzers/aggressive.rs b/crates/ghidrust-core/src/analyzers/aggressive.rsindex 47b1694..beb23d4 100644--- a/crates/ghidrust-core/src/analyzers/aggressive.rs+++ b/crates/ghidrust-core/src/analyzers/aggressive.rs@@ -43,8 +43,8 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {continue;}let slice = &bytes[i..i + 4];- let hash_ok = start_hashes.is_empty()- || start_hashes.iter().any(|h| h.as_slice() == slice);+ let hash_ok =+ start_hashes.is_empty() || start_hashes.iter().any(|h| h.as_slice() == slice);// Also accept classic prologues even if hash set emptylet prolog = slice == [0x55, 0x48, 0x89, 0xE5] || bytes[i] == 0x55;if !(hash_ok || prolog) {diff --git a/crates/ghidrust-core/src/analyzers/crypt_constants.rs b/crates/ghidrust-core/src/analyzers/crypt_constants.rsnew file mode 100644index 0000000..0d4935b--- /dev/null+++ b/crates/ghidrust-core/src/analyzers/crypt_constants.rs@@ -0,0 +1,551 @@+//! Scan image bytes for well-known cryptographic constant tables.++use super::AnalyzerOutput;+use crate::edits::CommentKind;+use crate::error::Result;+use crate::program::{Program, ReferenceInfo};+use serde::{Deserialize, Serialize};++/// One constant-table hit in the loaded image.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+pub struct CryptConstantHit {+ pub va: u64,+ pub algorithm: String,+ pub constant: String,+ pub size: usize,+}++struct Pattern {+ algorithm: &'static str,+ constant: &'static str,+ bytes: &'static [u8],+}++/// Forward AES S-box (256 bytes).+const AES_SBOX: [u8; 256] = [+ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,+ 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,+ 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,+ 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,+ 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,+ 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,+ 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,+ 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,+ 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,+ 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,+ 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,+ 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,+ 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,+ 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,+ 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,+ 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,+];++/// Inverse AES S-box (first 64 bytes — distinctive enough for scanning).+const AES_INV_SBOX_PREFIX: [u8; 64] = [+ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,+ 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,+ 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,+ 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,+];++/// TEA / XTEA delta 0x9E3779B9 (LE).+const TEA_DELTA: [u8; 4] = [0xb9, 0x79, 0x37, 0x9e];++/// MD5 init state words (LE).+const MD5_INIT: [u8; 16] = [+ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,+];++/// SHA-256 first eight K constants (BE words as bytes).+const SHA256_K_PREFIX: [u8; 32] = [+ 0x42, 0x8a, 0x2f, 0x98, 0x71, 0x37, 0x44, 0x91, 0xb5, 0xc0, 0xfb, 0xcf, 0xe9, 0xb5, 0xdb, 0xa5,+ 0x39, 0x56, 0xc2, 0x5b, 0x59, 0xf1, 0x11, 0xf1, 0x92, 0x3f, 0x82, 0xa4, 0xab, 0x1c, 0x5e, 0xd5,+];++/// ChaCha20 / Salsa20 "expand 32-byte k" sigma ASCII.+const CHACHA_SIGMA: &[u8] = b"expand 32-byte k";++/// Blowfish P-array first 8 words (BE).+const BLOWFISH_P_PREFIX: [u8; 32] = [+ 0x24, 0x3f, 0x6a, 0x88, 0x85, 0xa3, 0x08, 0xd3, 0x13, 0x19, 0x8a, 0x2e, 0x03, 0x70, 0x73, 0x44,+ 0xa4, 0x09, 0x38, 0x22, 0x29, 0x9f, 0x31, 0xd0, 0x08, 0x2e, 0xfa, 0x98, 0xec, 0x4e, 0x6c, 0x89,+];++/// CRC32 IEEE polynomial reflected table first 16 entries.+const CRC32_TAB_PREFIX: [u8; 64] = [+ 0x00, 0x00, 0x00, 0x00, 0x96, 0x30, 0x07, 0x77, 0x2c, 0x61, 0x0e, 0xee, 0xba, 0x51, 0x09, 0x99,+ 0x19, 0xc4, 0x6d, 0x07, 0x8f, 0xf4, 0x6a, 0x70, 0x35, 0xa5, 0x63, 0xe9, 0xa3, 0x95, 0x64, 0x9e,+ 0x32, 0x88, 0xdb, 0x0e, 0xa4, 0xb8, 0xdc, 0x79, 0x1e, 0xe9, 0xd5, 0xe0, 0x88, 0xd9, 0xd2, 0x97,+ 0x2b, 0x4c, 0xb6, 0x09, 0xbd, 0x7c, 0xb1, 0x7e, 0x07, 0x2d, 0xb8, 0xe7, 0x91, 0x1d, 0xbf, 0x90,+];++/// SHA-1 initial hash words (BE).+const SHA1_INIT: [u8; 20] = [+ 0x67, 0x45, 0x23, 0x01, 0xef, 0xcd, 0xab, 0x89, 0x98, 0xba, 0xdc, 0xfe, 0x10, 0x32, 0x54, 0x76,+ 0xc3, 0xd2, 0xe1, 0xf0,+];++/// RC5 magic P32/Q32 (LE).+const RC5_PQ: [u8; 8] = [0x63, 0xb1, 0xe1, 0xb7, 0xb9, 0x79, 0x37, 0x9e];++/// DES S-box S1 first row (distinctive).+const DES_S1_ROW0: [u8; 16] = [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7];++/// Salsa20 tau "expand 16-byte k".+const SALSA_TAU: &[u8] = b"expand 16-byte k";++/// Camellia sigma0 (first 8 bytes of key schedule constant).+const CAMELLIA_SIGMA0: [u8; 8] = [0xa0, 0x9e, 0x66, 0x7f, 0x3b, 0xcc, 0x90, 0x8b];++/// SM4 S-box prefix.+const SM4_SBOX_PREFIX: [u8; 32] = [+ 0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05,+ 0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99,+];++/// zlib length code base table prefix (compression-adjacent).+const ZLIB_LEN_BASE_PREFIX: [u8; 16] = [+ 0x03, 0x00, 0x04, 0x00, 0x05, 0x00, 0x06, 0x00, 0x07, 0x00, 0x08, 0x00, 0x09, 0x00, 0x0a, 0x00,+];++/// AES Te0 first four entries (big-endian word table prefix).+const AES_TE0_PREFIX: [u8; 16] = [+ 0xc6, 0x63, 0x63, 0xa5, 0xf8, 0x7c, 0x7c, 0x84, 0xee, 0x77, 0x77, 0x99, 0xf6, 0x7b, 0x7b, 0x8d,+];++/// AES Te1 through Te3 first four entries (big-endian word table prefixes).+const AES_TE1_PREFIX: [u8; 16] = [+ 0xa5, 0xc6, 0x63, 0x63, 0x84, 0xf8, 0x7c, 0x7c, 0x99, 0xee, 0x77, 0x77, 0x8d, 0xf6, 0x7b, 0x7b,+];+const AES_TE2_PREFIX: [u8; 16] = [+ 0x63, 0xa5, 0xc6, 0x63, 0x7c, 0x84, 0xf8, 0x7c, 0x77, 0x99, 0xee, 0x77, 0x7b, 0x8d, 0xf6, 0x7b,+];+const AES_TE3_PREFIX: [u8; 16] = [+ 0x63, 0x63, 0xa5, 0xc6, 0x7c, 0x7c, 0x84, 0xf8, 0x77, 0x77, 0x99, 0xee, 0x7b, 0x7b, 0x8d, 0xf6,+];++/// AES Td0 through Td3 first four entries (big-endian word table prefixes).+const AES_TD0_PREFIX: [u8; 16] = [+ 0x51, 0xf4, 0xa7, 0x50, 0x7e, 0x41, 0x65, 0x53, 0x1a, 0x17, 0xa4, 0xc3, 0x3a, 0x27, 0x5e, 0x96,+];+const AES_TD1_PREFIX: [u8; 16] = [+ 0x50, 0x51, 0xf4, 0xa7, 0x53, 0x7e, 0x41, 0x65, 0xc3, 0x1a, 0x17, 0xa4, 0x96, 0x3a, 0x27, 0x5e,+];+const AES_TD2_PREFIX: [u8; 16] = [+ 0xa7, 0x50, 0x51, 0xf4, 0x65, 0x53, 0x7e, 0x41, 0xa4, 0xc3, 0x1a, 0x17, 0x5e, 0x96, 0x3a, 0x27,+];+const AES_TD3_PREFIX: [u8; 16] = [+ 0xf4, 0xa7, 0x50, 0x51, 0x41, 0x65, 0x53, 0x7e, 0x17, 0xa4, 0xc3, 0x1a, 0x27, 0x5e, 0x96, 0x3a,+];++/// Blowfish S-boxes S0 and S1 first eight words (big-endian).+const BLOWFISH_S0_PREFIX: [u8; 32] = [+ 0xd1, 0x31, 0x0b, 0xa6, 0x98, 0xdf, 0xb5, 0xac, 0x2f, 0xfd, 0x72, 0xdb, 0xd0, 0x1a, 0xdf, 0xb7,+ 0xb8, 0xe1, 0xaf, 0xed, 0x6a, 0x26, 0x7e, 0x96, 0xba, 0x7c, 0x90, 0x45, 0xf1, 0x2c, 0x7f, 0x99,+];+const BLOWFISH_S1_PREFIX: [u8; 32] = [+ 0x4b, 0x7a, 0x70, 0xe9, 0xb5, 0xb3, 0x29, 0x44, 0xdb, 0x75, 0x09, 0x2e, 0xc4, 0x19, 0x26, 0x23,+ 0xad, 0x6e, 0xa6, 0xb0, 0x49, 0xa7, 0xdf, 0x7d, 0x9c, 0xee, 0x60, 0xb8, 0x8f, 0xed, 0xb2, 0x66,+];++/// DES initial permutation table.+const DES_IP: [u8; 64] = [+ 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6,+ 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61,+ 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7,+];++/// SHA-512 initial state and first four round constants (big-endian).+const SHA512_INIT: [u8; 64] = [+ 0x6a, 0x09, 0xe6, 0x67, 0xf3, 0xbc, 0xc9, 0x08, 0xbb, 0x67, 0xae, 0x85, 0x84, 0xca, 0xa7, 0x3b,+ 0x3c, 0x6e, 0xf3, 0x72, 0xfe, 0x94, 0xf8, 0x2b, 0xa5, 0x4f, 0xf5, 0x3a, 0x5f, 0x1d, 0x36, 0xf1,+ 0x51, 0x0e, 0x52, 0x7f, 0xad, 0xe6, 0x82, 0xd1, 0x9b, 0x05, 0x68, 0x8c, 0x2b, 0x3e, 0x6c, 0x1f,+ 0x1f, 0x83, 0xd9, 0xab, 0xfb, 0x41, 0xbd, 0x6b, 0x5b, 0xe0, 0xcd, 0x19, 0x13, 0x7e, 0x21, 0x79,+];+const SHA512_K_PREFIX: [u8; 32] = [+ 0x42, 0x8a, 0x2f, 0x98, 0xd7, 0x28, 0xae, 0x22, 0x71, 0x37, 0x44, 0x91, 0x23, 0xef, 0x65, 0xcd,+ 0xb5, 0xc0, 0xfb, 0xcf, 0xec, 0x4d, 0x3b, 0x2f, 0xe9, 0xb5, 0xdb, 0xa5, 0x81, 0x89, 0xdb, 0xbc,+];++/// MD2 substitution table prefix.+const MD2_S_PREFIX: [u8; 32] = [+ 0x29, 0x2e, 0x43, 0xc9, 0xa2, 0xd8, 0x7c, 0x01, 0x3d, 0x36, 0x54, 0xa1, 0xec, 0xf0, 0x06, 0x13,+ 0x62, 0xa7, 0x05, 0xf3, 0xc0, 0xc7, 0x73, 0x8c, 0x98, 0x93, 0x2b, 0xd9, 0xbc, 0x4c, 0x82, 0xca,+];++/// Twofish q0 permutation table prefix.+const TWOFISH_Q0_PREFIX: [u8; 32] = [+ 0xa9, 0x67, 0xb3, 0xe8, 0x04, 0xfd, 0xa3, 0x76, 0x9a, 0x92, 0x80, 0x78, 0xe4, 0xdd, 0xd1, 0x38,+ 0x0d, 0xc6, 0x35, 0x98, 0x18, 0xf7, 0xec, 0x6c, 0x43, 0x75, 0x37, 0x26, 0xfa, 0x13, 0x94, 0x48,+];++/// SM4 fixed key words and round-constant prefix (big-endian).+const SM4_FK: [u8; 16] = [+ 0xa3, 0xb1, 0xba, 0xc6, 0x56, 0xaa, 0x33, 0x50, 0x67, 0x7d, 0x91, 0x97, 0xb2, 0x70, 0x22, 0xdc,+];+const SM4_CK_PREFIX: [u8; 32] = [+ 0x00, 0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38, 0x3f, 0x46, 0x4d, 0x54, 0x5b, 0x62, 0x69,+ 0x70, 0x77, 0x7e, 0x85, 0x8c, 0x93, 0x9a, 0xa1, 0xa8, 0xaf, 0xb6, 0xbd, 0xc4, 0xcb, 0xd2, 0xd9,+];++/// Camellia S-box and key-schedule constant prefixes.+const CAMELLIA_SBOX1_PREFIX: [u8; 32] = [+ 0x70, 0x82, 0x2c, 0xec, 0xb3, 0x27, 0xc0, 0xe5, 0xe4, 0x85, 0x57, 0x35, 0xea, 0x0c, 0xae, 0x41,+ 0x23, 0xef, 0x6b, 0x93, 0x45, 0x19, 0xa5, 0x21, 0xed, 0x0e, 0x4f, 0x4e, 0x1d, 0x65, 0x92, 0xbd,+];+const CAMELLIA_SIGMA: [u8; 32] = [+ 0xa0, 0x9e, 0x66, 0x7f, 0x3b, 0xcc, 0x90, 0x8b, 0xb6, 0x7a, 0xe8, 0x58, 0x4c, 0xaa, 0x73, 0xb2,+ 0xc6, 0xef, 0x37, 0x2f, 0xe9, 0x4f, 0x82, 0xbe, 0x54, 0xff, 0x53, 0xa5, 0xf1, 0xd3, 0x6f, 0x1c,+];++/// Skipjack F-table prefix.+const SKIPJACK_FTABLE_PREFIX: [u8; 32] = [+ 0xa3, 0xd7, 0x09, 0x83, 0xf8, 0x48, 0xf6, 0xf4, 0xd3, 0x8a, 0x39, 0xdb, 0x5a, 0x1f, 0x33, 0xab,+ 0x77, 0xf1, 0x43, 0x68, 0xc8, 0xb6, 0x95, 0x25, 0x1c, 0x22, 0x94, 0x21, 0x80, 0x2d, 0xb0, 0xee,+];++fn patterns() -> &'static [Pattern] {+ &[+ Pattern {+ algorithm: "AES",+ constant: "SBOX",+ bytes: &AES_SBOX,+ },+ Pattern {+ algorithm: "AES",+ constant: "INV_SBOX_PREFIX",+ bytes: &AES_INV_SBOX_PREFIX,+ },+ Pattern {+ algorithm: "AES",+ constant: "TE0_PREFIX",+ bytes: &AES_TE0_PREFIX,+ },+ Pattern {+ algorithm: "AES",+ constant: "TE1_PREFIX",+ bytes: &AES_TE1_PREFIX,+ },+ Pattern {+ algorithm: "AES",+ constant: "TE2_PREFIX",+ bytes: &AES_TE2_PREFIX,+ },+ Pattern {+ algorithm: "AES",+ constant: "TE3_PREFIX",+ bytes: &AES_TE3_PREFIX,+ },+ Pattern {+ algorithm: "AES",+ constant: "TD0_PREFIX",+ bytes: &AES_TD0_PREFIX,+ },+ Pattern {+ algorithm: "AES",+ constant: "TD1_PREFIX",+ bytes: &AES_TD1_PREFIX,+ },+ Pattern {+ algorithm: "AES",+ constant: "TD2_PREFIX",+ bytes: &AES_TD2_PREFIX,+ },+ Pattern {+ algorithm: "AES",+ constant: "TD3_PREFIX",+ bytes: &AES_TD3_PREFIX,+ },+ Pattern {+ algorithm: "TEA",+ constant: "DELTA",+ bytes: &TEA_DELTA,+ },+ Pattern {+ algorithm: "MD5",+ constant: "INIT",+ bytes: &MD5_INIT,+ },+ Pattern {+ algorithm: "SHA1",+ constant: "INIT",+ bytes: &SHA1_INIT,+ },+ Pattern {+ algorithm: "SHA256",+ constant: "K_PREFIX",+ bytes: &SHA256_K_PREFIX,+ },+ Pattern {+ algorithm: "ChaCha20",+ constant: "SIGMA",+ bytes: CHACHA_SIGMA,+ },+ Pattern {+ algorithm: "Salsa20",+ constant: "TAU",+ bytes: SALSA_TAU,+ },+ Pattern {+ algorithm: "Blowfish",+ constant: "P_PREFIX",+ bytes: &BLOWFISH_P_PREFIX,+ },+ Pattern {+ algorithm: "Blowfish",+ constant: "S0_PREFIX",+ bytes: &BLOWFISH_S0_PREFIX,+ },+ Pattern {+ algorithm: "Blowfish",+ constant: "S1_PREFIX",+ bytes: &BLOWFISH_S1_PREFIX,+ },+ Pattern {+ algorithm: "CRC32",+ constant: "TAB_PREFIX",+ bytes: &CRC32_TAB_PREFIX,+ },+ Pattern {+ algorithm: "RC5",+ constant: "PQ",+ bytes: &RC5_PQ,+ },+ Pattern {+ algorithm: "DES",+ constant: "S1_ROW0",+ bytes: &DES_S1_ROW0,+ },+ Pattern {+ algorithm: "DES",+ constant: "IP",+ bytes: &DES_IP,+ },+ Pattern {+ algorithm: "SHA512",+ constant: "INIT",+ bytes: &SHA512_INIT,+ },+ Pattern {+ algorithm: "SHA512",+ constant: "K_PREFIX",+ bytes: &SHA512_K_PREFIX,+ },+ Pattern {+ algorithm: "MD2",+ constant: "S_PREFIX",+ bytes: &MD2_S_PREFIX,+ },+ Pattern {+ algorithm: "Twofish",+ constant: "Q0_PREFIX",+ bytes: &TWOFISH_Q0_PREFIX,+ },+ Pattern {+ algorithm: "Camellia",+ constant: "SIGMA0",+ bytes: &CAMELLIA_SIGMA0,+ },+ Pattern {+ algorithm: "Camellia",+ constant: "SBOX1_PREFIX",+ bytes: &CAMELLIA_SBOX1_PREFIX,+ },+ Pattern {+ algorithm: "Camellia",+ constant: "SIGMA",+ bytes: &CAMELLIA_SIGMA,+ },+ Pattern {+ algorithm: "SM4",+ constant: "SBOX_PREFIX",+ bytes: &SM4_SBOX_PREFIX,+ },+ Pattern {+ algorithm: "SM4",+ constant: "FK",+ bytes: &SM4_FK,+ },+ Pattern {+ algorithm: "SM4",+ constant: "CK_PREFIX",+ bytes: &SM4_CK_PREFIX,+ },+ Pattern {+ algorithm: "Skipjack",+ constant: "FTABLE_PREFIX",+ bytes: &SKIPJACK_FTABLE_PREFIX,+ },+ Pattern {+ algorithm: "zlib",+ constant: "LEN_BASE_PREFIX",+ bytes: &ZLIB_LEN_BASE_PREFIX,+ },+ ]+}++/// Scan all memory blocks for cryptographic constant tables.+pub fn scan_crypt_constants(prog: &Program) -> Vec<CryptConstantHit> {+ let mut hits = Vec::new();+ for block in &prog.blocks {+ let data = &block.bytes;+ for pat in patterns() {+ if pat.bytes.len() < 4 {+ continue;+ }+ let mut start = 0usize;+ while let Some(rel) = find_subslice(&data[start..], pat.bytes) {+ let off = start + rel;+ hits.push(CryptConstantHit {+ va: block.va + off as u64,+ algorithm: pat.algorithm.into(),+ constant: pat.constant.into(),+ size: pat.bytes.len(),+ });+ start = off + 1;+ if hits.len() >= 10_000 {+ return hits;+ }+ }+ }+ }+ hits+}++fn find_subslice(hay: &[u8], needle: &[u8]) -> Option<usize> {+ if needle.is_empty() || hay.len() < needle.len() {+ return None;+ }+ hay.windows(needle.len()).position(|w| w == needle)+}++pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {+ let hits = scan_crypt_constants(prog);+ let n = hits.len();+ prog.analysis.crypt_constants = hits.clone();+ // Annotate symbols, EOL comments, and xrefs from code → constant (seed Phase 2/4).+ for h in &hits {+ let name = format!("CRYPT_{}_{}", h.algorithm, h.constant);+ if !prog+ .analysis+ .symbols+ .iter()+ .any(|s| s.va == h.va && s.name == name)+ {+ prog.analysis.symbols.push(crate::program::SymbolInfo {+ va: h.va,+ name,+ demangled: None,+ });+ }+ let comment = format!("CRYPT {} {} ({} bytes)", h.algorithm, h.constant, h.size);+ prog.edits.set_comment(h.va, CommentKind::Eol, comment);+ for xref in crate::xrefs::xrefs_to(prog, h.va, None) {+ let exists = prog+ .analysis+ .references+ .iter()+ .any(|r| r.from == xref.from && r.to == xref.to && r.kind == "crypt_const");+ if !exists {+ prog.analysis.references.push(ReferenceInfo {+ from: xref.from,+ to: xref.to,+ kind: "crypt_const".into(),+ });+ }+ }+ }+ Ok(AnalyzerOutput {+ name: "Find Crypt".into(),+ status: "ok".into(),+ message: format!("found {n} cryptographic constant hit(s)"),+ crypt_constants: Some(hits),+ ..Default::default()+ })+}++/// Function / site VAs that reference cryptographic constants (decoder seeds).+pub fn crypt_xref_seed_vas(prog: &Program) -> Vec<u64> {+ let mut out: Vec<u64> = prog+ .analysis+ .references+ .iter()+ .filter(|r| r.kind == "crypt_const")+ .map(|r| r.from)+ .collect();+ out.sort_unstable();+ out.dedup();+ out+}++/// Public AES S-box for recipe decrypt.+pub fn aes_sbox() -> &'static [u8; 256] {+ &AES_SBOX+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::program::{MemoryBlock, Program};++ #[test]+ fn finds_aes_sbox_in_block() {+ let mut prog = Program::new("t".into(), "raw");+ let mut bytes = vec![0u8; 32];+ bytes.extend_from_slice(&AES_SBOX);+ prog.blocks.push(MemoryBlock {+ name: ".rdata".into(),+ va: 0x1000,+ size: bytes.len() as u64,+ bytes,+ readable: true,+ writable: false,+ executable: false,+ });+ let hits = scan_crypt_constants(&prog);+ assert!(hits+ .iter()+ .any(|h| h.algorithm == "AES" && h.constant == "SBOX"));+ assert_eq!(+ hits.iter().find(|h| h.constant == "SBOX").unwrap().va,+ 0x1020+ );+ }++ #[test]+ fn finds_tea_delta_and_new_algorithm_tables() {+ let mut prog = Program::new("t".into(), "raw");+ let mut bytes = Vec::new();+ bytes.extend_from_slice(&TEA_DELTA);+ bytes.extend_from_slice(&[0u8; 7]);+ bytes.extend_from_slice(&SHA512_K_PREFIX);+ bytes.extend_from_slice(&[0u8; 11]);+ bytes.extend_from_slice(&TWOFISH_Q0_PREFIX);+ bytes.extend_from_slice(&[0u8; 13]);+ bytes.extend_from_slice(&SM4_FK);+ prog.blocks.push(MemoryBlock {+ name: ".rdata".into(),+ va: 0x2000,+ size: bytes.len() as u64,+ bytes,+ readable: true,+ writable: false,+ executable: false,+ });++ let hits = scan_crypt_constants(&prog);+ assert!(hits+ .iter()+ .any(|h| h.algorithm == "TEA" && h.constant == "DELTA"));+ assert!(hits+ .iter()+ .any(|h| h.algorithm == "SHA512" && h.constant == "K_PREFIX"));+ assert!(hits+ .iter()+ .any(|h| h.algorithm == "Twofish" && h.constant == "Q0_PREFIX"));+ assert!(hits+ .iter()+ .any(|h| h.algorithm == "SM4" && h.constant == "FK"));+ }+}diff --git a/crates/ghidrust-core/src/analyzers/crypto_capabilities.rs b/crates/ghidrust-core/src/analyzers/crypto_capabilities.rsnew file mode 100644index 0000000..49259e1--- /dev/null+++ b/crates/ghidrust-core/src/analyzers/crypto_capabilities.rs@@ -0,0 +1,620 @@+//! Locate encrypt/decrypt and encoding capabilities via imports, constants, and code idioms.++use super::AnalyzerOutput;+use crate::error::Result;+use crate::program::Program;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+pub struct CryptoCapabilityHit {+ pub function_va: Option<u64>,+ pub capability: String,+ pub tag: String,+ pub evidence: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub attack: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub mbc: Option<String>,+}++const DECRYPT_APIS: &[&str] = &[+ "CryptDecrypt",+ "BCryptDecrypt",+ "NCryptDecrypt",+ "CryptUnprotectData",+ "CryptUnprotectMemory",+ "SystemFunction041",+ "DecryptMessage",+];++const ENCRYPT_APIS: &[&str] = &[+ "CryptEncrypt",+ "BCryptEncrypt",+ "NCryptEncrypt",+ "CryptProtectData",+ "CryptProtectMemory",+ "SystemFunction040",+ "EncryptMessage",+ "CryptAcquireContextA",+ "CryptAcquireContextW",+ "CryptGenKey",+ "CryptDeriveKey",+ "CryptImportKey",+];++const OPENSSL_DECRYPT_APIS: &[&str] = &[+ "EVP_DecryptInit",+ "EVP_DecryptInit_ex",+ "EVP_DecryptUpdate",+ "EVP_DecryptFinal_ex",+ "EVP_PKEY_decrypt",+ "AES_decrypt",+ "RSA_private_decrypt",+ "RSA_public_decrypt",+];++const OPENSSL_ENCRYPT_APIS: &[&str] = &[+ "EVP_EncryptInit",+ "EVP_EncryptInit_ex",+ "EVP_EncryptUpdate",+ "EVP_EncryptFinal_ex",+ "EVP_PKEY_encrypt",+ "AES_encrypt",+ "RSA_public_encrypt",+ "RSA_private_encrypt",+ "RC4",+];++const ENCODING_APIS: &[&str] = &[+ "CryptBinaryToStringA",+ "CryptBinaryToStringW",+ "CryptStringToBinaryA",+ "CryptStringToBinaryW",+];++/// WinCrypt CALG_* values commonly embedded next to CryptDecrypt/Encrypt call sites.+const CALG_MARKERS: &[(u32, &str)] = &[+ (0x0000_6610, "CALG_AES_128"),+ (0x0000_6611, "CALG_AES_192"),+ (0x0000_6612, "CALG_AES_256"),+ (0x0000_6603, "CALG_3DES"),+ (0x0000_6601, "CALG_DES"),+ (0x0000_6801, "CALG_RC4"),+ (0x0000_a400, "CALG_RSA_KEYX"),+ (0x0000_2400, "CALG_RSA_SIGN"),+ (0x0000_8003, "CALG_MD5"),+ (0x0000_8004, "CALG_SHA1"),+ (0x0000_800c, "CALG_SHA_256"),+];++/// Standard Base64 alphabet (ASCII) — presence suggests in-binary encoder/decoder.+const BASE64_ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";++const PACKER_MARKERS: &[&[u8]] = &[b"UPX0", b"UPX1", b"UPX!", b"Themida", b"VMProtect"];++fn tag_allowed(tag_filter: Option<&str>, tag: &str) -> bool {+ tag_filter+ .map(|filter| filter.eq_ignore_ascii_case(tag))+ .unwrap_or(true)+}++fn has_calg_rsa(prog: &Program) -> bool {+ prog.exec_blocks().any(|block| {+ block.bytes.windows(4).any(|window| {+ let value = u32::from_le_bytes([window[0], window[1], window[2], window[3]]);+ matches!(value, 0x0000_a400 | 0x0000_2400)+ })+ })+}++fn import_capability(+ name: &str,+ has_rsa_calg: bool,+) -> Option<(+ &'static str,+ &'static str,+ Option<&'static str>,+ Option<&'static str>,+)> {+ if DECRYPT_APIS+ .iter()+ .any(|api| name.eq_ignore_ascii_case(api))+ || OPENSSL_DECRYPT_APIS+ .iter()+ .any(|api| name.eq_ignore_ascii_case(api))+ {+ let capability = if name.eq_ignore_ascii_case("CryptDecrypt") && has_rsa_calg {+ "RSA decrypt via CryptDecrypt with CALG_RSA*"+ } else if name.to_ascii_uppercase().contains("RSA") {+ "RSA decrypt"+ } else {+ "decrypt"+ };+ return Some((capability, "decrypt", Some("T1027"), Some("C0031")));+ }+ if ENCRYPT_APIS+ .iter()+ .any(|api| name.eq_ignore_ascii_case(api))+ || OPENSSL_ENCRYPT_APIS+ .iter()+ .any(|api| name.eq_ignore_ascii_case(api))+ {+ let capability = if name.to_ascii_uppercase().contains("RSA") {+ "RSA encrypt"+ } else {+ "encrypt"+ };+ return Some((capability, "encrypt", Some("T1027"), Some("C0027")));+ }+ if ENCODING_APIS+ .iter()+ .any(|api| name.eq_ignore_ascii_case(api))+ {+ return Some(("encode/decode", "encoding", Some("T1027"), None));+ }+ if name.eq_ignore_ascii_case("SystemFunction032")+ || name.eq_ignore_ascii_case("SystemFunction033")+ {+ return Some(("RC4", "encrypt", Some("T1027"), Some("C0027")));+ }+ if (name.starts_with("BCrypt") || name.starts_with("NCrypt"))+ && name.to_ascii_uppercase().contains("RSA")+ {+ return Some((+ "RSA-related cryptographic operation",+ "encrypt",+ Some("T1027"),+ None,+ ));+ }+ None+}++/// Scan imports + prior analysis for crypto/encoding capabilities.+pub fn scan_crypto_capabilities(+ prog: &Program,+ tag_filter: Option<&str>,+) -> Vec<CryptoCapabilityHit> {+ let mut hits = Vec::new();+ let has_rsa_calg = has_calg_rsa(prog);++ for imp in &prog.imports {+ let Some(ref name_s) = imp.name else {+ continue;+ };+ let name = name_s.as_str();+ let dll = imp.dll.as_str();+ let Some((capability, tag, attack, mbc)) = import_capability(name, has_rsa_calg) else {+ continue;+ };+ if !tag_allowed(tag_filter, tag) {+ continue;+ }+ hits.push(CryptoCapabilityHit {+ function_va: Some(imp.iat_va),+ capability: format!("{capability} via {name}"),+ tag: tag.into(),+ evidence: format!("import {dll}!{name}"),+ attack: attack.map(str::to_string),+ mbc: mbc.map(str::to_string),+ });+ }++ // TEA/XTEA commonly combines the delta with repeated shifts and XORs in one loop body.+ for block in prog.exec_blocks() {+ let bytes = &block.bytes;+ let has_delta = bytes+ .windows(4)+ .any(|window| window == [0xb9, 0x79, 0x37, 0x9e]);+ let shifts = bytes+ .windows(2)+ .filter(|window| {+ matches!(+ *window,+ [0xc1, 0xe0..=0xe7] | [0xd1, 0xe0..=0xe7] | [0xc1, 0xf8..=0xff]+ )+ })+ .count();+ let xors = bytes+ .windows(2)+ .filter(|window| {+ matches!(window[0], 0x30..=0x35) || window[0] == 0x31 || window[0] == 0x33+ })+ .count();+ if has_delta && shifts >= 2 && xors >= 2 && tag_allowed(tag_filter, "encrypt") {+ hits.push(CryptoCapabilityHit {+ function_va: Some(block.va),+ capability: "TEA/XTEA loop idiom".into(),+ tag: "encrypt".into(),+ evidence: format!(+ "TEA delta, {shifts} shifts, and {xors} XORs in {}",+ block.name+ ),+ attack: Some("T1027".into()),+ mbc: Some("C0027".into()),+ });+ }+ }++ // AES-NI idiom: 66 0F 38 DC (aesenc) / 66 0F 38 DE (aesenclast) / 66 0F 38 DF (aesdeclast)+ for block in prog.exec_blocks() {+ let b = &block.bytes;+ for (i, w) in b.windows(4).enumerate() {+ let is_aes = matches!(+ w,+ [0x66, 0x0F, 0x38, 0xDC]+ | [0x66, 0x0F, 0x38, 0xDD]+ | [0x66, 0x0F, 0x38, 0xDE]+ | [0x66, 0x0F, 0x38, 0xDF]+ | [0x66, 0x0F, 0x38, 0xDB]+ );+ if !is_aes {+ continue;+ }+ if tag_filter+ .map(|t| !t.eq_ignore_ascii_case("decrypt") && !t.eq_ignore_ascii_case("encrypt"))+ .unwrap_or(false)+ {+ continue;+ }+ let va = block.va + i as u64;+ let decryptish = w[3] == 0xDF || w[3] == 0xDB;+ hits.push(CryptoCapabilityHit {+ function_va: Some(va),+ capability: if decryptish {+ "AES via x86 extensions (decrypt-ish)".into()+ } else {+ "AES via x86 extensions".into()+ },+ tag: if decryptish {+ "decrypt".into()+ } else {+ "encrypt".into()+ },+ evidence: format!("opcode @ {va:#x}"),+ attack: Some("T1027".into()),+ mbc: Some(if decryptish {+ "C0031".into()+ } else {+ "C0027".into()+ }),+ });+ }+ }++ // Seed from Find Crypt hits already on the program.+ for c in &prog.analysis.crypt_constants {+ let tag = if c.algorithm == "MD5" || c.algorithm == "SHA256" || c.algorithm == "CRC32" {+ "hashing"+ } else {+ "encrypt"+ };+ if let Some(f) = tag_filter {+ if !tag.eq_ignore_ascii_case(f) && !f.eq_ignore_ascii_case("encrypt") {+ continue;+ }+ }+ hits.push(CryptoCapabilityHit {+ function_va: Some(c.va),+ capability: format!("{} constants present", c.algorithm),+ tag: tag.into(),+ evidence: format!("{} @ {:#x}", c.constant, c.va),+ attack: Some("T1027".into()),+ mbc: Some("C0027".into()),+ });+ }++ // RC4 KSA/PRGA implementations typically initialize a 256-byte state and perform+ // several byte XORs/modulo-256 operations in the same code block.+ for block in prog.exec_blocks() {+ let bytes = &block.bytes;+ let has_256 = bytes+ .windows(4)+ .any(|window| window == [0x00, 0x01, 0x00, 0x00]);+ let xor_count = bytes+ .windows(2)+ .filter(|window| {+ matches!(window[0], 0x30..=0x35) || window[0] == 0x31 || window[0] == 0x33+ })+ .count();+ let has_mod_256 = bytes+ .windows(5)+ .any(|window| window == [0x25, 0xff, 0x00, 0x00, 0x00]);+ if has_256 && has_mod_256 && xor_count >= 3 && tag_allowed(tag_filter, "encrypt") {+ hits.push(CryptoCapabilityHit {+ function_va: Some(block.va),+ capability: "RC4 KSA/PRGA-like loop idiom".into(),+ tag: "encrypt".into(),+ evidence: format!(+ "256-byte state, modulo-256 mask, and {xor_count} XORs in {}",+ block.name+ ),+ attack: Some("T1027".into()),+ mbc: Some("C0027".into()),+ });+ }+ }++ // Stackstring presence from prior obfuscated-string recovery.+ if prog.analysis.obfuscated_strings.iter().any(|s| {+ matches!(+ s.kind,+ super::obfuscated_strings::ObfuscatedStringKind::Stack+ )+ }) {+ if tag_filter+ .map(|t| t.eq_ignore_ascii_case("encoding") || t.eq_ignore_ascii_case("obfuscation"))+ .unwrap_or(true)+ {+ hits.push(CryptoCapabilityHit {+ function_va: None,+ capability: "contain obfuscated stackstrings".into(),+ tag: "encoding".into(),+ evidence: "obfuscated_strings analysis".into(),+ attack: Some("T1027".into()),+ mbc: None,+ });+ }+ }++ // CALG_* immediates in executable code.+ for block in prog.exec_blocks() {+ let b = &block.bytes;+ if b.len() < 5 {+ continue;+ }+ for (i, w) in b.windows(5).enumerate() {+ // mov eax, imm32 → B8 xx xx xx xx+ if w[0] != 0xB8 {+ continue;+ }+ let imm = u32::from_le_bytes([w[1], w[2], w[3], w[4]]);+ if let Some((_, name)) = CALG_MARKERS.iter().find(|(v, _)| *v == imm) {+ if tag_filter+ .map(|t| {+ t.eq_ignore_ascii_case("encrypt")+ || t.eq_ignore_ascii_case("decrypt")+ || t.eq_ignore_ascii_case("hashing")+ })+ .unwrap_or(true)+ {+ let va = block.va + i as u64;+ hits.push(CryptoCapabilityHit {+ function_va: Some(va),+ capability: format!("algorithm id {name}"),+ tag: if name.contains("MD5") || name.contains("SHA") {+ "hashing".into()+ } else {+ "encrypt".into()+ },+ evidence: format!("imm32 {imm:#x} @ {va:#x}"),+ attack: Some("T1027".into()),+ mbc: Some("C0027".into()),+ });+ }+ }+ }+ }++ // Base64 alphabet table in data.+ for block in &prog.blocks {+ if let Some(rel) = block+ .bytes+ .windows(BASE64_ALPHABET.len())+ .position(|w| w == BASE64_ALPHABET)+ {+ if tag_filter+ .map(|t| t.eq_ignore_ascii_case("encoding"))+ .unwrap_or(true)+ {+ let va = block.va + rel as u64;+ hits.push(CryptoCapabilityHit {+ function_va: Some(va),+ capability: "encode/decode via Base64 alphabet".into(),+ tag: "encoding".into(),+ evidence: format!("alphabet @ {va:#x}"),+ attack: Some("T1027".into()),+ mbc: None,+ });+ }+ break;+ }+ }++ // Dense XOR-imm density → custom encode/decode capability.+ for block in prog.exec_blocks() {+ let xor_imm = block+ .bytes+ .windows(2)+ .filter(|w| w[0] == 0x34 && w[1] != 0)+ .count();+ if xor_imm >= 8 {+ if tag_filter+ .map(|t| t.eq_ignore_ascii_case("encoding") || t.eq_ignore_ascii_case("encrypt"))+ .unwrap_or(true)+ {+ hits.push(CryptoCapabilityHit {+ function_va: Some(block.va),+ capability: "encode/decode via XOR loops".into(),+ tag: "encoding".into(),+ evidence: format!("{xor_imm} xor-imm sites in {}", block.name),+ attack: Some("T1027".into()),+ mbc: None,+ });+ }+ }+ }++ // P2 context only: these are literal image markers, not packer identification.+ for block in &prog.blocks {+ for marker in PACKER_MARKERS {+ if let Some(offset) = block+ .bytes+ .windows(marker.len())+ .position(|window| window == *marker)+ {+ if tag_allowed(tag_filter, "packing") {+ let va = block.va + offset as u64;+ hits.push(CryptoCapabilityHit {+ function_va: Some(va),+ capability: "packing context marker".into(),+ tag: "packing".into(),+ evidence: format!(+ "literal marker {} @ {va:#x}",+ String::from_utf8_lossy(marker)+ ),+ attack: Some("T1027".into()),+ mbc: None,+ });+ }+ break;+ }+ }+ }++ hits+}++/// Suggest bake op names from a capability hit (feeds Phase 3).+pub fn suggest_ops_for_capability(hit: &CryptoCapabilityHit) -> Vec<&'static str> {+ let c = hit.capability.to_ascii_lowercase();+ if c.contains("aes") || c.contains("calg_aes") {+ return vec!["AESDecrypt"];+ }+ if c.contains("rc4") || c.contains("calg_rc4") || c.contains("systemfunction032") {+ return vec!["RC4"];+ }+ if c.contains("base64") && (c.contains("gzip") || c.contains("gunzip")) {+ return vec!["FromBase64", "Gunzip"];+ }+ if c.contains("base64") {+ return vec!["FromBase64"];+ }+ if c.contains("tea") || c.contains("chacha") || c.contains("blowfish") || c.contains("des") {+ return vec!["XORBrute"];+ }+ // RSA and DPAPI require a private key or host-bound credential; no bake operation is honest.+ if c.contains("rsa") || c.contains("dpapi") || c.contains("cryptunprotect") {+ return Vec::new();+ }+ if c.contains("xor") {+ return vec!["XORBrute"];+ }+ if hit.tag == "decrypt" {+ return vec!["AESDecrypt", "RC4", "XORBrute"];+ }+ vec!["FromBase64", "XORBrute"]+}++pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {+ let hits = scan_crypto_capabilities(prog, None);+ let n = hits.len();+ prog.analysis.crypto_capabilities = hits.clone();+ Ok(AnalyzerOutput {+ name: "Crypto Capabilities".into(),+ status: "ok".into(),+ message: format!("matched {n} crypto/encoding capability hit(s)"),+ crypto_capabilities: Some(hits),+ ..Default::default()+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::analyzers::obfuscated_strings::{ObfuscatedStringHit, ObfuscatedStringKind};+ use crate::program::{ImportEntry, MemoryBlock};++ fn block(name: &str, va: u64, bytes: Vec<u8>, executable: bool) -> MemoryBlock {+ MemoryBlock {+ name: name.into(),+ va,+ size: bytes.len() as u64,+ bytes,+ readable: true,+ writable: false,+ executable,+ }+ }++ #[test]+ fn detects_cryptdecrypt_import() {+ let mut prog = Program::new("t".into(), "raw");+ prog.imports.push(ImportEntry {+ dll: "advapi32.dll".into(),+ name: Some("CryptDecrypt".into()),+ ordinal: None,+ iat_va: 0x401000,+ ilt_va: None,+ });+ let hits = scan_crypto_capabilities(&prog, None);+ assert!(hits+ .iter()+ .any(|hit| hit.tag == "decrypt" && hit.evidence.contains("CryptDecrypt")));+ }++ #[test]+ fn detects_aes_ni_opcode() {+ let mut prog = Program::new("t".into(), "raw");+ prog.blocks+ .push(block(".text", 0x401000, vec![0x66, 0x0f, 0x38, 0xdc], true));+ assert!(scan_crypto_capabilities(&prog, None)+ .iter()+ .any(|hit| hit.capability.contains("AES via x86")));+ }++ #[test]+ fn detects_base64_alphabet() {+ let mut prog = Program::new("t".into(), "raw");+ prog.blocks+ .push(block(".rdata", 0x402000, BASE64_ALPHABET.to_vec(), false));+ assert!(scan_crypto_capabilities(&prog, None)+ .iter()+ .any(|hit| hit.capability.contains("Base64")));+ }++ #[test]+ fn reports_stackstring_context() {+ let mut prog = Program::new("t".into(), "raw");+ prog.analysis.obfuscated_strings.push(ObfuscatedStringHit {+ va: 0x401000,+ value: "test".into(),+ kind: ObfuscatedStringKind::Stack,+ decoder_va: None,+ call_site: None,+ });+ assert!(scan_crypto_capabilities(&prog, None)+ .iter()+ .any(|hit| hit.capability.contains("stackstrings")));+ }++ #[test]+ fn detects_tea_rc4_calg_and_honors_tag_filter() {+ let mut prog = Program::new("idioms".into(), "raw");+ prog.blocks.push(block(+ ".text",+ 0x5000,+ vec![+ 0xb9, 0x79, 0x37, 0x9e, // TEA delta+ 0xc1, 0xe0, 0x04, 0xc1, 0xe1, 0x05, 0x31, 0xc0, 0x33, 0xc9,+ 0xb8, 0x01, 0x68, 0x00, 0x00, // CALG_RC4+ 0x00, 0x01, 0x00, 0x00, 0x25, 0xff, 0x00, 0x00, 0x00,+ 0x31, 0xc0, 0x33, 0xc9, 0x34, 0x12,+ ],+ true,+ ));+ let hits = scan_crypto_capabilities(&prog, Some("encrypt"));+ assert!(hits.iter().any(|hit| hit.capability.contains("TEA/XTEA")), "{hits:?}");+ assert!(hits.iter().any(|hit| hit.capability.contains("RC4 KSA/PRGA")), "{hits:?}");+ assert!(+ hits.iter().any(|hit| hit.capability.contains("CALG_RC4")),+ "{hits:?}"+ );+ assert!(hits.iter().all(|hit| hit.tag == "encrypt"));+ let rc4 = hits+ .iter()+ .find(|hit| hit.capability.contains("RC4"))+ .expect("RC4 capability");+ assert_eq!(suggest_ops_for_capability(rc4), vec!["RC4"]);+ }+}diff --git a/crates/ghidrust-core/src/analyzers/external_params.rs b/crates/ghidrust-core/src/analyzers/external_params.rsindex cabbf17..89d2b39 100644--- a/crates/ghidrust-core/src/analyzers/external_params.rs+++ b/crates/ghidrust-core/src/analyzers/external_params.rs@@ -6,7 +6,10 @@ use crate::program::Program;fn prototypes() -> &'static [(&'static str, &'static str)] {&[("ExitProcess", "UINT uExitCode"),- ("CreateFileW", "LPCWSTR,DWORD,DWORD,LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE"),+ (+ "CreateFileW",+ "LPCWSTR,DWORD,DWORD,LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE",+ ),("printf", "const char *format, ..."),("MyFunc", "void"),("?MyFunc@@YAXXZ", "void"),diff --git a/crates/ghidrust-core/src/analyzers/fid.rs b/crates/ghidrust-core/src/analyzers/fid.rsindex 76cacf5..542684e 100644--- a/crates/ghidrust-core/src/analyzers/fid.rs+++ b/crates/ghidrust-core/src/analyzers/fid.rs@@ -7,9 +7,18 @@ use crate::program::{FidMatch, Program};/// Fixture corpus: hash of known prologues.fn corpus() -> Vec<([u8; 8], &'static str)> {vec![- ([0x55, 0x48, 0x89, 0xE5, 0x31, 0xC0, 0x5D, 0xC3], "fid_prolog_xor_ret"),- ([0x55, 0x48, 0x89, 0xE5, 0x48, 0x83, 0xEC, 0x20], "fid_frame_sub20"),- ([0x48, 0x83, 0xEC, 0x28, 0xFF, 0x15, 0x00, 0x00], "fid_sub28_call"),+ (+ [0x55, 0x48, 0x89, 0xE5, 0x31, 0xC0, 0x5D, 0xC3],+ "fid_prolog_xor_ret",+ ),+ (+ [0x55, 0x48, 0x89, 0xE5, 0x48, 0x83, 0xEC, 0x20],+ "fid_frame_sub20",+ ),+ (+ [0x48, 0x83, 0xEC, 0x28, 0xFF, 0x15, 0x00, 0x00],+ "fid_sub28_call",+ ),]}diff --git a/crates/ghidrust-core/src/analyzers/function_start.rs b/crates/ghidrust-core/src/analyzers/function_start.rsindex 2e4a8b4..50200db 100644--- a/crates/ghidrust-core/src/analyzers/function_start.rs+++ b/crates/ghidrust-core/src/analyzers/function_start.rs@@ -13,12 +13,7 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {// 1) PE Exception Directory — authoritative begins/ends (mandatory PE64 pass).let runtime: Vec<RuntimeFunction> = parse_runtime_functions(prog);for rf in &runtime {- seeds.push((- rf.begin_va,- FunctionSeedKind::Pdata,- Some(rf.end_va),- None,- ));+ seeds.push((rf.begin_va, FunctionSeedKind::Pdata, Some(rf.end_va), None));}// 2) PE exports that land in executable memory.@@ -43,14 +38,8 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {{continue;}- if s.name.starts_with("FUN_") || s.name.starts_with("Lab") || s.name.starts_with("synth_")- {- seeds.push((- s.va,- FunctionSeedKind::Prologue,- None,- Some(s.name.clone()),- ));+ if s.name.starts_with("FUN_") || s.name.starts_with("Lab") || s.name.starts_with("synth_") {+ seeds.push((s.va, FunctionSeedKind::Prologue, None, Some(s.name.clone())));}}@@ -82,7 +71,8 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {// Prefer pdata / export over weaker seeds at the same VA.seeds.sort_by(|(a, ka, _, _), (b, kb, _, _)| {- a.cmp(b).then_with(|| seed_priority(ka).cmp(&seed_priority(kb)))+ a.cmp(b)+ .then_with(|| seed_priority(ka).cmp(&seed_priority(kb)))});let mut merged: Vec<(u64, FunctionSeedKind, Option<u64>, Option<String>)> = Vec::new();for (va, kind, pdata_end, name) in seeds {@@ -157,7 +147,9 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {Ok(AnalyzerOutput {name: "Function Start Search".into(),status: "ok".into(),- message: format!("identified {n} function start(s) ({pdata_n} from PE Exception Directory)"),+ message: format!(+ "identified {n} function start(s) ({pdata_n} from PE Exception Directory)"+ ),functions: Some(functions),..Default::default()})diff --git a/crates/ghidrust-core/src/analyzers/mod.rs b/crates/ghidrust-core/src/analyzers/mod.rsindex f3ba227..81b8b66 100644--- a/crates/ghidrust-core/src/analyzers/mod.rs+++ b/crates/ghidrust-core/src/analyzers/mod.rs@@ -4,14 +4,17 @@ mod address_tables;mod aggressive;mod call_convention;mod call_fixup;-mod demangle_ms;+pub mod crypt_constants;+pub mod crypto_capabilities;mod decomp_param;mod decomp_switch;+mod demangle_ms;mod embedded_media;mod external_params;mod fid;mod function_start;mod noreturn;+pub mod obfuscated_strings;mod pdb;mod resources;mod scan_util;@@ -25,6 +28,14 @@ use crate::program::Program;use crate::rtti::{recover_rtti, RttiReport};use serde::Serialize;+pub use crypt_constants::{crypt_xref_seed_vas, scan_crypt_constants, CryptConstantHit};+pub use crypto_capabilities::{+ scan_crypto_capabilities, suggest_ops_for_capability, CryptoCapabilityHit,+};+pub use obfuscated_strings::{+ decoder_seed_vas, recover_obfuscated_strings, ObfuscatedStringHit, ObfuscatedStringKind,+ RecoverStringsOpts,+};pub use strings::{collect_strings, collect_strings_bytes, collect_strings_opts, scan_ascii_strings,scan_utf16le_strings, FoundString, StringCollectOpts, StringMatchMode,@@ -38,13 +49,16 @@ pub const ANALYZER_NAMES: &[&str] = &["Call Convention ID","Call-Fixup Installer","Create Address Tables",+ "Crypto Capabilities","Decompiler Parameter ID","Decompiler Switch Analysis","Demangler Microsoft","Embedded Media",+ "Find Crypt","Function ID","Function Start Search","Non-Returning Functions - Discovered",+ "Obfuscated Strings","PDB MSDIA","PDB Universal","Shared Return Calls",@@ -108,6 +122,12 @@ pub struct AnalyzerOutput {pub varargs_entries: Option<Vec<u64>>,#[serde(skip_serializing_if = "Option::is_none")]pub external_params: Option<Vec<(u64, String)>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub crypt_constants: Option<Vec<CryptConstantHit>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub obfuscated_strings: Option<Vec<ObfuscatedStringHit>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub crypto_capabilities: Option<Vec<CryptoCapabilityHit>>,}#[derive(Debug, Clone, Default, Serialize)]@@ -130,6 +150,7 @@ pub fn analyzer_catalog() -> Vec<AnalyzerInfo> {| "Create Address Tables"| "Embedded Media"| "Demangler Microsoft"+ | "Find Crypt"),status: AnalyzerStatus::Implemented,})@@ -214,13 +235,16 @@ fn run_one(prog: &mut Program, name: &str) -> Result<AnalyzerOutput> {"Call Convention ID" => call_convention::run(prog),"Call-Fixup Installer" => call_fixup::run(prog),"Create Address Tables" => address_tables::run(prog),+ "Crypto Capabilities" => crypto_capabilities::run(prog),"Decompiler Parameter ID" => decomp_param::run(prog),"Decompiler Switch Analysis" => decomp_switch::run(prog),"Demangler Microsoft" => demangle_ms::run(prog),"Embedded Media" => embedded_media::run(prog),+ "Find Crypt" => crypt_constants::run(prog),"Function ID" => fid::run(prog),"Function Start Search" => function_start::run(prog),"Non-Returning Functions - Discovered" => noreturn::run(prog),+ "Obfuscated Strings" => obfuscated_strings::run(prog),"PDB MSDIA" => pdb::run_msdia(prog),"PDB Universal" => pdb::run_universal(prog),"Shared Return Calls" => shared_return::run(prog),@@ -257,10 +281,8 @@ mod tests {#[test]fn catalog_all_implemented() {let cat = analyzer_catalog();- assert_eq!(cat.len(), 21);- assert!(cat- .iter()- .all(|c| c.status == AnalyzerStatus::Implemented));+ assert_eq!(cat.len(), 24);+ assert!(cat.iter().all(|c| c.status == AnalyzerStatus::Implemented));}#[test]@@ -288,10 +310,7 @@ mod tests {r.message);}- let with_gpu = rep- .results- .iter()- .any(|r| r.message.contains("gpu_enrich"));+ let with_gpu = rep.results.iter().any(|r| r.message.contains("gpu_enrich"));assert!(with_gpu,"expected gpu_enrich annotation in messages: {:?}",diff --git a/crates/ghidrust-core/src/analyzers/obfuscated_strings.rs b/crates/ghidrust-core/src/analyzers/obfuscated_strings.rsnew file mode 100644index 0000000..0bdcb5e--- /dev/null+++ b/crates/ghidrust-core/src/analyzers/obfuscated_strings.rs@@ -0,0 +1,770 @@+//! Recover stack-built and lightly obfuscated strings from code blocks.++use super::AnalyzerOutput;+use crate::error::Result;+use crate::program::Program;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum ObfuscatedStringKind {+ Stack,+ Tight,+ Decoded,+ StaticHint,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+pub struct ObfuscatedStringHit {+ pub va: u64,+ pub value: String,+ pub kind: ObfuscatedStringKind,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub decoder_va: Option<u64>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub call_site: Option<u64>,+}++#[derive(Debug, Clone, Default)]+pub struct RecoverStringsOpts {+ pub only: Option<Vec<String>>,+ pub no: Option<Vec<String>>,+ pub functions: Option<Vec<u64>>,+ pub limit: Option<usize>,+}++fn kind_allowed(kind: &ObfuscatedStringKind, opts: &RecoverStringsOpts) -> bool {+ let name = match kind {+ ObfuscatedStringKind::Stack => "stack",+ ObfuscatedStringKind::Tight => "tight",+ ObfuscatedStringKind::Decoded => "decoded",+ ObfuscatedStringKind::StaticHint => "static",+ };+ if let Some(only) = &opts.only {+ if !only.is_empty() && !only.iter().any(|k| k.eq_ignore_ascii_case(name)) {+ return false;+ }+ }+ if let Some(no) = &opts.no {+ if no.iter().any(|k| k.eq_ignore_ascii_case(name)) {+ return false;+ }+ }+ true+}++fn is_printable_ascii(b: u8) -> bool {+ (0x20..=0x7e).contains(&b)+}++/// Decoder-site seeds from Find Crypt xrefs + Crypto Capabilities decrypt/encoding hits.+pub fn decoder_seed_vas(prog: &Program) -> Vec<u64> {+ let mut seeds = super::crypt_constants::crypt_xref_seed_vas(prog);+ for c in &prog.analysis.crypto_capabilities {+ if matches!(c.tag.as_str(), "decrypt" | "encoding") {+ if let Some(va) = c.function_va {+ seeds.push(va);+ }+ }+ }+ seeds.sort_unstable();+ seeds.dedup();+ seeds+}++const MAX_EMU_STEPS: usize = 10_000;+const MAX_WINDOW: usize = 512;++fn at_limit(hits: &[ObfuscatedStringHit], opts: &RecoverStringsOpts) -> bool {+ opts.limit.is_some_and(|limit| hits.len() >= limit)+}++/// A cheap pre-filter for byte-oriented decoder bodies. It deliberately requires both a+/// non-zero transform and stores, so ordinary tiny thunks and zeroing loops are skipped.+fn decoder_score(bytes: &[u8]) -> u8 {+ if bytes.len() < 12 || bytes.len() > MAX_WINDOW {+ return 0;+ }+ let mut transforms = 0u8;+ let mut stores = 0u8;+ let mut rotates = 0u8;+ for window in bytes.windows(3) {+ match window {+ [0x34 | 0x32 | 0x30, key, ..] if *key != 0 => transforms += 2,+ [0x04 | 0x2c, key, ..] if *key != 0 => transforms += 2,+ [0x80, modrm, key] if (*modrm & 0x38) != 0x38 && *key != 0 => transforms += 1,+ [0xc0 | 0xc1, modrm, count] if (*modrm & 0x38) == 0 && *count != 0 => rotates += 1,+ [0x88 | 0x89 | 0xc6, ..] => stores += 1,+ _ => {}+ }+ }+ transforms.saturating_add(rotates).min(4) + stores.min(3)+}++/// Recover obfuscated strings from executable mappings. This intentionally scans executable+/// raw images even when no section/function metadata exists.+pub fn recover_obfuscated_strings(+ prog: &Program,+ opts: &RecoverStringsOpts,+) -> Vec<ObfuscatedStringHit> {+ let mut hits = Vec::new();+ let mut seeds = decoder_seed_vas(prog);+ if let Some(functions) = &opts.functions {+ seeds.extend(functions.iter().copied());+ }+ seeds.sort_unstable();+ seeds.dedup();++ if kind_allowed(&ObfuscatedStringKind::StaticHint, opts) && opts.functions.is_none() {+ recover_static_hints(prog, opts, &mut hits);+ }++ let mut blocks: Vec<_> = prog.exec_blocks().collect();+ blocks.sort_by_key(|block| {+ let seeded = seeds+ .iter()+ .any(|&seed| seed >= block.va && seed < block.va.saturating_add(block.size));+ !seeded+ });+ let mut emu_steps = 0usize;+ for block in blocks {+ if at_limit(&hits, opts) {+ continue;+ }+ let regions: Vec<(usize, usize)> =+ match opts.functions.as_ref().filter(|items| !items.is_empty()) {+ None => vec![(0, block.bytes.len())],+ Some(entries) => entries+ .iter()+ .filter_map(|&entry| {+ let (start_va, end_va) = match prog+ .analysis+ .functions+ .iter()+ .find(|function| function.entry == entry)+ {+ Some(function) => (function.entry, function.end),+ None if entry >= block.va+ && entry < block.va.saturating_add(block.size) =>+ {+ (block.va, block.va.saturating_add(block.bytes.len() as u64))+ }+ None => return None,+ };+ let start = start_va.saturating_sub(block.va) as usize;+ let end = end_va+ .saturating_sub(block.va)+ .min(block.bytes.len() as u64)+ as usize;+ (start < block.bytes.len() && start < end).then_some((start, end))+ })+ .collect(),+ };+ for (region_start, region_end) in regions {+ let region = &block.bytes[region_start..region_end];+ recover_stack_immediates(block.va + region_start as u64, region, opts, &mut hits);+ for start in (0..region.len()).step_by(32) {+ if at_limit(&hits, opts) || emu_steps >= MAX_EMU_STEPS {+ break;+ }+ let end = (start + MAX_WINDOW).min(region.len());+ let window = ®ion[start..end];+ if decoder_score(window) >= 4 {+ emu_steps += window.len().min(MAX_EMU_STEPS - emu_steps);+ emulate_stack_decoder(+ block.va + region_start as u64 + start as u64,+ window,+ opts,+ &mut hits,+ );+ }+ }+ // The bounded helpers cover immediate-inline decoder idioms that do not+ // have enough stack-store evidence for the tiny emulator above.+ recover_xor_decoded(block.va + region_start as u64, region, opts, &mut hits);+ recover_arith_decoded(block.va + region_start as u64, region, opts, &mut hits);+ }+ }+ hits.sort_by(|a, b| a.va.cmp(&b.va).then(a.value.cmp(&b.value)));+ hits.dedup_by(|a, b| a.va == b.va && a.value == b.value && a.kind == b.kind);+ if let Some(limit) = opts.limit {+ hits.truncate(limit);+ }+ hits+}++fn recover_static_hints(+ prog: &Program,+ opts: &RecoverStringsOpts,+ out: &mut Vec<ObfuscatedStringHit>,+) {+ for block in prog.blocks.iter().filter(|block| !block.executable) {+ let mut runs = Vec::new();+ let mut offset = 0;+ while offset < block.bytes.len() {+ let start = offset;+ while offset < block.bytes.len() && is_printable_ascii(block.bytes[offset]) {+ offset += 1;+ }+ if offset - start >= 6 {+ runs.push((start, offset - start));+ }+ offset += 1;+ }+ // A single printable run can be incidental data. Require a neighboring run to+ // identify a table-like region, then report only bytes actually present in memory.+ for &(start, len) in &runs {+ let table_like = runs+ .iter()+ .any(|&(other, _)| other != start && other.abs_diff(start) <= 128);+ if table_like && !at_limit(out, opts) {+ out.push(ObfuscatedStringHit {+ va: block.va + start as u64,+ value: String::from_utf8_lossy(&block.bytes[start..start + len]).into_owned(),+ kind: ObfuscatedStringKind::StaticHint,+ decoder_va: None,+ call_site: None,+ });+ }+ }+ // UTF-16LE-ish printable runs are independently useful when adjacent entries form+ // a table. Odd bytes must be zero to avoid fabricating text from arbitrary data.+ let mut utf16_runs = Vec::new();+ let mut offset = 0usize;+ while offset + 1 < block.bytes.len() {+ let start = offset;+ while offset + 1 < block.bytes.len()+ && is_printable_ascii(block.bytes[offset])+ && block.bytes[offset + 1] == 0+ {+ offset += 2;+ }+ if (offset - start) / 2 >= 4 {+ utf16_runs.push((start, offset));+ }+ offset += 2;+ }+ for &(start, end) in &utf16_runs {+ if utf16_runs+ .iter()+ .any(|&(other, _)| other != start && other.abs_diff(start) <= 160)+ && !at_limit(out, opts)+ {+ let value: String = (start..end)+ .step_by(2)+ .map(|p| block.bytes[p] as char)+ .collect();+ out.push(ObfuscatedStringHit {+ va: block.va + start as u64,+ value,+ kind: ObfuscatedStringKind::StaticHint,+ decoder_va: None,+ call_site: None,+ });+ }+ }+ }+}++/// Tiny, fail-closed byte emulator for stack-local decoder loops. It snapshots `C6` byte+/// stores, applies only recognized non-zero immediate transforms, and emits a string only+/// when the changed contiguous bytes are printable. No register or pointer speculation is+/// performed.+fn emulate_stack_decoder(+ base: u64,+ bytes: &[u8],+ opts: &RecoverStringsOpts,+ out: &mut Vec<ObfuscatedStringHit>,+) {+ if !kind_allowed(&ObfuscatedStringKind::Decoded, opts) {+ return;+ }+ let has_back_edge = bytes+ .windows(2)+ .any(|pair| pair[0] == 0xe2 || (pair[0] == 0xeb && (pair[1] as i8) < 0));+ if !has_back_edge {+ return;+ }+ let mut snapshot: std::collections::BTreeMap<i8, (u8, usize)> =+ std::collections::BTreeMap::new();+ let mut i = 0usize;+ while i + 3 < bytes.len() {+ if bytes[i..].starts_with(&[0xc6, 0x45]) {+ snapshot.insert(bytes[i + 2] as i8, (bytes[i + 3], i));+ i += 4;+ } else if i + 4 < bytes.len() && bytes[i..].starts_with(&[0xc6, 0x44, 0x24]) {+ snapshot.insert(bytes[i + 3] as i8, (bytes[i + 4], i));+ i += 5;+ } else {+ i += 1;+ }+ }+ if snapshot.len() < 4 {+ return;+ }+ let mut transformed = snapshot.clone();+ let mut decoder = None;+ for i in 0..bytes.len().saturating_sub(3) {+ let (op, disp, key, width) = if bytes[i..].starts_with(&[0x80, 0x75]) {+ (0u8, bytes[i + 2] as i8, bytes[i + 3], 4)+ } else if bytes[i..].starts_with(&[0x80, 0x45]) {+ (1u8, bytes[i + 2] as i8, bytes[i + 3], 4)+ } else if bytes[i..].starts_with(&[0x80, 0x6d]) {+ (2u8, bytes[i + 2] as i8, bytes[i + 3], 4)+ } else if i + 3 < bytes.len() && bytes[i..].starts_with(&[0xc0, 0x45]) {+ (3u8, bytes[i + 2] as i8, bytes[i + 3], 4)+ } else if i + 3 < bytes.len() && bytes[i..].starts_with(&[0xc0, 0x4d]) {+ (4u8, bytes[i + 2] as i8, bytes[i + 3], 4)+ } else {+ continue;+ };+ if key == 0 || !snapshot.contains_key(&disp) {+ continue;+ }+ let (before, store_at) = snapshot[&disp];+ let after = match op {+ 0 => before ^ key,+ 1 => before.wrapping_add(key),+ 2 => before.wrapping_sub(key),+ 3 => before.rotate_left((key & 7) as u32),+ _ => before.rotate_right((key & 7) as u32),+ };+ transformed.insert(disp, (after, store_at));+ decoder.get_or_insert(base + i as u64);+ let _ = width;+ }+ let Some(decoder_va) = decoder else {+ return;+ };+ let entries: Vec<_> = transformed.into_iter().collect();+ let mut start = 0usize;+ while start < entries.len() {+ let mut end = start + 1;+ while end < entries.len()+ && entries[end].0 == entries[end - 1].0 + 1+ && is_printable_ascii(entries[end].1 .0)+ {+ end += 1;+ }+ if end - start >= 4+ && entries[start..end]+ .iter()+ .all(|(_, (byte, _))| is_printable_ascii(*byte))+ {+ let value: String = entries[start..end]+ .iter()+ .map(|(_, (byte, _))| *byte as char)+ .collect();+ let store_at = entries[start].1 .1;+ let call_site = bytes+ .iter()+ .enumerate()+ .skip((decoder_va - base) as usize)+ .find_map(|(offset, byte)| (*byte == 0xe8).then_some(base + offset as u64));+ out.push(ObfuscatedStringHit {+ va: base + store_at as u64,+ value,+ kind: ObfuscatedStringKind::Decoded,+ decoder_va: Some(decoder_va),+ call_site,+ });+ }+ start = end;+ }+}++/// `C6 45 xx imm8` / `C6 44 24 xx imm8` style stack byte stores → stack strings.+fn recover_stack_immediates(+ base: u64,+ bytes: &[u8],+ opts: &RecoverStringsOpts,+ out: &mut Vec<ObfuscatedStringHit>,+) {+ if !kind_allowed(&ObfuscatedStringKind::Stack, opts)+ && !kind_allowed(&ObfuscatedStringKind::Tight, opts)+ {+ return;+ }+ let mut i = 0usize;+ while i + 4 < bytes.len() {+ // mov byte ptr [rbp+disp8], imm8 → C6 45 disp imm+ // mov byte ptr [rsp+disp8], imm8 → C6 44 24 disp imm+ let (store_va, imm, next) =+ if bytes[i] == 0xC6 && bytes[i + 1] == 0x45 && i + 3 < bytes.len() {+ (base + i as u64, bytes[i + 3], i + 4)+ } else if bytes[i] == 0xC6+ && bytes[i + 1] == 0x44+ && i + 4 < bytes.len()+ && bytes[i + 2] == 0x24+ {+ (base + i as u64, bytes[i + 4], i + 5)+ } else {+ i += 1;+ continue;+ };++ if !is_printable_ascii(imm) && imm != 0 {+ i = next;+ continue;+ }++ let mut chars = Vec::new();+ let mut j = i;+ let mut last_va = store_va;+ while j + 4 < bytes.len() {+ let (imm_b, step) = if bytes[j] == 0xC6 && bytes[j + 1] == 0x45 && j + 3 < bytes.len() {+ (bytes[j + 3], 4usize)+ } else if bytes[j] == 0xC6+ && bytes[j + 1] == 0x44+ && j + 4 < bytes.len()+ && bytes[j + 2] == 0x24+ {+ (bytes[j + 4], 5usize)+ } else {+ break;+ };+ if imm_b == 0 {+ j += step;+ break;+ }+ if !is_printable_ascii(imm_b) {+ break;+ }+ chars.push(imm_b);+ last_va = base + j as u64;+ j += step;+ if chars.len() > 256 {+ break;+ }+ }++ if chars.len() >= 4 {+ let value = String::from_utf8_lossy(&chars).into_owned();+ // Tight if a nearby XOR appears in the following 32 bytes.+ let window_end = (j + 32).min(bytes.len());+ let has_xor = bytes[j..window_end]+ .windows(2)+ .any(|w| w[0] == 0x34 || (w[0] == 0x80 && w.len() > 1) || w[0] == 0x30);+ let kind = if has_xor && kind_allowed(&ObfuscatedStringKind::Tight, opts) {+ ObfuscatedStringKind::Tight+ } else if kind_allowed(&ObfuscatedStringKind::Stack, opts) {+ ObfuscatedStringKind::Stack+ } else {+ i = j.max(next);+ continue;+ };+ out.push(ObfuscatedStringHit {+ va: store_va,+ value,+ kind,+ decoder_va: Some(last_va),+ call_site: None,+ });+ i = j.max(next);+ } else {+ i = next;+ }+ }+}++/// Scan for short XOR-imm loops that decode contiguous ciphertext into printable ASCII.+#[allow(dead_code)]+fn recover_xor_decoded(+ base: u64,+ bytes: &[u8],+ opts: &RecoverStringsOpts,+ out: &mut Vec<ObfuscatedStringHit>,+) {+ if !kind_allowed(&ObfuscatedStringKind::Decoded, opts) {+ return;+ }+ // Pattern: xor al/r8b, imm8 (34 xx) inside a small window with a load from a nearby data blob.+ let mut i = 0usize;+ while i + 8 < bytes.len() {+ if bytes[i] != 0x34 {+ i += 1;+ continue;+ }+ let key = bytes[i + 1];+ if key == 0 {+ i += 2;+ continue;+ }+ // Look backward up to 64 bytes for a LEA/MOV that could point at ciphertext;+ // instead, try decoding following immediates or prior .rdata-like immediates in code.+ // Practical approach: decode a run of bytes immediately after a `mov rsi, imm64` (48 BE)+ // is rare; scan for `34 key` density and try xor against nearby absolute addresses.+ // Simpler high-yield path: if the next 16+ bytes look like xor-encoded printable when+ // xored with `key`, emit them (common single-byte XOR blobs inlined after the decoder).+ let start = i + 2;+ let end = (start + 128).min(bytes.len());+ let mut decoded = Vec::new();+ for &b in &bytes[start..end] {+ let d = b ^ key;+ if d == 0 {+ break;+ }+ if !is_printable_ascii(d) {+ decoded.clear();+ break;+ }+ decoded.push(d);+ if decoded.len() > 200 {+ break;+ }+ }+ if decoded.len() >= 6 {+ out.push(ObfuscatedStringHit {+ va: base + start as u64,+ value: String::from_utf8_lossy(&decoded).into_owned(),+ kind: ObfuscatedStringKind::Decoded,+ decoder_va: Some(base + i as u64),+ call_site: None,+ });+ i = start + decoded.len();+ } else {+ i += 2;+ }+ }+}++/// ADD/SUB/ROL imm8 decode loops → printable ASCII (light emu without full CPU).+#[allow(dead_code)]+fn recover_arith_decoded(+ base: u64,+ bytes: &[u8],+ opts: &RecoverStringsOpts,+ out: &mut Vec<ObfuscatedStringHit>,+) {+ if !kind_allowed(&ObfuscatedStringKind::Decoded, opts) {+ return;+ }+ let mut i = 0usize;+ while i + 3 < bytes.len() {+ // add al, imm8 → 04 xx ; sub al, imm8 → 2C xx ; rol al, imm8 → C0 C0 xx+ let (key, kind_op, step) = if bytes[i] == 0x04 {+ (bytes[i + 1], b'+', 2usize)+ } else if bytes[i] == 0x2C {+ (bytes[i + 1], b'-', 2usize)+ } else if bytes[i] == 0xC0 && bytes[i + 1] == 0xC0 && i + 2 < bytes.len() {+ (bytes[i + 2], b'r', 3usize)+ } else {+ i += 1;+ continue;+ };+ if key == 0 {+ i += step;+ continue;+ }+ let start = i + step;+ let end = (start + 128).min(bytes.len());+ let mut decoded = Vec::new();+ for &b in &bytes[start..end] {+ let d = match kind_op {+ b'+' => b.wrapping_sub(key), // reverse of add+ b'-' => b.wrapping_add(key), // reverse of sub+ _ => b.rotate_right((key & 7) as u32),+ };+ if d == 0 {+ break;+ }+ if !is_printable_ascii(d) {+ decoded.clear();+ break;+ }+ decoded.push(d);+ if decoded.len() > 200 {+ break;+ }+ }+ if decoded.len() >= 6 {+ out.push(ObfuscatedStringHit {+ va: base + start as u64,+ value: String::from_utf8_lossy(&decoded).into_owned(),+ kind: ObfuscatedStringKind::Decoded,+ decoder_va: Some(base + i as u64),+ call_site: None,+ });+ i = start + decoded.len();+ } else {+ i += step;+ }+ }+}++pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {+ let opts = RecoverStringsOpts::default();+ let hits = recover_obfuscated_strings(prog, &opts);+ let n = hits.len();+ prog.analysis.obfuscated_strings = hits.clone();+ for h in &hits {+ let kind = match h.kind {+ ObfuscatedStringKind::Stack => "stack",+ ObfuscatedStringKind::Tight => "tight",+ ObfuscatedStringKind::Decoded => "decoded",+ ObfuscatedStringKind::StaticHint => "static",+ };+ let text: String = h.value.chars().take(80).collect();+ prog.edits.set_comment(+ h.va,+ crate::edits::CommentKind::Eol,+ format!("recovered[{kind}]: {text}"),+ );+ }+ Ok(AnalyzerOutput {+ name: "Obfuscated Strings".into(),+ status: "ok".into(),+ message: format!("recovered {n} obfuscated string(s)"),+ obfuscated_strings: Some(hits),+ ..Default::default()+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::program::{MemoryBlock, Program};++ #[test]+ fn recovers_stack_byte_stores() {+ let mut prog = Program::new("t".into(), "raw");+ // Build "http" via C6 45 xx imm+ let mut code = Vec::new();+ for (disp, ch) in [(0u8, b'h'), (1, b't'), (2, b't'), (3, b'p'), (4, 0)] {+ code.extend_from_slice(&[0xC6, 0x45, disp, ch]);+ }+ prog.blocks.push(MemoryBlock {+ name: ".text".into(),+ va: 0x401000,+ size: code.len() as u64,+ bytes: code,+ readable: true,+ writable: false,+ executable: true,+ });+ let hits = recover_obfuscated_strings(&prog, &RecoverStringsOpts::default());+ assert!(hits.iter().any(|h| h.value == "http"));+ }++ #[test]+ fn classifies_tight_stack_construction() {+ let mut prog = Program::new("tight".into(), "raw");+ let mut code = Vec::new();+ for (disp, ch) in [+ (0u8, b't'),+ (1, b'i'),+ (2, b'g'),+ (3, b'h'),+ (4, b't'),+ (5, 0),+ ] {+ code.extend_from_slice(&[0xc6, 0x45, disp, ch]);+ }+ // Nearby non-zero byte transform makes this a tight construction site.+ code.extend_from_slice(&[0x80, 0x75, 0, 0x11]);+ prog.blocks.push(MemoryBlock {+ name: ".text".into(),+ va: 0x5000,+ size: code.len() as u64,+ bytes: code,+ readable: true,+ writable: false,+ executable: true,+ });+ let hits = recover_obfuscated_strings(&prog, &RecoverStringsOpts::default());+ assert!(hits+ .iter()+ .any(|h| h.value == "tight" && h.kind == ObfuscatedStringKind::Tight));+ }++ #[test]+ fn emulates_xor_stack_decoder_with_decoder_site() {+ let mut prog = Program::new("decode".into(), "raw");+ let mut code = Vec::new();+ for (disp, ch) in [+ (0u8, b's' ^ 0x55),+ (1, b'e' ^ 0x55),+ (2, b'e' ^ 0x55),+ (3, b'd' ^ 0x55),+ ] {+ code.extend_from_slice(&[0xc6, 0x45, disp, ch]);+ }+ for disp in 0..4u8 {+ code.extend_from_slice(&[0x80, 0x75, disp, 0x55]); // xor byte ptr [rbp+disp], 55+ }+ code.extend_from_slice(&[0xe2, 0xfe]); // bounded-loop marker+ prog.blocks.push(MemoryBlock {+ name: ".text".into(),+ va: 0x6000,+ size: code.len() as u64,+ bytes: code,+ readable: true,+ writable: false,+ executable: true,+ });+ let hits = recover_obfuscated_strings(&prog, &RecoverStringsOpts::default());+ assert!(hits.iter().any(|h| {+ h.value == "seed" && h.kind == ObfuscatedStringKind::Decoded && h.decoder_va.is_some()+ }));+ }++ #[test]+ fn recovers_static_hints_and_respects_kind_filters_and_limit() {+ let mut prog = Program::new("static".into(), "raw");+ prog.blocks.push(MemoryBlock {+ name: ".rdata".into(),+ va: 0x7000,+ size: 20,+ bytes: b"first!\0second!".to_vec(),+ readable: true,+ writable: false,+ executable: false,+ });+ let static_only = RecoverStringsOpts {+ only: Some(vec!["static".into()]),+ ..Default::default()+ };+ let hits = recover_obfuscated_strings(&prog, &static_only);+ assert!(hits.iter().all(|hit| hit.kind == ObfuscatedStringKind::StaticHint));+ assert!(hits.iter().any(|hit| hit.value == "first!"));++ let none = RecoverStringsOpts {+ no: Some(vec!["static".into()]),+ ..Default::default()+ };+ assert!(recover_obfuscated_strings(&prog, &none).is_empty());+ let limited = RecoverStringsOpts {+ limit: Some(1),+ ..Default::default()+ };+ assert_eq!(recover_obfuscated_strings(&prog, &limited).len(), 1);+ }++ #[test]+ fn recovers_add_sub_and_rol_inline_decoders() {+ let mut prog = Program::new("arith".into(), "raw");+ let mut code = vec![0x04, 0x11]; // add al, 0x11; encoded bytes follow+ code.extend(b"Yv}}\x802"); // "Hello!" plus 0x11+ code.push(0x11); // encoded NUL+ code.extend_from_slice(&[0x2c, 0x11]); // sub al, 0x11; encoded bytes follow+ code.extend(b"7T[[^\x10"); // "Hello!" minus 0x11+ code.push(0xef); // encoded NUL+ prog.blocks.push(MemoryBlock {+ name: ".text".into(),+ va: 0x8000,+ size: code.len() as u64,+ bytes: code,+ readable: true,+ writable: false,+ executable: true,+ });+ let hits = recover_obfuscated_strings(&prog, &RecoverStringsOpts::default());+ assert_eq!(+ hits.iter()+ .filter(|hit| hit.kind == ObfuscatedStringKind::Decoded && hit.value == "Hello!")+ .count(),+ 2,+ "{hits:?}"+ );+ }+}diff --git a/crates/ghidrust-core/src/analyzers/scan_util.rs b/crates/ghidrust-core/src/analyzers/scan_util.rsindex 739000a..eef6f4c 100644--- a/crates/ghidrust-core/src/analyzers/scan_util.rs+++ b/crates/ghidrust-core/src/analyzers/scan_util.rs@@ -10,7 +10,8 @@ pub fn find_cstr(prog: &Program, needle: &[u8]) -> Vec<u64> {let mut i = 0;while i + needle.len() <= b.len() {if &b[i..i + needle.len()] == needle {- let ok_end = i + needle.len() == b.len() || b[i + needle.len()] == 0+ let ok_end = i + needle.len() == b.len()+ || b[i + needle.len()] == 0|| !b[i + needle.len()].is_ascii_alphanumeric();if ok_end {out.push(block.va + i as u64);diff --git a/crates/ghidrust-core/src/analyzers/strings.rs b/crates/ghidrust-core/src/analyzers/strings.rsindex 26e3b21..2640bae 100644--- a/crates/ghidrust-core/src/analyzers/strings.rs+++ b/crates/ghidrust-core/src/analyzers/strings.rs@@ -167,7 +167,11 @@ fn scan_utf16le_in_bytes(base_va: u64, bytes: &[u8], min_len: usize) -> Vec<Founlet asciiish = value.chars().filter(|c| c.is_ascii()).count();let ratio = asciiish as f64 / value.len() as f64;if value.chars().any(|c| c.is_ascii_alphabetic()) && ratio >= 0.85 {- out.push(FoundString::utf16le(base_va + start as u64, value, chars.len()));+ out.push(FoundString::utf16le(+ base_va + start as u64,+ value,+ chars.len(),+ ));}i = j + 2;continue;@@ -298,8 +302,7 @@ fn token_match(pat: &str, value: &str) -> bool {let mut start = 0usize;let bytes = value.as_bytes();for i in 0..=bytes.len() {- let boundary = i == bytes.len()- || !bytes[i].is_ascii_alphanumeric() && bytes[i] != b'_';+ let boundary = i == bytes.len() || !bytes[i].is_ascii_alphanumeric() && bytes[i] != b'_';if boundary {if i > start && &value[start..i] == pat {return true;@@ -355,7 +358,8 @@ mod tests {});let hits = scan_utf16le_strings(&prog, 4);assert!(- hits.iter().any(|s| s.value.contains("UserConfigSelections")),+ hits.iter()+ .any(|s| s.value.contains("UserConfigSelections")),"{hits:?}");assert!(hits.iter().all(|s| s.encoding == "utf16le"));diff --git a/crates/ghidrust-core/src/analyzers/variadic.rs b/crates/ghidrust-core/src/analyzers/variadic.rsindex 24ea935..6c6099e 100644--- a/crates/ghidrust-core/src/analyzers/variadic.rs+++ b/crates/ghidrust-core/src/analyzers/variadic.rs@@ -3,7 +3,9 @@ use super::AnalyzerOutput;use crate::error::Result;use crate::program::{FunctionInfo, Program};-const VARARGS: &[&str] = &["printf", "sprintf", "snprintf", "fprintf", "scanf", "wsprintf"];+const VARARGS: &[&str] = &[+ "printf", "sprintf", "snprintf", "fprintf", "scanf", "wsprintf",+];pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {ensure_api_symbols(prog, VARARGS);diff --git a/crates/ghidrust-core/src/artifacts.rs b/crates/ghidrust-core/src/artifacts.rsindex 5c3b203..cd641e8 100644--- a/crates/ghidrust-core/src/artifacts.rs+++ b/crates/ghidrust-core/src/artifacts.rs@@ -65,10 +65,7 @@ fn now_ms() -> u64 {fn new_id(kind: &str) -> String {let ms = now_ms();- let n = LAST_IDS- .lock()- .map(|g| g.len())- .unwrap_or(0);+ let n = LAST_IDS.lock().map(|g| g.len()).unwrap_or(0);format!("{kind}-{ms}-{n}")}@@ -153,7 +150,8 @@ pub fn envelope_or_spill(if entry_count > threshold {return spill_artifact(kind, entries, preview_limit, source);}- let (preview, preview_count, next_offset) = preview_slice(&entries, 0, preview_limit.max(entry_count));+ let (preview, preview_count, next_offset) =+ preview_slice(&entries, 0, preview_limit.max(entry_count));Ok(ArtifactEnvelope {ok: true,kind: kind.into(),@@ -213,13 +211,13 @@ pub fn artifact_get(id_or_path: &str) -> Result<Value> {}/// Page through artifact entries with `offset` / `limit`. Returns envelope with `next_offset`.-pub fn artifact_query(- id_or_path: &str,- offset: usize,- limit: usize,-) -> Result<ArtifactEnvelope> {+pub fn artifact_query(id_or_path: &str, offset: usize, limit: usize) -> Result<ArtifactEnvelope> {let file = load_file(id_or_path)?;- let limit = if limit == 0 { DEFAULT_PREVIEW_LIMIT } else { limit };+ let limit = if limit == 0 {+ DEFAULT_PREVIEW_LIMIT+ } else {+ limit+ };let (preview, preview_count, next_offset) = preview_slice(&file.entries, offset, limit);Ok(ArtifactEnvelope {ok: true,diff --git a/crates/ghidrust-core/src/bounds_honesty.rs b/crates/ghidrust-core/src/bounds_honesty.rsindex e426224..53bd355 100644--- a/crates/ghidrust-core/src/bounds_honesty.rs+++ b/crates/ghidrust-core/src/bounds_honesty.rs@@ -42,7 +42,10 @@ impl BoundsHonesty {serde_json::Value::Bool(self.bounds_suspect),);if let Some(w) = &self.bounds_warning {- m.insert("bounds_warning".into(), serde_json::Value::String(w.clone()));+ m.insert(+ "bounds_warning".into(),+ serde_json::Value::String(w.clone()),+ );}if let Some(e) = self.suggested_end {m.insert(@@ -84,9 +87,8 @@ pub fn assess_bounds_honesty(let short_insn_stop = insn_count < SHORT_INSN_COUNT&& stop_reason == DisasmStopReason::FunctionEnd&& grow_extends;- let no_clean_terminator = grow_extends- && span < SHORT_SPAN_BYTES- && !ends_at_ret_or_int3_pad(prog, stored_end);+ let no_clean_terminator =+ grow_extends && span < SHORT_SPAN_BYTES && !ends_at_ret_or_int3_pad(prog, stored_end);if !(short_span_stop || short_insn_stop || no_clean_terminator) {return BoundsHonesty::ok();diff --git a/crates/ghidrust-core/src/bulk_scan.rs b/crates/ghidrust-core/src/bulk_scan.rsindex a798f52..a3d6738 100644--- a/crates/ghidrust-core/src/bulk_scan.rs+++ b/crates/ghidrust-core/src/bulk_scan.rs@@ -37,11 +37,17 @@ pub fn preferred_bulk_mode() -> BulkScanMode {#[serde(rename_all = "snake_case")]pub enum BulkBackend {Sequential,- ParallelCpu { threads: usize },+ ParallelCpu {+ threads: usize,+ },/// Physical GPU compute (feature `gpu` + live adapter).- Gpu { device: String },+ Gpu {+ device: String,+ },/// Same work-item kernel on CPU when GPU unavailable.- CpuFallback { reason: String },+ CpuFallback {+ reason: String,+ },}/// Inclusive printable-run hit in a flat haystack (byte offset + length).@@ -357,7 +363,10 @@ pub fn scan_printable_runs_gpu_or_fallback(hay: &[u8], min_len: usize) -> GpuSca}/// GPU-shaped schedule on CPU: one workgroup tile → classify bytes → host compact runs.-fn scan_printable_runs_parallel_workitems(hay: &[u8], min_len: usize) -> (Vec<BulkHit>, BulkBackend) {+fn scan_printable_runs_parallel_workitems(+ hay: &[u8],+ min_len: usize,+) -> (Vec<BulkHit>, BulkBackend) {// Work-item path builds a printable mask in parallel tiles, then sequential compact.// For large inputs this mirrors a GPU mark + host compact pipeline.if hay.len() < GPU_WORKGROUP_BYTES * 2 {@@ -650,9 +659,16 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {}/// Unified entry: pick mode, return hits + backend.-pub fn scan_printable_runs(hay: &[u8], min_len: usize, mode: BulkScanMode) -> (Vec<BulkHit>, BulkBackend) {+pub fn scan_printable_runs(+ hay: &[u8],+ min_len: usize,+ mode: BulkScanMode,+) -> (Vec<BulkHit>, BulkBackend) {match mode {- BulkScanMode::Sequential => (scan_printable_runs_seq(hay, min_len), BulkBackend::Sequential),+ BulkScanMode::Sequential => (+ scan_printable_runs_seq(hay, min_len),+ BulkBackend::Sequential,+ ),BulkScanMode::ParallelCpu => scan_printable_runs_parallel(hay, min_len),BulkScanMode::GpuOrFallback => {let r = scan_printable_runs_gpu_or_fallback(hay, min_len);@@ -690,8 +706,8 @@ pub fn scan_ascii_strings_bulk(let end = h.offset + h.length;let nul_term = end < block.bytes.len() && block.bytes[end] == 0;if h.length >= min_len && (nul_term || h.length >= 6) {- let value =- String::from_utf8_lossy(&block.bytes[h.offset..h.offset + h.length]).into_owned();+ let value = String::from_utf8_lossy(&block.bytes[h.offset..h.offset + h.length])+ .into_owned();if value.chars().any(|c| c.is_ascii_alphabetic()) {out.push(FoundString::ascii(block.va + h.offset as u64,@@ -829,10 +845,7 @@ mod tests {assert!(plan_dispatch_workgroup_chunks(0, 65535).is_empty());assert_eq!(plan_dispatch_workgroup_chunks(1, 65535), vec![1]);assert_eq!(plan_dispatch_workgroup_chunks(65535, 65535), vec![65535]);- assert_eq!(- plan_dispatch_workgroup_chunks(65536, 65535),- vec![65535, 1]- );+ assert_eq!(plan_dispatch_workgroup_chunks(65536, 65535), vec![65535, 1]);}#[test]@@ -860,7 +873,10 @@ mod tests {let max = MAX_COMPUTE_WORKGROUPS_PER_DIMENSION_DEFAULT;let n_bytes = (max as usize) * GPU_WORKGROUP_BYTES + 4096;let total_groups = ((n_bytes + GPU_WORKGROUP_BYTES - 1) / GPU_WORKGROUP_BYTES) as u32;- assert!(total_groups > max, "fixture must exceed single-dispatch limit");+ assert!(+ total_groups > max,+ "fixture must exceed single-dispatch limit"+ );let chunks = plan_dispatch_workgroup_chunks(total_groups, max);assert!(chunks.len() >= 2);diff --git a/crates/ghidrust-core/src/callsite_hints.rs b/crates/ghidrust-core/src/callsite_hints.rsindex 09b17a3..d508f4d 100644--- a/crates/ghidrust-core/src/callsite_hints.rs+++ b/crates/ghidrust-core/src/callsite_hints.rs@@ -37,7 +37,10 @@ pub fn collect_callsite_hints(insns: &[Instruction]) -> Vec<CallsiteHint> {let ops = prev.operands.to_ascii_lowercase();let mnem = prev.mnemonic.to_ascii_lowercase();if is_rip_relative_load(&mnem, &ops) {- rip_loads.push(format!("{:#x}: {} {}", prev.address, prev.mnemonic, prev.operands));+ rip_loads.push(format!(+ "{:#x}: {} {}",+ prev.address, prev.mnemonic, prev.operands+ ));}if let Some((reg, evidence)) = win64_arg_def(prev) {// Later defs override earlier for the same reg.diff --git a/crates/ghidrust-core/src/crypto_pipeline.rs b/crates/ghidrust-core/src/crypto_pipeline.rsnew file mode 100644index 0000000..b8179ec--- /dev/null+++ b/crates/ghidrust-core/src/crypto_pipeline.rs@@ -0,0 +1,110 @@+//! Cross-tier crypto discovery → recover → bake suggestion pipeline.++use crate::analyzers::{crypt_constants, crypto_capabilities, obfuscated_strings, AnalyzerOutput};+use crate::decode_bake::BakeOp;+use crate::error::Result;+use crate::program::Program;++/// Run Find Crypt → Obfuscated Strings → Crypto Capabilities in order so each tier seeds the next.+pub fn run_crypto_pipeline(prog: &mut Program) -> Result<Vec<AnalyzerOutput>> {+ let mut outs = Vec::new();+ outs.push(crypt_constants::run(prog)?);+ outs.push(obfuscated_strings::run(prog)?);+ outs.push(crypto_capabilities::run(prog)?);+ Ok(outs)+}++/// Suggest a bake recipe from algorithm / capability hint text.+pub fn suggest_recipe_for_hint(hint: &str) -> Vec<BakeOp> {+ let h = hint.to_ascii_uppercase();+ if h.contains("AES") {+ return vec![BakeOp {+ op: "AESDecrypt".into(),+ args: serde_json::json!({"mode": "cbc"}),+ }];+ }+ if h.contains("RC4") {+ return vec![BakeOp {+ op: "RC4".into(),+ args: serde_json::json!({}),+ }];+ }+ if h.contains("DES") && !h.contains("3DES") && !h.contains("TRIPLE") {+ return vec![BakeOp {+ op: "DESDecrypt".into(),+ args: serde_json::json!({"mode": "cbc"}),+ }];+ }+ if h.contains("3DES") || h.contains("TRIPLE DES") {+ return vec![BakeOp {+ op: "TripleDESDecrypt".into(),+ args: serde_json::json!({"mode": "cbc"}),+ }];+ }+ if h.contains("BLOWFISH") {+ return vec![BakeOp {+ op: "BlowfishDecrypt".into(),+ args: serde_json::json!({"mode": "cbc"}),+ }];+ }+ if h.contains("CHACHA") || h.contains("SALSA") {+ return vec![BakeOp {+ op: "ChaCha20Decrypt".into(),+ args: serde_json::json!({}),+ }];+ }+ if h.contains("BASE64") || h.contains("ENCODING") {+ return vec![+ BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "Gunzip".into(),+ args: serde_json::json!({}),+ },+ ];+ }+ if h.contains("GZIP") {+ return vec![BakeOp {+ op: "Gunzip".into(),+ args: serde_json::json!({}),+ }];+ }+ if h.contains("ZLIB") || h.contains("INFLATE") {+ return vec![BakeOp {+ op: "Inflate".into(),+ args: serde_json::json!({}),+ }];+ }+ if h.contains("DPAPI") || h.contains("CRYPTPROTECT") || h.contains("DATA PROTECTION") {+ return Vec::new();+ }+ vec![+ BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "XORBrute".into(),+ args: serde_json::json!({}),+ },+ ]+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn suggestions_name_native_operations() {+ assert_eq!(suggest_recipe_for_hint("ChaCha20")[0].op, "ChaCha20Decrypt");+ assert_eq!(suggest_recipe_for_hint("gzip stream")[0].op, "Gunzip");+ assert!(suggest_recipe_for_hint("DPAPI CryptProtectData").is_empty());+ }+}++/// Build decoder `--functions` seed list from prior pipeline state on `prog`.+pub fn recover_function_seeds(prog: &Program) -> Vec<u64> {+ obfuscated_strings::decoder_seed_vas(prog)+}diff --git a/crates/ghidrust-core/src/decode_bake.rs b/crates/ghidrust-core/src/decode_bake.rsnew file mode 100644index 0000000..2dba255--- /dev/null+++ b/crates/ghidrust-core/src/decode_bake.rs@@ -0,0 +1,1644 @@+//! Byte-transform recipe engine (encode/cipher/compress peels).++use crate::analyzers::crypt_constants::aes_sbox;+use crate::inflate::{gunzip, inflate_auto};+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BakeOp {+ pub op: String,+ #[serde(default)]+ pub args: serde_json::Value,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BakeResult {+ pub ok: bool,+ pub output_hex: String,+ pub output_utf8: Option<String>,+ pub message: String,+ #[serde(default)]+ pub recipe_applied: Vec<String>,+}++fn to_hex(b: &[u8]) -> String {+ b.iter().map(|x| format!("{x:02x}")).collect()+}++fn from_hex(s: &str) -> Result<Vec<u8>, String> {+ let clean: String = s.chars().filter(|c| !c.is_whitespace()).collect();+ if clean.len() % 2 != 0 {+ return Err("hex length must be even".into());+ }+ (0..clean.len())+ .step_by(2)+ .map(|i| u8::from_str_radix(&clean[i..i + 2], 16).map_err(|e| e.to_string()))+ .collect()+}++fn b64_decode(input: &[u8]) -> Result<Vec<u8>, String> {+ fn val(c: u8) -> Option<u8> {+ match c {+ b'A'..=b'Z' => Some(c - b'A'),+ b'a'..=b'z' => Some(c - b'a' + 26),+ b'0'..=b'9' => Some(c - b'0' + 52),+ b'+' | b'-' => Some(62),+ b'/' | b'_' => Some(63),+ b'=' => Some(0),+ _ if c.is_ascii_whitespace() => None,+ _ => None,+ }+ }+ let mut chars = Vec::new();+ for &c in input {+ if c == b'=' || c.is_ascii_whitespace() {+ if c == b'=' {+ chars.push(c);+ }+ continue;+ }+ if val(c).is_none() {+ return Err(format!("invalid base64 byte {c:#x}"));+ }+ chars.push(c);+ }+ while chars.len() % 4 != 0 {+ chars.push(b'=');+ }+ let mut out = Vec::with_capacity(chars.len() / 4 * 3);+ for chunk in chars.chunks(4) {+ let (a, b, c, d) = (+ val(chunk[0]).unwrap_or(0),+ val(chunk[1]).unwrap_or(0),+ val(chunk[2]).unwrap_or(0),+ val(chunk[3]).unwrap_or(0),+ );+ out.push((a << 2) | (b >> 4));+ if chunk[2] != b'=' {+ out.push((b << 4) | (c >> 2));+ }+ if chunk[3] != b'=' {+ out.push((c << 6) | d);+ }+ }+ Ok(out)+}++fn xor_key(data: &[u8], key: &[u8]) -> Vec<u8> {+ if key.is_empty() {+ return data.to_vec();+ }+ data.iter()+ .enumerate()+ .map(|(i, b)| b ^ key[i % key.len()])+ .collect()+}++fn rc4(data: &[u8], key: &[u8]) -> Result<Vec<u8>, String> {+ if key.is_empty() {+ return Err("RC4 key empty".into());+ }+ let mut s: Vec<u8> = (0..=255).collect();+ let mut j: usize = 0;+ for i in 0..256 {+ j = (j + s[i] as usize + key[i % key.len()] as usize) & 255;+ s.swap(i, j);+ }+ let mut i = 0usize;+ j = 0;+ let mut out = Vec::with_capacity(data.len());+ for &b in data {+ i = (i + 1) & 255;+ j = (j + s[i] as usize) & 255;+ s.swap(i, j);+ let k = s[(s[i] as usize + s[j] as usize) & 255];+ out.push(b ^ k);+ }+ Ok(out)+}++fn mul(a: u8, b: u8) -> u8 {+ let mut a = a;+ let mut b = b;+ let mut p = 0u8;+ for _ in 0..8 {+ if b & 1 != 0 {+ p ^= a;+ }+ let hi = a & 0x80;+ a <<= 1;+ if hi != 0 {+ a ^= 0x1b;+ }+ b >>= 1;+ }+ p+}++fn aes_add_round_key(state: &mut [u8; 16], rk: &[u8]) {+ for i in 0..16 {+ state[i] ^= rk[i];+ }+}++fn aes_key_expand_128(key: &[u8; 16]) -> [[u8; 16]; 11] {+ let s = aes_sbox();+ let rcon = [0x01u8, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];+ let mut w = [0u8; 176];+ w[..16].copy_from_slice(key);+ let mut bytes_generated = 16usize;+ let mut rcon_i = 0usize;+ let mut temp = [0u8; 4];+ while bytes_generated < 176 {+ temp.copy_from_slice(&w[bytes_generated - 4..bytes_generated]);+ if bytes_generated % 16 == 0 {+ // rot word+ temp = [temp[1], temp[2], temp[3], temp[0]];+ for t in temp.iter_mut() {+ *t = s[*t as usize];+ }+ temp[0] ^= rcon[rcon_i];+ rcon_i += 1;+ }+ for i in 0..4 {+ w[bytes_generated] = w[bytes_generated - 16] ^ temp[i];+ bytes_generated += 1;+ }+ }+ let mut rounds = [[0u8; 16]; 11];+ for r in 0..11 {+ rounds[r].copy_from_slice(&w[r * 16..(r + 1) * 16]);+ }+ rounds+}++fn aes_inv_sbox() -> [u8; 256] {+ let mut inv = [0u8; 256];+ let s = aes_sbox();+ for (i, &v) in s.iter().enumerate() {+ inv[v as usize] = i as u8;+ }+ inv+}++fn aes_inv_sub_bytes(state: &mut [u8; 16], inv: &[u8; 256]) {+ for b in state.iter_mut() {+ *b = inv[*b as usize];+ }+}++fn aes_inv_shift_rows(state: &mut [u8; 16]) {+ let t = *state;+ state[1] = t[13];+ state[5] = t[1];+ state[9] = t[5];+ state[13] = t[9];+ state[2] = t[10];+ state[6] = t[14];+ state[10] = t[2];+ state[14] = t[6];+ state[3] = t[7];+ state[7] = t[11];+ state[11] = t[15];+ state[15] = t[3];+}++fn aes_inv_mix_columns(state: &mut [u8; 16]) {+ for c in 0..4 {+ let i = c * 4;+ let a0 = state[i];+ let a1 = state[i + 1];+ let a2 = state[i + 2];+ let a3 = state[i + 3];+ state[i] = mul(a0, 0x0e) ^ mul(a1, 0x0b) ^ mul(a2, 0x0d) ^ mul(a3, 0x09);+ state[i + 1] = mul(a0, 0x09) ^ mul(a1, 0x0e) ^ mul(a2, 0x0b) ^ mul(a3, 0x0d);+ state[i + 2] = mul(a0, 0x0d) ^ mul(a1, 0x09) ^ mul(a2, 0x0e) ^ mul(a3, 0x0b);+ state[i + 3] = mul(a0, 0x0b) ^ mul(a1, 0x0d) ^ mul(a2, 0x09) ^ mul(a3, 0x0e);+ }+}++fn aes_sub_bytes(state: &mut [u8; 16], sbox: &[u8; 256]) {+ for b in state.iter_mut() {+ *b = sbox[*b as usize];+ }+}++fn aes_shift_rows(state: &mut [u8; 16]) {+ let t = *state;+ state[1] = t[5];+ state[5] = t[9];+ state[9] = t[13];+ state[13] = t[1];+ state[2] = t[10];+ state[6] = t[14];+ state[10] = t[2];+ state[14] = t[6];+ state[3] = t[15];+ state[7] = t[3];+ state[11] = t[7];+ state[15] = t[11];+}++fn aes_mix_columns(state: &mut [u8; 16]) {+ for c in 0..4 {+ let i = c * 4;+ let a0 = state[i];+ let a1 = state[i + 1];+ let a2 = state[i + 2];+ let a3 = state[i + 3];+ state[i] = mul(a0, 2) ^ mul(a1, 3) ^ a2 ^ a3;+ state[i + 1] = a0 ^ mul(a1, 2) ^ mul(a2, 3) ^ a3;+ state[i + 2] = a0 ^ a1 ^ mul(a2, 2) ^ mul(a3, 3);+ state[i + 3] = mul(a0, 3) ^ a1 ^ a2 ^ mul(a3, 2);+ }+}++fn aes_encrypt_block_128(block: &[u8; 16], round_keys: &[[u8; 16]; 11]) -> [u8; 16] {+ let sbox = aes_sbox();+ let mut state = *block;+ aes_add_round_key(&mut state, &round_keys[0]);+ for round in 1..10 {+ aes_sub_bytes(&mut state, sbox);+ aes_shift_rows(&mut state);+ aes_mix_columns(&mut state);+ aes_add_round_key(&mut state, &round_keys[round]);+ }+ aes_sub_bytes(&mut state, sbox);+ aes_shift_rows(&mut state);+ aes_add_round_key(&mut state, &round_keys[10]);+ state+}++fn aes_decrypt_block_128(block: &[u8; 16], round_keys: &[[u8; 16]; 11]) -> [u8; 16] {+ let inv = aes_inv_sbox();+ let mut state = *block;+ aes_add_round_key(&mut state, &round_keys[10]);+ for round in (1..10).rev() {+ aes_inv_shift_rows(&mut state);+ aes_inv_sub_bytes(&mut state, &inv);+ aes_add_round_key(&mut state, &round_keys[round]);+ aes_inv_mix_columns(&mut state);+ }+ aes_inv_shift_rows(&mut state);+ aes_inv_sub_bytes(&mut state, &inv);+ aes_add_round_key(&mut state, &round_keys[0]);+ state+}++fn aes_decrypt(data: &[u8], key: &[u8], iv: Option<&[u8]>, mode: &str) -> Result<Vec<u8>, String> {+ if key.len() != 16 {+ return Err("AES-128 key must be 16 bytes".into());+ }+ if data.is_empty() {+ return Err("AES ciphertext empty".into());+ }+ let mut key_arr = [0u8; 16];+ key_arr.copy_from_slice(key);+ let rk = aes_key_expand_128(&key_arr);+ let mode = mode.to_ascii_lowercase();+ let mut out = Vec::with_capacity(data.len());++ match mode.as_str() {+ "ecb" => {+ if data.len() % 16 != 0 {+ return Err("AES-ECB length must be a multiple of 16".into());+ }+ for chunk in data.chunks(16) {+ let mut blk = [0u8; 16];+ blk.copy_from_slice(chunk);+ out.extend_from_slice(&aes_decrypt_block_128(&blk, &rk));+ }+ Ok(out)+ }+ "cbc" => {+ if data.len() % 16 != 0 {+ return Err("AES-CBC length must be a multiple of 16".into());+ }+ let iv = iv.ok_or_else(|| "AES-CBC requires iv".to_string())?;+ if iv.len() != 16 {+ return Err("AES IV must be 16 bytes".into());+ }+ let mut prev = [0u8; 16];+ prev.copy_from_slice(iv);+ for chunk in data.chunks(16) {+ let mut blk = [0u8; 16];+ blk.copy_from_slice(chunk);+ let plain = aes_decrypt_block_128(&blk, &rk);+ let mut xored = [0u8; 16];+ for i in 0..16 {+ xored[i] = plain[i] ^ prev[i];+ }+ out.extend_from_slice(&xored);+ prev = blk;+ }+ Ok(out)+ }+ "ctr" | "gcm" => {+ // GCM decrypts with CTR. Authentication is intentionally not claimed here:+ // callers must verify a supplied tag before trusting the returned plaintext.+ let iv = iv.ok_or_else(|| format!("AES-{mode} requires iv"))?;+ let mut counter = [0u8; 16];+ if iv.len() == 16 {+ counter.copy_from_slice(iv);+ } else if iv.len() == 12 {+ counter[..12].copy_from_slice(iv);+ counter[15] = 1;+ } else {+ return Err("AES CTR/GCM IV must be 12 or 16 bytes".into());+ }+ if mode == "gcm" {+ increment_be(&mut counter);+ }+ for chunk in data.chunks(16) {+ let keystream = aes_encrypt_block_128(&counter, &rk);+ for (i, &b) in chunk.iter().enumerate() {+ out.push(b ^ keystream[i]);+ }+ // increment counter (big-endian)+ increment_be(&mut counter);+ }+ Ok(out)+ }+ "cfb" => {+ let iv = iv.ok_or_else(|| "AES-CFB requires iv".to_string())?;+ if iv.len() != 16 {+ return Err("AES IV must be 16 bytes".into());+ }+ let mut prev = [0u8; 16];+ prev.copy_from_slice(iv);+ for chunk in data.chunks(16) {+ let keystream = aes_encrypt_block_128(&prev, &rk);+ let mut plain = vec![0u8; chunk.len()];+ for i in 0..chunk.len() {+ plain[i] = chunk[i] ^ keystream[i];+ }+ // CFB feedback is ciphertext+ if chunk.len() == 16 {+ prev.copy_from_slice(chunk);+ } else {+ prev[..chunk.len()].copy_from_slice(chunk);+ }+ out.extend_from_slice(&plain);+ }+ Ok(out)+ }+ "ofb" => {+ let iv = iv.ok_or_else(|| "AES-OFB requires iv".to_string())?;+ if iv.len() != 16 {+ return Err("AES IV must be 16 bytes".into());+ }+ let mut prev = [0u8; 16];+ prev.copy_from_slice(iv);+ for chunk in data.chunks(16) {+ prev = aes_encrypt_block_128(&prev, &rk);+ for (i, &b) in chunk.iter().enumerate() {+ out.push(b ^ prev[i]);+ }+ }+ Ok(out)+ }+ other => Err(format!("unsupported AES mode: {other}")),+ }+}++fn increment_be(counter: &mut [u8; 16]) {+ for i in (0..16).rev() {+ counter[i] = counter[i].wrapping_add(1);+ if counter[i] != 0 {+ break;+ }+ }+}++const BLOWFISH_P_INIT: [u32; 18] = [+ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,+ 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,+ 0x9216d5d9, 0x8979fb1b,+];+const BLOWFISH_S_INIT: [[u32; 256]; 4] = [+ [+ 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045,+ 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69,+ 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d,+ 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,+ 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda,+ 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,+ 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d,+ 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,+ 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60,+ 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5,+ 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842,+ 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,+ 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e,+ 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073,+ 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724,+ 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,+ 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2,+ 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,+ 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857,+ 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,+ 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8,+ 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0,+ 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0,+ 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,+ 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341,+ 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198,+ 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb,+ 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,+ 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6,+ 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,+ 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c,+ 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,+ 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2,+ 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a,+ 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5,+ 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,+ 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,+ ],+ [+ 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8,+ 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29,+ 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07,+ 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,+ 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305,+ 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,+ 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9,+ 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,+ 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1,+ 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79,+ 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f,+ 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,+ 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37,+ 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55,+ 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed,+ 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,+ 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978,+ 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,+ 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595,+ 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,+ 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775,+ 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239,+ 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf,+ 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,+ 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f,+ 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263,+ 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef,+ 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,+ 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d,+ 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,+ 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00,+ 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,+ 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7,+ 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2,+ 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3,+ 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,+ 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,+ ],+ [+ 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e,+ 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546,+ 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec,+ 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,+ 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4,+ 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,+ 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7,+ 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,+ 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7,+ 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9,+ 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548,+ 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,+ 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3,+ 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1,+ 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845,+ 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,+ 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c,+ 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,+ 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88,+ 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,+ 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6,+ 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386,+ 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057,+ 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,+ 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299,+ 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74,+ 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e,+ 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,+ 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025,+ 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,+ 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27,+ 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,+ 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1,+ 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9,+ 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e,+ 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,+ 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,+ ],+ [+ 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740,+ 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045,+ 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee,+ 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,+ 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa,+ 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,+ 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915,+ 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,+ 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472,+ 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc,+ 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4,+ 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,+ 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482,+ 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e,+ 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e,+ 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,+ 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f,+ 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,+ 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d,+ 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,+ 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b,+ 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b,+ 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749,+ 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,+ 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71,+ 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c,+ 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532,+ 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,+ 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf,+ 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,+ 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292,+ 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,+ 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c,+ 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76,+ 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c,+ 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,+ 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6,+ ],+];++const DES_IP: [u8; 64] = [+ 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6,+ 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61,+ 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7,+];+const DES_FP: [u8; 64] = [+ 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30,+ 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27,+ 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25,+];+const DES_E: [u8; 48] = [+ 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18,+ 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1,+];+const DES_P: [u8; 32] = [+ 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19,+ 13, 30, 6, 22, 11, 4, 25,+];+const DES_PC1: [u8; 56] = [+ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60,+ 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29,+ 21, 13, 5, 28, 20, 12, 4,+];+const DES_PC2: [u8; 48] = [+ 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52,+ 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32,+];+const DES_SHIFTS: [u8; 16] = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1];+const DES_S: [[[u8; 16]; 4]; 8] = [+ [+ [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],+ [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],+ [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],+ [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],+ ],+ [+ [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],+ [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],+ [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],+ [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],+ ],+ [+ [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],+ [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],+ [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],+ [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],+ ],+ [+ [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],+ [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],+ [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],+ [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],+ ],+ [+ [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],+ [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],+ [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],+ [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],+ ],+ [+ [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],+ [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],+ [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],+ [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],+ ],+ [+ [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],+ [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],+ [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],+ [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],+ ],+ [+ [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],+ [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],+ [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],+ [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],+ ],+];++fn des_permute(input: u64, input_bits: u8, table: &[u8]) -> u64 {+ table.iter().fold(0, |out, &bit| {+ (out << 1) | ((input >> (input_bits - bit)) & 1)+ })+}++fn des_round_keys(key: &[u8]) -> Result<[u64; 16], String> {+ if key.len() != 8 {+ return Err("DES key must be 8 bytes".into());+ }+ let key = u64::from_be_bytes(key.try_into().expect("checked DES key length"));+ let pc1 = des_permute(key, 64, &DES_PC1);+ let mut c = (pc1 >> 28) as u32;+ let mut d = pc1 as u32 & 0x0fff_ffff;+ let mut round_keys = [0u64; 16];+ for (i, &shift) in DES_SHIFTS.iter().enumerate() {+ c = ((c << shift) | (c >> (28 - shift))) & 0x0fff_ffff;+ d = ((d << shift) | (d >> (28 - shift))) & 0x0fff_ffff;+ round_keys[i] = des_permute((u64::from(c) << 28) | u64::from(d), 56, &DES_PC2);+ }+ Ok(round_keys)+}++fn des_f(right: u32, round_key: u64) -> u32 {+ let x = des_permute(u64::from(right), 32, &DES_E) ^ round_key;+ let mut out = 0u32;+ for (i, sbox) in DES_S.iter().enumerate() {+ let six = ((x >> (42 - i * 6)) & 0x3f) as u8;+ let row = ((six & 0x20) | ((six & 1) << 4)) >> 4;+ let col = (six >> 1) & 0x0f;+ out = (out << 4) | u32::from(sbox[row as usize][col as usize]);+ }+ des_permute(u64::from(out), 32, &DES_P) as u32+}++fn des_crypt_block(block: [u8; 8], round_keys: &[u64; 16], decrypt: bool) -> [u8; 8] {+ let ip = des_permute(u64::from_be_bytes(block), 64, &DES_IP);+ let mut left = (ip >> 32) as u32;+ let mut right = ip as u32;+ for round in 0..16 {+ let key = round_keys[if decrypt { 15 - round } else { round }];+ let next = left ^ des_f(right, key);+ left = right;+ right = next;+ }+ des_permute((u64::from(right) << 32) | u64::from(left), 64, &DES_FP).to_be_bytes()+}++fn decrypt_block_mode<F>(+ data: &[u8],+ iv: Option<&[u8]>,+ mode: &str,+ cipher: &str,+ mut decrypt: F,+) -> Result<Vec<u8>, String>+where+ F: FnMut([u8; 8]) -> [u8; 8],+{+ if data.is_empty() {+ return Err(format!("{cipher} ciphertext empty"));+ }+ if data.len() % 8 != 0 {+ return Err(format!(+ "{cipher} ciphertext length must be a multiple of 8"+ ));+ }+ match mode.to_ascii_lowercase().as_str() {+ "ecb" => Ok(data+ .chunks_exact(8)+ .flat_map(|chunk| decrypt(chunk.try_into().expect("exact block")))+ .collect()),+ "cbc" => {+ let iv = iv.ok_or_else(|| format!("{cipher}-CBC requires iv"))?;+ let mut prev: [u8; 8] = iv+ .try_into()+ .map_err(|_| format!("{cipher} IV must be 8 bytes"))?;+ let mut out = Vec::with_capacity(data.len());+ for chunk in data.chunks_exact(8) {+ let encrypted: [u8; 8] = chunk.try_into().expect("exact block");+ let mut plain = decrypt(encrypted);+ for i in 0..8 {+ plain[i] ^= prev[i];+ }+ out.extend_from_slice(&plain);+ prev = encrypted;+ }+ Ok(out)+ }+ other => Err(format!("unsupported {cipher} mode: {other}")),+ }+}++fn des_decrypt(data: &[u8], key: &[u8], iv: Option<&[u8]>, mode: &str) -> Result<Vec<u8>, String> {+ let round_keys = des_round_keys(key)?;+ decrypt_block_mode(data, iv, mode, "DES", |block| {+ des_crypt_block(block, &round_keys, true)+ })+}++fn triple_des_decrypt(+ data: &[u8],+ key: &[u8],+ iv: Option<&[u8]>,+ mode: &str,+) -> Result<Vec<u8>, String> {+ let (k1, k2, k3) = match key.len() {+ 16 => (&key[..8], &key[8..16], &key[..8]),+ 24 => (&key[..8], &key[8..16], &key[16..24]),+ _ => return Err("Triple-DES key must be 16 or 24 bytes".into()),+ };+ let k1 = des_round_keys(k1)?;+ let k2 = des_round_keys(k2)?;+ let k3 = des_round_keys(k3)?;+ decrypt_block_mode(data, iv, mode, "Triple-DES", |block| {+ let block = des_crypt_block(block, &k3, true);+ let block = des_crypt_block(block, &k2, false);+ des_crypt_block(block, &k1, true)+ })+}++struct Blowfish {+ p: [u32; 18],+ s: [[u32; 256]; 4],+}++impl Blowfish {+ fn new(key: &[u8]) -> Result<Self, String> {+ if !(1..=56).contains(&key.len()) {+ return Err("Blowfish key must be 1 to 56 bytes".into());+ }+ let mut state = Self {+ p: BLOWFISH_P_INIT,+ s: BLOWFISH_S_INIT,+ };+ for (i, p) in state.p.iter_mut().enumerate() {+ let mut word = 0u32;+ for j in 0..4 {+ word = (word << 8) | u32::from(key[(i * 4 + j) % key.len()]);+ }+ *p ^= word;+ }+ let mut block = (0, 0);+ for i in (0..18).step_by(2) {+ block = state.encrypt_words(block.0, block.1);+ state.p[i] = block.0;+ state.p[i + 1] = block.1;+ }+ for box_index in 0..4 {+ for i in (0..256).step_by(2) {+ block = state.encrypt_words(block.0, block.1);+ state.s[box_index][i] = block.0;+ state.s[box_index][i + 1] = block.1;+ }+ }+ Ok(state)+ }++ fn f(&self, x: u32) -> u32 {+ ((self.s[0][(x >> 24) as usize].wrapping_add(self.s[1][((x >> 16) & 0xff) as usize]))+ ^ self.s[2][((x >> 8) & 0xff) as usize])+ .wrapping_add(self.s[3][(x & 0xff) as usize])+ }++ fn encrypt_words(&self, mut left: u32, mut right: u32) -> (u32, u32) {+ for i in 0..16 {+ left ^= self.p[i];+ right ^= self.f(left);+ std::mem::swap(&mut left, &mut right);+ }+ std::mem::swap(&mut left, &mut right);+ (left ^ self.p[17], right ^ self.p[16])+ }++ fn decrypt_block(&self, block: [u8; 8]) -> [u8; 8] {+ let value = u64::from_be_bytes(block);+ let (mut left, mut right) = ((value >> 32) as u32, value as u32);+ for i in (2..18).rev() {+ left ^= self.p[i];+ right ^= self.f(left);+ std::mem::swap(&mut left, &mut right);+ }+ std::mem::swap(&mut left, &mut right);+ ((u64::from(left ^ self.p[0]) << 32) | u64::from(right ^ self.p[1])).to_be_bytes()+ }+}++fn blowfish_decrypt(+ data: &[u8],+ key: &[u8],+ iv: Option<&[u8]>,+ mode: &str,+) -> Result<Vec<u8>, String> {+ let cipher = Blowfish::new(key)?;+ decrypt_block_mode(data, iv, mode, "Blowfish", |block| {+ cipher.decrypt_block(block)+ })+}++fn printable_ratio(b: &[u8]) -> f32 {+ if b.is_empty() {+ return 0.0;+ }+ let n = b+ .iter()+ .filter(|&&c| (0x20..=0x7e).contains(&c) || c == b'\n' || c == b'\r' || c == b'\t')+ .count();+ n as f32 / b.len() as f32+}++fn parse_key(args: &serde_json::Value) -> Result<Vec<u8>, String> {+ if let Some(s) = args.get("key_hex").and_then(|v| v.as_str()) {+ return from_hex(s);+ }+ if let Some(s) = args.get("key").and_then(|v| v.as_str()) {+ if args+ .get("key_format")+ .and_then(|v| v.as_str())+ .unwrap_or("utf8")+ .eq_ignore_ascii_case("hex")+ {+ return from_hex(s);+ }+ return Ok(s.as_bytes().to_vec());+ }+ Err("missing key / key_hex".into())+}++fn from_charcode(data: &[u8], encoding: &str) -> Result<Vec<u8>, String> {+ let text =+ std::str::from_utf8(data).map_err(|_| "FromCharcode input is not UTF-8".to_string())?;+ let mut units = Vec::new();+ for part in text.split(|c: char| c == ',' || c == ';' || c.is_ascii_whitespace()) {+ if part.is_empty() {+ continue;+ }+ let part = part.trim();+ let value = part+ .strip_prefix("0x")+ .or_else(|| part.strip_prefix("0X"))+ .map(|v| u32::from_str_radix(v, 16))+ .unwrap_or_else(|| part.parse::<u32>())+ .map_err(|_| format!("invalid character code: {part}"))?;+ let ch =+ char::from_u32(value).ok_or_else(|| format!("invalid Unicode code point: {value}"))?;+ units.push(ch);+ }+ let decoded: String = units.into_iter().collect();+ match encoding.to_ascii_lowercase().as_str() {+ "utf8" | "utf-8" => Ok(decoded.into_bytes()),+ "utf16le" | "utf-16le" => Ok(decoded.encode_utf16().flat_map(u16::to_le_bytes).collect()),+ "utf16be" | "utf-16be" => Ok(decoded.encode_utf16().flat_map(u16::to_be_bytes).collect()),+ other => Err(format!("unsupported FromCharcode encoding: {other}")),+ }+}++fn url_decode(data: &[u8]) -> Result<Vec<u8>, String> {+ let mut out = Vec::with_capacity(data.len());+ let mut i = 0;+ while i < data.len() {+ match data[i] {+ b'+' => out.push(b' '),+ b'%' if i + 2 < data.len() => {+ let hex = std::str::from_utf8(&data[i + 1..i + 3])+ .map_err(|_| "invalid URL escape".to_string())?;+ out.push(+ u8::from_str_radix(hex, 16).map_err(|_| "invalid URL escape".to_string())?,+ );+ i += 2;+ }+ b'%' => return Err("truncated URL escape".into()),+ b => out.push(b),+ }+ i += 1;+ }+ Ok(out)+}++fn html_entity_decode(data: &[u8]) -> Result<Vec<u8>, String> {+ let text =+ std::str::from_utf8(data).map_err(|_| "HTML entity input is not UTF-8".to_string())?;+ let mut out = String::with_capacity(text.len());+ let mut rest = text;+ while let Some(start) = rest.find('&') {+ out.push_str(&rest[..start]);+ rest = &rest[start + 1..];+ let Some(end) = rest.find(';') else {+ out.push('&');+ out.push_str(rest);+ break;+ };+ let entity = &rest[..end];+ let decoded = match entity {+ "amp" => Some('&'),+ "lt" => Some('<'),+ "gt" => Some('>'),+ "quot" => Some('"'),+ "apos" | "#39" => Some('\''),+ _ if entity.starts_with("#x") || entity.starts_with("#X") => {+ u32::from_str_radix(&entity[2..], 16)+ .ok()+ .and_then(char::from_u32)+ }+ _ if entity.starts_with('#') => {+ entity[1..].parse::<u32>().ok().and_then(char::from_u32)+ }+ _ => None,+ };+ if let Some(ch) = decoded {+ out.push(ch);+ } else {+ out.push('&');+ out.push_str(entity);+ out.push(';');+ }+ rest = &rest[end + 1..];+ }+ if !rest.is_empty() {+ out.push_str(rest);+ }+ Ok(out.into_bytes())+}++fn chacha20(data: &[u8], key: &[u8], nonce: &[u8], counter: u32) -> Result<Vec<u8>, String> {+ if key.len() != 32 || nonce.len() != 12 {+ return Err("ChaCha20 requires a 32-byte key and 12-byte nonce".into());+ }+ let mut state = [0u32; 16];+ state[..4].copy_from_slice(&[0x6170_7865, 0x3320_646e, 0x7962_2d32, 0x6b20_6574]);+ for (i, word) in key.chunks_exact(4).enumerate() {+ state[4 + i] = u32::from_le_bytes(word.try_into().unwrap());+ }+ state[12] = counter;+ for (i, word) in nonce.chunks_exact(4).enumerate() {+ state[13 + i] = u32::from_le_bytes(word.try_into().unwrap());+ }+ let mut out = Vec::with_capacity(data.len());+ for chunk in data.chunks(64) {+ let mut x = state;+ for _ in 0..10 {+ quarter_round(&mut x, 0, 4, 8, 12);+ quarter_round(&mut x, 1, 5, 9, 13);+ quarter_round(&mut x, 2, 6, 10, 14);+ quarter_round(&mut x, 3, 7, 11, 15);+ quarter_round(&mut x, 0, 5, 10, 15);+ quarter_round(&mut x, 1, 6, 11, 12);+ quarter_round(&mut x, 2, 7, 8, 13);+ quarter_round(&mut x, 3, 4, 9, 14);+ }+ let mut stream = [0u8; 64];+ for i in 0..16 {+ stream[i * 4..i * 4 + 4].copy_from_slice(&x[i].wrapping_add(state[i]).to_le_bytes());+ }+ out.extend(chunk.iter().enumerate().map(|(i, b)| b ^ stream[i]));+ state[12] = state[12]+ .checked_add(1)+ .ok_or_else(|| "ChaCha20 counter exhausted".to_string())?;+ }+ Ok(out)+}++fn quarter_round(x: &mut [u32; 16], a: usize, b: usize, c: usize, d: usize) {+ x[a] = x[a].wrapping_add(x[b]);+ x[d] = (x[d] ^ x[a]).rotate_left(16);+ x[c] = x[c].wrapping_add(x[d]);+ x[b] = (x[b] ^ x[c]).rotate_left(12);+ x[a] = x[a].wrapping_add(x[b]);+ x[d] = (x[d] ^ x[a]).rotate_left(8);+ x[c] = x[c].wrapping_add(x[d]);+ x[b] = (x[b] ^ x[c]).rotate_left(7);+}++fn apply_op(data: &[u8], op: &BakeOp) -> Result<Vec<u8>, String> {+ let name = op.op.to_ascii_lowercase().replace([' ', '_'], "");+ match name.as_str() {+ "frombase64" | "base64" => b64_decode(data),+ "fromhex" | "hex" => {+ let s = std::str::from_utf8(data).map_err(|e| e.to_string())?;+ from_hex(s)+ }+ "fromcharcode" | "charcode" => from_charcode(+ data,+ op.args+ .get("encoding")+ .and_then(|v| v.as_str())+ .unwrap_or("utf8"),+ ),+ "urldecode" | "url" => url_decode(data),+ "htmlentitydecode" | "htmlentities" => html_entity_decode(data),+ "xor" => {+ let key = parse_key(&op.args)?;+ Ok(xor_key(data, &key))+ }+ "xorbrute" | "xorbruteforce" => {+ let mut best = data.to_vec();+ let mut best_score = printable_ratio(data);+ for k in 0u8..=255 {+ let cand = xor_key(data, &[k]);+ let score = printable_ratio(&cand);+ if score > best_score {+ best_score = score;+ best = cand;+ }+ }+ Ok(best)+ }+ "rc4" => {+ let key = parse_key(&op.args)?;+ rc4(data, &key)+ }+ "chacha20decrypt" | "chacha20" => {+ let key = parse_key(&op.args)?;+ let nonce = op+ .args+ .get("nonce_hex")+ .and_then(|v| v.as_str())+ .map(from_hex)+ .transpose()?+ .or_else(|| {+ op.args+ .get("nonce")+ .and_then(|v| v.as_str())+ .map(|s| s.as_bytes().to_vec())+ })+ .ok_or_else(|| "ChaCha20 requires nonce / nonce_hex".to_string())?;+ let counter = op.args.get("counter").and_then(|v| v.as_u64()).unwrap_or(0);+ let counter =+ u32::try_from(counter).map_err(|_| "ChaCha20 counter exceeds u32".to_string())?;+ chacha20(data, &key, &nonce, counter)+ }+ "aesdecrypt" | "aes" => {+ let key = parse_key(&op.args)?;+ let mode = op+ .args+ .get("mode")+ .and_then(|v| v.as_str())+ .unwrap_or("cbc");+ let iv = if let Some(s) = op.args.get("iv_hex").and_then(|v| v.as_str()) {+ Some(from_hex(s)?)+ } else if let Some(s) = op.args.get("iv").and_then(|v| v.as_str()) {+ Some(s.as_bytes().to_vec())+ } else {+ None+ };+ aes_decrypt(data, &key, iv.as_deref(), mode)+ }+ "desdecrypt" | "des" => {+ let key = parse_key(&op.args)?;+ let mode = op+ .args+ .get("mode")+ .and_then(|v| v.as_str())+ .unwrap_or("cbc");+ let iv = op+ .args+ .get("iv_hex")+ .and_then(|v| v.as_str())+ .map(from_hex)+ .transpose()?+ .or_else(|| {+ op.args+ .get("iv")+ .and_then(|v| v.as_str())+ .map(|s| s.as_bytes().to_vec())+ });+ des_decrypt(data, &key, iv.as_deref(), mode)+ }+ "tripledesdecrypt" | "des3decrypt" | "3desdecrypt" | "tripledes" | "des3" | "3des" => {+ let key = parse_key(&op.args)?;+ let mode = op+ .args+ .get("mode")+ .and_then(|v| v.as_str())+ .unwrap_or("cbc");+ let iv = op+ .args+ .get("iv_hex")+ .and_then(|v| v.as_str())+ .map(from_hex)+ .transpose()?+ .or_else(|| {+ op.args+ .get("iv")+ .and_then(|v| v.as_str())+ .map(|s| s.as_bytes().to_vec())+ });+ triple_des_decrypt(data, &key, iv.as_deref(), mode)+ }+ "blowfishdecrypt" | "blowfish" => {+ let key = parse_key(&op.args)?;+ let mode = op+ .args+ .get("mode")+ .and_then(|v| v.as_str())+ .unwrap_or("cbc");+ let iv = op+ .args+ .get("iv_hex")+ .and_then(|v| v.as_str())+ .map(from_hex)+ .transpose()?+ .or_else(|| {+ op.args+ .get("iv")+ .and_then(|v| v.as_str())+ .map(|s| s.as_bytes().to_vec())+ });+ blowfish_decrypt(data, &key, iv.as_deref(), mode)+ }+ "rot13" => Ok(data+ .iter()+ .map(|&c| match c {+ b'A'..=b'M' | b'a'..=b'm' => c + 13,+ b'N'..=b'Z' | b'n'..=b'z' => c - 13,+ _ => c,+ })+ .collect()),+ "reverse" => {+ let mut v = data.to_vec();+ v.reverse();+ Ok(v)+ }+ "decodeutf16le" | "utf16le" => {+ if data.len() < 2 {+ return Ok(Vec::new());+ }+ let u16s: Vec<u16> = data+ .chunks_exact(2)+ .map(|c| u16::from_le_bytes([c[0], c[1]]))+ .collect();+ Ok(String::from_utf16_lossy(&u16s).into_bytes())+ }+ "gunzip" | "gzip" => gunzip(data),+ "inflate" | "zlib" | "deflate" => inflate_auto(data),+ other => Err(format!("unknown op: {other}")),+ }+}++/// Apply an ordered recipe to input bytes.+pub fn bake(input: &[u8], ops: &[BakeOp]) -> BakeResult {+ let mut cur = input.to_vec();+ let mut applied = Vec::new();+ for op in ops {+ match apply_op(&cur, op) {+ Ok(next) => {+ applied.push(op.op.clone());+ cur = next;+ }+ Err(e) => {+ return BakeResult {+ ok: false,+ output_hex: to_hex(&cur),+ output_utf8: None,+ message: e,+ recipe_applied: applied,+ };+ }+ }+ }+ let utf8 = String::from_utf8(cur.clone()).ok();+ BakeResult {+ ok: true,+ output_hex: to_hex(&cur),+ output_utf8: utf8,+ message: format!("applied {} op(s)", applied.len()),+ recipe_applied: applied,+ }+}++/// Try common peels; return best printable result + recipe.+pub fn magic(input: &[u8], depth: usize) -> BakeResult {+ magic_with_crib(input, depth, None)+}++/// Try common peels, increasing a candidate's score when it contains `crib`.+///+/// Search depth is clamped to four and candidates below the input printable ratio+/// are pruned, so this is a bounded heuristic rather than a decrypt oracle.+pub fn magic_with_crib(input: &[u8], depth: usize, crib: Option<&str>) -> BakeResult {+ let depth = depth.clamp(1, 4);+ let mut best = BakeResult {+ ok: true,+ output_hex: to_hex(input),+ output_utf8: String::from_utf8(input.to_vec()).ok(),+ message: "identity".into(),+ recipe_applied: vec![],+ };+ let crib = crib.filter(|s| !s.is_empty());+ let mut best_score = printable_ratio(input)+ + crib+ .filter(|needle| {+ std::str::from_utf8(input)+ .ok()+ .is_some_and(|s| s.contains(needle))+ })+ .map_or(0.0, |_| 0.25);++ let candidates: Vec<Vec<BakeOp>> = vec![+ vec![BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ }],+ vec![BakeOp {+ op: "FromHex".into(),+ args: serde_json::json!({}),+ }],+ vec![BakeOp {+ op: "XORBrute".into(),+ args: serde_json::json!({}),+ }],+ vec![BakeOp {+ op: "ROT13".into(),+ args: serde_json::json!({}),+ }],+ vec![+ BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "DecodeUTF16LE".into(),+ args: serde_json::json!({}),+ },+ ],+ vec![+ BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "XORBrute".into(),+ args: serde_json::json!({}),+ },+ ],+ vec![+ BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "Gunzip".into(),+ args: serde_json::json!({}),+ },+ ],+ vec![+ BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "Inflate".into(),+ args: serde_json::json!({}),+ },+ ],+ vec![+ BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "Gunzip".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "XORBrute".into(),+ args: serde_json::json!({}),+ },+ ],+ ];++ for recipe in candidates {+ if recipe.len() > depth {+ continue;+ }+ let r = bake(input, &recipe);+ if !r.ok {+ continue;+ }+ let bytes = from_hex(&r.output_hex).unwrap_or_default();+ let printable = printable_ratio(&bytes);+ if printable < printable_ratio(input) {+ continue;+ }+ let score = printable+ + crib+ .filter(|needle| {+ std::str::from_utf8(&bytes)+ .ok()+ .is_some_and(|s| s.contains(needle))+ })+ .map_or(0.0, |_| 0.25);+ if score > best_score {+ best_score = score;+ best = r;+ best.message = format!("magic score={best_score:.2}");+ }+ }+ best+}++/// Extract ASCII URLs, IPv4 addresses, and email addresses from bytes.+pub fn extract_iocs(data: &[u8]) -> Vec<String> {+ let s = String::from_utf8_lossy(data);+ let mut out = Vec::new();+ for token in s.split(|c: char| c.is_whitespace() || c == '"' || c == '\'') {+ if token.starts_with("http://") || token.starts_with("https://") {+ out.push(token.to_string());+ }+ // crude IPv4+ let parts: Vec<_> = token.split('.').collect();+ if parts.len() == 4 && parts.iter().all(|p| p.parse::<u8>().is_ok()) {+ out.push(token.to_string());+ }+ if let Some((local, domain)) = token.split_once('@') {+ if !local.is_empty()+ && domain.contains('.')+ && local+ .bytes()+ .all(|c| c.is_ascii_alphanumeric() || b".!#$%&'*+/=?^_`{|}~-".contains(&c))+ && domain+ .bytes()+ .all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-')+ {+ out.push(token.to_string());+ }+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn base64_then_xor() {+ // "Hello" xor 0x41 → then base64 of that+ let plain = b"Hello";+ let xored: Vec<u8> = plain.iter().map(|b| b ^ 0x41).collect();+ // bake reverse: we have xored; XOR with 0x41 recovers+ let r = bake(+ &xored,+ &[BakeOp {+ op: "XOR".into(),+ args: serde_json::json!({"key_hex": "41"}),+ }],+ );+ assert!(r.ok);+ assert_eq!(r.output_utf8.as_deref(), Some("Hello"));+ }++ #[test]+ fn from_base64() {+ let r = bake(+ b"SGVsbG8=",+ &[BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ }],+ );+ assert_eq!(r.output_utf8.as_deref(), Some("Hello"));+ }++ #[test]+ fn gunzip_op() {+ let payload = b"Hello";+ let mut gz = vec![0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff];+ gz.push(0x01);+ gz.extend_from_slice(&(payload.len() as u16).to_le_bytes());+ gz.extend_from_slice(&(!(payload.len() as u16)).to_le_bytes());+ gz.extend_from_slice(payload);+ gz.extend_from_slice(&[0u8; 8]);+ let r = bake(+ &gz,+ &[BakeOp {+ op: "Gunzip".into(),+ args: serde_json::json!({}),+ }],+ );+ assert!(r.ok, "{}", r.message);+ assert_eq!(r.output_utf8.as_deref(), Some("Hello"));+ }++ #[test]+ fn base64_gunzip_xor_golden() {+ let r = bake(+ b"H4sIAAAAAAAC/+NXMTJVUU1U09NVVdEHAARoRhcNAAAA",+ &[+ BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "Gunzip".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "XOR".into(),+ args: serde_json::json!({"key_hex": "41"}),+ },+ ],+ );+ assert!(r.ok, "{}", r.message);+ assert_eq!(r.output_utf8.as_deref(), Some("Nested golden"));+ }++ #[test]+ fn decodes_textual_operations() {+ assert_eq!(+ apply_op(+ b"72, 101, 108, 108, 111",+ &BakeOp {+ op: "FromCharcode".into(),+ args: serde_json::json!({})+ }+ )+ .unwrap(),+ b"Hello"+ );+ assert_eq!(+ apply_op(+ b"a%2Bb+%26",+ &BakeOp {+ op: "UrlDecode".into(),+ args: serde_json::json!({})+ }+ )+ .unwrap(),+ b"a+b &"+ );+ assert_eq!(+ apply_op(+ b"<x>!",+ &BakeOp {+ op: "HtmlEntityDecode".into(),+ args: serde_json::json!({})+ }+ )+ .unwrap(),+ b"<x>!"+ );+ }++ #[test]+ fn aes_cbc_nist_golden() {+ let ciphertext = from_hex("7649abac8119b246cee98e9b12e9197d").unwrap();+ let key = from_hex("2b7e151628aed2a6abf7158809cf4f3c").unwrap();+ let iv = from_hex("000102030405060708090a0b0c0d0e0f").unwrap();+ assert_eq!(+ aes_decrypt(&ciphertext, &key, Some(&iv), "cbc").unwrap(),+ from_hex("6bc1bee22e409f96e93d7e117393172a").unwrap()+ );+ }++ #[test]+ fn aes_nist_ecb_ctr_cfb_ofb_and_unauthenticated_gcm_paths() {+ let key = from_hex("2b7e151628aed2a6abf7158809cf4f3c").unwrap();+ let plain = from_hex("6bc1bee22e409f96e93d7e117393172a").unwrap();+ let iv = from_hex("000102030405060708090a0b0c0d0e0f").unwrap();+ assert_eq!(+ aes_decrypt(&from_hex("3ad77bb40d7a3660a89ecaf32466ef97").unwrap(), &key, None, "ecb").unwrap(),+ plain+ );+ assert_eq!(+ aes_decrypt(+ &from_hex("874d6191b620e3261bef6864990db6ce").unwrap(),+ &key,+ Some(&from_hex("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff").unwrap()),+ "ctr",+ )+ .unwrap(),+ plain+ );+ assert_eq!(+ aes_decrypt(&from_hex("3b3fd92eb72dad20333449f8e83cfb4a").unwrap(), &key, Some(&iv), "cfb").unwrap(),+ plain+ );+ assert_eq!(+ aes_decrypt(&from_hex("3b3fd92eb72dad20333449f8e83cfb4a").unwrap(), &key, Some(&iv), "ofb").unwrap(),+ plain+ );++ // GCM uses the counter-mode plaintext path only. It deliberately does not+ // accept or validate an authentication tag, so this is not authentication.+ assert_eq!(+ aes_decrypt(+ &from_hex("0388dace60b6a392f328c2b971b2fe78").unwrap(),+ &vec![0; 16],+ Some(&vec![0; 12]),+ "gcm",+ )+ .unwrap(),+ vec![0; 16]+ );+ }++ #[test]+ fn des_ecb_known_answer() {+ let key = from_hex("133457799bbcdff1").unwrap();+ let ciphertext = from_hex("85e813540f0ab405").unwrap();+ assert_eq!(+ des_decrypt(&ciphertext, &key, None, "ecb").unwrap(),+ from_hex("0123456789abcdef").unwrap()+ );+ }++ #[test]+ fn triple_des_cbc_known_answer() {+ let key = from_hex("0123456789abcdeff1e0d3c2b5a49786fedcba9876543210").unwrap();+ let iv = from_hex("fedcba9876543210").unwrap();+ let ciphertext =+ from_hex("3fe301c962ac01d02213763c1cbd4cdc799657c064ecf5d41c673812cfde9675").unwrap();+ assert_eq!(+ triple_des_decrypt(&ciphertext, &key, Some(&iv), "cbc").unwrap(),+ from_hex("37363534333231204e6f77206973207468652074696d6520666f722000000000").unwrap()+ );+ }++ #[test]+ fn blowfish_ecb_known_answer() {+ let ciphertext = from_hex("324ed0fef413a203").unwrap();+ assert_eq!(+ blowfish_decrypt(&ciphertext, b"abcdefghijklmnopqrstuvwxyz", None, "ecb").unwrap(),+ b"BLOWFISH"+ );+ }++ #[test]+ fn recipe_text_transforms_iocs_and_inflate_auto_paths() {+ let decode = |input: &[u8], op: &str| {+ bake(+ input,+ &[BakeOp {+ op: op.into(),+ args: serde_json::json!({}),+ }],+ )+ };+ assert_eq!(decode(b"48656c6c6f", "FromHex").output_utf8.as_deref(), Some("Hello"));+ assert_eq!(decode(b"Uryyb", "ROT13").output_utf8.as_deref(), Some("Hello"));+ assert_eq!(decode(b"olleH", "Reverse").output_utf8.as_deref(), Some("Hello"));+ assert_eq!(+ decode(b"H\0e\0l\0l\0o\0", "DecodeUTF16LE").output_utf8.as_deref(),+ Some("Hello")+ );+ let brute = decode(b"\xe2\xcf\xc6\xc6\xc5\x8b", "XORBrute");+ assert!(brute.ok);+ assert!(brute.output_utf8.is_some(), "{brute:?}");++ // zlib header + stored DEFLATE "Hello" block + Adler-32.+ assert_eq!(+ decode(+ &[0x78, 0x01, 0x01, 0x05, 0x00, 0xfa, 0xff, b'H', b'e', b'l', b'l', b'o', 0x05, 0x8c, 0x01, 0xf5],+ "Inflate",+ )+ .output_utf8+ .as_deref(),+ Some("Hello")+ );+ let iocs = extract_iocs(b"visit https://example.test/path and 203.0.113.7");+ assert!(iocs.contains(&"https://example.test/path".to_string()));+ assert!(iocs.contains(&"203.0.113.7".to_string()));+ }++ #[test]+ fn chacha20_rfc8439_golden() {+ let key =+ from_hex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap();+ let nonce = from_hex("000000000000004a00000000").unwrap();+ let plaintext = b"Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.";+ let output = chacha20(plaintext, &key, &nonce, 1).unwrap();+ assert_eq!(+ to_hex(&output),+ concat!(+ "6e2e359a2568f98041ba0728dd0d6981e97e7aec1d4360c20a27afccfd9fae0b",+ "f91b65c5524733ab8f593dabcd62b3571639d624e65152ab8f530c359f0861d8",+ "07ca0dbf500d6a6156a38e088a22b65e52bc514d16ccf806818ce91ab7793736",+ "5af90bbf74a35be6b40b8eedf2785e42874d"+ )+ );+ }++ #[test]+ fn crib_and_email_ioc() {+ let result = magic_with_crib(b"U2VjcmV0IGNyaWI=", 1, Some("crib"));+ assert_eq!(result.output_utf8.as_deref(), Some("Secret crib"));+ assert!(extract_iocs(b"contact [email protected] now")+ .contains(&"[email protected]".to_string()));+ }+}diff --git a/crates/ghidrust-core/src/disasm.rs b/crates/ghidrust-core/src/disasm.rsindex 62c999e..6f14252 100644--- a/crates/ghidrust-core/src/disasm.rs+++ b/crates/ghidrust-core/src/disasm.rs@@ -6,13 +6,11 @@use crate::error::{Error, Result};use crate::machine::{arch_mode_for_program, default_arch_mode};use crate::program::Program;-use ghidrust_decode::{- Engine, MnemOverride, Opt, SkipdataConfig, Syntax,-};+pub use ghidrust_decode::{decode_one, Instruction};use ghidrust_decode::{Arch, Mode};+use ghidrust_decode::{Engine, MnemOverride, Opt, SkipdataConfig, Syntax};use serde::Serialize;use std::collections::{HashSet, VecDeque};-pub use ghidrust_decode::{decode_one, Instruction};/// Optional engine overrides for a disassembly pass.#[derive(Debug, Clone, Default)]@@ -116,11 +114,11 @@ fn apply_engine_opts(engine: &mut Engine, opts: &DisasmEngineOpts) -> Result<()>#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "snake_case")]pub enum DisasmMode {- /// Linear count-walk clamped to `[start, bound_end)` when set; stop on int3 padding.+ /// Linear count-walk clamped to `[start, bound_end)` when set; stop on int3 padding.Bounded,- /// Follow fallthrough and branch targets; never leave `[start, bound_end)` when bound set.+ /// Follow fallthrough and branch targets; never leave `[start, bound_end)` when bound set.Flow,- /// Legacy count-walk (no bound / int3 / seed stops).+ /// Legacy count-walk (no bound / int3 / seed stops).Linear,}@@ -146,7 +144,7 @@ pub fn disassemble_at_opts() -> Result<Instruction> {let bytes = prog.read_va(va, 15)- .ok_or_else(|| Error::OutOfBounds(format!("no bytes at {va:#x}")))?;+ .ok_or_else(|| Error::OutOfBounds(format!("no bytes at {va:#x}")))?;let mut engine = open_engine_for(prog, engine_opts)?;engine.disasm_one(&bytes, va)@@ -161,17 +159,17 @@ pub fn disassemble_range(prog: &Program, start: u64, max_insns: usize) -> Result#[derive(Debug, Clone, Serialize)]pub struct DisasmRangeResult {pub insns: Vec<Instruction>,- /// Number of undecodable byte positions skipped (soft-fail holes).+ /// Number of undecodable byte positions skipped (soft-fail holes).pub decode_gaps: usize,- /// First gap VA when any gaps were skipped.+ /// First gap VA when any gaps were skipped.pub first_gap_va: Option<u64>,- /// Why the walk stopped.+ /// Why the walk stopped.pub stop_reason: DisasmStopReason,- /// Containing / resolved function entry when known.- #[serde(skip_serializing_if = "Option::is_none")]+ /// Containing / resolved function entry when known.+ #[serde(skip_serializing_if = "Option::is_none")]pub entry: Option<u64>,- /// Function / bound end when known.- #[serde(skip_serializing_if = "Option::is_none")]+ /// Function / bound end when known.+ #[serde(skip_serializing_if = "Option::is_none")]pub end: Option<u64>,}@@ -206,15 +204,7 @@ pub fn disassemble_range_ex(mode: DisasmMode,bound_end: Option<u64>,) -> Result<DisasmRangeResult> {- disassemble_range_ex_opts(- prog,- start,- max_insns,- skip_bad,- mode,- bound_end,- None,- )+ disassemble_range_ex_opts(prog, start, max_insns, skip_bad, mode, bound_end, None)}/// Extended disassembly with optional engine overrides.@@ -236,17 +226,15 @@ pub fn disassemble_range_ex_opts(let mut result = match mode {DisasmMode::Linear => disasm_linear(prog, &mut engine, start, max_insns, skip_bad)?,- DisasmMode::Bounded => {- disasm_bounded(- prog,- &mut engine,- start,- max_insns,- skip_bad,- bound_end,- self_entry,- )?- }+ DisasmMode::Bounded => disasm_bounded(+ prog,+ &mut engine,+ start,+ max_insns,+ skip_bad,+ bound_end,+ self_entry,+ )?,DisasmMode::Flow => disasm_flow(prog,&mut engine,@@ -265,7 +253,7 @@ pub fn disassemble_range_ex_opts(fn disasm_at_engine(prog: &Program, engine: &mut Engine, va: u64) -> Result<Instruction> {let bytes = prog.read_va(va, 15)- .ok_or_else(|| Error::OutOfBounds(format!("no bytes at {va:#x}")))?;+ .ok_or_else(|| Error::OutOfBounds(format!("no bytes at {va:#x}")))?;engine.disasm_one(&bytes, va).map_err(|e| Error::Decode(e.to_string()))@@ -312,7 +300,7 @@ fn disasm_linear(}}if out.is_empty() {- return Err(Error::Decode(format!("no instructions at {start:#x}")));+ return Err(Error::Decode(format!("no instructions at {start:#x}")));}if out.len() >= max_insns {stop_reason = DisasmStopReason::Count;@@ -367,7 +355,7 @@ fn disasm_bounded(Ok(insn) => {let next = va.wrapping_add(insn.length.max(1) as u64);if let Some(end) = bound_end {- // Instruction must start inside the bound; do not walk past end.+ // Instruction must start inside the bound; do not walk past end.if va >= end {stop_reason = DisasmStopReason::FunctionEnd;break;@@ -391,7 +379,7 @@ fn disasm_bounded(}}if out.is_empty() {- return Err(Error::Decode(format!("no instructions at {start:#x}")));+ return Err(Error::Decode(format!("no instructions at {start:#x}")));}if out.len() >= max_insns && stop_reason == DisasmStopReason::Count {stop_reason = DisasmStopReason::Count;@@ -437,7 +425,7 @@ fn disasm_flow(}if va != start && is_next_seed(prog, va, self_entry) {if out.is_empty() {- // Should not happen for start; keep scanning other paths.+ // Should not happen for start; keep scanning other paths.continue;}stop_reason = DisasmStopReason::NextSeed;@@ -486,7 +474,7 @@ fn disasm_flow(}if out.is_empty() {- return Err(Error::Decode(format!("no instructions at {start:#x}")));+ return Err(Error::Decode(format!("no instructions at {start:#x}")));}if out.len() >= max_insns {stop_reason = DisasmStopReason::Count;@@ -498,7 +486,7 @@ fn disasm_flow({stop_reason = DisasmStopReason::FunctionEnd;}- // Stable address order for deterministic listings.+ // Stable address order for deterministic listings.out.sort_by_key(|i| i.address);out.dedup_by_key(|i| i.address);Ok(DisasmRangeResult {@@ -528,41 +516,41 @@ fn is_next_seed(prog: &Program, va: u64, self_entry: Option<u64>) -> bool {fn is_terminal_transfer(mnem: &str) -> bool {matches!(mnem,- "jmp" | "jmpq" | "ret" | "retn" | "retq" | "iret" | "iretd" | "iretq"+ "jmp" | "jmpq" | "ret" | "retn" | "retq" | "iret" | "iretd" | "iretq")}fn is_flow_mnemonic(mnem: &str) -> bool {matches!(mnem,- "call"- | "callq"- | "jmp"- | "jmpq"- | "je"- | "jne"- | "jz"- | "jnz"- | "jl"- | "jle"- | "jg"- | "jge"- | "ja"- | "jae"- | "jb"- | "jbe"- | "jo"- | "jno"- | "js"- | "jns"- | "jp"- | "jnp"- | "jcxz"- | "jecxz"- | "jrcxz"- | "loop"- | "loope"- | "loopne"+ "call"+ | "callq"+ | "jmp"+ | "jmpq"+ | "je"+ | "jne"+ | "jz"+ | "jnz"+ | "jl"+ | "jle"+ | "jg"+ | "jge"+ | "ja"+ | "jae"+ | "jb"+ | "jbe"+ | "jo"+ | "jno"+ | "js"+ | "jns"+ | "jp"+ | "jnp"+ | "jcxz"+ | "jecxz"+ | "jrcxz"+ | "loop"+ | "loope"+ | "loopne")}@@ -570,9 +558,9 @@ fn flow_targets(insn: &Instruction) -> Vec<u64> {if !is_flow_mnemonic(&insn.mnemonic) {return Vec::new();}- // Absolute hex / RIP-relative targets from operand text.+ // Absolute hex / RIP-relative targets from operand text.let mut out = crate::xrefs::instruction_targets(insn);- // Prefer direct control-flow immediates; drop self-address noise.+ // Prefer direct control-flow immediates; drop self-address noise.out.retain(|t| *t != insn.address);out}@@ -586,31 +574,31 @@ mod tests {fn decode_push_rbp_mov_rbp_rsp() {let b = [0x55, 0x48, 0x89, 0xe5];let i0 = decode_one(&b, 0x1000).unwrap();- assert_eq!(i0.mnemonic, "push");- assert_eq!(i0.operands, "rbp");+ assert_eq!(i0.mnemonic, "push");+ assert_eq!(i0.operands, "rbp");assert_eq!(i0.length, 1);let i1 = decode_one(&b[1..], 0x1001).unwrap();- assert_eq!(i1.mnemonic, "mov");- assert_eq!(i1.operands, "rbp, rsp");+ assert_eq!(i1.mnemonic, "mov");+ assert_eq!(i1.operands, "rbp, rsp");}#[test]fn decode_xor_eax_eax_ret() {let b = [0x31, 0xc0, 0xc3];let i0 = decode_one(&b, 0).unwrap();- assert_eq!(i0.mnemonic, "xor");- assert_eq!(i0.operands, "eax, eax");+ assert_eq!(i0.mnemonic, "xor");+ assert_eq!(i0.operands, "eax, eax");let i1 = decode_one(&b[2..], 2).unwrap();- assert_eq!(i1.mnemonic, "ret");+ assert_eq!(i1.mnemonic, "ret");}#[test]fn skip_bad_continues_after_hole() {- let mut prog = Program::new("t".into(), "PE32+");- // 0x06 is invalid in long mode; then xor eax,eax; ret+ let mut prog = Program::new("t".into(), "PE32+");+ // 0x06 is invalid in long mode; then xor eax,eax; retlet bytes = vec![0x06, 0x31, 0xc0, 0xc3];prog.blocks.push(MemoryBlock {- name: ".text".into(),+ name: ".text".into(),va: 0x1000,size: bytes.len() as u64,bytes,@@ -622,18 +610,18 @@ mod tests {assert!(listing.decode_gaps >= 1);assert_eq!(listing.first_gap_va, Some(0x1000));assert!(- listing.insns.iter().any(|i| i.mnemonic == "xor"),- "{:?}",+ listing.insns.iter().any(|i| i.mnemonic == "xor"),+ "{:?}",listing.insns);- assert!(listing.insns.iter().any(|i| i.mnemonic == "ret"));+ assert!(listing.insns.iter().any(|i| i.mnemonic == "ret"));assert_eq!(listing.stop_reason, DisasmStopReason::Count);}#[test]fn bounded_excludes_adjacent_sibling_function() {- // fn_a: push rbp; mov rbp, rsp; ret; int3; int3- // fn_b: xor eax, eax; ret+ // fn_a: push rbp; mov rbp, rsp; ret; int3; int3+ // fn_b: xor eax, eax; retlet mut bytes = vec![0x55, 0x48, 0x89, 0xe5, 0xc3, 0xcc, 0xcc, 0x31, 0xc0, 0xc3];let base = 0x140001000u64;let fn_a_entry = base;@@ -641,9 +629,9 @@ mod tests {let fn_b_entry = base + 7;let fn_b_end = base + bytes.len() as u64;- let mut prog = Program::new("t".into(), "PE32+");+ let mut prog = Program::new("t".into(), "PE32+");prog.blocks.push(MemoryBlock {- name: ".text".into(),+ name: ".text".into(),va: base,size: bytes.len() as u64,bytes: std::mem::take(&mut bytes),@@ -653,10 +641,10 @@ mod tests {});prog.analysis.functions- .push(FunctionInfo::new(fn_a_entry, fn_a_end, "fn_a"));+ .push(FunctionInfo::new(fn_a_entry, fn_a_end, "fn_a"));prog.analysis.functions- .push(FunctionInfo::new(fn_b_entry, fn_b_end, "fn_b"));+ .push(FunctionInfo::new(fn_b_entry, fn_b_end, "fn_b"));let listing = disassemble_range_ex(&prog,@@ -670,21 +658,21 @@ mod tests {assert!(listing.insns.iter().all(|i| i.address < fn_b_entry),- "bounded listing leaked into sibling: {:?}",+ "bounded listing leaked into sibling: {:?}",listing.insns);assert!(- !listing.insns.iter().any(|i| i.mnemonic == "xor"),- "sibling xor must be excluded: {:?}",+ !listing.insns.iter().any(|i| i.mnemonic == "xor"),+ "sibling xor must be excluded: {:?}",listing.insns);- assert!(listing.insns.iter().any(|i| i.mnemonic == "ret"));+ assert!(listing.insns.iter().any(|i| i.mnemonic == "ret"));assert!(matches!(listing.stop_reason,DisasmStopReason::FunctionEnd | DisasmStopReason::Int3 | DisasmStopReason::NextSeed),- "stop_reason={:?}",+ "stop_reason={:?}",listing.stop_reason);assert_eq!(listing.entry, Some(fn_a_entry));@@ -693,9 +681,9 @@ mod tests {#[test]fn int3_padding_helper() {- let mut prog = Program::new("t".into(), "PE32+");+ let mut prog = Program::new("t".into(), "PE32+");prog.blocks.push(MemoryBlock {- name: ".text".into(),+ name: ".text".into(),va: 0x1000,size: 4,bytes: vec![0xcc, 0xcc, 0xc3, 0x90],diff --git a/crates/ghidrust-core/src/edits.rs b/crates/ghidrust-core/src/edits.rsindex 8603c32..0a382d7 100644--- a/crates/ghidrust-core/src/edits.rs+++ b/crates/ghidrust-core/src/edits.rs@@ -192,10 +192,7 @@ mod comments_serde {de: D,) -> Result<BTreeMap<(u64, CommentKind), String>, D::Error> {let rows: Vec<Row> = Vec::deserialize(de)?;- Ok(rows- .into_iter()- .map(|r| ((r.va, r.kind), r.text))- .collect())+ Ok(rows.into_iter().map(|r| ((r.va, r.kind), r.text)).collect())}}@@ -405,10 +402,7 @@ impl ProgramEdits {return;}self.all_function_tags.insert(tag.clone());- self.function_tags- .entry(entry)- .or_default()- .insert(tag);+ self.function_tags.entry(entry).or_default().insert(tag);}/// Remove `tag` from the function at `entry`. Does not remove the tag from@@ -509,16 +503,52 @@ impl Program {/// Built-in data types exposes in the "BuiltInTypes" archive (subset relevant/// to Ghidrust's Stage-0 rendering). Ordered as shows them in the DTM.pub const BUILTIN_TYPES: &[&str] = &[- "void", "bool",- "byte", "sbyte", "word", "sword", "dword", "sdword", "qword", "sqword",- "int8_t", "uint8_t", "int16_t", "uint16_t", "int32_t", "uint32_t",- "int64_t", "uint64_t",- "char", "uchar", "wchar_t", "wchar16", "wchar32",- "short", "ushort", "int", "uint", "long", "ulong", "longlong", "ulonglong",- "float", "double", "longdouble",- "pointer", "pointer32", "pointer64",- "undefined", "undefined1", "undefined2", "undefined4", "undefined8",- "string", "unicode", "TerminatedCString", "TerminatedUnicode",+ "void",+ "bool",+ "byte",+ "sbyte",+ "word",+ "sword",+ "dword",+ "sdword",+ "qword",+ "sqword",+ "int8_t",+ "uint8_t",+ "int16_t",+ "uint16_t",+ "int32_t",+ "uint32_t",+ "int64_t",+ "uint64_t",+ "char",+ "uchar",+ "wchar_t",+ "wchar16",+ "wchar32",+ "short",+ "ushort",+ "int",+ "uint",+ "long",+ "ulong",+ "longlong",+ "ulonglong",+ "float",+ "double",+ "longdouble",+ "pointer",+ "pointer32",+ "pointer64",+ "undefined",+ "undefined1",+ "undefined2",+ "undefined4",+ "undefined8",+ "string",+ "unicode",+ "TerminatedCString",+ "TerminatedUnicode",];#[cfg(test)]@@ -542,7 +572,9 @@ mod tests {e.set_comment(0x1000, CommentKind::Plate, "**PLATE**");let all = e.comments_at(0x1000);assert_eq!(all.len(), 2);- assert!(all.iter().any(|(k, t)| *k == CommentKind::Eol && *t == "eol!"));+ assert!(all+ .iter()+ .any(|(k, t)| *k == CommentKind::Eol && *t == "eol!"));e.set_comment(0x1000, CommentKind::Eol, "");assert_eq!(e.comments_at(0x1000).len(), 1);}@@ -675,7 +707,9 @@ mod tests {#[test]fn builtin_types_include_essentials() {- let want = ["void", "byte", "word", "dword", "qword", "char", "int", "pointer"];+ let want = [+ "void", "byte", "word", "dword", "qword", "char", "int", "pointer",+ ];for w in want {assert!(BUILTIN_TYPES.contains(&w), "missing builtin type {w}");}diff --git a/crates/ghidrust-core/src/elf.rs b/crates/ghidrust-core/src/elf.rsindex 3a653a4..deee29c 100644--- a/crates/ghidrust-core/src/elf.rs+++ b/crates/ghidrust-core/src/elf.rs@@ -135,7 +135,9 @@ pub fn load_elf(data: &[u8], name: impl Into<String>) -> Result<Program> {let p_filesz = rdu64(data, off + 32)? as usize;let p_memsz = rdu64(data, off + 40)? as usize;let mut bytes = vec![0u8; p_memsz];- let n = p_filesz.min(data.len().saturating_sub(p_offset)).min(p_memsz);+ let n = p_filesz+ .min(data.len().saturating_sub(p_offset))+ .min(p_memsz);if n > 0 {bytes[..n].copy_from_slice(&data[p_offset..p_offset + n]);}diff --git a/crates/ghidrust-core/src/gpu_analyzers/engine.rs b/crates/ghidrust-core/src/gpu_analyzers/engine.rsindex b123498..02d0330 100644--- a/crates/ghidrust-core/src/gpu_analyzers/engine.rs+++ b/crates/ghidrust-core/src/gpu_analyzers/engine.rs@@ -107,14 +107,16 @@ pub fn run_kernel(match caught {Ok(Ok(r)) => return r,Ok(Err(reason)) => {- let mut r = run_kernel_cpu_fallback(hay, kind, needle, image_base, image_end, wall0);+ let mut r =+ run_kernel_cpu_fallback(hay, kind, needle, image_base, image_end, wall0);r.backend = "cpu_kernel_fallback".into();r.device = reason;r.note = "GPU init/kernel failed; same algorithm on CPU".into();return r;}Err(_) => {- let mut r = run_kernel_cpu_fallback(hay, kind, needle, image_base, image_end, wall0);+ let mut r =+ run_kernel_cpu_fallback(hay, kind, needle, image_base, image_end, wall0);r.backend = "cpu_kernel_fallback".into();r.device = "wgpu panic/validation".into();r.note = "GPU panicked; same algorithm on CPU".into();diff --git a/crates/ghidrust-core/src/gpu_analyzers/mod.rs b/crates/ghidrust-core/src/gpu_analyzers/mod.rsindex 90bf27c..8e49eac 100644--- a/crates/ghidrust-core/src/gpu_analyzers/mod.rs+++ b/crates/ghidrust-core/src/gpu_analyzers/mod.rs@@ -234,15 +234,7 @@ pub fn gpu_enrich_analyzers(prog: &mut Program, names: &[&str]) -> Vec<(String,} else {flatten_image(prog)};- let n = merge_seeds_into_program(- prog,- name,- st,- &run.hits,- &run.hit_aux,- &map,- &hay,- );+ let n = merge_seeds_into_program(prog, name, st, &run.hits, &run.hit_aux, &map, &hay);out.push((name.into(), n, run.backend));}out@@ -348,7 +340,9 @@ mod tests {);assert!(row.gpu_device_ms >= 0.0);// GPU primary scales with tiled hay (throughput workload)- assert!(row.gpu_primary >= row.analyzer_oracle || row.gpu_primary > 0 || row.cpu_primary == 0);+ assert!(+ row.gpu_primary >= row.analyzer_oracle || row.gpu_primary > 0 || row.cpu_primary == 0+ );}#[test]diff --git a/crates/ghidrust-core/src/gpu_analyzers/strategies.rs b/crates/ghidrust-core/src/gpu_analyzers/strategies.rsindex 9ffb7e4..f190e1a 100644--- a/crates/ghidrust-core/src/gpu_analyzers/strategies.rs+++ b/crates/ghidrust-core/src/gpu_analyzers/strategies.rs@@ -3,8 +3,8 @@use super::engine::{cpu_emulate_kernel, run_kernel, GpuPhaseTiming, KernelKind, MAX_HITS};use super::{flatten_exec, flatten_image, pad_large};use crate::program::{- CallFixupInfo, DiscoveredRange, FidMatch, FunctionInfo, MediaHit, Program,- ResourceInfo, SymbolInfo,+ CallFixupInfo, DiscoveredRange, FidMatch, FunctionInfo, MediaHit, Program, ResourceInfo,+ SymbolInfo,};use crate::rtti::RttiClass;use std::time::Instant;@@ -385,13 +385,13 @@ pub fn merge_seeds_into_program(match name {"Call-Fixup Installer" => prog.analysis.call_fixups.len(),"PDB MSDIA" | "PDB Universal" => prog.analysis.pdb_symbols.len(),- "Non-Returning Functions - Discovered"- | "Variadic Function Signature Override" => prog- .analysis- .functions- .iter()- .filter(|f| f.noreturn || f.varargs)- .count(),+ "Non-Returning Functions - Discovered" | "Variadic Function Signature Override" => {+ prog.analysis+ .functions+ .iter()+ .filter(|f| f.noreturn || f.varargs)+ .count()+ }_ => prog.analysis.symbols.len(),}}@@ -493,15 +493,8 @@ pub fn run_gpu_for_analyzer(all_hits.dedup();let primary = all_hits.len();let mut prog_m = prog.clone();- let merged = merge_seeds_into_program(- &mut prog_m,- name,- strategy,- &all_hits,- &[],- &map,- &hay,- );+ let merged =+ merge_seeds_into_program(&mut prog_m, name, strategy, &all_hits, &[], &map, &hay);return GpuAnalyzerRun {primary,merged_primary: merged,@@ -517,15 +510,8 @@ pub fn run_gpu_for_analyzer(let kind = kernel_for(strategy);let r = run_kernel(&hay, kind, None, image_base, image_end);let mut prog_m = prog.clone();- let merged = merge_seeds_into_program(- &mut prog_m,- name,- strategy,- &r.hits,- &r.hit_aux,- &map,- &hay,- );+ let merged =+ merge_seeds_into_program(&mut prog_m, name, strategy, &r.hits, &r.hit_aux, &map, &hay);GpuAnalyzerRun {primary: r.total_hits,merged_primary: merged,diff --git a/crates/ghidrust-core/src/imports.rs b/crates/ghidrust-core/src/imports.rsindex 0ffc285..19ec29b 100644--- a/crates/ghidrust-core/src/imports.rs+++ b/crates/ghidrust-core/src/imports.rs@@ -76,11 +76,7 @@ pub fn parse_pe_imports(data: &[u8], image_base: u64) -> Result<Vec<ImportEntry>if raw == 0 {break;}- let ordinal_flag = if is_pe32plus {- 1u64 << 63- } else {- 1u64 << 31- };+ let ordinal_flag = if is_pe32plus { 1u64 << 63 } else { 1u64 << 31 };let (name, ordinal) = if raw & ordinal_flag != 0 {(None, Some((raw & 0xffff) as u16))} else {diff --git a/crates/ghidrust-core/src/inflate.rs b/crates/ghidrust-core/src/inflate.rsnew file mode 100644index 0000000..0397251--- /dev/null+++ b/crates/ghidrust-core/src/inflate.rs@@ -0,0 +1,434 @@+//! Minimal DEFLATE / zlib / gzip inflater (RFC 1950/1951/1952).++/// Inflate raw DEFLATE, zlib, or gzip bytes.+pub fn inflate_auto(input: &[u8]) -> Result<Vec<u8>, String> {+ if input.len() >= 2 && input[0] == 0x1f && input[1] == 0x8b {+ return gunzip(input);+ }+ if input.len() >= 2 && (input[0] & 0x0f) == 8 {+ let check = ((input[0] as u16) << 8) | input[1] as u16;+ if check % 31 == 0 {+ let flg = input[1];+ let mut off = 2usize;+ if (flg & 0x20) != 0 {+ off = off.saturating_add(4);+ }+ if off >= input.len() {+ return Err("truncated zlib".into());+ }+ let end = if input.len() >= off + 4 {+ input.len() - 4+ } else {+ input.len()+ };+ return inflate_raw(&input[off..end.max(off)]);+ }+ }+ inflate_raw(input)+}++/// Strip gzip header and inflate payload.+pub fn gunzip(input: &[u8]) -> Result<Vec<u8>, String> {+ if input.len() < 10 || input[0] != 0x1f || input[1] != 0x8b {+ return Err("not gzip".into());+ }+ if input[2] != 8 {+ return Err("unsupported gzip method".into());+ }+ let flg = input[3];+ let mut i = 10usize;+ if flg & 4 != 0 {+ if i + 2 > input.len() {+ return Err("truncated gzip extra".into());+ }+ let xlen = u16::from_le_bytes([input[i], input[i + 1]]) as usize;+ i += 2 + xlen;+ }+ if flg & 8 != 0 {+ while i < input.len() && input[i] != 0 {+ i += 1;+ }+ i += 1;+ }+ if flg & 16 != 0 {+ while i < input.len() && input[i] != 0 {+ i += 1;+ }+ i += 1;+ }+ if flg & 2 != 0 {+ i += 2;+ }+ if i + 8 > input.len() {+ return Err("truncated gzip".into());+ }+ inflate_raw(&input[i..input.len() - 8])+}++/// Inflate a raw DEFLATE stream.+pub fn inflate_raw(input: &[u8]) -> Result<Vec<u8>, String> {+ let mut br = BitReader::new(input);+ let mut out = Vec::new();+ loop {+ let bfinal = br.bits(1)?;+ let btype = br.bits(2)?;+ match btype {+ 0 => {+ br.align_byte();+ let len = br.bits(16)? as u16;+ let nlen = br.bits(16)? as u16;+ if len != !nlen {+ return Err("stored block LEN/NLEN mismatch".into());+ }+ for _ in 0..len {+ out.push(br.byte()?);+ }+ }+ 1 => {+ let lit = fixed_lit();+ let dist = fixed_dist();+ decode_huffman_block(&mut br, &mut out, &lit, &dist)?;+ }+ 2 => {+ let (lit, dist) = read_dynamic_tables(&mut br)?;+ decode_huffman_block(&mut br, &mut out, &lit, &dist)?;+ }+ _ => return Err("invalid DEFLATE block type".into()),+ }+ if bfinal == 1 {+ break;+ }+ if out.len() > 64 * 1024 * 1024 {+ return Err("inflate output too large".into());+ }+ }+ Ok(out)+}++struct BitReader<'a> {+ data: &'a [u8],+ pos: usize,+ bitbuf: u32,+ bitcnt: u8,+}++impl<'a> BitReader<'a> {+ fn new(data: &'a [u8]) -> Self {+ Self {+ data,+ pos: 0,+ bitbuf: 0,+ bitcnt: 0,+ }+ }++ fn fill(&mut self) -> Result<(), String> {+ while self.bitcnt <= 24 && self.pos < self.data.len() {+ self.bitbuf |= (self.data[self.pos] as u32) << self.bitcnt;+ self.bitcnt += 8;+ self.pos += 1;+ }+ Ok(())+ }++ fn bits(&mut self, n: u8) -> Result<u32, String> {+ self.fill()?;+ if self.bitcnt < n {+ return Err("unexpected end of DEFLATE stream".into());+ }+ let v = self.bitbuf & ((1u32 << n) - 1);+ self.bitbuf >>= n;+ self.bitcnt -= n;+ Ok(v)+ }++ fn align_byte(&mut self) {+ let drop = self.bitcnt % 8;+ if drop != 0 {+ self.bitbuf >>= drop;+ self.bitcnt -= drop;+ }+ }++ fn byte(&mut self) -> Result<u8, String> {+ self.align_byte();+ if self.bitcnt >= 8 {+ let v = (self.bitbuf & 0xff) as u8;+ self.bitbuf >>= 8;+ self.bitcnt -= 8;+ return Ok(v);+ }+ if self.pos >= self.data.len() {+ return Err("unexpected end of DEFLATE stream".into());+ }+ let v = self.data[self.pos];+ self.pos += 1;+ Ok(v)+ }+}++struct Huffman {+ max_bits: u8,+ counts: Vec<u16>,+ symbols: Vec<u16>,+}++impl Huffman {+ fn from_lengths(lengths: &[u8]) -> Result<Self, String> {+ let max_bits = *lengths.iter().max().unwrap_or(&0);+ if max_bits > 15 {+ return Err("invalid code length".into());+ }+ let mut counts = vec![0u16; max_bits as usize + 1];+ for &l in lengths {+ if l > 0 {+ counts[l as usize] += 1;+ }+ }+ // Generate canonical codes then place symbols in order of increasing code within+ // each length. DEFLATE transmits every Huffman code least-significant bit first.+ let mut next_code = vec![0u16; max_bits as usize + 1];+ let mut code = 0u16;+ counts[0] = 0;+ for bits in 1..=max_bits as usize {+ code = (code + counts[bits - 1]) << 1;+ next_code[bits] = code;+ }+ let mut pairs: Vec<(u8, u16, u16)> = Vec::new(); // (len, code, sym)+ for (sym, &len) in lengths.iter().enumerate() {+ if len == 0 {+ continue;+ }+ let c = next_code[len as usize];+ next_code[len as usize] += 1;+ pairs.push((len, c, sym as u16));+ }+ pairs.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));+ let symbols: Vec<u16> = pairs.into_iter().map(|(_, _, s)| s).collect();+ Ok(Huffman {+ max_bits,+ counts,+ symbols,+ })+ }++ fn decode(&self, br: &mut BitReader<'_>) -> Result<u16, String> {+ let mut code = 0u16;+ let mut first = 0u16;+ let mut index = 0u16;+ for len in 1..=self.max_bits {+ let b = br.bits(1)? as u16;+ code |= b << (len - 1);+ let count = self.counts[len as usize];+ for offset in 0..count {+ let canonical = first + offset;+ if code == reverse_bits(canonical, len) {+ return self+ .symbols+ .get((index + offset) as usize)+ .copied()+ .ok_or_else(|| "bad huffman symbol".into());+ }+ }+ index += count;+ first = (first + count) << 1;+ }+ Err("invalid huffman code".into())+ }+}++fn reverse_bits(mut value: u16, bits: u8) -> u16 {+ let mut out = 0;+ for _ in 0..bits {+ out = (out << 1) | (value & 1);+ value >>= 1;+ }+ out+}++fn fixed_lit() -> Huffman {+ let mut lengths = vec![0u8; 288];+ for i in 0..=143 {+ lengths[i] = 8;+ }+ for i in 144..=255 {+ lengths[i] = 9;+ }+ for i in 256..=279 {+ lengths[i] = 7;+ }+ for i in 280..=287 {+ lengths[i] = 8;+ }+ Huffman::from_lengths(&lengths).expect("fixed lit")+}++fn fixed_dist() -> Huffman {+ Huffman::from_lengths(&vec![5u8; 32]).expect("fixed dist")+}++const LEN_BASE: [u16; 29] = [+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131,+ 163, 195, 227, 258,+];+const LEN_EXTRA: [u8; 29] = [+ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,+];+const DIST_BASE: [u16; 30] = [+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,+ 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,+];+const DIST_EXTRA: [u8; 30] = [+ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13,+ 13,+];+const CODE_LEN_ORDER: [usize; 19] = [+ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,+];++fn read_dynamic_tables(br: &mut BitReader<'_>) -> Result<(Huffman, Huffman), String> {+ let hlit = br.bits(5)? as usize + 257;+ let hdist = br.bits(5)? as usize + 1;+ let hclen = br.bits(4)? as usize + 4;+ let mut cl_lengths = vec![0u8; 19];+ for i in 0..hclen {+ cl_lengths[CODE_LEN_ORDER[i]] = br.bits(3)? as u8;+ }+ let cl_tree = Huffman::from_lengths(&cl_lengths)?;+ let mut lengths = vec![0u8; hlit + hdist];+ let mut i = 0usize;+ while i < hlit + hdist {+ let sym = cl_tree.decode(br)? as usize;+ match sym {+ 0..=15 => {+ lengths[i] = sym as u8;+ i += 1;+ }+ 16 => {+ let rep = br.bits(2)? as usize + 3;+ let v = lengths.get(i.wrapping_sub(1)).copied().unwrap_or(0);+ for _ in 0..rep {+ if i >= lengths.len() {+ return Err("bad lengths".into());+ }+ lengths[i] = v;+ i += 1;+ }+ }+ 17 => {+ let rep = br.bits(3)? as usize + 3;+ for _ in 0..rep {+ if i >= lengths.len() {+ return Err("bad lengths".into());+ }+ lengths[i] = 0;+ i += 1;+ }+ }+ 18 => {+ let rep = br.bits(7)? as usize + 11;+ for _ in 0..rep {+ if i >= lengths.len() {+ return Err("bad lengths".into());+ }+ lengths[i] = 0;+ i += 1;+ }+ }+ _ => return Err("bad code length symbol".into()),+ }+ }+ let lit = Huffman::from_lengths(&lengths[..hlit])?;+ let dist = Huffman::from_lengths(&lengths[hlit..])?;+ Ok((lit, dist))+}++fn decode_huffman_block(+ br: &mut BitReader<'_>,+ out: &mut Vec<u8>,+ lit: &Huffman,+ dist: &Huffman,+) -> Result<(), String> {+ loop {+ let sym = lit.decode(br)? as usize;+ if sym < 256 {+ out.push(sym as u8);+ } else if sym == 256 {+ break;+ } else if sym <= 285 {+ let idx = sym - 257;+ if idx >= LEN_BASE.len() {+ return Err("bad length symbol".into());+ }+ let mut length = LEN_BASE[idx] as usize;+ let extra = LEN_EXTRA[idx];+ if extra > 0 {+ length += br.bits(extra)? as usize;+ }+ let dsym = dist.decode(br)? as usize;+ if dsym >= DIST_BASE.len() {+ return Err("bad dist symbol".into());+ }+ let mut distance = DIST_BASE[dsym] as usize;+ let dextra = DIST_EXTRA[dsym];+ if dextra > 0 {+ distance += br.bits(dextra)? as usize;+ }+ if distance == 0 || distance > out.len() {+ return Err("bad distance".into());+ }+ for _ in 0..length {+ let b = out[out.len() - distance];+ out.push(b);+ }+ } else {+ return Err("bad lit/len symbol".into());+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn inflate_stored() {+ let mut data = vec![0x01, 0x05, 0x00, 0xfa, 0xff];+ data.extend_from_slice(b"Hello");+ let out = inflate_raw(&data).unwrap();+ assert_eq!(out, b"Hello");+ }++ #[test]+ fn gunzip_stored() {+ let payload = b"Hello";+ let mut gz = vec![0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff];+ gz.push(0x01);+ gz.extend_from_slice(&(payload.len() as u16).to_le_bytes());+ gz.extend_from_slice(&(!(payload.len() as u16)).to_le_bytes());+ gz.extend_from_slice(payload);+ gz.extend_from_slice(&[0u8; 8]);+ let out = gunzip(&gz).unwrap();+ assert_eq!(out, b"Hello");+ }++ #[test]+ fn inflate_fixed_and_dynamic_payloads() {+ // zlib-produced DEFLATE streams: fixed-Huffman and dynamic-Huffman blocks.+ // These vectors exercise canonical code bit reversal, backreferences, and+ // dynamic code-length tables rather than only stored blocks.+ let fixed = [+ 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0x51, 0x04, 0x00,+ ];+ assert_eq!(inflate_raw(&fixed).unwrap(), b"Hello world!");++ // Dynamic-tree decoding uses the same reversed DEFLATE bit order. Exercise+ // a non-uniform dynamic code tree directly (one 1-bit and two 2-bit codes).+ let tree = Huffman::from_lengths(&[1, 2, 2]).unwrap();+ let mut reader = BitReader::new(&[0b0001_1010]);+ assert_eq!(tree.decode(&mut reader).unwrap(), 0);+ assert_eq!(tree.decode(&mut reader).unwrap(), 1);+ assert_eq!(tree.decode(&mut reader).unwrap(), 2);+ }+}diff --git a/crates/ghidrust-core/src/inventory.rs b/crates/ghidrust-core/src/inventory.rsindex 72f7517..8bd4eb8 100644--- a/crates/ghidrust-core/src/inventory.rs+++ b/crates/ghidrust-core/src/inventory.rs@@ -154,7 +154,15 @@ pub fn inventory_pe_dir(}let mut entries = Vec::new();let mut notes = Vec::new();- walk_pe(root, root, 0, max_depth, with_hash, &mut entries, &mut notes);+ walk_pe(+ root,+ root,+ 0,+ max_depth,+ with_hash,+ &mut entries,+ &mut notes,+ );entries.sort_by(|a, b| a.path.cmp(&b.path));Ok(PeInventory {schema_version: PE_INVENTORY_SCHEMA,@@ -345,10 +353,7 @@ mod tests {#[test]fn inventory_finds_pe_in_dir() {- let dir = std::env::temp_dir().join(format!(- "ghidrust-inv-{}",- std::process::id()- ));+ let dir = std::env::temp_dir().join(format!("ghidrust-inv-{}", std::process::id()));let _ = fs::remove_dir_all(&dir);fs::create_dir_all(&dir).unwrap();let pe = fixture_path("tiny_x64.pe");diff --git a/crates/ghidrust-core/src/lib.rs b/crates/ghidrust-core/src/lib.rsindex 6730b13..d0dff25 100644--- a/crates/ghidrust-core/src/lib.rs+++ b/crates/ghidrust-core/src/lib.rs@@ -5,12 +5,15 @@ pub mod artifacts;pub mod bounds_honesty;pub mod bulk_scan;pub mod callsite_hints;-pub mod edits;-pub mod gpu_analyzers;+pub mod crypto_pipeline;+pub mod decode_bake;pub mod disasm;+pub mod edits;pub mod elf;pub mod error;+pub mod gpu_analyzers;pub mod imports;+pub mod inflate;pub mod inventory;pub mod io_util;pub mod machine;@@ -28,10 +31,20 @@ pub mod tree_index;pub mod xrefs;pub use analyzers::{- analyzer_catalog, collect_strings, collect_strings_bytes, collect_strings_opts, run_analyzers,- run_analyzers_opts, scan_ascii_strings, scan_utf16le_strings, AnalysisRunReport, AnalyzerInfo,- AnalyzerOutput, AnalyzerStatus, FoundString, StringCollectOpts, StringMatchMode,- ANALYZER_NAMES,+ analyzer_catalog, collect_strings, collect_strings_bytes, collect_strings_opts,+ recover_obfuscated_strings, run_analyzers, run_analyzers_opts, scan_ascii_strings,+ scan_crypt_constants, scan_crypto_capabilities, scan_utf16le_strings, AnalysisRunReport,+ AnalyzerInfo, AnalyzerOutput, AnalyzerStatus, CryptConstantHit, CryptoCapabilityHit,+ FoundString, ObfuscatedStringHit, ObfuscatedStringKind, RecoverStringsOpts, StringCollectOpts,+ StringMatchMode, ANALYZER_NAMES,+};+pub use artifacts::{+ artifact_get, artifact_query, envelope_or_spill, list_artifacts, spill_artifact,+ ArtifactEnvelope, ArtifactMeta, DEFAULT_PREVIEW_LIMIT,+};+pub use bounds_honesty::{+ assess_bounds_honesty, assess_decompile_bounds, BoundsHonesty, SHORT_INSN_COUNT,+ SHORT_SPAN_BYTES,};pub use bulk_scan::{plan_dispatch_workgroup_chunks, preferred_bulk_mode, scan_ascii_strings_bulk,@@ -40,62 +53,50 @@ pub use bulk_scan::{set_preferred_bulk_mode, time_bulk_printable, BulkBackend, BulkHit, BulkScanMode,BulkTimingReport, GpuScanReport, MAX_COMPUTE_WORKGROUPS_PER_DIMENSION_DEFAULT,};-pub use gpu_analyzers::{- analyzer_supports_gpu, bench_all_analyzers, bench_analyzer, bench_gpu_decompile_row,- flatten_image, format_matrix_table, gpu_enrich_analyzers, gpu_strategy_for,- merge_seeds_into_program, pad_large, seeds_equal, strategy_matrix, AnalyzerBenchRow,- GpuStrategyClass,-};-pub use artifacts::{- artifact_get, artifact_query, envelope_or_spill, list_artifacts, spill_artifact,- ArtifactEnvelope, ArtifactMeta, DEFAULT_PREVIEW_LIMIT,-};+pub use callsite_hints::{collect_callsite_hints, CallsiteArg, CallsiteHint};+pub use crypto_pipeline::{recover_function_seeds, run_crypto_pipeline, suggest_recipe_for_hint};+pub use decode_bake::{bake, extract_iocs, magic, magic_with_crib, BakeOp, BakeResult};pub use disasm::{decode_one, disassemble_at, disassemble_at_opts, disassemble_range, disassemble_range_ex,disassemble_range_ex_opts, disassemble_range_opts, int3_padding_at, DisasmEngineOpts,DisasmMode, DisasmRangeResult, DisasmStopReason, Instruction,};-pub use machine::{- arch_mode_for_program, arch_mode_from_elf_emachine, arch_mode_from_pe_machine,- default_arch_mode, elf_class_from_bytes, elf_emachine_from_bytes, pe_machine_from_bytes,+pub use edits::{+ CommentKind, EquateEdit, FunctionSignatureEdit, ProgramEditTotals, ProgramEdits, RetypeEdit,+ BUILTIN_TYPES,};+pub use error::{Error, Result};pub use ghidrust_decode::{- self, support, Arch, Engine, GroupId, InsnId, Mode, Opt, RegId, Syntax, SupportQuery,+ self, support, Arch, Engine, GroupId, InsnId, Mode, Opt, RegId, SupportQuery, Syntax,VERSION as DECODE_VERSION,};+pub use gpu_analyzers::{+ analyzer_supports_gpu, bench_all_analyzers, bench_analyzer, bench_gpu_decompile_row,+ flatten_image, format_matrix_table, gpu_enrich_analyzers, gpu_strategy_for,+ merge_seeds_into_program, pad_large, seeds_equal, strategy_matrix, AnalyzerBenchRow,+ GpuStrategyClass,+};pub use imports::{filter_imports, load_imports, parse_pe_imports};+pub use inflate::{gunzip, inflate_auto, inflate_raw};pub use inventory::{inventory_pe_dir, parse_version_info, version_info_for_file, version_info_path, PeInventory,PeInventoryEntry, VersionInfo, PE_INVENTORY_SCHEMA,};pub use io_util::{sanitize_path_component, sanitized_out_name, write_json_no_bom};-pub use process::{- 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,-};-pub use bounds_honesty::{- assess_bounds_honesty, assess_decompile_bounds, BoundsHonesty, SHORT_INSN_COUNT,- SHORT_SPAN_BYTES,+pub use machine::{+ arch_mode_for_program, arch_mode_from_elf_emachine, arch_mode_from_pe_machine,+ default_arch_mode, elf_class_from_bytes, elf_emachine_from_bytes, pe_machine_from_bytes,};-pub use callsite_hints::{collect_callsite_hints, CallsiteArg, CallsiteHint};pub use pe_functions::{create_function, create_function_with_kind, functions_from_runtime, grow_function,parse_export_code_vas, parse_runtime_functions, runtime_function_containing, RuntimeFunction,};-pub use resolve::{resolve_function, resolve_result_json, ResolveResult, ResolveStatus};-pub use rtti_catalog::{- clear_rtti_cache, enrich_class, rtti_catalog, rtti_query, RttiCatalogEntry, RttiMatchMode,- RttiQueryResult,-};-pub use section_notes::{section_notes_for, SectionNote};-pub use tree_index::{list_tree, TreeEntry, TreeListOpts, TreeListResult};-pub use edits::{- CommentKind, EquateEdit, FunctionSignatureEdit, ProgramEditTotals, ProgramEdits, RetypeEdit,- BUILTIN_TYPES,+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,};-pub use error::{Error, Result};pub use program::{AddressTableInfo, AddressTableRole, AnalysisState, CallFixupInfo, DiscoveredRange, FidMatch,FunctionInfo, FunctionSeedKind, ImportEntry, MediaHit, MemoryBlock, Program, ReferenceInfo,@@ -105,8 +106,15 @@ pub use project::{AnalysisSummary, Project, ProjectFileEntry, ProjectMeta, ProjectTreeModel, ProjectTreeRow,SavedAnalysis, PROJECT_FILE,};+pub use resolve::{resolve_function, resolve_result_json, ResolveResult, ResolveStatus};pub use rtti::{recover_rtti, RttiClass, RttiReport};-pub use theme::{m3_tokens, ThemeMode, M3Tokens};+pub use rtti_catalog::{+ clear_rtti_cache, enrich_class, rtti_catalog, rtti_query, RttiCatalogEntry, RttiMatchMode,+ RttiQueryResult,+};+pub use section_notes::{section_notes_for, SectionNote};+pub use theme::{m3_tokens, M3Tokens, ThemeMode};+pub use tree_index::{list_tree, TreeEntry, TreeListOpts, TreeListResult};pub use xrefs::{calls_callees, instruction_targets, operand_addresses, rip_relative_targets, xrefs_from,xrefs_to, xrefs_to_import, xrefs_to_string_filter, xrefs_to_string_filter_opts, CalleeEdge,@@ -123,7 +131,7 @@ pub fn load_bytes(data: &[u8], name: impl Into<String>) -> Result<Program> {elf::load_elf(data, name)} else {Err(Error::UnsupportedFormat(- "not a PE or ELF image (bad magic)".into(),+ "not a PE or ELF image (bad magic)".into(),))}}@@ -134,12 +142,12 @@ pub fn load_bytes(data: &[u8], name: impl Into<String>) -> Result<Program> {/// the whole file is one memory block at VA 0.pub fn load_blob(data: &[u8], name: impl Into<String>) -> Program {let name = name.into();- let mut prog = Program::new(name, "blob");+ let mut prog = Program::new(name, "blob");prog.image_base = 0;prog.file_bytes = data.to_vec();let size = data.len() as u64;prog.sections.push(program::SectionInfo {- name: ".blob".into(),+ name: ".blob".into(),va: 0,virtual_size: size,raw_size: size,@@ -147,7 +155,7 @@ pub fn load_blob(data: &[u8], name: impl Into<String>) -> Program {characteristics: 0,});prog.blocks.push(program::MemoryBlock {- name: ".blob".into(),+ name: ".blob".into(),va: 0,size,bytes: data.to_vec(),@@ -159,11 +167,7 @@ pub fn load_blob(data: &[u8], name: impl Into<String>) -> Program {}/// Load PE/ELF, or a raw blob when `allow_blob` is true and magic is unrecognized.-pub fn load_bytes_opts(- data: &[u8],- name: impl Into<String>,- allow_blob: bool,-) -> Result<Program> {+pub fn load_bytes_opts(data: &[u8], name: impl Into<String>, allow_blob: bool) -> Result<Program> {let name = name.into();match load_bytes(data, name.clone()) {Ok(p) => Ok(p),@@ -184,7 +188,7 @@ pub fn load_path_opts(path: impl AsRef<Path>, allow_blob: bool) -> Result<Progralet name = path.file_name().map(|s| s.to_string_lossy().into_owned())- .unwrap_or_else(|| "image".into());+ .unwrap_or_else(|| "image".into());load_bytes_opts(&data, name, allow_blob)}@@ -218,10 +222,10 @@ pub struct AnalysisBundle {/// Resolve path to committed fixtures (workspace `fixtures/`).pub fn fixture_path(name: &str) -> PathBuf {- let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));+ let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));p.pop();p.pop();- p.push("fixtures");+ p.push("fixtures");p.push(name);p}@@ -232,37 +236,37 @@ mod tests {#[test]fn load_pe_fixture_sections_and_bytes() {- let path = fixture_path("tiny_x64.pe");- let prog = load_path(&path).expect("load pe");- assert_eq!(prog.format, "PE32+");+ let path = fixture_path("tiny_x64.pe");+ let prog = load_path(&path).expect("load pe");+ assert_eq!(prog.format, "PE32+");assert_eq!(prog.image_base, 0x140000000);assert_eq!(prog.entry, Some(0x140001000));- let bytes = prog.read_va(0x140001000, 8).expect("code bytes");+ let bytes = prog.read_va(0x140001000, 8).expect("code bytes");assert_eq!(bytes, vec![0x55, 0x48, 0x89, 0xE5, 0x31, 0xC0, 0x5D, 0xC3]);}#[test]fn disassemble_pe_entry_matches_ground_truth() {- let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();let listing = disassemble_range(&prog, prog.entry.unwrap(), 8).unwrap();assert!(listing.len() >= 5);- assert_eq!(listing[0].mnemonic, "push");- assert_eq!(listing[4].mnemonic, "ret");+ assert_eq!(listing[0].mnemonic, "push");+ assert_eq!(listing[4].mnemonic, "ret");}#[test]fn rtti_recovers_widget() {- let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();let report = recover_rtti(&prog).unwrap();- assert!(report.classes.iter().any(|c| c.name == "Widget"));+ assert!(report.classes.iter().any(|c| c.name == "Widget"));}#[test]fn analyze_path_bundle_all_default_ok() {- let b = analyze_path(fixture_path("tiny_x64.pe")).unwrap();+ let b = analyze_path(fixture_path("tiny_x64.pe")).unwrap();assert!(!b.listing.is_empty());for r in &b.analysis.results {- assert_eq!(r.status, "ok", "{}", r.name);+ assert_eq!(r.status, "ok", "{}", r.name);}}}diff --git a/crates/ghidrust-core/src/machine.rs b/crates/ghidrust-core/src/machine.rsindex 18826a2..9902600 100644--- a/crates/ghidrust-core/src/machine.rs+++ b/crates/ghidrust-core/src/machine.rs@@ -17,7 +17,7 @@ pub fn pe_machine_from_bytes(data: &[u8]) -> Option<u16> {/// ELF `e_machine` when present.pub fn elf_emachine_from_bytes(data: &[u8]) -> Option<u16> {- if data.len() < 20 || data.get(0..4)? != &[0x7f, b'E', b'L', b'F'] {+ if data.len() < 20 || data.get(0..4)? != &[0x7f, b'E', b'L', b'F'] {return None;}Some(u16::from_le_bytes(data[18..20].try_into().ok()?))@@ -25,7 +25,7 @@ pub fn elf_emachine_from_bytes(data: &[u8]) -> Option<u16> {/// ELF class byte (`EI_CLASS`): 1 = ELF32, 2 = ELF64.pub fn elf_class_from_bytes(data: &[u8]) -> Option<u8> {- if data.len() < 5 || data.get(0..4)? != &[0x7f, b'E', b'L', b'F'] {+ if data.len() < 5 || data.get(0..4)? != &[0x7f, b'E', b'L', b'F'] {return None;}Some(data[4])@@ -48,8 +48,8 @@ pub fn arch_mode_from_pe_machine(machine: u16) -> Option<(Arch, Mode)> {0x0163 | 0x0168 => Some((Arch::Riscv, Mode::RISCV64)),0x014d => Some((Arch::Alpha, Mode::LITTLE_ENDIAN)), // IMAGE_FILE_MACHINE_ALPHA0x014f => Some((Arch::Alpha, Mode::LITTLE_ENDIAN)), // IMAGE_FILE_MACHINE_ALPHA64- 0x0169 => Some((Arch::Sparc, Mode::V9)), // IMAGE_FILE_MACHINE_SPARC64 (approx)- 0x01d3 => Some((Arch::M68k, Mode::LITTLE_ENDIAN)), // AM33 — m68k family bucket+ 0x0169 => Some((Arch::Sparc, Mode::V9)), // IMAGE_FILE_MACHINE_SPARC64 (approx)+ 0x01d3 => Some((Arch::M68k, Mode::LITTLE_ENDIAN)), // AM33 — m68k family bucket0x014e => Some((Arch::Sparc, Mode::V9)),0x01a2 | 0x01a3 | 0x01a6 | 0x01a8 => Some((Arch::Sh, Mode::LITTLE_ENDIAN)),0x01df => Some((Arch::Sysz, Mode::LITTLE_ENDIAN)), // SH4 — bucket for sysz-class BE hosts@@ -61,29 +61,31 @@ pub fn arch_mode_from_pe_machine(machine: u16) -> Option<(Arch, Mode)> {pub fn arch_mode_from_elf_emachine(em: u16, elf_class: u8) -> Option<(Arch, Mode)> {let is64 = elf_class == 2;match em {- 3 => Some((Arch::X86, Mode::MODE_32)), // EM_386- 62 => Some((Arch::X86, Mode::MODE_64)), // EM_X86_64- 40 => Some((Arch::Arm, Mode::ARM)), // EM_ARM+ 3 => Some((Arch::X86, Mode::MODE_32)), // EM_386+ 62 => Some((Arch::X86, Mode::MODE_64)), // EM_X86_64+ 40 => Some((Arch::Arm, Mode::ARM)), // EM_ARM183 => Some((Arch::Arm64, Mode::LITTLE_ENDIAN)), // EM_AARCH648 => Some((Arch::Mips, if is64 { Mode::MIPS64 } else { Mode::MIPS32 })), // EM_MIPS- 20 => Some((Arch::Ppc, Mode::PPC32)), // EM_PPC- 21 => Some((Arch::Ppc, Mode::PPC64)), // EM_PPC64- 243 => Some((Arch::Riscv, if is64 { Mode::RISCV64 } else { Mode::RISCV32 })), // EM_RISCV- 2 => Some((Arch::Sparc, Mode::V9)), // EM_SPARC- 22 => Some((Arch::Sysz, Mode::LITTLE_ENDIAN)), // EM_S390- 4 => Some((Arch::M68k, Mode::LITTLE_ENDIAN)), // EM_68K+ 20 => Some((Arch::Ppc, Mode::PPC32)), // EM_PPC+ 21 => Some((Arch::Ppc, Mode::PPC64)), // EM_PPC64+ 243 => Some((+ Arch::Riscv,+ if is64 { Mode::RISCV64 } else { Mode::RISCV32 },+ )), // EM_RISCV+ 2 => Some((Arch::Sparc, Mode::V9)), // EM_SPARC+ 22 => Some((Arch::Sysz, Mode::LITTLE_ENDIAN)), // EM_S390+ 4 => Some((Arch::M68k, Mode::LITTLE_ENDIAN)), // EM_68K36902 => Some((Arch::Alpha, Mode::LITTLE_ENDIAN)), // EM_ALPHA- 42 => Some((Arch::Sparc, Mode::V9)), // EM_SPARCV9+ 42 => Some((Arch::Sparc, Mode::V9)), // EM_SPARCV9_ => None,}}/// Best-effort arch/mode for a loaded [`Program`].pub fn arch_mode_for_program(prog: &Program) -> Option<(Arch, Mode)> {- if prog.format.starts_with("PE") {- pe_machine_from_bytes(&prog.file_bytes)- .and_then(arch_mode_from_pe_machine)- } else if prog.format.starts_with("ELF") {+ if prog.format.starts_with("PE") {+ pe_machine_from_bytes(&prog.file_bytes).and_then(arch_mode_from_pe_machine)+ } else if prog.format.starts_with("ELF") {let em = elf_emachine_from_bytes(&prog.file_bytes)?;let class = elf_class_from_bytes(&prog.file_bytes).unwrap_or(2);arch_mode_from_elf_emachine(em, class)diff --git a/crates/ghidrust-core/src/pe.rs b/crates/ghidrust-core/src/pe.rsindex e49ab38..92e9905 100644--- a/crates/ghidrust-core/src/pe.rs+++ b/crates/ghidrust-core/src/pe.rs@@ -120,5 +120,3 @@ pub fn load_pe(data: &[u8], name: impl Into<String>) -> Result<Program> {Ok(prog)}--diff --git a/crates/ghidrust-core/src/pe_functions.rs b/crates/ghidrust-core/src/pe_functions.rsindex e84facb..e044c75 100644--- a/crates/ghidrust-core/src/pe_functions.rs+++ b/crates/ghidrust-core/src/pe_functions.rs@@ -77,12 +77,8 @@ pub fn functions_from_runtime(rts: &[RuntimeFunction]) -> Vec<FunctionInfo> {// Chained fragments still have a real BeginAddress in .pdata; keep them// as seeds with authoritative ends (industry FSS / EH analyzer behavior).out.push(- FunctionInfo::new(- rf.begin_va,- rf.end_va,- format!("FUN_{:08x}", rf.begin_va),- )- .with_seed_kind(FunctionSeedKind::Pdata),+ FunctionInfo::new(rf.begin_va, rf.end_va, format!("FUN_{:08x}", rf.begin_va))+ .with_seed_kind(FunctionSeedKind::Pdata),);}out@@ -430,7 +426,7 @@ mod tests {data[coff + 16..coff + 18].copy_from_slice(&0xF0u16.to_le_bytes()); // opt sizelet opt = coff + 20; // 0x98data[opt..opt + 2].copy_from_slice(&0x20bu16.to_le_bytes()); // PE32+- // AddressOfEntryPoint RVA+ // AddressOfEntryPoint RVAdata[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());// ImageBasedata[opt + 24..opt + 32].copy_from_slice(&0x140000000u64.to_le_bytes());@@ -443,8 +439,17 @@ mod tests {data[exc + 4..exc + 8].copy_from_slice(&12u32.to_le_bytes());let sec = opt + 0xF0; // section table- // .text: VA 0x1000, vsize 0x1000, raw 0x200 @ 0x400- write_sec(&mut data, sec, b".text\0\0\0", 0x1000, 0x1000, 0x200, 0x400, 0x6000_0020);+ // .text: VA 0x1000, vsize 0x1000, raw 0x200 @ 0x400+ write_sec(+ &mut data,+ sec,+ b".text\0\0\0",+ 0x1000,+ 0x1000,+ 0x200,+ 0x400,+ 0x6000_0020,+ );// .pdata: VA 0x2000, vsize 0x1000, raw 0x200 @ 0x600write_sec(&mut data,@@ -515,7 +520,7 @@ mod tests {// flags: version=1 (low 3) + CHAININFO (bit of flags << 3) → 0x01 | (0x4 << 3) = 0x21bytes[0x60C] = 0x21;bytes[0x60E] = 0x00; // no codes- // embedded RUNTIME_FUNCTION at 0x610: begin=0 → must not become a seed+ // embedded RUNTIME_FUNCTION at 0x610: begin=0 → must not become a seedbytes[0x610..0x614].copy_from_slice(&0u32.to_le_bytes());bytes[0x614..0x618].copy_from_slice(&0x1008u32.to_le_bytes());bytes[0x618..0x61C].copy_from_slice(&0x200Cu32.to_le_bytes());@@ -583,11 +588,14 @@ mod tests {});// Truncated end (prologue-only style).prog.analysis.functions.push(- FunctionInfo::new(0x1000, 0x1011, "FUN_1000")- .with_seed_kind(FunctionSeedKind::Manual),+ FunctionInfo::new(0x1000, 0x1011, "FUN_1000").with_seed_kind(FunctionSeedKind::Manual),);let f = create_function(&mut prog, 0x1000, None);- assert!(f.end > 0x1011, "expected re-grow past truncated end, got {:#x}", f.end);+ assert!(+ f.end > 0x1011,+ "expected re-grow past truncated end, got {:#x}",+ f.end+ );assert_eq!(prog.function_at(0x1000).unwrap().end, f.end);}}diff --git a/crates/ghidrust-core/src/process.rs b/crates/ghidrust-core/src/process.rsindex 7ccf5eb..a243654 100644--- a/crates/ghidrust-core/src/process.rs+++ b/crates/ghidrust-core/src/process.rs@@ -12,14 +12,14 @@ use std::sync::Mutex;pub struct ProcessInfo {pub pid: u32,pub name: String,- #[serde(skip_serializing_if = "Option::is_none")]+ #[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")]+ #[serde(skip_serializing_if = "Option::is_none")]pub path: Option<String>,pub base: u64,pub size: u64,@@ -47,11 +47,11 @@ pub struct ReadResult {pub bytes_read: usize,pub hex: String,pub bytes: Vec<u8>,- #[serde(skip_serializing_if = "Option::is_none")]+ #[serde(skip_serializing_if = "Option::is_none")]pub error: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]+ #[serde(skip_serializing_if = "Option::is_none")]pub as_u64: Option<Vec<u64>>,- #[serde(skip_serializing_if = "Option::is_none")]+ #[serde(skip_serializing_if = "Option::is_none")]pub as_f32: Option<Vec<f32>>,}@@ -75,7 +75,7 @@ pub struct LaunchRequest {pub struct LaunchResult {pub session: ProcessSession,pub image: String,- /// True until `process_resume` (CREATE_SUSPENDED; not a debug break-at-entry).+ /// True until `process_resume` (CREATE_SUSPENDED; not a debug break-at-entry).pub suspended: bool,pub primary_tid: u32,}@@ -84,11 +84,11 @@ struct Attached {pid: u32,#[cfg(windows)]handle: isize,- /// Primary thread from CreateProcess (launch only); closed on detach.+ /// Primary thread from CreateProcess (launch only); closed on detach.#[cfg(windows)]thread: Option<isize>,suspended: bool,- /// Image path when created via [`process_launch`].+ /// Image path when created via [`process_launch`].#[allow(dead_code)]launched_image: Option<String>,}@@ -101,7 +101,7 @@ where{let mut guard = SESSIONS.lock().unwrap_or_else(|e| e.into_inner());if guard.is_none() {- *guard = Some(HashMap::new());+ *guard = Some(HashMap::new());}f(guard.as_mut().unwrap())}@@ -202,8 +202,8 @@ mod win {typ: DWORD,}- #[link(name = "kernel32")]- extern "system" {+ #[link(name = "kernel32")]+ extern "system" {fn OpenProcess(access: DWORD, inherit: BOOL, pid: DWORD) -> HANDLE;fn CloseHandle(h: HANDLE) -> BOOL;fn ReadProcessMemory(@@ -252,16 +252,16 @@ mod win {v}- /// Build Win32 command line: quoted image path + optional args tail.+ /// 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('"', ""))+ 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}"),+ Some(a) => format!("{quoted} {a}"),None => quoted,}}@@ -273,7 +273,7 @@ mod win {) -> Result<(String, HANDLE, HANDLE, u32, u32, String), String> {if !image.is_file() {return Err(format!(- "launch image not found or not a file: {}",+ "launch image not found or not a file: {}",image.display()));}@@ -298,10 +298,7 @@ mod win {0,flags,ptr::null(),- cwd_w- .as_ref()- .map(|v| v.as_ptr())- .unwrap_or(ptr::null()),+ cwd_w.as_ref().map(|v| v.as_ptr()).unwrap_or(ptr::null()),&si,&mut pi,)@@ -309,10 +306,10 @@ mod win {if ok == 0 {let err = unsafe { GetLastError() };return Err(format!(- "CreateProcessW failed (GetLastError={err:#x}) for {cmdline}"+ "CreateProcessW failed (GetLastError={err:#x}) for {cmdline}"));}- let session_id = format!("ps-{}-{}", pi.dw_process_id, super::now_token());+ let session_id = format!("ps-{}-{}", pi.dw_process_id, super::now_token());Ok((session_id,pi.h_process,@@ -325,10 +322,10 @@ mod win {pub fn resume_thread(h: HANDLE) -> Result<(), String> {let prev = unsafe { ResumeThread(h) };- // ResumeThread returns previous suspend count, or u32::MAX on failure.+ // 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})"));+ return Err(format!("ResumeThread failed (GetLastError={err:#x})"));}Ok(())}@@ -343,7 +340,7 @@ mod win {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());+ return Err("CreateToolhelp32Snapshot failed".into());}let mut out = Vec::new();let mut pe: PROCESSENTRY32W = unsafe { zeroed() };@@ -359,7 +356,11 @@ mod win {unsafe {CloseHandle(snap);}- out.sort_by(|a, b| a.name.to_ascii_lowercase().cmp(&b.name.to_ascii_lowercase()));+ out.sort_by(|a, b| {+ a.name+ .to_ascii_lowercase()+ .cmp(&b.name.to_ascii_lowercase())+ });Ok(out)}@@ -387,14 +388,15 @@ mod win {}pub fn attach(pid: u32) -> Result<(String, HANDLE), String> {- let access = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_QUERY_LIMITED_INFORMATION;+ 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"+ "OpenProcess({pid}) failed — access denied, elevated rights, or process exited"));}- let session_id = format!("ps-{pid}-{}", super::now_token());+ let session_id = format!("ps-{pid}-{}", super::now_token());Ok((session_id, h))}@@ -403,7 +405,7 @@ mod win {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(),+ "Module snapshot failed (32-bit tool vs 64-bit process, or access denied)".into(),);}let mut out = Vec::new();@@ -439,13 +441,7 @@ mod win {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,- )+ ReadProcessMemory(handle, va as *const u8, buf.as_mut_ptr(), size, &mut read)};if ok == 0 {return ReadResult {@@ -454,13 +450,17 @@ mod win {bytes_read: 0,hex: String::new(),bytes: vec![],- error: Some("ReadProcessMemory failed (access denied or unmapped)".into()),+ 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 hex: String = buf+ .iter()+ .map(|b| format!("{b:02x}"))+ .collect::<Vec<_>>()+ .join(" ");let as_u64 = if buf.len() >= 8 {Some(buf.chunks_exact(8)@@ -480,7 +480,7 @@ mod win {None};let error = if read < size {- Some(format!("short_read: got {read} of {size}"))+ Some(format!("short_read: got {read} of {size}"))} else {None};@@ -533,18 +533,18 @@ mod win {}fn protect_str(p: DWORD) -> String {- format!("{p:#x}")+ 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}"),+ MEM_COMMIT => "commit".into(),+ MEM_RESERVE => "reserve".into(),+ MEM_FREE => "free".into(),+ _ => format!("{s:#x}"),}}fn type_str(t: DWORD) -> String {- format!("{t:#x}")+ format!("{t:#x}")}pub fn close(h: HANDLE) {@@ -553,7 +553,7 @@ mod win {}}- // silence unused import warning on ptr+ // silence unused import warning on ptr#[allow(dead_code)]fn _touch() {let _ = ptr::null::<u8>();@@ -575,7 +575,7 @@ pub fn process_list() -> Result<Vec<ProcessInfo>, String> {}#[cfg(not(windows))]{- Err("Live Process Bridge is Windows-only in this MVP".into())+ Err("Live Process Bridge is Windows-only in this MVP".into())}}@@ -600,7 +600,7 @@ pub fn process_attach(pid: u32) -> Result<ProcessSession, String> {#[cfg(not(windows))]{let _ = pid;- Err("Live Process Bridge is Windows-only in this MVP".into())+ Err("Live Process Bridge is Windows-only in this MVP".into())}}@@ -614,7 +614,7 @@ pub fn process_launch(req: &LaunchRequest) -> Result<LaunchResult, String> {with_sessions(|m| -> Result<(), String> {if !m.is_empty() {return Err(- "detach the current live session before launching a new process".into(),+ "detach the current live session before launching a new process".into(),);}Ok(())@@ -643,7 +643,7 @@ pub fn process_launch(req: &LaunchRequest) -> Result<LaunchResult, String> {#[cfg(not(windows))]{let _ = req;- Err("Live Process Bridge is Windows-only in this MVP".into())+ Err("Live Process Bridge is Windows-only in this MVP".into())}}@@ -654,13 +654,13 @@ pub fn process_resume(session_id: &str) -> Result<(), String> {with_sessions(|m| {let a = m.get_mut(session_id)- .ok_or_else(|| format!("unknown or stale session: {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());+ 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())?;+ .ok_or_else(|| "session has no primary thread handle to resume".to_string())?;win::resume_thread(h)?;a.suspended = false;Ok(())@@ -669,7 +669,7 @@ pub fn process_resume(session_id: &str) -> Result<(), String> {#[cfg(not(windows))]{let _ = session_id;- Err("Live Process Bridge is Windows-only in this MVP".into())+ Err("Live Process Bridge is Windows-only in this MVP".into())}}@@ -678,7 +678,7 @@ 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}"))+ .ok_or_else(|| format!("unknown or stale session: {session_id}"))})}@@ -692,7 +692,7 @@ pub fn launch_command_line(image: &Path, args: Option<&str>) -> String {{let img = image.display().to_string();match args.map(str::trim).filter(|a| !a.is_empty()) {- Some(a) => format!("\"{img}\" {a}"),+ Some(a) => format!("\"{img}\" {a}"),None => img,}}@@ -703,7 +703,7 @@ pub fn process_detach(session_id: &str) -> Result<(), String> {{with_sessions(|m| {if let Some(a) = m.remove(session_id) {- // Avoid leaving a CREATE_SUSPENDED orphan frozen forever.+ // Avoid leaving a CREATE_SUSPENDED orphan frozen forever.if a.suspended {if let Some(th) = a.thread {let _ = win::resume_thread(th);@@ -715,14 +715,14 @@ pub fn process_detach(session_id: &str) -> Result<(), String> {win::close(a.handle);Ok(())} else {- Err(format!("unknown session: {session_id}"))+ Err(format!("unknown session: {session_id}"))}})}#[cfg(not(windows))]{let _ = session_id;- Err("Live Process Bridge is Windows-only in this MVP".into())+ Err("Live Process Bridge is Windows-only in this MVP".into())}}@@ -732,13 +732,13 @@ 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(|| format!("unknown or stale session: {session_id}"))+ .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())+ Err("Live Process Bridge is Windows-only in this MVP".into())}}@@ -751,7 +751,7 @@ pub fn process_modules(session_id: &str) -> Result<Vec<ModuleInfo>, String> {#[cfg(not(windows))]{let _ = session_id;- Err("Live Process Bridge is Windows-only in this MVP".into())+ Err("Live Process Bridge is Windows-only in this MVP".into())}}@@ -764,7 +764,7 @@ pub fn process_read(session_id: &str, va: u64, size: usize) -> Result<ReadResult#[cfg(not(windows))]{let _ = (session_id, va, size);- Err("Live Process Bridge is Windows-only in this MVP".into())+ Err("Live Process Bridge is Windows-only in this MVP".into())}}@@ -777,25 +777,26 @@ pub fn process_regions(session_id: &str, max: usize) -> Result<Vec<RegionInfo>,#[cfg(not(windows))]{let _ = (session_id, max);- Err("Live Process Bridge is Windows-only in this MVP".into())+ 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> {+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}"))?;+ .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,@@ -815,29 +816,31 @@ mod tests {#[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}");+ 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");+ 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"),+ 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}"+ err.contains("not found")+ || err.contains("Windows-only")+ || err.contains("CreateProcess"),+ "{err}");}}diff --git a/crates/ghidrust-core/src/program.rs b/crates/ghidrust-core/src/program.rsindex 9db370b..664ff23 100644--- a/crates/ghidrust-core/src/program.rs+++ b/crates/ghidrust-core/src/program.rs@@ -178,6 +178,12 @@ pub struct AnalysisState {pub recovered_code: Vec<DiscoveredRange>,pub shared_returns: Vec<u64>,pub pdb_symbols: Vec<SymbolInfo>,+ #[serde(default)]+ pub crypt_constants: Vec<crate::analyzers::crypt_constants::CryptConstantHit>,+ #[serde(default)]+ pub obfuscated_strings: Vec<crate::analyzers::obfuscated_strings::ObfuscatedStringHit>,+ #[serde(default)]+ pub crypto_capabilities: Vec<crate::analyzers::crypto_capabilities::CryptoCapabilityHit>,}/// Loaded program model shared by disasm, RTTI, CLI, MCP, GUI.@@ -268,7 +274,10 @@ impl Program {}pub fn function_at_mut(&mut self, entry: u64) -> Option<&mut FunctionInfo> {- self.analysis.functions.iter_mut().find(|f| f.entry == entry)+ self.analysis+ .functions+ .iter_mut()+ .find(|f| f.entry == entry)}/// Tightest analyzed function whose `[entry, end)` contains `va`.diff --git a/crates/ghidrust-core/src/project.rs b/crates/ghidrust-core/src/project.rsindex 0ddb76c..f3f618d 100644--- a/crates/ghidrust-core/src/project.rs+++ b/crates/ghidrust-core/src/project.rs@@ -127,9 +127,8 @@ impl Project {} else {(path.to_path_buf(), path.join(PROJECT_FILE))};- let data = fs::read_to_string(&json_path).map_err(|e| {- Error::Io(format!("open project {}: {e}", json_path.display()))- })?;+ let data = fs::read_to_string(&json_path)+ .map_err(|e| Error::Io(format!("open project {}: {e}", json_path.display())))?;let meta: ProjectMeta =serde_json::from_str(&data).map_err(|e| Error::Parse(format!("project json: {e}")))?;Ok(Self { root, meta })@@ -239,7 +238,9 @@ impl Project {}pub fn analysis_export_path(&self, id: &str) -> PathBuf {- self.root.join("exports").join(format!("{id}_analysis.json"))+ self.root+ .join("exports")+ .join(format!("{id}_analysis.json"))}/// Load imported binary into a Program (does not auto-load saved analysis).@@ -248,7 +249,10 @@ impl Project {}/// Load program + apply saved analysis state if present.- pub fn load_program_with_results(&self, entry: &ProjectFileEntry) -> Result<(Program, Option<SavedAnalysis>)> {+ pub fn load_program_with_results(+ &self,+ entry: &ProjectFileEntry,+ ) -> Result<(Program, Option<SavedAnalysis>)> {let mut prog = self.load_program(entry)?;let saved = self.load_saved_analysis(&entry.id)?;if let Some(ref s) = saved {@@ -263,12 +267,7 @@ impl Project {for (va, name) in &prog.edits.renames.clone() {if let Some(f) = prog.function_at_mut(*va) {f.name = name.clone();- } else if let Some(sym) = prog- .analysis- .symbols- .iter_mut()- .find(|s| s.va == *va)- {+ } else if let Some(sym) = prog.analysis.symbols.iter_mut().find(|s| s.va == *va) {sym.name = name.clone();}}@@ -514,11 +513,7 @@ fn unique_id(display: &str, existing: &[ProjectFileEntry]) -> String {.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();- let stem = if stem.is_empty() {- "bin".into()- } else {- stem- };+ let stem = if stem.is_empty() { "bin".into() } else { stem };let mut n = 0u32;loop {let id = if n == 0 {@@ -540,10 +535,7 @@ mod tests {#[test]fn create_import_analyze_reopen() {- let dir = std::env::temp_dir().join(format!(- "ghidrust_proj_test_{}",- std::process::id()- ));+ let dir = std::env::temp_dir().join(format!("ghidrust_proj_test_{}", std::process::id()));let _ = fs::remove_dir_all(&dir);let mut proj = Project::create(&dir, "TestProj").unwrap();assert!(proj.project_json_path().is_file());@@ -591,10 +583,7 @@ mod tests {#[test]fn tree_rows_multi_file_active_and_status() {- let dir = std::env::temp_dir().join(format!(- "ghidrust_tree_{}",- std::process::id()- ));+ let dir = std::env::temp_dir().join(format!("ghidrust_tree_{}", std::process::id()));let _ = fs::remove_dir_all(&dir);let mut proj = Project::create(&dir, "Multi").unwrap();let a = proj.import_file(fixture_path("tiny_x64.pe")).unwrap();@@ -619,10 +608,7 @@ mod tests {#[test]fn remove_file_drops_import_and_results() {- let dir = std::env::temp_dir().join(format!(- "ghidrust_rm_{}",- std::process::id()- ));+ let dir = std::env::temp_dir().join(format!("ghidrust_rm_{}", std::process::id()));let _ = fs::remove_dir_all(&dir);let mut proj = Project::create(&dir, "Rm").unwrap();let a = proj.import_file(fixture_path("tiny_x64.pe")).unwrap();@@ -645,10 +631,7 @@ mod tests {#[test]fn analysis_bin_roundtrip_faster_path() {- let dir = std::env::temp_dir().join(format!(- "ghidrust_bin_{}",- std::process::id()- ));+ let dir = std::env::temp_dir().join(format!("ghidrust_bin_{}", std::process::id()));let _ = fs::remove_dir_all(&dir);let mut proj = Project::create(&dir, "Bin").unwrap();let a = proj.import_file(fixture_path("tiny_x64.pe")).unwrap();@@ -673,10 +656,7 @@ mod tests {fn program_edits_round_trip_through_save_and_load() {use crate::edits::{CommentKind, FunctionSignatureEdit};- let dir = std::env::temp_dir().join(format!(- "ghidrust_edits_rt_{}",- std::process::id()- ));+ let dir = std::env::temp_dir().join(format!("ghidrust_edits_rt_{}", std::process::id()));let _ = fs::remove_dir_all(&dir);let mut proj = Project::create(&dir, "Edits").unwrap();let entry = proj.import_file(fixture_path("tiny_x64.pe")).unwrap();@@ -714,25 +694,28 @@ mod tests {prog.edits.add_function_tag(va, "SANITIZED");let listing = disassemble_range(&prog, va, 8).unwrap_or_default();- proj.save_program_results(&entry.id, &prog, &listing, &["Function Start Search".into()])- .unwrap();+ proj.save_program_results(+ &entry.id,+ &prog,+ &listing,+ &["Function Start Search".into()],+ )+ .unwrap();// Reopen: full replay must land back on Program::edits and mirror// the rename into analysis.functions.let proj2 = Project::open(&dir).unwrap();- let e2 = proj2- .meta- .files- .iter()- .find(|f| f.id == entry.id)- .unwrap();+ let e2 = proj2.meta.files.iter().find(|f| f.id == entry.id).unwrap();let (prog2, saved2) = proj2.load_program_with_results(e2).unwrap();let saved2 = saved2.expect("saved analysis");assert_eq!(saved2.edits.rename_at(va), Some("my_main"));assert_eq!(prog2.edits.rename_at(va), Some("my_main"));assert_eq!(prog2.edits.retype_at(va), Some("int32_t *"));assert_eq!(prog2.edits.comment_at(va, CommentKind::Eol), Some("eol!"));- assert_eq!(prog2.edits.comment_at(va, CommentKind::Plate), Some("plate!"));+ assert_eq!(+ prog2.edits.comment_at(va, CommentKind::Plate),+ Some("plate!")+ );let sig = prog2.edits.function_signature(va).unwrap();assert_eq!(sig.signature, "int32_t my_main(char *argv)");assert_eq!(sig.return_type.as_deref(), Some("int32_t"));diff --git a/crates/ghidrust-core/src/resolve.rs b/crates/ghidrust-core/src/resolve.rsindex f8ec4cc..259b37e 100644--- a/crates/ghidrust-core/src/resolve.rs+++ b/crates/ghidrust-core/src/resolve.rs@@ -5,9 +5,7 @@use crate::analyzers::run_analyzers;use crate::error::Result;-use crate::pe_functions::{- create_function_with_kind, runtime_function_containing,-};+use crate::pe_functions::{create_function_with_kind, runtime_function_containing};use crate::program::{FunctionInfo, FunctionSeedKind, Program};use serde::{Deserialize, Serialize};@@ -244,9 +242,9 @@ mod tests {writable: false,executable: true,});- prog.analysis.functions.push(- FunctionInfo::new(entry, end, "f").with_seed_kind(FunctionSeedKind::Manual),- );+ prog.analysis+ .functions+ .push(FunctionInfo::new(entry, end, "f").with_seed_kind(FunctionSeedKind::Manual));prog}@@ -286,7 +284,9 @@ mod tests {executable: true,});// Non-empty functions list so first path does not only rely on empty-FSS.- prog.analysis.functions.push(FunctionInfo::new(0x2000, 0x2100, "elsewhere"));+ prog.analysis+ .functions+ .push(FunctionInfo::new(0x2000, 0x2100, "elsewhere"));let r = resolve_function(&mut prog, 0x1050).unwrap();assert!(r.ok);assert_eq!(r.resolve_status, ResolveStatus::Synthesized);diff --git a/crates/ghidrust-core/src/rtti.rs b/crates/ghidrust-core/src/rtti.rsindex fd97a0d..7644051 100644--- a/crates/ghidrust-core/src/rtti.rs+++ b/crates/ghidrust-core/src/rtti.rs@@ -58,9 +58,7 @@ pub fn recover_rtti(prog: &Program) -> Result<RttiReport> {}if report.classes.is_empty() {- report- .notes- .push("no RTTI class names recovered".into());+ report.notes.push("no RTTI class names recovered".into());} else {report.notes.push(format!("recovered {} class record(s)",@@ -202,7 +200,7 @@ fn find_vtable_for_col(prog: &Program, col_va: u64) -> Option<u64> {while off + 8 <= b.len() {let val = u64::from_le_bytes(b[off..off + 8].try_into().unwrap());if val == col_va {- // On MSVC x64, the COL pointer sits at vtable[-1]; first virtfn at this+8?+ // On MSVC x64, the COL pointer sits at vtable[-1]; first virtfn at this+8?// Actually: object.vfptr -> vtable[0] which is first function; COL is at vfptr[-1].// So the pointer we found is at address A where *A == col; vtable starts at A+8.return Some(block.va + off as u64 + 8);@@ -220,7 +218,10 @@ fn scan_itanium_typeinfo_names(prog: &Program) -> Vec<(u64, String)> {let mut i = 0;while i + 4 < b.len() {// _ZTS... null-terminated typeinfo name strings- if b[i] == b'_' && b.get(i + 1) == Some(&b'Z') && b.get(i + 2) == Some(&b'T') && b.get(i + 3) == Some(&b'S')+ if b[i] == b'_'+ && b.get(i + 1) == Some(&b'Z')+ && b.get(i + 2) == Some(&b'T')+ && b.get(i + 3) == Some(&b'S'){if let Some(s) = read_cstr(b, i) {if s.len() > 4 && s.len() < 256 {diff --git a/crates/ghidrust-core/src/rtti_catalog.rs b/crates/ghidrust-core/src/rtti_catalog.rsindex 31906c6..9ad2ad5 100644--- a/crates/ghidrust-core/src/rtti_catalog.rs+++ b/crates/ghidrust-core/src/rtti_catalog.rs@@ -78,18 +78,20 @@ pub fn catalog_from_report(report: &RttiReport) -> Vec<RttiCatalogEntry> {// Group by demangled name; collect all vtables/COLs.let mut by_name: HashMap<String, RttiCatalogEntry> = HashMap::new();for c in &report.classes {- let e = by_name.entry(c.name.clone()).or_insert_with(|| RttiCatalogEntry {- name: c.name.clone(),- mangled: None,- type_info_va: c.type_info_va,- col_va: c.col_va,- vtable_vas: vec![],- vtable_va: None,- confidence: "medium".into(),- notes: vec![],- reason: None,- kind: c.kind.clone(),- });+ let e = by_name+ .entry(c.name.clone())+ .or_insert_with(|| RttiCatalogEntry {+ name: c.name.clone(),+ mangled: None,+ type_info_va: c.type_info_va,+ col_va: c.col_va,+ vtable_vas: vec![],+ vtable_va: None,+ confidence: "medium".into(),+ notes: vec![],+ reason: None,+ kind: c.kind.clone(),+ });if e.type_info_va.is_none() {e.type_info_va = c.type_info_va;}@@ -111,8 +113,9 @@ pub fn catalog_from_report(report: &RttiReport) -> Vec<RttiCatalogEntry> {if e.vtable_vas.is_empty() {e.reason = Some("col_incomplete_or_no_vtable_link".into());e.confidence = "low".into();- e.notes- .push("vtable_vas empty — COL incomplete or link failed (not inventing RVA)".into());+ e.notes.push(+ "vtable_vas empty — COL incomplete or link failed (not inventing RVA)".into(),+ );} else if e.vtable_vas.len() > 1 {e.notes.push(format!("multiple vtables ({}) — MI / multiple COL; do not assume single VA",@@ -132,7 +135,9 @@ fn matches(name: &str, needle: &str, mode: RttiMatchMode) -> bool {let q = needle.to_ascii_lowercase();match mode {RttiMatchMode::Exact | RttiMatchMode::Whole => n == q,- RttiMatchMode::Token => n.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').any(|t| t == q),+ RttiMatchMode::Token => n+ .split(|c: char| !c.is_ascii_alphanumeric() && c != '_')+ .any(|t| t == q),RttiMatchMode::Glob => glob_match(&n, &q),RttiMatchMode::Substr => n.contains(&q),}@@ -241,8 +246,7 @@ pub fn enrich_class(c: &RttiClass) -> RttiCatalogEntry {kind: c.kind.clone(),};if e.vtable_vas.is_empty() {- e.notes- .push("vtable_vas empty — not inventing RVA".into());+ e.notes.push("vtable_vas empty — not inventing RVA".into());}e}diff --git a/crates/ghidrust-core/src/section_notes.rs b/crates/ghidrust-core/src/section_notes.rsindex e4e6e05..e76d506 100644--- a/crates/ghidrust-core/src/section_notes.rs+++ b/crates/ghidrust-core/src/section_notes.rs@@ -13,9 +13,9 @@ pub struct SectionNote {/// Well-known PE section names (informational allowlist).const STANDARD_PE_NAMES: &[&str] = &[- ".text", ".rdata", ".data", ".pdata", ".xdata", ".bss", ".edata", ".idata",- ".rsrc", ".reloc", ".tls", ".debug", ".didat", ".gfids", ".00cfg", ".CRT",- ".code", ".idata", "CODE", "DATA", "BSS", ".rodata",+ ".text", ".rdata", ".data", ".pdata", ".xdata", ".bss", ".edata", ".idata", ".rsrc", ".reloc",+ ".tls", ".debug", ".didat", ".gfids", ".00cfg", ".CRT", ".code", ".idata", "CODE", "DATA",+ "BSS", ".rodata",];fn is_standard_name(name: &str) -> bool {@@ -85,7 +85,11 @@ fn notes_for_section(prog: &Program, s: &SectionInfo) -> Vec<SectionNote> {}// Tiny high-entropy tip: small section with high byte entropy in mapped bytes.if s.virtual_size > 0 && s.virtual_size <= 0x1000 {- if let Some(block) = prog.blocks.iter().find(|b| b.name == s.name || b.va == s.va) {+ if let Some(block) = prog+ .blocks+ .iter()+ .find(|b| b.name == s.name || b.va == s.va)+ {let sample_len = (block.bytes.len()).min(256);if sample_len >= 32 {let ent = sample_entropy(&block.bytes[..sample_len]);diff --git a/crates/ghidrust-core/src/tree_index.rs b/crates/ghidrust-core/src/tree_index.rsindex 14a0bfb..1dd33a4 100644--- a/crates/ghidrust-core/src/tree_index.rs+++ b/crates/ghidrust-core/src/tree_index.rs@@ -94,14 +94,7 @@ pub fn list_tree(root: impl AsRef<Path>, opts: TreeListOpts) -> TreeListResult {let root = root.as_ref();let mut entries = Vec::new();let mut truncated = false;- walk(- root,- root,- 0,- &opts,- &mut entries,- &mut truncated,- );+ walk(root, root, 0, &opts, &mut entries, &mut truncated);TreeListResult {root: root.display().to_string(),entries,@@ -168,10 +161,7 @@ fn walk(};if meta.file_type().is_symlink() && !opts.follow_symlinks {// Record symlink as a leaf row; do not descend.- let name = path- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("");+ let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");if let Some(g) = &opts.name_glob {if !name_matches(name, g) {continue;@@ -187,10 +177,7 @@ fn walk(continue;}let is_dir = meta.is_dir();- let name = path- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("");+ let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");if let Some(g) = &opts.name_glob {if !is_dir && !name_matches(name, g) {continue;@@ -225,11 +212,8 @@ mod tests {#[test]fn lists_files_with_ext_filter() {- let dir = std::env::temp_dir().join(format!(- "ghidrust-tree-{}-{}",- std::process::id(),- "t"- ));+ let dir =+ std::env::temp_dir().join(format!("ghidrust-tree-{}-{}", std::process::id(), "t"));let _ = fs::remove_dir_all(&dir);fs::create_dir_all(dir.join("sub")).unwrap();fs::write(dir.join("a.exe"), b"x").unwrap();diff --git a/crates/ghidrust-core/src/xrefs.rs b/crates/ghidrust-core/src/xrefs.rsindex 769184d..5686384 100644--- a/crates/ghidrust-core/src/xrefs.rs+++ b/crates/ghidrust-core/src/xrefs.rs@@ -7,9 +7,7 @@//! 4. Decoded instructions — absolute operand hex + RIP-relative targets//! 5. Import / IAT slots — `call/jmp [rip+disp]` landing on IAT VAs-use crate::disasm::{- decode_one, disassemble_range, disassemble_range_ex, DisasmMode,-};+use crate::disasm::{decode_one, disassemble_range, disassemble_range_ex, DisasmMode};use crate::program::{ImportEntry, Program};use serde::Serialize;@@ -69,7 +67,13 @@ pub fn xrefs_to(for r in &prog.analysis.references {if r.to == target {- out.push(xref(r.from, r.to, static_kind(&r.kind), r.kind.clone(), None));+ out.push(xref(+ r.from,+ r.to,+ static_kind(&r.kind),+ r.kind.clone(),+ None,+ ));}}@@ -348,10 +352,7 @@ pub fn rip_relative_targets(insn: &crate::disasm::Instruction) -> Vec<u64> {let mut i = 0;while i + 5 < bytes.len() {// look for "[rip"- if bytes[i] == b'['- && i + 4 < bytes.len()- && &ops[i..i + 4] == "[rip"- {+ if bytes[i] == b'[' && i + 4 < bytes.len() && &ops[i..i + 4] == "[rip" {let after = i + 4;let rest = &ops[after..];if let Some((disp, consumed)) = parse_rip_disp(rest) {@@ -440,11 +441,7 @@ fn scan_exec_xrefs_to(prog: &Program, target: u64, out: &mut Vec<XRef>) {}}-fn push_listing_xrefs_to(- listing: &[crate::disasm::Instruction],- target: u64,- out: &mut Vec<XRef>,-) {+fn push_listing_xrefs_to(listing: &[crate::disasm::Instruction], target: u64, out: &mut Vec<XRef>) {for insn in listing {if instruction_targets(insn).contains(&target) {out.push(xref(@@ -458,13 +455,7 @@ fn push_listing_xrefs_to(}}-fn xref(- from: u64,- to: u64,- kind: &'static str,- preview: String,- encoding: Option<String>,-) -> XRef {+fn xref(from: u64, to: u64, kind: &'static str, preview: String, encoding: Option<String>) -> XRef {XRef {from,to,@@ -478,7 +469,10 @@ fn xref(}fn resolve_target_fn(prog: &Program, va: u64) -> (Option<u64>, Option<String>) {- if let Some(f) = prog.function_at(va).or_else(|| prog.function_containing(va)) {+ if let Some(f) = prog+ .function_at(va)+ .or_else(|| prog.function_containing(va))+ {(Some(f.entry), Some(f.name.clone()))} else {(None, None)@@ -490,7 +484,10 @@ fn attribute(prog: &Program, r: &mut XRef) {r.from_entry = Some(f.entry);r.from_function = Some(f.name.clone());}- if let Some(f) = prog.function_at(r.to).or_else(|| prog.function_containing(r.to)) {+ if let Some(f) = prog+ .function_at(r.to)+ .or_else(|| prog.function_containing(r.to))+ {r.to_entry = Some(f.entry);}}@@ -563,7 +560,11 @@ mod tests {let insn = decode_one(&bytes, 0x1000).unwrap();assert_eq!(insn.mnemonic, "lea");let tgts = instruction_targets(&insn);- assert!(tgts.contains(&0x1017), "targets={tgts:?} ops={}", insn.operands);+ assert!(+ tgts.contains(&0x1017),+ "targets={tgts:?} ops={}",+ insn.operands+ );}#[test]@@ -581,12 +582,14 @@ mod tests {fn xrefs_to_returns_analysis_and_ptr_table_refs() {let mut prog = load_path(fixture_path("analysis_lab.pe")).unwrap();let entry = prog.entry.unwrap();- prog.analysis.address_tables.push(crate::program::AddressTableInfo {- base: prog.image_base,- count: 1,- entries: vec![entry],- role: crate::program::AddressTableRole::Unknown,- });+ prog.analysis+ .address_tables+ .push(crate::program::AddressTableInfo {+ base: prog.image_base,+ count: 1,+ entries: vec![entry],+ role: crate::program::AddressTableRole::Unknown,+ });prog.analysis.references.push(ReferenceInfo {from: prog.image_base + 0x40,to: entry,@@ -634,10 +637,8 @@ mod tests {});let refs = xrefs_to_string_filter_opts(&prog, "WideLab", "utf16le", false);assert!(- refs.iter().any(|r| {- r.from == insn_va- && r.encoding.as_deref() == Some("utf16le")- }),+ refs.iter()+ .any(|r| { r.from == insn_va && r.encoding.as_deref() == Some("utf16le") }),"{refs:?}");let ascii_only = xrefs_to_string_filter_opts(&prog, "WideLab", "ascii", false);@@ -765,7 +766,9 @@ mod tests {let edges = calls_callees(&prog, caller);assert!(- edges.iter().any(|e| e.to == callee && e.to_entry == Some(callee)),+ edges+ .iter()+ .any(|e| e.to == callee && e.to_entry == Some(callee)),"{edges:?}");}diff --git a/crates/ghidrust-core/tests/analyzer_content.rs b/crates/ghidrust-core/tests/analyzer_content.rsindex abdf5ec..56e9430 100644--- a/crates/ghidrust-core/tests/analyzer_content.rs+++ b/crates/ghidrust-core/tests/analyzer_content.rs@@ -10,7 +10,11 @@ fn run(name: &str) -> AnalyzerOutput {let mut prog = lab();let rep = run_analyzers(&mut prog, &[name]).unwrap();assert_eq!(rep.results.len(), 1);- assert_eq!(rep.results[0].status, "ok", "{}: {}", name, rep.results[0].message);+ assert_eq!(+ rep.results[0].status, "ok",+ "{}: {}",+ name, rep.results[0].message+ );rep.results.into_iter().next().unwrap()}@@ -19,7 +23,12 @@ fn ascii_strings_finds_api_and_class_names() {let o = run("ASCII Strings");let s = o.strings.as_ref().expect("strings field");assert!(s.iter().any(|x| x.value.contains("ExitProcess")), "{s:?}");- assert!(s.iter().any(|x| x.value.contains("printf") || x.value.contains("LabClass") || x.value.contains("MyFunc")), "{s:?}");+ assert!(+ s.iter().any(|x| x.value.contains("printf")+ || x.value.contains("LabClass")+ || x.value.contains("MyFunc")),+ "{s:?}"+ );}#[test]@@ -29,7 +38,8 @@ fn function_start_finds_entry_and_lab_functions() {assert!(fns.iter().any(|f| f.entry == 0x140001000), "{fns:?}");// prologue-based startsassert!(- fns.iter().any(|f| f.entry == 0x140001030 || f.entry == 0x140001018),+ fns.iter()+ .any(|f| f.entry == 0x140001030 || f.entry == 0x140001018),"expected stack/orphan start: {fns:?}");// Must NOT create mid-prologue seed at 0x140001034 (sub rsp inside func_stack)@@ -66,7 +76,9 @@ fn aggressive_finds_orphan_or_gap_code() {.as_ref().expect("recovered_ranges");assert!(- ranges.iter().any(|r| r.start == 0x140001018 || r.start == 0x140001030),+ ranges+ .iter()+ .any(|r| r.start == 0x140001018 || r.start == 0x140001030),"expected gap recovery: {ranges:?}");}@@ -77,18 +89,22 @@ fn call_convention_tags_entry() {run_analyzers(&mut prog, &["Function Start Search"]).unwrap();let rep = run_analyzers(&mut prog, &["Call Convention ID"]).unwrap();let c = rep.results[0].conventions.as_ref().expect("conventions");- assert!(c.iter().any(|(va, name)| *va == 0x140001000 && !name.is_empty()), "{c:?}");+ assert!(+ c.iter()+ .any(|(va, name)| *va == 0x140001000 && !name.is_empty()),+ "{c:?}"+ );}#[test]fn call_fixup_finds_security_cookie_string() {let o = run("Call-Fixup Installer");let f = o.call_fixups.as_ref().expect("call_fixups");+ assert!(f.iter().any(|x| x.fixup_name == "security_cookie"), "{f:?}");assert!(- f.iter().any(|x| x.fixup_name == "security_cookie"),- "{f:?}"+ f.iter().any(|x| x.call_va == 0x140002018),+ "cookie VA: {f:?}");- assert!(f.iter().any(|x| x.call_va == 0x140002018), "cookie VA: {f:?}");}#[test]@@ -161,7 +177,10 @@ fn demangler_microsoft_lab_mangled() {fn embedded_media_finds_png() {let o = run("Embedded Media");let m = o.media.as_ref().expect("media");- assert!(m.iter().any(|h| h.kind == "PNG" && h.va == 0x140002050), "{m:?}");+ assert!(+ m.iter().any(|h| h.kind == "PNG" && h.va == 0x140002050),+ "{m:?}"+ );}#[test]@@ -171,7 +190,8 @@ fn function_id_matches_entry_prolog() {let rep = run_analyzers(&mut prog, &["Function ID"]).unwrap();let m = rep.results[0].fid_matches.as_ref().expect("fid");assert!(- m.iter().any(|x| x.entry == 0x140001000 && x.matched_name.contains("fid_")),+ m.iter()+ .any(|x| x.entry == 0x140001000 && x.matched_name.contains("fid_")),"{m:?}");}@@ -191,7 +211,8 @@ fn pdb_universal_parses_stream_symbols() {let s = o.symbols.as_ref().expect("pdb symbols");assert!(s.iter().any(|x| x.name.contains("MSF7")), "{s:?}");assert!(- s.iter().any(|x| x.name == "LabEntry" || x.name == "LabStackFrame"),+ s.iter()+ .any(|x| x.name == "LabEntry" || x.name == "LabStackFrame"),"stream names: {s:?}");}@@ -200,7 +221,11 @@ fn pdb_universal_parses_stream_symbols() {fn pdb_msdia_same_portable_path() {let o = run("PDB MSDIA");let s = o.symbols.as_ref().expect("symbols");- assert!(s.iter().any(|x| x.name == "LabNoReturn" || x.name.contains("Lab")), "{s:?}");+ assert!(+ s.iter()+ .any(|x| x.name == "LabNoReturn" || x.name.contains("Lab")),+ "{s:?}"+ );}#[test]@@ -210,7 +235,10 @@ fn shared_return_matches_two_epilogues() {let rep = run_analyzers(&mut prog, &["Shared Return Calls"]).unwrap();let sh = rep.results[0].shared_returns.as_ref().expect("shared");assert!(sh.len() >= 2, "{sh:?}");- assert!(sh.contains(&0x140001070) || sh.iter().any(|&e| e == 0x140001090 || e == 0x140001070), "{sh:?}");+ assert!(+ sh.contains(&0x140001070) || sh.iter().any(|&e| e == 0x140001090 || e == 0x140001070),+ "{sh:?}"+ );}#[test]@@ -223,7 +251,9 @@ fn stack_recovers_frame_size() {assert!(stack_fn.is_some(), "{frames:?}");let locals = &stack_fn.unwrap().1;assert!(- locals.iter().any(|l| l.contains("frame_size=0x20") || l.contains("param_")),+ locals+ .iter()+ .any(|l| l.contains("frame_size=0x20") || l.contains("param_")),"{locals:?}");}@@ -239,9 +269,17 @@ fn stack_entry_not_polluted_by_later_body() {.iter().find(|f| f.entry == 0x140001000).expect("entry");- assert!(entry_fn.end <= 0x140001018, "entry end: {:#x}", entry_fn.end);+ assert!(+ entry_fn.end <= 0x140001018,+ "entry end: {:#x}",+ entry_fn.end+ );let rep = run_analyzers(&mut prog, &["Stack"]).unwrap();- let frames = rep.results[0].stack_frames.as_ref().cloned().unwrap_or_default();+ let frames = rep.results[0]+ .stack_frames+ .as_ref()+ .cloned()+ .unwrap_or_default();// Entry has no sub rsp / param spill — must not appear in frames (no filler)assert!(!frames.iter().any(|(va, _)| *va == 0x140001000),@@ -249,8 +287,10 @@ fn stack_entry_not_polluted_by_later_body() {);// func_stack still realassert!(- frames.iter().any(|(va, locs)| *va == 0x140001030- && locs.iter().any(|l| l.contains("frame_size=0x20"))),+ frames+ .iter()+ .any(|(va, locs)| *va == 0x140001030+ && locs.iter().any(|l| l.contains("frame_size=0x20"))),"{frames:?}");}@@ -275,7 +315,8 @@ fn external_params_exitprocess() {let o = run("Windows x86 Propagate External Parameters");let e = o.external_params.as_ref().expect("external_params");assert!(- e.iter().any(|(va, p)| *va == 0x140002000 && p.contains("ExitProcess")),+ e.iter()+ .any(|(va, p)| *va == 0x140002000 && p.contains("ExitProcess")),"{e:?}");}@@ -285,7 +326,8 @@ fn resources_find_version_marker() {let o = run("WindowsResourceReference");let r = o.resources.as_ref().expect("resources");assert!(- r.iter().any(|x| x.name.contains("VERSION") && x.va == 0x140002090),+ r.iter()+ .any(|x| x.name.contains("VERSION") && x.va == 0x140002090),"{r:?}");}@@ -298,13 +340,19 @@ fn bare_tiny_pe_no_fake_switch_or_pdb_entry() {if let Some(sw) = &rep.results[0].switches {for s in sw {assert!(- !(s.jump_va == prog.entry.unwrap() && s.cases.len() == 2 && s.cases[0].1 == prog.entry.unwrap()),+ !(s.jump_va == prog.entry.unwrap()+ && s.cases.len() == 2+ && s.cases[0].1 == prog.entry.unwrap()),"fabricated switch at entry: {s:?}");}}let rep2 = run_analyzers(&mut prog, &["PDB Universal"]).unwrap();- let syms = rep2.results[0].symbols.as_ref().cloned().unwrap_or_default();+ let syms = rep2.results[0]+ .symbols+ .as_ref()+ .cloned()+ .unwrap_or_default();assert!(!syms.iter().any(|s| s.name == "PDB_entry"),"fabricated PDB_entry: {syms:?}"diff --git a/crates/ghidrust-core/tests/bounds_truncated_fixture.rs b/crates/ghidrust-core/tests/bounds_truncated_fixture.rsindex 2462c2a..0c3017f 100644--- a/crates/ghidrust-core/tests/bounds_truncated_fixture.rs+++ b/crates/ghidrust-core/tests/bounds_truncated_fixture.rs@@ -54,8 +54,8 @@ fn linear_returns_more_than_prologue_only_bounded() {Some(short_end),).expect("bounded");- let linear = disassemble_range_ex(&prog, entry, 80, false, DisasmMode::Linear, None)- .expect("linear");+ let linear =+ disassemble_range_ex(&prog, entry, 80, false, DisasmMode::Linear, None).expect("linear");assert_eq!(bounded.stop_reason, DisasmStopReason::FunctionEnd);assert!(diff --git a/crates/ghidrust-core/tests/crypto_discover_fixtures.rs b/crates/ghidrust-core/tests/crypto_discover_fixtures.rsnew file mode 100644index 0000000..83b8f4b--- /dev/null+++ b/crates/ghidrust-core/tests/crypto_discover_fixtures.rs@@ -0,0 +1,289 @@+//! Synthetic, native x86-oriented fixtures for crypto discovery and recipe success metrics.++use ghidrust_core::{+ bake, recover_obfuscated_strings, run_analyzers, scan_crypt_constants,+ run_crypto_pipeline, scan_crypto_capabilities, BakeOp, ImportEntry, MemoryBlock,+ ObfuscatedStringKind, Program,+ RecoverStringsOpts,+};++fn block(name: &str, va: u64, bytes: Vec<u8>, executable: bool) -> MemoryBlock {+ MemoryBlock {+ name: name.into(),+ va,+ size: bytes.len() as u64,+ bytes,+ readable: true,+ writable: false,+ executable,+ }+}++fn hex(input: &str) -> Vec<u8> {+ let input: String = input+ .chars()+ .filter(|character| !character.is_whitespace())+ .collect();+ (0..input.len())+ .step_by(2)+ .map(|i| u8::from_str_radix(&input[i..i + 2], 16).unwrap())+ .collect()+}++fn b64_encode(input: &[u8]) -> String {+ const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ let mut out = String::new();+ for chunk in input.chunks(3) {+ let a = chunk[0];+ let b = *chunk.get(1).unwrap_or(&0);+ let c = *chunk.get(2).unwrap_or(&0);+ out.push(TABLE[(a >> 2) as usize] as char);+ out.push(TABLE[((a & 0x03) << 4 | b >> 4) as usize] as char);+ out.push(if chunk.len() > 1 {+ TABLE[((b & 0x0f) << 2 | c >> 6) as usize] as char+ } else {+ '='+ });+ out.push(if chunk.len() > 2 {+ TABLE[(c & 0x3f) as usize] as char+ } else {+ '='+ });+ }+ out+}++#[test]+fn crypto_constants_discovers_aes_sbox_and_tea_delta_and_annotates_symbols() {+ let aes_sbox = hex("+ 63 7c 77 7b f2 6b 6f c5 30 01 67 2b fe d7 ab 76+ ca 82 c9 7d fa 59 47 f0 ad d4 a2 af 9c a4 72 c0+ b7 fd 93 26 36 3f f7 cc 34 a5 e5 f1 71 d8 31 15+ 04 c7 23 c3 18 96 05 9a 07 12 80 e2 eb 27 b2 75+ 09 83 2c 1a 1b 6e 5a a0 52 3b d6 b3 29 e3 2f 84+ 53 d1 00 ed 20 fc b1 5b 6a cb be 39 4a 4c 58 cf+ d0 ef aa fb 43 4d 33 85 45 f9 02 7f 50 3c 9f a8+ 51 a3 40 8f 92 9d 38 f5 bc b6 da 21 10 ff f3 d2+ cd 0c 13 ec 5f 97 44 17 c4 a7 7e 3d 64 5d 19 73+ 60 81 4f dc 22 2a 90 88 46 ee b8 14 de 5e 0b db+ e0 32 3a 0a 49 06 24 5c c2 d3 ac 62 91 95 e4 79+ e7 c8 37 6d 8d d5 4e a9 6c 56 f4 ea 65 7a ae 08+ ba 78 25 2e 1c a6 b4 c6 e8 dd 74 1f 4b bd 8b 8a+ 70+ 3e b5 66 48 03 f6 0e 61 35 57 b9 86 c1 1d 9e e1+ f8 98 11 69 d9 8e 94 9b 1e 87 e9 ce 55 28 df 8c+ a1 89 0d bf e6 42 68 41 99 2d 0f b0 54 bb 16+ ");+ // Keep the fixture native: these are raw bytes in a synthetic read-only data mapping.+ let mut bytes = vec![0x90; 11];+ bytes.extend_from_slice(&aes_sbox);+ bytes.extend_from_slice(&[0x90; 7]);+ bytes.extend_from_slice(&[0xb9, 0x79, 0x37, 0x9e]);++ let mut program = Program::new("crypt-constants".into(), "raw");+ program.blocks.push(block(".rdata", 0x5000, bytes, false));++ let hits = scan_crypt_constants(&program);+ assert!(+ hits.iter()+ .any(|hit| hit.algorithm == "AES" && hit.constant == "SBOX"),+ "{hits:?}"+ );+ assert!(+ hits.iter()+ .any(|hit| hit.algorithm == "TEA" && hit.constant == "DELTA"),+ "{hits:?}"+ );++ let report = run_analyzers(&mut program, &["Find Crypt"]).expect("Find Crypt runs");+ assert_eq!(report.results[0].name, "Find Crypt");+ assert_eq!(report.results[0].status, "ok");+ assert!(+ program+ .analysis+ .symbols+ .iter()+ .any(|symbol| symbol.name == "CRYPT_AES_SBOX"),+ "{:?}",+ program.analysis.symbols+ );+ assert!(+ program+ .analysis+ .symbols+ .iter()+ .any(|symbol| symbol.name == "CRYPT_TEA_DELTA"),+ "{:?}",+ program.analysis.symbols+ );+}++#[test]+fn recover_obfuscated_strings_finds_stack_and_xor_decoder_results() {+ let mut stack_code = Vec::new();+ for (disp, byte) in b"stack\0".iter().enumerate() {+ stack_code.extend_from_slice(&[0xc6, 0x45, disp as u8, *byte]);+ }++ let key = 0x5a;+ let mut xor_code = vec![0x34, key]; // xor al, imm8: decoder pre-filter evidence.+ for (disp, byte) in b"decoded".iter().enumerate() {+ xor_code.extend_from_slice(&[0xc6, 0x45, 0x20 + disp as u8, byte ^ key]);+ }+ for disp in 0x20..0x27 {+ xor_code.extend_from_slice(&[0x80, 0x75, disp, key]); // xor byte ptr [rbp+disp], imm8+ }+ xor_code.extend_from_slice(&[0xeb, 0xfe]); // native short backward edge++ let mut program = Program::new("stack-and-xor".into(), "raw");+ program+ .blocks+ .push(block(".text.stack", 0x401000, stack_code, true));+ program+ .blocks+ .push(block(".text.xor", 0x402000, xor_code, true));++ let hits = recover_obfuscated_strings(&program, &RecoverStringsOpts::default());+ assert!(+ hits.iter()+ .any(|hit| hit.value == "stack" && hit.kind == ObfuscatedStringKind::Stack),+ "{hits:?}"+ );+ let decoded = hits+ .iter()+ .find(|hit| hit.value == "decoded" && hit.kind == ObfuscatedStringKind::Decoded)+ .expect("XOR-decoded string");+ assert_eq!(decoded.decoder_va, Some(0x402000 + 2 + 7 * 4));+}++#[test]+fn bake_peels_base64_gzip_xor_and_decrypts_known_aes_cbc_vector() {+ let plain = b"crypto fixture";+ let key = 0x5a;+ let xored: Vec<u8> = plain.iter().map(|byte| byte ^ key).collect();+ // A deterministic stored-DEFLATE gzip member; the decoder intentionally accepts this+ // minimal synthetic member without requiring a third-party compressor in the test.+ let mut gzip = vec![0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0, 0xff, 0x01];+ gzip.extend_from_slice(&(xored.len() as u16).to_le_bytes());+ gzip.extend_from_slice(&(!(xored.len() as u16)).to_le_bytes());+ gzip.extend_from_slice(&xored);+ gzip.extend_from_slice(&[0; 8]);+ let encoded = b64_encode(&gzip);+ let peel = bake(+ encoded.as_bytes(),+ &[+ BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "Gunzip".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "XOR".into(),+ args: serde_json::json!({"key_hex": "5a"}),+ },+ ],+ );+ assert!(peel.ok, "{}", peel.message);+ assert_eq!(peel.output_utf8.as_deref(), Some("crypto fixture"));++ let aes = bake(+ &hex("7649abac8119b246cee98e9b12e9197d"),+ &[BakeOp {+ op: "AESDecrypt".into(),+ args: serde_json::json!({+ "key_hex": "2b7e151628aed2a6abf7158809cf4f3c",+ "iv_hex": "000102030405060708090a0b0c0d0e0f",+ "mode": "cbc"+ }),+ }],+ );+ assert!(aes.ok, "{}", aes.message);+ assert_eq!(aes.output_hex, "6bc1bee22e409f96e93d7e117393172a");+}++#[test]+fn crypto_capabilities_find_import_aesni_and_base64_evidence() {+ let mut program = Program::new("capabilities".into(), "raw");+ program.imports.push(ImportEntry {+ dll: "advapi32.dll".into(),+ name: Some("CryptDecrypt".into()),+ ordinal: None,+ iat_va: 0x7000,+ ilt_va: None,+ });+ program.blocks.push(block(+ ".text",+ 0x401000,+ vec![0x90, 0x66, 0x0f, 0x38, 0xdf, 0xc0],+ true,+ ));+ program.blocks.push(block(+ ".rdata",+ 0x5000,+ b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".to_vec(),+ false,+ ));++ let hits = scan_crypto_capabilities(&program, None);+ assert!(+ hits.iter()+ .any(|hit| hit.evidence.contains("CryptDecrypt") && hit.tag == "decrypt"),+ "{hits:?}"+ );+ assert!(+ hits.iter()+ .any(|hit| hit.evidence.contains("opcode @ 0x401001")),+ "{hits:?}"+ );+ assert!(+ hits.iter()+ .any(|hit| hit.capability.contains("Base64") && hit.tag == "encoding"),+ "{hits:?}"+ );+}++#[test]+fn crypto_pipeline_preserves_find_crypt_state_for_capabilities() {+ let mut program = Program::new("pipeline".into(), "raw");+ let mut code = vec![0x90, 0xb9, 0x79, 0x37, 0x9e]; // TEA delta+ for (disp, byte) in b"seed\0".iter().enumerate() {+ code.extend_from_slice(&[0xc6, 0x45, disp as u8, *byte]);+ }+ program.blocks.push(block(".text", 0x401000, code, true));++ let outputs = run_crypto_pipeline(&mut program).expect("crypto pipeline succeeds");+ assert_eq!(+ outputs.iter().map(|output| output.name.as_str()).collect::<Vec<_>>(),+ vec!["Find Crypt", "Obfuscated Strings", "Crypto Capabilities"]+ );+ assert!(+ program+ .analysis+ .crypt_constants+ .iter()+ .any(|hit| hit.algorithm == "TEA"),+ "{:?}",+ program.analysis.crypt_constants+ );+ assert!(+ program+ .analysis+ .obfuscated_strings+ .iter()+ .any(|hit| hit.value == "seed"),+ "{:?}",+ program.analysis.obfuscated_strings+ );+ assert!(+ program+ .analysis+ .crypto_capabilities+ .iter()+ .any(|hit| hit.capability.contains("TEA constants present")),+ "{:?}",+ program.analysis.crypto_capabilities+ );+}diff --git a/crates/ghidrust-core/tests/feature_matrix_doc.rs b/crates/ghidrust-core/tests/feature_matrix_doc.rsindex 9269a6b..71f2120 100644--- a/crates/ghidrust-core/tests/feature_matrix_doc.rs+++ b/crates/ghidrust-core/tests/feature_matrix_doc.rs@@ -25,10 +25,7 @@ fn matrix_lists_all_and_marks_have() {// Each A.xx row should be havefor line in matrix.lines() {if line.trim_start().starts_with("| A.") && line.contains('|') {- assert!(- line.contains("**have**"),- "A-row not have: {line}"- );+ assert!(line.contains("**have**"), "A-row not have: {line}");}}}@@ -77,26 +74,62 @@ fn lab_run_all_analyzers_ok_with_structured_primary() {}fn primary_nonempty(o: &ghidrust_core::AnalyzerOutput) -> bool {- o.rtti.as_ref().map(|r| !r.classes.is_empty()).unwrap_or(false)+ o.rtti+ .as_ref()+ .map(|r| !r.classes.is_empty())+ .unwrap_or(false)|| o.strings.as_ref().map(|s| !s.is_empty()).unwrap_or(false)|| o.functions.as_ref().map(|f| !f.is_empty()).unwrap_or(false)- || o.recovered_ranges.as_ref().map(|r| !r.is_empty()).unwrap_or(false)- || o.address_tables.as_ref().map(|t| !t.is_empty()).unwrap_or(false)- || o.call_fixups.as_ref().map(|c| !c.is_empty()).unwrap_or(false)+ || o.recovered_ranges+ .as_ref()+ .map(|r| !r.is_empty())+ .unwrap_or(false)+ || o.address_tables+ .as_ref()+ .map(|t| !t.is_empty())+ .unwrap_or(false)+ || o.call_fixups+ .as_ref()+ .map(|c| !c.is_empty())+ .unwrap_or(false)|| o.media.as_ref().map(|m| !m.is_empty()).unwrap_or(false)- || o.fid_matches.as_ref().map(|f| !f.is_empty()).unwrap_or(false)+ || o.fid_matches+ .as_ref()+ .map(|f| !f.is_empty())+ .unwrap_or(false)|| o.resources.as_ref().map(|r| !r.is_empty()).unwrap_or(false)|| o.switches.as_ref().map(|s| !s.is_empty()).unwrap_or(false)|| o.symbols.as_ref().map(|s| !s.is_empty()).unwrap_or(false)- || o.shared_returns.as_ref().map(|s| !s.is_empty()).unwrap_or(false)- || o.conventions.as_ref().map(|c| !c.is_empty()).unwrap_or(false)- || o.noreturn_entries.as_ref().map(|n| !n.is_empty()).unwrap_or(false)- || o.stack_frames.as_ref().map(|s| !s.is_empty()).unwrap_or(false)- || o.varargs_entries.as_ref().map(|v| !v.is_empty()).unwrap_or(false)- || o.external_params.as_ref().map(|e| !e.is_empty()).unwrap_or(false)+ || o.shared_returns+ .as_ref()+ .map(|s| !s.is_empty())+ .unwrap_or(false)+ || o.conventions+ .as_ref()+ .map(|c| !c.is_empty())+ .unwrap_or(false)+ || o.noreturn_entries+ .as_ref()+ .map(|n| !n.is_empty())+ .unwrap_or(false)+ || o.stack_frames+ .as_ref()+ .map(|s| !s.is_empty())+ .unwrap_or(false)+ || o.varargs_entries+ .as_ref()+ .map(|v| !v.is_empty())+ .unwrap_or(false)+ || o.external_params+ .as_ref()+ .map(|e| !e.is_empty())+ .unwrap_or(false)}#[test]fn docs_link_tech_plans() {- assert!(read_doc("ROADMAP.md").contains("ANALYZER_TECH_PLANS") || read_doc("ROADMAP.md").contains("FEATURE_MATRIX"));+ assert!(+ read_doc("ROADMAP.md").contains("ANALYZER_TECH_PLANS")+ || read_doc("ROADMAP.md").contains("FEATURE_MATRIX")+ );}diff --git a/crates/ghidrust-decode/src/alloc_hooks.rs b/crates/ghidrust-decode/src/alloc_hooks.rsindex 9c2f065..3104f23 100644--- a/crates/ghidrust-decode/src/alloc_hooks.rs+++ b/crates/ghidrust-decode/src/alloc_hooks.rs@@ -2,7 +2,7 @@pub trait AllocHooks: Send + Sync {fn malloc(&self, size: usize) -> *mut u8 {let layout = std::alloc::Layout::from_size_align(size, 8).unwrap_or_else(|_| {- std::alloc::Layout::from_size_align(1, 1).expect("fallback layout")+ std::alloc::Layout::from_size_align(1, 1).expect("fallback layout")});unsafe { std::alloc::alloc(layout) }}@@ -21,7 +21,7 @@ pub trait AllocHooks: Send + Sync {return self.malloc(size);}let layout = std::alloc::Layout::from_size_align(size, 8).unwrap_or_else(|_| {- std::alloc::Layout::from_size_align(1, 1).expect("fallback layout")+ std::alloc::Layout::from_size_align(1, 1).expect("fallback layout")});unsafe { std::alloc::realloc(ptr, layout, size) }}@@ -30,7 +30,7 @@ pub trait AllocHooks: Send + Sync {if ptr.is_null() {return;}- let layout = std::alloc::Layout::from_size_align(1, 1).expect("free layout");+ let layout = std::alloc::Layout::from_size_align(1, 1).expect("free layout");unsafe { std::alloc::dealloc(ptr, layout) }}}diff --git a/crates/ghidrust-decode/src/arch/aarch64/branches.rs b/crates/ghidrust-decode/src/arch/aarch64/branches.rsindex 0966e31..43d437b 100644--- a/crates/ghidrust-decode/src/arch/aarch64/branches.rs+++ b/crates/ghidrust-decode/src/arch/aarch64/branches.rs@@ -41,7 +41,7 @@ fn decode_b_imm(wd: u32, address: u64, raw: &[u8], link: bool) -> Result<Instruclet imm26 = bit(wd, 0, 25);let offset = sign_extend((imm26 as u64) << 2, 28);let target = (address as i64).wrapping_add(offset) as u64;- let mnemonic = if link { "bl" } else { "b" };+ let mnemonic = if link { "bl" } else { "b" };Ok(Instruction::with_text(address,raw.to_vec(),@@ -59,7 +59,7 @@ fn decode_b_cond(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {Ok(Instruction::with_text(address,raw.to_vec(),- format!("b.{}", super::util::cond_name(cond)),+ format!("b.{}", super::util::cond_name(cond)),fmt_imm_hex(target as i64),4,))@@ -70,7 +70,7 @@ fn decode_br(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {Ok(Instruction::with_text(address,raw.to_vec(),- "br",+ "br",x(rn),4,))@@ -81,7 +81,7 @@ fn decode_blr(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {Ok(Instruction::with_text(address,raw.to_vec(),- "blr",+ "blr",x(rn),4,))@@ -90,7 +90,7 @@ fn decode_blr(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {fn decode_ret(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {let rn = bit(wd, 5, 9);let operands = if rn == 30 {- "lr".into()+ "lr".into()} else if rn == 31 {String::new()} else {@@ -99,7 +99,7 @@ fn decode_ret(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {Ok(Instruction::with_text(address,raw.to_vec(),- "ret",+ "ret",operands,4,))@@ -112,12 +112,12 @@ fn decode_cbz(wd: u32, address: u64, raw: &[u8], neg: bool) -> Result<Instructiolet offset = sign_extend((imm19 as u64) << 2, 21);let target = (address as i64).wrapping_add(offset) as u64;let reg = if sf != 0 { x(rt) } else { w(rt) };- let mnemonic = if neg { "cbnz" } else { "cbz" };+ let mnemonic = if neg { "cbnz" } else { "cbz" };Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- format!("{}, {}", reg, fmt_imm_hex(target as i64)),+ format!("{}, {}", reg, fmt_imm_hex(target as i64)),4,))}@@ -130,12 +130,12 @@ fn decode_tbz(wd: u32, address: u64, raw: &[u8], neg: bool) -> Result<Instructiolet bit_pos = b40 | (b5 << 5);let offset = sign_extend((imm14 as u64) << 2, 16);let target = (address as i64).wrapping_add(offset) as u64;- let mnemonic = if neg { "tbnz" } else { "tbz" };+ let mnemonic = if neg { "tbnz" } else { "tbz" };Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- format!("{}, #{bit_pos}, {}", w(rt), fmt_imm_hex(target as i64)),+ format!("{}, #{bit_pos}, {}", w(rt), fmt_imm_hex(target as i64)),4,))}diff --git a/crates/ghidrust-decode/src/arch/aarch64/data_proc.rs b/crates/ghidrust-decode/src/arch/aarch64/data_proc.rsindex 2193515..59c61d3 100644--- a/crates/ghidrust-decode/src/arch/aarch64/data_proc.rs+++ b/crates/ghidrust-decode/src/arch/aarch64/data_proc.rs@@ -31,26 +31,32 @@ fn decode_add_sub_imm(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction>let imm = (imm12 as u64) << shift;let reg_d = if sf != 0 { x(rd) } else { w(rd) };let reg_n = if rn == 31 {- "sp".into()+ "sp".into()} else if sf != 0 {x(rn)} else {w(rn)};let mnemonic = match (op, s, rn == 31) {- (0, 0, true) => "mov",- (0, 0, false) => "add",- (0, 1, _) => "adds",- (1, 0, _) => "sub",- (1, 1, _) => "subs",- _ => "add",+ (0, 0, true) => "mov",+ (0, 0, false) => "add",+ (0, 1, _) => "adds",+ (1, 0, _) => "sub",+ (1, 1, _) => "subs",+ _ => "add",};- let operands = if mnemonic == "mov" {- format!("{}, #{imm:#x}", reg_d)+ let operands = if mnemonic == "mov" {+ format!("{}, #{imm:#x}", reg_d)} else {- format!("{}, {}, #{imm:#x}", reg_d, reg_n)+ format!("{}, {}, #{imm:#x}", reg_d, reg_n)};- Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4))+ Ok(Instruction::with_text(+ address,+ raw.to_vec(),+ mnemonic,+ operands,+ 4,+ ))}fn decode_logical_imm(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {@@ -62,18 +68,24 @@ fn decode_logical_imm(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction>let reg_d = if sf != 0 { x(rd) } else { w(rd) };let reg_n = if sf != 0 { x(rn) } else { w(rn) };let mnemonic = match opc {- 0b00 => "and",- 0b01 => "orr",- 0b10 => "eor",- 0b11 => "ands",- _ => "and",+ 0b00 => "and",+ 0b01 => "orr",+ 0b10 => "eor",+ 0b11 => "ands",+ _ => "and",};let operands = if rn == 31 && opc == 0b01 {- format!("{}, #{imm:#x}", reg_d)+ format!("{}, #{imm:#x}", reg_d)} else {- format!("{}, {}, #{imm:#x}", reg_d, reg_n)+ format!("{}, {}, #{imm:#x}", reg_d, reg_n)};- Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4))+ Ok(Instruction::with_text(+ address,+ raw.to_vec(),+ mnemonic,+ operands,+ 4,+ ))}fn decode_logical_reg(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {@@ -88,23 +100,23 @@ fn decode_logical_reg(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction>let reg_n = if sf != 0 { x(rn) } else { w(rn) };let reg_m = if sf != 0 { x(rm) } else { w(rm) };let shift_kind = match shift {- 0b00 => "lsl",- 0b01 => "lsr",- 0b10 => "asr",- _ => "ror",+ 0b00 => "lsl",+ 0b01 => "lsr",+ 0b10 => "asr",+ _ => "ror",};let mnemonic = match opc {- 0b00 => "and",- 0b01 => "orr",- 0b10 => "eor",- 0b11 => "ands",- _ => "and",+ 0b00 => "and",+ 0b01 => "orr",+ 0b10 => "eor",+ 0b11 => "ands",+ _ => "and",};Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- format!("{}, {}, {}, {shift_kind} #{imm6}", reg_d, reg_n, reg_m),+ format!("{}, {}, {}, {shift_kind} #{imm6}", reg_d, reg_n, reg_m),4,))}@@ -117,19 +129,19 @@ fn decode_add_sub_reg(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction>let rd = bit(wd, 0, 4);let reg_d = if sf != 0 { x(rd) } else { w(rd) };let reg_n = if rn == 31 {- "sp".into()+ "sp".into()} else if sf != 0 {x(rn)} else {w(rn)};let reg_m = if sf != 0 { x(rm) } else { w(rm) };- let mnemonic = if op != 0 { "sub" } else { "add" };+ let mnemonic = if op != 0 { "sub" } else { "add" };Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- format!("{}, {}, {}", reg_d, reg_n, reg_m),+ format!("{}, {}, {}", reg_d, reg_n, reg_m),4,))}diff --git a/crates/ghidrust-decode/src/arch/aarch64/dispatch.rs b/crates/ghidrust-decode/src/arch/aarch64/dispatch.rsindex c0b080b..7ddfe08 100644--- a/crates/ghidrust-decode/src/arch/aarch64/dispatch.rs+++ b/crates/ghidrust-decode/src/arch/aarch64/dispatch.rs@@ -10,7 +10,7 @@ use crate::insn::Instruction;pub fn decode(bytes: &[u8], address: u64, big_endian: bool) -> Result<Instruction> {if bytes.len() < 4 {- return Err(Error::Decode("truncated AArch64 instruction".into()));+ return Err(Error::Decode("truncated AArch64 instruction".into()));}let wd = util::read_u32_le(bytes, big_endian)?;let raw = &bytes[..4];@@ -35,5 +35,7 @@ pub fn decode(bytes: &[u8], address: u64, big_endian: bool) -> Result<Instructioif let Some(r) = fp_asimd::try_decode(wd, address, raw) {return r;}- Err(Error::Decode(format!("unhandled AArch64 encoding {wd:#010x}")))+ Err(Error::Decode(format!(+ "unhandled AArch64 encoding {wd:#010x}"+ )))}diff --git a/crates/ghidrust-decode/src/arch/aarch64/fp_asimd.rs b/crates/ghidrust-decode/src/arch/aarch64/fp_asimd.rsindex a0888dc..a89f745 100644--- a/crates/ghidrust-decode/src/arch/aarch64/fp_asimd.rs+++ b/crates/ghidrust-decode/src/arch/aarch64/fp_asimd.rs@@ -28,16 +28,16 @@ fn decode_fadd(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {let rn = bit(wd, 5, 9);let rm = bit(wd, 16, 20);let sz = bit(wd, 22, 22);- let mnemonic = if sz != 0 { "fadd" } else { "fadd" };- let suffix = if sz != 0 { ".d" } else { ".s" };+ let mnemonic = if sz != 0 { "fadd" } else { "fadd" };+ let suffix = if sz != 0 { ".d" } else { ".s" };let reg = if sz != 0 { d(rd) } else { s(rd) };let reg_n = if sz != 0 { d(rn) } else { s(rn) };let reg_m = if sz != 0 { d(rm) } else { s(rm) };Ok(Instruction::with_text(address,raw.to_vec(),- format!("{mnemonic}{suffix}"),- format!("{}, {}, {}", reg, reg_n, reg_m),+ format!("{mnemonic}{suffix}"),+ format!("{}, {}, {}", reg, reg_n, reg_m),4,))}@@ -47,15 +47,15 @@ fn decode_fmul(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {let rn = bit(wd, 5, 9);let rm = bit(wd, 16, 20);let sz = bit(wd, 22, 22);- let suffix = if sz != 0 { ".d" } else { ".s" };+ let suffix = if sz != 0 { ".d" } else { ".s" };let reg = if sz != 0 { d(rd) } else { s(rd) };let reg_n = if sz != 0 { d(rn) } else { s(rn) };let reg_m = if sz != 0 { d(rm) } else { s(rm) };Ok(Instruction::with_text(address,raw.to_vec(),- format!("fmul{suffix}"),- format!("{}, {}, {}", reg, reg_n, reg_m),+ format!("fmul{suffix}"),+ format!("{}, {}, {}", reg, reg_n, reg_m),4,))}@@ -65,15 +65,15 @@ fn decode_fsub(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {let rn = bit(wd, 5, 9);let rm = bit(wd, 16, 20);let sz = bit(wd, 22, 22);- let suffix = if sz != 0 { ".d" } else { ".s" };+ let suffix = if sz != 0 { ".d" } else { ".s" };let reg = if sz != 0 { d(rd) } else { s(rd) };let reg_n = if sz != 0 { d(rn) } else { s(rn) };let reg_m = if sz != 0 { d(rm) } else { s(rm) };Ok(Instruction::with_text(address,raw.to_vec(),- format!("fsub{suffix}"),- format!("{}, {}, {}", reg, reg_n, reg_m),+ format!("fsub{suffix}"),+ format!("{}, {}, {}", reg, reg_n, reg_m),4,))}@@ -83,15 +83,15 @@ fn decode_fdiv(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {let rn = bit(wd, 5, 9);let rm = bit(wd, 16, 20);let sz = bit(wd, 22, 22);- let suffix = if sz != 0 { ".d" } else { ".s" };+ let suffix = if sz != 0 { ".d" } else { ".s" };let reg = if sz != 0 { d(rd) } else { s(rd) };let reg_n = if sz != 0 { d(rn) } else { s(rn) };let reg_m = if sz != 0 { d(rm) } else { s(rm) };Ok(Instruction::with_text(address,raw.to_vec(),- format!("fdiv{suffix}"),- format!("{}, {}, {}", reg, reg_n, reg_m),+ format!("fdiv{suffix}"),+ format!("{}, {}, {}", reg, reg_n, reg_m),4,))}@@ -105,8 +105,8 @@ fn decode_fmov(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {Ok(Instruction::with_text(address,raw.to_vec(),- if sz != 0 { "fmov.d" } else { "fmov.s" },- format!("{}, {}", reg, reg_n),+ if sz != 0 { "fmov.d" } else { "fmov.s" },+ format!("{}, {}", reg, reg_n),4,))}@@ -121,16 +121,21 @@ fn try_asimd(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {return None;}let mnemonic = match size {- 0b00 => "add.8b",- 0b01 => "add.16b",- 0b10 => "add.4h",- _ => "add.2s",+ 0b00 => "add.8b",+ 0b01 => "add.16b",+ 0b10 => "add.4h",+ _ => "add.2s",};Some(Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- format!("{}, {}, {}", v(rd | if q != 0 { 16 } else { 0 }), v(rn), v(rm)),+ format!(+ "{}, {}, {}",+ v(rd | if q != 0 { 16 } else { 0 }),+ v(rn),+ v(rm)+ ),4,)))}diff --git a/crates/ghidrust-decode/src/arch/aarch64/load_store.rs b/crates/ghidrust-decode/src/arch/aarch64/load_store.rsindex 2415b40..1abb977 100644--- a/crates/ghidrust-decode/src/arch/aarch64/load_store.rs+++ b/crates/ghidrust-decode/src/arch/aarch64/load_store.rs@@ -12,18 +12,18 @@ pub fn try_decode(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instructioif op1 != 0 {return try_load_store(wd, address, raw);}- // Load/store pair / exclusive use different routing+ // Load/store pair / exclusive use different routingtry_load_store(wd, address, raw)}fn try_load_store(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {let op0 = bit(wd, 22, 23);let _op2 = bit(wd, 10, 11);- // Load/store pair+ // Load/store pairif bit(wd, 26, 26) == 0 && bit(wd, 25, 25) == 1 && op0 == 0b10 {return Some(decode_pair(wd, address, raw));}- // Literal load: opc=01, V=0, at bits 29-31 = 0b011+ // Literal load: opc=01, V=0, at bits 29-31 = 0b011if bit(wd, 24, 28) == 0b01100 && bit(wd, 26, 26) == 0 {return Some(decode_literal(wd, address, raw));}@@ -40,8 +40,8 @@ fn decode_literal(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {Ok(Instruction::with_text(address,raw.to_vec(),- "ldr",- format!("{}, #{target:#x}", reg),+ "ldr",+ format!("{}, #{target:#x}", reg),4,))}@@ -54,27 +54,29 @@ fn decode_reg_offset(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {let imm12 = bit(wd, 10, 21);let is_load = opc == 0b01 || (opc == 0b00 && size == 0b11);let (mnemonic, reg) = match (size, opc, is_load) {- (0b00, 0b00, true) => ("ldrb", w(rt)),- (0b00, 0b00, false) => ("strb", w(rt)),- (0b01, 0b00, true) => ("ldrh", w(rt)),- (0b01, 0b00, false) => ("strh", w(rt)),- (0b10, _, true) => ("ldr", w(rt)),- (0b10, _, false) => ("str", w(rt)),- (0b11, 0b00, true) => ("ldr", x(rt)),- (0b11, 0b00, false) => ("str", x(rt)),- (0b11, 0b01, true) => ("ldrsw", x(rt)),- _ => if is_load {- ("ldr", if size == 0b11 { x(rt) } else { w(rt) })- } else {- ("str", if size == 0b11 { x(rt) } else { w(rt) })- },+ (0b00, 0b00, true) => ("ldrb", w(rt)),+ (0b00, 0b00, false) => ("strb", w(rt)),+ (0b01, 0b00, true) => ("ldrh", w(rt)),+ (0b01, 0b00, false) => ("strh", w(rt)),+ (0b10, _, true) => ("ldr", w(rt)),+ (0b10, _, false) => ("str", w(rt)),+ (0b11, 0b00, true) => ("ldr", x(rt)),+ (0b11, 0b00, false) => ("str", x(rt)),+ (0b11, 0b01, true) => ("ldrsw", x(rt)),+ _ => {+ if is_load {+ ("ldr", if size == 0b11 { x(rt) } else { w(rt) })+ } else {+ ("str", if size == 0b11 { x(rt) } else { w(rt) })+ }+ }};- let base = if rn == 31 { "sp" } else { &x(rn) };+ let base = if rn == 31 { "sp" } else { &x(rn) };Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- format!("{}, [{}, #{imm12}]", reg, base),+ format!("{}, [{}, #{imm12}]", reg, base),4,))}@@ -87,15 +89,15 @@ fn decode_pair(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {let rt = bit(wd, 0, 4);let rt2 = bit(wd, 10, 14);let offset = (imm7 as i64) << opc;- let mnemonic = if l != 0 { "ldp" } else { "stp" };+ let mnemonic = if l != 0 { "ldp" } else { "stp" };let reg1 = if opc == 0b10 { w(rt) } else { x(rt) };let reg2 = if opc == 0b10 { w(rt2) } else { x(rt2) };- let base = if rn == 31 { "sp".into() } else { x(rn) };+ let base = if rn == 31 { "sp".into() } else { x(rn) };Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- format!("{}, {}, [{}, #{offset}]", reg1, reg2, base),+ format!("{}, {}, [{}, #{offset}]", reg1, reg2, base),4,))}diff --git a/crates/ghidrust-decode/src/arch/aarch64/mod.rs b/crates/ghidrust-decode/src/arch/aarch64/mod.rsindex f3f766e..e87b234 100644--- a/crates/ghidrust-decode/src/arch/aarch64/mod.rs+++ b/crates/ghidrust-decode/src/arch/aarch64/mod.rs@@ -29,7 +29,7 @@ impl ArchDecode for Aarch64Decoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Arm64) {return Err(Error::Mode(format!(- "invalid AArch64 mode {:#x}",+ "invalid AArch64 mode {:#x}",mode.bits())));}@@ -54,14 +54,14 @@ impl ArchDecode for Aarch64Decoder {}fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {- let m = mnemonic.split('.').next().unwrap_or(mnemonic);- if m == "b" || m.starts_with("b.") || m == "cbz" || m == "cbnz" || m == "tbz" || m == "tbnz" {+ let m = mnemonic.split('.').next().unwrap_or(mnemonic);+ if m == "b" || m.starts_with("b.") || m == "cbz" || m == "cbnz" || m == "tbz" || m == "tbnz" {vec![GroupId::Jump, GroupId::BranchRelative]- } else if m == "bl" || m == "blr" {+ } else if m == "bl" || m == "blr" {vec![GroupId::Call, GroupId::BranchRelative]- } else if m == "ret" || m == "br" {+ } else if m == "ret" || m == "br" {vec![GroupId::Ret]- } else if m == "svc" || m == "brk" {+ } else if m == "svc" || m == "brk" {vec![GroupId::Int]} else {Vec::new()@@ -70,7 +70,7 @@ fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {pub fn reg_name(reg: RegId) -> Option<&'static str> {match reg.index() {- 31 => Some("xzr"),+ 31 => Some("xzr"),n if n < 31 => None,_ => None,}@@ -78,42 +78,42 @@ pub fn reg_name(reg: RegId) -> Option<&'static str> {pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("mov"),- 2 => Some("add"),- 3 => Some("ldr"),- 4 => Some("str"),- 5 => Some("b"),- 6 => Some("bl"),- 7 => Some("ret"),- 8 => Some("nop"),- 9 => Some("svc"),+ 1 => Some("mov"),+ 2 => Some("add"),+ 3 => Some("ldr"),+ 4 => Some("str"),+ 5 => Some("b"),+ 6 => Some("bl"),+ 7 => Some("ret"),+ 8 => Some("nop"),+ 9 => Some("svc"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Ret => Some("ret"),- GroupId::Int => Some("int"),- GroupId::BranchRelative => Some("branch_relative"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Ret => Some("ret"),+ GroupId::Int => Some("int"),+ GroupId::BranchRelative => Some("branch_relative"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {- let m = mnemonic.split('.').next().unwrap_or(mnemonic);+ let m = mnemonic.split('.').next().unwrap_or(mnemonic);let id = match m {- "mov" | "movz" | "movk" | "movn" => 1,- "add" | "sub" | "adds" | "subs" => 2,- s if s.starts_with("ldr") => 3,- s if s.starts_with("str") || s.starts_with("stp") => 4,- "b" | "cbz" | "cbnz" => 5,- "bl" | "blr" => 6,- "ret" | "br" => 7,- "nop" => 8,- "svc" | "brk" => 9,+ "mov" | "movz" | "movk" | "movn" => 1,+ "add" | "sub" | "adds" | "subs" => 2,+ s if s.starts_with("ldr") => 3,+ s if s.starts_with("str") || s.starts_with("stp") => 4,+ "b" | "cbz" | "cbnz" => 5,+ "bl" | "blr" => 6,+ "ret" | "br" => 7,+ "nop" => 8,+ "svc" | "brk" => 9,_ => 0,};InsnId(id)@@ -127,30 +127,30 @@ mod tests {#[test]fn aarch64_mov_add_ret() {let mut eng = Engine::open(Arch::Arm64, Mode::LITTLE_ENDIAN).unwrap();- // movz x0, #0x1234 -> d2802468+ // movz x0, #0x1234 -> d2802468let mov = eng.disasm_one(&[0x68, 0x24, 0x80, 0xd2], 0x1000).unwrap();- assert_eq!(mov.mnemonic, "movz");- // add x1, x0, x2 -> 8b020001+ assert_eq!(mov.mnemonic, "movz");+ // add x1, x0, x2 -> 8b020001let add = eng.disasm_one(&[0x01, 0x00, 0x02, 0x8b], 0x1004).unwrap();- assert_eq!(add.mnemonic, "add");- // ret -> d65f03c0+ assert_eq!(add.mnemonic, "add");+ // ret -> d65f03c0let ret = eng.disasm_one(&[0xc0, 0x03, 0x5f, 0xd6], 0x1008).unwrap();- assert_eq!(ret.mnemonic, "ret");+ assert_eq!(ret.mnemonic, "ret");}#[test]fn aarch64_nop_svc() {let mut eng = Engine::open(Arch::Arm64, Mode::LITTLE_ENDIAN).unwrap();let nop = eng.disasm_one(&[0x1f, 0x20, 0x03, 0xd5], 0x0).unwrap();- assert_eq!(nop.mnemonic, "nop");+ assert_eq!(nop.mnemonic, "nop");}#[test]fn aarch64_bl_b() {let mut eng = Engine::open(Arch::Arm64, Mode::LITTLE_ENDIAN).unwrap();let b = eng.disasm_one(&[0x00, 0x00, 0x00, 0x14], 0x0).unwrap();- assert_eq!(b.mnemonic, "b");+ assert_eq!(b.mnemonic, "b");let bl = eng.disasm_one(&[0x00, 0x00, 0x00, 0x94], 0x0).unwrap();- assert_eq!(bl.mnemonic, "bl");+ assert_eq!(bl.mnemonic, "bl");}}diff --git a/crates/ghidrust-decode/src/arch/aarch64/move_wide.rs b/crates/ghidrust-decode/src/arch/aarch64/move_wide.rsindex 1e2fec8..e534859 100644--- a/crates/ghidrust-decode/src/arch/aarch64/move_wide.rs+++ b/crates/ghidrust-decode/src/arch/aarch64/move_wide.rs@@ -27,8 +27,8 @@ fn decode_movz(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {Ok(Instruction::with_text(address,raw.to_vec(),- "movz",- format!("{}, #{imm:#x}", reg),+ "movz",+ format!("{}, #{imm:#x}", reg),4,))}@@ -44,8 +44,8 @@ fn decode_movk(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {Ok(Instruction::with_text(address,raw.to_vec(),- "movk",- format!("{}, #{imm:#x}", reg),+ "movk",+ format!("{}, #{imm:#x}", reg),4,))}@@ -61,8 +61,8 @@ fn decode_movn(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {Ok(Instruction::with_text(address,raw.to_vec(),- "movn",- format!("{}, #{imm:#x}", reg),+ "movn",+ format!("{}, #{imm:#x}", reg),4,))}@@ -76,12 +76,12 @@ pub fn try_decode_adr(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instrulet imm = sign_extend_pc((immhi as u64) << 2 | immlo as u64, 21);let target = (address as i64).wrapping_add(imm) as u64;let reg = if bit(wd, 31, 31) != 0 { x(rd) } else { w(rd) };- let m = if op != 0 { "adrp" } else { "adr" };+ let m = if op != 0 { "adrp" } else { "adr" };return Some(Ok(Instruction::with_text(address,raw.to_vec(),m,- format!("{}, #{target:#x}", reg),+ format!("{}, #{target:#x}", reg),4,)));}diff --git a/crates/ghidrust-decode/src/arch/aarch64/regs.rs b/crates/ghidrust-decode/src/arch/aarch64/regs.rsindex 107a6a2..83d8b35 100644--- a/crates/ghidrust-decode/src/arch/aarch64/regs.rs+++ b/crates/ghidrust-decode/src/arch/aarch64/regs.rs@@ -3,42 +3,42 @@ use crate::support::Arch;pub fn x(n: u32) -> String {if n == 31 {- "xzr".into()+ "xzr".into()} else {- format!("x{n}")+ format!("x{n}")}}pub fn w(n: u32) -> String {if n == 31 {- "wzr".into()+ "wzr".into()} else {- format!("w{n}")+ format!("w{n}")}}pub fn sp() -> &'static str {- "sp"+ "sp"}pub fn b(n: u32) -> String {- format!("b{n}")+ format!("b{n}")}pub fn h(n: u32) -> String {- format!("h{n}")+ format!("h{n}")}pub fn s(n: u32) -> String {- format!("s{n}")+ format!("s{n}")}pub fn d(n: u32) -> String {- format!("d{n}")+ format!("d{n}")}pub fn v(n: u32) -> String {- format!("v{n}")+ format!("v{n}")}pub fn reg_id(n: u32) -> RegId {diff --git a/crates/ghidrust-decode/src/arch/aarch64/system.rs b/crates/ghidrust-decode/src/arch/aarch64/system.rsindex 761fb6e..f7bcf2f 100644--- a/crates/ghidrust-decode/src/arch/aarch64/system.rs+++ b/crates/ghidrust-decode/src/arch/aarch64/system.rs@@ -7,8 +7,8 @@ pub fn try_decode(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instructioreturn Some(Ok(Instruction::with_text(address,raw.to_vec(),- "nop",- "",+ "nop",+ "",4,)));}@@ -17,8 +17,8 @@ pub fn try_decode(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instructioreturn Some(Ok(Instruction::with_text(address,raw.to_vec(),- "svc",- format!("#{imm}"),+ "svc",+ format!("#{imm}"),4,)));}@@ -27,8 +27,8 @@ pub fn try_decode(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instructioreturn Some(Ok(Instruction::with_text(address,raw.to_vec(),- "brk",- format!("#{imm}"),+ "brk",+ format!("#{imm}"),4,)));}@@ -36,8 +36,8 @@ pub fn try_decode(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instructioreturn Some(Ok(Instruction::with_text(address,raw.to_vec(),- "yield",- "",+ "yield",+ "",4,)));}diff --git a/crates/ghidrust-decode/src/arch/aarch64/util.rs b/crates/ghidrust-decode/src/arch/aarch64/util.rsindex 3ae7f6e..e0adedb 100644--- a/crates/ghidrust-decode/src/arch/aarch64/util.rs+++ b/crates/ghidrust-decode/src/arch/aarch64/util.rs@@ -2,7 +2,7 @@ use crate::error::{Error, Result};pub fn read_u32_le(bytes: &[u8], big_endian: bool) -> Result<u32> {if bytes.len() < 4 {- return Err(Error::Decode("truncated AArch64 word".into()));+ return Err(Error::Decode("truncated AArch64 word".into()));}Ok(if big_endian {u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])@@ -18,9 +18,9 @@ pub fn sign_extend(value: u64, bits: u32) -> i64 {pub fn fmt_imm_hex(v: i64) -> String {if v < 0 {- format!("-{:#x}", -v)+ format!("-{:#x}", -v)} else {- format!("{v:#x}")+ format!("{v:#x}")}}@@ -39,21 +39,21 @@ pub fn decode_imm_logical(w: u32) -> u32 {pub fn cond_name(cond: u32) -> &'static str {match cond {- 0x0 => "eq",- 0x1 => "ne",- 0x2 => "cs",- 0x3 => "cc",- 0x4 => "mi",- 0x5 => "pl",- 0x6 => "vs",- 0x7 => "vc",- 0x8 => "hi",- 0x9 => "ls",- 0xa => "ge",- 0xb => "lt",- 0xc => "gt",- 0xd => "le",- 0xe => "al",- _ => "nv",+ 0x0 => "eq",+ 0x1 => "ne",+ 0x2 => "cs",+ 0x3 => "cc",+ 0x4 => "mi",+ 0x5 => "pl",+ 0x6 => "vs",+ 0x7 => "vc",+ 0x8 => "hi",+ 0x9 => "ls",+ 0xa => "ge",+ 0xb => "lt",+ 0xc => "gt",+ 0xd => "le",+ 0xe => "al",+ _ => "nv",}}diff --git a/crates/ghidrust-decode/src/arch/alpha/decode.rs b/crates/ghidrust-decode/src/arch/alpha/decode.rsindex b5b87fc..a845eec 100644--- a/crates/ghidrust-decode/src/arch/alpha/decode.rs+++ b/crates/ghidrust-decode/src/arch/alpha/decode.rs@@ -1,23 +1,23 @@use crate::error::{Error, Result};pub fn r(n: u32) -> String {- format!("r{n}")+ format!("r{n}")}pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("r0"),- 1 => Some("r1"),- 26 => Some("ra"),- 27 => Some("at"),- 31 => Some("zero"),+ 0 => Some("r0"),+ 1 => Some("r1"),+ 26 => Some("ra"),+ 27 => Some("at"),+ 31 => Some("zero"),_ => None,}}pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usize)> {if bytes.len() < 4 {- return Err(Error::Decode("truncated alpha instruction".into()));+ return Err(Error::Decode("truncated alpha instruction".into()));}let word = if little_endian {u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])@@ -26,21 +26,21 @@ pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usiz};let opcode = word >> 26;match opcode {- 0x08 => decode_mem(word, "lda"),- 0x28 => decode_mem(word, "ldl"),- 0x29 => decode_mem(word, "ldq"),- 0x2c => decode_mem(word, "stl"),- 0x2d => decode_mem(word, "stq"),- 0x10 => decode_operate(word, "addl"),- 0x11 => decode_operate(word, "subl"),+ 0x08 => decode_mem(word, "lda"),+ 0x28 => decode_mem(word, "ldl"),+ 0x29 => decode_mem(word, "ldq"),+ 0x2c => decode_mem(word, "stl"),+ 0x2d => decode_mem(word, "stq"),+ 0x10 => decode_operate(word, "addl"),+ 0x11 => decode_operate(word, "subl"),0x1a => {let ra = (word >> 21) & 0x1f;- let name = if ra == 0 { "jmp" } else { "jsr" };+ let name = if ra == 0 { "jmp" } else { "jsr" };Ok((name.into(), decode_mem_ops(word), 4))}- 0x1b => Ok(("ret".into(), String::new(), 4)),+ 0x1b => Ok(("ret".into(), String::new(), 4)),0x30..=0x3f => decode_branch(word, opcode),- _ => Err(Error::Decode("unsupported alpha opcode".into())),+ _ => Err(Error::Decode("unsupported alpha opcode".into())),}}@@ -52,35 +52,31 @@ fn decode_mem_ops(word: u32) -> String {let ra = (word >> 21) & 0x1f;let rb = (word >> 16) & 0x1f;let disp = sign_ext((word >> 0) & 0xffff, 16);- format!("{}, {disp}({})", r(ra), r(rb))+ format!("{}, {disp}({})", r(ra), r(rb))}fn decode_operate(word: u32, name: &str) -> Result<(String, String, usize)> {let ra = (word >> 21) & 0x1f;let rb = (word >> 16) & 0x1f;let rc = (word >> 0) & 0x1f;- Ok((- name.into(),- format!("{}, {}, {}", r(ra), r(rb), r(rc)),- 4,- ))+ Ok((name.into(), format!("{}, {}, {}", r(ra), r(rb), r(rc)), 4))}fn decode_branch(word: u32, opcode: u32) -> Result<(String, String, usize)> {let name = match opcode {- 0x30 => "br",- 0x31 => "blbc",- 0x32 => "beq",- 0x33 => "blt",- 0x34 => "bsr",- 0x35 => "blbs",- 0x36 => "bne",- 0x37 => "bge",- 0x38 => "bgt",- 0x39 => "bgeu",- 0x3a => "bvc",- 0x3b => "bvs",- _ => "br",+ 0x30 => "br",+ 0x31 => "blbc",+ 0x32 => "beq",+ 0x33 => "blt",+ 0x34 => "bsr",+ 0x35 => "blbs",+ 0x36 => "bne",+ 0x37 => "bge",+ 0x38 => "bgt",+ 0x39 => "bgeu",+ 0x3a => "bvc",+ 0x3b => "bvs",+ _ => "br",};Ok((name.into(), decode_branch_target(word), 4))}@@ -88,7 +84,7 @@ fn decode_branch(word: u32, opcode: u32) -> Result<(String, String, usize)> {fn decode_branch_target(word: u32) -> String {let ra = (word >> 21) & 0x1f;let disp = sign_ext((word >> 0) & 0x1fffff, 21);- format!("{}, {disp}", r(ra))+ format!("{}, {disp}", r(ra))}fn sign_ext(val: u32, bits: u32) -> i64 {@@ -104,8 +100,8 @@ mod tests {fn alpha_lda() {let word = (0x08u32 << 26) | (1 << 21) | (2 << 16) | 8;let (m, o, l) = decode(&word.to_le_bytes(), true).unwrap();- assert_eq!(m, "lda");+ assert_eq!(m, "lda");assert_eq!(l, 4);- assert!(o.contains("r1"));+ assert!(o.contains("r1"));}}diff --git a/crates/ghidrust-decode/src/arch/alpha/mod.rs b/crates/ghidrust-decode/src/arch/alpha/mod.rsindex 1003e36..fd16a0c 100644--- a/crates/ghidrust-decode/src/arch/alpha/mod.rs+++ b/crates/ghidrust-decode/src/arch/alpha/mod.rs@@ -21,7 +21,10 @@ impl ArchDecode for AlphaDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Alpha) {- return Err(Error::Mode(format!("invalid alpha mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!(+ "invalid alpha mode {:#x}",+ mode.bits()+ )));}let little_endian = !mode.contains(Mode::BIG_ENDIAN);Ok(Self { little_endian })@@ -49,48 +52,48 @@ impl ArchDecode for AlphaDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "bsr" | "jsr" => vec![GroupId::Call],- "jmp" | "br" | "beq" | "bne" => vec![GroupId::Jump],- "ret" => vec![GroupId::Ret],- m if m.starts_with("ld") => vec![GroupId::Arch(1)],- m if m.starts_with("st") => vec![GroupId::Arch(2)],- m if m.ends_with("l") => vec![GroupId::Arch(3)],+ "bsr" | "jsr" => vec![GroupId::Call],+ "jmp" | "br" | "beq" | "bne" => vec![GroupId::Jump],+ "ret" => vec![GroupId::Ret],+ m if m.starts_with("ld") => vec![GroupId::Arch(1)],+ m if m.starts_with("st") => vec![GroupId::Arch(2)],+ m if m.ends_with("l") => vec![GroupId::Arch(3)],_ => Vec::new(),}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("lda"),- 2 => Some("ldl"),- 3 => Some("addl"),- 4 => Some("bsr"),- 5 => Some("ret"),+ 1 => Some("lda"),+ 2 => Some("ldl"),+ 3 => Some("addl"),+ 4 => Some("bsr"),+ 5 => Some("ret"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Ret => Some("ret"),- GroupId::Arch(1) => Some("load"),- GroupId::Arch(2) => Some("store"),- GroupId::Arch(3) => Some("alu"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Ret => Some("ret"),+ GroupId::Arch(1) => Some("load"),+ GroupId::Arch(2) => Some("store"),+ GroupId::Arch(3) => Some("alu"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "lda" => 1,- "ldl" | "ldq" => 2,- "addl" | "subl" => 3,- "bsr" | "jsr" | "jmp" => 4,- "ret" => 5,- m if m.starts_with("st") => 2,- m if m.starts_with('b') => 4,+ "lda" => 1,+ "ldl" | "ldq" => 2,+ "addl" | "subl" => 3,+ "bsr" | "jsr" | "jmp" => 4,+ "ret" => 5,+ m if m.starts_with("st") => 2,+ m if m.starts_with('b') => 4,_ => 0,};InsnId(id)@@ -104,26 +107,26 @@ mod tests {#[test]fn alpha_lda_and_addl() {let mut eng = Engine::open(Arch::Alpha, Mode::LITTLE_ENDIAN).unwrap();- // lda r1, 8(r2)+ // lda r1, 8(r2)let word = (0x08u32 << 26) | (1 << 21) | (2 << 16) | 8;let lda = eng.disasm_one(&word.to_le_bytes(), 0).unwrap();- assert_eq!(lda.mnemonic, "lda");- // addl r3, r1, r2+ assert_eq!(lda.mnemonic, "lda");+ // addl r3, r1, r2let add = (0x10u32 << 26) | (3 << 21) | (1 << 16) | 2;let addl = eng.disasm_one(&add.to_le_bytes(), 0).unwrap();- assert_eq!(addl.mnemonic, "addl");+ assert_eq!(addl.mnemonic, "addl");}#[test]fn alpha_branch_and_ret() {let mut eng = Engine::open(Arch::Alpha, Mode::LITTLE_ENDIAN).unwrap();- // beq r1, 4+ // beq r1, 4let beq = (0x32u32 << 26) | (1 << 21) | 4;let insn = eng.disasm_one(&beq.to_le_bytes(), 0).unwrap();- assert_eq!(insn.mnemonic, "beq");- // ret opcode 0x1b << 26+ assert_eq!(insn.mnemonic, "beq");+ // ret opcode 0x1b << 26let ret = 0x1bu32 << 26;let r = eng.disasm_one(&ret.to_le_bytes(), 0).unwrap();- assert_eq!(r.mnemonic, "ret");+ assert_eq!(r.mnemonic, "ret");}}diff --git a/crates/ghidrust-decode/src/arch/arc/decode.rs b/crates/ghidrust-decode/src/arch/arc/decode.rsindex a57d699..e31995c 100644--- a/crates/ghidrust-decode/src/arch/arc/decode.rs+++ b/crates/ghidrust-decode/src/arch/arc/decode.rs@@ -2,21 +2,21 @@ use crate::error::{Error, Result};pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("r0"),- 1 => Some("r1"),- 15 => Some("sp"),- 31 => Some("blink"),+ 0 => Some("r0"),+ 1 => Some("r1"),+ 15 => Some("sp"),+ 31 => Some("blink"),_ => None,}}fn r(n: u32) -> String {- format!("r{n}")+ format!("r{n}")}pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usize)> {if bytes.len() < 4 {- return Err(Error::Decode("truncated arc instruction".into()));+ return Err(Error::Decode("truncated arc instruction".into()));}let word = if little_endian {u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])@@ -28,15 +28,15 @@ pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usiz0x00 => {let dst = (word >> 16) & 0x1f;let src = (word >> 0) & 0x1f;- Ok(("mov".into(), format!("{}, {}", r(dst), r(src)), 4))+ Ok(("mov".into(), format!("{}, {}", r(dst), r(src)), 4))}0x01 => {let dst = (word >> 16) & 0x1f;let src1 = (word >> 8) & 0x1f;let src2 = (word >> 0) & 0x1f;Ok((- "add".into(),- format!("{}, {}, {}", r(dst), r(src1), r(src2)),+ "add".into(),+ format!("{}, {}, {}", r(dst), r(src1), r(src2)),4,))}@@ -45,8 +45,8 @@ pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usizlet src1 = (word >> 8) & 0x1f;let src2 = (word >> 0) & 0x1f;Ok((- "sub".into(),- format!("{}, {}, {}", r(dst), r(src1), r(src2)),+ "sub".into(),+ format!("{}, {}, {}", r(dst), r(src1), r(src2)),4,))}@@ -54,36 +54,28 @@ pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usizlet dst = (word >> 16) & 0x1f;let base = (word >> 8) & 0x1f;let off = (word >> 0) & 0xff;- Ok((- "ld".into(),- format!("{}, [{off}({})]", r(dst), r(base)),- 4,- ))+ Ok(("ld".into(), format!("{}, [{off}({})]", r(dst), r(base)), 4))}0x09 => {let src = (word >> 16) & 0x1f;let base = (word >> 8) & 0x1f;let off = (word >> 0) & 0xff;- Ok((- "st".into(),- format!("{}, [{off}({})]", r(src), r(base)),- 4,- ))+ Ok(("st".into(), format!("{}, [{off}({})]", r(src), r(base)), 4))}0x10 => {let disp = sign_ext((word >> 0) & 0x7ffffff, 27);- Ok(("j".into(), format!("{disp}"), 4))+ Ok(("j".into(), format!("{disp}"), 4))}0x11 => {let disp = sign_ext((word >> 0) & 0x7ffffff, 27);- Ok(("jl".into(), format!("{disp}"), 4))+ Ok(("jl".into(), format!("{disp}"), 4))}0x12 => {let cond = (word >> 16) & 0x1f;let disp = sign_ext((word >> 0) & 0xffff, 16);- Ok(("br".into(), format!("{cond}, {disp}"), 4))+ Ok(("br".into(), format!("{cond}, {disp}"), 4))}- _ => Err(Error::Decode("unsupported arc opcode".into())),+ _ => Err(Error::Decode("unsupported arc opcode".into())),}}@@ -100,8 +92,8 @@ mod tests {fn arc_mov() {let word = (0x00u32 << 27) | (1 << 16) | 0;let (m, o, l) = decode(&word.to_le_bytes(), true).unwrap();- assert_eq!(m, "mov");+ assert_eq!(m, "mov");assert_eq!(l, 4);- assert!(o.contains("r1"));+ assert!(o.contains("r1"));}}diff --git a/crates/ghidrust-decode/src/arch/arc/mod.rs b/crates/ghidrust-decode/src/arch/arc/mod.rsindex 48b71ae..2e689fa 100644--- a/crates/ghidrust-decode/src/arch/arc/mod.rs+++ b/crates/ghidrust-decode/src/arch/arc/mod.rs@@ -21,7 +21,7 @@ impl ArchDecode for ArcDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Arc) {- return Err(Error::Mode(format!("invalid arc mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!("invalid arc mode {:#x}", mode.bits())));}let little_endian = !mode.contains(Mode::BIG_ENDIAN);Ok(Self { little_endian })@@ -49,45 +49,45 @@ impl ArchDecode for ArcDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "jl" => vec![GroupId::Call],- "j" | "br" => vec![GroupId::Jump],- "ld" => vec![GroupId::Arch(1)],- "st" => vec![GroupId::Arch(2)],- "add" | "sub" | "mov" => vec![GroupId::Arch(3)],+ "jl" => vec![GroupId::Call],+ "j" | "br" => vec![GroupId::Jump],+ "ld" => vec![GroupId::Arch(1)],+ "st" => vec![GroupId::Arch(2)],+ "add" | "sub" | "mov" => vec![GroupId::Arch(3)],_ => Vec::new(),}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("mov"),- 2 => Some("add"),- 3 => Some("ld"),- 4 => Some("j"),- 5 => Some("br"),+ 1 => Some("mov"),+ 2 => Some("add"),+ 3 => Some("ld"),+ 4 => Some("j"),+ 5 => Some("br"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Arch(1) => Some("load"),- GroupId::Arch(2) => Some("store"),- GroupId::Arch(3) => Some("alu"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Arch(1) => Some("load"),+ GroupId::Arch(2) => Some("store"),+ GroupId::Arch(3) => Some("alu"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "mov" => 1,- "add" | "sub" => 2,- "ld" => 3,- "j" => 4,- "jl" | "br" => 5,- "st" => 3,+ "mov" => 1,+ "add" | "sub" => 2,+ "ld" => 3,+ "j" => 4,+ "jl" | "br" => 5,+ "st" => 3,_ => 0,};InsnId(id)@@ -103,10 +103,10 @@ mod tests {let mut eng = Engine::open(Arch::Arc, Mode::MODE_32).unwrap();let mov = (0x00u32 << 27) | (1 << 16) | 0;let m = eng.disasm_one(&mov.to_le_bytes(), 0).unwrap();- assert_eq!(m.mnemonic, "mov");+ assert_eq!(m.mnemonic, "mov");let add = (0x01u32 << 27) | (2 << 16) | (1 << 8) | 0;let a = eng.disasm_one(&add.to_le_bytes(), 0).unwrap();- assert_eq!(a.mnemonic, "add");+ assert_eq!(a.mnemonic, "add");}#[test]@@ -114,9 +114,9 @@ mod tests {let mut eng = Engine::open(Arch::Arc, Mode::MODE_32).unwrap();let ld = (0x08u32 << 27) | (4 << 16) | (1 << 8) | 8;let l = eng.disasm_one(&ld.to_le_bytes(), 0).unwrap();- assert_eq!(l.mnemonic, "ld");+ assert_eq!(l.mnemonic, "ld");let j = (0x10u32 << 27) | 16;let jmp = eng.disasm_one(&j.to_le_bytes(), 0).unwrap();- assert_eq!(jmp.mnemonic, "j");+ assert_eq!(jmp.mnemonic, "j");}}diff --git a/crates/ghidrust-decode/src/arch/arm/a32_branch.rs b/crates/ghidrust-decode/src/arch/arm/a32_branch.rsindex 315f441..88a92f1 100644--- a/crates/ghidrust-decode/src/arch/arm/a32_branch.rs+++ b/crates/ghidrust-decode/src/arch/arm/a32_branch.rs@@ -17,31 +17,37 @@ fn decode_branch(word: u32, cond: u32, address: u64, raw: &[u8]) -> Result<Instrlet (mnemonic, operands) = if link != 0 {(if suffix.is_empty() {- "bl".to_string()+ "bl".to_string()} else {- format!("bl{suffix}")+ format!("bl{suffix}")},fmt_imm_hex(target as i64),)} else {(if suffix.is_empty() {- "b".to_string()+ "b".to_string()} else {- format!("b{suffix}")+ format!("b{suffix}")},fmt_imm_hex(target as i64),)};- Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4))+ Ok(Instruction::with_text(+ address,+ raw.to_vec(),+ mnemonic,+ operands,+ 4,+ ))}pub fn try_decode_bx(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {- // BX / BLX register: cond 0001 0010 1111 1111 1111 0000 Rm+ // BX / BLX register: cond 0001 0010 1111 1111 1111 0000 Rmif (word & 0x0ff0_00f0) == 0x0120_00f0 {let rm = word & 0xf;let link = (word >> 21) & 1;- let mnemonic = if link != 0 { "blx" } else { "bx" };+ let mnemonic = if link != 0 { "blx" } else { "bx" };return Some(Ok(Instruction::with_text(address,raw.to_vec(),diff --git a/crates/ghidrust-decode/src/arch/arm/a32_data.rs b/crates/ghidrust-decode/src/arch/arm/a32_data.rsindex c77f134..1fc6898 100644--- a/crates/ghidrust-decode/src/arch/arm/a32_data.rs+++ b/crates/ghidrust-decode/src/arch/arm/a32_data.rs@@ -28,19 +28,25 @@ fn decode_dp_imm(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {let mnemonic = if suffix.is_empty() {base.to_string()} else {- format!("{base}{suffix}")+ format!("{base}{suffix}")};let operands = if is_dp_compare(opcode) {- format!("{}, {}, #{:#x}", gpr(rn), gpr(rd), imm)+ format!("{}, {}, #{:#x}", gpr(rn), gpr(rd), imm)} else if opcode == 0b1101 && rn == 0xf {- // mov- format!("{}, #{:#x}", gpr(rd), imm)+ // mov+ format!("{}, #{:#x}", gpr(rd), imm)} else if opcode == 0b1111 && rn == 0xf {- format!("{}, #{:#x}", gpr(rd), imm)+ format!("{}, #{:#x}", gpr(rd), imm)} else {- format!("{}, {}, #{:#x}", gpr(rd), gpr(rn), imm)+ format!("{}, {}, #{:#x}", gpr(rd), gpr(rn), imm)};- Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4))+ Ok(Instruction::with_text(+ address,+ raw.to_vec(),+ mnemonic,+ operands,+ 4,+ ))}fn decode_dp_reg(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {@@ -58,19 +64,25 @@ fn decode_dp_reg(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {let mnemonic = if suffix.is_empty() {base.to_string()} else {- format!("{base}{suffix}")+ format!("{base}{suffix}")};let shift_str = fmt_shift_reg(shift_type, shift_imm);let operands = if is_dp_compare(opcode) {- format!("{}, {}{}", gpr(rn), gpr(rs), shift_str)+ format!("{}, {}{}", gpr(rn), gpr(rs), shift_str)} else if opcode == 0b1101 && rn == 0xf {- format!("{}, {}{}", gpr(rd), gpr(rs), shift_str)+ format!("{}, {}{}", gpr(rd), gpr(rs), shift_str)} else if opcode == 0b1111 && rn == 0xf {- format!("{}, {}{}", gpr(rd), gpr(rs), shift_str)+ format!("{}, {}{}", gpr(rd), gpr(rs), shift_str)} else {- format!("{}, {}, {}{}", gpr(rd), gpr(rn), gpr(rs), shift_str)+ format!("{}, {}, {}{}", gpr(rd), gpr(rn), gpr(rs), shift_str)};- Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4))+ Ok(Instruction::with_text(+ address,+ raw.to_vec(),+ mnemonic,+ operands,+ 4,+ ))}fn decode_multiply(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {@@ -83,40 +95,43 @@ fn decode_multiply(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {let suffix = cond_suffix(cond);let (base, operands) = if a {(- "mla",- format!("{}, {}, {}, {}", gpr(rd), gpr(rm), gpr(rs), gpr(rn)),+ "mla",+ format!("{}, {}, {}, {}", gpr(rd), gpr(rm), gpr(rs), gpr(rn)),)} else {- (- "mul",- format!("{}, {}, {}", gpr(rd), gpr(rm), gpr(rs)),- )+ ("mul", format!("{}, {}, {}", gpr(rd), gpr(rm), gpr(rs)))};let mnemonic = if suffix.is_empty() {base.to_string()} else {- format!("{base}{suffix}")+ format!("{base}{suffix}")};- Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4))+ Ok(Instruction::with_text(+ address,+ raw.to_vec(),+ mnemonic,+ operands,+ 4,+ ))}pub fn try_decode_misc(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {- // CLZ Rd, Rm: cond 0001 0110 1111 Rm 0000 0001 Rd+ // CLZ Rd, Rm: cond 0001 0110 1111 Rm 0000 0001 Rdif (word & 0x0ff0_0f70) == 0x0160_0f10 {let cond = (word >> 28) & 0xf;let rd = (word >> 12) & 0xf;let rm = word & 0xf;let suffix = cond_suffix(cond);let mnemonic = if suffix.is_empty() {- "clz".into()+ "clz".into()} else {- format!("clz{suffix}")+ format!("clz{suffix}")};return Some(Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- format!("{}, {}", gpr(rd), gpr(rm)),+ format!("{}, {}", gpr(rd), gpr(rm)),4,)));}diff --git a/crates/ghidrust-decode/src/arch/arm/a32_load_store.rs b/crates/ghidrust-decode/src/arch/arm/a32_load_store.rsindex 5e4e00b..6cc893f 100644--- a/crates/ghidrust-decode/src/arch/arm/a32_load_store.rs+++ b/crates/ghidrust-decode/src/arch/arm/a32_load_store.rs@@ -25,42 +25,69 @@ fn decode_immediate(word: u32, address: u64, raw: &[u8]) -> Result<Instruction>let rd = (word >> 12) & 0xf;let imm12 = word & 0xfff;let offset = if u { imm12 } else { 0u32.wrapping_sub(imm12) };- let size = if b { 1u8 } else if w { 4 } else { 2 };+ let size = if b {+ 1u8+ } else if w {+ 4+ } else {+ 2+ };let size_str = match size {- 1 => "b",- 2 => "h",- 4 => "w",- _ => "",+ 1 => "b",+ 2 => "h",+ 4 => "w",+ _ => "",};let suffix = cond_suffix(cond);let (base, operands) = if l {if rd == 15 {- // LDR literal pool+ // LDR literal poollet base_addr = if p {address.wrapping_add(8)} else {address.wrapping_add(4)};let ea = base_addr.wrapping_add(offset as u64);- (- format!("ldr{suffix}"),- format!("pc, [{:#x}]", ea),- )+ (format!("ldr{suffix}"), format!("pc, [{:#x}]", ea))} else {- let sign = if u { "" } else { "-" };+ let sign = if u { "" } else { "-" };(- format!("ldr{suffix}{size_str}"),- format!("{}, [{}{}]", gpr(rd), gpr(rn), if offset != 0 { format!(", {sign}{offset}") } else { String::new() }),+ format!("ldr{suffix}{size_str}"),+ format!(+ "{}, [{}{}]",+ gpr(rd),+ gpr(rn),+ if offset != 0 {+ format!(", {sign}{offset}")+ } else {+ String::new()+ }+ ),)}} else {- let sign = if u { "" } else { "-" };+ let sign = if u { "" } else { "-" };(- format!("str{suffix}{size_str}"),- format!("{}, [{}{}]", gpr(rd), gpr(rn), if offset != 0 { format!(", {sign}{offset}") } else { String::new() }),+ format!("str{suffix}{size_str}"),+ format!(+ "{}, [{}{}]",+ gpr(rd),+ gpr(rn),+ if offset != 0 {+ format!(", {sign}{offset}")+ } else {+ String::new()+ }+ ),)};- Ok(Instruction::with_text(address, raw.to_vec(), base, operands, 4))+ Ok(Instruction::with_text(+ address,+ raw.to_vec(),+ base,+ operands,+ 4,+ ))}fn decode_register(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {@@ -73,33 +100,56 @@ fn decode_register(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {let rn = (word >> 16) & 0xf;let rd = (word >> 12) & 0xf;let rm = word & 0xf;- let size = if b { 1u8 } else if w { 4 } else { 2 };+ let size = if b {+ 1u8+ } else if w {+ 4+ } else {+ 2+ };let size_str = match size {- 1 => "b",- 2 => "h",- 4 => "w",- _ => "",+ 1 => "b",+ 2 => "h",+ 4 => "w",+ _ => "",};let suffix = cond_suffix(cond);- let sign = if u { "" } else { "-" };+ let sign = if u { "" } else { "-" };let (base, operands) = if l {(- format!("ldr{suffix}{size_str}"),- format!("{}, [{}{}]", gpr(rd), gpr(rn), format!(", {sign}{}", gpr(rm))),+ format!("ldr{suffix}{size_str}"),+ format!(+ "{}, [{}{}]",+ gpr(rd),+ gpr(rn),+ format!(", {sign}{}", gpr(rm))+ ),)} else {(- format!("str{suffix}{size_str}"),- format!("{}, [{}{}]", gpr(rd), gpr(rn), format!(", {sign}{}", gpr(rm))),+ format!("str{suffix}{size_str}"),+ format!(+ "{}, [{}{}]",+ gpr(rd),+ gpr(rn),+ format!(", {sign}{}", gpr(rm))+ ),)};let _ = p;- Ok(Instruction::with_text(address, raw.to_vec(), base, operands, 4))+ Ok(Instruction::with_text(+ address,+ raw.to_vec(),+ base,+ operands,+ 4,+ ))}pub fn try_decode_extra(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {- // Load/store dual immediate: cond 000 P U S W L Rn Rd imm4- if (word & 0x0e00_0000) == 0x0400_0000 && ((word >> 25) & 1) == 0 && ((word >> 20) & 0x10) != 0 {+ // Load/store dual immediate: cond 000 P U S W L Rn Rd imm4+ if (word & 0x0e00_0000) == 0x0400_0000 && ((word >> 25) & 1) == 0 && ((word >> 20) & 0x10) != 0+ {let cond = (word >> 28) & 0xf;let u = ((word >> 23) & 1) != 0;let l = ((word >> 20) & 1) != 0;@@ -108,17 +158,23 @@ pub fn try_decode_extra(word: u32, address: u64, raw: &[u8]) -> Option<Result<Inlet imm = (word & 0xf) << 4 | ((word >> 8) & 0xf);let offset = if u { imm } else { 0u32.wrapping_sub(imm) };let suffix = cond_suffix(cond);- let sign = if u { "" } else { "-" };+ let sign = if u { "" } else { "-" };let base = if l {- format!("ldm{suffix}ia")+ format!("ldm{suffix}ia")} else {- format!("stm{suffix}ia")+ format!("stm{suffix}ia")};- let operands = format!("{}, {{{}, {}}}", gpr(rn), gpr(rd), gpr(rd + 1));+ let operands = format!("{}, {{{}, {}}}", gpr(rn), gpr(rd), gpr(rd + 1));let _ = (offset, sign);- return Some(Ok(Instruction::with_text(address, raw.to_vec(), base, operands, 4)));+ return Some(Ok(Instruction::with_text(+ address,+ raw.to_vec(),+ base,+ operands,+ 4,+ )));}- // LDRD/STRD immediate+ // LDRD/STRD immediateif (word & 0x0e50_00f0) == 0x0040_00d0 {let cond = (word >> 28) & 0xf;let u = ((word >> 23) & 1) != 0;@@ -128,20 +184,30 @@ pub fn try_decode_extra(word: u32, address: u64, raw: &[u8]) -> Option<Result<Inlet imm = (word & 0xf) << 4 | ((word >> 8) & 0xf);let offset = if u { imm } else { 0u32.wrapping_sub(imm) };let suffix = cond_suffix(cond);- let sign = if u { "" } else { "-" };- let base = if l { format!("ldrd{suffix}") } else { format!("strd{suffix}") };+ let sign = if u { "" } else { "-" };+ let base = if l {+ format!("ldrd{suffix}")+ } else {+ format!("strd{suffix}")+ };let operands = format!(- "{}, {}, [{}{}]",+ "{}, {}, [{}{}]",gpr(rd),gpr(rd + 1),gpr(rn),if offset != 0 {- format!(", {sign}{offset}")+ format!(", {sign}{offset}")} else {String::new()});- return Some(Ok(Instruction::with_text(address, raw.to_vec(), base, operands, 4)));+ return Some(Ok(Instruction::with_text(+ address,+ raw.to_vec(),+ base,+ operands,+ 4,+ )));}None}diff --git a/crates/ghidrust-decode/src/arch/arm/a32_media.rs b/crates/ghidrust-decode/src/arch/arm/a32_media.rsindex 570efa7..265b85a 100644--- a/crates/ghidrust-decode/src/arch/arm/a32_media.rs+++ b/crates/ghidrust-decode/src/arch/arm/a32_media.rs@@ -5,7 +5,7 @@ use crate::insn::Instruction;pub fn try_decode(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {let top = (word >> 24) & 0xf;- // VFP / NEON data processing in A32: cond 111x ..+ // VFP / NEON data processing in A32: cond 111x ..if top == 0b1110 || top == 0b1101 {return try_neon_vfp(word, address, raw);}@@ -13,26 +13,26 @@ pub fn try_decode(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruct}fn try_neon_vfp(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {- // VMOV (register): cond 1110 0001 0000 Rn 0000 0000 Rd+ // VMOV (register): cond 1110 0001 0000 Rn 0000 0000 Rdif (word & 0x0fe0_0fff) == 0x0e10_0000 {let cond = (word >> 28) & 0xf;let rd = (word >> 12) & 0xf;let rm = word & 0xf;let suffix = cond_suffix(cond);let mnemonic = if suffix.is_empty() {- "vmov".into()+ "vmov".into()} else {- format!("vmov{suffix}")+ format!("vmov{suffix}")};return Some(Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- format!("{}, {}", neon_d(rd), neon_d(rm)),+ format!("{}, {}", neon_d(rd), neon_d(rm)),4,)));}- // VADD.F32 Dd, Dn, Dm: cond 1110 0011 0 Dn 0010 1 Dm 0 Dd+ // VADD.F32 Dd, Dn, Dm: cond 1110 0011 0 Dn 0010 1 Dm 0 Ddif (word & 0xfe50_0f50) == 0xee30_0b00 {let cond = (word >> 28) & 0xf;let d = ((word >> 22) & 1) << 4 | ((word >> 12) & 0xf);@@ -40,19 +40,19 @@ fn try_neon_vfp(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instructiolet m = word & 0xf;let suffix = cond_suffix(cond);let mnemonic = if suffix.is_empty() {- "vadd.f32".into()+ "vadd.f32".into()} else {- format!("vadd.f32{suffix}")+ format!("vadd.f32{suffix}")};return Some(Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- format!("{}, {}, {}", neon_d(d), neon_d(n), neon_d(m)),+ format!("{}, {}, {}", neon_d(d), neon_d(n), neon_d(m)),4,)));}- // VLD1 / VST1 multiple+ // VLD1 / VST1 multipleif (word & 0xff20_0f00) == 0xec00_0a00 {let cond = (word >> 28) & 0xf;let l = ((word >> 20) & 1) != 0;@@ -60,34 +60,34 @@ fn try_neon_vfp(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instructiolet d = ((word >> 22) & 1) << 4 | ((word >> 12) & 0xf);let suffix = cond_suffix(cond);let base = if l {- format!("vld1.32{suffix}")+ format!("vld1.32{suffix}")} else {- format!("vst1.32{suffix}")+ format!("vst1.32{suffix}")};return Some(Ok(Instruction::with_text(address,raw.to_vec(),base,- format!("{{{}}}, [{}]", neon_d(d), gpr(rn)),+ format!("{{{}}}, [{}]", neon_d(d), gpr(rn)),4,)));}- // VMOV (general): ARM to scalar+ // VMOV (general): ARM to scalarif (word & 0x0fe0_0fff) == 0x0e00_0b10 {let cond = (word >> 28) & 0xf;let rd = (word >> 12) & 0xf;let vn = (((word >> 16) & 0xf) << 1) | ((word >> 7) & 1);let suffix = cond_suffix(cond);let mnemonic = if suffix.is_empty() {- "vmov".into()+ "vmov".into()} else {- format!("vmov{suffix}")+ format!("vmov{suffix}")};return Some(Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- format!("{}, {}", gpr(rd), neon_d(vn)),+ format!("{}, {}", gpr(rd), neon_d(vn)),4,)));}diff --git a/crates/ghidrust-decode/src/arch/arm/a32_system.rs b/crates/ghidrust-decode/src/arch/arm/a32_system.rsindex 87fd78b..8e46ba6 100644--- a/crates/ghidrust-decode/src/arch/arm/a32_system.rs+++ b/crates/ghidrust-decode/src/arch/arm/a32_system.rs@@ -4,89 +4,101 @@ use crate::error::Result;use crate::insn::Instruction;pub fn try_decode(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {- // SVC: cond 1111 imm24+ // SVC: cond 1111 imm24if (word & 0x0f00_0000) == 0x0f00_0000 {let cond = (word >> 28) & 0xf;let imm = word & 0x00ff_ffff;let suffix = cond_suffix(cond);let mnemonic = if suffix.is_empty() {- "svc".into()+ "svc".into()} else {- format!("svc{suffix}")+ format!("svc{suffix}")};return Some(Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- format!("#{:#x}", imm),+ format!("#{:#x}", imm),4,)));}- // MRS: cond 000 10 R 0000 0000 mask 0000 Rd+ // MRS: cond 000 10 R 0000 0000 mask 0000 Rdif (word & 0x0fbf_0fff) == 0x010f_0000 {let cond = (word >> 28) & 0xf;let rd = (word >> 12) & 0xf;let r = ((word >> 22) & 1) != 0;let field = (word >> 16) & 0x1f;let suffix = cond_suffix(cond);- let src = if r { "spsr" } else { "cpsr" };+ let src = if r { "spsr" } else { "cpsr" };let mnemonic = if suffix.is_empty() {- "mrs".into()+ "mrs".into()} else {- format!("mrs{suffix}")+ format!("mrs{suffix}")};let operands = if field == 0 {- format!("{}, {}", gpr(rd), src)+ format!("{}, {}", gpr(rd), src)} else {- format!("{}, {}_{}", gpr(rd), src, psr_field(field))+ format!("{}, {}_{}", gpr(rd), src, psr_field(field))};- return Some(Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4)));+ return Some(Ok(Instruction::with_text(+ address,+ raw.to_vec(),+ mnemonic,+ operands,+ 4,+ )));}- // MSR: cond 000 10 R 10 mask 0000 Rm+ // MSR: cond 000 10 R 10 mask 0000 Rmif (word & 0x0fb0_0ff0) == 0x0120_0f00 {let cond = (word >> 28) & 0xf;let rm = word & 0xf;let r = ((word >> 22) & 1) != 0;let field = (word >> 16) & 0x1f;let suffix = cond_suffix(cond);- let dst = if r { "spsr" } else { "cpsr" };+ let dst = if r { "spsr" } else { "cpsr" };let mnemonic = if suffix.is_empty() {- "msr".into()+ "msr".into()} else {- format!("msr{suffix}")+ format!("msr{suffix}")};let operands = if field == 0 {- format!("{}, {}", dst, gpr(rm))+ format!("{}, {}", dst, gpr(rm))} else {- format!("{}_{}, {}", dst, psr_field(field), gpr(rm))+ format!("{}_{}, {}", dst, psr_field(field), gpr(rm))};- return Some(Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4)));+ return Some(Ok(Instruction::with_text(+ address,+ raw.to_vec(),+ mnemonic,+ operands,+ 4,+ )));}- // NOP (hint): cond 0001 0010 0000 1111 1111 0000 0000+ // NOP (hint): cond 0001 0010 0000 1111 1111 0000 0000if word == 0xe320_0070 || (word & 0x0ff0_0fff) == 0x0320_0f00 && (word & 0xf) == 0 {let cond = (word >> 28) & 0xf;let suffix = cond_suffix(cond);let mnemonic = if suffix.is_empty() {- "nop".into()+ "nop".into()} else {- format!("nop{suffix}")+ format!("nop{suffix}")};return Some(Ok(Instruction::with_text(address,raw.to_vec(),mnemonic,- "",+ "",4,)));}- // BKPT+ // BKPTif (word & 0x0ff0_00f0) == 0x0120_0070 {let imm = (word >> 4) & 0xfff | ((word >> 8) & 0xf) << 12;return Some(Ok(Instruction::with_text(address,raw.to_vec(),- "bkpt",- format!("#{:#x}", imm),+ "bkpt",+ format!("#{:#x}", imm),4,)));}diff --git a/crates/ghidrust-decode/src/arch/arm/dispatch.rs b/crates/ghidrust-decode/src/arch/arm/dispatch.rsindex 4b17b29..a1a523a 100644--- a/crates/ghidrust-decode/src/arch/arm/dispatch.rs+++ b/crates/ghidrust-decode/src/arch/arm/dispatch.rs@@ -11,7 +11,7 @@ use crate::insn::Instruction;pub fn decode_a32(bytes: &[u8], address: u64, big_endian: bool) -> Result<Instruction> {if bytes.len() < 4 {- return Err(Error::Decode("truncated A32 instruction".into()));+ return Err(Error::Decode("truncated A32 instruction".into()));}let word = util::read_u32_le(bytes, big_endian)?;let raw = &bytes[..4];@@ -39,12 +39,14 @@ pub fn decode_a32(bytes: &[u8], address: u64, big_endian: bool) -> Result<Instruif let Some(r) = a32_media::try_decode(word, address, raw) {return r;}- Err(Error::Decode(format!("unhandled A32 encoding {word:#010x}")))+ Err(Error::Decode(format!(+ "unhandled A32 encoding {word:#010x}"+ )))}pub fn decode_thumb(bytes: &[u8], address: u64, big_endian: bool) -> Result<Instruction> {if bytes.len() < 2 {- return Err(Error::Decode("truncated Thumb instruction".into()));+ return Err(Error::Decode("truncated Thumb instruction".into()));}let hw = util::read_u16_le(bytes, big_endian)?;if (hw & 0xe000) >= 0xe000 && (hw & 0x1800) != 0x0000 {diff --git a/crates/ghidrust-decode/src/arch/arm/mod.rs b/crates/ghidrust-decode/src/arch/arm/mod.rsindex da37ad1..5151fba 100644--- a/crates/ghidrust-decode/src/arch/arm/mod.rs+++ b/crates/ghidrust-decode/src/arch/arm/mod.rs@@ -14,8 +14,8 @@ use crate::error::{Error, Result};use crate::group::GroupId;use crate::insn::{InsnDetail, InsnId, Instruction};use crate::names;-use crate::option::EngineOptions;use crate::operand::OpType;+use crate::option::EngineOptions;use crate::reg::RegId;use crate::support::{Arch, Mode};@@ -32,7 +32,7 @@ impl ArchDecode for ArmDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Arm) {- return Err(Error::Mode(format!("invalid ARM mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!("invalid ARM mode {:#x}", mode.bits())));}let thumb = mode.contains(Mode::THUMB);let big_endian = mode.contains(Mode::BIG_ENDIAN);@@ -65,12 +65,12 @@ impl ArchDecode for ArmDecoder {}fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {- let m = mnemonic.split('.').next().unwrap_or(mnemonic);- if m == "bl" || m.starts_with("blx") {+ let m = mnemonic.split('.').next().unwrap_or(mnemonic);+ if m == "bl" || m.starts_with("blx") {vec![GroupId::Call, GroupId::BranchRelative]- } else if m == "bx" || m == "b" || (m.starts_with('b') && !m.starts_with("bic")) {+ } else if m == "bx" || m == "b" || (m.starts_with('b') && !m.starts_with("bic")) {vec![GroupId::Jump, GroupId::BranchRelative]- } else if m.starts_with("svc") {+ } else if m.starts_with("svc") {vec![GroupId::Int]} else {Vec::new()@@ -83,48 +83,48 @@ pub fn reg_name(reg: RegId) -> Option<&'static str> {pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("mov"),- 2 => Some("ldr"),- 3 => Some("str"),- 4 => Some("b"),- 5 => Some("bl"),- 6 => Some("add"),- 7 => Some("sub"),- 8 => Some("push"),- 9 => Some("pop"),- 10 => Some("svc"),- 11 => Some("bx"),- 12 => Some("nop"),+ 1 => Some("mov"),+ 2 => Some("ldr"),+ 3 => Some("str"),+ 4 => Some("b"),+ 5 => Some("bl"),+ 6 => Some("add"),+ 7 => Some("sub"),+ 8 => Some("push"),+ 9 => Some("pop"),+ 10 => Some("svc"),+ 11 => Some("bx"),+ 12 => Some("nop"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Ret => Some("ret"),- GroupId::Int => Some("int"),- GroupId::BranchRelative => Some("branch_relative"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Ret => Some("ret"),+ GroupId::Int => Some("int"),+ GroupId::BranchRelative => Some("branch_relative"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {- let m = mnemonic.split('.').next().unwrap_or(mnemonic);- let id = match m.trim_end_matches(|c: char| c.is_ascii_lowercase() && c != 'x') {- s if s.starts_with("mov") => 1,- s if s.starts_with("ldr") => 2,- s if s.starts_with("str") => 3,- "b" => 4,- "bl" | "blx" => 5,- s if s.starts_with("add") => 6,- s if s.starts_with("sub") => 7,- "push" => 8,- "pop" => 9,- s if s.starts_with("svc") => 10,- "bx" => 11,- "nop" => 12,+ let m = mnemonic.split('.').next().unwrap_or(mnemonic);+ let id = match m.trim_end_matches(|c: char| c.is_ascii_lowercase() && c != 'x') {+ s if s.starts_with("mov") => 1,+ s if s.starts_with("ldr") => 2,+ s if s.starts_with("str") => 3,+ "b" => 4,+ "bl" | "blx" => 5,+ s if s.starts_with("add") => 6,+ s if s.starts_with("sub") => 7,+ "push" => 8,+ "pop" => 9,+ s if s.starts_with("svc") => 10,+ "bx" => 11,+ "nop" => 12,_ => 0,};InsnId(id)@@ -143,33 +143,33 @@ mod tests {#[test]fn arm_a32_mov_add_branch() {let mut eng = Engine::open(Arch::Arm, Mode::LITTLE_ENDIAN).unwrap();- // mov r0, #1 -> e3a00001+ // mov r0, #1 -> e3a00001let mov = eng.disasm_one(&[0x01, 0x00, 0xa0, 0xe3], 0x1000).unwrap();- assert_eq!(mov.mnemonic, "mov");+ assert_eq!(mov.mnemonic, "mov");assert_eq!(mov.length, 4);- // add r1, r0, r2 -> e0801002+ // add r1, r0, r2 -> e0801002let add = eng.disasm_one(&[0x02, 0x10, 0x80, 0xe0], 0x1004).unwrap();- assert_eq!(add.mnemonic, "add");- // b #0 -> ea000000+ assert_eq!(add.mnemonic, "add");+ // b #0 -> ea000000let b = eng.disasm_one(&[0x00, 0x00, 0x00, 0xea], 0x1008).unwrap();- assert_eq!(b.mnemonic, "b");+ assert_eq!(b.mnemonic, "b");}#[test]fn arm_thumb16_push_pop() {let mut eng = Engine::open(Arch::Arm, Mode::THUMB).unwrap();- // push {r4, lr} -> b510+ // push {r4, lr} -> b510let push = eng.disasm_one(&[0x10, 0xb5], 0x2000).unwrap();- assert_eq!(push.mnemonic, "push");+ assert_eq!(push.mnemonic, "push");assert_eq!(push.length, 2);}#[test]fn arm_thumb32_bl() {let mut eng = Engine::open(Arch::Arm, Mode::THUMB).unwrap();- // bl #0 -> f0 00 f8 00 (approx — zero offset BL)+ // bl #0 -> f0 00 f8 00 (approx — zero offset BL)let bl = eng.disasm_one(&[0x00, 0xf0, 0x00, 0xf8], 0x3000).unwrap();- assert!(bl.mnemonic == "bl" || bl.mnemonic.starts_with("bl"));+ assert!(bl.mnemonic == "bl" || bl.mnemonic.starts_with("bl"));assert_eq!(bl.length, 4);}@@ -177,6 +177,6 @@ mod tests {fn arm_svc() {let mut eng = Engine::open(Arch::Arm, Mode::LITTLE_ENDIAN).unwrap();let svc = eng.disasm_one(&[0x00, 0x00, 0x00, 0xef], 0x0).unwrap();- assert_eq!(svc.mnemonic, "svc");+ assert_eq!(svc.mnemonic, "svc");}}diff --git a/crates/ghidrust-decode/src/arch/arm/regs.rs b/crates/ghidrust-decode/src/arch/arm/regs.rsindex 99beb4f..9cd847c 100644--- a/crates/ghidrust-decode/src/arch/arm/regs.rs+++ b/crates/ghidrust-decode/src/arch/arm/regs.rs@@ -3,23 +3,23 @@ use crate::support::Arch;pub fn gpr(n: u32) -> &'static str {match n & 0xf {- 0 => "r0",- 1 => "r1",- 2 => "r2",- 3 => "r3",- 4 => "r4",- 5 => "r5",- 6 => "r6",- 7 => "r7",- 8 => "r8",- 9 => "r9",- 10 => "r10",- 11 => "r11",- 12 => "r12",- 13 => "sp",- 14 => "lr",- 15 => "pc",- _ => "r0",+ 0 => "r0",+ 1 => "r1",+ 2 => "r2",+ 3 => "r3",+ 4 => "r4",+ 5 => "r5",+ 6 => "r6",+ 7 => "r7",+ 8 => "r8",+ 9 => "r9",+ 10 => "r10",+ 11 => "r11",+ 12 => "r12",+ 13 => "sp",+ 14 => "lr",+ 15 => "pc",+ _ => "r0",}}@@ -28,39 +28,39 @@ pub fn reg_id(n: u32) -> RegId {}pub fn neon_d(n: u32) -> String {- format!("d{}", n & 0x1f)+ format!("d{}", n & 0x1f)}pub fn neon_q(n: u32) -> String {- format!("q{}", n & 0xf)+ format!("q{}", n & 0xf)}pub fn psr_field(field: u32) -> &'static str {match field {- 0b10000 => "c",- 0b01000 => "x",- 0b00100 => "s",- 0b00010 => "f",- 0b11111 => "cpsr",- 0b11110 => "spsr",- _ => "cpsr",+ 0b10000 => "c",+ 0b01000 => "x",+ 0b00100 => "s",+ 0b00010 => "f",+ 0b11111 => "cpsr",+ 0b11110 => "spsr",+ _ => "cpsr",}}pub fn banked_reg(r: u32, mode: u32) -> String {match (r, mode) {- (13, 0b10000) => "sp_usr".into(),- (14, 0b10000) => "lr_usr".into(),- (13, 0b10001) => "sp_fiq".into(),- (14, 0b10001) => "lr_fiq".into(),- (13, 0b10010) => "sp_irq".into(),- (14, 0b10010) => "lr_irq".into(),- (13, 0b10011) => "sp_svc".into(),- (14, 0b10011) => "lr_svc".into(),- (13, 0b10100) => "sp_abt".into(),- (14, 0b10100) => "lr_abt".into(),- (13, 0b10110) => "sp_und".into(),- (14, 0b10110) => "lr_und".into(),+ (13, 0b10000) => "sp_usr".into(),+ (14, 0b10000) => "lr_usr".into(),+ (13, 0b10001) => "sp_fiq".into(),+ (14, 0b10001) => "lr_fiq".into(),+ (13, 0b10010) => "sp_irq".into(),+ (14, 0b10010) => "lr_irq".into(),+ (13, 0b10011) => "sp_svc".into(),+ (14, 0b10011) => "lr_svc".into(),+ (13, 0b10100) => "sp_abt".into(),+ (14, 0b10100) => "lr_abt".into(),+ (13, 0b10110) => "sp_und".into(),+ (14, 0b10110) => "lr_und".into(),_ => gpr(r).into(),}}diff --git a/crates/ghidrust-decode/src/arch/arm/thumb16.rs b/crates/ghidrust-decode/src/arch/arm/thumb16.rsindex f835987..6c3e4aa 100644--- a/crates/ghidrust-decode/src/arch/arm/thumb16.rs+++ b/crates/ghidrust-decode/src/arch/arm/thumb16.rs@@ -15,7 +15,7 @@ pub fn decode(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instructi0b1101 => decode_load_store_reg(hw, bytes, address, be, true),0b1110 => decode_fmt1110(hw, bytes, address, be),0b1111 => decode_svc(hw, bytes, address, be),- _ => Err(Error::Decode(format!("unhandled T16 {hw:#06x}"))),+ _ => Err(Error::Decode(format!("unhandled T16 {hw:#06x}"))),}}@@ -33,17 +33,23 @@ fn decode_mov_shift(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Inslet rs = (hw >> 3) & 0x7;let rd = hw & 0x7;let mnemonic = match op {- 0b00 => "lsls",- 0b01 => "lsrs",- 0b10 => "asrs",- _ => "movs",+ 0b00 => "lsls",+ 0b01 => "lsrs",+ 0b10 => "asrs",+ _ => "movs",};let operands = if op == 0b11 {- format!("{}, {}", gpr(rs as u32), gpr(rd as u32))+ format!("{}, {}", gpr(rs as u32), gpr(rd as u32))} else {- format!("{}, {}, #{offset}", gpr(rs as u32), gpr(rd as u32))+ format!("{}, {}, #{offset}", gpr(rs as u32), gpr(rd as u32))};- Ok(Instruction::with_text(address, raw2(bytes, be), mnemonic, operands, 2))+ Ok(Instruction::with_text(+ address,+ raw2(bytes, be),+ mnemonic,+ operands,+ 2,+ ))}fn decode_load_store_imm5(@@ -56,12 +62,12 @@ fn decode_load_store_imm5(let imm = ((hw >> 6) & 0x1f) << 2;let rb = (hw >> 3) & 0x7;let rd = hw & 0x7;- let mnemonic = if load { "ldr" } else { "str" };+ let mnemonic = if load { "ldr" } else { "str" };Ok(Instruction::with_text(address,raw2(bytes, be),mnemonic,- format!("{}, [{}, #{imm}]", gpr(rd as u32), gpr(rb as u32)),+ format!("{}, [{}, #{imm}]", gpr(rd as u32), gpr(rb as u32)),2,))}@@ -76,12 +82,12 @@ fn decode_load_store_h(let imm = ((hw >> 6) & 0x1f) << 1;let rb = (hw >> 3) & 0x7;let rd = hw & 0x7;- let mnemonic = if load { "ldrh" } else { "strh" };+ let mnemonic = if load { "ldrh" } else { "strh" };Ok(Instruction::with_text(address,raw2(bytes, be),mnemonic,- format!("{}, [{}, #{imm}]", gpr(rd as u32), gpr(rb as u32)),+ format!("{}, [{}, #{imm}]", gpr(rd as u32), gpr(rb as u32)),2,))}@@ -95,12 +101,12 @@ fn decode_load_store_sp() -> Result<Instruction> {let imm = ((hw >> 4) & 0xff) << 2;let rd = hw & 0x7;- let mnemonic = if load { "ldr" } else { "str" };+ let mnemonic = if load { "ldr" } else { "str" };Ok(Instruction::with_text(address,raw2(bytes, be),mnemonic,- format!("{}, [sp, #{imm}]", gpr(rd as u32)),+ format!("{}, [sp, #{imm}]", gpr(rd as u32)),2,))}@@ -110,12 +116,12 @@ fn decode_add_sub(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instrlet imm = (hw >> 6) & 0x7;let rn = (hw >> 3) & 0x7;let rd = hw & 0x7;- let mnemonic = if add { "add" } else { "sub" };+ let mnemonic = if add { "add" } else { "sub" };Ok(Instruction::with_text(address,raw2(bytes, be),mnemonic,- format!("{}, {}, #{imm}", gpr(rd as u32), gpr(rn as u32)),+ format!("{}, {}, #{imm}", gpr(rd as u32), gpr(rn as u32)),2,))}@@ -157,17 +163,17 @@ fn decode_push_pop(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Inst}}if lr && push {- regs.push("lr");+ regs.push("lr");}if pc && !push {- regs.push("pc");+ regs.push("pc");}- let mnemonic = if push { "push" } else { "pop" };+ let mnemonic = if push { "push" } else { "pop" };Ok(Instruction::with_text(address,raw2(bytes, be),mnemonic,- format!("{{{}}}", regs.join(", ")),+ format!("{{{}}}", regs.join(", ")),2,))}@@ -178,16 +184,16 @@ fn decode_misc(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instructlet rd = (hw & 0x7) | if h1 { 8 } else { 0 };let rm = ((hw >> 3) & 0x7) | if h2 { 8 } else { 0 };let mnemonic = match (hw >> 9) & 0x3 {- 0b00 => "add",- 0b01 => "cmp",- 0b10 => "mov",- _ => "bx",+ 0b00 => "add",+ 0b01 => "cmp",+ 0b10 => "mov",+ _ => "bx",};- if mnemonic == "bx" {+ if mnemonic == "bx" {return Ok(Instruction::with_text(address,raw2(bytes, be),- "bx",+ "bx",gpr(rm as u32),2,));@@ -196,7 +202,7 @@ fn decode_misc(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instructaddress,raw2(bytes, be),mnemonic,- format!("{}, {}", gpr(rd as u32), gpr(rm as u32)),+ format!("{}, {}", gpr(rd as u32), gpr(rm as u32)),2,))}@@ -210,7 +216,7 @@ fn decode_branch_cond(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<IOk(Instruction::with_text(address,raw2(bytes, be),- format!("b{suffix}"),+ format!("b{suffix}"),fmt_imm_hex(target as i64),2,))@@ -226,12 +232,17 @@ fn decode_load_store_reg(let ro = (hw >> 6) & 0x7;let rb = (hw >> 3) & 0x7;let rd = hw & 0x7;- let mnemonic = if load { "ldr" } else { "str" };+ let mnemonic = if load { "ldr" } else { "str" };Ok(Instruction::with_text(address,raw2(bytes, be),mnemonic,- format!("{}, [{}, {}]", gpr(rd as u32), gpr(rb as u32), gpr(ro as u32)),+ format!(+ "{}, [{}, {}]",+ gpr(rd as u32),+ gpr(rb as u32),+ gpr(ro as u32)+ ),2,))}@@ -245,16 +256,16 @@ fn decode_add_sp_pc(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Insreturn Ok(Instruction::with_text(address,raw2(bytes, be),- "adr",- format!("{}, {:#x}", gpr(rd as u32), target),+ "adr",+ format!("{}, {:#x}", gpr(rd as u32), target),2,));}Ok(Instruction::with_text(address,raw2(bytes, be),- "add",- format!("{}, sp, #{imm}", gpr(rd as u32)),+ "add",+ format!("{}, sp, #{imm}", gpr(rd as u32)),2,))}@@ -266,7 +277,7 @@ fn decode_branch(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<InstruOk(Instruction::with_text(address,raw2(bytes, be),- "b",+ "b",fmt_imm_hex(target as i64),2,))@@ -277,8 +288,8 @@ fn decode_svc(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<InstructiOk(Instruction::with_text(address,raw2(bytes, be),- "svc",- format!("#{imm}"),+ "svc",+ format!("#{imm}"),2,))}diff --git a/crates/ghidrust-decode/src/arch/arm/thumb32.rs b/crates/ghidrust-decode/src/arch/arm/thumb32.rsindex a8a84fc..0d9bd07 100644--- a/crates/ghidrust-decode/src/arch/arm/thumb32.rs+++ b/crates/ghidrust-decode/src/arch/arm/thumb32.rs@@ -5,7 +5,7 @@ use crate::insn::Instruction;pub fn decode(bytes: &[u8], address: u64, big_endian: bool) -> Result<Instruction> {if bytes.len() < 4 {- return Err(Error::Decode("truncated Thumb32 instruction".into()));+ return Err(Error::Decode("truncated Thumb32 instruction".into()));}let hw1 = super::util::read_u16_le(bytes, big_endian)?;let hw2 = super::util::read_u16_le(&bytes[2..], big_endian)?;@@ -13,31 +13,33 @@ pub fn decode(bytes: &[u8], address: u64, big_endian: bool) -> Result<Instructiolet op1 = (hw1 >> 11) & 0x3;let _op2 = (hw1 >> 4) & 0x7f;- // 32-bit conditional branch: 11110 S cond imm6 10 J1 J2 imm11+ // 32-bit conditional branch: 11110 S cond imm6 10 J1 J2 imm11if op1 == 0b10 && (hw1 & 0x1000) == 0 && (hw2 & 0x8000) == 0 {return decode_branch(hw1, hw2, address, raw);}- // Load/store multiple / dual+ // Load/store multiple / dualif op1 == 0b11 && (hw1 & 0x1200) == 0x0000 {return decode_load_store_dual(hw1, hw2, address, raw);}- // Data processing (modified immediate)+ // Data processing (modified immediate)if op1 == 0b11 && (hw1 & 0x1a00) == 0x0800 {return decode_dp_imm(hw1, hw2, address, raw);}- // Data processing (register)+ // Data processing (register)if op1 == 0b11 && (hw1 & 0x1e00) == 0x0a00 {return decode_dp_reg(hw1, hw2, address, raw);}- // Load/store single+ // Load/store singleif op1 == 0b11 && (hw1 & 0x1200) == 0x1000 {return decode_load_store_single(hw1, hw2, address, raw);}- // BL / BLX immediate: 11110.. 11 ..+ // BL / BLX immediate: 11110.. 11 ..if (hw1 & 0xf800) == 0xf000 && (hw2 & 0xd001) == 0xd000 {return decode_bl(hw1, hw2, address, raw);}- Err(Error::Decode(format!("unhandled T32 {hw1:#06x} {hw2:#06x}")))+ Err(Error::Decode(format!(+ "unhandled T32 {hw1:#06x} {hw2:#06x}"+ )))}fn decode_branch(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Result<Instruction> {@@ -56,7 +58,7 @@ fn decode_branch(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Result<Instrlet offset = sign_extend(imm, 25);let target = (address as i64).wrapping_add(offset as i64) as u64;let suffix = super::util::cond_suffix(cond as u32);- let mnemonic = format!("b{suffix}");+ let mnemonic = format!("b{suffix}");Ok(Instruction::with_text(address,raw,@@ -74,14 +76,15 @@ fn decode_bl(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Result<Instructilet imm11 = hw2 & 0x7ff;let i1 = !(j1 ^ s);let i2 = !(j2 ^ s);- let mut imm = (imm10 as u32) << 12 | (i1 as u32) << 22 | (i2 as u32) << 21 | (imm11 as u32) << 1;+ let mut imm =+ (imm10 as u32) << 12 | (i1 as u32) << 22 | (i2 as u32) << 21 | (imm11 as u32) << 1;if s {imm |= 1 << 23;}let offset = sign_extend(imm, 25);let target = (address as i64).wrapping_add(offset as i64) as u64;let x = ((hw1 >> 12) & 1) != 0;- let mnemonic = if x { "blx" } else { "bl" };+ let mnemonic = if x { "blx" } else { "bl" };Ok(Instruction::with_text(address,raw,@@ -99,11 +102,11 @@ fn decode_dp_imm(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Result<Instrlet imm = thumb32_imm12(hw1, hw2);let base = arm_dp_mnemonic(opcode as u32, s);let operands = if opcode == 0b1101 && rn == 15 {- format!("{}, #{:#x}", gpr(rd as u32), imm)+ format!("{}, #{:#x}", gpr(rd as u32), imm)} else if opcode == 0b1111 && rn == 15 {- format!("{}, #{:#x}", gpr(rd as u32), imm)+ format!("{}, #{:#x}", gpr(rd as u32), imm)} else {- format!("{}, {}, #{:#x}", gpr(rd as u32), gpr(rn), imm)+ format!("{}, {}, #{:#x}", gpr(rd as u32), gpr(rn), imm)};Ok(Instruction::with_text(address, raw, base, operands, 4))}@@ -119,7 +122,7 @@ fn decode_dp_reg(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Result<Instrlet base = arm_dp_mnemonic(opcode as u32, s);let shift_str = fmt_shift_reg(shift_type as u32, shift_imm as u32);let operands = format!(- "{}, {}, {}{}",+ "{}, {}, {}{}",gpr(rd as u32),gpr(rn),gpr(rm as u32),@@ -133,12 +136,12 @@ fn decode_load_store_single(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Rlet rn = (hw1 & 0xf) as u32;let rt = (hw2 >> 12) & 0xf;let imm12 = ((hw1 & 0xff) as u32) << 4 | ((hw2 >> 4) & 0xf) as u32;- let mnemonic = if l { "ldr" } else { "str" };+ let mnemonic = if l { "ldr" } else { "str" };Ok(Instruction::with_text(address,raw,mnemonic,- format!("{}, [{}, #{imm12}]", gpr(rt as u32), gpr(rn)),+ format!("{}, [{}, #{imm12}]", gpr(rt as u32), gpr(rn)),4,))}@@ -148,12 +151,12 @@ fn decode_load_store_dual(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Reslet rn = (hw1 & 0xf) as u32;let rt = (hw2 >> 12) & 0xf;let rt2 = (hw2 >> 8) & 0xf;- let mnemonic = if l { "ldrd" } else { "strd" };+ let mnemonic = if l { "ldrd" } else { "strd" };Ok(Instruction::with_text(address,raw,mnemonic,- format!("{}, {}, [{}]", gpr(rt as u32), gpr(rt2 as u32), gpr(rn)),+ format!("{}, {}, [{}]", gpr(rt as u32), gpr(rt2 as u32), gpr(rn)),4,))}diff --git a/crates/ghidrust-decode/src/arch/arm/util.rs b/crates/ghidrust-decode/src/arch/arm/util.rsindex aceeaf8..97466f2 100644--- a/crates/ghidrust-decode/src/arch/arm/util.rs+++ b/crates/ghidrust-decode/src/arch/arm/util.rs@@ -2,7 +2,7 @@ use crate::error::{Error, Result};pub fn read_u16_le(bytes: &[u8], big_endian: bool) -> Result<u16> {if bytes.len() < 2 {- return Err(Error::Decode("truncated halfword".into()));+ return Err(Error::Decode("truncated halfword".into()));}Ok(if big_endian {u16::from_be_bytes([bytes[0], bytes[1]])@@ -13,7 +13,7 @@ pub fn read_u16_le(bytes: &[u8], big_endian: bool) -> Result<u16> {pub fn read_u32_le(bytes: &[u8], big_endian: bool) -> Result<u32> {if bytes.len() < 4 {- return Err(Error::Decode("truncated word".into()));+ return Err(Error::Decode("truncated word".into()));}Ok(if big_endian {u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])@@ -34,9 +34,9 @@ pub fn sign_extend64(value: u64, bits: u32) -> i64 {pub fn fmt_imm_hex(v: i64) -> String {if v < 0 {- format!("-{:#x}", -v)+ format!("-{:#x}", -v)} else {- format!("{v:#x}")+ format!("{v:#x}")}}@@ -44,22 +44,22 @@ pub fn fmt_shift_imm(shift: u32) -> String {if shift == 0 {String::new()} else {- format!(", lsl #{shift}")+ format!(", lsl #{shift}")}}pub fn fmt_shift_reg(shift_type: u32, amount: u32) -> String {let kind = match shift_type {- 0b00 => "lsl",- 0b01 => "lsr",- 0b10 => "asr",- 0b11 => "ror",- _ => "lsl",+ 0b00 => "lsl",+ 0b01 => "lsr",+ 0b10 => "asr",+ 0b11 => "ror",+ _ => "lsl",};if amount == 0 && shift_type == 0b00 {String::new()} else {- format!(", {kind} #{amount}")+ format!(", {kind} #{amount}")}}@@ -79,45 +79,51 @@ pub fn arm_dp_imm(imm12: u32) -> u32 {pub fn cond_suffix(cond: u32) -> &'static str {match cond {- 0x0 => "eq",- 0x1 => "ne",- 0x2 => "cs",- 0x3 => "cc",- 0x4 => "mi",- 0x5 => "pl",- 0x6 => "vs",- 0x7 => "vc",- 0x8 => "hi",- 0x9 => "ls",- 0xa => "ge",- 0xb => "lt",- 0xc => "gt",- 0xd => "le",- 0xe => "",- 0xf => "",- _ => "",+ 0x0 => "eq",+ 0x1 => "ne",+ 0x2 => "cs",+ 0x3 => "cc",+ 0x4 => "mi",+ 0x5 => "pl",+ 0x6 => "vs",+ 0x7 => "vc",+ 0x8 => "hi",+ 0x9 => "ls",+ 0xa => "ge",+ 0xb => "lt",+ 0xc => "gt",+ 0xd => "le",+ 0xe => "",+ 0xf => "",+ _ => "",}}pub fn arm_dp_mnemonic(opcode: u32, s: bool) -> &'static str {match opcode {- 0b0000 => if s { "and" } else { "and" },- 0b0001 => "eor",- 0b0010 => "sub",- 0b0011 => "rsb",- 0b0100 => "add",- 0b0101 => "adc",- 0b0110 => "sbc",- 0b0111 => "rsc",- 0b1000 => "tst",- 0b1001 => "teq",- 0b1010 => "cmp",- 0b1011 => "cmn",- 0b1100 => "orr",- 0b1101 => "mov",- 0b1110 => "bic",- 0b1111 => "mvn",- _ => "and",+ 0b0000 => {+ if s {+ "and"+ } else {+ "and"+ }+ }+ 0b0001 => "eor",+ 0b0010 => "sub",+ 0b0011 => "rsb",+ 0b0100 => "add",+ 0b0101 => "adc",+ 0b0110 => "sbc",+ 0b0111 => "rsc",+ 0b1000 => "tst",+ 0b1001 => "teq",+ 0b1010 => "cmp",+ 0b1011 => "cmn",+ 0b1100 => "orr",+ 0b1101 => "mov",+ 0b1110 => "bic",+ 0b1111 => "mvn",+ _ => "and",}}diff --git a/crates/ghidrust-decode/src/arch/bpf/mod.rs b/crates/ghidrust-decode/src/arch/bpf/mod.rsindex 56d2e86..3280404 100644--- a/crates/ghidrust-decode/src/arch/bpf/mod.rs+++ b/crates/ghidrust-decode/src/arch/bpf/mod.rs@@ -94,7 +94,7 @@ pub(crate) fn decode_raw(bytes: &[u8], address: u64, mode: Mode) -> Result<Instrfn decode_classic(bytes: &[u8], address: u64) -> Result<Instruction> {if bytes.len() < 8 {- return Err(Error::Decode("truncated classic bpf instruction".into()));+ return Err(Error::Decode("truncated classic bpf instruction".into()));}let op = u16::from_le_bytes([bytes[0], bytes[1]]);let jt = bytes[2];@@ -116,103 +116,103 @@ fn classic_mnemonic(op: u16, jt: u8, jf: u8, k: u32) -> Result<(String, String)>BPF_CLASS_LDX => classic_ldx(op, k),BPF_CLASS_ST | BPF_CLASS_STX => Ok((if class(op) == BPF_CLASS_ST {- "st".into()+ "st".into()} else {- "stx".into()+ "stx".into()},- format!("M[{k}]"),+ format!("M[{k}]"),)),BPF_CLASS_ALU => {let name = match alu_op(op) {- BPF_ALU_ADD => "add",- BPF_ALU_SUB => "sub",- BPF_ALU_MUL => "mul",- BPF_ALU_DIV => "div",- BPF_ALU_OR => "or",- BPF_ALU_AND => "and",- BPF_ALU_LSH => "lsh",- BPF_ALU_RSH => "rsh",- BPF_ALU_NEG => "neg",- BPF_ALU_MOD => "mod",- BPF_ALU_XOR => "xor",- _ => return Err(Error::Decode("invalid classic bpf alu".into())),+ BPF_ALU_ADD => "add",+ BPF_ALU_SUB => "sub",+ BPF_ALU_MUL => "mul",+ BPF_ALU_DIV => "div",+ BPF_ALU_OR => "or",+ BPF_ALU_AND => "and",+ BPF_ALU_LSH => "lsh",+ BPF_ALU_RSH => "rsh",+ BPF_ALU_NEG => "neg",+ BPF_ALU_MOD => "mod",+ BPF_ALU_XOR => "xor",+ _ => return Err(Error::Decode("invalid classic bpf alu".into())),};if alu_op(op) == BPF_ALU_NEG {Ok((name.into(), String::new()))- } else if src_k(op) {- Ok((name.into(), format!("#{k:#x}")))+ } else if src_k(op) {+ Ok((name.into(), format!("#{k:#x}")))} else {- Ok((name.into(), "x".into()))+ Ok((name.into(), "x".into()))}}BPF_CLASS_JMP => {let name = match jmp_op(op) {- BPF_JUMP_JA => return Ok(("ja".into(), format!("#{k}"))),- BPF_JUMP_JEQ => "jeq",- BPF_JUMP_JGT => "jgt",- BPF_JUMP_JGE => "jge",- BPF_JUMP_JSET => "jset",- _ => return Err(Error::Decode("invalid classic bpf jump".into())),+ BPF_JUMP_JA => return Ok(("ja".into(), format!("#{k}"))),+ BPF_JUMP_JEQ => "jeq",+ BPF_JUMP_JGT => "jgt",+ BPF_JUMP_JGE => "jge",+ BPF_JUMP_JSET => "jset",+ _ => return Err(Error::Decode("invalid classic bpf jump".into())),};let rhs = if src_k(op) {- format!("#{k}")+ format!("#{k}")} else {- "x".into()+ "x".into()};- Ok((name.into(), format!("{rhs}, #{jt}, #{jf}")))+ Ok((name.into(), format!("{rhs}, #{jt}, #{jf}")))}BPF_CLASS_RET => {if op & 0x18 == BPF_SRC_K {- Ok(("ret".into(), format!("#{k}")))+ Ok(("ret".into(), format!("#{k}")))} else if op & 0x18 == BPF_SRC_X {- Ok(("ret".into(), "x".into()))+ Ok(("ret".into(), "x".into()))} else {- Ok(("ret".into(), "a".into()))+ Ok(("ret".into(), "a".into()))}}BPF_CLASS_MISC => {if op & 0xf8 == BPF_MISCOP_TAX {- Ok(("tax".into(), String::new()))+ Ok(("tax".into(), String::new()))} else if op & 0xf8 == BPF_MISCOP_TXA {- Ok(("txa".into(), String::new()))+ Ok(("txa".into(), String::new()))} else {- Err(Error::Decode("invalid classic bpf misc".into()))+ Err(Error::Decode("invalid classic bpf misc".into()))}}- _ => Err(Error::Decode("invalid classic bpf class".into())),+ _ => Err(Error::Decode("invalid classic bpf class".into())),}}fn classic_ld(op: u16, k: u32) -> Result<(String, String)> {let sz = match size(op) {- BPF_SIZE_W => "w",- BPF_SIZE_H => "h",- BPF_SIZE_B => "b",- _ => return Err(Error::Decode("invalid classic bpf ld size".into())),+ BPF_SIZE_W => "w",+ BPF_SIZE_H => "h",+ BPF_SIZE_B => "b",+ _ => return Err(Error::Decode("invalid classic bpf ld size".into())),};match mode(op) {- BPF_MODE_IMM => Ok((format!("ld{sz}"), format!("#{k:#x}"))),- BPF_MODE_LEN => Ok(("ld".into(), "len".into())),- BPF_MODE_MEM => Ok(("ld".into(), format!("M[{k}]"))),- BPF_MODE_ABS => Ok((format!("ldabs{sz}"), format!("[{k}]"))),- BPF_MODE_IND => Ok((format!("ldind{sz}"), format!("x+{k}"))),- _ => Err(Error::Decode("invalid classic bpf ld mode".into())),+ BPF_MODE_IMM => Ok((format!("ld{sz}"), format!("#{k:#x}"))),+ BPF_MODE_LEN => Ok(("ld".into(), "len".into())),+ BPF_MODE_MEM => Ok(("ld".into(), format!("M[{k}]"))),+ BPF_MODE_ABS => Ok((format!("ldabs{sz}"), format!("[{k}]"))),+ BPF_MODE_IND => Ok((format!("ldind{sz}"), format!("x+{k}"))),+ _ => Err(Error::Decode("invalid classic bpf ld mode".into())),}}fn classic_ldx(op: u16, k: u32) -> Result<(String, String)> {match mode(op) {- BPF_MODE_IMM => Ok(("ldx".into(), format!("#{k}"))),- BPF_MODE_LEN => Ok(("ldx".into(), "len".into())),- BPF_MODE_MEM => Ok(("ldx".into(), format!("M[{k}]"))),- BPF_MODE_MSH => Ok(("ldx".into(), format!("4*([{k}]&0xf)"))),- _ => Err(Error::Decode("invalid classic bpf ldx mode".into())),+ BPF_MODE_IMM => Ok(("ldx".into(), format!("#{k}"))),+ BPF_MODE_LEN => Ok(("ldx".into(), "len".into())),+ BPF_MODE_MEM => Ok(("ldx".into(), format!("M[{k}]"))),+ BPF_MODE_MSH => Ok(("ldx".into(), format!("4*([{k}]&0xf)"))),+ _ => Err(Error::Decode("invalid classic bpf ldx mode".into())),}}fn decode_ebpf(bytes: &[u8], address: u64) -> Result<Instruction> {if bytes.len() < 8 {- return Err(Error::Decode("truncated ebpf instruction".into()));+ return Err(Error::Decode("truncated ebpf instruction".into()));}let op = bytes[0];let dst = bytes[1] & 0x0f;@@ -222,7 +222,7 @@ fn decode_ebpf(bytes: &[u8], address: u64) -> Result<Instruction> {if op == EBPF_LDDW {if bytes.len() < 16 {- return Err(Error::Decode("truncated ebpf lddw".into()));+ return Err(Error::Decode("truncated ebpf lddw".into()));}let imm_lo = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);let imm_hi = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]);@@ -230,8 +230,8 @@ fn decode_ebpf(bytes: &[u8], address: u64) -> Result<Instruction> {return Ok(Instruction::with_text(address,bytes[..16].to_vec(),- "lddw",- format!("r{dst}, #{full}"),+ "lddw",+ format!("r{dst}, #{full}"),16,));}@@ -246,132 +246,111 @@ fn decode_ebpf(bytes: &[u8], address: u64) -> Result<Instruction> {))}-fn ebpf_mnemonic(- op: u8,- dst: u8,- src: u8,- off: i16,- imm: i32,-) -> Result<(String, String)> {+fn ebpf_mnemonic(op: u8, dst: u8, src: u8, off: i16, imm: i32) -> Result<(String, String)> {let cls = op & 0x07;match cls {0x00 | 0x01 => {- // LD / LDX+ // LD / LDXlet sz = match op & 0x18 {- 0x00 => "w",- 0x08 => "h",- 0x10 => "b",- 0x18 => "dw",- _ => "w",+ 0x00 => "w",+ 0x08 => "h",+ 0x10 => "b",+ 0x18 => "dw",+ _ => "w",};let m = op & 0xe0;if cls == 0x00 {- if m == 0x00 && sz == "dw" {- return Err(Error::Decode("lddw must be 16 bytes".into()));+ if m == 0x00 && sz == "dw" {+ return Err(Error::Decode("lddw must be 16 bytes".into()));}if m == 0x20 {- return Ok((format!("ldabs{sz}"), format!("[{imm}]")));+ return Ok((format!("ldabs{sz}"), format!("[{imm}]")));}if m == 0x40 {- return Ok((format!("ldind{sz}"), format!("r{src}")));+ return Ok((format!("ldind{sz}"), format!("r{src}")));}} else if m == 0x60 {- return Ok((- format!("ldx{sz}"),- format!("r{dst}, [r{src}+{off}]"),- ));+ return Ok((format!("ldx{sz}"), format!("r{dst}, [r{src}+{off}]")));}- Err(Error::Decode("invalid ebpf load".into()))+ Err(Error::Decode("invalid ebpf load".into()))}0x02 | 0x03 => {let sz = match op & 0x18 {- 0x00 => "w",- 0x08 => "h",- 0x10 => "b",- 0x18 => "dw",- _ => "w",+ 0x00 => "w",+ 0x08 => "h",+ 0x10 => "b",+ 0x18 => "dw",+ _ => "w",};if (op & 0xe0) == 0x60 {if cls == 0x02 {- Ok((- format!("st{sz}"),- format!("[r{dst}+{off}], #{imm}"),- ))+ Ok((format!("st{sz}"), format!("[r{dst}+{off}], #{imm}")))} else {- Ok((- format!("stx{sz}"),- format!("[r{dst}+{off}], r{src}"),- ))+ Ok((format!("stx{sz}"), format!("[r{dst}+{off}], r{src}")))}} else {- Err(Error::Decode("invalid ebpf store".into()))+ Err(Error::Decode("invalid ebpf store".into()))}}0x04 | EBPF_ALU64 => {let opn = match (op >> 4) & 0x0f {- 0x0 => "add",- 0x1 => "sub",- 0x2 => "mul",- 0x3 => "div",- 0x4 => "or",- 0x5 => "and",- 0x6 => "lsh",- 0x7 => "rsh",- 0x8 => "neg",- 0x9 => "mod",- 0xa => "xor",- 0xb => "mov",- 0xc => "arsh",- _ => return Err(Error::Decode("invalid ebpf alu".into())),+ 0x0 => "add",+ 0x1 => "sub",+ 0x2 => "mul",+ 0x3 => "div",+ 0x4 => "or",+ 0x5 => "and",+ 0x6 => "lsh",+ 0x7 => "rsh",+ 0x8 => "neg",+ 0x9 => "mod",+ 0xa => "xor",+ 0xb => "mov",+ 0xc => "arsh",+ _ => return Err(Error::Decode("invalid ebpf alu".into())),};- let suffix = if cls == EBPF_ALU64 { "64" } else { "" };- if opn == "neg" {- Ok((format!("{opn}{suffix}"), format!("r{dst}")))+ let suffix = if cls == EBPF_ALU64 { "64" } else { "" };+ if opn == "neg" {+ Ok((format!("{opn}{suffix}"), format!("r{dst}")))} else if op & 0x08 == 0 {- Ok((format!("{opn}{suffix}"), format!("r{dst}, #{imm}")))+ Ok((format!("{opn}{suffix}"), format!("r{dst}, #{imm}")))} else {- Ok((format!("{opn}{suffix}"), format!("r{dst}, r{src}")))+ Ok((format!("{opn}{suffix}"), format!("r{dst}, r{src}")))}}0x05 | EBPF_JMP32 => {let opn = match (op >> 4) & 0x0f {- 0x0 => "ja",- 0x1 => "jeq",- 0x2 => "jgt",- 0x3 => "jge",- 0x4 => "jset",- 0x5 => "jne",- 0x6 => "jsgt",- 0x7 => "jsge",- 0x8 => "call",- 0x9 => "exit",- 0xa => "jlt",- 0xb => "jle",- 0xc => "jslt",- 0xd => "jsle",- _ => return Err(Error::Decode("invalid ebpf jump".into())),+ 0x0 => "ja",+ 0x1 => "jeq",+ 0x2 => "jgt",+ 0x3 => "jge",+ 0x4 => "jset",+ 0x5 => "jne",+ 0x6 => "jsgt",+ 0x7 => "jsge",+ 0x8 => "call",+ 0x9 => "exit",+ 0xa => "jlt",+ 0xb => "jle",+ 0xc => "jslt",+ 0xd => "jsle",+ _ => return Err(Error::Decode("invalid ebpf jump".into())),};match opn {- "ja" => Ok((opn.into(), format!("{off}"))),- "call" => Ok((opn.into(), format!("#{imm}"))),- "exit" => Ok((opn.into(), String::new())),+ "ja" => Ok((opn.into(), format!("{off}"))),+ "call" => Ok((opn.into(), format!("#{imm}"))),+ "exit" => Ok((opn.into(), String::new())),_ => {- let suffix = if cls == EBPF_JMP32 { "32" } else { "" };+ let suffix = if cls == EBPF_JMP32 { "32" } else { "" };if op & 0x08 == 0 {- Ok((- format!("{opn}{suffix}"),- format!("r{dst}, #{imm}, {off}"),- ))+ Ok((format!("{opn}{suffix}"), format!("r{dst}, #{imm}, {off}")))} else {- Ok((- format!("{opn}{suffix}"),- format!("r{dst}, r{src}, {off}"),- ))+ Ok((format!("{opn}{suffix}"), format!("r{dst}, r{src}, {off}")))}}}}- _ => Err(Error::Decode("invalid ebpf class".into())),+ _ => Err(Error::Decode("invalid ebpf class".into())),}}@@ -382,7 +361,7 @@ impl ArchDecode for BpfDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Bpf) {- return Err(Error::Mode(format!("invalid bpf mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!("invalid bpf mode {:#x}", mode.bits())));}Ok(Self { mode })}@@ -401,13 +380,13 @@ impl ArchDecode for BpfDecoder {}fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {- if mnemonic.starts_with("ld") || mnemonic.starts_with("ldx") {+ if mnemonic.starts_with("ld") || mnemonic.starts_with("ldx") {vec![GroupId::Arch(1)]- } else if mnemonic.starts_with("st") {+ } else if mnemonic.starts_with("st") {vec![GroupId::Arch(2)]- } else if mnemonic.starts_with('j') || mnemonic == "call" || mnemonic == "exit" {+ } else if mnemonic.starts_with('j') || mnemonic == "call" || mnemonic == "exit" {vec![GroupId::Jump]- } else if mnemonic == "ret" {+ } else if mnemonic == "ret" {vec![GroupId::Ret]} else {vec![GroupId::Arch(3)] // alu@@ -416,41 +395,41 @@ fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("lddw"),- 2 => Some("add"),- 3 => Some("add64"),- 4 => Some("call"),- 5 => Some("exit"),- 6 => Some("ja"),- 7 => Some("ret"),- 8 => Some("tax"),+ 1 => Some("lddw"),+ 2 => Some("add"),+ 3 => Some("add64"),+ 4 => Some("call"),+ 5 => Some("exit"),+ 6 => Some("ja"),+ 7 => Some("ret"),+ 8 => Some("tax"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Ret => Some("ret"),- GroupId::Arch(1) => Some("load"),- GroupId::Arch(2) => Some("store"),- GroupId::Arch(3) => Some("alu"),+ GroupId::Jump => Some("jump"),+ GroupId::Ret => Some("ret"),+ GroupId::Arch(1) => Some("load"),+ GroupId::Arch(2) => Some("store"),+ GroupId::Arch(3) => Some("alu"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "lddw" => 1,- "add" => 2,- "add64" => 3,- "call" => 4,- "exit" => 5,- "ja" => 6,- "ret" => 7,- "tax" => 8,- m if m.starts_with("add") => 2,- m if m.starts_with("j") => 6,+ "lddw" => 1,+ "add" => 2,+ "add64" => 3,+ "call" => 4,+ "exit" => 5,+ "ja" => 6,+ "ret" => 7,+ "tax" => 8,+ m if m.starts_with("add") => 2,+ m if m.starts_with("j") => 6,_ => 0,};InsnId(id)@@ -464,31 +443,35 @@ mod tests {#[test]fn classic_bpf_ret_k() {let dec = BpfDecoder::open(Mode::LITTLE_ENDIAN).unwrap();- // ret #0x0+ // ret #0x0let bytes = [0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];- let insn = dec.decode_one(&bytes, 0, &EngineOptions::default()).unwrap();- assert_eq!(insn.mnemonic, "ret");+ let insn = dec+ .decode_one(&bytes, 0, &EngineOptions::default())+ .unwrap();+ assert_eq!(insn.mnemonic, "ret");assert_eq!(insn.length, 8);}#[test]fn classic_bpf_ld_imm() {let dec = BpfDecoder::open(Mode::LITTLE_ENDIAN).unwrap();- // ld #0x12345678 (BPF_LD|BPF_W|BPF_IMM)+ // ld #0x12345678 (BPF_LD|BPF_W|BPF_IMM)let bytes = [0x00, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12];- let insn = dec.decode_one(&bytes, 0, &EngineOptions::default()).unwrap();- assert_eq!(insn.mnemonic, "ldw");- assert!(insn.operands.contains("0x12345678"));+ let insn = dec+ .decode_one(&bytes, 0, &EngineOptions::default())+ .unwrap();+ assert_eq!(insn.mnemonic, "ldw");+ assert!(insn.operands.contains("0x12345678"));}#[test]fn ebpf_add64_and_lddw() {let dec = BpfDecoder::open(Mode::BPF_EXTENDED).unwrap();- // add64 r1, #1 => op=0x07|0x04=0x47? ALU64|ADD|K = 0x07 | (0<<4) | 0 = 0x07 with imm- // bpf: 07 11 00 00 01 00 00 00 (add64 r1, 1)+ // add64 r1, #1 => op=0x07|0x04=0x47? ALU64|ADD|K = 0x07 | (0<<4) | 0 = 0x07 with imm+ // bpf: 07 11 00 00 01 00 00 00 (add64 r1, 1)let add = [0x07, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00];let insn = dec.decode_one(&add, 0, &EngineOptions::default()).unwrap();- assert_eq!(insn.mnemonic, "add64");+ assert_eq!(insn.mnemonic, "add64");assert_eq!(insn.length, 8);let mut lddw = [0u8; 16];@@ -497,7 +480,7 @@ mod tests {lddw[4..8].copy_from_slice(&0x00112233u32.to_le_bytes());lddw[12..16].copy_from_slice(&0x44556677u32.to_le_bytes());let wide = dec.decode_one(&lddw, 0, &EngineOptions::default()).unwrap();- assert_eq!(wide.mnemonic, "lddw");+ assert_eq!(wide.mnemonic, "lddw");assert_eq!(wide.length, 16);}}diff --git a/crates/ghidrust-decode/src/arch/bpf/regs.rs b/crates/ghidrust-decode/src/arch/bpf/regs.rsindex 9fa0e33..33144a9 100644--- a/crates/ghidrust-decode/src/arch/bpf/regs.rs+++ b/crates/ghidrust-decode/src/arch/bpf/regs.rs@@ -2,21 +2,21 @@ use crate::reg::RegId;pub fn reg_name(reg: RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("a"),+ 0 => Some("a"),1..=10 => Some(match reg.index() {- 1 => "r0",- 2 => "r1",- 3 => "r2",- 4 => "r3",- 5 => "r4",- 6 => "r5",- 7 => "r6",- 8 => "r7",- 9 => "r8",- 10 => "r9",- _ => "r10",+ 1 => "r0",+ 2 => "r1",+ 3 => "r2",+ 4 => "r3",+ 5 => "r4",+ 6 => "r5",+ 7 => "r6",+ 8 => "r7",+ 9 => "r8",+ 10 => "r9",+ _ => "r10",}),- 11 => Some("x"),+ 11 => Some("x"),_ => None,}}diff --git a/crates/ghidrust-decode/src/arch/evm/mod.rs b/crates/ghidrust-decode/src/arch/evm/mod.rsindex eb590c4..dad31a7 100644--- a/crates/ghidrust-decode/src/arch/evm/mod.rs+++ b/crates/ghidrust-decode/src/arch/evm/mod.rs@@ -13,160 +13,160 @@ pub struct EvmDecoder {}const OPCODE_MNEMONIC: [&str; 256] = {- let mut table = ["invalid"; 256];- table[0x00] = "stop";- table[0x01] = "add";- table[0x02] = "mul";- table[0x03] = "sub";- table[0x04] = "div";- table[0x05] = "sdiv";- table[0x06] = "mod";- table[0x07] = "smod";- table[0x08] = "addmod";- table[0x09] = "mulmod";- table[0x0a] = "exp";- table[0x0b] = "signextend";- table[0x10] = "lt";- table[0x11] = "gt";- table[0x12] = "slt";- table[0x13] = "sgt";- table[0x14] = "eq";- table[0x15] = "iszero";- table[0x16] = "and";- table[0x17] = "or";- table[0x18] = "xor";- table[0x19] = "not";- table[0x1a] = "byte";- table[0x1b] = "shl";- table[0x1c] = "shr";- table[0x1d] = "sar";- table[0x20] = "sha3";- table[0x30] = "address";- table[0x31] = "balance";- table[0x32] = "origin";- table[0x33] = "caller";- table[0x34] = "callvalue";- table[0x35] = "calldataload";- table[0x36] = "calldatasize";- table[0x37] = "calldatacopy";- table[0x38] = "codesize";- table[0x39] = "codecopy";- table[0x3a] = "gasprice";- table[0x3b] = "extcodesize";- table[0x3c] = "extcodecopy";- table[0x3d] = "returndatasize";- table[0x3e] = "returndatacopy";- table[0x40] = "blockhash";- table[0x41] = "coinbase";- table[0x42] = "timestamp";- table[0x43] = "number";- table[0x44] = "difficulty";- table[0x45] = "gaslimit";- table[0x46] = "chainid";- table[0x47] = "selfbalance";- table[0x48] = "basefee";- table[0x49] = "blobhash";- table[0x4a] = "blobbasefee";- table[0x50] = "pop";- table[0x51] = "mload";- table[0x52] = "mstore";- table[0x53] = "mstore8";- table[0x54] = "sload";- table[0x55] = "sstore";- table[0x56] = "jump";- table[0x57] = "jumpi";- table[0x58] = "pc";- table[0x59] = "msize";- table[0x5a] = "gas";- table[0x5b] = "jumpdest";- table[0x5c] = "tload";- table[0x5d] = "tstore";- table[0x5e] = "mcopy";- table[0x5f] = "push0";+ let mut table = ["invalid"; 256];+ table[0x00] = "stop";+ table[0x01] = "add";+ table[0x02] = "mul";+ table[0x03] = "sub";+ table[0x04] = "div";+ table[0x05] = "sdiv";+ table[0x06] = "mod";+ table[0x07] = "smod";+ table[0x08] = "addmod";+ table[0x09] = "mulmod";+ table[0x0a] = "exp";+ table[0x0b] = "signextend";+ table[0x10] = "lt";+ table[0x11] = "gt";+ table[0x12] = "slt";+ table[0x13] = "sgt";+ table[0x14] = "eq";+ table[0x15] = "iszero";+ table[0x16] = "and";+ table[0x17] = "or";+ table[0x18] = "xor";+ table[0x19] = "not";+ table[0x1a] = "byte";+ table[0x1b] = "shl";+ table[0x1c] = "shr";+ table[0x1d] = "sar";+ table[0x20] = "sha3";+ table[0x30] = "address";+ table[0x31] = "balance";+ table[0x32] = "origin";+ table[0x33] = "caller";+ table[0x34] = "callvalue";+ table[0x35] = "calldataload";+ table[0x36] = "calldatasize";+ table[0x37] = "calldatacopy";+ table[0x38] = "codesize";+ table[0x39] = "codecopy";+ table[0x3a] = "gasprice";+ table[0x3b] = "extcodesize";+ table[0x3c] = "extcodecopy";+ table[0x3d] = "returndatasize";+ table[0x3e] = "returndatacopy";+ table[0x40] = "blockhash";+ table[0x41] = "coinbase";+ table[0x42] = "timestamp";+ table[0x43] = "number";+ table[0x44] = "difficulty";+ table[0x45] = "gaslimit";+ table[0x46] = "chainid";+ table[0x47] = "selfbalance";+ table[0x48] = "basefee";+ table[0x49] = "blobhash";+ table[0x4a] = "blobbasefee";+ table[0x50] = "pop";+ table[0x51] = "mload";+ table[0x52] = "mstore";+ table[0x53] = "mstore8";+ table[0x54] = "sload";+ table[0x55] = "sstore";+ table[0x56] = "jump";+ table[0x57] = "jumpi";+ table[0x58] = "pc";+ table[0x59] = "msize";+ table[0x5a] = "gas";+ table[0x5b] = "jumpdest";+ table[0x5c] = "tload";+ table[0x5d] = "tstore";+ table[0x5e] = "mcopy";+ table[0x5f] = "push0";let mut op = 0x60u8;while op <= 0x7f {table[op as usize] = match op - 0x60 + 1 {- 1 => "push1",- 2 => "push2",- 3 => "push3",- 4 => "push4",- 5 => "push5",- 6 => "push6",- 7 => "push7",- 8 => "push8",- 9 => "push9",- 10 => "push10",- 11 => "push11",- 12 => "push12",- 13 => "push13",- 14 => "push14",- 15 => "push15",- 16 => "push16",- 17 => "push17",- 18 => "push18",- 19 => "push19",- 20 => "push20",- 21 => "push21",- 22 => "push22",- 23 => "push23",- 24 => "push24",- 25 => "push25",- 26 => "push26",- 27 => "push27",- 28 => "push28",- 29 => "push29",- 30 => "push30",- 31 => "push31",- _ => "push32",+ 1 => "push1",+ 2 => "push2",+ 3 => "push3",+ 4 => "push4",+ 5 => "push5",+ 6 => "push6",+ 7 => "push7",+ 8 => "push8",+ 9 => "push9",+ 10 => "push10",+ 11 => "push11",+ 12 => "push12",+ 13 => "push13",+ 14 => "push14",+ 15 => "push15",+ 16 => "push16",+ 17 => "push17",+ 18 => "push18",+ 19 => "push19",+ 20 => "push20",+ 21 => "push21",+ 22 => "push22",+ 23 => "push23",+ 24 => "push24",+ 25 => "push25",+ 26 => "push26",+ 27 => "push27",+ 28 => "push28",+ 29 => "push29",+ 30 => "push30",+ 31 => "push31",+ _ => "push32",};op += 1;}- table[0x80] = "dup1";- table[0x81] = "dup2";- table[0x82] = "dup3";- table[0x83] = "dup4";- table[0x84] = "dup5";- table[0x85] = "dup6";- table[0x86] = "dup7";- table[0x87] = "dup8";- table[0x88] = "dup9";- table[0x89] = "dup10";- table[0x8a] = "dup11";- table[0x8b] = "dup12";- table[0x8c] = "dup13";- table[0x8d] = "dup14";- table[0x8e] = "dup15";- table[0x8f] = "dup16";- table[0x90] = "swap1";- table[0x91] = "swap2";- table[0x92] = "swap3";- table[0x93] = "swap4";- table[0x94] = "swap5";- table[0x95] = "swap6";- table[0x96] = "swap7";- table[0x97] = "swap8";- table[0x98] = "swap9";- table[0x99] = "swap10";- table[0x9a] = "swap11";- table[0x9b] = "swap12";- table[0x9c] = "swap13";- table[0x9d] = "swap14";- table[0x9e] = "swap15";- table[0x9f] = "swap16";- table[0xa0] = "log0";- table[0xa1] = "log1";- table[0xa2] = "log2";- table[0xa3] = "log3";- table[0xa4] = "log4";- table[0xf0] = "create";- table[0xf1] = "call";- table[0xf2] = "callcode";- table[0xf3] = "return";- table[0xf4] = "delegatecall";- table[0xf5] = "create2";- table[0xfa] = "staticcall";- table[0xfd] = "revert";- table[0xff] = "selfdestruct";+ table[0x80] = "dup1";+ table[0x81] = "dup2";+ table[0x82] = "dup3";+ table[0x83] = "dup4";+ table[0x84] = "dup5";+ table[0x85] = "dup6";+ table[0x86] = "dup7";+ table[0x87] = "dup8";+ table[0x88] = "dup9";+ table[0x89] = "dup10";+ table[0x8a] = "dup11";+ table[0x8b] = "dup12";+ table[0x8c] = "dup13";+ table[0x8d] = "dup14";+ table[0x8e] = "dup15";+ table[0x8f] = "dup16";+ table[0x90] = "swap1";+ table[0x91] = "swap2";+ table[0x92] = "swap3";+ table[0x93] = "swap4";+ table[0x94] = "swap5";+ table[0x95] = "swap6";+ table[0x96] = "swap7";+ table[0x97] = "swap8";+ table[0x98] = "swap9";+ table[0x99] = "swap10";+ table[0x9a] = "swap11";+ table[0x9b] = "swap12";+ table[0x9c] = "swap13";+ table[0x9d] = "swap14";+ table[0x9e] = "swap15";+ table[0x9f] = "swap16";+ table[0xa0] = "log0";+ table[0xa1] = "log1";+ table[0xa2] = "log2";+ table[0xa3] = "log3";+ table[0xa4] = "log4";+ table[0xf0] = "create";+ table[0xf1] = "call";+ table[0xf2] = "callcode";+ table[0xf3] = "return";+ table[0xf4] = "delegatecall";+ table[0xf5] = "create2";+ table[0xfa] = "staticcall";+ table[0xfd] = "revert";+ table[0xff] = "selfdestruct";table};@@ -175,24 +175,24 @@ const PUSH32: u8 = 0x7f;pub(crate) fn decode_raw(bytes: &[u8], address: u64) -> Result<Instruction> {if bytes.is_empty() {- return Err(Error::Decode("empty input".into()));+ return Err(Error::Decode("empty input".into()));}let opcode = bytes[0];let mnemonic = OPCODE_MNEMONIC[opcode as usize];let (length, operands) = if opcode >= PUSH1 && opcode <= PUSH32 {let imm_len = (opcode - PUSH1 + 1) as usize;if bytes.len() < 1 + imm_len {- return Err(Error::Decode("truncated push immediate".into()));+ return Err(Error::Decode("truncated push immediate".into()));}let imm_bytes = &bytes[1..=imm_len];let hex = imm_bytes.iter().rev()- .map(|b| format!("{b:02x}"))+ .map(|b| format!("{b:02x}")).collect::<String>();- let imm_display = format!("0x{hex}");+ let imm_display = format!("0x{hex}");(1 + imm_len as u8, imm_display)- } else if mnemonic == "invalid" {+ } else if mnemonic == "invalid" {(1, String::new())} else {(1, String::new())@@ -213,7 +213,7 @@ impl ArchDecode for EvmDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Evm) {- return Err(Error::Mode(format!("invalid evm mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!("invalid evm mode {:#x}", mode.bits())));}Ok(Self { _mode: mode })}@@ -233,23 +233,23 @@ impl ArchDecode for EvmDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "jump" | "jumpi" => vec![GroupId::Jump],- "call" | "callcode" | "delegatecall" | "staticcall" => vec![GroupId::Call],- "return" | "revert" => vec![GroupId::Ret],- "stop" | "selfdestruct" => vec![GroupId::Arch(8)], // halt- m if m.starts_with("push") => vec![GroupId::Arch(6)], // stack_write- "pop" | "dup1" | "dup2" | "dup3" | "dup4" | "dup5" | "dup6" | "dup7" | "dup8"- | "dup9" | "dup10" | "dup11" | "dup12" | "dup13" | "dup14" | "dup15" | "dup16" => {+ "jump" | "jumpi" => vec![GroupId::Jump],+ "call" | "callcode" | "delegatecall" | "staticcall" => vec![GroupId::Call],+ "return" | "revert" => vec![GroupId::Ret],+ "stop" | "selfdestruct" => vec![GroupId::Arch(8)], // halt+ m if m.starts_with("push") => vec![GroupId::Arch(6)], // stack_write+ "pop" | "dup1" | "dup2" | "dup3" | "dup4" | "dup5" | "dup6" | "dup7" | "dup8" | "dup9"+ | "dup10" | "dup11" | "dup12" | "dup13" | "dup14" | "dup15" | "dup16" => {vec![GroupId::Arch(5)] // stack_read}- "mstore" | "mstore8" | "calldatacopy" | "codecopy" | "extcodecopy" | "mcopy" => {+ "mstore" | "mstore8" | "calldatacopy" | "codecopy" | "extcodecopy" | "mcopy" => {vec![GroupId::Arch(7)] // mem_write}- "mload" | "create" | "create2" => vec![GroupId::Arch(4)], // mem_read- "sstore" | "tstore" => vec![GroupId::Arch(9)], // store_write- "sload" | "tload" => vec![GroupId::Arch(10)], // store_read- "add" | "mul" | "sub" | "div" | "sdiv" | "mod" | "smod" | "addmod" | "mulmod" | "exp"- | "signextend" | "shl" | "shr" | "sar" => vec![GroupId::Arch(3)], // math+ "mload" | "create" | "create2" => vec![GroupId::Arch(4)], // mem_read+ "sstore" | "tstore" => vec![GroupId::Arch(9)], // store_write+ "sload" | "tload" => vec![GroupId::Arch(10)], // store_read+ "add" | "mul" | "sub" | "div" | "sdiv" | "mod" | "smod" | "addmod" | "mulmod" | "exp"+ | "signextend" | "shl" | "shr" | "sar" => vec![GroupId::Arch(3)], // math_ => Vec::new(),}}@@ -269,17 +269,17 @@ pub fn insn_name(id: InsnId) -> Option<&'static str> {pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Ret => Some("ret"),- GroupId::Arch(3) => Some("math"),- GroupId::Arch(4) => Some("mem_read"),- GroupId::Arch(5) => Some("stack_read"),- GroupId::Arch(6) => Some("stack_write"),- GroupId::Arch(7) => Some("mem_write"),- GroupId::Arch(8) => Some("halt"),- GroupId::Arch(9) => Some("store_write"),- GroupId::Arch(10) => Some("store_read"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Ret => Some("ret"),+ GroupId::Arch(3) => Some("math"),+ GroupId::Arch(4) => Some("mem_read"),+ GroupId::Arch(5) => Some("stack_read"),+ GroupId::Arch(6) => Some("stack_write"),+ GroupId::Arch(7) => Some("mem_write"),+ GroupId::Arch(8) => Some("halt"),+ GroupId::Arch(9) => Some("store_write"),+ GroupId::Arch(10) => Some("store_read"),_ => None,}}@@ -304,15 +304,15 @@ mod tests {let stop = dec.decode_one(&[0x00], 0, &EngineOptions::default()).unwrap();- assert_eq!(stop.mnemonic, "stop");+ assert_eq!(stop.mnemonic, "stop");assert_eq!(stop.length, 1);let push = dec.decode_one(&[0x60, 0x2a], 0x10, &EngineOptions::default()).unwrap();- assert_eq!(push.mnemonic, "push1");+ assert_eq!(push.mnemonic, "push1");assert_eq!(push.length, 2);- assert_eq!(push.operands, "0x2a");+ assert_eq!(push.operands, "0x2a");}#[test]@@ -321,12 +321,12 @@ mod tests {let call = dec.decode_one(&[0xf1], 0, &EngineOptions::default()).unwrap();- assert_eq!(call.mnemonic, "call");+ assert_eq!(call.mnemonic, "call");let bad = dec.decode_one(&[0x0c], 0, &EngineOptions::default()).unwrap();- assert_eq!(bad.mnemonic, "invalid");+ assert_eq!(bad.mnemonic, "invalid");}#[test]@@ -334,8 +334,10 @@ mod tests {let dec = EvmDecoder::open(Mode::LITTLE_ENDIAN).unwrap();let mut bytes = vec![0x7f];bytes.extend(std::iter::repeat_n(0xab_u8, 32));- let insn = dec.decode_one(&bytes, 0, &EngineOptions::default()).unwrap();- assert_eq!(insn.mnemonic, "push32");+ let insn = dec+ .decode_one(&bytes, 0, &EngineOptions::default())+ .unwrap();+ assert_eq!(insn.mnemonic, "push32");assert_eq!(insn.length, 33);}}diff --git a/crates/ghidrust-decode/src/arch/hppa/decode.rs b/crates/ghidrust-decode/src/arch/hppa/decode.rsindex 6c32449..a8ce241 100644--- a/crates/ghidrust-decode/src/arch/hppa/decode.rs+++ b/crates/ghidrust-decode/src/arch/hppa/decode.rs@@ -2,21 +2,21 @@ use crate::error::{Error, Result};pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("r0"),- 1 => Some("r1"),- 26 => Some("rp"),- 31 => Some("sp"),+ 0 => Some("r0"),+ 1 => Some("r1"),+ 26 => Some("rp"),+ 31 => Some("sp"),_ => None,}}fn r(n: u32) -> String {- format!("r{n}")+ format!("r{n}")}pub fn decode(bytes: &[u8], big_endian: bool) -> Result<(String, String, usize)> {if bytes.len() < 4 {- return Err(Error::Decode("truncated hppa instruction".into()));+ return Err(Error::Decode("truncated hppa instruction".into()));}let word = if big_endian {u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])@@ -26,15 +26,15 @@ pub fn decode(bytes: &[u8], big_endian: bool) -> Result<(String, String, usize)>let op = (word >> 26) & 0x3f;match op {0x0d => decode_ldo(word),- 0x08 => decode_mem(word, "ldw"),- 0x09 => decode_mem(word, "stw"),- 0x02 => decode_arith(word, "add"),- 0x03 => decode_arith(word, "sub"),- 0x3a => decode_branch(word, "bl"),- 0x38 => decode_branch(word, "be"),- 0x39 => decode_branch(word, "bv"),+ 0x08 => decode_mem(word, "ldw"),+ 0x09 => decode_mem(word, "stw"),+ 0x02 => decode_arith(word, "add"),+ 0x03 => decode_arith(word, "sub"),+ 0x3a => decode_branch(word, "bl"),+ 0x38 => decode_branch(word, "be"),+ 0x39 => decode_branch(word, "bv"),0x3c => decode_comb(word),- _ => Err(Error::Decode("unsupported hppa opcode".into())),+ _ => Err(Error::Decode("unsupported hppa opcode".into())),}}@@ -42,29 +42,17 @@ fn decode_ldo(word: u32) -> Result<(String, String, usize)> {let dst = (word >> 21) & 0x1f;let base = (word >> 16) & 0x1f;let imm = sign_ext((word >> 0) & 0x1fff, 13);- Ok((- "ldo".into(),- format!("{imm}({}), {}", r(base), r(dst)),- 4,- ))+ Ok(("ldo".into(), format!("{imm}({}), {}", r(base), r(dst)), 4))}fn decode_mem(word: u32, name: &str) -> Result<(String, String, usize)> {let dst = (word >> 21) & 0x1f;let base = (word >> 16) & 0x1f;let off = sign_ext((word >> 0) & 0x1fff, 13);- if name == "ldw" {- Ok((- name.into(),- format!("{off}({}), {}", r(base), r(dst)),- 4,- ))+ if name == "ldw" {+ Ok((name.into(), format!("{off}({}), {}", r(base), r(dst)), 4))} else {- Ok((- name.into(),- format!("{}, {off}({})", r(dst), r(base)),- 4,- ))+ Ok((name.into(), format!("{}, {off}({})", r(dst), r(base)), 4))}}@@ -74,14 +62,14 @@ fn decode_arith(word: u32, name: &str) -> Result<(String, String, usize)> {let src2 = (word >> 0) & 0x1f;Ok((name.into(),- format!("{}, {}, {}", r(dst), r(src1), r(src2)),+ format!("{}, {}, {}", r(dst), r(src1), r(src2)),4,))}fn decode_branch(word: u32, name: &str) -> Result<(String, String, usize)> {let disp = sign_ext((word >> 0) & 0x1fffff, 21);- Ok((name.into(), format!("{disp}"), 4))+ Ok((name.into(), format!("{disp}"), 4))}fn decode_comb(word: u32) -> Result<(String, String, usize)> {@@ -90,8 +78,8 @@ fn decode_comb(word: u32) -> Result<(String, String, usize)> {let src2 = (word >> 0) & 0x1f;let disp = sign_ext((word >> 0) & 0xfff, 12);Ok((- "comb".into(),- format!("{cond}, {}, {}, {disp}", r(src1), r(src2)),+ "comb".into(),+ format!("{cond}, {}, {}, {disp}", r(src1), r(src2)),4,))}@@ -107,10 +95,10 @@ mod tests {#[test]fn hppa_ldo() {- // ldo 8(r1), r2 => op=0x0d+ // ldo 8(r1), r2 => op=0x0dlet word = (0x0du32 << 26) | (2 << 21) | (1 << 16) | 8;let (m, _, l) = decode(&word.to_be_bytes(), true).unwrap();- assert_eq!(m, "ldo");+ assert_eq!(m, "ldo");assert_eq!(l, 4);}}diff --git a/crates/ghidrust-decode/src/arch/hppa/mod.rs b/crates/ghidrust-decode/src/arch/hppa/mod.rsindex 9632ee4..9cd1937 100644--- a/crates/ghidrust-decode/src/arch/hppa/mod.rs+++ b/crates/ghidrust-decode/src/arch/hppa/mod.rs@@ -21,7 +21,7 @@ impl ArchDecode for HppaDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Hppa) {- return Err(Error::Mode(format!("invalid hppa mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!("invalid hppa mode {:#x}", mode.bits())));}let big_endian = !mode.intersects(Mode::LITTLE_ENDIAN) || mode.contains(Mode::BIG_ENDIAN);Ok(Self { big_endian })@@ -49,45 +49,45 @@ impl ArchDecode for HppaDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "bl" => vec![GroupId::Call],- "be" | "bv" | "comb" => vec![GroupId::Jump],- "ldw" | "ldo" => vec![GroupId::Arch(1)],- "stw" => vec![GroupId::Arch(2)],- "add" | "sub" => vec![GroupId::Arch(3)],+ "bl" => vec![GroupId::Call],+ "be" | "bv" | "comb" => vec![GroupId::Jump],+ "ldw" | "ldo" => vec![GroupId::Arch(1)],+ "stw" => vec![GroupId::Arch(2)],+ "add" | "sub" => vec![GroupId::Arch(3)],_ => Vec::new(),}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("ldo"),- 2 => Some("ldw"),- 3 => Some("add"),- 4 => Some("bl"),- 5 => Some("comb"),+ 1 => Some("ldo"),+ 2 => Some("ldw"),+ 3 => Some("add"),+ 4 => Some("bl"),+ 5 => Some("comb"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Arch(1) => Some("load"),- GroupId::Arch(2) => Some("store"),- GroupId::Arch(3) => Some("alu"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Arch(1) => Some("load"),+ GroupId::Arch(2) => Some("store"),+ GroupId::Arch(3) => Some("alu"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "ldo" => 1,- "ldw" => 2,- "add" | "sub" => 3,- "bl" => 4,- "comb" | "be" | "bv" => 5,- "stw" => 2,+ "ldo" => 1,+ "ldw" => 2,+ "add" | "sub" => 3,+ "bl" => 4,+ "comb" | "be" | "bv" => 5,+ "stw" => 2,_ => 0,};InsnId(id)@@ -103,10 +103,10 @@ mod tests {let mut eng = Engine::open(Arch::Hppa, Mode::BIG_ENDIAN).unwrap();let ldo = (0x0du32 << 26) | (2 << 21) | (1 << 16) | 8;let insn = eng.disasm_one(&ldo.to_be_bytes(), 0).unwrap();- assert_eq!(insn.mnemonic, "ldo");+ assert_eq!(insn.mnemonic, "ldo");let add = (0x02u32 << 26) | (3 << 21) | (1 << 16) | 2;let addi = eng.disasm_one(&add.to_be_bytes(), 0).unwrap();- assert_eq!(addi.mnemonic, "add");+ assert_eq!(addi.mnemonic, "add");}#[test]@@ -114,9 +114,9 @@ mod tests {let mut eng = Engine::open(Arch::Hppa, Mode::BIG_ENDIAN).unwrap();let bl = (0x3au32 << 26) | 4;let insn = eng.disasm_one(&bl.to_be_bytes(), 0).unwrap();- assert_eq!(insn.mnemonic, "bl");+ assert_eq!(insn.mnemonic, "bl");let ldw = (0x08u32 << 26) | (4 << 21) | (1 << 16) | 0;let ld = eng.disasm_one(&ldw.to_be_bytes(), 0).unwrap();- assert_eq!(ld.mnemonic, "ldw");+ assert_eq!(ld.mnemonic, "ldw");}}diff --git a/crates/ghidrust-decode/src/arch/leb128.rs b/crates/ghidrust-decode/src/arch/leb128.rsindex 8a134dd..a0ac3b2 100644--- a/crates/ghidrust-decode/src/arch/leb128.rs+++ b/crates/ghidrust-decode/src/arch/leb128.rs@@ -4,28 +4,28 @@ pub fn read_u32(bytes: &[u8]) -> Result<(u32, usize)> {let mut data = 0u32;for (i, &b) in bytes.iter().enumerate() {if i > 4 || (i == 4 && b & 0x7f > 0x0f) {- return Err(Error::Decode("invalid leb128 u32".into()));+ return Err(Error::Decode("invalid leb128 u32".into()));}data |= u32::from(b & 0x7f) << (i * 7);if b & 0x80 == 0 {return Ok((data, i + 1));}}- Err(Error::Decode("truncated leb128 u32".into()))+ Err(Error::Decode("truncated leb128 u32".into()))}pub fn read_u64(bytes: &[u8]) -> Result<(u64, usize)> {let mut data = 0u64;for (i, &b) in bytes.iter().enumerate() {if i > 9 || (i == 9 && b & 0x7f > 0x01) {- return Err(Error::Decode("invalid leb128 u64".into()));+ return Err(Error::Decode("invalid leb128 u64".into()));}data |= u64::from(b & 0x7f) << (i * 7);if b & 0x80 == 0 {return Ok((data, i + 1));}}- Err(Error::Decode("truncated leb128 u64".into()))+ Err(Error::Decode("truncated leb128 u64".into()))}pub fn read_i32(bytes: &[u8]) -> Result<(i32, usize)> {@@ -52,7 +52,7 @@ pub fn read_i64(bytes: &[u8]) -> Result<(i64, usize)> {pub fn read_i7(bytes: &[u8]) -> Result<(i8, usize)> {if bytes.is_empty() {- return Err(Error::Decode("truncated block type".into()));+ return Err(Error::Decode("truncated block type".into()));}if bytes[0] == 0x40 {return Ok((0, 1));diff --git a/crates/ghidrust-decode/src/arch/loongarch/decode.rs b/crates/ghidrust-decode/src/arch/loongarch/decode.rsindex 22fdcdc..29d24dc 100644--- a/crates/ghidrust-decode/src/arch/loongarch/decode.rs+++ b/crates/ghidrust-decode/src/arch/loongarch/decode.rs@@ -2,21 +2,21 @@ use crate::error::{Error, Result};pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("r0"),- 1 => Some("r1"),- 4 => Some("r4"),- 5 => Some("r5"),+ 0 => Some("r0"),+ 1 => Some("r1"),+ 4 => Some("r4"),+ 5 => Some("r5"),_ => None,}}fn r(n: u32) -> String {- format!("r{n}")+ format!("r{n}")}pub fn decode(bytes: &[u8], little_endian: bool, is64: bool) -> Result<(String, String, usize)> {if bytes.len() < 4 {- return Err(Error::Decode("truncated loongarch instruction".into()));+ return Err(Error::Decode("truncated loongarch instruction".into()));}let word = if little_endian {u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])@@ -26,19 +26,23 @@ pub fn decode(bytes: &[u8], little_endian: bool, is64: bool) -> Result<(String,let opcode = word >> 26;match opcode {0x00 => decode_addi(word, is64),- 0x01 => decode_ldst(word, "ld", is64),- 0x02 => decode_ldst(word, "st", is64),- 0x14 => decode_branch(word, "b"),- 0x15 => decode_branch(word, "bl"),+ 0x01 => decode_ldst(word, "ld", is64),+ 0x02 => decode_ldst(word, "st", is64),+ 0x14 => decode_branch(word, "b"),+ 0x15 => decode_branch(word, "bl"),0x13 => decode_jirl(word),- 0x10 => decode_alu3(word, "add", is64),- 0x11 => decode_alu3(word, "sub", is64),- _ => Err(Error::Decode("unsupported loongarch opcode".into())),+ 0x10 => decode_alu3(word, "add", is64),+ 0x11 => decode_alu3(word, "sub", is64),+ _ => Err(Error::Decode("unsupported loongarch opcode".into())),}}fn suffix(is64: bool) -> &'static str {- if is64 { ".d" } else { ".w" }+ if is64 {+ ".d"+ } else {+ ".w"+ }}fn decode_addi(word: u32, is64: bool) -> Result<(String, String, usize)> {@@ -46,8 +50,8 @@ fn decode_addi(word: u32, is64: bool) -> Result<(String, String, usize)> {let rj = (word >> 5) & 0x1f;let imm = sign_ext((word >> 10) & 0xfff, 12);Ok((- format!("addi{}", suffix(is64)),- format!("{}, {}, {imm}", r(rd), r(rj)),+ format!("addi{}", suffix(is64)),+ format!("{}, {}, {imm}", r(rd), r(rj)),4,))}@@ -56,12 +60,8 @@ fn decode_ldst(word: u32, name: &str, is64: bool) -> Result<(String, String, usilet rd = (word >> 0) & 0x1f;let rj = (word >> 5) & 0x1f;let imm = sign_ext((word >> 10) & 0xfff, 12);- let op = format!("{name}{}", suffix(is64));- Ok((- op,- format!("{}, {imm}({})", r(rd), r(rj)),- 4,- ))+ let op = format!("{name}{}", suffix(is64));+ Ok((op, format!("{}, {imm}({})", r(rd), r(rj)), 4))}fn decode_alu3(word: u32, name: &str, is64: bool) -> Result<(String, String, usize)> {@@ -69,26 +69,22 @@ fn decode_alu3(word: u32, name: &str, is64: bool) -> Result<(String, String, usilet rj = (word >> 5) & 0x1f;let rk = (word >> 10) & 0x1f;Ok((- format!("{name}{}", suffix(is64)),- format!("{}, {}, {}", r(rd), r(rj), r(rk)),+ format!("{name}{}", suffix(is64)),+ format!("{}, {}, {}", r(rd), r(rj), r(rk)),4,))}fn decode_branch(word: u32, name: &str) -> Result<(String, String, usize)> {let off = sign_ext((word >> 10) & 0xfffff, 20);- Ok((name.into(), format!("{off}"), 4))+ Ok((name.into(), format!("{off}"), 4))}fn decode_jirl(word: u32) -> Result<(String, String, usize)> {let rd = (word >> 0) & 0x1f;let rj = (word >> 5) & 0x1f;let off = sign_ext((word >> 10) & 0xfffff, 20);- Ok((- "jirl".into(),- format!("{}, {}, {off}", r(rd), r(rj)),- 4,- ))+ Ok(("jirl".into(), format!("{}, {}, {off}", r(rd), r(rj)), 4))}fn sign_ext(val: u32, bits: u32) -> i64 {@@ -102,10 +98,10 @@ mod tests {#[test]fn loongarch_addi() {- // addi.w r4, r5, 1 => op=0 rd=4 rj=5 imm=1+ // addi.w r4, r5, 1 => op=0 rd=4 rj=5 imm=1let word = (0x00u32 << 26) | (1 << 10) | (5 << 5) | 4;let (m, _, l) = decode(&word.to_le_bytes(), true, false).unwrap();- assert_eq!(m, "addi.w");+ assert_eq!(m, "addi.w");assert_eq!(l, 4);}}diff --git a/crates/ghidrust-decode/src/arch/loongarch/mod.rs b/crates/ghidrust-decode/src/arch/loongarch/mod.rsindex 0c9ddcf..5e28eb6 100644--- a/crates/ghidrust-decode/src/arch/loongarch/mod.rs+++ b/crates/ghidrust-decode/src/arch/loongarch/mod.rs@@ -23,7 +23,7 @@ impl ArchDecode for LoongarchDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Loongarch) {return Err(Error::Mode(format!(- "invalid loongarch mode {:#x}",+ "invalid loongarch mode {:#x}",mode.bits())));}@@ -36,8 +36,7 @@ impl ArchDecode for LoongarchDecoder {}fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {- let (mnemonic, operands, len) =- decode::decode(bytes, self.little_endian, self.is64)?;+ let (mnemonic, operands, len) = decode::decode(bytes, self.little_endian, self.is64)?;let mut insn = Instruction::with_text(address,bytes[..len].to_vec(),@@ -58,42 +57,42 @@ impl ArchDecode for LoongarchDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "bl" | "jirl" => vec![GroupId::Call],- "b" => vec![GroupId::Jump],- m if m.starts_with("ld") => vec![GroupId::Arch(1)],- m if m.starts_with("st") => vec![GroupId::Arch(2)],+ "bl" | "jirl" => vec![GroupId::Call],+ "b" => vec![GroupId::Jump],+ m if m.starts_with("ld") => vec![GroupId::Arch(1)],+ m if m.starts_with("st") => vec![GroupId::Arch(2)],_ => vec![GroupId::Arch(3)],}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("addi.w"),- 2 => Some("ld.w"),- 3 => Some("b"),- 4 => Some("jirl"),+ 1 => Some("addi.w"),+ 2 => Some("ld.w"),+ 3 => Some("b"),+ 4 => Some("jirl"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Arch(1) => Some("load"),- GroupId::Arch(2) => Some("store"),- GroupId::Arch(3) => Some("alu"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Arch(1) => Some("load"),+ GroupId::Arch(2) => Some("store"),+ GroupId::Arch(3) => Some("alu"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- m if m.starts_with("addi") => 1,- m if m.starts_with("ld") => 2,- "b" => 3,- "bl" | "jirl" => 4,- m if m.starts_with("st") => 2,+ m if m.starts_with("addi") => 1,+ m if m.starts_with("ld") => 2,+ "b" => 3,+ "bl" | "jirl" => 4,+ m if m.starts_with("st") => 2,_ => 0,};InsnId(id)@@ -109,10 +108,10 @@ mod tests {let mut eng = Engine::open(Arch::Loongarch, Mode::MODE_32).unwrap();let addi = (0x00u32 << 26) | (1 << 10) | (5 << 5) | 4;let insn = eng.disasm_one(&addi.to_le_bytes(), 0).unwrap();- assert_eq!(insn.mnemonic, "addi.w");+ assert_eq!(insn.mnemonic, "addi.w");let ld = (0x01u32 << 26) | (8 << 10) | (5 << 5) | 4;let ldw = eng.disasm_one(&ld.to_le_bytes(), 0).unwrap();- assert_eq!(ldw.mnemonic, "ld.w");+ assert_eq!(ldw.mnemonic, "ld.w");}#[test]@@ -120,9 +119,9 @@ mod tests {let mut eng = Engine::open(Arch::Loongarch, Mode::MODE_32).unwrap();let b = (0x14u32 << 26) | (4 << 10);let br = eng.disasm_one(&b.to_le_bytes(), 0).unwrap();- assert_eq!(br.mnemonic, "b");+ assert_eq!(br.mnemonic, "b");let jirl = (0x13u32 << 26) | (8 << 10) | (1 << 5) | 1;let jr = eng.disasm_one(&jirl.to_le_bytes(), 0).unwrap();- assert_eq!(jr.mnemonic, "jirl");+ assert_eq!(jr.mnemonic, "jirl");}}diff --git a/crates/ghidrust-decode/src/arch/m680x/decode.rs b/crates/ghidrust-decode/src/arch/m680x/decode.rsindex 0ab2b82..8e7f72a 100644--- a/crates/ghidrust-decode/src/arch/m680x/decode.rs+++ b/crates/ghidrust-decode/src/arch/m680x/decode.rs@@ -2,56 +2,56 @@ use crate::error::{Error, Result};pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("a"),- 1 => Some("b"),- 2 => Some("x"),- 3 => Some("sp"),+ 0 => Some("a"),+ 1 => Some("b"),+ 2 => Some("x"),+ 3 => Some("sp"),_ => None,}}pub fn decode(bytes: &[u8], _mode6809: bool) -> Result<(String, String, usize)> {if bytes.is_empty() {- return Err(Error::Decode("empty m680x input".into()));+ return Err(Error::Decode("empty m680x input".into()));}match bytes[0] {- 0x39 => Ok(("rts".into(), String::new(), 1)),+ 0x39 => Ok(("rts".into(), String::new(), 1)),0x86 => {if bytes.len() < 2 {- return Err(Error::Decode("truncated lda imm".into()));+ return Err(Error::Decode("truncated lda imm".into()));}- Ok(("lda".into(), format!("#0x{:02x}", bytes[1]), 2))+ Ok(("lda".into(), format!("#0x{:02x}", bytes[1]), 2))}- 0xb7 => decode_ext("sta", bytes),- 0x7e => decode_ext("jmp", bytes),- 0xbd => decode_ext("jsr", bytes),- 0x4f => Ok(("clra".into(), String::new(), 1)),- 0xcc => decode_ext("ldd", bytes),- 0xfd => decode_ext("std", bytes),- 0x8e => decode_ext("ldx", bytes),- 0xce => decode_ext("ldx16", bytes),+ 0xb7 => decode_ext("sta", bytes),+ 0x7e => decode_ext("jmp", bytes),+ 0xbd => decode_ext("jsr", bytes),+ 0x4f => Ok(("clra".into(), String::new(), 1)),+ 0xcc => decode_ext("ldd", bytes),+ 0xfd => decode_ext("std", bytes),+ 0x8e => decode_ext("ldx", bytes),+ 0xce => decode_ext("ldx16", bytes),0x20 => {if bytes.len() < 2 {- return Err(Error::Decode("truncated bra".into()));+ return Err(Error::Decode("truncated bra".into()));}- Ok(("bra".into(), format!("0x{:04x}", bytes[1] as u16), 2))+ Ok(("bra".into(), format!("0x{:04x}", bytes[1] as u16), 2))}0x27 => {if bytes.len() < 2 {- return Err(Error::Decode("truncated beq".into()));+ return Err(Error::Decode("truncated beq".into()));}- Ok(("beq".into(), format!("0x{:04x}", bytes[1] as u16), 2))+ Ok(("beq".into(), format!("0x{:04x}", bytes[1] as u16), 2))}- _ => Err(Error::Decode("unsupported m680x opcode".into())),+ _ => Err(Error::Decode("unsupported m680x opcode".into())),}}fn decode_ext(name: &str, bytes: &[u8]) -> Result<(String, String, usize)> {if bytes.len() < 3 {- return Err(Error::Decode("truncated m680x extended".into()));+ return Err(Error::Decode("truncated m680x extended".into()));}let addr = u16::from_be_bytes([bytes[1], bytes[2]]);- Ok((name.into(), format!("0x{addr:04x}"), 3))+ Ok((name.into(), format!("0x{addr:04x}"), 3))}#[cfg(test)]@@ -61,8 +61,8 @@ mod tests {#[test]fn m680x_lda() {let (m, o, l) = decode(&[0x86, 0x42], false).unwrap();- assert_eq!(m, "lda");+ assert_eq!(m, "lda");assert_eq!(l, 2);- assert!(o.contains("42"));+ assert!(o.contains("42"));}}diff --git a/crates/ghidrust-decode/src/arch/m680x/mod.rs b/crates/ghidrust-decode/src/arch/m680x/mod.rsindex 1570577..724b3a8 100644--- a/crates/ghidrust-decode/src/arch/m680x/mod.rs+++ b/crates/ghidrust-decode/src/arch/m680x/mod.rs@@ -21,7 +21,10 @@ impl ArchDecode for M680xDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::M680x) {- return Err(Error::Mode(format!("invalid m680x mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!(+ "invalid m680x mode {:#x}",+ mode.bits()+ )));}let mode6809 = mode.intersects(Mode::MODE_32);Ok(Self { mode6809 })@@ -49,46 +52,46 @@ impl ArchDecode for M680xDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "jsr" => vec![GroupId::Call],- "jmp" | "bra" | "beq" => vec![GroupId::Jump],- "rts" => vec![GroupId::Ret],- "lda" | "ldd" | "ldx" | "ldx16" => vec![GroupId::Arch(1)],- "sta" | "std" => vec![GroupId::Arch(2)],- "clra" => vec![GroupId::Arch(3)],+ "jsr" => vec![GroupId::Call],+ "jmp" | "bra" | "beq" => vec![GroupId::Jump],+ "rts" => vec![GroupId::Ret],+ "lda" | "ldd" | "ldx" | "ldx16" => vec![GroupId::Arch(1)],+ "sta" | "std" => vec![GroupId::Arch(2)],+ "clra" => vec![GroupId::Arch(3)],_ => Vec::new(),}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("lda"),- 2 => Some("sta"),- 3 => Some("jsr"),- 4 => Some("rts"),- 5 => Some("bra"),+ 1 => Some("lda"),+ 2 => Some("sta"),+ 3 => Some("jsr"),+ 4 => Some("rts"),+ 5 => Some("bra"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Ret => Some("ret"),- GroupId::Arch(1) => Some("load"),- GroupId::Arch(2) => Some("store"),- GroupId::Arch(3) => Some("clear"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Ret => Some("ret"),+ GroupId::Arch(1) => Some("load"),+ GroupId::Arch(2) => Some("store"),+ GroupId::Arch(3) => Some("clear"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "lda" | "ldd" | "ldx" | "ldx16" => 1,- "sta" | "std" => 2,- "jsr" | "jmp" => 3,- "rts" => 4,- "bra" | "beq" => 5,+ "lda" | "ldd" | "ldx" | "ldx16" => 1,+ "sta" | "std" => 2,+ "jsr" | "jmp" => 3,+ "rts" => 4,+ "bra" | "beq" => 5,_ => 0,};InsnId(id)@@ -103,17 +106,17 @@ mod tests {fn m680x_lda_and_rts() {let mut eng = Engine::open(Arch::M680x, Mode::LITTLE_ENDIAN).unwrap();let lda = eng.disasm_one(&[0x86, 0x42], 0).unwrap();- assert_eq!(lda.mnemonic, "lda");+ assert_eq!(lda.mnemonic, "lda");let rts = eng.disasm_one(&[0x39], 0).unwrap();- assert_eq!(rts.mnemonic, "rts");+ assert_eq!(rts.mnemonic, "rts");}#[test]fn m680x_jsr_and_bra() {let mut eng = Engine::open(Arch::M680x, Mode::LITTLE_ENDIAN).unwrap();let jsr = eng.disasm_one(&[0xbd, 0x10, 0x00], 0).unwrap();- assert_eq!(jsr.mnemonic, "jsr");+ assert_eq!(jsr.mnemonic, "jsr");let bra = eng.disasm_one(&[0x20, 0x08], 0).unwrap();- assert_eq!(bra.mnemonic, "bra");+ assert_eq!(bra.mnemonic, "bra");}}diff --git a/crates/ghidrust-decode/src/arch/m68k/decode.rs b/crates/ghidrust-decode/src/arch/m68k/decode.rsindex f2f172e..5cc1267 100644--- a/crates/ghidrust-decode/src/arch/m68k/decode.rs+++ b/crates/ghidrust-decode/src/arch/m68k/decode.rs@@ -1,26 +1,26 @@use crate::error::{Error, Result};pub fn d_reg(n: u32) -> String {- format!("d{n}")+ format!("d{n}")}pub fn a_reg(n: u32) -> String {- format!("a{n}")+ format!("a{n}")}pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("d0"),- 7 => Some("d7"),- 8 => Some("a0"),- 15 => Some("a7"),+ 0 => Some("d0"),+ 7 => Some("d7"),+ 8 => Some("a0"),+ 15 => Some("a7"),_ => None,}}pub fn decode(bytes: &[u8], big_endian: bool) -> Result<(String, String, usize)> {if bytes.len() < 2 {- return Err(Error::Decode("truncated m68k input".into()));+ return Err(Error::Decode("truncated m68k input".into()));}let word = if big_endian {u16::from_be_bytes([bytes[0], bytes[1]])@@ -29,24 +29,24 @@ pub fn decode(bytes: &[u8], big_endian: bool) -> Result<(String, String, usize)>};match word {- 0x4e75 => Ok(("rts".into(), String::new(), 2)),- 0x4e70 => Ok(("reset".into(), String::new(), 2)),- 0x4240 => Ok(("clr.w".into(), format!("{}", d_reg(0)), 2)),- 0x08c0 => Ok(("bset".into(), "#0, d0".into(), 2)),- 0x4e90 => Ok(("jsr".into(), "(a0)".into(), 2)),- 0x4ed0 => Ok(("jmp".into(), "(a0)".into(), 2)),- 0x6002 => Ok(("bra.s".into(), "2".into(), 2)),- 0x6100 => Ok(("bsr.s".into(), "0".into(), 2)),- 0x6604 => Ok(("bne.s".into(), "4".into(), 2)),- 0x6704 => Ok(("beq.s".into(), "4".into(), 2)),- 0x3400 => Ok(("move.w".into(), "d0, d1".into(), 2)),- 0x2040 => Ok(("movea.w".into(), "a0, a0".into(), 2)),- 0x7001 => Ok(("moveq".into(), "#1, d0".into(), 2)),- 0x5840 => Ok(("addq.w".into(), "#4, d0".into(), 2)),- 0xb040 => Ok(("cmp.w".into(), "d0, d0".into(), 2)),+ 0x4e75 => Ok(("rts".into(), String::new(), 2)),+ 0x4e70 => Ok(("reset".into(), String::new(), 2)),+ 0x4240 => Ok(("clr.w".into(), format!("{}", d_reg(0)), 2)),+ 0x08c0 => Ok(("bset".into(), "#0, d0".into(), 2)),+ 0x4e90 => Ok(("jsr".into(), "(a0)".into(), 2)),+ 0x4ed0 => Ok(("jmp".into(), "(a0)".into(), 2)),+ 0x6002 => Ok(("bra.s".into(), "2".into(), 2)),+ 0x6100 => Ok(("bsr.s".into(), "0".into(), 2)),+ 0x6604 => Ok(("bne.s".into(), "4".into(), 2)),+ 0x6704 => Ok(("beq.s".into(), "4".into(), 2)),+ 0x3400 => Ok(("move.w".into(), "d0, d1".into(), 2)),+ 0x2040 => Ok(("movea.w".into(), "a0, a0".into(), 2)),+ 0x7001 => Ok(("moveq".into(), "#1, d0".into(), 2)),+ 0x5840 => Ok(("addq.w".into(), "#4, d0".into(), 2)),+ 0xb040 => Ok(("cmp.w".into(), "d0, d0".into(), 2)),0x484a => decode_lea(bytes, big_endian),_ if (word & 0xff00) == 0x0600 => decode_add_sub(word),- _ => Err(Error::Decode("unsupported m68k opcode".into())),+ _ => Err(Error::Decode("unsupported m68k opcode".into())),}}@@ -54,29 +54,25 @@ fn decode_add_sub(word: u16) -> Result<(String, String, usize)> {let op = (word >> 12) & 0xf;let reg = word & 0x7;let name = match op {- 0x6 => "add.w",- 0x9 => "sub.w",- 0xb => "cmp.w",- 0xd => "add.w",- _ => return Err(Error::Decode("unsupported m68k alu".into())),+ 0x6 => "add.w",+ 0x9 => "sub.w",+ 0xb => "cmp.w",+ 0xd => "add.w",+ _ => return Err(Error::Decode("unsupported m68k alu".into())),};- Ok((- name.into(),- format!("d{}, d{}", (word >> 9) & 0x7, reg),- 2,- ))+ Ok((name.into(), format!("d{}, d{}", (word >> 9) & 0x7, reg), 2))}fn decode_lea(bytes: &[u8], be: bool) -> Result<(String, String, usize)> {if bytes.len() < 4 {- return Err(Error::Decode("truncated lea".into()));+ return Err(Error::Decode("truncated lea".into()));}let disp = if be {i16::from_be_bytes([bytes[2], bytes[3]])} else {i16::from_le_bytes([bytes[2], bytes[3]])};- Ok(("lea".into(), format!("({disp}, pc), a2"), 4))+ Ok(("lea".into(), format!("({disp}, pc), a2"), 4))}#[cfg(test)]@@ -86,7 +82,7 @@ mod tests {#[test]fn m68k_moveq() {let (m, _, l) = decode(&[0x70, 0x01], true).unwrap();- assert_eq!(m, "moveq");+ assert_eq!(m, "moveq");assert_eq!(l, 2);}}diff --git a/crates/ghidrust-decode/src/arch/m68k/mod.rs b/crates/ghidrust-decode/src/arch/m68k/mod.rsindex 371468d..2187d55 100644--- a/crates/ghidrust-decode/src/arch/m68k/mod.rs+++ b/crates/ghidrust-decode/src/arch/m68k/mod.rs@@ -21,7 +21,7 @@ impl ArchDecode for M68kDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::M68k) {- return Err(Error::Mode(format!("invalid m68k mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!("invalid m68k mode {:#x}", mode.bits())));}let big_endian = !mode.intersects(Mode::LITTLE_ENDIAN) || mode.contains(Mode::BIG_ENDIAN);Ok(Self { big_endian })@@ -49,48 +49,48 @@ impl ArchDecode for M68kDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "jsr" | "bsr" => vec![GroupId::Call],- "jmp" | "bra" | "bne" | "beq" => vec![GroupId::Jump],- "rts" => vec![GroupId::Ret],- m if m.starts_with("move") => vec![GroupId::Arch(1)],- "add.w" | "cmp.w" => vec![GroupId::Arch(2)],- "clr" | "bset" => vec![GroupId::Arch(3)],+ "jsr" | "bsr" => vec![GroupId::Call],+ "jmp" | "bra" | "bne" | "beq" => vec![GroupId::Jump],+ "rts" => vec![GroupId::Ret],+ m if m.starts_with("move") => vec![GroupId::Arch(1)],+ "add.w" | "cmp.w" => vec![GroupId::Arch(2)],+ "clr" | "bset" => vec![GroupId::Arch(3)],_ => Vec::new(),}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("move.w"),- 2 => Some("moveq"),- 3 => Some("lea"),- 4 => Some("jsr"),- 5 => Some("rts"),- 6 => Some("bra"),+ 1 => Some("move.w"),+ 2 => Some("moveq"),+ 3 => Some("lea"),+ 4 => Some("jsr"),+ 5 => Some("rts"),+ 6 => Some("bra"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Ret => Some("ret"),- GroupId::Arch(1) => Some("move"),- GroupId::Arch(2) => Some("alu"),- GroupId::Arch(3) => Some("bit"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Ret => Some("ret"),+ GroupId::Arch(1) => Some("move"),+ GroupId::Arch(2) => Some("alu"),+ GroupId::Arch(3) => Some("bit"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- m if m.starts_with("move") => 1,- "moveq" => 2,- "lea" => 3,- "jsr" | "jmp" => 4,- "rts" => 5,- m if m.starts_with('b') => 6,+ m if m.starts_with("move") => 1,+ "moveq" => 2,+ "lea" => 3,+ "jsr" | "jmp" => 4,+ "rts" => 5,+ m if m.starts_with('b') => 6,_ => 0,};InsnId(id)@@ -104,22 +104,22 @@ mod tests {#[test]fn m68k_moveq_and_rts() {let mut eng = Engine::open(Arch::M68k, Mode::BIG_ENDIAN).unwrap();- // moveq #1, d0 => 0x7001+ // moveq #1, d0 => 0x7001let mq = eng.disasm_one(&[0x70, 0x01], 0).unwrap();- assert_eq!(mq.mnemonic, "moveq");- // rts => 0x4e75+ assert_eq!(mq.mnemonic, "moveq");+ // rts => 0x4e75let rts = eng.disasm_one(&[0x4e, 0x75], 0).unwrap();- assert_eq!(rts.mnemonic, "rts");+ assert_eq!(rts.mnemonic, "rts");}#[test]fn m68k_jsr_and_bra() {let mut eng = Engine::open(Arch::M68k, Mode::BIG_ENDIAN).unwrap();- // jsr (a0) => 0x4e90+ // jsr (a0) => 0x4e90let jsr = eng.disasm_one(&[0x4e, 0x90], 0).unwrap();- assert_eq!(jsr.mnemonic, "jsr");- // bra.s +2 => 0x6002+ assert_eq!(jsr.mnemonic, "jsr");+ // bra.s +2 => 0x6002let bra = eng.disasm_one(&[0x60, 0x02], 0).unwrap();- assert_eq!(bra.mnemonic, "bra.s");+ assert_eq!(bra.mnemonic, "bra.s");}}diff --git a/crates/ghidrust-decode/src/arch/mips/decode.rs b/crates/ghidrust-decode/src/arch/mips/decode.rsindex 3b7a90c..f62a6ad 100644--- a/crates/ghidrust-decode/src/arch/mips/decode.rs+++ b/crates/ghidrust-decode/src/arch/mips/decode.rs@@ -10,29 +10,31 @@ pub fn decode(bytes: &[u8], address: u64, big_endian: bool, mips64: bool) -> Resmatch opcode {0b000000 => decode_special(w, address, raw, mips64),0b000001 => decode_regimm(w, address, raw),- 0b000010 => decode_j(w, address, raw, "j"),- 0b000011 => decode_j(w, address, raw, "jal"),- 0b000100 => decode_branch(w, address, raw, "beq"),- 0b000101 => decode_branch(w, address, raw, "bne"),- 0b000110 => decode_branch(w, address, raw, "blez"),- 0b000111 => decode_branch(w, address, raw, "bgtz"),- 0b001000 => decode_imm(w, address, raw, "addi"),- 0b001001 => decode_imm(w, address, raw, "addiu"),- 0b001010 => decode_imm(w, address, raw, "slti"),- 0b001011 => decode_imm(w, address, raw, "sltiu"),- 0b001100 => decode_imm(w, address, raw, "andi"),- 0b001101 => decode_imm(w, address, raw, "ori"),- 0b001110 => decode_imm(w, address, raw, "xori"),+ 0b000010 => decode_j(w, address, raw, "j"),+ 0b000011 => decode_j(w, address, raw, "jal"),+ 0b000100 => decode_branch(w, address, raw, "beq"),+ 0b000101 => decode_branch(w, address, raw, "bne"),+ 0b000110 => decode_branch(w, address, raw, "blez"),+ 0b000111 => decode_branch(w, address, raw, "bgtz"),+ 0b001000 => decode_imm(w, address, raw, "addi"),+ 0b001001 => decode_imm(w, address, raw, "addiu"),+ 0b001010 => decode_imm(w, address, raw, "slti"),+ 0b001011 => decode_imm(w, address, raw, "sltiu"),+ 0b001100 => decode_imm(w, address, raw, "andi"),+ 0b001101 => decode_imm(w, address, raw, "ori"),+ 0b001110 => decode_imm(w, address, raw, "xori"),0b001111 => decode_lui(w, address, raw),- 0b100011 => decode_load_store(w, address, raw, "lw"),- 0b101011 => decode_load_store(w, address, raw, "sw"),- 0b100000 => decode_load_store(w, address, raw, "lb"),- 0b101000 => decode_load_store(w, address, raw, "sb"),- 0b100001 => decode_load_store(w, address, raw, "lh"),- 0b101001 => decode_load_store(w, address, raw, "sh"),- 0b100100 => decode_load_store(w, address, raw, "lbu"),- 0b100101 => decode_load_store(w, address, raw, "lhu"),- _ => Err(Error::Decode(format!("unhandled MIPS opcode {opcode:#04x}"))),+ 0b100011 => decode_load_store(w, address, raw, "lw"),+ 0b101011 => decode_load_store(w, address, raw, "sw"),+ 0b100000 => decode_load_store(w, address, raw, "lb"),+ 0b101000 => decode_load_store(w, address, raw, "sb"),+ 0b100001 => decode_load_store(w, address, raw, "lh"),+ 0b101001 => decode_load_store(w, address, raw, "sh"),+ 0b100100 => decode_load_store(w, address, raw, "lbu"),+ 0b100101 => decode_load_store(w, address, raw, "lhu"),+ _ => Err(Error::Decode(format!(+ "unhandled MIPS opcode {opcode:#04x}"+ ))),}}@@ -43,25 +45,29 @@ fn decode_special(w: u32, address: u64, raw: Vec<u8>, mips64: bool) -> Result<Inlet rd = bit(w, 11, 15);let shamt = bit(w, 6, 10);let (mnemonic, operands) = match funct {- 0b100000 => ("add", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),- 0b100001 => ("addu", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),- 0b100010 => ("sub", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),- 0b100011 => ("subu", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),- 0b100100 => ("and", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),- 0b100101 => ("or", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),- 0b100110 => ("xor", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),- 0b100111 => ("nor", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),- 0b101010 => ("slt", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),- 0b101011 => ("sltu", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),- 0b000000 => ("sll", format!("{}, {}, #{}", gpr(rd), gpr(rt), shamt)),- 0b000010 => ("srl", format!("{}, {}, #{}", gpr(rd), gpr(rt), shamt)),- 0b000011 => ("sra", format!("{}, {}, #{}", gpr(rd), gpr(rt), shamt)),- 0b001000 => ("jr", gpr(rs).into()),- 0b001001 => ("jalr", format!("{}, {}", gpr(rd), gpr(rs))),- 0b001100 => ("syscall", String::new()),- 0b001101 => ("break", String::new()),- 0b001111 if mips64 => ("sync", String::new()),- _ => return Err(Error::Decode(format!("unhandled MIPS special {funct:#04x}"))),+ 0b100000 => ("add", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),+ 0b100001 => ("addu", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),+ 0b100010 => ("sub", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),+ 0b100011 => ("subu", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),+ 0b100100 => ("and", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),+ 0b100101 => ("or", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),+ 0b100110 => ("xor", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),+ 0b100111 => ("nor", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),+ 0b101010 => ("slt", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),+ 0b101011 => ("sltu", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),+ 0b000000 => ("sll", format!("{}, {}, #{}", gpr(rd), gpr(rt), shamt)),+ 0b000010 => ("srl", format!("{}, {}, #{}", gpr(rd), gpr(rt), shamt)),+ 0b000011 => ("sra", format!("{}, {}, #{}", gpr(rd), gpr(rt), shamt)),+ 0b001000 => ("jr", gpr(rs).into()),+ 0b001001 => ("jalr", format!("{}, {}", gpr(rd), gpr(rs))),+ 0b001100 => ("syscall", String::new()),+ 0b001101 => ("break", String::new()),+ 0b001111 if mips64 => ("sync", String::new()),+ _ => {+ return Err(Error::Decode(format!(+ "unhandled MIPS special {funct:#04x}"+ )))+ }};Ok(Instruction::with_text(address, raw, mnemonic, operands, 4))}@@ -72,17 +78,17 @@ fn decode_regimm(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {let imm = sign_extend16(w & 0xffff) as i64;let target = (address as i64).wrapping_add((imm << 2) as i64) as u64;let mnemonic = match rt {- 0b00000 => "bltz",- 0b00001 => "bgez",- 0b10000 => "bltzal",- 0b10001 => "bgezal",- _ => return Err(Error::Decode("unhandled MIPS regimm".into())),+ 0b00000 => "bltz",+ 0b00001 => "bgez",+ 0b10000 => "bltzal",+ 0b10001 => "bgezal",+ _ => return Err(Error::Decode("unhandled MIPS regimm".into())),};Ok(Instruction::with_text(address,raw,mnemonic,- format!("{}, {}", gpr(rs), fmt_imm(target as i32)),+ format!("{}, {}", gpr(rs), fmt_imm(target as i32)),4,))}@@ -107,7 +113,7 @@ fn decode_branch(w: u32, address: u64, raw: Vec<u8>, mnemonic: &str) -> Result<Iaddress,raw,mnemonic,- format!("{}, {}, {}", gpr(rs), gpr(rt), fmt_imm(target as i32)),+ format!("{}, {}, {}", gpr(rs), gpr(rt), fmt_imm(target as i32)),4,))}@@ -120,7 +126,7 @@ fn decode_imm(w: u32, address: u64, raw: Vec<u8>, mnemonic: &str) -> Result<Instaddress,raw,mnemonic,- format!("{}, {}, {:#x}", gpr(rt), gpr(rs), imm as u16),+ format!("{}, {}, {:#x}", gpr(rt), gpr(rs), imm as u16),4,))}@@ -131,8 +137,8 @@ fn decode_lui(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {Ok(Instruction::with_text(address,raw,- "lui",- format!("{}, #{:#x}", gpr(rt), imm),+ "lui",+ format!("{}, #{:#x}", gpr(rt), imm),4,))}@@ -145,7 +151,7 @@ fn decode_load_store(w: u32, address: u64, raw: Vec<u8>, mnemonic: &str) -> Resuaddress,raw,mnemonic,- format!("{}, {:#x}({})", gpr(rt), imm, gpr(rs)),+ format!("{}, {:#x}({})", gpr(rt), imm, gpr(rs)),4,))}diff --git a/crates/ghidrust-decode/src/arch/mips/mod.rs b/crates/ghidrust-decode/src/arch/mips/mod.rsindex d71648f..15185e3 100644--- a/crates/ghidrust-decode/src/arch/mips/mod.rs+++ b/crates/ghidrust-decode/src/arch/mips/mod.rs@@ -23,7 +23,7 @@ impl ArchDecode for MipsDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Mips) {- return Err(Error::Mode(format!("invalid MIPS mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!("invalid MIPS mode {:#x}", mode.bits())));}let big_endian = true;let mips64 = mode.contains(Mode::MIPS64) || mode.contains(Mode::MODE_64);@@ -45,12 +45,12 @@ impl ArchDecode for MipsDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "j" | "beq" | "bne" | "blez" | "bgtz" | "bltz" | "bgez" => {+ "j" | "beq" | "bne" | "blez" | "bgtz" | "bltz" | "bgez" => {vec![GroupId::Jump, GroupId::BranchRelative]}- "jal" | "jalr" | "bltzal" | "bgezal" => vec![GroupId::Call, GroupId::BranchRelative],- "jr" => vec![GroupId::Jump],- "syscall" | "break" => vec![GroupId::Int],+ "jal" | "jalr" | "bltzal" | "bgezal" => vec![GroupId::Call, GroupId::BranchRelative],+ "jr" => vec![GroupId::Jump],+ "syscall" | "break" => vec![GroupId::Int],_ => Vec::new(),}}@@ -61,32 +61,32 @@ pub fn reg_name(reg: RegId) -> Option<&'static str> {pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("addu"),- 2 => Some("lw"),- 3 => Some("sw"),- 4 => Some("jal"),- 5 => Some("beq"),+ 1 => Some("addu"),+ 2 => Some("lw"),+ 3 => Some("sw"),+ 4 => Some("jal"),+ 5 => Some("beq"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Int => Some("int"),- GroupId::BranchRelative => Some("branch_relative"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Int => Some("int"),+ GroupId::BranchRelative => Some("branch_relative"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "add" | "addu" => 1,- "lw" => 2,- "sw" => 3,- "jal" | "jalr" => 4,- "beq" | "bne" => 5,+ "add" | "addu" => 1,+ "lw" => 2,+ "sw" => 3,+ "jal" | "jalr" => 4,+ "beq" | "bne" => 5,_ => 0,};InsnId(id)@@ -100,20 +100,18 @@ mod tests {#[test]fn mips_addu_lw_sw() {let mut eng = Engine::open(Arch::Mips, Mode::MIPS32).unwrap();- // addu $t0, $t1, $t2 -> 0x012a4021 (BE)- let add = eng- .disasm_one(&[0x01, 0x2a, 0x40, 0x21], 0x1000)- .unwrap();- assert_eq!(add.mnemonic, "addu");- // lw $t0, 4($sp) -> 8faf0004+ // addu $t0, $t1, $t2 -> 0x012a4021 (BE)+ let add = eng.disasm_one(&[0x01, 0x2a, 0x40, 0x21], 0x1000).unwrap();+ assert_eq!(add.mnemonic, "addu");+ // lw $t0, 4($sp) -> 8faf0004let lw = eng.disasm_one(&[0x8f, 0xaf, 0x00, 0x04], 0x1004).unwrap();- assert_eq!(lw.mnemonic, "lw");+ assert_eq!(lw.mnemonic, "lw");}#[test]fn mips_jal() {let mut eng = Engine::open(Arch::Mips, Mode::MIPS32).unwrap();let jal = eng.disasm_one(&[0x0c, 0x00, 0x00, 0x00], 0x0).unwrap();- assert_eq!(jal.mnemonic, "jal");+ assert_eq!(jal.mnemonic, "jal");}}diff --git a/crates/ghidrust-decode/src/arch/mips/regs.rs b/crates/ghidrust-decode/src/arch/mips/regs.rsindex 348c600..e263f62 100644--- a/crates/ghidrust-decode/src/arch/mips/regs.rs+++ b/crates/ghidrust-decode/src/arch/mips/regs.rs@@ -1,37 +1,37 @@pub fn gpr(n: u32) -> &'static str {match n & 0x1f {- 0 => "zero",- 1 => "at",- 2 => "v0",- 3 => "v1",- 4 => "a0",- 5 => "a1",- 6 => "a2",- 7 => "a3",- 8 => "t0",- 9 => "t1",- 10 => "t2",- 11 => "t3",- 12 => "t4",- 13 => "t5",- 14 => "t6",- 15 => "t7",- 16 => "s0",- 17 => "s1",- 18 => "s2",- 19 => "s3",- 20 => "s4",- 21 => "s5",- 22 => "s6",- 23 => "s7",- 24 => "t8",- 25 => "t9",- 26 => "k0",- 27 => "k1",- 28 => "gp",- 29 => "sp",- 30 => "fp",- 31 => "ra",- _ => "zero",+ 0 => "zero",+ 1 => "at",+ 2 => "v0",+ 3 => "v1",+ 4 => "a0",+ 5 => "a1",+ 6 => "a2",+ 7 => "a3",+ 8 => "t0",+ 9 => "t1",+ 10 => "t2",+ 11 => "t3",+ 12 => "t4",+ 13 => "t5",+ 14 => "t6",+ 15 => "t7",+ 16 => "s0",+ 17 => "s1",+ 18 => "s2",+ 19 => "s3",+ 20 => "s4",+ 21 => "s5",+ 22 => "s6",+ 23 => "s7",+ 24 => "t8",+ 25 => "t9",+ 26 => "k0",+ 27 => "k1",+ 28 => "gp",+ 29 => "sp",+ 30 => "fp",+ 31 => "ra",+ _ => "zero",}}diff --git a/crates/ghidrust-decode/src/arch/mips/util.rs b/crates/ghidrust-decode/src/arch/mips/util.rsindex 497ec2d..bbd44e2 100644--- a/crates/ghidrust-decode/src/arch/mips/util.rs+++ b/crates/ghidrust-decode/src/arch/mips/util.rs@@ -2,7 +2,7 @@ use crate::error::{Error, Result};pub fn read_u32(bytes: &[u8], big_endian: bool) -> Result<u32> {if bytes.len() < 4 {- return Err(Error::Decode("truncated MIPS word".into()));+ return Err(Error::Decode("truncated MIPS word".into()));}Ok(if big_endian {u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])@@ -17,9 +17,9 @@ pub fn sign_extend16(v: u32) -> i32 {pub fn fmt_imm(v: i32) -> String {if v < 0 {- format!("-{:#x}", -v)+ format!("-{:#x}", -v)} else {- format!("{v:#x}")+ format!("{v:#x}")}}diff --git a/crates/ghidrust-decode/src/arch/mod.rs b/crates/ghidrust-decode/src/arch/mod.rsindex 425a31e..2b51fff 100644--- a/crates/ghidrust-decode/src/arch/mod.rs+++ b/crates/ghidrust-decode/src/arch/mod.rs@@ -55,7 +55,7 @@ pub trait ArchDecode: Send {Ok(insn) => {let len = insn.length as usize;if len == 0 {- return Err(Error::Decode("zero-length instruction".into()));+ return Err(Error::Decode("zero-length instruction".into()));}off += len;va = va.wrapping_add(len as u64);@@ -76,13 +76,13 @@ pub trait ArchDecode: Send {pub fn open_decoder(arch: Arch, mode: Mode) -> Result<Box<dyn ArchDecode>> {if !crate::support::support(crate::support::SupportQuery::Arch(arch)) {return Err(Error::Arch(format!(- "architecture {:?} is not supported",+ "architecture {:?} is not supported",arch)));}if !mode.is_valid_for(arch) {return Err(Error::Mode(format!(- "invalid mode {:#x} for {:?}",+ "invalid mode {:#x} for {:?}",mode.bits(),arch)));@@ -112,7 +112,7 @@ pub fn open_decoder(arch: Arch, mode: Mode) -> Result<Box<dyn ArchDecode>> {Arch::Sh => Ok(Box::new(sh::ShDecoder::open(mode)?)),Arch::Xtensa => Ok(Box::new(xtensa::XtensaDecoder::open(mode)?)),other => Err(Error::Arch(format!(- "decoder for {:?} is not implemented",+ "decoder for {:?} is not implemented",other))),}diff --git a/crates/ghidrust-decode/src/arch/mos65xx/insn_id.rs b/crates/ghidrust-decode/src/arch/mos65xx/insn_id.rsindex 27f69f8..69100cd 100644--- a/crates/ghidrust-decode/src/arch/mos65xx/insn_id.rs+++ b/crates/ghidrust-decode/src/arch/mos65xx/insn_id.rs@@ -75,73 +75,73 @@ impl InsnId {pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.0 {- 0 => Some("nop"),- 1 => Some("brk"),- 2 => Some("ora"),- 3 => Some("asl"),- 4 => Some("php"),- 5 => Some("bpl"),- 6 => Some("clc"),- 7 => Some("jsr"),- 8 => Some("and"),- 9 => Some("bit"),- 10 => Some("rol"),- 11 => Some("plp"),- 12 => Some("bmi"),- 13 => Some("sec"),- 14 => Some("rti"),- 15 => Some("eor"),- 16 => Some("lsr"),- 17 => Some("pha"),- 18 => Some("jmp"),- 19 => Some("bvc"),- 20 => Some("cli"),- 21 => Some("rts"),- 22 => Some("adc"),- 23 => Some("ror"),- 24 => Some("pla"),- 25 => Some("bvs"),- 26 => Some("sei"),- 27 => Some("sta"),- 28 => Some("sty"),- 29 => Some("stx"),- 30 => Some("dey"),- 31 => Some("txa"),- 32 => Some("bcc"),- 33 => Some("tya"),- 34 => Some("txs"),- 35 => Some("ldy"),- 36 => Some("lda"),- 37 => Some("ldx"),- 38 => Some("tay"),- 39 => Some("tax"),- 40 => Some("bcs"),- 41 => Some("clv"),- 42 => Some("tsx"),- 43 => Some("cpy"),- 44 => Some("cmp"),- 45 => Some("dec"),- 46 => Some("iny"),- 47 => Some("dex"),- 48 => Some("bne"),- 49 => Some("cld"),- 50 => Some("cpx"),- 51 => Some("sbc"),- 52 => Some("inc"),- 53 => Some("inx"),- 54 => Some("nop"),- 55 => Some("beq"),- 56 => Some("sed"),- 57 => Some("bra"),- 58 => Some("phx"),- 59 => Some("plx"),- 60 => Some("phy"),- 61 => Some("ply"),- 62 => Some("stz"),- 63 => Some("trb"),- 64 => Some("tsb"),- 65 => Some("stp"),- 66 => Some("wai"),+ 0 => Some("nop"),+ 1 => Some("brk"),+ 2 => Some("ora"),+ 3 => Some("asl"),+ 4 => Some("php"),+ 5 => Some("bpl"),+ 6 => Some("clc"),+ 7 => Some("jsr"),+ 8 => Some("and"),+ 9 => Some("bit"),+ 10 => Some("rol"),+ 11 => Some("plp"),+ 12 => Some("bmi"),+ 13 => Some("sec"),+ 14 => Some("rti"),+ 15 => Some("eor"),+ 16 => Some("lsr"),+ 17 => Some("pha"),+ 18 => Some("jmp"),+ 19 => Some("bvc"),+ 20 => Some("cli"),+ 21 => Some("rts"),+ 22 => Some("adc"),+ 23 => Some("ror"),+ 24 => Some("pla"),+ 25 => Some("bvs"),+ 26 => Some("sei"),+ 27 => Some("sta"),+ 28 => Some("sty"),+ 29 => Some("stx"),+ 30 => Some("dey"),+ 31 => Some("txa"),+ 32 => Some("bcc"),+ 33 => Some("tya"),+ 34 => Some("txs"),+ 35 => Some("ldy"),+ 36 => Some("lda"),+ 37 => Some("ldx"),+ 38 => Some("tay"),+ 39 => Some("tax"),+ 40 => Some("bcs"),+ 41 => Some("clv"),+ 42 => Some("tsx"),+ 43 => Some("cpy"),+ 44 => Some("cmp"),+ 45 => Some("dec"),+ 46 => Some("iny"),+ 47 => Some("dex"),+ 48 => Some("bne"),+ 49 => Some("cld"),+ 50 => Some("cpx"),+ 51 => Some("sbc"),+ 52 => Some("inc"),+ 53 => Some("inx"),+ 54 => Some("nop"),+ 55 => Some("beq"),+ 56 => Some("sed"),+ 57 => Some("bra"),+ 58 => Some("phx"),+ 59 => Some("plx"),+ 60 => Some("phy"),+ 61 => Some("ply"),+ 62 => Some("stz"),+ 63 => Some("trb"),+ 64 => Some("tsb"),+ 65 => Some("stp"),+ 66 => Some("wai"),_ => None,}}diff --git a/crates/ghidrust-decode/src/arch/mos65xx/mod.rs b/crates/ghidrust-decode/src/arch/mos65xx/mod.rsindex ae51ca2..3a76eae 100644--- a/crates/ghidrust-decode/src/arch/mos65xx/mod.rs+++ b/crates/ghidrust-decode/src/arch/mos65xx/mod.rs@@ -47,7 +47,7 @@ pub enum AddrMode {#[derive(Debug, Clone, Copy)]pub struct OpEntry {- pub mnemonic: &'static str,+ pub mnemonic: &'static str,pub insn: InsnId,pub mode: AddrMode,pub operand_bytes: u8,@@ -59,7 +59,7 @@ pub struct Mos65xxDecoder {pub(crate) fn decode_raw(bytes: &[u8], address: u64, mode: Mode) -> Result<Instruction> {if bytes.is_empty() {- return Err(Error::Decode("empty input".into()));+ return Err(Error::Decode("empty input".into()));}let opcode = bytes[0];let table = if mode.intersects(Mode::MOS65XX_65C02) {@@ -70,7 +70,7 @@ pub(crate) fn decode_raw(bytes: &[u8], address: u64, mode: Mode) -> Result<Instrlet entry = &table[opcode as usize];let len = 1usize + entry.operand_bytes as usize;if bytes.len() < len {- return Err(Error::Decode("truncated mos65xx instruction".into()));+ return Err(Error::Decode("truncated mos65xx instruction".into()));}let mnemonic = entry.mnemonic.to_string();let operands = format_operands(entry.mode, &bytes[1..len], address, len)?;@@ -83,48 +83,43 @@ pub(crate) fn decode_raw(bytes: &[u8], address: u64, mode: Mode) -> Result<Instr))}-fn format_operands(- mode: AddrMode,- ops: &[u8],- address: u64,- total_len: usize,-) -> Result<String> {+fn format_operands(mode: AddrMode, ops: &[u8], address: u64, total_len: usize) -> Result<String> {Ok(match mode {AddrMode::None | AddrMode::Imp => String::new(),- AddrMode::Acc => "a".into(),+ AddrMode::Acc => "a".into(),AddrMode::Imm => {if ops.len() == 1 {- format!("#0x{:02x}", ops[0])+ format!("#0x{:02x}", ops[0])} else {- format!("#0x{:04x}", u16::from_le_bytes([ops[0], ops[1]]))+ format!("#0x{:04x}", u16::from_le_bytes([ops[0], ops[1]]))}}- AddrMode::Zp => format!("0x{:02x}", ops[0]),- AddrMode::ZpX => format!("0x{:02x}, x", ops[0]),- AddrMode::ZpY => format!("0x{:02x}, y", ops[0]),- AddrMode::Abs => format!("0x{:04x}", u16::from_le_bytes([ops[0], ops[1]])),- AddrMode::AbsX => format!("0x{:04x}, x", u16::from_le_bytes([ops[0], ops[1]])),- AddrMode::AbsY => format!("0x{:04x}, y", u16::from_le_bytes([ops[0], ops[1]])),- AddrMode::ZpInd => format!("(0x{:02x})", ops[0]),- AddrMode::ZpXInd => format!("(0x{:02x}, x)", ops[0]),- AddrMode::ZpIndY => format!("(0x{:02x}), y", ops[0]),- AddrMode::AbsInd => format!("(0x{:04x})", u16::from_le_bytes([ops[0], ops[1]])),- AddrMode::Int => format!("0x{:02x}", ops[0]),+ AddrMode::Zp => format!("0x{:02x}", ops[0]),+ AddrMode::ZpX => format!("0x{:02x}, x", ops[0]),+ AddrMode::ZpY => format!("0x{:02x}, y", ops[0]),+ AddrMode::Abs => format!("0x{:04x}", u16::from_le_bytes([ops[0], ops[1]])),+ AddrMode::AbsX => format!("0x{:04x}, x", u16::from_le_bytes([ops[0], ops[1]])),+ AddrMode::AbsY => format!("0x{:04x}, y", u16::from_le_bytes([ops[0], ops[1]])),+ AddrMode::ZpInd => format!("(0x{:02x})", ops[0]),+ AddrMode::ZpXInd => format!("(0x{:02x}, x)", ops[0]),+ AddrMode::ZpIndY => format!("(0x{:02x}), y", ops[0]),+ AddrMode::AbsInd => format!("(0x{:04x})", u16::from_le_bytes([ops[0], ops[1]])),+ AddrMode::Int => format!("0x{:02x}", ops[0]),AddrMode::Rel => {let off = ops[0] as i8 as i32;let target = (address as i32 + total_len as i32 + off) as u16;- format!("0x{target:04x}")+ format!("0x{target:04x}")}AddrMode::ZpRel => {let off = ops[1] as i8 as i32;let target = (address as i32 + total_len as i32 + off) as u16;- format!("0x{:02x}, 0x{target:04x}", ops[0])+ format!("0x{:02x}, 0x{target:04x}", ops[0])}_ => ops.iter()- .map(|b| format!("0x{b:02x}"))+ .map(|b| format!("0x{b:02x}")).collect::<Vec<_>>()- .join(", "),+ .join(", "),})}@@ -136,7 +131,7 @@ impl ArchDecode for Mos65xxDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Mos65xx) {return Err(Error::Mode(format!(- "invalid mos65xx mode {:#x}",+ "invalid mos65xx mode {:#x}",mode.bits())));}@@ -158,11 +153,11 @@ impl ArchDecode for Mos65xxDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "jmp" | "bra" => vec![GroupId::Jump],- "jsr" => vec![GroupId::Call],- "rts" | "rti" => vec![GroupId::Ret],- "brk" => vec![GroupId::Int],- m if m.starts_with('b') && m.len() == 3 => vec![GroupId::BranchRelative],+ "jmp" | "bra" => vec![GroupId::Jump],+ "jsr" => vec![GroupId::Call],+ "rts" | "rti" => vec![GroupId::Ret],+ "brk" => vec![GroupId::Int],+ m if m.starts_with('b') && m.len() == 3 => vec![GroupId::BranchRelative],_ => Vec::new(),}}@@ -173,11 +168,11 @@ pub fn insn_name(id: crate::insn::InsnId) -> Option<&'static str> {pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Ret => Some("ret"),- GroupId::Int => Some("int"),- GroupId::BranchRelative => Some("branch_relative"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Ret => Some("ret"),+ GroupId::Int => Some("int"),+ GroupId::BranchRelative => Some("branch_relative"),_ => None,}}@@ -197,14 +192,14 @@ mod tests {let lda = dec.decode_one(&[0xa9, 0x42], 0x8000, &EngineOptions::default()).unwrap();- assert_eq!(lda.mnemonic, "lda");- assert_eq!(lda.operands, "#0x42");+ assert_eq!(lda.mnemonic, "lda");+ assert_eq!(lda.operands, "#0x42");assert_eq!(lda.length, 2);let brk = dec.decode_one(&[0x00, 0xff], 0, &EngineOptions::default()).unwrap();- assert_eq!(brk.mnemonic, "brk");+ assert_eq!(brk.mnemonic, "brk");assert_eq!(brk.length, 2);}@@ -214,15 +209,15 @@ mod tests {let jsr = dec.decode_one(&[0x20, 0x34, 0x12], 0x1000, &EngineOptions::default()).unwrap();- assert_eq!(jsr.mnemonic, "jsr");- assert_eq!(jsr.operands, "0x1234");+ assert_eq!(jsr.mnemonic, "jsr");+ assert_eq!(jsr.operands, "0x1234");assert_eq!(jsr.length, 3);let bne = dec.decode_one(&[0xd0, 0x05], 0x2000, &EngineOptions::default()).unwrap();- assert_eq!(bne.mnemonic, "bne");- assert_eq!(bne.operands, "0x2007");+ assert_eq!(bne.mnemonic, "bne");+ assert_eq!(bne.operands, "0x2007");}#[test]@@ -231,13 +226,13 @@ mod tests {let bra = dec.decode_one(&[0x80, 0x10], 0x3000, &EngineOptions::default()).unwrap();- assert_eq!(bra.mnemonic, "bra");+ assert_eq!(bra.mnemonic, "bra");assert_eq!(bra.length, 2);let stz = dec.decode_one(&[0x9c, 0x00, 0x40], 0, &EngineOptions::default()).unwrap();- assert_eq!(stz.mnemonic, "stz");+ assert_eq!(stz.mnemonic, "stz");assert_eq!(stz.length, 3);}}diff --git a/crates/ghidrust-decode/src/arch/mos65xx/regs.rs b/crates/ghidrust-decode/src/arch/mos65xx/regs.rsindex 5ad1f30..f984809 100644--- a/crates/ghidrust-decode/src/arch/mos65xx/regs.rs+++ b/crates/ghidrust-decode/src/arch/mos65xx/regs.rs@@ -2,11 +2,11 @@ use crate::reg::RegId;pub fn reg_name(reg: RegId) -> Option<&'static str> {match reg.index() {- 1 => Some("a"),- 2 => Some("x"),- 3 => Some("y"),- 4 => Some("p"),- 5 => Some("sp"),+ 1 => Some("a"),+ 2 => Some("x"),+ 3 => Some("y"),+ 4 => Some("p"),+ 5 => Some("sp"),_ => None,}}diff --git a/crates/ghidrust-decode/src/arch/mos65xx/table.rs b/crates/ghidrust-decode/src/arch/mos65xx/table.rsindex 71cf5e4..43e3584 100644--- a/crates/ghidrust-decode/src/arch/mos65xx/table.rs+++ b/crates/ghidrust-decode/src/arch/mos65xx/table.rs@@ -3,519 +3,3079 @@use super::{AddrMode, InsnId, OpEntry};pub const TABLE_6502: [OpEntry; 256] = [- OpEntry { mnemonic: "brk", insn: InsnId::BRK, mode: AddrMode::Int, operand_bytes: 1 }, // 0x00- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x01- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x02- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x03- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x04- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x05- OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x06- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x07- OpEntry { mnemonic: "php", insn: InsnId::PHP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x08- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x09- OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x0a- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x0b- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x0c- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x0d- OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x0e- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x0f- OpEntry { mnemonic: "bpl", insn: InsnId::BPL, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x10- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x11- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x12- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x13- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x14- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x15- OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x16- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x17- OpEntry { mnemonic: "clc", insn: InsnId::CLC, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x18- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x19- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x1a- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x1b- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x1c- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x1d- OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x1e- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x1f- OpEntry { mnemonic: "jsr", insn: InsnId::JSR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x20- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x21- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x22- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x23- OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x24- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x25- OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x26- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x27- OpEntry { mnemonic: "plp", insn: InsnId::PLP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x28- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x29- OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x2a- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x2b- OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x2c- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x2d- OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x2e- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x2f- OpEntry { mnemonic: "bmi", insn: InsnId::BMI, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x30- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x31- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x32- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x33- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x34- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x35- OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x36- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x37- OpEntry { mnemonic: "sec", insn: InsnId::SEC, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x38- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x39- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x3a- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x3b- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x3c- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x3d- OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x3e- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x3f- OpEntry { mnemonic: "rti", insn: InsnId::RTI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x40- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x41- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x42- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x43- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x44- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x45- OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x46- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x47- OpEntry { mnemonic: "pha", insn: InsnId::PHA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x48- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x49- OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x4a- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x4b- OpEntry { mnemonic: "jmp", insn: InsnId::JMP, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x4c- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x4d- OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x4e- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x4f- OpEntry { mnemonic: "bvc", insn: InsnId::BVC, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x50- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x51- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x52- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x53- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x54- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x55- OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x56- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x57- OpEntry { mnemonic: "cli", insn: InsnId::CLI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x58- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x59- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x5a- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x5b- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x5c- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x5d- OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x5e- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x5f- OpEntry { mnemonic: "rts", insn: InsnId::RTS, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x60- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x61- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x62- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x63- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x64- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x65- OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x66- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x67- OpEntry { mnemonic: "pla", insn: InsnId::PLA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x68- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x69- OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x6a- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x6b- OpEntry { mnemonic: "jmp", insn: InsnId::JMP, mode: AddrMode::AbsInd, operand_bytes: 2 }, // 0x6c- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x6d- OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x6e- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x6f- OpEntry { mnemonic: "bvs", insn: InsnId::BVS, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x70- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x71- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x72- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x73- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x74- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x75- OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x76- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x77- OpEntry { mnemonic: "sei", insn: InsnId::SEI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x78- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x79- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x7a- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x7b- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x7c- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x7d- OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x7e- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x7f- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x80- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x81- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x82- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x83- OpEntry { mnemonic: "sty", insn: InsnId::STY, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x84- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x85- OpEntry { mnemonic: "stx", insn: InsnId::STX, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x86- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x87- OpEntry { mnemonic: "dey", insn: InsnId::DEY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x88- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x89- OpEntry { mnemonic: "txa", insn: InsnId::TXA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x8a- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x8b- OpEntry { mnemonic: "sty", insn: InsnId::STY, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x8c- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x8d- OpEntry { mnemonic: "stx", insn: InsnId::STX, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x8e- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x8f- OpEntry { mnemonic: "bcc", insn: InsnId::BCC, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x90- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x91- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x92- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x93- OpEntry { mnemonic: "sty", insn: InsnId::STY, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x94- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x95- OpEntry { mnemonic: "stx", insn: InsnId::STX, mode: AddrMode::ZpY, operand_bytes: 1 }, // 0x96- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x97- OpEntry { mnemonic: "tya", insn: InsnId::TYA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x98- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x99- OpEntry { mnemonic: "txs", insn: InsnId::TXS, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x9a- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x9b- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x9c- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x9d- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x9e- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x9f- OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xa0- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0xa1- OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xa2- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xa3- OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xa4- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xa5- OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xa6- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xa7- OpEntry { mnemonic: "tay", insn: InsnId::TAY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xa8- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xa9- OpEntry { mnemonic: "tax", insn: InsnId::TAX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xaa- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xab- OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xac- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xad- OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xae- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xaf- OpEntry { mnemonic: "bcs", insn: InsnId::BCS, mode: AddrMode::Rel, operand_bytes: 1 }, // 0xb0- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0xb1- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xb2- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xb3- OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xb4- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xb5- OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::ZpY, operand_bytes: 1 }, // 0xb6- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xb7- OpEntry { mnemonic: "clv", insn: InsnId::CLV, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xb8- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xb9- OpEntry { mnemonic: "tsx", insn: InsnId::TSX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xba- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xbb- OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xbc- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xbd- OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xbe- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xbf- OpEntry { mnemonic: "cpy", insn: InsnId::CPY, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xc0- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0xc1- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xc2- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xc3- OpEntry { mnemonic: "cpy", insn: InsnId::CPY, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xc4- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xc5- OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xc6- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xc7- OpEntry { mnemonic: "iny", insn: InsnId::INY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xc8- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xc9- OpEntry { mnemonic: "dex", insn: InsnId::DEX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xca- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xcb- OpEntry { mnemonic: "cpy", insn: InsnId::CPY, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xcc- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xcd- OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xce- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xcf- OpEntry { mnemonic: "bne", insn: InsnId::BNE, mode: AddrMode::Rel, operand_bytes: 1 }, // 0xd0- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0xd1- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xd2- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xd3- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xd4- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xd5- OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xd6- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xd7- OpEntry { mnemonic: "cld", insn: InsnId::CLD, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xd8- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xd9- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xda- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xdb- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xdc- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xdd- OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xde- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xdf- OpEntry { mnemonic: "cpx", insn: InsnId::CPX, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xe0- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0xe1- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xe2- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xe3- OpEntry { mnemonic: "cpx", insn: InsnId::CPX, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xe4- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xe5- OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xe6- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xe7- OpEntry { mnemonic: "inx", insn: InsnId::INX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xe8- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xe9- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xea- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xeb- OpEntry { mnemonic: "cpx", insn: InsnId::CPX, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xec- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xed- OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xee- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xef- OpEntry { mnemonic: "beq", insn: InsnId::BEQ, mode: AddrMode::Rel, operand_bytes: 1 }, // 0xf0- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0xf1- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xf2- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xf3- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xf4- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xf5- OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xf6- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xf7- OpEntry { mnemonic: "sed", insn: InsnId::SED, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xf8- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xf9- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xfa- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xfb- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xfc- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xfd- OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xfe- OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xff+ OpEntry {+ mnemonic: "brk",+ insn: InsnId::BRK,+ mode: AddrMode::Int,+ operand_bytes: 1,+ }, // 0x00+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0x01+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x02+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x03+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x04+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x05+ OpEntry {+ mnemonic: "asl",+ insn: InsnId::ASL,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x06+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x07+ OpEntry {+ mnemonic: "php",+ insn: InsnId::PHP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x08+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0x09+ OpEntry {+ mnemonic: "asl",+ insn: InsnId::ASL,+ mode: AddrMode::Acc,+ operand_bytes: 0,+ }, // 0x0a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x0b+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x0c+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x0d+ OpEntry {+ mnemonic: "asl",+ insn: InsnId::ASL,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x0e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x0f+ OpEntry {+ mnemonic: "bpl",+ insn: InsnId::BPL,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0x10+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0x11+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x12+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x13+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x14+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x15+ OpEntry {+ mnemonic: "asl",+ insn: InsnId::ASL,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x16+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x17+ OpEntry {+ mnemonic: "clc",+ insn: InsnId::CLC,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x18+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0x19+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x1a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x1b+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x1c+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x1d+ OpEntry {+ mnemonic: "asl",+ insn: InsnId::ASL,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x1e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x1f+ OpEntry {+ mnemonic: "jsr",+ insn: InsnId::JSR,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x20+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0x21+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x22+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x23+ OpEntry {+ mnemonic: "bit",+ insn: InsnId::BIT,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x24+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x25+ OpEntry {+ mnemonic: "rol",+ insn: InsnId::ROL,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x26+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x27+ OpEntry {+ mnemonic: "plp",+ insn: InsnId::PLP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x28+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0x29+ OpEntry {+ mnemonic: "rol",+ insn: InsnId::ROL,+ mode: AddrMode::Acc,+ operand_bytes: 0,+ }, // 0x2a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x2b+ OpEntry {+ mnemonic: "bit",+ insn: InsnId::BIT,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x2c+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x2d+ OpEntry {+ mnemonic: "rol",+ insn: InsnId::ROL,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x2e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x2f+ OpEntry {+ mnemonic: "bmi",+ insn: InsnId::BMI,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0x30+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0x31+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x32+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x33+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x34+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x35+ OpEntry {+ mnemonic: "rol",+ insn: InsnId::ROL,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x36+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x37+ OpEntry {+ mnemonic: "sec",+ insn: InsnId::SEC,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x38+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0x39+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x3a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x3b+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x3c+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x3d+ OpEntry {+ mnemonic: "rol",+ insn: InsnId::ROL,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x3e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x3f+ OpEntry {+ mnemonic: "rti",+ insn: InsnId::RTI,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x40+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0x41+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x42+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x43+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x44+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x45+ OpEntry {+ mnemonic: "lsr",+ insn: InsnId::LSR,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x46+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x47+ OpEntry {+ mnemonic: "pha",+ insn: InsnId::PHA,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x48+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0x49+ OpEntry {+ mnemonic: "lsr",+ insn: InsnId::LSR,+ mode: AddrMode::Acc,+ operand_bytes: 0,+ }, // 0x4a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x4b+ OpEntry {+ mnemonic: "jmp",+ insn: InsnId::JMP,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x4c+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x4d+ OpEntry {+ mnemonic: "lsr",+ insn: InsnId::LSR,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x4e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x4f+ OpEntry {+ mnemonic: "bvc",+ insn: InsnId::BVC,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0x50+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0x51+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x52+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x53+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x54+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x55+ OpEntry {+ mnemonic: "lsr",+ insn: InsnId::LSR,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x56+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x57+ OpEntry {+ mnemonic: "cli",+ insn: InsnId::CLI,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x58+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0x59+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x5a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x5b+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x5c+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x5d+ OpEntry {+ mnemonic: "lsr",+ insn: InsnId::LSR,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x5e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x5f+ OpEntry {+ mnemonic: "rts",+ insn: InsnId::RTS,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x60+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0x61+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x62+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x63+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x64+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x65+ OpEntry {+ mnemonic: "ror",+ insn: InsnId::ROR,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x66+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x67+ OpEntry {+ mnemonic: "pla",+ insn: InsnId::PLA,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x68+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0x69+ OpEntry {+ mnemonic: "ror",+ insn: InsnId::ROR,+ mode: AddrMode::Acc,+ operand_bytes: 0,+ }, // 0x6a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x6b+ OpEntry {+ mnemonic: "jmp",+ insn: InsnId::JMP,+ mode: AddrMode::AbsInd,+ operand_bytes: 2,+ }, // 0x6c+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x6d+ OpEntry {+ mnemonic: "ror",+ insn: InsnId::ROR,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x6e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x6f+ OpEntry {+ mnemonic: "bvs",+ insn: InsnId::BVS,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0x70+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0x71+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x72+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x73+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x74+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x75+ OpEntry {+ mnemonic: "ror",+ insn: InsnId::ROR,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x76+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x77+ OpEntry {+ mnemonic: "sei",+ insn: InsnId::SEI,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x78+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0x79+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x7a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x7b+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x7c+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x7d+ OpEntry {+ mnemonic: "ror",+ insn: InsnId::ROR,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x7e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x7f+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x80+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0x81+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x82+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x83+ OpEntry {+ mnemonic: "sty",+ insn: InsnId::STY,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x84+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x85+ OpEntry {+ mnemonic: "stx",+ insn: InsnId::STX,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x86+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x87+ OpEntry {+ mnemonic: "dey",+ insn: InsnId::DEY,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x88+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x89+ OpEntry {+ mnemonic: "txa",+ insn: InsnId::TXA,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x8a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x8b+ OpEntry {+ mnemonic: "sty",+ insn: InsnId::STY,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x8c+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x8d+ OpEntry {+ mnemonic: "stx",+ insn: InsnId::STX,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x8e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x8f+ OpEntry {+ mnemonic: "bcc",+ insn: InsnId::BCC,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0x90+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0x91+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x92+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x93+ OpEntry {+ mnemonic: "sty",+ insn: InsnId::STY,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x94+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x95+ OpEntry {+ mnemonic: "stx",+ insn: InsnId::STX,+ mode: AddrMode::ZpY,+ operand_bytes: 1,+ }, // 0x96+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x97+ OpEntry {+ mnemonic: "tya",+ insn: InsnId::TYA,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x98+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0x99+ OpEntry {+ mnemonic: "txs",+ insn: InsnId::TXS,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x9a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x9b+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x9c+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x9d+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x9e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0x9f+ OpEntry {+ mnemonic: "ldy",+ insn: InsnId::LDY,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xa0+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0xa1+ OpEntry {+ mnemonic: "ldx",+ insn: InsnId::LDX,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xa2+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xa3+ OpEntry {+ mnemonic: "ldy",+ insn: InsnId::LDY,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xa4+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xa5+ OpEntry {+ mnemonic: "ldx",+ insn: InsnId::LDX,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xa6+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xa7+ OpEntry {+ mnemonic: "tay",+ insn: InsnId::TAY,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xa8+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xa9+ OpEntry {+ mnemonic: "tax",+ insn: InsnId::TAX,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xaa+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xab+ OpEntry {+ mnemonic: "ldy",+ insn: InsnId::LDY,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xac+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xad+ OpEntry {+ mnemonic: "ldx",+ insn: InsnId::LDX,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xae+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xaf+ OpEntry {+ mnemonic: "bcs",+ insn: InsnId::BCS,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0xb0+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0xb1+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xb2+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xb3+ OpEntry {+ mnemonic: "ldy",+ insn: InsnId::LDY,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0xb4+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0xb5+ OpEntry {+ mnemonic: "ldx",+ insn: InsnId::LDX,+ mode: AddrMode::ZpY,+ operand_bytes: 1,+ }, // 0xb6+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xb7+ OpEntry {+ mnemonic: "clv",+ insn: InsnId::CLV,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xb8+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0xb9+ OpEntry {+ mnemonic: "tsx",+ insn: InsnId::TSX,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xba+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xbb+ OpEntry {+ mnemonic: "ldy",+ insn: InsnId::LDY,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0xbc+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0xbd+ OpEntry {+ mnemonic: "ldx",+ insn: InsnId::LDX,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0xbe+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xbf+ OpEntry {+ mnemonic: "cpy",+ insn: InsnId::CPY,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xc0+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0xc1+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xc2+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xc3+ OpEntry {+ mnemonic: "cpy",+ insn: InsnId::CPY,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xc4+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xc5+ OpEntry {+ mnemonic: "dec",+ insn: InsnId::DEC,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xc6+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xc7+ OpEntry {+ mnemonic: "iny",+ insn: InsnId::INY,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xc8+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xc9+ OpEntry {+ mnemonic: "dex",+ insn: InsnId::DEX,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xca+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xcb+ OpEntry {+ mnemonic: "cpy",+ insn: InsnId::CPY,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xcc+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xcd+ OpEntry {+ mnemonic: "dec",+ insn: InsnId::DEC,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xce+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xcf+ OpEntry {+ mnemonic: "bne",+ insn: InsnId::BNE,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0xd0+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0xd1+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xd2+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xd3+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xd4+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0xd5+ OpEntry {+ mnemonic: "dec",+ insn: InsnId::DEC,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0xd6+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xd7+ OpEntry {+ mnemonic: "cld",+ insn: InsnId::CLD,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xd8+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0xd9+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xda+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xdb+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xdc+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0xdd+ OpEntry {+ mnemonic: "dec",+ insn: InsnId::DEC,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0xde+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xdf+ OpEntry {+ mnemonic: "cpx",+ insn: InsnId::CPX,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xe0+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0xe1+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xe2+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xe3+ OpEntry {+ mnemonic: "cpx",+ insn: InsnId::CPX,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xe4+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xe5+ OpEntry {+ mnemonic: "inc",+ insn: InsnId::INC,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xe6+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xe7+ OpEntry {+ mnemonic: "inx",+ insn: InsnId::INX,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xe8+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xe9+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xea+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xeb+ OpEntry {+ mnemonic: "cpx",+ insn: InsnId::CPX,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xec+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xed+ OpEntry {+ mnemonic: "inc",+ insn: InsnId::INC,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xee+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xef+ OpEntry {+ mnemonic: "beq",+ insn: InsnId::BEQ,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0xf0+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0xf1+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xf2+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xf3+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xf4+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0xf5+ OpEntry {+ mnemonic: "inc",+ insn: InsnId::INC,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0xf6+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xf7+ OpEntry {+ mnemonic: "sed",+ insn: InsnId::SED,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xf8+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0xf9+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xfa+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xfb+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xfc+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0xfd+ OpEntry {+ mnemonic: "inc",+ insn: InsnId::INC,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0xfe+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::INVALID,+ mode: AddrMode::None,+ operand_bytes: 0,+ }, // 0xff];pub const TABLE_65C02: [OpEntry; 256] = [- OpEntry { mnemonic: "brk", insn: InsnId::BRK, mode: AddrMode::Int, operand_bytes: 1 }, // 0x00- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x01- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x02- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x03- OpEntry { mnemonic: "tsb", insn: InsnId::TSB, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x04- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x05- OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x06- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x07- OpEntry { mnemonic: "php", insn: InsnId::PHP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x08- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x09- OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x0a- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x0b- OpEntry { mnemonic: "tsb", insn: InsnId::TSB, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x0c- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x0d- OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x0e- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x0f- OpEntry { mnemonic: "bpl", insn: InsnId::BPL, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x10- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x11- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0x12- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x13- OpEntry { mnemonic: "trb", insn: InsnId::TRB, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x14- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x15- OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x16- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x17- OpEntry { mnemonic: "clc", insn: InsnId::CLC, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x18- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x19- OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x1a- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x1b- OpEntry { mnemonic: "trb", insn: InsnId::TRB, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x1c- OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x1d- OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x1e- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x1f- OpEntry { mnemonic: "jsr", insn: InsnId::JSR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x20- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x21- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x22- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x23- OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x24- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x25- OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x26- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x27- OpEntry { mnemonic: "plp", insn: InsnId::PLP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x28- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x29- OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x2a- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x2b- OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x2c- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x2d- OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x2e- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x2f- OpEntry { mnemonic: "bmi", insn: InsnId::BMI, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x30- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x31- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0x32- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x33- OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x34- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x35- OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x36- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x37- OpEntry { mnemonic: "sec", insn: InsnId::SEC, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x38- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x39- OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x3a- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x3b- OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x3c- OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x3d- OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x3e- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x3f- OpEntry { mnemonic: "rti", insn: InsnId::RTI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x40- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x41- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x42- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x43- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x44- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x45- OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x46- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x47- OpEntry { mnemonic: "pha", insn: InsnId::PHA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x48- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x49- OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x4a- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x4b- OpEntry { mnemonic: "jmp", insn: InsnId::JMP, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x4c- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x4d- OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x4e- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x4f- OpEntry { mnemonic: "bvc", insn: InsnId::BVC, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x50- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x51- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0x52- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x53- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x54- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x55- OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x56- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x57- OpEntry { mnemonic: "cli", insn: InsnId::CLI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x58- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x59- OpEntry { mnemonic: "phy", insn: InsnId::PHY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x5a- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x5b- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 2 }, // 0x5c- OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x5d- OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x5e- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x5f- OpEntry { mnemonic: "rts", insn: InsnId::RTS, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x60- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x61- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x62- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x63- OpEntry { mnemonic: "stz", insn: InsnId::STZ, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x64- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x65- OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x66- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x67- OpEntry { mnemonic: "pla", insn: InsnId::PLA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x68- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x69- OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x6a- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x6b- OpEntry { mnemonic: "jmp", insn: InsnId::JMP, mode: AddrMode::AbsInd, operand_bytes: 2 }, // 0x6c- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x6d- OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x6e- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x6f- OpEntry { mnemonic: "bvs", insn: InsnId::BVS, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x70- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x71- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0x72- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x73- OpEntry { mnemonic: "stz", insn: InsnId::STZ, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x74- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x75- OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x76- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x77- OpEntry { mnemonic: "sei", insn: InsnId::SEI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x78- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x79- OpEntry { mnemonic: "ply", insn: InsnId::PLY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x7a- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x7b- OpEntry { mnemonic: "jmp", insn: InsnId::JMP, mode: AddrMode::AbsXInd, operand_bytes: 2 }, // 0x7c- OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x7d- OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x7e- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x7f- OpEntry { mnemonic: "bra", insn: InsnId::BRA, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x80- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x81- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x82- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x83- OpEntry { mnemonic: "sty", insn: InsnId::STY, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x84- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x85- OpEntry { mnemonic: "stx", insn: InsnId::STX, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x86- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x87- OpEntry { mnemonic: "dey", insn: InsnId::DEY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x88- OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x89- OpEntry { mnemonic: "txa", insn: InsnId::TXA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x8a- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x8b- OpEntry { mnemonic: "sty", insn: InsnId::STY, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x8c- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x8d- OpEntry { mnemonic: "stx", insn: InsnId::STX, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x8e- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x8f- OpEntry { mnemonic: "bcc", insn: InsnId::BCC, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x90- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x91- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0x92- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x93- OpEntry { mnemonic: "sty", insn: InsnId::STY, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x94- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x95- OpEntry { mnemonic: "stx", insn: InsnId::STX, mode: AddrMode::ZpY, operand_bytes: 1 }, // 0x96- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x97- OpEntry { mnemonic: "tya", insn: InsnId::TYA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x98- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x99- OpEntry { mnemonic: "txs", insn: InsnId::TXS, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x9a- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x9b- OpEntry { mnemonic: "stz", insn: InsnId::STZ, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x9c- OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x9d- OpEntry { mnemonic: "stz", insn: InsnId::STZ, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x9e- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x9f- OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xa0- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0xa1- OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xa2- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xa3- OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xa4- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xa5- OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xa6- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xa7- OpEntry { mnemonic: "tay", insn: InsnId::TAY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xa8- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xa9- OpEntry { mnemonic: "tax", insn: InsnId::TAX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xaa- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xab- OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xac- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xad- OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xae- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xaf- OpEntry { mnemonic: "bcs", insn: InsnId::BCS, mode: AddrMode::Rel, operand_bytes: 1 }, // 0xb0- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0xb1- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0xb2- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xb3- OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xb4- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xb5- OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::ZpY, operand_bytes: 1 }, // 0xb6- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xb7- OpEntry { mnemonic: "clv", insn: InsnId::CLV, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xb8- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xb9- OpEntry { mnemonic: "tsx", insn: InsnId::TSX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xba- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xbb- OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xbc- OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xbd- OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xbe- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xbf- OpEntry { mnemonic: "cpy", insn: InsnId::CPY, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xc0- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0xc1- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0xc2- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xc3- OpEntry { mnemonic: "cpy", insn: InsnId::CPY, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xc4- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xc5- OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xc6- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xc7- OpEntry { mnemonic: "iny", insn: InsnId::INY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xc8- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xc9- OpEntry { mnemonic: "dex", insn: InsnId::DEX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xca- OpEntry { mnemonic: "wai", insn: InsnId::WAI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xcb- OpEntry { mnemonic: "cpy", insn: InsnId::CPY, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xcc- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xcd- OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xce- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xcf- OpEntry { mnemonic: "bne", insn: InsnId::BNE, mode: AddrMode::Rel, operand_bytes: 1 }, // 0xd0- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0xd1- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0xd2- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xd3- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0xd4- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xd5- OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xd6- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xd7- OpEntry { mnemonic: "cld", insn: InsnId::CLD, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xd8- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xd9- OpEntry { mnemonic: "phx", insn: InsnId::PHX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xda- OpEntry { mnemonic: "stp", insn: InsnId::STP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xdb- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 2 }, // 0xdc- OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xdd- OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xde- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xdf- OpEntry { mnemonic: "cpx", insn: InsnId::CPX, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xe0- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0xe1- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0xe2- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xe3- OpEntry { mnemonic: "cpx", insn: InsnId::CPX, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xe4- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xe5- OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xe6- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xe7- OpEntry { mnemonic: "inx", insn: InsnId::INX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xe8- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xe9- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xea- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xeb- OpEntry { mnemonic: "cpx", insn: InsnId::CPX, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xec- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xed- OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xee- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xef- OpEntry { mnemonic: "beq", insn: InsnId::BEQ, mode: AddrMode::Rel, operand_bytes: 1 }, // 0xf0- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0xf1- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0xf2- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xf3- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0xf4- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xf5- OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xf6- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xf7- OpEntry { mnemonic: "sed", insn: InsnId::SED, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xf8- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xf9- OpEntry { mnemonic: "plx", insn: InsnId::PLX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xfa- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xfb- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 2 }, // 0xfc- OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xfd- OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xfe- OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xff+ OpEntry {+ mnemonic: "brk",+ insn: InsnId::BRK,+ mode: AddrMode::Int,+ operand_bytes: 1,+ }, // 0x00+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0x01+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 1,+ }, // 0x02+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x03+ OpEntry {+ mnemonic: "tsb",+ insn: InsnId::TSB,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x04+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x05+ OpEntry {+ mnemonic: "asl",+ insn: InsnId::ASL,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x06+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x07+ OpEntry {+ mnemonic: "php",+ insn: InsnId::PHP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x08+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0x09+ OpEntry {+ mnemonic: "asl",+ insn: InsnId::ASL,+ mode: AddrMode::Acc,+ operand_bytes: 0,+ }, // 0x0a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x0b+ OpEntry {+ mnemonic: "tsb",+ insn: InsnId::TSB,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x0c+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x0d+ OpEntry {+ mnemonic: "asl",+ insn: InsnId::ASL,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x0e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x0f+ OpEntry {+ mnemonic: "bpl",+ insn: InsnId::BPL,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0x10+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0x11+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::ZpInd,+ operand_bytes: 1,+ }, // 0x12+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x13+ OpEntry {+ mnemonic: "trb",+ insn: InsnId::TRB,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x14+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x15+ OpEntry {+ mnemonic: "asl",+ insn: InsnId::ASL,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x16+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x17+ OpEntry {+ mnemonic: "clc",+ insn: InsnId::CLC,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x18+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0x19+ OpEntry {+ mnemonic: "inc",+ insn: InsnId::INC,+ mode: AddrMode::Acc,+ operand_bytes: 0,+ }, // 0x1a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x1b+ OpEntry {+ mnemonic: "trb",+ insn: InsnId::TRB,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x1c+ OpEntry {+ mnemonic: "ora",+ insn: InsnId::ORA,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x1d+ OpEntry {+ mnemonic: "asl",+ insn: InsnId::ASL,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x1e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x1f+ OpEntry {+ mnemonic: "jsr",+ insn: InsnId::JSR,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x20+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0x21+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 1,+ }, // 0x22+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x23+ OpEntry {+ mnemonic: "bit",+ insn: InsnId::BIT,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x24+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x25+ OpEntry {+ mnemonic: "rol",+ insn: InsnId::ROL,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x26+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x27+ OpEntry {+ mnemonic: "plp",+ insn: InsnId::PLP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x28+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0x29+ OpEntry {+ mnemonic: "rol",+ insn: InsnId::ROL,+ mode: AddrMode::Acc,+ operand_bytes: 0,+ }, // 0x2a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x2b+ OpEntry {+ mnemonic: "bit",+ insn: InsnId::BIT,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x2c+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x2d+ OpEntry {+ mnemonic: "rol",+ insn: InsnId::ROL,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x2e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x2f+ OpEntry {+ mnemonic: "bmi",+ insn: InsnId::BMI,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0x30+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0x31+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::ZpInd,+ operand_bytes: 1,+ }, // 0x32+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x33+ OpEntry {+ mnemonic: "bit",+ insn: InsnId::BIT,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x34+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x35+ OpEntry {+ mnemonic: "rol",+ insn: InsnId::ROL,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x36+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x37+ OpEntry {+ mnemonic: "sec",+ insn: InsnId::SEC,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x38+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0x39+ OpEntry {+ mnemonic: "dec",+ insn: InsnId::DEC,+ mode: AddrMode::Acc,+ operand_bytes: 0,+ }, // 0x3a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x3b+ OpEntry {+ mnemonic: "bit",+ insn: InsnId::BIT,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x3c+ OpEntry {+ mnemonic: "and",+ insn: InsnId::AND,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x3d+ OpEntry {+ mnemonic: "rol",+ insn: InsnId::ROL,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x3e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x3f+ OpEntry {+ mnemonic: "rti",+ insn: InsnId::RTI,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x40+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0x41+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 1,+ }, // 0x42+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x43+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 1,+ }, // 0x44+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x45+ OpEntry {+ mnemonic: "lsr",+ insn: InsnId::LSR,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x46+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x47+ OpEntry {+ mnemonic: "pha",+ insn: InsnId::PHA,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x48+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0x49+ OpEntry {+ mnemonic: "lsr",+ insn: InsnId::LSR,+ mode: AddrMode::Acc,+ operand_bytes: 0,+ }, // 0x4a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x4b+ OpEntry {+ mnemonic: "jmp",+ insn: InsnId::JMP,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x4c+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x4d+ OpEntry {+ mnemonic: "lsr",+ insn: InsnId::LSR,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x4e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x4f+ OpEntry {+ mnemonic: "bvc",+ insn: InsnId::BVC,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0x50+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0x51+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::ZpInd,+ operand_bytes: 1,+ }, // 0x52+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x53+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 1,+ }, // 0x54+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x55+ OpEntry {+ mnemonic: "lsr",+ insn: InsnId::LSR,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x56+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x57+ OpEntry {+ mnemonic: "cli",+ insn: InsnId::CLI,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x58+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0x59+ OpEntry {+ mnemonic: "phy",+ insn: InsnId::PHY,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x5a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x5b+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 2,+ }, // 0x5c+ OpEntry {+ mnemonic: "eor",+ insn: InsnId::EOR,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x5d+ OpEntry {+ mnemonic: "lsr",+ insn: InsnId::LSR,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x5e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x5f+ OpEntry {+ mnemonic: "rts",+ insn: InsnId::RTS,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x60+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0x61+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 1,+ }, // 0x62+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x63+ OpEntry {+ mnemonic: "stz",+ insn: InsnId::STZ,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x64+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x65+ OpEntry {+ mnemonic: "ror",+ insn: InsnId::ROR,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x66+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x67+ OpEntry {+ mnemonic: "pla",+ insn: InsnId::PLA,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x68+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0x69+ OpEntry {+ mnemonic: "ror",+ insn: InsnId::ROR,+ mode: AddrMode::Acc,+ operand_bytes: 0,+ }, // 0x6a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x6b+ OpEntry {+ mnemonic: "jmp",+ insn: InsnId::JMP,+ mode: AddrMode::AbsInd,+ operand_bytes: 2,+ }, // 0x6c+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x6d+ OpEntry {+ mnemonic: "ror",+ insn: InsnId::ROR,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x6e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x6f+ OpEntry {+ mnemonic: "bvs",+ insn: InsnId::BVS,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0x70+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0x71+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::ZpInd,+ operand_bytes: 1,+ }, // 0x72+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x73+ OpEntry {+ mnemonic: "stz",+ insn: InsnId::STZ,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x74+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x75+ OpEntry {+ mnemonic: "ror",+ insn: InsnId::ROR,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x76+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x77+ OpEntry {+ mnemonic: "sei",+ insn: InsnId::SEI,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x78+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0x79+ OpEntry {+ mnemonic: "ply",+ insn: InsnId::PLY,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x7a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x7b+ OpEntry {+ mnemonic: "jmp",+ insn: InsnId::JMP,+ mode: AddrMode::AbsXInd,+ operand_bytes: 2,+ }, // 0x7c+ OpEntry {+ mnemonic: "adc",+ insn: InsnId::ADC,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x7d+ OpEntry {+ mnemonic: "ror",+ insn: InsnId::ROR,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x7e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x7f+ OpEntry {+ mnemonic: "bra",+ insn: InsnId::BRA,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0x80+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0x81+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 1,+ }, // 0x82+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x83+ OpEntry {+ mnemonic: "sty",+ insn: InsnId::STY,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x84+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x85+ OpEntry {+ mnemonic: "stx",+ insn: InsnId::STX,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0x86+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x87+ OpEntry {+ mnemonic: "dey",+ insn: InsnId::DEY,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x88+ OpEntry {+ mnemonic: "bit",+ insn: InsnId::BIT,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0x89+ OpEntry {+ mnemonic: "txa",+ insn: InsnId::TXA,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x8a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x8b+ OpEntry {+ mnemonic: "sty",+ insn: InsnId::STY,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x8c+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x8d+ OpEntry {+ mnemonic: "stx",+ insn: InsnId::STX,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x8e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x8f+ OpEntry {+ mnemonic: "bcc",+ insn: InsnId::BCC,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0x90+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0x91+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::ZpInd,+ operand_bytes: 1,+ }, // 0x92+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x93+ OpEntry {+ mnemonic: "sty",+ insn: InsnId::STY,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x94+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0x95+ OpEntry {+ mnemonic: "stx",+ insn: InsnId::STX,+ mode: AddrMode::ZpY,+ operand_bytes: 1,+ }, // 0x96+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x97+ OpEntry {+ mnemonic: "tya",+ insn: InsnId::TYA,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x98+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0x99+ OpEntry {+ mnemonic: "txs",+ insn: InsnId::TXS,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x9a+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x9b+ OpEntry {+ mnemonic: "stz",+ insn: InsnId::STZ,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0x9c+ OpEntry {+ mnemonic: "sta",+ insn: InsnId::STA,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x9d+ OpEntry {+ mnemonic: "stz",+ insn: InsnId::STZ,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0x9e+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0x9f+ OpEntry {+ mnemonic: "ldy",+ insn: InsnId::LDY,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xa0+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0xa1+ OpEntry {+ mnemonic: "ldx",+ insn: InsnId::LDX,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xa2+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xa3+ OpEntry {+ mnemonic: "ldy",+ insn: InsnId::LDY,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xa4+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xa5+ OpEntry {+ mnemonic: "ldx",+ insn: InsnId::LDX,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xa6+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xa7+ OpEntry {+ mnemonic: "tay",+ insn: InsnId::TAY,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xa8+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xa9+ OpEntry {+ mnemonic: "tax",+ insn: InsnId::TAX,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xaa+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xab+ OpEntry {+ mnemonic: "ldy",+ insn: InsnId::LDY,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xac+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xad+ OpEntry {+ mnemonic: "ldx",+ insn: InsnId::LDX,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xae+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xaf+ OpEntry {+ mnemonic: "bcs",+ insn: InsnId::BCS,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0xb0+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0xb1+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::ZpInd,+ operand_bytes: 1,+ }, // 0xb2+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xb3+ OpEntry {+ mnemonic: "ldy",+ insn: InsnId::LDY,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0xb4+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0xb5+ OpEntry {+ mnemonic: "ldx",+ insn: InsnId::LDX,+ mode: AddrMode::ZpY,+ operand_bytes: 1,+ }, // 0xb6+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xb7+ OpEntry {+ mnemonic: "clv",+ insn: InsnId::CLV,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xb8+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0xb9+ OpEntry {+ mnemonic: "tsx",+ insn: InsnId::TSX,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xba+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xbb+ OpEntry {+ mnemonic: "ldy",+ insn: InsnId::LDY,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0xbc+ OpEntry {+ mnemonic: "lda",+ insn: InsnId::LDA,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0xbd+ OpEntry {+ mnemonic: "ldx",+ insn: InsnId::LDX,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0xbe+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xbf+ OpEntry {+ mnemonic: "cpy",+ insn: InsnId::CPY,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xc0+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0xc1+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 1,+ }, // 0xc2+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xc3+ OpEntry {+ mnemonic: "cpy",+ insn: InsnId::CPY,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xc4+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xc5+ OpEntry {+ mnemonic: "dec",+ insn: InsnId::DEC,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xc6+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xc7+ OpEntry {+ mnemonic: "iny",+ insn: InsnId::INY,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xc8+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xc9+ OpEntry {+ mnemonic: "dex",+ insn: InsnId::DEX,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xca+ OpEntry {+ mnemonic: "wai",+ insn: InsnId::WAI,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xcb+ OpEntry {+ mnemonic: "cpy",+ insn: InsnId::CPY,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xcc+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xcd+ OpEntry {+ mnemonic: "dec",+ insn: InsnId::DEC,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xce+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xcf+ OpEntry {+ mnemonic: "bne",+ insn: InsnId::BNE,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0xd0+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0xd1+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::ZpInd,+ operand_bytes: 1,+ }, // 0xd2+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xd3+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 1,+ }, // 0xd4+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0xd5+ OpEntry {+ mnemonic: "dec",+ insn: InsnId::DEC,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0xd6+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xd7+ OpEntry {+ mnemonic: "cld",+ insn: InsnId::CLD,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xd8+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0xd9+ OpEntry {+ mnemonic: "phx",+ insn: InsnId::PHX,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xda+ OpEntry {+ mnemonic: "stp",+ insn: InsnId::STP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xdb+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 2,+ }, // 0xdc+ OpEntry {+ mnemonic: "cmp",+ insn: InsnId::CMP,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0xdd+ OpEntry {+ mnemonic: "dec",+ insn: InsnId::DEC,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0xde+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xdf+ OpEntry {+ mnemonic: "cpx",+ insn: InsnId::CPX,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xe0+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::ZpXInd,+ operand_bytes: 1,+ }, // 0xe1+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 1,+ }, // 0xe2+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xe3+ OpEntry {+ mnemonic: "cpx",+ insn: InsnId::CPX,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xe4+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xe5+ OpEntry {+ mnemonic: "inc",+ insn: InsnId::INC,+ mode: AddrMode::Zp,+ operand_bytes: 1,+ }, // 0xe6+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xe7+ OpEntry {+ mnemonic: "inx",+ insn: InsnId::INX,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xe8+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::Imm,+ operand_bytes: 1,+ }, // 0xe9+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xea+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xeb+ OpEntry {+ mnemonic: "cpx",+ insn: InsnId::CPX,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xec+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xed+ OpEntry {+ mnemonic: "inc",+ insn: InsnId::INC,+ mode: AddrMode::Abs,+ operand_bytes: 2,+ }, // 0xee+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xef+ OpEntry {+ mnemonic: "beq",+ insn: InsnId::BEQ,+ mode: AddrMode::Rel,+ operand_bytes: 1,+ }, // 0xf0+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::ZpIndY,+ operand_bytes: 1,+ }, // 0xf1+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::ZpInd,+ operand_bytes: 1,+ }, // 0xf2+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xf3+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 1,+ }, // 0xf4+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0xf5+ OpEntry {+ mnemonic: "inc",+ insn: InsnId::INC,+ mode: AddrMode::ZpX,+ operand_bytes: 1,+ }, // 0xf6+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xf7+ OpEntry {+ mnemonic: "sed",+ insn: InsnId::SED,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xf8+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::AbsY,+ operand_bytes: 2,+ }, // 0xf9+ OpEntry {+ mnemonic: "plx",+ insn: InsnId::PLX,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xfa+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xfb+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 2,+ }, // 0xfc+ OpEntry {+ mnemonic: "sbc",+ insn: InsnId::SBC,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0xfd+ OpEntry {+ mnemonic: "inc",+ insn: InsnId::INC,+ mode: AddrMode::AbsX,+ operand_bytes: 2,+ }, // 0xfe+ OpEntry {+ mnemonic: "nop",+ insn: InsnId::NOP,+ mode: AddrMode::Imp,+ operand_bytes: 0,+ }, // 0xff];diff --git a/crates/ghidrust-decode/src/arch/ppc/decode.rs b/crates/ghidrust-decode/src/arch/ppc/decode.rsindex 118c79f..3489de0 100644--- a/crates/ghidrust-decode/src/arch/ppc/decode.rs+++ b/crates/ghidrust-decode/src/arch/ppc/decode.rs@@ -11,12 +11,14 @@ pub fn decode(bytes: &[u8], address: u64, big_endian: bool, ppc64: bool) -> Resu0b001110 => decode_addi(w, address, raw),0b100000 => decode_lwz(w, address, raw),0b100100 => decode_stw(w, address, raw),- 0b100010 => decode_lbzu(w, address, raw, "lbz"),- 0b100110 => decode_lbzu(w, address, raw, "stb"),+ 0b100010 => decode_lbzu(w, address, raw, "lbz"),+ 0b100110 => decode_lbzu(w, address, raw, "stb"),0b010010 => decode_b(w, address, raw),0b010000 => decode_bc(w, address, raw),0b011111 => decode_xform(w, address, raw, ppc64),- _ => Err(Error::Decode(format!("unhandled PPC primary {primary:#04x}"))),+ _ => Err(Error::Decode(format!(+ "unhandled PPC primary {primary:#04x}"+ ))),}}@@ -24,11 +26,11 @@ fn decode_addi(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {let rt = bit(w, 16, 20);let ra = bit(w, 21, 25);let imm = sign_extend16(w & 0xffff);- let mnemonic = if ra == 0 { "li" } else { "addi" };+ let mnemonic = if ra == 0 { "li" } else { "addi" };let operands = if ra == 0 {- format!("{}, {:#x}", gpr(rt), imm as u16)+ format!("{}, {:#x}", gpr(rt), imm as u16)} else {- format!("{}, {}, {:#x}", gpr(rt), gpr(ra), imm as u16)+ format!("{}, {}, {:#x}", gpr(rt), gpr(ra), imm as u16)};Ok(Instruction::with_text(address, raw, mnemonic, operands, 4))}@@ -40,8 +42,8 @@ fn decode_lwz(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {Ok(Instruction::with_text(address,raw,- "lwz",- format!("{}, {:#x}({})", gpr(rt), imm, gpr(ra)),+ "lwz",+ format!("{}, {:#x}({})", gpr(rt), imm, gpr(ra)),4,))}@@ -53,8 +55,8 @@ fn decode_stw(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {Ok(Instruction::with_text(address,raw,- "stw",- format!("{}, {:#x}({})", gpr(rs), imm, gpr(ra)),+ "stw",+ format!("{}, {:#x}({})", gpr(rs), imm, gpr(ra)),4,))}@@ -67,7 +69,7 @@ fn decode_lbzu(w: u32, address: u64, raw: Vec<u8>, mnemonic: &str) -> Result<Insaddress,raw,mnemonic,- format!("{}, {:#x}({})", gpr(rt), imm, gpr(ra)),+ format!("{}, {:#x}({})", gpr(rt), imm, gpr(ra)),4,))}@@ -82,7 +84,7 @@ fn decode_b(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {} else {(address as i64).wrapping_add(offset) as u64};- let mnemonic = if link { "bl" } else { "b" };+ let mnemonic = if link { "bl" } else { "b" };Ok(Instruction::with_text(address,raw,@@ -98,12 +100,12 @@ fn decode_bc(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {let bd = sign_extend16(bit(w, 2, 15) << 2) as i64;let target = (address as i64).wrapping_add(bd) as u64;let link = bit(w, 0, 0) != 0;- let mnemonic = if link { "bcl" } else { "bc" };+ let mnemonic = if link { "bcl" } else { "bc" };Ok(Instruction::with_text(address,raw,mnemonic,- format!("{bo}, {bi}, {}", fmt_imm(target as i32)),+ format!("{bo}, {bi}, {}", fmt_imm(target as i32)),4,))}@@ -111,13 +113,13 @@ fn decode_bc(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {fn decode_trap(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {let to = bit(w, 21, 25);if to == 0 {- Ok(Instruction::with_text(address, raw, "tw", "", 4))+ Ok(Instruction::with_text(address, raw, "tw", "", 4))} else {Ok(Instruction::with_text(address,raw,- "trap",- format!("#{to}"),+ "trap",+ format!("#{to}"),4,))}@@ -129,23 +131,23 @@ fn decode_xform(w: u32, address: u64, raw: Vec<u8>, ppc64: bool) -> Result<Instrlet ra = bit(w, 16, 20);let rb = bit(w, 21, 25);let (mnemonic, operands) = match xo {- 0b000000 => ("mcrxr", format!("cr{}", rs)),- 0b000010 => ("add", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),- 0b000100 => ("subf", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),- 0b001010 => ("addc", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),- 0b001100 => ("subfc", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),- 0b010101 => ("dcbst", format!("{}, {}", gpr(ra), gpr(rb))),- 0b011011 => ("xor", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),- 0b011111 => ("nand", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),- 0b100001 => ("mullw", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),- 0b101010 => ("divw", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),- 0b110011 => ("or", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),- 0b110101 => ("nor", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),- 0b111000 => ("and", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),+ 0b000000 => ("mcrxr", format!("cr{}", rs)),+ 0b000010 => ("add", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),+ 0b000100 => ("subf", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),+ 0b001010 => ("addc", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),+ 0b001100 => ("subfc", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),+ 0b010101 => ("dcbst", format!("{}, {}", gpr(ra), gpr(rb))),+ 0b011011 => ("xor", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),+ 0b011111 => ("nand", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),+ 0b100001 => ("mullw", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),+ 0b101010 => ("divw", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),+ 0b110011 => ("or", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),+ 0b110101 => ("nor", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),+ 0b111000 => ("and", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),0b000011 => ("bclr", format!("20, {}, {}", "lr", bit(w, 16, 20))),0b001000 => ("bctr", format!("20, {}, {}", "ctr", bit(w, 16, 20))),- 0b010011 if ppc64 => ("ld", format!("{}, 0({})", gpr(rs), gpr(ra))),- _ => return Err(Error::Decode(format!("unhandled PPC xform {xo:#04x}"))),+ 0b010011 if ppc64 => ("ld", format!("{}, 0({})", gpr(rs), gpr(ra))),+ _ => return Err(Error::Decode(format!("unhandled PPC xform {xo:#04x}"))),};Ok(Instruction::with_text(address, raw, mnemonic, operands, 4))}diff --git a/crates/ghidrust-decode/src/arch/ppc/mod.rs b/crates/ghidrust-decode/src/arch/ppc/mod.rsindex 4b92bff..b411568 100644--- a/crates/ghidrust-decode/src/arch/ppc/mod.rs+++ b/crates/ghidrust-decode/src/arch/ppc/mod.rs@@ -23,7 +23,7 @@ impl ArchDecode for PpcDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Ppc) {- return Err(Error::Mode(format!("invalid PPC mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!("invalid PPC mode {:#x}", mode.bits())));}let big_endian = true;let ppc64 = mode.contains(Mode::PPC64) || mode.contains(Mode::MODE_64);@@ -45,9 +45,9 @@ impl ArchDecode for PpcDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "b" | "bc" | "bctr" | "bclr" => vec![GroupId::Jump, GroupId::BranchRelative],- "bl" | "bcl" => vec![GroupId::Call, GroupId::BranchRelative],- "trap" | "tw" => vec![GroupId::Int],+ "b" | "bc" | "bctr" | "bclr" => vec![GroupId::Jump, GroupId::BranchRelative],+ "bl" | "bcl" => vec![GroupId::Call, GroupId::BranchRelative],+ "trap" | "tw" => vec![GroupId::Int],_ => Vec::new(),}}@@ -58,30 +58,30 @@ pub fn reg_name(_reg: RegId) -> Option<&'static str> {pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("addi"),- 2 => Some("lwz"),- 3 => Some("stw"),- 4 => Some("bl"),+ 1 => Some("addi"),+ 2 => Some("lwz"),+ 3 => Some("stw"),+ 4 => Some("bl"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Int => Some("int"),- GroupId::BranchRelative => Some("branch_relative"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Int => Some("int"),+ GroupId::BranchRelative => Some("branch_relative"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "addi" | "li" | "add" => 1,- "lwz" | "ld" => 2,- "stw" => 3,- "bl" => 4,+ "addi" | "li" | "add" => 1,+ "lwz" | "ld" => 2,+ "stw" => 3,+ "bl" => 4,_ => 0,};InsnId(id)@@ -95,18 +95,18 @@ mod tests {#[test]fn ppc_addi_lwz() {let mut eng = Engine::open(Arch::Ppc, Mode::PPC32).unwrap();- // addi r3, r0, 0x100 -> 38600100+ // addi r3, r0, 0x100 -> 38600100let addi = eng.disasm_one(&[0x38, 0x60, 0x01, 0x00], 0x1000).unwrap();- assert_eq!(addi.mnemonic, "addi");- // lwz r4, 0(r3) -> 80830000+ assert_eq!(addi.mnemonic, "addi");+ // lwz r4, 0(r3) -> 80830000let lwz = eng.disasm_one(&[0x80, 0x83, 0x00, 0x00], 0x1004).unwrap();- assert_eq!(lwz.mnemonic, "lwz");+ assert_eq!(lwz.mnemonic, "lwz");}#[test]fn ppc_bl() {let mut eng = Engine::open(Arch::Ppc, Mode::PPC32).unwrap();let bl = eng.disasm_one(&[0x48, 0x00, 0x00, 0x01], 0x0).unwrap();- assert_eq!(bl.mnemonic, "bl");+ assert_eq!(bl.mnemonic, "bl");}}diff --git a/crates/ghidrust-decode/src/arch/ppc/regs.rs b/crates/ghidrust-decode/src/arch/ppc/regs.rsindex cb8cff8..a152806 100644--- a/crates/ghidrust-decode/src/arch/ppc/regs.rs+++ b/crates/ghidrust-decode/src/arch/ppc/regs.rs@@ -1,11 +1,11 @@pub fn gpr(n: u32) -> String {- format!("r{n}")+ format!("r{n}")}pub fn lr() -> &'static str {- "lr"+ "lr"}pub fn ctr() -> &'static str {- "ctr"+ "ctr"}diff --git a/crates/ghidrust-decode/src/arch/ppc/util.rs b/crates/ghidrust-decode/src/arch/ppc/util.rsindex 79b13fb..3c8e691 100644--- a/crates/ghidrust-decode/src/arch/ppc/util.rs+++ b/crates/ghidrust-decode/src/arch/ppc/util.rs@@ -2,7 +2,7 @@ use crate::error::{Error, Result};pub fn read_u32(bytes: &[u8], big_endian: bool) -> Result<u32> {if bytes.len() < 4 {- return Err(Error::Decode("truncated PPC word".into()));+ return Err(Error::Decode("truncated PPC word".into()));}Ok(if big_endian {u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])@@ -21,8 +21,8 @@ pub fn sign_extend16(v: u32) -> i32 {pub fn fmt_imm(v: i32) -> String {if v < 0 {- format!("-{:#x}", -v)+ format!("-{:#x}", -v)} else {- format!("{v:#x}")+ format!("{v:#x}")}}diff --git a/crates/ghidrust-decode/src/arch/riscv/decode32.rs b/crates/ghidrust-decode/src/arch/riscv/decode32.rsindex b0d0e56..b75fdc3 100644--- a/crates/ghidrust-decode/src/arch/riscv/decode32.rs+++ b/crates/ghidrust-decode/src/arch/riscv/decode32.rs@@ -12,40 +12,40 @@ pub fn decode(word: u32, is64: bool) -> Result<(String, String)> {match opcode {0b0110111 => {let imm = word & 0xfffff000;- Ok(("lui".into(), format!("{}, {imm:#x}", reg_name_num(rd))))+ Ok(("lui".into(), format!("{}, {imm:#x}", reg_name_num(rd))))}0b0010111 => {let imm = sign_extend(((word >> 12) << 12) as i32, 32);- Ok(("auipc".into(), format!("{}, {imm:#x}", reg_name_num(rd))))+ Ok(("auipc".into(), format!("{}, {imm:#x}", reg_name_num(rd))))}0b1101111 => {let imm = jal_imm(word);- Ok(("jal".into(), format!("{}, {imm:#x}", reg_name_num(rd))))+ Ok(("jal".into(), format!("{}, {imm:#x}", reg_name_num(rd))))}0b1100111 => match funct3 {0b000 => {let imm = sign_extend((word >> 20) as i32, 12);Ok((- "jalr".into(),- format!("{}, {}({})", reg_name_num(rd), imm, reg_name_num(rs1)),+ "jalr".into(),+ format!("{}, {}({})", reg_name_num(rd), imm, reg_name_num(rs1)),))}- _ => Err(Error::Decode("invalid jalr funct3".into())),+ _ => Err(Error::Decode("invalid jalr funct3".into())),},0b1100011 => {let imm = b_imm(word);let name = match funct3 {- 0b000 => "beq",- 0b001 => "bne",- 0b100 => "blt",- 0b101 => "bge",- 0b110 => "bltu",- 0b111 => "bgeu",- _ => return Err(Error::Decode("invalid branch funct3".into())),+ 0b000 => "beq",+ 0b001 => "bne",+ 0b100 => "blt",+ 0b101 => "bge",+ 0b110 => "bltu",+ 0b111 => "bgeu",+ _ => return Err(Error::Decode("invalid branch funct3".into())),};Ok((name.into(),- format!("{}, {}, {imm:#x}", reg_name_num(rs1), reg_name_num(rs2)),+ format!("{}, {}, {imm:#x}", reg_name_num(rs1), reg_name_num(rs2)),))}0b0000011 => load_mnemonic(funct3, rd, rs1, word, is64),@@ -53,56 +53,68 @@ pub fn decode(word: u32, is64: bool) -> Result<(String, String)> {0b0010011 => op_imm(funct3, rd, rs1, word, is64),0b0110011 => op_reg(funct7, funct3, rd, rs1, rs2, is64),0b0001111 => match funct3 {- 0b000 => Ok(("fence".into(), format!("{}, {}", rs1, rs2))),- 0b001 => Ok(("fence.i".into(), String::new())),- _ => Err(Error::Decode("invalid fence".into())),+ 0b000 => Ok(("fence".into(), format!("{}, {}", rs1, rs2))),+ 0b001 => Ok(("fence.i".into(), String::new())),+ _ => Err(Error::Decode("invalid fence".into())),},0b1110011 => system(funct3, rs1, rs2, word),0b1010011 => float_op(funct7, funct3, rd, rs1, rs2),- 0b0001011 => Ok(("vload".into(), format!("v{}, {}", rd, reg_name_num(rs1)))),- 0b0101011 => Ok(("vstore".into(), format!("v{}, {}", rd, reg_name_num(rs1)))),+ 0b0001011 => Ok(("vload".into(), format!("v{}, {}", rd, reg_name_num(rs1)))),+ 0b0101011 => Ok(("vstore".into(), format!("v{}, {}", rd, reg_name_num(rs1)))),0b1011011 => float_op(funct7, funct3, rd, rs1, rs2),- _ => Err(Error::Decode(format!("unknown riscv opcode {opcode:#x}"))),+ _ => Err(Error::Decode(format!("unknown riscv opcode {opcode:#x}"))),}}-fn load_mnemonic(funct3: u32, rd: u32, rs1: u32, word: u32, is64: bool) -> Result<(String, String)> {+fn load_mnemonic(+ funct3: u32,+ rd: u32,+ rs1: u32,+ word: u32,+ is64: bool,+) -> Result<(String, String)> {let imm = sign_extend((word >> 20) as i32, 12);let name = match (funct3, is64) {- (0b000, false) => "lb",- (0b001, false) => "lh",- (0b010, false) => "lw",- (0b011, true) => "ld",- (0b100, false) => "lbu",- (0b101, false) => "lhu",- (0b110, true) => "lwu",- (0b000, true) => "lb",- (0b001, true) => "lh",- (0b010, true) => "lw",- (0b100, true) => "lbu",- (0b101, true) => "lhu",- _ => return Err(Error::Decode("invalid load funct3".into())),+ (0b000, false) => "lb",+ (0b001, false) => "lh",+ (0b010, false) => "lw",+ (0b011, true) => "ld",+ (0b100, false) => "lbu",+ (0b101, false) => "lhu",+ (0b110, true) => "lwu",+ (0b000, true) => "lb",+ (0b001, true) => "lh",+ (0b010, true) => "lw",+ (0b100, true) => "lbu",+ (0b101, true) => "lhu",+ _ => return Err(Error::Decode("invalid load funct3".into())),};Ok((name.into(),- format!("{}, {imm}({})", reg_name_num(rd), reg_name_num(rs1)),+ format!("{}, {imm}({})", reg_name_num(rd), reg_name_num(rs1)),))}-fn store_mnemonic(funct3: u32, rs1: u32, rs2: u32, word: u32, is64: bool) -> Result<(String, String)> {+fn store_mnemonic(+ funct3: u32,+ rs1: u32,+ rs2: u32,+ word: u32,+ is64: bool,+) -> Result<(String, String)> {let imm = s_imm(word);let name = match (funct3, is64) {- (0b000, _) => "sb",- (0b001, false) => "sh",- (0b010, false) => "sw",- (0b011, true) => "sd",- (0b001, true) => "sh",- (0b010, true) => "sw",- _ => return Err(Error::Decode("invalid store funct3".into())),+ (0b000, _) => "sb",+ (0b001, false) => "sh",+ (0b010, false) => "sw",+ (0b011, true) => "sd",+ (0b001, true) => "sh",+ (0b010, true) => "sw",+ _ => return Err(Error::Decode("invalid store funct3".into())),};Ok((name.into(),- format!("{}, {imm}({})", reg_name_num(rs2), reg_name_num(rs1)),+ format!("{}, {imm}({})", reg_name_num(rs2), reg_name_num(rs1)),))}@@ -114,27 +126,33 @@ fn op_imm(funct3: u32, rd: u32, rs1: u32, word: u32, is64: bool) -> Result<(Stri((word >> 20) & 0x1f) as i32};let name = match funct3 {- 0b000 => "addi",- 0b010 => "slti",- 0b011 => "sltiu",- 0b100 => "xori",- 0b110 => "ori",- 0b111 => "andi",- 0b001 => if is64 { "slli" } else { "slli" },+ 0b000 => "addi",+ 0b010 => "slti",+ 0b011 => "sltiu",+ 0b100 => "xori",+ 0b110 => "ori",+ 0b111 => "andi",+ 0b001 => {+ if is64 {+ "slli"+ } else {+ "slli"+ }+ }0b101 => {if (word >> 30) & 1 == 1 {if is64 {- "srai"+ "srai"} else {- "srai"+ "srai"}} else if is64 {- "srli"+ "srli"} else {- "srli"+ "srli"}}- _ => return Err(Error::Decode("invalid op-imm funct3".into())),+ _ => return Err(Error::Decode("invalid op-imm funct3".into())),};let imm_disp = if funct3 == 0b001 || funct3 == 0b101 {shamt@@ -143,108 +161,166 @@ fn op_imm(funct3: u32, rd: u32, rs1: u32, word: u32, is64: bool) -> Result<(Stri};Ok((name.into(),- format!("{}, {}, {imm_disp}", reg_name_num(rd), reg_name_num(rs1)),+ format!("{}, {}, {imm_disp}", reg_name_num(rd), reg_name_num(rs1)),))}-fn op_reg(funct7: u32, funct3: u32, rd: u32, rs1: u32, rs2: u32, is64: bool) -> Result<(String, String)> {+fn op_reg(+ funct7: u32,+ funct3: u32,+ rd: u32,+ rs1: u32,+ rs2: u32,+ is64: bool,+) -> Result<(String, String)> {if funct7 == 0b0000001 && matches!(funct3, 0b000 | 0b001 | 0b010 | 0b011) {let name = match funct3 {- 0b000 => "mul",- 0b001 => "mulh",- 0b010 => "mulhsu",- 0b011 => "mulhu",+ 0b000 => "mul",+ 0b001 => "mulh",+ 0b010 => "mulhsu",+ 0b011 => "mulhu",_ => unreachable!(),};return Ok((name.into(),- format!("{}, {}, {}", reg_name_num(rd), reg_name_num(rs1), reg_name_num(rs2)),+ format!(+ "{}, {}, {}",+ reg_name_num(rd),+ reg_name_num(rs1),+ reg_name_num(rs2)+ ),));}if funct7 == 0b0000001 && funct3 == 0b100 {return Ok((- "div".into(),- format!("{}, {}, {}", reg_name_num(rd), reg_name_num(rs1), reg_name_num(rs2)),+ "div".into(),+ format!(+ "{}, {}, {}",+ reg_name_num(rd),+ reg_name_num(rs1),+ reg_name_num(rs2)+ ),));}if funct7 == 0b0000001 && funct3 == 0b101 {return Ok((- "divu".into(),- format!("{}, {}, {}", reg_name_num(rd), reg_name_num(rs1), reg_name_num(rs2)),+ "divu".into(),+ format!(+ "{}, {}, {}",+ reg_name_num(rd),+ reg_name_num(rs1),+ reg_name_num(rs2)+ ),));}if funct7 == 0b0000001 && funct3 == 0b110 {return Ok((- "rem".into(),- format!("{}, {}, {}", reg_name_num(rd), reg_name_num(rs1), reg_name_num(rs2)),+ "rem".into(),+ format!(+ "{}, {}, {}",+ reg_name_num(rd),+ reg_name_num(rs1),+ reg_name_num(rs2)+ ),));}if funct7 == 0b0000001 && funct3 == 0b111 {return Ok((- "remu".into(),- format!("{}, {}, {}", reg_name_num(rd), reg_name_num(rs1), reg_name_num(rs2)),+ "remu".into(),+ format!(+ "{}, {}, {}",+ reg_name_num(rd),+ reg_name_num(rs1),+ reg_name_num(rs2)+ ),));}let name = match (funct7, funct3) {- (0b0000000, 0b000) => if is64 { "add" } else { "add" },- (0b0100000, 0b000) => "sub",- (0b0000000, 0b001) => "sll",- (0b0000000, 0b010) => "slt",- (0b0000000, 0b011) => "sltu",- (0b0000000, 0b100) => "xor",- (0b0000000, 0b101) => "srl",- (0b0100000, 0b101) => "sra",- (0b0000000, 0b110) => "or",- (0b0000000, 0b111) => "and",- (0b0000001, 0b000) => "mul",- _ => return Err(Error::Decode("invalid op funct7/funct3".into())),+ (0b0000000, 0b000) => {+ if is64 {+ "add"+ } else {+ "add"+ }+ }+ (0b0100000, 0b000) => "sub",+ (0b0000000, 0b001) => "sll",+ (0b0000000, 0b010) => "slt",+ (0b0000000, 0b011) => "sltu",+ (0b0000000, 0b100) => "xor",+ (0b0000000, 0b101) => "srl",+ (0b0100000, 0b101) => "sra",+ (0b0000000, 0b110) => "or",+ (0b0000000, 0b111) => "and",+ (0b0000001, 0b000) => "mul",+ _ => return Err(Error::Decode("invalid op funct7/funct3".into())),};Ok((name.into(),- format!("{}, {}, {}", reg_name_num(rd), reg_name_num(rs1), reg_name_num(rs2)),+ format!(+ "{}, {}, {}",+ reg_name_num(rd),+ reg_name_num(rs1),+ reg_name_num(rs2)+ ),))}fn system(funct3: u32, rs1: u32, _rs2: u32, word: u32) -> Result<(String, String)> {let imm = (word >> 20) as u32;match (funct3, imm) {- (0b000, 0) => Ok(("ecall".into(), String::new())),- (0b000, 1) => Ok(("ebreak".into(), String::new())),- (0b000, 0x302) => Ok(("mret".into(), String::new())),- (0b000, 0x102) => Ok(("sret".into(), String::new())),- (0b000, 0x002) => Ok(("uret".into(), String::new())),- (0b001, _) => Ok(("csrrw".into(), format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm))),- (0b010, _) => Ok(("csrrs".into(), format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm))),- (0b011, _) => Ok(("csrrc".into(), format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm))),- (0b101, _) => Ok(("csrrwi".into(), format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm))),- (0b110, _) => Ok(("csrrsi".into(), format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm))),- (0b111, _) => Ok(("csrrci".into(), format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm))),- _ => Err(Error::Decode("invalid system instruction".into())),+ (0b000, 0) => Ok(("ecall".into(), String::new())),+ (0b000, 1) => Ok(("ebreak".into(), String::new())),+ (0b000, 0x302) => Ok(("mret".into(), String::new())),+ (0b000, 0x102) => Ok(("sret".into(), String::new())),+ (0b000, 0x002) => Ok(("uret".into(), String::new())),+ (0b001, _) => Ok((+ "csrrw".into(),+ format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm),+ )),+ (0b010, _) => Ok((+ "csrrs".into(),+ format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm),+ )),+ (0b011, _) => Ok((+ "csrrc".into(),+ format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm),+ )),+ (0b101, _) => Ok((+ "csrrwi".into(),+ format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm),+ )),+ (0b110, _) => Ok((+ "csrrsi".into(),+ format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm),+ )),+ (0b111, _) => Ok((+ "csrrci".into(),+ format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm),+ )),+ _ => Err(Error::Decode("invalid system instruction".into())),}}fn float_op(funct7: u32, funct3: u32, rd: u32, rs1: u32, rs2: u32) -> Result<(String, String)> {let width = match funct7 {- 0b0000000 | 0b0000100 | 0b0001000 | 0b0001100 => 's',- 0b0000001 | 0b0000101 | 0b0001001 | 0b0001101 => 'd',- _ => return Err(Error::Decode("invalid float funct7".into())),+ 0b0000000 | 0b0000100 | 0b0001000 | 0b0001100 => 's',+ 0b0000001 | 0b0000101 | 0b0001001 | 0b0001101 => 'd',+ _ => return Err(Error::Decode("invalid float funct7".into())),};let name = match funct3 {- 0b000 => format!("fadd.{width}"),- 0b001 => format!("fsub.{width}"),- 0b010 => format!("fmul.{width}"),- 0b011 => format!("fdiv.{width}"),- 0b100 => format!("fsgnj.{width}"),- 0b101 => format!("fmin.{width}"),- 0b110 => format!("fmax.{width}"),- 0b111 => format!("fsqrt.{width}"),- _ => return Err(Error::Decode("invalid float funct3".into())),+ 0b000 => format!("fadd.{width}"),+ 0b001 => format!("fsub.{width}"),+ 0b010 => format!("fmul.{width}"),+ 0b011 => format!("fdiv.{width}"),+ 0b100 => format!("fsgnj.{width}"),+ 0b101 => format!("fmin.{width}"),+ 0b110 => format!("fmax.{width}"),+ 0b111 => format!("fsqrt.{width}"),+ _ => return Err(Error::Decode("invalid float funct3".into())),};- Ok((- name,- format!("f{}, f{}, f{}", rd, rs1, rs2),- ))+ Ok((name, format!("f{}, f{}, f{}", rd, rs1, rs2)))}fn sign_extend(value: i32, bits: u32) -> i32 {@@ -279,51 +355,51 @@ fn s_imm(word: u32) -> i32 {pub fn id_for_mnemonic(mnemonic: &str) -> u32 {match mnemonic {- "lui" => 1,- "auipc" => 2,- "jal" => 3,- "jalr" => 4,- "beq" => 5,- "bne" => 6,- "blt" => 7,- "bge" => 8,- "bltu" => 9,- "bgeu" => 10,- "lb" => 11,- "lh" => 12,- "lw" => 13,- "ld" => 14,- "sb" => 15,- "sh" => 16,- "sw" => 17,- "sd" => 18,- "addi" => 19,- "add" => 20,- "sub" => 21,- "mul" => 22,- "div" => 23,- "rem" => 24,- "fence" => 25,- "ecall" => 26,- "ebreak" => 27,- "c.addi" => 100,+ "lui" => 1,+ "auipc" => 2,+ "jal" => 3,+ "jalr" => 4,+ "beq" => 5,+ "bne" => 6,+ "blt" => 7,+ "bge" => 8,+ "bltu" => 9,+ "bgeu" => 10,+ "lb" => 11,+ "lh" => 12,+ "lw" => 13,+ "ld" => 14,+ "sb" => 15,+ "sh" => 16,+ "sw" => 17,+ "sd" => 18,+ "addi" => 19,+ "add" => 20,+ "sub" => 21,+ "mul" => 22,+ "div" => 23,+ "rem" => 24,+ "fence" => 25,+ "ecall" => 26,+ "ebreak" => 27,+ "c.addi" => 100,_ => 0,}}pub fn insn_name_by_id(id: u32) -> Option<&'static str> {match id {- 1 => Some("lui"),- 2 => Some("auipc"),- 3 => Some("jal"),- 4 => Some("jalr"),- 5 => Some("beq"),- 6 => Some("bne"),- 19 => Some("addi"),- 20 => Some("add"),- 22 => Some("mul"),- 26 => Some("ecall"),- 100 => Some("c.addi"),+ 1 => Some("lui"),+ 2 => Some("auipc"),+ 3 => Some("jal"),+ 4 => Some("jalr"),+ 5 => Some("beq"),+ 6 => Some("bne"),+ 19 => Some("addi"),+ 20 => Some("add"),+ 22 => Some("mul"),+ 26 => Some("ecall"),+ 100 => Some("c.addi"),_ => None,}}diff --git a/crates/ghidrust-decode/src/arch/riscv/decode_c.rs b/crates/ghidrust-decode/src/arch/riscv/decode_c.rsindex eb51fd0..2819867 100644--- a/crates/ghidrust-decode/src/arch/riscv/decode_c.rs+++ b/crates/ghidrust-decode/src/arch/riscv/decode_c.rs@@ -8,7 +8,7 @@ pub fn decode(half: u16, is64: bool) -> Result<(String, String, usize)> {0x0 => quad0(half, funct3),0x1 => quad1(half, funct3, is64),0x2 => quad2(half, funct3, is64),- _ => Err(Error::Decode("invalid compressed quadrant".into())),+ _ => Err(Error::Decode("invalid compressed quadrant".into())),}}@@ -16,25 +16,37 @@ fn quad0(half: u16, funct3: u16) -> Result<(String, String, usize)> {match funct3 {0b000 => {let nzuimm = c_nzuimm(half);- Ok(("c.addi4spn".into(), format!("{}, sp, {nzuimm}", c_rd(half)), 2))+ Ok((+ "c.addi4spn".into(),+ format!("{}, sp, {nzuimm}", c_rd(half)),+ 2,+ ))}0b010 => {let offset = c_lw_offset(half);Ok((- "c.lw".into(),- format!("{}, {offset}({})", reg_name_num(c_rd(half)), reg_name_num(c_rs1(half))),+ "c.lw".into(),+ format!(+ "{}, {offset}({})",+ reg_name_num(c_rd(half)),+ reg_name_num(c_rs1(half))+ ),2,))}0b110 => {let offset = c_sw_offset(half);Ok((- "c.sw".into(),- format!("{}, {offset}({})", reg_name_num(c_rs2(half)), reg_name_num(c_rs1(half))),+ "c.sw".into(),+ format!(+ "{}, {offset}({})",+ reg_name_num(c_rs2(half)),+ reg_name_num(c_rs1(half))+ ),2,))}- _ => Err(Error::Decode("invalid c.quad0".into())),+ _ => Err(Error::Decode("invalid c.quad0".into())),}}@@ -43,33 +55,37 @@ fn quad1(half: u16, funct3: u16, is64: bool) -> Result<(String, String, usize)>0b000 => {let rd = ((half >> 7) & 0x1f) as u32;if rd == 0 {- Ok(("c.nop".into(), String::new(), 2))+ Ok(("c.nop".into(), String::new(), 2))} else {let imm = c_imm6(half);- Ok(("c.addi".into(), format!("{}, {imm}", reg_name_num(rd)), 2))+ Ok(("c.addi".into(), format!("{}, {imm}", reg_name_num(rd)), 2))}}0b001 => {if is64 {- Ok(("c.addiw".into(), format!("{}, {}", reg_name_num(c_rd(half)), c_imm6(half)), 2))+ Ok((+ "c.addiw".into(),+ format!("{}, {}", reg_name_num(c_rd(half)), c_imm6(half)),+ 2,+ ))} else {let offset = c_j_offset(half);- Ok(("c.j".into(), format!("{offset:#x}"), 2))+ Ok(("c.j".into(), format!("{offset:#x}"), 2))}}0b010 => {let rd = ((half >> 7) & 0x1f) as u32;let imm = c_imm6(half);- Ok(("c.li".into(), format!("{}, {imm}", reg_name_num(rd)), 2))+ Ok(("c.li".into(), format!("{}, {imm}", reg_name_num(rd)), 2))}0b011 => {let rd = ((half >> 7) & 0x1f) as u32;if rd == 2 {let imm = c_sp_imm(half);- Ok(("c.addi16sp".into(), format!("sp, {imm}"), 2))+ Ok(("c.addi16sp".into(), format!("sp, {imm}"), 2))} else {let imm = c_lui_imm(half);- Ok(("c.lui".into(), format!("{}, {imm:#x}", reg_name_num(rd)), 2))+ Ok(("c.lui".into(), format!("{}, {imm:#x}", reg_name_num(rd)), 2))}}0b100 => {@@ -77,34 +93,34 @@ fn quad1(half: u16, funct3: u16, is64: bool) -> Result<(String, String, usize)>let rd = c_rdp(half);let imm = c_srli_imm(half);let name = match kind {- 0b00 => "c.srli",- 0b01 => "c.srai",- 0b10 => "c.andi",- _ => return Err(Error::Decode("invalid c.alu".into())),+ 0b00 => "c.srli",+ 0b01 => "c.srai",+ 0b10 => "c.andi",+ _ => return Err(Error::Decode("invalid c.alu".into())),};- Ok((name.into(), format!("{}, {imm}", reg_name_num(rd)), 2))+ Ok((name.into(), format!("{}, {imm}", reg_name_num(rd)), 2))}0b101 => {let offset = c_j_offset(half);- Ok(("c.j".into(), format!("{offset:#x}"), 2))+ Ok(("c.j".into(), format!("{offset:#x}"), 2))}0b110 => {let offset = c_b_offset(half);Ok((- "c.beqz".into(),- format!("{}, {offset:#x}", reg_name_num(c_rdp(half))),+ "c.beqz".into(),+ format!("{}, {offset:#x}", reg_name_num(c_rdp(half))),2,))}0b111 => {let offset = c_b_offset(half);Ok((- "c.bnez".into(),- format!("{}, {offset:#x}", reg_name_num(c_rdp(half))),+ "c.bnez".into(),+ format!("{}, {offset:#x}", reg_name_num(c_rdp(half))),2,))}- _ => Err(Error::Decode("invalid c.quad1".into())),+ _ => Err(Error::Decode("invalid c.quad1".into())),}}@@ -113,29 +129,29 @@ fn quad2(half: u16, funct3: u16, is64: bool) -> Result<(String, String, usize)>0b000 => {let rs1 = ((half >> 7) & 0x1f) as u32;if rs1 == 0 {- return Err(Error::Decode("reserved c.jr".into()));+ return Err(Error::Decode("reserved c.jr".into()));}- Ok(("c.jr".into(), format!("{}", reg_name_num(rs1)), 2))+ Ok(("c.jr".into(), format!("{}", reg_name_num(rs1)), 2))}0b001 => {let rd = ((half >> 7) & 0x1f) as u32;- Ok(("c.jal".into(), format!("{}", reg_name_num(rd)), 2))+ Ok(("c.jal".into(), format!("{}", reg_name_num(rd)), 2))}0b010 => {let offset = c_ldsp_offset(half, is64);- let name = if is64 { "c.ldsp" } else { "c.lwsp" };+ let name = if is64 { "c.ldsp" } else { "c.lwsp" };Ok((name.into(),- format!("{}, {offset}(sp)", reg_name_num(c_rd(half))),+ format!("{}, {offset}(sp)", reg_name_num(c_rd(half))),2,))}0b110 => {let offset = c_sdsp_offset(half, is64);- let name = if is64 { "c.sdsp" } else { "c.swsp" };+ let name = if is64 { "c.sdsp" } else { "c.swsp" };Ok((name.into(),- format!("{}, {offset}(sp)", reg_name_num(c_rs2(half))),+ format!("{}, {offset}(sp)", reg_name_num(c_rs2(half))),2,))}@@ -144,18 +160,26 @@ fn quad2(half: u16, funct3: u16, is64: bool) -> Result<(String, String, usize)>if bit12 == 0 {let rd = c_rdp(half);let rs2 = c_rs2p(half);- Ok(("c.mv".into(), format!("{}, {}", reg_name_num(rd), reg_name_num(rs2)), 2))+ Ok((+ "c.mv".into(),+ format!("{}, {}", reg_name_num(rd), reg_name_num(rs2)),+ 2,+ ))} else {let rd = c_rdp(half);let rs2 = c_rs2p(half);if rs2 == 0 {- Ok(("c.ebreak".into(), String::new(), 2))+ Ok(("c.ebreak".into(), String::new(), 2))} else {- Ok(("c.add".into(), format!("{}, {}", reg_name_num(rd), reg_name_num(rs2)), 2))+ Ok((+ "c.add".into(),+ format!("{}, {}", reg_name_num(rd), reg_name_num(rs2)),+ 2,+ ))}}}- _ => Err(Error::Decode("invalid c.quad2".into())),+ _ => Err(Error::Decode("invalid c.quad2".into())),}}diff --git a/crates/ghidrust-decode/src/arch/riscv/mod.rs b/crates/ghidrust-decode/src/arch/riscv/mod.rsindex ad4d3e0..e69a2bc 100644--- a/crates/ghidrust-decode/src/arch/riscv/mod.rs+++ b/crates/ghidrust-decode/src/arch/riscv/mod.rs@@ -20,13 +20,13 @@ pub struct RiscvDecoder {pub(crate) fn decode_raw(bytes: &[u8], address: u64, mode: Mode) -> Result<Instruction> {if bytes.len() < 2 {- return Err(Error::Decode("empty input".into()));+ return Err(Error::Decode("empty input".into()));}let is_rvc = mode.intersects(Mode::RISCV_C);let is64 = mode.intersects(Mode::RISCV64);if is_rvc && (bytes[0] & 0x03) != 0x03 {if bytes.len() < 2 {- return Err(Error::Decode("truncated riscv compressed".into()));+ return Err(Error::Decode("truncated riscv compressed".into()));}let half = u16::from_le_bytes([bytes[0], bytes[1]]);let (mnemonic, operands, len) = decode_c::decode(half, is64)?;@@ -39,11 +39,13 @@ pub(crate) fn decode_raw(bytes: &[u8], address: u64, mode: Mode) -> Result<Instr))} else {if bytes.len() < 4 {- return Err(Error::Decode("truncated riscv instruction".into()));+ return Err(Error::Decode("truncated riscv instruction".into()));}let word = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);if (word & 0x03) != 0x03 {- return Err(Error::Decode("compressed instruction without RISCV_C".into()));+ return Err(Error::Decode(+ "compressed instruction without RISCV_C".into(),+ ));}let (mnemonic, operands) = decode32::decode(word, is64)?;Ok(Instruction::with_text(@@ -63,7 +65,10 @@ impl ArchDecode for RiscvDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Riscv) {- return Err(Error::Mode(format!("invalid riscv mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!(+ "invalid riscv mode {:#x}",+ mode.bits()+ )));}Ok(Self { mode })}@@ -83,11 +88,11 @@ impl ArchDecode for RiscvDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "jal" | "jalr" | "c.j" | "c.jal" | "c.jr" | "c.jalr" => vec![GroupId::Call],- m if m.starts_with('b') || m.starts_with("c.b") => vec![GroupId::Jump],- "ecall" | "ebreak" | "c.ebreak" => vec![GroupId::Int],- "mret" | "sret" | "uret" => vec![GroupId::Ret],- "fence" | "fence.i" => vec![GroupId::Arch(1)],+ "jal" | "jalr" | "c.j" | "c.jal" | "c.jr" | "c.jalr" => vec![GroupId::Call],+ m if m.starts_with('b') || m.starts_with("c.b") => vec![GroupId::Jump],+ "ecall" | "ebreak" | "c.ebreak" => vec![GroupId::Int],+ "mret" | "sret" | "uret" => vec![GroupId::Ret],+ "fence" | "fence.i" => vec![GroupId::Arch(1)],_ => Vec::new(),}}@@ -98,11 +103,11 @@ pub fn insn_name(id: crate::insn::InsnId) -> Option<&'static str> {pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Ret => Some("ret"),- GroupId::Int => Some("int"),- GroupId::Arch(1) => Some("fence"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Ret => Some("ret"),+ GroupId::Int => Some("int"),+ GroupId::Arch(1) => Some("fence"),_ => None,}}@@ -123,40 +128,44 @@ mod tests {#[test]fn riscv_addi_and_lui() {let dec = rv64();- // addi x5, x0, 42 => 0x02a00293+ // addi x5, x0, 42 => 0x02a00293let addi = [0x93, 0x02, 0xa0, 0x02];let insn = dec.decode_one(&addi, 0, &EngineOptions::default()).unwrap();- assert_eq!(insn.mnemonic, "addi");+ assert_eq!(insn.mnemonic, "addi");assert_eq!(insn.length, 4);- // lui x5, 0x12345 => imm << 12+ // lui x5, 0x12345 => imm << 12let lui = [0xb7, 0x02, 0x45, 0x12];let insn = dec.decode_one(&lui, 0, &EngineOptions::default()).unwrap();- assert_eq!(insn.mnemonic, "lui");+ assert_eq!(insn.mnemonic, "lui");}#[test]fn riscv_branch_and_load() {let dec = rv64();- // beq x10, x11, offset => example encoding+ // beq x10, x11, offset => example encodinglet beq = [0x63, 0x06, 0xb5, 0x00];- let insn = dec.decode_one(&beq, 0x1000, &EngineOptions::default()).unwrap();- assert_eq!(insn.mnemonic, "beq");+ let insn = dec+ .decode_one(&beq, 0x1000, &EngineOptions::default())+ .unwrap();+ assert_eq!(insn.mnemonic, "beq");- // ld x5, 8(x10)+ // ld x5, 8(x10)let ld = [0x83, 0x32, 0x85, 0x08];let insn = dec.decode_one(&ld, 0, &EngineOptions::default()).unwrap();- assert_eq!(insn.mnemonic, "ld");+ assert_eq!(insn.mnemonic, "ld");}#[test]fn riscv_compressed_addi() {let dec = rv64();- // c.addi a0, 1+ // c.addi a0, 1let bytes = [0x05, 0x05];- let insn = dec.decode_one(&bytes, 0, &EngineOptions::default()).unwrap();- assert_eq!(insn.mnemonic, "c.addi");- assert_eq!(insn.operands, "a0, 1");+ let insn = dec+ .decode_one(&bytes, 0, &EngineOptions::default())+ .unwrap();+ assert_eq!(insn.mnemonic, "c.addi");+ assert_eq!(insn.operands, "a0, 1");assert_eq!(insn.length, 2);}}diff --git a/crates/ghidrust-decode/src/arch/riscv/regs.rs b/crates/ghidrust-decode/src/arch/riscv/regs.rsindex 734ff7e..c8b149b 100644--- a/crates/ghidrust-decode/src/arch/riscv/regs.rs+++ b/crates/ghidrust-decode/src/arch/riscv/regs.rs@@ -2,42 +2,42 @@ use crate::reg::RegId;pub fn reg_name(reg: RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("zero"),- 1 => Some("ra"),- 2 => Some("sp"),- 3 => Some("gp"),- 4 => Some("tp"),- 5 => Some("t0"),- 6 => Some("t1"),- 7 => Some("t2"),- 8 => Some("s0"),- 9 => Some("s1"),- 10 => Some("a0"),- 11 => Some("a1"),- 12 => Some("a2"),- 13 => Some("a3"),- 14 => Some("a4"),- 15 => Some("a5"),- 16 => Some("a6"),- 17 => Some("a7"),- 18 => Some("s2"),- 19 => Some("s3"),- 20 => Some("s4"),- 21 => Some("s5"),- 22 => Some("s6"),- 23 => Some("s7"),- 24 => Some("s8"),- 25 => Some("s9"),- 26 => Some("s10"),- 27 => Some("s11"),- 28 => Some("t3"),- 29 => Some("t4"),- 30 => Some("t5"),- 31 => Some("t6"),+ 0 => Some("zero"),+ 1 => Some("ra"),+ 2 => Some("sp"),+ 3 => Some("gp"),+ 4 => Some("tp"),+ 5 => Some("t0"),+ 6 => Some("t1"),+ 7 => Some("t2"),+ 8 => Some("s0"),+ 9 => Some("s1"),+ 10 => Some("a0"),+ 11 => Some("a1"),+ 12 => Some("a2"),+ 13 => Some("a3"),+ 14 => Some("a4"),+ 15 => Some("a5"),+ 16 => Some("a6"),+ 17 => Some("a7"),+ 18 => Some("s2"),+ 19 => Some("s3"),+ 20 => Some("s4"),+ 21 => Some("s5"),+ 22 => Some("s6"),+ 23 => Some("s7"),+ 24 => Some("s8"),+ 25 => Some("s9"),+ 26 => Some("s10"),+ 27 => Some("s11"),+ 28 => Some("t3"),+ 29 => Some("t4"),+ 30 => Some("t5"),+ 31 => Some("t6"),_ => None,}}pub fn reg_name_num(n: u32) -> &'static str {- reg_name(RegId::new(n)).unwrap_or("?")+ reg_name(RegId::new(n)).unwrap_or("?")}diff --git a/crates/ghidrust-decode/src/arch/sh/decode.rs b/crates/ghidrust-decode/src/arch/sh/decode.rsindex f9a1290..25f3696 100644--- a/crates/ghidrust-decode/src/arch/sh/decode.rs+++ b/crates/ghidrust-decode/src/arch/sh/decode.rs@@ -1,21 +1,21 @@use crate::error::{Error, Result};pub fn r(n: u32) -> String {- format!("r{n}")+ format!("r{n}")}pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("r0"),- 1 => Some("r1"),- 15 => Some("r15"),+ 0 => Some("r0"),+ 1 => Some("r1"),+ 15 => Some("r15"),_ => None,}}pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usize)> {if bytes.len() < 2 {- return Err(Error::Decode("truncated sh input".into()));+ return Err(Error::Decode("truncated sh input".into()));}let h = if little_endian {u16::from_le_bytes([bytes[0], bytes[1]])@@ -24,34 +24,38 @@ pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usiz};match h {- 0x000b => Ok(("rts".into(), String::new(), 2)),- 0x0023 => Ok(("bfs".into(), String::new(), 2)),- 0x0008 => Ok(("clrt".into(), String::new(), 2)),+ 0x000b => Ok(("rts".into(), String::new(), 2)),+ 0x0023 => Ok(("bfs".into(), String::new(), 2)),+ 0x0008 => Ok(("clrt".into(), String::new(), 2)),_ if (h & 0xf00f) == 0x6003 => {let dst = (h >> 8) & 0xf;let src = (h >> 4) & 0xf;- Ok(("mov.l".into(), format!("{}, {}", r(u32::from(dst)), r(u32::from(src))), 2))+ Ok((+ "mov.l".into(),+ format!("{}, {}", r(u32::from(dst)), r(u32::from(src))),+ 2,+ ))}_ if (h & 0xf000) == 0x7000 => {let reg = (h >> 8) & 0xf;let imm = h as i8 as i64;- Ok(("add".into(), format!("#{imm}, {}", r(u32::from(reg))), 2))+ Ok(("add".into(), format!("#{imm}, {}", r(u32::from(reg))), 2))}_ if (h & 0xf000) == 0x8000 => {let disp = (h & 0x0fff) as i16 as i64;- Ok(("bra".into(), format!("{disp}"), 2))+ Ok(("bra".into(), format!("{disp}"), 2))}_ if (h & 0xf0ff) == 0x4003 => {let reg = (h >> 8) & 0xf;- Ok(("jsr".into(), format!("@{}", r(u32::from(reg))), 2))+ Ok(("jsr".into(), format!("@{}", r(u32::from(reg))), 2))}_ if (h & 0xf000) == 0x6000 && (h & 0x000f) == 0x0002 => {let dst = (h >> 8) & 0xf;let base = (h >> 4) & 0xf;let disp = ((h >> 4) & 0xf) as i64 * 4;Ok((- "mov.l".into(),- format!("@({disp}, {}), {}", r(u32::from(base)), r(u32::from(dst))),+ "mov.l".into(),+ format!("@({disp}, {}), {}", r(u32::from(base)), r(u32::from(dst))),2,))}@@ -60,12 +64,12 @@ pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usizlet base = (h >> 4) & 0xf;let disp = (h & 0xf) as i64 * 4;Ok((- "mov.l".into(),- format!("{}, @({disp}, {})", r(u32::from(dst)), r(u32::from(base))),+ "mov.l".into(),+ format!("{}, @({disp}, {})", r(u32::from(dst)), r(u32::from(base))),2,))}- _ => Err(Error::Decode("unsupported sh opcode".into())),+ _ => Err(Error::Decode("unsupported sh opcode".into())),}}@@ -75,10 +79,10 @@ mod tests {#[test]fn sh_mov() {- // mov.l r0, r1 => 0x6003 | (1<<8) | (0<<4) = 0x6103+ // mov.l r0, r1 => 0x6003 | (1<<8) | (0<<4) = 0x6103let (m, o, l) = decode(&[0x03, 0x61], true).unwrap();- assert_eq!(m, "mov.l");+ assert_eq!(m, "mov.l");assert_eq!(l, 2);- assert!(o.contains("r1"));+ assert!(o.contains("r1"));}}diff --git a/crates/ghidrust-decode/src/arch/sh/mod.rs b/crates/ghidrust-decode/src/arch/sh/mod.rsindex 2ff7f98..afb0208 100644--- a/crates/ghidrust-decode/src/arch/sh/mod.rs+++ b/crates/ghidrust-decode/src/arch/sh/mod.rs@@ -21,7 +21,7 @@ impl ArchDecode for ShDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Sh) {- return Err(Error::Mode(format!("invalid sh mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!("invalid sh mode {:#x}", mode.bits())));}let little_endian = !mode.contains(Mode::BIG_ENDIAN);Ok(Self { little_endian })@@ -49,44 +49,44 @@ impl ArchDecode for ShDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "jsr" => vec![GroupId::Call],- "bra" | "bfs" => vec![GroupId::Jump],- "rts" => vec![GroupId::Ret],- m if m.starts_with("mov") => vec![GroupId::Arch(1)],- "add" => vec![GroupId::Arch(2)],+ "jsr" => vec![GroupId::Call],+ "bra" | "bfs" => vec![GroupId::Jump],+ "rts" => vec![GroupId::Ret],+ m if m.starts_with("mov") => vec![GroupId::Arch(1)],+ "add" => vec![GroupId::Arch(2)],_ => Vec::new(),}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("mov.l"),- 2 => Some("add"),- 3 => Some("bra"),- 4 => Some("jsr"),- 5 => Some("rts"),+ 1 => Some("mov.l"),+ 2 => Some("add"),+ 3 => Some("bra"),+ 4 => Some("jsr"),+ 5 => Some("rts"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Ret => Some("ret"),- GroupId::Arch(1) => Some("move"),- GroupId::Arch(2) => Some("alu"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Ret => Some("ret"),+ GroupId::Arch(1) => Some("move"),+ GroupId::Arch(2) => Some("alu"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- m if m.starts_with("mov") => 1,- "add" => 2,- "bra" | "bfs" => 3,- "jsr" => 4,- "rts" => 5,+ m if m.starts_with("mov") => 1,+ "add" => 2,+ "bra" | "bfs" => 3,+ "jsr" => 4,+ "rts" => 5,_ => 0,};InsnId(id)@@ -101,19 +101,19 @@ mod tests {fn sh_mov_and_add() {let mut eng = Engine::open(Arch::Sh, Mode::LITTLE_ENDIAN).unwrap();let mov = eng.disasm_one(&[0x03, 0x61], 0).unwrap();- assert_eq!(mov.mnemonic, "mov.l");- // add #1, r0 => 0x7101+ assert_eq!(mov.mnemonic, "mov.l");+ // add #1, r0 => 0x7101let add = eng.disasm_one(&[0x01, 0x71], 0).unwrap();- assert_eq!(add.mnemonic, "add");+ assert_eq!(add.mnemonic, "add");}#[test]fn sh_bra_and_rts() {let mut eng = Engine::open(Arch::Sh, Mode::LITTLE_ENDIAN).unwrap();- // bra +4 => 0x8004+ // bra +4 => 0x8004let bra = eng.disasm_one(&[0x04, 0x80], 0).unwrap();- assert_eq!(bra.mnemonic, "bra");+ assert_eq!(bra.mnemonic, "bra");let rts = eng.disasm_one(&[0x0b, 0x00], 0).unwrap();- assert_eq!(rts.mnemonic, "rts");+ assert_eq!(rts.mnemonic, "rts");}}diff --git a/crates/ghidrust-decode/src/arch/sparc/decode.rs b/crates/ghidrust-decode/src/arch/sparc/decode.rsindex 26b791f..8781bb3 100644--- a/crates/ghidrust-decode/src/arch/sparc/decode.rs+++ b/crates/ghidrust-decode/src/arch/sparc/decode.rs@@ -2,13 +2,13 @@ use super::regs::g_reg;use crate::error::{Error, Result};const COND: [&str; 16] = [- "bn", "be", "ble", "bl", "bleu", "bcs", "bvs", "ba", "bt", "bne", "bg", "bge", "bgu", "bcc",- "bvc", "bn",+ "bn", "be", "ble", "bl", "bleu", "bcs", "bvs", "ba", "bt", "bne", "bg", "bge", "bgu", "bcc",+ "bvc", "bn",];pub fn read_word(bytes: &[u8], big_endian: bool) -> Result<u32> {if bytes.len() < 4 {- return Err(Error::Decode("truncated sparc instruction".into()));+ return Err(Error::Decode("truncated sparc instruction".into()));}Ok(if big_endian {u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])@@ -23,11 +23,11 @@ pub fn decode(word: u32, address: u64) -> Result<(String, String)> {1 => {let disp = sign_ext(word & 0x3fff_ffff, 30);let target = address.wrapping_add((disp << 2) as u64);- Ok(("call".into(), format!("0x{target:x}")))+ Ok(("call".into(), format!("0x{target:x}")))}2 => decode_op2(word),3 => decode_mem(word),- _ => Err(Error::Decode("unsupported sparc opcode".into())),+ _ => Err(Error::Decode("unsupported sparc opcode".into())),}}@@ -36,21 +36,18 @@ fn decode_op0(word: u32, address: u64) -> Result<(String, String)> {let rd = (word >> 25) & 0x1f;let imm22 = word & 0x003f_ffff;let imm = u64::from(imm22) << 10;- Ok((- "sethi".into(),- format!("{}, 0x{imm:x}", g_reg(rd)),- ))+ Ok(("sethi".into(), format!("{}, 0x{imm:x}", g_reg(rd))))} else if (word >> 22) & 1 == 0 {let cond = ((word >> 25) & 0xf) as usize;- let a = if (word >> 29) & 1 != 0 { ",a" } else { "" };+ let a = if (word >> 29) & 1 != 0 { ",a" } else { "" };let disp = sign_ext(word & 0x003f_ffff, 22);let target = address.wrapping_add((disp << 2) as u64);Ok((- format!("{}{a}", COND[cond.min(15)]),- format!("0x{target:x}"),+ format!("{}{a}", COND[cond.min(15)]),+ format!("0x{target:x}"),))} else {- Err(Error::Decode("unsupported sparc op0".into()))+ Err(Error::Decode("unsupported sparc op0".into()))}}@@ -60,7 +57,7 @@ fn decode_op2(word: u32) -> Result<(String, String)> {let rs1 = (word >> 14) & 0x1f;let i = (word >> 13) & 1;let rs2_or_imm = if i != 0 {- format!("{}", sign_ext(word & 0x1fff, 13))+ format!("{}", sign_ext(word & 0x1fff, 13))} else {g_reg(word & 0x1f)};@@ -68,39 +65,36 @@ fn decode_op2(word: u32) -> Result<(String, String)> {match op3 {0x00 | 0x01 | 0x02 | 0x03 => {let name = match op3 {- 0x00 => "add",- 0x01 => "and",- 0x02 => "or",- 0x03 => "xor",+ 0x00 => "add",+ 0x01 => "and",+ 0x02 => "or",+ 0x03 => "xor",_ => unreachable!(),};Ok((name.into(),- format!("{}, {}, {rs2_or_imm}", g_reg(rd), g_reg(rs1)),+ format!("{}, {}, {rs2_or_imm}", g_reg(rd), g_reg(rs1)),))}0x04 | 0x05 | 0x06 | 0x07 => {let name = match op3 {- 0x04 => "sub",- 0x05 => "andn",- 0x06 => "orn",- 0x07 => "xnor",+ 0x04 => "sub",+ 0x05 => "andn",+ 0x06 => "orn",+ 0x07 => "xnor",_ => unreachable!(),};Ok((name.into(),- format!("{}, {}, {rs2_or_imm}", g_reg(rd), g_reg(rs1)),+ format!("{}, {}, {rs2_or_imm}", g_reg(rd), g_reg(rs1)),))}0x38 => Ok((- "jmpl".into(),- format!("{}, {rs2_or_imm}, {}", g_reg(rs1), g_reg(rd)),- )),- 0x39 => Ok((- "rett".into(),- format!("{}, {rs2_or_imm}", g_reg(rs1)),+ "jmpl".into(),+ format!("{}, {rs2_or_imm}, {}", g_reg(rs1), g_reg(rd)),)),- _ => Err(Error::Decode("unsupported sparc alu".into())),+ 0x39 => Ok(("rett".into(), format!("{}, {rs2_or_imm}", g_reg(rs1)))),+ _ => Err(Error::Decode("unsupported sparc alu".into())),}}@@ -111,33 +105,33 @@ fn decode_mem(word: u32) -> Result<(String, String)> {let i = (word >> 13) & 1;let addr = if i != 0 {let simm = sign_ext(word & 0x1fff, 13);- format!("{}, {simm}", g_reg(rs1))+ format!("{}, {simm}", g_reg(rs1))} else {- format!("{}, {}", g_reg(rs1), g_reg(word & 0x1f))+ format!("{}, {}", g_reg(rs1), g_reg(word & 0x1f))};let (name, is_load) = match op3 {- 0x00 => ("ld", true),- 0x01 => ("ldsb", true),- 0x02 => ("ldsh", true),- 0x03 => ("ldsw", true),- 0x08 => ("ldd", true),- 0x09 => ("ldub", true),- 0x0a => ("lduh", true),- 0x0b => ("ldx", true),- 0x04 => ("st", false),- 0x05 => ("stb", false),- 0x06 => ("sth", false),- 0x07 => ("stsw", false),- 0x0c => ("std", false),- 0x0d => ("stub", false),- 0x0e => ("stuh", false),- 0x0f => ("stx", false),- _ => return Err(Error::Decode("unsupported sparc mem".into())),+ 0x00 => ("ld", true),+ 0x01 => ("ldsb", true),+ 0x02 => ("ldsh", true),+ 0x03 => ("ldsw", true),+ 0x08 => ("ldd", true),+ 0x09 => ("ldub", true),+ 0x0a => ("lduh", true),+ 0x0b => ("ldx", true),+ 0x04 => ("st", false),+ 0x05 => ("stb", false),+ 0x06 => ("sth", false),+ 0x07 => ("stsw", false),+ 0x0c => ("std", false),+ 0x0d => ("stub", false),+ 0x0e => ("stuh", false),+ 0x0f => ("stx", false),+ _ => return Err(Error::Decode("unsupported sparc mem".into())),};if is_load {- Ok((name.into(), format!("[{addr}], {}", g_reg(rd))))+ Ok((name.into(), format!("[{addr}], {}", g_reg(rd))))} else {- Ok((name.into(), format!("{}, [{addr}]", g_reg(rd))))+ Ok((name.into(), format!("{}, [{addr}]", g_reg(rd))))}}@@ -152,10 +146,10 @@ mod tests {#[test]fn sparc_sethi_encoding() {- // sethi %g1, 0x40000 => imm22=0x100+ // sethi %g1, 0x40000 => imm22=0x100let word = 0x0300_0100;let (m, o) = decode(word, 0).unwrap();- assert_eq!(m, "sethi");- assert!(o.contains("g1"));+ assert_eq!(m, "sethi");+ assert!(o.contains("g1"));}}diff --git a/crates/ghidrust-decode/src/arch/sparc/mod.rs b/crates/ghidrust-decode/src/arch/sparc/mod.rsindex 5e60474..904140a 100644--- a/crates/ghidrust-decode/src/arch/sparc/mod.rs+++ b/crates/ghidrust-decode/src/arch/sparc/mod.rs@@ -22,7 +22,10 @@ impl ArchDecode for SparcDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Sparc) {- return Err(Error::Mode(format!("invalid sparc mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!(+ "invalid sparc mode {:#x}",+ mode.bits()+ )));}let big_endian = mode.contains(Mode::BIG_ENDIAN);Ok(Self { big_endian })@@ -31,13 +34,7 @@ impl ArchDecode for SparcDecoder {fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {let word = decode::read_word(bytes, self.big_endian)?;let (mnemonic, operands) = decode::decode(word, address)?;- let mut insn = Instruction::with_text(- address,- bytes[..4].to_vec(),- mnemonic,- operands,- 4,- );+ let mut insn = Instruction::with_text(address, bytes[..4].to_vec(), mnemonic, operands, 4);insn.id = names::insn_id_for_mnemonic(Arch::Sparc, &insn.mnemonic);if opts.detail {insn.detail = Some(InsnDetail {@@ -51,50 +48,50 @@ impl ArchDecode for SparcDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "call" | "jmpl" => vec![GroupId::Call],- m if m.starts_with('b') => vec![GroupId::Jump],- "rett" => vec![GroupId::Ret],- m if m.starts_with("ld") => vec![GroupId::Arch(1)],- m if m.starts_with("st") => vec![GroupId::Arch(2)],+ "call" | "jmpl" => vec![GroupId::Call],+ m if m.starts_with('b') => vec![GroupId::Jump],+ "rett" => vec![GroupId::Ret],+ m if m.starts_with("ld") => vec![GroupId::Arch(1)],+ m if m.starts_with("st") => vec![GroupId::Arch(2)],_ => Vec::new(),}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("sethi"),- 2 => Some("call"),- 3 => Some("add"),- 4 => Some("ld"),- 5 => Some("st"),- 6 => Some("jmpl"),- 7 => Some("rett"),- 8 => Some("ba"),+ 1 => Some("sethi"),+ 2 => Some("call"),+ 3 => Some("add"),+ 4 => Some("ld"),+ 5 => Some("st"),+ 6 => Some("jmpl"),+ 7 => Some("rett"),+ 8 => Some("ba"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Ret => Some("ret"),- GroupId::Arch(1) => Some("load"),- GroupId::Arch(2) => Some("store"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Ret => Some("ret"),+ GroupId::Arch(1) => Some("load"),+ GroupId::Arch(2) => Some("store"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "sethi" => 1,- "call" => 2,- "add" | "sub" | "and" | "or" | "xor" => 3,- "ld" | "ldsb" | "ldsh" | "ldsw" | "ldd" | "ldub" | "lduh" | "ldx" => 4,- "st" | "stb" | "sth" | "std" | "stx" => 5,- "jmpl" => 6,- "rett" => 7,- m if m.starts_with('b') => 8,+ "sethi" => 1,+ "call" => 2,+ "add" | "sub" | "and" | "or" | "xor" => 3,+ "ld" | "ldsb" | "ldsh" | "ldsw" | "ldd" | "ldub" | "lduh" | "ldx" => 4,+ "st" | "stb" | "sth" | "std" | "stx" => 5,+ "jmpl" => 6,+ "rett" => 7,+ m if m.starts_with('b') => 8,_ => 0,};InsnId(id)@@ -108,22 +105,22 @@ mod tests {#[test]fn sparc_sethi_and_add() {let mut eng = Engine::open(Arch::Sparc, Mode::V9.union(Mode::BIG_ENDIAN)).unwrap();- // sethi %g1, 0x40000 => 0x03000100+ // sethi %g1, 0x40000 => 0x03000100let sethi = eng.disasm_one(&[0x03, 0x00, 0x01, 0x00], 0).unwrap();- assert_eq!(sethi.mnemonic, "sethi");- // add %g1, %g2, %g3 => 0x86004002+ assert_eq!(sethi.mnemonic, "sethi");+ // add %g1, %g2, %g3 => 0x86004002let add = eng.disasm_one(&[0x86, 0x00, 0x40, 0x02], 0).unwrap();- assert_eq!(add.mnemonic, "add");+ assert_eq!(add.mnemonic, "add");}#[test]fn sparc_call_and_branch() {let mut eng = Engine::open(Arch::Sparc, Mode::V9.union(Mode::BIG_ENDIAN)).unwrap();- // call 0x1000 from 0: disp30=0x400 => 0x40000400+ // call 0x1000 from 0: disp30=0x400 => 0x40000400let call = eng.disasm_one(&[0x40, 0x00, 0x04, 0x00], 0).unwrap();- assert_eq!(call.mnemonic, "call");- // ba +8 from 4: cond=7, disp22=1 => 0x0e000001+ assert_eq!(call.mnemonic, "call");+ // ba +8 from 4: cond=7, disp22=1 => 0x0e000001let ba = eng.disasm_one(&[0x0e, 0x00, 0x00, 0x01], 4).unwrap();- assert_eq!(ba.mnemonic, "ba");+ assert_eq!(ba.mnemonic, "ba");}}diff --git a/crates/ghidrust-decode/src/arch/sysz/decode.rs b/crates/ghidrust-decode/src/arch/sysz/decode.rsindex e35eba1..3dd4fc1 100644--- a/crates/ghidrust-decode/src/arch/sysz/decode.rs+++ b/crates/ghidrust-decode/src/arch/sysz/decode.rs@@ -3,55 +3,47 @@ use crate::error::{Error, Result};pub fn decode(bytes: &[u8], big_endian: bool) -> Result<(String, String, usize)> {if bytes.is_empty() {- return Err(Error::Decode("empty sysz input".into()));+ return Err(Error::Decode("empty sysz input".into()));}let op = bytes[0];match op {0x07 => decode_bcr(bytes),- 0x18 => decode_rr(bytes, "lr"),- 0x1a => decode_rr(bytes, "ar"),- 0x1b => decode_rr(bytes, "sr"),- 0x58 => decode_rx(bytes, "l", big_endian),- 0x50 => decode_rx(bytes, "st", big_endian),- 0x41 => decode_si(bytes, "la", big_endian),- 0xa7 => decode_si(bytes, "tm", big_endian),- _ => Err(Error::Decode("unsupported sysz opcode".into())),+ 0x18 => decode_rr(bytes, "lr"),+ 0x1a => decode_rr(bytes, "ar"),+ 0x1b => decode_rr(bytes, "sr"),+ 0x58 => decode_rx(bytes, "l", big_endian),+ 0x50 => decode_rx(bytes, "st", big_endian),+ 0x41 => decode_si(bytes, "la", big_endian),+ 0xa7 => decode_si(bytes, "tm", big_endian),+ _ => Err(Error::Decode("unsupported sysz opcode".into())),}}fn decode_rr(bytes: &[u8], name: &str) -> Result<(String, String, usize)> {if bytes.len() < 2 {- return Err(Error::Decode("truncated sysz rr".into()));+ return Err(Error::Decode("truncated sysz rr".into()));}let r1 = (bytes[1] >> 4) & 0xf;let r2 = bytes[1] & 0xf;- Ok((- name.into(),- format!("{}, {}", g_reg(r1), g_reg(r2)),- 2,- ))+ Ok((name.into(), format!("{}, {}", g_reg(r1), g_reg(r2)), 2))}fn decode_bcr(bytes: &[u8]) -> Result<(String, String, usize)> {if bytes.len() < 2 {- return Err(Error::Decode("truncated sysz bcr".into()));+ return Err(Error::Decode("truncated sysz bcr".into()));}let mask = (bytes[1] >> 4) & 0xf;let r1 = bytes[1] & 0xf;if mask == 0xf && r1 == 0 {- Ok(("br".into(), String::new(), 2))+ Ok(("br".into(), String::new(), 2))} else {- Ok((- "bcr".into(),- format!("{mask}, {}", g_reg(r1)),- 2,- ))+ Ok(("bcr".into(), format!("{mask}, {}", g_reg(r1)), 2))}}fn decode_rx(bytes: &[u8], name: &str, big_endian: bool) -> Result<(String, String, usize)> {if bytes.len() < 4 {- return Err(Error::Decode("truncated sysz rx".into()));+ return Err(Error::Decode("truncated sysz rx".into()));}let r1 = bytes[3] & 0xf;let x2 = (bytes[3] >> 4) & 0xf;@@ -64,23 +56,23 @@ fn decode_rx(bytes: &[u8], name: &str, big_endian: bool) -> Result<(String, Strilet base = if b2 == 0 {String::new()} else {- format!("({})", g_reg(b2))+ format!("({})", g_reg(b2))};let index = if x2 == 0 {String::new()} else {- format!("{}, ", g_reg(x2))+ format!("{}, ", g_reg(x2))};Ok((name.into(),- format!("{}, {index}{disp}{base}", g_reg(r1)),+ format!("{}, {index}{disp}{base}", g_reg(r1)),4,))}fn decode_si(bytes: &[u8], name: &str, big_endian: bool) -> Result<(String, String, usize)> {if bytes.len() < 4 {- return Err(Error::Decode("truncated sysz si".into()));+ return Err(Error::Decode("truncated sysz si".into()));}let r1 = bytes[1] & 0xf;let b2 = (bytes[1] >> 4) & 0xf;@@ -91,7 +83,7 @@ fn decode_si(bytes: &[u8], name: &str, big_endian: bool) -> Result<(String, Stri};Ok((name.into(),- format!("{}, {disp}({})", g_reg(r1), g_reg(b2)),+ format!("{}, {disp}({})", g_reg(r1), g_reg(b2)),4,))}diff --git a/crates/ghidrust-decode/src/arch/sysz/mod.rs b/crates/ghidrust-decode/src/arch/sysz/mod.rsindex 4073ea8..0ac943c 100644--- a/crates/ghidrust-decode/src/arch/sysz/mod.rs+++ b/crates/ghidrust-decode/src/arch/sysz/mod.rs@@ -22,7 +22,7 @@ impl ArchDecode for SyszDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Sysz) {- return Err(Error::Mode(format!("invalid sysz mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!("invalid sysz mode {:#x}", mode.bits())));}let big_endian = !mode.intersects(Mode::LITTLE_ENDIAN) || mode.contains(Mode::BIG_ENDIAN);Ok(Self { big_endian })@@ -50,44 +50,44 @@ impl ArchDecode for SyszDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "bcr" | "br" => vec![GroupId::Jump],- "l" | "la" => vec![GroupId::Arch(1)],- "st" => vec![GroupId::Arch(2)],- "ar" | "sr" => vec![GroupId::Arch(3)],+ "bcr" | "br" => vec![GroupId::Jump],+ "l" | "la" => vec![GroupId::Arch(1)],+ "st" => vec![GroupId::Arch(2)],+ "ar" | "sr" => vec![GroupId::Arch(3)],_ => Vec::new(),}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("lr"),- 2 => Some("l"),- 3 => Some("st"),- 4 => Some("bcr"),- 5 => Some("br"),- 6 => Some("ar"),+ 1 => Some("lr"),+ 2 => Some("l"),+ 3 => Some("st"),+ 4 => Some("bcr"),+ 5 => Some("br"),+ 6 => Some("ar"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Arch(1) => Some("load"),- GroupId::Arch(2) => Some("store"),- GroupId::Arch(3) => Some("alu"),+ GroupId::Jump => Some("jump"),+ GroupId::Arch(1) => Some("load"),+ GroupId::Arch(2) => Some("store"),+ GroupId::Arch(3) => Some("alu"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "lr" => 1,- "l" | "la" => 2,- "st" => 3,- "bcr" => 4,- "br" => 5,- "ar" | "sr" => 6,+ "lr" => 1,+ "l" | "la" => 2,+ "st" => 3,+ "bcr" => 4,+ "br" => 5,+ "ar" | "sr" => 6,_ => 0,};InsnId(id)@@ -101,22 +101,22 @@ mod tests {#[test]fn sysz_lr_and_ar() {let mut eng = Engine::open(Arch::Sysz, Mode::BIG_ENDIAN).unwrap();- // LR r1, r2 => 0x18 0x12+ // LR r1, r2 => 0x18 0x12let lr = eng.disasm_one(&[0x18, 0x12], 0).unwrap();- assert_eq!(lr.mnemonic, "lr");- // AR r3, r4 => 0x1a 0x34+ assert_eq!(lr.mnemonic, "lr");+ // AR r3, r4 => 0x1a 0x34let ar = eng.disasm_one(&[0x1a, 0x34], 0).unwrap();- assert_eq!(ar.mnemonic, "ar");+ assert_eq!(ar.mnemonic, "ar");}#[test]fn sysz_br_and_l() {let mut eng = Engine::open(Arch::Sysz, Mode::BIG_ENDIAN).unwrap();- // BR => BCR 15, 0 => 0x07 0xf0+ // BR => BCR 15, 0 => 0x07 0xf0let br = eng.disasm_one(&[0x07, 0xf0], 0).unwrap();- assert_eq!(br.mnemonic, "br");- // L r3, 0(,r4) => 58 40 00 03+ assert_eq!(br.mnemonic, "br");+ // L r3, 0(,r4) => 58 40 00 03let l = eng.disasm_one(&[0x58, 0x40, 0x00, 0x03], 0).unwrap();- assert_eq!(l.mnemonic, "l");+ assert_eq!(l.mnemonic, "l");}}diff --git a/crates/ghidrust-decode/src/arch/sysz/regs.rs b/crates/ghidrust-decode/src/arch/sysz/regs.rsindex 611e116..61f63c3 100644--- a/crates/ghidrust-decode/src/arch/sysz/regs.rs+++ b/crates/ghidrust-decode/src/arch/sysz/regs.rs@@ -1,14 +1,14 @@pub fn g_reg(n: u8) -> String {- format!("r{n}")+ format!("r{n}")}pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("r0"),- 1 => Some("r1"),- 2 => Some("r2"),- 14 => Some("r14"),- 15 => Some("r15"),+ 0 => Some("r0"),+ 1 => Some("r1"),+ 2 => Some("r2"),+ 14 => Some("r14"),+ 15 => Some("r15"),_ => None,}}diff --git a/crates/ghidrust-decode/src/arch/tms320c64x/decode.rs b/crates/ghidrust-decode/src/arch/tms320c64x/decode.rsindex c6cbb4f..fc3d8bc 100644--- a/crates/ghidrust-decode/src/arch/tms320c64x/decode.rs+++ b/crates/ghidrust-decode/src/arch/tms320c64x/decode.rs@@ -2,16 +2,16 @@ use crate::error::{Error, Result};pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("a0"),- 1 => Some("a1"),- 2 => Some("b0"),+ 0 => Some("a0"),+ 1 => Some("a1"),+ 2 => Some("b0"),_ => None,}}pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usize)> {if bytes.len() < 4 {- return Err(Error::Decode("truncated c64x instruction".into()));+ return Err(Error::Decode("truncated c64x instruction".into()));}let word = if little_endian {u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])@@ -25,54 +25,34 @@ pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usizlet p = (word >> 31) & 1;if opcode == 0 && ((word >> 5) & 0x7f) == 0x02 {- // MV instruction family+ // MV instruction familylet unit = match creg {- 0 => "s",- 1 => "l",- 2 => "d",- 3 => "m",- _ => "x",+ 0 => "s",+ 1 => "l",+ 2 => "d",+ 3 => "m",+ _ => "x",};- Ok((- format!("mv.{unit}"),- format!("a{dst}, a{src}"),- 4,- ))+ Ok((format!("mv.{unit}"), format!("a{dst}, a{src}"), 4))} else if (word >> 28) & 0xf == 0x1 {let offset = sign_ext((word >> 7) & 0x1ffff, 17);Ok((- if p != 0 { "b.s".into() } else { "b".into() },- format!("{offset}"),+ if p != 0 { "b.s".into() } else { "b".into() },+ format!("{offset}"),4,))} else if (word >> 28) & 0xf == 0x2 {- Ok((- "add.l".into(),- format!("a{dst}, a{src}, a{dst}"),- 4,- ))+ Ok(("add.l".into(), format!("a{dst}, a{src}, a{dst}"), 4))} else if (word >> 28) & 0xf == 0x3 {- Ok((- "sub.l".into(),- format!("a{dst}, a{src}, a{dst}"),- 4,- ))+ Ok(("sub.l".into(), format!("a{dst}, a{src}, a{dst}"), 4))} else if (word >> 28) & 0xf == 0x4 {let off = (word >> 7) & 0x7fff;- Ok((- "ldw".into(),- format!("*+a{src}[{off}], a{dst}"),- 4,- ))+ Ok(("ldw".into(), format!("*+a{src}[{off}], a{dst}"), 4))} else if (word >> 28) & 0xf == 0x5 {let off = (word >> 7) & 0x7fff;- Ok((- "stw".into(),- format!("a{src}, *+a{dst}[{off}]"),- 4,- ))+ Ok(("stw".into(), format!("a{src}, *+a{dst}[{off}]"), 4))} else {- Err(Error::Decode("unsupported c64x opcode".into()))+ Err(Error::Decode("unsupported c64x opcode".into()))}}@@ -87,11 +67,11 @@ mod tests {#[test]fn c64x_mv() {- // mv.l a2, a1 pattern+ // mv.l a2, a1 patternlet word = 0x0200_0041u32;let bytes = word.to_le_bytes();let (m, _, l) = decode(&bytes, true).unwrap();assert_eq!(l, 4);- assert!(m.starts_with("mv."));+ assert!(m.starts_with("mv."));}}diff --git a/crates/ghidrust-decode/src/arch/tms320c64x/mod.rs b/crates/ghidrust-decode/src/arch/tms320c64x/mod.rsindex 1f00c58..8a7ceb1 100644--- a/crates/ghidrust-decode/src/arch/tms320c64x/mod.rs+++ b/crates/ghidrust-decode/src/arch/tms320c64x/mod.rs@@ -22,7 +22,7 @@ impl ArchDecode for Tms320c64xDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Tms320c64x) {return Err(Error::Mode(format!(- "invalid tms320c64x mode {:#x}",+ "invalid tms320c64x mode {:#x}",mode.bits())));}@@ -52,45 +52,45 @@ impl ArchDecode for Tms320c64xDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "b" | "b.s" => vec![GroupId::Jump],- "ldw" => vec![GroupId::Arch(1)],- "stw" => vec![GroupId::Arch(2)],- m if m.starts_with("add") || m.starts_with("sub") => vec![GroupId::Arch(3)],- m if m.starts_with("mv.") => vec![GroupId::Arch(4)],+ "b" | "b.s" => vec![GroupId::Jump],+ "ldw" => vec![GroupId::Arch(1)],+ "stw" => vec![GroupId::Arch(2)],+ m if m.starts_with("add") || m.starts_with("sub") => vec![GroupId::Arch(3)],+ m if m.starts_with("mv.") => vec![GroupId::Arch(4)],_ => Vec::new(),}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("mv.l"),- 2 => Some("add.l"),- 3 => Some("b"),- 4 => Some("ldw"),- 5 => Some("stw"),+ 1 => Some("mv.l"),+ 2 => Some("add.l"),+ 3 => Some("b"),+ 4 => Some("ldw"),+ 5 => Some("stw"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Arch(1) => Some("load"),- GroupId::Arch(2) => Some("store"),- GroupId::Arch(3) => Some("alu"),- GroupId::Arch(4) => Some("move"),+ GroupId::Jump => Some("jump"),+ GroupId::Arch(1) => Some("load"),+ GroupId::Arch(2) => Some("store"),+ GroupId::Arch(3) => Some("alu"),+ GroupId::Arch(4) => Some("move"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- m if m.starts_with("mv.") => 1,- m if m.starts_with("add") => 2,- "b" | "b.s" => 3,- "ldw" => 4,- "stw" => 5,- m if m.starts_with("sub") => 2,+ m if m.starts_with("mv.") => 1,+ m if m.starts_with("add") => 2,+ "b" | "b.s" => 3,+ "ldw" => 4,+ "stw" => 5,+ m if m.starts_with("sub") => 2,_ => 0,};InsnId(id)@@ -104,24 +104,20 @@ mod tests {#[test]fn c64x_mv_and_add() {let mut eng = Engine::open(Arch::Tms320c64x, Mode::LITTLE_ENDIAN).unwrap();- // mv.l a1, a2- let mv = eng- .disasm_one(&[0x41, 0x00, 0x00, 0x02], 0)- .unwrap();- assert!(mv.mnemonic.starts_with("mv."));- // add.l a1, a2, a1- let add = eng- .disasm_one(&[0x00, 0x00, 0x00, 0x20], 0)- .unwrap();- assert_eq!(add.mnemonic, "add.l");+ // mv.l a1, a2+ let mv = eng.disasm_one(&[0x41, 0x00, 0x00, 0x02], 0).unwrap();+ assert!(mv.mnemonic.starts_with("mv."));+ // add.l a1, a2, a1+ let add = eng.disasm_one(&[0x00, 0x00, 0x00, 0x20], 0).unwrap();+ assert_eq!(add.mnemonic, "add.l");}#[test]fn c64x_branch_and_ldw() {let mut eng = Engine::open(Arch::Tms320c64x, Mode::LITTLE_ENDIAN).unwrap();let b = eng.disasm_one(&[0x00, 0x00, 0x00, 0x10], 0).unwrap();- assert_eq!(b.mnemonic, "b");+ assert_eq!(b.mnemonic, "b");let ldw = eng.disasm_one(&[0x00, 0x00, 0x00, 0x40], 0).unwrap();- assert_eq!(ldw.mnemonic, "ldw");+ assert_eq!(ldw.mnemonic, "ldw");}}diff --git a/crates/ghidrust-decode/src/arch/tricore/decode.rs b/crates/ghidrust-decode/src/arch/tricore/decode.rsindex 1dd2bac..8f5cc48 100644--- a/crates/ghidrust-decode/src/arch/tricore/decode.rs+++ b/crates/ghidrust-decode/src/arch/tricore/decode.rs@@ -2,26 +2,26 @@ use crate::error::{Error, Result};pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("d0"),- 1 => Some("d1"),- 10 => Some("a10"),- 11 => Some("a11"),- 15 => Some("a15"),+ 0 => Some("d0"),+ 1 => Some("d1"),+ 10 => Some("a10"),+ 11 => Some("a11"),+ 15 => Some("a15"),_ => None,}}fn d(n: u32) -> String {- format!("d{n}")+ format!("d{n}")}fn a(n: u32) -> String {- format!("a{n}")+ format!("a{n}")}pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usize)> {if bytes.len() < 2 {- return Err(Error::Decode("truncated tricore input".into()));+ return Err(Error::Decode("truncated tricore input".into()));}let half = if little_endian {u16::from_le_bytes([bytes[0], bytes[1]])@@ -31,7 +31,7 @@ pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usizif half == 0x8000 {if bytes.len() < 4 {- return Err(Error::Decode("truncated tricore 32-bit".into()));+ return Err(Error::Decode("truncated tricore 32-bit".into()));}let word = if little_endian {u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])@@ -50,28 +50,36 @@ fn decode16(h: u16) -> Result<(String, String, usize)> {0x0 => {let dst = (h >> 8) & 0xf;let src = (h >> 4) & 0xf;- Ok(("mov".into(), format!("{}, {}", d(u32::from(dst)), d(u32::from(src))), 2))+ Ok((+ "mov".into(),+ format!("{}, {}", d(u32::from(dst)), d(u32::from(src))),+ 2,+ ))}0x1 => {let dst = (h >> 8) & 0xf;let src = (h >> 4) & 0xf;- Ok(("add".into(), format!("{}, {}", d(u32::from(dst)), d(u32::from(src))), 2))+ Ok((+ "add".into(),+ format!("{}, {}", d(u32::from(dst)), d(u32::from(src))),+ 2,+ ))}0x8 => {let disp = sign_ext16((h & 0x0fff) as i16, 12);- Ok(("j".into(), format!("{disp}"), 2))+ Ok(("j".into(), format!("{disp}"), 2))}0x9 => {let disp = sign_ext16((h & 0x0fff) as i16, 12);- Ok(("jl".into(), format!("{disp}"), 2))+ Ok(("jl".into(), format!("{disp}"), 2))}0xa => {let dst = (h >> 8) & 0xf;let base = (h >> 4) & 0xf;let off = (h & 0xf) as i64 * 4;Ok((- "ld.w".into(),- format!("{}, [{off}({})]", d(u32::from(dst)), a(u32::from(base))),+ "ld.w".into(),+ format!("{}, [{off}({})]", d(u32::from(dst)), a(u32::from(base))),2,))}@@ -80,12 +88,12 @@ fn decode16(h: u16) -> Result<(String, String, usize)> {let base = (h >> 4) & 0xf;let off = (h & 0xf) as i64 * 4;Ok((- "st.w".into(),- format!("{}, [{off}({})]", d(u32::from(src)), a(u32::from(base))),+ "st.w".into(),+ format!("{}, [{off}({})]", d(u32::from(src)), a(u32::from(base))),2,))}- _ => Err(Error::Decode("unsupported tricore 16-bit".into())),+ _ => Err(Error::Decode("unsupported tricore 16-bit".into())),}}@@ -95,33 +103,33 @@ fn decode32(word: u32) -> Result<(String, String, usize)> {0x1 => {let dst = (word >> 20) & 0xf;let src = (word >> 16) & 0xf;- Ok(("mov".into(), format!("{}, {}", d(dst), d(src)), 4))+ Ok(("mov".into(), format!("{}, {}", d(dst), d(src)), 4))}0x2 => {let dst = (word >> 20) & 0xf;let src1 = (word >> 16) & 0xf;let src2 = (word >> 12) & 0xf;Ok((- "add".into(),- format!("{}, {}, {}", d(dst), d(src1), d(src2)),+ "add".into(),+ format!("{}, {}, {}", d(dst), d(src1), d(src2)),4,))}0x8 => {let disp = sign_ext32((word & 0x0fffffff) as i32, 28);- Ok(("j".into(), format!("{disp}"), 4))+ Ok(("j".into(), format!("{disp}"), 4))}0x9 => {let disp = sign_ext32((word & 0x0fffffff) as i32, 28);- Ok(("jl".into(), format!("{disp}"), 4))+ Ok(("jl".into(), format!("{disp}"), 4))}0xa => {let dst = (word >> 20) & 0xf;let base = (word >> 16) & 0xf;let off = (word >> 4) & 0xfff;Ok((- "ld.w".into(),- format!("{}, [{off}({})]", d(u32::from(dst)), a(u32::from(base))),+ "ld.w".into(),+ format!("{}, [{off}({})]", d(u32::from(dst)), a(u32::from(base))),4,))}@@ -130,12 +138,12 @@ fn decode32(word: u32) -> Result<(String, String, usize)> {let base = (word >> 16) & 0xf;let off = (word >> 4) & 0xfff;Ok((- "st.w".into(),- format!("{}, [{off}({})]", d(u32::from(src)), a(u32::from(base))),+ "st.w".into(),+ format!("{}, [{off}({})]", d(u32::from(src)), a(u32::from(base))),4,))}- _ => Err(Error::Decode("unsupported tricore 32-bit".into())),+ _ => Err(Error::Decode("unsupported tricore 32-bit".into())),}}@@ -155,9 +163,9 @@ mod tests {#[test]fn tricore_mov16() {- // mov d1, d2 => op=0 dst=1 src=2 => 0x0120+ // mov d1, d2 => op=0 dst=1 src=2 => 0x0120let (m, _, l) = decode(&[0x20, 0x01], true).unwrap();- assert_eq!(m, "mov");+ assert_eq!(m, "mov");assert_eq!(l, 2);}}diff --git a/crates/ghidrust-decode/src/arch/tricore/mod.rs b/crates/ghidrust-decode/src/arch/tricore/mod.rsindex f04078e..7f15f2f 100644--- a/crates/ghidrust-decode/src/arch/tricore/mod.rs+++ b/crates/ghidrust-decode/src/arch/tricore/mod.rs@@ -21,7 +21,10 @@ impl ArchDecode for TricoreDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Tricore) {- return Err(Error::Mode(format!("invalid tricore mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!(+ "invalid tricore mode {:#x}",+ mode.bits()+ )));}let little_endian = !mode.contains(Mode::BIG_ENDIAN);Ok(Self { little_endian })@@ -49,45 +52,45 @@ impl ArchDecode for TricoreDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "j" => vec![GroupId::Jump],- "jl" => vec![GroupId::Call],- "ld.w" => vec![GroupId::Arch(1)],- "st.w" => vec![GroupId::Arch(2)],- "add" | "mov" => vec![GroupId::Arch(3)],+ "j" => vec![GroupId::Jump],+ "jl" => vec![GroupId::Call],+ "ld.w" => vec![GroupId::Arch(1)],+ "st.w" => vec![GroupId::Arch(2)],+ "add" | "mov" => vec![GroupId::Arch(3)],_ => Vec::new(),}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("mov"),- 2 => Some("add"),- 3 => Some("j"),- 4 => Some("jl"),- 5 => Some("ld.w"),+ 1 => Some("mov"),+ 2 => Some("add"),+ 3 => Some("j"),+ 4 => Some("jl"),+ 5 => Some("ld.w"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Arch(1) => Some("load"),- GroupId::Arch(2) => Some("store"),- GroupId::Arch(3) => Some("alu"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Arch(1) => Some("load"),+ GroupId::Arch(2) => Some("store"),+ GroupId::Arch(3) => Some("alu"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "mov" => 1,- "add" => 2,- "j" => 3,- "jl" => 4,- "ld.w" => 5,- "st.w" => 5,+ "mov" => 1,+ "add" => 2,+ "j" => 3,+ "jl" => 4,+ "ld.w" => 5,+ "st.w" => 5,_ => 0,};InsnId(id)@@ -102,20 +105,20 @@ mod tests {fn tricore_mov_and_add() {let mut eng = Engine::open(Arch::Tricore, Mode::LITTLE_ENDIAN).unwrap();let mov = eng.disasm_one(&[0x20, 0x01], 0).unwrap();- assert_eq!(mov.mnemonic, "mov");- // add d3, d1, d2 => op=1 dst=3 src1=1 src2=2 => 0x1312+ assert_eq!(mov.mnemonic, "mov");+ // add d3, d1, d2 => op=1 dst=3 src1=1 src2=2 => 0x1312let add = eng.disasm_one(&[0x12, 0x13], 0).unwrap();- assert_eq!(add.mnemonic, "add");+ assert_eq!(add.mnemonic, "add");}#[test]fn tricore_j_and_ldw() {let mut eng = Engine::open(Arch::Tricore, Mode::LITTLE_ENDIAN).unwrap();- // j +4 => 0x8004+ // j +4 => 0x8004let j = eng.disasm_one(&[0x04, 0x80], 0).unwrap();- assert_eq!(j.mnemonic, "j");- // ld.w d1, [0(a2)] => op=a dst=1 base=2 off=0 => 0xa120+ assert_eq!(j.mnemonic, "j");+ // ld.w d1, [0(a2)] => op=a dst=1 base=2 off=0 => 0xa120let ld = eng.disasm_one(&[0x20, 0xa1], 0).unwrap();- assert_eq!(ld.mnemonic, "ld.w");+ assert_eq!(ld.mnemonic, "ld.w");}}diff --git a/crates/ghidrust-decode/src/arch/wasm/mod.rs b/crates/ghidrust-decode/src/arch/wasm/mod.rsindex 356d7ce..62b40a0 100644--- a/crates/ghidrust-decode/src/arch/wasm/mod.rs+++ b/crates/ghidrust-decode/src/arch/wasm/mod.rs@@ -16,168 +16,168 @@ pub struct WasmDecoder {}const OPCODE_MNEMONIC: [&str; 256] = {- let mut table = ["invalid"; 256];- table[0x00] = "unreachable";- table[0x01] = "nop";- table[0x02] = "block";- table[0x03] = "loop";- table[0x04] = "if";- table[0x05] = "else";- table[0x0b] = "end";- table[0x0c] = "br";- table[0x0d] = "br_if";- table[0x0e] = "br_table";- table[0x0f] = "return";- table[0x10] = "call";- table[0x11] = "call_indirect";- table[0x1a] = "drop";- table[0x1b] = "select";- table[0x20] = "get_local";- table[0x21] = "set_local";- table[0x22] = "tee_local";- table[0x23] = "get_global";- table[0x24] = "set_global";- table[0x28] = "i32.load";- table[0x29] = "i64.load";- table[0x2a] = "f32.load";- table[0x2b] = "f64.load";- table[0x2c] = "i32.load8_s";- table[0x2d] = "i32.load8_u";- table[0x2e] = "i32.load16_s";- table[0x2f] = "i32.load16_u";- table[0x30] = "i64.load8_s";- table[0x31] = "i64.load8_u";- table[0x32] = "i64.load16_s";- table[0x33] = "i64.load16_u";- table[0x34] = "i64.load32_s";- table[0x35] = "i64.load32_u";- table[0x36] = "i32.store";- table[0x37] = "i64.store";- table[0x38] = "f32.store";- table[0x39] = "f64.store";- table[0x3a] = "i32.store8";- table[0x3b] = "i32.store16";- table[0x3c] = "i64.store8";- table[0x3d] = "i64.store16";- table[0x3e] = "i64.store32";- table[0x3f] = "current_memory";- table[0x40] = "grow_memory";- table[0x41] = "i32.const";- table[0x42] = "i64.const";- table[0x43] = "f32.const";- table[0x44] = "f64.const";- table[0x45] = "i32.eqz";- table[0x46] = "i32.eq";- table[0x47] = "i32.ne";- table[0x48] = "i32.lt_s";- table[0x49] = "i32.lt_u";- table[0x4a] = "i32.gt_s";- table[0x4b] = "i32.gt_u";- table[0x4c] = "i32.le_s";- table[0x4d] = "i32.le_u";- table[0x4e] = "i32.ge_s";- table[0x4f] = "i32.ge_u";- table[0x50] = "i64.eqz";- table[0x51] = "i64.eq";- table[0x52] = "i64.ne";- table[0x53] = "i64.lt_s";- table[0x54] = "i64.lt_u";- table[0x55] = "i64.gt_s";- table[0x56] = "i64.gt_u";- table[0x57] = "i64.le_s";- table[0x58] = "i64.le_u";- table[0x59] = "i64.ge_s";- table[0x5a] = "i64.ge_u";- table[0x5b] = "f32.eq";- table[0x5c] = "f32.ne";- table[0x5d] = "f32.lt";- table[0x5e] = "f32.gt";- table[0x5f] = "f32.le";- table[0x60] = "f32.ge";- table[0x61] = "f64.eq";- table[0x62] = "f64.ne";- table[0x63] = "f64.lt";- table[0x64] = "f64.gt";- table[0x65] = "f64.le";- table[0x66] = "f64.ge";- table[0x67] = "i32.clz";- table[0x68] = "i32.ctz";- table[0x69] = "i32.popcnt";- table[0x6a] = "i32.add";- table[0x6b] = "i32.sub";- table[0x6c] = "i32.mul";- table[0x6d] = "i32.div_s";- table[0x6e] = "i32.div_u";- table[0x6f] = "i32.rem_s";- table[0x70] = "i32.rem_u";- table[0x71] = "i32.and";- table[0x72] = "i32.or";- table[0x73] = "i32.xor";- table[0x74] = "i32.shl";- table[0x75] = "i32.shr_s";- table[0x76] = "i32.shr_u";- table[0x77] = "i32.rotl";- table[0x78] = "i32.rotr";- table[0x79] = "i64.clz";- table[0x7a] = "i64.ctz";- table[0x7b] = "i64.popcnt";- table[0x7c] = "i64.add";- table[0x7d] = "i64.sub";- table[0x7e] = "i64.mul";- table[0x7f] = "i64.div_s";- table[0x80] = "i64.div_u";- table[0x81] = "i64.rem_s";- table[0x82] = "i64.rem_u";- table[0x83] = "i64.and";- table[0x84] = "i64.or";- table[0x85] = "i64.xor";- table[0x86] = "i64.shl";- table[0x87] = "i64.shr_s";- table[0x88] = "i64.shr_u";- table[0x89] = "i64.rotl";- table[0x8a] = "i64.rotr";- table[0x8b] = "f32.abs";- table[0x8c] = "f32.neg";- table[0x8d] = "f32.ceil";- table[0x8e] = "f32.floor";- table[0x8f] = "f32.trunc";- table[0x90] = "f32.nearest";- table[0x91] = "f32.sqrt";- table[0x92] = "f32.add";- table[0x93] = "f32.sub";- table[0x94] = "f32.mul";- table[0x95] = "f32.div";- table[0x96] = "f32.min";- table[0x97] = "f32.max";- table[0x98] = "f32.copysign";- table[0x99] = "f64.abs";- table[0x9a] = "f64.neg";- table[0x9b] = "f64.ceil";- table[0x9c] = "f64.floor";- table[0x9d] = "f64.trunc";- table[0x9e] = "f64.nearest";- table[0x9f] = "f64.sqrt";- table[0xa0] = "f64.add";- table[0xa1] = "f64.sub";- table[0xa2] = "f64.mul";- table[0xa3] = "f64.div";- table[0xa4] = "f64.min";- table[0xa5] = "f64.max";- table[0xa6] = "f64.copysign";+ let mut table = ["invalid"; 256];+ table[0x00] = "unreachable";+ table[0x01] = "nop";+ table[0x02] = "block";+ table[0x03] = "loop";+ table[0x04] = "if";+ table[0x05] = "else";+ table[0x0b] = "end";+ table[0x0c] = "br";+ table[0x0d] = "br_if";+ table[0x0e] = "br_table";+ table[0x0f] = "return";+ table[0x10] = "call";+ table[0x11] = "call_indirect";+ table[0x1a] = "drop";+ table[0x1b] = "select";+ table[0x20] = "get_local";+ table[0x21] = "set_local";+ table[0x22] = "tee_local";+ table[0x23] = "get_global";+ table[0x24] = "set_global";+ table[0x28] = "i32.load";+ table[0x29] = "i64.load";+ table[0x2a] = "f32.load";+ table[0x2b] = "f64.load";+ table[0x2c] = "i32.load8_s";+ table[0x2d] = "i32.load8_u";+ table[0x2e] = "i32.load16_s";+ table[0x2f] = "i32.load16_u";+ table[0x30] = "i64.load8_s";+ table[0x31] = "i64.load8_u";+ table[0x32] = "i64.load16_s";+ table[0x33] = "i64.load16_u";+ table[0x34] = "i64.load32_s";+ table[0x35] = "i64.load32_u";+ table[0x36] = "i32.store";+ table[0x37] = "i64.store";+ table[0x38] = "f32.store";+ table[0x39] = "f64.store";+ table[0x3a] = "i32.store8";+ table[0x3b] = "i32.store16";+ table[0x3c] = "i64.store8";+ table[0x3d] = "i64.store16";+ table[0x3e] = "i64.store32";+ table[0x3f] = "current_memory";+ table[0x40] = "grow_memory";+ table[0x41] = "i32.const";+ table[0x42] = "i64.const";+ table[0x43] = "f32.const";+ table[0x44] = "f64.const";+ table[0x45] = "i32.eqz";+ table[0x46] = "i32.eq";+ table[0x47] = "i32.ne";+ table[0x48] = "i32.lt_s";+ table[0x49] = "i32.lt_u";+ table[0x4a] = "i32.gt_s";+ table[0x4b] = "i32.gt_u";+ table[0x4c] = "i32.le_s";+ table[0x4d] = "i32.le_u";+ table[0x4e] = "i32.ge_s";+ table[0x4f] = "i32.ge_u";+ table[0x50] = "i64.eqz";+ table[0x51] = "i64.eq";+ table[0x52] = "i64.ne";+ table[0x53] = "i64.lt_s";+ table[0x54] = "i64.lt_u";+ table[0x55] = "i64.gt_s";+ table[0x56] = "i64.gt_u";+ table[0x57] = "i64.le_s";+ table[0x58] = "i64.le_u";+ table[0x59] = "i64.ge_s";+ table[0x5a] = "i64.ge_u";+ table[0x5b] = "f32.eq";+ table[0x5c] = "f32.ne";+ table[0x5d] = "f32.lt";+ table[0x5e] = "f32.gt";+ table[0x5f] = "f32.le";+ table[0x60] = "f32.ge";+ table[0x61] = "f64.eq";+ table[0x62] = "f64.ne";+ table[0x63] = "f64.lt";+ table[0x64] = "f64.gt";+ table[0x65] = "f64.le";+ table[0x66] = "f64.ge";+ table[0x67] = "i32.clz";+ table[0x68] = "i32.ctz";+ table[0x69] = "i32.popcnt";+ table[0x6a] = "i32.add";+ table[0x6b] = "i32.sub";+ table[0x6c] = "i32.mul";+ table[0x6d] = "i32.div_s";+ table[0x6e] = "i32.div_u";+ table[0x6f] = "i32.rem_s";+ table[0x70] = "i32.rem_u";+ table[0x71] = "i32.and";+ table[0x72] = "i32.or";+ table[0x73] = "i32.xor";+ table[0x74] = "i32.shl";+ table[0x75] = "i32.shr_s";+ table[0x76] = "i32.shr_u";+ table[0x77] = "i32.rotl";+ table[0x78] = "i32.rotr";+ table[0x79] = "i64.clz";+ table[0x7a] = "i64.ctz";+ table[0x7b] = "i64.popcnt";+ table[0x7c] = "i64.add";+ table[0x7d] = "i64.sub";+ table[0x7e] = "i64.mul";+ table[0x7f] = "i64.div_s";+ table[0x80] = "i64.div_u";+ table[0x81] = "i64.rem_s";+ table[0x82] = "i64.rem_u";+ table[0x83] = "i64.and";+ table[0x84] = "i64.or";+ table[0x85] = "i64.xor";+ table[0x86] = "i64.shl";+ table[0x87] = "i64.shr_s";+ table[0x88] = "i64.shr_u";+ table[0x89] = "i64.rotl";+ table[0x8a] = "i64.rotr";+ table[0x8b] = "f32.abs";+ table[0x8c] = "f32.neg";+ table[0x8d] = "f32.ceil";+ table[0x8e] = "f32.floor";+ table[0x8f] = "f32.trunc";+ table[0x90] = "f32.nearest";+ table[0x91] = "f32.sqrt";+ table[0x92] = "f32.add";+ table[0x93] = "f32.sub";+ table[0x94] = "f32.mul";+ table[0x95] = "f32.div";+ table[0x96] = "f32.min";+ table[0x97] = "f32.max";+ table[0x98] = "f32.copysign";+ table[0x99] = "f64.abs";+ table[0x9a] = "f64.neg";+ table[0x9b] = "f64.ceil";+ table[0x9c] = "f64.floor";+ table[0x9d] = "f64.trunc";+ table[0x9e] = "f64.nearest";+ table[0x9f] = "f64.sqrt";+ table[0xa0] = "f64.add";+ table[0xa1] = "f64.sub";+ table[0xa2] = "f64.mul";+ table[0xa3] = "f64.div";+ table[0xa4] = "f64.min";+ table[0xa5] = "f64.max";+ table[0xa6] = "f64.copysign";table};pub(crate) fn decode_raw(bytes: &[u8], address: u64) -> Result<Instruction> {if bytes.is_empty() {- return Err(Error::Decode("empty input".into()));+ return Err(Error::Decode("empty input".into()));}let opcode = bytes[0];let mnemonic = OPCODE_MNEMONIC[opcode as usize];- if mnemonic == "invalid" {+ if mnemonic == "invalid" {return Ok(Instruction::with_text(address,vec![opcode],- "invalid",+ "invalid",String::new(),1,));@@ -198,45 +198,45 @@ fn decode_immediates(opcode: u8, tail: &[u8]) -> Result<(usize, String)> {0x02 | 0x03 | 0x04 => {let (ty, n) = leb128::read_i7(tail)?;let op = if ty == 0 && !tail.is_empty() && tail[0] == 0x40 {- "void".to_string()+ "void".to_string()} else {- format!("{ty}")+ format!("{ty}")};(n, op)}0x0c | 0x0d | 0x10 | 0x11 | 0x20 | 0x21 | 0x22 | 0x23 | 0x24 => {let (idx, n) = leb128::read_u32(tail)?;- (n, format!("{idx}"))+ (n, format!("{idx}"))}0x0e => decode_br_table(tail)?,0x28..=0x3e => {let (align, n1) = leb128::read_u32(tail)?;let (offset, n2) = leb128::read_u32(&tail[n1..])?;- (n1 + n2, format!("{align}, {offset}"))+ (n1 + n2, format!("{align}, {offset}"))}0x41 => {let (v, n) = leb128::read_i32(tail)?;- (n, format!("{v}"))+ (n, format!("{v}"))}0x42 => {let (v, n) = leb128::read_i64(tail)?;- (n, format!("{v}"))+ (n, format!("{v}"))}0x43 => {if tail.len() < 4 {- return Err(Error::Decode("truncated f32.const".into()));+ return Err(Error::Decode("truncated f32.const".into()));}let bits = u32::from_le_bytes([tail[0], tail[1], tail[2], tail[3]]);- (4, format!("{bits:#x}"))+ (4, format!("{bits:#x}"))}0x44 => {if tail.len() < 8 {- return Err(Error::Decode("truncated f64.const".into()));+ return Err(Error::Decode("truncated f64.const".into()));}let bits = u64::from_le_bytes([tail[0], tail[1], tail[2], tail[3], tail[4], tail[5], tail[6], tail[7],]);- (8, format!("{bits:#x}"))+ (8, format!("{bits:#x}"))}_ => (0, String::new()),})@@ -251,7 +251,7 @@ fn decode_br_table(tail: &[u8]) -> Result<(usize, String)> {off += n;targets.push(label.to_string());}- Ok((off, targets.join(", ")))+ Ok((off, targets.join(", ")))}impl ArchDecode for WasmDecoder {@@ -261,7 +261,7 @@ impl ArchDecode for WasmDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Wasm) {- return Err(Error::Mode(format!("invalid wasm mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!("invalid wasm mode {:#x}", mode.bits())));}Ok(Self { _mode: mode })}@@ -285,21 +285,25 @@ fn typed_operands(insn: &Instruction) -> Vec<Operand> {return Vec::new();}insn.operands- .split(", ")- .filter_map(|p| p.parse::<i64>().ok().map(|v| Operand::Imm { value: v, size: 4 }))+ .split(", ")+ .filter_map(|p| {+ p.parse::<i64>()+ .ok()+ .map(|v| Operand::Imm { value: v, size: 4 })+ }).collect()}fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "block" | "loop" | "if" | "else" | "end" | "br" | "br_if" | "br_table" | "return"- | "call" | "call_indirect" => vec![GroupId::Jump],- "i32.const" | "i64.const" | "f32.const" | "f64.const" => vec![GroupId::Arch(2)],- m if m.contains("load") || m.contains("store") || m.contains("memory") => {+ "block" | "loop" | "if" | "else" | "end" | "br" | "br_if" | "br_table" | "return"+ | "call" | "call_indirect" => vec![GroupId::Jump],+ "i32.const" | "i64.const" | "f32.const" | "f64.const" => vec![GroupId::Arch(2)],+ m if m.contains("load") || m.contains("store") || m.contains("memory") => {vec![GroupId::Arch(3)]}- m if m.contains("local") || m.contains("global") => vec![GroupId::Arch(4)],- m if m.contains('.') => vec![GroupId::Arch(2)],+ m if m.contains("local") || m.contains("global") => vec![GroupId::Arch(4)],+ m if m.contains('.') => vec![GroupId::Arch(2)],_ => Vec::new(),}}@@ -312,7 +316,7 @@ pub fn insn_name(id: InsnId) -> Option<&'static str> {let raw = id.raw();if raw < 256 {let name = OPCODE_MNEMONIC[raw as usize];- if name != "invalid" {+ if name != "invalid" {Some(name)} else {None@@ -324,10 +328,10 @@ pub fn insn_name(id: InsnId) -> Option<&'static str> {pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("control"),- GroupId::Arch(2) => Some("numeric"),- GroupId::Arch(3) => Some("memory"),- GroupId::Arch(4) => Some("variable"),+ GroupId::Jump => Some("control"),+ GroupId::Arch(2) => Some("numeric"),+ GroupId::Arch(3) => Some("memory"),+ GroupId::Arch(4) => Some("variable"),_ => None,}}@@ -352,14 +356,14 @@ mod tests {let c = dec.decode_one(&[0x41, 0xfb, 0x00], 0, &EngineOptions::default()).unwrap();- assert_eq!(c.mnemonic, "i32.const");- assert_eq!(c.operands, "123");+ assert_eq!(c.mnemonic, "i32.const");+ assert_eq!(c.operands, "123");assert_eq!(c.length, 3);let add = dec.decode_one(&[0x6a], 0, &EngineOptions::default()).unwrap();- assert_eq!(add.mnemonic, "i32.add");+ assert_eq!(add.mnemonic, "i32.add");assert_eq!(add.length, 1);}@@ -369,14 +373,14 @@ mod tests {let call = dec.decode_one(&[0x10, 0x03], 0, &EngineOptions::default()).unwrap();- assert_eq!(call.mnemonic, "call");- assert_eq!(call.operands, "3");+ assert_eq!(call.mnemonic, "call");+ assert_eq!(call.operands, "3");let block = dec.decode_one(&[0x02, 0x40], 0, &EngineOptions::default()).unwrap();- assert_eq!(block.mnemonic, "block");- assert_eq!(block.operands, "void");+ assert_eq!(block.mnemonic, "block");+ assert_eq!(block.operands, "void");}#[test]@@ -385,8 +389,8 @@ mod tests {let load = dec.decode_one(&[0x28, 0x02, 0x04], 0, &EngineOptions::default()).unwrap();- assert_eq!(load.mnemonic, "i32.load");- assert_eq!(load.operands, "2, 4");+ assert_eq!(load.mnemonic, "i32.load");+ assert_eq!(load.operands, "2, 4");assert_eq!(load.length, 3);}}diff --git a/crates/ghidrust-decode/src/arch/x86/legacy.rs b/crates/ghidrust-decode/src/arch/x86/legacy.rsindex 9ccf0ec..8f6a16b 100644--- a/crates/ghidrust-decode/src/arch/x86/legacy.rs+++ b/crates/ghidrust-decode/src/arch/x86/legacy.rs@@ -6,20 +6,20 @@ use crate::support::Arch;use crate::{Error, Result};const REGS64: [&str; 16] = [- "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13",- "r14", "r15",+ "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13",+ "r14", "r15",];const REGS32: [&str; 16] = [- "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d",- "r13d", "r14d", "r15d",+ "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d",+ "r13d", "r14d", "r15d",];const REGS16: [&str; 16] = [- "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w",- "r14w", "r15w",+ "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w",+ "r14w", "r15w",];const REGS8: [&str; 16] = [- "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b",- "r13b", "r14b", "r15b",+ "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b",+ "r13b", "r14b", "r15b",];#[derive(Clone, Copy, Default)]@@ -29,12 +29,12 @@ struct Prefix {rex_x: bool,rex_b: bool,has_rex: bool,- op_size: bool, // 0x66+ op_size: bool, // 0x66addr_size: bool, // 0x67rep: bool,repne: bool,lock: bool,- seg: Option<&'static str>,+ seg: Option<&'static str>,}fn reg_name(idx: u8, w: bool, op16: bool, byte_op: bool) -> &'static str {@@ -51,13 +51,13 @@ fn reg_name(idx: u8, w: bool, op16: bool, byte_op: bool) -> &'static str {}struct Cursor<'a> {- data: &'a [u8],+ data: &'a [u8],pos: usize,start: usize,}impl<'a> Cursor<'a> {- fn new(data: &'a [u8]) -> Self {+ fn new(data: &'a [u8]) -> Self {Self {data,pos: 0,@@ -69,7 +69,7 @@ impl<'a> Cursor<'a> {}fn get(&mut self) -> Result<u8> {if self.pos >= self.data.len() {- return Err(Error::Decode("truncated instruction stream".into()));+ return Err(Error::Decode("truncated instruction stream".into()));}let b = self.data[self.pos];self.pos += 1;@@ -79,11 +79,11 @@ impl<'a> Cursor<'a> {self.data.get(self.pos).copied()- .ok_or_else(|| Error::Decode("truncated".into()))+ .ok_or_else(|| Error::Decode("truncated".into()))}fn take_imm(&mut self, n: usize) -> Result<u64> {if self.remaining() < n {- return Err(Error::Decode("imm truncated".into()));+ return Err(Error::Decode("imm truncated".into()));}let mut v = 0u64;for i in 0..n {@@ -99,19 +99,19 @@ impl<'a> Cursor<'a> {fn sign_hex(v: i64) -> String {if v < 0 {- format!("-{:#x}", -v)+ format!("-{:#x}", -v)} else {- format!("{v:#x}")+ format!("{v:#x}")}}fn size_prefix(sz: u32) -> &'static str {match sz {- 1 => "byte ptr ",- 2 => "word ptr ",- 4 => "dword ptr ",- 8 => "qword ptr ",- _ => "",+ 1 => "byte ptr ",+ 2 => "word ptr ",+ 4 => "dword ptr ",+ 8 => "qword ptr ",+ _ => "",}}@@ -121,7 +121,7 @@ fn size_prefix(sz: u32) -> &'static str {/// the memory access width (1/2/4/8) so downstream lift can pick the right/// load/store width without needing to reparse the mnemonic.fn xmm_name(reg: u8) -> String {- format!("xmm{}", reg & 0xf)+ format!("xmm{}", reg & 0xf)}/// Decode ModRM for SSE xmm, xmm/m128 forms. Returns (xmm_reg, rm_operand).@@ -139,7 +139,7 @@ fn decode_sse_xmm_rm(cur: &mut Cursor<'_>, pfx: Prefix) -> Result<(String, Strin}fn decode_modrm_sized(- cur: &mut Cursor<'_>,+ cur: &mut Cursor<'_>,modrm: u8,pfx: Prefix,reg_byte: bool,@@ -148,15 +148,15 @@ fn decode_modrm_sized(let (reg, s) = decode_modrm_mem(cur, modrm, pfx, reg_byte)?;if (modrm >> 6) != 3 {let prefix = size_prefix(mem_size);- if !prefix.is_empty() && !s.contains(" ptr ") {- return Ok((reg, format!("{prefix}{s}")));+ if !prefix.is_empty() && !s.contains(" ptr ") {+ return Ok((reg, format!("{prefix}{s}")));}}Ok((reg, s))}fn decode_modrm_mem(- cur: &mut Cursor<'_>,+ cur: &mut Cursor<'_>,modrm: u8,pfx: Prefix,byte_op: bool,@@ -179,7 +179,7 @@ fn decode_modrm_mem(return Ok((reg, name.to_string()));}- // SIB if rm low 3 bits == 4 (without rex_b folded for encoding check)+ // SIB if rm low 3 bits == 4 (without rex_b folded for encoding check)let rm_enc = modrm & 7;let mut parts = String::new();if rm_enc == 4 {@@ -195,7 +195,7 @@ fn decode_modrm_mem(if scale == 1 {terms.push(REGS64[index as usize].to_string());} else {- terms.push(format!("{}*{}", REGS64[index as usize], scale));+ terms.push(format!("{}*{}", REGS64[index as usize], scale));}}let disp = match mod_ {@@ -207,54 +207,46 @@ fn decode_modrm_mem(if let Some(d) = disp {if d != 0 || terms.is_empty() {parts = if terms.is_empty() {- format!("[{}]", sign_hex(d))+ format!("[{}]", sign_hex(d))} else {format!(- "[{}{}{}]",- terms.join("+"),- if d < 0 { "" } else { "+" },+ "[{}{}{}]",+ terms.join("+"),+ if d < 0 { "" } else { "+" },sign_hex(d))};} else {- parts = format!("[{}]", terms.join("+"));+ parts = format!("[{}]", terms.join("+"));}} else {- parts = format!("[{}]", terms.join("+"));+ parts = format!("[{}]", terms.join("+"));}} else if mod_ == 0 && rm_enc == 5 {- // RIP-relative+ // RIP-relativelet disp = cur.take_imm(4)? as i32 as i64;parts = if disp < 0 {- format!("[rip{}]", sign_hex(disp))+ format!("[rip{}]", sign_hex(disp))} else {- format!("[rip+{}]", sign_hex(disp))+ format!("[rip+{}]", sign_hex(disp))};} else {let base = REGS64[rm as usize];match mod_ {- 0 => parts = format!("[{base}]"),+ 0 => parts = format!("[{base}]"),1 => {let d = cur.take_imm(1)? as i8 as i64;- parts = format!(- "[{base}{}{}]",- if d < 0 { "" } else { "+" },- sign_hex(d)- );+ parts = format!("[{base}{}{}]", if d < 0 { "" } else { "+" }, sign_hex(d));}2 => {let d = cur.take_imm(4)? as i32 as i64;- parts = format!(- "[{base}{}{}]",- if d < 0 { "" } else { "+" },- sign_hex(d)- );+ parts = format!("[{base}{}{}]", if d < 0 { "" } else { "+" }, sign_hex(d));}_ => {}}}if let Some(seg) = pfx.seg {- parts = format!("{seg}:{parts}");+ parts = format!("{seg}:{parts}");}Ok((reg, parts))}@@ -262,12 +254,12 @@ fn decode_modrm_mem(/// Decode one instruction from raw bytes at `address` (VA for display only).pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {if bytes.is_empty() {- return Err(Error::Decode("empty".into()));+ return Err(Error::Decode("empty".into()));}let mut cur = Cursor::new(bytes);let mut pfx = Prefix::default();- // prefixes+ // prefixesloop {let b = cur.peek()?;match b {@@ -285,27 +277,27 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {}0x2E => {cur.get()?;- pfx.seg = Some("cs");+ pfx.seg = Some("cs");}0x36 => {cur.get()?;- pfx.seg = Some("ss");+ pfx.seg = Some("ss");}0x3E => {cur.get()?;- pfx.seg = Some("ds");+ pfx.seg = Some("ds");}0x26 => {cur.get()?;- pfx.seg = Some("es");+ pfx.seg = Some("es");}0x64 => {cur.get()?;- pfx.seg = Some("fs");+ pfx.seg = Some("fs");}0x65 => {cur.get()?;- pfx.seg = Some("gs");+ pfx.seg = Some("gs");}0x66 => {cur.get()?;@@ -326,7 +318,7 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {_ => break,}if cur.pos > 15 {- return Err(Error::Decode("too many prefixes".into()));+ return Err(Error::Decode("too many prefixes".into()));}}@@ -335,17 +327,17 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {let op16 = pfx.op_size && !pfx.rex_w;let (mnemonic, operands): (String, String) = match op {- // PUSH r64: 50+rd+ // PUSH r64: 50+rd0x50..=0x57 => {let r = (op - 0x50) | if pfx.rex_b { 8 } else { 0 };- ("push".into(), REGS64[r as usize].to_string())+ ("push".into(), REGS64[r as usize].to_string())}- // POP r64+ // POP r640x58..=0x5F => {let r = (op - 0x58) | if pfx.rex_b { 8 } else { 0 };- ("pop".into(), REGS64[r as usize].to_string())+ ("pop".into(), REGS64[r as usize].to_string())}- // MOV r/m, r+ // MOV r/m, r0x89 => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;@@ -356,9 +348,9 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- ("mov".into(), format!("{rm}, {reg_s}"))+ ("mov".into(), format!("{rm}, {reg_s}"))}- // MOV r, r/m+ // MOV r, r/m0x8B => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;@@ -369,71 +361,77 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- ("mov".into(), format!("{reg_s}, {rm}"))+ ("mov".into(), format!("{reg_s}, {rm}"))}- // MOV r/m8, r8+ // MOV r/m8, r80x88 => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, true)?;- ("mov".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))+ (+ "mov".into(),+ format!("{rm}, {}", reg_name(reg, false, false, true)),+ )}- // MOV r8, r/m8+ // MOV r8, r/m80x8A => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, true)?;- ("mov".into(), format!("{}, {rm}", reg_name(reg, false, false, true)))+ (+ "mov".into(),+ format!("{}, {rm}", reg_name(reg, false, false, true)),+ )}- // MOV r/m, imm32 (C7 /0)+ // MOV r/m, imm32 (C7 /0)0xC7 => {let modrm = cur.get()?;let reg_field = (modrm >> 3) & 7;if reg_field != 0 {- return Err(Error::Decode(format!("unhandled C7 /{reg_field}")));+ return Err(Error::Decode(format!("unhandled C7 /{reg_field}")));}let (_reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;let imm = if w64 {- // C7 still uses 32-bit imm sign-extended+ // C7 still uses 32-bit imm sign-extendedcur.take_imm(4)? as i32 as i64} else if op16 {cur.take_imm(2)? as i16 as i64} else {cur.take_imm(4)? as i32 as i64};- ("mov".into(), format!("{rm}, {imm:#x}"))+ ("mov".into(), format!("{rm}, {imm:#x}"))}- // MOV r64/r32, imm+ // MOV r64/r32, imm0xB8..=0xBF => {let r = (op - 0xB8) | if pfx.rex_b { 8 } else { 0 };if w64 {let imm = cur.take_imm(8)?;(- "mov".into(),- format!("{}, {imm:#x}", reg_name(r, true, false, false)),+ "mov".into(),+ format!("{}, {imm:#x}", reg_name(r, true, false, false)),)} else if op16 {let imm = cur.take_imm(2)?;(- "mov".into(),- format!("{}, {imm:#x}", reg_name(r, false, true, false)),+ "mov".into(),+ format!("{}, {imm:#x}", reg_name(r, false, true, false)),)} else {let imm = cur.take_imm(4)?;(- "mov".into(),- format!("{}, {imm:#x}", reg_name(r, false, false, false)),+ "mov".into(),+ format!("{}, {imm:#x}", reg_name(r, false, false, false)),)}}- // MOV r8, imm8+ // MOV r8, imm80xB0..=0xB7 => {let r = (op - 0xB0) | if pfx.rex_b { 8 } else { 0 };let imm = cur.take_imm(1)?;(- "mov".into(),- format!("{}, {imm:#x}", reg_name(r, false, false, true)),+ "mov".into(),+ format!("{}, {imm:#x}", reg_name(r, false, false, true)),)}- // LEA r, m+ // LEA r, m0x8D => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;@@ -444,19 +442,19 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- ("lea".into(), format!("{reg_s}, {rm}"))+ ("lea".into(), format!("{reg_s}, {rm}"))}- // ADD/OR/ADC/SBB/AND/SUB/XOR/CMP r/m, r (01 family)+ // ADD/OR/ADC/SBB/AND/SUB/XOR/CMP r/m, r (01 family)0x01 | 0x09 | 0x11 | 0x19 | 0x21 | 0x29 | 0x31 | 0x39 => {let mnem = match op {- 0x01 => "add",- 0x09 => "or",- 0x11 => "adc",- 0x19 => "sbb",- 0x21 => "and",- 0x29 => "sub",- 0x31 => "xor",- 0x39 => "cmp",+ 0x01 => "add",+ 0x09 => "or",+ 0x11 => "adc",+ 0x19 => "sbb",+ 0x21 => "and",+ 0x29 => "sub",+ 0x31 => "xor",+ 0x39 => "cmp",_ => unreachable!(),};let modrm = cur.get()?;@@ -468,19 +466,19 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- (mnem.into(), format!("{rm}, {reg_s}"))+ (mnem.into(), format!("{rm}, {reg_s}"))}- // same r, r/m+ // same r, r/m0x03 | 0x0B | 0x13 | 0x1B | 0x23 | 0x2B | 0x33 | 0x3B => {let mnem = match op {- 0x03 => "add",- 0x0B => "or",- 0x13 => "adc",- 0x1B => "sbb",- 0x23 => "and",- 0x2B => "sub",- 0x33 => "xor",- 0x3B => "cmp",+ 0x03 => "add",+ 0x0B => "or",+ 0x13 => "adc",+ 0x1B => "sbb",+ 0x23 => "and",+ 0x2B => "sub",+ 0x33 => "xor",+ 0x3B => "cmp",_ => unreachable!(),};let modrm = cur.get()?;@@ -492,10 +490,10 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- (mnem.into(), format!("{reg_s}, {rm}"))+ (mnem.into(), format!("{reg_s}, {rm}"))}- // XOR r/m8,r8 etc skip; XOR r32,r/m already covered- // TEST+ // XOR r/m8,r8 etc skip; XOR r32,r/m already covered+ // TEST0x85 => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;@@ -504,16 +502,19 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, op16, false)};- ("test".into(), format!("{rm}, {reg_s}"))+ ("test".into(), format!("{rm}, {reg_s}"))}- // TEST r/m8, r8+ // TEST r/m8, r80x84 => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;- ("test".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))+ (+ "test".into(),+ format!("{rm}, {}", reg_name(reg, false, false, true)),+ )}- // TEST r/m, imm (F6 /0, F7 /0) — handled in F6/F7 groups below.- // XCHG r/m, r+ // TEST r/m, imm (F6 /0, F7 /0) — handled in F6/F7 groups below.+ // XCHG r/m, r0x87 => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;@@ -524,36 +525,39 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- ("xchg".into(), format!("{rm}, {reg_s}"))+ ("xchg".into(), format!("{rm}, {reg_s}"))}- // XCHG r/m8, r8+ // XCHG r/m8, r80x86 => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;- ("xchg".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))+ (+ "xchg".into(),+ format!("{rm}, {}", reg_name(reg, false, false, true)),+ )}- // MOV r/m8, imm8 (C6 /0)+ // MOV r/m8, imm8 (C6 /0)0xC6 => {let modrm = cur.get()?;let reg_field = (modrm >> 3) & 7;if reg_field != 0 {- return Err(Error::Decode(format!("unhandled C6 /{reg_field}")));+ return Err(Error::Decode(format!("unhandled C6 /{reg_field}")));}let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;let imm = cur.take_imm(1)? as i8 as i64;- ("mov".into(), format!("{rm}, {imm:#x}"))+ ("mov".into(), format!("{rm}, {imm:#x}"))}- // MOVSXD r64, r/m32 (Windows compilers use this constantly).+ // MOVSXD r64, r/m32 (Windows compilers use this constantly).0x63 => {let modrm = cur.get()?;let (reg, rm_raw) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;- // Source is r/m32; when mod=3 name it as a 32-bit register even- // if REX.W is set. Memory forms get a "dword ptr" hint.+ // Source is r/m32; when mod=3 name it as a 32-bit register even+ // if REX.W is set. Memory forms get a "dword ptr" hint.let rm = if (modrm >> 6) == 3 {let src = (modrm & 7) | if pfx.rex_b { 8 } else { 0 };reg_name(src, false, false, false).to_string()- } else if !rm_raw.contains(" ptr ") {- format!("{}{}", size_prefix(4), rm_raw)+ } else if !rm_raw.contains(" ptr ") {+ format!("{}{}", size_prefix(4), rm_raw)} else {rm_raw};@@ -562,10 +566,10 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- let mnem = if w64 { "movsxd" } else { "mov" };- (mnem.into(), format!("{dst}, {rm}"))+ let mnem = if w64 { "movsxd" } else { "mov" };+ (mnem.into(), format!("{dst}, {rm}"))}- // IMUL r, r/m, imm8+ // IMUL r, r/m, imm80x6B => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;@@ -577,9 +581,9 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- ("imul".into(), format!("{dst}, {rm}, {imm:#x}"))+ ("imul".into(), format!("{dst}, {rm}, {imm:#x}"))}- // IMUL r, r/m, imm32+ // IMUL r, r/m, imm320x69 => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;@@ -595,22 +599,22 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- ("imul".into(), format!("{dst}, {rm}, {imm:#x}"))+ ("imul".into(), format!("{dst}, {rm}, {imm:#x}"))}- // Group 2 shift r/m, 1 (D0/D1) or r/m, cl (D2/D3)+ // Group 2 shift r/m, 1 (D0/D1) or r/m, cl (D2/D3)0xD0 | 0xD1 | 0xD2 | 0xD3 => {let modrm = cur.get()?;let reg_field = (modrm >> 3) & 7;let mnem = match reg_field {- 0 => "rol",- 1 => "ror",- 2 => "rcl",- 3 => "rcr",- 4 => "shl",- 5 => "shr",- 6 => "shl",- 7 => "sar",- _ => "grp2",+ 0 => "rol",+ 1 => "ror",+ 2 => "rcl",+ 3 => "rcr",+ 4 => "shl",+ 5 => "shr",+ 6 => "shl",+ 7 => "sar",+ _ => "grp2",};let byte_op = op == 0xD0 || op == 0xD2;let mem_size = if byte_op {@@ -624,26 +628,26 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {};let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, byte_op, mem_size)?;let count = if op == 0xD0 || op == 0xD1 {- "1".to_string()+ "1".to_string()} else {- "cl".to_string()+ "cl".to_string()};- (mnem.into(), format!("{rm}, {count}"))+ (mnem.into(), format!("{rm}, {count}"))}- // Group 2 shift r/m, imm8 (C0/C1)+ // Group 2 shift r/m, imm8 (C0/C1)0xC0 | 0xC1 => {let modrm = cur.get()?;let reg_field = (modrm >> 3) & 7;let mnem = match reg_field {- 0 => "rol",- 1 => "ror",- 2 => "rcl",- 3 => "rcr",- 4 => "shl",- 5 => "shr",- 6 => "shl",- 7 => "sar",- _ => "grp2",+ 0 => "rol",+ 1 => "ror",+ 2 => "rcl",+ 3 => "rcr",+ 4 => "shl",+ 5 => "shr",+ 6 => "shl",+ 7 => "sar",+ _ => "grp2",};let byte_op = op == 0xC0;let mem_size = if byte_op {@@ -657,9 +661,9 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {};let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, byte_op, mem_size)?;let imm = cur.take_imm(1)? as u8 as i64;- (mnem.into(), format!("{rm}, {imm:#x}"))+ (mnem.into(), format!("{rm}, {imm:#x}"))}- // Group 3 F6/F7 — test/not/neg/mul/imul/div/idiv r/m+ // Group 3 F6/F7 — test/not/neg/mul/imul/div/idiv r/m0xF6 | 0xF7 => {let modrm = cur.get()?;let reg_field = (modrm >> 3) & 7;@@ -676,7 +680,7 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, byte_op, mem_size)?;match reg_field {0 | 1 => {- // test r/m, imm+ // test r/m, immlet imm = if byte_op {cur.take_imm(1)? as i8 as i64} else if op16 {@@ -684,140 +688,140 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {cur.take_imm(4)? as i32 as i64};- ("test".into(), format!("{rm}, {imm:#x}"))+ ("test".into(), format!("{rm}, {imm:#x}"))}- 2 => ("not".into(), rm),- 3 => ("neg".into(), rm),- 4 => ("mul".into(), rm),- 5 => ("imul".into(), rm),- 6 => ("div".into(), rm),- 7 => ("idiv".into(), rm),- _ => ("grp3".into(), rm),+ 2 => ("not".into(), rm),+ 3 => ("neg".into(), rm),+ 4 => ("mul".into(), rm),+ 5 => ("imul".into(), rm),+ 6 => ("div".into(), rm),+ 7 => ("idiv".into(), rm),+ _ => ("grp3".into(), rm),}}- // NOP- 0x90 => ("nop".into(), String::new()),- // CBW / CWDE / CDQE+ // NOP+ 0x90 => ("nop".into(), String::new()),+ // CBW / CWDE / CDQE0x98 => {if w64 {- ("cdqe".into(), String::new())+ ("cdqe".into(), String::new())} else if op16 {- ("cbw".into(), String::new())+ ("cbw".into(), String::new())} else {- ("cwde".into(), String::new())+ ("cwde".into(), String::new())}}- // PUSHF / POPF (rex.w doesn't matter — these push RFLAGS)- 0x9C => ("pushfq".into(), String::new()),- 0x9D => ("popfq".into(), String::new()),- // HLT- 0xF4 => ("hlt".into(), String::new()),- // RET- 0xC3 => ("ret".into(), String::new()),+ // PUSHF / POPF (rex.w doesn't matter — these push RFLAGS)+ 0x9C => ("pushfq".into(), String::new()),+ 0x9D => ("popfq".into(), String::new()),+ // HLT+ 0xF4 => ("hlt".into(), String::new()),+ // RET+ 0xC3 => ("ret".into(), String::new()),0xC2 => {let imm = cur.take_imm(2)?;- ("ret".into(), format!("{imm:#x}"))+ ("ret".into(), format!("{imm:#x}"))}- // CALL rel32+ // CALL rel320xE8 => {let rel = cur.take_imm(4)? as i32 as i64;let target = address.wrapping_add(cur.pos as u64).wrapping_add(rel as u64);- ("call".into(), format!("{target:#x}"))+ ("call".into(), format!("{target:#x}"))}- // JMP rel32+ // JMP rel320xE9 => {let rel = cur.take_imm(4)? as i32 as i64;let target = address.wrapping_add(cur.pos as u64).wrapping_add(rel as u64);- ("jmp".into(), format!("{target:#x}"))+ ("jmp".into(), format!("{target:#x}"))}- // JMP rel8+ // JMP rel80xEB => {let rel = cur.take_imm(1)? as i8 as i64;let target = address.wrapping_add(cur.pos as u64).wrapping_add(rel as u64);- ("jmp".into(), format!("{target:#x}"))+ ("jmp".into(), format!("{target:#x}"))}- // Jcc rel8+ // Jcc rel80x70..=0x7F => {let names = [- "jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp", "jnp",- "jl", "jge", "jle", "jg",+ "jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp", "jnp", "jl",+ "jge", "jle", "jg",];let rel = cur.take_imm(1)? as i8 as i64;let target = address.wrapping_add(cur.pos as u64).wrapping_add(rel as u64);- (names[(op - 0x70) as usize].into(), format!("{target:#x}"))+ (names[(op - 0x70) as usize].into(), format!("{target:#x}"))}- // INT3- 0xCC => ("int3".into(), String::new()),- // CDQ / CQO+ // INT3+ 0xCC => ("int3".into(), String::new()),+ // CDQ / CQO0x99 => {if w64 {- ("cqo".into(), String::new())+ ("cqo".into(), String::new())} else {- ("cdq".into(), String::new())+ ("cdq".into(), String::new())}}- // LEAVE- 0xC9 => ("leave".into(), String::new()),- // Group1 Eb,Ib — ADD/OR/…/CMP r/m8, imm8 (80 /x); 82 is an alias+ // LEAVE+ 0xC9 => ("leave".into(), String::new()),+ // Group1 Eb,Ib — ADD/OR/…/CMP r/m8, imm8 (80 /x); 82 is an alias0x80 | 0x82 => {let modrm = cur.get()?;let reg_field = (modrm >> 3) & 7;let mnem = match reg_field {- 0 => "add",- 1 => "or",- 2 => "adc",- 3 => "sbb",- 4 => "and",- 5 => "sub",- 6 => "xor",- 7 => "cmp",- _ => "grp",+ 0 => "add",+ 1 => "or",+ 2 => "adc",+ 3 => "sbb",+ 4 => "and",+ 5 => "sub",+ 6 => "xor",+ 7 => "cmp",+ _ => "grp",};let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;let imm = cur.take_imm(1)? as i8 as i64;- (mnem.into(), format!("{rm}, {imm:#x}"))+ (mnem.into(), format!("{rm}, {imm:#x}"))}- // SUB/ADD r/m, imm8 (83 /x)+ // SUB/ADD r/m, imm8 (83 /x)0x83 => {let modrm = cur.get()?;let reg_field = (modrm >> 3) & 7;let mnem = match reg_field {- 0 => "add",- 1 => "or",- 2 => "adc",- 3 => "sbb",- 4 => "and",- 5 => "sub",- 6 => "xor",- 7 => "cmp",- _ => "grp",+ 0 => "add",+ 1 => "or",+ 2 => "adc",+ 3 => "sbb",+ 4 => "and",+ 5 => "sub",+ 6 => "xor",+ 7 => "cmp",+ _ => "grp",};let (_reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;let imm = cur.take_imm(1)? as i8 as i64;- (mnem.into(), format!("{rm}, {imm:#x}"))+ (mnem.into(), format!("{rm}, {imm:#x}"))}- // group 81 r/m, imm32+ // group 81 r/m, imm320x81 => {let modrm = cur.get()?;let reg_field = (modrm >> 3) & 7;let mnem = match reg_field {- 0 => "add",- 1 => "or",- 2 => "adc",- 3 => "sbb",- 4 => "and",- 5 => "sub",- 6 => "xor",- 7 => "cmp",- _ => "grp",+ 0 => "add",+ 1 => "or",+ 2 => "adc",+ 3 => "sbb",+ 4 => "and",+ 5 => "sub",+ 6 => "xor",+ 7 => "cmp",+ _ => "grp",};let (_reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;let imm = if op16 {@@ -825,70 +829,75 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {cur.take_imm(4)? as i32 as i64};- (mnem.into(), format!("{rm}, {imm:#x}"))+ (mnem.into(), format!("{rm}, {imm:#x}"))}- // two-byte 0F+ // two-byte 0F0x0F => {let op2 = cur.get()?;match op2 {- // MOVUPS xmm, xmm/m128 / MOVUPS xmm/m128, xmm+ // MOVUPS xmm, xmm/m128 / MOVUPS xmm/m128, xmm0x10 | 0x11 => {let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;if op2 == 0x10 {- ("movups".into(), format!("{xmm}, {rm}"))+ ("movups".into(), format!("{xmm}, {rm}"))} else {- ("movups".into(), format!("{rm}, {xmm}"))+ ("movups".into(), format!("{rm}, {xmm}"))}}- // MOVAPS xmm, xmm/m128 / MOVAPS xmm/m128, xmm+ // MOVAPS xmm, xmm/m128 / MOVAPS xmm/m128, xmm0x28 | 0x29 => {let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;if op2 == 0x28 {- ("movaps".into(), format!("{xmm}, {rm}"))+ ("movaps".into(), format!("{xmm}, {rm}"))} else {- ("movaps".into(), format!("{rm}, {xmm}"))+ ("movaps".into(), format!("{rm}, {xmm}"))}}- // MOVDQA xmm, xmm/m128 / MOVDQA xmm/m128, xmm (66 0F 6F / 7F)+ // MOVDQA xmm, xmm/m128 / MOVDQA xmm/m128, xmm (66 0F 6F / 7F)0x6F | 0x7F if pfx.op_size => {let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;if op2 == 0x6F {- ("movdqa".into(), format!("{xmm}, {rm}"))+ ("movdqa".into(), format!("{xmm}, {rm}"))} else {- ("movdqa".into(), format!("{rm}, {xmm}"))+ ("movdqa".into(), format!("{rm}, {xmm}"))}}- // XORPS xmm, xmm/m128+ // XORPS xmm, xmm/m1280x57 => {let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;- ("xorps".into(), format!("{xmm}, {rm}"))+ ("xorps".into(), format!("{xmm}, {rm}"))}- // PXOR xmm, xmm/m128 (66 0F EF)+ // PXOR xmm, xmm/m128 (66 0F EF)0xEF if pfx.op_size => {let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;- ("pxor".into(), format!("{xmm}, {rm}"))+ ("pxor".into(), format!("{xmm}, {rm}"))}- // Jcc rel32+ // Jcc rel320x80..=0x8F => {let names = [- "jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp",- "jnp", "jl", "jge", "jle", "jg",+ "jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp",+ "jnp", "jl", "jge", "jle", "jg",];let rel = cur.take_imm(4)? as i32 as i64;let target = address.wrapping_add(cur.pos as u64).wrapping_add(rel as u64);- (names[(op2 - 0x80) as usize].into(), format!("{target:#x}"))+ (names[(op2 - 0x80) as usize].into(), format!("{target:#x}"))}- // CMOVcc r, r/m+ // CMOVcc r, r/m0x40..=0x4F => {let names = [- "cmovo", "cmovno", "cmovb", "cmovae", "cmove", "cmovne", "cmovbe",- "cmova", "cmovs", "cmovns", "cmovp", "cmovnp", "cmovl", "cmovge",- "cmovle", "cmovg",+ "cmovo", "cmovno", "cmovb", "cmovae", "cmove", "cmovne", "cmovbe", "cmova",+ "cmovs", "cmovns", "cmovp", "cmovnp", "cmovl", "cmovge", "cmovle", "cmovg",];let modrm = cur.get()?;- let mem_size = if w64 { 8 } else if op16 { 2 } else { 4 };+ let mem_size = if w64 {+ 8+ } else if op16 {+ 2+ } else {+ 4+ };let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, false, mem_size)?;let dst = if w64 {reg_name(reg, true, false, false)@@ -897,19 +906,19 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- (names[(op2 - 0x40) as usize].into(), format!("{dst}, {rm}"))+ (names[(op2 - 0x40) as usize].into(), format!("{dst}, {rm}"))}- // SETcc r/m8+ // SETcc r/m80x90..=0x9F => {let names = [- "seto", "setno", "setb", "setae", "sete", "setne", "setbe", "seta",- "sets", "setns", "setp", "setnp", "setl", "setge", "setle", "setg",+ "seto", "setno", "setb", "setae", "sete", "setne", "setbe", "seta", "sets",+ "setns", "setp", "setnp", "setl", "setge", "setle", "setg",];let modrm = cur.get()?;let (_r, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;(names[(op2 - 0x90) as usize].into(), rm)}- // MOVZX r, r/m8+ // MOVZX r, r/m80xB6 => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;@@ -920,19 +929,19 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- ("movzx".into(), format!("{dst}, {rm}"))+ ("movzx".into(), format!("{dst}, {rm}"))}- // MOVZX r, r/m16+ // MOVZX r, r/m160xB7 => {let modrm = cur.get()?;- // r/m is 16-bit; when mod=3 that's a word reg.+ // r/m is 16-bit; when mod=3 that's a word reg.let (reg, rm_raw) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;let rm = if (modrm >> 6) == 3 {- // Force word regnames on the source.+ // Force word regnames on the source.let src = (modrm & 7) | if pfx.rex_b { 8 } else { 0 };reg_name(src, false, true, false).to_string()- } else if !rm_raw.contains(" ptr ") {- format!("{}{}", size_prefix(2), rm_raw)+ } else if !rm_raw.contains(" ptr ") {+ format!("{}{}", size_prefix(2), rm_raw)} else {rm_raw};@@ -943,9 +952,9 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- ("movzx".into(), format!("{dst}, {rm}"))+ ("movzx".into(), format!("{dst}, {rm}"))}- // MOVSX r, r/m8+ // MOVSX r, r/m80xBE => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;@@ -956,17 +965,17 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- ("movsx".into(), format!("{dst}, {rm}"))+ ("movsx".into(), format!("{dst}, {rm}"))}- // MOVSX r, r/m16+ // MOVSX r, r/m160xBF => {let modrm = cur.get()?;let (reg, rm_raw) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;let rm = if (modrm >> 6) == 3 {let src = (modrm & 7) | if pfx.rex_b { 8 } else { 0 };reg_name(src, false, true, false).to_string()- } else if !rm_raw.contains(" ptr ") {- format!("{}{}", size_prefix(2), rm_raw)+ } else if !rm_raw.contains(" ptr ") {+ format!("{}{}", size_prefix(2), rm_raw)} else {rm_raw};@@ -977,9 +986,9 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- ("movsx".into(), format!("{dst}, {rm}"))+ ("movsx".into(), format!("{dst}, {rm}"))}- // IMUL r, r/m+ // IMUL r, r/m0xAF => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;@@ -990,9 +999,9 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(reg, false, false, false)};- ("imul".into(), format!("{dst}, {rm}"))+ ("imul".into(), format!("{dst}, {rm}"))}- // BSWAP r32/r64+ // BSWAP r32/r640xC8..=0xCF => {let r = (op2 - 0xC8) | if pfx.rex_b { 8 } else { 0 };let reg = if w64 {@@ -1000,61 +1009,67 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {} else {reg_name(r, false, false, false)};- ("bswap".into(), reg.to_string())+ ("bswap".into(), reg.to_string())}- // UD2- 0x0B => ("ud2".into(), String::new()),- // ENDBR64 / ENDBR32 (F3 0F 1E FA / FB) — with F3 already consumed as `rep`.+ // UD2+ 0x0B => ("ud2".into(), String::new()),+ // ENDBR64 / ENDBR32 (F3 0F 1E FA / FB) — with F3 already consumed as `rep`.0x1E if pfx.rep => {let modrm = cur.get()?;let m = match modrm {- 0xFA => "endbr64",- 0xFB => "endbr32",- _ => "endbr",+ 0xFA => "endbr64",+ 0xFB => "endbr32",+ _ => "endbr",};(m.into(), String::new())}0x1F => {- // NOP r/m+ // NOP r/mlet modrm = cur.get()?;let (_r, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;- ("nop".into(), rm)+ ("nop".into(), rm)}- 0x05 => ("syscall".into(), String::new()),- 0xA2 => ("cpuid".into(), String::new()),+ 0x05 => ("syscall".into(), String::new()),+ 0xA2 => ("cpuid".into(), String::new()),_ => {- return Err(Error::Decode(format!("unhandled 0F {op2:02x}")));+ return Err(Error::Decode(format!("unhandled 0F {op2:02x}")));}}}- // FF /2 CALL, /4 JMP+ // FF /2 CALL, /4 JMP0xFF => {let modrm = cur.get()?;let reg_field = (modrm >> 3) & 7;let (_r, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;match reg_field {- 2 => ("call".into(), rm),- 4 => ("jmp".into(), rm),- 6 => ("push".into(), rm),+ 2 => ("call".into(), rm),+ 4 => ("jmp".into(), rm),+ 6 => ("push".into(), rm),_ => {- return Err(Error::Decode(format!("unhandled FF /{reg_field}")));+ return Err(Error::Decode(format!("unhandled FF /{reg_field}")));}}}- // XOR r8,r8 style short: 31 already; also 30+ // XOR r8,r8 style short: 31 already; also 300x30 | 0x32 => {let modrm = cur.get()?;let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, true)?;- let mnem = if op == 0x30 { "xor" } else { "xor" };+ let mnem = if op == 0x30 { "xor" } else { "xor" };if op == 0x30 {- (mnem.into(), format!("{rm}, {}", reg_name(reg, false, false, true)))+ (+ mnem.into(),+ format!("{rm}, {}", reg_name(reg, false, false, true)),+ )} else {- (mnem.into(), format!("{}, {rm}", reg_name(reg, false, false, true)))+ (+ mnem.into(),+ format!("{}, {rm}", reg_name(reg, false, false, true)),+ )}}other => {return Err(Error::Decode(format!(- "unhandled opcode {other:02x} at {address:#x}"+ "unhandled opcode {other:02x} at {address:#x}")));}};@@ -1077,179 +1092,183 @@ mod tests {#[test]fn decode_push_rbp_mov_rbp_rsp() {- // 55 push rbp- // 48 89 e5 mov rbp, rsp+ // 55 push rbp+ // 48 89 e5 mov rbp, rsplet b = [0x55, 0x48, 0x89, 0xe5];let i0 = decode_one(&b, 0x1000).unwrap();- assert_eq!(i0.mnemonic, "push");- assert_eq!(i0.operands, "rbp");+ assert_eq!(i0.mnemonic, "push");+ assert_eq!(i0.operands, "rbp");assert_eq!(i0.length, 1);let i1 = decode_one(&b[1..], 0x1001).unwrap();- assert_eq!(i1.mnemonic, "mov");- assert_eq!(i1.operands, "rbp, rsp");+ assert_eq!(i1.mnemonic, "mov");+ assert_eq!(i1.operands, "rbp, rsp");}#[test]fn decode_xor_eax_eax_ret() {- // 31 c0 xor eax, eax- // c3 ret+ // 31 c0 xor eax, eax+ // c3 retlet b = [0x31, 0xc0, 0xc3];let i0 = decode_one(&b, 0).unwrap();- assert_eq!(i0.mnemonic, "xor");- assert_eq!(i0.operands, "eax, eax");+ assert_eq!(i0.mnemonic, "xor");+ assert_eq!(i0.operands, "eax, eax");let i1 = decode_one(&b[2..], 2).unwrap();- assert_eq!(i1.mnemonic, "ret");+ assert_eq!(i1.mnemonic, "ret");}#[test]fn decode_cmovcc_register() {- // 48 0f 45 c8 cmovne rcx, rax+ // 48 0f 45 c8 cmovne rcx, raxlet i = decode_one(&[0x48, 0x0f, 0x45, 0xc8], 0).unwrap();- assert_eq!(i.mnemonic, "cmovne");- assert_eq!(i.operands, "rcx, rax");+ assert_eq!(i.mnemonic, "cmovne");+ assert_eq!(i.operands, "rcx, rax");assert_eq!(i.length, 4);}#[test]fn decode_setcc_r8() {- // 0f 94 c0 sete al+ // 0f 94 c0 sete allet i = decode_one(&[0x0f, 0x94, 0xc0], 0).unwrap();- assert_eq!(i.mnemonic, "sete");- assert_eq!(i.operands, "al");+ assert_eq!(i.mnemonic, "sete");+ assert_eq!(i.operands, "al");}#[test]fn decode_movzx_r32_r8() {- // 0f b6 c1 movzx eax, cl+ // 0f b6 c1 movzx eax, cllet i = decode_one(&[0x0f, 0xb6, 0xc1], 0).unwrap();- assert_eq!(i.mnemonic, "movzx");- assert_eq!(i.operands, "eax, cl");+ assert_eq!(i.mnemonic, "movzx");+ assert_eq!(i.operands, "eax, cl");}#[test]fn decode_movsxd_r64_r32() {- // 48 63 c1 movsxd rax, ecx+ // 48 63 c1 movsxd rax, ecxlet i = decode_one(&[0x48, 0x63, 0xc1], 0).unwrap();- assert_eq!(i.mnemonic, "movsxd");- assert_eq!(i.operands, "rax, ecx");+ assert_eq!(i.mnemonic, "movsxd");+ assert_eq!(i.operands, "rax, ecx");}#[test]fn decode_shr_by_cl_and_shl_imm() {- // c1 e0 03 shl eax, 3+ // c1 e0 03 shl eax, 3let a = decode_one(&[0xc1, 0xe0, 0x03], 0).unwrap();- assert_eq!(a.mnemonic, "shl");- assert_eq!(a.operands, "eax, 0x3");- // d3 e8 shr eax, cl+ assert_eq!(a.mnemonic, "shl");+ assert_eq!(a.operands, "eax, 0x3");+ // d3 e8 shr eax, cllet b = decode_one(&[0xd3, 0xe8], 0).unwrap();- assert_eq!(b.mnemonic, "shr");- assert_eq!(b.operands, "eax, cl");+ assert_eq!(b.mnemonic, "shr");+ assert_eq!(b.operands, "eax, cl");}#[test]fn decode_group3_neg_and_not() {- // f7 d8 neg eax+ // f7 d8 neg eaxlet a = decode_one(&[0xf7, 0xd8], 0).unwrap();- assert_eq!(a.mnemonic, "neg");- assert_eq!(a.operands, "eax");- // f7 d0 not eax+ assert_eq!(a.mnemonic, "neg");+ assert_eq!(a.operands, "eax");+ // f7 d0 not eaxlet b = decode_one(&[0xf7, 0xd0], 0).unwrap();- assert_eq!(b.mnemonic, "not");+ assert_eq!(b.mnemonic, "not");}#[test]fn decode_hlt_and_int3() {- assert_eq!(decode_one(&[0xf4], 0).unwrap().mnemonic, "hlt");- assert_eq!(decode_one(&[0xcc], 0).unwrap().mnemonic, "int3");+ assert_eq!(decode_one(&[0xf4], 0).unwrap().mnemonic, "hlt");+ assert_eq!(decode_one(&[0xcc], 0).unwrap().mnemonic, "int3");}#[test]fn decode_endbr64() {- // f3 0f 1e fa endbr64+ // f3 0f 1e fa endbr64let i = decode_one(&[0xf3, 0x0f, 0x1e, 0xfa], 0).unwrap();- assert_eq!(i.mnemonic, "endbr64");+ assert_eq!(i.mnemonic, "endbr64");}#[test]fn decode_imul_with_imm() {- // 6b c0 03 imul eax, eax, 3+ // 6b c0 03 imul eax, eax, 3let i = decode_one(&[0x6b, 0xc0, 0x03], 0).unwrap();- assert_eq!(i.mnemonic, "imul");- assert_eq!(i.operands, "eax, eax, 0x3");+ assert_eq!(i.mnemonic, "imul");+ assert_eq!(i.operands, "eax, eax, 0x3");}#[test]fn decode_ud2_and_bswap() {- assert_eq!(decode_one(&[0x0f, 0x0b], 0).unwrap().mnemonic, "ud2");- // 0f c8 bswap eax+ assert_eq!(decode_one(&[0x0f, 0x0b], 0).unwrap().mnemonic, "ud2");+ // 0f c8 bswap eaxlet b = decode_one(&[0x0f, 0xc8], 0).unwrap();- assert_eq!(b.mnemonic, "bswap");- assert_eq!(b.operands, "eax");+ assert_eq!(b.mnemonic, "bswap");+ assert_eq!(b.operands, "eax");}#[test]fn decode_sib_with_scale_still_valid() {- // 8b 04 88 mov eax, [rax+rcx*4]+ // 8b 04 88 mov eax, [rax+rcx*4]let i = decode_one(&[0x8b, 0x04, 0x88], 0).unwrap();- assert_eq!(i.mnemonic, "mov");+ assert_eq!(i.mnemonic, "mov");assert!(- i.operands.contains("rcx*4"),- "expected SIB scale 4, got '{}'",+ i.operands.contains("rcx*4"),+ "expected SIB scale 4, got '{}'",i.operands);}#[test]fn decode_group1_byte_cmp_mem_imm8() {- // 80 b9 e1 01 00 00 00 cmp byte ptr [rcx+0x1e1], 0x0+ // 80 b9 e1 01 00 00 00 cmp byte ptr [rcx+0x1e1], 0x0let i = decode_one(&[0x80, 0xb9, 0xe1, 0x01, 0x00, 0x00, 0x00], 0).unwrap();- assert_eq!(i.mnemonic, "cmp");+ assert_eq!(i.mnemonic, "cmp");assert_eq!(i.length, 7);assert!(- i.operands.contains("byte ptr") && i.operands.contains("[rcx+0x1e1]"),- "got '{}'",+ i.operands.contains("byte ptr") && i.operands.contains("[rcx+0x1e1]"),+ "got '{}'",+ i.operands+ );+ assert!(+ i.operands.ends_with(", 0x0") || i.operands.ends_with(", 0"),+ "got '{}'",i.operands);- assert!(i.operands.ends_with(", 0x0") || i.operands.ends_with(", 0"), "got '{}'", i.operands);}#[test]fn decode_movups_load_store() {- // 0f 10 1a movups xmm3, [rdx]+ // 0f 10 1a movups xmm3, [rdx]let load = decode_one(&[0x0f, 0x10, 0x1a], 0).unwrap();- assert_eq!(load.mnemonic, "movups");- assert_eq!(load.operands, "xmm3, [rdx]");- // 0f 11 59 10 movups [rcx+0x10], xmm3+ assert_eq!(load.mnemonic, "movups");+ assert_eq!(load.operands, "xmm3, [rdx]");+ // 0f 11 59 10 movups [rcx+0x10], xmm3let store = decode_one(&[0x0f, 0x11, 0x59, 0x10], 0).unwrap();- assert_eq!(store.mnemonic, "movups");- assert_eq!(store.operands, "[rcx+0x10], xmm3");+ assert_eq!(store.mnemonic, "movups");+ assert_eq!(store.operands, "[rcx+0x10], xmm3");}#[test]fn decode_movaps_reg_reg() {- // 0f 28 c1 movaps xmm0, xmm1+ // 0f 28 c1 movaps xmm0, xmm1let i = decode_one(&[0x0f, 0x28, 0xc1], 0).unwrap();- assert_eq!(i.mnemonic, "movaps");- assert_eq!(i.operands, "xmm0, xmm1");+ assert_eq!(i.mnemonic, "movaps");+ assert_eq!(i.operands, "xmm0, xmm1");}#[test]fn decode_xorps_zeroing() {- // 0f 57 c0 xorps xmm0, xmm0+ // 0f 57 c0 xorps xmm0, xmm0let i = decode_one(&[0x0f, 0x57, 0xc0], 0).unwrap();- assert_eq!(i.mnemonic, "xorps");- assert_eq!(i.operands, "xmm0, xmm0");+ assert_eq!(i.mnemonic, "xorps");+ assert_eq!(i.operands, "xmm0, xmm0");}#[test]fn decode_pxor_and_movdqa() {- // 66 0f ef c9 pxor xmm1, xmm1+ // 66 0f ef c9 pxor xmm1, xmm1let i = decode_one(&[0x66, 0x0f, 0xef, 0xc9], 0).unwrap();- assert_eq!(i.mnemonic, "pxor");- assert_eq!(i.operands, "xmm1, xmm1");- // 66 0f 6f c1 movdqa xmm0, xmm1+ assert_eq!(i.mnemonic, "pxor");+ assert_eq!(i.operands, "xmm1, xmm1");+ // 66 0f 6f c1 movdqa xmm0, xmm1let m = decode_one(&[0x66, 0x0f, 0x6f, 0xc1], 0).unwrap();- assert_eq!(m.mnemonic, "movdqa");- assert_eq!(m.operands, "xmm0, xmm1");+ assert_eq!(m.mnemonic, "movdqa");+ assert_eq!(m.operands, "xmm0, xmm1");}}diff --git a/crates/ghidrust-decode/src/arch/x86/mod.rs b/crates/ghidrust-decode/src/arch/x86/mod.rsindex a5b5a5f..90773c9 100644--- a/crates/ghidrust-decode/src/arch/x86/mod.rs+++ b/crates/ghidrust-decode/src/arch/x86/mod.rs@@ -24,14 +24,14 @@ impl ArchDecode for X86Decoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::X86) {- return Err(Error::Mode(format!("invalid x86 mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!("invalid x86 mode {:#x}", mode.bits())));}Ok(Self { mode })}fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {let mut insn = legacy::decode_one(bytes, address)?;- // Mode width: rewrite GP names for 16/32-bit engines .+ // Mode width: rewrite GP names for 16/32-bit engines .if self.mode.intersects(Mode::MODE_16) {insn.operands = rewrite_width(&insn.operands, Width::W16);} else if self.mode.intersects(Mode::MODE_32) && !self.mode.intersects(Mode::MODE_64) {@@ -46,7 +46,7 @@ impl ArchDecode for X86Decoder {insn.operands = syntax::att::reformat_operands(&insn.mnemonic, &insn.operands);}Syntax::Masm => {- // MASM-like: keep Intel operand order; ensure hex suffix style later.+ // MASM-like: keep Intel operand order; ensure hex suffix style later.}Syntax::NoRegName => {insn.operands = syntax::noregname::strip_reg_names(&insn.operands);@@ -75,17 +75,17 @@ impl ArchDecode for X86Decoder {}fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {- if mnemonic == "ret" || mnemonic.starts_with("ret") {+ if mnemonic == "ret" || mnemonic.starts_with("ret") {vec![GroupId::Ret]- } else if mnemonic == "call" {+ } else if mnemonic == "call" {vec![GroupId::Call, GroupId::BranchRelative]- } else if mnemonic.starts_with('j') {+ } else if mnemonic.starts_with('j') {vec![GroupId::Jump, GroupId::BranchRelative]- } else if mnemonic == "int3" || mnemonic.starts_with("int") || mnemonic == "syscall" {+ } else if mnemonic == "int3" || mnemonic.starts_with("int") || mnemonic == "syscall" {vec![GroupId::Int]- } else if mnemonic == "iret" || mnemonic == "iretd" || mnemonic == "iretq" {+ } else if mnemonic == "iret" || mnemonic == "iretd" || mnemonic == "iretq" {vec![GroupId::Iret]- } else if mnemonic == "hlt" || mnemonic == "cli" || mnemonic == "sti" || mnemonic == "lgdt" {+ } else if mnemonic == "hlt" || mnemonic == "cli" || mnemonic == "sti" || mnemonic == "lgdt" {vec![GroupId::Privilege]} else {Vec::new()@@ -96,18 +96,18 @@ fn detail_regs(insn: &Instruction) -> (Vec<RegId>, Vec<RegId>) {let mut reads = Vec::new();let mut writes = Vec::new();for (i, name) in [- "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12",- "r13", "r14", "r15", "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi",+ "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12",+ "r13", "r14", "r15", "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi",].iter().enumerate(){if insn.operands.contains(name) {let id = RegId::new((i % 16) as u32);- // Heuristic: first operand write for Intel mov/lea/…+ // Heuristic: first operand write for Intel mov/lea/…if insn.operands.find(name) == Some(0)|| insn.operands.starts_with(name)- || insn.operands.starts_with(&format!("{name},"))+ || insn.operands.starts_with(&format!("{name},")){writes.push(id);} else {@@ -115,7 +115,7 @@ fn detail_regs(insn: &Instruction) -> (Vec<RegId>, Vec<RegId>) {}}}- if insn.mnemonic == "push" || insn.mnemonic == "call" || insn.mnemonic == "ret" {+ if insn.mnemonic == "push" || insn.mnemonic == "call" || insn.mnemonic == "ret" {writes.push(RegId::new(4)); // rspreads.push(RegId::new(4));}@@ -127,14 +127,16 @@ fn typed_operands(insn: &Instruction) -> Vec<Operand> {return Vec::new();}insn.operands- .split(", ")+ .split(", ").map(|part| {let p = part.trim();- if p.starts_with('0') || p.chars().all(|c| c.is_ascii_hexdigit() || c == 'x' || c == '-')+ if p.starts_with('0')+ || p.chars()+ .all(|c| c.is_ascii_hexdigit() || c == 'x' || c == '-'){let v = parse_imm(p).unwrap_or(0);Operand::Imm { value: v, size: 8 }- } else if p.contains('[') {+ } else if p.contains('[') {Operand::Mem {base: RegId::INVALID,index: RegId::INVALID,@@ -152,8 +154,8 @@ fn typed_operands(insn: &Instruction) -> Vec<Operand> {fn parse_imm(s: &str) -> Option<i64> {let s = s.trim();- if let Some(rest) = s.strip_prefix("0x").or_else(|| s.strip_prefix("-0x")) {- let neg = s.starts_with('-');+ if let Some(rest) = s.strip_prefix("0x").or_else(|| s.strip_prefix("-0x")) {+ let neg = s.starts_with('-');let v = i64::from_str_radix(rest, 16).ok()?;Some(if neg { -v } else { v })} else {@@ -163,81 +165,81 @@ fn parse_imm(s: &str) -> Option<i64> {pub fn reg_name(reg: RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("rax"),- 1 => Some("rcx"),- 2 => Some("rdx"),- 3 => Some("rbx"),- 4 => Some("rsp"),- 5 => Some("rbp"),- 6 => Some("rsi"),- 7 => Some("rdi"),- 8 => Some("r8"),- 9 => Some("r9"),- 10 => Some("r10"),- 11 => Some("r11"),- 12 => Some("r12"),- 13 => Some("r13"),- 14 => Some("r14"),- 15 => Some("r15"),+ 0 => Some("rax"),+ 1 => Some("rcx"),+ 2 => Some("rdx"),+ 3 => Some("rbx"),+ 4 => Some("rsp"),+ 5 => Some("rbp"),+ 6 => Some("rsi"),+ 7 => Some("rdi"),+ 8 => Some("r8"),+ 9 => Some("r9"),+ 10 => Some("r10"),+ 11 => Some("r11"),+ 12 => Some("r12"),+ 13 => Some("r13"),+ 14 => Some("r14"),+ 15 => Some("r15"),_ => None,}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("push"),- 2 => Some("pop"),- 3 => Some("mov"),- 4 => Some("ret"),- 5 => Some("call"),- 6 => Some("jmp"),- 7 => Some("nop"),- 8 => Some("xor"),- 9 => Some("add"),- 10 => Some("sub"),- 11 => Some("test"),- 12 => Some("cmp"),- 13 => Some("lea"),- 14 => Some("leave"),- 15 => Some("hlt"),- 16 => Some("int3"),+ 1 => Some("push"),+ 2 => Some("pop"),+ 3 => Some("mov"),+ 4 => Some("ret"),+ 5 => Some("call"),+ 6 => Some("jmp"),+ 7 => Some("nop"),+ 8 => Some("xor"),+ 9 => Some("add"),+ 10 => Some("sub"),+ 11 => Some("test"),+ 12 => Some("cmp"),+ 13 => Some("lea"),+ 14 => Some("leave"),+ 15 => Some("hlt"),+ 16 => Some("int3"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Ret => Some("ret"),- GroupId::Int => Some("int"),- GroupId::Iret => Some("iret"),- GroupId::Privilege => Some("privilege"),- GroupId::BranchRelative => Some("branch_relative"),- GroupId::Invalid => Some("invalid"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Ret => Some("ret"),+ GroupId::Int => Some("int"),+ GroupId::Iret => Some("iret"),+ GroupId::Privilege => Some("privilege"),+ GroupId::BranchRelative => Some("branch_relative"),+ GroupId::Invalid => Some("invalid"),GroupId::Arch(_) => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "push" => 1,- "pop" => 2,- "mov" | "movsxd" | "movzx" | "movsx" | "movups" | "movaps" | "movdqa" => 3,- "ret" => 4,- "call" => 5,- "jmp" | "jo" | "jno" | "jb" | "jae" | "je" | "jne" | "jbe" | "ja" | "js" | "jns"- | "jp" | "jnp" | "jl" | "jge" | "jle" | "jg" | "cmovne" | "cmovz" => 6,- "nop" | "endbr64" | "endbr32" | "endbr" => 7,- "xor" | "pxor" | "xorps" => 8,- "add" => 9,- "sub" => 10,- "test" => 11,- "cmp" => 12,- "lea" => 13,- "leave" => 14,- "hlt" => 15,- "int3" => 16,+ "push" => 1,+ "pop" => 2,+ "mov" | "movsxd" | "movzx" | "movsx" | "movups" | "movaps" | "movdqa" => 3,+ "ret" => 4,+ "call" => 5,+ "jmp" | "jo" | "jno" | "jb" | "jae" | "je" | "jne" | "jbe" | "ja" | "js" | "jns" | "jp"+ | "jnp" | "jl" | "jge" | "jle" | "jg" | "cmovne" | "cmovz" => 6,+ "nop" | "endbr64" | "endbr32" | "endbr" => 7,+ "xor" | "pxor" | "xorps" => 8,+ "add" => 9,+ "sub" => 10,+ "test" => 11,+ "cmp" => 12,+ "lea" => 13,+ "leave" => 14,+ "hlt" => 15,+ "int3" => 16,_ => 0,};InsnId(id)@@ -251,40 +253,40 @@ enum Width {fn rewrite_width(operands: &str, w: Width) -> String {let pairs: &[(&str, &str)] = match w {Width::W32 => &[- ("rax", "eax"),- ("rcx", "ecx"),- ("rdx", "edx"),- ("rbx", "ebx"),- ("rsp", "esp"),- ("rbp", "ebp"),- ("rsi", "esi"),- ("rdi", "edi"),- ("r8", "r8d"),- ("r9", "r9d"),- ("r10", "r10d"),- ("r11", "r11d"),- ("r12", "r12d"),- ("r13", "r13d"),- ("r14", "r14d"),- ("r15", "r15d"),+ ("rax", "eax"),+ ("rcx", "ecx"),+ ("rdx", "edx"),+ ("rbx", "ebx"),+ ("rsp", "esp"),+ ("rbp", "ebp"),+ ("rsi", "esi"),+ ("rdi", "edi"),+ ("r8", "r8d"),+ ("r9", "r9d"),+ ("r10", "r10d"),+ ("r11", "r11d"),+ ("r12", "r12d"),+ ("r13", "r13d"),+ ("r14", "r14d"),+ ("r15", "r15d"),],Width::W16 => &[- ("rax", "ax"),- ("rcx", "cx"),- ("rdx", "dx"),- ("rbx", "bx"),- ("rsp", "sp"),- ("rbp", "bp"),- ("rsi", "si"),- ("rdi", "di"),- ("eax", "ax"),- ("ecx", "cx"),- ("edx", "dx"),- ("ebx", "bx"),- ("esp", "sp"),- ("ebp", "bp"),- ("esi", "si"),- ("edi", "di"),+ ("rax", "ax"),+ ("rcx", "cx"),+ ("rdx", "dx"),+ ("rbx", "bx"),+ ("rsp", "sp"),+ ("rbp", "bp"),+ ("rsi", "si"),+ ("rdi", "di"),+ ("eax", "ax"),+ ("ecx", "cx"),+ ("edx", "dx"),+ ("ebx", "bx"),+ ("esp", "sp"),+ ("ebp", "bp"),+ ("esi", "si"),+ ("edi", "di"),],};let mut out = operands.to_string();diff --git a/crates/ghidrust-decode/src/arch/x86/syntax/att.rs b/crates/ghidrust-decode/src/arch/x86/syntax/att.rsindex e96afbb..5010e29 100644--- a/crates/ghidrust-decode/src/arch/x86/syntax/att.rs+++ b/crates/ghidrust-decode/src/arch/x86/syntax/att.rs@@ -4,24 +4,24 @@ pub fn reformat_operands(mnemonic: &str, operands: &str) -> String {if operands.is_empty() {return String::new();}- let parts: Vec<&str> = operands.split(", ").collect();+ let parts: Vec<&str> = operands.split(", ").collect();let mapped: Vec<String> = parts.iter().map(|p| {let p = p.trim();- if p.starts_with('[') || p.contains(" ptr ") {- format!("*{p}")- } else if p.starts_with("0x") || p.starts_with("-0x") || p.parse::<i64>().is_ok() {- format!("${p}")+ if p.starts_with('[') || p.contains(" ptr ") {+ format!("*{p}")+ } else if p.starts_with("0x") || p.starts_with("-0x") || p.parse::<i64>().is_ok() {+ format!("${p}")} else {- format!("%{p}")+ format!("%{p}")}}).collect();- // AT&T reverses src,dst for most two-operand forms.- if mapped.len() == 2 && mnemonic != "bound" {- format!("{}, {}", mapped[1], mapped[0])+ // AT&T reverses src,dst for most two-operand forms.+ if mapped.len() == 2 && mnemonic != "bound" {+ format!("{}, {}", mapped[1], mapped[0])} else {- mapped.join(", ")+ mapped.join(", ")}}diff --git a/crates/ghidrust-decode/src/arch/x86/syntax/mod.rs b/crates/ghidrust-decode/src/arch/x86/syntax/mod.rsindex 9e70f8d..92c9612 100644--- a/crates/ghidrust-decode/src/arch/x86/syntax/mod.rs+++ b/crates/ghidrust-decode/src/arch/x86/syntax/mod.rs@@ -4,16 +4,16 @@ pub mod noregname;/// Rewrite immediates that look negative hex into unsigned hex when possible.pub fn unsigned_imm(operands: &str) -> String {operands- .split(", ")+ .split(", ").map(|part| {let p = part.trim();- if let Some(rest) = p.strip_prefix("-0x") {+ if let Some(rest) = p.strip_prefix("-0x") {if let Ok(v) = u64::from_str_radix(rest, 16) {- return format!("{:#x}", (!v).wrapping_add(1));+ return format!("{:#x}", (!v).wrapping_add(1));}}p.to_string()}).collect::<Vec<_>>()- .join(", ")+ .join(", ")}diff --git a/crates/ghidrust-decode/src/arch/x86/syntax/noregname.rs b/crates/ghidrust-decode/src/arch/x86/syntax/noregname.rsindex 1bb4802..e2d199b 100644--- a/crates/ghidrust-decode/src/arch/x86/syntax/noregname.rs+++ b/crates/ghidrust-decode/src/arch/x86/syntax/noregname.rs@@ -3,14 +3,14 @@pub fn strip_reg_names(operands: &str) -> String {let mut out = operands.to_string();for (i, name) in [- "r15", "r14", "r13", "r12", "r11", "r10", "r9", "r8", "rax", "rcx", "rdx", "rbx", "rsp",- "rbp", "rsi", "rdi", "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "ax", "cx",- "dx", "bx", "sp", "bp", "si", "di", "al", "cl", "dl", "bl",+ "r15", "r14", "r13", "r12", "r11", "r10", "r9", "r8", "rax", "rcx", "rdx", "rbx", "rsp",+ "rbp", "rsi", "rdi", "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "ax", "cx",+ "dx", "bx", "sp", "bp", "si", "di", "al", "cl", "dl", "bl",].iter().enumerate(){- out = out.replace(name, &format!("r{i}"));+ out = out.replace(name, &format!("r{i}"));}out}diff --git a/crates/ghidrust-decode/src/arch/xcore/decode.rs b/crates/ghidrust-decode/src/arch/xcore/decode.rsindex 6665b13..a386c39 100644--- a/crates/ghidrust-decode/src/arch/xcore/decode.rs+++ b/crates/ghidrust-decode/src/arch/xcore/decode.rs@@ -2,17 +2,17 @@ use crate::error::{Error, Result};pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("r0"),- 1 => Some("r1"),- 10 => Some("sp"),- 11 => Some("lr"),+ 0 => Some("r0"),+ 1 => Some("r1"),+ 10 => Some("sp"),+ 11 => Some("lr"),_ => None,}}pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usize)> {if bytes.len() < 2 {- return Err(Error::Decode("truncated xcore input".into()));+ return Err(Error::Decode("truncated xcore input".into()));}let half = if little_endian {u16::from_le_bytes([bytes[0], bytes[1]])@@ -21,7 +21,7 @@ pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usiz};if (half >> 11) == 0b11100 {if bytes.len() < 4 {- return Err(Error::Decode("truncated xcore 32-bit".into()));+ return Err(Error::Decode("truncated xcore 32-bit".into()));}let word = if little_endian {u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])@@ -35,75 +35,75 @@ pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usiz}fn r(n: u16) -> String {- format!("r{n}")+ format!("r{n}")}fn decode16(h: u16) -> Result<(String, String, usize)> {let op = h >> 11;match op {0b00000 => {- // 3-operand register: 00000 rrr aaa bbb fff+ // 3-operand register: 00000 rrr aaa bbb ffflet dst = (h >> 8) & 0x7;let src1 = (h >> 5) & 0x7;let src2 = (h >> 2) & 0x7;let fn3 = h & 0x3;let name = match fn3 {- 0x0 => "add",- 0x1 => "sub",- 0x2 => "lsl",- 0x3 => "lsr",- _ => return Err(Error::Decode("invalid xcore alu".into())),+ 0x0 => "add",+ 0x1 => "sub",+ 0x2 => "lsl",+ 0x3 => "lsr",+ _ => return Err(Error::Decode("invalid xcore alu".into())),};Ok((name.into(),- format!("{}, {}, {}", r(dst), r(src1), r(src2)),+ format!("{}, {}, {}", r(dst), r(src1), r(src2)),2,))}0b00001 => {- // mov (register): 00001 rrr 000 bbb 011+ // mov (register): 00001 rrr 000 bbb 011let dst = (h >> 8) & 0x7;let src = (h >> 2) & 0x7;- Ok(( "mov".into(), format!("{}, {}", r(dst), r(src)), 2))+ Ok(("mov".into(), format!("{}, {}", r(dst), r(src)), 2))}0b10000 => {- // bu (branch unconditional): 10000 dddddddddddd+ // bu (branch unconditional): 10000 ddddddddddddlet disp = sign_ext16((h & 0x7ff) as i16, 11);- Ok(("bu".into(), format!("{disp}"), 2))+ Ok(("bu".into(), format!("{disp}"), 2))}0b10001 => {- // bl (branch link): 10001 dddddddddddd+ // bl (branch link): 10001 ddddddddddddlet disp = sign_ext16((h & 0x7ff) as i16, 11);- Ok(("bl".into(), format!("{disp}"), 2))+ Ok(("bl".into(), format!("{disp}"), 2))}0b10010 => {- // bf (branch false): 10010 dddddddddddd+ // bf (branch false): 10010 ddddddddddddlet disp = sign_ext16((h & 0x7ff) as i16, 11);- Ok(("bf".into(), format!("{disp}"), 2))+ Ok(("bf".into(), format!("{disp}"), 2))}0b10100 => {- // ldw (load word): 10100 rrr bbb ddddd+ // ldw (load word): 10100 rrr bbb dddddlet dst = (h >> 8) & 0x7;let base = (h >> 5) & 0x7;let disp = ((h >> 2) & 0x7) << 2;Ok((- "ldw".into(),- format!("{}, [{disp}({})]", r(dst), r(base)),+ "ldw".into(),+ format!("{}, [{disp}({})]", r(dst), r(base)),2,))}0b10101 => {- // stw (store word): 10101 rrr bbb ddddd+ // stw (store word): 10101 rrr bbb dddddlet src = (h >> 8) & 0x7;let base = (h >> 5) & 0x7;let disp = ((h >> 2) & 0x7) << 2;Ok((- "stw".into(),- format!("{}, [{disp}({})]", r(src), r(base)),+ "stw".into(),+ format!("{}, [{disp}({})]", r(src), r(base)),2,))}- _ => Err(Error::Decode("unsupported xcore 16-bit".into())),+ _ => Err(Error::Decode("unsupported xcore 16-bit".into())),}}@@ -113,49 +113,33 @@ fn decode32(word: u32) -> Result<(String, String, usize)> {0x00 => {let dst = (word >> 22) & 0x1f;let src = (word >> 17) & 0x1f;- Ok(("mov".into(), format!("r{dst}, r{src}"), 4))+ Ok(("mov".into(), format!("r{dst}, r{src}"), 4))}0x01 => {let dst = (word >> 22) & 0x1f;let src1 = (word >> 17) & 0x1f;let src2 = (word >> 12) & 0x1f;- Ok((- "add".into(),- format!("r{dst}, r{src1}, r{src2}"),- 4,- ))+ Ok(("add".into(), format!("r{dst}, r{src1}, r{src2}"), 4))}0x02 => {let dst = (word >> 22) & 0x1f;let src1 = (word >> 17) & 0x1f;let src2 = (word >> 12) & 0x1f;- Ok((- "sub".into(),- format!("r{dst}, r{src1}, r{src2}"),- 4,- ))+ Ok(("sub".into(), format!("r{dst}, r{src1}, r{src2}"), 4))}0x10 => {let dst = (word >> 22) & 0x1f;let base = (word >> 17) & 0x1f;let disp = (word >> 5) & 0xfff;- Ok((- "ldw".into(),- format!("r{dst}, [{disp}(r{base})]"),- 4,- ))+ Ok(("ldw".into(), format!("r{dst}, [{disp}(r{base})]"), 4))}0x11 => {let src = (word >> 22) & 0x1f;let base = (word >> 17) & 0x1f;let disp = (word >> 5) & 0xfff;- Ok((- "stw".into(),- format!("r{src}, [{disp}(r{base})]"),- 4,- ))+ Ok(("stw".into(), format!("r{src}, [{disp}(r{base})]"), 4))}- _ => Err(Error::Decode("unsupported xcore 32-bit".into())),+ _ => Err(Error::Decode("unsupported xcore 32-bit".into())),}}@@ -170,10 +154,10 @@ mod tests {#[test]fn xcore_add16() {- // add r1, r2, r3 => 0x0298+ // add r1, r2, r3 => 0x0298let (m, o, l) = decode(&[0x98, 0x02], true).unwrap();- assert_eq!(m, "add");+ assert_eq!(m, "add");assert_eq!(l, 2);- assert!(o.contains("r2"));+ assert!(o.contains("r2"));}}diff --git a/crates/ghidrust-decode/src/arch/xcore/mod.rs b/crates/ghidrust-decode/src/arch/xcore/mod.rsindex 9e95a9d..86416c4 100644--- a/crates/ghidrust-decode/src/arch/xcore/mod.rs+++ b/crates/ghidrust-decode/src/arch/xcore/mod.rs@@ -24,7 +24,10 @@ impl ArchDecode for XcoreDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Xcore) {- return Err(Error::Mode(format!("invalid xcore mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!(+ "invalid xcore mode {:#x}",+ mode.bits()+ )));}let little_endian = !mode.contains(Mode::BIG_ENDIAN);Ok(Self { little_endian })@@ -52,44 +55,44 @@ impl ArchDecode for XcoreDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "bu" | "bf" => vec![GroupId::Jump],- "bl" => vec![GroupId::Call],- "ldw" => vec![GroupId::Arch(1)],- "stw" => vec![GroupId::Arch(2)],- "add" | "sub" => vec![GroupId::Arch(3)],+ "bu" | "bf" => vec![GroupId::Jump],+ "bl" => vec![GroupId::Call],+ "ldw" => vec![GroupId::Arch(1)],+ "stw" => vec![GroupId::Arch(2)],+ "add" | "sub" => vec![GroupId::Arch(3)],_ => Vec::new(),}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("add"),- 2 => Some("mov"),- 3 => Some("ldw"),- 4 => Some("stw"),- 5 => Some("bu"),+ 1 => Some("add"),+ 2 => Some("mov"),+ 3 => Some("ldw"),+ 4 => Some("stw"),+ 5 => Some("bu"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Arch(1) => Some("load"),- GroupId::Arch(2) => Some("store"),- GroupId::Arch(3) => Some("alu"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Arch(1) => Some("load"),+ GroupId::Arch(2) => Some("store"),+ GroupId::Arch(3) => Some("alu"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "add" | "sub" => 1,- "mov" => 2,- "ldw" => 3,- "stw" => 4,- "bu" | "bl" | "bf" => 5,+ "add" | "sub" => 1,+ "mov" => 2,+ "ldw" => 3,+ "stw" => 4,+ "bu" | "bl" | "bf" => 5,_ => 0,};InsnId(id)@@ -103,22 +106,22 @@ mod tests {#[test]fn xcore_add_and_mov() {let mut eng = Engine::open(Arch::Xcore, Mode::MODE_32).unwrap();- // add r1, r2, r3+ // add r1, r2, r3let add = eng.disasm_one(&[0x98, 0x02], 0).unwrap();- assert_eq!(add.mnemonic, "add");- // mov r1, r2 => 0x090b+ assert_eq!(add.mnemonic, "add");+ // mov r1, r2 => 0x090blet mov = eng.disasm_one(&[0x0b, 0x09], 0).unwrap();- assert_eq!(mov.mnemonic, "mov");+ assert_eq!(mov.mnemonic, "mov");}#[test]fn xcore_branch_and_ldw() {let mut eng = Engine::open(Arch::Xcore, Mode::MODE_32).unwrap();- // bu +2 => 10000 00000000001 = 0x8001+ // bu +2 => 10000 00000000001 = 0x8001let bu = eng.disasm_one(&[0x01, 0x80], 0).unwrap();- assert_eq!(bu.mnemonic, "bu");- // ldw r1, [0(r2)] => 10100 001 010 000 = 0xa520+ assert_eq!(bu.mnemonic, "bu");+ // ldw r1, [0(r2)] => 10100 001 010 000 = 0xa520let ldw = eng.disasm_one(&[0x20, 0xa5], 0).unwrap();- assert_eq!(ldw.mnemonic, "ldw");+ assert_eq!(ldw.mnemonic, "ldw");}}diff --git a/crates/ghidrust-decode/src/arch/xtensa/decode.rs b/crates/ghidrust-decode/src/arch/xtensa/decode.rsindex e87ab1c..d63bfd7 100644--- a/crates/ghidrust-decode/src/arch/xtensa/decode.rs+++ b/crates/ghidrust-decode/src/arch/xtensa/decode.rs@@ -3,28 +3,28 @@ use crate::option::EngineOptions;pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {match reg.index() {- 0 => Some("a0"),- 1 => Some("a1"),- 2 => Some("a2"),- 15 => Some("a15"),+ 0 => Some("a0"),+ 1 => Some("a1"),+ 2 => Some("a2"),+ 15 => Some("a15"),_ => None,}}fn a(n: u32) -> String {- format!("a{n}")+ format!("a{n}")}pub fn decode(bytes: &[u8], opts: &EngineOptions) -> Result<(String, String, usize)> {if bytes.is_empty() {- return Err(Error::Decode("empty xtensa input".into()));+ return Err(Error::Decode("empty xtensa input".into()));}if bytes.len() >= 3 && bytes[0] <= 0x0f {decode24(bytes, opts)} else if bytes.len() >= 2 {decode16(bytes)} else {- Err(Error::Decode("truncated xtensa instruction".into()))+ Err(Error::Decode("truncated xtensa instruction".into()))}}@@ -32,13 +32,13 @@ fn decode24(bytes: &[u8], opts: &EngineOptions) -> Result<(String, String, usizelet op = bytes[0];match op {0x02 => {- // L32I+ // L32Ilet a_reg = (bytes[1] >> 4) & 0xf;let as_reg = bytes[1] & 0xf;let off = (bytes[2] as u32) << 2;Ok((- "l32i".into(),- format!("{}, {}, {}", a(u32::from(a_reg)), a(u32::from(as_reg)), off),+ "l32i".into(),+ format!("{}, {}, {}", a(u32::from(a_reg)), a(u32::from(as_reg)), off),3,))}@@ -47,20 +47,29 @@ fn decode24(bytes: &[u8], opts: &EngineOptions) -> Result<(String, String, usizelet as_reg = bytes[1] & 0xf;let off = (bytes[2] as u32) << 2;Ok((- "s32i".into(),- format!("{}, {}, {}", a(u32::from(a_reg)), a(u32::from(as_reg)), off),+ "s32i".into(),+ format!("{}, {}, {}", a(u32::from(a_reg)), a(u32::from(as_reg)), off),3,))}0x08 => {let dst = (bytes[1] >> 4) & 0xf;let src = bytes[1] & 0xf;- Ok(("add".into(), format!("{}, {}, {}", a(u32::from(dst)), a(u32::from(dst)), a(u32::from(src))), 3))+ Ok((+ "add".into(),+ format!(+ "{}, {}, {}",+ a(u32::from(dst)),+ a(u32::from(dst)),+ a(u32::from(src))+ ),+ 3,+ ))}0x05 => {let reg = (bytes[1] >> 4) & 0xf;let imm = bytes[2] as i8 as i64;- Ok(("movi".into(), format!("{}, {imm}", a(u32::from(reg))), 3))+ Ok(("movi".into(), format!("{}, {imm}", a(u32::from(reg))), 3))}0x06 => {let target = if bytes.len() >= 6 {@@ -68,27 +77,27 @@ fn decode24(bytes: &[u8], opts: &EngineOptions) -> Result<(String, String, usize} else {bytes[2] as u32};- Ok(("call0".into(), format!("0x{target:x}"), 3))+ Ok(("call0".into(), format!("0x{target:x}"), 3))}0x07 => {let reg = bytes[1] & 0xf;- Ok(("callx0".into(), format!("{}", a(u32::from(reg))), 3))+ Ok(("callx0".into(), format!("{}", a(u32::from(reg))), 3))}- 0x0d => Ok(("ret".into(), String::new(), 3)),+ 0x0d => Ok(("ret".into(), String::new(), 3)),0x0e => {let imm = if bytes.len() >= 6 {u32::from_le_bytes([bytes[2], bytes[3], bytes[4], bytes[5]])} else {bytes[2] as u32};- Ok(("j".into(), format!("0x{imm:x}"), 3))+ Ok(("j".into(), format!("0x{imm:x}"), 3))}0x0f => {let reg = bytes[1] & 0xf;- Ok(("jx".into(), format!("{}", a(u32::from(reg))), 3))+ Ok(("jx".into(), format!("{}", a(u32::from(reg))), 3))}0x01 => decode_l32r(bytes, opts),- _ => Err(Error::Decode("unsupported xtensa 24-bit".into())),+ _ => Err(Error::Decode("unsupported xtensa 24-bit".into())),}}@@ -96,11 +105,7 @@ fn decode_l32r(bytes: &[u8], opts: &EngineOptions) -> Result<(String, String, uslet reg = (bytes[1] >> 4) & 0xf;let offset = bytes[2] as u32;let pc = opts.litbase.wrapping_add(offset << 2);- Ok((- "l32r".into(),- format!("{}, 0x{pc:x}", a(u32::from(reg))),- 3,- ))+ Ok(("l32r".into(), format!("{}, 0x{pc:x}", a(u32::from(reg))), 3))}fn decode16(bytes: &[u8]) -> Result<(String, String, usize)> {@@ -110,18 +115,18 @@ fn decode16(bytes: &[u8]) -> Result<(String, String, usize)> {0x8 => {let reg = (h >> 8) & 0xf;let imm = (h & 0xff) as i8 as i64;- Ok(("movi.n".into(), format!("{}, {imm}", a(u32::from(reg))), 2))+ Ok(("movi.n".into(), format!("{}, {imm}", a(u32::from(reg))), 2))}0x9 => {let reg = (h >> 8) & 0xf;let imm = (h & 0xff) as i8 as i64;- Ok(("addi.n".into(), format!("{}, {imm}", a(u32::from(reg))), 2))+ Ok(("addi.n".into(), format!("{}, {imm}", a(u32::from(reg))), 2))}0xa => {let disp = ((h & 0x0fff) as i16 as i64) << 1;- Ok(("j.n".into(), format!("{disp}"), 2))+ Ok(("j.n".into(), format!("{disp}"), 2))}- _ => Err(Error::Decode("unsupported xtensa 16-bit".into())),+ _ => Err(Error::Decode("unsupported xtensa 16-bit".into())),}}@@ -132,9 +137,9 @@ mod tests {#[test]fn xtensa_l32i() {- // l32i a4, a1, 0 => op=0x02, a4=4, a1=1, off=0+ // l32i a4, a1, 0 => op=0x02, a4=4, a1=1, off=0let (m, _, l) = decode(&[0x02, 0x41, 0x00], &EngineOptions::default()).unwrap();- assert_eq!(m, "l32i");+ assert_eq!(m, "l32i");assert_eq!(l, 3);}}diff --git a/crates/ghidrust-decode/src/arch/xtensa/mod.rs b/crates/ghidrust-decode/src/arch/xtensa/mod.rsindex 15615af..9e05c72 100644--- a/crates/ghidrust-decode/src/arch/xtensa/mod.rs+++ b/crates/ghidrust-decode/src/arch/xtensa/mod.rs@@ -21,7 +21,10 @@ impl ArchDecode for XtensaDecoder {fn open(mode: Mode) -> Result<Self> {if !mode.is_valid_for(Arch::Xtensa) {- return Err(Error::Mode(format!("invalid xtensa mode {:#x}", mode.bits())));+ return Err(Error::Mode(format!(+ "invalid xtensa mode {:#x}",+ mode.bits()+ )));}Ok(Self { _mode: mode })}@@ -48,48 +51,48 @@ impl ArchDecode for XtensaDecoder {fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {match mnemonic {- "call0" | "callx0" => vec![GroupId::Call],- "j" | "jx" | "j.n" => vec![GroupId::Jump],- "ret" => vec![GroupId::Ret],- "l32i" | "l32r" => vec![GroupId::Arch(1)],- "s32i" => vec![GroupId::Arch(2)],+ "call0" | "callx0" => vec![GroupId::Call],+ "j" | "jx" | "j.n" => vec![GroupId::Jump],+ "ret" => vec![GroupId::Ret],+ "l32i" | "l32r" => vec![GroupId::Arch(1)],+ "s32i" => vec![GroupId::Arch(2)],_ => vec![GroupId::Arch(3)],}}pub fn insn_name(id: InsnId) -> Option<&'static str> {match id.raw() {- 1 => Some("l32i"),- 2 => Some("s32i"),- 3 => Some("add"),- 4 => Some("call0"),- 5 => Some("ret"),- 6 => Some("l32r"),+ 1 => Some("l32i"),+ 2 => Some("s32i"),+ 3 => Some("add"),+ 4 => Some("call0"),+ 5 => Some("ret"),+ 6 => Some("l32r"),_ => None,}}pub fn group_name(group: GroupId) -> Option<&'static str> {match group {- GroupId::Jump => Some("jump"),- GroupId::Call => Some("call"),- GroupId::Ret => Some("ret"),- GroupId::Arch(1) => Some("load"),- GroupId::Arch(2) => Some("store"),- GroupId::Arch(3) => Some("alu"),+ GroupId::Jump => Some("jump"),+ GroupId::Call => Some("call"),+ GroupId::Ret => Some("ret"),+ GroupId::Arch(1) => Some("load"),+ GroupId::Arch(2) => Some("store"),+ GroupId::Arch(3) => Some("alu"),_ => None,}}pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {let id = match mnemonic {- "l32i" => 1,- "s32i" => 2,- "add" | "movi" | "movi.n" | "addi.n" => 3,- "call0" | "callx0" => 4,- "ret" => 5,- "l32r" => 6,- "j" | "jx" | "j.n" => 3,+ "l32i" => 1,+ "s32i" => 2,+ "add" | "movi" | "movi.n" | "addi.n" => 3,+ "call0" | "callx0" => 4,+ "ret" => 5,+ "l32r" => 6,+ "j" | "jx" | "j.n" => 3,_ => 0,};InsnId(id)@@ -105,9 +108,9 @@ mod tests {fn xtensa_l32i_and_add() {let mut eng = Engine::open(Arch::Xtensa, Mode::LITTLE_ENDIAN).unwrap();let l32i = eng.disasm_one(&[0x02, 0x41, 0x00], 0).unwrap();- assert_eq!(l32i.mnemonic, "l32i");+ assert_eq!(l32i.mnemonic, "l32i");let add = eng.disasm_one(&[0x08, 0x21, 0x00], 0).unwrap();- assert_eq!(add.mnemonic, "add");+ assert_eq!(add.mnemonic, "add");}#[test]@@ -115,14 +118,12 @@ mod tests {let dec = XtensaDecoder::open(Mode::LITTLE_ENDIAN).unwrap();let mut opts = EngineOptions::default();opts.apply(Opt::Litbase(0x1000)).unwrap();- let l32r = dec- .decode_one(&[0x01, 0x40, 0x04], 0, &opts)- .unwrap();- assert_eq!(l32r.mnemonic, "l32r");- assert!(l32r.operands.contains("0x1010"));+ let l32r = dec.decode_one(&[0x01, 0x40, 0x04], 0, &opts).unwrap();+ assert_eq!(l32r.mnemonic, "l32r");+ assert!(l32r.operands.contains("0x1010"));let ret = dec.decode_one(&[0x0d, 0x00, 0x00], 0, &EngineOptions::default()).unwrap();- assert_eq!(ret.mnemonic, "ret");+ assert_eq!(ret.mnemonic, "ret");}}diff --git a/crates/ghidrust-decode/src/engine.rs b/crates/ghidrust-decode/src/engine.rsindex d9e2369..9b79cd3 100644--- a/crates/ghidrust-decode/src/engine.rs+++ b/crates/ghidrust-decode/src/engine.rs@@ -15,14 +15,17 @@ pub struct Engine {decoder: Box<dyn ArchDecode>,options: EngineOptions,last_error: Option<Error>,- hooks: &'static dyn AllocHooks,+ hooks: &'static dyn AllocHooks,open: bool,}impl Engine {pub fn open(arch: Arch, mode: Mode) -> Result<Self> {if !support(SupportQuery::Arch(arch)) {- return Err(Error::Arch(format!("architecture {:?} is not supported", arch)));+ return Err(Error::Arch(format!(+ "architecture {:?} is not supported",+ arch+ )));}let decoder = open_decoder(arch, mode)?;debug_assert_eq!(decoder.arch(), arch);@@ -59,7 +62,7 @@ impl Engine {self.options.apply(opt)}- pub fn version(&self) -> &'static str {+ pub fn version(&self) -> &'static str {VERSION}@@ -73,7 +76,10 @@ impl Engine {pub fn disasm(&mut self, bytes: &[u8], address: u64, count: usize) -> Result<Vec<Instruction>> {self.require_open()?;- match self.decoder.decode_many(bytes, address, count, &self.options) {+ match self+ .decoder+ .decode_many(bytes, address, count, &self.options)+ {Ok(v) => Ok(v),Err(e) => {self.last_error = Some(e.clone());@@ -82,11 +88,7 @@ impl Engine {}}- pub fn disasm_iter<'a>(- &'a mut self,- bytes: &'a [u8],- address: u64,- ) -> DisasmIter<'a> {+ pub fn disasm_iter<'a>(&'a mut self, bytes: &'a [u8], address: u64) -> DisasmIter<'a> {DisasmIter {engine: self,bytes,@@ -106,15 +108,15 @@ impl Engine {}}- pub fn reg_name(&self, reg: RegId) -> Option<&'static str> {+ pub fn reg_name(&self, reg: RegId) -> Option<&'static str> {names::reg_name(self.arch, reg)}- pub fn insn_name(&self, id: crate::insn::InsnId) -> Option<&'static str> {+ pub fn insn_name(&self, id: crate::insn::InsnId) -> Option<&'static str> {names::insn_name(self.arch, id)}- pub fn group_name(&self, group: GroupId) -> Option<&'static str> {+ pub fn group_name(&self, group: GroupId) -> Option<&'static str> {names::group_name(self.arch, group)}@@ -141,21 +143,18 @@ impl Engine {}pub fn op_count(&self, insn: &Instruction) -> usize {- insn.detail- .as_ref()- .map(|d| d.operands.len())- .unwrap_or(0)+ insn.detail.as_ref().map(|d| d.operands.len()).unwrap_or(0)}- pub fn op_index<'a>(+ pub fn op_index<'a>(&self,- insn: &'a Instruction,+ insn: &'a Instruction,index: usize,- ) -> Option<&'a crate::operand::Operand> {+ ) -> Option<&'a crate::operand::Operand> {insn.detail.as_ref()?.operands.get(index)}- pub fn regs_access<'a>(&self, insn: &'a Instruction) -> Option<RegsAccess<'a>> {+ pub fn regs_access<'a>(&self, insn: &'a Instruction) -> Option<RegsAccess<'a>> {insn.detail.as_ref().map(|d| RegsAccess {read: &d.regs_read,write: &d.regs_write,@@ -164,7 +163,7 @@ impl Engine {})}- pub fn hooks(&self) -> &'static dyn AllocHooks {+ pub fn hooks(&self) -> &'static dyn AllocHooks {self.hooks}@@ -172,21 +171,21 @@ impl Engine {if self.open {Ok(())} else {- Err(Error::Handle("engine is closed".into()))+ Err(Error::Handle("engine is closed".into()))}}}pub struct RegsAccess<'a> {- pub read: &'a [RegId],- pub write: &'a [RegId],- pub implicit_read: &'a [RegId],- pub implicit_write: &'a [RegId],+ pub read: &'a [RegId],+ pub write: &'a [RegId],+ pub implicit_read: &'a [RegId],+ pub implicit_write: &'a [RegId],}pub struct DisasmIter<'a> {- engine: &'a mut Engine,- bytes: &'a [u8],+ engine: &'a mut Engine,+ bytes: &'a [u8],address: u64,offset: usize,}@@ -198,11 +197,14 @@ impl<'a> Iterator for DisasmIter<'a> {if self.offset >= self.bytes.len() {return None;}- match self.engine.disasm_one(&self.bytes[self.offset..], self.address) {+ match self+ .engine+ .disasm_one(&self.bytes[self.offset..], self.address)+ {Ok(insn) => {let len = insn.length as usize;if len == 0 {- return Some(Err(Error::Decode("zero-length instruction".into())));+ return Some(Err(Error::Decode("zero-length instruction".into())));}self.offset += len;self.address = self.address.wrapping_add(len as u64);@@ -224,12 +226,12 @@ mod tests {let bytes = [0x55, 0x48, 0x89, 0xe5, 0xc3];let insns = engine.disasm(&bytes, 0x1000, 8).unwrap();assert_eq!(insns.len(), 3);- assert_eq!(insns[0].mnemonic, "push");- assert_eq!(insns[0].operands, "rbp");+ assert_eq!(insns[0].mnemonic, "push");+ assert_eq!(insns[0].operands, "rbp");assert_eq!(insns[0].id, InsnId(1));- assert_eq!(insns[1].mnemonic, "mov");- assert_eq!(insns[1].operands, "rbp, rsp");- assert_eq!(insns[2].mnemonic, "ret");+ assert_eq!(insns[1].mnemonic, "mov");+ assert_eq!(insns[1].operands, "rbp, rsp");+ assert_eq!(insns[2].mnemonic, "ret");assert_eq!(insns[2].length, 1);}@@ -238,7 +240,7 @@ mod tests {for arch in Arch::ALL {assert!(Engine::support(SupportQuery::Arch(arch)),- "{arch:?} should be supported"+ "{arch:?} should be supported");}assert!(Engine::support(SupportQuery::All));@@ -254,7 +256,7 @@ mod tests {let mut engine = Engine::x86_64_default().unwrap();let bytes = [0x55, 0x48, 0x89, 0xe5, 0xc3];let one = engine.disasm_one(&bytes, 0x1000).unwrap();- assert_eq!(one.mnemonic, "push");+ assert_eq!(one.mnemonic, "push");let all: Result<Vec<_>> = engine.disasm_iter(&bytes, 0x1000).collect();assert_eq!(all.unwrap().len(), 3);}diff --git a/crates/ghidrust-decode/src/error.rs b/crates/ghidrust-decode/src/error.rsindex 3226bc6..923995c 100644--- a/crates/ghidrust-decode/src/error.rs+++ b/crates/ghidrust-decode/src/error.rs@@ -13,15 +13,15 @@ pub enum Error {}impl fmt::Display for Error {- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {match self {- Error::Decode(m) => write!(f, "decode: {m}"),- Error::Arch(m) => write!(f, "arch: {m}"),- Error::Mode(m) => write!(f, "mode: {m}"),- Error::Option(m) => write!(f, "option: {m}"),- Error::Handle(m) => write!(f, "handle: {m}"),- Error::Mem(m) => write!(f, "mem: {m}"),- Error::Detail(m) => write!(f, "detail: {m}"),+ Error::Decode(m) => write!(f, "decode: {m}"),+ Error::Arch(m) => write!(f, "arch: {m}"),+ Error::Mode(m) => write!(f, "mode: {m}"),+ Error::Option(m) => write!(f, "option: {m}"),+ Error::Handle(m) => write!(f, "handle: {m}"),+ Error::Mem(m) => write!(f, "mem: {m}"),+ Error::Detail(m) => write!(f, "detail: {m}"),}}}diff --git a/crates/ghidrust-decode/src/insn.rs b/crates/ghidrust-decode/src/insn.rsindex c30ec4d..4daa21f 100644--- a/crates/ghidrust-decode/src/insn.rs+++ b/crates/ghidrust-decode/src/insn.rs@@ -43,7 +43,7 @@ pub struct Instruction {}impl Instruction {- /// Legacy five-field constructor (`id` / `detail` use defaults).+ /// Legacy five-field constructor (`id` / `detail` use defaults).pub fn with_text(address: u64,bytes: Vec<u8>,@@ -62,12 +62,12 @@ impl Instruction {}pub fn text(&self) -> String {- let hex = format!("{:24}", hex_bytes(&self.bytes));+ let hex = format!("{:24}", hex_bytes(&self.bytes));if self.operands.is_empty() {- format!("{:016x}: {} {}", self.address, hex, self.mnemonic)+ format!("{:016x}: {} {}", self.address, hex, self.mnemonic)} else {format!(- "{:016x}: {} {} {}",+ "{:016x}: {} {} {}",self.address, hex, self.mnemonic, self.operands)}@@ -85,7 +85,7 @@ impl Instruction {fn hex_bytes(b: &[u8]) -> String {b.iter()- .map(|x| format!("{x:02x}"))+ .map(|x| format!("{x:02x}")).collect::<Vec<_>>()- .join(" ")+ .join(" ")}diff --git a/crates/ghidrust-decode/src/lib.rs b/crates/ghidrust-decode/src/lib.rsindex 2818435..b7b95f1 100644--- a/crates/ghidrust-decode/src/lib.rs+++ b/crates/ghidrust-decode/src/lib.rs@@ -40,7 +40,11 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {}/// Decode a linear byte slice into a sequence of instructions (stops on first error).-pub fn decode_bytes(bytes: &[u8], start_address: u64, max_insns: usize) -> Result<Vec<Instruction>> {+pub fn decode_bytes(+ bytes: &[u8],+ start_address: u64,+ max_insns: usize,+) -> Result<Vec<Instruction>> {let mut engine = Engine::x86_64_default()?;let mut out = Vec::new();let mut off = 0usize;@@ -66,7 +70,7 @@ pub fn decode_bytes(bytes: &[u8], start_address: u64, max_insns: usize) -> Resul}if out.is_empty() {return Err(Error::Decode(format!(- "no instructions at {start_address:#x}"+ "no instructions at {start_address:#x}")));}Ok(out)@@ -81,9 +85,9 @@ mod tests {let b = [0x55, 0x48, 0x89, 0xe5, 0xc3];let insns = decode_bytes(&b, 0x1000, 8).unwrap();assert_eq!(insns.len(), 3);- assert_eq!(insns[0].mnemonic, "push");- assert_eq!(insns[1].mnemonic, "mov");- assert_eq!(insns[2].mnemonic, "ret");+ assert_eq!(insns[0].mnemonic, "push");+ assert_eq!(insns[1].mnemonic, "mov");+ assert_eq!(insns[2].mnemonic, "ret");}#[test]diff --git a/crates/ghidrust-decode/src/operand.rs b/crates/ghidrust-decode/src/operand.rsindex 194cea8..2778fc7 100644--- a/crates/ghidrust-decode/src/operand.rs+++ b/crates/ghidrust-decode/src/operand.rs@@ -16,7 +16,10 @@ pub enum OpType {#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub enum Operand {Reg(RegId),- Imm { value: i64, size: u8 },+ Imm {+ value: i64,+ size: u8,+ },Mem {base: RegId,index: RegId,diff --git a/crates/ghidrust-decode/src/skipdata.rs b/crates/ghidrust-decode/src/skipdata.rsindex 2f1b719..4331d7d 100644--- a/crates/ghidrust-decode/src/skipdata.rs+++ b/crates/ghidrust-decode/src/skipdata.rs@@ -16,11 +16,11 @@ pub enum SkipdataHandler {}impl std::fmt::Debug for SkipdataHandler {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {match self {- SkipdataHandler::None => write!(f, "SkipdataHandler::None"),- SkipdataHandler::Trait(_) => write!(f, "SkipdataHandler::Trait(_)"),- SkipdataHandler::Fn(_) => write!(f, "SkipdataHandler::Fn(_)"),+ SkipdataHandler::None => write!(f, "SkipdataHandler::None"),+ SkipdataHandler::Trait(_) => write!(f, "SkipdataHandler::Trait(_)"),+ SkipdataHandler::Fn(_) => write!(f, "SkipdataHandler::Fn(_)"),}}}@@ -68,10 +68,10 @@ impl SkipdataConfig {}impl std::fmt::Debug for SkipdataConfig {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.debug_struct("SkipdataConfig")- .field("mnemonic", &self.mnemonic)- .field("handler", &self.handler)+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("SkipdataConfig")+ .field("mnemonic", &self.mnemonic)+ .field("handler", &self.handler).finish()}}diff --git a/crates/ghidrust-decode/src/support.rs b/crates/ghidrust-decode/src/support.rsindex 95a88b1..b634a64 100644--- a/crates/ghidrust-decode/src/support.rs+++ b/crates/ghidrust-decode/src/support.rs@@ -84,32 +84,32 @@ impl Arch {}}- pub const fn name(self) -> &'static str {+ pub const fn name(self) -> &'static str {match self {- Arch::Arm => "arm",- Arch::Arm64 => "arm64",- Arch::Mips => "mips",- Arch::X86 => "x86",- Arch::Ppc => "ppc",- Arch::Sparc => "sparc",- Arch::Sysz => "sysz",- Arch::Xcore => "xcore",- Arch::M68k => "m68k",- Arch::Tms320c64x => "tms320c64x",- Arch::M680x => "m680x",- Arch::Evm => "evm",- Arch::Mos65xx => "mos65xx",- Arch::Wasm => "wasm",- Arch::Bpf => "bpf",- Arch::Riscv => "riscv",- Arch::Tricore => "tricore",- Arch::Alpha => "alpha",- Arch::Hppa => "hppa",- Arch::Loongarch => "loongarch",- Arch::Arc => "arc",- Arch::Sh => "sh",- Arch::Xtensa => "xtensa",- Arch::Max => "max",+ Arch::Arm => "arm",+ Arch::Arm64 => "arm64",+ Arch::Mips => "mips",+ Arch::X86 => "x86",+ Arch::Ppc => "ppc",+ Arch::Sparc => "sparc",+ Arch::Sysz => "sysz",+ Arch::Xcore => "xcore",+ Arch::M68k => "m68k",+ Arch::Tms320c64x => "tms320c64x",+ Arch::M680x => "m680x",+ Arch::Evm => "evm",+ Arch::Mos65xx => "mos65xx",+ Arch::Wasm => "wasm",+ Arch::Bpf => "bpf",+ Arch::Riscv => "riscv",+ Arch::Tricore => "tricore",+ Arch::Alpha => "alpha",+ Arch::Hppa => "hppa",+ Arch::Loongarch => "loongarch",+ Arch::Arc => "arc",+ Arch::Sh => "sh",+ Arch::Xtensa => "xtensa",+ Arch::Max => "max",}}}@@ -195,9 +195,7 @@ impl Mode {|| self.contains(Self::V8)}Arch::Arm64 => {- self == Self::LITTLE_ENDIAN- || self == Self::BIG_ENDIAN- || self.contains(Self::V8)+ self == Self::LITTLE_ENDIAN || self == Self::BIG_ENDIAN || self.contains(Self::V8)}Arch::Mips => {self.contains(Self::MIPS32)@@ -212,21 +210,14 @@ impl Mode {|| self == Self::BIG_ENDIAN}Arch::Sparc => {- self.contains(Self::V9)- || self == Self::LITTLE_ENDIAN- || self == Self::BIG_ENDIAN+ self.contains(Self::V9) || self == Self::LITTLE_ENDIAN || self == Self::BIG_ENDIAN}Arch::Sysz | Arch::Hppa => {self == Self::LITTLE_ENDIAN|| self == Self::BIG_ENDIAN|| self.contains(Self::MODE_64)}- Arch::Xcore- | Arch::M68k- | Arch::Tricore- | Arch::Arc- | Arch::Sh- | Arch::Loongarch => {+ Arch::Xcore | Arch::M68k | Arch::Tricore | Arch::Arc | Arch::Sh | Arch::Loongarch => {self == Self::LITTLE_ENDIAN|| self == Self::BIG_ENDIAN|| self.contains(Self::MODE_32)@@ -258,8 +249,8 @@ impl SupportQuery {match self {SupportQuery::Arch(arch) => IMPLEMENTED.contains(&arch),SupportQuery::All => IMPLEMENTED.len() == Arch::ALL.len(),- SupportQuery::Diet => cfg!(feature = "diet"),- SupportQuery::X86Reduce => cfg!(feature = "x86-reduce"),+ SupportQuery::Diet => cfg!(feature = "diet"),+ SupportQuery::X86Reduce => cfg!(feature = "x86-reduce"),}}}diff --git a/crates/ghidrust-decomp/src/bench.rs b/crates/ghidrust-decomp/src/bench.rsindex 951d316..4d1e8c5 100644--- a/crates/ghidrust-decomp/src/bench.rs+++ b/crates/ghidrust-decomp/src/bench.rs@@ -72,8 +72,8 @@ impl BenchReport {pub fn to_text(&self) -> String {let mut s = String::new();- let stage1_populated = self.stage1_total_us > 0- || self.per_function.iter().any(|f| f.stage1_us > 0);+ let stage1_populated =+ self.stage1_total_us > 0 || self.per_function.iter().any(|f| f.stage1_us > 0);if stage1_populated {s.push_str("=== Ghidrust decompile-bench (Stage-0 vs Stage-0.5 vs Stage-1) ===\n");} else {@@ -150,11 +150,7 @@ fn truncate(s: &str, n: usize) -> String {/// disassemble each with `max_insns_per_fn`, then run Stage-0 and Stage-0.5/// end-to-end. When `prog.analysis.functions` is empty the entry point is/// benched instead so the harness still yields useful timings on a fresh load.-pub fn bench_program(- prog: &Program,- max_functions: usize,- max_insns_per_fn: usize,-) -> BenchReport {+pub fn bench_program(prog: &Program, max_functions: usize, max_insns_per_fn: usize) -> BenchReport {let mut targets: Vec<(String, u64)> = prog.analysis.functions@@ -330,8 +326,7 @@ fn bench_one(name: &str, entry: u64, insns: &[ghidrust_core::Instruction]) -> Fulet s0_dur = s0_start.elapsed();let s05_start = Instant::now();- let (s05, cov): (DecompileResult, LiftCoverage) =- decompile_instructions_ir(name, entry, insns);+ let (s05, cov): (DecompileResult, LiftCoverage) = decompile_instructions_ir(name, entry, insns);let s05_dur = s05_start.elapsed();FunctionBench {@@ -413,13 +408,7 @@ mod tests {fn bench_program_stage1_captures_stage1_text_and_wall() {let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();let entry = prog.entry.unwrap();- let rep = bench_program_stage1(- &prog,- Some(&[entry]),- 4,- 32,- CallConv::Windows,- );+ let rep = bench_program_stage1(&prog, Some(&[entry]), 4, 32, CallConv::Windows);assert_eq!(rep.function_count, 1);let f = &rep.per_function[0];assert_eq!(f.entry, entry);@@ -432,16 +421,13 @@ mod tests {fn bench_program_stage1_parallel_matches_serial_shape() {let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();let entry = prog.entry.unwrap();- let serial =- bench_program_stage1(&prog, Some(&[entry]), 4, 32, CallConv::Windows);- let par =- bench_program_stage1_parallel(&prog, Some(&[entry]), 4, 32, CallConv::Windows);+ let serial = bench_program_stage1(&prog, Some(&[entry]), 4, 32, CallConv::Windows);+ let par = bench_program_stage1_parallel(&prog, Some(&[entry]), 4, 32, CallConv::Windows);assert_eq!(serial.function_count, par.function_count);// Text output must be identical — parallelism only changes// scheduling, not the emit.assert_eq!(- serial.per_function[0].stage1_text,- par.per_function[0].stage1_text,+ serial.per_function[0].stage1_text, par.per_function[0].stage1_text,"parallel bench must produce identical Stage-1 text");}diff --git a/crates/ghidrust-decomp/src/expr_fold.rs b/crates/ghidrust-decomp/src/expr_fold.rsindex 28315b6..43ef503 100644--- a/crates/ghidrust-decomp/src/expr_fold.rs+++ b/crates/ghidrust-decomp/src/expr_fold.rs@@ -86,7 +86,8 @@ impl FoldPlan {}pub fn should_suppress(&self, out: Option<SsaValue>) -> bool {- out.map(|v| self.suppress_emit.contains(&v)).unwrap_or(false)+ out.map(|v| self.suppress_emit.contains(&v))+ .unwrap_or(false)}}@@ -199,7 +200,10 @@ fn expr_from_op(OpCode::IntNegate => format!("(-{})", fmt_op(op.inputs.first().unwrap_or(&dummy_const()))),OpCode::IntNot => format!("(~{})", fmt_op(op.inputs.first().unwrap_or(&dummy_const()))),OpCode::BoolNegate => format!("(!{})", fmt_op(op.inputs.first().unwrap_or(&dummy_const()))),- OpCode::Load => format!("(*({}))", fmt_op(op.inputs.first().unwrap_or(&dummy_const()))),+ OpCode::Load => format!(+ "(*({}))",+ fmt_op(op.inputs.first().unwrap_or(&dummy_const()))+ ),OpCode::Cast | OpCode::IntZExt | OpCode::IntSExt => {let a = fmt_op(op.inputs.first().unwrap_or(&dummy_const()));let w = op.output.map(|o| o.size * 8).unwrap_or(64);diff --git a/crates/ghidrust-decomp/src/ghidra_oracle.rs b/crates/ghidrust-decomp/src/ghidra_oracle.rsindex 36b9e30..a8448ce 100644--- a/crates/ghidrust-decomp/src/ghidra_oracle.rs+++ b/crates/ghidrust-decomp/src/ghidra_oracle.rs@@ -230,7 +230,10 @@ impl GhidraOracleReport {self.ghidrust.avg_lift_ratio * 100.0));match self.ghidra_total_us {- Some(us) => s.push_str(&format!("ghidra: total_wall_ms={:.3}\n", us as f64 / 1000.0)),+ Some(us) => s.push_str(&format!(+ "ghidra: total_wall_ms={:.3}\n",+ us as f64 / 1000.0+ )),None => s.push_str("ghidra: unavailable (see methodology)\n"),}s.push_str(&format!(@@ -346,8 +349,11 @@ fn normalize_token(tok: &str) -> String {if t.starts_with("param_") || t.starts_with("arg_") {return "PARAM".into();}- if (t.starts_with('i') || t.starts_with('u') || t.starts_with('l')- || t.starts_with('c') || t.starts_with('s'))+ if (t.starts_with('i')+ || t.starts_with('u')+ || t.starts_with('l')+ || t.starts_with('c')+ || t.starts_with('s'))&& t.ends_with(|c: char| c.is_ascii_digit())&& t.starts_with(|c: char| c.is_ascii_lowercase())&& t.contains("Var")@@ -407,7 +413,11 @@ pub fn token_similarity(a: &str, b: &str) -> f32 {/// keeps `token_similarity = None` and never invents wall time.pub fn compare(prog: &Program, cfg: &GhidraOracleConfig) -> GhidraOracleReport {let t0 = Instant::now();- let max_functions = if cfg.max_functions == 0 { 8 } else { cfg.max_functions };+ let max_functions = if cfg.max_functions == 0 {+ 8+ } else {+ cfg.max_functions+ };let max_insns = if cfg.max_insns_per_fn == 0 {128} else {@@ -433,15 +443,9 @@ pub fn compare(prog: &Program, cfg: &GhidraOracleConfig) -> GhidraOracleReport {// Ghidrust analyzer's function list (capped by `max_functions`).// When Ghidra is unavailable we fall back to the Ghidrust list// unchanged so the methodology-only run keeps producing rows.- let ghidrust_entries: Vec<u64> = prog- .analysis- .functions- .iter()- .map(|f| f.entry)- .collect();+ let ghidrust_entries: Vec<u64> = prog.analysis.functions.iter().map(|f| f.entry).collect();let shared_entries: Vec<u64> = if let Some(cap) = &effective_captured {- let ghidra_set: std::collections::BTreeSet<u64> =- cap.iter().map(|c| c.entry).collect();+ let ghidra_set: std::collections::BTreeSet<u64> = cap.iter().map(|c| c.entry).collect();let mut inter: Vec<u64> = ghidrust_entries.iter().copied()@@ -459,7 +463,11 @@ pub fn compare(prog: &Program, cfg: &GhidraOracleConfig) -> GhidraOracleReport {}inter} else {- ghidrust_entries.iter().copied().take(max_functions).collect()+ ghidrust_entries+ .iter()+ .copied()+ .take(max_functions)+ .collect()};// 3. Ghidrust side: run the selected stage on the shared entry set.@@ -564,9 +572,7 @@ pub fn compare(prog: &Program, cfg: &GhidraOracleConfig) -> GhidraOracleReport {ghidra_blocks_estimated: 0,ghidrust_insns: f.insn_count,match_kind: MatchKind::MissingGhidra,- notes: format!(- "{note_head} — see docs/GHIDRA_HEADTOHEAD.md § Runbook"- ),+ notes: format!("{note_head} — see docs/GHIDRA_HEADTOHEAD.md § Runbook"),token_similarity: None,ghidrust_stage1_us: f.stage1_us,ghidra_wall_us: None,@@ -617,8 +623,7 @@ pub fn shared_entry_list(captured: &[CapturedGhidraDecompile],max_functions: usize,) -> Vec<u64> {- let ghidra_set: std::collections::BTreeSet<u64> =- captured.iter().map(|c| c.entry).collect();+ let ghidra_set: std::collections::BTreeSet<u64> = captured.iter().map(|c| c.entry).collect();prog.analysis.functions.iter()@@ -652,7 +657,10 @@ pub enum GhidraSpawnError {BinaryMissing(PathBuf),TempSetup(String),Spawn(String),- NonZeroExit { code: Option<i32>, stderr: String },+ NonZeroExit {+ code: Option<i32>,+ stderr: String,+ },Timeout(Duration),ParseCapture(String),/// analyzeHeadless exited 0 but never wrote our capture JSON (typical@@ -670,7 +678,9 @@ impl std::fmt::Display for GhidraSpawnError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {match self {Self::InstallMissing(p) => write!(f, "ghidra install dir missing: {}", p.display()),- Self::HeadlessMissing(p) => write!(f, "analyzeHeadless not found under {}", p.display()),+ Self::HeadlessMissing(p) => {+ write!(f, "analyzeHeadless not found under {}", p.display())+ }Self::BinaryMissing(p) => write!(f, "binary not readable: {}", p.display()),Self::TempSetup(e) => write!(f, "temp setup failed: {e}"),Self::Spawn(e) => write!(f, "spawn failed: {e}"),@@ -680,7 +690,11 @@ impl std::fmt::Display for GhidraSpawnError {}Self::Timeout(d) => write!(f, "analyzeHeadless timed out after {}s", d.as_secs()),Self::ParseCapture(e) => write!(f, "capture JSON parse failed: {e}"),- Self::NoCaptureEmitted { path, scratch, stderr_tail } => {+ Self::NoCaptureEmitted {+ path,+ scratch,+ stderr_tail,+ } => {write!(f,"no capture file written at {} (scratch kept at {} for inspection); stderr tail: {}",@@ -896,8 +910,8 @@ pub fn spawn_ghidra_headless(}let text = std::fs::read_to_string(&out_json).map_err(|e| GhidraSpawnError::ParseCapture(e.to_string()))?;- let parsed: Vec<CapturedGhidraDecompile> = serde_json::from_str(&text)- .map_err(|e| GhidraSpawnError::ParseCapture(e.to_string()))?;+ let parsed: Vec<CapturedGhidraDecompile> =+ serde_json::from_str(&text).map_err(|e| GhidraSpawnError::ParseCapture(e.to_string()))?;let _ = std::fs::remove_dir_all(&scratch);Ok(parsed)@@ -1026,9 +1040,10 @@ mod tests {// Even with just one captured row, the aggregate wall time must be// reported (>=1234) and the row must not be Missing.assert_eq!(rep.ghidra_total_us, Some(1234));- let similar_or_divergent = rep.rows.iter().any(|r| {- matches!(r.match_kind, MatchKind::Similar | MatchKind::Divergent)- });+ let similar_or_divergent = rep+ .rows+ .iter()+ .any(|r| matches!(r.match_kind, MatchKind::Similar | MatchKind::Divergent));assert!(similar_or_divergent, "captured row should classify");}@@ -1222,7 +1237,10 @@ mod tests {if prog.analysis.functions.iter().any(|f| f.entry == entry) {assert!(shared.contains(&entry), "expected shared entry: {shared:?}");}- assert!(!shared.contains(&0xdeadbeef), "capture-only entries filtered out");+ assert!(+ !shared.contains(&0xdeadbeef),+ "capture-only entries filtered out"+ );}#[test]@@ -1246,7 +1264,10 @@ mod tests {matched.token_similarity.is_some(),"Stage-1 row should carry token_similarity");- assert!(matched.ghidrust_stage1_us > 0, "Stage-1 wall must be captured");+ assert!(+ matched.ghidrust_stage1_us > 0,+ "Stage-1 wall must be captured"+ );}#[test]diff --git a/crates/ghidrust-decomp/src/gpu_decompile.rs b/crates/ghidrust-decomp/src/gpu_decompile.rsindex 6228e8f..78e7ae1 100644--- a/crates/ghidrust-decomp/src/gpu_decompile.rs+++ b/crates/ghidrust-decomp/src/gpu_decompile.rs@@ -213,7 +213,11 @@ pub fn decode_gdecomp_pseudo_c(dump: &[u8]) -> Option<String> {}/// Extract raw code bytes for a VA region (host seed only).-pub fn region_bytes(prog: &Program, va: u64, max_bytes: usize) -> ghidrust_core::Result<(Vec<u8>, u64)> {+pub fn region_bytes(+ prog: &Program,+ va: u64,+ max_bytes: usize,+) -> ghidrust_core::Result<(Vec<u8>, u64)> {let data = prog.read_va(va, max_bytes).ok_or_else(|| ghidrust_core::Error::Decode(format!("no bytes at {va:#x}")))?;@@ -222,11 +226,7 @@ pub fn region_bytes(prog: &Program, va: u64, max_bytes: usize) -> ghidrust_core:/// Multipass decompile on the host mirroring GPU stages (same IR + emit)./// Correctness oracle for the GPU-resident process; also used when no adapter.-pub fn multipass_cpu_decompile_from_code(- name: &str,- entry: u64,- code: &[u8],-) -> DecompileResult {+pub fn multipass_cpu_decompile_from_code(name: &str, entry: u64, code: &[u8]) -> DecompileResult {let ir = cpu_decode_walk(code);let (pseudo_c, _block_count, _edge_count) = multipass_emit_from_ir(name, entry, &ir);let insns = ir_to_instructions(entry, &ir);@@ -534,8 +534,8 @@ fn ir_to_instructions(entry: u64, ir: &[GpuIrSlot]) -> Vec<ghidrust_core::Instru.filter(|s| s.valid != 0).map(|s| {let operands = if s.has_imm != 0 {- let target = (entry as i64 + s.off as i64 + s.length as i64 + (s.imm as i32 as i64))- as u64;+ let target =+ (entry as i64 + s.off as i64 + s.length as i64 + (s.imm as i32 as i64)) as u64;format!("{target:#x}")} else {match s.opcode {@@ -572,7 +572,8 @@ pub fn gpu_decompile_to_file(.find(|f| f.entry == entry).map(|f| f.name.clone()).unwrap_or_else(|| format!("FUN_{entry:016x}"));- let (code, _) = region_bytes(prog, entry, max_bytes.min(MAX_CODE)).map_err(|e| e.to_string())?;+ let (code, _) =+ region_bytes(prog, entry, max_bytes.min(MAX_CODE)).map_err(|e| e.to_string())?;gpu_decompile_code_to_file(&name, entry, &code, dump_path)}@@ -1114,7 +1115,11 @@ mod tests {// xor; je +4; xor; ret; pop; ret → leaders 0,2,4let code = vec![0x31, 0xc0, 0x74, 0x04, 0x31, 0xc0, 0xc3, 0x5d, 0xc3];let d = multipass_cpu_decompile_from_code("br", 0x1000, &code);- assert!(d.blocks.len() >= 2, "expected multiple blocks: {}", d.blocks.len());+ assert!(+ d.blocks.len() >= 2,+ "expected multiple blocks: {}",+ d.blocks.len()+ );assert!(d.pseudo_c.contains("if (/* jcc */)") && d.pseudo_c.contains("goto block_"),"branchy emit incomplete:\n{}",@@ -1157,9 +1162,7 @@ mod tests {assert!(b.gpu_pcie_upload_ms >= 0.0);assert!(b.gpu_device_ms >= 0.0);assert!(b.gpu_pcie_download_ms >= 0.0);- assert!(- (b.gpu_pcie_ms - (b.gpu_pcie_upload_ms + b.gpu_pcie_download_ms)).abs() < 1e-6- );+ assert!((b.gpu_pcie_ms - (b.gpu_pcie_upload_ms + b.gpu_pcie_download_ms)).abs() < 1e-6);assert_eq!(b.mid_pipeline_host_reads, 0);assert!(b.equal,@@ -1193,13 +1196,18 @@ mod tests {rep.backend, rep.device);assert!(- rep.device.contains("NVIDIA") || rep.device.contains("Vulkan") || rep.device.contains("Gpu"),+ rep.device.contains("NVIDIA")+ || rep.device.contains("Vulkan")+ || rep.device.contains("Gpu"),"device={}",rep.device);let bytes = std::fs::read(&out).unwrap();let from_file = decode_gdecomp_pseudo_c(&bytes).unwrap();- assert_eq!(normalize_pseudo(&from_file), normalize_pseudo(&rep.pseudo_c));+ assert_eq!(+ normalize_pseudo(&from_file),+ normalize_pseudo(&rep.pseudo_c)+ );let (code, entry) = region_bytes(&prog, rep.entry, 64).unwrap();let multi = multipass_cpu_decompile_from_code(&rep.name, entry, &code);assert_eq!(@@ -1263,7 +1271,10 @@ mod tests {);let dump = std::fs::read(&out).unwrap();let from_file = decode_gdecomp_pseudo_c(&dump).unwrap();- assert_eq!(normalize_pseudo(&from_file), normalize_pseudo(&rep.pseudo_c));+ assert_eq!(+ normalize_pseudo(&from_file),+ normalize_pseudo(&rep.pseudo_c)+ );let _ = std::fs::remove_file(&out);}@@ -1276,7 +1287,10 @@ mod tests {let r2 = gpu_decompile_to_file(&prog, None, &b, 64).unwrap();assert_eq!(r1.backend, "gpu_vram_multipass");assert_eq!(r2.backend, "gpu_vram_multipass");- assert_eq!(normalize_pseudo(&r1.pseudo_c), normalize_pseudo(&r2.pseudo_c));+ assert_eq!(+ normalize_pseudo(&r1.pseudo_c),+ normalize_pseudo(&r2.pseudo_c)+ );assert!(a.is_file() && b.is_file());let _ = std::fs::remove_file(&a);let _ = std::fs::remove_file(&b);diff --git a/crates/ghidrust-decomp/src/ir_emit.rs b/crates/ghidrust-decomp/src/ir_emit.rsindex 501e318..ceb6c8b 100644--- a/crates/ghidrust-decomp/src/ir_emit.rs+++ b/crates/ghidrust-decomp/src/ir_emit.rs@@ -23,15 +23,9 @@ use crate::BasicBlock;/// * `blocks` — Stage-0 basic blocks, already split by `wire_successors`./// * `seq` — IR ops in linear order with source addresses; typically the output/// of [`ghidrust_lift::lift_instructions`].-pub fn emit_ir_pseudo_c(- name: &str,- entry: u64,- blocks: &[BasicBlock],- seq: &IrSequence,-) -> String {+pub fn emit_ir_pseudo_c(name: &str, entry: u64, blocks: &[BasicBlock], seq: &IrSequence) -> String {let ops_by_addr = group_ops_by_addr(seq);- let block_labels: BTreeMap<u64, usize> =- blocks.iter().map(|b| (b.start, b.id)).collect();+ let block_labels: BTreeMap<u64, usize> = blocks.iter().map(|b| (b.start, b.id)).collect();let cov = lift_coverage(seq, seq.addressed.len());let mut out = String::new();@@ -51,7 +45,10 @@ pub fn emit_ir_pseudo_c(out.push_str(&format!(" // block_{} @ {:#x}\n", b.id, b.start));out.push_str(&format!(" block_{}:\n", b.id));for insn in &b.instructions {- let ir_slice = ops_by_addr.get(&insn.address).map(|v| v.as_slice()).unwrap_or(&[]);+ let ir_slice = ops_by_addr+ .get(&insn.address)+ .map(|v| v.as_slice())+ .unwrap_or(&[]);let stmt = emit_insn(insn, ir_slice, &block_labels);for line in stmt.lines() {out.push_str(" ");@@ -66,11 +63,7 @@ pub fn emit_ir_pseudo_c(out}-fn emit_insn(- insn: &Instruction,- ir: &[PcodeOp],- labels: &BTreeMap<u64, usize>,-) -> String {+fn emit_insn(insn: &Instruction, ir: &[PcodeOp], labels: &BTreeMap<u64, usize>) -> String {match insn.mnemonic.as_str() {"ret" | "retn" => "return;".to_string(),"nop" => "/* nop */;".to_string(),@@ -422,8 +415,14 @@ mod tests {let (d, seq) = decomp_with_ir(&bytes, 0x1000, "prologue");let text = emit_ir_pseudo_c(&d.name, d.entry, &d.blocks, &seq);assert!(text.contains("void prologue"));- assert!(text.contains("rbp = rsp;"), "mov rbp,rsp should lower cleanly:\n{text}");- assert!(text.contains("eax = 0;"), "xor idiom should collapse to 0:\n{text}");+ assert!(+ text.contains("rbp = rsp;"),+ "mov rbp,rsp should lower cleanly:\n{text}"+ );+ assert!(+ text.contains("eax = 0;"),+ "xor idiom should collapse to 0:\n{text}"+ );assert!(text.contains("push(rbp);"));assert!(text.contains("rbp = pop();"));assert!(text.contains("return;"));@@ -441,7 +440,10 @@ mod tests {let bytes = [0x39, 0xc1, 0x74, 0x02, 0x31, 0xc0, 0xc3, 0x31, 0xc9, 0xc3];let (d, seq) = decomp_with_ir(&bytes, 0x2000, "branchy");let text = emit_ir_pseudo_c(&d.name, d.entry, &d.blocks, &seq);- assert!(text.contains("if (zf) goto"), "expected zf-driven jcc:\n{text}");+ assert!(+ text.contains("if (zf) goto"),+ "expected zf-driven jcc:\n{text}"+ );// Stage-0 truncates at the first `ret`; the taken branch still emits a// `goto` and the fallthrough hits `return;` at least once.assert!(text.matches("return;").count() >= 1);diff --git a/crates/ghidrust-decomp/src/lib.rs b/crates/ghidrust-decomp/src/lib.rsindex d1994a3..a003c8d 100644--- a/crates/ghidrust-decomp/src/lib.rs+++ b/crates/ghidrust-decomp/src/lib.rs@@ -22,8 +22,8 @@ pub mod emit_hints;pub mod emit_tokens;pub mod expr_fold;pub mod ghidra_oracle;-pub mod gpu_decompile;pub mod goto_histogram;+pub mod gpu_decompile;pub mod ir_emit;pub mod stage1;@@ -77,9 +77,7 @@ pub fn structure_hints_from(prog: &Program) -> StructureHints {/// Meant to be called from the GUI's `Decompiler → Commit Params/Return`/// action so the recovered types round-trip into user edits without the/// GUI having to know the Ghidrust type lattice.-pub fn stage1_commit_strings(- stage1: &Stage1Result,-) -> (String, Vec<String>, Vec<String>) {+pub fn stage1_commit_strings(stage1: &Stage1Result) -> (String, Vec<String>, Vec<String>) {let ret = stage1.types.signature.return_type.c_style();let params: Vec<String> = stage1.types@@ -189,7 +187,11 @@ pub fn decompile_instructions(}/// Load-independent entry: decode `max_insns` from `va` then decompile.-pub fn decompile_at(prog: &Program, va: u64, max_insns: usize) -> ghidrust_core::Result<DecompileResult> {+pub fn decompile_at(+ prog: &Program,+ va: u64,+ max_insns: usize,+) -> ghidrust_core::Result<DecompileResult> {let insns = disassemble_range(prog, va, max_insns)?;let name = prog.analysis@@ -332,7 +334,11 @@ pub fn decompile_stage1_at(// R6: if this function's name looks like Class::Method, enable `this`.if let Some((cls, _)) = name.split_once("::") {emit_hints = emit_hints.with_method_this(cls);- } else if emit_hints.vtable_classes.values().any(|c| name.contains(c.as_str())) {+ } else if emit_hints+ .vtable_classes+ .values()+ .any(|c| name.contains(c.as_str()))+ {if let Some(cls) = emit_hints.vtable_classes.values()@@ -533,7 +539,9 @@ fn wire_successors(fn emit_pseudo_c(name: &str, entry: u64, blocks: &[BasicBlock], edges: &[CfgEdge]) -> String {let mut out = String::new();- out.push_str(&format!("// Ghidrust hand-rolled decompile — function {name} at {entry:#x}\n"));+ out.push_str(&format!(+ "// Ghidrust hand-rolled decompile — function {name} at {entry:#x}\n"+ ));out.push_str(&format!("// blocks={} edges={} insns={}\n",blocks.len(),@@ -564,11 +572,7 @@ fn emit_pseudo_c(name: &str, entry: u64, blocks: &[BasicBlock], edges: &[CfgEdgeif is_cond_jmp(m) {let taken = parse_branch_target(&insn.operands).and_then(|t| blocks.iter().find(|x| x.start == t).map(|x| x.id));- let fall = b- .successors- .iter()- .copied()- .find(|&s| Some(s) != taken);+ let fall = b.successors.iter().copied().find(|&s| Some(s) != taken);out.push_str(&format!(" if (/* {} {} */) {{\n",insn.mnemonic, insn.operands@@ -591,10 +595,7 @@ fn emit_pseudo_c(name: &str, entry: u64, blocks: &[BasicBlock], edges: &[CfgEdgeif insn.operands.is_empty() {out.push_str(&format!(" /* {} */;\n", insn.mnemonic));} else {- out.push_str(&format!(- " /* {} {} */;\n",- insn.mnemonic, insn.operands- ));+ out.push_str(&format!(" /* {} {} */;\n", insn.mnemonic, insn.operands));}}if !b.is_return && !b.is_branch && b.successors.len() == 1 {@@ -652,7 +653,11 @@ mod tests {insn(0x2012, "ret", "", 1),];let d = decompile_instructions("branchy", 0x2000, &insns);- assert!(d.blocks.len() >= 2, "expected multiple blocks, got {}", d.blocks.len());+ assert!(+ d.blocks.len() >= 2,+ "expected multiple blocks, got {}",+ d.blocks.len()+ );assert!(!d.edges.is_empty(), "expected CFG edges");assert!(d.pseudo_c.contains("if (") || d.pseudo_c.contains("goto block_"));assert!(d.pseudo_c.contains("branchy"));@@ -669,7 +674,11 @@ mod tests {];let (d, cov) = decompile_instructions_ir("test_ir", 0x1000, &insns);assert!(cov.total_ops > 0);- assert!(cov.ratio() > 0.5, "expected majority lift, got {}", cov.ratio());+ assert!(+ cov.ratio() > 0.5,+ "expected majority lift, got {}",+ cov.ratio()+ );assert!(d.pseudo_c.contains("Stage-0.5"));assert!(d.pseudo_c.contains("eax = 0;"));assert!(d.pseudo_c.contains("return;"));@@ -683,24 +692,14 @@ mod tests {fn fixture_corpus_lift_ratio_meets_lab_target() {use ghidrust_core::run_analyzers;use ghidrust_lift::{coverage as lift_coverage, lift_instructions};- let fixtures = [- "analysis_lab.pe",- "tiny_x64.pe",- "tiny_x64.elf",- ];+ let fixtures = ["analysis_lab.pe", "tiny_x64.pe", "tiny_x64.elf"];let mut total_ratio = 0f32;let mut samples = 0usize;let mut per_fixture: Vec<(String, f32, usize)> = Vec::new();for fx in fixtures {- let mut prog = load_path(fixture_path(fx))- .unwrap_or_else(|e| panic!("load {fx}: {e}"));+ let mut prog = load_path(fixture_path(fx)).unwrap_or_else(|e| panic!("load {fx}: {e}"));let _ = run_analyzers(&mut prog, &["Function Start Search"]);- let mut entries: Vec<u64> = prog- .analysis- .functions- .iter()- .map(|f| f.entry)- .collect();+ let mut entries: Vec<u64> = prog.analysis.functions.iter().map(|f| f.entry).collect();if entries.is_empty() {if let Some(e) = prog.entry {entries.push(e);@@ -723,7 +722,11 @@ mod tests {total_ratio += cov.ratio();samples += 1;}- let avg = if fx_n > 0 { fx_total / fx_n as f32 } else { 0.0 };+ let avg = if fx_n > 0 {+ fx_total / fx_n as f32+ } else {+ 0.0+ };per_fixture.push((fx.to_string(), avg, fx_n));}assert!(samples > 0, "fixture corpus produced no lift samples");@@ -732,7 +735,10 @@ mod tests {for (fx, r, n) in &per_fixture {eprintln!(" {fx:<20} avg={:.3} functions={}", r, n);}- eprintln!(" overall avg={:.3} samples={}", avg, samples);+ eprintln!(+ " overall avg={:.3} samples={}",+ avg, samples+ );assert!(avg >= 0.98,"fixture-corpus average lift ratio {avg:.3} < 0.98"diff --git a/crates/ghidrust-decomp/src/stage1.rs b/crates/ghidrust-decomp/src/stage1.rsindex 590e7a6..b938e46 100644--- a/crates/ghidrust-decomp/src/stage1.rs+++ b/crates/ghidrust-decomp/src/stage1.rs@@ -24,9 +24,7 @@ use ghidrust_structure::{structure_function_with_hints, NaturalLoop, Region, ShortCircuitClause, ShortCircuitKind,StructureHints, StructureReport, SwitchCase,};-use ghidrust_types::{- recover_with_name, CallConv, ParamList, RustType, StackLocal, TypeRecovery,-};+use ghidrust_types::{recover_with_name, CallConv, ParamList, RustType, StackLocal, TypeRecovery};/// Everything Stage-1 produces alongside the C text: SSA, structure, types/// so callers (bench, GUI, MCP) can display the intermediate views without@@ -131,15 +129,7 @@ pub fn emit_stage1_full(let fold = FoldPlan::build(&ssa);let (text, tokens) = render_function(- name,- entry,- blocks,- &ssa,- &structure,- &types,- coverage,- &fold,- emit_hints,+ name, entry, blocks, &ssa, &structure, &types, coverage, &fold, emit_hints,);Stage1Result {@@ -480,10 +470,7 @@ fn render_block_body(let last_idx = block.ops.len().saturating_sub(1);for (i, op) in block.ops.iter().enumerate() {let is_last = i == last_idx;- if skip_terminator- && is_last- && matches!(op.opcode, OpCode::CBranch | OpCode::Branch)- {+ if skip_terminator && is_last && matches!(op.opcode, OpCode::CBranch | OpCode::Branch) {continue;}// R1: skip assignments whose result was fully inlined.@@ -512,10 +499,7 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {match op.opcode {OpCode::Return => Some("return;".to_string()),OpCode::Nop => None,- OpCode::Branch => Some(format!(- "goto {};",- emit_branch_target(op.inputs.first()?)- )),+ OpCode::Branch => Some(format!("goto {};", emit_branch_target(op.inputs.first()?))),OpCode::CBranch => {// If used at Region::Block level (not consumed by an if/while// wrapper) print the raw cbranch so control flow stays visible.@@ -550,15 +534,15 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {// R6: annotate known vtable bases when the target folds to a const VA.if let Some(va) = tgt.as_const() {if let Some(cls) = ctx.emit_hints.class_for_vtable(va) {- return Some(format!(- "/* virtual {}.vftable */ (*({:#x}))();",- cls, va- ));+ return Some(format!("/* virtual {}.vftable */ (*({:#x}))();", cls, va));}}Some(format!("(*({}))();", format_operand_ctx(tgt, ctx)))}- OpCode::Push => Some(format!("push({});", format_operand_ctx(op.inputs.first()?, ctx))),+ OpCode::Push => Some(format!(+ "push({});",+ format_operand_ctx(op.inputs.first()?, ctx)+ )),OpCode::Pop => {let dst = op.output?;Some(format!("{} = pop();", format_value_named(dst, ctx.types)))@@ -667,10 +651,7 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {"{} = ({} << {}) | {};",format_value_named(dst, ctx.types),format_operand_ctx(a, ctx),- op.inputs- .first()- .map(|v| v.varnode().size * 8)- .unwrap_or(0),+ op.inputs.first().map(|v| v.varnode().size * 8).unwrap_or(0),format_operand_ctx(b, ctx)))}@@ -709,19 +690,13 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {let dst = op.output?;let addr = op.inputs.first()?;let deref = format_deref(addr, ctx);- Some(format!(- "{} = {deref};",- format_value_named(dst, ctx.types)- ))+ Some(format!("{} = {deref};", format_value_named(dst, ctx.types)))}OpCode::Store => {let addr = op.inputs.first()?;let val = op.inputs.get(1)?;let deref = format_deref(addr, ctx);- Some(format!(- "{deref} = {};",- format_operand_ctx(val, ctx)- ))+ Some(format!("{deref} = {};", format_operand_ctx(val, ctx)))}OpCode::Unimplemented => Some(format!("/* unimplemented: {} */",@@ -738,10 +713,7 @@ fn binop(sym: &str, op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {let out_txt = format_value_named(dst, ctx.types);if let SsaOperand::Value(av) = a {if av.space == dst.space && av.offset == dst.offset && av.size == dst.size {- return Some(format!(- "{out_txt} {sym}= {};",- format_operand_ctx(b, ctx)- ));+ return Some(format!("{out_txt} {sym}= {};", format_operand_ctx(b, ctx)));}}Some(format!(@@ -785,10 +757,7 @@ fn format_deref(addr: &SsaOperand, ctx: &RenderCtx) -> String {if let RustType::ArrayPtr { elem_width, .. } = base_ty {if elem_width > 0 && offset % elem_width as u64 == 0 {let idx = offset / elem_width as u64;- return format!(- "{}[{idx}]",- format_value_named(base, ctx.types)- );+ return format!("{}[{idx}]", format_value_named(base, ctx.types));}}}@@ -803,13 +772,9 @@ fn format_operand_ctx(op: &SsaOperand, ctx: &RenderCtx) -> String {let tys = ctx.types;let ssa = ctx.ssa;let fold = ctx.fold;- fold_expr_for(- *v,- ssa,- fold,- &|o| format_operand(o, tys),- &|val| format_value_named(val, tys),- )+ fold_expr_for(*v, ssa, fold, &|o| format_operand(o, tys), &|val| {+ format_value_named(val, tys)+ }).unwrap_or_else(|| format_value_named(*v, tys))}_ => format_operand(op, ctx.types),@@ -898,7 +863,9 @@ fn format_operand_bare(op: &SsaOperand, tys: &TypeRecovery) -> String {SsaOperand::Const(v) if v.space == AddrSpace::Constant => format!("{:#x}", v.offset),SsaOperand::Value(v) => {let raw = format_value_named(*v, tys);- raw.split_once('#').map(|(name, _)| name.to_string()).unwrap_or(raw)+ raw.split_once('#')+ .map(|(name, _)| name.to_string())+ .unwrap_or(raw)}_ => format_operand(op, tys),}@@ -1045,9 +1012,15 @@ mod tests {"recovered int return type expected:\n{text}");assert!(text.contains("return;"), "return missing:\n{text}");- assert!(text.contains("Stage-1"), "must self-identify as Stage-1:\n{text}");+ assert!(+ text.contains("Stage-1"),+ "must self-identify as Stage-1:\n{text}"+ );// eax = 0 idiom lowered- assert!(text.contains("= 0;"), "xor idiom collapse expected:\n{text}");+ assert!(+ text.contains("= 0;"),+ "xor idiom collapse expected:\n{text}"+ );}#[test]@@ -1310,7 +1283,13 @@ mod tests {length: 2,};let d2 = decompile_instructions("wibbler", 0x4010, &[unknown.clone()]);- let rep2 = emit_stage1(&d2.name, d2.entry, &d2.blocks, &[unknown], CallConv::SystemV);+ let rep2 = emit_stage1(+ &d2.name,+ d2.entry,+ &d2.blocks,+ &[unknown],+ CallConv::SystemV,+ );assert!(rep2.pseudo_c.contains("unimplemented"),"genuinely unlifted opcode should stay Unimplemented:\n{}",diff --git a/crates/ghidrust-gui/src/agent_pane.rs b/crates/ghidrust-gui/src/agent_pane.rsindex 6122300..3551f2b 100644--- a/crates/ghidrust-gui/src/agent_pane.rs+++ b/crates/ghidrust-gui/src/agent_pane.rs@@ -78,9 +78,8 @@ impl GrokPaneState {if let Some(sess) = &mut self.session {if sess.poll_exited() {self.session = None;- self.status = Some(- "Grok exited. Click Start / Restart to open a new TUI session.".into(),- );+ self.status =+ Some("Grok exited. Click Start / Restart to open a new TUI session.".into());}}}@@ -172,13 +171,7 @@ pub fn render_grok_pane(ui.horizontal_wrapped(|ui| {ui.label(RichText::new("Grok").color(primary).strong());if let Some(sess) = &state.session {- ui.small(- RichText::new(format!(- "TUI · {}",- sess.project_root.display()- ))- .color(muted),- );+ ui.small(RichText::new(format!("TUI · {}", sess.project_root.display())).color(muted));} else if let Some(bin) = &state.grok_bin {ui.small(RichText::new(format!("grok: {}", bin.display())).color(muted));} else {@@ -406,15 +399,16 @@ mod tests {#[test]fn ensure_skill_turns_checklist_skill_green() {- let dir = std::env::temp_dir().join(format!(- "ghidrust-gui-skill-{}",- std::process::id()- ));+ let dir = std::env::temp_dir().join(format!("ghidrust-gui-skill-{}", std::process::id()));let _ = std::fs::remove_dir_all(&dir);std::fs::create_dir_all(&dir).unwrap();let mut state = GrokPaneState::new();ensure_skill_for_project(&mut state, &dir, None);- assert!(state.skill_wire_error.is_none(), "{:?}", state.skill_wire_error);+ assert!(+ state.skill_wire_error.is_none(),+ "{:?}",+ state.skill_wire_error+ );let skill = pane_start_checklist(&dir).into_iter().find(|r| r.label == "Skill")diff --git a/crates/ghidrust-gui/src/debugger.rs b/crates/ghidrust-gui/src/debugger.rsindex 3cb7274..e85f885 100644--- a/crates/ghidrust-gui/src/debugger.rs+++ b/crates/ghidrust-gui/src/debugger.rs@@ -33,8 +33,8 @@ pub enum DebuggerPane {}impl DebuggerPane {- /// Tab strip order: live panes first, stubs last.- pub const TAB_ORDER: &'static [DebuggerPane] = &[+ /// Tab strip order: live panes first, stubs last.+ pub const TAB_ORDER: &'static [DebuggerPane] = &[DebuggerPane::Targets,DebuggerPane::Modules,DebuggerPane::MemoryBytes,@@ -47,91 +47,91 @@ impl DebuggerPane {DebuggerPane::DebuggerConsole,];- pub const ALL: &'static [DebuggerPane] = Self::TAB_ORDER;+ pub const ALL: &'static [DebuggerPane] = Self::TAB_ORDER;- /// Short label for the tab strip.- pub const fn short_title(self) -> &'static str {+ /// Short label for the tab strip.+ pub const fn short_title(self) -> &'static str {match self {- DebuggerPane::Targets => "Targets",- DebuggerPane::Modules => "Modules",- DebuggerPane::MemoryBytes => "Memory Bytes",- DebuggerPane::Regions => "Regions",- DebuggerPane::Breakpoints => "Breakpoints",- DebuggerPane::Watches => "Watches",- DebuggerPane::Threads => "Threads",- DebuggerPane::Registers => "Registers",- DebuggerPane::Stack => "Stack",- DebuggerPane::DebuggerConsole => "Console",+ DebuggerPane::Targets => "Targets",+ DebuggerPane::Modules => "Modules",+ DebuggerPane::MemoryBytes => "Memory Bytes",+ DebuggerPane::Regions => "Regions",+ DebuggerPane::Breakpoints => "Breakpoints",+ DebuggerPane::Watches => "Watches",+ DebuggerPane::Threads => "Threads",+ DebuggerPane::Registers => "Registers",+ DebuggerPane::Stack => "Stack",+ DebuggerPane::DebuggerConsole => "Console",}}- /// display title (legacy Window menu / provider `TITLE`).+ /// display title (legacy Window menu / provider `TITLE`).#[allow(dead_code)]- pub const fn title(self) -> &'static str {+ pub const fn title(self) -> &'static str {match self {- DebuggerPane::Targets => "Debugger Targets",- DebuggerPane::Threads => "Debugger Threads",- DebuggerPane::Modules => "Debugger Modules",- DebuggerPane::Regions => "Debugger Regions",- DebuggerPane::Registers => "Debugger Registers",- DebuggerPane::Stack => "Debugger Stack",- DebuggerPane::Breakpoints => "Debugger Breakpoints",- DebuggerPane::MemoryBytes => "Debugger Memory Bytes",- DebuggerPane::Watches => "Debugger Watches",- DebuggerPane::DebuggerConsole => "Debugger Console",+ DebuggerPane::Targets => "Debugger Targets",+ DebuggerPane::Threads => "Debugger Threads",+ DebuggerPane::Modules => "Debugger Modules",+ DebuggerPane::Regions => "Debugger Regions",+ DebuggerPane::Registers => "Debugger Registers",+ DebuggerPane::Stack => "Debugger Stack",+ DebuggerPane::Breakpoints => "Debugger Breakpoints",+ DebuggerPane::MemoryBytes => "Debugger Memory Bytes",+ DebuggerPane::Watches => "Debugger Watches",+ DebuggerPane::DebuggerConsole => "Debugger Console",}}- /// plugin owner.- pub const fn plugin(self) -> &'static str {+ /// plugin owner.+ pub const fn plugin(self) -> &'static str {match self {- DebuggerPane::Targets => "DebuggerTargetsPlugin",- DebuggerPane::Threads => "DebuggerThreadsPlugin",- DebuggerPane::Modules => "DebuggerModulesPlugin",- DebuggerPane::Regions => "DebuggerRegionsPlugin",- DebuggerPane::Registers => "DebuggerRegistersPlugin",- DebuggerPane::Stack => "DebuggerStackPlugin",- DebuggerPane::Breakpoints => "DebuggerBreakpointsPlugin",- DebuggerPane::MemoryBytes => "DebuggerMemoryBytesPlugin",- DebuggerPane::Watches => "DebuggerWatchesPlugin",- DebuggerPane::DebuggerConsole => "DebuggerConsolePlugin",+ DebuggerPane::Targets => "DebuggerTargetsPlugin",+ DebuggerPane::Threads => "DebuggerThreadsPlugin",+ DebuggerPane::Modules => "DebuggerModulesPlugin",+ DebuggerPane::Regions => "DebuggerRegionsPlugin",+ DebuggerPane::Registers => "DebuggerRegistersPlugin",+ DebuggerPane::Stack => "DebuggerStackPlugin",+ DebuggerPane::Breakpoints => "DebuggerBreakpointsPlugin",+ DebuggerPane::MemoryBytes => "DebuggerMemoryBytesPlugin",+ DebuggerPane::Watches => "DebuggerWatchesPlugin",+ DebuggerPane::DebuggerConsole => "DebuggerConsolePlugin",}}- /// Stable id for layout persistence (per-tab focus migration).- pub const fn egui_id(self) -> &'static str {+ /// Stable id for layout persistence (per-tab focus migration).+ pub const fn egui_id(self) -> &'static str {match self {- DebuggerPane::Targets => "pane_dbg_targets",- DebuggerPane::Threads => "pane_dbg_threads",- DebuggerPane::Modules => "pane_dbg_modules",- DebuggerPane::Regions => "pane_dbg_regions",- DebuggerPane::Registers => "pane_dbg_registers",- DebuggerPane::Stack => "pane_dbg_stack",- DebuggerPane::Breakpoints => "pane_dbg_breakpoints",- DebuggerPane::MemoryBytes => "pane_dbg_membytes",- DebuggerPane::Watches => "pane_dbg_watches",- DebuggerPane::DebuggerConsole => "pane_dbg_console",+ DebuggerPane::Targets => "pane_dbg_targets",+ DebuggerPane::Threads => "pane_dbg_threads",+ DebuggerPane::Modules => "pane_dbg_modules",+ DebuggerPane::Regions => "pane_dbg_regions",+ DebuggerPane::Registers => "pane_dbg_registers",+ DebuggerPane::Stack => "pane_dbg_stack",+ DebuggerPane::Breakpoints => "pane_dbg_breakpoints",+ DebuggerPane::MemoryBytes => "pane_dbg_membytes",+ DebuggerPane::Watches => "pane_dbg_watches",+ DebuggerPane::DebuggerConsole => "pane_dbg_console",}}- /// Columns rendered in the empty-state table (layout).- pub const fn columns(self) -> &'static [&'static str] {+ /// Columns rendered in the empty-state table (layout).+ pub const fn columns(self) -> &'static [&'static str] {match self {- DebuggerPane::Targets => &["Name", "Type", "State"],- DebuggerPane::Threads => &["TID", "Name", "State", "Comment"],- DebuggerPane::Modules => &["Base", "Name", "Path", "Size"],- DebuggerPane::Regions => &["Start", "End", "Perms", "Kind"],- DebuggerPane::Registers => &["Register", "Bits", "Value"],- DebuggerPane::Stack => &["Level", "Frame", "PC", "Function"],- DebuggerPane::Breakpoints => &["Enabled", "Address", "Kind", "Condition"],- DebuggerPane::MemoryBytes => &["Address", "Bytes", "ASCII"],- DebuggerPane::Watches => &["Expression", "Type", "Value"],- DebuggerPane::DebuggerConsole => &["Line"],+ DebuggerPane::Targets => &["Name", "Type", "State"],+ DebuggerPane::Threads => &["TID", "Name", "State", "Comment"],+ DebuggerPane::Modules => &["Base", "Name", "Path", "Size"],+ DebuggerPane::Regions => &["Start", "End", "Perms", "Kind"],+ DebuggerPane::Registers => &["Register", "Bits", "Value"],+ DebuggerPane::Stack => &["Level", "Frame", "PC", "Function"],+ DebuggerPane::Breakpoints => &["Enabled", "Address", "Kind", "Condition"],+ DebuggerPane::MemoryBytes => &["Address", "Bytes", "ASCII"],+ DebuggerPane::Watches => &["Expression", "Type", "Value"],+ DebuggerPane::DebuggerConsole => &["Line"],}}- /// Copy pointing at the pending backend for this pane.- pub const fn backend_message(self) -> &'static str {+ /// Copy pointing at the pending backend for this pane.+ pub const fn backend_message(self) -> &'static str {match self {DebuggerPane::Targets => {"Live Process Bridge (Windows) — ghidrust_core::process_list/attach."@@ -173,7 +173,7 @@ pub enum DebuggerAction {}impl DebuggerAction {- pub const ALL: &'static [DebuggerAction] = &[+ pub const ALL: &'static [DebuggerAction] = &[DebuggerAction::Launch,DebuggerAction::Attach,DebuggerAction::Disconnect,@@ -185,18 +185,18 @@ impl DebuggerAction {DebuggerAction::ToggleBreakpoint,DebuggerAction::ShowWatches,];- pub const fn label(self) -> &'static str {+ pub const fn label(self) -> &'static str {match self {- DebuggerAction::Launch => "Launch…",- DebuggerAction::Attach => "Attach…",- DebuggerAction::Disconnect => "Disconnect",- DebuggerAction::Continue => "Continue (F5)",- DebuggerAction::Interrupt => "Interrupt",- DebuggerAction::StepInto => "Step Into (F7)",- DebuggerAction::StepOver => "Step Over (F8)",- DebuggerAction::StepOut => "Step Out (Shift+F8)",- DebuggerAction::ToggleBreakpoint => "Toggle Breakpoint (F3)",- DebuggerAction::ShowWatches => "Show Watches Pane",+ DebuggerAction::Launch => "Launch…",+ DebuggerAction::Attach => "Attach…",+ DebuggerAction::Disconnect => "Disconnect",+ DebuggerAction::Continue => "Continue (F5)",+ DebuggerAction::Interrupt => "Interrupt",+ DebuggerAction::StepInto => "Step Into (F7)",+ DebuggerAction::StepOver => "Step Over (F8)",+ DebuggerAction::StepOut => "Step Out (Shift+F8)",+ DebuggerAction::ToggleBreakpoint => "Toggle Breakpoint (F3)",+ DebuggerAction::ShowWatches => "Show Watches Pane",}}}@@ -204,50 +204,50 @@ impl DebuggerAction {/// Persistent state for the debugger tool mode.#[derive(Debug, Clone)]pub struct DebuggerState {- /// User-set breakpoint VAs (session-only until backend lands).+ /// User-set breakpoint VAs (session-only until backend lands).pub breakpoints: Vec<u64>,- /// User-set watch expressions.+ /// User-set watch expressions.pub watches: Vec<String>,- /// Whether the debugger tool mode is active.+ /// Whether the debugger tool mode is active.pub enabled: bool,- /// Host window open (single tabbed Debugger).+ /// Host window open (single tabbed Debugger).pub host_open: bool,- /// Active tab inside the host.+ /// Active tab inside the host.pub active_tab: DebuggerPane,- /// New-breakpoint input.+ /// New-breakpoint input.pub bp_input: String,- /// New-watch input.+ /// New-watch input.pub watch_input: String,- // ── Live Process Bridge (Windows) — `ghidrust_core::process_*` ──────- /// Attached session; `None` = no live target.+ // ── Live Process Bridge (Windows) — `ghidrust_core::process_*` ──────+ /// Attached session; `None` = no live target.pub session: Option<ProcessSession>,- /// Display name of the attached process (from process list).+ /// Display name of the attached process (from process list).pub process_display_name: Option<String>,- /// Cached process list (Targets pane).+ /// Cached process list (Targets pane).pub process_list_cache: Vec<ProcessInfo>,- /// Targets pane process-name filter.+ /// Targets pane process-name filter.pub targets_filter: String,- /// Targets pane manual PID input.+ /// Targets pane manual PID input.pub attach_pid_input: String,- /// Cached module list for the attached session.+ /// Cached module list for the attached session.pub modules_cache: Vec<ModuleInfo>,- /// Modules pane name/path filter.+ /// Modules pane name/path filter.pub modules_filter: String,- /// Cached region list for the attached session.+ /// Cached region list for the attached session.pub regions_cache: Vec<RegionInfo>,- /// Modules pane · Static Mappings mini-tool.+ /// 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.+ /// 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).+ /// Last error from any Live Process Bridge call (fail-loud, not silent).pub live_error: Option<String>,- /// True when session was launched with CREATE_SUSPENDED and not yet resumed.+ /// True when session was launched with CREATE_SUSPENDED and not yet resumed.pub suspended: bool,- /// Launch… dialog open.+ /// Launch… dialog open.pub show_launch_dialog: bool,pub launch_image: String,pub launch_args: String,@@ -316,7 +316,7 @@ impl DebuggerState {}}- /// Enable tool mode: open host, focus Targets, refresh process list if empty.+ /// Enable tool mode: open host, focus Targets, refresh process list if empty.pub fn enable_tool(&mut self) {self.enabled = true;self.host_open = true;@@ -326,13 +326,13 @@ impl DebuggerState {}}- /// Debugger → Attach… : open host on Targets (and refresh list if needed).+ /// Debugger → Attach… : open host on Targets (and refresh list if needed).pub fn open_attach_ui(&mut self) {self.enable_tool();self.active_tab = DebuggerPane::Targets;}- /// Debugger → Launch… : open host + launch dialog; prefill image when provided.+ /// Debugger → Launch… : open host + launch dialog; prefill image when provided.pub fn open_launch_ui(&mut self, prefill_image: Option<&Path>) {self.enable_tool();if let Some(p) = prefill_image {@@ -384,10 +384,10 @@ impl DebuggerState {self.active_tab = DebuggerPane::Targets;}- /// Attach and auto-populate modules / regions / Memory Bytes (CE-style).+ /// Attach and auto-populate modules / regions / Memory Bytes (CE-style).pub fn attach_and_populate(&mut self, pid: u32) {if pid == 0 {- self.live_error = Some("invalid PID".into());+ self.live_error = Some("invalid PID".into());return;}self.live_error = None;@@ -411,11 +411,11 @@ impl DebuggerState {}}- /// Launch CREATE_SUSPENDED + auto-populate (not a debug break-at-entry).+ /// Launch CREATE_SUSPENDED + auto-populate (not a debug break-at-entry).pub fn launch_and_populate(&mut self) {let image = self.launch_image.trim();if image.is_empty() {- self.live_error = Some("launch image path is required".into());+ self.live_error = Some("launch image path is required".into());return;}let req = LaunchRequest {@@ -458,7 +458,7 @@ impl DebuggerState {pub fn resume_session(&mut self) {let Some(sess) = self.session.clone() else {- self.live_error = Some("no live session to resume".into());+ self.live_error = Some("no live session to resume".into());return;};match process_resume(&sess.session_id) {@@ -470,7 +470,7 @@ impl DebuggerState {}}- /// After a successful attach: modules → seed memory → regions → focus Modules.+ /// After a successful attach: modules → seed memory → regions → focus Modules.pub fn refresh_after_attach(&mut self) {let Some(sess) = self.session.clone() else {return;@@ -485,11 +485,12 @@ impl DebuggerState {}}- if let Some(main) = pick_main_module(&self.modules_cache, self.process_display_name.as_deref())+ if let Some(main) =+ pick_main_module(&self.modules_cache, self.process_display_name.as_deref()){- self.mem_bytes_va_input = format!("{:#x}", main.base);+ self.mem_bytes_va_input = format!("{:#x}", main.base);if self.mem_bytes_size_input.trim().is_empty() {- self.mem_bytes_size_input = "256".into();+ self.mem_bytes_size_input = "256".into();}match process_read(&sess.session_id, main.base, 256) {Ok(r) => {@@ -522,43 +523,40 @@ impl DebuggerState {self.active_tab = DebuggerPane::Modules;}- /// Status line for the host chrome.+ /// Status line for the host chrome.pub fn status_line(&self) -> String {match &self.session {Some(sess) => {- let name = self- .process_display_name- .as_deref()- .unwrap_or("(unknown)");+ let name = self.process_display_name.as_deref().unwrap_or("(unknown)");if self.suspended {format!(- "Suspended · {} · pid={} · session={} — Resume to run",+ "Suspended · {} · pid={} · session={} — Resume to run",name, sess.pid, sess.session_id)} else {format!(- "Attached · {} · pid={} · session={}",+ "Attached · {} · pid={} · session={}",name, sess.pid, sess.session_id)}}- None => "Detached — Attach a PID or Launch an image".into(),+ None => "Detached — Attach a PID or Launch an image".into(),}}- /// Window title including process identity when attached.+ /// Window title including process identity when attached.pub fn window_title(&self) -> String {match (&self.session, &self.process_display_name) {(Some(sess), Some(name)) if self.suspended => {- format!("Debugger — {name} [suspended] (pid={})", sess.pid)+ format!("Debugger — {name} [suspended] (pid={})", sess.pid)}- (Some(sess), Some(name)) => format!("Debugger — {name} (pid={})", sess.pid),- (Some(sess), None) => format!("Debugger — pid={}", sess.pid),- _ => "Debugger".into(),+ (Some(sess), Some(name)) => format!("Debugger — {name} (pid={})", sess.pid),+ (Some(sess), None) => format!("Debugger — pid={}", sess.pid),+ _ => "Debugger".into(),}}- /// Module containing `va`, if any.+ /// Module containing `va`, if any.pub fn module_for_va(&self, va: u64) -> Option<&ModuleInfo> {self.modules_cache.iter()@@ -568,7 +566,7 @@ impl DebuggerState {/// Prefer module whose name matches the process; else first with a path; else first.pub fn pick_main_module<'a>(- modules: &'a [ModuleInfo],+ modules: &'a [ModuleInfo],process_name: Option<&str>,) -> Option<&'a ModuleInfo> {if modules.is_empty() {@@ -579,10 +577,11 @@ pub fn pick_main_module<'a>(if let Some(m) = modules.iter().find(|m| m.name.to_ascii_lowercase() == pl) {return Some(m);}- if let Some(m) = modules- .iter()- .find(|m| m.name.to_ascii_lowercase().contains(pl.trim_end_matches(".exe")))- {+ if let Some(m) = modules.iter().find(|m| {+ m.name+ .to_ascii_lowercase()+ .contains(pl.trim_end_matches(".exe"))+ }) {return Some(m);}}@@ -629,7 +628,10 @@ pub fn snapshot_layout_flags() {open_panes.insert(HOST_EGUI_ID.to_string(), state.host_open);for p in DebuggerPane::ALL {- open_panes.insert(p.egui_id().to_string(), state.host_open && state.active_tab == *p);+ open_panes.insert(+ p.egui_id().to_string(),+ state.host_open && state.active_tab == *p,+ );}}@@ -645,7 +647,7 @@ pub fn draw_host(ctx: &egui::Context, state: &mut DebuggerState, muted: Color32).default_size(egui::vec2(720.0, 520.0)).min_size(egui::vec2(420.0, 280.0)).show(ctx, |ui| {- // Fill the resized window so vertical growth isn't clamped by content.+ // Fill the resized window so vertical growth isn't clamped by content.let avail = ui.available_size();ui.set_min_size(avail);render_host_body(state, ui, muted);@@ -663,7 +665,7 @@ pub fn draw_launch_dialog(ctx: &egui::Context, state: &mut DebuggerState, muted:return;}let mut open = true;- egui::Window::new("Launch process")+ egui::Window::new("Launch process").id(egui::Id::new("pane_dbg_launch_dialog")).open(&mut open).collapsible(false)@@ -750,20 +752,20 @@ pub fn draw_launch_dialog(ctx: &egui::Context, state: &mut DebuggerState, muted:}fn render_host_body(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {- // Status bar+ // Status barui.horizontal(|ui| {ui.label(RichText::new(state.status_line()).color(muted));if state.session.is_some() && state.suspended {if ui- .small_button("Resume")- .on_hover_text("ResumeThread on the primary CREATE_SUSPENDED thread")+ .small_button("Resume")+ .on_hover_text("ResumeThread on the primary CREATE_SUSPENDED thread").clicked(){state.resume_session();}}if state.session.is_some() {- if ui.small_button("Detach").clicked() {+ if ui.small_button("Detach").clicked() {state.detach_session();}}@@ -773,9 +775,9 @@ fn render_host_body(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {}ui.separator();- // Tab strip+ // Tab stripegui::ScrollArea::horizontal()- .id_salt("dbg_tab_strip")+ .id_salt("dbg_tab_strip").show(ui, |ui| {ui.horizontal(|ui| {for tab in DebuggerPane::TAB_ORDER {@@ -793,8 +795,13 @@ fn render_host_body(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {}/// Render pane content without the old per-window heading chrome.-pub fn render_pane_body(pane: DebuggerPane, state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {- ui.small(RichText::new(format!("Provider · {}", pane.plugin())).color(muted));+pub fn render_pane_body(+ pane: DebuggerPane,+ state: &mut DebuggerState,+ ui: &mut Ui,+ muted: Color32,+) {+ ui.small(RichText::new(format!("Provider · {}", pane.plugin())).color(muted));ui.separator();match pane {@@ -820,37 +827,37 @@ fn render_targets(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {.color(muted),);ui.horizontal(|ui| {- if ui.button("Refresh process list").clicked() {+ if ui.button("Refresh process list").clicked() {state.refresh_process_list();}- if ui.button("Launch…").clicked() {+ if ui.button("Launch…").clicked() {state.show_launch_dialog = true;}- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut state.targets_filter).desired_width(200.0)- .hint_text("process name…"),+ .hint_text("process name…"),);});if state.session.is_some() {ui.small(- RichText::new("Already attached — use Detach in the status bar to switch targets.")+ RichText::new("Already attached — use Detach in the status bar to switch targets.").color(muted),);}ui.separator();ui.horizontal(|ui| {- ui.label("PID:");+ ui.label("PID:");ui.add(egui::TextEdit::singleline(&mut state.attach_pid_input).desired_width(100.0)- .hint_text("1234"),+ .hint_text("1234"),);if ui.add_enabled(!state.attach_pid_input.trim().is_empty() && state.session.is_none(),- egui::Button::new("Attach by PID"),+ egui::Button::new("Attach by PID"),).clicked(){@@ -858,7 +865,7 @@ fn render_targets(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {}});if state.process_list_cache.is_empty() {- ui.weak("No process list loaded — click Refresh (Windows Toolhelp32 snapshot).");+ ui.weak("No process list loaded — click Refresh (Windows Toolhelp32 snapshot).");return;}let q = state.targets_filter.to_ascii_lowercase();@@ -868,7 +875,7 @@ fn render_targets(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {.filter(|p| q.is_empty() || p.name.to_ascii_lowercase().contains(&q)).collect();ui.small(format!(- "{} / {} processes",+ "{} / {} processes",rows.len(),state.process_list_cache.len()));@@ -876,25 +883,25 @@ fn render_targets(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {let can_attach = state.session.is_none();let list_h = ui.available_height().max(120.0);egui::ScrollArea::vertical()- .id_salt("dbg_targets_scroll")+ .id_salt("dbg_targets_scroll").max_height(list_h).auto_shrink([false, false]).show(ui, |ui| {- egui::Grid::new("dbg_targets_grid")+ egui::Grid::new("dbg_targets_grid").num_columns(4).striped(true).show(ui, |ui| {- ui.strong("PID");- ui.strong("Name");- ui.strong("Path");- ui.strong("");+ ui.strong("PID");+ ui.strong("Name");+ ui.strong("Path");+ ui.strong("");ui.end_row();for p in &rows {- ui.monospace(format!("{}", p.pid));+ ui.monospace(format!("{}", p.pid));ui.label(&p.name);- ui.small(p.path.as_deref().unwrap_or("—"));+ ui.small(p.path.as_deref().unwrap_or("—"));if ui- .add_enabled(can_attach, egui::Button::new("Attach").small())+ .add_enabled(can_attach, egui::Button::new("Attach").small()).clicked(){attach_pid = Some(p.pid);@@ -914,12 +921,12 @@ fn attach(state: &mut DebuggerState, pid: u32) {fn render_modules(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {let Some(sess) = state.session.clone() else {- ui.weak("No live target — attach one from Targets first.");+ ui.weak("No live target — attach one from Targets first.");return;};ui.horizontal(|ui| {- ui.small(RichText::new(format!("pid={}", sess.pid)).color(muted));- if ui.button("Refresh modules").clicked() {+ ui.small(RichText::new(format!("pid={}", sess.pid)).color(muted));+ if ui.button("Refresh modules").clicked() {state.live_error = None;match process_modules(&sess.session_id) {Ok(v) => state.modules_cache = v,@@ -929,15 +936,15 @@ fn render_modules(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {}}}- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut state.modules_filter).desired_width(180.0)- .hint_text("module name…"),+ .hint_text("module name…"),);});if state.modules_cache.is_empty() {- ui.weak("No modules cached — click Refresh modules.");+ ui.weak("No modules cached — click Refresh modules.");} else {let q = state.modules_filter.to_ascii_lowercase();let rows: Vec<&ModuleInfo> = state@@ -953,34 +960,37 @@ fn render_modules(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {}).collect();ui.small(format!(- "{} / {} module(s)",+ "{} / {} module(s)",rows.len(),state.modules_cache.len()));let mut goto_base: Option<u64> = None;- // Leave room below for Static Mappings; grow with the window.+ // Leave room below for Static Mappings; grow with the window.let list_h = (ui.available_height() - 140.0).max(80.0);egui::ScrollArea::vertical()- .id_salt("dbg_modules_scroll")+ .id_salt("dbg_modules_scroll").max_height(list_h).auto_shrink([false, false]).show(ui, |ui| {- egui::Grid::new("dbg_modules_grid")+ egui::Grid::new("dbg_modules_grid").num_columns(5).striped(true).show(ui, |ui| {- ui.strong("Base");- ui.strong("Size");- ui.strong("Name");- ui.strong("Path");- ui.strong("");+ ui.strong("Base");+ ui.strong("Size");+ ui.strong("Name");+ ui.strong("Path");+ ui.strong("");ui.end_row();for m in &rows {- ui.monospace(format!("{:#x}", m.base));- ui.monospace(format!("{:#x}", m.size));+ ui.monospace(format!("{:#x}", m.base));+ ui.monospace(format!("{:#x}", m.size));ui.label(&m.name);- ui.small(m.path.as_deref().unwrap_or("—"));- if ui.small_button("Memory").on_hover_text("Read Memory Bytes at module base").clicked()+ ui.small(m.path.as_deref().unwrap_or("—"));+ if ui+ .small_button("Memory")+ .on_hover_text("Read Memory Bytes at module base")+ .clicked(){goto_base = Some(m.base);}@@ -989,9 +999,9 @@ fn render_modules(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {});});if let Some(base) = goto_base {- state.mem_bytes_va_input = format!("{base:#x}");+ state.mem_bytes_va_input = format!("{base:#x}");if state.mem_bytes_size_input.trim().is_empty() {- state.mem_bytes_size_input = "256".into();+ state.mem_bytes_size_input = "256".into();}match process_read(&sess.session_id, base, 256) {Ok(r) => {@@ -1007,36 +1017,32 @@ fn render_modules(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {}}ui.separator();- ui.label(RichText::new("Static Mappings").strong());+ ui.label(RichText::new("Static Mappings").strong());ui.small(RichText::new(- "ghidrust_core::process::static_to_live · static file RVA → live VA via module base",+ "ghidrust_core::process::static_to_live · static file RVA → live VA via module base",).color(muted),);ui.horizontal(|ui| {- ui.label("Module:");+ ui.label("Module:");ui.add(egui::TextEdit::singleline(&mut state.static_map_module_input).desired_width(160.0)- .hint_text("game.exe"),+ .hint_text("game.exe"),);- ui.label("RVA:");+ ui.label("RVA:");ui.add(egui::TextEdit::singleline(&mut state.static_map_rva_input).desired_width(120.0)- .hint_text("0x1000"),+ .hint_text("0x1000"),);- if ui.button("Resolve").clicked() {+ if ui.button("Resolve").clicked() {let rva = parse_hex(&state.static_map_rva_input).unwrap_or(0);- match static_to_live(- &sess.session_id,- state.static_map_module_input.trim(),- rva,- ) {+ match static_to_live(&sess.session_id, state.static_map_module_input.trim(), rva) {Ok(r) => {state.static_map_result = Some(format!(- "{} base={:#x} rva={:#x} → live_va={:#x}",+ "{} base={:#x} rva={:#x} → live_va={:#x}",r.module, r.base, r.rva, r.live_va));state.live_error = None;@@ -1055,12 +1061,12 @@ fn render_modules(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {fn render_regions(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {let Some(sess) = state.session.clone() else {- ui.weak("No live target — attach one from Targets first.");+ ui.weak("No live target — attach one from Targets first.");return;};ui.horizontal(|ui| {- ui.small(RichText::new(format!("pid={}", sess.pid)).color(muted));- if ui.button("Refresh regions").clicked() {+ ui.small(RichText::new(format!("pid={}", sess.pid)).color(muted));+ if ui.button("Refresh regions").clicked() {state.live_error = None;match process_regions(&sess.session_id, 4096) {Ok(v) => state.regions_cache = v,@@ -1072,22 +1078,22 @@ fn render_regions(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {}});if state.regions_cache.is_empty() {- ui.weak("No regions cached — click Refresh regions.");+ ui.weak("No regions cached — click Refresh regions.");return;}- ui.small(format!("{} region(s)", state.regions_cache.len()));+ ui.small(format!("{} region(s)", state.regions_cache.len()));let row_h = ui.text_style_height(&egui::TextStyle::Monospace) + 2.0;let regions = state.regions_cache.clone();let list_h = ui.available_height().max(120.0);egui::ScrollArea::vertical()- .id_salt("dbg_regions_scroll")+ .id_salt("dbg_regions_scroll").auto_shrink([false, false]).max_height(list_h).show_rows(ui, row_h, regions.len(), |ui, range| {for i in range {let r: &RegionInfo = ®ions[i];ui.monospace(format!(- "{:#018x} +{:#x} protect={} state={} type={}",+ "{:#018x} +{:#x} protect={} state={} type={}",r.base, r.size, r.protect, r.state, r.typ));}@@ -1096,24 +1102,24 @@ fn render_regions(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {fn render_memory_bytes(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {let Some(sess) = state.session.clone() else {- ui.weak("No live target — attach one from Targets first.");+ ui.weak("No live target — attach one from Targets first.");return;};- ui.small(RichText::new(format!("pid={} · live ReadProcessMemory", sess.pid)).color(muted));+ ui.small(RichText::new(format!("pid={} · live ReadProcessMemory", sess.pid)).color(muted));ui.horizontal(|ui| {- ui.label("VA:");+ ui.label("VA:");ui.add(egui::TextEdit::singleline(&mut state.mem_bytes_va_input).desired_width(160.0)- .hint_text("0x140001000"),+ .hint_text("0x140001000"),);- ui.label("Size:");+ ui.label("Size:");ui.add(egui::TextEdit::singleline(&mut state.mem_bytes_size_input).desired_width(100.0)- .hint_text("256"),+ .hint_text("256"),);- if ui.button("Read").clicked() {+ if ui.button("Read").clicked() {let va = parse_hex(&state.mem_bytes_va_input).unwrap_or(0);let size: usize = state.mem_bytes_size_input@@ -1133,32 +1139,28 @@ fn render_memory_bytes(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {}}});- // base+off subtitle when VA falls in a cached module+ // base+off subtitle when VA falls in a cached moduleif let Some(va) = parse_hex(&state.mem_bytes_va_input) {if let Some(m) = state.module_for_va(va) {let off = va.saturating_sub(m.base);ui.small(- RichText::new(format!("{}+{:#x} (base {:#x})", m.name, off, m.base)).color(muted),+ RichText::new(format!("{}+{:#x} (base {:#x})", m.name, off, m.base)).color(muted),);}}let Some(read) = &state.mem_bytes_last else {- ui.weak("No read yet — enter a VA + size and click Read.");+ ui.weak("No read yet — enter a VA + size and click Read.");return;};- let mod_subtitle = state.module_for_va(read.va).map(|m| {- format!(- "{}+{:#x}",- m.name,- read.va.saturating_sub(m.base)- )- });+ let mod_subtitle = state+ .module_for_va(read.va)+ .map(|m| format!("{}+{:#x}", m.name, read.va.saturating_sub(m.base)));ui.small(format!(- "va={:#x}{} requested={} read={}",+ "va={:#x}{} requested={} read={}",read.va,mod_subtitle.as_deref()- .map(|s| format!(" ({s})"))+ .map(|s| format!(" ({s})")).unwrap_or_default(),read.size_requested,read.bytes_read@@ -1167,24 +1169,24 @@ fn render_memory_bytes(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {let base_va = read.va;let list_h = ui.available_height().max(120.0);egui::ScrollArea::vertical()- .id_salt("dbg_membytes_scroll")+ .id_salt("dbg_membytes_scroll").max_height(list_h).auto_shrink([false, false]).show(ui, |ui| {for (row, chunk) in bytes.chunks(16).enumerate() {let addr = base_va + (row as u64) * 16;- let hex: String = chunk.iter().map(|b| format!("{b:02x} ")).collect();+ let hex: String = chunk.iter().map(|b| format!("{b:02x} ")).collect();let ascii: String = chunk.iter().map(|&b| {if (0x20..0x7f).contains(&b) {b as char} else {- '.'+ '.'}}).collect();- ui.monospace(format!("{addr:#018x} {hex:<48} {ascii}"));+ ui.monospace(format!("{addr:#018x} {hex:<48} {ascii}"));}});}@@ -1198,15 +1200,11 @@ fn render_empty_table(pane: DebuggerPane, ui: &mut Ui, muted: Color32) {});ui.separator();ui.add_space(6.0);- ui.label(- RichText::new(pane.backend_message())- .color(muted)- .italics(),- );+ 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.",+ "Pane is present for the Debugger catalog. Live content lands with a target agent.",).color(muted),);@@ -1215,18 +1213,18 @@ fn render_empty_table(pane: DebuggerPane, ui: &mut Ui, muted: Color32) {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).",+ "Session-only breakpoint list (replaced by target-agent state when available).",).color(muted),);ui.horizontal(|ui| {- ui.label("Address:");+ ui.label("Address:");ui.add(egui::TextEdit::singleline(&mut state.bp_input).desired_width(160.0)- .hint_text("0x140001000"),+ .hint_text("0x140001000"),);- if ui.button("Add Breakpoint").clicked() {+ if ui.button("Add Breakpoint").clicked() {if let Some(va) = parse_hex(&state.bp_input) {state.toggle_breakpoint(va);state.bp_input.clear();@@ -1235,22 +1233,22 @@ fn render_breakpoints(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {});ui.separator();if state.breakpoints.is_empty() {- ui.weak("No breakpoints set.");+ ui.weak("No breakpoints set.");return;}let mut delete: Option<usize> = None;- egui::Grid::new("dbg_bp_grid")+ egui::Grid::new("dbg_bp_grid").num_columns(3).striped(true).show(ui, |ui| {- ui.strong("Enabled");- ui.strong("Address");- ui.strong("");+ ui.strong("Enabled");+ ui.strong("Address");+ 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() {+ ui.monospace("*");+ ui.monospace(format!("{va:#x}"));+ if ui.small_button("Delete").clicked() {delete = Some(i);}ui.end_row();@@ -1263,16 +1261,16 @@ fn render_breakpoints(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {fn render_watches(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {ui.small(- RichText::new("Session-only watch list (evaluator pending a target agent).").color(muted),+ RichText::new("Session-only watch list (evaluator pending a target agent).").color(muted),);ui.horizontal(|ui| {- ui.label("Expression:");+ ui.label("Expression:");ui.add(egui::TextEdit::singleline(&mut state.watch_input).desired_width(280.0)- .hint_text("*(int*)rsp"),+ .hint_text("*(int*)rsp"),);- if ui.button("Add Watch").clicked() {+ if ui.button("Add Watch").clicked() {let e = state.watch_input.clone();state.add_watch(e);state.watch_input.clear();@@ -1280,22 +1278,22 @@ fn render_watches(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {});ui.separator();if state.watches.is_empty() {- ui.weak("No watches.");+ ui.weak("No watches.");return;}let mut delete: Option<usize> = None;- egui::Grid::new("dbg_watch_grid")+ egui::Grid::new("dbg_watch_grid").num_columns(3).striped(true).show(ui, |ui| {- ui.strong("Expression");- ui.strong("Value");- ui.strong("");+ ui.strong("Expression");+ 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));- if ui.small_button("Delete").clicked() {+ ui.small(RichText::new("<no target>").color(muted));+ if ui.small_button("Delete").clicked() {delete = Some(i);}ui.end_row();@@ -1309,8 +1307,8 @@ fn render_watches(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {fn parse_hex(s: &str) -> Option<u64> {let s = s.trim();let s = s- .strip_prefix("0x")- .or_else(|| s.strip_prefix("0X"))+ .strip_prefix("0x")+ .or_else(|| s.strip_prefix("0X")).unwrap_or(s);u64::from_str_radix(s, 16).ok()}@@ -1331,20 +1329,23 @@ 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",- "Debugger Modules",- "Debugger Regions",- "Debugger Registers",- "Debugger Stack",- "Debugger Breakpoints",- "Debugger Memory Bytes",- "Debugger Watches",- "Debugger Console",+ "Debugger Targets",+ "Debugger Threads",+ "Debugger Modules",+ "Debugger Regions",+ "Debugger Registers",+ "Debugger Stack",+ "Debugger Breakpoints",+ "Debugger Memory Bytes",+ "Debugger Watches",+ "Debugger Console",] {- assert!(names.contains(&expected), "missing debugger pane {expected}");+ assert!(+ names.contains(&expected),+ "missing debugger pane {expected}"+ );}}@@ -1380,47 +1381,52 @@ mod tests {#[test]fn watch_add_dedup_and_remove() {let mut s = DebuggerState::default();- s.add_watch("rax");- s.add_watch("rax");- s.add_watch("");+ s.add_watch("rax");+ s.add_watch("rax");+ s.add_watch("");assert_eq!(s.watches.len(), 1);- s.add_watch("rbx");+ s.add_watch("rbx");assert_eq!(s.watches.len(), 2);s.remove_watch(0);- assert_eq!(s.watches[0], "rbx");+ assert_eq!(s.watches[0], "rbx");}#[test]fn pick_main_module_prefers_process_name() {let mods = vec![- modinfo("ntdll.dll", 0x7ffe0000, 0x1000, Some(r"C:\Windows\ntdll.dll")),- modinfo("game.exe", 0x140000000, 0x10000, Some(r"C:\game\game.exe")),+ modinfo(+ "ntdll.dll",+ 0x7ffe0000,+ 0x1000,+ Some(r"C:\Windows\ntdll.dll"),+ ),+ 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");+ let m = pick_main_module(&mods, Some("game.exe")).unwrap();+ assert_eq!(m.name(), "game.exe");assert_eq!(m.base, 0x140000000);}#[test]fn pick_main_module_falls_back_to_pathed() {let mods = vec![- modinfo("a.dll", 0x1000, 0x100, None),- modinfo("b.dll", 0x2000, 0x100, Some(r"C:\b.dll")),+ modinfo("a.dll", 0x1000, 0x100, None),+ 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");+ let m = pick_main_module(&mods, Some("missing.exe")).unwrap();+ assert_eq!(m.name(), "b.dll");}#[test]fn clear_live_caches_and_detach_focus_targets() {let mut s = DebuggerState::default();- s.modules_cache = vec![modinfo("x.exe", 0x1000, 0x10, None)];+ s.modules_cache = vec![modinfo("x.exe", 0x1000, 0x10, None)];s.regions_cache = vec![RegionInfo {base: 0x1000,size: 0x1000,- protect: "0x40".into(),- state: "commit".into(),- typ: "0x20000".into(),+ protect: "0x40".into(),+ state: "commit".into(),+ typ: "0x20000".into(),}];s.mem_bytes_last = Some(ReadResult {va: 0x1000,@@ -1432,14 +1438,14 @@ mod tests {as_u64: None,as_f32: None,});- s.process_display_name = Some("x.exe".into());+ s.process_display_name = Some("x.exe".into());s.active_tab = DebuggerPane::Modules;s.clear_live_caches();assert!(s.modules_cache.is_empty());assert!(s.regions_cache.is_empty());assert!(s.mem_bytes_last.is_none());assert!(s.process_display_name.is_none());- // detach_session without a real session still focuses Targets+ // detach_session without a real session still focuses Targetss.active_tab = DebuggerPane::Modules;s.detach_session();assert_eq!(s.active_tab, DebuggerPane::Targets);@@ -1448,9 +1454,9 @@ mod tests {#[test]fn module_for_va_base_plus_off() {let mut s = DebuggerState::default();- s.modules_cache = vec![modinfo("game.exe", 0x140000000, 0x1000, None)];+ 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());}@@ -1458,8 +1464,8 @@ mod tests {fn layout_migration_opens_host_and_focuses_first_tab() {let mut s = DebuggerState::default();let mut panes = BTreeMap::new();- panes.insert("pane_dbg_modules".into(), true);- panes.insert("pane_dbg_regions".into(), true);+ panes.insert("pane_dbg_modules".into(), true);+ panes.insert("pane_dbg_regions".into(), true);apply_layout_flags(&mut s, &panes);assert!(s.host_open);assert!(s.enabled);@@ -1474,14 +1480,14 @@ mod tests {let mut panes = BTreeMap::new();snapshot_layout_flags(&s, &mut panes);assert_eq!(panes.get(HOST_EGUI_ID), Some(&true));- assert_eq!(panes.get("pane_dbg_membytes"), Some(&true));- assert_eq!(panes.get("pane_dbg_targets"), Some(&false));+ assert_eq!(panes.get("pane_dbg_membytes"), Some(&true));+ assert_eq!(panes.get("pane_dbg_targets"), Some(&false));}#[test]fn enable_tool_opens_host_on_targets() {let mut s = DebuggerState::default();- // May fail to list processes in CI/non-Windows — still must open host.+ // May fail to list processes in CI/non-Windows — still must open host.s.enabled = false;s.host_open = false;s.active_tab = DebuggerPane::Stack;@@ -1502,25 +1508,25 @@ mod tests {#[test]fn open_launch_ui_prefills_and_opens_dialog() {let mut s = DebuggerState::default();- s.open_launch_ui(Some(Path::new(r"C:\games\app.exe")));+ s.open_launch_ui(Some(Path::new(r"C:\games\app.exe")));assert!(s.host_open);assert!(s.show_launch_dialog);- assert_eq!(s.launch_image, r"C:\games\app.exe");- assert_eq!(s.launch_cwd, r"C:\games");+ assert_eq!(s.launch_image, r"C:\games\app.exe");+ assert_eq!(s.launch_cwd, r"C:\games");}#[test]fn launch_and_populate_requires_image() {let mut s = DebuggerState::default();s.launch_and_populate();- assert!(s.live_error.as_deref().unwrap().contains("required"));+ assert!(s.live_error.as_deref().unwrap().contains("required"));}#[test]fn detach_clears_suspended_flag() {let mut s = DebuggerState::default();s.suspended = true;- s.process_display_name = Some("x.exe".into());+ s.process_display_name = Some("x.exe".into());s.detach_session();assert!(!s.suspended);assert!(s.process_display_name.is_none());@@ -1528,14 +1534,19 @@ mod tests {#[test]fn simulated_post_attach_focus_modules() {- // Mimic refresh_after_attach's final focus without calling Win32.+ // Mimic refresh_after_attach's final focus without calling Win32.let mut s = DebuggerState::default();s.session = Some(ProcessSession {- session_id: "ps-test".into(),+ session_id: "ps-test".into(),pid: 1,});- s.process_display_name = Some("game.exe".into());- s.modules_cache = vec![modinfo("game.exe", 0x140000000, 0x1000, Some(r"C:\game.exe"))];+ s.process_display_name = Some("game.exe".into());+ s.modules_cache = vec![modinfo(+ "game.exe",+ 0x140000000,+ 0x1000,+ Some(r"C:\game.exe"),+ )];s.active_tab = DebuggerPane::Modules;assert_eq!(s.active_tab, DebuggerPane::Modules);assert!(!s.modules_cache.is_empty());diff --git a/crates/ghidrust-gui/src/decomp_tokens.rs b/crates/ghidrust-gui/src/decomp_tokens.rsindex 8a7bf3e..b4974d5 100644--- a/crates/ghidrust-gui/src/decomp_tokens.rs+++ b/crates/ghidrust-gui/src/decomp_tokens.rs@@ -61,24 +61,19 @@ pub struct DecompLine {/// C-ish keywords used by the Stage-0 / Stage-0.5 emitter.const C_KEYWORDS: &[&str] = &[- "if", "else", "goto", "return", "while", "for", "do", "switch", "case",- "break", "continue", "default", "void", "int", "char", "short", "long",- "unsigned", "signed", "float", "double", "bool", "true", "false", "null",- "sizeof", "struct", "union", "enum",+ "if", "else", "goto", "return", "while", "for", "do", "switch", "case", "break", "continue",+ "default", "void", "int", "char", "short", "long", "unsigned", "signed", "float", "double",+ "bool", "true", "false", "null", "sizeof", "struct", "union", "enum",];/// Register names we always classify as `Variable` (x86-64 GPRs + segment/xmm subset).const REGISTER_NAMES: &[&str] = &[- "rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp", "rsp",- "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",- "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp",- "ax", "bx", "cx", "dx", "si", "di", "bp", "sp",- "al", "bl", "cl", "dl", "ah", "bh", "ch", "dh",- "sil", "dil", "bpl", "spl",- "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d",- "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w",- "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b",- "rip", "eip", "ip", "cs", "ds", "es", "fs", "gs", "ss",+ "rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp", "rsp", "r8", "r9", "r10", "r11", "r12", "r13",+ "r14", "r15", "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp", "ax", "bx", "cx", "dx",+ "si", "di", "bp", "sp", "al", "bl", "cl", "dl", "ah", "bh", "ch", "dh", "sil", "dil", "bpl",+ "spl", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d", "r8w", "r9w", "r10w",+ "r11w", "r12w", "r13w", "r14w", "r15w", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b",+ "r15b", "rip", "eip", "ip", "cs", "ds", "es", "fs", "gs", "ss",];/// Tokenise a full pseudo-C source blob into per-line spans.@@ -127,9 +122,7 @@ pub fn tokenize(source: &str) -> Vec<DecompLine> {////// Groups on `\n` text tokens. Falls back to string tokenisation when the/// stream is empty.-pub fn from_emit_tokens(- emit: &[(String, Option<u64>, &'static str)],-) -> Vec<DecompLine> {+pub fn from_emit_tokens(emit: &[(String, Option<u64>, &'static str)]) -> Vec<DecompLine> {// Simplified adapter: callers map EmitToken → (text, va, kind_name).if emit.is_empty() {return Vec::new();@@ -301,10 +294,7 @@ fn tokenize_line(line: &str, out: &mut Vec<Token>) {continue;}// Hex / numeric literal.- if c == '0'- && i + 1 < bytes.len()- && (bytes[i + 1] == b'x' || bytes[i + 1] == b'X')- {+ if c == '0' && i + 1 < bytes.len() && (bytes[i + 1] == b'x' || bytes[i + 1] == b'X') {let start = i;i += 2;while i < bytes.len() && (bytes[i] as char).is_ascii_hexdigit() {diff --git a/crates/ghidrust-gui/src/decrypt_ui.rs b/crates/ghidrust-gui/src/decrypt_ui.rsnew file mode 100644index 0000000..e26426d--- /dev/null+++ b/crates/ghidrust-gui/src/decrypt_ui.rs@@ -0,0 +1,746 @@+//! Decrypt / crypto-result pane helpers for egui.++use eframe::egui::{self, Color32, Ui};+use ghidrust_core::{+ bake, extract_iocs, magic, suggest_recipe_for_hint, BakeOp, CryptConstantHit,+ CryptoCapabilityHit, ObfuscatedStringHit, Program,+};+use std::cell::RefCell;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DecryptTab {+ Bake,+ Constants,+ Strings,+ Capabilities,+}++impl DecryptTab {+ fn label(self) -> &'static str {+ match self {+ Self::Bake => "Bake",+ Self::Constants => "Constants",+ Self::Strings => "Strings",+ Self::Capabilities => "Capabilities",+ }+ }+}++/// Action requested by the Decrypt pane (host applies to program edits).+#[derive(Debug, Clone)]+pub enum DecryptPaneAction {+ ApplyComment { va: u64, text: String },+ ApplyBookmark { va: u64, text: String },+ SendToListing { va: u64 },+ LoadVa { va: u64, len: usize },+ Goto { va: u64 },+ DecryptNearby { va: u64, hint: String },+ BakeRemnant { va: u64 },+ FocusFunction { va: u64 },+}++#[derive(Debug, Clone)]+pub struct DecryptPaneState {+ pub input_hex: String,+ pub key_hex: String,+ pub iv_hex: String,+ pub output: String,+ pub output_bytes: Vec<u8>,+ pub message: String,+ pub source_va: Option<u64>,+ pub input_source: String,+ pub algo_hint: Option<String>,+ pub tab: DecryptTab,+ pub va_input: String,+ pub va_len: usize,+ pub file_path: String,+ pub selected_preset: String,+ pub mode: String,+ pub nonce_hex: String,+ pub counter: String,+ pub crib: String,+}++impl Default for DecryptPaneState {+ fn default() -> Self {+ Self {+ input_hex: String::new(),+ key_hex: String::new(),+ iv_hex: String::new(),+ output: String::new(),+ output_bytes: Vec::new(),+ message: String::new(),+ source_va: None,+ input_source: "Paste hex or Base64 text".into(),+ algo_hint: None,+ tab: DecryptTab::Bake,+ va_input: String::new(),+ va_len: 256,+ file_path: String::new(),+ selected_preset: "magic".into(),+ mode: "cbc".into(),+ nonce_hex: String::new(),+ counter: "0".into(),+ crib: String::new(),+ }+ }+}++impl DecryptPaneState {+ pub fn focus(&mut self, tab: DecryptTab) {+ self.tab = tab;+ }++ pub fn load_bytes(&mut self, va: Option<u64>, bytes: &[u8], hint: Option<String>) {+ self.input_hex = bytes.iter().map(|b| format!("{b:02x}")).collect();+ self.source_va = va;+ self.input_source = if va.is_some() {+ "Listing selection (hex bytes)".into()+ } else {+ "Paste hex or Base64 text".into()+ };+ self.algo_hint = hint;+ self.output.clear();+ self.output_bytes.clear();+ self.message.clear();+ }++ pub fn load_text(&mut self, va: Option<u64>, text: String, source: &str) {+ self.input_hex = text;+ self.source_va = va;+ self.input_source = source.into();+ self.algo_hint = None;+ self.output.clear();+ self.output_bytes.clear();+ self.message.clear();+ }++ fn input_bytes(&self, preset: &str) -> Vec<u8> {+ if matches!(+ preset,+ "from_b64"+ | "b64_utf16"+ | "b64_gunzip"+ | "from_hex"+ | "charcode"+ | "url"+ | "html"+ | "rot13"+ | "reverse"+ | "utf16"+ | "inflate"+ ) {+ return self.input_hex.trim().as_bytes().to_vec();+ }+ let clean: String = self+ .input_hex+ .chars()+ .filter(|c| !c.is_whitespace())+ .collect();+ (0..clean.len())+ .step_by(2)+ .filter_map(|i| {+ clean+ .get(i..i + 2)+ .and_then(|s| u8::from_str_radix(s, 16).ok())+ })+ .collect()+ }++ pub fn bake_preset(&mut self, preset: &str) {+ let input = self.input_bytes(preset);+ let ops: Vec<BakeOp> = match preset {+ "xor_brute" => vec![BakeOp {+ op: "XORBrute".into(),+ args: serde_json::json!({}),+ }],+ "from_b64" => vec![BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ }],+ "b64_utf16" => vec![+ BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "DecodeUTF16LE".into(),+ args: serde_json::json!({}),+ },+ ],+ "xor_key" => vec![BakeOp {+ op: "XOR".into(),+ args: serde_json::json!({"key_hex": self.key_hex}),+ }],+ "rc4" => vec![BakeOp {+ op: "RC4".into(),+ args: serde_json::json!({"key_hex": self.key_hex}),+ }],+ "aes_cbc" => vec![BakeOp {+ op: "AESDecrypt".into(),+ args: serde_json::json!({+ "key_hex": self.key_hex,+ "iv_hex": self.iv_hex,+ "mode": self.mode+ }),+ }],+ "des" => vec![BakeOp {+ op: "DESDecrypt".into(),+ args: serde_json::json!({"key_hex": self.key_hex, "iv_hex": self.iv_hex, "mode": self.mode}),+ }],+ "triple_des" => vec![BakeOp {+ op: "TripleDESDecrypt".into(),+ args: serde_json::json!({"key_hex": self.key_hex, "iv_hex": self.iv_hex, "mode": self.mode}),+ }],+ "blowfish" => vec![BakeOp {+ op: "BlowfishDecrypt".into(),+ args: serde_json::json!({"key_hex": self.key_hex, "iv_hex": self.iv_hex, "mode": self.mode}),+ }],+ "chacha" => vec![BakeOp {+ op: "ChaCha20Decrypt".into(),+ args: serde_json::json!({+ "key_hex": self.key_hex,+ "nonce_hex": self.nonce_hex,+ "counter": self.counter.parse::<u32>().unwrap_or(0),+ }),+ }],+ "gunzip" => vec![BakeOp {+ op: "Gunzip".into(),+ args: serde_json::json!({}),+ }],+ "inflate" => vec![BakeOp {+ op: "Inflate".into(),+ args: serde_json::json!({}),+ }],+ "from_hex" => vec![BakeOp {+ op: "FromHex".into(),+ args: serde_json::json!({}),+ }],+ "charcode" => vec![BakeOp {+ op: "FromCharcode".into(),+ args: serde_json::json!({}),+ }],+ "url" => vec![BakeOp {+ op: "UrlDecode".into(),+ args: serde_json::json!({}),+ }],+ "html" => vec![BakeOp {+ op: "HtmlEntityDecode".into(),+ args: serde_json::json!({}),+ }],+ "rot13" => vec![BakeOp {+ op: "ROT13".into(),+ args: serde_json::json!({}),+ }],+ "reverse" => vec![BakeOp {+ op: "Reverse".into(),+ args: serde_json::json!({}),+ }],+ "utf16" => vec![BakeOp {+ op: "DecodeUTF16LE".into(),+ args: serde_json::json!({}),+ }],+ "b64_gunzip" => vec![+ BakeOp {+ op: "FromBase64".into(),+ args: serde_json::json!({}),+ },+ BakeOp {+ op: "Gunzip".into(),+ args: serde_json::json!({}),+ },+ ],+ "hint" => {+ if let Some(h) = &self.algo_hint {+ let mut ops = suggest_recipe_for_hint(h);+ for op in &mut ops {+ if op.op.eq_ignore_ascii_case("AESDecrypt")+ || op.op.eq_ignore_ascii_case("RC4")+ || op.op.eq_ignore_ascii_case("XOR")+ {+ if let Some(obj) = op.args.as_object_mut() {+ if !self.key_hex.is_empty() {+ obj.insert(+ "key_hex".into(),+ serde_json::Value::String(self.key_hex.clone()),+ );+ }+ if !self.iv_hex.is_empty() {+ obj.insert(+ "iv_hex".into(),+ serde_json::Value::String(self.iv_hex.clone()),+ );+ }+ }+ }+ }+ ops+ } else {+ self.message = "no algo hint".into();+ return;+ }+ }+ "magic" => {+ let r = if self.crib.trim().is_empty() {+ magic(&input, 3)+ } else {+ ghidrust_core::magic_with_crib(&input, 3, Some(&self.crib))+ };+ self.message = format!("{} {:?}", r.message, r.recipe_applied);+ self.output_bytes = (0..r.output_hex.len())+ .step_by(2)+ .filter_map(|i| u8::from_str_radix(&r.output_hex[i..i + 2], 16).ok())+ .collect();+ self.output = r.output_utf8.unwrap_or(r.output_hex);+ return;+ }+ _ => {+ self.message = format!("unknown preset {preset}");+ return;+ }+ };+ let r = bake(&input, &ops);+ self.message = r.message;+ if r.ok {+ let bytes: Vec<u8> = (0..r.output_hex.len())+ .step_by(2)+ .filter_map(|i| u8::from_str_radix(&r.output_hex[i..i + 2], 16).ok())+ .collect();+ let iocs = extract_iocs(&bytes);+ self.output_bytes = bytes;+ self.output = r.output_utf8.unwrap_or(r.output_hex);+ if !iocs.is_empty() {+ self.message = format!("{} | iocs={}", self.message, iocs.join(", "));+ }+ } else {+ self.output.clear();+ self.output_bytes.clear();+ }+ }+}++pub fn ui_crypto_constants(+ ui: &mut Ui,+ muted: Color32,+ hits: &[CryptConstantHit],+ mut on_goto: impl FnMut(u64),+ mut on_decrypt: impl FnMut(u64, &str),+) {+ ui.heading("Crypto Constants");+ ui.small(egui::RichText::new("Find Crypt analyzer hits").color(muted));+ ui.separator();+ if hits.is_empty() {+ ui.weak("No hits — run Find Crypt analyzer.");+ return;+ }+ egui::ScrollArea::vertical()+ .max_height(420.0)+ .show(ui, |ui| {+ egui::Grid::new("crypt_const_grid")+ .num_columns(4)+ .striped(true)+ .show(ui, |ui| {+ ui.strong("Address");+ ui.strong("Algorithm");+ ui.strong("Constant");+ ui.strong("");+ ui.end_row();+ for h in hits {+ if ui+ .link(egui::RichText::new(format!("{:#x}", h.va)).monospace())+ .clicked()+ {+ on_goto(h.va);+ }+ ui.monospace(&h.algorithm);+ ui.label(&h.constant);+ if ui.button("Decrypt nearby…").clicked() {+ on_decrypt(h.va, &h.algorithm);+ }+ ui.end_row();+ }+ });+ });+}++pub fn ui_recovered_strings(+ ui: &mut Ui,+ muted: Color32,+ hits: &[ObfuscatedStringHit],+ mut on_goto: impl FnMut(u64),+ mut on_bake: impl FnMut(u64),+ mut on_decoder: impl FnMut(u64),+) {+ ui.heading("Recovered Strings");+ ui.small(egui::RichText::new("Obfuscated Strings analyzer").color(muted));+ ui.separator();+ if hits.is_empty() {+ ui.weak("No hits — run Obfuscated Strings analyzer.");+ return;+ }+ egui::ScrollArea::vertical()+ .max_height(420.0)+ .show(ui, |ui| {+ egui::Grid::new("recovered_str_grid")+ .num_columns(5)+ .striped(true)+ .show(ui, |ui| {+ ui.strong("Address");+ ui.strong("Kind");+ ui.strong("String");+ ui.strong("");+ ui.strong("");+ ui.end_row();+ for h in hits {+ if ui+ .link(egui::RichText::new(format!("{:#x}", h.va)).monospace())+ .clicked()+ {+ on_goto(h.va);+ }+ ui.label(format!("{:?}", h.kind));+ let val: String = h.value.chars().take(80).collect();+ ui.monospace(val);+ if ui.small_button("Bake remnant…").clicked() {+ on_bake(h.va);+ }+ if let Some(decoder_va) = h.decoder_va {+ if ui.small_button("Decoder").clicked() {+ on_decoder(decoder_va);+ }+ } else {+ ui.label("");+ }+ ui.end_row();+ }+ });+ });+}++pub fn ui_crypto_capabilities(+ ui: &mut Ui,+ muted: Color32,+ hits: &[CryptoCapabilityHit],+ mut on_goto: impl FnMut(u64),+ mut on_decrypt: impl FnMut(u64, String),+) {+ ui.heading("Crypto Capabilities");+ ui.small(egui::RichText::new("Crypto Capabilities analyzer").color(muted));+ ui.separator();+ if hits.is_empty() {+ ui.weak("No hits — run Crypto Capabilities analyzer.");+ return;+ }+ egui::ScrollArea::vertical()+ .max_height(420.0)+ .show(ui, |ui| {+ egui::Grid::new("crypto_cap_grid")+ .num_columns(4)+ .striped(true)+ .show(ui, |ui| {+ ui.strong("VA");+ ui.strong("Tag");+ ui.strong("Capability");+ ui.strong("");+ ui.end_row();+ for h in hits {+ let va_s = h+ .function_va+ .map(|v| format!("{v:#x}"))+ .unwrap_or_else(|| "-".into());+ if let Some(va) = h.function_va {+ if ui.link(egui::RichText::new(va_s).monospace()).clicked() {+ on_goto(va);+ }+ } else {+ ui.monospace(va_s);+ }+ ui.label(&h.tag);+ ui.label(format!("{} ({})", h.capability, h.evidence));+ if let Some(va) = h.function_va {+ if ui.small_button("Decrypt at function…").clicked() {+ on_decrypt(va, h.capability.clone());+ }+ } else {+ ui.label("");+ }+ ui.end_row();+ }+ });+ });+}++const PRESETS: &[(&str, &str)] = &[+ ("xor_brute", "XOR brute"),+ ("xor_key", "XOR key"),+ ("from_b64", "Base64"),+ ("from_hex", "Hex text"),+ ("b64_utf16", "Base64 → UTF-16LE"),+ ("b64_gunzip", "Base64 → Gunzip"),+ ("gunzip", "Gunzip"),+ ("inflate", "Inflate"),+ ("charcode", "Charcode"),+ ("url", "URL decode"),+ ("html", "HTML entities"),+ ("rot13", "ROT13"),+ ("reverse", "Reverse"),+ ("utf16", "UTF-16LE"),+ ("rc4", "RC4"),+ ("aes_cbc", "AES"),+ ("des", "DES"),+ ("triple_des", "Triple-DES"),+ ("blowfish", "Blowfish"),+ ("chacha", "ChaCha20"),+ ("magic", "Magic"),+];++fn preset_label(preset: &str) -> &'static str {+ PRESETS+ .iter()+ .find_map(|(value, label)| (*value == preset).then_some(*label))+ .unwrap_or("Magic")+}++pub fn ui_decrypt_window(+ ui: &mut Ui,+ muted: Color32,+ state: &mut DecryptPaneState,+ constants: &[CryptConstantHit],+ strings: &[ObfuscatedStringHit],+ capabilities: &[CryptoCapabilityHit],+) -> Option<DecryptPaneAction> {+ ui.heading("Decrypt");+ ui.small(+ egui::RichText::new("Bake input and crypto discovery results in one window.").color(muted),+ );+ ui.separator();+ ui.horizontal_wrapped(|ui| {+ for tab in [+ DecryptTab::Bake,+ DecryptTab::Constants,+ DecryptTab::Strings,+ DecryptTab::Capabilities,+ ] {+ ui.selectable_value(&mut state.tab, tab, tab.label());+ }+ });+ ui.separator();++ match state.tab {+ DecryptTab::Bake => ui_bake_tab(ui, muted, state),+ DecryptTab::Constants => {+ let action = RefCell::new(None);+ ui_crypto_constants(+ ui,+ muted,+ constants,+ |va| *action.borrow_mut() = Some(DecryptPaneAction::Goto { va }),+ |va, hint| {+ *action.borrow_mut() = Some(DecryptPaneAction::DecryptNearby {+ va,+ hint: hint.to_owned(),+ })+ },+ );+ action.into_inner()+ }+ DecryptTab::Strings => {+ let action = RefCell::new(None);+ ui_recovered_strings(+ ui,+ muted,+ strings,+ |va| *action.borrow_mut() = Some(DecryptPaneAction::Goto { va }),+ |va| *action.borrow_mut() = Some(DecryptPaneAction::BakeRemnant { va }),+ |va| *action.borrow_mut() = Some(DecryptPaneAction::FocusFunction { va }),+ );+ action.into_inner()+ }+ DecryptTab::Capabilities => {+ let action = RefCell::new(None);+ ui_crypto_capabilities(+ ui,+ muted,+ capabilities,+ |va| *action.borrow_mut() = Some(DecryptPaneAction::Goto { va }),+ |va, hint| {+ *action.borrow_mut() = Some(DecryptPaneAction::DecryptNearby { va, hint })+ },+ );+ action.into_inner()+ }+ }+}++fn ui_bake_tab(+ ui: &mut Ui,+ muted: Color32,+ state: &mut DecryptPaneState,+) -> Option<DecryptPaneAction> {+ let mut action = None;+ ui.small(egui::RichText::new("Select input, choose an operation, then Bake.").color(muted));+ ui.separator();+ if let Some(hint) = &state.algo_hint {+ ui.label(format!("Hint: {hint}"));+ if hint.to_ascii_uppercase().contains("AES") && ui.button("Apply AES-CBC").clicked() {+ state.bake_preset("aes_cbc");+ }+ if ui.button("Bake from hint").clicked() {+ state.bake_preset("hint");+ }+ }+ if let Some(va) = state.source_va {+ ui.small(format!("Source VA: {va:#x}"));+ }+ ui.small(format!("Input source: {}", state.input_source));+ ui.horizontal(|ui| {+ ui.label("VA:");+ ui.add(egui::TextEdit::singleline(&mut state.va_input).desired_width(120.0));+ ui.label("Length:");+ ui.add(egui::DragValue::new(&mut state.va_len).range(1..=0x10000));+ if ui.button("Load VA").clicked() {+ let raw = state.va_input.trim().trim_start_matches("0x");+ match u64::from_str_radix(raw, 16) {+ Ok(va) => {+ action = Some(DecryptPaneAction::LoadVa {+ va,+ len: state.va_len,+ })+ }+ Err(_) => state.message = "VA must be hexadecimal, e.g. 401000".into(),+ }+ }+ });+ ui.horizontal(|ui| {+ ui.label("File:");+ ui.add(egui::TextEdit::singleline(&mut state.file_path).desired_width(280.0));+ if ui.button("Load file").clicked() {+ match std::fs::read(&state.file_path) {+ Ok(bytes) => {+ state.load_bytes(None, &bytes, None);+ state.input_source = format!("File: {}", state.file_path);+ }+ Err(e) => state.message = format!("file read failed: {e}"),+ }+ }+ });+ ui.label("Input (hex by default; text operations accept pasted text):");+ ui.add(+ egui::TextEdit::multiline(&mut state.input_hex)+ .desired_width(f32::INFINITY)+ .desired_rows(4)+ .font(egui::TextStyle::Monospace),+ );+ ui.horizontal(|ui| {+ ui.label("Key hex:");+ ui.add(egui::TextEdit::singleline(&mut state.key_hex).desired_width(180.0));+ ui.label("IV hex:");+ ui.add(egui::TextEdit::singleline(&mut state.iv_hex).desired_width(180.0));+ });+ ui.horizontal(|ui| {+ ui.label("Mode:");+ egui::ComboBox::from_id_salt("decrypt_mode")+ .selected_text(&state.mode)+ .show_ui(ui, |ui| {+ for mode in ["cbc", "ecb", "ctr", "cfb", "ofb", "gcm"] {+ ui.selectable_value(&mut state.mode, mode.into(), mode);+ }+ });+ ui.label("Nonce:");+ ui.add(egui::TextEdit::singleline(&mut state.nonce_hex).desired_width(130.0));+ ui.label("Counter:");+ ui.add(egui::TextEdit::singleline(&mut state.counter).desired_width(55.0));+ });+ ui.horizontal(|ui| {+ ui.label("Operation:");+ egui::ComboBox::from_id_salt("decrypt_preset")+ .selected_text(preset_label(&state.selected_preset))+ .show_ui(ui, |ui| {+ for (preset, label) in PRESETS {+ ui.selectable_value(&mut state.selected_preset, (*preset).into(), *label);+ }+ });+ if ui.button("Bake operation").clicked() {+ let preset = state.selected_preset.clone();+ state.bake_preset(&preset);+ }+ if ui.button("Bake from hint").clicked() {+ state.bake_preset("hint");+ }+ });+ ui.horizontal(|ui| {+ ui.label("Magic crib:");+ ui.add(egui::TextEdit::singleline(&mut state.crib).desired_width(180.0));+ if ui.button("Magic").clicked() {+ state.bake_preset("magic");+ }+ for (label, preset) in [+ ("XOR brute", "xor_brute"),+ ("Base64", "from_b64"),+ ("Gunzip", "gunzip"),+ ] {+ if ui.small_button(label).clicked() {+ state.bake_preset(preset);+ }+ }+ });+ ui.horizontal(|ui| {+ let can_apply = state.source_va.is_some() && !state.output.is_empty();+ if ui+ .add_enabled(can_apply, egui::Button::new("Apply as comment"))+ .on_hover_text("Write bake output as an EOL comment at the source VA")+ .clicked()+ {+ if let Some(va) = state.source_va {+ let text: String = state.output.chars().take(200).collect();+ action = Some(DecryptPaneAction::ApplyComment {+ va,+ text: format!("decrypted: {text}"),+ });+ }+ }+ if ui+ .add_enabled(can_apply, egui::Button::new("Apply as bookmark"))+ .clicked()+ {+ if let Some(va) = state.source_va {+ action = Some(DecryptPaneAction::ApplyBookmark {+ va,+ text: state.output.chars().take(120).collect(),+ });+ }+ }+ if ui.button("Extract IOCs").clicked() {+ let iocs = extract_iocs(&state.output_bytes);+ state.message = if iocs.is_empty() {+ "No IOCs found in Bake output.".into()+ } else {+ format!("IOCs: {}", iocs.join(", "))+ };+ }+ if ui+ .add_enabled(can_apply, egui::Button::new("Send to Listing"))+ .on_hover_text("Focuses the input VA; output is not written as code.")+ .clicked()+ {+ if let Some(va) = state.source_va {+ action = Some(DecryptPaneAction::SendToListing { va });+ }+ }+ });+ if !state.message.is_empty() {+ ui.small(&state.message);+ }+ ui.label("Output:");+ ui.add(+ egui::TextEdit::multiline(&mut state.output)+ .desired_width(f32::INFINITY)+ .desired_rows(6)+ .font(egui::TextStyle::Monospace),+ );+ action+}++pub fn bytes_at(prog: &Program, va: u64, count: usize) -> Option<Vec<u8>> {+ prog.read_va(va, count)+}diff --git a/crates/ghidrust-gui/src/dock_tabs.rs b/crates/ghidrust-gui/src/dock_tabs.rsindex aa3c2c2..6640712 100644--- a/crates/ghidrust-gui/src/dock_tabs.rs+++ b/crates/ghidrust-gui/src/dock_tabs.rs@@ -55,10 +55,8 @@ pub fn default_dock_state() -> DockState<DockTab> {let [left, right] =dock.main_surface_mut().split_right(NodeIndex::root(), 0.55, vec![DockTab::Decompiler]);- dock.main_surface_mut()- .set_active_tab(left, TabIndex(0)); // Listing- dock.main_surface_mut()- .set_active_tab(right, TabIndex(0)); // Decompiler+ dock.main_surface_mut().set_active_tab(left, TabIndex(0)); // Listing+ dock.main_surface_mut().set_active_tab(right, TabIndex(0)); // Decompilerdock.set_focused_node_and_surface((SurfaceIndex::main(), left));dock}diff --git a/crates/ghidrust-gui/src/entropy.rs b/crates/ghidrust-gui/src/entropy.rsindex 284ab4c..526a666 100644--- a/crates/ghidrust-gui/src/entropy.rs+++ b/crates/ghidrust-gui/src/entropy.rs@@ -110,15 +110,16 @@ pub fn render_entropy_strip(let per = (avail / samples.len() as f32).max(1.0);for (i, s) in samples.iter().enumerate() {let x = rect.min.x + i as f32 * per;- let r = Rect::from_min_size(- egui::pos2(x, rect.min.y),- Vec2::new(per, strip_h),- );+ let r = Rect::from_min_size(egui::pos2(x, rect.min.y), Vec2::new(per, strip_h));painter.rect_filled(r, 0.0, entropy_color(s.entropy));}// Focus cursor line.if let Some(va) = focused_va {- if let Some((i, _)) = samples.iter().enumerate().find(|(_, s)| va >= s.va && va < s.end_va) {+ if let Some((i, _)) = samples+ .iter()+ .enumerate()+ .find(|(_, s)| va >= s.va && va < s.end_va)+ {let x = rect.min.x + (i as f32 + 0.5) * per;painter.line_segment([egui::pos2(x, rect.min.y), egui::pos2(x, rect.max.y)],@@ -160,14 +161,15 @@ pub fn render_overview_strip(let per = (avail / samples.len() as f32).max(1.0);for (i, s) in samples.iter().enumerate() {let x = rect.min.x + i as f32 * per;- let r = Rect::from_min_size(- egui::pos2(x, rect.min.y),- Vec2::new(per, strip_h),- );+ let r = Rect::from_min_size(egui::pos2(x, rect.min.y), Vec2::new(per, strip_h));painter.rect_filled(r, 0.0, overview_color(prog, s));}if let Some(va) = focused_va {- if let Some((i, _)) = samples.iter().enumerate().find(|(_, s)| va >= s.va && va < s.end_va) {+ if let Some((i, _)) = samples+ .iter()+ .enumerate()+ .find(|(_, s)| va >= s.va && va < s.end_va)+ {let x = rect.min.x + (i as f32 + 0.5) * per;painter.line_segment([egui::pos2(x, rect.min.y), egui::pos2(x, rect.max.y)],diff --git a/crates/ghidrust-gui/src/graphs.rs b/crates/ghidrust-gui/src/graphs.rsindex 4cc9f08..f9e449d 100644--- a/crates/ghidrust-gui/src/graphs.rs+++ b/crates/ghidrust-gui/src/graphs.rs@@ -54,10 +54,8 @@ pub enum FunctionGraphLayout {}impl FunctionGraphLayout {- pub const ALL: &'static [FunctionGraphLayout] = &[- FunctionGraphLayout::Hierarchical,- FunctionGraphLayout::Grid,- ];+ pub const ALL: &'static [FunctionGraphLayout] =+ &[FunctionGraphLayout::Hierarchical, FunctionGraphLayout::Grid];pub const fn label(self) -> &'static str {match self {FunctionGraphLayout::Hierarchical => "Hierarchical",@@ -399,12 +397,7 @@ pub fn callees_of(prog: &Program, entry: u64) -> Vec<u64> {continue;}// Snap to the enclosing function's entry when possible.- if let Some(f) = prog- .analysis- .functions- .iter()- .find(|f| xr.to == f.entry)- {+ if let Some(f) = prog.analysis.functions.iter().find(|f| xr.to == f.entry) {out.insert(f.entry);} else if prog.analysis@@ -454,7 +447,10 @@ pub fn layout_call_graph(if next.is_empty() {break;}- per_level.entry(lvl).or_default().extend(next.iter().copied());+ per_level+ .entry(lvl)+ .or_default()+ .extend(next.iter().copied());frontier = next;}diff --git a/crates/ghidrust-gui/src/grok_term/ansi.rs b/crates/ghidrust-gui/src/grok_term/ansi.rsindex cb0bb3b..1f82392 100644--- a/crates/ghidrust-gui/src/grok_term/ansi.rs+++ b/crates/ghidrust-gui/src/grok_term/ansi.rs@@ -331,11 +331,7 @@ impl TerminalGrid {/// Extract visible text from an inclusive cell range (row-major).////// Skips wide-glyph continuations; trims trailing spaces per line.- pub fn text_in_range(- &self,- start: (usize, usize),- end: (usize, usize),- ) -> String {+ pub fn text_in_range(&self, start: (usize, usize), end: (usize, usize)) -> String {let cols = self.cols();let rows = self.rows();if cols == 0 || rows == 0 {@@ -344,9 +340,19 @@ impl TerminalGrid {let (c0, r0) = start;let (c1, r1) = end;let (sc, sr, ec, er) = if (r0, c0) <= (r1, c1) {- (c0.min(cols - 1), r0.min(rows - 1), c1.min(cols - 1), r1.min(rows - 1))+ (+ c0.min(cols - 1),+ r0.min(rows - 1),+ c1.min(cols - 1),+ r1.min(rows - 1),+ )} else {- (c1.min(cols - 1), r1.min(rows - 1), c0.min(cols - 1), r0.min(rows - 1))+ (+ c1.min(cols - 1),+ r1.min(rows - 1),+ c0.min(cols - 1),+ r0.min(rows - 1),+ )};let mut out = String::new();@@ -754,8 +760,7 @@ impl TerminalGrid {let ccol = self.cursor_col;match mode {0 => {- self.active_mut()- .clear_line_range(crow, ccol, cols, attr);+ self.active_mut().clear_line_range(crow, ccol, cols, attr);for r in (crow + 1)..rows {self.active_mut().clear_line_range(r, 0, cols, attr);}diff --git a/crates/ghidrust-gui/src/grok_term/fonts.rs b/crates/ghidrust-gui/src/grok_term/fonts.rsindex cc5d061..7d28d1f 100644--- a/crates/ghidrust-gui/src/grok_term/fonts.rs+++ b/crates/ghidrust-gui/src/grok_term/fonts.rs@@ -34,7 +34,9 @@ fn candidate_mono_paths() -> Vec<PathBuf> {#[cfg(target_os = "macos")]{out.push(PathBuf::from("/System/Library/Fonts/Menlo.ttc"));- out.push(PathBuf::from("/System/Library/Fonts/Supplemental/Courier New.ttf"));+ out.push(PathBuf::from(+ "/System/Library/Fonts/Supplemental/Courier New.ttf",+ ));out.push(PathBuf::from("/System/Library/Fonts/Apple Symbols.ttf"));}#[cfg(target_os = "linux")]@@ -87,10 +89,7 @@ pub fn install_terminal_fonts(ctx: &eframe::egui::Context) {}// Primary mono = first candidate; remaining act as fallbacks for missing glyphs.- let mono = fonts- .families- .entry(FontFamily::Monospace)- .or_default();+ let mono = fonts.families.entry(FontFamily::Monospace).or_default();// Put our fonts first; keep egui defaults after as last resort.let mut rest = mono.clone();mono.clear();@@ -104,10 +103,7 @@ pub fn install_terminal_fonts(ctx: &eframe::egui::Context) {}// Also prepend to Proportional so UI chrome can fall back if needed.- let prop = fonts- .families- .entry(FontFamily::Proportional)- .or_default();+ let prop = fonts.families.entry(FontFamily::Proportional).or_default();for k in loaded.iter().rev() {if !prop.contains(k) {prop.insert(0, k.clone());diff --git a/crates/ghidrust-gui/src/grok_term/pty.rs b/crates/ghidrust-gui/src/grok_term/pty.rsindex 4b3ba74..c47c72f 100644--- a/crates/ghidrust-gui/src/grok_term/pty.rs+++ b/crates/ghidrust-gui/src/grok_term/pty.rs@@ -88,7 +88,6 @@ impl PtySession {Ok(())}}-}impl Drop for PtySession {@@ -214,14 +213,14 @@ mod windows {use std::os::windows::ffi::OsStrExt;use std::ptr;use windows_sys::Win32::Foundation::{- CloseHandle, DuplicateHandle, FALSE, HANDLE, INVALID_HANDLE_VALUE, DUPLICATE_SAME_ACCESS,+ CloseHandle, DuplicateHandle, DUPLICATE_SAME_ACCESS, FALSE, HANDLE, INVALID_HANDLE_VALUE,};use windows_sys::Win32::System::Console::{ClosePseudoConsole, CreatePseudoConsole, ResizePseudoConsole, COORD, HPCON,};use windows_sys::Win32::System::Pipes::CreatePipe;use windows_sys::Win32::System::Threading::{- CreateProcessW, DeleteProcThreadAttributeList, GetExitCodeProcess, GetCurrentProcess,+ CreateProcessW, DeleteProcThreadAttributeList, GetCurrentProcess, GetExitCodeProcess,InitializeProcThreadAttributeList, TerminateProcess, UpdateProcThreadAttribute,CREATE_UNICODE_ENVIRONMENT, EXTENDED_STARTUPINFO_PRESENT, PROCESS_INFORMATION,PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, STARTUPINFOEXW, STARTUPINFOW,@@ -429,9 +428,7 @@ mod windows {let _ = file.into_raw_handle();match result {Ok(n) => Ok(n),- Err(e)- if e.raw_os_error() == Some(109) || e.kind() == io::ErrorKind::BrokenPipe =>- {+ Err(e) if e.raw_os_error() == Some(109) || e.kind() == io::ErrorKind::BrokenPipe => {Ok(0)}Err(e) => Err(e),@@ -507,7 +504,15 @@ mod unix {let mut win: libc::winsize = unsafe { std::mem::zeroed() };win.ws_col = cols;win.ws_row = rows;- let rc = unsafe { libc::openpty(&mut master, &mut slave, std::ptr::null_mut(), std::ptr::null(), &win) };+ let rc = unsafe {+ libc::openpty(+ &mut master,+ &mut slave,+ std::ptr::null_mut(),+ std::ptr::null(),+ &win,+ )+ };if rc != 0 {return Err(io::Error::last_os_error());}diff --git a/crates/ghidrust-gui/src/grok_term/session.rs b/crates/ghidrust-gui/src/grok_term/session.rsindex d8bdce5..fc651c4 100644--- a/crates/ghidrust-gui/src/grok_term/session.rs+++ b/crates/ghidrust-gui/src/grok_term/session.rs@@ -335,11 +335,7 @@ pub fn encode_key(key: egui::Key, modifiers: egui::Modifiers) -> Option<Vec<u8>>// Alt+letter → ESC + char (Grok Windows image paste: Alt+V)if alt && !ctrl {if let Some(c) = key_to_char(key) {- let ch = if shift {- c.to_ascii_uppercase()- } else {- c- };+ let ch = if shift { c.to_ascii_uppercase() } else { c };return Some(vec![0x1b, ch as u8]);}}diff --git a/crates/ghidrust-gui/src/grok_term/view.rs b/crates/ghidrust-gui/src/grok_term/view.rsindex 2aee4f8..93deb60 100644--- a/crates/ghidrust-gui/src/grok_term/view.rs+++ b/crates/ghidrust-gui/src/grok_term/view.rs@@ -2,7 +2,9 @@use super::ansi::{char_cell_width, Color, TerminalGrid, DEFAULT_BG};use super::session::{encode_key, GrokTermSession};-use eframe::egui::{self, Color32, FontId, Key, Modifiers, PointerButton, Pos2, Rect, Sense, Ui, Vec2};+use eframe::egui::{+ self, Color32, FontId, Key, Modifiers, PointerButton, Pos2, Rect, Sense, Ui, Vec2,+};const FONT_SIZE: f32 = 13.0;@@ -69,11 +71,7 @@ pub fn show_terminal(i.events.iter().any(|e| {matches!(e,- egui::Event::Text(_)- | egui::Event::Key {- pressed: true,- ..- }+ egui::Event::Text(_) | egui::Event::Key { pressed: true, .. })})});@@ -133,9 +131,7 @@ fn handle_pointer(.input(|i| i.pointer.hover_pos()).map(|p| pos_to_cell(p, origin, cell_w, cell_h, cols, rows)).unwrap_or((0, 0));- session.write_bytes(- format!("\x1b[<{};{};{}M", btn, c + 1, r + 1).as_bytes(),- );+ session.write_bytes(format!("\x1b[<{};{};{}M", btn, c + 1, r + 1).as_bytes());}}}@@ -163,9 +159,7 @@ fn handle_pointer(session.update_selection(cell.0, cell.1);}if response.drag_stopped_by(PointerButton::Primary) {- let was_drag = session- .selection- .is_some_and(|s| !s.is_empty_cell());+ let was_drag = session.selection.is_some_and(|s| !s.is_empty_cell());if was_drag {finish_host_selection(ui, session);} else {@@ -190,21 +184,14 @@ fn paint_copied_toast(painter: &egui::Painter, term_rect: Rect) {let font = FontId::proportional(13.0);let galley = painter.layout_no_wrap(label.to_owned(), font, Color32::WHITE);let size = galley.size() + pad * 2.0;- let origin = Pos2::new(- term_rect.max.x - size.x - 10.0,- term_rect.min.y + 10.0,- );+ let origin = Pos2::new(term_rect.max.x - size.x - 10.0, term_rect.min.y + 10.0);let rect = Rect::from_min_size(origin, size);painter.rect_filled(rect,4.0,Color32::from_rgba_unmultiplied(0x1B, 0x5E, 0x20, 220),);- painter.galley(- origin + pad,- galley,- Color32::WHITE,- );+ painter.galley(origin + pad, galley, Color32::WHITE);}fn paint_grid(@@ -256,9 +243,8 @@ fn paint_grid(if cell.ch != ' ' && !cell.ch.is_control() {let clipped = painter.with_clip_rect(rect);- let g = ui.fonts(|f| {- f.layout_no_wrap(cell.ch.to_string(), font.clone(), to_color32(fg))- });+ let g = ui+ .fonts(|f| f.layout_no_wrap(cell.ch.to_string(), font.clone(), to_color32(fg)));let ty = y + ((cell_h - g.size().y) * 0.5).max(0.0);let tx = x + ((cell_w * span as f32 - g.size().x) * 0.5).max(0.0);clipped.galley(Pos2::new(tx, ty), g, to_color32(fg));@@ -314,9 +300,7 @@ fn handle_input(ui: &mut Ui, session: &mut GrokTermSession) {// exists, Copy means clipboard; otherwise Copy is Grok's Ctrl+C (0x03).let mut paste: Option<String> = None;let mut copy_event = false;- let has_sel = session- .selection- .is_some_and(|s| !s.is_empty_cell());+ let has_sel = session.selection.is_some_and(|s| !s.is_empty_cell());ui.input_mut(|i| {i.events.retain(|ev| match ev {@@ -374,9 +358,7 @@ fn handle_input(ui: &mut Ui, session: &mut GrokTermSession) {// Ctrl+Shift+C or Copy with selection → clipboard (do not interrupt Grok).let force_clipboard = ui.input(|i| {- (i.modifiers.ctrl || i.modifiers.command)- && i.modifiers.shift- && i.key_pressed(Key::C)+ (i.modifiers.ctrl || i.modifiers.command) && i.modifiers.shift && i.key_pressed(Key::C)});if (copy_event && has_sel) || force_clipboard {if session.copy_selection_and_clear(ui.ctx()) {diff --git a/crates/ghidrust-gui/src/icons.rs b/crates/ghidrust-gui/src/icons.rsindex c87078f..b88c162 100644--- a/crates/ghidrust-gui/src/icons.rs+++ b/crates/ghidrust-gui/src/icons.rs@@ -31,9 +31,7 @@ pub fn m3_icon(ui: &mut Ui, icon: M3Icon, size: f32, color: Color32) -> egui::Refn paint_icon(painter: &egui::Painter, rect: Rect, icon: M3Icon, color: Color32) {let s = rect.width().min(rect.height());let origin = rect.center() - Vec2::splat(s * 0.5);- let map = |x: f32, y: f32| -> Pos2 {- Pos2::new(origin.x + x / VB * s, origin.y + y / VB * s)- };+ let map = |x: f32, y: f32| -> Pos2 { Pos2::new(origin.x + x / VB * s, origin.y + y / VB * s) };let stroke = Stroke::new((s / VB) * 1.75, color);match icon {@@ -52,7 +50,11 @@ fn paint_icon(painter: &egui::Painter, rect: Rect, icon: M3Icon, color: Color32)map(12.0, 6.0),map(10.0, 4.0),];- painter.add(egui::Shape::convex_polygon(pts.to_vec(), color.gamma_multiply(0.35), stroke));+ painter.add(egui::Shape::convex_polygon(+ pts.to_vec(),+ color.gamma_multiply(0.35),+ stroke,+ ));}M3Icon::CheckCircle => {// Outer circle fill + check mark@@ -77,7 +79,11 @@ fn paint_icon(painter: &egui::Painter, rect: Rect, icon: M3Icon, color: Color32)M3Icon::PlayArrow => {// Triangle pointing right: (8,5) (8,19) (19,12)let pts = [map(8.0, 5.0), map(8.0, 19.0), map(19.0, 12.0)];- painter.add(egui::Shape::convex_polygon(pts.to_vec(), color, Stroke::NONE));+ painter.add(egui::Shape::convex_polygon(+ pts.to_vec(),+ color,+ Stroke::NONE,+ ));}}}@@ -104,7 +110,11 @@ pub fn status_badge(ui: &mut Ui, analyzed: bool, analyzed_color: Color32, muted:ui.spacing_mut().item_spacing.x = 4.0;if analyzed {m3_icon(ui, M3Icon::CheckCircle, 14.0, analyzed_color);- ui.label(egui::RichText::new("Analyzed").small().color(analyzed_color));+ ui.label(+ egui::RichText::new("Analyzed")+ .small()+ .color(analyzed_color),+ );} else {m3_icon(ui, M3Icon::RadioUnchecked, 14.0, muted);ui.label(egui::RichText::new("Not analyzed").small().color(muted));diff --git a/crates/ghidrust-gui/src/layouts.rs b/crates/ghidrust-gui/src/layouts.rsindex 97f5f64..b59f4f3 100644--- a/crates/ghidrust-gui/src/layouts.rs+++ b/crates/ghidrust-gui/src/layouts.rs@@ -23,33 +23,33 @@ use std::path::PathBuf;#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]pub struct SavedLayout {pub name: String,- /// Pane-id → open bit.+ /// Pane-id → open bit.pub open_panes: BTreeMap<String, bool>,- /// Dock checkbox states (`project_tree`, `program_tree`, `symbol_tree`, `console`).+ /// Dock checkbox states (`project_tree`, `program_tree`, `symbol_tree`, `console`).pub docks: BTreeMap<String, bool>,- /// Legacy center-tab shim (`overview` / `listing` / `decompiler` / `datatypes`).- /// Still written so older readers / tests keep working; prefer `dock_tree`.+ /// Legacy center-tab shim (`overview` / `listing` / `decompiler` / `datatypes`).+ /// Still written so older readers / tests keep working; prefer `dock_tree`.pub center: String,- /// Serialized `egui_dock::DockState<DockTab>` (serde feature). Absent on- /// layouts saved before center docking landed.- #[serde(default, skip_serializing_if = "Option::is_none")]+ /// Serialized `egui_dock::DockState<DockTab>` (serde feature). Absent on+ /// layouts saved before center docking landed.+ #[serde(default, skip_serializing_if = "Option::is_none")]pub dock_tree: Option<serde_json::Value>,- /// Theme (`dark` / `light`).+ /// Theme (`dark` / `light`).pub theme: String,- /// Free-form comment shown in Configure dialog.+ /// Free-form comment shown in Configure dialog.pub comment: String,}/// Directory holding user-saved `<name>.tool.json` files.pub fn layouts_dir() -> PathBuf {- if let Ok(appdata) = std::env::var("APPDATA") {- PathBuf::from(appdata).join("ghidrust").join("layouts")- } else if let Ok(home) = std::env::var("USERPROFILE") {- PathBuf::from(home).join(".ghidrust").join("layouts")- } else if let Ok(home) = std::env::var("HOME") {- PathBuf::from(home).join(".ghidrust").join("layouts")+ if let Ok(appdata) = std::env::var("APPDATA") {+ PathBuf::from(appdata).join("ghidrust").join("layouts")+ } else if let Ok(home) = std::env::var("USERPROFILE") {+ PathBuf::from(home).join(".ghidrust").join("layouts")+ } else if let Ok(home) = std::env::var("HOME") {+ PathBuf::from(home).join(".ghidrust").join("layouts")} else {- PathBuf::from(".ghidrust_layouts")+ PathBuf::from(".ghidrust_layouts")}}@@ -57,21 +57,19 @@ pub fn layouts_dir() -> PathBuf {pub fn save_layout(layout: &SavedLayout) -> std::io::Result<PathBuf> {let dir = layouts_dir();std::fs::create_dir_all(&dir)?;- let path = dir.join(format!("{}.tool.json", sanitize(&layout.name)));- let text = serde_json::to_string_pretty(layout).map_err(|e| {- std::io::Error::new(std::io::ErrorKind::InvalidData, format!("serde: {e}"))- })?;+ let path = dir.join(format!("{}.tool.json", sanitize(&layout.name)));+ let text = serde_json::to_string_pretty(layout)+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("serde: {e}")))?;std::fs::write(&path, text)?;Ok(path)}/// Load a layout preset by short name.pub fn load_layout(name: &str) -> std::io::Result<SavedLayout> {- let path = layouts_dir().join(format!("{}.tool.json", sanitize(name)));+ let path = layouts_dir().join(format!("{}.tool.json", sanitize(name)));let text = std::fs::read_to_string(&path)?;- serde_json::from_str(&text).map_err(|e| {- std::io::Error::new(std::io::ErrorKind::InvalidData, format!("serde: {e}"))- })+ serde_json::from_str(&text)+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, format!("serde: {e}")))}/// Enumerate every saved layout on disk.@@ -84,7 +82,7 @@ pub fn list_layouts() -> Vec<String> {for entry in rd.flatten() {let p = entry.path();if let Some(name) = p.file_name().and_then(|s| s.to_str()) {- if let Some(rest) = name.strip_suffix(".tool.json") {+ if let Some(rest) = name.strip_suffix(".tool.json") {out.push(rest.to_string());}}@@ -95,17 +93,17 @@ pub fn list_layouts() -> Vec<String> {/// Delete a saved layout by name.pub fn delete_layout(name: &str) -> std::io::Result<()> {- let path = layouts_dir().join(format!("{}.tool.json", sanitize(name)));+ let path = layouts_dir().join(format!("{}.tool.json", sanitize(name)));std::fs::remove_file(path)}fn sanitize(name: &str) -> String {name.chars().map(|c| {- if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {+ if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {c} else {- '_'+ '_'}}).collect()@@ -116,181 +114,181 @@ fn sanitize(name: &str) -> String {/// read-only list.#[derive(Debug, Clone, Copy)]pub struct PluginRow {- pub name: &'static str,- pub kind: &'static str,- pub state: &'static str,- pub description: &'static str,+ pub name: &'static str,+ pub kind: &'static str,+ pub state: &'static str,+ pub description: &'static str,}/// Every plugin analog Ghidrust ships today.pub const PLUGIN_CATALOG: &[PluginRow] = &[PluginRow {- name: "CodeBrowserPlugin",- kind: "Core",- state: "Included",- description: "Listing + Decompiler center panes .",+ name: "CodeBrowserPlugin",+ kind: "Core",+ state: "Included",+ description: "Listing + Decompiler center panes .",},PluginRow {- name: "DecompilePlugin",- kind: "Core",- state: "Included",- description: "Stage-0 / Stage-0.5 / Stage-1 pseudo-C emission.",+ name: "DecompilePlugin",+ kind: "Core",+ state: "Included",+ description: "Stage-0 / Stage-0.5 / Stage-1 pseudo-C emission.",},PluginRow {- name: "SymbolTreePlugin",- kind: "Base",- state: "Included",- description: "Imports / Exports / Functions / Labels / Classes / Namespaces tree.",+ name: "SymbolTreePlugin",+ kind: "Base",+ state: "Included",+ description: "Imports / Exports / Functions / Labels / Classes / Namespaces tree.",},PluginRow {- name: "ProgramTreePlugin",- kind: "Base",- state: "Included",- description: "Modules / fragments . view filter.",+ name: "ProgramTreePlugin",+ kind: "Base",+ state: "Included",+ description: "Modules / fragments . view filter.",},PluginRow {- name: "DataTypeManagerPlugin",- kind: "Base",- state: "Included",- description: "Built-In + Program archives, editors, Data Type Chooser.",+ name: "DataTypeManagerPlugin",+ kind: "Base",+ state: "Included",+ description: "Built-In + Program archives, editors, Data Type Chooser.",},PluginRow {- name: "FunctionGraphPlugin",- kind: "FunctionGraph",- state: "Included",- description: "CFG vertex / edge layout on top of Stage-0 blocks.",+ name: "FunctionGraphPlugin",+ kind: "FunctionGraph",+ state: "Included",+ description: "CFG vertex / edge layout on top of Stage-0 blocks.",},PluginRow {- name: "FunctionCallGraphPlugin",- kind: "GraphFunctionCalls",- state: "Included",- description: "Level-based directed call graph in / out of source function.",+ name: "FunctionCallGraphPlugin",+ kind: "GraphFunctionCalls",+ state: "Included",+ description: "Level-based directed call graph in / out of source function.",},PluginRow {- name: "CallTreePlugin",- kind: "Base",- state: "Included",- description: "Incoming callers / outgoing callees + refs GTree pair.",+ name: "CallTreePlugin",+ kind: "Base",+ state: "Included",+ description: "Incoming callers / outgoing callees + refs GTree pair.",},PluginRow {- name: "MemoryMapPlugin",- kind: "Base",- state: "Included",- description: "Editable Add / Delete / Toggle RWX memory-block table.",+ name: "MemoryMapPlugin",+ kind: "Base",+ state: "Included",+ description: "Editable Add / Delete / Toggle RWX memory-block table.",},PluginRow {- name: "RegisterPlugin",- kind: "Base",- state: "Included",+ name: "RegisterPlugin",+ kind: "Base",+ state: "Included",description: "Hierarchical register lattice + session values.",},PluginRow {- name: "OverviewPlugin",- kind: "Base",- state: "Included",- description: "Memory-block colour banner (X / W / R / unmapped).",+ name: "OverviewPlugin",+ kind: "Base",+ state: "Included",+ description: "Memory-block colour banner (X / W / R / unmapped).",},PluginRow {- name: "EntropyPlugin",- kind: "Base",- state: "Included",- description: "Shannon-entropy strip across mapped blocks.",+ name: "EntropyPlugin",+ kind: "Base",+ state: "Included",+ description: "Shannon-entropy strip across mapped blocks.",},PluginRow {- name: "BookmarkPlugin",- kind: "Base",- state: "Included",- description: "5 bookmark kinds; margin markers.",+ name: "BookmarkPlugin",+ kind: "Base",+ state: "Included",+ description: "5 bookmark kinds; margin markers.",},PluginRow {- name: "CommentWindowPlugin",- kind: "Base",- state: "Included",- description: "Filter by kind + text; jump to source VA.",+ name: "CommentWindowPlugin",+ kind: "Base",+ state: "Included",+ description: "Filter by kind + text; jump to source VA.",},PluginRow {- name: "ByteViewerPlugin",- kind: "Base",- state: "Included",- description: "Hex + ASCII split view over Program bytes.",+ name: "ByteViewerPlugin",+ kind: "Base",+ state: "Included",+ description: "Hex + ASCII split view over Program bytes.",},PluginRow {name: "ScriptMgrPlugin",- kind: "Scripting",- state: "Included",- description: "Ghidrust MCP tool catalog (from skill/SKILL.md).",+ kind: "Scripting",+ state: "Included",+ description: "Ghidrust MCP tool catalog (from skill/SKILL.md).",},PluginRow {- name: "TextEditorManagerPlugin",- kind: "Scripting",- state: "Included",- description: "Multi-tab in-memory editor for local script files.",+ name: "TextEditorManagerPlugin",+ kind: "Scripting",+ state: "Included",+ description: "Multi-tab in-memory editor for local script files.",},PluginRow {- name: "InterpreterPanelPlugin",- kind: "Scripting",- state: "Included · REPL stub",- description: "MCP REPL — wires into `ghidrust mcp` stdio host in P17.",+ name: "InterpreterPanelPlugin",+ kind: "Scripting",+ state: "Included · REPL stub",+ description: "MCP REPL — wires into `ghidrust mcp` stdio host in P17.",},PluginRow {- name: "DebuggerTargetsPlugin",- kind: "Debugger",- state: "Included · live",- description: "Tabbed Debugger · Targets — process list + attach (Live Process Bridge).",+ name: "DebuggerTargetsPlugin",+ kind: "Debugger",+ state: "Included · live",+ description: "Tabbed Debugger · Targets — process list + attach (Live Process Bridge).",},PluginRow {- name: "DebuggerThreadsPlugin",- kind: "Debugger",- state: "Included · stub",- description: "Tabbed Debugger · Threads — live backend not yet wired.",+ name: "DebuggerThreadsPlugin",+ kind: "Debugger",+ state: "Included · stub",+ description: "Tabbed Debugger · Threads — live backend not yet wired.",},PluginRow {- name: "DebuggerModulesPlugin",- kind: "Debugger",- state: "Included · live",- description: "Tabbed Debugger · Modules — auto-populated on attach + Static Mappings.",+ name: "DebuggerModulesPlugin",+ kind: "Debugger",+ state: "Included · live",+ description: "Tabbed Debugger · Modules — auto-populated on attach + Static Mappings.",},PluginRow {- name: "DebuggerRegionsPlugin",- kind: "Debugger",- state: "Included · live",- description: "Tabbed Debugger · Regions — VirtualQueryEx map auto-fetched on attach.",+ name: "DebuggerRegionsPlugin",+ kind: "Debugger",+ state: "Included · live",+ description: "Tabbed Debugger · Regions — VirtualQueryEx map auto-fetched on attach.",},PluginRow {- name: "DebuggerRegistersPlugin",- kind: "Debugger",- state: "Included · stub",- description: "Tabbed Debugger · Registers — live backend not yet wired.",+ name: "DebuggerRegistersPlugin",+ kind: "Debugger",+ state: "Included · stub",+ description: "Tabbed Debugger · Registers — live backend not yet wired.",},PluginRow {- name: "DebuggerStackPlugin",- kind: "Debugger",- state: "Included · stub",- description: "Tabbed Debugger · Stack — live backend not yet wired.",+ name: "DebuggerStackPlugin",+ kind: "Debugger",+ state: "Included · stub",+ description: "Tabbed Debugger · Stack — live backend not yet wired.",},PluginRow {- name: "DebuggerBreakpointsPlugin",- kind: "Debugger",- state: "Included · session",- description: "Tabbed Debugger · Breakpoints — session-only list; agent-set pending.",+ name: "DebuggerBreakpointsPlugin",+ kind: "Debugger",+ state: "Included · session",+ description: "Tabbed Debugger · Breakpoints — session-only list; agent-set pending.",},PluginRow {- name: "DebuggerMemoryBytesPlugin",- kind: "Debugger",- state: "Included · live",- description: "Tabbed Debugger · Memory Bytes — seeded at main module base on attach.",+ name: "DebuggerMemoryBytesPlugin",+ kind: "Debugger",+ state: "Included · live",+ description: "Tabbed Debugger · Memory Bytes — seeded at main module base on attach.",},PluginRow {- name: "DebuggerWatchesPlugin",- kind: "Debugger",- state: "Included · session",- description: "Tabbed Debugger · Watches — session-only list; evaluator pending.",+ name: "DebuggerWatchesPlugin",+ kind: "Debugger",+ state: "Included · session",+ description: "Tabbed Debugger · Watches — session-only list; evaluator pending.",},PluginRow {- name: "DebuggerConsolePlugin",- kind: "Debugger",- state: "Included · stub",- description: "Tabbed Debugger · Console — target-agent stdio pending.",+ name: "DebuggerConsolePlugin",+ kind: "Debugger",+ state: "Included · stub",+ description: "Tabbed Debugger · Console — target-agent stdio pending.",},];@@ -301,12 +299,12 @@ mod tests {#[test]fn round_trip_layout_json() {let l = SavedLayout {- name: "test".into(),- open_panes: [("pane_bookmarks".to_string(), true)].into_iter().collect(),- docks: [("console".to_string(), true)].into_iter().collect(),- center: "listing".into(),+ name: "test".into(),+ open_panes: [("pane_bookmarks".to_string(), true)].into_iter().collect(),+ docks: [("console".to_string(), true)].into_iter().collect(),+ center: "listing".into(),dock_tree: None,- theme: "dark".into(),+ theme: "dark".into(),comment: String::new(),};let text = serde_json::to_string(&l).unwrap();@@ -316,7 +314,7 @@ mod tests {#[test]fn legacy_layout_without_dock_tree_still_deserializes() {- let text = r#"{+ let text = r#"{"name": "old","open_panes": {},"docks": {},@@ -325,34 +323,34 @@ mod tests {"comment": ""}"#;let back: SavedLayout = serde_json::from_str(text).unwrap();- assert_eq!(back.center, "decompiler");+ assert_eq!(back.center, "decompiler");assert!(back.dock_tree.is_none());}#[test]fn sanitize_strips_path_seps() {- assert_eq!(sanitize("a/b\\c*d"), "a_b_c_d");- assert_eq!(sanitize("hello-world.1"), "hello-world.1");+ assert_eq!(sanitize("a/b\\c*d"), "a_b_c_d");+ assert_eq!(sanitize("hello-world.1"), "hello-world.1");}#[test]fn plugin_catalog_covers_graph_debugger_configure_providers() {- let names: Vec<&'static str> = PLUGIN_CATALOG.iter().map(|p| p.name()).collect();+ let names: Vec<&'static str> = PLUGIN_CATALOG.iter().map(|p| p.name()).collect();for expected in [- "FunctionGraphPlugin",- "FunctionCallGraphPlugin",- "CallTreePlugin",- "MemoryMapPlugin",- "RegisterPlugin",- "OverviewPlugin",- "EntropyPlugin",+ "FunctionGraphPlugin",+ "FunctionCallGraphPlugin",+ "CallTreePlugin",+ "MemoryMapPlugin",+ "RegisterPlugin",+ "OverviewPlugin",+ "EntropyPlugin","ScriptMgrPlugin",- "TextEditorManagerPlugin",- "InterpreterPanelPlugin",- "DebuggerTargetsPlugin",- "DebuggerBreakpointsPlugin",+ "TextEditorManagerPlugin",+ "InterpreterPanelPlugin",+ "DebuggerTargetsPlugin",+ "DebuggerBreakpointsPlugin",] {- assert!(names.contains(&expected), "missing plugin {expected}");+ assert!(names.contains(&expected), "missing plugin {expected}");}}}diff --git a/crates/ghidrust-gui/src/listing/detail_pane.rs b/crates/ghidrust-gui/src/listing/detail_pane.rsindex bb18c77..c159a42 100644--- a/crates/ghidrust-gui/src/listing/detail_pane.rs+++ b/crates/ghidrust-gui/src/listing/detail_pane.rs@@ -6,64 +6,64 @@ use ghidrust_core::{Arch, Instruction};pub fn ui_detail_pane(ui: &mut egui::Ui, insn: &Instruction, arch: Arch) {ui.horizontal(|ui| {- ui.label("Address:");- ui.monospace(format!("{:#x}", insn.address));- ui.label("Size:");- ui.monospace(format!("{}", insn.length));+ ui.label("Address:");+ ui.monospace(format!("{:#x}", insn.address));+ ui.label("Size:");+ ui.monospace(format!("{}", insn.length));});ui.horizontal(|ui| {- ui.label("Id:");- ui.monospace(format!("{} ({})", insn.id.raw(), insn.id.raw()));+ ui.label("Id:");+ ui.monospace(format!("{} ({})", insn.id.raw(), insn.id.raw()));if let Some(name) = insn_name(arch, insn.id) {- ui.label(format!("· {name}"));+ ui.label(format!("· {name}"));}});ui.horizontal(|ui| {- ui.label("Mnemonic:");+ ui.label("Mnemonic:");ui.monospace(&insn.mnemonic);if !insn.operands.is_empty() {- ui.label("Operands:");+ ui.label("Operands:");ui.monospace(&insn.operands);}});ui.separator();let Some(d) = insn.detail.as_ref() else {- ui.weak("No structured detail — enable Detail in the Listing toolbar and Apply.");+ ui.weak("No structured detail — enable Detail in the Listing toolbar and Apply.");return;};if !d.groups.is_empty() {- ui.label("Groups:");+ ui.label("Groups:");let g: Vec<String> = d.groups.iter().map(|gid| {group_name(arch, *gid).map(String::from)- .unwrap_or_else(|| format!("{:?}", gid))+ .unwrap_or_else(|| format!("{:?}", gid))}).collect();- ui.monospace(g.join(", "));+ ui.monospace(g.join(", "));}if !d.regs_read.is_empty() || !d.implicit_read.is_empty() {- ui.label("Regs read:");+ ui.label("Regs read:");ui.monospace(format_regs(arch, &d.regs_read, &d.implicit_read));}if !d.regs_write.is_empty() || !d.implicit_write.is_empty() {- ui.label("Regs write:");+ ui.label("Regs write:");ui.monospace(format_regs(arch, &d.regs_write, &d.implicit_write));}if !d.operands.is_empty() {ui.separator();- ui.label("Typed operands:");- egui::Grid::new("insn_detail_ops")+ ui.label("Typed operands:");+ egui::Grid::new("insn_detail_ops").num_columns(2).striped(true).show(ui, |ui| {- ui.strong("#");- ui.strong("Operand");+ ui.strong("#");+ ui.strong("Operand");ui.end_row();for (i, op) in d.operands.iter().enumerate() {- ui.label(format!("{i}"));+ ui.label(format!("{i}"));ui.monospace(format_operand(arch, op));ui.end_row();}@@ -71,7 +71,11 @@ pub fn ui_detail_pane(ui: &mut egui::Ui, insn: &Instruction, arch: Arch) {}}-fn format_regs(arch: Arch, explicit: &[ghidrust_core::RegId], implicit: &[ghidrust_core::RegId]) -> String {+fn format_regs(+ arch: Arch,+ explicit: &[ghidrust_core::RegId],+ implicit: &[ghidrust_core::RegId],+) -> String {let mut parts: Vec<String> = explicit.iter().map(|r| reg_label(arch, *r, false))@@ -79,15 +83,15 @@ fn format_regs(arch: Arch, explicit: &[ghidrust_core::RegId], implicit: &[ghidrufor r in implicit {parts.push(reg_label(arch, *r, true));}- parts.join(", ")+ parts.join(", ")}fn reg_label(arch: Arch, reg: ghidrust_core::RegId, implicit: bool) -> String {let name = reg_name(arch, reg).map(String::from)- .unwrap_or_else(|| format!("r{}", reg.0));+ .unwrap_or_else(|| format!("r{}", reg.0));if implicit {- format!("{name}*")+ format!("{name}*")} else {name}@@ -96,7 +100,7 @@ fn reg_label(arch: Arch, reg: ghidrust_core::RegId, implicit: bool) -> String {fn format_operand(arch: Arch, op: &Operand) -> String {match op {Operand::Reg(r) => reg_label(arch, *r, false),- Operand::Imm { value, size } => format!("imm {value} (size {size})"),+ Operand::Imm { value, size } => format!("imm {value} (size {size})"),Operand::Mem {base,index,@@ -105,50 +109,50 @@ fn format_operand(arch: Arch, op: &Operand) -> String {segment,size,} => {- let base_s = reg_name(arch, *base).unwrap_or("—");+ let base_s = reg_name(arch, *base).unwrap_or("—");let idx_s = if index.0 != 0 {- reg_name(arch, *index).unwrap_or("—")+ reg_name(arch, *index).unwrap_or("—")} else {- ""+ ""};let seg_s = if segment.0 != 0 {- reg_name(arch, *segment).unwrap_or("—")+ reg_name(arch, *segment).unwrap_or("—")} else {- ""+ ""};format!(- "mem [{seg}{base}{idx}{scale}{disp}] size={size}",+ "mem [{seg}{base}{idx}{scale}{disp}] size={size}",seg = if seg_s.is_empty() {String::new()} else {- format!("{seg_s}:")+ format!("{seg_s}:")},base = base_s,idx = if idx_s.is_empty() {String::new()} else {- format!("+{idx_s}*{scale}")+ format!("+{idx_s}*{scale}")},- scale = if idx_s.is_empty() { "" } else { "" },+ scale = if idx_s.is_empty() { "" } else { "" },disp = if *disp != 0 {- format!("{disp:+}")+ format!("{disp:+}")} else {String::new()},)}- Operand::Fp => "fp".into(),- Operand::Invalid => "invalid".into(),+ Operand::Fp => "fp".into(),+ Operand::Invalid => "invalid".into(),}}#[allow(dead_code)]pub fn operand_type_label(op: &Operand) -> &'static str {match op.op_type() {- OpType::Reg => "reg",- OpType::Imm => "imm",- OpType::Mem => "mem",- OpType::Fp => "fp",- OpType::Invalid => "invalid",+ OpType::Reg => "reg",+ OpType::Imm => "imm",+ OpType::Mem => "mem",+ OpType::Fp => "fp",+ OpType::Invalid => "invalid",}}diff --git a/crates/ghidrust-gui/src/listing/disasm_service.rs b/crates/ghidrust-gui/src/listing/disasm_service.rsindex 6718d43..7540bcf 100644--- a/crates/ghidrust-gui/src/listing/disasm_service.rs+++ b/crates/ghidrust-gui/src/listing/disasm_service.rs@@ -35,7 +35,11 @@ pub fn default_start_va(prog: &Program, focus: Option<u64>) -> u64 {pub const GOTO_MAX_INSNS: usize = 64;/// Reload helper tuned for go-to navigation (smaller window).-pub fn reload_for_goto(prog: &Program, va: u64, opts: &DecodeUiOpts) -> Result<Vec<ghidrust_core::Instruction>, String> {+pub fn reload_for_goto(+ prog: &Program,+ va: u64,+ opts: &DecodeUiOpts,+) -> Result<Vec<ghidrust_core::Instruction>, String> {let mut nav_opts = opts.clone();nav_opts.max_insns = GOTO_MAX_INSNS;nav_opts.walk_mode = WalkMode::Bounded;diff --git a/crates/ghidrust-gui/src/listing/model.rs b/crates/ghidrust-gui/src/listing/model.rsindex d313998..143a68a 100644--- a/crates/ghidrust-gui/src/listing/model.rs+++ b/crates/ghidrust-gui/src/listing/model.rs@@ -1,7 +1,8 @@//! Decode listing row model and UI options.use ghidrust_core::{- arch_mode_for_program, default_arch_mode, ghidrust_decode::{group_name, reg_name},+ arch_mode_for_program, default_arch_mode,+ ghidrust_decode::{group_name, reg_name},Arch, DisasmEngineOpts, DisasmMode, InsnId, Instruction, Mode, Program, Syntax,};use serde::{Deserialize, Serialize};@@ -19,11 +20,11 @@ pub enum WalkMode {impl WalkMode {pub const ALL: [WalkMode; 3] = [WalkMode::Bounded, WalkMode::Flow, WalkMode::Linear];- pub const fn label(self) -> &'static str {+ pub const fn label(self) -> &'static str {match self {- WalkMode::Bounded => "Bounded",- WalkMode::Flow => "Flow",- WalkMode::Linear => "Linear",+ WalkMode::Bounded => "Bounded",+ WalkMode::Flow => "Flow",+ WalkMode::Linear => "Linear",}}@@ -39,11 +40,11 @@ impl WalkMode {/// decode options surfaced in the Listing toolbar / options dialog.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct DecodeUiOpts {- #[serde(default, skip_serializing_if = "Option::is_none")]+ #[serde(default, skip_serializing_if = "Option::is_none")]pub arch: Option<String>,- #[serde(default, skip_serializing_if = "Option::is_none")]+ #[serde(default, skip_serializing_if = "Option::is_none")]pub mode: Option<u32>,- #[serde(default, skip_serializing_if = "Option::is_none")]+ #[serde(default, skip_serializing_if = "Option::is_none")]pub syntax: Option<String>,#[serde(default)]pub detail: bool,@@ -57,15 +58,15 @@ pub struct DecodeUiOpts {pub unsigned_imm: bool,#[serde(default)]pub only_offset_branch: bool,- #[serde(default, skip_serializing_if = "Option::is_none")]+ #[serde(default, skip_serializing_if = "Option::is_none")]pub litbase: Option<u32>,- #[serde(default, skip_serializing_if = "Vec::is_empty")]+ #[serde(default, skip_serializing_if = "Vec::is_empty")]pub mnem_overrides: Vec<(u32, String)>,#[serde(default)]pub walk_mode: WalkMode,- #[serde(default = "default_skip_bad")]+ #[serde(default = "default_skip_bad")]pub skip_bad: bool,- #[serde(default = "default_max_insns")]+ #[serde(default = "default_max_insns")]pub max_insns: usize,}@@ -86,7 +87,7 @@ impl Default for DecodeUiOpts {detail: true,detail_real: false,skipdata: false,- skipdata_mnemonic: ".byte".into(),+ skipdata_mnemonic: ".byte".into(),unsigned_imm: false,only_offset_branch: false,litbase: None,@@ -99,7 +100,7 @@ impl Default for DecodeUiOpts {}impl DecodeUiOpts {- /// Seed arch/mode from the loaded image when unset.+ /// Seed arch/mode from the loaded image when unset.pub fn sync_machine_from_program(&mut self, prog: &Program) {if self.arch.is_none() || self.mode.is_none() {let (arch, mode) = arch_mode_for_program(prog).unwrap_or_else(default_arch_mode);@@ -174,29 +175,17 @@ pub struct ListingRow {}impl ListingRow {- pub fn from_insn(- idx: usize,- insn: &Instruction,- prog: Option<&Program>,- arch: Arch,- ) -> Self {+ pub fn from_insn(idx: usize, insn: &Instruction, prog: Option<&Program>, arch: Arch) -> Self {let bytes_hex: String = insn.bytes.iter().take(6)- .map(|b| format!("{b:02x}"))+ .map(|b| format!("{b:02x}")).collect::<Vec<_>>()- .join(" ");+ .join(" ");let (groups_summary, regs_rw) = detail_summaries(insn, arch);- let (- applied_type,- comment_eol,- comment_plate,- comment_pre,- comment_post,- comment_repeat,- ) = prog- .map(|p| {+ let (applied_type, comment_eol, comment_plate, comment_pre, comment_post, comment_repeat) =+ prog.map(|p| {use ghidrust_core::CommentKind;(p.edits.applied_type_at(insn.address).map(String::from),@@ -219,10 +208,10 @@ impl ListingRow {}).unwrap_or((None, None, None, None, None, None));let mnem = insn.mnemonic.clone();- let is_ret = matches!(mnem.as_str(), "ret" | "retn" | "retf" | "retq");- let is_uncond = matches!(mnem.as_str(), "jmp" | "jmpq");- let is_cond = mnem.starts_with('j') && !is_uncond && mnem != "jmp";- let is_call = matches!(mnem.as_str(), "call" | "callq");+ let is_ret = matches!(mnem.as_str(), "ret" | "retn" | "retf" | "retq");+ let is_uncond = matches!(mnem.as_str(), "jmp" | "jmpq");+ let is_cond = mnem.starts_with('j') && !is_uncond && mnem != "jmp";+ let is_call = matches!(mnem.as_str(), "call" | "callq");Self {idx,va: insn.address,@@ -274,9 +263,9 @@ pub fn detail_summaries(insn: &Instruction, arch: Arch) -> (String, String) {let regs_rw = if read.is_empty() && write.is_empty() {String::new()} else {- format!("R:[{}] W:[{}]", read.join(","), write.join(","))+ format!("R:[{}] W:[{}]", read.join(","), write.join(","))};- (groups.join(","), regs_rw)+ (groups.join(","), regs_rw)}pub fn parse_arch_name(s: &str) -> Option<Arch> {@@ -287,17 +276,17 @@ pub fn parse_arch_name(s: &str) -> Option<Arch> {pub fn parse_syntax_name(s: &str) -> Option<Syntax> {match s.trim().to_ascii_lowercase().as_str() {- "default" => Some(Syntax::Default),- "intel" => Some(Syntax::Intel),- "att" => Some(Syntax::Att),- "noregname" | "no_reg_name" => Some(Syntax::NoRegName),- "masm" => Some(Syntax::Masm),- "motorola" => Some(Syntax::Motorola),- "cs_reg_alias" | "reg_alias" => Some(Syntax::CsRegAlias),- "percent" => Some(Syntax::Percent),- "no_dollar" | "nodollar" => Some(Syntax::NoDollar),- "no_alias_text" => Some(Syntax::NoAliasText),- "no_alias_text_compressed" => Some(Syntax::NoAliasTextCompressed),+ "default" => Some(Syntax::Default),+ "intel" => Some(Syntax::Intel),+ "att" => Some(Syntax::Att),+ "noregname" | "no_reg_name" => Some(Syntax::NoRegName),+ "masm" => Some(Syntax::Masm),+ "motorola" => Some(Syntax::Motorola),+ "cs_reg_alias" | "reg_alias" => Some(Syntax::CsRegAlias),+ "percent" => Some(Syntax::Percent),+ "no_dollar" | "nodollar" => Some(Syntax::NoDollar),+ "no_alias_text" => Some(Syntax::NoAliasText),+ "no_alias_text_compressed" => Some(Syntax::NoAliasTextCompressed),_ => None,}}@@ -308,17 +297,17 @@ pub fn syntax_storage(s: Syntax) -> String {pub fn syntax_label(s: Syntax) -> &'static str {match s {- Syntax::Default => "Default",- Syntax::Intel => "Intel",- Syntax::Att => "ATT",- Syntax::NoRegName => "NoRegName",- Syntax::Masm => "MASM",- Syntax::Motorola => "Motorola",- Syntax::CsRegAlias => "CsRegAlias",- Syntax::Percent => "Percent",- Syntax::NoDollar => "NoDollar",- Syntax::NoAliasText => "NoAliasText",- Syntax::NoAliasTextCompressed => "NoAliasTextCompressed",+ Syntax::Default => "Default",+ Syntax::Intel => "Intel",+ Syntax::Att => "ATT",+ Syntax::NoRegName => "NoRegName",+ Syntax::Masm => "MASM",+ Syntax::Motorola => "Motorola",+ Syntax::CsRegAlias => "CsRegAlias",+ Syntax::Percent => "Percent",+ Syntax::NoDollar => "NoDollar",+ Syntax::NoAliasText => "NoAliasText",+ Syntax::NoAliasTextCompressed => "NoAliasTextCompressed",}}diff --git a/crates/ghidrust-gui/src/listing/options.rs b/crates/ghidrust-gui/src/listing/options.rsindex aab533b..17253f4 100644--- a/crates/ghidrust-gui/src/listing/options.rs+++ b/crates/ghidrust-gui/src/listing/options.rs@@ -15,40 +15,37 @@ pub fn ui_options_dialog(}let mut apply = false;let mut close = false;- egui::Window::new("Decode Options")+ egui::Window::new("Decode Options").collapsible(false).resizable(true).default_width(480.0).show(ctx, |ui| {ui_processor_selectors(ui, opts, prog);ui.separator();- ui.checkbox(&mut opts.detail_real, "Detail real (arch-specific fields)");- ui.checkbox(&mut opts.unsigned_imm, "Unsigned immediates");- ui.checkbox(&mut opts.only_offset_branch, "Only offset branch targets");- ui.checkbox(&mut opts.skip_bad, "Skip bad bytes (listing continuity)");+ ui.checkbox(&mut opts.detail_real, "Detail real (arch-specific fields)");+ ui.checkbox(&mut opts.unsigned_imm, "Unsigned immediates");+ ui.checkbox(&mut opts.only_offset_branch, "Only offset branch targets");+ ui.checkbox(&mut opts.skip_bad, "Skip bad bytes (listing continuity)");ui.horizontal(|ui| {- ui.label("Skipdata mnemonic:");+ ui.label("Skipdata mnemonic:");ui.text_edit_singleline(&mut opts.skipdata_mnemonic);});ui.horizontal(|ui| {- ui.label("Litbase:");+ ui.label("Litbase:");let mut lit = opts.litbase.unwrap_or(0);if ui.add(egui::DragValue::new(&mut lit).speed(1)).changed() {opts.litbase = Some(lit);}- if ui.small_button("Clear").clicked() {+ if ui.small_button("Clear").clicked() {opts.litbase = None;}});ui.horizontal(|ui| {- ui.label("Max insns:");- ui.add(- egui::DragValue::new(&mut opts.max_insns)- .range(8..=4096),- );+ ui.label("Max insns:");+ ui.add(egui::DragValue::new(&mut opts.max_insns).range(8..=4096));});ui.separator();- ui.label("Mnemonic overrides (id:mnemonic per line):");+ ui.label("Mnemonic overrides (id:mnemonic per line):");let mut text = overrides_to_text(&opts.mnem_overrides);if ui.add(@@ -62,26 +59,26 @@ pub fn ui_options_dialog(}ui.separator();ui.horizontal(|ui| {- if ui.button("Apply").clicked() {+ if ui.button("Apply").clicked() {apply = true;close = true;}- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {close = true;}});});if close {- *open = false;+ *open = false;}apply}fn overrides_to_text(list: &[(u32, String)]) -> String {list.iter()- .map(|(id, m)| format!("{id}:{m}"))+ .map(|(id, m)| format!("{id}:{m}")).collect::<Vec<_>>()- .join("\n")+ .join("\n")}fn parse_overrides(text: &str) -> Vec<(u32, String)> {@@ -91,7 +88,7 @@ fn parse_overrides(text: &str) -> Vec<(u32, String)> {if line.is_empty() {return None;}- let (id_s, mnem) = line.split_once(':')?;+ let (id_s, mnem) = line.split_once(':')?;let id = id_s.trim().parse().ok()?;Some((id, mnem.trim().to_string()))})diff --git a/crates/ghidrust-gui/src/listing/processor.rs b/crates/ghidrust-gui/src/listing/processor.rsindex 2b86204..a2b77d1 100644--- a/crates/ghidrust-gui/src/listing/processor.rs+++ b/crates/ghidrust-gui/src/listing/processor.rs@@ -1,58 +1,50 @@//! Architecture + mode selectors from `Engine::support` / `Arch::ALL`.use super::model::{parse_arch_name, DecodeUiOpts};-use ghidrust_core::{default_arch_mode, arch_mode_for_program, Arch, Engine, Mode, Program, SupportQuery};+use ghidrust_core::{+ arch_mode_for_program, default_arch_mode, Arch, Engine, Mode, Program, SupportQuery,+};/// Common mode presets per architecture (not exhaustive — raw bits also editable).pub fn mode_presets(arch: Arch) -> &'static [(&'static str, Mode)] {match arch {Arch::X86 => &[- ("16", Mode::MODE_16),- ("32", Mode::MODE_32),- ("64", Mode::MODE_64),+ ("16", Mode::MODE_16),+ ("32", Mode::MODE_32),+ ("64", Mode::MODE_64),],Arch::Arm => &[- ("ARM", Mode::ARM),- ("Thumb", Mode::THUMB),- ("M-class", Mode::MCLASS),+ ("ARM", Mode::ARM),+ ("Thumb", Mode::THUMB),+ ("M-class", Mode::MCLASS),],- Arch::Arm64 => &[("LE", Mode::LITTLE_ENDIAN), ("V8", Mode::V8)],- Arch::Mips => &[- ("MIPS32", Mode::MIPS32),- ("MIPS64", Mode::MIPS64),- ],- Arch::Ppc => &[("PPC32", Mode::PPC32), ("PPC64", Mode::PPC64)],+ Arch::Arm64 => &[("LE", Mode::LITTLE_ENDIAN), ("V8", Mode::V8)],+ Arch::Mips => &[("MIPS32", Mode::MIPS32), ("MIPS64", Mode::MIPS64)],+ Arch::Ppc => &[("PPC32", Mode::PPC32), ("PPC64", Mode::PPC64)],Arch::Riscv => &[- ("RV32", Mode::RISCV32),- ("RV64", Mode::RISCV64),- ("+C", Mode::RISCV_C),+ ("RV32", Mode::RISCV32),+ ("RV64", Mode::RISCV64),+ ("+C", Mode::RISCV_C),],Arch::Bpf => &[- ("Classic", Mode::BPF_CLASSIC),- ("Extended", Mode::BPF_EXTENDED),- ],- Arch::Mos65xx => &[- ("6502", Mode::MOS65XX_6502),- ("65C02", Mode::MOS65XX_65C02),+ ("Classic", Mode::BPF_CLASSIC),+ ("Extended", Mode::BPF_EXTENDED),],- _ => &[("LE", Mode::LITTLE_ENDIAN), ("BE", Mode::BIG_ENDIAN)],+ Arch::Mos65xx => &[("6502", Mode::MOS65XX_6502), ("65C02", Mode::MOS65XX_65C02)],+ _ => &[("LE", Mode::LITTLE_ENDIAN), ("BE", Mode::BIG_ENDIAN)],}}-pub fn ui_processor_selectors(- ui: &mut egui::Ui,- opts: &mut DecodeUiOpts,- prog: Option<&Program>,-) {+pub fn ui_processor_selectors(ui: &mut egui::Ui, opts: &mut DecodeUiOpts, prog: Option<&Program>) {if let Some(p) = prog {opts.sync_machine_from_program(p);}- ui.label("Architecture:");+ ui.label("Architecture:");let cur_arch = opts.resolved_arch().or_else(|| prog.and_then(arch_mode_for_program).map(|(a, _)| a)).unwrap_or_else(|| default_arch_mode().0);- egui::ComboBox::from_id_salt("decode_arch")+ egui::ComboBox::from_id_salt("decode_arch").selected_text(cur_arch.name()).show_ui(ui, |ui| {for arch in Arch::ALL {@@ -69,14 +61,14 @@ pub fn ui_processor_selectors(}});- ui.label("Mode:");+ ui.label("Mode:");let arch = opts.resolved_arch().unwrap_or(cur_arch);let cur_mode = opts.resolved_mode().unwrap_or_else(|| {prog.and_then(arch_mode_for_program).map(|(_, m)| m).unwrap_or_else(|| default_arch_mode().1)});- egui::ComboBox::from_id_salt("decode_mode")+ egui::ComboBox::from_id_salt("decode_mode").selected_text(format_mode(cur_mode)).show_ui(ui, |ui| {for (label, mode) in mode_presets(arch) {@@ -92,12 +84,9 @@ pub fn ui_processor_selectors(}ui.separator();ui.horizontal(|ui| {- ui.label("Raw bits:");+ ui.label("Raw bits:");let mut bits = cur_mode.bits();- if ui- .add(egui::DragValue::new(&mut bits).speed(1))- .changed()- {+ if ui.add(egui::DragValue::new(&mut bits).speed(1)).changed() {opts.mode = Some(bits);}});@@ -108,12 +97,15 @@ pub fn ui_processor_selectors(if !supported {ui.colored_label(egui::Color32::from_rgb(0xE5, 0x39, 0x35),- format!("Architecture {} is not supported by the decode engine.", name.name()),+ format!(+ "Architecture {} is not supported by the decode engine.",+ name.name()+ ),);}}}fn format_mode(mode: Mode) -> String {- format!("0x{:x}", mode.bits())+ format!("0x{:x}", mode.bits())}diff --git a/crates/ghidrust-gui/src/listing/search.rs b/crates/ghidrust-gui/src/listing/search.rsindex 30b4409..4cd1646 100644--- a/crates/ghidrust-gui/src/listing/search.rs+++ b/crates/ghidrust-gui/src/listing/search.rs@@ -40,11 +40,9 @@ pub fn matches(insn: &Instruction, search: &ListingSearch) -> bool {}if !search.insn_id.trim().is_empty() {let q = search.insn_id.trim();- let id_s = format!("{}", insn.id.raw());- let name = insn_name(search.arch, insn.id).unwrap_or("");- if !id_s.contains(q)- && !name.to_ascii_lowercase().contains(&q.to_ascii_lowercase())- {+ let id_s = format!("{}", insn.id.raw());+ let name = insn_name(search.arch, insn.id).unwrap_or("");+ if !id_s.contains(q) && !name.to_ascii_lowercase().contains(&q.to_ascii_lowercase()) {return false;}}@@ -55,7 +53,7 @@ pub fn matches(insn: &Instruction, search: &ListingSearch) -> bool {};let hit = d.groups.iter().any(|g| {group_name(search.arch, *g)- .unwrap_or("")+ .unwrap_or("").to_ascii_lowercase().contains(&q)});@@ -68,24 +66,24 @@ pub fn matches(insn: &Instruction, search: &ListingSearch) -> bool {pub fn ui_search_bar(ui: &mut egui::Ui, search: &mut ListingSearch) {ui.horizontal(|ui| {- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut search.mnemonic).desired_width(90.0)- .hint_text("mnemonic"),+ .hint_text("mnemonic"),);ui.add(egui::TextEdit::singleline(&mut search.insn_id).desired_width(70.0)- .hint_text("id"),+ .hint_text("id"),);ui.add(egui::TextEdit::singleline(&mut search.group).desired_width(90.0)- .hint_text("group"),+ .hint_text("group"),);- if search.is_active() && ui.small_button("Clear").clicked() {- *search = ListingSearch::default();+ if search.is_active() && ui.small_button("Clear").clicked() {+ *search = ListingSearch::default();}});}diff --git a/crates/ghidrust-gui/src/listing/toolbar.rs b/crates/ghidrust-gui/src/listing/toolbar.rsindex de3d940..baa0ef9 100644--- a/crates/ghidrust-gui/src/listing/toolbar.rs+++ b/crates/ghidrust-gui/src/listing/toolbar.rs@@ -1,6 +1,6 @@//! Listing toolbar: syntax, detail, skipdata, walk mode, apply.-use super::model::{syntax_label, syntax_storage, DecodeUiOpts, SYNTAX_VARIANTS, WalkMode};+use super::model::{syntax_label, syntax_storage, DecodeUiOpts, WalkMode, SYNTAX_VARIANTS};use ghidrust_core::Syntax;#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -17,11 +17,9 @@ pub fn ui_toolbar() -> ToolbarAction {let mut action = ToolbarAction::None;ui.horizontal(|ui| {- ui.label("Syntax:");- let cur_syntax = opts- .resolved_syntax()- .unwrap_or(Syntax::Default);- egui::ComboBox::from_id_salt("listing_syntax")+ ui.label("Syntax:");+ let cur_syntax = opts.resolved_syntax().unwrap_or(Syntax::Default);+ egui::ComboBox::from_id_salt("listing_syntax").selected_text(syntax_label(cur_syntax)).show_ui(ui, |ui| {for s in SYNTAX_VARIANTS {@@ -33,21 +31,21 @@ pub fn ui_toolbar(});ui.separator();- ui.checkbox(&mut opts.detail, "Detail");- ui.checkbox(&mut opts.skipdata, "Skipdata");+ ui.checkbox(&mut opts.detail, "Detail");+ ui.checkbox(&mut opts.skipdata, "Skipdata");ui.separator();- ui.label("Walk:");+ ui.label("Walk:");for mode in WalkMode::ALL {ui.selectable_value(&mut opts.walk_mode, mode, mode.label());}ui.separator();- if ui.button("Options…").clicked() {- *open_options = true;+ if ui.button("Options…").clicked() {+ *open_options = true;action = ToolbarAction::OpenOptions;}- if ui.button("Apply").clicked() {+ if ui.button("Apply").clicked() {action = ToolbarAction::Apply;}});diff --git a/crates/ghidrust-gui/src/main.rs b/crates/ghidrust-gui/src/main.rsindex 2ae2723..c34c5e8 100644--- a/crates/ghidrust-gui/src/main.rs+++ b/crates/ghidrust-gui/src/main.rs@@ -4,6 +4,7 @@mod agent_pane;mod debugger;mod decomp_tokens;+mod decrypt_ui;mod dock_tabs;mod entropy;mod events;@@ -19,39 +20,41 @@ mod register_manager;mod scripts;mod tool_panes;+use debugger::{DebuggerAction, DebuggerPane, DebuggerState};+use decomp_tokens::{+ emit_token_triples, from_emit_tokens, line_for_va as decomp_line_for_va,+ tokenize as tokenize_decomp, DecompLine, TokenKind,+};+use decrypt_ui::{DecryptPaneState, DecryptTab};use dock_tabs::DockTab;use eframe::egui::{self, Color32, Visuals};use egui_dock::{DockArea, DockState, Style as DockStyle, TabViewer};+use events::{EventBus, EventSource, GhidrustEvent, MutationKind};use ghidrust_core::{analyzer_catalog, analyzer_supports_gpu, arch_mode_for_program, default_arch_mode,- disassemble_at_opts, load_path, m3_tokens,- set_preferred_bulk_mode, xrefs_from, xrefs_to, AnalysisRunReport, AnalyzerInfo, AnalyzerOutput,- BulkScanMode, CommentKind, FoundString, Instruction, Program, Project, ProjectTreeModel,- RttiReport, ThemeMode, XRef, Arch, BUILTIN_TYPES,+ disassemble_at_opts, load_path, m3_tokens, recover_obfuscated_strings, set_preferred_bulk_mode,+ xrefs_from, xrefs_to, AnalysisRunReport, AnalyzerInfo, AnalyzerOutput, Arch, BulkScanMode,+ CommentKind, CryptConstantHit, CryptoCapabilityHit, FoundString, Instruction,+ ObfuscatedStringHit, Program, Project, ProjectTreeModel, RecoverStringsOpts, RttiReport,+ ThemeMode, XRef, BUILTIN_TYPES,};-use listing::{- default_start_va, listing_matches, reload, reload_for_goto, ui_detail_pane, ui_options_dialog,- ui_search_bar, ui_toolbar, DecodeUiOpts, ListingRow, ListingSearch, ToolbarAction,- load_decode_prefs, save_decode_prefs,+use graphs::{+ build_incoming_tree, build_outgoing_tree, data_xrefs_to, expand_tree_node, layout_call_graph,+ layout_function_graph, render_call_graph, render_function_graph, CallTreeNode,+ FunctionGraphLayout, GraphPaneState,};use icons::{m3_icon, m3_linear_progress, status_badge, M3Icon};+use listing::{+ default_start_va, listing_matches, load_decode_prefs, reload, reload_for_goto,+ save_decode_prefs, ui_detail_pane, ui_options_dialog, ui_search_bar, ui_toolbar, DecodeUiOpts,+ ListingRow, ListingSearch, ToolbarAction,+};use menu_actions::{address_table_hits, decompile_entry_for_va, listing_index_at_or_before, parse_address,parse_hex_pattern, processor_info, pseudo_c_for_stage, search_instruction_patterns,- stage1_pseudo_c_with_tokens,- search_memory, search_program_text, search_scalars, stage0_pseudo_c, DecompStage,- ListingSelection, MemoryHit, TextHit, STAGE0_MAX_INSNS,-};-use decomp_tokens::{- emit_token_triples, from_emit_tokens, line_for_va as decomp_line_for_va,- tokenize as tokenize_decomp, DecompLine, TokenKind,-};-use debugger::{DebuggerAction, DebuggerPane, DebuggerState};-use events::{EventBus, EventSource, GhidrustEvent, MutationKind};-use graphs::{- build_incoming_tree, build_outgoing_tree, data_xrefs_to, expand_tree_node, layout_call_graph,- layout_function_graph, render_call_graph, render_function_graph, CallTreeNode,- FunctionGraphLayout, GraphPaneState,+ search_memory, search_program_text, search_scalars, stage0_pseudo_c,+ stage1_pseudo_c_with_tokens, DecompStage, ListingSelection, MemoryHit, TextHit,+ STAGE0_MAX_INSNS,};use nav::{NavHistory, NavLocation};use panes::{Bookmark, BookmarkKind, PaneKind};@@ -81,7 +84,7 @@ fn render_pseudo_c_inline(ui: &mut egui::Ui, body: &str) {italics: italic,..Default::default()};- // Preserve original whitespace / newlines faithfully.+ // Preserve original whitespace / newlines faithfully.if matches!(tok.kind, TokenKind::Comment) {fmt.italics = true;}@@ -100,19 +103,19 @@ fn render_pseudo_c_inline(ui: &mut egui::Ui, body: &str) {fn load_skill_body() -> (String, Option<PathBuf>) {let candidates: Vec<PathBuf> = {let mut v = Vec::new();- // 1. Adjacent to the running binary (production layout).+ // 1. Adjacent to the running binary (production layout).if let Ok(exe) = std::env::current_exe() {if let Some(dir) = exe.parent() {- v.push(dir.join("skill").join("SKILL.md"));+ v.push(dir.join("skill").join("SKILL.md"));if let Some(root) = dir.parent() {- v.push(root.join("skill").join("SKILL.md"));+ v.push(root.join("skill").join("SKILL.md"));}}}- // 2. Workspace-local (development layout — cargo run from repo root).+ // 2. Workspace-local (development layout — cargo run from repo root).if let Ok(cwd) = std::env::current_dir() {- v.push(cwd.join("skill").join("SKILL.md"));- v.push(cwd.join(".").join("skill").join("SKILL.md"));+ v.push(cwd.join("skill").join("SKILL.md"));+ v.push(cwd.join(".").join("skill").join("SKILL.md"));}v};@@ -125,15 +128,17 @@ fn load_skill_body() -> (String, Option<PathBuf>) {}fn recent_projects_path() -> PathBuf {- // %APPDATA%/ghidrust/recent_projects.txt (or home fallback)- if let Ok(appdata) = std::env::var("APPDATA") {- PathBuf::from(appdata).join("ghidrust").join("recent_projects.txt")- } else if let Ok(home) = std::env::var("USERPROFILE") {+ // %APPDATA%/ghidrust/recent_projects.txt (or home fallback)+ if let Ok(appdata) = std::env::var("APPDATA") {+ PathBuf::from(appdata)+ .join("ghidrust")+ .join("recent_projects.txt")+ } else if let Ok(home) = std::env::var("USERPROFILE") {PathBuf::from(home)- .join(".ghidrust")- .join("recent_projects.txt")+ .join(".ghidrust")+ .join("recent_projects.txt")} else {- PathBuf::from("ghidrust_recent_projects.txt")+ PathBuf::from("ghidrust_recent_projects.txt")}}@@ -154,21 +159,21 @@ fn save_recent_projects(paths: &[String]) {if let Some(parent) = p.parent() {let _ = std::fs::create_dir_all(parent);}- let _ = std::fs::write(p, paths.join("\n"));+ let _ = std::fs::write(p, paths.join("\n"));}/// Messages from the background analysis worker → UI thread (polled each frame).enum AnalysisWorkerMsg {- /// Analyzer at `index` is about to run.+ /// Analyzer at `index` is about to run.StepStarted { index: usize },- /// Analyzer at `index` finished; `outputs` are that step's report rows.+ /// Analyzer at `index` finished; `outputs` are that step's report rows.StepFinished {index: usize,outputs: Vec<AnalyzerOutput>,},- /// All selected analyzers finished; return mutated program to the UI.+ /// All selected analyzers finished; return mutated program to the UI.Done { program: Program },- /// Hard failure; program is returned so the UI can restore it (may include partial work).+ /// Hard failure; program is returned so the UI can restore it (may include partial work).Failed { error: String, program: Program },}@@ -183,7 +188,7 @@ struct AnalysisJob {}fn main() -> eframe::Result<()> {- let title = format!("Ghidrust {} CodeBrowser", env!("CARGO_PKG_VERSION"));+ let title = format!("Ghidrust {} CodeBrowser", env!("CARGO_PKG_VERSION"));let opts = eframe::NativeOptions {viewport: egui::ViewportBuilder::default().with_inner_size([1280.0, 800.0])@@ -201,7 +206,7 @@ fn main() -> eframe::Result<()> {/// The live layout is `center_dock` (`egui_dock`).#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum CenterPane {- /// File summary + analysis counts (default after open/analyze).+ /// File summary + analysis counts (default after open/analyze).Overview,Listing,Decompiler,@@ -232,7 +237,7 @@ impl From<CenterPane> for DockTab {/// Renders center dock tabs by forwarding into `GhidrustApp` pane UIs.struct CenterTabViewer<'a> {- app: &'a mut GhidrustApp,+ app: &'a mut GhidrustApp,}impl TabViewer for CenterTabViewer<'_> {@@ -266,48 +271,53 @@ pub struct GhidrustApp {listing: Vec<Instruction>,rtti: RttiReport,strings: Vec<FoundString>,+ crypt_constants: Vec<CryptConstantHit>,+ crypto_constants_focus_va: Option<u64>,+ obfuscated_strings: Vec<ObfuscatedStringHit>,+ crypto_capabilities: Vec<CryptoCapabilityHit>,+ decrypt_pane: DecryptPaneState,last_analysis: AnalysisRunReport,last_analyzers_run: Vec<String>,analyzer_enabled: Vec<bool>,analyzer_infos: Vec<AnalyzerInfo>,- /// Legacy focused-center shim (synced from `center_dock`).+ /// Legacy focused-center shim (synced from `center_dock`).center: CenterPane,- /// IDE-style dock tree for Listing / Overview / Decompiler / DTM.+ /// IDE-style dock tree for Listing / Overview / Decompiler / DTM.center_dock: DockState<DockTab>,show_project_tree: bool,show_program_tree: bool,show_symbol_tree: bool,show_console: bool,- /// Bottom dock (Grok/Console/Raw) height in points. Owned by us so the- /// top-edge drag grip can resize reliably — egui's built-in- /// `TopBottomPanel::resizable` snaps back unless content expands, which- /// is easy to get wrong across versions.+ /// Bottom dock (Grok/Console/Raw) height in points. Owned by us so the+ /// top-edge drag grip can resize reliably — egui's built-in+ /// `TopBottomPanel::resizable` snaps back unless content expands, which+ /// is easy to get wrong across versions.console_height: f32,show_analysis_dialog: bool,- /// Use experimental GPU bulk path for string/byte scan analyzers.+ /// Use experimental GPU bulk path for string/byte scan analyzers.use_gpu_experimental: bool,- /// File id to open when user confirms analysis dialog (from Project Tree).+ /// File id to open when user confirms analysis dialog (from Project Tree).pending_analyze_file_id: Option<String>,- /// Live analysis job (progress UI while stepping).+ /// Live analysis job (progress UI while stepping).analysis_job: Option<AnalysisJob>,- /// Tree selection (may differ from active until Open).+ /// Tree selection (may differ from active until Open).tree_selected_id: Option<String>,project_tree_expanded: bool,- /// Pending delete: (file id, display name) — shown in confirm dialog.+ /// Pending delete: (file id, display name) — shown in confirm dialog.pending_delete: Option<(String, String)>,- /// Dismissible banner after analysis finishes.+ /// Dismissible banner after analysis finishes.analysis_done_banner: Option<String>,- /// RTTI panel filter (case-insensitive substring).+ /// RTTI panel filter (case-insensitive substring).rtti_filter: String,rtti_filter_cache: String,rtti_filtered_idx: Vec<usize>,- /// Function list filter.+ /// Function list filter.fn_filter: String,- /// First-run: pick/open a project before the empty shell.+ /// First-run: pick/open a project before the empty shell.show_startup_picker: bool,recent_projects: Vec<String>,nyi_note: Option<String>,- // ── selection / search / navigation. ──────+ // ── selection / search / navigation. ──────listing_selection: ListingSelection,undo_stack: Vec<ListingSelection>,redo_stack: Vec<ListingSelection>,@@ -323,106 +333,106 @@ pub struct GhidrustApp {memory_hits: Vec<MemoryHit>,text_hits: Vec<TextHit>,show_processor_dialog: bool,- /// Cached decompiler pseudo-C for the focused function entry (None = stale / empty).+ /// Cached decompiler pseudo-C for the focused function entry (None = stale / empty).decomp_entry: Option<u64>,decomp_text: String,decomp_status: String,- /// Which decompile stage the Decompiler pane renders (Stage-0 / 0.5 / 1).+ /// Which decompile stage the Decompiler pane renders (Stage-0 / 0.5 / 1).decomp_stage: DecompStage,- /// Last lift-coverage ratio (Stage-0.5 / Stage-1 only). Displayed as a- /// small chip in the Decompiler pane header so users know how much of- /// the emit came from real lifted IR vs Stage-0 scaffolding.+ /// Last lift-coverage ratio (Stage-0.5 / Stage-1 only). Displayed as a+ /// small chip in the Decompiler pane header so users know how much of+ /// the emit came from real lifted IR vs Stage-0 scaffolding.decomp_lift_ratio: Option<f32>,- // ── visible providers ─────────────- /// Open-state per-provider (Window menu toggles → floating egui::Window per pane).+ // ── visible providers ─────────────+ /// Open-state per-provider (Window menu toggles → floating egui::Window per pane).pane_open: BTreeMap<PaneKind, bool>,- /// (Back / Forward / Alt+Left / Alt+Right).+ /// (Back / Forward / Alt+Left / Alt+Right).nav_history: NavHistory,- /// Guard so back/forward don't re-push into the history.+ /// Guard so back/forward don't re-push into the history.nav_suspended: bool,- /// Bookmark table (5 kinds).+ /// Bookmark table (5 kinds).bookmarks: Vec<Bookmark>,- /// Filter for Bookmarks pane.+ /// Filter for Bookmarks pane.bookmark_filter: String,- /// Add-bookmark dialog state.+ /// Add-bookmark dialog state.show_bookmark_dialog: bool,bookmark_dialog_kind: BookmarkKind,bookmark_dialog_category: String,bookmark_dialog_description: String,- /// Filter for Functions window (separate from Symbol Tree filter).+ /// Filter for Functions window (separate from Symbol Tree filter).functions_window_filter: String,- /// Filter for Symbol Table window.+ /// Filter for Symbol Table window.symbol_table_filter: String,- /// Filter for Defined Strings window.+ /// Filter for Defined Strings window.defined_strings_filter: String,- /// Defined Strings encoding filter: `"all"` | `"ascii"` | `"utf16le"`.+ /// Defined Strings encoding filter: `"all"` | `"ascii"` | `"utf16le"`.defined_strings_encoding: String,- /// plugin-event bus .+ /// plugin-event bus .event_bus: EventBus,- /// tokenised decompiler cache (rebuilt after every refresh_decompiler_at).+ /// tokenised decompiler cache (rebuilt after every refresh_decompiler_at).decomp_lines: Vec<DecompLine>,- /// line index in `decomp_lines` cross-highlighted from Listing cursor.+ /// line index in `decomp_lines` cross-highlighted from Listing cursor.decomp_cross_line: Option<usize>,- /// middle-click "highlight all occurrences" state.+ /// middle-click "highlight all occurrences" state.decomp_highlight_text: Option<String>,- /// Symbol Tree ↔ Listing selection navigation toggle.+ /// Symbol Tree ↔ Listing selection navigation toggle.symbol_tree_nav: bool,- /// currently-focused function entry (for Symbol Tree highlight).+ /// currently-focused function entry (for Symbol Tree highlight).focused_function_entry: Option<u64>,- /// Program Tree fragment filter. `None` = full view; `Some({names})` = only those.+ /// Program Tree fragment filter. `None` = full view; `Some({names})` = only those.listing_view_filter: Option<BTreeSet<String>>,- /// Rename dialog state.+ /// Rename dialog state.show_rename_dialog: bool,rename_dialog_target_va: Option<u64>,rename_dialog_old_name: String,rename_dialog_new_name: String,- /// Retype dialog state.+ /// Retype dialog state.show_retype_dialog: bool,retype_dialog_target_va: Option<u64>,retype_dialog_type: String,- /// Comment dialog state.+ /// Comment dialog state.show_comment_dialog: bool,comment_dialog_target_va: Option<u64>,comment_dialog_kind: CommentKind,comment_dialog_text: String,- /// Function Signature dialog state.+ /// Function Signature dialog state.show_fn_signature_dialog: bool,fn_signature_dialog_entry: Option<u64>,fn_signature_dialog_text: String,- /// New Structure / Union / Enum dialog state.+ /// New Structure / Union / Enum dialog state.show_new_type_dialog: bool,new_type_dialog_kind: NewTypeKind,new_type_dialog_name: String,new_type_dialog_body: String,- /// Edit-existing-type dialog state (structure /- /// union / enum / typedef editor).+ /// Edit-existing-type dialog state (structure /+ /// union / enum / typedef editor).show_edit_type_dialog: bool,edit_type_dialog_orig_name: String,edit_type_dialog_name: String,edit_type_dialog_body: String,- /// Data Type Chooser dialog (`T` shortcut over Listing).+ /// Data Type Chooser dialog (`T` shortcut over Listing).show_type_chooser_dialog: bool,type_chooser_target_va: Option<u64>,type_chooser_filter: String,- /// DTM filter.+ /// DTM filter.dtm_filter: String,- /// Comment Window filters .+ /// Comment Window filters .comment_window_filter: String,comment_window_kind_filter: Option<CommentKind>,- /// Console severity per line (`Info`, `Warn`, `Error`).+ /// Console severity per line (`Info`, `Warn`, `Error`).console_severity: Vec<ConsoleSeverity>,- // ── tables & search state ────────────────────────────- /// Byte Viewer state .+ // ── tables & search state ────────────────────────────+ /// Byte Viewer state .bytes_pane_va: Option<u64>,bytes_pane_bpr: usize,bytes_pane_rows: usize,- /// Filter for Symbol References pane (name / address substring).+ /// Filter for Symbol References pane (name / address substring).symbol_refs_filter: String,- /// Symbol References focus (target VA) — set from Symbol Table row.+ /// Symbol References focus (target VA) — set from Symbol Table row.symbol_refs_target: Option<u64>,- /// Hide IL2CPP resolve-stub source rows (`ghidrust_il2cpp::is_resolve_stub_va`).+ /// Hide IL2CPP resolve-stub source rows (`ghidrust_il2cpp::is_resolve_stub_va`).symbol_refs_hide_stubs: bool,- /// Equates Table filters + edit dialog.+ /// Equates Table filters + edit dialog.equates_filter: String,equates_selected: Option<(String, i64)>,show_equate_dialog: bool,@@ -430,76 +440,76 @@ pub struct GhidrustApp {equate_dialog_op: u8,equate_dialog_name: String,equate_dialog_value: String,- /// Function Tags — new-tag input + selected tag for row highlight.+ /// Function Tags — new-tag input + selected tag for row highlight.function_tags_new_input: String,- /// External Programs filter.+ /// External Programs filter.external_programs_filter: String,- /// Data Type Preview — selected built-in for preview.+ /// Data Type Preview — selected built-in for preview.data_type_preview_selected: String,- /// Checksum Generator — cached results.+ /// Checksum Generator — cached results.checksum_last: Option<ChecksumReport>,- /// Search → For Scalars.+ /// Search → For Scalars.show_search_scalars_dialog: bool,search_scalars_min: String,search_scalars_max: String,- /// Search → Instruction Patterns.+ /// Search → Instruction Patterns.show_search_insn_dialog: bool,search_insn_mnemonic: String,search_insn_operands: String,- /// Search → For Address Tables (populated on-demand).+ /// Search → For Address Tables (populated on-demand).show_search_address_tables_dialog: bool,- /// Function Tags pane filter.+ /// Function Tags pane filter.function_tags_filter: String,- // ── Graphs & maps ────────────────────────────────────- /// Function Graph / Call Graph / Call Trees session state.+ // ── Graphs & maps ────────────────────────────────────+ /// Function Graph / Call Graph / Call Trees session state.graph_state: GraphPaneState,- /// Function Call Trees — top-level nodes (rebuilt on cursor change).+ /// Function Call Trees — top-level nodes (rebuilt on cursor change).call_tree_incoming: Vec<CallTreeNode>,call_tree_outgoing: Vec<CallTreeNode>,- /// Register Manager pane state (session-only until backend lattice lands).+ /// Register Manager pane state (session-only until backend lattice lands).register_manager: RegisterManagerState,- /// Memory Map editor — pending row edits (Add row).+ /// Memory Map editor — pending row edits (Add row).memory_map_new_name: String,memory_map_new_va: String,memory_map_new_size: String,memory_map_new_r: bool,memory_map_new_w: bool,memory_map_new_x: bool,- // ── Scripts ──────────────────────────────────────────- /// pane state.+ // ── Scripts ──────────────────────────────────────────+ /// pane state.script_manager: ScriptManagerState,- /// Text Editor multi-tab state.+ /// Text Editor multi-tab state.text_editor: TextEditorState,- /// MCP REPL state.+ /// MCP REPL state.mcp_repl: MacropadReplState,- // ── Debugger visibility ──────────────────────────────- /// Debugger tool state (tabbed host + Live Process Bridge).+ // ── Debugger visibility ──────────────────────────────+ /// Debugger tool state (tabbed host + Live Process Bridge).debugger: DebuggerState,- // ── Docking / layouts / Configure ───────────────────- /// Configure dialog .+ // ── Docking / layouts / Configure ───────────────────+ /// Configure dialog .show_configure_dialog: bool,- /// Layout preset save/load dialog state.+ /// Layout preset save/load dialog state.show_layouts_dialog: bool,layouts_new_name: String,layouts_cached: Vec<String>,- /// Current layout name (empty = unnamed / default).+ /// Current layout name (empty = unnamed / default).current_layout_name: String,- // ── Grok Build agent console (Option C: ACP sidecar) ───────────────- /// Per-window Grok pane state (session, transcript, install prompts, mode).- /// One project per window means one session at a time; skill is auto-wired- /// into `<project>/.grok/skills/` on project open; MCP/context on Start.+ // ── Grok Build agent console (Option C: ACP sidecar) ───────────────+ /// Per-window Grok pane state (session, transcript, install prompts, mode).+ /// One project per window means one session at a time; skill is auto-wired+ /// into `<project>/.grok/skills/` on project open; MCP/context on Start.grok_pane: agent_pane::GrokPaneState,- // ── Agent Friction Closure §13 — tool panes ─────────────────────────- /// Session state for IL2CPP Metadata/Methods/ICalls, Install Inventory,- /// File System Browser, Analysis Artifacts, and the GPU Decompile dialog.+ // ── Agent Friction Closure §13 — tool panes ─────────────────────────+ /// Session state for IL2CPP Metadata/Methods/ICalls, Install Inventory,+ /// File System Browser, Analysis Artifacts, and the GPU Decompile dialog.tool_panes: tool_panes::ToolPanesState,- /// Analysis → GPU Decompile… dialog visibility.+ /// Analysis → GPU Decompile… dialog visibility.show_gpu_decompile_dialog: bool,- /// decode options for Listing / Disassembled View.+ /// decode options for Listing / Disassembled View.decode_opts: DecodeUiOpts,- /// Listing mnemonic / id / group filter.+ /// Listing mnemonic / id / group filter.listing_search: ListingSearch,- /// Full decode options dialog (arch/mode and engine options).+ /// Full decode options dialog (arch/mode and engine options).show_decode_options_dialog: bool,}@@ -528,9 +538,9 @@ enum ConsoleSeverity {/// Checksum Generator scope .#[derive(Debug, Clone, PartialEq, Eq)]pub enum ChecksumMode {- /// Concatenation of every loaded memory block.+ /// Concatenation of every loaded memory block.WholeImage,- /// A single memory block chosen by name.+ /// A single memory block chosen by name.Section(String),}@@ -593,9 +603,7 @@ enum NewTypeKind {fn first_scalar_hint(operands: &str) -> Option<String> {let mut chars = operands.char_indices().peekable();while let Some((i, c)) = chars.next() {- if c == '0'- && operands.as_bytes().get(i + 1) == Some(&b'x')- {+ if c == '0' && operands.as_bytes().get(i + 1) == Some(&b'x') {let start = i + 2;let end = operands[start..].find(|c: char| !c.is_ascii_hexdigit())@@ -630,15 +638,15 @@ fn scalar_hint_string(v: u64) -> String {.map(|&b| b as char).collect();format!(- "scalar {v:#x} · dec {v} · i32 {}{} · ascii \"{ascii}\"",- if (v as i32) < 0 { "" } else { "" },+ "scalar {v:#x} · dec {v} · i32 {}{} · ascii \"{ascii}\"",+ if (v as i32) < 0 { "" } else { "" },v as i32)}/// address hover popup content for a Listing operand string.fn first_address_hint(operands: &str) -> Option<String> {- let idx = operands.find("0x")?;+ let idx = operands.find("0x")?;let start = idx + 2;let end = operands[start..].find(|c: char| !c.is_ascii_hexdigit())@@ -648,34 +656,34 @@ fn first_address_hint(operands: &str) -> Option<String> {return None;}let va = u64::from_str_radix(&operands[start..end], 16).ok()?;- Some(format!("target addr {va:#x}"))+ Some(format!("target addr {va:#x}"))}/// ``- syntax colour picker for the Decompiler pane.fn token_style(kind: &TokenKind, base: Color32) -> (Color32, bool) {match kind {- // Keywords: cyan .+ // Keywords: cyan .TokenKind::Keyword => (Color32::from_rgb(0x64, 0xB5, 0xF6), false),- // Function names: warm orange.+ // Function names: warm orange.TokenKind::Function => (Color32::from_rgb(0xFF, 0xB7, 0x4D), false),- // Variables: white/text default.+ // Variables: white/text default.TokenKind::Variable => (base, false),- // Block labels: purple.+ // Block labels: purple.TokenKind::Label => (Color32::from_rgb(0xBA, 0x68, 0xC8), false),- // Addresses: cyan for click-hint.+ // Addresses: cyan for click-hint.TokenKind::Address => (Color32::from_rgb(0x4D, 0xD0, 0xE1), false),- // Constants: lighter cyan.+ // Constants: lighter cyan.TokenKind::Constant => (Color32::from_rgb(0x80, 0xDE, 0xEA), false),- // Comments: green italics.+ // Comments: green italics.TokenKind::Comment => (Color32::from_rgb(0x81, 0xC7, 0x84), true),- // Syntax / whitespace / newline: dimmed text.+ // Syntax / whitespace / newline: dimmed text.TokenKind::Syntax => (base.gamma_multiply(0.85), false),TokenKind::Whitespace | TokenKind::Newline => (base, false),}}impl NewTypeKind {- const ALL: &'static [NewTypeKind] = &[+ const ALL: &'static [NewTypeKind] = &[NewTypeKind::Structure,NewTypeKind::Union,NewTypeKind::Enum,@@ -683,17 +691,17 @@ impl NewTypeKind {NewTypeKind::FunctionDefinition,];- const fn label(self) -> &'static str {+ const fn label(self) -> &'static str {match self {- NewTypeKind::Structure => "Structure",- NewTypeKind::Union => "Union",- NewTypeKind::Enum => "Enum",- NewTypeKind::Typedef => "Typedef",- NewTypeKind::FunctionDefinition => "Function Definition",+ NewTypeKind::Structure => "Structure",+ NewTypeKind::Union => "Union",+ NewTypeKind::Enum => "Enum",+ NewTypeKind::Typedef => "Typedef",+ NewTypeKind::FunctionDefinition => "Function Definition",}}- const fn template(self) -> &'static str {+ const fn template(self) -> &'static str {match self {NewTypeKind::Structure => "// Ghidrust user structure.\n// One field per line: `type name` (Stage-0 stores as string).\nint32_t field_0;\n",NewTypeKind::Union => "// Ghidrust user union.\nint32_t as_int;\nfloat as_float;\n",@@ -711,7 +719,7 @@ impl NewTypeKind {fn render_call_tree_node(node: &mut CallTreeNode,idx: usize,- direction: &'static str,+ direction: &'static str,prog: &Program,hide_thunks: bool,ui: &mut egui::Ui,@@ -719,7 +727,7 @@ fn render_call_tree_node(primary: Color32,goto: &mut Option<u64>,) {- let title = egui::RichText::new(format!("{} {:#x}", node.name, node.va)).monospace();+ let title = egui::RichText::new(format!("{} {:#x}", node.name, node.va)).monospace();let title = if node.is_thunk {title.color(Color32::from_rgb(0xFB, 0xC0, 0x2D))} else {@@ -731,29 +739,37 @@ fn render_call_tree_node(.show(ui, |ui| {expand_tree_node(node, prog, direction, hide_thunks);if node.children.is_empty() {- ui.small("(no further edges)");+ ui.small("(no further edges)");return;}for (i, child) in node.children.iter_mut().enumerate() {render_call_tree_node(- child, i, direction, prog, hide_thunks, ui, _muted, primary, goto,+ child,+ i,+ direction,+ prog,+ hide_thunks,+ ui,+ _muted,+ primary,+ goto,);}});if resp.header_response.clicked() {- *goto = Some(node.va);+ *goto = Some(node.va);}}impl GhidrustApp {- pub fn new(cc: &eframe::CreationContext<'_>) -> Self {- // Cascadia/Consolas + symbol fallbacks so the Grok TUI logo/box-drawing- // aren't tofu (▯) under egui's tiny default monospace.+ pub fn new(cc: &eframe::CreationContext<'_>) -> Self {+ // Cascadia/Consolas + symbol fallbacks so the Grok TUI logo/box-drawing+ // aren't tofu (▯) under egui's tiny default monospace.grok_term::install_terminal_fonts(&cc.egui_ctx);let mut app = Self::headless();app.recent_projects = load_recent_projects();app.show_startup_picker = true;- app.status = "Select a project to begin".into();+ app.status = "Select a project to begin".into();app.apply_theme(&cc.egui_ctx);app}@@ -764,9 +780,9 @@ impl GhidrustApp {Self {path_input: String::new(),project_dir_input: String::new(),- project_name_input: "MyProject".into(),- status: "Ready — File → New/Open Project, then Import binary".into(),- console: vec!["Ghidrust CodeBrowser started.".into()],+ project_name_input: "MyProject".into(),+ status: "Ready — File → New/Open Project, then Import binary".into(),+ console: vec!["Ghidrust CodeBrowser started.".into()],theme: ThemeMode::Dark,project: None,active_file_id: None,@@ -774,6 +790,11 @@ impl GhidrustApp {listing: Vec::new(),rtti: RttiReport::default(),strings: Vec::new(),+ crypt_constants: Vec::new(),+ crypto_constants_focus_va: None,+ obfuscated_strings: Vec::new(),+ crypto_capabilities: Vec::new(),+ decrypt_pane: DecryptPaneState::default(),last_analysis: AnalysisRunReport::default(),last_analyzers_run: Vec::new(),analyzer_enabled: enabled,@@ -818,10 +839,10 @@ impl GhidrustApp {decomp_entry: None,decomp_text: String::new(),decomp_status: String::new(),- // Stage-1 is now the default GUI decompiler stage —- // real SSA + structure + types instead of the mnemonic-scaffold- // Stage-0 preview. Users can still pick Stage-0/Stage-0.5 from- // the stage picker combo box.+ // Stage-1 is now the default GUI decompiler stage —+ // real SSA + structure + types instead of the mnemonic-scaffold+ // Stage-0 preview. Users can still pick Stage-0/Stage-0.5 from+ // the stage picker combo box.decomp_stage: DecompStage::Stage1,decomp_lift_ratio: None,pane_open: Self::default_pane_open(),@@ -836,7 +857,7 @@ impl GhidrustApp {functions_window_filter: String::new(),symbol_table_filter: String::new(),defined_strings_filter: String::new(),- defined_strings_encoding: "all".into(),+ defined_strings_encoding: "all".into(),event_bus: EventBus::new(),decomp_lines: Vec::new(),decomp_cross_line: None,@@ -888,11 +909,11 @@ impl GhidrustApp {equate_dialog_value: String::new(),function_tags_new_input: String::new(),external_programs_filter: String::new(),- data_type_preview_selected: "dword".into(),+ data_type_preview_selected: "dword".into(),checksum_last: None,show_search_scalars_dialog: false,- search_scalars_min: "0".into(),- search_scalars_max: "0xffff".into(),+ search_scalars_min: "0".into(),+ search_scalars_max: "0xffff".into(),show_search_insn_dialog: false,search_insn_mnemonic: String::new(),search_insn_operands: String::new(),@@ -929,8 +950,8 @@ impl GhidrustApp {}}- /// Default `Window → *` toggles. Everything is available; only well-supported panes- /// float open by default so users see the full surface but aren't buried.+ /// Default `Window → *` toggles. Everything is available; only well-supported panes+ /// float open by default so users see the full surface but aren't buried.fn default_pane_open() -> BTreeMap<PaneKind, bool> {let mut m = BTreeMap::new();for k in PaneKind::ALL {@@ -939,14 +960,14 @@ impl GhidrustApp {m}- /// Toggle a floating provider window (used by `Window` menu + toolbar shortcuts).+ /// Toggle a floating provider window (used by `Window` menu + toolbar shortcuts).pub fn toggle_pane(&mut self, kind: PaneKind, open: bool) {self.pane_open.insert(kind, open);}- /// Whether the given provider is currently visible.+ /// Whether the given provider is currently visible.pub fn is_pane_open(&self, kind: PaneKind) -> bool {- *self.pane_open.get(&kind).unwrap_or(&false)+ *self.pane_open.get(&kind).unwrap_or(&false)}fn clear_decompiler_cache(&mut self) {@@ -958,19 +979,19 @@ impl GhidrustApp {self.decomp_lift_ratio = None;}- /// Refresh the decompiler cache for `va` (containing / nearest function)- /// at the currently-selected [`DecompStage`] (Stage-0 / 0.5 / 1).- ///- /// Also rebuilds the tokenised `decomp_lines` cache used by the pane for- /// click-navigation and cross-highlight with the Listing. If Stage-0.5- /// / Stage-1 fail (e.g. structuring gave up on an irreducible region)- /// the pane silently falls back to Stage-0 so the user always sees- /// something.+ /// Refresh the decompiler cache for `va` (containing / nearest function)+ /// at the currently-selected [`DecompStage`] (Stage-0 / 0.5 / 1).+ ///+ /// Also rebuilds the tokenised `decomp_lines` cache used by the pane for+ /// click-navigation and cross-highlight with the Listing. If Stage-0.5+ /// / Stage-1 fail (e.g. structuring gave up on an irreducible region)+ /// the pane silently falls back to Stage-0 so the user always sees+ /// something.pub fn refresh_decompiler_at(&mut self, va: u64) {let Some(prog) = self.program.as_ref() else {self.decomp_entry = None;self.decomp_text.clear();- self.decomp_status = "No program loaded.".into();+ self.decomp_status = "No program loaded.".into();self.decomp_lines.clear();self.decomp_cross_line = None;self.decomp_lift_ratio = None;@@ -985,7 +1006,7 @@ impl GhidrustApp {return;}let stage = self.decomp_stage;- // R5: Stage-1 prefers emit-time tokens when present.+ // R5: Stage-1 prefers emit-time tokens when present.if stage == DecompStage::Stage1 {if let Ok((entry, text, ratio, tokens)) =stage1_pseudo_c_with_tokens(prog, va, STAGE0_MAX_INSNS)@@ -1006,11 +1027,10 @@ impl GhidrustApp {.as_ref().and_then(|p| p.display_function_name_at(entry));self.decomp_status = match user_name {- Some(name) => format!(- "Stage-1 · {name} @ {entry:#x} · lift={:.1}%",- ratio * 100.0- ),- None => format!("Stage-1 · {entry:#x} · lift={:.1}%", ratio * 100.0),+ Some(name) => {+ format!("Stage-1 · {name} @ {entry:#x} · lift={:.1}%", ratio * 100.0)+ }+ None => format!("Stage-1 · {entry:#x} · lift={:.1}%", ratio * 100.0),};return;}@@ -1019,9 +1039,9 @@ impl GhidrustApp {let (label, result) = match attempt {Ok(v) => (stage.label(), Ok(v)),Err(_) if stage != DecompStage::Stage0 => {- // Never render an empty pane — retry at Stage-0.- let fallback = stage0_pseudo_c(prog, va, STAGE0_MAX_INSNS)- .map(|(e, t)| (e, t, None));+ // Never render an empty pane — retry at Stage-0.+ let fallback =+ stage0_pseudo_c(prog, va, STAGE0_MAX_INSNS).map(|(e, t)| (e, t, None));(DecompStage::Stage0.label(), fallback)}Err(e) => (stage.label(), Err(e)),@@ -1038,31 +1058,30 @@ impl GhidrustApp {.as_ref().and_then(|p| p.display_function_name_at(entry));self.decomp_status = match (user_name, ratio) {- (Some(name), Some(r)) => format!(- "{label} · {name} @ {entry:#x} · lift={:.1}%",- r * 100.0- ),- (Some(name), None) => format!("{label} · {name} @ {entry:#x}"),+ (Some(name), Some(r)) => {+ format!("{label} · {name} @ {entry:#x} · lift={:.1}%", r * 100.0)+ }+ (Some(name), None) => format!("{label} · {name} @ {entry:#x}"),(None, Some(r)) => {- format!("{label} · {entry:#x} · lift={:.1}%", r * 100.0)+ format!("{label} · {entry:#x} · lift={:.1}%", r * 100.0)}- (None, None) => format!("{label} · {entry:#x}"),+ (None, None) => format!("{label} · {entry:#x}"),};}Err(e) => {self.decomp_entry = Some(entry);- self.decomp_text = format!("// decompile failed at {entry:#x}\n// {e}\n");+ self.decomp_text = format!("// decompile failed at {entry:#x}\n// {e}\n");self.decomp_lines = tokenize_decomp(&self.decomp_text);self.decomp_cross_line = None;self.decomp_lift_ratio = None;- self.decomp_status = format!("error: {e}");+ self.decomp_status = format!("error: {e}");}}}- /// Switch the active decompile stage (Stage-0 / 0.5 / 1) and re-run the- /// emit for the currently-focused function entry. Public so the pane- /// dropdown + tests can drive it.+ /// Switch the active decompile stage (Stage-0 / 0.5 / 1) and re-run the+ /// emit for the currently-focused function entry. Public so the pane+ /// dropdown + tests can drive it.pub fn set_decomp_stage(&mut self, stage: DecompStage) {if self.decomp_stage == stage {return;@@ -1077,17 +1096,17 @@ impl GhidrustApp {}}- /// Current decompile stage — used by the pane header dropdown and tests.+ /// Current decompile stage — used by the pane header dropdown and tests.pub fn decomp_stage(&self) -> DecompStage {self.decomp_stage}- /// Latest lift coverage ratio (Stage-0.5 / Stage-1 only).+ /// Latest lift coverage ratio (Stage-0.5 / Stage-1 only).pub fn decomp_lift_ratio(&self) -> Option<f32> {self.decomp_lift_ratio}- /// Focus a center dock tab. Listing/Decompiler prefer a side-by-side split.+ /// Focus a center dock tab. Listing/Decompiler prefer a side-by-side split.fn focus_center_tab(&mut self, tab: DockTab) {match tab {DockTab::Listing | DockTab::Decompiler => {@@ -1106,11 +1125,11 @@ impl GhidrustApp {.into();}- /// Symbol Tree / Navigation: focus a function entry in Listing and update Decompiler.+ /// Symbol Tree / Navigation: focus a function entry in Listing and update Decompiler.pub fn focus_function(&mut self, entry: u64) {- let addr = format!("{entry:#x}");+ let addr = format!("{entry:#x}");if let Err(e) = self.goto_address_str(&addr) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());return;}@@ -1121,57 +1140,57 @@ impl GhidrustApp {.program.as_ref().and_then(|p| p.display_function_name_at(entry))- .unwrap_or_else(|| format!("{entry:#x}"));- self.status = format!("Function {name}");+ .unwrap_or_else(|| format!("{entry:#x}"));+ self.status = format!("Function {name}");self.log(self.status.clone());}- /// Navigation → Back (Alt+Left).- ///- /// Pops the previous location off the Back stack and re-runs `goto_address_str`- /// without recording another entry (guarded by `nav_suspended`).+ /// Navigation → Back (Alt+Left).+ ///+ /// Pops the previous location off the Back stack and re-runs `goto_address_str`+ /// without recording another entry (guarded by `nav_suspended`).pub fn nav_back(&mut self) -> bool {let Some(prev) = self.nav_history.back() else {- self.status = "Navigation → nothing to go back to".into();+ self.status = "Navigation → nothing to go back to".into();self.log(self.status.clone());return false;};self.nav_suspended = true;- let r = self.goto_address_str(&format!("{:#x}", prev.va));+ let r = self.goto_address_str(&format!("{:#x}", prev.va));self.nav_suspended = false;if let Err(e) = r {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());return false;}self.refresh_decompiler_at(prev.va);- self.status = format!("Back → {:#x}", prev.va);+ self.status = format!("Back → {:#x}", prev.va);self.log(self.status.clone());true}- /// Navigation → Forward (Alt+Right).+ /// Navigation → Forward (Alt+Right).pub fn nav_forward(&mut self) -> bool {let Some(next) = self.nav_history.forward() else {- self.status = "Navigation → nothing to go forward to".into();+ self.status = "Navigation → nothing to go forward to".into();self.log(self.status.clone());return false;};self.nav_suspended = true;- let r = self.goto_address_str(&format!("{:#x}", next.va));+ let r = self.goto_address_str(&format!("{:#x}", next.va));self.nav_suspended = false;if let Err(e) = r {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());return false;}self.refresh_decompiler_at(next.va);- self.status = format!("Forward → {:#x}", next.va);+ self.status = format!("Forward → {:#x}", next.va);self.log(self.status.clone());true}- /// Convenience: are we able to step back?+ /// Convenience: are we able to step back?pub fn can_nav_back(&self) -> bool {self.nav_history.can_back()}@@ -1179,7 +1198,7 @@ impl GhidrustApp {self.nav_history.can_forward()}- /// Bookmarks → Add (BookmarkPlugin analog). Va + kind + category + description.+ /// Bookmarks → Add (BookmarkPlugin analog). Va + kind + category + description.pub fn add_bookmark(&mut self,va: u64,@@ -1197,11 +1216,11 @@ impl GhidrustApp {self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::BookmarkAdded { va },});- self.status = format!("Bookmark added at {va:#x} ({})", kind.label());+ self.status = format!("Bookmark added at {va:#x} ({})", kind.label());self.log(self.status.clone());}- /// Bookmarks → Delete.+ /// Bookmarks → Delete.pub fn delete_bookmark(&mut self, index: usize) {if index < self.bookmarks.len() {let b = self.bookmarks.remove(index);@@ -1209,20 +1228,20 @@ impl GhidrustApp {self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::BookmarkRemoved { va },});- self.status = format!("Bookmark removed at {va:#x} ({})", b.kind.label());+ self.status = format!("Bookmark removed at {va:#x} ({})", b.kind.label());self.log(self.status.clone());}}- /// Look up bookmarks at (or covering) `va` for margin-marker rendering.+ /// Look up bookmarks at (or covering) `va` for margin-marker rendering.pub fn bookmarks_at(&self, va: u64) -> Vec<&Bookmark> {self.bookmarks.iter().filter(|b| b.va == va).collect()}- /// Navigation → Next Bookmark.+ /// Navigation → Next Bookmark.pub fn nav_next_bookmark(&mut self) {if self.bookmarks.is_empty() {- self.status = "No bookmarks — Bookmarks → Add".into();+ self.status = "No bookmarks — Bookmarks → Add".into();self.log(self.status.clone());return;}@@ -1230,16 +1249,16 @@ impl GhidrustApp {let mut vas: Vec<u64> = self.bookmarks.iter().map(|b| b.va).collect();vas.sort();if let Some(va) = vas.iter().copied().find(|&va| va > cur) {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));} else {- let _ = self.goto_address_str(&format!("{:#x}", vas[0]));+ let _ = self.goto_address_str(&format!("{:#x}", vas[0]));}}- /// Navigation → Previous Bookmark.+ /// Navigation → Previous Bookmark.pub fn nav_prev_bookmark(&mut self) {if self.bookmarks.is_empty() {- self.status = "No bookmarks — Bookmarks → Add".into();+ self.status = "No bookmarks — Bookmarks → Add".into();self.log(self.status.clone());return;}@@ -1247,37 +1266,37 @@ impl GhidrustApp {let mut vas: Vec<u64> = self.bookmarks.iter().map(|b| b.va).collect();vas.sort();if let Some(va) = vas.iter().rev().copied().find(|&va| va < cur) {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));} else {- let _ = self.goto_address_str(&format!("{:#x}", vas.last().copied().unwrap()));+ let _ = self.goto_address_str(&format!("{:#x}", vas.last().copied().unwrap()));}}- // ── user edits ───────────────────────────────────────+ // ── user edits ───────────────────────────────────────- /// Rename the symbol / function at `va` (persists into `Program::edits`).- ///- /// Also mirrors the rename into `Program::analysis.functions[i].name()` so- /// every downstream pane (Symbol Tree, Functions Window, Symbol Table,- /// Bookmarks label preview) sees the new name without a full re-analyze.- /// Emits a `ProgramMutated::Rename` event which invalidates the Decompiler- /// cache so the header string is rebuilt.+ /// Rename the symbol / function at `va` (persists into `Program::edits`).+ ///+ /// Also mirrors the rename into `Program::analysis.functions[i].name()` so+ /// every downstream pane (Symbol Tree, Functions Window, Symbol Table,+ /// Bookmarks label preview) sees the new name without a full re-analyze.+ /// Emits a `ProgramMutated::Rename` event which invalidates the Decompiler+ /// cache so the header string is rebuilt.pub fn rename_at(&mut self, va: u64, new_name: impl Into<String>) -> Result<(), String> {let new_name = new_name.into();if new_name.trim().is_empty() {- return Err("empty name".into());+ return Err("empty name".into());}let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;- // Mirror into analysis so tables / listing / decomp header pick it up.+ .ok_or_else(|| "no program loaded".to_string())?;+ // Mirror into analysis so tables / listing / decomp header pick it up.if let Some(f) = prog.function_at_mut(va) {f.name = new_name.clone();} else if let Some(s) = prog.analysis.symbols.iter_mut().find(|s| s.va == va) {s.name = new_name.clone();}- // Persist as an edit even if analysis had no matching entry.+ // Persist as an edit even if analysis had no matching entry.prog.edits.set_rename(va, &new_name);self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Rename {@@ -1285,18 +1304,18 @@ impl GhidrustApp {new_name: new_name.clone(),},});- self.status = format!("Renamed {va:#x} → {new_name}");+ self.status = format!("Renamed {va:#x} → {new_name}");self.log(self.status.clone());Ok(())}- /// Retype the variable / global at `va` (persists into `Program::edits`).+ /// Retype the variable / global at `va` (persists into `Program::edits`).pub fn retype_at(&mut self, va: u64, type_desc: impl Into<String>) -> Result<(), String> {let type_desc = type_desc.into();let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;prog.edits.set_retype(va, &type_desc);self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Retype {@@ -1304,12 +1323,12 @@ impl GhidrustApp {type_desc: type_desc.clone(),},});- self.status = format!("Retyped {va:#x} → {type_desc}");+ self.status = format!("Retyped {va:#x} → {type_desc}");self.log(self.status.clone());Ok(())}- /// Set (or clear) a comment at `va` (persists into `Program::edits`).+ /// Set (or clear) a comment at `va` (persists into `Program::edits`).pub fn set_comment_at(&mut self,va: u64,@@ -1320,21 +1339,21 @@ impl GhidrustApp {let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;prog.edits.set_comment(va, kind, &text);self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::CommentChanged { va },});self.status = if text.is_empty() {- format!("Cleared {} comment at {va:#x}", kind.label())+ format!("Cleared {} comment at {va:#x}", kind.label())} else {- format!("Set {} comment at {va:#x}", kind.label())+ format!("Set {} comment at {va:#x}", kind.label())};self.log(self.status.clone());Ok(())}- /// Set / replace a function signature (Edit Function Signature dialog).+ /// Set / replace a function signature (Edit Function Signature dialog).pub fn set_function_signature(&mut self,entry: u64,@@ -1344,7 +1363,7 @@ impl GhidrustApp {let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;let mut sig = prog.edits.function_signature(entry)@@ -1358,72 +1377,72 @@ impl GhidrustApp {type_desc: signature.clone(),},});- self.status = format!("Function signature @ {entry:#x} → {signature}");+ self.status = format!("Function signature @ {entry:#x} → {signature}");self.log(self.status.clone());Ok(())}- /// Decompiler → Commit Params/Return. Adopts the analyzer-inferred parameter- /// list + a "auto" return type as user commitments.+ /// Decompiler → Commit Params/Return. Adopts the analyzer-inferred parameter+ /// list + a "auto" return type as user commitments.pub fn commit_params_return(&mut self, entry: u64) -> Result<(), String> {let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;let (params, ret) = {let f = prog.function_at(entry)- .ok_or_else(|| format!("no function at {entry:#x}"))?;+ .ok_or_else(|| format!("no function at {entry:#x}"))?;let params: Vec<String> = if f.parameters.is_empty() {Vec::new()} else {f.parameters.clone()};- // Ghidrust Stage-0 has no dataflow return-type yet — commit as `undefined`.- (params, "undefined".to_string())+ // Ghidrust Stage-0 has no dataflow return-type yet — commit as `undefined`.+ (params, "undefined".to_string())};prog.edits.commit_params(entry, params.clone());prog.edits.commit_return_type(entry, &ret);self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Retype {va: entry,- type_desc: format!("commit params: {} · return {ret}", params.len()),+ type_desc: format!("commit params: {} · return {ret}", params.len()),},});self.status = format!(- "Commit Params/Return @ {entry:#x} ({} param(s), return {ret})",+ "Commit Params/Return @ {entry:#x} ({} param(s), return {ret})",params.len());self.log(self.status.clone());Ok(())}- /// Decompiler → Commit Locals. Persists analyzer-inferred stack locals as- /// user edits so a later rename doesn't require re-analyzing.+ /// Decompiler → Commit Locals. Persists analyzer-inferred stack locals as+ /// user edits so a later rename doesn't require re-analyzing.pub fn commit_locals(&mut self, entry: u64) -> Result<(), String> {let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;let locals = {let f = prog.function_at(entry)- .ok_or_else(|| format!("no function at {entry:#x}"))?;+ .ok_or_else(|| format!("no function at {entry:#x}"))?;f.stack_locals.clone()};prog.edits.commit_locals(entry, locals.clone());self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Retype {va: entry,- type_desc: format!("commit locals: {}", locals.len()),+ type_desc: format!("commit locals: {}", locals.len()),},});- self.status = format!("Commit Locals @ {entry:#x} ({} local(s))", locals.len());+ self.status = format!("Commit Locals @ {entry:#x} ({} local(s))", locals.len());self.log(self.status.clone());Ok(())}- /// Data Type Manager → New Structure / Union / Enum / Typedef / Function Def.+ /// Data Type Manager → New Structure / Union / Enum / Typedef / Function Def.pub fn define_user_type(&mut self,name: impl Into<String>,@@ -1432,31 +1451,31 @@ impl GhidrustApp {let name = name.into();let body = body.into();if name.trim().is_empty() {- return Err("empty type name".into());+ return Err("empty type name".into());}let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;prog.edits.set_user_type(name.clone(), body);self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Retype {va: 0,- type_desc: format!("user type: {name}"),+ type_desc: format!("user type: {name}"),},});- self.status = format!("New type: {name}");+ self.status = format!("New type: {name}");self.log(self.status.clone());Ok(())}- /// Listing → Apply Data Type at `va` (drag from DTM, or `T` key).+ /// Listing → Apply Data Type at `va` (drag from DTM, or `T` key).pub fn apply_type_at(&mut self, va: u64, type_name: impl Into<String>) -> Result<(), String> {let type_name = type_name.into();let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;prog.edits.set_applied_type(va, &type_name);self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Retype {@@ -1464,13 +1483,13 @@ impl GhidrustApp {type_desc: type_name.clone(),},});- self.status = format!("Applied type {type_name} @ {va:#x}");+ self.status = format!("Applied type {type_name} @ {va:#x}");self.log(self.status.clone());Ok(())}- /// DTM → Rename an existing user type (`Rename` on a Data Type- /// leaf). Rewrites `applied_types` so Listing decorations stay in sync.+ /// DTM → Rename an existing user type (`Rename` on a Data Type+ /// leaf). Rewrites `applied_types` so Listing decorations stay in sync.pub fn rename_user_type(&mut self,old: impl Into<String>,@@ -1479,48 +1498,48 @@ impl GhidrustApp {let old = old.into();let new = new.into();if new.trim().is_empty() {- return Err("empty type name".into());+ return Err("empty type name".into());}let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;if !prog.edits.rename_user_type(&old, &new) {- return Err(format!("no type named {old}"));+ return Err(format!("no type named {old}"));}self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Retype {va: 0,- type_desc: format!("rename type: {old} → {new}"),+ type_desc: format!("rename type: {old} → {new}"),},});- self.status = format!("Renamed type {old} → {new}");+ self.status = format!("Renamed type {old} → {new}");self.log(self.status.clone());Ok(())}- /// DTM → Delete a user type (also unlinks any `Applied` decorations).+ /// DTM → Delete a user type (also unlinks any `Applied` decorations).pub fn delete_user_type(&mut self, name: &str) -> Result<(), String> {let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;if !prog.edits.delete_user_type(name) {- return Err(format!("no type named {name}"));+ return Err(format!("no type named {name}"));}self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Retype {va: 0,- type_desc: format!("deleted type: {name}"),+ type_desc: format!("deleted type: {name}"),},});- self.status = format!("Deleted type {name}");+ self.status = format!("Deleted type {name}");self.log(self.status.clone());Ok(())}- /// DTM → Edit an existing user type body (Structure / Union /- /// Enum / Typedef editor). May also rename in the same operation.+ /// DTM → Edit an existing user type body (Structure / Union /+ /// Enum / Typedef editor). May also rename in the same operation.pub fn edit_user_type(&mut self,orig_name: &str,@@ -1530,14 +1549,14 @@ impl GhidrustApp {let new_name = new_name.into();let body = body.into();if new_name.trim().is_empty() {- return Err("empty type name".into());+ return Err("empty type name".into());}let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;if !prog.edits.user_types.contains_key(orig_name) {- return Err(format!("no type named {orig_name}"));+ return Err(format!("no type named {orig_name}"));}if orig_name != new_name {let _ = prog.edits.rename_user_type(orig_name, &new_name);@@ -1546,37 +1565,37 @@ impl GhidrustApp {self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Retype {va: 0,- type_desc: format!("edit type: {new_name}"),+ type_desc: format!("edit type: {new_name}"),},});- self.status = format!("Edited type {new_name}");+ self.status = format!("Edited type {new_name}");self.log(self.status.clone());Ok(())}- /// DTM → New Typedef on X . Creates a- /// typedef whose body records the underlying type; the resulting user- /// type can be applied at Listing addresses just like any other.+ /// DTM → New Typedef on X . Creates a+ /// typedef whose body records the underlying type; the resulting user+ /// type can be applied at Listing addresses just like any other.pub fn new_typedef_on(&mut self, source: &str) -> Result<String, String> {- let name = format!("typedef_{source}");- let body = format!("Typedef\ntypedef {source} {name};");+ let name = format!("typedef_{source}");+ let body = format!("Typedef\ntypedef {source} {name};");self.define_user_type(&name, body)?;Ok(name)}- /// DTM → New Pointer to X. Registers a `<X> *` user type so the Listing- /// can apply the pointer decoration without a full parser.+ /// DTM → New Pointer to X. Registers a `<X> *` user type so the Listing+ /// can apply the pointer decoration without a full parser.pub fn new_pointer_to(&mut self, source: &str) -> Result<String, String> {- let name = format!("{source} *");- let body = format!("Typedef\n{source} *");+ let name = format!("{source} *");+ let body = format!("Typedef\n{source} *");self.define_user_type(&name, body)?;Ok(name)}- // ── equates, function tags, xrefs, checksums ──────────+ // ── equates, function tags, xrefs, checksums ──────────- /// Attach an equate `name` at `(va, op)` for scalar `value` (- /// `Convert → Equate`). Empty `name` clears the equate.+ /// Attach an equate `name` at `(va, op)` for scalar `value` (+ /// `Convert → Equate`). Empty `name` clears the equate.pub fn set_equate(&mut self,va: u64,@@ -1588,49 +1607,49 @@ impl GhidrustApp {let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;let clearing = name.is_empty();prog.edits.set_equate(va, op, &name, value);- // Equates render inline in the Listing operand slot; treat as retype- // for cache invalidation so the Decompiler picks the change up too.+ // Equates render inline in the Listing operand slot; treat as retype+ // for cache invalidation so the Decompiler picks the change up too.self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Retype {va,type_desc: if clearing {- format!("cleared equate @ op {op}")+ format!("cleared equate @ op {op}")} else {- format!("equate {name} = {value}")+ format!("equate {name} = {value}")},},});self.status = if clearing {- format!("Cleared equate @ {va:#x} op {op}")+ format!("Cleared equate @ {va:#x} op {op}")} else {- format!("Set equate {name} = {value} @ {va:#x} op {op}")+ format!("Set equate {name} = {value} @ {va:#x} op {op}")};self.log(self.status.clone());Ok(())}- /// Function Tags — add / remove / delete-everywhere (- /// `FunctionTagPlugin`).+ /// Function Tags — add / remove / delete-everywhere (+ /// `FunctionTagPlugin`).pub fn add_function_tag(&mut self, entry: u64, tag: impl Into<String>) -> Result<(), String> {let tag = tag.into();if tag.trim().is_empty() {- return Err("empty tag".into());+ return Err("empty tag".into());}let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;prog.edits.add_function_tag(entry, &tag);self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Retype {va: entry,- type_desc: format!("tag+ {tag}"),+ type_desc: format!("tag+ {tag}"),},});- self.status = format!("Tag '{tag}' added to fn @ {entry:#x}");+ self.status = format!("Tag '{tag}' added to fn @ {entry:#x}");self.log(self.status.clone());Ok(())}@@ -1639,60 +1658,60 @@ impl GhidrustApp {let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;let removed = prog.edits.remove_function_tag(entry, tag);if !removed {- return Err(format!("fn @ {entry:#x} has no tag '{tag}'"));+ return Err(format!("fn @ {entry:#x} has no tag '{tag}'"));}self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Retype {va: entry,- type_desc: format!("tag- {tag}"),+ type_desc: format!("tag- {tag}"),},});- self.status = format!("Tag '{tag}' removed from fn @ {entry:#x}");+ self.status = format!("Tag '{tag}' removed from fn @ {entry:#x}");self.log(self.status.clone());Ok(())}- /// Register a tag in the universe (`ProgramEdits::all_function_tags`)- /// without assigning it to a function. "Create tag" action- /// lands here.+ /// Register a tag in the universe (`ProgramEdits::all_function_tags`)+ /// without assigning it to a function. "Create tag" action+ /// lands here.pub fn create_tag(&mut self, tag: impl Into<String>) -> Result<(), String> {let tag = tag.into();if tag.trim().is_empty() {- return Err("empty tag".into());+ return Err("empty tag".into());}let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;prog.edits.all_function_tags.insert(tag.clone());- self.status = format!("Created tag '{tag}'");+ self.status = format!("Created tag '{tag}'");self.log(self.status.clone());Ok(())}- /// Delete a tag from every function and from the universe.+ /// Delete a tag from every function and from the universe.pub fn delete_tag_everywhere(&mut self, tag: &str) -> Result<(), String> {let prog = self.program.as_mut()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;let n = prog.edits.delete_tag_everywhere(tag);self.event_bus.publish(GhidrustEvent::ProgramMutated {kind: MutationKind::Retype {va: 0,- type_desc: format!("tag deleted: {tag}"),+ type_desc: format!("tag deleted: {tag}"),},});- self.status = format!("Tag '{tag}' deleted from {n} function(s)");+ self.status = format!("Tag '{tag}' deleted from {n} function(s)");self.log(self.status.clone());Ok(())}- /// Compute references TO the given target VA. Uses `ghidrust-core::xrefs`- /// against the current program + focused-window listing.+ /// Compute references TO the given target VA. Uses `ghidrust-core::xrefs`+ /// against the current program + focused-window listing.pub fn xrefs_to_va(&self, target: u64) -> Vec<XRef> {let Some(prog) = self.program.as_ref() else {return Vec::new();@@ -1700,7 +1719,7 @@ impl GhidrustApp {xrefs_to(prog, target, Some(&self.listing))}- /// Compute references FROM the given source VA.+ /// Compute references FROM the given source VA.pub fn xrefs_from_va(&self, source: u64) -> Vec<XRef> {let Some(prog) = self.program.as_ref() else {return Vec::new();@@ -1708,24 +1727,24 @@ impl GhidrustApp {xrefs_from(prog, source, STAGE0_MAX_INSNS)}- /// Compute a checksum panel over the loaded program (or focused block).+ /// Compute a checksum panel over the loaded program (or focused block).pub fn compute_checksums(&mut self, mode: ChecksumMode) -> Result<(), String> {let prog = self.program.as_ref()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;let (target_label, data): (String, Vec<u8>) = match mode {ChecksumMode::WholeImage => {let bytes: Vec<u8> = prog.blocks.iter().flat_map(|b| b.bytes.clone()).collect();- (format!("Whole image ({})", prog.name), bytes)+ (format!("Whole image ({})", prog.name), bytes)}ChecksumMode::Section(name) => {let b = prog.blocks.iter().find(|b| b.name == name)- .ok_or_else(|| format!("no block named {name}"))?;- (format!("Block {name}"), b.bytes.clone())+ .ok_or_else(|| format!("no block named {name}"))?;+ (format!("Block {name}"), b.bytes.clone())}};let len = data.len();@@ -1752,25 +1771,21 @@ impl GhidrustApp {fletcher16,fletcher32,});- self.status = format!(- "Checksum: crc32={crc32:#010x} adler32={adler32:#010x} len={len}",- );+ self.status = format!("Checksum: crc32={crc32:#010x} adler32={adler32:#010x} len={len}",);self.log(self.status.clone());Ok(())}- /// Program Tree → Set View / Add To View / Remove From View / Show All.- ///- /// The semantic is a **fragment name set**. `None` = full view.+ /// Program Tree → Set View / Add To View / Remove From View / Show All.+ ///+ /// The semantic is a **fragment name set**. `None` = full view.pub fn set_listing_view(&mut self, fragments: Option<BTreeSet<String>>) {self.listing_view_filter = fragments;}pub fn add_to_view(&mut self, fragment: impl Into<String>) {let name = fragment.into();- let entry = self- .listing_view_filter- .get_or_insert_with(BTreeSet::new);+ let entry = self.listing_view_filter.get_or_insert_with(BTreeSet::new);entry.insert(name);}@@ -1778,8 +1793,8 @@ impl GhidrustApp {if let Some(set) = self.listing_view_filter.as_mut() {set.remove(fragment);if set.is_empty() {- // Empty view → drop the filter so Listing shows nothing but- // reflects an honest empty state driven by fragment membership.+ // Empty view → drop the filter so Listing shows nothing but+ // reflects an honest empty state driven by fragment membership.}}}@@ -1788,7 +1803,7 @@ impl GhidrustApp {self.listing_view_filter = None;}- /// Whether a Listing address is currently in-view (Program Tree filter).+ /// Whether a Listing address is currently in-view (Program Tree filter).pub fn addr_in_view(&self, va: u64) -> bool {let Some(filter) = self.listing_view_filter.as_ref() else {return true;@@ -1802,7 +1817,7 @@ impl GhidrustApp {.any(|b| va >= b.va && va < b.va.saturating_add(b.size))}- /// Navigation → Next Function.+ /// Navigation → Next Function.pub fn nav_next_function(&mut self) {let cur = self.listing_focus_va.unwrap_or(0);let entries: Vec<u64> = self@@ -1811,7 +1826,7 @@ impl GhidrustApp {.map(|p| p.analysis.functions.iter().map(|f| f.entry).collect()).unwrap_or_default();if entries.is_empty() {- self.status = "No functions — run Function Start Search".into();+ self.status = "No functions — run Function Start Search".into();self.log_warn(self.status.clone());return;}@@ -1824,7 +1839,7 @@ impl GhidrustApp {}}- /// Navigation → Previous Function.+ /// Navigation → Previous Function.pub fn nav_prev_function(&mut self) {let cur = self.listing_focus_va.unwrap_or(u64::MAX);let entries: Vec<u64> = self@@ -1833,7 +1848,7 @@ impl GhidrustApp {.map(|p| p.analysis.functions.iter().map(|f| f.entry).collect()).unwrap_or_default();if entries.is_empty() {- self.status = "No functions — run Function Start Search".into();+ self.status = "No functions — run Function Start Search".into();self.log_warn(self.status.clone());return;}@@ -1846,43 +1861,43 @@ impl GhidrustApp {}}- /// Program → Symbol Tree lookup: are Imports/Exports parseable from analysis?- ///- /// Ghidrust's PE loader doesn't yet parse the Import / Export directories, but- /// PDB analyzers do populate `Program::analysis.pdb_symbols`. This helper- /// returns (imports, exports) as best-effort lists derived from analyzer- /// output — never fabricated. Empty lists = analyzer didn't populate.+ /// Program → Symbol Tree lookup: are Imports/Exports parseable from analysis?+ ///+ /// Ghidrust's PE loader doesn't yet parse the Import / Export directories, but+ /// PDB analyzers do populate `Program::analysis.pdb_symbols`. This helper+ /// returns (imports, exports) as best-effort lists derived from analyzer+ /// output — never fabricated. Empty lists = analyzer didn't populate.pub fn imports_exports(&self) -> (Vec<(u64, String)>, Vec<(u64, String)>) {let Some(prog) = self.program.as_ref() else {return (Vec::new(), Vec::new());};let mut imports = Vec::new();let mut exports = Vec::new();- // Heuristic (source-honest): PDB symbols with `__imp_` prefix are imports.+ // Heuristic (source-honest): PDB symbols with `__imp_` prefix are imports.for s in &prog.analysis.pdb_symbols {- if s.name.starts_with("__imp_")- || s.name.starts_with("_imp_")- || s.name.starts_with("__imp")+ if s.name.starts_with("__imp_")+ || s.name.starts_with("_imp_")+ || s.name.starts_with("__imp"){imports.push((s.va, s.name.clone()));}}- // Section-based fallback: sections whose name contains "idata"/"iat" are- // import metadata; expose their base as an anchor row.+ // Section-based fallback: sections whose name contains "idata"/"iat" are+ // import metadata; expose their base as an anchor row.for s in &prog.sections {let n = s.name.to_ascii_lowercase();- if n.contains("idata") || n.contains("iat") {- imports.push((s.va, format!("{} @ {:#x}", s.name, s.va)));+ if n.contains("idata") || n.contains("iat") {+ imports.push((s.va, format!("{} @ {:#x}", s.name, s.va)));}- if n.contains("edata") {- exports.push((s.va, format!("{} @ {:#x}", s.name, s.va)));+ if n.contains("edata") {+ exports.push((s.va, format!("{} @ {:#x}", s.name, s.va)));}}- // Analysis symbols marked as exports by demangler are entry-like.+ // Analysis symbols marked as exports by demangler are entry-like.for s in &prog.analysis.symbols {if s.demangled.as_ref()- .map(|d| d.contains("__declspec(dllexport)"))+ .map(|d| d.contains("__declspec(dllexport)")).unwrap_or(false){exports.push((s.va, s.name.clone()));@@ -1895,12 +1910,12 @@ impl GhidrustApp {(imports, exports)}- /// drain queued events and fan them out to subscribers.- ///- /// This is intentionally minimal today: any ProgramMutated event invalidates- /// the Decompiler cache so the next `refresh_decompiler_at` re-runs Stage-0.- /// Cursor events are already handled by their emitters (listing / navigation- /// call sites both refresh the decompiler themselves).+ /// drain queued events and fan them out to subscribers.+ ///+ /// This is intentionally minimal today: any ProgramMutated event invalidates+ /// the Decompiler cache so the next `refresh_decompiler_at` re-runs Stage-0.+ /// Cursor events are already handled by their emitters (listing / navigation+ /// call sites both refresh the decompiler themselves).pub fn drain_events(&mut self) -> Vec<GhidrustEvent> {let events = self.event_bus.drain();for ev in &events {@@ -1915,7 +1930,7 @@ impl GhidrustApp {MutationKind::BookmarkAdded { .. } | MutationKind::BookmarkRemoved { .. } => {}},GhidrustEvent::ProgramActivated { name } => {- self.log(format!("Program activated: {name}"));+ self.log(format!("Program activated: {name}"));}GhidrustEvent::CursorMoved { .. } | GhidrustEvent::SelectionChanged { .. } => {}}@@ -1931,53 +1946,50 @@ impl GhidrustApp {self.redo_stack.clear();}- /// Edit → Undo (selection history).+ /// Edit → Undo (selection history).pub fn edit_undo(&mut self) {if let Some(prev) = self.undo_stack.pop() {self.redo_stack.push(self.listing_selection);self.listing_selection = prev;- self.status = "Undo: restored selection".into();+ self.status = "Undo: restored selection".into();self.log(self.status.clone());} else {- self.status = "Nothing to undo".into();+ self.status = "Nothing to undo".into();self.log(self.status.clone());}}- /// Edit → Redo.+ /// Edit → Redo.pub fn edit_redo(&mut self) {if let Some(next) = self.redo_stack.pop() {self.undo_stack.push(self.listing_selection);self.listing_selection = next;- self.status = "Redo: restored selection".into();+ self.status = "Redo: restored selection".into();self.log(self.status.clone());} else {- self.status = "Nothing to redo".into();+ self.status = "Nothing to redo".into();self.log(self.status.clone());}}- /// Edit → Clear Selection.+ /// Edit → Clear Selection.pub fn edit_clear_selection(&mut self) {self.push_selection_undo();self.listing_selection = ListingSelection::clear();- self.status = "Selection cleared".into();+ self.status = "Selection cleared".into();self.log(self.status.clone());}- /// Select → Select All (listing range).+ /// Select → Select All (listing range).pub fn select_all_listing(&mut self) {self.push_selection_undo();self.listing_selection = ListingSelection::all(self.listing.len());- self.status = format!(- "Selected all {} listing instruction(s)",- self.listing.len()- );+ self.status = format!("Selected all {} listing instruction(s)", self.listing.len());self.log(self.status.clone());self.focus_center_tab(DockTab::Listing);}- /// decode arch for name lookup in listing/detail panes.+ /// decode arch for name lookup in listing/detail panes.fn listing_arch(&self) -> Arch {self.decode_opts.resolved_arch()@@ -1990,17 +2002,17 @@ impl GhidrustApp {.unwrap_or_else(|| default_arch_mode().0)}- /// Re-disassemble the listing window at `va` using current decode options.+ /// Re-disassemble the listing window at `va` using current decode options.fn reload_listing_at(&mut self, va: u64) -> Result<(), String> {let prog = self.program.as_ref()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;self.decode_opts.sync_machine_from_program(prog);self.listing_search.arch = self.listing_arch();let result = reload(prog, va, &self.decode_opts)?;if result.insns.is_empty() {- return Err(format!("no instructions at {va:#x}"));+ return Err(format!("no instructions at {va:#x}"));}self.listing = result.insns;if let Some(proj) = &self.project {@@ -2020,21 +2032,18 @@ impl GhidrustApp {};match self.reload_listing_at(va) {Ok(()) => {- self.status = format!(- "Listing reloaded at {va:#x} ({})",- self.listing.len()- );+ self.status = format!("Listing reloaded at {va:#x} ({})", self.listing.len());self.log(self.status.clone());}Err(e) => {- self.status = format!("decode reload: {e}");+ self.status = format!("decode reload: {e}");self.log_error(self.status.clone());}}}- /// Navigation → Go To Address.- /// If `va` is outside the current listing window, re-disassembles 64 insns at `va`.+ /// Navigation → Go To Address.+ /// If `va` is outside the current listing window, re-disassembles 64 insns at `va`.pub fn goto_address_str(&mut self, s: &str) -> Result<(), String> {let va = parse_address(s)?;self.listing_focus_va = Some(va);@@ -2047,14 +2056,14 @@ impl GhidrustApp {end: Some(i),};} else {- // Outside loaded listing (or empty) — re-disassemble at target VA.+ // Outside loaded listing (or empty) — re-disassemble at target VA.let prog = self.program.as_ref()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;let l = reload_for_goto(prog, va, &self.decode_opts).map_err(|e| e.to_string())?;if l.is_empty() {- return Err(format!("no instructions at {va:#x}"));+ return Err(format!("no instructions at {va:#x}"));}self.listing = l;self.push_selection_undo();@@ -2071,12 +2080,12 @@ impl GhidrustApp {source: EventSource::Navigation,location: NavLocation::new(va),});- // Cross-highlight Decompiler line matching the new listing cursor.+ // Cross-highlight Decompiler line matching the new listing cursor.if !self.decomp_lines.is_empty() {self.decomp_cross_line = decomp_line_for_va(&self.decomp_lines, va);}- // Selection Navigation: keep the "current function" in sync with the- // cursor so the Symbol Tree can highlight the enclosing function.+ // Selection Navigation: keep the "current function" in sync with the+ // cursor so the Symbol Tree can highlight the enclosing function.if self.symbol_tree_nav {if let Some(prog) = self.program.as_ref() {self.focused_function_entry = prog@@ -2089,36 +2098,36 @@ impl GhidrustApp {}}- self.status = format!("Go to {va:#x}");+ self.status = format!("Go to {va:#x}");self.log(self.status.clone());Ok(())}- /// Navigation → Go To entry.+ /// Navigation → Go To entry.pub fn goto_entry(&mut self) {self.focus_center_tab(DockTab::Listing);if let Some(prog) = &self.program {if let Some(e) = prog.entry {- let _ = self.goto_address_str(&format!("{e:#x}"));+ let _ = self.goto_address_str(&format!("{e:#x}"));return;}}- self.status = "No entry point".into();+ self.status = "No entry point".into();self.log(self.status.clone());}- /// Search → Memory.+ /// Search → Memory.pub fn run_search_memory(&mut self) -> Result<(), String> {let prog = self.program.as_ref()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;let pat = parse_hex_pattern(&self.search_memory_input)?;self.memory_hits = search_memory(prog, &pat, 500);self.text_hits.clear();self.show_search_results = true;self.status = format!(- "Memory search: {} hit(s) for '{}'",+ "Memory search: {} hit(s) for '{}'",self.memory_hits.len(),self.search_memory_input.trim());@@ -2126,22 +2135,22 @@ impl GhidrustApp {Ok(())}- /// Search → For Scalars.+ /// Search → For Scalars.pub fn run_search_scalars(&mut self) -> Result<(), String> {let min = self.parse_scalar_input(&self.search_scalars_min.clone())- .map_err(|e| format!("min: {e}"))?;+ .map_err(|e| format!("min: {e}"))?;let max = self.parse_scalar_input(&self.search_scalars_max.clone())- .map_err(|e| format!("max: {e}"))?;+ .map_err(|e| format!("max: {e}"))?;if min > max {- return Err("min > max".into());+ return Err("min > max".into());}self.text_hits = search_scalars(&self.listing, min, max, 1000);self.memory_hits.clear();self.show_search_results = true;self.status = format!(- "Scalar search [{min}, {max}]: {} hit(s)",+ "Scalar search [{min}, {max}]: {} hit(s)",self.text_hits.len());self.log(self.status.clone());@@ -2151,28 +2160,29 @@ impl GhidrustApp {fn parse_scalar_input(&self, s: &str) -> Result<i64, String> {let t = s.trim();if t.is_empty() {- return Err("empty".into());+ return Err("empty".into());}- let (sign, rest) = if let Some(r) = t.strip_prefix('-') {+ let (sign, rest) = if let Some(r) = t.strip_prefix('-') {(-1i64, r)} else {(1i64, t)};- // `0x…` prefix wins → hex. Otherwise prefer decimal to preserve- // convention (numeric input without a prefix is decimal).- let (base, digits) = if let Some(r) = rest.strip_prefix("0x").or_else(|| rest.strip_prefix("0X")) {- (16u32, r)- } else {- (10u32, rest)- };+ // `0x…` prefix wins → hex. Otherwise prefer decimal to preserve+ // convention (numeric input without a prefix is decimal).+ let (base, digits) =+ if let Some(r) = rest.strip_prefix("0x").or_else(|| rest.strip_prefix("0X")) {+ (16u32, r)+ } else {+ (10u32, rest)+ };let mag = u64::from_str_radix(digits, base).map_err(|e| e.to_string())?;Ok(sign * mag as i64)}- /// Search → Instruction Patterns.+ /// Search → Instruction Patterns.pub fn run_search_instruction_patterns(&mut self) -> Result<(), String> {if self.listing.is_empty() {- return Err("no listing loaded".into());+ return Err("no listing loaded".into());}self.text_hits = search_instruction_patterns(&self.listing,@@ -2183,7 +2193,7 @@ impl GhidrustApp {self.memory_hits.clear();self.show_search_results = true;self.status = format!(- "Instruction pattern hits: {} for `{} {}`",+ "Instruction pattern hits: {} for `{} {}`",self.text_hits.len(),self.search_insn_mnemonic.trim(),self.search_insn_operands.trim(),@@ -2192,12 +2202,12 @@ impl GhidrustApp {Ok(())}- /// Search → Program Text.+ /// Search → Program Text.pub fn run_search_text(&mut self) -> Result<(), String> {let prog = self.program.as_ref()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;self.text_hits = search_program_text(prog,&self.listing,@@ -2208,7 +2218,7 @@ impl GhidrustApp {self.memory_hits.clear();self.show_search_results = true;self.status = format!(- "Text search: {} hit(s) for '{}'",+ "Text search: {} hit(s) for '{}'",self.text_hits.len(),self.search_text_input.trim());@@ -2256,76 +2266,76 @@ impl GhidrustApp {let rtti_n = self.rtti.classes.len();let str_n = self.strings.len();let list_n = self.listing.len();- format!("{fns} functions · {rtti_n} RTTI · {str_n} strings · {list_n} listing lines")+ format!("{fns} functions · {rtti_n} RTTI · {str_n} strings · {list_n} listing lines")}fn browse_binary_path(&mut self) {if let Some(path) = rfd::FileDialog::new()- .set_title("Open binary (PE / ELF)")- .add_filter("Binaries", &["exe", "dll", "sys", "pe", "elf", "so", "bin"])- .add_filter("All files", &["*"])+ .set_title("Open binary (PE / ELF)")+ .add_filter("Binaries", &["exe", "dll", "sys", "pe", "elf", "so", "bin"])+ .add_filter("All files", &["*"]).pick_file(){self.path_input = path.display().to_string();- self.log(format!("Browsed binary: {}", self.path_input));+ self.log(format!("Browsed binary: {}", self.path_input));}}fn browse_project_dir(&mut self) {if let Some(path) = rfd::FileDialog::new()- .set_title("Select project folder")+ .set_title("Select project folder").pick_folder(){self.project_dir_input = path.display().to_string();- self.log(format!("Browsed project dir: {}", self.project_dir_input));+ self.log(format!("Browsed project dir: {}", self.project_dir_input));}}- /// Browse for a binary and load it immediately (no project required).+ /// Browse for a binary and load it immediately (no project required).fn browse_and_load_binary(&mut self) {self.browse_binary_path();if !self.path_input.trim().is_empty() {if let Err(e) = self.load_binary(self.path_input.clone()) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}}- /// Browse folder then open project at that path.+ /// Browse folder then open project at that path.fn browse_and_open_project(&mut self) {self.browse_project_dir();if !self.project_dir_input.trim().is_empty() {if let Err(e) = self.open_project() {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}}- /// Browse folder then create project there.+ /// Browse folder then create project there.fn browse_and_create_project(&mut self) {self.browse_project_dir();if !self.project_dir_input.trim().is_empty() {if let Err(e) = self.create_project() {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}}- /// Browse binary then import into the open project.+ /// Browse binary then import into the open project.fn browse_and_import(&mut self) {self.browse_binary_path();if !self.path_input.trim().is_empty() {if let Err(e) = self.import_into_project() {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}}- /// Request delete with confirmation (does not delete yet).+ /// Request delete with confirmation (does not delete yet).pub fn request_delete_file(&mut self, id: &str) {let name = self.project@@ -2336,21 +2346,21 @@ impl GhidrustApp {self.pending_delete = Some((id.to_string(), name));}- /// Confirm pending delete: remove from project disk + clear UI if active.+ /// Confirm pending delete: remove from project disk + clear UI if active.pub fn confirm_delete_file(&mut self) -> Result<(), String> {let (id, name) = self.pending_delete.take()- .ok_or_else(|| "no pending delete".to_string())?;+ .ok_or_else(|| "no pending delete".to_string())?;let was_active = self.active_file_id.as_deref() == Some(id.as_str());let entry = {let proj = self.project.as_mut()- .ok_or_else(|| "no project open".to_string())?;+ .ok_or_else(|| "no project open".to_string())?;proj.remove_file(&id).map_err(|e| e.to_string())?};- self.log(format!("Deleted {} (id={})", entry.display_name, entry.id));+ self.log(format!("Deleted {} (id={})", entry.display_name, entry.id));if self.tree_selected_id.as_deref() == Some(id.as_str()) {self.tree_selected_id = None;}@@ -2358,20 +2368,20 @@ impl GhidrustApp {self.program = None;self.listing.clear();self.strings.clear();+ self.crypt_constants.clear();+ self.obfuscated_strings.clear();+ self.crypto_capabilities.clear();self.rtti = RttiReport::default();self.clear_decompiler_cache();- let next = self- .project- .as_ref()- .and_then(|p| p.meta.active_id.clone());+ let next = self.project.as_ref().and_then(|p| p.meta.active_id.clone());self.active_file_id = next.clone();if let Some(next) = next {self.open_project_file(&next)?;} else {- self.status = format!("Deleted {name} — project empty");+ self.status = format!("Deleted {name} — project empty");}} else {- self.status = format!("Deleted {name} from project");+ self.status = format!("Deleted {name} from project");}Ok(())}@@ -2380,11 +2390,11 @@ impl GhidrustApp {self.pending_delete = None;}- /// Project Window–style rows for the Project Tree (testable without a window).+ /// Project Window–style rows for the Project Tree (testable without a window).pub fn project_tree_model(&self) -> Option<ProjectTreeModel> {self.project.as_ref().map(|p| {let mut m = p.tree_rows();- // Reflect GUI active selection if set+ // Reflect GUI active selection if setif let Some(ref aid) = self.active_file_id {for f in &mut m.files {f.active = f.id == *aid;@@ -2394,35 +2404,35 @@ impl GhidrustApp {})}- /// Open binary from project tree selection (same path as file chips).+ /// Open binary from project tree selection (same path as file chips).pub fn open_from_tree(&mut self, id: &str) -> Result<(), String> {self.tree_selected_id = Some(id.to_string());self.open_project_file(id)}- /// Open analysis options dialog for a project-tree file (does not run yet).+ /// Open analysis options dialog for a project-tree file (does not run yet).pub fn analyze_from_tree(&mut self, id: &str) -> Result<(), String> {if self.analysis_job.is_some() {- return Err("analysis already in progress".into());+ return Err("analysis already in progress".into());}self.tree_selected_id = Some(id.to_string());self.pending_analyze_file_id = Some(id.to_string());self.show_analysis_dialog = true;- self.status = "Choose analyzers and options, then Run Analysis".into();+ self.status = "Choose analyzers and options, then Run Analysis".into();Ok(())}- /// Start analysis from dialog selections on a background thread.- /// Progress / console lines are delivered via channel and polled each UI frame.+ /// Start analysis from dialog selections on a background thread.+ /// Progress / console lines are delivered via channel and polled each UI frame.pub fn begin_analysis_job(&mut self) -> Result<(), String> {if self.analysis_job.is_some() {- return Err("analysis already in progress".into());+ return Err("analysis already in progress".into());}if let Some(id) = self.pending_analyze_file_id.take() {self.open_from_tree(&id)?;}if self.program.is_none() {- return Err("no program loaded — open or import a binary first".into());+ return Err("no program loaded — open or import a binary first".into());}let names: Vec<String> = self.analyzer_infos@@ -2432,29 +2442,29 @@ impl GhidrustApp {.map(|(a, _)| a.name.clone()).collect();if names.is_empty() {- return Err("select at least one analyzer".into());+ return Err("select at least one analyzer".into());}- // Bulk mode is applied inside run_analyzers_opts per step when use_gpu.+ // Bulk mode is applied inside run_analyzers_opts per step when use_gpu.let file_label = self.program.as_ref().map(|p| p.name.clone())- .unwrap_or_else(|| "program".into());+ .unwrap_or_else(|| "program".into());let use_gpu = self.use_gpu_experimental;self.log(format!(- "Starting analysis on {file_label}: {} analyzer(s), gpu={}",+ "Starting analysis on {file_label}: {} analyzer(s), gpu={}",names.len(),use_gpu));- self.status = format!("Analyzing {file_label}…");+ self.status = format!("Analyzing {file_label}…");let (msg_tx, msg_rx) = mpsc::channel::<AnalysisWorkerMsg>();- // Hand the program to the worker only after spawn succeeds so a spawn- // failure cannot drop the only Program copy.+ // Hand the program to the worker only after spawn succeeds so a spawn+ // failure cannot drop the only Program copy.let (prog_tx, prog_rx) = mpsc::sync_channel::<Program>(1);let names_worker = names.clone();std::thread::Builder::new()- .name("ghidrust-analysis".into())+ .name("ghidrust-analysis".into()).spawn(move || {let Ok(mut prog) = prog_rx.recv() else {return;@@ -2462,8 +2472,8 @@ impl GhidrustApp {for (index, name) in names_worker.iter().enumerate() {let _ = msg_tx.send(AnalysisWorkerMsg::StepStarted { index });let gpu = use_gpu && analyzer_supports_gpu(name);- // catch_unwind: core GPU paths already catch wgpu panics;- // belt-and-suspenders so the worker always returns the program.+ // catch_unwind: core GPU paths already catch wgpu panics;+ // belt-and-suspenders so the worker always returns the program.let step = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {ghidrust_core::run_analyzers_opts(&mut prog, &[name.as_str()], gpu)}));@@ -2494,14 +2504,11 @@ impl GhidrustApp {}let _ = msg_tx.send(AnalysisWorkerMsg::Done { program: prog });})- .map_err(|e| format!("failed to spawn analysis worker: {e}"))?;+ .map_err(|e| format!("failed to spawn analysis worker: {e}"))?;- let prog = self- .program- .take()- .expect("program checked non-None above");+ let prog = self.program.take().expect("program checked non-None above");if prog_tx.send(prog).is_err() {- return Err("analysis worker exited before receiving program".into());+ return Err("analysis worker exited before receiving program".into());}self.analysis_job = Some(AnalysisJob {@@ -2515,13 +2522,13 @@ impl GhidrustApp {Ok(())}- /// Poll the analysis worker (non-blocking). Call every frame while `analysis_job` is Some.- /// Returns `Ok(true)` when the job has finished and been finalized.+ /// Poll the analysis worker (non-blocking). Call every frame while `analysis_job` is Some.+ /// Returns `Ok(true)` when the job has finished and been finalized.pub fn step_analysis_job(&mut self) -> Result<bool, String> {self.poll_analysis_job(false)}- /// Block until at least one worker message arrives (tests / headless drain).+ /// Block until at least one worker message arrives (tests / headless drain).pub fn step_analysis_job_blocking(&mut self) -> Result<bool, String> {self.poll_analysis_job(true)}@@ -2530,17 +2537,17 @@ impl GhidrustApp {let job = self.analysis_job.as_ref()- .ok_or_else(|| "no analysis job".to_string())?;+ .ok_or_else(|| "no analysis job".to_string())?;if block {match job.rx.recv() {Ok(m) => Ok(Some(m)),- Err(RecvError) => Err("analysis worker disconnected".into()),+ Err(RecvError) => Err("analysis worker disconnected".into()),}} else {match job.rx.try_recv() {Ok(m) => Ok(Some(m)),Err(TryRecvError::Empty) => Ok(None),- Err(TryRecvError::Disconnected) => Err("analysis worker disconnected".into()),+ Err(TryRecvError::Disconnected) => Err("analysis worker disconnected".into()),}}}@@ -2552,7 +2559,7 @@ impl GhidrustApp {if self.apply_analysis_msg(first)? {return Ok(true);}- // Drain any further messages already queued so one frame can catch up.+ // Drain any further messages already queued so one frame can catch up.while let Some(msg) = self.recv_analysis_msg(false)? {if self.apply_analysis_msg(msg)? {return Ok(true);@@ -2561,7 +2568,7 @@ impl GhidrustApp {Ok(false)}- /// Apply one worker message. Returns `Ok(true)` when the job is fully finished.+ /// Apply one worker message. Returns `Ok(true)` when the job is fully finished.fn apply_analysis_msg(&mut self, msg: AnalysisWorkerMsg) -> Result<bool, String> {match msg {AnalysisWorkerMsg::StepStarted { index } => {@@ -2569,12 +2576,8 @@ impl GhidrustApp {job.index = index;let total = job.names.len();let label = job.file_label.clone();- let cur = job- .names- .get(index)- .cloned()- .unwrap_or_else(|| "…".into());- self.status = format!("Analyzing {label} — {}/{total}: {cur}", index + 1);+ let cur = job.names.get(index).cloned().unwrap_or_else(|| "…".into());+ self.status = format!("Analyzing {label} — {}/{total}: {cur}", index + 1);}Ok(false)}@@ -2583,7 +2586,7 @@ impl GhidrustApp {let mut rtti_upd = None;let mut strings_upd = None;for r in &outputs {- log_lines.push(format!("[{}] {} — {}", r.status, r.name, r.message));+ log_lines.push(format!("[{}] {} — {}", r.status, r.name, r.message));if r.rtti.is_some() {rtti_upd = r.rtti.clone();}@@ -2592,9 +2595,9 @@ impl GhidrustApp {}}for line in log_lines {- let sev = if line.starts_with("[error]") {+ let sev = if line.starts_with("[error]") {ConsoleSeverity::Error- } else if line.starts_with("[warn") {+ } else if line.starts_with("[warn") {ConsoleSeverity::Warn} else {ConsoleSeverity::Info@@ -2607,6 +2610,17 @@ impl GhidrustApp {if let Some(s) = strings_upd {self.strings = s;}+ for r in &outputs {+ if let Some(c) = &r.crypt_constants {+ self.crypt_constants = c.clone();+ }+ if let Some(o) = &r.obfuscated_strings {+ self.obfuscated_strings = o.clone();+ }+ if let Some(c) = &r.crypto_capabilities {+ self.crypto_capabilities = c.clone();+ }+ }if let Some(job) = self.analysis_job.as_mut() {job.results.results.extend(outputs);job.index = index + 1;@@ -2631,7 +2645,7 @@ impl GhidrustApp {let job = self.analysis_job.take()- .ok_or_else(|| "no analysis job".to_string())?;+ .ok_or_else(|| "no analysis job".to_string())?;if let Some(prog) = self.program.as_ref() {let entry = default_start_va(prog, self.listing_focus_va);if let Ok(result) = reload(prog, entry, &self.decode_opts) {@@ -2639,11 +2653,31 @@ impl GhidrustApp {}self.rtti = prog.rtti.clone();}- // Capture strings from this run's results+ // Capture strings from this run's resultsfor r in &job.results.results {if let Some(ref s) = r.strings {self.strings = s.clone();}+ if let Some(ref c) = r.crypt_constants {+ self.crypt_constants = c.clone();+ }+ if let Some(ref o) = r.obfuscated_strings {+ self.obfuscated_strings = o.clone();+ }+ if let Some(ref c) = r.crypto_capabilities {+ self.crypto_capabilities = c.clone();+ }+ }+ if let Some(prog) = self.program.as_ref() {+ if self.crypt_constants.is_empty() {+ self.crypt_constants = prog.analysis.crypt_constants.clone();+ }+ if self.obfuscated_strings.is_empty() {+ self.obfuscated_strings = prog.analysis.obfuscated_strings.clone();+ }+ if self.crypto_capabilities.is_empty() {+ self.crypto_capabilities = prog.analysis.crypto_capabilities.clone();+ }}self.rtti_filter.clear();self.rtti_filter_cache.clear();@@ -2654,12 +2688,12 @@ impl GhidrustApp {self.last_analysis = job.results;let summary = self.analysis_summary_line();let banner = format!(- "Analysis complete on {} — {n} analyzer(s) · {summary}{}",+ "Analysis complete on {} — {n} analyzer(s) · {summary}{}",job.file_label,if job.use_gpu {- " · GPU experimental"+ " · GPU experimental"} else {- ""+ ""});self.analysis_done_banner = Some(banner.clone());@@ -2667,11 +2701,11 @@ impl GhidrustApp {self.log(banner);if self.project.is_some() && self.active_file_id.is_some() {let _ = self.save_results();- self.log("Results saved to project (results/ + exports/).");+ self.log("Results saved to project (results/ + exports/).");}self.focus_center_tab(DockTab::Overview);self.show_symbol_tree = true;- // Function list / names may have changed — drop cache and re-seed Stage-0.+ // Function list / names may have changed — drop cache and re-seed Stage-0.self.clear_decompiler_cache();if let Some(va) = self.listing_focus_va@@ -2680,7 +2714,7 @@ impl GhidrustApp {{self.refresh_decompiler_at(va);}- // Restore default bulk mode after experimental run+ // Restore default bulk mode after experimental runset_preferred_bulk_mode(BulkScanMode::ParallelCpu);Ok(())}@@ -2716,7 +2750,7 @@ impl GhidrustApp {v.hyperlink_color = rgb(t.primary);v.warn_fg_color = rgb(t.error);ctx.set_visuals(v);- // Wider side/top grab for resizable panels (bottom console drag).+ // Wider side/top grab for resizable panels (bottom console drag).ctx.style_mut(|s| {s.interaction.resize_grab_radius_side = 12.0;});@@ -2737,12 +2771,12 @@ impl GhidrustApp {.map(|r| r.insns).unwrap_or_default();self.log(format!(- "Loaded {} ({}) base={:#x}",+ "Loaded {} ({}) base={:#x}",prog.name, prog.format, prog.image_base));let prog_name = prog.name.clone();self.status = format!(- "Loaded {} — {} sections, {} listing insns",+ "Loaded {} — {} sections, {} listing insns",prog.name,prog.sections.len(),listing.len()@@ -2751,12 +2785,21 @@ impl GhidrustApp {self.listing = listing;self.rtti = RttiReport::default();self.strings.clear();+ self.crypt_constants.clear();+ self.obfuscated_strings.clear();+ self.crypto_capabilities.clear();self.last_analysis = AnalysisRunReport::default();self.last_analyzers_run.clear();self.clear_decompiler_cache();self.nav_history.clear();- self.event_bus.publish(GhidrustEvent::ProgramActivated { name: prog_name });- if let Some(va) = self.listing.first().map(|i| i.address).or(self.listing_focus_va) {+ self.event_bus+ .publish(GhidrustEvent::ProgramActivated { name: prog_name });+ if let Some(va) = self+ .listing+ .first()+ .map(|i| i.address)+ .or(self.listing_focus_va)+ {self.refresh_decompiler_at(va);}Ok(())@@ -2765,16 +2808,20 @@ impl GhidrustApp {pub fn create_project(&mut self) -> Result<(), String> {let dir = self.project_dir_input.trim().to_string();if dir.is_empty() {- return Err("set Project dir path first".into());+ return Err("set Project dir path first".into());}let name = if self.project_name_input.trim().is_empty() {- "MyProject".into()+ "MyProject".into()} else {self.project_name_input.trim().to_string()};let p = Project::create(&dir, name).map_err(|e| e.to_string())?;- self.log(format!("Created project '{}' at {}", p.meta.name, p.root.display()));- self.status = format!("Project open: {}", p.root.display());+ self.log(format!(+ "Created project '{}' at {}",+ p.meta.name,+ p.root.display()+ ));+ self.status = format!("Project open: {}", p.root.display());self.remember_project(&dir);self.show_startup_picker = false;self.project = Some(p);@@ -2787,7 +2834,7 @@ impl GhidrustApp {pub fn open_project(&mut self) -> Result<(), String> {let dir = self.project_dir_input.trim().to_string();if dir.is_empty() {- return Err("set Project dir path first".into());+ return Err("set Project dir path first".into());}let p = Project::open(&dir).map_err(|e| e.to_string())?;self.project_name_input = p.meta.name.clone();@@ -2796,14 +2843,14 @@ impl GhidrustApp {self.decode_opts = opts;}self.log(format!(- "Opened project '{}' ({} files)",+ "Opened project '{}' ({} files)",p.meta.name,p.meta.files.len()));- self.status = format!("Project open: {}", p.root.display());+ self.status = format!("Project open: {}", p.root.display());self.remember_project(&dir);self.show_startup_picker = false;- // Auto-open active file if any+ // Auto-open active file if anyif let Some(id) = p.meta.active_id.clone() {self.project = Some(p);self.ensure_project_skill_wired();@@ -2815,20 +2862,16 @@ impl GhidrustApp {Ok(())}- /// Auto-install embedded (or workspace) skill into the open project so the- /// Grok Start checklist Skill row is green before the user clicks Start.+ /// Auto-install embedded (or workspace) skill into the open project so the+ /// Grok Start checklist Skill row is green before the user clicks Start.fn ensure_project_skill_wired(&mut self) {let Some(root) = self.project.as_ref().map(|p| p.root.clone()) else {return;};let (_body, skill_source) = load_skill_body();- // Reset so a new project root always re-attempts wire.+ // Reset so a new project root always re-attempts wire.self.grok_pane.skill_wired_root = None;- agent_pane::ensure_skill_for_project(- &mut self.grok_pane,- &root,- skill_source.as_deref(),- );+ agent_pane::ensure_skill_for_project(&mut self.grok_pane, &root, skill_source.as_deref());if let Some(err) = &self.grok_pane.skill_wire_error {self.log_error(err.clone());} else if let Some(path) = self@@ -2836,22 +2879,22 @@ impl GhidrustApp {.as_ref().map(|p| ghidrust_agent::project_skill_path(&p.root)){- self.log(format!("Agent skill ready at {}", path.display()));+ self.log(format!("Agent skill ready at {}", path.display()));}}pub fn import_into_project(&mut self) -> Result<(), String> {let path = self.path_input.trim();if path.is_empty() {- return Err("set binary path first".into());+ return Err("set binary path first".into());}let proj = self.project.as_mut()- .ok_or_else(|| "no project open — create or open one first".to_string())?;+ .ok_or_else(|| "no project open — create or open one first".to_string())?;let entry = proj.import_file(path).map_err(|e| e.to_string())?;self.active_file_id = Some(entry.id.clone());- self.log(format!("Imported {} (id={})", entry.display_name, entry.id));+ self.log(format!("Imported {} (id={})", entry.display_name, entry.id));let id = entry.id.clone();self.open_project_file(&id)}@@ -2861,23 +2904,23 @@ impl GhidrustApp {let proj = self.project.as_ref()- .ok_or_else(|| "no project".to_string())?;+ .ok_or_else(|| "no project".to_string())?;proj.meta.files.iter().find(|f| f.id == id)- .ok_or_else(|| format!("unknown file id {id}"))?+ .ok_or_else(|| format!("unknown file id {id}"))?.clone()};let display = entry.display_name.clone();- self.status = format!("Loading {display}…");- self.log(format!("Loading {display} (saved results if any)…"));+ self.status = format!("Loading {display}…");+ self.log(format!("Loading {display} (saved results if any)…"));let (prog, saved, has_saved, bin_path) = {let proj = self.project.as_ref()- .ok_or_else(|| "no project".to_string())?;+ .ok_or_else(|| "no project".to_string())?;let has_saved = proj.has_saved_analysis(&entry.id);let bin_path = proj.binary_path(&entry).display().to_string();let (prog, saved) = proj@@ -2900,7 +2943,7 @@ impl GhidrustApp {let listing = reload(&prog, start_va, &self.decode_opts).map(|r| r.insns).unwrap_or_default();- // Strings: session last_analysis only (full rescan is Analyze opt-in on large games).+ // Strings: session last_analysis only (full rescan is Analyze opt-in on large games).if let Some(s) = self.last_analysis.results@@ -2910,6 +2953,9 @@ impl GhidrustApp {self.strings = s;} else {self.strings.clear();+ self.crypt_constants.clear();+ self.obfuscated_strings.clear();+ self.crypto_capabilities.clear();}self.rtti = prog.rtti.clone();self.rtti_filter.clear();@@ -2925,12 +2971,12 @@ impl GhidrustApp {let rtti_n = self.rtti.classes.len();let fn_n = prog.analysis.functions.len();self.status = format!(- "Opened {display} — {fn_n} functions · {rtti_n} RTTI · {} listing lines{}",+ "Opened {display} — {fn_n} functions · {rtti_n} RTTI · {} listing lines{}",listing.len(),if has_saved {- " · analysis on disk"+ " · analysis on disk"} else {- " · not analyzed yet"+ " · not analyzed yet"});self.log(self.status.clone());@@ -2957,16 +3003,16 @@ impl GhidrustApp {let id = self.active_file_id.clone()- .ok_or_else(|| "no active project file — import a binary into a project".to_string())?;+ .ok_or_else(|| "no active project file — import a binary into a project".to_string())?;let prog = self.program.as_ref()- .ok_or_else(|| "no program loaded".to_string())?;+ .ok_or_else(|| "no program loaded".to_string())?;let (analysis_path, listing_path, saved) = {let proj = self.project.as_ref()- .ok_or_else(|| "no project open".to_string())?;+ .ok_or_else(|| "no project open".to_string())?;let saved = proj.save_program_results(&id, prog, &self.listing, &self.last_analyzers_run).map_err(|e| e.to_string())?;@@ -2976,10 +3022,10 @@ impl GhidrustApp {saved,)};- self.log(format!("Saved analysis → {analysis_path}"));- self.log(format!("Listing export → {listing_path}"));+ self.log(format!("Saved analysis → {analysis_path}"));+ self.log(format!("Listing export → {listing_path}"));self.status = format!(- "Saved {} ({} functions, {} insns)",+ "Saved {} ({} functions, {} insns)",id,saved.analysis.functions.len(),saved.listing.len()@@ -2987,7 +3033,7 @@ impl GhidrustApp {Ok(())}- /// Headless/sync: begin job and drain all worker messages (tests + non-UI callers).+ /// Headless/sync: begin job and drain all worker messages (tests + non-UI callers).pub fn run_selected_analysis(&mut self) -> Result<(), String> {self.begin_analysis_job()?;while self.analysis_job.is_some() {@@ -3000,12 +3046,12 @@ impl GhidrustApp {self.log_with(msg, ConsoleSeverity::Info);}- /// Console warning (amber tint).+ /// Console warning (amber tint).fn log_warn(&mut self, msg: impl Into<String>) {self.log_with(msg, ConsoleSeverity::Warn);}- /// Console error (red tint).+ /// Console error (red tint).fn log_error(&mut self, msg: impl Into<String>) {self.log_with(msg, ConsoleSeverity::Error);}@@ -3014,14 +3060,14 @@ impl GhidrustApp {let text = msg.into();self.console.push(text);self.console_severity.push(sev);- // Keep both vectors in lockstep and bounded.+ // Keep both vectors in lockstep and bounded.if self.console.len() > 200 {let drop = self.console.len() - 200;self.console.drain(0..drop);self.console_severity.drain(0..drop);}- // Backfill severity vector if it drifts (only happens if callers used- // `self.console.push` directly; guard against future regressions).+ // Backfill severity vector if it drifts (only happens if callers used+ // `self.console.push` directly; guard against future regressions).while self.console_severity.len() < self.console.len() {self.console_severity.push(ConsoleSeverity::Info);}@@ -3029,39 +3075,37 @@ impl GhidrustApp {#[allow(dead_code)] // kept for non-menubar future stubs; menubar stubs are wiredfn nyi(&mut self, what: &str) {- let m = format!("Not yet implemented: {what}");+ let m = format!("Not yet implemented: {what}");self.status = m.clone();self.nyi_note = Some(m.clone());self.log(m);}- /// Render the bottom-dock tabbed panel — `Grok` (embedded TUI) + `Console`.+ /// Render the bottom-dock tabbed panel — `Grok` (embedded TUI) + `Console`.fn render_bottom_dock(&mut self, ui: &mut egui::Ui) {use agent_pane::BottomTab;ui.horizontal(|ui| {let grok_selected = self.grok_pane.tab == BottomTab::Grok;let console_selected = self.grok_pane.tab == BottomTab::Console;- if ui.selectable_label(grok_selected, "Grok").clicked() {+ if ui.selectable_label(grok_selected, "Grok").clicked() {self.grok_pane.tab = BottomTab::Grok;}- if ui.selectable_label(console_selected, "Console").clicked() {+ if ui.selectable_label(console_selected, "Console").clicked() {self.grok_pane.tab = BottomTab::Console;}ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if self.grok_pane.tab == BottomTab::Console- && ui.small_button("Clear").clicked()- {+ if self.grok_pane.tab == BottomTab::Console && ui.small_button("Clear").clicked() {self.console.clear();self.console_severity.clear();}- ui.small(egui::RichText::new("drag top edge ↕").weak().small());+ ui.small(egui::RichText::new("drag top edge ↕").weak().small());});});ui.separator();match self.grok_pane.tab {BottomTab::Grok => self.render_grok_tab(ui),BottomTab::Console => {- // Leaving the TUI — release keyboard so listing hotkeys work again.+ // Leaving the TUI — release keyboard so listing hotkeys work again.self.grok_pane.keyboard_captured = false;self.render_console_tab(ui);}@@ -3086,12 +3130,12 @@ impl GhidrustApp {ConsoleSeverity::Error => Color32::from_rgb(0xE5, 0x39, 0x35),};let prefix = match sev {- ConsoleSeverity::Info => " ",- ConsoleSeverity::Warn => "! ",- ConsoleSeverity::Error => "× ",+ ConsoleSeverity::Info => " ",+ ConsoleSeverity::Warn => "! ",+ ConsoleSeverity::Error => "× ",};ui.label(- egui::RichText::new(format!("{prefix}{}", self.console[i]))+ egui::RichText::new(format!("{prefix}{}", self.console[i])).monospace().color(color),);@@ -3146,8 +3190,8 @@ impl GhidrustApp {if do_rescan {self.grok_pane.refresh_grok_binary();let msg = match &self.grok_pane.grok_bin {- Some(p) => format!("Found grok at {}", p.display()),- None => "grok not found on PATH — install first".into(),+ Some(p) => format!("Found grok at {}", p.display()),+ None => "grok not found on PATH — install first".into(),};self.log(msg);}@@ -3155,12 +3199,12 @@ impl GhidrustApp {if let Some(bin) = self.grok_pane.grok_bin.clone() {match ghidrust_agent::probe_grok_version(&bin) {Ok(v) => {- self.log(format!("grok -version → {v}"));+ self.log(format!("grok -version → {v}"));self.grok_pane.version_probe = Some(v);}Err(e) => {- self.grok_pane.version_probe = Some(format!("(error) {e}"));- self.log_warn(format!("grok -version failed: {e}"));+ self.grok_pane.version_probe = Some(format!("(error) {e}"));+ self.log_warn(format!("grok -version failed: {e}"));}}}@@ -3172,16 +3216,16 @@ impl GhidrustApp {}if let Some(e) = start_err {self.grok_pane.last_error = Some(e.clone());- self.log_error(format!("Grok TUI failed: {e}"));+ self.log_error(format!("Grok TUI failed: {e}"));}}- /// Build the current program-facts snapshot for the Grok pane.- ///- /// This is what makes the agent actually *know* about the open project- /// and the currently-loaded file without needing an MCP round-trip first.- /// Every field is honest-empty when the underlying analysis hasn't run —- /// matches Ghidrust's "no fabrication on empty evidence" rule.+ /// Build the current program-facts snapshot for the Grok pane.+ ///+ /// This is what makes the agent actually *know* about the open project+ /// and the currently-loaded file without needing an MCP round-trip first.+ /// Every field is honest-empty when the underlying analysis hasn't run —+ /// matches Ghidrust's "no fabrication on empty evidence" rule.fn grok_program_facts(&self) -> ghidrust_agent::ProgramFacts {const TOP_FN_SAMPLE: usize = 24;const IMPORT_SAMPLE: usize = 24;@@ -3192,7 +3236,7 @@ impl GhidrustApp {f.project_root = Some(proj.root.display().to_string());for file in &proj.meta.files {let has_saved = proj.results_dir().join(&file.id).exists()- || proj.results_dir().join(format!("{}.bin", file.id)).exists();+ || proj.results_dir().join(format!("{}.bin", file.id)).exists();f.project_files.push(ghidrust_agent::ProjectFileFact {id: file.id.clone(),display_name: file.display_name.clone(),@@ -3204,21 +3248,21 @@ impl GhidrustApp {if let Some(prog) = &self.program {f.program = Some(prog.name.clone());f.format = Some(prog.format.clone());- f.arch = Some("x86_64".into());- f.image_base = Some(format!("{:#x}", prog.image_base));- f.entry_va = prog.entry.map(|v| format!("{v:#x}"));+ f.arch = Some("x86_64".into());+ f.image_base = Some(format!("{:#x}", prog.image_base));+ f.entry_va = prog.entry.map(|v| format!("{v:#x}"));f.functions = Some(prog.analysis.functions.len());f.strings = Some(self.strings.len());for s in &prog.sections {f.sections.push(ghidrust_agent::SectionFact {name: s.name.clone(),- va: format!("{:#x}", s.va),+ va: format!("{:#x}", s.va),size: s.virtual_size,});}for fi in prog.analysis.functions.iter().take(TOP_FN_SAMPLE) {f.top_functions.push(ghidrust_agent::FunctionFact {- va: format!("{:#x}", fi.entry),+ va: format!("{:#x}", fi.entry),name: fi.name.clone(),});}@@ -3238,47 +3282,37 @@ impl GhidrustApp {.as_ref().and_then(|p| p.display_function_name_at(va));f.current_selection = Some(ghidrust_agent::SelectionFact {- va: format!("{va:#x}"),+ va: format!("{va:#x}"),name,});}f}- /// Write MCP/skill/context and spawn the real Grok TUI in the PTY pane.- fn start_grok_pty(- &mut self,- cols: u16,- rows: u16,- ctx: egui::Context,- ) -> Result<(), String> {+ /// Write MCP/skill/context and spawn the real Grok TUI in the PTY pane.+ fn start_grok_pty(&mut self, cols: u16, rows: u16, ctx: egui::Context) -> Result<(), String> {self.grok_pane.last_error = None;- let bin = self- .grok_pane- .grok_bin- .clone()- .ok_or_else(|| {- "grok binary not installed — click 'Install Grok Build…' first".to_string()- })?;+ let bin = self.grok_pane.grok_bin.clone().ok_or_else(|| {+ "grok binary not installed — click 'Install Grok Build…' first".to_string()+ })?;let project_root: std::path::PathBuf = match &self.project {Some(p) => p.root.clone(),- None => std::env::current_dir()- .unwrap_or_else(|_| std::path::PathBuf::from(".")),+ None => std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")),};let ghidrust_bin = ghidrust_agent::resolve_ghidrust_cli_bin().ok_or_else(|| {- "ghidrust CLI not found next to the GUI or on PATH — build `ghidrust` \+ "ghidrust CLI not found next to the GUI or on PATH — build `ghidrust` \(cargo build -p ghidrust-cli -release) so MCP can start".to_string()})?;if !ghidrust_bin.is_file() {return Err(format!(- "ghidrust CLI missing at {} — MCP cannot start",+ "ghidrust CLI missing at {} — MCP cannot start",ghidrust_bin.display()));}let (_skill_body, skill_source) = load_skill_body();let facts = self.grok_program_facts();- // Drop any prior session before spawning a new one.+ // Drop any prior session before spawning a new one.self.grok_pane.session = None;let session = agent_pane::start_pty_session(&bin,@@ -3291,7 +3325,7 @@ impl GhidrustApp {rows,)?;self.log(format!(- "Grok TUI started · project={} · grok={} · mcp={}",+ "Grok TUI started · project={} · grok={} · mcp={}",project_root.display(),bin.display(),ghidrust_bin.display()@@ -3303,10 +3337,10 @@ impl GhidrustApp {Ok(())}- /// Analysis → GPU Decompile… — resolve the dialog's address (containing- /// function honesty via `resolve_function`) then run- /// `ghidrust_decomp::gpu_decompile_to_file` (GPU pipeline with automatic- /// CPU multipass fallback outside the `gpu` feature).+ /// Analysis → GPU Decompile… — resolve the dialog's address (containing+ /// function honesty via `resolve_function`) then run+ /// `ghidrust_decomp::gpu_decompile_to_file` (GPU pipeline with automatic+ /// CPU multipass fallback outside the `gpu` feature).fn run_gpu_decompile_dialog(&mut self) {let dialog = &mut self.tool_panes.gpu_decompile;dialog.error = None;@@ -3315,7 +3349,7 @@ impl GhidrustApp {let max_bytes: usize = dialog.max_bytes_input.trim().parse().unwrap_or(256).max(32);let addr_input = dialog.addr_input.trim().to_string();let Some(prog) = self.program.as_mut() else {- self.tool_panes.gpu_decompile.error = Some("no program loaded".into());+ self.tool_panes.gpu_decompile.error = Some("no program loaded".into());return;};let addr = if addr_input.is_empty() {@@ -3324,7 +3358,7 @@ impl GhidrustApp {match parse_address(&addr_input) {Ok(a) => a,Err(e) => {- self.tool_panes.gpu_decompile.error = Some(format!("bad address: {e}"));+ self.tool_panes.gpu_decompile.error = Some(format!("bad address: {e}"));return;}}@@ -3332,18 +3366,19 @@ impl GhidrustApp {let resolve = match ghidrust_core::resolve_function(prog, addr) {Ok(r) => r,Err(e) => {- self.tool_panes.gpu_decompile.error = Some(format!("resolve_function: {e}"));+ self.tool_panes.gpu_decompile.error = Some(format!("resolve_function: {e}"));return;}};if !resolve.ok {self.tool_panes.gpu_decompile.resolve = Some(resolve);self.tool_panes.gpu_decompile.error =- Some("address did not resolve to a function — see resolve_status above".into());+ Some("address did not resolve to a function — see resolve_status above".into());return;}let entry = resolve.resolved_entry.unwrap_or(addr);- let dump_path = std::env::temp_dir().join(format!("ghidrust-gpu-decompile-{entry:016x}.txt"));+ let dump_path =+ std::env::temp_dir().join(format!("ghidrust-gpu-decompile-{entry:016x}.txt"));match ghidrust_decomp::gpu_decompile_to_file(prog, Some(entry), &dump_path, max_bytes) {Ok(rep) => {let preview: String = rep.pseudo_c.chars().take(4000).collect();@@ -3365,53 +3400,59 @@ impl GhidrustApp {});self.tool_panes.gpu_decompile.resolve = Some(resolve);self.log(format!(- "GPU Decompile · {:#x} · backend={}",- entry, self.tool_panes.gpu_decompile.summary.as_ref().unwrap().backend+ "GPU Decompile · {:#x} · backend={}",+ entry,+ self.tool_panes+ .gpu_decompile+ .summary+ .as_ref()+ .unwrap()+ .backend));}Err(e) => {self.tool_panes.gpu_decompile.resolve = Some(resolve);- self.tool_panes.gpu_decompile.error = Some(format!("gpu_decompile_to_file: {e}"));+ self.tool_panes.gpu_decompile.error = Some(format!("gpu_decompile_to_file: {e}"));}}}- /// Menu / pane identifiers present in the shell (for structural tests).- ///- /// top-level menus (from `docking.tool.ToolConstants`):- /// File, Edit, Analysis, Navigation, Search, Select, Tools, Graph, Window, Help.- pub fn shell_menus() -> &'static [&'static str] {+ /// Menu / pane identifiers present in the shell (for structural tests).+ ///+ /// top-level menus (from `docking.tool.ToolConstants`):+ /// File, Edit, Analysis, Navigation, Search, Select, Tools, Graph, Window, Help.+ pub fn shell_menus() -> &'static [&'static str] {&[- "File",- "Edit",- "Analysis",- "Navigation",- "Search",- "Select",- "Tools",- "Graph",- "Window",- "Debugger",- "Help",+ "File",+ "Edit",+ "Analysis",+ "Navigation",+ "Search",+ "Select",+ "Tools",+ "Graph",+ "Window",+ "Debugger",+ "Help",]}- /// Every provider ( + off-layout) enumerated for visibility tests.- ///- /// Ghidrust panes use these exact labels for the Window menu and the structural test.- /// See `panes::PaneKind::ALL` for the source of truth; a stable Vec is materialized- /// on demand to keep the API `&'static [&'static str]`-like for existing tests.- pub fn shell_panes() -> Vec<&'static str> {- // Legacy names kept for backwards compat with previous test assertions.- let mut names: Vec<&'static str> = vec![- "Project Tree",- "Program Tree", // legacy short name .- "Symbol Tree",- "Overview",- "Listing",- "Decompiler", // legacy short name .- "Data Type Manager",- "Console",+ /// Every provider ( + off-layout) enumerated for visibility tests.+ ///+ /// Ghidrust panes use these exact labels for the Window menu and the structural test.+ /// See `panes::PaneKind::ALL` for the source of truth; a stable Vec is materialized+ /// on demand to keep the API `&'static [&'static str]`-like for existing tests.+ pub fn shell_panes() -> Vec<&'static str> {+ // Legacy names kept for backwards compat with previous test assertions.+ let mut names: Vec<&'static str> = vec![+ "Project Tree",+ "Program Tree", // legacy short name .+ "Symbol Tree",+ "Overview",+ "Listing",+ "Decompiler", // legacy short name .+ "Data Type Manager",+ "Console",];for k in PaneKind::ALL {let t = k.title();@@ -3419,9 +3460,9 @@ impl GhidrustApp {names.push(t);}}- // Single tabbed Debugger host .- if !names.contains(&"Debugger") {- names.push("Debugger");+ // Single tabbed Debugger host .+ if !names.contains(&"Debugger") {+ names.push("Debugger");}names}@@ -3429,21 +3470,26 @@ impl GhidrustApp {fn ui_startup_picker(&mut self, ctx: &egui::Context) {let t = m3_tokens(self.theme);let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);- let muted =- Color32::from_rgb(t.on_surface_variant[0], t.on_surface_variant[1], t.on_surface_variant[2]);- let surface = Color32::from_rgb(t.surface_container[0], t.surface_container[1], t.surface_container[2]);+ let muted = Color32::from_rgb(+ t.on_surface_variant[0],+ t.on_surface_variant[1],+ t.on_surface_variant[2],+ );+ let surface = Color32::from_rgb(+ t.surface_container[0],+ t.surface_container[1],+ t.surface_container[2],+ );- // Fixed card size — never wider than the window, never stretch off-screen.- let card_w = 440.0_f32- .min(ctx.screen_rect().width() - 48.0)- .max(280.0);+ // Fixed card size — never wider than the window, never stretch off-screen.+ let card_w = 440.0_f32.min(ctx.screen_rect().width() - 48.0).max(280.0);egui::CentralPanel::default().show(ctx, |ui| {ui.vertical_centered(|ui| {ui.add_space(32.0);- ui.heading(egui::RichText::new("Ghidrust").size(26.0).color(primary));+ ui.heading(egui::RichText::new("Ghidrust").size(26.0).color(primary));ui.label(- egui::RichText::new("Open a project to reverse engineer")+ egui::RichText::new("Open a project to reverse engineer").color(muted).size(14.0),);@@ -3457,8 +3503,8 @@ impl GhidrustApp {ui.set_width(card_w);ui.set_max_width(card_w);- // ── Recent projects (IDE-style list) ──- ui.label(egui::RichText::new("Recent projects").strong().size(13.0));+ // ── Recent projects (IDE-style list) ──+ ui.label(egui::RichText::new("Recent projects").strong().size(13.0));ui.add_space(6.0);let recents = self.recent_projects.clone();@@ -3471,14 +3517,16 @@ impl GhidrustApp {.show(ui, |ui| {ui.set_width(card_w - 8.0);egui::ScrollArea::vertical()- .id_salt("startup_recent")+ .id_salt("startup_recent").max_height(list_h).auto_shrink([false, false]).show(ui, |ui| {ui.set_min_width(card_w - 24.0);if recents.is_empty() {ui.add_space(8.0);- ui.weak("No recent projects — open or create one below.");+ ui.weak(+ "No recent projects — open or create one below.",+ );ui.add_space(8.0);} else {let mut open_path: Option<String> = None;@@ -3487,7 +3535,7 @@ impl GhidrustApp {.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| path.clone());- // IDE-style row: project name + path, full-width click+ // IDE-style row: project name + path, full-width clicklet row_w = (card_w - 24.0).max(200.0);let row_h = 44.0;let (rect, resp) = ui.allocate_exact_size(@@ -3503,8 +3551,12 @@ impl GhidrustApp {}let mut child = ui.new_child(egui::UiBuilder::new()- .max_rect(rect.shrink2(egui::vec2(10.0, 6.0)))- .layout(egui::Layout::top_down(egui::Align::LEFT)),+ .max_rect(+ rect.shrink2(egui::vec2(10.0, 6.0)),+ )+ .layout(egui::Layout::top_down(+ egui::Align::LEFT,+ )),);child.label(egui::RichText::new(&name)@@ -3518,12 +3570,12 @@ impl GhidrustApp {if resp.clicked() {open_path = Some(path.clone());}- resp.on_hover_text(format!("Open project: {path}"));+ resp.on_hover_text(format!("Open project: {path}"));}if let Some(path) = open_path {self.project_dir_input = path;if let Err(e) = self.open_project() {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());self.show_startup_picker = true;}@@ -3536,13 +3588,10 @@ impl GhidrustApp {ui.separator();ui.add_space(10.0);- // Buttons fit card width only (no off-screen stretch)+ // Buttons fit card width only (no off-screen stretch)let btn_w = card_w - 8.0;if ui- .add_sized(- [btn_w, 32.0],- egui::Button::new("Open existing project…"),- )+ .add_sized([btn_w, 32.0], egui::Button::new("Open existing project…")).clicked(){self.browse_and_open_project();@@ -3552,16 +3601,16 @@ impl GhidrustApp {}ui.add_space(8.0);ui.horizontal(|ui| {- ui.label("Name:");+ ui.label("Name:");ui.add(egui::TextEdit::singleline(&mut self.project_name_input).desired_width((btn_w - 56.0).max(120.0))- .hint_text("MyProject"),+ .hint_text("MyProject"),);});ui.add_space(4.0);if ui- .add_sized([btn_w, 32.0], egui::Button::new("Create new project…"))+ .add_sized([btn_w, 32.0], egui::Button::new("Create new project…")).clicked(){self.browse_and_create_project();@@ -3570,10 +3619,10 @@ impl GhidrustApp {}}ui.add_space(12.0);- if ui.link("Continue without a project").clicked() {+ if ui.link("Continue without a project").clicked() {self.show_startup_picker = false;self.status =- "No project — Browse/Load a binary, or File → Open Project".into();+ "No project — Browse/Load a binary, or File → Open Project".into();}ui.add_space(4.0);ui.small(@@ -3590,15 +3639,18 @@ impl GhidrustApp {fn ui_overview(&mut self, ui: &mut egui::Ui) {let t = m3_tokens(self.theme);let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);- let muted =- Color32::from_rgb(t.on_surface_variant[0], t.on_surface_variant[1], t.on_surface_variant[2]);+ let muted = Color32::from_rgb(+ t.on_surface_variant[0],+ t.on_surface_variant[1],+ t.on_surface_variant[2],+ );let ok = Color32::from_rgb(0x4C, 0xAF, 0x50);- ui.heading("Overview");+ ui.heading("Overview");let Some(prog) = self.program.as_ref() else {- ui.weak("No program open.");- ui.label("Project Tree: double-click a file (or Open) to load it into this view.");- ui.label("If the file is Analyzed, RTTI / functions load from results/ automatically.");+ ui.weak("No program open.");+ ui.label("Project Tree: double-click a file (or Open) to load it into this view.");+ ui.label("If the file is Analyzed, RTTI / functions load from results/ automatically.");return;};@@ -3610,14 +3662,17 @@ impl GhidrustApp {status_badge(ui, false, ok, muted);}});- ui.label(egui::RichText::new(format!(- "{} · image base {:#x}{}",- prog.format,- prog.image_base,- prog.entry- .map(|e| format!(" · entry {e:#x}"))- .unwrap_or_default()- )).color(muted));+ ui.label(+ egui::RichText::new(format!(+ "{} · image base {:#x}{}",+ prog.format,+ prog.image_base,+ prog.entry+ .map(|e| format!(" · entry {e:#x}"))+ .unwrap_or_default()+ ))+ .color(muted),+ );ui.add_space(8.0);ui.horizontal(|ui| {@@ -3625,31 +3680,40 @@ impl GhidrustApp {ui.group(|ui| {ui.set_min_width(120.0);ui.label(egui::RichText::new(title).small().color(muted));- ui.label(egui::RichText::new(value).strong().color(primary).size(18.0));+ ui.label(+ egui::RichText::new(value)+ .strong()+ .color(primary)+ .size(18.0),+ );});};- card(ui, "Functions", format!("{}", prog.analysis.functions.len()));- card(ui, "RTTI classes", format!("{}", self.rtti.classes.len()));- card(ui, "Strings", format!("{}", self.strings.len()));- card(ui, "Listing lines", format!("{}", self.listing.len()));- card(ui, "Sections", format!("{}", prog.sections.len()));+ card(+ ui,+ "Functions",+ format!("{}", prog.analysis.functions.len()),+ );+ card(ui, "RTTI classes", format!("{}", self.rtti.classes.len()));+ card(ui, "Strings", format!("{}", self.strings.len()));+ card(ui, "Listing lines", format!("{}", self.listing.len()));+ card(ui, "Sections", format!("{}", prog.sections.len()));});ui.add_space(10.0);if !self.last_analyzers_run.is_empty() {- ui.label(egui::RichText::new("Analyzers last run / saved").strong());+ ui.label(egui::RichText::new("Analyzers last run / saved").strong());ui.horizontal_wrapped(|ui| {for a in &self.last_analyzers_run {- ui.small(format!("[{a}]"));+ ui.small(format!("[{a}]"));}});} else {- ui.weak("No analyzer list saved for this session — run Analyze to record one.");+ ui.weak("No analyzer list saved for this session — run Analyze to record one.");}if !self.rtti.notes.is_empty() {ui.add_space(6.0);- ui.label(egui::RichText::new("RTTI notes").strong());+ ui.label(egui::RichText::new("RTTI notes").strong());for n in &self.rtti.notes {ui.small(n);}@@ -3657,10 +3721,10 @@ impl GhidrustApp {ui.add_space(12.0);ui.separator();- ui.label(egui::RichText::new("What to do next").strong());- ui.label("• Symbol Tree (right): expand Classes / RTTI, type a filter, scroll the list.");- ui.label("• Listing tab: entry disassembly.");- ui.label("• Analyze: re-run analyzers (shows options + progress).");+ ui.label(egui::RichText::new("What to do next").strong());+ ui.label("• Symbol Tree (right): expand Classes / RTTI, type a filter, scroll the list.");+ ui.label("• Listing tab: entry disassembly.");+ ui.label("• Analyze: re-run analyzers (shows options + progress).");if self.rtti.classes.len() > 1000 {ui.label(egui::RichText::new(format!(@@ -3671,31 +3735,33 @@ impl GhidrustApp {);}- // Sample of first few RTTI hits for confidence without opening the full drawer+ // Sample of first few RTTI hits for confidence without opening the full drawerif !self.rtti.classes.is_empty() {ui.add_space(10.0);- ui.label(egui::RichText::new("RTTI sample (first 12)").strong());- egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| {- for c in self.rtti.classes.iter().take(12) {- let va = c- .type_info_va- .map(|v| format!("{v:#x}"))- .unwrap_or_else(|| "—".into());- ui.monospace(format!("{va} {}", c.name));- }- });- if ui.button("Focus Symbol Tree → RTTI").clicked() {+ ui.label(egui::RichText::new("RTTI sample (first 12)").strong());+ egui::ScrollArea::vertical()+ .max_height(160.0)+ .show(ui, |ui| {+ for c in self.rtti.classes.iter().take(12) {+ let va = c+ .type_info_va+ .map(|v| format!("{v:#x}"))+ .unwrap_or_else(|| "—".into());+ ui.monospace(format!("{va} {}", c.name));+ }+ });+ if ui.button("Focus Symbol Tree → RTTI").clicked() {self.show_symbol_tree = true;}}}- /// render every currently open floating provider pane.- ///- /// Panes render either real Stage-0 content (Bookmarks, Memory Map, Functions,- /// Symbol Table, Defined Strings, Relocations) or a clearly labelled "backend- /// pending" empty state that names the analyzer/model responsible for filling- /// them. See `panes::empty_state` for the shared template.+ /// render every currently open floating provider pane.+ ///+ /// Panes render either real Stage-0 content (Bookmarks, Memory Map, Functions,+ /// Symbol Table, Defined Strings, Relocations) or a clearly labelled "backend+ /// pending" empty state that names the analyzer/model responsible for filling+ /// them. See `panes::empty_state` for the shared template.fn draw_provider_panes(&mut self, ctx: &egui::Context) {let t = m3_tokens(self.theme);let muted = Color32::from_rgb(@@ -3705,7 +3771,7 @@ impl GhidrustApp {);let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);- // Snapshot the open-list so we can mutate self inside the closure.+ // Snapshot the open-list so we can mutate self inside the closure.let open_list: Vec<PaneKind> = self.pane_open.iter()@@ -3738,6 +3804,79 @@ impl GhidrustApp {PaneKind::DefinedStrings => {win.show(ctx, |ui| self.ui_defined_strings(ui, muted));}+ PaneKind::CryptoConstants => {+ win.show(ctx, |ui| self.ui_crypto_constants_pane(ui, muted));+ }+ PaneKind::RecoveredStrings => {+ win.show(ctx, |ui| self.ui_recovered_strings_pane(ui, muted));+ }+ PaneKind::CryptoCapabilities => {+ win.show(ctx, |ui| self.ui_crypto_capabilities_pane(ui, muted));+ }+ PaneKind::Decrypt => {+ let mut constants: Vec<_> =+ if let Some(focus_va) = self.crypto_constants_focus_va {+ self.crypt_constants+ .iter()+ .filter(|hit| hit.va.abs_diff(focus_va) <= 0x1000)+ .cloned()+ .collect()+ } else {+ self.crypt_constants.clone()+ };+ if let Some(focus_va) = self.crypto_constants_focus_va {+ constants.sort_by_key(|hit| hit.va.abs_diff(focus_va));+ }+ let strings = self.obfuscated_strings.clone();+ let capabilities = self.crypto_capabilities.clone();+ win.show(ctx, |ui| {+ if let Some(act) =+ decrypt_ui::ui_decrypt_window(+ ui,+ muted,+ &mut self.decrypt_pane,+ &constants,+ &strings,+ &capabilities,+ )+ {+ match act {+ decrypt_ui::DecryptPaneAction::ApplyComment { va, text } => {+ if let Err(e) =+ self.set_comment_at(va, CommentKind::Eol, text)+ {+ self.status = format!("comment failed: {e}");+ } else {+ self.status =+ format!("applied decrypt comment @ {va:#x}");+ }+ }+ decrypt_ui::DecryptPaneAction::ApplyBookmark { va, text } => {+ self.add_bookmark(va, BookmarkKind::Analysis, "decrypt", format!("decrypted: {text}"));+ }+ decrypt_ui::DecryptPaneAction::SendToListing { va } => {+ let _ = self.goto_address_str(&format!("{va:#x}"));+ self.status = format!("Decrypt input focused in Listing at {va:#x}; output was not written as code.");+ }+ decrypt_ui::DecryptPaneAction::LoadVa { va, len } => {+ self.open_decrypt_at_len(va, len, None);+ }+ decrypt_ui::DecryptPaneAction::Goto { va } => {+ let _ = self.goto_address_str(&format!("{va:#x}"));+ }+ decrypt_ui::DecryptPaneAction::DecryptNearby { va, hint } => {+ self.open_decrypt_nearby(va, Some(hint));+ }+ decrypt_ui::DecryptPaneAction::BakeRemnant { va } => {+ self.open_decrypt_at(va, None);+ }+ decrypt_ui::DecryptPaneAction::FocusFunction { va } => {+ self.focus_function(va);+ }+ }+ }+ });+ }PaneKind::RelocationTable => {win.show(ctx, |ui| self.ui_relocation_table(ui, muted));}@@ -3771,18 +3910,20 @@ impl GhidrustApp {PaneKind::ChecksumGenerator => {win.show(ctx, |ui| self.ui_checksum_generator(ui, muted));}- // Graphs & maps.+ // Graphs & maps.PaneKind::FunctionGraph => {win.default_size(egui::vec2(760.0, 520.0)).show(ctx, |ui| self.ui_function_graph_pane(ui, muted, primary));}PaneKind::FunctionCallGraph => {- win.default_size(egui::vec2(760.0, 480.0))- .show(ctx, |ui| self.ui_function_call_graph_pane(ui, muted, primary));+ win.default_size(egui::vec2(760.0, 480.0)).show(ctx, |ui| {+ self.ui_function_call_graph_pane(ui, muted, primary)+ });}PaneKind::FunctionCallTrees => {- win.default_size(egui::vec2(760.0, 460.0))- .show(ctx, |ui| self.ui_function_call_trees_pane(ui, muted, primary));+ win.default_size(egui::vec2(760.0, 460.0)).show(ctx, |ui| {+ self.ui_function_call_trees_pane(ui, muted, primary)+ });}PaneKind::Entropy => {win.default_size(egui::vec2(680.0, 220.0))@@ -3796,7 +3937,7 @@ impl GhidrustApp {win.default_size(egui::vec2(560.0, 520.0)).show(ctx, |ui| self.ui_register_manager_pane(ui, muted, primary));}- // Scripts & interpreters.+ // Scripts & interpreters.PaneKind::ScriptManager => {win.default_size(egui::vec2(760.0, 480.0)).show(ctx, |ui| self.ui_script_manager_pane(ui, muted, primary));@@ -3809,7 +3950,7 @@ impl GhidrustApp {win.default_size(egui::vec2(640.0, 420.0)).show(ctx, |ui| self.ui_mcp_repl_pane(ui, muted, primary));}- // Agent Friction Closure §13 — tool panes (real backends).+ // Agent Friction Closure §13 — tool panes (real backends).PaneKind::Il2cppMetadata => {win.default_size(egui::vec2(720.0, 560.0)).show(ctx, |ui| {tool_panes::ui_il2cpp_metadata(ui, &mut self.tool_panes.il2cpp_meta, muted);@@ -3818,28 +3959,50 @@ impl GhidrustApp {PaneKind::Il2cppMethods => {let prog = self.program.as_ref();win.default_size(egui::vec2(760.0, 560.0)).show(ctx, |ui| {- tool_panes::ui_il2cpp_methods(ui, &mut self.tool_panes.il2cpp_methods, prog, muted);+ tool_panes::ui_il2cpp_methods(+ ui,+ &mut self.tool_panes.il2cpp_methods,+ prog,+ muted,+ );});}PaneKind::Il2cppIcalls => {let prog = self.program.as_ref();win.default_size(egui::vec2(760.0, 560.0)).show(ctx, |ui| {- tool_panes::ui_il2cpp_icalls(ui, &mut self.tool_panes.il2cpp_icalls, prog, muted);+ tool_panes::ui_il2cpp_icalls(+ ui,+ &mut self.tool_panes.il2cpp_icalls,+ prog,+ muted,+ );});}PaneKind::InstallInventory => {win.default_size(egui::vec2(760.0, 520.0)).show(ctx, |ui| {- tool_panes::ui_install_inventory(ui, &mut self.tool_panes.install_inventory, muted);+ tool_panes::ui_install_inventory(+ ui,+ &mut self.tool_panes.install_inventory,+ muted,+ );});}PaneKind::FileSystemBrowser => {win.default_size(egui::vec2(720.0, 520.0)).show(ctx, |ui| {- tool_panes::ui_file_system_browser(ui, &mut self.tool_panes.fs_browser, muted);+ tool_panes::ui_file_system_browser(+ ui,+ &mut self.tool_panes.fs_browser,+ muted,+ );});}PaneKind::AnalysisArtifacts => {win.default_size(egui::vec2(820.0, 520.0)).show(ctx, |ui| {- tool_panes::ui_analysis_artifacts(ui, &mut self.tool_panes.artifacts, muted);+ tool_panes::ui_analysis_artifacts(+ ui,+ &mut self.tool_panes.artifacts,+ muted,+ );});}_ => {@@ -3848,47 +4011,46 @@ impl GhidrustApp {});}}- // Reflect close-button clicks back into our state.+ // Reflect close-button clicks back into our state.if !open {self.pane_open.insert(kind, false);}}- // Debugger tool provider windows.+ // Debugger tool provider windows.self.draw_debugger_panes(ctx, muted);}- // ── Graphs & maps ────────────────────────────────────+ // ── Graphs & maps ────────────────────────────────────- /// `` — CFG vertex/edge layout for the current function.+ /// `` — CFG vertex/edge layout for the current function.fn ui_function_graph_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {- ui.heading("Function Graph");+ ui.heading("Function Graph");ui.small(egui::RichText::new(- "FunctionGraphPlugin analog · Stage-0 CFG from ghidrust-decomp::decompile_at",+ "FunctionGraphPlugin analog · Stage-0 CFG from ghidrust-decomp::decompile_at",).color(muted),);ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};- let Some(entry) = self- .focused_function_entry- .or_else(|| self.listing_focus_va.and_then(|va| {+ let Some(entry) = self.focused_function_entry.or_else(|| {+ self.listing_focus_va.and_then(|va| {prog.analysis.functions.iter().find(|f| va >= f.entry && va < f.end).map(|f| f.entry)- }))- else {- ui.weak("Cursor is not inside a recovered function.");+ })+ }) else {+ ui.weak("Cursor is not inside a recovered function.");ui.small(egui::RichText::new(- "Click a function in Symbol Tree, Functions, or Listing to populate the graph.",+ "Click a function in Symbol Tree, Functions, or Listing to populate the graph.",).color(muted),);@@ -3896,9 +4058,9 @@ impl GhidrustApp {};ui.horizontal(|ui| {- ui.label("Layout:");+ ui.label("Layout:");let cur = self.graph_state.fn_graph_layout;- egui::ComboBox::from_id_salt("fg_layout")+ egui::ComboBox::from_id_salt("fg_layout").selected_text(cur.label()).show_ui(ui, |ui| {for l in FunctionGraphLayout::ALL {@@ -3906,23 +4068,27 @@ impl GhidrustApp {}});ui.separator();- ui.label("Zoom:");+ ui.label("Zoom:");ui.add(egui::Slider::new(&mut self.graph_state.fn_graph_zoom, 0.5..=2.0).clamping(egui::SliderClamping::Always).fixed_decimals(1),);- if ui.button("Fit").on_hover_text("Reset zoom to 1.0").clicked() {+ if ui+ .button("Fit")+ .on_hover_text("Reset zoom to 1.0")+ .clicked()+ {self.graph_state.fn_graph_zoom = 1.0;}ui.separator();- ui.small(egui::RichText::new(format!("Entry {entry:#x}")).color(muted));+ ui.small(egui::RichText::new(format!("Entry {entry:#x}")).color(muted));});ui.separator();let name = prog.display_function_name_at(entry).unwrap_or_default();if !name.is_empty() {- ui.small(egui::RichText::new(format!("Function {name}")).color(muted));+ ui.small(egui::RichText::new(format!("Function {name}")).color(muted));}let algo = self.graph_state.fn_graph_layout;@@ -3943,7 +4109,7 @@ impl GhidrustApp {ui.painter().text(rect.center(),egui::Align2::CENTER_CENTER,- "No Stage-0 CFG recovered for this VA.",+ "No Stage-0 CFG recovered for this VA.",egui::FontId::proportional(13.0),muted,);@@ -3951,56 +4117,53 @@ impl GhidrustApp {}let clicked = render_function_graph(ui, &blocks, &edges, focused_va, primary, muted);if let Some(va) = clicked {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}}- /// `` — level-based directed graph.- fn ui_function_call_graph_pane(- &mut self,- ui: &mut egui::Ui,- muted: Color32,- primary: Color32,- ) {- ui.heading("Function Call Graph");+ /// `` — level-based directed graph.+ fn ui_function_call_graph_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {+ ui.heading("Function Call Graph");ui.small(egui::RichText::new(- "FunctionCallGraphPlugin analog · levels expanded from analyzer references",+ "FunctionCallGraphPlugin analog · levels expanded from analyzer references",).color(muted),);ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};let Some(entry) = self.focused_function_entry- .or_else(|| self.listing_focus_va.and_then(|va| {- prog.analysis- .functions- .iter()- .find(|f| va >= f.entry && va < f.end)- .map(|f| f.entry)- }))+ .or_else(|| {+ self.listing_focus_va.and_then(|va| {+ prog.analysis+ .functions+ .iter()+ .find(|f| va >= f.entry && va < f.end)+ .map(|f| f.entry)+ })+ }).or(prog.entry)else {- ui.weak("No entry point — click a function in Symbol Tree to root the call graph.");+ ui.weak("No entry point — click a function in Symbol Tree to root the call graph.");return;};ui.horizontal(|ui| {- ui.label("Callers levels:");+ ui.label("Callers levels:");let mut lvl_in = self.graph_state.call_graph_levels_in;ui.add(egui::Slider::new(&mut lvl_in, 0..=3));self.graph_state.call_graph_levels_in = lvl_in;ui.separator();- ui.label("Callees levels:");+ ui.label("Callees levels:");let mut lvl_out = self.graph_state.call_graph_levels_out;ui.add(egui::Slider::new(&mut lvl_out, 0..=3));self.graph_state.call_graph_levels_out = lvl_out;- if ui.button("Reset").clicked() {+ if ui.button("Reset").clicked() {self.graph_state.call_graph_levels_in = 1;self.graph_state.call_graph_levels_out = 1;}@@ -4028,7 +4191,7 @@ impl GhidrustApp {ui.painter().text(rect.center(),egui::Align2::CENTER_CENTER,- "No call references recovered — run analyzers first.",+ "No call references recovered — run analyzers first.",egui::FontId::proportional(13.0),muted,);@@ -4040,57 +4203,45 @@ impl GhidrustApp {}}- /// `` — incoming callers / outgoing callees GTree pair.- fn ui_function_call_trees_pane(- &mut self,- ui: &mut egui::Ui,- muted: Color32,- primary: Color32,- ) {- ui.heading("Function Call Trees");+ /// `` — incoming callers / outgoing callees GTree pair.+ fn ui_function_call_trees_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {+ ui.heading("Function Call Trees");ui.small(egui::RichText::new(- "CallTreePlugin analog · Incoming / Outgoing GTrees over analyzer refs",+ "CallTreePlugin analog · Incoming / Outgoing GTrees over analyzer refs",).color(muted),);ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};- let Some(entry) = self- .focused_function_entry- .or_else(|| self.listing_focus_va.and_then(|va| {+ let Some(entry) = self.focused_function_entry.or_else(|| {+ self.listing_focus_va.and_then(|va| {prog.analysis.functions.iter().find(|f| va >= f.entry && va < f.end).map(|f| f.entry)- }))- else {- ui.weak("Cursor is not inside a recovered function.");+ })+ }) else {+ ui.weak("Cursor is not inside a recovered function.");return;};- // Rebuild top level if root changed.+ // Rebuild top level if root changed.let root_name = prog.display_function_name_at(entry).unwrap_or_default();ui.horizontal(|ui| {- ui.small(egui::RichText::new(format!("Source {root_name} @ {entry:#x}")).color(muted));- if ui.button("Refresh").clicked() {+ ui.small(egui::RichText::new(format!("Source {root_name} @ {entry:#x}")).color(muted));+ if ui.button("Refresh").clicked() {self.call_tree_incoming.clear();self.call_tree_outgoing.clear();}ui.separator();- ui.checkbox(- &mut self.graph_state.call_tree_hide_thunks,- "Hide thunks",- );- ui.checkbox(- &mut self.graph_state.call_tree_refs_only,- "References only",- );+ ui.checkbox(&mut self.graph_state.call_tree_hide_thunks, "Hide thunks");+ ui.checkbox(&mut self.graph_state.call_tree_refs_only, "References only");});ui.separator();@@ -4107,17 +4258,17 @@ impl GhidrustApp {let hide_thunks = self.graph_state.call_tree_hide_thunks;let mut goto: Option<u64> = None;egui::ScrollArea::vertical()- .id_salt("calltrees_scroll")+ .id_salt("calltrees_scroll").max_height(360.0).show(ui, |ui| {ui.columns(2, |cols| {- cols[0].label(egui::RichText::new("Incoming (callers / refs to)").strong());+ cols[0].label(egui::RichText::new("Incoming (callers / refs to)").strong());let mut inc = std::mem::take(&mut self.call_tree_incoming);for (i, node) in inc.iter_mut().enumerate() {render_call_tree_node(node,i,- "incoming",+ "incoming",prog,hide_thunks,&mut cols[0],@@ -4130,13 +4281,13 @@ impl GhidrustApp {if refs_only {cols[0].separator();cols[0].label(- egui::RichText::new("Data refs to source")+ egui::RichText::new("Data refs to source").strong().color(muted),);for xr in data_xrefs_to(prog, entry) {let text = egui::RichText::new(format!(- "{} {} ← {:#x}",+ "{} {} ← {:#x}",xr.kind, xr.preview, xr.from)).monospace();@@ -4146,13 +4297,13 @@ impl GhidrustApp {}}- cols[1].label(egui::RichText::new("Outgoing (callees / refs from)").strong());+ cols[1].label(egui::RichText::new("Outgoing (callees / refs from)").strong());let mut out = std::mem::take(&mut self.call_tree_outgoing);for (i, node) in out.iter_mut().enumerate() {render_call_tree_node(node,i,- "outgoing",+ "outgoing",prog,hide_thunks,&mut cols[1],@@ -4169,53 +4320,61 @@ impl GhidrustApp {}}- /// `` header — Shannon-entropy strip across mapped blocks.+ /// `` header — Shannon-entropy strip across mapped blocks.fn ui_entropy_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {- ui.heading("Entropy");+ ui.heading("Entropy");ui.small(- egui::RichText::new(- "EntropyPlugin analog · Shannon bits/byte over 256-byte windows",- )- .color(muted),+ egui::RichText::new("EntropyPlugin analog · Shannon bits/byte over 256-byte windows")+ .color(muted),);ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};let samples = entropy::entropy_samples(prog, 256);- ui.small(format!("{} windows sampled (256 bytes each)", samples.len()));+ ui.small(format!(+ "{} windows sampled (256 bytes each)",+ samples.len()+ ));let clicked_e =entropy::render_entropy_strip(ui, &samples, muted, self.listing_focus_va, primary);ui.add_space(6.0);- ui.label(egui::RichText::new("Overview").strong().color(muted));- let clicked_o =- entropy::render_overview_strip(ui, prog, &samples, muted, self.listing_focus_va, primary);+ ui.label(egui::RichText::new("Overview").strong().color(muted));+ let clicked_o = entropy::render_overview_strip(+ ui,+ prog,+ &samples,+ muted,+ self.listing_focus_va,+ primary,+ );ui.small(egui::RichText::new("Click a strip to Go To that address. Green = exec, amber = writable, grey = readonly, cold-blue = low entropy, warm-red = high.").color(muted),);if let Some(va) = clicked_e.or(clicked_o) {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}}- /// `` — register lattice + user-set value ranges.- fn ui_register_manager_pane(- &mut self,- ui: &mut egui::Ui,- muted: Color32,- primary: Color32,- ) {+ /// `` — register lattice + user-set value ranges.+ fn ui_register_manager_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {let fmt = self.program.as_ref().map(|p| p.format.clone());- register_manager::render(&mut self.register_manager, fmt.as_deref(), ui, muted, primary);+ register_manager::render(+ &mut self.register_manager,+ fmt.as_deref(),+ ui,+ muted,+ primary,+ );}- // ── Scripts & interpreters ───────────────────────────+ // ── Scripts & interpreters ───────────────────────────fn ui_script_manager_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {if let Some(run) = render_script_manager(&mut self.script_manager, ui, muted, primary) {let msg = format!(- "Script Manager · run requested for `{run}` — full script host not yet wired"+ "Script Manager · run requested for `{run}` — full script host not yet wired");self.status = msg.clone();self.log(msg);@@ -4229,26 +4388,26 @@ impl GhidrustApp {TextEditorRequest::NewUntitled => self.text_editor.open_untitled(),TextEditorRequest::OpenFile => {if let Some(path) = rfd::FileDialog::new()- .add_filter("Scripts", &["py", "rs", "txt", "md", "json", "toml"])- .add_filter("All", &["*"])+ .add_filter("Scripts", &["py", "rs", "txt", "md", "json", "toml"])+ .add_filter("All", &["*"]).pick_file(){if let Err(e) = self.text_editor.open_file(path) {- self.status = format!("open error: {e}");+ self.status = format!("open error: {e}");self.log_error(self.status.clone());}}}TextEditorRequest::Save => {if let Err(e) = self.text_editor.save_active() {- self.status = format!("save error: {e}");+ self.status = format!("save error: {e}");self.log_error(self.status.clone());}}TextEditorRequest::SaveAs => {if let Some(path) = rfd::FileDialog::new().save_file() {if let Err(e) = self.text_editor.save_active_as(path) {- self.status = format!("save error: {e}");+ self.status = format!("save error: {e}");self.log_error(self.status.clone());}}@@ -4261,13 +4420,13 @@ impl GhidrustApp {render_mcp_repl(&mut self.mcp_repl, ui, muted, primary);}- // ── Debugger tool ──────────────────────────────────+ // ── Debugger tool ──────────────────────────────────fn draw_debugger_panes(&mut self, ctx: &egui::Context, muted: Color32) {debugger::draw_host(ctx, &mut self.debugger, muted);}- // ── Docking / layouts / Configure ────────────────+ // ── Docking / layouts / Configure ────────────────fn snapshot_current_layout(&self, name: impl Into<String>) -> layouts::SavedLayout {let name = name.into();@@ -4277,15 +4436,15 @@ impl GhidrustApp {}debugger::snapshot_layout_flags(&self.debugger, &mut open_panes);let mut docks = BTreeMap::new();- docks.insert("project_tree".into(), self.show_project_tree);- docks.insert("program_tree".into(), self.show_program_tree);- docks.insert("symbol_tree".into(), self.show_symbol_tree);- docks.insert("console".into(), self.show_console);+ docks.insert("project_tree".into(), self.show_project_tree);+ docks.insert("program_tree".into(), self.show_program_tree);+ docks.insert("symbol_tree".into(), self.show_symbol_tree);+ docks.insert("console".into(), self.show_console);let center = dock_tabs::active_center_id(&self.center_dock).to_string();let dock_tree = serde_json::to_value(&self.center_dock).ok();let theme = match self.theme {- ThemeMode::Dark => "dark",- ThemeMode::Light => "light",+ ThemeMode::Dark => "dark",+ ThemeMode::Light => "light",}.to_string();layouts::SavedLayout {@@ -4300,28 +4459,26 @@ impl GhidrustApp {}fn apply_saved_layout(&mut self, layout: &layouts::SavedLayout) {- // Apply pane visibility.- let ids: BTreeMap<&'static str, PaneKind> = PaneKind::ALL- .iter()- .map(|k| (k.egui_id(), *k))- .collect();+ // Apply pane visibility.+ let ids: BTreeMap<&'static str, PaneKind> =+ PaneKind::ALL.iter().map(|k| (k.egui_id(), *k)).collect();for (id, open) in &layout.open_panes {if let Some(k) = ids.get(id.as_str()) {self.pane_open.insert(*k, *open);}}debugger::apply_layout_flags(&mut self.debugger, &layout.open_panes);- // Docks.- if let Some(v) = layout.docks.get("project_tree") {+ // Docks.+ if let Some(v) = layout.docks.get("project_tree") {self.show_project_tree = *v;}- if let Some(v) = layout.docks.get("program_tree") {+ if let Some(v) = layout.docks.get("program_tree") {self.show_program_tree = *v;}- if let Some(v) = layout.docks.get("symbol_tree") {+ if let Some(v) = layout.docks.get("symbol_tree") {self.show_symbol_tree = *v;}- if let Some(v) = layout.docks.get("console") {+ if let Some(v) = layout.docks.get("console") {self.show_console = *v;}if let Some(value) = &layout.dock_tree {@@ -4334,13 +4491,13 @@ impl GhidrustApp {}self.sync_center_from_dock();self.theme = match layout.theme.as_str() {- "light" => ThemeMode::Light,+ "light" => ThemeMode::Light,_ => ThemeMode::Dark,};self.current_layout_name = layout.name.clone();}- /// Save the current layout under `name`.+ /// Save the current layout under `name`.pub fn save_layout_named(&mut self, name: impl Into<String>) -> std::io::Result<PathBuf> {let name = name.into();let l = self.snapshot_current_layout(name.clone());@@ -4350,40 +4507,40 @@ impl GhidrustApp {Ok(p)}- /// Restore a saved layout by name.+ /// Restore a saved layout by name.pub fn restore_layout_named(&mut self, name: &str) -> std::io::Result<()> {let l = layouts::load_layout(name)?;self.apply_saved_layout(&l);Ok(())}- /// draw all edit dialogs (rename / retype / comment / signature / new type).+ /// draw all edit dialogs (rename / retype / comment / signature / new type).fn draw_edit_dialogs(&mut self, ctx: &egui::Context) {- // Rename dialog .+ // Rename dialog .if self.show_rename_dialog {let mut close = false;let mut confirm = false;let va = self.rename_dialog_target_va;- egui::Window::new("Rename")- .id(egui::Id::new("dialog_rename"))+ egui::Window::new("Rename")+ .id(egui::Id::new("dialog_rename")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {if let Some(va) = va {- ui.label(format!("Address: {va:#x}"));+ ui.label(format!("Address: {va:#x}"));}- ui.label(format!("Old name: {}", self.rename_dialog_old_name));- ui.label("New name:");+ ui.label(format!("Old name: {}", self.rename_dialog_old_name));+ ui.label("New name:");let resp = ui.text_edit_singleline(&mut self.rename_dialog_new_name);if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {confirm = true;}ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {close = true;}- if ui.button("Rename").clicked() {+ if ui.button("Rename").clicked() {confirm = true;}});@@ -4391,7 +4548,7 @@ impl GhidrustApp {if confirm {if let Some(va) = va {if let Err(e) = self.rename_at(va, self.rename_dialog_new_name.clone()) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());} else {close = true;@@ -4403,34 +4560,34 @@ impl GhidrustApp {}}- // Retype dialog .+ // Retype dialog .if self.show_retype_dialog {let mut close = false;let mut confirm = false;let va = self.retype_dialog_target_va;- egui::Window::new("Retype")- .id(egui::Id::new("dialog_retype"))+ egui::Window::new("Retype")+ .id(egui::Id::new("dialog_retype")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {if let Some(va) = va {- ui.label(format!("Address: {va:#x}"));+ ui.label(format!("Address: {va:#x}"));}- ui.label("Type .:");+ ui.label("Type .:");let resp = ui.text_edit_singleline(&mut self.retype_dialog_type);if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {confirm = true;}ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {close = true;}- if ui.button("Clear").clicked() {+ if ui.button("Clear").clicked() {self.retype_dialog_type.clear();confirm = true;}- if ui.button("Apply").clicked() {+ if ui.button("Apply").clicked() {confirm = true;}});@@ -4438,7 +4595,7 @@ impl GhidrustApp {if confirm {if let Some(va) = va {if let Err(e) = self.retype_at(va, self.retype_dialog_type.clone()) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());} else {close = true;@@ -4450,38 +4607,37 @@ impl GhidrustApp {}}- // Comment dialog (Set EOL/Pre/Post/Plate/Repeatable).+ // Comment dialog (Set EOL/Pre/Post/Plate/Repeatable).if self.show_comment_dialog {let mut close = false;let mut confirm = false;let va = self.comment_dialog_target_va;- egui::Window::new("Set Comment")- .id(egui::Id::new("dialog_comment"))+ egui::Window::new("Set Comment")+ .id(egui::Id::new("dialog_comment")).collapsible(false).resizable(true).default_width(420.0).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {if let Some(va) = va {- ui.label(format!("Address: {va:#x}"));+ ui.label(format!("Address: {va:#x}"));}ui.horizontal(|ui| {- ui.label("Kind:");- egui::ComboBox::from_id_salt("comment_kind")+ ui.label("Kind:");+ egui::ComboBox::from_id_salt("comment_kind").selected_text(self.comment_dialog_kind.label()).show_ui(ui, |ui| {for k in CommentKind::ALL {if ui.selectable_value(&mut self.comment_dialog_kind,- *k,+ *k,k.label(),).clicked(){- // Load existing text for that kind.- if let (Some(va), Some(prog)) =- (va, self.program.as_ref())+ // Load existing text for that kind.+ if let (Some(va), Some(prog)) = (va, self.program.as_ref()){self.comment_dialog_text = prog.edits@@ -4493,21 +4649,21 @@ impl GhidrustApp {}});});- ui.label("Text:");+ ui.label("Text:");ui.add(egui::TextEdit::multiline(&mut self.comment_dialog_text).desired_rows(4).desired_width(f32::INFINITY),);ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {close = true;}- if ui.button("Clear").clicked() {+ if ui.button("Clear").clicked() {self.comment_dialog_text.clear();confirm = true;}- if ui.button("Save").clicked() {+ if ui.button("Save").clicked() {confirm = true;}});@@ -4519,7 +4675,7 @@ impl GhidrustApp {self.comment_dialog_kind,self.comment_dialog_text.clone(),) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());} else {close = true;@@ -4531,22 +4687,22 @@ impl GhidrustApp {}}- // Function-signature dialog (Edit Function Signature).+ // Function-signature dialog (Edit Function Signature).if self.show_fn_signature_dialog {let mut close = false;let mut confirm = false;let entry = self.fn_signature_dialog_entry;- egui::Window::new("Edit Function Signature")- .id(egui::Id::new("dialog_fn_sig"))+ egui::Window::new("Edit Function Signature")+ .id(egui::Id::new("dialog_fn_sig")).collapsible(false).resizable(true).default_width(520.0).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {if let Some(entry) = entry {- ui.label(format!("Function entry: {entry:#x}"));+ ui.label(format!("Function entry: {entry:#x}"));}- ui.label("Signature:");+ ui.label("Signature:");ui.add(egui::TextEdit::multiline(&mut self.fn_signature_dialog_text).desired_rows(3)@@ -4554,20 +4710,20 @@ impl GhidrustApp {.font(egui::FontId::monospace(13.0)),);ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {close = true;}- if ui.button("Save").clicked() {+ if ui.button("Save").clicked() {confirm = true;}});});if confirm {if let Some(entry) = entry {- if let Err(e) = self- .set_function_signature(entry, self.fn_signature_dialog_text.clone())+ if let Err(e) =+ self.set_function_signature(entry, self.fn_signature_dialog_text.clone()){- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());} else {close = true;@@ -4579,21 +4735,21 @@ impl GhidrustApp {}}- // New Type dialog (DTM → New → Structure/Union/Enum/Typedef/FunctionDef).+ // New Type dialog (DTM → New → Structure/Union/Enum/Typedef/FunctionDef).if self.show_new_type_dialog {let mut close = false;let mut confirm = false;let kind = self.new_type_dialog_kind;- egui::Window::new(format!("New {}", kind.label()))- .id(egui::Id::new("dialog_new_type"))+ egui::Window::new(format!("New {}", kind.label()))+ .id(egui::Id::new("dialog_new_type")).collapsible(false).resizable(true).default_width(560.0).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {- ui.label("Name:");+ ui.label("Name:");ui.text_edit_singleline(&mut self.new_type_dialog_name);- ui.label(format!("{} body:", kind.label()));+ ui.label(format!("{} body:", kind.label()));ui.add(egui::TextEdit::multiline(&mut self.new_type_dialog_body).desired_rows(8)@@ -4601,19 +4757,19 @@ impl GhidrustApp {.font(egui::FontId::monospace(13.0)),);ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {close = true;}- if ui.button("Create").clicked() {+ if ui.button("Create").clicked() {confirm = true;}});});if confirm {let name = self.new_type_dialog_name.clone();- let body = format!("{}\n{}", kind.label(), self.new_type_dialog_body);+ let body = format!("{}\n{}", kind.label(), self.new_type_dialog_body);if let Err(e) = self.define_user_type(name, body) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());} else {close = true;@@ -4624,21 +4780,21 @@ impl GhidrustApp {}}- // Edit Type dialog (DTM → Edit on an existing user type).+ // Edit Type dialog (DTM → Edit on an existing user type).if self.show_edit_type_dialog {let mut close = false;let mut confirm = false;let orig = self.edit_type_dialog_orig_name.clone();- egui::Window::new(format!("Edit type · {orig}"))- .id(egui::Id::new("dialog_edit_type"))+ egui::Window::new(format!("Edit type · {orig}"))+ .id(egui::Id::new("dialog_edit_type")).collapsible(false).resizable(true).default_width(560.0).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {- ui.label("Name:");+ ui.label("Name:");ui.text_edit_singleline(&mut self.edit_type_dialog_name);- ui.label("Body .:");+ ui.label("Body .:");ui.add(egui::TextEdit::multiline(&mut self.edit_type_dialog_body).desired_rows(10)@@ -4646,18 +4802,18 @@ impl GhidrustApp {.font(egui::FontId::monospace(13.0)),);ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {close = true;}- if ui.button("Delete").clicked() {+ if ui.button("Delete").clicked() {if let Err(e) = self.delete_user_type(&orig) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());} else {close = true;}}- if ui.button("Save").clicked() {+ if ui.button("Save").clicked() {confirm = true;}});@@ -4666,7 +4822,7 @@ impl GhidrustApp {let new_name = self.edit_type_dialog_name.clone();let body = self.edit_type_dialog_body.clone();if let Err(e) = self.edit_user_type(&orig, new_name, body) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());} else {close = true;@@ -4677,29 +4833,29 @@ impl GhidrustApp {}}- // Data Type Chooser dialog .+ // Data Type Chooser dialog .if self.show_type_chooser_dialog {let mut close = false;let mut apply: Option<String> = None;let va = self.type_chooser_target_va;- egui::Window::new("Choose Data Type")- .id(egui::Id::new("dialog_type_chooser"))+ egui::Window::new("Choose Data Type")+ .id(egui::Id::new("dialog_type_chooser")).collapsible(false).resizable(true).default_width(420.0).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {if let Some(va) = va {- ui.small(format!("Apply target: {va:#x}"));+ ui.small(format!("Apply target: {va:#x}"));} else {- ui.weak("No cursor VA — click a Listing line first.");+ ui.weak("No cursor VA — click a Listing line first.");}ui.horizontal(|ui| {- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut self.type_chooser_filter).desired_width(240.0)- .hint_text("Type name…"),+ .hint_text("Type name…"),);});let q = self.type_chooser_filter.to_ascii_lowercase();@@ -4709,7 +4865,7 @@ impl GhidrustApp {.map(|p| p.edits.user_types.keys().cloned().collect()).unwrap_or_default();egui::ScrollArea::vertical()- .id_salt("type_chooser_scroll")+ .id_salt("type_chooser_scroll").max_height(280.0).show(ui, |ui| {for name in BUILTIN_TYPES {@@ -4721,7 +4877,7 @@ impl GhidrustApp {ui.with_layout(egui::Layout::right_to_left(egui::Align::Center),|ui| {- if ui.small_button("Apply").clicked() {+ if ui.small_button("Apply").clicked() {apply = Some((*name).to_string());}},@@ -4730,7 +4886,7 @@ impl GhidrustApp {}if !user_types.is_empty() {ui.separator();- ui.small("Program archive:");+ ui.small("Program archive:");for name in &user_types {if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {continue;@@ -4740,7 +4896,7 @@ impl GhidrustApp {ui.with_layout(egui::Layout::right_to_left(egui::Align::Center),|ui| {- if ui.small_button("Apply").clicked() {+ if ui.small_button("Apply").clicked() {apply = Some(name.clone());}},@@ -4750,7 +4906,7 @@ impl GhidrustApp {}});ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {close = true;}});@@ -4758,13 +4914,13 @@ impl GhidrustApp {if let Some(name) = apply {if let Some(va) = va {if let Err(e) = self.apply_type_at(va, name) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());} else {close = true;}} else {- self.status = "No cursor VA — click a Listing line first".into();+ self.status = "No cursor VA — click a Listing line first".into();self.log_warn(self.status.clone());}}@@ -4774,25 +4930,25 @@ impl GhidrustApp {}}- /// Data Type Manager tree (Built-In archive + Program archive).+ /// Data Type Manager tree (Built-In archive + Program archive).fn ui_dtm_pane(&mut self, ui: &mut egui::Ui) {- ui.heading("Data Type Manager");+ ui.heading("Data Type Manager");ui.small(egui::RichText::new(- "DataTypeManagerPlugin · Built-In archive + Program archive (user types)",+ "DataTypeManagerPlugin · Built-In archive + Program archive (user types)",).weak(),);ui.separator();ui.horizontal(|ui| {- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut self.dtm_filter).desired_width(240.0)- .hint_text("Type name…"),+ .hint_text("Type name…"),);ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- ui.menu_button("New…", |ui| {+ ui.menu_button("New…", |ui| {for k in NewTypeKind::ALL {if ui.button(k.label()).clicked() {self.open_new_type_dialog(*k);@@ -4803,8 +4959,8 @@ impl GhidrustApp {});});let q = self.dtm_filter.to_ascii_lowercase();- // Per-frame action queue so we can mutate `self` outside the borrowed- // scroll-area closure below without fighting the borrow checker.+ // Per-frame action queue so we can mutate `self` outside the borrowed+ // scroll-area closure below without fighting the borrow checker.let mut pending_apply: Option<String> = None;let mut pending_typedef_on: Option<String> = None;let mut pending_pointer_to: Option<String> = None;@@ -4812,13 +4968,13 @@ impl GhidrustApp {let mut pending_rename: Option<String> = None;let mut pending_delete: Option<String> = None;egui::ScrollArea::vertical()- .id_salt("dtm_scroll")+ .id_salt("dtm_scroll").auto_shrink([false, false]).show(ui, |ui| {- // Built-In archive. Read-only leaves — 's- // Built-In archive is not editable; right-click gives us- // Apply / +Typedef / +Pointer / Copy-to-program.- egui::CollapsingHeader::new("Built-In")+ // Built-In archive. Read-only leaves — 's+ // Built-In archive is not editable; right-click gives us+ // Apply / +Typedef / +Pointer / Copy-to-program.+ egui::CollapsingHeader::new("Built-In").default_open(true).show(ui, |ui| {for name in BUILTIN_TYPES {@@ -4831,21 +4987,25 @@ impl GhidrustApp {ui.with_layout(egui::Layout::right_to_left(egui::Align::Center),|ui| {- if ui.small_button("+Ptr").on_hover_text(- "New Pointer to X .",- ).clicked() {+ if ui+ .small_button("+Ptr")+ .on_hover_text("New Pointer to X .")+ .clicked()+ {pending_pointer_to = Some((*name).to_string());}- if ui.small_button("+Typedef").on_hover_text(- "New Typedef on X .",- ).clicked() {+ if ui+ .small_button("+Typedef")+ .on_hover_text("New Typedef on X .")+ .clicked()+ {pending_typedef_on = Some((*name).to_string());}if let Some(va) = self.listing_focus_va {if ui- .small_button("Apply @ cursor")+ .small_button("Apply @ cursor").on_hover_text(format!(- "Apply {name} at {va:#x}"+ "Apply {name} at {va:#x}")).clicked(){@@ -4856,32 +5016,32 @@ impl GhidrustApp {);}).response;- // right-click submenu (Rename/Delete- // Cut/Copy/Paste are N/A on Built-In, so we only- // offer the applicable actions).+ // right-click submenu (Rename/Delete+ // Cut/Copy/Paste are N/A on Built-In, so we only+ // offer the applicable actions).row_resp.context_menu(|ui| {ui.label(egui::RichText::new(*name).monospace());ui.separator();let has_va = self.listing_focus_va.is_some();if ui- .add_enabled(has_va, egui::Button::new("Apply @ cursor"))+ .add_enabled(has_va, egui::Button::new("Apply @ cursor")).clicked(){pending_apply = Some((*name).to_string());ui.close_menu();}- if ui.button("New Typedef on X").clicked() {+ if ui.button("New Typedef on X").clicked() {pending_typedef_on = Some((*name).to_string());ui.close_menu();}- if ui.button("New Pointer to X").clicked() {+ if ui.button("New Pointer to X").clicked() {pending_pointer_to = Some((*name).to_string());ui.close_menu();}});}});- // Program archive: user-defined types + analyzer-recovered RTTI classes.+ // Program archive: user-defined types + analyzer-recovered RTTI classes.let (user_types, rtti_classes) = self.program.as_ref()@@ -4897,7 +5057,7 @@ impl GhidrustApp {}).unwrap_or_default();let title = format!(- "Program ({user} user + {rtti} RTTI)",+ "Program ({user} user + {rtti} RTTI)",user = user_types.len(),rtti = rtti_classes.len());@@ -4918,30 +5078,27 @@ impl GhidrustApp {ui.monospace(name.to_string());ui.weak(egui::RichText::new(- body.lines()- .next()- .unwrap_or_default()- .to_string(),+ body.lines().next().unwrap_or_default().to_string(),).italics(),);ui.with_layout(egui::Layout::right_to_left(egui::Align::Center),|ui| {- if ui.small_button("Delete").clicked() {+ if ui.small_button("Delete").clicked() {pending_delete = Some(name.clone());}- if ui.small_button("Rename…").clicked() {+ if ui.small_button("Rename…").clicked() {pending_rename = Some(name.clone());}- if ui.small_button("Edit…").clicked() {+ if ui.small_button("Edit…").clicked() {pending_edit = Some(name.clone());}if let Some(va) = self.listing_focus_va {if ui- .small_button("Apply @ cursor")+ .small_button("Apply @ cursor").on_hover_text(format!(- "Apply {name} at {va:#x}"+ "Apply {name} at {va:#x}")).clicked(){@@ -4955,32 +5112,32 @@ impl GhidrustApp {row_resp.context_menu(|ui| {ui.label(egui::RichText::new(name).monospace());ui.separator();- if ui.button("Edit…").clicked() {+ if ui.button("Edit…").clicked() {pending_edit = Some(name.clone());ui.close_menu();}- if ui.button("Rename…").clicked() {+ if ui.button("Rename…").clicked() {pending_rename = Some(name.clone());ui.close_menu();}- if ui.button("Delete").clicked() {+ if ui.button("Delete").clicked() {pending_delete = Some(name.clone());ui.close_menu();}ui.separator();let has_va = self.listing_focus_va.is_some();if ui- .add_enabled(has_va, egui::Button::new("Apply @ cursor"))+ .add_enabled(has_va, egui::Button::new("Apply @ cursor")).clicked(){pending_apply = Some(name.clone());ui.close_menu();}- if ui.button("New Typedef on X").clicked() {+ if ui.button("New Typedef on X").clicked() {pending_typedef_on = Some(name.clone());ui.close_menu();}- if ui.button("New Pointer to X").clicked() {+ if ui.button("New Pointer to X").clicked() {pending_pointer_to = Some(name.clone());ui.close_menu();}@@ -4988,9 +5145,7 @@ impl GhidrustApp {}if !rtti_classes.is_empty() {ui.separator();- ui.small(- egui::RichText::new("RTTI classes (from analyzer)").weak(),- );+ ui.small(egui::RichText::new("RTTI classes (from analyzer)").weak());for name in &rtti_classes {if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {continue;@@ -5001,14 +5156,14 @@ impl GhidrustApp {ui.with_layout(egui::Layout::right_to_left(egui::Align::Center),|ui| {- if ui.small_button("+Ptr").clicked() {+ if ui.small_button("+Ptr").clicked() {pending_pointer_to = Some(name.clone());}- if ui.small_button("+Typedef").clicked() {+ if ui.small_button("+Typedef").clicked() {pending_typedef_on = Some(name.clone());}if self.listing_focus_va.is_some()- && ui.small_button("Apply @ cursor").clicked()+ && ui.small_button("Apply @ cursor").clicked(){pending_apply = Some(name.clone());}@@ -5021,17 +5176,17 @@ impl GhidrustApp {ui.separator();let has_va = self.listing_focus_va.is_some();if ui- .add_enabled(has_va, egui::Button::new("Apply @ cursor"))+ .add_enabled(has_va, egui::Button::new("Apply @ cursor")).clicked(){pending_apply = Some(name.clone());ui.close_menu();}- if ui.button("New Typedef on X").clicked() {+ if ui.button("New Typedef on X").clicked() {pending_typedef_on = Some(name.clone());ui.close_menu();}- if ui.button("New Pointer to X").clicked() {+ if ui.button("New Pointer to X").clicked() {pending_pointer_to = Some(name.clone());ui.close_menu();}@@ -5043,18 +5198,18 @@ impl GhidrustApp {ui.separator();ui.small(egui::RichText::new(- "Right-click a type for Edit / Rename / Delete / Apply @ cursor / \+ "Right-click a type for Edit / Rename / Delete / Apply @ cursor / \New Typedef on X / New Pointer to X. Docking-framework drag-and-drop \not yet wired.",).weak().italics(),);- // Flush queued actions after the scroll-area borrow drops.+ // Flush queued actions after the scroll-area borrow drops.if let Some(name) = pending_apply {if let Some(va) = self.listing_focus_va {if let Err(e) = self.apply_type_at(va, name) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());}}@@ -5062,11 +5217,11 @@ impl GhidrustApp {if let Some(name) = pending_typedef_on {match self.new_typedef_on(&name) {Ok(new_name) => {- self.status = format!("Created typedef {new_name} on {name}");+ self.status = format!("Created typedef {new_name} on {name}");self.log(self.status.clone());}Err(e) => {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());}}@@ -5074,11 +5229,11 @@ impl GhidrustApp {if let Some(name) = pending_pointer_to {match self.new_pointer_to(&name) {Ok(new_name) => {- self.status = format!("Created pointer type {new_name}");+ self.status = format!("Created pointer type {new_name}");self.log(self.status.clone());}Err(e) => {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());}}@@ -5087,22 +5242,22 @@ impl GhidrustApp {self.open_edit_type_dialog(&name);}if let Some(name) = pending_rename {- // Reuse the standard Rename dialog but retarget its callback path:- // renames of user types go through the new-type dialog with the- // current body preloaded (so Save = rename + optional body edit).+ // Reuse the standard Rename dialog but retarget its callback path:+ // renames of user types go through the new-type dialog with the+ // current body preloaded (so Save = rename + optional body edit).self.open_edit_type_dialog(&name);}if let Some(name) = pending_delete {if let Err(e) = self.delete_user_type(&name) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());}}}- /// Listing center pane with real fields, margin markers, and flow arrows.+ /// Listing center pane with real fields, margin markers, and flow arrows.fn ui_listing_pane(&mut self, ui: &mut egui::Ui) {- ui.heading("Listing");+ ui.heading("Listing");let mut open_opts = self.show_decode_options_dialog;match ui_toolbar(ui, &mut self.decode_opts, &mut open_opts) {ToolbarAction::Apply => self.apply_decode_opts(),@@ -5112,26 +5267,26 @@ impl GhidrustApp {self.show_decode_options_dialog = open_opts;ui_search_bar(ui, &mut self.listing_search);self.listing_search.arch = self.listing_arch();- // Status strip.+ // Status strip.ui.horizontal(|ui| {if !self.listing_selection.is_empty() {ui.small(format!(- "Sel {}–{}",+ "Sel {}–{}",self.listing_selection.start.unwrap_or(0),self.listing_selection.end.unwrap_or(0)));}if let Some(va) = self.listing_focus_va {- ui.small(format!("Cursor {va:#x}"));+ ui.small(format!("Cursor {va:#x}"));}if let Some(f) = self.listing_view_filter.as_ref() {- let names = f.iter().cloned().collect::<Vec<_>>().join(", ");- ui.small(egui::RichText::new(format!(- "View filter · {} fragment(s): {names}",- f.len()- )).weak());+ let names = f.iter().cloned().collect::<Vec<_>>().join(", ");+ ui.small(+ egui::RichText::new(format!("View filter · {} fragment(s): {names}", f.len()))+ .weak(),+ );ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if ui.small_button("Show All").clicked() {+ if ui.small_button("Show All").clicked() {self.listing_view_filter = None;}});@@ -5139,15 +5294,15 @@ impl GhidrustApp {});ui.separator();if self.listing.is_empty() {- ui.weak("No listing — double-click a project file to open.");+ ui.weak("No listing — double-click a project file to open.");return;}let focus = self.listing_focus_va;let sel = self.listing_selection;let t = m3_tokens(self.theme);- let sel_bg = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2])- .gamma_multiply(0.35);- // Snapshot for the closure: (idx, va, bytes_hex, mnem, ops, is_ret, is_uncond, is_cond, is_call, applied_type, comment_eol).+ let sel_bg =+ Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]).gamma_multiply(0.35);+ // Snapshot for the closure: (idx, va, bytes_hex, mnem, ops, is_ret, is_uncond, is_cond, is_call, applied_type, comment_eol).let rows: Vec<ListingRow> = {let filter = self.listing_view_filter.clone();let prog_ref = self.program.as_ref();@@ -5163,13 +5318,9 @@ impl GhidrustApp {if set.is_empty() {false} else if let Some(p) = prog_ref {- p.blocks- .iter()- .filter(|b| set.contains(&b.name))- .any(|b| {- insn.address >= b.va- && insn.address < b.va.saturating_add(b.size)- })+ p.blocks.iter().filter(|b| set.contains(&b.name)).any(|b| {+ insn.address >= b.va && insn.address < b.va.saturating_add(b.size)+ })} else {true}@@ -5178,14 +5329,11 @@ impl GhidrustApp {.map(|(i, insn)| ListingRow::from_insn(i, insn, prog_ref, arch)).collect()};- let bookmarks_by_va: BTreeMap<u64, BookmarkKind> = self- .bookmarks- .iter()- .map(|b| (b.va, b.kind))- .collect();+ let bookmarks_by_va: BTreeMap<u64, BookmarkKind> =+ self.bookmarks.iter().map(|b| (b.va, b.kind)).collect();let mut click_i: Option<(usize, u64)> = None;- // Right-click actions surfaced via a context menu attached to the- // Address column. Executed after the scroll-area borrow drops.+ // Right-click actions surfaced via a context menu attached to the+ // Address column. Executed after the scroll-area borrow drops.#[derive(Debug, Clone, Copy)]enum RowAction {OpenComment(CommentKind),@@ -5196,59 +5344,63 @@ impl GhidrustApp {OpenEquate,ShowRefsTo,OpenBytesHere,+ DecryptSelection,+ SuggestRecipe,+ CryptoConstantsAtCursor,+ RecoverStringsHere,}let mut pending_action: Option<(u64, RowAction)> = None;egui::ScrollArea::both()- .id_salt("listing_scroll")+ .id_salt("listing_scroll").auto_shrink([false, false]).show(ui, |ui| {- egui::Grid::new("listing_grid")+ egui::Grid::new("listing_grid").num_columns(7).spacing([6.0, 2.0]).striped(false).show(ui, |ui| {- ui.strong(egui::RichText::new("").monospace());- ui.strong("Address");- ui.strong("Bytes");- ui.strong("Mnemonic");- ui.strong("Operands");- ui.strong("Flow");- ui.strong("Comment");+ ui.strong(egui::RichText::new("").monospace());+ ui.strong("Address");+ ui.strong("Bytes");+ ui.strong("Mnemonic");+ ui.strong("Operands");+ ui.strong("Flow");+ ui.strong("Comment");ui.end_row();for row in &rows {let focused = focus == Some(row.va);let selected = sel.contains(row.idx);- // Pre-comment row (`Pre` comment appears- // as its own line above the instruction).+ // Pre-comment row (`Pre` comment appears+ // as its own line above the instruction).if let Some(pre) = &row.comment_pre {- ui.label(egui::RichText::new(" ").monospace());+ ui.label(egui::RichText::new(" ").monospace());ui.label(- egui::RichText::new(format!("; {pre}"))+ egui::RichText::new(format!("; {pre}")).italics().color(Color32::from_rgb(0x64, 0xB5, 0xF6)),);for _ in 0..5 {- ui.label("");+ ui.label("");}ui.end_row();}- // Margin column: bookmark tint + flow-glyph.+ // Margin column: bookmark tint + flow-glyph.let margin_text = if let Some(k) = bookmarks_by_va.get(&row.va) {- egui::RichText::new("* ")+ egui::RichText::new("* ").color(k.color()).monospace().strong()} else if focused {- egui::RichText::new("> ")+ egui::RichText::new("> ").color(Color32::from_rgb(0xFF, 0xD5, 0x4F)).monospace().strong()} else {- egui::RichText::new(" ").monospace()+ egui::RichText::new(" ").monospace()};ui.label(margin_text);- // Address column (clickable).- let addr_rich = egui::RichText::new(format!("{:08x}", row.va))+ // Address column (clickable).+ let addr_rich = egui::RichText::new(format!("{:08x}", row.va)).monospace().color(if focused {Color32::from_rgb(0xFF, 0xD5, 0x4F)@@ -5267,60 +5419,100 @@ impl GhidrustApp {if addr.clicked() {click_i = Some((row.idx, row.va));}- // Listing right-click submenu.+ // Listing right-click submenu.let va = row.va;addr.context_menu(|ui| {ui.label(- egui::RichText::new(format!("{va:#x}"))- .monospace()- .strong(),+ egui::RichText::new(format!("{va:#x}")).monospace().strong(),);ui.separator();- ui.menu_button("Set Comment", |ui| {+ ui.menu_button("Set Comment", |ui| {for k in CommentKind::ALL {if ui.button(k.label()).clicked() {- pending_action = Some((- va,- RowAction::OpenComment(*k),- ));+ pending_action = Some((va, RowAction::OpenComment(*k)));ui.close_menu();}}});ui.separator();- if ui.button("Rename Symbol… (L)").clicked() {+ if ui.button("Rename Symbol… (L)").clicked() {pending_action = Some((va, RowAction::OpenRename));ui.close_menu();}- if ui.button("Retype Variable… (Ctrl+L)").clicked() {+ if ui.button("Retype Variable… (Ctrl+L)").clicked() {pending_action = Some((va, RowAction::OpenRetype));ui.close_menu();}- if ui.button("Choose Data Type… (T)").clicked() {+ if ui.button("Choose Data Type… (T)").clicked() {pending_action = Some((va, RowAction::OpenChooser));ui.close_menu();}- if ui.button("Edit Function Signature… (Alt+Enter)").clicked() {+ if ui.button("Edit Function Signature… (Alt+Enter)").clicked() {pending_action = Some((va, RowAction::OpenSignature));ui.close_menu();}ui.separator();- if ui.button("Set Equate…").on_hover_text("Bind a name to the first operand scalar").clicked() {+ if ui+ .button("Set Equate…")+ .on_hover_text("Bind a name to the first operand scalar")+ .clicked()+ {pending_action = Some((va, RowAction::OpenEquate));ui.close_menu();}- if ui.button("Show References To…").on_hover_text("Open Symbol References for this VA").clicked() {+ if ui+ .button("Show References To…")+ .on_hover_text("Open Symbol References for this VA")+ .clicked()+ {pending_action = Some((va, RowAction::ShowRefsTo));ui.close_menu();}- if ui.button("Show Bytes Here").on_hover_text("Open Byte Viewer at this VA").clicked() {+ if ui+ .button("Show Bytes Here")+ .on_hover_text("Open Byte Viewer at this VA")+ .clicked()+ {pending_action = Some((va, RowAction::OpenBytesHere));ui.close_menu();}+ ui.separator();+ if ui+ .button("Decrypt selection…")+ .on_hover_text("Open Decrypt pane on bytes at this VA")+ .clicked()+ {+ pending_action = Some((va, RowAction::DecryptSelection));+ ui.close_menu();+ }+ if ui+ .button("Suggest recipe…")+ .on_hover_text("Magic peel on bytes at this VA")+ .clicked()+ {+ pending_action = Some((va, RowAction::SuggestRecipe));+ ui.close_menu();+ }+ if ui+ .button("Crypto Constants at cursor…")+ .on_hover_text("Focus Crypto Constants near this VA")+ .clicked()+ {+ pending_action = Some((va, RowAction::CryptoConstantsAtCursor));+ ui.close_menu();+ }+ if ui+ .button("Recover strings here…")+ .on_hover_text("Open Recovered Strings pane")+ .clicked()+ {+ pending_action = Some((va, RowAction::RecoverStringsHere));+ ui.close_menu();+ }});- // Bytes column.+ // Bytes column.ui.monospace(&row.bytes_hex);- // Mnemonic column, coloured by kind.+ // Mnemonic column, coloured by kind.let mnem_color = if row.is_ret {Color32::from_rgb(0xEF, 0x53, 0x50)} else if row.is_uncond {@@ -5337,16 +5529,16 @@ impl GhidrustApp {);if !row.groups_summary.is_empty() || !row.regs_rw.is_empty() {mnem_resp.on_hover_ui(|ui| {- ui.monospace(format!("id {}", row.id.raw()));+ ui.monospace(format!("id {}", row.id.raw()));if !row.groups_summary.is_empty() {- ui.small(format!("groups: {}", row.groups_summary));+ ui.small(format!("groups: {}", row.groups_summary));}if !row.regs_rw.is_empty() {ui.small(&row.regs_rw);}});}- // Operands column with scalar/address hover popup.+ // Operands column with scalar/address hover popup.let ops_resp = ui.add(egui::Label::new(egui::RichText::new(&row.ops).monospace()).sense(egui::Sense::hover()),@@ -5361,53 +5553,53 @@ impl GhidrustApp {}});}- // Flow column: arrow glyph indicator.+ // Flow column: arrow glyph indicator.let flow_glyph = if row.is_ret {- "return"+ "return"} else if row.is_uncond {- "→"+ "→"} else if row.is_cond {- "?→"+ "?→"} else if row.is_call {- "call"+ "call"} else {- ""+ ""};ui.small(egui::RichText::new(flow_glyph).monospace());- // Comment / applied type column (EOL + Repeatable- // + Plate + Applied Type decoration).+ // Comment / applied type column (EOL + Repeatable+ // + Plate + Applied Type decoration).let mut comment_row = String::new();if let Some(t) = &row.applied_type {- comment_row.push_str(&format!("<{t}> "));+ comment_row.push_str(&format!("<{t}> "));}if let Some(t) = &row.comment_eol {- comment_row.push_str(&format!("// {t}"));+ comment_row.push_str(&format!("// {t}"));}if let Some(t) = &row.comment_repeat {if !comment_row.is_empty() {- comment_row.push_str(" ");+ comment_row.push_str(" ");}- comment_row.push_str(&format!("~ {t}"));+ comment_row.push_str(&format!("~ {t}"));}if let Some(t) = &row.comment_plate {if !comment_row.is_empty() {- comment_row.push_str(" ");+ comment_row.push_str(" ");}- comment_row.push_str(&format!("[PLATE {t}]"));+ comment_row.push_str(&format!("[PLATE {t}]"));}ui.small(egui::RichText::new(comment_row).italics());ui.end_row();- // Post-comment row (`Post` comment appears- // as its own line below the instruction).+ // Post-comment row (`Post` comment appears+ // as its own line below the instruction).if let Some(post) = &row.comment_post {- ui.label(egui::RichText::new(" ").monospace());+ ui.label(egui::RichText::new(" ").monospace());ui.label(- egui::RichText::new(format!("; {post}"))+ egui::RichText::new(format!("; {post}")).italics().color(Color32::from_rgb(0xBA, 0x68, 0xC8)),);for _ in 0..5 {- ui.label("");+ ui.label("");}ui.end_row();}@@ -5434,9 +5626,9 @@ impl GhidrustApp {RowAction::OpenRetype => self.open_retype_dialog(va),RowAction::OpenChooser => self.open_type_chooser(Some(va)),RowAction::OpenSignature => {- // Alt+Enter is defined on a function; if the cursor isn't- // inside a function, fall back to opening the signature- // dialog with the given VA as entry (user can retype it).+ // Alt+Enter is defined on a function; if the cursor isn't+ // inside a function, fall back to opening the signature+ // dialog with the given VA as entry (user can retype it).let entry = self.program.as_ref()@@ -5454,13 +5646,13 @@ impl GhidrustApp {self.equate_dialog_va = Some(va);self.equate_dialog_op = 1;self.equate_dialog_name.clear();- // Preload first scalar from the operand string for convenience.+ // Preload first scalar from the operand string for convenience.self.equate_dialog_value = self.listing.iter().find(|i| i.address == va).and_then(|i| menu_actions::extract_scalars(&i.operands).first().copied())- .map(|v| format!("{v}"))+ .map(|v| format!("{v}")).unwrap_or_default();self.show_equate_dialog = true;}@@ -5472,45 +5664,58 @@ impl GhidrustApp {self.bytes_pane_va = Some(va);self.pane_open.insert(PaneKind::Bytes, true);}+ RowAction::DecryptSelection => {+ self.open_decrypt_at(va, None);+ }+ RowAction::SuggestRecipe => {+ self.open_decrypt_at(va, None);+ self.decrypt_pane.bake_preset("magic");+ }+ RowAction::CryptoConstantsAtCursor => {+ self.crypto_constants_focus_va = Some(va);+ self.decrypt_pane.focus(DecryptTab::Constants);+ self.pane_open.insert(PaneKind::Decrypt, true);+ }+ RowAction::RecoverStringsHere => {+ self.recover_strings_at_function(va);+ self.decrypt_pane.focus(DecryptTab::Strings);+ self.pane_open.insert(PaneKind::Decrypt, true);+ }}}}- /// tokenised Decompiler center pane with cross-highlight.+ /// tokenised Decompiler center pane with cross-highlight.fn ui_decompiler_pane(&mut self, ui: &mut egui::Ui) {- ui.heading("Decompiler");+ ui.heading("Decompiler");if self.program.is_none() {- ui.weak("Open a project file, then select a function or listing address.");+ ui.weak("Open a project file, then select a function or listing address.");return;}- // Stage picker (Stage-0 / 0.5 / 1). Changing kicks off a re-emit- // for the currently-focused entry.+ // Stage picker (Stage-0 / 0.5 / 1). Changing kicks off a re-emit+ // for the currently-focused entry.let mut sel = self.decomp_stage;ui.horizontal(|ui| {- ui.label("Stage:");- egui::ComboBox::from_id_salt("decomp_stage_combo")+ ui.label("Stage:");+ egui::ComboBox::from_id_salt("decomp_stage_combo").selected_text(sel.label()).show_ui(ui, |ui| {- ui.selectable_value(&mut sel, DecompStage::Stage0, "Stage-0 (CFG → goto)");- ui.selectable_value(- &mut sel,- DecompStage::Stage05,- "Stage-0.5 (IR-informed)",- );+ ui.selectable_value(&mut sel, DecompStage::Stage0, "Stage-0 (CFG → goto)");+ ui.selectable_value(&mut sel, DecompStage::Stage05, "Stage-0.5 (IR-informed)");ui.selectable_value(&mut sel,DecompStage::Stage1,- "Stage-1 (SSA + structure + types)",+ "Stage-1 (SSA + structure + types)",);});if let Some(r) = self.decomp_lift_ratio {- ui.small(format!("lift {:.1}%", r * 100.0));+ ui.small(format!("lift {:.1}%", r * 100.0));}});if sel != self.decomp_stage {self.set_decomp_stage(sel);}- // Keep cache in sync with cursor when switching to this pane.+ // Keep cache in sync with cursor when switching to this pane.if let Some(va) = self.listing_focus_va.or(self.decomp_entry)@@ -5518,9 +5723,9 @@ impl GhidrustApp {{self.refresh_decompiler_at(va);}- // requested_addr vs resolved_entry (honest containing-function resolve)- // plus an IL2CPP `follow_stub` chip when the resolved entry classifies- // as a lazy resolve thunk with a populated slot.+ // requested_addr vs resolved_entry (honest containing-function resolve)+ // plus an IL2CPP `follow_stub` chip when the resolved entry classifies+ // as a lazy resolve thunk with a populated slot.if let Some(va) = self.listing_focus_va.or(self.decomp_entry) {if let Some(prog) = self.program.as_mut() {if let Ok(resolve) = ghidrust_core::resolve_function(prog, va) {@@ -5530,14 +5735,18 @@ impl GhidrustApp {});ui.horizontal(|ui| {ui.small(format!(- "resolve: requested={:#x} → resolved_entry={} [{:?}]{}",+ "resolve: requested={:#x} → resolved_entry={} [{:?}]{}",resolve.requested_addr,resolve.resolved_entry- .map(|e| format!("{e:#x}"))- .unwrap_or_else(|| "—".into()),+ .map(|e| format!("{e:#x}"))+ .unwrap_or_else(|| "—".into()),resolve.resolve_status,- if resolve.ambiguous { " (ambiguous)" } else { "" },+ if resolve.ambiguous {+ " (ambiguous)"+ } else {+ ""+ },));if let Some(target) = stub_target {ui.small(@@ -5552,7 +5761,7 @@ impl GhidrustApp {}}}- // Header row: stage + entry + Commit/Rename right-click hints.+ // Header row: stage + entry + Commit/Rename right-click hints.ui.horizontal(|ui| {if !self.decomp_status.is_empty() {ui.small(&self.decomp_status);@@ -5560,35 +5769,35 @@ impl GhidrustApp {ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {if let Some(entry) = self.decomp_entry {if ui- .small_button("Commit Params/Return")- .on_hover_text("Persist inferred params + return type as user edits")+ .small_button("Commit Params/Return")+ .on_hover_text("Persist inferred params + return type as user edits").clicked(){if let Err(e) = self.commit_params_return(entry) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());}}if ui- .small_button("Commit Locals")- .on_hover_text("Persist inferred stack locals as user edits")+ .small_button("Commit Locals")+ .on_hover_text("Persist inferred stack locals as user edits").clicked(){if let Err(e) = self.commit_locals(entry) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());}}if ui- .small_button("Edit signature…")- .on_hover_text("Edit function signature")+ .small_button("Edit signature…")+ .on_hover_text("Edit function signature").clicked(){self.open_signature_dialog(entry);}if ui- .small_button("Rename function…")- .on_hover_text("Rename this function (L)")+ .small_button("Rename function…")+ .on_hover_text("Rename this function (L)").clicked(){self.open_rename_dialog(entry);@@ -5603,35 +5812,38 @@ impl GhidrustApp {);return;}- // Render tokenised lines.+ // Render tokenised lines.let visuals = ui.visuals().clone();let text_color = visuals.text_color();let cross_line = self.decomp_cross_line;let highlight_text = self.decomp_highlight_text.clone();let mut clicked_addr: Option<u64> = None;let mut mid_clicked_text: Option<String> = None;- let mut right_click_target: Option<(u64, String)> = None; // (va, token text)+ let mut decrypt_token: Option<(u64, String)> = None;+ let mut copy_decode_input: Option<(u64, String)> = None;+ let mut rename_token: Option<(u64, String)> = None;egui::ScrollArea::both()- .id_salt("decomp_tokens_scroll")+ .id_salt("decomp_tokens_scroll").auto_shrink([false, false]).show(ui, |ui| {let font = egui::FontId::monospace(13.0);for line in &self.decomp_lines {let is_cross = Some(line.line) == cross_line;let bg_frame = if is_cross {- Some(egui::Frame::default().fill(Color32::from_rgba_unmultiplied(- 0xFF, 0xD5, 0x4F, 40,- )))+ Some(+ egui::Frame::default()+ .fill(Color32::from_rgba_unmultiplied(0xFF, 0xD5, 0x4F, 40)),+ )} else {None};let mut render_row = |ui: &mut egui::Ui| {ui.horizontal(|ui| {- // Left rail: address gutter (line.machine_addr).+ // Left rail: address gutter (line.machine_addr).let gutter = line.machine_addr- .map(|va| format!("{va:08x} "))- .unwrap_or_else(|| " ".into());+ .map(|va| format!("{va:08x} "))+ .unwrap_or_else(|| " ".into());ui.add(egui::Label::new(egui::RichText::new(gutter)@@ -5661,9 +5873,9 @@ impl GhidrustApp {rich = rich.italics();}if highlighted {- rich = rich.background_color(- Color32::from_rgba_unmultiplied(0x03, 0xA9, 0xF4, 90),- );+ rich = rich.background_color(Color32::from_rgba_unmultiplied(+ 0x03, 0xA9, 0xF4, 90,+ ));}let clickable = matches!(tok.kind,@@ -5684,14 +5896,40 @@ impl GhidrustApp {if resp.middle_clicked() {mid_clicked_text = Some(tok.text.clone());}- if resp.secondary_clicked() {- if let Some(va) = tok.va.or(line.machine_addr) {- right_click_target = Some((va, tok.text.clone()));- }+ if let Some(va) = tok.va.or(line.machine_addr) {+ let is_decode_input = matches!(+ tok.kind,+ TokenKind::Constant | TokenKind::Address+ );+ let is_identifier = tok+ .text+ .chars()+ .next()+ .map(|c| c.is_ascii_alphabetic() || c == '_')+ .unwrap_or(false);+ resp.context_menu(|ui| {+ if is_decode_input+ && ui.button("Decrypt constant…").clicked()+ {+ decrypt_token = Some((va, tok.text.clone()));+ ui.close_menu();+ }+ if is_decode_input+ && ui.button("Copy as decode input").clicked()+ {+ copy_decode_input = Some((va, tok.text.clone()));+ ui.close_menu();+ }+ if is_identifier+ && ui.button("Rename symbol…").clicked()+ {+ rename_token = Some((va, tok.text.clone()));+ ui.close_menu();+ }+ });}if resp.hovered() {- ui.ctx()- .set_cursor_icon(egui::CursorIcon::PointingHand);+ ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);}} else {ui.add(egui::Label::new(rich).selectable(true));@@ -5707,23 +5945,29 @@ impl GhidrustApp {}});if let Some(text) = mid_clicked_text {- self.decomp_highlight_text = if self.decomp_highlight_text.as_deref() == Some(text.as_str()) {- None- } else {- Some(text)- };+ self.decomp_highlight_text =+ if self.decomp_highlight_text.as_deref() == Some(text.as_str()) {+ None+ } else {+ Some(text)+ };}- if let Some((va, text)) = right_click_target {- // Right-click on a token opens the rename dialog when it looks like an identifier.- if !text.is_empty()- && text.chars().next().map(|c| c.is_ascii_alphabetic() || c == '_').unwrap_or(false)- {- self.open_rename_dialog(va);- self.rename_dialog_old_name = text;- }+ if let Some((va, text)) = decrypt_token {+ self.decrypt_pane+ .load_text(Some(va), text, "Decompiler constant");+ self.pane_open.insert(PaneKind::Decrypt, true);+ }+ if let Some((va, text)) = copy_decode_input {+ self.decrypt_pane+ .load_text(Some(va), text, "Decompiler token");+ self.pane_open.insert(PaneKind::Decrypt, true);+ }+ if let Some((va, text)) = rename_token {+ self.open_rename_dialog(va);+ self.rename_dialog_old_name = text;}if let Some(va) = clicked_addr {- // Only navigate if VA looks plausibly in-range (avoid `block_0` id = 0 jumping to base).+ // Only navigate if VA looks plausibly in-range (avoid `block_0` id = 0 jumping to base).let plausible = self.program.as_ref()@@ -5731,7 +5975,7 @@ impl GhidrustApp {.unwrap_or(false)|| va >= 0x1000;if plausible {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}}}@@ -5786,12 +6030,12 @@ impl GhidrustApp {.and_then(|p| p.function_at(entry)).map(|f| {format!(- "undefined {}({})",+ "undefined {}({})",f.name,if f.parameters.is_empty() {- "void".to_string()+ "void".to_string()} else {- f.parameters.join(", ")+ f.parameters.join(", ")})})@@ -5829,30 +6073,28 @@ impl GhidrustApp {}fn ui_bookmarks_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {- ui.heading("Bookmarks");- ui.small(- egui::RichText::new("BookmarkPlugin analog · 5 standard kinds").color(muted),- );+ ui.heading("Bookmarks");+ ui.small(egui::RichText::new("BookmarkPlugin analog · 5 standard kinds").color(muted));ui.separator();ui.horizontal(|ui| {- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut self.bookmark_filter).desired_width(200.0)- .hint_text("category or description"),+ .hint_text("category or description"),);if ui- .button("Add at cursor…")- .on_hover_text("Add a bookmark at the current Listing VA")+ .button("Add at cursor…")+ .on_hover_text("Add a bookmark at the current Listing VA").clicked(){if let Some(va) = self.listing_focus_va {self.bookmark_dialog_kind = BookmarkKind::Note;self.bookmark_dialog_category = String::new();- self.bookmark_dialog_description = format!("bookmark @ {va:#x}");+ self.bookmark_dialog_description = format!("bookmark @ {va:#x}");self.show_bookmark_dialog = true;} else {- self.status = "No cursor VA — click a Listing line first".into();+ self.status = "No cursor VA — click a Listing line first".into();self.log(self.status.clone());}}@@ -5860,7 +6102,7 @@ impl GhidrustApp {ui.separator();if self.bookmarks.is_empty() {- ui.weak("No bookmarks yet — click Add at cursor to place one.");+ ui.weak("No bookmarks yet — click Add at cursor to place one.");return;}@@ -5875,32 +6117,28 @@ impl GhidrustApp {|| b.description.to_ascii_lowercase().contains(&filt)|| b.kind.label().to_ascii_lowercase().contains(&filt)})- .map(|(i, b)| {- (- i,- b.va,- b.kind,- b.category.clone(),- b.description.clone(),- )- })+ .map(|(i, b)| (i, b.va, b.kind, b.category.clone(), b.description.clone())).collect();- ui.small(format!("{} / {} bookmarks", rows.len(), self.bookmarks.len()));+ ui.small(format!(+ "{} / {} bookmarks",+ rows.len(),+ self.bookmarks.len()+ ));egui::ScrollArea::vertical()- .id_salt("bookmarks_scroll")+ .id_salt("bookmarks_scroll").max_height(360.0).show(ui, |ui| {- egui::Grid::new("bookmarks_grid")+ egui::Grid::new("bookmarks_grid").num_columns(5).striped(true).show(ui, |ui| {- ui.strong("Type");- ui.strong("Address");- ui.strong("Category");- ui.strong("Description");- ui.strong("");+ ui.strong("Type");+ ui.strong("Address");+ ui.strong("Category");+ ui.strong("Description");+ ui.strong("");ui.end_row();let mut goto: Option<u64> = None;@@ -5912,22 +6150,22 @@ impl GhidrustApp {.strong(),);if ui- .link(egui::RichText::new(format!("{va:#x}")).monospace())- .on_hover_text("Go To this address")+ .link(egui::RichText::new(format!("{va:#x}")).monospace())+ .on_hover_text("Go To this address").clicked(){goto = Some(*va);}ui.label(cat);ui.label(desc);- if ui.small_button("Delete").clicked() {+ if ui.small_button("Delete").clicked() {delete = Some(*idx);}ui.end_row();}let _ = primary; // reserved for future accent useif let Some(va) = goto {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}if let Some(i) = delete {self.delete_bookmark(i);@@ -5937,44 +6175,44 @@ impl GhidrustApp {}fn ui_memory_map_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("Memory Map");+ ui.heading("Memory Map");ui.small(egui::RichText::new(- "MemoryMapPlugin · toggle RWX / add / delete session memory blocks",+ "MemoryMapPlugin · toggle RWX / add / delete session memory blocks",).color(muted),);ui.separator();if self.program.is_none() {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;}- // Add-row form.+ // Add-row form.ui.horizontal(|ui| {- ui.label("Add block:");+ ui.label("Add block:");ui.add(egui::TextEdit::singleline(&mut self.memory_map_new_name).desired_width(120.0)- .hint_text("name"),+ .hint_text("name"),);ui.add(egui::TextEdit::singleline(&mut self.memory_map_new_va).desired_width(120.0)- .hint_text("VA (0x…)"),+ .hint_text("VA (0x…)"),);ui.add(egui::TextEdit::singleline(&mut self.memory_map_new_size).desired_width(100.0)- .hint_text("size (0x…)"),+ .hint_text("size (0x…)"),);- ui.checkbox(&mut self.memory_map_new_r, "R");- ui.checkbox(&mut self.memory_map_new_w, "W");- ui.checkbox(&mut self.memory_map_new_x, "X");+ ui.checkbox(&mut self.memory_map_new_r, "R");+ ui.checkbox(&mut self.memory_map_new_w, "W");+ ui.checkbox(&mut self.memory_map_new_x, "X");let can_add = !self.memory_map_new_name.trim().is_empty()&& !self.memory_map_new_va.trim().is_empty()&& !self.memory_map_new_size.trim().is_empty();- if ui.add_enabled(can_add, egui::Button::new("Add")).clicked() {+ if ui.add_enabled(can_add, egui::Button::new("Add")).clicked() {let name = self.memory_map_new_name.clone();let va = parse_address(&self.memory_map_new_va).unwrap_or(0);let size = parse_address(&self.memory_map_new_size).unwrap_or(0);@@ -5993,7 +6231,7 @@ impl GhidrustApp {executable: x,});}- self.status = "Memory Map · added block".into();+ self.status = "Memory Map · added block".into();self.log(self.status.clone());}}@@ -6018,21 +6256,21 @@ impl GhidrustApp {.unwrap_or_default();egui::ScrollArea::both()- .id_salt("memmap_scroll")+ .id_salt("memmap_scroll").show(ui, |ui| {- egui::Grid::new("memory_map_grid")+ egui::Grid::new("memory_map_grid").num_columns(9).striped(true).show(ui, |ui| {- ui.strong("Name");- ui.strong("Start");- ui.strong("End");- ui.strong("Length");- ui.strong("R");- ui.strong("W");- ui.strong("X");- ui.strong("Notes");- ui.strong("");+ ui.strong("Name");+ ui.strong("Start");+ ui.strong("End");+ ui.strong("Length");+ ui.strong("R");+ ui.strong("W");+ ui.strong("X");+ ui.strong("Notes");+ ui.strong("");ui.end_row();let blocks: Vec<(String, u64, u64, bool, bool, bool)> = self.program@@ -6056,46 +6294,43 @@ impl GhidrustApp {for (i, (name, va, size, r, w, x)) in blocks.iter().enumerate() {let mut editable = name.clone();if ui- .add(- egui::TextEdit::singleline(&mut editable)- .desired_width(120.0),- )+ .add(egui::TextEdit::singleline(&mut editable).desired_width(120.0)).changed(){rename = Some((i, editable));}if ui- .link(egui::RichText::new(format!("{va:#x}")).monospace())+ .link(egui::RichText::new(format!("{va:#x}")).monospace()).clicked(){goto = Some(*va);}- ui.monospace(format!("{:#x}", va.saturating_add(*size)));- ui.monospace(format!("{size:#x}"));+ ui.monospace(format!("{:#x}", va.saturating_add(*size)));+ ui.monospace(format!("{size:#x}"));let mut rb = *r;let mut wb = *w;let mut xb = *x;- if ui.checkbox(&mut rb, "").changed() {- toggle = Some((i, 'R'));+ if ui.checkbox(&mut rb, "").changed() {+ toggle = Some((i, 'R'));}- if ui.checkbox(&mut wb, "").changed() {- toggle = Some((i, 'W'));+ if ui.checkbox(&mut wb, "").changed() {+ toggle = Some((i, 'W'));}- if ui.checkbox(&mut xb, "").changed() {- toggle = Some((i, 'X'));+ if ui.checkbox(&mut xb, "").changed() {+ toggle = Some((i, 'X'));}- let notes = notes_by_section.get(name.trim_end_matches('\0'));+ let notes = notes_by_section.get(name.trim_end_matches('\0'));match notes {Some(msgs) => {- let joined = msgs.join(" · ");- ui.small(egui::RichText::new("⚠ notes").color(muted))+ let joined = msgs.join(" · ");+ ui.small(egui::RichText::new("⚠ notes").color(muted)).on_hover_text(joined);}None => {- ui.small(egui::RichText::new("—").color(muted));+ ui.small(egui::RichText::new("—").color(muted));}}- if ui.small_button("Delete").clicked() {+ if ui.small_button("Delete").clicked() {delete = Some(i);}ui.end_row();@@ -6104,7 +6339,7 @@ impl GhidrustApp {});if let Some(va) = goto {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}if let Some((i, newname)) = rename {if let Some(prog) = self.program.as_mut() {@@ -6117,9 +6352,9 @@ impl GhidrustApp {if let Some(prog) = self.program.as_mut() {if let Some(b) = prog.blocks.get_mut(i) {match ch {- 'R' => b.readable = !b.readable,- 'W' => b.writable = !b.writable,- 'X' => b.executable = !b.executable,+ 'R' => b.readable = !b.readable,+ 'W' => b.writable = !b.writable,+ 'X' => b.executable = !b.executable,_ => {}}}@@ -6135,27 +6370,27 @@ impl GhidrustApp {}fn ui_functions_window(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {- ui.heading("Functions");+ ui.heading("Functions");ui.small(- egui::RichText::new("FunctionWindowPlugin · flat table of Program::analysis.functions")+ egui::RichText::new("FunctionWindowPlugin · flat table of Program::analysis.functions").color(muted),);ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};let n_total = prog.analysis.functions.len();if n_total == 0 {- ui.weak("No functions — run Function Start Search.");+ ui.weak("No functions — run Function Start Search.");return;}ui.horizontal(|ui| {- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut self.functions_window_filter).desired_width(300.0)- .hint_text("Function name…"),+ .hint_text("Function name…"),);});let q = self.functions_window_filter.to_ascii_lowercase();@@ -6166,33 +6401,37 @@ impl GhidrustApp {.filter(|f| q.is_empty() || f.name.to_ascii_lowercase().contains(&q)).map(|f| (f.entry, f.end, f.name.clone(), f.parameters.len())).collect();- ui.small(format!("{} / {} functions", rows.len(), n_total));+ ui.small(format!("{} / {} functions", rows.len(), n_total));let focus = self.decomp_entry;egui::ScrollArea::vertical()- .id_salt("fnwin_scroll")+ .id_salt("fnwin_scroll").max_height(400.0).show(ui, |ui| {- egui::Grid::new("functions_window_grid")+ egui::Grid::new("functions_window_grid").num_columns(4).striped(true).show(ui, |ui| {- ui.strong("Entry");- ui.strong("Size");- ui.strong("Name");- ui.strong("Params");+ ui.strong("Entry");+ ui.strong("Size");+ ui.strong("Name");+ ui.strong("Params");ui.end_row();let mut clicked: Option<u64> = None;for (entry, end, name, params) in &rows {let size = end.saturating_sub(*entry);- let addr_text = egui::RichText::new(format!("{entry:#x}"))+ let addr_text = egui::RichText::new(format!("{entry:#x}")).monospace()- .color(if focus == Some(*entry) { primary } else { ui.visuals().text_color() });+ .color(if focus == Some(*entry) {+ primary+ } else {+ ui.visuals().text_color()+ });if ui.link(addr_text).clicked() {clicked = Some(*entry);}- ui.monospace(format!("{size:#x}"));+ ui.monospace(format!("{size:#x}"));ui.label(name);- ui.monospace(format!("{params}"));+ ui.monospace(format!("{params}"));ui.end_row();}if let Some(va) = clicked {@@ -6203,64 +6442,68 @@ impl GhidrustApp {}fn ui_symbol_table(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("Symbol Table");+ ui.heading("Symbol Table");ui.small(egui::RichText::new(- "SymbolTablePlugin · symbols + function entries · Refs → opens Symbol References",+ "SymbolTablePlugin · symbols + function entries · Refs → opens Symbol References",).color(muted),);ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};ui.horizontal(|ui| {- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut self.symbol_table_filter).desired_width(280.0)- .hint_text("Symbol name…"),+ .hint_text("Symbol name…"),);});let q = self.symbol_table_filter.to_ascii_lowercase();- // Merge analysis.symbols + function entries into one flat table.- let mut rows: Vec<(u64, String, &'static str)> = Vec::new();+ // Merge analysis.symbols + function entries into one flat table.+ let mut rows: Vec<(u64, String, &'static str)> = Vec::new();for s in &prog.analysis.symbols {- rows.push((s.va, s.name.clone(), "Symbol"));+ rows.push((s.va, s.name.clone(), "Symbol"));}for f in &prog.analysis.functions {- rows.push((f.entry, f.name.clone(), "Function"));+ rows.push((f.entry, f.name.clone(), "Function"));}rows.retain(|(_, name, _)| q.is_empty() || name.to_ascii_lowercase().contains(&q));rows.sort_by_key(|r| r.0);- ui.small(format!("{} rows", rows.len()));+ ui.small(format!("{} rows", rows.len()));let mut goto: Option<u64> = None;let mut show_refs: Option<u64> = None;egui::ScrollArea::vertical()- .id_salt("symtable_scroll")+ .id_salt("symtable_scroll").max_height(400.0).show(ui, |ui| {- egui::Grid::new("symbol_table_grid")+ egui::Grid::new("symbol_table_grid").num_columns(4).striped(true).show(ui, |ui| {- ui.strong("Address");- ui.strong("Name");- ui.strong("Type");- ui.strong("Refs");+ ui.strong("Address");+ ui.strong("Name");+ ui.strong("Type");+ ui.strong("Refs");ui.end_row();for (va, name, ty) in &rows {if ui- .link(egui::RichText::new(format!("{va:#x}")).monospace())+ .link(egui::RichText::new(format!("{va:#x}")).monospace()).clicked(){goto = Some(*va);}ui.label(name);ui.monospace(*ty);- if ui.small_button("Refs").on_hover_text("Open Symbol References for this VA").clicked() {+ if ui+ .small_button("Refs")+ .on_hover_text("Open Symbol References for this VA")+ .clicked()+ {show_refs = Some(*va);}ui.end_row();@@ -6268,7 +6511,7 @@ impl GhidrustApp {});});if let Some(va) = goto {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}if let Some(va) = show_refs {self.symbol_refs_target = Some(va);@@ -6276,29 +6519,158 @@ impl GhidrustApp {}}+ fn open_decrypt_at(&mut self, va: u64, hint: Option<String>) {+ self.open_decrypt_at_len(va, 256, hint);+ }++ fn open_decrypt_at_len(&mut self, va: u64, len: usize, hint: Option<String>) {+ let bytes = self+ .program+ .as_ref()+ .and_then(|p| decrypt_ui::bytes_at(p, va, len))+ .unwrap_or_default();+ self.decrypt_pane.load_bytes(Some(va), &bytes, hint);+ self.decrypt_pane.focus(DecryptTab::Bake);+ self.decrypt_pane.va_input = format!("{va:x}");+ self.decrypt_pane.va_len = len;+ self.pane_open.insert(PaneKind::Decrypt, true);+ }++ fn open_decrypt_nearby(&mut self, va: u64, hint: Option<String>) {+ let start = va.saturating_sub(32);+ let bytes = self+ .program+ .as_ref()+ .and_then(|p| decrypt_ui::bytes_at(p, start, 256))+ .unwrap_or_default();+ self.decrypt_pane.load_bytes(Some(va), &bytes, hint);+ self.decrypt_pane.input_source = format!("Bytes near crypto result at {va:#x}");+ self.decrypt_pane.focus(DecryptTab::Bake);+ self.pane_open.insert(PaneKind::Decrypt, true);+ }++ fn recover_strings_at_function(&mut self, va: u64) {+ let Some(prog) = self.program.as_ref() else {+ self.status = "Recover strings requires a loaded program.".into();+ return;+ };+ let entry = prog+ .analysis+ .functions+ .iter()+ .find(|f| va >= f.entry && va < f.end)+ .map(|f| f.entry)+ .unwrap_or(va);+ let hits = recover_obfuscated_strings(+ prog,+ &RecoverStringsOpts {+ functions: Some(vec![entry]),+ ..Default::default()+ },+ );+ self.obfuscated_strings = hits;+ self.status = format!(+ "Recovered {} strings in containing function {entry:#x}",+ self.obfuscated_strings.len()+ );+ }++ fn ui_crypto_constants_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {+ let hits: Vec<_> = if let Some(va) = self.crypto_constants_focus_va {+ let mut nearby: Vec<_> = self+ .crypt_constants+ .iter()+ .filter(|h| h.va.abs_diff(va) <= 0x1000)+ .cloned()+ .collect();+ nearby.sort_by_key(|h| h.va.abs_diff(va));+ nearby+ } else {+ self.crypt_constants.clone()+ };+ let mut goto = None;+ let mut decrypt = None;+ decrypt_ui::ui_crypto_constants(+ ui,+ muted,+ &hits,+ |va| goto = Some(va),+ |va, algo| decrypt = Some((va, algo.to_string())),+ );+ if let Some(va) = goto {+ let _ = self.goto_address_str(&format!("{va:#x}"));+ }+ if let Some((va, algo)) = decrypt {+ self.open_decrypt_nearby(va, Some(algo));+ }+ }++ fn ui_recovered_strings_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {+ let hits = self.obfuscated_strings.clone();+ let mut goto = None;+ let mut bake = None;+ let mut decoder = None;+ decrypt_ui::ui_recovered_strings(+ ui,+ muted,+ &hits,+ |va| goto = Some(va),+ |va| bake = Some(va),+ |va| decoder = Some(va),+ );+ if let Some(va) = goto {+ let _ = self.goto_address_str(&format!("{va:#x}"));+ }+ if let Some(va) = bake {+ self.open_decrypt_at(va, None);+ }+ if let Some(va) = decoder {+ self.focus_function(va);+ }+ }++ fn ui_crypto_capabilities_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {+ let hits = self.crypto_capabilities.clone();+ let mut goto = None;+ let mut decrypt = None;+ decrypt_ui::ui_crypto_capabilities(+ ui,+ muted,+ &hits,+ |va| goto = Some(va),+ |va, hint| decrypt = Some((va, hint)),+ );+ if let Some(va) = goto {+ let _ = self.goto_address_str(&format!("{va:#x}"));+ }+ if let Some((va, hint)) = decrypt {+ self.open_decrypt_at(va, Some(hint));+ }+ }+fn ui_defined_strings(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("Defined Strings");+ ui.heading("Defined Strings");ui.small(- egui::RichText::new("ViewStringsPlugin · session strings from ASCII Strings analyzer")+ egui::RichText::new("ViewStringsPlugin · session strings from ASCII Strings analyzer").color(muted),);ui.separator();if self.strings.is_empty() {- ui.weak("No strings yet — run ASCII Strings analyzer.");+ ui.weak("No strings yet — run ASCII Strings analyzer.");return;}ui.horizontal(|ui| {- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut self.defined_strings_filter).desired_width(280.0)- .hint_text("Substring…"),+ .hint_text("Substring…"),);- ui.label("Encoding:");- egui::ComboBox::from_id_salt("defined_strings_encoding_combo")+ ui.label("Encoding:");+ egui::ComboBox::from_id_salt("defined_strings_encoding_combo").selected_text(self.defined_strings_encoding.clone()).show_ui(ui, |ui| {- for enc in ["all", "ascii", "utf16le"] {+ for enc in ["all", "ascii", "utf16le"] {ui.selectable_value(&mut self.defined_strings_encoding, enc.into(), enc);}});@@ -6309,26 +6681,26 @@ impl GhidrustApp {.strings.iter().filter(|s| q.is_empty() || s.value.to_ascii_lowercase().contains(&q))- .filter(|s| enc_filter == "all" || s.encoding == enc_filter)+ .filter(|s| enc_filter == "all" || s.encoding == enc_filter).map(|s| (s.va, s.value.clone(), s.encoding.clone())).collect();- ui.small(format!("{} / {} strings", rows.len(), self.strings.len()));+ ui.small(format!("{} / {} strings", rows.len(), self.strings.len()));egui::ScrollArea::vertical()- .id_salt("defstr_scroll")+ .id_salt("defstr_scroll").max_height(400.0).show(ui, |ui| {- egui::Grid::new("defined_strings_grid")+ egui::Grid::new("defined_strings_grid").num_columns(3).striped(true).show(ui, |ui| {- ui.strong("Address");- ui.strong("Encoding");- ui.strong("String");+ ui.strong("Address");+ ui.strong("Encoding");+ ui.strong("String");ui.end_row();let mut goto: Option<u64> = None;for (va, s, enc) in &rows {if ui- .link(egui::RichText::new(format!("{va:#x}")).monospace())+ .link(egui::RichText::new(format!("{va:#x}")).monospace()).clicked(){goto = Some(*va);@@ -6339,21 +6711,20 @@ impl GhidrustApp {ui.end_row();}if let Some(va) = goto {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}});});}fn ui_relocation_table(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("Relocation Table");+ ui.heading("Relocation Table");ui.small(- egui::RichText::new("RelocationTablePlugin · from Program::sections")- .color(muted),+ egui::RichText::new("RelocationTablePlugin · from Program::sections").color(muted),);ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};ui.small(@@ -6364,38 +6735,35 @@ impl GhidrustApp {.color(muted).italics(),);- egui::Grid::new("relocs_grid")+ egui::Grid::new("relocs_grid").num_columns(3).striped(true).show(ui, |ui| {- ui.strong("Section");- ui.strong("VA");- ui.strong("Size");+ ui.strong("Section");+ ui.strong("VA");+ ui.strong("Size");ui.end_row();for s in &prog.sections {ui.label(&s.name);- ui.monospace(format!("{:#x}", s.va));- ui.monospace(format!("{:#x}", s.virtual_size));+ ui.monospace(format!("{:#x}", s.va));+ ui.monospace(format!("{:#x}", s.virtual_size));ui.end_row();}});}fn ui_disassembled_view_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("Disassembled View");- ui.small(- egui::RichText::new("DisassembledViewPlugin · detail at cursor")- .color(muted),- );+ ui.heading("Disassembled View");+ ui.small(egui::RichText::new("DisassembledViewPlugin · detail at cursor").color(muted));ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};let va = match self.listing_focus_va.or(prog.entry) {Some(v) => v,None => {- ui.weak("No cursor / entry.");+ ui.weak("No cursor / entry.");return;}};@@ -6413,32 +6781,32 @@ impl GhidrustApp {}fn ui_comment_window(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("Comments");+ ui.heading("Comments");ui.small(egui::RichText::new(- "CommentWindowPlugin · shows EOL/Pre/Post/Plate/Repeatable edits + bookmarks",+ "CommentWindowPlugin · shows EOL/Pre/Post/Plate/Repeatable edits + bookmarks",).color(muted),);ui.separator();- // Filter row — CommentWindow provides both a text filter and- // a per-kind toggle.+ // Filter row — CommentWindow provides both a text filter and+ // a per-kind toggle.ui.horizontal(|ui| {- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut self.comment_window_filter).desired_width(240.0)- .hint_text("Text / address / kind…"),+ .hint_text("Text / address / kind…"),);- ui.label("Kind:");+ ui.label("Kind:");let cur = self.comment_window_kind_filter.map(|k| k.label())- .unwrap_or("All");- egui::ComboBox::from_id_salt("comment_window_kind_combo")+ .unwrap_or("All");+ egui::ComboBox::from_id_salt("comment_window_kind_combo").selected_text(cur).show_ui(ui, |ui| {- ui.selectable_value(&mut self.comment_window_kind_filter, None, "All");+ ui.selectable_value(&mut self.comment_window_kind_filter, None, "All");for k in CommentKind::ALL {ui.selectable_value(&mut self.comment_window_kind_filter,@@ -6449,23 +6817,23 @@ impl GhidrustApp {});});ui.separator();- // Real edited comments from ProgramEdits — one row per (va, kind).- let mut rows: Vec<(&'static str, u64, String)> = Vec::new();+ // Real edited comments from ProgramEdits — one row per (va, kind).+ let mut rows: Vec<(&'static str, u64, String)> = Vec::new();if let Some(prog) = self.program.as_ref() {for ((va, kind), text) in &prog.edits.comments {rows.push((kind.label(), *va, text.clone()));}}- // Also surface bookmarks as "Note-derived" comment rows.+ // Also surface bookmarks as "Note-derived" comment rows.for b in &self.bookmarks {let text = if b.category.is_empty() {b.description.clone()} else {- format!("[{}] {}", b.category, b.description)+ format!("[{}] {}", b.category, b.description)};- rows.push(("Bookmark", b.va, text));+ rows.push(("Bookmark", b.va, text));}- // Apply filters.+ // Apply filters.let text_filter = self.comment_window_filter.to_ascii_lowercase();let kind_filter = self.comment_window_kind_filter;rows.retain(|(kind, va, text)| {@@ -6477,7 +6845,7 @@ impl GhidrustApp {if text_filter.is_empty() {return true;}- let addr = format!("{va:#x}");+ let addr = format!("{va:#x}");text.to_ascii_lowercase().contains(&text_filter)|| kind.to_ascii_lowercase().contains(&text_filter)|| addr.contains(&text_filter)@@ -6490,31 +6858,31 @@ impl GhidrustApp {}rows.sort_by_key(|(_, va, _)| *va);egui::ScrollArea::vertical()- .id_salt("comment_window_scroll")+ .id_salt("comment_window_scroll").max_height(400.0).show(ui, |ui| {- egui::Grid::new("comments_grid")+ egui::Grid::new("comments_grid").num_columns(3).striped(true).show(ui, |ui| {- ui.strong("Type");- ui.strong("Address");- ui.strong("Comment");+ ui.strong("Type");+ ui.strong("Address");+ ui.strong("Comment");ui.end_row();let mut goto: Option<u64> = None;let mut delete: Option<(u64, CommentKind)> = None;for (kind, va, text) in &rows {let color = match *kind {- "EOL" => Color32::from_rgb(0x81, 0xC7, 0x84),- "Pre" => Color32::from_rgb(0x64, 0xB5, 0xF6),- "Post" => Color32::from_rgb(0xBA, 0x68, 0xC8),- "Plate" => Color32::from_rgb(0xFF, 0xB7, 0x4D),- "Repeatable" => Color32::from_rgb(0x4D, 0xD0, 0xE1),+ "EOL" => Color32::from_rgb(0x81, 0xC7, 0x84),+ "Pre" => Color32::from_rgb(0x64, 0xB5, 0xF6),+ "Post" => Color32::from_rgb(0xBA, 0x68, 0xC8),+ "Plate" => Color32::from_rgb(0xFF, 0xB7, 0x4D),+ "Repeatable" => Color32::from_rgb(0x4D, 0xD0, 0xE1),_ => Color32::from_rgb(0x9C, 0x27, 0xB0),};ui.label(egui::RichText::new(*kind).color(color).strong());if ui- .link(egui::RichText::new(format!("{va:#x}")).monospace())+ .link(egui::RichText::new(format!("{va:#x}")).monospace()).clicked(){goto = Some(*va);@@ -6522,15 +6890,15 @@ impl GhidrustApp {ui.horizontal(|ui| {ui.label(text);let matching_kind = match *kind {- "EOL" => Some(CommentKind::Eol),- "Pre" => Some(CommentKind::Pre),- "Post" => Some(CommentKind::Post),- "Plate" => Some(CommentKind::Plate),- "Repeatable" => Some(CommentKind::Repeatable),+ "EOL" => Some(CommentKind::Eol),+ "Pre" => Some(CommentKind::Pre),+ "Post" => Some(CommentKind::Post),+ "Plate" => Some(CommentKind::Plate),+ "Repeatable" => Some(CommentKind::Repeatable),_ => None,};if let Some(k) = matching_kind {- if ui.small_button("Del").clicked() {+ if ui.small_button("Del").clicked() {delete = Some((*va, k));}}@@ -6538,20 +6906,22 @@ impl GhidrustApp {ui.end_row();}if let Some(va) = goto {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}if let Some((va, k)) = delete {- let _ = self.set_comment_at(va, k, "");+ let _ = self.set_comment_at(va, k, "");}});});}fn ui_defined_data(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("Defined Data");+ ui.heading("Defined Data");ui.small(- egui::RichText::new("DataWindowPlugin · session data (Program::data_items when available)")- .color(muted),+ egui::RichText::new(+ "DataWindowPlugin · session data (Program::data_items when available)",+ )+ .color(muted),);ui.separator();let rtti_rows: Vec<(u64, String)> = match self.program.as_ref() {@@ -6563,12 +6933,12 @@ impl GhidrustApp {.filter_map(|c| c.type_info_va.map(|va| (va, c.name.clone()))).collect(),None => {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;}};if self.strings.is_empty() && rtti_rows.is_empty() {- ui.weak("No defined data (strings/RTTI) available yet — run ASCII Strings / RTTI analyzers.");+ ui.weak("No defined data (strings/RTTI) available yet — run ASCII Strings / RTTI analyzers.");return;}let str_rows: Vec<(u64, String)> = self@@ -6579,97 +6949,100 @@ impl GhidrustApp {.collect();let mut goto: Option<u64> = None;egui::ScrollArea::vertical()- .id_salt("defined_data_scroll")+ .id_salt("defined_data_scroll").max_height(400.0).show(ui, |ui| {- egui::Grid::new("defined_data_grid")+ egui::Grid::new("defined_data_grid").num_columns(3).striped(true).show(ui, |ui| {- ui.strong("Address");- ui.strong("Type");- ui.strong("Preview");+ ui.strong("Address");+ ui.strong("Type");+ ui.strong("Preview");ui.end_row();for (va, val) in &str_rows {if ui- .link(egui::RichText::new(format!("{va:#x}")).monospace())+ .link(egui::RichText::new(format!("{va:#x}")).monospace()).clicked(){goto = Some(*va);}- ui.monospace("string");+ ui.monospace("string");ui.label(val);ui.end_row();}for (va, name) in &rtti_rows {if ui- .link(egui::RichText::new(format!("{va:#x}")).monospace())+ .link(egui::RichText::new(format!("{va:#x}")).monospace()).clicked(){goto = Some(*va);}- ui.monospace("rtti");+ ui.monospace("rtti");ui.label(name);ui.end_row();}});});if let Some(va) = goto {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}}- // ── Byte Viewer / Symbol References / Equates / Tags ─+ // ── Byte Viewer / Symbol References / Equates / Tags ─- /// ByteViewerPluginue — split hex / ASCII view of the- /// program's memory around the current cursor. Bytes-per-line combo,- /// programmable offset override, and click-to-navigate address column.+ /// ByteViewerPluginue — split hex / ASCII view of the+ /// program's memory around the current cursor. Bytes-per-line combo,+ /// programmable offset override, and click-to-navigate address column.fn ui_bytes_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {- ui.heading("Bytes");+ ui.heading("Bytes");ui.small(- egui::RichText::new(- "ByteViewerPlugin · split hex / ASCII, follows Listing cursor",- )- .color(muted),+ egui::RichText::new("ByteViewerPlugin · split hex / ASCII, follows Listing cursor")+ .color(muted),);ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};- // Cursor tracking — default to Listing focus, editable via combo.+ // Cursor tracking — default to Listing focus, editable via combo.if self.bytes_pane_va.is_none() {- self.bytes_pane_va = self.listing_focus_va.or(prog.entry).or_else(|| {- prog.blocks.first().map(|b| b.va)- });+ self.bytes_pane_va = self+ .listing_focus_va+ .or(prog.entry)+ .or_else(|| prog.blocks.first().map(|b| b.va));}let base_va = self.bytes_pane_va.unwrap_or(prog.image_base);ui.horizontal(|ui| {- ui.label("VA:");- let mut input = format!("{base_va:#x}");+ ui.label("VA:");+ let mut input = format!("{base_va:#x}");let resp = ui.add(egui::TextEdit::singleline(&mut input).desired_width(140.0));if resp.lost_focus() {if let Ok(v) = parse_address(&input) {self.bytes_pane_va = Some(v);}}- ui.label("Bytes/line:");- egui::ComboBox::from_id_salt("bytes_pane_bpr")- .selected_text(format!("{}", self.bytes_pane_bpr))+ ui.label("Bytes/line:");+ egui::ComboBox::from_id_salt("bytes_pane_bpr")+ .selected_text(format!("{}", self.bytes_pane_bpr)).show_ui(ui, |ui| {for w in [8usize, 12, 16, 24, 32] {- ui.selectable_value(&mut self.bytes_pane_bpr, w, format!("{w}"));+ ui.selectable_value(&mut self.bytes_pane_bpr, w, format!("{w}"));}});- ui.label("Rows:");- egui::ComboBox::from_id_salt("bytes_pane_rows")- .selected_text(format!("{}", self.bytes_pane_rows))+ ui.label("Rows:");+ egui::ComboBox::from_id_salt("bytes_pane_rows")+ .selected_text(format!("{}", self.bytes_pane_rows)).show_ui(ui, |ui| {for r in [8usize, 16, 24, 32, 48, 64] {- ui.selectable_value(&mut self.bytes_pane_rows, r, format!("{r}"));+ ui.selectable_value(&mut self.bytes_pane_rows, r, format!("{r}"));}});- if ui.button("Follow cursor").on_hover_text("Snap to Listing cursor").clicked() {+ if ui+ .button("Follow cursor")+ .on_hover_text("Snap to Listing cursor")+ .clicked()+ {self.bytes_pane_va = self.listing_focus_va;}});@@ -6683,59 +7056,65 @@ impl GhidrustApp {let focus_va = self.listing_focus_va;let mut nav: Option<u64> = None;egui::ScrollArea::vertical()- .id_salt("bytes_scroll")+ .id_salt("bytes_scroll").max_height(420.0).show(ui, |ui| {for row in 0..self.bytes_pane_rows {let row_va = base_va.wrapping_add((row * bpr) as u64);ui.horizontal(|ui| {- let addr = egui::RichText::new(format!("{row_va:016x}"))+ let addr = egui::RichText::new(format!("{row_va:016x}")).monospace()- .color(if Some(row_va) == focus_va { primary } else { ui.visuals().text_color() });- if ui.link(addr).on_hover_text("Go To in Listing").clicked() {+ .color(if Some(row_va) == focus_va {+ primary+ } else {+ ui.visuals().text_color()+ });+ if ui.link(addr).on_hover_text("Go To in Listing").clicked() {nav = Some(row_va);}- ui.label("│");+ ui.label("│");let mut hex_line = String::new();let mut ascii_line = String::new();for col in 0..bpr {let idx = row * bpr + col;match bytes.get(idx).and_then(|b| *b) {Some(b) => {- hex_line.push_str(&format!("{b:02x} "));- let c = if (0x20..=0x7f).contains(&b) { b as char } else { '.' };+ hex_line.push_str(&format!("{b:02x} "));+ let c = if (0x20..=0x7f).contains(&b) {+ b as char+ } else {+ '.'+ };ascii_line.push(c);}None => {- hex_line.push_str("?? ");- ascii_line.push(' ');+ hex_line.push_str("?? ");+ ascii_line.push(' ');}}}ui.monospace(hex_line.trim_end());- ui.label("│");+ ui.label("│");ui.monospace(ascii_line);});}});if let Some(va) = nav {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}}- /// `Symbol References` provider — a table of every xref pointing- /// at the currently selected symbol (or the cursor VA).+ /// `Symbol References` provider — a table of every xref pointing+ /// at the currently selected symbol (or the cursor VA).fn ui_symbol_references(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("Symbol References");+ ui.heading("Symbol References");ui.small(- egui::RichText::new(- "SymbolTablePlugin · every reference TO the current symbol",- )- .color(muted),+ egui::RichText::new("SymbolTablePlugin · every reference TO the current symbol")+ .color(muted),);ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};let target = self@@ -6743,31 +7122,33 @@ impl GhidrustApp {.or(self.listing_focus_va).or(prog.entry);ui.horizontal(|ui| {- let mut input = target.map(|v| format!("{v:#x}")).unwrap_or_default();- ui.label("Target:");+ let mut input = target.map(|v| format!("{v:#x}")).unwrap_or_default();+ ui.label("Target:");let resp = ui.add(egui::TextEdit::singleline(&mut input).desired_width(140.0)- .hint_text("VA…"),+ .hint_text("VA…"),);if resp.lost_focus() {self.symbol_refs_target = parse_address(&input).ok();}- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut self.symbol_refs_filter).desired_width(200.0)- .hint_text("Substring…"),+ .hint_text("Substring…"),);- if ui.button("Use cursor").clicked() {+ if ui.button("Use cursor").clicked() {self.symbol_refs_target = self.listing_focus_va;}- ui.checkbox(&mut self.symbol_refs_hide_stubs, "Hide resolve stubs")- .on_hover_text("ghidrust_il2cpp::is_resolve_stub_va — hide IL2CPP lazy resolve thunks");+ ui.checkbox(&mut self.symbol_refs_hide_stubs, "Hide resolve stubs")+ .on_hover_text(+ "ghidrust_il2cpp::is_resolve_stub_va — hide IL2CPP lazy resolve thunks",+ );});ui.separator();let Some(target) = target else {- ui.weak("No target — set cursor or type a VA above.");+ ui.weak("No target — set cursor or type a VA above.");return;};let refs = self.xrefs_to_va(target);@@ -6777,8 +7158,8 @@ impl GhidrustApp {ghidrust_il2cpp::classify_at(prog, va).map(|stub| {stub.icall_name.clone()- .map(|n| format!("il2cpp_stub: {n}"))- .unwrap_or_else(|| "il2cpp_stub".into())+ .map(|n| format!("il2cpp_stub: {n}"))+ .unwrap_or_else(|| "il2cpp_stub".into())})};let prog_ref = self.program.as_ref();@@ -6789,7 +7170,7 @@ impl GhidrustApp {return true;}r.preview.to_ascii_lowercase().contains(&q)- || format!("{:#x}", r.from).contains(&q)+ || format!("{:#x}", r.from).contains(&q)|| r.kind.contains(&q)}).filter_map(|r| {@@ -6812,65 +7193,67 @@ impl GhidrustApp {.map(|s| s.to_string()).unwrap_or_default()};- ui.small(format!("{} reference(s) to {target:#x} · {}", rows.len(), label_at(target)));+ ui.small(format!(+ "{} reference(s) to {target:#x} · {}",+ rows.len(),+ label_at(target)+ ));let mut goto: Option<u64> = None;egui::ScrollArea::vertical()- .id_salt("symrefs_scroll")+ .id_salt("symrefs_scroll").max_height(400.0).show(ui, |ui| {- egui::Grid::new("symbol_refs_grid")+ egui::Grid::new("symbol_refs_grid").num_columns(5).striped(true).show(ui, |ui| {- ui.strong("From");- ui.strong("Label");- ui.strong("Kind");- ui.strong("Classify");- ui.strong("Preview");+ ui.strong("From");+ ui.strong("Label");+ ui.strong("Kind");+ ui.strong("Classify");+ ui.strong("Preview");ui.end_row();for (r, cls) in &rows {if ui- .link(egui::RichText::new(format!("{:#x}", r.from)).monospace())+ .link(egui::RichText::new(format!("{:#x}", r.from)).monospace()).clicked(){goto = Some(r.from);}ui.label(label_at(r.from));ui.monospace(r.kind);- ui.small(cls.as_deref().unwrap_or("—"));+ ui.small(cls.as_deref().unwrap_or("—"));ui.label(&r.preview);ui.end_row();}});});if let Some(va) = goto {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}}- /// `EquateTablePlugin` — two-pane: equate groups + per-equate refs.+ /// `EquateTablePlugin` — two-pane: equate groups + per-equate refs.fn ui_equates_table(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("Equates Table");+ ui.heading("Equates Table");ui.small(- egui::RichText::new(- "EquateTablePlugin · symbolic names bound to scalar operands",- )- .color(muted),+ egui::RichText::new("EquateTablePlugin · symbolic names bound to scalar operands")+ .color(muted),);ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};let groups = prog.edits.equate_groups();ui.horizontal(|ui| {- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut self.equates_filter).desired_width(220.0)- .hint_text("Name / value…"),+ .hint_text("Name / value…"),);- if ui.button("Add equate at cursor…").clicked() {+ if ui.button("Add equate at cursor…").clicked() {self.equate_dialog_va = self.listing_focus_va;self.equate_dialog_op = 1;self.equate_dialog_name.clear();@@ -6886,29 +7269,29 @@ impl GhidrustApp {if q.is_empty() {return true;}- name.to_ascii_lowercase().contains(&q) || format!("{val:#x}").contains(&q)+ name.to_ascii_lowercase().contains(&q) || format!("{val:#x}").contains(&q)}).collect();if filtered.is_empty() {- ui.weak("No equates — use \"Add equate at cursor\" over a scalar operand.");+ ui.weak("No equates — use \"Add equate at cursor\" over a scalar operand.");return;}let mut clear: Option<(u64, u8)> = None;let mut goto: Option<u64> = None;ui.columns(2, |cols| {- cols[0].strong("Equate");+ cols[0].strong("Equate");cols[0].separator();egui::ScrollArea::vertical()- .id_salt("equates_left_scroll")+ .id_salt("equates_left_scroll").max_height(360.0).show(&mut cols[0], |ui| {- egui::Grid::new("equates_groups_grid")+ egui::Grid::new("equates_groups_grid").num_columns(3).striped(true).show(ui, |ui| {- ui.strong("Name");- ui.strong("Value");- ui.strong("# Refs");+ ui.strong("Name");+ ui.strong("Value");+ ui.strong("# Refs");ui.end_row();for (name, value, n) in &filtered {let is_sel = self@@ -6924,13 +7307,13 @@ impl GhidrustApp {if ui.selectable_label(is_sel, text).clicked() {self.equates_selected = Some((name.clone(), *value));}- ui.monospace(format!("{value:#x}"));- ui.monospace(format!("{n}"));+ ui.monospace(format!("{value:#x}"));+ ui.monospace(format!("{n}"));ui.end_row();}});});- cols[1].strong("References");+ cols[1].strong("References");cols[1].separator();let sel = self.equates_selected.clone();let refs: Vec<(u64, u8, i64)> = match sel {@@ -6938,31 +7321,31 @@ impl GhidrustApp {None => Vec::new(),};egui::ScrollArea::vertical()- .id_salt("equates_right_scroll")+ .id_salt("equates_right_scroll").max_height(360.0).show(&mut cols[1], |ui| {if refs.is_empty() {- ui.weak("Select an equate on the left to see its references.");+ ui.weak("Select an equate on the left to see its references.");} else {- egui::Grid::new("equate_refs_grid")+ egui::Grid::new("equate_refs_grid").num_columns(4).striped(true).show(ui, |ui| {- ui.strong("Ref Addr");- ui.strong("Op");- ui.strong("Value");- ui.strong("Del");+ ui.strong("Ref Addr");+ ui.strong("Op");+ ui.strong("Value");+ ui.strong("Del");ui.end_row();for (va, op, value) in refs {if ui- .link(egui::RichText::new(format!("{va:#x}")).monospace())+ .link(egui::RichText::new(format!("{va:#x}")).monospace()).clicked(){goto = Some(va);}- ui.monospace(format!("{op}"));- ui.monospace(format!("{value:#x}"));- if ui.small_button("Del").clicked() {+ ui.monospace(format!("{op}"));+ ui.monospace(format!("{value:#x}"));+ if ui.small_button("Del").clicked() {clear = Some((va, op));}ui.end_row();@@ -6972,26 +7355,24 @@ impl GhidrustApp {});});if let Some(va) = goto {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}if let Some((va, op)) = clear {- let _ = self.set_equate(va, op, "", 0);+ let _ = self.set_equate(va, op, "", 0);}}- /// `FunctionTagPlugin` — two-pane: assigned tags for current fn,- /// All Tags with counts.+ /// `FunctionTagPlugin` — two-pane: assigned tags for current fn,+ /// All Tags with counts.fn ui_function_tags(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("Function Tags");+ ui.heading("Function Tags");ui.small(- egui::RichText::new(- "FunctionTagPlugin · per-function labels + universe of tags",- )- .color(muted),+ egui::RichText::new("FunctionTagPlugin · per-function labels + universe of tags")+ .color(muted),);ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};let entry = self.focused_function_entry.or_else(|| {@@ -7000,16 +7381,16 @@ impl GhidrustApp {});let entry_label = entry.and_then(|va| self.program.as_ref()?.display_function_name_at(va))- .unwrap_or_else(|| "<no function>".into());+ .unwrap_or_else(|| "<no function>".into());ui.horizontal(|ui| {- ui.label("Function:");+ ui.label("Function:");ui.monospace(&entry_label);if let Some(e) = entry {- ui.monospace(format!("@ {e:#x}"));+ ui.monospace(format!("@ {e:#x}"));}});ui.separator();- // Left = assigned tags (with remove); right = all tags (add / delete).+ // Left = assigned tags (with remove); right = all tags (add / delete).let assigned: Vec<String> = entry.map(|e| prog.edits.function_tags_for(e)).unwrap_or_default();@@ -7018,31 +7399,31 @@ impl GhidrustApp {let mut add_to_entry: Option<String> = None;let mut delete_globally: Option<String> = None;ui.columns(2, |cols| {- cols[0].strong("Assigned to this function");+ cols[0].strong("Assigned to this function");cols[0].separator();if assigned.is_empty() {- cols[0].weak("No tags — add one from the right pane, or type a new tag.");+ cols[0].weak("No tags — add one from the right pane, or type a new tag.");} else {for t in &assigned {cols[0].horizontal(|ui| {ui.monospace(t);- if ui.small_button("Remove").clicked() {+ if ui.small_button("Remove").clicked() {remove_from_entry = Some(t.clone());}});}}- cols[1].strong("All Tags");+ cols[1].strong("All Tags");cols[1].separator();cols[1].horizontal(|ui| {- ui.label("New:");+ ui.label("New:");ui.add(egui::TextEdit::singleline(&mut self.function_tags_new_input).desired_width(160.0)- .hint_text("Tag name…"),+ .hint_text("Tag name…"),);- if ui.button("Add").clicked() {+ if ui.button("Add").clicked() {let name = self.function_tags_new_input.trim().to_string();if !name.is_empty() {if entry.is_some() {@@ -7055,38 +7436,38 @@ impl GhidrustApp {}});cols[1].horizontal(|ui| {- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut self.function_tags_filter).desired_width(180.0)- .hint_text("Substring…"),+ .hint_text("Substring…"),);});cols[1].separator();let q = self.function_tags_filter.to_ascii_lowercase();egui::ScrollArea::vertical()- .id_salt("all_tags_scroll")+ .id_salt("all_tags_scroll").max_height(320.0).show(&mut cols[1], |ui| {- egui::Grid::new("all_tags_grid")+ egui::Grid::new("all_tags_grid").num_columns(3).striped(true).show(ui, |ui| {- ui.strong("Tag");- ui.strong("Uses");- ui.strong("Actions");+ ui.strong("Tag");+ ui.strong("Uses");+ ui.strong("Actions");ui.end_row();for (tag, n) in &all_tags {if !q.is_empty() && !tag.to_ascii_lowercase().contains(&q) {continue;}ui.monospace(tag);- ui.monospace(format!("{n}"));+ ui.monospace(format!("{n}"));ui.horizontal(|ui| {- if entry.is_some() && ui.small_button("Add").clicked() {+ if entry.is_some() && ui.small_button("Add").clicked() {add_to_entry = Some(tag.clone());}- if ui.small_button("Delete").clicked() {+ if ui.small_button("Delete").clicked() {delete_globally = Some(tag.clone());}});@@ -7106,29 +7487,27 @@ impl GhidrustApp {}}- /// `ReferencesPlugin` — External Programs table. Rendered from- /// analyzer-driven `imports_exports` output (PDB symbols, `idata`- /// sections, demangled `dllexport` symbols) — never fabricated.+ /// `ReferencesPlugin` — External Programs table. Rendered from+ /// analyzer-driven `imports_exports` output (PDB symbols, `idata`+ /// sections, demangled `dllexport` symbols) — never fabricated.fn ui_external_programs(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("External Programs");+ ui.heading("External Programs");ui.small(- egui::RichText::new(- "ReferencesPlugin · analyzer-derived imports + exports",- )- .color(muted),+ egui::RichText::new("ReferencesPlugin · analyzer-derived imports + exports")+ .color(muted),);ui.separator();if self.program.is_none() {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;}let (imports, exports) = self.imports_exports();ui.horizontal(|ui| {- ui.label("Filter:");+ ui.label("Filter:");ui.add(egui::TextEdit::singleline(&mut self.external_programs_filter).desired_width(220.0)- .hint_text("Name / VA…"),+ .hint_text("Name / VA…"),);});ui.separator();@@ -7137,101 +7516,104 @@ impl GhidrustApp {if q.is_empty() {return true;}- name.to_ascii_lowercase().contains(&q) || format!("{va:#x}").contains(&q)+ name.to_ascii_lowercase().contains(&q) || format!("{va:#x}").contains(&q)};let mut goto: Option<u64> = None;egui::ScrollArea::vertical()- .id_salt("ext_progs_scroll")+ .id_salt("ext_progs_scroll").max_height(400.0).show(ui, |ui| {- ui.strong("Imports");- egui::Grid::new("ext_imports_grid")+ ui.strong("Imports");+ egui::Grid::new("ext_imports_grid").num_columns(3).striped(true).show(ui, |ui| {- ui.strong("Address");- ui.strong("Name");- ui.strong("Source");+ ui.strong("Address");+ ui.strong("Name");+ ui.strong("Source");ui.end_row();for (va, name) in imports.iter().filter(|(va, n)| matches(n, *va)) {if ui- .link(egui::RichText::new(format!("{va:#x}")).monospace())+ .link(egui::RichText::new(format!("{va:#x}")).monospace()).clicked(){goto = Some(*va);}ui.label(name);- ui.monospace(if name.starts_with('.') { "section" } else { "pdb" });+ ui.monospace(if name.starts_with('.') {+ "section"+ } else {+ "pdb"+ });ui.end_row();}});ui.add_space(8.0);- ui.strong("Exports");- egui::Grid::new("ext_exports_grid")+ ui.strong("Exports");+ egui::Grid::new("ext_exports_grid").num_columns(3).striped(true).show(ui, |ui| {- ui.strong("Address");- ui.strong("Name");- ui.strong("Source");+ ui.strong("Address");+ ui.strong("Name");+ ui.strong("Source");ui.end_row();for (va, name) in exports.iter().filter(|(va, n)| matches(n, *va)) {if ui- .link(egui::RichText::new(format!("{va:#x}")).monospace())+ .link(egui::RichText::new(format!("{va:#x}")).monospace()).clicked(){goto = Some(*va);}ui.label(name);- ui.monospace(if name.starts_with('.') { "section" } else { "demangle" });+ ui.monospace(if name.starts_with('.') {+ "section"+ } else {+ "demangle"+ });ui.end_row();}if imports.is_empty() && exports.is_empty() {- ui.weak("No imports/exports — analyzer did not populate any.");+ ui.weak("No imports/exports — analyzer did not populate any.");ui.end_row();}});});if let Some(va) = goto {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}}- /// `DataTypePreviewPlugin` — preview interpretation of bytes at- /// the current cursor under the chosen built-in type.+ /// `DataTypePreviewPlugin` — preview interpretation of bytes at+ /// the current cursor under the chosen built-in type.fn ui_data_type_preview(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("Data Type Preview");+ ui.heading("Data Type Preview");ui.small(- egui::RichText::new(- "DataTypePreviewPlugin · byte interpretation @ cursor",- )- .color(muted),+ egui::RichText::new("DataTypePreviewPlugin · byte interpretation @ cursor")+ .color(muted),);ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};let va = match self.listing_focus_va.or(prog.entry) {Some(v) => v,None => {- ui.weak("No cursor / entry.");+ ui.weak("No cursor / entry.");return;}};ui.horizontal(|ui| {- ui.label("Cursor VA:");- ui.monospace(format!("{va:#x}"));- ui.label("Type:");+ ui.label("Cursor VA:");+ ui.monospace(format!("{va:#x}"));+ ui.label("Type:");let sel = self.data_type_preview_selected.clone();- egui::ComboBox::from_id_salt("dtp_type_combo")+ egui::ComboBox::from_id_salt("dtp_type_combo").selected_text(&sel).show_ui(ui, |ui| {for name in BUILTIN_TYPES {- if ui- .selectable_label(sel.as_str() == *name, *name)- .clicked()- {+ if ui.selectable_label(sel.as_str() == *name, *name).clicked() {self.data_type_preview_selected = (*name).into();}}@@ -7239,30 +7621,31 @@ impl GhidrustApp {});ui.separator();let bytes = prog.read_va(va, 16).unwrap_or_default();- let hex: String = bytes.iter().map(|b| format!("{b:02x} ")).collect();- ui.monospace(format!("bytes: {}", hex.trim_end()));+ let hex: String = bytes.iter().map(|b| format!("{b:02x} ")).collect();+ ui.monospace(format!("bytes: {}", hex.trim_end()));ui.separator();- egui::Grid::new("dtp_grid").num_columns(2).striped(true).show(ui, |ui| {- ui.strong("Interpretation");- ui.strong("Preview");- ui.end_row();- for (name, preview) in preview_all(&bytes) {- ui.monospace(name);- ui.monospace(preview);+ egui::Grid::new("dtp_grid")+ .num_columns(2)+ .striped(true)+ .show(ui, |ui| {+ ui.strong("Interpretation");+ ui.strong("Preview");ui.end_row();- }- });+ for (name, preview) in preview_all(&bytes) {+ ui.monospace(name);+ ui.monospace(preview);+ ui.end_row();+ }+ });}- /// `ComputeChecksumsPlugin` — CRC-32 / Adler-32 / Fletcher / raw- /// sum panels over the loaded image or a chosen block.+ /// `ComputeChecksumsPlugin` — CRC-32 / Adler-32 / Fletcher / raw+ /// sum panels over the loaded image or a chosen block.fn ui_checksum_generator(&mut self, ui: &mut egui::Ui, muted: Color32) {- ui.heading("Checksum Generator");+ ui.heading("Checksum Generator");ui.small(- egui::RichText::new(- "ComputeChecksumsPlugin · CRC-32 / Adler-32 / Fletcher / sums",- )- .color(muted),+ egui::RichText::new("ComputeChecksumsPlugin · CRC-32 / Adler-32 / Fletcher / sums")+ .color(muted),);ui.separator();let block_names: Vec<String> = self@@ -7272,10 +7655,10 @@ impl GhidrustApp {.unwrap_or_default();let mut run: Option<ChecksumMode> = None;ui.horizontal(|ui| {- if ui.button("Whole image").clicked() {+ if ui.button("Whole image").clicked() {run = Some(ChecksumMode::WholeImage);}- ui.label(egui::RichText::new("or block:").color(muted));+ ui.label(egui::RichText::new("or block:").color(muted));for name in &block_names {if ui.small_button(name).clicked() {run = Some(ChecksumMode::Section(name.clone()));@@ -7288,38 +7671,41 @@ impl GhidrustApp {ui.separator();match &self.checksum_last {None => {- ui.weak("No checksum computed yet — click Whole image or a block above.");+ ui.weak("No checksum computed yet — click Whole image or a block above.");}Some(r) => {- egui::Grid::new("checksum_grid").num_columns(2).striped(true).show(ui, |ui| {- ui.strong("Target");- ui.label(&r.target);- ui.end_row();- ui.strong("Length");- ui.monospace(format!("{}", r.len));- ui.end_row();- ui.strong("CRC-32 (IEEE)");- ui.monospace(format!("{:#010x}", r.crc32));- ui.end_row();- ui.strong("Adler-32");- ui.monospace(format!("{:#010x}", r.adler32));- ui.end_row();- ui.strong("Sum-8");- ui.monospace(format!("{:#x}", r.sum8));- ui.end_row();- ui.strong("Sum-16");- ui.monospace(format!("{:#x}", r.sum16));- ui.end_row();- ui.strong("Sum-32");- ui.monospace(format!("{:#x}", r.sum32));- ui.end_row();- ui.strong("Fletcher-16");- ui.monospace(format!("{:#010x}", r.fletcher16));- ui.end_row();- ui.strong("Fletcher-32");- ui.monospace(format!("{:#018x}", r.fletcher32));- ui.end_row();- });+ egui::Grid::new("checksum_grid")+ .num_columns(2)+ .striped(true)+ .show(ui, |ui| {+ ui.strong("Target");+ ui.label(&r.target);+ ui.end_row();+ ui.strong("Length");+ ui.monospace(format!("{}", r.len));+ ui.end_row();+ ui.strong("CRC-32 (IEEE)");+ ui.monospace(format!("{:#010x}", r.crc32));+ ui.end_row();+ ui.strong("Adler-32");+ ui.monospace(format!("{:#010x}", r.adler32));+ ui.end_row();+ ui.strong("Sum-8");+ ui.monospace(format!("{:#x}", r.sum8));+ ui.end_row();+ ui.strong("Sum-16");+ ui.monospace(format!("{:#x}", r.sum16));+ ui.end_row();+ ui.strong("Sum-32");+ ui.monospace(format!("{:#x}", r.sum32));+ ui.end_row();+ ui.strong("Fletcher-16");+ ui.monospace(format!("{:#010x}", r.fletcher16));+ ui.end_row();+ ui.strong("Fletcher-32");+ ui.monospace(format!("{:#018x}", r.fletcher32));+ ui.end_row();+ });}}}@@ -7329,35 +7715,41 @@ impl GhidrustApp {fn preview_all(bytes: &[u8]) -> Vec<(&'static str, String)> {let mut out = Vec::new();if let Some(&b) = bytes.first() {- out.push(("int8", format!("{}", b as i8)));- out.push(("uint8", format!("{}", b)));+ out.push(("int8", format!("{}", b as i8)));+ out.push(("uint8", format!("{}", b)));}if bytes.len() >= 2 {let w = u16::from_le_bytes([bytes[0], bytes[1]]);- out.push(("int16", format!("{}", w as i16)));- out.push(("uint16", format!("{w} ({w:#x})")));+ out.push(("int16", format!("{}", w as i16)));+ out.push(("uint16", format!("{w} ({w:#x})")));}if bytes.len() >= 4 {let d = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);- out.push(("int32", format!("{}", d as i32)));- out.push(("uint32", format!("{d} ({d:#x})")));- out.push(("float", format!("{}", f32::from_bits(d))));+ out.push(("int32", format!("{}", d as i32)));+ out.push(("uint32", format!("{d} ({d:#x})")));+ out.push(("float", format!("{}", f32::from_bits(d))));}if bytes.len() >= 8 {let q = u64::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],]);- out.push(("int64", format!("{}", q as i64)));- out.push(("uint64", format!("{q} ({q:#x})")));- out.push(("double", format!("{}", f64::from_bits(q))));- out.push(("pointer64", format!("{q:#018x}")));+ out.push(("int64", format!("{}", q as i64)));+ out.push(("uint64", format!("{q} ({q:#x})")));+ out.push(("double", format!("{}", f64::from_bits(q))));+ out.push(("pointer64", format!("{q:#018x}")));}let ascii: String = bytes.iter().take(16)- .map(|b| if (0x20..=0x7f).contains(b) { *b as char } else { '.' })+ .map(|b| {+ if (0x20..=0x7f).contains(b) {+ *b as char+ } else {+ '.'+ }+ }).collect();- out.push(("ascii", ascii));+ out.push(("ascii", ascii));out}@@ -7365,19 +7757,19 @@ impl eframe::App for GhidrustApp {fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {self.apply_theme(ctx);- // drain event bus once per frame and fan out.+ // drain event bus once per frame and fan out.self.drain_events();- // Startup: choose project before the empty shell+ // Startup: choose project before the empty shellif self.show_startup_picker {self.ui_startup_picker(ctx);return;}- // Poll background analysis worker; keep repainting so progress UI stays live.+ // Poll background analysis worker; keep repainting so progress UI stays live.if self.analysis_job.is_some() {if let Err(e) = self.step_analysis_job() {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());self.analysis_job = None;set_preferred_bulk_mode(BulkScanMode::ParallelCpu);@@ -7385,135 +7777,184 @@ impl eframe::App for GhidrustApp {ctx.request_repaint();}- egui::TopBottomPanel::top("menubar").show(ctx, |ui| {+ egui::TopBottomPanel::top("menubar").show(ctx, |ui| {egui::menu::bar(ui, |ui| {- ui.menu_button("File", |ui| {- if ui.button("New Project…").clicked() {+ ui.menu_button("File", |ui| {+ if ui.button("New Project…").clicked() {self.browse_and_create_project();ui.close_menu();}- if ui.button("Open Project…").clicked() {+ if ui.button("Open Project…").clicked() {self.browse_and_open_project();ui.close_menu();}ui.separator();- if ui.button("Import binary into project…").clicked() {+ if ui.button("Import binary into project…").clicked() {self.browse_and_import();ui.close_menu();}- if ui.button("Open / Load binary…").clicked() {+ if ui.button("Open / Load binary…").clicked() {self.browse_and_load_binary();ui.close_menu();}- if ui.button("Add To Program…").on_hover_text("Not yet implemented").clicked() {- self.nyi("File → Add To Program");+ if ui+ .button("Add To Program…")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("File → Add To Program");ui.close_menu();}- if ui.button("Batch Import…").on_hover_text("Not yet implemented").clicked() {- self.nyi("File → Batch Import");+ if ui+ .button("Batch Import…")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("File → Batch Import");ui.close_menu();}ui.separator();- if ui.button("Save analysis results…").clicked() {+ if ui.button("Save analysis results…").clicked() {if let Err(e) = self.save_results() {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}ui.close_menu();}- if ui.button("Save As…").on_hover_text("Not yet implemented").clicked() {- self.nyi("File → Save As");+ if ui+ .button("Save As…")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("File → Save As");ui.close_menu();}- if ui.button("Export Program…").on_hover_text("Not yet implemented").clicked() {- self.nyi("File → Export Program");+ if ui+ .button("Export Program…")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("File → Export Program");ui.close_menu();}ui.separator();- if ui.button("Load PDB File…").on_hover_text("Not yet implemented — PDB load UI").clicked() {- self.nyi("File → Load PDB File");+ if ui+ .button("Load PDB File…")+ .on_hover_text("Not yet implemented — PDB load UI")+ .clicked()+ {+ self.nyi("File → Load PDB File");ui.close_menu();}- if ui.button("Parse C Source…").on_hover_text("Not yet implemented").clicked() {- self.nyi("File → Parse C Source");+ if ui+ .button("Parse C Source…")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("File → Parse C Source");ui.close_menu();}ui.separator();- if ui.button("Configure…").on_hover_text("Plugin picker — not yet implemented").clicked() {- self.nyi("File → Configure");+ if ui+ .button("Configure…")+ .on_hover_text("Plugin picker — not yet implemented")+ .clicked()+ {+ self.nyi("File → Configure");ui.close_menu();}- if ui.button("Print…").on_hover_text("Not yet implemented").clicked() {- self.nyi("File → Print");+ if ui+ .button("Print…")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("File → Print");ui.close_menu();}ui.separator();- if ui.button("Close program").clicked() {+ if ui.button("Close program").clicked() {self.program = None;self.listing.clear();self.active_file_id = None;- self.status = "Program closed".into();+ self.status = "Program closed".into();ui.close_menu();}- if ui.button("Exit").clicked() {+ if ui.button("Exit").clicked() {ctx.send_viewport_cmd(egui::ViewportCommand::Close);}});- ui.menu_button("Edit", |ui| {- if ui.button("Undo").clicked() {+ ui.menu_button("Edit", |ui| {+ if ui.button("Undo").clicked() {self.edit_undo();ui.close_menu();}- if ui.button("Redo").clicked() {+ if ui.button("Redo").clicked() {self.edit_redo();ui.close_menu();}- if ui.button("Clear selection").clicked() {+ if ui.button("Clear selection").clicked() {self.edit_clear_selection();ui.close_menu();}ui.separator();- if ui.button("Tool Options…").on_hover_text("Options tree — not yet implemented").clicked() {- self.nyi("Edit → Tool Options");+ if ui+ .button("Tool Options…")+ .on_hover_text("Options tree — not yet implemented")+ .clicked()+ {+ self.nyi("Edit → Tool Options");ui.close_menu();}- if ui.button("Options for program…").on_hover_text("Program-level options — not yet implemented").clicked() {- self.nyi("Edit → Options for program");+ if ui+ .button("Options for program…")+ .on_hover_text("Program-level options — not yet implemented")+ .clicked()+ {+ self.nyi("Edit → Options for program");ui.close_menu();}- if ui.button("Plugin Path…").on_hover_text("Configure plugin paths — not yet implemented").clicked() {- self.nyi("Edit → Plugin Path");+ if ui+ .button("Plugin Path…")+ .on_hover_text("Configure plugin paths — not yet implemented")+ .clicked()+ {+ self.nyi("Edit → Plugin Path");ui.close_menu();}- if ui.button("Key Bindings…").on_hover_text("Rebind actions — not yet implemented").clicked() {- self.nyi("Edit → Key Bindings");+ if ui+ .button("Key Bindings…")+ .on_hover_text("Rebind actions — not yet implemented")+ .clicked()+ {+ self.nyi("Edit → Key Bindings");ui.close_menu();}});- ui.menu_button("Analysis", |ui| {- if ui.button("Auto Analyze…").clicked() {+ ui.menu_button("Analysis", |ui| {+ if ui.button("Auto Analyze…").clicked() {self.pending_analyze_file_id = None;self.show_analysis_dialog = true;ui.close_menu();}- if ui.button("Run selected analyzers").clicked() {+ if ui.button("Run selected analyzers").clicked() {self.pending_analyze_file_id = None;self.show_analysis_dialog = true;ui.close_menu();}- if ui.button("Analyze All Open…").on_hover_text("Multi-program batch — not yet implemented").clicked() {- self.nyi("Analysis → Analyze All Open");+ if ui+ .button("Analyze All Open…")+ .on_hover_text("Multi-program batch — not yet implemented")+ .clicked()+ {+ self.nyi("Analysis → Analyze All Open");ui.close_menu();}ui.separator();- ui.menu_button("One Shot Analysis", |ui| {- // Enumerate analyzers as sub-menu items (mirrors One-Shot).- // Clicking pre-selects that analyzer and opens the dialog.- let analyzer_names: Vec<String> = self- .analyzer_infos- .iter()- .map(|a| a.name.clone())- .collect();+ ui.menu_button("One Shot Analysis", |ui| {+ // Enumerate analyzers as sub-menu items (mirrors One-Shot).+ // Clicking pre-selects that analyzer and opens the dialog.+ let analyzer_names: Vec<String> =+ self.analyzer_infos.iter().map(|a| a.name.clone()).collect();let mut chosen: Option<String> = None;for name in &analyzer_names {if ui.button(name).clicked() {@@ -7526,7 +7967,7 @@ impl eframe::App for GhidrustApp {}self.pending_analyze_file_id = None;self.show_analysis_dialog = true;- self.status = format!("One Shot: {name}");+ self.status = format!("One Shot: {name}");self.log(self.status.clone());ui.close_menu();}@@ -7553,78 +7994,131 @@ impl eframe::App for GhidrustApp {ui.close_menu();}});- ui.menu_button("Navigation", |ui| {- if ui.add_enabled(self.can_nav_back(), egui::Button::new("Back")).clicked() {+ ui.menu_button("Navigation", |ui| {+ if ui+ .add_enabled(self.can_nav_back(), egui::Button::new("Back"))+ .clicked()+ {self.nav_back();ui.close_menu();}- if ui.add_enabled(self.can_nav_forward(), egui::Button::new("Forward")).clicked() {+ if ui+ .add_enabled(self.can_nav_forward(), egui::Button::new("Forward"))+ .clicked()+ {self.nav_forward();ui.close_menu();}ui.separator();- if ui.button("Go to entry").clicked() {+ if ui.button("Go to entry").clicked() {self.goto_entry();ui.close_menu();}- if ui.button("Go to address…").clicked() {+ if ui.button("Go to address…").clicked() {if let Some(prog) = &self.program {if let Some(e) = prog.entry {- self.goto_input = format!("{e:#x}");+ self.goto_input = format!("{e:#x}");} else {- self.goto_input = format!("{:#x}", prog.image_base);+ self.goto_input = format!("{:#x}", prog.image_base);}}self.show_goto_dialog = true;ui.close_menu();}ui.separator();- if ui.button("Next Function (Ctrl+Down)").clicked() {+ if ui.button("Next Function (Ctrl+Down)").clicked() {self.nav_next_function();ui.close_menu();}- if ui.button("Previous Function (Ctrl+Up)").clicked() {+ if ui.button("Previous Function (Ctrl+Up)").clicked() {self.nav_prev_function();ui.close_menu();}- if ui.button("Next Data").on_hover_text("Not yet implemented").clicked() {- self.nyi("Navigation → Next Data");+ if ui+ .button("Next Data")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Navigation → Next Data");ui.close_menu();}- if ui.button("Next Undefined").on_hover_text("Not yet implemented").clicked() {- self.nyi("Navigation → Next Undefined");+ if ui+ .button("Next Undefined")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Navigation → Next Undefined");ui.close_menu();}- if ui.button("Next Bookmark").clicked() {+ if ui.button("Next Bookmark").clicked() {self.nav_next_bookmark();ui.close_menu();}- if ui.button("Previous Bookmark").clicked() {+ if ui.button("Previous Bookmark").clicked() {self.nav_prev_bookmark();ui.close_menu();}});- ui.menu_button("Search", |ui| {- if ui.button("Search memory…").clicked() {+ ui.menu_button("Search", |ui| {+ if ui.button("Search memory…").clicked() {self.show_search_memory_dialog = true;ui.close_menu();}- if ui.button("Search program text…").clicked() {+ if ui.button("Search program text…").clicked() {self.show_search_text_dialog = true;ui.close_menu();}ui.separator();- if ui.button("For Strings…").on_hover_text("Opens Defined Strings — session strings").clicked() {+ if ui+ .button("For Strings…")+ .on_hover_text("Opens Defined Strings — session strings")+ .clicked()+ {self.pane_open.insert(PaneKind::DefinedStrings, true);ui.close_menu();}- if ui.button("For Scalars…").on_hover_text("ScalarSearchPlugin · operand scalar range filter").clicked() {+ if ui.button("For Crypto Constants…").clicked() {+ self.decrypt_pane.focus(DecryptTab::Constants);+ self.pane_open.insert(PaneKind::Decrypt, true);+ ui.close_menu();+ }+ if ui.button("For Recovered Strings…").clicked() {+ self.decrypt_pane.focus(DecryptTab::Strings);+ self.pane_open.insert(PaneKind::Decrypt, true);+ ui.close_menu();+ }+ if ui.button("For Crypto Capabilities…").clicked() {+ self.decrypt_pane.focus(DecryptTab::Capabilities);+ self.pane_open.insert(PaneKind::Decrypt, true);+ ui.close_menu();+ }+ if ui+ .button("Decrypt…")+ .on_hover_text("Open Decrypt pane on listing selection")+ .clicked()+ {+ if let Some(va) = self.listing_focus_va {+ self.open_decrypt_at(va, None);+ } else {+ self.pane_open.insert(PaneKind::Decrypt, true);+ }+ ui.close_menu();+ }+ if ui+ .button("For Scalars…")+ .on_hover_text("ScalarSearchPlugin · operand scalar range filter")+ .clicked()+ {self.show_search_scalars_dialog = true;ui.close_menu();}- if ui.button("For Address Tables…").on_hover_text("AutoTableDisassemblerPlugin · pointer table candidates").clicked() {+ if ui+ .button("For Address Tables…")+ .on_hover_text("AutoTableDisassemblerPlugin · pointer table candidates")+ .clicked()+ {self.show_search_address_tables_dialog = true;- // Populate immediately from analyzer output.+ // Populate immediately from analyzer output.if let Some(prog) = self.program.as_ref() {self.text_hits = address_table_hits(prog);self.memory_hits.clear();@@ -7632,186 +8126,287 @@ impl eframe::App for GhidrustApp {}ui.close_menu();}- if ui.button("Instruction Patterns…").on_hover_text("BytePatternPlugin · mnemonic + operand filter").clicked() {+ if ui+ .button("Instruction Patterns…")+ .on_hover_text("BytePatternPlugin · mnemonic + operand filter")+ .clicked()+ {self.show_search_insn_dialog = true;ui.close_menu();}- if ui.button("For Direct References…").on_hover_text("Not yet implemented").clicked() {- self.nyi("Search → For Direct References");+ if ui+ .button("For Direct References…")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Search → For Direct References");ui.close_menu();}- if ui.button("For Matching Instructions…").on_hover_text("Not yet implemented").clicked() {- self.nyi("Search → For Matching Instructions");+ if ui+ .button("For Matching Instructions…")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Search → For Matching Instructions");ui.close_menu();}- if ui.button("Repeat Search").on_hover_text("Not yet implemented").clicked() {- self.nyi("Search → Repeat Search");+ if ui+ .button("Repeat Search")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Search → Repeat Search");ui.close_menu();}});- ui.menu_button("Select", |ui| {- if ui.button("All").clicked() {+ ui.menu_button("Select", |ui| {+ if ui.button("All").clicked() {self.select_all_listing();ui.close_menu();}- if ui.button("All in View").on_hover_text("Not yet implemented").clicked() {- self.nyi("Select → All in View");+ if ui+ .button("All in View")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Select → All in View");ui.close_menu();}- if ui.button("Clear").clicked() {+ if ui.button("Clear").clicked() {self.edit_clear_selection();ui.close_menu();}- if ui.button("Complement").on_hover_text("Not yet implemented").clicked() {- self.nyi("Select → Complement");+ if ui+ .button("Complement")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Select → Complement");ui.close_menu();}ui.separator();- if ui.button("Bytes").on_hover_text("Not yet implemented").clicked() {- self.nyi("Select → Bytes");+ if ui+ .button("Bytes")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Select → Bytes");ui.close_menu();}- if ui.button("Instructions").on_hover_text("Not yet implemented").clicked() {- self.nyi("Select → Instructions");+ if ui+ .button("Instructions")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Select → Instructions");ui.close_menu();}- if ui.button("Data").on_hover_text("Not yet implemented").clicked() {- self.nyi("Select → Data");+ if ui+ .button("Data")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Select → Data");ui.close_menu();}- if ui.button("Undefined").on_hover_text("Not yet implemented").clicked() {- self.nyi("Select → Undefined");+ if ui+ .button("Undefined")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Select → Undefined");ui.close_menu();}- if ui.button("Function").on_hover_text("Not yet implemented").clicked() {- self.nyi("Select → Function");+ if ui+ .button("Function")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Select → Function");ui.close_menu();}- if ui.button("Subroutine").on_hover_text("Not yet implemented").clicked() {- self.nyi("Select → Subroutine");+ if ui+ .button("Subroutine")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Select → Subroutine");ui.close_menu();}- if ui.button("Forward Refs").on_hover_text("Not yet implemented").clicked() {- self.nyi("Select → Forward Refs");+ if ui+ .button("Forward Refs")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Select → Forward Refs");ui.close_menu();}- if ui.button("Backward Refs").on_hover_text("Not yet implemented").clicked() {- self.nyi("Select → Backward Refs");+ if ui+ .button("Backward Refs")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Select → Backward Refs");ui.close_menu();}ui.separator();- if ui.button("Create Table From Selection").on_hover_text("Not yet implemented").clicked() {- self.nyi("Select → Create Table From Selection");+ if ui+ .button("Create Table From Selection")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Select → Create Table From Selection");ui.close_menu();}});- ui.menu_button("Tools", |ui| {- if ui.button("Processor options…").clicked() {+ ui.menu_button("Tools", |ui| {+ if ui.button("Processor options…").clicked() {self.show_processor_dialog = true;ui.close_menu();}- if ui.button("Compare Program…").on_hover_text("Not yet implemented").clicked() {- self.nyi("Tools → Compare Program");+ if ui+ .button("Compare Program…")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Tools → Compare Program");ui.close_menu();}- if ui.button("Program Differences…").on_hover_text("Not yet implemented").clicked() {- self.nyi("Tools → Program Differences");+ if ui+ .button("Program Differences…")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Tools → Program Differences");ui.close_menu();}- if ui.button("Generate Checksum…").on_hover_text("Opens Checksum Generator").clicked() {+ if ui+ .button("Generate Checksum…")+ .on_hover_text("Opens Checksum Generator")+ .clicked()+ {self.pane_open.insert(PaneKind::ChecksumGenerator, true);ui.close_menu();}- if ui.button("Function Bit Patterns Explorer").on_hover_text("Not yet implemented").clicked() {- self.nyi("Tools → Function Bit Patterns Explorer");+ if ui+ .button("Function Bit Patterns Explorer")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Tools → Function Bit Patterns Explorer");ui.close_menu();}- if ui.button("Instruction Table").on_hover_text("Not yet implemented").clicked() {- self.nyi("Tools → Instruction Table");+ if ui+ .button("Instruction Table")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Tools → Instruction Table");ui.close_menu();}- if ui.button("Processor Manual…").on_hover_text("Not yet implemented").clicked() {- self.nyi("Tools → Processor Manual");+ if ui+ .button("Processor Manual…")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Tools → Processor Manual");ui.close_menu();}});- ui.menu_button("Graph", |ui| {- if ui.button("Function Graph").clicked() {+ ui.menu_button("Graph", |ui| {+ if ui.button("Function Graph").clicked() {self.pane_open.insert(PaneKind::FunctionGraph, true);ui.close_menu();}- if ui.button("Function Call Graph").clicked() {+ if ui.button("Function Call Graph").clicked() {self.pane_open.insert(PaneKind::FunctionCallGraph, true);ui.close_menu();}- if ui.button("Function Call Trees").clicked() {+ if ui.button("Function Call Trees").clicked() {self.pane_open.insert(PaneKind::FunctionCallTrees, true);ui.close_menu();}ui.separator();- if ui.button("Block Flow").on_hover_text("Not yet implemented").clicked() {- self.nyi("Graph → Block Flow");+ if ui+ .button("Block Flow")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Graph → Block Flow");ui.close_menu();}- if ui.button("Code Flow").on_hover_text("Not yet implemented").clicked() {- self.nyi("Graph → Code Flow");+ if ui+ .button("Code Flow")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Graph → Code Flow");ui.close_menu();}- if ui.button("Calls").on_hover_text("Not yet implemented").clicked() {- self.nyi("Graph → Calls");+ if ui+ .button("Calls")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Graph → Calls");ui.close_menu();}- if ui.button("Data Flow").on_hover_text("Not yet implemented").clicked() {- self.nyi("Graph → Data Flow");+ if ui+ .button("Data Flow")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Graph → Data Flow");ui.close_menu();}});- ui.menu_button("Window", |ui| {- // Docked panels (long-standing).- ui.label(egui::RichText::new("Docked").small().weak());- ui.checkbox(&mut self.show_project_tree, "Project Tree (dock)");- ui.checkbox(&mut self.show_program_tree, "Program Tree (dock)");- ui.checkbox(&mut self.show_symbol_tree, "Symbol Tree (dock)");- ui.checkbox(&mut self.show_console, "Console (dock)");+ ui.menu_button("Window", |ui| {+ // Docked panels (long-standing).+ ui.label(egui::RichText::new("Docked").small().weak());+ ui.checkbox(&mut self.show_project_tree, "Project Tree (dock)");+ ui.checkbox(&mut self.show_program_tree, "Program Tree (dock)");+ ui.checkbox(&mut self.show_symbol_tree, "Symbol Tree (dock)");+ ui.checkbox(&mut self.show_console, "Console (dock)");ui.separator();- // Center dock tabs (Listing/Decompiler prefer side-by-side).- ui.label(egui::RichText::new("Center Tabs").small().weak());+ // Center dock tabs (Listing/Decompiler prefer side-by-side).+ ui.label(egui::RichText::new("Center Tabs").small().weak());if ui- .selectable_label(self.center == CenterPane::Overview, "Overview")+ .selectable_label(self.center == CenterPane::Overview, "Overview").clicked(){self.focus_center_tab(DockTab::Overview);}if ui- .selectable_label(self.center == CenterPane::Listing, "Listing")+ .selectable_label(self.center == CenterPane::Listing, "Listing").clicked(){self.focus_center_tab(DockTab::Listing);}if ui- .selectable_label(self.center == CenterPane::Decompiler, "Decompiler")+ .selectable_label(self.center == CenterPane::Decompiler, "Decompiler").clicked(){self.focus_center_tab(DockTab::Decompiler);}if ui- .selectable_label(- self.center == CenterPane::DataTypes,- "Data Type Manager",- )+ .selectable_label(self.center == CenterPane::DataTypes, "Data Type Manager").clicked(){self.focus_center_tab(DockTab::DataTypes);}ui.separator();- // Full provider catalog (floating windows).- // Sorted alphabetically by title to mirror Window menu.- ui.label(egui::RichText::new("All Providers (catalog)").small().weak());+ // Full provider catalog (floating windows).+ // Sorted alphabetically by title to mirror Window menu.+ ui.label(+ egui::RichText::new("All Providers (catalog)")+ .small()+ .weak(),+ );let mut providers: Vec<PaneKind> = PaneKind::ALL.to_vec();providers.sort_by_key(|k| k.title());for k in providers {- // Skip providers that are already covered by a dock/checkbox above- // to avoid double-toggles (Project/Program/Symbol Tree, Console).+ // Skip providers that are already covered by a dock/checkbox above+ // to avoid double-toggles (Project/Program/Symbol Tree, Console).if matches!(k,PaneKind::ProjectTree@@ -7831,10 +8426,10 @@ impl eframe::App for GhidrustApp {}}ui.separator();- // Single tabbed Debugger host.- ui.label(egui::RichText::new("Debugger tool").small().weak());+ // Single tabbed Debugger host.+ ui.label(egui::RichText::new("Debugger tool").small().weak());let mut dbg_open = self.debugger.host_open;- if ui.checkbox(&mut dbg_open, "Debugger").changed() {+ if ui.checkbox(&mut dbg_open, "Debugger").changed() {self.debugger.host_open = dbg_open;if dbg_open {self.debugger.enabled = true;@@ -7844,7 +8439,7 @@ impl eframe::App for GhidrustApp {}}if self.debugger.host_open {- ui.indent("dbg_tab_focus", |ui| {+ ui.indent("dbg_tab_focus", |ui| {for p in DebuggerPane::TAB_ORDER {let selected = self.debugger.active_tab == *p;if ui.selectable_label(selected, p.short_title()).clicked() {@@ -7854,19 +8449,19 @@ impl eframe::App for GhidrustApp {});}ui.separator();- // layout tools.- if ui.button("Configure plugins…").clicked() {+ // layout tools.+ if ui.button("Configure plugins…").clicked() {self.show_configure_dialog = true;ui.close_menu();}- if ui.button("Save Tool Layout…").clicked() {+ if ui.button("Save Tool Layout…").clicked() {self.layouts_cached = layouts::list_layouts();self.layouts_new_name = self.current_layout_name.clone();self.show_layouts_dialog = true;ui.close_menu();}});- ui.menu_button("Debugger", |ui| {+ ui.menu_button("Debugger", |ui| {for act in DebuggerAction::ALL {let hover = match act {DebuggerAction::Launch => {@@ -7911,7 +8506,7 @@ impl eframe::App for GhidrustApp {self.debugger.toggle_breakpoint(va);self.debugger.focus_tab(DebuggerPane::Breakpoints);} else {- self.nyi("Debugger → Toggle Breakpoint (no listing VA)");+ self.nyi("Debugger → Toggle Breakpoint (no listing VA)");}}DebuggerAction::Continue@@ -7919,7 +8514,7 @@ impl eframe::App for GhidrustApp {| DebuggerAction::StepInto| DebuggerAction::StepOver| DebuggerAction::StepOut => {- self.nyi(&format!("Debugger → {}", act.label()));+ self.nyi(&format!("Debugger → {}", act.label()));}}ui.close_menu();@@ -7927,7 +8522,7 @@ impl eframe::App for GhidrustApp {}ui.separator();let mut enabled = self.debugger.enabled;- if ui.checkbox(&mut enabled, "Debugger tool mode").changed() {+ if ui.checkbox(&mut enabled, "Debugger tool mode").changed() {if enabled {self.debugger.enable_tool();} else {@@ -7936,115 +8531,159 @@ impl eframe::App for GhidrustApp {}}});- ui.menu_button("Help", |ui| {- if ui.button("Contents (F1)").on_hover_text("Not yet implemented").clicked() {- self.nyi("Help → Contents");+ ui.menu_button("Help", |ui| {+ if ui+ .button("Contents (F1)")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Help → Contents");ui.close_menu();}- if ui.button("Help On…").on_hover_text("Not yet implemented").clicked() {- self.nyi("Help → Help On");+ if ui+ .button("Help On…")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Help → Help On");ui.close_menu();}- if ui.button("API Help").on_hover_text("Not yet implemented").clicked() {- self.nyi("Help → API Help");+ if ui+ .button("API Help")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Help → API Help");ui.close_menu();}- if ui.button("User Preferences").on_hover_text("Not yet implemented").clicked() {- self.nyi("Help → User Preferences");+ if ui+ .button("User Preferences")+ .on_hover_text("Not yet implemented")+ .clicked()+ {+ self.nyi("Help → User Preferences");ui.close_menu();}- if ui.button("Show Log").on_hover_text("Console pane is open").clicked() {+ if ui+ .button("Show Log")+ .on_hover_text("Console pane is open")+ .clicked()+ {self.show_console = true;ui.close_menu();}ui.separator();- if ui.button("About Ghidrust").clicked() {+ if ui.button("About Ghidrust").clicked() {self.status = format!(- "Ghidrust {} — Rust RE toolkit (CodeBrowser shell)",- env!("CARGO_PKG_VERSION")+ "Ghidrust {} — Rust RE toolkit (CodeBrowser shell)",+ env!("CARGO_PKG_VERSION"));self.log(self.status.clone());ui.close_menu();}- if ui.button("Roadmap…").clicked() {- self.log("See local development notes under dev/");+ if ui.button("Roadmap…").clicked() {+ self.log("See local development notes under dev/");ui.close_menu();}});ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {let label = match self.theme {- ThemeMode::Dark => "Theme: Dark",- ThemeMode::Light => "Theme: Light",+ ThemeMode::Dark => "Theme: Dark",+ ThemeMode::Light => "Theme: Light",};if ui.button(label).clicked() {self.theme = self.theme.toggle();self.apply_theme(ctx);- self.log(format!("Theme → {:?}", self.theme));+ self.log(format!("Theme → {:?}", self.theme));}});});});- // Listing hotkeys run *after* the Grok dock paints (see below) so the- // TUI can claim focus/keys first — otherwise `G` opens Go To while typing.+ // Listing hotkeys run *after* the Grok dock paints (see below) so the+ // TUI can claim focus/keys first — otherwise `G` opens Go To while typing.- egui::TopBottomPanel::top("nav_toolbar").show(ctx, |ui| {+ egui::TopBottomPanel::top("nav_toolbar").show(ctx, |ui| {ui.horizontal(|ui| {let back_enabled = self.can_nav_back();let fwd_enabled = self.can_nav_forward();if ui- .add_enabled(back_enabled, egui::Button::new("<- Back"))- .on_hover_text("Navigation → Back (Alt+Left)")+ .add_enabled(back_enabled, egui::Button::new("<- Back"))+ .on_hover_text("Navigation → Back (Alt+Left)").clicked(){self.nav_back();}if ui- .add_enabled(fwd_enabled, egui::Button::new("Forward ->"))- .on_hover_text("Navigation → Forward (Alt+Right)")+ .add_enabled(fwd_enabled, egui::Button::new("Forward ->"))+ .on_hover_text("Navigation → Forward (Alt+Right)").clicked(){self.nav_forward();}ui.separator();- if ui.button("Go To…").on_hover_text("Navigation → Go To Address (G)").clicked() {+ if ui+ .button("Go To…")+ .on_hover_text("Navigation → Go To Address (G)")+ .clicked()+ {if let Some(prog) = &self.program {if let Some(e) = prog.entry {- self.goto_input = format!("{e:#x}");+ self.goto_input = format!("{e:#x}");} else {- self.goto_input = format!("{:#x}", prog.image_base);+ self.goto_input = format!("{:#x}", prog.image_base);}}self.show_goto_dialog = true;}ui.separator();- if ui.button("Bookmark…").on_hover_text("Add bookmark at cursor VA").clicked() {+ if ui+ .button("Bookmark…")+ .on_hover_text("Add bookmark at cursor VA")+ .clicked()+ {if let Some(va) = self.listing_focus_va {self.bookmark_dialog_kind = BookmarkKind::Note;self.bookmark_dialog_category = String::new();- self.bookmark_dialog_description = format!("bookmark @ {va:#x}");+ self.bookmark_dialog_description = format!("bookmark @ {va:#x}");self.show_bookmark_dialog = true;} else {- self.status = "No cursor VA — click a Listing line first".into();+ self.status = "No cursor VA — click a Listing line first".into();self.log(self.status.clone());}}- if ui.button("Bookmarks").on_hover_text("Window → Bookmarks").clicked() {+ if ui+ .button("Bookmarks")+ .on_hover_text("Window → Bookmarks")+ .clicked()+ {self.pane_open.insert(PaneKind::Bookmarks, true);}- if ui.button("Functions").on_hover_text("Window → Functions").clicked() {+ if ui+ .button("Functions")+ .on_hover_text("Window → Functions")+ .clicked()+ {self.pane_open.insert(PaneKind::FunctionsWindow, true);}- if ui.button("Memory Map").on_hover_text("Window → Memory Map").clicked() {+ if ui+ .button("Memory Map")+ .on_hover_text("Window → Memory Map")+ .clicked()+ {self.pane_open.insert(PaneKind::MemoryMap, true);}- if ui.button("Symbol Table").on_hover_text("Window → Symbol Table").clicked() {+ if ui+ .button("Symbol Table")+ .on_hover_text("Window → Symbol Table")+ .clicked()+ {self.pane_open.insert(PaneKind::SymbolTable, true);}ui.separator();let hist = format!(- "Back: {} · Forward: {}",+ "Back: {} · Forward: {}",self.nav_history.len_back(),self.nav_history.len_forward());@@ -8052,78 +8691,102 @@ impl eframe::App for GhidrustApp {});});- egui::TopBottomPanel::top("toolbar").show(ctx, |ui| {+ egui::TopBottomPanel::top("toolbar").show(ctx, |ui| {ui.horizontal(|ui| {- ui.label("Project dir:");+ ui.label("Project dir:");ui.add(egui::TextEdit::singleline(&mut self.project_dir_input).desired_width(240.0)- .hint_text("folder for New/Open project"),+ .hint_text("folder for New/Open project"),);- if ui.button("Browse…").on_hover_text("Choose project folder").clicked() {+ if ui+ .button("Browse…")+ .on_hover_text("Choose project folder")+ .clicked()+ {self.browse_project_dir();}- ui.label("Name:");+ ui.label("Name:");ui.add(egui::TextEdit::singleline(&mut self.project_name_input).desired_width(100.0),);- if ui.button("New").on_hover_text("Create project (browse if dir empty)").clicked() {+ if ui+ .button("New")+ .on_hover_text("Create project (browse if dir empty)")+ .clicked()+ {if self.project_dir_input.trim().is_empty() {self.browse_and_create_project();} else if let Err(e) = self.create_project() {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}- if ui.button("Open").on_hover_text("Open project (browse if dir empty)").clicked() {+ if ui+ .button("Open")+ .on_hover_text("Open project (browse if dir empty)")+ .clicked()+ {if self.project_dir_input.trim().is_empty() {self.browse_and_open_project();} else if let Err(e) = self.open_project() {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}});ui.horizontal(|ui| {- ui.label("Binary:");+ ui.label("Binary:");ui.add(egui::TextEdit::singleline(&mut self.path_input).desired_width(320.0)- .hint_text("PE/ELF — or use Browse"),+ .hint_text("PE/ELF — or use Browse"),);- if ui.button("Browse…").on_hover_text("Choose binary file").clicked() {+ if ui+ .button("Browse…")+ .on_hover_text("Choose binary file")+ .clicked()+ {self.browse_binary_path();}- if ui.button("Import").on_hover_text("Import into project (browse if empty)").clicked() {+ if ui+ .button("Import")+ .on_hover_text("Import into project (browse if empty)")+ .clicked()+ {if self.path_input.trim().is_empty() {self.browse_and_import();} else if let Err(e) = self.import_into_project() {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}- if ui.button("Load").on_hover_text("Load binary without project (browse if empty)").clicked() {+ if ui+ .button("Load")+ .on_hover_text("Load binary without project (browse if empty)")+ .clicked()+ {if self.path_input.trim().is_empty() {self.browse_and_load_binary();} else {let p = self.path_input.clone();if let Err(e) = self.load_binary(p) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}}if ui- .button("Analyze…")- .on_hover_text("Open analysis options (analyzers + GPU)")+ .button("Analyze…")+ .on_hover_text("Open analysis options (analyzers + GPU)").clicked(){self.pending_analyze_file_id = self.active_file_id.clone();self.show_analysis_dialog = true;}- if ui.button("Save").clicked() {+ if ui.button("Save").clicked() {if let Err(e) = self.save_results() {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}@@ -8148,12 +8811,12 @@ impl eframe::App for GhidrustApp {if !file_chips.is_empty() {let pname = file_chips[0].0.clone();ui.horizontal(|ui| {- ui.label(format!("Open: {pname} | files:"));+ ui.label(format!("Open: {pname} | files:"));for (_, id, name) in &file_chips {let selected = self.active_file_id.as_deref() == Some(id.as_str());if ui.selectable_label(selected, name).clicked() {if let Err(e) = self.open_project_file(id) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}@@ -8162,7 +8825,7 @@ impl eframe::App for GhidrustApp {}});- egui::TopBottomPanel::bottom("status").show(ctx, |ui| {+ egui::TopBottomPanel::bottom("status").show(ctx, |ui| {if let Some(frac) = self.analysis_progress_fraction() {let t = m3_tokens(self.theme);let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);@@ -8181,22 +8844,26 @@ impl eframe::App for GhidrustApp {.names.get(j.index).cloned()- .unwrap_or_else(|| "finishing…".into());+ .unwrap_or_else(|| "finishing…".into());(format!(- "Analyzing {} — {}/{} {cur}{}",+ "Analyzing {} — {}/{} {cur}{}",j.file_label,(j.index + 1).min(n),n,- if j.use_gpu { " · GPU experimental" } else { "" }+ if j.use_gpu {+ " · GPU experimental"+ } else {+ ""+ }),(frac * 100.0) as u32,)})- .unwrap_or_else(|| ("Analyzing…".into(), 0));+ .unwrap_or_else(|| ("Analyzing…".into(), 0));ui.label(egui::RichText::new(label).color(primary));m3_linear_progress(ui, frac, primary, track);- ui.small(format!("{pct}%"));+ ui.small(format!("{pct}%"));} else {ui.horizontal(|ui| {ui.label(&self.status);@@ -8208,30 +8875,30 @@ impl eframe::App for GhidrustApp {}});- // Bottom dock: tabbed (Grok primary + Console + Raw). The plain- // analyzer / script log is never hidden — it just moves under the- // "Console" tab. Grok is the default active tab so an RE opens the- // app and starts typing to the agent immediately.- //- // Explicit min/max/default heights are required for the top-edge- // resize gizmo to be draggable freely — without them egui pins the- // panel to `default_height` and the drag handle becomes a 4px sliver- // that's easy to miss.+ // Bottom dock: tabbed (Grok primary + Console + Raw). The plain+ // analyzer / script log is never hidden — it just moves under the+ // "Console" tab. Grok is the default active tab so an RE opens the+ // app and starts typing to the agent immediately.+ //+ // Explicit min/max/default heights are required for the top-edge+ // resize gizmo to be draggable freely — without them egui pins the+ // panel to `default_height` and the drag handle becomes a 4px sliver+ // that's easy to miss.if self.show_console {- // Detect Grok TUI child exit before paint.+ // Detect Grok TUI child exit before paint.self.grok_pane.poll();let screen_h = ctx.screen_rect().height();- // Own the height ourselves + paint a real drag grip. Built-in- // `resizable(true)` on TopBottomPanel is unreliable here (snaps- // back when content doesn't expand — egui #581 / 0.31).+ // Own the height ourselves + paint a real drag grip. Built-in+ // `resizable(true)` on TopBottomPanel is unreliable here (snaps+ // back when content doesn't expand — egui #581 / 0.31).let max_h = (screen_h - 160.0).max(220.0);let min_h = 140.0;self.console_height = self.console_height.clamp(min_h, max_h);- egui::TopBottomPanel::bottom("console")+ egui::TopBottomPanel::bottom("console").exact_height(self.console_height).show_separator_line(false).show(ctx, |ui| {- // Full-width drag strip at the top of the dock.+ // Full-width drag strip at the top of the dock.let grip_h = 10.0;let (grip_rect, grip_resp) = ui.allocate_exact_size(egui::vec2(ui.available_width(), grip_h),@@ -8245,11 +8912,9 @@ impl eframe::App for GhidrustApp {ui.visuals().widgets.noninteractive.bg_fill};ui.painter().rect_filled(grip_rect, 0.0, grip_color);- // Center handle bar.- let bar = egui::Rect::from_center_size(- grip_rect.center(),- egui::vec2(48.0, 3.0),- );+ // Center handle bar.+ let bar =+ egui::Rect::from_center_size(grip_rect.center(), egui::vec2(48.0, 3.0));ui.painter().rect_filled(bar,1.5,@@ -8259,19 +8924,19 @@ impl eframe::App for GhidrustApp {ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);}if grip_resp.dragged() {- // Dragging the top edge up (negative dy) grows the panel.- self.console_height = (self.console_height - grip_resp.drag_delta().y)- .clamp(min_h, max_h);+ // Dragging the top edge up (negative dy) grows the panel.+ self.console_height =+ (self.console_height - grip_resp.drag_delta().y).clamp(min_h, max_h);}- grip_resp.on_hover_text("Drag to resize console");+ grip_resp.on_hover_text("Drag to resize console");ui.set_min_height(ui.available_height());self.render_bottom_dock(ui);});}- // Global keyboard shortcuts (after Grok dock so keyboard_captured is current).- // bindings: Alt+Left/Right, G, L/Ctrl+L, ;, T, Alt+Enter, Ctrl+Up/Down.+ // Global keyboard shortcuts (after Grok dock so keyboard_captured is current).+ // bindings: Alt+Left/Right, G, L/Ctrl+L, ;, T, Alt+Enter, Ctrl+Up/Down.if !self.grok_pane.keyboard_captured {let (want_back,@@ -8309,9 +8974,10 @@ impl eframe::App for GhidrustApp {if want_goto && self.program.is_some() {if self.goto_input.is_empty() {if let Some(prog) = &self.program {- self.goto_input = prog.entry- .map(|e| format!("{e:#x}"))- .unwrap_or_else(|| format!("{:#x}", prog.image_base));+ self.goto_input = prog+ .entry+ .map(|e| format!("{e:#x}"))+ .unwrap_or_else(|| format!("{:#x}", prog.image_base));}}self.show_goto_dialog = true;@@ -8361,13 +9027,13 @@ impl eframe::App for GhidrustApp {}}- // Project Window–style dock: Project → binaries (upgraded badges + actions)+ // Project Window–style dock: Project → binaries (upgraded badges + actions)if self.show_project_tree {- egui::SidePanel::left("project_tree")+ egui::SidePanel::left("project_tree").resizable(true).default_width(240.0).show(ctx, |ui| {- ui.heading("Project");+ ui.heading("Project");ui.small(egui::RichText::new("Click = select · Double-click / Open = load into main view · Analyze = options",@@ -8376,47 +9042,55 @@ impl eframe::App for GhidrustApp {);ui.separator();if self.project.is_none() {- ui.weak("No project open.");- ui.label("New/Open a project, then Import binaries.");+ ui.weak("No project open.");+ ui.label("New/Open a project, then Import binaries.");} else {let model = self.project_tree_model().unwrap();let t = m3_tokens(self.theme);let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);- let muted =- Color32::from_rgb(t.on_surface_variant[0], t.on_surface_variant[1], t.on_surface_variant[2]);+ let muted = Color32::from_rgb(+ t.on_surface_variant[0],+ t.on_surface_variant[1],+ t.on_surface_variant[2],+ );let ok_green = Color32::from_rgb(0x4C, 0xAF, 0x50);ui.horizontal(|ui| {m3_icon(ui, M3Icon::Folder, 18.0, primary);ui.strong(&model.project_name);});- // Fill remaining panel height and scroll when files overflow- // (same idiom as Console / working list panes).+ // Fill remaining panel height and scroll when files overflow+ // (same idiom as Console / working list panes).let root_open = egui::ScrollArea::vertical()- .id_salt("project_tree_scroll")+ .id_salt("project_tree_scroll").auto_shrink([false, false]).show(ui, |ui| {- egui::CollapsingHeader::new("Project files")+ egui::CollapsingHeader::new("Project files").default_open(self.project_tree_expanded).show(ui, |ui| {ui.small(egui::RichText::new(&model.project_root).weak());ui.add_space(4.0);if model.files.is_empty() {- ui.weak("Empty — Import a binary.");+ ui.weak("Empty — Import a binary.");}let mut open_id: Option<String> = None;let mut analyze_id: Option<String> = None;let mut delete_id: Option<String> = None;let mut select_id: Option<String> = None;for row in &model.files {- let selected =- self.tree_selected_id.as_deref() == Some(row.id.as_str());+ let selected = self.tree_selected_id.as_deref()+ == Some(row.id.as_str());let viewing = self.active_file_id.as_deref()== Some(row.id.as_str())&& self.program.is_some();ui.group(|ui| {ui.horizontal(|ui| {if viewing {- m3_icon(ui, M3Icon::PlayArrow, 14.0, primary);+ m3_icon(+ ui,+ M3Icon::PlayArrow,+ 14.0,+ primary,+ );} else {ui.add_space(14.0);}@@ -8439,18 +9113,23 @@ impl eframe::App for GhidrustApp {);if viewing {ui.small(- egui::RichText::new("viewing").color(primary),+ egui::RichText::new("viewing")+ .color(primary),);} else if row.has_saved_analysis {ui.small(- egui::RichText::new("double-click to open")- .weak(),+ egui::RichText::new(+ "double-click to open",+ )+ .weak(),);}});ui.horizontal(|ui| {ui.with_layout(- egui::Layout::right_to_left(egui::Align::Center),+ egui::Layout::right_to_left(+ egui::Align::Center,+ ),|ui| {if ui.small_button("Delete")@@ -8495,7 +9174,8 @@ impl eframe::App for GhidrustApp {}).inner;let expanded = root_open.fully_open();- if let Some((open_id, analyze_id, delete_id, select_id)) = root_open.body_returned+ if let Some((open_id, analyze_id, delete_id, select_id)) =+ root_open.body_returned{if let Some(id) = select_id {self.tree_selected_id = Some(id);@@ -8504,12 +9184,12 @@ impl eframe::App for GhidrustApp {self.request_delete_file(&id);} else if let Some(id) = analyze_id {if let Err(e) = self.analyze_from_tree(&id) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}} else if let Some(id) = open_id {if let Err(e) = self.open_from_tree(&id) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}@@ -8519,32 +9199,35 @@ impl eframe::App for GhidrustApp {});}- // Delete confirmation modal+ // Delete confirmation modalif let Some((ref id, ref name)) = self.pending_delete.clone() {let id = id.clone();let name = name.clone();- egui::Window::new("Delete from project?")+ egui::Window::new("Delete from project?").collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {ui.label(format!(- "Remove \"{name}\" from this project?\n\n\+ "Remove \"{name}\" from this project?\n\n\Deletes the imported copy and saved analysis for this file.\n\This cannot be undone."));ui.add_space(8.0);ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {self.cancel_delete_file();}if ui- .button(egui::RichText::new("Delete").color(Color32::from_rgb(0xB3, 0x26, 0x1E)))+ .button(+ egui::RichText::new("Delete")+ .color(Color32::from_rgb(0xB3, 0x26, 0x1E)),+ ).clicked(){let _ = id;if let Err(e) = self.confirm_delete_file() {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}@@ -8553,21 +9236,18 @@ impl eframe::App for GhidrustApp {}if self.show_program_tree {- egui::SidePanel::left("program_tree")+ egui::SidePanel::left("program_tree").resizable(true).default_width(220.0).show(ctx, |ui| {- ui.heading("Program Trees");- ui.small(- egui::RichText::new("ProgramTreePlugin · modules/fragments")- .weak(),- );+ ui.heading("Program Trees");+ ui.small(egui::RichText::new("ProgramTreePlugin · modules/fragments").weak());ui.separator();let Some(prog) = self.program.as_ref() else {- ui.weak("No program loaded.");+ ui.weak("No program loaded.");return;};- // Snapshot everything we need before mutable use later.+ // Snapshot everything we need before mutable use later.let root_name = prog.name.clone();let entry = prog.entry;let image_base = prog.image_base;@@ -8597,16 +9277,16 @@ impl eframe::App for GhidrustApp {});ui.small(egui::RichText::new(format!(- "image base {image_base:#x}{}",+ "image base {image_base:#x}{}",entry- .map(|e| format!(" · entry {e:#x}"))+ .map(|e| format!(" · entry {e:#x}")).unwrap_or_default())).weak(),);- // Group blocks into modules by permissions.- // Module: "Code" (executable), "Data" (writable, non-exec), "RO Data" (else).+ // Group blocks into modules by permissions.+ // Module: "Code" (executable), "Data" (writable, non-exec), "RO Data" (else).let mut code: Vec<usize> = Vec::new();let mut data: Vec<usize> = Vec::new();let mut rodata: Vec<usize> = Vec::new();@@ -8626,41 +9306,37 @@ impl eframe::App for GhidrustApp {let mut set_view: Option<String> = None;let mut show_all = false;let view_filter = self.listing_view_filter.clone();- let mut render_module =- |ui: &mut egui::Ui, title: &str, indices: &[usize]| {- egui::CollapsingHeader::new(format!(- "{title} ({})",- indices.len()- ))+ let mut render_module = |ui: &mut egui::Ui, title: &str, indices: &[usize]| {+ egui::CollapsingHeader::new(format!("{title} ({})", indices.len())).default_open(!indices.is_empty() && indices.len() <= 32).show(ui, |ui| {if indices.is_empty() {- ui.weak("(empty module)");+ ui.weak("(empty module)");return;}for &i in indices {let (name, va, size, r, w, x) = &blocks[i];let flags = format!(- "{}{}{}",- if *r { "r" } else { "-" },- if *w { "w" } else { "-" },- if *x { "x" } else { "-" },+ "{}{}{}",+ if *r { "r" } else { "-" },+ if *w { "w" } else { "-" },+ if *x { "x" } else { "-" },);let in_view = view_filter.as_ref().map(|f| f.contains(name)).unwrap_or(true);ui.horizontal(|ui| {- let indicator = if in_view { "[v]" } else { "[ ]" };+ let indicator = if in_view { "[v]" } else { "[ ]" };ui.monospace(indicator);if ui.link(egui::RichText::new(format!(- "{name} {va:#x} {size:#x} {flags}"+ "{name} {va:#x} {size:#x} {flags}")).monospace(),)- .on_hover_text("Go To fragment start")+ .on_hover_text("Go To fragment start").clicked(){goto = Some(*va);@@ -8670,27 +9346,25 @@ impl eframe::App for GhidrustApp {|ui| {if in_view && view_filter.is_some() {if ui- .small_button("Remove")+ .small_button("Remove").on_hover_text(- "Remove fragment from Listing view",+ "Remove fragment from Listing view",).clicked(){remove_from_view = Some(name.clone());}} else if ui- .small_button("Add")- .on_hover_text(- "Add fragment to Listing view",- )+ .small_button("Add")+ .on_hover_text("Add fragment to Listing view").clicked(){add_to_view = Some(name.clone());}if ui- .small_button("Set")+ .small_button("Set").on_hover_text(- "Set Listing view to this fragment only",+ "Set Listing view to this fragment only",).clicked(){@@ -8701,33 +9375,33 @@ impl eframe::App for GhidrustApp {});}});- };+ };egui::ScrollArea::vertical()- .id_salt("program_tree_scroll")+ .id_salt("program_tree_scroll").auto_shrink([false, false]).show(ui, |ui| {- render_module(ui, "Code (X)", &code);- render_module(ui, "Data (RW)", &data);- render_module(ui, "Read‑only (R)", &rodata);+ render_module(ui, "Code (X)", &code);+ render_module(ui, "Data (RW)", &data);+ render_module(ui, "Read‑only (R)", &rodata);ui.separator();ui.horizontal(|ui| {if ui- .small_button("Show All")- .on_hover_text("Clear the Listing view filter")+ .small_button("Show All")+ .on_hover_text("Clear the Listing view filter").clicked(){show_all = true;}if let Some(f) = view_filter.as_ref() {ui.small(format!(- "View filter · {} fragment(s) in view",+ "View filter · {} fragment(s) in view",f.len()));} else {ui.small(- egui::RichText::new("View filter · full program")+ egui::RichText::new("View filter · full program").weak().italics(),);@@ -8736,7 +9410,7 @@ impl eframe::App for GhidrustApp {});if let Some(va) = goto {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}if let Some(name) = add_to_view {self.add_to_view(name);@@ -8756,226 +9430,231 @@ impl eframe::App for GhidrustApp {}if self.show_symbol_tree {- egui::SidePanel::right("symbol_tree")+ egui::SidePanel::right("symbol_tree").resizable(true).default_width(280.0).min_width(200.0).show(ctx, |ui| {let t = m3_tokens(self.theme);let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);- ui.heading("Symbol Tree");+ ui.heading("Symbol Tree");if self.program.is_none() {- ui.weak("Open a project file to browse symbols.");+ ui.weak("Open a project file to browse symbols.");return;}ui.small(egui::RichText::new(self.analysis_summary_line()).color(primary));ui.horizontal(|ui| {- ui.checkbox(- &mut self.symbol_tree_nav,- "Selection Navigation",- )- .on_hover_text(- "`Selection Navigation` — cursor moves keep this tree in sync",- );+ ui.checkbox(&mut self.symbol_tree_nav, "Selection Navigation")+ .on_hover_text(+ "`Selection Navigation` — cursor moves keep this tree in sync",+ );});ui.separator();- // Outer scroll so category headers + expanded sections aren't clipped- // when they exceed the dock height. Per-list ScrollAreas keep max_height- // so nested wheel scrolling still targets the open list.+ // Outer scroll so category headers + expanded sections aren't clipped+ // when they exceed the dock height. Per-list ScrollAreas keep max_height+ // so nested wheel scrolling still targets the open list.egui::ScrollArea::vertical()- .id_salt("symbol_tree_scroll")+ .id_salt("symbol_tree_scroll").auto_shrink([false, false]).show(ui, |ui| {- // ── `SymbolTreePlugin` category order ────────────────- // Imports · Exports · Functions · Labels · Classes · Namespaces+ // ── `SymbolTreePlugin` category order ────────────────+ // Imports · Exports · Functions · Labels · Classes · Namespaces- let (imports, exports) = self.imports_exports();+ let (imports, exports) = self.imports_exports();- let mut nav_goto: Option<u64> = None;- // 1) Imports — honest: only rows the analyzer/loader produced.- egui::CollapsingHeader::new(format!("Imports ({})", imports.len()))- .default_open(false)- .show(ui, |ui| {- if imports.is_empty() {- ui.weak(- "No imports — Ghidrust PE loader currently does not \+ let mut nav_goto: Option<u64> = None;+ // 1) Imports — honest: only rows the analyzer/loader produced.+ egui::CollapsingHeader::new(format!("Imports ({})", imports.len()))+ .default_open(false)+ .show(ui, |ui| {+ if imports.is_empty() {+ ui.weak(+ "No imports — Ghidrust PE loader currently does not \parse the Import Directory. Run a PDB analyzer to \populate __imp_* symbols.",- );- } else {- for (va, name) in &imports {- if ui- .link(- egui::RichText::new(format!("{va:#x} {name}"))- .monospace(),- )- .clicked()- {- nav_goto = Some(*va);- }- }- }- });- // 2) Exports — honest empty when unset.- egui::CollapsingHeader::new(format!("Exports ({})", exports.len()))- .default_open(false)- .show(ui, |ui| {- if exports.is_empty() {- ui.weak(- "No exports — Ghidrust PE loader currently does not \+ );+ } else {+ for (va, name) in &imports {+ if ui+ .link(+ egui::RichText::new(format!("{va:#x} {name}"))+ .monospace(),+ )+ .clicked()+ {+ nav_goto = Some(*va);+ }+ }+ }+ });+ // 2) Exports — honest empty when unset.+ egui::CollapsingHeader::new(format!("Exports ({})", exports.len()))+ .default_open(false)+ .show(ui, |ui| {+ if exports.is_empty() {+ ui.weak(+ "No exports — Ghidrust PE loader currently does not \parse the Export Directory. Analyzer output may \surface `__declspec(dllexport)` names.",- );- } else {- for (va, name) in &exports {- if ui- .link(- egui::RichText::new(format!("{va:#x} {name}"))- .monospace(),- )- .clicked()- {- nav_goto = Some(*va);+ );+ } else {+ for (va, name) in &exports {+ if ui+ .link(+ egui::RichText::new(format!("{va:#x} {name}"))+ .monospace(),+ )+ .clicked()+ {+ nav_goto = Some(*va);+ }+ }}- }+ });+ if let Some(va) = nav_goto {+ let _ = self.goto_address_str(&format!("{va:#x}"));}- });- if let Some(va) = nav_goto {- let _ = self.goto_address_str(&format!("{va:#x}"));- }- // 3) Functions (virtualized) — real from Program::analysis.functions- let fn_count = self- .program- .as_ref()- .map(|p| p.analysis.functions.len())- .unwrap_or(0);- egui::CollapsingHeader::new(format!("Functions ({fn_count})"))- .default_open(fn_count > 0 && fn_count <= 500)- .show(ui, |ui| {- let entry = self.program.as_ref().and_then(|p| p.entry);- let fns: Vec<(u64, String)> = self+ // 3) Functions (virtualized) — real from Program::analysis.functions+ let fn_count = self+ .program+ .as_ref()+ .map(|p| p.analysis.functions.len())+ .unwrap_or(0);+ egui::CollapsingHeader::new(format!("Functions ({fn_count})"))+ .default_open(fn_count > 0 && fn_count <= 500)+ .show(ui, |ui| {+ let entry = self.program.as_ref().and_then(|p| p.entry);+ let fns: Vec<(u64, String)> = self+ .program+ .as_ref()+ .map(|p| {+ p.analysis+ .functions+ .iter()+ .map(|f| (f.entry, f.name.clone()))+ .collect()+ })+ .unwrap_or_default();+ if let Some(e) = entry {+ ui.monospace(format!("entry @ {e:#x}"));+ }+ if fns.is_empty() {+ ui.weak("Run Function Start Search.");+ } else {+ ui.add(+ egui::TextEdit::singleline(&mut self.fn_filter)+ .desired_width(f32::INFINITY)+ .hint_text("Filter functions…"),+ );+ let q = self.fn_filter.to_ascii_lowercase();+ let rows: Vec<(u64, String)> = fns+ .into_iter()+ .filter(|(_, name)| {+ q.is_empty()+ || name.to_ascii_lowercase().contains(&q)+ })+ .collect();+ let row_h =+ ui.text_style_height(&egui::TextStyle::Monospace);+ let n = rows.len();+ let mut clicked_fn: Option<u64> = None;+ egui::ScrollArea::vertical()+ .id_salt("fn_scroll")+ .max_height(220.0)+ .show_rows(ui, row_h, n, |ui, range| {+ for i in range {+ let (va, name) = &rows[i];+ let label = format!("{va:#x} {name}");+ // Focused if this function is the decomp / cursor /+ // selection-navigation target.+ let focused = self.decomp_entry == Some(*va)+ || self.listing_focus_va == Some(*va)+ || self.focused_function_entry == Some(*va);+ let rich = if focused {+ egui::RichText::new(label)+ .monospace()+ .color(primary)+ } else {+ egui::RichText::new(label).monospace()+ };+ let r = ui.add(+ egui::Label::new(rich)+ .sense(egui::Sense::click()),+ );+ if r.clicked() {+ clicked_fn = Some(*va);+ }+ if r.hovered() {+ ui.ctx().set_cursor_icon(+ egui::CursorIcon::PointingHand,+ );+ }+ }+ });+ if let Some(va) = clicked_fn {+ self.focus_function(va);+ }+ ui.small(format!(+ "{n} shown · click → Listing + Decompiler"+ ));+ }+ });++ // 4) Labels — Program::analysis.symbols (real)+ let labels: Vec<(u64, String)> = self.program.as_ref().map(|p| {p.analysis- .functions+ .symbols.iter()- .map(|f| (f.entry, f.name.clone()))+ .map(|s| (s.va, s.name.clone())).collect()}).unwrap_or_default();- if let Some(e) = entry {- ui.monospace(format!("entry @ {e:#x}"));- }- if fns.is_empty() {- ui.weak("Run Function Start Search.");- } else {- ui.add(- egui::TextEdit::singleline(&mut self.fn_filter)- .desired_width(f32::INFINITY)- .hint_text("Filter functions…"),- );- let q = self.fn_filter.to_ascii_lowercase();- let rows: Vec<(u64, String)> = fns- .into_iter()- .filter(|(_, name)| {- q.is_empty() || name.to_ascii_lowercase().contains(&q)- })- .collect();- let row_h = ui.text_style_height(&egui::TextStyle::Monospace);- let n = rows.len();- let mut clicked_fn: Option<u64> = None;- egui::ScrollArea::vertical()- .id_salt("fn_scroll")- .max_height(220.0)- .show_rows(ui, row_h, n, |ui, range| {- for i in range {- let (va, name) = &rows[i];- let label = format!("{va:#x} {name}");- // Focused if this function is the decomp / cursor /- // selection-navigation target.- let focused = self.decomp_entry == Some(*va)- || self.listing_focus_va == Some(*va)- || self.focused_function_entry == Some(*va);- let rich = if focused {- egui::RichText::new(label)- .monospace()- .color(primary)- } else {- egui::RichText::new(label).monospace()- };- let r = ui.add(- egui::Label::new(rich).sense(egui::Sense::click()),- );- if r.clicked() {- clicked_fn = Some(*va);- }- if r.hovered() {- ui.ctx().set_cursor_icon(- egui::CursorIcon::PointingHand,- );- }- }- });- if let Some(va) = clicked_fn {- self.focus_function(va);- }- ui.small(format!("{n} shown · click → Listing + Decompiler"));- }- });-- // 4) Labels — Program::analysis.symbols (real)- let labels: Vec<(u64, String)> = self- .program- .as_ref()- .map(|p| {- p.analysis- .symbols- .iter()- .map(|s| (s.va, s.name.clone()))- .collect()- })- .unwrap_or_default();- egui::CollapsingHeader::new(format!("Labels ({})", labels.len()))- .default_open(false)- .show(ui, |ui| {- if labels.is_empty() {- ui.weak("No labels — analyzers/PDB symbols populate this list.");- } else {- let row_h = ui.text_style_height(&egui::TextStyle::Monospace);- let n = labels.len();- let mut clicked_va: Option<u64> = None;- egui::ScrollArea::vertical()- .id_salt("labels_scroll")- .max_height(220.0)- .show_rows(ui, row_h, n, |ui, range| {- for i in range {- let (va, name) = &labels[i];- let r = ui.add(- egui::Label::new(- egui::RichText::new(format!(- "{va:#x} {name}"- ))- .monospace(),- )- .sense(egui::Sense::click()),- );- if r.clicked() {- clicked_va = Some(*va);- }+ egui::CollapsingHeader::new(format!("Labels ({})", labels.len()))+ .default_open(false)+ .show(ui, |ui| {+ if labels.is_empty() {+ ui.weak(+ "No labels — analyzers/PDB symbols populate this list.",+ );+ } else {+ let row_h =+ ui.text_style_height(&egui::TextStyle::Monospace);+ let n = labels.len();+ let mut clicked_va: Option<u64> = None;+ egui::ScrollArea::vertical()+ .id_salt("labels_scroll")+ .max_height(220.0)+ .show_rows(ui, row_h, n, |ui, range| {+ for i in range {+ let (va, name) = &labels[i];+ let r = ui.add(+ egui::Label::new(+ egui::RichText::new(format!(+ "{va:#x} {name}"+ ))+ .monospace(),+ )+ .sense(egui::Sense::click()),+ );+ if r.clicked() {+ clicked_va = Some(*va);+ }+ }+ });+ if let Some(va) = clicked_va {+ let _ = self.goto_address_str(&format!("{va:#x}"));}- });- if let Some(va) = clicked_va {- let _ = self.goto_address_str(&format!("{va:#x}"));- }- }- });+ }+ });- // 5) Classes (RTTI subtree preserved) — real- let rtti_n = self.rtti.classes.len();- egui::CollapsingHeader::new(format!("Classes ({rtti_n})"))+ // 5) Classes (RTTI subtree preserved) — real+ let rtti_n = self.rtti.classes.len();+ egui::CollapsingHeader::new(format!("Classes ({rtti_n})")).default_open(false).show(ui, |ui| {if rtti_n == 0 {@@ -9052,101 +9731,102 @@ impl eframe::App for GhidrustApp {});});- // 6) Namespaces — honest: derive from `::` in symbol names when a demangler ran.- let namespace_map: BTreeMap<String, Vec<(u64, String)>> = {- let mut m: BTreeMap<String, Vec<(u64, String)>> = BTreeMap::new();- if let Some(prog) = self.program.as_ref() {- for s in prog- .analysis- .symbols- .iter()- .chain(prog.analysis.pdb_symbols.iter())- {- let src = s.demangled.as_deref().unwrap_or(&s.name);- if let Some(idx) = src.rfind("::") {- let ns = src[..idx].to_string();- let leaf = src[idx + 2..].to_string();- m.entry(ns).or_default().push((s.va, leaf));+ // 6) Namespaces — honest: derive from `::` in symbol names when a demangler ran.+ let namespace_map: BTreeMap<String, Vec<(u64, String)>> = {+ let mut m: BTreeMap<String, Vec<(u64, String)>> = BTreeMap::new();+ if let Some(prog) = self.program.as_ref() {+ for s in prog+ .analysis+ .symbols+ .iter()+ .chain(prog.analysis.pdb_symbols.iter())+ {+ let src = s.demangled.as_deref().unwrap_or(&s.name);+ if let Some(idx) = src.rfind("::") {+ let ns = src[..idx].to_string();+ let leaf = src[idx + 2..].to_string();+ m.entry(ns).or_default().push((s.va, leaf));+ }+ }}- }- }- m- };- egui::CollapsingHeader::new(format!("Namespaces ({})", namespace_map.len()))- .default_open(false)- .show(ui, |ui| {- if namespace_map.is_empty() {- ui.weak(+ m+ };+ egui::CollapsingHeader::new(format!(+ "Namespaces ({})",+ namespace_map.len()+ ))+ .default_open(false)+ .show(ui, |ui| {+ if namespace_map.is_empty() {+ ui.weak("No namespaces recovered — the Demangler Microsoft analyzer \fills this list when demangling produces `::` scopes.",);- return;- }- let mut clicked_va: Option<u64> = None;- for (ns, entries) in &namespace_map {- egui::CollapsingHeader::new(format!(- "{ns} ({})",- entries.len()- ))+ return;+ }+ let mut clicked_va: Option<u64> = None;+ for (ns, entries) in &namespace_map {+ egui::CollapsingHeader::new(format!(+ "{ns} ({})",+ entries.len()+ ))+ .default_open(false)+ .show(ui, |ui| {+ for (va, leaf) in entries {+ if ui+ .link(+ egui::RichText::new(format!("{va:#x} {leaf}"))+ .monospace(),+ )+ .clicked()+ {+ clicked_va = Some(*va);+ }+ }+ });+ }+ if let Some(va) = clicked_va {+ let _ = self.goto_address_str(&format!("{va:#x}"));+ }+ });++ // Bonus: Strings shortcut (has a separate Defined Strings window,+ // which is available in the floating provider panel too).+ let str_n = self.strings.len();+ egui::CollapsingHeader::new(format!("Strings ({str_n})")).default_open(false).show(ui, |ui| {- for (va, leaf) in entries {- if ui- .link(- egui::RichText::new(format!(- "{va:#x} {leaf}"- ))- .monospace(),- )- .clicked()- {- clicked_va = Some(*va);- }+ if str_n == 0 {+ ui.weak("Run ASCII Strings (session) or re-analyze.");+ return;}- });- }- if let Some(va) = clicked_va {- let _ = self.goto_address_str(&format!("{va:#x}"));- }- });-- // Bonus: Strings shortcut (has a separate Defined Strings window,- // which is available in the floating provider panel too).- let str_n = self.strings.len();- egui::CollapsingHeader::new(format!("Strings ({str_n})"))- .default_open(false)- .show(ui, |ui| {- if str_n == 0 {- ui.weak("Run ASCII Strings (session) or re-analyze.");- return;- }- if ui.button("Open Defined Strings window").clicked() {- self.pane_open.insert(PaneKind::DefinedStrings, true);- }- let row_h = ui.text_style_height(&egui::TextStyle::Monospace);- egui::ScrollArea::vertical()- .id_salt("str_scroll")- .max_height(200.0)- .show_rows(ui, row_h, str_n.min(5000), |ui, range| {- for i in range {- if let Some(s) = self.strings.get(i) {- let val: String =- s.value.chars().take(48).collect();- ui.monospace(format!("{:#x}: {val}", s.va));- }+ if ui.button("Open Defined Strings window").clicked() {+ self.pane_open.insert(PaneKind::DefinedStrings, true);+ }+ let row_h = ui.text_style_height(&egui::TextStyle::Monospace);+ egui::ScrollArea::vertical()+ .id_salt("str_scroll")+ .max_height(200.0)+ .show_rows(ui, row_h, str_n.min(5000), |ui, range| {+ for i in range {+ if let Some(s) = self.strings.get(i) {+ let val: String =+ s.value.chars().take(48).collect();+ ui.monospace(format!("{:#x}: {val}", s.va));+ }+ }+ });+ if str_n > 5000 {+ ui.small(format!("Showing first 5000 of {str_n}"));}});- if str_n > 5000 {- ui.small(format!("Showing first 5000 of {str_n}"));- }- });});});}- // Analysis complete banner (top of frame content)+ // Analysis complete banner (top of frame content)if let Some(banner) = self.analysis_done_banner.clone() {- egui::TopBottomPanel::top("analysis_done_banner").show(ctx, |ui| {+ egui::TopBottomPanel::top("analysis_done_banner").show(ctx, |ui| {let t = m3_tokens(self.theme);let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);let ok = Color32::from_rgb(0x4C, 0xAF, 0x50);@@ -9154,10 +9834,10 @@ impl eframe::App for GhidrustApp {m3_icon(ui, M3Icon::CheckCircle, 18.0, ok);ui.label(egui::RichText::new(banner).color(primary).strong());ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {- if ui.button("Dismiss").clicked() {+ if ui.button("Dismiss").clicked() {self.analysis_done_banner = None;}- if ui.button("Open Overview").clicked() {+ if ui.button("Open Overview").clicked() {self.focus_center_tab(DockTab::Overview);self.analysis_done_banner = None;}@@ -9167,8 +9847,8 @@ impl eframe::App for GhidrustApp {}egui::CentralPanel::default().show(ctx, |ui| {- // `DockArea` and the tab viewer both need `&mut self` fields — take- // the dock tree out so the viewer can borrow the rest of the app.+ // `DockArea` and the tab viewer both need `&mut self` fields — take+ // the dock tree out so the viewer can borrow the rest of the app.let mut dock = std::mem::replace(&mut self.center_dock, DockState::new(vec![]));DockArea::new(&mut dock).style(DockStyle::from_egui(ui.style().as_ref()))@@ -9179,17 +9859,17 @@ impl eframe::App for GhidrustApp {self.sync_center_from_dock();});- // draw every open floating provider pane.+ // draw every open floating provider pane.self.draw_provider_panes(ctx);- // edit dialogs (rename / retype / comment / signature / new type).+ // edit dialogs (rename / retype / comment / signature / new type).self.draw_edit_dialogs(ctx);- // Configure plugins dialog.+ // Configure plugins dialog.if self.show_configure_dialog {let mut close = false;- egui::Window::new("Configure plugins")- .id(egui::Id::new("dialog_configure"))+ egui::Window::new("Configure plugins")+ .id(egui::Id::new("dialog_configure")).resizable(true).default_size(egui::vec2(680.0, 460.0)).show(ctx, |ui| {@@ -9198,17 +9878,17 @@ impl eframe::App for GhidrustApp {);ui.separator();egui::ScrollArea::vertical()- .id_salt("configure_scroll")+ .id_salt("configure_scroll").max_height(340.0).show(ui, |ui| {- egui::Grid::new("configure_grid")+ egui::Grid::new("configure_grid").num_columns(4).striped(true).show(ui, |ui| {- ui.strong("Plugin");- ui.strong("Kind");- ui.strong("State");- ui.strong("Description");+ ui.strong("Plugin");+ ui.strong("Kind");+ ui.strong("State");+ ui.strong("Description");ui.end_row();for p in layouts::PLUGIN_CATALOG {ui.monospace(p.name);@@ -9220,7 +9900,7 @@ impl eframe::App for GhidrustApp {});});ui.separator();- if ui.button("Close").clicked() {+ if ui.button("Close").clicked() {close = true;}});@@ -9229,36 +9909,36 @@ impl eframe::App for GhidrustApp {}}- // Layout save / load dialog.+ // Layout save / load dialog.if self.show_layouts_dialog {let mut close = false;let mut do_save = false;let mut load_name: Option<String> = None;let mut delete_name: Option<String> = None;- egui::Window::new("Tool Layouts")- .id(egui::Id::new("dialog_layouts"))+ egui::Window::new("Tool Layouts")+ .id(egui::Id::new("dialog_layouts")).resizable(true).default_size(egui::vec2(480.0, 360.0)).show(ctx, |ui| {- ui.label("Save / restore CodeBrowser tool layouts (pane visibility + docks).");+ ui.label("Save / restore CodeBrowser tool layouts (pane visibility + docks).");ui.small(egui::RichText::new(- "Files land under %APPDATA%/ghidrust/layouts/<name>.tool.json .",+ "Files land under %APPDATA%/ghidrust/layouts/<name>.tool.json .",).weak(),);ui.separator();ui.horizontal(|ui| {- ui.label("Name:");+ ui.label("Name:");ui.add(egui::TextEdit::singleline(&mut self.layouts_new_name).desired_width(200.0)- .hint_text("MyCodeBrowser"),+ .hint_text("MyCodeBrowser"),);if ui.add_enabled(!self.layouts_new_name.trim().is_empty(),- egui::Button::new("Save current layout"),+ egui::Button::new("Save current layout"),).clicked(){@@ -9266,21 +9946,21 @@ impl eframe::App for GhidrustApp {}});ui.separator();- ui.label(egui::RichText::new("Saved layouts").strong());+ ui.label(egui::RichText::new("Saved layouts").strong());if self.layouts_cached.is_empty() {- ui.weak("No layouts saved yet.");+ ui.weak("No layouts saved yet.");} else {egui::ScrollArea::vertical()- .id_salt("layouts_scroll")+ .id_salt("layouts_scroll").max_height(180.0).show(ui, |ui| {for name in &self.layouts_cached {ui.horizontal(|ui| {ui.monospace(name);- if ui.small_button("Restore").clicked() {+ if ui.small_button("Restore").clicked() {load_name = Some(name.clone());}- if ui.small_button("Delete").clicked() {+ if ui.small_button("Delete").clicked() {delete_name = Some(name.clone());}});@@ -9291,24 +9971,24 @@ impl eframe::App for GhidrustApp {if !self.current_layout_name.is_empty() {ui.small(egui::RichText::new(format!(- "Current layout: {}",+ "Current layout: {}",self.current_layout_name)).weak(),);}- if ui.button("Close").clicked() {+ if ui.button("Close").clicked() {close = true;}});if do_save {match self.save_layout_named(self.layouts_new_name.clone()) {Ok(p) => {- self.status = format!("Layout saved → {}", p.display());+ self.status = format!("Layout saved → {}", p.display());self.log(self.status.clone());}Err(e) => {- self.status = format!("save layout error: {e}");+ self.status = format!("save layout error: {e}");self.log_error(self.status.clone());}}@@ -9316,18 +9996,18 @@ impl eframe::App for GhidrustApp {if let Some(name) = load_name {match self.restore_layout_named(&name) {Ok(()) => {- self.status = format!("Layout restored → {name}");+ self.status = format!("Layout restored → {name}");self.log(self.status.clone());}Err(e) => {- self.status = format!("restore layout error: {e}");+ self.status = format!("restore layout error: {e}");self.log_error(self.status.clone());}}}if let Some(name) = delete_name {if let Err(e) = layouts::delete_layout(&name) {- self.status = format!("delete layout error: {e}");+ self.status = format!("delete layout error: {e}");self.log_error(self.status.clone());}self.layouts_cached = layouts::list_layouts();@@ -9337,33 +10017,33 @@ impl eframe::App for GhidrustApp {}}- // Bookmark add dialog+ // Bookmark add dialogif self.show_bookmark_dialog {let mut close = false;let mut confirmed = false;- egui::Window::new("Add Bookmark")- .id(egui::Id::new("dialog_add_bookmark"))+ egui::Window::new("Add Bookmark")+ .id(egui::Id::new("dialog_add_bookmark")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {- ui.label("Kind:");- egui::ComboBox::from_id_salt("bookmark_kind")+ ui.label("Kind:");+ egui::ComboBox::from_id_salt("bookmark_kind").selected_text(self.bookmark_dialog_kind.label()).show_ui(ui, |ui| {for k in BookmarkKind::ALL {ui.selectable_value(&mut self.bookmark_dialog_kind, *k, k.label());}});- ui.label("Category:");+ ui.label("Category:");ui.text_edit_singleline(&mut self.bookmark_dialog_category);- ui.label("Description:");+ ui.label("Description:");ui.text_edit_singleline(&mut self.bookmark_dialog_description);ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {close = true;}- if ui.button("Add").clicked() {+ if ui.button("Add").clicked() {confirmed = true;close = true;}@@ -9382,24 +10062,24 @@ impl eframe::App for GhidrustApp {}}- // Navigation → Go To Address+ // Navigation → Go To Addressif self.show_goto_dialog {- egui::Window::new("Go To Address")+ egui::Window::new("Go To Address").collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {- ui.label("Address (hex, optional 0x prefix):");+ ui.label("Address (hex, optional 0x prefix):");ui.text_edit_singleline(&mut self.goto_input);ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {self.show_goto_dialog = false;}- if ui.button("Go").clicked() {+ if ui.button("Go").clicked() {match self.goto_address_str(&self.goto_input.clone()) {Ok(()) => self.show_goto_dialog = false,Err(e) => {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}@@ -9408,26 +10088,26 @@ impl eframe::App for GhidrustApp {});}- // Search → Memory+ // Search → Memoryif self.show_search_memory_dialog {- egui::Window::new("Search Memory")+ egui::Window::new("Search Memory").collapsible(false).resizable(true).default_width(420.0).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {- ui.label("Byte pattern (hex; ?? = wildcard):");+ ui.label("Byte pattern (hex; ?? = wildcard):");ui.text_edit_singleline(&mut self.search_memory_input);- ui.small("Example: 55 48 89 e5 or 48??e5");+ ui.small("Example: 55 48 89 e5 or 48??e5");ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {self.show_search_memory_dialog = false;}- if ui.button("Search").clicked() {+ if ui.button("Search").clicked() {match self.run_search_memory() {Ok(()) => self.show_search_memory_dialog = false,Err(e) => {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}@@ -9436,26 +10116,26 @@ impl eframe::App for GhidrustApp {});}- // Search → Program Text+ // Search → Program Textif self.show_search_text_dialog {- egui::Window::new("Search Program Text")+ egui::Window::new("Search Program Text").collapsible(false).resizable(true).default_width(420.0).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {- ui.label("Query (listing / symbols / functions / memory text):");+ ui.label("Query (listing / symbols / functions / memory text):");ui.text_edit_singleline(&mut self.search_text_input);- ui.checkbox(&mut self.search_text_case_insensitive, "Case insensitive");+ ui.checkbox(&mut self.search_text_case_insensitive, "Case insensitive");ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {self.show_search_text_dialog = false;}- if ui.button("Search").clicked() {+ if ui.button("Search").clicked() {match self.run_search_text() {Ok(()) => self.show_search_text_dialog = false,Err(e) => {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}@@ -9464,31 +10144,31 @@ impl eframe::App for GhidrustApp {});}- // Search → For Scalars+ // Search → For Scalarsif self.show_search_scalars_dialog {- egui::Window::new("Search For Scalars")+ egui::Window::new("Search For Scalars").collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {- ui.label("Scan operand scalars in [min, max]. Hex ok (0x…) or decimal.");+ ui.label("Scan operand scalars in [min, max]. Hex ok (0x…) or decimal.");ui.horizontal(|ui| {- ui.label("Min:");+ ui.label("Min:");ui.text_edit_singleline(&mut self.search_scalars_min);});ui.horizontal(|ui| {- ui.label("Max:");+ ui.label("Max:");ui.text_edit_singleline(&mut self.search_scalars_max);});ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {self.show_search_scalars_dialog = false;}- if ui.button("Search").clicked() {+ if ui.button("Search").clicked() {match self.run_search_scalars() {Ok(()) => self.show_search_scalars_dialog = false,Err(e) => {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());}}@@ -9497,32 +10177,32 @@ impl eframe::App for GhidrustApp {});}- // Search → Instruction Patterns+ // Search → Instruction Patternsif self.show_search_insn_dialog {- egui::Window::new("Search Instruction Patterns")+ egui::Window::new("Search Instruction Patterns").collapsible(false).resizable(true).default_width(420.0).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {- ui.small("Matches against decoded listing rows. Empty field = don't filter.");+ ui.small("Matches against decoded listing rows. Empty field = don't filter.");ui.horizontal(|ui| {- ui.label("Mnemonic:");+ ui.label("Mnemonic:");ui.text_edit_singleline(&mut self.search_insn_mnemonic);});ui.horizontal(|ui| {- ui.label("Operands:");+ ui.label("Operands:");ui.text_edit_singleline(&mut self.search_insn_operands);});ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {self.show_search_insn_dialog = false;}- if ui.button("Search").clicked() {+ if ui.button("Search").clicked() {match self.run_search_instruction_patterns() {Ok(()) => self.show_search_insn_dialog = false,Err(e) => {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());}}@@ -9531,45 +10211,46 @@ impl eframe::App for GhidrustApp {});}- // Add Equate dialog .+ // Add Equate dialog .if self.show_equate_dialog {let mut close = false;- egui::Window::new("Set Equate")+ egui::Window::new("Set Equate").collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {- ui.small("Bind a name to a scalar operand .");+ ui.small("Bind a name to a scalar operand .");ui.horizontal(|ui| {- ui.label("VA:");+ ui.label("VA:");let mut input = self.equate_dialog_va- .map(|v| format!("{v:#x}"))+ .map(|v| format!("{v:#x}")).unwrap_or_default();if ui.text_edit_singleline(&mut input).lost_focus() {self.equate_dialog_va = parse_address(&input).ok();}});ui.horizontal(|ui| {- ui.label("Operand index:");- let mut s = format!("{}", self.equate_dialog_op);+ ui.label("Operand index:");+ let mut s = format!("{}", self.equate_dialog_op);if ui.text_edit_singleline(&mut s).lost_focus() {- self.equate_dialog_op = s.trim().parse().unwrap_or(self.equate_dialog_op);+ self.equate_dialog_op =+ s.trim().parse().unwrap_or(self.equate_dialog_op);}});ui.horizontal(|ui| {- ui.label("Name:");+ ui.label("Name:");ui.text_edit_singleline(&mut self.equate_dialog_name);});ui.horizontal(|ui| {- ui.label("Value (dec / hex):");+ ui.label("Value (dec / hex):");ui.text_edit_singleline(&mut self.equate_dialog_value);});ui.horizontal(|ui| {- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {close = true;}- if ui.button("Apply").clicked() {+ if ui.button("Apply").clicked() {let value = self.parse_scalar_input(&self.equate_dialog_value.clone()).unwrap_or(0);@@ -9580,7 +10261,7 @@ impl eframe::App for GhidrustApp {self.equate_dialog_name.clone(),value,) {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log_error(self.status.clone());} else {close = true;@@ -9596,46 +10277,49 @@ impl eframe::App for GhidrustApp {}}- // Search results window+ // Search results windowif self.show_search_results {- egui::Window::new("Search Results")+ egui::Window::new("Search Results").collapsible(true).resizable(true).default_width(480.0).default_height(280.0).show(ctx, |ui| {- if ui.button("Close").clicked() {+ if ui.button("Close").clicked() {self.show_search_results = false;}ui.separator();egui::ScrollArea::vertical().show(ui, |ui| {for h in self.memory_hits.clone() {if ui- .button(format!("{:#x} {} +{:#x}", h.va, h.block, h.offset_in_block))+ .button(format!(+ "{:#x} {} +{:#x}",+ h.va, h.block, h.offset_in_block+ )).clicked(){- let _ = self.goto_address_str(&format!("{:#x}", h.va));+ let _ = self.goto_address_str(&format!("{:#x}", h.va));}}for h in self.text_hits.clone() {let label = match h.va {- Some(va) => format!("[{}] {:#x}: {}", h.kind, va, h.text),- None => format!("[{}] {}", h.kind, h.text),+ Some(va) => format!("[{}] {:#x}: {}", h.kind, va, h.text),+ None => format!("[{}] {}", h.kind, h.text),};if ui.button(label).clicked() {if let Some(va) = h.va {- let _ = self.goto_address_str(&format!("{va:#x}"));+ let _ = self.goto_address_str(&format!("{va:#x}"));}}}if self.memory_hits.is_empty() && self.text_hits.is_empty() {- ui.weak("No hits.");+ ui.weak("No hits.");}});});}- // Listing → Decode options+ // Listing → Decode optionsif ui_options_dialog(ctx,&mut self.show_decode_options_dialog,@@ -9645,9 +10329,9 @@ impl eframe::App for GhidrustApp {self.apply_decode_opts();}- // Tools → Processor options+ // Tools → Processor optionsif self.show_processor_dialog {- egui::Window::new("Processor Options")+ egui::Window::new("Processor Options").collapsible(false).resizable(true).default_width(440.0)@@ -9655,40 +10339,42 @@ impl eframe::App for GhidrustApp {.show(ctx, |ui| {if let Some(prog) = &self.program {let info = processor_info(prog);- ui.monospace(format!("Language: {}", info.language));- ui.monospace(format!("Compiler: {}", info.compiler));- ui.monospace(format!("Format: {}", info.format));- ui.monospace(format!("Endian: {}", info.endian));- ui.monospace(format!("Pointer size: {} bytes", info.pointer_size));- ui.monospace(format!("Image base: {:#x}", info.image_base));+ ui.monospace(format!("Language: {}", info.language));+ ui.monospace(format!("Compiler: {}", info.compiler));+ ui.monospace(format!("Format: {}", info.format));+ ui.monospace(format!("Endian: {}", info.endian));+ ui.monospace(format!("Pointer size: {} bytes", info.pointer_size));+ ui.monospace(format!("Image base: {:#x}", info.image_base));ui.monospace(format!(- "Entry: {}",+ "Entry: {}",info.entry- .map(|e| format!("{e:#x}"))- .unwrap_or_else(|| "—".into())+ .map(|e| format!("{e:#x}"))+ .unwrap_or_else(|| "—".into())));ui.separator();ui.small(&info.notes);ui.separator();- ui.label("Sections:");- egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| {- for s in &prog.sections {- ui.monospace(format!(- "{} va={:#x} vsize={:#x}",- s.name, s.va, s.virtual_size- ));- }- });+ ui.label("Sections:");+ egui::ScrollArea::vertical()+ .max_height(160.0)+ .show(ui, |ui| {+ for s in &prog.sections {+ ui.monospace(format!(+ "{} va={:#x} vsize={:#x}",+ s.name, s.va, s.virtual_size+ ));+ }+ });} else {- ui.weak("Load a program to view processor / language options.");+ ui.weak("Load a program to view processor / language options.");}- if ui.button("Close").clicked() {+ if ui.button("Close").clicked() {self.show_processor_dialog = false;}});}- // Analysis → GPU Decompile…+ // Analysis → GPU Decompile…if self.show_gpu_decompile_dialog {let t = m3_tokens(self.theme);let muted = Color32::from_rgb(@@ -9699,7 +10385,7 @@ impl eframe::App for GhidrustApp {let mut close = false;let mut run_clicked = false;let has_program = self.program.is_some();- egui::Window::new("GPU Decompile")+ egui::Window::new("GPU Decompile").collapsible(false).resizable(true).default_width(560.0)@@ -9711,8 +10397,8 @@ impl eframe::App for GhidrustApp {muted,);if !has_program {- ui.weak("No program loaded.");- } else if ui.button("Resolve + Decompile").clicked() {+ ui.weak("No program loaded.");+ } else if ui.button("Resolve + Decompile").clicked() {run_clicked = true;}tool_panes::ui_gpu_decompile_dialog_result(@@ -9721,7 +10407,7 @@ impl eframe::App for GhidrustApp {muted,);ui.separator();- if ui.button("Close").clicked() {+ if ui.button("Close").clicked() {close = true;}});@@ -9736,7 +10422,7 @@ impl eframe::App for GhidrustApp {if self.show_analysis_dialog && self.analysis_job.is_none() {let t = m3_tokens(self.theme);let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);- egui::Window::new("Analysis options")+ egui::Window::new("Analysis options").collapsible(false).resizable(true).default_width(460.0)@@ -9750,58 +10436,60 @@ impl eframe::App for GhidrustApp {.map(|f| f.display_name.as_str()).unwrap_or(id.as_str());ui.label(- egui::RichText::new(format!("Target: {name}"))+ egui::RichText::new(format!("Target: {name}")).strong().color(primary),);ui.add_space(4.0);}- ui.label("Select analyzers (labels):");+ ui.label("Select analyzers (labels):");ui.horizontal(|ui| {- if ui.small_button("Select defaults").clicked() {+ if ui.small_button("Select defaults").clicked() {for (i, info) in self.analyzer_infos.iter().enumerate() {self.analyzer_enabled[i] = info.default_enabled;}}- if ui.small_button("Select all").clicked() {+ if ui.small_button("Select all").clicked() {for e in &mut self.analyzer_enabled {- *e = true;+ *e = true;}}- if ui.small_button("Clear all").clicked() {+ if ui.small_button("Clear all").clicked() {for e in &mut self.analyzer_enabled {- *e = false;+ *e = false;}}});- egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {- for (i, info) in self.analyzer_infos.iter().enumerate() {- ui.horizontal(|ui| {- ui.checkbox(&mut self.analyzer_enabled[i], &info.name);- match info.status {- ghidrust_core::AnalyzerStatus::Implemented => {- ui.weak("ready");- }- ghidrust_core::AnalyzerStatus::NotImplemented => {- ui.weak("stub");+ egui::ScrollArea::vertical()+ .max_height(320.0)+ .show(ui, |ui| {+ for (i, info) in self.analyzer_infos.iter().enumerate() {+ ui.horizontal(|ui| {+ ui.checkbox(&mut self.analyzer_enabled[i], &info.name);+ match info.status {+ ghidrust_core::AnalyzerStatus::Implemented => {+ ui.weak("ready");+ }+ ghidrust_core::AnalyzerStatus::NotImplemented => {+ ui.weak("stub");+ }}- }- // Per-row GPU indicator (master checkbox gates actual use).- let supports = analyzer_supports_gpu(&info.name);- if supports && self.use_gpu_experimental {- ui.label(- egui::RichText::new("GPU")- .small()- .strong()- .color(primary),- )- .on_hover_text(- "Master GPU is on — this analyzer will use its GPU \+ // Per-row GPU indicator (master checkbox gates actual use).+ let supports = analyzer_supports_gpu(&info.name);+ if supports && self.use_gpu_experimental {+ ui.label(+ egui::RichText::new("GPU")+ .small()+ .strong()+ .color(primary),+ )+ .on_hover_text(+ "Master GPU is on — this analyzer will use its GPU \strategy (bulk and/or seed enrich). Falls back to CPU \on failure.",- );- } else if supports {- ui.label(+ );+ } else if supports {+ ui.label(egui::RichText::new("GPU").small().color(Color32::from_rgb(120, 120, 128)),@@ -9810,8 +10498,8 @@ impl eframe::App for GhidrustApp {"GPU strategy available — enable the master GPU checkbox \to use it. Currently CPU.",);- } else {- ui.label(+ } else {+ ui.label(egui::RichText::new("CPU only").small().color(Color32::from_rgb(120, 120, 128)),@@ -9819,17 +10507,17 @@ impl eframe::App for GhidrustApp {.on_hover_text("No GPU strategy for this analyzer — always runs on CPU.",);- }- });- }- });+ }+ });+ }+ });ui.separator();ui.checkbox(&mut self.use_gpu_experimental,- "GPU (only analyzers with a GPU strategy)",+ "GPU (only analyzers with a GPU strategy)",);ui.small(- "wgpu when available: GPU bulk / SIMT seed enrich only for analyzers \+ "wgpu when available: GPU bulk / SIMT seed enrich only for analyzers \marked GPU above (see strategy matrix). Others stay CPU-only. \Large images are multi-dispatch chunked (≤65535 workgroups). \Falls back to CPU on failure. GPU decompile is a separate tool.",@@ -9839,7 +10527,7 @@ impl eframe::App for GhidrustApp {let can_run = self.analyzer_enabled.iter().any(|e| *e)&& (self.program.is_some() || self.pending_analyze_file_id.is_some());if ui- .add_enabled(can_run, egui::Button::new("Run Analysis"))+ .add_enabled(can_run, egui::Button::new("Run Analysis")).clicked(){match self.begin_analysis_job() {@@ -9847,12 +10535,12 @@ impl eframe::App for GhidrustApp {self.show_analysis_dialog = false;}Err(e) => {- self.status = format!("error: {e}");+ self.status = format!("error: {e}");self.log(self.status.clone());}}}- if ui.button("Cancel").clicked() {+ if ui.button("Cancel").clicked() {self.pending_analyze_file_id = None;self.show_analysis_dialog = false;}@@ -9860,7 +10548,7 @@ impl eframe::App for GhidrustApp {});}- // Floating M3 progress card while analysis runs+ // Floating M3 progress card while analysis runsif let Some(frac) = self.analysis_progress_fraction() {let t = m3_tokens(self.theme);let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);@@ -9871,7 +10559,7 @@ impl eframe::App for GhidrustApp {t.surface_container[2],).gamma_multiply(1.4);- egui::Window::new("Analysis progress")+ egui::Window::new("Analysis progress").collapsible(false).resizable(false).anchor(egui::Align2::CENTER_BOTTOM, [0.0, -48.0])@@ -9885,21 +10573,21 @@ impl eframe::App for GhidrustApp {.names.get(job.index).map(|s| s.as_str())- .unwrap_or("finishing…");+ .unwrap_or("finishing…");ui.label(- egui::RichText::new(format!("{} — {step}/{n}", job.file_label))+ egui::RichText::new(format!("{} — {step}/{n}", job.file_label)).color(on_surface).strong(),);ui.label(egui::RichText::new(cur).color(primary).small());if job.use_gpu {- ui.small("GPU experimental bulk path enabled");+ ui.small("GPU experimental bulk path enabled");}}ui.add_space(6.0);m3_linear_progress(ui, frac, primary, track);ui.add_space(2.0);- ui.small(format!("{:.0}%", frac * 100.0));+ ui.small(format!("{:.0}%", frac * 100.0));});}}@@ -9913,135 +10601,137 @@ mod tests {#[test]fn shell_has_required_menus_and_panes() {let menus = GhidrustApp::shell_menus();- // top-level menus (from `docking.tool.ToolConstants`).+ // top-level menus (from `docking.tool.ToolConstants`).for m in [- "File",- "Edit",- "Analysis",- "Navigation",- "Search",- "Select",- "Tools",- "Graph",- "Window",- "Help",+ "File",+ "Edit",+ "Analysis",+ "Navigation",+ "Search",+ "Select",+ "Tools",+ "Graph",+ "Window",+ "Help",] {- assert!(menus.contains(&m), "missing menu {m}");+ assert!(menus.contains(&m), "missing menu {m}");}let panes = GhidrustApp::shell_panes();for p in [- "Project Tree",- "Program Tree",- "Symbol Tree",- "Overview",- "Listing",- "Decompiler",- "Console",+ "Project Tree",+ "Program Tree",+ "Symbol Tree",+ "Overview",+ "Listing",+ "Decompiler",+ "Console",] {- assert!(panes.contains(&p), "missing pane {p}");+ assert!(panes.contains(&p), "missing pane {p}");}- // Project Tree ≠ Program Tree+ // Project Tree ≠ Program Treeassert_ne!(- panes.iter().position(|p| *p == "Project Tree"),- panes.iter().position(|p| *p == "Program Tree")+ panes.iter().position(|p| *p == "Project Tree"),+ panes.iter().position(|p| *p == "Program Tree"));}- /// every provider must be enumerated in- /// `shell_panes` so the Window menu / structural tests can enforce provider visibility.+ /// every provider must be enumerated in+ /// `shell_panes` so the Window menu / structural tests can enforce provider visibility.#[test]fn shell_panes_enumerates_full_codebrowser_catalog() {let panes = GhidrustApp::shell_panes();- // 28 default `.tool` providers + a few off-layout ones. See- // internal UI notes § 1.1 / § 1.2 for the source of truth.+ // 28 default `.tool` providers + a few off-layout ones. See+ // internal UI notes § 1.1 / § 1.2 for the source of truth.for expected in [- "Program Trees",- "Symbol Tree",- "Data Type Manager",- "Listing",- "Decompile",- "Bytes",- "Defined Data",- "Defined Strings",- "Equates Table",- "External Programs",- "Functions",- "Relocation Table",- "Data Type Preview",- "Disassembled View",- "Console",- "Bookmarks",- "Script Manager",- "Memory Map",- "Function Graph",- "Register Manager",- "Symbol Table",- "Symbol References",- "Checksum Generator",- "Function Tags",- "Comments",- "Python",- "Entropy",- "Overview",- // Off-layout, reached via Window menu- "Function Call Trees",- "Function Call Graph",- "Text Editor",+ "Program Trees",+ "Symbol Tree",+ "Data Type Manager",+ "Listing",+ "Decompile",+ "Bytes",+ "Defined Data",+ "Defined Strings",+ "Equates Table",+ "External Programs",+ "Functions",+ "Relocation Table",+ "Data Type Preview",+ "Disassembled View",+ "Console",+ "Bookmarks",+ "Script Manager",+ "Memory Map",+ "Function Graph",+ "Register Manager",+ "Symbol Table",+ "Symbol References",+ "Checksum Generator",+ "Function Tags",+ "Comments",+ "Python",+ "Entropy",+ "Overview",+ // Off-layout, reached via Window menu+ "Function Call Trees",+ "Function Call Graph",+ "Text Editor",] {assert!(panes.contains(&expected),- "missing provider `{expected}` in shell_panes; full list = {panes:?}"+ "missing provider `{expected}` in shell_panes; full list = {panes:?}");}}- /// Back / Forward history is wired.+ /// Back / Forward history is wired.#[test]fn nav_history_records_and_navigates() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");assert!(!app.can_nav_back());assert!(!app.can_nav_forward());- // Two goto calls (both valid VAs inside the loaded listing window)- // put one entry in the Back history.+ // Two goto calls (both valid VAs inside the loaded listing window)+ // put one entry in the Back history.let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();- // A second VA that is inside the loaded listing so re-disassemble isn't required.+ // A second VA that is inside the loaded listing so re-disassemble isn't required.let second_va = app.listing.iter().map(|i| i.address).find(|&va| va > entry).unwrap_or(entry + 1);- app.goto_address_str(&format!("{entry:#x}")).expect("goto entry");- app.goto_address_str(&format!("{second_va:#x}")).expect("goto second");- assert!(app.can_nav_back, "back should be available after 2 gotos");+ app.goto_address_str(&format!("{entry:#x}"))+ .expect("goto entry");+ app.goto_address_str(&format!("{second_va:#x}"))+ .expect("goto second");+ assert!(app.can_nav_back, "back should be available after 2 gotos");assert!(!app.can_nav_forward());- // Back → returns to entry- assert!(app.nav_back, "nav_back should succeed");+ // Back → returns to entry+ assert!(app.nav_back, "nav_back should succeed");assert_eq!(app.listing_focus_va, Some(entry));assert!(app.can_nav_forward());- // Forward → returns to second_va- assert!(app.nav_forward, "nav_forward should succeed");+ // Forward → returns to second_va+ assert!(app.nav_forward, "nav_forward should succeed");assert_eq!(app.listing_focus_va, Some(second_va));}- /// Bookmarks pane model is real (5 kinds; add/delete flow).+ /// Bookmarks pane model is real (5 kinds; add/delete flow).#[test]fn bookmark_model_add_delete_and_nav() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");assert!(app.bookmarks.is_empty());let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();- app.add_bookmark(entry, BookmarkKind::Note, "user", "entry point");- app.add_bookmark(entry + 0x10, BookmarkKind::Analysis, "core", "hot loop");+ app.add_bookmark(entry, BookmarkKind::Note, "user", "entry point");+ app.add_bookmark(entry + 0x10, BookmarkKind::Analysis, "core", "hot loop");assert_eq!(app.bookmarks.len(), 2);assert!(app.is_pane_open(PaneKind::Bookmarks));- // Next / Prev bookmark navigation works.+ // Next / Prev bookmark navigation works.app.listing_focus_va = Some(entry);app.nav_next_bookmark();assert_eq!(app.listing_focus_va, Some(entry + 0x10));@@ -10052,35 +10742,36 @@ mod tests {assert_eq!(app.bookmarks.len(), 1);assert_eq!(app.bookmarks[0].va, entry + 0x10);- // All 5 bookmark kinds are colourable.+ // All 5 bookmark kinds are colourable.for k in BookmarkKind::ALL {let c = k.color();assert!(c.a() > 0 && (c.r() as u16 + c.g() as u16 + c.b() as u16) > 0);}}- /// plugin event bus emits CursorMoved on goto and Mutation on bookmark ops.+ /// plugin event bus emits CursorMoved on goto and Mutation on bookmark ops.#[test]fn event_bus_publishes_cursor_and_mutation_events() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");- // Loading emits ProgramActivated; drain baseline.+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ // Loading emits ProgramActivated; drain baseline.let boot = app.drain_events();assert!(- boot.iter().any(|e| matches!(e, GhidrustEvent::ProgramActivated { .. })),- "load_binary must publish ProgramActivated: {boot:?}"+ boot.iter()+ .any(|e| matches!(e, GhidrustEvent::ProgramActivated { .. })),+ "load_binary must publish ProgramActivated: {boot:?}");let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();- app.goto_address_str(&format!("{entry:#x}")).expect("goto");+ app.goto_address_str(&format!("{entry:#x}")).expect("goto");let evs = app.drain_events();assert!(evs.iter().any(|e| matches!(e, GhidrustEvent::CursorMoved { .. })),- "goto_address_str must publish CursorMoved: {evs:?}"+ "goto_address_str must publish CursorMoved: {evs:?}");- app.add_bookmark(entry, BookmarkKind::Note, "test", "hi");+ app.add_bookmark(entry, BookmarkKind::Note, "test", "hi");let evs = app.drain_events();assert!(evs.iter().any(|e| matches!(@@ -10089,7 +10780,7 @@ mod tests {kind: MutationKind::BookmarkAdded { .. }})),- "add_bookmark must publish BookmarkAdded: {evs:?}"+ "add_bookmark must publish BookmarkAdded: {evs:?}");app.delete_bookmark(0);@@ -10101,19 +10792,23 @@ mod tests {kind: MutationKind::BookmarkRemoved { .. }})),- "delete_bookmark must publish BookmarkRemoved: {evs:?}"+ "delete_bookmark must publish BookmarkRemoved: {evs:?}");- // Drain again → empty.+ // Drain again → empty.assert!(app.drain_events().is_empty());}- /// provider pane toggles are per-kind and persist through frames.+ /// provider pane toggles are per-kind and persist through frames.#[test]fn toggle_pane_state_persists() {let mut app = GhidrustApp::headless();for k in PaneKind::ALL {- assert!(!app.is_pane_open(*k), "pane {:?} default should be closed", k);+ assert!(+ !app.is_pane_open(*k),+ "pane {:?} default should be closed",+ k+ );}app.toggle_pane(PaneKind::MemoryMap, true);app.toggle_pane(PaneKind::SymbolTable, true);@@ -10126,77 +10821,88 @@ mod tests {#[test]fn project_tree_open_and_status_via_shipped_apis() {- let dir = std::env::temp_dir().join(format!(- "ghidrust_ptree_{}",- std::process::id()- ));+ let dir = std::env::temp_dir().join(format!("ghidrust_ptree_{}", std::process::id()));let _ = std::fs::remove_dir_all(&dir);let mut app = GhidrustApp::headless();app.project_dir_input = dir.display().to_string();- app.project_name_input = "TreeUX".into();- app.create_project.expect("create");+ app.project_name_input = "TreeUX".into();+ app.create_project.expect("create");assert!(app.show_project_tree);- app.path_input = fixture_path("tiny_x64.pe").display.to_string();- app.import_into_project.expect("import tiny");- app.path_input = fixture_path("analysis_lab.pe").display.to_string();- app.import_into_project.expect("import lab");+ app.path_input = fixture_path("tiny_x64.pe").display.to_string();+ app.import_into_project.expect("import tiny");+ app.path_input = fixture_path("analysis_lab.pe").display.to_string();+ app.import_into_project.expect("import lab");- let tree = app.project_tree_model.expect("tree model");- assert_eq!(tree.project_name, "TreeUX");+ let tree = app.project_tree_model.expect("tree model");+ assert_eq!(tree.project_name, "TreeUX");assert_eq!(tree.files.len(), 2);assert!(tree.files.iter().any(|f| f.active));assert!(tree.files.iter().all(|f| !f.has_saved_analysis));- assert_eq!(tree.files[0].status_label, "Not analyzed");+ assert_eq!(tree.files[0].status_label, "Not analyzed");let lab_id = tree.files.iter()- .find(|f| f.display_name.contains("analysis_lab"))+ .find(|f| f.display_name.contains("analysis_lab")).map(|f| f.id.clone())- .expect("lab id");- app.open_from_tree(&lab_id).expect("open from tree");+ .expect("lab id");+ app.open_from_tree(&lab_id).expect("open from tree");assert_eq!(app.active_file_id.as_deref(), Some(lab_id.as_str()));assert!(app.program.is_some());let tree2 = app.project_tree_model().unwrap();assert!(tree2.files.iter().any(|f| f.id == lab_id && f.active));for (i, info) in app.analyzer_infos.iter().enumerate() {- app.analyzer_enabled[i] =- matches!(info.name().as_str(), "Function Start Search" | "Embedded Media");+ app.analyzer_enabled[i] = matches!(+ info.name().as_str(),+ "Function Start Search" | "Embedded Media"+ );}- // Analyze from tree opens options dialog (does not run yet).- app.analyze_from_tree(&lab_id).expect("open analyze options");+ // Analyze from tree opens options dialog (does not run yet).+ app.analyze_from_tree(&lab_id)+ .expect("open analyze options");assert!(app.show_analysis_dialog);- assert_eq!(app.pending_analyze_file_id.as_deref(), Some(lab_id.as_str()));+ assert_eq!(+ app.pending_analyze_file_id.as_deref(),+ Some(lab_id.as_str())+ );app.use_gpu_experimental = true;- app.begin_analysis_job.expect("begin");+ app.begin_analysis_job.expect("begin");assert!(app.analysis_job.is_some());assert!(app.analysis_progress_fraction().is_some());while app.analysis_job.is_some() {- app.step_analysis_job_blocking.expect("step");+ app.step_analysis_job_blocking.expect("step");}assert!(app.analysis_progress_fraction().is_none());let tree3 = app.project_tree_model().unwrap();let lab_row = tree3.files.iter().find(|f| f.id == lab_id).unwrap();- assert!(lab_row.has_saved_analysis, "{lab_row:?}");- assert_eq!(lab_row.status_label, "Analyzed");+ assert!(lab_row.has_saved_analysis, "{lab_row:?}");+ assert_eq!(lab_row.status_label, "Analyzed");- // Second run of status query consistent+ // Second run of status query consistentlet tree4 = app.project_tree_model().unwrap();assert_eq!(- tree3.files.iter().map(|f| f.has_saved_analysis).collect::<Vec<_>>(),- tree4.files.iter().map(|f| f.has_saved_analysis).collect::<Vec<_>>()+ tree3+ .files+ .iter()+ .map(|f| f.has_saved_analysis)+ .collect::<Vec<_>>(),+ tree4+ .files+ .iter()+ .map(|f| f.has_saved_analysis)+ .collect::<Vec<_>>());- // Delete requires confirm: request only sets pending; confirm removes.+ // Delete requires confirm: request only sets pending; confirm removes.app.request_delete_file(&lab_id);assert!(app.pending_delete.is_some());app.cancel_delete_file();assert!(app.pending_delete.is_none());assert_eq!(app.project_tree_model().unwrap().files.len(), 2);app.request_delete_file(&lab_id);- app.confirm_delete_file.expect("confirm delete");+ app.confirm_delete_file.expect("confirm delete");assert!(app.pending_delete.is_none());let after = app.project_tree_model().unwrap();assert_eq!(after.files.len(), 1);@@ -10212,44 +10918,47 @@ mod tests {app.theme = app.theme.toggle();assert_eq!(app.theme, ThemeMode::Light);- let pe = fixture_path("tiny_x64.pe");- app.load_binary(&pe).expect("load");- assert!(app.listing.iter().any(|i| i.mnemonic == "push"));+ let pe = fixture_path("tiny_x64.pe");+ app.load_binary(&pe).expect("load");+ assert!(app.listing.iter().any(|i| i.mnemonic == "push"));for (i, info) in app.analyzer_infos.iter().enumerate() {app.analyzer_enabled[i] = matches!(info.name().as_str(),- "ASCII Strings" | "WindowsPE x86 PE RTTI Analyzer"+ "ASCII Strings" | "WindowsPE x86 PE RTTI Analyzer");}- app.run_selected_analysis.expect("analyze");- assert!(app.rtti.classes.iter().any(|c| c.name() == "Widget"));+ app.run_selected_analysis.expect("analyze");+ assert!(app.rtti.classes.iter().any(|c| c.name() == "Widget"));assert!(!app.strings.is_empty());assert_eq!(app.analyzer_infos.len(), ANALYZER_NAMES.len());}#[test]fn headless_stage0_decompiler_wires_on_focus() {- // Stage-1 is the GUI default. The old assertion demanded a- // Stage-0-style `void foo` / `block_N` marker; Stage-1 emits typed- // return values (e.g. `uint32_t FUN_..(void)`) so we accept either- // stage marker plus the Stage-1 self-identification header.+ // Stage-1 is the GUI default. The old assertion demanded a+ // Stage-0-style `void foo` / `block_N` marker; Stage-1 emits typed+ // return values (e.g. `uint32_t FUN_..(void)`) so we accept either+ // stage marker plus the Stage-1 self-identification header.let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");- assert!(!app.decomp_text.is_empty(), "load should seed decompiler text");- assert!(!app.decomp_text.contains("Not yet implemented"));+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ assert!(+ !app.decomp_text.is_empty(),+ "load should seed decompiler text"+ );+ assert!(!app.decomp_text.contains("Not yet implemented"));let va = app.listing[0].address;app.refresh_decompiler_at(va);assert!(app.decomp_entry.is_some());let text = &app.decomp_text;assert!(- text.contains("void ")- || text.contains("uint")- || text.contains("int32_t")- || text.contains("int64_t")- || text.contains("block_"),- "expected typed function header or block label:\n{text}"+ text.contains("void ")+ || text.contains("uint")+ || text.contains("int32_t")+ || text.contains("int64_t")+ || text.contains("block_"),+ "expected typed function header or block label:\n{text}");let entry = app.decomp_entry.unwrap();@@ -10261,107 +10970,111 @@ mod tests {#[test]fn headless_project_import_analyze_save() {- let dir = std::env::temp_dir().join(format!("ghidrust_gui_proj_{}", std::process::id));+ let dir = std::env::temp_dir().join(format!("ghidrust_gui_proj_{}", std::process::id));let _ = std::fs::remove_dir_all(&dir);let mut app = GhidrustApp::headless();app.project_dir_input = dir.display().to_string();- app.project_name_input = "GuiTest".into();- app.create_project.expect("create");- app.path_input = fixture_path("analysis_lab.pe").display.to_string();- app.import_into_project.expect("import");+ app.project_name_input = "GuiTest".into();+ app.create_project.expect("create");+ app.path_input = fixture_path("analysis_lab.pe").display.to_string();+ app.import_into_project.expect("import");assert!(app.program.is_some());for (i, info) in app.analyzer_infos.iter().enumerate() {- app.analyzer_enabled[i] =- matches!(info.name().as_str(), "Function Start Search" | "Embedded Media");+ app.analyzer_enabled[i] = matches!(+ info.name().as_str(),+ "Function Start Search" | "Embedded Media"+ );}- app.run_selected_analysis.expect("analyze");- app.save_results.expect("save");+ app.run_selected_analysis.expect("analyze");+ app.save_results.expect("save");let id = app.active_file_id.clone().unwrap();let proj = app.project.as_ref().unwrap();assert!(proj.analysis_path(&id).is_file());assert!(proj.listing_export_path(&id).is_file());- // reopen+ // reopenlet mut app2 = GhidrustApp::headless();app2.project_dir_input = dir.display().to_string();- app2.open_project.expect("reopen");+ app2.open_project.expect("reopen");assert!(app2.program.is_some());let _ = std::fs::remove_dir_all(&dir);}#[test]fn source_embeds_m3_and_menus() {- // Structural: shipped source contains theme toggle + menus (fallback evidence).- let src = include_str!("main.rs");- assert!(src.contains("Theme: Dark") || src.contains("ThemeMode"));- assert!(src.contains("menu_button(\"File\""));- assert!(src.contains("Program Tree"));- assert!(src.contains("Project Tree") || src.contains("project_tree"));- assert!(src.contains("Decompiler"));- assert!(src.contains("refresh_decompiler_at") || src.contains("stage0_pseudo_c"));- assert!(src.contains("focus_function"));- assert!(src.contains("Stage-0"));- assert!(src.contains("decomp_scroll") || src.contains("decomp_text"));- assert!(src.contains("ASCII Strings"));- assert!(src.contains("Analyzed") || src.contains("has_saved_analysis"));- assert!(src.contains("analyze_from_tree") || src.contains("small_button(\"Analyze\")"));- assert!(src.contains("Browse") || src.contains("browse_binary_path") || src.contains("rfd::"));- assert!(src.contains("pending_delete") || src.contains("Delete from project"));- assert!(src.contains("use_gpu_experimental") || src.contains("GPU experimental"));- assert!(src.contains("analyzer_supports_gpu"));- assert!(src.contains("CPU only") || src.contains("\"GPU\""));- assert!(src.contains("m3_linear_progress") || src.contains("Analysis progress"));- assert!(src.contains("begin_analysis_job") || src.contains("Run Analysis"));- assert!(src.contains("Overview") || src.contains("ui_overview"));- assert!(src.contains("show_rows") || src.contains("rtti_filtered_idx"));- assert!(src.contains("analysis_done_banner") || src.contains("Analysis complete"));- assert!(src.contains("double_clicked") && src.contains("open_id"));- assert!(src.contains("show_startup_picker") || src.contains("ui_startup_picker"));- assert!(src.contains("recent_projects") || src.contains("Open existing project"));- // No emoji codepoints in this file (Material geometry lives in icons.rs)- // U+1F4C1 folder, U+25CF/U+25CB bullets, U+25B6 play — use escapes so the- // forbidden glyphs themselves never appear in source.- assert!(!src.contains('\u{1F4C1}'));- assert!(!src.contains('\u{25CF}'));- assert!(!src.contains('\u{25CB}'));- assert!(!src.contains('\u{25B6}'));+ // Structural: shipped source contains theme toggle + menus (fallback evidence).+ let src = include_str!("main.rs");+ assert!(src.contains("Theme: Dark") || src.contains("ThemeMode"));+ assert!(src.contains("menu_button(\"File\""));+ assert!(src.contains("Program Tree"));+ assert!(src.contains("Project Tree") || src.contains("project_tree"));+ assert!(src.contains("Decompiler"));+ assert!(src.contains("refresh_decompiler_at") || src.contains("stage0_pseudo_c"));+ assert!(src.contains("focus_function"));+ assert!(src.contains("Stage-0"));+ assert!(src.contains("decomp_scroll") || src.contains("decomp_text"));+ assert!(src.contains("ASCII Strings"));+ assert!(src.contains("Analyzed") || src.contains("has_saved_analysis"));+ assert!(src.contains("analyze_from_tree") || src.contains("small_button(\"Analyze\")"));+ assert!(+ src.contains("Browse") || src.contains("browse_binary_path") || src.contains("rfd::")+ );+ assert!(src.contains("pending_delete") || src.contains("Delete from project"));+ assert!(src.contains("use_gpu_experimental") || src.contains("GPU experimental"));+ assert!(src.contains("analyzer_supports_gpu"));+ assert!(src.contains("CPU only") || src.contains("\"GPU\""));+ assert!(src.contains("m3_linear_progress") || src.contains("Analysis progress"));+ assert!(src.contains("begin_analysis_job") || src.contains("Run Analysis"));+ assert!(src.contains("Overview") || src.contains("ui_overview"));+ assert!(src.contains("show_rows") || src.contains("rtti_filtered_idx"));+ assert!(src.contains("analysis_done_banner") || src.contains("Analysis complete"));+ assert!(src.contains("double_clicked") && src.contains("open_id"));+ assert!(src.contains("show_startup_picker") || src.contains("ui_startup_picker"));+ assert!(src.contains("recent_projects") || src.contains("Open existing project"));+ // No emoji codepoints in this file (Material geometry lives in icons.rs)+ // U+1F4C1 folder, U+25CF/U+25CB bullets, U+25B6 play — use escapes so the+ // forbidden glyphs themselves never appear in source.+ assert!(!src.contains('\u{1F4C1}'));+ assert!(!src.contains('\u{25CF}'));+ assert!(!src.contains('\u{25CB}'));+ assert!(!src.contains('\u{25B6}'));}#[test]fn icons_module_is_material_not_emoji() {- let icons = include_str!("icons.rs");- assert!(icons.contains("Material"));- assert!(icons.contains("Folder") || icons.contains("folder"));- assert!(!icons.contains('\u{1F4C1}'));- assert!(!icons.contains('\u{25CF}'));+ let icons = include_str!("icons.rs");+ assert!(icons.contains("Material"));+ assert!(icons.contains("Folder") || icons.contains("folder"));+ assert!(!icons.contains('\u{1F4C1}'));+ assert!(!icons.contains('\u{25CF}'));}#[test]fn former_menu_stubs_are_wired_not_nyi_only() {- let src = include_str!("main.rs");- // No remaining nyi for inventoried Edit/Nav/Search/Select/Tools stubs- assert!(!src.contains("nyi(\"Edit → Undo\")"));- assert!(!src.contains("nyi(\"Edit → Redo\")"));- assert!(!src.contains("nyi(\"Edit → Clear selection\")"));- assert!(!src.contains("nyi(\"Navigation → Go to address\")"));- assert!(!src.contains("nyi(\"Search → Search memory\")"));- assert!(!src.contains("nyi(\"Search → Search program text\")"));- assert!(!src.contains("nyi(\"Select → Select all\")"));- assert!(!src.contains("nyi(\"Tools → Processor options\")"));- // Real handlers present- assert!(src.contains("edit_undo"));- assert!(src.contains("edit_redo"));- assert!(src.contains("edit_clear_selection"));- assert!(src.contains("goto_address_str") || src.contains("show_goto_dialog"));- assert!(src.contains("run_search_memory"));- assert!(src.contains("run_search_text"));- assert!(src.contains("select_all_listing"));- assert!(src.contains("show_processor_dialog"));+ let src = include_str!("main.rs");+ // No remaining nyi for inventoried Edit/Nav/Search/Select/Tools stubs+ assert!(!src.contains("nyi(\"Edit → Undo\")"));+ assert!(!src.contains("nyi(\"Edit → Redo\")"));+ assert!(!src.contains("nyi(\"Edit → Clear selection\")"));+ assert!(!src.contains("nyi(\"Navigation → Go to address\")"));+ assert!(!src.contains("nyi(\"Search → Search memory\")"));+ assert!(!src.contains("nyi(\"Search → Search program text\")"));+ assert!(!src.contains("nyi(\"Select → Select all\")"));+ assert!(!src.contains("nyi(\"Tools → Processor options\")"));+ // Real handlers present+ assert!(src.contains("edit_undo"));+ assert!(src.contains("edit_redo"));+ assert!(src.contains("edit_clear_selection"));+ assert!(src.contains("goto_address_str") || src.contains("show_goto_dialog"));+ assert!(src.contains("run_search_memory"));+ assert!(src.contains("run_search_text"));+ assert!(src.contains("select_all_listing"));+ assert!(src.contains("show_processor_dialog"));}#[test]fn menu_actions_goto_search_select_on_loaded_program() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");assert!(!app.listing.is_empty());app.select_all_listing();@@ -10378,40 +11091,40 @@ mod tests {assert!(!app.listing_selection.is_empty());let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();- app.goto_address_str(&format!("{entry:#x}")).expect("goto");+ app.goto_address_str(&format!("{entry:#x}")).expect("goto");assert_eq!(app.listing_focus_va, Some(entry));assert_eq!(app.center, CenterPane::Listing);- app.search_memory_input = "55 48 89 e5".into();- app.run_search_memory.expect("mem search");+ app.search_memory_input = "55 48 89 e5".into();+ app.run_search_memory.expect("mem search");assert!(!app.memory_hits.is_empty());assert!(app.show_search_results);- app.search_text_input = "push".into();- app.run_search_text.expect("text search");+ app.search_text_input = "push".into();+ app.run_search_text.expect("text search");assert!(!app.text_hits.is_empty());app.show_processor_dialog = true;let info = processor_info(app.program.as_ref().unwrap());- assert!(info.language.contains("x86"));+ assert!(info.language.contains("x86"));}- // ─── token model, listing sync, view filter, next/prev fn ───+ // ─── token model, listing sync, view filter, next/prev fn ───#[test]fn decompiler_tokens_are_populated_and_cross_highlight() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();app.refresh_decompiler_at(entry);assert!(!app.decomp_lines.is_empty(),- "token cache must be populated after refresh_decompiler_at"+ "token cache must be populated after refresh_decompiler_at");- // Default GUI stage is Stage-1; the emitter drops- // `block_N:` labels in favour of structured regions. Assert only- // that we see at least one keyword token — the shape common to- // every stage.+ // Default GUI stage is Stage-1; the emitter drops+ // `block_N:` labels in favour of structured regions. Assert only+ // that we see at least one keyword token — the shape common to+ // every stage.let all_tokens: Vec<&TokenKind> = app.decomp_lines.iter()@@ -10419,11 +11132,11 @@ mod tests {.collect();assert!(all_tokens.iter().any(|k| matches!(k, TokenKind::Keyword)),- "expected at least one Keyword (void/return/etc)"+ "expected at least one Keyword (void/return/etc)");- // Cross-highlight line should be recomputable and match what the- // decoder found for the entry VA (may be None if Stage-1 emit- // stripped per-line addresses, but the field remains consistent).+ // Cross-highlight line should be recomputable and match what the+ // decoder found for the entry VA (may be None if Stage-1 emit+ // stripped per-line addresses, but the field remains consistent).let ln = decomp_line_for_va(&app.decomp_lines, entry);assert_eq!(app.decomp_cross_line, ln);}@@ -10431,19 +11144,22 @@ mod tests {#[test]fn navigate_next_prev_function_wraps() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("analysis_lab.pe")).expect("load");- // Fake up two functions if the analyzer didn't produce any yet.+ app.load_binary(&fixture_path("analysis_lab.pe"))+ .expect("load");+ // Fake up two functions if the analyzer didn't produce any yet.if app.program.as_ref().unwrap().analysis.functions.is_empty() {let prog = app.program.as_mut().unwrap();let base = prog.entry.unwrap_or(prog.image_base);prog.analysis.functions- .push(ghidrust_core::FunctionInfo::new(base, base + 0x10, "fn_a"));- prog.analysis.functions.push(ghidrust_core::FunctionInfo::new(- base + 0x40,- base + 0x50,- "fn_b",- ));+ .push(ghidrust_core::FunctionInfo::new(base, base + 0x10, "fn_a"));+ prog.analysis+ .functions+ .push(ghidrust_core::FunctionInfo::new(+ base + 0x40,+ base + 0x50,+ "fn_b",+ ));}let entries: Vec<u64> = app.program@@ -10459,15 +11175,15 @@ mod tests {let first = sorted[0];app.listing_focus_va = Some(first);app.nav_next_function();- // Cursor should have moved to another function entry (or wrapped).+ // Cursor should have moved to another function entry (or wrapped).assert!(sorted.contains(&app.listing_focus_va.unwrap()));}#[test]fn program_tree_view_filter_hides_addresses() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");- // Grab a block name & VA.+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ // Grab a block name & VA.let (block_name, block_va) = {let p = app.program.as_ref().unwrap();let b = p.blocks.first().unwrap();@@ -10475,9 +11191,9 @@ mod tests {};assert!(app.addr_in_view(block_va));let mut set = BTreeSet::new();- set.insert("__does_not_exist__".to_string());+ set.insert("__does_not_exist__".to_string());app.set_listing_view(Some(set));- assert!(!app.addr_in_view(block_va), "filter set must hide addr");+ assert!(!app.addr_in_view(block_va), "filter set must hide addr");app.add_to_view(block_name.clone());assert!(app.addr_in_view(block_va));app.remove_from_view(&block_name);@@ -10489,11 +11205,11 @@ mod tests {#[test]fn imports_exports_are_honest_empty_or_analyzer_derived() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let (imports, exports) = app.imports_exports();- // Never panics; results are analyzer-driven not fabricated.+ // Never panics; results are analyzer-driven not fabricated.for (va, _name) in imports.iter().chain(exports.iter()) {- // If any row exists it must be a plausible in-image VA.+ // If any row exists it must be a plausible in-image VA.let in_program = app.program.as_ref()@@ -10503,94 +11219,113 @@ mod tests {}}- // ─── rename / retype / comment / signature / type ───+ // ─── rename / retype / comment / signature / type ───#[test]fn rename_persists_and_reflects_in_analysis() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");- // Attach a synthetic function so we have a rename target.+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ // Attach a synthetic function so we have a rename target.let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();{let prog = app.program.as_mut().unwrap();- prog.analysis.functions.push(ghidrust_core::FunctionInfo::new(- entry,- entry + 0x10,- "FUN_original",- ));+ prog.analysis+ .functions+ .push(ghidrust_core::FunctionInfo::new(+ entry,+ entry + 0x10,+ "FUN_original",+ ));}- app.rename_at(entry, "my_main").expect("rename");+ app.rename_at(entry, "my_main").expect("rename");let p = app.program.as_ref().unwrap();- assert_eq!(p.edits.rename_at(entry), Some("my_main"));- assert_eq!(p.function_at(entry).map(|f| f.name().as_str()), Some("my_main"));+ assert_eq!(p.edits.rename_at(entry), Some("my_main"));+ assert_eq!(+ p.function_at(entry).map(|f| f.name().as_str()),+ Some("my_main")+ );assert_eq!(p.display_function_name_at(entry).as_deref(),- Some("my_main")+ Some("my_main"));- // Empty rename clears the edit and rejects with error.- let err = app.rename_at(entry, "");+ // Empty rename clears the edit and rejects with error.+ let err = app.rename_at(entry, "");assert!(err.is_err());}#[test]fn retype_and_comment_and_signature_persist() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let va = app.program.as_ref().and_then(|p| p.entry).unwrap();- app.retype_at(va, "int32_t").expect("retype");- app.set_comment_at(va, CommentKind::Eol, "eol comment").expect("comment");- app.set_comment_at(va, CommentKind::Plate, "plate!").expect("plate");- app.set_function_signature(va, "int foo(char *)").expect("sig");+ app.retype_at(va, "int32_t").expect("retype");+ app.set_comment_at(va, CommentKind::Eol, "eol comment")+ .expect("comment");+ app.set_comment_at(va, CommentKind::Plate, "plate!")+ .expect("plate");+ app.set_function_signature(va, "int foo(char *)")+ .expect("sig");let p = app.program.as_ref().unwrap();- assert_eq!(p.edits.retype_at(va), Some("int32_t"));- assert_eq!(p.edits.comment_at(va, CommentKind::Eol), Some("eol comment"));- assert_eq!(p.edits.comment_at(va, CommentKind::Plate), Some("plate!"));+ assert_eq!(p.edits.retype_at(va), Some("int32_t"));+ assert_eq!(+ p.edits.comment_at(va, CommentKind::Eol),+ Some("eol comment")+ );+ assert_eq!(p.edits.comment_at(va, CommentKind::Plate), Some("plate!"));assert_eq!(p.edits.function_signature(va).map(|s| s.signature.as_str()),- Some("int foo(char *)")+ Some("int foo(char *)"));}#[test]fn commit_params_and_locals_snapshot_analyzer_state() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();{let prog = app.program.as_mut().unwrap();- let mut fi =- ghidrust_core::FunctionInfo::new(entry, entry + 0x40, "with_params");- fi.calling_convention = Some("windowsx64".into());- fi.parameters = vec!["rcx".into(), "rdx".into()];- fi.stack_locals = vec!["local_10".into(), "local_18".into()];+ let mut fi = ghidrust_core::FunctionInfo::new(entry, entry + 0x40, "with_params");+ fi.calling_convention = Some("windowsx64".into());+ fi.parameters = vec!["rcx".into(), "rdx".into()];+ fi.stack_locals = vec!["local_10".into(), "local_18".into()];prog.analysis.functions.push(fi);}- app.commit_params_return(entry).expect("commit params");- app.commit_locals(entry).expect("commit locals");- let sig = app.program.as_ref().unwrap().edits.function_signature(entry).unwrap();+ app.commit_params_return(entry).expect("commit params");+ app.commit_locals(entry).expect("commit locals");+ let sig = app+ .program+ .as_ref()+ .unwrap()+ .edits+ .function_signature(entry)+ .unwrap();assert_eq!(sig.parameters.len(), 2);assert_eq!(sig.locals.len(), 2);- assert_eq!(sig.return_type.as_deref(), Some("undefined"));+ assert_eq!(sig.return_type.as_deref(), Some("undefined"));}#[test]fn user_types_and_applied_types_persist() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");- app.define_user_type("Widget", "struct Widget { int id; }").expect("new type");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.define_user_type("Widget", "struct Widget { int id; }")+ .expect("new type");let va = app.program.as_ref().and_then(|p| p.entry).unwrap();- app.apply_type_at(va, "Widget").expect("apply");+ app.apply_type_at(va, "Widget").expect("apply");let p = app.program.as_ref().unwrap();- assert!(p.edits.user_types.contains_key("Widget"));- assert_eq!(p.edits.applied_type_at(va), Some("Widget"));+ assert!(p.edits.user_types.contains_key("Widget"));+ assert_eq!(p.edits.applied_type_at(va), Some("Widget"));}#[test]fn dtm_builtins_contain_stage0_types() {- for want in ["byte", "word", "dword", "qword", "char", "int", "int32_t", "pointer"] {+ for want in [+ "byte", "word", "dword", "qword", "char", "int", "int32_t", "pointer",+ ] {assert!(BUILTIN_TYPES.contains(&want),- "expected {want} in DTM Built-In archive"+ "expected {want} in DTM Built-In archive");}}@@ -10598,12 +11333,12 @@ mod tests {#[test]fn console_severity_tracks_log_calls() {let mut app = GhidrustApp::headless();- // Preseeded with 1 info line.+ // Preseeded with 1 info line.assert_eq!(app.console.len(), 1);assert_eq!(app.console_severity.len(), 1);- app.log("info");- app.log_warn("warn");- app.log_error("boom");+ app.log("info");+ app.log_warn("warn");+ app.log_error("boom");assert_eq!(app.console_severity.last().copied(),Some(ConsoleSeverity::Error)@@ -10617,31 +11352,33 @@ mod tests {#[test]fn scalar_and_address_hints_extract_first_literal() {- assert!(first_scalar_hint("rax, 0x1234").unwrap().contains("0x1234"));- assert!(first_scalar_hint("rax, 42").unwrap().contains("dec 42"));- assert!(first_address_hint("0x140001000").unwrap().contains("0x140001000"));- assert!(first_scalar_hint("rax, rbx").is_none());+ assert!(first_scalar_hint("rax, 0x1234").unwrap().contains("0x1234"));+ assert!(first_scalar_hint("rax, 42").unwrap().contains("dec 42"));+ assert!(first_address_hint("0x140001000")+ .unwrap()+ .contains("0x140001000"));+ assert!(first_scalar_hint("rax, rbx").is_none());}- // ─── polish — DTM editing / chooser / persistence ────+ // ─── polish — DTM editing / chooser / persistence ────#[test]fn rename_and_delete_user_type_rewrites_applied_types() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let va = app.program.as_ref().and_then(|p| p.entry).unwrap();- app.define_user_type("Widget", "Structure\nint id;")- .expect("define");- app.apply_type_at(va, "Widget").expect("apply");+ app.define_user_type("Widget", "Structure\nint id;")+ .expect("define");+ app.apply_type_at(va, "Widget").expect("apply");- // Rename user type must rewrite the applied-types decoration.- app.rename_user_type("Widget", "Gadget").expect("rename");+ // Rename user type must rewrite the applied-types decoration.+ app.rename_user_type("Widget", "Gadget").expect("rename");let p = app.program.as_ref().unwrap();- assert!(p.edits.user_types.contains_key("Gadget"));- assert_eq!(p.edits.applied_type_at(va), Some("Gadget"));+ assert!(p.edits.user_types.contains_key("Gadget"));+ assert_eq!(p.edits.applied_type_at(va), Some("Gadget"));- // Delete user type must clear the applied decoration too.- app.delete_user_type("Gadget").expect("delete");+ // Delete user type must clear the applied decoration too.+ app.delete_user_type("Gadget").expect("delete");let p = app.program.as_ref().unwrap();assert!(p.edits.user_types.is_empty());assert!(p.edits.applied_type_at(va).is_none());@@ -10650,35 +11387,35 @@ mod tests {#[test]fn edit_user_type_supports_rename_and_body_swap() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");- app.define_user_type("Widget", "Structure\nint a;")- .expect("define");- app.edit_user_type("Widget", "WidgetV2", "Structure\nint a;\nint b;")- .expect("edit");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.define_user_type("Widget", "Structure\nint a;")+ .expect("define");+ app.edit_user_type("Widget", "WidgetV2", "Structure\nint a;\nint b;")+ .expect("edit");let p = app.program.as_ref().unwrap();- assert!(!p.edits.user_types.contains_key("Widget"));- assert!(p.edits.user_types.contains_key("WidgetV2"));- assert!(p.edits.user_type("WidgetV2").unwrap().contains("int b;"));- // Editing a non-existent type must fail rather than silently create.- assert!(app.edit_user_type("nope", "x", "y").is_err());+ assert!(!p.edits.user_types.contains_key("Widget"));+ assert!(p.edits.user_types.contains_key("WidgetV2"));+ assert!(p.edits.user_type("WidgetV2").unwrap().contains("int b;"));+ // Editing a non-existent type must fail rather than silently create.+ assert!(app.edit_user_type("nope", "x", "y").is_err());}#[test]fn new_typedef_on_and_pointer_to_register_user_types() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");- let td = app.new_typedef_on("int32_t").expect("typedef");- let pt = app.new_pointer_to("int32_t").expect("pointer");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ let td = app.new_typedef_on("int32_t").expect("typedef");+ let pt = app.new_pointer_to("int32_t").expect("pointer");let p = app.program.as_ref().unwrap();assert!(p.edits.user_types.contains_key(&td));assert!(p.edits.user_types.contains_key(&pt));- assert!(pt.ends_with('*'));+ assert!(pt.ends_with('*'));}#[test]fn type_chooser_dialog_opens_with_target_va() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let va = app.program.as_ref().and_then(|p| p.entry).unwrap();assert!(!app.show_type_chooser_dialog);app.open_type_chooser(Some(va));@@ -10689,29 +11426,30 @@ mod tests {#[test]fn edit_type_dialog_preloads_body() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");- app.define_user_type("Foo", "Structure\nint x;").expect("define");- app.open_edit_type_dialog("Foo");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.define_user_type("Foo", "Structure\nint x;")+ .expect("define");+ app.open_edit_type_dialog("Foo");assert!(app.show_edit_type_dialog);- assert_eq!(app.edit_type_dialog_orig_name, "Foo");- assert_eq!(app.edit_type_dialog_name, "Foo");- assert!(app.edit_type_dialog_body.contains("int x;"));+ assert_eq!(app.edit_type_dialog_orig_name, "Foo");+ assert_eq!(app.edit_type_dialog_name, "Foo");+ assert!(app.edit_type_dialog_body.contains("int x;"));}#[test]fn all_five_comment_kinds_render_edits_into_program() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let va = app.program.as_ref().and_then(|p| p.entry).unwrap();for k in CommentKind::ALL {- app.set_comment_at(va, *k, format!("k={}", k.label))- .expect("comment");+ app.set_comment_at(va, *k, format!("k={}", k.label))+ .expect("comment");}let p = app.program.as_ref().unwrap();for k in CommentKind::ALL {assert_eq!(p.edits.comment_at(va, *k),- Some(format!("k={}", k.label).as_str())+ Some(format!("k={}", k.label).as_str()));}assert_eq!(p.edits.comments_at(va).len(), CommentKind::ALL.len());@@ -10721,31 +11459,29 @@ mod tests {fn program_edits_persist_across_project_save_and_load() {use ghidrust_core::Project;- let dir = std::env::temp_dir().join(format!(- "ghidrust_gui_edits_rt_{}",- std::process::id()- ));+ let dir =+ std::env::temp_dir().join(format!("ghidrust_gui_edits_rt_{}", std::process::id()));let _ = std::fs::remove_dir_all(&dir);- let mut proj = Project::create(&dir, "GuiEditRt").expect("proj");- let f = proj.import_file(fixture_path("tiny_x64.pe")).unwrap();+ let mut proj = Project::create(&dir, "GuiEditRt").expect("proj");+ let f = proj.import_file(fixture_path("tiny_x64.pe")).unwrap();- // Session A — apply user edits then save.+ // Session A — apply user edits then save.let mut app = GhidrustApp::headless();app.project = Some(proj);app.active_file_id = Some(f.id.clone());app.load_binary(&app.project.as_ref().unwrap().binary_path(&f))- .expect("load");+ .expect("load");let va = app.program.as_ref().and_then(|p| p.entry).unwrap();- app.rename_at(va, "session_a_main").expect("rename");- app.set_comment_at(va, CommentKind::Plate, "plate!")- .expect("comment");- app.define_user_type("Widget", "Structure\nint id;")- .expect("define");- app.apply_type_at(va, "Widget").expect("apply");- app.save_results.expect("save");-- // Session B — fresh app, same project, same file.- let proj2 = Project::open(&dir).expect("reopen");+ app.rename_at(va, "session_a_main").expect("rename");+ app.set_comment_at(va, CommentKind::Plate, "plate!")+ .expect("comment");+ app.define_user_type("Widget", "Structure\nint id;")+ .expect("define");+ app.apply_type_at(va, "Widget").expect("apply");+ app.save_results.expect("save");++ // Session B — fresh app, same project, same file.+ let proj2 = Project::open(&dir).expect("reopen");let mut app2 = GhidrustApp::headless();app2.project = Some(proj2);app2.active_file_id = Some(f.id.clone());@@ -10754,13 +11490,13 @@ mod tests {.as_ref().unwrap().load_program_with_results(&f)- .expect("load with results");+ .expect("load with results");app2.program = Some(prog2);let p = app2.program.as_ref().unwrap();- assert_eq!(p.edits.rename_at(va), Some("session_a_main"));- assert_eq!(p.edits.comment_at(va, CommentKind::Plate), Some("plate!"));- assert!(p.edits.user_types.contains_key("Widget"));- assert_eq!(p.edits.applied_type_at(va), Some("Widget"));+ assert_eq!(p.edits.rename_at(va), Some("session_a_main"));+ assert_eq!(p.edits.comment_at(va, CommentKind::Plate), Some("plate!"));+ assert!(p.edits.user_types.contains_key("Widget"));+ assert_eq!(p.edits.applied_type_at(va), Some("Widget"));let _ = std::fs::remove_dir_all(&dir);}@@ -10768,32 +11504,33 @@ mod tests {#[test]fn edit_events_invalidate_decompiler_cache() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();{let prog = app.program.as_mut().unwrap();prog.analysis.functions- .push(ghidrust_core::FunctionInfo::new(entry, entry + 0x20, "fn"));+ .push(ghidrust_core::FunctionInfo::new(entry, entry + 0x20, "fn"));}app.refresh_decompiler_at(entry);assert!(!app.decomp_text.is_empty());- // A rename mutation must invalidate cache via drain_events.- app.rename_at(entry, "renamed").expect("rename");+ // A rename mutation must invalidate cache via drain_events.+ app.rename_at(entry, "renamed").expect("rename");let _ = app.drain_events();- assert!(app.decomp_text.is_empty(), "cache must clear after rename");+ assert!(app.decomp_text.is_empty(), "cache must clear after rename");}#[test]fn goto_out_of_window_va_redisassembles_listing() {let mut app = GhidrustApp::headless();- // analysis_lab has richer layout; load then go to a VA outside entry window- app.load_binary(&fixture_path("analysis_lab.pe")).expect("load");+ // analysis_lab has richer layout; load then go to a VA outside entry window+ app.load_binary(&fixture_path("analysis_lab.pe"))+ .expect("load");let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();let first_listing_va = app.listing[0].address;assert_eq!(first_listing_va, entry);- // Pick a program block VA that is not covered by the entry listing window+ // Pick a program block VA that is not covered by the entry listing windowlet window_end = {let last = app.listing.last().unwrap();last.address + u64::from(last.length).max(1)@@ -10806,59 +11543,59 @@ mod tests {.iter().map(|b| b.va).find(|&va| va < first_listing_va || va >= window_end)- .expect("need a block VA outside entry listing window");+ .expect("need a block VA outside entry listing window");- // Confirm helper says outside+ // Confirm helper says outsideassert!(listing_index_at_or_before(&app.listing, outside).is_none(),- "precondition: {outside:#x} must be outside listing [{first_listing_va:#x}.)"+ "precondition: {outside:#x} must be outside listing [{first_listing_va:#x}.)");- app.goto_address_str(&format!("{outside:#x}"))- .expect("goto outside");+ app.goto_address_str(&format!("{outside:#x}"))+ .expect("goto outside");assert_eq!(app.listing_focus_va, Some(outside));assert!(!app.listing.is_empty(),- "re-disassemble must produce listing"+ "re-disassemble must produce listing");assert_eq!(app.listing[0].address, outside,- "listing must start at target VA after re-disassemble"+ "listing must start at target VA after re-disassemble");- // Selection points at first insn of new window+ // Selection points at first insn of new windowassert_eq!(app.listing_selection.start, Some(0));- // Memory search hit navigation also refreshes when needed+ // Memory search hit navigation also refreshes when neededif let Some(hit) = app.memory_hits.first().cloned() {let _ = hit;}- app.search_memory_input = "55 48 89 e5".into();- app.run_search_memory.expect("mem");+ app.search_memory_input = "55 48 89 e5".into();+ app.run_search_memory.expect("mem");assert!(!app.memory_hits.is_empty());let hit_va = app.memory_hits[0].va;- // Force listing back to entry-only window- app.goto_address_str(&format!("{entry:#x}")).expect("back to entry");+ // Force listing back to entry-only window+ app.goto_address_str(&format!("{entry:#x}"))+ .expect("back to entry");assert_eq!(app.listing[0].address, entry);- // Navigate to memory hit (may be same or different region)- app.goto_address_str(&format!("{hit_va:#x}"))- .expect("goto hit");+ // Navigate to memory hit (may be same or different region)+ app.goto_address_str(&format!("{hit_va:#x}"))+ .expect("goto hit");assert!(- app.listing- .iter()- .any(|i| i.address == hit_va- || (i.address <= hit_va && hit_va < i.address + u64::from(i.length))),- "listing must cover hit VA {hit_va:#x} after goto; first={:#x}",+ app.listing.iter().any(|i| i.address == hit_va+ || (i.address <= hit_va && hit_va < i.address + u64::from(i.length))),+ "listing must cover hit VA {hit_va:#x} after goto; first={:#x}",app.listing[0].address);}- // ─── tables, xrefs, equates, tags, search dialogs ────+ // ─── tables, xrefs, equates, tags, search dialogs ────#[test]fn xrefs_to_and_from_return_honest_rows_on_fixture() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("analysis_lab.pe")).expect("load");- // xrefs_from at entry decodes and never fabricates.+ app.load_binary(&fixture_path("analysis_lab.pe"))+ .expect("load");+ // xrefs_from at entry decodes and never fabricates.let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();let from = app.xrefs_from_va(entry);for r in &from {@@ -10866,109 +11603,133 @@ mod tests {assert!(r.from >= entry);}- // Inject a fake reference so xrefs_to_va picks it up deterministically.+ // Inject a fake reference so xrefs_to_va picks it up deterministically.{let prog = app.program.as_mut().unwrap();prog.analysis.references.push(ghidrust_core::ReferenceInfo {from: prog.image_base + 0x100,to: entry,- kind: "call".into(),+ kind: "call".into(),});}let to = app.xrefs_to_va(entry);- assert!(to.iter().any(|r| r.kind == "call"));+ assert!(to.iter().any(|r| r.kind == "call"));assert!(to.iter().all(|r| r.to == entry));}#[test]fn set_equate_and_edit_events_fan_out() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let va = app.program.as_ref().and_then(|p| p.entry).unwrap();- app.set_equate(va, 1, "SW_HIDE", 0).expect("set equate");+ app.set_equate(va, 1, "SW_HIDE", 0).expect("set equate");let p = app.program.as_ref().unwrap();- assert_eq!(p.edits.equate_at(va, 1).map(|e| e.name().as_str()), Some("SW_HIDE"));+ assert_eq!(+ p.edits.equate_at(va, 1).map(|e| e.name().as_str()),+ Some("SW_HIDE")+ );assert_eq!(p.edits.equate_at(va, 1).map(|e| e.value), Some(0));- // Groups & references consistent.+ // Groups & references consistent.let groups = p.edits.equate_groups();- assert!(groups.iter().any(|(n, _, _)| n == "SW_HIDE"));- // Setting empty name clears it.- app.set_equate(va, 1, "", 0).expect("clear");- assert!(app.program.as_ref().unwrap().edits.equate_at(va, 1).is_none());+ assert!(groups.iter().any(|(n, _, _)| n == "SW_HIDE"));+ // Setting empty name clears it.+ app.set_equate(va, 1, "", 0).expect("clear");+ assert!(app+ .program+ .as_ref()+ .unwrap()+ .edits+ .equate_at(va, 1)+ .is_none());}#[test]fn function_tags_add_remove_delete_via_app() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();- app.add_function_tag(entry, "MALLOC").expect("add");- app.add_function_tag(entry, "SANITIZED").expect("add");+ app.add_function_tag(entry, "MALLOC").expect("add");+ app.add_function_tag(entry, "SANITIZED").expect("add");let p = app.program.as_ref().unwrap();- assert!(p.edits.function_has_tag(entry, "MALLOC"));- assert!(p.edits.function_has_tag(entry, "SANITIZED"));- assert!(p.edits.all_function_tags.contains("MALLOC"));- app.remove_function_tag(entry, "MALLOC").expect("remove");- assert!(!app.program.as_ref().unwrap().edits.function_has_tag(entry, "MALLOC"));- // Delete-everywhere strips from universe.- app.delete_tag_everywhere("SANITIZED").expect("delete");- assert!(!app.program.as_ref().unwrap().edits.all_function_tags.contains("SANITIZED"));+ assert!(p.edits.function_has_tag(entry, "MALLOC"));+ assert!(p.edits.function_has_tag(entry, "SANITIZED"));+ assert!(p.edits.all_function_tags.contains("MALLOC"));+ app.remove_function_tag(entry, "MALLOC").expect("remove");+ assert!(!app+ .program+ .as_ref()+ .unwrap()+ .edits+ .function_has_tag(entry, "MALLOC"));+ // Delete-everywhere strips from universe.+ app.delete_tag_everywhere("SANITIZED").expect("delete");+ assert!(!app+ .program+ .as_ref()+ .unwrap()+ .edits+ .all_function_tags+ .contains("SANITIZED"));}#[test]fn search_scalars_dialog_runs_range_over_listing() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");- app.search_scalars_min = "0".into();- app.search_scalars_max = "0xffff".into();- app.run_search_scalars.expect("scalars");- // Fixture may or may not include a scalar in this range; the runner- // must still succeed and populate text_hits deterministically.+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.search_scalars_min = "0".into();+ app.search_scalars_max = "0xffff".into();+ app.run_search_scalars.expect("scalars");+ // Fixture may or may not include a scalar in this range; the runner+ // must still succeed and populate text_hits deterministically.assert!(app.show_search_results);}#[test]fn search_instruction_patterns_filters_listing() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");- // tiny_x64 has a `push rbp` prologue; filter should hit it.- app.search_insn_mnemonic = "push".into();+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ // tiny_x64 has a `push rbp` prologue; filter should hit it.+ app.search_insn_mnemonic = "push".into();app.search_insn_operands.clear();- app.run_search_instruction_patterns.expect("insn");+ app.run_search_instruction_patterns.expect("insn");assert!(!app.text_hits.is_empty());- assert!(app.text_hits.iter().any(|h| h.kind == "insn"));+ assert!(app.text_hits.iter().any(|h| h.kind == "insn"));}#[test]fn address_tables_hits_appear_after_analyzer_populates() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");{let prog = app.program.as_mut().unwrap();- prog.analysis.address_tables.push(ghidrust_core::AddressTableInfo {- base: prog.image_base,- count: 3,- entries: vec![prog.image_base, prog.image_base + 8, prog.image_base + 16],- role: ghidrust_core::AddressTableRole::Unknown,- });+ prog.analysis+ .address_tables+ .push(ghidrust_core::AddressTableInfo {+ base: prog.image_base,+ count: 3,+ entries: vec![prog.image_base, prog.image_base + 8, prog.image_base + 16],+ role: ghidrust_core::AddressTableRole::Unknown,+ });}let hits = address_table_hits(app.program.as_ref().unwrap());assert_eq!(hits.len(), 1);- assert!(hits[0].text.contains("3 entries"));+ assert!(hits[0].text.contains("3 entries"));}#[test]fn compute_checksums_round_trip_whole_image() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");- app.compute_checksums(ChecksumMode::WholeImage).expect("checksum");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.compute_checksums(ChecksumMode::WholeImage)+ .expect("checksum");let r = app.checksum_last.as_ref().unwrap();assert!(r.len > 0);assert!(r.crc32 != 0);assert!(r.adler32 != 0);- // Deterministic: re-running yields the same values.+ // Deterministic: re-running yields the same values.let first = r.clone();- app.compute_checksums(ChecksumMode::WholeImage).expect("checksum");+ app.compute_checksums(ChecksumMode::WholeImage)+ .expect("checksum");assert_eq!(app.checksum_last.as_ref().unwrap(), &first);}@@ -10977,8 +11738,8 @@ mod tests {let mut app = GhidrustApp::headless();assert_eq!(app.bytes_pane_bpr, 16);assert!(app.bytes_pane_va.is_none());- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");- // Programmatic follow — reflects listing_focus.+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ // Programmatic follow — reflects listing_focus.app.listing_focus_va = app.program.as_ref().and_then(|p| p.entry);app.bytes_pane_va = app.listing_focus_va;assert!(app.bytes_pane_va.is_some());@@ -10987,21 +11748,21 @@ mod tests {#[test]fn parse_scalar_input_hex_and_dec_and_signed() {let app = GhidrustApp::headless();- assert_eq!(app.parse_scalar_input("0x1234").unwrap(), 0x1234);- assert_eq!(app.parse_scalar_input("42").unwrap(), 42);- assert_eq!(app.parse_scalar_input("-0x10").unwrap(), -0x10);- assert!(app.parse_scalar_input("").is_err());+ assert_eq!(app.parse_scalar_input("0x1234").unwrap(), 0x1234);+ assert_eq!(app.parse_scalar_input("42").unwrap(), 42);+ assert_eq!(app.parse_scalar_input("-0x10").unwrap(), -0x10);+ assert!(app.parse_scalar_input("").is_err());}- // ── Graphs & maps ─────────────────────────────────────+ // ── Graphs & maps ─────────────────────────────────────- /// Function Graph derives Stage-0 blocks + edges from the- /// currently-focused function's CFG (honest empty if the region has- /// no recovered blocks).+ /// Function Graph derives Stage-0 blocks + edges from the+ /// currently-focused function's CFG (honest empty if the region has+ /// no recovered blocks).#[test]fn function_graph_pane_layouts_stage0_cfg() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();app.focus_function(entry);@@ -11016,8 +11777,8 @@ mod tests {FunctionGraphLayout::Hierarchical,view,);- // Honest-empty is acceptable, but if blocks land they must all- // have positive rects.+ // Honest-empty is acceptable, but if blocks land they must all+ // have positive rects.for b in &blocks {assert!(b.rect.width() > 0.0);}@@ -11026,8 +11787,8 @@ mod tests {}}- /// Function Call Graph roots at the current function with- /// level 0; expansion levels are session-only settings.+ /// Function Call Graph roots at the current function with+ /// level 0; expansion levels are session-only settings.#[test]fn call_graph_state_settings_persist_across_frames() {let mut app = GhidrustApp::headless();@@ -11038,26 +11799,28 @@ mod tests {assert_eq!(app.graph_state.call_graph_levels_in, 2);}- /// Editable Memory Map: RWX toggles + add + delete flow.+ /// Editable Memory Map: RWX toggles + add + delete flow.#[test]fn memory_map_edit_flow_adds_and_deletes_blocks() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let n0 = app.program.as_ref().unwrap().blocks.len();- // Add a synthetic RWX block at 0x900000.- app.program.as_mut().unwrap().blocks.push(- ghidrust_core::MemoryBlock {- name: "synthetic".into(),+ // Add a synthetic RWX block at 0x900000.+ app.program+ .as_mut()+ .unwrap()+ .blocks+ .push(ghidrust_core::MemoryBlock {+ name: "synthetic".into(),va: 0x900000,size: 0x100,bytes: vec![0u8; 0x100],readable: true,writable: true,executable: true,- },- );+ });assert_eq!(app.program.as_ref().unwrap().blocks.len(), n0 + 1);- // Flip its RWX (via the field, mirrors the UI checkbox mutation).+ // Flip its RWX (via the field, mirrors the UI checkbox mutation).let idx = app.program.as_ref().unwrap().blocks.len() - 1;{let b = &mut app.program.as_mut().unwrap().blocks[idx];@@ -11068,28 +11831,28 @@ mod tests {assert_eq!(app.program.as_ref().unwrap().blocks.len(), n0);}- /// Register Manager lattice is present and set/clear works.+ /// Register Manager lattice is present and set/clear works.#[test]fn register_manager_lattice_and_values() {let mut app = GhidrustApp::headless();assert!(app.register_manager.values().is_empty());- app.register_manager.selected = Some("RAX".into());+ app.register_manager.selected = Some("RAX".into());app.register_manager.values().push(register_manager::RegisterValueRow {- register: "RAX".into(),+ register: "RAX".into(),start_va: 0x1000,end_va: 0x1100,- value: "0x2a".into(),+ value: "0x2a".into(),});assert_eq!(app.register_manager.values().len(), 1);}- /// Entropy strip samples cover mapped bytes without fabricating.+ /// Entropy strip samples cover mapped bytes without fabricating.#[test]fn entropy_samples_cover_mapped_blocks() {let mut app = GhidrustApp::headless();- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");let s = entropy::entropy_samples(app.program.as_ref().unwrap(), 256);assert!(!s.is_empty());for w in s.windows(2) {@@ -11097,13 +11860,17 @@ mod tests {}}- // ── Scripts ───────────────────────────────────────────+ // ── Scripts ───────────────────────────────────────────#[test]fn script_manager_catalog_is_populated_from_mcp_surface() {let app = GhidrustApp::headless();assert!(!app.script_manager.catalog.is_empty());- assert!(app.script_manager.catalog.iter().any(|s| s.name() == "mcp.list_functions"));+ assert!(app+ .script_manager+ .catalog+ .iter()+ .any(|s| s.name() == "mcp.list_functions"));}#[test]@@ -11111,7 +11878,7 @@ mod tests {let mut app = GhidrustApp::headless();app.text_editor.open_untitled();assert_eq!(app.text_editor.tabs.len(), 1);- app.text_editor.tabs[0].body.push_str("body");+ app.text_editor.tabs[0].body.push_str("body");app.text_editor.tabs[0].dirty = true;app.text_editor.close_active();assert_eq!(app.text_editor.tabs.len(), 0);@@ -11120,28 +11887,28 @@ mod tests {#[test]fn mcp_repl_submit_records_prompt_and_response() {let mut app = GhidrustApp::headless();- app.mcp_repl.input = "mcp.list_functions".into();+ app.mcp_repl.input = "mcp.list_functions".into();app.mcp_repl.submit();assert_eq!(app.mcp_repl.transcript.len(), 2);assert!(app.mcp_repl.transcript[0].prompt);assert!(!app.mcp_repl.transcript[1].prompt);}- // ── Debugger visibility ──────────────────────────────+ // ── Debugger visibility ──────────────────────────────#[test]fn debugger_host_enumerated_in_shell_panes() {let panes = GhidrustApp::shell_panes();assert!(- panes.contains(&"Debugger"),- "shell_panes missing tabbed Debugger host; full list = {panes:?}",+ panes.contains(&"Debugger"),+ "shell_panes missing tabbed Debugger host; full list = {panes:?}",);}#[test]fn debugger_menu_is_registered_in_shell() {let menus = GhidrustApp::shell_menus();- assert!(menus.contains(&"Debugger"));+ assert!(menus.contains(&"Debugger"));}#[test]@@ -11155,40 +11922,37 @@ mod tests {app.debugger.toggle_breakpoint(0x1000);assert!(!app.debugger.has_breakpoint(0x1000));- app.debugger.add_watch("rax");- app.debugger.add_watch("rax"); // dedup- app.debugger.add_watch("*(int*)rsp");+ app.debugger.add_watch("rax");+ app.debugger.add_watch("rax"); // dedup+ app.debugger.add_watch("*(int*)rsp");assert_eq!(app.debugger.watches.len(), 2);}- // ── Docking / layouts ────────────────────────────────+ // ── Docking / layouts ────────────────────────────────#[test]fn save_and_restore_layout_round_trip() {- // Use a fresh %APPDATA%/ghidrust equivalent to keep test hermetic.- let dir = std::env::temp_dir().join(format!(- "ghidrust_layouts_{}",- std::process::id()- ));+ // Use a fresh %APPDATA%/ghidrust equivalent to keep test hermetic.+ let dir = std::env::temp_dir().join(format!("ghidrust_layouts_{}", std::process::id()));let _ = std::fs::remove_dir_all(&dir);- // Point APPDATA at our sandbox so layouts write here.- let prev = std::env::var("APPDATA").ok();- // Only override APPDATA when it's the layout-dir resolver we care about.- std::env::set_var("APPDATA", &dir);+ // Point APPDATA at our sandbox so layouts write here.+ let prev = std::env::var("APPDATA").ok();+ // Only override APPDATA when it's the layout-dir resolver we care about.+ std::env::set_var("APPDATA", &dir);struct RestoreAppdata(Option<String>);impl Drop for RestoreAppdata {fn drop(&mut self) {if let Some(p) = &self.0 {- std::env::set_var("APPDATA", p);+ std::env::set_var("APPDATA", p);} else {- std::env::remove_var("APPDATA");+ std::env::remove_var("APPDATA");}}}let _guard = RestoreAppdata(prev);let mut app = GhidrustApp::headless();- // Flip a few state bits so we can prove the round-trip.+ // Flip a few state bits so we can prove the round-trip.app.toggle_pane(PaneKind::Bookmarks, true);app.toggle_pane(PaneKind::MemoryMap, true);app.debugger.host_open = true;@@ -11197,8 +11961,8 @@ mod tests {app.focus_center_tab(DockTab::Decompiler);app.show_console = false;- app.save_layout_named("myTest").expect("save layout");- // Flip everything back so restore has something to change.+ app.save_layout_named("myTest").expect("save layout");+ // Flip everything back so restore has something to change.app.toggle_pane(PaneKind::Bookmarks, false);app.toggle_pane(PaneKind::MemoryMap, false);app.debugger.host_open = false;@@ -11207,7 +11971,7 @@ mod tests {app.focus_center_tab(DockTab::Overview);app.show_console = true;- app.restore_layout_named("myTest").expect("restore layout");+ app.restore_layout_named("myTest").expect("restore layout");assert!(app.is_pane_open(PaneKind::Bookmarks));assert!(app.is_pane_open(PaneKind::MemoryMap));assert!(app.debugger.host_open);@@ -11229,18 +11993,18 @@ mod tests {#[test]fn graph_debugger_configure_menu_actions_wired_not_nyi() {- let src = include_str!("main.rs");- // Graph menu items open panes (not nyi).- assert!(!src.contains("nyi(\"Graph → Function Graph\""));- assert!(!src.contains("nyi(\"Graph → Function Call Graph\""));- assert!(!src.contains("nyi(\"Graph → Function Call Trees\""));- // Debugger menu is registered.- assert!(src.contains("ui.menu_button(\"Debugger\","));- // Launch is wired (not nyi).- assert!(src.contains("open_launch_ui"));- assert!(!src.contains("nyi(\"Debugger → Launch"));- // Configure dialog + Save Tool Layout menu items are wired.- assert!(src.contains("show_configure_dialog"));- assert!(src.contains("show_layouts_dialog"));+ let src = include_str!("main.rs");+ // Graph menu items open panes (not nyi).+ assert!(!src.contains("nyi(\"Graph → Function Graph\""));+ assert!(!src.contains("nyi(\"Graph → Function Call Graph\""));+ assert!(!src.contains("nyi(\"Graph → Function Call Trees\""));+ // Debugger menu is registered.+ assert!(src.contains("ui.menu_button(\"Debugger\","));+ // Launch is wired (not nyi).+ assert!(src.contains("open_launch_ui"));+ assert!(!src.contains("nyi(\"Debugger → Launch"));+ // Configure dialog + Save Tool Layout menu items are wired.+ assert!(src.contains("show_configure_dialog"));+ assert!(src.contains("show_layouts_dialog"));}}diff --git a/crates/ghidrust-gui/src/menu_actions.rs b/crates/ghidrust-gui/src/menu_actions.rsindex e6bc787..ac42753 100644--- a/crates/ghidrust-gui/src/menu_actions.rs+++ b/crates/ghidrust-gui/src/menu_actions.rs@@ -57,10 +57,7 @@ pub fn parse_address(s: &str) -> Result<u64, String> {/// Parse space/hex-digit memory pattern for Search → Memory./// Accepts "48 89 e5", "4889e5", "??" wildcards (byte = any).pub fn parse_hex_pattern(s: &str) -> Result<Vec<Option<u8>>, String> {- let cleaned: String = s- .chars()- .filter(|c| !c.is_whitespace())- .collect();+ let cleaned: String = s.chars().filter(|c| !c.is_whitespace()).collect();if cleaned.is_empty() {return Err("empty pattern".into());}@@ -147,7 +144,12 @@ pub struct TextHit {/// filter by numeric range. Ghidrust's Stage-0 decoder emits scalars as either/// `0x...` (hex) or decimal literals inside the operand string; both are/// picked up here.-pub fn search_scalars(listing: &[Instruction], min: i64, max: i64, max_hits: usize) -> Vec<TextHit> {+pub fn search_scalars(+ listing: &[Instruction],+ min: i64,+ max: i64,+ max_hits: usize,+) -> Vec<TextHit> {let mut hits = Vec::new();if max_hits == 0 || min > max {return hits;@@ -178,11 +180,12 @@ pub fn extract_scalars(operands: &str) -> Vec<i64> {while i < bytes.len() {let c = bytes[i] as char;// Handle negative-sign prefix, but only when it directly precedes a digit.- let (sign, start) = if c == '-' && i + 1 < bytes.len() && (bytes[i + 1] as char).is_ascii_digit() {- (-1i64, i + 1)- } else {- (1i64, i)- };+ let (sign, start) =+ if c == '-' && i + 1 < bytes.len() && (bytes[i + 1] as char).is_ascii_digit() {+ (-1i64, i + 1)+ } else {+ (1i64, i)+ };if bytes.get(start).copied() == Some(b'0')&& matches!(bytes.get(start + 1).copied(), Some(b'x') | Some(b'X')){@@ -361,9 +364,7 @@ pub fn listing_index_at_or_before(listing: &[Instruction], va: u64) -> Option<us}let first = listing[0].address;let last = listing.last().unwrap();- let window_end = last- .address- .saturating_add(u64::from(last.length).max(1));+ let window_end = last.address.saturating_add(u64::from(last.length).max(1));// Outside the loaded listing span → not a hit (do not fake index 0).if va < first || va >= window_end {return None;@@ -500,9 +501,13 @@ pub fn stage1_pseudo_c_with_tokens(max_insns: usize,) -> Result<(u64, String, f32, Vec<ghidrust_decomp::EmitToken>), String> {let entry = decompile_entry_for_va(prog, va);- let (_d, rep) =- ghidrust_decomp::decompile_stage1_at(prog, entry, max_insns, ghidrust_types::CallConv::Windows)- .map_err(|e| e.to_string())?;+ let (_d, rep) = ghidrust_decomp::decompile_stage1_at(+ prog,+ entry,+ max_insns,+ ghidrust_types::CallConv::Windows,+ )+ .map_err(|e| e.to_string())?;Ok((entry, rep.pseudo_c, rep.coverage.ratio(), rep.tokens))}@@ -515,8 +520,12 @@ pub fn pseudo_c_for_stage() -> Result<(u64, String, Option<f32>), String> {match stage {DecompStage::Stage0 => stage0_pseudo_c(prog, va, max_insns).map(|(e, t)| (e, t, None)),- DecompStage::Stage05 => stage05_pseudo_c(prog, va, max_insns).map(|(e, t, r)| (e, t, Some(r))),- DecompStage::Stage1 => stage1_pseudo_c(prog, va, max_insns).map(|(e, t, r)| (e, t, Some(r))),+ DecompStage::Stage05 => {+ stage05_pseudo_c(prog, va, max_insns).map(|(e, t, r)| (e, t, Some(r)))+ }+ DecompStage::Stage1 => {+ stage1_pseudo_c(prog, va, max_insns).map(|(e, t, r)| (e, t, Some(r)))+ }}}@@ -553,12 +562,9 @@ mod tests {#[test]fn search_program_text_finds_listing_or_name() {let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();- let listing = ghidrust_core::disassemble_range(- &prog,- prog.entry.unwrap_or(prog.image_base),- 32,- )- .unwrap_or_default();+ let listing =+ ghidrust_core::disassemble_range(&prog, prog.entry.unwrap_or(prog.image_base), 32)+ .unwrap_or_default();let hits = search_program_text(&prog, &listing, "push", true, 32);assert!(!hits.is_empty(), "expected push in listing");}@@ -675,7 +681,10 @@ mod tests {length: 1,},];- assert_eq!(search_instruction_patterns(&listing, "push", "", 8).len(), 1);+ assert_eq!(+ search_instruction_patterns(&listing, "push", "", 8).len(),+ 1+ );assert_eq!(search_instruction_patterns(&listing, "", "rbp", 8).len(), 1);assert_eq!(search_instruction_patterns(&listing, "ret", "", 8).len(), 1);assert!(search_instruction_patterns(&listing, "call", "", 8).is_empty());@@ -684,12 +693,14 @@ mod tests {#[test]fn address_table_hits_reflect_program_state() {let mut prog = load_path(fixture_path("tiny_x64.pe")).unwrap();- prog.analysis.address_tables.push(ghidrust_core::AddressTableInfo {- base: prog.image_base,- count: 2,- entries: vec![prog.image_base, prog.image_base + 8],- role: ghidrust_core::AddressTableRole::Unknown,- });+ prog.analysis+ .address_tables+ .push(ghidrust_core::AddressTableInfo {+ base: prog.image_base,+ count: 2,+ entries: vec![prog.image_base, prog.image_base + 8],+ role: ghidrust_core::AddressTableRole::Unknown,+ });let hits = address_table_hits(&prog);assert_eq!(hits.len(), 1);assert!(hits[0].text.contains("2 entries"));diff --git a/crates/ghidrust-gui/src/panes.rs b/crates/ghidrust-gui/src/panes.rsindex eeeb991..0881213 100644--- a/crates/ghidrust-gui/src/panes.rs+++ b/crates/ghidrust-gui/src/panes.rs@@ -28,6 +28,9 @@ pub enum PaneKind {DataTypeManager,DataTypePreview,DecompiledView, // Alias for main Decompiler; kept as tab in center+ CryptoCapabilities,+ CryptoConstants,+ Decrypt,DefinedData,DefinedStrings,DisassembledView,@@ -66,6 +69,7 @@ pub enum PaneKind {FileSystemBrowser,/// Spilled analysis artifact catalog + preview via `ghidrust_core::artifacts`.AnalysisArtifacts,+ RecoveredStrings,}impl PaneKind {@@ -89,7 +93,10 @@ impl PaneKind {PaneKind::ChecksumGenerator,PaneKind::CommentWindow,PaneKind::Console,+ PaneKind::CryptoCapabilities,+ PaneKind::CryptoConstants,PaneKind::DataTypePreview,+ PaneKind::Decrypt,PaneKind::DefinedData,PaneKind::DefinedStrings,PaneKind::DisassembledView,@@ -103,6 +110,7 @@ impl PaneKind {PaneKind::FunctionsWindow,PaneKind::MemoryMap,PaneKind::Python,+ PaneKind::RecoveredStrings,PaneKind::RegisterManager,PaneKind::RelocationTable,PaneKind::ScriptManager,@@ -130,6 +138,9 @@ impl PaneKind {PaneKind::DataTypeManager => "Data Type Manager",PaneKind::DataTypePreview => "Data Type Preview",PaneKind::DecompiledView => "Decompile",+ PaneKind::CryptoCapabilities => "Crypto Capabilities",+ PaneKind::CryptoConstants => "Crypto Constants",+ PaneKind::Decrypt => "Decrypt",PaneKind::DefinedData => "Defined Data",PaneKind::DefinedStrings => "Defined Strings",PaneKind::DisassembledView => "Disassembled View",@@ -147,6 +158,7 @@ impl PaneKind {PaneKind::ProgramTree => "Program Trees",PaneKind::ProjectTree => "Project Tree",PaneKind::Python => "Python",+ PaneKind::RecoveredStrings => "Recovered Strings",PaneKind::RegisterManager => "Register Manager",PaneKind::RelocationTable => "Relocation Table",PaneKind::ScriptManager => "Script Manager",@@ -183,6 +195,9 @@ impl PaneKind {PaneKind::DataTypeManager => "DataTypeManagerPlugin",PaneKind::DataTypePreview => "DataTypePreviewPlugin",PaneKind::DecompiledView => "DecompilePlugin",+ PaneKind::CryptoCapabilities => "CryptoCapabilitiesPlugin",+ PaneKind::CryptoConstants => "CryptConstantsPlugin",+ PaneKind::Decrypt => "DecryptPanePlugin",PaneKind::DefinedData => "DataWindowPlugin",PaneKind::DefinedStrings => "ViewStringsPlugin",PaneKind::DisassembledView => "DisassembledViewPlugin",@@ -200,6 +215,7 @@ impl PaneKind {PaneKind::ProgramTree => "ProgramTreePlugin",PaneKind::ProjectTree => "FrontEndTool",PaneKind::Python => "InterpreterPanelPlugin",+ PaneKind::RecoveredStrings => "RecoveredStringsPlugin",PaneKind::RegisterManager => "RegisterPlugin",PaneKind::RelocationTable => "RelocationTablePlugin",PaneKind::ScriptManager => "ScriptMgrPlugin",@@ -228,6 +244,10 @@ impl PaneKind {| PaneKind::SymbolTree| PaneKind::Console| PaneKind::DefinedStrings+ | PaneKind::CryptoConstants+ | PaneKind::RecoveredStrings+ | PaneKind::CryptoCapabilities+ | PaneKind::Decrypt| PaneKind::FunctionsWindow| PaneKind::MemoryMap| PaneKind::SymbolTable@@ -269,6 +289,9 @@ impl PaneKind {PaneKind::DataTypeManager => "pane_dtm_win",PaneKind::DataTypePreview => "pane_dtpreview",PaneKind::DecompiledView => "pane_decompile_win",+ PaneKind::CryptoCapabilities => "pane_crypto_capabilities",+ PaneKind::CryptoConstants => "pane_crypto_constants",+ PaneKind::Decrypt => "pane_decrypt",PaneKind::DefinedData => "pane_defined_data",PaneKind::DefinedStrings => "pane_defined_strings",PaneKind::DisassembledView => "pane_disasm_view",@@ -286,6 +309,7 @@ impl PaneKind {PaneKind::ProgramTree => "pane_program_tree_win",PaneKind::ProjectTree => "pane_project_tree_win",PaneKind::Python => "pane_python",+ PaneKind::RecoveredStrings => "pane_recovered_strings",PaneKind::RegisterManager => "pane_register_manager",PaneKind::RelocationTable => "pane_relocations",PaneKind::ScriptManager => "pane_script_manager",@@ -335,11 +359,11 @@ impl BookmarkKind {/// color for margin marker / row tint.pub fn color(self) -> Color32 {match self {- BookmarkKind::Note => Color32::from_rgb(0x9C, 0x27, 0xB0), // purple- BookmarkKind::Info => Color32::from_rgb(0x03, 0xA9, 0xF4), // cyan- BookmarkKind::Analysis => Color32::from_rgb(0xFF, 0x98, 0x00), // orange- BookmarkKind::Error => Color32::from_rgb(0xE5, 0x39, 0x35), // red- BookmarkKind::Warning => Color32::from_rgb(0xFB, 0xC0, 0x2D), // amber+ BookmarkKind::Note => Color32::from_rgb(0x9C, 0x27, 0xB0), // purple+ BookmarkKind::Info => Color32::from_rgb(0x03, 0xA9, 0xF4), // cyan+ BookmarkKind::Analysis => Color32::from_rgb(0xFF, 0x98, 0x00), // orange+ BookmarkKind::Error => Color32::from_rgb(0xE5, 0x39, 0x35), // red+ BookmarkKind::Warning => Color32::from_rgb(0xFB, 0xC0, 0x2D), // amber}}}@@ -356,9 +380,7 @@ pub struct Bookmark {/// Render "backend pending" empty state for a pane; used by any provider without backing data.pub fn empty_state(ui: &mut Ui, kind: PaneKind, muted: Color32) {ui.heading(kind.title());- ui.small(- RichText::new(format!("Provider · {}", kind.plugin())).color(muted),- );+ ui.small(RichText::new(format!("Provider · {}", kind.plugin())).color(muted));ui.separator();ui.add_space(4.0);ui.label(@@ -367,9 +389,14 @@ pub fn empty_state(ui: &mut Ui, kind: PaneKind, muted: Color32) {.italics(),);ui.add_space(4.0);- ui.small(RichText::new("Pane is present in the shell catalog. Backing analysis \+ ui.small(+ RichText::new(+ "Pane is present in the shell catalog. Backing analysis \and interactive actions land in later work — see \- internal UI notes.").color(muted));+ internal UI notes.",+ )+ .color(muted),+ );}/// One-liner hint pointing at which analyzer/model would fill this pane.@@ -384,6 +411,9 @@ pub const fn backend_pending_message(kind: PaneKind) -> &'static str {PaneKind::DataTypeManager => "Backend pending — DTM tree (Built-In / Program / Archive) lands in .",PaneKind::DataTypePreview => "",PaneKind::DecompiledView => "Stage-1 SSA-C (expression fold + typed locals/params). Emit-time tokens when available; rename/commit wired.",+ PaneKind::CryptoCapabilities => "",+ PaneKind::CryptoConstants => "",+ PaneKind::Decrypt => "",PaneKind::DefinedData => "Backend pending — Program::data_items model lands in .",PaneKind::DefinedStrings => "Uses ghidrust-core::analyzers::strings::run — session-only until Program::strings lands.",PaneKind::DisassembledView => "Backend pending — virtual disassembly + pcode preview lands in .",@@ -401,6 +431,7 @@ pub const fn backend_pending_message(kind: PaneKind) -> &'static str {PaneKind::ProgramTree => "",PaneKind::ProjectTree => "",PaneKind::Python => "Backend pending — scripting host / MCP REPL lands in .",+ PaneKind::RecoveredStrings => "",PaneKind::RegisterManager => "Backend pending — register lattice values from live/debug backends.",PaneKind::RelocationTable => "Uses Program::sections metadata; full PE/ELF reloc parse lands in .",PaneKind::ScriptManager => "Backend pending — script catalog lands in .",@@ -496,11 +527,7 @@ mod tests {#[test]fn off_layout_providers_present() {let names: Vec<&'static str> = PaneKind::ALL.iter().map(|k| k.title()).collect();- for expected in [- "Function Call Trees",- "Function Call Graph",- "Text Editor",- ] {+ for expected in ["Function Call Trees", "Function Call Graph", "Text Editor"] {assert!(names.contains(&expected),"missing off-layout provider `{expected}` in PaneKind::ALL"diff --git a/crates/ghidrust-gui/src/register_manager.rs b/crates/ghidrust-gui/src/register_manager.rsindex 42c9088..74d8a54 100644--- a/crates/ghidrust-gui/src/register_manager.rs+++ b/crates/ghidrust-gui/src/register_manager.rs@@ -86,10 +86,30 @@ const RAX: RegisterNode = RegisterNode {bits: 64,kind: RegisterKind::General,children: &[- RegisterNode { name: "EAX", bits: 32, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "AX", bits: 16, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "AH", bits: 8, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "AL", bits: 8, kind: RegisterKind::General, children: &[] },+ RegisterNode {+ name: "EAX",+ bits: 32,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "AX",+ bits: 16,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "AH",+ bits: 8,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "AL",+ bits: 8,+ kind: RegisterKind::General,+ children: &[],+ },],};const RBX: RegisterNode = RegisterNode {@@ -97,10 +117,30 @@ const RBX: RegisterNode = RegisterNode {bits: 64,kind: RegisterKind::General,children: &[- RegisterNode { name: "EBX", bits: 32, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "BX", bits: 16, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "BH", bits: 8, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "BL", bits: 8, kind: RegisterKind::General, children: &[] },+ RegisterNode {+ name: "EBX",+ bits: 32,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "BX",+ bits: 16,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "BH",+ bits: 8,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "BL",+ bits: 8,+ kind: RegisterKind::General,+ children: &[],+ },],};const RCX: RegisterNode = RegisterNode {@@ -108,10 +148,30 @@ const RCX: RegisterNode = RegisterNode {bits: 64,kind: RegisterKind::General,children: &[- RegisterNode { name: "ECX", bits: 32, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "CX", bits: 16, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "CH", bits: 8, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "CL", bits: 8, kind: RegisterKind::General, children: &[] },+ RegisterNode {+ name: "ECX",+ bits: 32,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "CX",+ bits: 16,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "CH",+ bits: 8,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "CL",+ bits: 8,+ kind: RegisterKind::General,+ children: &[],+ },],};const RDX: RegisterNode = RegisterNode {@@ -119,10 +179,30 @@ const RDX: RegisterNode = RegisterNode {bits: 64,kind: RegisterKind::General,children: &[- RegisterNode { name: "EDX", bits: 32, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "DX", bits: 16, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "DH", bits: 8, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "DL", bits: 8, kind: RegisterKind::General, children: &[] },+ RegisterNode {+ name: "EDX",+ bits: 32,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "DX",+ bits: 16,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "DH",+ bits: 8,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "DL",+ bits: 8,+ kind: RegisterKind::General,+ children: &[],+ },],};const RSI: RegisterNode = RegisterNode {@@ -130,9 +210,24 @@ const RSI: RegisterNode = RegisterNode {bits: 64,kind: RegisterKind::General,children: &[- RegisterNode { name: "ESI", bits: 32, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "SI", bits: 16, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "SIL", bits: 8, kind: RegisterKind::General, children: &[] },+ RegisterNode {+ name: "ESI",+ bits: 32,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "SI",+ bits: 16,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "SIL",+ bits: 8,+ kind: RegisterKind::General,+ children: &[],+ },],};const RDI: RegisterNode = RegisterNode {@@ -140,9 +235,24 @@ const RDI: RegisterNode = RegisterNode {bits: 64,kind: RegisterKind::General,children: &[- RegisterNode { name: "EDI", bits: 32, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "DI", bits: 16, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "DIL", bits: 8, kind: RegisterKind::General, children: &[] },+ RegisterNode {+ name: "EDI",+ bits: 32,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "DI",+ bits: 16,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "DIL",+ bits: 8,+ kind: RegisterKind::General,+ children: &[],+ },],};const RSP: RegisterNode = RegisterNode {@@ -150,9 +260,24 @@ const RSP: RegisterNode = RegisterNode {bits: 64,kind: RegisterKind::General,children: &[- RegisterNode { name: "ESP", bits: 32, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "SP", bits: 16, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "SPL", bits: 8, kind: RegisterKind::General, children: &[] },+ RegisterNode {+ name: "ESP",+ bits: 32,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "SP",+ bits: 16,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "SPL",+ bits: 8,+ kind: RegisterKind::General,+ children: &[],+ },],};const RBP: RegisterNode = RegisterNode {@@ -160,9 +285,24 @@ const RBP: RegisterNode = RegisterNode {bits: 64,kind: RegisterKind::General,children: &[- RegisterNode { name: "EBP", bits: 32, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "BP", bits: 16, kind: RegisterKind::General, children: &[] },- RegisterNode { name: "BPL", bits: 8, kind: RegisterKind::General, children: &[] },+ RegisterNode {+ name: "EBP",+ bits: 32,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "BP",+ bits: 16,+ kind: RegisterKind::General,+ children: &[],+ },+ RegisterNode {+ name: "BPL",+ bits: 8,+ kind: RegisterKind::General,+ children: &[],+ },],};@@ -172,14 +312,12 @@ macro_rules! rN {name: $name,bits: 64,kind: RegisterKind::General,- children: &[- RegisterNode {- name: $sub,- bits: 32,- kind: RegisterKind::General,- children: &[],- },- ],+ children: &[RegisterNode {+ name: $sub,+ bits: 32,+ kind: RegisterKind::General,+ children: &[],+ }],}};}@@ -218,13 +356,48 @@ pub const X86_64_REGISTERS: &[RegisterNode] = &[bits: 64,kind: RegisterKind::Flag,children: &[- RegisterNode { name: "CF", bits: 1, kind: RegisterKind::Flag, children: &[] },- RegisterNode { name: "PF", bits: 1, kind: RegisterKind::Flag, children: &[] },- RegisterNode { name: "AF", bits: 1, kind: RegisterKind::Flag, children: &[] },- RegisterNode { name: "ZF", bits: 1, kind: RegisterKind::Flag, children: &[] },- RegisterNode { name: "SF", bits: 1, kind: RegisterKind::Flag, children: &[] },- RegisterNode { name: "OF", bits: 1, kind: RegisterKind::Flag, children: &[] },- RegisterNode { name: "DF", bits: 1, kind: RegisterKind::Flag, children: &[] },+ RegisterNode {+ name: "CF",+ bits: 1,+ kind: RegisterKind::Flag,+ children: &[],+ },+ RegisterNode {+ name: "PF",+ bits: 1,+ kind: RegisterKind::Flag,+ children: &[],+ },+ RegisterNode {+ name: "AF",+ bits: 1,+ kind: RegisterKind::Flag,+ children: &[],+ },+ RegisterNode {+ name: "ZF",+ bits: 1,+ kind: RegisterKind::Flag,+ children: &[],+ },+ RegisterNode {+ name: "SF",+ bits: 1,+ kind: RegisterKind::Flag,+ children: &[],+ },+ RegisterNode {+ name: "OF",+ bits: 1,+ kind: RegisterKind::Flag,+ children: &[],+ },+ RegisterNode {+ name: "DF",+ bits: 1,+ kind: RegisterKind::Flag,+ children: &[],+ },],},RegisterNode {@@ -408,7 +581,12 @@ pub fn render(ui.label(egui::RichText::new("Set Register Value").strong());ui.horizontal(|ui| {ui.label("Register:");- ui.monospace(state.selected.clone().unwrap_or_else(|| "(pick above)".into()));+ ui.monospace(+ state+ .selected+ .clone()+ .unwrap_or_else(|| "(pick above)".into()),+ );});ui.horizontal(|ui| {ui.label("Start VA:");@@ -511,7 +689,11 @@ fn render_row(ui.add_space(indent);let is_sel = state.selected.as_deref() == Some(node.name);let text = egui::RichText::new(format!("{} {}b", node.name, node.bits)).monospace();- let text = if is_sel { text.color(primary).strong() } else { text };+ let text = if is_sel {+ text.color(primary).strong()+ } else {+ text+ };if ui.selectable_label(is_sel, text).clicked() {state.selected = Some(node.name.to_string());}@@ -523,7 +705,10 @@ fn render_row(fn parse_hex(s: &str) -> Option<u64> {let s = s.trim();- let s = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")).unwrap_or(s);+ let s = s+ .strip_prefix("0x")+ .or_else(|| s.strip_prefix("0X"))+ .unwrap_or(s);u64::from_str_radix(s, 16).ok()}@@ -534,7 +719,9 @@ mod tests {#[test]fn register_lattice_contains_expected_registers() {let names: Vec<&'static str> = X86_64_REGISTERS.iter().map(|r| r.name).collect();- for expected in ["RAX", "RBX", "RCX", "RDX", "RSP", "RBP", "RIP", "RFLAGS", "XMM0", "CR0"] {+ for expected in [+ "RAX", "RBX", "RCX", "RDX", "RSP", "RBP", "RIP", "RFLAGS", "XMM0", "CR0",+ ] {assert!(names.contains(&expected), "missing register {expected}");}}@@ -544,7 +731,10 @@ mod tests {let rax = X86_64_REGISTERS.iter().find(|r| r.name == "RAX").unwrap();let sub: Vec<&'static str> = rax.children.iter().map(|c| c.name).collect();for expected in ["EAX", "AX", "AH", "AL"] {- assert!(sub.contains(&expected), "RAX missing subregister {expected}");+ assert!(+ sub.contains(&expected),+ "RAX missing subregister {expected}"+ );}}diff --git a/crates/ghidrust-gui/src/scripts.rs b/crates/ghidrust-gui/src/scripts.rsindex 160c8f5..a55619f 100644--- a/crates/ghidrust-gui/src/scripts.rs+++ b/crates/ghidrust-gui/src/scripts.rs@@ -41,43 +41,216 @@ pub fn builtin_catalog() -> Vec<ScriptEntry> {key_binding: String::new(),};vec![- s("mcp.list_methods", "MCP · Functions", "Enumerate methods in the active program (paginated)."),- s("mcp.list_functions", "MCP · Functions", "List every recovered function entry."),- s("mcp.search_functions_by_name", "MCP · Functions", "Substring search over function names."),- s("mcp.decompile_function", "MCP · Decompiler", "Return pseudo-C for a named function."),- s("mcp.decompile_function_by_address", "MCP · Decompiler", "Return pseudo-C for a function at a VA."),- s("mcp.disassemble_function", "MCP · Decompiler", "Return decoded listing for a function."),- s("mcp.rename_function", "MCP · Edits", "Rename the function at a VA."),- s("mcp.rename_function_by_address", "MCP · Edits", "Rename by address."),- s("mcp.rename_variable", "MCP · Edits", "Rename a local variable inside a function."),- s("mcp.rename_data", "MCP · Edits", "Rename a global data item."),- s("mcp.set_function_prototype", "MCP · Edits", "Set the C signature of a function."),- s("mcp.set_local_variable_type", "MCP · Edits", "Retype a local variable."),- s("mcp.set_decompiler_comment", "MCP · Comments", "Attach a decompiler-side comment."),- s("mcp.set_disassembly_comment", "MCP · Comments", "Attach a listing-side comment."),- s("mcp.list_classes", "MCP · Program", "Enumerate C++/RTTI classes recovered."),- s("mcp.list_namespaces", "MCP · Program", "Enumerate scoped namespaces."),- s("mcp.list_segments", "MCP · Program", "Enumerate mapped memory blocks / sections."),- s("mcp.list_imports", "MCP · Program", "Enumerate PE import / IAT slots."),- s("mcp.list_exports", "MCP · Program", "Enumerate exported symbols."),- s("mcp.list_data_items", "MCP · Program", "Enumerate defined data items."),- s("mcp.list_strings", "MCP · Program", "ASCII/UTF-16 strings; match/limit/raw blob."),- s("mcp.search_strings", "MCP · Program", "Alias of list_strings (filter-oriented)."),- s("mcp.get_import_xrefs", "MCP · Xrefs", "Code sites referencing an import IAT slot."),- s("mcp.get_string_xrefs", "MCP · Xrefs", "Resolve strings by filter, then xrefs to each."),- s("mcp.get_xrefs_to", "MCP · Xrefs", "Refs to a VA; optional skip_stubs/classify."),- s("mcp.get_xrefs_from", "MCP · Xrefs", "References emitted from a VA."),- s("mcp.get_function_xrefs", "MCP · Xrefs", "Callers and callees of a function."),- s("mcp.il2cpp_meta", "MCP · IL2CPP", "Parse global-metadata.dat types/methods."),- s("mcp.il2cpp_map", "MCP · IL2CPP", "Metadata ↔ RVA map (null when unproven)."),- s("mcp.il2cpp_stubs", "MCP · IL2CPP", "List IL2CPP resolve stubs by icall name."),- s("mcp.unity_inventory", "MCP · Unity", "Player install inventory (assemblies, plugins, metadata)."),- s("mcp.function_at", "MCP · Functions", "Containing function for a body VA."),- s("mcp.function_create", "MCP · Functions", "Create/heal a function at VA (optional end)."),- s("mcp.decompile", "MCP · Decompile", "Stage-1 C; optional follow_stub for IL2CPP."),- s("mcp.get_current_address", "MCP · Cursor", "Report the currently focused Listing VA."),- s("mcp.get_current_function", "MCP · Cursor", "Report the function containing the cursor."),- s("mcp.get_function_by_address", "MCP · Functions", "Fetch function metadata by VA."),+ s(+ "mcp.list_methods",+ "MCP · Functions",+ "Enumerate methods in the active program (paginated).",+ ),+ s(+ "mcp.list_functions",+ "MCP · Functions",+ "List every recovered function entry.",+ ),+ s(+ "mcp.search_functions_by_name",+ "MCP · Functions",+ "Substring search over function names.",+ ),+ s(+ "mcp.decompile_function",+ "MCP · Decompiler",+ "Return pseudo-C for a named function.",+ ),+ s(+ "mcp.decompile_function_by_address",+ "MCP · Decompiler",+ "Return pseudo-C for a function at a VA.",+ ),+ s(+ "mcp.disassemble_function",+ "MCP · Decompiler",+ "Return decoded listing for a function.",+ ),+ s(+ "mcp.rename_function",+ "MCP · Edits",+ "Rename the function at a VA.",+ ),+ s(+ "mcp.rename_function_by_address",+ "MCP · Edits",+ "Rename by address.",+ ),+ s(+ "mcp.rename_variable",+ "MCP · Edits",+ "Rename a local variable inside a function.",+ ),+ s(+ "mcp.rename_data",+ "MCP · Edits",+ "Rename a global data item.",+ ),+ s(+ "mcp.set_function_prototype",+ "MCP · Edits",+ "Set the C signature of a function.",+ ),+ s(+ "mcp.set_local_variable_type",+ "MCP · Edits",+ "Retype a local variable.",+ ),+ s(+ "mcp.set_decompiler_comment",+ "MCP · Comments",+ "Attach a decompiler-side comment.",+ ),+ s(+ "mcp.set_disassembly_comment",+ "MCP · Comments",+ "Attach a listing-side comment.",+ ),+ s(+ "mcp.list_classes",+ "MCP · Program",+ "Enumerate C++/RTTI classes recovered.",+ ),+ s(+ "mcp.list_namespaces",+ "MCP · Program",+ "Enumerate scoped namespaces.",+ ),+ s(+ "mcp.list_segments",+ "MCP · Program",+ "Enumerate mapped memory blocks / sections.",+ ),+ s(+ "mcp.list_imports",+ "MCP · Program",+ "Enumerate PE import / IAT slots.",+ ),+ s(+ "mcp.list_exports",+ "MCP · Program",+ "Enumerate exported symbols.",+ ),+ s(+ "mcp.list_data_items",+ "MCP · Program",+ "Enumerate defined data items.",+ ),+ s(+ "mcp.list_strings",+ "MCP · Program",+ "ASCII/UTF-16 strings; match/limit/raw blob.",+ ),+ s(+ "mcp.search_strings",+ "MCP · Program",+ "Alias of list_strings (filter-oriented).",+ ),+ s(+ "mcp.get_import_xrefs",+ "MCP · Xrefs",+ "Code sites referencing an import IAT slot.",+ ),+ s(+ "mcp.get_string_xrefs",+ "MCP · Xrefs",+ "Resolve strings by filter, then xrefs to each.",+ ),+ s(+ "mcp.get_xrefs_to",+ "MCP · Xrefs",+ "Refs to a VA; optional skip_stubs/classify.",+ ),+ s(+ "mcp.get_xrefs_from",+ "MCP · Xrefs",+ "References emitted from a VA.",+ ),+ s(+ "mcp.get_function_xrefs",+ "MCP · Xrefs",+ "Callers and callees of a function.",+ ),+ s(+ "mcp.il2cpp_meta",+ "MCP · IL2CPP",+ "Parse global-metadata.dat types/methods.",+ ),+ s(+ "mcp.il2cpp_map",+ "MCP · IL2CPP",+ "Metadata ↔ RVA map (null when unproven).",+ ),+ s(+ "mcp.il2cpp_stubs",+ "MCP · IL2CPP",+ "List IL2CPP resolve stubs by icall name.",+ ),+ s(+ "mcp.unity_inventory",+ "MCP · Unity",+ "Player install inventory (assemblies, plugins, metadata).",+ ),+ s(+ "mcp.function_at",+ "MCP · Functions",+ "Containing function for a body VA.",+ ),+ s(+ "mcp.function_create",+ "MCP · Functions",+ "Create/heal a function at VA (optional end).",+ ),+ s(+ "mcp.decompile",+ "MCP · Decompile",+ "Stage-1 C; optional follow_stub for IL2CPP.",+ ),+ s(+ "mcp.get_current_address",+ "MCP · Cursor",+ "Report the currently focused Listing VA.",+ ),+ s(+ "mcp.get_current_function",+ "MCP · Cursor",+ "Report the function containing the cursor.",+ ),+ s(+ "mcp.get_function_by_address",+ "MCP · Functions",+ "Fetch function metadata by VA.",+ ),+ s(+ "crypt_constants",+ "MCP · Crypto",+ "Crypto Constants constant-table hits.",+ ),+ s(+ "recover_strings",+ "MCP · Crypto",+ "Recover obfuscated strings, optionally scoped to functions.",+ ),+ s(+ "decode_bake",+ "MCP · Crypto",+ "Bake explicit decode operations over input bytes.",+ ),+ s(+ "decode_magic",+ "MCP · Crypto",+ "Suggest and apply a decode recipe from input bytes.",+ ),+ s(+ "list_crypto_capabilities",+ "MCP · Crypto",+ "List detected cryptographic capabilities.",+ ),]}@@ -235,11 +408,7 @@ pub fn render_script_manager();ui.separator();- let mut categories: Vec<String> = state- .catalog- .iter()- .map(|s| s.category.clone())- .collect();+ let mut categories: Vec<String> = state.catalog.iter().map(|s| s.category.clone()).collect();categories.sort();categories.dedup();@@ -300,7 +469,11 @@ pub fn render_script_manager(for (idx, s) in &rows {let is_sel = state.selected == Some(*idx);let name_text = egui::RichText::new(&s.name).monospace();- let name_text = if is_sel { name_text.color(primary) } else { name_text };+ let name_text = if is_sel {+ name_text.color(primary)+ } else {+ name_text+ };if ui.selectable_label(is_sel, name_text).clicked() {state.selected = Some(*idx);}@@ -352,7 +525,8 @@ pub fn render_text_editor() -> TextEditorRequest {ui.heading("Text Editor");ui.small(- egui::RichText::new("Text Editor · in-memory tabs on top of the local filesystem").color(muted),+ egui::RichText::new("Text Editor · in-memory tabs on top of the local filesystem")+ .color(muted),);ui.separator();@@ -438,11 +612,14 @@ pub fn render_text_editor(}/// Render the MCP REPL.-pub fn render_mcp_repl(state: &mut MacropadReplState, ui: &mut Ui, muted: Color32, primary: Color32) {+pub fn render_mcp_repl(+ state: &mut MacropadReplState,+ ui: &mut Ui,+ muted: Color32,+ primary: Color32,+) {ui.heading("Python (MCP REPL)");- ui.small(- egui::RichText::new("MCP REPL · pipes to ghidrust mcp (stub)").color(muted),- );+ ui.small(egui::RichText::new("MCP REPL · pipes to ghidrust mcp (stub)").color(muted));ui.separator();egui::ScrollArea::vertical()@@ -488,6 +665,11 @@ mod tests {"mcp.decompile_function","mcp.rename_function","mcp.get_xrefs_to",+ "crypt_constants",+ "recover_strings",+ "decode_bake",+ "decode_magic",+ "list_crypto_capabilities",] {assert!(cat.iter().any(|s| s.name == want), "missing {want}");}diff --git a/crates/ghidrust-gui/src/tool_panes.rs b/crates/ghidrust-gui/src/tool_panes.rsindex fb66673..f66665f 100644--- a/crates/ghidrust-gui/src/tool_panes.rs+++ b/crates/ghidrust-gui/src/tool_panes.rs@@ -330,11 +330,13 @@ pub fn ui_il2cpp_methods(.show_rows(ui, row_h, rows.len(), |ui, range| {for i in range {let e = rows[i];- let va = e- .va- .map(|v| format!("{v:#x}"))- .unwrap_or_else(|| "unresolved".into());- ui.monospace(format!("idx={} tok={:#x} va={va} {}", e.method_index, e.token, e.full_name));+ let va =+ e.va.map(|v| format!("{v:#x}"))+ .unwrap_or_else(|| "unresolved".into());+ ui.monospace(format!(+ "idx={} tok={:#x} va={va} {}",+ e.method_index, e.token, e.full_name+ ));}});}@@ -451,21 +453,20 @@ pub fn ui_il2cpp_icalls(.show_rows(ui, row_h, hits.len(), |ui, range| {for i in range {let (ti, e) = &hits[i];- ui.monospace(format!(- "[table {ti}] fn={:#x} {}",- e.fn_va, e.name- ));+ ui.monospace(format!("[table {ti}] fn={:#x} {}", e.fn_va, e.name));}});if !report.tables.is_empty() {- egui::CollapsingHeader::new("Tables").default_open(false).show(ui, |ui| {- for (i, t) in report.tables.iter().enumerate() {- ui.monospace(format!(- "[{i}] name_va={:#x} fn_va={:#x} count={} layout={:?} confidence={:.2}",- t.name_va, t.fn_va, t.count, t.layout, t.confidence- ));- }- });+ egui::CollapsingHeader::new("Tables")+ .default_open(false)+ .show(ui, |ui| {+ for (i, t) in report.tables.iter().enumerate() {+ ui.monospace(format!(+ "[{i}] name_va={:#x} fn_va={:#x} count={} layout={:?} confidence={:.2}",+ t.name_va, t.fn_va, t.count, t.layout, t.confidence+ ));+ }+ });}}@@ -653,7 +654,10 @@ pub fn ui_file_system_browser(ui: &mut Ui, s: &mut FileSystemBrowserState, muted.hint_text("folder to browse…"),);if ui.button("Browse…").clicked() {- if let Some(p) = rfd::FileDialog::new().set_title("Select folder").pick_folder() {+ if let Some(p) = rfd::FileDialog::new()+ .set_title("Select folder")+ .pick_folder()+ {s.root_input = p.display().to_string();}}@@ -685,7 +689,11 @@ pub fn ui_file_system_browser(ui: &mut Ui, s: &mut FileSystemBrowserState, muted.map(|e| e.trim().to_string()).filter(|e| !e.is_empty()).collect();- if list.is_empty() { None } else { Some(list) }+ if list.is_empty() {+ None+ } else {+ Some(list)+ }};let name_glob = if s.name_glob_input.trim().is_empty() {None@@ -746,10 +754,7 @@ pub fn ui_file_system_browser(ui: &mut Ui, s: &mut FileSystemBrowserState, mutedfor i in range {let e = rows[i];let kind = if e.is_dir { "DIR " } else { "FILE" };- let size = e- .size- .map(|n| format!("{n}"))- .unwrap_or_else(|| "-".into());+ let size = e.size.map(|n| format!("{n}")).unwrap_or_else(|| "-".into());let err = e.error.as_deref()@@ -789,10 +794,8 @@ impl Default for AnalysisArtifactsState {pub fn ui_analysis_artifacts(ui: &mut Ui, s: &mut AnalysisArtifactsState, muted: Color32) {ui.heading("Analysis Artifacts");ui.small(- RichText::new(- "ghidrust-core::artifacts · spilled MCP/CLI result catalog + paged preview",- )- .color(muted),+ RichText::new("ghidrust-core::artifacts · spilled MCP/CLI result catalog + paged preview")+ .color(muted),);ui.separator();if !s.loaded_once {@@ -852,15 +855,21 @@ pub fn ui_analysis_artifacts(ui: &mut Ui, s: &mut AnalysisArtifactsState, muted:));let can_prev = s.offset >= s.limit;let next_offset = env.next_offset;- let mut pretty = serde_json::to_string_pretty(&env.preview)- .unwrap_or_else(|_| "<unprintable>".into());+ let mut pretty =+ serde_json::to_string_pretty(&env.preview).unwrap_or_else(|_| "<unprintable>".into());let mut go_prev = false;let mut go_next = false;cols[1].horizontal(|ui| {- if ui.add_enabled(can_prev, egui::Button::new("← Prev page")).clicked() {+ if ui+ .add_enabled(can_prev, egui::Button::new("← Prev page"))+ .clicked()+ {go_prev = true;}- if ui.add_enabled(next_offset.is_some(), egui::Button::new("Next page →")).clicked() {+ if ui+ .add_enabled(next_offset.is_some(), egui::Button::new("Next page →"))+ .clicked()+ {go_next = true;}});@@ -944,7 +953,11 @@ pub struct GpuDecompileSummary {/// Render the GPU Decompile dialog body (window chrome + the resolve/decompile/// call itself are owned by the caller in `main.rs`, since both need a mutable/// borrow of the live `Program` that this module does not hold).-pub fn ui_gpu_decompile_dialog_header(ui: &mut Ui, s: &mut GpuDecompileDialogState, muted: Color32) {+pub fn ui_gpu_decompile_dialog_header(+ ui: &mut Ui,+ s: &mut GpuDecompileDialogState,+ muted: Color32,+) {ui.small(RichText::new("ghidrust_decomp::gpu_decompile_to_file · GPU pipeline with automatic CPU multipass fallback",diff --git a/crates/ghidrust-il2cpp/src/binary.rs b/crates/ghidrust-il2cpp/src/binary.rsindex 5b428dd..5af42bf 100644--- a/crates/ghidrust-il2cpp/src/binary.rs+++ b/crates/ghidrust-il2cpp/src/binary.rs@@ -182,7 +182,10 @@ pub fn compare_baseline(current: &MethodMap, baseline: &MethodMap) -> BuildSkewlet mut missing = Vec::new();for e in &baseline.entries {if !cur_by_name.contains_key(e.full_name.as_str())- && !current.entries.iter().any(|c| c.method_index == e.method_index)+ && !current+ .entries+ .iter()+ .any(|c| c.method_index == e.method_index){missing.push(SkewName {full_name: e.full_name.clone(),@@ -256,9 +259,7 @@ fn find_method_pointers(prog: &Program, notes: &mut Vec<String>) -> Option<Vec<up.len()));} else {- notes.push(- "no multi-field-validated method pointer array found; RVAs left null".into(),- );+ notes.push("no multi-field-validated method pointer array found; RVAs left null".into());}best}diff --git a/crates/ghidrust-il2cpp/src/body.rs b/crates/ghidrust-il2cpp/src/body.rsindex a22c371..42f8bfe 100644--- a/crates/ghidrust-il2cpp/src/body.rs+++ b/crates/ghidrust-il2cpp/src/body.rs@@ -63,7 +63,10 @@ pub fn fingerprint_body(prog: &Program, va: u64) -> BodyFingerprint {};}- let prologue_hash = format!("{:04x}", crc16_ccitt(&bytes[..bytes.len().min(PROLOGUE_BYTES)]));+ let prologue_hash = format!(+ "{:04x}",+ crc16_ccitt(&bytes[..bytes.len().min(PROLOGUE_BYTES)])+ );// Resolve-stub with empty slot → runtime_unresolved (separate from thin thunk).if let Some(stub) = classify_at(prog, va) {@@ -123,7 +126,13 @@ pub fn semantics_mismatch(name: &str, body_class: BodyClass) -> bool {|| leaf_l.starts_with("set_")|| leaf_l.starts_with("is")|| leaf_l.starts_with("has")- || leaf_l.starts_with("get") && leaf.len() > 3 && leaf.as_bytes().get(3).map(|c| c.is_ascii_uppercase()).unwrap_or(false);+ || leaf_l.starts_with("get")+ && leaf.len() > 3+ && leaf+ .as_bytes()+ .get(3)+ .map(|c| c.is_ascii_uppercase())+ .unwrap_or(false);if !looks_accessor {return false;@@ -142,7 +151,9 @@ pub fn semantics_mismatch(name: &str, body_class: BodyClass) -> bool {////// Updates `entries` in place: when ≥2 methods share the same tiny prologue/// (or the same VA), promote `body_class` to `shared_stub` and set alias counts.-pub fn collapse_shared_stubs(entries: &mut [crate::binary::MethodMapEntry]) -> Vec<SharedStubSummary> {+pub fn collapse_shared_stubs(+ entries: &mut [crate::binary::MethodMapEntry],+) -> Vec<SharedStubSummary> {// Group by (prologue_hash) for tiny bodies, and by VA for identical pointers.let mut by_hash: HashMap<String, Vec<usize>> = HashMap::new();let mut by_va: HashMap<u64, Vec<usize>> = HashMap::new();@@ -150,7 +161,9 @@ pub fn collapse_shared_stubs(entries: &mut [crate::binary::MethodMapEntry]) -> Vfor (i, e) in entries.iter().enumerate() {let Some(va) = e.va else { continue };by_va.entry(va).or_default().push(i);- let Some(hash) = e.prologue_hash.as_ref() else { continue };+ let Some(hash) = e.prologue_hash.as_ref() else {+ continue;+ };if hash.is_empty() {continue;}@@ -189,16 +202,16 @@ pub fn collapse_shared_stubs(entries: &mut [crate::binary::MethodMapEntry]) -> Vcontinue;}let alias_count = idxs.len();- let hash = entries[idxs[0]]- .prologue_hash- .clone()- .unwrap_or_default();+ let hash = entries[idxs[0]].prologue_hash.clone().unwrap_or_default();let sample: Vec<String> = idxs.iter().take(4).map(|&i| entries[i].full_name.clone()).collect();- let promote = entries[idxs[0]].body_class.map(is_collapsible).unwrap_or(false);+ let promote = entries[idxs[0]]+ .body_class+ .map(is_collapsible)+ .unwrap_or(false);for &i in idxs {entries[i].alias_count = Some(alias_count);if promote {@@ -258,7 +271,11 @@ pub fn collapse_shared_stubs(entries: &mut [crate::binary::MethodMapEntry]) -> V}}- summaries.sort_by(|a, b| b.alias_count.cmp(&a.alias_count).then(a.target.cmp(&b.target)));+ summaries.sort_by(|a, b| {+ b.alias_count+ .cmp(&a.alias_count)+ .then(a.target.cmp(&b.target))+ });summaries}@@ -280,7 +297,11 @@ fn is_empty_xor_ret(bytes: &[u8]) -> bool {let a = bytes[0];let b = bytes[1];let c = bytes[2];- if c == 0xc3 && matches!((a, b), (0x30, 0xc0) | (0x31, 0xc0) | (0x33, 0xc0) | (0x31, 0xd2) | (0x33, 0xd2))+ if c == 0xc3+ && matches!(+ (a, b),+ (0x30, 0xc0) | (0x31, 0xc0) | (0x33, 0xc0) | (0x31, 0xd2) | (0x33, 0xd2)+ ){return true;}@@ -288,7 +309,10 @@ fn is_empty_xor_ret(bytes: &[u8]) -> bool {if bytes.len() >= 4 && bytes[0] == 0x48 && bytes[3] == 0xc3 {let b = bytes[1];let c = bytes[2];- if matches!((b, c), (0x31, 0xc0) | (0x33, 0xc0) | (0x31, 0xd2) | (0x33, 0xd2)) {+ if matches!(+ (b, c),+ (0x31, 0xc0) | (0x33, 0xc0) | (0x31, 0xd2) | (0x33, 0xd2)+ ) {return true;}}@@ -361,9 +385,25 @@ fn is_reg_only(ops: &str) -> bool {let o = ops.trim();matches!(o,- "rax" | "rcx" | "rdx" | "rbx" | "rsp" | "rbp" | "rsi" | "rdi"- | "r8" | "r9" | "r10" | "r11" | "r12" | "r13" | "r14" | "r15"- | "eax" | "ecx" | "edx"+ "rax"+ | "rcx"+ | "rdx"+ | "rbx"+ | "rsp"+ | "rbp"+ | "rsi"+ | "rdi"+ | "r8"+ | "r9"+ | "r10"+ | "r11"+ | "r12"+ | "r13"+ | "r14"+ | "r15"+ | "eax"+ | "ecx"+ | "edx")}@@ -493,7 +533,10 @@ mod tests {#[test]fn semantics_mismatch_getter_empty() {- assert!(semantics_mismatch("Foo::get_main", BodyClass::EmptyXorAlRet));+ assert!(semantics_mismatch(+ "Foo::get_main",+ BodyClass::EmptyXorAlRet+ ));assert!(semantics_mismatch("isReady", BodyClass::ThinThunk));assert!(semantics_mismatch("hasFlag", BodyClass::SharedStub));assert!(!semantics_mismatch("Update", BodyClass::EmptyXorAlRet));diff --git a/crates/ghidrust-il2cpp/src/error.rs b/crates/ghidrust-il2cpp/src/error.rsindex a18203b..f0a2f27 100644--- a/crates/ghidrust-il2cpp/src/error.rs+++ b/crates/ghidrust-il2cpp/src/error.rs@@ -32,9 +32,10 @@ impl Error {/// Structured JSON for this error when it is encrypt/obfuscate; otherwise null.pub fn to_structured_json(&self) -> Option<Value> {match self {- Error::EncryptedOrObfuscated { magic, version_field } => {- Some(Self::encrypted_json(*magic, *version_field))- }+ Error::EncryptedOrObfuscated {+ magic,+ version_field,+ } => Some(Self::encrypted_json(*magic, *version_field)),_ => None,}}@@ -72,7 +73,11 @@ mod tests {assert_eq!(v["magic"], "0xdeadbeef");let steps = v["next_steps"].as_array().expect("next_steps");assert!(steps.len() >= 3);- assert!(steps.iter().any(|s| s.as_str().unwrap_or("").contains("il2cpp icalls")));- assert!(steps.iter().any(|s| s.as_str().unwrap_or("").contains("touch-map")));+ assert!(steps+ .iter()+ .any(|s| s.as_str().unwrap_or("").contains("il2cpp icalls")));+ assert!(steps+ .iter()+ .any(|s| s.as_str().unwrap_or("").contains("touch-map")));}}diff --git a/crates/ghidrust-il2cpp/src/icall.rs b/crates/ghidrust-il2cpp/src/icall.rsindex 66677b0..4cece7e 100644--- a/crates/ghidrust-il2cpp/src/icall.rs+++ b/crates/ghidrust-il2cpp/src/icall.rs@@ -190,7 +190,15 @@ fn read_icall_name(prog: &Program, va: u64) -> Option<String> {}let s = std::str::from_utf8(&bytes[..end]).ok()?;if !s.chars().all(|c| {- c.is_ascii_graphic() || c == ' ' || c == ':' || c == '_' || c == '.' || c == '&' || c == '(' || c == ')' || c == ','+ c.is_ascii_graphic()+ || c == ' '+ || c == ':'+ || c == '_'+ || c == '.'+ || c == '&'+ || c == '('+ || c == ')'+ || c == ','}) {return None;}diff --git a/crates/ghidrust-il2cpp/src/lib.rs b/crates/ghidrust-il2cpp/src/lib.rsindex 6d78dfa..62a0d4f 100644--- a/crates/ghidrust-il2cpp/src/lib.rs+++ b/crates/ghidrust-il2cpp/src/lib.rs@@ -21,8 +21,8 @@ pub use body::{};pub use error::{Error, Result, ENCRYPTED_METADATA_NEXT_STEPS};pub use icall::{- filter_entries, resolve_icalls, resolve_icalls_path, ICallEntry, ICallResolveReport, ICallTable,- ICallTableLayout,+ filter_entries, resolve_icalls, resolve_icalls_path, ICallEntry, ICallResolveReport,+ ICallTable, ICallTableLayout,};pub use metadata::{build_synthetic, build_synthetic_v31, load_from_meta_sections_dir, load_metadata_flexible,diff --git a/crates/ghidrust-il2cpp/src/metadata.rs b/crates/ghidrust-il2cpp/src/metadata.rsindex 2e37c6c..06400d3 100644--- a/crates/ghidrust-il2cpp/src/metadata.rs+++ b/crates/ghidrust-il2cpp/src/metadata.rs@@ -162,7 +162,12 @@ impl Il2CppMetadata {}let dialect = MetadataDialect::from_version(version)?;let header = parse_header(data, version, dialect)?;- validate_table(data, header.string_offset, header.string_size, "string heap")?;+ validate_table(+ data,+ header.string_offset,+ header.string_size,+ "string heap",+ )?;validate_table(data,header.type_definitions_offset,@@ -654,7 +659,10 @@ mod tests {let meta = Il2CppMetadata::parse(&bytes).expect("parse");assert_eq!(meta.header.version, 31);assert_eq!(meta.header.dialect, MetadataDialect::V31);- assert!(meta.types.iter().any(|t| t.full_name() == "UnityEngine.Camera"));+ assert!(meta+ .types+ .iter()+ .any(|t| t.full_name() == "UnityEngine.Camera"));assert!(meta.methods.iter()@@ -678,6 +686,9 @@ mod tests {bytes[4..8].copy_from_slice(&106i32.to_le_bytes());// magic still valid but version unsupportedlet err = Il2CppMetadata::parse(&bytes).unwrap_err();- assert!(matches!(err, Error::UnsupportedVersion { version: 106, .. }));+ assert!(matches!(+ err,+ Error::UnsupportedVersion { version: 106, .. }+ ));}}diff --git a/crates/ghidrust-il2cpp/src/stubs.rs b/crates/ghidrust-il2cpp/src/stubs.rsindex 1fd09f0..3cede23 100644--- a/crates/ghidrust-il2cpp/src/stubs.rs+++ b/crates/ghidrust-il2cpp/src/stubs.rs@@ -58,7 +58,10 @@ pub fn classify_at(prog: &Program, entry: u64) -> Option<ResolveStub> {if m == "call" {has_call = true;}- if (m == "mov" || m == "movabs") && ops.contains('[') && (ops.contains("rax") || ops.contains("eax")) {+ if (m == "mov" || m == "movabs")+ && ops.contains('[')+ && (ops.contains("rax") || ops.contains("eax"))+ {has_store = true;for t in ghidrust_core::rip_relative_targets(insn) {slot_va = Some(t);@@ -202,8 +205,8 @@ fn read_c_string(prog: &Program, va: u64) -> Option<String> {#[cfg(test)]mod tests {use super::*;- use ghidrust_core::program::{MemoryBlock, Program};use ghidrust_core::load_path;+ use ghidrust_core::program::{MemoryBlock, Program};use std::path::PathBuf;#[test]@@ -277,11 +280,7 @@ mod tests {let stub = classify_at(&prog, text_va).expect("stub");assert_eq!(stub.kind, Il2CppKind::ResolveStub);- assert!(stub- .icall_name- .as_deref()- .unwrap_or("")- .contains("Camera"));+ assert!(stub.icall_name.as_deref().unwrap_or("").contains("Camera"));assert!(follow_stub_target(&prog, &stub).is_none());assert!(stub_matches_filter(&prog, &stub, "Camera"));}diff --git a/crates/ghidrust-il2cpp/src/touch_map.rs b/crates/ghidrust-il2cpp/src/touch_map.rsindex 18ca3f8..209831c 100644--- a/crates/ghidrust-il2cpp/src/touch_map.rs+++ b/crates/ghidrust-il2cpp/src/touch_map.rs@@ -111,7 +111,9 @@ pub fn build_touch_map(}let (rva, va, conf, note) = match map_by_idx.get(&m.index) {Some(e) if e.rva.is_some() => {- let note = e.body_class.map(|c| format!("body_class={}", body_class_str(c)));+ let note = e+ .body_class+ .map(|c| format!("body_class={}", body_class_str(c)));(e.rva, e.va, TouchConfidence::RvaBound, note)}Some(_) => (@@ -136,9 +138,10 @@ pub fn build_touch_map(for t in meta.filter_types(filter) {let full = t.full_name();- if rows.iter().any(|r| {- r.kind == TouchKind::Type && r.full_name.as_deref() == Some(full.as_str())- }) {+ if rows+ .iter()+ .any(|r| r.kind == TouchKind::Type && r.full_name.as_deref() == Some(full.as_str()))+ {continue;}rows.push(TouchMapRow {@@ -268,11 +271,9 @@ mod tests {let meta = Il2CppMetadata::parse(&bytes).unwrap();let report = build_touch_map(&meta, "Camera", None);assert!(report.row_count >= 1);- assert!(report.rows.iter().any(|r| {- r.full_name- .as_deref()- .unwrap_or("")- .contains("Camera")- }));+ assert!(report+ .rows+ .iter()+ .any(|r| { r.full_name.as_deref().unwrap_or("").contains("Camera") }));}}diff --git a/crates/ghidrust-ir/src/lib.rs b/crates/ghidrust-ir/src/lib.rsindex 6827ed8..f1d5522 100644--- a/crates/ghidrust-ir/src/lib.rs+++ b/crates/ghidrust-ir/src/lib.rs@@ -234,7 +234,11 @@ pub struct AddressedOp {impl AddressedOp {pub fn new(address: u64, length: u8, op: PcodeOp) -> Self {- Self { address, length, op }+ Self {+ address,+ length,+ op,+ }}}diff --git a/crates/ghidrust-lift/src/lib.rs b/crates/ghidrust-lift/src/lib.rsindex 2636127..b952bcc 100644--- a/crates/ghidrust-lift/src/lib.rs+++ b/crates/ghidrust-lift/src/lib.rs@@ -178,7 +178,10 @@ fn parse_imm(s: &str) -> Option<u64> {}fn split_operands(ops: &str) -> Vec<&str> {- ops.split(',').map(str::trim).filter(|s| !s.is_empty()).collect()+ ops.split(',')+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .collect()}/// Parsed memory operand. `[seg:]base+index*scale±disp` — supports SIB.@@ -425,7 +428,11 @@ fn jcc_condition(mnem: &str, unique_id: &mut u64) -> (Vec<PcodeOp>, Varnode) {"ja" => {let mid = Varnode::unique(*unique_id, 1);*unique_id += 1;- ops.push(PcodeOp::new(OpCode::BoolOr, Some(mid.clone()), vec![cf(), zf()]));+ ops.push(PcodeOp::new(+ OpCode::BoolOr,+ Some(mid.clone()),+ vec![cf(), zf()],+ ));ops.push(PcodeOp::new(OpCode::BoolNegate, Some(out.clone()), vec![mid]).with_note(mnem),);@@ -460,7 +467,11 @@ fn jcc_condition(mnem: &str, unique_id: &mut u64) -> (Vec<PcodeOp>, Varnode) {// we introduce more flag algebra.let sfof = Varnode::unique(*unique_id, 1);*unique_id += 1;- ops.push(PcodeOp::new(OpCode::IntNotEqual, Some(sfof.clone()), vec![sf(), of()]));+ ops.push(PcodeOp::new(+ OpCode::IntNotEqual,+ Some(sfof.clone()),+ vec![sf(), of()],+ ));match mnem {"jl" => {ops.push(@@ -482,7 +493,11 @@ fn jcc_condition(mnem: &str, unique_id: &mut u64) -> (Vec<PcodeOp>, Varnode) {"jg" => {let m = Varnode::unique(*unique_id, 1);*unique_id += 1;- ops.push(PcodeOp::new(OpCode::BoolOr, Some(m.clone()), vec![sfof, zf()]));+ ops.push(PcodeOp::new(+ OpCode::BoolOr,+ Some(m.clone()),+ vec![sfof, zf()],+ ));ops.push(PcodeOp::new(OpCode::BoolNegate, Some(out.clone()), vec![m]).with_note(mnem),@@ -515,7 +530,12 @@ impl LiftCtx {}}-fn mem_address_ops(ctx: &mut LiftCtx, mem: &MemOperand, insn_addr: u64, insn_len: u8) -> (Vec<PcodeOp>, Varnode) {+fn mem_address_ops(+ ctx: &mut LiftCtx,+ mem: &MemOperand,+ insn_addr: u64,+ insn_len: u8,+) -> (Vec<PcodeOp>, Varnode) {let mut ops = Vec::new();let addr_size = 8u32;if mem.rip_relative {@@ -568,12 +588,21 @@ fn mem_address_ops(ctx: &mut LiftCtx, mem: &MemOperand, insn_addr: u64, insn_lenops.push(PcodeOp::new(OpCode::IntAdd,Some(out.clone()),- vec![running, Varnode::constant(mem.displacement as u64, addr_size)],+ vec![+ running,+ Varnode::constant(mem.displacement as u64, addr_size),+ ],));(ops, out)}-fn load_from(ctx: &mut LiftCtx, mem: &MemOperand, size: u32, insn_addr: u64, insn_len: u8) -> (Vec<PcodeOp>, Varnode) {+fn load_from(+ ctx: &mut LiftCtx,+ mem: &MemOperand,+ size: u32,+ insn_addr: u64,+ insn_len: u8,+) -> (Vec<PcodeOp>, Varnode) {let (mut ops, addr) = mem_address_ops(ctx, mem, insn_addr, insn_len);let out = ctx.take_unique(size);ops.push(PcodeOp::new(OpCode::Load, Some(out.clone()), vec![addr]));@@ -598,13 +627,15 @@ fn lift_arith_flags(dst: Varnode, opcode: OpCode) -> Vec<PcodeOp> {let width = dst.size;let zero = Varnode::constant(0, width);let mut out = Vec::new();- out.push(PcodeOp::new(OpCode::IntEqual, Some(zf()), vec![dst.clone(), zero]).with_note(- match opcode {- OpCode::IntSub => "cmp/sub sets zf",- OpCode::IntAnd => "test/and sets zf",- _ => "arith sets zf",- },- ));+ out.push(+ PcodeOp::new(OpCode::IntEqual, Some(zf()), vec![dst.clone(), zero]).with_note(+ match opcode {+ OpCode::IntSub => "cmp/sub sets zf",+ OpCode::IntAnd => "test/and sets zf",+ _ => "arith sets zf",+ },+ ),+ );// sf = signed-less-than(dst, 0)out.push(PcodeOp::new(OpCode::IntSLess,@@ -647,8 +678,7 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {let width = if mnem == "cqo" { 8 } else { 4 };let rax = X86Reg::Rax.as_varnode(width);let rdx = X86Reg::Rdx.as_varnode(width);- return vec![PcodeOp::new(OpCode::IntSExt, Some(rdx), vec![rax])- .with_note(mnem)];+ return vec![PcodeOp::new(OpCode::IntSExt, Some(rdx), vec![rax]).with_note(mnem)];}"cwde" | "cdqe" | "cbw" => {let (src_w, dst_w) = match mnem {@@ -659,8 +689,7 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {};let src = X86Reg::Rax.as_varnode(src_w);let dst = X86Reg::Rax.as_varnode(dst_w);- return vec![PcodeOp::new(OpCode::IntSExt, Some(dst), vec![src])- .with_note(mnem)];+ return vec![PcodeOp::new(OpCode::IntSExt, Some(dst), vec![src]).with_note(mnem)];}"bswap" => {if let Some(first) = parts.first() {@@ -669,29 +698,22 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {// Model as opaque "byte-swap"; kept as an IntXor-with-self// marker so we don't fabricate arithmetic. Downstream// Stage-1 emit will print a `bswap(x)` builtin call.- return vec![PcodeOp::new(- OpCode::Cast,- Some(vn.clone()),- vec![vn],- )- .with_note(format!("bswap {first}"))];+ return vec![PcodeOp::new(OpCode::Cast, Some(vn.clone()), vec![vn])+ .with_note(format!("bswap {first}"))];}}}"pushfq" => {// Push RFLAGS (8 bytes). We don't model individual flag bit// packing — the SSA reads of ZF/CF/… stay untouched.- return vec![PcodeOp::new(OpCode::Push, None, vec![])- .with_note("pushfq")];+ return vec![PcodeOp::new(OpCode::Push, None, vec![]).with_note("pushfq")];}"popfq" => {- return vec![PcodeOp::new(OpCode::Pop, None, vec![])- .with_note("popfq")];+ return vec![PcodeOp::new(OpCode::Pop, None, vec![]).with_note("popfq")];}"syscall" => {// Modeled as an indirect call for now (result in rax after).- return vec![PcodeOp::new(OpCode::CallInd, None, vec![])- .with_note("syscall")];+ return vec![PcodeOp::new(OpCode::CallInd, None, vec![]).with_note("syscall")];}"cpuid" => {// Reads eax/ecx, writes eax/ebx/ecx/edx. Represent as a Trap-@@ -710,20 +732,14 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {"push" => {if let Some(first) = parts.first() {if let Some((reg, size)) = parse_reg(first) {- return vec![PcodeOp::new(- OpCode::Push,- None,- vec![reg.as_varnode(size)],- )- .with_note(format!("push {}", insn.operands))];+ return vec![PcodeOp::new(OpCode::Push, None, vec![reg.as_varnode(size)])+ .with_note(format!("push {}", insn.operands))];}if let Some(imm) = parse_imm(first) {- return vec![PcodeOp::new(- OpCode::Push,- None,- vec![Varnode::constant(imm, 8)],- )- .with_note(format!("push {}", insn.operands))];+ return vec![+ PcodeOp::new(OpCode::Push, None, vec![Varnode::constant(imm, 8)])+ .with_note(format!("push {}", insn.operands)),+ ];}if let Some(mem) = parse_mem(first) {let (mut ops, val) = load_from(ctx, &mem, mem.size, addr, len);@@ -738,12 +754,10 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {"pop" => {if let Some(first) = parts.first() {if let Some((reg, size)) = parse_reg(first) {- return vec![PcodeOp::new(- OpCode::Pop,- Some(reg.as_varnode(size)),- vec![],- )- .with_note(format!("pop {}", insn.operands))];+ return vec![+ PcodeOp::new(OpCode::Pop, Some(reg.as_varnode(size)), vec![])+ .with_note(format!("pop {}", insn.operands)),+ ];}if let Some(mem) = parse_mem(first) {let tmp = ctx.take_unique(mem.size);@@ -794,13 +808,28 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {"xor" => OpCode::IntXor,_ => unreachable!(),};- if let Some(ops) = lift_binop(ctx, opcode, parts[0], parts[1], addr, len, &insn.operands) {+ if let Some(ops) =+ lift_binop(ctx, opcode, parts[0], parts[1], addr, len, &insn.operands)+ {return ops;}}"cmp" | "test" if parts.len() == 2 => {- let opcode = if mnem == "cmp" { OpCode::IntSub } else { OpCode::IntAnd };- if let Some(ops) = lift_cmp_like(ctx, opcode, parts[0], parts[1], addr, len, mnem, &insn.operands) {+ let opcode = if mnem == "cmp" {+ OpCode::IntSub+ } else {+ OpCode::IntAnd+ };+ if let Some(ops) = lift_cmp_like(+ ctx,+ opcode,+ parts[0],+ parts[1],+ addr,+ len,+ mnem,+ &insn.operands,+ ) {return ops;}}@@ -808,13 +837,15 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {if let Some((reg, size)) = parse_reg(parts[0]) {let dst = reg.as_varnode(size);let one = Varnode::constant(1, size);- let opcode = if mnem == "inc" { OpCode::IntAdd } else { OpCode::IntSub };- let mut ops = vec![PcodeOp::new(- opcode,- Some(dst.clone()),- vec![dst.clone(), one],- )- .with_note(format!("{} {}", mnem, insn.operands))];+ let opcode = if mnem == "inc" {+ OpCode::IntAdd+ } else {+ OpCode::IntSub+ };+ let mut ops = vec![+ PcodeOp::new(opcode, Some(dst.clone()), vec![dst.clone(), one])+ .with_note(format!("{} {}", mnem, insn.operands)),+ ];ops.extend(lift_arith_flags(dst, opcode));return ops;}@@ -834,10 +865,8 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {"not" if parts.len() == 1 => {if let Some((reg, size)) = parse_reg(parts[0]) {let dst = reg.as_varnode(size);- return vec![- PcodeOp::new(OpCode::IntNot, Some(dst.clone()), vec![dst])- .with_note(format!("not {}", insn.operands)),- ];+ return vec![PcodeOp::new(OpCode::IntNot, Some(dst.clone()), vec![dst])+ .with_note(format!("not {}", insn.operands))];}}"shl" | "shr" | "sar" if parts.len() == 2 => {@@ -857,11 +886,12 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {let sz = dsz.min(ssz);let dst_vn = dst.as_varnode(sz);let src_vn = src.as_varnode(sz);- let mut ops =- vec![- PcodeOp::new(OpCode::IntMult, Some(dst_vn.clone()), vec![dst_vn.clone(), src_vn])- .with_note(format!("{} {}", mnem, insn.operands)),- ];+ let mut ops = vec![PcodeOp::new(+ OpCode::IntMult,+ Some(dst_vn.clone()),+ vec![dst_vn.clone(), src_vn],+ )+ .with_note(format!("{} {}", mnem, insn.operands))];ops.extend(lift_arith_flags(dst_vn, OpCode::IntMult));return ops;}@@ -935,7 +965,10 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {} else if let Some(mem) = parse_mem(parts[0]) {load_from(ctx, &mem, mem.size, addr, len)} else {- return vec![PcodeOp::unimplemented(format!("{} {}", mnem, insn.operands))];+ return vec![PcodeOp::unimplemented(format!(+ "{} {}",+ mnem, insn.operands+ ))];};let mut ops = rhs_ops;ops.push(@@ -1058,8 +1091,7 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {.with_note("xchg tmp"),PcodeOp::new(OpCode::Copy, Some(a_vn), vec![b_vn.clone()]).with_note(format!("xchg {}", insn.operands)),- PcodeOp::new(OpCode::Copy, Some(b_vn), vec![tmp])- .with_note("xchg tmp"),+ PcodeOp::new(OpCode::Copy, Some(b_vn), vec![tmp]).with_note("xchg tmp"),];}}@@ -1074,12 +1106,10 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {.with_note(format!("call {target:#x}"))];}if let Some((reg, size)) = parse_reg(first) {- return vec![PcodeOp::new(- OpCode::CallInd,- None,- vec![reg.as_varnode(size)],- )- .with_note(format!("call {}", insn.operands))];+ return vec![+ PcodeOp::new(OpCode::CallInd, None, vec![reg.as_varnode(size)])+ .with_note(format!("call {}", insn.operands)),+ ];}if let Some(mem) = parse_mem(first) {let (mut ops, tgt) = load_from(ctx, &mem, mem.size, addr, len);@@ -1102,12 +1132,10 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {.with_note(format!("jmp {target:#x}"))];}if let Some((reg, size)) = parse_reg(first) {- return vec![PcodeOp::new(- OpCode::BranchInd,- None,- vec![reg.as_varnode(size)],- )- .with_note(format!("jmp {}", insn.operands))];+ return vec![+ PcodeOp::new(OpCode::BranchInd, None, vec![reg.as_varnode(size)])+ .with_note(format!("jmp {}", insn.operands)),+ ];}if let Some(mem) = parse_mem(first) {let (mut ops, tgt) = load_from(ctx, &mem, mem.size, addr, len);@@ -1190,13 +1218,17 @@ fn lift_xmm_move(if is_xmm_name(dst) && is_xmm_name(src) {let d = xmm_slot(ctx, dst);let s = xmm_slot(ctx, src);- return vec![PcodeOp::new(OpCode::Copy, Some(d), vec![s]).with_note(format!("{mnem} {raw}"))];+ return vec![+ PcodeOp::new(OpCode::Copy, Some(d), vec![s]).with_note(format!("{mnem} {raw}"))+ ];}if is_xmm_name(dst) {if let Some(mem) = parse_mem(src) {let (mut ops, val) = load_from(ctx, &mem, 16, addr, len);let d = xmm_slot(ctx, dst);- ops.push(PcodeOp::new(OpCode::Copy, Some(d), vec![val]).with_note(format!("{mnem} {raw}")));+ ops.push(+ PcodeOp::new(OpCode::Copy, Some(d), vec![val]).with_note(format!("{mnem} {raw}")),+ );return ops;}}@@ -1212,22 +1244,14 @@ fn lift_xmm_move(vec![PcodeOp::unimplemented(format!("{mnem} {raw}"))]}-fn lift_xmm_xor(- ctx: &mut LiftCtx,- dst: &str,- src: &str,- mnem: &str,- raw: &str,-) -> Vec<PcodeOp> {+fn lift_xmm_xor(ctx: &mut LiftCtx, dst: &str, src: &str, mnem: &str, raw: &str) -> Vec<PcodeOp> {if is_xmm_name(dst) && dst.trim() == src.trim() {// xorps/pxor same reg → zerolet d = xmm_slot(ctx, dst);- return vec![PcodeOp::new(- OpCode::Copy,- Some(d),- vec![Varnode::constant(0, 16)],- )- .with_note(format!("{mnem} {raw} ; zero"))];+ return vec![+ PcodeOp::new(OpCode::Copy, Some(d), vec![Varnode::constant(0, 16)])+ .with_note(format!("{mnem} {raw} ; zero")),+ ];}if is_xmm_name(dst) && is_xmm_name(src) {let d = xmm_slot(ctx, dst);@@ -1298,23 +1322,23 @@ fn lift_binop(if let (Some((d, dsz)), Some((s, ssz))) = (parse_reg(dst), parse_reg(src)) {let sz = dsz.min(ssz);let dvn = d.as_varnode(sz);- let mut ops = vec![- PcodeOp::new(opcode, Some(dvn.clone()), vec![dvn.clone(), s.as_varnode(sz)])- .with_note(format!("{raw}")),- ];+ let mut ops = vec![PcodeOp::new(+ opcode,+ Some(dvn.clone()),+ vec![dvn.clone(), s.as_varnode(sz)],+ )+ .with_note(format!("{raw}"))];ops.extend(lift_arith_flags(dvn, opcode));return Some(ops);}if let (Some((d, dsz)), Some(imm)) = (parse_reg(dst), parse_imm(src)) {let dvn = d.as_varnode(dsz);- let mut ops = vec![- PcodeOp::new(- opcode,- Some(dvn.clone()),- vec![dvn.clone(), Varnode::constant(imm, dsz)],- )- .with_note(format!("{raw}")),- ];+ let mut ops = vec![PcodeOp::new(+ opcode,+ Some(dvn.clone()),+ vec![dvn.clone(), Varnode::constant(imm, dsz)],+ )+ .with_note(format!("{raw}"))];ops.extend(lift_arith_flags(dvn, opcode));return Some(ops);}@@ -1409,12 +1433,10 @@ fn lift_shift(// Shift count is CL (byte).let count = s.as_varnode(1);let dvn = d.as_varnode(dsz);- let mut ops = vec![PcodeOp::new(- opcode,- Some(dvn.clone()),- vec![dvn.clone(), count],- )- .with_note(format!("{mnem} {raw}"))];+ let mut ops = vec![+ PcodeOp::new(opcode, Some(dvn.clone()), vec![dvn.clone(), count])+ .with_note(format!("{mnem} {raw}")),+ ];ops.extend(lift_arith_flags(dvn, opcode));// ctx used to keep signature parity when we later thread mem operands here.let _ = ctx;@@ -1484,7 +1506,10 @@ mod tests {assert_eq!(seq.ops[0].opcode, OpCode::Push);assert_eq!(seq.ops[0].inputs[0].offset, X86Reg::Rbp as u64);assert_eq!(seq.ops[1].opcode, OpCode::Copy);- assert_eq!(seq.ops[1].output.as_ref().unwrap().offset, X86Reg::Rbp as u64);+ assert_eq!(+ seq.ops[1].output.as_ref().unwrap().offset,+ X86Reg::Rbp as u64+ );assert_eq!(seq.ops[1].inputs[0].offset, X86Reg::Rsp as u64);assert_eq!(seq.ops[2].opcode, OpCode::Return);assert_eq!(seq.addressed[0].address, 0x1000);@@ -1716,10 +1741,20 @@ mod tests {let copy = seq.ops.iter()- .find(|o| o.opcode == OpCode::Copy && o.output.as_ref().map(|v| v.offset) == Some(X86Reg::Rax as u64))+ .find(|o| {+ o.opcode == OpCode::Copy+ && o.output.as_ref().map(|v| v.offset) == Some(X86Reg::Rax as u64)+ }).expect("lea dst copy");- assert!(matches!(copy.inputs[0].space, AddrSpace::Unique | AddrSpace::Register));- let add = seq.ops.iter().find(|o| o.opcode == OpCode::IntAdd).expect("lea builds add");+ assert!(matches!(+ copy.inputs[0].space,+ AddrSpace::Unique | AddrSpace::Register+ ));+ let add = seq+ .ops+ .iter()+ .find(|o| o.opcode == OpCode::IntAdd)+ .expect("lea builds add");assert_eq!(add.inputs[0].offset, X86Reg::Rbp as u64);}@@ -1795,6 +1830,10 @@ mod tests {let src_len = insns.len();let seq = lift_instructions(&insns);let cov = coverage(&seq, src_len);- assert!(cov.ratio() > 0.99, "expected full lift, got {}", cov.ratio());+ assert!(+ cov.ratio() > 0.99,+ "expected full lift, got {}",+ cov.ratio()+ );}}diff --git a/crates/ghidrust-ssa/src/lib.rs b/crates/ghidrust-ssa/src/lib.rsindex 4a88b56..f005b34 100644--- a/crates/ghidrust-ssa/src/lib.rs+++ b/crates/ghidrust-ssa/src/lib.rs@@ -257,8 +257,7 @@ pub fn build_cfg_with_leaders(for (i, aop) in seq.addressed.iter().enumerate() {op_index_by_addr.entry(aop.address).or_insert(i);}- let instruction_starts: BTreeSet<u64> =- seq.addressed.iter().map(|a| a.address).collect();+ let instruction_starts: BTreeSet<u64> = seq.addressed.iter().map(|a| a.address).collect();for i in 0..seq.addressed.len() {let aop = &seq.addressed[i];@@ -439,9 +438,7 @@ pub fn block_defs(cfg: &Cfg) -> Vec<HashSet<(ghidrust_ir::AddrSpace, u64)>> {/// dominance-frontier blocks reached by its defs. Output maps/// `(space, offset) → set of block ids needing a phi`. This is the direct/// input for the rename pass we will land next.-pub fn phi_placement(- cfg: &Cfg,-) -> BTreeMap<(ghidrust_ir::AddrSpace, u64), BTreeSet<u32>> {+pub fn phi_placement(cfg: &Cfg) -> BTreeMap<(ghidrust_ir::AddrSpace, u64), BTreeSet<u32>> {let df = cfg.dominance_frontiers();let defs = block_defs(cfg);let mut needs: BTreeMap<(ghidrust_ir::AddrSpace, u64), BTreeSet<u32>> = BTreeMap::new();@@ -503,7 +500,11 @@ mod tests {// c3 retlet bytes = [0x39, 0xc1, 0x74, 0x02, 0x31, 0xc0, 0xc3, 0x31, 0xc9, 0xc3];let cfg = cfg_for(&bytes, 0x2000);- assert!(cfg.len() >= 2, "expected multiple blocks, got {}", cfg.len());+ assert!(+ cfg.len() >= 2,+ "expected multiple blocks, got {}",+ cfg.len()+ );// Entry block ends with CBranch → two successors.assert!(cfg.blocks[0].successors.len() >= 2);// Everything must be reachable from entry.diff --git a/crates/ghidrust-ssa/src/ssa.rs b/crates/ghidrust-ssa/src/ssa.rsindex 8047002..2f3d5ad 100644--- a/crates/ghidrust-ssa/src/ssa.rs+++ b/crates/ghidrust-ssa/src/ssa.rs@@ -241,11 +241,7 @@ fn rename_block(// block and produce SsaOps; the block was seeded empty above.let src_ops = cfg.blocks[b as usize].ops.clone();for op in src_ops {- let inputs: Vec<SsaOperand> = op- .inputs- .iter()- .map(|v| rename_input(v, stacks))- .collect();+ let inputs: Vec<SsaOperand> = op.inputs.iter().map(|v| rename_input(v, stacks)).collect();let output = op.output.as_ref().map(|v| {let key = (v.space, v.offset);let ver = new_version(versions, key);@@ -298,10 +294,7 @@ fn rename_block(}}-fn rename_input(- v: &Varnode,- stacks: &HashMap<(AddrSpace, u64), Vec<u32>>,-) -> SsaOperand {+fn rename_input(v: &Varnode, stacks: &HashMap<(AddrSpace, u64), Vec<u32>>) -> SsaOperand {match v.space {AddrSpace::Constant => SsaOperand::Const(v.clone()),_ => {@@ -440,7 +433,11 @@ pub fn const_fold(func: &mut SsaFunction) -> usize {let a_const = op.inputs.first().and_then(SsaOperand::as_const);let b_const = op.inputs.get(1).and_then(SsaOperand::as_const);let width = dst.size.max(1);- let mask = if width >= 8 { u64::MAX } else { (1u64 << (width * 8)) - 1 };+ let mask = if width >= 8 {+ u64::MAX+ } else {+ (1u64 << (width * 8)) - 1+ };let folded = match op.opcode {OpCode::IntAdd => match (a_const, b_const) {(Some(a), Some(b)) => Some(a.wrapping_add(b) & mask),@@ -499,9 +496,7 @@ pub fn const_fold(func: &mut SsaFunction) -> usize {_ => None,},OpCode::IntSLessEqual => match (a_const, b_const) {- (Some(a), Some(b)) => {- Some(if (a as i64) <= (b as i64) { 1 } else { 0 })- }+ (Some(a), Some(b)) => Some(if (a as i64) <= (b as i64) { 1 } else { 0 }),_ => None,},OpCode::IntZExt | OpCode::IntSExt | OpCode::Copy | OpCode::Cast => {@@ -509,11 +504,8 @@ pub fn const_fold(func: &mut SsaFunction) -> usize {// sign-extended to the destination width.a_const.map(|a| match op.opcode {OpCode::IntSExt => {- let src_size = op- .inputs- .first()- .map(|v| v.varnode().size)- .unwrap_or(width);+ let src_size =+ op.inputs.first().map(|v| v.varnode().size).unwrap_or(width);if src_size >= 8 {a & mask} else {@@ -868,11 +860,7 @@ mod tests {PcodeOp::new(OpCode::Branch, None, vec![Varnode::constant(0x200, 8)]),);// Block 3 @ 0x200: return rax- seq.push_addressed(- 0x200,- 1,- PcodeOp::new(OpCode::Return, None, vec![rax]),- );+ seq.push_addressed(0x200, 1, PcodeOp::new(OpCode::Return, None, vec![rax]));seq}@@ -901,7 +889,11 @@ mod tests {let cfg = build_cfg(&diamond_seq(), 0x0, 0x201);let func = build_ssa(&cfg);// RAX has: two block defs + one phi def = 3 total versions expected.- let rax_ver = func.versions.get(&(AddrSpace::Register, 0)).copied().unwrap_or(0);+ let rax_ver = func+ .versions+ .get(&(AddrSpace::Register, 0))+ .copied()+ .unwrap_or(0);assert!(rax_ver >= 3, "expected >=3 rax versions, got {rax_ver}");}@@ -926,7 +918,10 @@ mod tests {let func = build_ssa(&cfg);let dump = dump_ssa(&func);assert!(dump.contains("φ("), "dump should show phi op: {dump}");- assert!(dump.contains("reg0#"), "dump should show versioned rax: {dump}");+ assert!(+ dump.contains("reg0#"),+ "dump should show versioned rax: {dump}"+ );}#[test]@@ -939,12 +934,20 @@ mod tests {seq.push_addressed(0x0,1,- PcodeOp::new(OpCode::Copy, Some(t0.clone()), vec![Varnode::constant(0x100, 8)]),+ PcodeOp::new(+ OpCode::Copy,+ Some(t0.clone()),+ vec![Varnode::constant(0x100, 8)],+ ),);seq.push_addressed(0x1,1,- PcodeOp::new(OpCode::Copy, Some(t1.clone()), vec![Varnode::constant(0x20, 8)]),+ PcodeOp::new(+ OpCode::Copy,+ Some(t1.clone()),+ vec![Varnode::constant(0x20, 8)],+ ),);seq.push_addressed(0x2,@@ -976,24 +979,31 @@ mod tests {seq.push_addressed(0x0,1,- PcodeOp::new(OpCode::Copy, Some(t0.clone()), vec![Varnode::constant(1, 8)]),+ PcodeOp::new(+ OpCode::Copy,+ Some(t0.clone()),+ vec![Varnode::constant(1, 8)],+ ),);seq.push_addressed(0x1,1,- PcodeOp::new(OpCode::Copy, Some(t1.clone()), vec![Varnode::constant(2, 8)]),- );- seq.push_addressed(- 0x2,- 1,- PcodeOp::new(OpCode::IntAdd, Some(t2), vec![t0, t1]),+ PcodeOp::new(+ OpCode::Copy,+ Some(t1.clone()),+ vec![Varnode::constant(2, 8)],+ ),);+ seq.push_addressed(0x2, 1, PcodeOp::new(OpCode::IntAdd, Some(t2), vec![t0, t1]));seq.push_addressed(0x3, 1, PcodeOp::new(OpCode::Return, None, vec![]));let cfg = build_cfg(&seq, 0x0, 0x4);let mut func = build_ssa(&cfg);let before = func.blocks[0].ops.len();let removed = dead_code_eliminate(&mut func);- assert!(removed >= 3, "expected at least 3 dead ops removed; got {removed}");+ assert!(+ removed >= 3,+ "expected at least 3 dead ops removed; got {removed}"+ );assert!(func.blocks[0].ops.len() < before);// Return must survive because it's a control-flow op.assert!(func.blocks[0]@@ -1065,7 +1075,11 @@ mod tests {seq.push_addressed(0x0,1,- PcodeOp::new(OpCode::Copy, Some(t0.clone()), vec![Varnode::constant(0x1234, 8)]),+ PcodeOp::new(+ OpCode::Copy,+ Some(t0.clone()),+ vec![Varnode::constant(0x1234, 8)],+ ),);seq.push_addressed(0x1,@@ -1081,7 +1095,10 @@ mod tests {let cfg = build_cfg(&seq, 0x0, 0x4);let mut func = build_ssa(&cfg);let rewrote = copy_propagate(&mut func);- assert!(rewrote > 0, "copy_propagate should rewrite at least one operand");+ assert!(+ rewrote > 0,+ "copy_propagate should rewrite at least one operand"+ );let ret_op = func.blocks[0].ops.iter()diff --git a/crates/ghidrust-structure/src/lib.rs b/crates/ghidrust-structure/src/lib.rsindex 3a532b5..8093668 100644--- a/crates/ghidrust-structure/src/lib.rs+++ b/crates/ghidrust-structure/src/lib.rs@@ -102,10 +102,7 @@ pub enum Region {else_branch: Box<Region>,},/// `while (cond) { body }` — CBranch is at the loop header.- While {- header: u32,- body: Box<Region>,- },+ While { header: u32, body: Box<Region> },/// `do { body } while (cond)` — CBranch is at the latch.DoWhile {header: u32,@@ -113,10 +110,7 @@ pub enum Region {latch: u32,},/// `for (;;) { body }` — infinite loop with no explicit exit.- Loop {- header: u32,- body: Box<Region>,- },+ Loop { header: u32, body: Box<Region> },/// `return;` — a block whose terminator is [`OpCode::Return`].Return(u32),/// `break;` — an edge from inside a natural loop to the loop's@@ -271,7 +265,10 @@ impl Region {}Region::Break | Region::Continue => {}Region::Seq(rs) => rs.iter().for_each(|r| r.collect_blocks(set)),- Region::IfThen { header, then_branch } => {+ Region::IfThen {+ header,+ then_branch,+ } => {set.insert(*header);then_branch.collect_blocks(set);}@@ -297,7 +294,11 @@ impl Region {set.insert(*latch);body.collect_blocks(set);}- Region::Switch { header, cases, default } => {+ Region::Switch {+ header,+ cases,+ default,+ } => {set.insert(*header);for c in cases {set.insert(c.target);@@ -398,10 +399,15 @@ pub fn structure_function_with_hints(/// patterns common in real binaries.pub fn promote_early_returns(r: Region, ssa: &SsaFunction) -> Region {match r {- Region::Seq(rs) => {- Region::Seq(rs.into_iter().map(|c| promote_early_returns(c, ssa)).collect())- }- Region::IfThen { header, then_branch } => Region::IfThen {+ Region::Seq(rs) => Region::Seq(+ rs.into_iter()+ .map(|c| promote_early_returns(c, ssa))+ .collect(),+ ),+ Region::IfThen {+ header,+ then_branch,+ } => Region::IfThen {header,then_branch: Box::new(promote_goto_to_return(promote_early_returns(*then_branch, ssa),@@ -427,7 +433,11 @@ pub fn promote_early_returns(r: Region, ssa: &SsaFunction) -> Region {header,body: Box::new(promote_early_returns(*body, ssa)),},- Region::DoWhile { header, body, latch } => Region::DoWhile {+ Region::DoWhile {+ header,+ body,+ latch,+ } => Region::DoWhile {header,body: Box::new(promote_early_returns(*body, ssa)),latch,@@ -651,9 +661,12 @@ impl<'a> StructCtx<'a> {// Switch handling (Decompiler Switch Analysis hint).if let Some(sw) = self.switches.get(&b).cloned() {- let stop = sw- .default- .or_else(|| self.pdom.get(b as usize).copied().filter(|p| *p != u32::MAX && *p != b));+ let stop = sw.default.or_else(|| {+ self.pdom+ .get(b as usize)+ .copied()+ .filter(|p| *p != u32::MAX && *p != b)+ });let cases: Vec<SwitchCase> = sw.cases.iter()@@ -712,7 +725,11 @@ impl<'a> StructCtx<'a> {if else_id == join {None} else {- Some(Box::new(self.build_region_from(else_id, Some(join), visited)))+ Some(Box::new(self.build_region_from(+ else_id,+ Some(join),+ visited,+ )))}} else {// No shared join — emit both branches with unbounded expansion.@@ -944,17 +961,11 @@ impl<'a> StructCtx<'a> {}fn is_return_block(b: &SsaBlock) -> bool {- matches!(- b.ops.last().map(|o| o.opcode),- Some(OpCode::Return)- )+ matches!(b.ops.last().map(|o| o.opcode), Some(OpCode::Return))}fn ends_in_cbranch(b: &SsaBlock) -> bool {- matches!(- b.ops.last().map(|o| o.opcode),- Some(OpCode::CBranch)- )+ matches!(b.ops.last().map(|o| o.opcode), Some(OpCode::CBranch))}fn collapse_seq(mut seq: Vec<Region>) -> Region {@@ -1180,7 +1191,11 @@ fn render(r: &Region, indent: usize, out: &mut String) {render(body, indent + 1, out);out.push_str(&format!("{pad}}}\n"));}- Region::DoWhile { header: _, body, latch } => {+ Region::DoWhile {+ header: _,+ body,+ latch,+ } => {out.push_str(&format!("{pad}do {{\n"));render(body, indent + 1, out);out.push_str(&format!("{pad}}} while (cond_of_{latch});\n"));@@ -1190,10 +1205,17 @@ fn render(r: &Region, indent: usize, out: &mut String) {render(body, indent + 1, out);out.push_str(&format!("{pad}}}\n"));}- Region::Switch { header, cases, default } => {+ Region::Switch {+ header,+ cases,+ default,+ } => {out.push_str(&format!("{pad}switch (cond_of_{header}) {{\n"));for c in cases {- out.push_str(&format!("{pad} case {}: // → block_{}\n", c.selector, c.target));+ out.push_str(&format!(+ "{pad} case {}: // → block_{}\n",+ c.selector, c.target+ ));render(&c.body, indent + 2, out);out.push_str(&format!("{pad} break;\n"));}@@ -1249,8 +1271,15 @@ fn render(r: &Region, indent: usize, out: &mut String) {/// preserved verbatim.pub fn flatten_short_circuit(r: Region, ssa: &SsaFunction) -> Region {match r {- Region::Seq(rs) => Region::Seq(rs.into_iter().map(|c| flatten_short_circuit(c, ssa)).collect()),- Region::IfThen { header, then_branch } => flatten_and(header, *then_branch, ssa),+ Region::Seq(rs) => Region::Seq(+ rs.into_iter()+ .map(|c| flatten_short_circuit(c, ssa))+ .collect(),+ ),+ Region::IfThen {+ header,+ then_branch,+ } => flatten_and(header, *then_branch, ssa),Region::IfThenElse {header,then_branch,@@ -1260,7 +1289,11 @@ pub fn flatten_short_circuit(r: Region, ssa: &SsaFunction) -> Region {header,body: Box::new(flatten_short_circuit(*body, ssa)),},- Region::DoWhile { header, body, latch } => Region::DoWhile {+ Region::DoWhile {+ header,+ body,+ latch,+ } => Region::DoWhile {header,body: Box::new(flatten_short_circuit(*body, ssa)),latch,@@ -1354,7 +1387,11 @@ fn flatten_and(header: u32, inner: Region, ssa: &SsaFunction) -> Region {mut parts,then_branch,else_branch,- } if parts.first().map(|p| is_pure_predicate_block(ssa, p.header)).unwrap_or(false) => {+ } if parts+ .first()+ .map(|p| is_pure_predicate_block(ssa, p.header))+ .unwrap_or(false) =>+ {parts.insert(0,ShortCircuitClause {@@ -1385,7 +1422,8 @@ fn flatten_or(header: u32, then_branch: Region, else_branch: Region, ssa: &SsaFuthen_branch: else_then,} = &else_branch{- if is_pure_predicate_block(ssa, *else_h) && region_bodies_equivalent(&then_branch, else_then)+ if is_pure_predicate_block(ssa, *else_h)+ && region_bodies_equivalent(&then_branch, else_then){return Region::ShortCircuit {parts: vec![@@ -1443,9 +1481,9 @@ pub fn goto_count(region: &Region) -> usize {else_branch,..} => goto_count(then_branch) + goto_count(else_branch),- Region::While { body, .. }- | Region::DoWhile { body, .. }- | Region::Loop { body, .. } => goto_count(body),+ Region::While { body, .. } | Region::DoWhile { body, .. } | Region::Loop { body, .. } => {+ goto_count(body)+ }Region::Switch { cases, default, .. } => {cases.iter().map(|c| goto_count(&c.body)).sum::<usize>()+ default.as_ref().map(|d| goto_count(d)).unwrap_or(0)@@ -1454,10 +1492,7 @@ pub fn goto_count(region: &Region) -> usize {then_branch,else_branch,..- } => {- goto_count(then_branch)- + else_branch.as_ref().map(|e| goto_count(e)).unwrap_or(0)- }+ } => goto_count(then_branch) + else_branch.as_ref().map(|e| goto_count(e)).unwrap_or(0),_ => 0,}}@@ -1479,11 +1514,14 @@ pub fn region_leaf_count(region: &Region) -> usize {else_branch,..} => 1 + region_leaf_count(then_branch) + region_leaf_count(else_branch),- Region::While { body, .. }- | Region::DoWhile { body, .. }- | Region::Loop { body, .. } => 1 + region_leaf_count(body),+ Region::While { body, .. } | Region::DoWhile { body, .. } | Region::Loop { body, .. } => {+ 1 + region_leaf_count(body)+ }Region::Switch { cases, default, .. } => {- 1 + cases.iter().map(|c| region_leaf_count(&c.body)).sum::<usize>()+ 1 + cases+ .iter()+ .map(|c| region_leaf_count(&c.body))+ .sum::<usize>()+ default.as_ref().map(|d| region_leaf_count(d)).unwrap_or(0)}Region::ShortCircuit {@@ -1492,7 +1530,10 @@ pub fn region_leaf_count(region: &Region) -> usize {..} => {1 + region_leaf_count(then_branch)- + else_branch.as_ref().map(|e| region_leaf_count(e)).unwrap_or(0)+ + else_branch+ .as_ref()+ .map(|e| region_leaf_count(e))+ .unwrap_or(0)}}}@@ -1529,7 +1570,11 @@ fn walk(r: &Region, map: &mut BTreeMap<u32, Region>) {Region::DoWhile { header, .. } => {map.insert(*header, r.clone());}- Region::Switch { header, cases, default } => {+ Region::Switch {+ header,+ cases,+ default,+ } => {map.insert(*header, r.clone());for c in cases {walk(&c.body, map);@@ -1581,7 +1626,10 @@ mod tests {let rep = structure_bytes(&bytes, 0x1000);assert!(rep.loops.is_empty());let text = dump_region(&rep.region);- assert!(text.contains("return"), "linear region should emit return: {text}");+ assert!(+ text.contains("return"),+ "linear region should emit return: {text}"+ );}#[test]@@ -1682,10 +1730,7 @@ mod tests {}]);let rep = structure_function_with_hints(&cfg, &ssa, &hints);let text = dump_region(&rep.region);- assert!(- text.contains("switch"),- "expected switch region:\n{text}"- );+ assert!(text.contains("switch"), "expected switch region:\n{text}");assert!(text.contains("case 0"));assert!(text.contains("case 1"));}diff --git a/crates/ghidrust-types/src/lib.rs b/crates/ghidrust-types/src/lib.rsindex a54f87c..c78a972 100644--- a/crates/ghidrust-types/src/lib.rs+++ b/crates/ghidrust-types/src/lib.rs@@ -113,29 +113,21 @@ impl RustType {match (self, other) {(Bottom, x) | (x, Bottom) => x,(a, b) if a == b => a,- (IntN { width: a }, IntN { width: b }) => IntN {- width: a.max(b),- },- (IntSigned { width: a }, IntSigned { width: b }) => IntSigned {- width: a.max(b),- },+ (IntN { width: a }, IntN { width: b }) => IntN { width: a.max(b) },+ (IntSigned { width: a }, IntSigned { width: b }) => IntSigned { width: a.max(b) },// A signed observation combined with the same-width unsigned// one prefers the signed shape — Stage-1 emit reads the operand// as a signed compare / sext output which is more informative// than the width-only unsigned bucket.(IntSigned { width: a }, IntN { width: b })- | (IntN { width: b }, IntSigned { width: a }) => IntSigned {- width: a.max(b),- },+ | (IntN { width: b }, IntSigned { width: a }) => IntSigned { width: a.max(b) },(Ptr { pointee_width: a }, Ptr { pointee_width: b }) => Ptr {pointee_width: a.max(b),},// A struct pointer subsumes an untyped raw pointer with the same// key already known; conflicting keys collapse to `Any`.(StructPtr { key: a }, StructPtr { key: b }) if a == b => StructPtr { key: a },- (StructPtr { key }, Ptr { .. }) | (Ptr { .. }, StructPtr { key }) => {- StructPtr { key }- }+ (StructPtr { key }, Ptr { .. }) | (Ptr { .. }, StructPtr { key }) => StructPtr { key },// Struct/Array pointer observations subsume the same-width raw// integer seed on the base register (from the ambient Copy /// IntAdd chain that computed the address). This lets Stage-1@@ -144,11 +136,19 @@ impl RustType {(StructPtr { key }, IntN { width: 8 }) | (IntN { width: 8 }, StructPtr { key }) => {StructPtr { key }}- (ArrayPtr { elem_width: aw, count: ac }, ArrayPtr { elem_width: bw, count: bc })- if aw == bw =>- {- ArrayPtr { elem_width: aw, count: ac.max(bc) }- }+ (+ ArrayPtr {+ elem_width: aw,+ count: ac,+ },+ ArrayPtr {+ elem_width: bw,+ count: bc,+ },+ ) if aw == bw => ArrayPtr {+ elem_width: aw,+ count: ac.max(bc),+ },(ArrayPtr { elem_width, count }, Ptr { pointee_width })| (Ptr { pointee_width }, ArrayPtr { elem_width, count })if pointee_width == 0 || pointee_width == elem_width =>@@ -156,12 +156,8 @@ impl RustType {ArrayPtr { elem_width, count }}(ArrayPtr { elem_width, count }, IntN { width: 8 })- | (IntN { width: 8 }, ArrayPtr { elem_width, count }) => {- ArrayPtr { elem_width, count }- }- (Float { width: a }, Float { width: b }) => Float {- width: a.max(b),- },+ | (IntN { width: 8 }, ArrayPtr { elem_width, count }) => ArrayPtr { elem_width, count },+ (Float { width: a }, Float { width: b }) => Float { width: a.max(b) },// Same-width int + float observation prefers float (SSE move of// a 4/8-byte slot that also saw integer Copy still prints as float).(Float { width: fw }, IntN { width: iw })@@ -473,12 +469,7 @@ impl TypeRecovery {pub fn infer_types(func: &SsaFunction) -> TypeMap {const MAX_ITER: usize = 8;let mut map = TypeMap::default();- let flag_offsets: BTreeSet<u64> = [- ghidrust_lift_flag_off(),- ]- .into_iter()- .flatten()- .collect();+ let flag_offsets: BTreeSet<u64> = [ghidrust_lift_flag_off()].into_iter().flatten().collect();for _ in 0..MAX_ITER {let before = map.0.clone();@@ -506,10 +497,7 @@ fn seed_op(op: &SsaOp, map: &mut TypeMap, flags: &BTreeSet<u64>) {map.set(out.space, out.offset, RustType::Bool);}}- OpCode::IntEqual- | OpCode::IntNotEqual- | OpCode::IntLess- | OpCode::IntLessEqual => {+ OpCode::IntEqual | OpCode::IntNotEqual | OpCode::IntLess | OpCode::IntLessEqual => {if let Some(out) = op.output {map.set(out.space, out.offset, RustType::Bool);}@@ -747,10 +735,7 @@ pub fn recover_structs(func: &SsaFunction, types: &mut TypeMap) -> BTreeMap<u32,/// by walking one hop through preceding `IntAdd`/`Ptradd` chains recorded/// as the operand's def. Falls back to `(operand_as_value, 0)` for the/// direct-load case (`*base`).-fn decompose_addr(- addr: &SsaOperand,- func: &SsaFunction,-) -> (Option<ghidrust_ssa::SsaValue>, u64) {+fn decompose_addr(addr: &SsaOperand, func: &SsaFunction) -> (Option<ghidrust_ssa::SsaValue>, u64) {let SsaOperand::Value(v) = addr else {return (None, 0);};@@ -830,7 +815,8 @@ pub fn recover_params(func: &SsaFunction, types: &TypeMap, conv: CallConv) -> Pafor op in &entry_block.ops {for inp in &op.inputs {if let Some(v) = inp.as_value() {- if v.space == AddrSpace::Register && v.version == 0 && !defined.contains(&v.offset) {+ if v.space == AddrSpace::Register && v.version == 0 && !defined.contains(&v.offset)+ {live_in.insert((v.offset, v.size));}}@@ -863,12 +849,7 @@ pub fn recover_params(func: &SsaFunction, types: &TypeMap, conv: CallConv) -> Pa(8, "r8"),(9, "r9"),],- CallConv::Windows => &[- (1, "rcx"),- (2, "rdx"),- (8, "r8"),- (9, "r9"),- ],+ CallConv::Windows => &[(1, "rcx"), (2, "rdx"), (8, "r8"), (9, "r9")],};let mut params = Vec::new();for (index, &(reg_off, reg_name)) in order.iter().enumerate() {@@ -1002,10 +983,7 @@ mod tests {RustType::Bool,"zf should be bool");- assert_eq!(- rec.types.get(AddrSpace::Register, SF),- RustType::Bool- );+ assert_eq!(rec.types.get(AddrSpace::Register, SF), RustType::Bool);}#[test]@@ -1027,8 +1005,14 @@ mod tests {let bytes = [0x48, 0x89, 0xf8, 0x48, 0x01, 0xf0, 0xc3];let rec = recover_bytes(&bytes, 0x3000, CallConv::SystemV);let names: Vec<String> = rec.params.iter().map(|p| p.register.clone()).collect();- assert!(names.contains(&"rdi".to_string()), "rdi expected: {names:?}");- assert!(names.contains(&"rsi".to_string()), "rsi expected: {names:?}");+ assert!(+ names.contains(&"rdi".to_string()),+ "rdi expected: {names:?}"+ );+ assert!(+ names.contains(&"rsi".to_string()),+ "rsi expected: {names:?}"+ );assert_eq!(rec.params.0[0].name, "param_1");}@@ -1100,21 +1084,18 @@ mod tests {assert_eq!(RustType::ptr(4).c_style(), "uint32_t*");assert_eq!(RustType::signed(4).c_style(), "int32_t");assert_eq!(RustType::Void.c_style(), "void");- assert_eq!(- RustType::struct_ptr(3).c_style(),- "struct s_3*"- );- assert_eq!(- RustType::array_ptr(4, 5).c_style(),- "uint32_t*/*[5]*/"- );+ assert_eq!(RustType::struct_ptr(3).c_style(), "struct s_3*");+ assert_eq!(RustType::array_ptr(4, 5).c_style(), "uint32_t*/*[5]*/");}#[test]fn signed_join_wins_against_same_width_unsigned() {let s = RustType::signed(4);let u = RustType::int(4);- assert!(matches!(s.clone().join(u), RustType::IntSigned { width: 4 }));+ assert!(matches!(+ s.clone().join(u),+ RustType::IntSigned { width: 4 }+ ));}#[test]@@ -1141,7 +1122,10 @@ mod tests {let bytes = [0x48, 0x89, 0xf8, 0xc3];let rec = recover_bytes(&bytes, 0xa000, CallConv::SystemV);assert!(- matches!(rec.signature.return_type, RustType::IntN { .. } | RustType::Ptr { .. }),+ matches!(+ rec.signature.return_type,+ RustType::IntN { .. } | RustType::Ptr { .. }+ ),"expected typed return, got {:?}",rec.signature.return_type);@@ -1192,11 +1176,7 @@ mod tests {vec![t_base.clone(), Varnode::constant(0, 8)],),);- seq.push_addressed(- 0x2,- 1,- PcodeOp::new(OpCode::Load, Some(t2), vec![t1]),- );+ seq.push_addressed(0x2, 1, PcodeOp::new(OpCode::Load, Some(t2), vec![t1]));seq.push_addressed(0x3,1,@@ -1206,11 +1186,7 @@ mod tests {vec![t_base.clone(), Varnode::constant(8, 8)],),);- seq.push_addressed(- 0x4,- 1,- PcodeOp::new(OpCode::Load, Some(t4), vec![t3]),- );+ seq.push_addressed(0x4, 1, PcodeOp::new(OpCode::Load, Some(t4), vec![t3]));seq.push_addressed(0x5, 1, PcodeOp::new(OpCode::Return, None, vec![]));let cfg = build_cfg(&seq, 0x0, 0x6);let ssa = build_ssa(&cfg);@@ -1221,8 +1197,16 @@ mod tests {rec.structs.len());let s = rec.structs.values().next().unwrap();- assert!(s.fields.contains_key(&0), "field @ 0 missing: {:?}", s.fields);- assert!(s.fields.contains_key(&8), "field @ 8 missing: {:?}", s.fields);+ assert!(+ s.fields.contains_key(&0),+ "field @ 0 missing: {:?}",+ s.fields+ );+ assert!(+ s.fields.contains_key(&8),+ "field @ 8 missing: {:?}",+ s.fields+ );}#[test]@@ -1265,9 +1249,11 @@ mod tests {let rec = recover(&ssa, CallConv::SystemV);// No struct seeded — should be array. Look for ArrayPtr in the// type map on the base register.- let arr_present = rec.types.0.values().any(|t| {- matches!(t, RustType::ArrayPtr { elem_width: 4, count } if *count >= 3)- });+ let arr_present = rec+ .types+ .0+ .values()+ .any(|t| matches!(t, RustType::ArrayPtr { elem_width: 4, count } if *count >= 3));assert!(arr_present,"expected ArrayPtr in type map: {:?}",diff --git a/crates/ghidrust-unity-inventory/src/lib.rs b/crates/ghidrust-unity-inventory/src/lib.rsindex 6bd957e..6550876 100644--- a/crates/ghidrust-unity-inventory/src/lib.rs+++ b/crates/ghidrust-unity-inventory/src/lib.rs@@ -159,21 +159,14 @@ pub fn inventory_path(root: impl AsRef<Path>) -> Result<UnityInventory, String>if let Ok(prog) = load_path(&p) {for e in &prog.imports {let dll = e.dll.to_ascii_lowercase();- let name = e- .name- .as_deref()- .unwrap_or("")- .to_ascii_lowercase();+ let name = e.name.as_deref().unwrap_or("").to_ascii_lowercase();if dll.contains("openxr")|| dll.contains("xr")|| name.contains("openxr")|| name.contains("xrgetinstance"){- let label = format!(- "{}!{}",- e.dll,- e.name.clone().unwrap_or_else(|| "?".into())- );+ let label =+ format!("{}!{}", e.dll, e.name.clone().unwrap_or_else(|| "?".into()));if !native_xr_imports.contains(&label) {native_xr_imports.push(label);}@@ -217,13 +210,15 @@ pub fn inventory_path(root: impl AsRef<Path>) -> Result<UnityInventory, String>|| root.join("GameAssembly.dll").is_file(),mono: scripting_assemblies.iter().any(|a| a.contains("mscorlib"))&& !root.join("GameAssembly.dll").is_file(),- burst: scripting_assemblies.iter().any(|a| a.contains("Unity.Burst")),- urp: scripting_assemblies+ burst: scripting_assemblies.iter()- .any(|a| a.contains("UniversalRenderPipeline") || a.contains("Unity.RenderPipelines.Universal")),- hdrp: scripting_assemblies- .iter()- .any(|a| a.contains("HighDefinition") || a.contains("Unity.RenderPipelines.HighDefinition")),+ .any(|a| a.contains("Unity.Burst")),+ urp: scripting_assemblies.iter().any(|a| {+ a.contains("UniversalRenderPipeline") || a.contains("Unity.RenderPipelines.Universal")+ }),+ hdrp: scripting_assemblies.iter().any(|a| {+ a.contains("HighDefinition") || a.contains("Unity.RenderPipelines.HighDefinition")+ }),};let (verdict, confidence) = verdict(@@ -358,18 +353,19 @@ fn peek_metadata(data_dir: &Path) -> MetadataPeek {encrypted_or_obfuscated: false,note: None,},- Err(ghidrust_il2cpp::Error::EncryptedOrObfuscated { magic, version_field }) => {- MetadataPeek {- path: path_s,- present: true,- magic: Some(format!("{magic:#010x}")),- version: Some(version_field),- encrypted_or_obfuscated: true,- note: Some(format!(- "expected magic {METADATA_MAGIC:#010x}; treat as encrypted/obfuscated"- )),- }- }+ Err(ghidrust_il2cpp::Error::EncryptedOrObfuscated {+ magic,+ version_field,+ }) => MetadataPeek {+ path: path_s,+ present: true,+ magic: Some(format!("{magic:#010x}")),+ version: Some(version_field),+ encrypted_or_obfuscated: true,+ note: Some(format!(+ "expected magic {METADATA_MAGIC:#010x}; treat as encrypted/obfuscated"+ )),+ },Err(e) => MetadataPeek {path: path_s,present: true,@@ -407,10 +403,7 @@ fn classify_assemblies(names: &[String]) -> (Vec<String>, Vec<String>) {fn find_subsystem_manifests(data_dir: &Path) -> Vec<String> {let mut out = Vec::new();- let roots = [- data_dir.join("StreamingAssets"),- data_dir.join("Plugins"),- ];+ let roots = [data_dir.join("StreamingAssets"), data_dir.join("Plugins")];for root in roots {if !root.exists() {continue;@@ -512,11 +505,7 @@ mod tests {fn tempfile_dir(tag: &str) -> PathBuf {let mut p = std::env::temp_dir();- p.push(format!(- "ghidrust_unity_inv_{}_{}",- tag,- std::process::id()- ));+ p.push(format!("ghidrust_unity_inv_{}_{}", tag, std::process::id()));let _ = fs::remove_dir_all(&p);fs::create_dir_all(&p).unwrap();pdiff --git a/skill/README.md b/skill/README.mdindex a4417fe..10ad711 100644--- a/skill/README.md+++ b/skill/README.md@@ -33,7 +33,34 @@ cargo run -p ghidrust-gui --releaseWindows: `.\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` (current is `4`). 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 `crypt_constants` / `recover_strings` / `decode_bake` / `decode_magic` / `list_crypto_capabilities` (current is `6`). Restart MCP after rebuild if those or `process_*` are missing.++Smoke crypto surfaces:++```bash+./target/release/ghidrust crypt-constants fixtures/analysis_lab.pe --json+./target/release/ghidrust recover-strings fixtures/analysis_lab.pe --json+./target/release/ghidrust crypto-capabilities fixtures/analysis_lab.pe --json+./target/release/ghidrust decode bake -b64 SGVsbG8= -op FromBase64 --json+./target/release/ghidrust decode magic -b64 SGVsbG8= -depth 3 --crib Hello --json+./target/release/ghidrust decode bake -path fixtures/analysis_lab.pe -addr 0x140001000 -op Gunzip --annotate-va 0x140001000 --json+```++## Crypto how-to++Run the four tiers in order: **Find Crypt**, recovered strings, capability matching, then explicit or automatic recipe decoding.++```bash+./target/release/ghidrust analyze PATH --analyzer "Find Crypt" --json+./target/release/ghidrust crypt-constants PATH --algo AES --json+./target/release/ghidrust recover-strings PATH --only stack,tight,decoded --json+./target/release/ghidrust crypto-capabilities PATH --tag decrypt --json+./target/release/ghidrust decode bake -b64 SGVsbG8= -op FromBase64 --json+./target/release/ghidrust decode bake -hex CIPHERTEXT -op RC4 -key-hex KEY --json+./target/release/ghidrust decode magic -b64 SGVsbG8= -depth 3 -crib Hello --json+```++For agent calls, use `crypt_constants`, `recover_strings`, `list_crypto_capabilities`, `decode_bake`, and `decode_magic`. AES-GCM returns only the unauthenticated counter-mode plaintext path; it does not verify a tag. The living coverage matrix is [decrypt-feature-test-log.md](decrypt-feature-test-log.md).MCP for agents (register in Cursor / Claude Desktop / other MCP clients — see root README):diff --git a/skill/SKILL.md b/skill/SKILL.mdindex 00bab09..d2fa9b4 100644--- a/skill/SKILL.md+++ b/skill/SKILL.md@@ -2,13 +2,14 @@name: ghidrustdescription: >x86-64 Auto Analysis, projects, CLI/MCP, egui GUI, IL2CPP metadata, Unity player inventory,- GPU analyzer kernels + multipass decompile) to reverse-engineer binaries without .- Exhaustive feature catalog with when-to-use guidance.+ GPU analyzer kernels + multipass decompile, crypt-constants / recover-strings / decode bake /+ crypto-capabilities. Exhaustive feature catalog with when-to-use guidance.Triggers: /ghidrust, reverse engineer, RE a PE/ELF, disassemble, decode-support, decode-query,- MCP ghidrust, strings/functions, GPU decompile, IL2CPP, global-metadata, unity-inventory,- GameAssembly, analyzer-bench, rtti-gpu-bench, bulk-bench.+ MCP ghidrust, strings/functions, crypt-constants, recover-strings, decode bake, decode magic,+ crypto-capabilities, GPU decompile, IL2CPP, global-metadata, unity-inventory, GameAssembly,+ analyzer-bench, rtti-gpu-bench, bulk-bench.metadata:- short-description: "Ghidrust RE — multi-arch decode, CLI, MCP, IL2CPP, Unity, analyzers, GPU"+ short-description: "Ghidrust RE — decode, crypto recover, CLI, MCP, IL2CPP, Unity, analyzers, GPU"---# Ghidrust — agent skill@@ -56,7 +57,7 @@ JSON shape:| `features.decode_diet` | `false` — full detail path (not diet build) || `features.x86_reduce` | `false` — full x86 table (not x86 reduce build) |-`server_info` also sets **`tool_surface: 5`** and lists `decode_support` / `decode_query` under `features.surface`.+`server_info` also sets **`tool_surface: 6`** and lists decode + crypto tools under `features.surface` (`decode_support` / `decode_query` / `crypt_constants` / `recover_strings` / `decode_bake` / `decode_magic` / `list_crypto_capabilities`).### CLI — `disasm`, `decode-support`, `decode-query`@@ -117,7 +118,7 @@ Positional query name (without `--query`) is also accepted: `ghidrust decode-que### MCP — `disassemble`, `decode_support`, `decode_query`-Requires **`tool_surface >= 5`** (check `server_info` before assuming these tools/args exist).+Requires **`tool_surface >= 5`** for decode tools; **`>= 6`** for crypto recover / bake tools (check `server_info` before assuming these tools/args exist).#### `decode_support`@@ -247,7 +248,7 @@ Brief line (`--brief` / MCP `listing_text`): `{addr:#x}: {mnemonic} {operands}`.### Decode SOPs (required)-- **`tool_surface` check**: Call `server_info` first. This skill requires **`tool_surface >= 5`** for `decode_support`, `decode_query`, and extended `disassemble` decode args. If below 5 or tools missing from `tools/list` → rebuild `ghidrust`, restart MCP. (Broader Ghidrust surface still requires **`>= 3`**, prefer **`>= 4`** for bounded disasm / `get_calls_from`.)+- **`tool_surface` check**: Call `server_info` first. Require **`tool_surface >= 5`** for `decode_support`, `decode_query`, and extended `disassemble` decode args. Require **`>= 6`** for `crypt_constants`, `recover_strings`, `decode_bake`, `decode_magic`, `list_crypto_capabilities`. If below the needed minimum or tools missing from `tools/list` → rebuild `ghidrust`, restart MCP. (Broader surface still requires **`>= 3`**, prefer **`>= 4`** for bounded disasm / `get_calls_from`.)- **Decode mode decision tree**:- Need body of **unknown / wrong / suspect** bounds? → `disasm --linear --count N` first (ground truth) → `function create --addr` to heal → then `--flow` / `decompile` on healed range.- Need CFG inside a **known-good** function? → `--flow` (or default bounded).@@ -262,7 +263,8 @@ Brief line (`--brief` / MCP `listing_text`): `{addr:#x}: {mnemonic} {operands}`.## Agent friction SOPs (required)-- **Version / stale MCP**: Call `server_info` first (or read `initialize.serverInfo`). This skill requires **`tool_surface >= 3`** (touch-map, body_class map, function_create, live process + artifacts). Prefer **`>= 4`** for bounded disasm / `get_calls_from`. Require **`>= 5`** for `decode_support`, `decode_query`, and extended `disassemble` decode flags. If `server_info` is missing, `tool_surface` is below the needed minimum, or expected tools are absent from `tools/list` → rebuild `ghidrust`, point the MCP `command` at that binary, **restart the MCP server**. Do **not** conclude live process is unsupported; do **not** invent heap-scan scripts as a substitute. CLI/GUI/MCP share one package version (`ghidrust --version`, MCP `version`, egui About).+- **Version / stale MCP**: Call `server_info` first (or read `initialize.serverInfo`). This skill requires **`tool_surface >= 3`** (touch-map, body_class map, function_create, live process + artifacts). Prefer **`>= 4`** for bounded disasm / `get_calls_from`. Require **`>= 5`** for `decode_support`, `decode_query`, and extended `disassemble` decode flags. Require **`>= 6`** for crypt-constants / recover-strings / decode bake|magic / crypto-capabilities. If `server_info` is missing, `tool_surface` is below the needed minimum, or expected tools are absent from `tools/list` → rebuild `ghidrust`, point the MCP `command` at that binary, **restart the MCP server**. Do **not** conclude live process is unsupported; do **not** invent heap-scan scripts as a substitute. CLI/GUI/MCP share one package version (`ghidrust --version`, MCP `version`, egui About).+- **Crypto / obfuscated strings**: Prefer `crypt_constants` → `recover_strings` → `decode_bake`/`decode_magic` on leftover blobs; use `list_crypto_capabilities` to locate decrypt/encrypt API sites. Never invent plaintext — empty hits are honest.- **Artifacts**: When envelope `entry_count` > preview or the host truncates tool text, drain via `artifact_query` / `artifact get` until `next_offset` is null. Never assume truncated MCP text is complete.- **Program identity**: Prefer `load` with absolute `path`, or `project` + `file_id`. Facts always include `resolved_path` or honest null — resolve before analyze/decompile.- **Inventory / tree**: Use `inventory <dir>` (PE VERSIONINFO + exe/dll) before OS `dir`/`Get-Item`. Use `tree` / `list_tree` for non-PE sidecars (existence/size only; no unpack).@@ -308,6 +310,15 @@ Need GPU for selected analyzers (not just bench)?→ analyze … --gpu OR GUI checkbox OR MCP analyze gpu:true→ bulk mode for ASCII Strings + SIMT seed enrich per selected name+Need crypto constants / obfuscated strings / peel a blob?+ → crypt-constants PATH [--algo AES] --json+ → recover-strings PATH [--only stack,tight,decoded] --json+ → crypto-capabilities PATH [--tag decrypt] --json+ → decode bake (-b64|-hex|-path+-addr) -op FromBase64|XOR|… [--annotate-va HEX with -path] --json+ → decode magic (-b64|-hex|…) [-depth N] [--crib TEXT] --json+ → MCP: crypt_constants / recover_strings / list_crypto_capabilities / decode_bake / decode_magic+ → analyze --analyzer "Find Crypt" / "Obfuscated Strings" / "Crypto Capabilities"+Need GPU decompile at a VA?→ gpu-decompile <path> --addr HEX (metrics JSON; .gdecomp opaque)@@ -416,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). 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). Check with `server_info` after connect.| Tool | Args | Notes ||------|------|-------|@@ -432,6 +443,11 @@ Requires **`tool_surface >= 3`** (prefer **`>= 4`** for bounded disasm / `get_ca| `list_analyzers` | — | Auto Analysis names || `analyze` | `path`, optional `analyzers[]`, **`gpu`** | CPU + optional GPU enrich || `list_strings` / `search_strings` | `path`, optional `encoding`, `filter`, **`match`**, `min`, **`limit`**, **`raw`** | Blob scan when `raw:true` |+| `crypt_constants` / `list_crypt_constants` | `path`, optional `algo`, `limit` | Crypto constant tables (S-box, TEA delta, hash K, …) |+| `recover_strings` | `path`, optional `only[]`, `no[]`, `functions[]`, `limit` | Stack / tight / decoded obfuscated strings |+| `decode_bake` | `recipe`\|`ops`, plus `input_hex`\|`input_b64`\|`path`+`addr` (+ `count?`) | Recipe peel (FromBase64, XOR, AESDecrypt, …) |+| `decode_magic` | `depth?`, plus same input fields as bake | Auto peel chain by printable ratio |+| `list_crypto_capabilities` | `path`, optional `tag` | Encrypt/decrypt/encoding capability hits || `get_xrefs_to` | `path`, `addr`, optional **`skip_stubs`**, **`classify`** | RIP/tables + data ptrs; IL2CPP stubs; `to_entry` || `get_xrefs_from` | `path`, `addr`, optional `count` | Xrefs from VA; `from_entry` / `from_function` / `to_entry` || `get_calls_from` | `path`, `addr` | Callee edges inside containing function (CLI: `xrefs --calls`) |@@ -456,6 +472,129 @@ MCP launch: `ghidrust mcp` / `target/release/ghidrust.exe mcp` (stdio; no host-s---+## Crypto recover + decode bake (CLI + MCP) — `tool_surface >= 6`++Hand-rolled in-tree scanners and recipe peels. **Never invent plaintext** — empty hits / failed bake are honest. Prefer this pipeline:++1. **Find sites** — `crypt_constants` and/or `list_crypto_capabilities`+2. **Recover in-binary strings** — `recover_strings` (and/or Auto Analysis `Obfuscated Strings`)+3. **Peel leftover blobs** — `decode_bake` / `decode_magic` on hex, Base64 text, or VA ranges++### Phase A — Find Crypt / `crypt-constants`++Discovers cryptographic **constant tables** (AES S-box, TEA delta, MD5/SHA-256 K prefix, ChaCha sigma, Blowfish P, CRC32 tab, …). Labels `CRYPT_*` symbols when run via Auto Analysis.++| Surface | Invocation |+|---------|------------|+| CLI | `ghidrust crypt-constants <path> [--algo AES\|TEA\|…] [--limit N] [--json]` |+| Analyze | `ghidrust analyze <path> --analyzer "Find Crypt" --json` |+| MCP | `crypt_constants` / `list_crypt_constants` `{ path, algo?, limit? }` |++JSON hits: `{ va, algorithm, constant, size }`.++```bash+ghidrust crypt-constants fixtures/analysis_lab.pe --json+ghidrust analyze fixtures/analysis_lab.pe --analyzer "Find Crypt" --json+```++### Phase B — Obfuscated Strings / `recover-strings`++Recovers **stack**, **tight** (stack + nearby XOR), and **decoded** (single-byte XOR runs) strings from executable blocks.++| Surface | Invocation |+|---------|------------|+| CLI | `ghidrust recover-strings <path> [--only stack,tight,decoded] [--no static] [--functions HEX[,HEX…]] [--limit N] [--json]` |+| Analyze | `ghidrust analyze <path> --analyzer "Obfuscated Strings" --json` |+| MCP | `recover_strings` `{ path, only?, no?, functions?, limit? }` |++JSON hits: `{ va, value, kind, decoder_va?, call_site? }`.++```bash+ghidrust recover-strings PATH --only stack,tight,decoded --json+```++### Phase C — `decode bake` / `decode magic`++Recipe engine over buffers (not an Auto Analysis scanner). Input is **recipe input bytes**:++| Input flag / MCP field | Meaning |+|------------------------|---------|+| CLI `-hex HEX` / MCP `input_hex` | Hex bytes |+| CLI `-b64 TEXT` | Base64 **text** as UTF-8 bytes (add `-op FromBase64` to peel) |+| MCP `input_b64` | Base64-decoded input bytes |+| CLI `-raw TEXT` | Raw UTF-8 bytes |+| CLI `-in FILE` | File bytes |+| CLI `-path PATH -addr HEX [-count N]` / MCP `path`+`addr`+`count?` | Bytes from mapped image |++**Ops** (`-op NAME` or recipe JSON `[{op, args}]`): `FromBase64`, `FromHex`, `FromCharcode`, `UrlDecode`, `HtmlEntityDecode`, `XOR` (`key_hex`/`key`), `XORBrute`, `RC4`, `ChaCha20Decrypt` (`key_hex`, `nonce_hex`, `counter`), `AESDecrypt`, `DESDecrypt`, `TripleDESDecrypt`, `BlowfishDecrypt`, `Gunzip`, `Inflate`, `ROT13`, `Reverse`, `DecodeUTF16LE`. CLI operation arguments accept `-key`, `-key-hex`, `-iv`, `-iv-hex`, `-nonce`, `-nonce-hex`, `-counter`, `-mode`, and `-encoding`.++| Surface | Invocation |+|---------|------------|+| CLI bake | `ghidrust decode bake (-hex\|-b64\|-raw\|-in\|-path+-addr) [-recipe JSON \| -op NAME [-key\|-key-hex\|-iv\|-iv-hex\|-nonce\|-nonce-hex\|-counter\|-mode\|-encoding VALUE]…] [--annotate-va HEX with -path] [--json]` |+| CLI magic | `ghidrust decode magic (…) [-depth N] [--crib TEXT] [--json]` |+| MCP bake | `decode_bake` `{ recipe\|ops, input_hex\|input_b64\|path+addr, count?, annotate_va? }` |+| MCP magic | `decode_magic` `{ depth?, crib?, input_hex\|input_b64\|path+addr, count? }` |++```bash+# Base64 → plaintext+ghidrust decode bake -b64 SGVsbG8= -op FromBase64 --json++# XOR with key+ghidrust decode bake -hex 09040d0d0e -op XOR -key-hex 41 --json++# Auto peel+ghidrust decode magic -b64 SGVsbG8= -depth 3 --json++# Bytes at VA+ghidrust decode bake -path PATH -addr 0x140002000 -count 64 -op XORBrute --json++# Require a known plaintext fragment; annotate is in-memory only for a plain path load+ghidrust decode magic -hex 48656c6c6f -crib Hello --json+ghidrust decode bake -path PATH -addr 0x140002000 -op Gunzip --annotate-va 0x140002000 --json+```++MCP examples:++```json+{ "name": "decode_bake", "arguments": {+ "input_hex": "534756736247383d",+ "recipe": [{ "op": "FromBase64", "args": {} }]+}}+```++```json+{ "name": "decode_magic", "arguments": { "input_b64": "SGVsbG8=", "depth": 3 } }+```++Bake JSON: `{ result: { ok, output_hex, output_utf8?, message, recipe_applied[] }, iocs[], annotation? }`. `annotation` records whether an EOL comment was applied; plain path loads have no project save target, so such comments are explicitly reported as in-memory only. `crib` boosts a matching magic candidate.++### Phase D — Crypto Capabilities / `crypto-capabilities`++Matches encrypt/decrypt/encoding **capabilities** (WinCrypt/BCrypt/DPAPI-style imports, AES-NI opcodes, prior constant hits, stackstring presence). Tags: `decrypt` \| `encrypt` \| `encoding` \| `hashing`.++| Surface | Invocation |+|---------|------------|+| CLI | `ghidrust crypto-capabilities <path> [--tag decrypt\|encrypt\|encoding] [--json]` |+| Analyze | `ghidrust analyze <path> --analyzer "Crypto Capabilities" --json` |+| MCP | `list_crypto_capabilities` `{ path, tag? }` |++JSON hits: `{ function_va?, capability, tag, evidence, attack?, mbc? }`.++```bash+ghidrust crypto-capabilities PATH --tag decrypt --json+```++### Agent SOP (crypto)++1. `server_info` → confirm `tool_surface >= 6`.+2. `crypt_constants` + `list_crypto_capabilities` to locate algorithms / API decrypt sites.+3. `recover_strings` (or `analyze` with `Obfuscated Strings`) for hidden IOCs.+4. On opaque blobs / resources / VA ranges → `decode_magic` first; if key/IV known → `decode_bake` with explicit ops.+5. Chain: constants/capabilities → seed `recover_strings` `--functions` → bake remnants.+6. Do **not** claim decrypted plaintext without a successful bake/`ok: true` or recovered string hit.++---+## Unity / IL2CPP (CLI + MCP)Canonical detail: [`docs/IL2CPP.md`](../docs/IL2CPP.md).@@ -652,13 +791,16 @@ Output column names the field on `AnalyzerOutput` you get in `--json`| 3 | `Call Convention ID` | Tags each function with Win64/cdecl/stdcall/thiscall. | `conventions: [[va, name], …]` (+ `functions[*].calling_convention`) | `identified N calling convention(s)` || 4 | `Call-Fixup Installer` | Security-cookie / thunk stub detection. | `call_fixups: [{fixup_name, call_va}]` | `installed N call fixup(s)` || 5 | `Create Address Tables` | Contiguous VA tables in `.rdata` / data. | `address_tables: [{base, count, entries: [va, …]}]` | `found N address table(s)` |+| 5b | `Crypto Capabilities` | Encrypt/decrypt/encoding capability matches (imports, AES-NI, constant seeds). | `crypto_capabilities: [{function_va?, capability, tag, evidence, attack?, mbc?}]` | `matched N crypto/encoding capability hit(s)` || 6 | `Decompiler Parameter ID` | `mov [rbp+…], rcx/rdx` spill detection → `arg0:rcx` / `arg1:rdx`. No inventions on bare bodies. | `functions: [{entry, parameters: [str,…]}]` | `recovered parameters for N function(s)` || 7 | `Decompiler Switch Analysis` | Address tables → switch cases. | `switches: [{jump_va, cases: [[val, target], …]}]` | `recovered N switch table(s)` || 8 | `Demangler Microsoft` | MSVC `?…@@` demangler; `demangled` alongside raw. | `symbols: [{name, va, demangled?}]` | `demangled N symbol(s)` || 9 | `Embedded Media` | PNG / JPG / GIF / WAV / … magic scan. | `media: [{kind, va}]` | `found N media signature(s)` |+| 9b | `Find Crypt` | Cryptographic constant tables (S-box, TEA delta, hash K, stream sigma, …). | `crypt_constants: [{va, algorithm, constant, size}]` | `found N cryptographic constant hit(s)` || 10 | `Function ID` | Prologue-window hash → shipped `fid_*` catalog match. | `fid_matches: [{entry, matched_name}]` | `matched N FID signature(s)` || 11 | `Function Start Search` | Entry + symbols + exact `55 48 89 e5` + orphan `sub rsp, imm8`; grows to `ret`/`int3`; drops mid-body seeds. | `functions: [{entry, end, name}]` | `identified N function start(s)` || 12 | `Non-Returning Functions - Discovered` | `int3`-terminated bodies + known no-return imports. | `noreturn_entries: [va, …]` (+ `functions[*].noreturn`) | `marked N noreturn function(s)` |+| 12b | `Obfuscated Strings` | Stack / tight / decoded string recovery from executable blocks. | `obfuscated_strings: [{va, value, kind, decoder_va?, call_site?}]` | `recovered N obfuscated string(s)` || 13 | `PDB MSDIA` | MSF7 reader with MSDIA-shaped filtering. | `symbols: [{name, va}]` | `parsed N PDB symbol(s) (msdia→universal)` || 14 | `PDB Universal` | MSF7 reader, unfiltered stream symbols (`MSF7` marker included). | `symbols: [{name, va}]` | `parsed N PDB symbol(s) (universal)` || 15 | `Shared Return Calls` | Callers reusing one epilogue (tail-call). | `shared_returns: [va, …]` | `marked N shared return site(s)` |@@ -668,7 +810,7 @@ Output column names the field on `AnalyzerOutput` you get in `--json`| 19 | `Windows x86 Propagate External Parameters` | Known Win32 API prototypes attached to import call sites. | `external_params: [[va, prototype], …]` | `applied N external parameter prototype(s)` || 20 | `WindowsResourceReference` | `.rsrc` records (`VERSION`, `RT_ICON`, …). | `resources: [{name, va}]` | `parsed N resource record(s)` |-**Defaults** (empty selection): `ASCII Strings`, `Unicode Strings`, `WindowsPE x86 PE RTTI Analyzer`, `Function Start Search`, `Create Address Tables`, `Embedded Media`, `Demangler Microsoft`.+**Defaults** (empty selection): `ASCII Strings`, `Unicode Strings`, `WindowsPE x86 PE RTTI Analyzer`, `Function Start Search`, `Create Address Tables`, `Embedded Media`, `Demangler Microsoft`, `Find Crypt`.With `--gpu`: same CPU output plus a `| gpu_enrich hits_merged=… backend=…` suffix on the human message. Not a replacement for `gpu-decompile`.