Craft Anything: understand how any software works, and craft your own.
Rust
Every engine listing finds a Ghidra installed in a versioned folder or set through its folder setting (#55)
Tommy Leonhardsen63aaaeeb08ac
diff --git a/apps/craft-anything-cli/src/main.rs b/apps/craft-anything-cli/src/main.rsindex 5a6f143b..4570ea2b 100644--- a/apps/craft-anything-cli/src/main.rs+++ b/apps/craft-anything-cli/src/main.rs@@ -341,7 +341,7 @@ fn capabilities(cli: &Cli, f: Format) -> u8 {let engines: Vec<Value> = craft_anything_engines::ENGINES.iter().map(|e| {- let found = craft_anything_engines::locate(e.id, &session.settings.engines.tools, &session.settings.engine_store_dir());+ let found = session.settings.engine_path(e.id);json!({"id": e.id, "name": e.name, "needed_for": e.needed_for, "found": found.is_some(), "path": found, "installable_here": e.host_pin().is_some()})}).collect();diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 20fe8cae..e84faa61 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -176,7 +176,7 @@ impl Engine {Availability::no("This needs Deep mode (with Ghidra), and you're in Clean room mode.", "Turn on Deep mode in the title bar or Settings.")}}- Requires::Engine(id) => match craft_anything_engines::locate(id, &session.settings.engines.tools, &session.settings.engine_store_dir()) {+ Requires::Engine(id) => match session.settings.engine_path(id) {Some(_) => Availability::ok(),None => Availability::no(format!("This needs {} installed.", craft_anything_engines::display_name(id)),diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rsindex ecf7655a..23b868bb 100644--- a/crates/engine/src/settings.rs+++ b/crates/engine/src/settings.rs@@ -384,6 +384,18 @@ impl Settings {pub fn ghidra_java(&self) -> Option<PathBuf> {craft_anything_engines::ghidra::get::java_home(self.engines.ghidra.java_home.as_deref(), &self.engine_store_dir())}++ /// Where an external engine is on this computer, honouring every setting that can name one:+ /// the path overrides (`engines.tools`) and, for Ghidra, its own folder setting+ /// (`engines.ghidra.install_dir`). The one lookup behind every listing (`engines_list`,+ /// `doctor`, `capabilities`) and behind `Requires::Engine`, so they all agree with what Deep+ /// mode actually runs.+ pub fn engine_path(&self, id: &str) -> Option<PathBuf> {+ if id == craft_anything_engines::ghidra::get::ID {+ return self.ghidra_launcher();+ }+ craft_anything_engines::locate(id, &self.engines.tools, &self.engine_store_dir())+ }}#[cfg(test)]diff --git a/crates/engine/src/tools/setup_tools.rs b/crates/engine/src/tools/setup_tools.rsindex 8e6676fc..fd189137 100644--- a/crates/engine/src/tools/setup_tools.rs+++ b/crates/engine/src/tools/setup_tools.rs@@ -392,7 +392,7 @@ fn engines_list(ctx: &mut Ctx<'_>, _params: Value) -> Result<ToolOutput, ToolErr"id": e.id,"name": e.name,"needed_for": e.needed_for,- "found": craft_anything_engines::locate(e.id, &s.engines.tools, &store).map(|p| p.display().to_string()),+ "found": s.engine_path(e.id).map(|p| p.display().to_string()),"installable_here": e.host_pin().is_some(),})})@@ -613,6 +613,25 @@ mod tests {assert!(e.call("engines_install", json!({"engine": "no-such-engine"}), CallOptions::new(Caller::Cli)).is_err());}+ /// A Ghidra chosen through its own folder setting is what Deep mode runs, so the listing says+ /// it's there (it once said "not found" while `native_function_pseudocode` used it).+ #[test]+ fn a_ghidra_folder_setting_shows_in_engines_list() {+ let dir = tempfile::tempdir().unwrap();+ let exe = if cfg!(windows) { "analyzeHeadless.bat" } else { "analyzeHeadless" };+ let launcher = dir.path().join("support").join(exe);+ std::fs::create_dir_all(launcher.parent().unwrap()).unwrap();+ std::fs::write(&launcher, b"x").unwrap();+ let mut s = crate::testing::session();+ s.settings.engines.ghidra.install_dir = Some(dir.path().to_path_buf());+ assert_eq!(s.settings.engine_path("ghidra"), Some(launcher.clone()));+ let e = Engine::new(s);+ let out = e.call("engines_list", json!({}), CallOptions::new(Caller::Cli)).unwrap().to_json();+ let ghidra = out["result"]["engines"].as_array().unwrap().iter().find(|v| v["id"] == "ghidra").unwrap();+ assert_eq!(ghidra["found"].as_str(), Some(launcher.display().to_string().as_str()));+ assert_eq!(out["result"]["deep_mode"]["ghidra"], ghidra["found"]);+ }+#[test]fn an_isolated_session_keeps_settings_in_its_own_folder() {let s = crate::testing::session();diff --git a/crates/engines/src/ghidra/get.rs b/crates/engines/src/ghidra/get.rsindex 7c74c10b..f8bf9ff0 100644--- a/crates/engines/src/ghidra/get.rs+++ b/crates/engines/src/ghidra/get.rs@@ -5,6 +5,8 @@ use craft_anything_evidence::{ErrorCode, ToolError};use craft_anything_platform::process::Cancel;use std::path::{Path, PathBuf};+/// Ghidra's engine id, as the engine table, Settings and every listing name it.+pub const ID: &str = "ghidra";/// The Ghidra release Craft Anything installs (it needs Java 21).pub const VERSION: &str = "12.1.4";/// What the person downloads, for the question we ask first (Ghidra 543 MB + Java 196 MB).@@ -20,7 +22,7 @@ fn pin(id: &str) -> Option<&'static crate::Pin> {/// Whether [`install`] works on this computer: Ghidra and its Java both have a pin here (Java is/// pinned for Windows x64 and for Linux and macOS on x64 and arm64).pub fn can_install() -> bool {- pin("ghidra").is_some() && pin("java").is_some()+ pin(ID).is_some() && pin("java").is_some()}/// Ghidra's headless launcher: in the folder the person picked (Ghidra's own folder, or one that@@ -34,7 +36,7 @@ pub fn headless(install_dir: Option<&Path>, store: &Path) -> Option<PathBuf> {return Some(p);}}- in_child(&store.join("ghidra"), launcher).or_else(|| crate::find_on_path(&["analyzeHeadless.bat", "analyzeHeadless"]))+ in_child(&store.join(ID), launcher).or_else(|| crate::find_on_path(&["analyzeHeadless.bat", "analyzeHeadless"]))}/// The Java runtime to run Ghidra with: the one the person set, else the managed one. `None` lets@@ -47,7 +49,7 @@ pub fn java_home(java_home: Option<&Path>, store: &Path) -> Option<PathBuf> {/// store, then point Ghidra at that Java. `progress` gets (what, bytes so far, total); a step with/// no bytes (0, `None`) is setting up. Returns the headless launcher.pub fn install(store: &Path, cancel: Option<Cancel>, progress: &dyn Fn(&str, u64, Option<u64>)) -> Result<PathBuf, ToolError> {- let (Some(ghidra), Some(java)) = (pin("ghidra"), pin("java")) else {+ let (Some(ghidra), Some(java)) = (pin(ID), pin("java")) else {return Err(ToolError::new(ErrorCode::NotSupported, "Ghidra can't be installed for you on this computer.").with_remediation(format!("Install Ghidra {VERSION} from {PAGE}, then choose its folder in Settings → Engines.")));};diff --git a/crates/engines/src/lib.rs b/crates/engines/src/lib.rsindex 0a04326a..f0468db6 100644--- a/crates/engines/src/lib.rs+++ b/crates/engines/src/lib.rs@@ -54,12 +54,8 @@ pub fn locate(id: &str, overrides: &dyn ToolPathLookup, store: &Path) -> Option<}let e = engine(id)?;let exes = e.host_exes();- for exe in exes {- for candidate in [store.join(id).join("bin").join(exe), store.join(id).join(exe)] {- if candidate.is_file() {- return Some(candidate);- }- }+ if let Some(p) = in_managed(&store.join(id), exes) {+ return Some(p);}// A single-file install (a .jar) is found by the name its pin saved it under.for pin in e.pins() {@@ -72,6 +68,19 @@ pub fn locate(id: &str, overrides: &dyn ToolPathLookup, store: &Path) -> Option<find_on_path(exes).or_else(|| e.known_install_paths().into_iter().find(|p| p.is_file()))}+/// An executable in a managed install folder: `<dir>/<exe>`, `<dir>/bin/<exe>` or+/// `<dir>/support/<exe>`, in `dir` itself or in one of its sub-folders, newest name first (an+/// archive unpacks into one top folder, often versioned: `ghidra_12.1.4_PUBLIC/support/…`).+fn in_managed(dir: &Path, exes: &[&str]) -> Option<PathBuf> {+ let here = |d: &Path| exes.iter().flat_map(|exe| [d.join(exe), d.join("bin").join(exe), d.join("support").join(exe)]).find(|p| p.is_file());+ if let Some(p) = here(dir) {+ return Some(p);+ }+ let mut subs: Vec<PathBuf> = std::fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();+ subs.sort();+ subs.iter().rev().find_map(|d| here(d))+}+/// Standard install locations for programs that don't put themselves on PATH (browsers on/// Windows and macOS), most common first.pub fn well_known(id: &str) -> Vec<PathBuf> {@@ -108,6 +117,27 @@ mod tests {assert_eq!(display_name("adb"), "Android platform tools (adb)");}+ /// Ghidra's zip unpacks into `<store>/ghidra/ghidra_<version>_PUBLIC/`, with the launcher in+ /// `support/`; `engines_list` said "not found" for an install that Deep mode was using.+ #[test]+ fn a_managed_install_in_a_versioned_folder_is_found() {+ let store = tempfile::tempdir().unwrap();+ let exe = if cfg!(windows) { "analyzeHeadless.bat" } else { "analyzeHeadless" };+ let launcher = store.path().join("ghidra").join("ghidra_12.1.4_PUBLIC").join("support").join(exe);+ std::fs::create_dir_all(launcher.parent().unwrap()).unwrap();+ std::fs::write(&launcher, b"x").unwrap();+ assert_eq!(locate("ghidra", &NoOverrides, store.path()), Some(launcher));+ // An older unpack beside it loses to the newest name.+ let newer = store.path().join("ghidra").join("ghidra_12.2.0_PUBLIC").join("support").join(exe);+ std::fs::create_dir_all(newer.parent().unwrap()).unwrap();+ std::fs::write(&newer, b"x").unwrap();+ assert_eq!(locate("ghidra", &NoOverrides, store.path()), Some(newer));+ // Nothing but folders: still none, not a panic.+ let empty = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(empty.path().join("ghidra").join("ghidra_12.1.4_PUBLIC")).unwrap();+ assert!(locate("ghidra", &NoOverrides, empty.path()).is_none());+ }+#[test]fn browsers_have_well_known_locations_off_path() {assert!(well_known("adb").is_empty());diff --git a/crates/engines/src/table.rs b/crates/engines/src/table.rsindex 8a344236..878bfe26 100644--- a/crates/engines/src/table.rs+++ b/crates/engines/src/table.rs@@ -317,7 +317,7 @@ const fn manual(/// (the `tool_paths!` list in the engine crate, which a test keeps identical to this order).pub const ENGINES: &[ExternalEngine] = &[ExternalEngine {- id: "ghidra",+ id: crate::ghidra::get::ID,name: "Ghidra",needed_for: "Deep mode: richer decompiled code",exes: &["analyzeHeadless"],diff --git a/crates/setup/src/doctor.rs b/crates/setup/src/doctor.rsindex 8f348624..d8ed4dc9 100644--- a/crates/setup/src/doctor.rs+++ b/crates/setup/src/doctor.rs@@ -155,10 +155,9 @@ pub fn doctor(host: &Host, req: &DoctorRequest) -> DoctorReport {// Optional engines.if req.engines {let settings = craft_anything_engine::Settings::load();- let store = settings.engine_store_dir();for e in craft_anything_engines::ENGINES {let name = format!("engine:{}", e.id);- checks.push(match craft_anything_engines::locate(e.id, &settings.engines.tools, &store) {+ checks.push(match settings.engine_path(e.id) {Some(p) => Check::new(name, CheckStatus::Ok, format!("{}: {}", e.name, p.display())),None => Check::new(name, CheckStatus::Info, format!("{} not found (optional; {}).", e.name, e.needed_for)),});