Merge main and combine the timeout and staging changes in cmd_run

Resolves the conflict with #477: staged names are still collected, the
guest's share of --timeout is computed from active (non-suspended) time
and still refuses to launch when initialization used all of it, and the
diagnostics #477 added after the signal handlers are installed go
through the non-panicking helper.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
This commit is contained in:
sahib453 committed 2026-11-27 02:27:52 +05:30
commit 68d4b449f2
14 files changed
+3589 -93

No files matched your search

+17 -1
View File
@@ -10,6 +10,21 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- `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.
- **XGameSave:** provider init, containers, updates, blob writes, submit and read (both asynchronous), enumeration and the close calls. Saves are separated by SCID: each container is one file under `C:\bx_pls\<hash>\saves\<SCID hash>\`, replaced atomically on submit. A named mutex per SCID directory serializes access across threads and processes. Damaged files (truncated, trailing bytes, duplicate or NUL-bearing names) read as `ERROR_FILE_CORRUPT`, and enumeration skips them and unreadable files with a log line. Offline choices where the reference is silent (16 MiB including blob names, 256-byte blob names, no sync, retry after a failed submit) are listed in `game_save.cpp`.
- **XPackage:** the running executable's directory stands in for the installed package: a stable `BXPKG…` identifier, `XPackageKind::Game` for it, and `XPackageMount` / mount-path queries that return that directory.
- **Lifetimes:** the last uninitialize closes every XGameSave and XPackage handle and drops unconsumed results. Closing a provider closes its containers and their updates. Each handle type has its own value range. An operation queued before an uninitialize completes with `E_GAMERUNTIME_NOT_INITIALIZED` without running.
- **Async:** results of the new operations go through the existing XAsync engine, including `XAsyncGetResultSize`, cancellation and reuse rules. A cancel that arrives after an operation started no longer reports `E_ABORT` for work that was done. An unconsumed result is kept until its block is reused or the runtime is uninitialized.
- **Tests:** `tests/conformance/test_xgameruntime_saves/` covers both families through `QueryApiImpl`, with its own copies of the keys, slot numbers, structure layouts and storage format. It checks:
- name rules, the write and read round trip, and the size limits;
- SCID isolation and enumeration;
- crafted damaged files, a failed replace that keeps the old save, and a successful one that replaces the file;
- 64 threaded and 160 cross-process concurrent submits;
- uninitialize with pending work, stale handles and released memory, and a non-ASCII executable directory.
Each of eleven injected faults (non-atomic write, missing or per-process lock, ignored SCID, no-op close, lax parsing, uncounted names, retained results, stale work running, children kept after a provider close) makes it fail.
- **Not done:** validation against a caller linked to Microsoft's `xgameruntime.lib`, since these keys are BetterXen's own. `abi/defs/xgameruntime.def` is unchanged (49 exports).
- Added `docs/research/d3dmetal-gpu-limits.md` and `tests/conformance/test_d3dmetal_gpu_limits/` (#453). The fixture is an original D3D12 compute test that loads the host `d3d12.dll` directly, with four original HLSL kernels and committed DXC 1.9.2609 output (`shaders/compile.sh` regenerates them). It skips with exit 77 below shader model 6.6. Required checks:
- a kernel without `WaveSize` runs, and its lane indices form a permutation within each wave;
- a per-texel spin lock with acquire and release fences and a 1024-try cap emulates 64-bit add and max with no dropped update and exact values.
@@ -94,7 +109,8 @@ 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` signal handling (#461). The environment's `wineserver` is now stopped before anything is reported on the stop path, and those reports and the trace summary no longer use panicking print macros, so Ctrl-C through `| tee` or a closed terminal can no longer skip cleanup. A signal inherited as ignored (`nohup`, a background job of a non-interactive shell) stays ignored. SIGQUIT (Ctrl-\\) stops the guest group and the environment like SIGINT. SIGTSTP (Ctrl-Z) is passed to the guest group, which is continued when `bx-cli` is, and suspended time does not count against `--timeout`. The cleanup `wineserver -k`/`-w` run in their own process group so a second Ctrl-C cannot kill them. The trace summary covers only what this run appended to the log; a log replaced or rewritten during the run (recognized by file identity and by the bytes before the old end, not by size) is summarized in full. A pause during prefix initialization is not charged to the guest's share of `--timeout` either. `THIRD_PARTY_NOTICES.md` no longer claims zero crates.io dependencies and now includes the `libc` MIT text. The stop messages changed from "stopping the environment" to "stopped the environment" because they are printed afterwards. Covered by 10 new unit tests with stub launchers and servers (27 `bx-cli` tests pass); each fix was removed in turn and its test failed. A reviewer confirmed Ctrl-C through `| tee` on a real terminal under CrossOver 26.3. The author then ran seven scenarios under CrossOver Preview build 20261006 (Ctrl-C through `tee`, an inherited-ignored SIGHUP, Ctrl-\\, Ctrl-Z and continue, repeated Ctrl-C during cleanup, a pause during prefix setup, a log replaced mid-run) with signals sent to the process group rather than typed, using a build that differs only in where it looks for CrossOver; each showed the old behaviour before the change and the fixed behaviour after. Not confirmed with real key presses, and not on CrossOver 26.3 for anything but the first. The same pattern in the unmerged #425 is not touched.
- `bx-cli run` signal handling (#461). The environment's `wineserver` is now stopped before anything is reported on the stop path, and those reports and the trace summary no longer use panicking print macros, so Ctrl-C through `| tee` or a closed terminal can no longer skip cleanup. A signal inherited as ignored (`nohup`, a background job of a non-interactive shell) stays ignored. SIGQUIT (Ctrl-\\) stops the guest group and the environment like SIGINT. SIGTSTP (Ctrl-Z) is passed to the guest group, which is continued when `bx-cli` is, and suspended time does not count against `--timeout`. The cleanup `wineserver -k`/`-w` run in their own process group so a second Ctrl-C cannot kill them. The trace summary covers only what this run appended to the log; a log replaced or rewritten during the run (recognized by file identity and by the bytes before the old end, not by size) is summarized in full. A pause during prefix initialization is not charged to the guest's share of `--timeout` either. `THIRD_PARTY_NOTICES.md` no longer claims zero crates.io dependencies and now includes the `libc` MIT text. The stop messages changed from "stopping the environment" to "stopped the environment" because they are printed afterwards. Covered by 10 new unit tests with stub launchers and servers; each fix was removed in turn and its test failed. A reviewer confirmed Ctrl-C through `| tee` on a real terminal under CrossOver 26.3. The author then ran seven scenarios under CrossOver Preview build 20261006 (Ctrl-C through `tee`, an inherited-ignored SIGHUP, Ctrl-\\, Ctrl-Z and continue, repeated Ctrl-C during cleanup, a pause during prefix setup, a log replaced mid-run) with signals sent to the process group rather than typed, using a build that differs only in where it looks for CrossOver; each showed the old behaviour before the change and the fixed behaviour after. Not confirmed with real key presses, and not on CrossOver 26.3 for anything but the first. The same pattern in the unmerged #425 is not touched.
- `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).
- `bx-cli trace` reports the highest sampled CLWB total as a lower bound, labels counterless CLWB records as samples, and lists unhandled exceptions with their code, module base, RVA, and RIP (#438).
+158 -27
View File
@@ -426,6 +426,45 @@ where
Ok(prefixes)
}
/// The prefix a named bottle resolves to now, if that is no longer `staged_prefix`.
///
/// For a managed-only bottle CrossOver's `bin/wine` may create a private stub bottle and launch
/// the guest there. Shims staged before launch then sit in a prefix the guest never used; this
/// detects that so the run can say so instead of reporting "staged" (#474).
fn staging_prefix_mismatch<F>(
staged_prefix: &Path,
bottle: Option<&str>,
mut re_resolve: F,
) -> Result<Option<PathBuf>, String>
where
F: FnMut(&str) -> Result<PathBuf, String>,
{
let Some(name) = bottle else {
return Ok(None);
};
let current = re_resolve(name)?;
let same = |a: &Path, b: &Path| {
a == b || matches!((fs::canonicalize(a), fs::canonicalize(b)), (Ok(x), Ok(y)) if x == y)
};
Ok((!same(&current, staged_prefix)).then_some(current))
}
/// What is left of `--timeout` for the guest after initialization took `used`. `Ok(None)` means
/// no limit. An error means initialization used all of it: the guest must not be started only to
/// be reported as timed out, as if it had hung (#474).
fn guest_time_left(timeout: Option<Duration>, used: Duration) -> Result<Option<Duration>, String> {
match timeout {
None => Ok(None),
Some(limit) if used < limit => Ok(Some(limit - used)),
Some(limit) => Err(format!(
"initialization (prefix setup and shim staging) took {:.1}s and used the whole \
--timeout of {:.1}s; the guest was not started",
used.as_secs_f64(),
limit.as_secs_f64()
)),
}
}
/// `bin/wine` deletes an inherited `WINEDLLOVERRIDES` and applies the bottle's
/// `[EnvironmentVariables]` over what it is given, so bottle mode passes both as options.
fn bottle_options(backend: Option<&str>) -> Vec<String> {
@@ -585,14 +624,10 @@ fn appended_since<'a>(bytes: &'a [u8], identity: (u64, u64), before: Option<&Log
appended.unwrap_or(bytes)
}
/// What is left of `--timeout` after `elapsed` wall-clock time, of which `suspended` was spent
/// stopped by Ctrl-Z. Suspended time is not charged, whichever phase of the run it fell in.
fn remaining_budget(
timeout: Option<Duration>,
elapsed: Duration,
suspended: Duration,
) -> Option<Duration> {
timeout.map(|limit| limit.saturating_sub(elapsed.saturating_sub(suspended)))
/// The part of `elapsed` wall-clock time that counts against `--timeout`: everything except the
/// `suspended` time spent stopped by Ctrl-Z, whichever phase of the run that fell in.
fn active_time(elapsed: Duration, suspended: Duration) -> Duration {
elapsed.saturating_sub(suspended)
}
fn cmd_run(args: &[String]) -> ExitCode {
@@ -679,14 +714,22 @@ fn cmd_run(args: &[String]) -> ExitCode {
}
}
}
let mut staged_names: Vec<String> = Vec::new();
match stage::stage_system32(&abs_shims, &system32) {
Ok(staged) => {
for item in &staged {
if let stage::Staged::Copied(path)
| stage::Staged::Replaced(path)
| stage::Staged::Unchanged(path) = item
&& let Some(name) = path.file_name()
{
staged_names.push(name.to_string_lossy().into_owned());
}
diag(format_args!("bx-cli: {}", item.describe()));
}
}
Err(e) => {
let hint = if bottle.is_some() {
let hint = if bottle.is_some() && !system32.is_dir() {
" (start the bottle once so CrossOver creates it)"
} else {
""
@@ -737,7 +780,14 @@ fn cmd_run(args: &[String]) -> ExitCode {
// `--timeout` bounds the whole run, including any prefix initialization above, but not
// time the run spent suspended in either phase.
let remaining = remaining_budget(timeout, started.elapsed(), supervise::suspended_time());
let active = active_time(started.elapsed(), supervise::suspended_time());
let remaining = match guest_time_left(timeout, active) {
Ok(remaining) => remaining,
Err(e) => {
diag(format_args!("timed out during initialization: {e}"));
return ExitCode::from(124);
}
};
let outcome = supervise::supervise(cmd, remaining, supervise::received_signal);
let code = match &outcome {
Ok(outcome) => outcome.exit_code(),
@@ -780,8 +830,54 @@ fn cmd_run(args: &[String]) -> ExitCode {
);
}
}
// The reason for the stop is kept; a failed cleanup only turns success into failure.
ExitCode::from(if cleanup_failed { code.max(1) } else { code })
// #474: the shims were staged into the prefix resolved before launch. If CrossOver launched
// the bottle from a different prefix that does not expose them, the guest never saw them,
// and the run must not pass quietly. A different prefix alone is not a failure: a private
// stub of a managed bottle links its system32 entries back to the managed prefix.
let mut staged_elsewhere = false;
if !staged_names.is_empty() {
match staging_prefix_mismatch(&environment_dir, bottle.as_deref(), |name| {
resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env)
}) {
Ok(None) => {}
Ok(Some(launched)) => {
let missing = stage::shims_not_visible_in(
&system32,
&stage::system32_dir(&launched),
&staged_names,
);
if missing.is_empty() {
diag(format_args!(
"bx-cli: bottle launched in {}; the shims staged in {} are visible there",
launched.display(),
environment_dir.display()
));
} else {
staged_elsewhere = true;
diag(format_args!(
"error: system32 shims were staged in {} but CrossOver launched the \
bottle in {}, where {} cannot be found as staged; the guest did not \
see them. Run again: staging will now use the prefix the bottle \
launches in",
environment_dir.display(),
launched.display(),
missing.join(", ")
));
}
}
Err(e) => diag(format_args!(
"warning: cannot confirm which prefix the bottle launched in, so the staged \
system32 shims may not have been used: {e}"
)),
}
}
// The reason for the stop is kept; a failed cleanup or misplaced staging only turns success
// into failure.
ExitCode::from(if cleanup_failed || staged_elsewhere {
code.max(1)
} else {
code
})
}
fn cmd_shader(path: &str) -> ExitCode {
@@ -990,28 +1086,63 @@ mod tests {
#[test]
fn a_pause_in_an_earlier_phase_is_not_charged_to_the_guest() {
let limit = Some(Duration::from_secs(2));
let ms = Duration::from_millis;
// As reviewed: paused 2.5 s during wineboot with --timeout 2, 0.3 s actually running.
assert_eq!(
remaining_budget(
limit,
Duration::from_millis(2800),
Duration::from_millis(2500)
),
Some(Duration::from_millis(1700))
guest_time_left(limit, active_time(ms(2800), ms(2500))),
Ok(Some(ms(1700)))
);
// Without a pause the wall clock counts in full, down to zero.
// Without a pause the wall clock counts in full.
assert_eq!(
remaining_budget(limit, Duration::from_millis(500), Duration::ZERO),
Some(Duration::from_millis(1500))
guest_time_left(limit, active_time(ms(500), Duration::ZERO)),
Ok(Some(ms(1500)))
);
// Initialization that really ran for the whole timeout still stops the launch.
assert!(guest_time_left(limit, active_time(ms(5000), ms(2500))).is_err());
// More suspension than elapsed time cannot go negative.
assert_eq!(active_time(ms(100), ms(900)), Duration::ZERO);
}
#[test]
fn staging_into_a_prefix_the_bottle_did_not_launch_in_is_reported() {
let resolved_before = Path::new("/bottles/managed/corp");
let stub = PathBuf::from("/bottles/private/corp");
// CrossOver created a private stub during launch: the bottle now resolves there.
let moved = staging_prefix_mismatch(resolved_before, Some("corp"), |name| {
assert_eq!(name, "corp");
Ok(stub.clone())
});
assert_eq!(moved, Ok(Some(stub)));
// The usual case: the bottle still resolves to where the shims went.
let same = staging_prefix_mismatch(resolved_before, Some("corp"), |_| {
Ok(resolved_before.to_path_buf())
});
assert_eq!(same, Ok(None));
// A bare --prefix is launched exactly where it was staged; nothing is re-resolved.
let bare = staging_prefix_mismatch(resolved_before, None, |_| {
panic!("a bare prefix must not be re-resolved")
});
assert_eq!(bare, Ok(None));
// A resolver failure is passed on, not mistaken for a match.
let failed = staging_prefix_mismatch(resolved_before, Some("corp"), |_| {
Err("cannot locate".to_string())
});
assert_eq!(failed, Err("cannot locate".to_string()));
}
#[test]
fn the_guest_is_not_started_when_initialization_used_the_whole_timeout() {
let limit = Some(Duration::from_secs(30));
assert_eq!(guest_time_left(None, Duration::from_secs(999)), Ok(None));
assert_eq!(
remaining_budget(limit, Duration::from_secs(5), Duration::ZERO),
Some(Duration::ZERO)
);
assert_eq!(
remaining_budget(None, Duration::from_secs(5), Duration::ZERO),
None
guest_time_left(limit, Duration::from_secs(12)),
Ok(Some(Duration::from_secs(18)))
);
for used in [Duration::from_secs(30), Duration::from_secs(45)] {
let err = guest_time_left(limit, used).unwrap_err();
assert!(err.contains("initialization"), "{err}");
assert!(err.contains("guest was not started"), "{err}");
}
}
fn args(list: &[&str]) -> Vec<String> {
+594 -22
View File
@@ -8,8 +8,13 @@
//! 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.
//!
//! #474: a bottle's `system32` is not ours. Staging records what it wrote in a `.bx-staged`
//! manifest there (one SHA-256 per file) and afterwards replaces only files that are listed and
//! still have the recorded hash. A file of the same name that the bottle already had, or that
//! was changed since, is never modified: staging stops with an error that names it.
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
@@ -74,10 +79,146 @@ pub fn system32_dir(prefix: &Path) -> PathBuf {
prefix.join("drive_c").join("windows").join("system32")
}
/// SHA-256 (FIPS 180-4), used only to recognize files this tool staged earlier.
pub fn sha256_hex(data: &[u8]) -> String {
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2,
];
let mut h: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
];
let mut message = data.to_vec();
message.push(0x80);
while message.len() % 64 != 56 {
message.push(0);
}
message.extend_from_slice(&((data.len() as u64).wrapping_mul(8)).to_be_bytes());
for block in message.chunks_exact(64) {
let mut w = [0u32; 64];
for (i, word) in block.chunks_exact(4).enumerate() {
w[i] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
for i in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ (!e & g);
let t1 = hh
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(K[i])
.wrapping_add(w[i]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let t2 = s0.wrapping_add(maj);
hh = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
for (state, value) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
*state = state.wrapping_add(value);
}
}
h.iter().map(|word| format!("{word:08x}")).collect()
}
/// Name of the ownership record kept in `system32`.
pub const MANIFEST_NAME: &str = ".bx-staged";
/// The files this tool staged into a `system32`, as lowercase name -> SHA-256 of what it wrote.
///
/// A file is BetterXen's to refresh only while it is listed here and still has the recorded
/// hash. Anything else in `system32` belongs to the bottle and is never modified (#474).
fn read_manifest(system32: &Path) -> Result<BTreeMap<String, String>, String> {
let path = system32.join(MANIFEST_NAME);
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
};
let mut owned = BTreeMap::new();
for line in text.lines() {
// "<64 hex digits> <name>", as `shasum -a 256` prints. Other lines are ignored, which
// only ever makes a file look foreign.
if let Some((hash, name)) = line.split_once(" ")
&& hash.len() == 64
&& hash.bytes().all(|b| b.is_ascii_hexdigit())
&& !name.is_empty()
{
owned.insert(name.to_ascii_lowercase(), hash.to_ascii_lowercase());
}
}
Ok(owned)
}
fn write_manifest(system32: &Path, owned: &BTreeMap<String, String>) -> Result<(), String> {
let mut text = String::from(
"# Files staged by bx-cli (sha256, two spaces, name). bx-cli replaces only these.\n",
);
for (name, hash) in owned {
text.push_str(&format!("{hash} {name}\n"));
}
let path = system32.join(MANIFEST_NAME);
let tmp = system32.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
fs::write(&tmp, text).map_err(|e| {
let _ = fs::remove_file(&tmp);
format!("cannot write {}: {e}", tmp.display())
})?;
fs::rename(&tmp, &path).map_err(|e| {
let _ = fs::remove_file(&tmp);
format!("cannot replace {}: {e}", path.display())
})
}
/// Names from `names` that a guest in `launched_system32` would not find as staged: the entry
/// there is missing or, read through any link, does not have the bytes of the staged copy in
/// `staged_system32`.
///
/// CrossOver may launch a managed bottle from a private stub whose `system32` links back to the
/// managed prefix, so a different directory alone does not mean the shims were missed (#474).
pub fn shims_not_visible_in(
staged_system32: &Path,
launched_system32: &Path,
names: &[String],
) -> Vec<String> {
names
.iter()
.filter(|name| {
let staged = fs::read(staged_system32.join(name));
let seen = fs::read(launched_system32.join(name));
!matches!((staged, seen), (Ok(a), Ok(b)) if a == b)
})
.cloned()
.collect()
}
/// What staging did to one file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Staged {
Copied(PathBuf),
/// An earlier copy staged by this tool, refreshed because the shim changed.
Replaced(PathBuf),
Unchanged(PathBuf),
/// A [`SYSTEM32_SHIMS`] file the shim folder does not have.
@@ -88,7 +229,7 @@ impl Staged {
pub fn describe(&self) -> String {
match self {
Staged::Copied(p) => format!("staged {}", p.display()),
Staged::Replaced(p) => format!("replaced {}", p.display()),
Staged::Replaced(p) => format!("refreshed own earlier copy {}", p.display()),
Staged::Unchanged(p) => format!("already current {}", p.display()),
Staged::Absent(p) => format!("not staged, {} not found", p.display()),
}
@@ -106,7 +247,11 @@ pub fn has_system32_shims(shims_dir: &Path) -> bool {
/// `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.
/// left alone. A different one is replaced only if this tool staged it and it is unchanged since
/// (see [`MANIFEST_NAME`]); any other existing entry, including a symbolic link that points
/// nowhere, is an error and nothing is written, so a DLL the bottle already had is never
/// modified or deleted. New files are installed without replacing anything, and each installed
/// file is recorded before the next one is touched. Nothing outside `system32` is written.
pub fn stage_system32(shims_dir: &Path, system32: &Path) -> Result<Vec<Staged>, String> {
stage_system32_with(shims_dir, system32, pe_imports)
}
@@ -114,10 +259,44 @@ pub fn stage_system32(shims_dir: &Path, system32: &Path) -> Result<Vec<Staged>,
fn stage_system32_with<I>(
shims_dir: &Path,
system32: &Path,
mut imports_of: I,
imports_of: I,
) -> Result<Vec<Staged>, String>
where
I: FnMut(&Path) -> Result<Vec<String>, String>,
{
stage_system32_hooked(shims_dir, system32, imports_of, |_| Ok(()))
}
/// Puts `bytes` at `dst` only if nothing is there, not even a dangling symbolic link.
///
/// `tmp` already holds the bytes. A hard link either creates `dst` whole or fails because the
/// name is taken; where links are not supported the file is created exclusively instead.
fn install_new(tmp: &Path, dst: &Path, bytes: &[u8]) -> io::Result<()> {
match fs::hard_link(tmp, dst) {
Ok(()) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Err(e),
Err(_) => {
use std::io::Write as _;
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(dst)?;
file.write_all(bytes)
}
}
}
/// [`stage_system32_with`] with a hook called for each file just before it is put in place, so
/// tests can make something go wrong between the checks and the installation.
fn stage_system32_hooked<I, H>(
shims_dir: &Path,
system32: &Path,
mut imports_of: I,
mut before_publish: H,
) -> Result<Vec<Staged>, String>
where
I: FnMut(&Path) -> Result<Vec<String>, String>,
H: FnMut(&str) -> Result<(), String>,
{
let (roots, absent): (Vec<&str>, Vec<&str>) = SYSTEM32_SHIMS
.iter()
@@ -147,29 +326,112 @@ where
)),
},
)?;
let mut owned = read_manifest(system32)?;
let foreign = |dst: &Path, name: &str, what: &str| {
format!(
"{} {what}; it is left untouched. Use a bottle or prefix without its own {name}, \
or move that entry aside yourself, then run again",
dst.display()
)
};
// 1. Decide everything before writing anything, so a foreign entry stops the run with
// `system32` exactly as it was.
let mut plan = Vec::new();
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()),
// The directory entry itself is inspected, without following links: a dangling
// symbolic link has no contents to read but is still the bottle's entry.
let result = match fs::symlink_metadata(&dst) {
Err(e) if e.kind() == io::ErrorKind::NotFound => Staged::Copied(dst.clone()),
Err(e) => return Err(format!("cannot read {}: {e}", dst.display())),
Err(e) => return Err(format!("cannot inspect {}: {e}", dst.display())),
Ok(meta) => {
let existing = match fs::read(&dst) {
Ok(existing) => Some(existing),
Err(_) if !meta.is_file() => None,
Err(e) => return Err(format!("cannot read {}: {e}", dst.display())),
};
if existing.as_deref() == Some(bytes.as_slice()) {
Staged::Unchanged(dst.clone())
} else if !meta.is_file() {
// bx-cli only ever writes regular files, so a link or anything else here
// was not staged by it.
return Err(foreign(
&dst,
name,
"already exists and is not a regular file (for example a symbolic link)",
));
} else if existing.as_deref().map(sha256_hex).as_ref() == owned.get(name) {
Staged::Replaced(dst.clone())
} else {
return Err(foreign(
&dst,
name,
"already exists and was not staged by bx-cli (or was changed since)",
));
}
}
};
plan.push((name, bytes, dst, result));
}
// 2. Write every new file beside its target first. A failure here publishes nothing.
let tmp_of = |name: &str| system32.join(format!(".{name}.{}.bx-staging", std::process::id()));
let pending: Vec<PathBuf> = plan
.iter()
.filter(|(_, _, _, result)| !matches!(result, Staged::Unchanged(_)))
.map(|(name, _, _, _)| tmp_of(name))
.collect();
let discard = |tmps: &[PathBuf]| {
for tmp in tmps {
let _ = fs::remove_file(tmp);
}
};
for (name, bytes, _, result) in &plan {
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())
})?;
let tmp = tmp_of(name);
if let Err(e) = fs::write(&tmp, bytes) {
discard(&pending);
return Err(format!("cannot write {}: {e}", tmp.display()));
}
}
}
// 3. Put the files in place one at a time, recording each in the manifest as soon as it is
// there. If a later file fails, the earlier ones are installed and owned, not orphaned.
for (name, bytes, dst, result) in plan {
if !matches!(result, Staged::Unchanged(_)) {
let tmp = tmp_of(name);
let published = before_publish(name).and_then(|()| match result {
// Nothing was there at step 1; refuse to replace whatever appeared since.
Staged::Copied(_) => install_new(&tmp, &dst, &bytes).map_err(|e| {
if e.kind() == io::ErrorKind::AlreadyExists {
foreign(
&dst,
name,
"appeared while staging and was not staged by bx-cli",
)
} else {
format!("cannot install {}: {e}", dst.display())
}
}),
// 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)
.map_err(|e| format!("cannot replace {}: {e}", dst.display())),
_ => Err(foreign(&dst, name, "changed while staging")),
},
});
if let Err(e) = published {
discard(&pending);
return Err(e);
}
let _ = fs::remove_file(&tmp);
owned.insert(name.clone(), sha256_hex(&bytes));
if let Err(e) = write_manifest(system32, &owned) {
discard(&pending);
return Err(e);
}
}
staged.push(result);
}
@@ -277,13 +539,144 @@ mod tests {
}
#[test]
fn replaces_an_older_copy() {
fn sha256_matches_the_published_test_vectors() {
// FIPS 180-4 / NIST example values.
assert_eq!(
sha256_hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(
sha256_hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(
sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
);
// Padding boundaries (one block, two blocks, exactly one block of data); expected
// values computed independently with Python's hashlib.
for (len, expected) in [
(
55usize,
"9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318",
),
(
56usize,
"b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a",
),
(
64usize,
"ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb",
),
(
1000usize,
"41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3",
),
] {
assert_eq!(sha256_hex(&vec![b'a'; len]), expected, "{len} bytes");
}
}
/// Every regular file in `dir` with its bytes, for before/after comparison.
fn snapshot(dir: &Path) -> BTreeMap<String, Vec<u8>> {
fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap())
.map(|e| {
(
e.file_name().to_string_lossy().into_owned(),
fs::read(e.path()).unwrap(),
)
})
.collect()
}
#[test]
fn a_foreign_file_with_different_bytes_is_never_modified() {
let (_t, shims, prefix) = setup("foreign");
let sys = system32_dir(&prefix);
// The bottle's own runtime, put there by something other than bx-cli.
fs::write(sys.join("xgameruntime.dll"), b"the bottle's own runtime").unwrap();
let before = snapshot(&sys);
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("xgameruntime.dll"), "{err}");
assert!(err.contains("not staged by bx-cli"), "{err}");
// Nothing changed: not the foreign file, no dependency copied beside it, no manifest.
assert_eq!(snapshot(&sys), before);
// Still refused on the next run.
assert!(stage(&shims, &sys).is_err());
assert_eq!(snapshot(&sys), before);
}
#[test]
fn a_foreign_dependency_blocks_staging_before_anything_is_written() {
let (_t, shims, prefix) = setup("foreign-dep");
let sys = system32_dir(&prefix);
fs::write(sys.join("bx_runtime_veh.dll"), b"someone else's file").unwrap();
let before = snapshot(&sys);
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("bx_runtime_veh.dll"), "{err}");
assert_eq!(
snapshot(&sys),
before,
"xgameruntime.dll must not be staged either"
);
}
#[test]
fn an_owned_copy_changed_by_someone_else_is_not_replaced() {
let (_t, shims, prefix) = setup("tampered");
let sys = system32_dir(&prefix);
stage(&shims, &sys).unwrap();
// Something else (an installer) replaced our copy after we staged it.
fs::write(sys.join("xgameruntime.dll"), b"installed over ours").unwrap();
fs::write(shims.join("xgameruntime.dll"), b"shim v2").unwrap();
let before = snapshot(&sys);
assert!(stage(&shims, &sys).is_err());
assert_eq!(snapshot(&sys), before);
}
#[test]
fn an_identical_foreign_file_is_left_alone_and_not_claimed() {
let (_t, shims, prefix) = setup("identical");
let sys = system32_dir(&prefix);
fs::write(sys.join("xgameruntime.dll"), b"shim v1").unwrap();
let staged = stage(&shims, &sys).unwrap();
assert!(staged.contains(&Staged::Unchanged(sys.join("xgameruntime.dll"))));
assert!(
!read_manifest(&sys)
.unwrap()
.contains_key("xgameruntime.dll")
);
// Not ours, so a later shim change must not replace it.
fs::write(shims.join("xgameruntime.dll"), b"shim v2").unwrap();
assert!(stage(&shims, &sys).is_err());
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v1");
}
#[test]
fn refreshes_a_stale_copy_it_staged_itself() {
let (_t, shims, prefix) = setup("replace");
let sys = system32_dir(&prefix);
fs::write(sys.join("xgameruntime.dll"), b"old").unwrap();
let first = stage(&shims, &sys).unwrap();
assert!(first.iter().all(|s| matches!(s, Staged::Copied(_))));
let manifest = fs::read_to_string(sys.join(MANIFEST_NAME)).unwrap();
assert!(
manifest.contains(&format!("{} xgameruntime.dll\n", sha256_hex(b"shim v1"))),
"{manifest}"
);
// The shim is rebuilt; the copy in system32 is now stale but still ours.
fs::write(shims.join("xgameruntime.dll"), b"shim v2").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");
assert!(staged.contains(&Staged::Unchanged(sys.join("bx_runtime_veh.dll"))));
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v2");
let owned = read_manifest(&sys).unwrap();
assert_eq!(owned.get("xgameruntime.dll"), Some(&sha256_hex(b"shim v2")));
assert_eq!(
owned.get("bx_runtime_veh.dll"),
Some(&sha256_hex(b"veh v1"))
);
let leftovers: Vec<_> = fs::read_dir(&sys)
.unwrap()
.filter_map(|e| e.ok())
@@ -292,6 +685,185 @@ mod tests {
assert!(leftovers.is_empty(), "temporary file left behind");
}
#[test]
fn a_dangling_symlink_is_a_foreign_entry_and_stays() {
let (_t, shims, prefix) = setup("dangling");
let sys = system32_dir(&prefix);
let link = sys.join("xgameruntime.dll");
std::os::unix::fs::symlink(sys.join("no-such-target.dll"), &link).unwrap();
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("xgameruntime.dll"), "{err}");
assert!(err.contains("symbolic link"), "{err}");
// Still the same dangling link, and nothing else was staged beside it.
assert_eq!(
fs::read_link(&link).unwrap(),
sys.join("no-such-target.dll")
);
assert!(!sys.join("bx_runtime_veh.dll").exists());
assert!(!sys.join(MANIFEST_NAME).exists());
}
#[test]
fn a_symlink_is_never_replaced_whatever_it_points_to() {
let (t, shims, prefix) = setup("symlink");
let sys = system32_dir(&prefix);
let link = sys.join("xgameruntime.dll");
// Pointing at a file with other contents: foreign, and the target is not written to.
let target = t.0.join("elsewhere.dll");
fs::write(&target, b"the bottle's own runtime").unwrap();
std::os::unix::fs::symlink(&target, &link).unwrap();
assert!(stage(&shims, &sys).is_err());
assert_eq!(fs::read(&target).unwrap(), b"the bottle's own runtime");
assert_eq!(fs::read_link(&link).unwrap(), target);
// Pointing at identical contents: already current, left as a link and not claimed.
fs::write(&target, b"shim v1").unwrap();
let staged = stage(&shims, &sys).unwrap();
assert!(staged.contains(&Staged::Unchanged(link.clone())));
assert_eq!(fs::read_link(&link).unwrap(), target);
assert!(
!read_manifest(&sys)
.unwrap()
.contains_key("xgameruntime.dll")
);
}
#[test]
fn an_entry_that_appears_after_the_checks_is_not_replaced() {
let (_t, shims, prefix) = setup("late");
let sys = system32_dir(&prefix);
let dst = sys.join("xgameruntime.dll");
let late = dst.clone();
let err = stage_system32_hooked(&shims, &sys, fake_imports, |name| {
if name == "xgameruntime.dll" {
fs::write(&late, b"installed meanwhile").unwrap();
}
Ok(())
})
.unwrap_err();
assert!(err.contains("appeared while staging"), "{err}");
assert_eq!(fs::read(&dst).unwrap(), b"installed meanwhile");
assert!(
!read_manifest(&sys)
.unwrap()
.contains_key("xgameruntime.dll")
);
assert!(no_temporary_files(&sys));
}
#[test]
fn a_later_failure_leaves_earlier_copies_installed_and_owned() {
let (_t, shims, prefix) = setup("partial");
let sys = system32_dir(&prefix);
// Files are installed in name order: the VEH logger first, then the runtime.
let err = stage_system32_hooked(&shims, &sys, fake_imports, |name| {
if name == "xgameruntime.dll" {
return Err("disk full".to_string());
}
Ok(())
})
.unwrap_err();
assert_eq!(err, "disk full");
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v1");
assert!(!sys.join("xgameruntime.dll").exists());
let owned = read_manifest(&sys).unwrap();
assert_eq!(
owned.get("bx_runtime_veh.dll"),
Some(&sha256_hex(b"veh v1"))
);
assert!(no_temporary_files(&sys));
// The retry completes, and the first file is still ours: a later update refreshes it.
let retry = stage(&shims, &sys).unwrap();
assert!(retry.contains(&Staged::Unchanged(sys.join("bx_runtime_veh.dll"))));
assert!(retry.contains(&Staged::Copied(sys.join("xgameruntime.dll"))));
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
let update = stage(&shims, &sys).unwrap();
assert!(update.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v2");
}
#[test]
fn a_failed_temporary_write_publishes_nothing() {
let (_t, shims, prefix) = setup("prepare");
let sys = system32_dir(&prefix);
// A directory where the second file's temporary copy has to go makes that write fail.
let obstacle = sys.join(format!(
".xgameruntime.dll.{}.bx-staging",
std::process::id()
));
fs::create_dir(&obstacle).unwrap();
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("cannot write"), "{err}");
assert!(
!sys.join("bx_runtime_veh.dll").exists(),
"first file was published"
);
assert!(!sys.join("xgameruntime.dll").exists());
assert!(!sys.join(MANIFEST_NAME).exists());
fs::remove_dir(&obstacle).unwrap();
assert!(
stage(&shims, &sys)
.unwrap()
.iter()
.all(|s| matches!(s, Staged::Copied(_)))
);
}
#[test]
fn staged_shims_reached_through_a_stub_prefix_count_as_visible() {
let (t, shims, prefix) = setup("visible");
let sys = system32_dir(&prefix);
stage(&shims, &sys).unwrap();
let names = vec![
"bx_runtime_veh.dll".to_string(),
"xgameruntime.dll".to_string(),
];
// A private stub whose system32 links back to the managed prefix, as CrossOver creates.
let stub = system32_dir(&t.0.join("stub"));
fs::create_dir_all(&stub).unwrap();
for name in &names {
std::os::unix::fs::symlink(sys.join(name), stub.join(name)).unwrap();
}
assert!(shims_not_visible_in(&sys, &stub, &names).is_empty());
// A stub that really lacks one shim, or has other bytes under that name.
fs::remove_file(stub.join("xgameruntime.dll")).unwrap();
assert_eq!(
shims_not_visible_in(&sys, &stub, &names),
vec!["xgameruntime.dll"]
);
fs::write(stub.join("xgameruntime.dll"), b"something else").unwrap();
assert_eq!(
shims_not_visible_in(&sys, &stub, &names),
vec!["xgameruntime.dll"]
);
// An empty stub sees none of them.
let empty = system32_dir(&t.0.join("empty"));
fs::create_dir_all(&empty).unwrap();
assert_eq!(shims_not_visible_in(&sys, &empty, &names), names);
}
fn no_temporary_files(sys: &Path) -> bool {
fs::read_dir(sys)
.unwrap()
.filter_map(|e| e.ok())
.all(|e| !e.file_name().to_string_lossy().contains("bx-staging"))
}
#[test]
fn a_damaged_manifest_only_makes_files_look_foreign() {
let (_t, shims, prefix) = setup("manifest");
let sys = system32_dir(&prefix);
stage(&shims, &sys).unwrap();
fs::write(
sys.join(MANIFEST_NAME),
"not a manifest\nabc xgameruntime.dll\n",
)
.unwrap();
assert!(read_manifest(&sys).unwrap().is_empty());
fs::write(shims.join("xgameruntime.dll"), b"shim v2").unwrap();
assert!(stage(&shims, &sys).is_err());
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v1");
}
#[test]
fn missing_shim_is_reported_and_nothing_is_staged() {
let (t, shims, prefix) = setup("missing");
@@ -0,0 +1,59 @@
# dxbc-accc
Classifies D3D shader containers (`DXBC` with `DXIL`, legacy `SHDR`/`SHEX`, and `ACCC` chunks carrying BetterXen's synthetic `FSPX` table) and exposes the C ABI in [`abi/include/bx_shader_bridge.h`](../../../abi/include/bx_shader_bridge.h): `bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal` and `bx_shader_free_buffer`.
## Guest access: `bx_shader_bridge.dll` (#445)
The shims that see shader bytecode (`d3d12_xs.dll`) are x86-64 Windows PE32+ DLLs running inside CrossOver. They cannot load the arm64 macOS library that `cargo build` produces on the host. The bridge reaches guests as a **Windows build of this same crate**, with no second implementation:
- **Build:** `cargo build --target x86_64-pc-windows-gnu` turns the crate's `cdylib` into a PE32+ DLL, published as `bx_shader_bridge.dll`. Its Export Address Table holds exactly the three header functions as direct RVAs. It imports only Windows system DLLs that Wine provides, so no MinGW runtime DLL. `guest/build.sh` enforces both. The allowlist is `KERNEL32`, `ntdll`, `bcryptprimitives`, `USERENV`, `WS2_32` and the `api-ms-win-crt-*` / `api-ms-win-core-*` sets.
- **Callers:** a shim loads the bridge at run time with `GetProcAddress`, so a missing bridge is a logged condition, not a load failure of the shim.
- **Full path:** it must load the bridge by **full path from its own directory**. That is `GetModuleFileNameW` of the shim's own module (for example via `GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, ...)`), plus `bx_shader_bridge.dll`, loaded with `LoadLibraryExW(..., LOAD_WITH_ALTERED_SEARCH_PATH)`.
- **Why not the bare name:** a bare `LoadLibraryW(L"bx_shader_bridge.dll")` searches the guest EXE's directory first under the [standard search order](https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order). It can therefore miss a bridge staged next to the shims, or pick up a different copy.
- **Staging:** the bridge is meant to be staged in the same directory as the shims that call it.
- **Why not a host tool over captured logs:** the M2 gate needs the decision at `Create*PipelineState` time inside the guest. That means passing DXIL through and rejecting ACCC-only containers. An offline host tool could count shaders but could not act on them.
### Build and check
```sh
rustup target add x86_64-pc-windows-gnu # once
shader-transpiler/crates/dxbc-accc/guest/build.sh
target/debug/bx-cli run --prefix /tmp/bx-shader --shims target/bx-shader-bridge \
--exe target/bx-shader-bridge/check_bridge.exe
```
`guest/build.sh` writes `bx_shader_bridge.dll` and `check_bridge.exe` to `target/bx-shader-bridge/`. It always builds into, and copies from, `<repo>/target`, whatever `CARGO_TARGET_DIR` says, so it cannot package a stale DLL. It resolves `cargo` and `rustc` through rustup, checks that this `rustc` has `std` for the Windows target, and prints which `rustc` it used. It fails if the Export Address Table holds anything other than the three entry points as direct RVAs (an ordinal-only entry or a forwarder fails it), or if any import is outside the allowlist above.
[`guest/check_bridge.c`](guest/check_bridge.c) is a C guest program built against the frozen header. It checks the struct layout with `_Static_assert`, loads the DLL by full path from its own directory, and sends nine containers through the DLL:
- a real DXC SM 6.6 compute blob (from [`d3dmetal-harness`](../d3dmetal-harness/README.md));
- synthetic DXIL pixel SM 6.0 with `RTS0`, once as is and once followed by 16 bytes past its declared size;
- `ACCC` with an `FSPX` v1 stage section, and `ACCC` with an `FSPX` v0 stub;
- `DXIL` + `ACCC`;
- legacy `SHEX`;
- two malformed blobs.
The program prints one `BXSHADER` line per container and a count line, and checks:
- **Classification:**
- kind, stage and shader model;
- the declared container size;
- the exact `DXIL` and `ACCC` chunk sizes and the root signature flag, each derived from the program's own chunk-table walk;
- the digest, compared with header bytes 4..20 for every container, the real one included.
- **Prepare:** exactly the declared container is copied, never the trailing bytes. ACCC-only and legacy are `BX_SHADER_ERR_UNSUPPORTED`. Malformed input is `BX_SHADER_ERR_INVALID_BLOB`, with output cleared.
- **Free and argument errors:** freeing returned buffers, and null arguments at the DLL boundary.
Recorded run (one Apple M5 Pro, macOS 27.2.1, CrossOver 26.3 `26.3.0.39832`, both a fresh prefix and a D3DMetal bottle):
```text
BXSHADER counts dxil=3 accc_only=2 dual=1 legacy=1 unknown=0 invalid=2
PASS: check_bridge (9 containers through bx_shader_bridge.dll)
```
This is a synthetic, single-host result. It is not a measurement of any title's shader corpus, and not Xbox hardware.
Each of these faults compiled into the DLL fails the check: `dxil_chunk_size` clamped to 1, `accc_chunk_size` multiplied, the digest zeroed, `has_root_signature` set to 7, and the DXIL and ACCC kind numbers swapped. The last one also fails when it is rebuilt with `CARGO_TARGET_DIR` set elsewhere.
### Not done here (other owners)
- **`abi/defs/bx_shader_bridge.def` (`[ABI]`):** the frozen export list for the DLL. Linking with it would also set the export directory's internal name, which is `dxbc_accc.dll` today. Wine loads by file name, so this does not affect loading.
- **Staging in `scripts/build-shims.sh` (Track A):** building the DLL there and verifying it with the other shims, so `build-shims/bin` ships it. That would also make CI build it; today nothing does, and `rustup target add x86_64-pc-windows-gnu` is a manual step.
- **Calling it from `d3d12_xs` at PSO creation, and JSONL telemetry (#466):** today `bx_shader_prepare_for_d3dmetal` reports an ACCC-only container on the guest's stderr (`bx-shader event=prepare status=unsupported …`), not through `bx_log_emit`.
+108
View File
@@ -0,0 +1,108 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Builds bx_shader_bridge.dll (this crate for x86_64-pc-windows-gnu) and the guest check
# check_bridge.exe into one directory (default: <repo>/target/bx-shader-bridge), then checks
# the DLL: its Export Address Table holds exactly the three bx_shader_bridge.h entry points as
# direct RVAs (no extra named or ordinal-only entries, no forwarders), and every imported DLL
# is a system DLL Wine provides. Run the check under CrossOver afterwards, for example:
# target/debug/bx-cli run --prefix /tmp/bx-shader --shims target/bx-shader-bridge \
# --exe target/bx-shader-bridge/check_bridge.exe
#
# Needs: rustup with the x86_64-pc-windows-gnu target, x86_64-w64-mingw32-gcc / -objdump
# (mingw-w64), and python3.
set -eu
crate=$(cd "$(dirname "$0")/.." && pwd)
root=$(cd "$crate/../../.." && pwd)
out=${1:-$root/target/bx-shader-bridge}
target=x86_64-pc-windows-gnu
cc=${BX_MINGW_CC:-x86_64-w64-mingw32-gcc}
objdump=${BX_MINGW_OBJDUMP:-x86_64-w64-mingw32-objdump}
# Always build here and copy from here, whatever CARGO_TARGET_DIR or build.target-dir say,
# so a stale DLL left elsewhere can never be packaged.
target_dir=$root/target
for tool in "$cc" "$objdump" python3; do
command -v "$tool" >/dev/null 2>&1 || { echo "build.sh: $tool not found" >&2; exit 1; }
done
# Use one toolchain for both the target check and the build. With rustup, resolve cargo and
# rustc through it (a cargo earlier on PATH, e.g. Homebrew's, has no Windows std).
if command -v rustup >/dev/null 2>&1; then
cargo=$(cd "$root" && rustup which cargo)
rustc=$(cd "$root" && rustup which rustc)
else
cargo=$(command -v cargo) || { echo "build.sh: cargo not found" >&2; exit 1; }
rustc=$(command -v rustc) || { echo "build.sh: rustc not found" >&2; exit 1; }
fi
libdir=$("$rustc" --print target-libdir --target "$target" 2>/dev/null || true)
if [ -z "$libdir" ] || ! ls "$libdir"/libstd-*.rlib >/dev/null 2>&1; then
echo "build.sh: $rustc ($("$rustc" --version)) has no std for $target" >&2
echo "build.sh: install it with: rustup target add $target" >&2
exit 1
fi
echo "build.sh: using $("$rustc" --version) at $rustc"
RUSTC=$rustc CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=$cc \
"$cargo" build --locked --release -p dxbc-accc --target "$target" \
--target-dir "$target_dir" --manifest-path "$root/Cargo.toml"
mkdir -p "$out"
cp "$target_dir/$target/release/dxbc_accc.dll" "$out/bx_shader_bridge.dll"
dll=$out/bx_shader_bridge.dll
# Same reading of `objdump -p` as scripts/build-shims.sh: every populated Export Address Table
# slot must be a direct RVA owned by one of the expected names.
"$objdump" -p "$dll" | python3 -I -c '
import re, sys
expected = {"bx_shader_inspect", "bx_shader_prepare_for_d3dmetal", "bx_shader_free_buffer"}
# The Windows-provided system DLLs a Rust std cdylib imports; anything else is an error.
allowed = {"kernel32.dll", "ntdll.dll", "bcryptprimitives.dll", "userenv.dll", "ws2_32.dll"}
allowed_prefixes = ("api-ms-win-crt-", "api-ms-win-core-")
eat, names, imports, mode = {}, {}, [], None
for line in sys.stdin:
line = line.rstrip("\n")
m = re.match(r"^\s*DLL Name:\s*(\S+)", line)
if m:
imports.append(m.group(1))
if line.startswith("Export Address Table --"):
mode = "eat"; continue
if line.startswith("[Ordinal/Name Pointer] Table --"):
mode = "names"; continue
if not line.strip():
mode = None; continue
if mode == "eat":
m = re.match(r"^\s*\[\s*\d+\]\s*\+base\[\s*(\d+)\]\s+[0-9a-fA-F]+\s+(Export|Forwarder) RVA", line)
if m:
eat[int(m.group(1))] = m.group(2)
elif mode == "names":
m = re.match(r"^\s*\[\s*\d+\]\s*\+base\[\s*(\d+)\]\s+[0-9a-fA-F]+\s+(\S+)", line)
if m:
names[m.group(2)] = int(m.group(1))
errors = []
if set(names) != expected:
errors.append("named exports %s, want %s" % (sorted(names), sorted(expected)))
owned = set(names.values())
for ordinal, kind in sorted(eat.items()):
if ordinal not in owned:
errors.append("export @%d has no name (ordinal-only or stray entry)" % ordinal)
if kind != "Export":
errors.append("export @%d is a forwarder" % ordinal)
for name, ordinal in names.items():
if ordinal not in eat:
errors.append("%s @%d missing from the Export Address Table" % (name, ordinal))
for dll in imports:
low = dll.lower()
if low not in allowed and not low.startswith(allowed_prefixes):
errors.append("unexpected import %s (only Wine-provided system DLLs are allowed)" % dll)
if errors:
sys.exit("build.sh: bx_shader_bridge.dll: " + "; ".join(errors))
print("build.sh: exports %s; imports %s" % (" ".join(sorted(names)), " ".join(imports)))
'
"$cc" -std=c11 -O2 -Wall -Wextra -Werror -static \
-I"$root/abi/include" -I"$crate/../d3dmetal-harness/probe/shaders" \
-o "$out/check_bridge.exe" "$crate/guest/check_bridge.c"
echo "built $dll"
echo "built $out/check_bridge.exe"
@@ -0,0 +1,296 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
*
* Guest-side check for bx_shader_bridge.dll, the x86-64 Windows build of this crate (#445).
*
* Runs as a PE32+ guest under CrossOver/Wine, loads the DLL by full path from its own directory,
* and drives the three entry points from abi/include/bx_shader_bridge.h with synthetic
* containers plus one real DXC SM 6.6 compute blob. It counts the classifications and checks
* them, and the prepare/free behaviour, against expectations written here from the DXBC
* layout and the frozen header, not from the Rust implementation.
*
* Output: "BXSHADER" lines with each blob's classification, one "BXSHADER counts" line, then
* PASS or FAIL. Exit code 0 on success, 1 on a failed check, 2 if the DLL cannot be loaded.
*/
#include <windows.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include "bx_shader_bridge.h"
#include "fill_cs66.h" /* g_fill_cs66: DXC 1.9.2609 output, see d3dmetal-harness */
/* The Rust side asserts the same layout; agreeing here proves both sides read one struct. */
_Static_assert(sizeof(bx_shader_kind_t) == 4, "C enum must be 4 bytes");
_Static_assert(sizeof(bx_shader_inspection_t) == 48, "bx_shader_inspection_t size");
_Static_assert(offsetof(bx_shader_inspection_t, container_size) == 16, "container_size offset");
_Static_assert(offsetof(bx_shader_inspection_t, digest_hash) == 32, "digest_hash offset");
typedef bx_shader_status_t (*inspect_fn)(const uint8_t*, size_t, bx_shader_inspection_t*);
typedef bx_shader_status_t (*prepare_fn)(const uint8_t*, size_t, uint8_t**, size_t*);
typedef void (*free_fn)(uint8_t*, size_t);
static int failures;
#define CHECK(expr) \
do { \
if (!(expr)) { \
fprintf(stderr, "FAIL: check_bridge line %d: %s\n", __LINE__, #expr); \
++failures; \
} \
} while (0)
/* --- Synthetic DXBC containers --- */
static void put32(uint8_t* at, uint32_t value) {
at[0] = (uint8_t)value;
at[1] = (uint8_t)(value >> 8);
at[2] = (uint8_t)(value >> 16);
at[3] = (uint8_t)(value >> 24);
}
typedef struct {
const char* fourcc;
const uint8_t* data;
uint32_t size;
} chunk_t;
/* DXBC layout: "DXBC", 16-byte digest, u32 version 1, u32 total size, u32 chunk count, then
* one u32 offset per chunk; each chunk is fourcc, u32 size, payload. */
static uint32_t build_dxbc(uint8_t* out, size_t cap, const chunk_t* chunks, uint32_t count) {
uint32_t at = 32 + 4 * count;
for (uint32_t i = 0; i < count; ++i) at += 8 + chunks[i].size;
if (at > cap) abort();
memcpy(out, "DXBC", 4);
memset(out + 4, 0x5A, 16);
put32(out + 20, 1);
put32(out + 24, at);
put32(out + 28, count);
uint32_t offset = 32 + 4 * count;
for (uint32_t i = 0; i < count; ++i) {
put32(out + 32 + 4 * i, offset);
memcpy(out + offset, chunks[i].fourcc, 4);
put32(out + offset + 4, chunks[i].size);
memcpy(out + offset + 8, chunks[i].data, chunks[i].size);
offset += 8 + chunks[i].size;
}
return at;
}
/* A 28-byte DxilProgramHeader: program version word (kind << 16 | major << 4 | minor), size
* in dwords (7), "DXIL", DXIL version 1.0, bitcode offset 16, bitcode size 4, 4 bitcode bytes. */
static void dxil_program(uint8_t out[28], uint32_t kind, uint32_t major, uint32_t minor) {
memset(out, 0, 28);
put32(out, kind << 16 | major << 4 | minor);
put32(out + 4, 7);
memcpy(out + 8, "DXIL", 4);
put32(out + 12, 0x0100);
put32(out + 16, 16);
put32(out + 20, 4);
put32(out + 24, 0xDEC011D1u);
}
/* Size of the first chunk named fourcc in a well-formed container, 0 if absent. Written from
* the DXBC layout, independently of the Rust parser. */
static uint32_t get32(const uint8_t* at) {
return (uint32_t)at[0] | (uint32_t)at[1] << 8 | (uint32_t)at[2] << 16 | (uint32_t)at[3] << 24;
}
static int chunk(const uint8_t* bytes, size_t len, const char* fourcc, uint32_t* size) {
if (len < 32 || memcmp(bytes, "DXBC", 4) != 0) return 0;
const uint32_t count = get32(bytes + 28);
for (uint32_t i = 0; i < count && 36 + 4 * (size_t)i <= len; ++i) {
const uint32_t offset = get32(bytes + 32 + 4 * i);
if (offset + 8 <= len && memcmp(bytes + offset, fourcc, 4) == 0) {
*size = get32(bytes + offset + 4);
return 1;
}
}
return 0;
}
/* --- Cases --- */
typedef struct {
const char* name;
const uint8_t* bytes;
size_t len;
bx_shader_status_t inspect_status;
bx_shader_kind_t kind;
bx_shader_stage_t stage;
uint32_t sm_major, sm_minor;
uint32_t container_size; /* the container's declared size, which may be less than len */
bx_shader_status_t prepare_status;
} case_t;
static const char* kind_name(bx_shader_kind_t kind) {
switch (kind) {
case BX_SHADER_DXBC_DXIL: return "dxil";
case BX_SHADER_DXBC_LEGACY: return "legacy";
case BX_SHADER_DXBC_ACCC: return "accc_only";
case BX_SHADER_DXBC_DUAL: return "dual";
default: return "unknown";
}
}
int main(void) {
/* By full path beside this EXE, as a caller should (see the crate README). */
wchar_t path[MAX_PATH];
const DWORD path_len = GetModuleFileNameW(NULL, path, MAX_PATH);
wchar_t* slash = path_len && path_len < MAX_PATH ? wcsrchr(path, L'\\') : NULL;
if (!slash || (size_t)(slash + 1 - path) + 21 > MAX_PATH) {
fprintf(stderr, "FAIL: check_bridge: executable path too long\n");
return 2;
}
wcscpy(slash + 1, L"bx_shader_bridge.dll");
HMODULE dll = LoadLibraryExW(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!dll) {
fprintf(stderr, "FAIL: check_bridge: bx_shader_bridge.dll not loaded (error %lu)\n", GetLastError());
return 2;
}
inspect_fn inspect = (inspect_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_inspect");
prepare_fn prepare = (prepare_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_prepare_for_d3dmetal");
free_fn release = (free_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_free_buffer");
if (!inspect || !prepare || !release) {
fprintf(stderr, "FAIL: check_bridge: missing export\n");
return 2;
}
uint8_t dxil_cs66[28], dxil_ps60[28];
dxil_program(dxil_cs66, 5, 6, 6); /* DXIL program kind 5 = compute */
dxil_program(dxil_ps60, 0, 6, 0); /* kind 0 = pixel */
const uint8_t rts0[4] = {1, 2, 3, 4};
/* FSPX v1 (BetterXen's synthetic layout): header "FSPX", version 1, 1 section, flags 0;
* descriptor {id 1 (stage config), offset 28, size 12}; body {stage 6 compute, SM 6.0}. */
uint8_t fspx_v1[40] = {0};
memcpy(fspx_v1, "FSPX", 4);
put32(fspx_v1 + 4, 1);
put32(fspx_v1 + 8, 1);
put32(fspx_v1 + 16, 1);
put32(fspx_v1 + 20, 28);
put32(fspx_v1 + 24, 12);
put32(fspx_v1 + 28, BX_STAGE_COMPUTE);
put32(fspx_v1 + 32, 6);
put32(fspx_v1 + 36, 0);
/* FSPX version 0: magic-only stub, no sections. */
uint8_t fspx_v0[16] = {'F', 'S', 'P', 'X'};
/* SM 5.0 compute SHEX token (program type 5 << 16 | 5 << 4 | 0) and a length dword. */
uint8_t shex[8];
put32(shex, 5u << 16 | 5u << 4);
put32(shex + 4, 2);
static uint8_t ps60[256], accc_v1[256], accc_v0[256], dual[256], legacy[256];
const chunk_t ps60_chunks[] = {{"RTS0", rts0, 4}, {"DXIL", dxil_ps60, 28}};
const chunk_t accc_v1_chunks[] = {{"ACCC", fspx_v1, sizeof(fspx_v1)}};
const chunk_t accc_v0_chunks[] = {{"ACCC", fspx_v0, sizeof(fspx_v0)}};
const chunk_t dual_chunks[] = {{"DXIL", dxil_cs66, 28}, {"ACCC", fspx_v0, sizeof(fspx_v0)}};
const chunk_t legacy_chunks[] = {{"SHEX", shex, sizeof(shex)}};
const uint32_t ps60_len = build_dxbc(ps60, sizeof(ps60), ps60_chunks, 2);
const uint32_t accc_v1_len = build_dxbc(accc_v1, sizeof(accc_v1), accc_v1_chunks, 1);
const uint32_t accc_v0_len = build_dxbc(accc_v0, sizeof(accc_v0), accc_v0_chunks, 1);
const uint32_t dual_len = build_dxbc(dual, sizeof(dual), dual_chunks, 2);
const uint32_t legacy_len = build_dxbc(legacy, sizeof(legacy), legacy_chunks, 1);
/* The pixel shader again, followed by 16 bytes that are not part of the container. */
static uint8_t padded[256 + 16];
memcpy(padded, ps60, ps60_len);
memset(padded + ps60_len, 0xEE, 16);
static const uint8_t truncated[20] = {'D', 'X', 'B', 'C'};
static const uint8_t not_dxbc[64] = {'X', 'X', 'X', 'X'};
const case_t cases[] = {
{"dxc_cs_6_6", g_fill_cs66, sizeof(g_fill_cs66), BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_COMPUTE, 6, 6,
sizeof(g_fill_cs66), BX_SHADER_OK},
{"synthetic_ps_6_0", ps60, ps60_len, BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_PIXEL, 6, 0, ps60_len,
BX_SHADER_OK},
{"trailing_bytes", padded, ps60_len + 16, BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_PIXEL, 6, 0, ps60_len,
BX_SHADER_OK},
{"accc_fspx_v1", accc_v1, accc_v1_len, BX_SHADER_OK, BX_SHADER_DXBC_ACCC, BX_STAGE_COMPUTE, 6, 0, accc_v1_len,
BX_SHADER_ERR_UNSUPPORTED},
{"accc_fspx_v0", accc_v0, accc_v0_len, BX_SHADER_OK, BX_SHADER_DXBC_ACCC, BX_STAGE_UNKNOWN, 0, 0, accc_v0_len,
BX_SHADER_ERR_UNSUPPORTED},
{"dual_dxil_accc", dual, dual_len, BX_SHADER_OK, BX_SHADER_DXBC_DUAL, BX_STAGE_COMPUTE, 6, 6, dual_len,
BX_SHADER_OK},
{"legacy_shex_5_0", legacy, legacy_len, BX_SHADER_OK, BX_SHADER_DXBC_LEGACY, BX_STAGE_COMPUTE, 5, 0,
legacy_len, BX_SHADER_ERR_UNSUPPORTED},
{"truncated", truncated, sizeof(truncated), BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_UNKNOWN, BX_STAGE_UNKNOWN,
0, 0, 0, BX_SHADER_ERR_INVALID_BLOB},
{"not_dxbc", not_dxbc, sizeof(not_dxbc), BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_UNKNOWN, BX_STAGE_UNKNOWN, 0,
0, 0, BX_SHADER_ERR_INVALID_BLOB},
};
const size_t count = sizeof(cases) / sizeof(cases[0]);
unsigned tally[5] = {0};
unsigned invalid = 0;
for (size_t i = 0; i < count; ++i) {
const case_t* c = &cases[i];
bx_shader_inspection_t info;
memset(&info, 0xEE, sizeof(info));
const bx_shader_status_t status = inspect(c->bytes, c->len, &info);
printf("BXSHADER %s status=%d kind=%s stage=%d sm=%u.%u container_size=%u dxil=%u accc=%u rts0=%u\n",
c->name, (int)status, kind_name(info.kind), (int)info.stage, info.shader_model_major,
info.shader_model_minor, info.container_size, info.dxil_chunk_size, info.accc_chunk_size,
info.has_root_signature);
CHECK(status == c->inspect_status);
if (status == BX_SHADER_OK) {
if ((unsigned)info.kind < 5) ++tally[info.kind];
CHECK(info.kind == c->kind);
CHECK(info.stage == c->stage);
CHECK(info.shader_model_major == c->sm_major && info.shader_model_minor == c->sm_minor);
CHECK(info.container_size == c->container_size);
/* Exact chunk sizes and the root signature flag, from this file's own chunk walk. */
uint32_t want_dxil = 0, want_accc = 0, rts0_size = 0;
chunk(c->bytes, c->len, "DXIL", &want_dxil);
chunk(c->bytes, c->len, "ACCC", &want_accc);
const uint32_t want_rts0 = (uint32_t)chunk(c->bytes, c->len, "RTS0", &rts0_size);
CHECK(info.dxil_chunk_size == want_dxil);
CHECK(info.accc_chunk_size == want_accc);
CHECK(info.has_root_signature == want_rts0);
CHECK((want_dxil != 0) == (c->kind == BX_SHADER_DXBC_DXIL || c->kind == BX_SHADER_DXBC_DUAL));
CHECK((want_accc != 0) == (c->kind == BX_SHADER_DXBC_ACCC || c->kind == BX_SHADER_DXBC_DUAL));
/* The digest is the container header's bytes 4..20, for every case. */
CHECK(memcmp(info.digest_hash, c->bytes + 4, 16) == 0);
} else {
++invalid;
const bx_shader_inspection_t zero = {0};
CHECK(memcmp(&info, &zero, sizeof(info)) == 0); /* cleared on failure */
}
uint8_t* copy = (uint8_t*)(uintptr_t)1;
size_t copy_len = 1;
const bx_shader_status_t prepared = prepare(c->bytes, c->len, &copy, &copy_len);
CHECK(prepared == c->prepare_status);
if (prepared == BX_SHADER_OK) {
/* Only the declared container is copied, never bytes past it. */
CHECK(copy && copy_len == c->container_size && memcmp(copy, c->bytes, c->container_size) == 0);
release(copy, copy_len);
} else {
CHECK(copy == NULL && copy_len == 0);
}
}
/* Argument checks at the DLL boundary. */
bx_shader_inspection_t info;
CHECK(inspect(g_fill_cs66, sizeof(g_fill_cs66), NULL) == BX_SHADER_ERR_INVALID_BLOB);
CHECK(inspect(NULL, 16, &info) == BX_SHADER_ERR_INVALID_BLOB);
uint8_t* copy = NULL;
CHECK(prepare(g_fill_cs66, sizeof(g_fill_cs66), NULL, NULL) == BX_SHADER_ERR_INVALID_BLOB);
CHECK(prepare(NULL, 16, &copy, &(size_t){0}) == BX_SHADER_ERR_INVALID_BLOB && copy == NULL);
release(NULL, 0);
printf("BXSHADER counts dxil=%u accc_only=%u dual=%u legacy=%u unknown=%u invalid=%u\n",
tally[BX_SHADER_DXBC_DXIL], tally[BX_SHADER_DXBC_ACCC], tally[BX_SHADER_DXBC_DUAL],
tally[BX_SHADER_DXBC_LEGACY], tally[BX_SHADER_UNKNOWN], invalid);
CHECK(tally[BX_SHADER_DXBC_DXIL] == 3 && tally[BX_SHADER_DXBC_ACCC] == 2 && tally[BX_SHADER_DXBC_DUAL] == 1);
CHECK(tally[BX_SHADER_DXBC_LEGACY] == 1 && tally[BX_SHADER_UNKNOWN] == 0 && invalid == 2);
if (failures) {
fprintf(stderr, "FAIL: check_bridge (%d failed checks)\n", failures);
return 1;
}
printf("PASS: check_bridge (%u containers through bx_shader_bridge.dll)\n", (unsigned)count);
return 0;
}
+2
View File
@@ -2,6 +2,8 @@ bx_add_shim_dll(xgameruntime xgameruntime xgameruntime.def
xgameruntime.cpp
task_queue.cpp
com_dispatch.cpp
game_save.cpp
package.cpp
)
target_link_libraries(xgameruntime PRIVATE bx_runtime_veh kernel32)
target_compile_options(xgameruntime PRIVATE -fexceptions)
+930
View File
@@ -0,0 +1,930 @@
/*
* Offline XGameSave over bottle-local storage (#468).
*
* Reached only through QueryApiImpl with the BetterXen synthetic xgamesave key; the key and
* the vtable slot order are in synthetic_keys.h. Nothing here is exported.
*
* Public reference (Microsoft Learn, gdk-2610, checked 2026-11-26): the XGameSave members
* page and the function and structure pages it links. The signatures, the
* XGameSaveContainerInfo / XGameSaveBlobInfo / XGameSaveBlob layouts, the E_GS_* values,
* the container-name rules and the 16 MB update limit come from there:
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgamesave/xgamesave_members
* No Microsoft header, source or binary was used.
*
* Storage: each SCID has its own directory, <XPersistentLocalStorage path>\saves\<scid id>,
* and each container is one file in it, <container id>.bxgs. Both ids are the 64-bit FNV-1a
* hash of the string's bytes (each byte taken as one UTF-16 code unit 0-255) as 16 lowercase
* hex digits; neither string is ever used as a path. A submitted update
* rewrites the file through a temporary file and MoveFileExW, so an update lands entirely or
* not at all. Every read and read-modify-write of a SCID directory holds a named mutex derived
* from that directory, so threads and processes sharing a title directory do not lose updates.
* The format is BetterXen-defined, little-endian:
* u32 magic "BXGS", u32 version 1, str name, str display name, i64 last-modified time_t,
* u32 blob count, then per blob: str name, u32 size, size bytes. (str = u32 length + bytes)
* A file is valid only if it is consumed exactly, its container name is valid and matches its
* file name, no string holds a NUL, and blob names are unique and within the limit below.
*
* Offline behaviour, where the public pages leave it open:
* - There is no service. syncOnDemand has no effect and needsSync is always false.
* - The provider needs a live XUser handle and a non-null SCID. Saves are separated by SCID.
* - A second write of the same blob in one update fails with E_INVALIDARG (the page allows
* one modification per blob per update but names no error).
* - "16 MB" for GS_MAX_BLOB_SIZE is read as 16 MiB, enforced on the staged total of blob
* names and data.
* - GS_MAX_BLOB_NAME_SIZE has no published value. BetterXen limits blob names to 256 bytes.
* - A null display name in CreateUpdate keeps the container's current display name.
* - While an update's submit is pending, writing to or submitting that update fails with
* E_ILLEGAL_METHOD_CALL. Once it completes, succeeded, failed or canceled, the update can
* be submitted again, so a failed submit can be retried without staging the data again.
* - Reading named blobs of a container that was never submitted fails with
* E_GS_BLOB_NOT_FOUND; reading all of them returns zero blobs.
* - A full disk on submit is E_GS_OUT_OF_LOCAL_STORAGE.
* - Closing a provider closes its containers and their updates; closing a container closes
* its updates. The last XGameRuntimeUninitialize closes every handle.
* - Paths of MAX_PATH or more (executable or storage) fail with ERROR_FILENAME_EXCED_RANGE.
*/
#include "runtime_internal.h"
#include "synthetic_keys.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iterator>
#include <map>
#include <memory>
#include <mutex>
#include <new>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "bx_log.h"
namespace bx::gdk {
namespace {
using synthetic::GameSaveSlot;
// E_GS_* values listed on the XGameSave members page.
constexpr HRESULT kInvalidContainerName = static_cast<HRESULT>(0x80830001u);
constexpr HRESULT kOutOfLocalStorage = static_cast<HRESULT>(0x80830003u);
constexpr HRESULT kUpdateTooBig = static_cast<HRESULT>(0x80830005u);
constexpr HRESULT kProvidedBufferTooSmall = static_cast<HRESULT>(0x80830007u);
constexpr HRESULT kBlobNotFound = static_cast<HRESULT>(0x80830008u);
constexpr HRESULT kFileCorrupt = HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT);
constexpr size_t kMaxUpdateBytes = 16u * 1024u * 1024u;
constexpr size_t kMaxContainerName = 256;
constexpr size_t kMaxBlobName = 256;
struct ContainerInfo { // XGameSaveContainerInfo
const char* name;
const char* display_name;
uint32_t blob_count;
uint64_t total_size;
time_t last_modified_time;
bool needs_sync;
};
static_assert(sizeof(time_t) == 8);
static_assert(offsetof(ContainerInfo, blob_count) == 16 && offsetof(ContainerInfo, total_size) == 24);
static_assert(offsetof(ContainerInfo, last_modified_time) == 32 && offsetof(ContainerInfo, needs_sync) == 40);
struct BlobInfo { // XGameSaveBlobInfo
const char* name;
uint32_t size;
};
struct Blob { // XGameSaveBlob
BlobInfo info;
uint8_t* data;
};
static_assert(sizeof(BlobInfo) == 16 && offsetof(Blob, data) == 16 && sizeof(Blob) == 24);
using ContainerInfoCallback = bool(CALLBACK*)(const ContainerInfo*, void*);
// FNV-1a over the string's bytes, each taken as one UTF-16 code unit 0-255, as 16 hex digits.
std::wstring hex_id(const std::string& text) {
std::wstring wide;
wide.reserve(text.size());
for (const char c : text) wide.push_back(static_cast<wchar_t>(static_cast<unsigned char>(c)));
wchar_t id[17];
std::swprintf(id, 17, L"%016llx", static_cast<unsigned long long>(fnv1a(wide.c_str())));
return id;
}
// --- Names ---
bool name_char(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_';
}
// Rules from the XGameSaveCreateContainer page: an optional path part up to the last '/'
// (A-Z, a-z, 0-9, _, /) and a non-empty file part (A-Z, a-z, 0-9, _, ., -) that does not
// end in a period or contain "..". At most 256 characters.
bool valid_container_name(const char* name, size_t length) {
if (!name || length == 0 || length > kMaxContainerName) return false;
const char* end = name + length;
const char* file = name;
for (const char* c = name; c < end; ++c) {
if (*c == '/') file = c + 1;
}
for (const char* c = name; c < file; ++c) {
if (!name_char(*c) && *c != '/') return false;
}
if (file == end || end[-1] == '.') return false;
for (const char* c = file; c < end; ++c) {
if (!name_char(*c) && *c != '.' && *c != '-') return false;
if (c[0] == '.' && c + 1 < end && c[1] == '.') return false;
}
return true;
}
bool valid_container_name(const char* name) {
return name && valid_container_name(name, strnlen(name, kMaxContainerName + 1));
}
bool valid_blob_name(const std::string& name) {
return !name.empty() && name.size() <= kMaxBlobName && name.find('\0') == std::string::npos;
}
// --- Container files ---
struct ContainerData {
std::string name;
std::string display_name;
int64_t last_modified = 0;
uint64_t total_size = 0;
std::map<std::string, std::vector<uint8_t>> blobs; // Data left empty when parsed without data.
};
constexpr uint32_t kMagic = 0x53475842; // "BXGS"
constexpr uint32_t kFormatVersion = 1;
constexpr wchar_t kExtension[] = L".bxgs";
void put_u32(std::vector<uint8_t>& out, uint32_t value) {
for (int shift = 0; shift < 32; shift += 8) out.push_back(static_cast<uint8_t>(value >> shift));
}
void put_u64(std::vector<uint8_t>& out, uint64_t value) {
put_u32(out, static_cast<uint32_t>(value));
put_u32(out, static_cast<uint32_t>(value >> 32));
}
void put_string(std::vector<uint8_t>& out, const std::string& text) {
put_u32(out, static_cast<uint32_t>(text.size()));
out.insert(out.end(), text.begin(), text.end());
}
std::vector<uint8_t> serialize(const ContainerData& data) {
std::vector<uint8_t> out;
put_u32(out, kMagic);
put_u32(out, kFormatVersion);
put_string(out, data.name);
put_string(out, data.display_name);
put_u64(out, static_cast<uint64_t>(data.last_modified));
put_u32(out, static_cast<uint32_t>(data.blobs.size()));
for (const auto& [name, bytes] : data.blobs) {
put_string(out, name);
put_u32(out, static_cast<uint32_t>(bytes.size()));
out.insert(out.end(), bytes.begin(), bytes.end());
}
return out;
}
class Reader {
public:
explicit Reader(const std::vector<uint8_t>& bytes) : next_(bytes.data()), left_(bytes.size()) {}
bool u32(uint32_t& value) {
if (left_ < 4) return false;
value = 0;
for (int i = 0; i < 4; ++i) value |= static_cast<uint32_t>(next_[i]) << (8 * i);
next_ += 4;
left_ -= 4;
return true;
}
bool u64(uint64_t& value) {
uint32_t low, high;
if (!u32(low) || !u32(high)) return false;
value = (static_cast<uint64_t>(high) << 32) | low;
return true;
}
bool bytes(size_t size, const uint8_t*& data) {
if (left_ < size) return false;
data = next_;
next_ += size;
left_ -= size;
return true;
}
// A NUL cannot pass through the C string APIs, so a stored one is corruption.
bool string(std::string& text) {
uint32_t size;
const uint8_t* data;
if (!u32(size) || !bytes(size, data) || std::memchr(data, 0, size)) return false;
text.assign(reinterpret_cast<const char*>(data), size);
return true;
}
bool done() const { return left_ == 0; }
private:
const uint8_t* next_;
size_t left_;
};
// with_data false validates the whole file but keeps only names and sizes.
bool parse(const std::vector<uint8_t>& bytes, ContainerData& data, bool with_data) {
Reader in(bytes);
uint32_t magic, version, count;
uint64_t modified;
if (!in.u32(magic) || magic != kMagic || !in.u32(version) || version != kFormatVersion ||
!in.string(data.name) || !valid_container_name(data.name.c_str(), data.name.size()) ||
!in.string(data.display_name) || !in.u64(modified) || !in.u32(count)) {
return false;
}
data.last_modified = static_cast<int64_t>(modified);
for (uint32_t i = 0; i < count; ++i) {
std::string name;
uint32_t size;
const uint8_t* blob;
if (!in.string(name) || !valid_blob_name(name) || !in.u32(size) || !in.bytes(size, blob)) return false;
auto content = with_data ? std::vector<uint8_t>(blob, blob + size) : std::vector<uint8_t>();
if (!data.blobs.emplace(std::move(name), std::move(content)).second) return false;
data.total_size += size;
}
return in.done();
}
std::wstring container_file(const std::wstring& dir, const std::string& name) {
return dir + L"\\" + hex_id(name) + kExtension;
}
HRESULT read_file(const std::wstring& path, std::vector<uint8_t>& out, bool& exists) {
exists = false;
// Share everything, so a reader never blocks another process's replace.
const HANDLE file = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) {
const auto error = GetLastError();
return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? S_OK : HRESULT_FROM_WIN32(error);
}
exists = true;
HRESULT hr = S_OK;
LARGE_INTEGER size{};
if (!GetFileSizeEx(file, &size)) {
hr = HRESULT_FROM_WIN32(GetLastError());
} else {
try {
out.resize(static_cast<size_t>(size.QuadPart));
} catch (const std::bad_alloc&) {
hr = E_OUTOFMEMORY;
}
size_t done = 0;
while (SUCCEEDED(hr) && done < out.size()) {
const DWORD chunk = static_cast<DWORD>(std::min<size_t>(out.size() - done, 1u << 30));
DWORD got = 0;
if (!ReadFile(file, out.data() + done, chunk, &got, nullptr)) hr = HRESULT_FROM_WIN32(GetLastError());
else if (got == 0) hr = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
done += got;
}
}
CloseHandle(file);
return hr;
}
HRESULT write_error(DWORD error) {
return error == ERROR_DISK_FULL || error == ERROR_HANDLE_DISK_FULL ? kOutOfLocalStorage
: HRESULT_FROM_WIN32(error);
}
HRESULT write_file_atomic(const std::wstring& path, const std::vector<uint8_t>& bytes) {
const std::wstring temp = path + L"." + std::to_wstring(GetCurrentProcessId()) + L".tmp";
const HANDLE file =
CreateFileW(temp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) return write_error(GetLastError());
HRESULT hr = S_OK;
size_t done = 0;
while (SUCCEEDED(hr) && done < bytes.size()) {
const DWORD chunk = static_cast<DWORD>(std::min<size_t>(bytes.size() - done, 1u << 30));
DWORD wrote = 0;
if (!WriteFile(file, bytes.data() + done, chunk, &wrote, nullptr)) hr = write_error(GetLastError());
done += wrote;
}
if (SUCCEEDED(hr) && !FlushFileBuffers(file)) hr = write_error(GetLastError());
CloseHandle(file);
if (SUCCEEDED(hr) && !MoveFileExW(temp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
hr = write_error(GetLastError());
}
if (FAILED(hr)) DeleteFileW(temp.c_str());
return hr;
}
// Logs the file name only: bx_log_emit does not escape, and a Windows file name cannot hold
// a backslash, quote or control character, so it is always valid JSON string content. The
// directory is the title's saves directory for one SCID.
void log_bad_file(const char* event, const std::wstring& path) {
const auto slash = path.find_last_of(L'\\');
const std::wstring name = slash == std::wstring::npos ? path : path.substr(slash + 1);
char detail[MAX_PATH * 3 + 8];
const int bytes = WideCharToMultiByte(CP_UTF8, 0, name.c_str(), -1, detail, sizeof(detail), nullptr, nullptr);
if (bytes <= 0) std::snprintf(detail, sizeof(detail), "(unprintable file name)");
bx_log_emit(BX_LOG_WARN, "xgamesave", event, detail);
}
// Holds the named mutex for one SCID directory. Abandonment by a crashed owner is not an
// error: every file is replaced atomically, so a half-done update never reaches disk.
class DirectoryLock {
public:
explicit DirectoryLock(const std::wstring& dir) {
wchar_t lower[MAX_PATH];
if (!LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, dir.c_str(), -1, lower, MAX_PATH, nullptr,
nullptr, 0)) {
status_ = HRESULT_FROM_WIN32(GetLastError());
return;
}
wchar_t name[64];
std::swprintf(name, 64, L"Local\\BetterXen.XGameSave.%016llx", static_cast<unsigned long long>(fnv1a(lower)));
mutex_ = CreateMutexW(nullptr, FALSE, name);
if (!mutex_) {
status_ = HRESULT_FROM_WIN32(GetLastError());
return;
}
const DWORD wait = WaitForSingleObject(mutex_, INFINITE);
status_ = wait == WAIT_OBJECT_0 || wait == WAIT_ABANDONED ? S_OK : HRESULT_FROM_WIN32(GetLastError());
}
~DirectoryLock() {
if (!mutex_) return;
if (SUCCEEDED(status_)) ReleaseMutex(mutex_);
CloseHandle(mutex_);
}
DirectoryLock(const DirectoryLock&) = delete;
DirectoryLock& operator=(const DirectoryLock&) = delete;
HRESULT status() const { return status_; }
private:
HANDLE mutex_ = nullptr;
HRESULT status_ = E_FAIL;
};
// Caller holds the DirectoryLock for dir.
HRESULT load_container(const std::wstring& dir, const std::string& name, ContainerData& data, bool& exists) {
const auto path = container_file(dir, name);
std::vector<uint8_t> bytes;
auto hr = read_file(path, bytes, exists);
if (FAILED(hr) || !exists) return hr;
if (!parse(bytes, data, true)) {
log_bad_file("corrupt_container", path);
return kFileCorrupt;
}
if (data.name != name) {
log_bad_file("container_id_collision", path);
return HRESULT_FROM_WIN32(ERROR_FILE_EXISTS);
}
return S_OK;
}
// Caller holds the DirectoryLock for dir. Files that cannot be read or parsed are logged and
// skipped, so one bad file does not hide the others.
HRESULT list_containers(const std::wstring& dir, std::vector<ContainerData>& out) {
WIN32_FIND_DATAW found;
const HANDLE search = FindFirstFileW((dir + L"\\*" + kExtension).c_str(), &found);
if (search == INVALID_HANDLE_VALUE) {
const auto error = GetLastError();
return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? S_OK : HRESULT_FROM_WIN32(error);
}
HRESULT hr = S_OK;
do {
const std::wstring file = found.cFileName;
constexpr size_t ext = std::size(kExtension) - 1;
if ((found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || file.size() <= ext ||
file.compare(file.size() - ext, ext, kExtension) != 0) {
continue;
}
const std::wstring path = dir + L"\\" + file;
std::vector<uint8_t> bytes;
bool exists;
ContainerData data;
const auto read = read_file(path, bytes, exists);
if (read == E_OUTOFMEMORY) {
hr = read;
break;
}
if (FAILED(read)) {
log_bad_file("unreadable_container", path);
continue;
}
if (!exists) continue; // Replaced or removed since the search returned it.
if (!parse(bytes, data, false) || container_file(dir, data.name) != path) {
log_bad_file("corrupt_container", path);
continue;
}
try {
out.push_back(std::move(data));
} catch (const std::bad_alloc&) {
hr = E_OUTOFMEMORY;
}
} while (SUCCEEDED(hr) && FindNextFileW(search, &found));
FindClose(search);
return hr;
}
HRESULT saves_directory(const std::string& scid, std::wstring& dir) {
wchar_t root[MAX_PATH];
auto hr = title_storage_directory(root);
if (FAILED(hr)) return hr;
const std::wstring saves = std::wstring(root) + L"\\saves";
hr = ensure_directory(saves.c_str());
if (FAILED(hr)) return hr;
dir = saves + L"\\" + hex_id(scid);
if (dir.size() >= MAX_PATH) return HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE);
return ensure_directory(dir.c_str());
}
// --- Handles ---
// Lock order: the runtime lock (taken by active_runtime_generation, is_valid_user, around
// consume callbacks and around release_game_save_state) before handle_mutex. Nothing here
// calls into the runtime while holding handle_mutex.
struct Provider {
uint32_t generation;
std::wstring dir;
};
struct Container {
void* provider;
std::string name;
};
struct Update {
void* container;
bool keep_display_name;
std::string display_name;
std::map<std::string, std::vector<uint8_t>> writes;
size_t staged_bytes = 0;
// Set while a submit of this update is queued or running; cleared by that operation.
std::shared_ptr<std::atomic<bool>> pending;
};
std::mutex handle_mutex;
std::unordered_map<void*, Provider> providers;
std::unordered_map<void*, Container> containers;
std::unordered_map<void*, Update> updates;
// Each handle type has its own range (tag in bits 40-43), so a handle of one type is never
// a valid handle of another. package.cpp uses tag 4.
enum : uintptr_t { kProviderTag = 1, kContainerTag = 2, kUpdateTag = 3 };
uintptr_t handle_counter = 0;
void* next_handle(uintptr_t tag) {
++handle_counter;
return reinterpret_cast<void*>(tag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
}
// The finders below require handle_mutex. A handle from before the last uninitialize, or
// one whose provider was closed, is not found.
const Provider* find_provider(void* handle, uint32_t generation) {
const auto found = providers.find(handle);
if (found == providers.end() || generation == 0 || found->second.generation != generation) return nullptr;
return &found->second;
}
const Container* find_container(void* handle, uint32_t generation, const Provider** provider) {
const auto found = containers.find(handle);
if (found == containers.end()) return nullptr;
*provider = find_provider(found->second.provider, generation);
return *provider ? &found->second : nullptr;
}
Update* find_update(void* handle, uint32_t generation, const Container** container, const Provider** provider) {
const auto found = updates.find(handle);
if (found == updates.end()) return nullptr;
*container = find_container(found->second.container, generation, provider);
return *container ? &found->second : nullptr;
}
template <typename Map, typename Value>
HRESULT insert_handle(Map& map, uintptr_t tag, Value&& value, void** out) {
void* handle = next_handle(tag);
try {
map.emplace(handle, std::forward<Value>(value));
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
*out = handle;
return S_OK;
}
// Caller holds handle_mutex.
void erase_updates_of(void* container) {
std::erase_if(updates, [&](const auto& entry) { return entry.second.container == container; });
}
// Caller holds handle_mutex.
void erase_containers_of(void* provider) {
for (auto it = containers.begin(); it != containers.end();) {
if (it->second.provider == provider) {
erase_updates_of(it->first);
it = containers.erase(it);
} else {
++it;
}
}
}
// --- Async operations ---
enum : uint32_t { kInitProviderOp = 0x58475301, kSubmitUpdateOp = 0x58475302, kReadBlobsOp = 0x58475303 };
class InitProviderOp final : public AsyncOp {
public:
uint32_t generation = 0;
std::string scid;
std::wstring dir;
uint32_t kind() const override { return kInitProviderOp; }
HRESULT execute() override try {
return saves_directory(scid, dir);
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
size_t result_size() const override { return sizeof(void*); }
};
class SubmitUpdateOp final : public AsyncOp {
public:
std::wstring dir;
std::string name;
bool keep_display_name = false;
std::string display_name;
std::map<std::string, std::vector<uint8_t>> writes;
std::shared_ptr<std::atomic<bool>> pending;
// Covers cancellation and a submission that never ran.
~SubmitUpdateOp() override { finish(); }
uint32_t kind() const override { return kSubmitUpdateOp; }
size_t result_size() const override { return 0; }
HRESULT execute() override {
const auto hr = write();
finish();
return hr;
}
private:
// Once per op: a resubmit shares the flag, so an old op must not clear it again later.
void finish() {
if (pending) pending->store(false);
pending.reset();
}
HRESULT write() try {
DirectoryLock lock(dir);
if (FAILED(lock.status())) return lock.status();
ContainerData data;
bool exists = false;
auto hr = load_container(dir, name, data, exists);
if (FAILED(hr)) return hr;
if (!exists) data.name = name;
if (!keep_display_name) data.display_name = display_name;
for (auto& [blob, bytes] : writes) data.blobs[blob] = std::move(bytes);
data.last_modified = static_cast<int64_t>(std::time(nullptr));
return write_file_atomic(container_file(dir, name), serialize(data));
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
};
class ReadBlobsOp final : public AsyncOp {
public:
std::wstring dir;
std::string name;
std::vector<std::string> wanted; // Empty: every blob.
std::vector<std::pair<std::string, std::vector<uint8_t>>> found;
size_t bytes = 0;
uint32_t kind() const override { return kReadBlobsOp; }
size_t result_size() const override { return bytes; }
HRESULT execute() override try {
DirectoryLock lock(dir);
if (FAILED(lock.status())) return lock.status();
ContainerData data;
bool exists = false;
const auto hr = load_container(dir, name, data, exists);
if (FAILED(hr)) return hr;
if (wanted.empty()) {
for (auto& [blob, content] : data.blobs) found.emplace_back(blob, std::move(content));
} else {
for (const auto& blob : wanted) {
const auto match = data.blobs.find(blob);
if (match == data.blobs.end()) return kBlobNotFound;
found.emplace_back(blob, std::move(match->second));
}
}
bytes = found.size() * sizeof(Blob);
for (const auto& [blob, content] : found) bytes += blob.size() + 1 + content.size();
return S_OK;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
// Layout in the caller's buffer: the Blob array, then all data, then the names.
void copy_to(Blob* out) const {
auto* cursor = reinterpret_cast<uint8_t*>(out) + found.size() * sizeof(Blob);
for (size_t i = 0; i < found.size(); ++i) {
const auto& content = found[i].second;
out[i].info.size = static_cast<uint32_t>(content.size());
out[i].data = cursor;
if (!content.empty()) std::memcpy(cursor, content.data(), content.size());
cursor += content.size();
}
for (size_t i = 0; i < found.size(); ++i) {
const auto& blob = found[i].first;
std::memcpy(cursor, blob.c_str(), blob.size() + 1);
out[i].info.name = reinterpret_cast<const char*>(cursor);
cursor += blob.size() + 1;
}
}
};
HRESULT stale_handle_error(uint32_t generation) {
return generation ? kRuntimeInvalidHandle : kRuntimeNotInitialized;
}
// --- Slots ---
HRESULT WINAPI initialize_provider_async(void*, void* user, const char* scid, bool /*sync_on_demand*/,
void* async) {
if (!async) return E_POINTER;
if (!scid) return E_INVALIDARG;
const auto generation = active_runtime_generation();
if (!is_valid_user(user)) return stale_handle_error(generation);
std::unique_ptr<InitProviderOp> op(new (std::nothrow) InitProviderOp);
if (!op) return E_OUTOFMEMORY;
try {
op->scid = scid;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
op->generation = generation;
return begin_async_op(async, std::move(op));
}
HRESULT WINAPI initialize_provider_result(void*, void* async, void** provider) {
if (!provider) return E_POINTER;
*provider = nullptr;
return consume_async_op(async, kInitProviderOp, [&](AsyncOp& base) {
auto& op = static_cast<InitProviderOp&>(base);
std::lock_guard lock(handle_mutex);
return insert_handle(providers, kProviderTag, Provider{op.generation, op.dir}, provider);
});
}
void WINAPI close_provider(void*, void* provider) {
std::lock_guard lock(handle_mutex);
if (providers.erase(provider)) erase_containers_of(provider);
}
HRESULT WINAPI create_container(void*, void* provider, const char* name, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
const auto generation = active_runtime_generation();
std::lock_guard lock(handle_mutex);
if (!find_provider(provider, generation)) return stale_handle_error(generation);
if (!valid_container_name(name)) return kInvalidContainerName;
try {
return insert_handle(containers, kContainerTag, Container{provider, name}, out);
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
}
void WINAPI close_container(void*, void* container) {
std::lock_guard lock(handle_mutex);
if (containers.erase(container)) erase_updates_of(container);
}
HRESULT WINAPI create_update(void*, void* container, const char* display_name, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
const auto generation = active_runtime_generation();
std::lock_guard lock(handle_mutex);
const Provider* provider = nullptr;
if (!find_container(container, generation, &provider)) return stale_handle_error(generation);
try {
Update staged;
staged.container = container;
staged.keep_display_name = display_name == nullptr;
staged.display_name = display_name ? display_name : "";
staged.pending = std::make_shared<std::atomic<bool>>(false);
return insert_handle(updates, kUpdateTag, std::move(staged), out);
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
}
void WINAPI close_update(void*, void* update) {
std::lock_guard lock(handle_mutex);
updates.erase(update);
}
HRESULT WINAPI submit_blob_write(void*, void* update, const char* blob_name, const uint8_t* data, size_t size) {
if (!blob_name) return E_INVALIDARG;
const size_t name_length = strnlen(blob_name, kMaxBlobName + 1);
if (name_length == 0 || name_length > kMaxBlobName) return E_INVALIDARG;
if (!data && size) return E_POINTER;
const auto generation = active_runtime_generation();
std::lock_guard lock(handle_mutex);
const Container* container = nullptr;
const Provider* provider = nullptr;
auto* staged = find_update(update, generation, &container, &provider);
if (!staged) return stale_handle_error(generation);
if (staged->pending->load()) return kIllegalMethodCall;
if (staged->writes.contains(blob_name)) return E_INVALIDARG;
if (size > kMaxUpdateBytes - staged->staged_bytes ||
name_length > kMaxUpdateBytes - staged->staged_bytes - size) {
return kUpdateTooBig;
}
try {
staged->writes.emplace(blob_name, std::vector<uint8_t>(data, data + size));
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
staged->staged_bytes += name_length + size;
return S_OK;
}
HRESULT WINAPI submit_update_async(void*, void* update, void* async) {
if (!async) return E_POINTER;
std::unique_ptr<SubmitUpdateOp> op(new (std::nothrow) SubmitUpdateOp);
if (!op) return E_OUTOFMEMORY;
const auto generation = active_runtime_generation();
{
std::lock_guard lock(handle_mutex);
const Container* container = nullptr;
const Provider* provider = nullptr;
auto* staged = find_update(update, generation, &container, &provider);
if (!staged) return stale_handle_error(generation);
if (staged->pending->load()) return kIllegalMethodCall;
try {
op->dir = provider->dir;
op->name = container->name;
op->keep_display_name = staged->keep_display_name;
op->display_name = staged->display_name;
op->writes = staged->writes;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
staged->pending->store(true);
op->pending = staged->pending;
}
// On failure begin_async_op destroys op, whose destructor clears the pending flag.
return begin_async_op(async, std::move(op));
}
HRESULT WINAPI submit_update_result(void*, void* async) {
return consume_async_op(async, kSubmitUpdateOp, [](AsyncOp&) { return S_OK; });
}
HRESULT WINAPI read_blob_data_async(void*, void* container, const char** names, uint32_t count, void* async) {
if (!async) return E_POINTER;
if (count && !names) return E_INVALIDARG;
std::unique_ptr<ReadBlobsOp> op(new (std::nothrow) ReadBlobsOp);
if (!op) return E_OUTOFMEMORY;
try {
for (uint32_t i = 0; i < count; ++i) {
if (!names[i] || !*names[i]) return E_INVALIDARG;
if (std::find(op->wanted.begin(), op->wanted.end(), names[i]) != op->wanted.end()) return E_INVALIDARG;
op->wanted.emplace_back(names[i]);
}
const auto generation = active_runtime_generation();
std::lock_guard lock(handle_mutex);
const Provider* provider = nullptr;
const auto* open = find_container(container, generation, &provider);
if (!open) return stale_handle_error(generation);
op->dir = provider->dir;
op->name = open->name;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
return begin_async_op(async, std::move(op));
}
HRESULT WINAPI read_blob_data_result(void*, void* async, size_t size, Blob* blobs, uint32_t* count) {
if (!count) return E_POINTER;
*count = 0;
return consume_async_op(async, kReadBlobsOp, [&](AsyncOp& base) {
const auto& op = static_cast<const ReadBlobsOp&>(base);
if (size < op.bytes) return kProvidedBufferTooSmall;
if (op.bytes && !blobs) return E_POINTER;
op.copy_to(blobs);
*count = static_cast<uint32_t>(op.found.size());
return S_OK;
});
}
HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, ContainerInfoCallback callback) {
if (!callback) return E_INVALIDARG;
const auto generation = active_runtime_generation();
std::vector<ContainerData> list;
try {
std::wstring dir;
{
std::lock_guard lock(handle_mutex);
const auto* open = find_provider(provider, generation);
if (!open) return stale_handle_error(generation);
dir = open->dir;
}
DirectoryLock lock(dir);
if (FAILED(lock.status())) return lock.status();
const auto hr = list_containers(dir, list);
if (FAILED(hr)) return hr;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
std::sort(list.begin(), list.end(), [](const auto& a, const auto& b) { return a.name < b.name; });
// No lock is held here, so the callback may call back into XGameSave.
for (const auto& data : list) {
const ContainerInfo info{data.name.c_str(), data.display_name.c_str(),
static_cast<uint32_t>(data.blobs.size()), data.total_size,
static_cast<time_t>(data.last_modified), false};
if (!callback(&info, context)) break;
}
return S_OK;
}
// --- COM object ---
HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!iid) return E_INVALIDARG;
constexpr GUID own = synthetic::key(synthetic::kGameSave.iid);
if (IsEqualGUID(*iid, kIUnknownIid) || IsEqualGUID(*iid, own)) {
*out = self;
return S_OK;
}
return E_NOINTERFACE;
}
// A process-lifetime singleton: reference counting has nothing to free.
ULONG WINAPI add_ref(void*) { return 1; }
ULONG WINAPI release(void*) { return 1; }
template <typename Fn>
const void* slot_fn(Fn fn) {
return reinterpret_cast<const void*>(fn);
}
constexpr size_t at(GameSaveSlot slot) { return static_cast<size_t>(slot); }
const std::array<const void*, at(GameSaveSlot::Count)> kVtbl = [] {
std::array<const void*, at(GameSaveSlot::Count)> v{};
v[at(GameSaveSlot::QueryInterface)] = slot_fn(&query_interface);
v[at(GameSaveSlot::AddRef)] = slot_fn(&add_ref);
v[at(GameSaveSlot::Release)] = slot_fn(&release);
v[at(GameSaveSlot::InitializeProviderAsync)] = slot_fn(&initialize_provider_async);
v[at(GameSaveSlot::InitializeProviderResult)] = slot_fn(&initialize_provider_result);
v[at(GameSaveSlot::CloseProvider)] = slot_fn(&close_provider);
v[at(GameSaveSlot::CreateContainer)] = slot_fn(&create_container);
v[at(GameSaveSlot::CloseContainer)] = slot_fn(&close_container);
v[at(GameSaveSlot::CreateUpdate)] = slot_fn(&create_update);
v[at(GameSaveSlot::CloseUpdate)] = slot_fn(&close_update);
v[at(GameSaveSlot::SubmitBlobWrite)] = slot_fn(&submit_blob_write);
v[at(GameSaveSlot::SubmitUpdateAsync)] = slot_fn(&submit_update_async);
v[at(GameSaveSlot::SubmitUpdateResult)] = slot_fn(&submit_update_result);
v[at(GameSaveSlot::ReadBlobDataAsync)] = slot_fn(&read_blob_data_async);
v[at(GameSaveSlot::ReadBlobDataResult)] = slot_fn(&read_blob_data_result);
v[at(GameSaveSlot::EnumerateContainerInfo)] = slot_fn(&enumerate_container_info);
return v;
}();
struct ComObject {
const void* const* vtbl;
};
const ComObject kObject{kVtbl.data()};
} // namespace
const void* const game_save_object = &kObject;
void release_game_save_state() {
std::lock_guard lock(handle_mutex);
updates.clear();
containers.clear();
providers.clear();
}
} // namespace bx::gdk
+236
View File
@@ -0,0 +1,236 @@
/*
* Offline XPackage identity and mount queries (#468).
*
* Reached only through QueryApiImpl with the BetterXen synthetic xpackage key; the key and
* the vtable slot order are in synthetic_keys.h. Nothing here is exported.
*
* Public reference (Microsoft Learn, gdk-2610, checked 2026-11-26): the XPackage members
* page, the pages for the functions below, and XPackageKind (enum class : uint32_t
* { Game, Content, PublisherContent }, so Game is 0):
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xpackage/xpackage_members
* No Microsoft header, source or binary was used.
*
* Offline behaviour: the running executable's directory stands in for the installed package.
* - The identifier is "BXPKG" + 16 hex digits of the FNV-1a hash of that directory
* (lowercased), so it is stable for a directory and differs between directories.
* XPACKAGE_IDENTIFIER_MAX_LENGTH has no published value; this identifier needs 22 bytes.
* - GetPackageKind reports Game for that identifier and ERROR_NOT_FOUND for any other.
* - Mount (the documented, deprecated XPackageMount) accepts only that identifier, and the
* mount path is the executable's directory. On Windows only content packages can be
* mounted; BetterXen allows the game's own package so titles can locate their files.
* - The last XGameRuntimeUninitialize closes every mount handle.
* - An executable path of MAX_PATH or more fails with ERROR_FILENAME_EXCED_RANGE.
*/
#include "runtime_internal.h"
#include "synthetic_keys.h"
#include <array>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <mutex>
#include <new>
#include <string>
#include <unordered_map>
namespace bx::gdk {
namespace {
using synthetic::PackageSlot;
constexpr uint32_t kPackageKindGame = 0;
constexpr HRESULT kNotFound = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
constexpr char kIdPrefix[] = "BXPKG";
constexpr size_t kIdBytes = sizeof(kIdPrefix) - 1 + 16 + 1;
HRESULT executable_directory(std::wstring& dir) {
wchar_t path[MAX_PATH];
const auto hr = executable_path(path);
if (FAILED(hr)) return hr;
wchar_t* slash = std::wcsrchr(path, L'\\');
if (!slash) return HRESULT_FROM_WIN32(ERROR_BAD_PATHNAME);
// Keep the separator of a drive root ("C:\").
slash[slash == path + 2 && path[1] == L':' ? 1 : 0] = L'\0';
dir = path;
return S_OK;
}
HRESULT current_identifier(char (&id)[kIdBytes]) {
std::wstring dir;
auto hr = executable_directory(dir);
if (FAILED(hr)) return hr;
wchar_t lower[MAX_PATH];
if (!LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, dir.c_str(), -1, lower, MAX_PATH, nullptr, nullptr, 0)) {
return HRESULT_FROM_WIN32(GetLastError());
}
std::snprintf(id, kIdBytes, "%s%016llx", kIdPrefix, static_cast<unsigned long long>(fnv1a(lower)));
return S_OK;
}
HRESULT is_current_package(const char* identifier, bool& match) {
char id[kIdBytes];
const auto hr = current_identifier(id);
match = SUCCEEDED(hr) && std::strcmp(identifier, id) == 0;
return hr;
}
struct Mount {
uint32_t generation;
std::string path; // UTF-8
};
std::mutex mount_mutex;
uintptr_t handle_counter = 0;
std::unordered_map<void*, Mount> mounts;
// Mount handles use tag 4 in bits 40-43, a range no XGameSave handle uses (game_save.cpp).
constexpr uintptr_t kMountTag = 4;
// Caller holds mount_mutex.
const Mount* find_mount(void* handle, uint32_t generation) {
const auto found = mounts.find(handle);
if (found == mounts.end() || generation == 0 || found->second.generation != generation) return nullptr;
return &found->second;
}
HRESULT stale_handle_error(uint32_t generation) {
return generation ? kRuntimeInvalidHandle : kRuntimeNotInitialized;
}
// --- Slots ---
HRESULT WINAPI get_current_process_package_identifier(void*, size_t size, char* buffer) {
if (!buffer) return E_POINTER;
if (!active_runtime_generation()) return kRuntimeNotInitialized;
char id[kIdBytes];
const auto hr = current_identifier(id);
if (FAILED(hr)) return hr;
if (size < kIdBytes) return kInsufficientBuffer;
std::memcpy(buffer, id, kIdBytes);
return S_OK;
}
HRESULT WINAPI get_package_kind(void*, const char* identifier, uint32_t* kind) {
if (!kind) return E_POINTER;
if (!identifier) return E_INVALIDARG;
if (!active_runtime_generation()) return kRuntimeNotInitialized;
bool match = false;
const auto hr = is_current_package(identifier, match);
if (FAILED(hr)) return hr;
if (!match) return kNotFound;
*kind = kPackageKindGame;
return S_OK;
}
HRESULT WINAPI mount(void*, const char* identifier, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!identifier) return E_INVALIDARG;
const auto generation = active_runtime_generation();
if (!generation) return kRuntimeNotInitialized;
bool match = false;
auto hr = is_current_package(identifier, match);
if (FAILED(hr)) return hr;
if (!match) return kNotFound;
std::wstring dir;
hr = executable_directory(dir);
if (FAILED(hr)) return hr;
const int bytes = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, dir.c_str(), -1, nullptr, 0, nullptr, nullptr);
if (bytes <= 0) return HRESULT_FROM_WIN32(GetLastError());
try {
std::string path(static_cast<size_t>(bytes), '\0');
WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, dir.c_str(), -1, path.data(), bytes, nullptr, nullptr);
path.pop_back(); // The terminator is added back on copy-out.
std::lock_guard lock(mount_mutex);
++handle_counter;
void* handle = reinterpret_cast<void*>(kMountTag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
mounts.emplace(handle, Mount{generation, std::move(path)});
*out = handle;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
return S_OK;
}
HRESULT WINAPI get_mount_path_size(void*, void* handle, size_t* size) {
if (!size) return E_POINTER;
*size = 0;
const auto generation = active_runtime_generation();
std::lock_guard lock(mount_mutex);
const auto* open = find_mount(handle, generation);
if (!open) return stale_handle_error(generation);
*size = open->path.size() + 1;
return S_OK;
}
HRESULT WINAPI get_mount_path(void*, void* handle, size_t size, char* path) {
if (!path) return E_POINTER;
const auto generation = active_runtime_generation();
std::lock_guard lock(mount_mutex);
const auto* open = find_mount(handle, generation);
if (!open) return stale_handle_error(generation);
if (size < open->path.size() + 1) return kInsufficientBuffer;
std::memcpy(path, open->path.c_str(), open->path.size() + 1);
return S_OK;
}
void WINAPI close_mount_handle(void*, void* handle) {
std::lock_guard lock(mount_mutex);
mounts.erase(handle);
}
// --- COM object ---
HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!iid) return E_INVALIDARG;
constexpr GUID own = synthetic::key(synthetic::kPackage.iid);
if (IsEqualGUID(*iid, kIUnknownIid) || IsEqualGUID(*iid, own)) {
*out = self;
return S_OK;
}
return E_NOINTERFACE;
}
// A process-lifetime singleton: reference counting has nothing to free.
ULONG WINAPI add_ref(void*) { return 1; }
ULONG WINAPI release(void*) { return 1; }
template <typename Fn>
const void* slot_fn(Fn fn) {
return reinterpret_cast<const void*>(fn);
}
constexpr size_t at(PackageSlot slot) { return static_cast<size_t>(slot); }
const std::array<const void*, at(PackageSlot::Count)> kVtbl = [] {
std::array<const void*, at(PackageSlot::Count)> v{};
v[at(PackageSlot::QueryInterface)] = slot_fn(&query_interface);
v[at(PackageSlot::AddRef)] = slot_fn(&add_ref);
v[at(PackageSlot::Release)] = slot_fn(&release);
v[at(PackageSlot::GetCurrentProcessPackageIdentifier)] = slot_fn(&get_current_process_package_identifier);
v[at(PackageSlot::GetPackageKind)] = slot_fn(&get_package_kind);
v[at(PackageSlot::Mount)] = slot_fn(&mount);
v[at(PackageSlot::GetMountPathSize)] = slot_fn(&get_mount_path_size);
v[at(PackageSlot::GetMountPath)] = slot_fn(&get_mount_path);
v[at(PackageSlot::CloseMountHandle)] = slot_fn(&close_mount_handle);
return v;
}();
struct ComObject {
const void* const* vtbl;
};
const ComObject kObject{kVtbl.data()};
} // namespace
const void* const package_object = &kObject;
void release_package_state() {
std::lock_guard lock(mount_mutex);
mounts.clear();
}
} // namespace bx::gdk
+75
View File
@@ -0,0 +1,75 @@
#pragma once
// Internal interfaces shared by the xgameruntime.dll translation units. Nothing here is exported.
#include <windows.h>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
namespace bx::gdk {
// ABI values checked against Microsoft's public PC GDK 2510.5.6322 (see xgameruntime.cpp).
constexpr HRESULT kRuntimeNotInitialized = static_cast<HRESULT>(0x89240100u);
constexpr HRESULT kRuntimeInvalidHandle = static_cast<HRESULT>(0x8924010cu);
constexpr HRESULT kIllegalMethodCall = static_cast<HRESULT>(0x8000000eu);
constexpr HRESULT kInsufficientBuffer = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
// Work for an XAsyncBlock, run on the block's work port. execute() is skipped, and the block
// completes with E_GAMERUNTIME_NOT_INITIALIZED (0x89240100), if the runtime was uninitialized
// after the operation started; an execute() that is already running finishes. A finished
// object, including its result data, is kept until its Result call consumes it, the same
// block starts another operation, or the last uninitialize. A caller that frees a block
// without calling Result leaves that result in memory until then; the retention is not
// bounded.
class AsyncOp {
public:
virtual ~AsyncOp() = default;
// Identifies the family/function, so a Result call can reject a foreign block.
virtual uint32_t kind() const = 0;
// Runs without the runtime lock held. Not called if the operation was canceled.
virtual HRESULT execute() = 0;
// Value reported by XAsyncGetResultSize after execute() succeeded.
virtual size_t result_size() const = 0;
};
// Starts op on block (an XAsyncBlock*). Returns the submission status, as XUserAddAsync does.
HRESULT begin_async_op(void* block, std::unique_ptr<AsyncOp> op);
// Checks that block holds a finished op of this kind, then calls consume while the runtime
// lock is held. The result is marked consumed only when consume succeeds, so a caller can
// retry with a larger buffer. consume must not call back into the runtime.
HRESULT consume_async_op(void* block, uint32_t kind, const std::function<HRESULT(AsyncOp&)>& consume);
// Zero while the runtime is not initialized; otherwise changes on every first initialize,
// so handles created before an uninitialize can be recognized as stale.
uint32_t active_runtime_generation();
bool is_valid_user(void* user);
// Full Windows path of the running executable.
HRESULT executable_path(wchar_t (&path)[MAX_PATH]);
// The executable's C:\bx_pls\<hash> directory (XPersistentLocalStorageGetPath), created if needed.
HRESULT title_storage_directory(wchar_t (&path)[MAX_PATH]);
// Creates path if missing. Fails if it exists and is not a plain directory.
HRESULT ensure_directory(const wchar_t* path);
// FNV-1a over UTF-16 code units, as used for the storage directory name.
uint64_t fnv1a(const wchar_t* text);
constexpr GUID kIUnknownIid = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
// COM IUnknown objects QueryApiImpl returns for the synthetic xgamesave and xpackage keys.
extern const void* const game_save_object; // game_save.cpp
extern const void* const package_object; // package.cpp
// Close every XGameSave / XPackage handle. Called by the last uninitialize, with the runtime
// lock held (the runtime lock is always taken before these files' own locks).
void release_game_save_state(); // game_save.cpp
void release_package_state(); // package.cpp
} // namespace bx::gdk
+90
View File
@@ -0,0 +1,90 @@
#pragma once
/*
* BetterXen synthetic QueryApiImpl keys: the single place to find or change them.
*
* These class and interface ids are defined by BetterXen. They are NOT Microsoft
* identifiers and were not derived from any Microsoft binary. A title linked against
* Microsoft's xgameruntime.lib will not request them. They let BetterXen's own callers
* and conformance fixtures reach the offline families through QueryApiImpl until a
* properly sourced mapping exists. To replace a family's keys, change its entry here and
* the expected values in the fixtures listed below. The fixtures keep their own copies on
* purpose, so a wrong key here fails a test instead of agreeing with itself:
* tests/conformance/test_xgameruntime/main.cpp (all families)
* tests/conformance/test_xgameruntime_saves/main.cpp (xgamesave, xpackage)
*
* Encoding: Data1 is the key below. Data2 = 0x5853 ("XS"), Data3 = 0x4000,
* Data4 = 80 00 00 00 00 00 00 01. For example, 0xB7581601 is
* {B7581601-5853-4000-8000-000000000001}.
*/
#include <windows.h>
#include <cstdint>
namespace bx::gdk::synthetic {
constexpr uint16_t kData2 = 0x5853;
constexpr uint16_t kData3 = 0x4000;
constexpr uint8_t kData4[8] = {0x80, 0, 0, 0, 0, 0, 0, 0x01};
constexpr GUID key(uint32_t data1) {
return {data1, kData2, kData3, {kData4[0], kData4[1], kData4[2], kData4[3],
kData4[4], kData4[5], kData4[6], kData4[7]}};
}
struct FamilyKey {
uint32_t clsid;
uint32_t iid;
};
// Plain function tables (#439). QueryApiImpl returns a pointer to a C struct of
// function pointers; the layouts are the *Dispatch structs in xgameruntime.cpp.
constexpr FamilyKey kTaskQueue{0xB7581001, 0xB7581002};
constexpr FamilyKey kAsync{0xB7581101, 0xB7581102};
constexpr FamilyKey kUser{0xB7581201, 0xB7581202};
constexpr FamilyKey kStore{0xB7581301, 0xB7581302};
constexpr FamilyKey kSystem{0xB7581401, 0xB7581402};
constexpr FamilyKey kPersistentLocalStorage{0xB7581501, 0xB7581502};
// COM IUnknown objects (#468). QueryApiImpl returns an object whose first member is a
// vtable pointer. Slots 0-2 are IUnknown; the remaining slots follow the enums below.
// Every slot takes the object pointer first, then the parameters of the Microsoft Learn
// function it names, in the documented order.
constexpr FamilyKey kGameSave{0xB7581601, 0xB7581602};
constexpr FamilyKey kPackage{0xB7581701, 0xB7581702};
enum class GameSaveSlot : uint32_t {
QueryInterface,
AddRef,
Release,
InitializeProviderAsync, // (XUserHandle, const char* scid, bool syncOnDemand, XAsyncBlock*)
InitializeProviderResult, // (XAsyncBlock*, XGameSaveProviderHandle*)
CloseProvider, // (XGameSaveProviderHandle)
CreateContainer, // (XGameSaveProviderHandle, const char* name, XGameSaveContainerHandle*)
CloseContainer, // (XGameSaveContainerHandle)
CreateUpdate, // (XGameSaveContainerHandle, const char* displayName, XGameSaveUpdateHandle*)
CloseUpdate, // (XGameSaveUpdateHandle)
SubmitBlobWrite, // (XGameSaveUpdateHandle, const char* blobName, const uint8_t*, size_t)
SubmitUpdateAsync, // (XGameSaveUpdateHandle, XAsyncBlock*)
SubmitUpdateResult, // (XAsyncBlock*)
ReadBlobDataAsync, // (XGameSaveContainerHandle, const char** names, uint32_t count, XAsyncBlock*)
ReadBlobDataResult, // (XAsyncBlock*, size_t, XGameSaveBlob*, uint32_t* count)
EnumerateContainerInfo, // (XGameSaveProviderHandle, void* context, XGameSaveContainerInfoCallback*)
Count,
};
enum class PackageSlot : uint32_t {
QueryInterface,
AddRef,
Release,
GetCurrentProcessPackageIdentifier, // (size_t bufferSize, char* buffer)
GetPackageKind, // (const char* packageIdentifier, XPackageKind*)
Mount, // (const char* packageIdentifier, XPackageMountHandle*)
GetMountPathSize, // (XPackageMountHandle, size_t*)
GetMountPath, // (XPackageMountHandle, size_t, char*)
CloseMountHandle, // (XPackageMountHandle)
Count,
};
} // namespace bx::gdk::synthetic
+142 -43
View File
@@ -1,4 +1,6 @@
#include "com_dispatch.h"
#include "runtime_internal.h"
#include "synthetic_keys.h"
#include "task_queue.h"
#include <condition_variable>
@@ -6,6 +8,7 @@
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <map>
#include <mutex>
#include <new>
#include <unordered_set>
@@ -18,10 +21,10 @@ namespace {
using namespace bx::gdk;
// ABI values and layouts checked against Microsoft's public PC GDK 2510.5.6322.
constexpr HRESULT runtime_not_initialized = static_cast<HRESULT>(0x89240100u);
constexpr HRESULT runtime_invalid_handle = static_cast<HRESULT>(0x8924010cu);
constexpr HRESULT illegal_method_call = static_cast<HRESULT>(0x8000000eu);
constexpr HRESULT insufficient_buffer = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
constexpr HRESULT runtime_not_initialized = kRuntimeNotInitialized;
constexpr HRESULT runtime_invalid_handle = kRuntimeInvalidHandle;
constexpr HRESULT illegal_method_call = kIllegalMethodCall;
constexpr HRESULT insufficient_buffer = kInsufficientBuffer;
struct AsyncBlock {
void* queue;
@@ -56,7 +59,8 @@ struct SpaceInfo {
uint64_t total_bytes;
};
enum class Operation : uint32_t { add_user, game_license };
// custom: an AsyncOp from another translation unit (XGameSave), see runtime_internal.h.
enum class Operation : uint32_t { add_user, game_license, custom };
struct AsyncState {
const AsyncBlock* owner;
@@ -79,6 +83,8 @@ uint64_t next_operation = 1;
uintptr_t next_handle = 2;
std::unordered_set<void*> users;
std::unordered_set<void*> stores;
// Finished custom operations awaiting their Result call, keyed by AsyncState::sequence.
std::map<uint64_t, std::unique_ptr<AsyncOp>> finished_ops;
HRESULT create_handle(std::unordered_set<void*>& handles, void** out) {
auto handle = reinterpret_cast<void*>(next_handle);
@@ -159,10 +165,12 @@ class AsyncTask final : public Task {
public:
AsyncBlock* block;
Operation operation;
std::unique_ptr<AsyncOp> op;
std::unique_ptr<CompletionTask> completion;
bool queued = false;
AsyncTask(AsyncBlock* block, Operation operation) : block(block), operation(operation) {}
AsyncTask(AsyncBlock* block, Operation operation, std::unique_ptr<AsyncOp> op)
: block(block), operation(operation), op(std::move(op)) {}
~AsyncTask() override {
if (!queued) return;
@@ -185,11 +193,34 @@ public:
private:
void finish(const QueueRef& queue, bool canceled) {
const bool entitled = !canceled && operation == Operation::game_license && fixture_entitlement();
bool cancel_requested;
bool stale;
{
std::lock_guard lock(state_mutex);
const auto state = read_state(block);
cancel_requested = state.cancel_requested;
stale = !runtime_refs || state.runtime_generation != runtime_generation;
}
// The block stays E_PENDING meanwhile, so the caller cannot reuse it. Once an op has
// run, a later XAsyncCancel or uninitialize cannot undo it, so its own status is
// reported. An op whose runtime was uninitialized before it ran is not run.
const bool executed = op && !canceled && !cancel_requested && !stale;
const HRESULT op_status = executed ? op->execute() : S_OK;
{
std::lock_guard lock(state_mutex);
auto state = read_state(block);
state.status = (canceled || state.cancel_requested) ? E_ABORT : S_OK;
state.status = executed ? op_status
: canceled || state.cancel_requested ? E_ABORT
: op && stale ? runtime_not_initialized
: S_OK;
state.entitled = entitled;
if (op && SUCCEEDED(state.status) && state.runtime_generation == runtime_generation && runtime_refs) {
try {
finished_ops[state.sequence] = std::move(op);
} catch (const std::bad_alloc&) {
state.status = E_OUTOFMEMORY;
}
}
if (completion) completion->sequence = state.sequence;
queued = false;
write_state(block, state);
@@ -198,12 +229,12 @@ private:
}
};
HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr) {
HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr, std::unique_ptr<AsyncOp> op = nullptr) {
if (!block) return E_POINTER;
const auto queue = acquire_queue(block->queue);
if (!queue) return block->queue ? E_HANDLE : E_OUTOFMEMORY;
auto work = std::unique_ptr<AsyncTask>(new (std::nothrow) AsyncTask(block, operation));
auto work = std::unique_ptr<AsyncTask>(new (std::nothrow) AsyncTask(block, operation, std::move(op)));
if (!work) return E_OUTOFMEMORY;
if (block->callback) {
work->completion.reset(new (std::nothrow) CompletionTask(block));
@@ -222,6 +253,8 @@ HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr) {
callback_running(previous.sequence, GetCurrentThreadId()))) {
return illegal_method_call;
}
// An unconsumed result of an earlier operation on this block is abandoned.
if (previous.owner == block) finished_ops.erase(previous.sequence);
write_state(block, {block, next_operation++, E_PENDING, operation, runtime_generation,
false, block->callback != nullptr, false, false});
work->queued = true;
@@ -277,19 +310,6 @@ bool fixture_entitlement() {
GetProcAddress(GetModuleHandleW(nullptr), "BetterXenSyntheticStoreFixture") != nullptr;
}
HRESULT ensure_directory(const wchar_t* path) {
if (CreateDirectoryW(path, nullptr)) return S_OK;
const auto error = GetLastError();
if (error != ERROR_ALREADY_EXISTS) return HRESULT_FROM_WIN32(error);
const auto attributes = GetFileAttributesW(path);
if (attributes == INVALID_FILE_ATTRIBUTES) return HRESULT_FROM_WIN32(GetLastError());
if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) != FILE_ATTRIBUTE_DIRECTORY) {
return HRESULT_FROM_WIN32(ERROR_DIRECTORY);
}
return S_OK;
}
HRESULT storage_path(wchar_t (&path)[MAX_PATH]) {
wchar_t module[MAX_PATH];
const wchar_t* name = nullptr;
@@ -302,11 +322,7 @@ HRESULT storage_path(wchar_t (&path)[MAX_PATH]) {
normalized, MAX_PATH, nullptr, nullptr, 0)) {
return HRESULT_FROM_WIN32(GetLastError());
}
uint64_t path_id = 14695981039346656037ULL;
for (auto* ch = normalized; *ch; ++ch) {
path_id ^= static_cast<uint16_t>(*ch);
path_id *= 1099511628211ULL;
}
const uint64_t path_id = bx::gdk::fnv1a(normalized);
const auto length = std::swprintf(path, MAX_PATH, L"%ls\\%016llx", storage_root,
static_cast<unsigned long long>(path_id));
return length < 0 ? HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE) : S_OK;
@@ -323,6 +339,9 @@ bool release_runtime_ref() {
if (!--runtime_refs) {
users.clear();
stores.clear();
finished_ops.clear();
bx::gdk::release_game_save_state();
bx::gdk::release_package_state();
}
return true;
}
@@ -369,13 +388,10 @@ struct ApiInitOptions {
};
static_assert(offsetof(ApiInitOptions, game_config) == 8);
constexpr uint16_t family_data2 = 0x5853;
constexpr uint16_t family_data3 = 0x4000;
// The synthetic key encoding is defined in synthetic_keys.h.
bool synthetic_guid(const GUID* guid) {
return guid->Data2 == family_data2 && guid->Data3 == family_data3 && guid->Data4[0] == 0x80 &&
guid->Data4[1] == 0 && guid->Data4[2] == 0 && guid->Data4[3] == 0 && guid->Data4[4] == 0 &&
guid->Data4[5] == 0 && guid->Data4[6] == 0 && guid->Data4[7] == 1;
return guid->Data2 == synthetic::kData2 && guid->Data3 == synthetic::kData3 &&
std::memcmp(guid->Data4, synthetic::kData4, sizeof(synthetic::kData4)) == 0;
}
void format_guid(char* dst, size_t cap, const GUID* guid) {
@@ -459,6 +475,75 @@ HRESULT check_loader_versions(uint32_t gdk_ver, uint32_t gs_ver, const char* eve
} // namespace
namespace bx::gdk {
HRESULT ensure_directory(const wchar_t* path) {
if (CreateDirectoryW(path, nullptr)) return S_OK;
const auto error = GetLastError();
if (error != ERROR_ALREADY_EXISTS) return HRESULT_FROM_WIN32(error);
const auto attributes = GetFileAttributesW(path);
if (attributes == INVALID_FILE_ATTRIBUTES) return HRESULT_FROM_WIN32(GetLastError());
if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) != FILE_ATTRIBUTE_DIRECTORY) {
return HRESULT_FROM_WIN32(ERROR_DIRECTORY);
}
return S_OK;
}
uint64_t fnv1a(const wchar_t* text) {
uint64_t hash = 14695981039346656037ULL;
for (auto* ch = text; *ch; ++ch) {
hash ^= static_cast<uint16_t>(*ch);
hash *= 1099511628211ULL;
}
return hash;
}
HRESULT executable_path(wchar_t (&path)[MAX_PATH]) {
const wchar_t* name = nullptr;
return executable_name(path, name);
}
HRESULT title_storage_directory(wchar_t (&path)[MAX_PATH]) {
const auto hr = storage_path(path);
return FAILED(hr) ? hr : create_storage(path);
}
uint32_t active_runtime_generation() {
std::lock_guard lock(state_mutex);
return runtime_refs ? runtime_generation : 0;
}
bool is_valid_user(void* user) {
std::lock_guard lock(state_mutex);
return runtime_refs && users.contains(user);
}
HRESULT begin_async_op(void* block, std::unique_ptr<AsyncOp> op) {
if (!op) return E_OUTOFMEMORY;
return begin(static_cast<AsyncBlock*>(block), Operation::custom, nullptr, std::move(op));
}
HRESULT consume_async_op(void* block, uint32_t kind, const std::function<HRESULT(AsyncOp&)>& consume) {
auto* async = static_cast<AsyncBlock*>(block);
std::lock_guard lock(state_mutex);
AsyncState state{};
const auto hr = check_result(async, Operation::custom, state);
if (FAILED(hr)) return hr;
const auto found = finished_ops.find(state.sequence);
if (found == finished_ops.end() || found->second->kind() != kind) return illegal_method_call;
const auto result = consume(*found->second);
if (SUCCEEDED(result)) {
finished_ops.erase(found);
state.result_consumed = true;
write_state(async, state);
}
return result;
}
} // namespace bx::gdk
extern "C" {
HRESULT WINAPI XGameRuntimeInitialize() {
@@ -513,7 +598,16 @@ HRESULT WINAPI XAsyncGetResultSize(AsyncBlock* block, size_t* size) {
const auto state = read_state(block);
if (state.owner != block || state.result_consumed) return illegal_method_call;
if (SUCCEEDED(state.status)) {
*size = state.operation == Operation::add_user ? sizeof(void*) : sizeof(GameLicense);
switch (state.operation) {
case Operation::add_user: *size = sizeof(void*); break;
case Operation::game_license: *size = sizeof(GameLicense); break;
case Operation::custom: {
const auto found = finished_ops.find(state.sequence);
if (found == finished_ops.end()) return illegal_method_call;
*size = found->second->result_size();
break;
}
}
}
return state.status;
}
@@ -802,17 +896,21 @@ struct Family {
uint32_t iid;
const char* name;
const void* table;
bool com; // table is a COM object, so IID_IUnknown also reaches it
};
// Synthetic BetterXen dispatch keys, not Microsoft CLSIDs.
// Data2 = 0x5853, Data3 = 0x4000, Data4 = 80 00 00 00 00 00 00 01.
// Synthetic BetterXen dispatch keys, not Microsoft CLSIDs. All keys and the COM slot
// orders live in synthetic_keys.h.
const Family families[] = {
{0xB7581001, 0xB7581002, "xtaskqueue", &task_queue_api},
{0xB7581101, 0xB7581102, "xasync", &async_api},
{0xB7581201, 0xB7581202, "xuser", &user_api},
{0xB7581301, 0xB7581302, "xstore", &store_api},
{0xB7581401, 0xB7581402, "xsystem", &system_api},
{0xB7581501, 0xB7581502, "xpersistentlocalstorage", &storage_api},
{synthetic::kTaskQueue.clsid, synthetic::kTaskQueue.iid, "xtaskqueue", &task_queue_api, false},
{synthetic::kAsync.clsid, synthetic::kAsync.iid, "xasync", &async_api, false},
{synthetic::kUser.clsid, synthetic::kUser.iid, "xuser", &user_api, false},
{synthetic::kStore.clsid, synthetic::kStore.iid, "xstore", &store_api, false},
{synthetic::kSystem.clsid, synthetic::kSystem.iid, "xsystem", &system_api, false},
{synthetic::kPersistentLocalStorage.clsid, synthetic::kPersistentLocalStorage.iid, "xpersistentlocalstorage",
&storage_api, false},
{synthetic::kGameSave.clsid, synthetic::kGameSave.iid, "xgamesave", bx::gdk::game_save_object, true},
{synthetic::kPackage.clsid, synthetic::kPackage.iid, "xpackage", bx::gdk::package_object, true},
};
const Family* find_family(const GUID* clsid) {
@@ -844,7 +942,8 @@ HRESULT WINAPI QueryApiImpl(const GUID* clsid, const GUID* iid, void** out) {
}
const auto* family = find_family(clsid);
if (family && synthetic_guid(iid) && iid->Data1 == family->iid) {
if (family && ((synthetic_guid(iid) && iid->Data1 == family->iid) ||
(family->com && IsEqualGUID(*iid, bx::gdk::kIUnknownIid)))) {
*out = const_cast<void*>(family->table);
char detail[64];
std::snprintf(detail, sizeof(detail), "dispatch family=%s", family->name);
@@ -0,0 +1,2 @@
add_executable(test_xgameruntime_saves main.cpp)
target_link_libraries(test_xgameruntime_saves PRIVATE xgameruntime kernel32 shell32)
@@ -0,0 +1,880 @@
// Offline XGameSave and XPackage through QueryApiImpl (#468).
//
// This fixture declares its own copies of the BetterXen synthetic keys and slot orders, of
// the public structures, and of the documented storage layout, instead of including the
// shim's headers, so a mistake there fails here. The keys must match
// shims/xgameruntime/synthetic_keys.h. Structure layouts and error values follow the Microsoft
// Learn XGameSave and XPackage reference pages; the file layout and naming follow the header
// comment of shims/xgameruntime/game_save.cpp.
//
// Run with no arguments. "--writer <id> <count> <event>" is the child mode used by the
// cross-process check.
#include <windows.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <ctime>
#include <string>
#include <vector>
namespace {
#define CHECK(expr) do { \
if (!(expr)) { std::fprintf(stderr, "FAIL: test_xgameruntime_saves line %d: %s\n", __LINE__, #expr); std::exit(1); } \
} while (false)
struct Async {
void* queue;
void* context;
void (CALLBACK* callback)(Async*);
unsigned char reserved[32];
};
struct ContainerInfo { // XGameSaveContainerInfo
const char* name;
const char* display_name;
uint32_t blob_count;
uint64_t total_size;
time_t last_modified_time;
bool needs_sync;
};
static_assert(offsetof(ContainerInfo, total_size) == 24 && offsetof(ContainerInfo, needs_sync) == 40);
struct Blob { // XGameSaveBlob { XGameSaveBlobInfo { name, size }, data }
const char* name;
uint32_t size;
uint8_t* data;
};
static_assert(sizeof(Blob) == 24 && offsetof(Blob, data) == 16);
extern "C" {
HRESULT WINAPI XGameRuntimeInitialize();
void WINAPI XGameRuntimeUninitialize();
HRESULT WINAPI XTaskQueueCreate(uint32_t, uint32_t, void**);
void WINAPI XTaskQueueCloseHandle(void*);
bool WINAPI XTaskQueueDispatch(void*, uint32_t, uint32_t);
HRESULT WINAPI XUserAddAsync(uint32_t, Async*);
HRESULT WINAPI XUserAddResult(Async*, void**);
void WINAPI XUserCloseHandle(void*);
HRESULT WINAPI XAsyncGetStatus(Async*, bool);
HRESULT WINAPI XAsyncGetResultSize(Async*, size_t*);
void WINAPI XAsyncCancel(Async*);
HRESULT WINAPI XPersistentLocalStorageGetPath(size_t, char*, size_t*);
HRESULT WINAPI QueryApiImpl(const GUID*, const GUID*, void**);
}
// Expected values, from the public reference pages and the existing runtime.
constexpr HRESULT kInvalidContainerName = static_cast<HRESULT>(0x80830001u);
constexpr HRESULT kUpdateTooBig = static_cast<HRESULT>(0x80830005u);
constexpr HRESULT kBufferTooSmall = static_cast<HRESULT>(0x80830007u);
constexpr HRESULT kBlobNotFound = static_cast<HRESULT>(0x80830008u);
constexpr HRESULT kInvalidHandle = static_cast<HRESULT>(0x8924010cu);
constexpr HRESULT kNotInitialized = static_cast<HRESULT>(0x89240100u);
constexpr HRESULT kIllegalCall = static_cast<HRESULT>(0x8000000eu);
constexpr HRESULT kInsufficient = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
constexpr HRESULT kNotFound = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
constexpr HRESULT kCorrupt = HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT);
constexpr uint32_t kManual = 0, kWork = 0;
constexpr size_t kMiB16 = 16u * 1024u * 1024u;
constexpr const char* kScid = "00000000-0000-0000-0000-000000000000";
GUID synthetic(uint32_t data1) {
return {data1, 0x5853, 0x4000, {0x80, 0, 0, 0, 0, 0, 0, 0x01}};
}
// Slot numbers from the synthetic_keys.h contract, written out independently.
enum : int {
kQueryInterface = 0, kAddRef = 1, kRelease = 2,
kInitAsync = 3, kInitResult = 4, kCloseProvider = 5, kCreateContainer = 6, kCloseContainer = 7,
kCreateUpdate = 8, kCloseUpdate = 9, kSubmitBlobWrite = 10, kSubmitUpdateAsync = 11,
kSubmitUpdateResult = 12, kReadAsync = 13, kReadResult = 14, kEnumerate = 15,
};
enum : int { kGetId = 3, kGetKind = 4, kMount = 5, kGetMountPathSize = 6, kGetMountPath = 7, kCloseMount = 8 };
template <typename Fn>
Fn slot(void* object, int index) {
void** vtbl = *static_cast<void***>(object);
Fn fn;
std::memcpy(&fn, &vtbl[index], sizeof(fn));
return fn;
}
using QiFn = HRESULT(WINAPI*)(void*, const GUID*, void**);
using RefFn = ULONG(WINAPI*)(void*);
using InitAsyncFn = HRESULT(WINAPI*)(void*, void*, const char*, bool, Async*);
using InitResultFn = HRESULT(WINAPI*)(void*, Async*, void**);
using CloseFn = void(WINAPI*)(void*, void*);
using CreateContainerFn = HRESULT(WINAPI*)(void*, void*, const char*, void**);
using CreateUpdateFn = HRESULT(WINAPI*)(void*, void*, const char*, void**);
using BlobWriteFn = HRESULT(WINAPI*)(void*, void*, const char*, const uint8_t*, size_t);
using SubmitAsyncFn = HRESULT(WINAPI*)(void*, void*, Async*);
using AsyncResultFn = HRESULT(WINAPI*)(void*, Async*);
using ReadAsyncFn = HRESULT(WINAPI*)(void*, void*, const char**, uint32_t, Async*);
using ReadResultFn = HRESULT(WINAPI*)(void*, Async*, size_t, Blob*, uint32_t*);
using InfoCallback = bool(CALLBACK*)(const ContainerInfo*, void*);
using EnumerateFn = HRESULT(WINAPI*)(void*, void*, void*, InfoCallback);
using GetIdFn = HRESULT(WINAPI*)(void*, size_t, char*);
using GetKindFn = HRESULT(WINAPI*)(void*, const char*, uint32_t*);
using MountFn = HRESULT(WINAPI*)(void*, const char*, void**);
using PathSizeFn = HRESULT(WINAPI*)(void*, void*, size_t*);
using PathFn = HRESULT(WINAPI*)(void*, void*, size_t, char*);
using Blobs = std::vector<std::pair<std::string, std::string>>;
void* query(uint32_t clsid, uint32_t iid) {
const GUID c = synthetic(clsid), i = synthetic(iid);
void* api = nullptr;
CHECK(QueryApiImpl(&c, &i, &api) == S_OK && api);
return api;
}
void* add_user(void* queue) {
Async async{queue, nullptr, nullptr, {}};
void* user = nullptr;
CHECK(XUserAddAsync(0, &async) == S_OK);
if (queue) CHECK(XTaskQueueDispatch(queue, kWork, 0));
else CHECK(XAsyncGetStatus(&async, true) == S_OK);
CHECK(XUserAddResult(&async, &user) == S_OK && user);
return user;
}
// queue null: the process task queue (thread pool); otherwise a manual queue run inline.
struct Saves {
void* api;
void* queue;
void wait(Async& async) const {
if (queue) CHECK(XTaskQueueDispatch(queue, kWork, 0));
else XAsyncGetStatus(&async, true);
}
void* provider(void* user, const char* scid = kScid) const {
Async async{queue, nullptr, nullptr, {}};
CHECK(slot<InitAsyncFn>(api, kInitAsync)(api, user, scid, false, &async) == S_OK);
if (queue) CHECK(XAsyncGetStatus(&async, false) == E_PENDING);
wait(async);
size_t size = 0;
CHECK(XAsyncGetResultSize(&async, &size) == S_OK && size == sizeof(void*));
void* provider = nullptr;
CHECK(slot<InitResultFn>(api, kInitResult)(api, &async, &provider) == S_OK && provider);
void* again = nullptr;
CHECK(slot<InitResultFn>(api, kInitResult)(api, &async, &again) == kIllegalCall && !again);
return provider;
}
void* container(void* provider, const char* name) const {
void* handle = nullptr;
CHECK(slot<CreateContainerFn>(api, kCreateContainer)(api, provider, name, &handle) == S_OK && handle);
return handle;
}
void* update(void* container, const char* display_name) const {
void* handle = nullptr;
CHECK(slot<CreateUpdateFn>(api, kCreateUpdate)(api, container, display_name, &handle) == S_OK && handle);
return handle;
}
HRESULT write(void* update, const char* blob, const void* data, size_t size) const {
return slot<BlobWriteFn>(api, kSubmitBlobWrite)(api, update, blob, static_cast<const uint8_t*>(data), size);
}
HRESULT submit_status(void* update) const {
Async async{queue, nullptr, nullptr, {}};
const auto hr = slot<SubmitAsyncFn>(api, kSubmitUpdateAsync)(api, update, &async);
if (FAILED(hr)) return hr;
wait(async);
const auto status = XAsyncGetStatus(&async, false);
CHECK(slot<AsyncResultFn>(api, kSubmitUpdateResult)(api, &async) == status);
return status;
}
void submit(void* update) const {
const auto status = submit_status(update);
if (status != S_OK) std::fprintf(stderr, "submit status 0x%08lx\n", static_cast<unsigned long>(status));
CHECK(status == S_OK);
}
// One update writing one blob, submitted and closed.
void put(void* container, const char* blob, const std::string& data) const {
void* staged = update(container, nullptr);
CHECK(write(staged, blob, data.data(), data.size()) == S_OK);
submit(staged);
close(kCloseUpdate, staged);
}
void close(int which, void* handle) const { slot<CloseFn>(api, which)(api, handle); }
// Reads blobs (all when names is empty) and returns them as name -> bytes.
Blobs read(void* container, std::vector<const char*> names) const {
Async async{queue, nullptr, nullptr, {}};
CHECK(slot<ReadAsyncFn>(api, kReadAsync)(api, container, names.empty() ? nullptr : names.data(),
static_cast<uint32_t>(names.size()), &async) == S_OK);
wait(async);
size_t size = 0;
CHECK(XAsyncGetResultSize(&async, &size) == S_OK);
std::vector<unsigned char> buffer(size + 16, 0xCD);
auto* blobs = reinterpret_cast<Blob*>(buffer.data());
uint32_t count = 7;
const auto read_result = slot<ReadResultFn>(api, kReadResult);
if (size) CHECK(read_result(api, &async, size - 1, blobs, &count) == kBufferTooSmall && count == 0);
CHECK(read_result(api, &async, size, size ? blobs : nullptr, &count) == S_OK);
uint32_t consumed = 7;
CHECK(read_result(api, &async, size, blobs, &consumed) == kIllegalCall && consumed == 0);
for (size_t i = size; i < buffer.size(); ++i) CHECK(buffer[i] == 0xCD);
Blobs out;
size_t expected = count * sizeof(Blob);
const auto* base = reinterpret_cast<const unsigned char*>(buffer.data());
for (uint32_t i = 0; i < count; ++i) {
CHECK(reinterpret_cast<const unsigned char*>(blobs[i].name) >= base &&
reinterpret_cast<const unsigned char*>(blobs[i].name) < base + size);
CHECK(blobs[i].size == 0 || (blobs[i].data >= base && blobs[i].data + blobs[i].size <= base + size));
out.emplace_back(blobs[i].name, std::string(reinterpret_cast<const char*>(blobs[i].data), blobs[i].size));
expected += std::strlen(blobs[i].name) + 1 + blobs[i].size;
}
CHECK(expected == size);
return out;
}
HRESULT read_status(void* container, std::vector<const char*> names) const {
Async async{queue, nullptr, nullptr, {}};
const auto hr = slot<ReadAsyncFn>(api, kReadAsync)(api, container, names.empty() ? nullptr : names.data(),
static_cast<uint32_t>(names.size()), &async);
if (FAILED(hr)) return hr;
wait(async);
uint32_t count = 0;
const auto status = XAsyncGetStatus(&async, false);
size_t size = 0;
if (SUCCEEDED(status)) CHECK(XAsyncGetResultSize(&async, &size) == S_OK);
std::vector<unsigned char> buffer(size);
CHECK(slot<ReadResultFn>(api, kReadResult)(api, &async, size,
size ? reinterpret_cast<Blob*>(buffer.data()) : nullptr,
&count) == status);
return status;
}
};
const std::string* find_blob(const Blobs& blobs, const char* name) {
for (const auto& [blob, bytes] : blobs) {
if (blob == name) return &bytes;
}
return nullptr;
}
struct Seen {
std::string name, display_name;
uint32_t blob_count;
uint64_t total_size;
time_t modified;
bool needs_sync;
};
struct Listing {
std::vector<Seen> seen;
size_t stop_after = SIZE_MAX;
};
bool CALLBACK collect(const ContainerInfo* info, void* context) {
auto& listing = *static_cast<Listing*>(context);
listing.seen.push_back({info->name, info->display_name, info->blob_count, info->total_size,
info->last_modified_time, info->needs_sync});
return listing.seen.size() < listing.stop_after;
}
Listing list(const Saves& saves, void* provider) {
Listing listing;
CHECK(slot<EnumerateFn>(saves.api, kEnumerate)(saves.api, provider, &listing, collect) == S_OK);
return listing;
}
// --- The documented storage layout, re-derived here ---
// FNV-1a (64-bit) over each byte widened to a UTF-16 code unit, printed as 16 hex digits.
std::string hex_id(const std::string& text) {
uint64_t hash = 14695981039346656037ULL;
for (unsigned char c : text) {
hash ^= c;
hash *= 1099511628211ULL;
}
char out[17];
std::snprintf(out, sizeof(out), "%016llx", static_cast<unsigned long long>(hash));
return out;
}
std::string saves_directory(const char* scid) {
char path[MAX_PATH * 4]{};
CHECK(XPersistentLocalStorageGetPath(sizeof(path), path, nullptr) == S_OK);
return std::string(path) + "\\saves\\" + hex_id(scid);
}
std::string container_path(const std::string& dir, const std::string& name) {
return dir + "\\" + hex_id(name) + ".bxgs";
}
void put32(std::string& out, uint32_t value) {
for (int i = 0; i < 4; ++i) out.push_back(static_cast<char>(value >> (8 * i)));
}
void put_str(std::string& out, const std::string& text) {
put32(out, static_cast<uint32_t>(text.size()));
out += text;
}
// "BXGS", version 1, name, display name, i64 time, blob count, then name / size / bytes.
std::string container_bytes(const std::string& name, const std::vector<std::pair<std::string, std::string>>& blobs) {
std::string out = "BXGS";
put32(out, 1);
put_str(out, name);
put_str(out, "crafted");
put32(out, 1700000000);
put32(out, 0);
put32(out, static_cast<uint32_t>(blobs.size()));
for (const auto& [blob, data] : blobs) {
put_str(out, blob);
put_str(out, data);
}
return out;
}
void write_file(const std::string& path, const std::string& bytes) {
const HANDLE file = CreateFileA(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
nullptr);
CHECK(file != INVALID_HANDLE_VALUE);
DWORD wrote = 0;
CHECK(WriteFile(file, bytes.data(), static_cast<DWORD>(bytes.size()), &wrote, nullptr) && wrote == bytes.size());
CHECK(CloseHandle(file));
}
// Files matching pattern in dir; optionally deletes them.
size_t files(const std::string& dir, const char* pattern, bool remove) {
WIN32_FIND_DATAA found;
const HANDLE search = FindFirstFileA((dir + "\\" + pattern).c_str(), &found);
if (search == INVALID_HANDLE_VALUE) return 0;
size_t count = 0;
do {
if (found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
++count;
if (remove) CHECK(DeleteFileA((dir + "\\" + found.cFileName).c_str()));
} while (FindNextFileA(search, &found));
FindClose(search);
return count;
}
void check_com(void* object, const GUID& own, const GUID& other) {
const GUID iunknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
void* out = nullptr;
CHECK(slot<QiFn>(object, kQueryInterface)(object, &iunknown, &out) == S_OK && out == object);
CHECK(slot<QiFn>(object, kQueryInterface)(object, &own, &out) == S_OK && out == object);
CHECK(slot<QiFn>(object, kQueryInterface)(object, &other, &out) == E_NOINTERFACE && !out);
CHECK(slot<QiFn>(object, kQueryInterface)(object, &own, nullptr) == E_POINTER);
CHECK(slot<RefFn>(object, kAddRef)(object) >= 1 && slot<RefFn>(object, kRelease)(object) >= 1);
}
// Committed private memory, summed over the address space (Wine reports PrivateUsage as 0).
uint64_t private_bytes() {
uint64_t total = 0;
MEMORY_BASIC_INFORMATION region{};
for (auto* at = static_cast<const char*>(nullptr);
VirtualQuery(at, &region, sizeof(region)) == sizeof(region);
at = static_cast<const char*>(region.BaseAddress) + region.RegionSize) {
if (region.State == MEM_COMMIT && region.Type == MEM_PRIVATE) total += region.RegionSize;
if (region.RegionSize == 0) break;
}
return total;
}
std::string utf8(const wchar_t* text) {
const int bytes = WideCharToMultiByte(CP_UTF8, 0, text, -1, nullptr, 0, nullptr, nullptr);
CHECK(bytes > 0);
std::string out(static_cast<size_t>(bytes), '\0');
WideCharToMultiByte(CP_UTF8, 0, text, -1, out.data(), bytes, nullptr, nullptr);
out.pop_back();
return out;
}
// --- Concurrency ---
constexpr char kShared[] = "shared/race";
struct ThreadJob {
void* api;
void* container;
int id;
int count;
};
DWORD WINAPI thread_writer(void* context) {
const auto& job = *static_cast<ThreadJob*>(context);
const Saves saves{job.api, nullptr};
for (int k = 0; k < job.count; ++k) {
char blob[32];
std::snprintf(blob, sizeof(blob), "t%d_%d", job.id, k);
saves.put(job.container, blob, blob);
}
return 0;
}
// Cross-process payload: the blob name, then padding to 64 KiB so each rewrite takes a while.
std::string payload(const char* blob) {
std::string data(blob);
data.resize(64 * 1024, '.');
return data;
}
// Child process: submits count blobs "w<id>_<k>" to kShared once the parent's event is set.
int writer_main(int id, int count, const wchar_t* event_name) {
CHECK(XGameRuntimeInitialize() == S_OK);
const Saves saves{query(0xB7581601, 0xB7581602), nullptr};
void* user = add_user(nullptr);
void* provider = saves.provider(user);
void* container = saves.container(provider, kShared);
const HANDLE go = OpenEventW(SYNCHRONIZE, FALSE, event_name);
CHECK(go && WaitForSingleObject(go, 30000) == WAIT_OBJECT_0);
CloseHandle(go);
for (int k = 0; k < count; ++k) {
char blob[32];
std::snprintf(blob, sizeof(blob), "w%d_%d", id, k);
saves.put(container, blob, payload(blob));
}
XGameRuntimeUninitialize();
return 0;
}
void check_blobs(const Blobs& blobs, char prefix, int writers, int count) {
for (int id = 0; id < writers; ++id) {
for (int k = 0; k < count; ++k) {
char blob[32];
std::snprintf(blob, sizeof(blob), "%c%d_%d", prefix, id, k);
const auto* data = find_blob(blobs, blob);
CHECK(data && *data == (prefix == 'w' ? payload(blob) : std::string(blob)));
}
}
}
} // namespace
int main() {
int argc = 0;
wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc);
if (argc == 5 && std::wcscmp(argv[1], L"--writer") == 0) {
return writer_main(std::wcstol(argv[2], nullptr, 10), std::wcstol(argv[3], nullptr, 10), argv[4]);
}
const time_t started = std::time(nullptr);
CHECK(XGameRuntimeInitialize() == S_OK);
// --- QueryApiImpl reaches both families as COM objects ---
const GUID save_clsid = synthetic(0xB7581601), save_iid = synthetic(0xB7581602);
const GUID package_clsid = synthetic(0xB7581701), package_iid = synthetic(0xB7581702);
const GUID iunknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
void* api = query(0xB7581601, 0xB7581602);
void* package = query(0xB7581701, 0xB7581702);
CHECK(package != api);
void* wrong = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
CHECK(QueryApiImpl(&save_clsid, &package_iid, &wrong) == E_NOINTERFACE && !wrong);
void* via_unknown = nullptr;
CHECK(QueryApiImpl(&save_clsid, &iunknown, &via_unknown) == S_OK && via_unknown == api);
CHECK(QueryApiImpl(&package_clsid, &iunknown, &via_unknown) == S_OK && via_unknown == package);
check_com(api, save_iid, package_iid);
check_com(package, package_iid, save_iid);
void* queue = nullptr;
CHECK(XTaskQueueCreate(kManual, kManual, &queue) == S_OK && queue);
const Saves saves{api, queue};
void* user = add_user(queue);
const std::string dir = saves_directory(kScid);
const std::string other_dir = saves_directory("scid-b");
files(dir, "*", true);
files(other_dir, "*", true);
// --- Provider ---
Async async{queue, nullptr, nullptr, {}};
const auto init_async = slot<InitAsyncFn>(api, kInitAsync);
CHECK(init_async(api, nullptr, kScid, false, &async) == kInvalidHandle);
CHECK(init_async(api, user, nullptr, false, &async) == E_INVALIDARG);
CHECK(init_async(api, user, kScid, false, nullptr) == E_POINTER);
void* provider = saves.provider(user);
// --- Container names (XGameSaveCreateContainer rules) ---
const auto create_container = slot<CreateContainerFn>(api, kCreateContainer);
const std::string too_long(257, 'a');
for (const char* bad : {"", "a..b", "trail.", "has space", "dir.x/file", "dir/", "semi;colon", too_long.c_str()}) {
void* handle = nullptr;
CHECK(create_container(api, provider, bad, &handle) == kInvalidContainerName && !handle);
}
void* handle = nullptr;
CHECK(create_container(api, provider, nullptr, &handle) == kInvalidContainerName);
CHECK(create_container(api, nullptr, "slot", &handle) == kInvalidHandle);
const std::string longest(256, 'a');
for (const char* good : {"slot_1", "profiles/main", "/a", "a-b.c_d", longest.c_str()}) {
saves.close(kCloseContainer, saves.container(provider, good));
}
// --- A container that was never submitted ---
void* main_container = saves.container(provider, "profiles/main");
CHECK(saves.read(main_container, {}).empty());
CHECK(saves.read_status(main_container, {"progress"}) == kBlobNotFound);
CHECK(saves.read_status(main_container, {"progress", "progress"}) == E_INVALIDARG);
{
Async read{queue, nullptr, nullptr, {}};
CHECK(slot<ReadAsyncFn>(api, kReadAsync)(api, main_container, nullptr, 1, &read) == E_INVALIDARG);
}
CHECK(files(dir, "*.bxgs", false) == 0);
// --- Write, then read back ---
std::string progress(300, '\0');
for (size_t i = 0; i < progress.size(); ++i) progress[i] = static_cast<char>(i * 7 + 3);
const std::string settings = "volume=7";
void* update = saves.update(main_container, "Main profile");
CHECK(saves.write(update, "progress", progress.data(), progress.size()) == S_OK);
CHECK(saves.write(update, "progress", progress.data(), progress.size()) == E_INVALIDARG);
CHECK(saves.write(update, "", "x", 1) == E_INVALIDARG);
CHECK(saves.write(update, std::string(257, 'n').c_str(), "x", 1) == E_INVALIDARG); // 256-byte name limit
CHECK(saves.write(update, "settings", settings.data(), settings.size()) == S_OK);
{
Async submit{queue, nullptr, nullptr, {}};
CHECK(slot<SubmitAsyncFn>(api, kSubmitUpdateAsync)(api, update, &submit) == S_OK);
Async twice{queue, nullptr, nullptr, {}};
CHECK(slot<SubmitAsyncFn>(api, kSubmitUpdateAsync)(api, update, &twice) == kIllegalCall); // pending
CHECK(saves.write(update, "late", "x", 1) == kIllegalCall);
saves.wait(submit);
size_t size = 1;
CHECK(XAsyncGetResultSize(&submit, &size) == S_OK && size == 0);
CHECK(slot<AsyncResultFn>(api, kSubmitUpdateResult)(api, &submit) == S_OK);
}
saves.close(kCloseUpdate, update);
CHECK(saves.write(update, "closed", "x", 1) == kInvalidHandle); // CloseUpdate closes it
auto blobs = saves.read(main_container, {});
CHECK(blobs.size() == 2);
CHECK(find_blob(blobs, "progress") && *find_blob(blobs, "progress") == progress);
CHECK(find_blob(blobs, "settings") && *find_blob(blobs, "settings") == settings);
blobs = saves.read(main_container, {"settings"});
CHECK(blobs.size() == 1 && blobs[0].first == "settings" && blobs[0].second == settings);
// The 16 MiB limit counts blob names: "big" (3 bytes) plus 16 MiB - 3 bytes fills it exactly.
{
std::vector<char> big(kMiB16);
void* full = saves.update(main_container, nullptr);
CHECK(saves.write(full, "big", big.data(), kMiB16 - 3 + 1) == kUpdateTooBig);
CHECK(saves.write(full, "big", big.data(), kMiB16 - 3) == S_OK);
CHECK(saves.write(full, "x", nullptr, 0) == kUpdateTooBig);
saves.close(kCloseUpdate, full);
}
// --- A second container, then enumeration ---
void* slot_container = saves.container(provider, "slot_1");
saves.put(slot_container, "a", "A");
saves.close(kCloseContainer, slot_container);
CHECK(files(dir, "*.bxgs", false) == 2);
const auto enumerate = slot<EnumerateFn>(api, kEnumerate);
Listing listing = list(saves, provider);
CHECK(listing.seen.size() == 2);
const time_t now = std::time(nullptr);
for (const auto& seen : listing.seen) {
CHECK(!seen.needs_sync && seen.modified >= started - 5 && seen.modified <= now + 5);
if (seen.name == "profiles/main") {
CHECK(seen.display_name == "Main profile" && seen.blob_count == 2 &&
seen.total_size == progress.size() + settings.size());
} else {
CHECK(seen.name == "slot_1" && seen.display_name.empty() && seen.blob_count == 1 && seen.total_size == 1);
}
}
CHECK(listing.seen[0].name != listing.seen[1].name);
Listing first_only;
first_only.stop_after = 1;
CHECK(enumerate(api, provider, &first_only, collect) == S_OK && first_only.seen.size() == 1);
CHECK(enumerate(api, provider, nullptr, nullptr) == E_INVALIDARG);
// --- Saves are separated by SCID ---
{
void* other = saves.provider(user, "scid-b");
CHECK(list(saves, other).seen.empty());
void* same_name = saves.container(other, "profiles/main");
CHECK(saves.read(same_name, {}).empty());
saves.put(same_name, "progress", "other scid");
CHECK(files(other_dir, "*.bxgs", false) == 1);
void* staged = saves.update(same_name, nullptr);
{
std::vector<char> big(kMiB16 - 16);
CHECK(saves.write(staged, "staged", big.data(), big.size()) == S_OK);
}
const uint64_t open_bytes = private_bytes();
saves.close(kCloseProvider, other);
// Closing a provider closes its containers and their updates, and frees what they staged.
CHECK(private_bytes() + 8 * (1u << 20) < open_bytes);
CHECK(saves.read_status(same_name, {}) == kInvalidHandle);
CHECK(saves.write(staged, "x", "x", 1) == kInvalidHandle);
CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == progress);
}
// --- Files that are damaged, foreign or unreadable ---
{
const auto crafted = [&](const char* name, std::string bytes) {
write_file(container_path(dir, name), bytes);
void* container = saves.container(provider, name);
const auto status = saves.read_status(container, {});
saves.close(kCloseContainer, container);
return status;
};
CHECK(crafted("craft_ok", container_bytes("craft_ok", {{"a", "1"}})) == S_OK); // the format is as documented
CHECK(crafted("craft_tail", container_bytes("craft_tail", {{"a", "1"}}) + "!") == kCorrupt);
CHECK(crafted("craft_dup", container_bytes("craft_dup", {{"a", "1"}, {"a", "2"}})) == kCorrupt);
std::string truncated = container_bytes("craft_cut", {{"a", "12345"}});
truncated.pop_back();
CHECK(crafted("craft_cut", truncated) == kCorrupt);
CHECK(crafted("craft_nul", container_bytes(std::string("craft_nul\0x", 11), {})) == kCorrupt);
CHECK(crafted("craft_blobnul", container_bytes("craft_blobnul", {{std::string("a\0b", 3), "1"}})) == kCorrupt);
CHECK(crafted("craft_badname", container_bytes("bad name", {})) == kCorrupt);
// Enumeration lists the two real containers and the valid crafted one, skipping the rest.
CHECK(list(saves, provider).seen.size() == 3);
// A file another process holds exclusively is skipped, not fatal to enumeration.
const HANDLE locked = CreateFileA(container_path(dir, "craft_ok").c_str(), GENERIC_READ, 0, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
CHECK(locked != INVALID_HANDLE_VALUE);
CHECK(list(saves, provider).seen.size() == 2);
CloseHandle(locked);
CHECK(files(dir, "*.bxgs", false) == 9);
for (const char* name : {"craft_ok", "craft_tail", "craft_dup", "craft_cut", "craft_nul", "craft_blobnul",
"craft_badname"}) {
CHECK(DeleteFileA(container_path(dir, name).c_str()));
}
}
// --- A failed replace keeps the old save; a successful one replaces the file ---
{
const auto file_id = [&] {
const HANDLE file = CreateFileA(container_path(dir, "profiles/main").c_str(), 0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
CHECK(file != INVALID_HANDLE_VALUE);
BY_HANDLE_FILE_INFORMATION info{};
CHECK(GetFileInformationByHandle(file, &info));
CloseHandle(file);
return (static_cast<uint64_t>(info.nFileIndexHigh) << 32) | info.nFileIndexLow;
};
const uint64_t original = file_id();
// A reader that allows writes but not deletion blocks the rename, not an in-place write.
const HANDLE reader = CreateFileA(container_path(dir, "profiles/main").c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, nullptr);
CHECK(reader != INVALID_HANDLE_VALUE);
void* blocked = saves.update(main_container, nullptr);
CHECK(saves.write(blocked, "progress", "BLOCKED", 7) == S_OK);
CHECK(FAILED(saves.submit_status(blocked)));
CloseHandle(reader);
CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == progress);
CHECK(files(dir, "*.tmp", false) == 0);
// The failed update was not consumed: submitting it again now succeeds.
CHECK(file_id() == original);
saves.submit(blocked);
saves.close(kCloseUpdate, blocked);
CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == "BLOCKED");
CHECK(file_id() != original); // written to a new file and renamed over, not in place
}
// --- Persistence across provider close and reopen ---
saves.close(kCloseContainer, main_container);
saves.close(kCloseProvider, provider);
CHECK(create_container(api, provider, "slot_1", &handle) == kInvalidHandle && !handle);
provider = saves.provider(user);
main_container = saves.container(provider, "profiles/main");
blobs = saves.read(main_container, {"settings", "progress"});
CHECK(blobs.size() == 2 && *find_blob(blobs, "progress") == "BLOCKED" && *find_blob(blobs, "settings") == settings);
// Overwrite one blob through the process task queue; the other blob and the display name stay.
const std::string progress2 = "lvl=9";
{
const Saves pooled{api, nullptr};
pooled.put(main_container, "progress", progress2);
}
blobs = saves.read(main_container, {});
CHECK(blobs.size() == 2 && *find_blob(blobs, "progress") == progress2 && *find_blob(blobs, "settings") == settings);
for (const auto& seen : list(saves, provider).seen) {
if (seen.name == "profiles/main") CHECK(seen.display_name == "Main profile");
}
// A canceled submit writes nothing, and the update can then be submitted again.
update = saves.update(main_container, nullptr);
CHECK(saves.write(update, "progress", "X", 1) == S_OK);
{
Async canceled{queue, nullptr, nullptr, {}};
CHECK(slot<SubmitAsyncFn>(api, kSubmitUpdateAsync)(api, update, &canceled) == S_OK);
XAsyncCancel(&canceled);
saves.wait(canceled);
CHECK(XAsyncGetStatus(&canceled, false) == E_ABORT);
CHECK(slot<AsyncResultFn>(api, kSubmitUpdateResult)(api, &canceled) == E_ABORT);
}
CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == progress2);
saves.submit(update);
saves.close(kCloseUpdate, update);
CHECK(*find_blob(saves.read(main_container, {"progress"}), "progress") == "X");
// A closed container handle is rejected, and so are its updates.
void* orphan = saves.update(main_container, nullptr);
saves.close(kCloseContainer, main_container);
CHECK(saves.read_status(main_container, {}) == kInvalidHandle);
CHECK(saves.write(orphan, "x", "x", 1) == kInvalidHandle);
update = nullptr;
CHECK(slot<CreateUpdateFn>(api, kCreateUpdate)(api, main_container, "x", &update) == kInvalidHandle && !update);
// --- Concurrent submits to one container: threads, then processes ---
void* shared = saves.container(provider, kShared);
{
constexpr int kThreads = 8, kEach = 8;
ThreadJob jobs[kThreads];
HANDLE threads[kThreads];
for (int i = 0; i < kThreads; ++i) {
jobs[i] = {api, shared, i, kEach};
threads[i] = CreateThread(nullptr, 0, thread_writer, &jobs[i], 0, nullptr);
CHECK(threads[i]);
}
CHECK(WaitForMultipleObjects(kThreads, threads, TRUE, 60000) == WAIT_OBJECT_0);
for (HANDLE thread : threads) CloseHandle(thread);
blobs = saves.read(shared, {});
CHECK(blobs.size() == kThreads * kEach);
check_blobs(blobs, 't', kThreads, kEach);
}
{
constexpr int kWriters = 4, kEach = 40;
wchar_t event_name[64];
std::swprintf(event_name, 64, L"Local\\bx_saves_go_%lu", GetCurrentProcessId());
const HANDLE go = CreateEventW(nullptr, TRUE, FALSE, event_name);
CHECK(go);
wchar_t exe[MAX_PATH];
CHECK(GetModuleFileNameW(nullptr, exe, MAX_PATH) > 0);
PROCESS_INFORMATION children[kWriters];
for (int id = 0; id < kWriters; ++id) {
wchar_t command[MAX_PATH + 128];
std::swprintf(command, MAX_PATH + 128, L"\"%ls\" --writer %d %d %ls", exe, id, kEach, event_name);
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
CHECK(CreateProcessW(exe, command, nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &children[id]));
}
CHECK(SetEvent(go));
for (auto& child : children) {
DWORD code = 99;
CHECK(WaitForSingleObject(child.hProcess, 120000) == WAIT_OBJECT_0);
CHECK(GetExitCodeProcess(child.hProcess, &code) && code == 0);
CloseHandle(child.hProcess);
CloseHandle(child.hThread);
}
CloseHandle(go);
blobs = saves.read(shared, {});
CHECK(blobs.size() == 8 * 8 + kWriters * kEach);
check_blobs(blobs, 'w', kWriters, kEach);
}
saves.close(kCloseContainer, shared);
// --- XPackage ---
char id[64]{};
CHECK(slot<GetIdFn>(package, kGetId)(package, sizeof(id), id) == S_OK);
CHECK(std::strncmp(id, "BXPKG", 5) == 0 && std::strlen(id) == 21);
for (const char* c = id + 5; *c; ++c) CHECK((*c >= '0' && *c <= '9') || (*c >= 'a' && *c <= 'f'));
char again[64]{};
CHECK(slot<GetIdFn>(package, kGetId)(package, sizeof(again), again) == S_OK && std::strcmp(id, again) == 0);
CHECK(slot<GetIdFn>(package, kGetId)(package, std::strlen(id), again) == kInsufficient);
CHECK(slot<GetIdFn>(package, kGetId)(package, sizeof(again), nullptr) == E_POINTER);
uint32_t kind = 99;
CHECK(slot<GetKindFn>(package, kGetKind)(package, id, &kind) == S_OK && kind == 0); // XPackageKind::Game
CHECK(slot<GetKindFn>(package, kGetKind)(package, "BXPKG0000000000000000", &kind) == kNotFound);
// The mount path is the executable's directory in UTF-8 (W API, so non-ASCII paths work).
wchar_t exe_w[MAX_PATH]{};
CHECK(GetModuleFileNameW(nullptr, exe_w, MAX_PATH) > 0);
*std::wcsrchr(exe_w, L'\\') = L'\0';
const std::string exe_dir = utf8(exe_w);
void* mount = nullptr;
CHECK(slot<MountFn>(package, kMount)(package, "BXPKG0000000000000000", &mount) == kNotFound && !mount);
CHECK(slot<MountFn>(package, kMount)(package, id, &mount) == S_OK && mount);
size_t path_size = 0;
CHECK(slot<PathSizeFn>(package, kGetMountPathSize)(package, mount, &path_size) == S_OK);
CHECK(path_size == exe_dir.size() + 1);
std::vector<char> path(path_size);
CHECK(slot<PathFn>(package, kGetMountPath)(package, mount, path_size - 1, path.data()) == kInsufficient);
CHECK(slot<PathFn>(package, kGetMountPath)(package, mount, path_size, path.data()) == S_OK);
CHECK(exe_dir == path.data());
// Handle types do not overlap: a mount handle is not a provider handle.
saves.close(kCloseProvider, mount);
CHECK(list(saves, provider).seen.size() == 3);
CHECK(slot<PathSizeFn>(package, kGetMountPathSize)(package, mount, &path_size) == S_OK);
slot<CloseFn>(package, kCloseMount)(package, mount);
CHECK(slot<PathSizeFn>(package, kGetMountPathSize)(package, mount, &path_size) == kInvalidHandle);
// --- Uninitialize then reinitialize: old handles stay dead, queued work does not run ---
{
void* old_container = saves.container(provider, "profiles/main");
void* old_update = saves.update(old_container, nullptr);
CHECK(saves.write(old_update, "progress", "STALE", 5) == S_OK);
void* old_mount = nullptr;
CHECK(slot<MountFn>(package, kMount)(package, id, &old_mount) == S_OK);
// Results and staged data held across the uninitialize must be released by it.
std::vector<char> big(kMiB16 - 8);
void* heavy = saves.update(old_container, nullptr);
CHECK(saves.write(heavy, "heavy", big.data(), big.size()) == S_OK);
std::vector<Async> unread(6, Async{queue, nullptr, nullptr, {}});
void* big_container = saves.container(provider, "big");
{
void* filler = saves.update(big_container, nullptr);
CHECK(saves.write(filler, "data", big.data(), big.size()) == S_OK);
saves.submit(filler);
saves.close(kCloseUpdate, filler);
}
big = {};
const uint64_t before = private_bytes();
for (auto& read : unread) {
CHECK(slot<ReadAsyncFn>(api, kReadAsync)(api, big_container, nullptr, 0, &read) == S_OK);
CHECK(XTaskQueueDispatch(queue, kWork, 0));
}
const uint64_t held = private_bytes();
// Queued last on the manual queue, so the dispatches above do not run it.
Async pending{queue, nullptr, nullptr, {}};
CHECK(slot<SubmitAsyncFn>(api, kSubmitUpdateAsync)(api, old_update, &pending) == S_OK);
XGameRuntimeUninitialize();
CHECK(XGameRuntimeInitialize() == S_OK);
const uint64_t after = private_bytes();
std::printf("memory: before reads %llu MiB, with 6 unread results %llu MiB, after uninitialize %llu MiB\n",
static_cast<unsigned long long>(before >> 20), static_cast<unsigned long long>(held >> 20),
static_cast<unsigned long long>(after >> 20));
// The measurement sees the six results (about 16 MiB each)...
CHECK(held > before + 80 * (1u << 20));
// ...and uninitialize released them and the open 16 MiB update counted in "before".
CHECK(after + 8 * (1u << 20) < before);
// The submit queued before uninitialize must not write now.
CHECK(XTaskQueueDispatch(queue, kWork, 0));
CHECK(XAsyncGetStatus(&pending, false) == kNotInitialized);
CHECK(slot<AsyncResultFn>(api, kSubmitUpdateResult)(api, &pending) == kNotInitialized);
CHECK(slot<CreateContainerFn>(api, kCreateContainer)(api, provider, "slot_1", &handle) == kInvalidHandle);
CHECK(saves.read_status(old_container, {}) == kInvalidHandle);
CHECK(saves.write(old_update, "x", "x", 1) == kInvalidHandle);
CHECK(slot<PathSizeFn>(package, kGetMountPathSize)(package, old_mount, &path_size) == kInvalidHandle);
void* fresh_user = add_user(queue);
void* fresh = saves.provider(fresh_user);
void* check = saves.container(fresh, "profiles/main");
CHECK(*find_blob(saves.read(check, {"progress"}), "progress") == "X");
XUserCloseHandle(fresh_user);
}
// --- After the last uninitialize, handles are stale ---
XUserCloseHandle(user);
XTaskQueueCloseHandle(queue);
XGameRuntimeUninitialize();
CHECK(create_container(api, provider, "slot_1", &handle) == kNotInitialized);
CHECK(slot<GetIdFn>(package, kGetId)(package, sizeof(id), id) == kNotInitialized);
std::printf("PASS: test_xgameruntime_saves (round trip, SCID isolation, damaged files, failed replace, "
"64 threaded + 160 cross-process submits, uninitialize; package %s)\n", id);
return 0;
}