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
Ateş ac0fd2e502 Merge pull request #454 from MacosPorters/track-a/408-bx-cli-supervision
[M1-A1] Supervised timeout, cleanup and trace summary for bx-cli run
2026-11-26 20:45:44 +03:00
ates 73c190d725 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 20:43:46 +03:00
ates f3c2b7fe34 Re-resolve bottle prefix on timeout/signal cleanup for managed first-launch stubs
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 20:43:20 +03:00
Ateş 4333a7cc5e Merge pull request #452 from skakwy/track-a/437-api-set-shims
Add API-set resolution fixture and ADR 0007 (#437)
2026-11-26 20:42:35 +03:00
ates 66e9351410 Require valid module lookups in test_apiset_resolution and accept ADR 0007
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 20:42:05 +03:00
Ateş 060083cc56 Merge pull request #441 from devil8blade/track-e/439-xgameruntime-dynamic-api-impl
[M1-E3][ABI] Dynamic GDK loader exports in xgameruntime.dll
2026-11-26 20:36:09 +03:00
atharvranjan 7d7249ee8b Clean up the bottle CrossOver actually launches; limit --backend to bottles
- Locate --bottle through CrossOver's CXBottle module with the launch's
  environment, so CX_BOTTLE_PATH, configured paths and managed bottles are
  stopped correctly. Refuse to launch if it cannot be located.
- Require --bottle for --backend: a bare prefix loads Wine's own D3D12.

Both reproduced by atesahmet0 on #454.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 11:19:36 -06:00
atharvranjan d0395a61da Add supervised timeout and cleanup to bx-cli run (#408)
- --timeout, and cleanup on timeout, SIGINT, SIGTERM or SIGHUP: stop the
  launcher process group, then wineserver for the selected bottle or prefix.
  wineserver -k exit 1 (nothing running) is accepted only if -w succeeds.
- Pass shim overrides with bin/wine --dll and --backend with --env in bottle
  mode, because bin/wine discards WINEDLLOVERRIDES and applies bottle
  settings over the environment. First found by jelly013.
- Print the trace summary after a run with --log.
- Record the libc dependency and a one-host D3D12 swapchain observation.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 11:01:28 -06:00
skakwyandClaude Sonnet 5.5 2eb59e033b Add API-set resolution fixture and ADR 0007 (#437)
test_apiset_resolution imports one export from each of the six win32_bridge
API-set DLLs through the PE import directory and reports, per name, whether a
BetterXen shim file or a host module serves it, and which module the import
address table slot is bound to. --expect host (default) or --expect shim
selects the outcome that passes.

On CrossOver 26.0 all six names are served by the host (twinapi.appcore.dll
for PSM, user32.dll for ntuser) and +loaddll shows no Loaded record for any
shim file. ADR 0007 proposes relying on Wine's built-ins and records that
evidence; a CrossOver 26.3 re-run is still needed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: skakwy <nils_0805@icloud.com>
2026-11-26 17:53:14 +01:00
Ateş eec56dd028 Merge pull request #448 from MacosPorters/track-f/446-boot-texture-computer
[M1-F2] Exercise the texture computer in test_integration_boot
2026-11-26 19:27:14 +03:00
devil8blade e7899574ab Keep XErrorReport logs valid UTF-8 and record loader provenance
Invalid bytes are written as \u00XX and a multi-byte character is not
split when the detail buffer fills. The six loader prototypes are
recorded as BetterXen-defined. The two changelog notes are one entry.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 16:25:51 +00:00
devil8blade 18178da12c Address review: surface unsupported QueryApiImpl in trace, null out on failure
Unsupported and mismatched QueryApiImpl queries keep their structured log
and also call BX_STUB_LOG so bx-cli trace lists them. Failure paths clear
the output pointer. XErrorReport uses the public void signature.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 16:05:11 +00:00
devil8blade 2e895e0f9b Export GDK dynamic loader entry points from xgameruntime.dll
The static loader resolves InitializeApiImpl, InitializeApiImplEx,
InitializeApiImplEx2, UninitializeApiImpl, QueryApiImpl, and XErrorReport
with GetProcAddress. Those initialize entry points share the existing
runtime refcount with XGameRuntimeInitialize and
XGameRuntimeInitializeWithOptions. UninitializeApiImpl releases that same
state. QueryApiImpl dispatches the offline families this DLL already
implements and logs any other class or interface. XErrorReport records
the code and message and does not terminate the process.

Closes #439

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 15:38:34 +00:00
20 changed files with 1836 additions and 49 deletions

No files matched your search

+5
View File
@@ -10,8 +10,12 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- `bx-cli run` now stages allowlisted non-host Xbox shim DLLs (`bx_runtime_veh.dll`, `xgameruntime.dll`) into an initialized bottle/prefix `drive_c/windows/system32/` using an RAII guard so guests using `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)` resolve BetterXen's shim out of the box without permanently mutating the bottle or overwriting pre-existing files/symlinks. Added synthetic conformance fixture `test_system32_staging` (#459).
- `bx-cli run` gained `--timeout <secs>`, cleanup of the launcher process group and the selected bottle or prefix on timeout, SIGINT, SIGTERM or SIGHUP (including re-resolving managed bottles whose first launch creates a private stub), `--backend` (bottle mode only), and a printed trace summary after a run with `--log`. The bottle to stop is located through CrossOver itself, so bottles outside the default directory are covered. A normal exit does not stop the environment. Recorded a one-host observation that D3D12 swapchains stay referenced under D3DMetal (#408).
- Added `test_apiset_resolution`, a conformance fixture that statically imports the six API-set `win32_bridge` names and reports which module serves each (`--expect host|shim`), and accepted ADR 0007 recording that CrossOver 26.0 and 26.3 answer them via built-ins (`twinapi.appcore.dll` / `user32.dll`) (#437).
- Added file-mapping-backed 64 KiB and 2 MiB physical pages, contiguous and scatter aliases (including intra-span duplicate-tag aliasing), exact-span unmap validation, physical region queries (`bx_xmem_query_region`), and shared working-set accounting / combined title memory budget enforcement across heap, virtual, and physical allocations in `xmem.dll`. Synthetic `XMemAllocatePhysicalPages` / `XMemFreePhysicalPages` signatures follow Win32 AWE (`memoryapi.h`) pending a public console flag encoding (#412).
- Added Win32 bridge conformance coverage for a hidden window, message dispatch, concurrent PSM registrations, and per-event JSONL log verification. Offline PSM registration tokens are tracked without C++ exceptions using disjoint family tags so cross-family unregisters log `foreign_token` and retired or invalid tokens log `unknown_token` (#410).
- `xgameruntime.dll` exports BetterXen-defined `InitializeApiImpl`, `InitializeApiImplEx`, `InitializeApiImplEx2`, `UninitializeApiImpl`, `QueryApiImpl`, and `XErrorReport` so a static loader can resolve them. No public prototype for those six names was found. The documented `XGameRuntimeInitialize`, `XGameRuntimeUninitialize`, `XGameRuntimeInitializeWithOptions`, and `XGameRuntimeOptions` behavior is what the shared refcount follows. `QueryApiImpl` rejects a missing output or id, clears the output pointer on failure, dispatches the offline families this DLL already implements, and logs any other class through `BX_STUB_LOG` before `E_NOINTERFACE`. `XErrorReport` is `void` and writes only valid UTF-8, replacing an invalid byte with `\u00XX` and truncating on a character boundary. The DLL has 49 exports. This is not an Xbox hardware result (#439).
- Implemented synthetic APU heap mappings, per-connection APU and DSP queues, and the GameInput ordinal 1 COM stub. Added an audio/input conformance executable covering all four shim DLLs (#419).
- Added structured unhandled exception logging with module-relative addresses and x64 registers, and expanded the CLWB conformance test to require six traps across ModRM, SIB, REX and RIP-relative operands (#409).
- Enforced the configured title memory cap for default heap allocations and virtual commits in `xmem.dll`. Added working-set accounting and a synthetic fixture for alignment, commit overlap, decommit, release, and memory transfer (#411).
@@ -71,6 +75,7 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- 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).
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
Generated
+7
View File
@@ -9,6 +9,7 @@ dependencies = [
"bx-probe",
"bx-telemetry",
"dxbc-accc",
"libc",
]
[[package]]
@@ -29,3 +30,9 @@ dependencies = [
[[package]]
name = "dxbc-accc"
version = "0.2.0"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+1 -1
View File
@@ -132,7 +132,7 @@ The repository is organized into disjoint track directories around a single froz
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 16 shim DLLs |
| `launcher/` | Track A | Rust (`arm64`) | `bx-cli` (`doctor`, `probe`, `shader`, `trace`, `run`), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
| `shims/runtime_veh/` | Track A | C++20 (`x86_64` PE) | `bx_runtime_veh.dll`: `clwb` VEH trap, `adcx`/`adox` tripwire, Lockhart/Anaconda memory profile config, structured JSONL logging |
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders |
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; CrossOver answers these API-set names itself for static imports, so the files are not loaded that way ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
| `shims/xmem/`, `shims/xcrdapi/` | Track B | C++20 (`x86_64` PE) | `xmem.dll` (13 Xbox memory APIs + internal region stats) and `XCRDAPI.dll` (`DStorageGetFactory` async I/O) |
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Track C | C++20 (`x86_64` PE) | Xbox D3D12 COM proxy over D3DMetal 3.0, RDNA 2 texture tiling (`XG`), and future FidelityFX/BVH4 hooks |
| `shader-transpiler/` | Track D | Rust (`arm64`) | `dxbc-accc` (`DXBC`/`DXIL`/`ACCC`/`FSPX` classifier), future RDNA 2 transpiler & `d3dmetal-native` isolation harness |
+2
View File
@@ -2,6 +2,8 @@
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has **zero external crates.io dependencies** and is original `GPL-3.0-or-later` source.
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. Preserve the Rust Project Developers notice and permission text.
## External Host Tools & Runtime Dependencies (Never Bundled)
| Component | Role | Licensing & Provenance |
+6
View File
@@ -43,3 +43,9 @@ EXPORTS
XGameUiShowTextEntryAsync
XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync
XNetworkingQuerySecurityInformationForUrlAsync
InitializeApiImpl
InitializeApiImplEx
InitializeApiImplEx2
UninitializeApiImpl
QueryApiImpl
XErrorReport
+2
View File
@@ -14,6 +14,7 @@
- [ADR 0005: CrossOver-based hybrid direction](adr/0005-crossover-hybrid-direction.md) — Pivot to CrossOver + Rosetta 2 + D3DMetal as the external foundation.
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
## Research, Testing & Licensing
@@ -21,6 +22,7 @@
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — One-host observation to check before M2 presentation work.
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
## Governance, Security & Legal
@@ -0,0 +1,45 @@
# ADR 0007: API-set win32_bridge shims are not reached under CrossOver
Status: **Accepted** (2026-11-26, issue #437). Independently verified on CrossOver 26.0 and CrossOver 26.3 on Apple Silicon.
## Context
`shims/win32_bridge/` builds six DLLs named after Windows API sets:
`api-ms-win-core-psm-appnotify-l1-1-0`, `api-ms-win-core-psm-appnotify-l1-1-1` and four `ext-ms-win-rtcore-ntuser-*` forwarders to `user32.dll`. A guest that imports those names statically is expected to load the BetterXen files placed next to the EXE. #437 reports that under CrossOver 26.3 it does not: Wine answers the names itself, even with `WINEDLLOVERRIDES=<name>=n,b` and the shim files in the EXE's directory.
## Evidence
`tests/conformance/test_apiset_resolution` imports one export from each of the six DLLs through the PE import directory, then reports for every name the module that owns the name and the module the loader bound the import address table slot to.
Run on an Apple M-series Mac, macOS 27.2.1, Rosetta 2, **CrossOver 26.0 (`26.0.0.39794`)**, bare prefix, with the override list from `bx-cli` (`SHIM_DLL_OVERRIDES`) and `build-shims/bin` as the EXE directory:
| Import name | Served by | Module that owns the name | Module the import is bound to |
| --- | --- | --- | --- |
| `api-ms-win-core-psm-appnotify-l1-1-0` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
| `api-ms-win-core-psm-appnotify-l1-1-1` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
| `ext-ms-win-rtcore-ntuser-message-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
| `ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
| `ext-ms-win-rtcore-ntuser-window-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
| `ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
`WINEDEBUG=+loaddll` shows `Loaded` records for `user32.dll` and `twinapi.appcore.dll` (both builtin) and none for any of the six shim files. `--expect shim` fails 0/6, so the fixture does distinguish the two outcomes.
This behaviour was independently reproduced on **CrossOver 26.3** on Apple Silicon (`bx-cli run` with the shim directory and direct loader runs with `WINEDEBUG=+loaddll`), yielding the exact same 6/6 host resolution (`twinapi.appcore.dll` and `user32.dll`, both builtin, with no `Loaded` records for the six shim files) and `--expect shim` exiting 1. The internal Wine mechanism is not claimed here; this records observed loader behaviour.
## Decision
Rely on Wine's built-ins. Under CrossOver the six API-set shims are not part of the supported path: the host answers window and message calls through `user32.dll` and PSM registration through `twinapi.appcore.dll`.
- The six DLLs stay in the tree, built and export-checked, and are still exercised by explicit full-path loads (#431).
- No attempt is made to make them win name resolution. That would depend on undocumented Wine API-set behaviour (#350) and, within this issue's scope, on patching or redistributing CrossOver or Wine components, which is out of scope.
- Offline PSM behaviour that a title needs must live somewhere a static import actually reaches. This ADR does not choose that place.
## Consequences
- `test_apiset_resolution` records the current behaviour (`--expect host`) and fails when it changes. If a CrossOver build starts loading the shims, run it with `--expect shim` and revisit this ADR.
- `test_integration_boot` continues to report `shim_backing` as pending for these six names under CrossOver.
- Documentation describes the bridges as Windows-only stubs that CrossOver does not load for static imports.
## Not claimed
Nothing here shows Xbox title compatibility, behaviour on Xbox hardware, or behaviour on CrossOver builds outside 26.0 and 26.3. Evidence class: local Apple Silicon runs.
+1 -1
View File
@@ -9,7 +9,7 @@ BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-bas
| `abi/` | Shared (frozen) | C headers + `.def` | Cross-DLL contracts (`bx_log.h`, `bx_config.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical DLL export lists |
| `launcher/` | Track A | Rust (`aarch64-apple-darwin`) | Native ARM64 macOS CLI (`bx-cli`), PE32+ static probe (`bx-probe`), JSONL trace aggregator (`bx-telemetry`) |
| `shims/runtime_veh/` | Track A | C++20 (`mingw-w64`) | `bx_runtime_veh.dll`: `clwb` VEH handler, `adcx`/`adox` tripwire, Lockhart/Anaconda config, JSONL trace logger |
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders |
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
| `shims/xmem/` | Track B | C++20 (`mingw-w64`) | `xmem.dll`: physical/virtual/scatter memory allocator, `__XMemAllocationHooks__`, 16 GB Lockhart cap |
| `shims/xcrdapi/` | Track B | C++20 (`mingw-w64`) | `XCRDAPI.dll`: DirectStorage async I/O factory, queues, and decompression |
| `shims/d3d12_xs/` | Track C1 | C++20 (`mingw-w64`) | `d3d12_xs.dll`: Xbox D3D12 COM proxy over Wine `d3d12.dll` (D3DMetal 3.0), `PresentX`, placed resources |
+1
View File
@@ -20,5 +20,6 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
| x86-64 decode and ARM64 translation, runtime, gfx1030 compiler, Metal backend | BetterXen native implementation | **Preserved, paused** | Reuse only where hybrid needs it and it shows a demonstrated advantage; not forced into the architecture. |
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
| Process groups and signals for `bx-cli run` | rust-lang/libc 0.2.191 (MIT) | **Reuse** | Unmodified crates.io dependency (#408). |
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
@@ -0,0 +1,20 @@
# D3D12 swapchain references under D3DMetal
An observation to check before M2 builds presentation on `IDXGISwapChain3`. One Apple M4,
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. Not independently reproduced, and not an
Xbox hardware result.
| | D3DMetal | Wine `vkd3d` path |
| --- | --- | --- |
| References on the swapchain right after creation | 2 | 1 |
| Count returned by the application's final `Release` | 1 | 0 |
| Swapchains still referenced after 12 create/release cycles | 12 | 0 |
The same program was used for both, and it submitted no GPU work of its own. Under D3DMetal
each retained swapchain also kept a device reference. The cause inside D3DMetal is unknown. A
program that recreates swapchains (for example on resize) should be expected to grow until this
is explained.
The probe is
[`lifetime.c` at `7c512af`](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_lifetime/lifetime.c)
on the branch of #425; it is not part of this branch. Tracked in #450.
+1
View File
@@ -14,6 +14,7 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
| VIctory | [Marvisak/VIctory](https://github.com/Marvisak/VIctory) | `13f91caee25f` | GPL-3.0 (GitHub); a prior local review found per-file notices (see `experiments/victory-native/licenses.md`, local, untracked) | Discovery reference only | Described as an attempt at running one commercial game on PC. Its inputs are an Xbox Series build of that game. PortWatch describes the efforts it tracks as targeting a "leaked Xbox Series build". |
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in retired `portwatch-native-macos.md` at tag `native-first-final`). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
| libc | [rust-lang/libc](https://github.com/rust-lang/libc) | `0.2.191` (`ccc2ff4aaab9`) | MIT OR Apache-2.0 (used under MIT) | `bx-cli` process groups and signals (#408) | Unmodified crates.io dependency, locked checksum. |
## Built and run for M1-D2 (#417)
+2
View File
@@ -13,6 +13,8 @@ path = "src/main.rs"
bx-probe = { path = "../bx-probe" }
bx-telemetry = { path = "../bx-telemetry" }
dxbc-accc = { path = "../../../shader-transpiler/crates/dxbc-accc" }
# POSIX signals and process groups for `run` supervision.
libc = "=0.2.191"
[lints]
workspace = true
+643 -43
View File
@@ -1,20 +1,107 @@
//! Track A (M1-A1): Native ARM64 macOS CLI for BetterXen hybrid execution.
mod supervise;
use std::collections::BTreeMap;
use std::env;
use std::fs;
use std::fmt::Write as _;
use std::fs::{self, OpenOptions};
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use std::time::Duration;
use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus};
use bx_telemetry::summarize_jsonl;
use dxbc_accc::inspect_dxbc;
use supervise::{Outcome, Stop};
const SHIM_DLL_OVERRIDES: &str = "bx_runtime_veh,d3d12_xs,xg_xs,xmem,XCRDAPI,xgameruntime,AcpHal,xapu,chad,GameInput,\
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"];
const SAFE_CHILD_PATH: &str = "/usr/bin:/bin:/usr/sbin:/sbin";
const HOST_ENV_ALLOWLIST: &[&str] = &[
@@ -39,7 +126,8 @@ fn print_usage() {
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env]\n"
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)]\n\
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix)\n"
);
}
@@ -171,20 +259,29 @@ fn cmd_trace(path: &str) -> ExitCode {
return ExitCode::FAILURE;
}
};
let summary = summarize_jsonl(&text);
println!("Trace events : {}", summary.total_lines);
println!(
print!("{}", render_trace(&text));
ExitCode::SUCCESS
}
fn render_trace(text: &str) -> String {
let mut out = String::new();
let summary = summarize_jsonl(text);
let _ = writeln!(out, "Trace events : {}", summary.total_lines);
let _ = writeln!(
out,
"{}",
format_clwb_line(summary.clwb_events, summary.clwb_trap_lower_bound)
);
println!("ADX illegal ops : {}", summary.adx_errors);
let _ = writeln!(out, "ADX illegal ops : {}", summary.adx_errors);
if !summary.unhandled_exceptions.is_empty() {
println!(
let _ = writeln!(
out,
"\nUnhandled exceptions ({}):",
summary.unhandled_exceptions.len()
);
for crash in summary.unhandled_exceptions {
println!(
let _ = writeln!(
out,
" code={} module_base={} + RVA={} RIP={}",
crash.exception_code.as_deref().unwrap_or("unknown"),
crash.module_base.as_deref().unwrap_or("unknown"),
@@ -194,18 +291,18 @@ fn cmd_trace(path: &str) -> ExitCode {
}
}
if !summary.unimpl_apis.is_empty() {
println!("\nUnimplemented APIs:");
let _ = writeln!(out, "\nUnimplemented APIs:");
for (api, count) in summary.unimpl_apis {
println!(" {count:5}x {api}");
let _ = writeln!(out, " {count:5}x {api}");
}
}
if !summary.unimpl_vtables.is_empty() {
println!("\nUnimplemented COM vtable slots:");
let _ = writeln!(out, "\nUnimplemented COM vtable slots:");
for (slot, count) in summary.unimpl_vtables {
println!(" {count:5}x {slot}");
let _ = writeln!(out, " {count:5}x {slot}");
}
}
ExitCode::SUCCESS
out
}
fn unix_to_wine_z_path(path: &Path) -> String {
@@ -227,7 +324,20 @@ where
env_map
}
fn cmd_run(args: &[String]) -> ExitCode {
#[derive(Debug)]
struct RunArgs {
exe: PathBuf,
shims_dir: PathBuf,
profile: String,
bottle: Option<String>,
prefix: Option<PathBuf>,
log: Option<PathBuf>,
inherit_env: bool,
timeout: Option<Duration>,
backend: Option<String>,
}
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
let mut exe_path: Option<PathBuf> = None;
let mut shims_dir = PathBuf::from("build-shims/bin");
let mut profile = String::from("lockhart");
@@ -235,6 +345,8 @@ fn cmd_run(args: &[String]) -> ExitCode {
let mut wine_prefix: Option<PathBuf> = None;
let mut log_file: Option<PathBuf> = None;
let mut inherit_env = false;
let mut timeout = None;
let mut backend: Option<String> = None;
let mut i = 0;
while i < args.len() {
@@ -263,21 +375,164 @@ fn cmd_run(args: &[String]) -> ExitCode {
log_file = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
"--timeout" if i + 1 < args.len() => {
let seconds: u64 = args[i + 1]
.parse()
.ok()
.filter(|s| *s > 0)
.ok_or("--timeout needs a whole number of seconds above 0")?;
timeout = Some(Duration::from_secs(seconds));
i += 2;
}
"--backend" if i + 1 < args.len() => {
let name = args[i + 1].clone();
if !BACKENDS.contains(&name.as_str()) {
return Err(format!(
"unknown backend {name:?}; use one of {}",
BACKENDS.join(", ")
));
}
backend = Some(name);
i += 2;
}
"--inherit-env" => {
inherit_env = true;
i += 1;
}
other => {
eprintln!("unknown argument: {other}");
return ExitCode::FAILURE;
}
other => return Err(format!("unknown argument: {other}")),
}
}
let Some(exe) = exe_path else {
eprintln!("error: --exe <path> is required");
return ExitCode::FAILURE;
if let Some(name) = &bottle
&& (name.is_empty() || name.starts_with(['-', '.']) || name.contains('/'))
{
return Err(format!("invalid bottle name {name:?}"));
}
if backend.is_some() && bottle.is_none() {
// A bare prefix loads Wine's own D3D12 whatever CX_GRAPHICS_BACKEND says (observed on
// CrossOver 26.3), so accepting it would claim a backend that is not in use.
return Err("--backend needs --bottle; a bare prefix cannot be made to use it".into());
}
Ok(RunArgs {
exe: exe_path.ok_or("error: --exe <path> is required")?,
shims_dir,
profile,
bottle,
prefix: wine_prefix,
log: log_file,
inherit_env,
timeout,
backend,
})
}
/// Asks CrossOver's installed `CXBottle` module where `--bottle` points, so cleanup targets the
/// prefix the launch uses. `bin/wine` searches `CX_BOTTLE_PATH`, configured paths and managed
/// bottles, so a fixed directory would be wrong for some bottles.
const BOTTLE_PREFIX_QUERY: &str = r#"
use lib "$ENV{CX_ROOT}/lib/perl";
require CXBottle;
CXBottle::get_crossover_config();
my ($scope, $found) = CXBottle::setup_bottle_wineprefix(undef);
die "$@\n" unless defined $scope;
print $ENV{WINEPREFIX};
"#;
/// The environment `bin/wine` starts from, shared by the launch and the bottle lookup.
fn apply_host_env(command: &mut Command, inherit_env: bool) {
if !inherit_env {
command.env_clear();
for (k, v) in collect_isolated_host_env(|k| env::var(k).ok()) {
command.env(k, v);
}
}
// Inherited values must not point the launcher at a different bottle than cleanup does.
command.env_remove("WINEPREFIX").env_remove("CX_BOTTLE");
}
fn resolve_bottle_prefix(
cx_root: &Path,
mut command: Command,
name: &str,
) -> Result<PathBuf, String> {
let output = command
.env("CX_ROOT", cx_root)
.env("CX_BOTTLE", name)
.args(["-e", BOTTLE_PREFIX_QUERY])
.output()
.map_err(|e| format!("cannot ask CrossOver where bottle {name:?} is: {e}"))?;
let path = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
if !output.status.success() || !path.is_absolute() || !path.is_dir() {
return Err(format!(
"CrossOver cannot locate bottle {name:?}: {}",
String::from_utf8_lossy(&output.stderr).trim()
));
}
Ok(path)
}
fn resolve_bottle_prefix_with_host_env(
cx_root: &Path,
name: &str,
inherit_env: bool,
) -> Result<PathBuf, String> {
let mut query = Command::new("/usr/bin/perl");
apply_host_env(&mut query, inherit_env);
resolve_bottle_prefix(cx_root, query, name)
}
/// Collects the prefixes that cleanup must stop. Re-resolving a named bottle after launch catches
/// the case where a managed-only bottle caused CrossOver's `bin/wine` to create and launch inside
/// a new private stub bottle.
fn cleanup_prefixes_for_stop<F>(
initial_prefix: &Path,
bottle: Option<&str>,
mut re_resolve: F,
) -> Result<Vec<PathBuf>, String>
where
F: FnMut(&str) -> Result<PathBuf, String>,
{
let mut prefixes = Vec::new();
if let Some(name) = bottle {
let current = re_resolve(name)?;
prefixes.push(current);
}
if !prefixes.iter().any(|p| p == initial_prefix) {
prefixes.push(initial_prefix.to_path_buf());
}
Ok(prefixes)
}
/// `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> {
let mut options = vec!["--dll".to_string(), SHIM_DLL_OVERRIDES.to_string()];
if let Some(backend) = backend {
options.push("--env".to_string());
options.push(format!("CX_GRAPHICS_BACKEND={backend}"));
}
options
}
fn cmd_run(args: &[String]) -> ExitCode {
let run = match parse_run_args(args) {
Ok(run) => run,
Err(e) => {
eprintln!("{e}");
return ExitCode::FAILURE;
}
};
let RunArgs {
exe,
shims_dir,
profile,
bottle,
prefix: wine_prefix,
log: log_file,
inherit_env,
timeout,
backend,
} = run;
let cx_root = Path::new("/Applications/CrossOver.app/Contents/SharedSupport/CrossOver");
let wine_wrapper = cx_root.join("bin/wine");
@@ -294,9 +549,23 @@ fn cmd_run(args: &[String]) -> ExitCode {
let resolved_prefix =
wine_prefix.unwrap_or_else(|| PathBuf::from("/tmp/betterxen-wine-prefix"));
// The environment a timeout or signal has to stop.
let environment_dir = match &bottle {
Some(name) => match resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env) {
Ok(path) => path,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::FAILURE;
}
},
None => resolved_prefix.clone(),
};
let mut cmd = if let Some(ref bname) = bottle {
let mut c = Command::new(&wine_wrapper);
c.args(["--bottle", bname]).arg(&abs_exe);
c.args(["--bottle", bname])
.args(bottle_options(backend.as_deref()))
.arg(&abs_exe);
c
} else {
let _ = fs::create_dir_all(&resolved_prefix);
@@ -305,12 +574,7 @@ fn cmd_run(args: &[String]) -> ExitCode {
c
};
if !inherit_env {
cmd.env_clear();
for (k, v) in collect_isolated_host_env(|k| env::var(k).ok()) {
cmd.env(k, v);
}
}
apply_host_env(&mut cmd, inherit_env);
if bottle.is_none() {
cmd.env("WINEPREFIX", &resolved_prefix)
@@ -340,26 +604,86 @@ fn cmd_run(args: &[String]) -> ExitCode {
.env("BX_PROFILE", &profile)
.env("WINEDEBUG", "-all");
if let Some(ref lf) = log_file {
let abs_log = if lf.is_absolute() {
lf.clone()
let abs_log = log_file.map(|lf| {
if lf.is_absolute() {
lf
} else {
env::current_dir().unwrap_or_default().join(lf)
};
cmd.env("BX_LOG_FILE", unix_to_wine_z_path(&abs_log));
}
});
if let Some(log) = &abs_log {
cmd.env("BX_LOG_FILE", unix_to_wine_z_path(log));
}
let log_size = |log: &PathBuf| fs::metadata(log).map_or(0, |m| m.len());
let log_size_before = abs_log.as_ref().map_or(0, log_size);
let mut staged_shims =
StagedSystem32Shims::stage(&environment_dir, &abs_shims, SYSTEM32_STAGED_SHIMS);
supervise::install_signal_handlers();
let outcome = supervise::supervise(cmd, timeout, supervise::received_signal);
let code = match &outcome {
Ok(outcome) => outcome.exit_code(),
Err(e) => {
eprintln!("failed to run CrossOver wine: {e}");
1
}
};
let mut cleanup_failed = false;
match &outcome {
Ok(Outcome::Exited(status)) if !status.success() => {
eprintln!("guest exited with status: {status}");
}
Ok(Outcome::Stopped(stop)) => {
match stop {
Stop::TimedOut => eprintln!("timed out; stopping the environment"),
Stop::Signalled(signal) => {
eprintln!("received signal {signal}; stopping the environment");
}
}
let server_env: Vec<(String, String)> = collect_isolated_host_env(|k| env::var(k).ok())
.into_iter()
.collect();
let prefixes_to_stop =
match cleanup_prefixes_for_stop(&environment_dir, bottle.as_deref(), |name| {
resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env)
}) {
Ok(prefixes) => prefixes,
Err(e) => {
eprintln!("cleanup failed to re-resolve bottle prefix: {e}");
cleanup_failed = true;
vec![environment_dir.clone()]
}
};
for prefix in &prefixes_to_stop {
if let Err(e) =
supervise::stop_server(&cx_root.join("bin/wineserver"), prefix, &server_env)
{
eprintln!("cleanup failed, programs may still be running: {e}");
cleanup_failed = true;
}
}
}
_ => {}
}
match cmd.status() {
Ok(st) if st.success() => ExitCode::SUCCESS,
Ok(st) => {
eprintln!("guest exited with status: {st}");
ExitCode::FAILURE
}
Err(e) => {
eprintln!("failed to launch CrossOver wine: {e}");
ExitCode::FAILURE
}
// 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
&& let Ok(bytes) = fs::read(log)
{
// Guest text may not be valid UTF-8; a summary is still worth printing.
print!(
"\nTrace summary of {}:\n{}",
log.display(),
render_trace(&String::from_utf8_lossy(&bytes))
);
}
// 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 })
}
fn cmd_shader(path: &str) -> ExitCode {
@@ -416,6 +740,197 @@ fn main() -> ExitCode {
mod tests {
use super::*;
fn args(list: &[&str]) -> Vec<String> {
list.iter().map(|s| s.to_string()).collect()
}
#[test]
fn parses_run_arguments() {
for bare in [&["--prefix", "/tmp/p"][..], &[]] {
let mut list = args(&["--exe", "a.exe", "--backend", "d3dmetal"]);
list.extend(args(bare));
let error = parse_run_args(&list).unwrap_err();
assert!(error.contains("--backend needs --bottle"), "{error}");
}
let run = parse_run_args(&args(&[
"--exe",
"a.exe",
"--bottle",
"b",
"--timeout",
"30",
"--backend",
"d3dmetal",
]))
.unwrap();
assert_eq!(run.timeout, Some(Duration::from_secs(30)));
assert_eq!(run.backend.as_deref(), Some("d3dmetal"));
assert_eq!(run.shims_dir, PathBuf::from("build-shims/bin"));
assert_eq!(run.profile, "lockhart");
let plain = parse_run_args(&args(&["--exe", "a.exe"])).unwrap();
assert!(plain.timeout.is_none() && plain.bottle.is_none() && plain.prefix.is_none());
for bad in [
&["--exe", "a.exe", "--timeout", "0"][..],
&["--exe", "a.exe", "--timeout", "soon"],
&["--exe", "a.exe", "--backend", "dmxt2"],
&["--exe", "a.exe", "--bottle", "../x"],
&["--exe", "a.exe", "--timeout"],
&["--bottle", "b"],
] {
assert!(parse_run_args(&args(bad)).is_err(), "{bad:?}");
}
}
// A stub CXBottle stands in for CrossOver's: this checks the lookup's environment and that
// a timeout's cleanup is aimed at the prefix it returns, not at the default directory.
#[test]
fn a_timeout_cleans_up_a_bottle_outside_the_default_directory() {
use std::os::unix::fs::PermissionsExt;
let root = env::temp_dir().join(format!("bx-cli-altbottle-{}", std::process::id()));
let bottle = root.join("elsewhere/mine");
fs::create_dir_all(&bottle).unwrap();
fs::create_dir_all(root.join("cx/lib/perl")).unwrap();
fs::write(
root.join("cx/lib/perl/CXBottle.pm"),
r#"package CXBottle;
sub get_crossover_config {}
sub setup_bottle_wineprefix {
my $p = "$ENV{CX_BOTTLE_PATH}/$ENV{CX_BOTTLE}";
return (undef, undef) unless -d $p;
$ENV{WINEPREFIX} = $p;
return ('private', $p);
}
1;
"#,
)
.unwrap();
let query = |name: &str| {
let mut command = Command::new("/usr/bin/perl");
command.env("CX_BOTTLE_PATH", root.join("elsewhere"));
resolve_bottle_prefix(&root.join("cx"), command, name)
};
assert!(query("absent").is_err());
let prefix = query("mine").unwrap();
assert_eq!(prefix, bottle);
let server = root.join("wineserver");
let seen = root.join("seen");
fs::write(
&server,
format!(
"#!/bin/sh\necho \"$1 $WINEPREFIX\" >> '{}'\n",
seen.display()
),
)
.unwrap();
fs::set_permissions(&server, fs::Permissions::from_mode(0o755)).unwrap();
let mut sleeper = Command::new("/bin/sh");
sleeper.args(["-c", "sleep 30"]);
let outcome =
supervise::supervise(sleeper, Some(Duration::from_millis(200)), || 0).unwrap();
assert!(matches!(outcome, Outcome::Stopped(Stop::TimedOut)));
supervise::stop_server(&server, &prefix, &[]).unwrap();
let expected = format!("-k {0}\n-w {0}\n", bottle.display());
assert_eq!(fs::read_to_string(&seen).unwrap(), expected);
fs::remove_dir_all(root).unwrap();
}
// Regression test starting with only a managed bottle and no private stub: the launch creates
// the private stub, and timeout cleanup re-resolves via CXBottle so wineserver stops the stub.
#[test]
fn a_timeout_cleans_up_a_managed_bottle_private_stub_created_on_first_launch() {
use std::os::unix::fs::PermissionsExt;
let root = env::temp_dir().join(format!("bx-cli-managed-stub-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let managed = root.join("managed/corp");
let private_dir = root.join("private");
let private_stub = private_dir.join("corp");
fs::create_dir_all(&managed).unwrap();
fs::create_dir_all(&private_dir).unwrap();
fs::create_dir_all(root.join("cx/lib/perl")).unwrap();
fs::write(
root.join("cx/lib/perl/CXBottle.pm"),
r#"package CXBottle;
sub get_crossover_config {}
sub setup_bottle_wineprefix {
my $priv = "$ENV{CX_BOTTLE_PATH}/$ENV{CX_BOTTLE}";
if (-f "$priv/system.reg") {
$ENV{WINEPREFIX} = $priv;
return ('private', $priv);
}
my $mgmt = "$ENV{CX_MANAGED_BOTTLE_PATH}/$ENV{CX_BOTTLE}";
if (-d $mgmt) {
$ENV{WINEPREFIX} = $mgmt;
return ('managed', $mgmt);
}
return (undef, undef);
}
1;
"#,
)
.unwrap();
let query = |name: &str| {
let mut command = Command::new("/usr/bin/perl");
command
.env("CX_BOTTLE_PATH", &private_dir)
.env("CX_MANAGED_BOTTLE_PATH", root.join("managed"));
resolve_bottle_prefix(&root.join("cx"), command, name)
};
// Before launch there is no private stub, so CXBottle reports the managed bottle.
assert!(!private_stub.exists());
let initial = query("corp").unwrap();
assert_eq!(initial, managed);
// Simulated first launch creates the private stub before hanging until timeout.
let mut launcher = Command::new("/bin/sh");
launcher.args([
"-c",
&format!(
"mkdir -p '{0}' && touch '{0}/system.reg' && exec sleep 30",
private_stub.display()
),
]);
let outcome =
supervise::supervise(launcher, Some(Duration::from_millis(300)), || 0).unwrap();
assert!(matches!(outcome, Outcome::Stopped(Stop::TimedOut)));
let prefixes = cleanup_prefixes_for_stop(&initial, Some("corp"), query).unwrap();
assert_eq!(prefixes, vec![private_stub.clone(), managed.clone()]);
let server = root.join("wineserver");
let seen = root.join("seen");
fs::write(
&server,
format!(
"#!/bin/sh\necho \"$1 $WINEPREFIX\" >> '{}'\n",
seen.display()
),
)
.unwrap();
fs::set_permissions(&server, fs::Permissions::from_mode(0o755)).unwrap();
for prefix in &prefixes {
supervise::stop_server(&server, prefix, &[]).unwrap();
}
let expected = format!(
"-k {0}\n-w {0}\n-k {1}\n-w {1}\n",
private_stub.display(),
managed.display()
);
assert_eq!(fs::read_to_string(&seen).unwrap(), expected);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn bottle_mode_passes_overrides_and_backend_as_launcher_options() {
assert_eq!(bottle_options(None), ["--dll", SHIM_DLL_OVERRIDES]);
assert_eq!(
bottle_options(Some("dxvk"))[2..],
["--env", "CX_GRAPHICS_BACKEND=dxvk"]
);
}
#[test]
fn isolated_env_strips_secrets_and_pins_path() {
let host = BTreeMap::from([
@@ -452,4 +967,89 @@ mod tests {
"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();
}
}
+245
View File
@@ -0,0 +1,245 @@
//! Supervision for `bx-cli run` (#408): the launcher gets its own process group, and a timeout
//! or signal stops that group and then the environment's `wineserver`.
//!
//! The `wineserver` is stopped only after a timeout or signal, never after a normal exit,
//! because it ends every program in that bottle or prefix, not only this run's.
use std::io::IsTerminal;
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::atomic::{AtomicI32, Ordering};
use std::time::{Duration, Instant};
const POLL: Duration = Duration::from_millis(50);
/// How long the launcher group has to exit after SIGTERM before SIGKILL.
const GRACE: Duration = Duration::from_secs(5);
const SERVER_WAIT: Duration = Duration::from_secs(15);
static SIGNAL: AtomicI32 = AtomicI32::new(0);
extern "C" fn note_signal(signal: libc::c_int) {
SIGNAL.store(signal, Ordering::SeqCst);
}
/// Records SIGINT, SIGTERM and SIGHUP instead of dying, so the run can be cleaned up.
pub fn install_signal_handlers() {
for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
// SAFETY: the handler only stores to an atomic, which is async-signal-safe.
unsafe {
libc::signal(
signal,
note_signal as extern "C" fn(libc::c_int) as libc::sighandler_t,
);
}
}
}
pub fn received_signal() -> i32 {
SIGNAL.load(Ordering::SeqCst)
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Stop {
TimedOut,
Signalled(i32),
}
#[derive(Debug)]
pub enum Outcome {
Exited(ExitStatus),
Stopped(Stop),
}
impl Outcome {
/// 0 or 1 for the guest's own result, 124 for a timeout (as `timeout(1)`), 128 + N for a
/// signal.
pub fn exit_code(&self) -> u8 {
match self {
Outcome::Exited(status) => u8::from(!status.success()),
Outcome::Stopped(Stop::TimedOut) => 124,
Outcome::Stopped(Stop::Signalled(signal)) => 128u8.saturating_add(*signal as u8),
}
}
}
fn signal_group(child: &Child, signal: libc::c_int) {
// SAFETY: kill takes no pointers. The child leads its own group and has not been reaped,
// so the group id cannot have been reused.
unsafe {
libc::kill(-(child.id() as libc::pid_t), signal);
}
}
fn wait_until(child: &mut Child, deadline: Instant) -> std::io::Result<Option<ExitStatus>> {
loop {
if let Some(status) = child.try_wait()? {
return Ok(Some(status));
}
if Instant::now() >= deadline {
return Ok(None);
}
std::thread::sleep(POLL);
}
}
/// Runs `command` in a new process group until it exits, `timeout` passes, or `signal`
/// returns non-zero. On a stop the whole group is terminated before this returns.
pub fn supervise(
mut command: Command,
timeout: Option<Duration>,
signal: impl Fn() -> i32,
) -> std::io::Result<Outcome> {
// A background process group is stopped by SIGTTIN if it reads the terminal, so a terminal
// is replaced by end-of-file. Piped and redirected input is passed through.
if std::io::stdin().is_terminal() {
command.stdin(Stdio::null());
}
let mut child = command.process_group(0).spawn()?;
let started = Instant::now();
let stop = loop {
if let Some(status) = child.try_wait()? {
return Ok(Outcome::Exited(status));
}
let received = signal();
if received != 0 {
break Stop::Signalled(received);
}
if timeout.is_some_and(|limit| started.elapsed() >= limit) {
break Stop::TimedOut;
}
std::thread::sleep(POLL);
};
signal_group(&child, libc::SIGTERM);
// Wait without reaping first, so SIGKILL still reaches members that outlive the leader.
std::thread::sleep(POLL);
let deadline = Instant::now() + GRACE;
while Instant::now() < deadline && group_leader_running(&child) {
std::thread::sleep(POLL);
}
signal_group(&child, libc::SIGKILL);
wait_until(&mut child, Instant::now() + GRACE)?;
Ok(Outcome::Stopped(stop))
}
/// True while the leader has not exited; does not reap it.
fn group_leader_running(child: &Child) -> bool {
// SAFETY: `info` is a valid, writable siginfo_t and WNOWAIT leaves the child unreaped.
unsafe {
let mut info: libc::siginfo_t = std::mem::zeroed();
libc::waitid(
libc::P_PID,
child.id() as libc::id_t,
&mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
) == 0
&& info.si_pid() == 0
}
}
/// `wineserver -k` then `-w` for the environment at `prefix`.
///
/// `-k` exits 1 when no server is running (observed on CrossOver 26.3), so 1 is accepted
/// there; `-w` must still succeed, which a surviving server prevents.
pub fn stop_server(
wineserver: &Path,
prefix: &Path,
environment: &[(String, String)],
) -> Result<(), String> {
for (flag, idle_code) in [("-k", Some(1)), ("-w", None)] {
let mut child = Command::new(wineserver)
.arg(flag)
.env_clear()
.envs(environment.iter().map(|(k, v)| (k, v)))
.env("WINEPREFIX", prefix)
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.map_err(|e| format!("cannot start wineserver {flag}: {e}"))?;
match wait_until(&mut child, Instant::now() + SERVER_WAIT) {
Ok(Some(status)) if status.success() => {}
Ok(Some(status)) if idle_code.is_some() && status.code() == idle_code => {}
other => {
let _ = child.kill();
let _ = child.wait();
return Err(format!("wineserver {flag} did not succeed: {other:?}"));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
fn shell(script: &str) -> Command {
let mut command = Command::new("/bin/sh");
command.args(["-c", script]);
command
}
fn scratch(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("bx-cli-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn classifies_exit_timeout_and_signal() {
let ok = supervise(shell("exit 0"), None, || 0).unwrap();
assert_eq!(ok.exit_code(), 0);
let failed = supervise(shell("exit 7"), Some(Duration::from_secs(10)), || 0).unwrap();
assert_eq!(failed.exit_code(), 1);
let slow = supervise(shell("sleep 30"), Some(Duration::from_millis(200)), || 0).unwrap();
assert!(matches!(slow, Outcome::Stopped(Stop::TimedOut)));
assert_eq!(slow.exit_code(), 124);
let interrupted = supervise(shell("sleep 30"), None, || libc::SIGTERM).unwrap();
assert_eq!(interrupted.exit_code(), 128 + libc::SIGTERM as u8);
}
#[test]
fn a_timeout_stops_children_that_ignore_sigterm() {
let dir = scratch("group");
let pid_file = dir.join("child.pid");
let script = format!(
"(trap '' TERM; exec sleep 30) & echo $! > '{}'; wait",
pid_file.display()
);
supervise(shell(&script), Some(Duration::from_millis(500)), || 0).unwrap();
let pid: libc::pid_t = std::fs::read_to_string(&pid_file)
.unwrap()
.trim()
.parse()
.unwrap();
let gone = (0..100).any(|_| {
std::thread::sleep(POLL);
// SAFETY: signal 0 only checks whether the process exists.
unsafe { libc::kill(pid, 0) != 0 }
});
assert!(gone, "grandchild {pid} survived the timeout");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn an_idle_server_is_accepted_only_when_the_wait_succeeds() {
let dir = scratch("server");
for (name, kill, wait, ok) in [
("running", 0, 0, true),
("idle", 1, 0, true),
("stuck", 1, 1, false),
("broken", 2, 0, false),
] {
let server = dir.join(name);
std::fs::write(
&server,
format!("#!/bin/sh\n[ \"$1\" = -k ] && exit {kill}\nexit {wait}\n"),
)
.unwrap();
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(stop_server(&server, &dir, &[]).is_ok(), ok, "{name}");
}
std::fs::remove_dir_all(dir).unwrap();
}
}
+304 -4
View File
@@ -2,6 +2,7 @@
#include <condition_variable>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <mutex>
@@ -315,6 +316,146 @@ HRESULT create_storage(const wchar_t* path) {
return FAILED(hr) ? hr : ensure_directory(path);
}
// Caller holds state_mutex. Same transition XGameRuntimeUninitialize uses.
bool release_runtime_ref() {
if (!runtime_refs) return false;
if (!--runtime_refs) {
users.clear();
stores.clear();
}
return true;
}
bool runtime_active() {
std::lock_guard lock(state_mutex);
return runtime_refs != 0;
}
/*
* Loader export provenance, checked 2026-11-26.
*
* Public Microsoft Learn pages that were opened:
* XGameRuntimeInitialize, XGameRuntimeUninitialize, and
* XGameRuntimeInitializeWithOptions (header named there: XGameRuntimeInit.h),
* XGameRuntimeOptions { XGameRuntimeGameConfigSource gameConfigSource; const char* gameConfig },
* and XGameRuntimeGameConfigSource : uint32_t { Default, Inline, File }.
* Those pages also say the DLL init is ref-counted and that an XErrorReport is
* emitted when uninit fails with live objects. They do not give a prototype
* for XErrorReport. The XError member list names only XErrorCallback,
* XErrorSetCallback, and XErrorSetOptions. XErrorCallback is
* bool(HRESULT, const char*, void*).
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgameruntimeinit/functions/xgameruntimeinitialize
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgameruntimeinit/functions/xgameruntimeuninitialize
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgameruntimeinit/functions/xgameruntimeinitializewithoptions
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgameruntimeinit/structures/xgameruntimeoptions
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgameruntimeinit/enumerations/xgameruntimegameconfigsource
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xerror/xerror_members
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xerror/functions/xerrorcallback
*
* InitializeApiImpl, InitializeApiImplEx, InitializeApiImplEx2, QueryApiImpl,
* UninitializeApiImpl, and a callable XErrorReport prototype were not found
* on those pages, and https://github.com/microsoft/GDK/main/include/XGameRuntimeInit.h
* returned 404. Their names and parameter lists below are BetterXen-defined
* so a static loader can resolve the exports. ApiInitOptions is not the
* public XGameRuntimeOptions struct. RuntimeOptions above matches that
* public two-field layout. No Microsoft source was copied.
*/
struct ApiInitOptions {
uint32_t unknown;
uint8_t is_inline;
uint8_t pad[3];
const char* game_config;
};
static_assert(offsetof(ApiInitOptions, game_config) == 8);
constexpr uint16_t family_data2 = 0x5853;
constexpr uint16_t family_data3 = 0x4000;
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;
}
void format_guid(char* dst, size_t cap, const GUID* guid) {
std::snprintf(dst, cap, "%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
static_cast<unsigned long>(guid->Data1), static_cast<unsigned>(guid->Data2),
static_cast<unsigned>(guid->Data3), guid->Data4[0], guid->Data4[1], guid->Data4[2],
guid->Data4[3], guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
}
bool utf8_continuation(unsigned char c) { return (c & 0xC0) == 0x80; }
/* Byte length of one well-formed UTF-8 character at s, or 0 if s is not one. */
size_t utf8_len(const unsigned char* s) {
const unsigned char c = s[0];
size_t len = 0;
if (c < 0x80) return 1;
if (c >= 0xC2 && c <= 0xDF) len = 2;
else if (c == 0xE0 || (c >= 0xE1 && c <= 0xEC) || c == 0xED || (c >= 0xEE && c <= 0xEF)) len = 3;
else if (c == 0xF0 || (c >= 0xF1 && c <= 0xF3) || c == 0xF4) len = 4;
else return 0;
for (size_t i = 1; i < len; ++i) {
if (s[i] == 0 || !utf8_continuation(s[i])) return 0;
}
if (c == 0xE0 && s[1] < 0xA0) return 0;
if (c == 0xED && s[1] > 0x9F) return 0;
if (c == 0xF0 && s[1] < 0x90) return 0;
if (c == 0xF4 && s[1] > 0x8F) return 0;
return len;
}
/*
* Append src as JSON string content and valid UTF-8.
* A quote or backslash is escaped. Bytes below 0x20 and an invalid UTF-8
* byte are written as \u00XX, which stays ASCII. A character that does not
* fit is left out, so a multi-byte sequence is never split.
*/
void append_escaped(char* dst, size_t cap, size_t* used, const char* src) {
size_t u = *used;
if (!src) src = "(null)";
const auto* p = reinterpret_cast<const unsigned char*>(src);
while (*p) {
auto fits = [&](size_t n) { return u + n < cap; };
const unsigned char c = *p;
if (c < 0x20 || c == 0x7F) {
if (!fits(6)) break;
u += static_cast<size_t>(std::snprintf(dst + u, cap - u, "\\u%04X", c));
++p;
continue;
}
if (c == '"' || c == '\\') {
if (!fits(2)) break;
dst[u++] = '\\';
dst[u++] = static_cast<char>(c);
++p;
continue;
}
const size_t len = c < 0x80 ? 1 : utf8_len(p);
if (len == 0) {
if (!fits(6)) break;
u += static_cast<size_t>(std::snprintf(dst + u, cap - u, "\\u%04X", c));
++p;
continue;
}
if (!fits(len)) break;
std::memcpy(dst + u, p, len);
u += len;
p += len;
}
if (u < cap) dst[u] = '\0';
else if (cap) dst[cap - 1] = '\0';
*used = u < cap ? u : cap - 1;
}
HRESULT check_loader_versions(uint32_t gdk_ver, uint32_t gs_ver, const char* event) {
if (gdk_ver == 0 || gs_ver == 0) {
bx_log_emit(BX_LOG_WARN, "xgameruntime", event, "invalid_args");
return E_INVALIDARG;
}
return S_OK;
}
} // namespace
extern "C" {
@@ -339,10 +480,7 @@ HRESULT WINAPI XGameRuntimeInitializeWithOptions(const RuntimeOptions* options)
void WINAPI XGameRuntimeUninitialize() {
std::lock_guard lock(state_mutex);
if (runtime_refs && !--runtime_refs) {
users.clear();
stores.clear();
}
release_runtime_ref();
}
HRESULT WINAPI XAsyncGetStatus(AsyncBlock* block, bool wait) {
@@ -561,4 +699,166 @@ OFFLINE_STUB(XNetworkingQuerySecurityInformationForUrlAsync, (const char*, Async
#undef OFFLINE_STUB
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 InitializeApiImpl(uint32_t gdk_ver, uint32_t gs_ver) {
const auto hr = check_loader_versions(gdk_ver, gs_ver, "InitializeApiImpl");
return FAILED(hr) ? hr : XGameRuntimeInitialize();
}
HRESULT WINAPI InitializeApiImplEx(uint32_t gdk_ver, uint32_t gs_ver, char /*mode*/) {
const auto hr = check_loader_versions(gdk_ver, gs_ver, "InitializeApiImplEx");
return FAILED(hr) ? hr : XGameRuntimeInitialize();
}
HRESULT WINAPI InitializeApiImplEx2(uint32_t gdk_ver, uint32_t gs_ver, char /*mode*/, const ApiInitOptions* options) {
const auto hr = check_loader_versions(gdk_ver, gs_ver, "InitializeApiImplEx2");
if (FAILED(hr)) return hr;
if (options && options->is_inline && !options->game_config) {
bx_log_emit(BX_LOG_WARN, "xgameruntime", "InitializeApiImplEx2", "invalid_args");
return E_INVALIDARG;
}
// Custom game config is the same unimplemented path as XGameRuntimeInitializeWithOptions.
if (options && (options->is_inline || options->game_config)) {
BX_STUB_LOG("xgameruntime.dll", "InitializeApiImplEx2");
return E_NOTIMPL;
}
return XGameRuntimeInitialize();
}
HRESULT WINAPI UninitializeApiImpl() {
bool released;
{
std::lock_guard lock(state_mutex);
released = release_runtime_ref();
}
if (!released) {
bx_log_emit(BX_LOG_WARN, "xgameruntime", "UninitializeApiImpl", "not_initialized");
return runtime_not_initialized;
}
return S_OK;
}
void WINAPI XErrorReport(HRESULT hr, const char* message) {
char detail[480];
const auto prefix = std::snprintf(detail, sizeof(detail), "hr=0x%08lX msg=",
static_cast<unsigned long>(static_cast<uint32_t>(hr)));
size_t used = prefix > 0 ? static_cast<size_t>(prefix) : 0;
if (used >= sizeof(detail)) used = sizeof(detail) - 1;
append_escaped(detail, sizeof(detail), &used, message);
bx_log_emit(BX_LOG_ERROR, "xgameruntime", "XErrorReport", detail);
}
struct TaskQueueDispatch {
decltype(&XTaskQueueCreate) create;
decltype(&XTaskQueueCloseHandle) close_handle;
decltype(&XTaskQueueDispatch) dispatch;
decltype(&XTaskQueueSubmitCallback) submit;
decltype(&XTaskQueueGetCurrentProcessTaskQueue) current;
};
struct AsyncDispatch {
decltype(&XAsyncGetStatus) get_status;
decltype(&XAsyncGetResultSize) get_result_size;
decltype(&XAsyncCancel) cancel;
};
struct UserDispatch {
decltype(&XUserAddAsync) add_async;
decltype(&XUserAddResult) add_result;
decltype(&XUserGetId) get_id;
decltype(&XUserGetGamertag) get_gamertag;
};
struct StoreDispatch {
decltype(&XStoreCreateContext) create_context;
decltype(&XStoreQueryGameLicenseAsync) query_license_async;
decltype(&XStoreQueryGameLicenseResult) query_license_result;
};
struct SystemDispatch {
decltype(&XSystemGetDeviceType) get_device_type;
decltype(&XSystemGetConsoleId) get_console_id;
decltype(&XSystemGetXboxLiveSandboxId) get_sandbox_id;
};
struct StorageDispatch {
decltype(&XPersistentLocalStorageGetPathSize) get_path_size;
decltype(&XPersistentLocalStorageGetPath) get_path;
decltype(&XPersistentLocalStorageGetSpaceInfo) get_space_info;
};
const TaskQueueDispatch task_queue_api{&XTaskQueueCreate, &XTaskQueueCloseHandle, &XTaskQueueDispatch,
&XTaskQueueSubmitCallback, &XTaskQueueGetCurrentProcessTaskQueue};
const AsyncDispatch async_api{&XAsyncGetStatus, &XAsyncGetResultSize, &XAsyncCancel};
const UserDispatch user_api{&XUserAddAsync, &XUserAddResult, &XUserGetId, &XUserGetGamertag};
const StoreDispatch store_api{&XStoreCreateContext, &XStoreQueryGameLicenseAsync, &XStoreQueryGameLicenseResult};
const SystemDispatch system_api{&XSystemGetDeviceType, &XSystemGetConsoleId, &XSystemGetXboxLiveSandboxId};
const StorageDispatch storage_api{&XPersistentLocalStorageGetPathSize, &XPersistentLocalStorageGetPath,
&XPersistentLocalStorageGetSpaceInfo};
struct Family {
uint32_t clsid;
uint32_t iid;
const char* name;
const void* table;
};
// Synthetic BetterXen dispatch keys, not Microsoft CLSIDs.
// Data2 = 0x5853, Data3 = 0x4000, Data4 = 80 00 00 00 00 00 00 01.
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},
};
const Family* find_family(const GUID* clsid) {
if (!synthetic_guid(clsid)) return nullptr;
for (const auto& family : families) {
if (clsid->Data1 == family.clsid) return &family;
}
return nullptr;
}
HRESULT WINAPI QueryApiImpl(const GUID* clsid, const GUID* iid, void** out) {
if (!out) {
bx_log_emit(BX_LOG_WARN, "xgameruntime", "QueryApiImpl", "invalid_args");
return E_POINTER;
}
*out = nullptr;
if (!clsid || !iid) {
bx_log_emit(BX_LOG_WARN, "xgameruntime", "QueryApiImpl", "invalid_args");
return E_INVALIDARG;
}
if (!runtime_active()) {
bx_log_emit(BX_LOG_WARN, "xgameruntime", "QueryApiImpl", "not_initialized");
return runtime_not_initialized;
}
const auto* family = find_family(clsid);
if (family && synthetic_guid(iid) && iid->Data1 == family->iid) {
*out = const_cast<void*>(family->table);
char detail[64];
std::snprintf(detail, sizeof(detail), "dispatch family=%s", family->name);
bx_log_emit(BX_LOG_INFO, "xgameruntime", "QueryApiImpl", detail);
return S_OK;
}
char clsid_text[48], iid_text[48], detail[192], symbol[160];
format_guid(clsid_text, sizeof(clsid_text), clsid);
format_guid(iid_text, sizeof(iid_text), iid);
std::snprintf(symbol, sizeof(symbol), "QueryApiImpl(%s/%s)", clsid_text, iid_text);
if (family) {
std::snprintf(detail, sizeof(detail), "iid_mismatch family=%s clsid=%s iid=%s", family->name, clsid_text,
iid_text);
} else {
std::snprintf(detail, sizeof(detail), "unsupported clsid=%s iid=%s", clsid_text, iid_text);
}
bx_log_emit(BX_LOG_WARN, "xgameruntime", "QueryApiImpl", detail);
BX_STUB_LOG("xgameruntime.dll", symbol);
return E_NOINTERFACE;
}
} // extern "C"
@@ -0,0 +1,16 @@
# #437: which module serves the six API-set import names under CrossOver?
#
# Links statically (PE import directory, not LoadLibrary) against the import
# library of each win32_bridge shim. The ntuser forwarder libraries come first so
# the ntuser exports bind to the shim import libraries instead of user32's.
add_executable(test_apiset_resolution main.cpp)
target_link_libraries(test_apiset_resolution PRIVATE
ntuser_win_ansi_1_0
ntuser_win_1_0
ntuser_msg_ansi_1_0
ntuser_msg_1_0
psm_appnotify_1_0
psm_appnotify_1_1
user32
kernel32
)
@@ -0,0 +1,240 @@
/*
* #437: API-set import resolution fixture.
*
* Statically imports one export from each of the six win32_bridge shim DLLs
* (api-ms-win-core-psm-appnotify-l1-1-{0,1}, ext-ms-win-rtcore-ntuser-*) and
* reports, per name, which module actually served it:
*
* shim - the BetterXen file of that name next to this EXE is the loaded module.
* host - a module that is not that file answers the name (for example Wine's
* own API-set handling).
* absent - no module is loaded under that name.
*
* `bound_to` is the module that owns the address the loader wrote into the first
* import address table slot for that name, which is the module that serves a call
* made through the static import. The check is made through the PE import directory, not LoadLibrary,
* which is how real titles reach these names (see #437).
*
* Usage: test_apiset_resolution [--expect host|shim]
* --expect host (default): pass when all six names are served by the host.
* --expect shim: pass when all six names are served by BetterXen shim files.
* Exit 0 when every name matches the expectation, 1 otherwise, 2 on bad arguments.
*/
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#define BX_IMPORT extern "C" __declspec(dllimport)
BX_IMPORT ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID context, PVOID* out_reg);
BX_IMPORT ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID callback, PVOID context, PVOID* out_reg);
namespace {
struct ApiSetName {
const char* dll;
const char* export_name;
};
/* One export per shim DLL. The calls in keep_imports() make the linker emit each import. */
const ApiSetName kNames[] = {
{"api-ms-win-core-psm-appnotify-l1-1-0.dll", "RegisterAppStateChangeNotification"},
{"api-ms-win-core-psm-appnotify-l1-1-1.dll", "RegisterAppConstrainedChangeNotification"},
{"ext-ms-win-rtcore-ntuser-message-l1-1-0.dll", "TranslateMessage"},
{"ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll", "PeekMessageA"},
{"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll", "ShowWindow"},
{"ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll", "CreateWindowExA"},
};
constexpr size_t kNameCount = sizeof(kNames) / sizeof(kNames[0]);
enum class Served { Shim, Host, Absent };
const char* served_name(Served s) {
switch (s) {
case Served::Shim: return "shim";
case Served::Host: return "host";
default: return "absent";
}
}
const IMAGE_IMPORT_DESCRIPTOR* find_import(const char* dll) {
auto* base = reinterpret_cast<const uint8_t*>(GetModuleHandleA(nullptr));
auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(base);
auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS64*>(base + dos->e_lfanew);
const IMAGE_DATA_DIRECTORY& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
if (dir.VirtualAddress == 0) {
return nullptr;
}
auto* desc = reinterpret_cast<const IMAGE_IMPORT_DESCRIPTOR*>(base + dir.VirtualAddress);
for (; desc->Name != 0; ++desc) {
if (_stricmp(reinterpret_cast<const char*>(base + desc->Name), dll) == 0) {
return desc;
}
}
return nullptr;
}
/* The address the loader wrote into the first import address table slot for `dll`. */
const void* first_bound_address(const IMAGE_IMPORT_DESCRIPTOR* desc) {
auto* base = reinterpret_cast<const uint8_t*>(GetModuleHandleA(nullptr));
auto* iat = reinterpret_cast<const uintptr_t*>(base + desc->FirstThunk);
return reinterpret_cast<const void*>(iat[0]);
}
/* Referencing each export makes the linker keep the import. main() calls this only for an impossible argc. */
__attribute__((noinline)) void keep_imports() {
const void* const sink[] = {
reinterpret_cast<const void*>(&RegisterAppStateChangeNotification),
reinterpret_cast<const void*>(&RegisterAppConstrainedChangeNotification),
reinterpret_cast<const void*>(&TranslateMessage),
reinterpret_cast<const void*>(&PeekMessageA),
reinterpret_cast<const void*>(&ShowWindow),
reinterpret_cast<const void*>(&CreateWindowExA),
};
for (const void* p : sink) {
std::printf("%p\n", p);
}
}
/* Lower-cased full path of a module; empty when it cannot be read. */
bool path_of(HMODULE mod, char* out, DWORD out_len) {
out[0] = '\0';
if (!mod) {
return false;
}
DWORD n = GetModuleFileNameA(mod, out, out_len);
if (n == 0 || n >= out_len) {
out[0] = '\0';
return false;
}
CharLowerBuffA(out, n);
return true;
}
/* Directory part of `path` (up to the last backslash), or false when there is none. */
bool dir_len_of(const char* path, size_t* len) {
const char* slash = std::strrchr(path, '\\');
if (!slash) {
return false;
}
*len = static_cast<size_t>(slash - path);
return true;
}
/* Paths contain backslashes; escape them (and quotes) so each line stays valid JSON. */
void json_escape(const char* in, char* out, size_t out_len) {
size_t o = 0;
for (; *in && o + 2 < out_len; ++in) {
if (*in == '\\' || *in == '"') {
out[o++] = '\\';
}
out[o++] = *in;
}
out[o] = '\0';
}
int g_fail = 0;
int g_seq = 0;
void checkpoint(const char* stage, bool ok, const char* served, bool imported, const char* name_path,
const char* bound_path, const char* detail) {
char np[1024];
char bp[1024];
json_escape(name_path, np, sizeof(np));
json_escape(bound_path, bp, sizeof(bp));
g_seq++;
if (!ok) {
g_fail++;
}
std::printf("{\"bx_checkpoint\":\"test_apiset_resolution\",\"seq\":%d,\"stage\":\"%s\",\"status\":\"%s\","
"\"served_by\":\"%s\",\"statically_imported\":%s,\"name_module\":\"%s\",\"bound_to\":\"%s\",\"detail\":\"%s\"}\n",
g_seq, stage, ok ? "pass" : "fail", served, imported ? "true" : "false", np, bp, detail);
std::fflush(stdout);
}
} // namespace
int main(int argc, char** argv) {
if (argc > 1000) {
keep_imports();
}
Served expect = Served::Host;
if (argc == 3 && std::strcmp(argv[1], "--expect") == 0) {
if (std::strcmp(argv[2], "shim") == 0) {
expect = Served::Shim;
} else if (std::strcmp(argv[2], "host") != 0) {
std::fprintf(stderr, "usage: %s [--expect host|shim]\n", argv[0]);
return 2;
}
} else if (argc != 1) {
std::fprintf(stderr, "usage: %s [--expect host|shim]\n", argv[0]);
return 2;
}
char exe[MAX_PATH] = "";
const bool exe_ok = path_of(GetModuleHandleA(nullptr), exe, sizeof(exe));
size_t exe_dir = 0;
const bool have_exe_dir = exe_ok && dir_len_of(exe, &exe_dir);
int matched = 0;
for (const ApiSetName& n : kNames) {
const IMAGE_IMPORT_DESCRIPTOR* import = find_import(n.dll);
const bool imported = import != nullptr;
HMODULE name_mod = GetModuleHandleA(n.dll);
char name_path[MAX_PATH] = "";
const bool name_ok = path_of(name_mod, name_path, sizeof(name_path));
HMODULE bound_mod = nullptr;
char bound_path[MAX_PATH] = "";
bool bound_ok = false;
if (import
&& GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
static_cast<LPCSTR>(first_bound_address(import)), &bound_mod)) {
bound_ok = path_of(bound_mod, bound_path, sizeof(bound_path));
}
/* The shim serves the name only when the loaded module is that file next to this EXE. */
Served served = Served::Absent;
if (name_mod && name_ok && have_exe_dir) {
size_t dir = 0;
const char* slash = std::strrchr(name_path, '\\');
const bool same_dir = dir_len_of(name_path, &dir) && dir == exe_dir
&& std::memcmp(name_path, exe, exe_dir) == 0;
served = same_dir && slash && _stricmp(slash + 1, n.dll) == 0 ? Served::Shim : Served::Host;
}
const bool lookup_ok = have_exe_dir && name_mod && name_ok && bound_ok;
const bool ok = imported && lookup_ok && served == expect;
if (ok) {
matched++;
}
char detail[160];
if (!imported) {
std::snprintf(detail, sizeof(detail), "name is not in the static import directory");
} else if (!have_exe_dir) {
std::snprintf(detail, sizeof(detail), "%s: failed to resolve executable directory", n.export_name);
} else if (!name_mod) {
std::snprintf(detail, sizeof(detail), "%s: GetModuleHandleA returned null (expected %s)", n.export_name,
served_name(expect));
} else if (!name_ok) {
std::snprintf(detail, sizeof(detail), "%s: failed to resolve path for name module", n.export_name);
} else if (!bound_ok) {
std::snprintf(detail, sizeof(detail), "%s: failed to resolve owning module for bound IAT entry",
n.export_name);
} else {
std::snprintf(detail, sizeof(detail), "%s: served by %s, expected %s", n.export_name, served_name(served),
served_name(expect));
}
checkpoint(n.dll, ok, served_name(served), imported, name_ok ? name_path : "", bound_ok ? bound_path : "",
detail);
}
const bool ok = g_fail == 0;
std::printf("{\"bx_summary\":\"test_apiset_resolution\",\"names\":%zu,\"matched\":%d,\"expected\":\"%s\",\"result\":\"%s\"}\n",
kNameCount, matched, served_name(expect), ok ? "pass" : "fail");
std::printf("%s: test_apiset_resolution (%d/%zu names served by %s)\n", ok ? "PASS" : "FAIL", matched, kNameCount,
served_name(expect));
std::fflush(stdout);
return ok ? 0 : 1;
}
@@ -0,0 +1,2 @@
add_executable(test_system32_staging main.cpp)
target_link_libraries(test_system32_staging PRIVATE kernel32)
@@ -0,0 +1,61 @@
/*
* #459: Synthetic conformance fixture for bx-cli reversible system32 shim staging.
*
* Does NOT statically import xgameruntime.dll. Instead, mirrors the dynamic loader path
* by calling LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32),
* verifying that the loaded module resolves from \windows\system32\xgameruntime.dll and
* exports InitializeApiImpl, then unloading cleanly.
*/
#include <windows.h>
#include <cstdio>
#include <cwchar>
#include <cwctype>
namespace {
bool ends_with_ci(const wchar_t* str, const wchar_t* suffix) {
const size_t slen = std::wcslen(str);
const size_t suflen = std::wcslen(suffix);
if (slen < suflen) return false;
const wchar_t* tail = str + (slen - suflen);
for (size_t i = 0; i < suflen; ++i) {
if (std::towlower(tail[i]) != std::towlower(suffix[i])) return false;
}
return true;
}
} // namespace
int main() {
HMODULE mod = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (!mod) {
std::fprintf(stderr, "FAIL: LoadLibraryExW(xgameruntime.dll, LOAD_LIBRARY_SEARCH_SYSTEM32) failed (err=%lu)\n",
static_cast<unsigned long>(GetLastError()));
return 1;
}
wchar_t path[MAX_PATH] = {};
const DWORD len = GetModuleFileNameW(mod, path, MAX_PATH);
if (len == 0 || len >= MAX_PATH) {
std::fprintf(stderr, "FAIL: GetModuleFileNameW failed (err=%lu)\n", static_cast<unsigned long>(GetLastError()));
FreeLibrary(mod);
return 1;
}
if (!ends_with_ci(path, L"\\windows\\system32\\xgameruntime.dll")) {
std::fprintf(stderr, "FAIL: unexpected module path: %ls\n", path);
FreeLibrary(mod);
return 1;
}
FARPROC init_fn = GetProcAddress(mod, "InitializeApiImpl");
if (!init_fn) {
std::fprintf(stderr, "FAIL: GetProcAddress(InitializeApiImpl) returned null\n");
FreeLibrary(mod);
return 1;
}
FreeLibrary(mod);
std::printf("PASS: test_system32_staging (%ls)\n", path);
return 0;
}
@@ -136,6 +136,29 @@ void check_storage() {
} // namespace
bool valid_utf8(const unsigned char* s, size_t n) {
size_t i = 0;
while (i < n) {
const unsigned char c = s[i];
size_t len = 0;
if (c < 0x80) len = 1;
else if (c >= 0xC2 && c <= 0xDF) len = 2;
else if (c == 0xE0 || (c >= 0xE1 && c <= 0xEC) || c == 0xED || (c >= 0xEE && c <= 0xEF)) len = 3;
else if (c == 0xF0 || (c >= 0xF1 && c <= 0xF3) || c == 0xF4) len = 4;
else return false;
if (i + len > n) return false;
for (size_t k = 1; k < len; ++k) {
if ((s[i + k] & 0xC0) != 0x80) return false;
}
if (c == 0xE0 && s[i + 1] < 0xA0) return false;
if (c == 0xED && s[i + 1] > 0x9F) return false;
if (c == 0xF0 && s[i + 1] < 0x90) return false;
if (c == 0xF4 && s[i + 1] > 0x8F) return false;
i += len;
}
return true;
}
#ifndef BX_TEST_UNENTITLED
extern "C" __declspec(dllexport) void BetterXenSyntheticStoreFixture() {}
#endif
@@ -277,6 +300,215 @@ int main() {
check_storage();
XGameRuntimeUninitialize();
CHECK(FAILED(XUserAddAsync(1, &uninitialized)));
// Dynamic loader entry points. Synthetic family GUIDs match xgameruntime.cpp:
// Data2 = 0x5853, Data3 = 0x4000, Data4 = 80 00 00 00 00 00 00 01.
HMODULE module = GetModuleHandleA("xgameruntime.dll");
CHECK(module);
const char* names[] = {"InitializeApiImpl", "InitializeApiImplEx", "InitializeApiImplEx2",
"UninitializeApiImpl", "QueryApiImpl", "XErrorReport"};
FARPROC procs[6]{};
for (int i = 0; i < 6; ++i) {
procs[i] = GetProcAddress(module, names[i]);
CHECK(procs[i]);
}
const auto load = [](FARPROC proc, auto& fn) { std::memcpy(&fn, &proc, sizeof(fn)); };
using InitFn = HRESULT(WINAPI*)(uint32_t, uint32_t);
using InitExFn = HRESULT(WINAPI*)(uint32_t, uint32_t, char);
using InitEx2Fn = HRESULT(WINAPI*)(uint32_t, uint32_t, char, const void*);
using UninitFn = HRESULT(WINAPI*)();
using QueryFn = HRESULT(WINAPI*)(const GUID*, const GUID*, void**);
using ErrorFn = void(WINAPI*)(HRESULT, const char*);
InitFn init_api{};
InitExFn init_ex{};
InitEx2Fn init_ex2{};
UninitFn uninit_api{};
QueryFn query_api{};
ErrorFn error_report{};
load(procs[0], init_api);
load(procs[1], init_ex);
load(procs[2], init_ex2);
load(procs[3], uninit_api);
load(procs[4], query_api);
load(procs[5], error_report);
struct ApiInitOptions {
uint32_t unknown;
uint8_t is_inline;
uint8_t pad[3];
const char* game_config;
};
static_assert(offsetof(ApiInitOptions, game_config) == 8);
const auto family_guid = [](uint32_t data1) {
GUID guid{};
guid.Data1 = data1;
guid.Data2 = 0x5853;
guid.Data3 = 0x4000;
guid.Data4[0] = 0x80;
guid.Data4[7] = 0x01;
return guid;
};
const GUID xsystem = family_guid(0xB7581401);
const GUID xsystem_iid = family_guid(0xB7581402);
const GUID wrong_iid = family_guid(0xB75814FF);
GUID bogus{};
bogus.Data1 = 0xDEADBEEF;
bogus.Data4[0] = 0x11;
constexpr HRESULT not_initialized = static_cast<HRESULT>(0x89240100u);
auto* sentinel = reinterpret_cast<void*>(static_cast<uintptr_t>(1));
void* api = sentinel;
CHECK(query_api(&xsystem, &xsystem_iid, nullptr) == E_POINTER);
CHECK(api == sentinel);
api = sentinel;
CHECK(query_api(nullptr, &xsystem_iid, &api) == E_INVALIDARG && !api);
api = sentinel;
CHECK(query_api(&xsystem, nullptr, &api) == E_INVALIDARG && !api);
api = sentinel;
CHECK(query_api(&xsystem, &xsystem_iid, &api) == not_initialized && !api);
CHECK(init_api(0, 1) == E_INVALIDARG);
CHECK(init_ex(1, 0, 2) == E_INVALIDARG);
const ApiInitOptions broken{1u, 1u, {0, 0, 0}, nullptr};
CHECK(init_ex2(1, 1, 2, &broken) == E_INVALIDARG);
const ApiInitOptions file_opt{1u, 0u, {0, 0, 0}, "C:\\bx_synthetic\\MicrosoftGame.config"};
CHECK(init_ex2(1, 1, 2, &file_opt) == E_NOTIMPL);
void* probe = nullptr;
CHECK(XStoreCreateContext(nullptr, &probe) == not_initialized);
CHECK(init_api(1, 1) == S_OK);
CHECK(XGameRuntimeInitialize() == S_OK);
CHECK(uninit_api() == S_OK);
CHECK(XStoreCreateContext(nullptr, &probe) == S_OK && probe);
XStoreCloseContextHandle(probe);
XGameRuntimeUninitialize();
CHECK(XStoreCreateContext(nullptr, &probe) == not_initialized);
CHECK(uninit_api() == not_initialized);
CHECK(init_ex(1, 1, 2) == S_OK);
CHECK(init_ex2(1, 1, 6, nullptr) == S_OK);
CHECK(uninit_api() == S_OK);
CHECK(XStoreCreateContext(nullptr, &probe) == S_OK && probe);
XStoreCloseContextHandle(probe);
XGameRuntimeUninitialize();
CHECK(XStoreCreateContext(nullptr, &probe) == not_initialized);
const ApiInitOptions default_opts{1u, 0u, {0, 0, 0}, nullptr};
CHECK(init_ex2(1, 1, 6, &default_opts) == S_OK);
CHECK(XStoreCreateContext(nullptr, &probe) == S_OK && probe);
XStoreCloseContextHandle(probe);
CHECK(uninit_api() == S_OK);
CHECK(XStoreCreateContext(nullptr, &probe) == not_initialized);
CHECK(init_api(1, 1) == S_OK);
const uint32_t families[][2] = {
{0xB7581001, 0xB7581002}, {0xB7581101, 0xB7581102}, {0xB7581201, 0xB7581202},
{0xB7581301, 0xB7581302}, {0xB7581401, 0xB7581402}, {0xB7581501, 0xB7581502},
};
struct SystemHead {
uint32_t(WINAPI* get_device_type)();
};
for (const auto& ids : families) {
const GUID clsid = family_guid(ids[0]);
const GUID iid = family_guid(ids[1]);
void* table = nullptr;
CHECK(query_api(&clsid, &iid, &table) == S_OK && table);
if (ids[0] == 0xB7581401) {
CHECK(static_cast<SystemHead*>(table)->get_device_type() == XSystemGetDeviceType());
}
}
struct LogSpan {
bool from_file = false;
char path[512]{};
long mark = 0;
HANDLE pipe_read = nullptr;
HANDLE pipe_write = nullptr;
HANDLE saved_err = nullptr;
char text[64 * 1024]{};
bool start() {
const auto n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n > 0 && n < sizeof(path)) {
from_file = true;
if (auto* file = std::fopen(path, "rb")) {
std::fseek(file, 0, SEEK_END);
mark = std::ftell(file);
std::fclose(file);
}
return true;
}
if (!CreatePipe(&pipe_read, &pipe_write, nullptr, sizeof(text))) return false;
saved_err = GetStdHandle(STD_ERROR_HANDLE);
return SetStdHandle(STD_ERROR_HANDLE, pipe_write) != 0;
}
void finish() {
size_t got = 0;
if (from_file) {
if (auto* file = std::fopen(path, "rb")) {
std::fseek(file, mark, SEEK_SET);
got = std::fread(text, 1, sizeof(text) - 1, file);
std::fclose(file);
}
} else if (pipe_read) {
SetStdHandle(STD_ERROR_HANDLE, saved_err);
CloseHandle(pipe_write);
DWORD chunk = 0;
while (got + 1 < sizeof(text) &&
ReadFile(pipe_read, text + got, static_cast<DWORD>(sizeof(text) - 1 - got), &chunk, nullptr) &&
chunk) {
got += chunk;
}
CloseHandle(pipe_read);
}
text[got] = '\0';
}
bool has(const char* needle) const { return std::strstr(text, needle) != nullptr; }
} span;
CHECK(span.start());
api = sentinel;
const auto mismatched = query_api(&xsystem, &wrong_iid, &api);
CHECK(mismatched == E_NOINTERFACE && !api);
api = sentinel;
const auto unsupported = query_api(&bogus, &bogus, &api);
error_report(E_FAIL, "synthetic-gdk-error");
error_report(E_FAIL, nullptr);
error_report(E_FAIL, "err \"quoted\" \\path\nline2");
error_report(E_FAIL, "caf\xE9");
char long_msg[701];
long_msg[0] = 'x';
size_t long_n = 1;
while (long_n + 2 <= 700) {
long_msg[long_n++] = '\xC3';
long_msg[long_n++] = '\xA9';
}
long_msg[long_n] = '\0';
error_report(E_FAIL, long_msg);
span.finish();
CHECK(unsupported == E_NOINTERFACE && !api);
CHECK(span.has("\"sub\":\"xgameruntime\",\"event\":\"QueryApiImpl\"") && span.has("unsupported clsid=DEADBEEF"));
CHECK(span.has("\"event\":\"unimpl_api\"") &&
span.has("xgameruntime.dll!QueryApiImpl(B7581401-5853-4000-8000-000000000001/"
"B75814FF-5853-4000-8000-000000000001)") &&
span.has("xgameruntime.dll!QueryApiImpl(DEADBEEF-0000-0000-1100-000000000000/"
"DEADBEEF-0000-0000-1100-000000000000)"));
CHECK(span.has("\"sub\":\"xgameruntime\",\"event\":\"XErrorReport\"") &&
span.has("hr=0x80004005 msg=synthetic-gdk-error"));
CHECK(span.has("hr=0x80004005 msg=(null)"));
CHECK(span.has("msg=err \\\"quoted\\\" \\\\path\\u000Aline2"));
CHECK(span.has("caf\\u00E9"));
CHECK(std::memchr(span.text, static_cast<unsigned char>(0xE9), std::strlen(span.text)) == nullptr);
CHECK(valid_utf8(reinterpret_cast<const unsigned char*>(span.text), std::strlen(span.text)));
size_t eacute = 0;
const auto* bytes = reinterpret_cast<const unsigned char*>(span.text);
const size_t nbytes = std::strlen(span.text);
for (size_t i = 0; i + 1 < nbytes; ++i) {
if (bytes[i] == 0xC3 && bytes[i + 1] == 0xA9) ++eacute;
}
CHECK(eacute > 0 && eacute < (long_n - 1) / 2);
XGameRuntimeUninitialize();
CHECK(XStoreCreateContext(nullptr, &probe) == not_initialized);
std::printf("xgameruntime conformance passed (%s, synthetic license %s)\n",
profile, entitled ? "active" : "inactive");
return 0;