Compare commits

...
Author SHA1 Message Date
ates 8a19b2b999 Add reversible system32 shim staging in bx-cli run (#459)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 21:06:10 +03:00
4 changed files with 235 additions and 1 deletions

No files matched your search

+1
View File
@@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- `bx-cli run` now stages allowlisted non-host Xbox shim DLLs (`bx_runtime_veh.dll`, `xgameruntime.dll`) into an initialized bottle/prefix `drive_c/windows/system32/` using an RAII guard so guests using `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)` resolve BetterXen's shim out of the box without permanently mutating the bottle or overwriting pre-existing files/symlinks. Added synthetic conformance fixture `test_system32_staging` (#459).
- `bx-cli run` gained `--timeout <secs>`, 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).
+171 -1
View File
@@ -5,7 +5,8 @@ mod supervise;
use std::collections::BTreeMap;
use std::env;
use std::fmt::Write as _;
use std::fs;
use std::fs::{self, OpenOptions};
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use std::time::Duration;
@@ -20,6 +21,84 @@ api-ms-win-core-psm-appnotify-l1-1-0,api-ms-win-core-psm-appnotify-l1-1-1,\
ext-ms-win-rtcore-ntuser-message-l1-1-0,ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0,\
ext-ms-win-rtcore-ntuser-window-l1-1-0,ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0=n,b";
/// Non-host Xbox shim DLLs that guest loaders resolve via `LOAD_LIBRARY_SEARCH_SYSTEM32`
/// (bypassing `WINEPATH`), plus `bx_runtime_veh.dll` which `xgameruntime.dll` imports. Staged into
/// `drive_c/windows/system32/` only when absent and removed when the run completes.
const SYSTEM32_STAGED_SHIMS: &[&str] = &["bx_runtime_veh.dll", "xgameruntime.dll"];
/// RAII guard for BetterXen shim DLLs temporarily staged into `drive_c/windows/system32/`.
/// Never overwrites or removes pre-existing files or symlinks.
struct StagedSystem32Shims {
staged: Vec<PathBuf>,
}
impl StagedSystem32Shims {
fn stage(prefix: &Path, shims_dir: &Path, dll_names: &[&str]) -> Self {
let mut staged = Vec::new();
let system32 = prefix.join("drive_c/windows/system32");
if !system32.is_dir() {
return Self { staged };
}
for &name in dll_names {
let src = shims_dir.join(name);
if !src.is_file() {
continue;
}
let dst = system32.join(name);
if dst.symlink_metadata().is_ok() {
eprintln!(
"note: leaving pre-existing {} untouched during system32 staging",
dst.display()
);
continue;
}
let copy_result = (|| -> io::Result<()> {
let mut reader = fs::File::open(&src)?;
let mut writer = OpenOptions::new().write(true).create_new(true).open(&dst)?;
io::copy(&mut reader, &mut writer)?;
Ok(())
})();
match copy_result {
Ok(()) => staged.push(dst),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
eprintln!(
"note: leaving pre-existing {} untouched during system32 staging",
dst.display()
);
}
Err(e) => {
let _ = fs::remove_file(&dst);
eprintln!(
"warning: could not stage {} into {}: {e}",
src.display(),
dst.display()
);
}
}
}
Self { staged }
}
fn cleanup(&mut self) {
for path in self.staged.drain(..) {
if let Err(e) = fs::remove_file(&path)
&& e.kind() != io::ErrorKind::NotFound
{
eprintln!(
"warning: failed to remove staged shim {}: {e}",
path.display()
);
}
}
}
}
impl Drop for StagedSystem32Shims {
fn drop(&mut self) {
self.cleanup();
}
}
/// Accepted `--backend` values. CrossOver ignores an unknown value silently, so one is refused.
const BACKENDS: [&str; 4] = ["d3dmetal", "dxmt", "dxvk", "wined3d"];
@@ -538,6 +617,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);
let mut staged_shims =
StagedSystem32Shims::stage(&environment_dir, &abs_shims, SYSTEM32_STAGED_SHIMS);
supervise::install_signal_handlers();
let outcome = supervise::supervise(cmd, timeout, supervise::received_signal);
let code = match &outcome {
@@ -585,6 +667,9 @@ fn cmd_run(args: &[String]) -> ExitCode {
_ => {}
}
// Remove staged system32 shims after wineserver teardown so open handles do not linger.
staged_shims.cleanup();
// Printed for failed and stopped runs too, which is when it matters most.
if let Some(log) = &abs_log
&& log_size(log) > log_size_before
@@ -882,4 +967,89 @@ sub setup_bottle_wineprefix {
"clwb VEH traps : at least 4 (sampled)"
);
}
#[test]
fn stages_allowlisted_shims_into_system32_and_removes_on_drop() {
let root = env::temp_dir().join(format!("bx-cli-stage-ok-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let shims = root.join("shims");
let sys32 = root.join("prefix/drive_c/windows/system32");
fs::create_dir_all(&shims).unwrap();
fs::create_dir_all(&sys32).unwrap();
fs::write(shims.join("bx_runtime_veh.dll"), b"bx-veh-bytes").unwrap();
fs::write(shims.join("xgameruntime.dll"), b"bx-shim-bytes").unwrap();
let staged_veh = sys32.join("bx_runtime_veh.dll");
let staged_xgr = sys32.join("xgameruntime.dll");
{
let guard =
StagedSystem32Shims::stage(&root.join("prefix"), &shims, SYSTEM32_STAGED_SHIMS);
assert_eq!(guard.staged, vec![staged_veh.clone(), staged_xgr.clone()]);
assert_eq!(fs::read(&staged_veh).unwrap(), b"bx-veh-bytes");
assert_eq!(fs::read(&staged_xgr).unwrap(), b"bx-shim-bytes");
}
assert!(!staged_veh.exists());
assert!(!staged_xgr.exists());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn staging_never_overwrites_or_deletes_preexisting_system32_dll() {
let root = env::temp_dir().join(format!("bx-cli-stage-keep-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let shims = root.join("shims");
let sys32 = root.join("prefix/drive_c/windows/system32");
fs::create_dir_all(&shims).unwrap();
fs::create_dir_all(&sys32).unwrap();
fs::write(shims.join("xgameruntime.dll"), b"bx-shim-bytes").unwrap();
let dst = sys32.join("xgameruntime.dll");
fs::write(&dst, b"host-original-bytes").unwrap();
{
let guard =
StagedSystem32Shims::stage(&root.join("prefix"), &shims, SYSTEM32_STAGED_SHIMS);
assert!(guard.staged.is_empty());
assert_eq!(fs::read(&dst).unwrap(), b"host-original-bytes");
}
assert_eq!(fs::read(&dst).unwrap(), b"host-original-bytes");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn staging_refuses_to_clobber_preexisting_symlink_in_system32() {
use std::os::unix::fs::symlink;
let root = env::temp_dir().join(format!("bx-cli-stage-sym-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let shims = root.join("shims");
let sys32 = root.join("prefix/drive_c/windows/system32");
fs::create_dir_all(&shims).unwrap();
fs::create_dir_all(&sys32).unwrap();
fs::write(shims.join("xgameruntime.dll"), b"bx-shim-bytes").unwrap();
let dst = sys32.join("xgameruntime.dll");
symlink(root.join("dangling-target"), &dst).unwrap();
{
let guard =
StagedSystem32Shims::stage(&root.join("prefix"), &shims, SYSTEM32_STAGED_SHIMS);
assert!(guard.staged.is_empty());
}
assert!(dst.symlink_metadata().unwrap().file_type().is_symlink());
assert!(!root.join("dangling-target").exists());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn staging_is_a_noop_when_system32_directory_is_absent() {
let root = env::temp_dir().join(format!("bx-cli-stage-empty-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let shims = root.join("shims");
fs::create_dir_all(&shims).unwrap();
fs::write(shims.join("xgameruntime.dll"), b"bx-shim-bytes").unwrap();
let guard =
StagedSystem32Shims::stage(&root.join("bare-prefix"), &shims, SYSTEM32_STAGED_SHIMS);
assert!(guard.staged.is_empty());
assert!(!root.join("bare-prefix").exists());
fs::remove_dir_all(root).unwrap();
}
}
@@ -0,0 +1,2 @@
add_executable(test_system32_staging main.cpp)
target_link_libraries(test_system32_staging PRIVATE kernel32)
@@ -0,0 +1,61 @@
/*
* #459: Synthetic conformance fixture for bx-cli reversible system32 shim staging.
*
* Does NOT statically import xgameruntime.dll. Instead, mirrors the dynamic loader path
* by calling LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32),
* verifying that the loaded module resolves from \windows\system32\xgameruntime.dll and
* exports InitializeApiImpl, then unloading cleanly.
*/
#include <windows.h>
#include <cstdio>
#include <cwchar>
#include <cwctype>
namespace {
bool ends_with_ci(const wchar_t* str, const wchar_t* suffix) {
const size_t slen = std::wcslen(str);
const size_t suflen = std::wcslen(suffix);
if (slen < suflen) return false;
const wchar_t* tail = str + (slen - suflen);
for (size_t i = 0; i < suflen; ++i) {
if (std::towlower(tail[i]) != std::towlower(suffix[i])) return false;
}
return true;
}
} // namespace
int main() {
HMODULE mod = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (!mod) {
std::fprintf(stderr, "FAIL: LoadLibraryExW(xgameruntime.dll, LOAD_LIBRARY_SEARCH_SYSTEM32) failed (err=%lu)\n",
static_cast<unsigned long>(GetLastError()));
return 1;
}
wchar_t path[MAX_PATH] = {};
const DWORD len = GetModuleFileNameW(mod, path, MAX_PATH);
if (len == 0 || len >= MAX_PATH) {
std::fprintf(stderr, "FAIL: GetModuleFileNameW failed (err=%lu)\n", static_cast<unsigned long>(GetLastError()));
FreeLibrary(mod);
return 1;
}
if (!ends_with_ci(path, L"\\windows\\system32\\xgameruntime.dll")) {
std::fprintf(stderr, "FAIL: unexpected module path: %ls\n", path);
FreeLibrary(mod);
return 1;
}
FARPROC init_fn = GetProcAddress(mod, "InitializeApiImpl");
if (!init_fn) {
std::fprintf(stderr, "FAIL: GetProcAddress(InitializeApiImpl) returned null\n");
FreeLibrary(mod);
return 1;
}
FreeLibrary(mod);
std::printf("PASS: test_system32_staging (%ls)\n", path);
return 0;
}