diff --git a/CHANGELOG.md b/CHANGELOG.md index c5e5e34b..4c4b6a7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,14 @@ remains unsupported. ### Added - Implemented clean-room COM `IUnknown` vtable dispatch in `xgameruntime.dll!QueryApiImpl` for the core public Microsoft PC GDK (`Microsoft.GDK.Windows 2610.0.9661`) interface families (`XAsync`/`XTaskQueue`/`XThread`, `XGameRuntimeIsFeatureAvailable`, `XSystem`, `XError`, `XPersistentLocalStorage`, `XUser`, `XStore`, `XGameUi`, `XNetworking`, `XGame`), with auto-logging `BX_VTABLE_STUB_LOG` fallback on unimplemented slots. Validated live on CrossOver 26.3 with an independently authored caller linked against Microsoft's public `xgameruntime.lib` (#456). +- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached. + - **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first. + - **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged. + - **Uninitialized environments:** a bare `--prefix` without `system32` is initialized with `wineboot --init` under the same isolated environment. A bottle without one fails with a hint. Neither case is ever skipped silently. + - **Partial shim folders:** a `--shims` folder without `xgameruntime.dll` prints a notice and the run continues without staging, as it did before staging existed. + - **Supervision:** `--timeout`, SIGINT, SIGTERM and SIGHUP also cover the `wineboot --init` step, so an interrupted first run does not leave `wineserver` running. + - **Tests:** 8 unit tests cover staging and the dependency walk. `tests/conformance/test_system32_staging/` makes the `LOAD_LIBRARY_SEARCH_SYSTEM32` load and requires BetterXen's shim, from `system32`, exporting `QueryApiImpl`, and the same module for `SYSTEM32 | APPLICATION_DIR`. `--expect-missing` is the negative control for an unstaged prefix. + - **Local result:** on one Apple M3 Pro (macOS 27.2.1) with CodeWeavers Wine 11.0 built from source, so not CrossOver 26.3, and with the staging done by hand: the control passed and the unstaged run failed as expected. Staging the runtime alone still failed, which is how the dependency rule was found. Staging both passed 4/4 in two runs. `bx-cli run` itself was not run, since CrossOver is not installed on that host. - `bx-cli run` gained `--timeout `, cleanup of the launcher process group and the selected bottle or prefix on timeout, SIGINT, SIGTERM or SIGHUP (including re-resolving managed bottles whose first launch creates a private stub), `--backend` (bottle mode only), and a printed trace summary after a run with `--log`. The bottle to stop is located through CrossOver itself, so bottles outside the default directory are covered. A normal exit does not stop the environment. Recorded a one-host observation that D3D12 swapchains stay referenced under D3DMetal (#408). - Added `test_apiset_resolution`, a conformance fixture that statically imports the six API-set `win32_bridge` names and reports which module serves each (`--expect host|shim`), and accepted ADR 0007 recording that CrossOver 26.0 and 26.3 answer them via built-ins (`twinapi.appcore.dll` / `user32.dll`) (#437). - Added file-mapping-backed 64 KiB and 2 MiB physical pages, contiguous and scatter aliases (including intra-span duplicate-tag aliasing), exact-span unmap validation, physical region queries (`bx_xmem_query_region`), and shared working-set accounting / combined title memory budget enforcement across heap, virtual, and physical allocations in `xmem.dll`. Synthetic `XMemAllocatePhysicalPages` / `XMemFreePhysicalPages` signatures follow Win32 AWE (`memoryapi.h`) pending a public console flag encoding (#412). diff --git a/launcher/crates/bx-cli/src/main.rs b/launcher/crates/bx-cli/src/main.rs index 07cf2c0b..aba56618 100644 --- a/launcher/crates/bx-cli/src/main.rs +++ b/launcher/crates/bx-cli/src/main.rs @@ -1,5 +1,6 @@ //! Track A (M1-A1): Native ARM64 macOS CLI for BetterXen hybrid execution. +mod stage; mod supervise; use std::collections::BTreeMap; @@ -8,7 +9,7 @@ use std::fmt::Write as _; use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode}; -use std::time::Duration; +use std::time::{Duration, Instant}; use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus}; use bx_telemetry::summarize_jsonl; @@ -435,6 +436,68 @@ fn bottle_options(backend: Option<&str>) -> Vec { options } +/// The CrossOver Wine environment for a bare `--prefix` (bottles get theirs from `bin/wine`). +fn apply_prefix_env(command: &mut Command, cx_root: &Path, prefix: &Path, wineloader: &Path) { + command + .env("WINEPREFIX", prefix) + .env("WINESERVER", cx_root.join("bin/wineserver")) + .env("WINELOADER", wineloader) + .env( + "WINEDLLPATH", + format!( + "{}:{}", + cx_root.join("lib/wine").display(), + cx_root.join("lib64/wine").display() + ), + ) + .env( + "DYLD_FALLBACK_LIBRARY_PATH", + format!( + "{}:{}:/usr/lib", + cx_root.join("lib64").display(), + cx_root.join("lib").display() + ), + ); +} + +/// Reports a timeout or signal and stops the environment's `wineserver`. True if cleanup failed. +fn stop_environment( + stop: Stop, + cx_root: &Path, + environment_dir: &Path, + bottle: Option<&str>, + inherit_env: bool, +) -> bool { + match stop { + Stop::TimedOut => eprintln!("timed out; stopping the environment"), + Stop::Signalled(signal) => { + eprintln!("received signal {signal}; stopping the environment"); + } + } + let server_env: Vec<(String, String)> = collect_isolated_host_env(|k| env::var(k).ok()) + .into_iter() + .collect(); + let mut cleanup_failed = false; + let prefixes_to_stop = match cleanup_prefixes_for_stop(environment_dir, bottle, |name| { + resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env) + }) { + Ok(prefixes) => prefixes, + Err(e) => { + eprintln!("cleanup failed to re-resolve bottle prefix: {e}"); + cleanup_failed = true; + vec![environment_dir.to_path_buf()] + } + }; + for prefix in &prefixes_to_stop { + if let Err(e) = supervise::stop_server(&cx_root.join("bin/wineserver"), prefix, &server_env) + { + eprintln!("cleanup failed, programs may still be running: {e}"); + cleanup_failed = true; + } + } + cleanup_failed +} + fn cmd_run(args: &[String]) -> ExitCode { let run = match parse_run_args(args) { Ok(run) => run, @@ -482,6 +545,60 @@ fn cmd_run(args: &[String]) -> ExitCode { None => resolved_prefix.clone(), }; + // Handled from here on, so that prefix initialization is cleaned up like the guest is. + supervise::install_signal_handlers(); + let started = Instant::now(); + + // #457: shims loaded with LOAD_LIBRARY_SEARCH_SYSTEM32 never see WINEPATH, so they are + // copied into the environment's system32 first. A bare prefix is initialized for that. + let system32 = stage::system32_dir(&environment_dir); + if bottle.is_none() && !system32.is_dir() && stage::has_system32_shims(&abs_shims) { + let _ = fs::create_dir_all(&resolved_prefix); + let mut boot = Command::new(&wineloader); + boot.args(["wineboot", "--init"]); + apply_host_env(&mut boot, inherit_env); + apply_prefix_env(&mut boot, cx_root, &resolved_prefix, &wineloader); + boot.env("WINEDEBUG", "-all"); + match supervise::supervise(boot, timeout, supervise::received_signal) { + Ok(Outcome::Exited(st)) if st.success() => {} + Ok(Outcome::Exited(st)) => { + eprintln!( + "error: wineboot --init failed for {}: {st}", + resolved_prefix.display() + ); + return ExitCode::FAILURE; + } + Ok(outcome @ Outcome::Stopped(stop)) => { + let failed = stop_environment(stop, cx_root, &environment_dir, None, inherit_env); + let code = outcome.exit_code(); + return ExitCode::from(if failed { code.max(1) } else { code }); + } + Err(e) => { + eprintln!( + "error: cannot run wineboot for {}: {e}", + resolved_prefix.display() + ); + return ExitCode::FAILURE; + } + } + } + match stage::stage_system32(&abs_shims, &system32) { + Ok(staged) => { + for item in &staged { + eprintln!("bx-cli: {}", item.describe()); + } + } + Err(e) => { + let hint = if bottle.is_some() { + " (start the bottle once so CrossOver creates it)" + } else { + "" + }; + eprintln!("error: cannot stage system32 shims: {e}{hint}"); + return ExitCode::FAILURE; + } + } + let mut cmd = if let Some(ref bname) = bottle { let mut c = Command::new(&wine_wrapper); c.args(["--bottle", bname]) @@ -498,25 +615,7 @@ fn cmd_run(args: &[String]) -> ExitCode { apply_host_env(&mut cmd, inherit_env); if bottle.is_none() { - cmd.env("WINEPREFIX", &resolved_prefix) - .env("WINESERVER", cx_root.join("bin/wineserver")) - .env("WINELOADER", &wineloader) - .env( - "WINEDLLPATH", - format!( - "{}:{}", - cx_root.join("lib/wine").display(), - cx_root.join("lib64/wine").display() - ), - ) - .env( - "DYLD_FALLBACK_LIBRARY_PATH", - format!( - "{}:{}:/usr/lib", - cx_root.join("lib64").display(), - cx_root.join("lib").display() - ), - ); + apply_prefix_env(&mut cmd, cx_root, &resolved_prefix, &wineloader); } cmd.env("ROSETTA_ADVERTISE_AVX", "1") @@ -538,8 +637,9 @@ fn cmd_run(args: &[String]) -> ExitCode { let log_size = |log: &PathBuf| fs::metadata(log).map_or(0, |m| m.len()); let log_size_before = abs_log.as_ref().map_or(0, log_size); - supervise::install_signal_handlers(); - let outcome = supervise::supervise(cmd, timeout, supervise::received_signal); + // `--timeout` bounds the whole run, including any prefix initialization above. + let remaining = timeout.map(|limit| limit.saturating_sub(started.elapsed())); + let outcome = supervise::supervise(cmd, remaining, supervise::received_signal); let code = match &outcome { Ok(outcome) => outcome.exit_code(), Err(e) => { @@ -553,34 +653,13 @@ fn cmd_run(args: &[String]) -> ExitCode { eprintln!("guest exited with status: {status}"); } Ok(Outcome::Stopped(stop)) => { - match stop { - Stop::TimedOut => eprintln!("timed out; stopping the environment"), - Stop::Signalled(signal) => { - eprintln!("received signal {signal}; stopping the environment"); - } - } - let server_env: Vec<(String, String)> = collect_isolated_host_env(|k| env::var(k).ok()) - .into_iter() - .collect(); - let prefixes_to_stop = - match cleanup_prefixes_for_stop(&environment_dir, bottle.as_deref(), |name| { - resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env) - }) { - Ok(prefixes) => prefixes, - Err(e) => { - eprintln!("cleanup failed to re-resolve bottle prefix: {e}"); - cleanup_failed = true; - vec![environment_dir.clone()] - } - }; - for prefix in &prefixes_to_stop { - if let Err(e) = - supervise::stop_server(&cx_root.join("bin/wineserver"), prefix, &server_env) - { - eprintln!("cleanup failed, programs may still be running: {e}"); - cleanup_failed = true; - } - } + cleanup_failed = stop_environment( + *stop, + cx_root, + &environment_dir, + bottle.as_deref(), + inherit_env, + ); } _ => {} } diff --git a/launcher/crates/bx-cli/src/stage.rs b/launcher/crates/bx-cli/src/stage.rs new file mode 100644 index 00000000..d23d44bb --- /dev/null +++ b/launcher/crates/bx-cli/src/stage.rs @@ -0,0 +1,330 @@ +//! #457: shims a guest loads by system-directory search, staged into the prefix's `system32`. +//! +//! The GDK bootstrap that titles link statically loads `xgameruntime.dll` with +//! `LoadLibraryExW(name, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32)`. That search never consults +//! `WINEPATH`, where `bx-cli run` otherwise exposes the shims, so those shims are copied into +//! `drive_c/windows/system32` of the prefix or bottle before launch. +//! +//! The same search flags apply to the DLL's own imports, so every BetterXen shim it imports +//! (for example `bx_runtime_veh.dll`) is staged too. Otherwise the load fails unless the guest +//! happened to load that dependency earlier. + +use std::collections::BTreeSet; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +/// Shims loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`. +pub const SYSTEM32_SHIMS: &[&str] = &["xgameruntime.dll"]; + +/// `roots` plus, transitively, every import that is itself a file in the shim folder +/// (`is_shim`). Names are compared case-insensitively, as the Windows loader does, and returned +/// lowercased in a stable order. +pub fn shim_closure( + roots: &[&str], + is_shim: S, + mut imports_of: I, +) -> Result, String> +where + I: FnMut(&str) -> Result, String>, + S: Fn(&str) -> bool, +{ + let mut done = BTreeSet::new(); + let mut todo: Vec = roots.iter().map(|r| r.to_ascii_lowercase()).collect(); + while let Some(name) = todo.pop() { + if !done.insert(name.clone()) { + continue; + } + for dep in imports_of(&name)? { + let dep = dep.to_ascii_lowercase(); + if is_shim(&dep) && !done.contains(&dep) { + todo.push(dep); + } + } + } + Ok(done.into_iter().collect()) +} + +/// The shim file in `shims_dir` named `name`, matched case-insensitively. +fn find_shim(shims_dir: &Path, name: &str) -> Option { + let exact = shims_dir.join(name); + if exact.is_file() { + return Some(exact); + } + fs::read_dir(shims_dir) + .ok()? + .filter_map(|e| e.ok()) + .find_map(|e| { + let file = e.file_name(); + (file.to_string_lossy().eq_ignore_ascii_case(name) && e.path().is_file()) + .then(|| e.path()) + }) +} + +/// DLL names a PE32+ file imports, read with `bx-probe`. +fn pe_imports(path: &Path) -> Result, String> { + let bytes = fs::read(path).map_err(|e| format!("cannot read shim {}: {e}", path.display()))?; + let summary = bx_probe::probe_pe32_plus(&bytes) + .map_err(|e| format!("cannot read imports of {}: {e:?}", path.display()))?; + Ok(summary.imports.into_keys().collect()) +} + +/// The 64-bit system directory of a Wine prefix. +pub fn system32_dir(prefix: &Path) -> PathBuf { + prefix.join("drive_c").join("windows").join("system32") +} + +/// What staging did to one file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Staged { + Copied(PathBuf), + Replaced(PathBuf), + Unchanged(PathBuf), + /// A [`SYSTEM32_SHIMS`] file the shim folder does not have. + Absent(PathBuf), +} + +impl Staged { + pub fn describe(&self) -> String { + match self { + Staged::Copied(p) => format!("staged {}", p.display()), + Staged::Replaced(p) => format!("replaced {}", p.display()), + Staged::Unchanged(p) => format!("already current {}", p.display()), + Staged::Absent(p) => format!("not staged, {} not found", p.display()), + } + } +} + +/// True if the shim folder has any [`SYSTEM32_SHIMS`] file, so there is something to stage. +pub fn has_system32_shims(shims_dir: &Path) -> bool { + SYSTEM32_SHIMS + .iter() + .any(|name| find_shim(shims_dir, name).is_some()) +} + +/// Copies every [`SYSTEM32_SHIMS`] file, and the shims they import, from `shims_dir` into +/// `system32`. The directory must already exist (an uninitialized prefix is a caller error, not +/// something to skip). A shim the folder does not have is reported as [`Staged::Absent`], so a +/// run with a partial `--shims` folder still starts. A copy already identical byte for byte is +/// left alone, a different one is replaced. Nothing outside `system32` is written. +pub fn stage_system32(shims_dir: &Path, system32: &Path) -> Result, String> { + stage_system32_with(shims_dir, system32, pe_imports) +} + +fn stage_system32_with( + shims_dir: &Path, + system32: &Path, + mut imports_of: I, +) -> Result, String> +where + I: FnMut(&Path) -> Result, String>, +{ + let (roots, absent): (Vec<&str>, Vec<&str>) = SYSTEM32_SHIMS + .iter() + .copied() + .partition(|name| find_shim(shims_dir, name).is_some()); + let mut staged: Vec = absent + .iter() + .map(|name| Staged::Absent(shims_dir.join(name))) + .collect(); + if roots.is_empty() { + return Ok(staged); + } + if !system32.is_dir() { + return Err(format!( + "{} does not exist; the prefix is not initialized", + system32.display() + )); + } + let names = shim_closure( + &roots, + |dep| find_shim(shims_dir, dep).is_some(), + |name| match find_shim(shims_dir, name) { + Some(path) => imports_of(&path), + None => Err(format!( + "cannot read shim {}: not found", + shims_dir.join(name).display() + )), + }, + )?; + for name in &names { + let src = find_shim(shims_dir, name).unwrap_or_else(|| shims_dir.join(name)); + let bytes = + fs::read(&src).map_err(|e| format!("cannot read shim {}: {e}", src.display()))?; + let dst = system32.join(name); + let result = match fs::read(&dst) { + Ok(existing) if existing == bytes => Staged::Unchanged(dst.clone()), + Ok(_) => Staged::Replaced(dst.clone()), + Err(e) if e.kind() == io::ErrorKind::NotFound => Staged::Copied(dst.clone()), + Err(e) => return Err(format!("cannot read {}: {e}", dst.display())), + }; + if !matches!(result, Staged::Unchanged(_)) { + // Write beside the target, then rename, so a guest never sees a half-written DLL. + // The name is per process, so a concurrent run cannot rename a partial write. + let tmp = system32.join(format!(".{name}.{}.bx-staging", std::process::id())); + fs::write(&tmp, &bytes).map_err(|e| { + let _ = fs::remove_file(&tmp); + format!("cannot write {}: {e}", tmp.display()) + })?; + fs::rename(&tmp, &dst).map_err(|e| { + let _ = fs::remove_file(&tmp); + format!("cannot replace {}: {e}", dst.display()) + })?; + } + staged.push(result); + } + Ok(staged) +} + +#[cfg(test)] +mod tests { + use super::*; + + struct TempDir(PathBuf); + impl TempDir { + fn new(tag: &str) -> Self { + let p = std::env::temp_dir().join(format!( + "bx-stage-{tag}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = fs::remove_dir_all(&p); + fs::create_dir_all(&p).unwrap(); + TempDir(p) + } + } + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn setup(tag: &str) -> (TempDir, PathBuf, PathBuf) { + let t = TempDir::new(tag); + let shims = t.0.join("shims"); + let prefix = t.0.join("prefix"); + fs::create_dir_all(&shims).unwrap(); + fs::create_dir_all(system32_dir(&prefix)).unwrap(); + for name in SYSTEM32_SHIMS { + fs::write(shims.join(name), b"shim v1").unwrap(); + } + fs::write(shims.join("bx_runtime_veh.dll"), b"veh v1").unwrap(); + fs::write(shims.join("unrelated.dll"), b"not imported").unwrap(); + (t, shims, prefix) + } + + /// The import graph of the fake shims: the runtime imports the VEH logger and a system DLL. + fn fake_imports(path: &Path) -> Result, String> { + let name = path + .file_name() + .unwrap() + .to_string_lossy() + .to_ascii_lowercase(); + Ok(match name.as_str() { + "xgameruntime.dll" => vec!["BX_RUNTIME_VEH.dll".into(), "KERNEL32.dll".into()], + _ => vec!["KERNEL32.dll".into()], + }) + } + + fn stage(shims: &Path, sys: &Path) -> Result, String> { + stage_system32_with(shims, sys, fake_imports) + } + + #[test] + fn closure_follows_shim_imports_only() { + let shims: BTreeSet<&str> = ["a.dll", "b.dll", "c.dll"].into(); + let graph = |n: &str| -> Result, String> { + Ok(match n { + "a.dll" => vec!["B.DLL".into(), "kernel32.dll".into()], + "b.dll" => vec!["c.dll".into(), "a.dll".into()], + _ => vec![], + }) + }; + let got = shim_closure(&["A.dll"], |d| shims.contains(d), graph).unwrap(); + assert_eq!(got, vec!["a.dll", "b.dll", "c.dll"]); + } + + #[test] + fn stages_the_runtime_and_its_shim_dependency() { + let (_t, shims, prefix) = setup("deps"); + let sys = system32_dir(&prefix); + let staged = stage(&shims, &sys).unwrap(); + assert_eq!(staged.len(), 2, "{staged:?}"); + assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v1"); + assert!( + !sys.join("unrelated.dll").exists(), + "only imported shims are staged" + ); + } + + #[test] + fn system32_is_under_drive_c() { + assert_eq!( + system32_dir(Path::new("/p")), + PathBuf::from("/p/drive_c/windows/system32") + ); + } + + #[test] + fn copies_then_leaves_identical_copy_alone() { + let (_t, shims, prefix) = setup("idem"); + let sys = system32_dir(&prefix); + let first = stage(&shims, &sys).unwrap(); + assert!(first.iter().all(|s| matches!(s, Staged::Copied(_)))); + assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v1"); + let second = stage(&shims, &sys).unwrap(); + assert!(second.iter().all(|s| matches!(s, Staged::Unchanged(_)))); + } + + #[test] + fn replaces_an_older_copy() { + let (_t, shims, prefix) = setup("replace"); + let sys = system32_dir(&prefix); + fs::write(sys.join("xgameruntime.dll"), b"old").unwrap(); + let staged = stage(&shims, &sys).unwrap(); + assert!(staged.contains(&Staged::Replaced(sys.join("xgameruntime.dll")))); + assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v1"); + let leftovers: Vec<_> = fs::read_dir(&sys) + .unwrap() + .filter_map(|e| e.ok()) + .filter(|e| e.file_name().to_string_lossy().contains("bx-staging")) + .collect(); + assert!(leftovers.is_empty(), "temporary file left behind"); + } + + #[test] + fn missing_shim_is_reported_and_nothing_is_staged() { + let (t, shims, prefix) = setup("missing"); + fs::remove_file(shims.join("xgameruntime.dll")).unwrap(); + assert!(!has_system32_shims(&shims)); + let sys = system32_dir(&prefix); + let expected = vec![Staged::Absent(shims.join("xgameruntime.dll"))]; + assert_eq!(stage(&shims, &sys).unwrap(), expected); + assert_eq!(fs::read_dir(&sys).unwrap().count(), 0); + // With nothing to stage, a prefix without system32 is not an error either. + let fresh = system32_dir(&t.0.join("fresh")); + assert_eq!(stage(&shims, &fresh).unwrap(), expected); + assert!(!fresh.exists()); + } + + #[test] + fn uninitialized_prefix_is_an_error_not_a_skip() { + let (t, shims, _prefix) = setup("uninit"); + let sys = system32_dir(&t.0.join("fresh")); + let err = stage(&shims, &sys).unwrap_err(); + assert!(err.contains("not initialized"), "{err}"); + assert!(!sys.exists(), "staging must not create the prefix itself"); + } + + #[test] + fn writes_only_inside_system32() { + let (_t, shims, prefix) = setup("scope"); + let sys = system32_dir(&prefix); + stage(&shims, &sys).unwrap(); + let windows: Vec<_> = fs::read_dir(prefix.join("drive_c/windows")) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(windows, vec![std::ffi::OsString::from("system32")]); + } +} diff --git a/tests/conformance/test_system32_staging/CMakeLists.txt b/tests/conformance/test_system32_staging/CMakeLists.txt new file mode 100644 index 00000000..6979b877 --- /dev/null +++ b/tests/conformance/test_system32_staging/CMakeLists.txt @@ -0,0 +1,4 @@ +# #457: xgameruntime.dll reached by LOAD_LIBRARY_SEARCH_SYSTEM32 after bx-cli run stages it. +# Links no shim: the load under test is the dynamic one GDK titles make. +add_executable(test_system32_staging main.cpp) +target_link_libraries(test_system32_staging PRIVATE kernel32) diff --git a/tests/conformance/test_system32_staging/main.cpp b/tests/conformance/test_system32_staging/main.cpp new file mode 100644 index 00000000..1ba1b7f1 --- /dev/null +++ b/tests/conformance/test_system32_staging/main.cpp @@ -0,0 +1,65 @@ +/* + * #457: clean-room synthetic test for system32 shim staging by `bx-cli run`. + * + * GDK titles load the runtime with LoadLibraryExW(L"xgameruntime.dll", NULL, + * LOAD_LIBRARY_SEARCH_SYSTEM32), which does not search WINEPATH or the executable's folder. + * This test makes that load and requires that BetterXen's shim answers it: + * - the module loads, from a path under system32; + * - it exports QueryApiImpl (a BetterXen xgameruntime export, absent from Wine builtins); + * - LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR gives the same module. + * + * `--expect-missing` is the negative control for an unstaged prefix: the load must fail. + * Exit 0 on pass, 1 on failure. + */ +#include + +#include +#include +#include + +namespace { + +int g_checks = 0; +int g_failures = 0; + +bool check(bool ok, const char* what) { + g_checks++; + if (!ok) { + g_failures++; + std::fprintf(stderr, "FAIL: %s\n", what); + } else { + std::printf("PASS: %s\n", what); + } + return ok; +} + +bool path_in_system32(HMODULE m) { + wchar_t path[MAX_PATH * 2] = {}; + const DWORD n = GetModuleFileNameW(m, path, MAX_PATH * 2); + if (n == 0 || n >= MAX_PATH * 2) return false; + for (DWORD i = 0; i < n; ++i) path[i] = static_cast(towlower(path[i])); + std::printf("INFO: loaded from %ls\n", path); + return std::wcsstr(path, L"\\windows\\system32\\xgameruntime.dll") != nullptr; +} + +} // namespace + +int main(int argc, char** argv) { + const bool expect_missing = argc > 1 && std::strcmp(argv[1], "--expect-missing") == 0; + + HMODULE sys = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + if (expect_missing) { + check(sys == nullptr, "unstaged: LOAD_LIBRARY_SEARCH_SYSTEM32 load fails"); + if (sys) FreeLibrary(sys); + } else if (check(sys != nullptr, "LOAD_LIBRARY_SEARCH_SYSTEM32 loads xgameruntime.dll")) { + check(path_in_system32(sys), "module path is under system32"); + check(GetProcAddress(sys, "QueryApiImpl") != nullptr, "module exports QueryApiImpl (BetterXen shim)"); + HMODULE both = LoadLibraryExW(L"xgameruntime.dll", nullptr, + LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR); + check(both == sys, "SYSTEM32 | APPLICATION_DIR search returns the same module"); + if (both) FreeLibrary(both); + FreeLibrary(sys); + } + std::printf("SUMMARY: %d checks, %d failed\n", g_checks, g_failures); + return g_failures == 0 ? 0 : 1; +}