Compare commits

...
Author SHA1 Message Date
Ateş d38c5253c6 Merge pull request #490 from MacosPorters/track-d/479-harness-pid-path
[Track D] Handle apostrophes in the harness test PID path
2026-11-27 00:28:19 +03:00
Ateş 6fb171b247 Merge pull request #489 from jelly013/track-a/484-bridge-staging
[ABI] + [M2-A] Build, stage and verify bx_shader_bridge.dll in build-shims (#484)
2026-11-27 00:26:55 +03:00
ates 482293fd35 Pass the harness PID file as a probe argument
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 00:25:28 +03:00
atharvranjan 993cd222a4 Merge pull request #480 from sahib453/track-d/479-harness-test-timing
[Track D] Stop d3dmetal-harness runner tests racing probe start-up (#479)
2026-11-26 15:24:29 -06:00
jelly013 54b295434e Merge remote-tracking branch 'upstream/main' into track-a/484-bridge-staging
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 22:09:36 +01:00
jelly013 8141b8e282 build-shims: build, stage and verify bx_shader_bridge.dll
scripts/build-shims.sh builds shader-transpiler/crates/dxbc-accc for
x86_64-pc-windows-gnu, linked with abi/defs/bx_shader_bridge.def, and
places it in build-shims/bin as bx_shader_bridge.dll. The existing
verifier then checks it like every shim: export directory name, exact
exports, ordinals, no forwarders, no MinGW runtime imports. It now
reports 17 DLLs and 111 exports.

cargo and rustc are resolved through rustup when present, and the
build always goes to <repo>/target. A rustc without std for the
Windows target stops the script with the rustup command to run; the
bridge is never skipped. The CI job installs that target with its
pinned toolchain.

d3d12_xs's shader format gate (#466) can then load the bridge from
build-shims/bin without a manual copy.

Closes #484

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 22:08:29 +01:00
jelly013 ba9a053b5c [ABI] Add the bx_shader_bridge.dll export list
abi/defs/bx_shader_bridge.def freezes the three entry points of
abi/include/bx_shader_bridge.h for bx_shader_bridge.dll, the x86-64
Windows build of shader-transpiler/crates/dxbc-accc (#445). Linking
with it also gives the DLL its export directory name. abi/README.md
notes that this is the one .def whose DLL is not under shims/.

build-shims.sh verifies every .def against a built DLL, so this
commit lands together with the next one, which builds the bridge.

Refs #484

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 22:08:29 +01:00
sahib453 e71fca720a Merge main and keep both changelog entries
Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:34:27 +05:30
atharvranjan 83391f57be Merge pull request #487 from MacosPorters/track-e/481-gameinput-callbacks
[M2-E3] gameinput: implement IGameInput callback lifecycle and SetFocusPolicy (#481)
2026-11-26 15:04:06 -06:00
atharvranjan 8877bff9f2 Merge pull request #488 from MacosPorters/track-a/482-stage-gameinput
[M2-A2] bx-cli: stage GameInput.dll in system32 with safe Wine builtin stub replacement (#482)
2026-11-26 15:02:15 -06:00
sahib453 daeeaeae34 Merge main; correct the changelog claim and clean up after a failed kill test
Addresses review of #480: the changelog no longer says the old kill
test passed with only the kill removed (it passed only with both the
kill and the wait removed). A PidFile guard removes the pid file and
kills the recorded process when the test fails.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:26:47 +05:30
ates f016960021 [M2-A2] bx-cli: stage GameInput.dll in system32 with Wine stub backup (#482)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 23:47:33 +03:00
sahib453 2cc44b8318 Stop d3dmetal-harness runner tests racing probe start-up
kills_a_probe_that_exceeds_the_timeout and
a_descendant_holding_the_pipes_cannot_outlast_the_deadline gave a
freshly written script 300 ms and 500 ms to start and print, and the
first failed intermittently with empty stdout (#479). Both now use a
2 s deadline. The kill test also checks that the probe ran until the
deadline and that its process is gone afterwards. Test-only change.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:00:21 +05:30
9 changed files with 306 additions and 32 deletions

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
test "$(sysctl -n sysctl.proc_translated)" = 0
- name: Install Rust toolchain
run: |
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy --target x86_64-pc-windows-gnu
rustc -vV
- name: Check ARM64 Rust workspace (launcher + shader-transpiler)
run: |
+5
View File
@@ -10,6 +10,9 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- `scripts/build-shims.sh` now builds and verifies `bx_shader_bridge.dll` with the shims (#484). It builds the Windows version of `shader-transpiler/crates/dxbc-accc` (#445), linked with the new frozen export list `abi/defs/bx_shader_bridge.def`, so its export directory name is `bx_shader_bridge.dll`. It places the DLL in `build-shims/bin` and checks it with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. The script now reports 17 DLLs and 111 exports.
- **Toolchain:** `cargo` and `rustc` come from rustup when available. The build always uses `<repo>/target`, and a missing `x86_64-pc-windows-gnu` target stops the script with `rustup target add x86_64-pc-windows-gnu` (it is never skipped). The CI job installs that target with its pinned toolchain.
- **Effect:** `d3d12_xs`'s shader gate (#466) finds the bridge in `build-shims/bin` without a manual copy.
- Implemented the `IGameInput` v0 device-callback lifecycle (`RegisterDeviceCallback`, `StopCallback`, `UnregisterCallback`) and `SetFocusPolicy` in `shims/gameinput/gameinput.cpp` (#481). `RegisterDeviceCallback` validates `callbackFunc`, `inputKind`, `statusFilter`, and `enumerationKind` (`0..=2`), allocates unique monotonic `GameInputCallbackToken` handles under `SRWLOCK`, and supports optional null `callbackToken` output pointers; `StopCallback` marks active registrations stopped while keeping them unregisterable once via `UnregisterCallback`; `SetFocusPolicy` records focus-policy flags without stub noise. Expanded `test_audio_input.exe` to cover validation, token uniqueness, stop/unregister idempotence, and focus-policy calls.
- `dxbc-accc` now reaches Windows guests as `bx_shader_bridge.dll`, the x86-64 Windows build of the same crate (#445). It exports exactly the three `bx_shader_bridge.h` entry points and needs no MinGW runtime DLL. `shader-transpiler/crates/dxbc-accc/guest/build.sh` builds the DLL and checks its exports and imports. It also builds `check_bridge.exe`, a C guest program compiled against the frozen header, which sends a real DXC SM 6.6 blob and eight synthetic containers (DXIL with and without trailing bytes, `ACCC`/`FSPX` v1 and v0, dual, legacy `SHEX`, malformed) through the DLL loaded by full path. It checks classification (exact chunk sizes, root signature flag, header digest, declared size), prepare (only the declared container is copied), free, and prints a DXIL vs. `ACCC` count. The build script always uses `<repo>/target` and rustup's toolchain, and checks the whole Export Address Table and an import allowlist. On one Apple M5 Pro with CrossOver 26.3, in a prefix and a D3DMetal bottle, it reported `dxil=3 accc_only=2 dual=1 legacy=1 invalid=2` and passed. Synthetic containers only. Staging the DLL in `build-shims`, an `abi/defs` export list, and the `d3d12_xs` PSO hook (#466) are separate changes.
- `xgameruntime.dll!QueryApiImpl` now serves offline `XGameSave` and `XPackage` as COM `IUnknown` objects under BetterXen synthetic keys (#468, not yet closed). A title linked against Microsoft's `xgameruntime.lib` does not request these keys. Every synthetic key and COM slot order now lives in `shims/xgameruntime/synthetic_keys.h`, the single place to find or replace them. Signatures, structure layouts, `E_GS_*` values and container-name rules follow the public Microsoft Learn reference.
@@ -110,6 +113,7 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- `bx-cli run` now stages `GameInput.dll` into `system32` alongside `xgameruntime.dll` and safely replaces Wine's `"Wine builtin DLL"` placeholder stub after saving a one-time backup (`.gameinput.dll.wine-builtin.bak`), while continuing to refuse modifying any non-Wine foreign DLL or symbolic link (#482). Wine pre-populates `drive_c/windows/system32/gameinput.dll` with a fake builtin PE stub whose `GameInputCreate` returns `E_NOTIMPL`, shadowing `WINEPATH` and `LOAD_LIBRARY_SEARCH_SYSTEM32` loads even when `WINEDLLOVERRIDES` specifies native-first (`=n,b`). Also added lowercase aliases (`gameinput`, `xcrdapi`, `acphal`) to `SHIM_DLL_OVERRIDES` and expanded `test_system32_staging.exe` and `stage.rs` unit tests to cover `GameInput.dll` staging and Wine stub backup/refusal rules.
- `bx-cli run` system32 shim staging (#474). Staging now records what it wrote in a `.bx-staged` manifest in the prefix's `system32` (one SHA-256 per file) and replaces only regular files that are listed there and still have the recorded hash. Any other same-named entry the bottle already had, including a symbolic link that points nowhere, or one changed since it was staged, is never modified or deleted: staging stops with an error naming it before anything is written. New files are installed without replacing anything, so an entry that appears after the checks is protected too. All temporary copies are written before the first file is put in place, and each installed file is recorded in the manifest before the next one is touched, so a failure part-way leaves the earlier files owned rather than orphaned. A byte-identical existing file is left alone and not claimed. For a named bottle, the prefix is resolved again after the run; if CrossOver launched the bottle elsewhere, the run fails only when the staged shims cannot be found with the same contents in that prefix's `system32` (a private stub of a managed bottle that links back to the managed prefix is accepted and reported). When prefix initialization uses the whole `--timeout`, the guest is no longer started and the message names initialization (exit 124). Copies staged by an earlier `bx-cli` have no manifest entry and are treated as the bottle's own, so after upgrading a changed shim needs that stale copy removed by hand once. Staged files are still not removed after a run. Covered by 15 new unit tests (32 `bx-cli` tests pass); twelve deliberate breakages each failed a test. A reviewer ran the first revision on CrossOver 26.3 with a managed-only bottle and found the false failure, dangling-link and partial-failure cases fixed here; this revision has not itself been run under CrossOver.
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
- `test_integration_boot.exe` now creates a real texture address computer, checks a two-mip layout against hand-computed values and requires the final `Release` to return 0, instead of reporting that stage as pending after a null-descriptor probe (#446).
@@ -123,6 +127,7 @@ remains unsupported.
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
- `d3dmetal-harness` runner tests no longer give a freshly written script only 300–500 ms to start (#479); both use a 2 s deadline. The kill test now also checks that the probe ran until the deadline and that its process is gone, which catches a timeout path that neither kills nor waits for the probe. It passes the PID-file path as a script argument so temporary directory names containing apostrophes work. Test-only change. Slow script start-up as the cause of the earlier failures is inferred, not measured. `output_complete` is not asserted for the killed probe, because a child spawned by a parallel test may inherit its pipe.
### Added
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
+1 -1
View File
@@ -7,4 +7,4 @@ This directory holds the **only shared interface boundary** across BetterXen's s
1. **ABI-First Changes:** If one track needs a new cross-DLL helper, config flag, or export symbol, open a small, focused `[ABI]` pull request touching only `abi/`.
2. **Zero File Collisions:** Never edit another track's implementation directory in an `[ABI]` PR. Once the `[ABI]` PR merges to `main`, both provider and consumer tracks implement in parallel.
3. **Versioned Contracts:** Increment `BX_ABI_VERSION` in `abi/include/bx_config.h` on any breaking struct or signature change.
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files.
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files. One entry is not under `shims/`: `bx_shader_bridge.def` is the export list of `bx_shader_bridge.dll`, the x86-64 Windows build of `shader-transpiler/crates/dxbc-accc` (#445). `scripts/build-shims.sh` links it into that build and verifies it with the shims (#484).
+5
View File
@@ -0,0 +1,5 @@
LIBRARY bx_shader_bridge.dll
EXPORTS
bx_shader_inspect
bx_shader_prepare_for_d3dmetal
bx_shader_free_buffer
+2 -1
View File
@@ -16,7 +16,7 @@ use bx_telemetry::summarize_jsonl;
use dxbc_accc::inspect_dxbc;
use supervise::{Outcome, Stop};
const SHIM_DLL_OVERRIDES: &str = "bx_runtime_veh,d3d12_xs,xg_xs,xmem,XCRDAPI,xgameruntime,AcpHal,xapu,chad,GameInput,\
const SHIM_DLL_OVERRIDES: &str = "bx_runtime_veh,d3d12_xs,xg_xs,xmem,xcrdapi,XCRDAPI,xgameruntime,acphal,AcpHal,xapu,chad,gameinput,GameInput,\
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";
@@ -627,6 +627,7 @@ fn cmd_run(args: &[String]) -> ExitCode {
for item in &staged {
if let stage::Staged::Copied(path)
| stage::Staged::Replaced(path)
| stage::Staged::ReplacedWineStub(path)
| stage::Staged::Unchanged(path) = item
&& let Some(name) = path.file_name()
{
+143 -6
View File
@@ -19,8 +19,32 @@ 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"];
/// Shims loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32` (or shadowed by Wine builtin stubs in
/// `system32`, which Windows searches before `WINEPATH`).
pub const SYSTEM32_SHIMS: &[&str] = &["xgameruntime.dll", "GameInput.dll"];
/// Returns true when `bytes` is a Wine `winebuild` fake-DLL placeholder stub in `system32`
/// (`"MZ"` header, `"Wine builtin DLL\0"` at DOS offset `0x40`, and `"PE\0\0"` at `e_lfanew`).
///
/// Wine populates `drive_c/windows/system32/` with fake PE stubs for built-in modules such as
/// `gameinput.dll`. Unlike user- or installer-provided native DLLs (#474), these placeholders are
/// created by Wine itself and would otherwise shadow BetterXen shims on `LOAD_LIBRARY_SEARCH_SYSTEM32`
/// loads (`fixme:ginput:GameInputCreate ... stub!`).
pub fn is_wine_builtin_dll(bytes: &[u8]) -> bool {
const WINE_SIG_OFFSET: usize = 0x40;
const WINE_SIG: &[u8] = b"Wine builtin DLL\0";
if bytes.len() < WINE_SIG_OFFSET + WINE_SIG.len() + 4 {
return false;
}
if &bytes[0..2] != b"MZ" {
return false;
}
if &bytes[WINE_SIG_OFFSET..WINE_SIG_OFFSET + WINE_SIG.len()] != WINE_SIG {
return false;
}
let pe_off = u32::from_le_bytes([bytes[0x3c], bytes[0x3d], bytes[0x3e], bytes[0x3f]]) as usize;
pe_off >= WINE_SIG_OFFSET + WINE_SIG.len() && bytes.get(pe_off..pe_off + 4) == Some(b"PE\0\0")
}
/// `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
@@ -220,6 +244,8 @@ pub enum Staged {
Copied(PathBuf),
/// An earlier copy staged by this tool, refreshed because the shim changed.
Replaced(PathBuf),
/// A Wine `"Wine builtin DLL"` placeholder stub in `system32`, backed up once and replaced.
ReplacedWineStub(PathBuf),
Unchanged(PathBuf),
/// A [`SYSTEM32_SHIMS`] file the shim folder does not have.
Absent(PathBuf),
@@ -230,6 +256,9 @@ impl Staged {
match self {
Staged::Copied(p) => format!("staged {}", p.display()),
Staged::Replaced(p) => format!("refreshed own earlier copy {}", p.display()),
Staged::ReplacedWineStub(p) => {
format!("replaced Wine builtin stub {} (backup saved)", p.display())
}
Staged::Unchanged(p) => format!("already current {}", p.display()),
Staged::Absent(p) => format!("not staged, {} not found", p.display()),
}
@@ -365,6 +394,8 @@ where
));
} else if existing.as_deref().map(sha256_hex).as_ref() == owned.get(name) {
Staged::Replaced(dst.clone())
} else if existing.as_deref().is_some_and(is_wine_builtin_dll) {
Staged::ReplacedWineStub(dst.clone())
} else {
return Err(foreign(
&dst,
@@ -415,6 +446,41 @@ where
format!("cannot install {}: {e}", dst.display())
}
}),
// Wine fake-DLL placeholder stub: verify it is still a regular Wine builtin stub,
// preserve a one-time backup `.<name>.wine-builtin.bak`, then atomically replace.
Staged::ReplacedWineStub(_) => match fs::symlink_metadata(&dst) {
Ok(meta) if meta.is_file() => match fs::read(&dst) {
Ok(now) if is_wine_builtin_dll(&now) => {
let bak = system32.join(format!(".{name}.wine-builtin.bak"));
if fs::symlink_metadata(&bak).is_err() {
let bak_tmp = system32.join(format!(
".{name}.wine-builtin.bak.{}.bx-staging",
std::process::id()
));
fs::write(&bak_tmp, &now).map_err(|e| {
let _ = fs::remove_file(&bak_tmp);
format!("cannot write backup {}: {e}", bak_tmp.display())
})?;
let bak_res = install_new(&bak_tmp, &bak, &now);
let _ = fs::remove_file(&bak_tmp);
match bak_res {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => {
return Err(format!(
"cannot save Wine stub backup {}: {e}",
bak.display()
));
}
}
}
fs::rename(&tmp, &dst)
.map_err(|e| format!("cannot replace {}: {e}", dst.display()))
}
_ => Err(foreign(&dst, name, "changed while staging")),
},
_ => Err(foreign(&dst, name, "changed while staging")),
},
// Still our own earlier copy? Then the rename replaces it in one step.
_ => match fs::read(&dst) {
Ok(now) if owned.get(name) == Some(&sha256_hex(&now)) => fs::rename(&tmp, &dst)
@@ -511,11 +577,12 @@ mod tests {
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!(staged.len(), 3, "{staged:?}");
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v1");
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), b"shim v1");
assert!(
!sys.join("unrelated.dll").exists(),
"only imported shims are staged"
"only SYSTEM32_SHIMS and imported shims are staged"
);
}
@@ -867,10 +934,15 @@ mod tests {
#[test]
fn missing_shim_is_reported_and_nothing_is_staged() {
let (t, shims, prefix) = setup("missing");
fs::remove_file(shims.join("xgameruntime.dll")).unwrap();
for name in SYSTEM32_SHIMS {
fs::remove_file(shims.join(name)).unwrap();
}
assert!(!has_system32_shims(&shims));
let sys = system32_dir(&prefix);
let expected = vec![Staged::Absent(shims.join("xgameruntime.dll"))];
let expected: Vec<Staged> = SYSTEM32_SHIMS
.iter()
.map(|name| Staged::Absent(shims.join(name)))
.collect();
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.
@@ -879,6 +951,71 @@ mod tests {
assert!(!fresh.exists());
}
fn make_fake_wine_builtin_pe() -> Vec<u8> {
let mut pe = vec![0u8; 0x100];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3c..0x40].copy_from_slice(&(0x80u32).to_le_bytes());
pe[0x40..0x51].copy_from_slice(b"Wine builtin DLL\0");
pe[0x80..0x84].copy_from_slice(b"PE\0\0");
pe
}
#[test]
fn replaces_a_wine_builtin_stub_after_saving_a_backup() {
let (_t, shims, prefix) = setup("wine-stub");
let sys = system32_dir(&prefix);
let wine_stub = make_fake_wine_builtin_pe();
assert!(is_wine_builtin_dll(&wine_stub));
fs::write(sys.join("gameinput.dll"), &wine_stub).unwrap();
let first = stage(&shims, &sys).unwrap();
assert!(first.contains(&Staged::ReplacedWineStub(sys.join("gameinput.dll"))));
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), b"shim v1");
assert_eq!(
fs::read(sys.join(".gameinput.dll.wine-builtin.bak")).unwrap(),
wine_stub
);
let owned = read_manifest(&sys).unwrap();
assert_eq!(owned.get("gameinput.dll"), Some(&sha256_hex(b"shim v1")));
// Subsequent rebuilds refresh our owned copy while keeping the original Wine backup intact.
fs::write(shims.join("GameInput.dll"), b"shim v2").unwrap();
let second = stage(&shims, &sys).unwrap();
assert!(second.contains(&Staged::Replaced(sys.join("gameinput.dll"))));
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), b"shim v2");
assert_eq!(
fs::read(sys.join(".gameinput.dll.wine-builtin.bak")).unwrap(),
wine_stub
);
}
#[test]
fn non_wine_pe_and_symlinks_to_wine_stubs_are_still_refused() {
let (t, shims, prefix) = setup("non-wine-pe");
let sys = system32_dir(&prefix);
// A regular native PE (standard DOS stub, no "Wine builtin DLL" marker) is foreign.
let mut native_pe = make_fake_wine_builtin_pe();
native_pe[0x40..0x51].copy_from_slice(b"This program can!");
assert!(!is_wine_builtin_dll(&native_pe));
fs::write(sys.join("gameinput.dll"), &native_pe).unwrap();
assert!(stage(&shims, &sys).is_err());
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), native_pe);
// A symlink pointing to a real Wine builtin stub is ALSO refused (never follow links).
fs::remove_file(sys.join("gameinput.dll")).unwrap();
let wine_target = t.0.join("wine_gameinput.dll");
fs::write(&wine_target, make_fake_wine_builtin_pe()).unwrap();
std::os::unix::fs::symlink(&wine_target, sys.join("gameinput.dll")).unwrap();
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("symbolic link"), "{err}");
assert!(
fs::symlink_metadata(sys.join("gameinput.dll"))
.unwrap()
.file_type()
.is_symlink()
);
}
#[test]
fn uninitialized_prefix_is_an_error_not_a_skip() {
let (t, shims, _prefix) = setup("uninit");
+31
View File
@@ -18,6 +18,37 @@ cmake -S "$ROOT_DIR/shims" -B "$BUILD_DIR" \
cmake --build "$BUILD_DIR" --parallel "$JOBS"
# bx_shader_bridge.dll (#445, #484): shader-transpiler/crates/dxbc-accc built for x86-64
# Windows guests, linked with abi/defs/bx_shader_bridge.def so its export list and internal
# name are the frozen ones. The verifier below then checks it like every other shim.
# Cargo and rustc are resolved through rustup when present (a cargo earlier on PATH may have
# no Windows std), and the build always goes to <repo>/target so no stale DLL is staged.
BRIDGE_TARGET=x86_64-pc-windows-gnu
if command -v rustup >/dev/null 2>&1; then
BRIDGE_CARGO="$(cd "$ROOT_DIR" && rustup which cargo)"
BRIDGE_RUSTC="$(cd "$ROOT_DIR" && rustup which rustc)"
else
BRIDGE_CARGO="$(command -v cargo || true)"
BRIDGE_RUSTC="$(command -v rustc || true)"
fi
if [ -z "$BRIDGE_CARGO" ] || [ -z "$BRIDGE_RUSTC" ]; then
echo "error: cargo/rustc not found; bx_shader_bridge.dll needs the Rust toolchain" >&2
exit 1
fi
BRIDGE_LIBDIR="$("$BRIDGE_RUSTC" --print target-libdir --target "$BRIDGE_TARGET" 2>/dev/null || true)"
if [ -z "$BRIDGE_LIBDIR" ] || ! ls "$BRIDGE_LIBDIR"/libstd-*.rlib >/dev/null 2>&1; then
echo "error: $("$BRIDGE_RUSTC" --version) has no std for $BRIDGE_TARGET, needed for bx_shader_bridge.dll" >&2
echo "error: install it with: rustup target add $BRIDGE_TARGET" >&2
exit 1
fi
echo "=== Building bx_shader_bridge.dll with $("$BRIDGE_RUSTC" --version) ==="
RUSTC="$BRIDGE_RUSTC" CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc \
"$BRIDGE_CARGO" rustc --locked --release -j "$JOBS" --manifest-path "$ROOT_DIR/Cargo.toml" \
-p dxbc-accc --lib --crate-type cdylib --target "$BRIDGE_TARGET" --target-dir "$ROOT_DIR/target" \
-- -C link-arg="$ROOT_DIR/abi/defs/bx_shader_bridge.def"
mkdir -p "$BUILD_DIR/bin"
cp "$ROOT_DIR/target/$BRIDGE_TARGET/release/dxbc_accc.dll" "$BUILD_DIR/bin/bx_shader_bridge.dll"
echo "=== Verifying built PE32+ DLL Export Directories against abi/defs/*.def ==="
python3 - "$ROOT_DIR/abi/defs" "$BUILD_DIR/bin" <<'PY'
import os
@@ -186,22 +186,70 @@ mod tests {
assert!(run.output_complete);
}
/// Timeout for the tests below whose stand-in probe has to start and print before the
/// deadline. Starting a freshly written script costs tens of milliseconds here and
/// occasionally far more, so a few hundred milliseconds made these tests fail now and then
/// (#479). They check what happens at the deadline, not how fast a script starts.
const START_MARGIN: Duration = Duration::from_secs(2);
/// Removes the pid file, and kills the recorded process if a failing test left it running.
struct PidFile(PathBuf);
impl Drop for PidFile {
fn drop(&mut self) {
if std::thread::panicking()
&& let Ok(pid) = std::fs::read_to_string(&self.0)
{
let _ = Command::new("/bin/kill").arg(pid.trim()).status();
}
let _ = std::fs::remove_file(&self.0);
}
}
#[test]
fn kills_a_probe_that_exceeds_the_timeout() {
let script = Script::new("hang", "echo started; exec sleep 30");
let pid_file = PidFile(
std::env::temp_dir().join(format!("bx-harness-probe's-{}.pid", std::process::id())),
);
let _ = std::fs::remove_file(&pid_file.0);
// Pass the path as the value of --framework. The apostrophe tests literal path handling.
// `exec` keeps the pid, so the recorded pid is the process that has to be killed.
let script = Script::new(
"hang",
"echo $$ > \"$2\" || exit 1; echo started; exec sleep 30",
);
let started = Instant::now();
let run = run_probe(&script.0, Path::new("/fw"), Duration::from_millis(300)).unwrap();
let run = run_probe(&script.0, &pid_file.0, START_MARGIN).unwrap();
let elapsed = started.elapsed();
assert!(run.status.is_none());
// Output written before the kill is kept.
assert_eq!(run.stdout, "started\n");
assert!(started.elapsed() < Duration::from_secs(10));
// The probe ran until the deadline and no longer: it was killed, not waited for.
assert!(elapsed >= START_MARGIN, "returned early after {elapsed:?}");
assert!(
elapsed < START_MARGIN + DRAIN_GRACE + Duration::from_secs(5),
"returned after {elapsed:?}"
);
// The process is gone. `output_complete` is deliberately not asserted: tests run in
// parallel, and a child spawned by another test at the wrong moment can inherit this
// probe's pipe and hold it open (seen in 2 of 200 runs).
let pid = std::fs::read_to_string(&pid_file.0).unwrap();
let alive = Command::new("/bin/kill")
.args(["-0", pid.trim()])
.stderr(Stdio::null())
.status()
.unwrap()
.success();
assert!(!alive, "probe {} survived the timeout", pid.trim());
}
/// The probe exits at once, but a background descendant inherits stdout and
/// keeps it open well past the timeout.
#[test]
fn a_descendant_holding_the_pipes_cannot_outlast_the_deadline() {
let script = Script::new("orphan", "sleep 5 & echo started");
let timeout = Duration::from_millis(500);
// The descendant has to outlive the bound asserted below by a wide margin.
let script = Script::new("orphan", "sleep 6 & echo started");
let timeout = START_MARGIN;
let started = Instant::now();
let run = run_probe(&script.0, Path::new("/fw"), timeout).unwrap();
let elapsed = started.elapsed();
@@ -1,17 +1,23 @@
/*
* #457: clean-room synthetic test for system32 shim staging by `bx-cli run`.
* #457 / #482: clean-room synthetic test for system32 shim staging by `bx-cli run`.
*
* GDK titles load the runtime with LoadLibraryExW(L"xgameruntime.dll", NULL,
* GDK titles load `xgameruntime.dll` and `GameInput.dll` with LoadLibraryExW(...,
* 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.
* In addition, Wine pre-populates `system32\gameinput.dll` with a builtin stub whose
* `GameInputCreate` returns E_NOTIMPL.
*
* `--expect-missing` is the negative control for an unstaged prefix: the load must fail.
* This test makes both loads and requires that BetterXen's shims answer them:
* - xgameruntime.dll loads from system32, exports QueryApiImpl, and matches
* LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR;
* - GameInput.dll loads from system32, exports GameInputCreate (@1 and by name), and
* GameInputCreate(&input) returns S_OK with a valid IUnknown pointer.
*
* `--expect-missing` is the negative control for an unstaged prefix: xgameruntime.dll must
* fail to load, and GameInput.dll must either fail to load or fail GameInputCreate (Wine stub).
* Exit 0 on pass, 1 on failure.
*/
#include <windows.h>
#include <unknwn.h>
#include <cstdio>
#include <cstring>
@@ -33,13 +39,13 @@ bool check(bool ok, const char* what) {
return ok;
}
bool path_in_system32(HMODULE m) {
bool path_in_system32(HMODULE m, const wchar_t* needle) {
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<wchar_t>(towlower(path[i]));
std::printf("INFO: loaded from %ls\n", path);
return std::wcsstr(path, L"\\windows\\system32\\xgameruntime.dll") != nullptr;
return std::wcsstr(path, needle) != nullptr;
}
} // namespace
@@ -49,16 +55,57 @@ int main(int argc, char** argv) {
HMODULE sys = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (expect_missing) {
check(sys == nullptr, "unstaged: LOAD_LIBRARY_SEARCH_SYSTEM32 load fails");
check(sys == nullptr, "unstaged: LOAD_LIBRARY_SEARCH_SYSTEM32 xgameruntime.dll 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);
HMODULE gi = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
bool gi_unusable = (gi == nullptr);
if (gi) {
using CreateFn = HRESULT (WINAPI*)(void**);
auto fn = reinterpret_cast<CreateFn>(
reinterpret_cast<void*>(GetProcAddress(gi, "GameInputCreate")));
void* obj = nullptr;
HRESULT hr = fn ? fn(&obj) : E_FAIL;
if (SUCCEEDED(hr) && obj) {
static_cast<IUnknown*>(obj)->Release();
} else {
gi_unusable = true;
}
FreeLibrary(gi);
}
check(gi_unusable, "unstaged: GameInput.dll is absent or Wine stub returns failure");
} else {
if (check(sys != nullptr, "LOAD_LIBRARY_SEARCH_SYSTEM32 loads xgameruntime.dll")) {
check(path_in_system32(sys, L"\\windows\\system32\\xgameruntime.dll"),
"xgameruntime.dll 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);
}
HMODULE gi = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (check(gi != nullptr, "LOAD_LIBRARY_SEARCH_SYSTEM32 loads GameInput.dll")) {
check(path_in_system32(gi, L"\\windows\\system32\\gameinput.dll"),
"GameInput.dll module path is under system32");
FARPROC ord1 = GetProcAddress(gi, MAKEINTRESOURCEA(1));
FARPROC named = GetProcAddress(gi, "GameInputCreate");
check(ord1 != nullptr && ord1 == named,
"GameInput.dll exports GameInputCreate at ordinal 1");
using CreateFn = HRESULT (WINAPI*)(void**);
auto create = reinterpret_cast<CreateFn>(reinterpret_cast<void*>(named));
void* input = nullptr;
HRESULT hr = create ? create(&input) : E_FAIL;
if (check(hr == S_OK && input != nullptr,
"GameInputCreate returns S_OK (BetterXen shim, not Wine builtin stub)")) {
static_cast<IUnknown*>(input)->Release();
}
FreeLibrary(gi);
}
}
std::printf("SUMMARY: %d checks, %d failed\n", g_checks, g_failures);
return g_failures == 0 ? 0 : 1;