diff --git a/Cargo.lock b/Cargo.lock index 468797a..2b2bec4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6,6 +6,7 @@ version = 4 name = "betterxen" version = "0.1.0" dependencies = [ + "betterxen-hybrid", "xenora-decoder", "xenora-import-gen", "xenora-isa", @@ -18,6 +19,9 @@ dependencies = [ [[package]] name = "betterxen-hybrid" version = "0.1.0" +dependencies = [ + "libc", +] [[package]] name = "bitflags" diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 005dc73..8c50cac 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -9,6 +9,7 @@ rust-version.workspace = true workspace = true [dependencies] +betterxen-hybrid = { path = "../hybrid" } xenora-decoder = { path = "../decoder" } xenora-isa = { path = "../isa" } xenora-metal = { path = "../metal" } diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 5262052..277fb09 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -43,6 +43,10 @@ fn main() -> ExitCode { } }, Some("run") => runner::command(std::env::args_os().skip(2)), + // Windows programs through an installed CrossOver: the active hybrid path. + Some("hybrid") => { + betterxen_hybrid::cli::run_cli(&std::env::args().skip(2).collect::>()) + } Some("imports") => imports_command(std::env::args().skip(2).collect()), Some("shaders") => shaders::command(&std::env::args().skip(2).collect::>()), Some("probe") => { @@ -137,7 +141,7 @@ fn main() -> ExitCode { } } _ => { - eprintln!("usage: betterxen "); + eprintln!("usage: betterxen "); ExitCode::from(2) } } diff --git a/crates/hybrid/Cargo.toml b/crates/hybrid/Cargo.toml index cc77d4c..1d0ae65 100644 --- a/crates/hybrid/Cargo.toml +++ b/crates/hybrid/Cargo.toml @@ -12,3 +12,7 @@ workspace = true [[bin]] name = "betterxen-hybrid" path = "src/main.rs" + +[dependencies] +# signal handling and process groups; already used by the native loader +libc = "0.2" diff --git a/crates/hybrid/src/cli.rs b/crates/hybrid/src/cli.rs new file mode 100644 index 0000000..971d8af --- /dev/null +++ b/crates/hybrid/src/cli.rs @@ -0,0 +1,569 @@ +//! Command-line interface of the hybrid tooling. + +use crate::{crossover, frames, host, json::Json, memory, pe, preflight, run, toolchain}; +use std::path::PathBuf; +use std::process::ExitCode; +use std::sync::atomic::{AtomicBool, Ordering}; + +const USAGE: &str = "usage: betterxen hybrid + host host receipt (JSON) + crossover [--app P] CrossOver installs and documented preferences (JSON) + toolchain Windows cross-compilers found on PATH (JSON) + frames frame-time statistics; file has one interval in ms per line (JSON) + guard [--min-start-free N] [--min-free N] -- CMD ARGS... + run CMD; refuse to start / stop it when free memory is low + doctor [--bottle B] [--min-start-free N] + check that a run could start here (JSON); non-zero exit if not + inspect identify a Windows executable: machine, subsystem, imports (JSON) + run --bottle B [--backend d3dmetal|dxmt|dxvk|wined3d] [--timeout S] [--stall-timeout S] + [--settle-bound S] [--expect TEXT] [--require-gates a,b,c] [--out DIR] + [--min-start-free N] [--min-free N] -- EXE [ARGS...] + run a Windows program through CrossOver; write a JSON record + bench --bottle B --backends a,b,c [--repeat N] [same options] -- EXE [ARGS...] + run the program per backend N times; summarise frame times + stop --bottle B stop every Windows process in a bottle (recovery) + receipt host + crossover + toolchain in one JSON document + +run and bench also accept: --env NAME=VALUE (repeatable), --inherit-env true, --keep-output true. +The child otherwise receives only a short allowlist of host variables. A bottle is not a sandbox."; + +/// Set by the signal handler; every run polls it. +static INTERRUPTED: AtomicBool = AtomicBool::new(false); + +extern "C" fn on_signal(_: libc::c_int) { + // Storing to an atomic is async-signal-safe. + INTERRUPTED.store(true, Ordering::SeqCst); +} + +fn install_signal_handlers() { + let handler = on_signal as extern "C" fn(libc::c_int) as libc::sighandler_t; + for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] { + // SAFETY: `on_signal` has the required signature and only touches an atomic. + unsafe { libc::signal(signal, handler) }; + } +} + +fn crossover_json(app: Option) -> Json { + let home = PathBuf::from(std::env::var("HOME").unwrap_or_default()); + let cands = match app { + Some(p) => vec![p], + None => crossover::candidate_paths(&home), + }; + let installs = crossover::discover(&cands); + Json::obj(vec![ + ("installed", Json::Bool(!installs.is_empty())), + ( + "installs", + Json::Arr(installs.iter().map(|i| i.to_json()).collect()), + ), + ( + "bottle_dir_preference", + Json::opt_str(crossover::preference("BottleDir")), + ), + ( + "managed_bottle_dirs_preference", + Json::opt_str(crossover::preference("ManagedBottleDirs")), + ), + ( + "searched", + Json::Arr( + cands + .iter() + .map(|p| Json::str(p.display().to_string())) + .collect(), + ), + ), + ( + "note", + Json::str( + "Only Info.plist metadata, lipo -archs and documented defaults keys are read. Bottle graphics backend and bundle internals are not interpreted (undocumented, #350).", + ), + ), + ]) +} + +fn toolchain_json() -> Json { + let path = std::env::var("PATH").unwrap_or_default(); + Json::Arr( + toolchain::probe(&path) + .iter() + .map(|c| c.to_json()) + .collect(), + ) +} + +fn guard(args: &[String]) -> ExitCode { + let mut limits = memory::Limits { + min_start_free: 70, + min_free: 20, + poll: std::time::Duration::from_secs(1), + grace: std::time::Duration::from_secs(10), + }; + let mut i = 0; + while i < args.len() && args[i] != "--" { + let v = args.get(i + 1).and_then(|v| v.parse::().ok()); + match (args[i].as_str(), v) { + ("--min-start-free", Some(v)) => limits.min_start_free = v, + ("--min-free", Some(v)) => limits.min_free = v, + _ => { + eprintln!("{USAGE}"); + return ExitCode::from(2); + } + } + i += 2; + } + let Some(cmd) = args.get(i + 1) else { + eprintln!("{USAGE}"); + return ExitCode::from(2); + }; + match memory::supervise(cmd, &args[i + 2..], limits, &mut memory::free_percentage) { + memory::Outcome::Exited(Some(0)) => ExitCode::SUCCESS, + memory::Outcome::Exited(c) => ExitCode::from(c.map_or(1, |c| c.clamp(1, 255)) as u8), + other => { + eprintln!("guard: {other:?}"); + ExitCode::from(3) + } + } +} + +struct RunArgs { + cfg: run::RunConfig, + backends: Vec, + repeat: u32, + out: Option, + /// What the program file is, recorded with every run. + executable: Json, +} + +fn parse_run_args(args: &[String]) -> Result { + let mut bottle = None; + let mut backend = None; + let mut backends = Vec::new(); + let mut repeat = 1u32; + let mut timeout = 300u64; + let mut stall = None; + let mut settle = 60u64; + let mut expect = None; + let mut require_gates = Vec::new(); + let mut out = None; + let (mut min_start, mut min_free) = (50u8, 15u8); + let (mut inherit_env, mut keep_output) = (false, false); + let mut env = Vec::new(); + let mut i = 0; + while i < args.len() && args[i] != "--" { + let v = args + .get(i + 1) + .ok_or_else(|| format!("{} needs a value", args[i]))? + .clone(); + match args[i].as_str() { + "--bottle" => bottle = Some(v), + "--backend" => backend = Some(v), + "--backends" => backends = v.split(',').map(String::from).collect(), + "--repeat" => repeat = v.parse().map_err(|_| "bad --repeat")?, + "--timeout" => timeout = v.parse().map_err(|_| "bad --timeout")?, + "--stall-timeout" => stall = Some(v.parse().map_err(|_| "bad --stall-timeout")?), + "--settle-bound" => settle = v.parse().map_err(|_| "bad --settle-bound")?, + "--expect" => expect = Some(v), + "--env" => { + let (name, value) = v.split_once('=').ok_or("--env needs NAME=VALUE")?; + if name.is_empty() || name.contains('\0') { + return Err("--env needs NAME=VALUE".into()); + } + if name.starts_with("CX_GRAPHICS_BACKEND") { + return Err("select the backend with --backend, not --env".into()); + } + if name.starts_with("DYLD_") { + return Err("DYLD_ variables are not passed to the launcher".into()); + } + env.push((name.to_string(), value.to_string())); + } + "--inherit-env" => inherit_env = v.parse().map_err(|_| "bad --inherit-env")?, + "--keep-output" => keep_output = v.parse().map_err(|_| "bad --keep-output")?, + "--require-gates" => require_gates = v.split(',').map(String::from).collect(), + "--out" => out = Some(PathBuf::from(v)), + "--min-start-free" => min_start = v.parse().map_err(|_| "bad --min-start-free")?, + "--min-free" => min_free = v.parse().map_err(|_| "bad --min-free")?, + o => return Err(format!("unknown option {o}")), + } + i += 2; + } + let program = args.get(i + 1).ok_or("missing program after --")?.clone(); + let bottle: String = bottle.ok_or("--bottle is required")?; + if !preflight::valid_bottle_name(&bottle) { + return Err(format!("invalid bottle name {bottle:?}")); + } + if let Some(unknown) = backend + .iter() + .chain(backends.iter().filter(|b| *b != "default")) + .find(|b| !run::BACKENDS.contains(&b.as_str())) + { + return Err(format!( + "unknown backend {unknown:?} (CrossOver would ignore it silently); use one of {}", + run::BACKENDS.join(", ") + )); + } + if program.starts_with('-') { + return Err("the program path must not start with '-' (write ./name.exe)".into()); + } + let executable = identify(std::path::Path::new(&program))?; + let home = PathBuf::from(std::env::var("HOME").unwrap_or_default()); + let installs = crossover::discover(&crossover::candidate_paths(&home)); + let install = installs.first().ok_or("no CrossOver installation found")?; + let wine = run::wine_path(&install.path); + if !wine.is_file() { + return Err(format!( + "{} not found in this CrossOver build", + wine.display() + )); + } + if !run::bottle_prefix(&bottle).join("drive_c").is_dir() { + return Err(format!( + "bottle {bottle:?} not found at {}", + run::bottle_prefix(&bottle).display() + )); + } + let work = out + .clone() + .unwrap_or_else(|| PathBuf::from("artifacts/hybrid-runs")); + Ok(RunArgs { + cfg: run::RunConfig { + wine, + bottle, + backend, + program, + args: args[i + 2..].to_vec(), + timeout: std::time::Duration::from_secs(timeout), + limits: memory::Limits { + min_start_free: min_start, + min_free, + poll: std::time::Duration::from_millis(250), + grace: std::time::Duration::from_secs(10), + }, + expect, + work_dir: work, + stall_timeout: stall.map(std::time::Duration::from_secs), + settle_bound: std::time::Duration::from_secs(settle), + read_free: memory::free_percentage, + require_gates, + max_output: 64 << 20, + inherit_env, + env, + keep_output, + interrupted: &INTERRUPTED, + }, + backends, + repeat, + out, + executable, + }) +} + +/// Refuse anything that is not a launchable Windows program, and describe what is. +fn identify(path: &std::path::Path) -> Result { + let image = pe::inspect(path)?; + image + .check_launchable() + .map_err(|e| format!("{}: {e}", path.display()))?; + let sha256 = crate::cmdutil::run( + "/usr/bin/shasum", + &["-a", "256", &path.display().to_string()], + ) + .and_then(|o| o.split_whitespace().next().map(String::from)); + Ok(Json::obj(vec![ + ("path", Json::str(path.display().to_string())), + ("sha256", Json::opt_str(sha256)), + ("image", image.to_json()), + ])) +} + +fn with_executable(mut record: Json, executable: &Json) -> Json { + if let Json::Obj(fields) = &mut record { + fields.push(("executable".into(), executable.clone())); + } + record +} + +fn doctor(args: &[String]) -> ExitCode { + let (mut bottle, mut min_start) = (None, 50u8); + let mut it = args.iter(); + while let Some(a) = it.next() { + match (a.as_str(), it.next()) { + ("--bottle", Some(v)) => bottle = Some(v.clone()), + ("--min-start-free", Some(v)) if v.parse::().is_ok() => { + min_start = v.parse().unwrap_or(min_start) + } + _ => { + eprintln!("{USAGE}"); + return ExitCode::from(2); + } + } + } + let home = PathBuf::from(std::env::var("HOME").unwrap_or_default()); + let install = crossover::discover(&crossover::candidate_paths(&home)) + .into_iter() + .next(); + let wine = install.as_ref().map(|i| run::wine_path(&i.path)); + let facts = preflight::gather( + bottle.as_deref(), + wine.as_deref() + .map(|w| (crossover_build().unwrap_or_else(|| "unknown".into()), w)), + min_start, + ); + let checks = preflight::evaluate(&facts); + print!("{}", preflight::to_json(&checks).render()); + if checks.iter().all(|c| c.ok) { + ExitCode::SUCCESS + } else { + ExitCode::from(1) + } +} + +fn crossover_build() -> Option { + let home = PathBuf::from(std::env::var("HOME").unwrap_or_default()); + crossover::discover(&crossover::candidate_paths(&home)) + .first() + .and_then(|i| { + Some(format!( + "{} ({})", + i.short_version.clone()?, + i.build_version.clone()? + )) + }) +} + +fn save(dir: &std::path::Path, kind: &str, j: &Json) -> Result<(), String> { + crate::records::save(dir, kind, j) + .map(|path| eprintln!("report saved: {}", path.display())) + .map_err(|error| format!("cannot save {kind} report in {}: {error}", dir.display())) +} + +fn finish_report(passed: bool, out: Option<&std::path::Path>, kind: &str, j: &Json) -> ExitCode { + print!("{}", j.render()); + if let Some(dir) = out + && let Err(error) = save(dir, kind, j) + { + eprintln!("{error}"); + return ExitCode::from(1); + } + if passed { + ExitCode::SUCCESS + } else { + ExitCode::from(1) + } +} + +fn run_cmd(args: &[String]) -> ExitCode { + let a = match parse_run_args(args) { + Ok(a) => a, + Err(e) => { + eprintln!("{e}\n{USAGE}"); + return ExitCode::from(2); + } + }; + let r = run::execute(&a.cfg, crossover_build()); + if r.class != run::Class::Passed { + eprintln!("run: {}", r.class.name()); + for g in r.gates.iter().filter(|g| !g.passed) { + eprintln!(" gate {} failed: {}", g.name, g.detail); + } + if let Some(e) = &r.error { + eprintln!(" {e}"); + } + } + finish_report( + r.class == run::Class::Passed, + a.out.as_deref(), + "run", + &with_executable(r.json, &a.executable), + ) +} + +fn bench_cmd(args: &[String]) -> ExitCode { + let a = match parse_run_args(args) { + Ok(a) if !a.backends.is_empty() => a, + Ok(_) => { + eprintln!("bench needs --backends\n{USAGE}"); + return ExitCode::from(2); + } + Err(e) => { + eprintln!("{e}\n{USAGE}"); + return ExitCode::from(2); + } + }; + let build = crossover_build(); + let mut per_backend = Vec::new(); + let mut all_ok = true; + for b in &a.backends { + let mut runs = Vec::new(); + for _ in 0..a.repeat { + if INTERRUPTED.load(Ordering::SeqCst) { + all_ok = false; + break; + } + let mut cfg = a.cfg.clone(); + cfg.backend = if b == "default" { + None + } else { + Some(b.clone()) + }; + let r = run::execute(&cfg, build.clone()); + all_ok &= r.class == run::Class::Passed; + runs.push(with_executable(r.json, &a.executable)); + } + per_backend.push(Json::obj(vec![ + ("backend", Json::str(b.clone())), + ("runs", Json::Arr(runs)), + ])); + } + let doc = Json::obj(vec![ + ("schema", Json::str("betterxen-hybrid-bench/0")), + ("repeat", Json::Num(a.repeat as f64)), + ("host", host::collect().to_json()), + ("results", Json::Arr(per_backend)), + ]); + finish_report(all_ok, a.out.as_deref(), "bench", &doc) +} + +fn stop(args: &[String]) -> ExitCode { + let [flag, bottle] = args else { + eprintln!("{USAGE}"); + return ExitCode::from(2); + }; + if flag != "--bottle" || !preflight::valid_bottle_name(bottle) { + eprintln!("{USAGE}"); + return ExitCode::from(2); + } + let home = PathBuf::from(std::env::var("HOME").unwrap_or_default()); + let Some(install) = crossover::discover(&crossover::candidate_paths(&home)) + .into_iter() + .next() + else { + eprintln!("no CrossOver installation found"); + return ExitCode::from(1); + }; + if !run::bottle_prefix(bottle).join("drive_c").is_dir() { + eprintln!("bottle {bottle:?} not found"); + return ExitCode::from(1); + } + run::stop_bottle(&run::wine_path(&install.path), bottle); + ExitCode::SUCCESS +} + +/// Entry point shared by `betterxen hybrid` and the `betterxen-hybrid` binary. `args` excludes +/// the program name and the `hybrid` word. +pub fn run_cli(args: &[String]) -> ExitCode { + let rest = args.get(1..).unwrap_or_default(); + match args.first().map(String::as_str) { + Some("run") => { + install_signal_handlers(); + return run_cmd(rest); + } + Some("bench") => { + install_signal_handlers(); + return bench_cmd(rest); + } + Some("doctor") => return doctor(rest), + Some("guard") => return guard(rest), + Some("stop") => return stop(rest), + _ => {} + } + let result: Result = match args.first().map(String::as_str) { + Some("host") => Ok(host::collect().to_json()), + Some("inspect") => match args.get(1) { + None => Err("inspect needs a file".into()), + Some(f) => pe::inspect(std::path::Path::new(f)).map(|i| i.to_json()), + }, + Some("crossover") => { + let app = match args.get(1).map(String::as_str) { + Some("--app") => args.get(2).map(PathBuf::from), + _ => None, + }; + Ok(crossover_json(app)) + } + Some("toolchain") => Ok(toolchain_json()), + Some("frames") => match args.get(1) { + None => Err("frames needs a file".into()), + Some(f) => std::fs::read_to_string(f) + .map_err(|e| format!("{f}: {e}")) + .and_then(|t| frames::parse_intervals(&t).map_err(|e| e.to_string())) + .and_then(|v| frames::analyze(&v).map_err(|e| e.to_string())) + .map(|s| s.to_json()), + }, + Some("receipt") => Ok(Json::obj(vec![ + ("schema", Json::str("betterxen-hybrid-receipt/0")), + ("host", host::collect().to_json()), + ("crossover", crossover_json(None)), + ("windows_cross_compilers", toolchain_json()), + ])), + _ => Err(USAGE.into()), + }; + match result { + Ok(j) => { + print!("{}", j.render()); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("{e}"); + ExitCode::from(2) + } + } +} + +#[cfg(test)] +mod report_tests { + use super::*; + + fn args(a: &[&str]) -> Vec { + a.iter().map(|s| s.to_string()).collect() + } + + // These fail before CrossOver discovery, so they run on hosts without CrossOver. + #[test] + fn bad_backend_bottle_or_program_is_refused_before_launch() { + let err = |a: &[&str]| parse_run_args(&args(a)).err().unwrap(); + assert!( + err(&["--bottle", "b", "--backend", "dmxt", "--", "x.exe"]).contains("unknown backend") + ); + assert!( + err(&["--bottle", "b", "--backends", "default,typo", "--", "x.exe"]) + .contains("unknown backend") + ); + assert!(err(&["--bottle", "../b", "--", "x.exe"]).contains("invalid bottle")); + assert!(err(&["--bottle", "b", "--", "/nonexistent/x.exe"]).contains("/nonexistent/x.exe")); + assert!(err(&["--bottle", "b", "--", "/bin/sh"]).contains("not a PE")); + assert!(err(&["--bottle", "b", "--", "--help"]).contains("must not start with")); + } + + #[test] + fn requested_evidence_failure_overrides_a_passing_workload() { + let path = std::env::temp_dir().join(format!( + "bx-report-invalid-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::write(&path, "keep this file").unwrap(); + for kind in ["run", "bench"] { + assert_eq!( + finish_report(true, Some(&path), kind, &Json::Null), + ExitCode::from(1) + ); + } + assert_eq!(std::fs::read_to_string(&path).unwrap(), "keep this file"); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn stdout_only_reporting_preserves_workload_status() { + assert_eq!( + finish_report(true, None, "run", &Json::Null), + ExitCode::SUCCESS + ); + assert_eq!( + finish_report(false, None, "bench", &Json::Null), + ExitCode::from(1) + ); + } +} diff --git a/crates/hybrid/src/lib.rs b/crates/hybrid/src/lib.rs index b909914..1f590cf 100644 --- a/crates/hybrid/src/lib.rs +++ b/crates/hybrid/src/lib.rs @@ -2,6 +2,7 @@ //! launches and measurement around an externally installed CrossOver. Nothing here claims //! game or console compatibility. +pub mod cli; pub mod cmdutil; pub mod crossover; pub mod frames; diff --git a/crates/hybrid/src/main.rs b/crates/hybrid/src/main.rs index 4bbd39c..ff92492 100644 --- a/crates/hybrid/src/main.rs +++ b/crates/hybrid/src/main.rs @@ -1,491 +1,5 @@ -use betterxen_hybrid::{ - crossover, frames, host, json::Json, memory, pe, preflight, run, toolchain, -}; -use std::path::PathBuf; -use std::process::ExitCode; +//! Standalone binary for the hybrid tooling; `betterxen hybrid` runs the same code. -const USAGE: &str = "usage: betterxen-hybrid - host host receipt (JSON) - crossover [--app P] CrossOver installs and documented preferences (JSON) - toolchain Windows cross-compilers found on PATH (JSON) - frames frame-time statistics; file has one interval in ms per line (JSON) - guard [--min-start-free N] [--min-free N] -- CMD ARGS... - run CMD; refuse to start / stop it when free memory is low - doctor [--bottle B] [--min-start-free N] - check that a run could start here (JSON); non-zero exit if not - inspect identify a Windows executable: machine, subsystem, imports (JSON) - run --bottle B [--backend d3dmetal|dxmt|dxvk|wined3d] [--timeout S] [--stall-timeout S] - [--settle-bound S] [--expect TEXT] [--require-gates a,b,c] [--out DIR] - [--min-start-free N] [--min-free N] -- EXE [ARGS...] - run a Windows program through CrossOver; write a JSON record - bench --bottle B --backends a,b,c [--repeat N] [same options] -- EXE [ARGS...] - run the program per backend N times; summarise frame times - receipt host + crossover + toolchain in one JSON document"; - -fn crossover_json(app: Option) -> Json { - let home = PathBuf::from(std::env::var("HOME").unwrap_or_default()); - let cands = match app { - Some(p) => vec![p], - None => crossover::candidate_paths(&home), - }; - let installs = crossover::discover(&cands); - Json::obj(vec![ - ("installed", Json::Bool(!installs.is_empty())), - ( - "installs", - Json::Arr(installs.iter().map(|i| i.to_json()).collect()), - ), - ( - "bottle_dir_preference", - Json::opt_str(crossover::preference("BottleDir")), - ), - ( - "managed_bottle_dirs_preference", - Json::opt_str(crossover::preference("ManagedBottleDirs")), - ), - ( - "searched", - Json::Arr( - cands - .iter() - .map(|p| Json::str(p.display().to_string())) - .collect(), - ), - ), - ( - "note", - Json::str( - "Only Info.plist metadata, lipo -archs and documented defaults keys are read. Bottle graphics backend and bundle internals are not interpreted (undocumented, #350).", - ), - ), - ]) -} - -fn toolchain_json() -> Json { - let path = std::env::var("PATH").unwrap_or_default(); - Json::Arr( - toolchain::probe(&path) - .iter() - .map(|c| c.to_json()) - .collect(), - ) -} - -fn guard(args: &[String]) -> ExitCode { - let mut limits = memory::Limits { - min_start_free: 70, - min_free: 20, - poll: std::time::Duration::from_secs(1), - grace: std::time::Duration::from_secs(10), - }; - let mut i = 0; - while i < args.len() && args[i] != "--" { - let v = args.get(i + 1).and_then(|v| v.parse::().ok()); - match (args[i].as_str(), v) { - ("--min-start-free", Some(v)) => limits.min_start_free = v, - ("--min-free", Some(v)) => limits.min_free = v, - _ => { - eprintln!("{USAGE}"); - return ExitCode::from(2); - } - } - i += 2; - } - let Some(cmd) = args.get(i + 1) else { - eprintln!("{USAGE}"); - return ExitCode::from(2); - }; - match memory::supervise(cmd, &args[i + 2..], limits, &mut memory::free_percentage) { - memory::Outcome::Exited(Some(0)) => ExitCode::SUCCESS, - memory::Outcome::Exited(c) => ExitCode::from(c.map_or(1, |c| c.clamp(1, 255)) as u8), - other => { - eprintln!("guard: {other:?}"); - ExitCode::from(3) - } - } -} - -struct RunArgs { - cfg: run::RunConfig, - backends: Vec, - repeat: u32, - out: Option, - /// What the program file is, recorded with every run. - executable: Json, -} - -fn parse_run_args(args: &[String]) -> Result { - let mut bottle = None; - let mut backend = None; - let mut backends = Vec::new(); - let mut repeat = 1u32; - let mut timeout = 300u64; - let mut stall = None; - let mut settle = 60u64; - let mut expect = None; - let mut require_gates = Vec::new(); - let mut out = None; - let (mut min_start, mut min_free) = (50u8, 15u8); - let mut i = 0; - while i < args.len() && args[i] != "--" { - let v = args - .get(i + 1) - .ok_or_else(|| format!("{} needs a value", args[i]))? - .clone(); - match args[i].as_str() { - "--bottle" => bottle = Some(v), - "--backend" => backend = Some(v), - "--backends" => backends = v.split(',').map(String::from).collect(), - "--repeat" => repeat = v.parse().map_err(|_| "bad --repeat")?, - "--timeout" => timeout = v.parse().map_err(|_| "bad --timeout")?, - "--stall-timeout" => stall = Some(v.parse().map_err(|_| "bad --stall-timeout")?), - "--settle-bound" => settle = v.parse().map_err(|_| "bad --settle-bound")?, - "--expect" => expect = Some(v), - "--require-gates" => require_gates = v.split(',').map(String::from).collect(), - "--out" => out = Some(PathBuf::from(v)), - "--min-start-free" => min_start = v.parse().map_err(|_| "bad --min-start-free")?, - "--min-free" => min_free = v.parse().map_err(|_| "bad --min-free")?, - o => return Err(format!("unknown option {o}")), - } - i += 2; - } - let program = args.get(i + 1).ok_or("missing program after --")?.clone(); - let bottle: String = bottle.ok_or("--bottle is required")?; - if !preflight::valid_bottle_name(&bottle) { - return Err(format!("invalid bottle name {bottle:?}")); - } - if let Some(unknown) = backend - .iter() - .chain(backends.iter().filter(|b| *b != "default")) - .find(|b| !run::BACKENDS.contains(&b.as_str())) - { - return Err(format!( - "unknown backend {unknown:?} (CrossOver would ignore it silently); use one of {}", - run::BACKENDS.join(", ") - )); - } - if program.starts_with('-') { - return Err("the program path must not start with '-' (write ./name.exe)".into()); - } - let executable = identify(std::path::Path::new(&program))?; - let home = PathBuf::from(std::env::var("HOME").unwrap_or_default()); - let installs = crossover::discover(&crossover::candidate_paths(&home)); - let install = installs.first().ok_or("no CrossOver installation found")?; - let wine = run::wine_path(&install.path); - if !wine.is_file() { - return Err(format!( - "{} not found in this CrossOver build", - wine.display() - )); - } - if !run::bottle_prefix(&bottle).join("drive_c").is_dir() { - return Err(format!( - "bottle {bottle:?} not found at {}", - run::bottle_prefix(&bottle).display() - )); - } - let work = out - .clone() - .unwrap_or_else(|| PathBuf::from("artifacts/hybrid-runs")); - Ok(RunArgs { - cfg: run::RunConfig { - wine, - bottle, - backend, - program, - args: args[i + 2..].to_vec(), - timeout: std::time::Duration::from_secs(timeout), - limits: memory::Limits { - min_start_free: min_start, - min_free, - poll: std::time::Duration::from_millis(250), - grace: std::time::Duration::from_secs(10), - }, - expect, - work_dir: work, - stall_timeout: stall.map(std::time::Duration::from_secs), - settle_bound: std::time::Duration::from_secs(settle), - read_free: memory::free_percentage, - require_gates, - max_output: 64 << 20, - }, - backends, - repeat, - out, - executable, - }) -} - -/// Refuse anything that is not a launchable Windows program, and describe what is. -fn identify(path: &std::path::Path) -> Result { - let image = pe::inspect(path)?; - image - .check_launchable() - .map_err(|e| format!("{}: {e}", path.display()))?; - let sha256 = betterxen_hybrid::cmdutil::run( - "/usr/bin/shasum", - &["-a", "256", &path.display().to_string()], - ) - .and_then(|o| o.split_whitespace().next().map(String::from)); - Ok(Json::obj(vec![ - ("path", Json::str(path.display().to_string())), - ("sha256", Json::opt_str(sha256)), - ("image", image.to_json()), - ])) -} - -fn with_executable(mut record: Json, executable: &Json) -> Json { - if let Json::Obj(fields) = &mut record { - fields.push(("executable".into(), executable.clone())); - } - record -} - -fn doctor(args: &[String]) -> ExitCode { - let (mut bottle, mut min_start) = (None, 50u8); - let mut it = args.iter(); - while let Some(a) = it.next() { - match (a.as_str(), it.next()) { - ("--bottle", Some(v)) => bottle = Some(v.clone()), - ("--min-start-free", Some(v)) if v.parse::().is_ok() => { - min_start = v.parse().unwrap_or(min_start) - } - _ => { - eprintln!("{USAGE}"); - return ExitCode::from(2); - } - } - } - let home = PathBuf::from(std::env::var("HOME").unwrap_or_default()); - let install = crossover::discover(&crossover::candidate_paths(&home)) - .into_iter() - .next(); - let wine = install.as_ref().map(|i| run::wine_path(&i.path)); - let facts = preflight::gather( - bottle.as_deref(), - wine.as_deref() - .map(|w| (crossover_build().unwrap_or_else(|| "unknown".into()), w)), - min_start, - ); - let checks = preflight::evaluate(&facts); - print!("{}", preflight::to_json(&checks).render()); - if checks.iter().all(|c| c.ok) { - ExitCode::SUCCESS - } else { - ExitCode::from(1) - } -} - -fn crossover_build() -> Option { - let home = PathBuf::from(std::env::var("HOME").unwrap_or_default()); - crossover::discover(&crossover::candidate_paths(&home)) - .first() - .and_then(|i| { - Some(format!( - "{} ({})", - i.short_version.clone()?, - i.build_version.clone()? - )) - }) -} - -fn save(dir: &std::path::Path, kind: &str, j: &Json) -> Result<(), String> { - betterxen_hybrid::records::save(dir, kind, j) - .map(|path| eprintln!("report saved: {}", path.display())) - .map_err(|error| format!("cannot save {kind} report in {}: {error}", dir.display())) -} - -fn finish_report(passed: bool, out: Option<&std::path::Path>, kind: &str, j: &Json) -> ExitCode { - print!("{}", j.render()); - if let Some(dir) = out - && let Err(error) = save(dir, kind, j) - { - eprintln!("{error}"); - return ExitCode::from(1); - } - if passed { - ExitCode::SUCCESS - } else { - ExitCode::from(1) - } -} - -fn run_cmd(args: &[String]) -> ExitCode { - let a = match parse_run_args(args) { - Ok(a) => a, - Err(e) => { - eprintln!("{e}\n{USAGE}"); - return ExitCode::from(2); - } - }; - let r = run::execute(&a.cfg, crossover_build()); - if r.class != run::Class::Passed { - eprintln!("run: {}", r.class.name()); - for g in r.gates.iter().filter(|g| !g.passed) { - eprintln!(" gate {} failed: {}", g.name, g.detail); - } - if let Some(e) = &r.error { - eprintln!(" {e}"); - } - } - finish_report( - r.class == run::Class::Passed, - a.out.as_deref(), - "run", - &with_executable(r.json, &a.executable), - ) -} - -fn bench_cmd(args: &[String]) -> ExitCode { - let a = match parse_run_args(args) { - Ok(a) if !a.backends.is_empty() => a, - Ok(_) => { - eprintln!("bench needs --backends\n{USAGE}"); - return ExitCode::from(2); - } - Err(e) => { - eprintln!("{e}\n{USAGE}"); - return ExitCode::from(2); - } - }; - let build = crossover_build(); - let mut per_backend = Vec::new(); - let mut all_ok = true; - for b in &a.backends { - let mut runs = Vec::new(); - for _ in 0..a.repeat { - let mut cfg = a.cfg.clone(); - cfg.backend = if b == "default" { - None - } else { - Some(b.clone()) - }; - let r = run::execute(&cfg, build.clone()); - all_ok &= r.class == run::Class::Passed; - runs.push(with_executable(r.json, &a.executable)); - } - per_backend.push(Json::obj(vec![ - ("backend", Json::str(b.clone())), - ("runs", Json::Arr(runs)), - ])); - } - let doc = Json::obj(vec![ - ("schema", Json::str("betterxen-hybrid-bench/0")), - ("repeat", Json::Num(a.repeat as f64)), - ("host", host::collect().to_json()), - ("results", Json::Arr(per_backend)), - ]); - finish_report(all_ok, a.out.as_deref(), "bench", &doc) -} - -fn main() -> ExitCode { - match std::env::args().nth(1).as_deref() { - Some("run") => return run_cmd(&std::env::args().skip(2).collect::>()), - Some("doctor") => return doctor(&std::env::args().skip(2).collect::>()), - Some("bench") => return bench_cmd(&std::env::args().skip(2).collect::>()), - _ => {} - } - if std::env::args().nth(1).as_deref() == Some("guard") { - return guard(&std::env::args().skip(2).collect::>()); - } - let args: Vec = std::env::args().skip(1).collect(); - let result: Result = match args.first().map(String::as_str) { - Some("host") => Ok(host::collect().to_json()), - Some("inspect") => match args.get(1) { - None => Err("inspect needs a file".into()), - Some(f) => pe::inspect(std::path::Path::new(f)).map(|i| i.to_json()), - }, - Some("crossover") => { - let app = match args.get(1).map(String::as_str) { - Some("--app") => args.get(2).map(PathBuf::from), - _ => None, - }; - Ok(crossover_json(app)) - } - Some("toolchain") => Ok(toolchain_json()), - Some("frames") => match args.get(1) { - None => Err("frames needs a file".into()), - Some(f) => std::fs::read_to_string(f) - .map_err(|e| format!("{f}: {e}")) - .and_then(|t| frames::parse_intervals(&t).map_err(|e| e.to_string())) - .and_then(|v| frames::analyze(&v).map_err(|e| e.to_string())) - .map(|s| s.to_json()), - }, - Some("receipt") => Ok(Json::obj(vec![ - ("schema", Json::str("betterxen-hybrid-receipt/0")), - ("host", host::collect().to_json()), - ("crossover", crossover_json(None)), - ("windows_cross_compilers", toolchain_json()), - ])), - _ => Err(USAGE.into()), - }; - match result { - Ok(j) => { - print!("{}", j.render()); - ExitCode::SUCCESS - } - Err(e) => { - eprintln!("{e}"); - ExitCode::from(2) - } - } -} - -#[cfg(test)] -mod report_tests { - use super::*; - - fn args(a: &[&str]) -> Vec { - a.iter().map(|s| s.to_string()).collect() - } - - // These fail before CrossOver discovery, so they run on hosts without CrossOver. - #[test] - fn bad_backend_bottle_or_program_is_refused_before_launch() { - let err = |a: &[&str]| parse_run_args(&args(a)).err().unwrap(); - assert!( - err(&["--bottle", "b", "--backend", "dmxt", "--", "x.exe"]).contains("unknown backend") - ); - assert!( - err(&["--bottle", "b", "--backends", "default,typo", "--", "x.exe"]) - .contains("unknown backend") - ); - assert!(err(&["--bottle", "../b", "--", "x.exe"]).contains("invalid bottle")); - assert!(err(&["--bottle", "b", "--", "/nonexistent/x.exe"]).contains("/nonexistent/x.exe")); - assert!(err(&["--bottle", "b", "--", "/bin/sh"]).contains("not a PE")); - assert!(err(&["--bottle", "b", "--", "--help"]).contains("must not start with")); - } - - #[test] - fn requested_evidence_failure_overrides_a_passing_workload() { - let path = std::env::temp_dir().join(format!( - "bx-report-invalid-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - std::fs::write(&path, "keep this file").unwrap(); - for kind in ["run", "bench"] { - assert_eq!( - finish_report(true, Some(&path), kind, &Json::Null), - ExitCode::from(1) - ); - } - assert_eq!(std::fs::read_to_string(&path).unwrap(), "keep this file"); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn stdout_only_reporting_preserves_workload_status() { - assert_eq!( - finish_report(true, None, "run", &Json::Null), - ExitCode::SUCCESS - ); - assert_eq!( - finish_report(false, None, "bench", &Json::Null), - ExitCode::from(1) - ); - } +fn main() -> std::process::ExitCode { + betterxen_hybrid::cli::run_cli(&std::env::args().skip(1).collect::>()) } diff --git a/crates/hybrid/src/run.rs b/crates/hybrid/src/run.rs index f5b8de8..45d5aee 100644 --- a/crates/hybrid/src/run.rs +++ b/crates/hybrid/src/run.rs @@ -20,6 +20,15 @@ //! environment unless a backend was requested. Inherited values silently changed the backend //! while the record said none was requested (reproduced by IamHeavyLazer in issue #350). //! +//! The child does not inherit the caller's environment. Only [`ENV_ALLOWLIST`] and explicit +//! `--env` pairs are passed, because a Windows program run this way could otherwise read any +//! host variable (observed: tokens and `SSH_AUTH_SOCK` are visible to it). This limits what +//! is handed over; it is not a sandbox, and the program can still reach the user's files. +//! +//! The launcher runs in its own process group. SIGINT, SIGTERM or SIGHUP to the supervisor +//! stops the group and the bottle. SIGKILL of the supervisor cannot be handled; use +//! `betterxen hybrid stop --bottle B` afterwards. +//! //! A workload may print `gate pass|FAIL ` lines. They are recorded, and a run //! whose process exits 0 is still not a pass if any gate failed or a required gate is absent: //! starting a process says nothing about whether it initialised. @@ -30,8 +39,10 @@ use crate::frames; use crate::json::Json; use crate::memory; +use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; +use std::process::{Child, Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; #[derive(Debug, Clone)] @@ -56,8 +67,31 @@ pub struct RunConfig { pub require_gates: Vec, /// Stop the run when stdout and stderr together exceed this many bytes. pub max_output: u64, + /// Pass the caller's whole environment instead of the allowlist. + pub inherit_env: bool, + /// Extra variables set for the child. + pub env: Vec<(String, String)>, + /// Keep the workload's full stdout and stderr files in `work_dir`. + pub keep_output: bool, + /// Set by a signal handler; the run is then stopped and classified `interrupted`. + pub interrupted: &'static AtomicBool, } +/// Host variables passed to the child unless the whole environment is requested. +pub const ENV_ALLOWLIST: [&str; 8] = [ + "HOME", + "USER", + "LOGNAME", + "TMPDIR", + "LANG", + "LC_ALL", + "LC_CTYPE", + "__CF_USER_TEXT_ENCODING", +]; + +/// System directories only: CrossOver's launcher is a script that needs standard tools. +const CHILD_PATH: &str = "/usr/bin:/bin:/usr/sbin:/sbin"; + /// Backend names accepted for `CX_GRAPHICS_BACKEND`. The installed CrossOver ignores an /// unknown value silently, so the runner refuses it instead. pub const BACKENDS: [&str; 4] = ["d3dmetal", "dxmt", "dxvk", "wined3d"]; @@ -107,6 +141,8 @@ pub enum Class { /// A gate reported failure, or a required gate never reported. GateFailed, OutputLimit, + /// The supervisor received SIGINT, SIGTERM or SIGHUP. + Interrupted, } impl Class { @@ -125,6 +161,7 @@ impl Class { Class::LaunchFailed => "launch_failed".into(), Class::GateFailed => "gate_failed".into(), Class::OutputLimit => "stopped_output_limit".into(), + Class::Interrupted => "interrupted".into(), } } } @@ -187,6 +224,62 @@ pub struct Samples { pub last_workload_rss_kb: u64, } +/// Process ids of the workload, identified the same way as for memory sampling. Input lines +/// are `ps -axo pid=,command=`. +fn workload_pids(ps: &str, file_name: &str) -> Vec { + let needle = format!("\\{file_name}").to_ascii_lowercase(); + ps.lines() + .filter_map(|l| { + let (pid, command) = l.trim_start().split_once(char::is_whitespace)?; + let command = command.trim_start().to_ascii_lowercase(); + let b = command.as_bytes(); + (b.len() > 3 && b[1] == b':' && b[2] == b'\\' && command.contains(&needle)) + .then(|| pid.parse().ok())? + }) + .filter(|pid| *pid > 1) + .collect() +} + +pub fn running_workload_pids(file_name: &str) -> Vec { + let ps = crate::cmdutil::run("/bin/ps", &["-axo", "pid=,command="]).unwrap_or_default(); + workload_pids(&ps, file_name) +} + +/// Wait briefly for the workload to disappear; kill what remains. Returns how many were +/// still alive after the wait. +fn reap_leftovers(file_name: &str, patience: Duration) -> usize { + let t = Instant::now(); + loop { + let pids = running_workload_pids(file_name); + if pids.is_empty() { + return 0; + } + if t.elapsed() >= patience { + for pid in &pids { + // SAFETY: kill takes plain integers; `pid` is a positive process id. + unsafe { libc::kill(*pid, libc::SIGKILL) }; + } + return pids.len(); + } + std::thread::sleep(Duration::from_millis(200)); + } +} + +/// Stop the launcher's whole process group: SIGTERM, then SIGKILL after `grace`. +fn stop_group(child: &mut Child, grace: Duration) { + let group = child.id() as i32; + // SAFETY: the child was started as leader of its own group, so `group` names only its + // descendants; killpg takes plain integers. + unsafe { libc::killpg(group, libc::SIGTERM) }; + let t = Instant::now(); + while t.elapsed() < grace && !matches!(child.try_wait(), Ok(Some(_))) { + std::thread::sleep(Duration::from_millis(50)); + } + // SAFETY: as above. A group that has already exited returns ESRCH, which is harmless. + unsafe { libc::killpg(group, libc::SIGKILL) }; + let _ = child.wait(); +} + /// RSS (KB) of the workload itself. Observed on CrossOver 26.3: the Windows program is /// re-parented to launchd and its command line is a drive-letter path (`Y:\...\name.exe`), /// so neither the bundle path nor the bottle path appears in it. @@ -272,6 +365,8 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option) -> RunRecord { .work_dir .join(format!("stderr-{t_wall}-{}.txt", std::process::id())); let mut settle: Option<(Duration, bool)> = None; + let mut leftovers: Option = None; + let mut passed_names: Vec = Vec::new(); let thermal_before = thermal(); let free_start = (cfg.read_free)(); @@ -292,6 +387,7 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option) -> RunRecord { .collect(); match free_start { + _ if cfg.interrupted.load(Ordering::SeqCst) => result.class = Class::Interrupted, None => result.class = Class::MemoryUnreadable, Some(f) if f < cfg.limits.min_start_free => result.class = Class::RefusedToStart, Some(_) => { @@ -307,9 +403,23 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option) -> RunRecord { .arg(&cfg.program) .args(&cfg.args); cmd.stdout(Stdio::from(o)).stderr(Stdio::from(e)); - for key in BACKEND_VARS { - cmd.env_remove(key); + cmd.process_group(0); + if cfg.inherit_env { + for key in BACKEND_VARS { + cmd.env_remove(key); + } + } else { + cmd.env_clear().env("PATH", CHILD_PATH); + for key in ENV_ALLOWLIST { + if let Some(value) = std::env::var_os(key) { + cmd.env(key, value); + } + } } + for (key, value) in &cfg.env { + cmd.env(key, value); + } + passed_names = cfg.env.iter().map(|(k, _)| k.clone()).collect(); if let Some(b) = &cfg.backend { cmd.env("CX_GRAPHICS_BACKEND", b); } @@ -341,7 +451,7 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option) -> RunRecord { Ok(None) => {} Err(error) => { result.error = Some(format!("lost track of the launcher: {error}")); - memory::terminate(&mut child, cfg.limits.grace); + stop_group(&mut child, cfg.limits.grace); stop_bottle(&cfg.wine, &cfg.bottle); break; } @@ -376,6 +486,9 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option) -> RunRecord { last_len = len; last_growth = Instant::now(); } + if cfg.interrupted.load(Ordering::SeqCst) { + stop = Some(Class::Interrupted); + } if stop.is_none() && len > cfg.max_output { stop = Some(Class::OutputLimit); } @@ -388,13 +501,14 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option) -> RunRecord { stop = Some(Class::Stalled); } if stop.is_some() { - memory::terminate(&mut child, cfg.limits.grace); + stop_group(&mut child, cfg.limits.grace); stop_bottle(&cfg.wine, &cfg.bottle); break; } std::thread::sleep(cfg.limits.poll); } result.duration = started.elapsed(); + leftovers = Some(reap_leftovers(file_name(&cfg.program), cfg.limits.grace)); if stop.is_some() { let t = Instant::now(); let need = cfg.limits.min_start_free; @@ -404,7 +518,8 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option) -> RunRecord { recovered = true; break; } - if t.elapsed() >= cfg.settle_bound { + // a second signal is not needed to leave the wait + if t.elapsed() >= cfg.settle_bound || stop == Some(Class::Interrupted) { break; } std::thread::sleep(cfg.limits.poll); @@ -580,24 +695,49 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option) -> RunRecord { ), ), ("launcher_error", Json::opt_str(result.error.clone())), + ( + "environment_policy", + Json::str(if cfg.inherit_env { + "inherited" + } else { + "allowlist" + }), + ), + ( + "extra_environment_names", + Json::Arr(passed_names.into_iter().map(Json::Str).collect()), + ), + ( + "workload_processes_killed_after_exit", + leftovers.map_or(Json::Null, |n| Json::Num(n as f64)), + ), ]); fields.extend(gpu_wired.json_fields()); result.json = Json::obj(fields); - let _ = std::fs::remove_file(&out_path); - let _ = std::fs::remove_file(&err_path); + if !cfg.keep_output { + let _ = std::fs::remove_file(&out_path); + let _ = std::fs::remove_file(&err_path); + } result } /// Prefix directory of a bottle. CrossOver documents `BottleDir` in its preferences; otherwise /// the default location under Application Support is used. pub fn bottle_prefix(bottle: &str) -> PathBuf { - let base = crate::crossover::preference("BottleDir") - .map(PathBuf::from) - .unwrap_or_else(|| { - PathBuf::from(std::env::var("HOME").unwrap_or_default()) - .join("Library/Application Support/CrossOver/Bottles") - }); - base.join(bottle) + let home = std::env::var("HOME").unwrap_or_default(); + bottle_base(crate::crossover::preference("BottleDir"), &home).join(bottle) +} + +/// The `BottleDir` preference may be written with a leading `~`, which `Path` does not expand. +fn bottle_base(preference: Option, home: &str) -> PathBuf { + let home = PathBuf::from(home); + match preference { + None => home.join("Library/Application Support/CrossOver/Bottles"), + Some(p) if p == "~" => home, + Some(p) => p + .strip_prefix("~/") + .map_or_else(|| PathBuf::from(&p), |rest| home.join(rest)), + } } /// Stop every process of one bottle with `wineserver -k`, selecting the bottle through @@ -666,6 +806,8 @@ mod tests { p } + static NEVER: AtomicBool = AtomicBool::new(false); + fn cfg(wine: PathBuf, timeout_ms: u64, tag: &str) -> RunConfig { RunConfig { wine, @@ -687,6 +829,10 @@ mod tests { read_free: memory::free_percentage, require_gates: vec![], max_output: 1 << 20, + inherit_env: false, + env: vec![], + keep_output: false, + interrupted: &NEVER, } } @@ -939,4 +1085,86 @@ mod tests { Class::Passed ); } + + #[test] + fn host_variables_are_withheld_unless_allowed_or_requested() { + if !cfg!(target_os = "macos") { + return; + } + // CARGO_MANIFEST_DIR is set by cargo for the test process and is not allowlisted. + assert!(std::env::var_os("CARGO_MANIFEST_DIR").is_some()); + let dir = std::env::temp_dir().join(format!("bxrun-env-{}", std::process::id())); + let w = stub( + &dir, + "echo \"manifest=${CARGO_MANIFEST_DIR:-absent} extra=${BX_EXTRA:-absent} home=${HOME:+set}\"; echo PASS", + ); + let mut c = cfg(w, 10_000, "env"); + c.env = vec![("BX_EXTRA".into(), "yes".into())]; + let r = execute(&c, None); + assert!( + r.stdout.contains("manifest=absent extra=yes home=set"), + "{}", + r.stdout + ); + assert!( + r.json + .render() + .contains("\"environment_policy\": \"allowlist\"") + ); + c.inherit_env = true; + let r = execute(&c, None); + assert!(!r.stdout.contains("manifest=absent"), "{}", r.stdout); + } + + #[test] + fn an_interrupt_stops_the_whole_process_group() { + if !cfg!(target_os = "macos") { + return; + } + static STOP: AtomicBool = AtomicBool::new(false); + let dir = std::env::temp_dir().join(format!("bxrun-int-{}", std::process::id())); + let pidfile = dir.join("grandchild.pid"); + let w = stub( + &dir, + &format!("/bin/sleep 30 & echo $! > '{}'; wait", pidfile.display()), + ); + let mut c = cfg(w, 20_000, "int"); + c.interrupted = &STOP; + let h = std::thread::spawn(|| { + std::thread::sleep(Duration::from_millis(400)); + STOP.store(true, Ordering::SeqCst); + }); + let t = Instant::now(); + let r = execute(&c, None); + h.join().unwrap(); + assert_eq!(r.class, Class::Interrupted); + assert!(t.elapsed() < Duration::from_secs(10)); + let pid: i32 = std::fs::read_to_string(pidfile) + .unwrap() + .trim() + .parse() + .unwrap(); + std::thread::sleep(Duration::from_millis(200)); + // SAFETY: signal 0 only asks whether the process exists. + assert_ne!(unsafe { libc::kill(pid, 0) }, 0, "grandchild survived"); + // A run requested after the interrupt does not start at all. + assert_eq!(execute(&c, None).class, Class::Interrupted); + } + + #[test] + fn workload_processes_are_identified_by_windows_command_line_only() { + let ps = " 501 Y:\\w\\d3d.exe --frames 1\n 502 /usr/bin/betterxen hybrid run -- /w/d3d.exe\n 1 C:\\x\\d3d.exe\n 503 Z:\\w\\other.exe"; + assert_eq!(workload_pids(ps, "d3d.exe"), [501]); + } + + #[test] + fn bottle_directory_preference_may_use_a_tilde() { + assert_eq!(bottle_base(Some("~/B".into()), "/h"), PathBuf::from("/h/B")); + assert_eq!(bottle_base(Some("~".into()), "/h"), PathBuf::from("/h")); + assert_eq!( + bottle_base(Some("/v/B".into()), "/h"), + PathBuf::from("/v/B") + ); + assert!(bottle_base(None, "/h").ends_with("CrossOver/Bottles")); + } }