Compare commits

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

No files matched your search

+1 -10
View File
@@ -10,16 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- Updated `README.md` and `docs/roadmap.md` to record Milestone M0 and Milestone M1 (`#17`, 16/16 issues) as verified complete on synthetic workloads and activate Milestone M2 (`#18`, First Rendered Frame & Shader Format Gate).
- Implemented clean-room COM `IUnknown` vtable dispatch in `xgameruntime.dll!QueryApiImpl` for the core public Microsoft PC GDK (`Microsoft.GDK.Windows 2610.0.9661`) interface families (`XAsync`/`XTaskQueue`/`XThread`, `XGameRuntimeIsFeatureAvailable`, `XSystem`, `XError`, `XPersistentLocalStorage`, `XUser`, `XStore`, `XGameUi`, `XNetworking`, `XGame`), with auto-logging `BX_VTABLE_STUB_LOG` fallback on unimplemented slots. Validated live on CrossOver 26.3 with an independently authored caller linked against Microsoft's public `xgameruntime.lib` (#456).
- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached.
- **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first.
- **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged.
- **Uninitialized environments:** a bare `--prefix` without `system32` is initialized with `wineboot --init` under the same isolated environment. A bottle without one fails with a hint. Neither case is ever skipped silently.
- **Partial shim folders:** a `--shims` folder without `xgameruntime.dll` prints a notice and the run continues without staging, as it did before staging existed.
- **Supervision:** `--timeout`, SIGINT, SIGTERM and SIGHUP also cover the `wineboot --init` step, so an interrupted first run does not leave `wineserver` running.
- **Tests:** 8 unit tests cover staging and the dependency walk. `tests/conformance/test_system32_staging/` makes the `LOAD_LIBRARY_SEARCH_SYSTEM32` load and requires BetterXen's shim, from `system32`, exporting `QueryApiImpl`, and the same module for `SYSTEM32 | APPLICATION_DIR`. `--expect-missing` is the negative control for an unstaged prefix.
- **Local result:** on one Apple M3 Pro (macOS 27.2.1) with CodeWeavers Wine 11.0 built from source, so not CrossOver 26.3, and with the staging done by hand: the control passed and the unstaged run failed as expected. Staging the runtime alone still failed, which is how the dependency rule was found. Staging both passed 4/4 in two runs. `bx-cli run` itself was not run, since CrossOver is not installed on that host.
- `bx-cli run` now stages allowlisted non-host Xbox shim DLLs (`bx_runtime_veh.dll`, `xgameruntime.dll`) into an initialized bottle/prefix `drive_c/windows/system32/` using an RAII guard so guests using `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)` resolve BetterXen's shim out of the box without permanently mutating the bottle or overwriting pre-existing files/symlinks. Added synthetic conformance fixture `test_system32_staging` (#459).
- `bx-cli run` gained `--timeout <secs>`, cleanup of the launcher process group and the selected bottle or prefix on timeout, SIGINT, SIGTERM or SIGHUP (including re-resolving managed bottles whose first launch creates a private stub), `--backend` (bottle mode only), and a printed trace summary after a run with `--log`. The bottle to stop is located through CrossOver itself, so bottles outside the default directory are covered. A normal exit does not stop the environment. Recorded a one-host observation that D3D12 swapchains stay referenced under D3DMetal (#408).
- Added `test_apiset_resolution`, a conformance fixture that statically imports the six API-set `win32_bridge` names and reports which module serves each (`--expect host|shim`), and accepted ADR 0007 recording that CrossOver 26.0 and 26.3 answer them via built-ins (`twinapi.appcore.dll` / `user32.dll`) (#437).
- Added file-mapping-backed 64 KiB and 2 MiB physical pages, contiguous and scatter aliases (including intra-span duplicate-tag aliasing), exact-span unmap validation, physical region queries (`bx_xmem_query_region`), and shared working-set accounting / combined title memory budget enforcement across heap, virtual, and physical allocations in `xmem.dll`. Synthetic `XMemAllocatePhysicalPages` / `XMemFreePhysicalPages` signatures follow Win32 AWE (`memoryapi.h`) pending a public console flag encoding (#412).
+15 -15
View File
@@ -9,13 +9,13 @@
![Platform: Apple Silicon](https://img.shields.io/badge/platform-Apple%20Silicon%20(ARM64)-1f6feb?logo=apple&logoColor=white)
![Graphics: D3DMetal 3.0](https://img.shields.io/badge/graphics-D3DMetal%203.0%20%2F%20Metal-8957e5)
![Stack: Rust + C++20 PE32+](https://img.shields.io/badge/stack-Rust%20%2B%20C%2B%2B20%20PE32%2B-dea584)
![Status: experimental](https://img.shields.io/badge/status-experimental%20(M2)-0969da)
![Status: experimental](https://img.shields.io/badge/status-experimental%20(M0)-d29922)
![License: GPL-3.0-or-later](https://img.shields.io/badge/license-GPL--3.0--or--later-2ea043)
</div>
> [!IMPORTANT]
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project with **Milestone M0 and Milestone M1 verified complete** on synthetic PE32+ workloads under CrossOver 26.3 + Rosetta 2, and **Milestone M2** (`First Rendered Frame & Shader Format Gate`) currently active. **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project currently at **Milestone M0** (cross-compiled shim foundation and live CrossOver/Rosetta smoke tests verified on synthetic PE32+ workloads). **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Rosetta 2**, and **D3DMetal 3.0** on Apple Silicon:
- **Native ARM64 macOS tooling** (`launcher/`, Rust) for host diagnostics, PE32+ static probing, CrossOver bottle orchestration, and structured trace aggregation.
@@ -33,9 +33,9 @@ BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Ro
```mermaid
flowchart LR
M0["M0: Foundation & Shims\n(Verified Complete)"]:::done
M1["M1: Boot to D3D12\n(Verified Complete — 16/16)"]:::done
M2["M2: First Frame &\nShader Gate\n(Active — Milestone #18)"]:::active
M0["M0: Foundation & Shims\n(Merged #406)"]:::done
M1["M1: Boot to D3D12\n(Active — Milestone #17)"]:::active
M2["M2: First Frame &\nShader Gate"]:::planned
M3["M3: Shaders &\nTexture Tiling"]:::planned
M4["M4: 3D, DXR/BVH\n& Input"]:::planned
M5["M5: Audio, Saves\n& Stability"]:::planned
@@ -50,16 +50,16 @@ flowchart LR
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
### Active Milestone — [M2: First Rendered Frame & Shader Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)
### Active Milestone — [M1: Startup Shims to `D3D12XboxCreateDevice`](https://github.com/MacosPorters/betterxen/milestone/17)
| Track | Focus | Visual Status | Live Issues |
| --- | --- | --- | --- |
| **Track A** | `system32` shim staging (`#457` / PR `#458` merged), AMD-only VEH emulation (`#451`), Track A/F runner integration (`#407`) | `🟩🟨🟨` *(#458 merged; #451, #407 active)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
| **Track B** | `XCRDAPI.dll` DirectStorage GPU-buffer & batch transfers (`#467`) | `⬜` *(1 ready)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
| **Track C** | `d3d12_xs` `D3D12ConfigureVirtualMemoryX` + placed resources (`#464`), `PresentX` swapchain bridge (`#465`), D3D workload fixes (`#450`) | `⬜⬜⬜` *(3 ready)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
| **Track D** | `dxbc-accc` Windows guest bridge (`#445`), M2 Shader Format Gate ADR & PSO hook (`#466`) | `⬜⬜` *(2 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
| **Track E** | Public GDK COM `QueryApiImpl` dispatch (`#456` / PR `#462` merged), offline `XGameSave` + `XPackage` COM dispatch (`#468`) | `🟩⬜` *(#462 merged, 1 ready)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
| **Track F** | D3DMetal GPU limits fixture (`#453` / PR #455), M2 first-frame + shader-gate exit fixture (`#469`) | `🟨⬜` *(PR #455 approved, 1 ready)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
| **Track A** | `bx-cli` supervision, `clwb` VEH + crash dumper, Win32 bridge | `🟨🟨🟨` *(3/3 PRs open)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
| **Track B** | `xmem.dll` core + physical/scatter pages, `XCRDAPI.dll` DirectStorage | `🟨🟨🟨` *(3/3 PRs open)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
| **Track C** | `d3d12_xs.dll` COM proxy (D3DMetal 3.0), `xg_xs.dll` texture computer | `⬜⬜` *(needs contributors!)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
| **Track D** | `dxbc-accc` FSPX C ABI bridge, `d3dmetal-native` harness | `🟨⬜` *(1 PR open, 1 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
| **Track E** | `xgameruntime.dll` offline GDK, `AcpHal`/`xapu`/`chad`, `GameInput` | `🟨🟨` *(2/2 PRs open)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
| **Track F** | End-to-end synthetic boot fixture (`test_integration_boot`) | `🟨` *(1/1 PR open)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
@@ -67,9 +67,9 @@ Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
| Milestone | Scope | Status |
| --- | --- | --- |
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime` + dynamic loader exports, audio queue stubs, supervised `bx-cli run`, ADR 0007, `test_integration_boot` 19 pass / 2 pending / 0 fail) | 🟢 **Verified complete ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
| **M2 — First Frame & Shader Gate** | Reversible `system32` staging, public GDK COM `QueryApiImpl` dispatch, `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0, `dxbc-accc` Windows bridge, D3DMetal GPU limits, and Shader Format Gate ADR | 🔵 **Active ([Milestone #18](https://github.com/MacosPorters/betterxen/milestone/18))** |
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Merged (`#406`)** |
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime`, audio queue stubs) | 🔵 **Active ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
| **M2 — First Frame & Shader Gate** | `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0; inspect runtime shaders to select DXIL fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation | ⚪ Planned |
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | ⚪ Planned |
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | ⚪ Planned |
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | ⚪ Planned |
+3 -3
View File
@@ -36,9 +36,9 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
| Milestone | Objective | Exit Gate | Status |
| --- | --- | --- | --- |
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; 16/16 PE32+ DLLs pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime` + dynamic loader exports, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, supervised `bx-cli run`, ADR 0007, and combined synthetic integration boot fixture | All Wave 1 conformance binaries pass under CrossOver 26.3 + Rosetta 2; combined `test_integration_boot.exe` passes (19 pass, 2 ADR-0007 pending, 0 fail) | **Verified complete (Milestone #17, 16/16)** |
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), placed resources over `xmem`, bridge `dxbc-accc` into Windows guests (`#445`), measure D3DMetal GPU limits (`#453`), and establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)** | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | **In development (Milestone #18)** |
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; 16/16 PE32+ DLLs pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **In validation (PR #406)** |
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime`, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, and combined synthetic integration boot fixture | All 13 Wave 1 conformance binaries pass under CrossOver + Rosetta 2; combined `integration_boot.exe` initializes every subsystem cleanly | **Next (Wave 1 ready)** |
| **M2 — First Rendered Frame & Shader Format Gate** | Implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), placed resources over `xmem`, and `dxbc-accc` shader inspection to establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)** | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | Planned |
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
+221 -130
View File
@@ -1,15 +1,15 @@
//! Track A (M1-A1): Native ARM64 macOS CLI for BetterXen hybrid execution.
mod stage;
mod supervise;
use std::collections::BTreeMap;
use std::env;
use std::fmt::Write as _;
use std::fs;
use std::fs::{self, OpenOptions};
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use std::time::{Duration, Instant};
use std::time::Duration;
use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus};
use bx_telemetry::summarize_jsonl;
@@ -21,6 +21,84 @@ api-ms-win-core-psm-appnotify-l1-1-0,api-ms-win-core-psm-appnotify-l1-1-1,\
ext-ms-win-rtcore-ntuser-message-l1-1-0,ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0,\
ext-ms-win-rtcore-ntuser-window-l1-1-0,ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0=n,b";
/// Non-host Xbox shim DLLs that guest loaders resolve via `LOAD_LIBRARY_SEARCH_SYSTEM32`
/// (bypassing `WINEPATH`), plus `bx_runtime_veh.dll` which `xgameruntime.dll` imports. Staged into
/// `drive_c/windows/system32/` only when absent and removed when the run completes.
const SYSTEM32_STAGED_SHIMS: &[&str] = &["bx_runtime_veh.dll", "xgameruntime.dll"];
/// RAII guard for BetterXen shim DLLs temporarily staged into `drive_c/windows/system32/`.
/// Never overwrites or removes pre-existing files or symlinks.
struct StagedSystem32Shims {
staged: Vec<PathBuf>,
}
impl StagedSystem32Shims {
fn stage(prefix: &Path, shims_dir: &Path, dll_names: &[&str]) -> Self {
let mut staged = Vec::new();
let system32 = prefix.join("drive_c/windows/system32");
if !system32.is_dir() {
return Self { staged };
}
for &name in dll_names {
let src = shims_dir.join(name);
if !src.is_file() {
continue;
}
let dst = system32.join(name);
if dst.symlink_metadata().is_ok() {
eprintln!(
"note: leaving pre-existing {} untouched during system32 staging",
dst.display()
);
continue;
}
let copy_result = (|| -> io::Result<()> {
let mut reader = fs::File::open(&src)?;
let mut writer = OpenOptions::new().write(true).create_new(true).open(&dst)?;
io::copy(&mut reader, &mut writer)?;
Ok(())
})();
match copy_result {
Ok(()) => staged.push(dst),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
eprintln!(
"note: leaving pre-existing {} untouched during system32 staging",
dst.display()
);
}
Err(e) => {
let _ = fs::remove_file(&dst);
eprintln!(
"warning: could not stage {} into {}: {e}",
src.display(),
dst.display()
);
}
}
}
Self { staged }
}
fn cleanup(&mut self) {
for path in self.staged.drain(..) {
if let Err(e) = fs::remove_file(&path)
&& e.kind() != io::ErrorKind::NotFound
{
eprintln!(
"warning: failed to remove staged shim {}: {e}",
path.display()
);
}
}
}
}
impl Drop for StagedSystem32Shims {
fn drop(&mut self) {
self.cleanup();
}
}
/// Accepted `--backend` values. CrossOver ignores an unknown value silently, so one is refused.
const BACKENDS: [&str; 4] = ["d3dmetal", "dxmt", "dxvk", "wined3d"];
@@ -436,68 +514,6 @@ fn bottle_options(backend: Option<&str>) -> Vec<String> {
options
}
/// The CrossOver Wine environment for a bare `--prefix` (bottles get theirs from `bin/wine`).
fn apply_prefix_env(command: &mut Command, cx_root: &Path, prefix: &Path, wineloader: &Path) {
command
.env("WINEPREFIX", prefix)
.env("WINESERVER", cx_root.join("bin/wineserver"))
.env("WINELOADER", wineloader)
.env(
"WINEDLLPATH",
format!(
"{}:{}",
cx_root.join("lib/wine").display(),
cx_root.join("lib64/wine").display()
),
)
.env(
"DYLD_FALLBACK_LIBRARY_PATH",
format!(
"{}:{}:/usr/lib",
cx_root.join("lib64").display(),
cx_root.join("lib").display()
),
);
}
/// Reports a timeout or signal and stops the environment's `wineserver`. True if cleanup failed.
fn stop_environment(
stop: Stop,
cx_root: &Path,
environment_dir: &Path,
bottle: Option<&str>,
inherit_env: bool,
) -> bool {
match stop {
Stop::TimedOut => eprintln!("timed out; stopping the environment"),
Stop::Signalled(signal) => {
eprintln!("received signal {signal}; stopping the environment");
}
}
let server_env: Vec<(String, String)> = collect_isolated_host_env(|k| env::var(k).ok())
.into_iter()
.collect();
let mut cleanup_failed = false;
let prefixes_to_stop = match cleanup_prefixes_for_stop(environment_dir, bottle, |name| {
resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env)
}) {
Ok(prefixes) => prefixes,
Err(e) => {
eprintln!("cleanup failed to re-resolve bottle prefix: {e}");
cleanup_failed = true;
vec![environment_dir.to_path_buf()]
}
};
for prefix in &prefixes_to_stop {
if let Err(e) = supervise::stop_server(&cx_root.join("bin/wineserver"), prefix, &server_env)
{
eprintln!("cleanup failed, programs may still be running: {e}");
cleanup_failed = true;
}
}
cleanup_failed
}
fn cmd_run(args: &[String]) -> ExitCode {
let run = match parse_run_args(args) {
Ok(run) => run,
@@ -545,60 +561,6 @@ fn cmd_run(args: &[String]) -> ExitCode {
None => resolved_prefix.clone(),
};
// Handled from here on, so that prefix initialization is cleaned up like the guest is.
supervise::install_signal_handlers();
let started = Instant::now();
// #457: shims loaded with LOAD_LIBRARY_SEARCH_SYSTEM32 never see WINEPATH, so they are
// copied into the environment's system32 first. A bare prefix is initialized for that.
let system32 = stage::system32_dir(&environment_dir);
if bottle.is_none() && !system32.is_dir() && stage::has_system32_shims(&abs_shims) {
let _ = fs::create_dir_all(&resolved_prefix);
let mut boot = Command::new(&wineloader);
boot.args(["wineboot", "--init"]);
apply_host_env(&mut boot, inherit_env);
apply_prefix_env(&mut boot, cx_root, &resolved_prefix, &wineloader);
boot.env("WINEDEBUG", "-all");
match supervise::supervise(boot, timeout, supervise::received_signal) {
Ok(Outcome::Exited(st)) if st.success() => {}
Ok(Outcome::Exited(st)) => {
eprintln!(
"error: wineboot --init failed for {}: {st}",
resolved_prefix.display()
);
return ExitCode::FAILURE;
}
Ok(outcome @ Outcome::Stopped(stop)) => {
let failed = stop_environment(stop, cx_root, &environment_dir, None, inherit_env);
let code = outcome.exit_code();
return ExitCode::from(if failed { code.max(1) } else { code });
}
Err(e) => {
eprintln!(
"error: cannot run wineboot for {}: {e}",
resolved_prefix.display()
);
return ExitCode::FAILURE;
}
}
}
match stage::stage_system32(&abs_shims, &system32) {
Ok(staged) => {
for item in &staged {
eprintln!("bx-cli: {}", item.describe());
}
}
Err(e) => {
let hint = if bottle.is_some() {
" (start the bottle once so CrossOver creates it)"
} else {
""
};
eprintln!("error: cannot stage system32 shims: {e}{hint}");
return ExitCode::FAILURE;
}
}
let mut cmd = if let Some(ref bname) = bottle {
let mut c = Command::new(&wine_wrapper);
c.args(["--bottle", bname])
@@ -615,7 +577,25 @@ fn cmd_run(args: &[String]) -> ExitCode {
apply_host_env(&mut cmd, inherit_env);
if bottle.is_none() {
apply_prefix_env(&mut cmd, cx_root, &resolved_prefix, &wineloader);
cmd.env("WINEPREFIX", &resolved_prefix)
.env("WINESERVER", cx_root.join("bin/wineserver"))
.env("WINELOADER", &wineloader)
.env(
"WINEDLLPATH",
format!(
"{}:{}",
cx_root.join("lib/wine").display(),
cx_root.join("lib64/wine").display()
),
)
.env(
"DYLD_FALLBACK_LIBRARY_PATH",
format!(
"{}:{}:/usr/lib",
cx_root.join("lib64").display(),
cx_root.join("lib").display()
),
);
}
cmd.env("ROSETTA_ADVERTISE_AVX", "1")
@@ -637,9 +617,11 @@ fn cmd_run(args: &[String]) -> ExitCode {
let log_size = |log: &PathBuf| fs::metadata(log).map_or(0, |m| m.len());
let log_size_before = abs_log.as_ref().map_or(0, log_size);
// `--timeout` bounds the whole run, including any prefix initialization above.
let remaining = timeout.map(|limit| limit.saturating_sub(started.elapsed()));
let outcome = supervise::supervise(cmd, remaining, supervise::received_signal);
let mut staged_shims =
StagedSystem32Shims::stage(&environment_dir, &abs_shims, SYSTEM32_STAGED_SHIMS);
supervise::install_signal_handlers();
let outcome = supervise::supervise(cmd, timeout, supervise::received_signal);
let code = match &outcome {
Ok(outcome) => outcome.exit_code(),
Err(e) => {
@@ -653,17 +635,41 @@ fn cmd_run(args: &[String]) -> ExitCode {
eprintln!("guest exited with status: {status}");
}
Ok(Outcome::Stopped(stop)) => {
cleanup_failed = stop_environment(
*stop,
cx_root,
&environment_dir,
bottle.as_deref(),
inherit_env,
);
match stop {
Stop::TimedOut => eprintln!("timed out; stopping the environment"),
Stop::Signalled(signal) => {
eprintln!("received signal {signal}; stopping the environment");
}
}
let server_env: Vec<(String, String)> = collect_isolated_host_env(|k| env::var(k).ok())
.into_iter()
.collect();
let prefixes_to_stop =
match cleanup_prefixes_for_stop(&environment_dir, bottle.as_deref(), |name| {
resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env)
}) {
Ok(prefixes) => prefixes,
Err(e) => {
eprintln!("cleanup failed to re-resolve bottle prefix: {e}");
cleanup_failed = true;
vec![environment_dir.clone()]
}
};
for prefix in &prefixes_to_stop {
if let Err(e) =
supervise::stop_server(&cx_root.join("bin/wineserver"), prefix, &server_env)
{
eprintln!("cleanup failed, programs may still be running: {e}");
cleanup_failed = true;
}
}
}
_ => {}
}
// Remove staged system32 shims after wineserver teardown so open handles do not linger.
staged_shims.cleanup();
// Printed for failed and stopped runs too, which is when it matters most.
if let Some(log) = &abs_log
&& log_size(log) > log_size_before
@@ -961,4 +967,89 @@ sub setup_bottle_wineprefix {
"clwb VEH traps : at least 4 (sampled)"
);
}
#[test]
fn stages_allowlisted_shims_into_system32_and_removes_on_drop() {
let root = env::temp_dir().join(format!("bx-cli-stage-ok-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let shims = root.join("shims");
let sys32 = root.join("prefix/drive_c/windows/system32");
fs::create_dir_all(&shims).unwrap();
fs::create_dir_all(&sys32).unwrap();
fs::write(shims.join("bx_runtime_veh.dll"), b"bx-veh-bytes").unwrap();
fs::write(shims.join("xgameruntime.dll"), b"bx-shim-bytes").unwrap();
let staged_veh = sys32.join("bx_runtime_veh.dll");
let staged_xgr = sys32.join("xgameruntime.dll");
{
let guard =
StagedSystem32Shims::stage(&root.join("prefix"), &shims, SYSTEM32_STAGED_SHIMS);
assert_eq!(guard.staged, vec![staged_veh.clone(), staged_xgr.clone()]);
assert_eq!(fs::read(&staged_veh).unwrap(), b"bx-veh-bytes");
assert_eq!(fs::read(&staged_xgr).unwrap(), b"bx-shim-bytes");
}
assert!(!staged_veh.exists());
assert!(!staged_xgr.exists());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn staging_never_overwrites_or_deletes_preexisting_system32_dll() {
let root = env::temp_dir().join(format!("bx-cli-stage-keep-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let shims = root.join("shims");
let sys32 = root.join("prefix/drive_c/windows/system32");
fs::create_dir_all(&shims).unwrap();
fs::create_dir_all(&sys32).unwrap();
fs::write(shims.join("xgameruntime.dll"), b"bx-shim-bytes").unwrap();
let dst = sys32.join("xgameruntime.dll");
fs::write(&dst, b"host-original-bytes").unwrap();
{
let guard =
StagedSystem32Shims::stage(&root.join("prefix"), &shims, SYSTEM32_STAGED_SHIMS);
assert!(guard.staged.is_empty());
assert_eq!(fs::read(&dst).unwrap(), b"host-original-bytes");
}
assert_eq!(fs::read(&dst).unwrap(), b"host-original-bytes");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn staging_refuses_to_clobber_preexisting_symlink_in_system32() {
use std::os::unix::fs::symlink;
let root = env::temp_dir().join(format!("bx-cli-stage-sym-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let shims = root.join("shims");
let sys32 = root.join("prefix/drive_c/windows/system32");
fs::create_dir_all(&shims).unwrap();
fs::create_dir_all(&sys32).unwrap();
fs::write(shims.join("xgameruntime.dll"), b"bx-shim-bytes").unwrap();
let dst = sys32.join("xgameruntime.dll");
symlink(root.join("dangling-target"), &dst).unwrap();
{
let guard =
StagedSystem32Shims::stage(&root.join("prefix"), &shims, SYSTEM32_STAGED_SHIMS);
assert!(guard.staged.is_empty());
}
assert!(dst.symlink_metadata().unwrap().file_type().is_symlink());
assert!(!root.join("dangling-target").exists());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn staging_is_a_noop_when_system32_directory_is_absent() {
let root = env::temp_dir().join(format!("bx-cli-stage-empty-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let shims = root.join("shims");
fs::create_dir_all(&shims).unwrap();
fs::write(shims.join("xgameruntime.dll"), b"bx-shim-bytes").unwrap();
let guard =
StagedSystem32Shims::stage(&root.join("bare-prefix"), &shims, SYSTEM32_STAGED_SHIMS);
assert!(guard.staged.is_empty());
assert!(!root.join("bare-prefix").exists());
fs::remove_dir_all(root).unwrap();
}
}
-330
View File
@@ -1,330 +0,0 @@
//! #457: shims a guest loads by system-directory search, staged into the prefix's `system32`.
//!
//! The GDK bootstrap that titles link statically loads `xgameruntime.dll` with
//! `LoadLibraryExW(name, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32)`. That search never consults
//! `WINEPATH`, where `bx-cli run` otherwise exposes the shims, so those shims are copied into
//! `drive_c/windows/system32` of the prefix or bottle before launch.
//!
//! The same search flags apply to the DLL's own imports, so every BetterXen shim it imports
//! (for example `bx_runtime_veh.dll`) is staged too. Otherwise the load fails unless the guest
//! happened to load that dependency earlier.
use std::collections::BTreeSet;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
/// Shims loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`.
pub const SYSTEM32_SHIMS: &[&str] = &["xgameruntime.dll"];
/// `roots` plus, transitively, every import that is itself a file in the shim folder
/// (`is_shim`). Names are compared case-insensitively, as the Windows loader does, and returned
/// lowercased in a stable order.
pub fn shim_closure<I, S>(
roots: &[&str],
is_shim: S,
mut imports_of: I,
) -> Result<Vec<String>, String>
where
I: FnMut(&str) -> Result<Vec<String>, String>,
S: Fn(&str) -> bool,
{
let mut done = BTreeSet::new();
let mut todo: Vec<String> = roots.iter().map(|r| r.to_ascii_lowercase()).collect();
while let Some(name) = todo.pop() {
if !done.insert(name.clone()) {
continue;
}
for dep in imports_of(&name)? {
let dep = dep.to_ascii_lowercase();
if is_shim(&dep) && !done.contains(&dep) {
todo.push(dep);
}
}
}
Ok(done.into_iter().collect())
}
/// The shim file in `shims_dir` named `name`, matched case-insensitively.
fn find_shim(shims_dir: &Path, name: &str) -> Option<PathBuf> {
let exact = shims_dir.join(name);
if exact.is_file() {
return Some(exact);
}
fs::read_dir(shims_dir)
.ok()?
.filter_map(|e| e.ok())
.find_map(|e| {
let file = e.file_name();
(file.to_string_lossy().eq_ignore_ascii_case(name) && e.path().is_file())
.then(|| e.path())
})
}
/// DLL names a PE32+ file imports, read with `bx-probe`.
fn pe_imports(path: &Path) -> Result<Vec<String>, String> {
let bytes = fs::read(path).map_err(|e| format!("cannot read shim {}: {e}", path.display()))?;
let summary = bx_probe::probe_pe32_plus(&bytes)
.map_err(|e| format!("cannot read imports of {}: {e:?}", path.display()))?;
Ok(summary.imports.into_keys().collect())
}
/// The 64-bit system directory of a Wine prefix.
pub fn system32_dir(prefix: &Path) -> PathBuf {
prefix.join("drive_c").join("windows").join("system32")
}
/// What staging did to one file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Staged {
Copied(PathBuf),
Replaced(PathBuf),
Unchanged(PathBuf),
/// A [`SYSTEM32_SHIMS`] file the shim folder does not have.
Absent(PathBuf),
}
impl Staged {
pub fn describe(&self) -> String {
match self {
Staged::Copied(p) => format!("staged {}", p.display()),
Staged::Replaced(p) => format!("replaced {}", p.display()),
Staged::Unchanged(p) => format!("already current {}", p.display()),
Staged::Absent(p) => format!("not staged, {} not found", p.display()),
}
}
}
/// True if the shim folder has any [`SYSTEM32_SHIMS`] file, so there is something to stage.
pub fn has_system32_shims(shims_dir: &Path) -> bool {
SYSTEM32_SHIMS
.iter()
.any(|name| find_shim(shims_dir, name).is_some())
}
/// Copies every [`SYSTEM32_SHIMS`] file, and the shims they import, from `shims_dir` into
/// `system32`. The directory must already exist (an uninitialized prefix is a caller error, not
/// something to skip). A shim the folder does not have is reported as [`Staged::Absent`], so a
/// run with a partial `--shims` folder still starts. A copy already identical byte for byte is
/// left alone, a different one is replaced. Nothing outside `system32` is written.
pub fn stage_system32(shims_dir: &Path, system32: &Path) -> Result<Vec<Staged>, String> {
stage_system32_with(shims_dir, system32, pe_imports)
}
fn stage_system32_with<I>(
shims_dir: &Path,
system32: &Path,
mut imports_of: I,
) -> Result<Vec<Staged>, String>
where
I: FnMut(&Path) -> Result<Vec<String>, String>,
{
let (roots, absent): (Vec<&str>, Vec<&str>) = SYSTEM32_SHIMS
.iter()
.copied()
.partition(|name| find_shim(shims_dir, name).is_some());
let mut staged: Vec<Staged> = absent
.iter()
.map(|name| Staged::Absent(shims_dir.join(name)))
.collect();
if roots.is_empty() {
return Ok(staged);
}
if !system32.is_dir() {
return Err(format!(
"{} does not exist; the prefix is not initialized",
system32.display()
));
}
let names = shim_closure(
&roots,
|dep| find_shim(shims_dir, dep).is_some(),
|name| match find_shim(shims_dir, name) {
Some(path) => imports_of(&path),
None => Err(format!(
"cannot read shim {}: not found",
shims_dir.join(name).display()
)),
},
)?;
for name in &names {
let src = find_shim(shims_dir, name).unwrap_or_else(|| shims_dir.join(name));
let bytes =
fs::read(&src).map_err(|e| format!("cannot read shim {}: {e}", src.display()))?;
let dst = system32.join(name);
let result = match fs::read(&dst) {
Ok(existing) if existing == bytes => Staged::Unchanged(dst.clone()),
Ok(_) => Staged::Replaced(dst.clone()),
Err(e) if e.kind() == io::ErrorKind::NotFound => Staged::Copied(dst.clone()),
Err(e) => return Err(format!("cannot read {}: {e}", dst.display())),
};
if !matches!(result, Staged::Unchanged(_)) {
// Write beside the target, then rename, so a guest never sees a half-written DLL.
// The name is per process, so a concurrent run cannot rename a partial write.
let tmp = system32.join(format!(".{name}.{}.bx-staging", std::process::id()));
fs::write(&tmp, &bytes).map_err(|e| {
let _ = fs::remove_file(&tmp);
format!("cannot write {}: {e}", tmp.display())
})?;
fs::rename(&tmp, &dst).map_err(|e| {
let _ = fs::remove_file(&tmp);
format!("cannot replace {}: {e}", dst.display())
})?;
}
staged.push(result);
}
Ok(staged)
}
#[cfg(test)]
mod tests {
use super::*;
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let p = std::env::temp_dir().join(format!(
"bx-stage-{tag}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = fs::remove_dir_all(&p);
fs::create_dir_all(&p).unwrap();
TempDir(p)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn setup(tag: &str) -> (TempDir, PathBuf, PathBuf) {
let t = TempDir::new(tag);
let shims = t.0.join("shims");
let prefix = t.0.join("prefix");
fs::create_dir_all(&shims).unwrap();
fs::create_dir_all(system32_dir(&prefix)).unwrap();
for name in SYSTEM32_SHIMS {
fs::write(shims.join(name), b"shim v1").unwrap();
}
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v1").unwrap();
fs::write(shims.join("unrelated.dll"), b"not imported").unwrap();
(t, shims, prefix)
}
/// The import graph of the fake shims: the runtime imports the VEH logger and a system DLL.
fn fake_imports(path: &Path) -> Result<Vec<String>, String> {
let name = path
.file_name()
.unwrap()
.to_string_lossy()
.to_ascii_lowercase();
Ok(match name.as_str() {
"xgameruntime.dll" => vec!["BX_RUNTIME_VEH.dll".into(), "KERNEL32.dll".into()],
_ => vec!["KERNEL32.dll".into()],
})
}
fn stage(shims: &Path, sys: &Path) -> Result<Vec<Staged>, String> {
stage_system32_with(shims, sys, fake_imports)
}
#[test]
fn closure_follows_shim_imports_only() {
let shims: BTreeSet<&str> = ["a.dll", "b.dll", "c.dll"].into();
let graph = |n: &str| -> Result<Vec<String>, String> {
Ok(match n {
"a.dll" => vec!["B.DLL".into(), "kernel32.dll".into()],
"b.dll" => vec!["c.dll".into(), "a.dll".into()],
_ => vec![],
})
};
let got = shim_closure(&["A.dll"], |d| shims.contains(d), graph).unwrap();
assert_eq!(got, vec!["a.dll", "b.dll", "c.dll"]);
}
#[test]
fn stages_the_runtime_and_its_shim_dependency() {
let (_t, shims, prefix) = setup("deps");
let sys = system32_dir(&prefix);
let staged = stage(&shims, &sys).unwrap();
assert_eq!(staged.len(), 2, "{staged:?}");
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v1");
assert!(
!sys.join("unrelated.dll").exists(),
"only imported shims are staged"
);
}
#[test]
fn system32_is_under_drive_c() {
assert_eq!(
system32_dir(Path::new("/p")),
PathBuf::from("/p/drive_c/windows/system32")
);
}
#[test]
fn copies_then_leaves_identical_copy_alone() {
let (_t, shims, prefix) = setup("idem");
let sys = system32_dir(&prefix);
let first = stage(&shims, &sys).unwrap();
assert!(first.iter().all(|s| matches!(s, Staged::Copied(_))));
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v1");
let second = stage(&shims, &sys).unwrap();
assert!(second.iter().all(|s| matches!(s, Staged::Unchanged(_))));
}
#[test]
fn replaces_an_older_copy() {
let (_t, shims, prefix) = setup("replace");
let sys = system32_dir(&prefix);
fs::write(sys.join("xgameruntime.dll"), b"old").unwrap();
let staged = stage(&shims, &sys).unwrap();
assert!(staged.contains(&Staged::Replaced(sys.join("xgameruntime.dll"))));
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v1");
let leftovers: Vec<_> = fs::read_dir(&sys)
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| e.file_name().to_string_lossy().contains("bx-staging"))
.collect();
assert!(leftovers.is_empty(), "temporary file left behind");
}
#[test]
fn missing_shim_is_reported_and_nothing_is_staged() {
let (t, shims, prefix) = setup("missing");
fs::remove_file(shims.join("xgameruntime.dll")).unwrap();
assert!(!has_system32_shims(&shims));
let sys = system32_dir(&prefix);
let expected = vec![Staged::Absent(shims.join("xgameruntime.dll"))];
assert_eq!(stage(&shims, &sys).unwrap(), expected);
assert_eq!(fs::read_dir(&sys).unwrap().count(), 0);
// With nothing to stage, a prefix without system32 is not an error either.
let fresh = system32_dir(&t.0.join("fresh"));
assert_eq!(stage(&shims, &fresh).unwrap(), expected);
assert!(!fresh.exists());
}
#[test]
fn uninitialized_prefix_is_an_error_not_a_skip() {
let (t, shims, _prefix) = setup("uninit");
let sys = system32_dir(&t.0.join("fresh"));
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("not initialized"), "{err}");
assert!(!sys.exists(), "staging must not create the prefix itself");
}
#[test]
fn writes_only_inside_system32() {
let (_t, shims, prefix) = setup("scope");
let sys = system32_dir(&prefix);
stage(&shims, &sys).unwrap();
let windows: Vec<_> = fs::read_dir(prefix.join("drive_c/windows"))
.unwrap()
.map(|e| e.unwrap().file_name())
.collect();
assert_eq!(windows, vec![std::ffi::OsString::from("system32")]);
}
}
-1
View File
@@ -1,7 +1,6 @@
bx_add_shim_dll(xgameruntime xgameruntime xgameruntime.def
xgameruntime.cpp
task_queue.cpp
com_dispatch.cpp
)
target_link_libraries(xgameruntime PRIVATE bx_runtime_veh kernel32)
target_compile_options(xgameruntime PRIVATE -fexceptions)
-616
View File
@@ -1,616 +0,0 @@
/*
* Clean-room COM IUnknown vtable dispatch for xgameruntime.dll!QueryApiImpl (#456).
*
* Provenance: Interface identifiers, IUnknown inheritance, and vtable slot indices were
* established via clean-room black-box interoperability testing against Microsoft's publicly
* distributed PC GDK NuGet package (Microsoft.GDK.Windows 2610.0.9661, nuget.org) using an
* independently authored synthetic caller invoking public documented GDK APIs. No Microsoft
* source code or binary code is copied or bundled.
*/
#include "com_dispatch.h"
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <unordered_set>
#include <utility>
#include "bx_log.h"
#include "task_queue.h"
extern "C" {
HRESULT WINAPI XTaskQueueCreate(bx::gdk::DispatchMode, bx::gdk::DispatchMode, void**);
void WINAPI XTaskQueueCloseHandle(void*);
bool WINAPI XTaskQueueDispatch(void*, bx::gdk::Port, uint32_t);
HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLBACK*)(void*, bool));
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
HRESULT WINAPI XAsyncGetStatus(void*, bool);
HRESULT WINAPI XAsyncGetResultSize(void*, size_t*);
void WINAPI XAsyncCancel(void*);
HRESULT WINAPI XUserAddAsync(uint32_t, void*);
HRESULT WINAPI XUserAddResult(void*, void**);
void WINAPI XUserCloseHandle(void*);
HRESULT WINAPI XUserGetId(void*, uint64_t*);
HRESULT WINAPI XUserGetGamertag(void*, uint32_t, size_t, char*, size_t*);
HRESULT WINAPI XUserGetTokenAndSignatureAsync(void*, uint32_t, const char*, const char*, size_t, const void*, size_t,
const uint8_t*, void*);
HRESULT WINAPI XUserGetTokenAndSignatureResultSize(void*, size_t*);
HRESULT WINAPI XUserGetTokenAndSignatureResult(void*, size_t, void*, void**, size_t*);
HRESULT WINAPI XUserResolvePrivilegeWithUiAsync(void*, uint32_t, uint32_t, void*);
HRESULT WINAPI XUserResolvePrivilegeWithUiResult(void*);
HRESULT WINAPI XStoreCreateContext(void*, void**);
void WINAPI XStoreCloseContextHandle(void*);
HRESULT WINAPI XStoreQueryGameLicenseAsync(void*, void*);
HRESULT WINAPI XStoreQueryGameLicenseResult(void*, void*);
HRESULT WINAPI XStoreAcquireLicenseForPackageAsync(void*, const char*, void*);
HRESULT WINAPI XStoreAcquireLicenseForPackageResult(void*, void**);
HRESULT WINAPI XStoreAcquireLicenseForDurablesAsync(void*, const char*, void*);
HRESULT WINAPI XStoreAcquireLicenseForDurablesResult(void*, void**);
HRESULT WINAPI XStoreQueryEntitledProductsAsync(void*, uint32_t, uint32_t, void*);
HRESULT WINAPI XStoreQueryEntitledProductsResult(void*, void**);
HRESULT WINAPI XStoreQueryAssociatedProductsAsync(void*, uint32_t, uint32_t, void*);
HRESULT WINAPI XStoreQueryAssociatedProductsResult(void*, void**);
HRESULT WINAPI XSystemGetConsoleId(size_t, char*, size_t*);
uint32_t WINAPI XSystemGetDeviceType();
HRESULT WINAPI XSystemGetXboxLiveSandboxId(size_t, char*, size_t*);
HRESULT WINAPI XPersistentLocalStorageGetPathSize(size_t*);
HRESULT WINAPI XPersistentLocalStorageGetPath(size_t, char*, size_t*);
HRESULT WINAPI XPersistentLocalStorageGetSpaceInfo(void*);
HRESULT WINAPI XGameUiShowPlayerProfileCardAsync(void*, uint64_t, void*);
HRESULT WINAPI XGameUiShowTextEntryAsync(const char*, const char*, const char*, uint32_t, uint32_t, void*);
HRESULT WINAPI XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync(void*);
HRESULT WINAPI XNetworkingQuerySecurityInformationForUrlAsync(const char*, void*);
} // extern "C"
namespace bx::gdk {
namespace {
constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
// Public Microsoft.GDK.Windows 2610.0.9661 QueryApiImpl class & interface identifiers.
constexpr GUID kCoreGuid = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
constexpr GUID kFeatureGuid = {0x8836FE87, 0xEDB9, 0x4FE3, {0x8D, 0xAD, 0x05, 0xF0, 0xD2, 0xCD, 0x5B, 0x40}};
constexpr GUID kSystemClsid = {0xE349BD1A, 0xFC20, 0x4E40, {0xB9, 0x9C, 0x41, 0x78, 0xCC, 0x6B, 0x40, 0x9F}};
constexpr GUID kSystemIid = {0x1861CF2E, 0xE18B, 0x4834, {0xA9, 0xF5, 0xB4, 0xA4, 0xE6, 0xEF, 0xB4, 0xCF}};
constexpr GUID kErrorGuid = {0x8CA467F7, 0x22E8, 0x4096, {0x84, 0x56, 0xBB, 0x8A, 0xA1, 0x3F, 0x79, 0xD8}};
constexpr GUID kPlsClsid = {0xF4FAF4D4, 0x2D04, 0x4FCE, {0xB3, 0xE0, 0x47, 0x4A, 0x71, 0x3A, 0x3E, 0x84}};
constexpr GUID kPlsIid = {0x41A4E10C, 0x5A7E, 0x41D9, {0x8C, 0x37, 0x37, 0xBD, 0xE6, 0x2A, 0x07, 0xD6}};
constexpr GUID kUserClsid = {0x01ACD177, 0x91F9, 0x4763, {0xA3, 0x8E, 0xCC, 0xBB, 0x55, 0xCE, 0x32, 0xE0}};
constexpr GUID kUserGamertagIid = {0xCEF4FAC0, 0x7676, 0x4A94, {0xA1, 0x19, 0x4C, 0x43, 0xF9, 0xEB, 0x5B, 0x74}};
constexpr GUID kStoreClsid = {0x0DD112AC, 0x7C24, 0x448C, {0xB9, 0x2B, 0x39, 0x60, 0xFB, 0x5B, 0xD3, 0x0C}};
constexpr GUID kStoreIid = {0xB09D803C, 0x2414, 0x4A05, {0x82, 0xC6, 0x66, 0xDF, 0xDC, 0x9E, 0x9A, 0x44}};
constexpr GUID kStoreDurablesIid = {0x2D42FEA5, 0xE71D, 0x4B76, {0x97, 0xCD, 0xC5, 0x0A, 0xFB, 0xB3, 0xAE, 0x5D}};
constexpr GUID kGameUiClsid = {0xDFCD4649, 0x4FF8, 0x4043, {0xBA, 0x07, 0x35, 0xD6, 0x07, 0xDF, 0x98, 0xB0}};
constexpr GUID kGameUiIid = {0xEAF669DF, 0x5542, 0x4590, {0x99, 0xA3, 0x8D, 0xC0, 0x61, 0xF8, 0x37, 0xCC}};
constexpr GUID kNetworkingClsid = {0x37E56907, 0x2F10, 0x41E8, {0xB7, 0x2F, 0x36, 0xED, 0xB1, 0x85, 0x33, 0x1A}};
constexpr GUID kNetworkingIid = {0xBF2346B2, 0x39AF, 0x4658, {0xB5, 0xEA, 0x44, 0x71, 0x3C, 0x7E, 0x83, 0xB3}};
constexpr GUID kGameClsid = {0x973A344E, 0x24BF, 0x4D0F, {0x84, 0x57, 0x56, 0xC5, 0x34, 0x89, 0x2B, 0x29}};
constexpr GUID kGameIid = {0x2549F142, 0x6419, 0x4A06, {0x97, 0xB5, 0x93, 0x1A, 0xAB, 0x7C, 0x2F, 0x34}};
bool guid_eq(const GUID& a, const GUID& b) {
return std::memcmp(&a, &b, sizeof(GUID)) == 0;
}
struct ComSingleton {
const void* const* vtbl;
const GUID* iid;
const char* name;
};
HRESULT WINAPI com_query_interface(void* self, const GUID* riid, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!riid) return E_INVALIDARG;
auto* obj = static_cast<ComSingleton*>(self);
if (guid_eq(*riid, kIUnknown) || guid_eq(*riid, *obj->iid)) {
*out = obj;
return S_OK;
}
return E_NOINTERFACE;
}
ULONG WINAPI com_add_ref(void*) {
return 1;
}
ULONG WINAPI com_release(void*) {
return 1;
}
template <size_t Slot>
HRESULT WINAPI com_unimpl_slot(void* self) {
auto* obj = static_cast<const ComSingleton*>(self);
char method[32];
std::snprintf(method, sizeof(method), "slot_%zu", Slot);
BX_VTABLE_STUB_LOG(obj ? obj->name : "IXGameRuntime", static_cast<uint32_t>(Slot), method);
return E_NOTIMPL;
}
template <size_t N, size_t... Is>
constexpr std::array<const void*, N> make_default_vtbl_impl(std::index_sequence<Is...>) {
return {((Is == 0) ? reinterpret_cast<const void*>(&com_query_interface)
: (Is == 1) ? reinterpret_cast<const void*>(&com_add_ref)
: (Is == 2) ? reinterpret_cast<const void*>(&com_release)
: reinterpret_cast<const void*>(&com_unimpl_slot<Is>))...};
}
template <size_t N>
std::array<const void*, N> make_default_vtbl() {
return make_default_vtbl_impl<N>(std::make_index_sequence<N>{});
}
// --- Core (XAsync + XTaskQueue + XThread) ---
thread_local bool tls_time_sensitive = false;
HRESULT WINAPI core_async_get_status(void*, void* async, bool wait) {
return XAsyncGetStatus(async, wait);
}
HRESULT WINAPI core_async_get_result_size(void*, void* async, size_t* size) {
return XAsyncGetResultSize(async, size);
}
void WINAPI core_async_cancel(void*, void* async) {
XAsyncCancel(async);
}
HRESULT WINAPI core_tq_create(void*, DispatchMode work, DispatchMode comp, void** out) {
return XTaskQueueCreate(work, comp, out);
}
bool WINAPI core_tq_dispatch(void*, void* queue, Port port, uint32_t timeout) {
return XTaskQueueDispatch(queue, port, timeout);
}
void WINAPI core_tq_close(void*, void* queue) {
XTaskQueueCloseHandle(queue);
}
HRESULT WINAPI core_tq_submit(void*, void* queue, Port port, void* ctx, void (CALLBACK* cb)(void*, bool)) {
return XTaskQueueSubmitCallback(queue, port, ctx, cb);
}
HRESULT WINAPI core_tq_submit_delayed(void*, void* queue, Port port, uint32_t delay_ms, void* ctx,
void (CALLBACK* cb)(void*, bool)) {
if (delay_ms > 0) {
BX_VTABLE_STUB_LOG("IXGameRuntimeCore", 19, "XTaskQueueSubmitDelayedCallback(nonzero_delay)");
}
return XTaskQueueSubmitCallback(queue, port, ctx, cb);
}
bool WINAPI core_tq_get_process(void*, void** out) {
return XTaskQueueGetCurrentProcessTaskQueue(out);
}
HRESULT WINAPI core_thread_set_time_sensitive(void*, bool is_ts) {
tls_time_sensitive = is_ts;
return S_OK;
}
HRESULT WINAPI core_thread_verify_not_time_sensitive(void*) {
return tls_time_sensitive ? E_FAIL : S_OK;
}
HRESULT WINAPI core_runtime_guard_hook(void*, uint32_t, void*) {
// Invoked by public GDK static thunks before subsystem dispatch.
return S_OK;
}
bool WINAPI core_thread_is_time_sensitive(void*) {
return tls_time_sensitive;
}
const std::array<const void*, 36> kCoreVtbl = [] {
auto v = make_default_vtbl<36>();
v[3] = reinterpret_cast<const void*>(&core_async_get_status);
v[4] = reinterpret_cast<const void*>(&core_async_get_result_size);
v[5] = reinterpret_cast<const void*>(&core_async_cancel);
v[12] = reinterpret_cast<const void*>(&core_tq_create);
v[16] = reinterpret_cast<const void*>(&core_tq_dispatch);
v[17] = reinterpret_cast<const void*>(&core_tq_close);
v[18] = reinterpret_cast<const void*>(&core_tq_submit);
v[19] = reinterpret_cast<const void*>(&core_tq_submit_delayed);
v[25] = reinterpret_cast<const void*>(&core_tq_get_process);
v[27] = reinterpret_cast<const void*>(&core_thread_set_time_sensitive);
v[28] = reinterpret_cast<const void*>(&core_thread_verify_not_time_sensitive);
v[29] = reinterpret_cast<const void*>(&core_runtime_guard_hook);
v[30] = reinterpret_cast<const void*>(&core_thread_is_time_sensitive);
return v;
}();
ComSingleton kCoreObj{kCoreVtbl.data(), &kCoreGuid, "IXGameRuntimeCore"};
// --- XGameRuntimeIsFeatureAvailable ---
bool WINAPI feature_is_available(void*, uint32_t feature) {
// XGameRuntimeFeature enum values from public XGameRuntimeFeature.h.
switch (feature) {
case 2: // XAsync
case 5: // XGame
case 8: // XGameUI
case 10: // XNetworking
case 12: // XPersistentLocalStorage
case 14: // XStore
case 15: // XSystem
case 16: // XTaskQueue
case 17: // XThread
case 18: // XUser
case 19: // XError
return true;
default:
return false;
}
}
const std::array<const void*, 8> kFeatureVtbl = [] {
auto v = make_default_vtbl<8>();
v[3] = reinterpret_cast<const void*>(&feature_is_available);
return v;
}();
ComSingleton kFeatureObj{kFeatureVtbl.data(), &kFeatureGuid, "IXGameRuntimeFeature"};
// --- XSystem ---
HRESULT WINAPI sys_get_console_id(void*, size_t sz, char* out, size_t* used) {
return XSystemGetConsoleId(sz, out, used);
}
HRESULT WINAPI sys_get_sandbox_id(void*, size_t sz, char* out, size_t* used) {
return XSystemGetXboxLiveSandboxId(sz, out, used);
}
HRESULT WINAPI sys_get_app_device_id(void*, size_t sz, char* out, size_t* used) {
constexpr char kDeviceId[] = "BX-OFFLINE-APP-DEVICE-000000000001";
if (used) *used = 0;
if (!out) return E_POINTER;
const size_t req = sizeof(kDeviceId);
if (sz < req) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
std::memcpy(out, kDeviceId, req);
if (used) *used = req;
return S_OK;
}
HRESULT WINAPI sys_handle_track(void*, void*, void*) {
return S_OK;
}
bool WINAPI sys_is_handle_valid(void*, void* handle) {
return handle != nullptr;
}
void WINAPI sys_allow_full_bandwidth(void*, bool) {}
const std::array<const void*, 12> kSystemVtbl = [] {
auto v = make_default_vtbl<12>();
v[3] = reinterpret_cast<const void*>(&sys_get_console_id);
v[4] = reinterpret_cast<const void*>(&sys_get_sandbox_id);
v[5] = reinterpret_cast<const void*>(&sys_get_app_device_id);
v[6] = reinterpret_cast<const void*>(&sys_handle_track);
v[7] = reinterpret_cast<const void*>(&sys_is_handle_valid);
v[8] = reinterpret_cast<const void*>(&sys_allow_full_bandwidth);
return v;
}();
ComSingleton kSystemObj{kSystemVtbl.data(), &kSystemIid, "IXSystem"};
// --- XError ---
void WINAPI err_set_callback(void*, void*, void*) {}
void WINAPI err_set_options(void*, uint32_t, uint32_t) {}
const std::array<const void*, 8> kErrorVtbl = [] {
auto v = make_default_vtbl<8>();
v[4] = reinterpret_cast<const void*>(&err_set_callback);
v[5] = reinterpret_cast<const void*>(&err_set_options);
return v;
}();
ComSingleton kErrorObj{kErrorVtbl.data(), &kErrorGuid, "IXError"};
// --- XPersistentLocalStorage ---
HRESULT WINAPI pls_get_path_size(void*, size_t* sz) {
return XPersistentLocalStorageGetPathSize(sz);
}
HRESULT WINAPI pls_get_path(void*, size_t sz, char* out, size_t* used) {
return XPersistentLocalStorageGetPath(sz, out, used);
}
HRESULT WINAPI pls_get_space_info(void*, void* info) {
return XPersistentLocalStorageGetSpaceInfo(info);
}
const std::array<const void*, 12> kPlsVtbl = [] {
auto v = make_default_vtbl<12>();
v[3] = reinterpret_cast<const void*>(&pls_get_path_size);
v[4] = reinterpret_cast<const void*>(&pls_get_path);
v[5] = reinterpret_cast<const void*>(&pls_get_space_info);
return v;
}();
ComSingleton kPlsObj{kPlsVtbl.data(), &kPlsIid, "IXPersistentLocalStorage"};
// --- XUser ---
std::mutex user_event_mutex;
uint64_t next_user_event_token = 1;
std::unordered_set<uint64_t> user_event_tokens;
void WINAPI user_close_handle(void*, void* h) {
XUserCloseHandle(h);
}
int32_t WINAPI user_compare(void*, void* u1, void* u2) {
if (u1 == u2) return 0;
return reinterpret_cast<uintptr_t>(u1) < reinterpret_cast<uintptr_t>(u2) ? -1 : 1;
}
HRESULT WINAPI user_get_max_users(void*, uint32_t* max_users) {
if (!max_users) return E_POINTER;
*max_users = 1;
return S_OK;
}
HRESULT WINAPI user_add_async(void*, uint32_t opts, void* async) {
return XUserAddAsync(opts, async);
}
HRESULT WINAPI user_add_result(void*, void* async, void** out) {
return XUserAddResult(async, out);
}
HRESULT WINAPI user_get_local_id(void*, void* user, uint64_t* local_id) {
if (!local_id) return E_POINTER;
if (!user) return E_INVALIDARG;
*local_id = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(user));
return S_OK;
}
HRESULT WINAPI user_get_id(void*, void* user, uint64_t* id) {
return XUserGetId(user, id);
}
HRESULT WINAPI user_get_is_guest(void*, void* user, bool* is_guest) {
if (!is_guest) return E_POINTER;
if (!user) return E_INVALIDARG;
*is_guest = false;
return S_OK;
}
HRESULT WINAPI user_get_state(void*, void* user, uint32_t* state) {
if (!state) return E_POINTER;
if (!user) return E_INVALIDARG;
*state = 0; // XUserState::SignedIn
return S_OK;
}
HRESULT WINAPI user_get_age_group(void*, void* user, uint32_t* age_group) {
if (!age_group) return E_POINTER;
if (!user) return E_INVALIDARG;
*age_group = 3; // XUserAgeGroup::Adult
return S_OK;
}
HRESULT WINAPI user_check_privilege(void*, void* user, uint32_t, uint32_t, bool* has_priv, uint32_t* deny_reason) {
if (!has_priv) return E_POINTER;
if (!user) return E_INVALIDARG;
*has_priv = true;
if (deny_reason) *deny_reason = 0; // XUserPrivilegeDenyReason::None
return S_OK;
}
HRESULT WINAPI user_resolve_priv_async(void*, void* user, uint32_t opts, uint32_t priv, void* async) {
return XUserResolvePrivilegeWithUiAsync(user, opts, priv, async);
}
HRESULT WINAPI user_resolve_priv_result(void*, void* async) {
return XUserResolvePrivilegeWithUiResult(async);
}
HRESULT WINAPI user_token_async(void*, void* user, uint32_t opts, const char* method, const char* url,
size_t hdr_cnt, const void* hdrs, size_t body_sz, const uint8_t* body, void* async) {
return XUserGetTokenAndSignatureAsync(user, opts, method, url, hdr_cnt, hdrs, body_sz, body, async);
}
HRESULT WINAPI user_token_result_size(void*, void* async, size_t* sz) {
return XUserGetTokenAndSignatureResultSize(async, sz);
}
HRESULT WINAPI user_token_result(void*, void* async, size_t sz, void* buf, void** res, size_t* used) {
return XUserGetTokenAndSignatureResult(async, sz, buf, res, used);
}
HRESULT WINAPI user_register_change_event(void*, void*, void*, void* callback, uint64_t* token) {
if (!token) return E_POINTER;
if (!callback) return E_INVALIDARG;
std::lock_guard lock(user_event_mutex);
const uint64_t id = next_user_event_token++;
user_event_tokens.insert(id);
*token = id;
return S_OK;
}
bool WINAPI user_unregister_change_event(void*, uint64_t token, bool) {
std::lock_guard lock(user_event_mutex);
return user_event_tokens.erase(token) > 0;
}
HRESULT WINAPI user_get_gamertag(void*, void* user, uint32_t comp, size_t sz, char* out, size_t* used) {
return XUserGetGamertag(user, comp, sz, out, used);
}
const std::array<const void*, 64> kUserVtbl = [] {
auto v = make_default_vtbl<64>();
v[4] = reinterpret_cast<const void*>(&user_close_handle);
v[5] = reinterpret_cast<const void*>(&user_compare);
v[6] = reinterpret_cast<const void*>(&user_get_max_users);
v[7] = reinterpret_cast<const void*>(&user_add_async);
v[8] = reinterpret_cast<const void*>(&user_add_result);
v[9] = reinterpret_cast<const void*>(&user_get_local_id);
v[11] = reinterpret_cast<const void*>(&user_get_id);
v[13] = reinterpret_cast<const void*>(&user_get_is_guest);
v[14] = reinterpret_cast<const void*>(&user_get_state);
v[19] = reinterpret_cast<const void*>(&user_get_age_group);
v[20] = reinterpret_cast<const void*>(&user_check_privilege);
v[21] = reinterpret_cast<const void*>(&user_resolve_priv_async);
v[22] = reinterpret_cast<const void*>(&user_resolve_priv_result);
v[23] = reinterpret_cast<const void*>(&user_token_async);
v[24] = reinterpret_cast<const void*>(&user_token_result_size);
v[25] = reinterpret_cast<const void*>(&user_token_result);
v[33] = reinterpret_cast<const void*>(&user_register_change_event);
v[34] = reinterpret_cast<const void*>(&user_unregister_change_event);
return v;
}();
ComSingleton kUserObj{kUserVtbl.data(), &kUserClsid, "IXUser"};
const std::array<const void*, 8> kUserGamertagVtbl = [] {
auto v = make_default_vtbl<8>();
v[3] = reinterpret_cast<const void*>(&user_get_gamertag);
return v;
}();
ComSingleton kUserGamertagObj{kUserGamertagVtbl.data(), &kUserGamertagIid, "IXUserGamertag"};
// --- XStore ---
HRESULT WINAPI store_create_ctx(void*, void* user, void** out) {
return XStoreCreateContext(user, out);
}
void WINAPI store_close_ctx(void*, void* ctx) {
XStoreCloseContextHandle(ctx);
}
HRESULT WINAPI store_assoc_async(void*, void* ctx, uint32_t pf, uint32_t max_items, void* async) {
return XStoreQueryAssociatedProductsAsync(ctx, pf, max_items, async);
}
HRESULT WINAPI store_assoc_result(void*, void* async, void** out) {
return XStoreQueryAssociatedProductsResult(async, out);
}
HRESULT WINAPI store_entitled_async(void*, void* ctx, uint32_t pf, uint32_t max_items, void* async) {
return XStoreQueryEntitledProductsAsync(ctx, pf, max_items, async);
}
HRESULT WINAPI store_entitled_result(void*, void* async, void** out) {
return XStoreQueryEntitledProductsResult(async, out);
}
HRESULT WINAPI store_pkg_lic_async(void*, void* ctx, const char* id, void* async) {
return XStoreAcquireLicenseForPackageAsync(ctx, id, async);
}
HRESULT WINAPI store_pkg_lic_result(void*, void* async, void** out) {
return XStoreAcquireLicenseForPackageResult(async, out);
}
HRESULT WINAPI store_game_lic_async(void*, void* ctx, void* async) {
return XStoreQueryGameLicenseAsync(ctx, async);
}
HRESULT WINAPI store_game_lic_result(void*, void* async, void* out) {
return XStoreQueryGameLicenseResult(async, out);
}
HRESULT WINAPI store_dur_lic_async(void*, void* ctx, const char* id, void* async) {
return XStoreAcquireLicenseForDurablesAsync(ctx, id, async);
}
HRESULT WINAPI store_dur_lic_result(void*, void* async, void** out) {
return XStoreAcquireLicenseForDurablesResult(async, out);
}
const std::array<const void*, 40> kStoreVtbl = [] {
auto v = make_default_vtbl<40>();
v[3] = reinterpret_cast<const void*>(&store_create_ctx);
v[4] = reinterpret_cast<const void*>(&store_close_ctx);
v[5] = reinterpret_cast<const void*>(&store_assoc_async);
v[6] = reinterpret_cast<const void*>(&store_assoc_result);
v[9] = reinterpret_cast<const void*>(&store_entitled_async);
v[10] = reinterpret_cast<const void*>(&store_entitled_result);
v[20] = reinterpret_cast<const void*>(&store_pkg_lic_async);
v[21] = reinterpret_cast<const void*>(&store_pkg_lic_result);
v[28] = reinterpret_cast<const void*>(&store_game_lic_async);
v[29] = reinterpret_cast<const void*>(&store_game_lic_result);
return v;
}();
ComSingleton kStoreObj{kStoreVtbl.data(), &kStoreIid, "IXStore"};
const std::array<const void*, 80> kStoreDurablesVtbl = [] {
auto v = make_default_vtbl<80>();
v[71] = reinterpret_cast<const void*>(&store_dur_lic_async);
v[72] = reinterpret_cast<const void*>(&store_dur_lic_result);
return v;
}();
ComSingleton kStoreDurablesObj{kStoreDurablesVtbl.data(), &kStoreDurablesIid, "IXStoreDurables"};
// --- XGameUi ---
HRESULT WINAPI gameui_profile_async(void*, void* user, uint64_t xuid, void* async) {
return XGameUiShowPlayerProfileCardAsync(user, xuid, async);
}
HRESULT WINAPI gameui_text_async(void*, const char* title, const char* desc, const char* def, uint32_t scope,
uint32_t max_chars, void* async) {
return XGameUiShowTextEntryAsync(title, desc, def, scope, max_chars, async);
}
const std::array<const void*, 32> kGameUiVtbl = [] {
auto v = make_default_vtbl<32>();
v[7] = reinterpret_cast<const void*>(&gameui_profile_async);
v[17] = reinterpret_cast<const void*>(&gameui_text_async);
return v;
}();
ComSingleton kGameUiObj{kGameUiVtbl.data(), &kGameUiIid, "IXGameUi"};
// --- XNetworking ---
struct ConnectivityHint {
uint32_t connectivity_level;
uint32_t connectivity_cost;
uint32_t iana_interface_type;
bool network_initialized;
bool approaching_data_limit;
bool over_data_limit;
bool roaming;
};
static_assert(sizeof(ConnectivityHint) == 16);
HRESULT WINAPI net_udp_port_async(void*, void* async) {
return XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync(async);
}
HRESULT WINAPI net_sec_info_async(void*, const char* url, void* async) {
return XNetworkingQuerySecurityInformationForUrlAsync(url, async);
}
HRESULT WINAPI net_get_connectivity_hint(void*, ConnectivityHint* hint) {
if (!hint) return E_POINTER;
// Offline profile: ConnectivityLevelHint::None (1), CostHint::Unrestricted (1).
*hint = {1u, 1u, 6u, true, false, false, false};
return S_OK;
}
const std::array<const void*, 24> kNetworkingVtbl = [] {
auto v = make_default_vtbl<24>();
v[4] = reinterpret_cast<const void*>(&net_udp_port_async);
v[8] = reinterpret_cast<const void*>(&net_sec_info_async);
v[15] = reinterpret_cast<const void*>(&net_get_connectivity_hint);
return v;
}();
ComSingleton kNetworkingObj{kNetworkingVtbl.data(), &kNetworkingIid, "IXNetworking"};
// --- XGame ---
HRESULT WINAPI game_get_xbox_title_id(void*, uint32_t* title_id) {
if (!title_id) return E_POINTER;
// Synthetic offline title ID for BetterXen runtime.
*title_id = 0x42580001u;
return S_OK;
}
const std::array<const void*, 8> kGameVtbl = [] {
auto v = make_default_vtbl<8>();
v[3] = reinterpret_cast<const void*>(&game_get_xbox_title_id);
return v;
}();
ComSingleton kGameObj{kGameVtbl.data(), &kGameIid, "IXGame"};
struct PublicEntry {
const GUID* clsid;
const GUID* iid;
ComSingleton* obj;
};
const PublicEntry kPublicEntries[] = {
{&kCoreGuid, &kCoreGuid, &kCoreObj},
{&kFeatureGuid, &kFeatureGuid, &kFeatureObj},
{&kSystemClsid, &kSystemIid, &kSystemObj},
{&kErrorGuid, &kErrorGuid, &kErrorObj},
{&kPlsClsid, &kPlsIid, &kPlsObj},
{&kUserClsid, &kUserClsid, &kUserObj},
{&kUserClsid, &kUserGamertagIid, &kUserGamertagObj},
{&kStoreClsid, &kStoreIid, &kStoreObj},
{&kStoreClsid, &kStoreDurablesIid, &kStoreDurablesObj},
{&kGameUiClsid, &kGameUiIid, &kGameUiObj},
{&kNetworkingClsid, &kNetworkingIid, &kNetworkingObj},
{&kGameClsid, &kGameIid, &kGameObj},
};
} // namespace
bool query_public_gdk_interface(const GUID* clsid, const GUID* iid, void** out, bool* clsid_known) {
*clsid_known = false;
for (const auto& entry : kPublicEntries) {
if (guid_eq(*clsid, *entry.clsid)) {
*clsid_known = true;
if (guid_eq(*iid, *entry.iid) || guid_eq(*iid, kIUnknown)) {
*out = entry.obj;
char detail[96];
std::snprintf(detail, sizeof(detail), "dispatch public_com=%s", entry.obj->name);
bx_log_emit(BX_LOG_INFO, "xgameruntime", "QueryApiImpl", detail);
return true;
}
}
}
return false;
}
} // namespace bx::gdk
-12
View File
@@ -1,12 +0,0 @@
#pragma once
#include <windows.h>
namespace bx::gdk {
// Dispatches public Microsoft PC GDK (Microsoft.GDK.Windows 2610.0.9661) COM IUnknown
// interfaces queried through QueryApiImpl. Returns true when (clsid, iid) matched and
// *out was populated, or sets *clsid_known=true when clsid matched but iid did not.
bool query_public_gdk_interface(const GUID* clsid, const GUID* iid, void** out, bool* clsid_known);
} // namespace bx::gdk
-8
View File
@@ -1,4 +1,3 @@
#include "com_dispatch.h"
#include "task_queue.h"
#include <condition_variable>
@@ -838,11 +837,6 @@ HRESULT WINAPI QueryApiImpl(const GUID* clsid, const GUID* iid, void** out) {
return runtime_not_initialized;
}
bool public_clsid_known = false;
if (bx::gdk::query_public_gdk_interface(clsid, iid, out, &public_clsid_known)) {
return S_OK;
}
const auto* family = find_family(clsid);
if (family && synthetic_guid(iid) && iid->Data1 == family->iid) {
*out = const_cast<void*>(family->table);
@@ -859,8 +853,6 @@ HRESULT WINAPI QueryApiImpl(const GUID* clsid, const GUID* iid, void** out) {
if (family) {
std::snprintf(detail, sizeof(detail), "iid_mismatch family=%s clsid=%s iid=%s", family->name, clsid_text,
iid_text);
} else if (public_clsid_known) {
std::snprintf(detail, sizeof(detail), "public_iid_mismatch clsid=%s iid=%s", clsid_text, iid_text);
} else {
std::snprintf(detail, sizeof(detail), "unsupported clsid=%s iid=%s", clsid_text, iid_text);
}
@@ -1,4 +1,2 @@
# #457: xgameruntime.dll reached by LOAD_LIBRARY_SEARCH_SYSTEM32 after bx-cli run stages it.
# Links no shim: the load under test is the dynamic one GDK titles make.
add_executable(test_system32_staging main.cpp)
target_link_libraries(test_system32_staging PRIVATE kernel32)
@@ -1,65 +1,61 @@
/*
* #457: clean-room synthetic test for system32 shim staging by `bx-cli run`.
* #459: Synthetic conformance fixture for bx-cli reversible system32 shim staging.
*
* GDK titles load the runtime with LoadLibraryExW(L"xgameruntime.dll", NULL,
* LOAD_LIBRARY_SEARCH_SYSTEM32), which does not search WINEPATH or the executable's folder.
* This test makes that load and requires that BetterXen's shim answers it:
* - the module loads, from a path under system32;
* - it exports QueryApiImpl (a BetterXen xgameruntime export, absent from Wine builtins);
* - LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR gives the same module.
*
* `--expect-missing` is the negative control for an unstaged prefix: the load must fail.
* Exit 0 on pass, 1 on failure.
* Does NOT statically import xgameruntime.dll. Instead, mirrors the dynamic loader path
* by calling LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32),
* verifying that the loaded module resolves from \windows\system32\xgameruntime.dll and
* exports InitializeApiImpl, then unloading cleanly.
*/
#include <windows.h>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <cwctype>
namespace {
int g_checks = 0;
int g_failures = 0;
bool check(bool ok, const char* what) {
g_checks++;
if (!ok) {
g_failures++;
std::fprintf(stderr, "FAIL: %s\n", what);
} else {
std::printf("PASS: %s\n", what);
bool ends_with_ci(const wchar_t* str, const wchar_t* suffix) {
const size_t slen = std::wcslen(str);
const size_t suflen = std::wcslen(suffix);
if (slen < suflen) return false;
const wchar_t* tail = str + (slen - suflen);
for (size_t i = 0; i < suflen; ++i) {
if (std::towlower(tail[i]) != std::towlower(suffix[i])) return false;
}
return ok;
return true;
}
bool path_in_system32(HMODULE m) {
wchar_t path[MAX_PATH * 2] = {};
const DWORD n = GetModuleFileNameW(m, path, MAX_PATH * 2);
if (n == 0 || n >= MAX_PATH * 2) return false;
for (DWORD i = 0; i < n; ++i) path[i] = static_cast<wchar_t>(towlower(path[i]));
std::printf("INFO: loaded from %ls\n", path);
return std::wcsstr(path, L"\\windows\\system32\\xgameruntime.dll") != nullptr;
}
} // namespace
} // namespace
int main(int argc, char** argv) {
const bool expect_missing = argc > 1 && std::strcmp(argv[1], "--expect-missing") == 0;
HMODULE sys = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (expect_missing) {
check(sys == nullptr, "unstaged: LOAD_LIBRARY_SEARCH_SYSTEM32 load fails");
if (sys) FreeLibrary(sys);
} else if (check(sys != nullptr, "LOAD_LIBRARY_SEARCH_SYSTEM32 loads xgameruntime.dll")) {
check(path_in_system32(sys), "module path is under system32");
check(GetProcAddress(sys, "QueryApiImpl") != nullptr, "module exports QueryApiImpl (BetterXen shim)");
HMODULE both = LoadLibraryExW(L"xgameruntime.dll", nullptr,
LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR);
check(both == sys, "SYSTEM32 | APPLICATION_DIR search returns the same module");
if (both) FreeLibrary(both);
FreeLibrary(sys);
int main() {
HMODULE mod = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (!mod) {
std::fprintf(stderr, "FAIL: LoadLibraryExW(xgameruntime.dll, LOAD_LIBRARY_SEARCH_SYSTEM32) failed (err=%lu)\n",
static_cast<unsigned long>(GetLastError()));
return 1;
}
std::printf("SUMMARY: %d checks, %d failed\n", g_checks, g_failures);
return g_failures == 0 ? 0 : 1;
wchar_t path[MAX_PATH] = {};
const DWORD len = GetModuleFileNameW(mod, path, MAX_PATH);
if (len == 0 || len >= MAX_PATH) {
std::fprintf(stderr, "FAIL: GetModuleFileNameW failed (err=%lu)\n", static_cast<unsigned long>(GetLastError()));
FreeLibrary(mod);
return 1;
}
if (!ends_with_ci(path, L"\\windows\\system32\\xgameruntime.dll")) {
std::fprintf(stderr, "FAIL: unexpected module path: %ls\n", path);
FreeLibrary(mod);
return 1;
}
FARPROC init_fn = GetProcAddress(mod, "InitializeApiImpl");
if (!init_fn) {
std::fprintf(stderr, "FAIL: GetProcAddress(InitializeApiImpl) returned null\n");
FreeLibrary(mod);
return 1;
}
FreeLibrary(mod);
std::printf("PASS: test_system32_staging (%ls)\n", path);
return 0;
}
@@ -506,70 +506,6 @@ int main() {
if (bytes[i] == 0xC3 && bytes[i + 1] == 0xA9) ++eacute;
}
CHECK(eacute > 0 && eacute < (long_n - 1) / 2);
// Public Microsoft.GDK.Windows 2610.0.9661 COM IUnknown QueryApiImpl dispatch checks (#456).
{
const GUID core_guid = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
const GUID sys_clsid = {0xE349BD1A, 0xFC20, 0x4E40, {0xB9, 0x9C, 0x41, 0x78, 0xCC, 0x6B, 0x40, 0x9F}};
const GUID sys_iid = {0x1861CF2E, 0xE18B, 0x4834, {0xA9, 0xF5, 0xB4, 0xA4, 0xE6, 0xEF, 0xB4, 0xCF}};
const GUID game_clsid = {0x973A344E, 0x24BF, 0x4D0F, {0x84, 0x57, 0x56, 0xC5, 0x34, 0x89, 0x2B, 0x29}};
const GUID game_iid = {0x2549F142, 0x6419, 0x4A06, {0x97, 0xB5, 0x93, 0x1A, 0xAB, 0x7C, 0x2F, 0x34}};
const GUID net_clsid = {0x37E56907, 0x2F10, 0x41E8, {0xB7, 0x2F, 0x36, 0xED, 0xB1, 0x85, 0x33, 0x1A}};
const GUID net_iid = {0xBF2346B2, 0x39AF, 0x4658, {0xB5, 0xEA, 0x44, 0x71, 0x3C, 0x7E, 0x83, 0xB3}};
const GUID iunknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
void* com_core = nullptr;
CHECK(SUCCEEDED(query_api(&core_guid, &core_guid, &com_core)) && com_core);
auto** core_vtbl = *static_cast<void***>(com_core);
auto qi = reinterpret_cast<HRESULT(WINAPI*)(void*, const GUID*, void**)>(core_vtbl[0]);
auto release = reinterpret_cast<ULONG(WINAPI*)(void*)>(core_vtbl[2]);
auto tq_create = reinterpret_cast<HRESULT(WINAPI*)(void*, uint32_t, uint32_t, void**)>(core_vtbl[12]);
auto tq_close = reinterpret_cast<void(WINAPI*)(void*, void*)>(core_vtbl[17]);
auto unimpl_slot = reinterpret_cast<HRESULT(WINAPI*)(void*)>(core_vtbl[14]);
void* qi_out = nullptr;
CHECK(SUCCEEDED(qi(com_core, &iunknown, &qi_out)) && qi_out == com_core);
void* q = nullptr;
CHECK(SUCCEEDED(tq_create(com_core, 2, 2, &q)) && q);
tq_close(com_core, q);
CHECK(unimpl_slot(com_core) == E_NOTIMPL);
CHECK(release(com_core) >= 1);
void* com_sys = nullptr;
CHECK(SUCCEEDED(query_api(&sys_clsid, &sys_iid, &com_sys)) && com_sys);
auto** sys_vtbl = *static_cast<void***>(com_sys);
auto get_cid = reinterpret_cast<HRESULT(WINAPI*)(void*, size_t, char*, size_t*)>(sys_vtbl[3]);
char cid[64]{};
size_t cid_used = 0;
CHECK(SUCCEEDED(get_cid(com_sys, sizeof(cid), cid, &cid_used)) && cid_used > 1);
void* com_game = nullptr;
CHECK(SUCCEEDED(query_api(&game_clsid, &game_iid, &com_game)) && com_game);
auto** game_vtbl = *static_cast<void***>(com_game);
auto get_tid = reinterpret_cast<HRESULT(WINAPI*)(void*, uint32_t*)>(game_vtbl[3]);
uint32_t title_id = 0;
CHECK(SUCCEEDED(get_tid(com_game, &title_id)) && title_id != 0);
void* com_net = nullptr;
CHECK(SUCCEEDED(query_api(&net_clsid, &net_iid, &com_net)) && com_net);
auto** net_vtbl = *static_cast<void***>(com_net);
struct NetHint { uint32_t lvl, cost, iana; bool init, app, over, roam; };
auto get_hint = reinterpret_cast<HRESULT(WINAPI*)(void*, NetHint*)>(net_vtbl[15]);
NetHint hint{};
CHECK(SUCCEEDED(get_hint(com_net, &hint)) && hint.init);
const GUID user_guid = {0x01ACD177, 0x91F9, 0x4763, {0xA3, 0x8E, 0xCC, 0xBB, 0x55, 0xCE, 0x32, 0xE0}};
void* com_user = nullptr;
CHECK(SUCCEEDED(query_api(&user_guid, &user_guid, &com_user)) && com_user);
auto** user_vtbl = *static_cast<void***>(com_user);
auto reg_ev = reinterpret_cast<HRESULT(WINAPI*)(void*, void*, void*, void*, uint64_t*)>(user_vtbl[33]);
auto unreg_ev = reinterpret_cast<bool(WINAPI*)(void*, uint64_t, bool)>(user_vtbl[34]);
uint64_t ev_tok = 0;
auto dummy_cb = [](void*, uint64_t, uint32_t) {};
CHECK(SUCCEEDED(reg_ev(com_user, nullptr, nullptr, reinterpret_cast<void*>(+dummy_cb), &ev_tok)) && ev_tok != 0);
CHECK(unreg_ev(com_user, ev_tok, false));
CHECK(!unreg_ev(com_user, ev_tok, false));
}
XGameRuntimeUninitialize();
CHECK(XStoreCreateContext(nullptr, &probe) == not_initialized);