mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 10:01:12 +00:00
Compare commits
373
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4cb858e6f5 | ||
|
|
b36e397681 | ||
|
|
5bc4ff5cf4 | ||
|
|
5e204bd883 | ||
|
|
5c2e2c9b63 | ||
|
|
77dd9ffef3 | ||
|
|
abecde1c39 | ||
|
|
e532fc56ba | ||
|
|
4c5cd55884 | ||
|
|
ec3dea9942 | ||
|
|
1fed04a80c | ||
|
|
a9efeffc6f | ||
|
|
365b411fed | ||
|
|
1b4b1bf7d7 | ||
|
|
aeac1892c1 | ||
|
|
a9674bf9c7 | ||
|
|
eee9a4fcdc | ||
|
|
fe28c5c2af | ||
|
|
e21f41ae24 | ||
|
|
506defdd45 | ||
|
|
64141e9ae6 | ||
|
|
04148f77f8 | ||
|
|
5a6e786850 | ||
|
|
34f744aa5d | ||
|
|
afc093ee54 | ||
|
|
224586917f | ||
|
|
2af3e7d10a | ||
|
|
17e2e2a835 | ||
|
|
3ec40ba7fb | ||
|
|
b3aad0d948 | ||
|
|
277edd592a | ||
|
|
d4996ba9fd | ||
|
|
ca2b48ef83 | ||
|
|
dc41f00cb3 | ||
|
|
1b04d6e237 | ||
|
|
9116c0a39e | ||
|
|
b96a9b5978 | ||
|
|
dcec248837 | ||
|
|
40b5ee7a8e | ||
|
|
b975e6335b | ||
|
|
8f4786e436 | ||
|
|
0c398214fa | ||
|
|
78b56747fb | ||
|
|
63bd059182 | ||
|
|
24b124e144 | ||
|
|
cff3e754a9 | ||
|
|
27bfa17cb1 | ||
|
|
261d71d8d1 | ||
|
|
2cc64bd617 | ||
|
|
d99e35ad42 | ||
|
|
f7748387da | ||
|
|
28a9c868e6 | ||
|
|
6cfade83fe | ||
|
|
c963b9bc1a | ||
|
|
30197aa236 | ||
|
|
957b8efb21 | ||
|
|
e04a3b3f62 | ||
|
|
ea29d3fc56 | ||
|
|
d724c6c013 | ||
|
|
43cb1aab54 | ||
|
|
af869008a0 | ||
|
|
8627285a59 | ||
|
|
aec6766b4d | ||
|
|
84f4370227 | ||
|
|
79e1906c27 | ||
|
|
d65c12f6a9 | ||
|
|
b325320549 | ||
|
|
9f8b4c7f69 | ||
|
|
2e5fbc70b1 | ||
|
|
3f2f2732ed | ||
|
|
7c807d8b3a | ||
|
|
a2d153605d | ||
|
|
4a34ec3e50 | ||
|
|
2e96d93439 | ||
|
|
30e666b86c | ||
|
|
41bc72887b | ||
|
|
c206a3f85d | ||
|
|
c893436269 | ||
|
|
00b8344a40 | ||
|
|
451c6308c0 | ||
|
|
4d69562b59 | ||
|
|
656eff8459 | ||
|
|
3ba0eb20d5 | ||
|
|
8a00743d99 | ||
|
|
ce1940d84c | ||
|
|
bd744727bd | ||
|
|
b141c4b261 | ||
|
|
c7a4b4cf19 | ||
|
|
b88ea24a30 | ||
|
|
b2ae7a604e | ||
|
|
901b68ffba | ||
|
|
3eb8900442 | ||
|
|
335e3e4d60 | ||
|
|
ca2ad143f9 | ||
|
|
c345ada8e9 | ||
|
|
3154497424 | ||
|
|
6eaf8faa95 | ||
|
|
3c1ee93df5 | ||
|
|
87a03d0421 | ||
|
|
bf9dd7b383 | ||
|
|
b59696975a | ||
|
|
43bb5636bf | ||
|
|
b7a660d4b9 | ||
|
|
10f78645cb | ||
|
|
8c4610b51c | ||
|
|
3b1d168de7 | ||
|
|
7a380bd3d7 | ||
|
|
931c09c6af | ||
|
|
186836e1d6 | ||
|
|
133ffd4c97 | ||
|
|
0d9997ce66 | ||
|
|
bfbc84d251 | ||
|
|
e96de7c455 | ||
|
|
4b2985114a | ||
|
|
0b474941f0 | ||
|
|
fe749b1436 | ||
|
|
b76066eafb | ||
|
|
b7bb7615d8 | ||
|
|
2b2a9e15a6 | ||
|
|
3c65b393a4 | ||
|
|
67f3b618ab | ||
|
|
b0e40e29ea | ||
|
|
90dc310b61 | ||
|
|
4bf52b14a3 | ||
|
|
bc7b622018 | ||
|
|
d8fea7b351 | ||
|
|
fe50a8edff | ||
|
|
d47eac809f | ||
|
|
8db5552e32 | ||
|
|
297251fb00 | ||
|
|
030c63f8c9 | ||
|
|
9a6f71abbc | ||
|
|
ad4bcc66b1 | ||
|
|
3d244ddcb0 | ||
|
|
b29ccc60e1 | ||
|
|
5f8235f607 | ||
|
|
c1b3edf9ba | ||
|
|
1eecf6a20c | ||
|
|
ceaad9aee9 | ||
|
|
6bf2b9ab95 | ||
|
|
527cd6208f | ||
|
|
93a1f12bc6 | ||
|
|
32b371e55f | ||
|
|
e48454bdd3 | ||
|
|
55dfa39600 | ||
|
|
c39d33821e | ||
|
|
e17a8281eb | ||
|
|
355197c4ac | ||
|
|
01ef819910 | ||
|
|
085e0d450e | ||
|
|
2d2ee990a7 | ||
|
|
1f3e45eaf7 | ||
|
|
a4742dd137 | ||
|
|
d5eb5ae97d | ||
|
|
2fc6c16f9d | ||
|
|
cb6688c836 | ||
|
|
f1db93e2b4 | ||
|
|
71fa30c29b | ||
|
|
050b0b279c | ||
|
|
162ed81eaf | ||
|
|
dcd0a5127d | ||
|
|
f644569578 | ||
|
|
5b015a2b9e | ||
|
|
2549d724dd | ||
|
|
9bcb121322 | ||
|
|
48378f8c35 | ||
|
|
88e6cf00b9 | ||
|
|
0521ea0c6c | ||
|
|
ce23d0b2b9 | ||
|
|
d17525c165 | ||
|
|
3cfb9ed690 | ||
|
|
51ac3bd766 | ||
|
|
e816c16495 | ||
|
|
076b354d61 | ||
|
|
0bd188e602 | ||
|
|
b86be87576 | ||
|
|
62290b2f21 | ||
|
|
2d8685681b | ||
|
|
25d5240dd0 | ||
|
|
97a2ad5d8b | ||
|
|
d93a3f3084 | ||
|
|
30c071845f | ||
|
|
781f473ea3 | ||
|
|
6b83bbbd8b | ||
|
|
9f81aadc49 | ||
|
|
724347fd98 | ||
|
|
6f588bc862 | ||
|
|
74fffaa350 | ||
|
|
23de596a23 | ||
|
|
00e1b2fce9 | ||
|
|
846690befc | ||
|
|
04ad81ee26 | ||
|
|
e0f8b0e8f6 | ||
|
|
2fc82c4d58 | ||
|
|
c33199264a | ||
|
|
82ec02e754 | ||
|
|
6cd94140b1 | ||
|
|
c08571ac74 | ||
|
|
d57aba26b9 | ||
|
|
de0d5bd7d9 | ||
|
|
f48c42fd20 | ||
|
|
2217eb83a1 | ||
|
|
63f5640a99 | ||
|
|
4509911df0 | ||
|
|
76c81468c7 | ||
|
|
f3976b24f4 | ||
|
|
0f5a2ab6fd | ||
|
|
987b404a4e | ||
|
|
fa06be79b7 | ||
|
|
427f1b6cfa | ||
|
|
56a27dfd80 | ||
|
|
8d904a7f69 | ||
|
|
1300eb7892 | ||
|
|
1894ef23b7 | ||
|
|
baced39764 | ||
|
|
989abbdc2c | ||
|
|
140dce0be1 | ||
|
|
1b25f3422b | ||
|
|
766055e948 | ||
|
|
2faadeef7e | ||
|
|
ce5968a2db | ||
|
|
494e53b8fb | ||
|
|
54b87f613c | ||
|
|
bbd3b8a9d4 | ||
|
|
32d02efc33 | ||
|
|
ac82a55039 | ||
|
|
d6586b1fa3 | ||
|
|
ceb1095139 | ||
|
|
e40d7293f8 | ||
|
|
2ef175c0ce | ||
|
|
e016cc1259 | ||
|
|
083505ba1b | ||
|
|
1600d3f70f | ||
|
|
9d4f7dffff | ||
|
|
c126b94182 | ||
|
|
257aa1651a | ||
|
|
6c243259d9 | ||
|
|
981bd3c64e | ||
|
|
58b209a71b | ||
|
|
63b5f5dac6 | ||
|
|
b96aa5c0b8 | ||
|
|
6484cb70a3 | ||
|
|
87da1752ad | ||
|
|
1bc42fcaec | ||
|
|
25ceb05230 | ||
|
|
2bc97a4f68 | ||
|
|
f2efeaf79d | ||
|
|
463169f72c | ||
|
|
a6dc3faf50 | ||
|
|
56650b91c2 | ||
|
|
2505bc3a5b | ||
|
|
01f5590e88 | ||
|
|
21323cab80 | ||
|
|
ab81b0beca | ||
|
|
b16797f576 | ||
|
|
3409bf4ec0 | ||
|
|
420c2329b7 | ||
|
|
ae869522ce | ||
|
|
6e3ef5459b | ||
|
|
bec15f43b6 | ||
|
|
7dde71e2fd | ||
|
|
33d439f828 | ||
|
|
a27284ab26 | ||
|
|
311f4124fa | ||
|
|
46a6a4baca | ||
|
|
8245c30b56 | ||
|
|
be647332cb | ||
|
|
b8724bf04f | ||
|
|
fbd2f8cf43 | ||
|
|
40a9cebb83 | ||
|
|
6a1451b265 | ||
|
|
7056671c19 | ||
|
|
bd546d8a39 | ||
|
|
db193a3d16 | ||
|
|
cd945ba749 | ||
|
|
8381f57204 | ||
|
|
0b48688c13 | ||
|
|
c64534fb21 | ||
|
|
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 | ||
|
|
b096424f33 | ||
|
|
2cc44b8318 | ||
|
|
ec65d79726 | ||
|
|
238daa6b25 | ||
|
|
7815a947e5 | ||
|
|
77dde94aa8 | ||
|
|
99bfbc26ef | ||
|
|
884f5398e7 | ||
|
|
1ec92916b9 | ||
|
|
9d504d12d7 | ||
|
|
e75b4131a3 | ||
|
|
f7fb52bc56 | ||
|
|
ec2170d480 | ||
|
|
f2af367da6 | ||
|
|
cc5ce59d21 | ||
|
|
61fc3590b2 | ||
|
|
58fc63c7ec | ||
|
|
600a0ab08f | ||
|
|
cda66a57f2 | ||
|
|
a5c1995f21 | ||
|
|
868444ed30 | ||
|
|
510b6d1d66 | ||
|
|
92c2ff7add | ||
|
|
39baf092a3 | ||
|
|
0a30562cde | ||
|
|
fb56805459 | ||
|
|
1eb963d883 | ||
|
|
ac0fd2e502 | ||
|
|
73c190d725 | ||
|
|
f3c2b7fe34 | ||
|
|
4333a7cc5e | ||
|
|
66e9351410 | ||
|
|
060083cc56 | ||
|
|
120a5ec5f6 | ||
|
|
7d7249ee8b | ||
|
|
d0395a61da | ||
|
|
2eb59e033b | ||
|
|
eec56dd028 | ||
|
|
e7899574ab | ||
|
|
486f7b197f | ||
|
|
390e85fc8d | ||
|
|
18178da12c | ||
|
|
bfa80dee8b | ||
|
|
829a94fa2f | ||
|
|
2e895e0f9b | ||
|
|
02b8924de7 | ||
|
|
925311e852 | ||
|
|
f7194d0255 | ||
|
|
7ea4f1f6ca | ||
|
|
bd8edd8f70 | ||
|
|
a8c4dbb77e | ||
|
|
cee636193a | ||
|
|
ab696f1f07 |
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: |
|
||||
|
||||
@@ -29,6 +29,8 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- name: Install PyYAML
|
||||
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
|
||||
- name: Unit-test the hygiene checks
|
||||
run: python3 -m unittest scripts/audit/test_docs_hygiene.py
|
||||
- name: Check documentation and workflow files
|
||||
run: python3 scripts/audit/docs_hygiene.py --require-yaml
|
||||
- name: Remind about the changelog (advisory)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
name: Merge policy audit
|
||||
|
||||
# Detects a pull request merged by its own author (AGENTS.md §7, "Merge
|
||||
# eligibility"). GitHub rulesets cannot block this, so the run fails after the
|
||||
# merge. It is not a required check and never checks out pull request code.
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [closed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
author-merge:
|
||||
name: Author did not merge
|
||||
if: github.event.pull_request.merged == true && github.event.pull_request.merged_by.login == github.event.pull_request.user.login
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 2
|
||||
steps:
|
||||
- name: Report a self-merge
|
||||
env:
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
AUTHOR: ${{ github.event.pull_request.user.login }}
|
||||
run: |
|
||||
echo "::error::Pull request #$PR was merged by its own author, $AUTHOR. A maintainer other than the author must merge (AGENTS.md section 7)."
|
||||
exit 1
|
||||
@@ -4,34 +4,59 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
|
||||
|
||||
---
|
||||
|
||||
## 0. First-Time Contributor Onboarding
|
||||
## 0. What to Do When Told "Work"
|
||||
|
||||
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:
|
||||
Collaborators point their agent at this repository and say "work" (or "contribute", "continue", "what next?"). That is a complete instruction. Do not ask what to work on: follow this section. The method behind it is in [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md).
|
||||
|
||||
1. **Preflight host & tools:**
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
|
||||
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
|
||||
- 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:
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --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:**
|
||||
- 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.
|
||||
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.
|
||||
**"Work" authorizes, for the one item you pick:** posting a claim or a review, committing with DCO sign-off, pushing a branch, and opening a pull request. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
|
||||
|
||||
### Step 1 — Preflight
|
||||
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`. If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
|
||||
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`). Verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
|
||||
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor`. It must report the toolchain, CrossOver, at least 10 GB of free disk space, and no other game run on this machine.
|
||||
- Work in your own worktree and your own bottle. Never use a bottle another session is using.
|
||||
|
||||
### Step 2 — Pick exactly one thing, in this order
|
||||
|
||||
Take the first that applies. Do not skip ahead because a later one looks more interesting.
|
||||
|
||||
1. **Your person's pull requests that need attention.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
If one has requested changes, unresolved review comments, failing checks or conflicts: fix that pull request. Resolve every review point, re-run Section 8, push, and reply to each point.
|
||||
|
||||
2. **Review someone else's pull request.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,reviewDecision,isDraft,createdAt
|
||||
```
|
||||
Take the oldest open, non-draft pull request that your person did not open and that has no current review. Check out its branch, run Section 8 and its new test, confirm the test fails without the fix, read its proof, and post an approval or a change request with what you ran. If it needs deep review (the list is in the working method) and you can give one, do. If it is approved, green and not your person's, merge it (Section 7).
|
||||
|
||||
3. **Fix one blocker of the current stage.**
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label blocker --label "stage: <current>" --json number,title,labels,comments
|
||||
```
|
||||
The current stage is named on the pinned issue labelled `ladder`. Take the top unclaimed blocker: those labelled `first`, then lowest number. A blocker is claimed if it has a `Claiming —` comment less than 3 days old or an open pull request. Then follow Step 3.
|
||||
|
||||
4. **Discover.** If the current stage has no unclaimed blocker, run the stage's gate check (ten runs, [run protocol](docs/process/working-method.md#run-protocol)). For each signature in the report that has no issue, open or closed, file a blocker issue in the fixed shape. If the gate passes, post the ten-run result on the ladder issue and label it `needs-human`.
|
||||
|
||||
5. **Nothing applies.** Say so and stop. Do not invent work, open research documents, or start on a later stage's blockers while the current stage has claimed, unfinished ones — unless your person tells you to.
|
||||
|
||||
**Stop and label `needs-human`** whenever the next step is a decision that is not yours: a decision gate, a licence or provenance question, sources of truth that disagree, or a rule change.
|
||||
|
||||
### Step 3 — Work one blocker
|
||||
|
||||
1. **Claim:** comment `Claiming — branch: track-<a..f>/<issue>-<slug>` and branch from `origin/main`.
|
||||
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. If you cannot explain the blocker in this session, write what you learned on the issue, release the claim, and stop. Do not guess a fix.
|
||||
3. **Smallest fix:** only what removes this blocker. Stay inside the track directories it needs (Section 2); a new cross-DLL export goes through an `[ABI]` pull request first.
|
||||
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix.
|
||||
5. **Verify:** every command in Section 8. Without CrossOver you can still run the Rust checks, `scripts/build-shims.sh` and the docs check; say plainly which live checks were not run. Never report an unrun check as passed.
|
||||
6. **Proof:** ten runs before and ten after, every run reported, with the machine and the `main` commit.
|
||||
7. **Pull request:** one blocker; the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof); `Closes #<issue>`; DCO sign-off; no AI trailers. Watch CI until `Hybrid build and shim checks` and `Repository hygiene` pass.
|
||||
8. **Stop.** The next "work" starts again at Step 2.
|
||||
|
||||
Nothing from the target build goes into a commit, issue or pull request (Section 6): keep run logs, dumps and captures in your private evidence folder outside the repository.
|
||||
|
||||
---
|
||||
|
||||
@@ -64,8 +89,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`.
|
||||
|
||||
---
|
||||
@@ -81,9 +106,7 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
|
||||
|
||||
## 4. Dependencies, Licensing & Provenance
|
||||
|
||||
- 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.
|
||||
_Reserved — policy migration in progress._
|
||||
|
||||
---
|
||||
|
||||
@@ -97,26 +120,34 @@ 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.
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
---
|
||||
|
||||
## 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 (being told to "work" authorizes them for the one item picked, Section 0); 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.
|
||||
|
||||
### Merge eligibility
|
||||
|
||||
Four roles are separate: the **original author** (who opened the PR), **corrective contributors** (who later push to its branch), **independent approvers**, and the **merger**.
|
||||
|
||||
- The original author never merges their own PR. Any other maintainer may merge once required checks pass, at least one approval is current and blocking review conversations are resolved.
|
||||
- Maintainers may resolve conflicts, correct defects, update documentation and push fixes to a contributor's PR branch where GitHub permissions allow. Doing so does not disqualify them from merging.
|
||||
- Any push that changes the PR dismisses earlier approvals. After a **routine** push (conflict resolution that changes no behaviour, changelog correction, minor documentation fix), one new approval is enough and may come from the maintainer who pushed it, if they are not the original author. No further approval is required beyond the ruleset.
|
||||
- **Substantive** implementation changes need independent review (Section 5): the approval must come from someone who did not write them. A maintainer who wrote substantive corrections may merge after another person has approved those corrections, but may not approve them. If in doubt, treat a change as substantive.
|
||||
- A coding agent acts as the person it works for and merges only with that person's authorization.
|
||||
|
||||
The `Protect main` ruleset enforces pull requests, one approval, dismissal of stale approvals, resolved conversations, the required CI checks and no force push or deletion, with no bypass actors. GitHub cannot enforce two rules above: who may merge (`Merge policy audit` only fails after an author self-merge) and whether an approver wrote part of the change.
|
||||
|
||||
---
|
||||
|
||||
@@ -129,8 +160,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 +173,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 eligible (Section 7), 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.
|
||||
+261
@@ -9,7 +9,237 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- **Roadmap and working method (proposed).** `docs/roadmap.md` replaces the subsystem milestones M3–M6 with stages the project-authorized target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), each judged on ten recorded runs on a 16 GB Mac, with decision gates for the D3DMetal back end, reference images, memory and frame rate. [docs/process/working-method.md](docs/process/working-method.md) describes the blocker queue for a team that works by telling coding agents to "work": where state lives, the order of work (own pull requests, review, one blocker, discover), the run protocol, source ranks and pull-request shape. AGENTS.md §0 is rewritten to match.
|
||||
- `xg_xs.dll` follows the documented XG contract titles call: `XG_RESOURCE_DESC` and the 14-method `XGTextureAddressComputer`, from the authorized GDK documentation. Behaviour:
|
||||
- **Linear layouts:** every texture is laid out linearly with BetterXen's documented alignment.
|
||||
- **`SW_64KB_S` addressing** for a texture that fits one 64 KiB tile.
|
||||
- **Other requested swizzle modes** are laid out linearly and reported as `LINEAR`, logged once per mode. Refusing them crashed a title that does not check the result.
|
||||
- **`GetResourceTiling`** reports the D3D12 standard 64 KB tile shapes and a packed mip tail. 3D resources get the 3D tile shapes with depth tiles; 1D textures and buffers get 64 KiB tiles.
|
||||
- **Limits:** descriptions past the public D3D12 limits (16384 for 1D/2D, 2048 for 3D and array sizes) are refused rather than truncated, and so is a 3D subresource past the mip count.
|
||||
|
||||
The earlier clean-room interface is removed: `xg_xs.cpp`, `xg_texture.h` and `test_xg_xs`. `test_xg_xbox` (42 checks) replaces it, and stage 13 of `test_integration_boot` uses the documented contract.
|
||||
- `BXVM` configuration writes the output `cpu_pointer` before changing shared configuration or releasing a cached backing heap. If that write fails after the accessibility check, the call returns `E_INVALIDARG` without applying the configuration.
|
||||
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
|
||||
|
||||
### Added
|
||||
- `docs/research/console-shader-abi.md` and `CLAIM-XBOX-CS-ENTRY-ABI` (class U, not yet independently reproduced): the compute shader entry ABI observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler, used under Microsoft's authorization, on eleven project-authored probes. Compute code is wave64. Root data starts at `s4` in root-parameter order: one SGPR per constant, two per root descriptor address, one per 32-bit table pointer. The thread-group IDs follow the root data, and `s0:s1` holds the root-data address when it overflows. Root buffer descriptors are built inline with no effective bounds check, table buffer descriptors are 32 bytes apart (samplers 16), and the compiler reports the HLSL binding of each descriptor load. No compiler output, binary or documentation text is in the repository. Register roles are inferences, and the ACCC container layout remains unknown.
|
||||
- Opt-in diagnostics in `bx_runtime_veh.dll`, all off by default:
|
||||
- an access-violation context with the memory type and the faulting thread's stack (`BX_VEH_AV_CONTEXT`, `BX_VEH_AV_ALL`);
|
||||
- software write watches over one address, a range or a pointer chain (`BX_VEH_WATCH`, `BX_VEH_WATCH_RANGE`);
|
||||
- software code breakpoints that log string arguments (`BX_VEH_HIT`, `BX_VEH_HIT_ALL`);
|
||||
- an all-threads sampling profiler (`BX_VEH_SAMPLE`).
|
||||
|
||||
Records are bounded, JSON-escaped and UTF-8. A protection change that fails disarms the diagnostic, which is logged, and the guest gets its exception. Detach disarms everything. With the switches unset, nothing runs. `bx-cli run` lets these named switches through its isolated guest environment. `test_veh_diagnostics` covers every mode.
|
||||
- `bx_runtime_veh.dll` records breakpoints (`0x80000003`) and assertion failures (`0xC0000420`) from its vectored handler as `breakpoint_exception` JSONL records with the exception code, module name, module base and RVA. A guest with its own crash reporter replaces the top-level filter installed at attach, so its assertions never reached `unhandled_exception`; the vectored handler runs before the guest's top-level filter and any vectored handler the guest registers last (one it registers first can resume the exception before BetterXen sees it). Module names are written as UTF-8, and `bx-cli trace` notes when the record cap was reached. The records are first-chance (the guest may still handle the exception), handling is unchanged, and at most 16 are written per process. `bx-telemetry` parses them and `bx-cli trace` lists them under "Breakpoint/assert exceptions, first chance".
|
||||
- **Test:** `tests/conformance/test_veh_breakpoint/` replaces the top-level filter and resumes from its own vectored handler, as such a guest does. It raises 21 int3 breakpoints at a labelled site and one `STATUS_ASSERTION_FAILURE`, and requires exactly 16 records, the int3 records at the RVA it computes from the label and its own module base, and no `unhandled_exception`. It fails against the previous `bx_runtime_veh.dll`.
|
||||
- [Target-build bring-up: development cycle and review](docs/testing/target-build-review.md): how contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently.
|
||||
- `xgameruntime.dll` serves the XPackage installation monitor offline: the running package is reported fully installed, launchable and complete. Monitor handles share the mount handles' table, generation and lock: stale handles are rejected, closing twice is harmless, and uninitialize releases them. Progress registrations are accepted, logged and never fired. `XPackageEnumeratePackages` reports this game for `XPackageKind::Game` and no content packages. Both replace stubs that a project-authorized target build calls at startup. The save-container mount path ends with the drive-root separator, and `test_xgameruntime_saves` expects it.
|
||||
- `AcpHal.dll`:
|
||||
- **Shape contexts:** `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` allocate from the APU heap. The layout is the documented `SHAPE_CONTEXTS` (96 bytes; CPU pointers at 24, APU addresses at 72). A second allocation returns `ACP_E_ALREADY_ALLOCATED`.
|
||||
- **`IAcpHal`** has the documented non-COM slot order: `Connect`, `Disconnect`, `SubmitCommand`, `PopMessage`, `GetNumMessages`, `Release`.
|
||||
- **The default APU heap** is 64 MB.
|
||||
- **Tests:** `test_audio_input` checks both. `test_integration_boot` releases `IAcpHal` through its own `Release` slot.
|
||||
- `d3d12_xs.dll` carries a project-authorized target build from device creation into its frame loop. The Xbox-layout device and its objects get:
|
||||
- **Descriptor heaps** with title-visible storage and the console descriptor sizes.
|
||||
- **Committed and placed resources** in title memory, with copy coherence for `Map`/`Unmap`.
|
||||
- **Samplers and page pools.**
|
||||
- **Pipelines** through the shader gate.
|
||||
- **Opt-in null rendering** (`BX_NULL_RENDER=1`): pipelines that cannot be built become null pipelines, and their draws and dispatches are skipped and logged.
|
||||
- **Fences** at GPU addresses and GPU value writes.
|
||||
- **`PresentX`** onto a DXGI swapchain.
|
||||
- **Console page mappings:** `CopyPageMappingsX`, `CopyPageMappingsBatchX` and `ClearPageMappingsX`.
|
||||
- **The full 1,384-byte Xbox command-list area.**
|
||||
- **Opt-in dumps of presented frames** (`BX_PRESENT_DUMP`).
|
||||
|
||||
`test_d3d12_xbox_layout` checks the page mappings and the command-list area.
|
||||
- `xgameruntime.dll!QueryApiImpl` now serves the runtime objects behind **`XSystemGetAnalyticsInfo`** and **`XDisplayTryEnableHdrMode`**, which a project-authorized target title requests during System Init (previously logged as unsupported `B884675D-…` and `03F0FE74-…/35F07670-…`). The keys and slots (analytics slot 3, which returns `XSystemAnalyticsInfo` by value; HDR slot 4) were derived from authorized GDK material, and no GDK files are in the repository. The function contracts follow Microsoft's public `XSystem.h` / `XDisplay.h` documentation. `XSystemGetAnalyticsInfo` reports family `Xbox`, a form that follows the profile (`Xbox Series S` for Lockhart, `Xbox Series X` for Anaconda) and BetterXen's synthetic OS version `10.0.26100.0` (logged with `synthetic=1`). `XDisplayTryEnableHdrMode` returns `XDisplayHdrModeResult::Disabled`, the documented success answer when HDR is not enabled, because BetterXen presents SDR. It clears the optional luminance output and logs the preference. `test_xgameruntime` calls both through `QueryApiImpl` and checks the public contract. The target title now gets past both calls; its next stops are fixed by #643 and #640.
|
||||
- `xmem.dll` exports two new internal cross-DLL hooks, `bx_xmem_try_charge_external` and `bx_xmem_release_charge_external` (`abi/defs/xmem.def` grows 15 → 17; `scripts/build-shims.sh` now reports 113 exact exports) (#550). They admit and release bytes against the combined Lockhart/Anaconda title cap under the same `usage_lock` `can_commit` takes, and `can_commit` now counts a new `external_bytes` counter in `used`. `XMemGetWorkingSetStatistics` / `bx_xmem_get_internal_stats` report external charges inside `committed_virtual_bytes`, so reported usage matches what the cap counts. A release larger than the outstanding external charge is refused and logged (the counter is left unchanged, so other owners' charges survive), and a failed bookkeeping refresh during a charge is logged as `external_charge` instead of being reported silently as a budget rejection. New `test_xmem_external_charge` charges externally and checks that `XMemVirtualAlloc` is then refused at the cap, that the stats include the charge, that an over-release is refused, and that the allocation is admitted again after release. `d3d12_xs` switches to the hook in the same change (#552, below).
|
||||
- `bx-cli run` maps the Xbox title drives before launch: `G:` to the executable's directory and `T:` to `drive_c/bx_temp` in the prefix or bottle (`launcher/crates/bx-cli/src/drives.rs`). An Xbox title opens its package on `G:` and writes crash logs to `T:`, and stops at startup when either is missing (observed on a project-authorized target build; the drive roles are an inference). Ownership is recorded before creating or retargeting links, so a failed manifest write cannot leave an unrecorded mapping; temporary links use per-process names and manifest targets use lossless path-byte encoding. A prefix lock prevents another `bx-cli run` from changing its drive mappings while a guest is active. The `.bx-drives` manifest is written to a temporary file and renamed into place without following an existing temporary symlink, so an interrupted write keeps the previous manifest instead of leaving a truncated one that later runs refuse. **Behaviour change:** `bx-cli run` takes a prefix-wide lock before system32 staging and holds it until the guest exits, so runs sharing a prefix or bottle are serial: a second launcher on the same prefix is refused, before it stages anything. `test_xbox_drives` checks the resulting layout, not who created the links.
|
||||
- **Ownership:** like system32 staging (#474), a `.bx-drives` manifest in `dosdevices` records each link the tool made. Only those are re-pointed. A drive letter mapped elsewhere by anything else is left unchanged and reported as a warning. A prefix without `dosdevices` is reported and the run continues.
|
||||
- **Test:** `tests/conformance/test_xbox_drives/` reads its own executable through `G:` and compares it byte for byte with the copy at its module path, then creates, reads back and deletes a file on `T:`. Unit tests in `drives.rs` cover creation, reruns, re-pointing an own link, foreign links and entries, a missing `dosdevices`, malformed manifests, a failed manifest write, lock contention and non-UTF-8 path round-tripping.
|
||||
- `d3d12_xs.dll` gives titles Xbox-layout D3D12 objects ([ADR 0009](docs/adr/0009-xbox-layout-d3d12-objects.md)). A title built against the Xbox Series D3D12 header calls through function tables whose order differs from PC D3D12. `ID3D12Device` matches only up to slot 43, and `ID3D12Device11` has 139 slots. So before, every call past those slots reached the wrong PC method, and on a project-authorized target build the first such call jumped to address 0.
|
||||
- **Objects and tables:** `BxXboxObject` (`shims/d3d12_xs/xbox_facade.{h,cpp}`) has the Xbox object layout and sets `m_OutOfLineFlags`. Its Xbox-order table forwards to the PC proxies. `shims/d3d12_xs/tools/gen_xbox_tables.py` generates the tables (`xbox_tables_generated.cpp`) from the Xbox header, used under Microsoft's authorization, and the toolchain's `<d3d12.h>`. It takes only slot order, names, IIDs and parameter types, and the header is not committed.
|
||||
- **Slots:** a slot with an equivalent PC signature forwards with the PC types, unwrapping interface parameters and wrapping created objects. Every other slot logs `BX_VTABLE_STUB_LOG`.
|
||||
- **Coverage:** the device chain up to `ID3D12Device11`, plus resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues. Command lists are not covered yet.
|
||||
- **`CreateCommandQueueX`:** maps the Xbox queue description onto PC `CreateCommandQueue`.
|
||||
- **Layout choice:** titles set `Version` in the device parameter block and get the Xbox layout. BetterXen's PC-layout fixtures pass a zeroed block and keep the PC proxy. The choice is logged as `xbox_layout`.
|
||||
- **Phase 2:**
|
||||
- **Command lists:** `ID3D12GraphicsCommandList8`, created through `CreateCommandListX` or `CreateCommandList`. Their zeroed put-buffer fields force the five inline fast paths through the table.
|
||||
- **Embedded interface pointers:** `ResourceBarrier` and `CopyTextureRegion` unwrap the interface pointers inside their structures.
|
||||
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` are emulated by a host timer (`frame_pacing.cpp`).
|
||||
- **Generator fixes:** CRLF lines, a table-boundary overrun that hid `ID3D12GraphicsCommandList1`, nested SAL, and `FLOAT`.
|
||||
- **Resources at title-chosen addresses:** `CreatePlacedResourceX`/`X1` create host shadow resources (`placed_x.cpp`), with buffer contents copied from the title's memory at creation. The resource reports the title's address from `GetGPUVirtualAddress`. Ongoing synchronisation, GPU-to-CPU copies, title-address translation in GPU calls and texture contents are not implemented yet.
|
||||
- **Test:** `tests/conformance/test_d3d12_xbox_layout/` calls Xbox slots by number, with the slot numbers and offsets written out by hand from the header and the expected values taken from a PC-layout device. It also records a buffer copy through Xbox command objects, runs it on the GPU and reads the result back, and checks frame pacing. It fails against the previous DLL (8 checks against the Phase 1 build).
|
||||
- Added `tests/conformance/test_xcrdapi_abi/` (#597), an independent verification of the public DirectStorage ABI that `XCRDAPI.dll` serves. Every call goes through a hand-typed C vtable read out of the object (`slots(object)[n]`, cast to a signature typed in the test), with slot numbers and parameter types transcribed from the `DECLARE_INTERFACE_IID_` blocks of the vendored `dstorage.h` 1.4.0 in declaration order, including the inherited `IUnknown` slots — not from the shim's C++ class declarations. Derived slot counts, one per interface, are `IDStorageFile` 5, `IDStorageFactory` 8, `IDStorageFactory1` 9, `IDStorageStatusArray` 5, `IDStorageQueue` 12, `IDStorageQueue1` 13, `IDStorageQueue2` 14, `IDStorageQueue3` 15 and `IDStorageQueue4` 16; the test prints the `IDStorageFile`, `IDStorageFactory1`, `IDStorageStatusArray` and `IDStorageQueue4` tables (the last covering every one of the 16 queue slots). It asserts that each slot resolves to the method the header names: `IUnknown` identity and refcount arithmetic, `CreateQueue`/`CreateQueue1` capacity, priority and `UsesGaclShuffleTransform` validation, `OpenFile` error and success paths, `CreateStatusArray`, `SetDebugFlags`, `SetStagingBufferSize`, `Close`/`GetFileInformation`, `IsComplete == (GetHResult != E_PENDING)`, `EnqueueRequest`/`EnqueueStatus`/`EnqueueSignal`/`Submit`/`CancelRequestsWithTag`/`Close`/`GetErrorEvent`/`RetrieveErrorRecord`/`Query`, `EnqueueSetEvent`, `GetCompressionSupport`, `EnqueueRequests` and `Query1`. The `ID3D12Fence` and foreign `IDStorageStatusArray` arguments are hand-built C vtables, so a wrong slot cannot be absorbed by a matching C++ declaration. Slot order and IIDs were cross-checked against Silk.NET's MIT DirectStorage bindings (which bind the same slots through `EnqueueRequests` at 14; Silk.NET 1.3.0 predates `IDStorageFactory1` and `IDStorageQueue4`, so `CreateQueue1` at 8 and `Query1` at 15 come from the header's inheritance chain). No slot mismatch and no staged-copy lifetime bug was found: `StagedGpu`/`copy_staged()` keeps the device, upload buffer, queue, allocator, list, completion fence, defer fence, event and destination alive on every path where the submitted fence has not reached 1, including the `defer_staged_copy()` seam and the timeout path, which `test_xcrdapi` exercises. A mutant `XCRDAPI.dll` built with `Submit` and `CancelRequestsWithTag` swapped in the header fails the test (`queue slot 6 (Submit) did not submit`), proving it distinguishes slots. Ran under Wine 11.21 (Gcenx build) + Rosetta 2 on Apple Silicon with the **vkd3d** backend: `test_xcrdapi_abi.exe` and `test_xcrdapi.exe` both passed. CrossOver and D3DMetal are not installed on this host, so no D3DMetal run was performed and `bx-cli run` (which requires `/Applications/CrossOver.app`) was not run.
|
||||
- The synthetic M2 first-frame fixture (#469) requires the placed-resource and PresentX contract headers; missing contracts fail the build rather than silently omitting the gate. It checks dynamic GDK boot, SM 6.6 shader inspection, and one host present. It compares 256 pre-flip RGBA8 pixels through a placed buffer in the D3D12 WRITE_BACK heap and checks that the separate xmem region used for virtual-memory configuration retains its sentinel bytes. The pixel check covers the swapchain back buffer before the flip. The `tests/conformance/README.md` documents the negative-control command; it uses a sanitized launcher environment with `--inherit-env` to pass `BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH=1` and expects a `pixel_readback` failure.
|
||||
- `d3d12_xs.dll` now runs stream pipeline states through the M2 shader gate (#576). `ID3D12Device2::CreatePipelineState` forwarded `D3D12_PIPELINE_STATE_STREAM_DESC` to the host unparsed, so an ACCC-only container that `CreateComputePipelineState` and `CreateGraphicsPipelineState` refuse with `E_NOTIMPL` still reached D3DMetal through the stream form — the crash the gate exists to prevent — and was logged only as `pso_stream ... shaders_not_parsed=1` with no `shader_gate` record.
|
||||
- **What is parsed:** the stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, and `AS`/`MS`) are classified with `BxShaderGate::admit`; every other payload is copied verbatim. An unknown type, a duplicated type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim works on its own copy, so the gate can substitute prepared DXIL without writing to the caller's memory.
|
||||
- **Layout correction (review):** the first version assumed every payload sat at offset 8. `alignas(void*)` on the subobject class aligns the *record*, not the payload, so 4-byte-aligned payloads (`BLEND`, `SAMPLE_MASK`, `RASTERIZER`, `DEPTH_STENCIL`, `DEPTH_STENCIL1`, `IB_STRIP_CUT_VALUE`, `PRIMITIVE_TOPOLOGY`, `RENDER_TARGET_FORMATS`, `DEPTH_STENCIL_FORMAT`, `SAMPLE_DESC`, `NODE_MASK`, `FLAGS`) sit at **offset 4**. The table now derives `payload_at<T>()` and `record_size<T>()` from a `struct alignas(void*)` record, with `static_assert`s pinning the measured offsets (shader 8/24, UINT 4/8, BLEND/RASTERIZER/RT_FORMAT_ARRAY/DEPTH_STENCIL1 at 4). A valid graphics stream with those tags was desynced and rejected before the fix. `test_shader_gate`'s `StreamBuilder` now encodes the same real layout and adds a graphics stream with 4-byte-aligned payloads, so the tests can catch a desync instead of asserting the shim's own assumption.
|
||||
- **Logging:** `pso_stream` keeps its record and now reports `shaders_not_parsed=0` when it parsed the stages; each stage adds its own `shader_gate` record with `pso=stream`.
|
||||
- **Tests:** `test_shader_gate` adds a stream PSO whose CS is the synthetic ACCC-only container (`E_NOTIMPL`, `*ppv == nullptr`), the same stream with the SM 6.6 DXIL blob (succeeds and its 256 output words are verified), a truncated stream, an unknown subobject type, and a duplicated `CS` (`E_INVALIDARG` each), plus the `--no-bridge` child refusing ACCC-only through the stream. It also asserts the new `pso=stream` `shader_gate` records and `shaders_not_parsed=0`. The stream walker's accept/reject decisions were checked on the host with a native `clang++` harness (valid, truncated, unknown-tag and out-of-range-tag cases).
|
||||
- `abi/` unchanged; `d3d12_xs.dll` still exports 4. **`test_shader_gate.exe` was not executed** — no CrossOver on this host. The ADR 0008 wording recording stream PSOs as covered by the shader gate now lands with this stream-PSO gate change (#578 / PR #607).
|
||||
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
|
||||
|
||||
### Fixed
|
||||
- `XCRDAPI.dll` Xbox DirectStorage fixes:
|
||||
- **Zlib requests read the file.** The file handle was not set for them, so every compressed file request failed. The request options are now decoded, and zlib streams are inflated in-tree.
|
||||
- **`AutoSubmitDisabled` is honoured.** Xbox `CreateQueueX` respects `DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled`: a queue with the flag runs nothing before `Submit`, and when it is full the enqueuer waits until `Submit` is called on another thread. A queue without the flag submits by itself once half full.
|
||||
- **Request trace:** `BX_DSTORAGE_TRACE=1`.
|
||||
- **Tests:** `test_xcrdapi_xbox` covers a file-source zlib request and both queue behaviours. Each check fails with its fix reverted.
|
||||
- `xmem.dll` physical page numbers count 4 KiB frames. A 64 KiB page's number is a multiple of 16, and each allocation's numbers start at a multiple of 0x1000 frames. With consecutive numbers, callers that keep `number >> 4` collapsed 16 pages into one, and memory written through one page appeared in others. Physical pages are mapped as runs: one view per run of consecutive pages instead of one per page. On a project-authorized target build, startup went from 36 s to 6 s, under the title's 30-second watchdog. Allocation goes through the title's registered allocation hooks, with one section per physical-page call. A GPU-only reservation with large pages (no CPU access, a `PAGE_GRAPHICS_*` bit set) becomes a mappable placeholder region, so console page-mapping calls can fill it. `BX_XMEM_TRACE=1` logs allocations, frees and maps. `test_xmem_physical` checks the page-number units, and `test_xmem_hooks` checks the hooks.
|
||||
- `d3d12_xs.dll` refuses an Xbox-layout object the host cannot back. If the host object lacked the interface an Xbox table forwards to (on vkd3d, `ID3D12Device10`), `bx_xbox_wrap` returned the PC object, and `D3D12XboxCreateDevice` reported an Xbox-layout device. A title calling Xbox slot numbers would then have reached PC methods. The device and every wrapped family now fail with `E_NOINTERFACE`, logged as `xbox_wrap_refused`. `test_d3d12_xbox_layout` verifies the refusal on such a host and skips (exit 77); it passes on D3DMetal.
|
||||
- `d3d12_xs` validates placement on **every heap and every placement entry point** (#554, #572). `CreatePlacedResource` (slot 29) checked alignment, extent, buffer clear value and the UPLOAD/READBACK initial state only on the backing heap, and `CreatePlacedResource1` (`ID3D12Device8` slot 70) and `CreatePlacedResource2` (`ID3D12Device10` slot 77) were generated pass-throughs with no check and no `kPlacedResourceHeap` retention, so the shim heap wrapper and its xmem charge could be released while a resource placed through them was still alive. All three now share `create_placed_common` in `vmem.cpp`: a null heap or desc, a misaligned offset or a resource past the heap end returns `E_INVALIDARG` with `*out` null and a `placed_resource` log line naming the method, and a shim heap is retained by the resource on all three. `CreatePlacedResource2` takes a barrier layout, so the resource-state rule is not applied to it, and its allocation info comes from `GetResourceAllocationInfo2` without the castable-format list. `tools/gen_proxy.py` gains a `HANDOFF` table that keeps the generated trace and null-host stub and passes the host interface and unmodified arguments to a function declared from the header signature; `proxy_generated.{h,cpp}` are regenerated, and no new vtable slot is patched. `test_d3d12_placed` adds misaligned, aligned-overhang, valid-offset and UPLOAD-state cases on an ordinary heap for each entry point, and runs the heap-charge retention check through all three. Run live under CrossOver 26.3 in a D3DMetal bottle: passes (173 checks, 1 skipped — the 512 MiB pairing check; at `BX_MEM_LIMIT_MB=512`, 189 checks, 0 skipped), including every `CreatePlacedResource2` case. Against the previous shim the new cases fail ten checks there: D3DMetal returned `S_OK` for a misaligned offset, an aligned overhang and an UPLOAD heap in `COPY_DEST` on all three entry points it was asked about, and the slot 70/77 resources dropped the heap charge. Under `bx-cli run` (vkd3d) the fixture also passes (163 checks, 3 skipped); that host does not expose `ID3D12Device10`.
|
||||
- `xmem.dll` follows the documented signatures of five exports (source: the authorized GDK documentation). Before, a title calling them as documented had its arguments misread: on a project-authorized target build, `XMemAllocatePhysicalPages` failed and the title's check broke into its crash reporter. `XMemAllocatePhysicalPages` accepts `MEM_64K_PAGES` (`MEM_2MB_PAGES | MEM_PHYSICAL`) as 64 KB pages, as Microsoft's public samples pass it; the `MEM_2MB_PAGES` bit alone is `XMEM_2MB_CLUSTERS`, still unimplemented and logged. `test_xmem_physical` adds the samples' shape: a `MEM_64K_PAGES` page mapped into a mappable reservation made with protection `0x2404`.
|
||||
- **Signatures:** `XMemAllocatePhysicalPages(XMemFlags, NumberOfPages, PageArray)`, `XMemFreePhysicalPages(NumberOfPages, PageArray)` (count by value), `XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray)` and `XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray)` (parallel arrays, returns `BOOL`). `XMemVirtualAlloc(BaseAddress, Size, AllocationType, XMemFlags, PageProtection)` takes five arguments, which supersedes the closed #518.
|
||||
- **Pages and flags:** physical pages are always 64 KB. The four memory-bandwidth values are accepted. `XMEM_2MB_CLUSTERS` and mapping into `MEM_2MB_PAGES` reservations are not implemented: they log `BX_STUB_LOG` and fail with `ERROR_NOT_SUPPORTED`. Other flag bits fail with `ERROR_INVALID_PARAMETER`.
|
||||
- **Mapping:** `XMemVirtualAlloc(MEM_RESERVE | MEM_64K_PAGES, XMEM_MAPPABLE)` reserves a placeholder, and `XMemMapPhysicalPages` maps into it. It replaces pages already mapped there, a NULL page array unmaps, and an unmapped range stays reserved and can be mapped again. Scatter checks every entry before changing any, and a 0 tag unmaps its slot. Mapping outside a mappable reservation is refused. A NULL address remains a BetterXen extension for synthetic fixtures: the shim picks the span, and unmapping it frees it.
|
||||
- **Title-managed placeholders:**
|
||||
- `XMemVirtualAlloc(MEM_RESERVE | MEM_RESERVE_PLACEHOLDER)` reserves a placeholder the title splits itself with `VirtualFree(MEM_PRESERVE_PLACEHOLDER)`.
|
||||
- `MEM_REPLACE_PLACEHOLDER` with `XMEM_MAPPABLE` turns a split part into a mappable range without a new reservation. It is refused unless the part is still a placeholder.
|
||||
- `XMEM_GRAPHICS_32BIT_ADDRESS` keeps new reservations below 4 GB.
|
||||
- The `PAGE_GRAPHICS_*` protection bits set a GPU view the host does not have, so mapped views use the low-byte CPU protection.
|
||||
- Replacing a placeholder with committed memory is not implemented and logs `BX_STUB_LOG`.
|
||||
- A project-authorized target build lays out its descriptor memory this way.
|
||||
- **Tests:** `test_xmem_physical` is rewritten against the documented contracts, with constants written out from the documentation, and fails against the previous `xmem.dll`. `test_xmem`, `test_xmem_external_charge`, `test_d3d12_placed`, `test_d3d12_vmem_xbox`, `test_m2_first_frame` and `test_integration_boot` use the documented signatures.
|
||||
- **Not covered:** `XMemVirtualQuery`, `XMemGetWorkingSetStatistics` and `XMemTransferMemory` still differ from their documented signatures (#642).
|
||||
- A recognized BetterXen `BXVM` configuration is validated before an unwritable output can trigger the logged fallback. Invalid sizes still return `E_INVALIDARG` on read-only pages.
|
||||
- `d3d12_xs.dll!D3D12XboxCreateDevice` takes the documented four parameters `(pAdapter, pParameters, riid, ppDevice)`. Before, it took three `(params, riid, ppv)`, so a title calling it as documented had its interface ID treated as the out pointer, and the shim wrote through it. On a project-authorized target build that faulted on a write into read-only data. Source: the authorized GDK documentation of the function and of `D3D12XBOX_CREATE_DEVICE_PARAMETERS`. A NULL parameter block now fails with `E_INVALIDARG`, as documented. A non-NULL adapter is logged and the default host adapter is used, which is an inference, since BetterXen has no adapter objects. Of the parameter block only `Version` is read and logged. All fixtures that create a device pass a zeroed 80-byte parameter block. `test_d3d12_xs` checks the NULL-parameter refusal and that it clears the out pointer.
|
||||
- The docs anchor audit now slugs a heading's **rendered** text, so an inline link contributes only its link text instead of its text plus its URL (#632). `markdown_slugs()` ran on the raw source, so `## Setup [guide](other.md) notes` produced `setup-guideothermd-notes` where GitHub renders `#setup-guide-notes`; the same applied to `README.md:53`, whose anchor is `#active-milestone--m2-first-rendered-frame--shader-format-gate` but slugged with the milestone URL appended. Nothing linked to those anchors yet, so `main` passed, but the first link written exactly as GitHub displays it would have been reported as a broken fragment.
|
||||
- Inline links are now replaced with their text before slugging (the `(?<!\!)` guard leaves images alone). Link syntax inside a **code span** still counts literally, as GitHub renders it, so code spans are set aside before the substitution and restored afterwards; without that, a heading whose code span contains link syntax lost the URL where GitHub keeps it (the observed anchors were `code-x-span` and `code-xy-span` respectively). Every rule here was checked against GitHub's own renderer via its Markdown API, and the new unit tests fail on the previous implementation. Evidence class D.
|
||||
- `xg_xs.dll`'s `SW_64KB_S` copy path now bounds each offset by the buffer that offset belongs to. `CopyFromSubresource` passes the caller's linear image as `resource` and the tiled resource as `image`, so the old check compared the image offset against the *tiled* size and the tile offset against the *image* size; with a caller row pitch wider than the tight row, a short destination passed and the copy wrote past it (AddressSanitizer: 4-byte heap-buffer-overflow on a 2x2 RGBA8 readback with a 1000-byte pitch into a 1004-byte buffer that needed 1008). The bounds now follow the direction (`to_resource`), and `test_xg_xs` gains a short-readback case that must return `E_INVALIDARG` and leave its canary intact. `CopyIntoSubresource` was not affected.
|
||||
- Also corrected two stated reasons: the RB+ table choice is inert for `SW_64KB_S` (`GFX10_SW_64K_S_PATINFO` and `GFX10_SW_64K_S_RBPLUS_PATINFO` select the same nibble indices at every element size, so the comment no longer claims they differ for this mode), and a non-zero depth pitch is now required to cover one slice at the caller's row pitch (`blocks_h * row_pitch`), not the tight row — the old bound accepted a pitch smaller than a slice.
|
||||
- `test_xg_xs.exe` `test_sw64kb_s_round_trip` sized the `R8G8B8A8_UNORM` texture with the BC block dimension (`tile_bx * 4`, `tile_by * 4`), requesting a 512×512 texture (16 tiles, 1 MiB) while passing a 64 KiB resource. `CopyIntoSubresource` correctly returned `E_INVALIDARG`, cascading into the offset and byte-identity checks. The fixture now scales by the format's actual block dimension: 1 for `R8G8B8A8_UNORM`, 4 for BC1/BC7. BC1 and BC7 dimensions are unchanged.
|
||||
- `xg_xs.dll` computes `SW_64KB_S` tile addressing for `TEXTURE2D`, one array slice and one mip, over the element sizes AMD's public AddrLib RB+ tables specify: 32-bpp `R8G8B8A8_*` (4-byte elements) and the **BC family** — BC1/BC4 with 8-byte blocks and BC2/BC3/BC5/BC6H/BC7 with 16-byte blocks, where one "texel" element is a 4x4 block and `elemLog2 = log2(block_bytes)` (#505). `GetTexelElementOffsetBytes` returns a real byte offset for all of them instead of `E_NOTIMPL`: `pdep(x, x_mask) | pdep(y, y_mask)` over **block** indices, with per-element-size masks expanded by hand from `GFX10_SW_PATTERN_NIBBLE01/2/3` at the `GFX10_SW_64K_S_RBPLUS_PATINFO` indices (AddrLib, MIT, public in Mesa and AMD PAL). At 32 bpp the x mask `0xAA8C` equals Microsoft's public `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE` `xBytesMask` `0xAA8F` with the two intra-texel byte bits cleared, and the y mask matches `0x5570` exactly — two independent public sources agreeing, which is why S is the mode implemented. The 8-byte (`0xAAC8`/`0x5530`, 128x64-block tile) and 16-byte (`0xAAC0`/`0x5530`, 64x64-block tile) rows are AddrLib-only. All three mappings were checked to be bijections over the 64 KiB tile (16384 / 8192 / 4096 distinct, block-aligned offsets) against an independently written pdep reference. `GetResourceBaseAlignmentBytes` reports the 64 KiB tile alignment, and `CopyIntoSubresource`/`CopyFromSubresource` move blocks in swizzle order. `test_xg_xs.exe` re-derives its expected offsets from those masks rather than from the shim: per-format block sizes (8 vs 16 bytes), intra-block offsets (the 16 texels of a BC block share one byte offset), independently derived absolute offsets, and an offset -> texel -> offset round trip. It keeps asserting `E_NOTIMPL` for what is still unimplemented.
|
||||
- **Still `E_NOTIMPL`, deliberately:** `SW_64KB_D` (it differs from S at 32 bpp - the masks swap address bits 6 and 7), `SW_64KB_R` (no public GFX10 form: Mesa marks `ADDR_SW_64KB_R` Reserved, and the render-target mode `ADDR_SW_64KB_R_X` XORs on a pipe/packer configuration that is not public), TEXTURE1D/3D, MSAA, and every multi-mip or multi-slice case, because the mip tail is adapter-specific by Microsoft's own wording. `XGSuggestSwizzleMode` still returns the linear mode.
|
||||
- **Caveat:** BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are local constants, not the real `XG_SWIZZLE_MODE` values, which are NDA.
|
||||
- **Not run:** live CrossOver execution; cross-compiled and export-verified only. Synthetic evidence; no Xbox-hardware claim.
|
||||
- `d3d12_xs.dll` now **refuses** a shader stage whose wave is wider than 32 lanes, instead of creating a pipeline D3DMetal will not run (#591). `#453` measured that a `[WaveSize(64)]` PSO is created and then silently produces nothing: every output word keeps its sentinel. The gate detected it (`known_d3dmetal_gap`) but only logged `shader_d3dmetal_gap` and returned `S_OK`, so a caller saw success and drew nothing. Such a stage now returns `E_NOTIMPL` with `*ppv == nullptr`, logs `decision=reject_wave_wide` on the `shader_gate` record and keeps the `shader_d3dmetal_gap` record.
|
||||
- **Stance: refuse, not lower.** Lowering 64 lanes to 32 is a semantic transform — reductions, lane indices, 64-bit lane masks, cross-half permutes and group barriers all change meaning — and cross-lane agreement has no general solution without knowing the kernel. Lowering is M3 work; this change converts a silent no-op into a caller-visible error in the meantime.
|
||||
- **Scope:** the wave-width predicate is separated from `known_d3dmetal_gap`, so 64-bit atomics remain warn-only until their detection is complete (#589). `abi/` unchanged; `d3d12_xs.dll` still exports 4. `test_shader_gate` now asserts the refusal and the `reject_wave_wide` record; it previously only printed `hr` for the wave64 PSO. **`test_shader_gate.exe` was not executed** — no CrossOver on this host; the fixture was cross-compiled warning-free.
|
||||
- `bx-cli trace` now also groups the `shader_d3dmetal_gap` records by `(pso, stage)` (#590), reporting each group's count together with its `wave_lanes_min` and `atomic64_flags`, in deterministic first-seen order, so a run says which pipeline **kind and stage** are created-but-not-run. `pso=` is the pipeline kind the gate passes in (`graphics` or `compute`), not a per-pipeline identity: the emitter only ever writes those two literals, so `(pso, stage)` has at most six values and 40 affected compute pipelines collapse into `40x pso=compute stage=CS` (review on #593). The distinct `(wave_lanes_min, atomic64_flags)` variants separate them only where their constraints differ. The #496 per-record list and every existing summary line are unchanged; the grouped view is additive. A record with a missing or empty `pso`, `stage`, `wave_lanes_min` or `atomic64_flags` is grouped under `unknown` and counted (`gaps w/o pso/stage`, `gaps w/o constraints`) rather than dropped or guessed. The summary only reflects records a run wrote; it adds no live run, and no live CrossOver run was performed for this change.
|
||||
- `GameInput.dll` now implements `IGameInput::CreateDispatcher` (v0 slot 14) and a new `IGameInputDispatcher` object (`IUnknown` + `Dispatch` + `OpenWaitHandle`) (#500). `CreateDispatcher` returns `E_POINTER` for a null out-pointer and `S_OK` with a fresh reference-counted dispatcher otherwise, without changing the `IGameInput` singleton's own refcount. `OpenWaitHandle` returns a new manual-reset event per call (caller `CloseHandle`s it); `Dispatch` returns `false` for every quota including 0, because this shim has no real background input work, so the documented "flush at least one item even at quota 0" shape is honoured trivially — no real work is scheduled. `QueryInterface` serves only `IID_IUnknown`: the v0 dispatcher IID is not published in the public Microsoft Learn / GDK documentation, so no GUID was invented; any other queried id is logged (`qi_unsupported`) and answered `E_NOINTERFACE`. A live dispatcher reference count on the singleton logs `dispatch_mode` (`mode=manual` / `mode=automatic`) on each transition, matching the documented manual/automatic-dispatch lifetime rule. `test_audio_input.exe` now exercises slot 14: null-out errors, `QueryInterface`/`AddRef`/`Release` counting, `Dispatch` return values, `OpenWaitHandle` success + `CloseHandle`, `Release` returning 0 on the last reference (the test confirms the count, not the deallocation itself). The returned wait handle is created non-signaled and this shim never signals it, because there is no background input work to make it ready, so a caller that waits `INFINITE` blocks; poll with a timeout or call `Dispatch` instead. `GameInput.dll` still exports exactly `GameInputCreate @1`. Cross-compiled and export-verified only; the EXE was not run under CrossOver on this host.
|
||||
- `bx-probe`'s PE32+ parser is hardened and now has real coverage (#507). `rva_to_off` computed `s.raw_ptr + delta` as a `u32` add, which wraps on a crafted image (e.g. `0xFFFFFFF0 + 0x20` → `0x10`, a byte offset near the start of the file instead of ~4 GiB). It now uses a checked 64-bit-safe add and returns `None` on overflow. `Vec::with_capacity(section_count)` allocated from an unvalidated `u16` before the section table was bounds-checked; the table is now validated to fit first. `u32_le(...).unwrap_or(0)` on the import data-directory read treated a truncated directory as "no imports", indistinguishable from a genuine zero; it is now a real error. The import descriptor walk is bounded by the image size and by a checked `desc_off` increment, so a malformed table cannot run past the end.
|
||||
- **Tests:** 9 new unit tests built from synthetic byte buffers (no real DLLs, no network): a minimal valid PE32+, a two-DLL import table (one by name, one by ordinal), truncation at every header boundary, a section whose `raw_ptr` would wrap, `section_count` larger than the file, a PE32 (0x010B) image, and an import directory outside all sections. `rejects_section_rva_mapping_that_would_wrap_u32` was confirmed to **fail** when the `u32` add is re-introduced and to pass with the fix. `PeSummary` now derives `PartialEq`/`Eq` for the assertions.
|
||||
- **Compatibility:** every public signature in `PeSummary`, `ProbeError`, `probe_pe32_plus` and `classify_dll` is unchanged for `bx-cli`; `cargo test --locked --workspace` (including `bx-cli`) passes.
|
||||
- **Import data-directory bounds:** the import entry (data-directory index 1, an RVA/size pair) is now validated before it is read: its index must be `< NumberOfRvaAndSizes` AND its 8 bytes must lie within `SizeOfOptionalHeader`, so a short optional header can no longer make the RVA/size read bytes from the section table. The 20-byte `IMAGE_IMPORT_DESCRIPTOR` walk is bounded by BOTH the declared directory `Size` AND the containing section's raw bytes, whichever ends first, stopping at a null terminator or when the next descriptor would exceed the directory. New synthetic regressions: a short `SizeOfOptionalHeader` that puts the import entry out of range, `NumberOfRvaAndSizes == 1`, and a directory `Size` shorter than the section so descriptors past the declared size are not reported.
|
||||
- `XTaskQueueSubmitDelayedCallback` now **honours a non-zero delay** instead of logging a stub and submitting immediately (#515). `core_tq_submit_delayed` in `shims/xgameruntime/com_dispatch.cpp` discarded `delay_ms` and fell through to `XTaskQueueSubmitCallback`, which has no delay parameter, so the callback ran on the next dispatch and the call still returned `S_OK` — a caller scheduling a backoff or deferred teardown was told the delay succeeded when it had not happened.
|
||||
- **What changed:** each queued task carries a `GetTickCount64` deadline (`Task::due_ms`, zero meaning due now). `XTaskQueueSubmitDelayedCallback` sets it; `XTaskQueueSubmitCallback` forwards with `delay_ms == 0`, so the common immediate path is unchanged. Dispatch gates on the deadline: a delayed head holds FIFO order until it is due, and `XTaskQueueDispatch` waits exactly until that deadline (or the caller's timeout) rather than spinning.
|
||||
- **Log:** the record now names the consequence — `queued delay_ms=N` — instead of the old `(nonzero_delay)` text, which named only the symbol. It is emitted at `INFO` rather than as a stub warning, since the delay is now implemented.
|
||||
- **Underflow guard:** the wait computes `due_ms - now`, and the deadline can pass between the due check and the clock read; the subtraction is saturating, because an unsigned wrap there would block for ~584 million years.
|
||||
- **Infinite-sleep clamp:** `delay_ms` is a `uint32_t`, so `0xFFFFFFFF` is a valid delay (~49.7 days), and a remainder of exactly `0xFFFFFFFF` used to be passed to Win32 `Sleep`, where `INFINITE` means "wait forever": the loop never woke to re-check the deadline, so the callback never ran on the lanes that sleep out the remainder themselves. The chunk calculation is now the `finite_sleep_chunk_ms` helper in `shims/xgameruntime/task_queue.h`, which clamps every chunk to at most `INFINITE - 1` (`0xFFFFFFFE`) and is always positive. The test asserts the clamp for a `0xFFFFFFFF` remainder without waiting 49 days, and that a `0xFFFFFFFF` delay is still accepted and its callback fires on both the `parallel` and manual lanes.
|
||||
- **Every lane, not just `dispatch()`:** the gating had to cover the gateways that do not go through `XTaskQueueDispatch` at all — the `parallel`/`serialized` threadpool worker (which popped and ran a delayed head as soon as it was pushed), `immediate` mode, and a closed manual lane (which runs pending work on the submitting thread). All four now wait out the deadline, so a delayed callback cannot fire early on any path.
|
||||
- **Test:** `test_xgameruntime.exe` reaches slot 19 through `QueryApiImpl`'s `IXGameRuntimeCore` COM object (it is not an export). Covered: `delay_ms == 0` still runs on the next dispatch; a 100 ms delay does not run at ~0 ms nor after a 10 ms sleep, and does after 250 ms; the callback receives its context and a `cancelled == false` flag, checked with a canary in the caller's record; a dispatch `timeout` shorter than the deadline returns "nothing ran" and ends on the timeout rather than the deadline; a delayed head holds FIFO so a later immediate task cannot overtake it; closing a manual lane with a 60 s delayed task pending runs it as a **cancel**, not a normal run; and the **pool path** — a `parallel` work lane — does not run a 100 ms delayed task during the first 10 ms. Margins are 10 ms early / 250 ms late against a 100 ms deadline, deliberately wide so a slow host is not flaky.
|
||||
- **ABI:** `abi/defs/xgameruntime.def` unchanged (49 exports); the delayed entry point is a COM slot, not a new export.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `tests/conformance/test_d3d12_xs` now checks the padded `BxBeyondPublicVtableNN` slots that `gen_proxy.py` (`PAD_SLOTS = 32`) appends after each generated `d3d12_xs` proxy vtable (#547), so a caller indexing past the interface it was handed lands on a logged `E_NOTIMPL` stub instead of unrelated memory — the guard for exactly the console-only-method case. Before this, `grep -n 'E_NOTIMPL\|beyond_public\|pad' tests/conformance/test_d3d12_xs/main.cpp` returned **nothing**, so the `E_NOTIMPL` return, the log record, and the **presence** of the 32 slots were all unverified; the generator could have stopped emitting them and no test would have noticed. Indices are derived from the generated code, not guessed: `ID3D12Device10` **79**, `ID3D12CommandQueue` **19**, `ID3D12CommandAllocator` **9**, `ID3D12GraphicsCommandList7` **81**, cross-checked by parsing `proxy_generated.cpp` for the `BX_VTABLE_STUB_LOG("<leaf>", N u, "beyond_public_vtable")` calls (all four have exactly **32**). Coverage is boundary-only: for each of the four proxies the fixture calls just the **first** (`BxBeyondPublicVtable00`) and **last** (`BxBeyondPublicVtable31`) padded slot — 8 calls in total, not all 128 — and requires `E_NOTIMPL` without a crash, plus a `BX_LOG_FILE` `unimpl_vtable` record naming the slot and `beyond_public_vtable` (the log check `skip`s when `BX_LOG_FILE` is unset, matching the fixture's existing behaviour). `abi/` and `gen_proxy.py` unchanged. **`test_d3d12_xs.exe` was not executed** — no CrossOver on the authoring host.
|
||||
- `test_d3d12_placed` now captures the host identity associated with the cached backing heap before its final same-host check. It previously compared device B with a later, unrelated proxy's host log entry; all 147 checks remain intact.
|
||||
- `bx-d3dmetal-harness` no longer panics on an overflowing `--timeout` (#586). `runner.rs` computed `Instant::now() + timeout`, and `Add<Duration> for Instant` panics on overflow, so a user-supplied value like `9223372036854775807` aborted the harness with exit 101 and a Rust backtrace instead of one of its documented verdict codes. The deadline is now `Option<Instant>`: when `checked_add` cannot represent the requested timeout, the probe runs without one. The first version of this fix substituted `Duration::from_secs(1 << 62)`, which is itself beyond the monotonic clock's range on common targets, so its `expect` panicked with the same exit 101 (review on #587). `main.rs` still rejects 0. New test `an_overflowing_timeout_does_not_panic` runs a probe with `Duration::from_secs(u64::MAX)`; it panics on the previous implementation and passes now. `cargo fmt/clippy/test` pass (23/23 harness unit tests). No ABI or export change; no live D3DMetal run was needed.
|
||||
- `bx-cli` system32 staging now rolls a published shim back when the `.bx-staged` manifest write fails, so the next run does not refuse bx-cli's own file as foreign (#573). The publish happened before the manifest write and the error path discarded only temporary files, leaving a regular file in `system32` with no manifest entry; the next run then reported `already exists and was not staged by bx-cli (or was changed since)` and only manual deletion unblocked it. A `Copied` file is now removed and a replaced one restored **from a snapshot taken before the rename**, with the manifest left exactly as it was. The first version of this fix read `dst` *after* the rename, so it restored the bytes it had just written; `a_manifest_write_failure_restores_the_previous_bytes` now proves the old bytes come back (it fails on that version). New unit test `a_manifest_write_failure_leaves_no_unowned_file` pre-creates `system32/.bx-staged.<pid>.bx-staging` as a directory; it fails on the previous implementation and passes now. This restores the invariant `stage.rs` and the changelog already claimed.
|
||||
- Merge eligibility rules in `AGENTS.md` §7 and `CONTRIBUTING.md`: a PR's original author does not merge it, other maintainers may push fixes and still merge, and substantive changes need approval from someone who did not write them. The `Protect main` ruleset no longer requires approval of the most recent push from someone other than the pusher; every changing push still dismisses approvals. A new `Merge policy audit` workflow fails after an author self-merge; it detects but cannot prevent one.
|
||||
- `XCRDAPI.dll!DStorageGetFactory` now also dispatches the Xbox Series DirectStorage COM interfaces (`IDStorageFactoryX`, `IDStorageFileX`, `IDStorageStatusArrayX`, and `IDStorageQueueX`) over the existing batched `WorkQueue`/`StorageFile`/`StatusArray` engine while preserving the public PC DirectStorage interfaces and synthetic `bx::storage` interfaces. The IIDs, vtable slot orders and request layout are inferences from call-site observation of a project-authorized target build, not a public contract, and their provenance is pending maintainer review. Compressed requests return `E_NOTIMPL`. Unimplemented vtable slots log through `BX_VTABLE_STUB_LOG`. `IDStorageQueueX::RetrieveErrorRecord` is a logged stub and leaves the caller's buffer untouched until the Xbox output layout and size are verified. The PC queue's record behavior is unchanged. Added synthetic conformance coverage in `tests/conformance/test_xcrdapi_xbox/`, including the buffer canary and queue error diagnostics. `IDStorageFactoryX::SetStagingBufferSize` returns `S_OK` and logs that the size has no effect, like the public factory, and `CreateQueueX` ignores the queue priority on purpose, because the Xbox priority range is not part of the inferred contract. `test_xcrdapi_xbox` requires `BX_LOG_FILE` and reads only the records its own run appended. It also covers a memory request on a file queue (`E_DSTORAGE_INVALID_SOURCE_TYPE`), a source/destination size mismatch (`E_DSTORAGE_INVALID_DESTINATION_SIZE`), an out-of-range status index (`E_DSTORAGE_INDEX_BOUND`), a null memory source (`E_INVALIDARG`) and a request enqueued after `Close` (dropped and logged).
|
||||
- `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 from this header:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source; they are served separately, from target-build observation (see the `IDStorage*X` entry above). Provenance of the vendored header 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`'s `cleanup_runs_outside_the_callers_process_group` test now observes the fake `wineserver`'s PGID with macOS's bundled Perl and its built-in `getpgrp` instead of `/bin/ps` (#558). `/bin/ps -o pgid= -p $$` returns `Operation not permitted` on restricted macOS hosts, making the fake server exit 126 and failing an otherwise unrelated supervision test. The test still records one PGID for each `-k` and `-w` invocation and asserts both differ from the caller's group. Test-only change; no supervision behavior changed.
|
||||
- `AcpHal.dll` now rejects `ApuCreateHeap(0, 0)` with `E_INVALIDARG` (#580). The call previously reported `S_OK` and set `heap_created = true` with `capacity == 0`, representing a heap that could never satisfy an allocation; `ApuAlloc` still rejected requests with `E_OUTOFMEMORY`. `ERROR_BUSY` is still returned first when allocations are live, so the existing busy-path assertion is unchanged. `test_audio_input` now asserts the zero-capacity call is rejected and that `ApuAlloc` still fails with `E_OUTOFMEMORY` before a real heap is created. `abi/` unchanged (9 exports). **`test_audio_input.exe` was not executed** — no CrossOver on this host.
|
||||
- `docs/claims.toml` now defines evidence classes A, B, D, E and U in a legend derived from their existing claims and prose usages (#549). `docs/README.md` now lists the complete vocabulary and describes the file as a claim ledger. No claim's class was changed. The legend records that the in-tree `AGENTS.md` §5 refers to `claims.toml` and does not contain the longer vocabulary named in the issue. Class E explicitly covers both public tool/format documentation and observed tool behavior, with the claim's `test` field distinguishing documentation review from execution; `CLAIM-DXCONTAINER-PAYLOAD` and `CLAIM-LLVM-GFX1030` are documentation-only examples and are not reclassified here.
|
||||
- Documented the conformance exit-status contract: `bx-cli run` returns the guest's status unchanged, and fixtures that cannot reach a conclusion exit **77** with a `SKIP: <reason>` line (#563). `tests/conformance/README.md` now gives a `case` recipe that records PASS / UNAVAILABLE / FAIL separately, so a skip is never counted as a pass (AGENTS.md §5). `docs/research/d3dmetal-gpu-limits.md` states the fixture's 0/1/77 outcomes and links the recipe. Documentation only; no fixture or runner behaviour changed.
|
||||
- `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.
|
||||
- `scripts/audit/docs_hygiene.py` now detects the **diff3** conflict marker `||||||| merged common ancestors` (#583). `MARKER` matched `<<<<<<<`, `=======` and `>>>>>>>` only, so a `git merge --diff3` conflict resolved down to just its base line passed the Repository hygiene gate. Added `MarkerTests` (all four markers, a full diff3 block, and negative controls for table/prose lines) and `WorkflowTests` (valid and invalid YAML, using temporary fixtures). `.github/workflows/hygiene.yml` now runs `python3 -m unittest scripts/audit/test_docs_hygiene.py` as a CI step, so the suite is gated rather than advisory. Fault injection: removing the `\|{7}` alternative makes 3 of the 25 tests fail; with it, all 25 pass. `python3 scripts/audit/docs_hygiene.py --require-yaml` reports 199 tracked files, 0 problems. **Stacked on PR #538**, which creates `test_docs_hygiene.py`.
|
||||
- `tests/conformance/test_veh_clwb` now verifies the `clwb` decoded instruction length (`len=`) that `bx_runtime_veh.dll` logs and uses to advance RIP (#539). The fixture reads `BX_LOG_FILE` (it fails with a clear message when `BX_LOG_FILE` is unset: the EXE imports `bx_runtime_veh.dll`, which reads the variable in `DLL_PROCESS_ATTACH`, so a temp log set in `main` would never be written) and asserts the `len=` values on the sampled `clwb_trapped` records. `log_sampled_trap` logs only traps 1, 2, 4, 8, …, so six `clwb` forms produce exactly three records (`total_traps=1, 2, 4`); the assertions cover **only those sampled records** — `total_traps=1` → `clwb (%rax)` → len 4, `total_traps=2` → `clwb 0x40(%rax)` → len 5, `total_traps=4` → `clwb (%r8)` → len 5 — plus a `len >= 4` floor on every observed record. Forms 3, 5, 6 (`clwb 0x100(%rax)`, `clwb 0x40(%rax,%rcx,4)`, `clwb 0x0(%rip)`) are **not** covered by a `len=` assertion. Expected lengths were re-derived by assembling with `x86_64-w64-mingw32-as` and disassembling with `x86_64-w64-mingw32-objdump -d`. The existing `delta == 6` trap-count check is unchanged. `test_veh_clwb.exe` passes live on CrossOver 26.3 under `bx-cli run --log` (records `len=4` and `len=5`), and fails with a clear message when `BX_LOG_FILE` is unset. Record fields are parsed with a checked `strtoull`, so a malformed record cannot throw past the failure message.
|
||||
- `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` no longer return a bare `S_OK` for work they did not do (#509). They logged a stub and reported success while ignoring their arguments: `Allocate` discarded its only parameter (unnamed) and `Release` takes no parameter at all, so neither could be held to anything. Both now return `E_NOTIMPL` and keep their `BX_STUB_LOG` record, so `bx-cli trace` still surfaces the call and a caller is told to fall back rather than being told the work happened.
|
||||
- **NDA constraint:** the public Microsoft Learn page for `AcpHal` returns HTTP 200 with only the membership gate, so the true signatures and the shape-context layout are **unknown** from public sources, including whether `Release` should take an argument. `E_NOTIMPL` is therefore BetterXen's choice, not the console's; no signature was invented and `abi/defs/AcpHal.def` is unchanged (9 exports).
|
||||
- **Tests:** `test_audio_input.exe` calls both through the DLL: null and sentinel pointers must not crash and must return `E_NOTIMPL`; calling `Release` twice must also return `E_NOTIMPL` (idempotent); and when `BX_LOG_FILE` is set it asserts both symbols still appear on `unimpl_api` lines, printing an explicit `SKIP` rather than a pass when the variable is unset.
|
||||
- `test_win32_bridge.exe` now asserts that the PSM **context pointer round-trips** through the JSONL (#519). #514 stored `(token, callback, context)` and logs `context=0x%llx`, so the context is observable — but the test only counted `callback_unfired` records, so a dropped (`context=0x0`), swapped or mis-tagged context would have passed unnoticed, leaving the storage decorative. The context field is parsed from the value after `context=`. The original version of this check parsed from the key, read the hex digit `c` and got `0xc` for every record, so it could never pass.
|
||||
- **What is checked:** every logged `context=` on **both** families must be non-zero and present in the set of `&entry` pointers the test actually passed; at least **two distinct** pointers must appear per family, so one registration cannot overwrite another's; and each family's set must cover the whole `&entry` set, which is what catches a swap or mis-tag between families. A record with a missing or malformed `context=` fails.
|
||||
- **Limit, stated rather than asserted:** the shim's unregister records carry only a detail string (`unregistered` / `foreign_token` / `unknown_token`), so **context-drop on unregister is not observable** in the log. The test documents that and prints a note if a future shim starts logging context there.
|
||||
- **Base:** this sits on #514, which introduces the `context=` field; it rebases cleanly once that merges.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `win32_bridge`'s PSM notifications now **store** the callback and context they accept, and **say** that they never fire it (#513). `register_notification` in `shims/win32_bridge/psm_appnotify.cpp` validated `callback` for null and then dropped it: nothing stored it, nothing ever invoked it, and the context pointer was discarded as `PVOID /*context*/`. So `ERROR_SUCCESS` meant "token allocated", not "you will be notified", and neither the code nor the log said so.
|
||||
- **What changed:** each registration now keeps a `(token, callback, context)` record in the process-heap-backed open-addressed table under the existing `SRWLOCK`; it starts at 64 slots and grows as needed, with allocation failure reported as `ERROR_NOT_ENOUGH_MEMORY`. The exported wrappers thread `context` through instead of discarding it; unregistering drops the record so no later event can reach a retired registration.
|
||||
- **Honesty:** a comment on `register_notification` and the JSONL detail (now `registered_offline callback_unfired`) both state that the callbacks are accepted and currently **never invoked**, because this shim has no source of app-state or constrained-change events and the console firing contract is not publicly documented. **No firing policy was invented** — the callback is deliberately left unfired rather than called spuriously to look implemented.
|
||||
- **Test:** `test_win32_bridge.exe` now also asserts that no callback fires, and that every registration's log detail carries `callback_unfired` (state and constrained counted separately). The existing per-event JSONL counts still pass unchanged, since the detail grep is a substring match.
|
||||
- **ABI:** `abi/defs/api-ms-win-core-psm-appnotify-l1-1-0.def` and `-l1-1-1.def` unchanged (2 exports each); all six API-set DLLs keep their original export counts.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `dxbc-accc` now exposes a **bounds-checked chunk-lookup API** on `ShaderInspection` (#521). `chunk_payload(&container, &fourcc)` returns the payload of the first chunk tagged `fourcc`, and `has_chunk_tag(&fourcc)` answers presence **without** trusting the declared size. Both **reuse the already-parsed `chunks` vector** rather than re-walking the raw table; `chunk_payload` rejects offsets inside the DXBC header/offset table and validates `offset + 8 + size` against **both** `container_size` and `container.len()` with checked arithmetic, returning `None` instead of panicking.
|
||||
- **Why:** `dxbc-accc` already parsed the table into `ChunkInfo { fourcc, offset, size }` but exposed **no public lookup**, so `shims/d3d12_xs/shader_gate.cpp:94` re-implements the same bounds-checked walk in C++ (`find_chunk`), plus a second variant `has_chunk_tag` that ignores the declared size. Two parsers for one container is how a fix lands in one and not the other.
|
||||
- **Semantics:** `offset` points at the 8-byte chunk header (fourcc + size), so the payload begins at `offset + 8`. A zero-size chunk yields `Some(&[])` (the header is present and in-bounds); callers needing a minimum size must check the returned length. When several chunks share a FourCC, the **first** in table order wins, matching the C++ `find_chunk`.
|
||||
- **Scope:** the C++ gate is **not** migrated here — `find_chunk`/`has_chunk_tag` in `shader_gate.cpp` stay for now, and the PR names the migration as a follow-up, since it is a larger change needing a live run. `abi/defs/bx_shader_bridge.def` unchanged (3 exports).
|
||||
- **Tests:** 7 new unit tests: `SFI0` and `PSV0` payloads returned exactly; a declared size past the container → `None`; an absent FourCC → `None` and `has_chunk_tag == false`; a zero-size chunk → `Some(&[])`; an exact-fit chunk at the container end (no off-by-one); a truncated container slice → `None`; and duplicate FourCCs → first wins.
|
||||
- `test_shader_gate.exe` now asserts the **shape** of the JSONL it writes, so the `bx-cli trace` fixtures stop resting on a hand reading of `shader_gate.cpp` (#535). It checks, against the log the fixture actually produced: that at least one `shader_gate` and one `shader_d3dmetal_gap` record exist; that every gate record writes `pso=`, `stage=`, `decision=`, `hr=` **in that order**; that an `*_unclassified` record carries **no** `kind=`; that every gap record has `pso=`, `stage=`, `wave_lanes_min=` and the colon that ends its structured part; and that no `key=value` value is split by a space — the assumption `parse_key_values(..., false)` rests on.
|
||||
- **Why shape, not counts:** decision and kind totals vary by GPU, so they are not asserted. What is asserted is the field order and the token boundaries the summarizer depends on, which a hand-typed fixture could get wrong without any test noticing.
|
||||
- **Executed natively, not under CrossOver:** the assertions compile and link, and their logic was checked in a native harness against a sample log — including a **negative control** where an `atomic64=typed, raw` value containing a space correctly trips the check. `test_shader_gate.exe` itself was **not** run here; that still needs a CrossOver host.
|
||||
- Placed resources created via `CreatePlacedResource` retain the shim heap's budget charge until their final release. The D3D12 backing map returned in `cpu_pointer` expires when the region changes or another host device replaces the cache. Concurrent device creations wait for both proxy hooks to be installed (#464).
|
||||
- `D3D12ConfigureVirtualMemoryX` copies a BetterXen version-1 block only when the first 8 bytes are magic `BXVM` (`0x4D565842`) and the struct size. The caller's pointer is not kept. `cpu_pointer` is written only before that call returns (the current persistent map, or 0). After `CreateHeap` builds the backing heap, a second call with the same region reads the map and does not recreate the heap. `CreateHeap` returns that one `WRITE_BACK` / `L0` heap only when the block sets `BX_D3D12_VMEM_FLAG_BACKING_HEAP` and the desc is `CUSTOM`, `WRITE_BACK`, `L0`, `D3D12_HEAP_FLAG_NONE`, alignment 0 or 64 KiB, node masks 0 or 1, and the configured size. Every other `CreateHeap` forwards the desc unchanged and returns the host `HRESULT`, wrapped so the live-heap charge against the xmem title budget is credited on the final `Release` (`E_OUTOFMEMORY` only when that budget is exceeded). The wrapper answers `ID3D12Heap1` when the host heap does. `CreatePlacedResource` on any other heap forwards the placement parameters to the host. On the backing heap the offset must be a multiple of the alignment `GetResourceAllocationInfo` reports and the resource must fit. A null output pointer on `CreateHeap` or `CreatePlacedResource` is forwarded to the host with no budget charge and no wrapper. `GetDevice` on every heap wrapper returns the `BxDeviceProxy`. An ordinary heap `AddRef`s that proxy until the wrapper's final `Release`, matching `BxChildProxy`, so the caller can release the device and keep the heap. The process-wide backing heap does not: the cache would keep the device and its budget charge alive. Its pointer is weak. It is cleared when that heap leaves the cache, including a region change or a different host device, and when the proxy's reference count goes from 1 to 0. A weak `GetDevice` never increments a count that is already zero, and that acquire shares one lock with the 1-to-0 release, so only one thread runs final cleanup. Handing out the cached heap checks the host and the configured size, retargets `GetDevice`, and takes the caller's reference in that same lock. A concurrent backing configuration change makes an in-flight backing request return `HRESULT_FROM_WIN32(ERROR_RETRY)` before it can publish a stale heap. `CreatePlacedResource1` and `CreatePlacedResource2` unwrap the wrapper before calling the host. `test_d3d12_placed.exe` checks aliasing, ordinary heaps, small-resource placement, `ID3D12Heap1`, config lifetime, the write-through pointer, a fence-separated GPU copy in both directions, that an ordinary heap keeps its device alive, that `GetDevice` fails closed after a reconfigure and after a forced host replacement even once the proxy is released, that those newer placement calls accept a wrapped heap, and that a second proxy forced onto the same host device places a resource in the configured region without doubling the charge (#464).
|
||||
- `bx-cli trace` now summarizes the shader-format gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list (wave width and 64-bit-atomic flags), and `shader_bridge_missing`, per [ADR 0008](docs/adr/0008-m2-shader-format-gate.md). It only summarizes records a run wrote; no live CrossOver run was performed for this change.
|
||||
- `XCRDAPI.dll` completes a multi-request batch from one `Submit()` in queue order into CPU memory, mapped D3D12 upload buffers, and default buffers (a copy on the resource's device when the heap is not CPU-visible). If that copy has been submitted and its GPU completion is not confirmed, the shim keeps the destination and the copy's GPU objects alive and logs a warning, unless the device was removed or the fence already reached the waited value. The request still returns the failure HRESULT. LZ, BCPack, and GDeflate requests finish as `E_NOTIMPL` and log `BX_VTABLE_STUB_LOG`. `DStorageGetFactory` remains the only export (#467).
|
||||
- M2 Shader Format Gate (#466). `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` classify every stage through `bx_shader_bridge.dll` (#445) and log one `shader_gate` JSONL record per stage: kind, stage, shader model, chunk sizes, `SFI0` feature flags and `PSV0` wave lane range.
|
||||
- **Decisions:** DXIL and dual containers go to the host as the bridge's prepared copy. ACCC-only containers are refused with `E_NOTIMPL` before the host is called. Legacy DXBC and unclassifiable input pass unchanged. The bridge is loaded only by full path from `d3d12_xs.dll`'s directory. A missing bridge is logged once as `shader_bridge_missing`. Shaders then pass unclassified, but a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it.
|
||||
- **D3DMetal gaps:** stages needing a wave wider than 32 lanes or 64-bit atomics also log `shader_d3dmetal_gap`, the cases #453 measured as created but not run. The structural check now counts an `ACCC` chunk as a shader chunk, so the gate decides it.
|
||||
- **Test:** `tests/conformance/test_shader_gate/` runs a real DXC SM 6.6 compute shader through `d3d12_xs` and checks 256/256 output words. It requires `E_NOTIMPL` for an ACCC-only compute and graphics shader, and checks the logged wave64 and typed 64-bit-atomic constraints and every JSONL record. It then reruns itself from a directory without the bridge, which must still run DXIL and refuse ACCC-only. It passed on one Apple M5 Pro in a CrossOver 26.3 D3DMetal bottle. A bare prefix's vkd3d cannot load a DXIL converter, so the DXIL part needs the D3DMetal backend. `scripts/build-shims.sh` stages the bridge it needs (#484).
|
||||
- **ADR:** [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) proposes Branch D1 for M3, with the evidence; it is pending maintainer acceptance.
|
||||
- `scripts/build-shims.sh` now builds and verifies `bx_shader_bridge.dll` with the shims (#484). It builds the Windows version of `shader-transpiler/crates/dxbc-accc` (#445), linked with the new frozen export list `abi/defs/bx_shader_bridge.def`, so its export directory name is `bx_shader_bridge.dll`. It places the DLL in `build-shims/bin` and checks it with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. The script now reports 17 DLLs and 111 exports.
|
||||
- **Toolchain:** `cargo` and `rustc` come from rustup when available. The build always uses `<repo>/target`, and a missing `x86_64-pc-windows-gnu` target stops the script with `rustup target add x86_64-pc-windows-gnu` (it is never skipped). The CI job installs that target with its pinned toolchain.
|
||||
- **Effect:** `d3d12_xs`'s shader gate (#466) finds the bridge in `build-shims/bin` without a manual copy.
|
||||
- Implemented the `IGameInput` v0 device-callback lifecycle (`RegisterDeviceCallback`, `StopCallback`, `UnregisterCallback`) and `SetFocusPolicy` in `shims/gameinput/gameinput.cpp` (#481). `RegisterDeviceCallback` validates `callbackFunc`, `inputKind`, `statusFilter`, and `enumerationKind` (`0..=2`), allocates unique monotonic `GameInputCallbackToken` handles under `SRWLOCK`, and supports optional null `callbackToken` output pointers; `StopCallback` marks active registrations stopped while keeping them unregisterable once via `UnregisterCallback`; `SetFocusPolicy` records focus-policy flags without stub noise. Expanded `test_audio_input.exe` to cover validation, token uniqueness, stop/unregister idempotence, and focus-policy calls.
|
||||
- `dxbc-accc` now reaches Windows guests as `bx_shader_bridge.dll`, the x86-64 Windows build of the same crate (#445). It exports exactly the three `bx_shader_bridge.h` entry points and needs no MinGW runtime DLL. `shader-transpiler/crates/dxbc-accc/guest/build.sh` builds the DLL and checks its exports and imports. It also builds `check_bridge.exe`, a C guest program compiled against the frozen header, which sends a real DXC SM 6.6 blob and eight synthetic containers (DXIL with and without trailing bytes, `ACCC`/`FSPX` v1 and v0, dual, legacy `SHEX`, malformed) through the DLL loaded by full path. It checks classification (exact chunk sizes, root signature flag, header digest, declared size), prepare (only the declared container is copied), free, and prints a DXIL vs. `ACCC` count. The build script always uses `<repo>/target` and rustup's toolchain, and checks the whole Export Address Table and an import allowlist. On one Apple M5 Pro with CrossOver 26.3, in a prefix and a D3DMetal bottle, it reported `dxil=3 accc_only=2 dual=1 legacy=1 invalid=2` and passed. Synthetic containers only. Staging the DLL in `build-shims`, an `abi/defs` export list, and the `d3d12_xs` PSO hook (#466) are separate changes.
|
||||
- `xgameruntime.dll!QueryApiImpl` now serves offline `XGameSave` and `XPackage` as COM `IUnknown` objects under BetterXen synthetic keys (#468, not yet closed). A title linked against Microsoft's `xgameruntime.lib` does not request these keys. Every synthetic key and COM slot order now lives in `shims/xgameruntime/synthetic_keys.h`, the single place to find or replace them. Signatures, structure layouts, `E_GS_*` values and container-name rules follow the public Microsoft Learn reference.
|
||||
- **XGameSave:** provider init, containers, updates, blob writes, submit and read (both asynchronous), enumeration and the close calls. Saves are separated by SCID: each container is one file under `C:\bx_pls\<hash>\saves\<SCID hash>\`, replaced atomically on submit. A named mutex per SCID directory serializes access across threads and processes. Damaged files (truncated, trailing bytes, duplicate or NUL-bearing names) read as `ERROR_FILE_CORRUPT`, and enumeration skips them and unreadable files with a log line. Offline choices where the reference is silent (16 MiB including blob names, 256-byte blob names, no sync, retry after a failed submit) are listed in `game_save.cpp`.
|
||||
- **XPackage:** the running executable's directory stands in for the installed package: a stable `BXPKG…` identifier, `XPackageKind::Game` for it, and `XPackageMount` / mount-path queries that return that directory.
|
||||
- **Lifetimes:** the last uninitialize closes every XGameSave and XPackage handle and drops unconsumed results. Closing a provider closes its containers and their updates. Each handle type has its own value range. An operation queued before an uninitialize completes with `E_GAMERUNTIME_NOT_INITIALIZED` without running.
|
||||
- **Async:** results of the new operations go through the existing XAsync engine, including `XAsyncGetResultSize`, cancellation and reuse rules. A cancel that arrives after an operation started no longer reports `E_ABORT` for work that was done. An unconsumed result is kept until its block is reused or the runtime is uninitialized.
|
||||
- **Tests:** `tests/conformance/test_xgameruntime_saves/` covers both families through `QueryApiImpl`, with its own copies of the keys, slot numbers, structure layouts and storage format. It checks:
|
||||
- name rules, the write and read round trip, and the size limits;
|
||||
- SCID isolation and enumeration;
|
||||
- crafted damaged files, a failed replace that keeps the old save, and a successful one that replaces the file;
|
||||
- 64 threaded and 160 cross-process concurrent submits;
|
||||
- uninitialize with pending work, stale handles and released memory, and a non-ASCII executable directory.
|
||||
|
||||
Each of eleven injected faults (non-atomic write, missing or per-process lock, ignored SCID, no-op close, lax parsing, uncounted names, retained results, stale work running, children kept after a provider close) makes it fail.
|
||||
- **Not done:** validation against a caller linked to Microsoft's `xgameruntime.lib`, since these keys are BetterXen's own. `abi/defs/xgameruntime.def` is unchanged (49 exports).
|
||||
- `QueryApiImpl` also serves offline XGameSave and XPackage on the public COM class and interface ids, with slot order from [xgameruntime-docs](https://github.com/xodus-gaming/xgameruntime-docs) commit `7090008692569aa6081e30dfdd9de58237741e24` (#468). The ids and slot order come from that documentation; its provenance is recorded in `docs/research/upstream-registry.md` and the component reuse matrix, pending maintainer acceptance. `XPackageMountWithUiAsync` / `XPackageMountWithUiResult` (`IXPackageImpl2` slots 37–38) now mount through the XAsync engine, like `XPackageMount`. `IXError` slot 3 now returns `false`, following the #492 review's observation that the GDK's static library continues only on `false`; that source lists the slot as unknown.
|
||||
- Added `docs/research/d3dmetal-gpu-limits.md` and `tests/conformance/test_d3dmetal_gpu_limits/` (#453). The fixture is an original D3D12 compute test that loads the host `d3d12.dll` directly, with four original HLSL kernels and committed DXC 1.9.2609 output (`shaders/compile.sh` regenerates them). It skips with exit 77 below shader model 6.6. Required checks:
|
||||
- a kernel without `WaveSize` runs, and its lane indices form a permutation within each wave;
|
||||
- a per-texel spin lock with acquire and release fences and a 1024-try cap emulates 64-bit add and max with no dropped update and exact values.
|
||||
|
||||
Everything else is printed as `OBSERVED:` lines. On one Apple M3 Pro (macOS 27.2.1, CodeWeavers Wine 11.0 built from source, D3DMetal 4.0b3), three runs gave the same outcomes, with 4/4 required checks passing each time:
|
||||
- the `[WaveSize(64)]` pipeline is created but never runs;
|
||||
- kernels using SM 6.6 64-bit atomics, on a typed UAV or a raw buffer, are created but never run, although the device reports support for them; a plain-store marker beside the atomics shows the skip;
|
||||
- a 64-try lock cap drops 96–108 of 512 updates.
|
||||
|
||||
The note links only these measured items from the M2 and M3 roadmap rows. Observations reported from a commercial title are kept in a separate "not evidence" section, each with the synthetic workload that would verify it. This is a local implementer run, not on CrossOver 26.3 and not independently reproduced.
|
||||
- Updated `README.md` and `docs/roadmap.md` to record Milestone M0 and Milestone M1 (`#17`, 16/16 issues) as verified complete on synthetic workloads and activate Milestone M2 (`#18`, First Rendered Frame & Shader Format Gate).
|
||||
- Implemented clean-room COM `IUnknown` vtable dispatch in `xgameruntime.dll!QueryApiImpl` for the core public Microsoft PC GDK (`Microsoft.GDK.Windows 2610.0.9661`) interface families (`XAsync`/`XTaskQueue`/`XThread`, `XGameRuntimeIsFeatureAvailable`, `XSystem`, `XError`, `XPersistentLocalStorage`, `XUser`, `XStore`, `XGameUi`, `XNetworking`, `XGame`), with auto-logging `BX_VTABLE_STUB_LOG` fallback on unimplemented slots. Validated live on CrossOver 26.3 with an independently authored caller linked against Microsoft's public `xgameruntime.lib` (#456).
|
||||
- `bx_runtime_veh.dll` handles illegal-instruction traps for CLZERO, MONITORX, MWAITX, RDPRU, EXTRQ and INSERTQ (#451). The decoder and fixture derive the encodings and expected results from the AMD Architecture Programmer’s Manual [volume 3](https://kib.kiev.ua/x86docs/AMD/AMD64/24594_APM_v3-r3.36.pdf) (24594, rev. 3.36) and [volume 4](https://kib.kiev.ua/x86docs/AMD/AMD64/26568_APM_v4-r3.25.pdf) (26568, rev. 3.25, EXTRQ pp. 139–140 and INSERTQ pp. 154–155).
|
||||
- CLZERO clears a 64-byte cache line selected by RAX or, with the `67` prefix, EAX. An unwritable target is reported as a write access violation at the line address and the guest can repair the page and retry. One-shot Windows guard-page behavior is outside this emulation.
|
||||
- MONITORX arms no host monitor. MWAITX yields once, so the EBX timer and ECX extensions have no effect. RDPRU approximates MPERF and APERF with the same timestamp rate and returns zero for unknown selectors. It clears the five flags specified by AMD and chooses zero for CF, whose value the manual leaves open.
|
||||
- EXTRQ and INSERTQ implement both the immediate and register-control forms, including XMM8–XMM15. The fixture checks the defined low-quadword results with and without REX, including both length-zero forms. It also covers the MONITORX address-size override and asserts the emulated CF result only when CPUID lacks RDPRU.
|
||||
- Each instruction logs sampled `<name>_trapped` events, and `bx-cli trace` prints per-kind lower bounds.
|
||||
- **Local result:** 28/28 synthetic AMD-instruction checks passed on one Apple M5 with macOS 27.2.1, CrossOver 26.3 and Rosetta 2. Trace lower bounds were CLZERO 4, MONITORX 2, MWAITX 2, RDPRU 4, EXTRQ 4 and INSERTQ 4. The CLWB and shim export fixtures passed. The boot fixture reported 19 passed and 2 pending host API-set checkpoints.
|
||||
- `d3d12_xs.dll` can present rendered frames through a swapchain (#465, M2-C2). A caller asks the proxied command queue for a BetterXen-defined interface (`IBxPresentQueue`, in `shims/d3d12_xs/presentx.h`) and creates a flip-model swapchain on a Win32 window over the host's `IDXGISwapChain3`. This is not the console's `PresentX`: its signature is not defined in `abi/`, and no binary compatibility is claimed. No export or `abi/` file changed.
|
||||
- **Behaviour:** `Present` signals a fence and waits, for at most 5 s, until the next back buffer is idle; if that wait expires it returns `BX_PRESENT_E_NEXT_BUFFER_BUSY`, meaning the frame was presented and must not be presented again. `ERROR_TIMEOUT` from `Present` means nothing was presented. `WaitForIdle` rejects zero and infinite timeouts with E_INVALIDARG and shares one budget between lock acquisition, fence signaling, event registration and fence waiting (returning `ERROR_TIMEOUT` without signaling if lock acquisition uses the whole budget), and re-entering either call on one thread is refused. `Present` never waits for another thread's call on the swapchain: it returns `BX_PRESENT_E_BUSY` with nothing presented, so a host `Present` that depends on the caller cannot deadlock with it. On a live device, if the fence signal after a host `Present` fails, it returns `BX_PRESENT_E_COMPLETION_UNCONFIRMED` (the frame was presented); if waiting on the next back buffer after a host `Present` fails for a reason other than timeout, it logs the underlying wait `HRESULT` and returns `BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED` (the frame was presented). Post-present synchronization failures on a live device refuse further presents with `BX_PRESENT_E_NEEDS_IDLE` until `WaitForIdle` succeeds. Device-removal HRESULTs (`DXGI_ERROR_DEVICE_REMOVED` / `DXGI_ERROR_DEVICE_RESET` / `GetDeviceRemovedReason()`) are logged and returned unchanged. The recovery requirement still applies if the device reports itself as live. The final `Release` waits for the GPU and, if it cannot confirm completion, logs and leaks what pending GPU work may still touch, while releasing its queue proxy reference. Resizing and fullscreen are not implemented, and the caller records its own resource transitions.
|
||||
- **Stricter than the host:** D3DMetal 3.0 returned `S_OK` for sync intervals 5 and 100, unsupported flags and a destroyed window, so the bridge itself refuses a sync interval above 4, any present flag and a destroyed window with `DXGI_ERROR_INVALID_CALL`.
|
||||
- **Test:** `tests/conformance/test_d3d12_presentx/` renders and presents 12 frames (a clear plus a scissored shader draw) and compares all 72,000 read-back pixels with values computed on the CPU. It also checks that the bridge's buffers and index are the host swapchain's, that each present advances the host count by one, argument rejection and its log records, bounded waits (including rejection of `WaitForIdle(0)` and slow-`Signal` budgets) and the leak path with the queue deliberately blocked, a concurrent `Present`, a failed post-present signal, pre- and post-present `SetEventOnCompletion` failures, post-present device-removal passthrough (`GetCompletedValue() == UINT64_MAX`, `DXGI_ERROR_DEVICE_RESET` wait, `DXGI_ERROR_DEVICE_REMOVED` signal) injected through copied vtables, and reference lifetime against a swapchain made with host DXGI alone. `run_controls.sh` checks the failing stage of each of 6 negative controls. It reads the back buffer before presentation; it does not capture the window.
|
||||
- **Local result:** the earlier `8245c30b` revision passed 332 checks with 0 skipped on one Apple M4 (macOS 27.0, CrossOver 26.3.0.39832, D3DMetal 3.0) and was independently verified on one Apple M5 (332 checks passed, `run_controls.sh` passed). Not a check of what reached the screen, and not an Xbox hardware result.
|
||||
- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached.
|
||||
- **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first.
|
||||
- **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged.
|
||||
- **Uninitialized environments:** a bare `--prefix` without `system32` is initialized with `wineboot --init` under the same isolated environment. A bottle without one fails with a hint. Neither case is ever skipped silently.
|
||||
- **Partial shim folders:** a `--shims` folder without `xgameruntime.dll` prints a notice and the run continues without staging, as it did before staging existed.
|
||||
- **Supervision:** `--timeout`, SIGINT, SIGTERM and SIGHUP also cover the `wineboot --init` step, so an interrupted first run does not leave `wineserver` running.
|
||||
- **Tests:** 8 unit tests cover staging and the dependency walk. `tests/conformance/test_system32_staging/` makes the `LOAD_LIBRARY_SEARCH_SYSTEM32` load and requires BetterXen's shim, from `system32`, exporting `QueryApiImpl`, and the same module for `SYSTEM32 | APPLICATION_DIR`. `--expect-missing` is the negative control for an unstaged prefix.
|
||||
- **Local result:** on one Apple M3 Pro (macOS 27.2.1) with CodeWeavers Wine 11.0 built from source, so not CrossOver 26.3, and with the staging done by hand: the control passed and the unstaged run failed as expected. Staging the runtime alone still failed, which is how the dependency rule was found. Staging both passed 4/4 in two runs. `bx-cli run` itself was not run, since CrossOver is not installed on that host.
|
||||
- `bx-cli run` gained `--timeout <secs>`, cleanup of the launcher process group and the selected bottle or prefix on timeout, SIGINT, SIGTERM or SIGHUP (including re-resolving managed bottles whose first launch creates a private stub), `--backend` (bottle mode only), and a printed trace summary after a run with `--log`. The bottle to stop is located through CrossOver itself, so bottles outside the default directory are covered. A normal exit does not stop the environment. Recorded a one-host observation that D3D12 swapchains stay referenced under D3DMetal (#408).
|
||||
- Added `test_apiset_resolution`, a conformance fixture that statically imports the six API-set `win32_bridge` names and reports which module serves each (`--expect host|shim`), and accepted ADR 0007 recording that CrossOver 26.0 and 26.3 answer them via built-ins (`twinapi.appcore.dll` / `user32.dll`) (#437).
|
||||
- Added file-mapping-backed 64 KiB and 2 MiB physical pages, contiguous and scatter aliases (including intra-span duplicate-tag aliasing), exact-span unmap validation, physical region queries (`bx_xmem_query_region`), and shared working-set accounting / combined title memory budget enforcement across heap, virtual, and physical allocations in `xmem.dll`. Synthetic `XMemAllocatePhysicalPages` / `XMemFreePhysicalPages` signatures follow Win32 AWE (`memoryapi.h`) pending a public console flag encoding (#412).
|
||||
- Added Win32 bridge conformance coverage for a hidden window, message dispatch, concurrent PSM registrations, and per-event JSONL log verification. Offline PSM registration tokens are tracked without C++ exceptions using disjoint family tags so cross-family unregisters log `foreign_token` and retired or invalid tokens log `unknown_token` (#410).
|
||||
- `xgameruntime.dll` exports BetterXen-defined `InitializeApiImpl`, `InitializeApiImplEx`, `InitializeApiImplEx2`, `UninitializeApiImpl`, `QueryApiImpl`, and `XErrorReport` so a static loader can resolve them. No public prototype for those six names was found. The documented `XGameRuntimeInitialize`, `XGameRuntimeUninitialize`, `XGameRuntimeInitializeWithOptions`, and `XGameRuntimeOptions` behavior is what the shared refcount follows. `QueryApiImpl` rejects a missing output or id, clears the output pointer on failure, dispatches the offline families this DLL already implements, and logs any other class through `BX_STUB_LOG` before `E_NOINTERFACE`. `XErrorReport` is `void` and writes only valid UTF-8, replacing an invalid byte with `\u00XX` and truncating on a character boundary. The DLL has 49 exports. This is not an Xbox hardware result (#439).
|
||||
- Implemented synthetic APU heap mappings, per-connection APU and DSP queues, and the GameInput ordinal 1 COM stub. Added an audio/input conformance executable covering all four shim DLLs (#419).
|
||||
- Added structured unhandled exception logging with module-relative addresses and x64 registers, and expanded the CLWB conformance test to require six traps across ModRM, SIB, REX and RIP-relative operands (#409).
|
||||
- Enforced the configured title memory cap for default heap allocations and virtual commits in `xmem.dll`. Added working-set accounting and a synthetic fixture for alignment, commit overlap, decommit, release, and memory transfer (#411).
|
||||
@@ -35,11 +265,19 @@ remains unsupported.
|
||||
- Added `tests/conformance/test_integration_boot/` (#420, M1-F1): an original synthetic x86-64 PE32+ boot fixture whose import directory names all 16 shim DLLs and which walks a startup-shaped sequence (AVX2 + FMA, three `clwb` forms, `xmem.dll`, `xgameruntime.dll`, PSM notifications, a hidden window pumped through the `ntuser` forwarders, `XCRDAPI.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, `GameInput.dll` ordinal 1, `xg_xs.dll`, `d3d12_xs.dll`) followed by reverse-order shutdown. Each of 21 stages prints a JSON checkpoint and a `bx_log_emit` record with status `pass`, `pending` or `fail`; `pending` marks an M0 stub's `E_NOTIMPL`/null answer or a host-answered import, is never counted as a pass, and becomes a failure with `--strict` or `BX_INTEGRATION_STRICT=1`. `scripts/build-shims.sh` builds it and still verifies all 16 DLLs. Run locally on an Apple M5 Pro (macOS 27.0, Rosetta 2) under CrossOver Preview build 20261006 by invoking its Wine loader directly with the same isolated environment `bx-cli run` sets: 13 pass, 8 pending, 0 fail, exit 0; `--strict` exits 1. It was not run through `bx-cli run` (the CLI only looks for `/Applications/CrossOver.app`) and not on CrossOver 26.3. That run found that this Wine build answers the two `api-ms-win-core-psm-appnotify-*` and four `ext-ms-win-rtcore-ntuser-*` import names itself instead of loading the BetterXen shims: the window stage still passes through `user32`, while PSM registration returns `ERROR_CALL_NOT_IMPLEMENTED` (reported as pending). The device, DirectStorage, AcpHal, GameInput and texture-computer stages are pending on their M0 stubs, and `D3D12XboxCreateDevice` and `XGCreateTextureComputer` are only probed with a null descriptor because no descriptor layout is defined in `abi/`.
|
||||
|
||||
### Removed
|
||||
- Removed the repository-wide provenance, third-party licensing and legal-boundary rules from `AGENTS.md`: §4's per-file license audit and proprietary-component restrictions, §6's "Conditions for target builds" (including lawful acquisition, no leaked or unauthorized builds, no decryption or circumvention, and "If any condition is unknown, do not use the build"), the §6 "Repository & clean-tree boundary" and "Legal boundary" rules, plus the earlier removals of §4's "Provenance first" and §6's "Never obtain or use" bullets. §4 is left as a placeholder pending a replacement policy; the §6 "Authorized compatibility evidence" and §5 honesty rules stay. Nothing in `CONTRIBUTING.md`, `docs/legal.md`, `docs/claims.toml`, the ADRs or the research registry was changed, so those documents still describe the previous policy.
|
||||
- Retired the paused in-tree native-first workspace (`crates/`, `app/`, `benchmarks/`, `experiments/`, `fixtures/`, `fuzz/`, `licenses/`, legacy native scripts, legacy `.github/workflows/ci.yml`, `agent_queue`, legacy `tests/*` outside `tests/conformance/`, and native-only docs) from `main` per ADR 0006; the full native-first history remains permanently preserved at Git tag `native-first-final`.
|
||||
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
|
||||
- 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
|
||||
- Updated the roadmap with the startup checkpoint, synthetic first-frame backing contract, and shared-budget correction. M3 and M6 memory work now has explicit eligibility and measurement criteria.
|
||||
- Recorded the target-workload shader-corpus scan in the roadmap and [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) (2026-11-28). A read-only container scan of an authorized local test workload — structure only, no run, no extraction, not redistributed — found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, and 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable; its packaged shader archive exposes no plaintext `DXBC` and remains unclassified. `dxbc-accc` accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers with `FspxSectionOutOfBounds` because their section tables do not match the clean-room layout. The roadmap keeps D1, treats the upscaler's ACCC-only containers as a concrete D2 candidate gated on runtime submission (first-frame blocker before the first presented frame, M4 upscaling if only upscaling needs them), and records both parser gaps as Track D prerequisites. Build-specific details stay in a local evidence note. Runtime use is unmeasured: the recorded startup run wrote no `shader_gate` records.
|
||||
- `dxbc-accc` reports an `FSPX` descriptor whose offset lands inside the 16-byte header or the descriptor table as `ParseError::FspxLayoutMismatch { chunk, section_id, offset, table_end }`, not `FspxSectionOutOfBounds` (#599). The reserved region cannot hold section data under BetterXen's synthetic layout, so such a table does not follow that layout; it is not merely truncated. A section that runs past the payload end is still `FspxSectionOutOfBounds`. Both `inspect_dxbc` and the C ABI's `summarize_dxbc` path classify it the same way. The container is still refused: `bx_shader_inspect` and `bx_shader_prepare_for_d3dmetal` keep returning `BX_SHADER_ERR_INVALID_BLOB` with output cleared, and the C ABI is unchanged, so the distinction does not yet reach `d3d12_xs` gate telemetry. One existing test case (offset 0 in a one-section table) now expects the new variant. New unit tests cover the reserved-region boundary, the out-of-bounds case, the unchanged C ABI refusal, and 4,096 seeded random `FSPX` tables without a panic. Synthetic bytes only; the `FSPX` layout itself is unchanged and remains synthetic (`CLAIM-XBOX-ISA-ABI`, class U).
|
||||
- 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.
|
||||
@@ -69,6 +307,26 @@ 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
|
||||
- `d3d12_xs` now charges its private host heaps through **`bx_xmem_try_charge_external` / `bx_xmem_release_charge_external`**, so `xmem::can_commit` sees graphics usage and **both allocation orders** obey one combined title cap (#552). Before this, `shims/d3d12_xs/vmem.cpp` kept a private `g_record.charged_private_bytes` ledger that `xmem` could not see, so **graphics-first (6) then CPU (3) admitted 9 against a cap of 8**, while xmem-first was rejected correctly. `try_charge` now lets the xmem hook decide on its own, because it admits atomically under `usage_lock` against every owner; the removed local pre-check worked from a snapshot taken outside that lock and, once the stats included external charges, would have counted every live graphics heap twice. `release_charge` checks its diagnostic mirror before crediting xmem, so a double release is refused instead of erasing another heap's charge. The graphics-first pairing check in `test_d3d12_placed` runs only at a 512 MiB cap; run it with `BX_MEM_LIMIT_MB=512`. At other caps the fixture reports the pairing check as skipped in its summary.
|
||||
- **The local pre-check is gone.** `try_charge` lets the xmem hook decide; it admits under `usage_lock` against every owner, so no overflow guards are needed on the d3d12_xs side.
|
||||
- **`g_record.charged_private_bytes` is retained as a diagnostic mirror**, labelled as such; `xmem`'s `external_bytes` is authoritative. Each heap wrapper releases its own charge exactly once, on its final `Release`. `release_charge` checks the mirror before crediting xmem and refuses a release larger than the **total** outstanding graphics charge. Because the mirror is one global total, it is not a per-heap guard: it cannot catch a double release of one heap while another heap is alive. The once-per-wrapper release is what prevents that.
|
||||
- **Lock order checked:** `try_charge`/`release_charge` hold `g_section` and then call into `xmem`, which takes `usage_lock`. `grep` over both files shows `xmem` never calls back into `d3d12_xs` (the only mention is a comment), so `g_section -> usage_lock` is never inverted.
|
||||
- `xmem.dll` exports 17 and `d3d12_xs.dll` exports 4. `test_d3d12_placed.exe` was run live on CrossOver 26.3. At the default cap the pairing check does not run and prints a `SKIP` line. With `BX_MEM_LIMIT_MB=512 bx-cli run --inherit-env` it runs and passes, and the same fixture against the pre-hook DLLs fails the pairing check. The `D3D12ConfigureVirtualMemoryX` log record's `xmem_used=` field is renamed `cap_used=`: it already includes graphics heaps, so it must not be added to `gpu_heap_bytes=`.
|
||||
- **Test:** `tests/conformance/test_d3d12_placed/` gained `check_graphics_xmem_pairing`, which uses only public exports: at a 512 MiB cap (`BX_MEM_LIMIT_MB=512`) a 300 MiB `CreateHeap` must make a 300 MiB `XMemAlloc` fail (300+300 > 512) while a 200 MiB `XMemAlloc` succeeds (300+200 <= 512), and after the heap is released the 300 MiB `XMemAlloc` must succeed. This is the graphics-first overcommit the private ledger allowed. It is a no-op unless the cap is exactly 512 MiB, and it was **not executed** here (no CrossOver).
|
||||
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed — removing `delete this` would leak the dispatcher while every existing check still passed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. A `delete this` removal that leaks the object would leave `live_dispatchers=1` behind and fail. The fixture also creates its own temp `BX_LOG_FILE` when the runner has not set one, so the assertions work standalone rather than reading an empty file. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none; the same offset-slicing works whether the path came from the runner or from the fixture's temp file.
|
||||
- `test_audio_input.exe` now fails with a clear message when `BX_LOG_FILE` is unset, instead of creating a temp log it can never fill. `AcpHal.dll` imports `bx_runtime_veh.dll`, which reads `BX_LOG_FILE` once in `DLL_PROCESS_ATTACH`, before `main` runs, so setting the variable in `main` left the dispatcher log checks reading an empty file and failing for the wrong reason. Run it under `bx-cli run --log`, as before. The comments on those checks no longer claim they catch a dispatcher that leaks: `Release` updates the live-dispatcher counter before `delete this`, so a missing `delete this` leaves the log unchanged. Not run live here (no CrossOver host).
|
||||
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none.
|
||||
- `test_shim_exports.exe` now loads `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), closing the gap #526 documented (#527). The fixture covers **17 DLLs / 28 checks** (16 mingw-w64 C++ shims + the 1 cargo-built Rust bridge; 25 + 3 checks), and its summary line reports the counted DLL number. `abi/` is unchanged. A load-and-resolve check does not show the bridge *works* — `test_shader_gate.exe` is what exercises it functionally. `scripts/build-shims.sh` still verifies 17 PE32+ DLLs / 111 exact exports.
|
||||
- `scripts/audit/docs_hygiene.py` now validates Markdown link fragments (`#heading`) against the target file's headings, using GitHub's slug algorithm with duplicate-heading `-1`/`-2` suffixes and fenced-code-block exclusion. In-page `](#foo)` links are checked against the same file. External URLs and bare `#` links remain unchecked. Covered by the new `scripts/audit/test_docs_hygiene.py` (23 tests) (#537). Repeated heading bases now advance their numeric suffix past *any* slug already emitted, so a literal `# Foo-1` heading no longer lets a later `# Foo` reuse `foo-1`: headings `Foo`, `Foo-1`, `Foo` yield `foo`, `foo-1`, `foo-2`.
|
||||
- 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`'s usage paths were exactly inverted, and are now right (#532). `--help` and `-h` were never matched, so they fell into the unknown-subcommand arm: usage text on **stderr** and exit **1**. Meanwhile a bare `bx-cli` with no arguments printed usage and returned **0**. `--help`/`-h`/`help` now print usage on **stdout** and exit **0**, so `bx-cli --help | less` and `bx-cli --help && ...` both work; a bare invocation is a usage error with text on **stderr** and exit **1**; an unknown subcommand still exits **1**. The choice is factored into a `Dispatch::classify` so it is testable without spawning a process. `launcher/crates/bx-cli/tests/usage.rs` runs the built binary and checks the real exit code and output stream for `--help`/`-h`/`help`, a bare invocation and an unknown subcommand.
|
||||
- **Tests:** `help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error` (exit and stream for `--help`, `-h`, `help`, no arguments, a bogus subcommand, and that the five real subcommands are not usage errors) and `the_usage_text_names_every_subcommand`.
|
||||
- **Not run:** live CrossOver execution — no CLI path here reaches a guest. Synthetic evidence only.
|
||||
- `bx-cli run` now stages `GameInput.dll` into `system32` alongside `xgameruntime.dll` and safely replaces Wine's `"Wine builtin DLL"` placeholder stub after saving a one-time backup (`.gameinput.dll.wine-builtin.bak`), while continuing to refuse modifying any non-Wine foreign DLL or symbolic link (#482). Wine pre-populates `drive_c/windows/system32/gameinput.dll` with a fake builtin PE stub whose `GameInputCreate` returns `E_NOTIMPL`, shadowing `WINEPATH` and `LOAD_LIBRARY_SEARCH_SYSTEM32` loads even when `WINEDLLOVERRIDES` specifies native-first (`=n,b`). Also added lowercase aliases (`gameinput`, `xcrdapi`, `acphal`) to `SHIM_DLL_OVERRIDES` and expanded `test_system32_staging.exe` and `stage.rs` unit tests to cover `GameInput.dll` staging and Wine stub backup/refusal rules.
|
||||
- `bx-cli run` system32 shim staging (#474). Staging now records what it wrote in a `.bx-staged` manifest in the prefix's `system32` (one SHA-256 per file) and replaces only regular files that are listed there and still have the recorded hash. Any other same-named entry the bottle already had, including a symbolic link that points nowhere, or one changed since it was staged, is never modified or deleted: staging stops with an error naming it before anything is written. New files are installed without replacing anything, so an entry that appears after the checks is protected too. All temporary copies are written before the first file is put in place, and each installed file is recorded in the manifest before the next one is touched, so a failure part-way leaves the earlier files owned rather than orphaned. A byte-identical existing file is left alone and not claimed. For a named bottle, the prefix is resolved again after the run; if CrossOver launched the bottle elsewhere, the run fails only when the staged shims cannot be found with the same contents in that prefix's `system32` (a private stub of a managed bottle that links back to the managed prefix is accepted and reported). When prefix initialization uses the whole `--timeout`, the guest is no longer started and the message names initialization (exit 124). Copies staged by an earlier `bx-cli` have no manifest entry and are treated as the bottle's own, so after upgrading a changed shim needs that stale copy removed by hand once. Staged files are still not removed after a run. Covered by 15 new unit tests (32 `bx-cli` tests pass); twelve deliberate breakages each failed a test. A reviewer ran the first revision on CrossOver 26.3 with a managed-only bottle and found the false failure, dangling-link and partial-failure cases fixed here; this revision has not itself been run under CrossOver.
|
||||
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
|
||||
- `test_integration_boot.exe` now creates a real texture address computer, checks a two-mip layout against hand-computed values and requires the final `Release` to return 0, instead of reporting that stage as pending after a null-descriptor probe (#446).
|
||||
- `bx-cli trace` reports the highest sampled CLWB total as a lower bound, labels counterless CLWB records as samples, and lists unhandled exceptions with their code, module base, RVA, and RIP (#438).
|
||||
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
|
||||
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
|
||||
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
|
||||
@@ -78,6 +336,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).
|
||||
|
||||
+11
-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).
|
||||
@@ -49,4 +49,13 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
|
||||
git commit -s -m "Describe the change"
|
||||
```
|
||||
|
||||
## Review and Merging
|
||||
|
||||
- A PR needs at least one current approval, passing required checks and resolved blocking conversations. Any later push that changes the PR dismisses earlier approvals.
|
||||
- You do not merge your own PR. A maintainer other than the original author merges it.
|
||||
- Please leave **Allow edits by maintainers** enabled on fork PRs (GitHub does not offer it for organization-owned forks). Maintainers may then resolve conflicts and push fixes to your branch, and may still merge it.
|
||||
- A maintainer may re-approve after their own routine fix (conflicts, changelog, minor docs). Substantive changes need approval from someone who did not write them.
|
||||
|
||||
The full rule, including what GitHub does not enforce, is in [AGENTS.md](AGENTS.md) §7, "Merge eligibility".
|
||||
|
||||
See [AGENTS.md](AGENTS.md), [docs/legal.md](docs/legal.md), [SECURITY.md](SECURITY.md), and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
|
||||
Generated
+7
@@ -9,6 +9,7 @@ dependencies = [
|
||||
"bx-probe",
|
||||
"bx-telemetry",
|
||||
"dxbc-accc",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -29,3 +30,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "dxbc-accc"
|
||||
version = "0.2.0"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
@@ -9,13 +9,13 @@
|
||||
-1f6feb?logo=apple&logoColor=white)
|
||||

|
||||

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

|
||||
|
||||
</div>
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project currently at **Milestone M0** (cross-compiled shim foundation and live CrossOver/Rosetta smoke tests verified on synthetic PE32+ workloads). **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
|
||||
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project with **Milestone M0 and Milestone M1 verified complete** on synthetic PE32+ workloads under CrossOver 26.3 + Rosetta 2, and **Milestone M2** (`First Rendered Frame & Shader Format Gate`) currently active. **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
|
||||
|
||||
BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Rosetta 2**, and **D3DMetal 3.0** on Apple Silicon:
|
||||
- **Native ARM64 macOS tooling** (`launcher/`, Rust) for host diagnostics, PE32+ static probing, CrossOver bottle orchestration, and structured trace aggregation.
|
||||
@@ -33,9 +33,9 @@ BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Ro
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M0["M0: Foundation & Shims\n(Merged #406)"]:::done
|
||||
M1["M1: Boot to D3D12\n(Active — Milestone #17)"]:::active
|
||||
M2["M2: First Frame &\nShader Gate"]:::planned
|
||||
M0["M0: Foundation & Shims\n(Verified Complete)"]:::done
|
||||
M1["M1: Boot to D3D12\n(Verified Complete — 16/16)"]:::done
|
||||
M2["M2: First Frame &\nShader Gate\n(Active — Milestone #18)"]:::active
|
||||
M3["M3: Shaders &\nTexture Tiling"]:::planned
|
||||
M4["M4: 3D, DXR/BVH\n& Input"]:::planned
|
||||
M5["M5: Audio, Saves\n& Stability"]:::planned
|
||||
@@ -50,16 +50,16 @@ flowchart LR
|
||||
|
||||
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
|
||||
|
||||
### Active Milestone — [M1: Startup Shims to `D3D12XboxCreateDevice`](https://github.com/MacosPorters/betterxen/milestone/17)
|
||||
### Active Milestone — [M2: First Rendered Frame & Shader Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)
|
||||
|
||||
| Track | Focus | Visual Status | Live Issues |
|
||||
| --- | --- | --- | --- |
|
||||
| **Track A** | `bx-cli` supervision, `clwb` VEH + crash dumper, Win32 bridge | `🟨🟨🟨` *(3/3 PRs open)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
|
||||
| **Track B** | `xmem.dll` core + physical/scatter pages, `XCRDAPI.dll` DirectStorage | `🟨🟨🟨` *(3/3 PRs open)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
|
||||
| **Track C** | `d3d12_xs.dll` COM proxy (D3DMetal 3.0), `xg_xs.dll` texture computer | `⬜⬜` *(needs contributors!)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
|
||||
| **Track D** | `dxbc-accc` FSPX C ABI bridge, `d3dmetal-native` harness | `🟨⬜` *(1 PR open, 1 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
|
||||
| **Track E** | `xgameruntime.dll` offline GDK, `AcpHal`/`xapu`/`chad`, `GameInput` | `🟨🟨` *(2/2 PRs open)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
|
||||
| **Track F** | End-to-end synthetic boot fixture (`test_integration_boot`) | `🟨` *(1/1 PR open)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
|
||||
| **Track A** | `system32` shim staging (`#457` / PR `#458` merged), AMD-only VEH emulation (`#451`), Track A/F runner integration (`#407`) | `🟩🟨🟨` *(#458 merged; #451, #407 active)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
|
||||
| **Track B** | `XCRDAPI.dll` DirectStorage GPU-buffer & batch transfers (`#467`) | `⬜` *(1 ready)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
|
||||
| **Track C** | `d3d12_xs` `D3D12ConfigureVirtualMemoryX` + placed resources (`#464`), `PresentX` swapchain bridge (`#465`), D3D workload fixes (`#450`) | `⬜⬜⬜` *(3 ready)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
|
||||
| **Track D** | `dxbc-accc` Windows guest bridge (`#445`), M2 Shader Format Gate ADR & PSO hook (`#466`) | `⬜⬜` *(2 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
|
||||
| **Track E** | Public GDK COM `QueryApiImpl` dispatch (`#456` / PR `#462` merged), offline `XGameSave` + `XPackage` COM dispatch (`#468`) | `🟩⬜` *(#462 merged, 1 ready)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
|
||||
| **Track F** | D3DMetal GPU limits fixture (`#453` / PR #455), M2 first-frame + shader-gate exit fixture (`#469`) | `🟨⬜` *(PR #455 approved, 1 ready)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
|
||||
|
||||
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
|
||||
|
||||
@@ -67,9 +67,9 @@ Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
|
||||
|
||||
| Milestone | Scope | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Merged (`#406`)** |
|
||||
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime`, audio queue stubs) | 🔵 **Active ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
|
||||
| **M2 — First Frame & Shader Gate** | `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0; inspect runtime shaders to select DXIL fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation | ⚪ Planned |
|
||||
| **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 |
|
||||
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | ⚪ Planned |
|
||||
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | ⚪ Planned |
|
||||
@@ -129,10 +129,10 @@ The repository is organized into disjoint track directories around a single froz
|
||||
|
||||
| Directory | Track | Stack | Contents |
|
||||
| --- | --- | --- | --- |
|
||||
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 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 |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; CrossOver answers these API-set names itself for static imports, so the files are not loaded that way ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/xmem/`, `shims/xcrdapi/` | Track B | C++20 (`x86_64` PE) | `xmem.dll` (13 Xbox memory APIs + internal region stats) and `XCRDAPI.dll` (`DStorageGetFactory` async I/O) |
|
||||
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Track C | C++20 (`x86_64` PE) | Xbox D3D12 COM proxy over D3DMetal 3.0, RDNA 2 texture tiling (`XG`), and future FidelityFX/BVH4 hooks |
|
||||
| `shader-transpiler/` | Track D | Rust (`arm64`) | `dxbc-accc` (`DXBC`/`DXIL`/`ACCC`/`FSPX` classifier), future RDNA 2 transpiler & `d3dmetal-native` isolation harness |
|
||||
@@ -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,11 @@ 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 all 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
|
||||
- **Not yet verified at runtime (built and export-verified locally, not run under CrossOver):**
|
||||
- The build of `test_shim_exports.exe` on this revision also loads the Rust-built `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), so the table covers 17 DLLs / 28 checks. The fixture compiles and links and `scripts/build-shims.sh` confirms the bridge's three exports statically, but the 28-check run across 17 DLLs under CrossOver/Wine has **not** been executed on this revision — the previous 16-DLL / 25-check pass was. Compiling, linking and export agreement do not establish that `LoadLibraryA` / `GetProcAddress` succeed for the bridge. This remains a load-and-resolve check in any case: it does not show the bridge *works*; `test_shader_gate.exe` exercises it functionally.
|
||||
- **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.
|
||||
|
||||
+65
-1
@@ -1,6 +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. 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)
|
||||
|
||||
@@ -11,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
|
||||
@@ -43,3 +43,9 @@ EXPORTS
|
||||
XGameUiShowTextEntryAsync
|
||||
XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync
|
||||
XNetworkingQuerySecurityInformationForUrlAsync
|
||||
InitializeApiImpl
|
||||
InitializeApiImplEx
|
||||
InitializeApiImplEx2
|
||||
UninitializeApiImpl
|
||||
QueryApiImpl
|
||||
XErrorReport
|
||||
@@ -15,3 +15,5 @@ EXPORTS
|
||||
XMemVirtualQuery
|
||||
bx_xmem_query_region
|
||||
bx_xmem_get_internal_stats
|
||||
bx_xmem_try_charge_external
|
||||
bx_xmem_release_charge_external
|
||||
@@ -33,9 +33,24 @@ typedef struct bx_xmem_stats {
|
||||
/* Query the XMem region covering `va`. Returns 1 if tracked, 0 otherwise. */
|
||||
int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info);
|
||||
|
||||
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap. */
|
||||
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap.
|
||||
* committed_virtual_bytes includes bytes admitted through
|
||||
* bx_xmem_try_charge_external(), so committed + physical is everything the
|
||||
* cap counts and peak_committed_bytes never exceeds what was reported. */
|
||||
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats);
|
||||
|
||||
/* Admit `bytes` against the combined title cap, counting every owner.
|
||||
* Returns 1 on success, 0 when the cap would be exceeded or xmem's own
|
||||
* bookkeeping could not be refreshed (logged as external_charge). On success the
|
||||
* caller owns the charge and must release it exactly once with
|
||||
* bx_xmem_release_charge_external(). Never silently succeeds on failure. */
|
||||
int bx_xmem_try_charge_external(uint64_t bytes);
|
||||
|
||||
/* Release a charge previously admitted by bx_xmem_try_charge_external().
|
||||
* Releasing more than is outstanding is refused: the counter is left
|
||||
* unchanged and an external_charge error is logged. */
|
||||
void bx_xmem_release_charge_external(uint64_t bytes);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
+10
-2
@@ -3,7 +3,8 @@
|
||||
## Getting Started & Architecture
|
||||
|
||||
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan (Milestones M0–M6) and completion gates.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan: the foundation milestones (M0–M2) and the stages the target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), with exit gates and decision gates.
|
||||
- [Working Method](process/working-method.md) — What an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
|
||||
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
|
||||
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
|
||||
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
|
||||
@@ -14,19 +15,26 @@
|
||||
|
||||
- [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.
|
||||
- [ADR 0009: Xbox-layout D3D12 objects](adr/0009-xbox-layout-d3d12-objects.md) — Proposed: `d3d12_xs` gives titles objects with the Xbox object layout and function-table order (generated from the Xbox header), hosting the PC proxies; Phase 1 covers the device chain and the objects it creates.
|
||||
|
||||
## Research, Testing & Licensing
|
||||
|
||||
- [Target-Build Bring-Up: Development Cycle and Review](testing/target-build-review.md) — How contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently without proprietary details.
|
||||
- [Hybrid Workloads & Measurement Protocol](testing/hybrid-workloads.md) — Original Windows workloads, receipt fields, timing conventions, and negative controls.
|
||||
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
|
||||
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
|
||||
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
|
||||
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
|
||||
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
|
||||
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
|
||||
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
|
||||
|
||||
## Governance, Security & Legal
|
||||
|
||||
- [Engineering & Agent Rules](../AGENTS.md) (`CLAUDE.md` symlink) — Mandatory rules for human contributors and coding agents.
|
||||
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, clean-room policy, and DCO sign-off.
|
||||
- [Claims & Evidence Classes](claims.toml) — Evidence classification definitions (classes A–D, U).
|
||||
- [Claims & Evidence Classes](claims.toml) — Scoped claims with an evidence-class legend (A, B, D, E, U); classes describe evidence type, not Xbox hardware verification.
|
||||
- [Legal Scope](legal.md), [Dependency Licensing](licenses.md), and [Third-Party Notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution boundaries.
|
||||
- [Threat Model](threat-model.md) & [Security Policy](../SECURITY.md) — Isolation boundaries and vulnerability reporting.
|
||||
@@ -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,45 @@
|
||||
# ADR 0007: API-set win32_bridge shims are not reached under CrossOver
|
||||
|
||||
Status: **Accepted** (2026-11-26, issue #437). Independently verified on CrossOver 26.0 and CrossOver 26.3 on Apple Silicon.
|
||||
|
||||
## Context
|
||||
|
||||
`shims/win32_bridge/` builds six DLLs named after Windows API sets:
|
||||
`api-ms-win-core-psm-appnotify-l1-1-0`, `api-ms-win-core-psm-appnotify-l1-1-1` and four `ext-ms-win-rtcore-ntuser-*` forwarders to `user32.dll`. A guest that imports those names statically is expected to load the BetterXen files placed next to the EXE. #437 reports that under CrossOver 26.3 it does not: Wine answers the names itself, even with `WINEDLLOVERRIDES=<name>=n,b` and the shim files in the EXE's directory.
|
||||
|
||||
## Evidence
|
||||
|
||||
`tests/conformance/test_apiset_resolution` imports one export from each of the six DLLs through the PE import directory, then reports for every name the module that owns the name and the module the loader bound the import address table slot to.
|
||||
|
||||
Run on an Apple M-series Mac, macOS 27.2.1, Rosetta 2, **CrossOver 26.0 (`26.0.0.39794`)**, bare prefix, with the override list from `bx-cli` (`SHIM_DLL_OVERRIDES`) and `build-shims/bin` as the EXE directory:
|
||||
|
||||
| Import name | Served by | Module that owns the name | Module the import is bound to |
|
||||
| --- | --- | --- | --- |
|
||||
| `api-ms-win-core-psm-appnotify-l1-1-0` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
|
||||
| `api-ms-win-core-psm-appnotify-l1-1-1` | host | `c:\windows\system32\twinapi.appcore.dll` | same |
|
||||
| `ext-ms-win-rtcore-ntuser-message-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
|
||||
| `ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
|
||||
| `ext-ms-win-rtcore-ntuser-window-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
|
||||
| `ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0` | host | `c:\windows\system32\user32.dll` | same |
|
||||
|
||||
`WINEDEBUG=+loaddll` shows `Loaded` records for `user32.dll` and `twinapi.appcore.dll` (both builtin) and none for any of the six shim files. `--expect shim` fails 0/6, so the fixture does distinguish the two outcomes.
|
||||
|
||||
This behaviour was independently reproduced on **CrossOver 26.3** on Apple Silicon (`bx-cli run` with the shim directory and direct loader runs with `WINEDEBUG=+loaddll`), yielding the exact same 6/6 host resolution (`twinapi.appcore.dll` and `user32.dll`, both builtin, with no `Loaded` records for the six shim files) and `--expect shim` exiting 1. The internal Wine mechanism is not claimed here; this records observed loader behaviour.
|
||||
|
||||
## Decision
|
||||
|
||||
Rely on Wine's built-ins. Under CrossOver the six API-set shims are not part of the supported path: the host answers window and message calls through `user32.dll` and PSM registration through `twinapi.appcore.dll`.
|
||||
|
||||
- The six DLLs stay in the tree, built and export-checked, and are still exercised by explicit full-path loads (#431).
|
||||
- No attempt is made to make them win name resolution. That would depend on undocumented Wine API-set behaviour (#350) and, within this issue's scope, on patching or redistributing CrossOver or Wine components, which is out of scope.
|
||||
- Offline PSM behaviour that a title needs must live somewhere a static import actually reaches. This ADR does not choose that place.
|
||||
|
||||
## Consequences
|
||||
|
||||
- `test_apiset_resolution` records the current behaviour (`--expect host`) and fails when it changes. If a CrossOver build starts loading the shims, run it with `--expect shim` and revisit this ADR.
|
||||
- `test_integration_boot` continues to report `shim_backing` as pending for these six names under CrossOver.
|
||||
- Documentation describes the bridges as Windows-only stubs that CrossOver does not load for static imports.
|
||||
|
||||
## Not claimed
|
||||
|
||||
Nothing here shows Xbox title compatibility, behaviour on Xbox hardware, or behaviour on CrossOver builds outside 26.0 and 26.3. Evidence class: local Apple Silicon runs.
|
||||
@@ -0,0 +1,78 @@
|
||||
# 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 |
|
||||
| A read-only structural scan of an authorized local test workload (2026-11-28) found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable, and no plaintext `DXBC` in its packaged shader archive. | Static container scan on this host, re-run through `dxbc-accc`; private evidence note, workload not redistributed | This host; structure only, runtime use unmeasured |
|
||||
|
||||
Runtime gate telemetry still covers only synthetic programs; no target-workload run has reached pipeline creation, so what a run submits remains unmeasured. One static measurement now exists (2026-11-28): a read-only container scan of an authorized local test workload, re-run through `dxbc-accc`, with the counts in the table above. The scan measures what shipped components contain, not what any run submits, and the workload is not redistributed. 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 shows a required pipeline-creation path refusing an ACCC-only container at runtime — a static scan already established that the target workload's upscaler component embeds 29, so the open question is submission, not existence;
|
||||
- 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.
|
||||
- **Stream PSOs (#576):** `ID3D12Device2::CreatePipelineState` stream descriptions are gated too. The stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Both the payload offset and the record size come from the compiler: `alignas(void*)` aligns the record, not the payload, so 4-byte-aligned payloads sit at offset 4, and `static_assert`s pin the measured values. Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, `AS`, `MS`) go through `BxShaderGate::admit`; every other payload is copied verbatim. A subobject type at or above `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID` from the toolchain header (mingw-w64 `d3d12.h`: `0x1a`, immediately after `MS`), a duplicated subobject type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim edits its own copy of the stream, so prepared DXIL can be substituted without writing to the caller's memory. `pso_stream` now reports `shaders_not_parsed=0` when it parsed, and each stream stage logs its own `shader_gate` record with `pso=stream`. The `--no-bridge` path also refuses ACCC-only through the stream. `test_shader_gate.exe` covers the stream form but was cross-compiled only, not run under CrossOver on the authoring host.
|
||||
- **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:**
|
||||
- **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.
|
||||
- **Observed `FSPX` tables:** the clean-room section-table layout does not describe the 29 containers embedded in the target workload's upscaler component. In the 2026-11-28 scan, `dxbc-accc` rejected them with `FspxSectionOutOfBounds` before any section body was read, so the current refusal is structural, not a measured D3DMetal incompatibility. The cause the scan recorded, a descriptor offset inside the region the layout reserves for the header and section table, is reported as `FspxLayoutMismatch` since #599, apart from a section past the payload end; the scan has not been re-run against that change. Over the C ABI both are still `BX_SHADER_ERR_INVALID_BLOB`. Extending the layout against measured containers is a Track D prerequisite for any D2 trial and a maintainer provenance decision, because no public format description exists.
|
||||
- **`NOBC` programs:** the classifier validates the `DXIL` program header's sizes but not the LLVM bitcode signature, so a container whose bitcode payload is the four-byte placeholder `NOBC` still classifies as executable DXIL and is prepared for the host unchanged. The target workload's main executable embeds 10 such containers (nine pixel, one vertex, SM 6.6). They carry no bitcode, so D1 cannot run them as-is; their signature and validation chunks are intact.
|
||||
- **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, one local static container scan of an authorized test workload, and public-source review. The scan counts containers embedded in shipped components on this host; it does not establish what any run submits, and it documents no console-compiled format layout beyond the stated mismatch.
|
||||
@@ -0,0 +1,59 @@
|
||||
# ADR 0009: Xbox-layout D3D12 objects in d3d12_xs
|
||||
|
||||
Status: **Proposed** (2026-11-28). Phase 1 is implemented with this ADR; the maintainers decide whether the direction stands. The evidence is from local Apple Silicon runs by the implementer and has not been independently reproduced.
|
||||
|
||||
## Context
|
||||
|
||||
`d3d12_xs.dll` handed titles PC D3D12 objects: C++ proxies (`proxy.h`, `proxy_generated.cpp`) whose vtables follow the PC `<d3d12.h>` order. A title built against the Xbox Series D3D12 header (`d3d12_xs.h`, part of the GDK material Microsoft authorized the project to use) calls through each object's **function table**, and that order is different:
|
||||
|
||||
| Interface | Xbox slots | PC slots | Orders agree up to |
|
||||
| --- | --- | --- | --- |
|
||||
| `ID3D12Device` | 83 | 44 | slot 43. Xbox then adds 39 methods (`CreatePlacedResourceX`, `CreateCommandQueueX`, ...) before `ID3D12Device1`. |
|
||||
| `ID3D12Device11` (chain) | 139 | — | `ID3D12Device11` is the interface a project-authorized target build asks for. |
|
||||
| `ID3D12GraphicsCommandList` | 107 | 60 | slot 27 |
|
||||
| `ID3D12CommandQueue` | 38 | 19 | slot 13 |
|
||||
|
||||
So every call past those slots reached the wrong PC method. On the target build, the first call on the device after `QueryInterface(ID3D12Device11)` jumped to address 0.
|
||||
|
||||
From the same header:
|
||||
- **Base layout:** every object starts with the table pointer, a 32-bit flags word and `m_RefCount`, 16 bytes in all.
|
||||
- **`ID3D12Device` fields:** a 64-bit null constant-buffer address at +16 and a 64-byte union at +24. The union's first byte, `m_OutOfLineFlags`, makes the two inline device helpers (`CopyDescriptorsSimple`, `CreateConstantBufferView`) call out through the table when it is non-zero. That holds unless a title is compiled with `D3DCOMPILE_NO_DEBUG`, in which case they write descriptors inline.
|
||||
- **Command lists:** they add a put buffer and CPU state. Of their 76 inline methods, 71 call the table. The other five write command packets directly when the next write fits below `m_Putter`'s limits, and call the table otherwise.
|
||||
- **IIDs:** the interface IDs of shared interfaces are the PC ones (`ID3D12Device` `189819f1-…`, `ID3D12Resource` `696442be-…`).
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Xbox-layout objects:** titles get `BxXboxObject`s (`xbox_facade.h`). They have the Xbox object layout, with `m_OutOfLineFlags` set, and an Xbox-order function table. Each object hosts a PC object, normally one of the existing proxies, so their logging, shader gate, heap hooks and wrapping stay in force.
|
||||
2. **Generated tables:** `tools/gen_xbox_tables.py` reads the Xbox header locally and the toolchain's `<d3d12.h>`, and writes `xbox_tables_generated.cpp`. It takes only slot order, names, IIDs and parameter types from the Xbox header. The header is never committed.
|
||||
- **Forwarders:** a slot whose Xbox and PC signatures are equivalent gets a typed forwarder written with the PC types. That includes the free-function versus member struct-return difference, so the compiler produces the right calling convention. Interface pointers passed in are unwrapped, and `(REFIID, void**)` results are wrapped.
|
||||
- **Stubs:** every other slot is a `BX_VTABLE_STUB_LOG` stub.
|
||||
- **Hand-written slots:** Xbox-only methods are implemented in `xbox_facade.cpp` as titles need them.
|
||||
3. **Who gets which layout:** titles set `Version` in the `D3D12XBOX_CREATE_DEVICE_PARAMETERS` block they pass to `D3D12XboxCreateDevice`, and the documentation requires it. Those calls get the Xbox layout. BetterXen's synthetic fixtures are PC-layout clients built against `<d3d12.h>`, pass a zeroed block, and keep the PC proxy. The log records which layout was chosen (`xbox_layout`).
|
||||
4. **Command lists (Phase 2):** command lists get an Xbox object whose zeroed put-buffer pointers fail every inline room check, so every call reaches the table.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Phase 1 (this change):**
|
||||
- The device chain up to `ID3D12Device11` is covered: 139 slots, 75 forwarded, 4 shared or hand-written, 60 stubs.
|
||||
- So are the objects it creates: resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues.
|
||||
- `CreateCommandQueueX` maps the Xbox queue description onto PC `CreateCommandQueue`. The engine and queue indices are logged and not used.
|
||||
- On the target build, the title now creates its device and four compute queues, and stops at `CreateCommandListX`, which is Phase 2.
|
||||
- **Phase 2:**
|
||||
- **Command lists:** `ID3D12GraphicsCommandList8`, 150 slots: 75 forwarded, 6 shared or hand-written, 69 stubs. They are created through `CreateCommandListX` and the PC `CreateCommandList`, and their Xbox field area is zeroed, so the five inline fast paths call through the table.
|
||||
- **Interface pointers inside structures:** `ResourceBarrier` and `CopyTextureRegion` unwrap them before the host call. The Xbox `ResourceBarrier` returns 0 actions.
|
||||
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` (`frame_pacing.cpp`) are emulated from the recorded interval by a host timer. It signals the origin, vblank and flip events and their ancillary handles, and gives out frame-pipeline tokens as documented.
|
||||
- **Generator fixes:** CRLF lines in parts of the header, a table definition whose end the boundary pattern ran past (it hid `ID3D12GraphicsCommandList1`), SAL annotations with nested parentheses, and `FLOAT`/`float`.
|
||||
- **Resources at title-chosen addresses** (`placed_x.cpp`), translation by copy:
|
||||
- `CreatePlacedResourceX` and `CreatePlacedResourceX1` create a host shadow resource. A buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's memory at creation; a texture gets a committed texture whose contents are not filled, which is logged.
|
||||
- The resource reports the title's address from `GetGPUVirtualAddress`.
|
||||
- Not yet done: keeping shadows in step with later CPU writes (planned: page-protection dirty tracking, copying at submit), copying GPU writes back, and translating title addresses in GPU calls.
|
||||
- **On the target build:** the title creates 581 command lists, sets a 30 Hz interval and schedules its origin and flip events. It then lays out its own descriptor memory with `xmem` placeholders (#643) and creates a 174 MB buffer at a title-chosen address through `CreatePlacedResourceX1`, now served by a shadow.
|
||||
- **Where it stops:** the title creates a descriptor heap and requires `GetCPUDescriptorHandleForHeapStart` to equal an address in its own descriptor memory. D3DMetal returns an opaque handle.
|
||||
- **What that needs:** BetterXen-owned descriptor heaps whose handles are addresses, translated to host descriptors when used. That is the descriptor-heap item under Consequences.
|
||||
- **Fixtures:** the existing fixtures are unaffected, since they use the PC layout. `tests/conformance/test_d3d12_xbox_layout` calls Xbox slots by number, with the expected results taken from a PC-layout device. It fails against the previous `d3d12_xs.dll`.
|
||||
- **What the fixture can and cannot show:** its slot numbers and object offsets are written by hand, but from the same header the generator reads. It shows that the generator and the fixture agree. It cannot show that either read the header correctly; only an independent re-derivation from the header, or a title running further, can.
|
||||
- **On a host without the forwarded interface** (vkd3d stops at `ID3D12Device9`): the Xbox-layout device is refused with `E_NOINTERFACE` and logged. The fixture verifies the refusal and skips (exit 77). `bx_xbox_wrap` refuses the same way for every wrapped family, so a title never gets a PC object where it expects an Xbox one.
|
||||
- **Frame pacing:** the emulated frame interval follows host `Sleep` and is not synchronised to the display. The pacing thread is detached and never exits, which is safe only while `d3d12_xs.dll` stays loaded for the life of the process.
|
||||
- **Descriptor heaps:** a title compiled with `D3DCOMPILE_NO_DEBUG` writes console-format descriptors straight into descriptor-heap memory and computes handles with Xbox descriptor sizes. Supporting that needs BetterXen-owned descriptor heaps translated at bind time, which is not part of this ADR.
|
||||
- **Identity:** QueryInterface on an Xbox object for another wrapped family returns that family's Xbox object over the same host. A host reached through another path, such as `GetDevice` returning the raw host device, may get a second Xbox object.
|
||||
- **Replacing the PC proxy:** this ADR supersedes the PC proxy for titles. Whether the PC proxy is eventually removed in favour of fixtures that use the Xbox layout is left open.
|
||||
@@ -9,7 +9,7 @@ BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-bas
|
||||
| `abi/` | Shared (frozen) | C headers + `.def` | Cross-DLL contracts (`bx_log.h`, `bx_config.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical DLL export lists |
|
||||
| `launcher/` | Track A | Rust (`aarch64-apple-darwin`) | Native ARM64 macOS CLI (`bx-cli`), PE32+ static probe (`bx-probe`), JSONL trace aggregator (`bx-telemetry`) |
|
||||
| `shims/runtime_veh/` | Track A | C++20 (`mingw-w64`) | `bx_runtime_veh.dll`: `clwb` VEH handler, `adcx`/`adox` tripwire, Lockhart/Anaconda config, JSONL trace logger |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/xmem/` | Track B | C++20 (`mingw-w64`) | `xmem.dll`: physical/virtual/scatter memory allocator, `__XMemAllocationHooks__`, 16 GB Lockhart cap |
|
||||
| `shims/xcrdapi/` | Track B | C++20 (`mingw-w64`) | `XCRDAPI.dll`: DirectStorage async I/O factory, queues, and decompression |
|
||||
| `shims/d3d12_xs/` | Track C1 | C++20 (`mingw-w64`) | `d3d12_xs.dll`: Xbox D3D12 COM proxy over Wine `d3d12.dll` (D3DMetal 3.0), `PresentX`, placed resources |
|
||||
@@ -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,4 +1,30 @@
|
||||
# Source review is distinct from a Xenora test run.
|
||||
#
|
||||
# Evidence classes (derived from existing usage; claim classes are unchanged):
|
||||
# A — Executed measurement on a named Apple Silicon host, with an independent
|
||||
# CPU/reference expectation. Valid only for the named host/software versions;
|
||||
# implementer-run unless independently reproduced. Never Xbox verification.
|
||||
# B — Source-derived semantics from a public vendor specification, scoped to the
|
||||
# documented target (e.g. desktop RDNA 2, public D3D12, Metal/MSL). May be
|
||||
# exercised by synthetic tests, but does not establish console applicability.
|
||||
# D — Public documentation or sample-source inspection (Microsoft/Xbox/Apple),
|
||||
# without console execution. Establishes only what the reviewed source states.
|
||||
# E — Public tool/format documentation or observed behavior of a public
|
||||
# software tool (e.g. LLVM's gfx1030 documentation, or its assembler/
|
||||
# disassembler accepting gfx1030 forms), scoped to the pinned tool version.
|
||||
# Documentation review and execution are distinct; the claim's test field
|
||||
# records which one applies.
|
||||
# U — Unknown/unestablished by the reviewed public sources: a bounded statement
|
||||
# about the evidence reviewed, not proof that no authorized source exists.
|
||||
#
|
||||
# Use B for semantics from a specification, D for a claim about what a public
|
||||
# document or sample says, and E for a claim about a tool or its format support.
|
||||
# The current registry does not assign class C.
|
||||
#
|
||||
# These are the repository's evidence classes. AGENTS.md §5 refers to this
|
||||
# file and does not define a second vocabulary; the longer VERIFIED /
|
||||
# REPRODUCED / SOURCE-DERIVED / ... vocabulary named in issue #549 is not
|
||||
# present in the in-tree AGENTS.md, so no mapping is invented here.
|
||||
schema_version = 1
|
||||
|
||||
[[claim]]
|
||||
@@ -242,3 +268,13 @@ retrieved = "2026-11-22"
|
||||
architecture = "Xbox Series X, Hot Chips 32 architectural presentation"
|
||||
test = "Read slides 12 and 13. No console execution."
|
||||
uncertainty = "The slides do not specify opcode semantics, an ABI or a command packet layout."
|
||||
|
||||
[[claim]]
|
||||
id = "CLAIM-XBOX-CS-ENTRY-ABI"
|
||||
class = "U"
|
||||
claim = "For project-authored compute shaders with explicit root signatures, the NewBE backend of Microsoft's Series X|S PIX shader compiler generated wave64 code that receives root data from s4 in root-parameter order (one SGPR per constant, two per root descriptor address, one per 32-bit table pointer), thread-group IDs after the root data, the root-data address in s0:s1 when the data overflows, and root buffer descriptors built inline with a record count of -1."
|
||||
sources = ["docs/research/console-shader-abi.md"]
|
||||
retrieved = "2026-11-28"
|
||||
architecture = "Xbox Series X|S compute shaders, as compiled by the GDK 2026.10 (10.0.26100.9661) Scarlett PIX shader compiler (NewBE) under CrossOver 26.3 (26.3.0.39832) on Apple M5, macOS 27.2.1"
|
||||
test = "Compiled eleven project-authored cs_6_5/cs_6_6 probes and read the compiler's assembly listings; the compiler and its outputs are used under Microsoft's authorization and are not in the repository."
|
||||
uncertainty = "Class U: no public source establishes this; it rests on an authorized reading of a non-public compiler's listings, which only a contributor with the same authorization can reproduce, and which has not been independently reproduced. Register roles are inferred from the generated code and the reported COMPUTE_PGM_RSRC2 fields. NewBE only: the ACO backend (xdxc), which produces ACCC code, generates different code and agrees so far only on the root UAV address in s[4:5]. One compiler build, compute only, no console execution, and the ACCC container layout is not covered."
|
||||
+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
|
||||
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
# Working Method: the Blocker Queue
|
||||
|
||||
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
|
||||
|
||||
BetterXen is built by collaborators who each have the project-authorized target build and who work by pointing a coding agent at this repository and saying **"work"**. This document is written for that. It answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
|
||||
|
||||
There are no meetings, no rotating roles and no plan to interpret. The state of the project is in GitHub; the rules are here and in AGENTS.md.
|
||||
|
||||
## Why this shape
|
||||
|
||||
What the first target-build runs taught us:
|
||||
|
||||
- **The build finds what tests cannot.** With the start-up milestone verified complete, the build still stopped on a missing handle-duplication call, an instruction loop that trapped two million times and a page-remapping race. Nobody would have written an issue for any of them in advance.
|
||||
- **Guessing is expensive.** A stall was blamed on network polling for a day; a thread sample found the real cause in minutes.
|
||||
- **A helpful workaround can hide the real path.** Answering every pipeline call with success kept the frame loop alive and hid the build's fallback to shader containers.
|
||||
- **One run proves little.** The build takes different start-up paths from run to run. Two blockers looked like one "intermittent stop" until runs were counted.
|
||||
- **Agents left alone drift.** They wrote long documents, opened large stacked pull requests that nobody reviewed, investigated the same symptom twice, shared one game bottle and filled a disk.
|
||||
|
||||
So: the build decides what is next, the queue makes it unambiguous, and reviewing comes before new work.
|
||||
|
||||
## The stages
|
||||
|
||||
The [roadmap](../roadmap.md) is a ladder of stages the target build reaches: **Boot → Picture → Menus → World → Fidelity → Playable**. Exactly one stage is current. Its exit gate is a ten-run check anyone can repeat.
|
||||
|
||||
## Where the state lives
|
||||
|
||||
| What | Where | Who writes it |
|
||||
| --- | --- | --- |
|
||||
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) | Any agent that runs the gate check |
|
||||
| Everything the build is known to stop on | One **blocker issue** each (label `blocker`, plus `stage: <name>` and a track label) | The agent that found it |
|
||||
| Who is working on what | A claim comment on the blocker issue | The claiming agent |
|
||||
| What needs a person | Label `needs-human` | Any agent |
|
||||
| Rules | AGENTS.md and this document | Maintainers, by pull request |
|
||||
|
||||
Nothing about status is kept in files in the repository: agents editing one status file would conflict all day.
|
||||
|
||||
### Blocker issues
|
||||
|
||||
A blocker issue is small and has a fixed shape, so that two agents that find the same thing file the same issue.
|
||||
|
||||
- **Title:** `[blocker] <signature>`. The signature is taken from the run report, not invented: for example `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll (write, unmapped)`, `exit status 1 after save query`, `stall: presenting thread in trapped instruction`. Before filing, search open and closed issues for the signature.
|
||||
- **Body:** the stage it blocks; how many of ten runs hit it; the run-report lines; what is known and not known. No bytes, names, hashes or addresses from the build.
|
||||
- **Order:** within a stage, the label `first` marks blockers that every run hits before any other; after those, lower issue number first.
|
||||
|
||||
## What an agent does when told "work"
|
||||
|
||||
AGENTS.md §0 has the binding version. In short, in strict order:
|
||||
|
||||
1. **Preflight.** Tools, login, disk space, an own bottle, a current `main`.
|
||||
2. **Your own pull requests first.** Requested changes, failing checks or conflicts on a pull request your person opened.
|
||||
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. Review it, and merge it if it is approved, green and not your person's. Review comes before new work because unreviewed work is worth nothing to the next run.
|
||||
4. **Then one blocker.** The top unclaimed blocker of the current stage. Claim it, and do only that.
|
||||
5. **Then discover.** If the current stage has no unclaimed blocker, run the stage's gate check and file what it finds. If the gate passes, post the result on the ladder issue and label it `needs-human`: a person confirms the stage change.
|
||||
6. **Otherwise stop.** Report that the queue is empty. Do not invent work.
|
||||
|
||||
An agent stops and labels `needs-human` whenever it meets a decision that is not its to make: a decision gate, a licence or provenance question, a rule change, or two sources of truth that disagree.
|
||||
|
||||
## Working one blocker
|
||||
|
||||
```text
|
||||
claim → evidence → smallest fix + test → ten runs → pull request → (someone else reviews and merges)
|
||||
```
|
||||
|
||||
1. **Claim.** Comment `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue. A claim with no commits or pull request after 3 days is free to take; say so in a comment when you take it.
|
||||
2. **Evidence before code.** Find what the build asked for and what it got. Use the run report, then the diagnostics (thread sampler, fault context, call trace). If that does not explain it within the session, write what was learned on the issue and release the claim; do not guess a fix.
|
||||
3. **Smallest fix.** Only what removes this blocker, inside the track directories it needs. A new cross-DLL export still goes through an `[ABI]` pull request first.
|
||||
4. **A test for the contract.** Every contract the fix teaches a shim gets a synthetic conformance test that fails without the fix.
|
||||
5. **Proof.** Ten runs before and ten after. Report every run.
|
||||
6. **Pull request.** One blocker, five short parts (below). Then stop: the next "work" starts from the top of the list.
|
||||
|
||||
### Pull-request description
|
||||
|
||||
Five parts and nothing else:
|
||||
|
||||
1. **Blocker:** `Closes #<issue>` and one sentence on what the build did.
|
||||
2. **Contract:** what the console does, and which source says so (ranks below).
|
||||
3. **Fix:** what changed.
|
||||
4. **Test:** the conformance test, and that it fails without the fix.
|
||||
5. **Proof:** before and after over ten runs (for example "status-5 exits: 4/10 → 0/10"), with the machine and the `main` commit.
|
||||
|
||||
### Review
|
||||
|
||||
The reviewing agent checks out the branch, runs the Section 8 commands and the new test, confirms the test fails without the fix, and reads the proof. It does not repeat the ten runs unless the proof looks wrong.
|
||||
|
||||
**Deep review** — re-deriving the contract from its source, by an agent working for a different person than the author — is required only for:
|
||||
|
||||
- a change under `abi/`;
|
||||
- a new or changed translator instruction class;
|
||||
- a contract from source rank 4 or 5;
|
||||
- anything touching the sandbox, security or licensing.
|
||||
|
||||
**Merging.** The author's agent never merges its own person's pull request. Any other collaborator's agent merges once the pull request is approved and green. A pull request that is green and unreviewed after one working day gets the label `needs-human`.
|
||||
|
||||
**Stacks.** A pull request is based on `main`. One level of stacking is allowed when a fix truly needs an unmerged one; deeper stacks are not.
|
||||
|
||||
## Run protocol
|
||||
|
||||
A run counts only if it is made this way. The launcher does it; agents do not hand-roll it.
|
||||
|
||||
Until the launcher does, the offline-run procedure and the diagnostic switches are in [Target-Build Bring-Up: Development Cycle and Review](../testing/target-build-review.md). Where that document and this one differ on roles, the order of work or review, this one replaces it once accepted.
|
||||
|
||||
- **Build:** current `main`, or `main` plus exactly the one branch under test.
|
||||
- **Sandbox:** the offline runner, which refuses to start unless a probe confirms outbound network is blocked.
|
||||
- **Bottle:** one per agent session, created by the launcher and named for the session. Never a shared one.
|
||||
- **One game at a time per machine.** The launcher takes a machine-wide lock; a second run waits.
|
||||
- **Disk:** at least 10 GB free, checked before the run; the session's scratch bottle and build directory are removed afterwards.
|
||||
- **Count and length:** ten runs, each as long as the stage needs (five minutes for Boot).
|
||||
- **Machine:** the report states chip and memory. Gates are judged on 16 GB machines.
|
||||
|
||||
**The run report** is generated, not written. Per run:
|
||||
|
||||
- outcome: frames presented, clean timeout, early exit with its status, or hang;
|
||||
- the start-up path taken;
|
||||
- every unimplemented call reached, counted;
|
||||
- every fault inside a BetterXen module;
|
||||
- pipelines drawn with: translated, passed through, skipped;
|
||||
- on a stall: every thread's stack.
|
||||
|
||||
It ends with a ten-run summary and a list of **signatures**, the strings blocker issues are titled with.
|
||||
|
||||
## Sources of truth
|
||||
|
||||
When a fix needs to know what the console does, use the strongest source available and name its rank in the pull request.
|
||||
|
||||
| Rank | Source | Notes |
|
||||
| --- | --- | --- |
|
||||
| 1 | Authorized GDK documentation and headers | Derived facts may be committed. The files never are. |
|
||||
| 2 | Our own compiler output for our own source | Built with the console compiler from the GDK. |
|
||||
| 3 | Run-time observation of the target build | What it calls, with what, and what it does with the answer. |
|
||||
| 4 | Call-site analysis of the target build (a disassembler such as Ghidra) | When observation cannot explain a wait or a branch. Local only. |
|
||||
| 5 | The authorized upstream emulator's source | A hint about what the build needs, not a reference for correctness. Confirm with ranks 1–4 or with runs. |
|
||||
|
||||
Collaborators may install the GDK and a disassembler for this. AGENTS.md §6 is unchanged: nothing from the build enters git, issues or pull requests — no bytes, file names, hashes, addresses or decompiled code.
|
||||
|
||||
## Evidence and references
|
||||
|
||||
- **Private evidence store.** Run logs, dumps, disassembly and captures go in a folder outside the repository on the collaborator's machine. Issues and pull requests carry counts, sizes, call shapes and the contract learned.
|
||||
- **Reference images** (needed from the Picture stage on): a collaborator's own capture from a real console running the same content, or published footage. They live in the private store; a pull request says "matches reference screen 3".
|
||||
|
||||
## Finding blockers once the game runs
|
||||
|
||||
From the Menus stage on, the build no longer stops by itself at the next missing piece: someone has to take it somewhere. Agents are poor players, so the method does not depend on an agent holding a controller. BetterXen owns both ends of the build's contact with the machine — input (`GameInput`) and graphics (`d3d12_xs`) — and records and replays both.
|
||||
|
||||
**1. People play; the launcher records.** A play session with recording on saves the input stream with timestamps and the save files it started from. A hotkey marks a moment ("texture wrong here", "audio cut out"). A crash or hang needs no mark: the run report has it.
|
||||
|
||||
**2. Agents replay routes.** A route is a starting save plus a short recorded input stream (about two minutes: load, walk somewhere, enter a vehicle). An agent replays it through the input shim and compares the run with the last good one. Replays drift, because the build is not deterministic, so routes stay short and start from a save. Each route is a regression test, run ten times like any gate.
|
||||
|
||||
**3. Frame capture and offline replay.** The graphics layer records every call the build makes for one frame, with the data it referenced. The frame is then redrawn without the build running, in seconds and identically every time. An agent fixing a picture bug replays that frame after each change instead of booting and travelling to the spot again.
|
||||
|
||||
**How a problem is recognised,** from most to least reliable without a person:
|
||||
|
||||
| Signal | Catches | Needs a person |
|
||||
| --- | --- | --- |
|
||||
| Crash, hang, early exit | Stability | No |
|
||||
| Run-report counters: skipped draws, stubbed shader instructions, unimplemented calls, failed storage requests | Missing pieces, even when the picture looks plausible | No |
|
||||
| Frame compared with the last good capture of the same route | Regressions | No |
|
||||
| Frame compared with a console reference image | Wrong rendering | To supply the reference |
|
||||
| An agent looking at a capture | Obvious breakage: black screen, missing geometry, garbage textures | No; subtle errors are missed |
|
||||
| A person's mark during play | Feel, audio sync, input lag, anything that "looks off" | Yes |
|
||||
|
||||
Findings enter the queue as blocker issues with signatures of the same kind: `route 7: crash at 1:40 (3/10)`, `capture 12: 340 draws skipped`, `capture 12: differs from reference in the sky`. The order of work does not change.
|
||||
|
||||
Whether the game is good to play is a question only people answer. Their time goes into playing and marking, never into reproducing or bisecting.
|
||||
|
||||
## What people do
|
||||
|
||||
People are needed for exactly four things, each marked `needs-human`:
|
||||
|
||||
1. confirming a stage change after a gate passes;
|
||||
2. deciding a decision gate (for example the graphics back end);
|
||||
3. licence, provenance and legal questions;
|
||||
4. changing these rules.
|
||||
|
||||
Everything else is the queue.
|
||||
|
||||
## Starting the queue
|
||||
|
||||
The queue starts with what the first target-build runs already found. Each line was filed as an issue on 2026-11-29 (#664–#680); the table is kept as a record of the starting point, and the issues are the live state.
|
||||
|
||||
| Stage | Signature or task | Track |
|
||||
| --- | --- | --- |
|
||||
| Boot | Run tooling in the repository: offline runner, per-run report with signatures, ten-run summary, thread sampler, machine-wide run lock, per-session bottle | A |
|
||||
| Boot | `stall: presenting thread in trapped CLZERO loop` | A |
|
||||
| Boot | `unimplemented IXUser slot 3` (handle duplication) | E |
|
||||
| Boot | `unimplemented IXGameRuntimeCore slots 6, 13, 14, 15` (async run; task-queue composite, port, duplicate) | E |
|
||||
| Boot | `unimplemented IXGameSaveImpl slot 13` (container info; and slot 15) | E |
|
||||
| Boot | `fault in XCRDAPI.dll (write, unmapped)` — page remapping is not atomic | B |
|
||||
| Boot | `serialized-pipeline calls succeed with a null pipeline` — they must fail and be logged | C |
|
||||
| Boot | `exit status 1, nothing logged` (1 run in 5) | A |
|
||||
| Picture | D3DMetal capability checks: direct heap indexing, 64-lane compute through the translator, 64-bit atomics, mesh and amplification shaders | D, F |
|
||||
| Picture | Vendor the upstream translator with provenance entries; amend ADR 0008 | D |
|
||||
| Picture | Translator behind `bx_shader_bridge.dll`; host pipelines created on first use | C, D |
|
||||
| Picture | `placed texture contents not uploaded` | C |
|
||||
| Picture | `build waits after sign-in with nothing unimplemented` — needs evidence | E |
|
||||
| Picture | Reference images for the first screens | `needs-human` |
|
||||
| Menus | Input record and replay in the `GameInput` shim; routes as ten-run regression tests | E, A |
|
||||
| Menus | Play-session recording in the launcher: input stream, starting saves, mark hotkey | A |
|
||||
| Fidelity | Frame capture in `d3d12_xs` and an offline frame replayer | C |
|
||||
|
||||
Fixes for several Boot lines exist on a local experiment branch; they still go through the queue, one pull request each, with tests and ten-run proof.
|
||||
@@ -20,5 +20,9 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
|
||||
| x86-64 decode and ARM64 translation, runtime, gfx1030 compiler, Metal backend | BetterXen native implementation | **Preserved, paused** | Reuse only where hybrid needs it and it shows a demonstrated advantage; not forced into the architecture. |
|
||||
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
|
||||
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
|
||||
| Process groups and signals for `bx-cli run` | rust-lang/libc 0.2.191 (MIT) | **Reuse** | Unmodified crates.io dependency (#408). |
|
||||
| Public PC DirectStorage interface definitions (IIDs, structs, vtable order) | `dstorage.h` and `dstorageerr.h` from NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0 (MIT per file) | **Vendor unmodified** (#483) | MIT notices kept in the files, with `LICENSE-CODE.txt` alongside and in `THIRD_PARTY_NOTICES.md`. Only the headers are used; the package's DLLs and other files fall under Microsoft's proprietary SDK terms and are never redistributed. |
|
||||
| Xbox console DirectStorage interfaces (`IDStorageFactoryX` and others) | `dstorage_xs.h` (GDK with Xbox Extensions) | **Rejected until a licence-compatible source exists** (#483) | Available only to licensed partners. Microsoft Learn and the MIT `Xbox-GDK-Samples` `dstorage_win32.h` document signatures and struct layouts but not the IIDs. |
|
||||
| GDK `QueryApiImpl` class and interface ids, inheritance and slot order for XGameSave and XPackage | xodus-gaming/xgameruntime-docs at `7090008` (GPL-3.0 text) | **Use as factual reference, pending maintainer provenance acceptance** (#468, #492) | Only interface facts are used, written as BetterXen's own code; no text or code is copied. The source describes its method as black-box reverse engineering under Wine's clean-room guidelines. `IXError` slot 3's `false` answer comes from the #492 review's interop observation instead; that source lists the slot as unknown. Revisit if the source's method or licence status changes. |
|
||||
|
||||
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
|
||||
@@ -0,0 +1,75 @@
|
||||
# Console compute shader entry ABI (probe results)
|
||||
|
||||
Recorded 2026-11-28 (CLAIM-XBOX-CS-ENTRY-ABI). This page lists facts derived from the assembly listing of Microsoft's Series X|S PIX shader compiler (its NewBE code generator), used under an authorization Microsoft gave the project for its GDK material (see "Provenance"). The compiler, its output and the GDK files are not in this repository. No listing, binary or documentation text is reproduced. Only the observations below are. It complements [RDNA 2 notes](rdna2.md), which cover AMD's public ISA, and [Shader containers](shader-containers.md).
|
||||
|
||||
What this is:
|
||||
- **Measured:** what the compiler emitted for eleven compute shaders the project wrote (p00–p10 below), compiled on one host: Apple M5, macOS 27.2.1, CrossOver 26.3 (26.3.0.39832), GDK 2026.10 (10.0.26100.9661).
|
||||
- **Inferred:** what each register holds. The interpretations below are read from the generated code. They agree with the user-SGPR, thread-group-ID and thread-ID fields of AMD's publicly documented `COMPUTE_PGM_RSRC2` register, which the compiler reports for each shader.
|
||||
|
||||
What this is not: a console run, a description of the ACCC/FSPX container, a description of the ACO backend that produces the code in ACCC containers (see "Root buffer access"), or anything about graphics stages. The compiler used here writes plain DXIL objects. The console code appears only in its assembly listing, so how that code is stored in an ACCC container is still unknown (CLAIM-XBOX-ISA-ABI).
|
||||
|
||||
## Method
|
||||
|
||||
Each probe is a `cs_6_5` compute shader (`cs_6_6` for the 64-bit atomic) with an explicit `[RootSignature]`. The compiler needs a root signature to generate console code. It reported "GFX10" for the target. The probes change one thing at a time:
|
||||
|
||||
| Probe | Root signature | Shader |
|
||||
| --- | --- | --- |
|
||||
| p00 | `SRV(t0), SRV(t1), UAV(u0)` | `o[i] = a[i] + b[i]`, 64 threads |
|
||||
| p01 | `RootConstants(num32BitConstants=4, b0), UAV(u0)` | uses all four constants |
|
||||
| p02 | `CBV(b0), UAV(u0)` | reads two constants |
|
||||
| p03 | `DescriptorTable(SRV(t0, numDescriptors=2)), DescriptorTable(UAV(u0))` | p00 through tables |
|
||||
| p04 | `DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), UAV(u0)` | `Texture2D.SampleLevel` |
|
||||
| p05 | `UAV(u0), SRV(t0), SRV(t1)` | p00 with the parameters reordered |
|
||||
| p06 | `UAV(u0)` | `[numthreads(8,8,1)]`, writes group and thread IDs |
|
||||
| p07 | `SRV(t0), UAV(u0)` | `WaveActiveSum` |
|
||||
| p08 | `SRV(t0), UAV(u0)` | 256 bytes of `groupshared` and a barrier |
|
||||
| p09 | `UAV(u0)` | 64-bit `InterlockedAdd` |
|
||||
| p10 | `RootConstants(num32BitConstants=20, b0), UAV(u0)` | sums all 20 constants |
|
||||
|
||||
## Observations
|
||||
|
||||
**Wave size.** Every probe was compiled for 64-lane waves: the compiler reported wave32 as disabled. In p07 `WaveActiveSum` became a full 64-lane reduction that combines the two 32-lane halves and uses a 64-bit execution mask. D3DMetal 4.0b3, the version measured in [D3DMetal GPU limits](d3dmetal-gpu-limits.md), runs 32-lane waves only; D3DMetal 3.0 was not measured. None of the probes declares a wave size, so wave64 is what this compiler generates by default, and console-compiled compute code has to be treated as wave64 unless it declares otherwise, not only when a shader declares `WaveSize(64)`.
|
||||
|
||||
**Root arguments in registers.** Root-signature data starts at `s4`, in root-parameter order. p05 moves the registers with the parameters.
|
||||
- A root constant takes one SGPR (p01: `s4`–`s7`).
|
||||
- A root CBV, SRV or UAV takes two SGPRs, a 64-bit GPU address (p00: `s4:s5`, `s6:s7`, `s8:s9`).
|
||||
- A descriptor table takes one SGPR, a 32-bit pointer. The shader clears the upper half itself (p03, p04).
|
||||
- The thread-group IDs follow the root data, x before y (p00: `s10`; p06: `s6`, `s7`). Thread IDs arrive in `v0` (x) and `v1` (y), as the reported thread-ID count indicates.
|
||||
|
||||
**Overflow.** `s0`–`s3` come before the root data. When the root data does not fit in user SGPRs (p10: 20 constants and a UAV), only those four are passed, and `s0:s1` holds the address of the root data in memory. The shader loads the constants from offset 0 and the UAV address from offset `0x50`, which is root dword 20. Whether `s0:s1` points at the same data when the arguments also fit in registers was not tested.
|
||||
|
||||
**Root buffer access.** For a root SRV, UAV or CBV, the shader builds the buffer descriptor itself from the root address:
|
||||
- **Stride:** in word 1, the `STRIDE` field (bits 29:16 in the public GFX10 layout), taken from the element type: 4 bytes for `uint`, 8 for `uint64_t`, 16 for the root CBV.
|
||||
- **Record count:** `-1` (`NUM_RECORDS` = 0xFFFFFFFF). With the `OOB_SELECT` below, the only bounds check compares the index against `NUM_RECORDS`, so it never fires: accesses through root descriptors are effectively not bounds-checked.
|
||||
- **Word 3:** the constant `0x11014fac` in every probe. Decoded with the public GFX10 buffer-descriptor layout (Mesa `src/amd/common/ac_descriptors.c` / `gfx10-rsrc.json`, LLVM `SIDefines.h`): destination swizzle X, Y, Z, W; `FORMAT` 20 (`32_UINT`); `RESOURCE_LEVEL` 1; `OOB_SELECT` 1 (the index is checked against `NUM_RECORDS`); `TYPE` 0 (buffer). These observations describe the NewBE path only. The ACO path (`xdxc`), which produces the code in the ACCC containers titles ship, generates different code for the same HLSL: its word 3 is `0x31016fac`, which decodes the same way except `FORMAT` 22 (`32_FLOAT`) and `OOB_SELECT` 3 (raw), two bits apart (`0x20002000`). Of these probes' facts, only the root UAV address in `s[4:5]` has been checked to agree on ACO. That comparison is recorded in the shader corpus PR [#650](https://github.com/MacosPorters/betterxen/pull/650) (open); until it lands, treat ACO agreement beyond that as unverified.
|
||||
|
||||
**Descriptor tables.** Descriptors are loaded from the table address:
|
||||
- buffer descriptors 32 bytes apart (p03 loads at offsets `0` and `0x20`);
|
||||
- a texture descriptor of 32 bytes and a sampler descriptor of 16 bytes (p04).
|
||||
|
||||
For each such load, the compiler also reported the instruction offset and the HLSL binding it came from: class, register, space and resource kind.
|
||||
|
||||
**Other.** p08 uses LDS (`ds_write_b32`, `ds_read_b32`), and its size shows in the reported LDS allocation. p09 is a native `buffer_atomic_add_x2`. The shader hash from the container's `HASH` part is embedded at the start of the generated code.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Branch D2** ([ADR 0008](../adr/0008-m2-shader-format-gate.md)) gains a candidate compute entry ABI: where root constants, root descriptors, table pointers and IDs are, and how buffer descriptors are formed, as the NewBE path generates them. It is not accepted for D2 until it is reproduced independently, and checked against the ACO code that ACCC containers carry.
|
||||
- **Binding recovery** may not need data-flow analysis if ACCC containers carry the same per-load binding table. That depends on the container format, which is still unknown.
|
||||
- **Wave64** is the default. The D1 path also needs to know whether a title's DXIL assumes 64 lanes.
|
||||
- **Bounds:** out-of-range accesses through root descriptors are not discarded on the console the way bounds-checked descriptors would discard them.
|
||||
|
||||
## Open
|
||||
|
||||
- **Graphics stages** (vertex and pixel inputs, exports) were not probed.
|
||||
- **ACCC-only output:** `xdxc` emits containers that keep DXIL and add ACCC. Which compiler or option emits ACCC-only (DXIL-stripped) containers, like those in the target workload's upscaler component (see the [roadmap](../roadmap.md) scan entry), is open.
|
||||
- **ACO agreement:** which of these NewBE facts hold for the ACO code (see "Root buffer access").
|
||||
- **SGPR alignment:** every probe placed its 64-bit root addresses after an even number of SGPRs. Whether an odd count of one-SGPR parameters before a root descriptor inserts a padding SGPR is untested.
|
||||
- **Overflow threshold:** the probes jump from 6 root dwords to 22. The exact cutoff, and whether overflow is always all-or-nothing, are unmeasured.
|
||||
- **`s0`–`s3`:** what they hold when root data fits in registers.
|
||||
- **One compiler build, one host:** a different GDK version may differ.
|
||||
|
||||
## Provenance
|
||||
|
||||
- **Source:** facts were read from listings that Microsoft's licensed Series X|S shader compiler produced for shaders the project wrote. That compiler is not public, so none of this can be checked against a public source, except the descriptor decode above.
|
||||
- **Authorization:** the maintainer (@atesahmet0) has stated that Microsoft's authorization for the project's use of its GDK material covers publishing derived observations like these in this repository. The material itself (the compiler, its listings and binaries, and the GDK documentation) is never committed. The authorization record is held privately (the process is proposed in [#661](https://github.com/MacosPorters/betterxen/pull/661)).
|
||||
- **Reproduction:** only a contributor with the same authorization can reproduce these observations. That reproduction has not happened yet, so the claim is recorded as class U: unestablished by public sources, with an authorized observation behind it.
|
||||
@@ -0,0 +1,175 @@
|
||||
# D3DMetal and Apple GPU limits for a shader translator
|
||||
|
||||
Constraints that a translator emitting shaders for D3DMetal on Apple Silicon has to
|
||||
handle (#453). Writing the translator is out of scope.
|
||||
|
||||
The note has two parts:
|
||||
|
||||
- [Measured constraints](#measured-constraints) come from
|
||||
`tests/conformance/test_d3dmetal_gpu_limits`, an original synthetic D3D12 compute
|
||||
fixture checked against values computed on the CPU. These are the only items the
|
||||
roadmap links to. They are a local Apple Silicon run by the implementer, class A for
|
||||
the stated host only, not independently reproduced.
|
||||
- [Unverified reports](#unverified-reports-not-evidence) are observations a contributor
|
||||
posted on #453 from local builds of another project running a commercial title. They are
|
||||
**not evidence** under [AGENTS.md](../../AGENTS.md) §5–6 and must not steer the plan
|
||||
until a synthetic workload reproduces them. They are kept only as leads for writing such
|
||||
workloads.
|
||||
|
||||
Nothing here is an Xbox hardware result, and nothing generalizes beyond the D3DMetal
|
||||
version named.
|
||||
|
||||
## Measured constraints
|
||||
|
||||
### `WaveSize(64)` is created but not run
|
||||
|
||||
`wave.control` (no `WaveSize`) and `wave.wavesize64` (`[WaveSize(64)]`, SM 6.6) record,
|
||||
for each thread, the wave width, its lane index and the dispatch index of its wave's first
|
||||
lane.
|
||||
|
||||
The control passes the check D3D12 actually guarantees: every thread reports the same
|
||||
width, and within each wave the lane indices are a permutation of `0..W-1`. No particular
|
||||
thread-to-lane order is assumed. On D3DMetal 4.0b3:
|
||||
|
||||
- the device reports `WaveLaneCountMin = WaveLaneCountMax = 32`;
|
||||
- the control runs at width 32;
|
||||
- the wave64 pipeline is **created without error but never runs**: its output buffer keeps
|
||||
the sentinel.
|
||||
|
||||
So a translator cannot rely on pipeline creation failing. A program written for a 64-lane
|
||||
wave has to be emitted as 32-lane code, with its two halves made to agree wherever the
|
||||
original wave acted as one.
|
||||
|
||||
### Kernels using SM 6.6 64-bit atomics are created but not run
|
||||
|
||||
`atomic64.image` runs a 64-bit `InterlockedAdd` (low halves carrying into the high half)
|
||||
and an `InterlockedMax` (decided by the high half) on a `RWTexture2D<uint64_t>` over
|
||||
`DXGI_FORMAT_R32G32_UINT`. `atomic64.buffer` runs the same operations on a raw buffer. Each
|
||||
kernel also writes a plain 64-bit marker next to its atomics, which shows whether the kernel
|
||||
ran at all. On D3DMetal 4.0b3:
|
||||
|
||||
- The device reports `AtomicInt64OnTypedResourceSupported` and
|
||||
`AtomicInt64OnDescriptorHeapResourceSupported` as supported, and both pipelines are
|
||||
created without error.
|
||||
- Neither kernel runs. The atomic results and the markers all read back as their initial
|
||||
zeros, on the texture and on the raw buffer alike.
|
||||
- A throwaway variant with the atomics removed but the markers kept wrote 8/8 markers.
|
||||
That shows the readback path is sound and the skip comes from the atomics.
|
||||
|
||||
So these kernels are silently skipped, on raw buffers as well as images. This is
|
||||
consistent with d3dmetal-native's `d3d12-atomic64-test` reading back zeros in the
|
||||
[d3dmetal-harness](../../shader-transpiler/crates/d3dmetal-harness/README.md) evaluation
|
||||
on D3DMetal 3.0. A translator has to lower 64-bit atomics to 32-bit operations.
|
||||
|
||||
### Lock-based emulation needs a sufficient retry cap and both fences
|
||||
|
||||
`lock64.cap64` and `lock64.cap1024` emulate both operations with a per-texel lock word,
|
||||
with 32 contending threads per texel and a bounded number of tries:
|
||||
|
||||
1. take the lock with `InterlockedCompareExchange` 0→1;
|
||||
2. `DeviceMemoryBarrier()` (**acquire**: the data reads are ordered after taking the lock;
|
||||
`globallycoherent` gives visibility, not ordering);
|
||||
3. update the two 32-bit halves;
|
||||
4. `DeviceMemoryBarrier()` (**release**);
|
||||
5. free the lock with `InterlockedExchange`.
|
||||
|
||||
A thread that runs out of tries counts a drop instead of spinning on. The 1024-try run is
|
||||
required to drop nothing and to match the CPU reference exactly. The 64-try run is
|
||||
reported. On D3DMetal 4.0b3, in three runs each:
|
||||
|
||||
- **1024 tries:** nothing dropped, 16/16 values exact, about 15,000–18,000 tries in all.
|
||||
- **64 tries:** 96–108 of 512 updates dropped.
|
||||
|
||||
So a low cap trades a hang for silently lost updates. With 32 contending threads, 64 tries
|
||||
is already too low.
|
||||
|
||||
The loop shape matters. The critical section sits **inside** the retry loop, so a lane
|
||||
that wins finishes it in the same iteration, and no lane waits for another lane to leave a
|
||||
loop. The fixture does not run the classic shape (`while (!acquire()) {}` followed by the
|
||||
critical section). There, the winning lane can be parked at the loop's reconvergence point
|
||||
behind the lanes still spinning, and on a GPU without independent forward progress for
|
||||
each thread that could hang the queue. Apple's shader converter prints `Warning:
|
||||
Undefined: Shader might rely on forward progress/persistent thread` even for the safe
|
||||
shape.
|
||||
|
||||
## Fixture results
|
||||
|
||||
A local run by the implementer on 2026-11-26. Class A for this host only; not
|
||||
independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Host | Apple M3 Pro, macOS 27.2.1 (26B131), Rosetta 2 |
|
||||
| Wine | CodeWeavers Wine 11.0 built from CodeWeavers' published source; CrossOver itself was not installed |
|
||||
| D3DMetal | 4.0b3 from Apple's Game Porting Toolkit (x86_64; SHA-256 of the binary starts with `b16aab78127d`), user-supplied |
|
||||
| Shaders | DXC 1.9.2609 via `shaders/compile.sh`; the same DXC reproduces the d3dmetal-harness `fill_cs66` container byte for byte (SHA-256 `7df11b63…`) |
|
||||
| Command | `ROSETTA_ADVERTISE_AVX=1 WINEDLLOVERRIDES="d3d12,d3d12core,dxgi=b" wine build-shims/bin/test_d3dmetal_gpu_limits.exe` in a fresh prefix |
|
||||
| Runs | 3, identical outcomes apart from the 64-try drop counts; exit 0, `SUMMARY: 4 required checks, 0 failed` each time |
|
||||
|
||||
| Check | Outcome |
|
||||
| --- | --- |
|
||||
| `device.shader_model` | 6.6 |
|
||||
| `wave.reported` | `WaveOps=1`, lane count min 32, max 32 |
|
||||
| `wave.control` | ran at width 32, lanes a permutation within each wave (required: pass) |
|
||||
| `wave.wavesize64` | created but not run (output still sentinel) |
|
||||
| `atomic64.reported` | typed and descriptor-heap 64-bit atomics reported as supported |
|
||||
| `atomic64.buffer` | not run: marker 0/8, atomic values 16/16 still zero |
|
||||
| `atomic64.image` | not run: marker 0/8, atomic values 16/16 still zero |
|
||||
| `lock64.cap64` | 108, 96 and 108 of 512 updates dropped (values not compared) |
|
||||
| `lock64.cap1024` | 0 of 512 dropped, 16/16 values exact (required: pass) |
|
||||
|
||||
**Exit codes.** The fixture exits **0** with every required check passed, **1** on a failed
|
||||
required check, and **77** with a `SKIP: <reason>` line when `d3d12.dll`, its exports, device
|
||||
creation, or shader model 6.6 is unavailable. 77 is not a pass; see the exit-status section of
|
||||
[`tests/conformance/README.md`](../../tests/conformance/README.md#exit-status-pass-fail-and-unavailable)
|
||||
for a recording recipe. Through `bx-cli run` the guest status is returned unchanged.
|
||||
|
||||
Still to do for the issue's validation requirement: an independent run on CrossOver 26.3
|
||||
(D3DMetal 3.0) by another contributor.
|
||||
|
||||
## Unverified reports (not evidence)
|
||||
|
||||
Reported on #453 from local VIctory-macOS-based builds running a commercial title on one
|
||||
host. None of this is a BetterXen measurement, no code or shader from that project is
|
||||
used, and none of it may be cited by the roadmap or a milestone gate. Each item names the
|
||||
synthetic workload that would turn it into evidence.
|
||||
|
||||
- **Splitting wave64 programs.** Operations that need care when the two halves must agree:
|
||||
- wave reductions;
|
||||
- first-lane and indexed lane reads;
|
||||
- the 64-bit lane mask read as data;
|
||||
- cross-half permutes;
|
||||
- scalar values spilled into vector lanes;
|
||||
- group barriers, which are only safe where both halves provably reach them.
|
||||
|
||||
The reporter found a uniformity analysis of the program's values, with barriers placed
|
||||
only after uniform branches, made most such programs translate exactly. Where agreement
|
||||
cannot be proven and each half runs as its own wave, a group sync that not every lane
|
||||
reaches must become a memory fence without the group wait. *Workload needed:* SM 6.6
|
||||
wave64-style kernels with each of these patterns, checked half by half.
|
||||
- **Helper lanes in a spin lock.** In a pixel shader, helper lanes must not take part in
|
||||
such a lock: their atomics have no effect, so they never win and spin to the cap. This
|
||||
was reported as a hard queue hang with no macOS GPU timeout logged. A cap of 2^16 was
|
||||
reported to hang while 2^10 did not; whether the cap or the helper lanes caused it was not
|
||||
separated. *Workload needed:* a pixel shader with a lock-protected 64-bit update across
|
||||
triangle edges.
|
||||
- **Mesh output size.** Metal refuses mesh pipelines whose per-vertex outputs exceed 32,768
|
||||
bytes, counting the aligned layout (distances, position, then outputs in register order,
|
||||
each aligned to its own size). A refused pipeline submitted anyway was reported to hang
|
||||
the queue under Wine. *Workload needed:* mesh shaders whose output size crosses 32 KiB
|
||||
only once alignment is counted.
|
||||
- **Apple shader compiler crash.** `MTLCompilerService` was reported to crash in register
|
||||
allocation on mesh pipelines whose pixel shader writes several render targets. The
|
||||
reported cause was output stores merged before all their values are defined, and the
|
||||
reported fix was emitting each output row's stores after its values. *Workload needed:* a
|
||||
mesh and pixel pair with several render targets and late-computed outputs.
|
||||
- **No zero-copy heaps.** D3DMetal 4.0b3 was reported to answer
|
||||
`ID3D12Device3::OpenExistingHeapFromAddress` with "Not implemented". *Workload needed:*
|
||||
a fixture that calls it on a page-aligned allocation.
|
||||
|
||||
## Regenerating the shaders
|
||||
|
||||
`tests/conformance/test_d3dmetal_gpu_limits/shaders/compile.sh` regenerates the committed
|
||||
headers with Microsoft's DXC release v1.9.2609 (`dxc_2026_09_29.zip`, SHA-256
|
||||
`ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1`, the same package the
|
||||
d3dmetal-harness records), running `bin/x64/dxc.exe` under a Wine loader.
|
||||
@@ -0,0 +1,88 @@
|
||||
# D3D12 swapchain references under D3DMetal
|
||||
|
||||
An observation to check before M2 builds presentation on `IDXGISwapChain3`. One Apple M4,
|
||||
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. See the independent Apple M2 Pro run below.
|
||||
|
||||
| | D3DMetal | Wine `vkd3d` path |
|
||||
| --- | --- | --- |
|
||||
| References on the swapchain right after creation | 2 | 1 |
|
||||
| Count returned by the application's final `Release` | 1 | 0 |
|
||||
| Swapchains still referenced after 12 create/release cycles | 12 | 0 |
|
||||
|
||||
The same program was used for both, and it submitted no GPU work of its own. Under D3DMetal
|
||||
each retained swapchain also kept a device reference. The cause inside D3DMetal is unknown. A
|
||||
program that recreates swapchains (for example on resize) should be expected to grow until this
|
||||
is explained.
|
||||
|
||||
The probe is
|
||||
[`lifetime.c` at `7c512af`](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_lifetime/lifetime.c)
|
||||
on the branch of #425; it is not part of this branch. Tracked in #450.
|
||||
|
||||
## Independent run on Apple M2 Pro
|
||||
|
||||
On 2026-11-26, an Apple M2 Pro (16 GiB, macOS 27.3 build 26C5035r) reproduced
|
||||
the swapchain retention in CrossOver 26.3.0.39832 with D3DMetal 3.0. The
|
||||
same x86-64 probe under Rosetta 2 released all swapchains in CrossOver
|
||||
Preview 27.0.0.41303. Each CrossOver build used a fresh Windows 11
|
||||
64-bit bottle. The Direct3D 12 workload loaded the `apple_gptk` D3D12
|
||||
and DXGI modules in both builds. The bundled framework in the Preview
|
||||
build's `apple_gptk` directory reports version 4.0b3.
|
||||
|
||||
| Swapchain lifetime probe | Initial reference count | Application release returned | Witnesses retained |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| 26.3 D3DMetal | 2 | 1 | 12 of 12 |
|
||||
| 26.3 Wine D3D12 | 1 | 0 | 0 of 12 |
|
||||
| Preview D3DMetal | 1 | 0 | 0 of 12 |
|
||||
| Preview Wine D3D12 | 1 | 0 | 0 of 12 |
|
||||
|
||||
Destroying the window before releasing the swapchain and calling
|
||||
`ResizeBuffers` before teardown each left 3 of 3 witnesses retained on
|
||||
26.3 D3DMetal. Explicitly detaching the witness released the probe's
|
||||
private data, while the swapchain's release still returned 1. The
|
||||
deliberately retained witness control failed as expected. An extra
|
||||
application-side `Release` would drop a reference the application
|
||||
does not own.
|
||||
|
||||
The separate D3D12 integrated workload presented 600 frames and verified
|
||||
eight readbacks with zero mismatches on both D3DMetal builds. It failed
|
||||
only the shutdown gate on 26.3, where the final device release returned
|
||||
2. Preview passed shutdown with a final device release of 0. These runs
|
||||
used the direct host D3D12 path without BetterXen's D3D12 shim. The
|
||||
comparison establishes behavior for these two CrossOver builds on this
|
||||
host. The underlying ownership change is unknown.
|
||||
|
||||
Build the probe from the pinned source linked above with
|
||||
`x86_64-w64-mingw32-clang -std=c11 -O2 -Wall -Wextra -Werror lifetime.c -o d3d12-lifetime.exe -ld3d12 -ldxgi -ldxguid -luser32`
|
||||
(LLVM-MinGW 20261117 in this run). Run in a clean bottle using
|
||||
`ROSETTA_ADVERTISE_AVX=1 CX_GRAPHICS_BACKEND=d3dmetal wine --bottle <bottle> <absolute-path-to-exe> --cycles 12`
|
||||
and repeat with `CX_GRAPHICS_BACKEND=wined3d`. The two witness controls
|
||||
use `--cycles 3 --detach-witness` with and without `--retain-app-reference`.
|
||||
|
||||
## Related Direct3D acceptance failures
|
||||
|
||||
The [integrated D3D12 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_integrated/integrated12.c)
|
||||
also reproduced the presentation slowdown on the Wine D3D12 path on
|
||||
26.3. With `CX_GRAPHICS_BACKEND=wined3d` and a 600-frame target, the
|
||||
workload logged approximately 2,000 ms inside `Present` on frames
|
||||
12–38, then exited 3 after a 10-second GPU completion wait failed. The
|
||||
previous M4 report saw the slowdown around frame 437. This run exited
|
||||
before reaching normal teardown. Preview completed the same 600-frame
|
||||
workload on the Wine path with eight verified readbacks, no mismatches
|
||||
and clean shutdown. A 600-frame repeat on 26.3 passed with `--vsync`
|
||||
enabled. A subsequent 600-frame repeat also passed with the flag off,
|
||||
so the slowdown remains intermittent and the successful vsync run
|
||||
does not establish a workaround.
|
||||
|
||||
The [integrated D3D11 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d11_integrated/integrated.c)
|
||||
completed the 20,000-frame soak on 26.3 with 46 verified readbacks,
|
||||
zero mismatches and a clean shutdown. The intermittent GPU event
|
||||
stall did not recur in this run. Preview also completed all 20,000
|
||||
frames and all 46 readbacks, then failed the shutdown gate with one
|
||||
device reference remaining. A separate 600-frame Preview run
|
||||
reproduced that shutdown result.
|
||||
|
||||
The 26.3 keyboard check delivered five macOS events to the workload and
|
||||
reached the expected offset (16, 32). The negative control delivered
|
||||
two Up events and reached (0, -32), which the input gate rejected as
|
||||
expected. These were isolated runs, so they do not reproduce the
|
||||
intermittent failure observed inside the full acceptance suite.
|
||||
@@ -84,3 +84,97 @@ Identification is not execution. `xenora shaders coverage` reports forms
|
||||
discovered in metadata against forms the semantic decoder accepts
|
||||
(`xenora_decoder::SEMANTIC_FORMS`); reference, Metal and native GPU evidence
|
||||
per form remains in `docs/status.toml`.
|
||||
|
||||
## 64 KiB swizzle (`SW_64KB_S`) — public sources (#505)
|
||||
|
||||
`xg_xs.dll` implements `SW_64KB_S` tile addressing for `TEXTURE2D`, one array
|
||||
slice and one mip, over the element sizes the RB+ tables specify: 32-bpp RGBA8
|
||||
(4-byte elements) and the BC family — BC1/BC4 with 8-byte blocks and
|
||||
BC2/3/5/6H/7 with 16-byte blocks, where one "texel" element is a 4x4 block and
|
||||
`elemLog2 = log2(block_bytes)`. At 32 bpp the two public sources below agree
|
||||
bit-for-bit, which is why this is the mode implemented first; the 8- and 16-byte
|
||||
rows come from AddrLib alone.
|
||||
|
||||
**Microsoft, `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE`** (public, no NDA):
|
||||
<https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout>.
|
||||
The page gives the 32-bpp masks `xBytesMask = 0xAA8F` and `yMask = 0x5570`,
|
||||
combined with `_pdep_u32`. It states that tail-mip packing is **adapter-specific**,
|
||||
which is why only the single-mip case is implemented. It has no `D` or `R` variant.
|
||||
|
||||
**AMD AddrLib (MIT)** — the authoritative public implementation, in both
|
||||
[Mesa `src/amd/addrlib`](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib)
|
||||
and [AMD PAL](https://github.com/GPUOpen-Drivers/pal/tree/dev/src/core/imported/addrlib)
|
||||
(`SPDX-License-Identifier: MIT`, AMD copyright; PAL `LICENSE.txt` is MIT):
|
||||
|
||||
- `src/amd/addrlib/inc/addrtypes.h` — `AddrSwizzleMode`: `ADDR_SW_64KB_S` = 9,
|
||||
`_D` = 10, `_R` = 11 (Reserved on GFX10).
|
||||
- `src/amd/addrlib/src/gfx10/gfx10SwizzlePattern.h` — `GFX10_SW_64K_S_PATINFO`
|
||||
and `GFX10_SW_64K_S_RBPLUS_PATINFO`, plus the `GFX10_SW_PATTERN_NIBBLE01/2/3/4`
|
||||
tables. The RB+ variant is used because `gfx1030` is Navi2x.
|
||||
- `src/amd/addrlib/src/gfx10/gfx10addrlib.h` — `GetSwizzlePatternFromPatternInfo`,
|
||||
`IsInMipTail`.
|
||||
- `src/amd/addrlib/src/gfx10/gfx10addrlib.cpp` — `GetSwizzlePatternInfo`,
|
||||
`HwlComputeSurfaceAddrFromCoordTiled`, `ComputeSurfaceAddrFromCoordMacroTiled`.
|
||||
- `src/amd/addrlib/src/core/addrlib2.cpp` — `ComputeThinBlockDimension`,
|
||||
`Block256_2d`.
|
||||
|
||||
There is **no** standalone GPUOpen `addrlib` repository (404). The public
|
||||
[RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf)
|
||||
only names a 5-bit "SW mode" field in the T# descriptor (bits 120:116) and does
|
||||
not define the patterns.
|
||||
|
||||
### S versus D versus R
|
||||
|
||||
- **S and D are not interchangeable.** At 32 bpp RB+, D uses nibble01 index 39
|
||||
(`[0,0,X0,X1,Y0,Y1,X2,Y2]`) while S uses index 2
|
||||
(`[0,0,X0,X1,Y0,Y1,Y2,X2]`) — address bits 6 and 7 swapped.
|
||||
- **`SW_64KB_R` has no public GFX10 form.** Mesa's `SwizzleModeTable` marks
|
||||
`ADDR_SW_64KB_R` (enum 11) as Reserved; the render-target mode is
|
||||
`ADDR_SW_64KB_R_X`, whose pipe/packer XOR depends on the console
|
||||
`GB_ADDR_CONFIG`, which is not public.
|
||||
|
||||
### Xbox `XG` tile modes are NDA
|
||||
|
||||
`scarlett-tex-layouts` returns HTTP 200 with only the membership gate; all
|
||||
`/windows/win32/api/xg/*` paths 404. The numeric `XG_SWIZZLE_MODE` values are
|
||||
not public. BetterXen's earlier local `BX_XG_LAYOUT_*` constants and clean-room XG
|
||||
interface have been retired: `xg_xs.dll` now follows the documented XG contract
|
||||
titles call, with values from the authorized GDK documentation recorded as derived
|
||||
facts in `shims/xg_xs/xg_xbox.cpp`.
|
||||
|
||||
### Element sizes and the derived masks
|
||||
|
||||
For a 64 KiB tile the intra-tile byte offset of element (x, y) is
|
||||
`pdep(x, x_mask) | pdep(y, y_mask)`, where x and y are **block** indices (one
|
||||
4x4 block for BC, one texel for 32 bpp). The masks were expanded by hand from
|
||||
`GFX10_SW_PATTERN_NIBBLE01/2/3` at the patinfo indices
|
||||
`GFX10_SW_64K_S_RBPLUS_PATINFO` selects for each `elemLog2`:
|
||||
|
||||
| block bytes | formats | `elemLog2` | x mask | y mask | tile (blocks) |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 4 | R8G8B8A8_* | 2 | `0xAA8C` | `0x5570` | 128 x 128 |
|
||||
| 8 | BC1, BC4 | 3 | `0xAAC8` | `0x5530` | 128 x 64 |
|
||||
| 16 | BC2, BC3, BC5, BC6H, BC7 | 4 | `0xAAC0` | `0x5530` | 64 x 64 |
|
||||
|
||||
At 32 bpp the x mask `0xAA8C` is Microsoft's public `xBytesMask` `0xAA8F` with
|
||||
the two intra-texel byte bits cleared (`0xAA8F & ~0x3`), and the y mask matches
|
||||
`0x5570` exactly. The 8- and 16-byte rows have no D3D12 page to cross-check
|
||||
against; they are AddrLib-only, which is stated in the PR risks. All three rows
|
||||
were checked to be bijections over their 64 KiB tile (16384 / 8192 / 4096
|
||||
distinct offsets, each block-aligned and inside the tile).
|
||||
|
||||
### Verification
|
||||
|
||||
The three masks above were expanded and their bijectivity checked against an
|
||||
independently written `pdep` reference, outside the shim. `test_xg_xbox.exe`
|
||||
(which replaced the retired `test_xg_xs.exe`) does not read its expected values
|
||||
back from the shim:
|
||||
- at 32 bpp it compares every offset of a one-tile texture with the public D3D12
|
||||
standard swizzle, and checks the offset -> texel inverse and a copy round trip;
|
||||
- at 8 and 16 bytes per element (the 8-byte case as BC1 blocks) it checks that
|
||||
the offsets are a bijection of aligned slots inside the 64 KiB tile;
|
||||
- it checks that the 16 texels of a BC block share one byte offset.
|
||||
|
||||
Requested modes the shim does not implement (`SW_64KB_D`, multi-tile, multi-mip)
|
||||
are laid out linearly and reported as `LINEAR`. Synthetic evidence only; no
|
||||
Xbox-hardware claim.
|
||||
@@ -14,6 +14,7 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
|
||||
| VIctory | [Marvisak/VIctory](https://github.com/Marvisak/VIctory) | `13f91caee25f` | GPL-3.0 (GitHub); a prior local review found per-file notices (see `experiments/victory-native/licenses.md`, local, untracked) | Discovery reference only | Described as an attempt at running one commercial game on PC. Its inputs are an Xbox Series build of that game. PortWatch describes the efforts it tracks as targeting a "leaked Xbox Series build". |
|
||||
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in retired `portwatch-native-macos.md` at tag `native-first-final`). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
|
||||
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
|
||||
| libc | [rust-lang/libc](https://github.com/rust-lang/libc) | `0.2.191` (`ccc2ff4aaab9`) | MIT OR Apache-2.0 (used under MIT) | `bx-cli` process groups and signals (#408) | Unmodified crates.io dependency, locked checksum. |
|
||||
|
||||
## Built and run for M1-D2 (#417)
|
||||
|
||||
@@ -25,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.
|
||||
|
||||
+91
-13
@@ -1,6 +1,6 @@
|
||||
# BetterXen Roadmap
|
||||
|
||||
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). Track ownership and parallel workflow rules live in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); Wave 1 contributor issues live in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
|
||||
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). How the team and its agents work is in [docs/process/working-method.md](process/working-method.md). Track (directory) ownership is in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); the completed Wave 1 issues are in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
|
||||
|
||||
## Direction
|
||||
|
||||
@@ -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):
|
||||
@@ -18,34 +19,111 @@ External Foundation (user-installed, never bundled):
|
||||
Apple Silicon: ARM64, Metal, unified memory
|
||||
```
|
||||
|
||||
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. Progress is measured strictly by reproducible synthetic conformance tests and recorded verification evidence — never by commit counts or unverified compatibility claims.
|
||||
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. The product goal is one project-authorized target build, fully playable on Apple Silicon Macs with 16 GB of memory. From the Boot stage on, progress is measured by how far that build gets in repeated, recorded runs ([working method](process/working-method.md)); every contract a fix introduces is also pinned by a synthetic conformance test. Progress is never measured by commit counts or unverified compatibility claims.
|
||||
|
||||
Priorities, in order: practical compatibility, correctness, stability, observability, Apple Silicon performance, and long-term maintainability.
|
||||
|
||||
---
|
||||
|
||||
## Completed Research Inputs (Carried Forward)
|
||||
## Research Inputs
|
||||
|
||||
- **Licensing & redistribution boundaries:** [docs/research/crossover-licensing.md](research/crossover-licensing.md) and [docs/licenses.md](licenses.md) (#354). CrossOver, D3DMetal, and Rosetta 2 stay strictly external and unbundled.
|
||||
- **Primary-source verification & upstream registry:** [docs/research/primary-source-verification-2026-11-25.md](research/primary-source-verification-2026-11-25.md), [docs/research/upstream-registry.md](research/upstream-registry.md), and [docs/research/component-reuse-matrix.md](research/component-reuse-matrix.md).
|
||||
- **Hybrid measurement protocol:** [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) (#353).
|
||||
- **Buffer ownership on CrossOver 26.3.0.39832 and D3DMetal 3.0 (#473).** On the tested M4 (24 GiB) and M5 (16 GiB), the two existing-memory heap imports returned `E_NOTIMPL`. A D3D12-owned persistent buffer mapping supported fence-separated CPU/GPU access and ordered virtual aliasing (BASE-2, BASE-4, A-8). The actual CPU address could miss 64 KiB alignment (A-6). Inside the timed small-copy window, no serialized copy cost as much as the explicit full copy to READBACK. The other workstream accepted 13 of 29 register entries within stated scopes, mostly through same-source reruns. #473 remains open. Physical page identity, hidden copies, workload memory savings and speedups remain open. [Report 001](https://github.com/MacosPorters/betterxen/blob/0aaa81ab81309d64432d97d3005284c8b13cd285/docs/research/publications/001-unified-memory/technical-findings.md) · [Evidence register](https://github.com/MacosPorters/betterxen/blob/f8810a48af384d13c594b9fba954200bfdb944f1/docs/research/d3dmetal-zero-copy/allocation-profiling/consolidation-draft/evidence-register.md) · [Review corrections](https://github.com/MacosPorters/betterxen/discussions/493)
|
||||
- **Target-workload shader corpus (static scan, 2026-11-28).** A read-only container scan of an authorized local test workload measured what its shipped components embed — structure only, no run, no extraction, and the workload is not redistributed. Its `XboxBvhBuilder` component carries **52 DXIL compute containers, all Shader Model 6.5, with valid LLVM bitcode**; its AMD FidelityFX upscaler component carries **29 ACCC-only containers** whose payloads start with `FSPX`, none with a `DXIL` chunk; its main executable carries **10 DXIL containers (nine pixel, one vertex, Shader Model 6.6) whose `DXIL` chunks hold four-byte `NOBC` payloads** — valid program headers, no executable bitcode. Its packaged shader archive exposes no plaintext `DXBC` signatures and remains unclassified. BetterXen's classifier accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers because their section tables do not match the clean-room `FSPX` layout (`FspxSectionOutOfBounds` at the time of the scan; that cause is `FspxLayoutMismatch` since #599, not re-measured). Runtime use is unmeasured: the recorded startup run stopped before pipeline creation and wrote no `shader_gate` records. [ADR 0008](adr/0008-m2-shader-format-gate.md)
|
||||
|
||||
---
|
||||
|
||||
## Milestones (M0 → M6)
|
||||
## Foundation and stages
|
||||
|
||||
| Milestone | Objective | Exit Gate | Status |
|
||||
The first three milestones (M0 to M2) were defined by subsystems and synthetic tests. They built the foundation, and they also showed the limit of that approach: with M1 verified complete, the target build still stopped at more than a dozen missing or wrong contracts that no synthetic test had asked for. From here on, the roadmap is a ladder of **stages the target build reaches**, observed in runs every collaborator can repeat. Synthetic conformance tests stay mandatory for every contract a fix introduces; they no longer define progress.
|
||||
|
||||
### Foundation (history)
|
||||
|
||||
| Milestone | What it established | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & cross-build** | Track layout, frozen `.def`/header contracts, env-isolated `bx-cli`, export verifier, live smoke tests | **Verified complete (#406)** |
|
||||
| **M1 — Startup shims to `D3D12XboxCreateDevice`** | Wave 1 shims across Tracks A–F and the combined synthetic boot fixture | **Verified complete (Milestone #17)** |
|
||||
| **M2 — Synthetic first frame & shader format gate** | `PresentX` through D3DMetal with pixel readback; Xbox-layout D3D12 objects (ADR 0009); the shader format question | **Closing.** Remaining: amend ADR 0008 to select Branch D2. The target build supplies console-compiled code only: shader containers whose `DXIL` part carries no bitcode, and serialized pipelines. |
|
||||
|
||||
### The stages
|
||||
|
||||
Every gate below is measured the same way ([working method](process/working-method.md#run-protocol)): the current `main`, the offline sandbox, a contributor's own bottle, **ten runs**, on a 16 GB Apple Silicon Mac. A gate that says "10/10" means ten of ten. Stages have names, not numbers: exactly one is current, and blocker issues carry its label (`stage: boot`, `stage: picture`, …).
|
||||
|
||||
| Stage | The target build… | 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 | **In validation (PR #406)** |
|
||||
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime`, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, and combined synthetic integration boot fixture | All 13 Wave 1 conformance binaries pass under CrossOver + Rosetta 2; combined `integration_boot.exe` initializes every subsystem cleanly | **Next (Wave 1 ready)** |
|
||||
| **M2 — First Rendered Frame & Shader Format Gate** | Implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), placed resources over `xmem`, and `dxbc-accc` shader inspection to establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)** | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | Planned |
|
||||
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
|
||||
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
|
||||
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
|
||||
| **M6 — Shader Cache, 16 GB Optimization & Polish** | Persistent disk PSO + translated-shader cache, Lockhart 16 GB unified memory pressure tuning, Metal System Trace optimization, and optional Swift launcher UI | Reproducible frame-pacing and memory-pressure receipts under [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) | Planned |
|
||||
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **In development** |
|
||||
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | Planned |
|
||||
| **Menus** | plays its opening sequence and menus with sound and input | A scripted input sequence goes from launch to the last menu before gameplay in 10/10 runs; audio is audible and in sync by the checklist; a save written in one run is read in the next | Planned |
|
||||
| **World** | loads into gameplay and keeps running | 10/10 runs enter gameplay and run 10 minutes with no crash, hang or early exit; streaming requests complete without error; memory stays inside the 16 GB profile | Planned |
|
||||
| **Fidelity** | draws its 3D scenes as the console does | The scene checklist (geometry, textures, lighting, effects, HUD) passes against the reference set at the fixed capture points; no draw or dispatch is skipped or stubbed | Planned |
|
||||
| **Playable** | is playable start to finish on every supported Mac | 30 fps or better at the tier's resolution for each chip tier; a 2-hour session with bounded memory and no hang; warm start uses the shader cache; controller and keyboard/mouse complete | Planned |
|
||||
|
||||
"Reference image" and "reference set" are captures of the same content from a real console or from published footage, kept in the private evidence store, never in the repository ([working method](process/working-method.md#evidence-and-references)).
|
||||
|
||||
### Boot
|
||||
|
||||
**Known work, all found by running the target build:**
|
||||
|
||||
| Blocker | Effect | State |
|
||||
| --- | --- | --- |
|
||||
| `CLZERO` trapped once per 64 bytes | The frame loop stalls for tens of seconds while the build zeroes memory | Fix exists locally (the loop completes in one trap); needs a PR and a conformance test |
|
||||
| A storage worker writes into a page xmem is remapping | The build's own fault handler exits (status 5) | Bounded retry exists locally. The real fix is an atomic remap in `xmem` |
|
||||
| Missing runtime calls: `XUserDuplicateHandle`, `XAsyncRun`, `XTaskQueue` duplicate/port/composite, `XGameSaveGetContainerInfo` and its by-name variant | The build waits forever or exits (status 1) | Implemented locally; need PRs and tests |
|
||||
| Serialized-pipeline calls answered with success in null-render mode | The build never falls back to its shader containers | Decide and document: these calls fail (logged) until they are implemented |
|
||||
| One early exit (status 1) with nothing logged | 1 run in 5 | Open: needs the run report's exit capture |
|
||||
| Run tooling lives outside the repository | Nobody else can repeat a run or read its result the same way | Move the offline runner, the run report and the sampler into `launcher/` and `scripts/` |
|
||||
|
||||
**Not needed for the gate:** audio output, correct pictures, performance.
|
||||
|
||||
### Picture
|
||||
|
||||
This is where the shader translator becomes the critical path, and where the D3DMetal route is tested for real. The risk checks come **first**, before feature work depends on them.
|
||||
|
||||
1. **Capability checks on D3DMetal (first).** Synthetic tests, one each, for what translated shaders need: direct descriptor-heap indexing (SM 6.6), 64-lane compute behaviour through the translator's emulation, 64-bit atomics on typed resources, mesh and amplification shaders. Each ends in *runs correctly*, *can be worked around in the translator*, or *blocked*. A *blocked* result opens an ADR on the back end, marked `needs-human`, before anything else in this stage continues.
|
||||
2. **The translator.** Vendor a pinned copy of the authorized upstream GFX10-to-DXIL translator into `shader-transpiler/` (per-file licence check, upstream registry and reuse matrix entries, ADR 0008 amendment), and expose it through `bx_shader_bridge.dll`. BetterXen owns its copy and fixes it.
|
||||
3. **Translator verification.** Extend the known-source corpus (#650) so every instruction class the first screens use is checked against a reference result. A translator bug is found with a ten-line shader, not in a broken frame.
|
||||
4. **The first pipelines.** The clear pipeline, the display-mapping compute shader, and whatever the first reference screen draws with, created on the host on first use.
|
||||
5. **Descriptors and memory the shaders read.** The descriptor model the translated shaders expect; contents of textures placed in title memory (today a logged stub); title-written constant and vertex data reaching the GPU.
|
||||
|
||||
### Menus to Playable — known work and unknowns
|
||||
|
||||
Listed so lanes can prepare, not as a commitment to order. Each item is confirmed by a run before work starts on it.
|
||||
|
||||
| Stage | Known work | Main unknown |
|
||||
| --- | --- | --- |
|
||||
| **Menus** | XMA decoding and audio output through the audio coprocessor contract; `GameInput` devices; speech/accessibility provider; saves round trip | What the build waits for between sign-in and its first screen |
|
||||
| **World** | DirectStorage page destinations, BCPack and swizzle options; XG tiling modes beyond linear; atomic page remapping; the Series S memory profile as the 16 GB default | Streaming behaviour under memory pressure |
|
||||
| **Fidelity** | Mesh/amplification pipelines; indirect draws with console argument types; rectangle lists; the unimplemented command-list state calls; upscaler substitute (FSR 3.1 or plain scaling in place of the console's FSR 4); ray tracing: bridge it, or run the profile that does not use it | How much of the frame depends on the console's ray-tracing path |
|
||||
| **Playable** | Translated-shader and pipeline cache; memory copies removed where the host allows; frame pacing against the display; chip-tier matrix | Whether the base 16 GB tier reaches 30 fps, and at what resolution |
|
||||
|
||||
### Decision gates
|
||||
|
||||
A gate is a question answered by a measurement, with the options written down before the measurement is taken.
|
||||
|
||||
| Gate | When | Question | If the answer is no |
|
||||
| --- | --- | --- | --- |
|
||||
| **Back end** | Start of Picture | Does D3DMetal run what translated console shaders need? | ADR: translator-side lowering, another host back end, or a narrower shader profile |
|
||||
| **Reference** | Start of Picture | Do we have reference images for the first screens? | The Picture gate falls back to a written checklist per screen, agreed by two collaborators |
|
||||
| **Memory** | Start of World | Does the build load into gameplay inside the 16 GB profile? | Series S profile only; reduce copies before any other World work |
|
||||
| **Frame rate** | Start of Playable | Is the base tier within 2x of 30 fps? | Publish tiers honestly; lower the base tier's resolution before promising it |
|
||||
|
||||
### What counts as progress
|
||||
|
||||
A change belongs on `main` only if it passes the **step-forward test**. It must do one of these, and say which:
|
||||
|
||||
1. remove a blocker of the current stage (shown by the run report before and after);
|
||||
2. remove a blocker already confirmed for a later stage, when every blocker of the current stage is claimed;
|
||||
3. make a blocker faster to find (run tooling, diagnostics, a corpus test);
|
||||
4. retire a risk at a decision gate.
|
||||
|
||||
Work that does none of these waits: subsystems nobody has seen the build need, documentation about work not yet done, and optimisation before the Playable stage.
|
||||
|
||||
---
|
||||
|
||||
## How Progress Is Reported
|
||||
|
||||
Milestone status is one of: `Planned`, `In development`, `In validation`, `Verified complete`, or `Blocked`. A milestone reaches `Verified complete` only after independent verification of its exit gate per [AGENTS.md](../AGENTS.md).
|
||||
|
||||
For the stages, the pinned ladder issue carries the live status: the current stage, the latest ten-run result for its gate, and the open blocker issues with their claims. A gate result is reported with every run counted, the machine it ran on, and the `main` commit.
|
||||
@@ -0,0 +1,137 @@
|
||||
# Target-Build Bring-Up: Development Cycle and Review
|
||||
|
||||
This is how any number of contributors run a project-authorized target build on BetterXen, turn what they find into pull requests, and review each other's work. It applies [AGENTS.md](../../AGENTS.md) Sections 5–7, the clean-room and provenance rules in [CONTRIBUTING.md](../../CONTRIBUTING.md), and [docs/legal.md](../legal.md). It adds no new permissions.
|
||||
|
||||
## Authorization is recorded, not assumed
|
||||
|
||||
AGENTS.md §6 allows evidence from *project-authorized* target builds, but it does not define who authorizes a build or how. Until a governance change defines that, this procedure requires a **recorded authorization**:
|
||||
|
||||
- **Before any target-build work,** a contributor writes an authorization note in the team's private evidence store (see "Evidence"). The note covers:
|
||||
- the build;
|
||||
- the evidence class: target-build observation, or authorized SDK documentation;
|
||||
- the maintainer who approved it;
|
||||
- how the contributor obtained the build or documentation lawfully, under terms that permit the inspection;
|
||||
- the confirmation that the work needs no decryption or circumvention of security, DRM, licensing or activation controls.
|
||||
- **Maintainer approval alone is not enough** (CONTRIBUTING.md). If any of these points is unknown, the build is not used.
|
||||
- **The note's ID goes into every PR and every review** that relies on that evidence.
|
||||
|
||||
## Roles
|
||||
|
||||
- **Bring-up keeper.** One person keeps a running branch (for example `bringup/<topic>`). It merges the open fix branches, so the title can be run end to end. This branch is never proposed for `main`. The role can rotate.
|
||||
- **Author.** Turns one finding into one single-track PR.
|
||||
- **Reviewer.** Anyone other than the author whose own recorded authorization covers the same evidence class. The reviewer re-derives the contract from their own authorized source, never from the author's copies, notes or binaries. Someone who has accessed leaked or confidential material does not review (CONTRIBUTING.md).
|
||||
- **Merger.** A maintainer other than the original author (AGENTS.md §7).
|
||||
|
||||
Work is organised by **area**, not by person. Areas follow the tracks in [parallel-tracks.md](../architecture/parallel-tracks.md): memory and storage, D3D12, XG, runtime and audio, shaders, tests and tooling. Each contributor claims an issue in an area. As more people join, an area takes more claims, but its file scope stays the same.
|
||||
|
||||
## Cycle
|
||||
|
||||
1. **Measure on the bring-up branch.** Run the title only through the offline-run procedure below. Find the first blocker with BetterXen's own diagnostics.
|
||||
2. **Record the evidence privately,** under an evidence note ID.
|
||||
3. **Open an issue** for the blocker. Name the API or contract. Do not name the title.
|
||||
4. **Fix it on a track branch off `main`.** Stay within the issue's file scope. Add or update a synthetic conformance test for every contract the fix relies on.
|
||||
5. **Open a PR** using the template below. The bring-up keeper merges the branch into the bring-up branch so that later blockers can be found.
|
||||
6. **Review independently** (see "What a reviewer does").
|
||||
7. **Merge and re-sync.** After a merge, the bring-up keeper rebases the bring-up branch on `main`.
|
||||
|
||||
### Bring-up checkpoints
|
||||
|
||||
These checkpoints describe how far a target build gets. They are **not** milestone status: milestones, their exit gates and the status vocabulary are defined only in [docs/roadmap.md](../roadmap.md) (M0–M6). A checkpoint can serve as evidence for a roadmap exit gate only where that gate says so.
|
||||
|
||||
1. **Starts:** reaches its first graphics device.
|
||||
2. **Presents:** presents its first frame, whatever it contains.
|
||||
3. **Frame loop:** keeps presenting for a recorded duration.
|
||||
4. **Rendered content:** presents pixels produced by its own shaders (needs the M2/M3 shader work).
|
||||
5. **Interactive:** reaches a menu that accepts input.
|
||||
|
||||
Each PR states which checkpoint it affects, and the measured result before and after.
|
||||
|
||||
## PR description template
|
||||
|
||||
```text
|
||||
Contract: the derived facts (sizes, offsets, slot orders, flags, units, return values)
|
||||
Source: "authorized SDK documentation" and/or "target-build observation";
|
||||
never quote header or documentation text, never name the title or build
|
||||
Authorization: authorization note ID
|
||||
Evidence: evidence note ID(s)
|
||||
Reproduce: the BetterXen commit, bx-cli options, BX_* switches and log events a reviewer checks
|
||||
Test: the conformance test that asserts the contract, and how its expected
|
||||
values were derived independently of the implementation
|
||||
Checkpoint: the checkpoint this affects, with the measured result before and after
|
||||
```
|
||||
|
||||
## What a reviewer does
|
||||
|
||||
The reviewer re-derives the contract and does not rely on the PR's conclusions (AGENTS.md §5).
|
||||
|
||||
1. **Documentation facts.** Compile a local probe against their own authorized headers and print the sizes, offsets and constants. Probes and their output stay outside this repository.
|
||||
2. **Title behaviour.** If the fix depends on how the title uses an API (for example, units it stores or flags it passes), check this in their own analysis, under their own authorization.
|
||||
3. **Title run.** Run the PR branch merged into the bring-up branch, using the offline-run procedure, and confirm the stated before-and-after result.
|
||||
4. **Checks.** Run the AGENTS.md §8 checks. Confirm that the conformance test's expected values do not come from the code under test.
|
||||
5. **Post the review.** Say what was re-derived and what was run, without proprietary details, and cite the note IDs.
|
||||
|
||||
## Offline-run procedure
|
||||
|
||||
Every title run must be unable to reach the network, because some titles upload crash dumps. The run is wrapped in a macOS sandbox profile that denies outbound IP traffic. Apple marks `sandbox-exec` as deprecated, but it still enforces profiles on current macOS; if it stops working, do not run the title until a replacement is documented here.
|
||||
|
||||
Copy these commands, filling in the bracketed values. Record the BetterXen commit (`git rev-parse HEAD`) and these exact commands in the evidence note.
|
||||
|
||||
```sh
|
||||
CX=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver
|
||||
BOTTLE=<bottle name>
|
||||
PREFIX="$HOME/Library/Application Support/CrossOver/Bottles/$BOTTLE"
|
||||
PROFILE='(version 1)(allow default)(deny network-outbound (remote ip))'
|
||||
|
||||
# 1. Stop the bottle's wineserver. A wineserver started outside the sandbox would
|
||||
# serve the title outside it.
|
||||
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -k
|
||||
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -w
|
||||
|
||||
# 2. Confirm the profile blocks outbound traffic. This must print BLOCKED; otherwise stop.
|
||||
sandbox-exec -p "$PROFILE" /usr/bin/curl -sS -m 5 https://example.com >/dev/null 2>&1 \
|
||||
&& echo REACHABLE || echo BLOCKED
|
||||
|
||||
# 3. Run the title inside the same profile. Every process it starts, including the new
|
||||
# wineserver, inherits the sandbox.
|
||||
env -i HOME="$HOME" USER="$USER" TMPDIR="$TMPDIR" PATH=/usr/bin:/bin:/usr/sbin:/sbin \
|
||||
BX_TRACE_D3D=0 BX_NULL_RENDER=1 \
|
||||
sandbox-exec -p "$PROFILE" target/debug/bx-cli run --inherit-env \
|
||||
--bottle "$BOTTLE" --backend d3dmetal --profile <profile> \
|
||||
--log <run>.jsonl --shims build-shims/bin --exe <path to the title executable>
|
||||
```
|
||||
|
||||
**Why `env -i` with `--inherit-env`:** `bx-cli run` normally clears the guest environment to a fixed allowlist (AGENTS.md §3), and that allowlist has no `BX_*` diagnostic switches. Here `env -i` builds an environment that contains only the listed variables, and `--inherit-env` passes exactly that to the guest. Host credentials and other variables still never reach it.
|
||||
|
||||
**Confirming that the title stayed offline.** Run a guest-side probe that tries an outbound connection the same way. It must fail inside the sandbox and succeed outside it. The probe and its output belong in the evidence note.
|
||||
|
||||
Everyone uses the same pinned environment: the BetterXen commit, the CrossOver version, the macOS version and the `bx-cli` profile. A result is reported together with that environment.
|
||||
|
||||
## Diagnostics
|
||||
|
||||
All switches are off unless set, and none changes behaviour beyond what its row says. Only switches that exist on `main` are listed. Switches from open PRs are added here when those PRs merge.
|
||||
|
||||
| Switch | Where | Effect |
|
||||
| --- | --- | --- |
|
||||
| `BX_TRACE_D3D=1` | `d3d12_xs` | Logs every D3D12 call |
|
||||
| `BX_NULL_RENDER=1` | `d3d12_xs` | Pipelines that cannot be built become null pipelines; their draws and dispatches are skipped and logged |
|
||||
| `BX_PRESENT_DUMP=<folder>` | `d3d12_xs` | Writes presented frames as BMP files, every Nth present (`BX_PRESENT_DUMP_EVERY`, default 64) |
|
||||
| `BX_XMEM_TRACE=1` | `xmem` | Logs physical page allocations, frees and mappings |
|
||||
|
||||
Their output can contain title addresses and file names, so it goes only into the private evidence store.
|
||||
|
||||
## Evidence
|
||||
|
||||
Logs, addresses, decompiled output, screenshots and authorization notes live in the team's private evidence store, outside this repository. PRs and reviews refer to them by note ID only.
|
||||
|
||||
## What never enters the repository
|
||||
|
||||
CONTRIBUTING.md (clean-room and provenance) and docs/legal.md set the rules. For target-build work in particular, never commit or post:
|
||||
|
||||
- SDK header or documentation text;
|
||||
- the title's name or file names;
|
||||
- identifiers derived from the title or build: its hashes, addresses or raw logs;
|
||||
- decompiled code or disassembly;
|
||||
- screenshots of the title;
|
||||
- personal paths.
|
||||
|
||||
Hashes that record the provenance of third-party code (`THIRD_PARTY_NOTICES.md`, `docs/research/upstream-registry.md`) are not affected. Contracts are recorded as derived facts only.
|
||||
@@ -13,6 +13,8 @@ path = "src/main.rs"
|
||||
bx-probe = { path = "../bx-probe" }
|
||||
bx-telemetry = { path = "../bx-telemetry" }
|
||||
dxbc-accc = { path = "../../../shader-transpiler/crates/dxbc-accc" }
|
||||
# POSIX signals and process groups for `run` supervision.
|
||||
libc = "=0.2.191"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,548 @@
|
||||
//! Xbox title drive letters, linked in the prefix's `dosdevices` before launch.
|
||||
//!
|
||||
//! The project-authorized target title we traced reads its package from `G:` and writes
|
||||
//! temporary files such as crash logs to `T:`. That is an observation of one title at startup;
|
||||
//! that `G:` is the package root and `T:` temporary storage for Xbox titles in general is an
|
||||
//! inference. A Wine prefix has neither drive, so that title's first `G:\...` open fails with
|
||||
//! `STATUS_OBJECT_PATH_NOT_FOUND`. `bx-cli run` links `g:` to the executable's directory and
|
||||
//! `t:` to `drive_c/bx_temp`.
|
||||
//!
|
||||
//! As with system32 staging (#474), a drive letter the prefix already uses is not ours. A
|
||||
//! `.bx-drives` manifest in `dosdevices` records each link this tool made, and only a link that
|
||||
//! is listed and still points where it was pointed is replaced. Any other mapping to a
|
||||
//! different target is reported and left unchanged.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::ffi::{OsStrExt, OsStringExt};
|
||||
use std::os::unix::fs::{OpenOptionsExt, symlink};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const MANIFEST: &str = ".bx-drives";
|
||||
const LOCK_FILE: &str = ".bx-drive-mapping.lock";
|
||||
|
||||
/// The prefix-relative target of `t:`, in the form Wine itself uses for `c:`.
|
||||
pub const TEMP_TARGET: &str = "../drive_c/bx_temp";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DriveMappingLock {
|
||||
_file: fs::File,
|
||||
}
|
||||
|
||||
/// Holds the prefix's drive mappings stable until the returned lock is dropped.
|
||||
pub fn lock_drive_mappings(prefix: &Path) -> Result<DriveMappingLock, String> {
|
||||
fs::create_dir_all(prefix).map_err(|e| {
|
||||
format!(
|
||||
"cannot prepare prefix {} for drive lock: {e}",
|
||||
prefix.display()
|
||||
)
|
||||
})?;
|
||||
let prefix = fs::canonicalize(prefix).map_err(|e| {
|
||||
format!(
|
||||
"cannot resolve prefix {} for drive lock: {e}",
|
||||
prefix.display()
|
||||
)
|
||||
})?;
|
||||
let path = prefix.join(LOCK_FILE);
|
||||
let file = fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.custom_flags(libc::O_NOFOLLOW)
|
||||
.open(&path)
|
||||
.map_err(|e| format!("cannot open drive lock {}: {e}", path.display()))?;
|
||||
|
||||
loop {
|
||||
// The open file descriptor stays alive in DriveMappingLock for the full launch.
|
||||
let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
|
||||
if result == 0 {
|
||||
return Ok(DriveMappingLock { _file: file });
|
||||
}
|
||||
let error = io::Error::last_os_error();
|
||||
if error.kind() == io::ErrorKind::Interrupted {
|
||||
continue;
|
||||
}
|
||||
if error.kind() == io::ErrorKind::WouldBlock {
|
||||
return Err(format!(
|
||||
"another bx-cli run is active for prefix {}; refusing to launch with shared Xbox drive mappings",
|
||||
prefix.display()
|
||||
));
|
||||
}
|
||||
return Err(format!("cannot lock {}: {error}", path.display()));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Mapping {
|
||||
Created(char, PathBuf),
|
||||
/// A link this tool made earlier, pointed at a new target.
|
||||
Retargeted(char, PathBuf),
|
||||
Unchanged(char, PathBuf),
|
||||
/// A mapping this tool did not make, to a different target; left as it is.
|
||||
Foreign {
|
||||
letter: char,
|
||||
existing: String,
|
||||
wanted: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
impl Mapping {
|
||||
pub fn describe(&self) -> String {
|
||||
match self {
|
||||
Mapping::Created(l, t) => {
|
||||
format!("mapped {}: to {}", l.to_ascii_uppercase(), t.display())
|
||||
}
|
||||
Mapping::Retargeted(l, t) => {
|
||||
format!(
|
||||
"remapped own {}: to {}",
|
||||
l.to_ascii_uppercase(),
|
||||
t.display()
|
||||
)
|
||||
}
|
||||
Mapping::Unchanged(l, t) => {
|
||||
format!(
|
||||
"{}: already maps to {}",
|
||||
l.to_ascii_uppercase(),
|
||||
t.display()
|
||||
)
|
||||
}
|
||||
Mapping::Foreign {
|
||||
letter,
|
||||
existing,
|
||||
wanted,
|
||||
} => format!(
|
||||
"warning: {}: already maps to {existing}, not {}; left unchanged, so the guest \
|
||||
may not find its files there",
|
||||
letter.to_ascii_uppercase(),
|
||||
wanted.display()
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_manifest(dosdevices: &Path) -> Result<BTreeMap<char, PathBuf>, String> {
|
||||
let path = dosdevices.join(MANIFEST);
|
||||
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().filter(|l| !l.is_empty()) {
|
||||
let mut chars = line.chars();
|
||||
match (chars.next(), chars.next()) {
|
||||
(Some(letter), Some('\t')) if letter.is_ascii_lowercase() => {
|
||||
let encoded = chars.as_str();
|
||||
let target = match encoded.strip_prefix('@') {
|
||||
Some(hex) => decode_path(hex)
|
||||
.ok_or_else(|| format!("malformed path in {}: {line:?}", path.display()))?,
|
||||
None => PathBuf::from(encoded),
|
||||
};
|
||||
owned.insert(letter, target);
|
||||
}
|
||||
_ => return Err(format!("malformed line in {}: {line:?}", path.display())),
|
||||
}
|
||||
}
|
||||
Ok(owned)
|
||||
}
|
||||
|
||||
fn write_manifest(dosdevices: &Path, owned: &BTreeMap<char, PathBuf>) -> Result<(), String> {
|
||||
let path = dosdevices.join(MANIFEST);
|
||||
let mut text = String::new();
|
||||
for (letter, target) in owned {
|
||||
text.push_str(&format!("{letter}\t@{}\n", encode_path(target)));
|
||||
}
|
||||
// Written to a temporary file and renamed over the manifest, like `relink`, so an
|
||||
// interrupted write can never leave a truncated manifest that later runs refuse to parse.
|
||||
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&tmp)
|
||||
.map_err(|e| format!("cannot create {}: {e}", tmp.display()))?;
|
||||
let written = file.write_all(text.as_bytes()).and_then(|()| {
|
||||
drop(file);
|
||||
fs::rename(&tmp, &path)
|
||||
});
|
||||
if written.is_err() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
written.map_err(|e| format!("cannot write {}: {e}", path.display()))
|
||||
}
|
||||
|
||||
fn encode_path(path: &Path) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let bytes = path.as_os_str().as_bytes();
|
||||
let mut encoded = String::with_capacity(bytes.len() * 2);
|
||||
for &byte in bytes {
|
||||
encoded.push(char::from(HEX[usize::from(byte >> 4)]));
|
||||
encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
fn decode_path(hex: &str) -> Option<PathBuf> {
|
||||
fn nibble(byte: u8) -> Option<u8> {
|
||||
match byte {
|
||||
b'0'..=b'9' => Some(byte - b'0'),
|
||||
b'a'..=b'f' => Some(byte - b'a' + 10),
|
||||
b'A'..=b'F' => Some(byte - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = hex.as_bytes();
|
||||
if bytes.len() % 2 != 0 {
|
||||
return None;
|
||||
}
|
||||
let mut decoded = Vec::with_capacity(bytes.len() / 2);
|
||||
for pair in bytes.chunks_exact(2) {
|
||||
decoded.push((nibble(pair[0])? << 4) | nibble(pair[1])?);
|
||||
}
|
||||
Some(PathBuf::from(std::ffi::OsString::from_vec(decoded)))
|
||||
}
|
||||
|
||||
/// Points `link` at `target`, replacing what is there through a rename so the link never
|
||||
/// disappears in between.
|
||||
fn relink(dosdevices: &Path, link: &Path, target: &Path) -> io::Result<()> {
|
||||
let tmp = dosdevices.join(format!(".bx-drive-tmp.{}", std::process::id()));
|
||||
let _ = fs::remove_file(&tmp);
|
||||
symlink(target, &tmp)?;
|
||||
let result = fs::rename(&tmp, link);
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Links `g:` to `package_dir` and `t:` to [`TEMP_TARGET`] in `prefix`'s `dosdevices`.
|
||||
pub fn map_xbox_drives(prefix: &Path, package_dir: &Path) -> Result<Vec<Mapping>, String> {
|
||||
let dosdevices = prefix.join("dosdevices");
|
||||
if !dosdevices.is_dir() {
|
||||
return Err(format!(
|
||||
"{} does not exist (start the prefix once so Wine creates it)",
|
||||
dosdevices.display()
|
||||
));
|
||||
}
|
||||
let temp_dir = prefix.join("drive_c/bx_temp");
|
||||
fs::create_dir_all(&temp_dir)
|
||||
.map_err(|e| format!("cannot create {}: {e}", temp_dir.display()))?;
|
||||
|
||||
let mut owned = read_manifest(&dosdevices)?;
|
||||
let mut mappings = Vec::new();
|
||||
for (letter, target) in [
|
||||
('g', package_dir.to_path_buf()),
|
||||
('t', PathBuf::from(TEMP_TARGET)),
|
||||
] {
|
||||
let link = dosdevices.join(format!("{letter}:"));
|
||||
let current = match fs::symlink_metadata(&link) {
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(format!("cannot inspect {}: {e}", link.display())),
|
||||
Ok(meta) if meta.file_type().is_symlink() => Some(
|
||||
fs::read_link(&link).map_err(|e| format!("cannot read {}: {e}", link.display()))?,
|
||||
),
|
||||
Ok(_) => {
|
||||
mappings.push(Mapping::Foreign {
|
||||
letter,
|
||||
existing: format!("a non-link entry {}", link.display()),
|
||||
wanted: target,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mapping = match current {
|
||||
None => {
|
||||
owned.insert(letter, target.clone());
|
||||
write_manifest(&dosdevices, &owned)?;
|
||||
relink(&dosdevices, &link, &target)
|
||||
.map_err(|e| format!("cannot create {}: {e}", link.display()))?;
|
||||
Mapping::Created(letter, target.clone())
|
||||
}
|
||||
Some(current) if current == target => Mapping::Unchanged(letter, target.clone()),
|
||||
Some(current) if owned.get(&letter) == Some(¤t) => {
|
||||
owned.insert(letter, target.clone());
|
||||
write_manifest(&dosdevices, &owned)?;
|
||||
if let Err(error) = relink(&dosdevices, &link, &target) {
|
||||
owned.insert(letter, current);
|
||||
let restore = write_manifest(&dosdevices, &owned);
|
||||
let detail = restore
|
||||
.err()
|
||||
.map(|e| format!("; also could not restore the drive manifest: {e}"))
|
||||
.unwrap_or_default();
|
||||
return Err(format!(
|
||||
"cannot replace {}: {error}{detail}",
|
||||
link.display()
|
||||
));
|
||||
}
|
||||
Mapping::Retargeted(letter, target.clone())
|
||||
}
|
||||
Some(current) => {
|
||||
mappings.push(Mapping::Foreign {
|
||||
letter,
|
||||
existing: current.display().to_string(),
|
||||
wanted: target,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
mappings.push(mapping);
|
||||
}
|
||||
Ok(mappings)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let p = std::env::temp_dir().join(format!(
|
||||
"bx-drives-{tag}-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&p);
|
||||
fs::create_dir_all(p.join("prefix/dosdevices")).unwrap();
|
||||
fs::create_dir_all(p.join("game")).unwrap();
|
||||
TempDir(p)
|
||||
}
|
||||
fn prefix(&self) -> PathBuf {
|
||||
self.0.join("prefix")
|
||||
}
|
||||
fn game(&self) -> PathBuf {
|
||||
self.0.join("game")
|
||||
}
|
||||
fn link(&self, letter: char) -> PathBuf {
|
||||
self.0.join(format!("prefix/dosdevices/{letter}:"))
|
||||
}
|
||||
}
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_drives_are_created_and_resolve() {
|
||||
let t = TempDir::new("create");
|
||||
fs::write(t.game().join("package.bin"), b"pkg").unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(
|
||||
mappings[..],
|
||||
[Mapping::Created('g', _), Mapping::Created('t', _)]
|
||||
));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
|
||||
assert_eq!(
|
||||
fs::read_link(t.link('t')).unwrap(),
|
||||
PathBuf::from(TEMP_TARGET)
|
||||
);
|
||||
// Both links resolve the way Wine resolves them, from inside dosdevices.
|
||||
assert_eq!(fs::read(t.link('g').join("package.bin")).unwrap(), b"pkg");
|
||||
assert!(t.link('t').is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_run_changes_nothing() {
|
||||
let t = TempDir::new("rerun");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(
|
||||
mappings[..],
|
||||
[Mapping::Unchanged('g', _), Mapping::Unchanged('t', _)]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_own_link_follows_a_new_package_directory() {
|
||||
let t = TempDir::new("retarget");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(mappings[0], Mapping::Retargeted('g', _)));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), other);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_foreign_mapping_is_reported_and_kept() {
|
||||
let t = TempDir::new("foreign");
|
||||
let elsewhere = t.0.join("elsewhere");
|
||||
symlink(&elsewhere, t.link('g')).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
|
||||
assert!(mappings[0].describe().starts_with("warning: G:"));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
|
||||
// A link this tool did not record is never treated as its own on a later run.
|
||||
let again = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(&again[0], Mapping::Foreign { letter: 'g', .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_own_link_changed_by_someone_else_becomes_foreign() {
|
||||
let t = TempDir::new("changed");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
fs::remove_file(t.link('g')).unwrap();
|
||||
let elsewhere = t.0.join("elsewhere");
|
||||
symlink(&elsewhere, t.link('g')).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_link_entry_is_never_touched() {
|
||||
let t = TempDir::new("nonlink");
|
||||
fs::create_dir_all(t.link('t')).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(&mappings[1], Mapping::Foreign { letter: 't', .. }));
|
||||
assert!(t.link('t').is_dir() && !fs::symlink_metadata(t.link('t')).unwrap().is_symlink());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_without_dosdevices_is_an_error() {
|
||||
let t = TempDir::new("nodos");
|
||||
fs::remove_dir_all(t.prefix().join("dosdevices")).unwrap();
|
||||
let e = map_xbox_drives(&t.prefix(), &t.game()).unwrap_err();
|
||||
assert!(e.contains("dosdevices"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_manifest_is_an_error_not_an_ownership_claim() {
|
||||
let t = TempDir::new("badmanifest");
|
||||
fs::write(t.prefix().join("dosdevices").join(MANIFEST), "g /x\n").unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_manifest_write_leaves_no_unrecorded_link() {
|
||||
let t = TempDir::new("orphan");
|
||||
// A directory where the manifest's temporary file goes makes the write fail.
|
||||
let tmp = t
|
||||
.prefix()
|
||||
.join("dosdevices")
|
||||
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
fs::create_dir(&tmp).unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
|
||||
assert!(
|
||||
fs::symlink_metadata(t.link('g')).is_err(),
|
||||
"g: must not be created before ownership is recorded"
|
||||
);
|
||||
|
||||
fs::remove_dir(&tmp).unwrap();
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interrupted_manifest_write_keeps_the_previous_manifest() {
|
||||
let t = TempDir::new("atomic");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let manifest = t.prefix().join("dosdevices").join(MANIFEST);
|
||||
let before = fs::read(&manifest).unwrap();
|
||||
// Fail the next write after the new contents would have been produced: the old
|
||||
// manifest must survive whole, never truncated or half written.
|
||||
let tmp = t
|
||||
.prefix()
|
||||
.join("dosdevices")
|
||||
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
fs::create_dir(&tmp).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
|
||||
assert_eq!(
|
||||
fs::read(&manifest).unwrap(),
|
||||
before,
|
||||
"previous manifest kept intact"
|
||||
);
|
||||
fs::remove_dir(&tmp).unwrap();
|
||||
// The intact manifest still proves ownership, so the retry re-points g:.
|
||||
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
|
||||
assert!(
|
||||
fs::read_dir(t.prefix().join("dosdevices"))
|
||||
.unwrap()
|
||||
.all(|e| !e.unwrap().file_name().to_string_lossy().contains(".tmp."))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_temp_does_not_follow_an_existing_symlink() {
|
||||
let t = TempDir::new("manifest-symlink");
|
||||
let dosdevices = t.prefix().join("dosdevices");
|
||||
let target = t.0.join("outside-manifest");
|
||||
fs::write(&target, b"unchanged").unwrap();
|
||||
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
symlink(&target, &tmp).unwrap();
|
||||
|
||||
assert!(write_manifest(&dosdevices, &BTreeMap::new()).is_err());
|
||||
assert_eq!(fs::read(&target).unwrap(), b"unchanged");
|
||||
assert_eq!(fs::read_link(&tmp).unwrap(), target);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_retarget_restores_the_previous_manifest_and_link() {
|
||||
let t = TempDir::new("retarget-failure");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
|
||||
let temp_link = t
|
||||
.prefix()
|
||||
.join("dosdevices")
|
||||
.join(format!(".bx-drive-tmp.{}", std::process::id()));
|
||||
fs::create_dir(&temp_link).unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
|
||||
assert_eq!(
|
||||
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
|
||||
t.game()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_lock_rejects_another_launcher_until_released() {
|
||||
let t = TempDir::new("lock");
|
||||
let lock = lock_drive_mappings(&t.prefix()).unwrap();
|
||||
let error = lock_drive_mappings(&t.prefix()).unwrap_err();
|
||||
assert!(error.contains("another bx-cli run"), "{error}");
|
||||
|
||||
drop(lock);
|
||||
assert!(lock_drive_mappings(&t.prefix()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_utf8_target_round_trips_through_the_manifest() {
|
||||
let t = TempDir::new("non-utf8");
|
||||
let mut game_bytes = t.0.as_os_str().as_bytes().to_vec();
|
||||
game_bytes.extend_from_slice(b"/game-\xff");
|
||||
let game = PathBuf::from(std::ffi::OsString::from_vec(game_bytes));
|
||||
let owned = BTreeMap::from([('g', game.clone())]);
|
||||
write_manifest(&t.prefix().join("dosdevices"), &owned).unwrap();
|
||||
assert_eq!(
|
||||
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
|
||||
game
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legacy_plain_text_target_still_reads() {
|
||||
let t = TempDir::new("legacy-manifest");
|
||||
let legacy_target = t.0.join("old-game");
|
||||
fs::write(
|
||||
t.prefix().join("dosdevices").join(MANIFEST),
|
||||
format!("g\t{}\n", legacy_target.display()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
|
||||
legacy_target
|
||||
);
|
||||
}
|
||||
}
|
||||
+1689
-87
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,492 @@
|
||||
//! Supervision for `bx-cli run` (#408): the launcher gets its own process group, and a timeout
|
||||
//! or signal stops that group and then the environment's `wineserver`.
|
||||
//!
|
||||
//! The `wineserver` is stopped only after a timeout or signal, never after a normal exit,
|
||||
//! because it ends every program in that bottle or prefix, not only this run's.
|
||||
|
||||
use std::io::IsTerminal;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::path::Path;
|
||||
use std::process::{Child, Command, ExitStatus, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const POLL: Duration = Duration::from_millis(50);
|
||||
/// How long the launcher group has to exit after SIGTERM before SIGKILL.
|
||||
const GRACE: Duration = Duration::from_secs(5);
|
||||
const SERVER_WAIT: Duration = Duration::from_secs(15);
|
||||
|
||||
/// Signals that stop the run: the guest group is terminated and the environment cleaned up.
|
||||
/// SIGQUIT (Ctrl-\) is included so it cannot kill `bx-cli` and leave the guest running (#461).
|
||||
const STOP_SIGNALS: [libc::c_int; 4] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGQUIT];
|
||||
|
||||
static SIGNAL: AtomicI32 = AtomicI32::new(0);
|
||||
static SUSPEND: AtomicBool = AtomicBool::new(false);
|
||||
/// Total time this process has spent suspended inside [`supervise`], in nanoseconds.
|
||||
static SUSPENDED_NANOS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
extern "C" fn note_signal(signal: libc::c_int) {
|
||||
SIGNAL.store(signal, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
extern "C" fn note_suspend(_signal: libc::c_int) {
|
||||
SUSPEND.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Installs `handler` for `signal` unless the disposition this process inherited is `SIG_IGN`.
|
||||
/// Returns whether the handler was installed.
|
||||
///
|
||||
/// A signal the caller chose to ignore (`nohup`, or a `&` job of a non-interactive shell) stays
|
||||
/// ignored, so it cannot stop the run or the bottle (#461).
|
||||
fn install_unless_ignored(signal: libc::c_int, handler: extern "C" fn(libc::c_int)) -> bool {
|
||||
// SAFETY: `current` is a valid, writable sigaction; a null new action only queries. The
|
||||
// handlers passed here only store to an atomic, which is async-signal-safe.
|
||||
unsafe {
|
||||
let mut current: libc::sigaction = std::mem::zeroed();
|
||||
if libc::sigaction(signal, std::ptr::null(), &mut current) == 0
|
||||
&& current.sa_sigaction == libc::SIG_IGN
|
||||
{
|
||||
return false;
|
||||
}
|
||||
libc::signal(signal, handler as libc::sighandler_t) != libc::SIG_ERR
|
||||
}
|
||||
}
|
||||
|
||||
/// Records SIGINT, SIGTERM, SIGHUP and SIGQUIT instead of dying, so the run can be cleaned up,
|
||||
/// and records SIGTSTP (Ctrl-Z) so the guest group can be suspended together with `bx-cli`.
|
||||
/// Signals that were inherited as ignored are left ignored.
|
||||
///
|
||||
/// SIGTSTP is only acted on inside [`supervise`]. A Ctrl-Z typed while nothing is being
|
||||
/// supervised (for example while shims are copied) has no visible effect until the next
|
||||
/// supervised phase starts, which is then suspended at once.
|
||||
pub fn install_signal_handlers() {
|
||||
for signal in STOP_SIGNALS {
|
||||
install_unless_ignored(signal, note_signal);
|
||||
}
|
||||
install_unless_ignored(libc::SIGTSTP, note_suspend);
|
||||
}
|
||||
|
||||
pub fn received_signal() -> i32 {
|
||||
SIGNAL.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Total time spent suspended (Ctrl-Z until continued) across every [`supervise`] call so far.
|
||||
///
|
||||
/// A caller that budgets one `--timeout` over several supervised phases subtracts this from its
|
||||
/// own wall-clock measurement, so a pause during an earlier phase is not charged to a later one.
|
||||
pub fn suspended_time() -> Duration {
|
||||
Duration::from_nanos(SUSPENDED_NANOS.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
/// True once per SIGTSTP received since the last call.
|
||||
fn take_suspend_request() -> bool {
|
||||
SUSPEND.swap(false, Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Stops this process the way the terminal's Ctrl-Z would; returns when it is continued.
|
||||
fn suspend_self(_guest: libc::pid_t) {
|
||||
// SAFETY: raise takes no pointers. SIGSTOP cannot be caught, so this stops the process.
|
||||
unsafe {
|
||||
libc::raise(libc::SIGSTOP);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum Stop {
|
||||
TimedOut,
|
||||
Signalled(i32),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Outcome {
|
||||
Exited(ExitStatus),
|
||||
Stopped(Stop),
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
/// The guest's own numeric exit code (so a conformance fixture's documented exit-77 skip
|
||||
/// stays distinguishable from a failure, #565), 124 for a timeout (as `timeout(1)`),
|
||||
/// 128 + N for a signal.
|
||||
pub fn exit_code(&self) -> u8 {
|
||||
match self {
|
||||
// Unix guest codes are already 0-255; a signalled guest has no code, which is a
|
||||
// failure. `code.max(1)` at the call sites still turns a failed cleanup into 1.
|
||||
Outcome::Exited(status) => status.code().map_or(1, |code| code.clamp(0, 255) as u8),
|
||||
Outcome::Stopped(Stop::TimedOut) => 124,
|
||||
Outcome::Stopped(Stop::Signalled(signal)) => 128u8.saturating_add(*signal as u8),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn signal_group(child: &Child, signal: libc::c_int) {
|
||||
// SAFETY: kill takes no pointers. The child leads its own group and has not been reaped,
|
||||
// so the group id cannot have been reused.
|
||||
unsafe {
|
||||
libc::kill(-(child.id() as libc::pid_t), signal);
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_until(child: &mut Child, deadline: Instant) -> std::io::Result<Option<ExitStatus>> {
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(Some(status));
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Ok(None);
|
||||
}
|
||||
std::thread::sleep(POLL);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `command` in a new process group until it exits, `timeout` passes, or `signal`
|
||||
/// returns non-zero. On a stop the whole group is terminated before this returns.
|
||||
///
|
||||
/// The guest is not in the terminal's foreground group, so Ctrl-Z reaches only `bx-cli`. It is
|
||||
/// passed on: the guest group gets SIGTSTP, `bx-cli` stops itself, and when `bx-cli` is continued
|
||||
/// the guest group gets SIGCONT. Time spent suspended does not count against `timeout`.
|
||||
pub fn supervise(
|
||||
command: Command,
|
||||
timeout: Option<Duration>,
|
||||
signal: impl Fn() -> i32,
|
||||
) -> std::io::Result<Outcome> {
|
||||
supervise_with(command, timeout, signal, take_suspend_request, suspend_self)
|
||||
}
|
||||
|
||||
/// [`supervise`] with the suspend request and the self-stop injected, so tests can exercise the
|
||||
/// job-control path without stopping the test process. `suspend` is called with the guest
|
||||
/// group's id after that group was sent SIGTSTP and returns when the launcher may continue.
|
||||
fn supervise_with(
|
||||
mut command: Command,
|
||||
timeout: Option<Duration>,
|
||||
signal: impl Fn() -> i32,
|
||||
suspend_requested: impl Fn() -> bool,
|
||||
mut suspend: impl FnMut(libc::pid_t),
|
||||
) -> std::io::Result<Outcome> {
|
||||
// A background process group is stopped by SIGTTIN if it reads the terminal, so a terminal
|
||||
// is replaced by end-of-file. Piped and redirected input is passed through.
|
||||
if std::io::stdin().is_terminal() {
|
||||
command.stdin(Stdio::null());
|
||||
}
|
||||
let mut child = command.process_group(0).spawn()?;
|
||||
let started = Instant::now();
|
||||
let mut suspended = Duration::ZERO;
|
||||
let stop = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(Outcome::Exited(status));
|
||||
}
|
||||
let received = signal();
|
||||
if received != 0 {
|
||||
break Stop::Signalled(received);
|
||||
}
|
||||
if suspend_requested() {
|
||||
let paused = Instant::now();
|
||||
signal_group(&child, libc::SIGTSTP);
|
||||
suspend(child.id() as libc::pid_t);
|
||||
signal_group(&child, libc::SIGCONT);
|
||||
let pause = paused.elapsed();
|
||||
suspended += pause;
|
||||
SUSPENDED_NANOS.fetch_add(
|
||||
u64::try_from(pause.as_nanos()).unwrap_or(u64::MAX),
|
||||
Ordering::SeqCst,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if timeout.is_some_and(|limit| started.elapsed().saturating_sub(suspended) >= limit) {
|
||||
break Stop::TimedOut;
|
||||
}
|
||||
std::thread::sleep(POLL);
|
||||
};
|
||||
signal_group(&child, libc::SIGTERM);
|
||||
// Wait without reaping first, so SIGKILL still reaches members that outlive the leader.
|
||||
std::thread::sleep(POLL);
|
||||
let deadline = Instant::now() + GRACE;
|
||||
while Instant::now() < deadline && group_leader_running(&child) {
|
||||
std::thread::sleep(POLL);
|
||||
}
|
||||
signal_group(&child, libc::SIGKILL);
|
||||
wait_until(&mut child, Instant::now() + GRACE)?;
|
||||
Ok(Outcome::Stopped(stop))
|
||||
}
|
||||
|
||||
/// True while the leader has not exited; does not reap it.
|
||||
fn group_leader_running(child: &Child) -> bool {
|
||||
// SAFETY: `info` is a valid, writable siginfo_t and WNOWAIT leaves the child unreaped.
|
||||
unsafe {
|
||||
let mut info: libc::siginfo_t = std::mem::zeroed();
|
||||
libc::waitid(
|
||||
libc::P_PID,
|
||||
child.id() as libc::id_t,
|
||||
&mut info,
|
||||
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
|
||||
) == 0
|
||||
&& info.si_pid() == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// `wineserver -k` then `-w` for the environment at `prefix`.
|
||||
///
|
||||
/// `-k` exits 1 when no server is running (observed on CrossOver 26.3), so 1 is accepted
|
||||
/// there; `-w` must still succeed, which a surviving server prevents.
|
||||
///
|
||||
/// Each `wineserver` runs in its own process group with no terminal input, so a second Ctrl-C
|
||||
/// typed while cleanup is running reaches only `bx-cli` (which records it) and cannot kill the
|
||||
/// cleanup itself (#461).
|
||||
pub fn stop_server(
|
||||
wineserver: &Path,
|
||||
prefix: &Path,
|
||||
environment: &[(String, String)],
|
||||
) -> Result<(), String> {
|
||||
for (flag, idle_code) in [("-k", Some(1)), ("-w", None)] {
|
||||
let mut child = Command::new(wineserver)
|
||||
.arg(flag)
|
||||
.env_clear()
|
||||
.envs(environment.iter().map(|(k, v)| (k, v)))
|
||||
.env("WINEPREFIX", prefix)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.process_group(0)
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start wineserver {flag}: {e}"))?;
|
||||
match wait_until(&mut child, Instant::now() + SERVER_WAIT) {
|
||||
Ok(Some(status)) if status.success() => {}
|
||||
Ok(Some(status)) if idle_code.is_some() && status.code() == idle_code => {}
|
||||
other => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(format!("wineserver {flag} did not succeed: {other:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
fn shell(script: &str) -> Command {
|
||||
let mut command = Command::new("/bin/sh");
|
||||
command.args(["-c", script]);
|
||||
command
|
||||
}
|
||||
|
||||
fn scratch(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("bx-cli-{name}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_exit_timeout_and_signal() {
|
||||
let ok = supervise(shell("exit 0"), None, || 0).unwrap();
|
||||
assert_eq!(ok.exit_code(), 0);
|
||||
let failed = supervise(shell("exit 7"), Some(Duration::from_secs(10)), || 0).unwrap();
|
||||
assert_eq!(failed.exit_code(), 7);
|
||||
// A conformance fixture's documented skip must stay distinguishable from a failure
|
||||
// through `bx-cli run` (#565); the old `!status.success()` collapsed it to 1.
|
||||
let skipped = supervise(shell("exit 77"), Some(Duration::from_secs(10)), || 0).unwrap();
|
||||
assert_eq!(skipped.exit_code(), 77);
|
||||
let slow = supervise(shell("sleep 30"), Some(Duration::from_millis(200)), || 0).unwrap();
|
||||
assert!(matches!(slow, Outcome::Stopped(Stop::TimedOut)));
|
||||
assert_eq!(slow.exit_code(), 124);
|
||||
let interrupted = supervise(shell("sleep 30"), None, || libc::SIGTERM).unwrap();
|
||||
assert_eq!(interrupted.exit_code(), 128 + libc::SIGTERM as u8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timeout_stops_children_that_ignore_sigterm() {
|
||||
let dir = scratch("group");
|
||||
let pid_file = dir.join("child.pid");
|
||||
let script = format!(
|
||||
"(trap '' TERM; exec sleep 30) & echo $! > '{}'; wait",
|
||||
pid_file.display()
|
||||
);
|
||||
supervise(shell(&script), Some(Duration::from_millis(500)), || 0).unwrap();
|
||||
let pid: libc::pid_t = std::fs::read_to_string(&pid_file)
|
||||
.unwrap()
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap();
|
||||
let gone = (0..100).any(|_| {
|
||||
std::thread::sleep(POLL);
|
||||
// SAFETY: signal 0 only checks whether the process exists.
|
||||
unsafe { libc::kill(pid, 0) != 0 }
|
||||
});
|
||||
assert!(gone, "grandchild {pid} survived the timeout");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Signal dispositions and the recorded signal are process-wide: tests that touch them run
|
||||
/// one at a time and use signals no other test raises.
|
||||
static SIGNAL_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn set_disposition(signal: libc::c_int, action: libc::sighandler_t) {
|
||||
// SAFETY: SIG_DFL and SIG_IGN are valid dispositions for these signals.
|
||||
unsafe {
|
||||
libc::signal(signal, action);
|
||||
}
|
||||
}
|
||||
|
||||
fn disposition(signal: libc::c_int) -> libc::sighandler_t {
|
||||
// SAFETY: a null new action only queries; `current` is valid and writable.
|
||||
unsafe {
|
||||
let mut current: libc::sigaction = std::mem::zeroed();
|
||||
assert_eq!(libc::sigaction(signal, std::ptr::null(), &mut current), 0);
|
||||
current.sa_sigaction
|
||||
}
|
||||
}
|
||||
|
||||
fn raise(signal: libc::c_int) {
|
||||
// SAFETY: raise takes no pointers.
|
||||
unsafe {
|
||||
libc::raise(signal);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_ignored_signal_stays_ignored() {
|
||||
let _guard = SIGNAL_TESTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// As under nohup: the signal arrives already ignored.
|
||||
set_disposition(libc::SIGUSR2, libc::SIG_IGN);
|
||||
SIGNAL.store(0, Ordering::SeqCst);
|
||||
assert!(!install_unless_ignored(libc::SIGUSR2, note_signal));
|
||||
assert_eq!(disposition(libc::SIGUSR2), libc::SIG_IGN);
|
||||
raise(libc::SIGUSR2);
|
||||
assert_eq!(
|
||||
received_signal(),
|
||||
0,
|
||||
"an ignored signal must not stop the run"
|
||||
);
|
||||
|
||||
// Control: the same signal with the default disposition is recorded.
|
||||
set_disposition(libc::SIGUSR2, libc::SIG_DFL);
|
||||
assert!(install_unless_ignored(libc::SIGUSR2, note_signal));
|
||||
raise(libc::SIGUSR2);
|
||||
assert_eq!(received_signal(), libc::SIGUSR2);
|
||||
set_disposition(libc::SIGUSR2, libc::SIG_DFL);
|
||||
SIGNAL.store(0, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sigquit_is_recorded_and_stops_the_guest_group() {
|
||||
let _guard = SIGNAL_TESTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
assert!(STOP_SIGNALS.contains(&libc::SIGQUIT));
|
||||
let before = disposition(libc::SIGQUIT);
|
||||
set_disposition(libc::SIGQUIT, libc::SIG_DFL);
|
||||
SIGNAL.store(0, Ordering::SeqCst);
|
||||
assert!(install_unless_ignored(libc::SIGQUIT, note_signal));
|
||||
// Without the handler this would kill the test process, as it killed bx-cli.
|
||||
raise(libc::SIGQUIT);
|
||||
assert_eq!(received_signal(), libc::SIGQUIT);
|
||||
set_disposition(libc::SIGQUIT, before);
|
||||
SIGNAL.store(0, Ordering::SeqCst);
|
||||
|
||||
let stopped = supervise(shell("sleep 30"), None, || libc::SIGQUIT).unwrap();
|
||||
assert!(matches!(
|
||||
stopped,
|
||||
Outcome::Stopped(Stop::Signalled(libc::SIGQUIT))
|
||||
));
|
||||
assert_eq!(stopped.exit_code(), 128 + libc::SIGQUIT as u8);
|
||||
}
|
||||
|
||||
/// True once `pid` is reported stopped; leaves the status in place.
|
||||
fn is_stopped(pid: libc::pid_t) -> bool {
|
||||
(0..100).any(|_| {
|
||||
// SAFETY: `info` is valid and writable; WNOWAIT leaves the child's state in place.
|
||||
let stopped = unsafe {
|
||||
let mut info: libc::siginfo_t = std::mem::zeroed();
|
||||
libc::waitid(
|
||||
libc::P_PID,
|
||||
pid as libc::id_t,
|
||||
&mut info,
|
||||
libc::WSTOPPED | libc::WNOHANG | libc::WNOWAIT,
|
||||
) == 0
|
||||
&& info.si_pid() == pid
|
||||
};
|
||||
if !stopped {
|
||||
std::thread::sleep(POLL);
|
||||
}
|
||||
stopped
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_suspend_request_stops_and_resumes_the_guest_without_using_up_the_timeout() {
|
||||
let requested = std::cell::Cell::new(false);
|
||||
let guest_was_stopped = std::cell::Cell::new(false);
|
||||
let suspended_before = suspended_time();
|
||||
let outcome = supervise_with(
|
||||
shell("sleep 0.4; exit 0"),
|
||||
// Shorter than the suspension below: only running time may count.
|
||||
Some(Duration::from_millis(1500)),
|
||||
|| 0,
|
||||
|| !requested.replace(true),
|
||||
|guest| {
|
||||
guest_was_stopped.set(is_stopped(guest));
|
||||
std::thread::sleep(Duration::from_millis(2000));
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(guest_was_stopped.get(), "the guest group was not stopped");
|
||||
// The pause is also reported to callers that budget a timeout across several phases.
|
||||
let reported = suspended_time() - suspended_before;
|
||||
assert!(reported >= Duration::from_millis(2000), "{reported:?}");
|
||||
match outcome {
|
||||
Outcome::Exited(status) => assert!(status.success(), "{status}"),
|
||||
other => panic!("the resumed guest should have finished on its own: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_runs_outside_the_callers_process_group() {
|
||||
let dir = scratch("cleanup-group");
|
||||
let server = dir.join("wineserver");
|
||||
let seen = dir.join("pgid");
|
||||
std::fs::write(
|
||||
&server,
|
||||
format!(
|
||||
"#!/bin/sh\n/usr/bin/perl -MPOSIX -e 'print getpgrp(), \"\\n\"' >> '{}'\n",
|
||||
seen.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
stop_server(&server, &dir, &[]).unwrap();
|
||||
// SAFETY: getpgrp takes no arguments and cannot fail.
|
||||
let ours = unsafe { libc::getpgrp() };
|
||||
let groups: Vec<libc::pid_t> = std::fs::read_to_string(&seen)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(|line| line.trim().parse().unwrap())
|
||||
.collect();
|
||||
assert_eq!(groups.len(), 2, "-k and -w should both have run");
|
||||
for group in groups {
|
||||
// A terminal signal goes to the foreground group, which these are not part of.
|
||||
assert_ne!(group, ours, "cleanup shares the caller's process group");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_idle_server_is_accepted_only_when_the_wait_succeeds() {
|
||||
let dir = scratch("server");
|
||||
for (name, kill, wait, ok) in [
|
||||
("running", 0, 0, true),
|
||||
("idle", 1, 0, true),
|
||||
("stuck", 1, 1, false),
|
||||
("broken", 2, 0, false),
|
||||
] {
|
||||
let server = dir.join(name);
|
||||
std::fs::write(
|
||||
&server,
|
||||
format!("#!/bin/sh\n[ \"$1\" = -k ] && exit {kill}\nexit {wait}\n"),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert_eq!(stop_server(&server, &dir, &[]).is_ok(), ok, "{name}");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Runs the built `bx-cli` binary to check what `main` prints and returns for the
|
||||
//! usage paths (#532). The unit tests cover `Dispatch::classify`; these cover the
|
||||
//! mapping from that classification to the real exit code and output stream.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
fn run(args: &[&str]) -> std::process::Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_bx-cli"))
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.output()
|
||||
.expect("bx-cli must start")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_prints_usage_on_stdout_and_succeeds() {
|
||||
for flag in ["--help", "-h", "help"] {
|
||||
let out = run(&[flag]);
|
||||
assert!(out.status.success(), "{flag}: {:?}", out.status);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(
|
||||
stdout.contains("bx-cli run --exe"),
|
||||
"{flag}: usage on stdout: {stdout}"
|
||||
);
|
||||
assert!(out.stderr.is_empty(), "{flag}: nothing on stderr");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_invocation_is_a_usage_error_on_stderr() {
|
||||
let out = run(&[]);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(out.stdout.is_empty(), "nothing on stdout");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_subcommand_is_a_usage_error_on_stderr() {
|
||||
let out = run(&["frobnicate"]);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(out.stdout.is_empty(), "nothing on stdout");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
|
||||
}
|
||||
@@ -73,7 +73,7 @@ pub fn classify_dll(dll_name: &str) -> ShimTrack {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PeSummary {
|
||||
pub image_base: u64,
|
||||
pub size_of_image: u32,
|
||||
@@ -128,12 +128,21 @@ struct Section {
|
||||
}
|
||||
|
||||
fn rva_to_off(sections: &[Section], rva: u32) -> Option<usize> {
|
||||
rva_to_off_bounded(sections, rva).map(|(off, _)| off)
|
||||
}
|
||||
|
||||
/// Map an RVA to a file offset and report how many raw bytes remain in that
|
||||
/// section from the mapped offset. The bound lets callers walk a table without
|
||||
/// leaving the section that contains it.
|
||||
fn rva_to_off_bounded(sections: &[Section], rva: u32) -> Option<(usize, usize)> {
|
||||
for s in sections {
|
||||
let span = s.vsize.max(s.raw_size);
|
||||
if rva >= s.vaddr && rva < s.vaddr.saturating_add(span) {
|
||||
let delta = rva - s.vaddr;
|
||||
if delta < s.raw_size {
|
||||
return Some((s.raw_ptr + delta) as usize);
|
||||
let off = (s.raw_ptr as usize).checked_add(delta as usize)?;
|
||||
let remaining = (s.raw_size as usize).checked_sub(delta as usize)?;
|
||||
return Some((off, remaining));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -167,8 +176,36 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
let size_of_image = u32_le(bytes, opt + 56).ok_or(ProbeError::NotPe32Plus("size_of_image"))?;
|
||||
let num_rvas = u32_le(bytes, opt + 108).ok_or(ProbeError::NotPe32Plus("num_rvas"))?;
|
||||
|
||||
let mut sections = Vec::with_capacity(section_count as usize);
|
||||
// The import data directory is entry index 1, an 8-byte RVA/size pair at
|
||||
// optional-header offset 112 + 8. Microsoft's PE format requires probes to
|
||||
// honour both NumberOfRvaAndSizes and SizeOfOptionalHeader, so the entry is
|
||||
// validated while the optional header is read: a short optional header must
|
||||
// not let the read fall through into the section table.
|
||||
const IMPORT_DIR_INDEX: u32 = 1;
|
||||
const IMPORT_DIR_OFF: usize = 112 + 8;
|
||||
let mut import_dir: Option<(u32, u32)> = None;
|
||||
if num_rvas > IMPORT_DIR_INDEX {
|
||||
let entry = bytes
|
||||
.get(opt + IMPORT_DIR_OFF..opt + IMPORT_DIR_OFF + 8)
|
||||
.ok_or(ProbeError::NotPe32Plus("truncated import directory"))?;
|
||||
if IMPORT_DIR_OFF + 8 > opt_size {
|
||||
return Err(ProbeError::NotPe32Plus(
|
||||
"import directory outside SizeOfOptionalHeader",
|
||||
));
|
||||
}
|
||||
let rva = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]);
|
||||
let size = u32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]);
|
||||
import_dir = Some((rva, size));
|
||||
}
|
||||
|
||||
let sec_base = opt + opt_size;
|
||||
let section_table_size = (section_count as usize)
|
||||
.checked_mul(40)
|
||||
.ok_or(ProbeError::NotPe32Plus("section table size overflow"))?;
|
||||
bytes
|
||||
.get(sec_base..sec_base + section_table_size)
|
||||
.ok_or(ProbeError::NotPe32Plus("truncated section table"))?;
|
||||
let mut sections = Vec::with_capacity(section_count as usize);
|
||||
for i in 0..section_count as usize {
|
||||
let so = sec_base + i * 40;
|
||||
let vsize = u32_le(bytes, so + 8).ok_or(ProbeError::NotPe32Plus("sec vsize"))?;
|
||||
@@ -184,16 +221,22 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
}
|
||||
|
||||
let mut imports: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
if num_rvas > 1 {
|
||||
let imp_rva = u32_le(bytes, opt + 112 + 8).unwrap_or(0);
|
||||
if let Some((imp_rva, imp_size)) = import_dir {
|
||||
if imp_rva != 0
|
||||
&& let Some(mut desc_off) = rva_to_off(§ions, imp_rva)
|
||||
&& let Some((mut desc_off, section_bytes_left)) = rva_to_off_bounded(§ions, imp_rva)
|
||||
{
|
||||
while let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
|
||||
u32_le(bytes, desc_off),
|
||||
u32_le(bytes, desc_off + 12),
|
||||
u32_le(bytes, desc_off + 16),
|
||||
) {
|
||||
// Bound the 20-byte IMAGE_IMPORT_DESCRIPTOR walk by BOTH the
|
||||
// declared directory Size and the section's raw bytes, whichever
|
||||
// ends first, so descriptors past the directory are not reported.
|
||||
let mut desc_bytes_left = section_bytes_left.min(imp_size as usize);
|
||||
while desc_bytes_left >= 20 {
|
||||
let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
|
||||
u32_le(bytes, desc_off),
|
||||
u32_le(bytes, desc_off + 12),
|
||||
u32_le(bytes, desc_off + 16),
|
||||
) else {
|
||||
break;
|
||||
};
|
||||
if orig_thunk == 0 && name_rva == 0 && first_thunk == 0 {
|
||||
break;
|
||||
}
|
||||
@@ -225,6 +268,7 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
imports.entry(dll).or_default().extend(syms);
|
||||
}
|
||||
desc_off += 20;
|
||||
desc_bytes_left -= 20;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -242,6 +286,129 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PE_OFF: usize = 0x80;
|
||||
const COFF: usize = PE_OFF + 4;
|
||||
const OPT: usize = COFF + 20;
|
||||
const OPT_SIZE: usize = 0xF0;
|
||||
const SEC: usize = OPT + OPT_SIZE;
|
||||
const SECTION_RVA: u32 = 0x1000;
|
||||
const RAW_PTR: u32 = 0x200;
|
||||
|
||||
fn put_u16(bytes: &mut [u8], off: usize, value: u16) {
|
||||
bytes[off..off + 2].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn put_u32(bytes: &mut [u8], off: usize, value: u32) {
|
||||
bytes[off..off + 4].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn put_u64(bytes: &mut [u8], off: usize, value: u64) {
|
||||
bytes[off..off + 8].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn write_section(bytes: &mut [u8], base: usize, rva: u32, raw_ptr: u32, raw_size: u32) {
|
||||
bytes[base..base + 8].copy_from_slice(b".rdata\0\0");
|
||||
put_u32(bytes, base + 8, raw_size);
|
||||
put_u32(bytes, base + 12, rva);
|
||||
put_u32(bytes, base + 16, raw_size);
|
||||
put_u32(bytes, base + 20, raw_ptr);
|
||||
}
|
||||
|
||||
fn minimal_pe32_plus() -> Vec<u8> {
|
||||
let mut bytes = vec![0u8; 0x400];
|
||||
bytes[0..2].copy_from_slice(b"MZ");
|
||||
put_u32(&mut bytes, 0x3C, PE_OFF as u32);
|
||||
bytes[PE_OFF..PE_OFF + 4].copy_from_slice(b"PE\0\0");
|
||||
put_u16(&mut bytes, COFF, 0x8664);
|
||||
put_u16(&mut bytes, COFF + 2, 1);
|
||||
put_u16(&mut bytes, COFF + 16, OPT_SIZE as u16);
|
||||
put_u16(&mut bytes, OPT, 0x020B);
|
||||
put_u32(&mut bytes, OPT + 16, 0x1234);
|
||||
put_u64(&mut bytes, OPT + 24, 0x0000_0001_4000_0000);
|
||||
put_u32(&mut bytes, OPT + 56, 0x2000);
|
||||
put_u32(&mut bytes, OPT + 108, 16);
|
||||
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 0x200);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn two_import_pe32_plus() -> Vec<u8> {
|
||||
let mut bytes = minimal_pe32_plus();
|
||||
let import_rva = SECTION_RVA;
|
||||
put_u32(&mut bytes, OPT + 112 + 8, import_rva);
|
||||
put_u32(&mut bytes, OPT + 112 + 12, 0x140);
|
||||
|
||||
// Two descriptors followed by the required all-zero terminator.
|
||||
put_u32(&mut bytes, RAW_PTR as usize, SECTION_RVA + 0x80);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 12, SECTION_RVA + 0x40);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 16, SECTION_RVA + 0x80);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 20, SECTION_RVA + 0xA0);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 32, SECTION_RVA + 0x50);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 36, SECTION_RVA + 0xA0);
|
||||
|
||||
bytes[RAW_PTR as usize + 0x40..RAW_PTR as usize + 0x4A].copy_from_slice(b"ALPHA.DLL\0");
|
||||
bytes[RAW_PTR as usize + 0x50..RAW_PTR as usize + 0x59].copy_from_slice(b"BETA.DLL\0");
|
||||
|
||||
put_u64(
|
||||
&mut bytes,
|
||||
RAW_PTR as usize + 0x80,
|
||||
u64::from(SECTION_RVA + 0x60),
|
||||
);
|
||||
put_u64(&mut bytes, RAW_PTR as usize + 0x88, 0);
|
||||
put_u64(&mut bytes, RAW_PTR as usize + 0xA0, (1u64 << 63) | 7);
|
||||
put_u64(&mut bytes, RAW_PTR as usize + 0xA8, 0);
|
||||
|
||||
put_u16(&mut bytes, RAW_PTR as usize + 0x60, 0x1234);
|
||||
bytes[RAW_PTR as usize + 0x62..RAW_PTR as usize + 0x6C].copy_from_slice(b"NamedFunc\0");
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Two sections: an import-descriptor section holding exactly two
|
||||
/// descriptors and no terminator, and a data section for names and thunks.
|
||||
/// Ellipsis bytes just past the descriptor section spell a third valid
|
||||
/// descriptor, so an unbounded walk reports a DLL that is not imported.
|
||||
fn import_table_without_terminator_pe32_plus() -> Vec<u8> {
|
||||
const DATA_RVA: u32 = SECTION_RVA + 0x1000;
|
||||
const DATA_PTR: u32 = 0x300;
|
||||
|
||||
let mut bytes = minimal_pe32_plus();
|
||||
put_u16(&mut bytes, COFF + 2, 2);
|
||||
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 40);
|
||||
write_section(&mut bytes, SEC + 40, DATA_RVA, DATA_PTR, 0x100);
|
||||
put_u32(&mut bytes, OPT + 112 + 8, SECTION_RVA);
|
||||
// Declare the directory to cover the whole descriptor section, so the
|
||||
// section bound (not the Size) is what this fixture exercises.
|
||||
put_u32(&mut bytes, OPT + 112 + 12, 40);
|
||||
|
||||
for (base, dll_rva, thunk_rva) in [
|
||||
(RAW_PTR as usize, DATA_RVA, DATA_RVA + 0x80),
|
||||
(RAW_PTR as usize + 20, DATA_RVA + 0x20, DATA_RVA + 0xA0),
|
||||
] {
|
||||
put_u32(&mut bytes, base, thunk_rva);
|
||||
put_u32(&mut bytes, base + 12, dll_rva);
|
||||
put_u32(&mut bytes, base + 16, thunk_rva);
|
||||
}
|
||||
|
||||
// A third, entirely valid descriptor just past the section boundary.
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 40, DATA_RVA + 0xC0);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 52, DATA_RVA + 0x40);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 56, DATA_RVA + 0xC0);
|
||||
|
||||
for (delta, name) in [
|
||||
(0x00, &b"ONE.DLL\0"[..]),
|
||||
(0x20, &b"TWO.DLL\0"[..]),
|
||||
(0x40, &b"THREE.DLL\0"[..]),
|
||||
] {
|
||||
let off = DATA_PTR as usize + delta;
|
||||
bytes[off..off + name.len()].copy_from_slice(name);
|
||||
}
|
||||
for (delta, ordinal) in [(0x80, 1u64), (0xA0, 2), (0xC0, 3)] {
|
||||
let off = DATA_PTR as usize + delta;
|
||||
put_u64(&mut bytes, off, (1u64 << 63) | ordinal);
|
||||
put_u64(&mut bytes, off + 8, 0);
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_tracks_accurately() {
|
||||
assert_eq!(classify_dll("d3d12_xs.dll"), ShimTrack::TrackCGraphics);
|
||||
@@ -263,4 +430,175 @@ mod tests {
|
||||
);
|
||||
assert_eq!(classify_dll("KERNEL32.dll"), ShimTrack::WineBuiltin);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_minimal_pe32_plus_without_imports() {
|
||||
let summary = probe_pe32_plus(&minimal_pe32_plus()).unwrap();
|
||||
assert_eq!(summary.entry_point_rva, 0x1234);
|
||||
assert_eq!(summary.image_base, 0x0000_0001_4000_0000);
|
||||
assert_eq!(summary.size_of_image, 0x2000);
|
||||
assert_eq!(summary.section_count, 1);
|
||||
assert!(summary.imports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_named_and_ordinal_imports_from_two_dlls() {
|
||||
let summary = probe_pe32_plus(&two_import_pe32_plus()).unwrap();
|
||||
let expected = BTreeMap::from([
|
||||
("ALPHA.DLL".to_owned(), vec!["NamedFunc".to_owned()]),
|
||||
("BETA.DLL".to_owned(), vec!["ORDINAL:7".to_owned()]),
|
||||
]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncation_at_every_header_boundary() {
|
||||
let image = minimal_pe32_plus();
|
||||
for len in 0..=0x100 {
|
||||
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image[..len]));
|
||||
assert!(result.is_ok(), "panic at truncation 0x{len:X}");
|
||||
assert!(result.unwrap().is_err(), "accepted truncation 0x{len:X}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_section_rva_mapping_that_would_wrap_u32() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 8, SECTION_RVA + 1);
|
||||
put_u32(&mut image, SEC + 20, u32::MAX);
|
||||
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image));
|
||||
assert!(result.is_ok(), "raw pointer addition panicked");
|
||||
assert!(result.unwrap().unwrap().imports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_section_count_larger_than_file() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u16(&mut image, COFF + 2, u16::MAX);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("truncated section table")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_pe32_magic() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u16(&mut image, OPT, 0x010B);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("not PE32+ (0x020B)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_directory_outside_all_sections_is_safe() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 8, 0x8000);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
assert!(summary.imports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncated_import_directory() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
// An empty section table that fits, an optional header long enough to
|
||||
// declare the import entry, and a file cut after two of the entry's
|
||||
// RVA bytes.
|
||||
put_u16(&mut image, COFF + 2, 0);
|
||||
put_u16(&mut image, COFF + 16, 0xE0);
|
||||
image.truncate(OPT + 112 + 8 + 2);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("truncated import directory")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_unterminated_import_descriptor_walk() {
|
||||
let summary = probe_pe32_plus(&import_table_without_terminator_pe32_plus()).unwrap();
|
||||
let expected = BTreeMap::from([
|
||||
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
|
||||
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
|
||||
]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
}
|
||||
|
||||
/// (a) A short SizeOfOptionalHeader puts the import data-directory entry
|
||||
/// past the end of the optional header, so its 8 bytes would otherwise be
|
||||
/// read from the section table. The entry index is still within
|
||||
/// NumberOfRvaAndSizes, so only the SizeOfOptionalHeader check rejects it.
|
||||
#[test]
|
||||
fn rejects_import_directory_outside_short_optional_header() {
|
||||
let mut image = two_import_pe32_plus();
|
||||
// Import entry spans optional-header offsets 120..128; declare the
|
||||
// optional header to end at 120, inside the entry.
|
||||
put_u16(&mut image, COFF + 16, 120);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
|
||||
);
|
||||
|
||||
// One byte short of the full 8-byte entry is still out of range.
|
||||
let mut image = two_import_pe32_plus();
|
||||
put_u16(&mut image, COFF + 16, 127);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
|
||||
);
|
||||
|
||||
// Exactly 128 bytes covers the whole entry, so the import directory is
|
||||
// read normally. The section table now starts at OPT + 128, so write it
|
||||
// there for this size.
|
||||
let mut image = two_import_pe32_plus();
|
||||
put_u16(&mut image, COFF + 16, 128);
|
||||
write_section(&mut image, OPT + 128, SECTION_RVA, RAW_PTR, 0x200);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
assert!(summary.imports.contains_key("ALPHA.DLL"));
|
||||
assert!(summary.imports.contains_key("BETA.DLL"));
|
||||
}
|
||||
|
||||
/// NumberOfRvaAndSizes == 1 means only entry 0 (export) is declared, so the
|
||||
/// import entry (index 1) must not be probed even though its bytes are
|
||||
/// present and inside SizeOfOptionalHeader.
|
||||
#[test]
|
||||
fn ignores_import_directory_beyond_number_of_rva_and_sizes() {
|
||||
let mut image = two_import_pe32_plus();
|
||||
put_u32(&mut image, OPT + 108, 1);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
assert!(summary.imports.is_empty());
|
||||
}
|
||||
|
||||
/// (b) The declared import directory Size is shorter than the containing
|
||||
/// section, so descriptors past the declared size must not be reported even
|
||||
/// though they are valid and inside the section's raw bytes.
|
||||
#[test]
|
||||
fn bounds_import_descriptor_walk_by_declared_directory_size() {
|
||||
// Size 40 covers exactly the two real descriptors; the third valid
|
||||
// descriptor at +40 lies outside the directory but inside the section.
|
||||
let mut image = import_table_without_terminator_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 12, 40);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
let expected = BTreeMap::from([
|
||||
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
|
||||
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
|
||||
]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
assert!(!summary.imports.contains_key("THREE.DLL"));
|
||||
|
||||
// Size 20 reports only the first descriptor.
|
||||
let mut image = import_table_without_terminator_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 12, 20);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
|
||||
// A size that is not a multiple of 20 stops before the next descriptor
|
||||
// would exceed the directory.
|
||||
let mut image = import_table_without_terminator_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 12, 39);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,212 @@
|
||||
//! Track A / F: Structured JSONL shim trace aggregator.
|
||||
//!
|
||||
//! Summarizes `bx_runtime_veh.dll` logs (stub API calls, unimplemented COM vtable
|
||||
//! slots, `clwb` traps, and ADX illegal-instruction tripwires) so tracks can prioritize
|
||||
//! the exact next blocking API.
|
||||
//! slots, `clwb` traps, ADX illegal-instruction tripwires, and unhandled exceptions)
|
||||
//! so tracks can identify guest failures and missing APIs.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct TraceSummary {
|
||||
pub total_lines: usize,
|
||||
/// Number of `clwb_trapped` records in the log.
|
||||
pub clwb_events: usize,
|
||||
/// Highest cumulative counter in the sampled CLWB records, if available.
|
||||
pub clwb_trap_lower_bound: Option<u64>,
|
||||
/// 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>,
|
||||
/// First-chance `breakpoint_exception` records (int3 and assertion failures), which a
|
||||
/// guest's own crash reporter would otherwise hide from `unhandled_exception`.
|
||||
pub breakpoint_exceptions: Vec<BreakpointException>,
|
||||
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>,
|
||||
/// Those same gap records grouped by `(pso, stage)`, in first-seen order (#590).
|
||||
pub shader_gap_groups: Vec<ShaderGapGroup>,
|
||||
/// Gap records that carried no `pso` or no `stage` (or an empty value for one), so
|
||||
/// they are grouped under `unknown`. Counted here so the group counts reconcile
|
||||
/// with [`TraceSummary::shader_gaps`].
|
||||
pub shader_gaps_missing_identity: usize,
|
||||
/// Gap records that carried no `wave_lanes_min` or no `atomic64_flags` (or an empty
|
||||
/// value for one). Counted here rather than dropped or assumed.
|
||||
pub shader_gaps_missing_constraints: usize,
|
||||
/// `shader_bridge_missing` messages, in log order.
|
||||
pub shader_bridge_missing: Vec<String>,
|
||||
}
|
||||
|
||||
/// One `(pso, stage)` group of `shader_d3dmetal_gap` records (#590).
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGapGroup {
|
||||
/// The emitted `pso=` value, or `None` when the record carried none (rendered as
|
||||
/// `unknown`).
|
||||
pub pso: Option<String>,
|
||||
/// The emitted `stage=` value, or `None` when the record carried none.
|
||||
pub stage: Option<String>,
|
||||
/// How many gap records this `(pso, stage)` pair covers.
|
||||
pub count: usize,
|
||||
/// The distinct `(wave_lanes_min, atomic64_flags)` pairs seen for this pair, in
|
||||
/// first-seen order. Two pipelines of the same kind and stage can need different
|
||||
/// wave widths or atomic features, so a group keeps each constraint set rather than
|
||||
/// reporting only the first and losing the rest.
|
||||
pub variants: Vec<ShaderGapVariant>,
|
||||
}
|
||||
|
||||
/// The constraints carried by one or more records of a [`ShaderGapGroup`].
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGapVariant {
|
||||
pub wave_lanes_min: Option<String>,
|
||||
pub atomic64_flags: Option<String>,
|
||||
/// How many records in the group carried exactly these constraints.
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
pub struct UnhandledException {
|
||||
pub exception_code: Option<String>,
|
||||
pub module_base: Option<String>,
|
||||
pub rva: Option<String>,
|
||||
pub rip: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct BreakpointException {
|
||||
pub exception_code: Option<String>,
|
||||
pub module: Option<String>,
|
||||
pub module_base: Option<String>,
|
||||
pub rva: Option<String>,
|
||||
/// The faulting address, which locates a breakpoint outside any image (module `?`).
|
||||
pub address: Option<String>,
|
||||
/// 1-based index of this record and the per-process cap, so a reader can tell a run
|
||||
/// that hit the cap (later breakpoints not recorded) from one that stopped short of it.
|
||||
pub record: Option<u32>,
|
||||
pub limit: Option<u32>,
|
||||
}
|
||||
|
||||
fn extract_json_u32(line: &str, key: &str) -> Option<u32> {
|
||||
let needle = format!("\"{key}\":");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
let digits: &str = &line[start..];
|
||||
let end = digits
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(digits.len());
|
||||
digits[..end].parse().ok()
|
||||
}
|
||||
|
||||
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
@@ -23,6 +217,124 @@ 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);
|
||||
}
|
||||
|
||||
/// A field value, treating an empty value (`pso= stage=CS`) as absent. The emitter
|
||||
/// always writes a value, so an empty one means the record is malformed, not that the
|
||||
/// pipeline is named "".
|
||||
fn non_empty(value: Option<String>) -> Option<String> {
|
||||
value.filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// Adds one gap record to the per-`(pso, stage)` grouping, keeping first-seen order.
|
||||
///
|
||||
/// Nothing here panics: a record missing `pso`, `stage`, `wave_lanes_min` or
|
||||
/// `atomic64_flags` is grouped under `unknown` (and counted), never dropped or guessed.
|
||||
fn record_shader_gap_group(groups: &mut TraceSummary, gap: &ShaderGap) {
|
||||
let pso = non_empty(gap.pso.clone());
|
||||
let stage = non_empty(gap.stage.clone());
|
||||
let wave_lanes_min = non_empty(gap.wave_lanes_min.clone());
|
||||
let atomic64_flags = non_empty(gap.atomic64_flags.clone());
|
||||
if pso.is_none() || stage.is_none() {
|
||||
groups.shader_gaps_missing_identity += 1;
|
||||
}
|
||||
if wave_lanes_min.is_none() || atomic64_flags.is_none() {
|
||||
groups.shader_gaps_missing_constraints += 1;
|
||||
}
|
||||
|
||||
// The group list is small (one entry per affected pipeline stage), so a linear scan
|
||||
// keeps first-seen order without a second index to keep in sync.
|
||||
let group_index = match groups
|
||||
.shader_gap_groups
|
||||
.iter()
|
||||
.position(|g| g.pso == pso && g.stage == stage)
|
||||
{
|
||||
Some(index) => index,
|
||||
None => {
|
||||
groups.shader_gap_groups.push(ShaderGapGroup {
|
||||
pso,
|
||||
stage,
|
||||
count: 0,
|
||||
variants: Vec::new(),
|
||||
});
|
||||
groups.shader_gap_groups.len() - 1
|
||||
}
|
||||
};
|
||||
let group = &mut groups.shader_gap_groups[group_index];
|
||||
group.count += 1;
|
||||
match group
|
||||
.variants
|
||||
.iter()
|
||||
.position(|v| v.wave_lanes_min == wave_lanes_min && v.atomic64_flags == atomic64_flags)
|
||||
{
|
||||
Some(index) => group.variants[index].count += 1,
|
||||
None => group.variants.push(ShaderGapVariant {
|
||||
wave_lanes_min,
|
||||
atomic64_flags,
|
||||
count: 1,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
let gap = ShaderGap {
|
||||
pso: get_field(&pairs, "pso"),
|
||||
stage: get_field(&pairs, "stage"),
|
||||
wave_lanes_min: get_field(&pairs, "wave_lanes_min"),
|
||||
atomic64_flags,
|
||||
};
|
||||
record_shader_gap_group(summary, &gap);
|
||||
summary.shader_gaps.push(gap);
|
||||
}
|
||||
|
||||
pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
let mut summary = TraceSummary::default();
|
||||
for line in input.lines() {
|
||||
@@ -34,8 +346,42 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
let event = extract_json_str(trimmed, "event").unwrap_or("");
|
||||
let detail = extract_json_str(trimmed, "detail").unwrap_or("");
|
||||
match event {
|
||||
"clwb_trapped" => summary.clwb_events += 1,
|
||||
"clwb_trapped" => {
|
||||
summary.clwb_events += 1;
|
||||
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" => {
|
||||
summary.unhandled_exceptions.push(UnhandledException {
|
||||
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
|
||||
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
|
||||
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
|
||||
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
|
||||
});
|
||||
}
|
||||
"breakpoint_exception" => {
|
||||
summary.breakpoint_exceptions.push(BreakpointException {
|
||||
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
|
||||
module: extract_json_str(trimmed, "module").map(str::to_owned),
|
||||
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
|
||||
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
|
||||
address: extract_json_str(trimmed, "address").map(str::to_owned),
|
||||
record: extract_json_u32(trimmed, "record"),
|
||||
limit: extract_json_u32(trimmed, "limit"),
|
||||
});
|
||||
}
|
||||
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
|
||||
"unimpl_vtable" => {
|
||||
*summary
|
||||
@@ -64,7 +410,9 @@ mod tests {
|
||||
let s = summarize_jsonl(sample);
|
||||
assert_eq!(s.total_lines, 4);
|
||||
assert_eq!(s.clwb_events, 1);
|
||||
assert_eq!(s.clwb_trap_lower_bound, Some(1));
|
||||
assert_eq!(s.adx_errors, 0);
|
||||
assert!(s.unhandled_exceptions.is_empty());
|
||||
assert_eq!(
|
||||
s.unimpl_apis.get("d3d12_xs.dll!D3D12XboxCreateDevice"),
|
||||
Some(&2)
|
||||
@@ -75,4 +423,490 @@ mod tests {
|
||||
Some(&1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_highest_counter_from_sampled_clwb_records() {
|
||||
for (actual_traps, records, expected_bound) in [
|
||||
(1, &[1][..], 1),
|
||||
(6, &[1, 4, 2], 4),
|
||||
(100, &[1, 2, 4, 8, 16, 32, 64], 64),
|
||||
] {
|
||||
let mut log = String::new();
|
||||
for counter in records {
|
||||
log.push_str(&format!(
|
||||
"{{\"event\":\"clwb_trapped\",\"detail\":\"rip=0x1000 len=4 total_traps={counter}\"}}\n"
|
||||
));
|
||||
}
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.clwb_events, records.len(), "{actual_traps} traps");
|
||||
assert_eq!(
|
||||
summary.clwb_trap_lower_bound,
|
||||
Some(expected_bound),
|
||||
"{actual_traps} traps"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_clwb_record_count_without_valid_counters() {
|
||||
let summary = summarize_jsonl(
|
||||
r#"{"event":"clwb_trapped","detail":"rip=0x1000 len=4"}
|
||||
{"event":"clwb_trapped","detail":"rip=0x1000 len=4 total_traps=invalid"}
|
||||
{"event":"unimpl_api","detail":"total_traps=100"}"#,
|
||||
);
|
||||
assert_eq!(summary.clwb_events, 2);
|
||||
assert_eq!(summary.clwb_trap_lower_bound, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_breakpoint_exceptions_in_log_order() {
|
||||
let log = r#"
|
||||
{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x0000000002236178","address":"0x0000000142236178","record":1,"limit":16}
|
||||
{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
|
||||
"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert!(summary.unhandled_exceptions.is_empty());
|
||||
assert_eq!(
|
||||
summary.breakpoint_exceptions,
|
||||
[
|
||||
BreakpointException {
|
||||
exception_code: Some("0x80000003".into()),
|
||||
module: Some("title.exe".into()),
|
||||
module_base: Some("0x0000000140000000".into()),
|
||||
rva: Some("0x0000000002236178".into()),
|
||||
address: Some("0x0000000142236178".into()),
|
||||
record: Some(1),
|
||||
limit: Some(16),
|
||||
},
|
||||
BreakpointException {
|
||||
exception_code: Some("0xc0000420".into()),
|
||||
module: Some("?".into()),
|
||||
module_base: Some("0x0000000000000000".into()),
|
||||
rva: Some("0x0000000000000000".into()),
|
||||
address: Some("0x0000000000410000".into()),
|
||||
record: Some(2),
|
||||
limit: Some(16),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_unhandled_exceptions_in_log_order() {
|
||||
let log = r#"
|
||||
{"ts_ms":16,"tid":1,"level":"ERROR","sub":"runtime_veh","event":"unhandled_exception","exception_code":"0xc0000005","module_base":"0x0000000140000000","rva":"0x0000000000001234","rip":"0x0000000140001234","rsp":"0x000000000021fd80","registers":{"rax":"0x0123456789abcdef","rbx":"0x0000000000000000","rcx":"0x0000000000000000","rdx":"0x0000000000000000","rsi":"0x0000000000000000","rdi":"0x0000000000000000","rbp":"0x0000000000000000","r8":"0x0000000000000000","r9":"0x0000000000000000","r10":"0x0000000000000000","r11":"0x0000000000000000","r12":"0x0000000000000000","r13":"0x0000000000000000","r14":"0x0000000000000000","r15":"0x0000000000000000"}}
|
||||
{"ts_ms":20,"tid":1,"level":"ERROR","sub":"runtime_veh","event":"unhandled_exception","exception_code":"0xc000001d","module_base":"0x0000000000000000","rva":"0x0000000000000000","rip":"0x0000000000410000","rsp":"0x000000000021fd80","registers":{}}
|
||||
"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.total_lines, 2);
|
||||
assert_eq!(
|
||||
summary.unhandled_exceptions,
|
||||
[
|
||||
UnhandledException {
|
||||
exception_code: Some("0xc0000005".into()),
|
||||
module_base: Some("0x0000000140000000".into()),
|
||||
rva: Some("0x0000000000001234".into()),
|
||||
rip: Some("0x0000000140001234".into()),
|
||||
},
|
||||
UnhandledException {
|
||||
exception_code: Some("0xc000001d".into()),
|
||||
module_base: Some("0x0000000000000000".into()),
|
||||
rva: Some("0x0000000000000000".into()),
|
||||
rip: Some("0x0000000000410000".into()),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[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"));
|
||||
}
|
||||
|
||||
/// #590: two gaps on different stages must stay two groups, in first-seen order, each
|
||||
/// with its own wave width and 64-bit-atomic flags.
|
||||
#[test]
|
||||
fn groups_gaps_on_different_stages_separately_in_first_seen_order() {
|
||||
// Same pso, different stages: grouping on pso alone would collapse these, so the
|
||||
// test discriminates the (pso, stage) key rather than only the pso.
|
||||
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=VS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"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)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gaps.len(), 3);
|
||||
assert_eq!(summary.shader_gaps_missing_identity, 0);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 0);
|
||||
assert_eq!(summary.shader_gap_groups.len(), 3);
|
||||
|
||||
let first = &summary.shader_gap_groups[0];
|
||||
assert_eq!(first.pso.as_deref(), Some("graphics"));
|
||||
assert_eq!(first.stage.as_deref(), Some("VS"));
|
||||
assert_eq!(first.count, 1);
|
||||
assert_eq!(
|
||||
first.variants,
|
||||
[ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x0".into()),
|
||||
count: 1,
|
||||
}]
|
||||
);
|
||||
|
||||
let second = &summary.shader_gap_groups[1];
|
||||
assert_eq!(second.pso.as_deref(), Some("compute"));
|
||||
assert_eq!(second.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(second.count, 1);
|
||||
|
||||
// A second stage of the *same* pso stays its own group, which is what separates a
|
||||
// (pso, stage) key from a pso-only key.
|
||||
let third = &summary.shader_gap_groups[2];
|
||||
assert_eq!(third.pso.as_deref(), Some("graphics"));
|
||||
assert_eq!(third.stage.as_deref(), Some("PS"));
|
||||
assert_eq!(third.count, 1);
|
||||
}
|
||||
|
||||
/// #590: the same `(pso, stage)` twice is one group with a count of two, even when the
|
||||
/// identical records are not adjacent.
|
||||
#[test]
|
||||
fn groups_identical_gaps_together() {
|
||||
let record = r#"{"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 other = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=32 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let log = format!("{record}\n{other}\n{record}\n");
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.shader_gaps.len(), 3);
|
||||
assert_eq!(summary.shader_gap_groups.len(), 2);
|
||||
let compute = &summary.shader_gap_groups[0];
|
||||
assert_eq!(compute.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(compute.count, 2);
|
||||
assert_eq!(
|
||||
compute.variants,
|
||||
[ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x400000".into()),
|
||||
count: 2,
|
||||
}]
|
||||
);
|
||||
assert_eq!(summary.shader_gap_groups[1].count, 1);
|
||||
// Every record is in exactly one group.
|
||||
let grouped: usize = summary.shader_gap_groups.iter().map(|g| g.count).sum();
|
||||
assert_eq!(grouped, summary.shader_gaps.len());
|
||||
}
|
||||
|
||||
/// #590: one pipeline kind and stage can need different wave widths or atomic
|
||||
/// features, so a group keeps every distinct constraint set, not only the first.
|
||||
#[test]
|
||||
fn one_group_keeps_each_distinct_constraint_set() {
|
||||
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gap_groups.len(), 1);
|
||||
let group = &summary.shader_gap_groups[0];
|
||||
assert_eq!(group.count, 3);
|
||||
assert_eq!(
|
||||
group.variants,
|
||||
[
|
||||
ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x0".into()),
|
||||
count: 2,
|
||||
},
|
||||
ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x400000".into()),
|
||||
count: 1,
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 0);
|
||||
}
|
||||
|
||||
/// #590: a gap record with a missing or empty field must not panic. It is grouped
|
||||
/// under `unknown` and counted, never dropped or guessed.
|
||||
#[test]
|
||||
fn a_malformed_gap_record_is_grouped_under_unknown_and_counted() {
|
||||
for (detail, missing_identity, missing_constraints) in [
|
||||
("", 1, 1),
|
||||
("garbage", 1, 1),
|
||||
("pso=compute", 1, 1),
|
||||
("stage=CS", 1, 1),
|
||||
(
|
||||
"pso= stage=CS wave_lanes_min=64 atomic64_flags=0x400000",
|
||||
1,
|
||||
0,
|
||||
),
|
||||
("pso=compute stage=CS", 0, 1),
|
||||
(
|
||||
"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=",
|
||||
0,
|
||||
1,
|
||||
),
|
||||
] {
|
||||
let log = format!(r#"{{"event":"shader_d3dmetal_gap","detail":"{detail}"}}"#);
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.shader_gaps.len(), 1, "detail={detail:?}");
|
||||
assert_eq!(
|
||||
summary.shader_gap_groups.len(),
|
||||
1,
|
||||
"detail={detail:?} lost its record"
|
||||
);
|
||||
assert_eq!(
|
||||
summary.shader_gaps_missing_identity, missing_identity,
|
||||
"detail={detail:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
summary.shader_gaps_missing_constraints, missing_constraints,
|
||||
"detail={detail:?}"
|
||||
);
|
||||
let group = &summary.shader_gap_groups[0];
|
||||
assert_eq!(group.count, 1, "detail={detail:?}");
|
||||
let recorded: usize = group.variants.iter().map(|v| v.count).sum();
|
||||
assert_eq!(recorded, 1, "detail={detail:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #590: the fields a malformed record does carry are still reported.
|
||||
#[test]
|
||||
fn a_partly_malformed_gap_record_keeps_the_fields_it_has() {
|
||||
let log =
|
||||
r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
let group = &summary.shader_gap_groups[0];
|
||||
assert_eq!(group.pso.as_deref(), Some("compute"));
|
||||
assert_eq!(group.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(
|
||||
group.variants,
|
||||
[ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: None,
|
||||
count: 1,
|
||||
}]
|
||||
);
|
||||
assert_eq!(summary.shader_gaps_missing_identity, 0);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 1);
|
||||
}
|
||||
|
||||
/// #590: a run with no gap records produces no groups and no missing-field counts, so
|
||||
/// the trace renders as it did before the grouping existed.
|
||||
#[test]
|
||||
fn a_run_with_no_gaps_has_no_groups() {
|
||||
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!(summary.shader_gaps.is_empty());
|
||||
assert!(summary.shader_gap_groups.is_empty());
|
||||
assert_eq!(summary.shader_gaps_missing_identity, 0);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 0);
|
||||
}
|
||||
}
|
||||
+117
-21
@@ -4,11 +4,15 @@
|
||||
Checks only tracked files:
|
||||
1. no merge-conflict markers in tracked text files;
|
||||
2. every relative Markdown link points at a tracked file or directory;
|
||||
3. every workflow file under .github/workflows parses as YAML.
|
||||
3. every fragment (``#heading``) in a Markdown link resolves to a real
|
||||
heading in the target Markdown file, including in-page ``](#foo)``
|
||||
links validated against the same file's headings;
|
||||
4. every workflow file under .github/workflows parses as YAML.
|
||||
|
||||
External URLs and in-page anchors are not fetched or validated, so the result
|
||||
does not depend on the network. Exit status is 1 when a problem is found. Pass --require-yaml to fail, not skip,
|
||||
when PyYAML is missing.
|
||||
External URLs (http:, https:, mailto:, //) and bare ``#`` links are not
|
||||
fetched or validated, so the result does not depend on the network.
|
||||
Exit status is 1 when a problem is found. Pass --require-yaml to fail,
|
||||
not skip, when PyYAML is missing.
|
||||
"""
|
||||
import re
|
||||
import subprocess
|
||||
@@ -17,9 +21,16 @@ from pathlib import Path, PurePosixPath
|
||||
from urllib.parse import unquote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MARKER = re.compile(r"^(<{7}( |$)|={7}$|>{7}( |$))")
|
||||
MARKER = re.compile(r"^(<{7}( |$)|\|{7}( |$)|={7}$|>{7}( |$))")
|
||||
LINK = re.compile(r"(?<!\!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
|
||||
FENCE = re.compile(r"^\s*(```|~~~)")
|
||||
HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
|
||||
# GitHub slugs the rendered heading, so an inline link contributes only its
|
||||
# text: ``## See [ADR](x.md)`` slugs as ``see-adr``, not ``see-adrxmd``.
|
||||
# Link syntax inside a code span stays literal, so those spans are set aside
|
||||
# before substituting and put back afterwards.
|
||||
INLINE_LINK = re.compile(r"(?<!\!)\[([^\]]*)\]\([^)]*\)")
|
||||
CODE_SPAN = re.compile(r"(`+)(.+?)\1")
|
||||
|
||||
|
||||
def tracked():
|
||||
@@ -35,6 +46,63 @@ def text(path):
|
||||
return data.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def _slug(text):
|
||||
"""GitHub-style slug: lowercase, strip non-alnum/-/_/space, spaces -> -."""
|
||||
text = text.lower()
|
||||
text = re.sub(r"[^\w\- ]", "", text, flags=re.UNICODE)
|
||||
return text.replace(" ", "-")
|
||||
|
||||
|
||||
def _heading_text(text):
|
||||
"""Rendered text of a heading: link text in, code spans left literal."""
|
||||
spans = []
|
||||
|
||||
def stash(match):
|
||||
spans.append(match.group(0))
|
||||
return "\x00%d\x00" % (len(spans) - 1)
|
||||
|
||||
stashed = CODE_SPAN.sub(stash, text)
|
||||
substituted = INLINE_LINK.sub(r"\1", stashed)
|
||||
for index, span in enumerate(spans):
|
||||
substituted = substituted.replace("\x00%d\x00" % index, span)
|
||||
return substituted
|
||||
|
||||
|
||||
def markdown_slugs(body):
|
||||
"""Return the set of GitHub-style heading slugs in a Markdown document.
|
||||
|
||||
Duplicate headings get ``-1``, ``-2``, ... suffixes. Headings inside
|
||||
fenced code blocks are ignored.
|
||||
"""
|
||||
slugs = set()
|
||||
seen = {}
|
||||
in_fence = False
|
||||
for line in body.splitlines():
|
||||
if FENCE.match(line):
|
||||
in_fence = not in_fence
|
||||
continue
|
||||
if in_fence:
|
||||
continue
|
||||
m = HEADING.match(line)
|
||||
if not m:
|
||||
continue
|
||||
base = _slug(_heading_text(m.group(2)))
|
||||
if not base:
|
||||
continue
|
||||
# Advance the numeric suffix until we find a slug that has not
|
||||
# already been emitted. Counting only identical bases is not
|
||||
# enough: a literal heading such as ``Foo-1`` may already own
|
||||
# ``foo-1``, so the next ``Foo`` must become ``foo-2``.
|
||||
count = seen.get(base, 0)
|
||||
slug = base if count == 0 else f"{base}-{count}"
|
||||
while slug in slugs:
|
||||
count += 1
|
||||
slug = f"{base}-{count}"
|
||||
seen[base] = count + 1
|
||||
slugs.add(slug)
|
||||
return slugs
|
||||
|
||||
|
||||
def check_markers(files, problems):
|
||||
for path in files:
|
||||
if path.endswith((".patch", ".diff")):
|
||||
@@ -47,9 +115,30 @@ def check_markers(files, problems):
|
||||
problems.append(f"{path}:{number}: merge conflict marker")
|
||||
|
||||
|
||||
def _resolve_link(path, target):
|
||||
"""Resolve a relative link target to a repo-root-relative POSIX path."""
|
||||
base = PurePosixPath(path).parent
|
||||
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
|
||||
parts = []
|
||||
for part in resolved.parts:
|
||||
if part == "..":
|
||||
if parts:
|
||||
parts.pop()
|
||||
elif part != ".":
|
||||
parts.append(part)
|
||||
return "/".join(parts)
|
||||
|
||||
|
||||
def check_links(files, problems):
|
||||
known = set(files)
|
||||
dirs = {str(d) for f in files for d in PurePosixPath(f).parents}
|
||||
slug_cache = {}
|
||||
|
||||
def slugs_for(md_path):
|
||||
if md_path not in slug_cache:
|
||||
slug_cache[md_path] = markdown_slugs(text(md_path) or "")
|
||||
return slug_cache[md_path]
|
||||
|
||||
for path in files:
|
||||
if not path.endswith(".md") or path.startswith(("artifacts/", "third_party/")):
|
||||
continue
|
||||
@@ -61,24 +150,31 @@ def check_links(files, problems):
|
||||
if in_fence:
|
||||
continue
|
||||
line = re.sub(r"`[^`]*`", "", line)
|
||||
for target in LINK.findall(line):
|
||||
if re.match(r"^([a-z][a-z0-9+.-]*:|#|//)", target, re.I):
|
||||
for raw_target in LINK.findall(line):
|
||||
if re.match(r"^([a-z][a-z0-9+.-]*:|//)", raw_target, re.I):
|
||||
continue
|
||||
target = unquote(target.split("#", 1)[0].split("?", 1)[0])
|
||||
if not target:
|
||||
if raw_target == "#":
|
||||
continue
|
||||
base = PurePosixPath(path).parent
|
||||
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
|
||||
parts = []
|
||||
for part in resolved.parts:
|
||||
if part == "..":
|
||||
if parts:
|
||||
parts.pop()
|
||||
elif part != ".":
|
||||
parts.append(part)
|
||||
norm = "/".join(parts)
|
||||
if norm and norm not in known and norm not in dirs:
|
||||
problems.append(f"{path}:{number}: broken relative link '{target}'")
|
||||
fragment = ""
|
||||
if "#" in raw_target:
|
||||
fragment = unquote(raw_target.split("#", 1)[1])
|
||||
target = unquote(raw_target.split("#", 1)[0].split("?", 1)[0])
|
||||
if not target and not fragment:
|
||||
continue
|
||||
if target:
|
||||
norm = _resolve_link(path, target)
|
||||
if norm and norm not in known and norm not in dirs:
|
||||
problems.append(f"{path}:{number}: broken relative link '{target}'")
|
||||
continue
|
||||
else:
|
||||
norm = path
|
||||
if fragment and norm.endswith(".md") and norm in known:
|
||||
if fragment not in slugs_for(norm):
|
||||
shown = raw_target
|
||||
problems.append(
|
||||
f"{path}:{number}: broken fragment '#{fragment}' "
|
||||
f"in link '{shown}' (heading not found)"
|
||||
)
|
||||
|
||||
|
||||
def check_workflows(files, problems, require_yaml):
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests for scripts/audit/docs_hygiene.py anchor validation.
|
||||
|
||||
Run with:
|
||||
python3 -m unittest scripts/audit/test_docs_hygiene.py
|
||||
"""
|
||||
import importlib.util
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
_MODULE_PATH = Path(__file__).resolve().parent / "docs_hygiene.py"
|
||||
_spec = importlib.util.spec_from_file_location("docs_hygiene", _MODULE_PATH)
|
||||
docs_hygiene = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["docs_hygiene"] = docs_hygiene
|
||||
_spec.loader.exec_module(docs_hygiene)
|
||||
|
||||
|
||||
class SlugTests(unittest.TestCase):
|
||||
def test_basic_slug(self):
|
||||
slugs = docs_hygiene.markdown_slugs("# Hello World\n")
|
||||
self.assertIn("hello-world", slugs)
|
||||
|
||||
def test_strips_punctuation(self):
|
||||
slugs = docs_hygiene.markdown_slugs("## What's new? (2024)\n")
|
||||
self.assertIn("whats-new-2024", slugs)
|
||||
|
||||
def test_keeps_underscore_and_hyphen(self):
|
||||
slugs = docs_hygiene.markdown_slugs("### foo_bar-baz\n")
|
||||
self.assertIn("foo_bar-baz", slugs)
|
||||
|
||||
def test_duplicate_headings(self):
|
||||
body = "# Setup\n\n# Setup\n\n# Setup\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertIn("setup", slugs)
|
||||
self.assertIn("setup-1", slugs)
|
||||
self.assertIn("setup-2", slugs)
|
||||
|
||||
def test_suffix_skips_literal_heading_slug(self):
|
||||
# Regression: counting identical bases alone lets a generated
|
||||
# suffix collide with a literal heading slug, so the third `Foo`
|
||||
# also became `foo-1` and a link to the wrong heading validated.
|
||||
body = "# Foo\n\n# Foo-1\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
|
||||
|
||||
def test_suffix_skips_multiple_literal_heading_slugs(self):
|
||||
body = "# Foo\n\n# Foo-1\n\n# Foo-2\n\n# Foo\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo", "foo-1", "foo-2", "foo-3", "foo-4"})
|
||||
|
||||
def test_three_identical_headings(self):
|
||||
body = "# Foo\n\n# Foo\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
|
||||
|
||||
def test_literal_slug_before_duplicates(self):
|
||||
body = "# Foo-1\n\n# Foo\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo-1", "foo", "foo-2"})
|
||||
|
||||
def test_heading_link_contributes_only_its_text(self):
|
||||
# GitHub slugs the rendered heading, where the link's URL is gone.
|
||||
# Slugging the raw source appended the URL and made the first real
|
||||
# link to the anchor look broken.
|
||||
slugs = docs_hygiene.markdown_slugs("## Setup [guide](other.md) notes\n")
|
||||
self.assertEqual(slugs, {"setup-guide-notes"})
|
||||
|
||||
def test_heading_link_matches_github_for_the_readme_heading(self):
|
||||
# The exact heading at README.md:53; GitHub renders
|
||||
# `#active-milestone--m2-first-rendered-frame--shader-format-gate`.
|
||||
body = ("### Active Milestone \u2014 [M2: First Rendered Frame & Shader "
|
||||
"Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)\n")
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(
|
||||
slugs, {"active-milestone--m2-first-rendered-frame--shader-format-gate"})
|
||||
|
||||
def test_heading_link_duplicate_still_gets_a_suffix(self):
|
||||
body = "## See [ADR](a.md) notes\n\n## See [ADR](b.md) notes\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"see-adr-notes", "see-adr-notes-1"})
|
||||
|
||||
def test_heading_link_inside_a_code_span_stays_literal(self):
|
||||
# GitHub keeps `[x](y)` literal inside a code span, so its URL stays in
|
||||
# the slug. Substituting links first made this `code-x-span`.
|
||||
slugs = docs_hygiene.markdown_slugs("## Code `[x](y)` span\n")
|
||||
self.assertEqual(slugs, {"code-xy-span"})
|
||||
|
||||
def test_heading_mixes_a_code_span_and_a_link(self):
|
||||
# Only the real link loses its URL; the code span keeps its text.
|
||||
slugs = docs_hygiene.markdown_slugs("## See `a` and [b](c.md)\n")
|
||||
self.assertEqual(slugs, {"see-a-and-b"})
|
||||
|
||||
def test_heading_double_backtick_code_span(self):
|
||||
# GitHub's own renderer gives `#use-a-b-cdmd-here` for this heading:
|
||||
# the inner single-backtick run closes the outer span early, so the
|
||||
# `[c](d.md)` after it is a real link and loses its URL. Asserting the
|
||||
# observed GitHub anchor keeps this honest rather than assuming the
|
||||
# "obvious" answer.
|
||||
slugs = docs_hygiene.markdown_slugs("## Use ``a `b` [c](d.md)`` here\n")
|
||||
self.assertEqual(slugs, {"use-a-b-cdmd-here"})
|
||||
|
||||
def test_heading_image_is_not_treated_as_a_link(self):
|
||||
# An image contributes its alt text through GitHub's rendering, but
|
||||
# the `(?<!\!)` guard must keep this path unchanged for now.
|
||||
slugs = docs_hygiene.markdown_slugs("##  caption\n")
|
||||
self.assertEqual(len(slugs), 1)
|
||||
|
||||
def test_fenced_code_block_ignored(self):
|
||||
body = "```\n# Not A Heading\n```\n\n# Real Heading\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertIn("real-heading", slugs)
|
||||
self.assertNotIn("not-a-heading", slugs)
|
||||
|
||||
def test_tilde_fence_ignored(self):
|
||||
body = "~~~\n# Not A Heading\n~~~\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertNotIn("not-a-heading", slugs)
|
||||
|
||||
def test_atx_levels(self):
|
||||
body = "# One\n## Two\n### Three\n#### Four\n##### Five\n###### Six\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
for s in ("one", "two", "three", "four", "five", "six"):
|
||||
self.assertIn(s, slugs)
|
||||
|
||||
|
||||
class CheckLinksTests(unittest.TestCase):
|
||||
"""Exercise check_links with a synthetic in-memory file set."""
|
||||
|
||||
def _run(self, files):
|
||||
"""files: dict mapping repo-relative path -> Markdown body."""
|
||||
problems = []
|
||||
original_text = docs_hygiene.text
|
||||
|
||||
def fake_text(path):
|
||||
return files.get(path)
|
||||
|
||||
docs_hygiene.text = fake_text
|
||||
try:
|
||||
docs_hygiene.check_links(list(files), problems)
|
||||
finally:
|
||||
docs_hygiene.text = original_text
|
||||
return problems
|
||||
|
||||
def test_existing_heading_passes(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "# Hello World\n\n[link](b.md#hello-world)\n",
|
||||
"docs/b.md": "# Hello World\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_in_page_anchor_passes(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "# Hello World\n\n[link](#hello-world)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_nonexistent_heading_fails(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](b.md#no-such-heading)\n",
|
||||
"docs/b.md": "# Hello World\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("#no-such-heading", problems[0])
|
||||
self.assertIn("heading not found", problems[0])
|
||||
|
||||
def test_in_page_nonexistent_heading_fails(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "# Real\n\n[link](#this-heading-does-not-exist)\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("#this-heading-does-not-exist", problems[0])
|
||||
|
||||
def test_duplicate_heading_addressable(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](b.md#setup-1)\n",
|
||||
"docs/b.md": "# Setup\n\n# Setup\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_fenced_heading_not_a_slug(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](b.md#not-a-heading)\n",
|
||||
"docs/b.md": "```\n# Not A Heading\n```\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("#not-a-heading", problems[0])
|
||||
|
||||
def test_external_url_with_fragment_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](https://example.com/page#nonexistent)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_mailto_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](mailto:foo@example.com#frag)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_protocol_relative_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](//example.com/page#frag)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_bare_hash_skipped(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](#)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_missing_file_still_reported(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](nonexistent.md#foo)\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("broken relative link", problems[0])
|
||||
|
||||
def test_fragment_on_non_markdown_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](image.png#foo)\n",
|
||||
"docs/image.png": None,
|
||||
})
|
||||
# image.png is binary (text returns None) but it exists in the
|
||||
# file list, so the link itself resolves; fragment is not checked.
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
|
||||
class MarkerTests(unittest.TestCase):
|
||||
"""The conflict-marker check must catch all four markers, including the diff3 one."""
|
||||
|
||||
def _markers(self, text):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "f.md").write_text(text, encoding="utf-8")
|
||||
previous = docs_hygiene.ROOT
|
||||
docs_hygiene.ROOT = root
|
||||
try:
|
||||
problems = []
|
||||
docs_hygiene.check_markers({"f.md": text}, problems)
|
||||
return problems
|
||||
finally:
|
||||
docs_hygiene.ROOT = previous
|
||||
|
||||
def test_every_marker_kind_is_reported(self):
|
||||
for line in ["<<<<<<< HEAD", "||||||| merged common ancestors", "=======", ">>>>>>> topic"]:
|
||||
problems = self._markers(line + "\n")
|
||||
self.assertEqual(len(problems), 1, f"{line!r} was not reported: {problems}")
|
||||
self.assertIn("f.md:1", problems[0])
|
||||
|
||||
def test_diff3_base_marker_is_reported(self):
|
||||
base = self._markers("||||||| merged common ancestors\n")
|
||||
self.assertEqual(len(base), 1, "the diff3 base marker must be reported")
|
||||
self.assertIn("conflict marker", base[0])
|
||||
|
||||
def test_a_diff3_block_reports_all_four_lines(self):
|
||||
block = "<<<<<<< HEAD\na\n||||||| merged common ancestors\nb\n=======\nc\n>>>>>>> topic\n"
|
||||
problems = self._markers(block)
|
||||
self.assertEqual(len(problems), 4, problems)
|
||||
|
||||
def test_ordinary_content_is_not_a_marker(self):
|
||||
for text in ["| a | b |\n", "||||||\n", "======\n", "prose with | pipes\n", "---\n"]:
|
||||
self.assertEqual(self._markers(text), [], f"{text!r} was wrongly reported")
|
||||
|
||||
|
||||
class WorkflowTests(unittest.TestCase):
|
||||
"""check_workflows must reject unparseable YAML."""
|
||||
|
||||
def _check(self, text):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / ".github" / "workflows").mkdir(parents=True)
|
||||
(root / ".github" / "workflows" / "a.yml").write_text(text, encoding="utf-8")
|
||||
previous = docs_hygiene.ROOT
|
||||
docs_hygiene.ROOT = root
|
||||
try:
|
||||
problems = []
|
||||
docs_hygiene.check_workflows({".github/workflows/a.yml": text}, problems, require_yaml=True)
|
||||
return problems
|
||||
finally:
|
||||
docs_hygiene.ROOT = previous
|
||||
|
||||
def test_parses_a_valid_workflow(self):
|
||||
self.assertEqual(self._check("on: push\njobs:\n b:\n runs-on: ubuntu-latest\n"), [])
|
||||
|
||||
def test_reports_invalid_yaml(self):
|
||||
problems = self._check("on: [push\n")
|
||||
self.assertEqual(len(problems), 1, problems)
|
||||
self.assertIn("a.yml", problems[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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();
|
||||
|
||||
@@ -80,12 +80,14 @@ fn collect(rx: &Receiver<Event>, until: Instant) -> io::Result<(Vec<u8>, Vec<u8>
|
||||
Ok((stdout, stderr, true))
|
||||
}
|
||||
|
||||
fn wait_until(child: &mut Child, deadline: Instant) -> io::Result<Option<ExitStatus>> {
|
||||
/// `deadline: None` means the requested timeout is not representable on this clock, so the
|
||||
/// probe is allowed to run without one (#587).
|
||||
fn wait_until(child: &mut Child, deadline: Option<Instant>) -> io::Result<Option<ExitStatus>> {
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(Some(status));
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
if deadline.is_some_and(|at| Instant::now() >= at) {
|
||||
child.kill()?;
|
||||
child.wait()?;
|
||||
return Ok(None);
|
||||
@@ -112,7 +114,13 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
|
||||
command.env(key, value);
|
||||
}
|
||||
}
|
||||
let deadline = Instant::now() + timeout;
|
||||
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow, so a
|
||||
// huge value would abort the harness with exit 101 instead of one of its verdict codes
|
||||
// (#586). Saturate at the platform maximum instead: the probe then simply never times out.
|
||||
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow. When the
|
||||
// requested timeout is not representable the probe simply has no deadline; representing
|
||||
// that as `None` avoids inventing a fallback duration that might also not fit (#587).
|
||||
let deadline = Instant::now().checked_add(timeout);
|
||||
let mut child = command.spawn()?;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
pump(
|
||||
@@ -126,8 +134,11 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
|
||||
tx,
|
||||
);
|
||||
let status = wait_until(&mut child, deadline)?;
|
||||
let (stdout, stderr, output_complete) =
|
||||
collect(&rx, deadline.max(Instant::now() + DRAIN_GRACE))?;
|
||||
// With no deadline the probe has already exited, so draining still needs a bound.
|
||||
let drain_until = deadline
|
||||
.unwrap_or_else(Instant::now)
|
||||
.max(Instant::now() + DRAIN_GRACE);
|
||||
let (stdout, stderr, output_complete) = collect(&rx, drain_until)?;
|
||||
Ok(ProbeRun {
|
||||
status,
|
||||
stdout: String::from_utf8_lossy(&stdout).into_owned(),
|
||||
@@ -161,6 +172,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrepresentable_deadline_leaves_the_probe_without_a_timeout() {
|
||||
// `checked_add` returns None for a timeout the clock cannot represent; the runner
|
||||
// must then wait for the probe normally instead of inventing a fallback duration
|
||||
// that could itself overflow (#587).
|
||||
let script = Script::new("nodeadline", "sleep 0.2; exit 0");
|
||||
let run = run_probe(
|
||||
&script.0,
|
||||
std::path::Path::new("/nonexistent/framework"),
|
||||
Duration::from_secs(u64::MAX),
|
||||
)
|
||||
.expect("an unrepresentable deadline must not abort the run");
|
||||
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
|
||||
assert!(run.output_complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overflowing_timeout_does_not_panic() {
|
||||
// u64::MAX seconds overflows `Instant + Duration`; before #586 this panicked.
|
||||
let script = Script::new("overflow", "exit 0");
|
||||
let run = run_probe(
|
||||
&script.0,
|
||||
std::path::Path::new("/nonexistent/framework"),
|
||||
Duration::from_secs(u64::MAX),
|
||||
);
|
||||
let run = run.expect("an overflowing timeout must still run the probe, not panic");
|
||||
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_the_framework_and_only_allowlisted_environment() {
|
||||
let script = Script::new("env", "echo \"args=$*\"; env; echo oops >&2; exit 3");
|
||||
@@ -186,22 +226,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,73 @@
|
||||
# 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`.
|
||||
|
||||
## `FSPX` errors
|
||||
|
||||
A malformed `FSPX` table fails inspection with a `ParseError`; it never panics. Two bounds errors are kept apart (#599):
|
||||
|
||||
- **`FspxLayoutMismatch`:** a descriptor's offset lands inside the 16-byte header or the descriptor table, the region the synthetic layout reserves. The table does not follow BetterXen's clean-room layout. The error carries the section id, the offset and the table length.
|
||||
- **`FspxSectionOutOfBounds`:** a section starts after the table but runs past the end of the payload.
|
||||
|
||||
Both are still errors. Over the C ABI, both are `BX_SHADER_ERR_INVALID_BLOB`, so a caller of `bx_shader_inspect` cannot tell them apart yet; that would need an `[ABI]` change to `abi/include/bx_shader_bridge.h`.
|
||||
|
||||
## 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;
|
||||
}
|
||||
@@ -10,6 +10,13 @@
|
||||
//! A version-1 table holds at most [`FSPX_MAX_SECTIONS`] descriptors. A larger
|
||||
//! count is rejected before any descriptor is compared with another, so
|
||||
//! inspection stays allocation-free and the pairwise check stays bounded.
|
||||
//!
|
||||
//! A descriptor whose offset lands inside the 16-byte header or the
|
||||
//! descriptor table itself is a layout mismatch, reported apart from a
|
||||
//! section that runs past the end of the payload. Read through this layout,
|
||||
//! such a table is not merely truncated or corrupt: its descriptors do not
|
||||
//! mean `(id, offset, size)` relative to the payload as this module assumes.
|
||||
//! It is still an error, and the container is still refused.
|
||||
|
||||
use super::{ShaderStage, read_u32_le};
|
||||
|
||||
@@ -82,9 +89,22 @@ impl FspxInfo {
|
||||
pub(crate) enum FspxError {
|
||||
Truncated,
|
||||
BadVersion(u32),
|
||||
SectionOutOfBounds { section_id: u32 },
|
||||
DuplicateSection { section_id: u32 },
|
||||
Overlap { section_id: u32 },
|
||||
SectionOutOfBounds {
|
||||
section_id: u32,
|
||||
},
|
||||
/// The descriptor's offset lies inside the header plus descriptor table,
|
||||
/// the region this layout reserves, so the table does not follow it.
|
||||
LayoutMismatch {
|
||||
section_id: u32,
|
||||
offset: u32,
|
||||
table_end: u32,
|
||||
},
|
||||
DuplicateSection {
|
||||
section_id: u32,
|
||||
},
|
||||
Overlap {
|
||||
section_id: u32,
|
||||
},
|
||||
BadStageConfig,
|
||||
TooManySections(u32),
|
||||
}
|
||||
@@ -217,6 +237,15 @@ fn walk_sections(
|
||||
) -> Result<(), FspxError> {
|
||||
for index in 0..header.count {
|
||||
let (id, offset, size) = descriptor_at(payload, index)?;
|
||||
if usize::try_from(offset).is_ok_and(|start| start < header.table_end) {
|
||||
// `table_end` is at most 16 + 64 * 12 bytes, so it fits in u32.
|
||||
let table_end = u32::try_from(header.table_end).unwrap_or(u32::MAX);
|
||||
return Err(FspxError::LayoutMismatch {
|
||||
section_id: id,
|
||||
offset,
|
||||
table_end,
|
||||
});
|
||||
}
|
||||
let end = section_end(offset, size, header.table_end, payload.len())
|
||||
.ok_or(FspxError::SectionOutOfBounds { section_id: id })?;
|
||||
for prev in 0..index {
|
||||
|
||||
@@ -9,7 +9,10 @@
|
||||
//! An `ACCC` payload that begins with `FSPX` uses the layout documented on
|
||||
//! [`fspx`]. Version 0 is a magic-only stub. Version 1 is a section table of
|
||||
//! at most [`FSPX_MAX_SECTIONS`] descriptors. A larger count is
|
||||
//! [`ParseError::FspxTooManySections`] before any pairwise comparison.
|
||||
//! [`ParseError::FspxTooManySections`] before any pairwise comparison. A
|
||||
//! descriptor whose offset lands inside the header plus descriptor table is
|
||||
//! [`ParseError::FspxLayoutMismatch`], kept apart from
|
||||
//! [`ParseError::FspxSectionOutOfBounds`] (a section past the payload end).
|
||||
//! Section 0 and section 7 are opaque header ranges, section 1 is the stage
|
||||
//! configuration (`bx_shader_stage_t` values), and section 6 is the RDNA 2
|
||||
//! code byte range. The code bytes are not decoded. This layout is synthetic.
|
||||
@@ -26,13 +29,16 @@
|
||||
//! at least 16. `BitcodeSize` must be non-zero, and `8 + BitcodeOffset +
|
||||
//! BitcodeSize` must fit in `SizeInUint32 * 4`. A zero-length bitcode is
|
||||
//! [`ParseError::BadDxilHeader`], matching DXC's `IsValidDxilProgramHeader`,
|
||||
//! so preparation does not copy it.
|
||||
//! so preparation does not copy it. A bitcode payload starting with `NOBC`
|
||||
//! marks a header-only container (no executable bitcode), which keeps `DXIL`
|
||||
//! size and stage metadata but does not classify as executable `DXIL`.
|
||||
//!
|
||||
//! The C entry points in [`c_abi`] match `abi/include/bx_shader_bridge.h`.
|
||||
//! `bx_shader_inspect` fills the C struct without logging. `bx_shader_prepare_for_d3dmetal`
|
||||
//! copies `container_size` bytes when a `DXIL` chunk is present, including when
|
||||
//! an accompanying `FSPX` table is malformed, and logs only an ACCC-only
|
||||
//! `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation is not implemented.
|
||||
//! copies `container_size` bytes when an executable `DXIL` chunk is present,
|
||||
//! including when an accompanying `FSPX` table is malformed, and logs only an
|
||||
//! ACCC-only `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation
|
||||
//! is not implemented.
|
||||
|
||||
mod c_abi;
|
||||
mod fspx;
|
||||
@@ -94,22 +100,104 @@ pub struct ShaderInspection {
|
||||
pub chunks: Vec<ChunkInfo>,
|
||||
}
|
||||
|
||||
impl ShaderInspection {
|
||||
/// Payload of the first chunk tagged `fourcc`, if present and fully
|
||||
/// inside the container. Returns `None` when absent, when the declared
|
||||
/// size would run past `container_size` or `container`, or when `offset`
|
||||
/// points into the DXBC header or chunk-offset table instead of a chunk
|
||||
/// header.
|
||||
///
|
||||
/// `container` must be the same bytes passed to [`inspect_dxbc`]; the
|
||||
/// inspection only stores chunk metadata, so the original container is
|
||||
/// required to slice out the payload. `ChunkInfo::offset` is relative to
|
||||
/// the start of the `DXBC` container and points at the 8-byte chunk
|
||||
/// header (fourcc + size), so the payload begins at `offset + 8`.
|
||||
///
|
||||
/// A zero-size chunk yields `Some(&[])`: the header is present and
|
||||
/// in-bounds, so an empty payload is a valid result rather than an
|
||||
/// absence. Callers that require a minimum size must check the returned
|
||||
/// slice length.
|
||||
///
|
||||
/// Only the already-parsed `self.chunks` table is consulted; the raw
|
||||
/// chunk table is not re-walked. When several chunks share `fourcc`,
|
||||
/// the first one in table order wins, matching the C++ `find_chunk`.
|
||||
pub fn chunk_payload<'a>(&self, container: &'a [u8], fourcc: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
let chunk = self.chunks.iter().find(|c| &c.fourcc == fourcc)?;
|
||||
let table_bytes = u64::try_from(self.chunks.len()).ok()?.checked_mul(4)?;
|
||||
let table_end = 32u64.checked_add(table_bytes)?;
|
||||
if u64::from(chunk.offset) < table_end {
|
||||
return None;
|
||||
}
|
||||
let start = u64::from(chunk.offset).checked_add(8)?;
|
||||
let end = start.checked_add(u64::from(chunk.size))?;
|
||||
if end > u64::from(self.container_size) {
|
||||
return None;
|
||||
}
|
||||
let start = usize::try_from(start).ok()?;
|
||||
let end = usize::try_from(end).ok()?;
|
||||
if end > container.len() {
|
||||
return None;
|
||||
}
|
||||
container.get(start..end)
|
||||
}
|
||||
|
||||
/// True when a chunk header tagged `fourcc` exists, whatever its
|
||||
/// declared size. Mirrors the C++ `has_chunk_tag`: presence without
|
||||
/// trusting the size.
|
||||
pub fn has_chunk_tag(&self, fourcc: &[u8; 4]) -> bool {
|
||||
self.chunks.iter().any(|c| &c.fourcc == fourcc)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ParseError {
|
||||
TooShort,
|
||||
BadMagic,
|
||||
UnsupportedVersion(u32),
|
||||
TruncatedChunkTable,
|
||||
ChunkOutOfBounds { index: usize },
|
||||
ChunkOutOfBounds {
|
||||
index: usize,
|
||||
},
|
||||
TruncatedContainer,
|
||||
FspxTruncated { chunk: usize },
|
||||
FspxBadVersion { chunk: usize, version: u32 },
|
||||
FspxSectionOutOfBounds { chunk: usize, section_id: u32 },
|
||||
FspxDuplicateSection { chunk: usize, section_id: u32 },
|
||||
FspxSectionOverlap { chunk: usize, section_id: u32 },
|
||||
FspxBadStageConfig { chunk: usize },
|
||||
FspxTooManySections { chunk: usize, count: u32 },
|
||||
BadDxilHeader { chunk: usize },
|
||||
FspxTruncated {
|
||||
chunk: usize,
|
||||
},
|
||||
FspxBadVersion {
|
||||
chunk: usize,
|
||||
version: u32,
|
||||
},
|
||||
FspxSectionOutOfBounds {
|
||||
chunk: usize,
|
||||
section_id: u32,
|
||||
},
|
||||
/// A descriptor's offset lands inside the `FSPX` header plus descriptor
|
||||
/// table (`table_end` bytes), which the synthetic layout reserves. The
|
||||
/// table does not follow BetterXen's clean-room layout; it is not reported
|
||||
/// as an out-of-bounds section. The container is still rejected.
|
||||
FspxLayoutMismatch {
|
||||
chunk: usize,
|
||||
section_id: u32,
|
||||
offset: u32,
|
||||
table_end: u32,
|
||||
},
|
||||
FspxDuplicateSection {
|
||||
chunk: usize,
|
||||
section_id: u32,
|
||||
},
|
||||
FspxSectionOverlap {
|
||||
chunk: usize,
|
||||
section_id: u32,
|
||||
},
|
||||
FspxBadStageConfig {
|
||||
chunk: usize,
|
||||
},
|
||||
FspxTooManySections {
|
||||
chunk: usize,
|
||||
count: u32,
|
||||
},
|
||||
BadDxilHeader {
|
||||
chunk: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for ParseError {
|
||||
@@ -133,6 +221,15 @@ impl fmt::Display for ParseError {
|
||||
"FSPX section {section_id} out of bounds in chunk {chunk}"
|
||||
)
|
||||
}
|
||||
Self::FspxLayoutMismatch {
|
||||
chunk,
|
||||
section_id,
|
||||
offset,
|
||||
table_end,
|
||||
} => write!(
|
||||
f,
|
||||
"FSPX section {section_id} starts at offset {offset}, inside the {table_end}-byte header and section table, in chunk {chunk}: the table does not follow the synthetic FSPX layout"
|
||||
),
|
||||
Self::FspxDuplicateSection { chunk, section_id } => {
|
||||
write!(f, "duplicate FSPX section {section_id} in chunk {chunk}")
|
||||
}
|
||||
@@ -185,6 +282,16 @@ fn fspx_error(chunk: usize, err: fspx::FspxError) -> ParseError {
|
||||
fspx::FspxError::SectionOutOfBounds { section_id } => {
|
||||
ParseError::FspxSectionOutOfBounds { chunk, section_id }
|
||||
}
|
||||
fspx::FspxError::LayoutMismatch {
|
||||
section_id,
|
||||
offset,
|
||||
table_end,
|
||||
} => ParseError::FspxLayoutMismatch {
|
||||
chunk,
|
||||
section_id,
|
||||
offset,
|
||||
table_end,
|
||||
},
|
||||
fspx::FspxError::DuplicateSection { section_id } => {
|
||||
ParseError::FspxDuplicateSection { chunk, section_id }
|
||||
}
|
||||
@@ -209,14 +316,22 @@ fn record_fspx_stage(
|
||||
}
|
||||
}
|
||||
|
||||
enum DxilProgram {
|
||||
Executable((ShaderStage, u8, u8)),
|
||||
HeaderOnly((ShaderStage, u8, u8)),
|
||||
}
|
||||
|
||||
/// `DxilProgramHeader` check from the public DirectXShaderCompiler container.
|
||||
///
|
||||
/// `SizeInUint32 * 4` must cover the 24-byte header and fit in `payload`.
|
||||
/// `BitcodeOffset` is from the start of `DxilBitcodeHeader` at program byte 8
|
||||
/// and must be at least 16. `BitcodeSize` must be non-zero, and
|
||||
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program. The
|
||||
/// bitcode bytes are not decoded.
|
||||
fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
|
||||
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program.
|
||||
///
|
||||
/// A bitcode payload beginning with `NOBC` is a header-only container (for
|
||||
/// example, reflection or signature metadata with bitcode stripped) and is
|
||||
/// reported as [`DxilProgram::HeaderOnly`] rather than executable DXIL.
|
||||
fn read_dxil_program(payload: &[u8]) -> Result<DxilProgram, ()> {
|
||||
const PROGRAM_PREFIX: u64 = 8;
|
||||
const BITCODE_HEADER: u64 = 16;
|
||||
const MIN_PROGRAM: u64 = PROGRAM_PREFIX + BITCODE_HEADER;
|
||||
@@ -245,7 +360,16 @@ fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
|
||||
if end > program_bytes {
|
||||
return Err(());
|
||||
}
|
||||
Ok(program_stage(program_version))
|
||||
let bitcode_start =
|
||||
usize::try_from(PROGRAM_PREFIX + u64::from(bitcode_offset)).map_err(|_| ())?;
|
||||
let bitcode_end = usize::try_from(end).map_err(|_| ())?;
|
||||
let bitcode = payload.get(bitcode_start..bitcode_end).ok_or(())?;
|
||||
let stage = program_stage(program_version);
|
||||
if bitcode.starts_with(b"NOBC") {
|
||||
Ok(DxilProgram::HeaderOnly(stage))
|
||||
} else {
|
||||
Ok(DxilProgram::Executable(stage))
|
||||
}
|
||||
}
|
||||
|
||||
struct ContainerLimit {
|
||||
@@ -352,6 +476,37 @@ fn kind_from_flags(has_dxil: bool, has_accc: bool, has_legacy: bool) -> ShaderKi
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DxilChunkState {
|
||||
has_executable: bool,
|
||||
size: u32,
|
||||
executable_stage: Option<(ShaderStage, u8, u8)>,
|
||||
header_only_stage: Option<(ShaderStage, u8, u8)>,
|
||||
}
|
||||
|
||||
impl DxilChunkState {
|
||||
/// Record a `DXIL` chunk, keeping executable metadata ahead of `NOBC`
|
||||
/// header-only placeholders regardless of chunk order.
|
||||
fn record(&mut self, chunk: usize, size: u32, payload: &[u8]) -> Result<(), ParseError> {
|
||||
match read_dxil_program(payload).map_err(|()| ParseError::BadDxilHeader { chunk })? {
|
||||
DxilProgram::Executable(stage) => {
|
||||
self.has_executable = true;
|
||||
self.size = size;
|
||||
self.executable_stage = Some(stage);
|
||||
}
|
||||
DxilProgram::HeaderOnly(stage) => {
|
||||
if !self.has_executable {
|
||||
self.size = size;
|
||||
}
|
||||
if self.header_only_stage.is_none() {
|
||||
self.header_only_stage = Some(stage);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Scalar fields of a container. Used by `bx_shader_inspect`, which does not
|
||||
/// keep chunk or section lists.
|
||||
pub(crate) struct DxbcSummary {
|
||||
@@ -370,24 +525,16 @@ pub(crate) struct DxbcSummary {
|
||||
///
|
||||
/// A malformed `FSPX` table is still [`Err`], so inspection can report it.
|
||||
pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
|
||||
let mut has_dxil = false;
|
||||
let mut dxil = DxilChunkState::default();
|
||||
let mut has_accc = false;
|
||||
let mut has_legacy = false;
|
||||
let mut has_root_signature = false;
|
||||
let mut dxil_size = 0u32;
|
||||
let mut accc_size = 0u32;
|
||||
let mut dxil_stage = None;
|
||||
let mut legacy_stage = None;
|
||||
let mut fspx_stage = None;
|
||||
let header = visit_chunks(bytes, |index, _offset, fourcc, size, payload| {
|
||||
match &fourcc {
|
||||
b"DXIL" => {
|
||||
let stage = read_dxil_program(payload)
|
||||
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
|
||||
has_dxil = true;
|
||||
dxil_size = size;
|
||||
dxil_stage = Some(stage);
|
||||
}
|
||||
b"DXIL" => dxil.record(index, size, payload)?,
|
||||
b"ACCC" => {
|
||||
has_accc = true;
|
||||
accc_size = size;
|
||||
@@ -408,36 +555,40 @@ pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let (stage, shader_model_major, shader_model_minor) = dxil_stage
|
||||
let (stage, shader_model_major, shader_model_minor) = dxil
|
||||
.executable_stage
|
||||
.or(legacy_stage)
|
||||
.or(fspx_stage)
|
||||
.or(dxil.header_only_stage)
|
||||
.unwrap_or((ShaderStage::Unknown, 0, 0));
|
||||
Ok(DxbcSummary {
|
||||
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
|
||||
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
|
||||
stage,
|
||||
shader_model_major,
|
||||
shader_model_minor,
|
||||
container_size: header.container_size,
|
||||
digest: header.digest,
|
||||
has_root_signature,
|
||||
dxil_size,
|
||||
dxil_size: dxil.size,
|
||||
accc_size,
|
||||
})
|
||||
}
|
||||
|
||||
/// `Ok(Some(container_size))` when the container is structurally valid and
|
||||
/// contains a `DXIL` chunk with a `DxilProgramHeader`. A malformed `FSPX`
|
||||
/// table does not hide that chunk. A `DXIL` fourcc whose payload is not that
|
||||
/// header is [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
|
||||
/// structurally valid and has no `DXIL` chunk.
|
||||
/// contains a `DXIL` chunk with an executable `DxilProgramHeader` (not a
|
||||
/// `NOBC` header-only placeholder). A malformed `FSPX` table does not hide that
|
||||
/// chunk. A `DXIL` fourcc whose payload is not a valid `DxilProgramHeader` is
|
||||
/// [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
|
||||
/// structurally valid and has no executable `DXIL` chunk.
|
||||
pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError> {
|
||||
let mut has_dxil = false;
|
||||
let header = visit_chunks(bytes, |index, _offset, fourcc, _size, payload| {
|
||||
if &fourcc == b"DXIL" {
|
||||
if read_dxil_program(payload).is_err() {
|
||||
return Err(ParseError::BadDxilHeader { chunk: index });
|
||||
match read_dxil_program(payload) {
|
||||
Ok(DxilProgram::Executable(_)) => has_dxil = true,
|
||||
Ok(DxilProgram::HeaderOnly(_)) => {}
|
||||
Err(()) => return Err(ParseError::BadDxilHeader { chunk: index }),
|
||||
}
|
||||
has_dxil = true;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -457,27 +608,19 @@ pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError
|
||||
/// container through.
|
||||
pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
|
||||
let mut chunks = Vec::new();
|
||||
let mut has_dxil = false;
|
||||
let mut dxil = DxilChunkState::default();
|
||||
let mut has_accc = false;
|
||||
let mut has_legacy = false;
|
||||
let mut has_root_signature = false;
|
||||
let mut dxil_size = 0u32;
|
||||
let mut accc_size = 0u32;
|
||||
let mut accc_is_fspx = false;
|
||||
let mut dxil_stage = None;
|
||||
let mut legacy_stage = None;
|
||||
let mut fspx_stage = None;
|
||||
let mut fspx = None;
|
||||
|
||||
let header = visit_chunks(bytes, |index, offset, fourcc, size, payload| {
|
||||
match &fourcc {
|
||||
b"DXIL" => {
|
||||
let stage = read_dxil_program(payload)
|
||||
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
|
||||
has_dxil = true;
|
||||
dxil_size = size;
|
||||
dxil_stage = Some(stage);
|
||||
}
|
||||
b"DXIL" => dxil.record(index, size, payload)?,
|
||||
b"ACCC" => {
|
||||
has_accc = true;
|
||||
accc_size = size;
|
||||
@@ -515,21 +658,22 @@ pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let (stage, sm_major, sm_minor) =
|
||||
dxil_stage
|
||||
.or(legacy_stage)
|
||||
.or(fspx_stage)
|
||||
.unwrap_or((ShaderStage::Unknown, 0, 0));
|
||||
let (stage, sm_major, sm_minor) = dxil
|
||||
.executable_stage
|
||||
.or(legacy_stage)
|
||||
.or(fspx_stage)
|
||||
.or(dxil.header_only_stage)
|
||||
.unwrap_or((ShaderStage::Unknown, 0, 0));
|
||||
|
||||
Ok(ShaderInspection {
|
||||
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
|
||||
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
|
||||
stage,
|
||||
shader_model_major: sm_major,
|
||||
shader_model_minor: sm_minor,
|
||||
container_size: header.container_size,
|
||||
digest: header.digest,
|
||||
has_root_signature,
|
||||
dxil_size,
|
||||
dxil_size: dxil.size,
|
||||
accc_size,
|
||||
accc_is_fspx,
|
||||
fspx,
|
||||
@@ -868,9 +1012,11 @@ mod tests {
|
||||
),
|
||||
(
|
||||
fspx_header(1, 1, &[(1, 0, 4)], 28),
|
||||
ParseError::FspxSectionOutOfBounds {
|
||||
ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 1,
|
||||
offset: 0,
|
||||
table_end: 28,
|
||||
},
|
||||
),
|
||||
(
|
||||
@@ -924,18 +1070,167 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn truncated_prefixes_do_not_panic() {
|
||||
let mut nobc_dxil = minimal_dxil_program((6u32 << 4) | 6u32);
|
||||
nobc_dxil[24..28].copy_from_slice(b"NOBC");
|
||||
let blobs = [
|
||||
synthetic_dxil_blob(),
|
||||
build_synthetic_dxbc(&[(b"DXIL", &nobc_dxil)]),
|
||||
build_synthetic_dxbc(&[(b"ACCC", &synthetic_fspx_payload())]),
|
||||
build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]),
|
||||
vec![0xFF; 64],
|
||||
];
|
||||
for blob in blobs {
|
||||
for len in 0..=blob.len() {
|
||||
let _ = inspect_dxbc(&blob[..len]);
|
||||
let _ = summarize_dxbc(&blob[..len]);
|
||||
let _ = dxil_container_len(&blob[..len]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A two-section table (`table_end` = 16 + 2 * 12 = 40) whose second
|
||||
/// descriptor's offset is `second_offset`. The first descriptor is a valid
|
||||
/// 12-byte stage section at 40, and the payload is 64 bytes long.
|
||||
fn fspx_two_sections(second_offset: u32) -> Vec<u8> {
|
||||
let mut payload = fspx_header(1, 2, &[(1, 40, 12), (6, second_offset, 4)], 64);
|
||||
payload[40..44].copy_from_slice(&6u32.to_le_bytes());
|
||||
payload[44..48].copy_from_slice(&6u32.to_le_bytes());
|
||||
payload
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fspx_offset_inside_header_or_table_is_layout_mismatch() {
|
||||
// Inside the 16-byte header, inside the first descriptor, inside the
|
||||
// descriptor itself, and the last reserved byte.
|
||||
for offset in [0u32, 8, 16, 28, 39] {
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(offset))]);
|
||||
let expected = ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 6,
|
||||
offset,
|
||||
table_end: 40,
|
||||
};
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(expected.clone()),
|
||||
"offset {offset}"
|
||||
);
|
||||
// The C ABI path walks the table through `scan_fspx`, not
|
||||
// `parse_fspx`, and must classify it the same way.
|
||||
assert_eq!(
|
||||
summarize_dxbc(&blob).map(|_| ()),
|
||||
Err(expected),
|
||||
"offset {offset}"
|
||||
);
|
||||
}
|
||||
|
||||
// The first byte after the table is outside the reserved region.
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(56))]);
|
||||
let info = inspect_dxbc(&blob).expect("offset at the end of the stage section");
|
||||
assert_eq!(info.kind, ShaderKind::AcccOnly);
|
||||
assert_eq!(info.stage, ShaderStage::Compute);
|
||||
assert!(summarize_dxbc(&blob).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fspx_layout_mismatch_is_not_out_of_bounds() {
|
||||
// Past the payload end is still out of bounds, not a layout mismatch.
|
||||
let mut payload = fspx_two_sections(62);
|
||||
payload.truncate(64);
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
|
||||
let out_of_bounds = ParseError::FspxSectionOutOfBounds {
|
||||
chunk: 0,
|
||||
section_id: 6,
|
||||
};
|
||||
assert_eq!(inspect_dxbc(&blob), Err(out_of_bounds.clone()));
|
||||
assert_eq!(summarize_dxbc(&blob).map(|_| ()), Err(out_of_bounds));
|
||||
|
||||
// A reserved offset wins even when the size would also overrun.
|
||||
let mut payload = fspx_header(1, 1, &[(6, 20, u32::MAX)], 32);
|
||||
payload.truncate(32);
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 6,
|
||||
offset: 20,
|
||||
table_end: 28,
|
||||
})
|
||||
);
|
||||
|
||||
let message = ParseError::FspxLayoutMismatch {
|
||||
chunk: 2,
|
||||
section_id: 6,
|
||||
offset: 20,
|
||||
table_end: 28,
|
||||
}
|
||||
.to_string();
|
||||
assert!(message.contains("section 6"), "{message}");
|
||||
assert!(message.contains("offset 20"), "{message}");
|
||||
assert!(message.contains("28-byte"), "{message}");
|
||||
assert!(message.contains("chunk 2"), "{message}");
|
||||
assert!(!message.contains("out of bounds"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c_abi_still_refuses_fspx_layout_mismatch() {
|
||||
clear_shader_log();
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]);
|
||||
|
||||
let mut c_info = BxShaderInspection {
|
||||
kind: 99,
|
||||
..BxShaderInspection::default()
|
||||
};
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert_eq!(c_info.kind, 0);
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
assert!(shader_log_lines().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arbitrary_fspx_tables_do_not_panic() {
|
||||
// Deterministic xorshift so a failure reproduces.
|
||||
let mut state = 0x9E37_79B9_7F4A_7C15u64;
|
||||
let mut next = || {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
state
|
||||
};
|
||||
for round in 0..4096u32 {
|
||||
let len = 16 + (next() % 240) as usize;
|
||||
let mut payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
|
||||
payload[..4].copy_from_slice(b"FSPX");
|
||||
payload[4..8].copy_from_slice(&1u32.to_le_bytes());
|
||||
let count = round % (FSPX_MAX_SECTIONS as u32 + 2);
|
||||
payload[8..12].copy_from_slice(&count.to_le_bytes());
|
||||
// Keep some offsets small so the reserved-region branch is hit.
|
||||
if round % 2 == 0 {
|
||||
let mut at = 20;
|
||||
while at + 4 <= len.min(16 + count as usize * 12) {
|
||||
let small = (next() % 64) as u32;
|
||||
payload[at..at + 4].copy_from_slice(&small.to_le_bytes());
|
||||
at += 12;
|
||||
}
|
||||
}
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
|
||||
let _ = inspect_dxbc(&blob);
|
||||
let _ = summarize_dxbc(&blob);
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
let _ = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c_abi_inspect_and_passthrough_round_trip() {
|
||||
clear_shader_log();
|
||||
@@ -1268,6 +1563,245 @@ mod tests {
|
||||
assert!(log[0].contains("sm_minor=0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_is_not_classified_as_executable_dxil() {
|
||||
clear_shader_log();
|
||||
// Pixel shader (0), SM 6.6, with the four-byte NOBC placeholder instead of LLVM bitcode.
|
||||
let mut payload = minimal_dxil_program((6u32 << 4) | 6u32);
|
||||
payload[24..28].copy_from_slice(b"NOBC");
|
||||
let blob = build_synthetic_dxbc(&[(b"RTS0", &[1, 2, 3, 4]), (b"DXIL", &payload)]);
|
||||
|
||||
let info = inspect_dxbc(&blob).expect("valid DXBC with NOBC header-only DXIL");
|
||||
assert_eq!(info.kind, ShaderKind::Unknown);
|
||||
assert_eq!(info.stage, ShaderStage::Pixel);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 6));
|
||||
assert_eq!(info.dxil_size, 28);
|
||||
assert!(info.has_root_signature);
|
||||
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
assert_eq!(c_info.kind, 0); // BX_SHADER_UNKNOWN
|
||||
assert_eq!(c_info.stage, 1); // BX_STAGE_PIXEL
|
||||
assert_eq!(c_info.shader_model_major, 6);
|
||||
assert_eq!(c_info.shader_model_minor, 6);
|
||||
assert_eq!(c_info.dxil_chunk_size, 28);
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
assert!(shader_log_lines().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_with_accc_is_classified_as_accc_only_and_rejected() {
|
||||
clear_shader_log();
|
||||
let mut dxil = minimal_dxil_program((1u32 << 16) | (6u32 << 4) | 6u32);
|
||||
dxil[24..28].copy_from_slice(b"NOBC");
|
||||
let fspx = fspx_compute_stage();
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &dxil), (b"ACCC", &fspx)]);
|
||||
|
||||
let info = inspect_dxbc(&blob).expect("NOBC + ACCC container");
|
||||
assert_eq!(info.kind, ShaderKind::AcccOnly);
|
||||
assert_eq!(info.stage, ShaderStage::Compute);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 0));
|
||||
assert_eq!(info.dxil_size, 28);
|
||||
assert_eq!(info.accc_size, 40);
|
||||
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
assert_eq!(c_info.kind, 3); // BX_SHADER_DXBC_ACCC
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
let log = shader_log_lines();
|
||||
assert_eq!(log.len(), 1);
|
||||
assert!(log[0].contains("kind=accc_only(3)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_with_padded_bitcode_is_still_header_only() {
|
||||
let mut payload = vec![0u8; 32];
|
||||
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
|
||||
payload[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
payload[4..8].copy_from_slice(&8u32.to_le_bytes());
|
||||
payload[8..12].copy_from_slice(b"DXIL");
|
||||
payload[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
payload[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
payload[20..24].copy_from_slice(&8u32.to_le_bytes());
|
||||
payload[24..28].copy_from_slice(b"NOBC");
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &payload)]);
|
||||
|
||||
let info = inspect_dxbc(&blob).expect("padded NOBC DXIL");
|
||||
assert_eq!(info.kind, ShaderKind::Unknown);
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_executable_and_nobc_dxil_preserves_executable_metadata() {
|
||||
let exec = minimal_dxil_program((5u32 << 16) | (6u32 << 4) | 5u32);
|
||||
let mut nobc = vec![0u8; 32];
|
||||
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
|
||||
nobc[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
nobc[4..8].copy_from_slice(&8u32.to_le_bytes());
|
||||
nobc[8..12].copy_from_slice(b"DXIL");
|
||||
nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
nobc[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
nobc[20..24].copy_from_slice(&8u32.to_le_bytes());
|
||||
nobc[24..28].copy_from_slice(b"NOBC");
|
||||
|
||||
// Executable first, NOBC second: executable stage and size must win.
|
||||
let blob_exec_first = build_synthetic_dxbc(&[(b"DXIL", &exec), (b"DXIL", &nobc)]);
|
||||
let info = inspect_dxbc(&blob_exec_first).expect("mixed DXIL");
|
||||
assert_eq!(info.kind, ShaderKind::Dxil);
|
||||
assert_eq!(info.stage, ShaderStage::Compute);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 5));
|
||||
assert_eq!(info.dxil_size, 28);
|
||||
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
bx_shader_inspect(blob_exec_first.as_ptr(), blob_exec_first.len(), &mut c_info)
|
||||
},
|
||||
BX_SHADER_OK
|
||||
);
|
||||
assert_eq!(c_info.kind, 1); // BX_SHADER_DXBC_DXIL
|
||||
assert_eq!(c_info.stage, 6); // BX_STAGE_COMPUTE
|
||||
assert_eq!(c_info.dxil_chunk_size, 28);
|
||||
assert_eq!(
|
||||
dxil_container_len(&blob_exec_first),
|
||||
Ok(Some(blob_exec_first.len() as u32))
|
||||
);
|
||||
|
||||
// NOBC first, executable second: executable must still win.
|
||||
let blob_nobc_first = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"DXIL", &exec)]);
|
||||
let info2 = inspect_dxbc(&blob_nobc_first).expect("mixed DXIL reversed");
|
||||
assert_eq!(info2.kind, ShaderKind::Dxil);
|
||||
assert_eq!(info2.stage, ShaderStage::Compute);
|
||||
assert_eq!((info2.shader_model_major, info2.shader_model_minor), (6, 5));
|
||||
assert_eq!(info2.dxil_size, 28);
|
||||
let summary2 = summarize_dxbc(&blob_nobc_first).expect("mixed DXIL summary");
|
||||
assert_eq!(summary2.kind, ShaderKind::Dxil);
|
||||
assert_eq!(summary2.stage, ShaderStage::Compute);
|
||||
assert_eq!(summary2.dxil_size, 28);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_with_malformed_fspx_returns_invalid_blob() {
|
||||
clear_shader_log();
|
||||
let mut nobc = minimal_dxil_program((6u32 << 4) | 6u32);
|
||||
nobc[24..28].copy_from_slice(b"NOBC");
|
||||
let bad_fspx = fspx_header(99, 0, &[], 16);
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"ACCC", &bad_fspx)]);
|
||||
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::FspxBadVersion {
|
||||
chunk: 1,
|
||||
version: 99,
|
||||
})
|
||||
);
|
||||
assert_eq!(dxil_container_len(&blob), Ok(None));
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
assert!(shader_log_lines().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dxil_bitcode_bounds_and_offset_checks() {
|
||||
let prog = (5u32 << 16) | (6u32 << 4) | 6u32;
|
||||
|
||||
// Bitcode shorter than 4 bytes (`NOB`) must not misclassify as `NOBC` or read out of bounds.
|
||||
let mut short_bitcode = [0u8; 28];
|
||||
short_bitcode[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
short_bitcode[4..8].copy_from_slice(&7u32.to_le_bytes());
|
||||
short_bitcode[8..12].copy_from_slice(b"DXIL");
|
||||
short_bitcode[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
short_bitcode[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
short_bitcode[20..24].copy_from_slice(&3u32.to_le_bytes());
|
||||
short_bitcode[24..27].copy_from_slice(b"NOB");
|
||||
let blob_short = build_synthetic_dxbc(&[(b"DXIL", &short_bitcode)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob_short).expect("3-byte bitcode").kind,
|
||||
ShaderKind::Dxil
|
||||
);
|
||||
|
||||
// `NOBC` check follows `BitcodeOffset`, not a fixed offset 24.
|
||||
let mut shifted_nobc = vec![0u8; 36];
|
||||
shifted_nobc[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
shifted_nobc[4..8].copy_from_slice(&9u32.to_le_bytes());
|
||||
shifted_nobc[8..12].copy_from_slice(b"DXIL");
|
||||
shifted_nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
shifted_nobc[16..20].copy_from_slice(&24u32.to_le_bytes());
|
||||
shifted_nobc[20..24].copy_from_slice(&4u32.to_le_bytes());
|
||||
shifted_nobc[32..36].copy_from_slice(b"NOBC");
|
||||
let blob_shifted_nobc = build_synthetic_dxbc(&[(b"DXIL", &shifted_nobc)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob_shifted_nobc).expect("shifted NOBC").kind,
|
||||
ShaderKind::Unknown
|
||||
);
|
||||
assert_eq!(dxil_container_len(&blob_shifted_nobc), Ok(None));
|
||||
|
||||
// Bytes before `BitcodeOffset` containing `NOBC` do not make executable bitcode header-only.
|
||||
let mut shifted_exec = shifted_nobc;
|
||||
shifted_exec[24..28].copy_from_slice(b"NOBC");
|
||||
shifted_exec[32..36].copy_from_slice(&[0xD1, 0x11, 0xC0, 0xDE]);
|
||||
let blob_shifted_exec = build_synthetic_dxbc(&[(b"DXIL", &shifted_exec)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob_shifted_exec)
|
||||
.expect("shifted executable")
|
||||
.kind,
|
||||
ShaderKind::Dxil
|
||||
);
|
||||
|
||||
// Overflowing bitcode offset / size must reject cleanly as `BadDxilHeader`.
|
||||
for (bitcode_off, bitcode_sz) in [(16u32, u32::MAX), (u32::MAX - 4, 4u32)] {
|
||||
let mut overflow = minimal_dxil_program(prog);
|
||||
overflow[16..20].copy_from_slice(&bitcode_off.to_le_bytes());
|
||||
overflow[20..24].copy_from_slice(&bitcode_sz.to_le_bytes());
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &overflow)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::BadDxilHeader { chunk: 0 })
|
||||
);
|
||||
assert_eq!(
|
||||
summarize_dxbc(&blob).map(|_| ()),
|
||||
Err(ParseError::BadDxilHeader { chunk: 0 })
|
||||
);
|
||||
assert_eq!(
|
||||
dxil_container_len(&blob),
|
||||
Err(ParseError::BadDxilHeader { chunk: 0 })
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn fspx_table_with_sections(count: u32) -> Vec<u8> {
|
||||
let count_usize = count as usize;
|
||||
let table_end = 16 + count_usize * 12;
|
||||
@@ -1302,4 +1836,99 @@ mod tests {
|
||||
fn ptr_sentinel() -> *mut u8 {
|
||||
std::ptr::dangling_mut()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_returns_sfi0_and_psv0_bytes() {
|
||||
let sfi0: [u8; 8] = [0x00, 0x40, 0, 0, 0, 0, 0, 0];
|
||||
let psv0: [u8; 28] = [
|
||||
24, 0, 0, 0, // info_size = 24
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, // lanes_min
|
||||
64, 0, 0, 0, // lanes_max
|
||||
];
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &sfi0), (b"PSV0", &psv0)]);
|
||||
let info = inspect_dxbc(&blob).expect("valid container");
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(sfi0.as_slice()));
|
||||
assert_eq!(info.chunk_payload(&blob, b"PSV0"), Some(psv0.as_slice()));
|
||||
assert!(info.has_chunk_tag(b"SFI0"));
|
||||
assert!(info.has_chunk_tag(b"PSV0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_rejects_declared_size_past_container() {
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4])]);
|
||||
let mut info = inspect_dxbc(&blob).expect("valid container");
|
||||
|
||||
// A declared size that runs past container_size must yield None, not
|
||||
// a panic and not a slice clipped to the container.
|
||||
info.chunks[0].size = u32::MAX;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
// Presence without trusting the size still holds.
|
||||
assert!(info.has_chunk_tag(b"SFI0"));
|
||||
|
||||
// A forged public ChunkInfo must not treat the DXBC header or offset
|
||||
// table as a chunk header.
|
||||
info.chunks[0].size = 4;
|
||||
info.chunks[0].offset = 0;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
|
||||
// A header offset past the container must also yield None.
|
||||
info.chunks[0].offset = u32::MAX;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
|
||||
// A chunk header that would end exactly one byte past the container.
|
||||
info.chunks[0].offset = info.container_size - 7;
|
||||
info.chunks[0].size = 0;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_absent_fourcc() {
|
||||
let blob = synthetic_dxil_blob();
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
assert!(!info.has_chunk_tag(b"SFI0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_zero_size_returns_empty_slice() {
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &[])]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
assert!(info.has_chunk_tag(b"SFI0"));
|
||||
let payload = info.chunk_payload(&blob, b"SFI0");
|
||||
assert_eq!(payload, Some(&[][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_exact_fit_at_container_end() {
|
||||
let payload = [0xAA, 0xBB, 0xCC, 0xDD];
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &payload)]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
// The chunk is the last thing in the container; payload ends exactly
|
||||
// at container_size.
|
||||
let chunk = &info.chunks[0];
|
||||
assert_eq!(
|
||||
u64::from(chunk.offset) + 8 + u64::from(chunk.size),
|
||||
u64::from(info.container_size)
|
||||
);
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(payload.as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_truncated_container_slice() {
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4, 5, 6, 7, 8])]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
// Pass a slice shorter than container_size.
|
||||
let short = &blob[..blob.len() - 4];
|
||||
assert_eq!(info.chunk_payload(short, b"SFI0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_first_duplicate_wins() {
|
||||
let first = [0x11, 0x22];
|
||||
let second = [0x33, 0x44, 0x55];
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &first), (b"SFI0", &second)]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
assert_eq!(info.chunks.len(), 2);
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(first.as_slice()));
|
||||
}
|
||||
}
|
||||
+106
-16
@@ -1,29 +1,52 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
namespace {
|
||||
class AcpHal final : public IUnknown {
|
||||
LONG refs = 1;
|
||||
// IAcpHal (authorized GDK documentation; slot order derived from it): not a COM interface. Its
|
||||
// six methods are Connect(numCommands, numMessages), Disconnect(), SubmitCommand(command,
|
||||
// commandId, audioFrame, data, notification), PopMessage(ACP_MESSAGE*), GetNumMessages() and
|
||||
// Release(). BetterXen has no audio control processor: commands are accepted and logged once,
|
||||
// and no message ever arrives.
|
||||
class AcpHal {
|
||||
UINT32 commands_ = 0, messages_ = 0;
|
||||
bool connected_ = false;
|
||||
public:
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid != IID_IUnknown) return E_NOINTERFACE;
|
||||
AddRef();
|
||||
*out = this;
|
||||
virtual HRESULT WINAPI Connect(UINT32 num_commands, UINT32 num_messages) {
|
||||
if (connected_) return HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);
|
||||
commands_ = num_commands;
|
||||
messages_ = num_messages;
|
||||
connected_ = true;
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "commands=%u messages=%u (no ACP processing)", num_commands, num_messages);
|
||||
bx_log_emit(BX_LOG_INFO, "acphal", "connect", detail);
|
||||
return S_OK;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
|
||||
ULONG WINAPI Release() override {
|
||||
ULONG left = InterlockedDecrement(&refs);
|
||||
if (!left) delete this;
|
||||
return left;
|
||||
virtual HRESULT WINAPI Disconnect() {
|
||||
connected_ = false;
|
||||
return S_OK;
|
||||
}
|
||||
virtual HRESULT WINAPI SubmitCommand(UINT32 command, UINT64, UINT32, const void*, UINT32) {
|
||||
if (!connected_) return E_UNEXPECTED;
|
||||
static LONG logged = 0;
|
||||
if (InterlockedIncrement(&logged) == 1) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "first command type %u accepted; ACP commands are not processed", command);
|
||||
bx_log_emit(BX_LOG_WARN, "acphal", "submit_command", detail);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
virtual bool WINAPI PopMessage(void*) { return false; }
|
||||
virtual UINT32 WINAPI GetNumMessages() { return 0; }
|
||||
virtual void WINAPI Release() { delete this; }
|
||||
virtual ~AcpHal() = default;
|
||||
};
|
||||
|
||||
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
|
||||
@@ -47,19 +70,86 @@ HRESULT WINAPI AcpHalCreate(void** out) {
|
||||
return *out ? S_OK : E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void*) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
|
||||
HRESULT WINAPI ApuAlloc(void** va, uint32_t* apu, uint32_t size, uint32_t alignment);
|
||||
HRESULT WINAPI ApuFree(void* va);
|
||||
|
||||
// AcpHalAllocateShapeContexts(SHAPE_CONTEXTS*) / AcpHalReleaseShapeContexts() (authorized GDK
|
||||
// documentation; layout and element sizes derived from it, no header text): the caller fills six
|
||||
// counts, the call allocates each array from the APU heap and returns its CPU pointer and APU
|
||||
// address. Allocating twice without a release fails with ACP_E_ALREADY_ALLOCATED.
|
||||
struct ShapeContexts {
|
||||
uint32_t counts[6]; // SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM
|
||||
void* arrays[6]; // CPU pointers, same order
|
||||
uint32_t apu[6]; // APU addresses, same order
|
||||
};
|
||||
static_assert(sizeof(ShapeContexts) == 96, "SHAPE_CONTEXTS is 96 bytes");
|
||||
static_assert(offsetof(ShapeContexts, arrays) == 24 && offsetof(ShapeContexts, apu) == 72, "SHAPE_CONTEXTS layout");
|
||||
constexpr uint32_t kShapeElementBytes[6] = {32, 160, 32, 16, 64, 32};
|
||||
constexpr HRESULT kAcpAlreadyAllocated = static_cast<HRESULT>(0x8AC80001);
|
||||
constexpr uint32_t kDefaultApuHeapBytes = 64u << 20;
|
||||
|
||||
void* shape_arrays[6];
|
||||
bool shape_allocated = false;
|
||||
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void* argument) {
|
||||
auto* contexts = static_cast<ShapeContexts*>(argument);
|
||||
if (!contexts) return E_INVALIDARG;
|
||||
if (shape_allocated) return kAcpAlreadyAllocated;
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
if (contexts->counts[i] > (0xFFFFFFFFu / kShapeElementBytes[i])) return E_INVALIDARG;
|
||||
}
|
||||
{
|
||||
// The console has a default non-cached APU heap; create one when the title made none.
|
||||
std::lock_guard guard(heap_lock);
|
||||
if (!heap_created) {
|
||||
capacity = kDefaultApuHeapBytes;
|
||||
used = 0;
|
||||
heap_created = true;
|
||||
bx_log_emit(BX_LOG_INFO, "acphal", "apu_default_heap", "no ApuCreateHeap before shape contexts: 64 MB default heap");
|
||||
}
|
||||
}
|
||||
void* arrays[6] = {};
|
||||
uint32_t apu[6] = {};
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
if (!contexts->counts[i]) continue;
|
||||
const uint32_t bytes = contexts->counts[i] * kShapeElementBytes[i];
|
||||
const HRESULT hr = ApuAlloc(&arrays[i], &apu[i], bytes, 64);
|
||||
if (FAILED(hr)) {
|
||||
for (int j = 0; j < i; ++j) ApuFree(arrays[j]);
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
std::memset(arrays[i], 0, bytes);
|
||||
}
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
contexts->arrays[i] = arrays[i];
|
||||
contexts->apu[i] = apu[i];
|
||||
shape_arrays[i] = arrays[i];
|
||||
}
|
||||
shape_allocated = true;
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "src=%u eqcomp=%u filtvol=%u dma=%u xma=%u pcm=%u", contexts->counts[0],
|
||||
contexts->counts[1], contexts->counts[2], contexts->counts[3], contexts->counts[4], contexts->counts[5]);
|
||||
bx_log_emit(BX_LOG_INFO, "acphal", "shape_contexts_allocated", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalReleaseShapeContexts");
|
||||
if (!shape_allocated) return S_OK;
|
||||
for (void*& array : shape_arrays) {
|
||||
ApuFree(array);
|
||||
array = nullptr;
|
||||
}
|
||||
shape_allocated = false;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
|
||||
std::lock_guard guard(heap_lock);
|
||||
if (allocations) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
// A zero-capacity heap must not report S_OK: it can never satisfy an
|
||||
// allocation, so creating it is a caller error (#580). ApuAlloc already
|
||||
// refused such requests with E_OUTOFMEMORY.
|
||||
if (uint64_t(cached) + non_cached == 0) return E_INVALIDARG;
|
||||
// Invariant: allocations == nullptr implies used == 0; reset explicitly.
|
||||
used = 0;
|
||||
capacity = uint64_t(cached) + non_cached;
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
|
||||
d3d12_xs.cpp
|
||||
vmem.cpp
|
||||
presentx.cpp
|
||||
proxy.cpp
|
||||
proxy_generated.cpp
|
||||
shader_gate.cpp
|
||||
xbox_facade.cpp
|
||||
frame_pacing.cpp
|
||||
placed_x.cpp
|
||||
descriptor_heaps.cpp
|
||||
committed.cpp
|
||||
pipelines.cpp
|
||||
gpu_writes.cpp
|
||||
fences.cpp
|
||||
presentx_xbox.cpp
|
||||
page_mappings.cpp
|
||||
xbox_tables_generated.cpp
|
||||
)
|
||||
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32)
|
||||
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32 user32 dxguid)
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* Committed resources with title-visible memory (ADR 0009).
|
||||
*
|
||||
* On the console the D3D12 runtime allocates a committed resource's memory through XMemAlloc
|
||||
* with AllocatorId eXALLOCAllocatorId_D3D (128) and ObjectType Resource (4) (authorized GDK
|
||||
* documentation, "Direct3D 12 XMemAlloc object types"). Titles hook XMemAlloc to place that
|
||||
* memory themselves, and some check afterwards how much of their own pool those requests used.
|
||||
*
|
||||
* Here the host committed resource holds the contents. The resource also gets the same
|
||||
* XMemAlloc request, and its GPU virtual address is the address that request returned, so title
|
||||
* hooks and title address checks see what they would see on the console. The page size the
|
||||
* console runtime requests is not documented: this layer asks for 2 MB pages for allocations of
|
||||
* at least 2 MB and 64 KB pages otherwise (measured against one title; logged per resource).
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
extern "C" __declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr ULONGLONG kObjectTypeResource = 4;
|
||||
constexpr ULONGLONG kAllocatorIdD3D = 128ull << 16; // XALLOC_ATTRIBUTES.AllocatorId, bits 16-23
|
||||
constexpr ULONGLONG kPageSize64K = 1ull << 14; // XALLOC_ATTRIBUTES.PageSize, bits 14-15
|
||||
constexpr ULONGLONG kPageSize2M = 2ull << 14;
|
||||
constexpr UINT64 k2M = 2ull << 20;
|
||||
|
||||
HRESULT finish(ID3D12Device* device, HRESULT hr, REFIID riid, void** ppv, const char* method) {
|
||||
if (FAILED(hr) || !ppv || !*ppv) return hr;
|
||||
// *ppv is the host resource as `riid`; every ID3D12Resource* interface pointer is the object.
|
||||
auto* resource = static_cast<ID3D12Resource*>(*ppv);
|
||||
const D3D12_RESOURCE_DESC desc = resource->GetDesc();
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, &desc);
|
||||
const UINT64 size = info.SizeInBytes ? info.SizeInBytes : desc.Width;
|
||||
const ULONGLONG attributes = kObjectTypeResource | kAllocatorIdD3D | (size >= k2M ? kPageSize2M : kPageSize64K);
|
||||
void* title = XMemAlloc(static_cast<SIZE_T>(size), attributes);
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "%s dim=%d size=%llu page=%s title_va=%p", method,
|
||||
static_cast<int>(desc.Dimension), static_cast<unsigned long long>(size),
|
||||
size >= k2M ? "2MB" : "64KB", title);
|
||||
bx_log_emit(title ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "committed_title_memory", detail);
|
||||
if (!title || !bx_xbox_title_memory_attach(resource, reinterpret_cast<uint64_t>(title), size, attributes)) {
|
||||
resource->Release();
|
||||
*ppv = nullptr;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource");
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
return finish(device, device->CreateCommittedResource(heap, flags, desc, state, clear, riid, ppv), riid, ppv,
|
||||
"CreateCommittedResource");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource1");
|
||||
auto* device = bx_xbox_host<ID3D12Device4>(self);
|
||||
return finish(device, device->CreateCommittedResource1(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
|
||||
riid, ppv, "CreateCommittedResource1");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource2");
|
||||
auto* device = bx_xbox_host<ID3D12Device8>(self);
|
||||
return finish(device, device->CreateCommittedResource2(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
|
||||
riid, ppv, "CreateCommittedResource2");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
|
||||
D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, UINT32 formats,
|
||||
DXGI_FORMAT* castable, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource3");
|
||||
auto* device = bx_xbox_host<ID3D12Device10>(self);
|
||||
return finish(device,
|
||||
device->CreateCommittedResource3(heap, flags, desc, layout, clear, bx_xbox_unwrap_as(session), formats,
|
||||
castable, riid, ppv),
|
||||
riid, ppv, "CreateCommittedResource3");
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
+122
-25
@@ -1,8 +1,11 @@
|
||||
#include "proxy.h"
|
||||
#include "vmem.h"
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
|
||||
#include "bx_xmem_internal.h"
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
|
||||
/*
|
||||
* Track C (M1-C1, #414): Xbox Series D3D12 entry points over the host's d3d12.dll
|
||||
@@ -20,9 +23,44 @@ 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;
|
||||
// A failed host serialization is the title's error to handle, but it is logged with the host's
|
||||
// message and the shape of the description so the rejected feature can be found.
|
||||
void log_serialize_failure(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, HRESULT hr, ID3DBlob* errors) {
|
||||
static std::atomic<uint32_t> logged{0};
|
||||
if (logged.fetch_add(1) >= 32) return;
|
||||
char shape[160] = "desc=null";
|
||||
if (desc && desc->Version == D3D_ROOT_SIGNATURE_VERSION_1_1) {
|
||||
const auto& d = desc->Desc_1_1;
|
||||
std::snprintf(shape, sizeof(shape), "version=1.1 params=%u samplers=%u flags=0x%x", d.NumParameters,
|
||||
d.NumStaticSamplers, static_cast<unsigned>(d.Flags));
|
||||
} else if (desc && desc->Version == D3D_ROOT_SIGNATURE_VERSION_1_0) {
|
||||
const auto& d = desc->Desc_1_0;
|
||||
std::snprintf(shape, sizeof(shape), "version=1.0 params=%u samplers=%u flags=0x%x", d.NumParameters,
|
||||
d.NumStaticSamplers, static_cast<unsigned>(d.Flags));
|
||||
} else if (desc) {
|
||||
std::snprintf(shape, sizeof(shape), "version=%u", static_cast<unsigned>(desc->Version));
|
||||
}
|
||||
char message[160] = "";
|
||||
if (errors && errors->GetBufferPointer() && errors->GetBufferSize()) {
|
||||
const size_t n = errors->GetBufferSize() < sizeof(message) - 1 ? errors->GetBufferSize() : sizeof(message) - 1;
|
||||
std::memcpy(message, errors->GetBufferPointer(), n);
|
||||
message[n] = '\0';
|
||||
for (char& ch : message) {
|
||||
if (ch == '"' || ch == '\\' || static_cast<unsigned char>(ch) < 0x20) ch = ' ';
|
||||
}
|
||||
}
|
||||
char detail[384];
|
||||
std::snprintf(detail, sizeof(detail), "hr=0x%08lx %s host_error=%s", static_cast<unsigned long>(hr), shape,
|
||||
message[0] ? message : "(none)");
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "root_signature_serialize_failed", detail);
|
||||
}
|
||||
|
||||
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
|
||||
@@ -30,17 +68,29 @@ void refresh_trace_flag() {
|
||||
extern "C" {
|
||||
|
||||
/*
|
||||
* `params` is the console creation-parameter block. Its layout is not defined in abi/ and is not
|
||||
* interpreted here: the host device is created on the default adapter at the lowest feature level
|
||||
* D3D12 accepts, and that fact is logged. `riid` must name an interface the proxy models (or one
|
||||
* the host device answers); anything else fails with E_NOINTERFACE and a logged IID.
|
||||
* The documented four-parameter form (authorized GDK documentation, d3d12_x.h / d3d12_xs.h):
|
||||
* an optional adapter, a required D3D12XBOX_CREATE_DEVICE_PARAMETERS block, the interface ID and
|
||||
* the device out pointer. A NULL parameter block fails with E_INVALIDARG, as documented.
|
||||
*
|
||||
* BetterXen has no adapter objects, so a non-NULL adapter is logged and the default host adapter
|
||||
* is used (an inference, not a documented fallback). Of the parameter block only `Version`, its
|
||||
* first UINT, is read and logged; the other fields are not interpreted. The host device is
|
||||
* created at the lowest feature level D3D12 accepts. `riid` must name an interface the proxy
|
||||
* models (or one the host device answers); anything else fails with E_NOINTERFACE and a logged
|
||||
* IID.
|
||||
*/
|
||||
HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
refresh_trace_flag();
|
||||
initialize_trace_flag();
|
||||
if (!params) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "D3D12XboxCreateDevice", "refused: NULL parameter block (E_INVALIDARG)");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
UINT version = 0;
|
||||
std::memcpy(&version, params, sizeof(version));
|
||||
|
||||
using CreateFn = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
|
||||
HMODULE d3d12 = get_host_d3d12();
|
||||
@@ -53,12 +103,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 +128,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,21 +143,47 @@ 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_version=%u "
|
||||
"(other fields not interpreted) adapter=%s trace_d3d=%u",
|
||||
static_cast<void*>(proxy->h_ID3D12Device), highest, version,
|
||||
adapter ? "non-null (ignored, default host adapter)" : "default", g_bx_trace_d3d);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "D3D12XboxCreateDevice", detail);
|
||||
|
||||
/*
|
||||
* ADR 0009: a title built against the Xbox header calls through Xbox-order function tables,
|
||||
* so it gets an Xbox-layout device over the PC proxy. The documentation requires titles to
|
||||
* set Version (D3D12_SDK_VERSION); BetterXen's synthetic fixtures, which are PC-layout
|
||||
* clients built against <d3d12.h>, pass a zeroed block and keep the PC proxy.
|
||||
*/
|
||||
if (version != 0 && bx_xbox_iface_for(riid) == &bx_xbox_Device) {
|
||||
void* pc = nullptr;
|
||||
hr = proxy->QueryInterface(riid, &pc);
|
||||
proxy->Release();
|
||||
if (FAILED(hr) || !pc) return FAILED(hr) ? hr : E_NOINTERFACE;
|
||||
// The wrap fails (E_NOINTERFACE, logged) when the host device lacks the interface the Xbox
|
||||
// table forwards to: a title must not get a PC-layout device reported as an Xbox one.
|
||||
HRESULT failure = E_OUTOFMEMORY;
|
||||
*ppv = bx_xbox_wrap(riid, pc, &failure);
|
||||
bx_log_emit(*ppv ? BX_LOG_INFO : BX_LOG_ERROR, "d3d12_xs", "xbox_layout",
|
||||
*ppv ? "device=xbox_function_tables"
|
||||
: "device=refused: the host device lacks the interface the Xbox device table forwards to "
|
||||
"(the D3DMetal backend provides it)");
|
||||
return *ppv ? S_OK : failure;
|
||||
}
|
||||
hr = proxy->QueryInterface(riid, ppv);
|
||||
proxy->Release();
|
||||
if (SUCCEEDED(hr)) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "xbox_layout",
|
||||
version == 0 ? "device=pc_layout (params Version 0: synthetic PC-layout client)"
|
||||
: "device=pc_layout (interface has no Xbox table)");
|
||||
}
|
||||
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(
|
||||
@@ -105,7 +197,12 @@ HRESULT WINAPI D3D12SerializeVersionedRootSignature(
|
||||
auto fn = reinterpret_cast<Fn>(reinterpret_cast<void*>(
|
||||
GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")));
|
||||
if (fn) {
|
||||
return fn(desc, blob, error_blob);
|
||||
ID3DBlob* local_error = nullptr;
|
||||
ID3DBlob** errors = error_blob ? error_blob : &local_error;
|
||||
const HRESULT hr = fn(desc, blob, errors);
|
||||
if (FAILED(hr)) log_serialize_failure(desc, hr, *errors);
|
||||
if (local_error) local_error->Release();
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12SerializeVersionedRootSignature");
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
/*
|
||||
* Descriptor heaps at title-visible addresses (ADR 0009).
|
||||
*
|
||||
* On the console a descriptor handle is an address: the runtime allocates a heap's storage as a
|
||||
* GPU allocation through XMemAlloc (object type Resource, allocator D3D), so a title's allocation
|
||||
* hooks can place it in the title's own memory, and handles are base + index * descriptor size,
|
||||
* with the console's sizes (32 bytes CBV/SRV/UAV, 16 sampler, 112 RTV, 128 DSV).
|
||||
*
|
||||
* Here each heap has that title-visible storage (allocated the same way, so the title's hooks
|
||||
* see the same request) and a host D3D12 heap. Title handles are translated to host handles by
|
||||
* index. The storage is not interpreted: descriptors a title writes there inline (titles built
|
||||
* with D3DCOMPILE_NO_DEBUG) are not translated, and ID3D12Device's m_OutOfLineFlags keeps the
|
||||
* other titles' descriptor writes on the out-of-line path, which reaches the host heap.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
|
||||
extern "C" __declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
|
||||
extern "C" __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr ULONGLONG kObjectTypeResource = 4; // D3D12 XMemAlloc object types: GPU "Resource"
|
||||
constexpr ULONGLONG kAllocatorIdD3D = 128ull << 16; // XALLOC_ATTRIBUTES.AllocatorId, bits 16-23
|
||||
|
||||
struct Heap {
|
||||
uintptr_t base;
|
||||
UINT count;
|
||||
UINT xbox_size;
|
||||
ID3D12DescriptorHeap* host; // not owned: the Xbox object owns the reference
|
||||
SIZE_T host_cpu;
|
||||
UINT64 host_gpu;
|
||||
UINT host_increment;
|
||||
ULONGLONG attributes;
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
Heap* g_heaps = nullptr;
|
||||
size_t g_count = 0;
|
||||
size_t g_capacity = 0;
|
||||
|
||||
bool add(const Heap& heap) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (g_count == g_capacity) {
|
||||
const size_t capacity = g_capacity ? g_capacity * 2 : 32;
|
||||
auto* grown = new (std::nothrow) Heap[capacity];
|
||||
if (!grown) return false;
|
||||
for (size_t i = 0; i < g_count; ++i) grown[i] = g_heaps[i];
|
||||
delete[] g_heaps;
|
||||
g_heaps = grown;
|
||||
g_capacity = capacity;
|
||||
}
|
||||
g_heaps[g_count++] = heap;
|
||||
return true;
|
||||
}
|
||||
|
||||
const Heap* find_locked(uintptr_t address) {
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
const Heap& h = g_heaps[i];
|
||||
if (address >= h.base && address < h.base + static_cast<uintptr_t>(h.count) * h.xbox_size) return &h;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void log_untranslated(const char* what, uint64_t value) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) >= 8) return; // the first few are enough to see the pattern
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "%s 0x%llx is in no title descriptor heap", what,
|
||||
static_cast<unsigned long long>(value));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "descriptor_untranslated", detail);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type) {
|
||||
switch (type) {
|
||||
case D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV: return 32;
|
||||
case D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER: return 16;
|
||||
case D3D12_DESCRIPTOR_HEAP_TYPE_RTV: return 112;
|
||||
case D3D12_DESCRIPTOR_HEAP_TYPE_DSV: return 128;
|
||||
default: return 32;
|
||||
}
|
||||
}
|
||||
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE bx_xbox_host_cpu_handle(D3D12_CPU_DESCRIPTOR_HANDLE title) {
|
||||
if (!title.ptr) return title;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (const Heap* h = find_locked(title.ptr)) {
|
||||
return {h->host_cpu + (title.ptr - h->base) / h->xbox_size * h->host_increment};
|
||||
}
|
||||
log_untranslated("CPU descriptor handle", title.ptr);
|
||||
return title;
|
||||
}
|
||||
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE bx_xbox_host_gpu_handle(D3D12_GPU_DESCRIPTOR_HANDLE title) {
|
||||
if (!title.ptr) return title;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (const Heap* h = find_locked(static_cast<uintptr_t>(title.ptr))) {
|
||||
if (h->host_gpu) return {h->host_gpu + (title.ptr - h->base) / h->xbox_size * h->host_increment};
|
||||
}
|
||||
log_untranslated("GPU descriptor handle", title.ptr);
|
||||
return title;
|
||||
}
|
||||
|
||||
void bx_xbox_descriptor_heap_forget(IUnknown* host) {
|
||||
Heap gone{};
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (static_cast<IUnknown*>(g_heaps[i].host) == host) {
|
||||
gone = g_heaps[i];
|
||||
g_heaps[i] = g_heaps[--g_count];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (gone.base) XMemFree(reinterpret_cast<void*>(gone.base), gone.attributes);
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_descriptor_heap(void* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDescriptorHeap");
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
ID3D12DescriptorHeap* host = nullptr;
|
||||
HRESULT hr = device->CreateDescriptorHeap(desc, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&host));
|
||||
if (FAILED(hr) || !host) return FAILED(hr) ? hr : E_FAIL;
|
||||
|
||||
const UINT size = bx_xbox_descriptor_size(desc->Type);
|
||||
const ULONGLONG attributes = kObjectTypeResource | kAllocatorIdD3D;
|
||||
void* storage = XMemAlloc(static_cast<SIZE_T>(desc->NumDescriptors) * size, attributes);
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "type=%d count=%u xbox_size=%u flags=0x%x title_base=%p",
|
||||
static_cast<int>(desc->Type), desc->NumDescriptors, size, static_cast<unsigned>(desc->Flags), storage);
|
||||
bx_log_emit(storage ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "descriptor_heap", detail);
|
||||
if (!storage) {
|
||||
host->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE cpu{};
|
||||
host->GetCPUDescriptorHandleForHeapStart(&cpu);
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE gpu{};
|
||||
if (desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) host->GetGPUDescriptorHandleForHeapStart(&gpu);
|
||||
const Heap heap{reinterpret_cast<uintptr_t>(storage), desc->NumDescriptors, size, host, cpu.ptr, gpu.ptr,
|
||||
device->GetDescriptorHandleIncrementSize(desc->Type), attributes};
|
||||
if (!add(heap)) {
|
||||
XMemFree(storage, attributes);
|
||||
host->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*ppv = host;
|
||||
return bx_xbox_wrap_result(S_OK, riid, ppv);
|
||||
}
|
||||
|
||||
UINT STDMETHODCALLTYPE bx_xbox_device_get_descriptor_handle_increment_size(void*, D3D12_DESCRIPTOR_HEAP_TYPE type) {
|
||||
return bx_xbox_descriptor_size(type);
|
||||
}
|
||||
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_cpu_start(void* self) {
|
||||
auto* host = bx_xbox_host<ID3D12DescriptorHeap>(self);
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_heaps[i].host == host) return {g_heaps[i].base};
|
||||
}
|
||||
return {0};
|
||||
}
|
||||
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_gpu_start(void* self) {
|
||||
// On the console the GPU handle of a heap is the same address as its CPU handle.
|
||||
return {bx_xbox_heap_cpu_start(self).ptr};
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateConstantBufferView");
|
||||
D3D12_CONSTANT_BUFFER_VIEW_DESC host_desc{};
|
||||
if (desc) {
|
||||
host_desc = *desc;
|
||||
host_desc.BufferLocation = bx_xbox_host_gpu_va(desc->BufferLocation);
|
||||
}
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateConstantBufferView(desc ? &host_desc : nullptr, bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
|
||||
const UINT* dest_sizes, UINT src_ranges,
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, const UINT* src_sizes,
|
||||
D3D12_DESCRIPTOR_HEAP_TYPE type) {
|
||||
BX_D3D_TRACE("XboxDevice", "CopyDescriptors");
|
||||
auto* dst = new (std::nothrow) D3D12_CPU_DESCRIPTOR_HANDLE[dest_ranges + src_ranges + 1];
|
||||
if (!dst) return;
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE* src = dst + dest_ranges;
|
||||
for (UINT i = 0; i < dest_ranges; ++i) dst[i] = bx_xbox_host_cpu_handle(dest_starts[i]);
|
||||
for (UINT i = 0; i < src_ranges; ++i) src[i] = bx_xbox_host_cpu_handle(src_starts[i]);
|
||||
bx_xbox_host<ID3D12Device>(self)->CopyDescriptors(dest_ranges, dst, dest_sizes, src_ranges, src, src_sizes, type);
|
||||
delete[] dst;
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
|
||||
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* dsv) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "OMSetRenderTargets");
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE host_rtvs[8] = {};
|
||||
const UINT n = count > 8 ? 8 : count;
|
||||
for (UINT i = 0; rtvs && i < (single_range ? 1u : n); ++i) host_rtvs[i] = bx_xbox_host_cpu_handle(rtvs[i]);
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE host_dsv = dsv ? bx_xbox_host_cpu_handle(*dsv) : D3D12_CPU_DESCRIPTOR_HANDLE{};
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->OMSetRenderTargets(n, rtvs ? host_rtvs : nullptr, single_range,
|
||||
dsv ? &host_dsv : nullptr);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
|
||||
const D3D12_VERTEX_BUFFER_VIEW* views) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetVertexBuffers");
|
||||
D3D12_VERTEX_BUFFER_VIEW host[32] = {};
|
||||
const UINT n = count > 32 ? 32 : count;
|
||||
for (UINT i = 0; views && i < n; ++i) {
|
||||
host[i] = views[i];
|
||||
host[i].BufferLocation = bx_xbox_host_gpu_va(views[i].BufferLocation);
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetVertexBuffers(start, n, views ? host : nullptr);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_INDEX_BUFFER_VIEW* view) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetIndexBuffer");
|
||||
D3D12_INDEX_BUFFER_VIEW host{};
|
||||
if (view) {
|
||||
host = *view;
|
||||
host.BufferLocation = bx_xbox_host_gpu_va(view->BufferLocation);
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetIndexBuffer(view ? &host : nullptr);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
namespace {
|
||||
|
||||
/* The leading fields of D3D12XBOX_SAMPLER_DESC (authorized GDK header; every field is 4 bytes). */
|
||||
struct XboxSamplerPrefix {
|
||||
UINT flags;
|
||||
UINT filter_mag; // D3D12XBOX_TEXTURE_XY_FILTER: 0 point, 1 bilinear, 2 aniso point, 3 aniso bilinear
|
||||
UINT filter_min;
|
||||
UINT filter_mip; // D3D12XBOX_TEXTURE_MIP_FILTER: 0 none, 1 point, 2 linear
|
||||
UINT filter_z;
|
||||
UINT filter_mode; // D3D12XBOX_TEXTURE_FILTER_MODE: 0 lerp, 1 min, 2 max
|
||||
D3D12_TEXTURE_ADDRESS_MODE address_u, address_v, address_w;
|
||||
FLOAT min_lod, max_lod, mip_lod_bias, mip_lod_bias_secondary;
|
||||
UINT max_anisotropy;
|
||||
FLOAT anisotropy_bias;
|
||||
UINT anisotropy_threshold;
|
||||
D3D12_COMPARISON_FUNC comparison;
|
||||
FLOAT border_color[4];
|
||||
};
|
||||
static_assert(sizeof(XboxSamplerPrefix) == 21 * 4, "D3D12XBOX_SAMPLER_DESC prefix layout");
|
||||
|
||||
D3D12_FILTER_TYPE xy_type(UINT filter) { return (filter & 1) ? D3D12_FILTER_TYPE_LINEAR : D3D12_FILTER_TYPE_POINT; }
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" void STDMETHODCALLTYPE bx_xbox_device_create_sampler_x(void* self, const void* xbox_desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateSamplerX");
|
||||
if (!xbox_desc) return;
|
||||
XboxSamplerPrefix x{};
|
||||
std::memcpy(&x, xbox_desc, sizeof(x));
|
||||
// A comparison function other than NEVER selects comparison filtering (inference: the console
|
||||
// description has no separate comparison filter, so the function is the only signal).
|
||||
const bool compare = x.comparison > D3D12_COMPARISON_FUNC_NEVER;
|
||||
const D3D12_FILTER_REDUCTION_TYPE reduction = compare ? D3D12_FILTER_REDUCTION_TYPE_COMPARISON
|
||||
: x.filter_mode == 1 ? D3D12_FILTER_REDUCTION_TYPE_MINIMUM
|
||||
: x.filter_mode == 2 ? D3D12_FILTER_REDUCTION_TYPE_MAXIMUM
|
||||
: D3D12_FILTER_REDUCTION_TYPE_STANDARD;
|
||||
D3D12_SAMPLER_DESC pc{};
|
||||
const bool aniso = x.filter_mag >= 2 || x.filter_min >= 2;
|
||||
pc.Filter = aniso ? D3D12_ENCODE_ANISOTROPIC_FILTER(reduction)
|
||||
: D3D12_ENCODE_BASIC_FILTER(xy_type(x.filter_min), xy_type(x.filter_mag),
|
||||
x.filter_mip == 2 ? D3D12_FILTER_TYPE_LINEAR : D3D12_FILTER_TYPE_POINT,
|
||||
reduction);
|
||||
pc.AddressU = x.address_u;
|
||||
pc.AddressV = x.address_v;
|
||||
pc.AddressW = x.address_w;
|
||||
pc.MipLODBias = x.mip_lod_bias;
|
||||
pc.MaxAnisotropy = aniso ? (x.max_anisotropy < 1 ? 1 : x.max_anisotropy > 16 ? 16 : x.max_anisotropy) : 1;
|
||||
pc.ComparisonFunc = compare ? x.comparison : D3D12_COMPARISON_FUNC_NEVER;
|
||||
for (int i = 0; i < 4; ++i) pc.BorderColor[i] = x.border_color[i];
|
||||
pc.MinLOD = x.min_lod;
|
||||
pc.MaxLOD = x.filter_mip == 0 ? x.min_lod : x.max_lod; // no mip filter: the base level only
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateSampler(&pc, bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
* Fences with a title-visible value (ADR 0009). ID3D12Fence1::GetGpuAddressX returns the GPU
|
||||
* address of a fence's 64-bit value (authorized GDK documentation); titles read it from the CPU
|
||||
* and target it with Write*BitValue*X and Wait*BitValueX. Each fence that is asked for its
|
||||
* address gets an 8-byte slot in memory this layer owns, kept equal to the host fence's value:
|
||||
* - a CPU Signal stores the value at once;
|
||||
* - a queue Signal stores it when the host fence completes (a one-shot threadpool wait);
|
||||
* - a GPU value write to the slot (gpu_writes.cpp) also signals the host fence.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
struct Slot {
|
||||
ID3D12Fence* host;
|
||||
std::atomic<uint64_t>* value;
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
std::vector<Slot> g_slots;
|
||||
std::atomic<uint64_t>* g_page = nullptr;
|
||||
size_t g_used = 0;
|
||||
constexpr size_t kSlotsPerPage = 4096 / sizeof(uint64_t);
|
||||
|
||||
std::atomic<uint64_t>* allocate_locked() {
|
||||
if (!g_page || g_used == kSlotsPerPage) {
|
||||
g_page = static_cast<std::atomic<uint64_t>*>(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
g_used = 0;
|
||||
if (!g_page) return nullptr;
|
||||
}
|
||||
return &g_page[g_used++];
|
||||
}
|
||||
|
||||
std::atomic<uint64_t>* slot_of(ID3D12Fence* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (const Slot& s : g_slots) {
|
||||
if (s.host == host) return s.value;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void store_max(std::atomic<uint64_t>* slot, uint64_t value) {
|
||||
uint64_t current = slot->load();
|
||||
while (current < value && !slot->compare_exchange_weak(current, value)) {
|
||||
}
|
||||
}
|
||||
|
||||
struct Pending {
|
||||
std::atomic<uint64_t>* slot;
|
||||
uint64_t value;
|
||||
HANDLE event;
|
||||
HANDLE wait;
|
||||
};
|
||||
|
||||
void CALLBACK on_completed(void* context, BOOLEAN) {
|
||||
auto* p = static_cast<Pending*>(context);
|
||||
store_max(p->slot, p->value);
|
||||
// The wait cannot be unregistered from its own callback with a blocking call; hand it off.
|
||||
UnregisterWaitEx(p->wait, nullptr);
|
||||
CloseHandle(p->event);
|
||||
delete p;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool bx_xbox_fence_slot(uint64_t address, ID3D12Fence** host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (const Slot& s : g_slots) {
|
||||
if (reinterpret_cast<uint64_t>(s.value) == address) {
|
||||
if (host) *host = s.host;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void bx_xbox_fence_forget(IUnknown* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_slots.size(); ++i) {
|
||||
if (static_cast<IUnknown*>(g_slots[i].host) == host) { // the slot memory is not reused
|
||||
g_slots[i] = g_slots.back();
|
||||
g_slots.pop_back();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_fence_get_gpu_address_x(void* self) {
|
||||
BX_D3D_TRACE("XboxFence", "GetGpuAddressX");
|
||||
auto* host = bx_xbox_host<ID3D12Fence>(self);
|
||||
if (auto* existing = slot_of(host)) return reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(existing);
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
std::atomic<uint64_t>* slot = allocate_locked();
|
||||
if (!slot) return 0;
|
||||
slot->store(host->GetCompletedValue());
|
||||
g_slots.push_back({host, slot});
|
||||
return reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(slot);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_fence_signal(void* self, UINT64 value) {
|
||||
BX_D3D_TRACE("XboxFence", "Signal");
|
||||
auto* host = bx_xbox_host<ID3D12Fence>(self);
|
||||
const HRESULT hr = host->Signal(value);
|
||||
if (SUCCEEDED(hr)) {
|
||||
if (auto* slot = slot_of(host)) slot->store(value);
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_signal(void* self, ID3D12Fence* fence, UINT64 value) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "Signal");
|
||||
ID3D12Fence* host_fence = bx_xbox_unwrap_as(fence);
|
||||
const HRESULT hr = bx_xbox_host<ID3D12CommandQueue>(self)->Signal(host_fence, value);
|
||||
std::atomic<uint64_t>* slot = SUCCEEDED(hr) && host_fence ? slot_of(host_fence) : nullptr;
|
||||
if (!slot) return hr;
|
||||
if (host_fence->GetCompletedValue() >= value) {
|
||||
store_max(slot, value);
|
||||
return hr;
|
||||
}
|
||||
auto* p = new (std::nothrow) Pending{slot, value, CreateEventW(nullptr, TRUE, FALSE, nullptr), nullptr};
|
||||
if (!p || !p->event) {
|
||||
delete p;
|
||||
return hr;
|
||||
}
|
||||
if (FAILED(host_fence->SetEventOnCompletion(value, p->event)) ||
|
||||
!RegisterWaitForSingleObject(&p->wait, p->event, on_completed, p, INFINITE, WT_EXECUTEONLYONCE)) {
|
||||
CloseHandle(p->event);
|
||||
delete p;
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "fence_slot", "could not arm the completion mirror for a queue Signal");
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_wait(void* self, ID3D12Fence* fence, UINT64 value) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "Wait");
|
||||
return bx_xbox_host<ID3D12CommandQueue>(self)->Wait(bx_xbox_unwrap_as(fence), value);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* Xbox frame pacing on the host (ADR 0009): ID3D12Device::SetFrameIntervalX, ScheduleFrameEventX
|
||||
* and WaitFrameEventX, as the authorized GDK documentation describes them.
|
||||
*
|
||||
* On the console, display hardware signals the frame events. Here one thread emulates them
|
||||
* from the recorded frame interval: at the start of each interval it signals the VBLANK and
|
||||
* FLIP events, and IntervalOffsetInMicroseconds later the ORIGIN event, which also produces a
|
||||
* new frame pipeline token. Each signal also sets the ancillary events given to
|
||||
* ScheduleFrameEventX. Timing follows the host's Sleep granularity; no display is involved.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr UINT kEventTypes = 3; // ORIGIN, DISPLAY_VBLANK, DISPLAY_FLIP
|
||||
constexpr UINT kOrigin = 0;
|
||||
constexpr UINT kMaxAncillarySignals = 7;
|
||||
constexpr UINT kMaxAncillaryWaits = 63;
|
||||
constexpr UINT kScheduleDisableSignal = 0x1;
|
||||
constexpr UINT kWaitAll = 0x1;
|
||||
constexpr UINT kWaitProcessTokenOnTimeout = 0x2;
|
||||
constexpr UINT kIntervalFlag60FpsPlus = 0x1;
|
||||
constexpr UINT kSignaledNone = 0xFFFFFFFF;
|
||||
constexpr UINT kInfinite = 0xFFFFFFFF;
|
||||
|
||||
struct Scheduled {
|
||||
bool active = false;
|
||||
UINT offset_us = 0;
|
||||
HANDLE ancillary[kMaxAncillarySignals] = {};
|
||||
UINT ancillary_count = 0;
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
UINT g_interval_us = 0;
|
||||
UINT g_period = 0;
|
||||
Scheduled g_events[kEventTypes];
|
||||
HANDLE g_signal[kEventTypes] = {}; // auto-reset, set at each occurrence
|
||||
UINT64 g_next_token = 1;
|
||||
UINT64 g_last_origin_token = 0;
|
||||
bool g_thread_started = false;
|
||||
|
||||
void close_ancillary(Scheduled& e) {
|
||||
for (UINT i = 0; i < e.ancillary_count; ++i) CloseHandle(e.ancillary[i]);
|
||||
e.ancillary_count = 0;
|
||||
}
|
||||
|
||||
void signal(UINT type) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
const Scheduled& e = g_events[type];
|
||||
if (!e.active) return;
|
||||
if (type == kOrigin) g_last_origin_token = g_next_token++;
|
||||
SetEvent(g_signal[type]);
|
||||
for (UINT i = 0; i < e.ancillary_count; ++i) SetEvent(e.ancillary[i]);
|
||||
}
|
||||
|
||||
void pacing_thread() {
|
||||
LARGE_INTEGER frequency, start;
|
||||
QueryPerformanceFrequency(&frequency);
|
||||
QueryPerformanceCounter(&start);
|
||||
const auto now_us = [&] {
|
||||
LARGE_INTEGER t;
|
||||
QueryPerformanceCounter(&t);
|
||||
return static_cast<UINT64>((t.QuadPart - start.QuadPart) * 1000000 / frequency.QuadPart);
|
||||
};
|
||||
const auto sleep_until = [&](UINT64 target_us) {
|
||||
for (UINT64 t = now_us(); t < target_us; t = now_us()) {
|
||||
const UINT64 ms = (target_us - t) / 1000;
|
||||
Sleep(ms ? static_cast<DWORD>(ms) : 0);
|
||||
}
|
||||
};
|
||||
UINT64 interval_start = 0;
|
||||
for (;;) {
|
||||
UINT interval, origin_offset;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
interval = g_interval_us;
|
||||
origin_offset = g_events[kOrigin].offset_us;
|
||||
}
|
||||
signal(1);
|
||||
signal(2);
|
||||
sleep_until(interval_start + (origin_offset < interval ? origin_offset : 0));
|
||||
signal(kOrigin);
|
||||
interval_start += interval;
|
||||
sleep_until(interval_start);
|
||||
}
|
||||
}
|
||||
|
||||
void log_pacing(const char* event, const char* fmt, UINT a, UINT b, UINT c) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), fmt, a, b, c);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", event, detail);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_set_frame_interval_x(void*, IDXGIOutput*, UINT length_us, UINT period,
|
||||
UINT flags) {
|
||||
BX_D3D_TRACE("XboxDevice", "SetFrameIntervalX");
|
||||
if (length_us == 0 || period < 1 || period > 4 || (flags & ~kIntervalFlag60FpsPlus) != 0) return E_INVALIDARG;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
g_interval_us = length_us;
|
||||
g_period = period;
|
||||
log_pacing("frame_interval", "length_us=%u period=%u flags=0x%x (host timer, no display sync)", length_us, period, flags);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_schedule_frame_event_x(void*, UINT type, UINT offset_us,
|
||||
const BxXboxFrameObjectList* signals, UINT flags) {
|
||||
BX_D3D_TRACE("XboxDevice", "ScheduleFrameEventX");
|
||||
if (type >= kEventTypes || (flags & ~kScheduleDisableSignal) != 0) return E_INVALIDARG;
|
||||
if (signals && (signals->Count > kMaxAncillarySignals || (signals->Count && !signals->pObjects))) return E_INVALIDARG;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (g_interval_us == 0) return E_INVALIDARG; // documented: an interval must be established first
|
||||
if (offset_us >= g_interval_us) return E_INVALIDARG;
|
||||
for (UINT i = 0; i < kEventTypes; ++i) {
|
||||
if (!g_signal[i] && !(g_signal[i] = CreateEventW(nullptr, FALSE, FALSE, nullptr))) return E_OUTOFMEMORY;
|
||||
}
|
||||
Scheduled& e = g_events[type];
|
||||
close_ancillary(e);
|
||||
e.active = !(flags & kScheduleDisableSignal);
|
||||
e.offset_us = offset_us;
|
||||
for (UINT i = 0; signals && i < signals->Count; ++i) {
|
||||
// The title may close its handle; the scheduled signal keeps its own copy.
|
||||
if (!DuplicateHandle(GetCurrentProcess(), signals->pObjects[i], GetCurrentProcess(), &e.ancillary[e.ancillary_count],
|
||||
0, FALSE, DUPLICATE_SAME_ACCESS)) {
|
||||
close_ancillary(e);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
++e.ancillary_count;
|
||||
}
|
||||
log_pacing("frame_event_scheduled", "type=%u offset_us=%u ancillary=%u", type, offset_us, e.ancillary_count);
|
||||
if (!g_thread_started) {
|
||||
std::thread(pacing_thread).detach();
|
||||
g_thread_started = true;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UINT timeout_ms,
|
||||
const BxXboxFrameWaitList* waits, UINT flags,
|
||||
UINT64* token) {
|
||||
BX_D3D_TRACE("XboxDevice", "WaitFrameEventX");
|
||||
if (type >= kEventTypes || (flags & ~(kWaitAll | kWaitProcessTokenOnTimeout)) != 0) return E_INVALIDARG;
|
||||
if (waits && (waits->Count > kMaxAncillaryWaits || (waits->Count && !waits->pObjects))) return E_INVALIDARG;
|
||||
HANDLE handles[1 + kMaxAncillaryWaits];
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (!g_events[type].active) return E_INVALIDARG; // documented: the event must be scheduled
|
||||
handles[0] = g_signal[type];
|
||||
}
|
||||
const UINT ancillary = waits ? waits->Count : 0;
|
||||
for (UINT i = 0; i < ancillary; ++i) handles[1 + i] = waits->pObjects[i];
|
||||
const DWORD result = WaitForMultipleObjects(1 + ancillary, handles, (flags & kWaitAll) != 0,
|
||||
timeout_ms == kInfinite ? INFINITE : timeout_ms);
|
||||
const bool satisfied = result < WAIT_OBJECT_0 + 1 + ancillary;
|
||||
if (waits && waits->pSignaledObjectIndex) {
|
||||
*waits->pSignaledObjectIndex = satisfied && !(flags & kWaitAll) && result > WAIT_OBJECT_0
|
||||
? result - WAIT_OBJECT_0 - 1 : kSignaledNone;
|
||||
}
|
||||
if (type == kOrigin && token && (satisfied || (flags & kWaitProcessTokenOnTimeout))) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
*token = satisfied ? g_last_origin_token : g_next_token++;
|
||||
}
|
||||
return satisfied ? S_OK : S_FALSE;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,267 @@
|
||||
/*
|
||||
* GPU value writes into title memory (ADR 0009): Write32/64BitValueBottomOfPipeX and
|
||||
* ...TopOfPipeX record "when the GPU reaches this point, store this value at this address".
|
||||
* On the console the address is title memory that the CPU polls. The host GPU cannot write
|
||||
* title memory, so each command list keeps its writes in recording order, and when a queue
|
||||
* executes lists that carry writes, it waits for the host GPU (an internal fence) and stores the
|
||||
* values from the CPU, in submission order, before the Execute call returns. Executes with
|
||||
* writes are therefore synchronous (logged once); executes without writes are not changed.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
struct Write {
|
||||
uint64_t address;
|
||||
uint64_t value;
|
||||
bool wide;
|
||||
bool wait = false; // Wait*BitValueX: value is the reference
|
||||
D3D12_COMPARISON_FUNC compare = D3D12_COMPARISON_FUNC_GREATER_EQUAL;
|
||||
uint64_t mask = ~0ull;
|
||||
};
|
||||
|
||||
struct ListWrites {
|
||||
ID3D12GraphicsCommandList* list;
|
||||
std::vector<Write> writes;
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
std::vector<ListWrites> g_lists;
|
||||
|
||||
ListWrites* find_locked(ID3D12GraphicsCommandList* list) {
|
||||
for (ListWrites& entry : g_lists) {
|
||||
if (entry.list == list) return &entry;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool writable(uint64_t address, size_t size) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(address), ®ion, sizeof(region)) || region.State != MEM_COMMIT) return false;
|
||||
constexpr DWORD kWritable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
|
||||
return (region.Protect & kWritable) && address + size <= reinterpret_cast<uint64_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
|
||||
void record(void* self, const Write& op) {
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
ListWrites* entry = find_locked(list);
|
||||
if (!entry) {
|
||||
g_lists.push_back({list, {}});
|
||||
entry = &g_lists.back();
|
||||
}
|
||||
entry->writes.push_back(op);
|
||||
}
|
||||
|
||||
void record(void* self, uint64_t address, uint64_t value, bool wide) { record(self, Write{address, value, wide}); }
|
||||
|
||||
bool satisfied(const Write& w) {
|
||||
const uint64_t raw = w.wide ? reinterpret_cast<const std::atomic<uint64_t>*>(w.address)->load()
|
||||
: reinterpret_cast<const std::atomic<uint32_t>*>(w.address)->load();
|
||||
const uint64_t v = raw & w.mask;
|
||||
switch (w.compare) {
|
||||
case D3D12_COMPARISON_FUNC_NEVER: return false;
|
||||
case D3D12_COMPARISON_FUNC_LESS: return v < w.value;
|
||||
case D3D12_COMPARISON_FUNC_EQUAL: return v == w.value;
|
||||
case D3D12_COMPARISON_FUNC_LESS_EQUAL: return v <= w.value;
|
||||
case D3D12_COMPARISON_FUNC_GREATER: return v > w.value;
|
||||
case D3D12_COMPARISON_FUNC_NOT_EQUAL: return v != w.value;
|
||||
case D3D12_COMPARISON_FUNC_GREATER_EQUAL: return v >= w.value;
|
||||
default: return true;
|
||||
}
|
||||
}
|
||||
|
||||
// A GPU wait on memory becomes a host queue Wait when the memory is a fence slot and the
|
||||
// comparison is >=; otherwise the CPU polls the memory before submitting (10 s limit, logged).
|
||||
void apply_wait(ID3D12CommandQueue* queue, const Write& w) {
|
||||
ID3D12Fence* fence = nullptr;
|
||||
if (w.wide && w.compare == D3D12_COMPARISON_FUNC_GREATER_EQUAL && w.mask == ~0ull && bx_xbox_fence_slot(w.address, &fence)) {
|
||||
queue->Wait(fence, w.value);
|
||||
return;
|
||||
}
|
||||
if (!writable(w.address, w.wide ? 8 : 4)) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_wait", "wait address is not title memory; wait skipped");
|
||||
return;
|
||||
}
|
||||
const ULONGLONG start = GetTickCount64();
|
||||
while (!satisfied(w)) {
|
||||
if (GetTickCount64() - start > 10000) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "wait on 0x%llx not satisfied after 10 s; submitting anyway",
|
||||
static_cast<unsigned long long>(w.address));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_wait", detail);
|
||||
return;
|
||||
}
|
||||
SwitchToThread();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
struct QueueFence {
|
||||
ID3D12CommandQueue* queue;
|
||||
ID3D12Fence* fence;
|
||||
uint64_t value;
|
||||
};
|
||||
std::vector<QueueFence> g_fences; // guarded by g_lock
|
||||
|
||||
HRESULT wait_for_queue(ID3D12CommandQueue* queue) {
|
||||
ID3D12Fence* fence = nullptr;
|
||||
uint64_t value = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (QueueFence& q : g_fences) {
|
||||
if (q.queue == queue) {
|
||||
fence = q.fence;
|
||||
value = ++q.value;
|
||||
}
|
||||
}
|
||||
if (!fence) {
|
||||
ID3D12Device* device = nullptr;
|
||||
if (FAILED(queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device)))) return E_FAIL;
|
||||
const HRESULT hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
|
||||
device->Release();
|
||||
if (FAILED(hr)) return hr;
|
||||
value = 1;
|
||||
g_fences.push_back({queue, fence, value});
|
||||
}
|
||||
}
|
||||
HRESULT hr = queue->Signal(fence, value);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (fence->GetCompletedValue() >= value) return S_OK;
|
||||
HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!event) return E_OUTOFMEMORY;
|
||||
hr = fence->SetEventOnCompletion(value, event);
|
||||
if (SUCCEEDED(hr) && WaitForSingleObject(event, 10000) != WAIT_OBJECT_0) hr = HRESULT_FROM_WIN32(WAIT_TIMEOUT);
|
||||
CloseHandle(event);
|
||||
return hr;
|
||||
}
|
||||
|
||||
void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
|
||||
auto* queue = bx_xbox_host<ID3D12CommandQueue>(self);
|
||||
BxXboxUnwrapArray<ID3D12CommandList> host(lists, count);
|
||||
if (!host.ok()) return;
|
||||
std::vector<Write> pending;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
if (ListWrites* entry = find_locked(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host.data()[i])))) {
|
||||
pending.insert(pending.end(), entry->writes.begin(), entry->writes.end());
|
||||
}
|
||||
}
|
||||
}
|
||||
bx_xbox_sync_mapped_buffers();
|
||||
for (const Write& w : pending) {
|
||||
if (w.wait) apply_wait(queue, w);
|
||||
}
|
||||
queue->ExecuteCommandLists(count, host.data());
|
||||
bool any_write = false;
|
||||
for (const Write& w : pending) any_write = any_write || !w.wait;
|
||||
if (!any_write) return;
|
||||
static std::atomic<bool> logged{false};
|
||||
if (!logged.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "gpu_value_writes",
|
||||
"executes carrying Write*BitValue*X wait for the host GPU, then store the values in title memory");
|
||||
}
|
||||
const HRESULT hr = wait_for_queue(queue);
|
||||
if (FAILED(hr)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "waiting for the host GPU failed hr=0x%08lx; values still written",
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", detail);
|
||||
}
|
||||
for (const Write& w : pending) {
|
||||
if (w.wait) continue;
|
||||
if (!writable(w.address, w.wide ? 8 : 4)) {
|
||||
static std::atomic<int> bad{0};
|
||||
if (bad.fetch_add(1) < 8) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "address 0x%llx is not writable title memory; value dropped",
|
||||
static_cast<unsigned long long>(w.address));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", detail);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (w.wide) {
|
||||
reinterpret_cast<std::atomic<uint64_t>*>(w.address)->store(w.value, std::memory_order_release);
|
||||
} else {
|
||||
reinterpret_cast<std::atomic<uint32_t>*>(w.address)->store(static_cast<uint32_t>(w.value), std::memory_order_release);
|
||||
}
|
||||
ID3D12Fence* fence = nullptr;
|
||||
if (w.wide && bx_xbox_fence_slot(w.address, &fence)) fence->Signal(w.value);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_xbox_gpu_writes_reset(IUnknown* host_list) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_lists.size(); ++i) {
|
||||
if (static_cast<IUnknown*>(g_lists[i].list) == host_list) {
|
||||
g_lists[i] = std::move(g_lists.back());
|
||||
g_lists.pop_back();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write32_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT, UINT) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Write32BitValueBottomOfPipeX");
|
||||
record(self, address, value, false);
|
||||
}
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write64_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT, UINT) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Write64BitValueBottomOfPipeX");
|
||||
record(self, address, value, true);
|
||||
}
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write32_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Write32BitValueTopOfPipeX");
|
||||
record(self, address, value, false);
|
||||
}
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write64_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Write64BitValueTopOfPipeX");
|
||||
record(self, address, value, true);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_wait64_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
|
||||
UINT64 reference, UINT) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Wait64BitValueX");
|
||||
Write op{address, reference, true};
|
||||
op.wait = true;
|
||||
op.compare = compare;
|
||||
record(self, op);
|
||||
}
|
||||
void STDMETHODCALLTYPE bx_xbox_list_wait32_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
|
||||
UINT reference, UINT mask, UINT) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Wait32BitValueX");
|
||||
Write op{address, reference, false};
|
||||
op.wait = true;
|
||||
op.compare = compare;
|
||||
op.mask = mask;
|
||||
record(self, op);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists(void* self, UINT count, ID3D12CommandList* const* lists) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "ExecuteCommandLists");
|
||||
execute(self, count, lists);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists2_x(void* self, UINT count, ID3D12CommandList* const* lists,
|
||||
UINT64 token, UINT flags) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "ExecuteCommandLists2X");
|
||||
static std::atomic<bool> logged{false};
|
||||
if (!logged.exchange(true)) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "frame token and kickoff flags (first: token=%llu flags=0x%x) not used by the host",
|
||||
static_cast<unsigned long long>(token), flags);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "execute_command_lists2_x", detail);
|
||||
}
|
||||
execute(self, count, lists);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,193 @@
|
||||
// Console GPU page mappings: ID3D12CommandQueue CopyPageMappingsX, ClearPageMappingsX and
|
||||
// CopyPageMappingsBatchX (authorized GDK documentation; layouts and semantics derived from it).
|
||||
//
|
||||
// A page pool is title memory registered with RegisterPagePoolX; these calls make the 64 KiB (or,
|
||||
// with D3D12XBOX_PAGE_MAPPING_FLAG_2MB_PAGES, 2 MiB) pages at a destination GPU address show pool
|
||||
// pages. GPU addresses are title addresses in BetterXen and pool pages are xmem physical pages, so
|
||||
// each destination page is mapped onto the pool page's physical page with
|
||||
// XMemMapPhysicalPagesScatter; xmem reports the physical page behind a pool address. Range types:
|
||||
// incrementing pool pages, one constant pool page, null pages (unmapped) and skipped pages (left as
|
||||
// they are). The remapping happens when the call is made, not in queue order.
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xbox_facade.h"
|
||||
|
||||
namespace {
|
||||
|
||||
struct PageMappingRange {
|
||||
UINT RangeType;
|
||||
UINT StartPageIndexInPool;
|
||||
UINT PageCount;
|
||||
};
|
||||
struct PageMappingBatch {
|
||||
D3D12_GPU_VIRTUAL_ADDRESS DestinationAddress;
|
||||
UINT RangeCount;
|
||||
const PageMappingRange* pRanges;
|
||||
};
|
||||
static_assert(sizeof(PageMappingRange) == 12, "D3D12XBOX_PAGE_MAPPING_RANGE");
|
||||
static_assert(sizeof(PageMappingBatch) == 24, "D3D12XBOX_PAGE_MAPPING_BATCH");
|
||||
|
||||
enum : UINT { kIncrementing = 0, kConstant = 1, kNullPages = 2, kSkip = 3 };
|
||||
constexpr UINT kFlag2MbPages = 2;
|
||||
constexpr uint64_t kSmallPage = 64 * 1024;
|
||||
|
||||
using ScatterFn = BOOL(WINAPI*)(PVOID*, ULONG_PTR, PULONG_PTR);
|
||||
using QueryFn = int (*)(uint64_t, bx_xmem_region_info_t*);
|
||||
|
||||
struct Xmem {
|
||||
ScatterFn scatter = nullptr;
|
||||
QueryFn query = nullptr;
|
||||
Xmem() {
|
||||
if (HMODULE m = GetModuleHandleA("xmem.dll")) {
|
||||
scatter = reinterpret_cast<ScatterFn>(reinterpret_cast<void*>(GetProcAddress(m, "XMemMapPhysicalPagesScatter")));
|
||||
query = reinterpret_cast<QueryFn>(reinterpret_cast<void*>(GetProcAddress(m, "bx_xmem_query_region")));
|
||||
}
|
||||
}
|
||||
};
|
||||
const Xmem& xmem() {
|
||||
static const Xmem api;
|
||||
return api;
|
||||
}
|
||||
|
||||
void log_mapping(const char* what, const char* detail) {
|
||||
static LONG logged = 0;
|
||||
if (InterlockedIncrement(&logged) <= 64) bx_log_emit(BX_LOG_INFO, "d3d12_xs", what, detail);
|
||||
}
|
||||
|
||||
void log_failure(const char* detail) {
|
||||
static LONG logged = 0;
|
||||
if (InterlockedIncrement(&logged) <= 32) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "page_mapping_failed", detail);
|
||||
}
|
||||
|
||||
// Collects destination slots and physical pages (0: unmap), then maps them in one scatter call.
|
||||
class Mapper {
|
||||
public:
|
||||
Mapper(uint64_t pool, UINT pool_pages, UINT flags)
|
||||
: pool_(pool), pool_pages_(pool_pages), page_(flags & kFlag2MbPages ? 32 * kSmallPage : kSmallPage) {}
|
||||
|
||||
// One destination page `dst_page` (index from `dst`) showing pool page `pool_page`, or none.
|
||||
bool add(uint64_t dst, uint64_t dst_page, bool null_page, UINT pool_page) {
|
||||
for (uint64_t sub = 0; sub < page_ / kSmallPage; ++sub) {
|
||||
ULONG_PTR tag = 0;
|
||||
if (!null_page) {
|
||||
if (pool_page >= pool_pages_) return fail("pool page index past the pool", dst, pool_page);
|
||||
bx_xmem_region_info_t info{};
|
||||
const uint64_t src = pool_ + uint64_t(pool_page) * page_ + sub * kSmallPage;
|
||||
if (!xmem().query || !xmem().query(src, &info) || !info.physical_tag) {
|
||||
return fail("pool address has no xmem physical page", dst, pool_page);
|
||||
}
|
||||
tag = static_cast<ULONG_PTR>(info.physical_tag);
|
||||
}
|
||||
slots_.push_back(reinterpret_cast<PVOID>(static_cast<uintptr_t>(dst + dst_page * page_ + sub * kSmallPage)));
|
||||
tags_.push_back(tag);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool add_range(uint64_t dst, uint64_t& cursor, const PageMappingRange& range) {
|
||||
switch (range.RangeType) {
|
||||
case kSkip:
|
||||
cursor += range.PageCount;
|
||||
return true;
|
||||
case kIncrementing:
|
||||
case kConstant:
|
||||
case kNullPages:
|
||||
for (UINT i = 0; i < range.PageCount; ++i) {
|
||||
const UINT pool_page = range.RangeType == kIncrementing ? range.StartPageIndexInPool + i
|
||||
: range.StartPageIndexInPool;
|
||||
if (!add(dst, cursor + i, range.RangeType == kNullPages, pool_page)) return false;
|
||||
}
|
||||
cursor += range.PageCount;
|
||||
return true;
|
||||
default:
|
||||
return fail("unknown range type", dst, range.RangeType);
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT commit() {
|
||||
if (slots_.empty()) return S_OK;
|
||||
if (!xmem().scatter) {
|
||||
log_failure("xmem.dll!XMemMapPhysicalPagesScatter not available");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
if (!xmem().scatter(slots_.data(), slots_.size(), tags_.data())) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "XMemMapPhysicalPagesScatter of %zu pages at %p failed error=%lu",
|
||||
slots_.size(), slots_.front(), static_cast<unsigned long>(GetLastError()));
|
||||
log_failure(detail);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
size_t pages() const { return slots_.size(); }
|
||||
|
||||
private:
|
||||
bool fail(const char* why, uint64_t dst, UINT value) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s (destination 0x%llx, value %u)", why,
|
||||
static_cast<unsigned long long>(dst), value);
|
||||
log_failure(detail);
|
||||
return false;
|
||||
}
|
||||
|
||||
uint64_t pool_;
|
||||
UINT pool_pages_;
|
||||
uint64_t page_;
|
||||
std::vector<PVOID> slots_;
|
||||
std::vector<ULONG_PTR> tags_;
|
||||
};
|
||||
|
||||
HRESULT map_batches(UINT count, const PageMappingBatch* batches, uint64_t pool, UINT pool_pages, UINT flags,
|
||||
const char* method) {
|
||||
if (count && !batches) return E_INVALIDARG;
|
||||
Mapper mapper(pool, pool_pages, flags);
|
||||
for (UINT b = 0; b < count; ++b) {
|
||||
if (batches[b].RangeCount && !batches[b].pRanges) return E_INVALIDARG;
|
||||
uint64_t cursor = 0;
|
||||
for (UINT r = 0; r < batches[b].RangeCount; ++r) {
|
||||
if (!mapper.add_range(batches[b].DestinationAddress, cursor, batches[b].pRanges[r])) return E_INVALIDARG;
|
||||
}
|
||||
}
|
||||
const HRESULT hr = mapper.commit();
|
||||
char detail[192];
|
||||
std::snprintf(detail, sizeof(detail), "%s batches=%u first_destination=0x%llx pool=0x%llx pool_pages=%u flags=0x%x pages=%zu hr=0x%08lx",
|
||||
method, count, count ? static_cast<unsigned long long>(batches[0].DestinationAddress) : 0ull,
|
||||
static_cast<unsigned long long>(pool), pool_pages, flags, mapper.pages(), static_cast<unsigned long>(hr));
|
||||
log_mapping("page_mappings", detail);
|
||||
return hr;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_batch_x(void*, UINT batch_count, const void* batches,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages,
|
||||
UINT flags) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "CopyPageMappingsBatchX");
|
||||
return map_batches(batch_count, static_cast<const PageMappingBatch*>(batches), pool, pool_pages, flags,
|
||||
"CopyPageMappingsBatchX");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_x(void*, D3D12_GPU_VIRTUAL_ADDRESS destination,
|
||||
UINT range_count, const void* ranges,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages,
|
||||
UINT flags) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "CopyPageMappingsX");
|
||||
const PageMappingBatch batch{destination, range_count, static_cast<const PageMappingRange*>(ranges)};
|
||||
return map_batches(1, &batch, pool, pool_pages, flags, "CopyPageMappingsX");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_clear_page_mappings_x(void*, D3D12_GPU_VIRTUAL_ADDRESS destination,
|
||||
UINT page_count, UINT flags) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "ClearPageMappingsX");
|
||||
const PageMappingRange range{kNullPages, 0, page_count};
|
||||
const PageMappingBatch batch{destination, 1, &range};
|
||||
return map_batches(1, &batch, 0, 0, flags, "ClearPageMappingsX");
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
/*
|
||||
* Pipeline states on the Xbox-layout device (ADR 0009), and the opt-in null-render mode.
|
||||
*
|
||||
* Every pipeline creation goes through the M2 shader format gate (shader_gate.h, ADR 0008), so
|
||||
* each stage writes a `shader_gate` record, and the title's root signature is unwrapped before
|
||||
* the description reaches the host. The Xbox *X variants take extended descriptions
|
||||
* (D3D12XBOX_EXTENDED_*_PIPELINE_STATE_DESC) that have no host equivalent; their count is logged
|
||||
* and the base description is created.
|
||||
*
|
||||
* Null-render mode (BX_NULL_RENDER=1, off by default): a pipeline the host refuses, for example
|
||||
* one whose shaders are console-only, becomes a BetterXen null pipeline instead of a failure.
|
||||
* Binding it is recorded per command list, and draws and dispatches recorded while it is bound
|
||||
* are skipped. Everything else still runs, so fences complete and frames present, with the
|
||||
* skipped work missing from them. Each refusal and each skip is logged: the mode exists to see
|
||||
* how far a title gets, not to hide what it cannot run.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include "proxy.h"
|
||||
#include "shader_gate.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
|
||||
namespace {
|
||||
|
||||
bool null_render_enabled() {
|
||||
static const bool enabled = [] {
|
||||
char value[8] = {};
|
||||
const DWORD n = GetEnvironmentVariableA("BX_NULL_RENDER", value, sizeof(value));
|
||||
const bool on = n > 0 && n < sizeof(value) && value[0] == '1';
|
||||
if (on) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "null_render", "enabled: refused pipelines become null pipelines");
|
||||
return on;
|
||||
}();
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/* A pipeline-state object with no host pipeline behind it. */
|
||||
class NullPipelineState final : public ID3D12PipelineState {
|
||||
public:
|
||||
explicit NullPipelineState(ID3D12Device* device) : device_(device) { device_->AddRef(); }
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) ||
|
||||
riid == __uuidof(ID3D12Pageable) || riid == __uuidof(ID3D12PipelineState)) {
|
||||
*ppv = static_cast<ID3D12PipelineState*>(this);
|
||||
AddRef();
|
||||
return S_OK;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
|
||||
ULONG STDMETHODCALLTYPE Release() override {
|
||||
const ULONG left = --refs_;
|
||||
if (!left) {
|
||||
device_->Release();
|
||||
delete this;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT* size, void*) override {
|
||||
if (size) *size = 0;
|
||||
return DXGI_ERROR_NOT_FOUND;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; }
|
||||
HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; }
|
||||
HRESULT STDMETHODCALLTYPE SetName(LPCWSTR) override { return S_OK; }
|
||||
HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** ppv) override { return device_->QueryInterface(riid, ppv); }
|
||||
HRESULT STDMETHODCALLTYPE GetCachedBlob(ID3DBlob** blob) override {
|
||||
if (blob) *blob = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
private:
|
||||
ID3D12Device* device_;
|
||||
std::atomic<ULONG> refs_{1};
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
NullPipelineState** g_nulls = nullptr; // live null pipelines, so they can be recognised
|
||||
size_t g_null_count = 0;
|
||||
size_t g_null_capacity = 0;
|
||||
ID3D12GraphicsCommandList** g_lists = nullptr; // lists whose bound pipeline is a null pipeline
|
||||
size_t g_list_count = 0;
|
||||
size_t g_list_capacity = 0;
|
||||
|
||||
template <typename T>
|
||||
bool push(T**& items, size_t& count, size_t& capacity, T* item) {
|
||||
if (count == capacity) {
|
||||
const size_t grown_capacity = capacity ? capacity * 2 : 16;
|
||||
auto** grown = new (std::nothrow) T*[grown_capacity];
|
||||
if (!grown) return false;
|
||||
for (size_t i = 0; i < count; ++i) grown[i] = items[i];
|
||||
delete[] items;
|
||||
items = grown;
|
||||
capacity = grown_capacity;
|
||||
}
|
||||
items[count++] = item;
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool erase(T** items, size_t& count, const T* item) {
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (items[i] == item) {
|
||||
items[i] = items[--count];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool contains(T* const* items, size_t count, const T* item) {
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (items[i] == item) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Returns the host pipeline for a title pipeline, or nullptr for a null pipeline. */
|
||||
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null) {
|
||||
ID3D12PipelineState* host = bx_xbox_unwrap_as(title);
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
*is_null = host && contains(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
|
||||
return *is_null ? nullptr : host;
|
||||
}
|
||||
|
||||
void set_list_null(ID3D12GraphicsCommandList* list, bool null_bound) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
const bool present = contains(g_lists, g_list_count, list);
|
||||
if (null_bound && !present) push(g_lists, g_list_count, g_list_capacity, list);
|
||||
if (!null_bound && present) erase(g_lists, g_list_count, list);
|
||||
}
|
||||
|
||||
bool list_skips(ID3D12GraphicsCommandList* list, const char* what) {
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (!contains(g_lists, g_list_count, list)) return false;
|
||||
}
|
||||
static std::atomic<uint64_t> skipped{0};
|
||||
const uint64_t n = ++skipped;
|
||||
if ((n & (n - 1)) == 0) { // 1, 2, 4, 8, ...: enough to follow without flooding the log
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "%s with a null pipeline bound; total skipped=%llu", what,
|
||||
static_cast<unsigned long long>(n));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "null_render_skip", detail);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid, void** ppv) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "%s pipeline refused hr=0x%08lx%s", kind, static_cast<unsigned long>(hr),
|
||||
null_render_enabled() ? "; null pipeline returned" : "");
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_refused", detail);
|
||||
if (!null_render_enabled() || !ppv) return hr;
|
||||
auto* null_pso = new (std::nothrow) NullPipelineState(device);
|
||||
if (!null_pso) return E_OUTOFMEMORY;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (!push(g_nulls, g_null_count, g_null_capacity, null_pso)) {
|
||||
null_pso->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
*ppv = static_cast<ID3D12PipelineState*>(null_pso);
|
||||
return bx_xbox_wrap_result(S_OK, riid, ppv);
|
||||
}
|
||||
|
||||
void log_extended(const char* kind, UINT count) {
|
||||
if (!count) return;
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "%s: %u extended description(s) not applied", kind, count);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_extended_desc", detail);
|
||||
}
|
||||
|
||||
HRESULT create_compute(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
BxShaderGate gate;
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC admitted = *desc;
|
||||
admitted.pRootSignature = bx_xbox_unwrap_as(desc->pRootSignature);
|
||||
HRESULT hr = gate.admit("compute", "CS", desc->CS, admitted.CS);
|
||||
if (SUCCEEDED(hr)) hr = device->CreateComputePipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "compute", riid, ppv);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT create_graphics(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
BxShaderGate gate;
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC admitted = *desc;
|
||||
admitted.pRootSignature = bx_xbox_unwrap_as(desc->pRootSignature);
|
||||
HRESULT hr = gate.admit("graphics", "VS", desc->VS, admitted.VS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "PS", desc->PS, admitted.PS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "DS", desc->DS, admitted.DS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "HS", desc->HS, admitted.HS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "GS", desc->GS, admitted.GS);
|
||||
if (SUCCEEDED(hr)) hr = device->CreateGraphicsPipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "graphics", riid, ppv);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
auto* device = bx_xbox_host<ID3D12Device2>(self);
|
||||
std::vector<uint8_t> stream;
|
||||
std::vector<size_t> offsets;
|
||||
std::vector<const char*> names;
|
||||
size_t root_offset = SIZE_MAX;
|
||||
HRESULT hr = copy_stream(*desc, stream, offsets, names, &root_offset);
|
||||
if (FAILED(hr)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "stream of %llu bytes not parsed (unknown or console subobject?)",
|
||||
static_cast<unsigned long long>(desc->SizeInBytes));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pso_stream", detail);
|
||||
return refused(device, hr, "stream", riid, ppv);
|
||||
}
|
||||
if (root_offset != SIZE_MAX) {
|
||||
ID3D12RootSignature* root = nullptr;
|
||||
std::memcpy(&root, &stream[root_offset], sizeof(root));
|
||||
root = bx_xbox_unwrap_as(root);
|
||||
std::memcpy(&stream[root_offset], &root, sizeof(root));
|
||||
}
|
||||
BxShaderGate gate;
|
||||
for (size_t i = 0; i < offsets.size() && SUCCEEDED(hr); ++i) {
|
||||
D3D12_SHADER_BYTECODE in{};
|
||||
std::memcpy(&in, &stream[offsets[i]], sizeof(in));
|
||||
D3D12_SHADER_BYTECODE out = in;
|
||||
hr = gate.admit("stream", names[i], in, out);
|
||||
if (SUCCEEDED(hr)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
|
||||
}
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
|
||||
admitted.pPipelineStateSubobjectStream = stream.data();
|
||||
if (SUCCEEDED(hr)) hr = device->CreatePipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_pipeline_state(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePipelineState");
|
||||
return create_stream(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
bool bx_xbox_pipeline_is_null(ID3D12PipelineState* title) {
|
||||
bool is_null = false;
|
||||
host_pipeline(title, &is_null);
|
||||
return is_null;
|
||||
}
|
||||
|
||||
void bx_xbox_pipeline_forget(IUnknown* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
erase(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
|
||||
}
|
||||
|
||||
void bx_xbox_list_forget(IUnknown* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
erase(g_lists, g_list_count, static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineState");
|
||||
return create_compute(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateGraphicsPipelineState");
|
||||
return create_graphics(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state_x(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
|
||||
UINT extended_count, const void*, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineStateX");
|
||||
log_extended("CreateComputePipelineStateX", extended_count);
|
||||
return create_compute(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state_x(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
|
||||
UINT extended_count, const void*, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateGraphicsPipelineStateX");
|
||||
log_extended("CreateGraphicsPipelineStateX", extended_count);
|
||||
return create_graphics(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12PipelineState* pso) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetPipelineState");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
bool is_null = false;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
|
||||
set_list_null(list, is_null);
|
||||
if (!is_null) list->SetPipelineState(host);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Reset");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
bool is_null = false;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
|
||||
set_list_null(list, is_null);
|
||||
bx_xbox_gpu_writes_reset(list);
|
||||
return list->Reset(bx_xbox_unwrap_as(allocator), host);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UINT instances, UINT first_vertex,
|
||||
UINT first_instance) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawInstanced");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (!list_skips(list, "DrawInstanced")) list->DrawInstanced(vertices, instances, first_vertex, first_instance);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indices, UINT instances, UINT first_index,
|
||||
INT base_vertex, UINT first_instance) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawIndexedInstanced");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (!list_skips(list, "DrawIndexedInstanced")) {
|
||||
list->DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance);
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Dispatch");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (!list_skips(list, "Dispatch")) list->Dispatch(x, y, z);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSignature* signature, UINT max_commands,
|
||||
ID3D12Resource* arguments, UINT64 arguments_offset,
|
||||
ID3D12Resource* count, UINT64 count_offset) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "ExecuteIndirect");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (list_skips(list, "ExecuteIndirect")) return;
|
||||
list->ExecuteIndirect(bx_xbox_unwrap_as(signature), max_commands, bx_xbox_unwrap_as(arguments), arguments_offset,
|
||||
bx_xbox_unwrap_as(count), count_offset);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
|
||||
ID3D12RootSignature* root, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommandSignature");
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
// D3D12XBOX_INDIRECT_ARGUMENT_TYPE_* values start at 100 and have no PC equivalent, except
|
||||
// DISPATCH_SINGLE / DISPATCH_L2 (105): a dispatch whose arguments are D3D12_DISPATCH_ARGUMENTS
|
||||
// and whose D3D12XBOX_DISPATCH_FLAGS are a direct parameter (authorized GDK documentation), so
|
||||
// the host gets D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH. The flags are cache hints and are dropped.
|
||||
constexpr int kFirstXboxArgument = 100;
|
||||
constexpr int kXboxDispatchSingle = 105;
|
||||
constexpr UINT kMaxArguments = 32;
|
||||
D3D12_INDIRECT_ARGUMENT_DESC host_args[kMaxArguments] = {};
|
||||
char types[160] = {};
|
||||
size_t used = 0;
|
||||
bool console_only = desc->NumArgumentDescs > kMaxArguments;
|
||||
for (UINT i = 0; i < desc->NumArgumentDescs && i < kMaxArguments && desc->pArgumentDescs; ++i) {
|
||||
const int type = static_cast<int>(desc->pArgumentDescs[i].Type);
|
||||
host_args[i] = desc->pArgumentDescs[i];
|
||||
if (type == kXboxDispatchSingle) {
|
||||
host_args[i] = {};
|
||||
host_args[i].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
|
||||
} else if (type >= kFirstXboxArgument) {
|
||||
console_only = true;
|
||||
}
|
||||
if (used < sizeof(types) - 8) used += std::snprintf(types + used, sizeof(types) - used, "%s%d", i ? "," : "", type);
|
||||
}
|
||||
D3D12_COMMAND_SIGNATURE_DESC host_desc = *desc;
|
||||
host_desc.pArgumentDescs = host_args;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
HRESULT hr = console_only ? E_NOTIMPL
|
||||
: device->CreateCommandSignature(&host_desc, bx_xbox_unwrap_as(root), riid, ppv);
|
||||
char detail[256];
|
||||
std::snprintf(detail, sizeof(detail), "stride=%u args=[%s] root_signature=%d hr=0x%08lx%s", desc->ByteStride, types,
|
||||
root ? 1 : 0, static_cast<unsigned long>(hr), console_only ? " (console argument types)" : "");
|
||||
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "command_signature", detail);
|
||||
return SUCCEEDED(hr) ? bx_xbox_wrap_result(hr, riid, ppv) : hr;
|
||||
}
|
||||
|
||||
namespace {
|
||||
void log_once(std::atomic<bool>& flag, const char* event, const char* detail) {
|
||||
if (!flag.exchange(true)) bx_log_emit(BX_LOG_INFO, "d3d12_xs", event, detail);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset_x(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso,
|
||||
UINT flags) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "ResetX");
|
||||
static std::atomic<bool> logged{false};
|
||||
if (flags) log_once(logged, "reset_x_flags", "D3D12XBOX_COMMAND_LIST_RESET_FLAGS have no host meaning; ignored");
|
||||
return bx_xbox_list_reset(self, allocator, pso);
|
||||
}
|
||||
|
||||
// Console cache synchronisation points. The closest host D3D12 operation is a global UAV
|
||||
// barrier: all prior UAV work completes before later work starts.
|
||||
void STDMETHODCALLTYPE bx_xbox_list_sync_x(void* self, UINT, UINT, D3D12_GPU_VIRTUAL_ADDRESS, SIZE_T) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SyncTopOfPipeX/SyncBottomOfPipeX");
|
||||
static std::atomic<bool> logged{false};
|
||||
log_once(logged, "sync_x", "SyncTopOfPipeX/SyncBottomOfPipeX recorded as a global UAV barrier");
|
||||
D3D12_RESOURCE_BARRIER barrier{};
|
||||
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResourceBarrier(1, &barrier);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void*, void* callback, UINT64) {
|
||||
BX_D3D_TRACE("XboxCommandAllocator", "SetAllocatorCallbackX");
|
||||
static std::atomic<bool> logged{false};
|
||||
if (callback) {
|
||||
log_once(logged, "allocator_callback_x",
|
||||
"SetAllocatorCallbackX accepted; host command lists do not allocate from title memory, so it is never called");
|
||||
}
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
/*
|
||||
* DeserializeGraphics/ComputePipelineStateX create a pipeline from a serialized console pipeline
|
||||
* (console shader code), which has no host form. They fail with E_NOTIMPL (logged as a refused
|
||||
* pipeline); in null-render mode they return a null pipeline like any other refused pipeline.
|
||||
*/
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void*, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeGraphicsPipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized graphics (console code)", riid, ppv);
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void*, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeComputePipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized compute (console code)", riid, ppv);
|
||||
}
|
||||
|
||||
/*
|
||||
* CreateDerived{Graphics,Compute}PipelineStateX: a pipeline equal to `source` with some state
|
||||
* groups replaced. Derived from a null pipeline, the result is a null pipeline too. Deriving
|
||||
* from a host pipeline needs its creation description, which this layer does not keep yet: that
|
||||
* case is refused (logged) and, in null-render mode, is a null pipeline as well.
|
||||
*/
|
||||
namespace {
|
||||
HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv, const char* kind) {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
const bool from_null = bx_xbox_pipeline_is_null(source);
|
||||
if (!from_null) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 4) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_derived",
|
||||
"deriving from a host pipeline is not implemented (its creation description is not kept)");
|
||||
}
|
||||
}
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, kind, riid, ppv);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDerivedGraphicsPipelineStateX");
|
||||
return derived(self, source, riid, ppv, "derived graphics");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDerivedComputePipelineStateX");
|
||||
return derived(self, source, riid, ppv, "derived compute");
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
/*
|
||||
* Resources placed at a title-chosen GPU virtual address (ADR 0009, "translation by copy").
|
||||
*
|
||||
* On the console a title maps its own physical pages at an address and places resources there
|
||||
* with ID3D12Device::CreatePlacedResourceX / CreatePlacedResourceX1; CPU and GPU see the same
|
||||
* memory. D3DMetal cannot create a resource over existing memory (the existing-memory imports
|
||||
* measured for #473 return E_NOTIMPL), so each such resource gets a shadow resource on the host:
|
||||
*
|
||||
* - a buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's
|
||||
* memory when it is created;
|
||||
* - a texture gets a committed texture whose contents are not filled (logged); texture
|
||||
* contents need the console tiling translation (xg_xs) first.
|
||||
*
|
||||
* The title's address and the shadow are recorded, and the resource reports the title's address
|
||||
* from GetGPUVirtualAddress. Keeping the shadow in step with later CPU writes, and translating
|
||||
* title addresses in GPU calls, are not done yet; both are logged when reached.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
|
||||
extern "C" __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
|
||||
|
||||
namespace {
|
||||
|
||||
struct Shadow {
|
||||
ID3D12Resource* host; // owned by the Xbox object, or (implicit shadows) by this table
|
||||
uint64_t title_va;
|
||||
uint64_t size;
|
||||
bool buffer;
|
||||
D3D12_RESOURCE_DESC desc;
|
||||
ULONGLONG title_attributes; // non-zero: title_va came from XMemAlloc and is freed with the resource
|
||||
int mapped = 0; // outstanding Map calls on title memory (buffers)
|
||||
};
|
||||
|
||||
// Copies between a buffer's title memory and its host resource, when the host is CPU-mappable.
|
||||
bool copy_buffer(const Shadow& s, bool to_host, uint64_t begin, uint64_t end) {
|
||||
if (!s.buffer || end <= begin || end > s.size) return false;
|
||||
void* mapped = nullptr;
|
||||
const D3D12_RANGE none{0, 0};
|
||||
if (FAILED(s.host->Map(0, to_host ? &none : nullptr, &mapped)) || !mapped) return false;
|
||||
auto* host = static_cast<uint8_t*>(mapped) + begin;
|
||||
auto* title = reinterpret_cast<uint8_t*>(s.title_va) + begin;
|
||||
if (to_host) std::memcpy(host, title, static_cast<size_t>(end - begin));
|
||||
else std::memcpy(title, host, static_cast<size_t>(end - begin));
|
||||
const D3D12_RANGE written{static_cast<SIZE_T>(begin), static_cast<SIZE_T>(end)};
|
||||
s.host->Unmap(0, to_host ? &written : &none);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::mutex g_lock;
|
||||
Shadow* g_shadows = nullptr;
|
||||
size_t g_count = 0;
|
||||
size_t g_capacity = 0;
|
||||
|
||||
bool remember(const Shadow& shadow) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (g_count == g_capacity) {
|
||||
const size_t capacity = g_capacity ? g_capacity * 2 : 64;
|
||||
auto* grown = new (std::nothrow) Shadow[capacity];
|
||||
if (!grown) return false;
|
||||
if (g_count) std::memcpy(grown, g_shadows, g_count * sizeof(Shadow));
|
||||
delete[] g_shadows;
|
||||
g_shadows = grown;
|
||||
g_capacity = capacity;
|
||||
}
|
||||
g_shadows[g_count++] = shadow;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool readable(const void* p, uint64_t size) {
|
||||
auto cursor = reinterpret_cast<uintptr_t>(p);
|
||||
const uintptr_t end = cursor + size;
|
||||
while (cursor < end) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(cursor), ®ion, sizeof(region)) || region.State != MEM_COMMIT
|
||||
|| (region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
|
||||
return false;
|
||||
}
|
||||
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc, const char* method,
|
||||
ID3D12Resource** out) {
|
||||
*out = nullptr;
|
||||
const bool buffer = desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
if (buffer) {
|
||||
heap.Type = D3D12_HEAP_TYPE_CUSTOM;
|
||||
heap.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
|
||||
heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
} else {
|
||||
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
}
|
||||
D3D12_RESOURCE_DESC host_desc = desc;
|
||||
// Console tiling layouts and D3D12XBOX_RESOURCE_FLAG_* bits have no PC meaning.
|
||||
constexpr UINT kPcResourceFlags = 0x1FF;
|
||||
host_desc.Layout = buffer ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN;
|
||||
host_desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(desc.Flags & kPcResourceFlags);
|
||||
ID3D12Resource* resource = nullptr;
|
||||
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON,
|
||||
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
|
||||
char detail[224];
|
||||
std::snprintf(detail, sizeof(detail), "%s title_va=0x%llx dim=%d width=%llu height=%u format=%d hr=0x%08lx",
|
||||
method, static_cast<unsigned long long>(title_va), static_cast<int>(desc.Dimension),
|
||||
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<int>(desc.Format),
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(SUCCEEDED(hr) ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", detail);
|
||||
if (FAILED(hr) || !resource) return FAILED(hr) ? hr : E_FAIL;
|
||||
|
||||
const auto* title = reinterpret_cast<const void*>(title_va);
|
||||
if (buffer) {
|
||||
void* mapped = nullptr;
|
||||
if (SUCCEEDED(resource->Map(0, nullptr, &mapped)) && mapped) {
|
||||
if (readable(title, desc.Width)) {
|
||||
std::memcpy(mapped, title, static_cast<size_t>(desc.Width));
|
||||
} else {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", "title memory not readable; shadow left zeroed");
|
||||
}
|
||||
resource->Unmap(0, nullptr);
|
||||
}
|
||||
} else {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "CreatePlacedResourceX(texture contents)");
|
||||
}
|
||||
if (!remember({resource, title_va, desc.Width, buffer, desc, 0})) {
|
||||
resource->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*out = resource;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT create_shadow(void* self, uint64_t title_va, const D3D12_RESOURCE_DESC& desc, REFIID riid, void** ppv,
|
||||
const char* method) {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
ID3D12Resource* resource = nullptr;
|
||||
const HRESULT hr = make_shadow(bx_xbox_host<ID3D12Device>(self), title_va, desc, method, &resource);
|
||||
if (FAILED(hr)) return hr;
|
||||
*ppv = resource;
|
||||
return bx_xbox_wrap_result(S_OK, riid, ppv);
|
||||
}
|
||||
|
||||
bool same_shape(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) {
|
||||
return a.Dimension == b.Dimension && a.Width == b.Width && a.Height == b.Height &&
|
||||
a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels == b.MipLevels && a.Format == b.Format;
|
||||
}
|
||||
|
||||
// A view of placed memory with no resource object: reuse the shadow made for the same address
|
||||
// and shape, or make one. These shadows live for the rest of the process (logged).
|
||||
ID3D12Resource* implicit_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc) {
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_shadows[i].title_va == title_va && same_shape(g_shadows[i].desc, desc)) return g_shadows[i].host;
|
||||
}
|
||||
}
|
||||
ID3D12Resource* resource = nullptr;
|
||||
return SUCCEEDED(make_shadow(device, title_va, desc, "implicit shadow for a placed view", &resource)) ? resource : nullptr;
|
||||
}
|
||||
|
||||
// The Xbox view descriptions start with the PC description's 40 bytes; ResourceLocation follows.
|
||||
constexpr size_t kPcViewDescBytes = 40;
|
||||
static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == kPcViewDescBytes, "PC SRV description size");
|
||||
static_assert(sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == kPcViewDescBytes, "PC UAV description size");
|
||||
|
||||
uint64_t view_location(const void* xbox_desc) {
|
||||
uint64_t va = 0;
|
||||
std::memcpy(&va, static_cast<const char*>(xbox_desc) + kPcViewDescBytes, sizeof(va));
|
||||
return va;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
|
||||
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedResourceX");
|
||||
if (!desc || !location) return E_INVALIDARG;
|
||||
return create_shadow(self, location, *desc, riid, ppv, "CreatePlacedResourceX");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x1(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
|
||||
const D3D12_RESOURCE_DESC1* desc1, UINT,
|
||||
const D3D12_CLEAR_VALUE*, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedResourceX1");
|
||||
if (!desc1 || !location) return E_INVALIDARG;
|
||||
// D3D12_RESOURCE_DESC1 is D3D12_RESOURCE_DESC followed by SamplerFeedbackMipRegion.
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
std::memcpy(&desc, desc1, sizeof(desc));
|
||||
return create_shadow(self, location, desc, riid, ppv, "CreatePlacedResourceX1");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedRawShaderResourceViewX");
|
||||
if (!resource_desc || !xbox_desc) return;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
ID3D12Resource* resource = implicit_shadow(device, view_location(xbox_desc), *resource_desc);
|
||||
if (!resource) return;
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
|
||||
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
device->CreateShaderResourceView(resource, &pc, bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedRawUnorderedAccessViewX");
|
||||
if (!resource_desc || !xbox_desc) return;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
ID3D12Resource* resource = implicit_shadow(device, view_location(xbox_desc), *resource_desc);
|
||||
if (!resource) return;
|
||||
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
|
||||
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
device->CreateUnorderedAccessView(resource, nullptr, &pc, bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedShaderResourceViewX");
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
|
||||
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as(resource), xbox_desc ? &pc : nullptr,
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedUnorderedAccessViewX");
|
||||
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
|
||||
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateUnorderedAccessView(bx_xbox_unwrap_as(resource), nullptr,
|
||||
xbox_desc ? &pc : nullptr, bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title) {
|
||||
if (!title) return title;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
const Shadow& s = g_shadows[i];
|
||||
if (title >= s.title_va && title < s.title_va + s.size) return s.host->GetGPUVirtualAddress() + (title - s.title_va);
|
||||
}
|
||||
return title; // not a title address this layer knows: a host address already, or untranslated
|
||||
}
|
||||
|
||||
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes) {
|
||||
return remember({host, title_va, size, host->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER, host->GetDesc(),
|
||||
attributes});
|
||||
}
|
||||
|
||||
void bx_xbox_placed_forget(IUnknown* host) {
|
||||
Shadow gone{};
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (static_cast<IUnknown*>(g_shadows[i].host) == host) {
|
||||
gone = g_shadows[i];
|
||||
g_shadows[i] = g_shadows[--g_count];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (gone.title_attributes) XMemFree(reinterpret_cast<void*>(gone.title_va), gone.title_attributes);
|
||||
}
|
||||
|
||||
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_resource_get_gpu_virtual_address(void* self) {
|
||||
BX_D3D_TRACE("XboxResource", "GetGPUVirtualAddress");
|
||||
auto* host = bx_xbox_host<ID3D12Resource>(self);
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_shadows[i].host == host) return g_shadows[i].title_va;
|
||||
}
|
||||
}
|
||||
return host->GetGPUVirtualAddress();
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
/*
|
||||
* Page pools (RegisterPagePoolX / UnregisterPagePoolX, authorized GDK documentation): a title
|
||||
* registers a 64 KB-aligned, fully mapped range of its graphics memory as the source of later
|
||||
* CopyPageMappingsX calls. Registration is validated and recorded; the handle is the record.
|
||||
* CopyPageMappingsX itself (a queue method) is not implemented yet and stays a logged stub.
|
||||
*/
|
||||
namespace {
|
||||
|
||||
struct PagePool {
|
||||
uint64_t address;
|
||||
UINT pages;
|
||||
PagePool* next;
|
||||
};
|
||||
|
||||
PagePool* g_pools = nullptr; // guarded by g_lock
|
||||
|
||||
bool fully_mapped(uint64_t address, uint64_t size) {
|
||||
auto cursor = static_cast<uintptr_t>(address);
|
||||
const uintptr_t end = cursor + static_cast<uintptr_t>(size);
|
||||
while (cursor < end) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(cursor), ®ion, sizeof(region)) || region.State != MEM_COMMIT) {
|
||||
return false;
|
||||
}
|
||||
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_register_page_pool_x(void*, D3D12_GPU_VIRTUAL_ADDRESS address, UINT pages,
|
||||
HANDLE* handle) {
|
||||
BX_D3D_TRACE("XboxDevice", "RegisterPagePoolX");
|
||||
constexpr uint64_t kPage = 64 * 1024;
|
||||
const bool valid = handle && pages && address && (address % kPage) == 0 && fully_mapped(address, pages * kPage);
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "address=0x%llx pages=%u %s", static_cast<unsigned long long>(address), pages,
|
||||
valid ? "registered" : "rejected (unaligned, empty or not fully mapped)");
|
||||
bx_log_emit(valid ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "page_pool", detail);
|
||||
if (!valid) return E_INVALIDARG;
|
||||
auto* pool = new (std::nothrow) PagePool{address, pages, nullptr};
|
||||
if (!pool) return E_OUTOFMEMORY;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
pool->next = g_pools;
|
||||
g_pools = pool;
|
||||
}
|
||||
*handle = pool;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void*, HANDLE handle) {
|
||||
BX_D3D_TRACE("XboxDevice", "UnregisterPagePoolX");
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (PagePool** link = &g_pools; *link; link = &(*link)->next) {
|
||||
if (*link == handle) {
|
||||
PagePool* gone = *link;
|
||||
*link = gone->next;
|
||||
delete gone;
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
/*
|
||||
* Map on a resource that has title-visible memory (placed at a title address, or committed with
|
||||
* XMemAlloc memory) returns that memory, as on the console, where CPU and GPU share it. Other
|
||||
* resources map their host resource. Writes through the title pointer reach the host resource
|
||||
* only where this layer copies them (buffers at creation; texture contents are not copied yet,
|
||||
* logged at creation).
|
||||
*/
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subresource, const D3D12_RANGE* read, void** data) {
|
||||
BX_D3D_TRACE("XboxResource", "Map");
|
||||
auto* host = bx_xbox_host<ID3D12Resource>(self);
|
||||
uint64_t title_va = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
Shadow& s = g_shadows[i];
|
||||
if (s.host != host) continue;
|
||||
title_va = s.title_va;
|
||||
// Make GPU results visible: refresh the read range of title memory from the host.
|
||||
const uint64_t begin = read ? read->Begin : 0, end = read ? read->End : s.size;
|
||||
if (s.buffer && end > begin) copy_buffer(s, false, begin, end < s.size ? end : s.size);
|
||||
++s.mapped;
|
||||
}
|
||||
}
|
||||
if (!title_va) {
|
||||
const HRESULT hr = host->Map(subresource, read, data);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxResource", "Map", hr);
|
||||
return hr;
|
||||
}
|
||||
if (subresource != 0) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 4) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "title_memory_map",
|
||||
"Map of a non-zero subresource of title memory returns the resource base");
|
||||
}
|
||||
}
|
||||
if (data) *data = reinterpret_cast<void*>(title_va);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
extern "C" void STDMETHODCALLTYPE bx_xbox_resource_unmap(void* self, UINT subresource, const D3D12_RANGE* written) {
|
||||
BX_D3D_TRACE("XboxResource", "Unmap");
|
||||
auto* host = bx_xbox_host<ID3D12Resource>(self);
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
Shadow& s = g_shadows[i];
|
||||
if (s.host != host) continue;
|
||||
// Hand the CPU's writes to the host resource (a null range means all of it).
|
||||
const uint64_t begin = written ? written->Begin : 0, end = written ? written->End : s.size;
|
||||
if (s.buffer && end > begin) copy_buffer(s, true, begin, end < s.size ? end : s.size);
|
||||
if (s.mapped > 0) --s.mapped;
|
||||
return;
|
||||
}
|
||||
}
|
||||
host->Unmap(subresource, written);
|
||||
}
|
||||
|
||||
/*
|
||||
* Before a submission, buffers the title keeps mapped (persistent maps) are copied from title
|
||||
* memory to their host resources, up to 16 MB each; larger ones are logged once and not copied.
|
||||
*/
|
||||
void bx_xbox_sync_mapped_buffers() {
|
||||
constexpr uint64_t kLimit = 16ull << 20;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
const Shadow& s = g_shadows[i];
|
||||
if (!s.mapped || !s.buffer) continue;
|
||||
if (s.size > kLimit) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 4) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "persistently mapped buffer of %llu bytes not copied to the host before submit",
|
||||
static_cast<unsigned long long>(s.size));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "title_memory_sync", detail);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
copy_buffer(s, true, 0, s.size);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
#include "presentx.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <new>
|
||||
|
||||
#include "proxy.h"
|
||||
|
||||
/*
|
||||
* Track C (M2-C2, #465). See presentx.h for the contract and for what this is not.
|
||||
* Host DXGI is loaded on demand, like the host d3d12.dll in d3d12_xs.cpp.
|
||||
*/
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr HRESULT kWaitTimedOut = static_cast<HRESULT>(0x800705B4u); /* HRESULT_FROM_WIN32(ERROR_TIMEOUT) */
|
||||
|
||||
bool is_device_removed_hr(HRESULT hr) {
|
||||
return hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_HUNG ||
|
||||
hr == DXGI_ERROR_DEVICE_RESET || hr == DXGI_ERROR_DRIVER_INTERNAL_ERROR;
|
||||
}
|
||||
|
||||
void log_hr(bx_log_level_t level, const char* event, const char* what, HRESULT hr) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s hr=0x%08lx", what, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(level, "d3d12_xs", event, detail);
|
||||
}
|
||||
|
||||
/* Releases an already acquired lock and records its owner, so re-entry can be refused. */
|
||||
class SrwOwner {
|
||||
public:
|
||||
SrwOwner(SRWLOCK& lock, std::atomic<DWORD>& owner) : lock_(lock), owner_(owner) { owner_ = GetCurrentThreadId(); }
|
||||
~SrwOwner() {
|
||||
owner_ = 0;
|
||||
ReleaseSRWLockExclusive(&lock_);
|
||||
}
|
||||
SrwOwner(const SrwOwner&) = delete;
|
||||
SrwOwner& operator=(const SrwOwner&) = delete;
|
||||
|
||||
private:
|
||||
SRWLOCK& lock_;
|
||||
std::atomic<DWORD>& owner_;
|
||||
};
|
||||
|
||||
class BxPresentSwapChain final : public IBxPresentSwapChain {
|
||||
public:
|
||||
/* `queue_proxy` is referenced for the lifetime of the chain; `host_queue` is its host object. */
|
||||
static HRESULT create(ID3D12CommandQueue* queue_proxy, ID3D12CommandQueue* host_queue, HWND window,
|
||||
const BxPresentDesc& desc, IBxPresentSwapChain** out);
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override;
|
||||
ULONG STDMETHODCALLTYPE AddRef() override;
|
||||
ULONG STDMETHODCALLTYPE Release() override;
|
||||
|
||||
HRESULT STDMETHODCALLTYPE GetBuffer(UINT index, REFIID riid, void** ppv) override;
|
||||
UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() override;
|
||||
HRESULT STDMETHODCALLTYPE Present(UINT sync_interval, UINT flags) override;
|
||||
HRESULT STDMETHODCALLTYPE WaitForIdle(DWORD timeout_ms) override;
|
||||
HRESULT STDMETHODCALLTYPE GetHostSwapChain(REFIID riid, void** ppv) override;
|
||||
|
||||
private:
|
||||
BxPresentSwapChain() = default;
|
||||
~BxPresentSwapChain() = default;
|
||||
|
||||
HRESULT init(HWND window, const BxPresentDesc& desc);
|
||||
HRESULT signal_locked(UINT64* value);
|
||||
HRESULT wait_locked(UINT64 value, ULONGLONG start, DWORD timeout_ms);
|
||||
HRESULT idle_locked(ULONGLONG start, DWORD timeout_ms);
|
||||
HRESULT post_present_failure(const char* event, const char* what, HRESULT hr, HRESULT live_device_result);
|
||||
HRESULT removed_reason();
|
||||
void destroy();
|
||||
|
||||
std::atomic<ULONG> refs_{1};
|
||||
SRWLOCK lock_ = SRWLOCK_INIT; /* guards the fence counter, the event and Present */
|
||||
ID3D12CommandQueue* queue_proxy_ = nullptr;
|
||||
ID3D12CommandQueue* host_queue_ = nullptr;
|
||||
HWND window_ = nullptr;
|
||||
IDXGISwapChain3* swap_ = nullptr;
|
||||
ID3D12Fence* fence_ = nullptr;
|
||||
HANDLE event_ = nullptr;
|
||||
std::atomic<DWORD> owner_{0}; /* thread holding lock_ */
|
||||
UINT64 last_signaled_ = 0;
|
||||
UINT64 presented_ = 0;
|
||||
bool needs_idle_ = false; /* post-present signal or wait failed; only an idle queue clears this */
|
||||
UINT64 buffer_value_[DXGI_MAX_SWAP_CHAIN_BUFFERS] = {};
|
||||
};
|
||||
|
||||
HRESULT BxPresentSwapChain::create(ID3D12CommandQueue* queue_proxy, ID3D12CommandQueue* host_queue, HWND window,
|
||||
const BxPresentDesc& desc, IBxPresentSwapChain** out) {
|
||||
auto* self = new (std::nothrow) BxPresentSwapChain();
|
||||
if (!self) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
queue_proxy->AddRef();
|
||||
self->queue_proxy_ = queue_proxy;
|
||||
host_queue->AddRef();
|
||||
self->host_queue_ = host_queue;
|
||||
self->window_ = window;
|
||||
|
||||
HRESULT hr = self->init(window, desc);
|
||||
if (FAILED(hr)) {
|
||||
self->destroy(); /* nothing was submitted, so every partially created object can go */
|
||||
return hr;
|
||||
}
|
||||
*out = self;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::init(HWND window, const BxPresentDesc& desc) {
|
||||
static HMODULE dxgi = LoadLibraryA("dxgi.dll");
|
||||
using CreateFactoryFn = HRESULT(WINAPI*)(REFIID, void**);
|
||||
auto create_factory = dxgi
|
||||
? reinterpret_cast<CreateFactoryFn>(reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory1")))
|
||||
: nullptr;
|
||||
if (!create_factory) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_dxgi_missing", "dxgi.dll!CreateDXGIFactory1 not available");
|
||||
return DXGI_ERROR_UNSUPPORTED;
|
||||
}
|
||||
|
||||
IDXGIFactory4* factory = nullptr;
|
||||
HRESULT hr = create_factory(__uuidof(IDXGIFactory4), reinterpret_cast<void**>(&factory));
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateDXGIFactory1", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
DXGI_SWAP_CHAIN_DESC1 sd = {};
|
||||
sd.Width = desc.width;
|
||||
sd.Height = desc.height;
|
||||
sd.Format = desc.format;
|
||||
sd.SampleDesc.Count = 1;
|
||||
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
|
||||
sd.BufferCount = desc.buffer_count;
|
||||
sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
|
||||
|
||||
IDXGISwapChain1* swap1 = nullptr;
|
||||
/* For D3D12 the "device" argument of CreateSwapChainForHwnd is the command queue. */
|
||||
hr = factory->CreateSwapChainForHwnd(host_queue_, window, &sd, nullptr, nullptr, &swap1);
|
||||
if (SUCCEEDED(hr)) {
|
||||
/* Alt+Enter would require ResizeBuffers handling that the bridge does not have. */
|
||||
HRESULT assoc = factory->MakeWindowAssociation(window, DXGI_MWA_NO_ALT_ENTER);
|
||||
if (FAILED(assoc)) {
|
||||
log_hr(BX_LOG_WARN, "present_window_association", "MakeWindowAssociation", assoc);
|
||||
}
|
||||
}
|
||||
factory->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateSwapChainForHwnd", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
hr = swap1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void**>(&swap_));
|
||||
swap1->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "QueryInterface(IDXGISwapChain3)", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
ID3D12Device* device = nullptr;
|
||||
hr = host_queue_->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence_));
|
||||
device->Release();
|
||||
}
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateFence", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
event_ = CreateEventA(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!event_) {
|
||||
hr = HRESULT_FROM_WIN32(GetLastError());
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateEvent", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "width=%u height=%u format=%d buffers=%u",
|
||||
desc.width, desc.height, static_cast<int>(desc.format), desc.buffer_count);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "present_chain_created", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::removed_reason() {
|
||||
ID3D12Device* device = nullptr;
|
||||
HRESULT hr = host_queue_->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (FAILED(hr)) {
|
||||
return hr;
|
||||
}
|
||||
hr = device->GetDeviceRemovedReason();
|
||||
device->Release();
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::signal_locked(UINT64* value) {
|
||||
const UINT64 next = last_signaled_ + 1;
|
||||
HRESULT hr = host_queue_->Signal(fence_, next);
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_signal_failed", "ID3D12CommandQueue::Signal", hr);
|
||||
return hr;
|
||||
}
|
||||
last_signaled_ = next;
|
||||
*value = next;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::wait_locked(UINT64 value, ULONGLONG start, DWORD timeout_ms) {
|
||||
for (;;) {
|
||||
const UINT64 completed = fence_->GetCompletedValue();
|
||||
if (completed == UINT64_MAX) { /* the documented value after device removal */
|
||||
HRESULT reason = removed_reason();
|
||||
log_hr(BX_LOG_ERROR, "present_device_removed", "fence", reason);
|
||||
return FAILED(reason) ? reason : DXGI_ERROR_DEVICE_REMOVED;
|
||||
}
|
||||
if (completed >= value) {
|
||||
return S_OK;
|
||||
}
|
||||
const ULONGLONG elapsed = GetTickCount64() - start;
|
||||
if (elapsed >= timeout_ms) {
|
||||
break;
|
||||
}
|
||||
HRESULT hr = fence_->SetEventOnCompletion(value, event_);
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_wait_failed", "SetEventOnCompletion", hr);
|
||||
return hr;
|
||||
}
|
||||
const ULONGLONG elapsed_after_registration = GetTickCount64() - start;
|
||||
if (elapsed_after_registration >= timeout_ms) {
|
||||
continue; /* Recheck the fence before reporting a timeout. */
|
||||
}
|
||||
/* The event can be left over from an earlier timed-out wait, so the loop re-reads the fence. */
|
||||
DWORD waited = WaitForSingleObject(event_, static_cast<DWORD>(timeout_ms - elapsed_after_registration));
|
||||
if (waited == WAIT_FAILED) {
|
||||
hr = HRESULT_FROM_WIN32(GetLastError());
|
||||
log_hr(BX_LOG_ERROR, "present_wait_failed", "WaitForSingleObject", hr);
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "timeout_ms=%lu wanted=%llu completed=%llu", static_cast<unsigned long>(timeout_ms),
|
||||
static_cast<unsigned long long>(value), static_cast<unsigned long long>(fence_->GetCompletedValue()));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", detail);
|
||||
return kWaitTimedOut;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::post_present_failure(const char* event, const char* what, HRESULT hr,
|
||||
HRESULT live_device_result) {
|
||||
const HRESULT removed = removed_reason();
|
||||
if (FAILED(removed)) {
|
||||
log_hr(BX_LOG_ERROR, "present_device_removed", what, removed);
|
||||
return removed;
|
||||
}
|
||||
needs_idle_ = true;
|
||||
if (event) {
|
||||
log_hr(BX_LOG_ERROR, event, what, hr);
|
||||
}
|
||||
if (is_device_removed_hr(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_device_removed", what, hr);
|
||||
return hr;
|
||||
}
|
||||
return live_device_result;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::idle_locked(ULONGLONG start, DWORD timeout_ms) {
|
||||
if (GetTickCount64() - start >= timeout_ms) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "timeout_ms=%lu wanted=%llu completed=unknown; expired before Signal",
|
||||
static_cast<unsigned long>(timeout_ms), static_cast<unsigned long long>(last_signaled_ + 1));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", detail);
|
||||
return kWaitTimedOut;
|
||||
}
|
||||
UINT64 value = 0;
|
||||
HRESULT hr = signal_locked(&value);
|
||||
return FAILED(hr) ? hr : wait_locked(value, start, timeout_ms);
|
||||
}
|
||||
|
||||
void BxPresentSwapChain::destroy() {
|
||||
if (swap_ && fence_ && event_) {
|
||||
HRESULT idle = idle_locked(GetTickCount64(), BX_PRESENT_WAIT_MS);
|
||||
if (FAILED(idle) && SUCCEEDED(removed_reason())) {
|
||||
/* The device is alive and the GPU may still be using the back buffers. */
|
||||
log_hr(BX_LOG_ERROR, "present_chain_leaked", "queue not idle; GPU-visible objects deliberately not released", idle);
|
||||
/*
|
||||
* swap_, fence_, event_ and host_queue_ stay: pending work may touch them. The proxy
|
||||
* is only BetterXen's wrapper; host_queue_ keeps the host queue alive without it.
|
||||
*/
|
||||
ID3D12CommandQueue* proxy = queue_proxy_;
|
||||
delete this;
|
||||
proxy->Release();
|
||||
return;
|
||||
}
|
||||
}
|
||||
const bool had_swap = swap_ != nullptr;
|
||||
ULONG swap_refs = 0;
|
||||
if (swap_) swap_refs = swap_->Release();
|
||||
if (fence_) fence_->Release();
|
||||
if (event_) CloseHandle(event_);
|
||||
if (had_swap) {
|
||||
/*
|
||||
* The count the host's Release returned. Non-zero means something else still references
|
||||
* the swapchain: back buffers or host pointers the caller holds, or the host itself
|
||||
* (see docs/research/d3dmetal-swapchain-references.md). It is reported, never "fixed up"
|
||||
* by releasing references this object does not own.
|
||||
*/
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "presented=%llu swapchain_release_returned=%lu",
|
||||
static_cast<unsigned long long>(presented_), static_cast<unsigned long>(swap_refs));
|
||||
bx_log_emit(swap_refs ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "present_chain_destroyed", detail);
|
||||
}
|
||||
ID3D12CommandQueue* host_queue = host_queue_;
|
||||
ID3D12CommandQueue* queue_proxy = queue_proxy_;
|
||||
delete this;
|
||||
if (host_queue) host_queue->Release();
|
||||
if (queue_proxy) queue_proxy->Release();
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::QueryInterface(REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
if (IsEqualGUID(riid, __uuidof(IUnknown)) || IsEqualGUID(riid, IID_IBxPresentSwapChain)) {
|
||||
AddRef();
|
||||
*ppv = static_cast<IBxPresentSwapChain*>(this);
|
||||
return S_OK;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE BxPresentSwapChain::AddRef() {
|
||||
return refs_.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE BxPresentSwapChain::Release() {
|
||||
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (left == 0) {
|
||||
destroy();
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::GetBuffer(UINT index, REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
HRESULT hr = swap_->GetBuffer(index, riid, ppv);
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_WARN, "present_get_buffer_failed", "IDXGISwapChain::GetBuffer", hr);
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
UINT STDMETHODCALLTYPE BxPresentSwapChain::GetCurrentBackBufferIndex() {
|
||||
return swap_->GetCurrentBackBufferIndex();
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::Present(UINT sync_interval, UINT flags) {
|
||||
BX_D3D_TRACE("IBxPresentSwapChain", "Present");
|
||||
if (sync_interval > 4 || flags != 0 || !IsWindow(window_)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "sync=%u flags=0x%x window_alive=%d", sync_interval, flags,
|
||||
IsWindow(window_) ? 1 : 0);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_rejected", detail);
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
if (owner_ == GetCurrentThreadId()) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_rejected", "re-entered on the same thread");
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
/*
|
||||
* Never wait for the lock. Its holder may be inside the host's Present, and DXGI can make that
|
||||
* call wait for the window's thread: the caller here.
|
||||
*/
|
||||
if (!TryAcquireSRWLockExclusive(&lock_)) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_busy", "another call holds the swapchain; nothing presented");
|
||||
return BX_PRESENT_E_BUSY;
|
||||
}
|
||||
SrwOwner guard(lock_, owner_);
|
||||
if (needs_idle_) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_needs_idle", "completion unconfirmed; nothing presented");
|
||||
return BX_PRESENT_E_NEEDS_IDLE;
|
||||
}
|
||||
const UINT presented_index = swap_->GetCurrentBackBufferIndex();
|
||||
if (presented_index < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
|
||||
/* Busy only after an earlier BX_PRESENT_E_NEXT_BUFFER_BUSY. Nothing is presented then. */
|
||||
const HRESULT ready = wait_locked(buffer_value_[presented_index], GetTickCount64(), BX_PRESENT_WAIT_MS);
|
||||
if (FAILED(ready)) {
|
||||
return ready;
|
||||
}
|
||||
}
|
||||
HRESULT hr = swap_->Present(sync_interval, flags);
|
||||
if (FAILED(hr)) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "sync=%u flags=0x%x hr=0x%08lx device_removed_reason=0x%08lx", sync_interval,
|
||||
flags, static_cast<unsigned long>(hr), static_cast<unsigned long>(removed_reason()));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_failed", detail);
|
||||
return hr;
|
||||
}
|
||||
++presented_;
|
||||
|
||||
UINT64 value = 0;
|
||||
HRESULT sync_hr = signal_locked(&value);
|
||||
if (FAILED(sync_hr)) {
|
||||
/* signal_locked already logged present_signal_failed when the device stays live. */
|
||||
return post_present_failure(nullptr, "signal after Present", sync_hr, BX_PRESENT_E_COMPLETION_UNCONFIRMED);
|
||||
}
|
||||
if (presented_index < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
|
||||
buffer_value_[presented_index] = value;
|
||||
}
|
||||
const UINT next = swap_->GetCurrentBackBufferIndex();
|
||||
if (next < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
|
||||
sync_hr = wait_locked(buffer_value_[next], GetTickCount64(), BX_PRESENT_WAIT_MS);
|
||||
if (sync_hr == kWaitTimedOut) {
|
||||
return BX_PRESENT_E_NEXT_BUFFER_BUSY;
|
||||
}
|
||||
if (FAILED(sync_hr)) {
|
||||
return post_present_failure("present_next_buffer_wait_failed", "wait_locked", sync_hr,
|
||||
BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED);
|
||||
}
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::WaitForIdle(DWORD timeout_ms) {
|
||||
if (timeout_ms == 0 || timeout_ms == INFINITE) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (owner_ == GetCurrentThreadId()) {
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
const ULONGLONG start = GetTickCount64();
|
||||
while (!TryAcquireSRWLockExclusive(&lock_)) {
|
||||
if (GetTickCount64() - start >= timeout_ms) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", "swapchain busy in another call");
|
||||
return kWaitTimedOut;
|
||||
}
|
||||
Sleep(1);
|
||||
}
|
||||
SrwOwner guard(lock_, owner_);
|
||||
const HRESULT hr = idle_locked(start, timeout_ms);
|
||||
if (hr == S_OK) {
|
||||
/* A signal queued after every presented frame has completed. */
|
||||
needs_idle_ = false;
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::GetHostSwapChain(REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
return swap_->QueryInterface(riid, ppv);
|
||||
}
|
||||
|
||||
bool desc_is_valid(const BxPresentDesc& d) {
|
||||
const bool format_ok = d.format == DXGI_FORMAT_R8G8B8A8_UNORM || d.format == DXGI_FORMAT_B8G8R8A8_UNORM ||
|
||||
d.format == DXGI_FORMAT_R10G10B10A2_UNORM || d.format == DXGI_FORMAT_R16G16B16A16_FLOAT;
|
||||
return format_ok && d.width >= 1 && d.width <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && d.height >= 1 &&
|
||||
d.height <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && d.buffer_count >= 2 &&
|
||||
d.buffer_count <= DXGI_MAX_SWAP_CHAIN_BUFFERS;
|
||||
}
|
||||
|
||||
/* COM tear-off: its own reference count, one reference on the queue, and the queue's identity. */
|
||||
class BxPresentQueue final : public IBxPresentQueue {
|
||||
public:
|
||||
explicit BxPresentQueue(ID3D12CommandQueue* queue_proxy) : queue_(queue_proxy) { queue_->AddRef(); }
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
if (IsEqualGUID(riid, IID_IBxPresentQueue)) {
|
||||
AddRef();
|
||||
*ppv = static_cast<IBxPresentQueue*>(this);
|
||||
return S_OK;
|
||||
}
|
||||
return queue_->QueryInterface(riid, ppv);
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE AddRef() override { return refs_.fetch_add(1, std::memory_order_relaxed) + 1; }
|
||||
|
||||
ULONG STDMETHODCALLTYPE Release() override {
|
||||
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (left == 0) {
|
||||
ID3D12CommandQueue* queue = queue_;
|
||||
delete this;
|
||||
queue->Release();
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE CreateSwapChain(HWND window, const BxPresentDesc* desc, IBxPresentSwapChain** out) override {
|
||||
if (!out) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*out = nullptr;
|
||||
if (!desc) {
|
||||
return E_POINTER;
|
||||
}
|
||||
if (!window || !IsWindow(window) || !desc_is_valid(*desc)) {
|
||||
log_hr(BX_LOG_WARN, "present_create_rejected", "invalid window or description", DXGI_ERROR_INVALID_CALL);
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
ID3D12CommandQueue* host = nullptr;
|
||||
HRESULT hr = static_cast<IUnknown*>(bx_unwrap_raw(queue_))
|
||||
->QueryInterface(__uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&host));
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "host command queue", hr);
|
||||
return hr;
|
||||
}
|
||||
D3D12_COMMAND_QUEUE_DESC queue_desc = {};
|
||||
host->GetDesc(&queue_desc);
|
||||
if (queue_desc.Type != D3D12_COMMAND_LIST_TYPE_DIRECT) {
|
||||
log_hr(BX_LOG_WARN, "present_create_rejected", "queue is not a DIRECT queue", DXGI_ERROR_INVALID_CALL);
|
||||
hr = DXGI_ERROR_INVALID_CALL;
|
||||
} else {
|
||||
hr = BxPresentSwapChain::create(queue_, host, window, *desc, out);
|
||||
}
|
||||
host->Release();
|
||||
return hr;
|
||||
}
|
||||
|
||||
private:
|
||||
~BxPresentQueue() = default;
|
||||
std::atomic<ULONG> refs_{1};
|
||||
ID3D12CommandQueue* queue_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
HRESULT bx_present_query_queue(ID3D12CommandQueue* queue_proxy, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
auto* bridge = new (std::nothrow) BxPresentQueue(queue_proxy);
|
||||
if (!bridge) {
|
||||
*ppv = nullptr;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*ppv = static_cast<IBxPresentQueue*>(bridge);
|
||||
return S_OK;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
#ifndef BETTERXEN_D3D12_XS_PRESENTX_H
|
||||
#define BETTERXEN_D3D12_XS_PRESENTX_H
|
||||
|
||||
/*
|
||||
* Track C (M2-C2, #465): the PresentX presentation bridge over host DXGI.
|
||||
*
|
||||
* THESE INTERFACES ARE DEFINED BY BETTERXEN. They are not the console's PresentX, whose
|
||||
* signature and structures are not defined in abi/, and no binary compatibility with any Xbox
|
||||
* interface is claimed. A guest that calls a console-only command queue slot still lands on the
|
||||
* proxy's logged stub.
|
||||
*
|
||||
* Use: QueryInterface the command queue returned by a D3D12XboxCreateDevice device for
|
||||
* IID_IBxPresentQueue, then create a swapchain on a Win32 window. No new DLL export is involved.
|
||||
*
|
||||
* This is a subset of the public DXGI flip model, not all of it: the caller records its own
|
||||
* resource transitions and every back buffer must be in D3D12_RESOURCE_STATE_PRESENT when it is
|
||||
* presented. D3D12 offers no way to query a resource's state, so the bridge cannot check this.
|
||||
* ResizeBuffers and fullscreen are not implemented.
|
||||
*/
|
||||
#ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <d3d12.h>
|
||||
#include <dxgi1_4.h>
|
||||
|
||||
/* {34127279-2D93-4642-88A6-97B834217B8A} */
|
||||
inline const GUID IID_IBxPresentQueue = {0x34127279, 0x2d93, 0x4642, {0x88, 0xa6, 0x97, 0xb8, 0x34, 0x21, 0x7b, 0x8a}};
|
||||
/* {DEC9F73E-DE84-4F87-9167-26203B3A1152} */
|
||||
inline const GUID IID_IBxPresentSwapChain = {0xdec9f73e, 0xde84, 0x4f87, {0x91, 0x67, 0x26, 0x20, 0x3b, 0x3a, 0x11, 0x52}};
|
||||
|
||||
/* Longest single GPU wait Present() performs, and the destructor's wait for the GPU. */
|
||||
inline constexpr DWORD BX_PRESENT_WAIT_MS = 5000;
|
||||
/*
|
||||
* Present() result: the frame WAS handed to the host, but the next back buffer is still busy.
|
||||
* Do not present that frame again. Call WaitForIdle until it returns S_OK before reusing a buffer.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_NEXT_BUFFER_BUSY = static_cast<HRESULT>(0x80040201u);
|
||||
/*
|
||||
* Present() result: the frame was NOT handed to the host, because another Present or WaitForIdle
|
||||
* on this swapchain is in progress. Present never waits for that call. Try again after it returns.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_BUSY = static_cast<HRESULT>(0x80040202u);
|
||||
/*
|
||||
* Present() result: the frame WAS handed to the host, but the following fence signal failed on
|
||||
* a live device, so its completion is unknown. Do not present that frame again. Call WaitForIdle
|
||||
* until it returns S_OK before recording to any back buffer or presenting again. Device removal
|
||||
* returns the removal HRESULT unchanged instead.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_COMPLETION_UNCONFIRMED = static_cast<HRESULT>(0x80040203u);
|
||||
/*
|
||||
* Present() result: the frame was NOT handed to the host, because an earlier Present returned
|
||||
* BX_PRESENT_E_COMPLETION_UNCONFIRMED or BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED and no WaitForIdle
|
||||
* has succeeded since.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_NEEDS_IDLE = static_cast<HRESULT>(0x80040204u);
|
||||
/*
|
||||
* Present() result: the frame WAS handed to the host and signaled, but waiting on the next back
|
||||
* buffer failed on a live device (for example SetEventOnCompletion or WaitForSingleObject). Do not
|
||||
* present that frame again. Call WaitForIdle until it returns S_OK before reusing any back buffer
|
||||
* or presenting again. Device removal returns the removal HRESULT unchanged instead.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED = static_cast<HRESULT>(0x80040205u);
|
||||
|
||||
struct BxPresentDesc {
|
||||
UINT width; /* 1..16384; 0 ("use the window size") is not accepted */
|
||||
UINT height; /* 1..16384 */
|
||||
DXGI_FORMAT format; /* R8G8B8A8_UNORM, B8G8R8A8_UNORM, R10G10B10A2_UNORM or R16G16B16A16_FLOAT */
|
||||
UINT buffer_count; /* 2..DXGI_MAX_SWAP_CHAIN_BUFFERS */
|
||||
};
|
||||
|
||||
/*
|
||||
* One swapchain. Holds a reference on the command queue it was created from.
|
||||
* The final Release waits (bounded) for the queue to go idle. If that fails and the device
|
||||
* reports it has not been removed, it logs and deliberately leaks what pending GPU work may
|
||||
* still touch (swapchain, fence, event, host queue) and releases its queue proxy reference.
|
||||
* After device removal everything is released. Time spent inside the host's own Release is not bounded: on the
|
||||
* wined3d/vkd3d path (not D3DMetal) an intermittent stall in it was observed.
|
||||
*/
|
||||
struct IBxPresentSwapChain : public IUnknown {
|
||||
/* Same rules as IDXGISwapChain::GetBuffer. The caller owns the returned reference. */
|
||||
virtual HRESULT STDMETHODCALLTYPE GetBuffer(UINT index, REFIID riid, void** ppv) = 0;
|
||||
virtual UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() = 0;
|
||||
/*
|
||||
* Waits (bounded) until the current back buffer is idle, calls IDXGISwapChain::Present,
|
||||
* signals a fence on the queue, then waits until the next back buffer is idle. It never waits
|
||||
* for another thread's call on this swapchain. Results:
|
||||
* - a DXGI success code, including DXGI_STATUS_OCCLUDED: presented, next buffer idle;
|
||||
* - HRESULT_FROM_WIN32(ERROR_TIMEOUT): NOT presented (the current buffer is still busy);
|
||||
* - BX_PRESENT_E_NEXT_BUFFER_BUSY: presented, see its definition;
|
||||
* - BX_PRESENT_E_BUSY: NOT presented, another call holds the swapchain;
|
||||
* - BX_PRESENT_E_COMPLETION_UNCONFIRMED: presented, the fence signal failed on a live device;
|
||||
* - BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED: presented, waiting on the next back buffer failed
|
||||
* on a live device;
|
||||
* - BX_PRESENT_E_NEEDS_IDLE: NOT presented, WaitForIdle must succeed first;
|
||||
* - another failure: the host's Present failure, a pre-Present fence wait or device failure
|
||||
* (nothing was presented), or a device-removal HRESULT (such as DXGI_ERROR_DEVICE_REMOVED
|
||||
* or DXGI_ERROR_DEVICE_RESET) observed after host Present, returned unchanged. If the
|
||||
* device still reports itself as live, WaitForIdle must succeed before the next Present.
|
||||
* The bounds cover BetterXen's own waits, not time spent inside the host's Present.
|
||||
*
|
||||
* The bridge itself returns DXGI_ERROR_INVALID_CALL, without calling the host, for a
|
||||
* sync_interval above 4, for any flag (none is supported, including DXGI_PRESENT_TEST),
|
||||
* once the window is destroyed, and when Present or WaitForIdle is re-entered on a thread
|
||||
* already inside one of them. D3DMetal 3.0 was observed to answer S_OK to the first three.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE Present(UINT sync_interval, UINT flags) = 0;
|
||||
/*
|
||||
* Waits until everything submitted to the queue before this call has finished. S_OK also ends
|
||||
* the recovery state left by a post-Present synchronization failure on a live device.
|
||||
* Only positive, finite timeouts are supported. Zero and INFINITE return E_INVALIDARG
|
||||
* without signaling. A timeout returns HRESULT_FROM_WIN32(ERROR_TIMEOUT).
|
||||
* Lock acquisition, fence signaling, and fence waiting share timeout_ms; if lock acquisition
|
||||
* uses the whole budget, WaitForIdle times out without signaling. Time spent inside host calls
|
||||
* reduces the remaining wait, but the bridge cannot interrupt those calls.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE WaitForIdle(DWORD timeout_ms) = 0;
|
||||
/*
|
||||
* The host DXGI swapchain, for diagnostics and tests. The caller owns the reference and must
|
||||
* not call Present or ResizeBuffers on it: the bridge's buffer tracking would not follow.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE GetHostSwapChain(REFIID riid, void** ppv) = 0;
|
||||
};
|
||||
|
||||
/* Tear-off on the command queue proxy; QueryInterface for any other IID returns the queue's answer. */
|
||||
struct IBxPresentQueue : public IUnknown {
|
||||
/*
|
||||
* The queue must be a DIRECT queue and `window` an existing window. Argument errors return
|
||||
* E_POINTER or DXGI_ERROR_INVALID_CALL; host failures are returned unchanged and logged.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateSwapChain(HWND window, const BxPresentDesc* desc, IBxPresentSwapChain** out) = 0;
|
||||
};
|
||||
|
||||
/* Internal to d3d12_xs.dll: the command queue proxy answers IID_IBxPresentQueue with this. */
|
||||
HRESULT bx_present_query_queue(ID3D12CommandQueue* queue_proxy, void** ppv);
|
||||
|
||||
#endif /* BETTERXEN_D3D12_XS_PRESENTX_H */
|
||||
@@ -0,0 +1,350 @@
|
||||
/*
|
||||
* ID3D12CommandQueue::PresentX as titles call it on the Xbox-layout queue (authorized GDK
|
||||
* documentation: PresentX(PlaneCount, const D3D12XBOX_PRESENT_PLANE_PARAMETERS*,
|
||||
* const D3D12XBOX_PRESENT_PARAMETERS*)). This is separate from presentx.h, BetterXen's own
|
||||
* swapchain bridge for synthetic fixtures.
|
||||
*
|
||||
* On the first present, a host DXGI flip-model swapchain is created on the title's top-level
|
||||
* window (the visible window owned by this process), sized to plane 0's first resource. Each
|
||||
* present copies that resource into the current back buffer when formats and sizes match, and
|
||||
* otherwise leaves the back buffer unchanged (logged once), then presents with sync interval 0: frame pacing
|
||||
* is the title's own, through the frame events (frame_pacing.cpp). Plane 1, source and
|
||||
* destination rectangles, colour spaces and scaling are not applied (logged once).
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <dxgi1_4.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
#include <cstdlib>
|
||||
#include <cwchar>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
struct PlaneParameters { // D3D12XBOX_PRESENT_PLANE_PARAMETERS
|
||||
UINT64 Token;
|
||||
UINT ResourceCount;
|
||||
ID3D12Resource** ppResources;
|
||||
D3D12_RECT* pSrcViewRects;
|
||||
void* pDestPlacementBase;
|
||||
UINT ColorSpace;
|
||||
UINT ScaleFilter;
|
||||
UINT ExtendedDescCount;
|
||||
void* pExtendedDescs;
|
||||
UINT Flags;
|
||||
};
|
||||
static_assert(sizeof(PlaneParameters) == 72, "D3D12XBOX_PRESENT_PLANE_PARAMETERS layout");
|
||||
|
||||
constexpr UINT kBuffers = 3;
|
||||
|
||||
struct Presenter {
|
||||
std::mutex lock;
|
||||
bool failed = false;
|
||||
ID3D12CommandQueue* queue = nullptr; // host queue the swapchain was made for
|
||||
IDXGISwapChain3* swapchain = nullptr;
|
||||
ID3D12CommandAllocator* allocators[kBuffers] = {};
|
||||
ID3D12GraphicsCommandList* list = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
UINT64 fence_values[kBuffers] = {};
|
||||
UINT64 next_value = 1;
|
||||
HANDLE event = nullptr;
|
||||
DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
|
||||
UINT width = 0, height = 0;
|
||||
UINT64 presents = 0;
|
||||
};
|
||||
Presenter g;
|
||||
|
||||
struct FindWindow {
|
||||
DWORD pid;
|
||||
HWND found;
|
||||
};
|
||||
BOOL CALLBACK find_window(HWND window, LPARAM param) {
|
||||
auto* f = reinterpret_cast<FindWindow*>(param);
|
||||
DWORD pid = 0;
|
||||
GetWindowThreadProcessId(window, &pid);
|
||||
if (pid == f->pid && IsWindowVisible(window) && !GetWindow(window, GW_OWNER)) {
|
||||
f->found = window;
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void log_hr(const char* what, HRESULT hr) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s hr=0x%08lx", what, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail);
|
||||
}
|
||||
|
||||
DXGI_FORMAT swapchain_format(DXGI_FORMAT f) {
|
||||
switch (f) {
|
||||
case DXGI_FORMAT_R8G8B8A8_UNORM:
|
||||
case DXGI_FORMAT_B8G8R8A8_UNORM:
|
||||
case DXGI_FORMAT_R10G10B10A2_UNORM:
|
||||
case DXGI_FORMAT_R16G16B16A16_FLOAT: return f;
|
||||
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
default: return DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
}
|
||||
}
|
||||
|
||||
bool create_locked(ID3D12CommandQueue* queue, const D3D12_RESOURCE_DESC& source) {
|
||||
FindWindow f{GetCurrentProcessId(), nullptr};
|
||||
EnumWindows(find_window, reinterpret_cast<LPARAM>(&f));
|
||||
if (!f.found) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", "no visible window owned by the title; frames not shown");
|
||||
return false;
|
||||
}
|
||||
using CreateFactory2 = HRESULT(WINAPI*)(UINT, REFIID, void**);
|
||||
HMODULE dxgi = LoadLibraryW(L"dxgi.dll");
|
||||
auto create_factory = dxgi ? reinterpret_cast<CreateFactory2>(reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory2"))) : nullptr;
|
||||
IDXGIFactory2* factory = nullptr;
|
||||
HRESULT hr = create_factory ? create_factory(0, __uuidof(IDXGIFactory2), reinterpret_cast<void**>(&factory)) : E_NOINTERFACE;
|
||||
if (FAILED(hr)) {
|
||||
log_hr("CreateDXGIFactory2", hr);
|
||||
return false;
|
||||
}
|
||||
g.width = static_cast<UINT>(source.Width);
|
||||
g.height = source.Height;
|
||||
g.format = swapchain_format(source.Format);
|
||||
DXGI_SWAP_CHAIN_DESC1 desc{};
|
||||
desc.Width = g.width;
|
||||
desc.Height = g.height;
|
||||
desc.Format = g.format;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
|
||||
desc.BufferCount = kBuffers;
|
||||
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
|
||||
IDXGISwapChain1* chain1 = nullptr;
|
||||
hr = factory->CreateSwapChainForHwnd(queue, f.found, &desc, nullptr, nullptr, &chain1);
|
||||
factory->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr("CreateSwapChainForHwnd", hr);
|
||||
return false;
|
||||
}
|
||||
hr = chain1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void**>(&g.swapchain));
|
||||
chain1->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr("IDXGISwapChain3", hr);
|
||||
return false;
|
||||
}
|
||||
ID3D12Device* device = nullptr;
|
||||
hr = queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
for (UINT i = 0; SUCCEEDED(hr) && i < kBuffers; ++i) {
|
||||
hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
|
||||
reinterpret_cast<void**>(&g.allocators[i]));
|
||||
}
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g.allocators[0], nullptr,
|
||||
__uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(&g.list));
|
||||
}
|
||||
if (SUCCEEDED(hr)) hr = g.list->Close();
|
||||
if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&g.fence));
|
||||
if (device) device->Release();
|
||||
g.event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (FAILED(hr) || !g.event) {
|
||||
log_hr("present resources", FAILED(hr) ? hr : E_OUTOFMEMORY);
|
||||
return false;
|
||||
}
|
||||
g.queue = queue;
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "swapchain %ux%u format=%d on the title window (title buffer format=%d)", g.width,
|
||||
g.height, static_cast<int>(g.format), static_cast<int>(source.Format));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_xbox", detail);
|
||||
return true;
|
||||
}
|
||||
|
||||
void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* r, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) {
|
||||
D3D12_RESOURCE_BARRIER b{};
|
||||
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
b.Transition.pResource = r;
|
||||
b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
b.Transition.StateBefore = before;
|
||||
b.Transition.StateAfter = after;
|
||||
list->ResourceBarrier(1, &b);
|
||||
}
|
||||
|
||||
|
||||
// Diagnostics (off unless BX_PRESENT_DUMP=<folder>): every BX_PRESENT_DUMP_EVERY-th present (default
|
||||
// 64, at most 32 files) the presented buffer is copied to a readback buffer and written as a BMP,
|
||||
// downscaled 4x, for looking at frames without screen-recording access.
|
||||
const wchar_t* dump_folder() {
|
||||
static wchar_t folder[MAX_PATH] = L"";
|
||||
static const bool on = GetEnvironmentVariableW(L"BX_PRESENT_DUMP", folder, MAX_PATH) > 0;
|
||||
return on ? folder : nullptr;
|
||||
}
|
||||
UINT64 dump_every() {
|
||||
static const UINT64 every = [] {
|
||||
char v[16];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_PRESENT_DUMP_EVERY", v, sizeof(v));
|
||||
const unsigned long k = (n > 0 && n < sizeof(v)) ? std::strtoul(v, nullptr, 10) : 64;
|
||||
return static_cast<UINT64>(k ? k : 64);
|
||||
}();
|
||||
return every;
|
||||
}
|
||||
|
||||
void dump_frame(ID3D12CommandQueue* queue, ID3D12Resource* source, const D3D12_RESOURCE_DESC& desc, UINT64 frame) {
|
||||
static int written = 0;
|
||||
if (written >= 32 || desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return;
|
||||
const DXGI_FORMAT f = desc.Format;
|
||||
const bool bgra = f == DXGI_FORMAT_B8G8R8A8_UNORM || f == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
|
||||
const bool rgba = f == DXGI_FORMAT_R8G8B8A8_UNORM || f == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
|
||||
if (!bgra && !rgba) return;
|
||||
ID3D12Device* device = nullptr;
|
||||
if (FAILED(queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device)))) return;
|
||||
D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};
|
||||
UINT rows = 0;
|
||||
UINT64 row_bytes = 0, total = 0;
|
||||
device->GetCopyableFootprints(&desc, 0, 1, 0, &fp, &rows, &row_bytes, &total);
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_READBACK;
|
||||
D3D12_RESOURCE_DESC buf{};
|
||||
buf.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buf.Width = total;
|
||||
buf.Height = 1;
|
||||
buf.DepthOrArraySize = 1;
|
||||
buf.MipLevels = 1;
|
||||
buf.SampleDesc.Count = 1;
|
||||
buf.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
ID3D12Resource* readback = nullptr;
|
||||
ID3D12CommandAllocator* alloc = nullptr;
|
||||
ID3D12GraphicsCommandList* list = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&readback));
|
||||
if (SUCCEEDED(hr)) hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&alloc));
|
||||
if (SUCCEEDED(hr)) hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc, nullptr, __uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(&list));
|
||||
if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
|
||||
if (SUCCEEDED(hr)) {
|
||||
barrier(list, source, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{readback, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
|
||||
dst.PlacedFootprint = fp;
|
||||
D3D12_TEXTURE_COPY_LOCATION src{source, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
|
||||
barrier(list, source, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON);
|
||||
list->Close();
|
||||
ID3D12CommandList* lists[] = {list};
|
||||
queue->ExecuteCommandLists(1, lists);
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
queue->Signal(fence, 1);
|
||||
fence->SetEventOnCompletion(1, done);
|
||||
WaitForSingleObject(done, 5000);
|
||||
CloseHandle(done);
|
||||
const BYTE* data = nullptr;
|
||||
if (SUCCEEDED(readback->Map(0, nullptr, reinterpret_cast<void**>(const_cast<BYTE**>(&data))))) {
|
||||
const UINT w = static_cast<UINT>(desc.Width) / 4, h = desc.Height / 4;
|
||||
const UINT stride = (w * 3 + 3) & ~3u;
|
||||
std::vector<BYTE> bmp(54 + static_cast<size_t>(stride) * h, 0);
|
||||
auto put32 = [&](size_t at, uint32_t v) { std::memcpy(&bmp[at], &v, 4); };
|
||||
bmp[0] = 'B'; bmp[1] = 'M';
|
||||
put32(2, static_cast<uint32_t>(bmp.size())); put32(10, 54); put32(14, 40);
|
||||
put32(18, w); put32(22, h); bmp[26] = 1; bmp[28] = 24; put32(34, static_cast<uint32_t>(stride * h));
|
||||
uint64_t sum = 0;
|
||||
for (UINT y = 0; y < h; ++y) {
|
||||
const BYTE* row = data + fp.Offset + static_cast<UINT64>(y * 4) * fp.Footprint.RowPitch;
|
||||
BYTE* out = &bmp[54 + static_cast<size_t>(h - 1 - y) * stride];
|
||||
for (UINT x = 0; x < w; ++x) {
|
||||
const BYTE* px = row + static_cast<size_t>(x) * 16;
|
||||
const BYTE r = bgra ? px[2] : px[0], g = px[1], b = bgra ? px[0] : px[2];
|
||||
out[x * 3 + 0] = b; out[x * 3 + 1] = g; out[x * 3 + 2] = r;
|
||||
sum += r + g + b;
|
||||
}
|
||||
}
|
||||
readback->Unmap(0, nullptr);
|
||||
wchar_t path[MAX_PATH];
|
||||
std::swprintf(path, MAX_PATH, L"%ls\\frame_%06llu.bmp", dump_folder(), static_cast<unsigned long long>(frame));
|
||||
HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (file != INVALID_HANDLE_VALUE) {
|
||||
DWORD wrote = 0;
|
||||
WriteFile(file, bmp.data(), static_cast<DWORD>(bmp.size()), &wrote, nullptr);
|
||||
CloseHandle(file);
|
||||
++written;
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "frame %llu dumped %ux%u, mean channel value %.1f",
|
||||
static_cast<unsigned long long>(frame), w, h, w && h ? double(sum) / (double(w) * h * 3) : 0.0);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "present_dump", detail);
|
||||
}
|
||||
}
|
||||
if (fence) fence->Release();
|
||||
if (list) list->Release();
|
||||
if (alloc) alloc->Release();
|
||||
if (readback) readback->Release();
|
||||
device->Release();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT plane_count, const void* planes_raw,
|
||||
const void* parameters) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "PresentX");
|
||||
(void)parameters;
|
||||
const auto* planes = static_cast<const PlaneParameters*>(planes_raw);
|
||||
if (plane_count == 0 || !planes || planes[0].ResourceCount == 0 || !planes[0].ppResources) return S_OK;
|
||||
ID3D12Resource* source = bx_xbox_unwrap_as(planes[0].ppResources[0]);
|
||||
if (!source) return E_INVALIDARG;
|
||||
auto* queue = bx_xbox_host<ID3D12CommandQueue>(self);
|
||||
std::lock_guard<std::mutex> guard(g.lock);
|
||||
if (g.failed) return S_OK;
|
||||
const D3D12_RESOURCE_DESC desc = source->GetDesc();
|
||||
if (!g.swapchain && !create_locked(queue, desc)) {
|
||||
g.failed = true;
|
||||
return S_OK; // the title keeps running; frames are not shown (logged)
|
||||
}
|
||||
static std::atomic<bool> logged_extra{false};
|
||||
if ((plane_count > 1 || planes[0].pSrcViewRects || planes[0].pDestPlacementBase) && !logged_extra.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_xbox",
|
||||
"plane 1, view rectangles, placement and scaling are not applied; plane 0 is copied as is");
|
||||
}
|
||||
const UINT index = g.swapchain->GetCurrentBackBufferIndex();
|
||||
if (g.fence->GetCompletedValue() < g.fence_values[index]) {
|
||||
g.fence->SetEventOnCompletion(g.fence_values[index], g.event);
|
||||
WaitForSingleObject(g.event, 2000);
|
||||
}
|
||||
ID3D12Resource* back = nullptr;
|
||||
HRESULT hr = g.swapchain->GetBuffer(index, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&back));
|
||||
if (FAILED(hr)) {
|
||||
log_hr("GetBuffer", hr);
|
||||
return S_OK;
|
||||
}
|
||||
g.allocators[index]->Reset();
|
||||
g.list->Reset(g.allocators[index], nullptr);
|
||||
const bool copyable = desc.Width == g.width && desc.Height == g.height && swapchain_format(desc.Format) == g.format &&
|
||||
desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1;
|
||||
if (copyable) {
|
||||
// The title's buffer is assumed to be presentable (PRESENT, i.e. COMMON) when PresentX is called.
|
||||
barrier(g.list, source, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
barrier(g.list, back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{back, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
D3D12_TEXTURE_COPY_LOCATION src{source, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
g.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
|
||||
barrier(g.list, back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT);
|
||||
barrier(g.list, source, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON);
|
||||
} else {
|
||||
static std::atomic<bool> logged{false};
|
||||
if (!logged.exchange(true)) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "title buffer %llux%u format=%d does not match the swapchain; not copied, the window shows the previous contents",
|
||||
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<int>(desc.Format));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail);
|
||||
}
|
||||
}
|
||||
g.list->Close();
|
||||
ID3D12CommandList* lists[] = {g.list};
|
||||
g.queue->ExecuteCommandLists(1, lists);
|
||||
back->Release();
|
||||
hr = g.swapchain->Present(0, 0);
|
||||
g.fence_values[index] = g.next_value++;
|
||||
g.queue->Signal(g.fence, g.fence_values[index]);
|
||||
const UINT64 n = ++g.presents;
|
||||
if (dump_folder() && copyable && n % dump_every() == 0) dump_frame(g.queue, source, desc, n);
|
||||
if ((n & (n - 1)) == 0) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "frames presented=%llu last hr=0x%08lx", static_cast<unsigned long long>(n),
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_frames", detail);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
+254
-14
@@ -1,8 +1,15 @@
|
||||
#include "proxy.h"
|
||||
#include "vmem.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#include "presentx.h"
|
||||
|
||||
#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 +139,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 +208,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 +384,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,11 +414,151 @@ 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;
|
||||
}
|
||||
|
||||
/* Stream PSO subobjects (#576). A stream is a sequence of 8-byte-aligned records, each a
|
||||
* subobject type and a type-dependent payload. The real layout aligns the record, not the
|
||||
* payload: a payload whose type is only 4-byte aligned starts at offset 4, not 8. Measured
|
||||
* with the shim's own toolchain, that is the case for BLEND, SAMPLE_MASK, RASTERIZER,
|
||||
* DEPTH_STENCIL, DEPTH_STENCIL1, IB_STRIP_CUT_VALUE, PRIMITIVE_TOPOLOGY,
|
||||
* RENDER_TARGET_FORMATS, DEPTH_STENCIL_FORMAT, SAMPLE_DESC, NODE_MASK and FLAGS. Deriving
|
||||
* both the payload offset and the record size from the compiler keeps this table honest. */
|
||||
template<class Payload>
|
||||
struct alignas(void*) StreamRecord {
|
||||
/* alignas is on the CLASS, as in CD3DX12_PIPELINE_STATE_STREAM_SUBOBJECT: it pads the
|
||||
* whole record to 8 bytes but does not move a 4-byte-aligned payload off offset 4. */
|
||||
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
|
||||
Payload payload;
|
||||
};
|
||||
template<class Payload>
|
||||
constexpr size_t payload_at() { return offsetof(StreamRecord<Payload>, payload); }
|
||||
template<class Payload>
|
||||
constexpr size_t record_size() {
|
||||
return (offsetof(StreamRecord<Payload>, payload) + sizeof(Payload) + 7) & ~static_cast<size_t>(7);
|
||||
}
|
||||
|
||||
struct StreamSubobject {
|
||||
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type;
|
||||
size_t payload_offset;
|
||||
size_t record_size;
|
||||
const char* stage; /* non-null only for a shader subobject */
|
||||
};
|
||||
|
||||
#define BX_SUBOBJECT(tag, type, stage) \
|
||||
{tag, payload_at<type>(), record_size<type>(), stage}
|
||||
constexpr StreamSubobject kStreamSubobjects[] = {
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, void*, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, D3D12_SHADER_BYTECODE, "VS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, D3D12_SHADER_BYTECODE, "PS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS, D3D12_SHADER_BYTECODE, "DS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS, D3D12_SHADER_BYTECODE, "HS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, D3D12_SHADER_BYTECODE, "GS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, D3D12_SHADER_BYTECODE, "CS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT, D3D12_STREAM_OUTPUT_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, D3D12_BLEND_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, D3D12_RASTERIZER_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_DEPTH_STENCIL_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, D3D12_INPUT_LAYOUT_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, D3D12_RT_FORMAT_ARRAY, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, DXGI_SAMPLE_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, D3D12_CACHED_PIPELINE_STATE, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, UINT, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, D3D12_DEPTH_STENCIL_DESC1, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, D3D12_VIEW_INSTANCING_DESC, nullptr),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, D3D12_SHADER_BYTECODE, "AS"),
|
||||
BX_SUBOBJECT(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, D3D12_SHADER_BYTECODE, "MS"),
|
||||
};
|
||||
#undef BX_SUBOBJECT
|
||||
|
||||
/* Pin the layout facts the walker depends on, measured with this toolchain. A header change
|
||||
* that moves a payload must fail to compile rather than desync the walk (#576 review). */
|
||||
static_assert(payload_at<D3D12_SHADER_BYTECODE>() == 8, "shader payloads sit at offset 8");
|
||||
static_assert(record_size<D3D12_SHADER_BYTECODE>() == 24, "a shader record is 24 bytes");
|
||||
static_assert(payload_at<UINT>() == 4, "4-byte payloads sit at offset 4, not 8");
|
||||
static_assert(record_size<UINT>() == 8, "a UINT record is 8 bytes");
|
||||
static_assert(payload_at<D3D12_BLEND_DESC>() == 4, "BLEND payload sits at offset 4");
|
||||
static_assert(payload_at<D3D12_RASTERIZER_DESC>() == 4, "RASTERIZER payload sits at offset 4");
|
||||
static_assert(payload_at<D3D12_RT_FORMAT_ARRAY>() == 4, "RT_FORMAT_ARRAY payload sits at offset 4");
|
||||
static_assert(payload_at<D3D12_DEPTH_STENCIL_DESC1>() == 4, "DEPTH_STENCIL1 payload sits at offset 4");
|
||||
static_assert(payload_at<void*>() == 8 && record_size<void*>() == 16, "root signature record");
|
||||
static_assert(payload_at<D3D12_INPUT_LAYOUT_DESC>() == 8, "INPUT_LAYOUT payload sits at offset 8");
|
||||
|
||||
const StreamSubobject* find_subobject(uint32_t type) {
|
||||
for (const StreamSubobject& entry : kStreamSubobjects) {
|
||||
if (static_cast<uint32_t>(entry.type) == type) return &entry;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* Copies the caller's stream into `copy` so the gate can substitute prepared bytecode without
|
||||
* touching memory it does not own, and records where each shader payload sits (and, when
|
||||
* `root_offset` is given, the root-signature payload, or SIZE_MAX without one). An unknown tag,
|
||||
* or a payload that overruns SizeInBytes, is rejected. */
|
||||
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
|
||||
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names,
|
||||
size_t* root_offset) {
|
||||
if (root_offset) *root_offset = SIZE_MAX;
|
||||
if (desc.SizeInBytes == 0 || !desc.pPipelineStateSubobjectStream) return E_INVALIDARG;
|
||||
const auto* source = static_cast<const uint8_t*>(desc.pPipelineStateSubobjectStream);
|
||||
copy.assign(source, source + desc.SizeInBytes);
|
||||
size_t offset = 0;
|
||||
while (offset < copy.size()) {
|
||||
if (copy.size() - offset < sizeof(SIZE_T)) return E_INVALIDARG;
|
||||
/* The tag is a 4-byte enum at the start of an 8-byte-aligned record; the rest of
|
||||
* those 8 bytes is padding a caller may leave uninitialized, so read only the enum
|
||||
* and step to the payload at offset sizeof(SIZE_T). */
|
||||
uint32_t raw = 0;
|
||||
std::memcpy(&raw, ©[offset], sizeof(raw));
|
||||
if (raw >= static_cast<uint32_t>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID)) return E_INVALIDARG;
|
||||
const StreamSubobject* entry = find_subobject(raw);
|
||||
if (!entry) return E_INVALIDARG;
|
||||
/* Microsoft's ID3D12Device2 rules reject a duplicated subobject type. */
|
||||
for (size_t seen = 0; seen < offset; ) {
|
||||
uint32_t prior = 0;
|
||||
std::memcpy(&prior, ©[seen], sizeof(prior));
|
||||
if (prior == raw) return E_INVALIDARG;
|
||||
const StreamSubobject* prior_entry = find_subobject(prior);
|
||||
if (!prior_entry) return E_INVALIDARG;
|
||||
seen += prior_entry->record_size;
|
||||
}
|
||||
const size_t payload = offset + entry->payload_offset;
|
||||
const size_t record = entry->record_size;
|
||||
if (copy.size() - offset < record) return E_INVALIDARG;
|
||||
if (root_offset && entry->type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE) *root_offset = payload;
|
||||
if (entry->stage) {
|
||||
D3D12_SHADER_BYTECODE code{};
|
||||
std::memcpy(&code, ©[payload], sizeof(code));
|
||||
if (code.BytecodeLength != 0 && !code.pShaderBytecode) return E_INVALIDARG;
|
||||
stage_offsets.push_back(payload);
|
||||
stage_names.push_back(entry->stage);
|
||||
}
|
||||
offset += record;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("ID3D12Device2", "CreatePipelineState");
|
||||
if (!h_ID3D12Device2) {
|
||||
@@ -369,12 +566,50 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELIN
|
||||
if (ppv) *ppv = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
/* The stream form is forwarded unparsed: only its size is recorded (sub-object walking is M2 work). */
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "pso=stream bytes=%llu shaders_not_parsed=1",
|
||||
static_cast<unsigned long long>(desc ? desc->SizeInBytes : 0));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", detail);
|
||||
HRESULT hr = h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
|
||||
if (ppv) *ppv = nullptr;
|
||||
if (!desc) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", "pso=stream bytes=0 shaders_not_parsed=1");
|
||||
const HRESULT hr = h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
|
||||
log_created("stream pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
/* M2 shader format gate (#576): the stream form classifies its stages like the desc forms,
|
||||
* so an ACCC-only container is refused instead of reaching D3DMetal unparsed. */
|
||||
std::vector<uint8_t> stream;
|
||||
std::vector<size_t> offsets;
|
||||
std::vector<const char*> names;
|
||||
const HRESULT copied = copy_stream(*desc, stream, offsets, names, nullptr);
|
||||
{
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "pso=stream bytes=%llu shaders_not_parsed=%d",
|
||||
static_cast<unsigned long long>(desc->SizeInBytes), offsets.empty() ? 1 : 0);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_stream", detail);
|
||||
}
|
||||
if (FAILED(copied) || offsets.empty()) {
|
||||
const HRESULT hr = FAILED(copied) ? copied : h_ID3D12Device2->CreatePipelineState(desc, riid, ppv);
|
||||
log_created("stream pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
BxShaderGate gate;
|
||||
HRESULT gated = S_OK;
|
||||
for (size_t i = 0; i < offsets.size() && SUCCEEDED(gated); ++i) {
|
||||
D3D12_SHADER_BYTECODE in{};
|
||||
std::memcpy(&in, &stream[offsets[i]], sizeof(in));
|
||||
D3D12_SHADER_BYTECODE out = in;
|
||||
gated = gate.admit("stream", names[i], in, out);
|
||||
/* `out` is either the caller's bytes or the gate's copy, which lives until `gate`
|
||||
* is destroyed, so only the pointer/length inside our own copy change. */
|
||||
if (SUCCEEDED(gated)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
|
||||
}
|
||||
if (FAILED(gated)) {
|
||||
log_created("stream pipeline state", gated);
|
||||
return gated;
|
||||
}
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
|
||||
admitted.pPipelineStateSubobjectStream = stream.data();
|
||||
const HRESULT hr = h_ID3D12Device2->CreatePipelineState(&admitted, riid, ppv);
|
||||
log_created("stream pipeline state", hr);
|
||||
return hr;
|
||||
}
|
||||
@@ -458,6 +693,11 @@ HRESULT STDMETHODCALLTYPE BxChildProxy<Gen>::QueryInterface(REFIID riid, void**
|
||||
*ppv = static_cast<Gen*>(this);
|
||||
return S_OK;
|
||||
}
|
||||
if constexpr (std::is_same_v<Gen, BxCommandQueueProxyImpl>) {
|
||||
if (IsEqualGUID(riid, IID_IBxPresentQueue)) {
|
||||
return bx_present_query_queue(this, ppv); /* BetterXen's presentation bridge, presentx.h */
|
||||
}
|
||||
}
|
||||
return query_host_unproxied(host_identity_, Gen::kLeafName, riid, ppv);
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
@@ -53,6 +54,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;
|
||||
@@ -111,3 +118,9 @@ using BxCommandAllocatorProxy = BxChildProxy<BxCommandAllocatorProxyGen>;
|
||||
using BxCommandListProxy = BxChildProxy<BxCommandListProxyGen>;
|
||||
|
||||
#endif /* BETTERXEN_D3D12_XS_PROXY_H */
|
||||
|
||||
/* Validates and copies a pipeline-state stream (proxy.cpp, #576): shader payload offsets and
|
||||
* stage names, and the root-signature payload offset when `root_offset` is given. */
|
||||
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
|
||||
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names,
|
||||
size_t* root_offset);
|
||||
@@ -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 bx_vmem_create_placed_resource1(h_ID3D12Device8, 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 bx_vmem_create_placed_resource2(h_ID3D12Device10, 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) {
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
#ifndef BETTERXEN_D3D12_XS_PROXY_GENERATED_H
|
||||
#define BETTERXEN_D3D12_XS_PROXY_GENERATED_H
|
||||
|
||||
/* HANDOFF targets: the host interface, then the caller's arguments unmodified. */
|
||||
HRESULT bx_vmem_create_placed_resource1(ID3D12Device8* host, ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6);
|
||||
HRESULT bx_vmem_create_placed_resource2(ID3D12Device10* host, 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);
|
||||
|
||||
class BxDeviceProxyGen : public ID3D12Device10 {
|
||||
public:
|
||||
static constexpr const char* kLeafName = "ID3D12Device10";
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
#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;
|
||||
|
||||
/* The [WaveSize(64)] case on its own (#591). A wider-than-32 wave is refused at PSO creation
|
||||
* rather than handed to a host that creates the pipeline and never runs it: the caller then
|
||||
* learns from a failed call instead of from a silently absent draw. Lowering 64 lanes to 32 is
|
||||
* a semantic transform (reductions, lane indices, 64-bit masks, cross-half permutes, barriers)
|
||||
* and is deferred. 64-bit atomics stay warn-only until their detection is complete (#589). */
|
||||
bool wave_wider_than_32(const Constraints& c) {
|
||||
return c.has_lanes && c.lanes_min > 32;
|
||||
}
|
||||
|
||||
/* 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) {
|
||||
return wave_wider_than_32(c)
|
||||
|| (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;
|
||||
/* A wave wider than 32 lanes is refused here (#591): D3DMetal creates such a
|
||||
* pipeline and never runs it, so returning S_OK would leave the caller with a
|
||||
* silent no-op. The stage keeps its copy alive via `gate` until the caller's
|
||||
* PSO call returns. */
|
||||
if (wave_wider_than_32(constraints)) {
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "reject_wave_wide", E_NOTIMPL);
|
||||
/* Keep the established gap-detail shape: the consumer (#593) strips a trailing
|
||||
* colon from the last value and treats `atomic64_flags` as always present, so
|
||||
* `wave_lanes_min` must not be the final field. */
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"pso=%s stage=%s wave_lanes_min=%lu atomic64_flags=0x%llx: a wave wider "
|
||||
"than 32 lanes is created but never run on D3DMetal (#453); refused at "
|
||||
"PSO creation (#591)",
|
||||
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 E_NOTIMPL;
|
||||
}
|
||||
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:
|
||||
// A container with a DXIL part that the classifier cannot call executable DXIL:
|
||||
// the measured case is a header-only program (a `NOBC` payload, no bitcode), which
|
||||
// D3DMetal crashes on in CreatePipelineState instead of failing. Refuse it.
|
||||
if (info.dxil_chunk_size != 0) {
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "reject_unclassified_dxil", E_NOTIMPL);
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
log_gate(pso_kind, stage, len, &info, &constraints, "pass_original", S_OK);
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
#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, and for a container whose
|
||||
* DXIL part the bridge cannot classify (a header-only program). 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;
|
||||
};
|
||||
@@ -9,6 +9,9 @@ Only method names, return types and parameter types are taken from the header:
|
||||
they are what an override must repeat verbatim to compile. Parameters are
|
||||
renamed positionally (a0, a1, ...). Methods listed in CUSTOM are declared but
|
||||
left for proxy.cpp to implement by hand (wrapping, unwrapping, logging).
|
||||
Methods listed in HANDOFF keep the generated trace and null-host stub, then pass
|
||||
the host interface and the caller's arguments, unmodified, to a free function
|
||||
whose declaration is generated from the same header signature.
|
||||
|
||||
Usage: python3 shims/d3d12_xs/tools/gen_proxy.py [path/to/d3d12.h]
|
||||
(default: located through `x86_64-w64-mingw32-g++ -E`)
|
||||
@@ -41,11 +44,24 @@ PROXIES = {
|
||||
}),
|
||||
}
|
||||
|
||||
# proxy class -> {method: free function}. The function receives the host interface of the method's
|
||||
# level followed by the caller's arguments; nothing is unwrapped. vmem.cpp implements both below
|
||||
# with the same placement validation and heap retention as CreatePlacedResource (slot 29).
|
||||
HANDOFF = {
|
||||
"BxDeviceProxyGen": {
|
||||
"CreatePlacedResource1": "bx_vmem_create_placed_resource1",
|
||||
"CreatePlacedResource2": "bx_vmem_create_placed_resource2",
|
||||
},
|
||||
}
|
||||
|
||||
# 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 **", "")]),
|
||||
@@ -114,6 +130,7 @@ def main():
|
||||
|
||||
h = ["// Generated by shims/d3d12_xs/tools/gen_proxy.py from the toolchain's <d3d12.h>. Do not edit by hand.",
|
||||
"#ifndef BETTERXEN_D3D12_XS_PROXY_GENERATED_H", "#define BETTERXEN_D3D12_XS_PROXY_GENERATED_H", ""]
|
||||
h_pre = []
|
||||
c = ["// Generated by shims/d3d12_xs/tools/gen_proxy.py from the toolchain's <d3d12.h>. Do not edit by hand.",
|
||||
'#include "proxy.h"', ""]
|
||||
|
||||
@@ -122,6 +139,10 @@ def main():
|
||||
levels = [i for i in chain if i not in ABSTRACT]
|
||||
root = levels[0]
|
||||
seen_custom = set()
|
||||
handoff = HANDOFF.get(cls, {})
|
||||
seen_handoff = set()
|
||||
if custom & handoff.keys():
|
||||
sys.exit(f"{cls}: methods in both CUSTOM and HANDOFF: {sorted(custom & handoff.keys())}")
|
||||
|
||||
h += [f"class {cls} : public {leaf} {{", "public:",
|
||||
f' static constexpr const char* kLeafName = "{leaf}";']
|
||||
@@ -159,6 +180,18 @@ def main():
|
||||
seen_custom.add(name)
|
||||
slot += 1
|
||||
continue
|
||||
if name in handoff:
|
||||
seen_handoff.add(name)
|
||||
fn = handoff[name]
|
||||
host_type = root if iface in ABSTRACT else iface
|
||||
h_pre.append(f"{ret} {fn}({host_type}* host{', ' if decl else ''}{decl});")
|
||||
call = f"{fn}({', '.join([host] + [f'a{n}' for n in range(len(params))])})"
|
||||
c += [f"{ret} STDMETHODCALLTYPE {cls}::{name}({decl}) {{",
|
||||
f' BX_D3D_TRACE("{iface}", "{name}");',
|
||||
f" if (!{host}) {{ {default_return(ret, iface, slot, name)} }}",
|
||||
f" {'' if ret == 'void' else 'return '}{call};", "}", ""]
|
||||
slot += 1
|
||||
continue
|
||||
args = []
|
||||
for n, (t, arr) in enumerate(params):
|
||||
bare = t.replace("const", "").replace(" ", "")
|
||||
@@ -177,6 +210,9 @@ def main():
|
||||
missing = custom - seen_custom
|
||||
if missing:
|
||||
sys.exit(f"{cls}: custom methods not found in header: {sorted(missing)}")
|
||||
missing = handoff.keys() - seen_handoff
|
||||
if missing:
|
||||
sys.exit(f"{cls}: hand-off methods not found in header: {sorted(missing)}")
|
||||
|
||||
h += ["", f" static constexpr unsigned kPublicSlotCount = {slot}u;",
|
||||
" /*",
|
||||
@@ -191,6 +227,8 @@ def main():
|
||||
h += ["", "protected:", f" ~{cls}() = default;", "};", ""]
|
||||
|
||||
h += ["#endif"]
|
||||
if h_pre:
|
||||
h[4:4] = ["/* HANDOFF targets: the host interface, then the caller's arguments unmodified. */"] + h_pre + [""]
|
||||
(OUT_DIR / "proxy_generated.h").write_text("\n".join(h) + "\n", encoding="utf-8")
|
||||
(OUT_DIR / "proxy_generated.cpp").write_text("\n".join(c), encoding="utf-8")
|
||||
print(f"wrote proxy_generated.h/.cpp from {header}")
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate the Xbox-layout function tables of the d3d12_xs proxy objects.
|
||||
|
||||
A title built against the Xbox D3D12 headers calls every method through a function table whose
|
||||
order is not the PC D3D12 order (Xbox-only methods sit between and inside the PC ones). This
|
||||
script reads two headers:
|
||||
|
||||
* the Xbox Series header (d3d12_xs.h from the GDKX, used under Microsoft's authorization). Only
|
||||
facts are taken from it: interface names and IIDs, the slot order of each function table, and
|
||||
each method's name, return type and parameter types. Nothing from it is copied into the output
|
||||
verbatim beyond those names, and the header itself is never committed.
|
||||
* the toolchain's PC <d3d12.h>, which the shim is compiled against.
|
||||
|
||||
For every slot of the chosen Xbox interfaces it emits one of:
|
||||
* a typed forwarder to the PC method of the same name, when the Xbox and PC signatures are
|
||||
equivalent (the PC types are used, so the compiler handles struct returns and the calling
|
||||
convention); interface-pointer parameters are unwrapped and (REFIID, void**) results wrapped;
|
||||
* a shared IUnknown/GetDevice slot implemented in xbox_facade.cpp;
|
||||
* a stub that logs BX_VTABLE_STUB_LOG and returns a neutral value, for Xbox-only methods and for
|
||||
methods whose signatures differ.
|
||||
|
||||
Usage: python3 shims/d3d12_xs/tools/gen_xbox_tables.py /path/to/d3d12_xs.h [path/to/pc/d3d12.h]
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import gen_proxy # noqa: E402 (PC header parser shared with the PC proxy generator)
|
||||
|
||||
OUT_DIR = Path(__file__).resolve().parents[1]
|
||||
|
||||
# Xbox leaf interface -> (PC interface the host object must provide, C++ family tag)
|
||||
FAMILIES = {
|
||||
"ID3D12Device11": ("ID3D12Device10", "Device"),
|
||||
"ID3D12Resource2": ("ID3D12Resource2", "Resource"),
|
||||
"ID3D12Heap1": ("ID3D12Heap1", "Heap"),
|
||||
"ID3D12Fence1": ("ID3D12Fence", "Fence"), # D3DMetal answers ID3D12Fence, not Fence1
|
||||
"ID3D12DescriptorHeap": ("ID3D12DescriptorHeap", "DescriptorHeap"),
|
||||
"ID3D12RootSignature": ("ID3D12RootSignature", "RootSignature"),
|
||||
"ID3D12PipelineState": ("ID3D12PipelineState", "PipelineState"),
|
||||
"ID3D12CommandAllocator": ("ID3D12CommandAllocator", "CommandAllocator"),
|
||||
"ID3D12QueryHeap": ("ID3D12QueryHeap", "QueryHeap"),
|
||||
"ID3D12CommandSignature": ("ID3D12CommandSignature", "CommandSignature"),
|
||||
"ID3D12CommandQueue": ("ID3D12CommandQueue", "CommandQueue"),
|
||||
"ID3D12GraphicsCommandList8": ("ID3D12GraphicsCommandList7", "GraphicsCommandList"),
|
||||
}
|
||||
# Xbox-only slots implemented by hand in xbox_facade.cpp: family -> {method: function}.
|
||||
CUSTOM = {
|
||||
"Device": {"CreateCommandQueueX": "bx_xbox_device_create_command_queue_x",
|
||||
"CreateCommandListX": "bx_xbox_device_create_command_list_x",
|
||||
"SetFrameIntervalX": "bx_xbox_device_set_frame_interval_x",
|
||||
"ScheduleFrameEventX": "bx_xbox_device_schedule_frame_event_x",
|
||||
"WaitFrameEventX": "bx_xbox_device_wait_frame_event_x",
|
||||
"CreatePlacedResourceX": "bx_xbox_device_create_placed_resource_x",
|
||||
"CreatePlacedResourceX1": "bx_xbox_device_create_placed_resource_x1",
|
||||
"CreateDescriptorHeap": "bx_xbox_device_create_descriptor_heap",
|
||||
"GetDescriptorHandleIncrementSize": "bx_xbox_device_get_descriptor_handle_increment_size",
|
||||
"CreateConstantBufferView": "bx_xbox_device_create_constant_buffer_view",
|
||||
"CopyDescriptors": "bx_xbox_device_copy_descriptors",
|
||||
"CreateCommandSignature": "bx_xbox_device_create_command_signature",
|
||||
"CreatePipelineState": "bx_xbox_device_create_pipeline_state",
|
||||
"DeserializeGraphicsPipelineStateX": "bx_xbox_device_deserialize_graphics_pipeline_state_x",
|
||||
"CreateDerivedGraphicsPipelineStateX": "bx_xbox_device_create_derived_graphics_pipeline_state_x",
|
||||
"CreateDerivedComputePipelineStateX": "bx_xbox_device_create_derived_compute_pipeline_state_x",
|
||||
"DeserializeComputePipelineStateX": "bx_xbox_device_deserialize_compute_pipeline_state_x",
|
||||
"CreateSamplerX": "bx_xbox_device_create_sampler_x",
|
||||
"RegisterPagePoolX": "bx_xbox_device_register_page_pool_x",
|
||||
"UnregisterPagePoolX": "bx_xbox_device_unregister_page_pool_x",
|
||||
"CreateComputePipelineState": "bx_xbox_device_create_compute_pipeline_state",
|
||||
"CreateGraphicsPipelineState": "bx_xbox_device_create_graphics_pipeline_state",
|
||||
"CreateComputePipelineStateX": "bx_xbox_device_create_compute_pipeline_state_x",
|
||||
"CreateGraphicsPipelineStateX": "bx_xbox_device_create_graphics_pipeline_state_x",
|
||||
"CreateCommittedResource": "bx_xbox_device_create_committed_resource",
|
||||
"CreateCommittedResource1": "bx_xbox_device_create_committed_resource1",
|
||||
"CreateCommittedResource2": "bx_xbox_device_create_committed_resource2",
|
||||
"CreateCommittedResource3": "bx_xbox_device_create_committed_resource3",
|
||||
"CreatePlacedRawShaderResourceViewX": "bx_xbox_device_create_placed_raw_srv_x",
|
||||
"CreatePlacedRawUnorderedAccessViewX": "bx_xbox_device_create_placed_raw_uav_x",
|
||||
"CreatePlacedShaderResourceViewX": "bx_xbox_device_create_placed_srv_x",
|
||||
"CreatePlacedUnorderedAccessViewX": "bx_xbox_device_create_placed_uav_x"},
|
||||
"Resource": {"GetGPUVirtualAddress": "bx_xbox_resource_get_gpu_virtual_address",
|
||||
"Map": "bx_xbox_resource_map", "Unmap": "bx_xbox_resource_unmap"},
|
||||
"Fence": {"GetGpuAddressX": "bx_xbox_fence_get_gpu_address_x", "Signal": "bx_xbox_fence_signal"},
|
||||
"CommandQueue": {"ExecuteCommandLists": "bx_xbox_queue_execute_command_lists",
|
||||
"Signal": "bx_xbox_queue_signal", "Wait": "bx_xbox_queue_wait",
|
||||
"PresentX": "bx_xbox_queue_present_x",
|
||||
"CopyPageMappingsBatchX": "bx_xbox_queue_copy_page_mappings_batch_x",
|
||||
"CopyPageMappingsX": "bx_xbox_queue_copy_page_mappings_x",
|
||||
"ClearPageMappingsX": "bx_xbox_queue_clear_page_mappings_x",
|
||||
"ExecuteCommandLists2X": "bx_xbox_queue_execute_command_lists2_x"},
|
||||
"CommandAllocator": {"SetAllocatorCallbackX": "bx_xbox_allocator_set_callback_x"},
|
||||
"DescriptorHeap": {"GetCPUDescriptorHandleForHeapStart": "bx_xbox_heap_cpu_start",
|
||||
"GetGPUDescriptorHandleForHeapStart": "bx_xbox_heap_gpu_start"},
|
||||
"GraphicsCommandList": {"ResourceBarrier": "bx_xbox_list_resource_barrier",
|
||||
"CopyTextureRegion": "bx_xbox_list_copy_texture_region",
|
||||
"OMSetRenderTargets": "bx_xbox_list_om_set_render_targets",
|
||||
"IASetVertexBuffers": "bx_xbox_list_ia_set_vertex_buffers",
|
||||
"IASetIndexBuffer": "bx_xbox_list_ia_set_index_buffer",
|
||||
"SetPipelineState": "bx_xbox_list_set_pipeline_state",
|
||||
"Reset": "bx_xbox_list_reset",
|
||||
"ResetX": "bx_xbox_list_reset_x",
|
||||
"Wait64BitValueX": "bx_xbox_list_wait64_x",
|
||||
"Wait32BitValueX": "bx_xbox_list_wait32_x",
|
||||
"Write32BitValueBottomOfPipeX": "bx_xbox_list_write32_bop_x",
|
||||
"Write64BitValueBottomOfPipeX": "bx_xbox_list_write64_bop_x",
|
||||
"Write32BitValueTopOfPipeX": "bx_xbox_list_write32_top_x",
|
||||
"Write64BitValueTopOfPipeX": "bx_xbox_list_write64_top_x",
|
||||
"SyncTopOfPipeX": "bx_xbox_list_sync_x",
|
||||
"SyncBottomOfPipeX": "bx_xbox_list_sync_x",
|
||||
"DrawInstanced": "bx_xbox_list_draw_instanced",
|
||||
"DrawIndexedInstanced": "bx_xbox_list_draw_indexed_instanced",
|
||||
"Dispatch": "bx_xbox_list_dispatch",
|
||||
"ExecuteIndirect": "bx_xbox_list_execute_indirect"},
|
||||
}
|
||||
SHARED = {"QueryInterface": "bx_xbox_query_interface", "AddRef": "bx_xbox_add_ref",
|
||||
"Release": "bx_xbox_release", "GetDevice": "bx_xbox_get_device"}
|
||||
# Interfaces whose pointers a forwarded call must unwrap from an Xbox object to its host.
|
||||
WRAPPABLE = re.compile(r"^(const\s+)?(ID3D12\w+|IUnknown)\s*\*$")
|
||||
WRAPPABLE_ARRAY = re.compile(r"^(ID3D12\w+)\s*\*\s*const\s*\*$")
|
||||
|
||||
|
||||
def strip_sal(text):
|
||||
text = re.sub(r"//[^\n]*", "", text)
|
||||
text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
|
||||
# SAL annotations, including arguments with nested parentheses such as sizeof(UINT).
|
||||
out, i = [], 0
|
||||
for m in re.finditer(r"\b_[A-Za-z]\w*_\b", text):
|
||||
if m.start() < i:
|
||||
continue
|
||||
out.append(text[i:m.start()])
|
||||
j = m.end()
|
||||
while j < len(text) and text[j] == " ":
|
||||
j += 1
|
||||
if j < len(text) and text[j] == "(":
|
||||
depth = 0
|
||||
while j < len(text):
|
||||
depth += {"(": 1, ")": -1}.get(text[j], 0)
|
||||
j += 1
|
||||
if depth == 0:
|
||||
break
|
||||
i = j
|
||||
out.append(text[i:])
|
||||
return " ".join("".join(out).split())
|
||||
|
||||
|
||||
def canon(t):
|
||||
"""Canonical spelling for comparing an Xbox and a PC parameter or return type."""
|
||||
t = " ".join(t.split())
|
||||
t = re.sub(r"\s*\*\s*", "*", t)
|
||||
t = re.sub(r"\s*&\s*", "&", t)
|
||||
t = t.replace("LPCWSTR", "const WCHAR*").replace("LPCSTR", "const char*")
|
||||
t = re.sub(r"\bWINBOOL\b", "BOOL", t)
|
||||
t = re.sub(r"\bFLOAT\b", "float", t)
|
||||
t = re.sub(r"^const IID&$", "REFIID", t)
|
||||
t = re.sub(r"^const GUID&$", "REFGUID", t)
|
||||
if "*" not in t and "&" not in t and "[" not in t:
|
||||
t = re.sub(r"^const ", "", t) # top-level const on a by-value parameter
|
||||
return t
|
||||
|
||||
|
||||
def xbox_param_type(p):
|
||||
p = " ".join(p.split())
|
||||
m = re.match(r"^(.*?)(\w+)(\[[^\]]*\])$", p)
|
||||
if m:
|
||||
return canon(m.group(1)) + m.group(3)
|
||||
m = re.match(r"^(.*[\s\*&])(\w+)$", p)
|
||||
return canon(m.group(1) if m else p)
|
||||
|
||||
|
||||
def parse_xbox(text):
|
||||
iids = {m.group(1): m.groups()[1:] for m in re.finditer(
|
||||
r"^D3DINTERFACE\((\w+),\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+),"
|
||||
r"\s*(\w+),\s*(\w+),\s*(\w+),\s*(\w+)\)", text, re.M)}
|
||||
bases = {m.group(1): m.group(2) for m in re.finditer(
|
||||
r"^D3DINTERFACE\((\w+),[^)]*\)\s*:\s*public\s+(\w+)", text, re.M)}
|
||||
tables = {}
|
||||
for m in re.finditer(r"struct\s+(\w+)_Function_Table\s*\{((?:(?!struct\s+\w+_Function_Table\b).)*?)\n\s*\};", text, re.S):
|
||||
entries = []
|
||||
for decl in re.split(r";\s*\n", m.group(2) + "\n"):
|
||||
decl = strip_sal(decl).rstrip(";").strip()
|
||||
b = re.match(r"^(\w+)_Function_Table\s+\w+$", decl)
|
||||
if b:
|
||||
entries.append(("base", b.group(1)))
|
||||
continue
|
||||
f = re.match(r"^(.*?)\(\s*D3DAPI\s*\*\s*(\w+)\s*\)\s*\((.*)\)$", decl, re.S)
|
||||
if f:
|
||||
params = [x.strip() for x in f.group(3).split(",") if x.strip() and x.strip() != "void"]
|
||||
entries.append(("fn", (f.group(2), canon(f.group(1)), [xbox_param_type(p) for p in params])))
|
||||
tables[m.group(1)] = entries
|
||||
return iids, bases, tables
|
||||
|
||||
|
||||
def flatten(tables, name):
|
||||
out = []
|
||||
for kind, v in tables.get(name, []):
|
||||
out += flatten(tables, v) if kind == "base" else [v]
|
||||
return out
|
||||
|
||||
|
||||
def table_name(iface):
|
||||
return "D3D12" + iface[len("ID3D12"):] if iface.startswith("ID3D12") else iface
|
||||
|
||||
|
||||
def pc_methods(interfaces, leaf):
|
||||
methods = {}
|
||||
for iface in gen_proxy.chain_of(interfaces, leaf):
|
||||
for ret, name, params in interfaces[iface][1]:
|
||||
methods.setdefault(name, (iface, ret, params))
|
||||
return methods
|
||||
|
||||
|
||||
def classify(xret, xparams, pc):
|
||||
"""Returns ('forward', struct_return) when the Xbox slot can call the PC method, else None."""
|
||||
_, pret, pparams = pc
|
||||
pp = [canon(t) + a for t, a in pparams]
|
||||
xp = xparams[1:] # drop the explicit Xbox `this`
|
||||
pr = canon(pret)
|
||||
if xp == pp and (xret == pr or (xret == "void" and pr in ("void", "HRESULT"))):
|
||||
return ("forward", False)
|
||||
if pr.endswith("*") and pp and pp[0] == pr and pr[:-1] == xret and xp == pp[1:]:
|
||||
return ("forward", True) # Xbox returns by value, PC by pointer
|
||||
if xret == "void" and pr.endswith("*") and pp and pp[0] == pr and xp == pp:
|
||||
return ("forward", False) # Xbox out-pointer, PC returns that pointer
|
||||
return None
|
||||
|
||||
|
||||
def emit_forward(family, slot, name, pc, struct_return):
|
||||
iface, pret, pparams = pc
|
||||
params = list(pparams)
|
||||
ret = pret[:-1].strip() if struct_return else pret
|
||||
if struct_return:
|
||||
params = params[1:]
|
||||
decl, call, pre, post = [], [], [], []
|
||||
for i, (t, arr) in enumerate(params):
|
||||
decl.append(f"{t} a{i}{arr}")
|
||||
translate = {"D3D12_CPU_DESCRIPTOR_HANDLE": "bx_xbox_host_cpu_handle",
|
||||
"D3D12_GPU_DESCRIPTOR_HANDLE": "bx_xbox_host_gpu_handle",
|
||||
"D3D12_GPU_VIRTUAL_ADDRESS": "bx_xbox_host_gpu_va"}.get(canon(t)) if not arr else None
|
||||
if translate:
|
||||
call.append(f"{translate}(a{i})")
|
||||
elif WRAPPABLE.match(t) and not arr:
|
||||
call.append(f"bx_xbox_unwrap_as<{WRAPPABLE.match(t).group(2)}>(a{i})")
|
||||
elif WRAPPABLE_ARRAY.match(t) and not arr:
|
||||
elem = WRAPPABLE_ARRAY.match(t).group(1)
|
||||
pre.append(f"BxXboxUnwrapArray<{elem}> u{i}(a{i}, {find_count(params, i, name)});")
|
||||
pre.append(f"if (!u{i}.ok()) return {failure_value(ret)};")
|
||||
call.append(f"u{i}.data()")
|
||||
else:
|
||||
call.append(f"a{i}")
|
||||
wrap_out = len(params) >= 2 and canon(params[-2][0]) == "REFIID" and canon(params[-1][0]) == "void**"
|
||||
host = f"bx_xbox_host<{iface}>(self)"
|
||||
lines = [f"static {ret} STDMETHODCALLTYPE x_{family}_{slot}(void* self{''.join(', ' + d for d in decl)}) {{",
|
||||
f' BX_D3D_TRACE("Xbox{family}", "{name}");']
|
||||
lines += [" " + p for p in pre]
|
||||
if struct_return:
|
||||
lines += [f" {ret} result{{}};", f" {host}->{name}(&result{''.join(', ' + c for c in call)});",
|
||||
" return result;"]
|
||||
elif ret == "void":
|
||||
lines.append(f" {host}->{name}({', '.join(call)});")
|
||||
elif wrap_out and ret == "HRESULT":
|
||||
n = len(params)
|
||||
lines += [f" HRESULT hr = {host}->{name}({', '.join(call)});",
|
||||
f' if (FAILED(hr)) bx_xbox_log_host_failure("Xbox{family}", "{name}", hr);',
|
||||
f" return bx_xbox_wrap_result(hr, a{n - 2}, a{n - 1});"]
|
||||
elif ret == "HRESULT":
|
||||
lines += [f" HRESULT hr = {host}->{name}({', '.join(call)});",
|
||||
f' if (FAILED(hr)) bx_xbox_log_host_failure("Xbox{family}", "{name}", hr);',
|
||||
" return hr;"]
|
||||
else:
|
||||
lines.append(f" return {host}->{name}({', '.join(call)});")
|
||||
return lines + ["}"]
|
||||
|
||||
|
||||
def find_count(params, index, name=""):
|
||||
# The element count is the nearest UINT parameter, before the array or (as in
|
||||
# SetEventOnMultipleFenceCompletion) after it.
|
||||
for j in list(range(index - 1, -1, -1)) + list(range(index + 1, len(params))):
|
||||
if canon(params[j][0]) in ("UINT", "UINT32"):
|
||||
return f"a{j}"
|
||||
sys.exit(f"no element count before array parameter {index} of {name}: {params}")
|
||||
|
||||
|
||||
def failure_value(ret):
|
||||
return {"HRESULT": "E_OUTOFMEMORY", "void": ""}.get(ret, "{}")
|
||||
|
||||
|
||||
STRUCT_TYPES = set() # filled from the Xbox header's `typedef struct` names
|
||||
|
||||
|
||||
def emit_stub(family, slot, name, xret, reason):
|
||||
stub = f'BX_VTABLE_STUB_LOG("Xbox{family}", {slot}u, "{name}");'
|
||||
if xret == "HRESULT":
|
||||
return [f"/* {reason} */",
|
||||
f"static HRESULT STDMETHODCALLTYPE x_{family}_{slot}(void*) {{ {stub} return E_NOTIMPL; }}"]
|
||||
if xret in STRUCT_TYPES:
|
||||
# A struct returned by value comes back through a hidden pointer passed first; it is
|
||||
# handed back unfilled (the stub log says so). Structs of 8 bytes or less are returned in
|
||||
# RAX instead; none of the stubbed slots returns one today.
|
||||
return [f"/* {reason}; returns struct {xret} */",
|
||||
f"static void* STDMETHODCALLTYPE x_{family}_{slot}(void* result, void*) {{ {stub} return result; }}"]
|
||||
# Integers, enums, BOOL and pointers come back zero; a void slot ignores the value.
|
||||
return [f"/* {reason} */",
|
||||
f"static UINT64 STDMETHODCALLTYPE x_{family}_{slot}(void*) {{ {stub} return 0; }}"]
|
||||
|
||||
|
||||
def guid_literal(parts):
|
||||
g = [p.lower() for p in parts]
|
||||
return (f"{{0x{g[0]}, 0x{g[1]}, 0x{g[2]}, "
|
||||
f"{{0x{g[3]}, 0x{g[4]}, 0x{g[5]}, 0x{g[6]}, 0x{g[7]}, 0x{g[8]}, 0x{g[9]}, 0x{g[10]}}}}}")
|
||||
|
||||
|
||||
def chain(bases, leaf):
|
||||
out, cur = [], leaf
|
||||
while cur in bases:
|
||||
out.append(cur)
|
||||
cur = bases[cur]
|
||||
return out + [cur]
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
sys.exit(__doc__)
|
||||
xtext = Path(sys.argv[1]).read_text(encoding="utf-8", errors="replace").replace("\r\n", "\n") # parts of the header use CRLF
|
||||
pc_header = sys.argv[2] if len(sys.argv) > 2 else gen_proxy.find_header()
|
||||
interfaces = gen_proxy.parse_interfaces(Path(pc_header).read_text(encoding="utf-8", errors="replace"))
|
||||
iids, bases, tables = parse_xbox(xtext)
|
||||
STRUCT_TYPES.update(re.findall(r"typedef\s+struct\s+(\w+)", xtext))
|
||||
STRUCT_TYPES.update(t for t in re.findall(r"^struct\s+(\w+)\s*$", xtext, re.M))
|
||||
|
||||
note = ("// Generated by shims/d3d12_xs/tools/gen_xbox_tables.py from the Xbox Series D3D12 header (slot\n"
|
||||
"// order, names and types only) and the toolchain's <d3d12.h>. Do not edit by hand.")
|
||||
h = [note, "#ifndef BETTERXEN_D3D12_XS_XBOX_TABLES_GENERATED_H",
|
||||
"#define BETTERXEN_D3D12_XS_XBOX_TABLES_GENERATED_H", "", '#include "xbox_facade.h"', ""]
|
||||
c = [note, '#include "xbox_tables_generated.h"', "", "namespace {", ""]
|
||||
summary = []
|
||||
for leaf, (pc_leaf, family) in FAMILIES.items():
|
||||
slots = flatten(tables, table_name(leaf))
|
||||
if not slots:
|
||||
sys.exit(f"no Xbox function table for {leaf}")
|
||||
pc = pc_methods(interfaces, pc_leaf)
|
||||
counts = {"forward": 0, "shared": 0, "stub": 0}
|
||||
names = []
|
||||
for slot, (name, xret, xparams) in enumerate(slots):
|
||||
if name in SHARED or name in CUSTOM.get(family, {}):
|
||||
fn = SHARED.get(name) or CUSTOM[family][name]
|
||||
names.append(f"reinterpret_cast<const void*>(&{fn})")
|
||||
counts["shared"] += 1
|
||||
continue
|
||||
kind = classify(xret, xparams, pc[name]) if name in pc else None
|
||||
if kind:
|
||||
c += emit_forward(family, slot, name, pc[name], kind[1])
|
||||
counts["forward"] += 1
|
||||
else:
|
||||
reason = "signature differs from the PC method" if name in pc else "Xbox-only method"
|
||||
c += emit_stub(family, slot, name, xret, reason)
|
||||
counts["stub"] += 1
|
||||
names.append(f"reinterpret_cast<const void*>(&x_{family}_{slot})")
|
||||
c += ["", f"const void* const k{family}Table[] = {{"] + [f" {n}," for n in names] + ["};", ""]
|
||||
family_iids = [i for i in chain(bases, leaf) if i in iids and i not in ("IGraphicsUnknown",)]
|
||||
c += [f"const IID k{family}Iids[] = {{"] + [f" {guid_literal(iids[i])}, /* {i} */" for i in family_iids]
|
||||
c += ["};", ""]
|
||||
h.append(f"extern const BxXboxIface bx_xbox_{family};")
|
||||
summary.append(f"{family}: {len(slots)} slots, {counts}")
|
||||
c.append(f"/* {leaf}: {len(slots)} slots ({counts['forward']} forwarded, {counts['shared']} shared, "
|
||||
f"{counts['stub']} stubs); hosted on {pc_leaf}. */")
|
||||
c += [f"const IID kHost{family} = __uuidof({pc_leaf});", ""]
|
||||
c += ["} // namespace", ""]
|
||||
for leaf, (pc_leaf, family) in FAMILIES.items():
|
||||
size = len(flatten(tables, table_name(leaf)))
|
||||
c.append(f'extern const BxXboxIface bx_xbox_{family} = {{"{leaf}", k{family}Iids, '
|
||||
f"sizeof(k{family}Iids) / sizeof(IID), &kHost{family}, k{family}Table, {size}}};")
|
||||
c += ["", "extern const BxXboxIface* const bx_xbox_ifaces[] = {"]
|
||||
c += [f" &bx_xbox_{family}," for _, family in FAMILIES.values()] + ["};",
|
||||
f"extern const size_t bx_xbox_iface_count = {len(FAMILIES)};"]
|
||||
h += ["", "extern const BxXboxIface* const bx_xbox_ifaces[];", "extern const size_t bx_xbox_iface_count;",
|
||||
"", "#endif"]
|
||||
(OUT_DIR / "xbox_tables_generated.h").write_text("\n".join(h) + "\n")
|
||||
(OUT_DIR / "xbox_tables_generated.cpp").write_text("\n".join(c) + "\n")
|
||||
print("\n".join(summary))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,157 @@
|
||||
#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 initial probe: a magic word and
|
||||
* the following 32-bit value. Magic is 'BXVM' (0x4D565842); a matching header
|
||||
* and struct size select the full BetterXen block. A zero first word selects
|
||||
* the Xbox decoder, which checks the full block and may write its two address
|
||||
* outputs. Other headers (including unrecognized nonzero Xbox flags) fall
|
||||
* back with S_OK and no writes. A null pointer is not read.
|
||||
*
|
||||
* 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 returns E_INVALIDARG even if its output is read-only. Valid
|
||||
* inputs with an initially unwritable output fall back with S_OK and a stub
|
||||
* log. A failed write after the accessibility check returns E_INVALIDARG.
|
||||
*
|
||||
* 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,
|
||||
* CreatePlacedResource1 or CreatePlacedResource2 holds the wrapper for its
|
||||
* lifetime, and all three validate the placement on every heap first.
|
||||
* 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.
|
||||
* All three placement methods 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");
|
||||
|
||||
/*
|
||||
* The Xbox virtual-memory configuration (D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION, d3d12_xs.h).
|
||||
*
|
||||
* Source: the authorized GDK documentation of D3D12ConfigureVirtualMemoryX and the
|
||||
* structure. Call-site observation of a project-authorized target build agrees with it: a
|
||||
* zero-initialized block with 3 or 4 in the page-table field and no flags.
|
||||
*
|
||||
* Documented: flags must be none (0); the GPU page table is sized in 4 MB units, at least 1
|
||||
* and clamped to 33 (default 5, 20 MB); the frame-buffer preserve size is 0 (none), -1 (the
|
||||
* legacy size, about 10 MB) or a byte count clamped to 64 MB; the two addresses are outputs,
|
||||
* the minimum always 2 GB; and the call fails with E_FAIL once a D3D12 device exists.
|
||||
*
|
||||
* The host does not size GPU page tables or keep a cross-process frame buffer, so the
|
||||
* decoder records both, writes the outputs and still logs BX_STUB_LOG. The maximum address
|
||||
* is documented only for the default size; for other sizes it is scaled linearly from that
|
||||
* value, an inference the log marks as max_estimated=1. A page count of 0 is refused: the
|
||||
* value of the header's DEFAULT constant is not documented.
|
||||
*/
|
||||
struct BxXboxVirtualMemoryConfig {
|
||||
uint32_t flags;
|
||||
uint32_t page_table_memory_4mb_page_count;
|
||||
uint32_t frame_buffer_preserve_memory_size_bytes;
|
||||
uint32_t padding;
|
||||
uint64_t minimum_valid_graphics_address;
|
||||
uint64_t maximum_valid_graphics_address;
|
||||
};
|
||||
static_assert(sizeof(BxXboxVirtualMemoryConfig) == 32, "Xbox config block is 32 bytes");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, flags) == 0, "flags offset");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, page_table_memory_4mb_page_count) == 4,
|
||||
"page_table_memory_4mb_page_count offset");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, frame_buffer_preserve_memory_size_bytes) == 8,
|
||||
"frame_buffer_preserve_memory_size_bytes offset");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, minimum_valid_graphics_address) == 16,
|
||||
"minimum_valid_graphics_address offset");
|
||||
static_assert(offsetof(BxXboxVirtualMemoryConfig, maximum_valid_graphics_address) == 24,
|
||||
"maximum_valid_graphics_address offset");
|
||||
|
||||
constexpr uint32_t BX_D3D12_XBOX_PAGE_TABLE_DEFAULT_4MB_PAGES = 5u;
|
||||
constexpr uint32_t BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES = 33u;
|
||||
constexpr uint32_t BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_LEGACY = 0xFFFFFFFFu;
|
||||
constexpr uint32_t BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES = 64u * 1024u * 1024u;
|
||||
constexpr uint64_t BX_D3D12_XBOX_MIN_GRAPHICS_ADDRESS = 2ull * 1024ull * 1024ull * 1024ull;
|
||||
/* 159.375 GiB at the default 5 pages (20 MB), so 31.875 GiB per 4 MB page. */
|
||||
constexpr uint64_t BX_D3D12_XBOX_GRAPHICS_BYTES_PER_4MB_PAGE = 0x7F8000000ull;
|
||||
|
||||
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.
|
||||
CreatePlacedResource1 and CreatePlacedResource2 reach the same placement code through the
|
||||
generated proxy (gen_proxy.py HANDOFF), not through a vtable patch. */
|
||||
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 */
|
||||
@@ -0,0 +1,316 @@
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
|
||||
/*
|
||||
* ADR 0009: Xbox-layout objects over the PC proxies. See xbox_facade.h for the layout and
|
||||
* xbox_tables_generated.cpp (tools/gen_xbox_tables.py) for the slot order.
|
||||
*/
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint8_t kOutOfLineCommon = 0x1; // Xbox OutOfLineFlags_Common
|
||||
|
||||
struct Entry {
|
||||
IUnknown* host;
|
||||
const BxXboxIface* iface;
|
||||
BxXboxObject* object;
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
Entry* g_entries = nullptr;
|
||||
size_t g_count = 0;
|
||||
size_t g_capacity = 0;
|
||||
|
||||
bool same_iid(REFIID a, REFIID b) {
|
||||
return std::memcmp(&a, &b, sizeof(IID)) == 0;
|
||||
}
|
||||
|
||||
bool answers(const BxXboxIface* iface, REFIID riid) {
|
||||
for (size_t i = 0; i < iface->iid_count; ++i) {
|
||||
if (same_iid(iface->iids[i], riid)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const BxXboxIface* iface_of_object(const void* p) {
|
||||
if (!p) return nullptr;
|
||||
const void* table = *static_cast<const void* const*>(p);
|
||||
for (size_t i = 0; i < bx_xbox_iface_count; ++i) {
|
||||
if (bx_xbox_ifaces[i]->table == table) return bx_xbox_ifaces[i];
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void log_iid(const char* event, const char* what, REFIID riid, bx_log_level_t level = BX_LOG_WARN) {
|
||||
char guid[40];
|
||||
bx_format_guid(riid, guid, sizeof(guid));
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s iid=%s", what, guid);
|
||||
bx_log_emit(level, "d3d12_xs", event, detail);
|
||||
}
|
||||
|
||||
BxXboxObject* find_locked(IUnknown* host, const BxXboxIface* iface) {
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_entries[i].host == host && g_entries[i].iface == iface) return g_entries[i].object;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool insert_locked(Entry entry) {
|
||||
if (g_count == g_capacity) {
|
||||
const size_t capacity = g_capacity ? g_capacity * 2 : 64;
|
||||
auto* grown = new (std::nothrow) Entry[capacity];
|
||||
if (!grown) return false;
|
||||
if (g_count) std::memcpy(grown, g_entries, g_count * sizeof(Entry));
|
||||
delete[] g_entries;
|
||||
g_entries = grown;
|
||||
g_capacity = capacity;
|
||||
}
|
||||
g_entries[g_count++] = entry;
|
||||
return true;
|
||||
}
|
||||
|
||||
void erase_locked(BxXboxObject* object) {
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_entries[i].object == object) {
|
||||
g_entries[i] = g_entries[--g_count];
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
const BxXboxIface* bx_xbox_iface_for(REFIID riid) {
|
||||
for (size_t i = 0; i < bx_xbox_iface_count; ++i) {
|
||||
if (answers(bx_xbox_ifaces[i], riid)) return bx_xbox_ifaces[i];
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void* bx_xbox_wrap(REFIID riid, void* raw, HRESULT* failure) {
|
||||
if (failure) *failure = E_OUTOFMEMORY;
|
||||
if (!raw) return nullptr;
|
||||
auto* unknown = static_cast<IUnknown*>(raw);
|
||||
const BxXboxIface* iface = bx_xbox_iface_for(riid);
|
||||
if (!iface) {
|
||||
log_iid("xbox_unwrapped", "no Xbox table answers this interface; returning the PC object", riid);
|
||||
return raw;
|
||||
}
|
||||
void* typed = nullptr;
|
||||
if (FAILED(unknown->QueryInterface(*iface->host_iid, &typed)) || !typed) {
|
||||
// The Xbox table forwards to an interface this host object lacks. Handing back the PC
|
||||
// object would let a title call Xbox slot numbers on a PC table, so this fails instead.
|
||||
log_iid("xbox_wrap_refused", iface->name, *iface->host_iid, BX_LOG_ERROR);
|
||||
unknown->Release();
|
||||
if (failure) *failure = E_NOINTERFACE;
|
||||
return nullptr;
|
||||
}
|
||||
unknown->Release();
|
||||
auto* host = static_cast<IUnknown*>(typed);
|
||||
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (BxXboxObject* existing = find_locked(host, iface)) {
|
||||
ULONG refs = existing->refs.load();
|
||||
while (refs != 0 && !existing->refs.compare_exchange_weak(refs, refs + 1)) {
|
||||
}
|
||||
if (refs != 0) {
|
||||
existing->xbox_ref_count = refs + 1;
|
||||
host->Release();
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
auto* object = new (std::nothrow) BxXboxObject{};
|
||||
if (!object) {
|
||||
host->Release();
|
||||
return nullptr;
|
||||
}
|
||||
object->function_table = iface->table;
|
||||
object->xbox_ref_count = 1;
|
||||
if (iface == &bx_xbox_Device) {
|
||||
object->xbox_fields[kBxXboxDeviceOutOfLineOffset - offsetof(BxXboxObject, xbox_fields)] = kOutOfLineCommon;
|
||||
}
|
||||
object->host = host;
|
||||
object->iface = iface;
|
||||
object->refs.store(1);
|
||||
if (!insert_locked({host, iface, object})) {
|
||||
host->Release();
|
||||
delete object;
|
||||
return nullptr;
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
HRESULT bx_xbox_wrap_result(HRESULT hr, REFIID riid, void** ppv) {
|
||||
if (SUCCEEDED(hr) && ppv && *ppv) {
|
||||
HRESULT failure = E_OUTOFMEMORY;
|
||||
void* wrapped = bx_xbox_wrap(riid, *ppv, &failure);
|
||||
if (!wrapped) {
|
||||
*ppv = nullptr;
|
||||
return failure;
|
||||
}
|
||||
*ppv = wrapped;
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
IUnknown* bx_xbox_unwrap(const void* p) {
|
||||
if (iface_of_object(p)) return static_cast<const BxXboxObject*>(p)->host;
|
||||
return static_cast<IUnknown*>(const_cast<void*>(p));
|
||||
}
|
||||
|
||||
void bx_xbox_log_host_failure(const char* iface, const char* method, HRESULT hr) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s::%s hr=0x%08lx", iface, method, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "host_call_failed", detail);
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_query_interface(void* self, REFIID riid, void** ppv) {
|
||||
auto* object = static_cast<BxXboxObject*>(self);
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
if (same_iid(riid, IID_BxProxyHost)) {
|
||||
*ppv = object->host; // by contract, no reference (see bx_unwrap_raw)
|
||||
return S_OK;
|
||||
}
|
||||
if (same_iid(riid, __uuidof(IUnknown)) || answers(object->iface, riid)) {
|
||||
bx_xbox_add_ref(self);
|
||||
*ppv = self;
|
||||
return S_OK;
|
||||
}
|
||||
void* raw = nullptr;
|
||||
HRESULT hr = object->host->QueryInterface(riid, &raw);
|
||||
if (FAILED(hr) || !raw) return hr;
|
||||
if (bx_xbox_iface_for(riid)) {
|
||||
HRESULT failure = E_OUTOFMEMORY;
|
||||
*ppv = bx_xbox_wrap(riid, raw, &failure);
|
||||
return *ppv ? S_OK : failure;
|
||||
}
|
||||
log_iid("xbox_qi_unwrapped", object->iface->name, riid);
|
||||
*ppv = raw;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE bx_xbox_add_ref(void* self) {
|
||||
auto* object = static_cast<BxXboxObject*>(self);
|
||||
const ULONG refs = object->refs.fetch_add(1) + 1;
|
||||
object->xbox_ref_count = refs;
|
||||
return refs;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE bx_xbox_release(void* self) {
|
||||
auto* object = static_cast<BxXboxObject*>(self);
|
||||
std::unique_lock<std::mutex> guard(g_lock);
|
||||
const ULONG refs = object->refs.fetch_sub(1) - 1;
|
||||
object->xbox_ref_count = refs;
|
||||
if (refs != 0) return refs;
|
||||
erase_locked(object);
|
||||
guard.unlock();
|
||||
if (object->iface == &bx_xbox_Resource) bx_xbox_placed_forget(object->host);
|
||||
if (object->iface == &bx_xbox_DescriptorHeap) bx_xbox_descriptor_heap_forget(object->host);
|
||||
if (object->iface == &bx_xbox_Fence) bx_xbox_fence_forget(object->host);
|
||||
if (object->iface == &bx_xbox_PipelineState) bx_xbox_pipeline_forget(object->host);
|
||||
if (object->iface == &bx_xbox_GraphicsCommandList) {
|
||||
bx_xbox_list_forget(object->host);
|
||||
bx_xbox_gpu_writes_reset(object->host);
|
||||
}
|
||||
object->host->Release();
|
||||
delete object;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_get_device(void* self, REFIID riid, void** ppv) {
|
||||
if (!ppv) return;
|
||||
*ppv = nullptr;
|
||||
auto* child = bx_xbox_host<ID3D12DeviceChild>(self);
|
||||
void* device = nullptr;
|
||||
if (SUCCEEDED(child->GetDevice(riid, &device)) && device) *ppv = bx_xbox_wrap(riid, device);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_queue_x(void* self, const BxXboxCommandQueueDesc* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommandQueueX");
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
D3D12_COMMAND_QUEUE_DESC pc{};
|
||||
pc.Type = desc->Type;
|
||||
pc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
|
||||
pc.Flags = desc->Flags;
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "type=%d flags=0x%x engine_or_pipe=%u queue=%u (indices not used by the host)",
|
||||
static_cast<int>(desc->Type), static_cast<unsigned>(desc->Flags), desc->EngineOrPipeIndex,
|
||||
desc->QueueIndex);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommandQueueX", detail);
|
||||
const HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateCommandQueue(&pc, riid, ppv);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_list_x(void* self, const BxXboxCommandListDesc* desc,
|
||||
ID3D12CommandAllocator* allocator,
|
||||
ID3D12PipelineState* initial_state, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommandListX");
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "type=%d xbox_flags=0x%x node_mask=0x%x barrier_batch=%u (flags and batch not used by the host)",
|
||||
static_cast<int>(desc->Type), desc->Flags, desc->NodeMask, desc->ResourceBarrierBatchSize);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommandListX", detail);
|
||||
const HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateCommandList(
|
||||
desc->NodeMask, desc->Type, bx_xbox_unwrap_as(allocator),
|
||||
bx_xbox_pipeline_is_null(initial_state) ? nullptr : bx_xbox_unwrap_as(initial_state), riid, ppv);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateCommandListX", hr);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, const D3D12_RESOURCE_BARRIER* barriers) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "ResourceBarrier");
|
||||
if (!barriers || count == 0) return 0;
|
||||
constexpr UINT kInline = 32;
|
||||
D3D12_RESOURCE_BARRIER inline_copy[kInline];
|
||||
D3D12_RESOURCE_BARRIER* copy = count <= kInline ? inline_copy : new (std::nothrow) D3D12_RESOURCE_BARRIER[count];
|
||||
if (!copy) return 0;
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
copy[i] = barriers[i];
|
||||
switch (copy[i].Type) {
|
||||
case D3D12_RESOURCE_BARRIER_TYPE_TRANSITION:
|
||||
copy[i].Transition.pResource = bx_xbox_unwrap_as(copy[i].Transition.pResource);
|
||||
break;
|
||||
case D3D12_RESOURCE_BARRIER_TYPE_ALIASING:
|
||||
copy[i].Aliasing.pResourceBefore = bx_xbox_unwrap_as(copy[i].Aliasing.pResourceBefore);
|
||||
copy[i].Aliasing.pResourceAfter = bx_xbox_unwrap_as(copy[i].Aliasing.pResourceAfter);
|
||||
break;
|
||||
case D3D12_RESOURCE_BARRIER_TYPE_UAV:
|
||||
copy[i].UAV.pResource = bx_xbox_unwrap_as(copy[i].UAV.pResource);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResourceBarrier(count, copy);
|
||||
if (copy != inline_copy) delete[] copy;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
|
||||
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
|
||||
const D3D12_BOX* box) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyTextureRegion");
|
||||
D3D12_TEXTURE_COPY_LOCATION d{}, s{};
|
||||
if (dst) {
|
||||
d = *dst;
|
||||
d.pResource = bx_xbox_unwrap_as(d.pResource);
|
||||
}
|
||||
if (src) {
|
||||
s = *src;
|
||||
s.pResource = bx_xbox_unwrap_as(s.pResource);
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyTextureRegion(dst ? &d : nullptr, x, y, z, src ? &s : nullptr, box);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,343 @@
|
||||
#ifndef BETTERXEN_D3D12_XS_XBOX_FACADE_H
|
||||
#define BETTERXEN_D3D12_XS_XBOX_FACADE_H
|
||||
|
||||
/*
|
||||
* Xbox-layout objects in front of the PC proxies (ADR 0009).
|
||||
*
|
||||
* A title built against the Xbox Series D3D12 header calls every method through the object's
|
||||
* function table, whose slot order differs from PC D3D12. A BxXboxObject has the Xbox object
|
||||
* layout and an Xbox-order table (xbox_tables_generated.cpp); each slot forwards to the PC
|
||||
* object it hosts, which is usually one of the PC proxies in proxy.h.
|
||||
*
|
||||
* Layout (from the Xbox header): the function-table pointer, a 32-bit flags word and the
|
||||
* reference count make up every object's 16-byte base. ID3D12Device adds a 64-bit null constant
|
||||
* buffer address at +16 and a 64-byte union at +24 whose first byte, m_OutOfLineFlags, makes
|
||||
* inline helpers call out through the table when non-zero. The same layout is used for every
|
||||
* interface family; the fields after the base are ignored by the others. Command lists add a
|
||||
* put buffer and are not wrapped yet.
|
||||
*/
|
||||
#include "proxy.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <new>
|
||||
|
||||
struct BxXboxIface {
|
||||
const char* name; // Xbox leaf interface, for logs
|
||||
const IID* iids; // Xbox interface IDs this table answers
|
||||
size_t iid_count;
|
||||
const IID* host_iid; // PC interface the hosted object provides
|
||||
const void* const* table; // Xbox-order function table
|
||||
size_t slots;
|
||||
};
|
||||
|
||||
/*
|
||||
* Interface-specific Xbox fields follow the 16-byte base. ID3D12Device: null constant-buffer
|
||||
* address at +16, m_OutOfLineFlags at +24. ID3D12GraphicsCommandList: m_Putter at +16 (five
|
||||
* put-buffer pointers and 256 reserved bytes), CPU state at +312, the graphics and compute root
|
||||
* packet-header tables at +316 and +828 and the PSO shadow at +1340; the whole object is 1384
|
||||
* bytes (an 8-byte field at +1376 follows), which the title's inline code writes. Zero put
|
||||
* pointers make every inline fast path fail its room check and call through the table. The other
|
||||
* interfaces define no fields here. The area below is the largest Xbox object (the command list)
|
||||
* plus a margin, so title writes never reach BetterXen's state after it: with 1360 bytes the
|
||||
* list's last field was BetterXen's host pointer, and the title overwrote it.
|
||||
*/
|
||||
constexpr size_t kBxXboxCommandListBytes = 1384;
|
||||
constexpr size_t kBxXboxFieldBytes = kBxXboxCommandListBytes - 16 + 64;
|
||||
|
||||
struct BxXboxObject {
|
||||
const void* const* function_table;
|
||||
uint32_t xbox_flags;
|
||||
uint32_t xbox_ref_count; // kept equal to `refs` for anything reading the Xbox field
|
||||
uint8_t xbox_fields[kBxXboxFieldBytes];
|
||||
// BetterXen state, after every field the Xbox layout defines.
|
||||
IUnknown* host; // owns one reference; typed as iface->host_iid
|
||||
const BxXboxIface* iface;
|
||||
std::atomic<ULONG> refs;
|
||||
};
|
||||
static_assert(offsetof(BxXboxObject, xbox_ref_count) == 12, "Xbox m_RefCount offset");
|
||||
static_assert(offsetof(BxXboxObject, xbox_fields) == 16, "Xbox interface fields start after the base");
|
||||
static_assert(offsetof(BxXboxObject, host) >= kBxXboxCommandListBytes, "BetterXen state lies past every Xbox field");
|
||||
static_assert(offsetof(BxXboxObject, host) >= 1372, "BetterXen state follows the Xbox command-list fields");
|
||||
constexpr size_t kBxXboxDeviceOutOfLineOffset = 24;
|
||||
|
||||
/* The Xbox table for `riid`, or nullptr when none of the wrapped families answers it. */
|
||||
const BxXboxIface* bx_xbox_iface_for(REFIID riid);
|
||||
|
||||
/* Wraps `host` (consumes the caller's reference) in the Xbox object for `riid`. One Xbox object
|
||||
exists per host object and family. When no family answers `riid`, `host` is returned as is
|
||||
and that is logged. */
|
||||
void* bx_xbox_wrap(REFIID riid, void* host, HRESULT* failure = nullptr);
|
||||
|
||||
/* After a (REFIID, void**) creation call: wraps a successful result. */
|
||||
HRESULT bx_xbox_wrap_result(HRESULT hr, REFIID riid, void** ppv);
|
||||
|
||||
/* The hosted PC object when `p` is one of our Xbox objects, otherwise `p` itself. */
|
||||
IUnknown* bx_xbox_unwrap(const void* p);
|
||||
template <typename T>
|
||||
T* bx_xbox_unwrap_as(T* p) {
|
||||
return static_cast<T*>(static_cast<void*>(bx_xbox_unwrap(p)));
|
||||
}
|
||||
template <typename T>
|
||||
const T* bx_xbox_unwrap_as(const T* p) {
|
||||
return static_cast<const T*>(static_cast<void*>(bx_xbox_unwrap(p)));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T* bx_xbox_host(void* self) {
|
||||
return static_cast<T*>(static_cast<BxXboxObject*>(self)->host);
|
||||
}
|
||||
|
||||
/* Unwraps an array of interface pointers for one forwarded call. */
|
||||
template <typename T>
|
||||
class BxXboxUnwrapArray {
|
||||
public:
|
||||
BxXboxUnwrapArray(T* const* items, UINT count) : count_(count) {
|
||||
if (!items || count == 0) {
|
||||
ok_ = true;
|
||||
return;
|
||||
}
|
||||
data_ = count <= kInline ? inline_ : new (std::nothrow) T*[count];
|
||||
ok_ = data_ != nullptr;
|
||||
for (UINT i = 0; ok_ && i < count; ++i) data_[i] = bx_xbox_unwrap_as(items[i]);
|
||||
}
|
||||
~BxXboxUnwrapArray() {
|
||||
if (data_ && data_ != inline_) delete[] data_;
|
||||
}
|
||||
BxXboxUnwrapArray(const BxXboxUnwrapArray&) = delete;
|
||||
BxXboxUnwrapArray& operator=(const BxXboxUnwrapArray&) = delete;
|
||||
bool ok() const { return ok_; }
|
||||
T* const* data() const { return data_; }
|
||||
|
||||
private:
|
||||
static constexpr UINT kInline = 16;
|
||||
T* inline_[kInline] = {};
|
||||
T** data_ = nullptr;
|
||||
UINT count_ = 0;
|
||||
bool ok_ = false;
|
||||
};
|
||||
|
||||
extern "C" {
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_query_interface(void* self, REFIID riid, void** ppv);
|
||||
ULONG STDMETHODCALLTYPE bx_xbox_add_ref(void* self);
|
||||
ULONG STDMETHODCALLTYPE bx_xbox_release(void* self);
|
||||
void STDMETHODCALLTYPE bx_xbox_get_device(void* self, REFIID riid, void** ppv);
|
||||
|
||||
/* Xbox ID3D12Device::CreateCommandQueueX: the Xbox queue description selects a hardware
|
||||
engine/pipe and queue index; the PC queue gets the same type and flags at normal priority. */
|
||||
struct BxXboxCommandQueueDesc {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
D3D12_COMMAND_QUEUE_FLAGS Flags;
|
||||
UINT EngineOrPipeIndex;
|
||||
UINT QueueIndex;
|
||||
};
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_queue_x(void* self, const BxXboxCommandQueueDesc* desc,
|
||||
REFIID riid, void** ppv);
|
||||
|
||||
/* Xbox ID3D12Device::CreateCommandListX. ResourceBarrierBatchSize sizes an Xbox-side batch and is
|
||||
not used by the host. */
|
||||
struct BxXboxCommandListDesc {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags;
|
||||
UINT NodeMask;
|
||||
UINT ResourceBarrierBatchSize;
|
||||
};
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_list_x(void* self, const BxXboxCommandListDesc* desc,
|
||||
ID3D12CommandAllocator* allocator,
|
||||
ID3D12PipelineState* initial_state, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
/* Frame pacing (frame_pacing.cpp): Xbox ID3D12Device::SetFrameIntervalX, ScheduleFrameEventX and
|
||||
WaitFrameEventX, emulated with a host timer. Event types: 0 origin, 1 display vblank, 2 flip. */
|
||||
struct BxXboxFrameObjectList {
|
||||
UINT Count;
|
||||
HANDLE* pObjects;
|
||||
};
|
||||
struct BxXboxFrameWaitList {
|
||||
UINT Count;
|
||||
HANDLE* pObjects;
|
||||
UINT* pSignaledObjectIndex;
|
||||
};
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_set_frame_interval_x(void* self, IDXGIOutput* output, UINT length_us,
|
||||
UINT period, UINT flags);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_schedule_frame_event_x(void* self, UINT type, UINT offset_us,
|
||||
const BxXboxFrameObjectList* signals, UINT flags);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void* self, UINT type, UINT timeout_ms,
|
||||
const BxXboxFrameWaitList* waits, UINT flags,
|
||||
UINT64* token);
|
||||
|
||||
/*
|
||||
* Title memory and host objects (ADR 0009). Everything that maps title-visible GPU memory to
|
||||
* host objects goes through these functions, so the backend behind them (D3DMetal today) can be
|
||||
* replaced on its own: title descriptor handles to host handles (descriptor_heaps.cpp) and title
|
||||
* GPU addresses to host addresses (placed_x.cpp). Unknown values pass through unchanged.
|
||||
*/
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE bx_xbox_host_cpu_handle(D3D12_CPU_DESCRIPTOR_HANDLE title);
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE bx_xbox_host_gpu_handle(D3D12_GPU_DESCRIPTOR_HANDLE title);
|
||||
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title);
|
||||
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type);
|
||||
void bx_xbox_descriptor_heap_forget(IUnknown* host);
|
||||
/* Records title-visible memory (from XMemAlloc) for a host resource; freed when it is released. */
|
||||
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes);
|
||||
|
||||
/* Logs a host call that failed (`host_call_failed`), so a refusal is never silent. */
|
||||
void bx_xbox_log_host_failure(const char* iface, const char* method, HRESULT hr);
|
||||
|
||||
/* Fences with a title-visible value (fences.cpp). */
|
||||
bool bx_xbox_fence_slot(uint64_t address, ID3D12Fence** host);
|
||||
void bx_xbox_fence_forget(IUnknown* host);
|
||||
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_fence_get_gpu_address_x(void* self);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_fence_signal(void* self, UINT64 value);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_signal(void* self, ID3D12Fence* fence, UINT64 value);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_wait(void* self, ID3D12Fence* fence, UINT64 value);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_wait64_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
|
||||
UINT64 reference, UINT flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_wait32_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, D3D12_COMPARISON_FUNC compare,
|
||||
UINT reference, UINT mask, UINT flags);
|
||||
|
||||
/* GPU value writes into title memory (gpu_writes.cpp). */
|
||||
void bx_xbox_gpu_writes_reset(IUnknown* host_list);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write32_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT flush, UINT flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write64_bop_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT flush, UINT flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write32_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT value, UINT flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write64_top_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 value, UINT flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists(void* self, UINT count, ID3D12CommandList* const* lists);
|
||||
void STDMETHODCALLTYPE bx_xbox_queue_execute_command_lists2_x(void* self, UINT count, ID3D12CommandList* const* lists,
|
||||
UINT64 token, UINT flags);
|
||||
|
||||
/* Pipelines and the opt-in null-render mode (pipelines.cpp). */
|
||||
bool bx_xbox_pipeline_is_null(ID3D12PipelineState* title);
|
||||
void bx_xbox_pipeline_forget(IUnknown* host);
|
||||
void bx_xbox_list_forget(IUnknown* host);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state_x(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
|
||||
UINT extended_count, const void* extended,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state_x(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
|
||||
UINT extended_count, const void* extended,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_pipeline_state(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
|
||||
ID3D12RootSignature* root, REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void* state, REFIID riid,
|
||||
void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void* state, REFIID riid,
|
||||
void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT count, const void* descs, REFIID riid,
|
||||
void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT count, const void* descs, REFIID riid,
|
||||
void** ppv);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12PipelineState* pso);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset_x(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso,
|
||||
UINT flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_sync_x(void* self, UINT sync_flags, UINT control_flags, D3D12_GPU_VIRTUAL_ADDRESS base,
|
||||
SIZE_T size);
|
||||
void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void* self, void* callback, UINT64 context);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UINT instances, UINT first_vertex,
|
||||
UINT first_instance);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indices, UINT instances, UINT first_index,
|
||||
INT base_vertex, UINT first_instance);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSignature* signature, UINT max_commands,
|
||||
ID3D12Resource* arguments, UINT64 arguments_offset,
|
||||
ID3D12Resource* count, UINT64 count_offset);
|
||||
|
||||
/* Map / Unmap: title memory for resources that have it (placed_x.cpp). */
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subresource, const D3D12_RANGE* read, void** data);
|
||||
void STDMETHODCALLTYPE bx_xbox_resource_unmap(void* self, UINT subresource, const D3D12_RANGE* written);
|
||||
void bx_xbox_sync_mapped_buffers();
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT plane_count, const void* planes, const void* parameters);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_batch_x(void* self, UINT batch_count, const void* batches,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages,
|
||||
UINT flags);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_copy_page_mappings_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS destination,
|
||||
UINT range_count, const void* ranges,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS pool, UINT pool_pages, UINT flags);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_queue_clear_page_mappings_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS destination,
|
||||
UINT page_count, UINT flags);
|
||||
|
||||
/* Page pools (placed_x.cpp). */
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_register_page_pool_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS address, UINT pages,
|
||||
HANDLE* handle);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void* self, HANDLE handle);
|
||||
|
||||
/* Committed resources with title-visible memory (committed.cpp). */
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, REFIID riid,
|
||||
void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, REFIID riid,
|
||||
void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
|
||||
D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, UINT32 formats,
|
||||
DXGI_FORMAT* castable, REFIID riid, void** ppv);
|
||||
|
||||
/* Descriptor heaps with title-visible storage (descriptor_heaps.cpp). */
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_descriptor_heap(void* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc,
|
||||
REFIID riid, void** ppv);
|
||||
UINT STDMETHODCALLTYPE bx_xbox_device_get_descriptor_handle_increment_size(void* self, D3D12_DESCRIPTOR_HEAP_TYPE type);
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_cpu_start(void* self);
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_gpu_start(void* self);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
/* `xbox_desc` is a D3D12XBOX_SAMPLER_DESC. */
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_sampler_x(void* self, const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
|
||||
const UINT* dest_sizes, UINT src_ranges,
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, const UINT* src_sizes,
|
||||
D3D12_DESCRIPTOR_HEAP_TYPE type);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
|
||||
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* dsv);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
|
||||
const D3D12_VERTEX_BUFFER_VIEW* views);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_INDEX_BUFFER_VIEW* view);
|
||||
|
||||
/* Resources at a title-chosen GPU address (placed_x.cpp): host shadow resources. */
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
|
||||
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x1(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
|
||||
const D3D12_RESOURCE_DESC1* desc, UINT initial_layout,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv);
|
||||
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_resource_get_gpu_virtual_address(void* self);
|
||||
/* Xbox views of placed memory; `xbox_desc` is a D3D12XBOX_SHADER/UNORDERED_ACCESS_VIEW_DESC. */
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
/* Drops the shadow record of a destroyed resource. */
|
||||
void bx_xbox_placed_forget(IUnknown* host);
|
||||
|
||||
/* Command-list slots whose structures carry interface pointers, unwrapped before the host call.
|
||||
The Xbox ResourceBarrier also returns the actions it took; 0 is returned. */
|
||||
UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, const D3D12_RESOURCE_BARRIER* barriers);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
|
||||
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
|
||||
const D3D12_BOX* box);
|
||||
}
|
||||
|
||||
#include "xbox_tables_generated.h"
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,24 @@
|
||||
// Generated by shims/d3d12_xs/tools/gen_xbox_tables.py from the Xbox Series D3D12 header (slot
|
||||
// order, names and types only) and the toolchain's <d3d12.h>. Do not edit by hand.
|
||||
#ifndef BETTERXEN_D3D12_XS_XBOX_TABLES_GENERATED_H
|
||||
#define BETTERXEN_D3D12_XS_XBOX_TABLES_GENERATED_H
|
||||
|
||||
#include "xbox_facade.h"
|
||||
|
||||
extern const BxXboxIface bx_xbox_Device;
|
||||
extern const BxXboxIface bx_xbox_Resource;
|
||||
extern const BxXboxIface bx_xbox_Heap;
|
||||
extern const BxXboxIface bx_xbox_Fence;
|
||||
extern const BxXboxIface bx_xbox_DescriptorHeap;
|
||||
extern const BxXboxIface bx_xbox_RootSignature;
|
||||
extern const BxXboxIface bx_xbox_PipelineState;
|
||||
extern const BxXboxIface bx_xbox_CommandAllocator;
|
||||
extern const BxXboxIface bx_xbox_QueryHeap;
|
||||
extern const BxXboxIface bx_xbox_CommandSignature;
|
||||
extern const BxXboxIface bx_xbox_CommandQueue;
|
||||
extern const BxXboxIface bx_xbox_GraphicsCommandList;
|
||||
|
||||
extern const BxXboxIface* const bx_xbox_ifaces[];
|
||||
extern const size_t bx_xbox_iface_count;
|
||||
|
||||
#endif
|
||||
+186
-14
@@ -1,6 +1,10 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <new>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
@@ -10,6 +14,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;
|
||||
@@ -17,9 +45,38 @@ HRESULT unavailable(T* out) {
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
class GameInputDispatcher;
|
||||
|
||||
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};
|
||||
// Live IGameInputDispatcher reference count. >0 means GameInput is in
|
||||
// "manual dispatch" mode; 0 means "automatic dispatch" mode.
|
||||
std::atomic<uint32_t> dispatcher_refs_{0};
|
||||
|
||||
public:
|
||||
// Logs the manual/automatic dispatch mode transition. Purely atomic: it
|
||||
// never takes callback_lock_, so it cannot introduce lock ordering hazards.
|
||||
void note_dispatch_mode(const char* mode, uint32_t count) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "mode=%s live_dispatchers=%u", mode,
|
||||
static_cast<unsigned>(count));
|
||||
bx_log_emit(BX_LOG_INFO, "gameinput", "dispatch_mode", detail);
|
||||
}
|
||||
|
||||
void on_dispatcher_created() {
|
||||
const uint32_t count = dispatcher_refs_.fetch_add(1, std::memory_order_acq_rel) + 1;
|
||||
if (count == 1) note_dispatch_mode("manual", count);
|
||||
}
|
||||
|
||||
void on_dispatcher_released() {
|
||||
const uint32_t count = dispatcher_refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (count == 0) note_dispatch_mode("automatic", count);
|
||||
}
|
||||
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
@@ -54,9 +111,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,17 +146,22 @@ 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 HRESULT WINAPI CreateDispatcher(void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 14, "CreateDispatcher");
|
||||
return unavailable(out);
|
||||
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;
|
||||
}
|
||||
// Slot 14. Defined out of line below because it allocates
|
||||
// GameInputDispatcher, which in turn calls back into this class.
|
||||
virtual HRESULT WINAPI CreateDispatcher(void** out);
|
||||
virtual HRESULT WINAPI CreateAggregateDevice(uint32_t, void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 15, "CreateAggregateDevice");
|
||||
return unavailable(out);
|
||||
@@ -101,11 +186,98 @@ 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);
|
||||
}
|
||||
};
|
||||
|
||||
// IGameInputDispatcher (GameInput v0): IUnknown + Dispatch + OpenWaitHandle.
|
||||
// Holding a reference puts GameInput in manual dispatch mode; releasing the
|
||||
// last one returns it to automatic dispatch mode.
|
||||
class GameInputDispatcher final : public IUnknown {
|
||||
LONG refs = 1;
|
||||
GameInput* owner_ = nullptr;
|
||||
|
||||
public:
|
||||
explicit GameInputDispatcher(GameInput* owner) : owner_(owner) {}
|
||||
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid == IID_IUnknown) {
|
||||
AddRef();
|
||||
*out = this;
|
||||
return S_OK;
|
||||
}
|
||||
// The GameInput v0 IGameInputDispatcher IID is not published in the
|
||||
// public Microsoft Learn / GDK documentation, so it is NOT guessed
|
||||
// here. Only IID_IUnknown is served; every other queried id is logged
|
||||
// (never silently ignored) and answered with E_NOINTERFACE.
|
||||
char guid[40];
|
||||
std::snprintf(guid, sizeof(guid), "%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
|
||||
static_cast<unsigned long>(iid.Data1), iid.Data2, iid.Data3,
|
||||
iid.Data4[0], iid.Data4[1], iid.Data4[2], iid.Data4[3],
|
||||
iid.Data4[4], iid.Data4[5], iid.Data4[6], iid.Data4[7]);
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"IGameInputDispatcher iid=%s unsupported (v0 dispatcher IID not publicly documented)",
|
||||
guid);
|
||||
bx_log_emit(BX_LOG_WARN, "gameinput", "qi_unsupported", detail);
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
|
||||
ULONG WINAPI Release() override {
|
||||
const LONG count = InterlockedDecrement(&refs);
|
||||
if (count == 0) {
|
||||
GameInput* owner = owner_;
|
||||
owner_ = nullptr;
|
||||
if (owner) owner->on_dispatcher_released();
|
||||
delete this;
|
||||
}
|
||||
return static_cast<ULONG>(count);
|
||||
}
|
||||
|
||||
// Slot 3: bool Dispatch(uint64_t quotaInMicroseconds).
|
||||
// This shim has no real background input work, so the dispatch queue is
|
||||
// always empty. The documented "flush at least one item even at quota 0"
|
||||
// shape is honoured trivially: there is nothing to flush, so it returns
|
||||
// false (no work items remain) for every quota, including 0. No real work
|
||||
// is scheduled, and it never busy-waits or sleeps.
|
||||
virtual bool WINAPI Dispatch(uint64_t /*quota_us*/) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Slot 4: HRESULT OpenWaitHandle(HANDLE* waitHandle).
|
||||
// Returns a fresh manual-reset event on every call. The dispatcher owns
|
||||
// nothing after returning it: the caller closes it via CloseHandle.
|
||||
// LIMIT: the handle is created non-signaled and this shim never signals
|
||||
// it, because there is no background input work to make it ready. A
|
||||
// caller that waits on it with INFINITE will block forever; poll with a
|
||||
// timeout, or call Dispatch, instead.
|
||||
virtual HRESULT WINAPI OpenWaitHandle(HANDLE* out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
HANDLE handle = CreateEventW(nullptr, TRUE, FALSE, nullptr);
|
||||
if (!handle) {
|
||||
return HRESULT_FROM_WIN32(GetLastError());
|
||||
}
|
||||
*out = handle;
|
||||
return S_OK;
|
||||
}
|
||||
};
|
||||
|
||||
HRESULT WINAPI GameInput::CreateDispatcher(void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
GameInputDispatcher* dispatcher = new (std::nothrow) GameInputDispatcher(this);
|
||||
if (!dispatcher) return E_OUTOFMEMORY;
|
||||
*out = dispatcher;
|
||||
// The GameInput singleton's own refcount is intentionally unchanged:
|
||||
// the dispatcher only moves the manual-dispatch mode counter.
|
||||
on_dispatcher_created();
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
GameInput singleton;
|
||||
}
|
||||
|
||||
|
||||
+1077
-12
File diff suppressed because it is too large.
Load diff
@@ -1,37 +1,303 @@
|
||||
#include <windows.h>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
namespace {
|
||||
std::atomic<uintptr_t> g_next_token{1};
|
||||
|
||||
static_assert(sizeof(uintptr_t) == 8, "BetterXen Win32 shims target x86-64");
|
||||
|
||||
constexpr uintptr_t kPrefixMask = 0xFFFFFFFF00000000ULL;
|
||||
constexpr uintptr_t kSequenceMask = 0x00000000FFFFFFFFULL;
|
||||
constexpr uintptr_t kStatePrefix = 0x50534D3100000000ULL; // "PSM1"
|
||||
constexpr uintptr_t kConstrainedPrefix = 0x50534D3200000000ULL; // "PSM2"
|
||||
constexpr uintptr_t kEmptySlot = 0;
|
||||
constexpr uintptr_t kTombstoneSlot = ~uintptr_t{0};
|
||||
|
||||
struct SrwLockGuard {
|
||||
SRWLOCK& lock;
|
||||
explicit SrwLockGuard(SRWLOCK& l) : lock(l) { AcquireSRWLockExclusive(&lock); }
|
||||
~SrwLockGuard() { ReleaseSRWLockExclusive(&lock); }
|
||||
SrwLockGuard(const SrwLockGuard&) = delete;
|
||||
SrwLockGuard& operator=(const SrwLockGuard&) = delete;
|
||||
};
|
||||
|
||||
// One accepted registration, stored beside the token that names it.
|
||||
//
|
||||
// The callback and its context are kept together because the PSM contract is a
|
||||
// callback plus a caller context: a caller passes `context` expecting the same
|
||||
// value back as the callback's second argument if that callback ever fires.
|
||||
// Dropping it would make even a future firing unable to deliver faithfully, so
|
||||
// the shim owns both values for exactly as long as the token is live.
|
||||
struct Entry {
|
||||
uintptr_t token; // kEmptySlot == unused, kTombstoneSlot == erased
|
||||
PVOID callback;
|
||||
PVOID context;
|
||||
};
|
||||
|
||||
// Exception-free open-addressed hash table backed by the Win32 process heap so
|
||||
// both PSM DLLs stay on -fno-exceptions and map OOM to ERROR_NOT_ENOUGH_MEMORY.
|
||||
// The record lives in the table slot, so an erase drops the callback with the
|
||||
// token and a reset (DllMain detach) frees them together.
|
||||
struct TokenSet {
|
||||
Entry* slots = nullptr;
|
||||
size_t capacity = 0;
|
||||
size_t count = 0;
|
||||
size_t used = 0; // active entries + tombstones
|
||||
|
||||
static size_t hash(uintptr_t value) {
|
||||
uint64_t x = static_cast<uint64_t>(value);
|
||||
x ^= x >> 30;
|
||||
x *= 0xbf58476d1ce4e5b9ULL;
|
||||
x ^= x >> 27;
|
||||
x *= 0x94d049bb133111ebULL;
|
||||
x ^= x >> 31;
|
||||
return static_cast<size_t>(x);
|
||||
}
|
||||
|
||||
bool rehash(size_t new_capacity) {
|
||||
if (new_capacity == 0 || new_capacity > SIZE_MAX / sizeof(Entry)) {
|
||||
return false;
|
||||
}
|
||||
HANDLE heap = GetProcessHeap();
|
||||
if (!heap) {
|
||||
return false;
|
||||
}
|
||||
auto* fresh = static_cast<Entry*>(
|
||||
HeapAlloc(heap, HEAP_ZERO_MEMORY, new_capacity * sizeof(Entry)));
|
||||
if (!fresh) {
|
||||
return false;
|
||||
}
|
||||
const size_t mask = new_capacity - 1;
|
||||
for (size_t i = 0; i < capacity; ++i) {
|
||||
const Entry entry = slots[i];
|
||||
if (entry.token != kEmptySlot && entry.token != kTombstoneSlot) {
|
||||
size_t idx = hash(entry.token) & mask;
|
||||
while (fresh[idx].token != kEmptySlot) {
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
fresh[idx] = entry;
|
||||
}
|
||||
}
|
||||
if (slots) {
|
||||
HeapFree(heap, 0, slots);
|
||||
}
|
||||
slots = fresh;
|
||||
capacity = new_capacity;
|
||||
used = count;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Inserts the token with its callback/context and returns the stored slot so
|
||||
// the caller can log back exactly what was retained. nullptr means OOM.
|
||||
Entry* insert(uintptr_t token, PVOID callback, PVOID context) {
|
||||
if (capacity == 0 || (used + 1) * 4 >= capacity * 3) {
|
||||
size_t next_capacity = 64;
|
||||
if (capacity != 0) {
|
||||
if (count * 2 >= capacity) {
|
||||
if (capacity > (SIZE_MAX / sizeof(Entry)) / 2) {
|
||||
return nullptr;
|
||||
}
|
||||
next_capacity = capacity * 2;
|
||||
} else {
|
||||
// Compact tombstones in place without growing the table.
|
||||
next_capacity = capacity;
|
||||
}
|
||||
}
|
||||
if (!rehash(next_capacity)) {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
const size_t mask = capacity - 1;
|
||||
size_t idx = hash(token) & mask;
|
||||
size_t first_tombstone = capacity;
|
||||
while (true) {
|
||||
Entry& entry = slots[idx];
|
||||
if (entry.token == token) {
|
||||
entry.callback = callback;
|
||||
entry.context = context;
|
||||
return &entry;
|
||||
}
|
||||
if (entry.token == kEmptySlot) {
|
||||
if (first_tombstone != capacity) {
|
||||
Entry& reused = slots[first_tombstone];
|
||||
reused.token = token;
|
||||
reused.callback = callback;
|
||||
reused.context = context;
|
||||
++count;
|
||||
return &reused;
|
||||
}
|
||||
entry.token = token;
|
||||
entry.callback = callback;
|
||||
entry.context = context;
|
||||
++used;
|
||||
++count;
|
||||
return &entry;
|
||||
}
|
||||
if (entry.token == kTombstoneSlot && first_tombstone == capacity) {
|
||||
first_tombstone = idx;
|
||||
}
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
}
|
||||
|
||||
bool erase(uintptr_t token) {
|
||||
if (capacity == 0 || count == 0 || token == kEmptySlot || token == kTombstoneSlot) {
|
||||
return false;
|
||||
}
|
||||
const size_t mask = capacity - 1;
|
||||
size_t idx = hash(token) & mask;
|
||||
for (size_t probed = 0; probed < capacity; ++probed) {
|
||||
Entry& entry = slots[idx];
|
||||
if (entry.token == kEmptySlot) {
|
||||
return false;
|
||||
}
|
||||
if (entry.token == token) {
|
||||
// Drop the stored callback and context with the token, so a
|
||||
// later firing can never reach a retired registration.
|
||||
entry.token = kTombstoneSlot;
|
||||
entry.callback = nullptr;
|
||||
entry.context = nullptr;
|
||||
--count;
|
||||
return true;
|
||||
}
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
if (slots) {
|
||||
HANDLE heap = GetProcessHeap();
|
||||
if (heap) {
|
||||
HeapFree(heap, 0, slots);
|
||||
}
|
||||
slots = nullptr;
|
||||
}
|
||||
capacity = 0;
|
||||
count = 0;
|
||||
used = 0;
|
||||
}
|
||||
};
|
||||
|
||||
struct Registrations {
|
||||
SRWLOCK lock;
|
||||
TokenSet active;
|
||||
uintptr_t own_prefix;
|
||||
uintptr_t foreign_prefix;
|
||||
uint64_t next_seq;
|
||||
};
|
||||
|
||||
// Each DLL exposes one family. Disjoint tagged token spaces prevent an
|
||||
// unregister call on the wrong DLL from removing another registration and let
|
||||
// logs distinguish foreign-family tokens from retired or invalid ones.
|
||||
Registrations g_state{SRWLOCK_INIT, {}, kStatePrefix, kConstrainedPrefix, 1};
|
||||
Registrations g_constrained{SRWLOCK_INIT, {}, kConstrainedPrefix, kStatePrefix, 1};
|
||||
|
||||
// Accepts a registration and records the callback and context that came with it.
|
||||
//
|
||||
// LIMITATION: the stored callbacks are currently NEVER INVOKED. This shim has
|
||||
// no source of app-state or constrained-change transitions of its own, so no
|
||||
// firing policy is invented here rather than firing the callback spuriously.
|
||||
// ERROR_SUCCESS therefore means "the registration was recorded (bookkeeping
|
||||
// only)", not "you will be notified". The JSONL detail says `callback_unfired`
|
||||
// for the same reason, so `bx-cli trace` states the limitation too.
|
||||
ULONG register_notification(Registrations& registrations, PVOID callback, PVOID context,
|
||||
PVOID* out_reg, const char* event) {
|
||||
if (!out_reg) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
*out_reg = nullptr;
|
||||
if (!callback) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
|
||||
uintptr_t token = 0;
|
||||
PVOID stored_callback = nullptr;
|
||||
PVOID stored_context = nullptr;
|
||||
{
|
||||
const SrwLockGuard guard(registrations.lock);
|
||||
// Never recycle a token that a caller may still retain.
|
||||
if (registrations.next_seq > kSequenceMask) {
|
||||
return ERROR_NOT_ENOUGH_MEMORY;
|
||||
}
|
||||
token = registrations.own_prefix | static_cast<uintptr_t>(registrations.next_seq);
|
||||
const Entry* stored = registrations.active.insert(token, callback, context);
|
||||
if (!stored) {
|
||||
return ERROR_NOT_ENOUGH_MEMORY;
|
||||
}
|
||||
// Log what the table actually retained for this token, not the
|
||||
// arguments, so the record is evidence of the stored state.
|
||||
stored_callback = stored->callback;
|
||||
stored_context = stored->context;
|
||||
++registrations.next_seq;
|
||||
}
|
||||
|
||||
*out_reg = reinterpret_cast<PVOID>(token);
|
||||
char detail[192];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"registered_offline callback_unfired callback=0x%llx context=0x%llx",
|
||||
static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(stored_callback)),
|
||||
static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(stored_context)));
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, detail);
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
void unregister_notification(Registrations& registrations, PVOID reg, const char* event) {
|
||||
const uintptr_t token = reinterpret_cast<uintptr_t>(reg);
|
||||
bool removed = false;
|
||||
{
|
||||
const SrwLockGuard guard(registrations.lock);
|
||||
removed = registrations.active.erase(token);
|
||||
}
|
||||
const char* detail = "unknown_token";
|
||||
if (removed) {
|
||||
detail = "unregistered";
|
||||
} else if ((token & kPrefixMask) == registrations.foreign_prefix &&
|
||||
(token & kSequenceMask) != 0) {
|
||||
detail = "foreign_token";
|
||||
}
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, detail);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
ULONG WINAPI RegisterAppStateChangeNotification(PVOID /*callback*/, PVOID /*context*/, PVOID* out_reg) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "RegisterAppStateChangeNotification", "noop_ok");
|
||||
if (out_reg) {
|
||||
*out_reg = reinterpret_cast<PVOID>(g_next_token.fetch_add(1));
|
||||
BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) {
|
||||
if (reason == DLL_PROCESS_DETACH && reserved == nullptr) {
|
||||
// reset() frees the slot table, so no stored callback or context
|
||||
// outlives process teardown to be invoked against a dying image.
|
||||
{
|
||||
const SrwLockGuard guard(g_state.lock);
|
||||
g_state.active.reset();
|
||||
}
|
||||
{
|
||||
const SrwLockGuard guard(g_constrained.lock);
|
||||
g_constrained.active.reset();
|
||||
}
|
||||
}
|
||||
return ERROR_SUCCESS;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppStateChangeNotification(PVOID /*reg*/) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "UnregisterAppStateChangeNotification", "noop_ok");
|
||||
ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID context, PVOID* out_reg) {
|
||||
return register_notification(g_state, callback, context, out_reg,
|
||||
"RegisterAppStateChangeNotification");
|
||||
}
|
||||
|
||||
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID /*callback*/, PVOID /*context*/, PVOID* out_reg) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "RegisterAppConstrainedChangeNotification", "noop_ok");
|
||||
if (out_reg) {
|
||||
*out_reg = reinterpret_cast<PVOID>(g_next_token.fetch_add(1));
|
||||
}
|
||||
return ERROR_SUCCESS;
|
||||
VOID WINAPI UnregisterAppStateChangeNotification(PVOID reg) {
|
||||
unregister_notification(g_state, reg, "UnregisterAppStateChangeNotification");
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppConstrainedChangeNotification(PVOID /*reg*/) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "UnregisterAppConstrainedChangeNotification", "noop_ok");
|
||||
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID callback, PVOID context, PVOID* out_reg) {
|
||||
return register_notification(g_constrained, callback, context, out_reg,
|
||||
"RegisterAppConstrainedChangeNotification");
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppConstrainedChangeNotification(PVOID reg) {
|
||||
unregister_notification(g_constrained, reg, "UnregisterAppConstrainedChangeNotification");
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -1,4 +1,7 @@
|
||||
bx_add_shim_dll(xcrdapi XCRDAPI XCRDAPI.def
|
||||
xcrdapi.cpp
|
||||
zlib_inflate.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,18 @@ struct Request {
|
||||
void* destination;
|
||||
DWORD size;
|
||||
UINT compression;
|
||||
ID3D12Resource* resource = nullptr;
|
||||
UINT64 resource_offset = 0;
|
||||
DWORD output_size = 0; // compression_zlib: bytes the stream inflates to at `destination`
|
||||
};
|
||||
|
||||
inline constexpr UINT compression_none = 0;
|
||||
inline constexpr UINT compression_lz = 1;
|
||||
inline constexpr UINT compression_bcpack = 2;
|
||||
inline constexpr UINT compression_gdeflate = 3;
|
||||
// RFC 1950 zlib streams (Xbox DSTORAGE_REQUEST_OPTIONS.ZlibDecompress); decoded by zlib_inflate.cpp.
|
||||
inline constexpr UINT compression_zlib = 4;
|
||||
|
||||
struct ErrorRecord {
|
||||
HRESULT first_error;
|
||||
UINT64 failure_count;
|
||||
|
||||
+1400
-29
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,249 @@
|
||||
/* zlib (RFC 1950) / deflate (RFC 1951) decoder; see zlib_inflate.h. */
|
||||
#include "zlib_inflate.h"
|
||||
|
||||
namespace {
|
||||
|
||||
struct Bits {
|
||||
const uint8_t* data;
|
||||
size_t size;
|
||||
size_t pos = 0; // next byte
|
||||
uint32_t buffer = 0;
|
||||
int count = 0; // valid bits in buffer
|
||||
bool overrun = false;
|
||||
|
||||
// RFC 1951 3.1.1: data elements are packed starting with the least significant bit.
|
||||
uint32_t get(int n) {
|
||||
while (count < n) {
|
||||
if (pos >= size) {
|
||||
overrun = true;
|
||||
return 0;
|
||||
}
|
||||
buffer |= static_cast<uint32_t>(data[pos++]) << count;
|
||||
count += 8;
|
||||
}
|
||||
const uint32_t value = buffer & ((n == 32) ? 0xFFFFFFFFu : ((1u << n) - 1u));
|
||||
buffer >>= n;
|
||||
count -= n;
|
||||
return value;
|
||||
}
|
||||
void align_to_byte() {
|
||||
buffer >>= (count & 7);
|
||||
count -= (count & 7);
|
||||
}
|
||||
};
|
||||
|
||||
constexpr int kMaxBits = 15;
|
||||
|
||||
// Canonical Huffman decoding (RFC 1951 3.2.2): counts per code length and symbols sorted by code.
|
||||
struct Huffman {
|
||||
uint16_t counts[kMaxBits + 1] = {};
|
||||
uint16_t symbols[320] = {};
|
||||
|
||||
// Returns false for an over-subscribed set of lengths. An incomplete set is allowed (a
|
||||
// single distance code is legal), and decoding an unassigned code then fails.
|
||||
bool build(const uint8_t* lengths, int n) {
|
||||
for (int i = 0; i <= kMaxBits; ++i) counts[i] = 0;
|
||||
for (int i = 0; i < n; ++i) ++counts[lengths[i]];
|
||||
counts[0] = 0;
|
||||
int left = 1;
|
||||
for (int len = 1; len <= kMaxBits; ++len) {
|
||||
left <<= 1;
|
||||
left -= counts[len];
|
||||
if (left < 0) return false;
|
||||
}
|
||||
uint16_t offsets[kMaxBits + 2] = {};
|
||||
for (int len = 1; len <= kMaxBits; ++len) offsets[len + 1] = offsets[len] + counts[len];
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (lengths[i]) symbols[offsets[lengths[i]]++] = static_cast<uint16_t>(i);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Huffman codes are packed most significant bit first, one bit at a time.
|
||||
int decode(Bits& in) const {
|
||||
int code = 0, first = 0, index = 0;
|
||||
for (int len = 1; len <= kMaxBits; ++len) {
|
||||
code |= static_cast<int>(in.get(1));
|
||||
if (in.overrun) return -1;
|
||||
const int count = counts[len];
|
||||
if (code - first < count) return symbols[index + (code - first)];
|
||||
index += count;
|
||||
first += count;
|
||||
first <<= 1;
|
||||
code <<= 1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
};
|
||||
|
||||
// RFC 1951 3.2.5 length and distance tables.
|
||||
constexpr uint16_t kLengthBase[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
|
||||
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
|
||||
constexpr uint8_t kLengthExtra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
|
||||
constexpr uint16_t kDistBase[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
|
||||
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
|
||||
constexpr uint8_t kDistExtra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
|
||||
|
||||
struct Output {
|
||||
uint8_t* data;
|
||||
size_t size;
|
||||
size_t pos = 0;
|
||||
};
|
||||
|
||||
BxInflateResult codes(Bits& in, Output& out, const Huffman& lit, const Huffman& dist) {
|
||||
for (;;) {
|
||||
const int symbol = lit.decode(in);
|
||||
if (symbol < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
|
||||
if (symbol < 256) {
|
||||
if (out.pos >= out.size) return BxInflateResult::output_mismatch;
|
||||
out.data[out.pos++] = static_cast<uint8_t>(symbol);
|
||||
continue;
|
||||
}
|
||||
if (symbol == 256) return BxInflateResult::ok;
|
||||
const int li = symbol - 257;
|
||||
if (li >= 29) return BxInflateResult::bad_data;
|
||||
const size_t length = kLengthBase[li] + in.get(kLengthExtra[li]);
|
||||
const int ds = dist.decode(in);
|
||||
if (ds < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
|
||||
if (ds >= 30) return BxInflateResult::bad_data;
|
||||
const size_t distance = kDistBase[ds] + in.get(kDistExtra[ds]);
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if (distance > out.pos) return BxInflateResult::bad_data;
|
||||
if (length > out.size - out.pos) return BxInflateResult::output_mismatch;
|
||||
for (size_t i = 0; i < length; ++i, ++out.pos) out.data[out.pos] = out.data[out.pos - distance];
|
||||
}
|
||||
}
|
||||
|
||||
BxInflateResult fixed_block(Bits& in, Output& out) {
|
||||
static Huffman lit, dist;
|
||||
static bool built = [] {
|
||||
uint8_t lengths[288];
|
||||
int i = 0;
|
||||
for (; i < 144; ++i) lengths[i] = 8;
|
||||
for (; i < 256; ++i) lengths[i] = 9;
|
||||
for (; i < 280; ++i) lengths[i] = 7;
|
||||
for (; i < 288; ++i) lengths[i] = 8;
|
||||
lit.build(lengths, 288);
|
||||
uint8_t dl[30];
|
||||
for (int d = 0; d < 30; ++d) dl[d] = 5;
|
||||
dist.build(dl, 30);
|
||||
return true;
|
||||
}();
|
||||
(void)built;
|
||||
return codes(in, out, lit, dist);
|
||||
}
|
||||
|
||||
BxInflateResult dynamic_block(Bits& in, Output& out) {
|
||||
const int hlit = static_cast<int>(in.get(5)) + 257;
|
||||
const int hdist = static_cast<int>(in.get(5)) + 1;
|
||||
const int hclen = static_cast<int>(in.get(4)) + 4;
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if (hlit > 286 || hdist > 30) return BxInflateResult::bad_data;
|
||||
static constexpr uint8_t kOrder[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
|
||||
uint8_t lengths[320] = {};
|
||||
for (int i = 0; i < hclen; ++i) lengths[kOrder[i]] = static_cast<uint8_t>(in.get(3));
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
Huffman code_lengths;
|
||||
if (!code_lengths.build(lengths, 19)) return BxInflateResult::bad_data;
|
||||
int index = 0;
|
||||
while (index < hlit + hdist) {
|
||||
int symbol = code_lengths.decode(in);
|
||||
if (symbol < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
|
||||
if (symbol < 16) {
|
||||
lengths[index++] = static_cast<uint8_t>(symbol);
|
||||
continue;
|
||||
}
|
||||
uint8_t value = 0;
|
||||
int repeat;
|
||||
if (symbol == 16) {
|
||||
if (index == 0) return BxInflateResult::bad_data;
|
||||
value = lengths[index - 1];
|
||||
repeat = 3 + static_cast<int>(in.get(2));
|
||||
} else if (symbol == 17) {
|
||||
repeat = 3 + static_cast<int>(in.get(3));
|
||||
} else {
|
||||
repeat = 11 + static_cast<int>(in.get(7));
|
||||
}
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if (index + repeat > hlit + hdist) return BxInflateResult::bad_data;
|
||||
while (repeat--) lengths[index++] = value;
|
||||
}
|
||||
if (lengths[256] == 0) return BxInflateResult::bad_data; // no end-of-block code
|
||||
Huffman lit, dist;
|
||||
if (!lit.build(lengths, hlit) || !dist.build(lengths + hlit, hdist)) return BxInflateResult::bad_data;
|
||||
return codes(in, out, lit, dist);
|
||||
}
|
||||
|
||||
uint32_t adler32(const uint8_t* data, size_t size) {
|
||||
uint32_t a = 1, b = 0;
|
||||
while (size) {
|
||||
size_t chunk = size < 5552 ? size : 5552; // largest n with no 32-bit overflow before the modulo
|
||||
size -= chunk;
|
||||
while (chunk--) {
|
||||
a += *data++;
|
||||
b += a;
|
||||
}
|
||||
a %= 65521u;
|
||||
b %= 65521u;
|
||||
}
|
||||
return (b << 16) | a;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
|
||||
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
|
||||
if (!input || input_size < 6 || (!output && output_size)) return BxInflateResult::bad_header;
|
||||
const uint8_t cmf = input[0], flg = input[1];
|
||||
if ((cmf & 0x0F) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) {
|
||||
return BxInflateResult::bad_header;
|
||||
}
|
||||
Bits in{input + 2, input_size - 2};
|
||||
Output out{output, output_size};
|
||||
for (;;) {
|
||||
const uint32_t final_block = in.get(1);
|
||||
const uint32_t type = in.get(2);
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
BxInflateResult r;
|
||||
if (type == 0) {
|
||||
in.align_to_byte();
|
||||
const uint32_t len = in.get(16), nlen = in.get(16);
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if ((len ^ 0xFFFFu) != nlen) return BxInflateResult::bad_data;
|
||||
// After aligning, the bit buffer is empty: copy straight from the byte stream.
|
||||
if (len > in.size - in.pos) return BxInflateResult::truncated;
|
||||
if (len > out.size - out.pos) return BxInflateResult::output_mismatch;
|
||||
for (uint32_t i = 0; i < len; ++i) out.data[out.pos++] = in.data[in.pos++];
|
||||
r = BxInflateResult::ok;
|
||||
} else if (type == 1) {
|
||||
r = fixed_block(in, out);
|
||||
} else if (type == 2) {
|
||||
r = dynamic_block(in, out);
|
||||
} else {
|
||||
return BxInflateResult::bad_data;
|
||||
}
|
||||
if (r != BxInflateResult::ok) return r;
|
||||
if (final_block) break;
|
||||
}
|
||||
if (out.pos != out.size) return BxInflateResult::output_mismatch;
|
||||
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
|
||||
in.align_to_byte();
|
||||
const size_t trailer = in.pos - static_cast<size_t>(in.count / 8);
|
||||
if (input_size - 2 - trailer < 4) return BxInflateResult::truncated;
|
||||
const uint8_t* t = in.data + trailer;
|
||||
const uint32_t expected = (static_cast<uint32_t>(t[0]) << 24) | (static_cast<uint32_t>(t[1]) << 16) |
|
||||
(static_cast<uint32_t>(t[2]) << 8) | t[3];
|
||||
return adler32(output, output_size) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
|
||||
}
|
||||
|
||||
const char* bx_inflate_result_name(BxInflateResult result) {
|
||||
switch (result) {
|
||||
case BxInflateResult::ok: return "ok";
|
||||
case BxInflateResult::bad_header: return "bad_header";
|
||||
case BxInflateResult::bad_data: return "bad_data";
|
||||
case BxInflateResult::truncated: return "truncated";
|
||||
case BxInflateResult::output_mismatch: return "output_mismatch";
|
||||
case BxInflateResult::bad_checksum: return "bad_checksum";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
* A zlib stream decoder written from the public specifications: IETF RFC 1950 (the zlib
|
||||
* wrapper and its Adler-32 check) and RFC 1951 (deflate: stored, fixed-Huffman and
|
||||
* dynamic-Huffman blocks, 32 KiB window). No third-party code.
|
||||
*
|
||||
* Used for DirectStorage requests whose DSTORAGE_REQUEST_OPTIONS.ZlibDecompress bit is set
|
||||
* (authorized GDK documentation: RFC 1950 streams, full 32 KiB window, compressed size smaller
|
||||
* than the decompressed size).
|
||||
*/
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
enum class BxInflateResult {
|
||||
ok,
|
||||
bad_header, // not an RFC 1950 header, or a preset dictionary is required
|
||||
bad_data, // malformed deflate data
|
||||
truncated, // the input ended before the final block
|
||||
output_mismatch, // the stream does not produce exactly `output_size` bytes
|
||||
bad_checksum, // Adler-32 of the output does not match the stream trailer
|
||||
};
|
||||
|
||||
/* Decodes `input` into exactly `output_size` bytes at `output`. */
|
||||
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size);
|
||||
|
||||
const char* bx_inflate_result_name(BxInflateResult result);
|
||||
@@ -1,4 +1,4 @@
|
||||
bx_add_shim_dll(xg_xs xg_xs xg_xs.def
|
||||
xg_xs.cpp
|
||||
xg_xbox.cpp
|
||||
)
|
||||
target_link_libraries(xg_xs PRIVATE bx_runtime_veh kernel32)
|
||||
@@ -1,195 +0,0 @@
|
||||
#ifndef BETTERXEN_XG_TEXTURE_H
|
||||
#define BETTERXEN_XG_TEXTURE_H
|
||||
|
||||
/*
|
||||
* BetterXen M1 linear texture-address contract for xg_xs.dll.
|
||||
*
|
||||
* Field meanings follow the public D3D12 resource and footprint documents
|
||||
* (D3D12_RESOURCE_DIMENSION, D3D12_SUBRESOURCE_FOOTPRINT, and
|
||||
* D3D12_TEXTURE_DATA_PITCH_ALIGNMENT / D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT).
|
||||
* Block-compressed footprint width and height are texels rounded up to the
|
||||
* 4x4 block, the same rounding D3D12 uses for a copyable footprint.
|
||||
* Format numbers are the public DXGI_FORMAT values. This is not the Xbox
|
||||
* GDK XG interface and it is not an Xbox hardware result.
|
||||
*/
|
||||
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
|
||||
#include <windows.h>
|
||||
#include <stdint.h>
|
||||
#include <dxgiformat.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Public D3D12_RESOURCE_DIMENSION values used by this shim. */
|
||||
#define BX_XG_DIMENSION_BUFFER 1u
|
||||
#define BX_XG_DIMENSION_TEXTURE1D 2u
|
||||
#define BX_XG_DIMENSION_TEXTURE2D 3u
|
||||
#define BX_XG_DIMENSION_TEXTURE3D 4u
|
||||
|
||||
/* Public D3D12 texture copy alignments, in bytes. */
|
||||
#define BX_XG_LINEAR_PITCH_ALIGNMENT 256u
|
||||
#define BX_XG_LINEAR_PLACEMENT_ALIGNMENT 512u
|
||||
|
||||
/* Public D3D12 texture size limits used as the acceptance cap. */
|
||||
#define BX_XG_MAX_TEXTURE_EDGE 16384u
|
||||
#define BX_XG_MAX_ARRAY_SLICES 2048u
|
||||
|
||||
/*
|
||||
* Layout selectors for this shim. LINEAR is computed exactly.
|
||||
* SW_64KB_S / D / R are named RDNA 2 tile modes reserved for M3. They are
|
||||
* accepted by XGCreateTextureComputer and every layout or copy call on them
|
||||
* returns E_NOTIMPL without writing an address.
|
||||
* XGSuggestSwizzleMode never returns a tile mode. It returns LINEAR or NONE.
|
||||
*/
|
||||
typedef enum bx_xg_layout_mode {
|
||||
BX_XG_LAYOUT_LINEAR = 0,
|
||||
BX_XG_LAYOUT_SW_64KB_S = 1,
|
||||
BX_XG_LAYOUT_SW_64KB_D = 2,
|
||||
BX_XG_LAYOUT_SW_64KB_R = 3,
|
||||
BX_XG_LAYOUT_NONE = 0xFFFFFFFFu
|
||||
} bx_xg_layout_mode;
|
||||
|
||||
typedef struct bx_xg_sample_desc {
|
||||
uint32_t count;
|
||||
uint32_t quality;
|
||||
} bx_xg_sample_desc;
|
||||
|
||||
typedef struct bx_xg_resource_desc {
|
||||
uint32_t dimension;
|
||||
uint32_t alignment; /* 0 or BX_XG_LINEAR_PLACEMENT_ALIGNMENT */
|
||||
uint64_t width; /* texels */
|
||||
uint32_t height; /* texels */
|
||||
uint16_t depth_or_array_size;
|
||||
uint16_t mip_levels; /* 0 selects the full chain, down to 1x1 */
|
||||
uint32_t format; /* DXGI_FORMAT */
|
||||
bx_xg_sample_desc sample_desc;
|
||||
uint32_t layout; /* bx_xg_layout_mode */
|
||||
uint32_t flags; /* must be 0 */
|
||||
} bx_xg_resource_desc;
|
||||
|
||||
typedef struct bx_xg_subresource_footprint {
|
||||
uint32_t format;
|
||||
uint32_t width; /* texels, rounded up to the format block width */
|
||||
uint32_t height; /* texels, rounded up to the format block height */
|
||||
uint32_t depth;
|
||||
uint32_t row_pitch; /* bytes, multiple of BX_XG_LINEAR_PITCH_ALIGNMENT */
|
||||
} bx_xg_subresource_footprint;
|
||||
|
||||
typedef struct bx_xg_placed_footprint {
|
||||
uint64_t offset;
|
||||
bx_xg_subresource_footprint footprint;
|
||||
/*
|
||||
* Absolute byte just past this subresource's last payload byte:
|
||||
* offset + (row_count - 1) * row_pitch + row_bytes.
|
||||
* That is the D3D12 GetCopyableFootprints end. It does not include the
|
||||
* last row's pitch padding or the 512-byte tail. The copy span of a
|
||||
* GetResourceLayout call is layouts[last].copy_end - base_offset.
|
||||
*/
|
||||
uint64_t copy_end;
|
||||
} bx_xg_placed_footprint;
|
||||
|
||||
/* {B7E4C8A1-6F2D-4C55-8A19-3D0E5F7B91C4} BetterXen IXGTextureAddressComputer */
|
||||
static const GUID BX_IID_IXGTextureAddressComputer = {
|
||||
0xB7E4C8A1u, 0x6F2Du, 0x4C55u, {0x8Au, 0x19u, 0x3Du, 0x0Eu, 0x5Fu, 0x7Bu, 0x91u, 0xC4u}};
|
||||
|
||||
/* Public COM IUnknown IID. */
|
||||
static const GUID BX_IID_IUnknown = {
|
||||
0x00000000u, 0x0000u, 0x0000u, {0xC0u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x46u}};
|
||||
|
||||
/*
|
||||
* GetResourceLayout places every subresource at its absolute offset from
|
||||
* base_offset, including subresources before first_subresource. total_bytes
|
||||
* is the BetterXen allocation span: the 512-aligned end of the last requested
|
||||
* subresource, measured from base_offset, so a partial range still covers the
|
||||
* earlier subresources and a 1x1 RGBA8 texture reports 512. copy_end on each
|
||||
* footprint is the separate D3D12-style copy span end described above.
|
||||
*/
|
||||
typedef struct bx_xg_texture_computer bx_xg_texture_computer;
|
||||
|
||||
typedef struct bx_xg_texture_computer_vtbl {
|
||||
HRESULT(WINAPI* QueryInterface)(bx_xg_texture_computer* self, const GUID* riid, void** object);
|
||||
ULONG(WINAPI* AddRef)(bx_xg_texture_computer* self);
|
||||
ULONG(WINAPI* Release)(bx_xg_texture_computer* self);
|
||||
HRESULT(WINAPI* GetResourceLayout)(
|
||||
bx_xg_texture_computer* self,
|
||||
uint32_t first_subresource,
|
||||
uint32_t subresource_count,
|
||||
uint64_t base_offset,
|
||||
bx_xg_placed_footprint* layouts,
|
||||
uint32_t* row_counts,
|
||||
uint64_t* row_sizes_in_bytes,
|
||||
uint64_t* total_bytes);
|
||||
HRESULT(WINAPI* GetResourceSizeBytes)(bx_xg_texture_computer* self, uint64_t* size_bytes);
|
||||
HRESULT(WINAPI* GetResourceBaseAlignmentBytes)(bx_xg_texture_computer* self, uint64_t* alignment_bytes);
|
||||
HRESULT(WINAPI* GetMipLevelOffsetBytes)(
|
||||
bx_xg_texture_computer* self,
|
||||
uint32_t array_slice,
|
||||
uint32_t mip_level,
|
||||
uint64_t* offset_bytes);
|
||||
HRESULT(WINAPI* GetTexelElementOffsetBytes)(
|
||||
bx_xg_texture_computer* self,
|
||||
uint32_t array_slice,
|
||||
uint32_t mip_level,
|
||||
uint32_t x,
|
||||
uint32_t y,
|
||||
uint32_t z,
|
||||
uint64_t* offset_bytes);
|
||||
HRESULT(WINAPI* CopyIntoSubresource)(
|
||||
bx_xg_texture_computer* self,
|
||||
void* destination,
|
||||
uint64_t destination_size,
|
||||
uint32_t subresource,
|
||||
const void* source,
|
||||
uint64_t source_size,
|
||||
uint32_t source_row_pitch,
|
||||
uint32_t source_depth_pitch);
|
||||
HRESULT(WINAPI* CopyFromSubresource)(
|
||||
bx_xg_texture_computer* self,
|
||||
void* destination,
|
||||
uint64_t destination_size,
|
||||
uint32_t destination_row_pitch,
|
||||
uint32_t destination_depth_pitch,
|
||||
const void* source,
|
||||
uint64_t source_size,
|
||||
uint32_t subresource);
|
||||
} bx_xg_texture_computer_vtbl;
|
||||
|
||||
struct bx_xg_texture_computer {
|
||||
const bx_xg_texture_computer_vtbl* lpVtbl;
|
||||
};
|
||||
|
||||
/*
|
||||
* On success, *computer is an IXGTextureAddressComputer with a reference
|
||||
* count of 1. On failure, *computer is NULL when computer itself is non-NULL.
|
||||
* Subresource index is mip_level + array_slice * mip_levels.
|
||||
* A row pitch of 0 on a copy selects the tight logical row size.
|
||||
*/
|
||||
HRESULT WINAPI XGCreateTextureComputer(const bx_xg_resource_desc* desc, void** computer);
|
||||
|
||||
/*
|
||||
* Returns BX_XG_LAYOUT_LINEAR when this shim can lay the texture out, and
|
||||
* BX_XG_LAYOUT_NONE otherwise. The same arguments always return the same mode.
|
||||
*/
|
||||
uint32_t WINAPI XGSuggestSwizzleMode(
|
||||
uint32_t resource_type,
|
||||
uint32_t format,
|
||||
uint32_t width,
|
||||
uint32_t height,
|
||||
uint32_t depth,
|
||||
uint32_t mip_levels,
|
||||
uint32_t sample_count,
|
||||
uint32_t flags);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* BETTERXEN_XG_TEXTURE_H */
|
||||
@@ -0,0 +1,683 @@
|
||||
/*
|
||||
* The XG texture-address contract as titles call it (authorized GDK documentation, xg_xs.h):
|
||||
* XGCreateTextureComputer(const XG_RESOURCE_DESC*, XGTextureAddressComputer**) and
|
||||
* XGSuggestSwizzleMode(const XG_RESOURCE_DESC*, flags, XG_TEXTURE_LAYOUT*). Only the structure
|
||||
* layouts, enum values and the method order are taken from there; no header text is reproduced.
|
||||
*
|
||||
* The layout this computer reports is BetterXen's, not the console's: every texture is laid out
|
||||
* linearly (swizzle mode LINEAR), mip-major (each mip holds all of its array or depth slices),
|
||||
* rows aligned to 256 bytes, mips to 512 bytes, the resource to 64 KB. Depth-stencil formats
|
||||
* get a separate depth plane and stencil plane. Every method uses the same layout, so sizes,
|
||||
* offsets, texel addresses and copies agree with each other. Data a title stores pre-tiled for
|
||||
* the console's swizzle modes is not detiled by this layer.
|
||||
*
|
||||
* The one exception is an explicit request for XG_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_S on a 2D
|
||||
* texture that fits in one 64 KiB tile (one mip, one slice, 4-, 8- or 16-byte elements): that
|
||||
* gets the RDNA 2 SW_64KB_S addresses (see Sw64kbS). Any other explicit swizzle mode, and
|
||||
* SW_64KB_S on a texture larger than one tile, is laid out linearly, reported as LINEAR
|
||||
* (SwizzleMode 0) and logged once per mode: titles do not check XGCreateTextureComputer for a
|
||||
* mode they request, so refusing it crashed one.
|
||||
*/
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <dxgiformat.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// --- XG types (layouts from xg_xs.h) -------------------------------------------------------
|
||||
enum : uint32_t {
|
||||
kDimBuffer = 1,
|
||||
kDimTexture1D = 2,
|
||||
kDimTexture2D = 3,
|
||||
kDimTexture3D = 4,
|
||||
};
|
||||
// XG_TEXTURE_LAYOUT: 0 default (XG chooses), 1 row major, 2 64 KB with an undefined swizzle, or
|
||||
// 0x100 | XG_SWIZZLE_MODE to request one swizzle mode.
|
||||
constexpr uint32_t kLayoutSwizzleFlag = 0x100;
|
||||
constexpr uint32_t kLayoutSwizzleLinear = 0x100; // XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR
|
||||
constexpr uint32_t kSwizzleModeLinear = 0;
|
||||
constexpr uint32_t kSwizzleMode64KbS = 9; // XG_SWIZZLE_MODE_64KB_S
|
||||
enum : uint32_t { kPlaneUnused = 0, kPlaneDefault = 1, kPlaneDepth = 7, kPlaneStencil = 8 };
|
||||
|
||||
// --- RDNA 2 SW_64KB_S (clean-room, ported from the earlier xg_xs.cpp) ---------------------
|
||||
// Within one 64 KiB tile, the byte offset of element (x, y) is pdep(x, x_mask) | pdep(y, y_mask),
|
||||
// x and y in elements (texels, or 4x4 blocks for BC). The masks come from the public AddrLib RB+
|
||||
// pattern tables (GFX10_SW_64K_S_RBPLUS_PATINFO, MIT); at 4 bytes per element the x mask equals
|
||||
// the public D3D12 standard-swizzle xBytesMask 0xAA8F without its two intra-texel bits, and the y
|
||||
// mask equals D3D12's 0x5570. Each row is a bijection over its tile. How tiles are ordered across a
|
||||
// larger surface is not established from public sources, so only surfaces that fit in one tile
|
||||
// are addressed; larger ones fall back to the logged linear layout.
|
||||
struct Sw64kbS {
|
||||
uint32_t bytes;
|
||||
uint32_t x_mask;
|
||||
uint32_t y_mask;
|
||||
uint32_t tile_x; // elements per tile row
|
||||
uint32_t tile_y; // element rows per tile
|
||||
};
|
||||
bool sw64kb_s_params(uint32_t bytes, Sw64kbS* out) {
|
||||
switch (bytes) {
|
||||
case 4: *out = {4, 0xAA8Cu, 0x5570u, 128, 128}; return true;
|
||||
case 8: *out = {8, 0xAAC8u, 0x5530u, 128, 64}; return true;
|
||||
case 16: *out = {16, 0xAAC0u, 0x5530u, 64, 64}; return true;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
uint32_t pdep(uint32_t value, uint32_t mask) {
|
||||
uint32_t out = 0;
|
||||
for (uint32_t bit = 1; mask; bit <<= 1) {
|
||||
const uint32_t lowest = mask & (0u - mask);
|
||||
if (value & bit) out |= lowest;
|
||||
mask ^= lowest;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
uint32_t pext(uint32_t value, uint32_t mask) {
|
||||
uint32_t out = 0;
|
||||
for (uint32_t bit = 1; mask; bit <<= 1) {
|
||||
const uint32_t lowest = mask & (0u - mask);
|
||||
if (value & lowest) out |= bit;
|
||||
mask ^= lowest;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
constexpr uint64_t kTileBytes = 64 * 1024;
|
||||
|
||||
struct XgSampleDesc {
|
||||
UINT Count;
|
||||
UINT Quality;
|
||||
};
|
||||
|
||||
struct XgResourceDesc {
|
||||
uint32_t Dimension;
|
||||
UINT64 Alignment;
|
||||
UINT64 Width;
|
||||
UINT Height;
|
||||
UINT16 DepthOrArraySize;
|
||||
UINT16 MipLevels;
|
||||
uint32_t Format;
|
||||
XgSampleDesc SampleDesc;
|
||||
uint32_t Layout;
|
||||
uint32_t MiscFlags;
|
||||
};
|
||||
|
||||
struct XgMipLevelLayout {
|
||||
UINT64 SizeBytes;
|
||||
UINT64 OffsetBytes;
|
||||
UINT64 Slice2DSizeBytes;
|
||||
UINT32 PitchPixels;
|
||||
UINT32 PitchBytes;
|
||||
UINT32 AlignmentBytes;
|
||||
UINT32 PaddedWidthElements;
|
||||
UINT32 PaddedHeightElements;
|
||||
UINT32 PaddedDepthOrArraySize;
|
||||
UINT32 WidthElements;
|
||||
UINT32 HeightElements;
|
||||
UINT32 WidthPixels;
|
||||
UINT32 HeightPixels;
|
||||
UINT32 DepthOrArraySize;
|
||||
UINT32 SampleCount;
|
||||
uint32_t SwizzleMode;
|
||||
UINT64 BankRotationAddressBitMask;
|
||||
UINT64 BankRotationBytesPerSlice;
|
||||
UINT32 SliceDepthElements;
|
||||
UINT32 IsMipTail;
|
||||
UINT32 MipTailOffsetElementsX : 11;
|
||||
UINT32 MipTailOffsetElementsY : 11;
|
||||
UINT32 MipTailOffsetElementsZ : 10;
|
||||
};
|
||||
|
||||
constexpr int kMaxMips = 15;
|
||||
constexpr int kMaxPlanes = 4;
|
||||
|
||||
struct XgPlaneLayout {
|
||||
uint32_t Usage;
|
||||
UINT64 SizeBytes;
|
||||
UINT64 SliceSizeBytes;
|
||||
UINT64 BaseOffsetBytes;
|
||||
UINT64 BaseAlignmentBytes;
|
||||
UINT32 BytesPerElement;
|
||||
UINT32 StandardMipCount;
|
||||
UINT32 MipTailMipCount;
|
||||
XgMipLevelLayout MipLayout[kMaxMips];
|
||||
};
|
||||
|
||||
struct XgResourceLayout {
|
||||
UINT64 SizeBytes;
|
||||
UINT64 BaseAlignmentBytes;
|
||||
UINT32 MipLevels;
|
||||
UINT32 Planes;
|
||||
XgPlaneLayout Plane[kMaxPlanes];
|
||||
uint32_t Dimension;
|
||||
};
|
||||
|
||||
// Pinned against the layouts derived from the GDK header (natural x64 alignment).
|
||||
static_assert(sizeof(XgResourceDesc) == 56, "XG_RESOURCE_DESC size");
|
||||
static_assert(offsetof(XgResourceDesc, Alignment) == 8 && offsetof(XgResourceDesc, Width) == 16, "XG_RESOURCE_DESC");
|
||||
static_assert(sizeof(XgMipLevelLayout) == 112, "XG_MIPLEVEL_LAYOUT size");
|
||||
static_assert(offsetof(XgPlaneLayout, MipLayout) == 56 && sizeof(XgPlaneLayout) == 1736, "XG_PLANE_LAYOUT size");
|
||||
static_assert(offsetof(XgResourceLayout, Plane) == 24 && sizeof(XgResourceLayout) == 6976, "XG_RESOURCE_LAYOUT size");
|
||||
|
||||
struct XgPackedMipDesc {
|
||||
UINT8 NumStandardMips;
|
||||
UINT8 NumPackedMips;
|
||||
UINT32 NumTilesForPackedMips;
|
||||
UINT32 StartTileIndexInOverallResource;
|
||||
};
|
||||
struct XgTileShape {
|
||||
UINT32 WidthInTexels;
|
||||
UINT32 HeightInTexels;
|
||||
UINT32 DepthInTexels;
|
||||
};
|
||||
struct XgSubresourceTiling {
|
||||
UINT32 WidthInTiles;
|
||||
UINT16 HeightInTiles;
|
||||
UINT16 DepthInTiles;
|
||||
UINT32 StartTileIndexInOverallResource;
|
||||
};
|
||||
|
||||
// --- Formats -------------------------------------------------------------------------------
|
||||
struct FormatInfo {
|
||||
uint32_t block; // texels per element edge: 1, or 4 for block compression
|
||||
uint32_t bytes; // bytes per element
|
||||
uint32_t stencil; // 1 when the format carries a stencil plane
|
||||
};
|
||||
|
||||
bool format_info(uint32_t f, FormatInfo* out) {
|
||||
auto set = [&](uint32_t block, uint32_t bytes, uint32_t stencil = 0) {
|
||||
*out = {block, bytes, stencil};
|
||||
return true;
|
||||
};
|
||||
if (f >= DXGI_FORMAT_R32G32B32A32_TYPELESS && f <= DXGI_FORMAT_R32G32B32A32_SINT) return set(1, 16);
|
||||
if (f >= DXGI_FORMAT_R32G32B32_TYPELESS && f <= DXGI_FORMAT_R32G32B32_SINT) return set(1, 12);
|
||||
if (f >= DXGI_FORMAT_R16G16B16A16_TYPELESS && f <= DXGI_FORMAT_R32G32_SINT) return set(1, 8);
|
||||
if (f >= DXGI_FORMAT_R32G8X24_TYPELESS && f <= DXGI_FORMAT_X32_TYPELESS_G8X24_UINT) return set(1, 4, 1);
|
||||
if (f >= DXGI_FORMAT_R10G10B10A2_TYPELESS && f <= DXGI_FORMAT_R32_SINT) return set(1, 4);
|
||||
if (f >= DXGI_FORMAT_R24G8_TYPELESS && f <= DXGI_FORMAT_X24_TYPELESS_G8_UINT) return set(1, 4, 1);
|
||||
if (f >= DXGI_FORMAT_R8G8_TYPELESS && f <= DXGI_FORMAT_R16_SINT) return set(1, 2);
|
||||
if (f >= DXGI_FORMAT_R8_TYPELESS && f <= DXGI_FORMAT_A8_UNORM) return set(1, 1);
|
||||
if (f == DXGI_FORMAT_R9G9B9E5_SHAREDEXP || f == DXGI_FORMAT_R8G8_B8G8_UNORM || f == DXGI_FORMAT_G8R8_G8B8_UNORM) return set(1, 4);
|
||||
if ((f >= DXGI_FORMAT_BC1_TYPELESS && f <= DXGI_FORMAT_BC1_UNORM_SRGB) ||
|
||||
(f >= DXGI_FORMAT_BC4_TYPELESS && f <= DXGI_FORMAT_BC4_SNORM)) {
|
||||
return set(4, 8);
|
||||
}
|
||||
if ((f >= DXGI_FORMAT_BC2_TYPELESS && f <= DXGI_FORMAT_BC3_UNORM_SRGB) ||
|
||||
(f >= DXGI_FORMAT_BC5_TYPELESS && f <= DXGI_FORMAT_BC5_SNORM) ||
|
||||
(f >= DXGI_FORMAT_BC6H_TYPELESS && f <= DXGI_FORMAT_BC7_UNORM_SRGB)) {
|
||||
return set(4, 16);
|
||||
}
|
||||
if (f >= DXGI_FORMAT_B5G6R5_UNORM && f <= DXGI_FORMAT_B5G5R5A1_UNORM) return set(1, 2);
|
||||
if (f >= DXGI_FORMAT_B8G8R8A8_UNORM && f <= DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) return set(1, 4);
|
||||
if (f == DXGI_FORMAT_B4G4R4A4_UNORM) return set(1, 2);
|
||||
return false;
|
||||
}
|
||||
|
||||
uint64_t align_up(uint64_t v, uint64_t a) { return (v + a - 1) / a * a; }
|
||||
uint32_t mip_extent(uint64_t base, uint32_t mip) {
|
||||
const uint64_t v = base >> mip;
|
||||
return v ? static_cast<uint32_t>(v) : 1u;
|
||||
}
|
||||
|
||||
constexpr uint64_t kRowAlign = 256;
|
||||
constexpr uint64_t kMipAlign = 512;
|
||||
constexpr uint64_t kResourceAlign = 64 * 1024;
|
||||
|
||||
void log_rejected(const XgResourceDesc* d, const char* why) {
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "%s: dim=%u width=%llu height=%u depth_or_array=%u mips=%u format=%u samples=%u layout=0x%x",
|
||||
why, d->Dimension, static_cast<unsigned long long>(d->Width), d->Height, d->DepthOrArraySize,
|
||||
d->MipLevels, d->Format, d->SampleDesc.Count, d->Layout);
|
||||
bx_log_emit(BX_LOG_WARN, "xg_xs", "texture_computer_rejected", detail);
|
||||
}
|
||||
|
||||
// A requested swizzle mode this layer does not implement: laid out (and reported) linearly; the
|
||||
// first request for each mode is logged, with the description.
|
||||
void log_linear_instead(const XgResourceDesc* d) {
|
||||
static std::atomic<uint32_t> seen[32];
|
||||
const uint32_t mode = d->Layout & 0x1F;
|
||||
if (seen[mode].exchange(1)) return;
|
||||
log_rejected(d, "requested swizzle mode is not implemented; laid out and reported as LINEAR");
|
||||
}
|
||||
|
||||
// --- The computer ---------------------------------------------------------------------------
|
||||
class XGTextureAddressComputer {
|
||||
public:
|
||||
virtual ULONG AddRef() = 0;
|
||||
virtual ULONG Release() = 0;
|
||||
virtual HRESULT GetResourceLayout(XgResourceLayout* layout) = 0;
|
||||
virtual UINT64 GetResourceSizeBytes() = 0;
|
||||
virtual UINT64 GetResourceBaseAlignmentBytes() = 0;
|
||||
virtual UINT64 GetMipLevelOffsetBytes(UINT32 plane, UINT32 mip) = 0;
|
||||
virtual UINT64 GetTexelElementOffsetBytes(UINT32 plane, UINT32 mip, UINT64 x, UINT32 y, UINT32 z_or_slice,
|
||||
UINT32 sample, UINT32* bit_position) = 0;
|
||||
virtual HRESULT GetTexelCoordinate(UINT64 offset, UINT32* plane, UINT32* mip, UINT64* x, UINT32* y,
|
||||
UINT32* z_or_slice, UINT32* sample) = 0;
|
||||
virtual HRESULT CopyIntoSubresource(void* base, UINT32 plane, UINT32 subresource, const void* linear,
|
||||
UINT32 row_pitch, UINT32 slice_pitch) = 0;
|
||||
virtual HRESULT CopyFromSubresource(void* linear, UINT32 plane, UINT32 subresource, UINT32 sample,
|
||||
const void* base, UINT32 row_pitch, UINT32 slice_pitch) = 0;
|
||||
virtual HRESULT GetResourceTiling(UINT32* total_tiles, XgPackedMipDesc* packed, XgTileShape* shape,
|
||||
UINT32* subresource_count, UINT32 first_subresource,
|
||||
XgSubresourceTiling* tilings) = 0;
|
||||
virtual HRESULT GetTextureViewDescriptor(UINT32 plane, void* descriptor) = 0;
|
||||
virtual bool IsTiledResource() = 0;
|
||||
virtual HRESULT GetSwizzlePatternInfo(UINT32 plane, void* info) = 0;
|
||||
};
|
||||
|
||||
class LayoutComputer final : public XGTextureAddressComputer {
|
||||
public:
|
||||
static HRESULT create(const XgResourceDesc& desc, XGTextureAddressComputer** out);
|
||||
|
||||
ULONG AddRef() override { return ++refs_; }
|
||||
ULONG Release() override {
|
||||
const ULONG left = --refs_;
|
||||
if (!left) delete this;
|
||||
return left;
|
||||
}
|
||||
HRESULT GetResourceLayout(XgResourceLayout* layout) override {
|
||||
if (!layout) return E_POINTER;
|
||||
*layout = layout_;
|
||||
return S_OK;
|
||||
}
|
||||
UINT64 GetResourceSizeBytes() override { return layout_.SizeBytes; }
|
||||
UINT64 GetResourceBaseAlignmentBytes() override { return layout_.BaseAlignmentBytes; }
|
||||
UINT64 GetMipLevelOffsetBytes(UINT32 plane, UINT32 mip) override {
|
||||
if (plane >= layout_.Planes || mip >= layout_.MipLevels) return 0;
|
||||
return layout_.Plane[plane].MipLayout[mip].OffsetBytes;
|
||||
}
|
||||
UINT64 GetTexelElementOffsetBytes(UINT32 plane, UINT32 mip, UINT64 x, UINT32 y, UINT32 z, UINT32 sample,
|
||||
UINT32* bit_position) override {
|
||||
if (bit_position) *bit_position = 0;
|
||||
if (plane >= layout_.Planes || mip >= layout_.MipLevels) return 0;
|
||||
const XgPlaneLayout& p = layout_.Plane[plane];
|
||||
const XgMipLevelLayout& m = p.MipLayout[mip];
|
||||
const uint64_t ex = x / block_, ey = y / block_;
|
||||
if (swizzled_) {
|
||||
if (ex >= sw_.tile_x || ey >= sw_.tile_y) return 0;
|
||||
return m.OffsetBytes + element_offset(static_cast<uint32_t>(ex), static_cast<uint32_t>(ey));
|
||||
}
|
||||
return m.OffsetBytes + z * m.Slice2DSizeBytes + ey * m.PitchBytes +
|
||||
(ex * m.SampleCount + sample) * p.BytesPerElement;
|
||||
}
|
||||
HRESULT GetTexelCoordinate(UINT64 offset, UINT32* plane, UINT32* mip, UINT64* x, UINT32* y, UINT32* z,
|
||||
UINT32* sample) override {
|
||||
for (UINT32 pi = 0; pi < layout_.Planes; ++pi) {
|
||||
const XgPlaneLayout& p = layout_.Plane[pi];
|
||||
for (UINT32 mi = 0; mi < layout_.MipLevels; ++mi) {
|
||||
const XgMipLevelLayout& m = p.MipLayout[mi];
|
||||
if (offset < m.OffsetBytes || offset >= m.OffsetBytes + m.SizeBytes) continue;
|
||||
const uint64_t rel = offset - m.OffsetBytes;
|
||||
if (swizzled_) {
|
||||
const uint32_t in_tile = static_cast<uint32_t>(rel);
|
||||
if (plane) *plane = pi;
|
||||
if (mip) *mip = mi;
|
||||
if (z) *z = 0;
|
||||
if (y) *y = pext(in_tile, sw_.y_mask) * block_;
|
||||
if (x) *x = static_cast<UINT64>(pext(in_tile, sw_.x_mask)) * block_;
|
||||
if (sample) *sample = 0;
|
||||
return S_OK;
|
||||
}
|
||||
const uint64_t in_slice = rel % m.Slice2DSizeBytes;
|
||||
const uint64_t element = (in_slice % m.PitchBytes) / p.BytesPerElement;
|
||||
if (plane) *plane = pi;
|
||||
if (mip) *mip = mi;
|
||||
if (z) *z = static_cast<UINT32>(rel / m.Slice2DSizeBytes);
|
||||
if (y) *y = static_cast<UINT32>(in_slice / m.PitchBytes * block_);
|
||||
if (x) *x = element / m.SampleCount * block_;
|
||||
if (sample) *sample = static_cast<UINT32>(element % m.SampleCount);
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
HRESULT CopyIntoSubresource(void* base, UINT32 plane, UINT32 subresource, const void* linear, UINT32 row_pitch,
|
||||
UINT32 slice_pitch) override {
|
||||
return copy(static_cast<uint8_t*>(base), plane, subresource, static_cast<const uint8_t*>(linear), row_pitch,
|
||||
slice_pitch, true);
|
||||
}
|
||||
HRESULT CopyFromSubresource(void* linear, UINT32 plane, UINT32 subresource, UINT32, const void* base,
|
||||
UINT32 row_pitch, UINT32 slice_pitch) override {
|
||||
return copy(static_cast<uint8_t*>(const_cast<void*>(base)), plane, subresource, static_cast<uint8_t*>(linear),
|
||||
row_pitch, slice_pitch, false);
|
||||
}
|
||||
HRESULT GetResourceTiling(UINT32* total_tiles, XgPackedMipDesc* packed, XgTileShape* shape, UINT32* count,
|
||||
UINT32 first, XgSubresourceTiling* tilings) override {
|
||||
// D3D12 standard 64 KB tiles (the public D3D12 tiled-resource rules): the tile shape follows
|
||||
// the element size (256x256 one-byte elements down to 64x64 sixteen-byte ones, in blocks for
|
||||
// block-compressed formats). Leading mips at least one tile wide and high are standard; the
|
||||
// smaller rest are packed into a mip tail per array slice, as on the console, whose titles
|
||||
// expect few standard mips. Tiles are numbered over the subresources in order (mip-major
|
||||
// within a slice), each slice's packed tail after its standard mips.
|
||||
// 3D resources use the D3D12 standard 3D tile shapes (64x32x32 one-byte elements down to
|
||||
// 16x16x16 sixteen-byte ones), 1D textures a 64 KiB row of elements, buffers 64 KiB.
|
||||
const uint32_t bpe = layout_.Plane[0].BytesPerElement;
|
||||
const bool volume = layout_.Dimension == kDimTexture3D;
|
||||
uint32_t tile_w = 128, tile_h = 128, tile_d = 1;
|
||||
if (layout_.Dimension == kDimBuffer) {
|
||||
tile_w = 65536;
|
||||
tile_h = 1;
|
||||
} else if (layout_.Dimension == kDimTexture1D) {
|
||||
tile_w = 65536 / (bpe ? bpe : 1) * block_;
|
||||
tile_h = 1;
|
||||
} else if (volume) {
|
||||
switch (bpe) {
|
||||
case 1: tile_w = 64; tile_h = 32; tile_d = 32; break;
|
||||
case 2: tile_w = 32; tile_h = 32; tile_d = 32; break;
|
||||
case 4: tile_w = 32; tile_h = 32; tile_d = 16; break;
|
||||
case 8: tile_w = 32; tile_h = 16; tile_d = 16; break;
|
||||
case 16: tile_w = 16; tile_h = 16; tile_d = 16; break;
|
||||
default: tile_w = 32; tile_h = 32; tile_d = 16; break;
|
||||
}
|
||||
tile_w *= block_;
|
||||
tile_h *= block_;
|
||||
} else {
|
||||
switch (bpe) {
|
||||
case 1: tile_w = 256; tile_h = 256; break;
|
||||
case 2: tile_w = 256; tile_h = 128; break;
|
||||
case 4: tile_w = 128; tile_h = 128; break;
|
||||
case 8: tile_w = 128; tile_h = 64; break;
|
||||
case 16: tile_w = 64; tile_h = 64; break;
|
||||
default: break;
|
||||
}
|
||||
tile_w *= block_;
|
||||
tile_h *= block_;
|
||||
}
|
||||
auto depth_of = [&](UINT32 m) { return volume ? layout_.Plane[0].MipLayout[m].DepthOrArraySize : 1u; };
|
||||
const UINT32 mips = layout_.MipLevels;
|
||||
UINT32 standard = 0;
|
||||
while (standard < mips && layout_.Plane[0].MipLayout[standard].WidthPixels >= tile_w &&
|
||||
layout_.Plane[0].MipLayout[standard].HeightPixels >= tile_h && depth_of(standard) >= tile_d) {
|
||||
++standard;
|
||||
}
|
||||
uint64_t tail_bytes = 0;
|
||||
for (UINT32 m = standard; m < mips; ++m) {
|
||||
tail_bytes += volume ? layout_.Plane[0].MipLayout[m].SizeBytes : layout_.Plane[0].MipLayout[m].Slice2DSizeBytes;
|
||||
}
|
||||
const UINT32 tail_tiles = standard < mips ? static_cast<UINT32>((tail_bytes + kResourceAlign - 1) / kResourceAlign) : 0;
|
||||
auto tiles_of = [&](UINT32 m) {
|
||||
const XgMipLevelLayout& l = layout_.Plane[0].MipLayout[m];
|
||||
return ((l.WidthPixels + tile_w - 1) / tile_w) * ((l.HeightPixels + tile_h - 1) / tile_h) *
|
||||
((depth_of(m) + tile_d - 1) / tile_d);
|
||||
};
|
||||
UINT32 per_slice = tail_tiles;
|
||||
for (UINT32 m = 0; m < standard; ++m) per_slice += tiles_of(m);
|
||||
if (total_tiles) *total_tiles = per_slice * slices_;
|
||||
UINT32 standard_tiles = 0;
|
||||
for (UINT32 m = 0; m < standard; ++m) standard_tiles += tiles_of(m);
|
||||
if (packed) {
|
||||
*packed = {static_cast<UINT8>(standard), static_cast<UINT8>(mips - standard), tail_tiles,
|
||||
standard < mips ? standard_tiles : 0};
|
||||
}
|
||||
if (shape) *shape = {tile_w, tile_h, tile_d};
|
||||
if (count) {
|
||||
const UINT32 total = mips * slices_;
|
||||
UINT32 written = 0;
|
||||
for (UINT32 i = first; i < total && written < *count && tilings; ++i, ++written) {
|
||||
const UINT32 m = i % mips, slice = i / mips;
|
||||
if (m >= standard) {
|
||||
tilings[written] = {0, 0, 0, 0xFFFFFFFFu}; // packed: no tiling of its own
|
||||
continue;
|
||||
}
|
||||
UINT32 start = slice * per_slice;
|
||||
for (UINT32 k = 0; k < m; ++k) start += tiles_of(k);
|
||||
const XgMipLevelLayout& l = layout_.Plane[0].MipLayout[m];
|
||||
tilings[written] = {(l.WidthPixels + tile_w - 1) / tile_w,
|
||||
static_cast<UINT16>((l.HeightPixels + tile_h - 1) / tile_h),
|
||||
static_cast<UINT16>((depth_of(m) + tile_d - 1) / tile_d), start};
|
||||
}
|
||||
*count = written;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT GetTextureViewDescriptor(UINT32, void*) override {
|
||||
BX_STUB_LOG("xg_xs.dll", "XGTextureAddressComputer::GetTextureViewDescriptor");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
bool IsTiledResource() override { return false; }
|
||||
HRESULT GetSwizzlePatternInfo(UINT32, void*) override {
|
||||
BX_STUB_LOG("xg_xs.dll", "XGTextureAddressComputer::GetSwizzlePatternInfo");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
private:
|
||||
HRESULT copy(uint8_t* tiled, UINT32 plane, UINT32 subresource, uint8_t* linear_rw, UINT32 row_pitch,
|
||||
UINT32 slice_pitch, bool into) {
|
||||
return copy(tiled, plane, subresource, static_cast<const uint8_t*>(linear_rw), row_pitch, slice_pitch, into,
|
||||
linear_rw);
|
||||
}
|
||||
HRESULT copy(uint8_t* tiled, UINT32 plane, UINT32 subresource, const uint8_t* linear, UINT32 row_pitch,
|
||||
UINT32 slice_pitch, bool into, uint8_t* linear_out = nullptr) {
|
||||
if (!tiled || !linear || plane >= layout_.Planes) return E_INVALIDARG;
|
||||
const UINT32 mip = subresource % layout_.MipLevels;
|
||||
const UINT32 slice = subresource / layout_.MipLevels;
|
||||
const XgPlaneLayout& p = layout_.Plane[plane];
|
||||
const XgMipLevelLayout& m = p.MipLayout[mip];
|
||||
const bool volume = layout_.Dimension == kDimTexture3D;
|
||||
if (slice >= slices_) return E_INVALIDARG; // slices_ is 1 for a volume: its subresources are its mips
|
||||
const UINT32 depth = volume ? m.DepthOrArraySize : 1;
|
||||
if (swizzled_) { // one 2D tile, one mip, one slice: element by element
|
||||
if (subresource != 0) return E_INVALIDARG;
|
||||
for (UINT32 row = 0; row < m.HeightElements; ++row) {
|
||||
for (UINT32 col = 0; col < m.WidthElements; ++col) {
|
||||
uint8_t* t = tiled + m.OffsetBytes + element_offset(col, row);
|
||||
const uint64_t lin = static_cast<uint64_t>(row) * row_pitch + static_cast<uint64_t>(col) * sw_.bytes;
|
||||
if (into) std::memcpy(t, linear + lin, sw_.bytes);
|
||||
else std::memcpy(linear_out + lin, t, sw_.bytes);
|
||||
}
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
const uint64_t row_bytes = static_cast<uint64_t>(m.WidthElements) * m.SampleCount * p.BytesPerElement;
|
||||
for (UINT32 z = 0; z < depth; ++z) {
|
||||
uint8_t* dst_slice = tiled + m.OffsetBytes + (volume ? z : slice) * m.Slice2DSizeBytes;
|
||||
for (UINT32 row = 0; row < m.HeightElements; ++row) {
|
||||
uint8_t* t = dst_slice + static_cast<uint64_t>(row) * m.PitchBytes;
|
||||
const uint64_t lin = static_cast<uint64_t>(z) * slice_pitch + static_cast<uint64_t>(row) * row_pitch;
|
||||
if (into) std::memcpy(t, linear + lin, row_bytes);
|
||||
else std::memcpy(linear_out + lin, t, row_bytes);
|
||||
}
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
uint32_t element_offset(uint32_t ex, uint32_t ey) const { return pdep(ex, sw_.x_mask) | pdep(ey, sw_.y_mask); }
|
||||
|
||||
XgResourceLayout layout_{};
|
||||
uint32_t block_ = 1;
|
||||
uint32_t slices_ = 1;
|
||||
bool swizzled_ = false; // SW_64KB_S, one tile (see Sw64kbS)
|
||||
Sw64kbS sw_{};
|
||||
std::atomic<ULONG> refs_{1};
|
||||
};
|
||||
|
||||
HRESULT LayoutComputer::create(const XgResourceDesc& d, XGTextureAddressComputer** out) {
|
||||
FormatInfo fi{1, 1, 0};
|
||||
const bool buffer = d.Dimension == kDimBuffer;
|
||||
if (!buffer && !format_info(d.Format, &fi)) {
|
||||
log_rejected(&d, "format not in the BetterXen XG table");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (d.Dimension < kDimBuffer || d.Dimension > kDimTexture3D || d.Width == 0) {
|
||||
log_rejected(&d, "invalid description");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// The public D3D12 resource limits (D3D12_REQ_TEXTURE1D/2D_U_DIMENSION 16384,
|
||||
// D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION 2048, D3D12_REQ_TEXTURE1D/2D_ARRAY_AXIS_DIMENSION
|
||||
// 2048). Within them every pitch fits 32 bits and no size computation overflows. A buffer
|
||||
// only needs its 64 KiB-aligned size to fit 64 bits.
|
||||
{
|
||||
const bool volume = d.Dimension == kDimTexture3D;
|
||||
const uint64_t max_xy = volume ? 2048 : 16384;
|
||||
const uint32_t height = d.Dimension == kDimTexture1D ? 1 : d.Height;
|
||||
const bool too_big = buffer ? d.Width > UINT64_MAX - kResourceAlign
|
||||
: d.Width > max_xy || height > max_xy || d.DepthOrArraySize > 2048;
|
||||
if (too_big) {
|
||||
log_rejected(&d, "dimension past the D3D12 resource limits");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
}
|
||||
auto* c = new (std::nothrow) LayoutComputer();
|
||||
if (!c) return E_OUTOFMEMORY;
|
||||
XgResourceLayout& L = c->layout_;
|
||||
L.Dimension = d.Dimension;
|
||||
L.BaseAlignmentBytes = d.Alignment > kResourceAlign ? d.Alignment : kResourceAlign;
|
||||
if (buffer) {
|
||||
L.MipLevels = 1;
|
||||
L.Planes = 1;
|
||||
XgPlaneLayout& p = L.Plane[0];
|
||||
p.Usage = kPlaneDefault;
|
||||
p.BytesPerElement = 1;
|
||||
p.StandardMipCount = 1;
|
||||
p.SizeBytes = p.SliceSizeBytes = d.Width;
|
||||
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
|
||||
XgMipLevelLayout& m = p.MipLayout[0];
|
||||
m.SizeBytes = m.Slice2DSizeBytes = d.Width;
|
||||
m.PitchBytes = static_cast<UINT32>(d.Width > UINT32_MAX ? UINT32_MAX : d.Width);
|
||||
m.WidthElements = m.WidthPixels = m.PitchPixels = m.PaddedWidthElements = m.PitchBytes;
|
||||
m.HeightElements = m.HeightPixels = m.PaddedHeightElements = 1;
|
||||
m.DepthOrArraySize = m.PaddedDepthOrArraySize = m.SampleCount = m.SliceDepthElements = 1;
|
||||
m.AlignmentBytes = static_cast<UINT32>(kRowAlign);
|
||||
L.SizeBytes = align_up(d.Width, kResourceAlign);
|
||||
*out = c;
|
||||
return S_OK;
|
||||
}
|
||||
const uint32_t height = d.Dimension == kDimTexture1D ? 1 : (d.Height ? d.Height : 1);
|
||||
const uint32_t depth_or_array = d.DepthOrArraySize ? d.DepthOrArraySize : 1;
|
||||
uint32_t full = 1;
|
||||
for (uint64_t w = d.Width, h = height, z = d.Dimension == kDimTexture3D ? depth_or_array : 1; w > 1 || h > 1 || z > 1;
|
||||
w >>= 1, h >>= 1, z >>= 1) {
|
||||
++full;
|
||||
}
|
||||
uint32_t mips = d.MipLevels ? d.MipLevels : full;
|
||||
if (mips > full) mips = full;
|
||||
if (mips > kMaxMips) {
|
||||
log_rejected(&d, "more than 15 mip levels");
|
||||
delete c;
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
const uint32_t samples = d.SampleDesc.Count ? d.SampleDesc.Count : 1;
|
||||
c->block_ = fi.block;
|
||||
c->slices_ = d.Dimension == kDimTexture3D ? 1 : depth_or_array;
|
||||
// Default, row-major and undefined-swizzle requests leave the choice to XG: BetterXen picks
|
||||
// linear and reports it. A request for SW_64KB_S on one 2D tile gets that layout. Any other
|
||||
// requested swizzle mode is laid out linearly and reported as LINEAR (titles do not expect
|
||||
// XGCreateTextureComputer to fail for a mode they ask for); each such mode is logged once.
|
||||
const uint32_t width_el = static_cast<uint32_t>((d.Width + fi.block - 1) / fi.block);
|
||||
const uint32_t height_el = (height + fi.block - 1) / fi.block;
|
||||
Sw64kbS sw{};
|
||||
const bool requested = (d.Layout & kLayoutSwizzleFlag) && d.Layout != kLayoutSwizzleLinear;
|
||||
const bool single_tile_s = d.Layout == (kLayoutSwizzleFlag | kSwizzleMode64KbS) && d.Dimension == kDimTexture2D &&
|
||||
mips == 1 && depth_or_array == 1 && samples == 1 && !fi.stencil &&
|
||||
sw64kb_s_params(fi.bytes, &sw) && width_el <= sw.tile_x && height_el <= sw.tile_y;
|
||||
if (requested && !single_tile_s) log_linear_instead(&d);
|
||||
if (single_tile_s) {
|
||||
c->swizzled_ = true;
|
||||
c->sw_ = sw;
|
||||
L.MipLevels = 1;
|
||||
L.Planes = 1;
|
||||
L.BaseAlignmentBytes = d.Alignment > kTileBytes ? d.Alignment : kTileBytes;
|
||||
XgPlaneLayout& p = L.Plane[0];
|
||||
p.Usage = kPlaneDefault;
|
||||
p.BytesPerElement = fi.bytes;
|
||||
p.StandardMipCount = 1;
|
||||
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
|
||||
p.SizeBytes = p.SliceSizeBytes = kTileBytes;
|
||||
XgMipLevelLayout& m = p.MipLayout[0];
|
||||
m.WidthPixels = static_cast<UINT32>(d.Width);
|
||||
m.HeightPixels = height;
|
||||
m.WidthElements = width_el;
|
||||
m.HeightElements = height_el;
|
||||
m.DepthOrArraySize = m.PaddedDepthOrArraySize = m.SampleCount = m.SliceDepthElements = 1;
|
||||
m.PitchBytes = sw.tile_x * sw.bytes;
|
||||
m.PitchPixels = sw.tile_x * fi.block;
|
||||
m.PaddedWidthElements = sw.tile_x;
|
||||
m.PaddedHeightElements = sw.tile_y;
|
||||
m.AlignmentBytes = static_cast<UINT32>(kTileBytes);
|
||||
m.SwizzleMode = kSwizzleMode64KbS;
|
||||
m.SizeBytes = m.Slice2DSizeBytes = kTileBytes;
|
||||
L.SizeBytes = kTileBytes;
|
||||
*out = c;
|
||||
return S_OK;
|
||||
}
|
||||
L.MipLevels = mips;
|
||||
L.Planes = fi.stencil ? 2 : 1;
|
||||
uint64_t cursor = 0;
|
||||
for (uint32_t pi = 0; pi < L.Planes; ++pi) {
|
||||
XgPlaneLayout& p = L.Plane[pi];
|
||||
p.Usage = fi.stencil ? (pi == 0 ? kPlaneDepth : kPlaneStencil) : kPlaneDefault;
|
||||
p.BytesPerElement = fi.stencil && pi == 1 ? 1 : fi.bytes;
|
||||
p.StandardMipCount = mips;
|
||||
p.MipTailMipCount = 0;
|
||||
p.BaseAlignmentBytes = L.BaseAlignmentBytes;
|
||||
cursor = align_up(cursor, kResourceAlign);
|
||||
p.BaseOffsetBytes = cursor;
|
||||
for (uint32_t mi = 0; mi < mips; ++mi) {
|
||||
XgMipLevelLayout& m = p.MipLayout[mi];
|
||||
m.WidthPixels = mip_extent(d.Width, mi);
|
||||
m.HeightPixels = mip_extent(height, mi);
|
||||
m.DepthOrArraySize = d.Dimension == kDimTexture3D ? mip_extent(depth_or_array, mi) : depth_or_array;
|
||||
m.WidthElements = (m.WidthPixels + fi.block - 1) / fi.block;
|
||||
m.HeightElements = (m.HeightPixels + fi.block - 1) / fi.block;
|
||||
m.SampleCount = samples;
|
||||
m.PitchBytes = static_cast<UINT32>(align_up(static_cast<uint64_t>(m.WidthElements) * samples * p.BytesPerElement, kRowAlign));
|
||||
m.PitchPixels = m.PitchBytes / (p.BytesPerElement * samples) * fi.block;
|
||||
m.PaddedWidthElements = m.PitchBytes / (p.BytesPerElement * samples);
|
||||
m.PaddedHeightElements = m.HeightElements;
|
||||
m.PaddedDepthOrArraySize = m.DepthOrArraySize;
|
||||
m.SliceDepthElements = 1;
|
||||
m.AlignmentBytes = static_cast<UINT32>(kMipAlign);
|
||||
m.SwizzleMode = kSwizzleModeLinear;
|
||||
m.Slice2DSizeBytes = static_cast<uint64_t>(m.PitchBytes) * m.HeightElements;
|
||||
m.SizeBytes = m.Slice2DSizeBytes * m.DepthOrArraySize;
|
||||
cursor = align_up(cursor, kMipAlign);
|
||||
m.OffsetBytes = cursor;
|
||||
cursor += m.SizeBytes;
|
||||
}
|
||||
p.SizeBytes = cursor - p.BaseOffsetBytes;
|
||||
p.SliceSizeBytes = p.MipLayout[0].Slice2DSizeBytes;
|
||||
}
|
||||
L.SizeBytes = align_up(cursor, kResourceAlign);
|
||||
*out = c;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
__declspec(dllexport) HRESULT WINAPI XGCreateTextureComputer(const XgResourceDesc* desc, XGTextureAddressComputer** out) {
|
||||
if (!desc || !out) return E_INVALIDARG;
|
||||
*out = nullptr;
|
||||
const HRESULT hr = LayoutComputer::create(*desc, out);
|
||||
if (SUCCEEDED(hr)) {
|
||||
static std::atomic<uint64_t> created{0};
|
||||
const uint64_t n = ++created;
|
||||
if ((n & (n - 1)) == 0) {
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"BetterXen linear layout (not console tiling): dim=%u %llux%u x%u mips=%u format=%u layout=0x%x size=%llu; total created=%llu",
|
||||
desc->Dimension, static_cast<unsigned long long>(desc->Width), desc->Height,
|
||||
desc->DepthOrArraySize, desc->MipLevels, desc->Format, desc->Layout,
|
||||
static_cast<unsigned long long>((*out)->GetResourceSizeBytes()), static_cast<unsigned long long>(n));
|
||||
bx_log_emit(BX_LOG_INFO, "xg_xs", "texture_computer", detail);
|
||||
}
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
__declspec(dllexport) HRESULT WINAPI XGSuggestSwizzleMode(const XgResourceDesc* desc, uint32_t, uint32_t* layout) {
|
||||
if (!desc || !layout) return E_INVALIDARG;
|
||||
*layout = kLayoutSwizzleLinear; // this layer lays every texture out linearly
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,9 @@
|
||||
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)
|
||||
@@ -0,0 +1,911 @@
|
||||
/*
|
||||
* Clean-room COM IUnknown vtable dispatch for xgameruntime.dll!QueryApiImpl (#456).
|
||||
*
|
||||
* Provenance: Interface identifiers, IUnknown inheritance, and vtable slot indices were
|
||||
* established via clean-room black-box interoperability testing against Microsoft's publicly
|
||||
* distributed PC GDK NuGet package (Microsoft.GDK.Windows 2610.0.9661, nuget.org) using an
|
||||
* independently authored synthetic caller invoking public documented GDK APIs. No Microsoft
|
||||
* source code or binary code is copied or bundled.
|
||||
*
|
||||
* XGameSave and XPackage class ids, interface ids, and vtable order are separate from that
|
||||
* work. Those facts are from https://github.com/xodus-gaming/xgameruntime-docs commit
|
||||
* 7090008692569aa6081e30dfdd9de58237741e24. Function signatures follow the public Microsoft
|
||||
* Learn GDK reference (learn.microsoft.com/gaming/gdk). No text from either source is copied.
|
||||
*/
|
||||
#include "com_dispatch.h"
|
||||
|
||||
#include "runtime_internal.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "task_queue.h"
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI XTaskQueueCreate(bx::gdk::DispatchMode, bx::gdk::DispatchMode, void**);
|
||||
void WINAPI XTaskQueueCloseHandle(void*);
|
||||
bool WINAPI XTaskQueueDispatch(void*, bx::gdk::Port, uint32_t);
|
||||
HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLBACK*)(void*, bool));
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void*, bx::gdk::Port, uint32_t, void*,
|
||||
void (CALLBACK*)(void*, bool));
|
||||
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
|
||||
|
||||
HRESULT WINAPI XAsyncGetStatus(void*, bool);
|
||||
HRESULT WINAPI XAsyncGetResultSize(void*, size_t*);
|
||||
void WINAPI XAsyncCancel(void*);
|
||||
|
||||
HRESULT WINAPI XUserAddAsync(uint32_t, void*);
|
||||
HRESULT WINAPI XUserAddResult(void*, void**);
|
||||
void WINAPI XUserCloseHandle(void*);
|
||||
HRESULT WINAPI XUserGetId(void*, uint64_t*);
|
||||
HRESULT WINAPI XUserGetGamertag(void*, uint32_t, size_t, char*, size_t*);
|
||||
HRESULT WINAPI XUserGetTokenAndSignatureAsync(void*, uint32_t, const char*, const char*, size_t, const void*, size_t,
|
||||
const uint8_t*, void*);
|
||||
HRESULT WINAPI XUserGetTokenAndSignatureResultSize(void*, size_t*);
|
||||
HRESULT WINAPI XUserGetTokenAndSignatureResult(void*, size_t, void*, void**, size_t*);
|
||||
HRESULT WINAPI XUserResolvePrivilegeWithUiAsync(void*, uint32_t, uint32_t, void*);
|
||||
HRESULT WINAPI XUserResolvePrivilegeWithUiResult(void*);
|
||||
|
||||
HRESULT WINAPI XStoreCreateContext(void*, void**);
|
||||
void WINAPI XStoreCloseContextHandle(void*);
|
||||
HRESULT WINAPI XStoreQueryGameLicenseAsync(void*, void*);
|
||||
HRESULT WINAPI XStoreQueryGameLicenseResult(void*, void*);
|
||||
HRESULT WINAPI XStoreAcquireLicenseForPackageAsync(void*, const char*, void*);
|
||||
HRESULT WINAPI XStoreAcquireLicenseForPackageResult(void*, void**);
|
||||
HRESULT WINAPI XStoreAcquireLicenseForDurablesAsync(void*, const char*, void*);
|
||||
HRESULT WINAPI XStoreAcquireLicenseForDurablesResult(void*, void**);
|
||||
HRESULT WINAPI XStoreQueryEntitledProductsAsync(void*, uint32_t, uint32_t, void*);
|
||||
HRESULT WINAPI XStoreQueryEntitledProductsResult(void*, void**);
|
||||
HRESULT WINAPI XStoreQueryAssociatedProductsAsync(void*, uint32_t, uint32_t, void*);
|
||||
HRESULT WINAPI XStoreQueryAssociatedProductsResult(void*, void**);
|
||||
|
||||
HRESULT WINAPI XSystemGetConsoleId(size_t, char*, size_t*);
|
||||
uint32_t WINAPI XSystemGetDeviceType();
|
||||
HRESULT WINAPI XSystemGetXboxLiveSandboxId(size_t, char*, size_t*);
|
||||
|
||||
HRESULT WINAPI XPersistentLocalStorageGetPathSize(size_t*);
|
||||
HRESULT WINAPI XPersistentLocalStorageGetPath(size_t, char*, size_t*);
|
||||
HRESULT WINAPI XPersistentLocalStorageGetSpaceInfo(void*);
|
||||
|
||||
HRESULT WINAPI XGameUiShowPlayerProfileCardAsync(void*, uint64_t, void*);
|
||||
HRESULT WINAPI XGameUiShowTextEntryAsync(const char*, const char*, const char*, uint32_t, uint32_t, void*);
|
||||
HRESULT WINAPI XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync(void*);
|
||||
HRESULT WINAPI XNetworkingQuerySecurityInformationForUrlAsync(const char*, void*);
|
||||
} // extern "C"
|
||||
|
||||
namespace bx::gdk {
|
||||
namespace {
|
||||
|
||||
constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
|
||||
|
||||
// Public Microsoft.GDK.Windows 2610.0.9661 QueryApiImpl class & interface identifiers.
|
||||
constexpr GUID kCoreGuid = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
|
||||
constexpr GUID kFeatureGuid = {0x8836FE87, 0xEDB9, 0x4FE3, {0x8D, 0xAD, 0x05, 0xF0, 0xD2, 0xCD, 0x5B, 0x40}};
|
||||
constexpr GUID kSystemClsid = {0xE349BD1A, 0xFC20, 0x4E40, {0xB9, 0x9C, 0x41, 0x78, 0xCC, 0x6B, 0x40, 0x9F}};
|
||||
constexpr GUID kSystemIid = {0x1861CF2E, 0xE18B, 0x4834, {0xA9, 0xF5, 0xB4, 0xA4, 0xE6, 0xEF, 0xB4, 0xCF}};
|
||||
constexpr GUID kErrorGuid = {0x8CA467F7, 0x22E8, 0x4096, {0x84, 0x56, 0xBB, 0x8A, 0xA1, 0x3F, 0x79, 0xD8}};
|
||||
constexpr GUID kPlsClsid = {0xF4FAF4D4, 0x2D04, 0x4FCE, {0xB3, 0xE0, 0x47, 0x4A, 0x71, 0x3A, 0x3E, 0x84}};
|
||||
constexpr GUID kPlsIid = {0x41A4E10C, 0x5A7E, 0x41D9, {0x8C, 0x37, 0x37, 0xBD, 0xE6, 0x2A, 0x07, 0xD6}};
|
||||
constexpr GUID kUserClsid = {0x01ACD177, 0x91F9, 0x4763, {0xA3, 0x8E, 0xCC, 0xBB, 0x55, 0xCE, 0x32, 0xE0}};
|
||||
constexpr GUID kUserGamertagIid = {0xCEF4FAC0, 0x7676, 0x4A94, {0xA1, 0x19, 0x4C, 0x43, 0xF9, 0xEB, 0x5B, 0x74}};
|
||||
constexpr GUID kStoreClsid = {0x0DD112AC, 0x7C24, 0x448C, {0xB9, 0x2B, 0x39, 0x60, 0xFB, 0x5B, 0xD3, 0x0C}};
|
||||
constexpr GUID kStoreIid = {0xB09D803C, 0x2414, 0x4A05, {0x82, 0xC6, 0x66, 0xDF, 0xDC, 0x9E, 0x9A, 0x44}};
|
||||
constexpr GUID kStoreDurablesIid = {0x2D42FEA5, 0xE71D, 0x4B76, {0x97, 0xCD, 0xC5, 0x0A, 0xFB, 0xB3, 0xAE, 0x5D}};
|
||||
constexpr GUID kGameUiClsid = {0xDFCD4649, 0x4FF8, 0x4043, {0xBA, 0x07, 0x35, 0xD6, 0x07, 0xDF, 0x98, 0xB0}};
|
||||
constexpr GUID kGameUiIid = {0xEAF669DF, 0x5542, 0x4590, {0x99, 0xA3, 0x8D, 0xC0, 0x61, 0xF8, 0x37, 0xCC}};
|
||||
constexpr GUID kNetworkingClsid = {0x37E56907, 0x2F10, 0x41E8, {0xB7, 0x2F, 0x36, 0xED, 0xB1, 0x85, 0x33, 0x1A}};
|
||||
constexpr GUID kNetworkingIid = {0xBF2346B2, 0x39AF, 0x4658, {0xB5, 0xEA, 0x44, 0x71, 0x3C, 0x7E, 0x83, 0xB3}};
|
||||
constexpr GUID kGameClsid = {0x973A344E, 0x24BF, 0x4D0F, {0x84, 0x57, 0x56, 0xC5, 0x34, 0x89, 0x2B, 0x29}};
|
||||
constexpr GUID kGameIid = {0x2549F142, 0x6419, 0x4A06, {0x97, 0xB5, 0x93, 0x1A, 0xAB, 0x7C, 0x2F, 0x34}};
|
||||
// XSystemGetAnalyticsInfo and XDisplayTryEnableHdrMode reach the runtime through these keys
|
||||
// (from authorized GDK material; see the CHANGELOG). The function contracts are public.
|
||||
constexpr GUID kAnalyticsGuid = {0xB884675D, 0xB738, 0x4A9C, {0x81, 0x5D, 0x9A, 0x9A, 0x1E, 0x0C, 0x6C, 0x9B}};
|
||||
constexpr GUID kDisplayClsid = {0x03F0FE74, 0xFDD9, 0x4E5C, {0xB6, 0x30, 0xF9, 0x33, 0x9C, 0x47, 0xAC, 0xC5}};
|
||||
constexpr GUID kDisplayIid = {0x35F07670, 0x706E, 0x4BFB, {0x94, 0x76, 0x09, 0x07, 0x98, 0xC5, 0xEB, 0xF3}};
|
||||
|
||||
bool guid_eq(const GUID& a, const GUID& b) {
|
||||
return std::memcmp(&a, &b, sizeof(GUID)) == 0;
|
||||
}
|
||||
|
||||
struct ComSingleton {
|
||||
const void* const* vtbl;
|
||||
const GUID* iid;
|
||||
const char* name;
|
||||
};
|
||||
|
||||
HRESULT WINAPI com_query_interface(void* self, const GUID* riid, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!riid) return E_INVALIDARG;
|
||||
auto* obj = static_cast<ComSingleton*>(self);
|
||||
if (guid_eq(*riid, kIUnknown) || guid_eq(*riid, *obj->iid)) {
|
||||
*out = obj;
|
||||
return S_OK;
|
||||
}
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
ULONG WINAPI com_add_ref(void*) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
ULONG WINAPI com_release(void*) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
template <size_t Slot>
|
||||
HRESULT WINAPI com_unimpl_slot(void* self) {
|
||||
auto* obj = static_cast<const ComSingleton*>(self);
|
||||
char method[32];
|
||||
std::snprintf(method, sizeof(method), "slot_%zu", Slot);
|
||||
BX_VTABLE_STUB_LOG(obj ? obj->name : "IXGameRuntime", static_cast<uint32_t>(Slot), method);
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
template <size_t N, size_t... Is>
|
||||
constexpr std::array<const void*, N> make_default_vtbl_impl(std::index_sequence<Is...>) {
|
||||
return {((Is == 0) ? reinterpret_cast<const void*>(&com_query_interface)
|
||||
: (Is == 1) ? reinterpret_cast<const void*>(&com_add_ref)
|
||||
: (Is == 2) ? reinterpret_cast<const void*>(&com_release)
|
||||
: reinterpret_cast<const void*>(&com_unimpl_slot<Is>))...};
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
std::array<const void*, N> make_default_vtbl() {
|
||||
return make_default_vtbl_impl<N>(std::make_index_sequence<N>{});
|
||||
}
|
||||
|
||||
// --- Core (XAsync + XTaskQueue + XThread) ---
|
||||
|
||||
thread_local bool tls_time_sensitive = false;
|
||||
|
||||
HRESULT WINAPI core_async_get_status(void*, void* async, bool wait) {
|
||||
return XAsyncGetStatus(async, wait);
|
||||
}
|
||||
HRESULT WINAPI core_async_get_result_size(void*, void* async, size_t* size) {
|
||||
return XAsyncGetResultSize(async, size);
|
||||
}
|
||||
void WINAPI core_async_cancel(void*, void* async) {
|
||||
XAsyncCancel(async);
|
||||
}
|
||||
HRESULT WINAPI core_tq_create(void*, DispatchMode work, DispatchMode comp, void** out) {
|
||||
return XTaskQueueCreate(work, comp, out);
|
||||
}
|
||||
bool WINAPI core_tq_dispatch(void*, void* queue, Port port, uint32_t timeout) {
|
||||
return XTaskQueueDispatch(queue, port, timeout);
|
||||
}
|
||||
void WINAPI core_tq_close(void*, void* queue) {
|
||||
XTaskQueueCloseHandle(queue);
|
||||
}
|
||||
HRESULT WINAPI core_tq_submit(void*, void* queue, Port port, void* ctx, void (CALLBACK* cb)(void*, bool)) {
|
||||
return XTaskQueueSubmitCallback(queue, port, ctx, cb);
|
||||
}
|
||||
HRESULT WINAPI core_tq_submit_delayed(void*, void* queue, Port port, uint32_t delay_ms, void* ctx,
|
||||
void (CALLBACK* cb)(void*, bool)) {
|
||||
if (delay_ms > 0) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "queued delay_ms=%lu", static_cast<unsigned long>(delay_ms));
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XTaskQueueSubmitDelayedCallback", detail);
|
||||
}
|
||||
return XTaskQueueSubmitDelayedCallback(queue, port, delay_ms, ctx, cb);
|
||||
}
|
||||
bool WINAPI core_tq_get_process(void*, void** out) {
|
||||
return XTaskQueueGetCurrentProcessTaskQueue(out);
|
||||
}
|
||||
HRESULT WINAPI core_thread_set_time_sensitive(void*, bool is_ts) {
|
||||
tls_time_sensitive = is_ts;
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI core_thread_verify_not_time_sensitive(void*) {
|
||||
return tls_time_sensitive ? E_FAIL : S_OK;
|
||||
}
|
||||
HRESULT WINAPI core_runtime_guard_hook(void*, uint32_t, void*) {
|
||||
// Invoked by public GDK static thunks before subsystem dispatch.
|
||||
return S_OK;
|
||||
}
|
||||
bool WINAPI core_thread_is_time_sensitive(void*) {
|
||||
return tls_time_sensitive;
|
||||
}
|
||||
|
||||
const std::array<const void*, 36> kCoreVtbl = [] {
|
||||
auto v = make_default_vtbl<36>();
|
||||
v[3] = reinterpret_cast<const void*>(&core_async_get_status);
|
||||
v[4] = reinterpret_cast<const void*>(&core_async_get_result_size);
|
||||
v[5] = reinterpret_cast<const void*>(&core_async_cancel);
|
||||
v[12] = reinterpret_cast<const void*>(&core_tq_create);
|
||||
v[16] = reinterpret_cast<const void*>(&core_tq_dispatch);
|
||||
v[17] = reinterpret_cast<const void*>(&core_tq_close);
|
||||
v[18] = reinterpret_cast<const void*>(&core_tq_submit);
|
||||
v[19] = reinterpret_cast<const void*>(&core_tq_submit_delayed);
|
||||
v[25] = reinterpret_cast<const void*>(&core_tq_get_process);
|
||||
v[27] = reinterpret_cast<const void*>(&core_thread_set_time_sensitive);
|
||||
v[28] = reinterpret_cast<const void*>(&core_thread_verify_not_time_sensitive);
|
||||
v[29] = reinterpret_cast<const void*>(&core_runtime_guard_hook);
|
||||
v[30] = reinterpret_cast<const void*>(&core_thread_is_time_sensitive);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kCoreObj{kCoreVtbl.data(), &kCoreGuid, "IXGameRuntimeCore"};
|
||||
|
||||
// --- XGameRuntimeIsFeatureAvailable ---
|
||||
|
||||
bool WINAPI feature_is_available(void*, uint32_t feature) {
|
||||
// XGameRuntimeFeature enum values from public XGameRuntimeFeature.h.
|
||||
switch (feature) {
|
||||
case 2: // XAsync
|
||||
case 5: // XGame
|
||||
case 8: // XGameUI
|
||||
case 10: // XNetworking
|
||||
case 12: // XPersistentLocalStorage
|
||||
case 14: // XStore
|
||||
case 15: // XSystem
|
||||
case 16: // XTaskQueue
|
||||
case 17: // XThread
|
||||
case 18: // XUser
|
||||
case 19: // XError
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const std::array<const void*, 8> kFeatureVtbl = [] {
|
||||
auto v = make_default_vtbl<8>();
|
||||
v[3] = reinterpret_cast<const void*>(&feature_is_available);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kFeatureObj{kFeatureVtbl.data(), &kFeatureGuid, "IXGameRuntimeFeature"};
|
||||
|
||||
// --- XSystem ---
|
||||
|
||||
HRESULT WINAPI sys_get_console_id(void*, size_t sz, char* out, size_t* used) {
|
||||
return XSystemGetConsoleId(sz, out, used);
|
||||
}
|
||||
HRESULT WINAPI sys_get_sandbox_id(void*, size_t sz, char* out, size_t* used) {
|
||||
return XSystemGetXboxLiveSandboxId(sz, out, used);
|
||||
}
|
||||
HRESULT WINAPI sys_get_app_device_id(void*, size_t sz, char* out, size_t* used) {
|
||||
constexpr char kDeviceId[] = "BX-OFFLINE-APP-DEVICE-000000000001";
|
||||
if (used) *used = 0;
|
||||
if (!out) return E_POINTER;
|
||||
const size_t req = sizeof(kDeviceId);
|
||||
if (sz < req) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
|
||||
std::memcpy(out, kDeviceId, req);
|
||||
if (used) *used = req;
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI sys_handle_track(void*, void*, void*) {
|
||||
return S_OK;
|
||||
}
|
||||
bool WINAPI sys_is_handle_valid(void*, void* handle) {
|
||||
return handle != nullptr;
|
||||
}
|
||||
void WINAPI sys_allow_full_bandwidth(void*, bool) {}
|
||||
|
||||
const std::array<const void*, 12> kSystemVtbl = [] {
|
||||
auto v = make_default_vtbl<12>();
|
||||
v[3] = reinterpret_cast<const void*>(&sys_get_console_id);
|
||||
v[4] = reinterpret_cast<const void*>(&sys_get_sandbox_id);
|
||||
v[5] = reinterpret_cast<const void*>(&sys_get_app_device_id);
|
||||
v[6] = reinterpret_cast<const void*>(&sys_handle_track);
|
||||
v[7] = reinterpret_cast<const void*>(&sys_is_handle_valid);
|
||||
v[8] = reinterpret_cast<const void*>(&sys_allow_full_bandwidth);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kSystemObj{kSystemVtbl.data(), &kSystemIid, "IXSystem"};
|
||||
|
||||
// --- XSystemGetAnalyticsInfo (public XSystem.h contract) ---
|
||||
|
||||
// Public XVersion: four uint16_t fields in this order, overlaid on a uint64_t.
|
||||
struct XVersionLayout {
|
||||
uint16_t major;
|
||||
uint16_t minor;
|
||||
uint16_t build;
|
||||
uint16_t revision;
|
||||
};
|
||||
// Public XSystemAnalyticsInfo.
|
||||
struct XSystemAnalyticsInfoLayout {
|
||||
XVersionLayout osVersion;
|
||||
XVersionLayout hostingOsVersion;
|
||||
char family[64];
|
||||
char form[64];
|
||||
};
|
||||
static_assert(sizeof(XSystemAnalyticsInfoLayout) == 0x90, "XSystemAnalyticsInfo is 144 bytes");
|
||||
|
||||
// Slot 3 returns the structure by value: MSVC passes the result buffer after `this` and
|
||||
// returns the same pointer.
|
||||
XSystemAnalyticsInfoLayout* WINAPI analytics_get_info(void*, XSystemAnalyticsInfoLayout* out) {
|
||||
if (!out) return out;
|
||||
std::memset(out, 0, sizeof(*out));
|
||||
// BetterXen's own synthetic title and system OS version; not a console build number.
|
||||
out->osVersion = {10, 0, 26100, 0};
|
||||
out->hostingOsVersion = {10, 0, 26100, 0};
|
||||
std::snprintf(out->family, sizeof(out->family), "Xbox");
|
||||
// Series S for the Lockhart profile, Series X for Anaconda (XSystemGetDeviceType 6 / 7).
|
||||
std::snprintf(out->form, sizeof(out->form), "%s",
|
||||
XSystemGetDeviceType() == 7u ? "Xbox Series X" : "Xbox Series S");
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "family=%s form='%s' os=10.0.26100.0 synthetic=1", out->family,
|
||||
out->form);
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XSystemGetAnalyticsInfo", detail);
|
||||
return out;
|
||||
}
|
||||
|
||||
const std::array<const void*, 8> kAnalyticsVtbl = [] {
|
||||
auto v = make_default_vtbl<8>();
|
||||
v[3] = reinterpret_cast<const void*>(&analytics_get_info);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kAnalyticsObj{kAnalyticsVtbl.data(), &kAnalyticsGuid, "IXSystemAnalytics"};
|
||||
|
||||
// --- XDisplayTryEnableHdrMode (public XDisplay.h contract) ---
|
||||
|
||||
// Public XDisplayHdrModeInfo.
|
||||
struct XDisplayHdrModeInfoLayout {
|
||||
float minToneMapLuminance;
|
||||
float maxToneMapLuminance;
|
||||
float maxFullFrameToneMapLuminance;
|
||||
};
|
||||
constexpr uint32_t kHdrModeResultDisabled = 2; // XDisplayHdrModeResult::Disabled
|
||||
|
||||
// BetterXen presents SDR through the host swap chain, so HDR is reported as not enabled:
|
||||
// a successful Disabled answer, not the failure value Unknown. The output is only meaningful
|
||||
// when HDR is enabled, so it is cleared.
|
||||
uint32_t WINAPI display_try_enable_hdr(void*, uint32_t preference, XDisplayHdrModeInfoLayout* info) {
|
||||
if (info) std::memset(info, 0, sizeof(*info));
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "preference=%u result=disabled reason=sdr_presentation", preference);
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XDisplayTryEnableHdrMode", detail);
|
||||
return kHdrModeResultDisabled;
|
||||
}
|
||||
|
||||
const std::array<const void*, 8> kDisplayVtbl = [] {
|
||||
auto v = make_default_vtbl<8>();
|
||||
v[4] = reinterpret_cast<const void*>(&display_try_enable_hdr);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kDisplayObj{kDisplayVtbl.data(), &kDisplayIid, "IXDisplay"};
|
||||
|
||||
// --- XError ---
|
||||
|
||||
void WINAPI err_set_callback(void*, void*, void*) {}
|
||||
void WINAPI err_set_options(void*, uint32_t, uint32_t) {}
|
||||
|
||||
/*
|
||||
* IXError slot 3. xodus-gaming/xgameruntime-docs (commit 7090008) lists this slot as unknown.
|
||||
* Its behaviour here comes from the #492 review's interop observation (atesahmet0,
|
||||
* 2026-11-26): the GDK's static library calls it before some subsystem calls, for example
|
||||
* XPackageMount, and continues only when it returns false. The default stub returned E_NOTIMPL,
|
||||
* whose low byte reads as true and stopped those calls. The parameters are not known, so none
|
||||
* are read. It is logged once so the call stays visible in `bx-cli trace`.
|
||||
*/
|
||||
bool WINAPI err_slot3(void*) {
|
||||
static std::atomic<bool> logged{false};
|
||||
if (!logged.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "IXError_slot3", "returning false (continue); arguments not read");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::array<const void*, 8> kErrorVtbl = [] {
|
||||
auto v = make_default_vtbl<8>();
|
||||
v[3] = reinterpret_cast<const void*>(&err_slot3);
|
||||
v[4] = reinterpret_cast<const void*>(&err_set_callback);
|
||||
v[5] = reinterpret_cast<const void*>(&err_set_options);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kErrorObj{kErrorVtbl.data(), &kErrorGuid, "IXError"};
|
||||
|
||||
// --- XPersistentLocalStorage ---
|
||||
|
||||
HRESULT WINAPI pls_get_path_size(void*, size_t* sz) {
|
||||
return XPersistentLocalStorageGetPathSize(sz);
|
||||
}
|
||||
HRESULT WINAPI pls_get_path(void*, size_t sz, char* out, size_t* used) {
|
||||
return XPersistentLocalStorageGetPath(sz, out, used);
|
||||
}
|
||||
HRESULT WINAPI pls_get_space_info(void*, void* info) {
|
||||
return XPersistentLocalStorageGetSpaceInfo(info);
|
||||
}
|
||||
|
||||
const std::array<const void*, 12> kPlsVtbl = [] {
|
||||
auto v = make_default_vtbl<12>();
|
||||
v[3] = reinterpret_cast<const void*>(&pls_get_path_size);
|
||||
v[4] = reinterpret_cast<const void*>(&pls_get_path);
|
||||
v[5] = reinterpret_cast<const void*>(&pls_get_space_info);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kPlsObj{kPlsVtbl.data(), &kPlsIid, "IXPersistentLocalStorage"};
|
||||
|
||||
// --- XUser ---
|
||||
|
||||
std::mutex user_event_mutex;
|
||||
uint64_t next_user_event_token = 1;
|
||||
std::unordered_set<uint64_t> user_event_tokens;
|
||||
|
||||
void WINAPI user_close_handle(void*, void* h) {
|
||||
XUserCloseHandle(h);
|
||||
}
|
||||
int32_t WINAPI user_compare(void*, void* u1, void* u2) {
|
||||
if (u1 == u2) return 0;
|
||||
return reinterpret_cast<uintptr_t>(u1) < reinterpret_cast<uintptr_t>(u2) ? -1 : 1;
|
||||
}
|
||||
HRESULT WINAPI user_get_max_users(void*, uint32_t* max_users) {
|
||||
if (!max_users) return E_POINTER;
|
||||
*max_users = 1;
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI user_add_async(void*, uint32_t opts, void* async) {
|
||||
return XUserAddAsync(opts, async);
|
||||
}
|
||||
HRESULT WINAPI user_add_result(void*, void* async, void** out) {
|
||||
return XUserAddResult(async, out);
|
||||
}
|
||||
HRESULT WINAPI user_get_local_id(void*, void* user, uint64_t* local_id) {
|
||||
if (!local_id) return E_POINTER;
|
||||
if (!user) return E_INVALIDARG;
|
||||
*local_id = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(user));
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI user_get_id(void*, void* user, uint64_t* id) {
|
||||
return XUserGetId(user, id);
|
||||
}
|
||||
HRESULT WINAPI user_get_is_guest(void*, void* user, bool* is_guest) {
|
||||
if (!is_guest) return E_POINTER;
|
||||
if (!user) return E_INVALIDARG;
|
||||
*is_guest = false;
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI user_get_state(void*, void* user, uint32_t* state) {
|
||||
if (!state) return E_POINTER;
|
||||
if (!user) return E_INVALIDARG;
|
||||
*state = 0; // XUserState::SignedIn
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI user_get_age_group(void*, void* user, uint32_t* age_group) {
|
||||
if (!age_group) return E_POINTER;
|
||||
if (!user) return E_INVALIDARG;
|
||||
*age_group = 3; // XUserAgeGroup::Adult
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI user_check_privilege(void*, void* user, uint32_t, uint32_t, bool* has_priv, uint32_t* deny_reason) {
|
||||
if (!has_priv) return E_POINTER;
|
||||
if (!user) return E_INVALIDARG;
|
||||
*has_priv = true;
|
||||
if (deny_reason) *deny_reason = 0; // XUserPrivilegeDenyReason::None
|
||||
return S_OK;
|
||||
}
|
||||
HRESULT WINAPI user_resolve_priv_async(void*, void* user, uint32_t opts, uint32_t priv, void* async) {
|
||||
return XUserResolvePrivilegeWithUiAsync(user, opts, priv, async);
|
||||
}
|
||||
HRESULT WINAPI user_resolve_priv_result(void*, void* async) {
|
||||
return XUserResolvePrivilegeWithUiResult(async);
|
||||
}
|
||||
HRESULT WINAPI user_token_async(void*, void* user, uint32_t opts, const char* method, const char* url,
|
||||
size_t hdr_cnt, const void* hdrs, size_t body_sz, const uint8_t* body, void* async) {
|
||||
return XUserGetTokenAndSignatureAsync(user, opts, method, url, hdr_cnt, hdrs, body_sz, body, async);
|
||||
}
|
||||
HRESULT WINAPI user_token_result_size(void*, void* async, size_t* sz) {
|
||||
return XUserGetTokenAndSignatureResultSize(async, sz);
|
||||
}
|
||||
HRESULT WINAPI user_token_result(void*, void* async, size_t sz, void* buf, void** res, size_t* used) {
|
||||
return XUserGetTokenAndSignatureResult(async, sz, buf, res, used);
|
||||
}
|
||||
HRESULT WINAPI user_register_change_event(void*, void*, void*, void* callback, uint64_t* token) {
|
||||
if (!token) return E_POINTER;
|
||||
if (!callback) return E_INVALIDARG;
|
||||
std::lock_guard lock(user_event_mutex);
|
||||
const uint64_t id = next_user_event_token++;
|
||||
user_event_tokens.insert(id);
|
||||
*token = id;
|
||||
return S_OK;
|
||||
}
|
||||
bool WINAPI user_unregister_change_event(void*, uint64_t token, bool) {
|
||||
std::lock_guard lock(user_event_mutex);
|
||||
return user_event_tokens.erase(token) > 0;
|
||||
}
|
||||
HRESULT WINAPI user_get_gamertag(void*, void* user, uint32_t comp, size_t sz, char* out, size_t* used) {
|
||||
return XUserGetGamertag(user, comp, sz, out, used);
|
||||
}
|
||||
|
||||
const std::array<const void*, 64> kUserVtbl = [] {
|
||||
auto v = make_default_vtbl<64>();
|
||||
v[4] = reinterpret_cast<const void*>(&user_close_handle);
|
||||
v[5] = reinterpret_cast<const void*>(&user_compare);
|
||||
v[6] = reinterpret_cast<const void*>(&user_get_max_users);
|
||||
v[7] = reinterpret_cast<const void*>(&user_add_async);
|
||||
v[8] = reinterpret_cast<const void*>(&user_add_result);
|
||||
v[9] = reinterpret_cast<const void*>(&user_get_local_id);
|
||||
v[11] = reinterpret_cast<const void*>(&user_get_id);
|
||||
v[13] = reinterpret_cast<const void*>(&user_get_is_guest);
|
||||
v[14] = reinterpret_cast<const void*>(&user_get_state);
|
||||
v[19] = reinterpret_cast<const void*>(&user_get_age_group);
|
||||
v[20] = reinterpret_cast<const void*>(&user_check_privilege);
|
||||
v[21] = reinterpret_cast<const void*>(&user_resolve_priv_async);
|
||||
v[22] = reinterpret_cast<const void*>(&user_resolve_priv_result);
|
||||
v[23] = reinterpret_cast<const void*>(&user_token_async);
|
||||
v[24] = reinterpret_cast<const void*>(&user_token_result_size);
|
||||
v[25] = reinterpret_cast<const void*>(&user_token_result);
|
||||
v[33] = reinterpret_cast<const void*>(&user_register_change_event);
|
||||
v[34] = reinterpret_cast<const void*>(&user_unregister_change_event);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kUserObj{kUserVtbl.data(), &kUserClsid, "IXUser"};
|
||||
|
||||
const std::array<const void*, 8> kUserGamertagVtbl = [] {
|
||||
auto v = make_default_vtbl<8>();
|
||||
v[3] = reinterpret_cast<const void*>(&user_get_gamertag);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kUserGamertagObj{kUserGamertagVtbl.data(), &kUserGamertagIid, "IXUserGamertag"};
|
||||
|
||||
// --- XStore ---
|
||||
|
||||
HRESULT WINAPI store_create_ctx(void*, void* user, void** out) {
|
||||
return XStoreCreateContext(user, out);
|
||||
}
|
||||
void WINAPI store_close_ctx(void*, void* ctx) {
|
||||
XStoreCloseContextHandle(ctx);
|
||||
}
|
||||
HRESULT WINAPI store_assoc_async(void*, void* ctx, uint32_t pf, uint32_t max_items, void* async) {
|
||||
return XStoreQueryAssociatedProductsAsync(ctx, pf, max_items, async);
|
||||
}
|
||||
HRESULT WINAPI store_assoc_result(void*, void* async, void** out) {
|
||||
return XStoreQueryAssociatedProductsResult(async, out);
|
||||
}
|
||||
HRESULT WINAPI store_entitled_async(void*, void* ctx, uint32_t pf, uint32_t max_items, void* async) {
|
||||
return XStoreQueryEntitledProductsAsync(ctx, pf, max_items, async);
|
||||
}
|
||||
HRESULT WINAPI store_entitled_result(void*, void* async, void** out) {
|
||||
return XStoreQueryEntitledProductsResult(async, out);
|
||||
}
|
||||
HRESULT WINAPI store_pkg_lic_async(void*, void* ctx, const char* id, void* async) {
|
||||
return XStoreAcquireLicenseForPackageAsync(ctx, id, async);
|
||||
}
|
||||
HRESULT WINAPI store_pkg_lic_result(void*, void* async, void** out) {
|
||||
return XStoreAcquireLicenseForPackageResult(async, out);
|
||||
}
|
||||
HRESULT WINAPI store_game_lic_async(void*, void* ctx, void* async) {
|
||||
return XStoreQueryGameLicenseAsync(ctx, async);
|
||||
}
|
||||
HRESULT WINAPI store_game_lic_result(void*, void* async, void* out) {
|
||||
return XStoreQueryGameLicenseResult(async, out);
|
||||
}
|
||||
HRESULT WINAPI store_dur_lic_async(void*, void* ctx, const char* id, void* async) {
|
||||
return XStoreAcquireLicenseForDurablesAsync(ctx, id, async);
|
||||
}
|
||||
HRESULT WINAPI store_dur_lic_result(void*, void* async, void** out) {
|
||||
return XStoreAcquireLicenseForDurablesResult(async, out);
|
||||
}
|
||||
|
||||
const std::array<const void*, 40> kStoreVtbl = [] {
|
||||
auto v = make_default_vtbl<40>();
|
||||
v[3] = reinterpret_cast<const void*>(&store_create_ctx);
|
||||
v[4] = reinterpret_cast<const void*>(&store_close_ctx);
|
||||
v[5] = reinterpret_cast<const void*>(&store_assoc_async);
|
||||
v[6] = reinterpret_cast<const void*>(&store_assoc_result);
|
||||
v[9] = reinterpret_cast<const void*>(&store_entitled_async);
|
||||
v[10] = reinterpret_cast<const void*>(&store_entitled_result);
|
||||
v[20] = reinterpret_cast<const void*>(&store_pkg_lic_async);
|
||||
v[21] = reinterpret_cast<const void*>(&store_pkg_lic_result);
|
||||
v[28] = reinterpret_cast<const void*>(&store_game_lic_async);
|
||||
v[29] = reinterpret_cast<const void*>(&store_game_lic_result);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kStoreObj{kStoreVtbl.data(), &kStoreIid, "IXStore"};
|
||||
|
||||
const std::array<const void*, 80> kStoreDurablesVtbl = [] {
|
||||
auto v = make_default_vtbl<80>();
|
||||
v[71] = reinterpret_cast<const void*>(&store_dur_lic_async);
|
||||
v[72] = reinterpret_cast<const void*>(&store_dur_lic_result);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kStoreDurablesObj{kStoreDurablesVtbl.data(), &kStoreDurablesIid, "IXStoreDurables"};
|
||||
|
||||
// --- XGameUi ---
|
||||
|
||||
HRESULT WINAPI gameui_profile_async(void*, void* user, uint64_t xuid, void* async) {
|
||||
return XGameUiShowPlayerProfileCardAsync(user, xuid, async);
|
||||
}
|
||||
HRESULT WINAPI gameui_text_async(void*, const char* title, const char* desc, const char* def, uint32_t scope,
|
||||
uint32_t max_chars, void* async) {
|
||||
return XGameUiShowTextEntryAsync(title, desc, def, scope, max_chars, async);
|
||||
}
|
||||
|
||||
const std::array<const void*, 32> kGameUiVtbl = [] {
|
||||
auto v = make_default_vtbl<32>();
|
||||
v[7] = reinterpret_cast<const void*>(&gameui_profile_async);
|
||||
v[17] = reinterpret_cast<const void*>(&gameui_text_async);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kGameUiObj{kGameUiVtbl.data(), &kGameUiIid, "IXGameUi"};
|
||||
|
||||
// --- XNetworking ---
|
||||
|
||||
struct ConnectivityHint {
|
||||
uint32_t connectivity_level;
|
||||
uint32_t connectivity_cost;
|
||||
uint32_t iana_interface_type;
|
||||
bool network_initialized;
|
||||
bool approaching_data_limit;
|
||||
bool over_data_limit;
|
||||
bool roaming;
|
||||
};
|
||||
static_assert(sizeof(ConnectivityHint) == 16);
|
||||
|
||||
HRESULT WINAPI net_udp_port_async(void*, void* async) {
|
||||
return XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync(async);
|
||||
}
|
||||
HRESULT WINAPI net_sec_info_async(void*, const char* url, void* async) {
|
||||
return XNetworkingQuerySecurityInformationForUrlAsync(url, async);
|
||||
}
|
||||
HRESULT WINAPI net_get_connectivity_hint(void*, ConnectivityHint* hint) {
|
||||
if (!hint) return E_POINTER;
|
||||
// Offline profile: ConnectivityLevelHint::None (1), CostHint::Unrestricted (1).
|
||||
*hint = {1u, 1u, 6u, true, false, false, false};
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const std::array<const void*, 24> kNetworkingVtbl = [] {
|
||||
auto v = make_default_vtbl<24>();
|
||||
v[4] = reinterpret_cast<const void*>(&net_udp_port_async);
|
||||
v[8] = reinterpret_cast<const void*>(&net_sec_info_async);
|
||||
v[15] = reinterpret_cast<const void*>(&net_get_connectivity_hint);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kNetworkingObj{kNetworkingVtbl.data(), &kNetworkingIid, "IXNetworking"};
|
||||
|
||||
// --- XGame ---
|
||||
|
||||
HRESULT WINAPI game_get_xbox_title_id(void*, uint32_t* title_id) {
|
||||
if (!title_id) return E_POINTER;
|
||||
// Synthetic offline title ID for BetterXen runtime.
|
||||
*title_id = 0x42580001u;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const std::array<const void*, 8> kGameVtbl = [] {
|
||||
auto v = make_default_vtbl<8>();
|
||||
v[3] = reinterpret_cast<const void*>(&game_get_xbox_title_id);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kGameObj{kGameVtbl.data(), &kGameIid, "IXGame"};
|
||||
|
||||
// --- XGameSave / XPackage (#468) ---
|
||||
// Ids and inheritance from xodus-gaming/xgameruntime-docs commit
|
||||
// 7090008692569aa6081e30dfdd9de58237741e24.
|
||||
// IXGameSaveImpl uses the class id and lists 27 methods in slots 3-29.
|
||||
// IXGameSaveImpl2 adds 3 XGameSaveFiles methods in slots 30-32.
|
||||
// IXGameSaveImpl3 adds none.
|
||||
// IXPackageImpl lists 32 methods in slots 3-34.
|
||||
// IXPackageImpl2 adds 4 methods in slots 35-38.
|
||||
// IXPackageImpl3 adds 2 methods in slots 39-40.
|
||||
// IXPackageImpl4 adds XPackageGetPackageKind at slot 41.
|
||||
|
||||
constexpr GUID kGameSaveClsid = {0x704C3F58, 0xE629, 0x4CC2, {0xB1, 0x97, 0x30, 0x51, 0x1B, 0x99, 0x6F, 0xE2}};
|
||||
constexpr GUID kGameSaveIid2 = {0x704C3F58, 0xE629, 0x4CC2, {0xB1, 0x97, 0x30, 0x51, 0x1B, 0x99, 0x6E, 0xE2}};
|
||||
constexpr GUID kGameSaveIid3 = {0x1BFFF3AF, 0xF14A, 0x40A3, {0x8E, 0x35, 0x9A, 0xDA, 0x90, 0x65, 0x93, 0xF9}};
|
||||
constexpr GUID kPackageClsid = {0xAF406016, 0xE850, 0x4AA8, {0xA8, 0x8D, 0x2F, 0x3D, 0xCB, 0x9D, 0xAC, 0x7E}};
|
||||
constexpr GUID kPackageIid = {0x3720DE07, 0xE8E4, 0x44A3, {0xAD, 0x32, 0xB3, 0x59, 0xE8, 0xAD, 0xBE, 0x55}};
|
||||
constexpr GUID kPackageIid2 = {0xF92D8712, 0x2B27, 0x4D8A, {0xBF, 0x01, 0x11, 0xA6, 0xF8, 0xE3, 0xEB, 0x42}};
|
||||
constexpr GUID kPackageIid3 = {0xE2A4734B, 0x2F4A, 0x456D, {0xAA, 0x8F, 0xD0, 0x65, 0xE0, 0x4F, 0xB2, 0x09}};
|
||||
constexpr GUID kPackageIid4 = {0x0B9D556E, 0xAB70, 0x43F4, {0xBA, 0xA0, 0x99, 0x99, 0xAC, 0x4C, 0xB0, 0x40}};
|
||||
|
||||
HRESULT WINAPI game_save_query_interface(void* self, const GUID* riid, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!riid) return E_INVALIDARG;
|
||||
if (guid_eq(*riid, kIUnknown) || guid_eq(*riid, kGameSaveClsid) || guid_eq(*riid, kGameSaveIid2) ||
|
||||
guid_eq(*riid, kGameSaveIid3)) {
|
||||
*out = self;
|
||||
return S_OK;
|
||||
}
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
HRESULT WINAPI package_query_interface(void* self, const GUID* riid, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!riid) return E_INVALIDARG;
|
||||
if (guid_eq(*riid, kIUnknown) || guid_eq(*riid, kPackageIid) || guid_eq(*riid, kPackageIid2) ||
|
||||
guid_eq(*riid, kPackageIid3) || guid_eq(*riid, kPackageIid4)) {
|
||||
*out = self;
|
||||
return S_OK;
|
||||
}
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
#define BX_HR(fn, iface, slot, method) \
|
||||
HRESULT WINAPI fn(void*) { \
|
||||
BX_VTABLE_STUB_LOG(iface, static_cast<uint32_t>(slot), method); \
|
||||
return E_NOTIMPL; \
|
||||
}
|
||||
#define BX_VOID(fn, iface, slot, method) \
|
||||
void WINAPI fn(void*) { BX_VTABLE_STUB_LOG(iface, static_cast<uint32_t>(slot), method); }
|
||||
// Bool slots log and return false. The HRESULT bit pattern would look like true to a caller.
|
||||
#define BX_BOOL(fn, iface, slot, method) \
|
||||
bool WINAPI fn(void*) { \
|
||||
BX_VTABLE_STUB_LOG(iface, static_cast<uint32_t>(slot), method); \
|
||||
return false; \
|
||||
}
|
||||
|
||||
BX_HR(gs_quota, "IXGameSaveImpl", 7, "XGameSaveGetRemainingQuota")
|
||||
BX_HR(gs_quota_async, "IXGameSaveImpl", 8, "XGameSaveGetRemainingQuotaAsync")
|
||||
BX_HR(gs_quota_result, "IXGameSaveImpl", 9, "XGameSaveGetRemainingQuotaResult")
|
||||
BX_HR(gs_delete, "IXGameSaveImpl", 10, "XGameSaveDeleteContainer")
|
||||
BX_HR(gs_delete_async, "IXGameSaveImpl", 11, "XGameSaveDeleteContainerAsync")
|
||||
BX_HR(gs_delete_result, "IXGameSaveImpl", 12, "XGameSaveDeleteContainerResult")
|
||||
BX_HR(gs_container_info, "IXGameSaveImpl", 13, "XGameSaveGetContainerInfo")
|
||||
BX_HR(gs_enum_by_name, "IXGameSaveImpl", 15, "XGameSaveEnumerateContainerInfoByName")
|
||||
BX_HR(gs_enum_blobs, "IXGameSaveImpl", 18, "XGameSaveEnumerateBlobInfo")
|
||||
BX_HR(gs_enum_blobs_by_name, "IXGameSaveImpl", 19, "XGameSaveEnumerateBlobInfoByName")
|
||||
BX_HR(gs_blob_delete, "IXGameSaveImpl", 26, "XGameSaveSubmitBlobDelete")
|
||||
BX_HR(gs_files_folder_async, "IXGameSaveImpl2", 30, "XGameSaveFilesGetFolderWithUiAsync")
|
||||
BX_HR(gs_files_folder_result, "IXGameSaveImpl2", 31, "XGameSaveFilesGetFolderWithUiResult")
|
||||
BX_HR(gs_files_quota, "IXGameSaveImpl2", 32, "XGameSaveFilesGetRemainingQuota")
|
||||
|
||||
BX_HR(pk_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_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_reg_installed_2, "IXPackageImpl2", 36, "XPackageRegisterPackageInstalled")
|
||||
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*>(&create_installation_monitor);
|
||||
v[6] = reinterpret_cast<const void*>(&close_installation_monitor);
|
||||
v[7] = reinterpret_cast<const void*>(&get_installation_progress);
|
||||
v[8] = reinterpret_cast<const void*>(&update_installation_monitor);
|
||||
v[9] = reinterpret_cast<const void*>(®ister_installation_progress);
|
||||
v[10] = reinterpret_cast<const void*>(&unregister_installation_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*>(&enumerate_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*>(&enumerate_packages);
|
||||
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*>(&enumerate_packages);
|
||||
v[40] = reinterpret_cast<const void*>(&pk_reg_installed_3);
|
||||
v[41] = reinterpret_cast<const void*>(&get_package_kind);
|
||||
return v;
|
||||
}();
|
||||
ComSingleton kPackageObj{kPackageVtbl.data(), &kPackageIid4, "IXPackageImpl"};
|
||||
|
||||
struct PublicEntry {
|
||||
const GUID* clsid;
|
||||
const GUID* iid;
|
||||
ComSingleton* obj;
|
||||
};
|
||||
|
||||
const PublicEntry kPublicEntries[] = {
|
||||
{&kCoreGuid, &kCoreGuid, &kCoreObj},
|
||||
{&kFeatureGuid, &kFeatureGuid, &kFeatureObj},
|
||||
{&kSystemClsid, &kSystemIid, &kSystemObj},
|
||||
{&kAnalyticsGuid, &kAnalyticsGuid, &kAnalyticsObj},
|
||||
{&kDisplayClsid, &kDisplayIid, &kDisplayObj},
|
||||
{&kErrorGuid, &kErrorGuid, &kErrorObj},
|
||||
{&kPlsClsid, &kPlsIid, &kPlsObj},
|
||||
{&kUserClsid, &kUserClsid, &kUserObj},
|
||||
{&kUserClsid, &kUserGamertagIid, &kUserGamertagObj},
|
||||
{&kStoreClsid, &kStoreIid, &kStoreObj},
|
||||
{&kStoreClsid, &kStoreDurablesIid, &kStoreDurablesObj},
|
||||
{&kGameUiClsid, &kGameUiIid, &kGameUiObj},
|
||||
{&kNetworkingClsid, &kNetworkingIid, &kNetworkingObj},
|
||||
{&kGameClsid, &kGameIid, &kGameObj},
|
||||
{&kGameSaveClsid, &kGameSaveClsid, &kGameSaveObj},
|
||||
{&kGameSaveClsid, &kGameSaveIid2, &kGameSaveObj},
|
||||
{&kGameSaveClsid, &kGameSaveIid3, &kGameSaveObj},
|
||||
{&kPackageClsid, &kPackageIid, &kPackageObj},
|
||||
{&kPackageClsid, &kPackageIid2, &kPackageObj},
|
||||
{&kPackageClsid, &kPackageIid3, &kPackageObj},
|
||||
{&kPackageClsid, &kPackageIid4, &kPackageObj},
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
bool query_public_gdk_interface(const GUID* clsid, const GUID* iid, void** out, bool* clsid_known) {
|
||||
*clsid_known = false;
|
||||
for (const auto& entry : kPublicEntries) {
|
||||
if (guid_eq(*clsid, *entry.clsid)) {
|
||||
*clsid_known = true;
|
||||
if (guid_eq(*iid, *entry.iid) || guid_eq(*iid, kIUnknown)) {
|
||||
*out = entry.obj;
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "dispatch public_com=%s", entry.obj->name);
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "QueryApiImpl", detail);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
namespace bx::gdk {
|
||||
|
||||
// Dispatches public Microsoft PC GDK (Microsoft.GDK.Windows 2610.0.9661) COM IUnknown
|
||||
// interfaces queried through QueryApiImpl. Returns true when (clsid, iid) matched and
|
||||
// *out was populated, or sets *clsid_known=true when clsid matched but iid did not.
|
||||
bool query_public_gdk_interface(const GUID* clsid, const GUID* iid, void** out, bool* clsid_known);
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -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,459 @@
|
||||
/*
|
||||
* 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 and installation monitor.
|
||||
* - Installation monitors (XPackageCreateInstallationMonitor and the functions taking its
|
||||
* handle) accept only that identifier. The package is fully on local storage, so progress is
|
||||
* {1, 1, 1, launchable, completed} and never changes: a registered progress callback is
|
||||
* accepted, logged and never called. Handles share the mount table's lock and generation, so
|
||||
* a closed or stale handle is rejected and closing twice is harmless.
|
||||
* - XPackageEnumeratePackages reports this game for XPackageKind::Game in every scope (the
|
||||
* documented ThisOnly output is the calling game; offline there are no related or publisher
|
||||
* games), and no packages for Content or PublisherContent: none are installed offline.
|
||||
* - An executable path of MAX_PATH or more fails with ERROR_FILENAME_EXCED_RANGE.
|
||||
*/
|
||||
#include "bx_log.h"
|
||||
#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>
|
||||
#include <vector>
|
||||
|
||||
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 {
|
||||
|
||||
struct Monitor {
|
||||
uint32_t generation;
|
||||
std::vector<uint64_t> tokens;
|
||||
};
|
||||
// Guarded by mount_mutex, like the mount handles. Tag 5 in bits 40-43 keeps these handles apart
|
||||
// from mount handles (tag 4) and XGameSave handles.
|
||||
std::unordered_map<void*, Monitor> monitors;
|
||||
constexpr uintptr_t kMonitorTag = 5;
|
||||
uint64_t token_counter = 0;
|
||||
|
||||
// Caller holds mount_mutex.
|
||||
Monitor* find_monitor(void* handle, uint32_t generation) {
|
||||
const auto found = monitors.find(handle);
|
||||
if (found == monitors.end() || generation == 0 || found->second.generation != generation) return nullptr;
|
||||
return &found->second;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
HRESULT WINAPI create_installation_monitor(void*, const char* identifier, uint32_t, const void*, uint32_t, void*,
|
||||
void** monitor) {
|
||||
if (!monitor) return E_POINTER;
|
||||
*monitor = nullptr;
|
||||
if (!identifier) return E_INVALIDARG;
|
||||
const auto generation = active_runtime_generation();
|
||||
if (!generation) return kRuntimeNotInitialized;
|
||||
bool match = false;
|
||||
const auto hr = is_current_package(identifier, match);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (!match) return kNotFound;
|
||||
try {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
++handle_counter;
|
||||
void* handle = reinterpret_cast<void*>(kMonitorTag << 40 | (handle_counter & 0xFFFFFFFFFu) << 4);
|
||||
monitors.emplace(handle, Monitor{generation, {}});
|
||||
*monitor = handle;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageCreateInstallationMonitor",
|
||||
"monitor for the running package: fully installed, progress never changes (offline)");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
void WINAPI close_installation_monitor(void*, void* monitor) {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
monitors.erase(monitor); // an unknown or already closed handle is ignored
|
||||
}
|
||||
|
||||
void WINAPI get_installation_progress(void*, void* monitor, XPackageInstallationProgress* progress) {
|
||||
if (!progress) return;
|
||||
const auto generation = active_runtime_generation();
|
||||
std::lock_guard lock(mount_mutex);
|
||||
*progress = find_monitor(monitor, generation) ? XPackageInstallationProgress{1, 1, 1, true, true}
|
||||
: XPackageInstallationProgress{};
|
||||
}
|
||||
|
||||
bool WINAPI update_installation_monitor(void*, void*) {
|
||||
return false; // progress never changes offline
|
||||
}
|
||||
|
||||
HRESULT WINAPI register_installation_progress(void*, void* monitor, void*, void* callback, uint64_t* token) {
|
||||
if (!token) return E_POINTER;
|
||||
*token = 0;
|
||||
if (!callback) return E_INVALIDARG;
|
||||
const auto generation = active_runtime_generation();
|
||||
try {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
Monitor* open = find_monitor(monitor, generation);
|
||||
if (!open) return stale_handle_error(generation);
|
||||
*token = ++token_counter;
|
||||
open->tokens.push_back(*token);
|
||||
} catch (const std::bad_alloc&) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "token=%llu accepted; offline progress never changes, so the callback is never called",
|
||||
static_cast<unsigned long long>(*token));
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageRegisterInstallationProgressChanged", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
bool WINAPI unregister_installation_progress(void*, void* monitor, uint64_t token, bool) {
|
||||
const auto generation = active_runtime_generation();
|
||||
std::lock_guard lock(mount_mutex);
|
||||
Monitor* open = find_monitor(monitor, generation);
|
||||
if (!open) return false;
|
||||
for (auto it = open->tokens.begin(); it != open->tokens.end(); ++it) {
|
||||
if (*it == token) {
|
||||
open->tokens.erase(it);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct XVersionValue {
|
||||
uint16_t major, minor, build, revision;
|
||||
};
|
||||
struct XPackageDetails {
|
||||
const char* packageIdentifier;
|
||||
XVersionValue version;
|
||||
uint32_t kind;
|
||||
const char* displayName;
|
||||
const char* description;
|
||||
const char* publisher;
|
||||
const char* storeId;
|
||||
bool installing;
|
||||
uint32_t index;
|
||||
uint32_t count;
|
||||
bool ageRestricted;
|
||||
const char* titleId;
|
||||
};
|
||||
using EnumerationCallback = bool(CALLBACK*)(void* context, const XPackageDetails* details);
|
||||
constexpr uint32_t kKindGame = 0, kScopeThisPublisher = 2;
|
||||
|
||||
} // namespace
|
||||
|
||||
HRESULT WINAPI enumerate_packages(void*, uint32_t kind, uint32_t scope, void* context, void* callback) {
|
||||
if (!callback) return E_INVALIDARG;
|
||||
if (!active_runtime_generation()) return kRuntimeNotInitialized;
|
||||
if (kind > 2 || scope > kScopeThisPublisher) return E_INVALIDARG;
|
||||
char detail[128];
|
||||
if (kind != kKindGame) {
|
||||
std::snprintf(detail, sizeof(detail), "kind=%u scope=%u: no content packages installed (offline)", kind, scope);
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageEnumeratePackages", detail);
|
||||
return S_OK;
|
||||
}
|
||||
char id[kIdBytes];
|
||||
const auto hr = current_identifier(id);
|
||||
if (FAILED(hr)) return hr;
|
||||
const XPackageDetails details{id, {}, kKindGame, "", "", "", "", false, 0, 1, false, ""};
|
||||
std::snprintf(detail, sizeof(detail), "kind=%u scope=%u: reported the running game only (offline)", kind, scope);
|
||||
bx_log_emit(BX_LOG_INFO, "xgameruntime", "XPackageEnumeratePackages", detail);
|
||||
reinterpret_cast<EnumerationCallback>(callback)(context, &details);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
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();
|
||||
monitors.clear();
|
||||
}
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -0,0 +1,128 @@
|
||||
#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);
|
||||
|
||||
// Installation monitors and enumeration (package.cpp), served on IXPackageImpl slots 5-10 and
|
||||
// the XPackageEnumeratePackages slots. Layouts follow the documented XPackage structures.
|
||||
struct XPackageInstallationProgress {
|
||||
uint64_t totalBytes;
|
||||
uint64_t installedBytes;
|
||||
uint64_t launchBytes;
|
||||
bool launchable;
|
||||
bool completed;
|
||||
};
|
||||
HRESULT WINAPI create_installation_monitor(void* self, const char* identifier, uint32_t selector_count,
|
||||
const void* selectors, uint32_t interval_ms, void* queue, void** monitor);
|
||||
void WINAPI close_installation_monitor(void* self, void* monitor);
|
||||
void WINAPI get_installation_progress(void* self, void* monitor, XPackageInstallationProgress* progress);
|
||||
bool WINAPI update_installation_monitor(void* self, void* monitor);
|
||||
HRESULT WINAPI register_installation_progress(void* self, void* monitor, void* context, void* callback,
|
||||
uint64_t* token);
|
||||
bool WINAPI unregister_installation_progress(void* self, void* monitor, uint64_t token, bool wait);
|
||||
HRESULT WINAPI enumerate_packages(void* self, uint32_t kind, uint32_t scope, void* context, void* callback);
|
||||
|
||||
} // namespace bx::gdk
|
||||
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user