mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 01:51:11 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c512afb2b | ||
|
|
d2ad5808ab | ||
|
|
66804f25b4 | ||
|
|
f34750f353 | ||
|
|
fadd742e63 | ||
|
|
d0d10c97cf | ||
|
|
25ba80e1eb | ||
|
|
78be10c187 | ||
|
|
9713018db6 | ||
|
|
7451f0f2ae | ||
|
|
1beef47c6f | ||
|
|
6ff97b98ec | ||
|
|
53c4380b3e | ||
|
|
c1e958194c | ||
|
|
1be97f2536 | ||
|
|
a9d7bc000b | ||
|
|
b9469aa22d | ||
|
|
bba0851e44 |
No files matched your search
@@ -31,7 +31,7 @@ jobs:
|
||||
test "$(sysctl -n sysctl.proc_translated)" = 0
|
||||
- name: Install Rust toolchain
|
||||
run: |
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy --target x86_64-pc-windows-gnu
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
|
||||
rustc -vV
|
||||
- name: Check ARM64 Rust workspace (launcher + shader-transpiler)
|
||||
run: |
|
||||
@@ -42,6 +42,10 @@ jobs:
|
||||
binary=target/aarch64-apple-darwin/debug/bx-cli
|
||||
file "$binary"
|
||||
test "$(lipo -archs "$binary")" = arm64
|
||||
- name: Check hybrid script syntax (no CrossOver on the runner, nothing launched)
|
||||
run: |
|
||||
for script in scripts/hybrid/*.sh tests/conformance/test_*/build.sh; do sh -n "$script"; done
|
||||
python3 -c 'import ast, glob; [ast.parse(open(f).read(), f) for f in glob.glob("scripts/hybrid/*.py") + glob.glob("tests/conformance/test_*/*.py")]'
|
||||
- name: Install mingw-w64 and CMake
|
||||
env:
|
||||
HOMEBREW_NO_AUTO_UPDATE: 1
|
||||
|
||||
@@ -4,9 +4,9 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
|
||||
|
||||
---
|
||||
|
||||
## 0. Contributor & Agent Task Dispatch (Onboarding & Priority Order)
|
||||
## 0. First-Time Contributor Onboarding
|
||||
|
||||
Whenever a user points their agent at BetterXen to contribute, get started, or pick work (even with a short prompt like *"help me contribute"* or *"what should we work on?"*), walk through preflight and then select work in the **strict 3-tier priority order** below:
|
||||
If the user asks to contribute, get started, or pick a task (even with a short prompt like *"help me contribute"*), walk them through this exact end-to-end flow:
|
||||
|
||||
1. **Preflight host & tools:**
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
|
||||
@@ -14,33 +14,21 @@ Whenever a user points their agent at BetterXen to contribute, get started, or p
|
||||
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
|
||||
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
|
||||
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
|
||||
2. **Select work in strict priority order:**
|
||||
- **Priority 1 (Highest) — Handle your own claimed PRs with requested changes or review feedback:**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,reviews,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
Inspect comments and reviews (`gh pr view <pr> --repo MacosPorters/betterxen --comments` and `gh api repos/MacosPorters/betterxen/pulls/<pr>/comments`). If any of the user's open/claimed PRs has `CHANGES_REQUESTED`, unresolved reviewer feedback, failing CI, or merge conflicts, **address that PR first before starting new work**: check out the PR branch, resolve every review item, re-run Section 8 checks, push the DCO-signed update (with the user's authorization, per Section 7), and summarize how each comment was addressed.
|
||||
- **Priority 2 — Pick an unclaimed open issue:**
|
||||
If Priority 1 is clear, query open issues (preferring `status: ready` in the active milestone, then other actionable open issues):
|
||||
2. **Discover & pick an unclaimed issue:**
|
||||
- Query ready issues in the active milestone:
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
|
||||
gh issue list --repo MacosPorters/betterxen --state open --json number,title,labels,assignees
|
||||
```
|
||||
Inspect comments and open PRs on candidate issues to filter out any issue with an active claim (< 7 days old) or open PR. Present the unclaimed options in plain English (recommending 1–2 good matches) and confirm with the user before coding.
|
||||
- **Priority 3 — Review & independently verify open PRs needing review:**
|
||||
When Priority 1 is clear and no unclaimed open issues remain (or the user asks to help unblock the queue), query open non-draft PRs by other contributors that still need review/verification:
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,headRefName,reviewDecision,isDraft
|
||||
```
|
||||
Fetch a candidate PR (`reviewDecision` empty or `REVIEW_REQUIRED`) into an isolated worktree, independently verify its contract and implementation per Section 5, run the Section 8 checks locally (including live CrossOver / D3DMetal runs where available), and draft an honest evidence-backed review for user approval before posting.
|
||||
3. **Claim & isolate (for Priority 2 issue work):**
|
||||
- Inspect comments and open PRs on candidate issues to filter out any issue that already has an active claim (< 7 days old).
|
||||
- Present the unclaimed options in plain English (recommending 1–2 good starting issues matching the user's background) and wait for the user to choose one before coding.
|
||||
3. **Claim & isolate:**
|
||||
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
|
||||
4. **Implement strictly in scope:**
|
||||
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
|
||||
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
|
||||
5. **Verify locally (including hosts without CrossOver):**
|
||||
- Run every command in Section 8 and fix all warnings/failures before stopping.
|
||||
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (cross-compiling the 16 mingw-w64 C++ shim DLLs, building the Rust `bx_shader_bridge.dll` with `cargo`, and verifying the exact exports of all 17 PE32+ DLLs), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
|
||||
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (verifying all 16 PE32+ DLLs and exact exports), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
|
||||
6. **Review & submit PR:**
|
||||
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
|
||||
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
|
||||
@@ -76,8 +64,8 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
|
||||
| **Track F** | `tests/conformance/`, `docs/` | Synthetic PE32+ conformance tests, integration fixture, benchmarks, documentation |
|
||||
|
||||
### Cross-Track `[ABI]` Rule
|
||||
- For issue-claimed contributor work, stay inside your issue's track directory; if your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first so provider and consumer tracks can implement in parallel.
|
||||
- Maintainer-directed compatibility and startup-unblocking tasks may touch the required shim and `tests/conformance/` directories across tracks without a pre-existing issue claim. They must not overlap another contributor's active claim or open PR without that contributor's or a maintainer's recorded agreement, any new cross-DLL helper or export still goes through an `abi/`-only `[ABI]` PR first, and independent review (Section 5) still applies.
|
||||
- Never edit another track's directory inside a feature PR.
|
||||
- If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both provider and consumer tracks implement against the frozen contract in parallel.
|
||||
- When adding a new conformance test, create `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories without editing `tests/conformance/CMakeLists.txt`.
|
||||
|
||||
---
|
||||
@@ -95,7 +83,7 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
|
||||
|
||||
- Before integrating or copying any third-party code: verify the **per-file** license (not just repository metadata), confirm compatibility with `GPL-3.0-or-later` and every selected component, preserve copyright notices, record the upstream repository and exact commit/version, document modifications, and record the entry in `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved.
|
||||
- Never bundle, modify, or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Never bypass licensing or activation requirements of any dependency.
|
||||
- **Provenance first:** Exclude anything (code, data, documentation, or observations) derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds (including VIctory, PE-Vulkan, KyTx, AnyPS5, and similar efforts) are never adopted as code, shader, asset, or tooling sources without a recorded per-file provenance and license audit. Game-specific patches, asset-specific workarounds, and decryption-related code are never adopted; general Xbox Game OS, Direct3D, DirectStorage, and runtime ABI contracts established from project-authorized builds that meet every Section 6 condition are in-scope compatibility work.
|
||||
- **Provenance first:** Exclude anything derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds (including VIctory, PE-Vulkan, KyTx, AnyPS5, and similar efforts) are never adopted as code, shader, asset, or tooling sources without a recorded per-file provenance and license audit. Game-specific, asset-specific, and decryption-related code is never adopted.
|
||||
|
||||
---
|
||||
|
||||
@@ -109,32 +97,26 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
|
||||
|
||||
---
|
||||
|
||||
## 6. Compatibility Evidence & Legal Boundaries
|
||||
## 6. Legal & Clean-Room Rules
|
||||
|
||||
- **Authorized compatibility evidence:** Contributors and agents may use publicly accessible documentation, publicly licensed software, synthetic workloads, and **project-authorized target builds** (via local call-site inspection and runtime diagnostics) to establish undocumented Xbox OS, graphics, memory, storage, and runtime ABI contracts (struct layouts, flags, COM IIDs, vtable slot orders, and expected return/error semantics). Separate direct observations from inferences and verify every implemented contract with a synthetic conformance test under `tests/conformance/`. Such a test shows that a shim matches the recorded inference, not that the inference is correct.
|
||||
- **Conditions for target builds:** A build is project-authorized only when a maintainer has approved it for compatibility research **and all** of the following hold. Approval is an additional condition, never a substitute: it cannot grant access or license rights that the project does not hold.
|
||||
- The person inspecting it obtained it lawfully.
|
||||
- Its license terms and applicable law permit the inspection performed.
|
||||
- It is not leaked, stolen, confidential, or otherwise distributed without authorization, and neither are the tools used on it.
|
||||
- Inspecting it requires no decryption and no circumvention of security, DRM, licensing, or activation controls.
|
||||
|
||||
If any condition is unknown, do not use the build. State in the PR which contracts come from target-build observation, without naming the title or build.
|
||||
- **Never obtain or use** leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or unauthorized game builds and shader collections. Maintainer approval does not change this.
|
||||
- **Repository & clean-tree boundary:** Never commit or paste proprietary executables, SDKs, confidential vendor documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, proprietary shaders, raw caller memory dumps, executable contents/addresses, private traces, proprietary file names or hashes, personal paths, or secrets into the repository, its Git history, commit messages, issues, or PR descriptions.
|
||||
- Use only publicly accessible documentation, publicly licensed software, and authorized synthetic workloads. Never obtain, paste, or commit leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds and shader collections.
|
||||
- **Legal boundary (`docs/legal.md`):** BetterXen does not circumvent console security or DRM and does not load encrypted or protected content. Validate technical compatibility and safety of user-provided files; do not ask for ownership receipts, accounts, or acquisition provenance as part of file loading.
|
||||
- Never place restricted material, personal paths, or secrets in the repository or its Git history.
|
||||
|
||||
---
|
||||
|
||||
## 7. Claiming, Git Safety & Changelog
|
||||
|
||||
1. **Check before coding (open backlog issues):** When picking an unclaimed backlog issue, read every comment and check open PRs so you never claim over an active claim; reply `Claiming — branch: track-<a..f>/<issue>-<slug>` (stale after 7 days without commits/PR). Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
|
||||
2. **Isolate with branches or worktrees:**
|
||||
1. **Check before coding:** Read every comment on the issue and check open PRs. Never claim over an active claim.
|
||||
2. **Claim in plain text:** Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue (earliest claim wins; stale after 7 days without commits/PR).
|
||||
3. **Isolate with branches or worktrees:**
|
||||
```sh
|
||||
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
|
||||
```
|
||||
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
|
||||
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user; never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
5. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
|
||||
4. **Link & sign off:** Put `Closes #<issue>` in the PR description and sign off every commit (`git commit -s`, DCO).
|
||||
5. **Git safety:** Never commit, push, or change remote visibility without explicit user authorization. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
6. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
|
||||
7. **Subagent reasoning:** When spawning helper subagents in automated workflows, keep subagent reasoning effort low unless the user explicitly asks otherwise.
|
||||
|
||||
---
|
||||
|
||||
@@ -147,9 +129,8 @@ cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli # must print: arm64
|
||||
|
||||
# 2. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust bx_shader_bridge.dll, and
|
||||
# build the auto-discovered conformance EXEs
|
||||
# (strictly verifies all 17 .edata Export Directories: names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
|
||||
# 2. Cross-compile all 16 x86-64 PE32+ shim DLLs + auto-discovered conformance EXEs
|
||||
# (strictly verifies .edata Export Directory names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
|
||||
scripts/build-shims.sh
|
||||
|
||||
# 3. Live synthetic PE32+ conformance tests inside CrossOver 26.3 + Rosetta 2
|
||||
@@ -160,20 +141,3 @@ target/debug/bx-cli trace /tmp/bx-test.jsonl
|
||||
# 4. Repository Markdown link & hygiene check
|
||||
python3 scripts/audit/docs_hygiene.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. AI Agent Efficiency & Resource Management
|
||||
|
||||
These rules apply to every coding agent, whatever its model, vendor or plan. Saving resources never justifies skipping necessary verification, fabricating or assuming results, weakening a security, legal or provenance safeguard, or bypassing independent review. Where this section and Sections 4–8 appear to conflict, Sections 4–8 win.
|
||||
|
||||
- **Spend in proportion:** Keep token consumption, API usage, reasoning effort and compute cost as low as correctness allows.
|
||||
- **Reuse what is still valid:** Reuse conversation context, repository knowledge, review findings and verification evidence. Evidence is valid only for the revision and environment it was recorded on; re-run whatever a later change could affect.
|
||||
- **Read narrowly:** Inspect relevant files and incremental diffs instead of rescanning the repository. Batch independent tool calls and GitHub API requests where practical.
|
||||
- **Delegate sparingly:** Avoid unnecessary subagents, duplicate investigations and overlapping responsibilities. Independent review (Section 5) is not duplicate work.
|
||||
- **Reasoning effort:** Default to low for routine tasks and for helper subagents; raise it only when technical complexity justifies it or the user asks.
|
||||
- **Verify without redundancy:** Use targeted checks while iterating and for small changes. This does not replace Section 8 or required CI. Do not repeat builds, tests or CI runs when nothing relevant has changed, and do not poll workflows repeatedly.
|
||||
- **Communicate concisely:** Report outcomes, blockers and what is needed next; skip lengthy status reports and repeated summaries.
|
||||
- **Blocked work:** Do not re-review an unchanged PR that is waiting on an unresolved external blocker.
|
||||
- **Finish authorized work:** Carry an authorized task through to completion, including a merge that is authorized and meets every required approval and check, instead of stopping at intermediate reports. This grants no permission beyond Section 7.
|
||||
- **Escalate real uncertainty:** Raise genuine doubt about ABI compatibility, memory safety, concurrency, security, GPU synchronization, licensing or architecture with a maintainer rather than guessing.
|
||||
+14
-78
@@ -9,76 +9,23 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Fixed
|
||||
- Fixed `bx-cli stop` failing on an idle environment, leaving its session marker in place: `wineserver -k` exits 1 when no server is running.
|
||||
- `bx-cli run` again configures the shim overrides from `build-shims/bin` when `--shims` is not given, as `main` does.
|
||||
- `bx-cli run --log` now prints the trace summary to stderr when the run ends, leaving the JSON record alone on stdout (#408).
|
||||
- `bx-cli run` and `bench` now refuse a CrossOver build they have not been run against unless `--allow-untested-crossover` is given, and records carry `crossover_build_tested`. The notices record the contributor work carried from #405.
|
||||
- Fixed `bx-cli run --bottle` losing DLL overrides, including those set for `--shims`: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll`. A requested `--backend` is also passed with `--env`, so a backend saved in the bottle's settings no longer replaces it. First found by jelly013 on #425.
|
||||
- Fixed unattended crash handling in new test bottles: `create-test-bottle.py` now turns off Wine's crash dialog, which otherwise waits for a click until the run times out (observed: timeout at 240 s with the dialog, 2.8 s without).
|
||||
- The acceptance suite now soaks Direct3D 12 as well as the Direct3D 11 control. One D3D11 soak stalled on a GPU event query after 9,183 frames; three reruns passed and the cause is unknown.
|
||||
|
||||
### Added
|
||||
- `XCRDAPI.dll!DStorageGetFactory` serves the public PC DirectStorage interfaces from Microsoft's MIT-licensed `dstorage.h` (SDK 1.4.0, vendored unmodified in `shims/xcrdapi/dstorage/`) over the existing queue engine: `IDStorageFactory`/`IDStorageFactory1`, `IDStorageFile`, `IDStorageQueue`…`IDStorageQueue4` and `IDStorageStatusArray` (#483). An unknown IID is logged with its value (`dstorage_get_factory_unknown_iid`) next to `BX_STUB_LOG`, so `bx-cli trace` names the interface a guest asked for. The synthetic `bx::storage` interfaces are unchanged. MinGW ignores the header's `__declspec(uuid)`, so `shims/xcrdapi/dstorage_mingw.h` restates its IIDs, generated from the header; the test checks `IDStorageFactory`'s IID against an independently typed value.
|
||||
- **Behaviour, from the header's documentation:** queue capacity 128–8192 (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`) with capacity − 1 usable slots, priority and source type checked at creation, automatic submission at half capacity, a full queue makes `EnqueueRequest` wait for a slot, status entries scoped to the requests since the previous one, and `IsComplete == (GetHResult != E_PENDING)`. The `void` enqueue methods report a rejected command in queue order: a rejected request feeds the next status entry, and every rejection reaches the error event and `RetrieveErrorRecord` (`FailureCount`, `FirstFailure.HResult`, `FirstFailure.CommandType`; per-command parameters stay zeroed).
|
||||
- **Supported:** uncompressed file or memory sources into memory or buffer destinations. A buffer destination needs a queue device.
|
||||
- **Not implemented, logged with `BX_VTABLE_STUB_LOG`:** GDeflate, Zstandard and custom compression (`E_NOTIMPL`; `GetCompressionSupport` reports none), GACL shuffle transforms, texture, subresource and tile destinations, fence-synchronized `EnqueueRequests`, `CancelRequestsWithTag` (requests still run) and the debug layer. `SetStagingBufferSize` returns `S_OK` and logs that it has no effect. `Close` drains what was already submitted.
|
||||
- **Not included:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source. Provenance is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
|
||||
- **Test:** `test_xcrdapi` gains public-interface checks whose expected values come from the header and `dstorageerr.h`: factory IIDs and identity, capacity and priority limits, `Query`/`Query1` counts, file and memory reads, rejection ordering and error records, unsupported shapes, auto-submission without `Submit`, 384 requests through a 127-slot queue, `Close`, and a memory-to-upload-buffer copy on a D3D12 device.
|
||||
- `bx-d3dmetal-harness` now judges the reported shader model: `judge()` requires `shader_model >= 0x66` for `Verdict::Pass` (#567). The field was parsed and printed but never judged, so a device below 6.6 — or a report with no `shader_model` record — passed on a matching readback alone, even though every kernel the harness runs is SM 6.6. A lower model returns the new `Verdict::UnsupportedShaderModel`; a missing record returns `Incomplete`. The live Rust test asserted this, but the standalone `bx-d3dmetal-harness run` verdict did not. Negative unit tests with `0x65`, `0x60`, and the record removed fail on the previous implementation. The live D3DMetal test remains `#[ignore]`d (no user-supplied framework on this host); 23/23 harness unit tests pass.
|
||||
- `bx-cli run` now propagates the guest's numeric exit code instead of collapsing every nonzero status to 1 (#565). `Outcome::exit_code` returned `u8::from(!status.success())`, so a conformance fixture's documented **exit 77** skip (see #563) arrived as 1 and was indistinguishable from a failure; a `case $status in 77)` recorder could never fire. Timeout (124) and signal (128+N) codes are unchanged, a failed cleanup or misplaced staging still turns success into failure with `code.max(1)`, and a signalled guest still has no code. `classifies_exit_timeout_and_signal` now asserts 7 for `exit 7` and 77 for `exit 77`; it previously asserted 1 for `exit 7`, which is why the collapse was invisible. No CrossOver run was needed for the tests that ran; live `bx-cli run` under CrossOver was not performed on this host.
|
||||
- ADR 0005 now points at `docs/progress.md` **at tag `native-first-final`** rather than a bare path that no longer exists on `main` (#569). The file was deleted with the native workspace (`30e551a`) and survives only at that tag, which ADR 0006 makes the canonical archive. The ADR's meaning is unchanged: no hybrid capability is claimed, and every listed item remains synthetic evidence. `docs_hygiene.py` cannot catch this class of error because it validates Markdown links only, and this reference is inline code.
|
||||
- Placed resources created via `CreatePlacedResource` retain the shim heap's budget charge until their final release. The D3D12 backing map returned in `cpu_pointer` expires when the region changes or another host device replaces the cache. Concurrent device creations wait for both proxy hooks to be installed (#464).
|
||||
- `D3D12ConfigureVirtualMemoryX` copies a BetterXen version-1 block only when the first 8 bytes are magic `BXVM` (`0x4D565842`) and the struct size. The caller's pointer is not kept. `cpu_pointer` is written only before that call returns (the current persistent map, or 0). After `CreateHeap` builds the backing heap, a second call with the same region reads the map and does not recreate the heap. `CreateHeap` returns that one `WRITE_BACK` / `L0` heap only when the block sets `BX_D3D12_VMEM_FLAG_BACKING_HEAP` and the desc is `CUSTOM`, `WRITE_BACK`, `L0`, `D3D12_HEAP_FLAG_NONE`, alignment 0 or 64 KiB, node masks 0 or 1, and the configured size. Every other `CreateHeap` forwards the desc unchanged and returns the host `HRESULT`, wrapped so the live-heap charge against the xmem title budget is credited on the final `Release` (`E_OUTOFMEMORY` only when that budget is exceeded). The wrapper answers `ID3D12Heap1` when the host heap does. `CreatePlacedResource` on any other heap forwards the placement parameters to the host. On the backing heap the offset must be a multiple of the alignment `GetResourceAllocationInfo` reports and the resource must fit. A null output pointer on `CreateHeap` or `CreatePlacedResource` is forwarded to the host with no budget charge and no wrapper. `GetDevice` on every heap wrapper returns the `BxDeviceProxy`. An ordinary heap `AddRef`s that proxy until the wrapper's final `Release`, matching `BxChildProxy`, so the caller can release the device and keep the heap. The process-wide backing heap does not: the cache would keep the device and its budget charge alive. Its pointer is weak. It is cleared when that heap leaves the cache, including a region change or a different host device, and when the proxy's reference count goes from 1 to 0. A weak `GetDevice` never increments a count that is already zero, and that acquire shares one lock with the 1-to-0 release, so only one thread runs final cleanup. Handing out the cached heap checks the host and the configured size, retargets `GetDevice`, and takes the caller's reference in that same lock. A concurrent backing configuration change makes an in-flight backing request return `HRESULT_FROM_WIN32(ERROR_RETRY)` before it can publish a stale heap. `CreatePlacedResource1` and `CreatePlacedResource2` unwrap the wrapper before calling the host. `test_d3d12_placed.exe` checks aliasing, ordinary heaps, small-resource placement, `ID3D12Heap1`, config lifetime, the write-through pointer, a fence-separated GPU copy in both directions, that an ordinary heap keeps its device alive, that `GetDevice` fails closed after a reconfigure and after a forced host replacement even once the proxy is released, that those newer placement calls accept a wrapped heap, and that a second proxy forced onto the same host device places a resource in the configured region without doubling the charge (#464).
|
||||
- `bx-cli trace` now summarizes the shader-format gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list (wave width and 64-bit-atomic flags), and `shader_bridge_missing`, per [ADR 0008](docs/adr/0008-m2-shader-format-gate.md). It only summarizes records a run wrote; no live CrossOver run was performed for this change.
|
||||
- `XCRDAPI.dll` completes a multi-request batch from one `Submit()` in queue order into CPU memory, mapped D3D12 upload buffers, and default buffers (a copy on the resource's device when the heap is not CPU-visible). If that copy has been submitted and its GPU completion is not confirmed, the shim keeps the destination and the copy's GPU objects alive and logs a warning, unless the device was removed or the fence already reached the waited value. The request still returns the failure HRESULT. LZ, BCPack, and GDeflate requests finish as `E_NOTIMPL` and log `BX_VTABLE_STUB_LOG`. `DStorageGetFactory` remains the only export (#467).
|
||||
- M2 Shader Format Gate (#466). `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` classify every stage through `bx_shader_bridge.dll` (#445) and log one `shader_gate` JSONL record per stage: kind, stage, shader model, chunk sizes, `SFI0` feature flags and `PSV0` wave lane range.
|
||||
- **Decisions:** DXIL and dual containers go to the host as the bridge's prepared copy. ACCC-only containers are refused with `E_NOTIMPL` before the host is called. Legacy DXBC and unclassifiable input pass unchanged. The bridge is loaded only by full path from `d3d12_xs.dll`'s directory. A missing bridge is logged once as `shader_bridge_missing`. Shaders then pass unclassified, but a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it.
|
||||
- **D3DMetal gaps:** stages needing a wave wider than 32 lanes or 64-bit atomics also log `shader_d3dmetal_gap`, the cases #453 measured as created but not run. The structural check now counts an `ACCC` chunk as a shader chunk, so the gate decides it.
|
||||
- **Test:** `tests/conformance/test_shader_gate/` runs a real DXC SM 6.6 compute shader through `d3d12_xs` and checks 256/256 output words. It requires `E_NOTIMPL` for an ACCC-only compute and graphics shader, and checks the logged wave64 and typed 64-bit-atomic constraints and every JSONL record. It then reruns itself from a directory without the bridge, which must still run DXIL and refuse ACCC-only. It passed on one Apple M5 Pro in a CrossOver 26.3 D3DMetal bottle. A bare prefix's vkd3d cannot load a DXIL converter, so the DXIL part needs the D3DMetal backend. `scripts/build-shims.sh` stages the bridge it needs (#484).
|
||||
- **ADR:** [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) proposes Branch D1 for M3, with the evidence; it is pending maintainer acceptance.
|
||||
- `scripts/build-shims.sh` now builds and verifies `bx_shader_bridge.dll` with the shims (#484). It builds the Windows version of `shader-transpiler/crates/dxbc-accc` (#445), linked with the new frozen export list `abi/defs/bx_shader_bridge.def`, so its export directory name is `bx_shader_bridge.dll`. It places the DLL in `build-shims/bin` and checks it with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. The script now reports 17 DLLs and 111 exports.
|
||||
- **Toolchain:** `cargo` and `rustc` come from rustup when available. The build always uses `<repo>/target`, and a missing `x86_64-pc-windows-gnu` target stops the script with `rustup target add x86_64-pc-windows-gnu` (it is never skipped). The CI job installs that target with its pinned toolchain.
|
||||
- **Effect:** `d3d12_xs`'s shader gate (#466) finds the bridge in `build-shims/bin` without a manual copy.
|
||||
- Implemented the `IGameInput` v0 device-callback lifecycle (`RegisterDeviceCallback`, `StopCallback`, `UnregisterCallback`) and `SetFocusPolicy` in `shims/gameinput/gameinput.cpp` (#481). `RegisterDeviceCallback` validates `callbackFunc`, `inputKind`, `statusFilter`, and `enumerationKind` (`0..=2`), allocates unique monotonic `GameInputCallbackToken` handles under `SRWLOCK`, and supports optional null `callbackToken` output pointers; `StopCallback` marks active registrations stopped while keeping them unregisterable once via `UnregisterCallback`; `SetFocusPolicy` records focus-policy flags without stub noise. Expanded `test_audio_input.exe` to cover validation, token uniqueness, stop/unregister idempotence, and focus-policy calls.
|
||||
- `dxbc-accc` now reaches Windows guests as `bx_shader_bridge.dll`, the x86-64 Windows build of the same crate (#445). It exports exactly the three `bx_shader_bridge.h` entry points and needs no MinGW runtime DLL. `shader-transpiler/crates/dxbc-accc/guest/build.sh` builds the DLL and checks its exports and imports. It also builds `check_bridge.exe`, a C guest program compiled against the frozen header, which sends a real DXC SM 6.6 blob and eight synthetic containers (DXIL with and without trailing bytes, `ACCC`/`FSPX` v1 and v0, dual, legacy `SHEX`, malformed) through the DLL loaded by full path. It checks classification (exact chunk sizes, root signature flag, header digest, declared size), prepare (only the declared container is copied), free, and prints a DXIL vs. `ACCC` count. The build script always uses `<repo>/target` and rustup's toolchain, and checks the whole Export Address Table and an import allowlist. On one Apple M5 Pro with CrossOver 26.3, in a prefix and a D3DMetal bottle, it reported `dxil=3 accc_only=2 dual=1 legacy=1 invalid=2` and passed. Synthetic containers only. Staging the DLL in `build-shims`, an `abi/defs` export list, and the `d3d12_xs` PSO hook (#466) are separate changes.
|
||||
- `xgameruntime.dll!QueryApiImpl` now serves offline `XGameSave` and `XPackage` as COM `IUnknown` objects under BetterXen synthetic keys (#468, not yet closed). A title linked against Microsoft's `xgameruntime.lib` does not request these keys. Every synthetic key and COM slot order now lives in `shims/xgameruntime/synthetic_keys.h`, the single place to find or replace them. Signatures, structure layouts, `E_GS_*` values and container-name rules follow the public Microsoft Learn reference.
|
||||
- **XGameSave:** provider init, containers, updates, blob writes, submit and read (both asynchronous), enumeration and the close calls. Saves are separated by SCID: each container is one file under `C:\bx_pls\<hash>\saves\<SCID hash>\`, replaced atomically on submit. A named mutex per SCID directory serializes access across threads and processes. Damaged files (truncated, trailing bytes, duplicate or NUL-bearing names) read as `ERROR_FILE_CORRUPT`, and enumeration skips them and unreadable files with a log line. Offline choices where the reference is silent (16 MiB including blob names, 256-byte blob names, no sync, retry after a failed submit) are listed in `game_save.cpp`.
|
||||
- **XPackage:** the running executable's directory stands in for the installed package: a stable `BXPKG…` identifier, `XPackageKind::Game` for it, and `XPackageMount` / mount-path queries that return that directory.
|
||||
- **Lifetimes:** the last uninitialize closes every XGameSave and XPackage handle and drops unconsumed results. Closing a provider closes its containers and their updates. Each handle type has its own value range. An operation queued before an uninitialize completes with `E_GAMERUNTIME_NOT_INITIALIZED` without running.
|
||||
- **Async:** results of the new operations go through the existing XAsync engine, including `XAsyncGetResultSize`, cancellation and reuse rules. A cancel that arrives after an operation started no longer reports `E_ABORT` for work that was done. An unconsumed result is kept until its block is reused or the runtime is uninitialized.
|
||||
- **Tests:** `tests/conformance/test_xgameruntime_saves/` covers both families through `QueryApiImpl`, with its own copies of the keys, slot numbers, structure layouts and storage format. It checks:
|
||||
- name rules, the write and read round trip, and the size limits;
|
||||
- SCID isolation and enumeration;
|
||||
- crafted damaged files, a failed replace that keeps the old save, and a successful one that replaces the file;
|
||||
- 64 threaded and 160 cross-process concurrent submits;
|
||||
- uninitialize with pending work, stale handles and released memory, and a non-ASCII executable directory.
|
||||
|
||||
Each of eleven injected faults (non-atomic write, missing or per-process lock, ignored SCID, no-op close, lax parsing, uncounted names, retained results, stale work running, children kept after a provider close) makes it fail.
|
||||
- **Not done:** validation against a caller linked to Microsoft's `xgameruntime.lib`, since these keys are BetterXen's own. `abi/defs/xgameruntime.def` is unchanged (49 exports).
|
||||
- `QueryApiImpl` also serves offline XGameSave and XPackage on the public COM class and interface ids, with slot order from [xgameruntime-docs](https://github.com/xodus-gaming/xgameruntime-docs) commit `7090008692569aa6081e30dfdd9de58237741e24` (#468). The ids and slot order come from that documentation; its provenance is recorded in `docs/research/upstream-registry.md` and the component reuse matrix, pending maintainer acceptance. `XPackageMountWithUiAsync` / `XPackageMountWithUiResult` (`IXPackageImpl2` slots 37–38) now mount through the XAsync engine, like `XPackageMount`. `IXError` slot 3 now returns `false`, following the #492 review's observation that the GDK's static library continues only on `false`; that source lists the slot as unknown.
|
||||
- Added `docs/research/d3dmetal-gpu-limits.md` and `tests/conformance/test_d3dmetal_gpu_limits/` (#453). The fixture is an original D3D12 compute test that loads the host `d3d12.dll` directly, with four original HLSL kernels and committed DXC 1.9.2609 output (`shaders/compile.sh` regenerates them). It skips with exit 77 below shader model 6.6. Required checks:
|
||||
- a kernel without `WaveSize` runs, and its lane indices form a permutation within each wave;
|
||||
- a per-texel spin lock with acquire and release fences and a 1024-try cap emulates 64-bit add and max with no dropped update and exact values.
|
||||
|
||||
Everything else is printed as `OBSERVED:` lines. On one Apple M3 Pro (macOS 27.2.1, CodeWeavers Wine 11.0 built from source, D3DMetal 4.0b3), three runs gave the same outcomes, with 4/4 required checks passing each time:
|
||||
- the `[WaveSize(64)]` pipeline is created but never runs;
|
||||
- kernels using SM 6.6 64-bit atomics, on a typed UAV or a raw buffer, are created but never run, although the device reports support for them; a plain-store marker beside the atomics shows the skip;
|
||||
- a 64-try lock cap drops 96–108 of 512 updates.
|
||||
|
||||
The note links only these measured items from the M2 and M3 roadmap rows. Observations reported from a commercial title are kept in a separate "not evidence" section, each with the synthetic workload that would verify it. This is a local implementer run, not on CrossOver 26.3 and not independently reproduced.
|
||||
- Updated `README.md` and `docs/roadmap.md` to record Milestone M0 and Milestone M1 (`#17`, 16/16 issues) as verified complete on synthetic workloads and activate Milestone M2 (`#18`, First Rendered Frame & Shader Format Gate).
|
||||
- Implemented clean-room COM `IUnknown` vtable dispatch in `xgameruntime.dll!QueryApiImpl` for the core public Microsoft PC GDK (`Microsoft.GDK.Windows 2610.0.9661`) interface families (`XAsync`/`XTaskQueue`/`XThread`, `XGameRuntimeIsFeatureAvailable`, `XSystem`, `XError`, `XPersistentLocalStorage`, `XUser`, `XStore`, `XGameUi`, `XNetworking`, `XGame`), with auto-logging `BX_VTABLE_STUB_LOG` fallback on unimplemented slots. Validated live on CrossOver 26.3 with an independently authored caller linked against Microsoft's public `xgameruntime.lib` (#456).
|
||||
- `bx_runtime_veh.dll` handles illegal-instruction traps for CLZERO, MONITORX, MWAITX, RDPRU, EXTRQ and INSERTQ (#451). The decoder and fixture derive the encodings and expected results from the AMD Architecture Programmer’s Manual [volume 3](https://kib.kiev.ua/x86docs/AMD/AMD64/24594_APM_v3-r3.36.pdf) (24594, rev. 3.36) and [volume 4](https://kib.kiev.ua/x86docs/AMD/AMD64/26568_APM_v4-r3.25.pdf) (26568, rev. 3.25, EXTRQ pp. 139–140 and INSERTQ pp. 154–155).
|
||||
- CLZERO clears a 64-byte cache line selected by RAX or, with the `67` prefix, EAX. An unwritable target is reported as a write access violation at the line address and the guest can repair the page and retry. One-shot Windows guard-page behavior is outside this emulation.
|
||||
- MONITORX arms no host monitor. MWAITX yields once, so the EBX timer and ECX extensions have no effect. RDPRU approximates MPERF and APERF with the same timestamp rate and returns zero for unknown selectors. It clears the five flags specified by AMD and chooses zero for CF, whose value the manual leaves open.
|
||||
- EXTRQ and INSERTQ implement both the immediate and register-control forms, including XMM8–XMM15. The fixture checks the defined low-quadword results with and without REX, including both length-zero forms. It also covers the MONITORX address-size override and asserts the emulated CF result only when CPUID lacks RDPRU.
|
||||
- Each instruction logs sampled `<name>_trapped` events, and `bx-cli trace` prints per-kind lower bounds.
|
||||
- **Local result:** 28/28 synthetic AMD-instruction checks passed on one Apple M5 with macOS 27.2.1, CrossOver 26.3 and Rosetta 2. Trace lower bounds were CLZERO 4, MONITORX 2, MWAITX 2, RDPRU 4, EXTRQ 4 and INSERTQ 4. The CLWB and shim export fixtures passed. The boot fixture reported 19 passed and 2 pending host API-set checkpoints.
|
||||
- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached.
|
||||
- **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first.
|
||||
- **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged.
|
||||
- **Uninitialized environments:** a bare `--prefix` without `system32` is initialized with `wineboot --init` under the same isolated environment. A bottle without one fails with a hint. Neither case is ever skipped silently.
|
||||
- **Partial shim folders:** a `--shims` folder without `xgameruntime.dll` prints a notice and the run continues without staging, as it did before staging existed.
|
||||
- **Supervision:** `--timeout`, SIGINT, SIGTERM and SIGHUP also cover the `wineboot --init` step, so an interrupted first run does not leave `wineserver` running.
|
||||
- **Tests:** 8 unit tests cover staging and the dependency walk. `tests/conformance/test_system32_staging/` makes the `LOAD_LIBRARY_SEARCH_SYSTEM32` load and requires BetterXen's shim, from `system32`, exporting `QueryApiImpl`, and the same module for `SYSTEM32 | APPLICATION_DIR`. `--expect-missing` is the negative control for an unstaged prefix.
|
||||
- **Local result:** on one Apple M3 Pro (macOS 27.2.1) with CodeWeavers Wine 11.0 built from source, so not CrossOver 26.3, and with the staging done by hand: the control passed and the unstaged run failed as expected. Staging the runtime alone still failed, which is how the dependency rule was found. Staging both passed 4/4 in two runs. `bx-cli run` itself was not run, since CrossOver is not installed on that host.
|
||||
- `bx-cli run` 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 `docs/maintainer-testing.md` (build, acceptance, expected graphics, known limitations, cleanup) and a CI syntax check for the hybrid scripts.
|
||||
- Strengthened the hybrid acceptance suite (#407): every injected rendering fault must now fail the specific gate it targets, the crash control allows for slow `winedbg` start-up, the suite includes the swapchain lifetime probe and the Shader Model 6 readback check (reported `NOT-RUN` without DXC, never as a pass), and a window hidden on another macOS Space is reported as such. `bx-cli doctor` again reports the recommended memory profile, D3DMetal presence and the shim cross-compiler.
|
||||
- Recorded two local findings on Apple M4 with CrossOver 26.3, neither independently reproduced: under D3DMetal a new D3D12 swapchain starts with two references and survives the application's release, while the same binary on the `vkd3d` path starts with one and is freed; on the `vkd3d` path frames after about 437 each spend 2000 ms inside `Present`, and teardown then hangs.
|
||||
- The migrated #405 work includes Adeeb Rahman's D3D11 compute-buffer readback workload (`ce9c10a`) and Bartosz Szczepański's GPU wired-memory fields in host receipts and run records (`0427465`).
|
||||
- Moved #405's supervised runtime onto the six-track layout (#407): `bx-cli run`, `doctor`, `bench`, `stop` and the evidence commands now share one engine in `launcher/crates/bx-runtime`, replacing the unsupervised launch path. It adds timeout, stall, memory and output limits, a per-environment session lock with explicit recovery, cleanup limited to the selected environment, and JSON run records; `probe`, `shader` and `trace` are unchanged. `bx-cli run` now requires `--bottle` or `--prefix` (there is no shared `/tmp` default). The D3D11 and D3D12 workloads moved to `tests/conformance/`. Verified locally only; no independent reproduction.
|
||||
- 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).
|
||||
@@ -109,10 +56,6 @@ remains unsupported.
|
||||
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
|
||||
|
||||
### Changed
|
||||
- Added a model-agnostic "AI Agent Efficiency & Resource Management" section to `AGENTS.md` (§9), absorbing the earlier subagent reasoning rule: agents reuse valid evidence, read and verify narrowly and avoid redundant work, without weakening required verification, safeguards or independent review.
|
||||
- Changed contributor and agent rules (`AGENTS.md`, `CONTRIBUTING.md`, `docs/legal.md`): agents now pick work in priority order (fix their own open PRs, then take an unclaimed issue, then review others' PRs); lawfully obtained, maintainer-approved target builds may be inspected locally as compatibility evidence where license terms and law permit, with no decryption or circumvention, and leaked or unauthorized material stays excluded; maintainer-directed tasks may cross track directories without a prior issue claim, while active claims, `[ABI]`-first changes and independent review still apply. Policy only; no compatibility claim.
|
||||
- Corrected `shader-transpiler/crates/dxbc-accc/README.md` (#498): its "Not done here" section listed the export list, the `build-shims.sh` staging and the `d3d12_xs` PSO hook as outstanding, but those shipped (#445, #484, #466). The section now describes each one and credits the issue that delivered it. Documentation only.
|
||||
- Documented independent Direct3D acceptance results on CrossOver 26.3 and CrossOver Preview 27, including D3D12 swapchain retention and Wine presentation stalls (#450).
|
||||
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
|
||||
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
|
||||
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
|
||||
@@ -142,10 +85,6 @@ 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
|
||||
- Corrected the stale shim-DLL counts in `AGENTS.md`, `README.md`, `docs/roadmap.md` and `docs/architecture/parallel-tracks.md` (#525). `scripts/build-shims.sh` verifies **17** PE32+ DLLs with **111** exact exports, not 16 with 102. The wording now distinguishes the **16 mingw-w64 C++ shims** (built by the CMake superbuild) from the **Rust `bx_shader_bridge.dll`** (built by `cargo` for `x86_64-pc-windows-gnu`, added by #484), rather than calling all 17 "cross-compiled C++ shims". `test_shim_exports.exe` still loads only the 16 C++ shims (25 checks); it does not load the bridge, which `test_shader_gate.exe` covers. The `docs/roadmap.md` M0 exit-gate text is a stale-count correction to a *recorded* gate (`#406`), not a re-opening of M0. Follow-up (not done here): `test_shim_exports` could also load `bx_shader_bridge.dll`.
|
||||
- `bx-cli run` now stages `GameInput.dll` into `system32` alongside `xgameruntime.dll` and safely replaces Wine's `"Wine builtin DLL"` placeholder stub after saving a one-time backup (`.gameinput.dll.wine-builtin.bak`), while continuing to refuse modifying any non-Wine foreign DLL or symbolic link (#482). Wine pre-populates `drive_c/windows/system32/gameinput.dll` with a fake builtin PE stub whose `GameInputCreate` returns `E_NOTIMPL`, shadowing `WINEPATH` and `LOAD_LIBRARY_SEARCH_SYSTEM32` loads even when `WINEDLLOVERRIDES` specifies native-first (`=n,b`). Also added lowercase aliases (`gameinput`, `xcrdapi`, `acphal`) to `SHIM_DLL_OVERRIDES` and expanded `test_system32_staging.exe` and `stage.rs` unit tests to cover `GameInput.dll` staging and Wine stub backup/refusal rules.
|
||||
- `bx-cli run` system32 shim staging (#474). Staging now records what it wrote in a `.bx-staged` manifest in the prefix's `system32` (one SHA-256 per file) and replaces only regular files that are listed there and still have the recorded hash. Any other same-named entry the bottle already had, including a symbolic link that points nowhere, or one changed since it was staged, is never modified or deleted: staging stops with an error naming it before anything is written. New files are installed without replacing anything, so an entry that appears after the checks is protected too. All temporary copies are written before the first file is put in place, and each installed file is recorded in the manifest before the next one is touched, so a failure part-way leaves the earlier files owned rather than orphaned. A byte-identical existing file is left alone and not claimed. For a named bottle, the prefix is resolved again after the run; if CrossOver launched the bottle elsewhere, the run fails only when the staged shims cannot be found with the same contents in that prefix's `system32` (a private stub of a managed bottle that links back to the managed prefix is accepted and reported). When prefix initialization uses the whole `--timeout`, the guest is no longer started and the message names initialization (exit 124). Copies staged by an earlier `bx-cli` have no manifest entry and are treated as the bottle's own, so after upgrading a changed shim needs that stale copy removed by hand once. Staged files are still not removed after a run. Covered by 15 new unit tests (32 `bx-cli` tests pass); twelve deliberate breakages each failed a test. A reviewer ran the first revision on CrossOver 26.3 with a managed-only bottle and found the false failure, dangling-link and partial-failure cases fixed here; this revision has not itself been run under CrossOver.
|
||||
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
|
||||
- `test_integration_boot.exe` now creates a real texture address computer, checks a two-mip layout against hand-computed values and requires the final `Release` to return 0, instead of reporting that stage as pending after a null-descriptor probe (#446).
|
||||
- `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.
|
||||
@@ -157,9 +96,6 @@ remains unsupported.
|
||||
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
|
||||
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
|
||||
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
|
||||
- `bx-cli run` signal handling (#461). The environment's `wineserver` is now stopped before anything is reported on the stop path, and those reports and the trace summary no longer use panicking print macros, so Ctrl-C through `| tee` or a closed terminal can no longer skip cleanup. A signal inherited as ignored (`nohup`, a background job of a non-interactive shell) stays ignored. SIGQUIT (Ctrl-\\) stops the guest group and the environment like SIGINT. SIGTSTP (Ctrl-Z) is passed to the guest group, which is continued when `bx-cli` is, and suspended time does not count against `--timeout`. The cleanup `wineserver -k`/`-w` run in their own process group so a second Ctrl-C cannot kill them. The trace summary covers only what this run appended to the log; a log replaced or rewritten during the run (recognized by file identity and by the bytes before the old end, not by size) is summarized in full. A pause during prefix initialization is not charged to the guest's share of `--timeout` either. `THIRD_PARTY_NOTICES.md` no longer claims zero crates.io dependencies and now includes the `libc` MIT text. The stop messages changed from "stopping the environment" to "stopped the environment" because they are printed afterwards. Covered by 10 new unit tests with stub launchers and servers; each fix was removed in turn and its test failed. A reviewer confirmed Ctrl-C through `| tee` on a real terminal under CrossOver 26.3. The author then ran seven scenarios under CrossOver Preview build 20261006 (Ctrl-C through `tee`, an inherited-ignored SIGHUP, Ctrl-\\, Ctrl-Z and continue, repeated Ctrl-C during cleanup, a pause during prefix setup, a log replaced mid-run) with signals sent to the process group rather than typed, using a build that differs only in where it looks for CrossOver; each showed the old behaviour before the change and the fixed behaviour after. Not confirmed with real key presses, and not on CrossOver 26.3 for anything but the first. The same pattern in the unmerged #425 is not touched.
|
||||
- `d3dmetal-harness` runner tests no longer give a freshly written script only 300–500 ms to start (#479); both use a 2 s deadline. The kill test now also checks that the probe ran until the deadline and that its process is gone, which catches a timeout path that neither kills nor waits for the probe. It passes the PID-file path as a script argument so temporary directory names containing apostrophes work. Test-only change. Slow script start-up as the cause of the earlier failures is inferred, not measured. `output_complete` is not asserted for the killed probe, because a child spawned by a parallel test may inherit its pipe.
|
||||
- `bx-cli run` no longer blocks when `--log` names something other than a regular file (#502). The trace-log reads added for #461 opened the path and read it to the end, which waits forever on a FIFO nobody writes to; the log is now opened without waiting and only a regular file is summarized (anything else gets no summary). Also added the missing test for the file-identity half of the replaced-log check (a different file that begins with the old log's bytes), which a reviewer found untested, and documented that Ctrl-Z typed between supervised phases takes effect when the next phase starts. Covered by 2 new unit tests; three deliberate breakages each failed a test. Not run under CrossOver.
|
||||
|
||||
### Added
|
||||
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ The single authoritative plan is [docs/roadmap.md](docs/roadmap.md) (Milestones
|
||||
|
||||
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
|
||||
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
|
||||
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**. Maintainer-directed tasks have a narrow exception ([AGENTS.md](AGENTS.md) §2).
|
||||
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**.
|
||||
4. If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both tracks implement in parallel.
|
||||
5. Add new synthetic PE32+ conformance binaries under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake — no shared-file edits needed).
|
||||
|
||||
@@ -33,7 +33,7 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
|
||||
|
||||
## Clean-Room, Licensing & Provenance Policy
|
||||
|
||||
- Use publicly accessible specifications, publicly licensed software, independently authored synthetic workloads, and project-authorized target builds only under every condition in [AGENTS.md](AGENTS.md) §6 (maintainer approval alone is not enough). Never obtain or use leaked or unauthorized material, and never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
|
||||
- Use publicly accessible specifications, publicly licensed software, and independently authored synthetic workloads only. Never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
|
||||
- Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
|
||||
- Before incorporating third-party code, verify **per-file** license compatibility with `GPL-3.0-or-later`, record provenance in [docs/research/upstream-registry.md](docs/research/upstream-registry.md) and [docs/research/component-reuse-matrix.md](docs/research/component-reuse-matrix.md), preserve copyright notices, and update [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Public visibility or a GPL license does not clear code derived from leaked material.
|
||||
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
|
||||
|
||||
Generated
+8
-1
@@ -7,15 +7,22 @@ name = "bx-cli"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"bx-probe",
|
||||
"bx-runtime",
|
||||
"bx-telemetry",
|
||||
"dxbc-accc",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bx-probe"
|
||||
version = "0.2.0"
|
||||
|
||||
[[package]]
|
||||
name = "bx-runtime"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bx-telemetry"
|
||||
version = "0.2.0"
|
||||
|
||||
@@ -3,6 +3,7 @@ members = [
|
||||
"launcher/crates/bx-cli",
|
||||
"launcher/crates/bx-probe",
|
||||
"launcher/crates/bx-telemetry",
|
||||
"launcher/crates/bx-runtime",
|
||||
"shader-transpiler/crates/d3dmetal-harness",
|
||||
"shader-transpiler/crates/dxbc-accc",
|
||||
]
|
||||
|
||||
@@ -9,13 +9,13 @@
|
||||
-1f6feb?logo=apple&logoColor=white)
|
||||

|
||||

|
||||
-0969da)
|
||||
-d29922)
|
||||

|
||||
|
||||
</div>
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project with **Milestone M0 and Milestone M1 verified complete** on synthetic PE32+ workloads under CrossOver 26.3 + Rosetta 2, and **Milestone M2** (`First Rendered Frame & Shader Format Gate`) currently active. **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
|
||||
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project currently at **Milestone M0** (cross-compiled shim foundation and live CrossOver/Rosetta smoke tests verified on synthetic PE32+ workloads). **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
|
||||
|
||||
BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Rosetta 2**, and **D3DMetal 3.0** on Apple Silicon:
|
||||
- **Native ARM64 macOS tooling** (`launcher/`, Rust) for host diagnostics, PE32+ static probing, CrossOver bottle orchestration, and structured trace aggregation.
|
||||
@@ -33,9 +33,9 @@ BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Ro
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M0["M0: Foundation & Shims\n(Verified Complete)"]:::done
|
||||
M1["M1: Boot to D3D12\n(Verified Complete — 16/16)"]:::done
|
||||
M2["M2: First Frame &\nShader Gate\n(Active — Milestone #18)"]:::active
|
||||
M0["M0: Foundation & Shims\n(Merged #406)"]:::done
|
||||
M1["M1: Boot to D3D12\n(Active — Milestone #17)"]:::active
|
||||
M2["M2: First Frame &\nShader Gate"]:::planned
|
||||
M3["M3: Shaders &\nTexture Tiling"]:::planned
|
||||
M4["M4: 3D, DXR/BVH\n& Input"]:::planned
|
||||
M5["M5: Audio, Saves\n& Stability"]:::planned
|
||||
@@ -50,16 +50,16 @@ flowchart LR
|
||||
|
||||
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
|
||||
|
||||
### Active Milestone — [M2: First Rendered Frame & Shader Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)
|
||||
### Active Milestone — [M1: Startup Shims to `D3D12XboxCreateDevice`](https://github.com/MacosPorters/betterxen/milestone/17)
|
||||
|
||||
| Track | Focus | Visual Status | Live Issues |
|
||||
| --- | --- | --- | --- |
|
||||
| **Track A** | `system32` shim staging (`#457` / PR `#458` merged), AMD-only VEH emulation (`#451`), Track A/F runner integration (`#407`) | `🟩🟨🟨` *(#458 merged; #451, #407 active)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
|
||||
| **Track B** | `XCRDAPI.dll` DirectStorage GPU-buffer & batch transfers (`#467`) | `⬜` *(1 ready)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
|
||||
| **Track C** | `d3d12_xs` `D3D12ConfigureVirtualMemoryX` + placed resources (`#464`), `PresentX` swapchain bridge (`#465`), D3D workload fixes (`#450`) | `⬜⬜⬜` *(3 ready)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
|
||||
| **Track D** | `dxbc-accc` Windows guest bridge (`#445`), M2 Shader Format Gate ADR & PSO hook (`#466`) | `⬜⬜` *(2 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
|
||||
| **Track E** | Public GDK COM `QueryApiImpl` dispatch (`#456` / PR `#462` merged), offline `XGameSave` + `XPackage` COM dispatch (`#468`) | `🟩⬜` *(#462 merged, 1 ready)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
|
||||
| **Track F** | D3DMetal GPU limits fixture (`#453` / PR #455), M2 first-frame + shader-gate exit fixture (`#469`) | `🟨⬜` *(PR #455 approved, 1 ready)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
|
||||
| **Track A** | `bx-cli` supervision, `clwb` VEH + crash dumper, Win32 bridge | `🟨🟨🟨` *(3/3 PRs open)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
|
||||
| **Track B** | `xmem.dll` core + physical/scatter pages, `XCRDAPI.dll` DirectStorage | `🟨🟨🟨` *(3/3 PRs open)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
|
||||
| **Track C** | `d3d12_xs.dll` COM proxy (D3DMetal 3.0), `xg_xs.dll` texture computer | `⬜⬜` *(needs contributors!)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
|
||||
| **Track D** | `dxbc-accc` FSPX C ABI bridge, `d3dmetal-native` harness | `🟨⬜` *(1 PR open, 1 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
|
||||
| **Track E** | `xgameruntime.dll` offline GDK, `AcpHal`/`xapu`/`chad`, `GameInput` | `🟨🟨` *(2/2 PRs open)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
|
||||
| **Track F** | End-to-end synthetic boot fixture (`test_integration_boot`) | `🟨` *(1/1 PR open)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
|
||||
|
||||
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
|
||||
|
||||
@@ -67,9 +67,9 @@ Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
|
||||
|
||||
| Milestone | Scope | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 mingw-w64 C++ PE32+ shims plus the Rust `bx_shader_bridge.dll` (17 verified DLLs), live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
|
||||
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime` + dynamic loader exports, audio queue stubs, supervised `bx-cli run`, ADR 0007, `test_integration_boot` 19 pass / 2 pending / 0 fail) | 🟢 **Verified complete ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
|
||||
| **M2 — First Frame & Shader Gate** | Reversible `system32` staging, public GDK COM `QueryApiImpl` dispatch, `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0, `dxbc-accc` Windows bridge, D3DMetal GPU limits, and Shader Format Gate ADR | 🔵 **Active ([Milestone #18](https://github.com/MacosPorters/betterxen/milestone/18))** |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Merged (`#406`)** |
|
||||
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime`, audio queue stubs) | 🔵 **Active ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
|
||||
| **M2 — First Frame & Shader Gate** | `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0; inspect runtime shaders to select DXIL fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation | ⚪ Planned |
|
||||
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | ⚪ Planned |
|
||||
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | ⚪ Planned |
|
||||
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | ⚪ Planned |
|
||||
@@ -129,10 +129,10 @@ The repository is organized into disjoint track directories around a single froz
|
||||
|
||||
| Directory | Track | Stack | Contents |
|
||||
| --- | --- | --- | --- |
|
||||
| [`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 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) |
|
||||
| [`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; 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/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/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 |
|
||||
@@ -165,9 +165,8 @@ cargo build -p bx-cli
|
||||
# 2. Check host Apple Silicon, Rosetta 2, CrossOver, D3DMetal, and mingw-w64 readiness
|
||||
target/debug/bx-cli doctor
|
||||
|
||||
# 3. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust
|
||||
# bx_shader_bridge.dll with cargo, and build the conformance binaries
|
||||
# (automatically verifies every abi/defs/*.def export across all 17 DLLs and zero MinGW runtime DLL deps)
|
||||
# 3. Cross-compile all 16 x86-64 PE32+ shim DLLs + conformance binaries
|
||||
# (automatically verifies every abi/defs/*.def export and zero MinGW runtime DLL deps)
|
||||
scripts/build-shims.sh
|
||||
|
||||
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + Rosetta 2
|
||||
@@ -186,7 +185,8 @@ python3 scripts/audit/docs_hygiene.py
|
||||
| `bx-cli doctor` | Inspects Apple Silicon host, RAM (recommends `lockhart` on 16 GB Macs or `anaconda` on 32 GB+), Rosetta 2, CrossOver, D3DMetal, and `mingw-w64` |
|
||||
| `bx-cli probe <pe32+>` | Static PE32+ import scanner that classifies every imported DLL into Tracks A–E or Wine built-ins |
|
||||
| `bx-cli shader <blob>` | Classifies a `DXBC` shader container (`DXIL` vs. legacy `SHDR`/`SHEX` vs. `ACCC`/`FSPX`) |
|
||||
| `bx-cli run --exe <path> ...` | Launches a PE32+ binary under CrossOver/Wine with `env_clear()` host isolation (`--inherit-env` opt-in), `ROSETTA_ADVERTISE_AVX=1`, `WINEDLLOVERRIDES`, `BX_PROFILE`, and JSONL trace capture |
|
||||
| `bx-cli run --exe <path> ...` | Launches a PE32+ binary under CrossOver/Wine with `env_clear()` host isolation (`--inherit-env` opt-in), `ROSETTA_ADVERTISE_AVX=1`, `WINEDLLOVERRIDES`, `BX_PROFILE`, and JSONL trace capture. Needs `--bottle` or `--prefix`; supervised with timeout, stall, memory and output limits and writes a JSON record |
|
||||
| `bx-cli stop (--bottle B \| --prefix P)` | Recovers an environment after a supervisor was force-killed |
|
||||
| `bx-cli trace <log.jsonl>` | Aggregates `bx_runtime_veh.dll` logs (unimplemented API counts, COM vtable misses, `clwb` VEH traps, ADX tripwires) |
|
||||
|
||||
---
|
||||
@@ -209,9 +209,9 @@ See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architectu
|
||||
|
||||
- **Verified (local Apple M5, macOS 27.2.1, CrossOver 26.3, Rosetta 2):**
|
||||
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
|
||||
- All 17 x86-64 PE32+ shim DLLs — the 16 mingw-w64 C++ shims plus the Rust-built `bx_shader_bridge.dll` — pass strict PE Export Directory verification (111 exact names, ordinals, forwarders, 0 extra exports) and carry zero dynamic MinGW runtime dependencies. `scripts/build-shims.sh` cross-compiles the 16 C++ shims with CMake/mingw-w64 and builds `bx_shader_bridge.dll` with `cargo` for `x86_64-pc-windows-gnu`.
|
||||
- All 16 x86-64 PE32+ shim DLLs cross-compile with zero warnings, pass strict PE Export Directory verification (102 exact names, ordinals, forwarders, 0 extra exports), and carry zero dynamic MinGW runtime dependencies.
|
||||
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
|
||||
- `test_shim_exports.exe` loads the 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine. It does **not** load `bx_shader_bridge.dll`; the Rust bridge is exercised by `test_shader_gate.exe` instead.
|
||||
- `test_shim_exports.exe` loads all 16 shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
|
||||
- **Not yet implemented (M1–M6):**
|
||||
- `d3d12_xs.dll` COM device/command-list/PSO proxy and `PresentX` swapchain presentation.
|
||||
- `xmem.dll` physical/scatter page mapping and `XCRDAPI.dll` async DirectStorage queues.
|
||||
|
||||
+15
-61
@@ -1,14 +1,24 @@
|
||||
# Third-party notices
|
||||
|
||||
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) is original `GPL-3.0-or-later` source with **one external crates.io dependency**: `libc`, used only by `bx-cli`.
|
||||
BetterXen's own source is `GPL-3.0-or-later`. The active launcher uses `libc` 0.2.191 (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX signals and file locks, under its MIT option. Preserve the Rust Project Developers notice and permission text. Private build bundles include the unmodified locked libc source and notices.
|
||||
|
||||
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. The crate is licensed `MIT OR Apache-2.0`; its notice and permission text (`LICENSE-MIT` in the 0.2.191 crate) are reproduced under [libc MIT license text](#libc-mit-license-text) below.
|
||||
The memory guard and stall/memory-settle concepts in `launcher/crates/bx-runtime` are inherited from BetterXen #405: attributed Rust reimplementations of contributor-owned supervision concepts from skakwy/victory-mac at `22b3f8e45a59`, GPL-3.0, used with the author's permission as recorded in the [donor per-component audit](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/upstream-integration-audit.md). No game-facing implementation is copied. The excluded `victory-shader` compiler is not imported.
|
||||
|
||||
## Vendored source files
|
||||
Original conformance workloads are built with external llvm-mingw 20261117 (archive SHA-256 `98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa`). Its wrappers are ISC; LLVM and MinGW compiler/runtime components carry separate terms. Compiler binaries are not bundled. Windows workload bundles preserve the unmodified LLVM/MinGW notices for linked runtime support. Microsoft DXC v1.9.2609 is an external, checksum-pinned Windows guest tool; its executable and DLLs are never bundled. Details: [selected source review](docs/research/maintainer-upstream-review.md).
|
||||
|
||||
| Files | Origin | License |
|
||||
## BetterXen contributor work carried from #405
|
||||
|
||||
These are contributions to BetterXen under `GPL-3.0-or-later`, not third-party code. They were moved onto the six-track layout, so their original commits are not in the new history. The sign-offs recorded in the original commits are:
|
||||
|
||||
```text
|
||||
ce9c10a Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
|
||||
0427465 Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
|
||||
```
|
||||
|
||||
| Contributor | Original commit | Carried to |
|
||||
| --- | --- | --- |
|
||||
| `shims/xcrdapi/dstorage/dstorage.h`, `shims/xcrdapi/dstorage/dstorageerr.h` | Microsoft DirectStorage SDK headers, NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0, unmodified (#483). Provenance and hashes: [shims/xcrdapi/dstorage/README.md](shims/xcrdapi/dstorage/README.md). | MIT, per-file notice. The package's `LICENSE-CODE.txt` is kept next to the headers and reproduced under [DirectStorage headers MIT license text](#directstorage-headers-mit-license-text) below. |
|
||||
| Adeeb Rahman | [`ce9c10a`](https://github.com/MacosPorters/betterxen/commit/ce9c10a3ab4e2c476bf8ab568688089e1edbd19e) | `tests/conformance/optional/d3d11-compute/` (D3D11 compute-buffer readback workload) |
|
||||
| Bartosz Szczepański | [`0427465`](https://github.com/MacosPorters/betterxen/commit/042746554c808dafe48b76b765efd872545429bd) | `launcher/crates/bx-runtime/src/host.rs` and `run.rs` (GPU wired-memory fields in receipts and run records) |
|
||||
|
||||
## External Host Tools & Runtime Dependencies (Never Bundled)
|
||||
|
||||
@@ -19,59 +29,3 @@ The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) is original `G
|
||||
| `mingw-w64` & CMake | Developer cross-compilation toolchain for x86-64 PE32+ shims | Installed externally via Homebrew (`brew install mingw-w64 cmake`) for building `shims/` and `tests/conformance/`. |
|
||||
|
||||
Historical third-party notices for the retired native-first workspace (including AMD RDNA 2 ISA metadata, `bitflags`, and `objc2-*`) remain preserved at Git tag `native-first-final` and are summarized in [docs/licenses.md](docs/licenses.md).
|
||||
|
||||
## libc MIT license text
|
||||
|
||||
```text
|
||||
Copyright (c) The Rust Project Developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
```
|
||||
|
||||
## DirectStorage headers MIT license text
|
||||
|
||||
```text
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
```
|
||||
+1
-1
@@ -7,4 +7,4 @@ This directory holds the **only shared interface boundary** across BetterXen's s
|
||||
1. **ABI-First Changes:** If one track needs a new cross-DLL helper, config flag, or export symbol, open a small, focused `[ABI]` pull request touching only `abi/`.
|
||||
2. **Zero File Collisions:** Never edit another track's implementation directory in an `[ABI]` PR. Once the `[ABI]` PR merges to `main`, both provider and consumer tracks implement in parallel.
|
||||
3. **Versioned Contracts:** Increment `BX_ABI_VERSION` in `abi/include/bx_config.h` on any breaking struct or signature change.
|
||||
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files. One entry is not under `shims/`: `bx_shader_bridge.def` is the export list of `bx_shader_bridge.dll`, the x86-64 Windows build of `shader-transpiler/crates/dxbc-accc` (#445). `scripts/build-shims.sh` links it into that build and verifies it with the shims (#484).
|
||||
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files.
|
||||
@@ -1,5 +0,0 @@
|
||||
LIBRARY bx_shader_bridge.dll
|
||||
EXPORTS
|
||||
bx_shader_inspect
|
||||
bx_shader_prepare_for_d3dmetal
|
||||
bx_shader_free_buffer
|
||||
@@ -43,9 +43,3 @@ EXPORTS
|
||||
XGameUiShowTextEntryAsync
|
||||
XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync
|
||||
XNetworkingQuerySecurityInformationForUrlAsync
|
||||
InitializeApiImpl
|
||||
InitializeApiImplEx
|
||||
InitializeApiImplEx2
|
||||
UninitializeApiImpl
|
||||
QueryApiImpl
|
||||
XErrorReport
|
||||
+2
-4
@@ -8,14 +8,13 @@
|
||||
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
|
||||
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
|
||||
- [Synthetic Conformance Suite](../tests/conformance/README.md) — Auto-discovered PE32+ conformance binaries.
|
||||
- [Maintainer Testing Guide](maintainer-testing.md) — Build, acceptance, expected graphics, known limitations and cleanup for the hybrid runtime.
|
||||
- [Changelog](../CHANGELOG.md) — Unreleased and historical changes.
|
||||
|
||||
## Architecture Decision Records
|
||||
|
||||
- [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.
|
||||
- [ADR 0008: M2 Shader Format Gate](adr/0008-m2-shader-format-gate.md) — Proposed: Branch D1 (DXIL through D3DMetal, with the measured wave64 and 64-bit-atomic gaps as M3 work); ACCC-only containers refused with `E_NOTIMPL` until a lawful format source exists.
|
||||
|
||||
## Research, Testing & Licensing
|
||||
|
||||
@@ -23,8 +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) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
|
||||
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
|
||||
- [Runtime Integration Source Review](research/maintainer-upstream-review.md) and its [reference revisions](research/maintainer-reference-heads.json) — Upstream source inspected for the supervised runtime; nothing adopted.
|
||||
- [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
|
||||
|
||||
@@ -26,7 +26,7 @@ BetterXen provides integration, configuration, environment management, diagnosti
|
||||
|
||||
## Verified implementation capabilities
|
||||
|
||||
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md` at tag `native-first-final`, the archive ADR 0006 makes canonical; the file is retired from `main`.
|
||||
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md`.
|
||||
|
||||
## Planning consequence
|
||||
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
# ADR 0007: API-set win32_bridge shims are not reached under CrossOver
|
||||
|
||||
Status: **Accepted** (2026-11-26, issue #437). Independently verified on CrossOver 26.0 and CrossOver 26.3 on Apple Silicon.
|
||||
|
||||
## Context
|
||||
|
||||
`shims/win32_bridge/` builds six DLLs named after Windows API sets:
|
||||
`api-ms-win-core-psm-appnotify-l1-1-0`, `api-ms-win-core-psm-appnotify-l1-1-1` and four `ext-ms-win-rtcore-ntuser-*` forwarders to `user32.dll`. A guest that imports those names statically is expected to load the BetterXen files placed next to the EXE. #437 reports that under CrossOver 26.3 it does not: Wine answers the names itself, even with `WINEDLLOVERRIDES=<name>=n,b` and the shim files in the EXE's directory.
|
||||
|
||||
## Evidence
|
||||
|
||||
`tests/conformance/test_apiset_resolution` imports one export from each of the six DLLs through the PE import directory, then reports for every name the module that owns the name and the module the loader bound the import address table slot to.
|
||||
|
||||
Run on an Apple M-series Mac, macOS 27.2.1, Rosetta 2, **CrossOver 26.0 (`26.0.0.39794`)**, bare prefix, with the override list from `bx-cli` (`SHIM_DLL_OVERRIDES`) and `build-shims/bin` as the EXE directory:
|
||||
|
||||
| Import name | Served by | Module that owns the name | Module the import is bound to |
|
||||
| --- | --- | --- | --- |
|
||||
| `api-ms-win-core-psm-appnotify-l1-1-0` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
|
||||
| `api-ms-win-core-psm-appnotify-l1-1-1` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
|
||||
| `ext-ms-win-rtcore-ntuser-message-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
|
||||
| `ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
|
||||
| `ext-ms-win-rtcore-ntuser-window-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
|
||||
| `ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
|
||||
|
||||
`WINEDEBUG=+loaddll` shows `Loaded` records for `user32.dll` and `twinapi.appcore.dll` (both builtin) and none for any of the six shim files. `--expect shim` fails 0/6, so the fixture does distinguish the two outcomes.
|
||||
|
||||
This behaviour was independently reproduced on **CrossOver 26.3** on Apple Silicon (`bx-cli run` with the shim directory and direct loader runs with `WINEDEBUG=+loaddll`), yielding the exact same 6/6 host resolution (`twinapi.appcore.dll` and `user32.dll`, both builtin, with no `Loaded` records for the six shim files) and `--expect shim` exiting 1. The internal Wine mechanism is not claimed here; this records observed loader behaviour.
|
||||
|
||||
## Decision
|
||||
|
||||
Rely on Wine's built-ins. Under CrossOver the six API-set shims are not part of the supported path: the host answers window and message calls through `user32.dll` and PSM registration through `twinapi.appcore.dll`.
|
||||
|
||||
- The six DLLs stay in the tree, built and export-checked, and are still exercised by explicit full-path loads (#431).
|
||||
- No attempt is made to make them win name resolution. That would depend on undocumented Wine API-set behaviour (#350) and, within this issue's scope, on patching or redistributing CrossOver or Wine components, which is out of scope.
|
||||
- Offline PSM behaviour that a title needs must live somewhere a static import actually reaches. This ADR does not choose that place.
|
||||
|
||||
## Consequences
|
||||
|
||||
- `test_apiset_resolution` records the current behaviour (`--expect host`) and fails when it changes. If a CrossOver build starts loading the shims, run it with `--expect shim` and revisit this ADR.
|
||||
- `test_integration_boot` continues to report `shim_backing` as pending for these six names under CrossOver.
|
||||
- Documentation describes the bridges as Windows-only stubs that CrossOver does not load for static imports.
|
||||
|
||||
## Not claimed
|
||||
|
||||
Nothing here shows Xbox title compatibility, behaviour on Xbox hardware, or behaviour on CrossOver builds outside 26.0 and 26.3. Evidence class: local Apple Silicon runs.
|
||||
@@ -1,75 +0,0 @@
|
||||
# ADR 0008: M2 Shader Format Gate — Branch D1 (DXIL normalization) for M3
|
||||
|
||||
Status: **Proposed** (2026-11-26, issue #466). The choice for M3 is the maintainers' to accept. The evidence below is from local Apple Silicon runs by the implementer and has not been independently reproduced.
|
||||
|
||||
## Context
|
||||
|
||||
The roadmap's M2 gate asks which shader path M3 builds:
|
||||
- **Branch D1, DXIL normalization:** shaders reach D3DMetal as DXIL, and BetterXen rewrites only what D3DMetal cannot run.
|
||||
- **Branch D2, `ACCC`/`FSPX` translation:** console-compiled RDNA 2 code in `ACCC` chunks is translated to DXIL or MSL.
|
||||
|
||||
The gate needs a classifier that guest pipeline creation actually reaches, plus measurements of what D3DMetal does with each form.
|
||||
|
||||
## What M2 built
|
||||
|
||||
- **Bridge (#445):** `bx_shader_bridge.dll` is the x86-64 Windows build of `dxbc-accc`, so guest code can call the inspector.
|
||||
- **Gate (#466):** `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` pass every stage through `bx_shader_inspect`. One `shader_gate` JSONL record per stage gives:
|
||||
- the container kind, stage, shader model and chunk sizes;
|
||||
- the `SFI0` feature flags (`D3D_SHADER_FEATURE_*` values from DirectX-Headers `d3dcommon.h`);
|
||||
- the `PSV0` wave lane range.
|
||||
- **Decisions:**
|
||||
- **DXIL and dual containers:** go to the host as the bridge's prepared copy (`bx_shader_prepare_for_d3dmetal`).
|
||||
- **ACCC-only containers:** are refused with `E_NOTIMPL` before the host device is called.
|
||||
- **Legacy DXBC and unclassifiable input:** pass unchanged.
|
||||
- **A missing bridge:** is logged once (`shader_bridge_missing`). Shaders then pass unclassified, except that a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it. The bridge is loaded only by full path from `d3d12_xs.dll`'s own directory.
|
||||
- **Known D3DMetal gaps:** a stage that needs a wave wider than 32 lanes, or 64-bit atomics, also gets a `shader_d3dmetal_gap` record.
|
||||
|
||||
`tests/conformance/test_shader_gate` exercises all of this.
|
||||
|
||||
## Evidence
|
||||
|
||||
| Observation | Source | Host and class |
|
||||
| --- | --- | --- |
|
||||
| A real DXC 1.9.2609 SM 6.6 compute shader (`fill_cs66`) creates a PSO through `d3d12_xs`, runs, and all 256 output words match the CPU reference. | `test_shader_gate` | Apple M5 Pro, macOS 27.2.1, CrossOver 26.3 (`26.3.0.39832`) bottle with `CX_GRAPHICS_BACKEND=d3dmetal`; class A, this host only |
|
||||
| The same shader, run outside Wine through `d3dmetal-native` against CrossOver's D3DMetal 3.0, matches 256/256. | [d3dmetal-harness](../../shader-transpiler/crates/d3dmetal-harness/README.md) (#417) | Same host; class A |
|
||||
| An ACCC-only container is refused with `E_NOTIMPL` for compute and graphics, no host object is created, and the device stays usable. | `test_shader_gate` | Same bottle; class A |
|
||||
| In a bare CrossOver 26.3 prefix (vkd3d), SM 6.6 DXIL PSOs fail with `E_FAIL`. vkd3d reports `Cannot load DXIL conversion library`. | `test_shader_gate`, same host | Class A; DXIL needs the D3DMetal backend under CrossOver |
|
||||
| `[WaveSize(64)]` kernels and kernels with SM 6.6 64-bit atomics are created but never run on D3DMetal. | [D3DMetal GPU limits](../research/d3dmetal-gpu-limits.md#measured-constraints) (#453) | Apple M3 Pro, Wine 11.0 source build, D3DMetal 4.0b3; class A for that host |
|
||||
| DXC records `[WaveSize(64)]` as `PSV0` lanes 64/64, and 64-bit atomics on typed resources as `SFI0` `0x400000`. 64-bit atomics on raw buffers set only `INT64_OPS` (`0x8000`), the same as other 64-bit integer use. | The #453 blobs, read by the gate and by a script | Class A |
|
||||
| Public sources do not establish a console-native shader container layout. BetterXen's `FSPX` is a clean-room synthetic layout, not a description of a console compiler's format. | `CLAIM-XBOX-ISA-ABI` (class U) in [claims.toml](../claims.toml); `shader-transpiler/crates/dxbc-accc/src/fspx.rs` | Source review |
|
||||
| A serialized console pipeline path exists for Series X\|S, with no public version-independent format. | `CLAIM-XBOX-ACO-SAMPLE` (class D) | Source review |
|
||||
|
||||
No measurement of a title's shader corpus exists or is planned. BetterXen runs only original synthetic programs, so the DXIL vs. ACCC mix of real titles is unknown. Wherever the gate runs, its `shader_gate` records count it.
|
||||
|
||||
## Decision
|
||||
|
||||
Branch **D1** is proposed for M3:
|
||||
|
||||
1. **Pass DXIL through the gate to D3DMetal.** This is the only path with measured, end-to-end execution evidence.
|
||||
2. **Spend M3 shader work on the two measured gaps,** within the [D3DMetal GPU limits](../research/d3dmetal-gpu-limits.md#measured-constraints):
|
||||
- lower `WaveSize(64)` programs to 32-lane code;
|
||||
- lower SM 6.6 64-bit atomics to 32-bit operations or bounded lock emulation.
|
||||
|
||||
The gate's `shader_d3dmetal_gap` records show which pipelines need this.
|
||||
3. **Keep refusing ACCC-only containers** with `E_NOTIMPL` and a structured log.
|
||||
|
||||
Branch **D2** is deferred. It needs a documented, lawfully available description of console-compiled containers and their RDNA 2 code, and none exists (`CLAIM-XBOX-ISA-ABI`). A translator built against the synthetic `FSPX` layout would prove nothing about real inputs.
|
||||
|
||||
Revisit this ADR in any of these cases:
|
||||
- an authorized public source for that format appears;
|
||||
- gate telemetry from a lawful workload shows ACCC-only containers in practice;
|
||||
- D3DMetal starts running the gap cases.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Pipeline creation:** `CreateComputePipelineState` and `CreateGraphicsPipelineState` now depend on `bx_shader_bridge.dll` for classification. Without it, they still work, refuse ACCC-only containers, and say so in the log.
|
||||
- **Packaging:** `scripts/build-shims.sh` builds the bridge, links it with `abi/defs/bx_shader_bridge.def`, and stages it in `build-shims/bin` beside `d3d12_xs.dll` (#484).
|
||||
- **Not covered by the gate yet:**
|
||||
- **Stream PSOs:** `ID3D12Device2::CreatePipelineState` stream descriptions are still forwarded unparsed.
|
||||
- **Raw-buffer 64-bit atomics:** these cannot be flagged from `SFI0`; the DXIL bitcode would have to be read.
|
||||
- **Telemetry summary:** `bx-cli trace` now summarizes the gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list with its wave-width and 64-bit-atomic flags, and `shader_bridge_missing`. The summary only reflects records a run actually wrote; it adds no live run and no new compatibility claim.
|
||||
- **Wave size:** the gate logs constraints but changes no shader. A pipeline that D3DMetal creates but does not run still behaves that way.
|
||||
|
||||
## Not claimed
|
||||
|
||||
Nothing here describes any Xbox title's shaders, behaviour on Xbox hardware, or D3DMetal versions other than those named. Evidence class: local Apple Silicon runs and public-source review.
|
||||
@@ -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; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders |
|
||||
| `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 |
|
||||
@@ -25,7 +25,7 @@ BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-bas
|
||||
## Milestones (M0 → M6)
|
||||
|
||||
1. **M0 — Repo, ABI & Cross-Build:** One-command ARM64 + x86-64 PE32+ build, export verification, and `test_veh_clwb.exe` passing under CrossOver + Rosetta 2 (`ROSETTA_ADVERTISE_AVX=1`).
|
||||
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) load cleanly; auto-logging COM proxy captures startup call traces.
|
||||
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 16 shim DLLs load cleanly; auto-logging COM proxy captures startup call traces.
|
||||
3. **M2 — First Frame & Shader Format Gate:** Present real frames through D3DMetal 3.0 (`PresentX` → `IDXGISwapChain3::Present`) and classify runtime shaders (`DXIL` fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation).
|
||||
4. **M3 — Full Shaders, Streaming & Texture Correctness:** Async DirectStorage decompression, accurate RDNA 2 `xg_xs` tiling/deswizzling, full shader pipeline.
|
||||
5. **M4 — 3D World, Ray Tracing & Input:** BVH4 rehydration → live D3DMetal 3.0 DXR build, FidelityFX/MetalFX upscaling shim, full `GameInput` controller/KB/M mapping.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Clean-room scope
|
||||
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation.
|
||||
|
||||
## User-provided game files
|
||||
|
||||
|
||||
@@ -2,6 +2,14 @@
|
||||
|
||||
The workspace is GPL-3.0-or-later. The following is the lead's preliminary compatibility inventory. The independent license audit is pending.
|
||||
|
||||
## Active hybrid launcher
|
||||
|
||||
The migrated `bx-cli` uses only `libc` 0.2.191 as an external Rust dependency (revision `ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`, MIT selected). Its MIT notice was read at the locked source and is compatible with GPL-3.0-or-later; source and notices are retained in private bundles. Rust 1.100.0, llvm-mingw 20261117 and optional Microsoft DXC v1.9.2609 are external build tools. Their compiler/runtime notices remain applicable to compiled output and are preserved as described in [third-party notices](../THIRD_PARTY_NOTICES.md).
|
||||
|
||||
The native-first dependency inventory and redistribution discussion below are historical, preserved for the retired code at `native-first-final`. Those objc2/native graphics packages are not dependencies of the active hybrid launcher.
|
||||
|
||||
## Historical native-first inventory
|
||||
|
||||
| Component | Version and upstream revision | License used | Scope |
|
||||
|---|---|---|---|
|
||||
| objc2 | 0.6.5, `d7d2fa23ceaa5e6096c923b081040e5d81b3b9df` | MIT | Runtime bindings |
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
# Maintainer testing guide
|
||||
|
||||
How to build and independently test the supervised hybrid runtime and its Direct3D
|
||||
workloads (issue #407). The workloads are original Windows programs. Passing them shows
|
||||
narrow Windows API behaviour under CrossOver on one Mac. It says nothing about Xbox
|
||||
software, game compatibility or performance, and no maintainer has reproduced these
|
||||
results yet.
|
||||
|
||||
The D3D11 and D3D12 workloads are Track F acceptance inputs for the launcher. They are not a
|
||||
second graphics pipeline and do not exercise the `d3d12_xs` shim.
|
||||
|
||||
`bx-cli` has been run only against CrossOver 26.3 (26.3.0.39832). On any other build `run` and
|
||||
`bench` refuse to start unless given `--allow-untested-crossover`, and `doctor` reports
|
||||
`crossover_build_tested: false`. `stop` is never refused.
|
||||
|
||||
## What has been run
|
||||
|
||||
On commit `7451f0f2ae27b19313015d1ee529b69a755ef12f`, from an existing checkout rebuilt with
|
||||
`build-maintainer.sh`, on one Apple M4 with CrossOver 26.3, by the author's coding agent.
|
||||
This is not independent verification.
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| fmt, clippy, tests | clean; 109 passed, 0 failed, 1 ignored (opt-in live D3DMetal test) |
|
||||
| Shim build | 16 DLLs, 102 exports |
|
||||
| `test_*.exe` fixtures, through `--bottle` and `--prefix` | passed, except `test_veh_unhandled.exe`, which crashes on purpose |
|
||||
| Full acceptance suite | exit 2: 50 `ok`, 2 `KNOWN`, 0 `FAIL`, 0 `NOT-RUN` |
|
||||
| On-screen capture checks | passed |
|
||||
|
||||
The two `KNOWN` lines are the D3D12 swapchain retention below. A clean-clone run and a
|
||||
private-bundle run were last done on earlier source, before `main` was merged.
|
||||
|
||||
`main` at `02b8924` (`xmem` physical pages) was merged afterwards. The Rust checks, shim
|
||||
build and all fixtures, now including `test_xmem_physical.exe`, were rerun with the same
|
||||
results; the full acceptance suite was not.
|
||||
|
||||
After merging `main` at `bfa80de` (`bx-cli trace` reporting), the Rust checks (113 passed, 0
|
||||
failed, 1 ignored), shim build and the shim export, CLWB and crash fixtures with their traces
|
||||
were rerun.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Apple Silicon Mac. Developed on an M4 with 24 GB and macOS 27; nothing else was tried.
|
||||
- CrossOver 26.3 installed from CodeWeavers, and Rosetta 2. Neither is bundled.
|
||||
- Xcode command line tools, `rustup`, Python 3.12 or newer.
|
||||
- For the shim superbuild: `brew install mingw-w64 cmake`.
|
||||
- At least 50% free memory (`memory_pressure -Q`) for the whole run. The runner refuses to
|
||||
start below that; close browsers and other large applications first.
|
||||
- For the on-screen and keyboard checks: a desktop Space in front (not a full-screen app),
|
||||
an unlocked display, and Screen Recording and Accessibility permission for the terminal.
|
||||
Do not type while the keyboard check runs.
|
||||
|
||||
## Build
|
||||
|
||||
From a fresh clone of the branch under test:
|
||||
|
||||
```sh
|
||||
TC=$(scripts/hybrid/install-dependencies.sh) # pinned llvm-mingw and Rust 1.100.0
|
||||
DXC=$(python3 scripts/hybrid/install-dxc.py) # pinned Microsoft DXC, for Shader Model 6
|
||||
export RUSTUP_TOOLCHAIN=1.100.0-aarch64-apple-darwin
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
scripts/build-shims.sh # 16 shim DLLs, 102 exports
|
||||
scripts/hybrid/build-maintainer.sh "$TC" # arm64 bx-cli and workloads
|
||||
BX=$PWD/artifacts/maintainer/bin/bx-cli
|
||||
```
|
||||
|
||||
Both installers download over the network, check a pinned SHA-256 and refuse to overwrite
|
||||
an existing installation.
|
||||
|
||||
## Run
|
||||
|
||||
Use a new bottle that nothing else uses. Stopping a run stops everything in its bottle.
|
||||
|
||||
```sh
|
||||
python3 scripts/hybrid/create-test-bottle.py "$BX" betterxen-maintainer-test
|
||||
"$BX" doctor --bottle betterxen-maintainer-test
|
||||
```
|
||||
|
||||
Shim fixtures (an explicit Wine prefix, separate from the bottle):
|
||||
|
||||
```sh
|
||||
for t in test_veh_clwb test_shim_exports; do
|
||||
"$BX" run --prefix "$PWD/artifacts/m0-prefix" --shims build-shims/bin \
|
||||
--log "$PWD/artifacts/m0-shim.jsonl" --exe build-shims/bin/$t.exe
|
||||
done
|
||||
"$BX" trace artifacts/m0-shim.jsonl # expect "clwb VEH traps : at least 4 (sampled)", ADX 0
|
||||
```
|
||||
|
||||
Full acceptance (Direct3D 12 and 11 workloads, negative controls, lifecycle, soak):
|
||||
|
||||
```sh
|
||||
BETTERXEN_DXC_DIR="$DXC" scripts/hybrid/accept-integrated.sh "$TC" betterxen-maintainer-test
|
||||
```
|
||||
|
||||
Each line is `ok`, `FAIL`, `KNOWN` or `NOT-RUN`. Records, logs and `summary.json` are
|
||||
written under `artifacts/acceptance/<timestamp>/`.
|
||||
|
||||
| Exit status | Meaning |
|
||||
| --- | --- |
|
||||
| 0 | Every check ran and passed |
|
||||
| 1 | At least one check failed |
|
||||
| 2 | No failures, but the known D3D12 retention was seen or a check did not run |
|
||||
|
||||
On CrossOver 26.3 with D3DMetal, 2 is the best result available today.
|
||||
|
||||
## See the graphics
|
||||
|
||||
```sh
|
||||
"$BX" run --bottle betterxen-maintainer-test -- \
|
||||
"$PWD/artifacts/maintainer/workloads/d3d12-integrated.exe" --frames 128 --hold-ms 15000
|
||||
```
|
||||
|
||||
A small window titled "BetterXen D3D12 workload" appears on a black background:
|
||||
|
||||
- a 16-row purple band across the top (the frame number, encoded as a colour);
|
||||
- an upper-left square split into green, blue (top) and red, white (bottom);
|
||||
- a lower-right square split into cyan, magenta (top) and yellow, grey (bottom),
|
||||
overlapping the first and drawn in front of it.
|
||||
|
||||
The command then reports `failed_exit_1` with only the `shutdown` gate failed. That is the
|
||||
known issue below, not a broken build. Any other failed gate is a new problem.
|
||||
|
||||
## Package (optional)
|
||||
|
||||
From a clean committed checkout, after `build-maintainer.sh`:
|
||||
|
||||
```sh
|
||||
scripts/hybrid/package-maintainer.sh
|
||||
```
|
||||
|
||||
It writes `artifacts/packages/betterxen-maintainer-<commit>.tar.gz` and its SHA-256. The
|
||||
bundle contains `bx-cli`, the original workloads, source and licence notices. On another
|
||||
Mac: check the SHA-256, unpack, and run `./test.sh NEW_BOTTLE_NAME` (set
|
||||
`BETTERXEN_DXC_DIR` to include Shader Model 6). The binaries are not signed or notarized.
|
||||
|
||||
## Known limitations
|
||||
|
||||
- **API-set bridge shims (#437).** Under CrossOver, statically imported `api-ms-win-*` and
|
||||
`ext-ms-win-*` names are answered by Wine, not by the `win32_bridge` shims.
|
||||
- **Bottle settings.** `[EnvironmentVariables]` in a bottle apply over variables given with
|
||||
`--env`; only `--backend` and DLL overrides are protected from this.
|
||||
- **Intermittent D3D11 control stall.** One 20,000-frame soak stopped after 9,183 frames
|
||||
because a GPU event query did not complete within 10 s. Three reruns passed. The cause is
|
||||
unknown. The two D3D12 soaks of the same length did not show it.
|
||||
- **Keyboard negative control.** It failed once inside a full run and passed twice on its
|
||||
own. The cause of that one failure was not captured.
|
||||
- **D3D12 swapchain retention (D3DMetal).** A new swapchain starts with two references and
|
||||
survives the application's release, with no application GPU work. The same binary on the
|
||||
`vkd3d` path starts with one and is freed. Observed on one Mac; the cause inside D3DMetal
|
||||
is unknown and BetterXen has no mitigation. Programs that recreate swapchains will grow.
|
||||
- **D3D12 on the `wined3d`/`dxvk` settings (`vkd3d`).** After about 437 frames every
|
||||
`Present` takes 2000 ms and teardown hangs. A 2000 ms wait in public Wine DXGI source is
|
||||
a likely explanation, not a confirmed one. Use the default D3DMetal path for D3D12.
|
||||
- The earlier two-hour D3D12 run presented 844,497 frames with no mismatch in the verified
|
||||
frames, but failed the shutdown gate. It used a pre-migration build, so it does not
|
||||
certify this one.
|
||||
- Double-precision shader operations are not exercised.
|
||||
- Pixel checks read back what was handed to `Present`. Only the window-capture checks
|
||||
observe the macOS compositor.
|
||||
|
||||
## Security limits
|
||||
|
||||
A bottle or prefix is not a sandbox. A Windows program started this way can read and write
|
||||
your files and use the network. `bx-cli` passes only a short list of environment variables
|
||||
(`--inherit-env` opts out), supervises time, output and memory, and stops the selected
|
||||
environment. Run only programs you trust.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Action |
|
||||
| --- | --- |
|
||||
| `refused_to_start_low_memory` | Free memory and rerun; do not run other heavy work alongside |
|
||||
| `bottle has an active BetterXen runner` | Stop that runner with Ctrl-C or SIGTERM |
|
||||
| `bottle has an unfinished session` | `bx-cli stop --bottle NAME` (or `--prefix PATH`) |
|
||||
| `the window exists but is not on the active Space` | Bring a desktop to the front and rerun |
|
||||
| `NOT-RUN Shader Model 6` | Install DXC and set `BETTERXEN_DXC_DIR` |
|
||||
| Crash control reports `timed_out` | Wine's crash dialog is waiting for a click. Create the bottle with `create-test-bottle.py`, which turns it off |
|
||||
|
||||
## Clean up
|
||||
|
||||
Stop any run with `bx-cli stop --bottle NAME`, then delete the test bottle from CrossOver.
|
||||
Build output lives in `artifacts/`, `target/` and `build-shims/` inside the checkout;
|
||||
installers use `~/Library/Caches/BetterXen/`.
|
||||
@@ -20,9 +20,5 @@ 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). |
|
||||
| Public PC DirectStorage interface definitions (IIDs, structs, vtable order) | `dstorage.h` and `dstorageerr.h` from NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0 (MIT per file) | **Vendor unmodified** (#483) | MIT notices kept in the files, with `LICENSE-CODE.txt` alongside and in `THIRD_PARTY_NOTICES.md`. Only the headers are used; the package's DLLs and other files fall under Microsoft's proprietary SDK terms and are never redistributed. |
|
||||
| Xbox console DirectStorage interfaces (`IDStorageFactoryX` and others) | `dstorage_xs.h` (GDK with Xbox Extensions) | **Rejected until a licence-compatible source exists** (#483) | Available only to licensed partners. Microsoft Learn and the MIT `Xbox-GDK-Samples` `dstorage_win32.h` document signatures and struct layouts but not the IIDs. |
|
||||
| GDK `QueryApiImpl` class and interface ids, inheritance and slot order for XGameSave and XPackage | xodus-gaming/xgameruntime-docs at `7090008` (GPL-3.0 text) | **Use as factual reference, pending maintainer provenance acceptance** (#468, #492) | Only interface facts are used, written as BetterXen's own code; no text or code is copied. The source describes its method as black-box reverse engineering under Wine's clean-room guidelines. `IXError` slot 3's `false` answer comes from the #492 review's interop observation instead; that source lists the slot as unknown. Revisit if the source's method or licence status changes. |
|
||||
|
||||
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.
|
||||
@@ -1,169 +0,0 @@
|
||||
# D3DMetal and Apple GPU limits for a shader translator
|
||||
|
||||
Constraints that a translator emitting shaders for D3DMetal on Apple Silicon has to
|
||||
handle (#453). Writing the translator is out of scope.
|
||||
|
||||
The note has two parts:
|
||||
|
||||
- [Measured constraints](#measured-constraints) come from
|
||||
`tests/conformance/test_d3dmetal_gpu_limits`, an original synthetic D3D12 compute
|
||||
fixture checked against values computed on the CPU. These are the only items the
|
||||
roadmap links to. They are a local Apple Silicon run by the implementer, class A for
|
||||
the stated host only, not independently reproduced.
|
||||
- [Unverified reports](#unverified-reports-not-evidence) are observations a contributor
|
||||
posted on #453 from local builds of another project running a commercial title. They are
|
||||
**not evidence** under [AGENTS.md](../../AGENTS.md) §5–6 and must not steer the plan
|
||||
until a synthetic workload reproduces them. They are kept only as leads for writing such
|
||||
workloads.
|
||||
|
||||
Nothing here is an Xbox hardware result, and nothing generalizes beyond the D3DMetal
|
||||
version named.
|
||||
|
||||
## Measured constraints
|
||||
|
||||
### `WaveSize(64)` is created but not run
|
||||
|
||||
`wave.control` (no `WaveSize`) and `wave.wavesize64` (`[WaveSize(64)]`, SM 6.6) record,
|
||||
for each thread, the wave width, its lane index and the dispatch index of its wave's first
|
||||
lane.
|
||||
|
||||
The control passes the check D3D12 actually guarantees: every thread reports the same
|
||||
width, and within each wave the lane indices are a permutation of `0..W-1`. No particular
|
||||
thread-to-lane order is assumed. On D3DMetal 4.0b3:
|
||||
|
||||
- the device reports `WaveLaneCountMin = WaveLaneCountMax = 32`;
|
||||
- the control runs at width 32;
|
||||
- the wave64 pipeline is **created without error but never runs**: its output buffer keeps
|
||||
the sentinel.
|
||||
|
||||
So a translator cannot rely on pipeline creation failing. A program written for a 64-lane
|
||||
wave has to be emitted as 32-lane code, with its two halves made to agree wherever the
|
||||
original wave acted as one.
|
||||
|
||||
### Kernels using SM 6.6 64-bit atomics are created but not run
|
||||
|
||||
`atomic64.image` runs a 64-bit `InterlockedAdd` (low halves carrying into the high half)
|
||||
and an `InterlockedMax` (decided by the high half) on a `RWTexture2D<uint64_t>` over
|
||||
`DXGI_FORMAT_R32G32_UINT`. `atomic64.buffer` runs the same operations on a raw buffer. Each
|
||||
kernel also writes a plain 64-bit marker next to its atomics, which shows whether the kernel
|
||||
ran at all. On D3DMetal 4.0b3:
|
||||
|
||||
- The device reports `AtomicInt64OnTypedResourceSupported` and
|
||||
`AtomicInt64OnDescriptorHeapResourceSupported` as supported, and both pipelines are
|
||||
created without error.
|
||||
- Neither kernel runs. The atomic results and the markers all read back as their initial
|
||||
zeros, on the texture and on the raw buffer alike.
|
||||
- A throwaway variant with the atomics removed but the markers kept wrote 8/8 markers.
|
||||
That shows the readback path is sound and the skip comes from the atomics.
|
||||
|
||||
So these kernels are silently skipped, on raw buffers as well as images. This is
|
||||
consistent with d3dmetal-native's `d3d12-atomic64-test` reading back zeros in the
|
||||
[d3dmetal-harness](../../shader-transpiler/crates/d3dmetal-harness/README.md) evaluation
|
||||
on D3DMetal 3.0. A translator has to lower 64-bit atomics to 32-bit operations.
|
||||
|
||||
### Lock-based emulation needs a sufficient retry cap and both fences
|
||||
|
||||
`lock64.cap64` and `lock64.cap1024` emulate both operations with a per-texel lock word,
|
||||
with 32 contending threads per texel and a bounded number of tries:
|
||||
|
||||
1. take the lock with `InterlockedCompareExchange` 0→1;
|
||||
2. `DeviceMemoryBarrier()` (**acquire**: the data reads are ordered after taking the lock;
|
||||
`globallycoherent` gives visibility, not ordering);
|
||||
3. update the two 32-bit halves;
|
||||
4. `DeviceMemoryBarrier()` (**release**);
|
||||
5. free the lock with `InterlockedExchange`.
|
||||
|
||||
A thread that runs out of tries counts a drop instead of spinning on. The 1024-try run is
|
||||
required to drop nothing and to match the CPU reference exactly. The 64-try run is
|
||||
reported. On D3DMetal 4.0b3, in three runs each:
|
||||
|
||||
- **1024 tries:** nothing dropped, 16/16 values exact, about 15,000–18,000 tries in all.
|
||||
- **64 tries:** 96–108 of 512 updates dropped.
|
||||
|
||||
So a low cap trades a hang for silently lost updates. With 32 contending threads, 64 tries
|
||||
is already too low.
|
||||
|
||||
The loop shape matters. The critical section sits **inside** the retry loop, so a lane
|
||||
that wins finishes it in the same iteration, and no lane waits for another lane to leave a
|
||||
loop. The fixture does not run the classic shape (`while (!acquire()) {}` followed by the
|
||||
critical section). There, the winning lane can be parked at the loop's reconvergence point
|
||||
behind the lanes still spinning, and on a GPU without independent forward progress for
|
||||
each thread that could hang the queue. Apple's shader converter prints `Warning:
|
||||
Undefined: Shader might rely on forward progress/persistent thread` even for the safe
|
||||
shape.
|
||||
|
||||
## Fixture results
|
||||
|
||||
A local run by the implementer on 2026-11-26. Class A for this host only; not
|
||||
independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Host | Apple M3 Pro, macOS 27.2.1 (26B131), Rosetta 2 |
|
||||
| Wine | CodeWeavers Wine 11.0 built from CodeWeavers' published source; CrossOver itself was not installed |
|
||||
| D3DMetal | 4.0b3 from Apple's Game Porting Toolkit (x86_64; SHA-256 of the binary starts with `b16aab78127d`), user-supplied |
|
||||
| Shaders | DXC 1.9.2609 via `shaders/compile.sh`; the same DXC reproduces the d3dmetal-harness `fill_cs66` container byte for byte (SHA-256 `7df11b63…`) |
|
||||
| Command | `ROSETTA_ADVERTISE_AVX=1 WINEDLLOVERRIDES="d3d12,d3d12core,dxgi=b" wine build-shims/bin/test_d3dmetal_gpu_limits.exe` in a fresh prefix |
|
||||
| Runs | 3, identical outcomes apart from the 64-try drop counts; exit 0, `SUMMARY: 4 required checks, 0 failed` each time |
|
||||
|
||||
| Check | Outcome |
|
||||
| --- | --- |
|
||||
| `device.shader_model` | 6.6 (the fixture skips with exit 77 below 6.6) |
|
||||
| `wave.reported` | `WaveOps=1`, lane count min 32, max 32 |
|
||||
| `wave.control` | ran at width 32, lanes a permutation within each wave (required: pass) |
|
||||
| `wave.wavesize64` | created but not run (output still sentinel) |
|
||||
| `atomic64.reported` | typed and descriptor-heap 64-bit atomics reported as supported |
|
||||
| `atomic64.buffer` | not run: marker 0/8, atomic values 16/16 still zero |
|
||||
| `atomic64.image` | not run: marker 0/8, atomic values 16/16 still zero |
|
||||
| `lock64.cap64` | 108, 96 and 108 of 512 updates dropped (values not compared) |
|
||||
| `lock64.cap1024` | 0 of 512 dropped, 16/16 values exact (required: pass) |
|
||||
|
||||
Still to do for the issue's validation requirement: an independent run on CrossOver 26.3
|
||||
(D3DMetal 3.0) by another contributor.
|
||||
|
||||
## Unverified reports (not evidence)
|
||||
|
||||
Reported on #453 from local VIctory-macOS-based builds running a commercial title on one
|
||||
host. None of this is a BetterXen measurement, no code or shader from that project is
|
||||
used, and none of it may be cited by the roadmap or a milestone gate. Each item names the
|
||||
synthetic workload that would turn it into evidence.
|
||||
|
||||
- **Splitting wave64 programs.** Operations that need care when the two halves must agree:
|
||||
- wave reductions;
|
||||
- first-lane and indexed lane reads;
|
||||
- the 64-bit lane mask read as data;
|
||||
- cross-half permutes;
|
||||
- scalar values spilled into vector lanes;
|
||||
- group barriers, which are only safe where both halves provably reach them.
|
||||
|
||||
The reporter found a uniformity analysis of the program's values, with barriers placed
|
||||
only after uniform branches, made most such programs translate exactly. Where agreement
|
||||
cannot be proven and each half runs as its own wave, a group sync that not every lane
|
||||
reaches must become a memory fence without the group wait. *Workload needed:* SM 6.6
|
||||
wave64-style kernels with each of these patterns, checked half by half.
|
||||
- **Helper lanes in a spin lock.** In a pixel shader, helper lanes must not take part in
|
||||
such a lock: their atomics have no effect, so they never win and spin to the cap. This
|
||||
was reported as a hard queue hang with no macOS GPU timeout logged. A cap of 2^16 was
|
||||
reported to hang while 2^10 did not; whether the cap or the helper lanes caused it was not
|
||||
separated. *Workload needed:* a pixel shader with a lock-protected 64-bit update across
|
||||
triangle edges.
|
||||
- **Mesh output size.** Metal refuses mesh pipelines whose per-vertex outputs exceed 32,768
|
||||
bytes, counting the aligned layout (distances, position, then outputs in register order,
|
||||
each aligned to its own size). A refused pipeline submitted anyway was reported to hang
|
||||
the queue under Wine. *Workload needed:* mesh shaders whose output size crosses 32 KiB
|
||||
only once alignment is counted.
|
||||
- **Apple shader compiler crash.** `MTLCompilerService` was reported to crash in register
|
||||
allocation on mesh pipelines whose pixel shader writes several render targets. The
|
||||
reported cause was output stores merged before all their values are defined, and the
|
||||
reported fix was emitting each output row's stores after its values. *Workload needed:* a
|
||||
mesh and pixel pair with several render targets and late-computed outputs.
|
||||
- **No zero-copy heaps.** D3DMetal 4.0b3 was reported to answer
|
||||
`ID3D12Device3::OpenExistingHeapFromAddress` with "Not implemented". *Workload needed:*
|
||||
a fixture that calls it on a page-aligned allocation.
|
||||
|
||||
## Regenerating the shaders
|
||||
|
||||
`tests/conformance/test_d3dmetal_gpu_limits/shaders/compile.sh` regenerates the committed
|
||||
headers with Microsoft's DXC release v1.9.2609 (`dxc_2026_09_29.zip`, SHA-256
|
||||
`ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1`, the same package the
|
||||
d3dmetal-harness records), running `bin/x64/dxc.exe` under a Wine loader.
|
||||
@@ -1,88 +0,0 @@
|
||||
# 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. See the independent Apple M2 Pro run below.
|
||||
|
||||
| | 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.
|
||||
|
||||
## Independent run on Apple M2 Pro
|
||||
|
||||
On 2026-11-26, an Apple M2 Pro (16 GiB, macOS 27.3 build 26C5035r) reproduced
|
||||
the swapchain retention in CrossOver 26.3.0.39832 with D3DMetal 3.0. The
|
||||
same x86-64 probe under Rosetta 2 released all swapchains in CrossOver
|
||||
Preview 27.0.0.41303. Each CrossOver build used a fresh Windows 11
|
||||
64-bit bottle. The Direct3D 12 workload loaded the `apple_gptk` D3D12
|
||||
and DXGI modules in both builds. The bundled framework in the Preview
|
||||
build's `apple_gptk` directory reports version 4.0b3.
|
||||
|
||||
| Swapchain lifetime probe | Initial reference count | Application release returned | Witnesses retained |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| 26.3 D3DMetal | 2 | 1 | 12 of 12 |
|
||||
| 26.3 Wine D3D12 | 1 | 0 | 0 of 12 |
|
||||
| Preview D3DMetal | 1 | 0 | 0 of 12 |
|
||||
| Preview Wine D3D12 | 1 | 0 | 0 of 12 |
|
||||
|
||||
Destroying the window before releasing the swapchain and calling
|
||||
`ResizeBuffers` before teardown each left 3 of 3 witnesses retained on
|
||||
26.3 D3DMetal. Explicitly detaching the witness released the probe's
|
||||
private data, while the swapchain's release still returned 1. The
|
||||
deliberately retained witness control failed as expected. An extra
|
||||
application-side `Release` would drop a reference the application
|
||||
does not own.
|
||||
|
||||
The separate D3D12 integrated workload presented 600 frames and verified
|
||||
eight readbacks with zero mismatches on both D3DMetal builds. It failed
|
||||
only the shutdown gate on 26.3, where the final device release returned
|
||||
2. Preview passed shutdown with a final device release of 0. These runs
|
||||
used the direct host D3D12 path without BetterXen's D3D12 shim. The
|
||||
comparison establishes behavior for these two CrossOver builds on this
|
||||
host. The underlying ownership change is unknown.
|
||||
|
||||
Build the probe from the pinned source linked above with
|
||||
`x86_64-w64-mingw32-clang -std=c11 -O2 -Wall -Wextra -Werror lifetime.c -o d3d12-lifetime.exe -ld3d12 -ldxgi -ldxguid -luser32`
|
||||
(LLVM-MinGW 20261117 in this run). Run in a clean bottle using
|
||||
`ROSETTA_ADVERTISE_AVX=1 CX_GRAPHICS_BACKEND=d3dmetal wine --bottle <bottle> <absolute-path-to-exe> --cycles 12`
|
||||
and repeat with `CX_GRAPHICS_BACKEND=wined3d`. The two witness controls
|
||||
use `--cycles 3 --detach-witness` with and without `--retain-app-reference`.
|
||||
|
||||
## Related Direct3D acceptance failures
|
||||
|
||||
The [integrated D3D12 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_integrated/integrated12.c)
|
||||
also reproduced the presentation slowdown on the Wine D3D12 path on
|
||||
26.3. With `CX_GRAPHICS_BACKEND=wined3d` and a 600-frame target, the
|
||||
workload logged approximately 2,000 ms inside `Present` on frames
|
||||
12–38, then exited 3 after a 10-second GPU completion wait failed. The
|
||||
previous M4 report saw the slowdown around frame 437. This run exited
|
||||
before reaching normal teardown. Preview completed the same 600-frame
|
||||
workload on the Wine path with eight verified readbacks, no mismatches
|
||||
and clean shutdown. A 600-frame repeat on 26.3 passed with `--vsync`
|
||||
enabled. A subsequent 600-frame repeat also passed with the flag off,
|
||||
so the slowdown remains intermittent and the successful vsync run
|
||||
does not establish a workaround.
|
||||
|
||||
The [integrated D3D11 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d11_integrated/integrated.c)
|
||||
completed the 20,000-frame soak on 26.3 with 46 verified readbacks,
|
||||
zero mismatches and a clean shutdown. The intermittent GPU event
|
||||
stall did not recur in this run. Preview also completed all 20,000
|
||||
frames and all 46 readbacks, then failed the shutdown gate with one
|
||||
device reference remaining. A separate 600-frame Preview run
|
||||
reproduced that shutdown result.
|
||||
|
||||
The 26.3 keyboard check delivered five macOS events to the workload and
|
||||
reached the expected offset (16, 32). The negative control delivered
|
||||
two Up events and reached (0, -32), which the input gate rejected as
|
||||
expected. These were isolated runs, so they do not reproduce the
|
||||
intermittent failure observed inside the full acceptance suite.
|
||||
@@ -0,0 +1,196 @@
|
||||
{
|
||||
"evidence_class": "D",
|
||||
"observed_date_local": "2026-11-25",
|
||||
"scope": "Public repository accessibility/head metadata only; authenticated private repository metadata remains in ignored local evidence. Source review scope is separate.",
|
||||
"repositories": [
|
||||
{
|
||||
"repo": "MacosPorters/VIctory-macOS",
|
||||
"url": "https://github.com/MacosPorters/VIctory-macOS",
|
||||
"branch": "main",
|
||||
"head": "d6fc0620f53a5c9073b9d08d0910c8d6aa5d0bdf",
|
||||
"license": "GPL-3.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "pragyaangaur/VIctory-macOS",
|
||||
"url": "https://github.com/pragyaangaur/VIctory-macOS",
|
||||
"branch": "main",
|
||||
"head": "b6dd0b184277fc307b93a4cc90d23dca9f05e7b3",
|
||||
"license": "GPL-3.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "utmapp/d3dmetal-native",
|
||||
"url": "https://github.com/utmapp/d3dmetal-native",
|
||||
"branch": "main",
|
||||
"head": "af1ee1710711fadff41dead87960d0f1336c1047",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "ProhorovIlja/NativeX-Runtime",
|
||||
"url": "https://github.com/ProhorovIlja/NativeX-Runtime",
|
||||
"branch": "main",
|
||||
"head": "b3087ce0ab191227dc9e7af37cab97a0b097bb98",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "wine-mirror/wine",
|
||||
"url": "https://github.com/wine-mirror/wine",
|
||||
"branch": "master",
|
||||
"head": "274fcfa9691bf3b7f24c0833ad33e9d57c3df65f",
|
||||
"license": "NOASSERTION",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "doitsujin/dxvk",
|
||||
"url": "https://github.com/doitsujin/dxvk",
|
||||
"branch": "master",
|
||||
"head": "6e25a5e7af5a05e5729e7abc5bf1184df9242e2a",
|
||||
"license": "Zlib",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "HansKristian-Work/vkd3d-proton",
|
||||
"url": "https://github.com/HansKristian-Work/vkd3d-proton",
|
||||
"branch": "master",
|
||||
"head": "71cae091b06571e51446cf2a937f0b04c237c04d",
|
||||
"license": "LGPL-2.1",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "3Shain/dxmt",
|
||||
"url": "https://github.com/3Shain/dxmt",
|
||||
"branch": "main",
|
||||
"head": "faa73e4a0686e432ce5d3bb99a02b5363d76885c",
|
||||
"license": "NOASSERTION",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "KhronosGroup/MoltenVK",
|
||||
"url": "https://github.com/KhronosGroup/MoltenVK",
|
||||
"branch": "main",
|
||||
"head": "5189f8de86ec365860f63bf1da736815cfaea5cd",
|
||||
"license": "Apache-2.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "llvm/llvm-project",
|
||||
"url": "https://github.com/llvm/llvm-project",
|
||||
"branch": "main",
|
||||
"head": "0cae57720c3ca7cb09b5ba48d199f1ba04e3aae2",
|
||||
"license": "NOASSERTION",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "mstorsjo/llvm-mingw",
|
||||
"url": "https://github.com/mstorsjo/llvm-mingw",
|
||||
"branch": "master",
|
||||
"head": "903f4cf7faa24e30c8e0c4615f8ce61a0f3d80f8",
|
||||
"license": "NOASSERTION",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "microsoft/DirectXShaderCompiler",
|
||||
"url": "https://github.com/microsoft/DirectXShaderCompiler",
|
||||
"branch": "main",
|
||||
"head": "2600ae89a6153302421b13b4db7d3bd1bd0d9385",
|
||||
"license": "NOASSERTION",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "microsoft/DirectX-Graphics-Samples",
|
||||
"url": "https://github.com/microsoft/DirectX-Graphics-Samples",
|
||||
"branch": "master",
|
||||
"head": "68a2b1e97f71642924e74c7757ca21756ad221b5",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "microsoft/DirectX-Headers",
|
||||
"url": "https://github.com/microsoft/DirectX-Headers",
|
||||
"branch": "main",
|
||||
"head": "61c7718954ec73dbdd43c723240fe1a0452a3724",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "microsoft/DirectXTex",
|
||||
"url": "https://github.com/microsoft/DirectXTex",
|
||||
"branch": "main",
|
||||
"head": "a8e5dbf42909aeeb9fcf9c2ae399ae3c06737379",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "KhronosGroup/SPIRV-Cross",
|
||||
"url": "https://github.com/KhronosGroup/SPIRV-Cross",
|
||||
"branch": "main",
|
||||
"head": "57e4efcc84112abcd426dc5ec248b5339bee04f2",
|
||||
"license": "Apache-2.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "gfx-rs/wgpu",
|
||||
"url": "https://github.com/gfx-rs/wgpu",
|
||||
"branch": "trunk",
|
||||
"head": "60cef2be828e03ba54e2e1598001b4625c0c2163",
|
||||
"license": "Apache-2.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "LIEF-project/LIEF",
|
||||
"url": "https://github.com/lief-project/LIEF",
|
||||
"branch": "main",
|
||||
"head": "2a6fdbc5a3af9b7ac797514ca38b1175c78f3fcf",
|
||||
"license": "Apache-2.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "FEX-Emu/FEX",
|
||||
"url": "https://github.com/FEX-Emu/FEX",
|
||||
"branch": "main",
|
||||
"head": "3ee25399232a6431c77c6314c437ea523ec29d0c",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "apitrace/apitrace",
|
||||
"url": "https://github.com/apitrace/apitrace",
|
||||
"branch": "master",
|
||||
"head": "28bb3aba57f3f9df4932867496308f4fc0a2b423",
|
||||
"license": "MIT",
|
||||
"archived": false,
|
||||
"private": false
|
||||
},
|
||||
{
|
||||
"repo": "apple/game-porting-toolkit",
|
||||
"url": "https://github.com/apple/game-porting-toolkit",
|
||||
"branch": "main",
|
||||
"head": "4f42344c90be22112f46becc3fb9687f423f2f88",
|
||||
"license": "Apache-2.0",
|
||||
"archived": false,
|
||||
"private": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
# Runtime integration source review
|
||||
|
||||
This continues the existing [donor audit ledger](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/audit-ledger.tsv), [donor reference assessment](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/reference-projects-2026-11-25.md) and [donor integration audit](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/hybrid-runtime-audit-2026-11-25.md). It does not recertify their execution results. Source review is evidence class D; newly run workloads must have separate execution records. No reference-project implementation was added to BetterXen source. A private bundle includes unmodified source/notices for the already selected libc dependency.
|
||||
|
||||
## Components affecting demonstrated blockers
|
||||
|
||||
| Component and exact revision | Source actually inspected | Finding and integration decision |
|
||||
| --- | --- | --- |
|
||||
| Wine `274fcfa9691bf3b7f24c0833ad33e9d57c3df65f` | `dlls/dxgi/swapchain.c`: D3D12 `Present`, worker presentation, destruction and release functions; LGPL-2.1-or-later header and `COPYING.LIB` | `d3d12_swapchain_present` waits up to 2000 ms on the frame-latency semaphore. The worker releases it after successful Vulkan presentation. This is a testable explanation for two-second frames, not proof of the installed CrossOver failure. Destruction joins the worker, destroys graphics resources and releases the command queue, device and factory. Do not replace CrossOver with this moving upstream head. |
|
||||
| VKD3D-Proton `71cae091b06571e51446cf2a937f0b04c237c04d` | `libs/vkd3d/swapchain.c`: frame-latency wait/signal sites; `COPYING` | Separate internal and application latency events. LGPL-2.1-or-later. This is not proof CrossOver ships this implementation: its official source list names Vkd3d. No integration or performance claim. |
|
||||
| DXMT `faa73e4a0686e432ce5d3bb99a02b5363d76885c` | `src/d3d12/d3d12_swapchain.cpp`: constructor/destructor and latency sites; `LICENSE` | Current source contains D3D12 development code despite older D3D11-only descriptions. Presence is not backend availability in installed CrossOver 26.3. LGPL-2.1-or-later, CodeWeavers attribution. Do not silently substitute an untested build. |
|
||||
| NativeX Runtime `b3087ce0ab191227dc9e7af37cab97a0b097bb98` | Entire `fixtures/native_win_dxgi_multiframe.cpp` and `src/native_upload_arena.cpp`; tiled-resource fixture through its GPU copy/readback path; `LICENSE`, `docs/PUBLIC_SCOPE.md` | MIT at repository root; fixture says original synthetic Win32/WARP work. Multiframe fixture uses explicit pacing and fences, releases per-frame resources before resizing, and disclaims physical-GPU/pixel verification. Upload arena bounds allocations and recycles only completed fence ranges. Windows/WARP assumptions and project-local timing/upload headers prevent treating these as turnkey Mac tests. Historical title-specific planning is disclosed; independent origin is not certified by a licence label. Source-level comparison only; nothing adopted or executed. |
|
||||
| d3dmetal-native `af1ee1710711fadff41dead87960d0f1336c1047` | Prior source/build record reused; no repeat build | See [donor evaluation](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/d3dmetal-native-evaluation.md), including exact dependencies and unverified framework rights. An x86-64 native graphics host does not replace Wine's Windows runtime and does not satisfy BetterXen's ARM64 host rule. No framework extraction, patching or new execution. |
|
||||
|
||||
Primary source links: [Wine swapchain](https://github.com/wine-mirror/wine/blob/274fcfa9691bf3b7f24c0833ad33e9d57c3df65f/dlls/dxgi/swapchain.c), [VKD3D-Proton](https://github.com/HansKristian-Work/vkd3d-proton/blob/71cae091b06571e51446cf2a937f0b04c237c04d/libs/vkd3d/swapchain.c), [DXMT](https://github.com/3Shain/dxmt/blob/faa73e4a0686e432ce5d3bb99a02b5363d76885c/src/d3d12/d3d12_swapchain.cpp), [NativeX fixture](https://github.com/ProhorovIlja/NativeX-Runtime/blob/b3087ce0ab191227dc9e7af37cab97a0b097bb98/fixtures/native_win_dxgi_multiframe.cpp).
|
||||
|
||||
## Shader decision and legitimate compiler path
|
||||
|
||||
The runtime consumes ordinary Windows shaders through CrossOver. `launcher/crates/bx-runtime` has no dependency on the console shader import. #394's compiler therefore solves no demonstrated requirement of this execution path. The complete per-file [independent #399 review](https://github.com/MacosPorters/betterxen/issues/399) and [donor decision proposal](https://github.com/MacosPorters/betterxen/blob/b42133add913297690dbade1941916f4ce0b666a/docs/research/shader-import-decision.md) identify unresolved origin and explicit project-policy exclusions. This candidate excludes #394 and the dependent #395 runner. Passing compiler tests cannot resolve those exclusions; no replacement console compiler is required.
|
||||
|
||||
Only the seven original `tests/conformance/test_d3d12_wave/` files from BetterXen commit `d8c7a398492c483599f02766ebf5707f38dc6128` are retained. The C runner has bounded inputs and releases successful-run resources; the build adds the missing GUID library. Numeric acceptance compares GPU words with independent arithmetic constants and checks a one-bit wrong expectation. Unsupported double precision is not counted as a pass.
|
||||
|
||||
Microsoft DXC is an external open-source **Windows guest build tool**, not a BetterXen x86-64 host executable. The selected release is [v1.9.2609](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.9.2609), asset `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1` (verified against GitHub release metadata). Its LLVM/MIT/Microsoft notices stay with the external installation. No compiler DLL or executable is packaged. Original HLSL and its compiled output are separate from the excluded console compiler. The installer must verify the archive before use.
|
||||
|
||||
The external llvm-mingw pin remains release `20261117`, SHA-256 `98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa`, LLVM commit `5b10d2d74929eae78912771222c9855af97496f4`. Its wrappers are ISC; compiler, builtins, headers and runtime carry their own notices. The universal compiler is run natively on ARM64 and is not distributed. Build notices include the unmodified LLVM and MinGW runtime terms. Rust Windows COFF timestamps are explicitly disabled; source paths are remapped. The original independent #364 build review remains separate from this task.
|
||||
|
||||
## Provenance restrictions and permission scope
|
||||
|
||||
The reachable heads for skakwy/victory-mac and MacosPorters/victory-mac-new remain identical at `3ecbb8f96956513df71343ad9de41aa48b0b8008`. MacosPorters/VIctory-macOS is `d6fc0620f53a5c9073b9d08d0910c8d6aa5d0bdf`; pragyaangaur/VIctory-macOS is `b6dd0b184277fc307b93a4cc90d23dca9f05e7b3`. Existing inventories and permission records are reused. Contributor permission covers only independently owned contributions; it does not clear other contributors' lines or underlying third-party material. No broader permission document was established by this task.
|
||||
|
||||
The current engineering rules require a recorded per-file provenance and licence audit before taking any code or tooling from leaked-build derivatives, and exclude game-, asset- and decryption-specific code. Contributor permission covers only contributions the contributor owns. This candidate takes no additional source from those projects; the inherited Rust memory guard is an attributed conceptual reimplementation from #405, with the original per-component review preserved in its donor audit. The current Track D shader-format gate remains separate from the excluded #394 import. No policy amendment is needed for the current Windows shader probes.
|
||||
|
||||
## Accessibility check and limits
|
||||
|
||||
All 23 requested GitHub repositories were reachable during this task; public heads are saved in the [accessibility snapshot](maintainer-reference-heads.json), with authenticated private metadata kept in ignored local evidence. The existing 84-entry PortWatch inventory was not repeated. Except for the source files identified above, those checks are metadata only, not implementation review. LLVM, llvm-mingw, DXC, DirectX-Headers, DirectXTex, DirectX-Graphics-Samples, SPIRV-Cross, wgpu, LIEF, FEX and apitrace remain available references; none supplies a demonstrated missing loader, translator or backend for this candidate merely by being available.
|
||||
|
||||
The [CodeWeavers source page](https://www.codeweavers.com/crossover/source) publishes `crossover-sources-26.3.0.tar.gz`. This task downloads that official archive for targeted source comparison; downloading is not a rebuilt or validated replacement runtime. CodeWeavers' [graphics documentation](https://support.codeweavers.com/advanced-settings-in-crossover-mac?kb_language=en_US) separates D3DMetal's D3D11/12 support from DXVK's D3D10/11 role. A `dxvk` or `wined3d` selection must not be labelled proof of the active D3D12 implementation.
|
||||
|
||||
Apple's [Metal command execution documentation](https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/Cmd-Submiss/Cmd-Submiss.html) distinguishes submission, completion and presentation. Accordingly, an application fence and matching readback do not establish that pixels reached the compositor; screen capture remains a separate check. None of this establishes Xbox execution, commercial-game compatibility or performance.
|
||||
@@ -14,7 +14,6 @@ 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)
|
||||
|
||||
@@ -26,22 +25,6 @@ Unlike the table above, these entries were cloned at the stated pin, built and r
|
||||
| directx-native | [osy/directx-native](https://github.com/osy/directx-native) | `7258be1c56cdbf1e55c56b1bc4a866169c8ca0da` (pinned by d3dmetal-native's `subprojects/directx-native.wrap`) | Apache-2.0: repository `LICENSE`, plus `SPDX-License-Identifier: Apache-2.0` in 22 of its 25 files | Build dependency of d3dmetal-native, statically linked into the dylib; nothing is copied into BetterXen | Supplies the shared-resource and embedder headers that `d3dmetal_native.h` includes. Apache-2.0 is compatible with GPL-3.0, not GPL-2.0. |
|
||||
| DirectX Shader Compiler | [microsoft/DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.9.2609) | Release `v1.9.2609`, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1` | The package ships the LLVM Release License, an MIT licence and Microsoft Software License Terms (`LICENSE-MS.txt`, covering the closed-source parts of the package) | External tool, used once to compile BetterXen's own HLSL kernel. Only its output (`fill_cs66.h`) is committed. | There is no macOS release, so `bin/x64/dxc.exe` was run under CrossOver 26.3 Wine. It reported `dxcompiler.dll 1.9.2609.5 (01b62ad47)`. |
|
||||
|
||||
## Interface facts for XGameSave and XPackage (#468, #492)
|
||||
|
||||
Facts only, no text or code copied. **Pending maintainer provenance acceptance** under AGENTS.md §4.
|
||||
|
||||
| Project | Source | Pin | License (per file) | Role for BetterXen | Findings |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| xgameruntime-docs | [xodus-gaming/xgameruntime-docs](https://github.com/xodus-gaming/xgameruntime-docs) | `7090008692569aa6081e30dfdd9de58237741e24` | Repository `LICENSE` is the unmodified GNU GPL version 3 text. No project copyright holder is named, nothing states "only" or "or later", and the documentation files checked (`README.md`, `COM/XErrorImpl/IXErrorImpl.md`, `COM/XPackageImpl/IXPackageImpl.md`, `IXPackageImpl2.md`, `XErrorReport.md`) carry no licence or copyright header. | Source of the interface facts behind the public `QueryApiImpl` entries in `shims/xgameruntime/com_dispatch.cpp`: class and interface ids, interface inheritance, and vtable slot order for `IXGameSaveImpl`–`IXGameSaveImpl3` and `IXPackageImpl`–`IXPackageImpl4`. | Its README says the information "was found using black box reverse engineering" following Wine's clean-room guidelines. It states no use of Microsoft binaries, leaked material or the GDK EULA either way, and the COM notes say the listing is incomplete. It lists `IXErrorImpl` slot 3 only as unknown. BetterXen's answer for that slot (return `false`) instead follows an interop observation in the #492 review (2026-11-26), not this repository. Function signatures come from Microsoft Learn. |
|
||||
|
||||
## Vendored for the public PC DirectStorage interfaces (#483)
|
||||
|
||||
Checked on 2026-11-26 by reading the package files, not just its metadata. Not legal advice. Details and file hashes: [`shims/xcrdapi/dstorage/README.md`](../../shims/xcrdapi/dstorage/README.md).
|
||||
|
||||
| Project | Source | Pin | License (per file) | Role for BetterXen | Findings |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| DirectStorage SDK headers | NuGet [`Microsoft.Direct3D.DirectStorage`](https://www.nuget.org/packages/Microsoft.Direct3D.DirectStorage/1.4.0) | `1.4.0`, package SHA-256 `0838e7f71b14acfbd1ac7ecc5e943f6c95e4f4e679e8a67f8ff6e7c102414321` | `native/include/dstorage.h` and `dstorageerr.h` each carry `Copyright (c) Microsoft Corporation` / `Licensed under the MIT license`; the package's `LICENSE-CODE.txt` is the MIT text. The package as a whole is under the proprietary *Microsoft DirectStorage SDK* terms, whose distributables are only `dstorage.dll` and `dstoragecore.dll`. | The two headers are vendored unmodified in `shims/xcrdapi/dstorage/` for the public `IDStorage*` interfaces in `XCRDAPI.dll` and `test_xcrdapi`. No DLL or other package file is used or redistributed. | The headers are not in the MIT `microsoft/DirectStorage` repository; they ship only in this package. Microsoft Learn documents the same API but gives neither IIDs nor vtable order. The Xbox `IDStorage*X` interfaces (`dstorage_xs.h`) ship only in the GDK with Xbox Extensions, "only available to licensed partners", so they are excluded. |
|
||||
|
||||
## Additional candidates found by search (not reviewed)
|
||||
|
||||
Found by GitHub search on 2026-11-25. Only repository metadata was read; none was evaluated, installed or run, and none is a recommendation. Licenses are what GitHub reported.
|
||||
|
||||
+5
-6
@@ -9,8 +9,7 @@ BetterXen builds a modular **Xbox Series (`Scarlett`) compatibility layer for Ap
|
||||
```text
|
||||
BetterXen (in-tree):
|
||||
launcher/ (ARM64 CLI, probe, telemetry) + abi/ (frozen contracts)
|
||||
shims/ (16 cross-compiled x86-64 PE32+ Xbox Game OS DLLs
|
||||
+ the Rust-built bx_shader_bridge.dll)
|
||||
shims/ (16 cross-compiled x86-64 PE32+ Xbox Game OS DLLs)
|
||||
shader-transpiler/ (DXBC / DXIL / ACCC / FSPX classifier & RDNA 2 pipeline)
|
||||
|
|
||||
External Foundation (user-installed, never bundled):
|
||||
@@ -37,10 +36,10 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
|
||||
|
||||
| Milestone | Objective | Exit Gate | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; all 17 PE32+ DLLs (16 mingw-w64 C++ shims + the Rust `bx_shader_bridge.dll`) pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
|
||||
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime` + dynamic loader exports, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, supervised `bx-cli run`, ADR 0007, and combined synthetic integration boot fixture | All Wave 1 conformance binaries pass under CrossOver 26.3 + Rosetta 2; combined `test_integration_boot.exe` passes (19 pass, 2 ADR-0007 pending, 0 fail) | **Verified complete (Milestone #17, 16/16)** |
|
||||
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), placed resources over `xmem`, bridge `dxbc-accc` into Windows guests (`#445`), measure D3DMetal GPU limits (`#453`), and establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)**. Measured translator constraints: [D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | **In development (Milestone #18)** |
|
||||
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler, within the [measured D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) (`WaveSize(64)` and SM 6.6 64-bit atomics not run; bounded lock emulation) | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
|
||||
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; 16/16 PE32+ DLLs pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **In validation (PR #406)** |
|
||||
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime`, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, and combined synthetic integration boot fixture | All 13 Wave 1 conformance binaries pass under CrossOver + Rosetta 2; combined `integration_boot.exe` initializes every subsystem cleanly | **Next (Wave 1 ready)** |
|
||||
| **M2 — First Rendered Frame & Shader Format Gate** | Implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), placed resources over `xmem`, and `dxbc-accc` shader inspection to establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)** | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | Planned |
|
||||
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
|
||||
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
|
||||
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
|
||||
| **M6 — Shader Cache, 16 GB Optimization & Polish** | Persistent disk PSO + translated-shader cache, Lockhart 16 GB unified memory pressure tuning, Metal System Trace optimization, and optional Swift launcher UI | Reproducible frame-pacing and memory-pressure receipts under [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) | Planned |
|
||||
|
||||
@@ -7,6 +7,11 @@ It adds no runner and reports no new Windows or GPU execution results.
|
||||
|
||||
## Implementation checkpoint
|
||||
|
||||
Current runner: the same commands are `bx-cli` subcommands (`receipt`, `run`, `bench`,
|
||||
`stop`, `frames`) and the workloads are under `tests/conformance/`; see
|
||||
[maintainer testing](../maintainer-testing.md). The text below records the protocol as
|
||||
first written against the earlier candidate and is kept for its provenance.
|
||||
|
||||
The commands below refer to [PR #384](https://github.com/MacosPorters/betterxen/pull/384),
|
||||
reviewed at commit `566272082a74d8b45fcec37edd00f4f6703df3ab` on 2026-11-25.
|
||||
Its `betterxen-hybrid` command, build script and Windows workloads are not on
|
||||
|
||||
@@ -13,8 +13,7 @@ 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"
|
||||
bx-runtime = { path = "../bx-runtime" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+65
-1473
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,492 +0,0 @@
|
||||
//! 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::{AtomicBool, AtomicI32, AtomicU64, 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);
|
||||
|
||||
/// Signals that stop the run: the guest group is terminated and the environment cleaned up.
|
||||
/// SIGQUIT (Ctrl-\) is included so it cannot kill `bx-cli` and leave the guest running (#461).
|
||||
const STOP_SIGNALS: [libc::c_int; 4] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGQUIT];
|
||||
|
||||
static SIGNAL: AtomicI32 = AtomicI32::new(0);
|
||||
static SUSPEND: AtomicBool = AtomicBool::new(false);
|
||||
/// Total time this process has spent suspended inside [`supervise`], in nanoseconds.
|
||||
static SUSPENDED_NANOS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
extern "C" fn note_signal(signal: libc::c_int) {
|
||||
SIGNAL.store(signal, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
extern "C" fn note_suspend(_signal: libc::c_int) {
|
||||
SUSPEND.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Installs `handler` for `signal` unless the disposition this process inherited is `SIG_IGN`.
|
||||
/// Returns whether the handler was installed.
|
||||
///
|
||||
/// A signal the caller chose to ignore (`nohup`, or a `&` job of a non-interactive shell) stays
|
||||
/// ignored, so it cannot stop the run or the bottle (#461).
|
||||
fn install_unless_ignored(signal: libc::c_int, handler: extern "C" fn(libc::c_int)) -> bool {
|
||||
// SAFETY: `current` is a valid, writable sigaction; a null new action only queries. The
|
||||
// handlers passed here only store to an atomic, which is async-signal-safe.
|
||||
unsafe {
|
||||
let mut current: libc::sigaction = std::mem::zeroed();
|
||||
if libc::sigaction(signal, std::ptr::null(), &mut current) == 0
|
||||
&& current.sa_sigaction == libc::SIG_IGN
|
||||
{
|
||||
return false;
|
||||
}
|
||||
libc::signal(signal, handler as libc::sighandler_t) != libc::SIG_ERR
|
||||
}
|
||||
}
|
||||
|
||||
/// Records SIGINT, SIGTERM, SIGHUP and SIGQUIT instead of dying, so the run can be cleaned up,
|
||||
/// and records SIGTSTP (Ctrl-Z) so the guest group can be suspended together with `bx-cli`.
|
||||
/// Signals that were inherited as ignored are left ignored.
|
||||
///
|
||||
/// SIGTSTP is only acted on inside [`supervise`]. A Ctrl-Z typed while nothing is being
|
||||
/// supervised (for example while shims are copied) has no visible effect until the next
|
||||
/// supervised phase starts, which is then suspended at once.
|
||||
pub fn install_signal_handlers() {
|
||||
for signal in STOP_SIGNALS {
|
||||
install_unless_ignored(signal, note_signal);
|
||||
}
|
||||
install_unless_ignored(libc::SIGTSTP, note_suspend);
|
||||
}
|
||||
|
||||
pub fn received_signal() -> i32 {
|
||||
SIGNAL.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Total time spent suspended (Ctrl-Z until continued) across every [`supervise`] call so far.
|
||||
///
|
||||
/// A caller that budgets one `--timeout` over several supervised phases subtracts this from its
|
||||
/// own wall-clock measurement, so a pause during an earlier phase is not charged to a later one.
|
||||
pub fn suspended_time() -> Duration {
|
||||
Duration::from_nanos(SUSPENDED_NANOS.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
/// True once per SIGTSTP received since the last call.
|
||||
fn take_suspend_request() -> bool {
|
||||
SUSPEND.swap(false, Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Stops this process the way the terminal's Ctrl-Z would; returns when it is continued.
|
||||
fn suspend_self(_guest: libc::pid_t) {
|
||||
// SAFETY: raise takes no pointers. SIGSTOP cannot be caught, so this stops the process.
|
||||
unsafe {
|
||||
libc::raise(libc::SIGSTOP);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum Stop {
|
||||
TimedOut,
|
||||
Signalled(i32),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Outcome {
|
||||
Exited(ExitStatus),
|
||||
Stopped(Stop),
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
/// The guest's own numeric exit code (so a conformance fixture's documented exit-77 skip
|
||||
/// stays distinguishable from a failure, #565), 124 for a timeout (as `timeout(1)`),
|
||||
/// 128 + N for a signal.
|
||||
pub fn exit_code(&self) -> u8 {
|
||||
match self {
|
||||
// Unix guest codes are already 0-255; a signalled guest has no code, which is a
|
||||
// failure. `code.max(1)` at the call sites still turns a failed cleanup into 1.
|
||||
Outcome::Exited(status) => status.code().map_or(1, |code| code.clamp(0, 255) as u8),
|
||||
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.
|
||||
///
|
||||
/// The guest is not in the terminal's foreground group, so Ctrl-Z reaches only `bx-cli`. It is
|
||||
/// passed on: the guest group gets SIGTSTP, `bx-cli` stops itself, and when `bx-cli` is continued
|
||||
/// the guest group gets SIGCONT. Time spent suspended does not count against `timeout`.
|
||||
pub fn supervise(
|
||||
command: Command,
|
||||
timeout: Option<Duration>,
|
||||
signal: impl Fn() -> i32,
|
||||
) -> std::io::Result<Outcome> {
|
||||
supervise_with(command, timeout, signal, take_suspend_request, suspend_self)
|
||||
}
|
||||
|
||||
/// [`supervise`] with the suspend request and the self-stop injected, so tests can exercise the
|
||||
/// job-control path without stopping the test process. `suspend` is called with the guest
|
||||
/// group's id after that group was sent SIGTSTP and returns when the launcher may continue.
|
||||
fn supervise_with(
|
||||
mut command: Command,
|
||||
timeout: Option<Duration>,
|
||||
signal: impl Fn() -> i32,
|
||||
suspend_requested: impl Fn() -> bool,
|
||||
mut suspend: impl FnMut(libc::pid_t),
|
||||
) -> 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 mut suspended = Duration::ZERO;
|
||||
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 suspend_requested() {
|
||||
let paused = Instant::now();
|
||||
signal_group(&child, libc::SIGTSTP);
|
||||
suspend(child.id() as libc::pid_t);
|
||||
signal_group(&child, libc::SIGCONT);
|
||||
let pause = paused.elapsed();
|
||||
suspended += pause;
|
||||
SUSPENDED_NANOS.fetch_add(
|
||||
u64::try_from(pause.as_nanos()).unwrap_or(u64::MAX),
|
||||
Ordering::SeqCst,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if timeout.is_some_and(|limit| started.elapsed().saturating_sub(suspended) >= 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.
|
||||
///
|
||||
/// Each `wineserver` runs in its own process group with no terminal input, so a second Ctrl-C
|
||||
/// typed while cleanup is running reaches only `bx-cli` (which records it) and cannot kill the
|
||||
/// cleanup itself (#461).
|
||||
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)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.process_group(0)
|
||||
.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(), 7);
|
||||
// A conformance fixture's documented skip must stay distinguishable from a failure
|
||||
// through `bx-cli run` (#565); the old `!status.success()` collapsed it to 1.
|
||||
let skipped = supervise(shell("exit 77"), Some(Duration::from_secs(10)), || 0).unwrap();
|
||||
assert_eq!(skipped.exit_code(), 77);
|
||||
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();
|
||||
}
|
||||
|
||||
/// Signal dispositions and the recorded signal are process-wide: tests that touch them run
|
||||
/// one at a time and use signals no other test raises.
|
||||
static SIGNAL_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn set_disposition(signal: libc::c_int, action: libc::sighandler_t) {
|
||||
// SAFETY: SIG_DFL and SIG_IGN are valid dispositions for these signals.
|
||||
unsafe {
|
||||
libc::signal(signal, action);
|
||||
}
|
||||
}
|
||||
|
||||
fn disposition(signal: libc::c_int) -> libc::sighandler_t {
|
||||
// SAFETY: a null new action only queries; `current` is valid and writable.
|
||||
unsafe {
|
||||
let mut current: libc::sigaction = std::mem::zeroed();
|
||||
assert_eq!(libc::sigaction(signal, std::ptr::null(), &mut current), 0);
|
||||
current.sa_sigaction
|
||||
}
|
||||
}
|
||||
|
||||
fn raise(signal: libc::c_int) {
|
||||
// SAFETY: raise takes no pointers.
|
||||
unsafe {
|
||||
libc::raise(signal);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_ignored_signal_stays_ignored() {
|
||||
let _guard = SIGNAL_TESTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// As under nohup: the signal arrives already ignored.
|
||||
set_disposition(libc::SIGUSR2, libc::SIG_IGN);
|
||||
SIGNAL.store(0, Ordering::SeqCst);
|
||||
assert!(!install_unless_ignored(libc::SIGUSR2, note_signal));
|
||||
assert_eq!(disposition(libc::SIGUSR2), libc::SIG_IGN);
|
||||
raise(libc::SIGUSR2);
|
||||
assert_eq!(
|
||||
received_signal(),
|
||||
0,
|
||||
"an ignored signal must not stop the run"
|
||||
);
|
||||
|
||||
// Control: the same signal with the default disposition is recorded.
|
||||
set_disposition(libc::SIGUSR2, libc::SIG_DFL);
|
||||
assert!(install_unless_ignored(libc::SIGUSR2, note_signal));
|
||||
raise(libc::SIGUSR2);
|
||||
assert_eq!(received_signal(), libc::SIGUSR2);
|
||||
set_disposition(libc::SIGUSR2, libc::SIG_DFL);
|
||||
SIGNAL.store(0, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sigquit_is_recorded_and_stops_the_guest_group() {
|
||||
let _guard = SIGNAL_TESTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
assert!(STOP_SIGNALS.contains(&libc::SIGQUIT));
|
||||
let before = disposition(libc::SIGQUIT);
|
||||
set_disposition(libc::SIGQUIT, libc::SIG_DFL);
|
||||
SIGNAL.store(0, Ordering::SeqCst);
|
||||
assert!(install_unless_ignored(libc::SIGQUIT, note_signal));
|
||||
// Without the handler this would kill the test process, as it killed bx-cli.
|
||||
raise(libc::SIGQUIT);
|
||||
assert_eq!(received_signal(), libc::SIGQUIT);
|
||||
set_disposition(libc::SIGQUIT, before);
|
||||
SIGNAL.store(0, Ordering::SeqCst);
|
||||
|
||||
let stopped = supervise(shell("sleep 30"), None, || libc::SIGQUIT).unwrap();
|
||||
assert!(matches!(
|
||||
stopped,
|
||||
Outcome::Stopped(Stop::Signalled(libc::SIGQUIT))
|
||||
));
|
||||
assert_eq!(stopped.exit_code(), 128 + libc::SIGQUIT as u8);
|
||||
}
|
||||
|
||||
/// True once `pid` is reported stopped; leaves the status in place.
|
||||
fn is_stopped(pid: libc::pid_t) -> bool {
|
||||
(0..100).any(|_| {
|
||||
// SAFETY: `info` is valid and writable; WNOWAIT leaves the child's state in place.
|
||||
let stopped = unsafe {
|
||||
let mut info: libc::siginfo_t = std::mem::zeroed();
|
||||
libc::waitid(
|
||||
libc::P_PID,
|
||||
pid as libc::id_t,
|
||||
&mut info,
|
||||
libc::WSTOPPED | libc::WNOHANG | libc::WNOWAIT,
|
||||
) == 0
|
||||
&& info.si_pid() == pid
|
||||
};
|
||||
if !stopped {
|
||||
std::thread::sleep(POLL);
|
||||
}
|
||||
stopped
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_suspend_request_stops_and_resumes_the_guest_without_using_up_the_timeout() {
|
||||
let requested = std::cell::Cell::new(false);
|
||||
let guest_was_stopped = std::cell::Cell::new(false);
|
||||
let suspended_before = suspended_time();
|
||||
let outcome = supervise_with(
|
||||
shell("sleep 0.4; exit 0"),
|
||||
// Shorter than the suspension below: only running time may count.
|
||||
Some(Duration::from_millis(1500)),
|
||||
|| 0,
|
||||
|| !requested.replace(true),
|
||||
|guest| {
|
||||
guest_was_stopped.set(is_stopped(guest));
|
||||
std::thread::sleep(Duration::from_millis(2000));
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(guest_was_stopped.get(), "the guest group was not stopped");
|
||||
// The pause is also reported to callers that budget a timeout across several phases.
|
||||
let reported = suspended_time() - suspended_before;
|
||||
assert!(reported >= Duration::from_millis(2000), "{reported:?}");
|
||||
match outcome {
|
||||
Outcome::Exited(status) => assert!(status.success(), "{status}"),
|
||||
other => panic!("the resumed guest should have finished on its own: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_runs_outside_the_callers_process_group() {
|
||||
let dir = scratch("cleanup-group");
|
||||
let server = dir.join("wineserver");
|
||||
let seen = dir.join("pgid");
|
||||
std::fs::write(
|
||||
&server,
|
||||
format!(
|
||||
"#!/bin/sh\n/bin/ps -o pgid= -p $$ >> '{}'\n",
|
||||
seen.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
stop_server(&server, &dir, &[]).unwrap();
|
||||
// SAFETY: getpgrp takes no arguments and cannot fail.
|
||||
let ours = unsafe { libc::getpgrp() };
|
||||
let groups: Vec<libc::pid_t> = std::fs::read_to_string(&seen)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(|line| line.trim().parse().unwrap())
|
||||
.collect();
|
||||
assert_eq!(groups.len(), 2, "-k and -w should both have run");
|
||||
for group in groups {
|
||||
// A terminal signal goes to the foreground group, which these are not part of.
|
||||
assert_ne!(group, ours, "cleanup shares the caller's process group");
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "bx-runtime"
|
||||
description = "Shared CrossOver launch supervision, environment checks and run evidence"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
libc = "=0.2.191"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,7 @@
|
||||
# Shared hybrid runtime
|
||||
|
||||
`bx-cli` is the executable. This library supplies its single supervised execution path for named CrossOver bottles and explicit Wine prefixes, environment preflight, PE validation, process/session lifecycle, memory and output limits, and JSON run evidence. `bx-cli probe`, `shader` and `trace` retain the original #406 classifiers and telemetry aggregator.
|
||||
|
||||
The implementation is migrated from BetterXen #405 (`b42133a`) and the maintainer draft preserved at `2645c42`, with #406 (`30e551a`, merged as `f2c42ba`) prefix/shim/profile/log contracts integrated. Original attribution remains in each source file; no retired native crate is a dependency and no alternate runner binary is built.
|
||||
|
||||
CrossOver, Rosetta 2 and graphics backends remain external. A dedicated Wine environment is required for safe cleanup: stopping one run stops that environment's server. Session locking coordinates BetterXen launchers; it does not prevent CrossOver's UI or another launcher from using the same environment. A bottle is not a security sandbox.
|
||||
@@ -0,0 +1,928 @@
|
||||
//! Command-line interface of the hybrid tooling.
|
||||
|
||||
use crate::session::BottleSession;
|
||||
use crate::{crossover, frames, host, json::Json, memory, pe, preflight, run, toolchain};
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
const USAGE: &str = "usage: bx-cli <command>
|
||||
host host receipt (JSON)
|
||||
crossover [--app P] CrossOver installs and documented preferences (JSON)
|
||||
toolchain Windows cross-compilers found on PATH (JSON)
|
||||
frames <file> frame-time statistics; file has one interval in ms per line (JSON)
|
||||
guard [--min-start-free N] [--min-free N] -- CMD ARGS...
|
||||
run CMD; refuse to start / stop it when free memory is low
|
||||
doctor [--bottle B] [--min-start-free N]
|
||||
check that a run could start here (JSON); non-zero exit if not
|
||||
inspect <file.exe> identify a Windows executable: machine, subsystem, imports (JSON)
|
||||
run (--bottle B | --prefix P) [--exe FILE] [--shims DIR (default build-shims/bin)] [--profile lockhart|anaconda] [--log FILE] [--backend d3dmetal|dxmt|dxvk|wined3d] [--timeout S] [--stall-timeout S]
|
||||
[--settle-bound S] [--expect TEXT] [--require-gates a,b,c] [--out DIR]
|
||||
[--min-start-free N] [--min-free N] [--allow-untested-crossover] -- EXE [ARGS...]
|
||||
run a Windows program through CrossOver; write a JSON record
|
||||
bench --bottle B --backends a,b,c [--repeat N] [same options] -- EXE [ARGS...]
|
||||
run the program per backend N times; summarise frame times
|
||||
stop (--bottle B | --prefix P) recover a dedicated environment; SIGTERM an active runner first
|
||||
receipt host + crossover + toolchain in one JSON document
|
||||
|
||||
run and bench also accept: --env NAME=VALUE (repeatable), --inherit-env true, --keep-output true.
|
||||
The child otherwise receives only a short allowlist of host variables. A bottle is not a sandbox.";
|
||||
|
||||
/// Set by the signal handler; every run polls it.
|
||||
static INTERRUPTED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
extern "C" fn on_signal(_: libc::c_int) {
|
||||
// Storing to an atomic is async-signal-safe.
|
||||
INTERRUPTED.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn install_signal_handlers() {
|
||||
let handler = on_signal as extern "C" fn(libc::c_int) as libc::sighandler_t;
|
||||
for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
|
||||
// SAFETY: `on_signal` has the required signature and only touches an atomic.
|
||||
unsafe { libc::signal(signal, handler) };
|
||||
}
|
||||
}
|
||||
|
||||
fn crossover_json(app: Option<PathBuf>) -> Json {
|
||||
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
|
||||
let cands = match app {
|
||||
Some(p) => vec![p],
|
||||
None => crossover::candidate_paths(&home),
|
||||
};
|
||||
let installs = crossover::discover(&cands);
|
||||
Json::obj(vec![
|
||||
("installed", Json::Bool(!installs.is_empty())),
|
||||
(
|
||||
"installs",
|
||||
Json::Arr(installs.iter().map(|i| i.to_json()).collect()),
|
||||
),
|
||||
(
|
||||
"bottle_dir_preference",
|
||||
Json::opt_str(crossover::preference("BottleDir")),
|
||||
),
|
||||
(
|
||||
"managed_bottle_dirs_preference",
|
||||
Json::opt_str(crossover::preference("ManagedBottleDirs")),
|
||||
),
|
||||
(
|
||||
"searched",
|
||||
Json::Arr(
|
||||
cands
|
||||
.iter()
|
||||
.map(|p| Json::str(p.display().to_string()))
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
(
|
||||
"note",
|
||||
Json::str(
|
||||
"Only Info.plist metadata, lipo -archs and documented defaults keys are read. Bottle graphics backend and bundle internals are not interpreted (undocumented, #350).",
|
||||
),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn toolchain_json() -> Json {
|
||||
let path = std::env::var("PATH").unwrap_or_default();
|
||||
Json::Arr(
|
||||
toolchain::probe(&path)
|
||||
.iter()
|
||||
.map(|c| c.to_json())
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn guard(args: &[String]) -> ExitCode {
|
||||
let mut limits = memory::Limits {
|
||||
min_start_free: 70,
|
||||
min_free: 20,
|
||||
poll: std::time::Duration::from_secs(1),
|
||||
grace: std::time::Duration::from_secs(10),
|
||||
};
|
||||
let mut i = 0;
|
||||
while i < args.len() && args[i] != "--" {
|
||||
let v = args.get(i + 1).and_then(|v| v.parse::<u8>().ok());
|
||||
match (args[i].as_str(), v) {
|
||||
("--min-start-free", Some(v)) => limits.min_start_free = v,
|
||||
("--min-free", Some(v)) => limits.min_free = v,
|
||||
_ => {
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
i += 2;
|
||||
}
|
||||
let Some(cmd) = args.get(i + 1) else {
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
match memory::supervise(cmd, &args[i + 2..], limits, &mut memory::free_percentage) {
|
||||
memory::Outcome::Exited(Some(0)) => ExitCode::SUCCESS,
|
||||
memory::Outcome::Exited(c) => ExitCode::from(c.map_or(1, |c| c.clamp(1, 255)) as u8),
|
||||
other => {
|
||||
eprintln!("guard: {other:?}");
|
||||
ExitCode::from(3)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RunArgs {
|
||||
allow_untested: bool,
|
||||
cfg: run::RunConfig,
|
||||
backends: Vec<String>,
|
||||
repeat: u32,
|
||||
out: Option<PathBuf>,
|
||||
/// What the program file is, recorded with every run.
|
||||
executable: Json,
|
||||
}
|
||||
|
||||
// Environment contract preserved from #406; frozen C headers remain unchanged.
|
||||
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";
|
||||
|
||||
fn unix_to_wine_z_path(path: &std::path::Path) -> String {
|
||||
format!("Z:{}", path.to_string_lossy().replace('/', "\\"))
|
||||
}
|
||||
|
||||
/// #406's launch contract: shim overrides and `WINEPATH` are always configured, from
|
||||
/// `build-shims/bin` unless `--shims` names another directory. An explicit `--shims` wins over
|
||||
/// `--env`; the default does not replace a value the caller passed with `--env`.
|
||||
fn shim_environment(
|
||||
explicit: Option<&std::path::Path>,
|
||||
user: &[(String, String)],
|
||||
) -> Result<Vec<(String, String)>, String> {
|
||||
let dir = match explicit {
|
||||
Some(path) => {
|
||||
let path = std::fs::canonicalize(path)
|
||||
.map_err(|e| format!("cannot open shims {}: {e}", path.display()))?;
|
||||
if !path.is_dir() {
|
||||
return Err("--shims must name a directory".into());
|
||||
}
|
||||
path
|
||||
}
|
||||
None => std::fs::canonicalize(DEFAULT_SHIMS).unwrap_or_else(|_| DEFAULT_SHIMS.into()),
|
||||
};
|
||||
Ok([
|
||||
("WINEDLLOVERRIDES", SHIM_DLL_OVERRIDES.to_string()),
|
||||
("WINEPATH", unix_to_wine_z_path(&dir)),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|(name, _)| explicit.is_some() || !user.iter().any(|(k, _)| k == name))
|
||||
.map(|(name, value)| (name.to_string(), value))
|
||||
.collect())
|
||||
}
|
||||
|
||||
const DEFAULT_SHIMS: &str = "build-shims/bin";
|
||||
|
||||
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
|
||||
let (mut bottle, mut prefix, mut exe, mut shims, mut log) = (None, None, None, None, None);
|
||||
let mut profile = "lockhart".to_string();
|
||||
let mut backend = None;
|
||||
let mut backends = Vec::new();
|
||||
let mut repeat = 1u32;
|
||||
let mut timeout = 300u64;
|
||||
let mut stall = None;
|
||||
let mut settle = 60u64;
|
||||
let mut expect = None;
|
||||
let mut require_gates = Vec::new();
|
||||
let mut out = None;
|
||||
let (mut min_start, mut min_free) = (50u8, 15u8);
|
||||
let (mut inherit_env, mut keep_output) = (false, false);
|
||||
let mut allow_untested = false;
|
||||
let mut env = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < args.len() && args[i] != "--" {
|
||||
let key = args[i].as_str();
|
||||
if matches!(
|
||||
key,
|
||||
"--inherit-env" | "--keep-output" | "--allow-untested-crossover"
|
||||
) {
|
||||
let value = args
|
||||
.get(i + 1)
|
||||
.filter(|v| matches!(v.as_str(), "true" | "false"));
|
||||
let enabled = value
|
||||
.map_or(Ok(true), |v| v.parse::<bool>())
|
||||
.map_err(|_| "invalid boolean")?;
|
||||
match key {
|
||||
"--inherit-env" => inherit_env = enabled,
|
||||
"--keep-output" => keep_output = enabled,
|
||||
_ => allow_untested = enabled,
|
||||
}
|
||||
i += if value.is_some() { 2 } else { 1 };
|
||||
continue;
|
||||
}
|
||||
let v = args
|
||||
.get(i + 1)
|
||||
.ok_or_else(|| format!("{key} needs a value"))?
|
||||
.clone();
|
||||
match key {
|
||||
"--bottle" => bottle = Some(v),
|
||||
"--prefix" => prefix = Some(PathBuf::from(v)),
|
||||
"--exe" => exe = Some(v),
|
||||
"--shims" => shims = Some(PathBuf::from(v)),
|
||||
"--profile" => profile = v,
|
||||
"--log" => log = Some(PathBuf::from(v)),
|
||||
"--backend" => backend = Some(v),
|
||||
"--backends" => backends = v.split(',').map(String::from).collect(),
|
||||
"--repeat" => repeat = v.parse().map_err(|_| "bad --repeat")?,
|
||||
"--timeout" => timeout = v.parse().map_err(|_| "bad --timeout")?,
|
||||
"--stall-timeout" => stall = Some(v.parse().map_err(|_| "bad --stall-timeout")?),
|
||||
"--settle-bound" => settle = v.parse().map_err(|_| "bad --settle-bound")?,
|
||||
"--expect" => expect = Some(v),
|
||||
"--env" => {
|
||||
let (name, value) = v.split_once('=').ok_or("--env needs NAME=VALUE")?;
|
||||
if !valid_environment_name(name) || value.contains('\0') {
|
||||
return Err("--env needs NAME=VALUE".into());
|
||||
}
|
||||
if [
|
||||
"HOME",
|
||||
"USER",
|
||||
"LOGNAME",
|
||||
"WINEPREFIX",
|
||||
"WINESERVER",
|
||||
"WINELOADER",
|
||||
"WINEDLLPATH",
|
||||
"CX_BOTTLE",
|
||||
"CX_BOTTLE_PATH",
|
||||
"CX_ROOT",
|
||||
]
|
||||
.contains(&name)
|
||||
{
|
||||
return Err(format!(
|
||||
"{name} controls launcher identity or bottle selection and cannot be overridden"
|
||||
));
|
||||
}
|
||||
if name.starts_with("CX_GRAPHICS_BACKEND") {
|
||||
return Err("select the backend with --backend, not --env".into());
|
||||
}
|
||||
if name.starts_with("DYLD_") {
|
||||
return Err("DYLD_ variables are not passed to the launcher".into());
|
||||
}
|
||||
env.push((name.to_string(), value.to_string()));
|
||||
}
|
||||
"--require-gates" => require_gates = v.split(',').map(String::from).collect(),
|
||||
"--out" => out = Some(PathBuf::from(v)),
|
||||
"--min-start-free" => min_start = v.parse().map_err(|_| "bad --min-start-free")?,
|
||||
"--min-free" => min_free = v.parse().map_err(|_| "bad --min-free")?,
|
||||
o => return Err(format!("unknown option {o}")),
|
||||
}
|
||||
i += 2;
|
||||
}
|
||||
let (program, guest_args) = if let Some(exe) = exe {
|
||||
(
|
||||
exe,
|
||||
if args.get(i).map(String::as_str) == Some("--") {
|
||||
args[i + 1..].to_vec()
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
)
|
||||
} else {
|
||||
(
|
||||
args.get(i + 1)
|
||||
.ok_or("use --exe FILE or -- FILE [ARGS...]")?
|
||||
.clone(),
|
||||
args[i + 2..].to_vec(),
|
||||
)
|
||||
};
|
||||
if bottle.is_some() && prefix.is_some() {
|
||||
return Err("choose --bottle or --prefix, not both".into());
|
||||
}
|
||||
if bottle.is_none() && prefix.is_none() {
|
||||
return Err("--bottle or --prefix is required; use a dedicated test environment".into());
|
||||
}
|
||||
let bottle = bottle.unwrap_or_default();
|
||||
if prefix.is_none() && !preflight::valid_bottle_name(&bottle) {
|
||||
return Err(format!("invalid bottle name {bottle:?}"));
|
||||
}
|
||||
if !matches!(profile.as_str(), "lockhart" | "anaconda") {
|
||||
return Err("profile must be lockhart or anaconda".into());
|
||||
}
|
||||
if min_start > 100 || min_free > 100 {
|
||||
return Err("memory percentages must be 0..100".into());
|
||||
}
|
||||
if let Some(unknown) = backend
|
||||
.iter()
|
||||
.chain(backends.iter().filter(|b| *b != "default"))
|
||||
.find(|b| !run::BACKENDS.contains(&b.as_str()))
|
||||
{
|
||||
return Err(format!(
|
||||
"unknown backend {unknown:?}; use one of {}",
|
||||
run::BACKENDS.join(", ")
|
||||
));
|
||||
}
|
||||
if program.starts_with('-') {
|
||||
return Err("the program path must not start with '-' (write ./name.exe)".into());
|
||||
}
|
||||
let executable = identify(std::path::Path::new(&program))?;
|
||||
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
|
||||
let installs = crossover::discover(&crossover::candidate_paths(&home));
|
||||
let install = installs.first().ok_or("no CrossOver installation found")?;
|
||||
let mut wine = run::wine_path(&install.path);
|
||||
let prefix = if let Some(path) = prefix {
|
||||
std::fs::create_dir_all(&path)
|
||||
.map_err(|e| format!("cannot create prefix {}: {e}", path.display()))?;
|
||||
wine.set_file_name("wineloader");
|
||||
Some(std::fs::canonicalize(path).map_err(|e| e.to_string())?)
|
||||
} else {
|
||||
if !run::bottle_prefix(&bottle).join("drive_c").is_dir() {
|
||||
return Err(format!("bottle {bottle:?} not found"));
|
||||
}
|
||||
None
|
||||
};
|
||||
if !wine.is_file() {
|
||||
return Err(format!(
|
||||
"{} not found in this CrossOver build",
|
||||
wine.display()
|
||||
));
|
||||
}
|
||||
env.push(("ROSETTA_ADVERTISE_AVX".into(), "1".into()));
|
||||
env.push(("BX_PROFILE".into(), profile));
|
||||
let shim_env = shim_environment(shims.as_deref(), &env)?;
|
||||
env.extend(shim_env);
|
||||
if let Some(path) = log {
|
||||
let path = if path.is_absolute() {
|
||||
path
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.map_err(|e| e.to_string())?
|
||||
.join(path)
|
||||
};
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
env.push(("BX_LOG_FILE".into(), unix_to_wine_z_path(&path)));
|
||||
}
|
||||
Ok(RunArgs {
|
||||
allow_untested,
|
||||
cfg: run::RunConfig {
|
||||
wine,
|
||||
bottle,
|
||||
prefix,
|
||||
backend,
|
||||
program,
|
||||
args: guest_args,
|
||||
timeout: std::time::Duration::from_secs(timeout),
|
||||
limits: memory::Limits {
|
||||
min_start_free: min_start,
|
||||
min_free,
|
||||
poll: std::time::Duration::from_millis(250),
|
||||
grace: std::time::Duration::from_secs(10),
|
||||
},
|
||||
expect,
|
||||
work_dir: out
|
||||
.clone()
|
||||
.unwrap_or_else(|| PathBuf::from("artifacts/hybrid-runs")),
|
||||
stall_timeout: stall.map(std::time::Duration::from_secs),
|
||||
settle_bound: std::time::Duration::from_secs(settle),
|
||||
read_free: memory::free_percentage,
|
||||
require_gates,
|
||||
max_output: 64 << 20,
|
||||
inherit_env,
|
||||
env,
|
||||
keep_output,
|
||||
interrupted: &INTERRUPTED,
|
||||
},
|
||||
backends,
|
||||
repeat,
|
||||
out,
|
||||
executable,
|
||||
})
|
||||
}
|
||||
|
||||
/// Refuse anything that is not a launchable Windows program, and describe what is.
|
||||
fn identify(path: &std::path::Path) -> Result<Json, String> {
|
||||
let image = pe::inspect(path)?;
|
||||
image
|
||||
.check_launchable()
|
||||
.map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let sha256 = crate::cmdutil::run(
|
||||
"/usr/bin/shasum",
|
||||
&["-a", "256", &path.display().to_string()],
|
||||
)
|
||||
.and_then(|o| o.split_whitespace().next().map(String::from));
|
||||
Ok(Json::obj(vec![
|
||||
("path", Json::str(path.display().to_string())),
|
||||
("sha256", Json::opt_str(sha256)),
|
||||
("image", image.to_json()),
|
||||
]))
|
||||
}
|
||||
|
||||
fn with_executable(mut record: Json, executable: &Json) -> Json {
|
||||
if let Json::Obj(fields) = &mut record {
|
||||
fields.push(("executable".into(), executable.clone()));
|
||||
}
|
||||
record
|
||||
}
|
||||
|
||||
fn doctor(args: &[String]) -> ExitCode {
|
||||
let (mut bottle, mut prefix, mut min_start) = (None, None, 50u8);
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match (a.as_str(), it.next()) {
|
||||
("--bottle", Some(v)) => bottle = Some(v.clone()),
|
||||
("--prefix", Some(v)) => prefix = Some(PathBuf::from(v)),
|
||||
("--min-start-free", Some(v)) if v.parse::<u8>().is_ok() => {
|
||||
min_start = v.parse().unwrap_or(min_start)
|
||||
}
|
||||
_ => {
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
if bottle.is_some() && prefix.is_some() {
|
||||
eprintln!("choose --bottle or --prefix");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
|
||||
let install = crossover::discover(&crossover::candidate_paths(&home))
|
||||
.into_iter()
|
||||
.next();
|
||||
let wine = install.as_ref().map(|i| run::wine_path(&i.path));
|
||||
let mut facts = preflight::gather(
|
||||
bottle.as_deref(),
|
||||
wine.as_deref()
|
||||
.map(|w| (crossover_build().unwrap_or_else(|| "unknown".into()), w)),
|
||||
min_start,
|
||||
);
|
||||
if let Some(path) = prefix {
|
||||
facts.bottle = Some(("prefix".into(), path));
|
||||
}
|
||||
let checks = preflight::evaluate(&facts);
|
||||
let mut report = preflight::to_json(&checks);
|
||||
if let Json::Obj(fields) = &mut report {
|
||||
fields.push(("host_info".into(), host_info(install.as_ref())));
|
||||
}
|
||||
print!("{}", report.render());
|
||||
if checks.iter().all(|c| c.ok) {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reported, never gating: running a prebuilt program needs none of these. Preserves what
|
||||
/// #406's `doctor` showed (memory profile, D3DMetal presence, the shim cross-compiler).
|
||||
fn host_info(install: Option<&crossover::Install>) -> Json {
|
||||
let memory_gib = host::collect().memory_bytes.map(|b| b >> 30);
|
||||
let d3dmetal = install.map(|i| {
|
||||
i.path
|
||||
.join("Contents/SharedSupport/CrossOver/lib64/apple_gptk/external/D3DMetal.framework")
|
||||
.exists()
|
||||
});
|
||||
let mingw = std::env::var_os("PATH").and_then(|path| {
|
||||
std::env::split_paths(&path)
|
||||
.map(|dir| dir.join("x86_64-w64-mingw32-g++"))
|
||||
.find(|candidate| candidate.is_file())
|
||||
});
|
||||
Json::obj(vec![
|
||||
(
|
||||
"memory_gib",
|
||||
memory_gib.map_or(Json::Null, |g| Json::Num(g as f64)),
|
||||
),
|
||||
(
|
||||
"recommended_profile",
|
||||
Json::opt_str(memory_gib.map(|g| recommended_profile(g).to_string())),
|
||||
),
|
||||
(
|
||||
"crossover_build_tested",
|
||||
install.map_or(Json::Null, |_| {
|
||||
Json::Bool(run::tested_crossover_build(crossover_build().as_deref()))
|
||||
}),
|
||||
),
|
||||
(
|
||||
"d3dmetal_framework_present",
|
||||
d3dmetal.map_or(Json::Null, Json::Bool),
|
||||
),
|
||||
(
|
||||
"shim_cross_compiler",
|
||||
Json::opt_str(mingw.map(|p| p.display().to_string())),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn recommended_profile(memory_gib: u64) -> &'static str {
|
||||
if memory_gib >= 32 {
|
||||
"anaconda"
|
||||
} else {
|
||||
"lockhart"
|
||||
}
|
||||
}
|
||||
|
||||
fn crossover_build() -> Option<String> {
|
||||
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
|
||||
crossover::discover(&crossover::candidate_paths(&home))
|
||||
.first()
|
||||
.and_then(|i| {
|
||||
Some(format!(
|
||||
"{} ({})",
|
||||
i.short_version.clone()?,
|
||||
i.build_version.clone()?
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// The launcher options are observed behaviour of specific builds, so an unlisted build is
|
||||
/// refused unless the caller opts in. `stop` is not gated: recovery must always work.
|
||||
fn check_build(build: Option<&str>, allow_untested: bool) -> Result<(), String> {
|
||||
if run::tested_crossover_build(build) {
|
||||
return Ok(());
|
||||
}
|
||||
let message = format!(
|
||||
"CrossOver {} has not been tested with this launcher (tested: {})",
|
||||
build.unwrap_or("of unknown version"),
|
||||
run::TESTED_CROSSOVER_BUILDS.join(", ")
|
||||
);
|
||||
if allow_untested {
|
||||
eprintln!("warning: {message}");
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"{message}; pass --allow-untested-crossover to run anyway"
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn save(dir: &std::path::Path, kind: &str, j: &Json) -> Result<(), String> {
|
||||
crate::records::save(dir, kind, j)
|
||||
.map(|path| eprintln!("report saved: {}", path.display()))
|
||||
.map_err(|error| format!("cannot save {kind} report in {}: {error}", dir.display()))
|
||||
}
|
||||
|
||||
fn finish_report(passed: bool, out: Option<&std::path::Path>, kind: &str, j: &Json) -> ExitCode {
|
||||
print!("{}", j.render());
|
||||
if let Some(dir) = out
|
||||
&& let Err(error) = save(dir, kind, j)
|
||||
{
|
||||
eprintln!("{error}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
if passed {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
|
||||
fn run_cmd(args: &[String]) -> ExitCode {
|
||||
if args == ["--help"] {
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
let a = match parse_run_args(args) {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
eprintln!("{e}\n{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let build = crossover_build();
|
||||
if let Err(e) = check_build(build.as_deref(), a.allow_untested) {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let mut session = match BottleSession::acquire(&a.cfg.prefix_path(), false) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let mut r = run::execute(&a.cfg, build);
|
||||
if r.class != run::Class::CleanupFailed
|
||||
&& let Err(e) = session.complete()
|
||||
{
|
||||
eprintln!("cannot finish bottle session: {e}");
|
||||
r.class = run::Class::CleanupFailed;
|
||||
if let Json::Obj(fields) = &mut r.json {
|
||||
fields.retain(|(name, _)| name != "classification");
|
||||
fields.push(("classification".into(), Json::str("cleanup_failed")));
|
||||
fields.push(("session_error".into(), Json::str(e)));
|
||||
}
|
||||
}
|
||||
if r.class != run::Class::Passed {
|
||||
eprintln!("run: {}", r.class.name());
|
||||
for g in r.gates.iter().filter(|g| !g.passed) {
|
||||
eprintln!(" gate {} failed: {}", g.name, g.detail);
|
||||
}
|
||||
if let Some(e) = &r.error {
|
||||
eprintln!(" {e}");
|
||||
}
|
||||
}
|
||||
finish_report(
|
||||
r.class == run::Class::Passed,
|
||||
a.out.as_deref(),
|
||||
"run",
|
||||
&with_executable(r.json, &a.executable),
|
||||
)
|
||||
}
|
||||
|
||||
fn bench_cmd(args: &[String]) -> ExitCode {
|
||||
let a = match parse_run_args(args) {
|
||||
Ok(a) if !a.backends.is_empty() => a,
|
||||
Ok(_) => {
|
||||
eprintln!("bench needs --backends\n{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("{e}\n{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let build = crossover_build();
|
||||
if let Err(e) = check_build(build.as_deref(), a.allow_untested) {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let mut session = match BottleSession::acquire(&a.cfg.prefix_path(), false) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let mut per_backend = Vec::new();
|
||||
let mut all_ok = true;
|
||||
let mut cleanup_failed = false;
|
||||
for b in &a.backends {
|
||||
let mut runs = Vec::new();
|
||||
for _ in 0..a.repeat {
|
||||
if INTERRUPTED.load(Ordering::SeqCst) || cleanup_failed {
|
||||
all_ok = false;
|
||||
break;
|
||||
}
|
||||
let mut cfg = a.cfg.clone();
|
||||
cfg.backend = if b == "default" {
|
||||
None
|
||||
} else {
|
||||
Some(b.clone())
|
||||
};
|
||||
let r = run::execute(&cfg, build.clone());
|
||||
cleanup_failed |= r.class == run::Class::CleanupFailed;
|
||||
all_ok &= r.class == run::Class::Passed;
|
||||
runs.push(with_executable(r.json, &a.executable));
|
||||
}
|
||||
per_backend.push(Json::obj(vec![
|
||||
("backend", Json::str(b.clone())),
|
||||
("runs", Json::Arr(runs)),
|
||||
]));
|
||||
}
|
||||
let doc = Json::obj(vec![
|
||||
("schema", Json::str("betterxen-hybrid-bench/0")),
|
||||
("repeat", Json::Num(a.repeat as f64)),
|
||||
("host", host::collect().to_json()),
|
||||
("results", Json::Arr(per_backend)),
|
||||
]);
|
||||
if !cleanup_failed && let Err(e) = session.complete() {
|
||||
eprintln!("cannot finish bottle session: {e}");
|
||||
all_ok = false;
|
||||
}
|
||||
finish_report(all_ok, a.out.as_deref(), "bench", &doc)
|
||||
}
|
||||
|
||||
fn stop(args: &[String]) -> ExitCode {
|
||||
let [flag, target] = args else {
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let prefix = match flag.as_str() {
|
||||
"--bottle" if preflight::valid_bottle_name(target) => run::bottle_prefix(target),
|
||||
"--prefix" => PathBuf::from(target),
|
||||
_ => {
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
if !prefix.join("drive_c").is_dir() {
|
||||
eprintln!("initialized environment not found at {}", prefix.display());
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
let prefix = match std::fs::canonicalize(&prefix) {
|
||||
Ok(path) => path,
|
||||
Err(error) => {
|
||||
eprintln!("cannot resolve prefix {}: {error}", prefix.display());
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
|
||||
let Some(install) = crossover::discover(&crossover::candidate_paths(&home))
|
||||
.into_iter()
|
||||
.next()
|
||||
else {
|
||||
eprintln!("no CrossOver installation found");
|
||||
return ExitCode::from(1);
|
||||
};
|
||||
let mut session = match BottleSession::acquire(&prefix, true) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
if let Err(e) =
|
||||
run::stop_prefix(&run::wine_path(&install.path), &prefix).and_then(|()| session.complete())
|
||||
{
|
||||
eprintln!("{e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
Json::obj(vec![
|
||||
("schema", Json::str("betterxen-hybrid-stop/0")),
|
||||
("prefix", Json::str(prefix.display().to_string())),
|
||||
("stopped", Json::Bool(true))
|
||||
])
|
||||
.render()
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn valid_environment_name(name: &str) -> bool {
|
||||
let mut chars = name.chars();
|
||||
chars
|
||||
.next()
|
||||
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|
||||
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod foundation_contract_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn profile_recommendation_matches_the_foundation_threshold() {
|
||||
assert_eq!(recommended_profile(16), "lockhart");
|
||||
assert_eq!(recommended_profile(24), "lockhart");
|
||||
assert_eq!(recommended_profile(32), "anaconda");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn untested_crossover_builds_are_refused_unless_allowed() {
|
||||
assert!(check_build(Some("26.3 (26.3.0.39832)"), false).is_ok());
|
||||
for build in [Some("26.2 (26.2.0.39821)"), None] {
|
||||
let refused = check_build(build, false).unwrap_err();
|
||||
assert!(refused.contains("--allow-untested-crossover"));
|
||||
assert!(check_build(build, true).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shims_are_configured_by_default_without_replacing_env_values() {
|
||||
let names =
|
||||
|env: Vec<(String, String)>| env.into_iter().map(|(k, _)| k).collect::<Vec<_>>();
|
||||
let default = shim_environment(None, &[]).unwrap();
|
||||
assert!(
|
||||
default[1].1.ends_with("build-shims\\bin"),
|
||||
"{}",
|
||||
default[1].1
|
||||
);
|
||||
assert_eq!(names(default), ["WINEDLLOVERRIDES", "WINEPATH"]);
|
||||
let user = [("WINEDLLOVERRIDES".to_string(), "xmem=".to_string())];
|
||||
assert_eq!(names(shim_environment(None, &user).unwrap()), ["WINEPATH"]);
|
||||
let dir = std::env::temp_dir();
|
||||
assert_eq!(
|
||||
names(shim_environment(Some(&dir), &user).unwrap()),
|
||||
["WINEDLLOVERRIDES", "WINEPATH"]
|
||||
);
|
||||
assert!(shim_environment(Some(std::path::Path::new("/nonexistent")), &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_unix_path_to_wine_z_drive() {
|
||||
assert_eq!(
|
||||
unix_to_wine_z_path(std::path::Path::new("/tmp/bx-test.jsonl")),
|
||||
"Z:\\tmp\\bx-test.jsonl"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Entry point for the runtime subcommands of `bx-cli`. `args` excludes the program name; a
|
||||
/// leading `hybrid` word (the #405 spelling) is accepted and ignored.
|
||||
pub fn run_cli(args: &[String]) -> ExitCode {
|
||||
// The standalone maintainer bundle accepts the same `hybrid ...` argument vector as
|
||||
// the full CLI. Both enter this implementation; no wrapper or native research runtime
|
||||
// needs to be distributed for the acceptance tools.
|
||||
let args = if args.first().map(String::as_str) == Some("hybrid") {
|
||||
&args[1..]
|
||||
} else {
|
||||
args
|
||||
};
|
||||
let rest = args.get(1..).unwrap_or_default();
|
||||
match args.first().map(String::as_str) {
|
||||
Some("run") => {
|
||||
install_signal_handlers();
|
||||
return run_cmd(rest);
|
||||
}
|
||||
Some("bench") => {
|
||||
install_signal_handlers();
|
||||
return bench_cmd(rest);
|
||||
}
|
||||
Some("doctor") => return doctor(rest),
|
||||
Some("guard") => return guard(rest),
|
||||
Some("stop") => return stop(rest),
|
||||
_ => {}
|
||||
}
|
||||
let result: Result<Json, String> = match args.first().map(String::as_str) {
|
||||
Some("host") => Ok(host::collect().to_json()),
|
||||
Some("inspect") => match args.get(1) {
|
||||
None => Err("inspect needs a file".into()),
|
||||
Some(f) => pe::inspect(std::path::Path::new(f)).map(|i| i.to_json()),
|
||||
},
|
||||
Some("crossover") => {
|
||||
let app = match args.get(1).map(String::as_str) {
|
||||
Some("--app") => args.get(2).map(PathBuf::from),
|
||||
_ => None,
|
||||
};
|
||||
Ok(crossover_json(app))
|
||||
}
|
||||
Some("toolchain") => Ok(toolchain_json()),
|
||||
Some("frames") => match args.get(1) {
|
||||
None => Err("frames needs a file".into()),
|
||||
Some(f) => std::fs::read_to_string(f)
|
||||
.map_err(|e| format!("{f}: {e}"))
|
||||
.and_then(|t| frames::parse_intervals(&t).map_err(|e| e.to_string()))
|
||||
.and_then(|v| frames::analyze(&v).map_err(|e| e.to_string()))
|
||||
.map(|s| s.to_json()),
|
||||
},
|
||||
Some("receipt") => Ok(Json::obj(vec![
|
||||
("schema", Json::str("betterxen-hybrid-receipt/0")),
|
||||
("host", host::collect().to_json()),
|
||||
("crossover", crossover_json(None)),
|
||||
("windows_cross_compilers", toolchain_json()),
|
||||
])),
|
||||
_ => Err(USAGE.into()),
|
||||
};
|
||||
match result {
|
||||
Ok(j) => {
|
||||
print!("{}", j.render());
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod report_tests {
|
||||
use super::*;
|
||||
|
||||
fn args(a: &[&str]) -> Vec<String> {
|
||||
a.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
// These fail before CrossOver discovery, so they run on hosts without CrossOver.
|
||||
#[test]
|
||||
fn bad_backend_bottle_or_program_is_refused_before_launch() {
|
||||
let err = |a: &[&str]| parse_run_args(&args(a)).err().unwrap();
|
||||
assert!(
|
||||
err(&["--bottle", "b", "--backend", "dmxt", "--", "x.exe"]).contains("unknown backend")
|
||||
);
|
||||
assert!(
|
||||
err(&["--bottle", "b", "--backends", "default,typo", "--", "x.exe"])
|
||||
.contains("unknown backend")
|
||||
);
|
||||
assert!(err(&["--bottle", "../b", "--", "x.exe"]).contains("invalid bottle"));
|
||||
assert!(err(&["--bottle", "b", "--", "/nonexistent/x.exe"]).contains("/nonexistent/x.exe"));
|
||||
assert!(err(&["--bottle", "b", "--", "/bin/sh"]).contains("not a PE"));
|
||||
assert!(err(&["--bottle", "b", "--", "--help"]).contains("must not start with"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requested_evidence_failure_overrides_a_passing_workload() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"bx-report-invalid-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::write(&path, "keep this file").unwrap();
|
||||
for kind in ["run", "bench"] {
|
||||
assert_eq!(
|
||||
finish_report(true, Some(&path), kind, &Json::Null),
|
||||
ExitCode::from(1)
|
||||
);
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "keep this file");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdout_only_reporting_preserves_workload_status() {
|
||||
assert_eq!(
|
||||
finish_report(true, None, "run", &Json::Null),
|
||||
ExitCode::SUCCESS
|
||||
);
|
||||
assert_eq!(
|
||||
finish_report(false, None, "bench", &Json::Null),
|
||||
ExitCode::from(1)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! Run a system tool and capture trimmed stdout. A missing tool or non-zero exit is `None`,
|
||||
//! never a guessed value.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
pub fn run(program: &str, args: &[&str]) -> Option<String> {
|
||||
let out = Command::new(program).args(args).output().ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
Some(s)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Discover installed CrossOver bundles and read standard bundle metadata.
|
||||
//!
|
||||
//! Only documented or standard macOS interfaces are used: the app bundle's `Info.plist`
|
||||
//! (read through `plutil`), `lipo -archs` on the bundle's main executable, and the
|
||||
//! `defaults` keys CodeWeavers documents in "Advanced CrossOver Mac Configuration"
|
||||
//! (`BottleDir`, `ManagedBottleDirs` in `com.codeweavers.CrossOver`). Bundle internals such
|
||||
//! as `Contents/SharedSupport` are NOT interpreted: they are undocumented and not a stable
|
||||
//! interface (#350). The graphics backend of a bottle is deliberately not read.
|
||||
|
||||
use crate::cmdutil::run;
|
||||
use crate::json::Json;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const BUNDLE_ID: &str = "com.codeweavers.CrossOver";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Install {
|
||||
pub path: PathBuf,
|
||||
pub bundle_id: Option<String>,
|
||||
pub short_version: Option<String>,
|
||||
pub build_version: Option<String>,
|
||||
pub executable_archs: Option<Vec<String>>,
|
||||
pub minimum_macos: Option<String>,
|
||||
}
|
||||
|
||||
/// Candidate bundle locations: standard application directories. Spotlight is consulted too.
|
||||
pub fn candidate_paths(home: &Path) -> Vec<PathBuf> {
|
||||
let mut v = vec![
|
||||
PathBuf::from("/Applications/CrossOver.app"),
|
||||
home.join("Applications/CrossOver.app"),
|
||||
];
|
||||
if let Some(found) = run(
|
||||
"/usr/bin/mdfind",
|
||||
&[&format!("kMDItemCFBundleIdentifier == '{BUNDLE_ID}'")],
|
||||
) {
|
||||
for line in found.lines().filter(|l| !l.is_empty()) {
|
||||
let p = PathBuf::from(line);
|
||||
if !v.contains(&p) {
|
||||
v.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
pub fn discover(candidates: &[PathBuf]) -> Vec<Install> {
|
||||
candidates.iter().filter_map(|p| inspect(p)).collect()
|
||||
}
|
||||
|
||||
/// Inspect one bundle. Returns None if the path has no readable `Contents/Info.plist`.
|
||||
pub fn inspect(app: &Path) -> Option<Install> {
|
||||
let plist = app.join("Contents/Info.plist");
|
||||
if !plist.is_file() {
|
||||
return None;
|
||||
}
|
||||
let json = run(
|
||||
"/usr/bin/plutil",
|
||||
&["-convert", "json", "-o", "-", plist.to_str()?],
|
||||
)?;
|
||||
let exe = crate::host_string(&json, "CFBundleExecutable");
|
||||
let archs = exe.and_then(|e| {
|
||||
let p = app.join("Contents/MacOS").join(e);
|
||||
run("/usr/bin/lipo", &["-archs", p.to_str()?])
|
||||
.map(|s| s.split_whitespace().map(String::from).collect())
|
||||
});
|
||||
Some(Install {
|
||||
path: app.to_path_buf(),
|
||||
bundle_id: crate::host_string(&json, "CFBundleIdentifier"),
|
||||
short_version: crate::host_string(&json, "CFBundleShortVersionString"),
|
||||
build_version: crate::host_string(&json, "CFBundleVersion"),
|
||||
executable_archs: archs,
|
||||
minimum_macos: crate::host_string(&json, "LSMinimumSystemVersion"),
|
||||
})
|
||||
}
|
||||
|
||||
/// A documented CrossOver preference, or None when unset or unreadable.
|
||||
pub fn preference(key: &str) -> Option<String> {
|
||||
run("/usr/bin/defaults", &["read", BUNDLE_ID, key])
|
||||
}
|
||||
|
||||
impl Install {
|
||||
pub fn to_json(&self) -> Json {
|
||||
Json::obj(vec![
|
||||
("path", Json::str(self.path.display().to_string())),
|
||||
("bundle_id", Json::opt_str(self.bundle_id.clone())),
|
||||
("short_version", Json::opt_str(self.short_version.clone())),
|
||||
("build_version", Json::opt_str(self.build_version.clone())),
|
||||
(
|
||||
"executable_archs",
|
||||
self.executable_archs.as_ref().map_or(Json::Null, |a| {
|
||||
Json::Arr(a.iter().map(|s| Json::str(s.clone())).collect())
|
||||
}),
|
||||
),
|
||||
("minimum_macos", Json::opt_str(self.minimum_macos.clone())),
|
||||
(
|
||||
"bundle_id_is_codeweavers_crossover",
|
||||
Json::Bool(self.bundle_id.as_deref() == Some(BUNDLE_ID)),
|
||||
),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
// A synthetic bundle written by the test: it proves the metadata path, not that
|
||||
// any real CrossOver build has this layout.
|
||||
fn fake_bundle(dir: &Path) -> PathBuf {
|
||||
let app = dir.join("CrossOver.app");
|
||||
fs::create_dir_all(app.join("Contents/MacOS")).unwrap();
|
||||
fs::write(
|
||||
app.join("Contents/Info.plist"),
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>CFBundleExecutable</key><string>CrossOver</string>
|
||||
<key>CFBundleIdentifier</key><string>com.codeweavers.CrossOver</string>
|
||||
<key>CFBundleShortVersionString</key><string>99.1.2</string>
|
||||
<key>CFBundleVersion</key><string>12345</string>
|
||||
<key>LSMinimumSystemVersion</key><string>14.0</string>
|
||||
</dict></plist>"#,
|
||||
)
|
||||
.unwrap();
|
||||
// Copy a real system executable so `lipo -archs` has a Mach-O to read.
|
||||
fs::copy("/usr/bin/true", app.join("Contents/MacOS/CrossOver")).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_bundle_metadata() {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return;
|
||||
}
|
||||
let tmp = std::env::temp_dir().join(format!("bxhybrid-co-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&tmp);
|
||||
fs::create_dir_all(&tmp).unwrap();
|
||||
let app = fake_bundle(&tmp);
|
||||
let i = inspect(&app).expect("inspect");
|
||||
assert_eq!(i.short_version.as_deref(), Some("99.1.2"));
|
||||
assert_eq!(i.build_version.as_deref(), Some("12345"));
|
||||
assert_eq!(i.minimum_macos.as_deref(), Some("14.0"));
|
||||
assert_eq!(i.bundle_id.as_deref(), Some(BUNDLE_ID));
|
||||
assert!(
|
||||
i.executable_archs.as_ref().is_some_and(|a| !a.is_empty()),
|
||||
"{:?}",
|
||||
i.executable_archs
|
||||
);
|
||||
assert_eq!(discover(&[app.clone(), tmp.join("Missing.app")]).len(), 1);
|
||||
fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_plistless_bundle_is_none() {
|
||||
let tmp = std::env::temp_dir().join(format!("bxhybrid-co2-{}", std::process::id()));
|
||||
fs::create_dir_all(tmp.join("X.app/Contents")).unwrap();
|
||||
assert!(inspect(&tmp.join("X.app")).is_none());
|
||||
assert!(inspect(&tmp.join("Nope.app")).is_none());
|
||||
fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//! Frame-time statistics from a list of frame intervals in milliseconds (issue #145).
|
||||
//!
|
||||
//! Percentiles use the nearest-rank method on the sorted intervals: the p-th percentile is
|
||||
//! the value at rank ceil(p/100 * n) (1-based). "1 % low FPS" is 1000 divided by the 99th
|
||||
//! percentile interval. These definitions are fixed here so reports are comparable; other
|
||||
//! tools define lows differently (for example as the mean of the worst 1 %).
|
||||
|
||||
use crate::json::Json;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct FrameStats {
|
||||
pub frames: usize,
|
||||
pub total_ms: f64,
|
||||
pub mean_ms: f64,
|
||||
pub avg_fps: f64,
|
||||
pub min_ms: f64,
|
||||
pub max_ms: f64,
|
||||
pub p50_ms: f64,
|
||||
pub p95_ms: f64,
|
||||
pub p99_ms: f64,
|
||||
pub p999_ms: f64,
|
||||
pub low_1pct_fps: f64,
|
||||
pub low_01pct_fps: f64,
|
||||
/// Frames longer than twice the median interval.
|
||||
pub stutters: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum FrameError {
|
||||
Empty,
|
||||
Invalid { index: usize, value: f64 },
|
||||
Parse { line: usize, text: String },
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FrameError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
FrameError::Empty => write!(f, "no frame intervals"),
|
||||
FrameError::Invalid { index, value } => {
|
||||
write!(
|
||||
f,
|
||||
"frame {index}: interval {value} is not a positive finite number of milliseconds"
|
||||
)
|
||||
}
|
||||
FrameError::Parse { line, text } => {
|
||||
write!(f, "line {line}: cannot parse {text:?} as milliseconds")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for FrameError {}
|
||||
|
||||
fn nearest_rank(sorted: &[f64], pct: f64) -> f64 {
|
||||
let n = sorted.len();
|
||||
let rank = ((pct / 100.0) * n as f64).ceil().max(1.0) as usize;
|
||||
sorted[rank.min(n) - 1]
|
||||
}
|
||||
|
||||
pub fn analyze(intervals_ms: &[f64]) -> Result<FrameStats, FrameError> {
|
||||
if intervals_ms.is_empty() {
|
||||
return Err(FrameError::Empty);
|
||||
}
|
||||
for (index, &value) in intervals_ms.iter().enumerate() {
|
||||
if !value.is_finite() || value <= 0.0 {
|
||||
return Err(FrameError::Invalid { index, value });
|
||||
}
|
||||
}
|
||||
let mut sorted = intervals_ms.to_vec();
|
||||
sorted.sort_by(|a, b| a.total_cmp(b));
|
||||
let total: f64 = intervals_ms.iter().sum();
|
||||
let n = sorted.len();
|
||||
let p50 = nearest_rank(&sorted, 50.0);
|
||||
let p99 = nearest_rank(&sorted, 99.0);
|
||||
let p999 = nearest_rank(&sorted, 99.9);
|
||||
Ok(FrameStats {
|
||||
frames: n,
|
||||
total_ms: total,
|
||||
mean_ms: total / n as f64,
|
||||
avg_fps: n as f64 / (total / 1000.0),
|
||||
min_ms: sorted[0],
|
||||
max_ms: sorted[n - 1],
|
||||
p50_ms: p50,
|
||||
p95_ms: nearest_rank(&sorted, 95.0),
|
||||
p99_ms: p99,
|
||||
p999_ms: p999,
|
||||
low_1pct_fps: 1000.0 / p99,
|
||||
low_01pct_fps: 1000.0 / p999,
|
||||
stutters: intervals_ms.iter().filter(|&&v| v > 2.0 * p50).count(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse one interval per line; blank lines and lines starting with `#` are skipped.
|
||||
pub fn parse_intervals(text: &str) -> Result<Vec<f64>, FrameError> {
|
||||
let mut out = Vec::new();
|
||||
for (i, line) in text.lines().enumerate() {
|
||||
let t = line.trim();
|
||||
if t.is_empty() || t.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let v: f64 = t.parse().map_err(|_| FrameError::Parse {
|
||||
line: i + 1,
|
||||
text: t.to_string(),
|
||||
})?;
|
||||
out.push(v);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl FrameStats {
|
||||
pub fn to_json(&self) -> Json {
|
||||
Json::obj(vec![
|
||||
("frames", Json::Num(self.frames as f64)),
|
||||
("total_ms", Json::Num(self.total_ms)),
|
||||
("mean_ms", Json::Num(self.mean_ms)),
|
||||
("avg_fps", Json::Num(self.avg_fps)),
|
||||
("min_ms", Json::Num(self.min_ms)),
|
||||
("max_ms", Json::Num(self.max_ms)),
|
||||
("p50_ms", Json::Num(self.p50_ms)),
|
||||
("p95_ms", Json::Num(self.p95_ms)),
|
||||
("p99_ms", Json::Num(self.p99_ms)),
|
||||
("p999_ms", Json::Num(self.p999_ms)),
|
||||
("low_1pct_fps", Json::Num(self.low_1pct_fps)),
|
||||
("low_0_1pct_fps", Json::Num(self.low_01pct_fps)),
|
||||
("stutters_over_2x_median", Json::Num(self.stutters as f64)),
|
||||
("percentile_method", Json::str("nearest-rank")),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Expected values below are worked out by hand, not produced by analyze().
|
||||
#[test]
|
||||
fn known_answer_ten_frames() {
|
||||
// Sorted: 10,10,10,10,10,10,10,10,20,100. Total 200 ms, n = 10.
|
||||
let v = [10.0, 10.0, 10.0, 10.0, 20.0, 10.0, 10.0, 10.0, 100.0, 10.0];
|
||||
let s = analyze(&v).unwrap();
|
||||
assert_eq!(s.frames, 10);
|
||||
assert_eq!(s.total_ms, 200.0);
|
||||
assert_eq!(s.mean_ms, 20.0);
|
||||
assert_eq!(s.avg_fps, 50.0);
|
||||
assert_eq!(s.p50_ms, 10.0); // rank 5
|
||||
assert_eq!(s.p95_ms, 100.0); // rank ceil(9.5) = 10
|
||||
assert_eq!(s.p99_ms, 100.0);
|
||||
assert_eq!(s.low_1pct_fps, 10.0);
|
||||
assert_eq!(s.stutters, 1); // threshold is 2 * 10 = 20; 20 is not > 20, only 100 is.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stutter_threshold_is_strict() {
|
||||
let s = analyze(&[10.0, 10.0, 10.0, 20.0, 21.0]).unwrap();
|
||||
assert_eq!(s.stutters, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_frame_per_second() {
|
||||
let s = analyze(&[1000.0, 1000.0]).unwrap();
|
||||
assert_eq!(s.avg_fps, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_input() {
|
||||
assert_eq!(analyze(&[]), Err(FrameError::Empty));
|
||||
assert!(matches!(
|
||||
analyze(&[1.0, 0.0]),
|
||||
Err(FrameError::Invalid { index: 1, .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
analyze(&[f64::NAN]),
|
||||
Err(FrameError::Invalid { .. })
|
||||
));
|
||||
assert!(matches!(analyze(&[-3.0]), Err(FrameError::Invalid { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_text() {
|
||||
assert_eq!(
|
||||
parse_intervals("# c\n16.5\n\n 8 \n").unwrap(),
|
||||
vec![16.5, 8.0]
|
||||
);
|
||||
assert_eq!(
|
||||
parse_intervals("1\nabc\n"),
|
||||
Err(FrameError::Parse {
|
||||
line: 2,
|
||||
text: "abc".into()
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//! Host receipt: what this Mac is, from documented system interfaces (issue #353).
|
||||
//!
|
||||
//! Every field is `Option` where the probe can fail; absence is reported as null, not guessed.
|
||||
|
||||
use crate::cmdutil::run;
|
||||
use crate::json::Json;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct HostReceipt {
|
||||
pub macos_version: Option<String>,
|
||||
pub macos_build: Option<String>,
|
||||
pub chip: Option<String>,
|
||||
pub apple_silicon: Option<bool>,
|
||||
pub memory_bytes: Option<u64>,
|
||||
pub logical_cpus: Option<u32>,
|
||||
pub performance_cores: Option<u32>,
|
||||
pub efficiency_cores: Option<u32>,
|
||||
/// True only if an x86_64 slice of a system binary actually executed.
|
||||
pub rosetta_executes_x86_64: Option<bool>,
|
||||
pub gpu_name: Option<String>,
|
||||
pub gpu_cores: Option<String>,
|
||||
pub metal_support: Option<String>,
|
||||
pub gpu_wired: GpuWired,
|
||||
pub host_arch_of_this_binary: &'static str,
|
||||
}
|
||||
|
||||
fn sysctl(name: &str) -> Option<String> {
|
||||
run("/usr/sbin/sysctl", &["-n", name])
|
||||
}
|
||||
|
||||
/// GPU wired-memory sysctls (issue #386), recorded as the raw integers `sysctl -n` prints.
|
||||
///
|
||||
/// Read only: nothing in BetterXen writes these keys. `None` means the key is absent (the
|
||||
/// command failed) or its output is not an unsigned integer. A value of 0 was observed on an
|
||||
/// M4 and an M5; Apple does not document what 0 means in anything reviewed for #386, so it is
|
||||
/// reported as observed and never interpreted (for example as "system default" or "no limit").
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct GpuWired {
|
||||
/// `iogpu.wired_limit_mb`.
|
||||
pub limit_mb: Option<u64>,
|
||||
/// `iogpu.wired_lwm_mb`.
|
||||
pub lwm_mb: Option<u64>,
|
||||
}
|
||||
|
||||
pub const GPU_WIRED_SOURCE: &str = "sysctl -n iogpu.wired_limit_mb, iogpu.wired_lwm_mb (read-only; raw values, meaning of 0 undocumented)";
|
||||
|
||||
/// Read the GPU wired-memory keys through `read`, which returns a key's trimmed output or
|
||||
/// `None` when the key cannot be read. Injected so tests do not depend on this Mac.
|
||||
pub fn gpu_wired_with(read: impl Fn(&str) -> Option<String>) -> GpuWired {
|
||||
let num = |key: &str| read(key).and_then(|v| v.trim().parse::<u64>().ok());
|
||||
GpuWired {
|
||||
limit_mb: num("iogpu.wired_limit_mb"),
|
||||
lwm_mb: num("iogpu.wired_lwm_mb"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn gpu_wired() -> GpuWired {
|
||||
gpu_wired_with(sysctl)
|
||||
}
|
||||
|
||||
impl GpuWired {
|
||||
/// The record fields shared by the host receipt and every run record.
|
||||
pub fn json_fields(&self) -> Vec<(&'static str, Json)> {
|
||||
let n = |v: Option<u64>| v.map_or(Json::Null, |x| Json::Num(x as f64));
|
||||
vec![
|
||||
("gpu_wired_limit_mb", n(self.limit_mb)),
|
||||
("gpu_wired_lwm_mb", n(self.lwm_mb)),
|
||||
("gpu_wired_source", Json::str(GPU_WIRED_SOURCE)),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn collect() -> HostReceipt {
|
||||
let gpu = run(
|
||||
"/usr/sbin/system_profiler",
|
||||
&["SPDisplaysDataType", "-json"],
|
||||
)
|
||||
.and_then(|j| parse_gpu(&j));
|
||||
HostReceipt {
|
||||
macos_version: run("/usr/bin/sw_vers", &["-productVersion"]),
|
||||
macos_build: sysctl("kern.osversion"),
|
||||
chip: sysctl("machdep.cpu.brand_string"),
|
||||
apple_silicon: sysctl("hw.optional.arm64").map(|v| v == "1"),
|
||||
memory_bytes: sysctl("hw.memsize").and_then(|v| v.parse().ok()),
|
||||
logical_cpus: sysctl("hw.logicalcpu").and_then(|v| v.parse().ok()),
|
||||
performance_cores: sysctl("hw.perflevel0.physicalcpu").and_then(|v| v.parse().ok()),
|
||||
efficiency_cores: sysctl("hw.perflevel1.physicalcpu").and_then(|v| v.parse().ok()),
|
||||
// Executes the x86_64 slice of /usr/bin/true. Failure means Rosetta cannot run it
|
||||
// now; it does not distinguish "not installed" from "disabled".
|
||||
rosetta_executes_x86_64: Some(
|
||||
run("/usr/bin/arch", &["-x86_64", "/usr/bin/true"]).is_some(),
|
||||
),
|
||||
gpu_name: gpu.as_ref().map(|g| g.0.clone()),
|
||||
gpu_cores: gpu.as_ref().and_then(|g| g.1.clone()),
|
||||
metal_support: gpu.as_ref().and_then(|g| g.2.clone()),
|
||||
gpu_wired: gpu_wired(),
|
||||
host_arch_of_this_binary: std::env::consts::ARCH,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pull `sppci_model`, `sppci_cores` and `spdisplays_mtlgpufamilysupport` of the first display
|
||||
/// entry from `system_profiler SPDisplaysDataType -json` output. Returns None if the model
|
||||
/// key is absent. Uses a small string scan because this crate has no JSON parser dependency.
|
||||
pub fn parse_gpu(json: &str) -> Option<(String, Option<String>, Option<String>)> {
|
||||
let model = string_value(json, "sppci_model")?;
|
||||
Some((
|
||||
model,
|
||||
string_value(json, "sppci_cores"),
|
||||
string_value(json, "spdisplays_mtlgpufamilysupport"),
|
||||
))
|
||||
}
|
||||
|
||||
fn string_value(json: &str, key: &str) -> Option<String> {
|
||||
let needle = format!("\"{key}\"");
|
||||
let at = json.find(&needle)? + needle.len();
|
||||
let rest = json[at..].trim_start().strip_prefix(':')?.trim_start();
|
||||
let rest = rest.strip_prefix('"')?;
|
||||
let end = rest.find('"')?;
|
||||
Some(rest[..end].to_string())
|
||||
}
|
||||
|
||||
impl HostReceipt {
|
||||
pub fn to_json(&self) -> Json {
|
||||
let n = |v: Option<u32>| v.map_or(Json::Null, |x| Json::Num(x as f64));
|
||||
let mut fields = vec![
|
||||
("macos_version", Json::opt_str(self.macos_version.clone())),
|
||||
("macos_build", Json::opt_str(self.macos_build.clone())),
|
||||
("chip", Json::opt_str(self.chip.clone())),
|
||||
(
|
||||
"apple_silicon",
|
||||
self.apple_silicon.map_or(Json::Null, Json::Bool),
|
||||
),
|
||||
(
|
||||
"memory_bytes",
|
||||
self.memory_bytes
|
||||
.map_or(Json::Null, |x| Json::Num(x as f64)),
|
||||
),
|
||||
("logical_cpus", n(self.logical_cpus)),
|
||||
("performance_cores", n(self.performance_cores)),
|
||||
("efficiency_cores", n(self.efficiency_cores)),
|
||||
(
|
||||
"rosetta_executes_x86_64",
|
||||
self.rosetta_executes_x86_64.map_or(Json::Null, Json::Bool),
|
||||
),
|
||||
("gpu_name", Json::opt_str(self.gpu_name.clone())),
|
||||
("gpu_cores", Json::opt_str(self.gpu_cores.clone())),
|
||||
("metal_support", Json::opt_str(self.metal_support.clone())),
|
||||
];
|
||||
fields.extend(self.gpu_wired.json_fields());
|
||||
fields.push((
|
||||
"receipt_binary_arch",
|
||||
Json::str(self.host_arch_of_this_binary),
|
||||
));
|
||||
Json::obj(fields)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_gpu_fixture() {
|
||||
let j = r#"{"SPDisplaysDataType":[{"sppci_cores":"10","sppci_model":"Apple M4",
|
||||
"spdisplays_mtlgpufamilysupport":"spdisplays_metal4"}]}"#;
|
||||
let g = parse_gpu(j).unwrap();
|
||||
assert_eq!(g.0, "Apple M4");
|
||||
assert_eq!(g.1.as_deref(), Some("10"));
|
||||
assert_eq!(g.2.as_deref(), Some("spdisplays_metal4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_gpu_is_none() {
|
||||
assert!(parse_gpu("{}").is_none());
|
||||
}
|
||||
|
||||
fn reader<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
|
||||
move |key| {
|
||||
pairs
|
||||
.iter()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_wired_values_are_reported_raw() {
|
||||
let w = gpu_wired_with(reader(&[
|
||||
("iogpu.wired_limit_mb", "24576"),
|
||||
("iogpu.wired_lwm_mb", "0"),
|
||||
]));
|
||||
assert_eq!(w.limit_mb, Some(24576));
|
||||
// 0 is a value like any other, not "absent".
|
||||
assert_eq!(w.lwm_mb, Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_unparsable_gpu_wired_keys_are_null() {
|
||||
let w = gpu_wired_with(reader(&[("iogpu.wired_limit_mb", "unlimited")]));
|
||||
assert_eq!(w, GpuWired::default());
|
||||
let j = Json::obj(w.json_fields()).render();
|
||||
assert!(j.contains("\"gpu_wired_limit_mb\": null"), "{j}");
|
||||
assert!(j.contains("\"gpu_wired_lwm_mb\": null"), "{j}");
|
||||
assert!(j.contains("\"gpu_wired_source\": \"sysctl -n"), "{j}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receipt_carries_gpu_wired_fields() {
|
||||
let mut r = collect();
|
||||
r.gpu_wired = GpuWired {
|
||||
limit_mb: Some(0),
|
||||
lwm_mb: None,
|
||||
};
|
||||
let j = r.to_json().render();
|
||||
assert!(j.contains("\"gpu_wired_limit_mb\": 0"), "{j}");
|
||||
assert!(j.contains("\"gpu_wired_lwm_mb\": null"), "{j}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_runs_on_this_host() {
|
||||
let r = collect();
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(r.macos_version.is_some());
|
||||
assert!(r.memory_bytes.unwrap() > 0);
|
||||
}
|
||||
assert!(r.to_json().render().contains("receipt_binary_arch"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Minimal JSON value and writer. Output only; no parsing is needed by this crate.
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Json {
|
||||
Null,
|
||||
Bool(bool),
|
||||
Num(f64),
|
||||
Str(String),
|
||||
Arr(Vec<Json>),
|
||||
Obj(Vec<(String, Json)>),
|
||||
}
|
||||
|
||||
impl Json {
|
||||
pub fn str(s: impl Into<String>) -> Json {
|
||||
Json::Str(s.into())
|
||||
}
|
||||
pub fn opt_str(s: Option<String>) -> Json {
|
||||
s.map_or(Json::Null, Json::Str)
|
||||
}
|
||||
pub fn obj(fields: Vec<(&str, Json)>) -> Json {
|
||||
Json::Obj(
|
||||
fields
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k.to_string(), v))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = String::new();
|
||||
self.write(&mut out, 0);
|
||||
out.push('\n');
|
||||
out
|
||||
}
|
||||
|
||||
fn write(&self, out: &mut String, depth: usize) {
|
||||
let pad = |out: &mut String, d: usize| out.push_str(&" ".repeat(d));
|
||||
match self {
|
||||
Json::Null => out.push_str("null"),
|
||||
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
|
||||
Json::Num(n) if n.is_finite() => {
|
||||
if n.fract() == 0.0 && n.abs() < 1e15 {
|
||||
out.push_str(&format!("{}", *n as i64));
|
||||
} else {
|
||||
out.push_str(&format!("{n}"));
|
||||
}
|
||||
}
|
||||
// JSON has no NaN or infinity; refuse to invent a number.
|
||||
Json::Num(_) => out.push_str("null"),
|
||||
Json::Str(s) => escape(s, out),
|
||||
Json::Arr(items) if items.is_empty() => out.push_str("[]"),
|
||||
Json::Arr(items) => {
|
||||
out.push_str("[\n");
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
pad(out, depth + 1);
|
||||
item.write(out, depth + 1);
|
||||
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
|
||||
}
|
||||
pad(out, depth);
|
||||
out.push(']');
|
||||
}
|
||||
Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
|
||||
Json::Obj(fields) => {
|
||||
out.push_str("{\n");
|
||||
for (i, (k, v)) in fields.iter().enumerate() {
|
||||
pad(out, depth + 1);
|
||||
escape(k, out);
|
||||
out.push_str(": ");
|
||||
v.write(out, depth + 1);
|
||||
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
|
||||
}
|
||||
pad(out, depth);
|
||||
out.push('}');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn escape(s: &str, out: &mut String) {
|
||||
out.push('"');
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn escapes_and_nests() {
|
||||
let j = Json::obj(vec![
|
||||
("a", Json::str("q\"\\\n\u{1}")),
|
||||
(
|
||||
"b",
|
||||
Json::Arr(vec![Json::Num(1.0), Json::Num(0.5), Json::Null]),
|
||||
),
|
||||
("c", Json::Num(f64::NAN)),
|
||||
]);
|
||||
let r = j.render();
|
||||
assert!(r.contains(r#""a": "q\"\\\n\u0001""#), "{r}");
|
||||
assert!(r.contains("0.5"));
|
||||
assert!(r.contains(r#""c": null"#));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! BetterXen hybrid tooling: environment checks, executable identification, supervised
|
||||
//! launches and measurement around an externally installed CrossOver. Nothing here claims
|
||||
//! game or console compatibility.
|
||||
|
||||
pub mod cli;
|
||||
pub mod cmdutil;
|
||||
pub mod crossover;
|
||||
pub mod frames;
|
||||
pub mod host;
|
||||
pub mod json;
|
||||
pub mod memory;
|
||||
pub mod pe;
|
||||
pub mod preflight;
|
||||
pub mod records;
|
||||
pub mod run;
|
||||
pub mod session;
|
||||
pub mod toolchain;
|
||||
|
||||
/// Value of a top-level string key in flat JSON produced by `plutil -convert json`.
|
||||
pub fn host_string(json: &str, key: &str) -> Option<String> {
|
||||
let needle = format!("\"{key}\"");
|
||||
let at = json.find(&needle)? + needle.len();
|
||||
let rest = json[at..]
|
||||
.trim_start()
|
||||
.strip_prefix(':')?
|
||||
.trim_start()
|
||||
.strip_prefix('"')?;
|
||||
let mut out = String::new();
|
||||
let mut chars = rest.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'"' => return Some(out),
|
||||
'\\' => out.push(chars.next()?),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
//! Memory-pressure supervision of a child process.
|
||||
//!
|
||||
//! Adapted in concept from the memory guard in `mac/run-victory.sh` of
|
||||
//! <https://github.com/skakwy/victory-mac> (author skakwy, GPL-3.0; commit 22b3f8e, used with
|
||||
//! the author's permission): do not start a workload when little memory is free, and stop it
|
||||
//! when system-wide free memory falls below a limit, because GPU memory is wired under
|
||||
//! unified memory and a runaway workload can take the whole Mac down. This version is
|
||||
//! reimplemented in Rust, stops the child with SIGTERM before SIGKILL, and reports why it
|
||||
//! stopped. It supervises any command; it contains nothing game-specific.
|
||||
//!
|
||||
//! The reading is the "System-wide memory free percentage" line of `memory_pressure -Q`.
|
||||
//! That line was observed on macOS 27.0 (build 26A428); its format is not a documented
|
||||
//! stable interface, so an unreadable value is an error, never "assume enough memory".
|
||||
|
||||
use crate::cmdutil::run;
|
||||
use std::process::{Child, Command};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub fn parse_free_percentage(output: &str) -> Option<u8> {
|
||||
let line = output
|
||||
.lines()
|
||||
.find(|l| l.contains("System-wide memory free percentage"))?;
|
||||
let digits: String = line
|
||||
.split(':')
|
||||
.nth(1)?
|
||||
.trim()
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_digit())
|
||||
.collect();
|
||||
let v: u8 = digits.parse().ok()?;
|
||||
(v <= 100).then_some(v)
|
||||
}
|
||||
|
||||
pub fn free_percentage() -> Option<u8> {
|
||||
run("/usr/bin/memory_pressure", &["-Q"]).and_then(|o| parse_free_percentage(&o))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Limits {
|
||||
/// Refuse to start below this percent free.
|
||||
pub min_start_free: u8,
|
||||
/// Stop the child when free memory drops below this percent.
|
||||
pub min_free: u8,
|
||||
pub poll: Duration,
|
||||
/// Time between SIGTERM and SIGKILL.
|
||||
pub grace: Duration,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Outcome {
|
||||
/// The child ran to completion; `None` means it ended by a signal.
|
||||
Exited(Option<i32>),
|
||||
RefusedToStart {
|
||||
free: u8,
|
||||
need: u8,
|
||||
},
|
||||
StoppedLowMemory {
|
||||
free: u8,
|
||||
limit: u8,
|
||||
},
|
||||
/// Memory could not be read, so no guarantee can be given.
|
||||
MemoryUnreadable,
|
||||
SpawnFailed(String),
|
||||
}
|
||||
|
||||
pub(crate) fn terminate(child: &mut Child, grace: Duration) {
|
||||
let _ = Command::new("/bin/kill")
|
||||
.args(["-TERM", &child.id().to_string()])
|
||||
.status();
|
||||
let t0 = Instant::now();
|
||||
while t0.elapsed() < grace {
|
||||
if matches!(child.try_wait(), Ok(Some(_))) {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
/// Run `program` under `limits`, reading memory through `read_free`.
|
||||
pub fn supervise(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
limits: Limits,
|
||||
read_free: &mut dyn FnMut() -> Option<u8>,
|
||||
) -> Outcome {
|
||||
match read_free() {
|
||||
None => return Outcome::MemoryUnreadable,
|
||||
Some(free) if free < limits.min_start_free => {
|
||||
return Outcome::RefusedToStart {
|
||||
free,
|
||||
need: limits.min_start_free,
|
||||
};
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
let mut child = match Command::new(program).args(args).spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => return Outcome::SpawnFailed(format!("{program}: {e}")),
|
||||
};
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => return Outcome::Exited(status.code()),
|
||||
Ok(None) => {}
|
||||
Err(e) => return Outcome::SpawnFailed(e.to_string()),
|
||||
}
|
||||
match read_free() {
|
||||
None => {
|
||||
terminate(&mut child, limits.grace);
|
||||
return Outcome::MemoryUnreadable;
|
||||
}
|
||||
Some(free) if free < limits.min_free => {
|
||||
terminate(&mut child, limits.grace);
|
||||
return Outcome::StoppedLowMemory {
|
||||
free,
|
||||
limit: limits.min_free,
|
||||
};
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
std::thread::sleep(limits.poll);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits {
|
||||
min_start_free: 50,
|
||||
min_free: 20,
|
||||
poll: Duration::from_millis(20),
|
||||
grace: Duration::from_millis(500),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_memory_pressure_output() {
|
||||
let real = "The system has 25769803776 (1572864 pages with a page size of 16384).\nSystem-wide memory free percentage: 71%\n";
|
||||
assert_eq!(parse_free_percentage(real), Some(71));
|
||||
assert_eq!(
|
||||
parse_free_percentage("System-wide memory free percentage: 100%"),
|
||||
Some(100)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_free_percentage("System-wide memory free percentage: 101%"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
parse_free_percentage("System-wide memory free percentage: x"),
|
||||
None
|
||||
);
|
||||
assert_eq!(parse_free_percentage("nothing"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_to_start_when_low() {
|
||||
let out = supervise("/usr/bin/true", &[], limits(), &mut || Some(30));
|
||||
assert_eq!(out, Outcome::RefusedToStart { free: 30, need: 50 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_memory_is_an_error() {
|
||||
assert_eq!(
|
||||
supervise("/usr/bin/true", &[], limits(), &mut || None),
|
||||
Outcome::MemoryUnreadable
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_exit_code_is_reported() {
|
||||
let out = supervise(
|
||||
"/bin/sh",
|
||||
&["-c".into(), "exit 7".into()],
|
||||
limits(),
|
||||
&mut || Some(90),
|
||||
);
|
||||
assert_eq!(out, Outcome::Exited(Some(7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_child_when_memory_drops() {
|
||||
let mut calls = 0;
|
||||
let t0 = Instant::now();
|
||||
let out = supervise("/bin/sleep", &["30".into()], limits(), &mut || {
|
||||
calls += 1;
|
||||
Some(if calls < 4 { 90 } else { 10 })
|
||||
});
|
||||
assert_eq!(
|
||||
out,
|
||||
Outcome::StoppedLowMemory {
|
||||
free: 10,
|
||||
limit: 20
|
||||
}
|
||||
);
|
||||
assert!(
|
||||
t0.elapsed() < Duration::from_secs(10),
|
||||
"child was not stopped promptly"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_reading_is_available_on_macos() {
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(free_percentage().is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
//! Identify a Windows executable before it is handed to CrossOver.
|
||||
//!
|
||||
//! Reads only the headers and the import directory names of a PE/COFF image, following
|
||||
//! Microsoft's published "PE Format" specification. The file is untrusted input: every
|
||||
//! offset is checked, counts are capped, and nothing is executed. This answers "is this a
|
||||
//! launchable x86 Windows program, and which DLLs does it import"; it does not prove that
|
||||
//! the program will run.
|
||||
|
||||
use crate::json::Json;
|
||||
|
||||
/// Largest file this will read. Larger programs are refused rather than partly checked.
|
||||
pub const MAX_BYTES: u64 = 1 << 30;
|
||||
const MAX_SECTIONS: usize = 96;
|
||||
const MAX_IMPORTS: usize = 512;
|
||||
const MAX_NAME: usize = 256;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum Machine {
|
||||
X86_64,
|
||||
I386,
|
||||
Arm64,
|
||||
Other(u16),
|
||||
}
|
||||
|
||||
impl Machine {
|
||||
pub fn name(self) -> String {
|
||||
match self {
|
||||
Machine::X86_64 => "x86_64".into(),
|
||||
Machine::I386 => "i386".into(),
|
||||
Machine::Arm64 => "arm64".into(),
|
||||
Machine::Other(m) => format!("unknown_0x{m:04x}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Image {
|
||||
pub machine: Machine,
|
||||
pub pe32_plus: bool,
|
||||
pub subsystem: u16,
|
||||
pub is_dll: bool,
|
||||
/// Imported DLL names, lower-cased, from the (non-delayed) import directory.
|
||||
pub imports: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Error {
|
||||
NotPe(&'static str),
|
||||
Truncated(&'static str),
|
||||
Unsupported(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Error::NotPe(why) => write!(f, "not a PE executable: {why}"),
|
||||
Error::Truncated(what) => write!(f, "truncated or inconsistent PE: {what}"),
|
||||
Error::Unsupported(why) => write!(f, "unsupported executable: {why}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bytes<'a>(d: &'a [u8], at: usize, n: usize, what: &'static str) -> Result<&'a [u8], Error> {
|
||||
at.checked_add(n)
|
||||
.and_then(|end| d.get(at..end))
|
||||
.ok_or(Error::Truncated(what))
|
||||
}
|
||||
|
||||
fn u16_at(d: &[u8], at: usize, what: &'static str) -> Result<u16, Error> {
|
||||
let b = bytes(d, at, 2, what)?;
|
||||
Ok(u16::from_le_bytes([b[0], b[1]]))
|
||||
}
|
||||
|
||||
fn u32_at(d: &[u8], at: usize, what: &'static str) -> Result<u32, Error> {
|
||||
let b = bytes(d, at, 4, what)?;
|
||||
Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
|
||||
}
|
||||
|
||||
struct Section {
|
||||
va: u32,
|
||||
size: u32,
|
||||
file: u32,
|
||||
}
|
||||
|
||||
fn file_offset(sections: &[Section], rva: u32) -> Option<usize> {
|
||||
sections.iter().find_map(|s| {
|
||||
let into = rva.checked_sub(s.va)?;
|
||||
(into < s.size).then(|| s.file.checked_add(into).map(|v| v as usize))?
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse(d: &[u8]) -> Result<Image, Error> {
|
||||
if bytes(d, 0, 2, "DOS magic").map_err(|_| Error::NotPe("file too small"))? != b"MZ" {
|
||||
return Err(Error::NotPe("missing MZ magic"));
|
||||
}
|
||||
let pe = u32_at(d, 0x3c, "e_lfanew")? as usize;
|
||||
if bytes(d, pe, 4, "PE signature")? != b"PE\0\0" {
|
||||
return Err(Error::NotPe("missing PE signature"));
|
||||
}
|
||||
let coff = pe.checked_add(4).ok_or(Error::Truncated("COFF header"))?;
|
||||
let machine = match u16_at(d, coff, "machine")? {
|
||||
0x8664 => Machine::X86_64,
|
||||
0x014c => Machine::I386,
|
||||
0xaa64 => Machine::Arm64,
|
||||
m => Machine::Other(m),
|
||||
};
|
||||
let section_count = u16_at(d, coff + 2, "section count")? as usize;
|
||||
let optional_size = u16_at(d, coff + 16, "optional header size")? as usize;
|
||||
let characteristics = u16_at(d, coff + 18, "characteristics")?;
|
||||
if characteristics & 0x0002 == 0 {
|
||||
return Err(Error::NotPe("not marked as an executable image"));
|
||||
}
|
||||
if section_count > MAX_SECTIONS {
|
||||
return Err(Error::Truncated("implausible section count"));
|
||||
}
|
||||
let opt = coff + 20;
|
||||
let optional = bytes(d, opt, optional_size, "optional header")?;
|
||||
let (pe32_plus, count_at, dirs_at) = match u16_at(optional, 0, "optional magic")? {
|
||||
0x20b => (true, 108, 112),
|
||||
0x10b => (false, 92, 96),
|
||||
_ => return Err(Error::NotPe("unknown optional header magic")),
|
||||
};
|
||||
let subsystem = u16_at(optional, 68, "subsystem")?;
|
||||
|
||||
let mut sections = Vec::with_capacity(section_count);
|
||||
let table = opt + optional_size;
|
||||
for i in 0..section_count {
|
||||
let at = table + i * 40;
|
||||
sections.push(Section {
|
||||
va: u32_at(d, at + 12, "section address")?,
|
||||
size: u32_at(d, at + 16, "section raw size")?,
|
||||
file: u32_at(d, at + 20, "section raw pointer")?,
|
||||
});
|
||||
}
|
||||
|
||||
let mut imports = Vec::new();
|
||||
let directories = u32_at(optional, count_at, "directory count")?;
|
||||
let import_rva = if directories >= 2 {
|
||||
u32_at(optional, dirs_at + 8, "import directory")?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if import_rva != 0 {
|
||||
let start = file_offset(§ions, import_rva)
|
||||
.ok_or(Error::Truncated("import directory outside sections"))?;
|
||||
let mut terminated = false;
|
||||
for i in 0..=MAX_IMPORTS {
|
||||
let entry = bytes(d, start + i * 20, 20, "import descriptor")?;
|
||||
if entry.iter().all(|b| *b == 0) {
|
||||
terminated = true;
|
||||
break;
|
||||
}
|
||||
let name_rva = u32_at(entry, 12, "import name")?;
|
||||
let at = file_offset(§ions, name_rva)
|
||||
.ok_or(Error::Truncated("import name outside sections"))?;
|
||||
let rest = d.get(at..).ok_or(Error::Truncated("import name"))?;
|
||||
let len = rest
|
||||
.iter()
|
||||
.take(MAX_NAME)
|
||||
.position(|b| *b == 0)
|
||||
.ok_or(Error::Truncated("unterminated import name"))?;
|
||||
imports.push(String::from_utf8_lossy(&rest[..len]).to_ascii_lowercase());
|
||||
}
|
||||
if !terminated {
|
||||
return Err(Error::Truncated("import directory has no terminator"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Image {
|
||||
machine,
|
||||
pe32_plus,
|
||||
subsystem,
|
||||
is_dll: characteristics & 0x2000 != 0,
|
||||
imports,
|
||||
})
|
||||
}
|
||||
|
||||
impl Image {
|
||||
/// Refuse what is known not to launch. ARM64 programs were observed to be rejected by
|
||||
/// CrossOver 26.3 on macOS ("cannot execute").
|
||||
pub fn check_launchable(&self) -> Result<(), Error> {
|
||||
if self.is_dll {
|
||||
return Err(Error::Unsupported(
|
||||
"the file is a DLL, not a program".into(),
|
||||
));
|
||||
}
|
||||
if !matches!(self.machine, Machine::X86_64 | Machine::I386) {
|
||||
return Err(Error::Unsupported(format!(
|
||||
"machine {} (CrossOver on macOS runs x86 and x86_64 Windows programs)",
|
||||
self.machine.name()
|
||||
)));
|
||||
}
|
||||
// 2 = Windows GUI, 3 = Windows console.
|
||||
if !matches!(self.subsystem, 2 | 3) {
|
||||
return Err(Error::Unsupported(format!("subsystem {}", self.subsystem)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn to_json(&self) -> Json {
|
||||
Json::obj(vec![
|
||||
("machine", Json::str(self.machine.name())),
|
||||
("pe32_plus", Json::Bool(self.pe32_plus)),
|
||||
("subsystem", Json::Num(self.subsystem as f64)),
|
||||
(
|
||||
"imports",
|
||||
Json::Arr(self.imports.iter().map(|s| Json::str(s.clone())).collect()),
|
||||
),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
/// Read and identify a program file, refusing anything that is not a regular file of a
|
||||
/// plausible size.
|
||||
pub fn inspect(path: &std::path::Path) -> Result<Image, String> {
|
||||
let meta = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
if !meta.is_file() {
|
||||
return Err(format!("{}: not a regular file", path.display()));
|
||||
}
|
||||
if meta.len() > MAX_BYTES {
|
||||
return Err(format!("{}: larger than {MAX_BYTES} bytes", path.display()));
|
||||
}
|
||||
let data = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
parse(&data).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
fn put16(d: &mut [u8], at: usize, v: u16) {
|
||||
d[at..at + 2].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
fn put32(d: &mut [u8], at: usize, v: u32) {
|
||||
d[at..at + 4].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
|
||||
/// A minimal image written field by field from the PE Format specification: one section
|
||||
/// at RVA 0x1000 holding one import descriptor and its name.
|
||||
pub(crate) fn synthetic(machine: u16, characteristics: u16) -> Vec<u8> {
|
||||
let mut d = vec![0u8; 0x400];
|
||||
d[0..2].copy_from_slice(b"MZ");
|
||||
put32(&mut d, 0x3c, 0x40);
|
||||
d[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
put16(&mut d, 0x44, machine);
|
||||
put16(&mut d, 0x46, 1); // one section
|
||||
put16(&mut d, 0x54, 240); // PE32+ optional header with 16 directories
|
||||
put16(&mut d, 0x56, characteristics);
|
||||
let opt = 0x58;
|
||||
put16(&mut d, opt, 0x20b);
|
||||
put16(&mut d, opt + 68, 3);
|
||||
put32(&mut d, opt + 108, 16);
|
||||
put32(&mut d, opt + 120, 0x1000); // directory 1: imports
|
||||
let section = opt + 240;
|
||||
put32(&mut d, section + 12, 0x1000);
|
||||
put32(&mut d, section + 16, 0x100);
|
||||
put32(&mut d, section + 20, 0x200);
|
||||
put32(&mut d, 0x200 + 12, 0x1080); // name of descriptor 0
|
||||
d[0x280..0x28a].copy_from_slice(b"D3D11.dll\0");
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_machine_subsystem_and_imports() {
|
||||
let i = parse(&synthetic(0x8664, 0x0022)).unwrap();
|
||||
assert_eq!(i.machine, Machine::X86_64);
|
||||
assert!(i.pe32_plus);
|
||||
assert_eq!(i.subsystem, 3);
|
||||
assert_eq!(i.imports, ["d3d11.dll"]);
|
||||
assert_eq!(i.check_launchable(), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_arm64_dlls_and_unknown_machines() {
|
||||
let arm = parse(&synthetic(0xaa64, 0x0022)).unwrap();
|
||||
assert!(matches!(arm.check_launchable(), Err(Error::Unsupported(_))));
|
||||
let dll = parse(&synthetic(0x8664, 0x2022)).unwrap();
|
||||
assert!(matches!(dll.check_launchable(), Err(Error::Unsupported(_))));
|
||||
let other = parse(&synthetic(0x1f0, 0x0022)).unwrap();
|
||||
assert!(other.check_launchable().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_pe_input_is_an_error() {
|
||||
assert!(matches!(parse(b""), Err(Error::NotPe(_))));
|
||||
assert!(matches!(parse(b"#!/bin/sh\n"), Err(Error::NotPe(_))));
|
||||
let mut d = synthetic(0x8664, 0x0022);
|
||||
d[0x40] = b'X';
|
||||
assert!(matches!(parse(&d), Err(Error::NotPe(_))));
|
||||
assert!(parse(&synthetic(0x8664, 0)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_offsets_and_truncation_never_panic() {
|
||||
let good = synthetic(0x8664, 0x0022);
|
||||
for n in 0..good.len() {
|
||||
let _ = parse(&good[..n]);
|
||||
}
|
||||
// Every aligned word replaced by extreme values: must return, never panic.
|
||||
for at in (0..good.len() - 4).step_by(2) {
|
||||
for v in [u32::MAX, 0x7fff_ffff, 0x1000] {
|
||||
let mut d = good.clone();
|
||||
put32(&mut d, at, v);
|
||||
let _ = parse(&d);
|
||||
}
|
||||
}
|
||||
let mut far = good.clone();
|
||||
put32(&mut far, 0x58 + 120, 0xdead_0000);
|
||||
assert!(matches!(parse(&far), Err(Error::Truncated(_))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
//! Read-only environment checks before a run (`bx-cli doctor`).
|
||||
//!
|
||||
//! Each check is something observed on this host. A pass means the pieces the runner needs
|
||||
//! are present; it does not mean any program will run.
|
||||
|
||||
use crate::json::Json;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Check {
|
||||
pub name: &'static str,
|
||||
pub ok: bool,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Facts {
|
||||
pub host_arch: &'static str,
|
||||
/// None when no CrossOver bundle was found.
|
||||
pub crossover: Option<(String, std::path::PathBuf)>,
|
||||
pub rosetta_runs_x86_64: bool,
|
||||
pub bottle: Option<(String, std::path::PathBuf)>,
|
||||
pub free_percent: Option<u8>,
|
||||
pub min_start_free: u8,
|
||||
}
|
||||
|
||||
pub fn evaluate(f: &Facts) -> Vec<Check> {
|
||||
let mut out = vec![Check {
|
||||
name: "host_arm64",
|
||||
ok: f.host_arch == "aarch64",
|
||||
detail: f.host_arch.to_string(),
|
||||
}];
|
||||
match &f.crossover {
|
||||
None => out.push(Check {
|
||||
name: "crossover_installed",
|
||||
ok: false,
|
||||
detail: "no CrossOver bundle found; install it from CodeWeavers".into(),
|
||||
}),
|
||||
Some((version, wine)) => {
|
||||
out.push(Check {
|
||||
name: "crossover_installed",
|
||||
ok: true,
|
||||
detail: version.clone(),
|
||||
});
|
||||
for (name, path) in [
|
||||
("wine_launcher", wine.clone()),
|
||||
("wineserver", wine.with_file_name("wineserver")),
|
||||
] {
|
||||
out.push(Check {
|
||||
name,
|
||||
ok: path.is_file(),
|
||||
detail: path.display().to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(Check {
|
||||
name: "rosetta",
|
||||
ok: f.rosetta_runs_x86_64,
|
||||
detail: "whether an x86_64 binary executes (CrossOver 26.3's Wine is x86_64-only)".into(),
|
||||
});
|
||||
if let Some((name, dir)) = &f.bottle {
|
||||
out.push(Check {
|
||||
name: "bottle",
|
||||
ok: valid_bottle_name(name) && dir.join("drive_c").is_dir(),
|
||||
detail: dir.display().to_string(),
|
||||
});
|
||||
if dir.join("drive_c").is_dir() {
|
||||
let marker = dir.join(".betterxen-session");
|
||||
let clean = match std::fs::symlink_metadata(&marker) {
|
||||
Ok(meta) => meta.is_file() && !meta.file_type().is_symlink() && meta.len() == 0,
|
||||
Err(e) => e.kind() == std::io::ErrorKind::NotFound,
|
||||
};
|
||||
out.push(Check {
|
||||
name: "bottle_session",
|
||||
ok: clean,
|
||||
detail: if clean { "no unfinished BetterXen session".into() } else {
|
||||
"active, unfinished or invalid session marker; SIGTERM an active runner, or use `bx-cli stop` for abandoned sessions".into()
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
out.push(match f.free_percent {
|
||||
Some(p) => Check {
|
||||
name: "free_memory",
|
||||
ok: p >= f.min_start_free,
|
||||
detail: format!("{p}% free, {}% required", f.min_start_free),
|
||||
},
|
||||
None => Check {
|
||||
name: "free_memory",
|
||||
ok: false,
|
||||
detail: "could not be read".into(),
|
||||
},
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// A bottle name becomes a path component and a command argument, so it must be neither a
|
||||
/// path nor something the launcher could read as an option.
|
||||
pub fn valid_bottle_name(name: &str) -> bool {
|
||||
!name.is_empty()
|
||||
&& !name.starts_with('-')
|
||||
&& !name.contains(['/', '\\'])
|
||||
&& !name.chars().any(char::is_control)
|
||||
&& name != "."
|
||||
&& name != ".."
|
||||
}
|
||||
|
||||
pub fn rosetta_runs_x86_64() -> bool {
|
||||
crate::cmdutil::run("/usr/bin/arch", &["-x86_64", "/usr/bin/true"]).is_some()
|
||||
}
|
||||
|
||||
pub fn gather(bottle: Option<&str>, wine: Option<(String, &Path)>, min_start_free: u8) -> Facts {
|
||||
Facts {
|
||||
host_arch: std::env::consts::ARCH,
|
||||
crossover: wine.map(|(v, p)| (v, p.to_path_buf())),
|
||||
rosetta_runs_x86_64: rosetta_runs_x86_64(),
|
||||
bottle: bottle.map(|b| (b.to_string(), crate::run::bottle_prefix(b))),
|
||||
free_percent: crate::memory::free_percentage(),
|
||||
min_start_free,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_json(checks: &[Check]) -> Json {
|
||||
Json::obj(vec![
|
||||
("schema", Json::str("betterxen-hybrid-doctor/0")),
|
||||
("ready", Json::Bool(checks.iter().all(|c| c.ok))),
|
||||
(
|
||||
"checks",
|
||||
Json::Arr(
|
||||
checks
|
||||
.iter()
|
||||
.map(|c| {
|
||||
Json::obj(vec![
|
||||
("name", Json::str(c.name)),
|
||||
("ok", Json::Bool(c.ok)),
|
||||
("detail", Json::str(c.detail.clone())),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn failing(checks: &[Check]) -> Vec<&str> {
|
||||
checks.iter().filter(|c| !c.ok).map(|c| c.name).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_pieces_are_named() {
|
||||
let f = Facts {
|
||||
host_arch: "aarch64",
|
||||
crossover: None,
|
||||
rosetta_runs_x86_64: false,
|
||||
bottle: Some(("nope".into(), "/nonexistent/nope".into())),
|
||||
free_percent: Some(10),
|
||||
min_start_free: 50,
|
||||
};
|
||||
assert_eq!(
|
||||
failing(&evaluate(&f)),
|
||||
["crossover_installed", "rosetta", "bottle", "free_memory"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn complete_synthetic_environment_passes() {
|
||||
let dir = std::env::temp_dir().join(format!("bx-preflight-{}", std::process::id()));
|
||||
std::fs::create_dir_all(dir.join("bottle/drive_c")).unwrap();
|
||||
std::fs::write(dir.join("wine"), "").unwrap();
|
||||
std::fs::write(dir.join("wineserver"), "").unwrap();
|
||||
let f = Facts {
|
||||
host_arch: "aarch64",
|
||||
crossover: Some(("1.0".into(), dir.join("wine"))),
|
||||
rosetta_runs_x86_64: true,
|
||||
bottle: Some(("bottle".into(), dir.join("bottle"))),
|
||||
free_percent: Some(80),
|
||||
min_start_free: 50,
|
||||
};
|
||||
assert!(failing(&evaluate(&f)).is_empty());
|
||||
std::fs::write(dir.join("bottle/.betterxen-session"), "pid=123").unwrap();
|
||||
assert_eq!(failing(&evaluate(&f)), ["bottle_session"]);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bottle_names_that_are_paths_or_options_are_invalid() {
|
||||
for bad in ["", "..", ".", "a/b", "a\\b", "a\nb", "--bottle"] {
|
||||
assert!(!valid_bottle_name(bad), "{bad}");
|
||||
}
|
||||
assert!(valid_bottle_name("betterxen-test"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Exclusive report creation: previous evidence is never replaced.
|
||||
|
||||
use crate::json::Json;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Save a run or benchmark report under a unique name, reporting all I/O errors.
|
||||
pub fn save(dir: &Path, kind: &str, report: &Json) -> io::Result<PathBuf> {
|
||||
if !matches!(kind, "run" | "bench") {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"unknown report kind",
|
||||
));
|
||||
}
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(io::Error::other)?
|
||||
.as_nanos();
|
||||
let bytes = report.render();
|
||||
loop {
|
||||
let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let path = dir.join(format!(
|
||||
"{kind}-{nanos}-{}-{sequence}.json",
|
||||
std::process::id()
|
||||
));
|
||||
match write_new(&path, bytes.as_bytes(), |file, bytes| file.write_all(bytes)) {
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e),
|
||||
Ok(()) => return Ok(path),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_new(
|
||||
path: &Path,
|
||||
bytes: &[u8],
|
||||
write: impl FnOnce(&mut File, &[u8]) -> io::Result<()>,
|
||||
) -> io::Result<()> {
|
||||
let mut file = OpenOptions::new().write(true).create_new(true).open(path)?;
|
||||
if let Err(error) = write(&mut file, bytes).and_then(|()| file.sync_all()) {
|
||||
drop(file);
|
||||
// Remove only the incomplete file this call exclusively created.
|
||||
return match std::fs::remove_file(path) {
|
||||
Ok(()) => Err(error),
|
||||
Err(cleanup) => Err(io::Error::new(
|
||||
error.kind(),
|
||||
format!(
|
||||
"{error}; cannot remove incomplete report {}: {cleanup}",
|
||||
path.display()
|
||||
),
|
||||
)),
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn directory() -> PathBuf {
|
||||
let id = SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("bx-records-{}-{id}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_run_and_bench_reports_preserve_prior_evidence() {
|
||||
let dir = directory();
|
||||
std::fs::write(dir.join("bench.json"), "previous evidence").unwrap();
|
||||
let first = save(&dir, "run", &Json::str("first")).unwrap();
|
||||
let second = save(&dir, "run", &Json::str("second")).unwrap();
|
||||
let bench1 = save(&dir, "bench", &Json::str("bench one")).unwrap();
|
||||
let bench2 = save(&dir, "bench", &Json::str("bench two")).unwrap();
|
||||
assert_ne!(first, second);
|
||||
assert_ne!(bench1, bench2);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(first).unwrap(),
|
||||
Json::str("first").render()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(second).unwrap(),
|
||||
Json::str("second").render()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(bench1).unwrap(),
|
||||
Json::str("bench one").render()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(bench2).unwrap(),
|
||||
Json::str("bench two").render()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.join("bench.json")).unwrap(),
|
||||
"previous evidence"
|
||||
);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_destination_is_never_truncated() {
|
||||
let dir = directory();
|
||||
let path = dir.join("record.json");
|
||||
std::fs::write(&path, "original").unwrap();
|
||||
let error =
|
||||
write_new(&path, b"replacement", |file, bytes| file.write_all(bytes)).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "original");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_directory_is_an_error() {
|
||||
let dir = directory();
|
||||
let path = dir.join("not-a-directory");
|
||||
std::fs::write(&path, "original").unwrap();
|
||||
assert!(save(&path, "run", &Json::Null).is_err());
|
||||
assert_eq!(std::fs::read_to_string(path).unwrap(), "original");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_write_failure_is_reported_and_incomplete_file_removed() {
|
||||
let dir = directory();
|
||||
let path = dir.join("record.json");
|
||||
let error = write_new(&path, b"a complete report", |file, _| {
|
||||
file.write_all(b"partial")?;
|
||||
Err(io::Error::other("injected write failure"))
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("injected write failure"));
|
||||
assert!(!path.exists());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,128 @@
|
||||
//! Coordinate BetterXen runners for one bottle. This does not lock out CrossOver's UI or
|
||||
//! other launchers: maintainers must dedicate the bottle to BetterXen tests.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
|
||||
use std::path::Path;
|
||||
|
||||
pub struct BottleSession {
|
||||
file: File,
|
||||
}
|
||||
|
||||
impl BottleSession {
|
||||
pub fn acquire(prefix: &Path, recovery: bool) -> Result<Self, String> {
|
||||
let path = prefix.join(".betterxen-session");
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.mode(0o600)
|
||||
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
|
||||
.open(&path)
|
||||
.map_err(|e| format!("cannot open {}: {e}", path.display()))?;
|
||||
let metadata = file.metadata().map_err(|e| e.to_string())?;
|
||||
// SAFETY: geteuid takes no pointers and has no memory preconditions.
|
||||
let uid = unsafe { libc::geteuid() };
|
||||
if !metadata.is_file() || metadata.nlink() != 1 || metadata.uid() != uid {
|
||||
return Err(format!(
|
||||
"{} must be a regular, singly linked file owned by the current user",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
// SAFETY: the descriptor remains owned by `file`; flock changes no Rust memory.
|
||||
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
|
||||
return Err(
|
||||
"bottle has an active BetterXen runner; stop that runner with SIGTERM first".into(),
|
||||
);
|
||||
}
|
||||
let mut previous = String::new();
|
||||
Read::by_ref(&mut file)
|
||||
.take(4096)
|
||||
.read_to_string(&mut previous)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !recovery && !previous.is_empty() {
|
||||
return Err(format!(
|
||||
"bottle has an unfinished session ({previous:?}); run `bx-cli stop --bottle B` (or `--prefix P`) before another run"
|
||||
));
|
||||
}
|
||||
file.set_len(0).map_err(|e| e.to_string())?;
|
||||
file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;
|
||||
writeln!(file, "pid={} recovery={recovery}", std::process::id())
|
||||
.map_err(|e| e.to_string())?;
|
||||
file.sync_all().map_err(|e| e.to_string())?;
|
||||
Ok(Self { file })
|
||||
}
|
||||
|
||||
/// Clear only after supervision or explicit bottle recovery completed successfully.
|
||||
pub fn complete(&mut self) -> Result<(), String> {
|
||||
self.file
|
||||
.set_len(0)
|
||||
.and_then(|()| self.file.sync_all())
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// The kernel releases the lock on close, including SIGKILL. Without `complete`, the
|
||||
// nonempty marker survives so a new runner cannot hide a surviving guest.
|
||||
impl Drop for BottleSession {
|
||||
fn drop(&mut self) {
|
||||
// A concurrent fork briefly inherits the open file description until exec closes
|
||||
// its CLOEXEC descriptor. Explicit unlock prevents that transient child reference
|
||||
// from keeping a completed parent session locked after this object is dropped.
|
||||
// SAFETY: the descriptor is still owned and open; flock changes no Rust memory.
|
||||
unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_UN) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn active_and_abandoned_sessions_require_distinct_recovery() {
|
||||
let dir = std::env::temp_dir().join(format!("bx-session-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let first = BottleSession::acquire(&dir, false).unwrap();
|
||||
assert!(BottleSession::acquire(&dir, false).is_err());
|
||||
assert!(BottleSession::acquire(&dir, true).is_err());
|
||||
drop(first); // models a supervisor disappearing without completing cleanup
|
||||
assert!(BottleSession::acquire(&dir, false).is_err());
|
||||
BottleSession::acquire(&dir, true)
|
||||
.unwrap()
|
||||
.complete()
|
||||
.unwrap();
|
||||
BottleSession::acquire(&dir, false)
|
||||
.unwrap()
|
||||
.complete()
|
||||
.unwrap();
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_marker_symlink_does_not_truncate_its_target() {
|
||||
let dir = std::env::temp_dir().join(format!("bx-session-link-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let target = dir.join("valuable");
|
||||
std::fs::write(&target, "preserve me").unwrap();
|
||||
std::os::unix::fs::symlink(&target, dir.join(".betterxen-session")).unwrap();
|
||||
assert!(BottleSession::acquire(&dir, true).is_err());
|
||||
assert_eq!(std::fs::read_to_string(target).unwrap(), "preserve me");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hardlinked_marker_is_never_truncated_during_recovery() {
|
||||
let dir = std::env::temp_dir().join(format!("bx-session-hardlink-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let target = dir.join("valuable");
|
||||
std::fs::write(&target, "preserve me").unwrap();
|
||||
std::fs::hard_link(&target, dir.join(".betterxen-session")).unwrap();
|
||||
assert!(BottleSession::acquire(&dir, true).is_err());
|
||||
assert_eq!(std::fs::read_to_string(target).unwrap(), "preserve me");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
//! Probe Windows cross-compilers for original test programs (issue #364).
|
||||
//!
|
||||
//! Reports what is installed and what each compiler targets; it does not install anything.
|
||||
|
||||
use crate::cmdutil::run;
|
||||
use crate::json::Json;
|
||||
|
||||
/// (name, kind). Order is the discovery order only, not a preference.
|
||||
pub const CANDIDATES: &[&str] = &[
|
||||
"aarch64-w64-mingw32-clang",
|
||||
"x86_64-w64-mingw32-clang",
|
||||
"x86_64-w64-mingw32-gcc",
|
||||
"i686-w64-mingw32-gcc",
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Compiler {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub version_line: Option<String>,
|
||||
pub target_machine: Option<String>,
|
||||
}
|
||||
|
||||
pub fn probe(search_path: &str) -> Vec<Compiler> {
|
||||
CANDIDATES
|
||||
.iter()
|
||||
.filter_map(|name| {
|
||||
let path = search_path
|
||||
.split(':')
|
||||
.map(|d| std::path::Path::new(d).join(name))
|
||||
.find(|p| p.is_file())?;
|
||||
let p = path.to_str()?.to_string();
|
||||
Some(Compiler {
|
||||
name: name.to_string(),
|
||||
version_line: run(&p, &["--version"])
|
||||
.and_then(|s| s.lines().next().map(String::from)),
|
||||
target_machine: run(&p, &["-dumpmachine"]),
|
||||
path: p,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Compiler {
|
||||
pub fn to_json(&self) -> Json {
|
||||
Json::obj(vec![
|
||||
("name", Json::str(self.name.clone())),
|
||||
("path", Json::str(self.path.clone())),
|
||||
("version", Json::opt_str(self.version_line.clone())),
|
||||
("target_machine", Json::opt_str(self.target_machine.clone())),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn empty_path_finds_nothing() {
|
||||
assert!(probe("").is_empty());
|
||||
assert!(probe("/nonexistent-dir").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_a_stub_compiler_and_reports_its_output() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = std::env::temp_dir().join(format!("bxhybrid-tc-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let f = dir.join("x86_64-w64-mingw32-gcc");
|
||||
std::fs::write(&f, "#!/bin/sh\nif [ \"$1\" = -dumpmachine ]; then echo x86_64-w64-mingw32; else echo stub 1.0; fi\n").unwrap();
|
||||
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let found = probe(dir.to_str().unwrap());
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(
|
||||
found[0].target_machine.as_deref(),
|
||||
Some("x86_64-w64-mingw32")
|
||||
);
|
||||
assert_eq!(found[0].version_line.as_deref(), Some("stub 1.0"));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -13,130 +13,10 @@ pub struct TraceSummary {
|
||||
pub clwb_events: usize,
|
||||
/// Highest cumulative counter in the sampled CLWB records, if available.
|
||||
pub clwb_trap_lower_bound: Option<u64>,
|
||||
/// Sampled `<kind>_trapped` records for the other AMD-only instructions the
|
||||
/// VEH emulates (`clzero`, `monitorx`, `mwaitx`, `rdpru`, `extrq`, `insertq`).
|
||||
pub amd_traps: BTreeMap<String, TrapCount>,
|
||||
pub adx_errors: usize,
|
||||
pub unhandled_exceptions: Vec<UnhandledException>,
|
||||
pub unimpl_apis: BTreeMap<String, usize>,
|
||||
pub unimpl_vtables: BTreeMap<String, usize>,
|
||||
/// Aggregated `shader_gate` records from `d3d12_xs.dll` (#496).
|
||||
pub shader_gate: ShaderGateSummary,
|
||||
/// `shader_d3dmetal_gap` records: pipelines D3DMetal creates but does not run (#453).
|
||||
pub shader_gaps: Vec<ShaderGap>,
|
||||
/// `shader_bridge_missing` messages, in log order.
|
||||
pub shader_bridge_missing: Vec<String>,
|
||||
}
|
||||
|
||||
/// Aggregated `shader_gate` records. Decisions, kinds and stages are keyed by
|
||||
/// their emitted string so unknown values are counted rather than dropped.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGateSummary {
|
||||
pub total: usize,
|
||||
/// Gate records whose `detail` could not be parsed as `key=value` pairs.
|
||||
pub unparsed: usize,
|
||||
/// Parsed gate records that carry no `decision` field, so they appear in no
|
||||
/// `decisions` bucket. Counted here so the decision counts can be
|
||||
/// reconciled against `total` (#497 review). `kind` is legitimately absent
|
||||
/// on unclassified records and is not counted here.
|
||||
pub missing_decision: usize,
|
||||
pub decisions: BTreeMap<String, usize>,
|
||||
pub kinds: BTreeMap<String, usize>,
|
||||
pub stages: BTreeMap<String, usize>,
|
||||
/// Individual gate records, in log order.
|
||||
pub records: Vec<ShaderGateRecord>,
|
||||
}
|
||||
|
||||
/// One `shader_gate` record. Fields absent from the emitted `detail` (for
|
||||
/// example on unclassified records) are `None`; `atomic64` may be `Some("")`.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGateRecord {
|
||||
pub pso: Option<String>,
|
||||
pub stage: Option<String>,
|
||||
pub decision: Option<String>,
|
||||
pub hr: Option<String>,
|
||||
pub kind: Option<String>,
|
||||
pub shader_stage: Option<String>,
|
||||
pub sm: Option<String>,
|
||||
pub bytes: Option<String>,
|
||||
pub dxil: Option<String>,
|
||||
pub accc: Option<String>,
|
||||
pub sfi0: Option<String>,
|
||||
pub wave_ops: Option<String>,
|
||||
pub int64_ops: Option<String>,
|
||||
pub atomic64: Option<String>,
|
||||
pub wave_lanes: Option<String>,
|
||||
}
|
||||
|
||||
/// One `shader_d3dmetal_gap` record.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGap {
|
||||
pub pso: Option<String>,
|
||||
pub stage: Option<String>,
|
||||
pub wave_lanes_min: Option<String>,
|
||||
pub atomic64_flags: Option<String>,
|
||||
}
|
||||
|
||||
/// Tokenize a `detail` string of space-separated `key=value` pairs.
|
||||
///
|
||||
/// Only the `shader_d3dmetal_gap` record appends free text after its pairs
|
||||
/// (`... atomic64_flags=0x400000: D3DMetal ...`), so `stop_at_free_text`
|
||||
/// selects how a token without `=` is treated:
|
||||
///
|
||||
/// - `true` (gap records): the token ends the key=value section.
|
||||
/// - `false` (`shader_gate` records): a stray token is skipped and parsing
|
||||
/// continues, so one unexpected word cannot silently drop every later
|
||||
/// field (#497 review).
|
||||
///
|
||||
/// Values never contain spaces, so `atomic64=` followed by a space yields an
|
||||
/// empty value.
|
||||
/// Splits a log detail string into `key=value` pairs.
|
||||
///
|
||||
/// `stop_at_free_text` exists for records that end with prose after their
|
||||
/// fields (`shader_d3dmetal_gap` ends in a sentence), where the first token
|
||||
/// without `=` marks the end of the structured part.
|
||||
///
|
||||
/// For `shader_gate` the whole string is structured, so a token without `=`
|
||||
/// is skipped rather than treated as the end. Stopping there would silently
|
||||
/// drop every later field while the record still counted as parsed: with
|
||||
/// `atomic64=typed, raw, wave_lanes=64-64`, a `break` loses `wave_lanes`,
|
||||
/// whereas a `continue` keeps it. The emitter writes no spaces inside a value
|
||||
/// today, so this is robustness against a future value containing one, not a
|
||||
/// fix for current output.
|
||||
fn parse_key_values(detail: &str, stop_at_free_text: bool) -> Vec<(&str, &str)> {
|
||||
let mut pairs = Vec::new();
|
||||
for token in detail.split_ascii_whitespace() {
|
||||
match token.split_once('=') {
|
||||
Some((key, value)) if !key.is_empty() => pairs.push((key, value)),
|
||||
_ if stop_at_free_text => break,
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
pairs
|
||||
}
|
||||
|
||||
/// Sampled trap records of one instruction kind.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct TrapCount {
|
||||
pub events: usize,
|
||||
/// Highest cumulative counter in the sampled records, if available.
|
||||
pub lower_bound: Option<u64>,
|
||||
}
|
||||
|
||||
const AMD_TRAP_EVENTS: [(&str, &str); 6] = [
|
||||
("clzero_trapped", "clzero"),
|
||||
("monitorx_trapped", "monitorx"),
|
||||
("mwaitx_trapped", "mwaitx"),
|
||||
("rdpru_trapped", "rdpru"),
|
||||
("extrq_trapped", "extrq"),
|
||||
("insertq_trapped", "insertq"),
|
||||
];
|
||||
|
||||
fn sampled_counter(detail: &str) -> Option<u64> {
|
||||
detail
|
||||
.split_ascii_whitespace()
|
||||
.find_map(|field| field.strip_prefix("total_traps="))
|
||||
.and_then(|count| count.parse::<u64>().ok())
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -155,65 +35,6 @@ fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
Some(&rest[..end])
|
||||
}
|
||||
|
||||
fn get_field<'a>(pairs: &[(&'a str, &'a str)], key: &str) -> Option<String> {
|
||||
pairs
|
||||
.iter()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| (*v).to_owned())
|
||||
}
|
||||
|
||||
fn record_shader_gate(summary: &mut TraceSummary, detail: &str) {
|
||||
let gate = &mut summary.shader_gate;
|
||||
gate.total += 1;
|
||||
let pairs = parse_key_values(detail, false);
|
||||
if pairs.is_empty() {
|
||||
gate.unparsed += 1;
|
||||
return;
|
||||
}
|
||||
let record = ShaderGateRecord {
|
||||
pso: get_field(&pairs, "pso"),
|
||||
stage: get_field(&pairs, "stage"),
|
||||
decision: get_field(&pairs, "decision"),
|
||||
hr: get_field(&pairs, "hr"),
|
||||
kind: get_field(&pairs, "kind"),
|
||||
shader_stage: get_field(&pairs, "shader_stage"),
|
||||
sm: get_field(&pairs, "sm"),
|
||||
bytes: get_field(&pairs, "bytes"),
|
||||
dxil: get_field(&pairs, "dxil"),
|
||||
accc: get_field(&pairs, "accc"),
|
||||
sfi0: get_field(&pairs, "sfi0"),
|
||||
wave_ops: get_field(&pairs, "wave_ops"),
|
||||
int64_ops: get_field(&pairs, "int64_ops"),
|
||||
atomic64: get_field(&pairs, "atomic64"),
|
||||
wave_lanes: get_field(&pairs, "wave_lanes"),
|
||||
};
|
||||
match &record.decision {
|
||||
Some(decision) => *gate.decisions.entry(decision.clone()).or_insert(0) += 1,
|
||||
None => gate.missing_decision += 1,
|
||||
}
|
||||
if let Some(kind) = &record.kind {
|
||||
*gate.kinds.entry(kind.clone()).or_insert(0) += 1;
|
||||
}
|
||||
if let Some(stage) = &record.stage {
|
||||
*gate.stages.entry(stage.clone()).or_insert(0) += 1;
|
||||
}
|
||||
gate.records.push(record);
|
||||
}
|
||||
|
||||
fn record_shader_gap(summary: &mut TraceSummary, detail: &str) {
|
||||
let pairs = parse_key_values(detail, true);
|
||||
// The emitter appends `: D3DMetal creates such pipelines ...` directly
|
||||
// after the flags value, so strip the trailing colon.
|
||||
let atomic64_flags = get_field(&pairs, "atomic64_flags")
|
||||
.map(|v| v.strip_suffix(':').map(str::to_owned).unwrap_or(v));
|
||||
summary.shader_gaps.push(ShaderGap {
|
||||
pso: get_field(&pairs, "pso"),
|
||||
stage: get_field(&pairs, "stage"),
|
||||
wave_lanes_min: get_field(&pairs, "wave_lanes_min"),
|
||||
atomic64_flags,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
let mut summary = TraceSummary::default();
|
||||
for line in input.lines() {
|
||||
@@ -227,19 +48,11 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
match event {
|
||||
"clwb_trapped" => {
|
||||
summary.clwb_events += 1;
|
||||
summary.clwb_trap_lower_bound =
|
||||
summary.clwb_trap_lower_bound.max(sampled_counter(detail));
|
||||
}
|
||||
_ if AMD_TRAP_EVENTS.iter().any(|(e, _)| *e == event) => {
|
||||
let name = AMD_TRAP_EVENTS.iter().find(|(e, _)| *e == event).unwrap().1;
|
||||
let entry = summary.amd_traps.entry(name.to_string()).or_default();
|
||||
entry.events += 1;
|
||||
entry.lower_bound = entry.lower_bound.max(sampled_counter(detail));
|
||||
}
|
||||
"shader_gate" => record_shader_gate(&mut summary, detail),
|
||||
"shader_d3dmetal_gap" => record_shader_gap(&mut summary, detail),
|
||||
"shader_bridge_missing" => {
|
||||
summary.shader_bridge_missing.push(detail.to_owned());
|
||||
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" => {
|
||||
@@ -352,221 +165,4 @@ mod tests {
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_amd_only_traps_per_kind() {
|
||||
let summary = summarize_jsonl(
|
||||
r#"{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=1"}
|
||||
{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=2"}
|
||||
{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=4"}
|
||||
{"event":"extrq_trapped","detail":"rip=0x2000 len=5 total_traps=1"}
|
||||
{"event":"rdpru_trapped","detail":"rip=0x3000 len=3"}"#,
|
||||
);
|
||||
assert_eq!(
|
||||
summary.amd_traps["clzero"],
|
||||
TrapCount {
|
||||
events: 3,
|
||||
lower_bound: Some(4)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
summary.amd_traps["extrq"],
|
||||
TrapCount {
|
||||
events: 1,
|
||||
lower_bound: Some(1)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
summary.amd_traps["rdpru"],
|
||||
TrapCount {
|
||||
events: 1,
|
||||
lower_bound: None
|
||||
}
|
||||
);
|
||||
assert!(!summary.amd_traps.contains_key("mwaitx"));
|
||||
assert_eq!(summary.clwb_events, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_full_pass_dxil_gate_record() {
|
||||
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.total, 1);
|
||||
assert_eq!(summary.shader_gate.unparsed, 0);
|
||||
assert_eq!(summary.shader_gate.decisions["pass_dxil"], 1);
|
||||
assert_eq!(summary.shader_gate.kinds["dxil"], 1);
|
||||
assert_eq!(summary.shader_gate.stages["CS"], 1);
|
||||
assert_eq!(summary.shader_gate.records.len(), 1);
|
||||
let r = &summary.shader_gate.records[0];
|
||||
assert_eq!(r.pso.as_deref(), Some("compute"));
|
||||
assert_eq!(r.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(r.decision.as_deref(), Some("pass_dxil"));
|
||||
assert_eq!(r.hr.as_deref(), Some("0x00000000"));
|
||||
assert_eq!(r.kind.as_deref(), Some("dxil"));
|
||||
assert_eq!(r.shader_stage.as_deref(), Some("5"));
|
||||
assert_eq!(r.sm.as_deref(), Some("6.6"));
|
||||
assert_eq!(r.bytes.as_deref(), Some("1234"));
|
||||
assert_eq!(r.dxil.as_deref(), Some("800"));
|
||||
assert_eq!(r.accc.as_deref(), Some("0"));
|
||||
assert_eq!(r.sfi0.as_deref(), Some("0x4000"));
|
||||
assert_eq!(r.wave_ops.as_deref(), Some("1"));
|
||||
assert_eq!(r.int64_ops.as_deref(), Some("0"));
|
||||
assert_eq!(r.atomic64.as_deref(), Some("typed,"));
|
||||
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_reject_accc_only_gate_record() {
|
||||
let log = r#"{"ts_ms":12,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_gate","detail":"pso=graphics stage=VS decision=reject_accc_only hr=0x80004001 kind=accc_only shader_stage=0 sm=6.0 bytes=2048 dxil=0 accc=512 sfi0=0x0 wave_ops=0 int64_ops=0 atomic64= wave_lanes=none"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.total, 1);
|
||||
assert_eq!(summary.shader_gate.decisions["reject_accc_only"], 1);
|
||||
assert_eq!(summary.shader_gate.kinds["accc_only"], 1);
|
||||
assert_eq!(summary.shader_gate.stages["VS"], 1);
|
||||
let r = &summary.shader_gate.records[0];
|
||||
assert_eq!(r.hr.as_deref(), Some("0x80004001"));
|
||||
assert_eq!(r.sm.as_deref(), Some("6.0"));
|
||||
assert_eq!(r.accc.as_deref(), Some("512"));
|
||||
assert_eq!(r.atomic64.as_deref(), Some(""));
|
||||
assert_eq!(r.wave_lanes.as_deref(), Some("none"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_unclassified_gate_record_without_kind() {
|
||||
let log = r#"{"ts_ms":14,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_unclassified hr=0x00000000 bytes=4096"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.total, 1);
|
||||
assert_eq!(summary.shader_gate.decisions["pass_unclassified"], 1);
|
||||
assert_eq!(summary.shader_gate.stages["CS"], 1);
|
||||
assert!(summary.shader_gate.kinds.is_empty());
|
||||
let r = &summary.shader_gate.records[0];
|
||||
assert_eq!(r.bytes.as_deref(), Some("4096"));
|
||||
assert_eq!(r.kind, None);
|
||||
assert_eq!(r.sm, None);
|
||||
assert_eq!(r.dxil, None);
|
||||
assert_eq!(r.atomic64, None);
|
||||
assert_eq!(r.wave_lanes, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_d3dmetal_gap_with_free_text_suffix() {
|
||||
let log = r#"{"ts_ms":16,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gaps.len(), 1);
|
||||
let gap = &summary.shader_gaps[0];
|
||||
assert_eq!(gap.pso.as_deref(), Some("compute"));
|
||||
assert_eq!(gap.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(gap.wave_lanes_min.as_deref(), Some("64"));
|
||||
assert_eq!(gap.atomic64_flags.as_deref(), Some("0x400000"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_shader_bridge_missing_messages() {
|
||||
let log = r#"{"ts_ms":18,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_bridge_missing","detail":"bx_shader_bridge.dll not found beside d3d12_xs.dll; shaders pass unclassified, ACCC-only refused"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_bridge_missing.len(), 1);
|
||||
assert!(summary.shader_bridge_missing[0].contains("not found beside d3d12_xs.dll"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_shader_gate_detail_is_counted_not_dropped() {
|
||||
for detail in ["", "garbage", "=value", " "] {
|
||||
let log = format!(
|
||||
"{{\"ts_ms\":20,\"tid\":1,\"level\":\"INFO\",\"sub\":\"d3d12_xs\",\"event\":\"shader_gate\",\"detail\":\"{detail}\"}}"
|
||||
);
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.shader_gate.total, 1, "detail={detail:?}");
|
||||
assert_eq!(summary.shader_gate.unparsed, 1, "detail={detail:?}");
|
||||
assert!(summary.shader_gate.records.is_empty(), "detail={detail:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_atomic64_value_is_preserved() {
|
||||
let log = r#"{"ts_ms":22,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=100 dxil=64 accc=0 sfi0=0x0 wave_ops=0 int64_ops=0 atomic64= wave_lanes=0-4294967295"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
let r = &summary.shader_gate.records[0];
|
||||
assert_eq!(r.atomic64.as_deref(), Some(""));
|
||||
assert_eq!(r.wave_lanes.as_deref(), Some("0-4294967295"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stray_token_does_not_drop_later_gate_fields() {
|
||||
// #497 review point 1: one value containing a space must not turn every
|
||||
// later field into None.
|
||||
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil atomic64=typed, raw wave_lanes=64-64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
let r = &summary.shader_gate.records[0];
|
||||
assert_eq!(r.decision.as_deref(), Some("pass_dxil"));
|
||||
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
|
||||
assert_eq!(summary.shader_gate.unparsed, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_atomic64_flags_are_parsed() {
|
||||
// #497 review point 1: the emitter concatenates flags with no separator,
|
||||
// but two flags must round-trip if they ever are spaced.
|
||||
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil kind=dxil atomic64=typed, groupshared, wave_lanes=64-64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
let r = &summary.shader_gate.records[0];
|
||||
assert_eq!(r.atomic64.as_deref(), Some("typed,"));
|
||||
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gate_record_without_a_decision_is_counted_as_missing() {
|
||||
// #497 review point 2: decision counts must reconcile against total.
|
||||
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.total, 1);
|
||||
assert_eq!(summary.shader_gate.missing_decision, 1);
|
||||
assert_eq!(summary.shader_gate.unparsed, 0);
|
||||
assert!(summary.shader_gate.decisions.is_empty());
|
||||
assert_eq!(summary.shader_gate.stages["CS"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decision_buckets_plus_missing_reconcile_with_total() {
|
||||
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil bytes=1"}
|
||||
{"event":"shader_gate","detail":"pso=compute stage=CS"}
|
||||
{"event":"shader_gate","detail":"garbage"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
let gate = &summary.shader_gate;
|
||||
let bucketed: usize = gate.decisions.values().sum();
|
||||
assert_eq!(gate.total, 3);
|
||||
assert_eq!(gate.unparsed, 1);
|
||||
assert_eq!(gate.missing_decision, 1);
|
||||
assert_eq!(bucketed + gate.unparsed + gate.missing_decision, gate.total);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_decisions_and_kinds_are_counted() {
|
||||
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=some_future_decision hr=0x00000000 kind=some_future_kind bytes=1"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.decisions["some_future_decision"], 1);
|
||||
assert_eq!(summary.shader_gate.kinds["some_future_kind"], 1);
|
||||
}
|
||||
|
||||
/// A stray token must not end the structured part of a `shader_gate`
|
||||
/// record: if it did, every later field would silently become `None`
|
||||
/// while the record still counted as parsed.
|
||||
#[test]
|
||||
fn a_record_without_a_decision_is_counted_as_missing() {
|
||||
let mut summary = TraceSummary::default();
|
||||
record_shader_gate(&mut summary, "pso=graphics stage=pixel");
|
||||
let gate = &summary.shader_gate;
|
||||
assert_eq!(gate.total, 1);
|
||||
assert_eq!(gate.unparsed, 0);
|
||||
assert_eq!(gate.missing_decision, 1);
|
||||
assert!(gate.decisions.is_empty());
|
||||
}
|
||||
|
||||
/// The free-text path is the opposite: `shader_d3dmetal_gap` ends in a
|
||||
/// sentence, so the first token without `=` ends the structured part.
|
||||
#[test]
|
||||
fn free_text_ends_the_structured_part_of_a_gap_record() {
|
||||
let pairs = parse_key_values("pso=graphics stage=pixel and then some prose", true);
|
||||
assert_eq!(pairs.len(), 2);
|
||||
assert_eq!(pairs[1], ("stage", "pixel"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
[toolchain]
|
||||
channel = "1.100.0"
|
||||
profile = "minimal"
|
||||
components = ["rustfmt", "clippy"]
|
||||
targets = ["aarch64-apple-darwin"]
|
||||
@@ -18,37 +18,6 @@ cmake -S "$ROOT_DIR/shims" -B "$BUILD_DIR" \
|
||||
|
||||
cmake --build "$BUILD_DIR" --parallel "$JOBS"
|
||||
|
||||
# bx_shader_bridge.dll (#445, #484): shader-transpiler/crates/dxbc-accc built for x86-64
|
||||
# Windows guests, linked with abi/defs/bx_shader_bridge.def so its export list and internal
|
||||
# name are the frozen ones. The verifier below then checks it like every other shim.
|
||||
# Cargo and rustc are resolved through rustup when present (a cargo earlier on PATH may have
|
||||
# no Windows std), and the build always goes to <repo>/target so no stale DLL is staged.
|
||||
BRIDGE_TARGET=x86_64-pc-windows-gnu
|
||||
if command -v rustup >/dev/null 2>&1; then
|
||||
BRIDGE_CARGO="$(cd "$ROOT_DIR" && rustup which cargo)"
|
||||
BRIDGE_RUSTC="$(cd "$ROOT_DIR" && rustup which rustc)"
|
||||
else
|
||||
BRIDGE_CARGO="$(command -v cargo || true)"
|
||||
BRIDGE_RUSTC="$(command -v rustc || true)"
|
||||
fi
|
||||
if [ -z "$BRIDGE_CARGO" ] || [ -z "$BRIDGE_RUSTC" ]; then
|
||||
echo "error: cargo/rustc not found; bx_shader_bridge.dll needs the Rust toolchain" >&2
|
||||
exit 1
|
||||
fi
|
||||
BRIDGE_LIBDIR="$("$BRIDGE_RUSTC" --print target-libdir --target "$BRIDGE_TARGET" 2>/dev/null || true)"
|
||||
if [ -z "$BRIDGE_LIBDIR" ] || ! ls "$BRIDGE_LIBDIR"/libstd-*.rlib >/dev/null 2>&1; then
|
||||
echo "error: $("$BRIDGE_RUSTC" --version) has no std for $BRIDGE_TARGET, needed for bx_shader_bridge.dll" >&2
|
||||
echo "error: install it with: rustup target add $BRIDGE_TARGET" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "=== Building bx_shader_bridge.dll with $("$BRIDGE_RUSTC" --version) ==="
|
||||
RUSTC="$BRIDGE_RUSTC" CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc \
|
||||
"$BRIDGE_CARGO" rustc --locked --release -j "$JOBS" --manifest-path "$ROOT_DIR/Cargo.toml" \
|
||||
-p dxbc-accc --lib --crate-type cdylib --target "$BRIDGE_TARGET" --target-dir "$ROOT_DIR/target" \
|
||||
-- -C link-arg="$ROOT_DIR/abi/defs/bx_shader_bridge.def"
|
||||
mkdir -p "$BUILD_DIR/bin"
|
||||
cp "$ROOT_DIR/target/$BRIDGE_TARGET/release/dxbc_accc.dll" "$BUILD_DIR/bin/bx_shader_bridge.dll"
|
||||
|
||||
echo "=== Verifying built PE32+ DLL Export Directories against abi/defs/*.def ==="
|
||||
python3 - "$ROOT_DIR/abi/defs" "$BUILD_DIR/bin" <<'PY'
|
||||
import os
|
||||
|
||||
Executable
+260
@@ -0,0 +1,260 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Run the integrated-workload acceptance sequence through `betterxen hybrid` on this Mac.
|
||||
# Every line printed is "ok <check>" or "FAIL <check>"; the exit status is non-zero if any
|
||||
# check failed. Raw JSON records and logs are kept under the output directory.
|
||||
#
|
||||
# scripts/hybrid/accept-integrated.sh <llvm-mingw-dir> <bottle> [soak-frames] [repeats]
|
||||
#
|
||||
# Exit 0: every check ran and passed. 1: a check failed. 2: the only deviations are the known
|
||||
# D3DMetal swapchain retention and/or checks reported NOT-RUN. NOT-RUN is never a pass.
|
||||
# Shader Model 6 needs Microsoft's DXC (scripts/hybrid/install-dxc.py); point
|
||||
# BETTERXEN_DXC_DIR at its bin/x64 directory.
|
||||
# Needs CrossOver, an existing win11_64 bottle, Rust 1.100.0, the pinned llvm-mingw
|
||||
# (https://github.com/MacosPorters/betterxen/blob/54264e23a417e861834ee879f810717385b91f58/docs/research/hybrid-toolchain.md), and for the on-screen check a GUI session with the
|
||||
# Screen Recording and Accessibility permissions (the latter for the keyboard check, which
|
||||
# brings the test window to the front: do not type while it runs). Opens small windows; do not
|
||||
# run on a busy machine or alongside anything else using the same bottle.
|
||||
set -u
|
||||
TC=${1:?usage: $0 <llvm-mingw-dir> <bottle> [soak-frames] [repeats]}
|
||||
BOTTLE=${2:?name an existing bottle}
|
||||
SOAK=${3:-20000}
|
||||
REPEATS=${4:-5}
|
||||
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
export RUSTUP_TOOLCHAIN=${RUSTUP_TOOLCHAIN:-1.100.0-aarch64-apple-darwin}
|
||||
mkdir -p "$ROOT/artifacts/acceptance" || exit 1
|
||||
OUT=$(mktemp -d "$ROOT/artifacts/acceptance/$(date -u +%Y%m%dT%H%M%SZ)-XXXXXX") || exit 1
|
||||
failed=0
|
||||
known=0
|
||||
not_run=0
|
||||
ok() { echo "ok $1"; }
|
||||
bad() { echo "FAIL $1"; failed=1; }
|
||||
|
||||
if [ -z "${BETTERXEN_RUNNER:-}" ]; then
|
||||
(cd "$ROOT" && cargo build --locked --release -p bx-cli) >"$OUT/build-runner.log" 2>&1 ||
|
||||
{ bad "build runner"; exit 1; }
|
||||
fi
|
||||
if [ -n "${BETTERXEN_WORKLOAD_DIR:-}" ]; then
|
||||
mkdir -p "$OUT/bin" || exit 1
|
||||
for name in d3d11-integrated d3d12-integrated d3d12-lifetime d3d12-wave-probe; do
|
||||
cp "$BETTERXEN_WORKLOAD_DIR/$name.exe" "$OUT/bin/" || exit 1
|
||||
done
|
||||
else
|
||||
"$ROOT/tests/conformance/test_d3d11_integrated/build.sh" "$TC" "$OUT/bin" >"$OUT/build-workload.log" 2>&1 ||
|
||||
{ bad "build workload"; exit 1; }
|
||||
"$ROOT/tests/conformance/test_d3d12_integrated/build.sh" "$TC" "$OUT/bin" >"$OUT/build-workload12.log" 2>&1 ||
|
||||
{ bad "build D3D12 workload"; exit 1; }
|
||||
for probe in lifetime wave; do
|
||||
"$ROOT/tests/conformance/test_d3d12_$probe/build.sh" "$TC" "$OUT/bin" >"$OUT/build-$probe.log" 2>&1 ||
|
||||
{ bad "build D3D12 $probe probe"; exit 1; }
|
||||
done
|
||||
fi
|
||||
BX=${BETTERXEN_RUNNER:-"${CARGO_TARGET_DIR:-$ROOT/target}/release/bx-cli"}
|
||||
HYBRID=${BETTERXEN_HYBRID_RUNNER:-"$(dirname "$BX")/bx-cli"}
|
||||
EXE12="$OUT/bin/d3d12-integrated.exe"
|
||||
EXE="$OUT/bin/d3d11-integrated.exe"
|
||||
# Unique executable names separate lifecycle observations from other bottles. Names are
|
||||
# never used as kill authority by the runner.
|
||||
RUN_ID=$(basename "$OUT")
|
||||
mv "$EXE" "$OUT/bin/d3d11-$RUN_ID.exe" || exit 1
|
||||
mv "$EXE12" "$OUT/bin/d3d12-$RUN_ID.exe" || exit 1
|
||||
EXE="$OUT/bin/d3d11-$RUN_ID.exe"
|
||||
EXE12="$OUT/bin/d3d12-$RUN_ID.exe"
|
||||
if [ "$(git -C "$ROOT" rev-parse --show-toplevel 2>/dev/null)" = "$ROOT" ]; then
|
||||
git -C "$ROOT" rev-parse HEAD >"$OUT/commit.txt"
|
||||
git -C "$ROOT" status --porcelain >>"$OUT/commit.txt"
|
||||
elif [ -n "${BETTERXEN_SOURCE_COMMIT:-}" ]; then
|
||||
printf '%s\nprebuilt bundle; source archive SHA-256 verified by test.sh\n' "$BETTERXEN_SOURCE_COMMIT" >"$OUT/commit.txt"
|
||||
else
|
||||
bad "source commit unavailable; use a Git checkout or the verified bundle test.sh"
|
||||
exit 1
|
||||
fi
|
||||
"$BX" hybrid receipt >"$OUT/receipt.json" 2>&1
|
||||
|
||||
if "$BX" hybrid doctor --bottle "$BOTTLE" >"$OUT/doctor.json" 2>&1; then ok "A environment"; else
|
||||
bad "A environment (see doctor.json)"; exit 1; fi
|
||||
if "$BX" hybrid inspect "$EXE" >"$OUT/inspect.json" 2>&1; then ok "B executable identified"; else bad "B inspect"; fi
|
||||
|
||||
GATES=runtime.threads,runtime.memory,runtime.exceptions,runtime.time,runtime.files,graphics.init,shader.compile,frame.first,frame.continuous,resources.churn,input,memory.bounded,shutdown
|
||||
|
||||
# run <name> <expected-classification> [runner options...] -- [workload args...]
|
||||
run() {
|
||||
name=$1; want=$2; shift 2
|
||||
opts=""
|
||||
while [ $# -gt 0 ] && [ "$1" != -- ]; do opts="$opts $1"; shift; done
|
||||
shift
|
||||
# shellcheck disable=SC2086 # options are fixed words from this script
|
||||
"$BX" hybrid run --bottle "$BOTTLE" --expect "PASS integrated" --keep-output true --out "$OUT/raw" $opts -- "$EXE" "$@" \
|
||||
>"$OUT/$name.json" 2>"$OUT/$name.log"
|
||||
got=$(sed -n 's/^ "classification": "\(.*\)",$/\1/p' "$OUT/$name.json")
|
||||
case "$got" in
|
||||
$want) ok "$name ($got)" ;;
|
||||
*) bad "$name: expected $want, got ${got:-no record}" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
run C-F-G-H-full passed --require-gates "$GATES" --timeout 180 --stall-timeout 60 -- --frames 600
|
||||
run BC1-full passed --require-gates "$GATES,textures.bc1" --timeout 180 -- --frames 128 --bc1
|
||||
run BC1-negative failed_exit_1 --timeout 120 -- --frames 128 --bc1 --fault bc1
|
||||
|
||||
# a negative control counts only if the gate the fault targets is the one that failed
|
||||
intended() {
|
||||
case "$1" in
|
||||
input) echo input ;;
|
||||
stale) echo frame.continuous ;;
|
||||
bc1) echo textures.bc1 ;;
|
||||
*) echo "frame.first frame.continuous" ;;
|
||||
esac
|
||||
}
|
||||
detects() {
|
||||
# shellcheck disable=SC2046 # gate names are fixed words
|
||||
if python3 "$ROOT/scripts/hybrid/check-failed-gates.py" "$OUT/$1.json" $(intended "$2") >"$OUT/$1.gates.log" 2>&1;
|
||||
then ok "$1 failed its intended gate ($(cat "$OUT/$1.gates.log"))"
|
||||
else bad "$1: $(cat "$OUT/$1.gates.log")"; fi
|
||||
}
|
||||
detects BC1-negative bc1
|
||||
for scene in C-F-G-H-full BC1-full; do
|
||||
if python3 "$ROOT/scripts/hybrid/check-image-digest.py" "$OUT/$scene.json" >"$OUT/oracle-$scene.log" 2>&1;
|
||||
then ok "independent image oracle $scene"; else bad "independent image oracle $scene (see log)"; fi
|
||||
done
|
||||
for fault in color blank stale input depth; do
|
||||
run "negative-$fault" failed_exit_1 --timeout 120 -- --frames 128 --fault "$fault"
|
||||
detects "negative-$fault" "$fault"
|
||||
done
|
||||
# With Wine's crash dialog on, winedbg waits for a click and this times out;
|
||||
# scripts/hybrid/create-test-bottle.py turns it off in new test bottles.
|
||||
run negative-crash 'failed_exit_*' --timeout 240 -- --frames 128 --fault crash
|
||||
run recovery-after-crash passed --require-gates "$GATES" --timeout 120 -- --frames 128
|
||||
run negative-hang stalled --timeout 90 --stall-timeout 15 -- --frames 128 --fault hang
|
||||
if pgrep -f "$(basename "$EXE")" >/dev/null; then bad "hung workload still running after stop";
|
||||
else ok "hung workload removed"; fi
|
||||
run recovery-after-hang passed --require-gates "$GATES" --timeout 120 -- --frames 128
|
||||
|
||||
if python3 "$ROOT/tests/conformance/test_d3d11_integrated/check_window.py" "$HYBRID" "$BOTTLE" "$EXE" \
|
||||
--keep "$OUT/window.png" >"$OUT/window.log" 2>&1; then ok "F on-screen frame"; else
|
||||
bad "F on-screen frame: $(cat "$OUT/window.log")"; fi
|
||||
if python3 "$ROOT/tests/conformance/test_d3d11_integrated/check_window.py" "$HYBRID" "$BOTTLE" "$EXE" \
|
||||
--fault depth >"$OUT/window-negative.log" 2>&1; then bad "on-screen check accepted a wrong image";
|
||||
else
|
||||
if grep -q 'samples differ' "$OUT/window-negative.log"; then ok "on-screen negative control";
|
||||
else bad "on-screen negative control did not reach comparison"; fi
|
||||
fi
|
||||
|
||||
i=1
|
||||
while [ "$i" -le "$REPEATS" ]; do
|
||||
run "I-repeat-$i" passed --require-gates "$GATES" --timeout 180 -- --frames 600
|
||||
i=$((i + 1))
|
||||
done
|
||||
# Direct3D 12. Under D3DMetal (CrossOver 26.3) a destroyed D3D12 swapchain leaves a device
|
||||
# reference, so the `shutdown` gate fails. That is reported as KNOWN only when it is the sole
|
||||
# failing gate; any other failure is a failure.
|
||||
d12_summary() {
|
||||
python3 - "$1" <<'PY'
|
||||
import json, re, sys
|
||||
j = json.load(open(sys.argv[1]))
|
||||
failed = sorted(g["name"] for g in j["gates"] if not g["passed"])
|
||||
digest = "".join(re.findall(r"digest=([0-9a-f]+)", " ".join(g["detail"] for g in j["gates"])))
|
||||
backend = j["backend_detected"].split(" ")[0]
|
||||
print(j["classification"], backend, ",".join(failed) or "-", digest or "-")
|
||||
PY
|
||||
}
|
||||
digest11=$(sed -n 's/.*digest=\([0-9a-f]*\).*/\1/p' "$OUT/C-F-G-H-full.json" | head -1)
|
||||
BX_SECRET_PROBE=1 "$BX" hybrid run --bottle "$BOTTLE" --keep-output true --out "$OUT/raw" --timeout 180 --stall-timeout 60 -- "$EXE12" \
|
||||
--expect-absent-env BX_SECRET_PROBE >"$OUT/d3d12-full.json" 2>"$OUT/d3d12-full.log"
|
||||
read -r class backend failed12 digest12 <<EOT
|
||||
$(d12_summary "$OUT/d3d12-full.json")
|
||||
EOT
|
||||
case "$class:$backend:$failed12" in
|
||||
passed:*:-) ok "D3D12 all gates (backend $backend)" ;;
|
||||
failed_exit_1:d3dmetal:shutdown)
|
||||
ok "D3D12 all gates but shutdown"
|
||||
known=1
|
||||
echo "KNOWN D3D12 shutdown: D3DMetal retains a device reference per swapchain" ;;
|
||||
*) bad "D3D12: $class backend=$backend failed=$failed12" ;;
|
||||
esac
|
||||
if [ -n "$digest11" ] && [ "$digest11" = "$digest12" ]; then ok "D3D11 and D3D12 pixel digests equal ($digest12)";
|
||||
else bad "pixel digests differ: d3d11=$digest11 d3d12=$digest12"; fi
|
||||
if python3 "$ROOT/scripts/hybrid/check-image-digest.py" "$OUT/d3d12-full.json" >"$OUT/oracle-d3d12.log" 2>&1;
|
||||
then ok "independent image oracle D3D12"; else bad "independent image oracle D3D12 (see log)"; fi
|
||||
if python3 "$ROOT/tests/conformance/test_d3d11_integrated/check_window.py" "$HYBRID" "$BOTTLE" "$EXE12" \
|
||||
--keep "$OUT/window12.png" >"$OUT/window12.log" 2>&1; then ok "D3D12 on-screen frame";
|
||||
else bad "D3D12 on-screen frame: $(cat "$OUT/window12.log")"; fi
|
||||
for api in d3d11 d3d12; do
|
||||
case "$api" in d3d11) first_exe=$EXE ;; d3d12) first_exe=$EXE12 ;; esac
|
||||
if python3 "$ROOT/tests/conformance/test_d3d11_integrated/check_window.py" "$HYBRID" "$BOTTLE" "$first_exe" \
|
||||
--first-frame --keep "$OUT/first-$api.png" >"$OUT/first-$api.log" 2>&1;
|
||||
then ok "$api first frame on screen"; else bad "$api first frame on screen (see log)"; fi
|
||||
done
|
||||
for fault in color blank stale input depth upload; do
|
||||
"$BX" hybrid run --bottle "$BOTTLE" --keep-output true --out "$OUT/raw" --timeout 90 -- "$EXE12" --frames 128 --fault "$fault" \
|
||||
>"$OUT/d3d12-negative-$fault.json" 2>/dev/null
|
||||
detects "d3d12-negative-$fault" "$fault"
|
||||
done
|
||||
|
||||
# Minimal swapchain lifetime probe: no application GPU work. The detach control must pass
|
||||
# and the deliberately retained reference must be caught, or the witness proves nothing.
|
||||
LIFE="$OUT/bin/d3d12-lifetime.exe"
|
||||
lifetime() {
|
||||
name=$1
|
||||
shift
|
||||
"$BX" hybrid run --bottle "$BOTTLE" --keep-output true --out "$OUT/raw" --timeout 90 -- "$LIFE" "$@" \
|
||||
>"$OUT/$name.json" 2>"$OUT/$name.log"
|
||||
}
|
||||
if lifetime lifetime-detach-control --detach-witness; then ok "lifetime witness detaches";
|
||||
else bad "lifetime detach control (see lifetime-detach-control.log)"; fi
|
||||
lifetime lifetime-retained-negative --detach-witness --retain-app-reference
|
||||
if python3 "$ROOT/scripts/hybrid/check-failed-gates.py" "$OUT/lifetime-retained-negative.json" resources.private-data-detach >/dev/null 2>&1;
|
||||
then ok "lifetime witness catches a retained reference"; else bad "lifetime retained-reference control"; fi
|
||||
if lifetime lifetime-swapchain; then ok "D3D12 swapchain released"
|
||||
elif grep -q 'adapter=AMD Compatibility Mode' "$OUT/lifetime-swapchain.json" &&
|
||||
python3 "$ROOT/scripts/hybrid/check-failed-gates.py" "$OUT/lifetime-swapchain.json" resources.swapchain-release >/dev/null 2>&1; then
|
||||
known=1
|
||||
echo "KNOWN D3D12 swapchain retention under D3DMetal (minimal probe)"
|
||||
else bad "lifetime probe (see lifetime-swapchain.log)"; fi
|
||||
|
||||
DXC=${BETTERXEN_DXC_DIR:-$ROOT/artifacts/dependencies/dxc-v1.9.2609/bin/x64}
|
||||
if [ -f "$DXC/dxc.exe" ]; then
|
||||
if python3 "$ROOT/scripts/hybrid/accept-sm6.py" "$BX" "$BOTTLE" "$OUT/bin/d3d12-wave-probe.exe" "$DXC" "$OUT/sm6" \
|
||||
>"$OUT/sm6.log" 2>&1; then ok "Shader Model 6 GPU readback"; else bad "Shader Model 6: $(tail -1 "$OUT/sm6.log")"; fi
|
||||
else
|
||||
not_run=1
|
||||
echo "NOT-RUN Shader Model 6: no dxc.exe at $DXC"
|
||||
fi
|
||||
if python3 "$ROOT/tests/conformance/test_d3d12_integrated/send_keys.py" "$BX" "$BOTTLE" "$EXE12" >"$OUT/keys.log" 2>&1;
|
||||
then ok "H macOS keyboard events"; else bad "H keyboard: $(tail -1 "$OUT/keys.log")"; fi
|
||||
if python3 "$ROOT/tests/conformance/test_d3d12_integrated/send_keys.py" "$BX" "$BOTTLE" "$EXE12" --keys up,up \
|
||||
--expect fail >"$OUT/keys-negative.log" 2>&1; then ok "keyboard negative control";
|
||||
else bad "keyboard negative control"; fi
|
||||
if python3 "$ROOT/scripts/hybrid/accept-lifecycle.py" "$BX" "$BOTTLE" "$EXE" >"$OUT/lifecycle.log" 2>&1;
|
||||
then ok "lifecycle: signals, kill and stop, repeated launch"; else
|
||||
bad "lifecycle (see lifecycle.log)"; grep FAIL "$OUT/lifecycle.log"; fi
|
||||
|
||||
# Direct3D 12 is the primary target, so it is soaked first; Direct3D 11 stays as the control.
|
||||
"$BX" hybrid run --bottle "$BOTTLE" --keep-output true --out "$OUT/raw" --timeout 1800 --stall-timeout 60 -- "$EXE12" \
|
||||
--frames "$SOAK" --verify-every 500 >"$OUT/I-soak-d3d12.json" 2>"$OUT/I-soak-d3d12.log"
|
||||
read -r class backend failed12 digest12 <<EOT
|
||||
$(d12_summary "$OUT/I-soak-d3d12.json")
|
||||
EOT
|
||||
case "$class:$backend:$failed12" in
|
||||
passed:*:-) ok "I-soak D3D12 ($SOAK frames)" ;;
|
||||
failed_exit_1:d3dmetal:shutdown)
|
||||
known=1
|
||||
ok "I-soak D3D12 all gates but the known shutdown ($SOAK frames)" ;;
|
||||
*) bad "I-soak D3D12: $class backend=$backend failed=$failed12" ;;
|
||||
esac
|
||||
run I-soak-d3d11 passed --require-gates "$GATES" --timeout 1800 --stall-timeout 60 -- --frames "$SOAK" --verify-every 500
|
||||
|
||||
echo "records: $OUT"
|
||||
python3 - "$OUT" "$failed" "$known" "$not_run" <<'PY'
|
||||
import json, pathlib, sys
|
||||
path = pathlib.Path(sys.argv[1])
|
||||
failed, known, not_run = map(int, sys.argv[2:])
|
||||
(path / "summary.json").write_text(json.dumps({
|
||||
"schema": "betterxen-integrated-acceptance/0",
|
||||
"unexpected_failures": bool(failed), "known_d3d12_swapchain_retention": bool(known),
|
||||
"checks_not_run": bool(not_run), "all_checks_passed": not (failed or known or not_run),
|
||||
}, indent=2) + "\n")
|
||||
PY
|
||||
[ "$failed" -eq 0 ] || exit 1
|
||||
[ "$known" -eq 0 ] && [ "$not_run" -eq 0 ] || exit 2
|
||||
exit 0
|
||||
Executable
+131
@@ -0,0 +1,131 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Process lifecycle checks for the hybrid runner against an installed CrossOver.
|
||||
|
||||
Uses the Direct3D 11 workload: `--fault hang` makes a program that never exits, and a normal
|
||||
run shows recovery. Prints "ok"/"FAIL" per check and exits non-zero on any failure. Do not
|
||||
run anything else in the same bottle meanwhile: stopping a run stops the whole bottle.
|
||||
|
||||
usage: accept-lifecycle.py RUNNER BOTTLE D3D11_EXE [--launches N]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def check(ok, what):
|
||||
global failed
|
||||
failed |= not ok
|
||||
print(("ok " if ok else "FAIL ") + what, flush=True)
|
||||
|
||||
|
||||
def workload_pids(exe_name):
|
||||
out = subprocess.run(["/bin/ps", "-axo", "pid=,command="], capture_output=True, text=True).stdout
|
||||
pids = []
|
||||
for line in out.splitlines():
|
||||
pid, _, command = line.strip().partition(" ")
|
||||
command = command.strip()
|
||||
# the Windows program appears with a drive-letter command line
|
||||
if command[1:3] == ":\\" and exe_name.lower() in command.lower():
|
||||
pids.append(int(pid))
|
||||
return pids
|
||||
|
||||
|
||||
def wait_for(predicate, seconds):
|
||||
end = time.time() + seconds
|
||||
while time.time() < end:
|
||||
if predicate():
|
||||
return True
|
||||
time.sleep(0.2)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("runner")
|
||||
p.add_argument("bottle")
|
||||
p.add_argument("exe")
|
||||
p.add_argument("--launches", type=int, default=20)
|
||||
a = p.parse_args()
|
||||
name = os.path.basename(a.exe)
|
||||
base = [a.runner, "hybrid", "run", "--bottle", a.bottle, "--timeout", "120"]
|
||||
if workload_pids(name):
|
||||
print(f"FAIL precondition: {name} is already running")
|
||||
return 1
|
||||
|
||||
def start(extra, out):
|
||||
return subprocess.Popen(base + ["--", a.exe] + extra, stdout=out, stderr=subprocess.DEVNULL,
|
||||
start_new_session=True)
|
||||
|
||||
def healthy(label):
|
||||
with tempfile.TemporaryFile("w+") as out:
|
||||
run = start(["--frames", "64"], out)
|
||||
code = run.wait(timeout=150)
|
||||
check(code == 0, f"{label}: next run passes")
|
||||
check(not workload_pids(name), f"{label}: nothing left running")
|
||||
|
||||
for sig, to_group in ((signal.SIGINT, True), (signal.SIGTERM, False), (signal.SIGHUP, False)):
|
||||
label = sig.name + (" to the process group" if to_group else "")
|
||||
with tempfile.TemporaryFile("w+") as out:
|
||||
run = start(["--frames", "64", "--fault", "hang"], out)
|
||||
if not wait_for(lambda: workload_pids(name), 60):
|
||||
check(False, f"{label}: workload never started")
|
||||
run.kill()
|
||||
continue
|
||||
time.sleep(2)
|
||||
began = time.time()
|
||||
(os.killpg if to_group else os.kill)(run.pid, sig)
|
||||
try:
|
||||
code = run.wait(timeout=40)
|
||||
except subprocess.TimeoutExpired:
|
||||
run.kill()
|
||||
check(False, f"{label}: supervisor did not exit")
|
||||
continue
|
||||
out.seek(0)
|
||||
try:
|
||||
record = json.load(out)
|
||||
except json.JSONDecodeError:
|
||||
record = {}
|
||||
check(code == 1 and record.get("classification") == "interrupted",
|
||||
f"{label}: classified {record.get('classification')} in {time.time() - began:.1f}s")
|
||||
check(wait_for(lambda: not workload_pids(name), 10), f"{label}: workload stopped")
|
||||
healthy(label)
|
||||
|
||||
with tempfile.TemporaryFile("w+") as out:
|
||||
run = start(["--frames", "64", "--fault", "hang"], out)
|
||||
started = wait_for(lambda: workload_pids(name), 60)
|
||||
time.sleep(2)
|
||||
run.kill()
|
||||
run.wait()
|
||||
# SIGKILL cannot be handled: the program is expected to survive until `stop`.
|
||||
check(started and bool(workload_pids(name)), "SIGKILL: program survives, as documented")
|
||||
subprocess.run([a.runner, "hybrid", "stop", "--bottle", a.bottle], timeout=60)
|
||||
check(wait_for(lambda: not workload_pids(name), 15), "SIGKILL: `hybrid stop` removes it")
|
||||
healthy("after stop")
|
||||
|
||||
passed = 0
|
||||
for launch in range(a.launches):
|
||||
with tempfile.TemporaryFile("w+") as out:
|
||||
code = start(["--frames", "64"], out).wait(timeout=150)
|
||||
passed += code == 0
|
||||
if code:
|
||||
out.seek(0)
|
||||
try:
|
||||
reason = json.load(out).get("classification")
|
||||
except json.JSONDecodeError:
|
||||
reason = "no record"
|
||||
print(f" launch {launch + 1}: {reason}", flush=True)
|
||||
check(passed == a.launches, f"repeated launch: {passed} of {a.launches} passed")
|
||||
check(not workload_pids(name), "repeated launch: nothing left running")
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+102
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Compile original HLSL with external DXC, then verify actual Shader Model 6 GPU readback.
|
||||
|
||||
RUNNER BOTTLE PROBE_EXE DXC_BIN_DIR OUTPUT_DIR
|
||||
The dedicated test bottle must have Z: mapped to / (CrossOver's observed default).
|
||||
Expected float bit patterns below are derived from arithmetic, not the compiler or GPU.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def windows(path):
|
||||
return "Z:" + str(Path(path).resolve()).replace("/", "\\")
|
||||
|
||||
|
||||
def main():
|
||||
runner, bottle, probe, dxc, output = sys.argv[1:]
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
output = Path(output).resolve()
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
dxc = Path(dxc).resolve() / "dxc.exe"
|
||||
base = [str(Path(runner).resolve()), "hybrid", "run", "--bottle", bottle,
|
||||
"--backend", "d3dmetal", "--timeout", "120", "--keep-output", "true", "--out", str(output / "raw")]
|
||||
|
||||
def run(name, command):
|
||||
result = subprocess.run(base + ["--"] + command, capture_output=True, text=True, timeout=180)
|
||||
(output / (name + ".json")).write_text(result.stdout)
|
||||
(output / (name + ".log")).write_text(result.stderr)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"{name} failed; see {output}")
|
||||
record = json.loads(result.stdout)
|
||||
# Read the complete supervised stdout; a successful exit alone proves no result.
|
||||
return Path(record["stdout_path"]).read_text(errors="replace")
|
||||
|
||||
caps = run("caps", [probe, "caps"])
|
||||
match = re.search(r"options1: hr=0x0+ wave_ops=1 wave_lane_count_min=(\d+) wave_lane_count_max=(\d+)", caps)
|
||||
if not match:
|
||||
raise RuntimeError("wave capability query did not succeed; SM6 acceptance unavailable")
|
||||
expectations = {"add_f32_4": [0x40000000, 0] * 4, "sum_f32_4": [0x40A00000] * 4}
|
||||
results = {}
|
||||
for name, words in [("lanes4", 4), ("add_f32_4", 8), ("sum_f32_4", 4)]:
|
||||
shader = output / (name + ".dxil")
|
||||
run("compile-" + name, [str(dxc), "-T", "cs_6_6", "-E", "main", "-Fo", windows(shader),
|
||||
windows(root / "tests/conformance/test_d3d12_wave/hlsl" / (name + ".hlsl"))])
|
||||
disassembly = run("dxil-" + name, [str(dxc), "-dumpbin", windows(shader)])
|
||||
operations = {
|
||||
"lanes4": [r"\bcall\b[^\n]*@dx\.op\.waveGetLaneIndex", r"\bcall\b[^\n]*@dx\.op\.waveGetLaneCount"],
|
||||
"sum_f32_4": [r"\bcall\b[^\n]*@dx\.op\.waveActiveOp\.f32"],
|
||||
"add_f32_4": [r"\bfadd\b"],
|
||||
}
|
||||
if any(not re.search(pattern, disassembly) for pattern in operations[name]):
|
||||
raise RuntimeError(f"{name}: compiled DXIL does not contain the operation being tested")
|
||||
text = run(name, [probe, "run", windows(shader), "1", str(words)])
|
||||
pairs = [(int(i), int(v, 16)) for i, v in re.findall(r"^out (\d+) 0x([0-9a-fA-F]+)$", text, re.M)]
|
||||
if [i for i, _ in pairs] != list(range(words)):
|
||||
raise RuntimeError(f"{name}: missing, duplicate or unexpected readback words")
|
||||
actual = [v for _, v in pairs]
|
||||
dispatch = re.search(r"dispatch_caps wave_ops=1 min=(\d+) max=(\d+)", text)
|
||||
if not dispatch:
|
||||
raise RuntimeError(f"{name}: no wave capabilities for the dispatch device")
|
||||
minimum, maximum = map(int, dispatch.groups())
|
||||
if name == "lanes4":
|
||||
width = actual[0] >> 8
|
||||
def valid_lanes(values):
|
||||
widths = {v >> 8 for v in values}
|
||||
lanes = {v & 255 for v in values}
|
||||
return (len(widths) == 1 and minimum <= width <= maximum and 4 <= width <= 128
|
||||
and not width & (width - 1) and len(lanes) == 4 and max(lanes) < width)
|
||||
if not valid_lanes(actual):
|
||||
raise RuntimeError(f"invalid or duplicate lane IDs or wave width: {actual}")
|
||||
wrong = actual.copy()
|
||||
wrong[0] ^= 0x80000000
|
||||
if valid_lanes(wrong):
|
||||
raise RuntimeError("lane invariant negative control failed")
|
||||
results[name] = {"actual": actual, "expected_properties": "one supported wave width; four distinct lane IDs below width", "negative_mismatches": 1}
|
||||
print("PASS SM6 lanes4: independent lane invariants and one-bit negative control")
|
||||
continue
|
||||
else:
|
||||
expected = expectations[name]
|
||||
mismatches = sum(a != b for a, b in zip(actual, expected))
|
||||
if mismatches:
|
||||
raise RuntimeError(f"{name}: {mismatches} incorrect GPU words: {actual}")
|
||||
# The deliberately wrong expectation must detect exactly one mismatch in this readback.
|
||||
wrong = expected.copy()
|
||||
wrong[0] ^= 1
|
||||
if sum(a != b for a, b in zip(actual, wrong)) != 1:
|
||||
raise RuntimeError(f"{name}: negative control failed")
|
||||
results[name] = {"actual": actual, "expected": expected, "negative_mismatches": 1}
|
||||
print(f"PASS SM6 {name}: {words} exact GPU words, one-bit negative control detected")
|
||||
(output / "summary.json").write_text(json.dumps({"schema": "betterxen-sm6/0", "passed": True, "results": results}, indent=2) + "\n")
|
||||
print("Unsupported double precision is not exercised or counted as passing.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (ValueError, OSError, RuntimeError, subprocess.SubprocessError, KeyError) as error:
|
||||
sys.exit(f"FAIL SM6: {error}")
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Produce a native runner and original redistributable workloads without starting CrossOver.
|
||||
set -eu
|
||||
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)
|
||||
TC=${1:?usage: build-maintainer.sh LLVM_MINGW_DIR}
|
||||
TC=$(CDPATH='' cd -- "$TC" && pwd)
|
||||
"$ROOT/scripts/hybrid/check-toolchain.sh" "$TC"
|
||||
export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-2}
|
||||
export RUSTUP_TOOLCHAIN=1.100.0-aarch64-apple-darwin
|
||||
OUT="$ROOT/artifacts/maintainer"
|
||||
mkdir -p "$OUT/bin" "$OUT/workloads" "$OUT/logs"
|
||||
cd "$ROOT"
|
||||
cargo build --locked --release --target aarch64-apple-darwin -p bx-cli \
|
||||
>"$OUT/logs/build.log" 2>&1 || { cat "$OUT/logs/build.log" >&2; exit 1; }
|
||||
for exe in bx-cli; do
|
||||
cp "${CARGO_TARGET_DIR:-$ROOT/target}/aarch64-apple-darwin/release/$exe" "$OUT/bin/$exe"
|
||||
file "$OUT/bin/$exe"
|
||||
[ "$(lipo -archs "$OUT/bin/$exe")" = arm64 ] || { echo "unexpected host architecture" >&2; exit 1; }
|
||||
otool -L "$OUT/bin/$exe" >"$OUT/logs/$exe-linkage.txt"
|
||||
python3 - "$OUT/logs/$exe-linkage.txt" <<'PY'
|
||||
from pathlib import Path
|
||||
import sys
|
||||
libraries = [line.strip().split(' (', 1)[0] for line in Path(sys.argv[1]).read_text().splitlines()[1:]]
|
||||
if not libraries or any(not lib.startswith(('/usr/lib/', '/System/Library/')) for lib in libraries):
|
||||
sys.exit(f'non-system or missing host linkage: {libraries}')
|
||||
PY
|
||||
done
|
||||
scripts/hybrid/build-windows-workloads.sh "$TC" >"$OUT/logs/build-workloads.log" 2>&1 ||
|
||||
{ cat "$OUT/logs/build-workloads.log" >&2; exit 1; }
|
||||
for exe in selfcheck-c selfcheck-rust d3d11-clear d3d11-frameloop; do
|
||||
cp "artifacts/hybrid-workloads/x86_64/$exe.exe" "$OUT/workloads/"
|
||||
done
|
||||
for api in d3d11 d3d12; do
|
||||
"tests/conformance/test_${api}_integrated/build.sh" "$TC" "$OUT/workloads" >>"$OUT/logs/build-workloads.log" 2>&1
|
||||
done
|
||||
tests/conformance/test_d3d12_lifetime/build.sh "$TC" "$OUT/workloads" >>"$OUT/logs/build-workloads.log" 2>&1
|
||||
tests/conformance/test_d3d12_wave/build.sh "$TC" "$OUT/workloads" >>"$OUT/logs/build-workloads.log" 2>&1
|
||||
python3 scripts/hybrid/collect-build-notices.py "$TC" "$OUT/licenses"
|
||||
git rev-parse HEAD >"$OUT/commit.txt"
|
||||
git status --porcelain >"$OUT/source-status.txt"
|
||||
"$OUT/bin/bx-cli" hybrid receipt >"$OUT/receipt.json"
|
||||
(cd "$OUT" && shasum -a 256 bin/* workloads/*.exe > SHA256SUMS)
|
||||
echo "Build and checksums: $OUT"
|
||||
Executable
+54
@@ -0,0 +1,54 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Build BetterXen's original Windows workloads (issue #364) with a pinned cross toolchain and
|
||||
# write the results to artifacts/hybrid-workloads/<arch>/. Nothing is executed; the script ends
|
||||
# by printing `file` and the PE machine type of every output so a build that produced the wrong
|
||||
# architecture fails here.
|
||||
#
|
||||
# scripts/hybrid/build-windows-workloads.sh <llvm-mingw-dir>
|
||||
#
|
||||
# <llvm-mingw-dir> is an unpacked llvm-mingw release (https://github.com/mstorsjo/llvm-mingw;
|
||||
# wrappers/scripts ISC, compiler and runtime under their component licences);
|
||||
# see https://github.com/MacosPorters/betterxen/blob/54264e23a417e861834ee879f810717385b91f58/docs/research/hybrid-toolchain.md for the pinned
|
||||
# release and checksum. Rust workloads use the x86_64-pc-windows-gnullvm and
|
||||
# aarch64-pc-windows-gnullvm targets (rustup target add ...) linked with that toolchain.
|
||||
set -eu
|
||||
TC=$(CDPATH='' cd -- "${1:?usage: $0 <llvm-mingw-dir>}" && pwd)
|
||||
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
OUT="$ROOT/artifacts/hybrid-workloads"
|
||||
RUSTC_TC=${RUSTUP_TOOLCHAIN_FOR_WORKLOADS:-1.100.0}
|
||||
[ -x "$TC/bin/x86_64-w64-mingw32-clang" ] || { echo "no llvm-mingw at $TC" >&2; exit 1; }
|
||||
"$ROOT/scripts/hybrid/check-toolchain.sh" "$TC"
|
||||
|
||||
for arch in x86_64; do
|
||||
d="$OUT/$arch"; mkdir -p "$d"
|
||||
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
|
||||
-o "$d/selfcheck-c.exe" "$ROOT/tests/conformance/test_runtime_c/selfcheck.c"
|
||||
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
|
||||
-o "$d/d3d11-clear.exe" "$ROOT/tests/conformance/test_d3d11_clear/d3d11_clear.c" -ld3d11 -ldxgi
|
||||
"$TC/bin/$arch-w64-mingw32-clang" -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp \
|
||||
-o "$d/d3d11-frameloop.exe" "$ROOT/tests/conformance/test_d3d11_frameloop/frameloop.c" -ld3d11 -ldxgi -ldxguid -ld3dcompiler -lm
|
||||
env_arch=$(echo "$arch" | tr a-z A-Z)
|
||||
(
|
||||
export PATH="$TC/bin:$PATH"
|
||||
export "CARGO_TARGET_${env_arch}_PC_WINDOWS_GNULLVM_LINKER=$TC/bin/$arch-w64-mingw32-clang"
|
||||
export CARGO_ENCODED_RUSTFLAGS
|
||||
CARGO_ENCODED_RUSTFLAGS=$(printf '%s\037%s\037%s' '-C' 'link-arg=-Wl,--no-insert-timestamp' "--remap-path-prefix=$ROOT=/betterxen")
|
||||
cd "$ROOT/tests/conformance/support/win-selfcheck-rust"
|
||||
CARGO_TARGET_DIR="$OUT/rust-target" rustup run "$RUSTC_TC" cargo build --locked --release --target "$arch-pc-windows-gnullvm" -q
|
||||
)
|
||||
cp "$OUT/rust-target/$arch-pc-windows-gnullvm/release/win-selfcheck-rust.exe" "$d/selfcheck-rust.exe"
|
||||
done
|
||||
|
||||
fail=0
|
||||
for f in "$OUT"/x86_64/*.exe; do
|
||||
want=$(basename "$(dirname "$f")")
|
||||
desc=$(file -b "$f")
|
||||
case "$want:$desc" in
|
||||
x86_64:*"PE32+"*"x86-64"*) ok=ok ;;
|
||||
aarch64:*"PE32+"*"Aarch64"*|aarch64:*"PE32+"*"ARM64"*) ok=ok ;;
|
||||
*) ok=WRONG; fail=1 ;;
|
||||
esac
|
||||
echo "$ok $f: $desc"
|
||||
done
|
||||
exit $fail
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""A negative control counts only when the injected fault failed the gate it targets.
|
||||
|
||||
check-failed-gates.py RECORD.json GATE [GATE...]
|
||||
|
||||
Passes when the record is a non-zero workload exit and every named gate was reported
|
||||
and failed. A crash, a missing gate or an unrelated failure is not a detection.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
path, *wanted = sys.argv[1:]
|
||||
if not wanted:
|
||||
raise ValueError("name at least one gate")
|
||||
record = json.loads(Path(path).read_text())
|
||||
if record["classification"] != "failed_exit_1":
|
||||
raise ValueError(f"expected failed_exit_1, got {record['classification']}")
|
||||
reported = {gate["name"]: gate["passed"] for gate in record["gates"]}
|
||||
for name in wanted:
|
||||
if name not in reported:
|
||||
raise ValueError(f"gate {name} was never reported")
|
||||
if reported[name]:
|
||||
raise ValueError(f"gate {name} passed despite the injected fault")
|
||||
failed = sorted(name for name, passed in reported.items() if not passed)
|
||||
print(",".join(failed))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, KeyError) as error:
|
||||
sys.exit(f"FAIL negative control: {error}")
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Independent image oracle for the fixed scripted D3D11/D3D12 scene.
|
||||
|
||||
Build images by painting whole rectangles, independently of the workloads' pixel
|
||||
functions and GPU shaders. The fixed protocol is: far A at (32,32), near B at
|
||||
(96,96), 128-square quads with four 64-square colours; five 16-pixel key moves;
|
||||
rotate RGB to BRG; overwrite the top 16 rows with the frame number. Hash only the
|
||||
specified verification frames, in row-major RGBA order. No renderer or C oracle
|
||||
is called. The legacy digest seed is intentionally preserved (it differs from
|
||||
the standard FNV offset basis).
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
PALETTES = (((255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)),
|
||||
((255, 255, 0), (0, 255, 255), (255, 0, 255), (128, 128, 128)))
|
||||
POSITIONS = ((96, 96), (112, 96), (128, 96), (128, 112), (112, 112), (112, 128))
|
||||
|
||||
|
||||
def image(frame, interval):
|
||||
pixels = bytearray(b"\x00\x00\x00\xff" * (256 * 256))
|
||||
|
||||
def rectangle(x, y, width, height, rgba):
|
||||
row = bytes(rgba) * width
|
||||
for line in range(y, y + height):
|
||||
start = (line * 256 + x) * 4
|
||||
pixels[start:start + width * 4] = row
|
||||
|
||||
# Painter's order is analytically equivalent to the scene's depth test.
|
||||
steps = min(frame // interval, 5)
|
||||
for palette, (x, y) in zip(PALETTES, ((32, 32), POSITIONS[steps])):
|
||||
for quadrant, (r, g, b) in enumerate(palette):
|
||||
rectangle(x + (quadrant % 2) * 64, y + (quadrant // 2) * 64, 64, 64, (b, r, g, 255))
|
||||
marker = (frame + 1) & 65535
|
||||
rectangle(0, 0, 256, 16, (marker & 255, marker >> 8, 77, 255))
|
||||
return pixels
|
||||
|
||||
|
||||
def expected_digest(frames, verify_every):
|
||||
interval = frames // 8
|
||||
selected = set(range(0, frames, verify_every)) | {0, frames - 1}
|
||||
selected.update(k * interval + 1 for k in range(1, 6) if k * interval + 1 < frames)
|
||||
digest = 1469598103934665603
|
||||
for frame in sorted(selected):
|
||||
for byte in image(frame, interval):
|
||||
digest = ((digest ^ byte) * 1099511628211) & 0xffffffffffffffff
|
||||
return f"{digest:016x}", len(selected)
|
||||
|
||||
|
||||
def main():
|
||||
record = json.loads(Path(sys.argv[1]).read_text())
|
||||
args = record["args"]
|
||||
if any(flag in args for flag in ["--fault", "--duration-s", "--external-input", "--interactive"]):
|
||||
raise ValueError("oracle accepts only the fixed scripted scene, without injected faults")
|
||||
frames = int(args[args.index("--frames") + 1]) if "--frames" in args else 600
|
||||
verify = int(args[args.index("--verify-every") + 1]) if "--verify-every" in args else 30
|
||||
if frames < 64 or verify < 1:
|
||||
raise ValueError("invalid verification schedule")
|
||||
gate = next(g for g in record["gates"] if g["name"] == "frame.continuous")
|
||||
if not gate["passed"]:
|
||||
raise ValueError("continuous rendering gate did not pass")
|
||||
observed = re.search(r"verified=(\d+) mismatched=0 digest=([0-9a-f]{16})", gate["detail"])
|
||||
expected, count = expected_digest(frames, verify)
|
||||
if not observed or observed.groups() != (str(count), expected):
|
||||
raise ValueError(f"independent digest mismatch: expected {count} verified frames, digest={expected}; {gate['detail']}")
|
||||
print(f"PASS independent image oracle: {count} frames digest={expected}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (OSError, ValueError, KeyError, StopIteration) as error:
|
||||
sys.exit(f"FAIL independent image oracle: {error}")
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
set -eu
|
||||
TC=${1:?usage: check-toolchain.sh LLVM_MINGW_DIR}
|
||||
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)
|
||||
PIN=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["llvm_commit"])' "$ROOT/scripts/hybrid/toolchain.json")
|
||||
[ "$(uname -s):$(uname -m)" = Darwin:arm64 ] || { echo "native Apple Silicon macOS is required" >&2; exit 1; }
|
||||
for name in clang ld.lld; do
|
||||
[ -x "$TC/bin/$name" ] || { echo "missing $TC/bin/$name" >&2; exit 1; }
|
||||
lipo "$TC/bin/$name" -verify_arch arm64
|
||||
done
|
||||
"$TC/bin/x86_64-w64-mingw32-clang" --version | grep -F "$PIN" >/dev/null
|
||||
echo "verified ARM64-capable llvm-mingw compiler at $PIN" >&2
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Preserve unmodified notices for the standalone hybrid runner and Windows runtime."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
toolchain, output = map(lambda p: Path(p).resolve(), sys.argv[1:])
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
meta = json.loads(subprocess.check_output(["cargo", "metadata", "--locked", "--format-version", "1"], cwd=root))
|
||||
libc = [p for p in meta["packages"] if p["name"] == "libc"]
|
||||
if len(libc) != 1:
|
||||
sys.exit("expected exactly one locked libc dependency")
|
||||
package = libc[0]
|
||||
source = Path(package["manifest_path"]).parent
|
||||
shutil.copytree(source, output / "libc-source", dirs_exist_ok=True)
|
||||
notices = [source / "LICENSE-MIT", source / "LICENSE-APACHE"]
|
||||
for path in notices:
|
||||
shutil.copy2(path, output / ("libc-" + path.name))
|
||||
shutil.copy2(toolchain / "LICENSE.TXT", output / "llvm-mingw-LICENSE.TXT")
|
||||
for path in (toolchain / "x86_64-w64-mingw32/share/mingw32").glob("COPYING*"):
|
||||
shutil.copy2(path, output / ("mingw-" + path.name))
|
||||
sysroot = Path(subprocess.check_output(["rustc", "--print", "sysroot"], text=True).strip())
|
||||
docs = sysroot / "share/doc/rust"
|
||||
for name in ["COPYRIGHT.html", "COPYRIGHT-library.html"]:
|
||||
shutil.copy2(docs / name, output / ("rust-" + name))
|
||||
shutil.copytree(docs / "licenses", output / "rust-licenses", dirs_exist_ok=True)
|
||||
manifest = {"schema": "betterxen-build-notices/0", "rust": "1.100.0", "libc": {
|
||||
"version": package["version"], "license": package["license"], "source": package["source"]},
|
||||
"llvm_mingw": json.loads((root / "scripts/hybrid/toolchain.json").read_text()),
|
||||
"scope": "Standalone bx-cli plus original Windows workloads; no native research CLI or external proprietary components"}
|
||||
(output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Create a new dedicated test bottle, refusing to reuse an existing directory.
|
||||
|
||||
This uses CrossOver's observed cxbottle interface, not a vendor-supported automation API.
|
||||
The new bottle also has Wine's crash dialog turned off: with it on, a crashing program
|
||||
waits for a click and an unattended run only ends at its timeout.
|
||||
|
||||
RUNNER BOTTLE
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
runner, name = sys.argv[1:]
|
||||
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", name):
|
||||
sys.exit("use a simple new bottle name with letters, digits, dots, dashes or underscores")
|
||||
facts = json.loads(subprocess.check_output([runner, "crossover"], text=True))
|
||||
if not facts["installs"]:
|
||||
sys.exit("install CrossOver from CodeWeavers first")
|
||||
app = Path(facts["installs"][0]["path"])
|
||||
base = Path(facts.get("bottle_dir_preference") or "~/Library/Application Support/CrossOver/Bottles").expanduser()
|
||||
prefix = base / name
|
||||
if prefix.exists() or prefix.is_symlink():
|
||||
sys.exit(f"refusing to reuse {prefix}; choose a fresh dedicated name")
|
||||
subprocess.run([str(app / "Contents/SharedSupport/CrossOver/bin/cxbottle"), "--bottle", name,
|
||||
"--create", "--template", "win11_64"], check=True, timeout=180, stdout=sys.stderr)
|
||||
if not (prefix / "drive_c").is_dir():
|
||||
sys.exit(f"CrossOver did not create the expected bottle at {prefix}")
|
||||
with tempfile.TemporaryDirectory() as records:
|
||||
subprocess.run([str(Path(runner).resolve()), "run", "--bottle", name, "--timeout", "180", "--out", records, "--",
|
||||
str(prefix / "drive_c/windows/system32/reg.exe"), "add", r"HKCU\Software\Wine\WineDbg",
|
||||
"/v", "ShowCrashDialog", "/t", "REG_DWORD", "/d", "0", "/f"],
|
||||
check=True, timeout=300, stdout=sys.stderr)
|
||||
print(json.dumps({"schema": "betterxen-test-bottle/0", "bottle": name, "prefix": str(prefix), "created": True, "crash_dialog": False}))
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Install only open-source build dependencies. CrossOver and Apple tools remain external.
|
||||
set -eu
|
||||
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)
|
||||
[ "$(uname -s):$(uname -m)" = Darwin:arm64 ] || { echo "native Apple Silicon macOS is required" >&2; exit 1; }
|
||||
command -v python3 >/dev/null
|
||||
command -v rustup >/dev/null || { echo "install native rustup from https://rustup.rs first" >&2; exit 1; }
|
||||
xcrun --find clang >/dev/null
|
||||
TC=$(python3 "$ROOT/scripts/hybrid/install-toolchain.py" "${1:-$HOME/Library/Caches/BetterXen/toolchains}")
|
||||
"$ROOT/scripts/hybrid/check-toolchain.sh" "$TC"
|
||||
rustup toolchain install 1.100.0 --profile minimal --component rustfmt --component clippy \
|
||||
--target aarch64-apple-darwin --target x86_64-pc-windows-gnullvm >&2
|
||||
printf '%s\n' "$TC"
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Install Microsoft's checksum-pinned open-source Windows DXC as an external guest tool."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import shutil
|
||||
import stat
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
URL = "https://github.com/microsoft/DirectXShaderCompiler/releases/download/v1.9.2609/dxc_2026_09_29.zip"
|
||||
SHA256 = "ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1"
|
||||
|
||||
|
||||
def install(destination):
|
||||
destination = destination.expanduser().resolve()
|
||||
archive = destination / "dxc_2026_09_29.zip"
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
if any(p != archive for p in destination.iterdir()):
|
||||
raise RuntimeError(f"{destination} already contains extracted files; choose a fresh installation directory")
|
||||
if not archive.exists():
|
||||
subprocess.run(["/usr/bin/curl", "--fail", "--location", "--retry", "3", "--connect-timeout", "30",
|
||||
URL, "-o", str(archive)], check=True)
|
||||
with archive.open("rb") as stream:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if digest != SHA256:
|
||||
raise RuntimeError(f"DXC checksum mismatch: {digest}, expected {SHA256}")
|
||||
with zipfile.ZipFile(archive) as bundle:
|
||||
entries = []
|
||||
for member in bundle.infolist():
|
||||
# Microsoft's Windows zip uses backslashes; normalize before checking containment.
|
||||
name = member.filename.replace("\\", "/")
|
||||
if Path(name).is_absolute() or ".." in Path(name).parts or ":" in name or stat.S_ISLNK(member.external_attr >> 16):
|
||||
raise RuntimeError(f"invalid archive path {member.filename}")
|
||||
entries.append((member, name))
|
||||
for member, name in entries:
|
||||
path = destination / name
|
||||
if name.endswith("/"):
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with bundle.open(member) as source, path.open("xb") as target:
|
||||
shutil.copyfileobj(source, target)
|
||||
compiler = destination / "bin/x64/dxc.exe"
|
||||
if not compiler.is_file():
|
||||
raise RuntimeError("pinned archive lacks bin/x64/dxc.exe")
|
||||
print(compiler.parent)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
install(Path(sys.argv[1]) if len(sys.argv) > 1 else Path.home() / "Library/Caches/BetterXen/dxc-v1.9.2609")
|
||||
except (OSError, RuntimeError, zipfile.BadZipFile, subprocess.CalledProcessError) as error:
|
||||
sys.exit(str(error))
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Download the pinned external llvm-mingw release; print its installed path on stdout.
|
||||
|
||||
Only the checksum-verified archive is extracted. No compiler, workload or proprietary
|
||||
component is executed. Existing installations are never overwritten.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
|
||||
def install(destination):
|
||||
if not hasattr(tarfile, "data_filter"):
|
||||
raise RuntimeError("Python with tarfile.data_filter is required (Python 3.12 or newer)")
|
||||
pin = json.loads(Path(__file__).with_name("toolchain.json").read_text())
|
||||
destination = destination.expanduser().resolve()
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
archive = destination / pin["asset"]
|
||||
if not archive.exists():
|
||||
print(f'Downloading {pin["url"]}', file=sys.stderr)
|
||||
with tempfile.NamedTemporaryFile(dir=destination, delete=False) as out:
|
||||
temporary = Path(out.name)
|
||||
try:
|
||||
out.close()
|
||||
subprocess.run(["/usr/bin/curl", "--fail", "--location", "--retry", "3",
|
||||
"--connect-timeout", "30", "--output", str(temporary), pin["url"]], check=True)
|
||||
verify(temporary, pin["sha256"])
|
||||
# Publish without overwriting an archive installed by a concurrent invocation.
|
||||
os.link(temporary, archive)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
verify(archive, pin["sha256"])
|
||||
installed = destination / pin["asset"].removesuffix(".tar.xz")
|
||||
if installed.exists():
|
||||
raise RuntimeError(f"{installed} already exists; choose a fresh destination to avoid using a modified toolchain")
|
||||
with tempfile.TemporaryDirectory(prefix=".llvm-mingw-", dir=destination) as staging:
|
||||
with tarfile.open(archive, "r:xz") as bundle:
|
||||
# The pinned archive is trusted; also reject names escaping its single root.
|
||||
for member in bundle.getmembers():
|
||||
parts = Path(member.name).parts
|
||||
if not parts or parts[0] != installed.name or ".." in parts or Path(member.name).is_absolute():
|
||||
raise RuntimeError(f"unexpected archive path: {member.name}")
|
||||
bundle.extractall(staging, filter="data")
|
||||
os.rename(Path(staging) / installed.name, installed)
|
||||
print(f'Verified SHA-256 {pin["sha256"]}', file=sys.stderr)
|
||||
return installed
|
||||
|
||||
|
||||
def verify(path, expected):
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as source:
|
||||
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
if digest.hexdigest() != expected:
|
||||
raise RuntimeError(f"checksum mismatch for {path}: got {digest.hexdigest()}, expected {expected}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
print(install(Path(sys.argv[1]) if len(sys.argv) > 1 else Path.home() / "Library/Caches/BetterXen/toolchains"))
|
||||
except (OSError, RuntimeError, tarfile.TarError, subprocess.CalledProcessError) as error:
|
||||
sys.exit(str(error))
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Private maintainer test bundle: original source, ARM64 runners and original Windows probes.
|
||||
set -eu
|
||||
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd)
|
||||
cd "$ROOT"
|
||||
[ -z "$(git status --porcelain)" ] || { echo "package requires a clean committed checkout" >&2; exit 1; }
|
||||
COMMIT=$(git rev-parse HEAD)
|
||||
OUT="$ROOT/artifacts/maintainer"
|
||||
[ "$(cat "$OUT/commit.txt")" = "$COMMIT" ] && [ ! -s "$OUT/source-status.txt" ] ||
|
||||
{ echo "rebuild from this clean commit before packaging" >&2; exit 1; }
|
||||
(cd "$OUT" && shasum -a 256 -c SHA256SUMS)
|
||||
mkdir -p "$ROOT/artifacts/packages"
|
||||
STAGE=$(mktemp -d "$ROOT/artifacts/packages/staging-XXXXXX")
|
||||
trap 'rm -rf "$STAGE"' EXIT HUP INT TERM
|
||||
NAME="betterxen-maintainer-$COMMIT"
|
||||
[ ! -e "$ROOT/artifacts/packages/$NAME.tar.gz" ] || { echo "artifact already exists; preserving it" >&2; exit 1; }
|
||||
mkdir "$STAGE/$NAME"
|
||||
mkdir "$STAGE/$NAME/bin"
|
||||
# bx-cli's only external dependency is libc (docs/licenses.md); CrossOver, Apple components,
|
||||
# compilers and DXC are never copied into the bundle.
|
||||
cp "$OUT/bin/bx-cli" "$STAGE/$NAME/bin/"
|
||||
mkdir "$STAGE/$NAME/workloads"
|
||||
for exe in selfcheck-c selfcheck-rust d3d11-clear d3d11-frameloop d3d11-integrated d3d12-integrated d3d12-lifetime d3d12-wave-probe; do
|
||||
cp "$OUT/workloads/$exe.exe" "$STAGE/$NAME/workloads/"
|
||||
done
|
||||
cp -R "$OUT/commit.txt" "$OUT/licenses" "$STAGE/$NAME/"
|
||||
(cd "$STAGE/$NAME" && shasum -a 256 bin/* workloads/*.exe > SHA256SUMS)
|
||||
cp LICENSE THIRD_PARTY_NOTICES.md docs/maintainer-testing.md "$STAGE/$NAME/"
|
||||
cp scripts/hybrid/test-bundle.sh "$STAGE/$NAME/test.sh"
|
||||
chmod +x "$STAGE/$NAME/test.sh"
|
||||
git archive --format=tar.gz --prefix=betterxen-source/ -o "$STAGE/$NAME/source.tar.gz" "$COMMIT"
|
||||
(cd "$STAGE/$NAME" && shasum -a 256 source.tar.gz > SOURCE-SHA256SUMS)
|
||||
tar -czf "$ROOT/artifacts/packages/$NAME.tar.gz" -C "$STAGE" "$NAME"
|
||||
(cd "$ROOT/artifacts/packages" && shasum -a 256 "$NAME.tar.gz" > "$NAME.tar.gz.sha256")
|
||||
echo "$ROOT/artifacts/packages/$NAME.tar.gz"
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
# Installed as test.sh at the root of a private maintainer bundle. No Rust or cross-compiler
|
||||
# is needed: both runners and original workload binaries were built from the recorded commit.
|
||||
set -eu
|
||||
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
|
||||
BOTTLE=${1:?usage: ./test.sh NEW_DEDICATED_BOTTLE_NAME}
|
||||
[ "$(uname -s):$(uname -m)" = Darwin:arm64 ] || { echo "native Apple Silicon macOS is required" >&2; exit 1; }
|
||||
cd "$ROOT"
|
||||
/usr/bin/shasum -a 256 -c SHA256SUMS
|
||||
/usr/bin/shasum -a 256 -c SOURCE-SHA256SUMS
|
||||
BUNDLE_TEST=$(mktemp -d "$ROOT/test-XXXXXX")
|
||||
tar -xzf "$ROOT/source.tar.gz" -C "$BUNDLE_TEST"
|
||||
SOURCE="$BUNDLE_TEST/betterxen-source"
|
||||
BX="$ROOT/bin/bx-cli"
|
||||
python3 "$SOURCE/scripts/hybrid/create-test-bottle.py" "$BX" "$BOTTLE" >"$BUNDLE_TEST/bottle.json"
|
||||
"$BX" hybrid doctor --bottle "$BOTTLE" >"$BUNDLE_TEST/doctor.json"
|
||||
echo "Testing commit $(cat "$ROOT/commit.txt"); diagnostics under $BUNDLE_TEST"
|
||||
export BETTERXEN_RUNNER="$BX"
|
||||
export BETTERXEN_HYBRID_RUNNER="$BX"
|
||||
export BETTERXEN_WORKLOAD_DIR="$ROOT/workloads"
|
||||
export BETTERXEN_SOURCE_COMMIT
|
||||
BETTERXEN_SOURCE_COMMIT=$(cat "$ROOT/commit.txt")
|
||||
exec "$SOURCE/scripts/hybrid/accept-integrated.sh" unused "$BOTTLE"
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"release": "20261117",
|
||||
"asset": "llvm-mingw-20261117-ucrt-macos-universal.tar.xz",
|
||||
"url": "https://github.com/mstorsjo/llvm-mingw/releases/download/20261117/llvm-mingw-20261117-ucrt-macos-universal.tar.xz",
|
||||
"sha256": "98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa",
|
||||
"llvm_commit": "5b10d2d74929eae78912771222c9855af97496f4",
|
||||
"rust": "1.100.0"
|
||||
}
|
||||
@@ -185,9 +185,6 @@ pub enum Verdict {
|
||||
DeviceRemoved { reason: u32 },
|
||||
/// The GPU did not signal completion in time.
|
||||
TimedOut { detail: String },
|
||||
/// The device reported a highest shader model below the 6.6 the harness kernel
|
||||
/// requires. The field was parsed and printed before, but never judged (#567).
|
||||
UnsupportedShaderModel { reported: u8 },
|
||||
/// Every word still holds the sentinel: the kernel never wrote.
|
||||
KernelDidNotRun,
|
||||
/// The kernel wrote, but some words differ from the expected values.
|
||||
@@ -227,12 +224,6 @@ impl fmt::Display for Verdict {
|
||||
)
|
||||
}
|
||||
Self::TimedOut { detail } => write!(f, "FAIL: GPU timeout ({detail})"),
|
||||
Self::UnsupportedShaderModel { reported } => write!(
|
||||
f,
|
||||
"FAIL: highest shader model {}.{} is below the 6.6 the harness kernel requires",
|
||||
reported >> 4,
|
||||
reported & 0xf
|
||||
),
|
||||
Self::KernelDidNotRun => write!(
|
||||
f,
|
||||
"FAIL: all {WORDS} words still hold the sentinel 0x{SENTINEL:08x}; the kernel did not write"
|
||||
@@ -281,14 +272,6 @@ pub fn judge(report: &ProbeReport) -> Verdict {
|
||||
let incomplete = |reason: &str| Verdict::Incomplete {
|
||||
reason: reason.to_owned(),
|
||||
};
|
||||
// Every kernel the harness runs is SM 6.6. A device that reports less, or a
|
||||
// report with no shader_model record, must not pass on a matching readback
|
||||
// alone (#567). The live Rust test asserted this; the standalone verdict did not.
|
||||
match report.shader_model {
|
||||
Some(sm) if sm < 0x66 => return Verdict::UnsupportedShaderModel { reported: sm },
|
||||
None => return incomplete("no shader_model record"),
|
||||
Some(_) => {}
|
||||
}
|
||||
match report.dispatch {
|
||||
None => return incomplete("no dispatch record"),
|
||||
Some(d) if d != expected_dispatch => {
|
||||
@@ -358,29 +341,6 @@ mod tests {
|
||||
assert_eq!(judge(&report), Verdict::Pass);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shader_model_below_6_6_fails_even_with_a_matching_readback() {
|
||||
// The kernel is SM 6.6; the readback matching proves only that something wrote.
|
||||
for reported in ["0x65", "0x60"] {
|
||||
let lower = output(&good_words()).replace(
|
||||
"BXD3DM shader_model 0x66",
|
||||
&format!("BXD3DM shader_model {reported}"),
|
||||
);
|
||||
let report = parse_report(&lower).unwrap();
|
||||
assert_eq!(
|
||||
judge(&report),
|
||||
Verdict::UnsupportedShaderModel {
|
||||
reported: if reported == "0x65" { 0x65 } else { 0x60 }
|
||||
}
|
||||
);
|
||||
}
|
||||
// Without the record the harness cannot say the device can run the shader.
|
||||
let absent = output(&good_words()).replace("BXD3DM shader_model 0x66\n", "");
|
||||
let report = parse_report(&absent).unwrap();
|
||||
assert_eq!(report.shader_model, None);
|
||||
assert!(matches!(judge(&report), Verdict::Incomplete { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn untouched_sentinel_means_the_kernel_did_not_run() {
|
||||
let report = parse_report(&output(&[SENTINEL; WORDS])).unwrap();
|
||||
|
||||
@@ -186,70 +186,22 @@ mod tests {
|
||||
assert!(run.output_complete);
|
||||
}
|
||||
|
||||
/// Timeout for the tests below whose stand-in probe has to start and print before the
|
||||
/// deadline. Starting a freshly written script costs tens of milliseconds here and
|
||||
/// occasionally far more, so a few hundred milliseconds made these tests fail now and then
|
||||
/// (#479). They check what happens at the deadline, not how fast a script starts.
|
||||
const START_MARGIN: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Removes the pid file, and kills the recorded process if a failing test left it running.
|
||||
struct PidFile(PathBuf);
|
||||
|
||||
impl Drop for PidFile {
|
||||
fn drop(&mut self) {
|
||||
if std::thread::panicking()
|
||||
&& let Ok(pid) = std::fs::read_to_string(&self.0)
|
||||
{
|
||||
let _ = Command::new("/bin/kill").arg(pid.trim()).status();
|
||||
}
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kills_a_probe_that_exceeds_the_timeout() {
|
||||
let pid_file = PidFile(
|
||||
std::env::temp_dir().join(format!("bx-harness-probe's-{}.pid", std::process::id())),
|
||||
);
|
||||
let _ = std::fs::remove_file(&pid_file.0);
|
||||
// Pass the path as the value of --framework. The apostrophe tests literal path handling.
|
||||
// `exec` keeps the pid, so the recorded pid is the process that has to be killed.
|
||||
let script = Script::new(
|
||||
"hang",
|
||||
"echo $$ > \"$2\" || exit 1; echo started; exec sleep 30",
|
||||
);
|
||||
let script = Script::new("hang", "echo started; exec sleep 30");
|
||||
let started = Instant::now();
|
||||
let run = run_probe(&script.0, &pid_file.0, START_MARGIN).unwrap();
|
||||
let elapsed = started.elapsed();
|
||||
let run = run_probe(&script.0, Path::new("/fw"), Duration::from_millis(300)).unwrap();
|
||||
assert!(run.status.is_none());
|
||||
// Output written before the kill is kept.
|
||||
assert_eq!(run.stdout, "started\n");
|
||||
// The probe ran until the deadline and no longer: it was killed, not waited for.
|
||||
assert!(elapsed >= START_MARGIN, "returned early after {elapsed:?}");
|
||||
assert!(
|
||||
elapsed < START_MARGIN + DRAIN_GRACE + Duration::from_secs(5),
|
||||
"returned after {elapsed:?}"
|
||||
);
|
||||
// The process is gone. `output_complete` is deliberately not asserted: tests run in
|
||||
// parallel, and a child spawned by another test at the wrong moment can inherit this
|
||||
// probe's pipe and hold it open (seen in 2 of 200 runs).
|
||||
let pid = std::fs::read_to_string(&pid_file.0).unwrap();
|
||||
let alive = Command::new("/bin/kill")
|
||||
.args(["-0", pid.trim()])
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.unwrap()
|
||||
.success();
|
||||
assert!(!alive, "probe {} survived the timeout", pid.trim());
|
||||
assert!(started.elapsed() < Duration::from_secs(10));
|
||||
}
|
||||
|
||||
/// The probe exits at once, but a background descendant inherits stdout and
|
||||
/// keeps it open well past the timeout.
|
||||
#[test]
|
||||
fn a_descendant_holding_the_pipes_cannot_outlast_the_deadline() {
|
||||
// The descendant has to outlive the bound asserted below by a wide margin.
|
||||
let script = Script::new("orphan", "sleep 6 & echo started");
|
||||
let timeout = START_MARGIN;
|
||||
let script = Script::new("orphan", "sleep 5 & echo started");
|
||||
let timeout = Duration::from_millis(500);
|
||||
let started = Instant::now();
|
||||
let run = run_probe(&script.0, Path::new("/fw"), timeout).unwrap();
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
# dxbc-accc
|
||||
|
||||
Classifies D3D shader containers (`DXBC` with `DXIL`, legacy `SHDR`/`SHEX`, and `ACCC` chunks carrying BetterXen's synthetic `FSPX` table) and exposes the C ABI in [`abi/include/bx_shader_bridge.h`](../../../abi/include/bx_shader_bridge.h): `bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal` and `bx_shader_free_buffer`.
|
||||
|
||||
## Guest access: `bx_shader_bridge.dll` (#445)
|
||||
|
||||
The shims that see shader bytecode (`d3d12_xs.dll`) are x86-64 Windows PE32+ DLLs running inside CrossOver. They cannot load the arm64 macOS library that `cargo build` produces on the host. The bridge reaches guests as a **Windows build of this same crate**, with no second implementation:
|
||||
|
||||
- **Build:** `cargo build --target x86_64-pc-windows-gnu` turns the crate's `cdylib` into a PE32+ DLL, published as `bx_shader_bridge.dll`. Its Export Address Table holds exactly the three header functions as direct RVAs. It imports only Windows system DLLs that Wine provides, so no MinGW runtime DLL. `guest/build.sh` enforces both. The allowlist is `KERNEL32`, `ntdll`, `bcryptprimitives`, `USERENV`, `WS2_32` and the `api-ms-win-crt-*` / `api-ms-win-core-*` sets.
|
||||
- **Callers:** a shim loads the bridge at run time with `GetProcAddress`, so a missing bridge is a logged condition, not a load failure of the shim.
|
||||
- **Full path:** it must load the bridge by **full path from its own directory**. That is `GetModuleFileNameW` of the shim's own module (for example via `GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, ...)`), plus `bx_shader_bridge.dll`, loaded with `LoadLibraryExW(..., LOAD_WITH_ALTERED_SEARCH_PATH)`.
|
||||
- **Why not the bare name:** a bare `LoadLibraryW(L"bx_shader_bridge.dll")` searches the guest EXE's directory first under the [standard search order](https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order). It can therefore miss a bridge staged next to the shims, or pick up a different copy.
|
||||
- **Staging:** the bridge is meant to be staged in the same directory as the shims that call it.
|
||||
- **Why not a host tool over captured logs:** the M2 gate needs the decision at `Create*PipelineState` time inside the guest. That means passing DXIL through and rejecting ACCC-only containers. An offline host tool could count shaders but could not act on them.
|
||||
|
||||
### Build and check
|
||||
|
||||
```sh
|
||||
rustup target add x86_64-pc-windows-gnu # once
|
||||
shader-transpiler/crates/dxbc-accc/guest/build.sh
|
||||
target/debug/bx-cli run --prefix /tmp/bx-shader --shims target/bx-shader-bridge \
|
||||
--exe target/bx-shader-bridge/check_bridge.exe
|
||||
```
|
||||
|
||||
`guest/build.sh` writes `bx_shader_bridge.dll` and `check_bridge.exe` to `target/bx-shader-bridge/`. It always builds into, and copies from, `<repo>/target`, whatever `CARGO_TARGET_DIR` says, so it cannot package a stale DLL. It resolves `cargo` and `rustc` through rustup, checks that this `rustc` has `std` for the Windows target, and prints which `rustc` it used. It fails if the Export Address Table holds anything other than the three entry points as direct RVAs (an ordinal-only entry or a forwarder fails it), or if any import is outside the allowlist above.
|
||||
|
||||
[`guest/check_bridge.c`](guest/check_bridge.c) is a C guest program built against the frozen header. It checks the struct layout with `_Static_assert`, loads the DLL by full path from its own directory, and sends nine containers through the DLL:
|
||||
- a real DXC SM 6.6 compute blob (from [`d3dmetal-harness`](../d3dmetal-harness/README.md));
|
||||
- synthetic DXIL pixel SM 6.0 with `RTS0`, once as is and once followed by 16 bytes past its declared size;
|
||||
- `ACCC` with an `FSPX` v1 stage section, and `ACCC` with an `FSPX` v0 stub;
|
||||
- `DXIL` + `ACCC`;
|
||||
- legacy `SHEX`;
|
||||
- two malformed blobs.
|
||||
|
||||
The program prints one `BXSHADER` line per container and a count line, and checks:
|
||||
- **Classification:**
|
||||
- kind, stage and shader model;
|
||||
- the declared container size;
|
||||
- the exact `DXIL` and `ACCC` chunk sizes and the root signature flag, each derived from the program's own chunk-table walk;
|
||||
- the digest, compared with header bytes 4..20 for every container, the real one included.
|
||||
- **Prepare:** exactly the declared container is copied, never the trailing bytes. ACCC-only and legacy are `BX_SHADER_ERR_UNSUPPORTED`. Malformed input is `BX_SHADER_ERR_INVALID_BLOB`, with output cleared.
|
||||
- **Free and argument errors:** freeing returned buffers, and null arguments at the DLL boundary.
|
||||
|
||||
Recorded run (one Apple M5 Pro, macOS 27.2.1, CrossOver 26.3 `26.3.0.39832`, both a fresh prefix and a D3DMetal bottle):
|
||||
|
||||
```text
|
||||
BXSHADER counts dxil=3 accc_only=2 dual=1 legacy=1 unknown=0 invalid=2
|
||||
PASS: check_bridge (9 containers through bx_shader_bridge.dll)
|
||||
```
|
||||
|
||||
This is a synthetic, single-host result. It is not a measurement of any title's shader corpus, and not Xbox hardware.
|
||||
|
||||
Each of these faults compiled into the DLL fails the check: `dxil_chunk_size` clamped to 1, `accc_chunk_size` multiplied, the digest zeroed, `has_root_signature` set to 7, and the DXIL and ACCC kind numbers swapped. The last one also fails when it is rebuilt with `CARGO_TARGET_DIR` set elsewhere.
|
||||
|
||||
### Related work, owned elsewhere
|
||||
|
||||
Three of these pieces around this crate were recorded here as outstanding when this section was written and have since landed. The fourth is the trace summary of the records the shim emits.
|
||||
|
||||
- **`abi/defs/bx_shader_bridge.def` (`[ABI]`, #445, #484):** present and in use. Its `LIBRARY` directive is `bx_shader_bridge.dll`, and `scripts/build-shims.sh` passes it to `cargo rustc` as `-C link-arg=…/abi/defs/bx_shader_bridge.def`, so the built DLL's export directory holds exactly the three header entry points and its internal name is `bx_shader_bridge.dll`, not `dxbc_accc.dll`. Cargo still names the built file `dxbc_accc.dll`; the script copies it to `build-shims/bin/bx_shader_bridge.dll`, and the verifier requires the export-directory name to match the `.def`.
|
||||
- **Staging in `scripts/build-shims.sh` (Track A, #484):** done. The script builds this crate for `x86_64-pc-windows-gnu`, copies the result to `build-shims/bin/bx_shader_bridge.dll`, and verifies its export directory with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. CI's hybrid job installs that target with its pinned toolchain, so `rustup target add x86_64-pc-windows-gnu` is only a one-off step for a local build, and the script stops with that hint when the target's `std` is missing.
|
||||
- **Calling it from `d3d12_xs` at PSO creation, and JSONL telemetry (Track C, #466):** done. `CreateGraphicsPipelineState` and `CreateComputePipelineState` in `shims/d3d12_xs/proxy.cpp` run every stage through `BxShaderGate::admit` (`shims/d3d12_xs/shader_gate.cpp`), which calls `bx_shader_inspect` and `bx_shader_prepare_for_d3dmetal` and emits `shader_gate`, `shader_d3dmetal_gap` and `shader_bridge_missing` records through `bx_log_emit`. The bridge itself still writes its ACCC-only inspection line to the guest's stderr (`bx-shader event=prepare status=unsupported …`), because this crate does not link `bx_log_emit`; the JSONL records come from the shim.
|
||||
- **Trace summary of those records (`bx-cli trace`, Track A, #496):** the work to parse `shader_gate`, `shader_d3dmetal_gap` and `shader_bridge_missing` into `bx-telemetry` and render them in `bx-cli trace` is tracked in #496. This bullet describes the split of responsibility only — it does not depend on that issue's status, and the crate's own behaviour is unaffected either way.
|
||||
|
||||
This change does not touch the crate's code or tests; the tests above still describe its own behavior.
|
||||
@@ -1,108 +0,0 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Builds bx_shader_bridge.dll (this crate for x86_64-pc-windows-gnu) and the guest check
|
||||
# check_bridge.exe into one directory (default: <repo>/target/bx-shader-bridge), then checks
|
||||
# the DLL: its Export Address Table holds exactly the three bx_shader_bridge.h entry points as
|
||||
# direct RVAs (no extra named or ordinal-only entries, no forwarders), and every imported DLL
|
||||
# is a system DLL Wine provides. Run the check under CrossOver afterwards, for example:
|
||||
# target/debug/bx-cli run --prefix /tmp/bx-shader --shims target/bx-shader-bridge \
|
||||
# --exe target/bx-shader-bridge/check_bridge.exe
|
||||
#
|
||||
# Needs: rustup with the x86_64-pc-windows-gnu target, x86_64-w64-mingw32-gcc / -objdump
|
||||
# (mingw-w64), and python3.
|
||||
set -eu
|
||||
|
||||
crate=$(cd "$(dirname "$0")/.." && pwd)
|
||||
root=$(cd "$crate/../../.." && pwd)
|
||||
out=${1:-$root/target/bx-shader-bridge}
|
||||
target=x86_64-pc-windows-gnu
|
||||
cc=${BX_MINGW_CC:-x86_64-w64-mingw32-gcc}
|
||||
objdump=${BX_MINGW_OBJDUMP:-x86_64-w64-mingw32-objdump}
|
||||
# Always build here and copy from here, whatever CARGO_TARGET_DIR or build.target-dir say,
|
||||
# so a stale DLL left elsewhere can never be packaged.
|
||||
target_dir=$root/target
|
||||
|
||||
for tool in "$cc" "$objdump" python3; do
|
||||
command -v "$tool" >/dev/null 2>&1 || { echo "build.sh: $tool not found" >&2; exit 1; }
|
||||
done
|
||||
|
||||
# Use one toolchain for both the target check and the build. With rustup, resolve cargo and
|
||||
# rustc through it (a cargo earlier on PATH, e.g. Homebrew's, has no Windows std).
|
||||
if command -v rustup >/dev/null 2>&1; then
|
||||
cargo=$(cd "$root" && rustup which cargo)
|
||||
rustc=$(cd "$root" && rustup which rustc)
|
||||
else
|
||||
cargo=$(command -v cargo) || { echo "build.sh: cargo not found" >&2; exit 1; }
|
||||
rustc=$(command -v rustc) || { echo "build.sh: rustc not found" >&2; exit 1; }
|
||||
fi
|
||||
libdir=$("$rustc" --print target-libdir --target "$target" 2>/dev/null || true)
|
||||
if [ -z "$libdir" ] || ! ls "$libdir"/libstd-*.rlib >/dev/null 2>&1; then
|
||||
echo "build.sh: $rustc ($("$rustc" --version)) has no std for $target" >&2
|
||||
echo "build.sh: install it with: rustup target add $target" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "build.sh: using $("$rustc" --version) at $rustc"
|
||||
|
||||
RUSTC=$rustc CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=$cc \
|
||||
"$cargo" build --locked --release -p dxbc-accc --target "$target" \
|
||||
--target-dir "$target_dir" --manifest-path "$root/Cargo.toml"
|
||||
mkdir -p "$out"
|
||||
cp "$target_dir/$target/release/dxbc_accc.dll" "$out/bx_shader_bridge.dll"
|
||||
dll=$out/bx_shader_bridge.dll
|
||||
|
||||
# Same reading of `objdump -p` as scripts/build-shims.sh: every populated Export Address Table
|
||||
# slot must be a direct RVA owned by one of the expected names.
|
||||
"$objdump" -p "$dll" | python3 -I -c '
|
||||
import re, sys
|
||||
expected = {"bx_shader_inspect", "bx_shader_prepare_for_d3dmetal", "bx_shader_free_buffer"}
|
||||
# The Windows-provided system DLLs a Rust std cdylib imports; anything else is an error.
|
||||
allowed = {"kernel32.dll", "ntdll.dll", "bcryptprimitives.dll", "userenv.dll", "ws2_32.dll"}
|
||||
allowed_prefixes = ("api-ms-win-crt-", "api-ms-win-core-")
|
||||
eat, names, imports, mode = {}, {}, [], None
|
||||
for line in sys.stdin:
|
||||
line = line.rstrip("\n")
|
||||
m = re.match(r"^\s*DLL Name:\s*(\S+)", line)
|
||||
if m:
|
||||
imports.append(m.group(1))
|
||||
if line.startswith("Export Address Table --"):
|
||||
mode = "eat"; continue
|
||||
if line.startswith("[Ordinal/Name Pointer] Table --"):
|
||||
mode = "names"; continue
|
||||
if not line.strip():
|
||||
mode = None; continue
|
||||
if mode == "eat":
|
||||
m = re.match(r"^\s*\[\s*\d+\]\s*\+base\[\s*(\d+)\]\s+[0-9a-fA-F]+\s+(Export|Forwarder) RVA", line)
|
||||
if m:
|
||||
eat[int(m.group(1))] = m.group(2)
|
||||
elif mode == "names":
|
||||
m = re.match(r"^\s*\[\s*\d+\]\s*\+base\[\s*(\d+)\]\s+[0-9a-fA-F]+\s+(\S+)", line)
|
||||
if m:
|
||||
names[m.group(2)] = int(m.group(1))
|
||||
errors = []
|
||||
if set(names) != expected:
|
||||
errors.append("named exports %s, want %s" % (sorted(names), sorted(expected)))
|
||||
owned = set(names.values())
|
||||
for ordinal, kind in sorted(eat.items()):
|
||||
if ordinal not in owned:
|
||||
errors.append("export @%d has no name (ordinal-only or stray entry)" % ordinal)
|
||||
if kind != "Export":
|
||||
errors.append("export @%d is a forwarder" % ordinal)
|
||||
for name, ordinal in names.items():
|
||||
if ordinal not in eat:
|
||||
errors.append("%s @%d missing from the Export Address Table" % (name, ordinal))
|
||||
for dll in imports:
|
||||
low = dll.lower()
|
||||
if low not in allowed and not low.startswith(allowed_prefixes):
|
||||
errors.append("unexpected import %s (only Wine-provided system DLLs are allowed)" % dll)
|
||||
if errors:
|
||||
sys.exit("build.sh: bx_shader_bridge.dll: " + "; ".join(errors))
|
||||
print("build.sh: exports %s; imports %s" % (" ".join(sorted(names)), " ".join(imports)))
|
||||
'
|
||||
|
||||
"$cc" -std=c11 -O2 -Wall -Wextra -Werror -static \
|
||||
-I"$root/abi/include" -I"$crate/../d3dmetal-harness/probe/shaders" \
|
||||
-o "$out/check_bridge.exe" "$crate/guest/check_bridge.c"
|
||||
|
||||
echo "built $dll"
|
||||
echo "built $out/check_bridge.exe"
|
||||
@@ -1,296 +0,0 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Guest-side check for bx_shader_bridge.dll, the x86-64 Windows build of this crate (#445).
|
||||
*
|
||||
* Runs as a PE32+ guest under CrossOver/Wine, loads the DLL by full path from its own directory,
|
||||
* and drives the three entry points from abi/include/bx_shader_bridge.h with synthetic
|
||||
* containers plus one real DXC SM 6.6 compute blob. It counts the classifications and checks
|
||||
* them, and the prepare/free behaviour, against expectations written here from the DXBC
|
||||
* layout and the frozen header, not from the Rust implementation.
|
||||
*
|
||||
* Output: "BXSHADER" lines with each blob's classification, one "BXSHADER counts" line, then
|
||||
* PASS or FAIL. Exit code 0 on success, 1 on a failed check, 2 if the DLL cannot be loaded.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <wchar.h>
|
||||
|
||||
#include "bx_shader_bridge.h"
|
||||
#include "fill_cs66.h" /* g_fill_cs66: DXC 1.9.2609 output, see d3dmetal-harness */
|
||||
|
||||
/* The Rust side asserts the same layout; agreeing here proves both sides read one struct. */
|
||||
_Static_assert(sizeof(bx_shader_kind_t) == 4, "C enum must be 4 bytes");
|
||||
_Static_assert(sizeof(bx_shader_inspection_t) == 48, "bx_shader_inspection_t size");
|
||||
_Static_assert(offsetof(bx_shader_inspection_t, container_size) == 16, "container_size offset");
|
||||
_Static_assert(offsetof(bx_shader_inspection_t, digest_hash) == 32, "digest_hash offset");
|
||||
|
||||
typedef bx_shader_status_t (*inspect_fn)(const uint8_t*, size_t, bx_shader_inspection_t*);
|
||||
typedef bx_shader_status_t (*prepare_fn)(const uint8_t*, size_t, uint8_t**, size_t*);
|
||||
typedef void (*free_fn)(uint8_t*, size_t);
|
||||
|
||||
static int failures;
|
||||
|
||||
#define CHECK(expr) \
|
||||
do { \
|
||||
if (!(expr)) { \
|
||||
fprintf(stderr, "FAIL: check_bridge line %d: %s\n", __LINE__, #expr); \
|
||||
++failures; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* --- Synthetic DXBC containers --- */
|
||||
|
||||
static void put32(uint8_t* at, uint32_t value) {
|
||||
at[0] = (uint8_t)value;
|
||||
at[1] = (uint8_t)(value >> 8);
|
||||
at[2] = (uint8_t)(value >> 16);
|
||||
at[3] = (uint8_t)(value >> 24);
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
const char* fourcc;
|
||||
const uint8_t* data;
|
||||
uint32_t size;
|
||||
} chunk_t;
|
||||
|
||||
/* DXBC layout: "DXBC", 16-byte digest, u32 version 1, u32 total size, u32 chunk count, then
|
||||
* one u32 offset per chunk; each chunk is fourcc, u32 size, payload. */
|
||||
static uint32_t build_dxbc(uint8_t* out, size_t cap, const chunk_t* chunks, uint32_t count) {
|
||||
uint32_t at = 32 + 4 * count;
|
||||
for (uint32_t i = 0; i < count; ++i) at += 8 + chunks[i].size;
|
||||
if (at > cap) abort();
|
||||
memcpy(out, "DXBC", 4);
|
||||
memset(out + 4, 0x5A, 16);
|
||||
put32(out + 20, 1);
|
||||
put32(out + 24, at);
|
||||
put32(out + 28, count);
|
||||
uint32_t offset = 32 + 4 * count;
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
put32(out + 32 + 4 * i, offset);
|
||||
memcpy(out + offset, chunks[i].fourcc, 4);
|
||||
put32(out + offset + 4, chunks[i].size);
|
||||
memcpy(out + offset + 8, chunks[i].data, chunks[i].size);
|
||||
offset += 8 + chunks[i].size;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
/* A 28-byte DxilProgramHeader: program version word (kind << 16 | major << 4 | minor), size
|
||||
* in dwords (7), "DXIL", DXIL version 1.0, bitcode offset 16, bitcode size 4, 4 bitcode bytes. */
|
||||
static void dxil_program(uint8_t out[28], uint32_t kind, uint32_t major, uint32_t minor) {
|
||||
memset(out, 0, 28);
|
||||
put32(out, kind << 16 | major << 4 | minor);
|
||||
put32(out + 4, 7);
|
||||
memcpy(out + 8, "DXIL", 4);
|
||||
put32(out + 12, 0x0100);
|
||||
put32(out + 16, 16);
|
||||
put32(out + 20, 4);
|
||||
put32(out + 24, 0xDEC011D1u);
|
||||
}
|
||||
|
||||
/* Size of the first chunk named fourcc in a well-formed container, 0 if absent. Written from
|
||||
* the DXBC layout, independently of the Rust parser. */
|
||||
static uint32_t get32(const uint8_t* at) {
|
||||
return (uint32_t)at[0] | (uint32_t)at[1] << 8 | (uint32_t)at[2] << 16 | (uint32_t)at[3] << 24;
|
||||
}
|
||||
|
||||
static int chunk(const uint8_t* bytes, size_t len, const char* fourcc, uint32_t* size) {
|
||||
if (len < 32 || memcmp(bytes, "DXBC", 4) != 0) return 0;
|
||||
const uint32_t count = get32(bytes + 28);
|
||||
for (uint32_t i = 0; i < count && 36 + 4 * (size_t)i <= len; ++i) {
|
||||
const uint32_t offset = get32(bytes + 32 + 4 * i);
|
||||
if (offset + 8 <= len && memcmp(bytes + offset, fourcc, 4) == 0) {
|
||||
*size = get32(bytes + offset + 4);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* --- Cases --- */
|
||||
|
||||
typedef struct {
|
||||
const char* name;
|
||||
const uint8_t* bytes;
|
||||
size_t len;
|
||||
bx_shader_status_t inspect_status;
|
||||
bx_shader_kind_t kind;
|
||||
bx_shader_stage_t stage;
|
||||
uint32_t sm_major, sm_minor;
|
||||
uint32_t container_size; /* the container's declared size, which may be less than len */
|
||||
bx_shader_status_t prepare_status;
|
||||
} case_t;
|
||||
|
||||
static const char* kind_name(bx_shader_kind_t kind) {
|
||||
switch (kind) {
|
||||
case BX_SHADER_DXBC_DXIL: return "dxil";
|
||||
case BX_SHADER_DXBC_LEGACY: return "legacy";
|
||||
case BX_SHADER_DXBC_ACCC: return "accc_only";
|
||||
case BX_SHADER_DXBC_DUAL: return "dual";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
/* By full path beside this EXE, as a caller should (see the crate README). */
|
||||
wchar_t path[MAX_PATH];
|
||||
const DWORD path_len = GetModuleFileNameW(NULL, path, MAX_PATH);
|
||||
wchar_t* slash = path_len && path_len < MAX_PATH ? wcsrchr(path, L'\\') : NULL;
|
||||
if (!slash || (size_t)(slash + 1 - path) + 21 > MAX_PATH) {
|
||||
fprintf(stderr, "FAIL: check_bridge: executable path too long\n");
|
||||
return 2;
|
||||
}
|
||||
wcscpy(slash + 1, L"bx_shader_bridge.dll");
|
||||
HMODULE dll = LoadLibraryExW(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
|
||||
if (!dll) {
|
||||
fprintf(stderr, "FAIL: check_bridge: bx_shader_bridge.dll not loaded (error %lu)\n", GetLastError());
|
||||
return 2;
|
||||
}
|
||||
inspect_fn inspect = (inspect_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_inspect");
|
||||
prepare_fn prepare = (prepare_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_prepare_for_d3dmetal");
|
||||
free_fn release = (free_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_free_buffer");
|
||||
if (!inspect || !prepare || !release) {
|
||||
fprintf(stderr, "FAIL: check_bridge: missing export\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
uint8_t dxil_cs66[28], dxil_ps60[28];
|
||||
dxil_program(dxil_cs66, 5, 6, 6); /* DXIL program kind 5 = compute */
|
||||
dxil_program(dxil_ps60, 0, 6, 0); /* kind 0 = pixel */
|
||||
const uint8_t rts0[4] = {1, 2, 3, 4};
|
||||
|
||||
/* FSPX v1 (BetterXen's synthetic layout): header "FSPX", version 1, 1 section, flags 0;
|
||||
* descriptor {id 1 (stage config), offset 28, size 12}; body {stage 6 compute, SM 6.0}. */
|
||||
uint8_t fspx_v1[40] = {0};
|
||||
memcpy(fspx_v1, "FSPX", 4);
|
||||
put32(fspx_v1 + 4, 1);
|
||||
put32(fspx_v1 + 8, 1);
|
||||
put32(fspx_v1 + 16, 1);
|
||||
put32(fspx_v1 + 20, 28);
|
||||
put32(fspx_v1 + 24, 12);
|
||||
put32(fspx_v1 + 28, BX_STAGE_COMPUTE);
|
||||
put32(fspx_v1 + 32, 6);
|
||||
put32(fspx_v1 + 36, 0);
|
||||
/* FSPX version 0: magic-only stub, no sections. */
|
||||
uint8_t fspx_v0[16] = {'F', 'S', 'P', 'X'};
|
||||
/* SM 5.0 compute SHEX token (program type 5 << 16 | 5 << 4 | 0) and a length dword. */
|
||||
uint8_t shex[8];
|
||||
put32(shex, 5u << 16 | 5u << 4);
|
||||
put32(shex + 4, 2);
|
||||
|
||||
static uint8_t ps60[256], accc_v1[256], accc_v0[256], dual[256], legacy[256];
|
||||
const chunk_t ps60_chunks[] = {{"RTS0", rts0, 4}, {"DXIL", dxil_ps60, 28}};
|
||||
const chunk_t accc_v1_chunks[] = {{"ACCC", fspx_v1, sizeof(fspx_v1)}};
|
||||
const chunk_t accc_v0_chunks[] = {{"ACCC", fspx_v0, sizeof(fspx_v0)}};
|
||||
const chunk_t dual_chunks[] = {{"DXIL", dxil_cs66, 28}, {"ACCC", fspx_v0, sizeof(fspx_v0)}};
|
||||
const chunk_t legacy_chunks[] = {{"SHEX", shex, sizeof(shex)}};
|
||||
const uint32_t ps60_len = build_dxbc(ps60, sizeof(ps60), ps60_chunks, 2);
|
||||
const uint32_t accc_v1_len = build_dxbc(accc_v1, sizeof(accc_v1), accc_v1_chunks, 1);
|
||||
const uint32_t accc_v0_len = build_dxbc(accc_v0, sizeof(accc_v0), accc_v0_chunks, 1);
|
||||
const uint32_t dual_len = build_dxbc(dual, sizeof(dual), dual_chunks, 2);
|
||||
const uint32_t legacy_len = build_dxbc(legacy, sizeof(legacy), legacy_chunks, 1);
|
||||
/* The pixel shader again, followed by 16 bytes that are not part of the container. */
|
||||
static uint8_t padded[256 + 16];
|
||||
memcpy(padded, ps60, ps60_len);
|
||||
memset(padded + ps60_len, 0xEE, 16);
|
||||
static const uint8_t truncated[20] = {'D', 'X', 'B', 'C'};
|
||||
static const uint8_t not_dxbc[64] = {'X', 'X', 'X', 'X'};
|
||||
|
||||
const case_t cases[] = {
|
||||
{"dxc_cs_6_6", g_fill_cs66, sizeof(g_fill_cs66), BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_COMPUTE, 6, 6,
|
||||
sizeof(g_fill_cs66), BX_SHADER_OK},
|
||||
{"synthetic_ps_6_0", ps60, ps60_len, BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_PIXEL, 6, 0, ps60_len,
|
||||
BX_SHADER_OK},
|
||||
{"trailing_bytes", padded, ps60_len + 16, BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_PIXEL, 6, 0, ps60_len,
|
||||
BX_SHADER_OK},
|
||||
{"accc_fspx_v1", accc_v1, accc_v1_len, BX_SHADER_OK, BX_SHADER_DXBC_ACCC, BX_STAGE_COMPUTE, 6, 0, accc_v1_len,
|
||||
BX_SHADER_ERR_UNSUPPORTED},
|
||||
{"accc_fspx_v0", accc_v0, accc_v0_len, BX_SHADER_OK, BX_SHADER_DXBC_ACCC, BX_STAGE_UNKNOWN, 0, 0, accc_v0_len,
|
||||
BX_SHADER_ERR_UNSUPPORTED},
|
||||
{"dual_dxil_accc", dual, dual_len, BX_SHADER_OK, BX_SHADER_DXBC_DUAL, BX_STAGE_COMPUTE, 6, 6, dual_len,
|
||||
BX_SHADER_OK},
|
||||
{"legacy_shex_5_0", legacy, legacy_len, BX_SHADER_OK, BX_SHADER_DXBC_LEGACY, BX_STAGE_COMPUTE, 5, 0,
|
||||
legacy_len, BX_SHADER_ERR_UNSUPPORTED},
|
||||
{"truncated", truncated, sizeof(truncated), BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_UNKNOWN, BX_STAGE_UNKNOWN,
|
||||
0, 0, 0, BX_SHADER_ERR_INVALID_BLOB},
|
||||
{"not_dxbc", not_dxbc, sizeof(not_dxbc), BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_UNKNOWN, BX_STAGE_UNKNOWN, 0,
|
||||
0, 0, BX_SHADER_ERR_INVALID_BLOB},
|
||||
};
|
||||
const size_t count = sizeof(cases) / sizeof(cases[0]);
|
||||
|
||||
unsigned tally[5] = {0};
|
||||
unsigned invalid = 0;
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
const case_t* c = &cases[i];
|
||||
bx_shader_inspection_t info;
|
||||
memset(&info, 0xEE, sizeof(info));
|
||||
const bx_shader_status_t status = inspect(c->bytes, c->len, &info);
|
||||
printf("BXSHADER %s status=%d kind=%s stage=%d sm=%u.%u container_size=%u dxil=%u accc=%u rts0=%u\n",
|
||||
c->name, (int)status, kind_name(info.kind), (int)info.stage, info.shader_model_major,
|
||||
info.shader_model_minor, info.container_size, info.dxil_chunk_size, info.accc_chunk_size,
|
||||
info.has_root_signature);
|
||||
CHECK(status == c->inspect_status);
|
||||
if (status == BX_SHADER_OK) {
|
||||
if ((unsigned)info.kind < 5) ++tally[info.kind];
|
||||
CHECK(info.kind == c->kind);
|
||||
CHECK(info.stage == c->stage);
|
||||
CHECK(info.shader_model_major == c->sm_major && info.shader_model_minor == c->sm_minor);
|
||||
CHECK(info.container_size == c->container_size);
|
||||
/* Exact chunk sizes and the root signature flag, from this file's own chunk walk. */
|
||||
uint32_t want_dxil = 0, want_accc = 0, rts0_size = 0;
|
||||
chunk(c->bytes, c->len, "DXIL", &want_dxil);
|
||||
chunk(c->bytes, c->len, "ACCC", &want_accc);
|
||||
const uint32_t want_rts0 = (uint32_t)chunk(c->bytes, c->len, "RTS0", &rts0_size);
|
||||
CHECK(info.dxil_chunk_size == want_dxil);
|
||||
CHECK(info.accc_chunk_size == want_accc);
|
||||
CHECK(info.has_root_signature == want_rts0);
|
||||
CHECK((want_dxil != 0) == (c->kind == BX_SHADER_DXBC_DXIL || c->kind == BX_SHADER_DXBC_DUAL));
|
||||
CHECK((want_accc != 0) == (c->kind == BX_SHADER_DXBC_ACCC || c->kind == BX_SHADER_DXBC_DUAL));
|
||||
/* The digest is the container header's bytes 4..20, for every case. */
|
||||
CHECK(memcmp(info.digest_hash, c->bytes + 4, 16) == 0);
|
||||
} else {
|
||||
++invalid;
|
||||
const bx_shader_inspection_t zero = {0};
|
||||
CHECK(memcmp(&info, &zero, sizeof(info)) == 0); /* cleared on failure */
|
||||
}
|
||||
|
||||
uint8_t* copy = (uint8_t*)(uintptr_t)1;
|
||||
size_t copy_len = 1;
|
||||
const bx_shader_status_t prepared = prepare(c->bytes, c->len, ©, ©_len);
|
||||
CHECK(prepared == c->prepare_status);
|
||||
if (prepared == BX_SHADER_OK) {
|
||||
/* Only the declared container is copied, never bytes past it. */
|
||||
CHECK(copy && copy_len == c->container_size && memcmp(copy, c->bytes, c->container_size) == 0);
|
||||
release(copy, copy_len);
|
||||
} else {
|
||||
CHECK(copy == NULL && copy_len == 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Argument checks at the DLL boundary. */
|
||||
bx_shader_inspection_t info;
|
||||
CHECK(inspect(g_fill_cs66, sizeof(g_fill_cs66), NULL) == BX_SHADER_ERR_INVALID_BLOB);
|
||||
CHECK(inspect(NULL, 16, &info) == BX_SHADER_ERR_INVALID_BLOB);
|
||||
uint8_t* copy = NULL;
|
||||
CHECK(prepare(g_fill_cs66, sizeof(g_fill_cs66), NULL, NULL) == BX_SHADER_ERR_INVALID_BLOB);
|
||||
CHECK(prepare(NULL, 16, ©, &(size_t){0}) == BX_SHADER_ERR_INVALID_BLOB && copy == NULL);
|
||||
release(NULL, 0);
|
||||
|
||||
printf("BXSHADER counts dxil=%u accc_only=%u dual=%u legacy=%u unknown=%u invalid=%u\n",
|
||||
tally[BX_SHADER_DXBC_DXIL], tally[BX_SHADER_DXBC_ACCC], tally[BX_SHADER_DXBC_DUAL],
|
||||
tally[BX_SHADER_DXBC_LEGACY], tally[BX_SHADER_UNKNOWN], invalid);
|
||||
CHECK(tally[BX_SHADER_DXBC_DXIL] == 3 && tally[BX_SHADER_DXBC_ACCC] == 2 && tally[BX_SHADER_DXBC_DUAL] == 1);
|
||||
CHECK(tally[BX_SHADER_DXBC_LEGACY] == 1 && tally[BX_SHADER_UNKNOWN] == 0 && invalid == 2);
|
||||
|
||||
if (failures) {
|
||||
fprintf(stderr, "FAIL: check_bridge (%d failed checks)\n", failures);
|
||||
return 1;
|
||||
}
|
||||
printf("PASS: check_bridge (%u containers through bx_shader_bridge.dll)\n", (unsigned)count);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
|
||||
d3d12_xs.cpp
|
||||
vmem.cpp
|
||||
proxy.cpp
|
||||
proxy_generated.cpp
|
||||
shader_gate.cpp
|
||||
)
|
||||
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32)
|
||||
+19
-36
@@ -1,8 +1,8 @@
|
||||
#include "proxy.h"
|
||||
#include "vmem.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
/*
|
||||
* Track C (M1-C1, #414): Xbox Series D3D12 entry points over the host's d3d12.dll
|
||||
@@ -20,12 +20,9 @@ HMODULE get_host_d3d12() {
|
||||
return mod;
|
||||
}
|
||||
|
||||
void initialize_trace_flag() {
|
||||
static std::once_flag initialized;
|
||||
std::call_once(initialized, [] {
|
||||
const bx_runtime_config_t* cfg = bx_get_runtime_config();
|
||||
g_bx_trace_d3d = (cfg && cfg->trace_d3d) ? 1u : 0u;
|
||||
});
|
||||
void refresh_trace_flag() {
|
||||
const bx_runtime_config_t* cfg = bx_get_runtime_config();
|
||||
g_bx_trace_d3d = (cfg && cfg->trace_d3d) ? 1u : 0u;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -43,7 +40,7 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
initialize_trace_flag();
|
||||
refresh_trace_flag();
|
||||
|
||||
using CreateFn = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
|
||||
HMODULE d3d12 = get_host_d3d12();
|
||||
@@ -56,24 +53,12 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
}
|
||||
|
||||
ID3D12Device* host = nullptr;
|
||||
char reuse[8] = {};
|
||||
/* Test hook. While the backing cache holds a host heap, that heap keeps the host
|
||||
device alive, and a real runtime then returns the same ID3D12Device. Set the
|
||||
variable so the next proxy wraps that device even if this host does not. */
|
||||
const bool reuse_backing = GetEnvironmentVariableA("BX_D3D12_REUSE_BACKING_HOST", reuse, sizeof(reuse)) > 0 &&
|
||||
reuse[0] == '1' && reuse[1] == '\0';
|
||||
if (reuse_backing) {
|
||||
host = static_cast<ID3D12Device*>(bx_vmem_addref_backing_host());
|
||||
}
|
||||
HRESULT hr = S_OK;
|
||||
if (!host) {
|
||||
hr = create(nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&host));
|
||||
if (FAILED(hr) || !host) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "D3D12CreateDevice hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "host_device_failed", detail);
|
||||
return FAILED(hr) ? hr : E_FAIL;
|
||||
}
|
||||
HRESULT hr = create(nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&host));
|
||||
if (FAILED(hr) || !host) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "D3D12CreateDevice hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "host_device_failed", detail);
|
||||
return FAILED(hr) ? hr : E_FAIL;
|
||||
}
|
||||
|
||||
BxDeviceProxy* proxy = BxDeviceProxy::create(host);
|
||||
@@ -81,10 +66,6 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
if (!proxy) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
if (!bx_vmem_install_device_hooks(proxy)) {
|
||||
proxy->Release();
|
||||
return E_FAIL;
|
||||
}
|
||||
|
||||
/* Record how far up the ID3D12DeviceN chain the host goes: QueryInterface on the proxy stops there. */
|
||||
int highest = 0;
|
||||
@@ -96,10 +77,10 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
for (int i = 0; i < 10; ++i) {
|
||||
if (levels[i]) highest = i + 1;
|
||||
}
|
||||
char detail[256];
|
||||
char detail[192];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"host_device=%p highest_host_interface=ID3D12Device%d feature_level=11_0 params=%s (not interpreted) trace_d3d=%u",
|
||||
static_cast<void*>(proxy->h_ID3D12Device), highest, params ? "non-null" : "null", g_bx_trace_d3d);
|
||||
"host device wrapped; highest_host_interface=ID3D12Device%d feature_level=11_0 params=%s (not interpreted) trace_d3d=%u",
|
||||
highest, params ? "non-null" : "null", g_bx_trace_d3d);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "D3D12XboxCreateDevice", detail);
|
||||
|
||||
hr = proxy->QueryInterface(riid, ppv);
|
||||
@@ -107,8 +88,10 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT WINAPI D3D12ConfigureVirtualMemoryX(PVOID config) {
|
||||
return bx_d3d12_configure_virtual_memory(config);
|
||||
/* Logged no-op: console startup sequences check SUCCEEDED(hr) before reserving virtual memory. */
|
||||
HRESULT WINAPI D3D12ConfigureVirtualMemoryX(PVOID /*config*/) {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI D3D12SerializeVersionedRootSignature(
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
#include "proxy.h"
|
||||
#include "vmem.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
|
||||
#include "shader_gate.h"
|
||||
|
||||
/* {6B1D5C0E-2F4A-4E0B-9A57-3C0E5D7B1A42}: private to this DLL, never handed to a host object. */
|
||||
const GUID IID_BxProxyHost = {0x6b1d5c0e, 0x2f4a, 0x4e0b, {0x9a, 0x57, 0x3c, 0x0e, 0x5d, 0x7b, 0x1a, 0x42}};
|
||||
|
||||
@@ -135,11 +132,9 @@ bool log_shader(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTE
|
||||
well_formed = false;
|
||||
break;
|
||||
}
|
||||
/* ACCC counts too: the shader format gate (#466) decides what happens to it. */
|
||||
if (std::memcmp(bytes + off, "DXIL", 4) == 0 ||
|
||||
std::memcmp(bytes + off, "SHEX", 4) == 0 ||
|
||||
std::memcmp(bytes + off, "SHDR", 4) == 0 ||
|
||||
std::memcmp(bytes + off, "ACCC", 4) == 0) {
|
||||
std::memcmp(bytes + off, "SHDR", 4) == 0) {
|
||||
has_shader_chunk = true;
|
||||
}
|
||||
if (i < 16) {
|
||||
@@ -204,43 +199,13 @@ ULONG STDMETHODCALLTYPE BxDeviceProxy::AddRef() {
|
||||
return refs_.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
}
|
||||
|
||||
bool BxDeviceProxy::bx_try_acquire_if_nonzero() {
|
||||
ULONG cur = refs_.load(std::memory_order_acquire);
|
||||
while (cur != 0) {
|
||||
if (refs_.compare_exchange_weak(cur, cur + 1, std::memory_order_acq_rel, std::memory_order_acquire)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool BxDeviceProxy::bx_try_release_last() {
|
||||
ULONG expected = 1;
|
||||
return refs_.compare_exchange_strong(expected, 0, std::memory_order_acq_rel, std::memory_order_acquire);
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE BxDeviceProxy::Release() {
|
||||
/* The 1->0 transition and a weak GetDevice acquire share g_section.
|
||||
GetDevice adds a reference only when the count is non-zero, so a proxy
|
||||
at zero is never brought back. Exactly one Release performs final cleanup. */
|
||||
ULONG cur = refs_.load(std::memory_order_acquire);
|
||||
for (;;) {
|
||||
if (cur == 0) {
|
||||
return 0;
|
||||
}
|
||||
if (cur > 1) {
|
||||
if (refs_.compare_exchange_weak(cur, cur - 1, std::memory_order_acq_rel, std::memory_order_acquire)) {
|
||||
return cur - 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (bx_vmem_final_release(this)) {
|
||||
bx_release_hosts();
|
||||
delete this;
|
||||
return 0;
|
||||
}
|
||||
cur = refs_.load(std::memory_order_acquire);
|
||||
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (left == 0) {
|
||||
bx_release_hosts();
|
||||
delete this;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
HRESULT BxDeviceProxy::wrap_child(IUnknown* host_child, const char* what, REFIID riid, void** ppv) {
|
||||
@@ -380,25 +345,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreateGraphicsPipelineState(const D3D12
|
||||
log_created("graphics pipeline state", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (!desc) {
|
||||
HRESULT hr = h_ID3D12Device->CreateGraphicsPipelineState(desc, riid, ppv);
|
||||
log_created("graphics pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
/* M2 shader format gate (#466): every stage is classified; an ACCC-only stage fails the PSO. */
|
||||
BxShaderGate gate;
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC admitted = *desc;
|
||||
HRESULT gated = gate.admit("graphics", "VS", desc->VS, admitted.VS);
|
||||
if (SUCCEEDED(gated)) gated = gate.admit("graphics", "PS", desc->PS, admitted.PS);
|
||||
if (SUCCEEDED(gated)) gated = gate.admit("graphics", "DS", desc->DS, admitted.DS);
|
||||
if (SUCCEEDED(gated)) gated = gate.admit("graphics", "HS", desc->HS, admitted.HS);
|
||||
if (SUCCEEDED(gated)) gated = gate.admit("graphics", "GS", desc->GS, admitted.GS);
|
||||
if (FAILED(gated)) {
|
||||
if (ppv) *ppv = nullptr;
|
||||
log_created("graphics pipeline state", gated);
|
||||
return gated;
|
||||
}
|
||||
HRESULT hr = h_ID3D12Device->CreateGraphicsPipelineState(&admitted, riid, ppv);
|
||||
HRESULT hr = h_ID3D12Device->CreateGraphicsPipelineState(desc, riid, ppv);
|
||||
log_created("graphics pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
@@ -410,21 +357,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreateComputePipelineState(const D3D12_
|
||||
log_created("compute pipeline state", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (!desc) {
|
||||
HRESULT hr = h_ID3D12Device->CreateComputePipelineState(desc, riid, ppv);
|
||||
log_created("compute pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
/* M2 shader format gate (#466): DXIL is passed on, an ACCC-only container is refused. */
|
||||
BxShaderGate gate;
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC admitted = *desc;
|
||||
const HRESULT gated = gate.admit("compute", "CS", desc->CS, admitted.CS);
|
||||
if (FAILED(gated)) {
|
||||
if (ppv) *ppv = nullptr;
|
||||
log_created("compute pipeline state", gated);
|
||||
return gated;
|
||||
}
|
||||
HRESULT hr = h_ID3D12Device->CreateComputePipelineState(&admitted, riid, ppv);
|
||||
HRESULT hr = h_ID3D12Device->CreateComputePipelineState(desc, riid, ppv);
|
||||
log_created("compute pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
@@ -53,12 +53,6 @@ public:
|
||||
ULONG STDMETHODCALLTYPE AddRef() override;
|
||||
ULONG STDMETHODCALLTYPE Release() override;
|
||||
|
||||
/* Compare-exchange increment. False when the count is already zero.
|
||||
Weak GetDevice calls this under g_section so a proxy at zero is never resurrected. */
|
||||
bool bx_try_acquire_if_nonzero();
|
||||
/* Compare-exchange 1 to 0. Caller holds g_section. True only for the thread that wins. */
|
||||
bool bx_try_release_last();
|
||||
|
||||
HRESULT STDMETHODCALLTYPE CreateCommandQueue(const D3D12_COMMAND_QUEUE_DESC* desc, REFIID riid, void** ppv) override;
|
||||
HRESULT STDMETHODCALLTYPE CreateCommandQueue1(const D3D12_COMMAND_QUEUE_DESC* desc, REFIID creator_id, REFIID riid, void** ppv) override;
|
||||
HRESULT STDMETHODCALLTYPE CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void** ppv) override;
|
||||
|
||||
@@ -175,7 +175,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateHeap(const D3D12_HEAP_DESC * a
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreatePlacedResource(ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6) {
|
||||
BX_D3D_TRACE("ID3D12Device", "CreatePlacedResource");
|
||||
if (!h_ID3D12Device) { BX_VTABLE_STUB_LOG("ID3D12Device", 29u, "CreatePlacedResource"); return E_NOTIMPL; }
|
||||
return h_ID3D12Device->CreatePlacedResource(bx_unwrap(a0), a1, a2, a3, a4, a5, a6);
|
||||
return h_ID3D12Device->CreatePlacedResource(a0, a1, a2, a3, a4, a5, a6);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateReservedResource(const D3D12_RESOURCE_DESC * a0, D3D12_RESOURCE_STATES a1, const D3D12_CLEAR_VALUE * a2, REFIID a3, void ** a4) {
|
||||
@@ -385,7 +385,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateCommittedResource2(const D3D12
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreatePlacedResource1(ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6) {
|
||||
BX_D3D_TRACE("ID3D12Device8", "CreatePlacedResource1");
|
||||
if (!h_ID3D12Device8) { BX_VTABLE_STUB_LOG("ID3D12Device8", 70u, "CreatePlacedResource1"); return E_NOTIMPL; }
|
||||
return h_ID3D12Device8->CreatePlacedResource1(bx_unwrap(a0), a1, a2, a3, a4, a5, a6);
|
||||
return h_ID3D12Device8->CreatePlacedResource1(a0, a1, a2, a3, a4, a5, a6);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE BxDeviceProxyGen::CreateSamplerFeedbackUnorderedAccessView(ID3D12Resource * a0, ID3D12Resource * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
|
||||
@@ -421,7 +421,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateCommittedResource3(const D3D12
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreatePlacedResource2(ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_BARRIER_LAYOUT a3, const D3D12_CLEAR_VALUE * a4, UINT32 a5, DXGI_FORMAT * a6, REFIID a7, void ** a8) {
|
||||
BX_D3D_TRACE("ID3D12Device10", "CreatePlacedResource2");
|
||||
if (!h_ID3D12Device10) { BX_VTABLE_STUB_LOG("ID3D12Device10", 77u, "CreatePlacedResource2"); return E_NOTIMPL; }
|
||||
return h_ID3D12Device10->CreatePlacedResource2(bx_unwrap(a0), a1, a2, a3, a4, a5, a6, a7, a8);
|
||||
return h_ID3D12Device10->CreatePlacedResource2(a0, a1, a2, a3, a4, a5, a6, a7, a8);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateReservedResource2(const D3D12_RESOURCE_DESC * a0, D3D12_BARRIER_LAYOUT a1, const D3D12_CLEAR_VALUE * a2, ID3D12ProtectedResourceSession * a3, UINT32 a4, DXGI_FORMAT * a5, REFIID a6, void ** a7) {
|
||||
@@ -634,7 +634,7 @@ HRESULT STDMETHODCALLTYPE BxCommandQueueProxyGen::SetName(const WCHAR * a0) {
|
||||
void STDMETHODCALLTYPE BxCommandQueueProxyGen::UpdateTileMappings(ID3D12Resource * a0, UINT a1, const D3D12_TILED_RESOURCE_COORDINATE * a2, const D3D12_TILE_REGION_SIZE * a3, ID3D12Heap * a4, UINT a5, const D3D12_TILE_RANGE_FLAGS * a6, const UINT * a7, const UINT * a8, D3D12_TILE_MAPPING_FLAGS a9) {
|
||||
BX_D3D_TRACE("ID3D12CommandQueue", "UpdateTileMappings");
|
||||
if (!h_ID3D12CommandQueue) { BX_VTABLE_STUB_LOG("ID3D12CommandQueue", 8u, "UpdateTileMappings"); return; }
|
||||
h_ID3D12CommandQueue->UpdateTileMappings(a0, a1, a2, a3, bx_unwrap(a4), a5, a6, a7, a8, a9);
|
||||
h_ID3D12CommandQueue->UpdateTileMappings(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE BxCommandQueueProxyGen::CopyTileMappings(ID3D12Resource * a0, const D3D12_TILED_RESOURCE_COORDINATE * a1, ID3D12Resource * a2, const D3D12_TILED_RESOURCE_COORDINATE * a3, const D3D12_TILE_REGION_SIZE * a4, D3D12_TILE_MAPPING_FLAGS a5) {
|
||||
|
||||
@@ -1,274 +0,0 @@
|
||||
#include "shader_gate.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <iterator>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_shader_bridge.h"
|
||||
|
||||
/*
|
||||
* The bridge is loaded on first use, only by full path from this DLL's own directory, where
|
||||
* build-shims.sh stages it with the shims (#484). A bare-name load would search the guest EXE's
|
||||
* directory and PATH first and could pick up a different copy. It is optional at load time, so a
|
||||
* missing bridge is a logged condition rather than a failure to load d3d12_xs.dll. Without it,
|
||||
* shaders are not classified, but a container that has an ACCC chunk and no DXIL chunk is still
|
||||
* refused, from a bounds-checked chunk scan, so it never reaches the host device.
|
||||
*
|
||||
* Constraint flags come from two public DXIL container parts, read here with bounds checks:
|
||||
* - SFI0 is one uint64 of feature flags (DXC DxilContainer.h, DxilShaderFeatureInfo). The bit
|
||||
* values are D3D_SHADER_FEATURE_* from the public DirectX-Headers d3dcommon.h (MIT):
|
||||
* WAVE_OPS 0x4000, INT64_OPS 0x8000, ATOMIC_INT64_ON_TYPED_RESOURCE 0x400000,
|
||||
* ATOMIC_INT64_ON_GROUP_SHARED 0x800000, ATOMIC_INT64_ON_DESCRIPTOR_HEAP_RESOURCE 0x10000000.
|
||||
* - PSV0 starts with a uint32 PSVRuntimeInfo size, then PSVRuntimeInfo0, whose 16-byte stage
|
||||
* union is followed by MinimumExpectedWaveLaneCount and MaximumExpectedWaveLaneCount (DXC
|
||||
* DxilPipelineStateValidation.h). DXC 1.9.2609 writes 64/64 there for [WaveSize(64)] and
|
||||
* 0/0xFFFFFFFF without it (checked on the #453 blobs).
|
||||
* 64-bit atomics on raw buffers set only INT64_OPS, so they cannot be told apart from other
|
||||
* 64-bit integer use here; see ADR 0008.
|
||||
*/
|
||||
|
||||
namespace {
|
||||
|
||||
using InspectFn = bx_shader_status_t (*)(const uint8_t*, size_t, bx_shader_inspection_t*);
|
||||
using PrepareFn = bx_shader_status_t (*)(const uint8_t*, size_t, uint8_t**, size_t*);
|
||||
using FreeFn = void (*)(uint8_t*, size_t);
|
||||
|
||||
struct Bridge {
|
||||
InspectFn inspect = nullptr;
|
||||
PrepareFn prepare = nullptr;
|
||||
FreeFn release = nullptr;
|
||||
};
|
||||
|
||||
Bridge g_bridge;
|
||||
INIT_ONCE g_bridge_once = INIT_ONCE_STATIC_INIT;
|
||||
|
||||
template <typename Fn>
|
||||
Fn proc(HMODULE module, const char* name) {
|
||||
return reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(module, name)));
|
||||
}
|
||||
|
||||
BOOL CALLBACK load_bridge(PINIT_ONCE, PVOID, PVOID*) {
|
||||
HMODULE self = nullptr;
|
||||
HMODULE module = nullptr;
|
||||
wchar_t path[MAX_PATH];
|
||||
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
reinterpret_cast<LPCWSTR>(&load_bridge), &self)) {
|
||||
const DWORD length = GetModuleFileNameW(self, path, MAX_PATH);
|
||||
wchar_t* slash = length && length < MAX_PATH ? std::wcsrchr(path, L'\\') : nullptr;
|
||||
constexpr wchar_t kName[] = L"bx_shader_bridge.dll";
|
||||
if (slash && static_cast<size_t>(slash + 1 - path) + std::size(kName) <= MAX_PATH) {
|
||||
std::memcpy(slash + 1, kName, sizeof(kName));
|
||||
module = LoadLibraryExW(path, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
|
||||
}
|
||||
}
|
||||
if (module) {
|
||||
g_bridge.inspect = proc<InspectFn>(module, "bx_shader_inspect");
|
||||
g_bridge.prepare = proc<PrepareFn>(module, "bx_shader_prepare_for_d3dmetal");
|
||||
g_bridge.release = proc<FreeFn>(module, "bx_shader_free_buffer");
|
||||
}
|
||||
if (!g_bridge.inspect || !g_bridge.prepare || !g_bridge.release) {
|
||||
g_bridge = {};
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "shader_bridge_missing",
|
||||
module ? "bx_shader_bridge.dll lacks an entry point; shaders pass unclassified, ACCC-only refused"
|
||||
: "bx_shader_bridge.dll not found beside d3d12_xs.dll; shaders pass unclassified, "
|
||||
"ACCC-only refused");
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
const Bridge* bridge() {
|
||||
InitOnceExecuteOnce(&g_bridge_once, load_bridge, nullptr, nullptr);
|
||||
return g_bridge.inspect ? &g_bridge : nullptr;
|
||||
}
|
||||
|
||||
uint32_t read_u32(const uint8_t* at) {
|
||||
uint32_t value;
|
||||
std::memcpy(&value, at, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
|
||||
/* The payload of the first chunk named `fourcc`, or null. Every read is bounds-checked, so this
|
||||
* is safe on a container nobody has validated (the no-bridge path relies on that). */
|
||||
const uint8_t* find_chunk(const uint8_t* bytes, size_t len, const char* fourcc, uint32_t* size) {
|
||||
if (len < 32) return nullptr;
|
||||
const uint32_t count = read_u32(bytes + 28);
|
||||
for (uint32_t i = 0; i < count && 32 + 4 * static_cast<size_t>(i) + 4 <= len; ++i) {
|
||||
const uint32_t offset = read_u32(bytes + 32 + 4 * static_cast<size_t>(i));
|
||||
if (offset > len || len - offset < 8) continue;
|
||||
if (std::memcmp(bytes + offset, fourcc, 4) != 0) continue;
|
||||
const uint32_t chunk = read_u32(bytes + offset + 4);
|
||||
if (chunk > len - offset - 8) return nullptr;
|
||||
*size = chunk;
|
||||
return bytes + offset + 8;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* True when any chunk header in the table is tagged `fourcc`, whatever its declared size. */
|
||||
bool has_chunk_tag(const uint8_t* bytes, size_t len, const char* fourcc) {
|
||||
if (len < 32) return false;
|
||||
const uint32_t count = read_u32(bytes + 28);
|
||||
for (uint32_t i = 0; i < count && 32 + 4 * static_cast<size_t>(i) + 4 <= len; ++i) {
|
||||
const uint32_t offset = read_u32(bytes + 32 + 4 * static_cast<size_t>(i));
|
||||
if (offset <= len && len - offset >= 4 && std::memcmp(bytes + offset, fourcc, 4) == 0) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
struct Constraints {
|
||||
bool has_flags = false;
|
||||
uint64_t flags = 0;
|
||||
bool has_lanes = false;
|
||||
uint32_t lanes_min = 0;
|
||||
uint32_t lanes_max = 0;
|
||||
};
|
||||
|
||||
Constraints read_constraints(const uint8_t* bytes, size_t len) {
|
||||
Constraints c;
|
||||
uint32_t size = 0;
|
||||
if (const uint8_t* sfi0 = find_chunk(bytes, len, "SFI0", &size); sfi0 && size >= 8) {
|
||||
std::memcpy(&c.flags, sfi0, sizeof(c.flags));
|
||||
c.has_flags = true;
|
||||
}
|
||||
if (const uint8_t* psv0 = find_chunk(bytes, len, "PSV0", &size); psv0 && size >= 4) {
|
||||
const uint32_t info_size = read_u32(psv0);
|
||||
if (info_size >= 24 && size >= 4u + 24u) {
|
||||
c.lanes_min = read_u32(psv0 + 4 + 16);
|
||||
c.lanes_max = read_u32(psv0 + 4 + 20);
|
||||
c.has_lanes = true;
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
constexpr uint64_t kWaveOps = 0x4000;
|
||||
constexpr uint64_t kInt64Ops = 0x8000;
|
||||
constexpr uint64_t kAtomic64Typed = 0x400000;
|
||||
constexpr uint64_t kAtomic64GroupShared = 0x800000;
|
||||
constexpr uint64_t kAtomic64Heap = 0x10000000;
|
||||
|
||||
/* Measured on D3DMetal (docs/research/d3dmetal-gpu-limits.md): pipelines that require a wave
|
||||
* wider than 32 lanes, or 64-bit atomics, are created but never run. */
|
||||
bool known_d3dmetal_gap(const Constraints& c) {
|
||||
const bool wide_wave = c.has_lanes && c.lanes_min > 32;
|
||||
return wide_wave || (c.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap));
|
||||
}
|
||||
|
||||
const char* kind_name(bx_shader_kind_t kind) {
|
||||
switch (kind) {
|
||||
case BX_SHADER_DXBC_DXIL: return "dxil";
|
||||
case BX_SHADER_DXBC_LEGACY: return "legacy_dxbc";
|
||||
case BX_SHADER_DXBC_ACCC: return "accc_only";
|
||||
case BX_SHADER_DXBC_DUAL: return "dual";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
void log_gate(const char* pso_kind, const char* stage, size_t len, const bx_shader_inspection_t* info,
|
||||
const Constraints* c, const char* decision, HRESULT hr) {
|
||||
char lanes[32] = "none";
|
||||
if (c && c->has_lanes) {
|
||||
std::snprintf(lanes, sizeof(lanes), "%lu-%lu", static_cast<unsigned long>(c->lanes_min),
|
||||
static_cast<unsigned long>(c->lanes_max));
|
||||
}
|
||||
char detail[400];
|
||||
if (info) {
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"pso=%s stage=%s decision=%s hr=0x%08lx kind=%s shader_stage=%d sm=%lu.%lu bytes=%llu "
|
||||
"dxil=%lu accc=%lu sfi0=0x%llx wave_ops=%d int64_ops=%d atomic64=%s%s%s wave_lanes=%s",
|
||||
pso_kind, stage, decision, static_cast<unsigned long>(hr), kind_name(info->kind),
|
||||
static_cast<int>(info->stage), static_cast<unsigned long>(info->shader_model_major),
|
||||
static_cast<unsigned long>(info->shader_model_minor), static_cast<unsigned long long>(len),
|
||||
static_cast<unsigned long>(info->dxil_chunk_size),
|
||||
static_cast<unsigned long>(info->accc_chunk_size),
|
||||
static_cast<unsigned long long>(c ? c->flags : 0), c && (c->flags & kWaveOps) ? 1 : 0,
|
||||
c && (c->flags & kInt64Ops) ? 1 : 0,
|
||||
c && (c->flags & kAtomic64Typed) ? "typed," : "",
|
||||
c && (c->flags & kAtomic64GroupShared) ? "groupshared," : "",
|
||||
c && (c->flags & kAtomic64Heap) ? "heap," : "", lanes);
|
||||
} else {
|
||||
std::snprintf(detail, sizeof(detail), "pso=%s stage=%s decision=%s hr=0x%08lx bytes=%llu", pso_kind, stage,
|
||||
decision, static_cast<unsigned long>(hr), static_cast<unsigned long long>(len));
|
||||
}
|
||||
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "shader_gate", detail);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
BxShaderGate::~BxShaderGate() {
|
||||
const Bridge* b = copy_count_ ? bridge() : nullptr;
|
||||
for (size_t i = 0; i < copy_count_; ++i) {
|
||||
if (b) b->release(copies_[i], copy_sizes_[i]);
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT BxShaderGate::admit(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTECODE& in,
|
||||
D3D12_SHADER_BYTECODE& out) {
|
||||
out = in;
|
||||
if (!in.pShaderBytecode || in.BytecodeLength == 0) return S_OK;
|
||||
const auto* bytes = static_cast<const uint8_t*>(in.pShaderBytecode);
|
||||
const size_t len = in.BytecodeLength;
|
||||
|
||||
const Bridge* b = bridge();
|
||||
if (!b) {
|
||||
/* No classifier: still keep ACCC-only containers away from the host (#478 review). */
|
||||
/* Any ACCC tag counts; only a DXIL chunk that fits counts as DXIL, so doubt refuses. */
|
||||
uint32_t size = 0;
|
||||
const bool dxbc = len >= 4 && std::memcmp(bytes, "DXBC", 4) == 0;
|
||||
if (dxbc && has_chunk_tag(bytes, len, "ACCC") && !find_chunk(bytes, len, "DXIL", &size)) {
|
||||
log_gate(pso_kind, stage, len, nullptr, nullptr, "reject_accc_only_unclassified", E_NOTIMPL);
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
log_gate(pso_kind, stage, len, nullptr, nullptr, "pass_unclassified", S_OK);
|
||||
return S_OK;
|
||||
}
|
||||
bx_shader_inspection_t info{};
|
||||
if (b->inspect(bytes, len, &info) != BX_SHADER_OK) {
|
||||
/* Not a container the bridge understands; the host keeps its own validation. */
|
||||
log_gate(pso_kind, stage, len, nullptr, nullptr, "pass_uninspected", S_OK);
|
||||
return S_OK;
|
||||
}
|
||||
const Constraints constraints = read_constraints(bytes, len);
|
||||
switch (info.kind) {
|
||||
case BX_SHADER_DXBC_ACCC:
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "reject_accc_only", E_NOTIMPL);
|
||||
return E_NOTIMPL;
|
||||
case BX_SHADER_DXBC_DXIL:
|
||||
case BX_SHADER_DXBC_DUAL: {
|
||||
if (copy_count_ == kMaxCopies) {
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "copy_limit", E_UNEXPECTED);
|
||||
return E_UNEXPECTED;
|
||||
}
|
||||
uint8_t* copy = nullptr;
|
||||
size_t copy_len = 0;
|
||||
const bx_shader_status_t status = b->prepare(bytes, len, ©, ©_len);
|
||||
if (status != BX_SHADER_OK) {
|
||||
const HRESULT hr = status == BX_SHADER_ERR_OOM ? E_OUTOFMEMORY : E_INVALIDARG;
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "prepare_failed", hr);
|
||||
return hr;
|
||||
}
|
||||
copies_[copy_count_] = copy;
|
||||
copy_sizes_[copy_count_] = copy_len;
|
||||
++copy_count_;
|
||||
out.pShaderBytecode = copy;
|
||||
out.BytecodeLength = copy_len;
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "pass_dxil", S_OK);
|
||||
if (known_d3dmetal_gap(constraints)) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"pso=%s stage=%s wave_lanes_min=%lu atomic64_flags=0x%llx: D3DMetal creates such "
|
||||
"pipelines but does not run them (#453)",
|
||||
pso_kind, stage, static_cast<unsigned long>(constraints.lanes_min),
|
||||
static_cast<unsigned long long>(
|
||||
constraints.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap)));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "shader_d3dmetal_gap", detail);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
default:
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "pass_original", S_OK);
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
* M2 Shader Format Gate (#466): classifies every shader handed to Create*PipelineState through
|
||||
* bx_shader_bridge.dll (abi/include/bx_shader_bridge.h, the Windows build of dxbc-accc, #445)
|
||||
* and decides what the host device receives. See docs/adr/0008-m2-shader-format-gate.md.
|
||||
*/
|
||||
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
class BxShaderGate {
|
||||
public:
|
||||
BxShaderGate() = default;
|
||||
~BxShaderGate();
|
||||
BxShaderGate(const BxShaderGate&) = delete;
|
||||
BxShaderGate& operator=(const BxShaderGate&) = delete;
|
||||
|
||||
/*
|
||||
* Logs one stage's classification (`shader_gate` event) and sets `out` to the bytecode the
|
||||
* host gets: the bridge's prepared DXIL copy for DXIL and dual containers, or `in` unchanged
|
||||
* for legacy DXBC, unclassifiable input, or when the bridge is missing (logged once as
|
||||
* `shader_bridge_missing`). Returns E_NOTIMPL for an ACCC-only container, which has no
|
||||
* DXIL for D3DMetal until M3 Branch D2, with or without the bridge. Copies live until this
|
||||
* object is destroyed.
|
||||
*/
|
||||
HRESULT admit(const char* pso_kind, const char* stage, const D3D12_SHADER_BYTECODE& in,
|
||||
D3D12_SHADER_BYTECODE& out);
|
||||
|
||||
private:
|
||||
static constexpr size_t kMaxCopies = 5; /* VS, PS, DS, HS, GS */
|
||||
uint8_t* copies_[kMaxCopies] = {};
|
||||
size_t copy_sizes_[kMaxCopies] = {};
|
||||
size_t copy_count_ = 0;
|
||||
};
|
||||
@@ -44,11 +44,8 @@ PROXIES = {
|
||||
# Interfaces that carry no host pointer of their own: their methods forward through the root level.
|
||||
ABSTRACT = {"IUnknown", "ID3D12Object", "ID3D12DeviceChild", "ID3D12Pageable", "ID3D12CommandList"}
|
||||
# A single-pointer parameter of one of these types may be one of our proxies and is unwrapped.
|
||||
# ID3D12Heap covers CreatePlacedResource, CreatePlacedResource1 and CreatePlacedResource2.
|
||||
# A wrapped heap passed straight through faults in the host (0xc0000005 on D3DMetal).
|
||||
MAYBE_PROXY = {"ID3D12CommandQueue", "ID3D12CommandAllocator", "ID3D12CommandList",
|
||||
"ID3D12GraphicsCommandList", "ID3D12Pageable", "ID3D12DeviceChild", "ID3D12Object",
|
||||
"ID3D12Heap", "ID3D12Heap1"}
|
||||
"ID3D12GraphicsCommandList", "ID3D12Pageable", "ID3D12DeviceChild", "ID3D12Object"}
|
||||
|
||||
IUNKNOWN = [
|
||||
("HRESULT", "QueryInterface", [("REFIID", ""), ("void **", "")]),
|
||||
|
||||
@@ -1,876 +0,0 @@
|
||||
#include "proxy.h"
|
||||
#include "vmem.h"
|
||||
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
|
||||
/*
|
||||
* The configured region is backed by one CUSTOM WRITE_BACK / L0 heap and a buffer
|
||||
* that stays mapped. That heap is created with D3D12_HEAP_FLAG_NONE, 64 KiB
|
||||
* alignment, and node masks 0. CreateHeap returns it only for the explicit
|
||||
* opt-in desc documented in vmem.h. In #473, CPU and GPU reads agreed after
|
||||
* a fence on tested L0 heaps. Both OpenExistingHeap methods returned E_NOTIMPL.
|
||||
* This file does not request L1 and does not treat an xmem address as a GPU pointer.
|
||||
*
|
||||
* Any other CreateHeap forwards the caller's D3D12_HEAP_DESC unmodified.
|
||||
* The wrapper charges the heap on create and credits it on final Release.
|
||||
* Resources created by CreatePlacedResource retain the wrapper.
|
||||
* GetDevice on every wrapper returns the BxDeviceProxy. An ordinary heap AddRefs
|
||||
* that proxy and Releases it after the wrapper is destroyed, matching
|
||||
* BxChildProxy, so the caller may release the device and keep the heap.
|
||||
* The cached backing heap does not AddRef: this record would keep the device
|
||||
* and its budget charge alive. That pointer is weak. It is cleared when the
|
||||
* proxy is destroyed and set to the proxy that next receives the cached heap.
|
||||
* The cache is keyed by the host ID3D12Device and is released when that device
|
||||
* changes.
|
||||
* A null out pointer is forwarded unchanged to the host.
|
||||
* vkd3d on CrossOver 26.2 faults on that pointer with or without this shim.
|
||||
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createheap
|
||||
*
|
||||
* CreatePlacedResource forwards the caller's parameters to the host.
|
||||
* On the backing heap the offset must be a multiple of the alignment
|
||||
* GetResourceAllocationInfo reports, the resource
|
||||
* must fit, and an upload or readback heap (not this CUSTOM heap) must use the
|
||||
* initial state Microsoft Learn requires:
|
||||
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource
|
||||
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getresourceallocationinfo
|
||||
* Heap alignment values 0, 64 KiB and 4 MiB, and ID3D12Heap1:
|
||||
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_heap_desc
|
||||
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12heap1
|
||||
* Non-custom heap properties use UNKNOWN CPU page and memory pool:
|
||||
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_heap_properties
|
||||
*/
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint64_t k64K = 64ull * 1024ull;
|
||||
constexpr uint32_t kConfigVersion = 1;
|
||||
constexpr GUID kPlacedResourceHeap = {0x3a652cbb, 0xb5b3, 0x4e09, {0xb3, 0x6c, 0xc0, 0x2c, 0xa9, 0x83, 0xae, 0x1a}};
|
||||
|
||||
struct Record {
|
||||
bool configured = false;
|
||||
bool backing_opt_in = false;
|
||||
bx_hardware_profile_t profile = BX_PROFILE_LOCKHART;
|
||||
uint64_t title_limit = 0;
|
||||
bool have_region = false;
|
||||
uint64_t config_base = 0;
|
||||
uint64_t config_size = 0;
|
||||
uint64_t config_generation = 0;
|
||||
bx_xmem_region_info_t region{};
|
||||
/* Bytes of host heaps still alive. D3DMetal keeps freed memory in its own
|
||||
pool, so this counts live heaps only: charge on create, credit on the
|
||||
final Release. It does not assume the OS reclaimed the pages. */
|
||||
uint64_t charged_private_bytes = 0;
|
||||
uint64_t cpu_pointer = 0;
|
||||
class BxChargedHeap* backing = nullptr;
|
||||
ID3D12Resource* backing_buffer = nullptr;
|
||||
/* Host device that created `backing`. Not an owning reference. A later
|
||||
CreateHeap whose host device pointer differs releases the cache. */
|
||||
ID3D12Device* backing_host = nullptr;
|
||||
};
|
||||
|
||||
struct Section {
|
||||
CRITICAL_SECTION cs;
|
||||
Section() { InitializeCriticalSection(&cs); }
|
||||
~Section() { DeleteCriticalSection(&cs); }
|
||||
};
|
||||
|
||||
Section g_section;
|
||||
Record g_record;
|
||||
|
||||
struct Guard {
|
||||
explicit Guard(Section& section) : section(section) { EnterCriticalSection(§ion.cs); }
|
||||
~Guard() { LeaveCriticalSection(§ion.cs); }
|
||||
Section& section;
|
||||
};
|
||||
|
||||
uint64_t title_limit() {
|
||||
const bx_runtime_config_t* cfg = bx_get_runtime_config();
|
||||
if (cfg && cfg->title_memory_limit_bytes) {
|
||||
return cfg->title_memory_limit_bytes;
|
||||
}
|
||||
/* Same 8 GiB Lockhart default bx_runtime_veh stores when no profile is set. */
|
||||
return 8ull << 30;
|
||||
}
|
||||
|
||||
uint64_t active_cap(const bx_xmem_stats_t& stats) {
|
||||
uint64_t cap = title_limit();
|
||||
if (stats.title_limit_bytes != 0 && stats.title_limit_bytes < cap) {
|
||||
cap = stats.title_limit_bytes;
|
||||
}
|
||||
return cap;
|
||||
}
|
||||
|
||||
const char* profile_name(bx_hardware_profile_t profile) {
|
||||
return profile == BX_PROFILE_ANACONDA ? "anaconda" : "lockhart";
|
||||
}
|
||||
|
||||
/* Private host heaps count against the same Lockhart/Anaconda cap as xmem. */
|
||||
bool try_charge(uint64_t bytes) {
|
||||
Guard guard(g_section);
|
||||
bx_xmem_stats_t stats{};
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
const uint64_t cap = active_cap(stats);
|
||||
const uint64_t xmem_used = stats.committed_virtual_bytes + stats.allocated_physical_bytes;
|
||||
if (bytes > cap || xmem_used > cap || g_record.charged_private_bytes > cap - xmem_used) {
|
||||
return false;
|
||||
}
|
||||
const uint64_t room = cap - xmem_used - g_record.charged_private_bytes;
|
||||
if (bytes > room) {
|
||||
return false;
|
||||
}
|
||||
g_record.charged_private_bytes += bytes;
|
||||
return true;
|
||||
}
|
||||
|
||||
void release_charge(uint64_t bytes) {
|
||||
Guard guard(g_section);
|
||||
if (bytes > g_record.charged_private_bytes) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "heap_budget", "GPU heap charge underflow on release");
|
||||
g_record.charged_private_bytes = 0;
|
||||
return;
|
||||
}
|
||||
g_record.charged_private_bytes -= bytes;
|
||||
}
|
||||
|
||||
/*
|
||||
* Holds the budget charge for one private host heap and drops it on the last Release.
|
||||
* QueryInterface for ID3D12Heap, and for ID3D12Heap1 when the host heap answers it,
|
||||
* returns this object. bx_unwrap sees IID_BxProxyHost and receives the host heap.
|
||||
* GetProtectedResourceSession forwards to the host ID3D12Heap1.
|
||||
* GetDevice returns the BxDeviceProxy, matching BxChildProxy::GetDevice.
|
||||
* Ordinary heaps (`owns_device_`) AddRef the proxy in the constructor and
|
||||
* Release it after `delete this`, the same order as BxChildProxy::Release.
|
||||
* The process-wide backing heap does not. g_record holds that heap for the
|
||||
* life of the region, so a strong reference would pin the device and the
|
||||
* budget charge after the caller dropped the proxy. `device_` on that heap is
|
||||
* weak. It is cleared when the heap leaves the cache and when its proxy's
|
||||
* reference count goes from 1 to 0. hand_out_backing_locked points it at the
|
||||
* proxy that receives the cache. Those writes happen under g_section, together
|
||||
* with the 1->0 transition, so GetDevice cannot resurrect a proxy at zero.
|
||||
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12heap1
|
||||
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12devicechild-getdevice
|
||||
*/
|
||||
class BxChargedHeap final : public ID3D12Heap1 {
|
||||
public:
|
||||
static BxChargedHeap* create(ID3D12Heap* host, ID3D12Heap1* host1, uint64_t bytes, BxDeviceProxy* device,
|
||||
bool own_device) {
|
||||
return new (std::nothrow) BxChargedHeap(host, host1, bytes, device, own_device);
|
||||
}
|
||||
|
||||
/* Weak backing heap only. Called under g_section. */
|
||||
void set_device(BxDeviceProxy* device) {
|
||||
if (!owns_device_) {
|
||||
device_ = device;
|
||||
}
|
||||
}
|
||||
BxDeviceProxy* device() const { return device_; }
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) ||
|
||||
riid == __uuidof(ID3D12Pageable) || riid == __uuidof(ID3D12Heap)) {
|
||||
*ppv = static_cast<ID3D12Heap*>(this);
|
||||
AddRef();
|
||||
return S_OK;
|
||||
}
|
||||
if (riid == __uuidof(ID3D12Heap1)) {
|
||||
if (!host1_) {
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
*ppv = static_cast<ID3D12Heap1*>(this);
|
||||
AddRef();
|
||||
return S_OK;
|
||||
}
|
||||
if (riid == IID_BxProxyHost) {
|
||||
*ppv = host_;
|
||||
return S_OK;
|
||||
}
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE AddRef() override { return InterlockedIncrement(&refs_); }
|
||||
|
||||
ULONG STDMETHODCALLTYPE Release() override {
|
||||
const ULONG left = InterlockedDecrement(&refs_);
|
||||
if (left == 0) {
|
||||
/* Final Release of a live heap. D3DMetal may pool the pages after this,
|
||||
so the budget credit is the live-heap count, not a physical-memory drop. */
|
||||
if (host1_) {
|
||||
host1_->Release();
|
||||
}
|
||||
if (host_) {
|
||||
host_->Release();
|
||||
}
|
||||
release_charge(bytes_);
|
||||
/* Same order as BxChildProxy::Release: destroy the wrapper, then Release the device. */
|
||||
BxDeviceProxy* owned = owns_device_ ? device_ : nullptr;
|
||||
device_ = nullptr;
|
||||
delete this;
|
||||
if (owned) {
|
||||
owned->Release();
|
||||
}
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override {
|
||||
return host_->GetPrivateData(guid, size, data);
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override {
|
||||
return host_->SetPrivateData(guid, size, data);
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* data) override {
|
||||
return host_->SetPrivateDataInterface(guid, data);
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE SetName(LPCWSTR name) override { return host_->SetName(name); }
|
||||
HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** ppv) override {
|
||||
BX_D3D_TRACE("ID3D12DeviceChild", "GetDevice");
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
/* The proxy, never the host device.
|
||||
An ordinary heap owns its proxy and nothing else writes device_, so that
|
||||
path stays lock-free. The backing heap is weak. Its acquire and the
|
||||
proxy's 1->0 Release share g_section. The acquire is a compare-exchange
|
||||
that refuses zero, so it cannot resurrect a proxy that Release has
|
||||
already claimed. QueryInterface below adds one more reference from a
|
||||
non-zero count and does not enter g_section; the compare-exchange
|
||||
reference is then dropped. Guard's critical section is recursive, and
|
||||
this path does not re-enter it. */
|
||||
if (owns_device_) {
|
||||
if (!device_) {
|
||||
*ppv = nullptr;
|
||||
return E_FAIL;
|
||||
}
|
||||
return device_->QueryInterface(riid, ppv);
|
||||
}
|
||||
BxDeviceProxy* proxy = nullptr;
|
||||
{
|
||||
Guard guard(g_section);
|
||||
proxy = device_;
|
||||
if (!proxy || !proxy->bx_try_acquire_if_nonzero()) {
|
||||
*ppv = nullptr;
|
||||
return E_FAIL;
|
||||
}
|
||||
}
|
||||
/* The compare-exchange reference keeps the proxy alive. QueryInterface
|
||||
adds the caller's reference from a non-zero count, then the
|
||||
compare-exchange reference is dropped. Release is outside g_section
|
||||
so a 1->0 transition cannot try to take that lock on this thread. */
|
||||
const HRESULT hr = proxy->QueryInterface(riid, ppv);
|
||||
proxy->Release();
|
||||
return hr;
|
||||
}
|
||||
D3D12_HEAP_DESC* STDMETHODCALLTYPE GetDesc(D3D12_HEAP_DESC* ret) override { return host_->GetDesc(ret); }
|
||||
HRESULT STDMETHODCALLTYPE GetProtectedResourceSession(REFIID riid, void** session) override {
|
||||
if (!session) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*session = nullptr;
|
||||
if (!host1_) {
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
return host1_->GetProtectedResourceSession(riid, session);
|
||||
}
|
||||
|
||||
private:
|
||||
BxChargedHeap(ID3D12Heap* host, ID3D12Heap1* host1, uint64_t bytes, BxDeviceProxy* device, bool own_device)
|
||||
: host_(host), host1_(host1), bytes_(bytes), device_(device), owns_device_(own_device) {
|
||||
if (host_) {
|
||||
host_->AddRef();
|
||||
}
|
||||
if (host1_) {
|
||||
host1_->AddRef();
|
||||
}
|
||||
if (owns_device_ && device_) {
|
||||
device_->AddRef();
|
||||
}
|
||||
}
|
||||
~BxChargedHeap() = default;
|
||||
|
||||
ID3D12Heap* host_;
|
||||
ID3D12Heap1* host1_;
|
||||
uint64_t bytes_;
|
||||
BxDeviceProxy* device_;
|
||||
bool owns_device_; /* ordinary heap: strong, like BxChildProxy. Backing cache: weak. */
|
||||
LONG refs_ = 1;
|
||||
};
|
||||
|
||||
struct RegionSnap {
|
||||
bool eligible = false;
|
||||
uint64_t base = 0;
|
||||
uint64_t size = 0;
|
||||
uint64_t generation = 0;
|
||||
};
|
||||
|
||||
RegionSnap region_snap() {
|
||||
Guard guard(g_section);
|
||||
RegionSnap snap;
|
||||
snap.eligible = g_record.configured && g_record.backing_opt_in && g_record.have_region && g_record.config_size != 0;
|
||||
snap.base = g_record.region.base_va;
|
||||
snap.size = g_record.config_size;
|
||||
snap.generation = g_record.config_generation;
|
||||
return snap;
|
||||
}
|
||||
|
||||
bool region_still_mapped(const RegionSnap& snap) {
|
||||
if (!snap.eligible || snap.size == 0) {
|
||||
return false;
|
||||
}
|
||||
bx_xmem_region_info_t live{};
|
||||
if (!bx_xmem_query_region(snap.base, &live) || live.base_va != snap.base || live.size_bytes == 0 ||
|
||||
snap.size % live.size_bytes != 0) {
|
||||
return false;
|
||||
}
|
||||
const uint64_t page = live.size_bytes;
|
||||
for (uint64_t offset = 0; offset < snap.size; offset += page) {
|
||||
bx_xmem_region_info_t part{};
|
||||
if (!bx_xmem_query_region(snap.base + offset, &part) || part.base_va != snap.base + offset ||
|
||||
part.size_bytes != page) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* True only for the explicit backing-heap request documented in vmem.h. */
|
||||
bool backing_request(const D3D12_HEAP_DESC* desc, RegionSnap& snap) {
|
||||
if (!desc) {
|
||||
return false;
|
||||
}
|
||||
if (desc->Properties.Type != D3D12_HEAP_TYPE_CUSTOM ||
|
||||
desc->Properties.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_WRITE_BACK ||
|
||||
desc->Properties.MemoryPoolPreference != D3D12_MEMORY_POOL_L0) {
|
||||
return false;
|
||||
}
|
||||
if (desc->Alignment != 0 && desc->Alignment != k64K) {
|
||||
return false;
|
||||
}
|
||||
if (desc->Flags != D3D12_HEAP_FLAG_NONE) {
|
||||
return false;
|
||||
}
|
||||
if (desc->Properties.CreationNodeMask > 1 || desc->Properties.VisibleNodeMask > 1) {
|
||||
return false;
|
||||
}
|
||||
snap = region_snap();
|
||||
if (!snap.eligible || desc->SizeInBytes != snap.size) {
|
||||
return false;
|
||||
}
|
||||
return region_still_mapped(snap);
|
||||
}
|
||||
|
||||
HRESULT host_private_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFIID riid, void** out, bool own_device);
|
||||
|
||||
/* Test hook. One CreateHeap treats the cached host as foreign even when the
|
||||
runtime returns the same ID3D12Device, so the replacement path can be checked
|
||||
on a machine that keeps a single host device alive. */
|
||||
bool force_backing_replace() {
|
||||
char buf[8] = {};
|
||||
return GetEnvironmentVariableA("BX_D3D12_FORCE_BACKING_REPLACE", buf, sizeof(buf)) > 0 && buf[0] == '1' &&
|
||||
buf[1] == '\0';
|
||||
}
|
||||
|
||||
/* Caller holds g_section. */
|
||||
bool cache_matches_locked(ID3D12Device* host, uint64_t bytes) {
|
||||
if (force_backing_replace()) {
|
||||
return false;
|
||||
}
|
||||
return g_record.backing && g_record.backing_host == host && g_record.configured && g_record.backing_opt_in &&
|
||||
g_record.have_region && g_record.config_size == bytes;
|
||||
}
|
||||
|
||||
/* Caller holds g_section. A heap that leaves the cache loses its weak proxy
|
||||
pointer before the cache drops it, so a caller who still holds the heap
|
||||
gets E_FAIL from GetDevice instead of a freed proxy. */
|
||||
void take_cached_heap_locked(BxChargedHeap** heap, ID3D12Resource** buffer) {
|
||||
*heap = g_record.backing;
|
||||
*buffer = g_record.backing_buffer;
|
||||
if (*heap) {
|
||||
(*heap)->set_device(nullptr);
|
||||
}
|
||||
g_record.backing = nullptr;
|
||||
g_record.backing_buffer = nullptr;
|
||||
g_record.backing_host = nullptr;
|
||||
g_record.cpu_pointer = 0;
|
||||
}
|
||||
|
||||
/* Caller holds g_section. Host and size were just checked. Retarget and take
|
||||
the caller's reference before the lock is released. */
|
||||
HRESULT hand_out_backing_locked(BxDeviceProxy* self, REFIID riid, void** out) {
|
||||
g_record.backing->set_device(self);
|
||||
g_record.backing->AddRef();
|
||||
const HRESULT hr = g_record.backing->QueryInterface(riid, out);
|
||||
g_record.backing->Release();
|
||||
return hr;
|
||||
}
|
||||
|
||||
void release_backing_pair(BxChargedHeap* heap, ID3D12Resource* buffer) {
|
||||
if (buffer) {
|
||||
buffer->Unmap(0, nullptr);
|
||||
buffer->Release();
|
||||
}
|
||||
if (heap) {
|
||||
heap->Release();
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT ensure_backing(BxDeviceProxy* self, const RegionSnap& snap, REFIID riid, void** out) {
|
||||
const uint64_t bytes = snap.size;
|
||||
BxChargedHeap* stale_heap = nullptr;
|
||||
ID3D12Resource* stale_buffer = nullptr;
|
||||
{
|
||||
/* One section covers the host and config check, the heap choice, and the
|
||||
reference handed to the caller. A second device cannot swap the cache
|
||||
in the middle of that. */
|
||||
Guard guard(g_section);
|
||||
if (snap.generation != g_record.config_generation) {
|
||||
return HRESULT_FROM_WIN32(ERROR_RETRY);
|
||||
}
|
||||
if (cache_matches_locked(self->h_ID3D12Device, bytes)) {
|
||||
return hand_out_backing_locked(self, riid, out);
|
||||
}
|
||||
if (g_record.backing) {
|
||||
take_cached_heap_locked(&stale_heap, &stale_buffer);
|
||||
}
|
||||
}
|
||||
release_backing_pair(stale_heap, stale_buffer);
|
||||
stale_heap = nullptr;
|
||||
stale_buffer = nullptr;
|
||||
|
||||
D3D12_HEAP_DESC desc = {};
|
||||
desc.SizeInBytes = bytes;
|
||||
desc.Alignment = k64K;
|
||||
desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM;
|
||||
desc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
|
||||
desc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
desc.Flags = D3D12_HEAP_FLAG_NONE;
|
||||
void* created = nullptr;
|
||||
HRESULT hr = host_private_heap(self, &desc, __uuidof(ID3D12Heap), &created, false);
|
||||
if (FAILED(hr) || !created) {
|
||||
return FAILED(hr) ? hr : E_FAIL;
|
||||
}
|
||||
auto* wrap = static_cast<BxChargedHeap*>(created);
|
||||
ID3D12Heap* host_heap = bx_unwrap(wrap);
|
||||
|
||||
D3D12_RESOURCE_DESC buffer = {};
|
||||
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buffer.Width = bytes;
|
||||
buffer.Height = 1;
|
||||
buffer.DepthOrArraySize = 1;
|
||||
buffer.MipLevels = 1;
|
||||
buffer.Format = DXGI_FORMAT_UNKNOWN;
|
||||
buffer.SampleDesc.Count = 1;
|
||||
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
ID3D12Resource* resource = nullptr;
|
||||
hr = self->h_ID3D12Device->CreatePlacedResource(host_heap, 0, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
|
||||
if (FAILED(hr) || !resource) {
|
||||
wrap->Release();
|
||||
return FAILED(hr) ? hr : E_FAIL;
|
||||
}
|
||||
void* mapped = nullptr;
|
||||
hr = resource->Map(0, nullptr, &mapped);
|
||||
if (FAILED(hr) || !mapped) {
|
||||
resource->Release();
|
||||
wrap->Release();
|
||||
return FAILED(hr) ? hr : E_FAIL;
|
||||
}
|
||||
|
||||
HRESULT published = E_FAIL;
|
||||
bool keep_new = false;
|
||||
{
|
||||
/* The host allocation may have raced with a config change or another
|
||||
creator. Publish only for the configuration this request validated. */
|
||||
Guard guard(g_section);
|
||||
if (snap.generation != g_record.config_generation) {
|
||||
published = HRESULT_FROM_WIN32(ERROR_RETRY);
|
||||
} else if (cache_matches_locked(self->h_ID3D12Device, bytes)) {
|
||||
published = hand_out_backing_locked(self, riid, out);
|
||||
} else {
|
||||
if (g_record.backing) {
|
||||
take_cached_heap_locked(&stale_heap, &stale_buffer);
|
||||
}
|
||||
keep_new = true;
|
||||
g_record.backing = wrap;
|
||||
g_record.backing_buffer = resource;
|
||||
g_record.backing_host = self->h_ID3D12Device;
|
||||
/* Remember the map. The caller's config block is not stored and is not written here. */
|
||||
g_record.cpu_pointer = reinterpret_cast<uint64_t>(mapped);
|
||||
published = hand_out_backing_locked(self, riid, out);
|
||||
}
|
||||
}
|
||||
if (!keep_new) {
|
||||
release_backing_pair(wrap, resource);
|
||||
}
|
||||
release_backing_pair(stale_heap, stale_buffer);
|
||||
return published;
|
||||
}
|
||||
|
||||
HRESULT host_private_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFIID riid, void** out, bool own_device) {
|
||||
/* desc is forwarded unmodified. The charge follows the wrapper, including ID3D12Heap1. */
|
||||
if (!try_charge(desc->SizeInBytes)) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "heap_budget",
|
||||
"CreateHeap exceeds the Lockhart/Anaconda xmem title budget");
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
void* raw = nullptr;
|
||||
HRESULT hr = self->h_ID3D12Device->CreateHeap(desc, riid, &raw);
|
||||
if (FAILED(hr) || !raw) {
|
||||
release_charge(desc->SizeInBytes);
|
||||
return FAILED(hr) ? hr : E_FAIL;
|
||||
}
|
||||
auto* unknown = static_cast<IUnknown*>(raw);
|
||||
ID3D12Heap* host = nullptr;
|
||||
const HRESULT heap_hr = unknown->QueryInterface(__uuidof(ID3D12Heap), reinterpret_cast<void**>(&host));
|
||||
if (FAILED(heap_hr) || !host) {
|
||||
unknown->Release();
|
||||
release_charge(desc->SizeInBytes);
|
||||
return FAILED(heap_hr) ? heap_hr : E_NOINTERFACE;
|
||||
}
|
||||
ID3D12Heap1* host1 = nullptr;
|
||||
void* probed = nullptr;
|
||||
if (host->QueryInterface(__uuidof(ID3D12Heap1), &probed) == S_OK && probed) {
|
||||
host1 = static_cast<ID3D12Heap1*>(probed);
|
||||
}
|
||||
BxChargedHeap* wrap = BxChargedHeap::create(host, host1, desc->SizeInBytes, self, own_device);
|
||||
if (host1) {
|
||||
host1->Release();
|
||||
}
|
||||
host->Release();
|
||||
unknown->Release();
|
||||
if (!wrap) {
|
||||
release_charge(desc->SizeInBytes);
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
hr = wrap->QueryInterface(riid, out);
|
||||
wrap->Release();
|
||||
if (FAILED(hr) && out) {
|
||||
*out = nullptr;
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
bool is_backing_heap(ID3D12Heap* heap) {
|
||||
if (!heap) {
|
||||
return false;
|
||||
}
|
||||
BxChargedHeap* backing = nullptr;
|
||||
{
|
||||
Guard guard(g_section);
|
||||
backing = g_record.backing;
|
||||
if (!backing) {
|
||||
return false;
|
||||
}
|
||||
backing->AddRef();
|
||||
}
|
||||
IUnknown* want = nullptr;
|
||||
IUnknown* got = nullptr;
|
||||
const HRESULT want_hr = backing->QueryInterface(IID_IUnknown, reinterpret_cast<void**>(&want));
|
||||
const HRESULT got_hr = heap->QueryInterface(IID_IUnknown, reinterpret_cast<void**>(&got));
|
||||
const bool same = SUCCEEDED(want_hr) && SUCCEEDED(got_hr) && want == got;
|
||||
if (want) {
|
||||
want->Release();
|
||||
}
|
||||
if (got) {
|
||||
got->Release();
|
||||
}
|
||||
backing->Release();
|
||||
return same;
|
||||
}
|
||||
|
||||
void log_placed(UINT64 offset, HRESULT hr) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "CreatePlacedResource offset=%llu hr=0x%08lx",
|
||||
static_cast<unsigned long long>(offset), static_cast<unsigned long>(hr));
|
||||
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "placed_resource", detail);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE create_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFIID riid, void** out) {
|
||||
BX_D3D_TRACE("ID3D12Device", "CreateHeap");
|
||||
if (!self || !self->h_ID3D12Device) {
|
||||
if (out) {
|
||||
*out = nullptr;
|
||||
}
|
||||
BX_VTABLE_STUB_LOG("ID3D12Device", 28u, "CreateHeap");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
if (!desc) {
|
||||
if (out) {
|
||||
*out = nullptr;
|
||||
}
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (!out) {
|
||||
/* A null out pointer is forwarded unchanged to the host.
|
||||
* vkd3d on CrossOver 26.2 faults on that pointer with or without this shim.
|
||||
*/
|
||||
return self->h_ID3D12Device->CreateHeap(desc, riid, nullptr);
|
||||
}
|
||||
*out = nullptr;
|
||||
RegionSnap snap;
|
||||
if (backing_request(desc, snap)) {
|
||||
return ensure_backing(self, snap, riid, out);
|
||||
}
|
||||
return host_private_heap(self, desc, riid, out, true);
|
||||
}
|
||||
|
||||
HRESULT validate_backing_placement(ID3D12Device* device, ID3D12Heap* heap, UINT64 offset, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear) {
|
||||
if (!heap || !desc) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && clear) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
D3D12_HEAP_DESC heap_desc = heap->GetDesc();
|
||||
if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_UPLOAD && state != D3D12_RESOURCE_STATE_GENERIC_READ) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_READBACK && state != D3D12_RESOURCE_STATE_COPY_DEST) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, desc);
|
||||
if (info.SizeInBytes == 0 || info.SizeInBytes == ~0ull) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (info.Alignment != 0 && (offset % info.Alignment) != 0) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (offset > heap_desc.SizeInBytes || info.SizeInBytes > heap_desc.SizeInBytes - offset) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE create_placed(BxDeviceProxy* self, ID3D12Heap* heap, UINT64 offset,
|
||||
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) {
|
||||
BX_D3D_TRACE("ID3D12Device", "CreatePlacedResource");
|
||||
if (!self || !self->h_ID3D12Device) {
|
||||
if (out) {
|
||||
*out = nullptr;
|
||||
}
|
||||
BX_VTABLE_STUB_LOG("ID3D12Device", 29u, "CreatePlacedResource");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
if (out) {
|
||||
*out = nullptr;
|
||||
}
|
||||
if (is_backing_heap(heap)) {
|
||||
const HRESULT check_hr = validate_backing_placement(self->h_ID3D12Device, heap, offset, desc, state, clear);
|
||||
if (FAILED(check_hr)) {
|
||||
log_placed(offset, check_hr);
|
||||
return check_hr;
|
||||
}
|
||||
}
|
||||
ID3D12Heap* host_heap = bx_unwrap(heap);
|
||||
HRESULT hr = self->h_ID3D12Device->CreatePlacedResource(host_heap, offset, desc, state, clear, riid, out);
|
||||
if (SUCCEEDED(hr) && out && *out && host_heap != heap) {
|
||||
/* The resource owns a reference to the shim heap through its host
|
||||
object's private data, including across QueryInterface calls. */
|
||||
auto* created = static_cast<IUnknown*>(*out);
|
||||
ID3D12Object* object = nullptr;
|
||||
HRESULT retain_hr = created->QueryInterface(__uuidof(ID3D12Object), reinterpret_cast<void**>(&object));
|
||||
if (SUCCEEDED(retain_hr)) {
|
||||
retain_hr = object->SetPrivateDataInterface(kPlacedResourceHeap, heap);
|
||||
object->Release();
|
||||
}
|
||||
if (FAILED(retain_hr)) {
|
||||
created->Release();
|
||||
*out = nullptr;
|
||||
hr = retain_hr;
|
||||
}
|
||||
}
|
||||
log_placed(offset, hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
struct ConfigHeader {
|
||||
uint32_t magic;
|
||||
uint32_t struct_size;
|
||||
};
|
||||
static_assert(sizeof(ConfigHeader) == 8, "config probe is the 8-byte header");
|
||||
|
||||
void write_cpu_pointer(void* config, uint64_t pointer) {
|
||||
std::memcpy(static_cast<char*>(config) + offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer), &pointer, sizeof(pointer));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
|
||||
if (!config) {
|
||||
/* Titles call this before reserving memory and require S_OK. */
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
/*
|
||||
* PVOID has no size. Read 8 bytes, and only then the rest of a block that
|
||||
* names this struct. A mismatch is left untouched.
|
||||
*/
|
||||
ConfigHeader header{};
|
||||
std::memcpy(&header, config, sizeof(header));
|
||||
if (header.magic != BX_D3D12_VMEM_MAGIC || header.struct_size != sizeof(BxD3d12VirtualMemoryConfig)) {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
BxD3d12VirtualMemoryConfig in{};
|
||||
std::memcpy(&in, config, sizeof(in));
|
||||
const uint32_t unknown_flags = in.flags & ~BX_D3D12_VMEM_FLAG_BACKING_HEAP;
|
||||
if (in.version != kConfigVersion || unknown_flags != 0 || in.reserved != 0) {
|
||||
/* A console parameter block is not this struct. Leave those bytes alone. */
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const bx_runtime_config_t* cfg = bx_get_runtime_config();
|
||||
const uint64_t cap = title_limit();
|
||||
const auto profile = (cfg && cfg->profile == BX_PROFILE_ANACONDA) ? BX_PROFILE_ANACONDA : BX_PROFILE_LOCKHART;
|
||||
if (in.size_bytes != 0 && (in.size_bytes % k64K != 0 || in.size_bytes > cap)) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
bx_xmem_stats_t stats{};
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
if (in.size_bytes != 0 && stats.title_limit_bytes != 0 && in.size_bytes > stats.title_limit_bytes) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
bx_xmem_region_info_t region{};
|
||||
bool have_region = false;
|
||||
if (in.base_va != 0) {
|
||||
bx_xmem_region_info_t first{};
|
||||
if (!bx_xmem_query_region(in.base_va, &first) || first.size_bytes == 0 || first.base_va != in.base_va ||
|
||||
first.base_va % k64K != 0 || first.size_bytes % k64K != 0) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
const uint64_t span = in.size_bytes != 0 ? in.size_bytes : first.size_bytes;
|
||||
if (span < first.size_bytes || span % first.size_bytes != 0) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
for (uint64_t offset = 0; offset < span; offset += first.size_bytes) {
|
||||
bx_xmem_region_info_t page{};
|
||||
if (!bx_xmem_query_region(first.base_va + offset, &page) || page.base_va != first.base_va + offset ||
|
||||
page.size_bytes != first.size_bytes) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
}
|
||||
region = first;
|
||||
region.size_bytes = span;
|
||||
have_region = true;
|
||||
}
|
||||
|
||||
const uint64_t new_base = have_region ? region.base_va : in.base_va;
|
||||
const uint64_t new_size = have_region ? region.size_bytes : in.size_bytes;
|
||||
const bool backing_opt_in = (in.flags & BX_D3D12_VMEM_FLAG_BACKING_HEAP) != 0;
|
||||
BxChargedHeap* old_heap = nullptr;
|
||||
ID3D12Resource* old_buffer = nullptr;
|
||||
uint64_t published = 0;
|
||||
{
|
||||
Guard guard(g_section);
|
||||
const bool same = g_record.configured && g_record.config_base == new_base && g_record.config_size == new_size;
|
||||
if (!same) {
|
||||
take_cached_heap_locked(&old_heap, &old_buffer);
|
||||
}
|
||||
if (!same || g_record.backing_opt_in != backing_opt_in || g_record.have_region != have_region) {
|
||||
++g_record.config_generation;
|
||||
}
|
||||
g_record.configured = true;
|
||||
g_record.backing_opt_in = backing_opt_in;
|
||||
g_record.profile = profile;
|
||||
g_record.title_limit = cap;
|
||||
g_record.have_region = have_region;
|
||||
g_record.config_base = new_base;
|
||||
g_record.config_size = new_size;
|
||||
g_record.region = have_region ? region : bx_xmem_region_info_t{};
|
||||
published = g_record.cpu_pointer;
|
||||
}
|
||||
/* The only write to caller memory, and it happens before this call returns. */
|
||||
write_cpu_pointer(config, published);
|
||||
if (old_buffer) {
|
||||
old_buffer->Unmap(0, nullptr);
|
||||
old_buffer->Release();
|
||||
}
|
||||
if (old_heap) {
|
||||
old_heap->Release();
|
||||
}
|
||||
uint64_t charged = 0;
|
||||
{
|
||||
Guard guard(g_section);
|
||||
charged = g_record.charged_private_bytes;
|
||||
}
|
||||
|
||||
char detail[384];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"profile=%s title_limit=%llu xmem_used=%llu xmem_region=%d base=0x%llx region_bytes=%llu gpu_heap_bytes=%llu",
|
||||
profile_name(profile), static_cast<unsigned long long>(cap),
|
||||
static_cast<unsigned long long>(stats.committed_virtual_bytes + stats.allocated_physical_bytes),
|
||||
have_region ? 1 : 0, static_cast<unsigned long long>(have_region ? region.base_va : 0),
|
||||
static_cast<unsigned long long>(have_region ? region.size_bytes : 0),
|
||||
static_cast<unsigned long long>(charged));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "D3D12ConfigureVirtualMemoryX", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
bool bx_vmem_final_release(void* device_proxy) {
|
||||
Guard guard(g_section);
|
||||
auto* proxy = static_cast<BxDeviceProxy*>(device_proxy);
|
||||
if (!proxy->bx_try_release_last()) {
|
||||
return false;
|
||||
}
|
||||
/* The only weak pointer is the cached backing heap. Heaps that already left
|
||||
the cache were cleared in take_cached_heap_locked. */
|
||||
if (g_record.backing && g_record.backing->device() == proxy) {
|
||||
g_record.backing->set_device(nullptr);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void* bx_vmem_addref_backing_host() {
|
||||
Guard guard(g_section);
|
||||
if (!g_record.backing_host) {
|
||||
return nullptr;
|
||||
}
|
||||
g_record.backing_host->AddRef();
|
||||
return g_record.backing_host;
|
||||
}
|
||||
|
||||
bool bx_vmem_install_device_hooks(void* device) {
|
||||
/*
|
||||
* CreateHeap is slot 28 and CreatePlacedResource is slot 29 on ID3D12Device.
|
||||
* BxDeviceProxy inherits both methods from the generated forwarders.
|
||||
* The proxy vtable is shared static data: every BxDeviceProxy instance points at
|
||||
* the same function table. Patching it once covers every device this DLL creates.
|
||||
* That table is in a read-only section, so VirtualProtect opens the two slots for
|
||||
* the store and then puts the previous protection back.
|
||||
* No other hook in this DLL replaces those methods without editing the proxy sources.
|
||||
*/
|
||||
/* No caller may publish a proxy until both shared slots are ready. */
|
||||
static bool installed = false;
|
||||
Guard guard(g_section);
|
||||
if (installed) {
|
||||
return true;
|
||||
}
|
||||
auto* proxy = static_cast<BxDeviceProxy*>(device);
|
||||
void** vtable = *reinterpret_cast<void***>(proxy);
|
||||
DWORD old = 0;
|
||||
if (!VirtualProtect(vtable + 28, sizeof(void*) * 2, PAGE_READWRITE, &old)) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "vmem_hook", "VirtualProtect on the device vtable failed");
|
||||
BX_VTABLE_STUB_LOG("ID3D12Device", 28u, "CreateHeap");
|
||||
return false;
|
||||
}
|
||||
vtable[28] = reinterpret_cast<void*>(&create_heap);
|
||||
vtable[29] = reinterpret_cast<void*>(&create_placed);
|
||||
DWORD ignored = 0;
|
||||
VirtualProtect(vtable + 28, sizeof(void*) * 2, old, &ignored);
|
||||
installed = true;
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "vmem_hook", "CreateHeap and CreatePlacedResource installed");
|
||||
return true;
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
#ifndef BETTERXEN_D3D12_XS_VMEM_H
|
||||
#define BETTERXEN_D3D12_XS_VMEM_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <windows.h>
|
||||
|
||||
/*
|
||||
* BetterXen-defined parameter block for D3D12ConfigureVirtualMemoryX.
|
||||
*
|
||||
* The export is PVOID and the frozen ABI has no size argument (abi/ is out of
|
||||
* scope). The first 8 bytes are therefore the minimum dereference: magic then
|
||||
* the struct size. Magic is 'BXVM' (0x4D565842). struct_size must equal
|
||||
* sizeof(BxD3d12VirtualMemoryConfig). Any other pointer, including null, is not
|
||||
* this struct: the call logs the unimplemented-API stub and returns S_OK. It
|
||||
* does not read past those 8 bytes and it does not write.
|
||||
*
|
||||
* A block whose magic and size match is then checked in full. version is 1.
|
||||
* flags may be 0 or BX_D3D12_VMEM_FLAG_BACKING_HEAP. Any other flag bit, or a
|
||||
* non-zero reserved word, is not this struct either (logged S_OK, no write).
|
||||
* A recognised block with a bad size or a base_va that bx_xmem_query_region
|
||||
* does not resolve still returns E_INVALIDARG and is not written.
|
||||
*
|
||||
* base_va is 0, or an address bx_xmem_query_region resolves. It is not a GPU pointer.
|
||||
* size_bytes is 0 or a 64 KiB multiple that does not exceed the active title limit.
|
||||
*
|
||||
* The call copies what it needs. The caller's pointer is not kept. cpu_pointer
|
||||
* is written only before this call returns: the persistent Map address of the
|
||||
* WRITE_BACK buffer if that backing heap already exists, otherwise 0. CreateHeap
|
||||
* does not write the block. A caller that needs the address after the backing
|
||||
* heap has been created calls D3D12ConfigureVirtualMemoryX again with the same
|
||||
* region (same base_va and size). That second call does not reset or recreate
|
||||
* the backing heap. It writes the current map into the new block. A nonzero
|
||||
* cpu_pointer is valid only while that backing buffer remains cached. Changing
|
||||
* the region or replacing the cache for another host device unmaps it, even if
|
||||
* the caller retains the heap. Callers must synchronize those operations with
|
||||
* access through the pointer and obtain a fresh pointer after replacement.
|
||||
*
|
||||
* CreateHeap returns that backing heap only when all of the following hold:
|
||||
* the block opted in with BX_D3D12_VMEM_FLAG_BACKING_HEAP, the region size is
|
||||
* non-zero, and the desc is the heap this file creates for the region:
|
||||
* Type CUSTOM, CPUPageProperty WRITE_BACK, MemoryPoolPreference L0,
|
||||
* SizeInBytes equal to the configured region, Alignment 0 or 64 KiB,
|
||||
* Flags exactly D3D12_HEAP_FLAG_NONE (the flag set used when the backing heap
|
||||
* is created), and CreationNodeMask and VisibleNodeMask each 0 or 1.
|
||||
* If the backing configuration changes during a backing request, CreateHeap
|
||||
* returns HRESULT_FROM_WIN32(ERROR_RETRY) and discards any newly allocated heap.
|
||||
* Any other CreateHeap is the host CreateHeap. The desc is not modified.
|
||||
* The live-heap budget charge is taken on create and dropped on the wrapper's
|
||||
* final Release. A resource created by CreatePlacedResource holds the wrapper
|
||||
* for its lifetime.
|
||||
* GetDevice on every wrapper returns the BxDeviceProxy. An ordinary heap AddRefs
|
||||
* that proxy until the wrapper's final Release, matching BxChildProxy, so the
|
||||
* caller can release the device and keep the heap. The process-wide backing heap
|
||||
* does not AddRef. The cache would keep the device and its charge alive. That
|
||||
* pointer is weak. It is cleared when the heap leaves the cache (a new region
|
||||
* or a different host device) and when that proxy's last reference drops.
|
||||
* CreatePlacedResource1 and CreatePlacedResource2 unwrap the wrapper to the
|
||||
* host heap before the host call. The cache records the host ID3D12Device
|
||||
* that built the heap. CreateHeap for a different host device releases the
|
||||
* heap and its buffer, credits the charge, and builds a new one. CreateHeap
|
||||
* for the same host device returns the cached heap. The check, the retarget,
|
||||
* and the caller's reference happen in one critical section.
|
||||
*
|
||||
* The layout must match tests/conformance/test_d3d12_placed/main.cpp.
|
||||
*/
|
||||
constexpr uint32_t BX_D3D12_VMEM_MAGIC = 0x4D565842u;
|
||||
constexpr uint32_t BX_D3D12_VMEM_FLAG_BACKING_HEAP = 0x1u;
|
||||
|
||||
struct BxD3d12VirtualMemoryConfig {
|
||||
uint32_t magic;
|
||||
uint32_t struct_size;
|
||||
uint32_t version;
|
||||
uint32_t flags;
|
||||
uint64_t base_va;
|
||||
uint64_t size_bytes;
|
||||
uint64_t reserved;
|
||||
uint64_t cpu_pointer;
|
||||
};
|
||||
static_assert(sizeof(BxD3d12VirtualMemoryConfig) == 48, "config block is 48 bytes");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, magic) == 0, "magic offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, struct_size) == 4, "struct_size offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, version) == 8, "version offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, flags) == 12, "flags offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, base_va) == 16, "base_va offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, size_bytes) == 24, "size_bytes offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, reserved) == 32, "reserved offset");
|
||||
static_assert(offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer) == 40, "cpu_pointer offset");
|
||||
|
||||
extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config);
|
||||
|
||||
/* Patches the device proxy vtable so CreateHeap and CreatePlacedResource run the code in vmem.cpp. */
|
||||
bool bx_vmem_install_device_hooks(void* device);
|
||||
|
||||
/* 1->0 Release of a device proxy, under g_section. Compare-exchanges the count from
|
||||
1 to 0 and clears every weak backing-heap pointer aimed at that proxy. Returns false
|
||||
when the count was no longer 1, so the caller retries. A true return is the only
|
||||
path into final cleanup. */
|
||||
bool bx_vmem_final_release(void* device_proxy);
|
||||
|
||||
/* AddRefs the host ID3D12Device that created the cached backing heap, or returns null.
|
||||
The test sets BX_D3D12_REUSE_BACKING_HOST=1 so a second proxy wraps this same host
|
||||
while the cache still holds it. */
|
||||
void* bx_vmem_addref_backing_host();
|
||||
|
||||
#endif /* BETTERXEN_D3D12_XS_VMEM_H */
|
||||
@@ -1,8 +1,6 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
@@ -12,30 +10,6 @@ constexpr GUID game_input_v0 = {0x11be2a7e, 0x4254, 0x445a,
|
||||
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
|
||||
using Callback = void (WINAPI*)();
|
||||
|
||||
// GameInputEnumerationKind values from Microsoft's public GDK GameInput (v0) reference:
|
||||
// 0 = GameInputNoEnumeration, 1 = GameInputAsyncEnumeration, 2 = GameInputBlockingEnumeration.
|
||||
constexpr uint32_t kMaxEnumerationKind = 2;
|
||||
|
||||
struct SrwExclusiveLock {
|
||||
explicit SrwExclusiveLock(SRWLOCK& lock) : lock_(lock) { AcquireSRWLockExclusive(&lock_); }
|
||||
~SrwExclusiveLock() { ReleaseSRWLockExclusive(&lock_); }
|
||||
SrwExclusiveLock(const SrwExclusiveLock&) = delete;
|
||||
SrwExclusiveLock& operator=(const SrwExclusiveLock&) = delete;
|
||||
|
||||
private:
|
||||
SRWLOCK& lock_;
|
||||
};
|
||||
|
||||
struct RegisteredDeviceCallback {
|
||||
void* device = nullptr;
|
||||
uint32_t input_kind = 0;
|
||||
uint32_t status_filter = 0;
|
||||
uint32_t enumeration_kind = 0;
|
||||
void* context = nullptr;
|
||||
Callback callback = nullptr;
|
||||
bool stopped = false;
|
||||
};
|
||||
|
||||
template<class T>
|
||||
HRESULT unavailable(T* out) {
|
||||
if (!out) return E_POINTER;
|
||||
@@ -45,11 +19,6 @@ HRESULT unavailable(T* out) {
|
||||
|
||||
class GameInput final : public IUnknown {
|
||||
LONG refs = 0;
|
||||
SRWLOCK callback_lock_ = SRWLOCK_INIT;
|
||||
uint64_t next_token_ = 1;
|
||||
std::unordered_map<uint64_t, RegisteredDeviceCallback> callbacks_;
|
||||
std::atomic<uint32_t> focus_policy_{0};
|
||||
|
||||
public:
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
@@ -85,32 +54,9 @@ public:
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 8, "RegisterReadingCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterDeviceCallback(
|
||||
void* device,
|
||||
uint32_t input_kind,
|
||||
uint32_t status_filter,
|
||||
uint32_t enumeration_kind,
|
||||
void* context,
|
||||
Callback callback,
|
||||
uint64_t* out_token
|
||||
) {
|
||||
if (out_token) *out_token = 0;
|
||||
if (!callback || input_kind == 0 || status_filter == 0 || enumeration_kind > kMaxEnumerationKind) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
SrwExclusiveLock guard(callback_lock_);
|
||||
const uint64_t token = next_token_++;
|
||||
callbacks_.emplace(token, RegisteredDeviceCallback{
|
||||
device,
|
||||
input_kind,
|
||||
status_filter,
|
||||
enumeration_kind,
|
||||
context,
|
||||
callback,
|
||||
false,
|
||||
});
|
||||
if (out_token) *out_token = token;
|
||||
return S_OK;
|
||||
virtual HRESULT WINAPI RegisterDeviceCallback(void*, uint32_t, uint32_t, uint32_t, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 9, "RegisterDeviceCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterSystemButtonCallback(void*, uint32_t, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 10, "RegisterSystemButtonCallback");
|
||||
@@ -120,18 +66,12 @@ public:
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 11, "RegisterKeyboardLayoutCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual void WINAPI StopCallback(uint64_t token) {
|
||||
if (token == 0) return;
|
||||
SrwExclusiveLock guard(callback_lock_);
|
||||
auto it = callbacks_.find(token);
|
||||
if (it != callbacks_.end()) {
|
||||
it->second.stopped = true;
|
||||
}
|
||||
virtual void WINAPI StopCallback(uint64_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 12, "StopCallback");
|
||||
}
|
||||
virtual bool WINAPI UnregisterCallback(uint64_t token, uint64_t /*timeout_us*/) {
|
||||
if (token == 0) return false;
|
||||
SrwExclusiveLock guard(callback_lock_);
|
||||
return callbacks_.erase(token) > 0;
|
||||
virtual bool WINAPI UnregisterCallback(uint64_t, uint64_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 13, "UnregisterCallback");
|
||||
return false;
|
||||
}
|
||||
virtual HRESULT WINAPI CreateDispatcher(void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 14, "CreateDispatcher");
|
||||
@@ -161,8 +101,8 @@ public:
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 20, "EnableOemDeviceSupport");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual void WINAPI SetFocusPolicy(uint32_t policy) {
|
||||
focus_policy_.store(policy, std::memory_order_relaxed);
|
||||
virtual void WINAPI SetFocusPolicy(uint32_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 21, "SetFocusPolicy");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <intrin.h>
|
||||
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
@@ -18,14 +17,6 @@ LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = nullptr;
|
||||
std::atomic_flag g_crash_logged{};
|
||||
std::atomic<bool> g_crash_in_flight{false};
|
||||
std::atomic<uint64_t> g_clwb_traps{0};
|
||||
|
||||
// Other AMD-only instructions Rosetta 2 (and Intel CPUs) raise #UD on. Their
|
||||
// counts reach the JSONL trace only: the frozen .def has no export for them.
|
||||
enum AmdKind { kClzero, kMonitorx, kMwaitx, kRdpru, kExtrq, kInsertq, kAmdKinds };
|
||||
constexpr const char* kAmdEvents[kAmdKinds] = {
|
||||
"clzero_trapped", "monitorx_trapped", "mwaitx_trapped",
|
||||
"rdpru_trapped", "extrq_trapped", "insertq_trapped"};
|
||||
std::atomic<uint64_t> g_amd_traps[kAmdKinds]{};
|
||||
bx_runtime_config_t g_config = {
|
||||
BX_ABI_VERSION,
|
||||
BX_PROFILE_LOCKHART,
|
||||
@@ -144,167 +135,6 @@ bool is_adx_opcode(const uint8_t* ip, size_t size) {
|
||||
return size - idx >= 4 && ip[idx] == 0x0F && ip[idx + 1] == 0x38 && ip[idx + 2] == 0xF6;
|
||||
}
|
||||
|
||||
// Logs the first trap of a kind and then every power of two, as for clwb.
|
||||
void log_sampled_trap(const char* event, uint64_t count, uint64_t rip, size_t len) {
|
||||
if (count == 1 || (count & (count - 1)) == 0) {
|
||||
char msg[160];
|
||||
std::snprintf(msg, sizeof(msg),
|
||||
"rip=0x%016llx len=%zu total_traps=%llu",
|
||||
static_cast<unsigned long long>(rip), len,
|
||||
static_cast<unsigned long long>(count));
|
||||
bx_log_emit(BX_LOG_INFO, "runtime_veh", event, msg);
|
||||
}
|
||||
}
|
||||
|
||||
// The instruction encodings and architectural effects below are derived from
|
||||
// AMD APM vol. 3 (24594, rev. 3.36), Instruction Prefixes and CLZERO, MONITORX,
|
||||
// MWAITX, RDPRU, and vol. 4 (26568, rev. 3.25), EXTRQ and INSERTQ.
|
||||
struct AmdInstruction {
|
||||
AmdKind kind = kAmdKinds;
|
||||
size_t length = 0;
|
||||
bool address32 = false;
|
||||
size_t destination = 0;
|
||||
size_t source = 0;
|
||||
bool immediate = false;
|
||||
uint16_t field = 0;
|
||||
};
|
||||
|
||||
AmdInstruction decode_amd_instruction(const uint8_t* bytes, size_t size) {
|
||||
if (size < 3) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const bool address32 = bytes[0] == 0x67;
|
||||
const bool extract = bytes[0] == 0x66;
|
||||
const bool insert = bytes[0] == 0xF2;
|
||||
size_t offset = (address32 || extract || insert) ? 1 : 0;
|
||||
uint8_t rex = 0;
|
||||
if ((bytes[offset] & 0xF0) == 0x40) {
|
||||
rex = bytes[offset++];
|
||||
}
|
||||
if (size - offset < 3 || bytes[offset] != 0x0F) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const uint8_t opcode = bytes[offset + 1];
|
||||
const uint8_t operand = bytes[offset + 2];
|
||||
const size_t length = offset + 3;
|
||||
if (!extract && !insert && opcode == 0x01) {
|
||||
switch (operand) {
|
||||
case 0xFC: return {kClzero, length, address32};
|
||||
case 0xFA: return {kMonitorx, length, address32};
|
||||
case 0xFB: return address32 ? AmdInstruction{} : AmdInstruction{kMwaitx, length};
|
||||
case 0xFD: return address32 ? AmdInstruction{} : AmdInstruction{kRdpru, length};
|
||||
default: return {};
|
||||
}
|
||||
}
|
||||
|
||||
if ((!extract && !insert) || (opcode != 0x78 && opcode != 0x79) ||
|
||||
(operand & 0xC0) != 0xC0) {
|
||||
return {};
|
||||
}
|
||||
const bool immediate = opcode == 0x78;
|
||||
const unsigned reg = (operand & 0x38) >> 3;
|
||||
if (immediate && (size - length < 2 || (extract && reg != 0))) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const size_t rm = (operand & 7) + ((rex & 1) ? 8 : 0);
|
||||
AmdInstruction result{extract ? kExtrq : kInsertq, length};
|
||||
result.destination = extract && immediate ? rm : reg + ((rex & 4) ? 8 : 0);
|
||||
result.source = rm;
|
||||
result.immediate = immediate;
|
||||
if (immediate) {
|
||||
result.length += 2;
|
||||
result.field = static_cast<uint16_t>(bytes[length + 1] * 256u + bytes[length]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void apply_sse4a(const AmdInstruction& instruction, CONTEXT& context) {
|
||||
M128A* registers = context.FltSave.XmmRegisters;
|
||||
M128A& destination = registers[instruction.destination];
|
||||
const M128A source = registers[instruction.source];
|
||||
const bool extract = instruction.kind == kExtrq;
|
||||
|
||||
// EXTRQ takes register controls from bits 13:0 and INSERTQ from 77:64.
|
||||
uint64_t field = instruction.field;
|
||||
if (!instruction.immediate) {
|
||||
field = extract ? source.Low : static_cast<uint64_t>(source.High);
|
||||
}
|
||||
const unsigned index = (field & 0x3F00) >> 8;
|
||||
const unsigned width = field & 0x3F;
|
||||
const uint64_t low_mask = width ? UINT64_MAX >> (64 - width) : UINT64_MAX;
|
||||
if (extract) {
|
||||
destination.Low = (destination.Low >> index) & low_mask;
|
||||
} else {
|
||||
const uint64_t positioned_mask = low_mask << index;
|
||||
destination.Low = (destination.Low & ~positioned_mask) |
|
||||
((source.Low << index) & positioned_mask);
|
||||
}
|
||||
// The APM leaves the upper quadword and out-of-range fields undefined.
|
||||
}
|
||||
|
||||
bool zero_guest_cache_line(uint64_t address, EXCEPTION_RECORD& exception) {
|
||||
// The supported guest has 64-byte cache lines. An aligned line fits
|
||||
// in one Windows page, including when the address is at the end of it.
|
||||
constexpr uintptr_t line_size = 64;
|
||||
const uintptr_t start = address & ~(line_size - 1);
|
||||
constexpr DWORD write_protections = PAGE_READWRITE | PAGE_WRITECOPY |
|
||||
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
|
||||
MEMORY_BASIC_INFORMATION page{};
|
||||
if (VirtualQuery(reinterpret_cast<const void*>(start), &page, sizeof(page)) &&
|
||||
page.State == MEM_COMMIT && (page.Protect & write_protections) &&
|
||||
!(page.Protect & PAGE_GUARD)) {
|
||||
std::memset(reinterpret_cast<void*>(start), 0, line_size);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Pass the write fault on at the original guest RIP. Guard pages use
|
||||
// the same fallback, without Windows' one-shot guard-page semantics.
|
||||
exception.ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
|
||||
exception.NumberParameters = 2;
|
||||
exception.ExceptionInformation[0] = 1; // Write access.
|
||||
exception.ExceptionInformation[1] = start;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool apply_amd_instruction(const AmdInstruction& instruction, CONTEXT& context,
|
||||
EXCEPTION_RECORD& exception) {
|
||||
switch (instruction.kind) {
|
||||
case kClzero:
|
||||
return zero_guest_cache_line(instruction.address32 ? static_cast<uint32_t>(context.Rax)
|
||||
: context.Rax, exception);
|
||||
case kMonitorx:
|
||||
// There is no host monitor state. MWAITX may complete immediately.
|
||||
return true;
|
||||
case kMwaitx:
|
||||
// Approximate an early wakeup with one scheduler yield.
|
||||
SwitchToThread();
|
||||
return true;
|
||||
case kRdpru: {
|
||||
const uint32_t selector = static_cast<uint32_t>(context.Rcx);
|
||||
const uint64_t counter = selector < 2 ? __rdtsc() : 0;
|
||||
context.Rax = static_cast<uint32_t>(counter);
|
||||
context.Rdx = static_cast<uint32_t>(counter >> 32);
|
||||
|
||||
// The APM specifies zero for these five flags and marks CF modified.
|
||||
// BetterXen chooses a clear CF until its native behavior is verified.
|
||||
constexpr DWORD arithmetic_flags = (1u << 11) | (1u << 7) | (1u << 6) |
|
||||
(1u << 4) | (1u << 2) | (1u << 0);
|
||||
context.EFlags &= ~arithmetic_flags;
|
||||
return true;
|
||||
}
|
||||
case kExtrq:
|
||||
case kInsertq:
|
||||
apply_sse4a(instruction, context);
|
||||
return true;
|
||||
case kAmdKinds:
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) {
|
||||
// Wine can invoke the top-level filter again for the same terminal fault.
|
||||
if (ep && ep->ExceptionRecord && ep->ContextRecord &&
|
||||
@@ -368,25 +198,20 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
|
||||
size_t len = decode_clwb_length(ip, size);
|
||||
if (len > 0) {
|
||||
uint64_t count = g_clwb_traps.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
log_sampled_trap("clwb_trapped", count, ep->ContextRecord->Rip, len);
|
||||
if (count == 1 || (count & (count - 1)) == 0) {
|
||||
char msg[160];
|
||||
std::snprintf(msg, sizeof(msg),
|
||||
"rip=0x%016llx len=%zu total_traps=%llu",
|
||||
static_cast<unsigned long long>(ep->ContextRecord->Rip),
|
||||
len,
|
||||
static_cast<unsigned long long>(count));
|
||||
bx_log_emit(BX_LOG_INFO, "runtime_veh", "clwb_trapped", msg);
|
||||
}
|
||||
ep->ContextRecord->Rip += len;
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
}
|
||||
|
||||
const AmdInstruction instruction = decode_amd_instruction(ip, size);
|
||||
if (instruction.length != 0) {
|
||||
if (!apply_amd_instruction(instruction, *ep->ContextRecord, *ep->ExceptionRecord)) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
const uint64_t count =
|
||||
g_amd_traps[instruction.kind].fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
log_sampled_trap(kAmdEvents[instruction.kind], count, ep->ContextRecord->Rip,
|
||||
instruction.length);
|
||||
ep->ContextRecord->Rip += instruction.length;
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
|
||||
if (g_config.enable_adx_tripwire && is_adx_opcode(ip, size)) {
|
||||
char msg[160];
|
||||
std::snprintf(msg, sizeof(msg),
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
bx_add_shim_dll(xcrdapi XCRDAPI XCRDAPI.def
|
||||
xcrdapi.cpp
|
||||
)
|
||||
target_include_directories(xcrdapi PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/dstorage")
|
||||
target_link_libraries(xcrdapi PRIVATE bx_runtime_veh kernel32 uuid)
|
||||
target_compile_definitions(xcrdapi PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
@@ -1,21 +0,0 @@
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,15 +0,0 @@
|
||||
# Vendored DirectStorage headers (#483)
|
||||
|
||||
`dstorage.h` and `dstorageerr.h` are Microsoft's public PC DirectStorage headers, copied **unmodified** (CRLF line endings preserved) so that `XCRDAPI.dll` and `test_xcrdapi` can implement and call the public `IDStorageFactory`, `IDStorageFile`, `IDStorageQueue`…`IDStorageQueue4` and `IDStorageStatusArray` interfaces.
|
||||
|
||||
| Item | Value |
|
||||
| --- | --- |
|
||||
| Source | NuGet package [`Microsoft.Direct3D.DirectStorage` 1.4.0](https://www.nuget.org/packages/Microsoft.Direct3D.DirectStorage/1.4.0), downloaded from `api.nuget.org` on 2026-11-26 |
|
||||
| Package SHA-256 | `0838e7f71b14acfbd1ac7ecc5e943f6c95e4f4e679e8a67f8ff6e7c102414321` |
|
||||
| Files | `native/include/dstorage.h` (SHA-256 `3f966750423b59145bd05b2ccd889b819f0484813baafbc1345cb16e544b4f87`), `native/include/dstorageerr.h` (SHA-256 `07ea8182503c25dd1684d3f9105db7b6fa70fc96dcdab18bd9de75fcec427fa2`), `LICENSE-CODE.txt` (SHA-256 `903df5512f7d02609fed0c780a9b704f5a3eeb6e4d84ebe42a29845c81899a3c`) |
|
||||
| Licence | MIT. Both headers start with `Copyright (c) Microsoft Corporation` / `Licensed under the MIT license`; the package's `LICENSE-CODE.txt` (copied here) holds the MIT text. |
|
||||
| Modifications | None |
|
||||
|
||||
The package as a whole is under the proprietary *Microsoft DirectStorage SDK* licence terms (`LICENSE.txt`), whose distributable list (`distributable_files.txt`) names only `dstorage.dll` and `dstoragecore.dll`. BetterXen uses neither DLL and copies nothing else from the package.
|
||||
|
||||
The Xbox console interfaces (`IDStorageFactoryX` and others, `dstorage_xs.h`) are not included: their IIDs have no licence-compatible public source. See the discussion on #483.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,502 +0,0 @@
|
||||
/*-------------------------------------------------------------------------------------
|
||||
*
|
||||
* Copyright (c) Microsoft Corporation
|
||||
* Licensed under the MIT license
|
||||
*
|
||||
*-------------------------------------------------------------------------------------*/
|
||||
#pragma once
|
||||
|
||||
/*++
|
||||
|
||||
MessageId's 0x0000 - 0x00ff (inclusive) are reserved for DirectStorage.
|
||||
|
||||
--*/
|
||||
//
|
||||
// Values are 32 bit values laid out as follows:
|
||||
//
|
||||
// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
|
||||
// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
|
||||
// +---+-+-+-----------------------+-------------------------------+
|
||||
// |Sev|C|R| Facility | Code |
|
||||
// +---+-+-+-----------------------+-------------------------------+
|
||||
//
|
||||
// where
|
||||
//
|
||||
// Sev - is the severity code
|
||||
//
|
||||
// 00 - Success
|
||||
// 01 - Informational
|
||||
// 10 - Warning
|
||||
// 11 - Error
|
||||
//
|
||||
// C - is the Customer code flag
|
||||
//
|
||||
// R - is a reserved bit
|
||||
//
|
||||
// Facility - is the facility code
|
||||
//
|
||||
// Code - is the facility's status code
|
||||
//
|
||||
//
|
||||
// Define the facility codes
|
||||
//
|
||||
#define FACILITY_GAME 2340
|
||||
|
||||
|
||||
//
|
||||
// Define the severity codes
|
||||
//
|
||||
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_ALREADY_RUNNING
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// DStorage is already running exclusively.
|
||||
//
|
||||
#define E_DSTORAGE_ALREADY_RUNNING ((HRESULT)0x89240001L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_NOT_RUNNING
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// DStorage is not running.
|
||||
//
|
||||
#define E_DSTORAGE_NOT_RUNNING ((HRESULT)0x89240002L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_QUEUE_CAPACITY
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// Invalid queue capacity parameter.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_QUEUE_CAPACITY ((HRESULT)0x89240003L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_XVD_DEVICE_NOT_SUPPORTED
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The specified XVD is not on a supported NVMe device.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_XVD_DEVICE_NOT_SUPPORTED ((HRESULT)0x89240004L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_UNSUPPORTED_VOLUME
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The specified XVD is not on a supported volume.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_UNSUPPORTED_VOLUME ((HRESULT)0x89240005L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_END_OF_FILE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The specified offset and length exceeds the size of the file.
|
||||
//
|
||||
#define E_DSTORAGE_END_OF_FILE ((HRESULT)0x89240007L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_REQUEST_TOO_LARGE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The IO request is too large.
|
||||
//
|
||||
#define E_DSTORAGE_REQUEST_TOO_LARGE ((HRESULT)0x89240008L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_ACCESS_VIOLATION
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The destination buffer for the DStorage request is not accessible.
|
||||
//
|
||||
#define E_DSTORAGE_ACCESS_VIOLATION ((HRESULT)0x89240009L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_UNSUPPORTED_FILE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The file is not supported by DStorage. Possible reasons include the file is a
|
||||
// sparse file, or is compressed in NTFS.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_UNSUPPORTED_FILE ((HRESULT)0x8924000AL)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_FILE_NOT_OPEN
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The file is not open.
|
||||
//
|
||||
#define E_DSTORAGE_FILE_NOT_OPEN ((HRESULT)0x8924000BL)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_RESERVED_FIELDS
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// A reserved field is not set to 0.
|
||||
//
|
||||
#define E_DSTORAGE_RESERVED_FIELDS ((HRESULT)0x8924000CL)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_BCPACK_MODE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The request has invalid BCPack decompression mode.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_BCPACK_MODE ((HRESULT)0x8924000DL)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_SWIZZLE_MODE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The request has invalid swizzle mode.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_SWIZZLE_MODE ((HRESULT)0x8924000EL)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_DESTINATION_SIZE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The request's destination size is invalid. If no decompression is used, it must
|
||||
// be equal to the request's length; If decompression is used, it must be larger
|
||||
// than the request's length.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_DESTINATION_SIZE ((HRESULT)0x8924000FL)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_QUEUE_CLOSED
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The request targets a queue that is closed.
|
||||
//
|
||||
#define E_DSTORAGE_QUEUE_CLOSED ((HRESULT)0x89240010L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_CLUSTER_SIZE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The volume is formatted with an unsupported cluster size.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_CLUSTER_SIZE ((HRESULT)0x89240011L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_TOO_MANY_QUEUES
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The number of queues has reached the maximum limit.
|
||||
//
|
||||
#define E_DSTORAGE_TOO_MANY_QUEUES ((HRESULT)0x89240012L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_QUEUE_PRIORITY
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// Invalid priority is specified for the queue.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_QUEUE_PRIORITY ((HRESULT)0x89240013L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_TOO_MANY_FILES
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The number of files has reached the maximum limit.
|
||||
//
|
||||
#define E_DSTORAGE_TOO_MANY_FILES ((HRESULT)0x89240014L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INDEX_BOUND
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The index parameter is out of bound.
|
||||
//
|
||||
#define E_DSTORAGE_INDEX_BOUND ((HRESULT)0x89240015L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_IO_TIMEOUT
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The IO operation has timed out.
|
||||
//
|
||||
#define E_DSTORAGE_IO_TIMEOUT ((HRESULT)0x89240016L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_FILE_HANDLE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The specified file has not been opened.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_FILE_HANDLE ((HRESULT)0x89240017L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_DEPRECATED_PREVIEW_GDK
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// This GDK preview is deprecated. Update to a supported GDK version.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_DEPRECATED_PREVIEW_GDK ((HRESULT)0x89240018L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_XVD_NOT_REGISTERED
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The specified XVD is not registered or unmounted.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_XVD_NOT_REGISTERED ((HRESULT)0x89240019L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_FILE_OFFSET
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The request has invalid file offset for the specified decompression mode.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_FILE_OFFSET ((HRESULT)0x8924001AL)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_SOURCE_TYPE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// A memory source request was enqueued into a file source queue, or a file source
|
||||
// request was enqueued into a memory source queue.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_SOURCE_TYPE ((HRESULT)0x8924001BL)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_INTERMEDIATE_SIZE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The request has invalid intermediate size for the specified decompression modes.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_INTERMEDIATE_SIZE ((HRESULT)0x8924001CL)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_SYSTEM_NOT_SUPPORTED
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// This console generation doesn't support DirectStorage.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_SYSTEM_NOT_SUPPORTED ((HRESULT)0x8924001DL)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_STAGING_BUFFER_LOCKED
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// Staging buffer size can only be changed when no queue is created and no file is
|
||||
// open.
|
||||
//
|
||||
#define E_DSTORAGE_STAGING_BUFFER_LOCKED ((HRESULT)0x8924001FL)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The specified staging buffer size is not valid.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE ((HRESULT)0x89240020L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_STAGING_BUFFER_TOO_SMALL
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The staging buffer isn't large enough to perform this operation.
|
||||
//
|
||||
#define E_DSTORAGE_STAGING_BUFFER_TOO_SMALL ((HRESULT)0x89240021L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_FENCE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The fence is not valid or has been released.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_FENCE ((HRESULT)0x89240022L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_STATUS_ARRAY
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The status array is not valid or has been released.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_STATUS_ARRAY ((HRESULT)0x89240023L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// Invalid priority is specified for the queue. Only DSTORAGE_PRIORITY_REALTIME
|
||||
// is a valid priority for a memory queue.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY ((HRESULT)0x89240024L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_DECOMPRESSION_ERROR
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// A generic error has happened during decompression.
|
||||
//
|
||||
#define E_DSTORAGE_DECOMPRESSION_ERROR ((HRESULT)0x89240030L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_ZLIB_BAD_HEADER
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// ZLIB header is corrupted.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_ZLIB_BAD_HEADER ((HRESULT)0x89240031L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_ZLIB_BAD_DATA
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// ZLIB compressed data is corrupted/invalid.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_ZLIB_BAD_DATA ((HRESULT)0x89240032L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_ZLIB_PARITY_FAIL
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// Block-level ADLER parity check failed during ZLIB decompression.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_ZLIB_PARITY_FAIL ((HRESULT)0x89240033L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_BCPACK_BAD_HEADER
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// BCPack header is corrupted.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_BCPACK_BAD_HEADER ((HRESULT)0x89240034L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_BCPACK_BAD_DATA
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// BCPack decoder has generated more data than expected, most likely due to
|
||||
// corrupted bitstream.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_BCPACK_BAD_DATA ((HRESULT)0x89240035L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_DECRYPTION_ERROR
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// A generic error has happened during decryption.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_DECRYPTION_ERROR ((HRESULT)0x89240036L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_PASSTHROUGH_ERROR
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// A generic error has happened during copy operation.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_PASSTHROUGH_ERROR ((HRESULT)0x89240037L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_FILE_TOO_FRAGMENTED
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The file is too fragmented to be accessed by DStorage. This error can only
|
||||
// happen with files overly fragmented on a writable volume.
|
||||
// This error only applies to Xbox.
|
||||
//
|
||||
#define E_DSTORAGE_FILE_TOO_FRAGMENTED ((HRESULT)0x89240038L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_COMPRESSED_DATA_TOO_LARGE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The size of the resulting compressed data is too large for
|
||||
// DirectStorage to decompress successfully on the GPU.
|
||||
//
|
||||
#define E_DSTORAGE_COMPRESSED_DATA_TOO_LARGE ((HRESULT)0x89240039L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_INVALID_DESTINATION_TYPE
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// A gpu memory destination request was enqueued into a queue that
|
||||
// was created without a D3D device or the destination type is
|
||||
// unknown.
|
||||
//
|
||||
#define E_DSTORAGE_INVALID_DESTINATION_TYPE ((HRESULT)0x89240040L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_FILEBUFFERING_REQUIRES_DISABLED_BYPASSIO
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// ForceFileBuffering was enabled without disabling BypassIO.
|
||||
//
|
||||
#define E_DSTORAGE_FILEBUFFERING_REQUIRES_DISABLED_BYPASSIO ((HRESULT)0x89240041L)
|
||||
|
||||
//
|
||||
// MessageId: E_DSTORAGE_SCRATCH_BUFFER_TOO_SMALL
|
||||
//
|
||||
// MessageText:
|
||||
//
|
||||
// The scratch buffer given to the driver is too small
|
||||
// to decompress buffers successfully.
|
||||
//
|
||||
#define E_DSTORAGE_SCRATCH_BUFFER_TOO_SMALL ((HRESULT)0x89240042L)
|
||||
@@ -1,27 +0,0 @@
|
||||
#ifndef BETTERXEN_DSTORAGE_MINGW_H
|
||||
#define BETTERXEN_DSTORAGE_MINGW_H
|
||||
|
||||
// dstorage.h attaches its IIDs with the MSVC-only __declspec(uuid(...)) through
|
||||
// DECLARE_INTERFACE_IID_, which MinGW-w64 GCC ignores, so __uuidof() has no
|
||||
// definition. These declarations restate the same IIDs for MinGW. They were
|
||||
// generated from the DECLARE_INTERFACE_IID_ lines of the vendored, unmodified
|
||||
// dstorage/dstorage.h (SDK 1.4.0, MIT); regenerate them if that header changes.
|
||||
|
||||
#include <dstorage.h>
|
||||
|
||||
#if defined(__MINGW32__) && !defined(_MSC_VER)
|
||||
__CRT_UUID_DECL(IDStorageFile, 0x5de95e7b, 0x955a, 0x4868, 0xa7, 0x3c, 0x24, 0x3b, 0x29, 0xf4, 0xb8, 0xda)
|
||||
__CRT_UUID_DECL(IDStorageCustomDecompressionQueue, 0x97179b2f, 0x2c21, 0x49ca, 0x82, 0x91, 0x4e, 0x1b, 0xf4, 0xa1, 0x60, 0xdf)
|
||||
__CRT_UUID_DECL(IDStorageCustomDecompressionQueue1, 0x0D47C6C9, 0xE61A, 0x4706, 0x93, 0xB4, 0x68, 0xBF, 0xE3, 0xF4, 0xAA, 0x4A)
|
||||
__CRT_UUID_DECL(IDStorageFactory, 0x6924ea0c, 0xc3cd, 0x4826, 0xb1, 0x0a, 0xf6, 0x4f, 0x4e, 0xd9, 0x27, 0xc1)
|
||||
__CRT_UUID_DECL(IDStorageFactory1, 0x1e0da17e, 0xb6d9, 0x4c17, 0x91, 0xb0, 0xe5, 0x7a, 0xe9, 0xbd, 0xa1, 0x2e)
|
||||
__CRT_UUID_DECL(IDStorageStatusArray, 0x82397587, 0x7cd5, 0x453b, 0xa0, 0x2e, 0x31, 0x37, 0x9b, 0xd6, 0x46, 0x56)
|
||||
__CRT_UUID_DECL(IDStorageQueue, 0xcfdbd83f, 0x9e06, 0x4fda, 0x8e, 0xa5, 0x69, 0x04, 0x21, 0x37, 0xf4, 0x9b)
|
||||
__CRT_UUID_DECL(IDStorageQueue1, 0xdd2f482c, 0x5eff, 0x41e8, 0x9c, 0x9e, 0xd2, 0x37, 0x4b, 0x27, 0x81, 0x28)
|
||||
__CRT_UUID_DECL(IDStorageQueue2, 0xb1c9d643, 0x3a49, 0x44a2, 0xb4, 0x6f, 0x65, 0x36, 0x49, 0x47, 0x0d, 0x18)
|
||||
__CRT_UUID_DECL(IDStorageQueue3, 0xdeb54c52, 0xeca8, 0x46b3, 0x82, 0xa7, 0x03, 0x1b, 0x72, 0x26, 0x26, 0x53)
|
||||
__CRT_UUID_DECL(IDStorageQueue4, 0x639ff1a7, 0x739e, 0x4291, 0xb6, 0x72, 0xc7, 0x21, 0xc5, 0xf2, 0xa3, 0xda)
|
||||
__CRT_UUID_DECL(IDStorageCompressionCodec, 0x84ef5121, 0x9b43, 0x4d03, 0xb5, 0xc1, 0xcc, 0x34, 0x60, 0x6b, 0x26, 0x2d)
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -2,12 +2,6 @@
|
||||
#define BETTERXEN_SYNTHETIC_STORAGE_H
|
||||
|
||||
#include <windows.h>
|
||||
// Host d3d12.dll returns large structs such as D3D12_RESOURCE_DESC through a
|
||||
// hidden pointer. WIDL_EXPLICIT_AGGREGATE_RETURNS has to be set before <d3d12.h>
|
||||
// is parsed. A #define in this header is too late if the translation unit
|
||||
// included <d3d12.h> already. The xcrdapi and test_xcrdapi targets pass it as
|
||||
// a compile definition. GetHeapProperties is an HRESULT with out-parameters
|
||||
// and does not use that aggregate-return ABI.
|
||||
#include <d3d12.h>
|
||||
#include <unknwn.h>
|
||||
|
||||
@@ -32,20 +26,9 @@ struct Status : IUnknown {
|
||||
virtual HRESULT STDMETHODCALLTYPE GetResult(UINT index) = 0;
|
||||
};
|
||||
|
||||
// BetterXen-defined request. Borrowed CPU pointers stay valid until completion.
|
||||
// Requests keep source and destination buffers borrowed until completion.
|
||||
// File requests retain a duplicate of the file handle when enqueued.
|
||||
// Exactly one of `file` or `source` may be non-null.
|
||||
// A non-zero `size` needs exactly one of `destination` (CPU memory) or `resource`
|
||||
// (an ID3D12Resource buffer written at `resource_offset`). CPU-visible heaps are
|
||||
// mapped. A default heap is copied on the device GetDevice returns and must be
|
||||
// in D3D12_RESOURCE_STATE_COMMON across that copy.
|
||||
// BX_XCRDAPI_COPY_TIMEOUT_MS is the staged-copy wait in milliseconds. Unset,
|
||||
// empty, or non-numeric values use 10000. Numeric values clamp to 0..60000.
|
||||
// BX_XCRDAPI_DEFER_COPY=1 holds the copy queue on a private fence until that
|
||||
// wait has been decided, so a 0 ms timeout observes an unconfirmed completion
|
||||
// instead of racing a fast GPU, then lets the copy finish. An unconfirmed
|
||||
// completion keeps the destination and the copy's GPU objects alive.
|
||||
// `compression` values are BetterXen-defined selectors, not an Xbox enum.
|
||||
// Exactly one of `file` or `source` may be non-null; setting both returns E_INVALIDARG.
|
||||
struct Request {
|
||||
File* file;
|
||||
UINT64 file_offset;
|
||||
@@ -53,15 +36,8 @@ struct Request {
|
||||
void* destination;
|
||||
DWORD size;
|
||||
UINT compression;
|
||||
ID3D12Resource* resource = nullptr;
|
||||
UINT64 resource_offset = 0;
|
||||
};
|
||||
|
||||
inline constexpr UINT compression_none = 0;
|
||||
inline constexpr UINT compression_lz = 1;
|
||||
inline constexpr UINT compression_bcpack = 2;
|
||||
inline constexpr UINT compression_gdeflate = 3;
|
||||
|
||||
struct ErrorRecord {
|
||||
HRESULT first_error;
|
||||
UINT64 failure_count;
|
||||
|
||||
+28
-878
File diff suppressed because it is too large.
Load diff
@@ -1,9 +1,6 @@
|
||||
bx_add_shim_dll(xgameruntime xgameruntime xgameruntime.def
|
||||
xgameruntime.cpp
|
||||
task_queue.cpp
|
||||
com_dispatch.cpp
|
||||
game_save.cpp
|
||||
package.cpp
|
||||
)
|
||||
target_link_libraries(xgameruntime PRIVATE bx_runtime_veh kernel32)
|
||||
target_compile_options(xgameruntime PRIVATE -fexceptions)
|
||||
@@ -1,837 +0,0 @@
|
||||
/*
|
||||
* Clean-room COM IUnknown vtable dispatch for xgameruntime.dll!QueryApiImpl (#456).
|
||||
*
|
||||
* Provenance: Interface identifiers, IUnknown inheritance, and vtable slot indices were
|
||||
* established via clean-room black-box interoperability testing against Microsoft's publicly
|
||||
* distributed PC GDK NuGet package (Microsoft.GDK.Windows 2610.0.9661, nuget.org) using an
|
||||
* independently authored synthetic caller invoking public documented GDK APIs. No Microsoft
|
||||
* source code or binary code is copied or bundled.
|
||||
*
|
||||
* XGameSave and XPackage class ids, interface ids, and vtable order are separate from that
|
||||
* work. Those facts are from https://github.com/xodus-gaming/xgameruntime-docs commit
|
||||
* 7090008692569aa6081e30dfdd9de58237741e24. Function signatures follow the public Microsoft
|
||||
* Learn GDK reference (learn.microsoft.com/gaming/gdk). No text from either source is copied.
|
||||
*/
|
||||
#include "com_dispatch.h"
|
||||
|
||||
#include "runtime_internal.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "task_queue.h"
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI XTaskQueueCreate(bx::gdk::DispatchMode, bx::gdk::DispatchMode, void**);
|
||||
void WINAPI XTaskQueueCloseHandle(void*);
|
||||
bool WINAPI XTaskQueueDispatch(void*, bx::gdk::Port, uint32_t);
|
||||
HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLBACK*)(void*, bool));
|
||||
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
|
||||
|
||||
HRESULT WINAPI XAsyncGetStatus(void*, bool);
|
||||
HRESULT WINAPI XAsyncGetResultSize(void*, size_t*);
|
||||
void WINAPI XAsyncCancel(void*);
|
||||
|
||||
HRESULT WINAPI XUserAddAsync(uint32_t, void*);
|
||||
HRESULT WINAPI XUserAddResult(void*, void**);
|
||||
void WINAPI XUserCloseHandle(void*);
|
||||
HRESULT WINAPI XUserGetId(void*, uint64_t*);
|
||||
HRESULT WINAPI XUserGetGamertag(void*, uint32_t, size_t, char*, size_t*);
|
||||
HRESULT WINAPI XUserGetTokenAndSignatureAsync(void*, uint32_t, const char*, const char*, size_t, const void*, size_t,
|
||||
const uint8_t*, void*);
|
||||
HRESULT WINAPI XUserGetTokenAndSignatureResultSize(void*, size_t*);
|
||||
HRESULT WINAPI XUserGetTokenAndSignatureResult(void*, size_t, void*, void**, size_t*);
|
||||
HRESULT WINAPI XUserResolvePrivilegeWithUiAsync(void*, uint32_t, uint32_t, void*);
|
||||
HRESULT WINAPI XUserResolvePrivilegeWithUiResult(void*);
|
||||
|
||||
HRESULT WINAPI XStoreCreateContext(void*, void**);
|
||||
void WINAPI XStoreCloseContextHandle(void*);
|
||||
HRESULT WINAPI XStoreQueryGameLicenseAsync(void*, void*);
|
||||
HRESULT WINAPI XStoreQueryGameLicenseResult(void*, void*);
|
||||
HRESULT WINAPI XStoreAcquireLicenseForPackageAsync(void*, const char*, void*);
|
||||
HRESULT WINAPI XStoreAcquireLicenseForPackageResult(void*, void**);
|
||||
HRESULT WINAPI XStoreAcquireLicenseForDurablesAsync(void*, const char*, void*);
|
||||
HRESULT WINAPI XStoreAcquireLicenseForDurablesResult(void*, void**);
|
||||
HRESULT WINAPI XStoreQueryEntitledProductsAsync(void*, uint32_t, uint32_t, void*);
|
||||
HRESULT WINAPI XStoreQueryEntitledProductsResult(void*, void**);
|
||||
HRESULT WINAPI XStoreQueryAssociatedProductsAsync(void*, uint32_t, uint32_t, void*);
|
||||
HRESULT WINAPI XStoreQueryAssociatedProductsResult(void*, void**);
|
||||
|
||||
HRESULT WINAPI XSystemGetConsoleId(size_t, char*, size_t*);
|
||||
uint32_t WINAPI XSystemGetDeviceType();
|
||||
HRESULT WINAPI XSystemGetXboxLiveSandboxId(size_t, char*, size_t*);
|
||||
|
||||
HRESULT WINAPI XPersistentLocalStorageGetPathSize(size_t*);
|
||||
HRESULT WINAPI XPersistentLocalStorageGetPath(size_t, char*, size_t*);
|
||||
HRESULT WINAPI XPersistentLocalStorageGetSpaceInfo(void*);
|
||||
|
||||
HRESULT WINAPI XGameUiShowPlayerProfileCardAsync(void*, uint64_t, void*);
|
||||
HRESULT WINAPI XGameUiShowTextEntryAsync(const char*, const char*, const char*, uint32_t, uint32_t, void*);
|
||||
HRESULT WINAPI XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync(void*);
|
||||
HRESULT WINAPI XNetworkingQuerySecurityInformationForUrlAsync(const char*, void*);
|
||||
} // extern "C"
|
||||
|
||||
namespace bx::gdk {
|
||||
namespace {
|
||||
|
||||
constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
|
||||
|
||||
// Public Microsoft.GDK.Windows 2610.0.9661 QueryApiImpl class & interface identifiers.
|
||||
constexpr GUID kCoreGuid = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
|
||||
constexpr GUID kFeatureGuid = {0x8836FE87, 0xEDB9, 0x4FE3, {0x8D, 0xAD, 0x05, 0xF0, 0xD2, 0xCD, 0x5B, 0x40}};
|
||||
constexpr GUID kSystemClsid = {0xE349BD1A, 0xFC20, 0x4E40, {0xB9, 0x9C, 0x41, 0x78, 0xCC, 0x6B, 0x40, 0x9F}};
|
||||
constexpr GUID kSystemIid = {0x1861CF2E, 0xE18B, 0x4834, {0xA9, 0xF5, 0xB4, 0xA4, 0xE6, 0xEF, 0xB4, 0xCF}};
|
||||
constexpr GUID kErrorGuid = {0x8CA467F7, 0x22E8, 0x4096, {0x84, 0x56, 0xBB, 0x8A, 0xA1, 0x3F, 0x79, 0xD8}};
|
||||
constexpr GUID kPlsClsid = {0xF4FAF4D4, 0x2D04, 0x4FCE, {0xB3, 0xE0, 0x47, 0x4A, 0x71, 0x3A, 0x3E, 0x84}};
|
||||
constexpr GUID kPlsIid = {0x41A4E10C, 0x5A7E, 0x41D9, {0x8C, 0x37, 0x37, 0xBD, 0xE6, 0x2A, 0x07, 0xD6}};
|
||||
constexpr GUID kUserClsid = {0x01ACD177, 0x91F9, 0x4763, {0xA3, 0x8E, 0xCC, 0xBB, 0x55, 0xCE, 0x32, 0xE0}};
|
||||
constexpr GUID kUserGamertagIid = {0xCEF4FAC0, 0x7676, 0x4A94, {0xA1, 0x19, 0x4C, 0x43, 0xF9, 0xEB, 0x5B, 0x74}};
|
||||
constexpr GUID kStoreClsid = {0x0DD112AC, 0x7C24, 0x448C, {0xB9, 0x2B, 0x39, 0x60, 0xFB, 0x5B, 0xD3, 0x0C}};
|
||||
constexpr GUID kStoreIid = {0xB09D803C, 0x2414, 0x4A05, {0x82, 0xC6, 0x66, 0xDF, 0xDC, 0x9E, 0x9A, 0x44}};
|
||||
constexpr GUID kStoreDurablesIid = {0x2D42FEA5, 0xE71D, 0x4B76, {0x97, 0xCD, 0xC5, 0x0A, 0xFB, 0xB3, 0xAE, 0x5D}};
|
||||
constexpr GUID kGameUiClsid = {0xDFCD4649, 0x4FF8, 0x4043, {0xBA, 0x07, 0x35, 0xD6, 0x07, 0xDF, 0x98, 0xB0}};
|
||||
constexpr GUID kGameUiIid = {0xEAF669DF, 0x5542, 0x4590, {0x99, 0xA3, 0x8D, 0xC0, 0x61, 0xF8, 0x37, 0xCC}};
|
||||
constexpr GUID kNetworkingClsid = {0x37E56907, 0x2F10, 0x41E8, {0xB7, 0x2F, 0x36, 0xED, 0xB1, 0x85, 0x33, 0x1A}};
|
||||
constexpr GUID kNetworkingIid = {0xBF2346B2, 0x39AF, 0x4658, {0xB5, 0xEA, 0x44, 0x71, 0x3C, 0x7E, 0x83, 0xB3}};
|
||||
constexpr GUID kGameClsid = {0x973A344E, 0x24BF, 0x4D0F, {0x84, 0x57, 0x56, 0xC5, 0x34, 0x89, 0x2B, 0x29}};
|
||||
constexpr GUID kGameIid = {0x2549F142, 0x6419, 0x4A06, {0x97, 0xB5, 0x93, 0x1A, 0xAB, 0x7C, 0x2F, 0x34}};
|
||||
|
||||
bool guid_eq(const GUID& a, const GUID& b) {
|
||||
return std::memcmp(&a, &b, sizeof(GUID)) == 0;
|
||||
}
|
||||
|
||||
struct ComSingleton {
|
||||
const void* const* vtbl;
|
||||
const GUID* iid;
|
||||
const char* name;
|
||||
};
|
||||
|
||||
HRESULT WINAPI com_query_interface(void* self, const GUID* riid, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!riid) return E_INVALIDARG;
|
||||
auto* obj = static_cast<ComSingleton*>(self);
|
||||
if (guid_eq(*riid, kIUnknown) || guid_eq(*riid, *obj->iid)) {
|
||||
*out = obj;
|
||||
return S_OK;
|
||||
}
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
ULONG WINAPI com_add_ref(void*) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
ULONG WINAPI com_release(void*) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
template <size_t Slot>
|
||||
HRESULT WINAPI com_unimpl_slot(void* self) {
|
||||
auto* obj = static_cast<const ComSingleton*>(self);
|
||||
char method[32];
|
||||
std::snprintf(method, sizeof(method), "slot_%zu", Slot);
|
||||
BX_VTABLE_STUB_LOG(obj ? obj->name : "IXGameRuntime", static_cast<uint32_t>(Slot), method);
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
template <size_t N, size_t... Is>
|
||||
constexpr std::array<const void*, N> make_default_vtbl_impl(std::index_sequence<Is...>) {
|
||||
return {((Is == 0) ? reinterpret_cast<const void*>(&com_query_interface)
|
||||
: (Is == 1) ? reinterpret_cast<const void*>(&com_add_ref)
|
||||
: (Is == 2) ? reinterpret_cast<const void*>(&com_release)
|
||||
: reinterpret_cast<const void*>(&com_unimpl_slot<Is>))...};
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
std::array<const void*, N> make_default_vtbl() {
|
||||
return make_default_vtbl_impl<N>(std::make_index_sequence<N>{});
|
||||
}
|
||||
|
||||
// --- Core (XAsync + XTaskQueue + XThread) ---
|
||||
|
||||
thread_local bool tls_time_sensitive = false;
|
||||
|
||||
HRESULT WINAPI core_async_get_status(void*, void* async, bool wait) {
|
||||
return XAsyncGetStatus(async, wait);
|
||||
}
|
||||
HRESULT WINAPI core_async_get_result_size(void*, void* async, size_t* size) {
|
||||
return XAsyncGetResultSize(async, size);
|
||||
}
|
||||
void WINAPI core_async_cancel(void*, void* async) {
|
||||
XAsyncCancel(async);
|
||||
}
|
||||
HRESULT WINAPI core_tq_create(void*, DispatchMode work, DispatchMode comp, void** out) {
|
||||
return XTaskQueueCreate(work, comp, out);
|
||||
}
|
||||
bool WINAPI core_tq_dispatch(void*, void* queue, Port port, uint32_t timeout) {
|
||||
return XTaskQueueDispatch(queue, port, timeout);
|
||||
}
|
||||
void WINAPI core_tq_close(void*, void* queue) {
|
||||
XTaskQueueCloseHandle(queue);
|
||||
}
|
||||
HRESULT WINAPI core_tq_submit(void*, void* queue, Port port, void* ctx, void (CALLBACK* cb)(void*, bool)) {
|
||||
return XTaskQueueSubmitCallback(queue, port, ctx, cb);
|
||||
}
|
||||
HRESULT WINAPI core_tq_submit_delayed(void*, void* queue, Port port, uint32_t delay_ms, void* ctx,
|
||||
void (CALLBACK* cb)(void*, bool)) {
|
||||
if (delay_ms > 0) {
|
||||
BX_VTABLE_STUB_LOG("IXGameRuntimeCore", 19, "XTaskQueueSubmitDelayedCallback(nonzero_delay)");
|
||||
}
|
||||
return XTaskQueueSubmitCallback(queue, port, ctx, cb);
|
||||
}
|
||||
bool WINAPI core_tq_get_process(void*, void** out) {
|
||||
return XTaskQueueGetCurrentProcessTaskQueue(out);
|
||||
}
|
||||
HRESULT WINAPI core_thread_set_time_sensitive(void*, bool is_ts) {
|
||||
tls_time_sensitive = is_ts;
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI core_thread_verify_not_time_sensitive(void*) {
|
||||
return tls_time_sensitive ? E_FAIL : S_OK;
|
||||
}
|
||||
HRESULT WINAPI core_runtime_guard_hook(void*, uint32_t, void*) {
|
||||
// Invoked by public GDK static thunks before subsystem dispatch.
|
||||
return S_OK;
|
||||
}
|
||||
bool WINAPI core_thread_is_time_sensitive(void*) {
|
||||
return tls_time_sensitive;
|
||||
}
|
||||
|
||||
const std::array<const void*, 36> kCoreVtbl = [] {
|
||||
auto v = make_default_vtbl<36>();
|
||||
v[3] = reinterpret_cast<const void*>(&core_async_get_status);
|
||||
v[4] = reinterpret_cast<const void*>(&core_async_get_result_size);
|
||||
v[5] = reinterpret_cast<const void*>(&core_async_cancel);
|
||||
v[12] = reinterpret_cast<const void*>(&core_tq_create);
|
||||
v[16] = reinterpret_cast<const void*>(&core_tq_dispatch);
|
||||
v[17] = reinterpret_cast<const void*>(&core_tq_close);
|
||||
v[18] = reinterpret_cast<const void*>(&core_tq_submit);
|
||||
v[19] = reinterpret_cast<const void*>(&core_tq_submit_delayed);
|
||||
v[25] = reinterpret_cast<const void*>(&core_tq_get_process);
|
||||
v[27] = reinterpret_cast<const void*>(&core_thread_set_time_sensitive);
|
||||
v[28] = reinterpret_cast<const void*>(&core_thread_verify_not_time_sensitive);
|
||||
v[29] = reinterpret_cast<const void*>(&core_runtime_guard_hook);
|
||||
v[30] = reinterpret_cast<const void*>(&core_thread_is_time_sensitive);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kCoreObj{kCoreVtbl.data(), &kCoreGuid, "IXGameRuntimeCore"};
|
||||
|
||||
// --- XGameRuntimeIsFeatureAvailable ---
|
||||
|
||||
bool WINAPI feature_is_available(void*, uint32_t feature) {
|
||||
// XGameRuntimeFeature enum values from public XGameRuntimeFeature.h.
|
||||
switch (feature) {
|
||||
case 2: // XAsync
|
||||
case 5: // XGame
|
||||
case 8: // XGameUI
|
||||
case 10: // XNetworking
|
||||
case 12: // XPersistentLocalStorage
|
||||
case 14: // XStore
|
||||
case 15: // XSystem
|
||||
case 16: // XTaskQueue
|
||||
case 17: // XThread
|
||||
case 18: // XUser
|
||||
case 19: // XError
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const std::array<const void*, 8> kFeatureVtbl = [] {
|
||||
auto v = make_default_vtbl<8>();
|
||||
v[3] = reinterpret_cast<const void*>(&feature_is_available);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kFeatureObj{kFeatureVtbl.data(), &kFeatureGuid, "IXGameRuntimeFeature"};
|
||||
|
||||
// --- XSystem ---
|
||||
|
||||
HRESULT WINAPI sys_get_console_id(void*, size_t sz, char* out, size_t* used) {
|
||||
return XSystemGetConsoleId(sz, out, used);
|
||||
}
|
||||
HRESULT WINAPI sys_get_sandbox_id(void*, size_t sz, char* out, size_t* used) {
|
||||
return XSystemGetXboxLiveSandboxId(sz, out, used);
|
||||
}
|
||||
HRESULT WINAPI sys_get_app_device_id(void*, size_t sz, char* out, size_t* used) {
|
||||
constexpr char kDeviceId[] = "BX-OFFLINE-APP-DEVICE-000000000001";
|
||||
if (used) *used = 0;
|
||||
if (!out) return E_POINTER;
|
||||
const size_t req = sizeof(kDeviceId);
|
||||
if (sz < req) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
|
||||
std::memcpy(out, kDeviceId, req);
|
||||
if (used) *used = req;
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI sys_handle_track(void*, void*, void*) {
|
||||
return S_OK;
|
||||
}
|
||||
bool WINAPI sys_is_handle_valid(void*, void* handle) {
|
||||
return handle != nullptr;
|
||||
}
|
||||
void WINAPI sys_allow_full_bandwidth(void*, bool) {}
|
||||
|
||||
const std::array<const void*, 12> kSystemVtbl = [] {
|
||||
auto v = make_default_vtbl<12>();
|
||||
v[3] = reinterpret_cast<const void*>(&sys_get_console_id);
|
||||
v[4] = reinterpret_cast<const void*>(&sys_get_sandbox_id);
|
||||
v[5] = reinterpret_cast<const void*>(&sys_get_app_device_id);
|
||||
v[6] = reinterpret_cast<const void*>(&sys_handle_track);
|
||||
v[7] = reinterpret_cast<const void*>(&sys_is_handle_valid);
|
||||
v[8] = reinterpret_cast<const void*>(&sys_allow_full_bandwidth);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kSystemObj{kSystemVtbl.data(), &kSystemIid, "IXSystem"};
|
||||
|
||||
// --- XError ---
|
||||
|
||||
void WINAPI err_set_callback(void*, void*, void*) {}
|
||||
void WINAPI err_set_options(void*, uint32_t, uint32_t) {}
|
||||
|
||||
/*
|
||||
* IXError slot 3. xodus-gaming/xgameruntime-docs (commit 7090008) lists this slot as unknown.
|
||||
* Its behaviour here comes from the #492 review's interop observation (atesahmet0,
|
||||
* 2026-11-26): the GDK's static library calls it before some subsystem calls, for example
|
||||
* XPackageMount, and continues only when it returns false. The default stub returned E_NOTIMPL,
|
||||
* whose low byte reads as true and stopped those calls. The parameters are not known, so none
|
||||
* are read. It is logged once so the call stays visible in `bx-cli trace`.
|
||||
*/
|
||||
bool WINAPI err_slot3(void*) {
|
||||
static std::atomic<bool> logged{false};
|
||||
if (!logged.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "IXError_slot3", "returning false (continue); arguments not read");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::array<const void*, 8> kErrorVtbl = [] {
|
||||
auto v = make_default_vtbl<8>();
|
||||
v[3] = reinterpret_cast<const void*>(&err_slot3);
|
||||
v[4] = reinterpret_cast<const void*>(&err_set_callback);
|
||||
v[5] = reinterpret_cast<const void*>(&err_set_options);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kErrorObj{kErrorVtbl.data(), &kErrorGuid, "IXError"};
|
||||
|
||||
// --- XPersistentLocalStorage ---
|
||||
|
||||
HRESULT WINAPI pls_get_path_size(void*, size_t* sz) {
|
||||
return XPersistentLocalStorageGetPathSize(sz);
|
||||
}
|
||||
HRESULT WINAPI pls_get_path(void*, size_t sz, char* out, size_t* used) {
|
||||
return XPersistentLocalStorageGetPath(sz, out, used);
|
||||
}
|
||||
HRESULT WINAPI pls_get_space_info(void*, void* info) {
|
||||
return XPersistentLocalStorageGetSpaceInfo(info);
|
||||
}
|
||||
|
||||
const std::array<const void*, 12> kPlsVtbl = [] {
|
||||
auto v = make_default_vtbl<12>();
|
||||
v[3] = reinterpret_cast<const void*>(&pls_get_path_size);
|
||||
v[4] = reinterpret_cast<const void*>(&pls_get_path);
|
||||
v[5] = reinterpret_cast<const void*>(&pls_get_space_info);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kPlsObj{kPlsVtbl.data(), &kPlsIid, "IXPersistentLocalStorage"};
|
||||
|
||||
// --- XUser ---
|
||||
|
||||
std::mutex user_event_mutex;
|
||||
uint64_t next_user_event_token = 1;
|
||||
std::unordered_set<uint64_t> user_event_tokens;
|
||||
|
||||
void WINAPI user_close_handle(void*, void* h) {
|
||||
XUserCloseHandle(h);
|
||||
}
|
||||
int32_t WINAPI user_compare(void*, void* u1, void* u2) {
|
||||
if (u1 == u2) return 0;
|
||||
return reinterpret_cast<uintptr_t>(u1) < reinterpret_cast<uintptr_t>(u2) ? -1 : 1;
|
||||
}
|
||||
HRESULT WINAPI user_get_max_users(void*, uint32_t* max_users) {
|
||||
if (!max_users) return E_POINTER;
|
||||
*max_users = 1;
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI user_add_async(void*, uint32_t opts, void* async) {
|
||||
return XUserAddAsync(opts, async);
|
||||
}
|
||||
HRESULT WINAPI user_add_result(void*, void* async, void** out) {
|
||||
return XUserAddResult(async, out);
|
||||
}
|
||||
HRESULT WINAPI user_get_local_id(void*, void* user, uint64_t* local_id) {
|
||||
if (!local_id) return E_POINTER;
|
||||
if (!user) return E_INVALIDARG;
|
||||
*local_id = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(user));
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI user_get_id(void*, void* user, uint64_t* id) {
|
||||
return XUserGetId(user, id);
|
||||
}
|
||||
HRESULT WINAPI user_get_is_guest(void*, void* user, bool* is_guest) {
|
||||
if (!is_guest) return E_POINTER;
|
||||
if (!user) return E_INVALIDARG;
|
||||
*is_guest = false;
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI user_get_state(void*, void* user, uint32_t* state) {
|
||||
if (!state) return E_POINTER;
|
||||
if (!user) return E_INVALIDARG;
|
||||
*state = 0; // XUserState::SignedIn
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI user_get_age_group(void*, void* user, uint32_t* age_group) {
|
||||
if (!age_group) return E_POINTER;
|
||||
if (!user) return E_INVALIDARG;
|
||||
*age_group = 3; // XUserAgeGroup::Adult
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI user_check_privilege(void*, void* user, uint32_t, uint32_t, bool* has_priv, uint32_t* deny_reason) {
|
||||
if (!has_priv) return E_POINTER;
|
||||
if (!user) return E_INVALIDARG;
|
||||
*has_priv = true;
|
||||
if (deny_reason) *deny_reason = 0; // XUserPrivilegeDenyReason::None
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI user_resolve_priv_async(void*, void* user, uint32_t opts, uint32_t priv, void* async) {
|
||||
return XUserResolvePrivilegeWithUiAsync(user, opts, priv, async);
|
||||
}
|
||||
HRESULT WINAPI user_resolve_priv_result(void*, void* async) {
|
||||
return XUserResolvePrivilegeWithUiResult(async);
|
||||
}
|
||||
HRESULT WINAPI user_token_async(void*, void* user, uint32_t opts, const char* method, const char* url,
|
||||
size_t hdr_cnt, const void* hdrs, size_t body_sz, const uint8_t* body, void* async) {
|
||||
return XUserGetTokenAndSignatureAsync(user, opts, method, url, hdr_cnt, hdrs, body_sz, body, async);
|
||||
}
|
||||
HRESULT WINAPI user_token_result_size(void*, void* async, size_t* sz) {
|
||||
return XUserGetTokenAndSignatureResultSize(async, sz);
|
||||
}
|
||||
HRESULT WINAPI user_token_result(void*, void* async, size_t sz, void* buf, void** res, size_t* used) {
|
||||
return XUserGetTokenAndSignatureResult(async, sz, buf, res, used);
|
||||
}
|
||||
HRESULT WINAPI user_register_change_event(void*, void*, void*, void* callback, uint64_t* token) {
|
||||
if (!token) return E_POINTER;
|
||||
if (!callback) return E_INVALIDARG;
|
||||
std::lock_guard lock(user_event_mutex);
|
||||
const uint64_t id = next_user_event_token++;
|
||||
user_event_tokens.insert(id);
|
||||
*token = id;
|
||||
return S_OK;
|
||||
}
|
||||
bool WINAPI user_unregister_change_event(void*, uint64_t token, bool) {
|
||||
std::lock_guard lock(user_event_mutex);
|
||||
return user_event_tokens.erase(token) > 0;
|
||||
}
|
||||
HRESULT WINAPI user_get_gamertag(void*, void* user, uint32_t comp, size_t sz, char* out, size_t* used) {
|
||||
return XUserGetGamertag(user, comp, sz, out, used);
|
||||
}
|
||||
|
||||
const std::array<const void*, 64> kUserVtbl = [] {
|
||||
auto v = make_default_vtbl<64>();
|
||||
v[4] = reinterpret_cast<const void*>(&user_close_handle);
|
||||
v[5] = reinterpret_cast<const void*>(&user_compare);
|
||||
v[6] = reinterpret_cast<const void*>(&user_get_max_users);
|
||||
v[7] = reinterpret_cast<const void*>(&user_add_async);
|
||||
v[8] = reinterpret_cast<const void*>(&user_add_result);
|
||||
v[9] = reinterpret_cast<const void*>(&user_get_local_id);
|
||||
v[11] = reinterpret_cast<const void*>(&user_get_id);
|
||||
v[13] = reinterpret_cast<const void*>(&user_get_is_guest);
|
||||
v[14] = reinterpret_cast<const void*>(&user_get_state);
|
||||
v[19] = reinterpret_cast<const void*>(&user_get_age_group);
|
||||
v[20] = reinterpret_cast<const void*>(&user_check_privilege);
|
||||
v[21] = reinterpret_cast<const void*>(&user_resolve_priv_async);
|
||||
v[22] = reinterpret_cast<const void*>(&user_resolve_priv_result);
|
||||
v[23] = reinterpret_cast<const void*>(&user_token_async);
|
||||
v[24] = reinterpret_cast<const void*>(&user_token_result_size);
|
||||
v[25] = reinterpret_cast<const void*>(&user_token_result);
|
||||
v[33] = reinterpret_cast<const void*>(&user_register_change_event);
|
||||
v[34] = reinterpret_cast<const void*>(&user_unregister_change_event);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kUserObj{kUserVtbl.data(), &kUserClsid, "IXUser"};
|
||||
|
||||
const std::array<const void*, 8> kUserGamertagVtbl = [] {
|
||||
auto v = make_default_vtbl<8>();
|
||||
v[3] = reinterpret_cast<const void*>(&user_get_gamertag);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kUserGamertagObj{kUserGamertagVtbl.data(), &kUserGamertagIid, "IXUserGamertag"};
|
||||
|
||||
// --- XStore ---
|
||||
|
||||
HRESULT WINAPI store_create_ctx(void*, void* user, void** out) {
|
||||
return XStoreCreateContext(user, out);
|
||||
}
|
||||
void WINAPI store_close_ctx(void*, void* ctx) {
|
||||
XStoreCloseContextHandle(ctx);
|
||||
}
|
||||
HRESULT WINAPI store_assoc_async(void*, void* ctx, uint32_t pf, uint32_t max_items, void* async) {
|
||||
return XStoreQueryAssociatedProductsAsync(ctx, pf, max_items, async);
|
||||
}
|
||||
HRESULT WINAPI store_assoc_result(void*, void* async, void** out) {
|
||||
return XStoreQueryAssociatedProductsResult(async, out);
|
||||
}
|
||||
HRESULT WINAPI store_entitled_async(void*, void* ctx, uint32_t pf, uint32_t max_items, void* async) {
|
||||
return XStoreQueryEntitledProductsAsync(ctx, pf, max_items, async);
|
||||
}
|
||||
HRESULT WINAPI store_entitled_result(void*, void* async, void** out) {
|
||||
return XStoreQueryEntitledProductsResult(async, out);
|
||||
}
|
||||
HRESULT WINAPI store_pkg_lic_async(void*, void* ctx, const char* id, void* async) {
|
||||
return XStoreAcquireLicenseForPackageAsync(ctx, id, async);
|
||||
}
|
||||
HRESULT WINAPI store_pkg_lic_result(void*, void* async, void** out) {
|
||||
return XStoreAcquireLicenseForPackageResult(async, out);
|
||||
}
|
||||
HRESULT WINAPI store_game_lic_async(void*, void* ctx, void* async) {
|
||||
return XStoreQueryGameLicenseAsync(ctx, async);
|
||||
}
|
||||
HRESULT WINAPI store_game_lic_result(void*, void* async, void* out) {
|
||||
return XStoreQueryGameLicenseResult(async, out);
|
||||
}
|
||||
HRESULT WINAPI store_dur_lic_async(void*, void* ctx, const char* id, void* async) {
|
||||
return XStoreAcquireLicenseForDurablesAsync(ctx, id, async);
|
||||
}
|
||||
HRESULT WINAPI store_dur_lic_result(void*, void* async, void** out) {
|
||||
return XStoreAcquireLicenseForDurablesResult(async, out);
|
||||
}
|
||||
|
||||
const std::array<const void*, 40> kStoreVtbl = [] {
|
||||
auto v = make_default_vtbl<40>();
|
||||
v[3] = reinterpret_cast<const void*>(&store_create_ctx);
|
||||
v[4] = reinterpret_cast<const void*>(&store_close_ctx);
|
||||
v[5] = reinterpret_cast<const void*>(&store_assoc_async);
|
||||
v[6] = reinterpret_cast<const void*>(&store_assoc_result);
|
||||
v[9] = reinterpret_cast<const void*>(&store_entitled_async);
|
||||
v[10] = reinterpret_cast<const void*>(&store_entitled_result);
|
||||
v[20] = reinterpret_cast<const void*>(&store_pkg_lic_async);
|
||||
v[21] = reinterpret_cast<const void*>(&store_pkg_lic_result);
|
||||
v[28] = reinterpret_cast<const void*>(&store_game_lic_async);
|
||||
v[29] = reinterpret_cast<const void*>(&store_game_lic_result);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kStoreObj{kStoreVtbl.data(), &kStoreIid, "IXStore"};
|
||||
|
||||
const std::array<const void*, 80> kStoreDurablesVtbl = [] {
|
||||
auto v = make_default_vtbl<80>();
|
||||
v[71] = reinterpret_cast<const void*>(&store_dur_lic_async);
|
||||
v[72] = reinterpret_cast<const void*>(&store_dur_lic_result);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kStoreDurablesObj{kStoreDurablesVtbl.data(), &kStoreDurablesIid, "IXStoreDurables"};
|
||||
|
||||
// --- XGameUi ---
|
||||
|
||||
HRESULT WINAPI gameui_profile_async(void*, void* user, uint64_t xuid, void* async) {
|
||||
return XGameUiShowPlayerProfileCardAsync(user, xuid, async);
|
||||
}
|
||||
HRESULT WINAPI gameui_text_async(void*, const char* title, const char* desc, const char* def, uint32_t scope,
|
||||
uint32_t max_chars, void* async) {
|
||||
return XGameUiShowTextEntryAsync(title, desc, def, scope, max_chars, async);
|
||||
}
|
||||
|
||||
const std::array<const void*, 32> kGameUiVtbl = [] {
|
||||
auto v = make_default_vtbl<32>();
|
||||
v[7] = reinterpret_cast<const void*>(&gameui_profile_async);
|
||||
v[17] = reinterpret_cast<const void*>(&gameui_text_async);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kGameUiObj{kGameUiVtbl.data(), &kGameUiIid, "IXGameUi"};
|
||||
|
||||
// --- XNetworking ---
|
||||
|
||||
struct ConnectivityHint {
|
||||
uint32_t connectivity_level;
|
||||
uint32_t connectivity_cost;
|
||||
uint32_t iana_interface_type;
|
||||
bool network_initialized;
|
||||
bool approaching_data_limit;
|
||||
bool over_data_limit;
|
||||
bool roaming;
|
||||
};
|
||||
static_assert(sizeof(ConnectivityHint) == 16);
|
||||
|
||||
HRESULT WINAPI net_udp_port_async(void*, void* async) {
|
||||
return XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync(async);
|
||||
}
|
||||
HRESULT WINAPI net_sec_info_async(void*, const char* url, void* async) {
|
||||
return XNetworkingQuerySecurityInformationForUrlAsync(url, async);
|
||||
}
|
||||
HRESULT WINAPI net_get_connectivity_hint(void*, ConnectivityHint* hint) {
|
||||
if (!hint) return E_POINTER;
|
||||
// Offline profile: ConnectivityLevelHint::None (1), CostHint::Unrestricted (1).
|
||||
*hint = {1u, 1u, 6u, true, false, false, false};
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const std::array<const void*, 24> kNetworkingVtbl = [] {
|
||||
auto v = make_default_vtbl<24>();
|
||||
v[4] = reinterpret_cast<const void*>(&net_udp_port_async);
|
||||
v[8] = reinterpret_cast<const void*>(&net_sec_info_async);
|
||||
v[15] = reinterpret_cast<const void*>(&net_get_connectivity_hint);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kNetworkingObj{kNetworkingVtbl.data(), &kNetworkingIid, "IXNetworking"};
|
||||
|
||||
// --- XGame ---
|
||||
|
||||
HRESULT WINAPI game_get_xbox_title_id(void*, uint32_t* title_id) {
|
||||
if (!title_id) return E_POINTER;
|
||||
// Synthetic offline title ID for BetterXen runtime.
|
||||
*title_id = 0x42580001u;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const std::array<const void*, 8> kGameVtbl = [] {
|
||||
auto v = make_default_vtbl<8>();
|
||||
v[3] = reinterpret_cast<const void*>(&game_get_xbox_title_id);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kGameObj{kGameVtbl.data(), &kGameIid, "IXGame"};
|
||||
|
||||
// --- XGameSave / XPackage (#468) ---
|
||||
// Ids and inheritance from xodus-gaming/xgameruntime-docs commit
|
||||
// 7090008692569aa6081e30dfdd9de58237741e24.
|
||||
// IXGameSaveImpl uses the class id and lists 27 methods in slots 3-29.
|
||||
// IXGameSaveImpl2 adds 3 XGameSaveFiles methods in slots 30-32.
|
||||
// IXGameSaveImpl3 adds none.
|
||||
// IXPackageImpl lists 32 methods in slots 3-34.
|
||||
// IXPackageImpl2 adds 4 methods in slots 35-38.
|
||||
// IXPackageImpl3 adds 2 methods in slots 39-40.
|
||||
// IXPackageImpl4 adds XPackageGetPackageKind at slot 41.
|
||||
|
||||
constexpr GUID kGameSaveClsid = {0x704C3F58, 0xE629, 0x4CC2, {0xB1, 0x97, 0x30, 0x51, 0x1B, 0x99, 0x6F, 0xE2}};
|
||||
constexpr GUID kGameSaveIid2 = {0x704C3F58, 0xE629, 0x4CC2, {0xB1, 0x97, 0x30, 0x51, 0x1B, 0x99, 0x6E, 0xE2}};
|
||||
constexpr GUID kGameSaveIid3 = {0x1BFFF3AF, 0xF14A, 0x40A3, {0x8E, 0x35, 0x9A, 0xDA, 0x90, 0x65, 0x93, 0xF9}};
|
||||
constexpr GUID kPackageClsid = {0xAF406016, 0xE850, 0x4AA8, {0xA8, 0x8D, 0x2F, 0x3D, 0xCB, 0x9D, 0xAC, 0x7E}};
|
||||
constexpr GUID kPackageIid = {0x3720DE07, 0xE8E4, 0x44A3, {0xAD, 0x32, 0xB3, 0x59, 0xE8, 0xAD, 0xBE, 0x55}};
|
||||
constexpr GUID kPackageIid2 = {0xF92D8712, 0x2B27, 0x4D8A, {0xBF, 0x01, 0x11, 0xA6, 0xF8, 0xE3, 0xEB, 0x42}};
|
||||
constexpr GUID kPackageIid3 = {0xE2A4734B, 0x2F4A, 0x456D, {0xAA, 0x8F, 0xD0, 0x65, 0xE0, 0x4F, 0xB2, 0x09}};
|
||||
constexpr GUID kPackageIid4 = {0x0B9D556E, 0xAB70, 0x43F4, {0xBA, 0xA0, 0x99, 0x99, 0xAC, 0x4C, 0xB0, 0x40}};
|
||||
|
||||
HRESULT WINAPI game_save_query_interface(void* self, const GUID* riid, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!riid) return E_INVALIDARG;
|
||||
if (guid_eq(*riid, kIUnknown) || guid_eq(*riid, kGameSaveClsid) || guid_eq(*riid, kGameSaveIid2) ||
|
||||
guid_eq(*riid, kGameSaveIid3)) {
|
||||
*out = self;
|
||||
return S_OK;
|
||||
}
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
HRESULT WINAPI package_query_interface(void* self, const GUID* riid, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!riid) return E_INVALIDARG;
|
||||
if (guid_eq(*riid, kIUnknown) || guid_eq(*riid, kPackageIid) || guid_eq(*riid, kPackageIid2) ||
|
||||
guid_eq(*riid, kPackageIid3) || guid_eq(*riid, kPackageIid4)) {
|
||||
*out = self;
|
||||
return S_OK;
|
||||
}
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
#define BX_HR(fn, iface, slot, method) \
|
||||
HRESULT WINAPI fn(void*) { \
|
||||
BX_VTABLE_STUB_LOG(iface, static_cast<uint32_t>(slot), method); \
|
||||
return E_NOTIMPL; \
|
||||
}
|
||||
#define BX_VOID(fn, iface, slot, method) \
|
||||
void WINAPI fn(void*) { BX_VTABLE_STUB_LOG(iface, static_cast<uint32_t>(slot), method); }
|
||||
// Bool slots log and return false. The HRESULT bit pattern would look like true to a caller.
|
||||
#define BX_BOOL(fn, iface, slot, method) \
|
||||
bool WINAPI fn(void*) { \
|
||||
BX_VTABLE_STUB_LOG(iface, static_cast<uint32_t>(slot), method); \
|
||||
return false; \
|
||||
}
|
||||
|
||||
BX_HR(gs_quota, "IXGameSaveImpl", 7, "XGameSaveGetRemainingQuota")
|
||||
BX_HR(gs_quota_async, "IXGameSaveImpl", 8, "XGameSaveGetRemainingQuotaAsync")
|
||||
BX_HR(gs_quota_result, "IXGameSaveImpl", 9, "XGameSaveGetRemainingQuotaResult")
|
||||
BX_HR(gs_delete, "IXGameSaveImpl", 10, "XGameSaveDeleteContainer")
|
||||
BX_HR(gs_delete_async, "IXGameSaveImpl", 11, "XGameSaveDeleteContainerAsync")
|
||||
BX_HR(gs_delete_result, "IXGameSaveImpl", 12, "XGameSaveDeleteContainerResult")
|
||||
BX_HR(gs_container_info, "IXGameSaveImpl", 13, "XGameSaveGetContainerInfo")
|
||||
BX_HR(gs_enum_by_name, "IXGameSaveImpl", 15, "XGameSaveEnumerateContainerInfoByName")
|
||||
BX_HR(gs_enum_blobs, "IXGameSaveImpl", 18, "XGameSaveEnumerateBlobInfo")
|
||||
BX_HR(gs_enum_blobs_by_name, "IXGameSaveImpl", 19, "XGameSaveEnumerateBlobInfoByName")
|
||||
BX_HR(gs_blob_delete, "IXGameSaveImpl", 26, "XGameSaveSubmitBlobDelete")
|
||||
BX_HR(gs_files_folder_async, "IXGameSaveImpl2", 30, "XGameSaveFilesGetFolderWithUiAsync")
|
||||
BX_HR(gs_files_folder_result, "IXGameSaveImpl2", 31, "XGameSaveFilesGetFolderWithUiResult")
|
||||
BX_HR(gs_files_quota, "IXGameSaveImpl2", 32, "XGameSaveFilesGetRemainingQuota")
|
||||
|
||||
BX_HR(pk_create_monitor, "IXPackageImpl", 5, "XPackageCreateInstallationMonitor")
|
||||
BX_VOID(pk_close_monitor, "IXPackageImpl", 6, "XPackageCloseInstallationMonitorHandle")
|
||||
BX_VOID(pk_get_progress, "IXPackageImpl", 7, "XPackageGetInstallationProgress")
|
||||
BX_BOOL(pk_update_monitor, "IXPackageImpl", 8, "XPackageUpdateInstallationMonitor")
|
||||
BX_HR(pk_reg_progress, "IXPackageImpl", 9, "XPackageRegisterInstallationProgressChanged")
|
||||
BX_BOOL(pk_unreg_progress, "IXPackageImpl", 10, "XPackageUnregisterInstallationProgressChanged")
|
||||
BX_HR(pk_locale, "IXPackageImpl", 11, "XPackageGetUserLocale")
|
||||
BX_HR(pk_find_chunk, "IXPackageImpl", 12, "XPackageFindChunkAvailability")
|
||||
BX_HR(pk_enum_chunk, "IXPackageImpl", 13, "XPackageEnumerateChunkAvailability")
|
||||
BX_HR(pk_change_order, "IXPackageImpl", 14, "XPackageChangeChunkInstallOrder")
|
||||
BX_HR(pk_install, "IXPackageImpl", 15, "XPackageInstallChunks")
|
||||
BX_HR(pk_install_async, "IXPackageImpl", 16, "XPackageInstallChunksAsync")
|
||||
BX_HR(pk_install_result, "IXPackageImpl", 17, "XPackageInstallChunksResult")
|
||||
BX_HR(pk_estimate, "IXPackageImpl", 18, "XPackageEstimateDownloadSize")
|
||||
BX_HR(pk_uninstall_chunks, "IXPackageImpl", 19, "XPackageUninstallChunks")
|
||||
BX_HR(pk_unknown_20, "IXPackageImpl", 20, "unknown")
|
||||
BX_HR(pk_unknown_21, "IXPackageImpl", 21, "unknown")
|
||||
BX_BOOL(pk_unreg_installed, "IXPackageImpl", 22, "XPackageUnregisterPackageInstalled")
|
||||
BX_HR(pk_unknown_27, "IXPackageImpl", 27, "unknown")
|
||||
BX_HR(pk_enum_packages, "IXPackageImpl", 28, "XPackageEnumeratePackages")
|
||||
BX_HR(pk_reg_installed, "IXPackageImpl", 29, "XPackageRegisterPackageInstalled")
|
||||
BX_HR(pk_write_stats, "IXPackageImpl", 30, "XPackageGetWriteStats")
|
||||
BX_HR(pk_unknown_31, "IXPackageImpl", 31, "unknown")
|
||||
BX_HR(pk_uninstall_uwp, "IXPackageImpl", 32, "XPackageUninstallUWPInstance")
|
||||
BX_HR(pk_enum_features, "IXPackageImpl", 33, "XPackageEnumerateFeatures")
|
||||
BX_HR(pk_uninstall, "IXPackageImpl", 34, "XPackageUninstallPackage")
|
||||
BX_HR(pk_enum_packages_2, "IXPackageImpl2", 35, "XPackageEnumeratePackages")
|
||||
BX_HR(pk_reg_installed_2, "IXPackageImpl2", 36, "XPackageRegisterPackageInstalled")
|
||||
BX_HR(pk_enum_packages_3, "IXPackageImpl3", 39, "XPackageEnumeratePackages")
|
||||
BX_HR(pk_reg_installed_3, "IXPackageImpl3", 40, "XPackageRegisterPackageInstalled")
|
||||
#undef BX_HR
|
||||
#undef BX_VOID
|
||||
#undef BX_BOOL
|
||||
|
||||
const std::array<const void*, 33> kGameSaveVtbl = [] {
|
||||
auto v = make_default_vtbl<33>();
|
||||
v[0] = reinterpret_cast<const void*>(&game_save_query_interface);
|
||||
v[3] = reinterpret_cast<const void*>(&initialize_provider);
|
||||
v[4] = reinterpret_cast<const void*>(&initialize_provider_async);
|
||||
v[5] = reinterpret_cast<const void*>(&initialize_provider_result);
|
||||
v[6] = reinterpret_cast<const void*>(&close_provider);
|
||||
v[7] = reinterpret_cast<const void*>(&gs_quota);
|
||||
v[8] = reinterpret_cast<const void*>(&gs_quota_async);
|
||||
v[9] = reinterpret_cast<const void*>(&gs_quota_result);
|
||||
v[10] = reinterpret_cast<const void*>(&gs_delete);
|
||||
v[11] = reinterpret_cast<const void*>(&gs_delete_async);
|
||||
v[12] = reinterpret_cast<const void*>(&gs_delete_result);
|
||||
v[13] = reinterpret_cast<const void*>(&gs_container_info);
|
||||
v[14] = reinterpret_cast<const void*>(&enumerate_container_info);
|
||||
v[15] = reinterpret_cast<const void*>(&gs_enum_by_name);
|
||||
v[16] = reinterpret_cast<const void*>(&create_container);
|
||||
v[17] = reinterpret_cast<const void*>(&close_container);
|
||||
v[18] = reinterpret_cast<const void*>(&gs_enum_blobs);
|
||||
v[19] = reinterpret_cast<const void*>(&gs_enum_blobs_by_name);
|
||||
v[20] = reinterpret_cast<const void*>(&read_blob_data);
|
||||
v[21] = reinterpret_cast<const void*>(&read_blob_data_async);
|
||||
v[22] = reinterpret_cast<const void*>(&read_blob_data_result);
|
||||
v[23] = reinterpret_cast<const void*>(&create_update);
|
||||
v[24] = reinterpret_cast<const void*>(&close_update);
|
||||
v[25] = reinterpret_cast<const void*>(&submit_blob_write);
|
||||
v[26] = reinterpret_cast<const void*>(&gs_blob_delete);
|
||||
v[27] = reinterpret_cast<const void*>(&submit_update);
|
||||
v[28] = reinterpret_cast<const void*>(&submit_update_async);
|
||||
v[29] = reinterpret_cast<const void*>(&submit_update_result);
|
||||
v[30] = reinterpret_cast<const void*>(&gs_files_folder_async);
|
||||
v[31] = reinterpret_cast<const void*>(&gs_files_folder_result);
|
||||
v[32] = reinterpret_cast<const void*>(&gs_files_quota);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kGameSaveObj{kGameSaveVtbl.data(), &kGameSaveClsid, "IXGameSaveImpl"};
|
||||
|
||||
const std::array<const void*, 42> kPackageVtbl = [] {
|
||||
auto v = make_default_vtbl<42>();
|
||||
v[0] = reinterpret_cast<const void*>(&package_query_interface);
|
||||
v[3] = reinterpret_cast<const void*>(&get_current_process_package_identifier);
|
||||
v[4] = reinterpret_cast<const void*>(&is_packaged_process);
|
||||
v[5] = reinterpret_cast<const void*>(&pk_create_monitor);
|
||||
v[6] = reinterpret_cast<const void*>(&pk_close_monitor);
|
||||
v[7] = reinterpret_cast<const void*>(&pk_get_progress);
|
||||
v[8] = reinterpret_cast<const void*>(&pk_update_monitor);
|
||||
v[9] = reinterpret_cast<const void*>(&pk_reg_progress);
|
||||
v[10] = reinterpret_cast<const void*>(&pk_unreg_progress);
|
||||
v[11] = reinterpret_cast<const void*>(&pk_locale);
|
||||
v[12] = reinterpret_cast<const void*>(&pk_find_chunk);
|
||||
v[13] = reinterpret_cast<const void*>(&pk_enum_chunk);
|
||||
v[14] = reinterpret_cast<const void*>(&pk_change_order);
|
||||
v[15] = reinterpret_cast<const void*>(&pk_install);
|
||||
v[16] = reinterpret_cast<const void*>(&pk_install_async);
|
||||
v[17] = reinterpret_cast<const void*>(&pk_install_result);
|
||||
v[18] = reinterpret_cast<const void*>(&pk_estimate);
|
||||
v[19] = reinterpret_cast<const void*>(&pk_uninstall_chunks);
|
||||
v[20] = reinterpret_cast<const void*>(&pk_unknown_20);
|
||||
v[21] = reinterpret_cast<const void*>(&pk_unknown_21);
|
||||
v[22] = reinterpret_cast<const void*>(&pk_unreg_installed);
|
||||
v[23] = reinterpret_cast<const void*>(&mount);
|
||||
v[24] = reinterpret_cast<const void*>(&get_mount_path_size);
|
||||
v[25] = reinterpret_cast<const void*>(&get_mount_path);
|
||||
v[26] = reinterpret_cast<const void*>(&close_mount_handle);
|
||||
v[27] = reinterpret_cast<const void*>(&pk_unknown_27);
|
||||
v[28] = reinterpret_cast<const void*>(&pk_enum_packages);
|
||||
v[29] = reinterpret_cast<const void*>(&pk_reg_installed);
|
||||
v[30] = reinterpret_cast<const void*>(&pk_write_stats);
|
||||
v[31] = reinterpret_cast<const void*>(&pk_unknown_31);
|
||||
v[32] = reinterpret_cast<const void*>(&pk_uninstall_uwp);
|
||||
v[33] = reinterpret_cast<const void*>(&pk_enum_features);
|
||||
v[34] = reinterpret_cast<const void*>(&pk_uninstall);
|
||||
v[35] = reinterpret_cast<const void*>(&pk_enum_packages_2);
|
||||
v[36] = reinterpret_cast<const void*>(&pk_reg_installed_2);
|
||||
v[37] = reinterpret_cast<const void*>(&mount_with_ui_async);
|
||||
v[38] = reinterpret_cast<const void*>(&mount_with_ui_result);
|
||||
v[39] = reinterpret_cast<const void*>(&pk_enum_packages_3);
|
||||
v[40] = reinterpret_cast<const void*>(&pk_reg_installed_3);
|
||||
v[41] = reinterpret_cast<const void*>(&get_package_kind);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kPackageObj{kPackageVtbl.data(), &kPackageIid4, "IXPackageImpl"};
|
||||
|
||||
struct PublicEntry {
|
||||
const GUID* clsid;
|
||||
const GUID* iid;
|
||||
ComSingleton* obj;
|
||||
};
|
||||
|
||||
const PublicEntry kPublicEntries[] = {
|
||||
{&kCoreGuid, &kCoreGuid, &kCoreObj},
|
||||
{&kFeatureGuid, &kFeatureGuid, &kFeatureObj},
|
||||
{&kSystemClsid, &kSystemIid, &kSystemObj},
|
||||
{&kErrorGuid, &kErrorGuid, &kErrorObj},
|
||||
{&kPlsClsid, &kPlsIid, &kPlsObj},
|
||||
{&kUserClsid, &kUserClsid, &kUserObj},
|
||||
{&kUserClsid, &kUserGamertagIid, &kUserGamertagObj},
|
||||
{&kStoreClsid, &kStoreIid, &kStoreObj},
|
||||
{&kStoreClsid, &kStoreDurablesIid, &kStoreDurablesObj},
|
||||
{&kGameUiClsid, &kGameUiIid, &kGameUiObj},
|
||||
{&kNetworkingClsid, &kNetworkingIid, &kNetworkingObj},
|
||||
{&kGameClsid, &kGameIid, &kGameObj},
|
||||
{&kGameSaveClsid, &kGameSaveClsid, &kGameSaveObj},
|
||||
{&kGameSaveClsid, &kGameSaveIid2, &kGameSaveObj},
|
||||
{&kGameSaveClsid, &kGameSaveIid3, &kGameSaveObj},
|
||||
{&kPackageClsid, &kPackageIid, &kPackageObj},
|
||||
{&kPackageClsid, &kPackageIid2, &kPackageObj},
|
||||
{&kPackageClsid, &kPackageIid3, &kPackageObj},
|
||||
{&kPackageClsid, &kPackageIid4, &kPackageObj},
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
bool query_public_gdk_interface(const GUID* clsid, const GUID* iid, void** out, bool* clsid_known) {
|
||||
*clsid_known = false;
|
||||
for (const auto& entry : kPublicEntries) {
|
||||
if (guid_eq(*clsid, *entry.clsid)) {
|
||||
*clsid_known = true;
|
||||
if (guid_eq(*iid, *entry.iid) || guid_eq(*iid, kIUnknown)) {
|
||||
*out = entry.obj;
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "dispatch public_com=%s", entry.obj->name);
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "QueryApiImpl", detail);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -1,12 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
namespace bx::gdk {
|
||||
|
||||
// Dispatches public Microsoft PC GDK (Microsoft.GDK.Windows 2610.0.9661) COM IUnknown
|
||||
// interfaces queried through QueryApiImpl. Returns true when (clsid, iid) matched and
|
||||
// *out was populated, or sets *clsid_known=true when clsid matched but iid did not.
|
||||
bool query_public_gdk_interface(const GUID* clsid, const GUID* iid, void** out, bool* clsid_known);
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -1,983 +0,0 @@
|
||||
/*
|
||||
* Offline XGameSave over bottle-local storage (#468).
|
||||
*
|
||||
* Reached through QueryApiImpl. The BetterXen synthetic key and its vtable order are in
|
||||
* synthetic_keys.h. Public class and interface ids use the const vtable in com_dispatch.cpp.
|
||||
* Nothing here is exported.
|
||||
*
|
||||
* Public reference (Microsoft Learn, gdk-2610, checked 2026-11-26): the XGameSave members
|
||||
* page and the function and structure pages it links. The signatures, the
|
||||
* XGameSaveContainerInfo / XGameSaveBlobInfo / XGameSaveBlob layouts, the E_GS_* values,
|
||||
* the container-name rules and the 16 MB update limit come from there:
|
||||
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xgamesave/xgamesave_members
|
||||
* No Microsoft header, source or binary was used.
|
||||
*
|
||||
* Storage: each SCID has its own directory, <XPersistentLocalStorage path>\saves\<scid id>,
|
||||
* and each container is one file in it, <container id>.bxgs. Both ids are the 64-bit FNV-1a
|
||||
* hash of the string's bytes (each byte taken as one UTF-16 code unit 0-255) as 16 lowercase
|
||||
* hex digits; neither string is ever used as a path. A submitted update
|
||||
* rewrites the file through a temporary file and MoveFileExW, so an update lands entirely or
|
||||
* not at all. Every read and read-modify-write of a SCID directory holds a named mutex derived
|
||||
* from that directory, so threads and processes sharing a title directory do not lose updates.
|
||||
* The format is BetterXen-defined, little-endian:
|
||||
* u32 magic "BXGS", u32 version 1, str name, str display name, i64 last-modified time_t,
|
||||
* u32 blob count, then per blob: str name, u32 size, size bytes. (str = u32 length + bytes)
|
||||
* A file is valid only if it is consumed exactly, its container name is valid and matches its
|
||||
* file name, no string holds a NUL, and blob names are unique and within the limit below.
|
||||
*
|
||||
* Offline behaviour, where the public pages leave it open:
|
||||
* - There is no service. syncOnDemand has no effect and needsSync is always false.
|
||||
* - The provider needs a live XUser handle and a non-null SCID. Saves are separated by SCID.
|
||||
* - A second write of the same blob in one update fails with E_INVALIDARG (the page allows
|
||||
* one modification per blob per update but names no error).
|
||||
* - "16 MB" for GS_MAX_BLOB_SIZE is read as 16 MiB, enforced on the staged total of blob
|
||||
* names and data.
|
||||
* - GS_MAX_BLOB_NAME_SIZE has no published value. BetterXen limits blob names to 256 bytes.
|
||||
* - A null display name in CreateUpdate keeps the container's current display name.
|
||||
* - While an update's submit is pending, writing to or submitting that update fails with
|
||||
* E_ILLEGAL_METHOD_CALL. Once it completes, succeeded, failed or canceled, the update can
|
||||
* be submitted again, so a failed submit can be retried without staging the data again.
|
||||
* - Reading named blobs of a container that was never submitted fails with
|
||||
* E_GS_BLOB_NOT_FOUND; reading all of them returns zero blobs.
|
||||
* - A full disk on submit is E_GS_OUT_OF_LOCAL_STORAGE.
|
||||
* - Closing a provider closes its containers and their updates; closing a container closes
|
||||
* its updates. The last XGameRuntimeUninitialize closes every handle.
|
||||
* - Paths of MAX_PATH or more (executable or storage) fail with ERROR_FILENAME_EXCED_RANGE.
|
||||
*/
|
||||
#include "runtime_internal.h"
|
||||
#include "synthetic_keys.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
extern "C" HRESULT WINAPI XAsyncGetStatus(void* block, bool wait);
|
||||
|
||||
namespace bx::gdk {
|
||||
namespace {
|
||||
|
||||
using synthetic::GameSaveSlot;
|
||||
|
||||
// E_GS_* values listed on the XGameSave members page.
|
||||
constexpr HRESULT kInvalidContainerName = static_cast<HRESULT>(0x80830001u);
|
||||
constexpr HRESULT kOutOfLocalStorage = static_cast<HRESULT>(0x80830003u);
|
||||
constexpr HRESULT kUpdateTooBig = static_cast<HRESULT>(0x80830005u);
|
||||
constexpr HRESULT kProvidedBufferTooSmall = static_cast<HRESULT>(0x80830007u);
|
||||
constexpr HRESULT kBlobNotFound = static_cast<HRESULT>(0x80830008u);
|
||||
constexpr HRESULT kFileCorrupt = HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT);
|
||||
|
||||
constexpr size_t kMaxUpdateBytes = 16u * 1024u * 1024u;
|
||||
constexpr size_t kMaxContainerName = 256;
|
||||
constexpr size_t kMaxBlobName = 256;
|
||||
|
||||
struct ContainerInfo { // XGameSaveContainerInfo
|
||||
const char* name;
|
||||
const char* display_name;
|
||||
uint32_t blob_count;
|
||||
uint64_t total_size;
|
||||
time_t last_modified_time;
|
||||
bool needs_sync;
|
||||
};
|
||||
static_assert(sizeof(time_t) == 8);
|
||||
static_assert(offsetof(ContainerInfo, blob_count) == 16 && offsetof(ContainerInfo, total_size) == 24);
|
||||
static_assert(offsetof(ContainerInfo, last_modified_time) == 32 && offsetof(ContainerInfo, needs_sync) == 40);
|
||||
|
||||
struct BlobInfo { // XGameSaveBlobInfo
|
||||
const char* name;
|
||||
uint32_t size;
|
||||
};
|
||||
|
||||
struct Blob { // XGameSaveBlob
|
||||
BlobInfo info;
|
||||
uint8_t* data;
|
||||
};
|
||||
static_assert(sizeof(BlobInfo) == 16 && offsetof(Blob, data) == 16 && sizeof(Blob) == 24);
|
||||
|
||||
using ContainerInfoCallback = bool(CALLBACK*)(const ContainerInfo*, void*);
|
||||
|
||||
// FNV-1a over the string's bytes, each taken as one UTF-16 code unit 0-255, as 16 hex digits.
|
||||
std::wstring hex_id(const std::string& text) {
|
||||
std::wstring wide;
|
||||
wide.reserve(text.size());
|
||||
for (const char c : text) wide.push_back(static_cast<wchar_t>(static_cast<unsigned char>(c)));
|
||||
wchar_t id[17];
|
||||
std::swprintf(id, 17, L"%016llx", static_cast<unsigned long long>(fnv1a(wide.c_str())));
|
||||
return id;
|
||||
}
|
||||
|
||||
// --- Names ---
|
||||
|
||||
bool name_char(char c) {
|
||||
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_';
|
||||
}
|
||||
|
||||
// Rules from the XGameSaveCreateContainer page: an optional path part up to the last '/'
|
||||
// (A-Z, a-z, 0-9, _, /) and a non-empty file part (A-Z, a-z, 0-9, _, ., -) that does not
|
||||
// end in a period or contain "..". At most 256 characters.
|
||||
bool valid_container_name(const char* name, size_t length) {
|
||||
if (!name || length == 0 || length > kMaxContainerName) return false;
|
||||
const char* end = name + length;
|
||||
const char* file = name;
|
||||
for (const char* c = name; c < end; ++c) {
|
||||
if (*c == '/') file = c + 1;
|
||||
}
|
||||
for (const char* c = name; c < file; ++c) {
|
||||
if (!name_char(*c) && *c != '/') return false;
|
||||
}
|
||||
if (file == end || end[-1] == '.') return false;
|
||||
for (const char* c = file; c < end; ++c) {
|
||||
if (!name_char(*c) && *c != '.' && *c != '-') return false;
|
||||
if (c[0] == '.' && c + 1 < end && c[1] == '.') return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool valid_container_name(const char* name) {
|
||||
return name && valid_container_name(name, strnlen(name, kMaxContainerName + 1));
|
||||
}
|
||||
|
||||
bool valid_blob_name(const std::string& name) {
|
||||
return !name.empty() && name.size() <= kMaxBlobName && name.find('\0') == std::string::npos;
|
||||
}
|
||||
|
||||
// --- Container files ---
|
||||
|
||||
struct ContainerData {
|
||||
std::string name;
|
||||
std::string display_name;
|
||||
int64_t last_modified = 0;
|
||||
uint64_t total_size = 0;
|
||||
std::map<std::string, std::vector<uint8_t>> blobs; // Data left empty when parsed without data.
|
||||
};
|
||||
|
||||
constexpr uint32_t kMagic = 0x53475842; // "BXGS"
|
||||
constexpr uint32_t kFormatVersion = 1;
|
||||
constexpr wchar_t kExtension[] = L".bxgs";
|
||||
|
||||
void put_u32(std::vector<uint8_t>& out, uint32_t value) {
|
||||
for (int shift = 0; shift < 32; shift += 8) out.push_back(static_cast<uint8_t>(value >> shift));
|
||||
}
|
||||
|
||||
void put_u64(std::vector<uint8_t>& out, uint64_t value) {
|
||||
put_u32(out, static_cast<uint32_t>(value));
|
||||
put_u32(out, static_cast<uint32_t>(value >> 32));
|
||||
}
|
||||
|
||||
void put_string(std::vector<uint8_t>& out, const std::string& text) {
|
||||
put_u32(out, static_cast<uint32_t>(text.size()));
|
||||
out.insert(out.end(), text.begin(), text.end());
|
||||
}
|
||||
|
||||
std::vector<uint8_t> serialize(const ContainerData& data) {
|
||||
std::vector<uint8_t> out;
|
||||
put_u32(out, kMagic);
|
||||
put_u32(out, kFormatVersion);
|
||||
put_string(out, data.name);
|
||||
put_string(out, data.display_name);
|
||||
put_u64(out, static_cast<uint64_t>(data.last_modified));
|
||||
put_u32(out, static_cast<uint32_t>(data.blobs.size()));
|
||||
for (const auto& [name, bytes] : data.blobs) {
|
||||
put_string(out, name);
|
||||
put_u32(out, static_cast<uint32_t>(bytes.size()));
|
||||
out.insert(out.end(), bytes.begin(), bytes.end());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
class Reader {
|
||||
public:
|
||||
explicit Reader(const std::vector<uint8_t>& bytes) : next_(bytes.data()), left_(bytes.size()) {}
|
||||
|
||||
bool u32(uint32_t& value) {
|
||||
if (left_ < 4) return false;
|
||||
value = 0;
|
||||
for (int i = 0; i < 4; ++i) value |= static_cast<uint32_t>(next_[i]) << (8 * i);
|
||||
next_ += 4;
|
||||
left_ -= 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool u64(uint64_t& value) {
|
||||
uint32_t low, high;
|
||||
if (!u32(low) || !u32(high)) return false;
|
||||
value = (static_cast<uint64_t>(high) << 32) | low;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool bytes(size_t size, const uint8_t*& data) {
|
||||
if (left_ < size) return false;
|
||||
data = next_;
|
||||
next_ += size;
|
||||
left_ -= size;
|
||||
return true;
|
||||
}
|
||||
|
||||
// A NUL cannot pass through the C string APIs, so a stored one is corruption.
|
||||
bool string(std::string& text) {
|
||||
uint32_t size;
|
||||
const uint8_t* data;
|
||||
if (!u32(size) || !bytes(size, data) || std::memchr(data, 0, size)) return false;
|
||||
text.assign(reinterpret_cast<const char*>(data), size);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool done() const { return left_ == 0; }
|
||||
|
||||
private:
|
||||
const uint8_t* next_;
|
||||
size_t left_;
|
||||
};
|
||||
|
||||
// with_data false validates the whole file but keeps only names and sizes.
|
||||
bool parse(const std::vector<uint8_t>& bytes, ContainerData& data, bool with_data) {
|
||||
Reader in(bytes);
|
||||
uint32_t magic, version, count;
|
||||
uint64_t modified;
|
||||
if (!in.u32(magic) || magic != kMagic || !in.u32(version) || version != kFormatVersion ||
|
||||
!in.string(data.name) || !valid_container_name(data.name.c_str(), data.name.size()) ||
|
||||
!in.string(data.display_name) || !in.u64(modified) || !in.u32(count)) {
|
||||
return false;
|
||||
}
|
||||
data.last_modified = static_cast<int64_t>(modified);
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
std::string name;
|
||||
uint32_t size;
|
||||
const uint8_t* blob;
|
||||
if (!in.string(name) || !valid_blob_name(name) || !in.u32(size) || !in.bytes(size, blob)) return false;
|
||||
auto content = with_data ? std::vector<uint8_t>(blob, blob + size) : std::vector<uint8_t>();
|
||||
if (!data.blobs.emplace(std::move(name), std::move(content)).second) return false;
|
||||
data.total_size += size;
|
||||
}
|
||||
return in.done();
|
||||
}
|
||||
|
||||
std::wstring container_file(const std::wstring& dir, const std::string& name) {
|
||||
return dir + L"\\" + hex_id(name) + kExtension;
|
||||
}
|
||||
|
||||
HRESULT read_file(const std::wstring& path, std::vector<uint8_t>& out, bool& exists) {
|
||||
exists = false;
|
||||
// Share everything, so a reader never blocks another process's replace.
|
||||
const HANDLE file = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (file == INVALID_HANDLE_VALUE) {
|
||||
const auto error = GetLastError();
|
||||
return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? S_OK : HRESULT_FROM_WIN32(error);
|
||||
}
|
||||
exists = true;
|
||||
HRESULT hr = S_OK;
|
||||
LARGE_INTEGER size{};
|
||||
if (!GetFileSizeEx(file, &size)) {
|
||||
hr = HRESULT_FROM_WIN32(GetLastError());
|
||||
} else {
|
||||
try {
|
||||
out.resize(static_cast<size_t>(size.QuadPart));
|
||||
} catch (const std::bad_alloc&) {
|
||||
hr = E_OUTOFMEMORY;
|
||||
}
|
||||
size_t done = 0;
|
||||
while (SUCCEEDED(hr) && done < out.size()) {
|
||||
const DWORD chunk = static_cast<DWORD>(std::min<size_t>(out.size() - done, 1u << 30));
|
||||
DWORD got = 0;
|
||||
if (!ReadFile(file, out.data() + done, chunk, &got, nullptr)) hr = HRESULT_FROM_WIN32(GetLastError());
|
||||
else if (got == 0) hr = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
|
||||
done += got;
|
||||
}
|
||||
}
|
||||
CloseHandle(file);
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT write_error(DWORD error) {
|
||||
return error == ERROR_DISK_FULL || error == ERROR_HANDLE_DISK_FULL ? kOutOfLocalStorage
|
||||
: HRESULT_FROM_WIN32(error);
|
||||
}
|
||||
|
||||
HRESULT write_file_atomic(const std::wstring& path, const std::vector<uint8_t>& bytes) {
|
||||
const std::wstring temp = path + L"." + std::to_wstring(GetCurrentProcessId()) + L".tmp";
|
||||
const HANDLE file =
|
||||
CreateFileW(temp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (file == INVALID_HANDLE_VALUE) return write_error(GetLastError());
|
||||
HRESULT hr = S_OK;
|
||||
size_t done = 0;
|
||||
while (SUCCEEDED(hr) && done < bytes.size()) {
|
||||
const DWORD chunk = static_cast<DWORD>(std::min<size_t>(bytes.size() - done, 1u << 30));
|
||||
DWORD wrote = 0;
|
||||
if (!WriteFile(file, bytes.data() + done, chunk, &wrote, nullptr)) hr = write_error(GetLastError());
|
||||
done += wrote;
|
||||
}
|
||||
if (SUCCEEDED(hr) && !FlushFileBuffers(file)) hr = write_error(GetLastError());
|
||||
CloseHandle(file);
|
||||
if (SUCCEEDED(hr) && !MoveFileExW(temp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
|
||||
hr = write_error(GetLastError());
|
||||
}
|
||||
if (FAILED(hr)) DeleteFileW(temp.c_str());
|
||||
return hr;
|
||||
}
|
||||
|
||||
// Logs the file name only: bx_log_emit does not escape, and a Windows file name cannot hold
|
||||
// a backslash, quote or control character, so it is always valid JSON string content. The
|
||||
// directory is the title's saves directory for one SCID.
|
||||
void log_bad_file(const char* event, const std::wstring& path) {
|
||||
const auto slash = path.find_last_of(L'\\');
|
||||
const std::wstring name = slash == std::wstring::npos ? path : path.substr(slash + 1);
|
||||
char detail[MAX_PATH * 3 + 8];
|
||||
const int bytes = WideCharToMultiByte(CP_UTF8, 0, name.c_str(), -1, detail, sizeof(detail), nullptr, nullptr);
|
||||
if (bytes <= 0) std::snprintf(detail, sizeof(detail), "(unprintable file name)");
|
||||
bx_log_emit(BX_LOG_WARN, "xgamesave", event, detail);
|
||||
}
|
||||
|
||||
// Holds the named mutex for one SCID directory. Abandonment by a crashed owner is not an
|
||||
// error: every file is replaced atomically, so a half-done update never reaches disk.
|
||||
class DirectoryLock {
|
||||
public:
|
||||
explicit DirectoryLock(const std::wstring& dir) {
|
||||
wchar_t lower[MAX_PATH];
|
||||
if (!LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, dir.c_str(), -1, lower, MAX_PATH, nullptr,
|
||||
nullptr, 0)) {
|
||||
status_ = HRESULT_FROM_WIN32(GetLastError());
|
||||
return;
|
||||
}
|
||||
wchar_t name[64];
|
||||
std::swprintf(name, 64, L"Local\\BetterXen.XGameSave.%016llx", static_cast<unsigned long long>(fnv1a(lower)));
|
||||
mutex_ = CreateMutexW(nullptr, FALSE, name);
|
||||
if (!mutex_) {
|
||||
status_ = HRESULT_FROM_WIN32(GetLastError());
|
||||
return;
|
||||
}
|
||||
const DWORD wait = WaitForSingleObject(mutex_, INFINITE);
|
||||
status_ = wait == WAIT_OBJECT_0 || wait == WAIT_ABANDONED ? S_OK : HRESULT_FROM_WIN32(GetLastError());
|
||||
}
|
||||
|
||||
~DirectoryLock() {
|
||||
if (!mutex_) return;
|
||||
if (SUCCEEDED(status_)) ReleaseMutex(mutex_);
|
||||
CloseHandle(mutex_);
|
||||
}
|
||||
|
||||
DirectoryLock(const DirectoryLock&) = delete;
|
||||
DirectoryLock& operator=(const DirectoryLock&) = delete;
|
||||
|
||||
HRESULT status() const { return status_; }
|
||||
|
||||
private:
|
||||
HANDLE mutex_ = nullptr;
|
||||
HRESULT status_ = E_FAIL;
|
||||
};
|
||||
|
||||
// Caller holds the DirectoryLock for dir.
|
||||
HRESULT load_container(const std::wstring& dir, const std::string& name, ContainerData& data, bool& exists) {
|
||||
const auto path = container_file(dir, name);
|
||||
std::vector<uint8_t> bytes;
|
||||
auto hr = read_file(path, bytes, exists);
|
||||
if (FAILED(hr) || !exists) return hr;
|
||||
if (!parse(bytes, data, true)) {
|
||||
log_bad_file("corrupt_container", path);
|
||||
return kFileCorrupt;
|
||||
}
|
||||
if (data.name != name) {
|
||||
log_bad_file("container_id_collision", path);
|
||||
return HRESULT_FROM_WIN32(ERROR_FILE_EXISTS);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
// Caller holds the DirectoryLock for dir. Files that cannot be read or parsed are logged and
|
||||
// skipped, so one bad file does not hide the others.
|
||||
HRESULT list_containers(const std::wstring& dir, std::vector<ContainerData>& out) {
|
||||
WIN32_FIND_DATAW found;
|
||||
const HANDLE search = FindFirstFileW((dir + L"\\*" + kExtension).c_str(), &found);
|
||||
if (search == INVALID_HANDLE_VALUE) {
|
||||
const auto error = GetLastError();
|
||||
return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? S_OK : HRESULT_FROM_WIN32(error);
|
||||
}
|
||||
HRESULT hr = S_OK;
|
||||
do {
|
||||
const std::wstring file = found.cFileName;
|
||||
constexpr size_t ext = std::size(kExtension) - 1;
|
||||
if ((found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || file.size() <= ext ||
|
||||
file.compare(file.size() - ext, ext, kExtension) != 0) {
|
||||
continue;
|
||||
}
|
||||
const std::wstring path = dir + L"\\" + file;
|
||||
std::vector<uint8_t> bytes;
|
||||
bool exists;
|
||||
ContainerData data;
|
||||
const auto read = read_file(path, bytes, exists);
|
||||
if (read == E_OUTOFMEMORY) {
|
||||
hr = read;
|
||||
break;
|
||||
}
|
||||
if (FAILED(read)) {
|
||||
log_bad_file("unreadable_container", path);
|
||||
continue;
|
||||
}
|
||||
if (!exists) continue; // Replaced or removed since the search returned it.
|
||||
if (!parse(bytes, data, false) || container_file(dir, data.name) != path) {
|
||||
log_bad_file("corrupt_container", path);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
out.push_back(std::move(data));
|
||||
} catch (const std::bad_alloc&) {
|
||||
hr = E_OUTOFMEMORY;
|
||||
}
|
||||
} while (SUCCEEDED(hr) && FindNextFileW(search, &found));
|
||||
FindClose(search);
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT saves_directory(const std::string& scid, std::wstring& dir) {
|
||||
wchar_t root[MAX_PATH];
|
||||
auto hr = title_storage_directory(root);
|
||||
if (FAILED(hr)) return hr;
|
||||
const std::wstring saves = std::wstring(root) + L"\\saves";
|
||||
hr = ensure_directory(saves.c_str());
|
||||
if (FAILED(hr)) return hr;
|
||||
dir = saves + L"\\" + hex_id(scid);
|
||||
if (dir.size() >= MAX_PATH) return HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE);
|
||||
return ensure_directory(dir.c_str());
|
||||
}
|
||||
|
||||
// --- Handles ---
|
||||
// Lock order: the runtime lock (taken by active_runtime_generation, is_valid_user, around
|
||||
// consume callbacks and around release_game_save_state) before handle_mutex. Nothing here
|
||||
// calls into the runtime while holding handle_mutex.
|
||||
|
||||
struct Provider {
|
||||
uint32_t generation;
|
||||
std::wstring dir;
|
||||
};
|
||||
|
||||
struct Container {
|
||||
void* provider;
|
||||
std::string name;
|
||||
};
|
||||
|
||||
struct Update {
|
||||
void* container;
|
||||
bool keep_display_name;
|
||||
std::string display_name;
|
||||
std::map<std::string, std::vector<uint8_t>> writes;
|
||||
size_t staged_bytes = 0;
|
||||
// Set while a submit of this update is queued or running; cleared by that operation.
|
||||
std::shared_ptr<std::atomic<bool>> pending;
|
||||
};
|
||||
|
||||
std::mutex handle_mutex;
|
||||
std::unordered_map<void*, Provider> providers;
|
||||
std::unordered_map<void*, Container> containers;
|
||||
std::unordered_map<void*, Update> updates;
|
||||
|
||||
// Each handle type has its own range (tag in bits 40-43), so a handle of one type is never
|
||||
// a valid handle of another. package.cpp uses tag 4.
|
||||
enum : uintptr_t { kProviderTag = 1, kContainerTag = 2, kUpdateTag = 3 };
|
||||
uintptr_t handle_counter = 0;
|
||||
|
||||
void* next_handle(uintptr_t tag) {
|
||||
++handle_counter;
|
||||
return reinterpret_cast<void*>(tag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
|
||||
}
|
||||
|
||||
// The finders below require handle_mutex. A handle from before the last uninitialize, or
|
||||
// one whose provider was closed, is not found.
|
||||
const Provider* find_provider(void* handle, uint32_t generation) {
|
||||
const auto found = providers.find(handle);
|
||||
if (found == providers.end() || generation == 0 || found->second.generation != generation) return nullptr;
|
||||
return &found->second;
|
||||
}
|
||||
|
||||
const Container* find_container(void* handle, uint32_t generation, const Provider** provider) {
|
||||
const auto found = containers.find(handle);
|
||||
if (found == containers.end()) return nullptr;
|
||||
*provider = find_provider(found->second.provider, generation);
|
||||
return *provider ? &found->second : nullptr;
|
||||
}
|
||||
|
||||
Update* find_update(void* handle, uint32_t generation, const Container** container, const Provider** provider) {
|
||||
const auto found = updates.find(handle);
|
||||
if (found == updates.end()) return nullptr;
|
||||
*container = find_container(found->second.container, generation, provider);
|
||||
return *container ? &found->second : nullptr;
|
||||
}
|
||||
|
||||
template <typename Map, typename Value>
|
||||
HRESULT insert_handle(Map& map, uintptr_t tag, Value&& value, void** out) {
|
||||
void* handle = next_handle(tag);
|
||||
try {
|
||||
map.emplace(handle, std::forward<Value>(value));
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*out = handle;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
// Caller holds handle_mutex.
|
||||
void erase_updates_of(void* container) {
|
||||
std::erase_if(updates, [&](const auto& entry) { return entry.second.container == container; });
|
||||
}
|
||||
|
||||
// Caller holds handle_mutex.
|
||||
void erase_containers_of(void* provider) {
|
||||
for (auto it = containers.begin(); it != containers.end();) {
|
||||
if (it->second.provider == provider) {
|
||||
erase_updates_of(it->first);
|
||||
it = containers.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Async operations ---
|
||||
|
||||
enum : uint32_t { kInitProviderOp = 0x58475301, kSubmitUpdateOp = 0x58475302, kReadBlobsOp = 0x58475303 };
|
||||
|
||||
class InitProviderOp final : public AsyncOp {
|
||||
public:
|
||||
uint32_t generation = 0;
|
||||
std::string scid;
|
||||
std::wstring dir;
|
||||
|
||||
uint32_t kind() const override { return kInitProviderOp; }
|
||||
HRESULT execute() override try {
|
||||
return saves_directory(scid, dir);
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
size_t result_size() const override { return sizeof(void*); }
|
||||
};
|
||||
|
||||
class SubmitUpdateOp final : public AsyncOp {
|
||||
public:
|
||||
std::wstring dir;
|
||||
std::string name;
|
||||
bool keep_display_name = false;
|
||||
std::string display_name;
|
||||
std::map<std::string, std::vector<uint8_t>> writes;
|
||||
std::shared_ptr<std::atomic<bool>> pending;
|
||||
|
||||
// Covers cancellation and a submission that never ran.
|
||||
~SubmitUpdateOp() override { finish(); }
|
||||
|
||||
uint32_t kind() const override { return kSubmitUpdateOp; }
|
||||
size_t result_size() const override { return 0; }
|
||||
|
||||
HRESULT execute() override {
|
||||
const auto hr = write();
|
||||
finish();
|
||||
return hr;
|
||||
}
|
||||
|
||||
private:
|
||||
// Once per op: a resubmit shares the flag, so an old op must not clear it again later.
|
||||
void finish() {
|
||||
if (pending) pending->store(false);
|
||||
pending.reset();
|
||||
}
|
||||
|
||||
HRESULT write() try {
|
||||
DirectoryLock lock(dir);
|
||||
if (FAILED(lock.status())) return lock.status();
|
||||
ContainerData data;
|
||||
bool exists = false;
|
||||
auto hr = load_container(dir, name, data, exists);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (!exists) data.name = name;
|
||||
if (!keep_display_name) data.display_name = display_name;
|
||||
for (auto& [blob, bytes] : writes) data.blobs[blob] = std::move(bytes);
|
||||
data.last_modified = static_cast<int64_t>(std::time(nullptr));
|
||||
return write_file_atomic(container_file(dir, name), serialize(data));
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
};
|
||||
|
||||
class ReadBlobsOp final : public AsyncOp {
|
||||
public:
|
||||
std::wstring dir;
|
||||
std::string name;
|
||||
std::vector<std::string> wanted; // Empty: every blob.
|
||||
std::vector<std::pair<std::string, std::vector<uint8_t>>> found;
|
||||
size_t bytes = 0;
|
||||
|
||||
uint32_t kind() const override { return kReadBlobsOp; }
|
||||
size_t result_size() const override { return bytes; }
|
||||
|
||||
HRESULT execute() override try {
|
||||
DirectoryLock lock(dir);
|
||||
if (FAILED(lock.status())) return lock.status();
|
||||
ContainerData data;
|
||||
bool exists = false;
|
||||
const auto hr = load_container(dir, name, data, exists);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (wanted.empty()) {
|
||||
for (auto& [blob, content] : data.blobs) found.emplace_back(blob, std::move(content));
|
||||
} else {
|
||||
for (const auto& blob : wanted) {
|
||||
const auto match = data.blobs.find(blob);
|
||||
if (match == data.blobs.end()) return kBlobNotFound;
|
||||
found.emplace_back(blob, std::move(match->second));
|
||||
}
|
||||
}
|
||||
bytes = found.size() * sizeof(Blob);
|
||||
for (const auto& [blob, content] : found) bytes += blob.size() + 1 + content.size();
|
||||
return S_OK;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
// Layout in the caller's buffer: the Blob array, then all data, then the names.
|
||||
void copy_to(Blob* out) const {
|
||||
auto* cursor = reinterpret_cast<uint8_t*>(out) + found.size() * sizeof(Blob);
|
||||
for (size_t i = 0; i < found.size(); ++i) {
|
||||
const auto& content = found[i].second;
|
||||
out[i].info.size = static_cast<uint32_t>(content.size());
|
||||
out[i].data = cursor;
|
||||
if (!content.empty()) std::memcpy(cursor, content.data(), content.size());
|
||||
cursor += content.size();
|
||||
}
|
||||
for (size_t i = 0; i < found.size(); ++i) {
|
||||
const auto& blob = found[i].first;
|
||||
std::memcpy(cursor, blob.c_str(), blob.size() + 1);
|
||||
out[i].info.name = reinterpret_cast<const char*>(cursor);
|
||||
cursor += blob.size() + 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
HRESULT stale_handle_error(uint32_t generation) {
|
||||
return generation ? kRuntimeInvalidHandle : kRuntimeNotInitialized;
|
||||
}
|
||||
|
||||
} // anonymous helpers
|
||||
|
||||
// Slot functions declared in runtime_internal.h. The const public vtable takes their addresses
|
||||
// at static initialization.
|
||||
|
||||
HRESULT WINAPI initialize_provider_async(void*, void* user, const char* scid, bool /*sync_on_demand*/,
|
||||
void* async) {
|
||||
if (!async) return E_POINTER;
|
||||
if (!scid) return E_INVALIDARG;
|
||||
const auto generation = active_runtime_generation();
|
||||
if (!is_valid_user(user)) return stale_handle_error(generation);
|
||||
std::unique_ptr<InitProviderOp> op(new (std::nothrow) InitProviderOp);
|
||||
if (!op) return E_OUTOFMEMORY;
|
||||
try {
|
||||
op->scid = scid;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
op->generation = generation;
|
||||
return begin_async_op(async, std::move(op));
|
||||
}
|
||||
|
||||
HRESULT WINAPI initialize_provider_result(void*, void* async, void** provider) {
|
||||
if (!provider) return E_POINTER;
|
||||
*provider = nullptr;
|
||||
return consume_async_op(async, kInitProviderOp, [&](AsyncOp& base) {
|
||||
auto& op = static_cast<InitProviderOp&>(base);
|
||||
std::lock_guard lock(handle_mutex);
|
||||
return insert_handle(providers, kProviderTag, Provider{op.generation, op.dir}, provider);
|
||||
});
|
||||
}
|
||||
|
||||
void WINAPI close_provider(void*, void* provider) {
|
||||
std::lock_guard lock(handle_mutex);
|
||||
if (providers.erase(provider)) erase_containers_of(provider);
|
||||
}
|
||||
|
||||
HRESULT WINAPI create_container(void*, void* provider, const char* name, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
const auto generation = active_runtime_generation();
|
||||
std::lock_guard lock(handle_mutex);
|
||||
if (!find_provider(provider, generation)) return stale_handle_error(generation);
|
||||
if (!valid_container_name(name)) return kInvalidContainerName;
|
||||
try {
|
||||
return insert_handle(containers, kContainerTag, Container{provider, name}, out);
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
void WINAPI close_container(void*, void* container) {
|
||||
std::lock_guard lock(handle_mutex);
|
||||
if (containers.erase(container)) erase_updates_of(container);
|
||||
}
|
||||
|
||||
HRESULT WINAPI create_update(void*, void* container, const char* display_name, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
const auto generation = active_runtime_generation();
|
||||
std::lock_guard lock(handle_mutex);
|
||||
const Provider* provider = nullptr;
|
||||
if (!find_container(container, generation, &provider)) return stale_handle_error(generation);
|
||||
try {
|
||||
Update staged;
|
||||
staged.container = container;
|
||||
staged.keep_display_name = display_name == nullptr;
|
||||
staged.display_name = display_name ? display_name : "";
|
||||
staged.pending = std::make_shared<std::atomic<bool>>(false);
|
||||
return insert_handle(updates, kUpdateTag, std::move(staged), out);
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
void WINAPI close_update(void*, void* update) {
|
||||
std::lock_guard lock(handle_mutex);
|
||||
updates.erase(update);
|
||||
}
|
||||
|
||||
HRESULT WINAPI submit_blob_write(void*, void* update, const char* blob_name, const uint8_t* data, size_t size) {
|
||||
if (!blob_name) return E_INVALIDARG;
|
||||
const size_t name_length = strnlen(blob_name, kMaxBlobName + 1);
|
||||
if (name_length == 0 || name_length > kMaxBlobName) return E_INVALIDARG;
|
||||
if (!data && size) return E_POINTER;
|
||||
const auto generation = active_runtime_generation();
|
||||
std::lock_guard lock(handle_mutex);
|
||||
const Container* container = nullptr;
|
||||
const Provider* provider = nullptr;
|
||||
auto* staged = find_update(update, generation, &container, &provider);
|
||||
if (!staged) return stale_handle_error(generation);
|
||||
if (staged->pending->load()) return kIllegalMethodCall;
|
||||
if (staged->writes.contains(blob_name)) return E_INVALIDARG;
|
||||
if (size > kMaxUpdateBytes - staged->staged_bytes ||
|
||||
name_length > kMaxUpdateBytes - staged->staged_bytes - size) {
|
||||
return kUpdateTooBig;
|
||||
}
|
||||
try {
|
||||
staged->writes.emplace(blob_name, std::vector<uint8_t>(data, data + size));
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
staged->staged_bytes += name_length + size;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI submit_update_async(void*, void* update, void* async) {
|
||||
if (!async) return E_POINTER;
|
||||
std::unique_ptr<SubmitUpdateOp> op(new (std::nothrow) SubmitUpdateOp);
|
||||
if (!op) return E_OUTOFMEMORY;
|
||||
const auto generation = active_runtime_generation();
|
||||
{
|
||||
std::lock_guard lock(handle_mutex);
|
||||
const Container* container = nullptr;
|
||||
const Provider* provider = nullptr;
|
||||
auto* staged = find_update(update, generation, &container, &provider);
|
||||
if (!staged) return stale_handle_error(generation);
|
||||
if (staged->pending->load()) return kIllegalMethodCall;
|
||||
try {
|
||||
op->dir = provider->dir;
|
||||
op->name = container->name;
|
||||
op->keep_display_name = staged->keep_display_name;
|
||||
op->display_name = staged->display_name;
|
||||
op->writes = staged->writes;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
staged->pending->store(true);
|
||||
op->pending = staged->pending;
|
||||
}
|
||||
// On failure begin_async_op destroys op, whose destructor clears the pending flag.
|
||||
return begin_async_op(async, std::move(op));
|
||||
}
|
||||
|
||||
HRESULT WINAPI submit_update_result(void*, void* async) {
|
||||
return consume_async_op(async, kSubmitUpdateOp, [](AsyncOp&) { return S_OK; });
|
||||
}
|
||||
|
||||
HRESULT WINAPI read_blob_data_async(void*, void* container, const char** names, uint32_t count, void* async) {
|
||||
if (!async) return E_POINTER;
|
||||
if (count && !names) return E_INVALIDARG;
|
||||
std::unique_ptr<ReadBlobsOp> op(new (std::nothrow) ReadBlobsOp);
|
||||
if (!op) return E_OUTOFMEMORY;
|
||||
try {
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
if (!names[i] || !*names[i]) return E_INVALIDARG;
|
||||
if (std::find(op->wanted.begin(), op->wanted.end(), names[i]) != op->wanted.end()) return E_INVALIDARG;
|
||||
op->wanted.emplace_back(names[i]);
|
||||
}
|
||||
const auto generation = active_runtime_generation();
|
||||
std::lock_guard lock(handle_mutex);
|
||||
const Provider* provider = nullptr;
|
||||
const auto* open = find_container(container, generation, &provider);
|
||||
if (!open) return stale_handle_error(generation);
|
||||
op->dir = provider->dir;
|
||||
op->name = open->name;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
return begin_async_op(async, std::move(op));
|
||||
}
|
||||
|
||||
HRESULT WINAPI read_blob_data_result(void*, void* async, size_t size, void* blobs, uint32_t* count) {
|
||||
if (!count) return E_POINTER;
|
||||
*count = 0;
|
||||
return consume_async_op(async, kReadBlobsOp, [&](AsyncOp& base) {
|
||||
const auto& op = static_cast<const ReadBlobsOp&>(base);
|
||||
if (size < op.bytes) return kProvidedBufferTooSmall;
|
||||
if (op.bytes && !blobs) return E_POINTER;
|
||||
op.copy_to(static_cast<Blob*>(blobs));
|
||||
*count = static_cast<uint32_t>(op.found.size());
|
||||
return S_OK;
|
||||
});
|
||||
}
|
||||
|
||||
HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, GameSaveContainerInfoCallback callback) {
|
||||
if (!callback) return E_INVALIDARG;
|
||||
const auto typed = reinterpret_cast<ContainerInfoCallback>(callback);
|
||||
const auto generation = active_runtime_generation();
|
||||
std::vector<ContainerData> list;
|
||||
try {
|
||||
std::wstring dir;
|
||||
{
|
||||
std::lock_guard lock(handle_mutex);
|
||||
const auto* open = find_provider(provider, generation);
|
||||
if (!open) return stale_handle_error(generation);
|
||||
dir = open->dir;
|
||||
}
|
||||
DirectoryLock lock(dir);
|
||||
if (FAILED(lock.status())) return lock.status();
|
||||
const auto hr = list_containers(dir, list);
|
||||
if (FAILED(hr)) return hr;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
std::sort(list.begin(), list.end(), [](const auto& a, const auto& b) { return a.name < b.name; });
|
||||
// No lock is held here, so the callback may call back into XGameSave.
|
||||
for (const auto& data : list) {
|
||||
const ContainerInfo info{data.name.c_str(), data.display_name.c_str(),
|
||||
static_cast<uint32_t>(data.blobs.size()), data.total_size,
|
||||
static_cast<time_t>(data.last_modified), false};
|
||||
if (!typed(&info, context)) break;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
// Synchronous public slots. Each one runs the async operation above on the process task
|
||||
// queue (a null XAsyncBlock queue) and waits. syncOnDemand is passed through and has no
|
||||
// effect, the same as InitializeProviderAsync. Signatures follow the public Microsoft Learn
|
||||
// pages for these three functions.
|
||||
struct LocalAsync {
|
||||
void* queue;
|
||||
void* context;
|
||||
void (CALLBACK* callback)(LocalAsync*);
|
||||
unsigned char internal[4 * sizeof(void*)];
|
||||
};
|
||||
static_assert(sizeof(LocalAsync) == 7 * sizeof(void*));
|
||||
|
||||
HRESULT WINAPI initialize_provider(void*, void* user, const char* scid, bool sync_on_demand, void** provider) {
|
||||
if (!provider) return E_POINTER;
|
||||
*provider = nullptr;
|
||||
LocalAsync block{};
|
||||
const auto hr = initialize_provider_async(nullptr, user, scid, sync_on_demand, &block);
|
||||
if (FAILED(hr)) return hr;
|
||||
const auto status = XAsyncGetStatus(&block, true);
|
||||
if (FAILED(status)) return status;
|
||||
return initialize_provider_result(nullptr, &block, provider);
|
||||
}
|
||||
|
||||
HRESULT WINAPI read_blob_data(void*, void* container, const char** names, uint32_t* count, size_t size, void* blobs) {
|
||||
if (!count) return E_POINTER;
|
||||
const uint32_t requested = *count;
|
||||
*count = 0;
|
||||
LocalAsync block{};
|
||||
const auto hr = read_blob_data_async(nullptr, container, names, requested, &block);
|
||||
if (FAILED(hr)) return hr;
|
||||
const auto status = XAsyncGetStatus(&block, true);
|
||||
if (FAILED(status)) return status;
|
||||
return read_blob_data_result(nullptr, &block, size, blobs, count);
|
||||
}
|
||||
|
||||
HRESULT WINAPI submit_update(void*, void* update) {
|
||||
LocalAsync block{};
|
||||
const auto hr = submit_update_async(nullptr, update, &block);
|
||||
if (FAILED(hr)) return hr;
|
||||
const auto status = XAsyncGetStatus(&block, true);
|
||||
if (FAILED(status)) return status;
|
||||
return submit_update_result(nullptr, &block);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// --- COM object ---
|
||||
|
||||
HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!iid) return E_INVALIDARG;
|
||||
constexpr GUID own = synthetic::key(synthetic::kGameSave.iid);
|
||||
if (IsEqualGUID(*iid, kIUnknownIid) || IsEqualGUID(*iid, own)) {
|
||||
*out = self;
|
||||
return S_OK;
|
||||
}
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
// A process-lifetime singleton: reference counting has nothing to free.
|
||||
ULONG WINAPI add_ref(void*) { return 1; }
|
||||
ULONG WINAPI release(void*) { return 1; }
|
||||
|
||||
template <typename Fn>
|
||||
const void* slot_fn(Fn fn) {
|
||||
return reinterpret_cast<const void*>(fn);
|
||||
}
|
||||
|
||||
constexpr size_t at(GameSaveSlot slot) { return static_cast<size_t>(slot); }
|
||||
|
||||
const std::array<const void*, at(GameSaveSlot::Count)> kVtbl = [] {
|
||||
std::array<const void*, at(GameSaveSlot::Count)> v{};
|
||||
v[at(GameSaveSlot::QueryInterface)] = slot_fn(&query_interface);
|
||||
v[at(GameSaveSlot::AddRef)] = slot_fn(&add_ref);
|
||||
v[at(GameSaveSlot::Release)] = slot_fn(&release);
|
||||
v[at(GameSaveSlot::InitializeProviderAsync)] = slot_fn(&initialize_provider_async);
|
||||
v[at(GameSaveSlot::InitializeProviderResult)] = slot_fn(&initialize_provider_result);
|
||||
v[at(GameSaveSlot::CloseProvider)] = slot_fn(&close_provider);
|
||||
v[at(GameSaveSlot::CreateContainer)] = slot_fn(&create_container);
|
||||
v[at(GameSaveSlot::CloseContainer)] = slot_fn(&close_container);
|
||||
v[at(GameSaveSlot::CreateUpdate)] = slot_fn(&create_update);
|
||||
v[at(GameSaveSlot::CloseUpdate)] = slot_fn(&close_update);
|
||||
v[at(GameSaveSlot::SubmitBlobWrite)] = slot_fn(&submit_blob_write);
|
||||
v[at(GameSaveSlot::SubmitUpdateAsync)] = slot_fn(&submit_update_async);
|
||||
v[at(GameSaveSlot::SubmitUpdateResult)] = slot_fn(&submit_update_result);
|
||||
v[at(GameSaveSlot::ReadBlobDataAsync)] = slot_fn(&read_blob_data_async);
|
||||
v[at(GameSaveSlot::ReadBlobDataResult)] = slot_fn(&read_blob_data_result);
|
||||
v[at(GameSaveSlot::EnumerateContainerInfo)] = slot_fn(&enumerate_container_info);
|
||||
return v;
|
||||
}();
|
||||
|
||||
struct ComObject {
|
||||
const void* const* vtbl;
|
||||
};
|
||||
const ComObject kObject{kVtbl.data()};
|
||||
|
||||
} // namespace
|
||||
|
||||
const void* const game_save_object = &kObject;
|
||||
|
||||
void release_game_save_state() {
|
||||
std::lock_guard lock(handle_mutex);
|
||||
updates.clear();
|
||||
containers.clear();
|
||||
providers.clear();
|
||||
}
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -1,306 +0,0 @@
|
||||
/*
|
||||
* Offline XPackage identity and mount queries (#468).
|
||||
*
|
||||
* Reached through QueryApiImpl. The BetterXen synthetic key and its vtable order are in
|
||||
* synthetic_keys.h. Public class and interface ids use the const vtable in com_dispatch.cpp.
|
||||
* Nothing here is exported.
|
||||
*
|
||||
* Public reference (Microsoft Learn, gdk-2610, checked 2026-11-26): the XPackage members
|
||||
* page, the pages for the functions below, and XPackageKind (enum class : uint32_t
|
||||
* { Game, Content, PublisherContent }, so Game is 0):
|
||||
* https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/xpackage/xpackage_members
|
||||
* No Microsoft header, source or binary was used.
|
||||
*
|
||||
* Offline behaviour: the running executable's directory stands in for the installed package.
|
||||
* - The identifier is "BXPKG" + 16 hex digits of the FNV-1a hash of that directory
|
||||
* (lowercased), so it is stable for a directory and differs between directories.
|
||||
* XPACKAGE_IDENTIFIER_MAX_LENGTH has no published value; this identifier needs 22 bytes.
|
||||
* - GetPackageKind reports Game for that identifier and ERROR_NOT_FOUND for any other.
|
||||
* - Mount (the documented, deprecated XPackageMount) and its replacement
|
||||
* XPackageMountWithUiAsync / XPackageMountWithUiResult accept only that identifier, and the
|
||||
* mount path is the executable's directory. On Windows only content packages can be
|
||||
* mounted; BetterXen allows the game's own package so titles can locate their files. Offline
|
||||
* there is no license or parental-consent prompt, so the asynchronous form shows no UI; an
|
||||
* identifier mismatch is reported as the operation's status (ERROR_NOT_FOUND).
|
||||
* - The last XGameRuntimeUninitialize closes every mount handle.
|
||||
* - An executable path of MAX_PATH or more fails with ERROR_FILENAME_EXCED_RANGE.
|
||||
*/
|
||||
#include "runtime_internal.h"
|
||||
#include "synthetic_keys.h"
|
||||
|
||||
#include <array>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace bx::gdk {
|
||||
namespace {
|
||||
|
||||
using synthetic::PackageSlot;
|
||||
|
||||
constexpr uint32_t kPackageKindGame = 0;
|
||||
constexpr HRESULT kNotFound = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
|
||||
constexpr char kIdPrefix[] = "BXPKG";
|
||||
constexpr size_t kIdBytes = sizeof(kIdPrefix) - 1 + 16 + 1;
|
||||
|
||||
HRESULT executable_directory(std::wstring& dir) {
|
||||
wchar_t path[MAX_PATH];
|
||||
const auto hr = executable_path(path);
|
||||
if (FAILED(hr)) return hr;
|
||||
wchar_t* slash = std::wcsrchr(path, L'\\');
|
||||
if (!slash) return HRESULT_FROM_WIN32(ERROR_BAD_PATHNAME);
|
||||
// Keep the separator of a drive root ("C:\").
|
||||
slash[slash == path + 2 && path[1] == L':' ? 1 : 0] = L'\0';
|
||||
dir = path;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT current_identifier(char (&id)[kIdBytes]) {
|
||||
std::wstring dir;
|
||||
auto hr = executable_directory(dir);
|
||||
if (FAILED(hr)) return hr;
|
||||
wchar_t lower[MAX_PATH];
|
||||
if (!LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, dir.c_str(), -1, lower, MAX_PATH, nullptr, nullptr, 0)) {
|
||||
return HRESULT_FROM_WIN32(GetLastError());
|
||||
}
|
||||
std::snprintf(id, kIdBytes, "%s%016llx", kIdPrefix, static_cast<unsigned long long>(fnv1a(lower)));
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT is_current_package(const char* identifier, bool& match) {
|
||||
char id[kIdBytes];
|
||||
const auto hr = current_identifier(id);
|
||||
match = SUCCEEDED(hr) && std::strcmp(identifier, id) == 0;
|
||||
return hr;
|
||||
}
|
||||
|
||||
struct Mount {
|
||||
uint32_t generation;
|
||||
std::string path; // UTF-8
|
||||
};
|
||||
|
||||
std::mutex mount_mutex;
|
||||
uintptr_t handle_counter = 0;
|
||||
std::unordered_map<void*, Mount> mounts;
|
||||
|
||||
// Mount handles use tag 4 in bits 40-43, a range no XGameSave handle uses (game_save.cpp).
|
||||
constexpr uintptr_t kMountTag = 4;
|
||||
|
||||
// Caller holds mount_mutex.
|
||||
const Mount* find_mount(void* handle, uint32_t generation) {
|
||||
const auto found = mounts.find(handle);
|
||||
if (found == mounts.end() || generation == 0 || found->second.generation != generation) return nullptr;
|
||||
return &found->second;
|
||||
}
|
||||
|
||||
HRESULT stale_handle_error(uint32_t generation) {
|
||||
return generation ? kRuntimeInvalidHandle : kRuntimeNotInitialized;
|
||||
}
|
||||
|
||||
// Checks that identifier names this process's package and returns its mount path in UTF-8.
|
||||
HRESULT resolve_mount(const char* identifier, std::string& path) {
|
||||
bool match = false;
|
||||
auto hr = is_current_package(identifier, match);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (!match) return kNotFound;
|
||||
std::wstring dir;
|
||||
hr = executable_directory(dir);
|
||||
if (FAILED(hr)) return hr;
|
||||
const int bytes = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, dir.c_str(), -1, nullptr, 0, nullptr, nullptr);
|
||||
if (bytes <= 0) return HRESULT_FROM_WIN32(GetLastError());
|
||||
try {
|
||||
path.assign(static_cast<size_t>(bytes), '\0');
|
||||
WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, dir.c_str(), -1, path.data(), bytes, nullptr, nullptr);
|
||||
path.pop_back(); // The terminator is added back on copy-out.
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT insert_mount(uint32_t generation, std::string path, void** out) {
|
||||
try {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
++handle_counter;
|
||||
void* handle = reinterpret_cast<void*>(kMountTag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
|
||||
mounts.emplace(handle, Mount{generation, std::move(path)});
|
||||
*out = handle;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
constexpr uint32_t kMountWithUiOp = 0x58504B01;
|
||||
|
||||
// XPackageMountWithUiAsync: the identity check runs on the work port; the Result call then
|
||||
// creates the mount handle, as XPackageMount does synchronously.
|
||||
class MountWithUiOp final : public AsyncOp {
|
||||
public:
|
||||
uint32_t generation = 0;
|
||||
std::string identifier;
|
||||
std::string path;
|
||||
|
||||
uint32_t kind() const override { return kMountWithUiOp; }
|
||||
HRESULT execute() override { return resolve_mount(identifier.c_str(), path); }
|
||||
size_t result_size() const override { return sizeof(void*); }
|
||||
};
|
||||
|
||||
} // anonymous helpers
|
||||
|
||||
// Slot functions declared in runtime_internal.h. The const public vtable takes their addresses
|
||||
// at static initialization.
|
||||
|
||||
bool WINAPI is_packaged_process(void*) {
|
||||
if (!active_runtime_generation()) return false;
|
||||
char id[kIdBytes];
|
||||
return SUCCEEDED(current_identifier(id));
|
||||
}
|
||||
|
||||
HRESULT WINAPI get_current_process_package_identifier(void*, size_t size, char* buffer) {
|
||||
if (!buffer) return E_POINTER;
|
||||
if (!active_runtime_generation()) return kRuntimeNotInitialized;
|
||||
char id[kIdBytes];
|
||||
const auto hr = current_identifier(id);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (size < kIdBytes) return kInsufficientBuffer;
|
||||
std::memcpy(buffer, id, kIdBytes);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI get_package_kind(void*, const char* identifier, uint32_t* kind) {
|
||||
if (!kind) return E_POINTER;
|
||||
if (!identifier) return E_INVALIDARG;
|
||||
if (!active_runtime_generation()) return kRuntimeNotInitialized;
|
||||
bool match = false;
|
||||
const auto hr = is_current_package(identifier, match);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (!match) return kNotFound;
|
||||
*kind = kPackageKindGame;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI mount(void*, const char* identifier, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!identifier) return E_INVALIDARG;
|
||||
const auto generation = active_runtime_generation();
|
||||
if (!generation) return kRuntimeNotInitialized;
|
||||
std::string path;
|
||||
const auto hr = resolve_mount(identifier, path);
|
||||
return FAILED(hr) ? hr : insert_mount(generation, std::move(path), out);
|
||||
}
|
||||
|
||||
HRESULT WINAPI mount_with_ui_async(void*, const char* identifier, void* async) {
|
||||
if (!async) return E_POINTER;
|
||||
if (!identifier) return E_INVALIDARG;
|
||||
const auto generation = active_runtime_generation();
|
||||
if (!generation) return kRuntimeNotInitialized;
|
||||
std::unique_ptr<MountWithUiOp> op(new (std::nothrow) MountWithUiOp);
|
||||
if (!op) return E_OUTOFMEMORY;
|
||||
try {
|
||||
op->identifier = identifier;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
op->generation = generation;
|
||||
return begin_async_op(async, std::move(op));
|
||||
}
|
||||
|
||||
HRESULT WINAPI mount_with_ui_result(void*, void* async, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
return consume_async_op(async, kMountWithUiOp, [&](AsyncOp& base) {
|
||||
auto& op = static_cast<MountWithUiOp&>(base);
|
||||
return insert_mount(op.generation, op.path, out);
|
||||
});
|
||||
}
|
||||
|
||||
HRESULT WINAPI get_mount_path_size(void*, void* handle, size_t* size) {
|
||||
if (!size) return E_POINTER;
|
||||
*size = 0;
|
||||
const auto generation = active_runtime_generation();
|
||||
std::lock_guard lock(mount_mutex);
|
||||
const auto* open = find_mount(handle, generation);
|
||||
if (!open) return stale_handle_error(generation);
|
||||
*size = open->path.size() + 1;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI get_mount_path(void*, void* handle, size_t size, char* path) {
|
||||
if (!path) return E_POINTER;
|
||||
const auto generation = active_runtime_generation();
|
||||
std::lock_guard lock(mount_mutex);
|
||||
const auto* open = find_mount(handle, generation);
|
||||
if (!open) return stale_handle_error(generation);
|
||||
if (size < open->path.size() + 1) return kInsufficientBuffer;
|
||||
std::memcpy(path, open->path.c_str(), open->path.size() + 1);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
void WINAPI close_mount_handle(void*, void* handle) {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
mounts.erase(handle);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// --- COM object ---
|
||||
|
||||
HRESULT WINAPI query_interface(void* self, const GUID* iid, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!iid) return E_INVALIDARG;
|
||||
constexpr GUID own = synthetic::key(synthetic::kPackage.iid);
|
||||
if (IsEqualGUID(*iid, kIUnknownIid) || IsEqualGUID(*iid, own)) {
|
||||
*out = self;
|
||||
return S_OK;
|
||||
}
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
// A process-lifetime singleton: reference counting has nothing to free.
|
||||
ULONG WINAPI add_ref(void*) { return 1; }
|
||||
ULONG WINAPI release(void*) { return 1; }
|
||||
|
||||
template <typename Fn>
|
||||
const void* slot_fn(Fn fn) {
|
||||
return reinterpret_cast<const void*>(fn);
|
||||
}
|
||||
|
||||
constexpr size_t at(PackageSlot slot) { return static_cast<size_t>(slot); }
|
||||
|
||||
const std::array<const void*, at(PackageSlot::Count)> kVtbl = [] {
|
||||
std::array<const void*, at(PackageSlot::Count)> v{};
|
||||
v[at(PackageSlot::QueryInterface)] = slot_fn(&query_interface);
|
||||
v[at(PackageSlot::AddRef)] = slot_fn(&add_ref);
|
||||
v[at(PackageSlot::Release)] = slot_fn(&release);
|
||||
v[at(PackageSlot::GetCurrentProcessPackageIdentifier)] = slot_fn(&get_current_process_package_identifier);
|
||||
v[at(PackageSlot::GetPackageKind)] = slot_fn(&get_package_kind);
|
||||
v[at(PackageSlot::Mount)] = slot_fn(&mount);
|
||||
v[at(PackageSlot::GetMountPathSize)] = slot_fn(&get_mount_path_size);
|
||||
v[at(PackageSlot::GetMountPath)] = slot_fn(&get_mount_path);
|
||||
v[at(PackageSlot::CloseMountHandle)] = slot_fn(&close_mount_handle);
|
||||
return v;
|
||||
}();
|
||||
|
||||
struct ComObject {
|
||||
const void* const* vtbl;
|
||||
};
|
||||
const ComObject kObject{kVtbl.data()};
|
||||
|
||||
} // namespace
|
||||
|
||||
const void* const package_object = &kObject;
|
||||
|
||||
void release_package_state() {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
mounts.clear();
|
||||
}
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -1,109 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
// Internal interfaces shared by the xgameruntime.dll translation units. Nothing here is exported.
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
namespace bx::gdk {
|
||||
|
||||
// ABI values checked against Microsoft's public PC GDK 2510.5.6322 (see xgameruntime.cpp).
|
||||
constexpr HRESULT kRuntimeNotInitialized = static_cast<HRESULT>(0x89240100u);
|
||||
constexpr HRESULT kRuntimeInvalidHandle = static_cast<HRESULT>(0x8924010cu);
|
||||
constexpr HRESULT kIllegalMethodCall = static_cast<HRESULT>(0x8000000eu);
|
||||
constexpr HRESULT kInsufficientBuffer = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
|
||||
|
||||
// Work for an XAsyncBlock, run on the block's work port. execute() is skipped, and the block
|
||||
// completes with E_GAMERUNTIME_NOT_INITIALIZED (0x89240100), if the runtime was uninitialized
|
||||
// after the operation started; an execute() that is already running finishes. A finished
|
||||
// object, including its result data, is kept until its Result call consumes it, the same
|
||||
// block starts another operation, or the last uninitialize. A caller that frees a block
|
||||
// without calling Result leaves that result in memory until then; the retention is not
|
||||
// bounded.
|
||||
class AsyncOp {
|
||||
public:
|
||||
virtual ~AsyncOp() = default;
|
||||
// Identifies the family/function, so a Result call can reject a foreign block.
|
||||
virtual uint32_t kind() const = 0;
|
||||
// Runs without the runtime lock held. Not called if the operation was canceled.
|
||||
virtual HRESULT execute() = 0;
|
||||
// Value reported by XAsyncGetResultSize after execute() succeeded.
|
||||
virtual size_t result_size() const = 0;
|
||||
};
|
||||
|
||||
// Starts op on block (an XAsyncBlock*). Returns the submission status, as XUserAddAsync does.
|
||||
HRESULT begin_async_op(void* block, std::unique_ptr<AsyncOp> op);
|
||||
|
||||
// Checks that block holds a finished op of this kind, then calls consume while the runtime
|
||||
// lock is held. The result is marked consumed only when consume succeeds, so a caller can
|
||||
// retry with a larger buffer. consume must not call back into the runtime.
|
||||
HRESULT consume_async_op(void* block, uint32_t kind, const std::function<HRESULT(AsyncOp&)>& consume);
|
||||
|
||||
// Zero while the runtime is not initialized; otherwise changes on every first initialize,
|
||||
// so handles created before an uninitialize can be recognized as stale.
|
||||
uint32_t active_runtime_generation();
|
||||
|
||||
bool is_valid_user(void* user);
|
||||
|
||||
// Full Windows path of the running executable.
|
||||
HRESULT executable_path(wchar_t (&path)[MAX_PATH]);
|
||||
|
||||
// The executable's C:\bx_pls\<hash> directory (XPersistentLocalStorageGetPath), created if needed.
|
||||
HRESULT title_storage_directory(wchar_t (&path)[MAX_PATH]);
|
||||
|
||||
// Creates path if missing. Fails if it exists and is not a plain directory.
|
||||
HRESULT ensure_directory(const wchar_t* path);
|
||||
|
||||
// FNV-1a over UTF-16 code units, as used for the storage directory name.
|
||||
uint64_t fnv1a(const wchar_t* text);
|
||||
|
||||
constexpr GUID kIUnknownIid = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
|
||||
|
||||
// COM IUnknown objects QueryApiImpl returns for the synthetic xgamesave and xpackage keys.
|
||||
extern const void* const game_save_object; // game_save.cpp
|
||||
extern const void* const package_object; // package.cpp
|
||||
|
||||
// Close every XGameSave / XPackage handle. Called by the last uninitialize, with the runtime
|
||||
// lock held (the runtime lock is always taken before these files' own locks).
|
||||
void release_game_save_state(); // game_save.cpp
|
||||
void release_package_state(); // package.cpp
|
||||
|
||||
// XGameSave and XPackage slots shared by the synthetic objects and the const public vtables
|
||||
// in com_dispatch.cpp. C++ linkage only. The DLL export list does not include them.
|
||||
// The container-info callback receives the public XGameSaveContainerInfo layout.
|
||||
using GameSaveContainerInfoCallback = bool(CALLBACK*)(const void* info, void* context);
|
||||
|
||||
HRESULT WINAPI initialize_provider(void* self, void* user, const char* scid, bool sync_on_demand, void** provider);
|
||||
HRESULT WINAPI initialize_provider_async(void* self, void* user, const char* scid, bool sync_on_demand, void* async);
|
||||
HRESULT WINAPI initialize_provider_result(void* self, void* async, void** provider);
|
||||
void WINAPI close_provider(void* self, void* provider);
|
||||
HRESULT WINAPI create_container(void* self, void* provider, const char* name, void** out);
|
||||
void WINAPI close_container(void* self, void* container);
|
||||
HRESULT WINAPI enumerate_container_info(void* self, void* provider, void* context,
|
||||
GameSaveContainerInfoCallback callback);
|
||||
HRESULT WINAPI read_blob_data(void* self, void* container, const char** names, uint32_t* count, size_t size,
|
||||
void* blobs);
|
||||
HRESULT WINAPI read_blob_data_async(void* self, void* container, const char** names, uint32_t count, void* async);
|
||||
HRESULT WINAPI read_blob_data_result(void* self, void* async, size_t size, void* blobs, uint32_t* count);
|
||||
HRESULT WINAPI create_update(void* self, void* container, const char* display_name, void** out);
|
||||
void WINAPI close_update(void* self, void* update);
|
||||
HRESULT WINAPI submit_blob_write(void* self, void* update, const char* blob_name, const uint8_t* data, size_t size);
|
||||
HRESULT WINAPI submit_update(void* self, void* update);
|
||||
HRESULT WINAPI submit_update_async(void* self, void* update, void* async);
|
||||
HRESULT WINAPI submit_update_result(void* self, void* async);
|
||||
|
||||
bool WINAPI is_packaged_process(void* self);
|
||||
HRESULT WINAPI get_current_process_package_identifier(void* self, size_t size, char* buffer);
|
||||
HRESULT WINAPI get_package_kind(void* self, const char* identifier, uint32_t* kind);
|
||||
HRESULT WINAPI mount(void* self, const char* identifier, void** out);
|
||||
HRESULT WINAPI mount_with_ui_async(void* self, const char* identifier, void* async);
|
||||
HRESULT WINAPI mount_with_ui_result(void* self, void* async, void** out);
|
||||
HRESULT WINAPI get_mount_path_size(void* self, void* handle, size_t* size);
|
||||
HRESULT WINAPI get_mount_path(void* self, void* handle, size_t size, char* path);
|
||||
void WINAPI close_mount_handle(void* self, void* handle);
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -1,92 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
* BetterXen synthetic QueryApiImpl keys: the single place to find or change them.
|
||||
*
|
||||
* These class and interface ids are defined by BetterXen. They are NOT Microsoft
|
||||
* identifiers and were not derived from any Microsoft binary. A title linked against
|
||||
* Microsoft's xgameruntime.lib will not request them. They let BetterXen's own callers
|
||||
* and conformance fixtures reach the offline families through QueryApiImpl. The public
|
||||
* class and interface ids for XGameSave and XPackage are registered separately in
|
||||
* com_dispatch.cpp. These synthetic keys stay so the fixtures below keep working.
|
||||
* To replace a family's keys, change its entry here and
|
||||
* the expected values in the fixtures listed below. The fixtures keep their own copies on
|
||||
* purpose, so a wrong key here fails a test instead of agreeing with itself:
|
||||
* tests/conformance/test_xgameruntime/main.cpp (all families)
|
||||
* tests/conformance/test_xgameruntime_saves/main.cpp (xgamesave, xpackage)
|
||||
*
|
||||
* Encoding: Data1 is the key below. Data2 = 0x5853 ("XS"), Data3 = 0x4000,
|
||||
* Data4 = 80 00 00 00 00 00 00 01. For example, 0xB7581601 is
|
||||
* {B7581601-5853-4000-8000-000000000001}.
|
||||
*/
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace bx::gdk::synthetic {
|
||||
|
||||
constexpr uint16_t kData2 = 0x5853;
|
||||
constexpr uint16_t kData3 = 0x4000;
|
||||
constexpr uint8_t kData4[8] = {0x80, 0, 0, 0, 0, 0, 0, 0x01};
|
||||
|
||||
constexpr GUID key(uint32_t data1) {
|
||||
return {data1, kData2, kData3, {kData4[0], kData4[1], kData4[2], kData4[3],
|
||||
kData4[4], kData4[5], kData4[6], kData4[7]}};
|
||||
}
|
||||
|
||||
struct FamilyKey {
|
||||
uint32_t clsid;
|
||||
uint32_t iid;
|
||||
};
|
||||
|
||||
// Plain function tables (#439). QueryApiImpl returns a pointer to a C struct of
|
||||
// function pointers; the layouts are the *Dispatch structs in xgameruntime.cpp.
|
||||
constexpr FamilyKey kTaskQueue{0xB7581001, 0xB7581002};
|
||||
constexpr FamilyKey kAsync{0xB7581101, 0xB7581102};
|
||||
constexpr FamilyKey kUser{0xB7581201, 0xB7581202};
|
||||
constexpr FamilyKey kStore{0xB7581301, 0xB7581302};
|
||||
constexpr FamilyKey kSystem{0xB7581401, 0xB7581402};
|
||||
constexpr FamilyKey kPersistentLocalStorage{0xB7581501, 0xB7581502};
|
||||
|
||||
// COM IUnknown objects (#468). QueryApiImpl returns an object whose first member is a
|
||||
// vtable pointer. Slots 0-2 are IUnknown; the remaining slots follow the enums below.
|
||||
// Every slot takes the object pointer first, then the parameters of the Microsoft Learn
|
||||
// function it names, in the documented order.
|
||||
constexpr FamilyKey kGameSave{0xB7581601, 0xB7581602};
|
||||
constexpr FamilyKey kPackage{0xB7581701, 0xB7581702};
|
||||
|
||||
enum class GameSaveSlot : uint32_t {
|
||||
QueryInterface,
|
||||
AddRef,
|
||||
Release,
|
||||
InitializeProviderAsync, // (XUserHandle, const char* scid, bool syncOnDemand, XAsyncBlock*)
|
||||
InitializeProviderResult, // (XAsyncBlock*, XGameSaveProviderHandle*)
|
||||
CloseProvider, // (XGameSaveProviderHandle)
|
||||
CreateContainer, // (XGameSaveProviderHandle, const char* name, XGameSaveContainerHandle*)
|
||||
CloseContainer, // (XGameSaveContainerHandle)
|
||||
CreateUpdate, // (XGameSaveContainerHandle, const char* displayName, XGameSaveUpdateHandle*)
|
||||
CloseUpdate, // (XGameSaveUpdateHandle)
|
||||
SubmitBlobWrite, // (XGameSaveUpdateHandle, const char* blobName, const uint8_t*, size_t)
|
||||
SubmitUpdateAsync, // (XGameSaveUpdateHandle, XAsyncBlock*)
|
||||
SubmitUpdateResult, // (XAsyncBlock*)
|
||||
ReadBlobDataAsync, // (XGameSaveContainerHandle, const char** names, uint32_t count, XAsyncBlock*)
|
||||
ReadBlobDataResult, // (XAsyncBlock*, size_t, XGameSaveBlob*, uint32_t* count)
|
||||
EnumerateContainerInfo, // (XGameSaveProviderHandle, void* context, XGameSaveContainerInfoCallback*)
|
||||
Count,
|
||||
};
|
||||
|
||||
enum class PackageSlot : uint32_t {
|
||||
QueryInterface,
|
||||
AddRef,
|
||||
Release,
|
||||
GetCurrentProcessPackageIdentifier, // (size_t bufferSize, char* buffer)
|
||||
GetPackageKind, // (const char* packageIdentifier, XPackageKind*)
|
||||
Mount, // (const char* packageIdentifier, XPackageMountHandle*)
|
||||
GetMountPathSize, // (XPackageMountHandle, size_t*)
|
||||
GetMountPath, // (XPackageMountHandle, size_t, char*)
|
||||
CloseMountHandle, // (XPackageMountHandle)
|
||||
Count,
|
||||
};
|
||||
|
||||
} // namespace bx::gdk::synthetic
|
||||
@@ -1,14 +1,9 @@
|
||||
#include "com_dispatch.h"
|
||||
#include "runtime_internal.h"
|
||||
#include "synthetic_keys.h"
|
||||
#include "task_queue.h"
|
||||
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
#include <unordered_set>
|
||||
@@ -21,10 +16,10 @@ namespace {
|
||||
using namespace bx::gdk;
|
||||
|
||||
// ABI values and layouts checked against Microsoft's public PC GDK 2510.5.6322.
|
||||
constexpr HRESULT runtime_not_initialized = kRuntimeNotInitialized;
|
||||
constexpr HRESULT runtime_invalid_handle = kRuntimeInvalidHandle;
|
||||
constexpr HRESULT illegal_method_call = kIllegalMethodCall;
|
||||
constexpr HRESULT insufficient_buffer = kInsufficientBuffer;
|
||||
constexpr HRESULT runtime_not_initialized = static_cast<HRESULT>(0x89240100u);
|
||||
constexpr HRESULT runtime_invalid_handle = static_cast<HRESULT>(0x8924010cu);
|
||||
constexpr HRESULT illegal_method_call = static_cast<HRESULT>(0x8000000eu);
|
||||
constexpr HRESULT insufficient_buffer = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
|
||||
|
||||
struct AsyncBlock {
|
||||
void* queue;
|
||||
@@ -59,8 +54,7 @@ struct SpaceInfo {
|
||||
uint64_t total_bytes;
|
||||
};
|
||||
|
||||
// custom: an AsyncOp from another translation unit (XGameSave), see runtime_internal.h.
|
||||
enum class Operation : uint32_t { add_user, game_license, custom };
|
||||
enum class Operation : uint32_t { add_user, game_license };
|
||||
|
||||
struct AsyncState {
|
||||
const AsyncBlock* owner;
|
||||
@@ -83,8 +77,6 @@ uint64_t next_operation = 1;
|
||||
uintptr_t next_handle = 2;
|
||||
std::unordered_set<void*> users;
|
||||
std::unordered_set<void*> stores;
|
||||
// Finished custom operations awaiting their Result call, keyed by AsyncState::sequence.
|
||||
std::map<uint64_t, std::unique_ptr<AsyncOp>> finished_ops;
|
||||
|
||||
HRESULT create_handle(std::unordered_set<void*>& handles, void** out) {
|
||||
auto handle = reinterpret_cast<void*>(next_handle);
|
||||
@@ -165,12 +157,10 @@ class AsyncTask final : public Task {
|
||||
public:
|
||||
AsyncBlock* block;
|
||||
Operation operation;
|
||||
std::unique_ptr<AsyncOp> op;
|
||||
std::unique_ptr<CompletionTask> completion;
|
||||
bool queued = false;
|
||||
|
||||
AsyncTask(AsyncBlock* block, Operation operation, std::unique_ptr<AsyncOp> op)
|
||||
: block(block), operation(operation), op(std::move(op)) {}
|
||||
AsyncTask(AsyncBlock* block, Operation operation) : block(block), operation(operation) {}
|
||||
|
||||
~AsyncTask() override {
|
||||
if (!queued) return;
|
||||
@@ -193,34 +183,11 @@ public:
|
||||
private:
|
||||
void finish(const QueueRef& queue, bool canceled) {
|
||||
const bool entitled = !canceled && operation == Operation::game_license && fixture_entitlement();
|
||||
bool cancel_requested;
|
||||
bool stale;
|
||||
{
|
||||
std::lock_guard lock(state_mutex);
|
||||
const auto state = read_state(block);
|
||||
cancel_requested = state.cancel_requested;
|
||||
stale = !runtime_refs || state.runtime_generation != runtime_generation;
|
||||
}
|
||||
// The block stays E_PENDING meanwhile, so the caller cannot reuse it. Once an op has
|
||||
// run, a later XAsyncCancel or uninitialize cannot undo it, so its own status is
|
||||
// reported. An op whose runtime was uninitialized before it ran is not run.
|
||||
const bool executed = op && !canceled && !cancel_requested && !stale;
|
||||
const HRESULT op_status = executed ? op->execute() : S_OK;
|
||||
{
|
||||
std::lock_guard lock(state_mutex);
|
||||
auto state = read_state(block);
|
||||
state.status = executed ? op_status
|
||||
: canceled || state.cancel_requested ? E_ABORT
|
||||
: op && stale ? runtime_not_initialized
|
||||
: S_OK;
|
||||
state.status = (canceled || state.cancel_requested) ? E_ABORT : S_OK;
|
||||
state.entitled = entitled;
|
||||
if (op && SUCCEEDED(state.status) && state.runtime_generation == runtime_generation && runtime_refs) {
|
||||
try {
|
||||
finished_ops[state.sequence] = std::move(op);
|
||||
} catch (const std::bad_alloc&) {
|
||||
state.status = E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
if (completion) completion->sequence = state.sequence;
|
||||
queued = false;
|
||||
write_state(block, state);
|
||||
@@ -229,12 +196,12 @@ private:
|
||||
}
|
||||
};
|
||||
|
||||
HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr, std::unique_ptr<AsyncOp> op = nullptr) {
|
||||
HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr) {
|
||||
if (!block) return E_POINTER;
|
||||
const auto queue = acquire_queue(block->queue);
|
||||
if (!queue) return block->queue ? E_HANDLE : E_OUTOFMEMORY;
|
||||
|
||||
auto work = std::unique_ptr<AsyncTask>(new (std::nothrow) AsyncTask(block, operation, std::move(op)));
|
||||
auto work = std::unique_ptr<AsyncTask>(new (std::nothrow) AsyncTask(block, operation));
|
||||
if (!work) return E_OUTOFMEMORY;
|
||||
if (block->callback) {
|
||||
work->completion.reset(new (std::nothrow) CompletionTask(block));
|
||||
@@ -253,8 +220,6 @@ HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr, std
|
||||
callback_running(previous.sequence, GetCurrentThreadId()))) {
|
||||
return illegal_method_call;
|
||||
}
|
||||
// An unconsumed result of an earlier operation on this block is abandoned.
|
||||
if (previous.owner == block) finished_ops.erase(previous.sequence);
|
||||
write_state(block, {block, next_operation++, E_PENDING, operation, runtime_generation,
|
||||
false, block->callback != nullptr, false, false});
|
||||
work->queued = true;
|
||||
@@ -310,173 +275,6 @@ bool fixture_entitlement() {
|
||||
GetProcAddress(GetModuleHandleW(nullptr), "BetterXenSyntheticStoreFixture") != nullptr;
|
||||
}
|
||||
|
||||
HRESULT storage_path(wchar_t (&path)[MAX_PATH]) {
|
||||
wchar_t module[MAX_PATH];
|
||||
const wchar_t* name = nullptr;
|
||||
const auto hr = executable_name(module, name);
|
||||
if (FAILED(hr)) return hr;
|
||||
// Hash the full Windows path so identically named workloads in separate
|
||||
// directories get distinct storage within the same bottle.
|
||||
wchar_t normalized[MAX_PATH];
|
||||
if (!LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, module, -1,
|
||||
normalized, MAX_PATH, nullptr, nullptr, 0)) {
|
||||
return HRESULT_FROM_WIN32(GetLastError());
|
||||
}
|
||||
const uint64_t path_id = bx::gdk::fnv1a(normalized);
|
||||
const auto length = std::swprintf(path, MAX_PATH, L"%ls\\%016llx", storage_root,
|
||||
static_cast<unsigned long long>(path_id));
|
||||
return length < 0 ? HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE) : S_OK;
|
||||
}
|
||||
|
||||
HRESULT create_storage(const wchar_t* path) {
|
||||
const auto hr = ensure_directory(storage_root);
|
||||
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();
|
||||
finished_ops.clear();
|
||||
bx::gdk::release_game_save_state();
|
||||
bx::gdk::release_package_state();
|
||||
}
|
||||
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);
|
||||
|
||||
// The synthetic key encoding is defined in synthetic_keys.h.
|
||||
bool synthetic_guid(const GUID* guid) {
|
||||
return guid->Data2 == synthetic::kData2 && guid->Data3 == synthetic::kData3 &&
|
||||
std::memcmp(guid->Data4, synthetic::kData4, sizeof(synthetic::kData4)) == 0;
|
||||
}
|
||||
|
||||
void format_guid(char* dst, size_t cap, const GUID* guid) {
|
||||
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
|
||||
|
||||
namespace bx::gdk {
|
||||
|
||||
HRESULT ensure_directory(const wchar_t* path) {
|
||||
if (CreateDirectoryW(path, nullptr)) return S_OK;
|
||||
const auto error = GetLastError();
|
||||
@@ -490,59 +288,34 @@ HRESULT ensure_directory(const wchar_t* path) {
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
uint64_t fnv1a(const wchar_t* text) {
|
||||
uint64_t hash = 14695981039346656037ULL;
|
||||
for (auto* ch = text; *ch; ++ch) {
|
||||
hash ^= static_cast<uint16_t>(*ch);
|
||||
hash *= 1099511628211ULL;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
HRESULT executable_path(wchar_t (&path)[MAX_PATH]) {
|
||||
HRESULT storage_path(wchar_t (&path)[MAX_PATH]) {
|
||||
wchar_t module[MAX_PATH];
|
||||
const wchar_t* name = nullptr;
|
||||
return executable_name(path, name);
|
||||
}
|
||||
|
||||
HRESULT title_storage_directory(wchar_t (&path)[MAX_PATH]) {
|
||||
const auto hr = storage_path(path);
|
||||
return FAILED(hr) ? hr : create_storage(path);
|
||||
}
|
||||
|
||||
uint32_t active_runtime_generation() {
|
||||
std::lock_guard lock(state_mutex);
|
||||
return runtime_refs ? runtime_generation : 0;
|
||||
}
|
||||
|
||||
bool is_valid_user(void* user) {
|
||||
std::lock_guard lock(state_mutex);
|
||||
return runtime_refs && users.contains(user);
|
||||
}
|
||||
|
||||
HRESULT begin_async_op(void* block, std::unique_ptr<AsyncOp> op) {
|
||||
if (!op) return E_OUTOFMEMORY;
|
||||
return begin(static_cast<AsyncBlock*>(block), Operation::custom, nullptr, std::move(op));
|
||||
}
|
||||
|
||||
HRESULT consume_async_op(void* block, uint32_t kind, const std::function<HRESULT(AsyncOp&)>& consume) {
|
||||
auto* async = static_cast<AsyncBlock*>(block);
|
||||
std::lock_guard lock(state_mutex);
|
||||
AsyncState state{};
|
||||
const auto hr = check_result(async, Operation::custom, state);
|
||||
const auto hr = executable_name(module, name);
|
||||
if (FAILED(hr)) return hr;
|
||||
const auto found = finished_ops.find(state.sequence);
|
||||
if (found == finished_ops.end() || found->second->kind() != kind) return illegal_method_call;
|
||||
|
||||
const auto result = consume(*found->second);
|
||||
if (SUCCEEDED(result)) {
|
||||
finished_ops.erase(found);
|
||||
state.result_consumed = true;
|
||||
write_state(async, state);
|
||||
// Hash the full Windows path so identically named workloads in separate
|
||||
// directories get distinct storage within the same bottle.
|
||||
wchar_t normalized[MAX_PATH];
|
||||
if (!LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, module, -1,
|
||||
normalized, MAX_PATH, nullptr, nullptr, 0)) {
|
||||
return HRESULT_FROM_WIN32(GetLastError());
|
||||
}
|
||||
return result;
|
||||
uint64_t path_id = 14695981039346656037ULL;
|
||||
for (auto* ch = normalized; *ch; ++ch) {
|
||||
path_id ^= static_cast<uint16_t>(*ch);
|
||||
path_id *= 1099511628211ULL;
|
||||
}
|
||||
const auto length = std::swprintf(path, MAX_PATH, L"%ls\\%016llx", storage_root,
|
||||
static_cast<unsigned long long>(path_id));
|
||||
return length < 0 ? HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE) : S_OK;
|
||||
}
|
||||
|
||||
} // namespace bx::gdk
|
||||
HRESULT create_storage(const wchar_t* path) {
|
||||
const auto hr = ensure_directory(storage_root);
|
||||
return FAILED(hr) ? hr : ensure_directory(path);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
@@ -566,7 +339,10 @@ HRESULT WINAPI XGameRuntimeInitializeWithOptions(const RuntimeOptions* options)
|
||||
|
||||
void WINAPI XGameRuntimeUninitialize() {
|
||||
std::lock_guard lock(state_mutex);
|
||||
release_runtime_ref();
|
||||
if (runtime_refs && !--runtime_refs) {
|
||||
users.clear();
|
||||
stores.clear();
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT WINAPI XAsyncGetStatus(AsyncBlock* block, bool wait) {
|
||||
@@ -598,16 +374,7 @@ HRESULT WINAPI XAsyncGetResultSize(AsyncBlock* block, size_t* size) {
|
||||
const auto state = read_state(block);
|
||||
if (state.owner != block || state.result_consumed) return illegal_method_call;
|
||||
if (SUCCEEDED(state.status)) {
|
||||
switch (state.operation) {
|
||||
case Operation::add_user: *size = sizeof(void*); break;
|
||||
case Operation::game_license: *size = sizeof(GameLicense); break;
|
||||
case Operation::custom: {
|
||||
const auto found = finished_ops.find(state.sequence);
|
||||
if (found == finished_ops.end()) return illegal_method_call;
|
||||
*size = found->second->result_size();
|
||||
break;
|
||||
}
|
||||
}
|
||||
*size = state.operation == Operation::add_user ? sizeof(void*) : sizeof(GameLicense);
|
||||
}
|
||||
return state.status;
|
||||
}
|
||||
@@ -794,178 +561,4 @@ 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;
|
||||
bool com; // table is a COM object, so IID_IUnknown also reaches it
|
||||
};
|
||||
|
||||
// Synthetic BetterXen dispatch keys, not Microsoft CLSIDs. All keys and the COM slot
|
||||
// orders live in synthetic_keys.h.
|
||||
const Family families[] = {
|
||||
{synthetic::kTaskQueue.clsid, synthetic::kTaskQueue.iid, "xtaskqueue", &task_queue_api, false},
|
||||
{synthetic::kAsync.clsid, synthetic::kAsync.iid, "xasync", &async_api, false},
|
||||
{synthetic::kUser.clsid, synthetic::kUser.iid, "xuser", &user_api, false},
|
||||
{synthetic::kStore.clsid, synthetic::kStore.iid, "xstore", &store_api, false},
|
||||
{synthetic::kSystem.clsid, synthetic::kSystem.iid, "xsystem", &system_api, false},
|
||||
{synthetic::kPersistentLocalStorage.clsid, synthetic::kPersistentLocalStorage.iid, "xpersistentlocalstorage",
|
||||
&storage_api, false},
|
||||
{synthetic::kGameSave.clsid, synthetic::kGameSave.iid, "xgamesave", bx::gdk::game_save_object, true},
|
||||
{synthetic::kPackage.clsid, synthetic::kPackage.iid, "xpackage", bx::gdk::package_object, true},
|
||||
};
|
||||
|
||||
const Family* find_family(const GUID* clsid) {
|
||||
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;
|
||||
}
|
||||
|
||||
bool public_clsid_known = false;
|
||||
if (bx::gdk::query_public_gdk_interface(clsid, iid, out, &public_clsid_known)) {
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const auto* family = find_family(clsid);
|
||||
if (family && ((synthetic_guid(iid) && iid->Data1 == family->iid) ||
|
||||
(family->com && IsEqualGUID(*iid, bx::gdk::kIUnknownIid)))) {
|
||||
*out = const_cast<void*>(family->table);
|
||||
char detail[64];
|
||||
std::snprintf(detail, sizeof(detail), "dispatch family=%s", family->name);
|
||||
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 if (public_clsid_known) {
|
||||
std::snprintf(detail, sizeof(detail), "public_iid_mismatch clsid=%s iid=%s", clsid_text, iid_text);
|
||||
} else {
|
||||
std::snprintf(detail, sizeof(detail), "unsupported clsid=%s iid=%s", clsid_text, iid_text);
|
||||
}
|
||||
bx_log_emit(BX_LOG_WARN, "xgameruntime", "QueryApiImpl", detail);
|
||||
BX_STUB_LOG("xgameruntime.dll", symbol);
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,74 @@
|
||||
# D3D11 compute-buffer workload
|
||||
|
||||
This original fixture submits an unsigned 32-bit addition in a Direct3D 11 compute shader and verifies the GPU output through CPU staging readback. It requires a hardware device at feature level 11.0 and uses no game data.
|
||||
|
||||
## Expected output
|
||||
|
||||
The shader adds one plus the lane's position within a repeating 16-word sequence. Write an output index as `16b + r` with `0 ≤ r < 16`. Pattern 0 starts its block at `4096 + 65536b`. Pattern 1 starts at `−16 − 65536b`, represented modulo 2³². Each input is its block's base plus `r`. The expected output is the corresponding odd-number progression from base plus 1 to base plus 31, reduced modulo 2³². The C code lists both first-block progressions as constants. Subsequent blocks shift the expected progression by the signed block offset. The block tags distinguish writes whose indices differ by a multiple of 16. The second pattern exercises unsigned wraparound in its first block.
|
||||
|
||||
Each pattern runs with counts 0, 1, 63, 64, 65, 127, 128, 129, and 191. A zero count skips dispatch and checks that the entire buffer retains its initial sentinel. The other cases dispatch groups of 64. The structured buffers physically hold 192 words, so an erroneous write from a rounded-up tail would overwrite a sentinel inside the allocated buffer. Every run compares all 192 words, including undispatched slots. The negative control changes only the expected word for pattern 0, count 65, index 64 from `00041001` to `00041000`.
|
||||
|
||||
The digest is 32-bit FNV-1a over all 3,456 readback words, each fed as four bytes in little-endian order. Pattern 0 comes first, each pattern uses the count order above, and each buffer is traversed by ascending index. The analytic result is `6ce404b5`. The negative control should give exactly one mismatch with the same digest because it leaves the GPU inputs and work unchanged.
|
||||
|
||||
The executable returns 0 for a matching readback, 1 for mismatches, 2 for no feature-level-11.0 hardware device, 3 for another API failure, and 4 for invalid arguments.
|
||||
|
||||
## Build and run
|
||||
|
||||
Use the external llvm-mingw 20261117 UCRT macOS universal release pinned by the candidate in #384. Its archive SHA-256 is `98d340bbb8d46b09ad6886ffba88bd9d5415e131c316de48e6bd7647377446aa`. Clang and LLD are 23.1.6. The package ships both host slices and the recipe explicitly runs Clang as ARM64. The release includes LLVM's Apache-2.0 license with LLVM exceptions and dependency notices. See the archive's `LICENSE.TXT`. It is a build dependency and is supplied separately.
|
||||
|
||||
```sh
|
||||
tests/conformance/optional/d3d11-compute/build.sh /absolute/path/to/llvm-mingw /absolute/path/to/vkd3d-compiler
|
||||
```
|
||||
|
||||
The second dependency is WineHQ vkd3d-compiler 2.2 with libvkd3d-shader 2.2 (LGPL-2.1-or-later). The WineHQ 2.2 source archive used locally had SHA-256 `6f8cdbfc52e36eb74ab6aff42b1e958c3d9af912ab8f23d16d63711f2bab051b`. Use a native ARM64 build. The recipe compiles HLSL entry `main` to the `cs_5_0` profile in a tokenized DXBC container and embeds the resulting bytes in the executable. The guest gives those bytes directly to `CreateComputeShader`. Neither compiler is bundled or invoked by the guest.
|
||||
|
||||
Local compiler build inputs were the WineHQ release, Xcode Command Line Tools, pkgconf 2.5.1, Bison 3.8.2, system Flex, Vulkan-Headers `d4a196d8c84e032d27f999adcea3075517c1c97f` and SPIRV-Headers `3f17b2af6784bfa2c5aa5dbb8e0e74a607dd8b3b`. From the extracted vkd3d source, the local ARM64 build used:
|
||||
|
||||
```sh
|
||||
PKG_CONFIG=/absolute/path/to/pkgconf SONAME_LIBVULKAN=libMoltenVK.dylib \
|
||||
CPPFLAGS="-I$VULKAN_HEADERS/include -I$SPIRV_HEADERS/include" \
|
||||
./configure --disable-tests --disable-demos
|
||||
for grammar in hlsl preproc; do
|
||||
bison -d -o "libs/vkd3d-shader/$grammar.tab.c" "libs/vkd3d-shader/$grammar.y"
|
||||
done
|
||||
make include/private/vkd3d_version.h
|
||||
make -j2 vkd3d-compiler
|
||||
```
|
||||
|
||||
The Vulkan soname satisfies configure's runtime-library setting for the broader vkd3d project. The compiler target links libvkd3d-shader and does not link Vulkan or MoltenVK. The default guest build output is `artifacts/hybrid-workloads/x86_64/d3d11-compute.exe`.
|
||||
|
||||
Use a fresh dedicated Windows 11 64-bit bottle and the evidence-saving runner from #398. The runner's backend selector is observed CrossOver behavior. Record the backend evidence from each run.
|
||||
|
||||
```sh
|
||||
bx-cli run --bottle betterxen-issue-401 --backend dxvk \
|
||||
--timeout 45 --expect 'PASS cases=' --out artifacts/issue-401/run-records \
|
||||
-- "$PWD/artifacts/hybrid-workloads/x86_64/d3d11-compute.exe"
|
||||
bx-cli run --bottle betterxen-issue-401 --backend dxvk \
|
||||
--timeout 45 --expect 'PASS cases=' --out artifacts/issue-401/run-records \
|
||||
-- "$PWD/artifacts/hybrid-workloads/x86_64/d3d11-compute.exe" --negative-control
|
||||
```
|
||||
|
||||
The second command should return 1 and report one mismatch. A result without a guest exit code or completed readback is unavailable.
|
||||
|
||||
## Local evidence
|
||||
|
||||
Workload branch base: `566272082a74d8b45fcec37edd00f4f6703df3ab` (#384). The separate Rust 1.100.0 runner checkout used `e1b6a24a4f37360abb1f5c77bedbfd470cf1c720` (#398's persistence fix on #384). Host was an ARM64 Apple M2 Pro with 16 GiB and macOS 27.3 (26C5035r). CrossOver Preview was 20261111 (27.0.0.41303). The pinned archive checksum matched. Separate source and output directories produced identical DXBC (SHA-256 `af046791dce24119b0452d50cd30f69a2735de649161101cb5d0626625eebee0`) and x86-64 PE32+ executables (SHA-256 `2f92cd68266592039cdc4860a2c3896a15ddabb83dbecd0d1ed928599009095f`).
|
||||
|
||||
The default memory guard refused the first request at 49% free. Subsequent local runs used the runner's `--min-start-free 45` option with the default during-run floor. Run records are under ignored `artifacts/issue-401/precompiled-records/`. This is author-side verification. Independent derivation and CrossOver reproduction are pending.
|
||||
|
||||
| Requested backend | Evidence in the run record | Normal run | Negative control |
|
||||
| --- | --- | --- | --- |
|
||||
| D3DMetal | Inferred from the `AMD Compatibility Mode` adapter | Exit 0, zero mismatches | Exit 1, one mismatch |
|
||||
| DXVK | DXVK banner and `Apple M2 Pro` adapter | Exit 0, zero mismatches | Exit 1, one mismatch |
|
||||
|
||||
All four completed runs read back 3,456 words and matched the independently calculated digest `6ce404b5`. The initial memory refusal was the only unavailable run in the final evidence set. The runner intentionally classifies a negative-control exit 1 as a workload failure.
|
||||
|
||||
## References
|
||||
|
||||
- [llvm-mingw 20261117 release](https://github.com/mstorsjo/llvm-mingw/releases/tag/20261117)
|
||||
- [WineHQ vkd3d 2.2 release](https://list.winehq.org/hyperkitty/list/wine-announce%40list.winehq.org/thread/QBVNHPS2PLCJXA67ESIEY3XZP7BV4KRA/)
|
||||
- [Microsoft compute shader creation and profile example](https://learn.microsoft.com/en-us/windows/win32/direct3d11/direct3d-11-advanced-stages-compute-create)
|
||||
- [Microsoft structured-buffer resource](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-structuredbuffer)
|
||||
- [Microsoft thread-group size and dispatch IDs](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-attributes-numthreads)
|
||||
- [Microsoft CopyResource reference](https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-copyresource)
|
||||
- [Microsoft Map reference](https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-map)
|
||||
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user