mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 18:10:43 +00:00
Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a19b2b999 | ||
|
|
ac0fd2e502 | ||
|
|
73c190d725 | ||
|
|
f3c2b7fe34 | ||
|
|
4333a7cc5e | ||
|
|
66e9351410 | ||
|
|
060083cc56 | ||
|
|
7d7249ee8b | ||
|
|
d0395a61da | ||
|
|
2eb59e033b | ||
|
|
eec56dd028 | ||
|
|
e7899574ab | ||
|
|
486f7b197f | ||
|
|
390e85fc8d | ||
|
|
18178da12c | ||
|
|
bfa80dee8b | ||
|
|
829a94fa2f | ||
|
|
2e895e0f9b | ||
|
|
02b8924de7 | ||
|
|
925311e852 | ||
|
|
f7194d0255 | ||
|
|
7ea4f1f6ca | ||
|
|
bd8edd8f70 | ||
|
|
a8c4dbb77e | ||
|
|
cee636193a | ||
|
|
ab696f1f07 |
No files matched your search
@@ -10,6 +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).
|
||||
@@ -69,6 +75,9 @@ 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.
|
||||
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
|
||||
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
|
||||
|
||||
Generated
+7
@@ -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"
|
||||
@@ -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,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 |
|
||||
|
||||
@@ -43,3 +43,9 @@ EXPORTS
|
||||
XGameUiShowTextEntryAsync
|
||||
XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync
|
||||
XNetworkingQuerySecurityInformationForUrlAsync
|
||||
InitializeApiImpl
|
||||
InitializeApiImplEx
|
||||
InitializeApiImplEx2
|
||||
UninitializeApiImpl
|
||||
QueryApiImpl
|
||||
XErrorReport
|
||||
@@ -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.
|
||||
@@ -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 |
|
||||
|
||||
@@ -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.
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -153,6 +241,16 @@ fn cmd_probe(path: &str) -> ExitCode {
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn format_clwb_line(clwb_events: usize, clwb_trap_lower_bound: Option<u64>) -> String {
|
||||
if let Some(lower_bound) = clwb_trap_lower_bound {
|
||||
format!("clwb VEH traps : at least {lower_bound} (sampled)")
|
||||
} else if clwb_events == 0 {
|
||||
"clwb VEH traps : 0".to_string()
|
||||
} else {
|
||||
format!("clwb VEH samples : {clwb_events}")
|
||||
}
|
||||
}
|
||||
|
||||
fn cmd_trace(path: &str) -> ExitCode {
|
||||
let text = match fs::read_to_string(path) {
|
||||
Ok(s) => s,
|
||||
@@ -161,23 +259,50 @@ fn cmd_trace(path: &str) -> ExitCode {
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let summary = summarize_jsonl(&text);
|
||||
println!("Trace events : {}", summary.total_lines);
|
||||
println!("clwb VEH traps : {}", summary.clwb_events);
|
||||
println!("ADX illegal ops : {}", summary.adx_errors);
|
||||
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)
|
||||
);
|
||||
let _ = writeln!(out, "ADX illegal ops : {}", summary.adx_errors);
|
||||
if !summary.unhandled_exceptions.is_empty() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nUnhandled exceptions ({}):",
|
||||
summary.unhandled_exceptions.len()
|
||||
);
|
||||
for crash in summary.unhandled_exceptions {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" code={} module_base={} + RVA={} RIP={}",
|
||||
crash.exception_code.as_deref().unwrap_or("unknown"),
|
||||
crash.module_base.as_deref().unwrap_or("unknown"),
|
||||
crash.rva.as_deref().unwrap_or("unknown"),
|
||||
crash.rip.as_deref().unwrap_or("unknown"),
|
||||
);
|
||||
}
|
||||
}
|
||||
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 {
|
||||
@@ -199,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");
|
||||
@@ -207,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() {
|
||||
@@ -235,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");
|
||||
@@ -266,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);
|
||||
@@ -277,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)
|
||||
@@ -312,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 {
|
||||
@@ -388,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([
|
||||
@@ -414,4 +957,99 @@ mod tests {
|
||||
"Z:\\tmp\\bx-test.jsonl"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_clwb_summary_lines() {
|
||||
assert_eq!(format_clwb_line(0, None), "clwb VEH traps : 0");
|
||||
assert_eq!(format_clwb_line(2, None), "clwb VEH samples : 2");
|
||||
assert_eq!(
|
||||
format_clwb_line(3, Some(4)),
|
||||
"clwb VEH traps : at least 4 (sampled)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stages_allowlisted_shims_into_system32_and_removes_on_drop() {
|
||||
let root = env::temp_dir().join(format!("bx-cli-stage-ok-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let shims = root.join("shims");
|
||||
let sys32 = root.join("prefix/drive_c/windows/system32");
|
||||
fs::create_dir_all(&shims).unwrap();
|
||||
fs::create_dir_all(&sys32).unwrap();
|
||||
fs::write(shims.join("bx_runtime_veh.dll"), b"bx-veh-bytes").unwrap();
|
||||
fs::write(shims.join("xgameruntime.dll"), b"bx-shim-bytes").unwrap();
|
||||
|
||||
let staged_veh = sys32.join("bx_runtime_veh.dll");
|
||||
let staged_xgr = sys32.join("xgameruntime.dll");
|
||||
{
|
||||
let guard =
|
||||
StagedSystem32Shims::stage(&root.join("prefix"), &shims, SYSTEM32_STAGED_SHIMS);
|
||||
assert_eq!(guard.staged, vec![staged_veh.clone(), staged_xgr.clone()]);
|
||||
assert_eq!(fs::read(&staged_veh).unwrap(), b"bx-veh-bytes");
|
||||
assert_eq!(fs::read(&staged_xgr).unwrap(), b"bx-shim-bytes");
|
||||
}
|
||||
assert!(!staged_veh.exists());
|
||||
assert!(!staged_xgr.exists());
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staging_never_overwrites_or_deletes_preexisting_system32_dll() {
|
||||
let root = env::temp_dir().join(format!("bx-cli-stage-keep-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let shims = root.join("shims");
|
||||
let sys32 = root.join("prefix/drive_c/windows/system32");
|
||||
fs::create_dir_all(&shims).unwrap();
|
||||
fs::create_dir_all(&sys32).unwrap();
|
||||
fs::write(shims.join("xgameruntime.dll"), b"bx-shim-bytes").unwrap();
|
||||
let dst = sys32.join("xgameruntime.dll");
|
||||
fs::write(&dst, b"host-original-bytes").unwrap();
|
||||
|
||||
{
|
||||
let guard =
|
||||
StagedSystem32Shims::stage(&root.join("prefix"), &shims, SYSTEM32_STAGED_SHIMS);
|
||||
assert!(guard.staged.is_empty());
|
||||
assert_eq!(fs::read(&dst).unwrap(), b"host-original-bytes");
|
||||
}
|
||||
assert_eq!(fs::read(&dst).unwrap(), b"host-original-bytes");
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staging_refuses_to_clobber_preexisting_symlink_in_system32() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let root = env::temp_dir().join(format!("bx-cli-stage-sym-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let shims = root.join("shims");
|
||||
let sys32 = root.join("prefix/drive_c/windows/system32");
|
||||
fs::create_dir_all(&shims).unwrap();
|
||||
fs::create_dir_all(&sys32).unwrap();
|
||||
fs::write(shims.join("xgameruntime.dll"), b"bx-shim-bytes").unwrap();
|
||||
let dst = sys32.join("xgameruntime.dll");
|
||||
symlink(root.join("dangling-target"), &dst).unwrap();
|
||||
|
||||
{
|
||||
let guard =
|
||||
StagedSystem32Shims::stage(&root.join("prefix"), &shims, SYSTEM32_STAGED_SHIMS);
|
||||
assert!(guard.staged.is_empty());
|
||||
}
|
||||
assert!(dst.symlink_metadata().unwrap().file_type().is_symlink());
|
||||
assert!(!root.join("dangling-target").exists());
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staging_is_a_noop_when_system32_directory_is_absent() {
|
||||
let root = env::temp_dir().join(format!("bx-cli-stage-empty-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let shims = root.join("shims");
|
||||
fs::create_dir_all(&shims).unwrap();
|
||||
fs::write(shims.join("xgameruntime.dll"), b"bx-shim-bytes").unwrap();
|
||||
|
||||
let guard =
|
||||
StagedSystem32Shims::stage(&root.join("bare-prefix"), &shims, SYSTEM32_STAGED_SHIMS);
|
||||
assert!(guard.staged.is_empty());
|
||||
assert!(!root.join("bare-prefix").exists());
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,32 @@
|
||||
//! Track A / F: Structured JSONL shim trace aggregator.
|
||||
//!
|
||||
//! Summarizes `bx_runtime_veh.dll` logs (stub API calls, unimplemented COM vtable
|
||||
//! slots, `clwb` traps, and ADX illegal-instruction tripwires) so tracks can prioritize
|
||||
//! the exact next blocking API.
|
||||
//! slots, `clwb` traps, ADX illegal-instruction tripwires, and unhandled exceptions)
|
||||
//! so tracks can identify guest failures and missing APIs.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct TraceSummary {
|
||||
pub total_lines: usize,
|
||||
/// Number of `clwb_trapped` records in the log.
|
||||
pub clwb_events: usize,
|
||||
/// Highest cumulative counter in the sampled CLWB records, if available.
|
||||
pub clwb_trap_lower_bound: Option<u64>,
|
||||
pub adx_errors: usize,
|
||||
pub unhandled_exceptions: Vec<UnhandledException>,
|
||||
pub unimpl_apis: BTreeMap<String, usize>,
|
||||
pub unimpl_vtables: BTreeMap<String, usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct UnhandledException {
|
||||
pub exception_code: Option<String>,
|
||||
pub module_base: Option<String>,
|
||||
pub rva: Option<String>,
|
||||
pub rip: Option<String>,
|
||||
}
|
||||
|
||||
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
let needle = format!("\"{key}\":\"");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
@@ -34,8 +46,23 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
let event = extract_json_str(trimmed, "event").unwrap_or("");
|
||||
let detail = extract_json_str(trimmed, "detail").unwrap_or("");
|
||||
match event {
|
||||
"clwb_trapped" => summary.clwb_events += 1,
|
||||
"clwb_trapped" => {
|
||||
summary.clwb_events += 1;
|
||||
let sample = detail
|
||||
.split_ascii_whitespace()
|
||||
.find_map(|field| field.strip_prefix("total_traps="))
|
||||
.and_then(|count| count.parse::<u64>().ok());
|
||||
summary.clwb_trap_lower_bound = summary.clwb_trap_lower_bound.max(sample);
|
||||
}
|
||||
"adx_illegal_instruction" => summary.adx_errors += 1,
|
||||
"unhandled_exception" => {
|
||||
summary.unhandled_exceptions.push(UnhandledException {
|
||||
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
|
||||
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
|
||||
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
|
||||
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
|
||||
});
|
||||
}
|
||||
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
|
||||
"unimpl_vtable" => {
|
||||
*summary
|
||||
@@ -64,7 +91,9 @@ mod tests {
|
||||
let s = summarize_jsonl(sample);
|
||||
assert_eq!(s.total_lines, 4);
|
||||
assert_eq!(s.clwb_events, 1);
|
||||
assert_eq!(s.clwb_trap_lower_bound, Some(1));
|
||||
assert_eq!(s.adx_errors, 0);
|
||||
assert!(s.unhandled_exceptions.is_empty());
|
||||
assert_eq!(
|
||||
s.unimpl_apis.get("d3d12_xs.dll!D3D12XboxCreateDevice"),
|
||||
Some(&2)
|
||||
@@ -75,4 +104,65 @@ mod tests {
|
||||
Some(&1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_highest_counter_from_sampled_clwb_records() {
|
||||
for (actual_traps, records, expected_bound) in [
|
||||
(1, &[1][..], 1),
|
||||
(6, &[1, 4, 2], 4),
|
||||
(100, &[1, 2, 4, 8, 16, 32, 64], 64),
|
||||
] {
|
||||
let mut log = String::new();
|
||||
for counter in records {
|
||||
log.push_str(&format!(
|
||||
"{{\"event\":\"clwb_trapped\",\"detail\":\"rip=0x1000 len=4 total_traps={counter}\"}}\n"
|
||||
));
|
||||
}
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.clwb_events, records.len(), "{actual_traps} traps");
|
||||
assert_eq!(
|
||||
summary.clwb_trap_lower_bound,
|
||||
Some(expected_bound),
|
||||
"{actual_traps} traps"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_clwb_record_count_without_valid_counters() {
|
||||
let summary = summarize_jsonl(
|
||||
r#"{"event":"clwb_trapped","detail":"rip=0x1000 len=4"}
|
||||
{"event":"clwb_trapped","detail":"rip=0x1000 len=4 total_traps=invalid"}
|
||||
{"event":"unimpl_api","detail":"total_traps=100"}"#,
|
||||
);
|
||||
assert_eq!(summary.clwb_events, 2);
|
||||
assert_eq!(summary.clwb_trap_lower_bound, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_unhandled_exceptions_in_log_order() {
|
||||
let log = r#"
|
||||
{"ts_ms":16,"tid":1,"level":"ERROR","sub":"runtime_veh","event":"unhandled_exception","exception_code":"0xc0000005","module_base":"0x0000000140000000","rva":"0x0000000000001234","rip":"0x0000000140001234","rsp":"0x000000000021fd80","registers":{"rax":"0x0123456789abcdef","rbx":"0x0000000000000000","rcx":"0x0000000000000000","rdx":"0x0000000000000000","rsi":"0x0000000000000000","rdi":"0x0000000000000000","rbp":"0x0000000000000000","r8":"0x0000000000000000","r9":"0x0000000000000000","r10":"0x0000000000000000","r11":"0x0000000000000000","r12":"0x0000000000000000","r13":"0x0000000000000000","r14":"0x0000000000000000","r15":"0x0000000000000000"}}
|
||||
{"ts_ms":20,"tid":1,"level":"ERROR","sub":"runtime_veh","event":"unhandled_exception","exception_code":"0xc000001d","module_base":"0x0000000000000000","rva":"0x0000000000000000","rip":"0x0000000000410000","rsp":"0x000000000021fd80","registers":{}}
|
||||
"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.total_lines, 2);
|
||||
assert_eq!(
|
||||
summary.unhandled_exceptions,
|
||||
[
|
||||
UnhandledException {
|
||||
exception_code: Some("0xc0000005".into()),
|
||||
module_base: Some("0x0000000140000000".into()),
|
||||
rva: Some("0x0000000000001234".into()),
|
||||
rip: Some("0x0000000140001234".into()),
|
||||
},
|
||||
UnhandledException {
|
||||
exception_code: Some("0xc000001d".into()),
|
||||
module_base: Some("0x0000000000000000".into()),
|
||||
rva: Some("0x0000000000000000".into()),
|
||||
rip: Some("0x0000000000410000".into()),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,37 +1,249 @@
|
||||
#include <windows.h>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
namespace {
|
||||
std::atomic<uintptr_t> g_next_token{1};
|
||||
|
||||
static_assert(sizeof(uintptr_t) == 8, "BetterXen Win32 shims target x86-64");
|
||||
|
||||
constexpr uintptr_t kPrefixMask = 0xFFFFFFFF00000000ULL;
|
||||
constexpr uintptr_t kSequenceMask = 0x00000000FFFFFFFFULL;
|
||||
constexpr uintptr_t kStatePrefix = 0x50534D3100000000ULL; // "PSM1"
|
||||
constexpr uintptr_t kConstrainedPrefix = 0x50534D3200000000ULL; // "PSM2"
|
||||
constexpr uintptr_t kEmptySlot = 0;
|
||||
constexpr uintptr_t kTombstoneSlot = ~uintptr_t{0};
|
||||
|
||||
struct SrwLockGuard {
|
||||
SRWLOCK& lock;
|
||||
explicit SrwLockGuard(SRWLOCK& l) : lock(l) { AcquireSRWLockExclusive(&lock); }
|
||||
~SrwLockGuard() { ReleaseSRWLockExclusive(&lock); }
|
||||
SrwLockGuard(const SrwLockGuard&) = delete;
|
||||
SrwLockGuard& operator=(const SrwLockGuard&) = delete;
|
||||
};
|
||||
|
||||
// Exception-free open-addressed hash set backed by the Win32 process heap so
|
||||
// both PSM DLLs stay on -fno-exceptions and map OOM to ERROR_NOT_ENOUGH_MEMORY.
|
||||
struct TokenSet {
|
||||
uintptr_t* slots = nullptr;
|
||||
size_t capacity = 0;
|
||||
size_t count = 0;
|
||||
size_t used = 0; // active entries + tombstones
|
||||
|
||||
static size_t hash(uintptr_t value) {
|
||||
uint64_t x = static_cast<uint64_t>(value);
|
||||
x ^= x >> 30;
|
||||
x *= 0xbf58476d1ce4e5b9ULL;
|
||||
x ^= x >> 27;
|
||||
x *= 0x94d049bb133111ebULL;
|
||||
x ^= x >> 31;
|
||||
return static_cast<size_t>(x);
|
||||
}
|
||||
|
||||
bool rehash(size_t new_capacity) {
|
||||
if (new_capacity == 0 || new_capacity > SIZE_MAX / sizeof(uintptr_t)) {
|
||||
return false;
|
||||
}
|
||||
HANDLE heap = GetProcessHeap();
|
||||
if (!heap) {
|
||||
return false;
|
||||
}
|
||||
auto* fresh = static_cast<uintptr_t*>(
|
||||
HeapAlloc(heap, HEAP_ZERO_MEMORY, new_capacity * sizeof(uintptr_t)));
|
||||
if (!fresh) {
|
||||
return false;
|
||||
}
|
||||
const size_t mask = new_capacity - 1;
|
||||
for (size_t i = 0; i < capacity; ++i) {
|
||||
const uintptr_t entry = slots[i];
|
||||
if (entry != kEmptySlot && entry != kTombstoneSlot) {
|
||||
size_t idx = hash(entry) & mask;
|
||||
while (fresh[idx] != kEmptySlot) {
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
fresh[idx] = entry;
|
||||
}
|
||||
}
|
||||
if (slots) {
|
||||
HeapFree(heap, 0, slots);
|
||||
}
|
||||
slots = fresh;
|
||||
capacity = new_capacity;
|
||||
used = count;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool insert(uintptr_t token) {
|
||||
if (capacity == 0 || (used + 1) * 4 >= capacity * 3) {
|
||||
size_t next_capacity = 64;
|
||||
if (capacity != 0) {
|
||||
if (count * 2 >= capacity) {
|
||||
if (capacity > (SIZE_MAX / sizeof(uintptr_t)) / 2) {
|
||||
return false;
|
||||
}
|
||||
next_capacity = capacity * 2;
|
||||
} else {
|
||||
// Compact tombstones in place without growing the table.
|
||||
next_capacity = capacity;
|
||||
}
|
||||
}
|
||||
if (!rehash(next_capacity)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const size_t mask = capacity - 1;
|
||||
size_t idx = hash(token) & mask;
|
||||
size_t first_tombstone = capacity;
|
||||
while (true) {
|
||||
const uintptr_t entry = slots[idx];
|
||||
if (entry == token) {
|
||||
return true;
|
||||
}
|
||||
if (entry == kEmptySlot) {
|
||||
if (first_tombstone != capacity) {
|
||||
slots[first_tombstone] = token;
|
||||
} else {
|
||||
slots[idx] = token;
|
||||
++used;
|
||||
}
|
||||
++count;
|
||||
return true;
|
||||
}
|
||||
if (entry == kTombstoneSlot && first_tombstone == capacity) {
|
||||
first_tombstone = idx;
|
||||
}
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
}
|
||||
|
||||
bool erase(uintptr_t token) {
|
||||
if (capacity == 0 || count == 0 || token == kEmptySlot || token == kTombstoneSlot) {
|
||||
return false;
|
||||
}
|
||||
const size_t mask = capacity - 1;
|
||||
size_t idx = hash(token) & mask;
|
||||
for (size_t probed = 0; probed < capacity; ++probed) {
|
||||
const uintptr_t entry = slots[idx];
|
||||
if (entry == kEmptySlot) {
|
||||
return false;
|
||||
}
|
||||
if (entry == token) {
|
||||
slots[idx] = kTombstoneSlot;
|
||||
--count;
|
||||
return true;
|
||||
}
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
if (slots) {
|
||||
HANDLE heap = GetProcessHeap();
|
||||
if (heap) {
|
||||
HeapFree(heap, 0, slots);
|
||||
}
|
||||
slots = nullptr;
|
||||
}
|
||||
capacity = 0;
|
||||
count = 0;
|
||||
used = 0;
|
||||
}
|
||||
};
|
||||
|
||||
struct Registrations {
|
||||
SRWLOCK lock;
|
||||
TokenSet active;
|
||||
uintptr_t own_prefix;
|
||||
uintptr_t foreign_prefix;
|
||||
uint64_t next_seq;
|
||||
};
|
||||
|
||||
// Each DLL exposes one family. Disjoint tagged token spaces prevent an
|
||||
// unregister call on the wrong DLL from removing another registration and let
|
||||
// logs distinguish foreign-family tokens from retired or invalid ones.
|
||||
Registrations g_state{SRWLOCK_INIT, {}, kStatePrefix, kConstrainedPrefix, 1};
|
||||
Registrations g_constrained{SRWLOCK_INIT, {}, kConstrainedPrefix, kStatePrefix, 1};
|
||||
|
||||
ULONG register_notification(Registrations& registrations, PVOID callback,
|
||||
PVOID* out_reg, const char* event) {
|
||||
if (!out_reg) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
*out_reg = nullptr;
|
||||
if (!callback) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
|
||||
uintptr_t token = 0;
|
||||
{
|
||||
const SrwLockGuard guard(registrations.lock);
|
||||
// Never recycle a token that a caller may still retain.
|
||||
if (registrations.next_seq > kSequenceMask) {
|
||||
return ERROR_NOT_ENOUGH_MEMORY;
|
||||
}
|
||||
token = registrations.own_prefix | static_cast<uintptr_t>(registrations.next_seq);
|
||||
if (!registrations.active.insert(token)) {
|
||||
return ERROR_NOT_ENOUGH_MEMORY;
|
||||
}
|
||||
++registrations.next_seq;
|
||||
}
|
||||
|
||||
*out_reg = reinterpret_cast<PVOID>(token);
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, "registered_offline");
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
void unregister_notification(Registrations& registrations, PVOID reg, const char* event) {
|
||||
const uintptr_t token = reinterpret_cast<uintptr_t>(reg);
|
||||
bool removed = false;
|
||||
{
|
||||
const SrwLockGuard guard(registrations.lock);
|
||||
removed = registrations.active.erase(token);
|
||||
}
|
||||
const char* detail = "unknown_token";
|
||||
if (removed) {
|
||||
detail = "unregistered";
|
||||
} else if ((token & kPrefixMask) == registrations.foreign_prefix &&
|
||||
(token & kSequenceMask) != 0) {
|
||||
detail = "foreign_token";
|
||||
}
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, detail);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
ULONG WINAPI RegisterAppStateChangeNotification(PVOID /*callback*/, PVOID /*context*/, PVOID* out_reg) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "RegisterAppStateChangeNotification", "noop_ok");
|
||||
if (out_reg) {
|
||||
*out_reg = reinterpret_cast<PVOID>(g_next_token.fetch_add(1));
|
||||
BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) {
|
||||
if (reason == DLL_PROCESS_DETACH && reserved == nullptr) {
|
||||
{
|
||||
const SrwLockGuard guard(g_state.lock);
|
||||
g_state.active.reset();
|
||||
}
|
||||
{
|
||||
const SrwLockGuard guard(g_constrained.lock);
|
||||
g_constrained.active.reset();
|
||||
}
|
||||
}
|
||||
return ERROR_SUCCESS;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppStateChangeNotification(PVOID /*reg*/) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "UnregisterAppStateChangeNotification", "noop_ok");
|
||||
ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
|
||||
return register_notification(g_state, callback, out_reg, "RegisterAppStateChangeNotification");
|
||||
}
|
||||
|
||||
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID /*callback*/, PVOID /*context*/, PVOID* out_reg) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "RegisterAppConstrainedChangeNotification", "noop_ok");
|
||||
if (out_reg) {
|
||||
*out_reg = reinterpret_cast<PVOID>(g_next_token.fetch_add(1));
|
||||
}
|
||||
return ERROR_SUCCESS;
|
||||
VOID WINAPI UnregisterAppStateChangeNotification(PVOID reg) {
|
||||
unregister_notification(g_state, reg, "UnregisterAppStateChangeNotification");
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppConstrainedChangeNotification(PVOID /*reg*/) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "UnregisterAppConstrainedChangeNotification", "noop_ok");
|
||||
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
|
||||
return register_notification(g_constrained, callback, out_reg, "RegisterAppConstrainedChangeNotification");
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppConstrainedChangeNotification(PVOID reg) {
|
||||
unregister_notification(g_constrained, reg, "UnregisterAppConstrainedChangeNotification");
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -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"
|
||||
@@ -1,4 +1,5 @@
|
||||
bx_add_shim_dll(xmem xmem xmem.def
|
||||
xmem.cpp
|
||||
physical_pages.cpp
|
||||
)
|
||||
target_link_libraries(xmem PRIVATE bx_runtime_veh kernel32)
|
||||
@@ -0,0 +1,385 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xmem_accounting.h"
|
||||
|
||||
namespace {
|
||||
constexpr SIZE_T small_page = 64 * 1024;
|
||||
constexpr SIZE_T large_page = 2 * 1024 * 1024;
|
||||
|
||||
struct PageBlock;
|
||||
|
||||
struct Page {
|
||||
PageBlock* block;
|
||||
HANDLE section;
|
||||
bool releasing;
|
||||
};
|
||||
|
||||
struct PageBlock {
|
||||
ULONG_PTR first_tag;
|
||||
SIZE_T count;
|
||||
SIZE_T size;
|
||||
SIZE_T live;
|
||||
Page* entries;
|
||||
PageBlock* next;
|
||||
};
|
||||
|
||||
struct View {
|
||||
Page* page;
|
||||
BYTE* address;
|
||||
View* next;
|
||||
};
|
||||
|
||||
SRWLOCK memory_lock = SRWLOCK_INIT;
|
||||
PageBlock* blocks = nullptr;
|
||||
View* views = nullptr;
|
||||
ULONG_PTR next_tag = 1;
|
||||
|
||||
struct Lock {
|
||||
Lock() { AcquireSRWLockExclusive(&memory_lock); }
|
||||
~Lock() { ReleaseSRWLockExclusive(&memory_lock); }
|
||||
};
|
||||
|
||||
using ReservePlaceholder = PVOID (WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG,
|
||||
MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
using ReplacePlaceholder = PVOID (WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG,
|
||||
ULONG, MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
|
||||
struct PlaceholderApi {
|
||||
HMODULE kernel = GetModuleHandleW(L"kernelbase.dll");
|
||||
ReservePlaceholder reserve = resolve<ReservePlaceholder>("VirtualAlloc2");
|
||||
ReplacePlaceholder replace = resolve<ReplacePlaceholder>("MapViewOfFile3");
|
||||
|
||||
template<class Function>
|
||||
Function resolve(const char* name) const {
|
||||
return reinterpret_cast<Function>(reinterpret_cast<void*>(GetProcAddress(kernel, name)));
|
||||
}
|
||||
};
|
||||
|
||||
// The public backlog defines the supported sizes. The flags accepted here
|
||||
// belong to BetterXen's synthetic fixtures, pending a public console flags ABI.
|
||||
SIZE_T page_size(uint64_t flags) {
|
||||
switch (flags) {
|
||||
case 0:
|
||||
case small_page: return small_page;
|
||||
case large_page: return large_page;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
Page* find_page(ULONG_PTR tag) {
|
||||
for (PageBlock* block = blocks; block; block = block->next) {
|
||||
if (tag >= block->first_tag && tag - block->first_tag < block->count) {
|
||||
Page* page = &block->entries[tag - block->first_tag];
|
||||
return page->section ? page : nullptr;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ULONG_PTR page_tag(const Page* page) {
|
||||
return page->block->first_tag + (page - page->block->entries);
|
||||
}
|
||||
|
||||
void delete_block(PageBlock* block) {
|
||||
for (SIZE_T i = 0; i < block->count; ++i) {
|
||||
if (block->entries[i].section) CloseHandle(block->entries[i].section);
|
||||
}
|
||||
delete[] block->entries;
|
||||
delete block;
|
||||
}
|
||||
|
||||
void destroy_views(View* first) {
|
||||
while (first) {
|
||||
View* next = first->next;
|
||||
delete first;
|
||||
first = next;
|
||||
}
|
||||
}
|
||||
|
||||
bool valid_span(PVOID base, SIZE_T count, SIZE_T size) {
|
||||
const auto address = reinterpret_cast<uintptr_t>(base);
|
||||
return size && count && address % size == 0
|
||||
&& count <= (std::numeric_limits<uintptr_t>::max() - address) / size;
|
||||
}
|
||||
|
||||
bool remove_view(View** link) {
|
||||
View* view = *link;
|
||||
if (!UnmapViewOfFile(view->address)) return false;
|
||||
*link = view->next;
|
||||
delete view;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Require every page slot in [base, base + count * size) to be actively mapped
|
||||
// with matching page size before unmapping; empty or partial spans fail without
|
||||
// modifying any existing views.
|
||||
PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
|
||||
if (!base) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
const auto begin = reinterpret_cast<uintptr_t>(base);
|
||||
const auto end = begin + count * size;
|
||||
|
||||
SIZE_T matched = 0;
|
||||
for (const View* view = views; view; view = view->next) {
|
||||
const auto address = reinterpret_cast<uintptr_t>(view->address);
|
||||
if (address >= begin && address < end && view->page->block->size == size) {
|
||||
++matched;
|
||||
}
|
||||
}
|
||||
if (matched != count) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
for (View** link = &views; *link;) {
|
||||
View* view = *link;
|
||||
const auto address = reinterpret_cast<uintptr_t>(view->address);
|
||||
if (address >= begin && address < end && view->page->block->size == size) {
|
||||
if (!remove_view(link)) return nullptr;
|
||||
} else {
|
||||
link = &view->next;
|
||||
}
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
// Duplicate tags in `tags` are intentionally permitted so a single virtual span
|
||||
// can alias one physical page at multiple offsets (e.g. ring buffers / tiles).
|
||||
PVOID map_pages(PVOID address, SIZE_T count, uint64_t flags, const ULONG_PTR* tags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!valid_span(address, count, size)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
if (!tags) return unmap_span(static_cast<BYTE*>(address), count, size);
|
||||
|
||||
static const PlaceholderApi api;
|
||||
if (!api.reserve || !api.replace) {
|
||||
BX_STUB_LOG("xmem.dll", "MapViewOfFile3");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
View* pending = nullptr;
|
||||
for (SIZE_T i = count; i > 0; --i) {
|
||||
Page* page = find_page(tags[i - 1]);
|
||||
if (!page || page->block->size != size) {
|
||||
destroy_views(pending);
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
auto* view = new (std::nothrow) View{page, nullptr, pending};
|
||||
if (!view) {
|
||||
destroy_views(pending);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
pending = view;
|
||||
}
|
||||
|
||||
MEM_ADDRESS_REQUIREMENTS requirements{};
|
||||
requirements.Alignment = size;
|
||||
MEM_EXTENDED_PARAMETER alignment{};
|
||||
alignment.Type = MemExtendedParameterAddressRequirements;
|
||||
alignment.Pointer = &requirements;
|
||||
auto* base = static_cast<BYTE*>(api.reserve(nullptr, address, count * size,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS,
|
||||
address ? nullptr : &alignment, address ? 0 : 1));
|
||||
if (!base) {
|
||||
const DWORD error = GetLastError();
|
||||
destroy_views(pending);
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
BYTE* cursor = base;
|
||||
SIZE_T remaining = count;
|
||||
View* view = pending;
|
||||
for (; view; view = view->next, cursor += size, --remaining) {
|
||||
const bool split = remaining > 1;
|
||||
if (split && !VirtualFree(cursor, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) break;
|
||||
if (!api.replace(view->page->section, nullptr, cursor, 0, size,
|
||||
MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) {
|
||||
const DWORD error = GetLastError();
|
||||
if (split) VirtualFree(cursor + size, 0, MEM_RELEASE);
|
||||
SetLastError(error);
|
||||
break;
|
||||
}
|
||||
view->address = cursor;
|
||||
}
|
||||
|
||||
if (view) {
|
||||
const DWORD error = GetLastError();
|
||||
VirtualFree(cursor, 0, MEM_RELEASE);
|
||||
for (View* completed = pending; completed != view; completed = completed->next) {
|
||||
UnmapViewOfFile(completed->address);
|
||||
}
|
||||
destroy_views(pending);
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
while (pending) {
|
||||
View* next = pending->next;
|
||||
pending->next = views;
|
||||
views = pending;
|
||||
pending = next;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// Clean-room synthetic signatures modeled after public Win32 AWE
|
||||
// AllocateUserPhysicalPages / FreeUserPhysicalPages (memoryapi.h, [in, out]
|
||||
// page count pointer), pending a public console flags/signature ABI.
|
||||
extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
|
||||
uint64_t flags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
const SIZE_T count = *num_pages;
|
||||
if (count > std::numeric_limits<ULONG_PTR>::max() - next_tag
|
||||
|| count > std::numeric_limits<SIZE_T>::max() / sizeof(Page)
|
||||
|| count > std::numeric_limits<uint64_t>::max() / size) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
const uint64_t total_bytes = static_cast<uint64_t>(count) * size;
|
||||
if (!bx_xmem::try_reserve_physical(total_bytes)) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
auto* entries = new (std::nothrow) Page[count]{};
|
||||
if (!entries) {
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
auto* block = new (std::nothrow) PageBlock{next_tag, count, size, count, entries, blocks};
|
||||
if (!block) {
|
||||
delete[] entries;
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE,
|
||||
0, static_cast<DWORD>(size), nullptr);
|
||||
if (!section) {
|
||||
const DWORD error = GetLastError();
|
||||
delete_block(block);
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
entries[i] = {block, section, false};
|
||||
}
|
||||
|
||||
blocks = block;
|
||||
for (SIZE_T i = 0; i < count; ++i) page_array[i] = next_tag + i;
|
||||
next_tag += count;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// Rejects unknown, wrong-size, or duplicate tags in `page_array` with
|
||||
// ERROR_INVALID_PARAMETER without mutating `page_array` or live views.
|
||||
extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
|
||||
uint64_t flags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
const SIZE_T count = *num_pages;
|
||||
SIZE_T validated = 0;
|
||||
for (; validated < count; ++validated) {
|
||||
Page* page = find_page(page_array[validated]);
|
||||
if (!page || page->block->size != size || page->releasing) break;
|
||||
page->releasing = true;
|
||||
}
|
||||
if (validated != count) {
|
||||
for (SIZE_T i = 0; i < validated; ++i) find_page(page_array[i])->releasing = false;
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
for (View** link = &views; *link;) {
|
||||
if ((*link)->page->releasing) {
|
||||
if (!remove_view(link)) {
|
||||
const DWORD error = GetLastError();
|
||||
for (SIZE_T i = 0; i < count; ++i) find_page(page_array[i])->releasing = false;
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
} else {
|
||||
link = &(*link)->next;
|
||||
}
|
||||
}
|
||||
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
Page* page = find_page(page_array[i]);
|
||||
CloseHandle(page->section);
|
||||
page->section = nullptr;
|
||||
--page->block->live;
|
||||
page_array[i] = 0;
|
||||
}
|
||||
for (PageBlock** link = &blocks; *link;) {
|
||||
PageBlock* block = *link;
|
||||
if (block->live) {
|
||||
link = &block->next;
|
||||
} else {
|
||||
*link = block->next;
|
||||
delete_block(block);
|
||||
}
|
||||
}
|
||||
bx_xmem::release_physical(static_cast<uint64_t>(count) * size);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
extern "C" PVOID WINAPI XMemMapPhysicalPages(PVOID base, SIZE_T count, uint64_t flags,
|
||||
PULONG_PTR page_array) {
|
||||
return map_pages(base, count, flags, page_array);
|
||||
}
|
||||
|
||||
extern "C" PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID base, SIZE_T count, uint64_t flags,
|
||||
PULONG_PTR page_array) {
|
||||
return map_pages(base, count, flags, page_array);
|
||||
}
|
||||
|
||||
extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info) {
|
||||
if (!out_info) return 0;
|
||||
|
||||
Lock lock;
|
||||
for (const View* view = views; view; view = view->next) {
|
||||
const auto base = reinterpret_cast<uintptr_t>(view->address);
|
||||
const SIZE_T size = view->page->block->size;
|
||||
if (va >= base && va - base < size) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(view->address, ®ion, sizeof(region))
|
||||
|| region.AllocationBase != view->address || region.Type != MEM_MAPPED) {
|
||||
return 0;
|
||||
}
|
||||
*out_info = {base, size, size, region.Protect, region.Type, page_tag(view->page)};
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
+25
-31
@@ -10,6 +10,7 @@
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xmem_accounting.h"
|
||||
|
||||
namespace {
|
||||
constexpr SIZE_T heap_alignment = 64;
|
||||
@@ -61,6 +62,7 @@ std::mutex usage_lock;
|
||||
CommitTable virtual_commits;
|
||||
uint64_t heap_bytes = 0;
|
||||
uint64_t virtual_bytes = 0;
|
||||
uint64_t physical_bytes = 0;
|
||||
uint64_t peak_bytes = 0;
|
||||
|
||||
uint64_t title_limit() {
|
||||
@@ -70,12 +72,12 @@ uint64_t title_limit() {
|
||||
|
||||
bool can_commit(uint64_t bytes) {
|
||||
const uint64_t limit = title_limit();
|
||||
const uint64_t used = heap_bytes + virtual_bytes;
|
||||
const uint64_t used = heap_bytes + virtual_bytes + physical_bytes;
|
||||
return used <= limit && bytes <= limit - used;
|
||||
}
|
||||
|
||||
void update_peak() {
|
||||
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes);
|
||||
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes);
|
||||
}
|
||||
|
||||
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
|
||||
@@ -268,29 +270,6 @@ SIZE_T WINAPI XMemVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buf, S
|
||||
return VirtualQuery(address, buf, len);
|
||||
}
|
||||
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* /*num_pages*/, PULONG_PTR /*page_array*/, uint64_t /*flags*/) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemAllocatePhysicalPages");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
BOOL WINAPI XMemFreePhysicalPages(SIZE_T /*num_pages*/, PULONG_PTR /*page_array*/, uint64_t /*flags*/) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemFreePhysicalPages");
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID /*base*/, SIZE_T /*num_pages*/, uint64_t /*flags*/, PULONG_PTR /*page_array*/) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPages");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID /*base*/, SIZE_T /*num_pages*/, uint64_t /*flags*/, PULONG_PTR /*page_array*/) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPagesScatter");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t /*flags*/) {
|
||||
if (bytes == 0) return TRUE;
|
||||
if (!dst || !src) {
|
||||
@@ -311,7 +290,7 @@ BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, 0, peak_bytes};
|
||||
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
|
||||
std::memset(out_stats, 0, stats_size);
|
||||
std::memcpy(out_stats, &stats, sizeof(stats));
|
||||
return TRUE;
|
||||
@@ -321,18 +300,33 @@ BOOL WINAPI XMemIsToolsMemAvailable(void) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
int bx_xmem_query_region(uint64_t /*va*/, bx_xmem_region_info_t* /*out_info*/) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats) {
|
||||
if (!out_stats) return;
|
||||
if (!XMemGetWorkingSetStatistics(out_stats, sizeof(*out_stats))) {
|
||||
// The internal ABI has no error return. Preserve the most recent
|
||||
// accounting snapshot if refreshing it runs out of bookkeeping memory.
|
||||
std::lock_guard guard(usage_lock);
|
||||
*out_stats = {title_limit(), heap_bytes + virtual_bytes, 0, peak_bytes};
|
||||
*out_stats = {title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
|
||||
}
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
namespace bx_xmem {
|
||||
|
||||
bool try_reserve_physical(uint64_t bytes) {
|
||||
std::lock_guard guard(usage_lock);
|
||||
if (!can_commit(bytes) && (!refresh_virtual_commits() || !can_commit(bytes))) {
|
||||
return false;
|
||||
}
|
||||
physical_bytes += bytes;
|
||||
update_peak();
|
||||
return true;
|
||||
}
|
||||
|
||||
void release_physical(uint64_t bytes) {
|
||||
std::lock_guard guard(usage_lock);
|
||||
physical_bytes = physical_bytes >= bytes ? physical_bytes - bytes : 0;
|
||||
}
|
||||
|
||||
} // namespace bx_xmem
|
||||
@@ -0,0 +1,15 @@
|
||||
#ifndef BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
#define BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace bx_xmem {
|
||||
|
||||
// Reserve or release physical-page bytes against the shared xmem title memory
|
||||
// cap and working-set statistics (heap + virtual + physical <= title limit).
|
||||
bool try_reserve_physical(uint64_t bytes);
|
||||
void release_physical(uint64_t bytes);
|
||||
|
||||
} // namespace bx_xmem
|
||||
|
||||
#endif // BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
@@ -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;
|
||||
}
|
||||
@@ -6,7 +6,9 @@
|
||||
# CreateWindowExA & co. bind to the ext-ms-win-rtcore-ntuser-* shims instead of
|
||||
# the toolchain's default user32 import library.
|
||||
add_executable(test_integration_boot main.cpp)
|
||||
target_include_directories(test_integration_boot PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_include_directories(test_integration_boot PRIVATE
|
||||
"${BX_ABI_INCLUDE_DIR}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../../../shims/xg_xs")
|
||||
target_link_libraries(test_integration_boot PRIVATE
|
||||
ntuser_win_ansi_1_0
|
||||
ntuser_win_1_0
|
||||
|
||||
@@ -24,7 +24,8 @@
|
||||
* or an error-severity exception.
|
||||
*
|
||||
* Function prototypes below mirror the in-tree shim sources and abi/defs; this
|
||||
* fixture deliberately invents no console structure layouts.
|
||||
* fixture deliberately invents no console structure layouts. The xg_xs
|
||||
* descriptor and vtable are BetterXen's own, from shims/xg_xs/xg_texture.h.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
@@ -40,6 +41,7 @@
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xg_texture.h"
|
||||
|
||||
#define BX_IMPORT __declspec(dllimport)
|
||||
|
||||
@@ -94,11 +96,7 @@ BX_IMPORT HRESULT WINAPI XDspDisconnect(void* handle);
|
||||
/* GameInput.dll (ordinal 1) */
|
||||
BX_IMPORT HRESULT WINAPI GameInputCreate(void** out_game_input);
|
||||
|
||||
/* xg_xs.dll */
|
||||
BX_IMPORT HRESULT WINAPI XGCreateTextureComputer(const void* desc, void** out_computer);
|
||||
BX_IMPORT uint32_t WINAPI XGSuggestSwizzleMode(uint32_t resource_type, uint32_t format, uint32_t width,
|
||||
uint32_t height, uint32_t depth, uint32_t mip_levels,
|
||||
uint32_t sample_count, uint32_t flags);
|
||||
/* xg_xs.dll is declared by "xg_texture.h". */
|
||||
|
||||
/* d3d12_xs.dll (D3D12SerializeVersionedRootSignature is declared by <d3d12.h>) */
|
||||
BX_IMPORT HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
|
||||
@@ -651,27 +649,71 @@ void stage_acphal_heap() {
|
||||
|
||||
/* ---- Stage 13: xg_xs ---------------------------------------------------------------------- */
|
||||
|
||||
/*
|
||||
* 100x50 R8G8B8A8 with two mips, so both public D3D12 alignments matter. By hand:
|
||||
* mip 0: 100 * 4 = 400 bytes per row, pitch 512 (256-byte pitch alignment);
|
||||
* ends at 49 * 512 + 400 = 25488.
|
||||
* mip 1: starts at the next 512 boundary, 25600; 50 * 4 = 200 bytes per row,
|
||||
* pitch 256; ends at 25600 + 24 * 256 + 200 = 31944.
|
||||
* total: 31944 rounded up to 512 = 32256.
|
||||
*/
|
||||
void* stage_xg_texture_computer() {
|
||||
begin_stage("xg_xs_texture_computer");
|
||||
bx_xg_resource_desc desc = {};
|
||||
desc.dimension = BX_XG_DIMENSION_TEXTURE2D;
|
||||
desc.width = 100;
|
||||
desc.height = 50;
|
||||
desc.depth_or_array_size = 1;
|
||||
desc.mip_levels = 2;
|
||||
desc.format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.sample_desc.count = 1;
|
||||
desc.layout = BX_XG_LAYOUT_LINEAR;
|
||||
|
||||
void* object = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
HRESULT hr = XGCreateTextureComputer(&desc, &object);
|
||||
if (hr != S_OK || !object || object == reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD))) {
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail, "XGCreateTextureComputer hr=0x%08lx object=%p",
|
||||
static_cast<unsigned long>(hr), object);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(object);
|
||||
bx_xg_placed_footprint mips[2] = {};
|
||||
uint32_t rows[2] = {};
|
||||
uint64_t row_bytes[2] = {};
|
||||
uint64_t total = 0;
|
||||
hr = computer->lpVtbl->GetResourceLayout(computer, 0, 2, 0, mips, rows, row_bytes, &total);
|
||||
auto shape_is = [](const bx_xg_subresource_footprint& f, uint32_t width, uint32_t height, uint32_t pitch) {
|
||||
return f.format == DXGI_FORMAT_R8G8B8A8_UNORM && f.width == width && f.height == height && f.depth == 1 &&
|
||||
f.row_pitch == pitch;
|
||||
};
|
||||
const bool mip0 = mips[0].offset == 0 && shape_is(mips[0].footprint, 100, 50, 512) && mips[0].copy_end == 25488 &&
|
||||
rows[0] == 50 && row_bytes[0] == 400;
|
||||
const bool mip1 = mips[1].offset == 25600 && shape_is(mips[1].footprint, 50, 25, 256) && mips[1].copy_end == 31944 &&
|
||||
rows[1] == 25 && row_bytes[1] == 200;
|
||||
if (hr == S_OK && mip0 && mip1 && total == 32256) {
|
||||
checkpoint("xg_xs_texture_computer", Status::Pass,
|
||||
"100x50 RGBA8 two-mip linear footprints and 32256 total bytes match hand-computed values");
|
||||
} else {
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail,
|
||||
"GetResourceLayout hr=0x%08lx mip0_ok=%d mip1_ok=%d total=%llu",
|
||||
static_cast<unsigned long>(hr), mip0, mip1, static_cast<unsigned long long>(total));
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
void* stage_xg_xs() {
|
||||
begin_stage("xg_xs_swizzle_mode");
|
||||
/* D3D12_RESOURCE_DIMENSION_TEXTURE2D / DXGI_FORMAT_R8G8B8A8_UNORM, 256x256, 1 mip, 1 sample. */
|
||||
uint32_t mode_a = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
|
||||
uint32_t mode_b = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
|
||||
if (mode_a == mode_b) {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode is deterministic for identical inputs (mode=%u)", mode_a);
|
||||
if (mode_a == BX_XG_LAYOUT_LINEAR && mode_b == mode_a) {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode suggests linear and is deterministic (mode=%u)", mode_a);
|
||||
} else {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode returned %u then %u for identical inputs", mode_a, mode_b);
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode returned %u then %u, expected linear", mode_a, mode_b);
|
||||
}
|
||||
|
||||
begin_stage("xg_xs_texture_computer");
|
||||
void* computer = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
HRESULT hr = XGCreateTextureComputer(nullptr, &computer);
|
||||
if (computer == reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD))) {
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail, "XGCreateTextureComputer left the out pointer unwritten (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
return nullptr;
|
||||
}
|
||||
report_create("xg_xs_texture_computer", "XGCreateTextureComputer", hr, computer, true);
|
||||
return hr == S_OK ? computer : nullptr;
|
||||
return stage_xg_texture_computer();
|
||||
}
|
||||
|
||||
/* ---- Stage 14: d3d12_xs ------------------------------------------------------------------- */
|
||||
@@ -825,7 +867,12 @@ int main(int argc, char** argv) {
|
||||
/* --- Shutdown (reverse order) ----------------------------------------- */
|
||||
begin_stage("shutdown");
|
||||
release_com(device);
|
||||
release_com(texture_computer);
|
||||
/* The fixture holds the only reference, so this Release must return 0. */
|
||||
ULONG texture_refs = 0;
|
||||
if (texture_computer) {
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(texture_computer);
|
||||
texture_refs = computer->lpVtbl->Release(computer);
|
||||
}
|
||||
release_com(game_input);
|
||||
bool dsp_closed = true;
|
||||
if (dsp) {
|
||||
@@ -841,10 +888,11 @@ int main(int argc, char** argv) {
|
||||
if (runtime_initialized) XGameRuntimeUninitialize();
|
||||
|
||||
LONG faults = InterlockedCompareExchange(&g_error_exceptions, 0, 0);
|
||||
if (dsp_closed && apu_closed && faults == 0) {
|
||||
if (dsp_closed && apu_closed && texture_refs == 0 && faults == 0) {
|
||||
checkpoint("shutdown", Status::Pass, "reverse-order teardown completed with 0 error-severity exceptions");
|
||||
} else {
|
||||
checkpoint("shutdown", Status::Fail, "dsp_closed=%d apu_closed=%d error_exceptions=%ld", dsp_closed, apu_closed, faults);
|
||||
checkpoint("shutdown", Status::Fail, "dsp_closed=%d apu_closed=%d texture_refs=%lu error_exceptions=%ld",
|
||||
dsp_closed, apu_closed, texture_refs, faults);
|
||||
}
|
||||
if (fault_handle) RemoveVectoredExceptionHandler(fault_handle);
|
||||
SetUnhandledExceptionFilter(g_prev_unhandled_filter);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
add_executable(test_win32_bridge main.cpp)
|
||||
target_link_libraries(test_win32_bridge PRIVATE kernel32 user32)
|
||||
add_dependencies(test_win32_bridge
|
||||
psm_appnotify_1_0 psm_appnotify_1_1
|
||||
ntuser_msg_1_0 ntuser_msg_ansi_1_0 ntuser_win_1_0 ntuser_win_ansi_1_0
|
||||
)
|
||||
@@ -0,0 +1,372 @@
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <bit>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr UINT kMessage = WM_APP + 1;
|
||||
constexpr WPARAM kPayload = 42;
|
||||
decltype(&DefWindowProcA) g_def_window_proc;
|
||||
bool g_received_message = false;
|
||||
std::atomic<bool> g_callback_called{false};
|
||||
|
||||
struct ScopedModule {
|
||||
HMODULE handle = nullptr;
|
||||
ScopedModule() = default;
|
||||
explicit ScopedModule(HMODULE h) : handle(h) {}
|
||||
~ScopedModule() {
|
||||
if (handle) {
|
||||
FreeLibrary(handle);
|
||||
}
|
||||
}
|
||||
ScopedModule(const ScopedModule&) = delete;
|
||||
ScopedModule& operator=(const ScopedModule&) = delete;
|
||||
explicit operator bool() const { return handle != nullptr; }
|
||||
HMODULE get() const { return handle; }
|
||||
};
|
||||
|
||||
LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
|
||||
if (message == kMessage) {
|
||||
g_received_message = wparam == kPayload;
|
||||
return 0;
|
||||
}
|
||||
return g_def_window_proc(window, message, wparam, lparam);
|
||||
}
|
||||
|
||||
void CALLBACK notification_callback(BOOLEAN, PVOID) {
|
||||
g_callback_called.store(true);
|
||||
}
|
||||
|
||||
HMODULE load_bridge(const wchar_t* dll) {
|
||||
wchar_t executable[MAX_PATH];
|
||||
const DWORD length = GetModuleFileNameW(nullptr, executable, MAX_PATH);
|
||||
if (!length || length == MAX_PATH) {
|
||||
return nullptr;
|
||||
}
|
||||
const std::wstring path(executable, length);
|
||||
const auto expected = path.substr(0, path.find_last_of(L"\\/") + 1) + dll;
|
||||
HMODULE module = LoadLibraryW(expected.c_str());
|
||||
if (!module) {
|
||||
std::fwprintf(stderr, L"FAIL: could not load built bridge %ls (error %lu)\n",
|
||||
expected.c_str(), GetLastError());
|
||||
return nullptr;
|
||||
}
|
||||
wchar_t actual[MAX_PATH];
|
||||
const DWORD actual_length = GetModuleFileNameW(module, actual, MAX_PATH);
|
||||
if (!actual_length || actual_length == MAX_PATH) {
|
||||
const DWORD err = GetLastError();
|
||||
FreeLibrary(module);
|
||||
std::fwprintf(stderr, L"FAIL: could not query path for bridge %ls (error %lu)\n",
|
||||
expected.c_str(), err);
|
||||
return nullptr;
|
||||
}
|
||||
if (CompareStringOrdinal(expected.c_str(), -1, actual, -1, TRUE) != CSTR_EQUAL) {
|
||||
FreeLibrary(module);
|
||||
std::fwprintf(stderr, L"FAIL: bridge %ls resolved to unexpected path %ls\n",
|
||||
expected.c_str(), actual);
|
||||
return nullptr;
|
||||
}
|
||||
return module;
|
||||
}
|
||||
|
||||
template<typename Function>
|
||||
Function lookup(HMODULE module, const char* name) {
|
||||
return std::bit_cast<Function>(GetProcAddress(module, name));
|
||||
}
|
||||
|
||||
bool test_window() {
|
||||
const ScopedModule window(load_bridge(L"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll"));
|
||||
const ScopedModule window_ansi(load_bridge(L"ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll"));
|
||||
const ScopedModule message(load_bridge(L"ext-ms-win-rtcore-ntuser-message-l1-1-0.dll"));
|
||||
const ScopedModule message_ansi(load_bridge(L"ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll"));
|
||||
if (!window || !window_ansi || !message || !message_ansi) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto show = lookup<decltype(&ShowWindow)>(window.get(), "ShowWindow");
|
||||
const auto create = lookup<decltype(&CreateWindowExA)>(window_ansi.get(), "CreateWindowExA");
|
||||
const auto register_class = lookup<decltype(&RegisterClassExA)>(window_ansi.get(), "RegisterClassExA");
|
||||
g_def_window_proc = lookup<decltype(&DefWindowProcA)>(window_ansi.get(), "DefWindowProcA");
|
||||
const auto translate = lookup<decltype(&TranslateMessage)>(message.get(), "TranslateMessage");
|
||||
const auto peek = lookup<decltype(&PeekMessageA)>(message_ansi.get(), "PeekMessageA");
|
||||
const auto dispatch = lookup<decltype(&DispatchMessageA)>(message_ansi.get(), "DispatchMessageA");
|
||||
if (!show || !create || !register_class || !g_def_window_proc || !translate || !peek || !dispatch) {
|
||||
return false;
|
||||
}
|
||||
|
||||
WNDCLASSEXA cls{};
|
||||
cls.cbSize = sizeof(cls);
|
||||
cls.lpfnWndProc = window_proc;
|
||||
cls.hInstance = GetModuleHandleW(nullptr);
|
||||
cls.lpszClassName = "BetterXenBridgeConformance";
|
||||
if (!register_class(&cls)) {
|
||||
return false;
|
||||
}
|
||||
const HWND hwnd = create(0, cls.lpszClassName, "BetterXen Win32 Bridge", WS_OVERLAPPEDWINDOW,
|
||||
0, 0, 100, 100, nullptr, nullptr, cls.hInstance, nullptr);
|
||||
if (hwnd) {
|
||||
show(hwnd, SW_HIDE);
|
||||
if (!IsWindowVisible(hwnd) && PostMessageA(hwnd, kMessage, kPayload, 0)) {
|
||||
MSG msg{};
|
||||
while (!g_received_message && peek(&msg, hwnd, 0, 0, PM_REMOVE)) {
|
||||
translate(&msg);
|
||||
dispatch(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
const bool destroyed = hwnd && DestroyWindow(hwnd);
|
||||
const bool unregistered = UnregisterClassA(cls.lpszClassName, cls.hInstance);
|
||||
return g_received_message && destroyed && unregistered;
|
||||
}
|
||||
|
||||
using RegisterNotification = ULONG (WINAPI*)(decltype(¬ification_callback), PVOID, PVOID*);
|
||||
using UnregisterNotification = VOID (WINAPI*)(PVOID);
|
||||
|
||||
struct PsmLogCounts {
|
||||
size_t state_registered = 0;
|
||||
size_t constrained_registered = 0;
|
||||
size_t state_unregistered = 0;
|
||||
size_t state_foreign = 0;
|
||||
size_t state_unknown = 0;
|
||||
size_t constrained_unregistered = 0;
|
||||
size_t constrained_foreign = 0;
|
||||
size_t constrained_unknown = 0;
|
||||
};
|
||||
|
||||
int64_t query_file_size(const char* path) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
return 0;
|
||||
}
|
||||
LARGE_INTEGER size{};
|
||||
const bool ok = GetFileSizeEx(f, &size) != 0;
|
||||
CloseHandle(f);
|
||||
return ok && size.QuadPart > 0 ? size.QuadPart : 0;
|
||||
}
|
||||
|
||||
bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts& out) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
std::fprintf(stderr, "FAIL: could not open PSM log %s (error %lu)\n", path, GetLastError());
|
||||
return false;
|
||||
}
|
||||
LARGE_INTEGER size{};
|
||||
if (!GetFileSizeEx(f, &size) || size.QuadPart < start_offset) {
|
||||
CloseHandle(f);
|
||||
std::fprintf(stderr, "FAIL: invalid PSM log size for %s\n", path);
|
||||
return false;
|
||||
}
|
||||
const int64_t delta = size.QuadPart - start_offset;
|
||||
if (delta <= 0 || delta > (64LL << 20)) {
|
||||
CloseHandle(f);
|
||||
std::fprintf(stderr, "FAIL: unexpected PSM log delta (%lld bytes)\n",
|
||||
static_cast<long long>(delta));
|
||||
return false;
|
||||
}
|
||||
LARGE_INTEGER seek{};
|
||||
seek.QuadPart = start_offset;
|
||||
if (!SetFilePointerEx(f, seek, nullptr, FILE_BEGIN)) {
|
||||
CloseHandle(f);
|
||||
return false;
|
||||
}
|
||||
std::string data(static_cast<size_t>(delta), '\0');
|
||||
size_t total_read = 0;
|
||||
while (total_read < data.size()) {
|
||||
DWORD chunk = 0;
|
||||
const DWORD want = static_cast<DWORD>(data.size() - total_read);
|
||||
if (!ReadFile(f, data.data() + total_read, want, &chunk, nullptr) || chunk == 0) {
|
||||
break;
|
||||
}
|
||||
total_read += chunk;
|
||||
}
|
||||
CloseHandle(f);
|
||||
data.resize(total_read);
|
||||
|
||||
size_t pos = 0;
|
||||
while (pos < data.size()) {
|
||||
size_t nl = data.find('\n', pos);
|
||||
if (nl == std::string::npos) {
|
||||
nl = data.size();
|
||||
}
|
||||
const std::string line = data.substr(pos, nl - pos);
|
||||
pos = nl + 1;
|
||||
|
||||
if (line.find("\"sub\":\"win32_bridge\"") == std::string::npos) {
|
||||
continue;
|
||||
}
|
||||
if (line.find("\"event\":\"RegisterAppStateChangeNotification\"") != std::string::npos &&
|
||||
line.find("\"detail\":\"registered_offline\"") != std::string::npos) {
|
||||
++out.state_registered;
|
||||
} else if (line.find("\"event\":\"RegisterAppConstrainedChangeNotification\"") != std::string::npos &&
|
||||
line.find("\"detail\":\"registered_offline\"") != std::string::npos) {
|
||||
++out.constrained_registered;
|
||||
} else if (line.find("\"event\":\"UnregisterAppStateChangeNotification\"") != std::string::npos) {
|
||||
if (line.find("\"detail\":\"unregistered\"") != std::string::npos) {
|
||||
++out.state_unregistered;
|
||||
} else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) {
|
||||
++out.state_foreign;
|
||||
} else if (line.find("\"detail\":\"unknown_token\"") != std::string::npos) {
|
||||
++out.state_unknown;
|
||||
}
|
||||
} else if (line.find("\"event\":\"UnregisterAppConstrainedChangeNotification\"") != std::string::npos) {
|
||||
if (line.find("\"detail\":\"unregistered\"") != std::string::npos) {
|
||||
++out.constrained_unregistered;
|
||||
} else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) {
|
||||
++out.constrained_foreign;
|
||||
} else if (line.find("\"detail\":\"unknown_token\"") != std::string::npos) {
|
||||
++out.constrained_unknown;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool test_psm() {
|
||||
char log_path[MAX_PATH]{};
|
||||
bool created_temp_log = false;
|
||||
const DWORD existing_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
if (existing_len == 0 || existing_len >= sizeof(log_path)) {
|
||||
char temp_dir[MAX_PATH]{};
|
||||
const DWORD dir_len = GetTempPathA(sizeof(temp_dir), temp_dir);
|
||||
if (dir_len == 0 || dir_len >= sizeof(temp_dir) ||
|
||||
GetTempFileNameA(temp_dir, "bxp", 0, log_path) == 0) {
|
||||
std::fprintf(stderr, "FAIL: could not create temporary PSM log file\n");
|
||||
return false;
|
||||
}
|
||||
if (!SetEnvironmentVariableA("BX_LOG_FILE", log_path)) {
|
||||
DeleteFileA(log_path);
|
||||
return false;
|
||||
}
|
||||
created_temp_log = true;
|
||||
}
|
||||
const int64_t log_start_offset = query_file_size(log_path);
|
||||
|
||||
bool ok = false;
|
||||
{
|
||||
const ScopedModule state_dll(load_bridge(L"api-ms-win-core-psm-appnotify-l1-1-0.dll"));
|
||||
const ScopedModule constrained_dll(load_bridge(L"api-ms-win-core-psm-appnotify-l1-1-1.dll"));
|
||||
if (state_dll && constrained_dll) {
|
||||
const auto register_state = lookup<RegisterNotification>(
|
||||
state_dll.get(), "RegisterAppStateChangeNotification");
|
||||
const auto unregister_state = lookup<UnregisterNotification>(
|
||||
state_dll.get(), "UnregisterAppStateChangeNotification");
|
||||
const auto register_constrained = lookup<RegisterNotification>(
|
||||
constrained_dll.get(), "RegisterAppConstrainedChangeNotification");
|
||||
const auto unregister_constrained = lookup<UnregisterNotification>(
|
||||
constrained_dll.get(), "UnregisterAppConstrainedChangeNotification");
|
||||
if (register_state && unregister_state && register_constrained && unregister_constrained) {
|
||||
PVOID token = reinterpret_cast<PVOID>(1);
|
||||
PVOID token2 = reinterpret_cast<PVOID>(1);
|
||||
const bool args_ok =
|
||||
register_state(nullptr, nullptr, &token) == ERROR_INVALID_PARAMETER && !token &&
|
||||
register_state(notification_callback, nullptr, nullptr) == ERROR_INVALID_PARAMETER &&
|
||||
register_constrained(nullptr, nullptr, &token2) == ERROR_INVALID_PARAMETER && !token2 &&
|
||||
register_constrained(notification_callback, nullptr, nullptr) == ERROR_INVALID_PARAMETER;
|
||||
|
||||
constexpr size_t kThreads = 4;
|
||||
constexpr size_t kRegistrationsPerThread = 16;
|
||||
constexpr size_t kPerFamily = kThreads * kRegistrationsPerThread;
|
||||
struct Tokens {
|
||||
PVOID state{};
|
||||
PVOID constrained{};
|
||||
};
|
||||
std::array<std::array<Tokens, kRegistrationsPerThread>, kThreads> tokens{};
|
||||
std::array<std::thread, kThreads> workers;
|
||||
std::atomic<bool> success{args_ok};
|
||||
for (size_t i = 0; i < workers.size(); ++i) {
|
||||
workers[i] = std::thread([&, i] {
|
||||
for (auto& entry : tokens[i]) {
|
||||
const auto state_status =
|
||||
register_state(notification_callback, &entry, &entry.state);
|
||||
const auto constrained_status =
|
||||
register_constrained(notification_callback, &entry, &entry.constrained);
|
||||
if (state_status != ERROR_SUCCESS || constrained_status != ERROR_SUCCESS ||
|
||||
!entry.state || !entry.constrained) {
|
||||
success.store(false);
|
||||
}
|
||||
// Cross-family unregister calls must log foreign_token and leave live tokens intact.
|
||||
unregister_constrained(entry.state);
|
||||
unregister_state(entry.constrained);
|
||||
// Valid unregister followed by duplicate unregister on each family.
|
||||
unregister_state(entry.state);
|
||||
unregister_state(entry.state);
|
||||
unregister_constrained(entry.constrained);
|
||||
unregister_constrained(entry.constrained);
|
||||
}
|
||||
});
|
||||
}
|
||||
for (auto& worker : workers) {
|
||||
worker.join();
|
||||
}
|
||||
|
||||
// Null and arbitrary invalid tokens must classify as unknown_token, not foreign_token.
|
||||
unregister_state(nullptr);
|
||||
unregister_constrained(reinterpret_cast<PVOID>(0x1234));
|
||||
|
||||
std::unordered_set<PVOID> seen;
|
||||
bool unique_ok = true;
|
||||
for (const auto& entries : tokens) {
|
||||
for (const auto& entry : entries) {
|
||||
if (!seen.insert(entry.state).second ||
|
||||
!seen.insert(entry.constrained).second) {
|
||||
unique_ok = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PsmLogCounts counts{};
|
||||
const bool log_read_ok = count_psm_log_events(log_path, log_start_offset, counts);
|
||||
const bool counts_ok = log_read_ok &&
|
||||
counts.state_registered == kPerFamily &&
|
||||
counts.constrained_registered == kPerFamily &&
|
||||
counts.state_unregistered == kPerFamily &&
|
||||
counts.state_foreign == kPerFamily &&
|
||||
counts.state_unknown == kPerFamily + 1 &&
|
||||
counts.constrained_unregistered == kPerFamily &&
|
||||
counts.constrained_foreign == kPerFamily &&
|
||||
counts.constrained_unknown == kPerFamily + 1;
|
||||
if (log_read_ok && !counts_ok) {
|
||||
std::fprintf(
|
||||
stderr,
|
||||
"FAIL: PSM log count mismatch: state(reg=%zu unreg=%zu foreign=%zu unknown=%zu) "
|
||||
"constrained(reg=%zu unreg=%zu foreign=%zu unknown=%zu)\n",
|
||||
counts.state_registered, counts.state_unregistered,
|
||||
counts.state_foreign, counts.state_unknown,
|
||||
counts.constrained_registered, counts.constrained_unregistered,
|
||||
counts.constrained_foreign, counts.constrained_unknown);
|
||||
}
|
||||
|
||||
ok = success.load() && unique_ok && !g_callback_called.load() && counts_ok;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (created_temp_log) {
|
||||
DeleteFileA(log_path);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
if (!test_window()) {
|
||||
std::fprintf(stderr, "FAIL: Win32 bridge window or message pump (error %lu)\n", GetLastError());
|
||||
return 1;
|
||||
}
|
||||
if (!test_psm()) {
|
||||
std::fprintf(stderr, "FAIL: PSM bridge registration lifecycle\n");
|
||||
return 2;
|
||||
}
|
||||
std::puts("PASS: test_win32_bridge (hidden window, message pump, 128 PSM registrations, per-event log verified)");
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_xmem_physical main.cpp)
|
||||
target_include_directories(test_xmem_physical PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_xmem_physical PRIVATE xmem kernel32)
|
||||
@@ -0,0 +1,148 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
extern "C" {
|
||||
PVOID WINAPI XMemAllocDefault(SIZE_T, uint64_t);
|
||||
VOID WINAPI XMemFreeDefault(PVOID, uint64_t);
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
|
||||
BOOL WINAPI XMemFreePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID, SIZE_T, uint64_t, PULONG_PTR);
|
||||
PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID, SIZE_T, uint64_t, PULONG_PTR);
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
}
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
std::fprintf(stderr, "xmem physical:%d: %s (Win32 error %lu)\n", \
|
||||
__LINE__, #condition, static_cast<unsigned long>(GetLastError())); \
|
||||
return false; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
bool check_aliases(SIZE_T page_size, uint64_t flags) {
|
||||
bx_xmem_stats_t stats{};
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
CHECK(stats.allocated_physical_bytes == 0);
|
||||
|
||||
SIZE_T count = 2;
|
||||
ULONG_PTR pages[2]{};
|
||||
// Invalid flags must be rejected cleanly before touching stats or tags.
|
||||
CHECK(!XMemAllocatePhysicalPages(&count, pages, 0x12345));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
CHECK(XMemAllocatePhysicalPages(&count, pages, flags));
|
||||
CHECK(count == 2 && pages[0] && pages[1] && pages[0] != pages[1]);
|
||||
|
||||
// Working-set statistics and internal stats must both reflect physical pages.
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == count * page_size);
|
||||
CHECK(stats.peak_committed_bytes >= count * page_size);
|
||||
bx_xmem_stats_t ws_stats{};
|
||||
CHECK(XMemGetWorkingSetStatistics(&ws_stats, sizeof(ws_stats)));
|
||||
CHECK(ws_stats.allocated_physical_bytes == count * page_size);
|
||||
|
||||
// Shared title budget cap: existing physical pages must block both full-cap
|
||||
// physical and full-cap heap allocations without allocating gigabytes.
|
||||
SIZE_T cap_pages = static_cast<SIZE_T>(stats.title_limit_bytes / page_size);
|
||||
CHECK(!XMemAllocatePhysicalPages(&cap_pages, pages, flags));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
CHECK(!XMemAllocDefault(static_cast<SIZE_T>(stats.title_limit_bytes), 0));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == count * page_size);
|
||||
|
||||
CHECK(!XMemMapPhysicalPages(nullptr, count, 0x12345, pages));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
auto* linear = static_cast<BYTE*>(XMemMapPhysicalPages(nullptr, count, flags, pages));
|
||||
CHECK(linear && reinterpret_cast<uintptr_t>(linear) % page_size == 0);
|
||||
ULONG_PTR reversed[] = {pages[1], pages[0]};
|
||||
auto* scatter = static_cast<BYTE*>(
|
||||
XMemMapPhysicalPagesScatter(nullptr, count, flags, reversed));
|
||||
CHECK(scatter && scatter != linear && reinterpret_cast<uintptr_t>(scatter) % page_size == 0);
|
||||
|
||||
linear[7] = 0x41;
|
||||
linear[page_size + 7] = 0x73;
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
scatter[page_size + 30] = 0xf2;
|
||||
CHECK(linear[30] == 0xf2);
|
||||
|
||||
// Duplicate tags are valid when mapping (intra-span ring-buffer/tile aliasing).
|
||||
ULONG_PTR dup_map[] = {pages[0], pages[0]};
|
||||
auto* dup_view = static_cast<BYTE*>(
|
||||
XMemMapPhysicalPagesScatter(nullptr, count, flags, dup_map));
|
||||
CHECK(dup_view && reinterpret_cast<uintptr_t>(dup_view) % page_size == 0);
|
||||
dup_view[13] = 0x9b;
|
||||
CHECK(dup_view[page_size + 13] == 0x9b && linear[13] == 0x9b);
|
||||
bx_xmem_region_info_t dup0{};
|
||||
bx_xmem_region_info_t dup1{};
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view), &dup0));
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view + page_size), &dup1));
|
||||
CHECK(dup0.physical_tag == pages[0] && dup1.physical_tag == pages[0]);
|
||||
CHECK(XMemMapPhysicalPagesScatter(dup_view, count, flags, nullptr) == dup_view);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view), &dup0));
|
||||
|
||||
bx_xmem_region_info_t first{};
|
||||
bx_xmem_region_info_t alias{};
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear + 7), &first));
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter + page_size + 7), &alias));
|
||||
CHECK(first.base_va == reinterpret_cast<uintptr_t>(linear));
|
||||
CHECK(alias.base_va == reinterpret_cast<uintptr_t>(scatter + page_size));
|
||||
CHECK(alias.physical_tag == first.physical_tag && first.physical_tag == pages[0]);
|
||||
CHECK(first.size_bytes == page_size && alias.page_size_bytes == page_size);
|
||||
CHECK(first.protect_flags == PAGE_READWRITE && first.mem_type_flags == MEM_MAPPED);
|
||||
|
||||
// Rejected frees (stale or duplicate tags) must fail without modifying
|
||||
// page_array or disturbing live mappings.
|
||||
ULONG_PTR stale[] = {pages[0], 0};
|
||||
CHECK(!XMemFreePhysicalPages(&count, stale, flags));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && stale[0] == pages[0] && stale[1] == 0);
|
||||
CHECK(linear[7] == 0x41);
|
||||
ULONG_PTR dup_free[] = {pages[0], pages[0]};
|
||||
CHECK(!XMemFreePhysicalPages(&count, dup_free, flags));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER
|
||||
&& dup_free[0] == pages[0] && dup_free[1] == pages[0]);
|
||||
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
|
||||
|
||||
CHECK(!XMemMapPhysicalPagesScatter(nullptr, count, flags, stale));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
CHECK(!XMemMapPhysicalPages(linear, count, flags, pages));
|
||||
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
|
||||
|
||||
// Partial/over-wide unmap must fail cleanly and leave mapped pages intact.
|
||||
CHECK(!XMemMapPhysicalPagesScatter(scatter, count + 1, flags, nullptr));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
|
||||
// Exact unmap succeeds; repeating unmap on the now-empty span must fail.
|
||||
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr) == scatter);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(!XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, reversed) == scatter);
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
CHECK(XMemFreePhysicalPages(&count, pages, flags));
|
||||
CHECK(!pages[0] && !pages[1]);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear), &first));
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(!XMemMapPhysicalPages(nullptr, count, flags, reversed));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
int main() {
|
||||
if (!check_aliases(64 * 1024, 0) || !check_aliases(2 * 1024 * 1024, 2 * 1024 * 1024)) {
|
||||
return 1;
|
||||
}
|
||||
std::puts("test_xmem_physical: passed");
|
||||
}
|
||||
Reference in new issue
Block a user