Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Stop Ghidra when the app closes, and skip the analysis of an Electron program's runtime (#1007)

BFlat4390e97e6078
diff --git a/crates/ai/src/rebuild/study.rs b/crates/ai/src/rebuild/study.rs
index f5d73393..7a483f74 100644
--- a/crates/ai/src/rebuild/study.rs
+++ b/crates/ai/src/rebuild/study.rs
@@ -3,6 +3,12 @@
use super::*;
+/// An Electron program is the Chromium and Node runtime, and analysing that takes hours: the app's
+/// own logic is the JavaScript in `resources/app.asar` beside it, which the study maps (#947).
+pub(super) fn is_electron_runtime(program: &Path) -> bool {
+ program.parent().is_some_and(|dir| dir.join("resources/app.asar").is_file())
+}
+
impl Worker {
pub(super) fn study(&mut self, ws: &mut Workspace, kind: &dyn TargetKind) -> Result<(), ToolError> {
match ws.manifest.target.clone() {
@@ -238,7 +244,7 @@ impl Worker {
/// rather than starting another), and it carries on if the person pauses, so nothing is lost.
pub(super) fn prepare_ghidra(&self, program: &Path) -> Option<Receiver<Result<(), String>>> {
// A folder (nothing in it recognised as the program) isn't something Ghidra can open.
- if !program.is_file() {
+ if !program.is_file() || is_electron_runtime(program) {
return None;
}
let settings = {
diff --git a/crates/ai/src/rebuild/tests.rs b/crates/ai/src/rebuild/tests.rs
index f1451d54..705eb223 100644
--- a/crates/ai/src/rebuild/tests.rs
+++ b/crates/ai/src/rebuild/tests.rs
@@ -1304,6 +1304,17 @@ fn clean_room_studies_nothing_inside_and_deep_mode_looks() {
}
}
+#[test]
+fn an_electron_programs_runtime_is_not_analysed() {
+ let d = tempfile::tempdir().unwrap();
+ std::fs::create_dir_all(d.path().join("resources")).unwrap();
+ let program = d.path().join("App.exe");
+ std::fs::write(&program, b"MZ").unwrap();
+ assert!(!super::study::is_electron_runtime(&program), "a program with no asar beside it is analysed");
+ std::fs::write(d.path().join("resources/app.asar"), b"asar").unwrap();
+ assert!(super::study::is_electron_runtime(&program));
+}
+
#[test]
fn deep_mode_maps_the_javascript_beside_an_exe_target() {
let d = tempfile::tempdir().unwrap();
diff --git a/crates/engine/src/tools/deep.rs b/crates/engine/src/tools/deep.rs
index cbe76706..ed9578dc 100644
--- a/crates/engine/src/tools/deep.rs
+++ b/crates/engine/src/tools/deep.rs
@@ -16,6 +16,7 @@ use craft_anything_engines::ghidra::{self, DeepDecompiler, DeepFunction};
use craft_anything_evidence::{Confidence, Environment, EvidenceBuilder, Limitation, Location, ToolError, host_triple};
use std::collections::HashMap;
use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;
/// The analysis settings hash for the default Deep profile. Part of the project cache key, so a
@@ -110,8 +111,29 @@ fn config(settings: &Settings, language_override: Option<String>) -> Option<(ghi
/// doing the same. `progress` gets a line now and then.
pub fn prepare(settings: &Settings, bytes: &[u8], sha256: &str, progress: &(dyn Fn(&str) + Send + Sync)) -> Result<(), String> {
let (cfg, digest) = config(settings, None).ok_or_else(|| NOT_INSTALLED.to_string())?;
- let never = || false;
- ghidra::analyse(&cfg, bytes, sha256, &digest, &never, &|_, m: &str| progress(m)).map(|_| ()).map_err(|e| e.to_string())
+ ANALYSING.fetch_add(1, Ordering::SeqCst);
+ let closing = || CLOSING.load(Ordering::SeqCst);
+ let result = ghidra::analyse(&cfg, bytes, sha256, &digest, &closing, &|_, m: &str| progress(m)).map(|_| ()).map_err(|e| e.to_string());
+ ANALYSING.fetch_sub(1, Ordering::SeqCst);
+ result
+}
+
+/// Analyses [`prepare`] has under way, and whether they are being stopped.
+static ANALYSING: AtomicUsize = AtomicUsize::new(0);
+static CLOSING: AtomicBool = AtomicBool::new(false);
+
+/// The app is closing: stop every analysis [`prepare`] started and wait up to `within` for them to
+/// end, as nothing acts on a process's drop once the app has gone (#946).
+pub fn stop_analyses(within: Duration) {
+ if ANALYSING.load(Ordering::SeqCst) == 0 {
+ return;
+ }
+ CLOSING.store(true, Ordering::SeqCst);
+ let until = std::time::Instant::now() + within;
+ while ANALYSING.load(Ordering::SeqCst) > 0 && std::time::Instant::now() < until {
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ CLOSING.store(false, Ordering::SeqCst);
}
fn remember(ctx: &mut Ctx<'_>, provider: Result<Arc<dyn DeepDecompiler>, String>) -> Result<Arc<dyn DeepDecompiler>, Option<String>> {
diff --git a/crates/engine/tests/deep_stop.rs b/crates/engine/tests/deep_stop.rs
new file mode 100644
index 00000000..036dfd7c
--- /dev/null
+++ b/crates/engine/tests/deep_stop.rs
@@ -0,0 +1,36 @@
+//! A test program of its own: stopping analyses is process-wide.
+
+use craft_anything_engine::tools::deep;
+use craft_anything_engines::ghidra;
+use std::time::{Duration, Instant};
+
+/// #946: closing the app ends an analysis, here one waiting for another's lock, within moments.
+#[test]
+fn closing_stops_an_analysis() {
+ let d = tempfile::Builder::new().prefix("ca").tempdir().unwrap();
+ let launcher = d.path().join("analyzeHeadless");
+ std::fs::write(&launcher, "").unwrap();
+ let store = d.path().join("store");
+ let mut settings = craft_anything_engine::testing::session().settings.clone();
+ settings.engines.store_dir = Some(store.clone());
+ settings.engines.ghidra.install_dir = Some(launcher);
+ settings.engines.ghidra.startup_timeout_secs = Some(120);
+ let bytes = b"not really a program";
+ let sha = craft_anything_evidence::sha256_hex(bytes);
+ let digest = craft_anything_evidence::sha256_hex(b"craft-anything-ghidra-fast-profile-v2|lang=");
+ let project = ghidra::project_cache_dir(&store, &sha, &digest);
+ std::fs::create_dir_all(project.parent().unwrap()).unwrap();
+ std::fs::write(project.with_extension("analysing"), "").unwrap();
+
+ let waiting = {
+ let sha = sha.clone();
+ std::thread::spawn(move || deep::prepare(&settings, bytes, &sha, &|_| {}))
+ };
+ let until = Instant::now() + Duration::from_secs(30);
+ while !waiting.is_finished() {
+ assert!(Instant::now() < until, "the analysis kept going");
+ deep::stop_analyses(Duration::from_secs(5));
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ assert!(waiting.join().unwrap().is_err(), "it stopped, it didn't finish");
+}
diff --git a/crates/engines/src/ghidra/mod.rs b/crates/engines/src/ghidra/mod.rs
index fa09463a..efa2eb38 100644
--- a/crates/engines/src/ghidra/mod.rs
+++ b/crates/engines/src/ghidra/mod.rs
@@ -573,6 +573,8 @@ pub fn analyse(
let mut last_progress = Instant::now();
let done = loop {
if cancel() {
+ // Confirmed here: the caller may be the app closing, and a drop only raises a flag (#946).
+ running.kill_and_wait(Duration::from_secs(10));
return Err(GhidraError::Cancelled);
}
if let Some(r) = running.wait_timeout(Duration::from_millis(500)) {
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 6df4028e..ae975445 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -2011,6 +2011,7 @@ impl eframe::App for CraftApp {
for j in self.jobs.running() {
j.cancel.cancel();
}
+ craft_anything_engine::tools::deep::stop_analyses(std::time::Duration::from_secs(12));
// A change not written yet (or one being written as the window closed) is written now.
if self.persist && (self.settings_dirty || self.save_due.is_some() || self.saving.is_some()) {
let saved = if let Some(mut session) = self.engine.try_session() {
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 550b237e..0846a0b3 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -49,6 +49,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| SQLite payload limits | Capped records retain column positions, disclose partial TEXT and BLOB values, omit incomplete BLOB hashes, and report partial coverage with read notes | Hand-built overflow-page regressions for five oversized records (including WITHOUT ROWID in declaration order) and two controls; table and index engine coverage and limitation regressions |
| SQLite added columns | Short records include missing trailing fields using literal column defaults, or NULL when absent; unsupported default expressions produce NULL with a row note. Stored fields and records longer than the schema retain their values. Defaults are filled before restoring rowid aliases | Nine hand-built parser regressions and an engine tool test cover added-column defaults, rewritten records and short records with a rowid alias, including a missing alias field |
| OpenCode models and thinking | OpenCode V2 locally and over SSH; Settings → AI lists only that instance's enabled chat models and supported Low/Medium/High/Xhigh/Max variants. Selection is validated and saved through UI, CLI and `ai_models_list` / `ai_model_set`. Explicit selections run natively with the Craft Anything MCP server (local runs; none over SSH yet). See [OpenCode](opencode.md). | Stand-in catalogue/process, persistence, remote-command and UI tests; local live catalogue checks (34 models, all five depths represented). Regression checks route explicit selections natively and parse V2 tool events. Live (2026-11-04, Windows, OpenCode 2.2.5, opencode-go/deepseek-v4.1-flash): a `--standalone` run connected the server (38 tools) and called `core_session_show`. No live SSH host or paid generation used |
+| Ghidra and closing the app | Closing the app stops an analysis a build started, and waits for it to end, so `java.exe` isn't left running (#946). An app that crashes or is killed can still leave one (#951). Deep mode doesn't analyse an Electron program's runtime, whose logic is in `app.asar` (#947) | Stopping tested with a waiting analysis; not run against a live Ghidra |
| Gemini tool calls | A tool call's `extra_content` (Gemini's thought signature) goes back with it unchanged, so Gemini 3 builders get past their first tool call; errors Gemini wraps in an array show their message (#978) | Unit-tested; not run against the live API |
| OpenCode models and thinking | OpenCode V2 locally and over SSH; Settings → AI lists only that instance's enabled chat models and supported Low/Medium/High/Xhigh/Max variants. Selection is validated and saved through UI, CLI and `ai_models_list` / `ai_model_set`. Explicit selections run natively with the Craft Anything MCP server (local runs, and over SSH: one `ssh` run checks `craft-anything-cli` on the host's PATH and writes the config on the host, `~/.cache/craft-anything/`, mode 600). See [OpenCode](opencode.md). | Stand-in catalogue/process, persistence, remote-command and UI tests; local live catalogue checks (34 models, all five depths represented). Regression checks route explicit selections natively and parse V2 tool events. Live (2026-11-04, Windows, OpenCode 2.2.5, opencode-go/deepseek-v4.1-flash): a `--standalone` run connected the server (38 tools) and called `core_session_show`. The SSH path is covered by a POSIX-shell regression test (probe fails fast without the helper; config written byte-exact, mode 600, atomic rename) and was exercised against a localhost SSH host; it has not been run with a live agent over SSH. No paid generation used |
| Claude desktop app without Claude Code | When the `claude` command isn't found but the Claude desktop app is (Windows: the Store package's `claude-desktop` app alias or the older installer's `AnthropicClaude` folder; macOS: `Claude.app`), the builder dialog under "No coding agent was found" and `ai detect` (on stderr) say the desktop app is installed but building needs Claude Code, installed apart (#259). Typed as `DetectHint` from `AiHub::detect_hints` | A regression finds the app in temp folders laid out as each Windows installer leaves it, and nothing on Linux; a UI test shows the hint in the dialog. On Windows 10 the real Store package's alias was found. Not checked: macOS, the older installer, and a computer with no `claude` installed |