From 610fff489647a99caaab95fe50efcb619abf699f Mon Sep 17 00:00:00 2001 From: Fadlalla-ai Date: Mon, 16 Nov 2026 16:56:00 +0400 Subject: [PATCH] Follow a Ghidra setting that names a file to its Ghidra folder, and never run anything else as Ghidra --- crates/engines/src/ghidra/get.rs | 167 ++++++++++++++++++++++++++++++- docs/ROADMAP.md | 10 +- docs/STATUS.md | 2 +- 3 files changed, 171 insertions(+), 8 deletions(-) diff --git a/crates/engines/src/ghidra/get.rs b/crates/engines/src/ghidra/get.rs index b67dadd13..74fa62a63 100644 --- a/crates/engines/src/ghidra/get.rs +++ b/crates/engines/src/ghidra/get.rs @@ -42,16 +42,77 @@ pub fn headless(install_dir: Option<&Path>, store: &Path) -> Option { /// [`headless`] finds before it looks around the computer. pub fn headless_configured(install_dir: Option<&Path>, store: &Path) -> Option { if let Some(dir) = install_dir { - if dir.is_file() { - return Some(dir.to_path_buf()); - } - if let Some(p) = in_root_or_child(dir, launcher) { - return Some(p); + let found = if dir.is_file() { launcher_from_file(dir) } else { in_root_or_child(dir, launcher) }; + if found.is_some() { + return found; } } in_child(&store.join(ID), launcher) } +/// Longest start script read when following one to its Ghidra folder. +const SCRIPT_CAP: u64 = 16 * 1024; +/// Most paths a start script names that are looked at on disk. +const SCRIPT_PATHS: usize = 32; + +/// Ghidra's headless launcher from a file the person picked as Ghidra's folder. Whatever is returned +/// is run as the launcher, so it is only ever Ghidra's own `support/analyzeHeadless` or a script +/// that runs it: +/// - the file itself when it is that launcher (by name, as given, even through a link), or a script +/// naming that launcher (a wrapper that sets up Java first, say); +/// - else the launcher of the Ghidra folder the file is in, links followed (`ghidraRun` on PATH as +/// a link); +/// - else, for a start script such as the one Linux packages put on PATH +/// (`exec /opt/ghidra/ghidraRun "$@"`), the launcher of the Ghidra folder it names. +/// +/// Anything else is `None`, so the setting isn't listed as Ghidra. +fn launcher_from_file(file: &Path) -> Option { + let exes = crate::engine(ID)?.host_exes(); + let is_launcher = |p: &Path| p.file_name().is_some_and(|n| exes.iter().any(|exe| n == *exe)); + let real = std::fs::canonicalize(file).ok()?; + if is_launcher(file) || is_launcher(&real) { + return Some(file.to_path_buf()); + } + let folder_of = |p: &Path| p.parent().and_then(|dir| launcher(dir).or_else(|| dir.parent().and_then(launcher))); + // The path as given first: on Windows `canonicalize` adds `\\?\`, which batch files handle badly. + if let Some(found) = folder_of(file).or_else(|| folder_of(&real)) { + return Some(found); + } + let named = named_in_script(&real)?; + if named.iter().any(|p| is_launcher(p) && p.is_file()) { + return Some(file.to_path_buf()); + } + named.iter().find_map(|p| if p.is_dir() { launcher(p) } else { folder_of(p) }) +} + +/// The absolute paths a short text file names that are on disk, as a start script names Ghidra's +/// folder (`None` when it is too long or isn't text). A quoted path is taken whole, spaces and all. +/// One level only: a script it names isn't read in turn. +fn named_in_script(file: &Path) -> Option> { + use std::io::Read; + let mut bytes = Vec::new(); + std::fs::File::open(file).ok()?.take(SCRIPT_CAP + 1).read_to_end(&mut bytes).ok()?; + if bytes.len() as u64 > SCRIPT_CAP || bytes.contains(&0) { + return None; + } + let text = String::from_utf8(bytes).ok()?; + // Between quotes first (odd pieces of a split on that quote), then word by word. + let quoted = ['"', '\''].into_iter().flat_map(|q| text.split(q).skip(1).step_by(2)); + // `$GHIDRA_HOME/ghidraRun` after `GHIDRA_HOME=/opt/ghidra`: the assigned folder is named too. + let words = text.split(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | '=' | ';' | '`' | '(' | ')')); + let mut paths: Vec = Vec::new(); + for p in quoted.chain(words).map(PathBuf::from).filter(|p| p.is_absolute()) { + if !paths.contains(&p) { + paths.push(p); + } + if paths.len() == SCRIPT_PATHS { + break; + } + } + paths.retain(|p| p.exists()); + Some(paths) +} + /// The Java runtime to run Ghidra with: the one the person set, else the managed one. `None` lets /// Ghidra look for its own. pub fn java_home(java_home: Option<&Path>, store: &Path) -> Option { @@ -262,6 +323,102 @@ mod tests { assert_eq!(java_home(Some(d.path()), &store).as_deref(), Some(d.path()), "a Java the person set wins"); } + const EXE: &str = if cfg!(windows) { "analyzeHeadless.bat" } else { "analyzeHeadless" }; + + /// A Ghidra folder as its zip unpacks: `ghidraRun` at the top, the headless launcher in `support/`. + fn ghidra_folder(at: &Path) -> PathBuf { + touch(&at.join("ghidraRun")); + let exe = at.join("support").join(EXE); + touch(&exe); + exe + } + + fn same(a: Option, b: &Path) -> bool { + a.and_then(|a| std::fs::canonicalize(a).ok()) == std::fs::canonicalize(b).ok() + } + + /// A Ghidra setting that names a file is run as Ghidra's headless launcher, so it has to be one. + #[test] + fn a_setting_naming_the_launcher_itself_is_that_launcher() { + let d = tempfile::tempdir().unwrap(); + let exe = ghidra_folder(&d.path().join("ghidra_12.1.4_PUBLIC")); + assert_eq!(headless_configured(Some(&exe), &d.path().join("store")), Some(exe)); + } + + /// Arch's package puts a start script on PATH that runs `/opt/ghidra/ghidraRun`, Ghidra's window, + /// not its headless launcher: picked as the setting, it was listed as found and Deep mode + /// quietly used the built-in decompiler. + #[test] + fn a_start_script_is_followed_to_the_ghidra_folder_it_names() { + let d = tempfile::tempdir().unwrap(); + let root = d.path().join("opt").join("My Ghidra"); + let exe = ghidra_folder(&root); + let script = d.path().join("bin").join("ghidra"); + let store = d.path().join("store"); + let mut bodies = vec![ + format!("#!/bin/sh\nexec \"{}\" \"$@\"\n", root.join("ghidraRun").display()), + format!("#!/bin/sh\nGHIDRA_HOME='{}'\nexec \"$GHIDRA_HOME/ghidraRun\" \"$@\"\n", root.display()), + ]; + let plain = d.path().join("opt").join("ghidra"); + if !plain.display().to_string().contains(' ') { + ghidra_folder(&plain); + bodies.push(format!("#!/bin/sh\nexec {}/ghidraRun \"$@\"\n", plain.display())); + } + for body in bodies { + touch(&script); + std::fs::write(&script, &body).unwrap(); + let found = headless_configured(Some(&script), &store); + assert!(same(found.clone(), &exe) || same(found, &plain.join("support").join(EXE)), "{body}"); + assert!(!headless_configured(Some(&script), &store).unwrap().display().to_string().starts_with(r"\\?\")); + } + // Too long to be a start script: not read. + std::fs::write(&script, format!("{}\nexec \"{}\"\n", "#".repeat(SCRIPT_CAP as usize), root.join("ghidraRun").display())).unwrap(); + assert_eq!(headless_configured(Some(&script), &store), None); + } + + /// A script that runs the headless launcher itself (setting up Java first, say) is run as it is. + #[test] + fn a_wrapper_around_the_launcher_is_kept() { + let d = tempfile::tempdir().unwrap(); + let exe = ghidra_folder(&d.path().join("ghidra")); + let wrapper = d.path().join("bin").join("ghidra-headless"); + touch(&wrapper); + std::fs::write(&wrapper, format!("#!/bin/sh\nJAVA_HOME=/jdk exec \"{}\" \"$@\"\n", exe.display())).unwrap(); + assert_eq!(headless_configured(Some(&wrapper), &d.path().join("store")), Some(wrapper)); + } + + #[test] + fn a_file_that_leads_to_no_ghidra_is_not_ghidra() { + let d = tempfile::tempdir().unwrap(); + let store = d.path().join("store"); + let notes = d.path().join("notes.txt"); + std::fs::write(¬es, "nothing to see").unwrap(); + assert_eq!(headless_configured(Some(¬es), &store), None); + let script = d.path().join("ghidra"); + std::fs::write(&script, format!("#!/bin/sh\nexec {}/ghidraRun \"$@\"\n", d.path().join("gone").display())).unwrap(); + assert_eq!(headless_configured(Some(&script), &store), None); + std::fs::write(&script, [0xff, 0xfe, 0x00, 0x2f]).unwrap(); + assert_eq!(headless_configured(Some(&script), &store), None, "not text"); + // With nothing usable set, the managed install is still found. + let managed = ghidra_folder(&store.join(ID).join("ghidra_12.1.4_PUBLIC")); + assert_eq!(headless_configured(Some(¬es), &store), Some(managed)); + } + + /// Homebrew and some packages link `ghidraRun` onto PATH instead. + #[cfg(unix)] + #[test] + fn a_link_to_ghidras_start_script_is_followed_to_its_folder() { + let d = tempfile::tempdir().unwrap(); + let root = d.path().join("Caskroom").join("ghidra_12.1.4_PUBLIC"); + let exe = ghidra_folder(&root); + let bin = d.path().join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + std::os::unix::fs::symlink(root.join("ghidraRun"), bin.join("ghidraRun")).unwrap(); + assert!(same(headless_configured(Some(&bin.join("ghidraRun")), &d.path().join("store")), &exe)); + std::os::unix::fs::symlink(&exe, bin.join(EXE)).unwrap(); + assert_eq!(headless_configured(Some(&bin.join(EXE)), &d.path().join("store")), Some(bin.join(EXE)), "a linked launcher is kept as given"); + } + #[test] fn the_java_override_is_read_as_ghidra_reads_it() { let env = |k: &str| (k == "JDK_HOME").then(|| "/opt/jdk-25".to_string()); diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index cfa4072d3..8f9d0c0bd 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -774,10 +774,16 @@ yet, and the quick start is how every new person begins. Deep mode) — claimed: Fadlalla-ai, branch test/ghidra-setup-linux - [ ] Ghidra setup tried for real on macOS (the Java pins were checked by tests only) -- [ ] A Ghidra folder setting that names a file, such as the `/usr/bin/ghidra` start script, is listed as +- [x] A Ghidra folder setting that names a file, such as the `/usr/bin/ghidra` start script, is listed as found by `engines_list`, but Deep mode then quietly decompiles with the built-in lifter instead; - refuse it, or follow the script to its Ghidra folder + refuse it, or follow the script to its Ghidra folder. A file is now run only when it is the + headless launcher or a script that runs it; a link or start script is followed to its Ghidra + folder; anything else isn't listed as found. Live in Debian 13 with Ghidra 12.1.4 laid out as + Arch-based packages do: `/usr/bin/ghidra` and a linked `ghidraRun` now decompile with Ghidra — claimed: Fadlalla-ai, branch bugfix/r5.7-ghidra-setting-names-a-file +- [ ] Settings → Engines looks Ghidra up on every frame it shows "Installed" (`engine_ui.rs`, the + hover text calls `ghidra_launcher`): folders searched, and a start script read, while drawing. + Keep the path found with `GhidraFlow::ready` instead - [x] A Ghidra with no decompiler program for this computer (public downloads leave out macOS) is refused before the long analysis, with the command that builds it; checked on a real Mac - [ ] `engines_install` builds Ghidra's native programs on macOS, so a Mac install works unaided diff --git a/docs/STATUS.md b/docs/STATUS.md index eb483944d..aa13f2de4 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -375,7 +375,7 @@ coverage and secrets passed. The companion CLI was built with locked dependencie | Builder tool lists | Each API backend's `tools` in `[[ai.backends]]` picks the tools a builder on it is offered. Lean is the building list (#417, `LOCAL_BUILDER_CORE`) and a system prompt without the memory steps; Full is every tool and the memory steps. Auto (the default) is Full on a paid service, and on a local model Full when the conversation's budget is `FULL_TOOLS_BUDGET` (49,152, a 64k window less its quarter) or more, else Lean, so a local model with no window known stays lean as before. The loop asks the server for its window before choosing and chooses again before each turn, rewriting the system prompt when the list changes (journaled as `tools`). Chats keep every tool (R5.4). Choose it in Settings → AI, which shows what Auto works out to for that AI (by its window on a local model, every tool on a paid service), or with `ai tools [auto|lean|full]`; Auto is saved as no setting, and agent apps are refused (they choose their own tools) | `ai_tools_reads_changes_and_clears_an_api_backends_tool_list` and `an_api_backends_tool_list_is_chosen_in_settings` cover the CLI and the Settings choice. `a_builders_tool_list_follows_its_setting_and_the_servers_window` covers each setting on local and paid backends, a window named after the first turn (lean, then full), a set budget and a chat; it was seen to fail when the prompt wasn't rewritten and when the server wasn't asked before choosing. Live on Linux, a Qwen model with a 512k window through llama-swap (2× RTX 6000), "a scientific calculator" with no target and one refinement round, unattended: Auto chose the full list (budget 393,216) before the first request. 2 of 3 full-list builds were Ready (22 and 26 minutes, the check's screenshot a working calculator) and used the brief, handoff and finding tools, one also enabling the Runtime toolset to read its own window; the third stopped at check 2 in 3 minutes after the model twice wrote calls to tools that don't exist (`web_search`, `web_fetch`) as text, which ended its turn. The same build on the lean list was Ready in 32 minutes. A small local model wasn't run | | Games | Engine detection for 12 engines (Unreal, Unity, Godot, Source, GameMaker, RPG Maker, Ren'Py, MonoGame, LÖVE, CryEngine, Cocos, Cube) with versions. Unreal and Godot games are rebuilt in the same engine, others in Unity; installed engines are found, Godot installs itself, others get guided installs. Picking an inner folder (Engine, Binaries, Paks…) finds the game's folder. Just look inside a game shows what it's made of (`core_target_triage` on its folder: engine and version, how its code ships, the libraries its Unity assembly names give away, its own code, scenes and size) and opens it in the chat to ask about it. The builder keeps `app/MECHANICS.md` and its structured twin `app/mechanics.json` (checked after each build), in Deep mode only, may reuse the original's readable files for private use (never decrypting; generated pictures and 3D models replace its art when the person turns them on; Clean room copies none of its files), lists them in `CREDITS.md` (checked, with the private-use line in `README.md`); a game is ready only when its `--self-test` shows the player moving, acting and the HUD drawn, and the result can be started from the project page | Unit tests; live runs on Windows | | Explicit Phaser and Bevy game requests | A request to use Phaser or Bevy selects that framework without requesting an editor installation. | Seven stack catalogue tests on Linux, including Phaser with Vite, Bevy, and a phaser cannon mentioned in game content. | -| Clean room and Deep mode | Clean room (the default) runs only the tools in `engine/src/clean_room.rs`: ones that touch no target or watch from outside (the website as a visitor sees it, pictures of a window, its controls, recorded runs, a phone's screen). Every other tool, a plugin's included, is refused in the app, CLI, MCP and agents, with a way to turn on Deep mode. A Clean room build studies an app or a game only from the person's pictures and words (and a picture of its window when runtime study is on); its builder's reads and commands go through an approval rule that keeps it out of the original's folder and site (with Claude Code, and with ACP agents for what they ask about; other agents aren't held to it, see roadmap R2.2). A builder over SSH starts the remote host's own `craft-anything-cli mcp` with this run's `--deep` or `--clean-room`, so the remote settings don't decide the mode; every release since 0.1.0 knows those flags and `--all-tools`, the only ones it is given (a test on `mcp_for` keeps it so; Codex's adapter adds only `--all-tools`). Claude Code, Codex and OpenCode builds over SSH first check that the host has `craft-anything-cli`. No release up to 0.5.0 reads `CRAFT_ANYTHING_AGENT`, so there a CLI the remote builder starts calls tools as the person (R2.8). Deep mode (`deep_mode` in Settings, `--deep` for one CLI run) uses every tool: the builder sees them all, and a website's study also reads its JavaScript and watches its start page for ten seconds (capture/how-it-works.md). Ghidra adds its decompiler in Deep mode when it's installed: it is found, or installed after asking. Study starts one analysis of the main program, saved and shared with the builder's tool server through a lock file (up to 8 h, Java gets half the machine's memory or the amount set in Settings → Engines, 4 to 31 GB, four slow passes skipped). The builder must decompile before the build is checked; addresses the built-in analysis can't place go to Ghidra, which makes a function on demand (for this run only) where its analysis has none, e.g. code reached only through tables of pointers. Before a decompile, a jump on a byte through a table with no bounds check (Rust's async state machines) is cut to the table's real entries, so it doesn't run away (#1715). Without Ghidra, Deep mode uses the built-in engines | Live runs with Ghidra 12.1.4 on Windows (a shared analysis, and a decompile in seconds on a large program). Live runs with Ghidra 12.2 on Linux x86-64 (decompiles by name in position-independent programs and shared libraries, whose addresses Ghidra moves). The guided install of Ghidra and its Java is offered on Linux and macOS too. On Linux it was tried on 2026-11-16 (`main` at `8dec7849`, through `engines_install`, which the app's Settings → Engines also calls): on a clean Debian 13 container and on a Debian 13 desktop (x86-64), it downloaded Ghidra 12.1.4 and Temurin 21 in 43–64 s (1.2 GB in the engine store), `engines_list` then found it, and a Deep-mode `native_function_pseudocode` came from Ghidra (`engine: ghidra`) in about 10 s. Ghidra laid out as Arch-based packages install it (in `/opt/ghidra`, with a `/usr/bin/ghidra` start script; recreated from the official release, as Arch's own repositories have no package) is found with no setting and with the Ghidra folder set to `/usr/bin` (#85). Not tried: macOS, the app's buttons themselves, and a distribution's own Ghidra package. Clean room and Deep mode: engine, AI, MCP, CLI and app tests; no live Clean room build run yet | +| Clean room and Deep mode | Clean room (the default) runs only the tools in `engine/src/clean_room.rs`: ones that touch no target or watch from outside (the website as a visitor sees it, pictures of a window, its controls, recorded runs, a phone's screen). Every other tool, a plugin's included, is refused in the app, CLI, MCP and agents, with a way to turn on Deep mode. A Clean room build studies an app or a game only from the person's pictures and words (and a picture of its window when runtime study is on); its builder's reads and commands go through an approval rule that keeps it out of the original's folder and site (with Claude Code, and with ACP agents for what they ask about; other agents aren't held to it, see roadmap R2.2). A builder over SSH starts the remote host's own `craft-anything-cli mcp` with this run's `--deep` or `--clean-room`, so the remote settings don't decide the mode; every release since 0.1.0 knows those flags and `--all-tools`, the only ones it is given (a test on `mcp_for` keeps it so; Codex's adapter adds only `--all-tools`). Claude Code, Codex and OpenCode builds over SSH first check that the host has `craft-anything-cli`. No release up to 0.5.0 reads `CRAFT_ANYTHING_AGENT`, so there a CLI the remote builder starts calls tools as the person (R2.8). Deep mode (`deep_mode` in Settings, `--deep` for one CLI run) uses every tool: the builder sees them all, and a website's study also reads its JavaScript and watches its start page for ten seconds (capture/how-it-works.md). Ghidra adds its decompiler in Deep mode when it's installed: it is found, or installed after asking. Study starts one analysis of the main program, saved and shared with the builder's tool server through a lock file (up to 8 h, Java gets half the machine's memory or the amount set in Settings → Engines, 4 to 31 GB, four slow passes skipped). The builder must decompile before the build is checked; addresses the built-in analysis can't place go to Ghidra, which makes a function on demand (for this run only) where its analysis has none, e.g. code reached only through tables of pointers. Before a decompile, a jump on a byte through a table with no bounds check (Rust's async state machines) is cut to the table's real entries, so it doesn't run away (#1715). Without Ghidra, Deep mode uses the built-in engines | Live runs with Ghidra 12.1.4 on Windows (a shared analysis, and a decompile in seconds on a large program). Live runs with Ghidra 12.2 on Linux x86-64 (decompiles by name in position-independent programs and shared libraries, whose addresses Ghidra moves). The guided install of Ghidra and its Java is offered on Linux and macOS too. On Linux it was tried on 2026-11-16 (`main` at `8dec7849`, through `engines_install`, which the app's Settings → Engines also calls): on a clean Debian 13 container and on a Debian 13 desktop (x86-64), it downloaded Ghidra 12.1.4 and Temurin 21 in 43–64 s (1.2 GB in the engine store), `engines_list` then found it, and a Deep-mode `native_function_pseudocode` came from Ghidra (`engine: ghidra`) in about 10 s. Ghidra laid out as Arch-based packages install it (in `/opt/ghidra`, with a `/usr/bin/ghidra` start script; recreated from the official release, as Arch's own repositories have no package) is found with no setting and with the Ghidra folder set to `/usr/bin` (#85). With the Ghidra folder set to a file, the file is run only if it is the headless launcher or a script that runs it; the `/usr/bin/ghidra` start script and a linked `ghidraRun` are followed to their Ghidra folder (tried live on Debian 13 with that layout: decompiles came from Ghidra), and any other file isn't listed as Ghidra. Not tried: macOS, the app's buttons themselves, and a distribution's own Ghidra package. Clean room and Deep mode: engine, AI, MCP, CLI and app tests; no live Clean room build run yet | | Auto mode | Settings → Safety, on by default. Builder actions go ahead without asking, except a fixed set that is never done unasked (deleting outside the project, system changes, publishing…); questions get "decide yourself"; asset spending stops at the budget. Each project can choose allow, ask or refuse per kind of action instead (`project_approvals_set`, the Approvals menu under the prompt box, or `/approvals publish ask`; read-only `gh … view`/`list` count as commands, not publishing) | Unit tests, UI tests; not tried in a live build | | Generated assets | Off until the person turns them on for a game (the switch on Make and on the project, `project_assets_allow`, `rebuild --generate-assets`, saved in craft.json; turning it on without a fal.ai key asks for one); the brief and the asset tools need both that and a key. `assets_image_generate` (Nano Banana Pro by default) and `assets_model_generate` (picture → Tripo P1 low-poly GLB with a face limit) through the person's key for each asset provider (fal.ai today), with agent apps and API-key builds alike; per-project budget, $5 by default (`[assets] budget_usd` in config.toml); models and prices from the `assets.toml` table (picture model selectable: Nano Banana Pro, FLUX dev or schnell; priced per picture or per megapixel); every call reports its cost | Unit tests; a live 3D generation with a real key (picture, then model) with FLUX dev; Nano Banana Pro not yet run with a real key; an API-key build not yet run with one | | Claude Code builder | Runs the person's own `claude` in headless mode (no `--model` by default, so the model its own settings name applies, custom ones included; a built-in Claude model can be picked instead; high effort unless configured) with our MCP server, a permission-prompt tool and `core_person_ask`; preflights for our CLI (a build stops plainly if it's missing or won't start) and sign-in | Argument and stream-parser tests; live preflight; live builder turns; see [claude-code.md](claude-code.md) |