mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 15:31:12 +00:00
Compare commits
71
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c126b94182 | ||
|
|
257aa1651a | ||
|
|
6c243259d9 | ||
|
|
58b209a71b | ||
|
|
b96aa5c0b8 | ||
|
|
463169f72c | ||
|
|
a6dc3faf50 | ||
|
|
56650b91c2 | ||
|
|
2505bc3a5b | ||
|
|
01f5590e88 | ||
|
|
21323cab80 | ||
|
|
b8724bf04f | ||
|
|
40a9cebb83 | ||
|
|
7056671c19 | ||
|
|
bd546d8a39 | ||
|
|
db193a3d16 | ||
|
|
cd945ba749 | ||
|
|
8381f57204 | ||
|
|
0b48688c13 | ||
|
|
c878ad5875 | ||
|
|
291047834a | ||
|
|
f07a24c28c | ||
|
|
aedd338980 | ||
|
|
e61e27055f | ||
|
|
0edb548e3d | ||
|
|
c13f9c7665 | ||
|
|
c219636ae2 | ||
|
|
0bd385cf05 | ||
|
|
38a21c2da1 | ||
|
|
c44ae4e221 | ||
|
|
af940476c6 | ||
|
|
6eaa594ae4 | ||
|
|
f0eb940504 | ||
|
|
d30b676813 | ||
|
|
4a585a79c6 | ||
|
|
b95b2c92a8 | ||
|
|
d38c5253c6 | ||
|
|
077e7d2f4e | ||
|
|
6fb171b247 | ||
|
|
482293fd35 | ||
|
|
993cd222a4 | ||
|
|
54b295434e | ||
|
|
8141b8e282 | ||
|
|
ba9a053b5c | ||
|
|
f6e0afeab1 | ||
|
|
f34b70dd45 | ||
|
|
e71fca720a | ||
|
|
83391f57be | ||
|
|
8877bff9f2 | ||
|
|
68d4b449f2 | ||
|
|
daeeaeae34 | ||
|
|
3b3e9f1c05 | ||
|
|
f016960021 | ||
|
|
cd72ef8ec3 | ||
|
|
6308fdc046 | ||
|
|
cf084e246b | ||
|
|
1571cf75c0 | ||
|
|
52e786664d | ||
|
|
b22ec27c79 | ||
|
|
0749dcf236 | ||
|
|
01a7435d35 | ||
|
|
2cc44b8318 | ||
|
|
ec65d79726 | ||
|
|
238daa6b25 | ||
|
|
7815a947e5 | ||
|
|
77dde94aa8 | ||
|
|
99bfbc26ef | ||
|
|
884f5398e7 | ||
|
|
1ec92916b9 | ||
|
|
9d504d12d7 | ||
|
|
e75b4131a3 |
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
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy --target x86_64-pc-windows-gnu
|
||||
rustc -vV
|
||||
- name: Check ARM64 Rust workspace (launcher + shader-transpiler)
|
||||
run: |
|
||||
|
||||
@@ -4,9 +4,9 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
|
||||
|
||||
---
|
||||
|
||||
## 0. First-Time Contributor Onboarding
|
||||
## 0. Contributor & Agent Task Dispatch (Onboarding & Priority Order)
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
1. **Preflight host & tools:**
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
|
||||
@@ -14,21 +14,33 @@ If the user asks to contribute, get started, or pick a task (even with a short 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. **Discover & pick an unclaimed issue:**
|
||||
- Query ready issues in the active milestone:
|
||||
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):
|
||||
```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 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:**
|
||||
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):**
|
||||
- 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` (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.
|
||||
- **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.
|
||||
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.
|
||||
@@ -64,8 +76,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
|
||||
- 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.
|
||||
- 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.
|
||||
- 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`.
|
||||
|
||||
---
|
||||
@@ -83,7 +95,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 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.
|
||||
- **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.
|
||||
|
||||
---
|
||||
|
||||
@@ -97,26 +109,32 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
|
||||
|
||||
---
|
||||
|
||||
## 6. Legal & Clean-Room Rules
|
||||
## 6. Compatibility Evidence & Legal Boundaries
|
||||
|
||||
- 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.
|
||||
- **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.
|
||||
- **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:** 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:**
|
||||
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:**
|
||||
```sh
|
||||
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
|
||||
```
|
||||
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.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
@@ -129,8 +147,9 @@ 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 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)
|
||||
# 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)
|
||||
scripts/build-shims.sh
|
||||
|
||||
# 3. Live synthetic PE32+ conformance tests inside CrossOver 26.3 + Rosetta 2
|
||||
@@ -141,3 +160,20 @@ 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.
|
||||
@@ -10,6 +10,44 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### 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.
|
||||
@@ -22,6 +60,12 @@ remains unsupported.
|
||||
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.
|
||||
@@ -65,6 +109,10 @@ 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.
|
||||
@@ -94,6 +142,9 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- 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).
|
||||
@@ -106,6 +157,9 @@ 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**.
|
||||
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).
|
||||
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, and independently authored synthetic workloads only. 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, 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.
|
||||
- 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).
|
||||
|
||||
@@ -67,7 +67,7 @@ Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
|
||||
|
||||
| Milestone | Scope | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
|
||||
| **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))** |
|
||||
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | ⚪ Planned |
|
||||
@@ -129,7 +129,7 @@ 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 16 shim DLLs |
|
||||
| [`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`) |
|
||||
| `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)) |
|
||||
@@ -165,8 +165,9 @@ 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 all 16 x86-64 PE32+ shim DLLs + conformance binaries
|
||||
# (automatically verifies every abi/defs/*.def export and zero MinGW runtime DLL deps)
|
||||
# 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)
|
||||
scripts/build-shims.sh
|
||||
|
||||
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + Rosetta 2
|
||||
@@ -208,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 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.
|
||||
- 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`.
|
||||
- `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 all 16 shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside 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.
|
||||
- **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.
|
||||
|
||||
+64
-2
@@ -1,8 +1,14 @@
|
||||
# Third-party notices
|
||||
|
||||
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has **zero external crates.io dependencies** and is original `GPL-3.0-or-later` source.
|
||||
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`.
|
||||
|
||||
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. Preserve the Rust Project Developers notice and permission text.
|
||||
`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.
|
||||
|
||||
## Vendored source files
|
||||
|
||||
| Files | Origin | License |
|
||||
| --- | --- | --- |
|
||||
| `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. |
|
||||
|
||||
## External Host Tools & Runtime Dependencies (Never Bundled)
|
||||
|
||||
@@ -13,3 +19,59 @@ The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has
|
||||
| `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.
|
||||
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).
|
||||
@@ -0,0 +1,5 @@
|
||||
LIBRARY bx_shader_bridge.dll
|
||||
EXPORTS
|
||||
bx_shader_inspect
|
||||
bx_shader_prepare_for_d3dmetal
|
||||
bx_shader_free_buffer
|
||||
+2
-1
@@ -15,6 +15,7 @@
|
||||
- [ADR 0005: CrossOver-based hybrid direction](adr/0005-crossover-hybrid-direction.md) — Pivot to CrossOver + Rosetta 2 + D3DMetal as the external foundation.
|
||||
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
|
||||
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
|
||||
- [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
|
||||
|
||||
@@ -22,7 +23,7 @@
|
||||
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
|
||||
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
|
||||
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
|
||||
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — One-host observation to check before M2 presentation work.
|
||||
- [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).
|
||||
- [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.
|
||||
|
||||
|
||||
@@ -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`.
|
||||
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`.
|
||||
|
||||
## Planning consequence
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# 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.
|
||||
@@ -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 16 shim DLLs load cleanly; auto-logging COM proxy captures startup call traces.
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
|
||||
## User-provided game files
|
||||
|
||||
|
||||
@@ -21,5 +21,8 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
|
||||
| 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,8 +1,7 @@
|
||||
# D3D12 swapchain references under D3DMetal
|
||||
|
||||
An observation to check before M2 builds presentation on `IDXGISwapChain3`. One Apple M4,
|
||||
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. Not independently reproduced, and not an
|
||||
Xbox hardware result.
|
||||
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 |
|
||||
| --- | --- | --- |
|
||||
@@ -18,3 +17,72 @@ 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.
|
||||
@@ -26,6 +26,22 @@ 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.
|
||||
|
||||
+3
-2
@@ -9,7 +9,8 @@ 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)
|
||||
shims/ (16 cross-compiled x86-64 PE32+ Xbox Game OS DLLs
|
||||
+ the Rust-built bx_shader_bridge.dll)
|
||||
shader-transpiler/ (DXBC / DXIL / ACCC / FSPX classifier & RDNA 2 pipeline)
|
||||
|
|
||||
External Foundation (user-installed, never bundled):
|
||||
@@ -36,7 +37,7 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
|
||||
|
||||
| Milestone | Objective | Exit Gate | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; 16/16 PE32+ DLLs pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
|
||||
| **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 |
|
||||
|
||||
@@ -7,16 +7,17 @@ use std::collections::BTreeMap;
|
||||
use std::env;
|
||||
use std::fmt::Write as _;
|
||||
use std::fs;
|
||||
use std::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitCode};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus};
|
||||
use bx_telemetry::summarize_jsonl;
|
||||
use bx_telemetry::{ShaderGap, TraceSummary, TrapCount, summarize_jsonl};
|
||||
use dxbc_accc::inspect_dxbc;
|
||||
use supervise::{Outcome, Stop};
|
||||
|
||||
const SHIM_DLL_OVERRIDES: &str = "bx_runtime_veh,d3d12_xs,xg_xs,xmem,XCRDAPI,xgameruntime,AcpHal,xapu,chad,GameInput,\
|
||||
const SHIM_DLL_OVERRIDES: &str = "bx_runtime_veh,d3d12_xs,xg_xs,xmem,xcrdapi,XCRDAPI,xgameruntime,acphal,AcpHal,xapu,chad,gameinput,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";
|
||||
@@ -165,14 +166,131 @@ fn cmd_probe(path: &str) -> ExitCode {
|
||||
|
||||
fn format_clwb_line(clwb_events: usize, clwb_trap_lower_bound: Option<u64>) -> String {
|
||||
if let Some(lower_bound) = clwb_trap_lower_bound {
|
||||
format!("clwb VEH traps : at least {lower_bound} (sampled)")
|
||||
format!("clwb VEH traps : at least {lower_bound} (sampled)")
|
||||
} else if clwb_events == 0 {
|
||||
"clwb VEH traps : 0".to_string()
|
||||
"clwb VEH traps : 0".to_string()
|
||||
} else {
|
||||
format!("clwb VEH samples : {clwb_events}")
|
||||
format!("clwb VEH samples : {clwb_events}")
|
||||
}
|
||||
}
|
||||
|
||||
fn format_amd_trap_line(name: &str, count: &TrapCount) -> String {
|
||||
let label = format!("{name} VEH traps");
|
||||
match count.lower_bound {
|
||||
Some(lower_bound) => format!("{label:<18} : at least {lower_bound} (sampled)"),
|
||||
None => format!("{label:<18} : {} samples", count.events),
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the log carried any shader-gate evidence. A log without it must render exactly as
|
||||
/// it did before the gate summary existed.
|
||||
fn has_shader_gate(summary: &TraceSummary) -> bool {
|
||||
summary.shader_gate.total > 0
|
||||
|| !summary.shader_gaps.is_empty()
|
||||
|| !summary.shader_bridge_missing.is_empty()
|
||||
}
|
||||
|
||||
/// One `label : value` line in the same column as the other trace lines.
|
||||
fn format_shader_line(label: &str, value: impl std::fmt::Display) -> String {
|
||||
format!("{label:<19} : {value}\n")
|
||||
}
|
||||
|
||||
/// A titled block of `{count:5}x {name}` lines, or nothing when there is nothing to count.
|
||||
fn format_count_list(title: &str, counts: &BTreeMap<String, usize>) -> String {
|
||||
if counts.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let mut out = format!("\n{title}:\n");
|
||||
for (name, count) in counts {
|
||||
let _ = writeln!(out, " {count:5}x {name}");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One `shader_d3dmetal_gap` record: the pipeline, stage, wave width it needs, and the 64-bit
|
||||
/// atomic feature flags that made it a gap. Missing fields say `unknown` rather than being lost.
|
||||
fn format_shader_gap_line(gap: &ShaderGap) -> String {
|
||||
format!(
|
||||
" pso={} stage={} wave_lanes_min={} atomic64_flags={}\n",
|
||||
gap.pso.as_deref().unwrap_or("unknown"),
|
||||
gap.stage.as_deref().unwrap_or("unknown"),
|
||||
gap.wave_lanes_min.as_deref().unwrap_or("unknown"),
|
||||
gap.atomic64_flags.as_deref().unwrap_or("unknown"),
|
||||
)
|
||||
}
|
||||
|
||||
/// One line per gate record whose decision is not a pass, naming the pipeline,
|
||||
/// stage, decision and HRESULT. These are the records a reader needs to find a
|
||||
/// blocker; the counted breakdown alone does not say which pipeline failed
|
||||
/// (#497 review point 5).
|
||||
fn format_non_pass_decisions(gate: &bx_telemetry::ShaderGateSummary) -> String {
|
||||
let failing: Vec<&bx_telemetry::ShaderGateRecord> = gate
|
||||
.records
|
||||
.iter()
|
||||
.filter(|record| {
|
||||
record
|
||||
.decision
|
||||
.as_deref()
|
||||
.is_some_and(|decision| !decision.starts_with("pass_"))
|
||||
})
|
||||
.collect();
|
||||
if failing.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let mut out = format!("\nNon-pass pipeline decisions ({}):\n", failing.len());
|
||||
for record in failing {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" pso={} stage={} decision={} hr={}",
|
||||
record.pso.as_deref().unwrap_or("unknown"),
|
||||
record.stage.as_deref().unwrap_or("unknown"),
|
||||
record.decision.as_deref().unwrap_or("unknown"),
|
||||
record.hr.as_deref().unwrap_or("unknown"),
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The shader-gate section, or an empty string for a log with no gate evidence.
|
||||
fn format_shader_gate_section(summary: &TraceSummary) -> String {
|
||||
if !has_shader_gate(summary) {
|
||||
return String::new();
|
||||
}
|
||||
let gate = &summary.shader_gate;
|
||||
let mut out = String::from("\nShader gate:\n");
|
||||
out.push_str(&format_shader_line("shader_gate records", gate.total));
|
||||
if gate.unparsed > 0 {
|
||||
out.push_str(&format_shader_line("unparsed details", gate.unparsed));
|
||||
}
|
||||
if gate.missing_decision > 0 {
|
||||
out.push_str(&format_shader_line(
|
||||
"records w/o decision",
|
||||
gate.missing_decision,
|
||||
));
|
||||
}
|
||||
out.push_str(&format_count_list("decisions", &gate.decisions));
|
||||
out.push_str(&format_count_list("kinds", &gate.kinds));
|
||||
out.push_str(&format_count_list("stages", &gate.stages));
|
||||
out.push_str(&format_non_pass_decisions(gate));
|
||||
if !summary.shader_gaps.is_empty() {
|
||||
let _ = writeln!(out, "\nD3DMetal gaps ({}):", summary.shader_gaps.len());
|
||||
for gap in &summary.shader_gaps {
|
||||
out.push_str(&format_shader_gap_line(gap));
|
||||
}
|
||||
}
|
||||
if !summary.shader_bridge_missing.is_empty() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nShader bridge missing ({}):",
|
||||
summary.shader_bridge_missing.len()
|
||||
);
|
||||
for message in &summary.shader_bridge_missing {
|
||||
let _ = writeln!(out, " {message}");
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn cmd_trace(path: &str) -> ExitCode {
|
||||
let text = match fs::read_to_string(path) {
|
||||
Ok(s) => s,
|
||||
@@ -188,20 +306,23 @@ fn cmd_trace(path: &str) -> ExitCode {
|
||||
fn render_trace(text: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let summary = summarize_jsonl(text);
|
||||
let _ = writeln!(out, "Trace events : {}", summary.total_lines);
|
||||
let _ = writeln!(out, "Trace events : {}", summary.total_lines);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{}",
|
||||
format_clwb_line(summary.clwb_events, summary.clwb_trap_lower_bound)
|
||||
);
|
||||
let _ = writeln!(out, "ADX illegal ops : {}", summary.adx_errors);
|
||||
for (name, count) in &summary.amd_traps {
|
||||
let _ = writeln!(out, "{}", format_amd_trap_line(name, count));
|
||||
}
|
||||
let _ = writeln!(out, "ADX illegal ops : {}", summary.adx_errors);
|
||||
if !summary.unhandled_exceptions.is_empty() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nUnhandled exceptions ({}):",
|
||||
summary.unhandled_exceptions.len()
|
||||
);
|
||||
for crash in summary.unhandled_exceptions {
|
||||
for crash in &summary.unhandled_exceptions {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" code={} module_base={} + RVA={} RIP={}",
|
||||
@@ -214,16 +335,17 @@ fn render_trace(text: &str) -> String {
|
||||
}
|
||||
if !summary.unimpl_apis.is_empty() {
|
||||
let _ = writeln!(out, "\nUnimplemented APIs:");
|
||||
for (api, count) in summary.unimpl_apis {
|
||||
for (api, count) in &summary.unimpl_apis {
|
||||
let _ = writeln!(out, " {count:5}x {api}");
|
||||
}
|
||||
}
|
||||
if !summary.unimpl_vtables.is_empty() {
|
||||
let _ = writeln!(out, "\nUnimplemented COM vtable slots:");
|
||||
for (slot, count) in summary.unimpl_vtables {
|
||||
for (slot, count) in &summary.unimpl_vtables {
|
||||
let _ = writeln!(out, " {count:5}x {slot}");
|
||||
}
|
||||
}
|
||||
out.push_str(&format_shader_gate_section(&summary));
|
||||
out
|
||||
}
|
||||
|
||||
@@ -425,6 +547,45 @@ where
|
||||
Ok(prefixes)
|
||||
}
|
||||
|
||||
/// The prefix a named bottle resolves to now, if that is no longer `staged_prefix`.
|
||||
///
|
||||
/// For a managed-only bottle CrossOver's `bin/wine` may create a private stub bottle and launch
|
||||
/// the guest there. Shims staged before launch then sit in a prefix the guest never used; this
|
||||
/// detects that so the run can say so instead of reporting "staged" (#474).
|
||||
fn staging_prefix_mismatch<F>(
|
||||
staged_prefix: &Path,
|
||||
bottle: Option<&str>,
|
||||
mut re_resolve: F,
|
||||
) -> Result<Option<PathBuf>, String>
|
||||
where
|
||||
F: FnMut(&str) -> Result<PathBuf, String>,
|
||||
{
|
||||
let Some(name) = bottle else {
|
||||
return Ok(None);
|
||||
};
|
||||
let current = re_resolve(name)?;
|
||||
let same = |a: &Path, b: &Path| {
|
||||
a == b || matches!((fs::canonicalize(a), fs::canonicalize(b)), (Ok(x), Ok(y)) if x == y)
|
||||
};
|
||||
Ok((!same(¤t, staged_prefix)).then_some(current))
|
||||
}
|
||||
|
||||
/// What is left of `--timeout` for the guest after initialization took `used`. `Ok(None)` means
|
||||
/// no limit. An error means initialization used all of it: the guest must not be started only to
|
||||
/// be reported as timed out, as if it had hung (#474).
|
||||
fn guest_time_left(timeout: Option<Duration>, used: Duration) -> Result<Option<Duration>, String> {
|
||||
match timeout {
|
||||
None => Ok(None),
|
||||
Some(limit) if used < limit => Ok(Some(limit - used)),
|
||||
Some(limit) => Err(format!(
|
||||
"initialization (prefix setup and shim staging) took {:.1}s and used the whole \
|
||||
--timeout of {:.1}s; the guest was not started",
|
||||
used.as_secs_f64(),
|
||||
limit.as_secs_f64()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `bin/wine` deletes an inherited `WINEDLLOVERRIDES` and applies the bottle's
|
||||
/// `[EnvironmentVariables]` over what it is given, so bottle mode passes both as options.
|
||||
fn bottle_options(backend: Option<&str>) -> Vec<String> {
|
||||
@@ -460,7 +621,37 @@ fn apply_prefix_env(command: &mut Command, cx_root: &Path, prefix: &Path, winelo
|
||||
);
|
||||
}
|
||||
|
||||
/// Reports a timeout or signal and stops the environment's `wineserver`. True if cleanup failed.
|
||||
/// Writes one diagnostic line to stderr. A closed pipe or hung-up terminal is ignored: unlike
|
||||
/// `eprintln!`, this cannot panic and so cannot cut a run's cleanup short (#461).
|
||||
fn diag(message: impl std::fmt::Display) {
|
||||
let _ = writeln!(std::io::stderr(), "{message}");
|
||||
}
|
||||
|
||||
/// Runs `cleanup` and only then reports the stop and any cleanup failures to `out`, ignoring
|
||||
/// write errors. True if cleanup reported a failure.
|
||||
///
|
||||
/// Cleanup comes first so that nothing about the diagnostic stream (Ctrl-C through `| tee`, a
|
||||
/// closed terminal) can prevent the environment from being stopped (#461).
|
||||
fn report_stop(
|
||||
stop: Stop,
|
||||
cleanup: impl FnOnce() -> Vec<String>,
|
||||
out: &mut dyn std::io::Write,
|
||||
) -> bool {
|
||||
let failures = cleanup();
|
||||
let _ = match stop {
|
||||
Stop::TimedOut => writeln!(out, "timed out; stopped the environment"),
|
||||
Stop::Signalled(signal) => {
|
||||
writeln!(out, "received signal {signal}; stopped the environment")
|
||||
}
|
||||
};
|
||||
for failure in &failures {
|
||||
let _ = writeln!(out, "{failure}");
|
||||
}
|
||||
!failures.is_empty()
|
||||
}
|
||||
|
||||
/// Stops the environment's `wineserver` after a timeout or signal, then reports it. True if
|
||||
/// cleanup failed.
|
||||
fn stop_environment(
|
||||
stop: Stop,
|
||||
cx_root: &Path,
|
||||
@@ -468,34 +659,111 @@ fn stop_environment(
|
||||
bottle: Option<&str>,
|
||||
inherit_env: bool,
|
||||
) -> bool {
|
||||
match stop {
|
||||
Stop::TimedOut => eprintln!("timed out; stopping the environment"),
|
||||
Stop::Signalled(signal) => {
|
||||
eprintln!("received signal {signal}; stopping the environment");
|
||||
}
|
||||
}
|
||||
let server_env: Vec<(String, String)> = collect_isolated_host_env(|k| env::var(k).ok())
|
||||
.into_iter()
|
||||
.collect();
|
||||
let mut cleanup_failed = false;
|
||||
let prefixes_to_stop = match cleanup_prefixes_for_stop(environment_dir, bottle, |name| {
|
||||
resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env)
|
||||
}) {
|
||||
Ok(prefixes) => prefixes,
|
||||
Err(e) => {
|
||||
eprintln!("cleanup failed to re-resolve bottle prefix: {e}");
|
||||
cleanup_failed = true;
|
||||
vec![environment_dir.to_path_buf()]
|
||||
let cleanup = || {
|
||||
let server_env: Vec<(String, String)> = collect_isolated_host_env(|k| env::var(k).ok())
|
||||
.into_iter()
|
||||
.collect();
|
||||
let mut failures = Vec::new();
|
||||
let prefixes_to_stop = match cleanup_prefixes_for_stop(environment_dir, bottle, |name| {
|
||||
resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env)
|
||||
}) {
|
||||
Ok(prefixes) => prefixes,
|
||||
Err(e) => {
|
||||
failures.push(format!("cleanup failed to re-resolve bottle prefix: {e}"));
|
||||
vec![environment_dir.to_path_buf()]
|
||||
}
|
||||
};
|
||||
for prefix in &prefixes_to_stop {
|
||||
if let Err(e) =
|
||||
supervise::stop_server(&cx_root.join("bin/wineserver"), prefix, &server_env)
|
||||
{
|
||||
failures.push(format!(
|
||||
"cleanup failed, programs may still be running: {e}"
|
||||
));
|
||||
}
|
||||
}
|
||||
failures
|
||||
};
|
||||
for prefix in &prefixes_to_stop {
|
||||
if let Err(e) = supervise::stop_server(&cx_root.join("bin/wineserver"), prefix, &server_env)
|
||||
{
|
||||
eprintln!("cleanup failed, programs may still be running: {e}");
|
||||
cleanup_failed = true;
|
||||
}
|
||||
}
|
||||
cleanup_failed
|
||||
report_stop(stop, cleanup, &mut std::io::stderr())
|
||||
}
|
||||
|
||||
/// How many trailing bytes of a log are remembered to recognize it again after the run.
|
||||
const LOG_MARK_TAIL: u64 = 256;
|
||||
|
||||
/// What a trace log was before the run: which file, how long, and how it ended.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct LogMark {
|
||||
/// Device and inode of the file.
|
||||
identity: (u64, u64),
|
||||
len: u64,
|
||||
/// The last bytes before `len` (up to [`LOG_MARK_TAIL`]).
|
||||
tail: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Opens `path` for reading only if it is a regular file.
|
||||
///
|
||||
/// `--log` can name anything. Opening a FIFO nobody writes to, or reading a terminal to its end,
|
||||
/// would block the run before the guest starts or after it has finished, so the open never
|
||||
/// waits and anything that is not a regular file is treated as having no log to summarize.
|
||||
fn open_regular_log(path: &Path) -> Option<(fs::File, fs::Metadata)> {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let file = fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(libc::O_NONBLOCK)
|
||||
.open(path)
|
||||
.ok()?;
|
||||
// Checked on the open handle, so the file cannot be swapped between the check and the read.
|
||||
let meta = file.metadata().ok()?;
|
||||
meta.is_file().then_some((file, meta))
|
||||
}
|
||||
|
||||
/// The mark of the log at `path`, or `None` if there is no readable regular-file log yet.
|
||||
fn log_mark(path: &Path) -> Option<LogMark> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let (mut file, meta) = open_regular_log(path)?;
|
||||
let len = meta.len();
|
||||
let tail_len = len.min(LOG_MARK_TAIL);
|
||||
file.seek(SeekFrom::Start(len - tail_len)).ok()?;
|
||||
let mut tail = Vec::new();
|
||||
file.take(tail_len).read_to_end(&mut tail).ok()?;
|
||||
Some(LogMark {
|
||||
identity: (meta.dev(), meta.ino()),
|
||||
len,
|
||||
tail,
|
||||
})
|
||||
}
|
||||
|
||||
/// A log's identity and contents, read through one open file so the two cannot disagree.
|
||||
fn read_log(path: &Path) -> Option<((u64, u64), Vec<u8>)> {
|
||||
use std::io::Read;
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let (mut file, meta) = open_regular_log(path)?;
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes).ok()?;
|
||||
Some(((meta.dev(), meta.ino()), bytes))
|
||||
}
|
||||
|
||||
/// The part of a trace log that this run added, given the log's mark from before the run.
|
||||
///
|
||||
/// The old length is used as an offset only when the log is still the same file and still holds
|
||||
/// the same bytes just before that offset. A log that was replaced or rewritten during the run,
|
||||
/// whatever its new size, is new in full, as is a log that did not exist before.
|
||||
fn appended_since<'a>(bytes: &'a [u8], identity: (u64, u64), before: Option<&LogMark>) -> &'a [u8] {
|
||||
let Some(mark) = before else {
|
||||
return bytes;
|
||||
};
|
||||
let appended = usize::try_from(mark.len).ok().and_then(|start| {
|
||||
let old_end = bytes.get(..start)?;
|
||||
(mark.identity == identity && old_end.ends_with(&mark.tail)).then(|| &bytes[start..])
|
||||
});
|
||||
appended.unwrap_or(bytes)
|
||||
}
|
||||
|
||||
/// The part of `elapsed` wall-clock time that counts against `--timeout`: everything except the
|
||||
/// `suspended` time spent stopped by Ctrl-Z, whichever phase of the run that fell in.
|
||||
fn active_time(elapsed: Duration, suspended: Duration) -> Duration {
|
||||
elapsed.saturating_sub(suspended)
|
||||
}
|
||||
|
||||
fn cmd_run(args: &[String]) -> ExitCode {
|
||||
@@ -562,10 +830,10 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
match supervise::supervise(boot, timeout, supervise::received_signal) {
|
||||
Ok(Outcome::Exited(st)) if st.success() => {}
|
||||
Ok(Outcome::Exited(st)) => {
|
||||
eprintln!(
|
||||
diag(format_args!(
|
||||
"error: wineboot --init failed for {}: {st}",
|
||||
resolved_prefix.display()
|
||||
);
|
||||
));
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
Ok(outcome @ Outcome::Stopped(stop)) => {
|
||||
@@ -574,27 +842,38 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
return ExitCode::from(if failed { code.max(1) } else { code });
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
diag(format_args!(
|
||||
"error: cannot run wineboot for {}: {e}",
|
||||
resolved_prefix.display()
|
||||
);
|
||||
));
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut staged_names: Vec<String> = Vec::new();
|
||||
match stage::stage_system32(&abs_shims, &system32) {
|
||||
Ok(staged) => {
|
||||
for item in &staged {
|
||||
eprintln!("bx-cli: {}", item.describe());
|
||||
if let stage::Staged::Copied(path)
|
||||
| stage::Staged::Replaced(path)
|
||||
| stage::Staged::ReplacedWineStub(path)
|
||||
| stage::Staged::Unchanged(path) = item
|
||||
&& let Some(name) = path.file_name()
|
||||
{
|
||||
staged_names.push(name.to_string_lossy().into_owned());
|
||||
}
|
||||
diag(format_args!("bx-cli: {}", item.describe()));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let hint = if bottle.is_some() {
|
||||
let hint = if bottle.is_some() && !system32.is_dir() {
|
||||
" (start the bottle once so CrossOver creates it)"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
eprintln!("error: cannot stage system32 shims: {e}{hint}");
|
||||
diag(format_args!(
|
||||
"error: cannot stage system32 shims: {e}{hint}"
|
||||
));
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
@@ -634,23 +913,30 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
if let Some(log) = &abs_log {
|
||||
cmd.env("BX_LOG_FILE", unix_to_wine_z_path(log));
|
||||
}
|
||||
let log_size = |log: &PathBuf| fs::metadata(log).map_or(0, |m| m.len());
|
||||
let log_size_before = abs_log.as_ref().map_or(0, log_size);
|
||||
let log_before = abs_log.as_deref().and_then(log_mark);
|
||||
|
||||
// `--timeout` bounds the whole run, including any prefix initialization above.
|
||||
let remaining = timeout.map(|limit| limit.saturating_sub(started.elapsed()));
|
||||
// `--timeout` bounds the whole run, including any prefix initialization above, but not
|
||||
// time the run spent suspended in either phase.
|
||||
let active = active_time(started.elapsed(), supervise::suspended_time());
|
||||
let remaining = match guest_time_left(timeout, active) {
|
||||
Ok(remaining) => remaining,
|
||||
Err(e) => {
|
||||
diag(format_args!("timed out during initialization: {e}"));
|
||||
return ExitCode::from(124);
|
||||
}
|
||||
};
|
||||
let outcome = supervise::supervise(cmd, remaining, supervise::received_signal);
|
||||
let code = match &outcome {
|
||||
Ok(outcome) => outcome.exit_code(),
|
||||
Err(e) => {
|
||||
eprintln!("failed to run CrossOver wine: {e}");
|
||||
diag(format_args!("failed to run CrossOver wine: {e}"));
|
||||
1
|
||||
}
|
||||
};
|
||||
let mut cleanup_failed = false;
|
||||
match &outcome {
|
||||
Ok(Outcome::Exited(status)) if !status.success() => {
|
||||
eprintln!("guest exited with status: {status}");
|
||||
diag(format_args!("guest exited with status: {status}"));
|
||||
}
|
||||
Ok(Outcome::Stopped(stop)) => {
|
||||
cleanup_failed = stop_environment(
|
||||
@@ -664,20 +950,71 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// Printed for failed and stopped runs too, which is when it matters most.
|
||||
// Printed for failed and stopped runs too, which is when it matters most. The log is
|
||||
// appended to across runs, so only what this run added is summarized.
|
||||
if let Some(log) = &abs_log
|
||||
&& log_size(log) > log_size_before
|
||||
&& let Ok(bytes) = fs::read(log)
|
||||
&& let Some((identity, bytes)) = read_log(log)
|
||||
{
|
||||
// Guest text may not be valid UTF-8; a summary is still worth printing.
|
||||
print!(
|
||||
"\nTrace summary of {}:\n{}",
|
||||
log.display(),
|
||||
render_trace(&String::from_utf8_lossy(&bytes))
|
||||
);
|
||||
let fresh = appended_since(&bytes, identity, log_before.as_ref());
|
||||
if !fresh.is_empty() {
|
||||
// Guest text may not be valid UTF-8; a summary is still worth printing. A closed
|
||||
// stdout must not turn into a panic after the run.
|
||||
let _ = write!(
|
||||
std::io::stdout(),
|
||||
"\nTrace summary of this run in {}:\n{}",
|
||||
log.display(),
|
||||
render_trace(&String::from_utf8_lossy(fresh))
|
||||
);
|
||||
}
|
||||
}
|
||||
// The reason for the stop is kept; a failed cleanup only turns success into failure.
|
||||
ExitCode::from(if cleanup_failed { code.max(1) } else { code })
|
||||
// #474: the shims were staged into the prefix resolved before launch. If CrossOver launched
|
||||
// the bottle from a different prefix that does not expose them, the guest never saw them,
|
||||
// and the run must not pass quietly. A different prefix alone is not a failure: a private
|
||||
// stub of a managed bottle links its system32 entries back to the managed prefix.
|
||||
let mut staged_elsewhere = false;
|
||||
if !staged_names.is_empty() {
|
||||
match staging_prefix_mismatch(&environment_dir, bottle.as_deref(), |name| {
|
||||
resolve_bottle_prefix_with_host_env(cx_root, name, inherit_env)
|
||||
}) {
|
||||
Ok(None) => {}
|
||||
Ok(Some(launched)) => {
|
||||
let missing = stage::shims_not_visible_in(
|
||||
&system32,
|
||||
&stage::system32_dir(&launched),
|
||||
&staged_names,
|
||||
);
|
||||
if missing.is_empty() {
|
||||
diag(format_args!(
|
||||
"bx-cli: bottle launched in {}; the shims staged in {} are visible there",
|
||||
launched.display(),
|
||||
environment_dir.display()
|
||||
));
|
||||
} else {
|
||||
staged_elsewhere = true;
|
||||
diag(format_args!(
|
||||
"error: system32 shims were staged in {} but CrossOver launched the \
|
||||
bottle in {}, where {} cannot be found as staged; the guest did not \
|
||||
see them. Run again: staging will now use the prefix the bottle \
|
||||
launches in",
|
||||
environment_dir.display(),
|
||||
launched.display(),
|
||||
missing.join(", ")
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(e) => diag(format_args!(
|
||||
"warning: cannot confirm which prefix the bottle launched in, so the staged \
|
||||
system32 shims may not have been used: {e}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
// The reason for the stop is kept; a failed cleanup or misplaced staging only turns success
|
||||
// into failure.
|
||||
ExitCode::from(if cleanup_failed || staged_elsewhere {
|
||||
code.max(1)
|
||||
} else {
|
||||
code
|
||||
})
|
||||
}
|
||||
|
||||
fn cmd_shader(path: &str) -> ExitCode {
|
||||
@@ -734,6 +1071,265 @@ fn main() -> ExitCode {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A stream whose reader is gone: every write fails, as with EPIPE or EIO.
|
||||
struct ClosedStream<'a> {
|
||||
cleanup_done: &'a std::cell::Cell<bool>,
|
||||
writes_before_cleanup: usize,
|
||||
writes: usize,
|
||||
}
|
||||
|
||||
impl std::io::Write for ClosedStream<'_> {
|
||||
fn write(&mut self, _buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.writes += 1;
|
||||
if !self.cleanup_done.get() {
|
||||
self.writes_before_cleanup += 1;
|
||||
}
|
||||
Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_diagnostic_stream_cannot_skip_cleanup() {
|
||||
for stop in [Stop::Signalled(libc::SIGINT), Stop::TimedOut] {
|
||||
let cleanup_done = std::cell::Cell::new(false);
|
||||
let mut closed = ClosedStream {
|
||||
cleanup_done: &cleanup_done,
|
||||
writes_before_cleanup: 0,
|
||||
writes: 0,
|
||||
};
|
||||
let failed = report_stop(
|
||||
stop,
|
||||
|| {
|
||||
cleanup_done.set(true);
|
||||
vec!["cleanup failed, programs may still be running: stub".to_string()]
|
||||
},
|
||||
&mut closed,
|
||||
);
|
||||
assert!(cleanup_done.get(), "cleanup did not run for {stop:?}");
|
||||
assert!(failed, "the cleanup failure was lost for {stop:?}");
|
||||
assert!(closed.writes > 0, "nothing was reported for {stop:?}");
|
||||
assert_eq!(
|
||||
closed.writes_before_cleanup, 0,
|
||||
"output came before cleanup"
|
||||
);
|
||||
}
|
||||
let mut text = Vec::new();
|
||||
assert!(!report_stop(Stop::Signalled(2), Vec::new, &mut text));
|
||||
assert_eq!(
|
||||
String::from_utf8(text).unwrap(),
|
||||
"received signal 2; stopped the environment\n"
|
||||
);
|
||||
}
|
||||
|
||||
fn mark(identity: (u64, u64), contents: &str) -> LogMark {
|
||||
let bytes = contents.as_bytes();
|
||||
let tail_start = bytes.len().saturating_sub(LOG_MARK_TAIL as usize);
|
||||
LogMark {
|
||||
identity,
|
||||
len: bytes.len() as u64,
|
||||
tail: bytes[tail_start..].to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_trace_summary_covers_only_what_this_run_appended() {
|
||||
let file = (1, 100);
|
||||
let earlier = "{\"event\":\"unimpl_api\",\"detail\":\"old.dll!Earlier\"}\n";
|
||||
let this_run = "{\"event\":\"unimpl_api\",\"detail\":\"new.dll!ThisRun\"}\n";
|
||||
let log = format!("{earlier}{this_run}");
|
||||
let before = mark(file, earlier);
|
||||
let fresh = appended_since(log.as_bytes(), file, Some(&before));
|
||||
assert_eq!(fresh, this_run.as_bytes());
|
||||
let rendered = render_trace(&String::from_utf8_lossy(fresh));
|
||||
assert!(rendered.contains("new.dll!ThisRun"), "{rendered}");
|
||||
assert!(!rendered.contains("old.dll!Earlier"), "{rendered}");
|
||||
// Nothing appended: nothing to summarize.
|
||||
assert!(appended_since(earlier.as_bytes(), file, Some(&before)).is_empty());
|
||||
// No log before the run: everything in it is from this run.
|
||||
assert_eq!(
|
||||
appended_since(this_run.as_bytes(), file, None),
|
||||
this_run.as_bytes()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replaced_log_is_summarized_in_full_whatever_its_size() {
|
||||
let old_file = (1, 100);
|
||||
let new_file = (1, 200);
|
||||
let old = "{\"event\":\"unimpl_api\",\"detail\":\"old.dll!Earlier\"}\n";
|
||||
let before = mark(old_file, old);
|
||||
let record = "{\"event\":\"unimpl_api\",\"detail\":\"new.dll!A\"}\n";
|
||||
// Shorter, exactly as long, and longer than the old log: the old length must never be
|
||||
// used as an offset into a different file.
|
||||
let shorter = &record[..record.len() - 1];
|
||||
let same_size = format!("{:<width$}\n", record.trim_end(), width = old.len() - 1);
|
||||
let longer = format!("{record}{record}{record}");
|
||||
assert!(shorter.len() < old.len() && same_size.len() == old.len());
|
||||
assert!(longer.len() > old.len());
|
||||
for replacement in [shorter, same_size.as_str(), longer.as_str()] {
|
||||
let fresh = appended_since(replacement.as_bytes(), new_file, Some(&before));
|
||||
assert_eq!(fresh, replacement.as_bytes(), "{} bytes", replacement.len());
|
||||
}
|
||||
// Rewritten in place (same file, different contents before the old end).
|
||||
let fresh = appended_since(longer.as_bytes(), old_file, Some(&before));
|
||||
assert_eq!(fresh, longer.as_bytes());
|
||||
assert_eq!(
|
||||
summarize_jsonl(&String::from_utf8_lossy(fresh)).total_lines,
|
||||
3
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_different_file_is_new_in_full_even_when_it_starts_with_the_old_bytes() {
|
||||
// Only the file identity can tell these apart: the replacement begins with exactly the
|
||||
// old log's bytes and then has more, so the bytes before the old end still match.
|
||||
let old = "{\"event\":\"unimpl_api\",\"detail\":\"old.dll!Earlier\"}\n";
|
||||
let more = "{\"event\":\"unimpl_api\",\"detail\":\"new.dll!ThisRun\"}\n";
|
||||
let replacement = format!("{old}{more}");
|
||||
let before = mark((1, 100), old);
|
||||
let fresh = appended_since(replacement.as_bytes(), (1, 200), Some(&before));
|
||||
assert_eq!(fresh, replacement.as_bytes());
|
||||
// Control: the same bytes in the same file are an append, and only the rest is new.
|
||||
let appended = appended_since(replacement.as_bytes(), (1, 100), Some(&before));
|
||||
assert_eq!(appended, more.as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_log_path_that_is_not_a_regular_file_never_blocks_the_run() {
|
||||
let dir = env::temp_dir().join(format!("bx-cli-lognonfile-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let fifo = dir.join("trace.fifo");
|
||||
let made = Command::new("/usr/bin/mkfifo").arg(&fifo).status().unwrap();
|
||||
assert!(made.success());
|
||||
// A FIFO with no writer: a plain open for reading would wait here forever.
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let probe = fifo.clone();
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send((log_mark(&probe), read_log(&probe)));
|
||||
});
|
||||
let (mark_of_fifo, contents_of_fifo) = rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("reading a FIFO log path blocked");
|
||||
assert_eq!(mark_of_fifo, None);
|
||||
assert_eq!(contents_of_fifo, None);
|
||||
// A directory and a missing path are not logs either; a regular file still is.
|
||||
assert_eq!(log_mark(&dir), None);
|
||||
assert_eq!(read_log(&dir), None);
|
||||
assert_eq!(log_mark(&dir.join("absent")), None);
|
||||
let real = dir.join("trace.jsonl");
|
||||
fs::write(&real, "{}\n").unwrap();
|
||||
assert_eq!(log_mark(&real).map(|m| m.len), Some(3));
|
||||
assert_eq!(
|
||||
read_log(&real).map(|(_, bytes)| bytes),
|
||||
Some(b"{}\n".to_vec())
|
||||
);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn log_marks_follow_the_file_on_disk() {
|
||||
let dir = env::temp_dir().join(format!("bx-cli-logmark-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let log = dir.join("trace.jsonl");
|
||||
assert_eq!(log_mark(&log), None);
|
||||
let old = "{\"event\":\"unimpl_api\",\"detail\":\"old.dll!Earlier\"}\n";
|
||||
fs::write(&log, old).unwrap();
|
||||
let before = log_mark(&log).unwrap();
|
||||
assert_eq!(before.len, old.len() as u64);
|
||||
assert_eq!(before.tail, old.as_bytes());
|
||||
|
||||
// Appended to, as bx_runtime_veh does: only the new record is this run's.
|
||||
let added = "{\"event\":\"unimpl_api\",\"detail\":\"new.dll!ThisRun\"}\n";
|
||||
fs::write(&log, format!("{old}{added}")).unwrap();
|
||||
let (identity, bytes) = read_log(&log).unwrap();
|
||||
assert_eq!(
|
||||
appended_since(&bytes, identity, Some(&before)),
|
||||
added.as_bytes()
|
||||
);
|
||||
|
||||
// Replaced by a new, longer file during the run: all of it is this run's.
|
||||
let replacement = dir.join("replacement");
|
||||
let longer = format!("{added}{added}{added}");
|
||||
fs::write(&replacement, &longer).unwrap();
|
||||
fs::rename(&replacement, &log).unwrap();
|
||||
let (identity, bytes) = read_log(&log).unwrap();
|
||||
assert_ne!(identity, before.identity);
|
||||
let fresh = appended_since(&bytes, identity, Some(&before));
|
||||
assert_eq!(
|
||||
summarize_jsonl(&String::from_utf8_lossy(fresh)).total_lines,
|
||||
3
|
||||
);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pause_in_an_earlier_phase_is_not_charged_to_the_guest() {
|
||||
let limit = Some(Duration::from_secs(2));
|
||||
let ms = Duration::from_millis;
|
||||
// As reviewed: paused 2.5 s during wineboot with --timeout 2, 0.3 s actually running.
|
||||
assert_eq!(
|
||||
guest_time_left(limit, active_time(ms(2800), ms(2500))),
|
||||
Ok(Some(ms(1700)))
|
||||
);
|
||||
// Without a pause the wall clock counts in full.
|
||||
assert_eq!(
|
||||
guest_time_left(limit, active_time(ms(500), Duration::ZERO)),
|
||||
Ok(Some(ms(1500)))
|
||||
);
|
||||
// Initialization that really ran for the whole timeout still stops the launch.
|
||||
assert!(guest_time_left(limit, active_time(ms(5000), ms(2500))).is_err());
|
||||
// More suspension than elapsed time cannot go negative.
|
||||
assert_eq!(active_time(ms(100), ms(900)), Duration::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staging_into_a_prefix_the_bottle_did_not_launch_in_is_reported() {
|
||||
let resolved_before = Path::new("/bottles/managed/corp");
|
||||
let stub = PathBuf::from("/bottles/private/corp");
|
||||
// CrossOver created a private stub during launch: the bottle now resolves there.
|
||||
let moved = staging_prefix_mismatch(resolved_before, Some("corp"), |name| {
|
||||
assert_eq!(name, "corp");
|
||||
Ok(stub.clone())
|
||||
});
|
||||
assert_eq!(moved, Ok(Some(stub)));
|
||||
// The usual case: the bottle still resolves to where the shims went.
|
||||
let same = staging_prefix_mismatch(resolved_before, Some("corp"), |_| {
|
||||
Ok(resolved_before.to_path_buf())
|
||||
});
|
||||
assert_eq!(same, Ok(None));
|
||||
// A bare --prefix is launched exactly where it was staged; nothing is re-resolved.
|
||||
let bare = staging_prefix_mismatch(resolved_before, None, |_| {
|
||||
panic!("a bare prefix must not be re-resolved")
|
||||
});
|
||||
assert_eq!(bare, Ok(None));
|
||||
// A resolver failure is passed on, not mistaken for a match.
|
||||
let failed = staging_prefix_mismatch(resolved_before, Some("corp"), |_| {
|
||||
Err("cannot locate".to_string())
|
||||
});
|
||||
assert_eq!(failed, Err("cannot locate".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_guest_is_not_started_when_initialization_used_the_whole_timeout() {
|
||||
let limit = Some(Duration::from_secs(30));
|
||||
assert_eq!(guest_time_left(None, Duration::from_secs(999)), Ok(None));
|
||||
assert_eq!(
|
||||
guest_time_left(limit, Duration::from_secs(12)),
|
||||
Ok(Some(Duration::from_secs(18)))
|
||||
);
|
||||
for used in [Duration::from_secs(30), Duration::from_secs(45)] {
|
||||
let err = guest_time_left(limit, used).unwrap_err();
|
||||
assert!(err.contains("initialization"), "{err}");
|
||||
assert!(err.contains("guest was not started"), "{err}");
|
||||
}
|
||||
}
|
||||
|
||||
fn args(list: &[&str]) -> Vec<String> {
|
||||
list.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
@@ -953,12 +1549,117 @@ sub setup_bottle_wineprefix {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_clwb_summary_lines() {
|
||||
assert_eq!(format_clwb_line(0, None), "clwb VEH traps : 0");
|
||||
assert_eq!(format_clwb_line(2, None), "clwb VEH samples : 2");
|
||||
fn formats_amd_trap_summary_lines() {
|
||||
let sampled = TrapCount {
|
||||
events: 3,
|
||||
lower_bound: Some(4),
|
||||
};
|
||||
assert_eq!(
|
||||
format_clwb_line(3, Some(4)),
|
||||
"clwb VEH traps : at least 4 (sampled)"
|
||||
format_amd_trap_line("clzero", &sampled),
|
||||
"clzero VEH traps : at least 4 (sampled)"
|
||||
);
|
||||
assert_eq!(
|
||||
format_amd_trap_line("monitorx", &sampled),
|
||||
"monitorx VEH traps : at least 4 (sampled)"
|
||||
);
|
||||
let unnumbered = TrapCount {
|
||||
events: 2,
|
||||
lower_bound: None,
|
||||
};
|
||||
assert_eq!(
|
||||
format_amd_trap_line("rdpru", &unnumbered),
|
||||
"rdpru VEH traps : 2 samples"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_clwb_summary_lines() {
|
||||
assert_eq!(format_clwb_line(0, None), "clwb VEH traps : 0");
|
||||
assert_eq!(format_clwb_line(2, None), "clwb VEH samples : 2");
|
||||
assert_eq!(
|
||||
format_clwb_line(3, Some(4)),
|
||||
"clwb VEH traps : at least 4 (sampled)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_log_without_shader_gate_records_renders_as_before() {
|
||||
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"runtime_veh","event":"clwb_trapped","detail":"rip=0x1000 len=4 total_traps=1"}
|
||||
{"ts_ms":12,"tid":1,"level":"WARN","sub":"stub","event":"unimpl_api","detail":"d3d12_xs.dll!D3D12XboxCreateDevice"}
|
||||
{"ts_ms":16,"tid":1,"level":"WARN","sub":"com_vtable","event":"unimpl_vtable","detail":"ID3D12Device11[44]::CreatePlacedResourceX"}
|
||||
"#;
|
||||
let rendered = render_trace(log);
|
||||
assert!(!rendered.contains("Shader"), "{rendered}");
|
||||
assert!(!rendered.contains("shader_gate"), "{rendered}");
|
||||
assert_eq!(
|
||||
rendered,
|
||||
"Trace events : 3\n\
|
||||
clwb VEH traps : at least 1 (sampled)\n\
|
||||
ADX illegal ops : 0\n\
|
||||
\n\
|
||||
Unimplemented APIs:\n\
|
||||
\x20 1x d3d12_xs.dll!D3D12XboxCreateDevice\n\
|
||||
\n\
|
||||
Unimplemented COM vtable slots:\n\
|
||||
\x20 1x ID3D12Device11[44]::CreatePlacedResourceX\n"
|
||||
);
|
||||
assert_eq!(format_shader_gate_section(&summarize_jsonl(log)), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_decisions_kinds_stages_gaps_and_missing_bridge() {
|
||||
// Realistic records, matching the emitter in shims/d3d12_xs/shader_gate.cpp.
|
||||
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"}
|
||||
{"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"}
|
||||
{"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)"}
|
||||
{"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 rendered = render_trace(log);
|
||||
assert!(rendered.contains("Shader gate:"), "{rendered}");
|
||||
assert!(rendered.contains("shader_gate records : 2"), "{rendered}");
|
||||
assert!(rendered.contains("decisions:"), "{rendered}");
|
||||
assert!(rendered.contains(" 1x pass_dxil"), "{rendered}");
|
||||
assert!(rendered.contains(" 1x reject_accc_only"), "{rendered}");
|
||||
assert!(rendered.contains("kinds:"), "{rendered}");
|
||||
assert!(rendered.contains(" 1x dxil"), "{rendered}");
|
||||
assert!(rendered.contains(" 1x accc_only"), "{rendered}");
|
||||
assert!(rendered.contains("stages:"), "{rendered}");
|
||||
assert!(rendered.contains(" 1x CS"), "{rendered}");
|
||||
assert!(rendered.contains(" 1x VS"), "{rendered}");
|
||||
assert!(rendered.contains("D3DMetal gaps (1):"), "{rendered}");
|
||||
assert!(
|
||||
rendered.contains(" pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(
|
||||
rendered.contains("Shader bridge missing (1):"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(
|
||||
rendered.contains("bx_shader_bridge.dll not found beside d3d12_xs.dll"),
|
||||
"{rendered}"
|
||||
);
|
||||
// #497 review point 5: name the rejected pipeline and its HRESULT, not just a count.
|
||||
assert!(
|
||||
rendered.contains("Non-pass pipeline decisions (1):"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(
|
||||
rendered.contains("pso=graphics stage=VS decision=reject_accc_only hr=0x80004001"),
|
||||
"{rendered}"
|
||||
);
|
||||
assert!(!rendered.contains("decision=pass_dxil hr="), "{rendered}");
|
||||
assert!(!rendered.contains("unparsed"), "{rendered}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unparsable_shader_gate_detail_shows_the_unparsed_count() {
|
||||
let log = r#"{"ts_ms":20,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"garbage"}
|
||||
{"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 rendered = render_trace(log);
|
||||
assert!(rendered.contains("shader_gate records : 2"), "{rendered}");
|
||||
assert!(rendered.contains("unparsed details : 1"), "{rendered}");
|
||||
assert!(rendered.contains(" 1x pass_dxil"), "{rendered}");
|
||||
}
|
||||
}
|
||||
@@ -8,14 +8,43 @@
|
||||
//! The same search flags apply to the DLL's own imports, so every BetterXen shim it imports
|
||||
//! (for example `bx_runtime_veh.dll`) is staged too. Otherwise the load fails unless the guest
|
||||
//! happened to load that dependency earlier.
|
||||
//!
|
||||
//! #474: a bottle's `system32` is not ours. Staging records what it wrote in a `.bx-staged`
|
||||
//! manifest there (one SHA-256 per file) and afterwards replaces only files that are listed and
|
||||
//! still have the recorded hash. A file of the same name that the bottle already had, or that
|
||||
//! was changed since, is never modified: staging stops with an error that names it.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Shims loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`.
|
||||
pub const SYSTEM32_SHIMS: &[&str] = &["xgameruntime.dll"];
|
||||
/// Shims loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32` (or shadowed by Wine builtin stubs in
|
||||
/// `system32`, which Windows searches before `WINEPATH`).
|
||||
pub const SYSTEM32_SHIMS: &[&str] = &["xgameruntime.dll", "GameInput.dll"];
|
||||
|
||||
/// Returns true when `bytes` is a Wine `winebuild` fake-DLL placeholder stub in `system32`
|
||||
/// (`"MZ"` header, `"Wine builtin DLL\0"` at DOS offset `0x40`, and `"PE\0\0"` at `e_lfanew`).
|
||||
///
|
||||
/// Wine populates `drive_c/windows/system32/` with fake PE stubs for built-in modules such as
|
||||
/// `gameinput.dll`. Unlike user- or installer-provided native DLLs (#474), these placeholders are
|
||||
/// created by Wine itself and would otherwise shadow BetterXen shims on `LOAD_LIBRARY_SEARCH_SYSTEM32`
|
||||
/// loads (`fixme:ginput:GameInputCreate ... stub!`).
|
||||
pub fn is_wine_builtin_dll(bytes: &[u8]) -> bool {
|
||||
const WINE_SIG_OFFSET: usize = 0x40;
|
||||
const WINE_SIG: &[u8] = b"Wine builtin DLL\0";
|
||||
if bytes.len() < WINE_SIG_OFFSET + WINE_SIG.len() + 4 {
|
||||
return false;
|
||||
}
|
||||
if &bytes[0..2] != b"MZ" {
|
||||
return false;
|
||||
}
|
||||
if &bytes[WINE_SIG_OFFSET..WINE_SIG_OFFSET + WINE_SIG.len()] != WINE_SIG {
|
||||
return false;
|
||||
}
|
||||
let pe_off = u32::from_le_bytes([bytes[0x3c], bytes[0x3d], bytes[0x3e], bytes[0x3f]]) as usize;
|
||||
pe_off >= WINE_SIG_OFFSET + WINE_SIG.len() && bytes.get(pe_off..pe_off + 4) == Some(b"PE\0\0")
|
||||
}
|
||||
|
||||
/// `roots` plus, transitively, every import that is itself a file in the shim folder
|
||||
/// (`is_shim`). Names are compared case-insensitively, as the Windows loader does, and returned
|
||||
@@ -74,11 +103,149 @@ pub fn system32_dir(prefix: &Path) -> PathBuf {
|
||||
prefix.join("drive_c").join("windows").join("system32")
|
||||
}
|
||||
|
||||
/// SHA-256 (FIPS 180-4), used only to recognize files this tool staged earlier.
|
||||
pub fn sha256_hex(data: &[u8]) -> String {
|
||||
const K: [u32; 64] = [
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
|
||||
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
|
||||
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
|
||||
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
|
||||
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
|
||||
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
|
||||
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
|
||||
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
|
||||
0xc67178f2,
|
||||
];
|
||||
let mut h: [u32; 8] = [
|
||||
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
|
||||
0x5be0cd19,
|
||||
];
|
||||
let mut message = data.to_vec();
|
||||
message.push(0x80);
|
||||
while message.len() % 64 != 56 {
|
||||
message.push(0);
|
||||
}
|
||||
message.extend_from_slice(&((data.len() as u64).wrapping_mul(8)).to_be_bytes());
|
||||
for block in message.chunks_exact(64) {
|
||||
let mut w = [0u32; 64];
|
||||
for (i, word) in block.chunks_exact(4).enumerate() {
|
||||
w[i] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
|
||||
}
|
||||
for i in 16..64 {
|
||||
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
|
||||
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
|
||||
w[i] = w[i - 16]
|
||||
.wrapping_add(s0)
|
||||
.wrapping_add(w[i - 7])
|
||||
.wrapping_add(s1);
|
||||
}
|
||||
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
|
||||
for i in 0..64 {
|
||||
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
|
||||
let ch = (e & f) ^ (!e & g);
|
||||
let t1 = hh
|
||||
.wrapping_add(s1)
|
||||
.wrapping_add(ch)
|
||||
.wrapping_add(K[i])
|
||||
.wrapping_add(w[i]);
|
||||
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
|
||||
let maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
let t2 = s0.wrapping_add(maj);
|
||||
hh = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d.wrapping_add(t1);
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = t1.wrapping_add(t2);
|
||||
}
|
||||
for (state, value) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
|
||||
*state = state.wrapping_add(value);
|
||||
}
|
||||
}
|
||||
h.iter().map(|word| format!("{word:08x}")).collect()
|
||||
}
|
||||
|
||||
/// Name of the ownership record kept in `system32`.
|
||||
pub const MANIFEST_NAME: &str = ".bx-staged";
|
||||
|
||||
/// The files this tool staged into a `system32`, as lowercase name -> SHA-256 of what it wrote.
|
||||
///
|
||||
/// A file is BetterXen's to refresh only while it is listed here and still has the recorded
|
||||
/// hash. Anything else in `system32` belongs to the bottle and is never modified (#474).
|
||||
fn read_manifest(system32: &Path) -> Result<BTreeMap<String, String>, String> {
|
||||
let path = system32.join(MANIFEST_NAME);
|
||||
let text = match fs::read_to_string(&path) {
|
||||
Ok(text) => text,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
|
||||
Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
|
||||
};
|
||||
let mut owned = BTreeMap::new();
|
||||
for line in text.lines() {
|
||||
// "<64 hex digits> <name>", as `shasum -a 256` prints. Other lines are ignored, which
|
||||
// only ever makes a file look foreign.
|
||||
if let Some((hash, name)) = line.split_once(" ")
|
||||
&& hash.len() == 64
|
||||
&& hash.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
&& !name.is_empty()
|
||||
{
|
||||
owned.insert(name.to_ascii_lowercase(), hash.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
Ok(owned)
|
||||
}
|
||||
|
||||
fn write_manifest(system32: &Path, owned: &BTreeMap<String, String>) -> Result<(), String> {
|
||||
let mut text = String::from(
|
||||
"# Files staged by bx-cli (sha256, two spaces, name). bx-cli replaces only these.\n",
|
||||
);
|
||||
for (name, hash) in owned {
|
||||
text.push_str(&format!("{hash} {name}\n"));
|
||||
}
|
||||
let path = system32.join(MANIFEST_NAME);
|
||||
let tmp = system32.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
|
||||
fs::write(&tmp, text).map_err(|e| {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
format!("cannot write {}: {e}", tmp.display())
|
||||
})?;
|
||||
fs::rename(&tmp, &path).map_err(|e| {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
format!("cannot replace {}: {e}", path.display())
|
||||
})
|
||||
}
|
||||
|
||||
/// Names from `names` that a guest in `launched_system32` would not find as staged: the entry
|
||||
/// there is missing or, read through any link, does not have the bytes of the staged copy in
|
||||
/// `staged_system32`.
|
||||
///
|
||||
/// CrossOver may launch a managed bottle from a private stub whose `system32` links back to the
|
||||
/// managed prefix, so a different directory alone does not mean the shims were missed (#474).
|
||||
pub fn shims_not_visible_in(
|
||||
staged_system32: &Path,
|
||||
launched_system32: &Path,
|
||||
names: &[String],
|
||||
) -> Vec<String> {
|
||||
names
|
||||
.iter()
|
||||
.filter(|name| {
|
||||
let staged = fs::read(staged_system32.join(name));
|
||||
let seen = fs::read(launched_system32.join(name));
|
||||
!matches!((staged, seen), (Ok(a), Ok(b)) if a == b)
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What staging did to one file.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Staged {
|
||||
Copied(PathBuf),
|
||||
/// An earlier copy staged by this tool, refreshed because the shim changed.
|
||||
Replaced(PathBuf),
|
||||
/// A Wine `"Wine builtin DLL"` placeholder stub in `system32`, backed up once and replaced.
|
||||
ReplacedWineStub(PathBuf),
|
||||
Unchanged(PathBuf),
|
||||
/// A [`SYSTEM32_SHIMS`] file the shim folder does not have.
|
||||
Absent(PathBuf),
|
||||
@@ -88,7 +255,10 @@ impl Staged {
|
||||
pub fn describe(&self) -> String {
|
||||
match self {
|
||||
Staged::Copied(p) => format!("staged {}", p.display()),
|
||||
Staged::Replaced(p) => format!("replaced {}", p.display()),
|
||||
Staged::Replaced(p) => format!("refreshed own earlier copy {}", p.display()),
|
||||
Staged::ReplacedWineStub(p) => {
|
||||
format!("replaced Wine builtin stub {} (backup saved)", p.display())
|
||||
}
|
||||
Staged::Unchanged(p) => format!("already current {}", p.display()),
|
||||
Staged::Absent(p) => format!("not staged, {} not found", p.display()),
|
||||
}
|
||||
@@ -106,7 +276,11 @@ pub fn has_system32_shims(shims_dir: &Path) -> bool {
|
||||
/// `system32`. The directory must already exist (an uninitialized prefix is a caller error, not
|
||||
/// something to skip). A shim the folder does not have is reported as [`Staged::Absent`], so a
|
||||
/// run with a partial `--shims` folder still starts. A copy already identical byte for byte is
|
||||
/// left alone, a different one is replaced. Nothing outside `system32` is written.
|
||||
/// left alone. A different one is replaced only if this tool staged it and it is unchanged since
|
||||
/// (see [`MANIFEST_NAME`]); any other existing entry, including a symbolic link that points
|
||||
/// nowhere, is an error and nothing is written, so a DLL the bottle already had is never
|
||||
/// modified or deleted. New files are installed without replacing anything, and each installed
|
||||
/// file is recorded before the next one is touched. Nothing outside `system32` is written.
|
||||
pub fn stage_system32(shims_dir: &Path, system32: &Path) -> Result<Vec<Staged>, String> {
|
||||
stage_system32_with(shims_dir, system32, pe_imports)
|
||||
}
|
||||
@@ -114,10 +288,44 @@ pub fn stage_system32(shims_dir: &Path, system32: &Path) -> Result<Vec<Staged>,
|
||||
fn stage_system32_with<I>(
|
||||
shims_dir: &Path,
|
||||
system32: &Path,
|
||||
mut imports_of: I,
|
||||
imports_of: I,
|
||||
) -> Result<Vec<Staged>, String>
|
||||
where
|
||||
I: FnMut(&Path) -> Result<Vec<String>, String>,
|
||||
{
|
||||
stage_system32_hooked(shims_dir, system32, imports_of, |_| Ok(()))
|
||||
}
|
||||
|
||||
/// Puts `bytes` at `dst` only if nothing is there, not even a dangling symbolic link.
|
||||
///
|
||||
/// `tmp` already holds the bytes. A hard link either creates `dst` whole or fails because the
|
||||
/// name is taken; where links are not supported the file is created exclusively instead.
|
||||
fn install_new(tmp: &Path, dst: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
match fs::hard_link(tmp, dst) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Err(e),
|
||||
Err(_) => {
|
||||
use std::io::Write as _;
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(dst)?;
|
||||
file.write_all(bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`stage_system32_with`] with a hook called for each file just before it is put in place, so
|
||||
/// tests can make something go wrong between the checks and the installation.
|
||||
fn stage_system32_hooked<I, H>(
|
||||
shims_dir: &Path,
|
||||
system32: &Path,
|
||||
mut imports_of: I,
|
||||
mut before_publish: H,
|
||||
) -> Result<Vec<Staged>, String>
|
||||
where
|
||||
I: FnMut(&Path) -> Result<Vec<String>, String>,
|
||||
H: FnMut(&str) -> Result<(), String>,
|
||||
{
|
||||
let (roots, absent): (Vec<&str>, Vec<&str>) = SYSTEM32_SHIMS
|
||||
.iter()
|
||||
@@ -147,29 +355,149 @@ where
|
||||
)),
|
||||
},
|
||||
)?;
|
||||
let mut owned = read_manifest(system32)?;
|
||||
let foreign = |dst: &Path, name: &str, what: &str| {
|
||||
format!(
|
||||
"{} {what}; it is left untouched. Use a bottle or prefix without its own {name}, \
|
||||
or move that entry aside yourself, then run again",
|
||||
dst.display()
|
||||
)
|
||||
};
|
||||
// 1. Decide everything before writing anything, so a foreign entry stops the run with
|
||||
// `system32` exactly as it was.
|
||||
let mut plan = Vec::new();
|
||||
for name in &names {
|
||||
let src = find_shim(shims_dir, name).unwrap_or_else(|| shims_dir.join(name));
|
||||
let bytes =
|
||||
fs::read(&src).map_err(|e| format!("cannot read shim {}: {e}", src.display()))?;
|
||||
let dst = system32.join(name);
|
||||
let result = match fs::read(&dst) {
|
||||
Ok(existing) if existing == bytes => Staged::Unchanged(dst.clone()),
|
||||
Ok(_) => Staged::Replaced(dst.clone()),
|
||||
// The directory entry itself is inspected, without following links: a dangling
|
||||
// symbolic link has no contents to read but is still the bottle's entry.
|
||||
let result = match fs::symlink_metadata(&dst) {
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => Staged::Copied(dst.clone()),
|
||||
Err(e) => return Err(format!("cannot read {}: {e}", dst.display())),
|
||||
Err(e) => return Err(format!("cannot inspect {}: {e}", dst.display())),
|
||||
Ok(meta) => {
|
||||
let existing = match fs::read(&dst) {
|
||||
Ok(existing) => Some(existing),
|
||||
Err(_) if !meta.is_file() => None,
|
||||
Err(e) => return Err(format!("cannot read {}: {e}", dst.display())),
|
||||
};
|
||||
if existing.as_deref() == Some(bytes.as_slice()) {
|
||||
Staged::Unchanged(dst.clone())
|
||||
} else if !meta.is_file() {
|
||||
// bx-cli only ever writes regular files, so a link or anything else here
|
||||
// was not staged by it.
|
||||
return Err(foreign(
|
||||
&dst,
|
||||
name,
|
||||
"already exists and is not a regular file (for example a symbolic link)",
|
||||
));
|
||||
} else if existing.as_deref().map(sha256_hex).as_ref() == owned.get(name) {
|
||||
Staged::Replaced(dst.clone())
|
||||
} else if existing.as_deref().is_some_and(is_wine_builtin_dll) {
|
||||
Staged::ReplacedWineStub(dst.clone())
|
||||
} else {
|
||||
return Err(foreign(
|
||||
&dst,
|
||||
name,
|
||||
"already exists and was not staged by bx-cli (or was changed since)",
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
plan.push((name, bytes, dst, result));
|
||||
}
|
||||
// 2. Write every new file beside its target first. A failure here publishes nothing.
|
||||
let tmp_of = |name: &str| system32.join(format!(".{name}.{}.bx-staging", std::process::id()));
|
||||
let pending: Vec<PathBuf> = plan
|
||||
.iter()
|
||||
.filter(|(_, _, _, result)| !matches!(result, Staged::Unchanged(_)))
|
||||
.map(|(name, _, _, _)| tmp_of(name))
|
||||
.collect();
|
||||
let discard = |tmps: &[PathBuf]| {
|
||||
for tmp in tmps {
|
||||
let _ = fs::remove_file(tmp);
|
||||
}
|
||||
};
|
||||
for (name, bytes, _, result) in &plan {
|
||||
if !matches!(result, Staged::Unchanged(_)) {
|
||||
// Write beside the target, then rename, so a guest never sees a half-written DLL.
|
||||
// The name is per process, so a concurrent run cannot rename a partial write.
|
||||
let tmp = system32.join(format!(".{name}.{}.bx-staging", std::process::id()));
|
||||
fs::write(&tmp, &bytes).map_err(|e| {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
format!("cannot write {}: {e}", tmp.display())
|
||||
})?;
|
||||
fs::rename(&tmp, &dst).map_err(|e| {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
format!("cannot replace {}: {e}", dst.display())
|
||||
})?;
|
||||
let tmp = tmp_of(name);
|
||||
if let Err(e) = fs::write(&tmp, bytes) {
|
||||
discard(&pending);
|
||||
return Err(format!("cannot write {}: {e}", tmp.display()));
|
||||
}
|
||||
}
|
||||
}
|
||||
// 3. Put the files in place one at a time, recording each in the manifest as soon as it is
|
||||
// there. If a later file fails, the earlier ones are installed and owned, not orphaned.
|
||||
for (name, bytes, dst, result) in plan {
|
||||
if !matches!(result, Staged::Unchanged(_)) {
|
||||
let tmp = tmp_of(name);
|
||||
let published = before_publish(name).and_then(|()| match result {
|
||||
// Nothing was there at step 1; refuse to replace whatever appeared since.
|
||||
Staged::Copied(_) => install_new(&tmp, &dst, &bytes).map_err(|e| {
|
||||
if e.kind() == io::ErrorKind::AlreadyExists {
|
||||
foreign(
|
||||
&dst,
|
||||
name,
|
||||
"appeared while staging and was not staged by bx-cli",
|
||||
)
|
||||
} else {
|
||||
format!("cannot install {}: {e}", dst.display())
|
||||
}
|
||||
}),
|
||||
// Wine fake-DLL placeholder stub: verify it is still a regular Wine builtin stub,
|
||||
// preserve a one-time backup `.<name>.wine-builtin.bak`, then atomically replace.
|
||||
Staged::ReplacedWineStub(_) => match fs::symlink_metadata(&dst) {
|
||||
Ok(meta) if meta.is_file() => match fs::read(&dst) {
|
||||
Ok(now) if is_wine_builtin_dll(&now) => {
|
||||
let bak = system32.join(format!(".{name}.wine-builtin.bak"));
|
||||
if fs::symlink_metadata(&bak).is_err() {
|
||||
let bak_tmp = system32.join(format!(
|
||||
".{name}.wine-builtin.bak.{}.bx-staging",
|
||||
std::process::id()
|
||||
));
|
||||
fs::write(&bak_tmp, &now).map_err(|e| {
|
||||
let _ = fs::remove_file(&bak_tmp);
|
||||
format!("cannot write backup {}: {e}", bak_tmp.display())
|
||||
})?;
|
||||
let bak_res = install_new(&bak_tmp, &bak, &now);
|
||||
let _ = fs::remove_file(&bak_tmp);
|
||||
match bak_res {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => {
|
||||
return Err(format!(
|
||||
"cannot save Wine stub backup {}: {e}",
|
||||
bak.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
fs::rename(&tmp, &dst)
|
||||
.map_err(|e| format!("cannot replace {}: {e}", dst.display()))
|
||||
}
|
||||
_ => Err(foreign(&dst, name, "changed while staging")),
|
||||
},
|
||||
_ => Err(foreign(&dst, name, "changed while staging")),
|
||||
},
|
||||
// Still our own earlier copy? Then the rename replaces it in one step.
|
||||
_ => match fs::read(&dst) {
|
||||
Ok(now) if owned.get(name) == Some(&sha256_hex(&now)) => fs::rename(&tmp, &dst)
|
||||
.map_err(|e| format!("cannot replace {}: {e}", dst.display())),
|
||||
_ => Err(foreign(&dst, name, "changed while staging")),
|
||||
},
|
||||
});
|
||||
if let Err(e) = published {
|
||||
discard(&pending);
|
||||
return Err(e);
|
||||
}
|
||||
let _ = fs::remove_file(&tmp);
|
||||
owned.insert(name.clone(), sha256_hex(&bytes));
|
||||
if let Err(e) = write_manifest(system32, &owned) {
|
||||
discard(&pending);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
staged.push(result);
|
||||
}
|
||||
@@ -249,11 +577,12 @@ mod tests {
|
||||
let (_t, shims, prefix) = setup("deps");
|
||||
let sys = system32_dir(&prefix);
|
||||
let staged = stage(&shims, &sys).unwrap();
|
||||
assert_eq!(staged.len(), 2, "{staged:?}");
|
||||
assert_eq!(staged.len(), 3, "{staged:?}");
|
||||
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v1");
|
||||
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), b"shim v1");
|
||||
assert!(
|
||||
!sys.join("unrelated.dll").exists(),
|
||||
"only imported shims are staged"
|
||||
"only SYSTEM32_SHIMS and imported shims are staged"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -277,13 +606,144 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaces_an_older_copy() {
|
||||
fn sha256_matches_the_published_test_vectors() {
|
||||
// FIPS 180-4 / NIST example values.
|
||||
assert_eq!(
|
||||
sha256_hex(b""),
|
||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
);
|
||||
assert_eq!(
|
||||
sha256_hex(b"abc"),
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
||||
);
|
||||
assert_eq!(
|
||||
sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
|
||||
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
|
||||
);
|
||||
// Padding boundaries (one block, two blocks, exactly one block of data); expected
|
||||
// values computed independently with Python's hashlib.
|
||||
for (len, expected) in [
|
||||
(
|
||||
55usize,
|
||||
"9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318",
|
||||
),
|
||||
(
|
||||
56usize,
|
||||
"b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a",
|
||||
),
|
||||
(
|
||||
64usize,
|
||||
"ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb",
|
||||
),
|
||||
(
|
||||
1000usize,
|
||||
"41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3",
|
||||
),
|
||||
] {
|
||||
assert_eq!(sha256_hex(&vec![b'a'; len]), expected, "{len} bytes");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every regular file in `dir` with its bytes, for before/after comparison.
|
||||
fn snapshot(dir: &Path) -> BTreeMap<String, Vec<u8>> {
|
||||
fs::read_dir(dir)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap())
|
||||
.map(|e| {
|
||||
(
|
||||
e.file_name().to_string_lossy().into_owned(),
|
||||
fs::read(e.path()).unwrap(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_foreign_file_with_different_bytes_is_never_modified() {
|
||||
let (_t, shims, prefix) = setup("foreign");
|
||||
let sys = system32_dir(&prefix);
|
||||
// The bottle's own runtime, put there by something other than bx-cli.
|
||||
fs::write(sys.join("xgameruntime.dll"), b"the bottle's own runtime").unwrap();
|
||||
let before = snapshot(&sys);
|
||||
let err = stage(&shims, &sys).unwrap_err();
|
||||
assert!(err.contains("xgameruntime.dll"), "{err}");
|
||||
assert!(err.contains("not staged by bx-cli"), "{err}");
|
||||
// Nothing changed: not the foreign file, no dependency copied beside it, no manifest.
|
||||
assert_eq!(snapshot(&sys), before);
|
||||
// Still refused on the next run.
|
||||
assert!(stage(&shims, &sys).is_err());
|
||||
assert_eq!(snapshot(&sys), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_foreign_dependency_blocks_staging_before_anything_is_written() {
|
||||
let (_t, shims, prefix) = setup("foreign-dep");
|
||||
let sys = system32_dir(&prefix);
|
||||
fs::write(sys.join("bx_runtime_veh.dll"), b"someone else's file").unwrap();
|
||||
let before = snapshot(&sys);
|
||||
let err = stage(&shims, &sys).unwrap_err();
|
||||
assert!(err.contains("bx_runtime_veh.dll"), "{err}");
|
||||
assert_eq!(
|
||||
snapshot(&sys),
|
||||
before,
|
||||
"xgameruntime.dll must not be staged either"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owned_copy_changed_by_someone_else_is_not_replaced() {
|
||||
let (_t, shims, prefix) = setup("tampered");
|
||||
let sys = system32_dir(&prefix);
|
||||
stage(&shims, &sys).unwrap();
|
||||
// Something else (an installer) replaced our copy after we staged it.
|
||||
fs::write(sys.join("xgameruntime.dll"), b"installed over ours").unwrap();
|
||||
fs::write(shims.join("xgameruntime.dll"), b"shim v2").unwrap();
|
||||
let before = snapshot(&sys);
|
||||
assert!(stage(&shims, &sys).is_err());
|
||||
assert_eq!(snapshot(&sys), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_identical_foreign_file_is_left_alone_and_not_claimed() {
|
||||
let (_t, shims, prefix) = setup("identical");
|
||||
let sys = system32_dir(&prefix);
|
||||
fs::write(sys.join("xgameruntime.dll"), b"shim v1").unwrap();
|
||||
let staged = stage(&shims, &sys).unwrap();
|
||||
assert!(staged.contains(&Staged::Unchanged(sys.join("xgameruntime.dll"))));
|
||||
assert!(
|
||||
!read_manifest(&sys)
|
||||
.unwrap()
|
||||
.contains_key("xgameruntime.dll")
|
||||
);
|
||||
// Not ours, so a later shim change must not replace it.
|
||||
fs::write(shims.join("xgameruntime.dll"), b"shim v2").unwrap();
|
||||
assert!(stage(&shims, &sys).is_err());
|
||||
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refreshes_a_stale_copy_it_staged_itself() {
|
||||
let (_t, shims, prefix) = setup("replace");
|
||||
let sys = system32_dir(&prefix);
|
||||
fs::write(sys.join("xgameruntime.dll"), b"old").unwrap();
|
||||
let first = stage(&shims, &sys).unwrap();
|
||||
assert!(first.iter().all(|s| matches!(s, Staged::Copied(_))));
|
||||
let manifest = fs::read_to_string(sys.join(MANIFEST_NAME)).unwrap();
|
||||
assert!(
|
||||
manifest.contains(&format!("{} xgameruntime.dll\n", sha256_hex(b"shim v1"))),
|
||||
"{manifest}"
|
||||
);
|
||||
// The shim is rebuilt; the copy in system32 is now stale but still ours.
|
||||
fs::write(shims.join("xgameruntime.dll"), b"shim v2").unwrap();
|
||||
let staged = stage(&shims, &sys).unwrap();
|
||||
assert!(staged.contains(&Staged::Replaced(sys.join("xgameruntime.dll"))));
|
||||
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v1");
|
||||
assert!(staged.contains(&Staged::Unchanged(sys.join("bx_runtime_veh.dll"))));
|
||||
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v2");
|
||||
let owned = read_manifest(&sys).unwrap();
|
||||
assert_eq!(owned.get("xgameruntime.dll"), Some(&sha256_hex(b"shim v2")));
|
||||
assert_eq!(
|
||||
owned.get("bx_runtime_veh.dll"),
|
||||
Some(&sha256_hex(b"veh v1"))
|
||||
);
|
||||
let leftovers: Vec<_> = fs::read_dir(&sys)
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
@@ -292,13 +752,197 @@ mod tests {
|
||||
assert!(leftovers.is_empty(), "temporary file left behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dangling_symlink_is_a_foreign_entry_and_stays() {
|
||||
let (_t, shims, prefix) = setup("dangling");
|
||||
let sys = system32_dir(&prefix);
|
||||
let link = sys.join("xgameruntime.dll");
|
||||
std::os::unix::fs::symlink(sys.join("no-such-target.dll"), &link).unwrap();
|
||||
let err = stage(&shims, &sys).unwrap_err();
|
||||
assert!(err.contains("xgameruntime.dll"), "{err}");
|
||||
assert!(err.contains("symbolic link"), "{err}");
|
||||
// Still the same dangling link, and nothing else was staged beside it.
|
||||
assert_eq!(
|
||||
fs::read_link(&link).unwrap(),
|
||||
sys.join("no-such-target.dll")
|
||||
);
|
||||
assert!(!sys.join("bx_runtime_veh.dll").exists());
|
||||
assert!(!sys.join(MANIFEST_NAME).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_symlink_is_never_replaced_whatever_it_points_to() {
|
||||
let (t, shims, prefix) = setup("symlink");
|
||||
let sys = system32_dir(&prefix);
|
||||
let link = sys.join("xgameruntime.dll");
|
||||
// Pointing at a file with other contents: foreign, and the target is not written to.
|
||||
let target = t.0.join("elsewhere.dll");
|
||||
fs::write(&target, b"the bottle's own runtime").unwrap();
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
assert!(stage(&shims, &sys).is_err());
|
||||
assert_eq!(fs::read(&target).unwrap(), b"the bottle's own runtime");
|
||||
assert_eq!(fs::read_link(&link).unwrap(), target);
|
||||
// Pointing at identical contents: already current, left as a link and not claimed.
|
||||
fs::write(&target, b"shim v1").unwrap();
|
||||
let staged = stage(&shims, &sys).unwrap();
|
||||
assert!(staged.contains(&Staged::Unchanged(link.clone())));
|
||||
assert_eq!(fs::read_link(&link).unwrap(), target);
|
||||
assert!(
|
||||
!read_manifest(&sys)
|
||||
.unwrap()
|
||||
.contains_key("xgameruntime.dll")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_that_appears_after_the_checks_is_not_replaced() {
|
||||
let (_t, shims, prefix) = setup("late");
|
||||
let sys = system32_dir(&prefix);
|
||||
let dst = sys.join("xgameruntime.dll");
|
||||
let late = dst.clone();
|
||||
let err = stage_system32_hooked(&shims, &sys, fake_imports, |name| {
|
||||
if name == "xgameruntime.dll" {
|
||||
fs::write(&late, b"installed meanwhile").unwrap();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(err.contains("appeared while staging"), "{err}");
|
||||
assert_eq!(fs::read(&dst).unwrap(), b"installed meanwhile");
|
||||
assert!(
|
||||
!read_manifest(&sys)
|
||||
.unwrap()
|
||||
.contains_key("xgameruntime.dll")
|
||||
);
|
||||
assert!(no_temporary_files(&sys));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_failure_leaves_earlier_copies_installed_and_owned() {
|
||||
let (_t, shims, prefix) = setup("partial");
|
||||
let sys = system32_dir(&prefix);
|
||||
// Files are installed in name order: the VEH logger first, then the runtime.
|
||||
let err = stage_system32_hooked(&shims, &sys, fake_imports, |name| {
|
||||
if name == "xgameruntime.dll" {
|
||||
return Err("disk full".to_string());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err, "disk full");
|
||||
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v1");
|
||||
assert!(!sys.join("xgameruntime.dll").exists());
|
||||
let owned = read_manifest(&sys).unwrap();
|
||||
assert_eq!(
|
||||
owned.get("bx_runtime_veh.dll"),
|
||||
Some(&sha256_hex(b"veh v1"))
|
||||
);
|
||||
assert!(no_temporary_files(&sys));
|
||||
// The retry completes, and the first file is still ours: a later update refreshes it.
|
||||
let retry = stage(&shims, &sys).unwrap();
|
||||
assert!(retry.contains(&Staged::Unchanged(sys.join("bx_runtime_veh.dll"))));
|
||||
assert!(retry.contains(&Staged::Copied(sys.join("xgameruntime.dll"))));
|
||||
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
|
||||
let update = stage(&shims, &sys).unwrap();
|
||||
assert!(update.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
|
||||
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_temporary_write_publishes_nothing() {
|
||||
let (_t, shims, prefix) = setup("prepare");
|
||||
let sys = system32_dir(&prefix);
|
||||
// A directory where the second file's temporary copy has to go makes that write fail.
|
||||
let obstacle = sys.join(format!(
|
||||
".xgameruntime.dll.{}.bx-staging",
|
||||
std::process::id()
|
||||
));
|
||||
fs::create_dir(&obstacle).unwrap();
|
||||
let err = stage(&shims, &sys).unwrap_err();
|
||||
assert!(err.contains("cannot write"), "{err}");
|
||||
assert!(
|
||||
!sys.join("bx_runtime_veh.dll").exists(),
|
||||
"first file was published"
|
||||
);
|
||||
assert!(!sys.join("xgameruntime.dll").exists());
|
||||
assert!(!sys.join(MANIFEST_NAME).exists());
|
||||
fs::remove_dir(&obstacle).unwrap();
|
||||
assert!(
|
||||
stage(&shims, &sys)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|s| matches!(s, Staged::Copied(_)))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_shims_reached_through_a_stub_prefix_count_as_visible() {
|
||||
let (t, shims, prefix) = setup("visible");
|
||||
let sys = system32_dir(&prefix);
|
||||
stage(&shims, &sys).unwrap();
|
||||
let names = vec![
|
||||
"bx_runtime_veh.dll".to_string(),
|
||||
"xgameruntime.dll".to_string(),
|
||||
];
|
||||
// A private stub whose system32 links back to the managed prefix, as CrossOver creates.
|
||||
let stub = system32_dir(&t.0.join("stub"));
|
||||
fs::create_dir_all(&stub).unwrap();
|
||||
for name in &names {
|
||||
std::os::unix::fs::symlink(sys.join(name), stub.join(name)).unwrap();
|
||||
}
|
||||
assert!(shims_not_visible_in(&sys, &stub, &names).is_empty());
|
||||
// A stub that really lacks one shim, or has other bytes under that name.
|
||||
fs::remove_file(stub.join("xgameruntime.dll")).unwrap();
|
||||
assert_eq!(
|
||||
shims_not_visible_in(&sys, &stub, &names),
|
||||
vec!["xgameruntime.dll"]
|
||||
);
|
||||
fs::write(stub.join("xgameruntime.dll"), b"something else").unwrap();
|
||||
assert_eq!(
|
||||
shims_not_visible_in(&sys, &stub, &names),
|
||||
vec!["xgameruntime.dll"]
|
||||
);
|
||||
// An empty stub sees none of them.
|
||||
let empty = system32_dir(&t.0.join("empty"));
|
||||
fs::create_dir_all(&empty).unwrap();
|
||||
assert_eq!(shims_not_visible_in(&sys, &empty, &names), names);
|
||||
}
|
||||
|
||||
fn no_temporary_files(sys: &Path) -> bool {
|
||||
fs::read_dir(sys)
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.all(|e| !e.file_name().to_string_lossy().contains("bx-staging"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_manifest_only_makes_files_look_foreign() {
|
||||
let (_t, shims, prefix) = setup("manifest");
|
||||
let sys = system32_dir(&prefix);
|
||||
stage(&shims, &sys).unwrap();
|
||||
fs::write(
|
||||
sys.join(MANIFEST_NAME),
|
||||
"not a manifest\nabc xgameruntime.dll\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(read_manifest(&sys).unwrap().is_empty());
|
||||
fs::write(shims.join("xgameruntime.dll"), b"shim v2").unwrap();
|
||||
assert!(stage(&shims, &sys).is_err());
|
||||
assert_eq!(fs::read(sys.join("xgameruntime.dll")).unwrap(), b"shim v1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_shim_is_reported_and_nothing_is_staged() {
|
||||
let (t, shims, prefix) = setup("missing");
|
||||
fs::remove_file(shims.join("xgameruntime.dll")).unwrap();
|
||||
for name in SYSTEM32_SHIMS {
|
||||
fs::remove_file(shims.join(name)).unwrap();
|
||||
}
|
||||
assert!(!has_system32_shims(&shims));
|
||||
let sys = system32_dir(&prefix);
|
||||
let expected = vec![Staged::Absent(shims.join("xgameruntime.dll"))];
|
||||
let expected: Vec<Staged> = SYSTEM32_SHIMS
|
||||
.iter()
|
||||
.map(|name| Staged::Absent(shims.join(name)))
|
||||
.collect();
|
||||
assert_eq!(stage(&shims, &sys).unwrap(), expected);
|
||||
assert_eq!(fs::read_dir(&sys).unwrap().count(), 0);
|
||||
// With nothing to stage, a prefix without system32 is not an error either.
|
||||
@@ -307,6 +951,71 @@ mod tests {
|
||||
assert!(!fresh.exists());
|
||||
}
|
||||
|
||||
fn make_fake_wine_builtin_pe() -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x100];
|
||||
pe[0..2].copy_from_slice(b"MZ");
|
||||
pe[0x3c..0x40].copy_from_slice(&(0x80u32).to_le_bytes());
|
||||
pe[0x40..0x51].copy_from_slice(b"Wine builtin DLL\0");
|
||||
pe[0x80..0x84].copy_from_slice(b"PE\0\0");
|
||||
pe
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaces_a_wine_builtin_stub_after_saving_a_backup() {
|
||||
let (_t, shims, prefix) = setup("wine-stub");
|
||||
let sys = system32_dir(&prefix);
|
||||
let wine_stub = make_fake_wine_builtin_pe();
|
||||
assert!(is_wine_builtin_dll(&wine_stub));
|
||||
fs::write(sys.join("gameinput.dll"), &wine_stub).unwrap();
|
||||
|
||||
let first = stage(&shims, &sys).unwrap();
|
||||
assert!(first.contains(&Staged::ReplacedWineStub(sys.join("gameinput.dll"))));
|
||||
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), b"shim v1");
|
||||
assert_eq!(
|
||||
fs::read(sys.join(".gameinput.dll.wine-builtin.bak")).unwrap(),
|
||||
wine_stub
|
||||
);
|
||||
let owned = read_manifest(&sys).unwrap();
|
||||
assert_eq!(owned.get("gameinput.dll"), Some(&sha256_hex(b"shim v1")));
|
||||
|
||||
// Subsequent rebuilds refresh our owned copy while keeping the original Wine backup intact.
|
||||
fs::write(shims.join("GameInput.dll"), b"shim v2").unwrap();
|
||||
let second = stage(&shims, &sys).unwrap();
|
||||
assert!(second.contains(&Staged::Replaced(sys.join("gameinput.dll"))));
|
||||
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), b"shim v2");
|
||||
assert_eq!(
|
||||
fs::read(sys.join(".gameinput.dll.wine-builtin.bak")).unwrap(),
|
||||
wine_stub
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_wine_pe_and_symlinks_to_wine_stubs_are_still_refused() {
|
||||
let (t, shims, prefix) = setup("non-wine-pe");
|
||||
let sys = system32_dir(&prefix);
|
||||
// A regular native PE (standard DOS stub, no "Wine builtin DLL" marker) is foreign.
|
||||
let mut native_pe = make_fake_wine_builtin_pe();
|
||||
native_pe[0x40..0x51].copy_from_slice(b"This program can!");
|
||||
assert!(!is_wine_builtin_dll(&native_pe));
|
||||
fs::write(sys.join("gameinput.dll"), &native_pe).unwrap();
|
||||
assert!(stage(&shims, &sys).is_err());
|
||||
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), native_pe);
|
||||
|
||||
// A symlink pointing to a real Wine builtin stub is ALSO refused (never follow links).
|
||||
fs::remove_file(sys.join("gameinput.dll")).unwrap();
|
||||
let wine_target = t.0.join("wine_gameinput.dll");
|
||||
fs::write(&wine_target, make_fake_wine_builtin_pe()).unwrap();
|
||||
std::os::unix::fs::symlink(&wine_target, sys.join("gameinput.dll")).unwrap();
|
||||
let err = stage(&shims, &sys).unwrap_err();
|
||||
assert!(err.contains("symbolic link"), "{err}");
|
||||
assert!(
|
||||
fs::symlink_metadata(sys.join("gameinput.dll"))
|
||||
.unwrap()
|
||||
.file_type()
|
||||
.is_symlink()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uninitialized_prefix_is_an_error_not_a_skip() {
|
||||
let (t, shims, _prefix) = setup("uninit");
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::io::IsTerminal;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::path::Path;
|
||||
use std::process::{Child, Command, ExitStatus, Stdio};
|
||||
use std::sync::atomic::{AtomicI32, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const POLL: Duration = Duration::from_millis(50);
|
||||
@@ -16,29 +16,81 @@ const POLL: Duration = Duration::from_millis(50);
|
||||
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);
|
||||
}
|
||||
|
||||
/// Records SIGINT, SIGTERM and SIGHUP instead of dying, so the run can be cleaned up.
|
||||
pub fn install_signal_handlers() {
|
||||
for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
|
||||
// SAFETY: the handler only stores to an atomic, which is async-signal-safe.
|
||||
unsafe {
|
||||
libc::signal(
|
||||
signal,
|
||||
note_signal as extern "C" fn(libc::c_int) as libc::sighandler_t,
|
||||
);
|
||||
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,
|
||||
@@ -52,11 +104,14 @@ pub enum Outcome {
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
/// 0 or 1 for the guest's own result, 124 for a timeout (as `timeout(1)`), 128 + N for a
|
||||
/// signal.
|
||||
/// 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 {
|
||||
Outcome::Exited(status) => u8::from(!status.success()),
|
||||
// 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),
|
||||
}
|
||||
@@ -85,10 +140,27 @@ fn wait_until(child: &mut Child, deadline: Instant) -> std::io::Result<Option<Ex
|
||||
|
||||
/// 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.
|
||||
@@ -97,6 +169,7 @@ pub fn supervise(
|
||||
}
|
||||
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));
|
||||
@@ -105,7 +178,20 @@ pub fn supervise(
|
||||
if received != 0 {
|
||||
break Stop::Signalled(received);
|
||||
}
|
||||
if timeout.is_some_and(|limit| started.elapsed() >= limit) {
|
||||
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);
|
||||
@@ -141,6 +227,10 @@ fn group_leader_running(child: &Child) -> bool {
|
||||
///
|
||||
/// `-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,
|
||||
@@ -152,8 +242,10 @@ pub fn stop_server(
|
||||
.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) {
|
||||
@@ -191,7 +283,11 @@ mod tests {
|
||||
let ok = supervise(shell("exit 0"), None, || 0).unwrap();
|
||||
assert_eq!(ok.exit_code(), 0);
|
||||
let failed = supervise(shell("exit 7"), Some(Duration::from_secs(10)), || 0).unwrap();
|
||||
assert_eq!(failed.exit_code(), 1);
|
||||
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);
|
||||
@@ -222,6 +318,157 @@ mod tests {
|
||||
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");
|
||||
|
||||
@@ -13,10 +13,130 @@ 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)]
|
||||
@@ -35,6 +155,65 @@ 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() {
|
||||
@@ -48,11 +227,19 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
match event {
|
||||
"clwb_trapped" => {
|
||||
summary.clwb_events += 1;
|
||||
let sample = detail
|
||||
.split_ascii_whitespace()
|
||||
.find_map(|field| field.strip_prefix("total_traps="))
|
||||
.and_then(|count| count.parse::<u64>().ok());
|
||||
summary.clwb_trap_lower_bound = summary.clwb_trap_lower_bound.max(sample);
|
||||
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());
|
||||
}
|
||||
"adx_illegal_instruction" => summary.adx_errors += 1,
|
||||
"unhandled_exception" => {
|
||||
@@ -165,4 +352,221 @@ 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"));
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,37 @@ 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
|
||||
|
||||
@@ -185,6 +185,9 @@ 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.
|
||||
@@ -224,6 +227,12 @@ 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"
|
||||
@@ -272,6 +281,14 @@ 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 => {
|
||||
@@ -341,6 +358,29 @@ 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,22 +186,70 @@ 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 script = Script::new("hang", "echo started; exec sleep 30");
|
||||
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 started = Instant::now();
|
||||
let run = run_probe(&script.0, Path::new("/fw"), Duration::from_millis(300)).unwrap();
|
||||
let run = run_probe(&script.0, &pid_file.0, START_MARGIN).unwrap();
|
||||
let elapsed = started.elapsed();
|
||||
assert!(run.status.is_none());
|
||||
// Output written before the kill is kept.
|
||||
assert_eq!(run.stdout, "started\n");
|
||||
assert!(started.elapsed() < Duration::from_secs(10));
|
||||
// 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());
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
let script = Script::new("orphan", "sleep 5 & echo started");
|
||||
let timeout = Duration::from_millis(500);
|
||||
// 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 started = Instant::now();
|
||||
let run = run_probe(&script.0, Path::new("/fw"), timeout).unwrap();
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# 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.
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Builds bx_shader_bridge.dll (this crate for x86_64-pc-windows-gnu) and the guest check
|
||||
# check_bridge.exe into one directory (default: <repo>/target/bx-shader-bridge), then checks
|
||||
# the DLL: its Export Address Table holds exactly the three bx_shader_bridge.h entry points as
|
||||
# direct RVAs (no extra named or ordinal-only entries, no forwarders), and every imported DLL
|
||||
# is a system DLL Wine provides. Run the check under CrossOver afterwards, for example:
|
||||
# target/debug/bx-cli run --prefix /tmp/bx-shader --shims target/bx-shader-bridge \
|
||||
# --exe target/bx-shader-bridge/check_bridge.exe
|
||||
#
|
||||
# Needs: rustup with the x86_64-pc-windows-gnu target, x86_64-w64-mingw32-gcc / -objdump
|
||||
# (mingw-w64), and python3.
|
||||
set -eu
|
||||
|
||||
crate=$(cd "$(dirname "$0")/.." && pwd)
|
||||
root=$(cd "$crate/../../.." && pwd)
|
||||
out=${1:-$root/target/bx-shader-bridge}
|
||||
target=x86_64-pc-windows-gnu
|
||||
cc=${BX_MINGW_CC:-x86_64-w64-mingw32-gcc}
|
||||
objdump=${BX_MINGW_OBJDUMP:-x86_64-w64-mingw32-objdump}
|
||||
# Always build here and copy from here, whatever CARGO_TARGET_DIR or build.target-dir say,
|
||||
# so a stale DLL left elsewhere can never be packaged.
|
||||
target_dir=$root/target
|
||||
|
||||
for tool in "$cc" "$objdump" python3; do
|
||||
command -v "$tool" >/dev/null 2>&1 || { echo "build.sh: $tool not found" >&2; exit 1; }
|
||||
done
|
||||
|
||||
# Use one toolchain for both the target check and the build. With rustup, resolve cargo and
|
||||
# rustc through it (a cargo earlier on PATH, e.g. Homebrew's, has no Windows std).
|
||||
if command -v rustup >/dev/null 2>&1; then
|
||||
cargo=$(cd "$root" && rustup which cargo)
|
||||
rustc=$(cd "$root" && rustup which rustc)
|
||||
else
|
||||
cargo=$(command -v cargo) || { echo "build.sh: cargo not found" >&2; exit 1; }
|
||||
rustc=$(command -v rustc) || { echo "build.sh: rustc not found" >&2; exit 1; }
|
||||
fi
|
||||
libdir=$("$rustc" --print target-libdir --target "$target" 2>/dev/null || true)
|
||||
if [ -z "$libdir" ] || ! ls "$libdir"/libstd-*.rlib >/dev/null 2>&1; then
|
||||
echo "build.sh: $rustc ($("$rustc" --version)) has no std for $target" >&2
|
||||
echo "build.sh: install it with: rustup target add $target" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "build.sh: using $("$rustc" --version) at $rustc"
|
||||
|
||||
RUSTC=$rustc CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=$cc \
|
||||
"$cargo" build --locked --release -p dxbc-accc --target "$target" \
|
||||
--target-dir "$target_dir" --manifest-path "$root/Cargo.toml"
|
||||
mkdir -p "$out"
|
||||
cp "$target_dir/$target/release/dxbc_accc.dll" "$out/bx_shader_bridge.dll"
|
||||
dll=$out/bx_shader_bridge.dll
|
||||
|
||||
# Same reading of `objdump -p` as scripts/build-shims.sh: every populated Export Address Table
|
||||
# slot must be a direct RVA owned by one of the expected names.
|
||||
"$objdump" -p "$dll" | python3 -I -c '
|
||||
import re, sys
|
||||
expected = {"bx_shader_inspect", "bx_shader_prepare_for_d3dmetal", "bx_shader_free_buffer"}
|
||||
# The Windows-provided system DLLs a Rust std cdylib imports; anything else is an error.
|
||||
allowed = {"kernel32.dll", "ntdll.dll", "bcryptprimitives.dll", "userenv.dll", "ws2_32.dll"}
|
||||
allowed_prefixes = ("api-ms-win-crt-", "api-ms-win-core-")
|
||||
eat, names, imports, mode = {}, {}, [], None
|
||||
for line in sys.stdin:
|
||||
line = line.rstrip("\n")
|
||||
m = re.match(r"^\s*DLL Name:\s*(\S+)", line)
|
||||
if m:
|
||||
imports.append(m.group(1))
|
||||
if line.startswith("Export Address Table --"):
|
||||
mode = "eat"; continue
|
||||
if line.startswith("[Ordinal/Name Pointer] Table --"):
|
||||
mode = "names"; continue
|
||||
if not line.strip():
|
||||
mode = None; continue
|
||||
if mode == "eat":
|
||||
m = re.match(r"^\s*\[\s*\d+\]\s*\+base\[\s*(\d+)\]\s+[0-9a-fA-F]+\s+(Export|Forwarder) RVA", line)
|
||||
if m:
|
||||
eat[int(m.group(1))] = m.group(2)
|
||||
elif mode == "names":
|
||||
m = re.match(r"^\s*\[\s*\d+\]\s*\+base\[\s*(\d+)\]\s+[0-9a-fA-F]+\s+(\S+)", line)
|
||||
if m:
|
||||
names[m.group(2)] = int(m.group(1))
|
||||
errors = []
|
||||
if set(names) != expected:
|
||||
errors.append("named exports %s, want %s" % (sorted(names), sorted(expected)))
|
||||
owned = set(names.values())
|
||||
for ordinal, kind in sorted(eat.items()):
|
||||
if ordinal not in owned:
|
||||
errors.append("export @%d has no name (ordinal-only or stray entry)" % ordinal)
|
||||
if kind != "Export":
|
||||
errors.append("export @%d is a forwarder" % ordinal)
|
||||
for name, ordinal in names.items():
|
||||
if ordinal not in eat:
|
||||
errors.append("%s @%d missing from the Export Address Table" % (name, ordinal))
|
||||
for dll in imports:
|
||||
low = dll.lower()
|
||||
if low not in allowed and not low.startswith(allowed_prefixes):
|
||||
errors.append("unexpected import %s (only Wine-provided system DLLs are allowed)" % dll)
|
||||
if errors:
|
||||
sys.exit("build.sh: bx_shader_bridge.dll: " + "; ".join(errors))
|
||||
print("build.sh: exports %s; imports %s" % (" ".join(sorted(names)), " ".join(imports)))
|
||||
'
|
||||
|
||||
"$cc" -std=c11 -O2 -Wall -Wextra -Werror -static \
|
||||
-I"$root/abi/include" -I"$crate/../d3dmetal-harness/probe/shaders" \
|
||||
-o "$out/check_bridge.exe" "$crate/guest/check_bridge.c"
|
||||
|
||||
echo "built $dll"
|
||||
echo "built $out/check_bridge.exe"
|
||||
@@ -0,0 +1,296 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Guest-side check for bx_shader_bridge.dll, the x86-64 Windows build of this crate (#445).
|
||||
*
|
||||
* Runs as a PE32+ guest under CrossOver/Wine, loads the DLL by full path from its own directory,
|
||||
* and drives the three entry points from abi/include/bx_shader_bridge.h with synthetic
|
||||
* containers plus one real DXC SM 6.6 compute blob. It counts the classifications and checks
|
||||
* them, and the prepare/free behaviour, against expectations written here from the DXBC
|
||||
* layout and the frozen header, not from the Rust implementation.
|
||||
*
|
||||
* Output: "BXSHADER" lines with each blob's classification, one "BXSHADER counts" line, then
|
||||
* PASS or FAIL. Exit code 0 on success, 1 on a failed check, 2 if the DLL cannot be loaded.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <wchar.h>
|
||||
|
||||
#include "bx_shader_bridge.h"
|
||||
#include "fill_cs66.h" /* g_fill_cs66: DXC 1.9.2609 output, see d3dmetal-harness */
|
||||
|
||||
/* The Rust side asserts the same layout; agreeing here proves both sides read one struct. */
|
||||
_Static_assert(sizeof(bx_shader_kind_t) == 4, "C enum must be 4 bytes");
|
||||
_Static_assert(sizeof(bx_shader_inspection_t) == 48, "bx_shader_inspection_t size");
|
||||
_Static_assert(offsetof(bx_shader_inspection_t, container_size) == 16, "container_size offset");
|
||||
_Static_assert(offsetof(bx_shader_inspection_t, digest_hash) == 32, "digest_hash offset");
|
||||
|
||||
typedef bx_shader_status_t (*inspect_fn)(const uint8_t*, size_t, bx_shader_inspection_t*);
|
||||
typedef bx_shader_status_t (*prepare_fn)(const uint8_t*, size_t, uint8_t**, size_t*);
|
||||
typedef void (*free_fn)(uint8_t*, size_t);
|
||||
|
||||
static int failures;
|
||||
|
||||
#define CHECK(expr) \
|
||||
do { \
|
||||
if (!(expr)) { \
|
||||
fprintf(stderr, "FAIL: check_bridge line %d: %s\n", __LINE__, #expr); \
|
||||
++failures; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
/* --- Synthetic DXBC containers --- */
|
||||
|
||||
static void put32(uint8_t* at, uint32_t value) {
|
||||
at[0] = (uint8_t)value;
|
||||
at[1] = (uint8_t)(value >> 8);
|
||||
at[2] = (uint8_t)(value >> 16);
|
||||
at[3] = (uint8_t)(value >> 24);
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
const char* fourcc;
|
||||
const uint8_t* data;
|
||||
uint32_t size;
|
||||
} chunk_t;
|
||||
|
||||
/* DXBC layout: "DXBC", 16-byte digest, u32 version 1, u32 total size, u32 chunk count, then
|
||||
* one u32 offset per chunk; each chunk is fourcc, u32 size, payload. */
|
||||
static uint32_t build_dxbc(uint8_t* out, size_t cap, const chunk_t* chunks, uint32_t count) {
|
||||
uint32_t at = 32 + 4 * count;
|
||||
for (uint32_t i = 0; i < count; ++i) at += 8 + chunks[i].size;
|
||||
if (at > cap) abort();
|
||||
memcpy(out, "DXBC", 4);
|
||||
memset(out + 4, 0x5A, 16);
|
||||
put32(out + 20, 1);
|
||||
put32(out + 24, at);
|
||||
put32(out + 28, count);
|
||||
uint32_t offset = 32 + 4 * count;
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
put32(out + 32 + 4 * i, offset);
|
||||
memcpy(out + offset, chunks[i].fourcc, 4);
|
||||
put32(out + offset + 4, chunks[i].size);
|
||||
memcpy(out + offset + 8, chunks[i].data, chunks[i].size);
|
||||
offset += 8 + chunks[i].size;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
/* A 28-byte DxilProgramHeader: program version word (kind << 16 | major << 4 | minor), size
|
||||
* in dwords (7), "DXIL", DXIL version 1.0, bitcode offset 16, bitcode size 4, 4 bitcode bytes. */
|
||||
static void dxil_program(uint8_t out[28], uint32_t kind, uint32_t major, uint32_t minor) {
|
||||
memset(out, 0, 28);
|
||||
put32(out, kind << 16 | major << 4 | minor);
|
||||
put32(out + 4, 7);
|
||||
memcpy(out + 8, "DXIL", 4);
|
||||
put32(out + 12, 0x0100);
|
||||
put32(out + 16, 16);
|
||||
put32(out + 20, 4);
|
||||
put32(out + 24, 0xDEC011D1u);
|
||||
}
|
||||
|
||||
/* Size of the first chunk named fourcc in a well-formed container, 0 if absent. Written from
|
||||
* the DXBC layout, independently of the Rust parser. */
|
||||
static uint32_t get32(const uint8_t* at) {
|
||||
return (uint32_t)at[0] | (uint32_t)at[1] << 8 | (uint32_t)at[2] << 16 | (uint32_t)at[3] << 24;
|
||||
}
|
||||
|
||||
static int chunk(const uint8_t* bytes, size_t len, const char* fourcc, uint32_t* size) {
|
||||
if (len < 32 || memcmp(bytes, "DXBC", 4) != 0) return 0;
|
||||
const uint32_t count = get32(bytes + 28);
|
||||
for (uint32_t i = 0; i < count && 36 + 4 * (size_t)i <= len; ++i) {
|
||||
const uint32_t offset = get32(bytes + 32 + 4 * i);
|
||||
if (offset + 8 <= len && memcmp(bytes + offset, fourcc, 4) == 0) {
|
||||
*size = get32(bytes + offset + 4);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* --- Cases --- */
|
||||
|
||||
typedef struct {
|
||||
const char* name;
|
||||
const uint8_t* bytes;
|
||||
size_t len;
|
||||
bx_shader_status_t inspect_status;
|
||||
bx_shader_kind_t kind;
|
||||
bx_shader_stage_t stage;
|
||||
uint32_t sm_major, sm_minor;
|
||||
uint32_t container_size; /* the container's declared size, which may be less than len */
|
||||
bx_shader_status_t prepare_status;
|
||||
} case_t;
|
||||
|
||||
static const char* kind_name(bx_shader_kind_t kind) {
|
||||
switch (kind) {
|
||||
case BX_SHADER_DXBC_DXIL: return "dxil";
|
||||
case BX_SHADER_DXBC_LEGACY: return "legacy";
|
||||
case BX_SHADER_DXBC_ACCC: return "accc_only";
|
||||
case BX_SHADER_DXBC_DUAL: return "dual";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
/* By full path beside this EXE, as a caller should (see the crate README). */
|
||||
wchar_t path[MAX_PATH];
|
||||
const DWORD path_len = GetModuleFileNameW(NULL, path, MAX_PATH);
|
||||
wchar_t* slash = path_len && path_len < MAX_PATH ? wcsrchr(path, L'\\') : NULL;
|
||||
if (!slash || (size_t)(slash + 1 - path) + 21 > MAX_PATH) {
|
||||
fprintf(stderr, "FAIL: check_bridge: executable path too long\n");
|
||||
return 2;
|
||||
}
|
||||
wcscpy(slash + 1, L"bx_shader_bridge.dll");
|
||||
HMODULE dll = LoadLibraryExW(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
|
||||
if (!dll) {
|
||||
fprintf(stderr, "FAIL: check_bridge: bx_shader_bridge.dll not loaded (error %lu)\n", GetLastError());
|
||||
return 2;
|
||||
}
|
||||
inspect_fn inspect = (inspect_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_inspect");
|
||||
prepare_fn prepare = (prepare_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_prepare_for_d3dmetal");
|
||||
free_fn release = (free_fn)(void (*)(void))GetProcAddress(dll, "bx_shader_free_buffer");
|
||||
if (!inspect || !prepare || !release) {
|
||||
fprintf(stderr, "FAIL: check_bridge: missing export\n");
|
||||
return 2;
|
||||
}
|
||||
|
||||
uint8_t dxil_cs66[28], dxil_ps60[28];
|
||||
dxil_program(dxil_cs66, 5, 6, 6); /* DXIL program kind 5 = compute */
|
||||
dxil_program(dxil_ps60, 0, 6, 0); /* kind 0 = pixel */
|
||||
const uint8_t rts0[4] = {1, 2, 3, 4};
|
||||
|
||||
/* FSPX v1 (BetterXen's synthetic layout): header "FSPX", version 1, 1 section, flags 0;
|
||||
* descriptor {id 1 (stage config), offset 28, size 12}; body {stage 6 compute, SM 6.0}. */
|
||||
uint8_t fspx_v1[40] = {0};
|
||||
memcpy(fspx_v1, "FSPX", 4);
|
||||
put32(fspx_v1 + 4, 1);
|
||||
put32(fspx_v1 + 8, 1);
|
||||
put32(fspx_v1 + 16, 1);
|
||||
put32(fspx_v1 + 20, 28);
|
||||
put32(fspx_v1 + 24, 12);
|
||||
put32(fspx_v1 + 28, BX_STAGE_COMPUTE);
|
||||
put32(fspx_v1 + 32, 6);
|
||||
put32(fspx_v1 + 36, 0);
|
||||
/* FSPX version 0: magic-only stub, no sections. */
|
||||
uint8_t fspx_v0[16] = {'F', 'S', 'P', 'X'};
|
||||
/* SM 5.0 compute SHEX token (program type 5 << 16 | 5 << 4 | 0) and a length dword. */
|
||||
uint8_t shex[8];
|
||||
put32(shex, 5u << 16 | 5u << 4);
|
||||
put32(shex + 4, 2);
|
||||
|
||||
static uint8_t ps60[256], accc_v1[256], accc_v0[256], dual[256], legacy[256];
|
||||
const chunk_t ps60_chunks[] = {{"RTS0", rts0, 4}, {"DXIL", dxil_ps60, 28}};
|
||||
const chunk_t accc_v1_chunks[] = {{"ACCC", fspx_v1, sizeof(fspx_v1)}};
|
||||
const chunk_t accc_v0_chunks[] = {{"ACCC", fspx_v0, sizeof(fspx_v0)}};
|
||||
const chunk_t dual_chunks[] = {{"DXIL", dxil_cs66, 28}, {"ACCC", fspx_v0, sizeof(fspx_v0)}};
|
||||
const chunk_t legacy_chunks[] = {{"SHEX", shex, sizeof(shex)}};
|
||||
const uint32_t ps60_len = build_dxbc(ps60, sizeof(ps60), ps60_chunks, 2);
|
||||
const uint32_t accc_v1_len = build_dxbc(accc_v1, sizeof(accc_v1), accc_v1_chunks, 1);
|
||||
const uint32_t accc_v0_len = build_dxbc(accc_v0, sizeof(accc_v0), accc_v0_chunks, 1);
|
||||
const uint32_t dual_len = build_dxbc(dual, sizeof(dual), dual_chunks, 2);
|
||||
const uint32_t legacy_len = build_dxbc(legacy, sizeof(legacy), legacy_chunks, 1);
|
||||
/* The pixel shader again, followed by 16 bytes that are not part of the container. */
|
||||
static uint8_t padded[256 + 16];
|
||||
memcpy(padded, ps60, ps60_len);
|
||||
memset(padded + ps60_len, 0xEE, 16);
|
||||
static const uint8_t truncated[20] = {'D', 'X', 'B', 'C'};
|
||||
static const uint8_t not_dxbc[64] = {'X', 'X', 'X', 'X'};
|
||||
|
||||
const case_t cases[] = {
|
||||
{"dxc_cs_6_6", g_fill_cs66, sizeof(g_fill_cs66), BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_COMPUTE, 6, 6,
|
||||
sizeof(g_fill_cs66), BX_SHADER_OK},
|
||||
{"synthetic_ps_6_0", ps60, ps60_len, BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_PIXEL, 6, 0, ps60_len,
|
||||
BX_SHADER_OK},
|
||||
{"trailing_bytes", padded, ps60_len + 16, BX_SHADER_OK, BX_SHADER_DXBC_DXIL, BX_STAGE_PIXEL, 6, 0, ps60_len,
|
||||
BX_SHADER_OK},
|
||||
{"accc_fspx_v1", accc_v1, accc_v1_len, BX_SHADER_OK, BX_SHADER_DXBC_ACCC, BX_STAGE_COMPUTE, 6, 0, accc_v1_len,
|
||||
BX_SHADER_ERR_UNSUPPORTED},
|
||||
{"accc_fspx_v0", accc_v0, accc_v0_len, BX_SHADER_OK, BX_SHADER_DXBC_ACCC, BX_STAGE_UNKNOWN, 0, 0, accc_v0_len,
|
||||
BX_SHADER_ERR_UNSUPPORTED},
|
||||
{"dual_dxil_accc", dual, dual_len, BX_SHADER_OK, BX_SHADER_DXBC_DUAL, BX_STAGE_COMPUTE, 6, 6, dual_len,
|
||||
BX_SHADER_OK},
|
||||
{"legacy_shex_5_0", legacy, legacy_len, BX_SHADER_OK, BX_SHADER_DXBC_LEGACY, BX_STAGE_COMPUTE, 5, 0,
|
||||
legacy_len, BX_SHADER_ERR_UNSUPPORTED},
|
||||
{"truncated", truncated, sizeof(truncated), BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_UNKNOWN, BX_STAGE_UNKNOWN,
|
||||
0, 0, 0, BX_SHADER_ERR_INVALID_BLOB},
|
||||
{"not_dxbc", not_dxbc, sizeof(not_dxbc), BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_UNKNOWN, BX_STAGE_UNKNOWN, 0,
|
||||
0, 0, BX_SHADER_ERR_INVALID_BLOB},
|
||||
};
|
||||
const size_t count = sizeof(cases) / sizeof(cases[0]);
|
||||
|
||||
unsigned tally[5] = {0};
|
||||
unsigned invalid = 0;
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
const case_t* c = &cases[i];
|
||||
bx_shader_inspection_t info;
|
||||
memset(&info, 0xEE, sizeof(info));
|
||||
const bx_shader_status_t status = inspect(c->bytes, c->len, &info);
|
||||
printf("BXSHADER %s status=%d kind=%s stage=%d sm=%u.%u container_size=%u dxil=%u accc=%u rts0=%u\n",
|
||||
c->name, (int)status, kind_name(info.kind), (int)info.stage, info.shader_model_major,
|
||||
info.shader_model_minor, info.container_size, info.dxil_chunk_size, info.accc_chunk_size,
|
||||
info.has_root_signature);
|
||||
CHECK(status == c->inspect_status);
|
||||
if (status == BX_SHADER_OK) {
|
||||
if ((unsigned)info.kind < 5) ++tally[info.kind];
|
||||
CHECK(info.kind == c->kind);
|
||||
CHECK(info.stage == c->stage);
|
||||
CHECK(info.shader_model_major == c->sm_major && info.shader_model_minor == c->sm_minor);
|
||||
CHECK(info.container_size == c->container_size);
|
||||
/* Exact chunk sizes and the root signature flag, from this file's own chunk walk. */
|
||||
uint32_t want_dxil = 0, want_accc = 0, rts0_size = 0;
|
||||
chunk(c->bytes, c->len, "DXIL", &want_dxil);
|
||||
chunk(c->bytes, c->len, "ACCC", &want_accc);
|
||||
const uint32_t want_rts0 = (uint32_t)chunk(c->bytes, c->len, "RTS0", &rts0_size);
|
||||
CHECK(info.dxil_chunk_size == want_dxil);
|
||||
CHECK(info.accc_chunk_size == want_accc);
|
||||
CHECK(info.has_root_signature == want_rts0);
|
||||
CHECK((want_dxil != 0) == (c->kind == BX_SHADER_DXBC_DXIL || c->kind == BX_SHADER_DXBC_DUAL));
|
||||
CHECK((want_accc != 0) == (c->kind == BX_SHADER_DXBC_ACCC || c->kind == BX_SHADER_DXBC_DUAL));
|
||||
/* The digest is the container header's bytes 4..20, for every case. */
|
||||
CHECK(memcmp(info.digest_hash, c->bytes + 4, 16) == 0);
|
||||
} else {
|
||||
++invalid;
|
||||
const bx_shader_inspection_t zero = {0};
|
||||
CHECK(memcmp(&info, &zero, sizeof(info)) == 0); /* cleared on failure */
|
||||
}
|
||||
|
||||
uint8_t* copy = (uint8_t*)(uintptr_t)1;
|
||||
size_t copy_len = 1;
|
||||
const bx_shader_status_t prepared = prepare(c->bytes, c->len, ©, ©_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,6 +1,8 @@
|
||||
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)
|
||||
+36
-19
@@ -1,8 +1,8 @@
|
||||
#include "proxy.h"
|
||||
#include "vmem.h"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
#include "bx_xmem_internal.h"
|
||||
#include <mutex>
|
||||
|
||||
/*
|
||||
* Track C (M1-C1, #414): Xbox Series D3D12 entry points over the host's d3d12.dll
|
||||
@@ -20,9 +20,12 @@ HMODULE get_host_d3d12() {
|
||||
return mod;
|
||||
}
|
||||
|
||||
void refresh_trace_flag() {
|
||||
const bx_runtime_config_t* cfg = bx_get_runtime_config();
|
||||
g_bx_trace_d3d = (cfg && cfg->trace_d3d) ? 1u : 0u;
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -40,7 +43,7 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
refresh_trace_flag();
|
||||
initialize_trace_flag();
|
||||
|
||||
using CreateFn = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
|
||||
HMODULE d3d12 = get_host_d3d12();
|
||||
@@ -53,12 +56,24 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
}
|
||||
|
||||
ID3D12Device* host = nullptr;
|
||||
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;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
BxDeviceProxy* proxy = BxDeviceProxy::create(host);
|
||||
@@ -66,6 +81,10 @@ 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;
|
||||
@@ -77,10 +96,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[192];
|
||||
char detail[256];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"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);
|
||||
"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);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "D3D12XboxCreateDevice", detail);
|
||||
|
||||
hr = proxy->QueryInterface(riid, ppv);
|
||||
@@ -88,10 +107,8 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
return hr;
|
||||
}
|
||||
|
||||
/* 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 D3D12ConfigureVirtualMemoryX(PVOID config) {
|
||||
return bx_d3d12_configure_virtual_memory(config);
|
||||
}
|
||||
|
||||
HRESULT WINAPI D3D12SerializeVersionedRootSignature(
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
#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}};
|
||||
|
||||
@@ -132,9 +135,11 @@ 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, "SHDR", 4) == 0 ||
|
||||
std::memcmp(bytes + off, "ACCC", 4) == 0) {
|
||||
has_shader_chunk = true;
|
||||
}
|
||||
if (i < 16) {
|
||||
@@ -199,13 +204,43 @@ 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() {
|
||||
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (left == 0) {
|
||||
bx_release_hosts();
|
||||
delete this;
|
||||
/* 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);
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
HRESULT BxDeviceProxy::wrap_child(IUnknown* host_child, const char* what, REFIID riid, void** ppv) {
|
||||
@@ -345,7 +380,25 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreateGraphicsPipelineState(const D3D12
|
||||
log_created("graphics pipeline state", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
HRESULT hr = h_ID3D12Device->CreateGraphicsPipelineState(desc, riid, ppv);
|
||||
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);
|
||||
log_created("graphics pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
@@ -357,7 +410,21 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreateComputePipelineState(const D3D12_
|
||||
log_created("compute pipeline state", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
HRESULT hr = h_ID3D12Device->CreateComputePipelineState(desc, riid, ppv);
|
||||
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);
|
||||
log_created("compute pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
@@ -53,6 +53,12 @@ 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(a0, a1, a2, a3, a4, a5, a6);
|
||||
return h_ID3D12Device->CreatePlacedResource(bx_unwrap(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(a0, a1, a2, a3, a4, a5, a6);
|
||||
return h_ID3D12Device8->CreatePlacedResource1(bx_unwrap(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(a0, a1, a2, a3, a4, a5, a6, a7, a8);
|
||||
return h_ID3D12Device10->CreatePlacedResource2(bx_unwrap(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, a4, a5, a6, a7, a8, a9);
|
||||
h_ID3D12CommandQueue->UpdateTileMappings(a0, a1, a2, a3, bx_unwrap(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) {
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
#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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
#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,8 +44,11 @@ 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"}
|
||||
"ID3D12GraphicsCommandList", "ID3D12Pageable", "ID3D12DeviceChild", "ID3D12Object",
|
||||
"ID3D12Heap", "ID3D12Heap1"}
|
||||
|
||||
IUNKNOWN = [
|
||||
("HRESULT", "QueryInterface", [("REFIID", ""), ("void **", "")]),
|
||||
|
||||
@@ -0,0 +1,876 @@
|
||||
#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;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
#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,6 +1,8 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
@@ -10,6 +12,30 @@ 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;
|
||||
@@ -19,6 +45,11 @@ 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;
|
||||
@@ -54,9 +85,32 @@ public:
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 8, "RegisterReadingCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
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 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 RegisterSystemButtonCallback(void*, uint32_t, void*, Callback, uint64_t* out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 10, "RegisterSystemButtonCallback");
|
||||
@@ -66,12 +120,18 @@ public:
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 11, "RegisterKeyboardLayoutCallback");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual void WINAPI StopCallback(uint64_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 12, "StopCallback");
|
||||
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 bool WINAPI UnregisterCallback(uint64_t, uint64_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 13, "UnregisterCallback");
|
||||
return false;
|
||||
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 HRESULT WINAPI CreateDispatcher(void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 14, "CreateDispatcher");
|
||||
@@ -101,8 +161,8 @@ public:
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 20, "EnableOemDeviceSupport");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual void WINAPI SetFocusPolicy(uint32_t) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 21, "SetFocusPolicy");
|
||||
virtual void WINAPI SetFocusPolicy(uint32_t policy) {
|
||||
focus_policy_.store(policy, std::memory_order_relaxed);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <intrin.h>
|
||||
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
@@ -17,6 +18,14 @@ 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,
|
||||
@@ -135,6 +144,167 @@ 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 &&
|
||||
@@ -198,20 +368,25 @@ 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;
|
||||
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);
|
||||
}
|
||||
log_sampled_trap("clwb_trapped", count, ep->ContextRecord->Rip, len);
|
||||
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,4 +1,6 @@
|
||||
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)
|
||||
@@ -0,0 +1,21 @@
|
||||
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.
|
||||
@@ -0,0 +1,15 @@
|
||||
# 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
@@ -0,0 +1,502 @@
|
||||
/*-------------------------------------------------------------------------------------
|
||||
*
|
||||
* 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)
|
||||
@@ -0,0 +1,27 @@
|
||||
#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,6 +2,12 @@
|
||||
#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>
|
||||
|
||||
@@ -26,9 +32,20 @@ struct Status : IUnknown {
|
||||
virtual HRESULT STDMETHODCALLTYPE GetResult(UINT index) = 0;
|
||||
};
|
||||
|
||||
// Requests keep source and destination buffers borrowed until completion.
|
||||
// BetterXen-defined request. Borrowed CPU pointers stay valid until completion.
|
||||
// File requests retain a duplicate of the file handle when enqueued.
|
||||
// Exactly one of `file` or `source` may be non-null; setting both returns E_INVALIDARG.
|
||||
// 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.
|
||||
struct Request {
|
||||
File* file;
|
||||
UINT64 file_offset;
|
||||
@@ -36,8 +53,15 @@ 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;
|
||||
|
||||
+878
-28
File diff suppressed because it is too large.
Load diff
@@ -2,6 +2,8 @@ bx_add_shim_dll(xgameruntime xgameruntime xgameruntime.def
|
||||
xgameruntime.cpp
|
||||
task_queue.cpp
|
||||
com_dispatch.cpp
|
||||
game_save.cpp
|
||||
package.cpp
|
||||
)
|
||||
target_link_libraries(xgameruntime PRIVATE bx_runtime_veh kernel32)
|
||||
target_compile_options(xgameruntime PRIVATE -fexceptions)
|
||||
@@ -6,9 +6,16 @@
|
||||
* 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>
|
||||
@@ -290,8 +297,25 @@ ComSingleton kSystemObj{kSystemVtbl.data(), &kSystemIid, "IXSystem"};
|
||||
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;
|
||||
@@ -573,6 +597,196 @@ const std::array<const void*, 8> kGameVtbl = [] {
|
||||
}();
|
||||
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;
|
||||
@@ -592,6 +806,13 @@ const PublicEntry kPublicEntries[] = {
|
||||
{&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
|
||||
|
||||
@@ -0,0 +1,983 @@
|
||||
/*
|
||||
* 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
|
||||
@@ -0,0 +1,306 @@
|
||||
/*
|
||||
* 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
|
||||
@@ -0,0 +1,109 @@
|
||||
#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
|
||||
@@ -0,0 +1,92 @@
|
||||
#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,4 +1,6 @@
|
||||
#include "com_dispatch.h"
|
||||
#include "runtime_internal.h"
|
||||
#include "synthetic_keys.h"
|
||||
#include "task_queue.h"
|
||||
|
||||
#include <condition_variable>
|
||||
@@ -6,6 +8,7 @@
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
#include <unordered_set>
|
||||
@@ -18,10 +21,10 @@ namespace {
|
||||
using namespace bx::gdk;
|
||||
|
||||
// ABI values and layouts checked against Microsoft's public PC GDK 2510.5.6322.
|
||||
constexpr HRESULT runtime_not_initialized = static_cast<HRESULT>(0x89240100u);
|
||||
constexpr HRESULT runtime_invalid_handle = static_cast<HRESULT>(0x8924010cu);
|
||||
constexpr HRESULT illegal_method_call = static_cast<HRESULT>(0x8000000eu);
|
||||
constexpr HRESULT insufficient_buffer = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
|
||||
constexpr HRESULT runtime_not_initialized = kRuntimeNotInitialized;
|
||||
constexpr HRESULT runtime_invalid_handle = kRuntimeInvalidHandle;
|
||||
constexpr HRESULT illegal_method_call = kIllegalMethodCall;
|
||||
constexpr HRESULT insufficient_buffer = kInsufficientBuffer;
|
||||
|
||||
struct AsyncBlock {
|
||||
void* queue;
|
||||
@@ -56,7 +59,8 @@ struct SpaceInfo {
|
||||
uint64_t total_bytes;
|
||||
};
|
||||
|
||||
enum class Operation : uint32_t { add_user, game_license };
|
||||
// custom: an AsyncOp from another translation unit (XGameSave), see runtime_internal.h.
|
||||
enum class Operation : uint32_t { add_user, game_license, custom };
|
||||
|
||||
struct AsyncState {
|
||||
const AsyncBlock* owner;
|
||||
@@ -79,6 +83,8 @@ uint64_t next_operation = 1;
|
||||
uintptr_t next_handle = 2;
|
||||
std::unordered_set<void*> users;
|
||||
std::unordered_set<void*> stores;
|
||||
// Finished custom operations awaiting their Result call, keyed by AsyncState::sequence.
|
||||
std::map<uint64_t, std::unique_ptr<AsyncOp>> finished_ops;
|
||||
|
||||
HRESULT create_handle(std::unordered_set<void*>& handles, void** out) {
|
||||
auto handle = reinterpret_cast<void*>(next_handle);
|
||||
@@ -159,10 +165,12 @@ class AsyncTask final : public Task {
|
||||
public:
|
||||
AsyncBlock* block;
|
||||
Operation operation;
|
||||
std::unique_ptr<AsyncOp> op;
|
||||
std::unique_ptr<CompletionTask> completion;
|
||||
bool queued = false;
|
||||
|
||||
AsyncTask(AsyncBlock* block, Operation operation) : block(block), operation(operation) {}
|
||||
AsyncTask(AsyncBlock* block, Operation operation, std::unique_ptr<AsyncOp> op)
|
||||
: block(block), operation(operation), op(std::move(op)) {}
|
||||
|
||||
~AsyncTask() override {
|
||||
if (!queued) return;
|
||||
@@ -185,11 +193,34 @@ public:
|
||||
private:
|
||||
void finish(const QueueRef& queue, bool canceled) {
|
||||
const bool entitled = !canceled && operation == Operation::game_license && fixture_entitlement();
|
||||
bool cancel_requested;
|
||||
bool stale;
|
||||
{
|
||||
std::lock_guard lock(state_mutex);
|
||||
const auto state = read_state(block);
|
||||
cancel_requested = state.cancel_requested;
|
||||
stale = !runtime_refs || state.runtime_generation != runtime_generation;
|
||||
}
|
||||
// The block stays E_PENDING meanwhile, so the caller cannot reuse it. Once an op has
|
||||
// run, a later XAsyncCancel or uninitialize cannot undo it, so its own status is
|
||||
// reported. An op whose runtime was uninitialized before it ran is not run.
|
||||
const bool executed = op && !canceled && !cancel_requested && !stale;
|
||||
const HRESULT op_status = executed ? op->execute() : S_OK;
|
||||
{
|
||||
std::lock_guard lock(state_mutex);
|
||||
auto state = read_state(block);
|
||||
state.status = (canceled || state.cancel_requested) ? E_ABORT : S_OK;
|
||||
state.status = executed ? op_status
|
||||
: canceled || state.cancel_requested ? E_ABORT
|
||||
: op && stale ? runtime_not_initialized
|
||||
: S_OK;
|
||||
state.entitled = entitled;
|
||||
if (op && SUCCEEDED(state.status) && state.runtime_generation == runtime_generation && runtime_refs) {
|
||||
try {
|
||||
finished_ops[state.sequence] = std::move(op);
|
||||
} catch (const std::bad_alloc&) {
|
||||
state.status = E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
if (completion) completion->sequence = state.sequence;
|
||||
queued = false;
|
||||
write_state(block, state);
|
||||
@@ -198,12 +229,12 @@ private:
|
||||
}
|
||||
};
|
||||
|
||||
HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr) {
|
||||
HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr, std::unique_ptr<AsyncOp> op = nullptr) {
|
||||
if (!block) return E_POINTER;
|
||||
const auto queue = acquire_queue(block->queue);
|
||||
if (!queue) return block->queue ? E_HANDLE : E_OUTOFMEMORY;
|
||||
|
||||
auto work = std::unique_ptr<AsyncTask>(new (std::nothrow) AsyncTask(block, operation));
|
||||
auto work = std::unique_ptr<AsyncTask>(new (std::nothrow) AsyncTask(block, operation, std::move(op)));
|
||||
if (!work) return E_OUTOFMEMORY;
|
||||
if (block->callback) {
|
||||
work->completion.reset(new (std::nothrow) CompletionTask(block));
|
||||
@@ -222,6 +253,8 @@ HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr) {
|
||||
callback_running(previous.sequence, GetCurrentThreadId()))) {
|
||||
return illegal_method_call;
|
||||
}
|
||||
// An unconsumed result of an earlier operation on this block is abandoned.
|
||||
if (previous.owner == block) finished_ops.erase(previous.sequence);
|
||||
write_state(block, {block, next_operation++, E_PENDING, operation, runtime_generation,
|
||||
false, block->callback != nullptr, false, false});
|
||||
work->queued = true;
|
||||
@@ -277,19 +310,6 @@ bool fixture_entitlement() {
|
||||
GetProcAddress(GetModuleHandleW(nullptr), "BetterXenSyntheticStoreFixture") != nullptr;
|
||||
}
|
||||
|
||||
HRESULT ensure_directory(const wchar_t* path) {
|
||||
if (CreateDirectoryW(path, nullptr)) return S_OK;
|
||||
const auto error = GetLastError();
|
||||
if (error != ERROR_ALREADY_EXISTS) return HRESULT_FROM_WIN32(error);
|
||||
|
||||
const auto attributes = GetFileAttributesW(path);
|
||||
if (attributes == INVALID_FILE_ATTRIBUTES) return HRESULT_FROM_WIN32(GetLastError());
|
||||
if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) != FILE_ATTRIBUTE_DIRECTORY) {
|
||||
return HRESULT_FROM_WIN32(ERROR_DIRECTORY);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT storage_path(wchar_t (&path)[MAX_PATH]) {
|
||||
wchar_t module[MAX_PATH];
|
||||
const wchar_t* name = nullptr;
|
||||
@@ -302,11 +322,7 @@ HRESULT storage_path(wchar_t (&path)[MAX_PATH]) {
|
||||
normalized, MAX_PATH, nullptr, nullptr, 0)) {
|
||||
return HRESULT_FROM_WIN32(GetLastError());
|
||||
}
|
||||
uint64_t path_id = 14695981039346656037ULL;
|
||||
for (auto* ch = normalized; *ch; ++ch) {
|
||||
path_id ^= static_cast<uint16_t>(*ch);
|
||||
path_id *= 1099511628211ULL;
|
||||
}
|
||||
const uint64_t path_id = bx::gdk::fnv1a(normalized);
|
||||
const auto length = std::swprintf(path, MAX_PATH, L"%ls\\%016llx", storage_root,
|
||||
static_cast<unsigned long long>(path_id));
|
||||
return length < 0 ? HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE) : S_OK;
|
||||
@@ -323,6 +339,9 @@ bool release_runtime_ref() {
|
||||
if (!--runtime_refs) {
|
||||
users.clear();
|
||||
stores.clear();
|
||||
finished_ops.clear();
|
||||
bx::gdk::release_game_save_state();
|
||||
bx::gdk::release_package_state();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -369,13 +388,10 @@ struct ApiInitOptions {
|
||||
};
|
||||
static_assert(offsetof(ApiInitOptions, game_config) == 8);
|
||||
|
||||
constexpr uint16_t family_data2 = 0x5853;
|
||||
constexpr uint16_t family_data3 = 0x4000;
|
||||
|
||||
// The synthetic key encoding is defined in synthetic_keys.h.
|
||||
bool synthetic_guid(const GUID* guid) {
|
||||
return guid->Data2 == family_data2 && guid->Data3 == family_data3 && guid->Data4[0] == 0x80 &&
|
||||
guid->Data4[1] == 0 && guid->Data4[2] == 0 && guid->Data4[3] == 0 && guid->Data4[4] == 0 &&
|
||||
guid->Data4[5] == 0 && guid->Data4[6] == 0 && guid->Data4[7] == 1;
|
||||
return guid->Data2 == synthetic::kData2 && guid->Data3 == synthetic::kData3 &&
|
||||
std::memcmp(guid->Data4, synthetic::kData4, sizeof(synthetic::kData4)) == 0;
|
||||
}
|
||||
|
||||
void format_guid(char* dst, size_t cap, const GUID* guid) {
|
||||
@@ -459,6 +475,75 @@ HRESULT check_loader_versions(uint32_t gdk_ver, uint32_t gs_ver, const char* eve
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace bx::gdk {
|
||||
|
||||
HRESULT ensure_directory(const wchar_t* path) {
|
||||
if (CreateDirectoryW(path, nullptr)) return S_OK;
|
||||
const auto error = GetLastError();
|
||||
if (error != ERROR_ALREADY_EXISTS) return HRESULT_FROM_WIN32(error);
|
||||
|
||||
const auto attributes = GetFileAttributesW(path);
|
||||
if (attributes == INVALID_FILE_ATTRIBUTES) return HRESULT_FROM_WIN32(GetLastError());
|
||||
if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) != FILE_ATTRIBUTE_DIRECTORY) {
|
||||
return HRESULT_FROM_WIN32(ERROR_DIRECTORY);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
uint64_t fnv1a(const wchar_t* text) {
|
||||
uint64_t hash = 14695981039346656037ULL;
|
||||
for (auto* ch = text; *ch; ++ch) {
|
||||
hash ^= static_cast<uint16_t>(*ch);
|
||||
hash *= 1099511628211ULL;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
HRESULT executable_path(wchar_t (&path)[MAX_PATH]) {
|
||||
const wchar_t* name = nullptr;
|
||||
return executable_name(path, name);
|
||||
}
|
||||
|
||||
HRESULT title_storage_directory(wchar_t (&path)[MAX_PATH]) {
|
||||
const auto hr = storage_path(path);
|
||||
return FAILED(hr) ? hr : create_storage(path);
|
||||
}
|
||||
|
||||
uint32_t active_runtime_generation() {
|
||||
std::lock_guard lock(state_mutex);
|
||||
return runtime_refs ? runtime_generation : 0;
|
||||
}
|
||||
|
||||
bool is_valid_user(void* user) {
|
||||
std::lock_guard lock(state_mutex);
|
||||
return runtime_refs && users.contains(user);
|
||||
}
|
||||
|
||||
HRESULT begin_async_op(void* block, std::unique_ptr<AsyncOp> op) {
|
||||
if (!op) return E_OUTOFMEMORY;
|
||||
return begin(static_cast<AsyncBlock*>(block), Operation::custom, nullptr, std::move(op));
|
||||
}
|
||||
|
||||
HRESULT consume_async_op(void* block, uint32_t kind, const std::function<HRESULT(AsyncOp&)>& consume) {
|
||||
auto* async = static_cast<AsyncBlock*>(block);
|
||||
std::lock_guard lock(state_mutex);
|
||||
AsyncState state{};
|
||||
const auto hr = check_result(async, Operation::custom, state);
|
||||
if (FAILED(hr)) return hr;
|
||||
const auto found = finished_ops.find(state.sequence);
|
||||
if (found == finished_ops.end() || found->second->kind() != kind) return illegal_method_call;
|
||||
|
||||
const auto result = consume(*found->second);
|
||||
if (SUCCEEDED(result)) {
|
||||
finished_ops.erase(found);
|
||||
state.result_consumed = true;
|
||||
write_state(async, state);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace bx::gdk
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT WINAPI XGameRuntimeInitialize() {
|
||||
@@ -513,7 +598,16 @@ HRESULT WINAPI XAsyncGetResultSize(AsyncBlock* block, size_t* size) {
|
||||
const auto state = read_state(block);
|
||||
if (state.owner != block || state.result_consumed) return illegal_method_call;
|
||||
if (SUCCEEDED(state.status)) {
|
||||
*size = state.operation == Operation::add_user ? sizeof(void*) : sizeof(GameLicense);
|
||||
switch (state.operation) {
|
||||
case Operation::add_user: *size = sizeof(void*); break;
|
||||
case Operation::game_license: *size = sizeof(GameLicense); break;
|
||||
case Operation::custom: {
|
||||
const auto found = finished_ops.find(state.sequence);
|
||||
if (found == finished_ops.end()) return illegal_method_call;
|
||||
*size = found->second->result_size();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return state.status;
|
||||
}
|
||||
@@ -802,17 +896,21 @@ struct Family {
|
||||
uint32_t iid;
|
||||
const char* name;
|
||||
const void* table;
|
||||
bool com; // table is a COM object, so IID_IUnknown also reaches it
|
||||
};
|
||||
|
||||
// Synthetic BetterXen dispatch keys, not Microsoft CLSIDs.
|
||||
// Data2 = 0x5853, Data3 = 0x4000, Data4 = 80 00 00 00 00 00 00 01.
|
||||
// Synthetic BetterXen dispatch keys, not Microsoft CLSIDs. All keys and the COM slot
|
||||
// orders live in synthetic_keys.h.
|
||||
const Family families[] = {
|
||||
{0xB7581001, 0xB7581002, "xtaskqueue", &task_queue_api},
|
||||
{0xB7581101, 0xB7581102, "xasync", &async_api},
|
||||
{0xB7581201, 0xB7581202, "xuser", &user_api},
|
||||
{0xB7581301, 0xB7581302, "xstore", &store_api},
|
||||
{0xB7581401, 0xB7581402, "xsystem", &system_api},
|
||||
{0xB7581501, 0xB7581502, "xpersistentlocalstorage", &storage_api},
|
||||
{synthetic::kTaskQueue.clsid, synthetic::kTaskQueue.iid, "xtaskqueue", &task_queue_api, false},
|
||||
{synthetic::kAsync.clsid, synthetic::kAsync.iid, "xasync", &async_api, false},
|
||||
{synthetic::kUser.clsid, synthetic::kUser.iid, "xuser", &user_api, false},
|
||||
{synthetic::kStore.clsid, synthetic::kStore.iid, "xstore", &store_api, false},
|
||||
{synthetic::kSystem.clsid, synthetic::kSystem.iid, "xsystem", &system_api, false},
|
||||
{synthetic::kPersistentLocalStorage.clsid, synthetic::kPersistentLocalStorage.iid, "xpersistentlocalstorage",
|
||||
&storage_api, false},
|
||||
{synthetic::kGameSave.clsid, synthetic::kGameSave.iid, "xgamesave", bx::gdk::game_save_object, true},
|
||||
{synthetic::kPackage.clsid, synthetic::kPackage.iid, "xpackage", bx::gdk::package_object, true},
|
||||
};
|
||||
|
||||
const Family* find_family(const GUID* clsid) {
|
||||
@@ -844,7 +942,8 @@ HRESULT WINAPI QueryApiImpl(const GUID* clsid, const GUID* iid, void** out) {
|
||||
}
|
||||
|
||||
const auto* family = find_family(clsid);
|
||||
if (family && synthetic_guid(iid) && iid->Data1 == family->iid) {
|
||||
if (family && ((synthetic_guid(iid) && iid->Data1 == family->iid) ||
|
||||
(family->com && IsEqualGUID(*iid, bx::gdk::kIUnknownIid)))) {
|
||||
*out = const_cast<void*>(family->table);
|
||||
char detail[64];
|
||||
std::snprintf(detail, sizeof(detail), "dispatch family=%s", family->name);
|
||||
|
||||
@@ -27,6 +27,10 @@ HRESULT WINAPI XDspDisconnect(void*);
|
||||
|
||||
#define CHECK(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0)
|
||||
|
||||
namespace {
|
||||
void WINAPI dummy_device_callback(uint64_t, void*, void*, uint64_t, uint32_t, uint32_t) {}
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
void* object = nullptr;
|
||||
CHECK(AcpHalCreate(&object) == S_OK && object);
|
||||
@@ -148,8 +152,42 @@ int main() {
|
||||
using Reading = HRESULT (WINAPI*)(IUnknown*, uint32_t, void*, void**);
|
||||
void* reading = reinterpret_cast<void*>(uintptr_t{1});
|
||||
CHECK(reinterpret_cast<Reading>(table[4])(v0, 0, nullptr, &reading) == E_NOTIMPL && !reading);
|
||||
|
||||
using RegisterDeviceCb = HRESULT (WINAPI*)(
|
||||
IUnknown*, void*, uint32_t, uint32_t, uint32_t, void*, void*, uint64_t*);
|
||||
using StopCb = void (WINAPI*)(IUnknown*, uint64_t);
|
||||
using UnregisterCb = bool (WINAPI*)(IUnknown*, uint64_t, uint64_t);
|
||||
using SetFocusPolicyFn = void (WINAPI*)(IUnknown*, uint32_t);
|
||||
auto reg_dev = reinterpret_cast<RegisterDeviceCb>(table[9]);
|
||||
auto stop_cb = reinterpret_cast<StopCb>(table[12]);
|
||||
auto unreg_cb = reinterpret_cast<UnregisterCb>(table[13]);
|
||||
auto set_focus = reinterpret_cast<SetFocusPolicyFn>(table[21]);
|
||||
void* cb_fn = reinterpret_cast<void*>(&dummy_device_callback);
|
||||
|
||||
uint64_t tok1 = 99, tok2 = 0;
|
||||
CHECK(reg_dev(v0, nullptr, 1, 1, 0, nullptr, nullptr, &tok1) == E_INVALIDARG && tok1 == 0);
|
||||
tok1 = 99;
|
||||
CHECK(reg_dev(v0, nullptr, 0, 1, 0, nullptr, cb_fn, &tok1) == E_INVALIDARG && tok1 == 0);
|
||||
tok1 = 99;
|
||||
CHECK(reg_dev(v0, nullptr, 1, 0, 0, nullptr, cb_fn, &tok1) == E_INVALIDARG && tok1 == 0);
|
||||
tok1 = 99;
|
||||
CHECK(reg_dev(v0, nullptr, 1, 1, 3, nullptr, cb_fn, &tok1) == E_INVALIDARG && tok1 == 0);
|
||||
|
||||
CHECK(reg_dev(v0, nullptr, 0x10000, 0x1, 2, &tok1, cb_fn, &tok1) == S_OK && tok1 != 0);
|
||||
CHECK(reg_dev(v0, nullptr, 0x10000, 0x1, 1, nullptr, cb_fn, &tok2) == S_OK && tok2 > tok1);
|
||||
CHECK(reg_dev(v0, nullptr, 0x10000, 0x1, 0, nullptr, cb_fn, nullptr) == S_OK);
|
||||
|
||||
CHECK(!unreg_cb(v0, 0, 5000));
|
||||
CHECK(!unreg_cb(v0, 0xdeadbeefULL, 5000));
|
||||
stop_cb(v0, tok1);
|
||||
CHECK(unreg_cb(v0, tok1, 5000));
|
||||
CHECK(!unreg_cb(v0, tok1, 5000));
|
||||
CHECK(unreg_cb(v0, tok2, 0));
|
||||
CHECK(!unreg_cb(v0, tok2, 0));
|
||||
set_focus(v0, 0x2);
|
||||
|
||||
CHECK(v0->Release() == 1);
|
||||
CHECK(input->Release() == 0);
|
||||
FreeLibrary(dll);
|
||||
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1");
|
||||
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1 and device callbacks");
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# M2-C1 (#464): D3D12ConfigureVirtualMemoryX plus placed buffer and RGBA8 texture readback.
|
||||
add_executable(test_d3d12_placed main.cpp)
|
||||
target_include_directories(test_d3d12_placed PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_d3d12_placed PRIVATE d3d12_xs xmem bx_runtime_veh kernel32)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
# M2 Shader Format Gate (#466): Create*PipelineState through d3d12_xs.dll with DXIL, ACCC-only and
|
||||
# constraint-carrying shaders. Needs bx_shader_bridge.dll (shader-transpiler/crates/dxbc-accc/guest/build.sh,
|
||||
# #445) next to the shims at run time. The DXIL blobs are existing DXC 1.9.2609 outputs in the tree.
|
||||
add_executable(test_shader_gate main.cpp)
|
||||
target_include_directories(test_shader_gate PRIVATE
|
||||
"${BX_ABI_INCLUDE_DIR}"
|
||||
"${BX_ROOT_DIR}/shader-transpiler/crates/d3dmetal-harness/probe/shaders"
|
||||
"${BX_ROOT_DIR}/tests/conformance/test_d3dmetal_gpu_limits/shaders"
|
||||
)
|
||||
target_link_libraries(test_shader_gate PRIVATE d3d12_xs kernel32)
|
||||
@@ -0,0 +1,473 @@
|
||||
/*
|
||||
* M2 Shader Format Gate (#466): synthetic conformance test for the PSO hook in d3d12_xs.dll.
|
||||
*
|
||||
* Through D3D12XboxCreateDevice it:
|
||||
* 1. creates a compute PSO from a real DXC 1.9.2609 SM 6.6 DXIL blob (fill_cs66, from
|
||||
* d3dmetal-harness), dispatches it and checks all 256 output words on the CPU;
|
||||
* 2. submits a synthetic ACCC-only container (BetterXen FSPX v1, compute) to
|
||||
* CreateComputePipelineState and to CreateGraphicsPipelineState and requires E_NOTIMPL
|
||||
* with no object and no call reaching the host device;
|
||||
* 3. creates PSOs from the #453 [WaveSize(64)] and 64-bit typed-atomic blobs and requires the
|
||||
* gate to log their constraints;
|
||||
* 4. checks the structured `shader_gate` JSONL records.
|
||||
*
|
||||
* It then runs a copy of itself with --no-bridge from a directory holding d3d12_xs.dll but not
|
||||
* the bridge, which must still run DXIL and refuse ACCC-only with E_NOTIMPL.
|
||||
*
|
||||
* Expected values come from the D3D12 contract, the DXBC layout and the documented kernel, not
|
||||
* from the shim. Needs bx_shader_bridge.dll next to the shims and BX_LOG_FILE (bx-cli --log).
|
||||
* It also checks that the bridge was loaded from d3d12_xs.dll's directory; run it with the EXE
|
||||
* in a different directory from the shims to exercise that lookup.
|
||||
*/
|
||||
#ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <climits>
|
||||
#include <cstdarg>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "atomic64_image.h" // g_atomic64_image_cs, #453
|
||||
#include "fill_cs66.h" // g_fill_cs66, d3dmetal-harness
|
||||
#include "wave64_lanes.h" // g_wave64_lanes_cs, #453
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12SerializeVersionedRootSignature(
|
||||
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, ID3DBlob** blob, ID3DBlob** error);
|
||||
|
||||
namespace {
|
||||
|
||||
int g_checks = 0;
|
||||
int g_failures = 0;
|
||||
|
||||
__attribute__((format(gnu_printf, 2, 3)))
|
||||
bool check(bool ok, const char* fmt, ...) {
|
||||
++g_checks;
|
||||
if (!ok) {
|
||||
++g_failures;
|
||||
char msg[320];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
std::vsnprintf(msg, sizeof(msg), fmt, ap);
|
||||
va_end(ap);
|
||||
std::fprintf(stderr, "FAIL: %s\n", msg);
|
||||
std::fflush(stderr);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
unsigned long ul(HRESULT hr) { return static_cast<unsigned long>(hr); }
|
||||
|
||||
int finish() {
|
||||
if (g_failures) {
|
||||
std::fprintf(stderr, "FAIL: test_shader_gate (%d of %d checks failed)\n", g_failures, g_checks);
|
||||
return 1;
|
||||
}
|
||||
std::printf("PASS: test_shader_gate (%d checks)\n", g_checks);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* The kernel in fill_cs66.hlsl: Out[i] = hash(i) for 4 groups of 64 threads. */
|
||||
constexpr uint32_t kWords = 256;
|
||||
uint32_t expected_word(uint32_t i) {
|
||||
uint32_t v = i * 0x9E3779B1u;
|
||||
v ^= v >> 15;
|
||||
return v + 0x01234567u;
|
||||
}
|
||||
|
||||
void put32(std::vector<uint8_t>& out, size_t at, uint32_t value) { std::memcpy(out.data() + at, &value, 4); }
|
||||
|
||||
/* A DXBC container (version 1) holding one ACCC chunk with a BetterXen FSPX v1 table whose only
|
||||
* section is the stage configuration: compute, shader model 6.0. No DXIL. */
|
||||
std::vector<uint8_t> accc_only_container() {
|
||||
std::vector<uint8_t> fspx(40, 0);
|
||||
std::memcpy(fspx.data(), "FSPX", 4);
|
||||
put32(fspx, 4, 1); // version
|
||||
put32(fspx, 8, 1); // section count
|
||||
put32(fspx, 16, 1); // section id 1: stage configuration
|
||||
put32(fspx, 20, 28); // offset
|
||||
put32(fspx, 24, 12); // size
|
||||
put32(fspx, 28, 6); // stage: compute
|
||||
put32(fspx, 32, 6); // shader model 6.0
|
||||
put32(fspx, 36, 0);
|
||||
const uint32_t total = 32 + 4 + 8 + static_cast<uint32_t>(fspx.size());
|
||||
std::vector<uint8_t> out(total, 0);
|
||||
std::memcpy(out.data(), "DXBC", 4);
|
||||
put32(out, 20, 1);
|
||||
put32(out, 24, total);
|
||||
put32(out, 28, 1);
|
||||
put32(out, 32, 36);
|
||||
std::memcpy(out.data() + 36, "ACCC", 4);
|
||||
put32(out, 40, static_cast<uint32_t>(fspx.size()));
|
||||
std::memcpy(out.data() + 44, fspx.data(), fspx.size());
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string read_log() {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return {};
|
||||
std::string text;
|
||||
if (FILE* file = std::fopen(path, "rb")) {
|
||||
char buffer[4096];
|
||||
size_t got;
|
||||
while ((got = std::fread(buffer, 1, sizeof(buffer), file)) > 0) text.append(buffer, got);
|
||||
std::fclose(file);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/* True when one JSONL line holds every needle. */
|
||||
bool log_has(const std::string& log, std::initializer_list<const char*> needles) {
|
||||
size_t start = 0;
|
||||
while (start < log.size()) {
|
||||
size_t end = log.find('\n', start);
|
||||
if (end == std::string::npos) end = log.size();
|
||||
const std::string line = log.substr(start, end - start);
|
||||
bool all = true;
|
||||
for (const char* needle : needles) all = all && line.find(needle) != std::string::npos;
|
||||
if (all) return true;
|
||||
start = end + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
ID3D12RootSignature* make_root(ID3D12Device* device, const D3D12_ROOT_PARAMETER& param) {
|
||||
D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc = {};
|
||||
desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
|
||||
desc.Desc_1_0.NumParameters = 1;
|
||||
desc.Desc_1_0.pParameters = ¶m;
|
||||
ID3DBlob* blob = nullptr;
|
||||
ID3DBlob* error = nullptr;
|
||||
HRESULT hr = D3D12SerializeVersionedRootSignature(&desc, &blob, &error);
|
||||
if (error) error->Release();
|
||||
if (!check(SUCCEEDED(hr) && blob, "D3D12SerializeVersionedRootSignature hr=0x%08lx", ul(hr))) return nullptr;
|
||||
ID3D12RootSignature* root = nullptr;
|
||||
hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), __uuidof(ID3D12RootSignature),
|
||||
reinterpret_cast<void**>(&root));
|
||||
blob->Release();
|
||||
check(SUCCEEDED(hr) && root, "CreateRootSignature hr=0x%08lx", ul(hr));
|
||||
return root;
|
||||
}
|
||||
|
||||
ID3D12Resource* make_buffer(ID3D12Device* device, D3D12_HEAP_TYPE heap, D3D12_RESOURCE_FLAGS flags,
|
||||
D3D12_RESOURCE_STATES state) {
|
||||
D3D12_HEAP_PROPERTIES props = {};
|
||||
props.Type = heap;
|
||||
D3D12_RESOURCE_DESC desc = {};
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Width = kWords * 4;
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
desc.Flags = flags;
|
||||
ID3D12Resource* buffer = nullptr;
|
||||
const HRESULT hr = device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&buffer));
|
||||
check(SUCCEEDED(hr) && buffer, "CreateCommittedResource heap=%d hr=0x%08lx", static_cast<int>(heap), ul(hr));
|
||||
return buffer;
|
||||
}
|
||||
|
||||
HRESULT create_compute(ID3D12Device* device, ID3D12RootSignature* root, const void* code, size_t size,
|
||||
ID3D12PipelineState** pso) {
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC desc = {};
|
||||
desc.pRootSignature = root;
|
||||
desc.CS.pShaderBytecode = code;
|
||||
desc.CS.BytecodeLength = size;
|
||||
*pso = nullptr;
|
||||
return device->CreateComputePipelineState(&desc, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(pso));
|
||||
}
|
||||
|
||||
/* Runs fill_cs66 and checks every output word. */
|
||||
void run_dxil(ID3D12Device* device, ID3D12RootSignature* root, ID3D12PipelineState* pso) {
|
||||
D3D12_COMMAND_QUEUE_DESC queue_desc = {};
|
||||
queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
|
||||
ID3D12CommandQueue* queue = nullptr;
|
||||
ID3D12CommandAllocator* allocator = nullptr;
|
||||
ID3D12GraphicsCommandList* list = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
HRESULT hr = device->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&queue));
|
||||
if (!check(SUCCEEDED(hr), "CreateCommandQueue hr=0x%08lx", ul(hr))) return;
|
||||
hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
|
||||
reinterpret_cast<void**>(&allocator));
|
||||
if (check(SUCCEEDED(hr), "CreateCommandAllocator hr=0x%08lx", ul(hr))) {
|
||||
hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator, pso,
|
||||
__uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(&list));
|
||||
check(SUCCEEDED(hr), "CreateCommandList hr=0x%08lx", ul(hr));
|
||||
}
|
||||
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
|
||||
check(SUCCEEDED(hr), "CreateFence hr=0x%08lx", ul(hr));
|
||||
ID3D12Resource* out = make_buffer(device, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
|
||||
D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
|
||||
ID3D12Resource* readback =
|
||||
make_buffer(device, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
if (list && fence && out && readback) {
|
||||
list->SetComputeRootSignature(root);
|
||||
list->SetComputeRootUnorderedAccessView(0, out->GetGPUVirtualAddress());
|
||||
list->Dispatch(kWords / 64, 1, 1);
|
||||
D3D12_RESOURCE_BARRIER barrier = {};
|
||||
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
barrier.Transition.pResource = out;
|
||||
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
list->ResourceBarrier(1, &barrier);
|
||||
list->CopyResource(readback, out);
|
||||
hr = list->Close();
|
||||
check(SUCCEEDED(hr), "Close hr=0x%08lx", ul(hr));
|
||||
ID3D12CommandList* lists[] = {list};
|
||||
queue->ExecuteCommandLists(1, lists);
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
check(SUCCEEDED(queue->Signal(fence, 1)), "Signal");
|
||||
if (fence->GetCompletedValue() < 1) {
|
||||
check(SUCCEEDED(fence->SetEventOnCompletion(1, done)), "SetEventOnCompletion");
|
||||
check(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0, "fence did not complete within 10 s");
|
||||
}
|
||||
CloseHandle(done);
|
||||
check(fence->GetCompletedValue() != UINT64_MAX, "device removed (fence value UINT64_MAX)");
|
||||
|
||||
void* mapped = nullptr;
|
||||
D3D12_RANGE range = {0, kWords * 4};
|
||||
hr = readback->Map(0, &range, &mapped);
|
||||
if (check(SUCCEEDED(hr) && mapped, "Map hr=0x%08lx", ul(hr))) {
|
||||
const auto* words = static_cast<const uint32_t*>(mapped);
|
||||
uint32_t mismatched = 0, first = kWords;
|
||||
for (uint32_t i = 0; i < kWords; ++i) {
|
||||
if (words[i] != expected_word(i)) {
|
||||
if (!mismatched) first = i;
|
||||
++mismatched;
|
||||
}
|
||||
}
|
||||
check(mismatched == 0, "DXIL readback: %u of %u words wrong (first %u: got 0x%08x want 0x%08x)",
|
||||
mismatched, kWords, first, first < kWords ? words[first] : 0u,
|
||||
first < kWords ? expected_word(first) : 0u);
|
||||
D3D12_RANGE none = {0, 0};
|
||||
readback->Unmap(0, &none);
|
||||
if (!mismatched) std::printf("dxil: %u/%u words verified\n", kWords, kWords);
|
||||
}
|
||||
}
|
||||
if (readback) readback->Release();
|
||||
if (out) out->Release();
|
||||
if (fence) fence->Release();
|
||||
if (list) list->Release();
|
||||
if (allocator) allocator->Release();
|
||||
if (queue) queue->Release();
|
||||
}
|
||||
|
||||
std::wstring directory_of(const wchar_t* path) {
|
||||
const std::wstring text(path);
|
||||
return text.substr(0, text.find_last_of(L'\\'));
|
||||
}
|
||||
|
||||
/* --no-bridge: run from a directory that holds d3d12_xs.dll and its BetterXen imports but no
|
||||
* bx_shader_bridge.dll. DXIL must still run and ACCC-only must still be refused. */
|
||||
int no_bridge_main() {
|
||||
ID3D12Device* device = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (!check(SUCCEEDED(hr) && device, "no-bridge: D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) return finish();
|
||||
D3D12_ROOT_PARAMETER uav = {};
|
||||
uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
|
||||
uav.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
|
||||
ID3D12RootSignature* root = make_root(device, uav);
|
||||
if (!root) return finish();
|
||||
ID3D12PipelineState* pso = nullptr;
|
||||
hr = create_compute(device, root, g_fill_cs66, sizeof(g_fill_cs66), &pso);
|
||||
check(SUCCEEDED(hr) && pso, "no-bridge: DXIL CreateComputePipelineState hr=0x%08lx", ul(hr));
|
||||
if (pso) {
|
||||
run_dxil(device, root, pso);
|
||||
pso->Release();
|
||||
}
|
||||
check(GetModuleHandleW(L"bx_shader_bridge.dll") == nullptr, "no-bridge: a bx_shader_bridge.dll was loaded anyway");
|
||||
const std::vector<uint8_t> accc = accc_only_container();
|
||||
hr = create_compute(device, root, accc.data(), accc.size(), &pso);
|
||||
check(hr == E_NOTIMPL && !pso, "no-bridge: ACCC-only compute hr=0x%08lx (want E_NOTIMPL)", ul(hr));
|
||||
if (pso) pso->Release();
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics = {};
|
||||
graphics.pRootSignature = root;
|
||||
graphics.VS.pShaderBytecode = accc.data();
|
||||
graphics.VS.BytecodeLength = accc.size();
|
||||
graphics.SampleMask = UINT_MAX;
|
||||
graphics.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
|
||||
graphics.SampleDesc.Count = 1;
|
||||
hr = device->CreateGraphicsPipelineState(&graphics, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(&pso));
|
||||
check(hr == E_NOTIMPL && !pso, "no-bridge: ACCC-only graphics VS hr=0x%08lx (want E_NOTIMPL)", ul(hr));
|
||||
if (pso) pso->Release();
|
||||
root->Release();
|
||||
device->Release();
|
||||
return finish();
|
||||
}
|
||||
|
||||
/* Copies this EXE and d3d12_xs.dll's directory minus the bridge into a scratch directory, runs
|
||||
* the copy with --no-bridge, and requires it to pass. */
|
||||
void run_no_bridge_child() {
|
||||
wchar_t exe[MAX_PATH] = {}, shim[MAX_PATH] = {}, temp[MAX_PATH] = {};
|
||||
GetModuleFileNameW(nullptr, exe, MAX_PATH);
|
||||
GetModuleFileNameW(GetModuleHandleW(L"d3d12_xs.dll"), shim, MAX_PATH);
|
||||
GetTempPathW(MAX_PATH, temp);
|
||||
wchar_t dir[MAX_PATH];
|
||||
std::swprintf(dir, MAX_PATH, L"%lsbx_shader_gate_nobridge_%lu", temp, GetCurrentProcessId());
|
||||
if (!check(CreateDirectoryW(dir, nullptr) || GetLastError() == ERROR_ALREADY_EXISTS,
|
||||
"no-bridge: cannot create %ls", dir)) {
|
||||
return;
|
||||
}
|
||||
const std::wstring from = directory_of(shim);
|
||||
const std::wstring to(dir);
|
||||
const wchar_t* files[] = {L"d3d12_xs.dll", L"xmem.dll", L"bx_runtime_veh.dll"};
|
||||
bool copied = CopyFileW(exe, (to + L"\\test_shader_gate.exe").c_str(), FALSE) != 0;
|
||||
for (const wchar_t* name : files) {
|
||||
copied = copied && CopyFileW((from + L"\\" + name).c_str(), (to + L"\\" + name).c_str(), FALSE) != 0;
|
||||
}
|
||||
if (check(copied, "no-bridge: copying the shims to %ls failed (error %lu)", dir, GetLastError())) {
|
||||
std::wstring command = L"\"" + to + L"\\test_shader_gate.exe\" --no-bridge";
|
||||
STARTUPINFOW startup = {};
|
||||
startup.cb = sizeof(startup);
|
||||
PROCESS_INFORMATION child = {};
|
||||
if (check(CreateProcessW(nullptr, command.data(), nullptr, nullptr, FALSE, 0, nullptr, dir, &startup, &child),
|
||||
"no-bridge: CreateProcessW error %lu", GetLastError())) {
|
||||
DWORD code = 99;
|
||||
check(WaitForSingleObject(child.hProcess, 60000) == WAIT_OBJECT_0, "no-bridge: child did not finish in 60 s");
|
||||
GetExitCodeProcess(child.hProcess, &code);
|
||||
check(code == 0, "no-bridge: child exited %lu (a crash shows as an exception code)", code);
|
||||
CloseHandle(child.hThread);
|
||||
CloseHandle(child.hProcess);
|
||||
}
|
||||
}
|
||||
DeleteFileW((to + L"\\test_shader_gate.exe").c_str());
|
||||
for (const wchar_t* name : files) DeleteFileW((to + L"\\" + name).c_str());
|
||||
RemoveDirectoryW(dir);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
if (std::wcsstr(GetCommandLineW(), L" --no-bridge")) return no_bridge_main();
|
||||
|
||||
// Self-check of the reference against values computed independently for d3dmetal-harness.
|
||||
check(expected_word(0) == 0x01234567u && expected_word(1) == 0x9f598b46u && expected_word(255) == 0x9a664b32u,
|
||||
"expected_word reference values");
|
||||
|
||||
if (!check(GetEnvironmentVariableA("BX_LOG_FILE", nullptr, 0) > 0,
|
||||
"BX_LOG_FILE is not set; run through bx-cli run --log")) {
|
||||
return finish();
|
||||
}
|
||||
|
||||
ID3D12Device* device = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (!check(SUCCEEDED(hr) && device, "D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) return finish();
|
||||
|
||||
D3D12_ROOT_PARAMETER uav = {};
|
||||
uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
|
||||
uav.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
|
||||
ID3D12RootSignature* root_uav = make_root(device, uav);
|
||||
D3D12_DESCRIPTOR_RANGE range = {};
|
||||
range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
|
||||
range.NumDescriptors = 1;
|
||||
D3D12_ROOT_PARAMETER table = {};
|
||||
table.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
|
||||
table.DescriptorTable.NumDescriptorRanges = 1;
|
||||
table.DescriptorTable.pDescriptorRanges = ⦥
|
||||
table.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
|
||||
ID3D12RootSignature* root_table = make_root(device, table);
|
||||
if (!root_uav || !root_table) return finish();
|
||||
|
||||
// 1. DXIL passes the gate and runs.
|
||||
ID3D12PipelineState* pso = nullptr;
|
||||
hr = create_compute(device, root_uav, g_fill_cs66, sizeof(g_fill_cs66), &pso);
|
||||
check(SUCCEEDED(hr) && pso, "DXIL SM 6.6 CreateComputePipelineState hr=0x%08lx", ul(hr));
|
||||
const HMODULE bridge = GetModuleHandleW(L"bx_shader_bridge.dll");
|
||||
if (!check(bridge != nullptr,
|
||||
"bx_shader_bridge.dll was not loaded beside d3d12_xs.dll: scripts/build-shims.sh stages it in "
|
||||
"build-shims/bin (#484)")) {
|
||||
if (pso) pso->Release();
|
||||
return finish();
|
||||
}
|
||||
// The shim must find the bridge beside itself, not through the EXE's directory (crate README).
|
||||
wchar_t bridge_path[MAX_PATH] = {}, shim_path[MAX_PATH] = {};
|
||||
GetModuleFileNameW(bridge, bridge_path, MAX_PATH);
|
||||
GetModuleFileNameW(GetModuleHandleW(L"d3d12_xs.dll"), shim_path, MAX_PATH);
|
||||
const auto dir_of = [](std::wstring path) { return path.substr(0, path.find_last_of(L'\\')); };
|
||||
check(_wcsicmp(dir_of(bridge_path).c_str(), dir_of(shim_path).c_str()) == 0,
|
||||
"bx_shader_bridge.dll was loaded from %ls, not beside d3d12_xs.dll (%ls)", bridge_path, shim_path);
|
||||
if (pso) {
|
||||
run_dxil(device, root_uav, pso);
|
||||
pso->Release();
|
||||
}
|
||||
|
||||
// 2. An ACCC-only container is refused, for compute and graphics, without a host object.
|
||||
const std::vector<uint8_t> accc = accc_only_container();
|
||||
hr = create_compute(device, root_uav, accc.data(), accc.size(), &pso);
|
||||
check(hr == E_NOTIMPL && !pso, "ACCC-only compute PSO: hr=0x%08lx (want E_NOTIMPL) pso=%p", ul(hr),
|
||||
static_cast<void*>(pso));
|
||||
if (pso) pso->Release();
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics = {};
|
||||
graphics.pRootSignature = root_uav;
|
||||
graphics.VS.pShaderBytecode = accc.data();
|
||||
graphics.VS.BytecodeLength = accc.size();
|
||||
graphics.SampleMask = UINT_MAX;
|
||||
graphics.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
|
||||
graphics.SampleDesc.Count = 1;
|
||||
hr = device->CreateGraphicsPipelineState(&graphics, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(&pso));
|
||||
check(hr == E_NOTIMPL && !pso, "ACCC-only graphics VS: hr=0x%08lx (want E_NOTIMPL) pso=%p", ul(hr),
|
||||
static_cast<void*>(pso));
|
||||
if (pso) pso->Release();
|
||||
// The device is still usable after a refusal.
|
||||
hr = create_compute(device, root_uav, g_fill_cs66, sizeof(g_fill_cs66), &pso);
|
||||
check(SUCCEEDED(hr) && pso, "DXIL PSO after a refusal hr=0x%08lx", ul(hr));
|
||||
if (pso) pso->Release();
|
||||
|
||||
// 3. Constraint-carrying DXIL still passes; its constraints are logged (results not dispatched).
|
||||
hr = create_compute(device, root_uav, g_wave64_lanes_cs, sizeof(g_wave64_lanes_cs), &pso);
|
||||
std::printf("wave64 PSO hr=0x%08lx\n", ul(hr));
|
||||
if (pso) pso->Release();
|
||||
hr = create_compute(device, root_table, g_atomic64_image_cs, sizeof(g_atomic64_image_cs), &pso);
|
||||
std::printf("atomic64 typed PSO hr=0x%08lx\n", ul(hr));
|
||||
if (pso) pso->Release();
|
||||
|
||||
// 4. Without the bridge (a separate process from a directory without it).
|
||||
run_no_bridge_child();
|
||||
|
||||
// 5. The JSONL records.
|
||||
const std::string log = read_log();
|
||||
char fill_bytes[32];
|
||||
std::snprintf(fill_bytes, sizeof(fill_bytes), "bytes=%u ", static_cast<unsigned>(sizeof(g_fill_cs66)));
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=compute", "decision=pass_dxil", "kind=dxil", "sm=6.6",
|
||||
fill_bytes, "atomic64= ", "wave_lanes=0-4294967295"}),
|
||||
"shader_gate record for the DXIL SM 6.6 compute shader");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=compute", "decision=reject_accc_only", "hr=0x80004001",
|
||||
"kind=accc_only", "sm=6.0"}),
|
||||
"shader_gate record rejecting the ACCC-only compute shader");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=graphics", "stage=VS", "decision=reject_accc_only"}),
|
||||
"shader_gate record rejecting the ACCC-only vertex shader");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "decision=pass_dxil", "wave_ops=1", "wave_lanes=64-64"}),
|
||||
"shader_gate record with WaveSize(64)");
|
||||
check(log_has(log, {"\"event\":\"shader_d3dmetal_gap\"", "wave_lanes_min=64"}),
|
||||
"shader_d3dmetal_gap record for WaveSize(64)");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "decision=pass_dxil", "int64_ops=1", "atomic64=typed,"}),
|
||||
"shader_gate record with 64-bit typed atomics");
|
||||
check(log_has(log, {"\"event\":\"shader_d3dmetal_gap\"", "atomic64_flags=0x400000"}),
|
||||
"shader_d3dmetal_gap record for 64-bit typed atomics");
|
||||
check(log_has(log, {"\"event\":\"shader_bridge_missing\"", "not found beside d3d12_xs.dll"}),
|
||||
"shader_bridge_missing record from the no-bridge child");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=compute", "decision=reject_accc_only_unclassified",
|
||||
"hr=0x80004001"}),
|
||||
"no-bridge child refused the ACCC-only compute shader");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=graphics", "decision=reject_accc_only_unclassified"}),
|
||||
"no-bridge child refused the ACCC-only vertex shader");
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=compute", "decision=pass_unclassified"}),
|
||||
"no-bridge child passed DXIL unclassified");
|
||||
|
||||
root_table->Release();
|
||||
root_uav->Release();
|
||||
device->Release();
|
||||
return finish();
|
||||
}
|
||||
@@ -1,17 +1,23 @@
|
||||
/*
|
||||
* #457: clean-room synthetic test for system32 shim staging by `bx-cli run`.
|
||||
* #457 / #482: clean-room synthetic test for system32 shim staging by `bx-cli run`.
|
||||
*
|
||||
* GDK titles load the runtime with LoadLibraryExW(L"xgameruntime.dll", NULL,
|
||||
* GDK titles load `xgameruntime.dll` and `GameInput.dll` with LoadLibraryExW(...,
|
||||
* LOAD_LIBRARY_SEARCH_SYSTEM32), which does not search WINEPATH or the executable's folder.
|
||||
* This test makes that load and requires that BetterXen's shim answers it:
|
||||
* - the module loads, from a path under system32;
|
||||
* - it exports QueryApiImpl (a BetterXen xgameruntime export, absent from Wine builtins);
|
||||
* - LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR gives the same module.
|
||||
* In addition, Wine pre-populates `system32\gameinput.dll` with a builtin stub whose
|
||||
* `GameInputCreate` returns E_NOTIMPL.
|
||||
*
|
||||
* `--expect-missing` is the negative control for an unstaged prefix: the load must fail.
|
||||
* This test makes both loads and requires that BetterXen's shims answer them:
|
||||
* - xgameruntime.dll loads from system32, exports QueryApiImpl, and matches
|
||||
* LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR;
|
||||
* - GameInput.dll loads from system32, exports GameInputCreate (@1 and by name), and
|
||||
* GameInputCreate(&input) returns S_OK with a valid IUnknown pointer.
|
||||
*
|
||||
* `--expect-missing` is the negative control for an unstaged prefix: xgameruntime.dll must
|
||||
* fail to load, and GameInput.dll must either fail to load or fail GameInputCreate (Wine stub).
|
||||
* Exit 0 on pass, 1 on failure.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -33,13 +39,13 @@ bool check(bool ok, const char* what) {
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool path_in_system32(HMODULE m) {
|
||||
bool path_in_system32(HMODULE m, const wchar_t* needle) {
|
||||
wchar_t path[MAX_PATH * 2] = {};
|
||||
const DWORD n = GetModuleFileNameW(m, path, MAX_PATH * 2);
|
||||
if (n == 0 || n >= MAX_PATH * 2) return false;
|
||||
for (DWORD i = 0; i < n; ++i) path[i] = static_cast<wchar_t>(towlower(path[i]));
|
||||
std::printf("INFO: loaded from %ls\n", path);
|
||||
return std::wcsstr(path, L"\\windows\\system32\\xgameruntime.dll") != nullptr;
|
||||
return std::wcsstr(path, needle) != nullptr;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -49,16 +55,57 @@ int main(int argc, char** argv) {
|
||||
|
||||
HMODULE sys = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
if (expect_missing) {
|
||||
check(sys == nullptr, "unstaged: LOAD_LIBRARY_SEARCH_SYSTEM32 load fails");
|
||||
check(sys == nullptr, "unstaged: LOAD_LIBRARY_SEARCH_SYSTEM32 xgameruntime.dll load fails");
|
||||
if (sys) FreeLibrary(sys);
|
||||
} else if (check(sys != nullptr, "LOAD_LIBRARY_SEARCH_SYSTEM32 loads xgameruntime.dll")) {
|
||||
check(path_in_system32(sys), "module path is under system32");
|
||||
check(GetProcAddress(sys, "QueryApiImpl") != nullptr, "module exports QueryApiImpl (BetterXen shim)");
|
||||
HMODULE both = LoadLibraryExW(L"xgameruntime.dll", nullptr,
|
||||
LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR);
|
||||
check(both == sys, "SYSTEM32 | APPLICATION_DIR search returns the same module");
|
||||
if (both) FreeLibrary(both);
|
||||
FreeLibrary(sys);
|
||||
|
||||
HMODULE gi = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
bool gi_unusable = (gi == nullptr);
|
||||
if (gi) {
|
||||
using CreateFn = HRESULT (WINAPI*)(void**);
|
||||
auto fn = reinterpret_cast<CreateFn>(
|
||||
reinterpret_cast<void*>(GetProcAddress(gi, "GameInputCreate")));
|
||||
void* obj = nullptr;
|
||||
HRESULT hr = fn ? fn(&obj) : E_FAIL;
|
||||
if (SUCCEEDED(hr) && obj) {
|
||||
static_cast<IUnknown*>(obj)->Release();
|
||||
} else {
|
||||
gi_unusable = true;
|
||||
}
|
||||
FreeLibrary(gi);
|
||||
}
|
||||
check(gi_unusable, "unstaged: GameInput.dll is absent or Wine stub returns failure");
|
||||
} else {
|
||||
if (check(sys != nullptr, "LOAD_LIBRARY_SEARCH_SYSTEM32 loads xgameruntime.dll")) {
|
||||
check(path_in_system32(sys, L"\\windows\\system32\\xgameruntime.dll"),
|
||||
"xgameruntime.dll module path is under system32");
|
||||
check(GetProcAddress(sys, "QueryApiImpl") != nullptr,
|
||||
"module exports QueryApiImpl (BetterXen shim)");
|
||||
HMODULE both = LoadLibraryExW(
|
||||
L"xgameruntime.dll", nullptr,
|
||||
LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR);
|
||||
check(both == sys, "SYSTEM32 | APPLICATION_DIR search returns the same module");
|
||||
if (both) FreeLibrary(both);
|
||||
FreeLibrary(sys);
|
||||
}
|
||||
|
||||
HMODULE gi = LoadLibraryExW(L"GameInput.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
if (check(gi != nullptr, "LOAD_LIBRARY_SEARCH_SYSTEM32 loads GameInput.dll")) {
|
||||
check(path_in_system32(gi, L"\\windows\\system32\\gameinput.dll"),
|
||||
"GameInput.dll module path is under system32");
|
||||
FARPROC ord1 = GetProcAddress(gi, MAKEINTRESOURCEA(1));
|
||||
FARPROC named = GetProcAddress(gi, "GameInputCreate");
|
||||
check(ord1 != nullptr && ord1 == named,
|
||||
"GameInput.dll exports GameInputCreate at ordinal 1");
|
||||
using CreateFn = HRESULT (WINAPI*)(void**);
|
||||
auto create = reinterpret_cast<CreateFn>(reinterpret_cast<void*>(named));
|
||||
void* input = nullptr;
|
||||
HRESULT hr = create ? create(&input) : E_FAIL;
|
||||
if (check(hr == S_OK && input != nullptr,
|
||||
"GameInputCreate returns S_OK (BetterXen shim, not Wine builtin stub)")) {
|
||||
static_cast<IUnknown*>(input)->Release();
|
||||
}
|
||||
FreeLibrary(gi);
|
||||
}
|
||||
}
|
||||
std::printf("SUMMARY: %d checks, %d failed\n", g_checks, g_failures);
|
||||
return g_failures == 0 ? 0 : 1;
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_veh_amd_only main.cpp)
|
||||
target_include_directories(test_veh_amd_only PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_veh_amd_only PRIVATE bx_runtime_veh kernel32)
|
||||
@@ -0,0 +1,251 @@
|
||||
// Synthetic Windows x64 fixture for the Rosetta exception path. Expectations
|
||||
// come from the AMD APM vol. 3 (24594, rev. 3.36), CLZERO, MONITORX, MWAITX,
|
||||
// and RDPRU, and vol. 4 (26568, rev. 3.25), EXTRQ and INSERTQ.
|
||||
#include <windows.h>
|
||||
#include <cpuid.h>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
extern "C" uint64_t bx_veh_get_clwb_trap_count(void);
|
||||
|
||||
namespace {
|
||||
|
||||
unsigned failures = 0;
|
||||
unsigned checks = 0;
|
||||
|
||||
void expect(bool passed, const char* name) {
|
||||
++checks;
|
||||
if (passed) {
|
||||
std::printf("ok: %s\n", name);
|
||||
} else {
|
||||
std::fprintf(stderr, "FAIL: %s\n", name);
|
||||
++failures;
|
||||
}
|
||||
}
|
||||
|
||||
bool equals(const uint8_t* bytes, size_t count, uint8_t value) {
|
||||
for (size_t index = 0; index < count; ++index) {
|
||||
if (bytes[index] != value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void clzero(uintptr_t address) {
|
||||
__asm__ volatile(".byte 0x0f, 0x01, 0xfc" :: "a"(address) : "memory");
|
||||
}
|
||||
|
||||
void check_cache_lines() {
|
||||
alignas(64) uint8_t lines[192];
|
||||
std::memset(lines, 0xA5, sizeof(lines));
|
||||
clzero(reinterpret_cast<uintptr_t>(lines + 127));
|
||||
expect(equals(lines + 64, 64, 0), "CLZERO clears the selected 64 bytes");
|
||||
expect(equals(lines, 64, 0xA5) && equals(lines + 128, 64, 0xA5),
|
||||
"CLZERO preserves both adjacent cache lines");
|
||||
|
||||
std::memset(lines, 0xA5, sizeof(lines));
|
||||
__asm__ volatile(".byte 0x48, 0x0f, 0x01, 0xfc" :: "a"(lines + 79) : "memory");
|
||||
expect(equals(lines + 64, 64, 0) && equals(lines, 64, 0xA5) &&
|
||||
equals(lines + 128, 64, 0xA5), "CLZERO accepts a redundant REX.W");
|
||||
}
|
||||
|
||||
void check_address_override() {
|
||||
uint8_t* page = nullptr;
|
||||
for (uintptr_t address = 0x10000000; address < 0x70000000; address += 0x10000000) {
|
||||
page = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(address), 4096,
|
||||
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
if (page) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
expect(page != nullptr, "allocate a page below 4 GiB for address-size coverage");
|
||||
if (!page) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::memset(page, 0x6C, 192);
|
||||
const uint64_t address = 0x1234567800000000ULL | reinterpret_cast<uintptr_t>(page + 75);
|
||||
__asm__ volatile(".byte 0x67, 0x0f, 0x01, 0xfc" :: "a"(address) : "memory");
|
||||
expect(equals(page + 64, 64, 0) && equals(page, 64, 0x6C) && equals(page + 128, 64, 0x6C),
|
||||
"CLZERO address-size override selects EAX and resumes after four bytes");
|
||||
__asm__ volatile(".byte 0x67, 0x0f, 0x01, 0xfa"
|
||||
:: "a"(address), "c"(0), "d"(0) : "memory");
|
||||
expect(page[75] == 0, "MONITORX with an address-size override resumes after four bytes");
|
||||
VirtualFree(page, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
struct WriteFault {
|
||||
uint8_t* page = nullptr;
|
||||
unsigned hits = 0;
|
||||
DWORD code = 0;
|
||||
ULONG_PTR operation = 0;
|
||||
ULONG_PTR address = 0;
|
||||
};
|
||||
|
||||
WriteFault fault;
|
||||
|
||||
LONG CALLBACK retry_cache_line_store(EXCEPTION_POINTERS* pointers) {
|
||||
const EXCEPTION_RECORD& record = *pointers->ExceptionRecord;
|
||||
if (record.ExceptionCode != EXCEPTION_ACCESS_VIOLATION &&
|
||||
record.ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
++fault.hits;
|
||||
fault.code = record.ExceptionCode;
|
||||
if (record.NumberParameters >= 2) {
|
||||
fault.operation = record.ExceptionInformation[0];
|
||||
fault.address = record.ExceptionInformation[1];
|
||||
}
|
||||
|
||||
// Repair the page and retry at the original guest instruction.
|
||||
DWORD previous = 0;
|
||||
if (fault.hits == 1 && VirtualProtect(fault.page, 4096, PAGE_READWRITE, &previous)) {
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
void check_write_fault() {
|
||||
fault.page = static_cast<uint8_t*>(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE,
|
||||
PAGE_READWRITE));
|
||||
expect(fault.page != nullptr, "allocate the CLZERO write-fault page");
|
||||
if (!fault.page) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::memset(fault.page, 0xA5, 192);
|
||||
DWORD previous = 0;
|
||||
if (!VirtualProtect(fault.page, 4096, PAGE_READONLY, &previous)) {
|
||||
expect(false, "protect the CLZERO write-fault page");
|
||||
VirtualFree(fault.page, 0, MEM_RELEASE);
|
||||
return;
|
||||
}
|
||||
PVOID handler = AddVectoredExceptionHandler(0, retry_cache_line_store);
|
||||
expect(handler != nullptr, "install the guest write-fault handler");
|
||||
if (handler) {
|
||||
clzero(reinterpret_cast<uintptr_t>(fault.page + 99));
|
||||
RemoveVectoredExceptionHandler(handler);
|
||||
expect(fault.hits == 1 && fault.code == EXCEPTION_ACCESS_VIOLATION &&
|
||||
fault.operation == 1 && fault.address == reinterpret_cast<uintptr_t>(fault.page + 64),
|
||||
"CLZERO dispatches a write access violation at the cache-line address");
|
||||
expect(equals(fault.page + 64, 64, 0) && equals(fault.page, 64, 0xA5) &&
|
||||
equals(fault.page + 128, 64, 0xA5), "CLZERO retries after the guest repairs the page");
|
||||
}
|
||||
VirtualFree(fault.page, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
void check_wait_instructions() {
|
||||
alignas(64) uint64_t word = 0;
|
||||
__asm__ volatile(".byte 0x0f, 0x01, 0xfa" :: "a"(&word), "c"(0), "d"(0) : "memory");
|
||||
__asm__ volatile(".byte 0x0f, 0x01, 0xfb" :: "a"(0xF0), "b"(1024), "c"(2) : "memory");
|
||||
expect(word == 0, "MONITORX and MWAITX return and preserve the watched value");
|
||||
__asm__ volatile(".byte 0x48, 0x0f, 0x01, 0xfa"
|
||||
:: "a"(&word), "c"(0), "d"(0) : "memory");
|
||||
__asm__ volatile(".byte 0x48, 0x0f, 0x01, 0xfb"
|
||||
:: "a"(0xF0), "b"(1024), "c"(2) : "memory");
|
||||
expect(word == 0, "MONITORX and MWAITX also return with redundant REX.W");
|
||||
}
|
||||
|
||||
uint64_t read_processor_register(uint32_t selector) {
|
||||
uint64_t low;
|
||||
uint64_t high;
|
||||
__asm__ volatile(".byte 0x0f, 0x01, 0xfd" : "=a"(low), "=d"(high) : "c"(selector) : "cc");
|
||||
return (high << 32) | low;
|
||||
}
|
||||
|
||||
void check_processor_registers() {
|
||||
const uint64_t mperf = read_processor_register(0);
|
||||
const uint64_t aperf = read_processor_register(1);
|
||||
expect(mperf != 0 && read_processor_register(0) >= mperf, "RDPRU reports a plausible MPERF");
|
||||
expect(aperf != 0 && read_processor_register(1) >= aperf, "RDPRU reports a plausible APERF");
|
||||
expect(read_processor_register(UINT32_MAX) == 0, "RDPRU returns zero for an unknown selector");
|
||||
uint32_t low;
|
||||
uint32_t high;
|
||||
__asm__ volatile(".byte 0x48, 0x0f, 0x01, 0xfd"
|
||||
: "=a"(low), "=d"(high) : "c"(1) : "cc");
|
||||
expect((low | high) != 0, "RDPRU accepts a redundant REX.W");
|
||||
|
||||
uint64_t flags;
|
||||
__asm__ volatile("pushfq\n\t"
|
||||
"orq $0x8d5, (%%rsp)\n\t"
|
||||
"popfq\n\t"
|
||||
".byte 0x0f, 0x01, 0xfd\n\t"
|
||||
"pushfq\n\t"
|
||||
"popq %0"
|
||||
: "=r"(flags) : "c"(0) : "rax", "rdx", "cc", "memory");
|
||||
expect((flags & 0x8D4) == 0, "RDPRU clears the five flags specified by the APM");
|
||||
// CF has no specified value on hardware. Check the shim's choice when
|
||||
// CPUID Fn8000_0008 EBX[4] does not advertise native RDPRU.
|
||||
unsigned eax, ebx, ecx, edx;
|
||||
if (!__get_cpuid(0x80000008, &eax, &ebx, &ecx, &edx) || !(ebx & (1u << 4))) {
|
||||
expect((flags & 1) == 0, "emulated RDPRU clears CF");
|
||||
}
|
||||
}
|
||||
|
||||
struct Quadwords {
|
||||
uint64_t low;
|
||||
uint64_t high;
|
||||
};
|
||||
|
||||
// The upper result quadword is undefined and is outside the assertion.
|
||||
#define CHECK_SSE4A(dst, src, encoding, initial, field, expected, name) \
|
||||
do { \
|
||||
uint64_t result; \
|
||||
__asm__ volatile("movdqu %1, %%" dst "\n\t" \
|
||||
"movdqu %2, %%" src "\n\t" \
|
||||
".byte " encoding "\n\t" \
|
||||
"movq %%" dst ", %0" \
|
||||
: "=r"(result) : "m"(initial), "m"(field) : dst, src); \
|
||||
expect(result == (expected), name); \
|
||||
} while (false)
|
||||
|
||||
void check_bit_fields() {
|
||||
const Quadwords initial{0xA1B2C3D4E5F60718ULL, 0};
|
||||
// Extract [63:60] from the destination.
|
||||
const Quadwords extract_field{0x3C04, 0};
|
||||
// Insert source nibble 5 into [63:60], or low byte 0xB5 into [15:8].
|
||||
const Quadwords insert_field{0x9876543210FEDCB5ULL, 0x3C04};
|
||||
CHECK_SSE4A("xmm3", "xmm4", "0x66, 0x0f, 0x78, 0xc3, 12, 12", initial, extract_field, 0xF60,
|
||||
"EXTRQ immediate without REX uses the destination low quadword");
|
||||
CHECK_SSE4A("xmm3", "xmm4", "0x66, 0x0f, 0x79, 0xdc", initial, extract_field, 0xA,
|
||||
"EXTRQ register without REX reads the source low quadword");
|
||||
CHECK_SSE4A("xmm3", "xmm4", "0xf2, 0x0f, 0x78, 0xdc, 8, 8", initial, insert_field,
|
||||
0xA1B2C3D4E5F6B518ULL, "INSERTQ immediate without REX preserves surrounding bits");
|
||||
CHECK_SSE4A("xmm3", "xmm4", "0xf2, 0x0f, 0x79, 0xdc", initial, insert_field,
|
||||
0x51B2C3D4E5F60718ULL, "INSERTQ register without REX reads the source high quadword");
|
||||
CHECK_SSE4A("xmm11", "xmm12", "0x66, 0x49, 0x0f, 0x78, 0xc3, 12, 12",
|
||||
initial, extract_field, 0xF60,
|
||||
"EXTRQ immediate uses REX.B and ignores REX.W");
|
||||
CHECK_SSE4A("xmm11", "xmm12", "0x66, 0x45, 0x0f, 0x79, 0xdc", initial, extract_field, 0xA,
|
||||
"EXTRQ register reads the source low quadword");
|
||||
CHECK_SSE4A("xmm11", "xmm12", "0xf2, 0x45, 0x0f, 0x78, 0xdc, 8, 8", initial, insert_field,
|
||||
0xA1B2C3D4E5F6B518ULL, "INSERTQ immediate preserves bits outside the field");
|
||||
CHECK_SSE4A("xmm11", "xmm12", "0xf2, 0x4d, 0x0f, 0x79, 0xdc", initial, insert_field,
|
||||
0x51B2C3D4E5F60718ULL, "INSERTQ register reads the source high quadword");
|
||||
CHECK_SSE4A("xmm11", "xmm12", "0x66, 0x41, 0x0f, 0x78, 0xc3, 0, 0", initial, extract_field,
|
||||
0xA1B2C3D4E5F60718ULL, "EXTRQ length zero selects all 64 bits");
|
||||
CHECK_SSE4A("xmm11", "xmm12", "0xf2, 0x45, 0x0f, 0x78, 0xdc, 0, 0", initial, insert_field,
|
||||
0x9876543210FEDCB5ULL, "INSERTQ length zero replaces all 64 bits");
|
||||
}
|
||||
|
||||
#undef CHECK_SSE4A
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
// Keep the DLL import so that its VEH is installed before this fixture.
|
||||
(void)bx_veh_get_clwb_trap_count();
|
||||
check_cache_lines();
|
||||
check_address_override();
|
||||
check_write_fault();
|
||||
check_wait_instructions();
|
||||
check_processor_registers();
|
||||
check_bit_fields();
|
||||
|
||||
std::printf("%s: test_veh_amd_only (%u/%u checks)\n",
|
||||
failures ? "FAIL" : "PASS", checks - failures, checks);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
add_executable(test_xcrdapi main.cpp)
|
||||
target_include_directories(test_xcrdapi PRIVATE "${BX_ROOT_DIR}/shims/xcrdapi")
|
||||
target_link_libraries(test_xcrdapi PRIVATE xcrdapi kernel32 uuid)
|
||||
target_compile_definitions(test_xcrdapi PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_include_directories(test_xcrdapi PRIVATE "${BX_ROOT_DIR}/shims/xcrdapi" "${BX_ROOT_DIR}/shims/xcrdapi/dstorage")
|
||||
target_link_libraries(test_xcrdapi PRIVATE xcrdapi d3d12_xs kernel32 uuid)
|
||||
@@ -1,10 +1,15 @@
|
||||
#include "synthetic_storage.h"
|
||||
|
||||
// Public PC DirectStorage contract (SDK 1.4.0, MIT per file), vendored under shims/xcrdapi/dstorage.
|
||||
#include "dstorage_mingw.h"
|
||||
|
||||
#include <array>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
|
||||
|
||||
using namespace bx::storage;
|
||||
|
||||
#define CHECK(condition) \
|
||||
@@ -62,6 +67,820 @@ struct MockFence final : ID3D12Fence {
|
||||
}
|
||||
};
|
||||
|
||||
unsigned char pattern_byte(unsigned index) {
|
||||
return static_cast<unsigned char>(index * 17u + 3u);
|
||||
}
|
||||
|
||||
bool bytes_match(const unsigned char* got, const unsigned char* expected, unsigned count, const char* label) {
|
||||
for (unsigned i = 0; i < count; ++i) {
|
||||
if (got[i] == expected[i]) continue;
|
||||
std::fprintf(stderr, "xcrdapi: %s[%u]=0x%02x expected 0x%02x\n", label, i, got[i], expected[i]);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int map_fill(ID3D12Resource* resource, unsigned char value, unsigned count) {
|
||||
D3D12_RANGE no_read{0, 0};
|
||||
void* mapped = nullptr;
|
||||
const HRESULT hr = resource->Map(0, &no_read, &mapped);
|
||||
if (hr != S_OK || !mapped) {
|
||||
std::fprintf(stderr, "xcrdapi: Map(fill) hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
std::memset(mapped, value, count);
|
||||
resource->Unmap(0, nullptr);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int map_copy(ID3D12Resource* resource, unsigned char* dest, unsigned count) {
|
||||
D3D12_RANGE read{0, count};
|
||||
void* mapped = nullptr;
|
||||
const HRESULT hr = resource->Map(0, &read, &mapped);
|
||||
if (hr != S_OK || !mapped) {
|
||||
std::fprintf(stderr, "xcrdapi: Map(read) hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
std::memcpy(dest, mapped, count);
|
||||
D3D12_RANGE none{0, 0};
|
||||
resource->Unmap(0, &none);
|
||||
return 0;
|
||||
}
|
||||
|
||||
HRESULT create_buffer(ID3D12Device* device, D3D12_HEAP_TYPE heap, D3D12_RESOURCE_STATES state,
|
||||
UINT64 width, ID3D12Resource** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
D3D12_HEAP_PROPERTIES props{};
|
||||
props.Type = heap;
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Width = width;
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
return device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(out));
|
||||
}
|
||||
|
||||
void test_transition(ID3D12GraphicsCommandList* list, ID3D12Resource* resource,
|
||||
D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) {
|
||||
if (before == after) return;
|
||||
D3D12_RESOURCE_BARRIER barrier{};
|
||||
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
barrier.Transition.pResource = resource;
|
||||
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
barrier.Transition.StateBefore = before;
|
||||
barrier.Transition.StateAfter = after;
|
||||
list->ResourceBarrier(1, &barrier);
|
||||
}
|
||||
|
||||
int copy_region(ID3D12Resource* dst, UINT64 dst_offset, ID3D12Resource* src, UINT64 src_offset, UINT64 size,
|
||||
D3D12_RESOURCE_STATES dst_state, D3D12_RESOURCE_STATES dst_for_copy,
|
||||
D3D12_RESOURCE_STATES src_state, D3D12_RESOURCE_STATES src_for_copy) {
|
||||
Com<ID3D12Device> device;
|
||||
HRESULT hr = dst->GetDevice(__uuidof(ID3D12Device), device.out());
|
||||
if (hr != S_OK || !device.value) {
|
||||
std::fprintf(stderr, "xcrdapi: GetDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
D3D12_COMMAND_QUEUE_DESC queue_desc{};
|
||||
queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
|
||||
Com<ID3D12CommandQueue> queue;
|
||||
hr = device->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), queue.out());
|
||||
if (hr != S_OK || !queue.value) {
|
||||
std::fprintf(stderr, "xcrdapi: CreateCommandQueue hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
Com<ID3D12CommandAllocator> allocator;
|
||||
hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), allocator.out());
|
||||
if (hr != S_OK || !allocator.value) {
|
||||
std::fprintf(stderr, "xcrdapi: CreateCommandAllocator hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
Com<ID3D12GraphicsCommandList> list;
|
||||
hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.value, nullptr,
|
||||
__uuidof(ID3D12GraphicsCommandList), list.out());
|
||||
if (hr != S_OK || !list.value) {
|
||||
std::fprintf(stderr, "xcrdapi: CreateCommandList hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
test_transition(list.value, dst, dst_state, dst_for_copy);
|
||||
test_transition(list.value, src, src_state, src_for_copy);
|
||||
list->CopyBufferRegion(dst, dst_offset, src, src_offset, size);
|
||||
test_transition(list.value, dst, dst_for_copy, dst_state);
|
||||
test_transition(list.value, src, src_for_copy, src_state);
|
||||
hr = list->Close();
|
||||
if (hr != S_OK) {
|
||||
std::fprintf(stderr, "xcrdapi: command list Close hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
ID3D12CommandList* lists[] = {list.value};
|
||||
queue->ExecuteCommandLists(1, lists);
|
||||
Com<ID3D12Fence> fence;
|
||||
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), fence.out());
|
||||
if (hr != S_OK || !fence.value) {
|
||||
std::fprintf(stderr, "xcrdapi: CreateFence hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
hr = queue->Signal(fence.value, 1);
|
||||
if (hr != S_OK) {
|
||||
std::fprintf(stderr, "xcrdapi: Signal hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
Event done;
|
||||
if (!done.handle) return 1;
|
||||
hr = fence->SetEventOnCompletion(1, done.handle);
|
||||
if (hr != S_OK) {
|
||||
std::fprintf(stderr, "xcrdapi: SetEventOnCompletion hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
const DWORD waited = WaitForSingleObject(done.handle, 10000);
|
||||
if (waited != WAIT_OBJECT_0) {
|
||||
std::fprintf(stderr, "xcrdapi: copy wait=%lu\n", static_cast<unsigned long>(waited));
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int check_compressed_rejection(Factory* factory) {
|
||||
unsigned char source[4];
|
||||
std::memset(source, 0x11, sizeof(source));
|
||||
unsigned char unchanged[4];
|
||||
std::memset(unchanged, 0x3C, sizeof(unchanged));
|
||||
unsigned char dests[3][4];
|
||||
for (auto& dest : dests) std::memset(dest, 0x3C, 4);
|
||||
const UINT formats[] = {compression_lz, compression_bcpack, compression_gdeflate};
|
||||
|
||||
Com<Status> status;
|
||||
CHECK(factory->CreateStatusArray(3, status_iid, status.out()) == S_OK);
|
||||
Com<Queue> queue;
|
||||
CHECK(factory->CreateQueue(8, queue_iid, queue.out()) == S_OK);
|
||||
Event event;
|
||||
CHECK(event.handle);
|
||||
|
||||
for (UINT i = 0; i < 3; ++i) {
|
||||
Request request{nullptr, 0, source, dests[i], 4, formats[i]};
|
||||
CHECK(queue->EnqueueRequest(&request) == S_OK);
|
||||
CHECK(queue->EnqueueStatus(status.value, i) == S_OK);
|
||||
}
|
||||
CHECK(queue->EnqueueSetEvent(event.handle) == S_OK);
|
||||
CHECK(status->GetResult(0) == E_PENDING);
|
||||
CHECK(queue->Submit() == S_OK);
|
||||
CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0);
|
||||
|
||||
for (UINT i = 0; i < 3; ++i) {
|
||||
const HRESULT hr = status->GetResult(i);
|
||||
if (hr != E_NOTIMPL) {
|
||||
std::fprintf(stderr, "xcrdapi: compression %u hr=0x%08lx\n", i, static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
CHECK(bytes_match(dests[i], unchanged, 4, "compressed"));
|
||||
}
|
||||
ErrorRecord error{};
|
||||
CHECK(queue->RetrieveErrorRecord(&error) == S_OK);
|
||||
CHECK(error.failure_count == 3 && error.first_error == E_NOTIMPL);
|
||||
CHECK(queue->Close() == S_OK);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int check_batched_buffer_transfers(Factory* factory) {
|
||||
// Expected bytes come from pattern_byte, the same function that fills the file.
|
||||
// Two slices overlap on purpose: index 8 matches the later slice only when Submit
|
||||
// runs the requests in enqueue order.
|
||||
constexpr unsigned kBytes = 32;
|
||||
constexpr unsigned kFileBytes = 40;
|
||||
CHECK(pattern_byte(8) != pattern_byte(24));
|
||||
|
||||
unsigned char expect_mem[kBytes] = {};
|
||||
unsigned char expect_gpu[kBytes];
|
||||
std::memset(expect_gpu, 0xA5, kBytes);
|
||||
for (unsigned i = 0; i < 16; ++i) {
|
||||
expect_mem[i] = pattern_byte(i);
|
||||
expect_gpu[i] = pattern_byte(i);
|
||||
}
|
||||
for (unsigned i = 0; i < 16; ++i) {
|
||||
expect_mem[8 + i] = pattern_byte(24 + i);
|
||||
expect_gpu[8 + i] = pattern_byte(24 + i);
|
||||
}
|
||||
CHECK(expect_mem[8] == pattern_byte(24) && expect_mem[24] == 0);
|
||||
CHECK(expect_gpu[8] == pattern_byte(24) && expect_gpu[24] == 0xA5);
|
||||
|
||||
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
|
||||
Com<ID3D12Device> device;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), device.out());
|
||||
if (hr != S_OK || !device.value) {
|
||||
std::fprintf(stderr, "xcrdapi: D3D12XboxCreateDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
Com<ID3D12Resource> upload;
|
||||
Com<ID3D12Resource> gpu;
|
||||
Com<ID3D12Resource> readback;
|
||||
hr = create_buffer(device.value, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, kBytes, &upload.value);
|
||||
if (hr != S_OK || !upload.value) {
|
||||
std::fprintf(stderr, "xcrdapi: upload buffer hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
hr = create_buffer(device.value, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, kBytes, &gpu.value);
|
||||
if (hr != S_OK || !gpu.value) {
|
||||
std::fprintf(stderr, "xcrdapi: default buffer hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
hr = create_buffer(device.value, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, kBytes, &readback.value);
|
||||
if (hr != S_OK || !readback.value) {
|
||||
std::fprintf(stderr, "xcrdapi: readback buffer hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
hr = upload->GetHeapProperties(&heap, nullptr);
|
||||
if (hr != S_OK || heap.Type != D3D12_HEAP_TYPE_UPLOAD) {
|
||||
std::fprintf(stderr, "xcrdapi: upload heap hr=0x%08lx type=%d\n", static_cast<unsigned long>(hr), static_cast<int>(heap.Type));
|
||||
return 1;
|
||||
}
|
||||
hr = gpu->GetHeapProperties(&heap, nullptr);
|
||||
if (hr != S_OK || heap.Type != D3D12_HEAP_TYPE_DEFAULT) {
|
||||
std::fprintf(stderr, "xcrdapi: default heap hr=0x%08lx type=%d\n", static_cast<unsigned long>(hr), static_cast<int>(heap.Type));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (map_fill(upload.value, 0xA5, kBytes) != 0) return 1;
|
||||
if (copy_region(gpu.value, 0, upload.value, 0, kBytes,
|
||||
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_GENERIC_READ) != 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
unsigned char file_bytes[kFileBytes];
|
||||
for (unsigned i = 0; i < kFileBytes; ++i) file_bytes[i] = pattern_byte(i);
|
||||
TemporaryFile temporary;
|
||||
WCHAR directory[MAX_PATH];
|
||||
const DWORD directory_len = GetTempPathW(MAX_PATH, directory);
|
||||
CHECK(directory_len && directory_len < MAX_PATH);
|
||||
CHECK(GetTempFileNameW(directory, L"bxg", 0, temporary.name));
|
||||
const HANDLE writer = CreateFileW(temporary.name, GENERIC_WRITE, 0, nullptr, TRUNCATE_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
CHECK(writer != INVALID_HANDLE_VALUE);
|
||||
DWORD written = 0;
|
||||
const BOOL wrote = WriteFile(writer, file_bytes, kFileBytes, &written, nullptr);
|
||||
CloseHandle(writer);
|
||||
CHECK(wrote && written == kFileBytes);
|
||||
|
||||
Com<File> file;
|
||||
CHECK(factory->OpenFile(temporary.name, file_iid, file.out()) == S_OK);
|
||||
unsigned char memory[kBytes] = {};
|
||||
Com<Status> status;
|
||||
CHECK(factory->CreateStatusArray(6, status_iid, status.out()) == S_OK);
|
||||
Com<Queue> queue;
|
||||
CHECK(factory->CreateQueue(16, queue_iid, queue.out()) == S_OK);
|
||||
Event event;
|
||||
CHECK(event.handle);
|
||||
|
||||
Request requests[6] = {
|
||||
{file.value, 0, nullptr, memory, 16, compression_none},
|
||||
{file.value, 24, nullptr, memory + 8, 16, compression_none},
|
||||
{file.value, 0, nullptr, nullptr, 16, compression_none, upload.value, 0},
|
||||
{file.value, 24, nullptr, nullptr, 16, compression_none, upload.value, 8},
|
||||
{file.value, 0, nullptr, nullptr, 16, compression_none, gpu.value, 0},
|
||||
{file.value, 24, nullptr, nullptr, 16, compression_none, gpu.value, 8},
|
||||
};
|
||||
for (UINT i = 0; i < 6; ++i) {
|
||||
CHECK(queue->EnqueueRequest(&requests[i]) == S_OK);
|
||||
CHECK(queue->EnqueueStatus(status.value, i) == S_OK);
|
||||
}
|
||||
CHECK(queue->EnqueueSetEvent(event.handle) == S_OK);
|
||||
CHECK(status->GetResult(0) == E_PENDING);
|
||||
CHECK(WaitForSingleObject(event.handle, 0) == WAIT_TIMEOUT);
|
||||
unsigned char zeros[kBytes] = {};
|
||||
CHECK(bytes_match(memory, zeros, kBytes, "memory-before"));
|
||||
unsigned char upload_before[kBytes];
|
||||
if (map_copy(upload.value, upload_before, kBytes) != 0) return 1;
|
||||
for (unsigned i = 0; i < kBytes; ++i) CHECK(upload_before[i] == 0xA5);
|
||||
|
||||
CHECK(queue->Submit() == S_OK);
|
||||
CHECK(WaitForSingleObject(event.handle, 15000) == WAIT_OBJECT_0);
|
||||
for (UINT i = 0; i < 6; ++i) {
|
||||
const HRESULT slot = status->GetResult(i);
|
||||
if (slot != S_OK) {
|
||||
std::fprintf(stderr, "xcrdapi: batch status %u hr=0x%08lx\n", i, static_cast<unsigned long>(slot));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
CHECK(bytes_match(memory, expect_mem, kBytes, "memory"));
|
||||
unsigned char upload_got[kBytes];
|
||||
if (map_copy(upload.value, upload_got, kBytes) != 0) return 1;
|
||||
CHECK(bytes_match(upload_got, expect_gpu, kBytes, "upload"));
|
||||
|
||||
if (copy_region(readback.value, 0, gpu.value, 0, kBytes,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE) != 0) {
|
||||
return 1;
|
||||
}
|
||||
unsigned char gpu_got[kBytes];
|
||||
if (map_copy(readback.value, gpu_got, kBytes) != 0) return 1;
|
||||
CHECK(bytes_match(gpu_got, expect_gpu, kBytes, "default"));
|
||||
|
||||
ErrorRecord error{};
|
||||
CHECK(queue->RetrieveErrorRecord(&error) == S_OK && error.failure_count == 0);
|
||||
CHECK(queue->Close() == S_OK);
|
||||
|
||||
Com<Queue> rejected;
|
||||
CHECK(factory->CreateQueue(4, queue_iid, rejected.out()) == S_OK);
|
||||
Request both{nullptr, 0, memory, memory, 4, compression_none, upload.value, 0};
|
||||
CHECK(rejected->EnqueueRequest(&both) == E_INVALIDARG);
|
||||
Com<Status> rejected_status;
|
||||
CHECK(factory->CreateStatusArray(1, status_iid, rejected_status.out()) == S_OK);
|
||||
Request past{file.value, 0, nullptr, nullptr, 1, compression_none, upload.value, kBytes};
|
||||
CHECK(rejected->EnqueueRequest(&past) == S_OK);
|
||||
CHECK(rejected->EnqueueStatus(rejected_status.value, 0) == S_OK);
|
||||
CHECK(rejected->Submit() == S_OK);
|
||||
CHECK(rejected->Close() == S_OK);
|
||||
const HRESULT past_hr = rejected_status->GetResult(0);
|
||||
if (past_hr != E_INVALIDARG) {
|
||||
std::fprintf(stderr, "xcrdapi: past-end buffer hr=0x%08lx\n", static_cast<unsigned long>(past_hr));
|
||||
return 1;
|
||||
}
|
||||
unsigned char upload_after[kBytes];
|
||||
if (map_copy(upload.value, upload_after, kBytes) != 0) return 1;
|
||||
CHECK(bytes_match(upload_after, expect_gpu, kBytes, "upload-after-reject"));
|
||||
return 0;
|
||||
}
|
||||
|
||||
ULONG live_refs(IUnknown* object) {
|
||||
const ULONG held = object->AddRef();
|
||||
object->Release();
|
||||
return held - 1;
|
||||
}
|
||||
|
||||
// Proves the post-ExecuteCommandLists timeout path: with a 0 ms wait and the
|
||||
// copy queue held until that wait is decided, at least one request returns
|
||||
// HRESULT_FROM_WIN32(WAIT_TIMEOUT), the device is not removed, the shim still
|
||||
// holds the destination, and the destination bytes match after the GPU drains.
|
||||
int check_unconfirmed_staged_copy(Factory* factory) {
|
||||
constexpr unsigned kBytes = 16;
|
||||
constexpr int kAttempts = 4;
|
||||
const HRESULT kTimeout = HRESULT_FROM_WIN32(WAIT_TIMEOUT);
|
||||
|
||||
struct RestoreEnv {
|
||||
~RestoreEnv() {
|
||||
SetEnvironmentVariableW(L"BX_XCRDAPI_COPY_TIMEOUT_MS", nullptr);
|
||||
SetEnvironmentVariableW(L"BX_XCRDAPI_DEFER_COPY", nullptr);
|
||||
}
|
||||
} restore_env;
|
||||
CHECK(SetEnvironmentVariableW(L"BX_XCRDAPI_COPY_TIMEOUT_MS", L"0"));
|
||||
CHECK(SetEnvironmentVariableW(L"BX_XCRDAPI_DEFER_COPY", L"1"));
|
||||
|
||||
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
|
||||
Com<ID3D12Device> device;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), device.out());
|
||||
if (hr != S_OK || !device.value) {
|
||||
std::fprintf(stderr, "xcrdapi: unconfirmed D3D12XboxCreateDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
Com<ID3D12Resource> upload;
|
||||
Com<ID3D12Resource> readback;
|
||||
hr = create_buffer(device.value, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, kBytes, &upload.value);
|
||||
if (hr != S_OK || !upload.value) {
|
||||
std::fprintf(stderr, "xcrdapi: unconfirmed upload hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
hr = create_buffer(device.value, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, kBytes, &readback.value);
|
||||
if (hr != S_OK || !readback.value) {
|
||||
std::fprintf(stderr, "xcrdapi: unconfirmed readback hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
if (map_fill(upload.value, 0x5A, kBytes) != 0) return 1;
|
||||
|
||||
unsigned char file_bytes[kBytes];
|
||||
unsigned char expect[kBytes];
|
||||
for (unsigned i = 0; i < kBytes; ++i) {
|
||||
file_bytes[i] = pattern_byte(i);
|
||||
expect[i] = pattern_byte(i);
|
||||
}
|
||||
CHECK(expect[0] != 0x5A);
|
||||
TemporaryFile temporary;
|
||||
WCHAR directory[MAX_PATH];
|
||||
const DWORD directory_len = GetTempPathW(MAX_PATH, directory);
|
||||
CHECK(directory_len && directory_len < MAX_PATH);
|
||||
CHECK(GetTempFileNameW(directory, L"bxu", 0, temporary.name));
|
||||
const HANDLE writer = CreateFileW(temporary.name, GENERIC_WRITE, 0, nullptr, TRUNCATE_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
CHECK(writer != INVALID_HANDLE_VALUE);
|
||||
DWORD written = 0;
|
||||
const BOOL wrote = WriteFile(writer, file_bytes, kBytes, &written, nullptr);
|
||||
CloseHandle(writer);
|
||||
CHECK(wrote && written == kBytes);
|
||||
Com<File> file;
|
||||
CHECK(factory->OpenFile(temporary.name, file_iid, file.out()) == S_OK);
|
||||
|
||||
HRESULT last_hr = E_FAIL;
|
||||
ULONG last_before = 0;
|
||||
ULONG last_after = 0;
|
||||
for (int attempt = 0; attempt < kAttempts; ++attempt) {
|
||||
Com<ID3D12Resource> dest;
|
||||
hr = create_buffer(device.value, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, kBytes, &dest.value);
|
||||
if (hr != S_OK || !dest.value) {
|
||||
std::fprintf(stderr, "xcrdapi: unconfirmed dest hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
hr = dest->GetHeapProperties(&heap, nullptr);
|
||||
if (hr != S_OK || heap.Type != D3D12_HEAP_TYPE_DEFAULT) {
|
||||
std::fprintf(stderr, "xcrdapi: unconfirmed heap hr=0x%08lx type=%d\n",
|
||||
static_cast<unsigned long>(hr), static_cast<int>(heap.Type));
|
||||
return 1;
|
||||
}
|
||||
if (copy_region(dest.value, 0, upload.value, 0, kBytes,
|
||||
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_STATE_GENERIC_READ) != 0) {
|
||||
return 1;
|
||||
}
|
||||
const ULONG before = live_refs(dest.value);
|
||||
const HRESULT removed_before = device->GetDeviceRemovedReason();
|
||||
if (removed_before != S_OK) {
|
||||
std::fprintf(stderr, "xcrdapi: device removed before unconfirmed copy hr=0x%08lx\n",
|
||||
static_cast<unsigned long>(removed_before));
|
||||
return 1;
|
||||
}
|
||||
|
||||
Com<Status> status;
|
||||
CHECK(factory->CreateStatusArray(1, status_iid, status.out()) == S_OK);
|
||||
Com<Queue> queue;
|
||||
CHECK(factory->CreateQueue(4, queue_iid, queue.out()) == S_OK);
|
||||
Event event;
|
||||
CHECK(event.handle);
|
||||
Request request{file.value, 0, nullptr, nullptr, kBytes, compression_none, dest.value, 0};
|
||||
CHECK(queue->EnqueueRequest(&request) == S_OK);
|
||||
CHECK(queue->EnqueueStatus(status.value, 0) == S_OK);
|
||||
CHECK(queue->EnqueueSetEvent(event.handle) == S_OK);
|
||||
CHECK(queue->Submit() == S_OK);
|
||||
CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0);
|
||||
CHECK(queue->Close() == S_OK);
|
||||
|
||||
last_hr = status->GetResult(0);
|
||||
last_before = before;
|
||||
last_after = live_refs(dest.value);
|
||||
const HRESULT removed = device->GetDeviceRemovedReason();
|
||||
if (removed != S_OK) {
|
||||
std::fprintf(stderr, "xcrdapi: device removed during unconfirmed copy hr=0x%08lx\n",
|
||||
static_cast<unsigned long>(removed));
|
||||
return 1;
|
||||
}
|
||||
// In-flight driver references can sit on top of the shim's hold. The
|
||||
// count after the GPU drains is the one that has to be exactly one
|
||||
// above the pre-request count.
|
||||
if (last_hr != kTimeout || last_after < before + 1) continue;
|
||||
|
||||
ErrorRecord error{};
|
||||
CHECK(queue->RetrieveErrorRecord(&error) == S_OK);
|
||||
if (error.failure_count != 1 || error.first_error != kTimeout) {
|
||||
std::fprintf(stderr, "xcrdapi: unconfirmed error record count=%llu hr=0x%08lx\n",
|
||||
static_cast<unsigned long long>(error.failure_count),
|
||||
static_cast<unsigned long>(error.first_error));
|
||||
return 1;
|
||||
}
|
||||
|
||||
bool bytes_ok = false;
|
||||
unsigned char got[kBytes];
|
||||
for (int spin = 0; spin < 8 && !bytes_ok; ++spin) {
|
||||
Sleep(spin == 0 ? 200 : 100);
|
||||
if (device->GetDeviceRemovedReason() != S_OK) break;
|
||||
if (copy_region(readback.value, 0, dest.value, 0, kBytes,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE) != 0) {
|
||||
return 1;
|
||||
}
|
||||
if (map_copy(readback.value, got, kBytes) != 0) return 1;
|
||||
bytes_ok = true;
|
||||
for (unsigned i = 0; i < kBytes; ++i) {
|
||||
if (got[i] != expect[i]) bytes_ok = false;
|
||||
}
|
||||
if (!bytes_ok && spin == 7) bytes_match(got, expect, kBytes, "unconfirmed");
|
||||
}
|
||||
if (!bytes_ok) return 1;
|
||||
const HRESULT removed_after = device->GetDeviceRemovedReason();
|
||||
const ULONG still_held = live_refs(dest.value);
|
||||
if (removed_after != S_OK || still_held != before + 1) {
|
||||
std::fprintf(stderr, "xcrdapi: after drain removed=0x%08lx refs=%lu expected=%lu (at timeout %lu)\n",
|
||||
static_cast<unsigned long>(removed_after),
|
||||
static_cast<unsigned long>(still_held),
|
||||
static_cast<unsigned long>(before + 1),
|
||||
static_cast<unsigned long>(last_after));
|
||||
return 1;
|
||||
}
|
||||
std::printf("test_xcrdapi: unconfirmed copy attempt=%d hr=0x%08lx refs %lu -> %lu device_removed=0x%08lx bytes=%u\n",
|
||||
attempt,
|
||||
static_cast<unsigned long>(last_hr),
|
||||
static_cast<unsigned long>(before),
|
||||
static_cast<unsigned long>(still_held),
|
||||
static_cast<unsigned long>(removed_after),
|
||||
kBytes);
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::fprintf(stderr, "xcrdapi: unconfirmed path not observed in %d attempts (last hr=0x%08lx refs %lu -> %lu)\n",
|
||||
kAttempts, static_cast<unsigned long>(last_hr),
|
||||
static_cast<unsigned long>(last_before), static_cast<unsigned long>(last_after));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Public PC DirectStorage interfaces. Expected values come from the documentation
|
||||
// comments in dstorage.h 1.4.0, not from the shim: capacity limits, "capacity - 1"
|
||||
// empty slots, automatic submission at half capacity, IsComplete == (GetHResult !=
|
||||
// E_PENDING), status entries scoped to the requests since the previous one, and the
|
||||
// E_DSTORAGE_* codes in dstorageerr.h. Where the header is silent (unsupported
|
||||
// destinations and compression), the expected E_NOTIMPL is BetterXen's documented choice.
|
||||
struct ForeignStatusArray final : IDStorageStatusArray {
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) override { return E_NOINTERFACE; }
|
||||
ULONG STDMETHODCALLTYPE AddRef() override { return 1; }
|
||||
ULONG STDMETHODCALLTYPE Release() override { return 1; }
|
||||
bool STDMETHODCALLTYPE IsComplete(UINT32) override { return true; }
|
||||
HRESULT STDMETHODCALLTYPE GetHResult(UINT32) override { return S_OK; }
|
||||
};
|
||||
|
||||
DSTORAGE_REQUEST file_to_memory(IDStorageFile* file, UINT64 offset, void* dest, UINT32 size) {
|
||||
DSTORAGE_REQUEST request{};
|
||||
request.Options.SourceType = DSTORAGE_REQUEST_SOURCE_FILE;
|
||||
request.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_MEMORY;
|
||||
request.Source.File.Source = file;
|
||||
request.Source.File.Offset = offset;
|
||||
request.Source.File.Size = size;
|
||||
request.Destination.Memory.Buffer = dest;
|
||||
request.Destination.Memory.Size = size;
|
||||
return request;
|
||||
}
|
||||
|
||||
DSTORAGE_REQUEST memory_to_memory(const void* source, void* dest, UINT32 size) {
|
||||
DSTORAGE_REQUEST request{};
|
||||
request.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
|
||||
request.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_MEMORY;
|
||||
request.Source.Memory.Source = source;
|
||||
request.Source.Memory.Size = size;
|
||||
request.Destination.Memory.Buffer = dest;
|
||||
request.Destination.Memory.Size = size;
|
||||
return request;
|
||||
}
|
||||
|
||||
int check_public_interfaces(const WCHAR* path, const char* contents) {
|
||||
// The generated MinGW IID declarations must match values typed independently from
|
||||
// Silk.NET's IDStorageFactory binding and the #483 issue text, not from dstorage_mingw.h.
|
||||
const IID typed_factory{0x6924ea0c, 0xc3cd, 0x4826, {0xb1, 0x0a, 0xf6, 0x4f, 0x4e, 0xd9, 0x27, 0xc1}};
|
||||
CHECK(IsEqualIID(__uuidof(IDStorageFactory), typed_factory));
|
||||
|
||||
// Factory: public IIDs are served, an unknown IID is refused with ppv cleared.
|
||||
const IID unknown_iid{0x0badf00d, 0x1234, 0x4abc, {0x80, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}};
|
||||
void* refused = reinterpret_cast<void*>(1);
|
||||
CHECK(DStorageGetFactory(unknown_iid, &refused) == E_NOINTERFACE && !refused);
|
||||
Com<IDStorageFactory> factory;
|
||||
CHECK(DStorageGetFactory(__uuidof(IDStorageFactory), factory.out()) == S_OK && factory.value);
|
||||
Com<IDStorageFactory1> factory1;
|
||||
CHECK(factory->QueryInterface(__uuidof(IDStorageFactory1), factory1.out()) == S_OK);
|
||||
Com<IUnknown> identity;
|
||||
CHECK(factory->QueryInterface(IID_IUnknown, identity.out()) == S_OK);
|
||||
Com<IUnknown> identity1;
|
||||
CHECK(factory1->QueryInterface(IID_IUnknown, identity1.out()) == S_OK && identity.value == identity1.value);
|
||||
Com<IDStorageFactory1> direct1;
|
||||
CHECK(DStorageGetFactory(__uuidof(IDStorageFactory1), direct1.out()) == S_OK && direct1.value);
|
||||
CHECK(factory->SetStagingBufferSize(DSTORAGE_STAGING_BUFFER_SIZE_32MB) == S_OK);
|
||||
|
||||
// Queue creation limits: DSTORAGE_MIN/MAX_QUEUE_CAPACITY and DSTORAGE_PRIORITY range.
|
||||
DSTORAGE_QUEUE_DESC desc{};
|
||||
desc.SourceType = DSTORAGE_REQUEST_SOURCE_FILE;
|
||||
desc.Capacity = DSTORAGE_MIN_QUEUE_CAPACITY;
|
||||
desc.Priority = DSTORAGE_PRIORITY_NORMAL;
|
||||
desc.Name = "bx file queue";
|
||||
void* bad_queue = reinterpret_cast<void*>(1);
|
||||
DSTORAGE_QUEUE_DESC bad = desc;
|
||||
bad.Capacity = DSTORAGE_MIN_QUEUE_CAPACITY - 1;
|
||||
CHECK(factory->CreateQueue(&bad, __uuidof(IDStorageQueue), &bad_queue) == E_DSTORAGE_INVALID_QUEUE_CAPACITY
|
||||
&& !bad_queue);
|
||||
bad.Capacity = DSTORAGE_MAX_QUEUE_CAPACITY + 1;
|
||||
CHECK(factory->CreateQueue(&bad, __uuidof(IDStorageQueue), &bad_queue) == E_DSTORAGE_INVALID_QUEUE_CAPACITY);
|
||||
bad = desc;
|
||||
bad.Priority = static_cast<DSTORAGE_PRIORITY>(DSTORAGE_PRIORITY_LAST + 1);
|
||||
CHECK(factory->CreateQueue(&bad, __uuidof(IDStorageQueue), &bad_queue) == E_DSTORAGE_INVALID_QUEUE_PRIORITY);
|
||||
|
||||
Com<IDStorageFile> file;
|
||||
CHECK(factory->OpenFile(path, __uuidof(IDStorageFile), file.out()) == S_OK);
|
||||
BY_HANDLE_FILE_INFORMATION file_info{};
|
||||
CHECK(file->GetFileInformation(&file_info) == S_OK && file_info.nFileSizeLow == std::strlen(contents) + 1);
|
||||
Com<IDStorageStatusArray> status;
|
||||
CHECK(factory->CreateStatusArray(4, "bx status", __uuidof(IDStorageStatusArray), status.out()) == S_OK);
|
||||
|
||||
Com<IDStorageQueue> queue;
|
||||
CHECK(factory->CreateQueue(&desc, __uuidof(IDStorageQueue), queue.out()) == S_OK);
|
||||
Com<IDStorageQueue4> queue4;
|
||||
CHECK(queue->QueryInterface(__uuidof(IDStorageQueue4), queue4.out()) == S_OK);
|
||||
DSTORAGE_QUEUE_INFO info{};
|
||||
queue->Query(&info);
|
||||
CHECK(info.Desc.Capacity == DSTORAGE_MIN_QUEUE_CAPACITY && info.Desc.SourceType == DSTORAGE_REQUEST_SOURCE_FILE);
|
||||
CHECK(info.Desc.Name && std::strcmp(info.Desc.Name, "bx file queue") == 0);
|
||||
CHECK(info.EmptySlotCount == DSTORAGE_MIN_QUEUE_CAPACITY - 1);
|
||||
CHECK(info.RequestCountUntilAutoSubmit == DSTORAGE_MIN_QUEUE_CAPACITY / 2);
|
||||
CHECK(queue4->GetCompressionSupport(DSTORAGE_COMPRESSION_FORMAT_GDEFLATE) == DSTORAGE_COMPRESSION_SUPPORT_NONE);
|
||||
|
||||
// Two file reads, a status entry and an event; nothing runs before Submit.
|
||||
std::array<char, 5> first{}, second{};
|
||||
Event done;
|
||||
CHECK(done.handle);
|
||||
DSTORAGE_REQUEST read1 = file_to_memory(file.value, 2, first.data(), 4);
|
||||
DSTORAGE_REQUEST read2 = file_to_memory(file.value, 10, second.data(), 4);
|
||||
queue->EnqueueRequest(&read1);
|
||||
queue->EnqueueRequest(&read2);
|
||||
queue->EnqueueStatus(status.value, 0);
|
||||
queue4->EnqueueSetEvent(done.handle);
|
||||
DSTORAGE_QUEUE_INFO1 info1{};
|
||||
queue4->Query1(&info1);
|
||||
CHECK(info1.EmptySlotCount == DSTORAGE_MIN_QUEUE_CAPACITY - 1 - 4);
|
||||
CHECK(info1.RequestCountUntilAutoSubmit == DSTORAGE_MIN_QUEUE_CAPACITY / 2 - 4);
|
||||
CHECK(!status->IsComplete(0) && status->GetHResult(0) == E_PENDING);
|
||||
queue->Submit();
|
||||
CHECK(WaitForSingleObject(done.handle, 5000) == WAIT_OBJECT_0);
|
||||
CHECK(status->IsComplete(0) && status->GetHResult(0) == S_OK);
|
||||
CHECK(std::memcmp(first.data(), contents + 2, 4) == 0 && std::memcmp(second.data(), contents + 10, 4) == 0);
|
||||
|
||||
// Rejected requests are reported in queue order, scoped by status entries.
|
||||
const HANDLE error_event = queue->GetErrorEvent();
|
||||
CHECK(error_event && WaitForSingleObject(error_event, 0) == WAIT_TIMEOUT);
|
||||
std::array<char, 5> scratch{}, third{};
|
||||
DSTORAGE_REQUEST reserved = file_to_memory(file.value, 0, scratch.data(), 4);
|
||||
reserved.Options.Reserved1[0] = 1;
|
||||
const char memory_source[4] = {'w', 'x', 'y', 'z'};
|
||||
DSTORAGE_REQUEST wrong_source = memory_to_memory(memory_source, scratch.data(), 4);
|
||||
DSTORAGE_REQUEST read3 = file_to_memory(file.value, 4, third.data(), 4);
|
||||
queue->EnqueueRequest(&reserved);
|
||||
queue->EnqueueRequest(&wrong_source);
|
||||
queue->EnqueueStatus(status.value, 1);
|
||||
queue->EnqueueRequest(&read3);
|
||||
queue->EnqueueStatus(status.value, 2);
|
||||
queue4->EnqueueSetEvent(done.handle);
|
||||
queue->Submit();
|
||||
CHECK(WaitForSingleObject(done.handle, 5000) == WAIT_OBJECT_0);
|
||||
CHECK(status->GetHResult(1) == E_DSTORAGE_RESERVED_FIELDS);
|
||||
CHECK(status->GetHResult(2) == S_OK && std::memcmp(third.data(), contents + 4, 4) == 0);
|
||||
CHECK(scratch[0] == 0);
|
||||
CHECK(WaitForSingleObject(error_event, 0) == WAIT_OBJECT_0);
|
||||
DSTORAGE_ERROR_RECORD record{};
|
||||
queue->RetrieveErrorRecord(&record);
|
||||
CHECK(record.FailureCount == 2 && record.FirstFailure.HResult == E_DSTORAGE_RESERVED_FIELDS);
|
||||
CHECK(record.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_REQUEST);
|
||||
queue->RetrieveErrorRecord(&record);
|
||||
CHECK(record.FailureCount == 0 && record.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_NONE);
|
||||
|
||||
// A foreign status array and a null fence are rejected without poisoning the next status.
|
||||
ForeignStatusArray foreign;
|
||||
queue->EnqueueStatus(&foreign, 0);
|
||||
queue->EnqueueSignal(nullptr, 1);
|
||||
queue->EnqueueStatus(status.value, 3);
|
||||
queue4->EnqueueSetEvent(done.handle);
|
||||
queue->Submit();
|
||||
CHECK(WaitForSingleObject(done.handle, 5000) == WAIT_OBJECT_0);
|
||||
CHECK(status->GetHResult(3) == S_OK);
|
||||
queue->RetrieveErrorRecord(&record);
|
||||
CHECK(record.FailureCount == 2 && record.FirstFailure.HResult == E_DSTORAGE_INVALID_STATUS_ARRAY);
|
||||
CHECK(record.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_STATUS);
|
||||
|
||||
// Unsupported shapes on a memory queue without a device: each is its own status scope.
|
||||
DSTORAGE_QUEUE_DESC memory_desc = desc;
|
||||
memory_desc.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
|
||||
memory_desc.Name = nullptr;
|
||||
Com<IDStorageQueue1> memory_queue;
|
||||
CHECK(factory->CreateQueue(&memory_desc, __uuidof(IDStorageQueue1), memory_queue.out()) == S_OK);
|
||||
Com<IDStorageStatusArray> shapes;
|
||||
CHECK(factory->CreateStatusArray(4, nullptr, __uuidof(IDStorageStatusArray), shapes.out()) == S_OK);
|
||||
unsigned char untouched[4] = {0x5A, 0x5A, 0x5A, 0x5A};
|
||||
DSTORAGE_REQUEST buffer_without_device = memory_to_memory(memory_source, untouched, 4);
|
||||
buffer_without_device.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_BUFFER;
|
||||
buffer_without_device.Destination.Buffer.Resource = nullptr;
|
||||
buffer_without_device.Destination.Buffer.Offset = 0;
|
||||
buffer_without_device.Destination.Buffer.Size = 4;
|
||||
DSTORAGE_REQUEST texture = memory_to_memory(memory_source, untouched, 4);
|
||||
texture.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_TEXTURE_REGION;
|
||||
DSTORAGE_REQUEST zstd = memory_to_memory(memory_source, untouched, 4);
|
||||
zstd.Options.CompressionFormat = DSTORAGE_COMPRESSION_FORMAT_ZSTD;
|
||||
DSTORAGE_REQUEST short_destination = memory_to_memory(memory_source, untouched, 4);
|
||||
short_destination.Destination.Memory.Size = 3;
|
||||
const DSTORAGE_REQUEST* shaped[] = {&buffer_without_device, &texture, &zstd, &short_destination};
|
||||
const HRESULT expected[] = {E_DSTORAGE_INVALID_DESTINATION_TYPE, E_NOTIMPL, E_NOTIMPL,
|
||||
E_DSTORAGE_INVALID_DESTINATION_SIZE};
|
||||
for (UINT i = 0; i < 4; ++i) {
|
||||
memory_queue->EnqueueRequest(shaped[i]);
|
||||
memory_queue->EnqueueStatus(shapes.value, i);
|
||||
}
|
||||
memory_queue->EnqueueSetEvent(done.handle);
|
||||
memory_queue->Submit();
|
||||
CHECK(WaitForSingleObject(done.handle, 5000) == WAIT_OBJECT_0);
|
||||
for (UINT i = 0; i < 4; ++i) {
|
||||
const HRESULT hr = shapes->GetHResult(i);
|
||||
if (hr != expected[i]) {
|
||||
std::fprintf(stderr, "xcrdapi: public shape %u hr=0x%08lx expected 0x%08lx\n", i,
|
||||
static_cast<unsigned long>(hr), static_cast<unsigned long>(expected[i]));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
CHECK(untouched[0] == 0x5A && untouched[3] == 0x5A);
|
||||
|
||||
// Half capacity triggers submission: the event is the 64th entry, and Submit is never called.
|
||||
constexpr UINT kAuto = DSTORAGE_MIN_QUEUE_CAPACITY / 2;
|
||||
static unsigned char auto_dest[kAuto - 1][4];
|
||||
std::memset(auto_dest, 0, sizeof(auto_dest));
|
||||
for (UINT i = 0; i + 1 < kAuto; ++i) {
|
||||
DSTORAGE_REQUEST copy = memory_to_memory(memory_source, auto_dest[i], 4);
|
||||
memory_queue->EnqueueRequest(©);
|
||||
}
|
||||
memory_queue->EnqueueSetEvent(done.handle);
|
||||
CHECK(WaitForSingleObject(done.handle, 5000) == WAIT_OBJECT_0);
|
||||
for (UINT i = 0; i + 1 < kAuto; ++i) CHECK(std::memcmp(auto_dest[i], memory_source, 4) == 0);
|
||||
|
||||
// More requests than the queue holds: all are accepted, the caller waiting for free slots.
|
||||
constexpr UINT kBlocking = 3 * DSTORAGE_MIN_QUEUE_CAPACITY;
|
||||
static unsigned char blocking_dest[kBlocking][4];
|
||||
std::memset(blocking_dest, 0, sizeof(blocking_dest));
|
||||
for (UINT i = 0; i < kBlocking; ++i) {
|
||||
DSTORAGE_REQUEST copy = memory_to_memory(memory_source, blocking_dest[i], 4);
|
||||
memory_queue->EnqueueRequest(©);
|
||||
}
|
||||
memory_queue->EnqueueStatus(shapes.value, 0);
|
||||
memory_queue->EnqueueSetEvent(done.handle);
|
||||
memory_queue->Submit();
|
||||
CHECK(WaitForSingleObject(done.handle, 10000) == WAIT_OBJECT_0);
|
||||
CHECK(shapes->GetHResult(0) == S_OK);
|
||||
for (UINT i = 0; i < kBlocking; ++i) CHECK(std::memcmp(blocking_dest[i], memory_source, 4) == 0);
|
||||
memory_queue->RetrieveErrorRecord(&record);
|
||||
CHECK(record.FailureCount == 4 && record.FirstFailure.HResult == E_DSTORAGE_INVALID_DESTINATION_TYPE);
|
||||
|
||||
// After Close, enqueued commands are dropped and Close is repeatable.
|
||||
file->Close();
|
||||
CHECK(file->GetFileInformation(&file_info) == HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE));
|
||||
queue->Close();
|
||||
queue->EnqueueRequest(&read1);
|
||||
queue->Submit();
|
||||
queue->Close();
|
||||
memory_queue->Close();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Public buffer destination: a memory source written into an upload-heap buffer on
|
||||
// the queue's device. Expected bytes are the source bytes.
|
||||
int check_public_buffer_destination() {
|
||||
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
|
||||
Com<ID3D12Device> device;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), device.out());
|
||||
if (hr != S_OK || !device.value) {
|
||||
std::fprintf(stderr, "xcrdapi: public D3D12XboxCreateDevice hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
constexpr unsigned kBytes = 16;
|
||||
Com<ID3D12Resource> upload;
|
||||
hr = create_buffer(device.value, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, kBytes, &upload.value);
|
||||
if (hr != S_OK || !upload.value) {
|
||||
std::fprintf(stderr, "xcrdapi: public upload buffer hr=0x%08lx\n", static_cast<unsigned long>(hr));
|
||||
return 1;
|
||||
}
|
||||
if (const int filled = map_fill(upload.value, 0xEE, kBytes)) return filled;
|
||||
|
||||
Com<IDStorageFactory> factory;
|
||||
CHECK(DStorageGetFactory(__uuidof(IDStorageFactory), factory.out()) == S_OK);
|
||||
DSTORAGE_QUEUE_DESC desc{};
|
||||
desc.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
|
||||
desc.Capacity = DSTORAGE_MIN_QUEUE_CAPACITY;
|
||||
desc.Priority = DSTORAGE_PRIORITY_NORMAL;
|
||||
desc.Device = device.value;
|
||||
Com<IDStorageQueue1> queue;
|
||||
CHECK(factory->CreateQueue(&desc, __uuidof(IDStorageQueue1), queue.out()) == S_OK);
|
||||
Com<IDStorageStatusArray> status;
|
||||
CHECK(factory->CreateStatusArray(1, nullptr, __uuidof(IDStorageStatusArray), status.out()) == S_OK);
|
||||
|
||||
unsigned char source[8];
|
||||
for (unsigned i = 0; i < 8; ++i) source[i] = pattern_byte(i);
|
||||
DSTORAGE_REQUEST request{};
|
||||
request.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
|
||||
request.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_BUFFER;
|
||||
request.Source.Memory.Source = source;
|
||||
request.Source.Memory.Size = 8;
|
||||
request.Destination.Buffer.Resource = upload.value;
|
||||
request.Destination.Buffer.Offset = 4;
|
||||
request.Destination.Buffer.Size = 8;
|
||||
Event done;
|
||||
CHECK(done.handle);
|
||||
queue->EnqueueRequest(&request);
|
||||
queue->EnqueueStatus(status.value, 0);
|
||||
queue->EnqueueSetEvent(done.handle);
|
||||
queue->Submit();
|
||||
CHECK(WaitForSingleObject(done.handle, 10000) == WAIT_OBJECT_0);
|
||||
CHECK(status->GetHResult(0) == S_OK);
|
||||
|
||||
unsigned char got[kBytes];
|
||||
if (const int copied = map_copy(upload.value, got, kBytes)) return copied;
|
||||
unsigned char expect[kBytes];
|
||||
std::memset(expect, 0xEE, kBytes);
|
||||
std::memcpy(expect + 4, source, 8);
|
||||
CHECK(bytes_match(got, expect, kBytes, "public_buffer"));
|
||||
queue->Close();
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main() {
|
||||
void* unsupported = nullptr;
|
||||
CHECK(DStorageGetFactory(file_iid, &unsupported) == E_NOINTERFACE && !unsupported);
|
||||
@@ -125,7 +944,7 @@ int main() {
|
||||
ErrorRecord error{};
|
||||
CHECK(queue->RetrieveErrorRecord(&error) == S_OK && error.failure_count == 0);
|
||||
Request past_end{file.value, sizeof(contents), nullptr, first.data(), 1, 0};
|
||||
Request compressed{nullptr, 0, first.data(), copied.data(), 4, 1};
|
||||
Request compressed{nullptr, 0, first.data(), copied.data(), 4, compression_lz};
|
||||
CHECK(queue->EnqueueRequest(&past_end) == S_OK);
|
||||
CHECK(queue->EnqueueRequest(&compressed) == S_OK);
|
||||
CHECK(queue->EnqueueStatus(status.value, 0) == S_OK);
|
||||
@@ -174,5 +993,11 @@ int main() {
|
||||
CHECK(status->GetResult(0) == S_OK);
|
||||
CHECK(WaitForSingleObject(close_event.handle, 0) == WAIT_OBJECT_0);
|
||||
|
||||
if (const int public_api = check_public_interfaces(temporary.name, contents)) return public_api;
|
||||
if (const int public_buffer = check_public_buffer_destination()) return public_buffer;
|
||||
if (const int compressed = check_compressed_rejection(factory.value)) return compressed;
|
||||
if (const int batched = check_batched_buffer_transfers(factory.value)) return batched;
|
||||
if (const int unconfirmed = check_unconfirmed_staged_copy(factory.value)) return unconfirmed;
|
||||
|
||||
std::puts("test_xcrdapi: passed");
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
add_executable(test_xgameruntime_saves main.cpp)
|
||||
target_link_libraries(test_xgameruntime_saves PRIVATE xgameruntime kernel32 shell32)
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user