mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 21:01:12 +00:00
Compare commits
277
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23d631e3c7 | ||
|
|
64f9b1dcb5 | ||
|
|
740df46b10 | ||
|
|
a648cdecc7 | ||
|
|
911c27f62b | ||
|
|
9b9c3c63ee | ||
|
|
b16bdc1d4a | ||
|
|
21700c2869 | ||
|
|
77af218878 | ||
|
|
da82407073 | ||
|
|
2e55cf2259 | ||
|
|
4cb858e6f5 | ||
|
|
b36e397681 | ||
|
|
5bc4ff5cf4 | ||
|
|
5e204bd883 | ||
|
|
6db66dc4a4 | ||
|
|
5c2e2c9b63 | ||
|
|
77dd9ffef3 | ||
|
|
abecde1c39 | ||
|
|
e532fc56ba | ||
|
|
ef58b18147 | ||
|
|
2deada1f9d | ||
|
|
65eef5b08e | ||
|
|
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 | ||
|
|
e57046a17d | ||
|
|
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 | ||
|
|
981bd3c64e | ||
|
|
63b5f5dac6 | ||
|
|
6484cb70a3 | ||
|
|
87da1752ad | ||
|
|
1bc42fcaec | ||
|
|
25ceb05230 | ||
|
|
2bc97a4f68 | ||
|
|
f2efeaf79d | ||
|
|
ab81b0beca | ||
|
|
b16797f576 | ||
|
|
3409bf4ec0 | ||
|
|
420c2329b7 | ||
|
|
ae869522ce | ||
|
|
6e3ef5459b | ||
|
|
bec15f43b6 | ||
|
|
7dde71e2fd | ||
|
|
33d439f828 | ||
|
|
a27284ab26 | ||
|
|
311f4124fa | ||
|
|
46a6a4baca | ||
|
|
8245c30b56 | ||
|
|
be647332cb | ||
|
|
fbd2f8cf43 | ||
|
|
6a1451b265 | ||
|
|
c64534fb21 | ||
|
|
b096424f33 | ||
|
|
f2af367da6 |
No files matched your search
@@ -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,46 +4,87 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
|
||||
|
||||
---
|
||||
|
||||
## 0. Contributor & Agent Task Dispatch (Onboarding & Priority Order)
|
||||
## 0. What to Do When Told "Work"
|
||||
|
||||
Whenever a user points their agent at BetterXen to contribute, get started, or pick work (even with a short prompt like *"help me contribute"* or *"what should we work on?"*), walk through preflight and then select work in the **strict 3-tier priority order** below:
|
||||
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. **Select work in strict priority order:**
|
||||
- **Priority 1 (Highest) — Handle your own claimed PRs with requested changes or review feedback:**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,reviews,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
Inspect comments and reviews (`gh pr view <pr> --repo MacosPorters/betterxen --comments` and `gh api repos/MacosPorters/betterxen/pulls/<pr>/comments`). If any of the user's open/claimed PRs has `CHANGES_REQUESTED`, unresolved reviewer feedback, failing CI, or merge conflicts, **address that PR first before starting new work**: check out the PR branch, resolve every review item, re-run Section 8 checks, push the DCO-signed update (with the user's authorization, per Section 7), and summarize how each comment was addressed.
|
||||
- **Priority 2 — Pick an unclaimed open issue:**
|
||||
If Priority 1 is clear, query open issues (preferring `status: ready` in the active milestone, then other actionable open issues):
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
|
||||
gh issue list --repo MacosPorters/betterxen --state open --json number,title,labels,assignees
|
||||
```
|
||||
Inspect comments and open PRs on candidate issues to filter out any issue with an active claim (< 7 days old) or open PR. Present the unclaimed options in plain English (recommending 1–2 good matches) and confirm with the user before coding.
|
||||
- **Priority 3 — Review & independently verify open PRs needing review:**
|
||||
When Priority 1 is clear and no unclaimed open issues remain (or the user asks to help unblock the queue), query open non-draft PRs by other contributors that still need review/verification:
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,headRefName,reviewDecision,isDraft
|
||||
```
|
||||
Fetch a candidate PR (`reviewDecision` empty or `REVIEW_REQUIRED`) into an isolated worktree, independently verify its contract and implementation per Section 5, run the Section 8 checks locally (including live CrossOver / D3DMetal runs where available), and draft an honest evidence-backed review for user approval before posting.
|
||||
3. **Claim & isolate (for Priority 2 issue work):**
|
||||
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
|
||||
4. **Implement strictly in scope:**
|
||||
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
|
||||
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
|
||||
5. **Verify locally (including hosts without CrossOver):**
|
||||
- Run every command in Section 8 and fix all warnings/failures before stopping.
|
||||
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (cross-compiling the 16 mingw-w64 C++ shim DLLs, building the Rust `bx_shader_bridge.dll` with `cargo`, and verifying the exact exports of all 17 PE32+ DLLs), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
|
||||
6. **Review & submit PR:**
|
||||
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
|
||||
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
|
||||
**"Work" authorizes, for the one item you pick:** opening a draft pull request, posting a review, committing with DCO sign-off, and pushing a branch. 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: make the machine ready yourself
|
||||
|
||||
```sh
|
||||
cargo build --locked -p bx-cli && target/debug/bx-cli preflight
|
||||
```
|
||||
|
||||
`bx-cli preflight` must print `Ready to work.` It requires **all** of:
|
||||
|
||||
| Required | How it is found |
|
||||
| --- | --- |
|
||||
| An Apple Silicon Mac with CrossOver 26.3+, D3DMetal and `mingw-w64` | Checked on the host |
|
||||
| **The project-authorized target build** | Found and saved by `bx-cli setup --find` |
|
||||
| **The GDK** (headers and compilers, under the project's authorization) | Found and saved by `bx-cli setup --find` |
|
||||
| At least 10 GiB of free disk space | Measured |
|
||||
|
||||
**If preflight fails, fix it yourself and run it again.** Your person said "work"; do not hand the setup back to them.
|
||||
|
||||
| `MISSING` line | What you do |
|
||||
| --- | --- |
|
||||
| Target build, GDK | `target/debug/bx-cli setup --find`. It searches the home folder, recognises the GDK by its header and the build by its structure (never by name), and saves both. |
|
||||
| `mingw-w64 g++` (also `cmake`, `gh`) | `brew install mingw-w64 cmake gh`. Being told to "work" authorizes installing these three. |
|
||||
| Free disk space | Remove your own scratch: build folders and scratch bottles of worktrees you created. Never another session's files. |
|
||||
|
||||
**Stop only for what an agent cannot supply**, and say exactly which:
|
||||
|
||||
- the host is not an Apple Silicon Mac;
|
||||
- CrossOver is not installed (it is licensed software; do not install it);
|
||||
- `setup --find` reports that the target build or the GDK is not on this machine, or found more than one distinct build (which build to use is your person's choice: they run `bx-cli setup --target-exe <path>` once).
|
||||
|
||||
In those cases do not work around it: no fixes, tests or reviews "for someone else to verify". Work here is found by running the target build and checked against the GDK; an agent without them is guessing.
|
||||
|
||||
Also check `git`, `gh` (`gh auth status`; if not logged in, ask the user to run `gh auth login`), `cargo`, `cmake` and `python3`; verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`); sync with `origin/main`. Work in your own worktree and your own bottle; never use a bottle another session is using.
|
||||
|
||||
`bx-cli setup` remembers the two locations in `~/.config/betterxen/local.conf`, outside every checkout, so it happens once per machine and works in every worktree, shell and agent session. (`BX_TARGET_EXE` and `BX_GDK_ROOT` override it for one command.) Never commit those paths, and never put a path, file name, hash or byte from the target build or the GDK into a commit, issue or pull request (Section 6).
|
||||
|
||||
### Step 2 — Pick exactly one thing, in this order
|
||||
|
||||
Take the first that applies.
|
||||
|
||||
1. **Your person's pull requests that need attention.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,isDraft,reviewDecision,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
Requested changes, unresolved review comments, failing checks, conflicts, or a draft you opened and have not finished: do that. 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 **twice in a row**, confirm the test fails without the fix, and post an approval or a change request with what you ran. If it is approved, green and not your person's, merge it (Section 7).
|
||||
|
||||
3. **A handoff issue of the current stage.**
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label handoff --label "stage: <current>" --json number,title,labels
|
||||
```
|
||||
A handoff is something a collaborator found and could not finish. The current stage is named on the pinned issue labelled `ladder`. Take the lowest-numbered one that no open pull request mentions, and follow Step 3.
|
||||
|
||||
4. **Run the target build and fix the first thing it stops on.** Run it under the [run protocol](docs/process/working-method.md#run-protocol) and read `bx-cli report`. Take the first signature in the report that no open pull request is titled with or mentions, and follow Step 3. A blocker you can see and fix needs **no issue**: the pull request is the record.
|
||||
|
||||
5. **The run stops on nothing.** Make the stage's gate check (ten runs). If it passes, post the result on the ladder issue and label it `needs-human`; a person confirms the stage change. Then stop.
|
||||
|
||||
**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 with a draft pull request, before writing the fix.** Branch `track-<a..f>/<slug>` from `origin/main`, push it with an empty commit or the first small change, and open a **draft** pull request titled `[<Stage>] <signature>`. Before opening it, list open pull requests once more; if one now covers the signature, take the next signature instead. A draft with no push for 3 days may be taken over; say so on it.
|
||||
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. Check the contract against the GDK where the GDK covers it.
|
||||
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 and passes twice in a row. The test is what holds on every machine; your run is only why you looked.
|
||||
5. **Verify:** every command in Section 8.
|
||||
6. **Proof:** runs before and after on your machine, every run reported, with the machine and the `main` commit. Another collaborator's machine may never take the path yours took; say which path your runs took.
|
||||
7. **Finish:** fill in the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof), sign off, no AI trailers, mark the pull request ready. Do not wait for CI before moving on.
|
||||
8. **Stop.** The next "work" starts again at Step 2.
|
||||
|
||||
**If you cannot fix what you found** (too large, out of session, or it needs a decision): close your draft, file one **handoff issue** labelled `handoff` and `stage: <name>`, titled `[handoff] <signature>`, with what you saw, what you tried and what is still unknown. That is the only time a blocker gets an issue.
|
||||
|
||||
---
|
||||
|
||||
@@ -93,9 +134,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 (code, data, documentation, or observations) derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds (including VIctory, PE-Vulkan, KyTx, AnyPS5, and similar efforts) are never adopted as code, shader, asset, or tooling sources without a recorded per-file provenance and license audit. Game-specific patches, asset-specific workarounds, and decryption-related code are never adopted; general Xbox Game OS, Direct3D, DirectStorage, and runtime ABI contracts established from project-authorized builds that meet every Section 6 condition are in-scope compatibility work.
|
||||
_Reserved — policy migration in progress._
|
||||
|
||||
---
|
||||
|
||||
@@ -112,30 +151,32 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
|
||||
## 6. Compatibility Evidence & Legal Boundaries
|
||||
|
||||
- **Authorized compatibility evidence:** Contributors and agents may use publicly accessible documentation, publicly licensed software, synthetic workloads, and **project-authorized target builds** (via local call-site inspection and runtime diagnostics) to establish undocumented Xbox OS, graphics, memory, storage, and runtime ABI contracts (struct layouts, flags, COM IIDs, vtable slot orders, and expected return/error semantics). Separate direct observations from inferences and verify every implemented contract with a synthetic conformance test under `tests/conformance/`. Such a test shows that a shim matches the recorded inference, not that the inference is correct.
|
||||
- **Conditions for target builds:** A build is project-authorized only when a maintainer has approved it for compatibility research **and all** of the following hold. Approval is an additional condition, never a substitute: it cannot grant access or license rights that the project does not hold.
|
||||
- The person inspecting it obtained it lawfully.
|
||||
- Its license terms and applicable law permit the inspection performed.
|
||||
- It is not leaked, stolen, confidential, or otherwise distributed without authorization, and neither are the tools used on it.
|
||||
- Inspecting it requires no decryption and no circumvention of security, DRM, licensing, or activation controls.
|
||||
|
||||
If any condition is unknown, do not use the build. State in the PR which contracts come from target-build observation, without naming the title or build.
|
||||
- **Never obtain or use** leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or unauthorized game builds and shader collections. Maintainer approval does not change this.
|
||||
- **Repository & clean-tree boundary:** Never commit or paste proprietary executables, SDKs, confidential vendor documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, proprietary shaders, raw caller memory dumps, executable contents/addresses, private traces, proprietary file names or hashes, personal paths, or secrets into the repository, its Git history, commit messages, issues, or PR descriptions.
|
||||
- **Legal boundary (`docs/legal.md`):** BetterXen does not circumvent console security or DRM and does not load encrypted or protected content. Validate technical compatibility and safety of user-provided files; do not ask for ownership receipts, accounts, or acquisition provenance as part of file loading.
|
||||
|
||||
---
|
||||
|
||||
## 7. Claiming, Git Safety & Changelog
|
||||
|
||||
1. **Check before coding (open backlog issues):** When picking an unclaimed backlog issue, read every comment and check open PRs so you never claim over an active claim; reply `Claiming — branch: track-<a..f>/<issue>-<slug>` (stale after 7 days without commits/PR). Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
|
||||
1. **Check before coding (claims):** A blocker is claimed by an open draft pull request titled with its signature (Section 0, Step 3); check open pull requests before opening yours. A draft with no push for 3 days may be taken over. 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
|
||||
git worktree add ../wt-<slug> -b track-<a..f>/<slug> origin/main
|
||||
```
|
||||
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
|
||||
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user; never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## 8. Verification Commands (Run Before Every Handoff / PR)
|
||||
@@ -175,5 +216,5 @@ These rules apply to every coding agent, whatever its model, vendor or plan. Sav
|
||||
- **Verify without redundancy:** Use targeted checks while iterating and for small changes. This does not replace Section 8 or required CI. Do not repeat builds, tests or CI runs when nothing relevant has changed, and do not poll workflows repeatedly.
|
||||
- **Communicate concisely:** Report outcomes, blockers and what is needed next; skip lengthy status reports and repeated summaries.
|
||||
- **Blocked work:** Do not re-review an unchanged PR that is waiting on an unresolved external blocker.
|
||||
- **Finish authorized work:** Carry an authorized task through to completion, including a merge that is authorized and meets every required approval and check, instead of stopping at intermediate reports. This grants no permission beyond Section 7.
|
||||
- **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.
|
||||
+186
-1
@@ -9,16 +9,178 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- **A collaborator only has to say "work"** (AGENTS.md §0, step 1). When `bx-cli preflight` fails, the agent makes the machine ready itself: the new `bx-cli setup --find` searches the home folder, recognises the GDK by its header and the target build by its structure (a large PE32+ file that imports `d3d12_xs.dll`; never by name), ignores the GDK's own tools, treats byte-identical copies as one build and keeps the copy with its imported DLLs beside it, and saves both settings. The agent may install `mingw-w64`, `cmake` and `gh` with Homebrew and free disk space by removing its own scratch. It stops only for what it cannot supply: no Apple Silicon Mac, no CrossOver, the build or the GDK not on the machine, or more than one distinct build.
|
||||
- **Working rules: the pull request is the unit of work, and the target build and the GDK are required** (AGENTS.md §0, [working method](docs/process/working-method.md)). An agent told to "work" first runs the new `bx-cli preflight`, which fails unless the host is an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`, the target build's executable and the GDK folder are known, and 10 GiB of disk is free. A collaborator records the two locations once with the new `bx-cli setup --target-exe <path> --gdk-root <folder>`, which checks them and keeps them in `~/.config/betterxen/local.conf`, outside the repository (`BX_TARGET_EXE` and `BX_GDK_ROOT` override it). If preflight fails the agent stops and does no work. A blocker the agent can fix no longer gets an issue: it is claimed by a draft pull request titled with its run-report signature. Issues are kept for handoffs (label `handoff`), decisions for a person, and the ladder status. Claims by comment and the 7-day stale window are gone; an idle draft may be taken over after 3 days.
|
||||
- **BetterXen is no longer a clean-room project** (repository owner's decision, #650). `CONTRIBUTING.md` now says that material the project is authorized to use, such as the GDK and its compilers, may be used and that facts derived from it may be committed, while the material and its outputs are never committed. Leaked or unauthorized material remains forbidden.
|
||||
- **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
|
||||
- Shader corpus, Phase 0 of the console shader translator (#649). `shader-transpiler/corpus/hlsl/` holds eight BetterXen-authored compute kernels covering integer and float ALU, divergent branches, loops, groupshared memory, wave operations, atomics and system values. `scripts/shader-corpus/build.sh` compiles each one locally with the console `xdxc` (a title-style container: `DXIL` plus `ACCC`/`FSPX`), the console PIX compiler (Microsoft's ISA listing) and the public PC DXC (DXIL for a D3DMetal reference run). `extract_code.py` then takes the code from the `FSPX` kind-6 section, skips the leading `v_nop_xbox_data` words and disassembles it with LLVM's public `gfx1030` decoder. All eight kernels build and decode cleanly. The extractor has nine unit tests on synthetic containers that need no GDK. Compiler outputs stay in the git-ignored `target/shader-corpus/`. One open question is recorded: a `v_cmp_class_f16` in the `wave` kernel's ballot sequence.
|
||||
- `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
|
||||
- `bx_runtime_veh.dll` completes a `CLZERO` loop in one exception (#665). A title that zeroes memory with `clzero; add rax,0x40; cmp rax,<reg64>; jb` raised one illegal-instruction exception per 64 bytes under Rosetta 2, which stalled a project-authorized target build's frame loop for tens of seconds. When the trapped `CLZERO` is followed by exactly that form, the handler zeroes every remaining line below the limit and leaves `RAX` at the last one, so the title's own `add`/`cmp`/`jb` leaves the loop. The range is zeroed region by region and stops at memory that is not committed and writable, where the next `CLZERO` traps and faults as before. Other loop forms keep the per-instruction path. `test_veh_clzero_loop` checks the memory result and counts the exceptions; it fails on the old handler.
|
||||
- `d3d12_xs.dll` no longer turns `DeserializeGraphicsPipelineStateX`, `DeserializeComputePipelineStateX`, `CreateDerivedGraphicsPipelineStateX` or `CreateDerivedComputePipelineStateX` into null pipelines in null-render mode (`BX_NULL_RENDER=1`) (#669). All four calls now always return `E_NOTIMPL`, clear `*ppv` and log `pipeline_refused` without `; null pipeline returned`, so a title falls back to creating pipelines from shader containers instead of silently receiving null pipelines. `test_d3d12_serialized_pipelines` checks all four slots and their refusal log lines with `BX_NULL_RENDER=1` active alongside a control shader-container null pipeline.
|
||||
- `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 included:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source. Provenance is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
|
||||
- **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.
|
||||
@@ -66,6 +228,11 @@ remains unsupported.
|
||||
- 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.
|
||||
@@ -104,11 +271,15 @@ 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.
|
||||
@@ -142,7 +313,21 @@ 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).
|
||||
|
||||
+11
-2
@@ -31,10 +31,10 @@ python3 scripts/audit/docs_hygiene.py
|
||||
|
||||
Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/skip counts. Never report a skipped test or unavailable tool as a pass.
|
||||
|
||||
## Clean-Room, Licensing & Provenance Policy
|
||||
## Licensing & Provenance Policy
|
||||
|
||||
- Use publicly accessible specifications, publicly licensed software, independently authored synthetic workloads, and project-authorized target builds only under every condition in [AGENTS.md](AGENTS.md) §6 (maintainer approval alone is not enough). Never obtain or use leaked or unauthorized material, and never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
|
||||
- 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.
|
||||
- BetterXen is **not** a clean-room project (repository owner's decision, 2026-11-29, #650). Material the project is authorized to use, such as the Microsoft GDK and its compilers under the project's authorization, may be used by contributors, and facts derived from it (layouts, slot orders, flag values, binary conventions) may be committed. The material itself, and its outputs, are never committed. **Leaked or unauthorized material is still forbidden:** anyone who has used it for this work must not contribute what they learned from it. 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).
|
||||
- Never claim Xbox hardware verification (BetterXen has no Xbox hardware access) or independent certification of your own work; classify evidence per [docs/claims.toml](docs/claims.toml).
|
||||
@@ -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).
|
||||
@@ -23,7 +23,7 @@ BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Ro
|
||||
- **Shader pipeline** (`shader-transpiler/`, Rust) for classifying `DXBC` containers (`DXIL` vs. `ACCC`/`FSPX` RDNA 2 machine code) and handling console shader translation where required.
|
||||
|
||||
> [!CAUTION]
|
||||
> **Clean-room and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
|
||||
> **Provenance and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
|
||||
|
||||
---
|
||||
|
||||
@@ -211,7 +211,9 @@ See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architectu
|
||||
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
|
||||
- All 17 x86-64 PE32+ shim DLLs — the 16 mingw-w64 C++ shims plus the Rust-built `bx_shader_bridge.dll` — pass strict PE Export Directory verification (111 exact names, ordinals, forwarders, 0 extra exports) and carry zero dynamic MinGW runtime dependencies. `scripts/build-shims.sh` cross-compiles the 16 C++ shims with CMake/mingw-w64 and builds `bx_shader_bridge.dll` with `cargo` for `x86_64-pc-windows-gnu`.
|
||||
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
|
||||
- `test_shim_exports.exe` loads the 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine. It does **not** load `bx_shader_bridge.dll`; the Rust bridge is exercised by `test_shader_gate.exe` instead.
|
||||
- `test_shim_exports.exe` loads all 16 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.
|
||||
|
||||
@@ -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
|
||||
|
||||
+8
-3
@@ -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/`).
|
||||
@@ -16,21 +17,25 @@
|
||||
- [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.
|
||||
- [Shader Corpus](../shader-transpiler/corpus/README.md) — Phase 0 of the console shader translator: BetterXen-authored kernels built locally into console containers, Microsoft ISA listings and PC DXIL, with the derived `FSPX` code-section layout (#649).
|
||||
- [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).
|
||||
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, provenance policy, and DCO sign-off.
|
||||
- [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.
|
||||
@@ -38,8 +38,9 @@ The gate needs a classifier that guest pipeline creation actually reaches, plus
|
||||
| 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 |
|
||||
|
||||
No measurement of a title's shader corpus exists or is planned. BetterXen runs only original synthetic programs, so the DXIL vs. ACCC mix of real titles is unknown. Wherever the gate runs, its `shader_gate` records count it.
|
||||
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
|
||||
|
||||
@@ -57,19 +58,21 @@ Branch **D2** is deferred. It needs a documented, lawfully available description
|
||||
|
||||
Revisit this ADR in any of these cases:
|
||||
- an authorized public source for that format appears;
|
||||
- gate telemetry from a lawful workload shows ACCC-only containers in practice;
|
||||
- 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:**
|
||||
- **Stream PSOs:** `ID3D12Device2::CreatePipelineState` stream descriptions are still forwarded unparsed.
|
||||
- **Raw-buffer 64-bit atomics:** these cannot be flagged from `SFI0`; the DXIL bitcode would have to be read.
|
||||
- **Telemetry summary:** `bx-cli trace` now summarizes the gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list with its wave-width and 64-bit-atomic flags, and `shader_bridge_missing`. The summary only reflects records a run actually wrote; it adds no live run and no new compatibility claim.
|
||||
- **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 and public-source review.
|
||||
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.
|
||||
@@ -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."
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# Clean-room scope
|
||||
# Legal scope
|
||||
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, vendor documentation and tools the project is authorized to use (never committed; see [CONTRIBUTING](../CONTRIBUTING.md)), 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: Run, Fix, Pull Request
|
||||
|
||||
**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 the GDK, and who work by pointing a coding agent at this repository and saying **"work"**. This document 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?*
|
||||
|
||||
The short answer: run the build, fix the first thing it stops on, and open a pull request. The pull request is the unit of work. There are no meetings, no rotating roles and no backlog to interpret.
|
||||
|
||||
## What you must have
|
||||
|
||||
No agent works without all of these. `bx-cli preflight` checks them and fails if one is missing:
|
||||
|
||||
- an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`;
|
||||
- **the project-authorized target build**;
|
||||
- **the GDK**, headers and compilers, under the project's authorization;
|
||||
- at least 10 GiB of free disk space.
|
||||
|
||||
A collaborator only says "work". When preflight fails, the agent makes the machine ready itself: `bx-cli setup --find` searches the home folder, recognises the GDK by its header and the target build by its structure (never by name), and saves both in `~/.config/betterxen/local.conf`, outside the repository, where every worktree and agent session on that machine finds them. It installs missing build tools with Homebrew and frees disk space by removing its own scratch.
|
||||
|
||||
Work here is found by running the build and checked against the GDK. Without them an agent can only guess, and a guess that looks like a fix costs a reviewer more than it saves. An agent stops only for what it cannot supply: the host is not an Apple Silicon Mac, CrossOver is not installed, the build or the GDK is not on the machine, or more than one distinct build is (the choice is the collaborator's). Then it says exactly which, and does not write fixes, tests or reviews "for someone else to verify".
|
||||
|
||||
## 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 |
|
||||
| --- | --- |
|
||||
| A blocker someone is fixing | An open pull request titled with its signature (a draft while in progress) |
|
||||
| A blocker someone found and could not finish | A **handoff issue** (label `handoff`, plus `stage: <name>`) |
|
||||
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) |
|
||||
| What needs a person | Label `needs-human` |
|
||||
| Rules | AGENTS.md and this document, changed by pull request |
|
||||
|
||||
Nothing about status is kept in files in the repository: agents editing one status file would conflict all day.
|
||||
|
||||
### Why a blocker gets a pull request and not an issue
|
||||
|
||||
An agent that runs the build and sees what it stops on usually knows the fix a few minutes later. Writing an issue, claiming it and then opening a pull request that closes it is three steps where one does the job. And an issue of the form "the build stops at X" is a fact about one run on one machine: the build takes different start-up paths from run to run, so another collaborator may never see it.
|
||||
|
||||
What holds on every machine is the **test**: "the console does X for this call, and this test fails without the fix". The run is why you looked; the test is the proof.
|
||||
|
||||
So:
|
||||
|
||||
- **You can fix it:** open a draft pull request titled with the signature, before writing the fix. The draft is the claim.
|
||||
- **You cannot fix it** (too large, out of session, needs a decision): file one handoff issue with what you saw, what you tried and what is unknown.
|
||||
|
||||
### Signatures
|
||||
|
||||
A signature is the fixed string `bx-cli report` prints for something a run stopped on: `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll`, `exit status 5`. Pull requests and handoff issues are titled with it (`[Boot] unimplemented IXUser slot 3`), so searching open pull requests for a signature tells you whether someone is already on it.
|
||||
|
||||
## What an agent does when told "work"
|
||||
|
||||
AGENTS.md §0 has the binding version. In short, in strict order:
|
||||
|
||||
1. **Preflight.** `bx-cli preflight` must pass. If it does not, stop.
|
||||
2. **Your own pull requests first.** Requested changes, failing checks, conflicts, or a draft you have not finished.
|
||||
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. 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 a handoff issue** of the current stage that no pull request covers.
|
||||
5. **Then run the build** and fix the first thing it stops on that no open pull request covers.
|
||||
6. **If the run stops on nothing,** make the stage's ten-run gate check and post it on the ladder issue with `needs-human`.
|
||||
|
||||
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
|
||||
run → signature → draft pull request (the claim) → evidence → smallest fix + test → runs before and after → ready → someone else reviews and merges
|
||||
```
|
||||
|
||||
1. **Claim with a draft pull request.** Check open pull requests for the signature. If nobody has it, branch from `origin/main`, push, and open a draft titled `[<Stage>] <signature>`. A draft with no push for 3 days may be taken over.
|
||||
2. **Evidence before code.** Find what the build asked for and what it got: the run report, then the diagnostics (thread sampler, fault context, call trace). Check the contract against the GDK where the GDK covers it. Do not guess a fix.
|
||||
3. **Smallest fix.** Only what removes this blocker. A new cross-DLL export still goes through an `[ABI]` pull request first.
|
||||
4. **A test for the contract.** It fails without the fix and passes twice in a row in the same bottle.
|
||||
5. **Proof.** Runs before and after on your machine, every run reported. Say which start-up path your runs took: another machine may take a different one.
|
||||
6. **Mark it ready** with the five-part description. Then stop: the next "work" starts from the top of the list.
|
||||
|
||||
If the blocker turns out to be more than you can finish, close the draft and file a handoff issue.
|
||||
|
||||
### 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 pull requests and handoff 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 become pull requests (or handoff issues, when they cannot be fixed at once) 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.
|
||||
|
||||
## The first handoffs
|
||||
|
||||
When this method started, the first target-build runs had already found more than could be fixed at once. Those were filed as issues #664–#680. The ones that were only "a blocker with a fix on the way" close as their pull requests merge; the ones that remain open as handoffs are the larger pieces: the run tooling, the D3DMetal capability checks, the translator, the reference images and the record-and-replay tools.
|
||||
@@ -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.
|
||||
@@ -108,7 +108,7 @@ independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
|
||||
|
||||
| Check | Outcome |
|
||||
| --- | --- |
|
||||
| `device.shader_model` | 6.6 (the fixture skips with exit 77 below 6.6) |
|
||||
| `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) |
|
||||
@@ -118,6 +118,12 @@ independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
|
||||
| `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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
+89
-12
@@ -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
|
||||
|
||||
@@ -19,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; all 17 PE32+ DLLs (16 mingw-w64 C++ shims + the Rust `bx_shader_bridge.dll`) pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
|
||||
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime` + dynamic loader exports, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, supervised `bx-cli run`, ADR 0007, and combined synthetic integration boot fixture | All Wave 1 conformance binaries pass under CrossOver 26.3 + Rosetta 2; combined `test_integration_boot.exe` passes (19 pass, 2 ADR-0007 pending, 0 fail) | **Verified complete (Milestone #17, 16/16)** |
|
||||
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), placed resources over `xmem`, bridge `dxbc-accc` into Windows guests (`#445`), measure D3DMetal GPU limits (`#453`), and establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)**. Measured translator constraints: [D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | **In development (Milestone #18)** |
|
||||
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler, within the [measured D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) (`WaveSize(64)` and SM 6.6 64-bit atomics not run; bounded lock emulation) | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
|
||||
| **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.
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
+1117
-28
File diff suppressed because it is too large.
Load diff
@@ -433,6 +433,12 @@ where
|
||||
for (name, bytes, dst, result) in plan {
|
||||
if !matches!(result, Staged::Unchanged(_)) {
|
||||
let tmp = tmp_of(name);
|
||||
// Snapshot what the target holds now, before the rename, so a failed manifest
|
||||
// write can put the *old* bytes back (not the bytes just written).
|
||||
let previous: Option<Vec<u8>> = match result {
|
||||
Staged::Copied(_) => None,
|
||||
_ => fs::read(&dst).ok(),
|
||||
};
|
||||
let published = before_publish(name).and_then(|()| match result {
|
||||
// Nothing was there at step 1; refuse to replace whatever appeared since.
|
||||
Staged::Copied(_) => install_new(&tmp, &dst, &bytes).map_err(|e| {
|
||||
@@ -495,6 +501,19 @@ where
|
||||
let _ = fs::remove_file(&tmp);
|
||||
owned.insert(name.clone(), sha256_hex(&bytes));
|
||||
if let Err(e) = write_manifest(system32, &owned) {
|
||||
// The file is installed but the manifest on disk does not name it, so the
|
||||
// next run would call bx-cli's own copy foreign (#573). Roll the publish
|
||||
// back: a Copied file is removed, a Replaced one is restored from the bytes
|
||||
// it had before. The manifest is left exactly as it was, so the retry sees
|
||||
// the same state it would have seen had the publish never happened.
|
||||
match previous {
|
||||
None => {
|
||||
let _ = fs::remove_file(&dst);
|
||||
}
|
||||
Some(before) => {
|
||||
let _ = fs::write(&dst, before);
|
||||
}
|
||||
}
|
||||
discard(&pending);
|
||||
return Err(e);
|
||||
}
|
||||
@@ -875,6 +894,67 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_manifest_write_failure_leaves_no_unowned_file() {
|
||||
let (_t, shims, prefix) = setup("manifest");
|
||||
let sys = system32_dir(&prefix);
|
||||
// A directory where the manifest's temporary file has to go makes
|
||||
// `write_manifest` fail after the first shim has already been published.
|
||||
let obstacle = sys.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
|
||||
fs::create_dir(&obstacle).unwrap();
|
||||
let err = stage(&shims, &sys).unwrap_err();
|
||||
assert!(err.contains("cannot write"), "{err}");
|
||||
assert!(
|
||||
!sys.join("bx_runtime_veh.dll").exists(),
|
||||
"the published file was rolled back, so the retry is not refused as foreign"
|
||||
);
|
||||
assert!(!sys.join(MANIFEST_NAME).exists());
|
||||
// Only the obstacle itself is left: no staged copy, no temporary file.
|
||||
let entries: Vec<String> = fs::read_dir(&sys)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
entries,
|
||||
vec![obstacle.file_name().unwrap().to_string_lossy().into_owned()],
|
||||
"system32 holds nothing but the obstacle that failed the manifest write"
|
||||
);
|
||||
fs::remove_dir(&obstacle).unwrap();
|
||||
// The retry installs everything fresh; nothing is reported as foreign.
|
||||
let retry = stage(&shims, &sys).unwrap();
|
||||
assert!(
|
||||
retry.iter().all(|s| matches!(s, Staged::Copied(_))),
|
||||
"{retry:?}"
|
||||
);
|
||||
// And a shim rebuilt later refreshes bx-cli's own copy rather than failing.
|
||||
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
|
||||
let update = stage(&shims, &sys).unwrap();
|
||||
assert!(update.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_manifest_write_failure_restores_the_previous_bytes() {
|
||||
let (_t, shims, prefix) = setup("restore");
|
||||
let sys = system32_dir(&prefix);
|
||||
stage(&shims, &sys).unwrap();
|
||||
// Rebuild the shim, then make the manifest write fail after the rename.
|
||||
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
|
||||
let obstacle = sys.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
|
||||
fs::create_dir(&obstacle).unwrap();
|
||||
assert!(stage(&shims, &sys).is_err());
|
||||
assert_eq!(
|
||||
fs::read(sys.join("bx_runtime_veh.dll")).unwrap(),
|
||||
b"veh v1",
|
||||
"the replaced file must be restored to the bytes it had before the rename"
|
||||
);
|
||||
// The manifest still names the old copy, so the retry refreshes it rather than
|
||||
// calling it foreign.
|
||||
fs::remove_dir(&obstacle).unwrap();
|
||||
let retry = stage(&shims, &sys).unwrap();
|
||||
assert!(retry.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
|
||||
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_shims_reached_through_a_stub_prefix_count_as_visible() {
|
||||
let (t, shims, prefix) = setup("visible");
|
||||
|
||||
@@ -447,7 +447,7 @@ mod tests {
|
||||
std::fs::write(
|
||||
&server,
|
||||
format!(
|
||||
"#!/bin/sh\n/bin/ps -o pgid= -p $$ >> '{}'\n",
|
||||
"#!/bin/sh\n/usr/bin/perl -MPOSIX -e 'print getpgrp(), \"\\n\"' >> '{}'\n",
|
||||
seen.display()
|
||||
),
|
||||
)
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -18,16 +18,54 @@ pub struct TraceSummary {
|
||||
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)]
|
||||
@@ -147,6 +185,30 @@ pub struct UnhandledException {
|
||||
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> {
|
||||
let needle = format!("\"{key}\":\"");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
@@ -200,18 +262,77 @@ fn record_shader_gate(summary: &mut TraceSummary, detail: &str) {
|
||||
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));
|
||||
summary.shader_gaps.push(ShaderGap {
|
||||
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 {
|
||||
@@ -250,6 +371,17 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
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
|
||||
@@ -326,6 +458,39 @@ mod tests {
|
||||
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#"
|
||||
@@ -569,4 +734,179 @@ mod tests {
|
||||
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()
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env bash
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Build the shader corpus (#649) locally. For every kernel in shader-transpiler/corpus/hlsl:
|
||||
# <name>.xs.cso / .xs.lst console container (DXIL + ACCC/FSPX) and listing, from xdxc
|
||||
# <name>.pix.lst console ISA listing with encodings, from the PIX compiler
|
||||
# <name>.pc.cso DXIL from the public PC DXC, for a D3DMetal reference run
|
||||
# <name>.code.bin / .aco.s console machine code extracted from the ACCC chunk, and its
|
||||
# llvm-mc gfx1030 disassembly
|
||||
# Outputs go to $OUT (default target/shader-corpus, which git ignores) and must not be
|
||||
# committed: they are compiler outputs from authorized GDK tools (see the corpus README).
|
||||
#
|
||||
# Required environment:
|
||||
# WINE a CrossOver/Wine loader that accepts --bottle (CrossOver's bin/wine)
|
||||
# BOTTLE a scratch bottle for the compilers (never a title's bottle)
|
||||
# XDXC the console xdxc.exe (GDK, xbox/bin/gen9)
|
||||
# PIX_DXC the console PIX dxc.exe (GDK, bin/Scarlett/pixsc)
|
||||
# DXC the PC dxc.exe from DXC release v1.9.2609
|
||||
# LLVM_MC llvm-mc built with the AMDGPU target
|
||||
set -euo pipefail
|
||||
|
||||
for var in WINE BOTTLE XDXC PIX_DXC DXC LLVM_MC; do
|
||||
if [ -z "${!var:-}" ]; then
|
||||
echo "error: set $var (see the header of $0)" >&2
|
||||
exit 2
|
||||
fi
|
||||
done
|
||||
|
||||
root=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
src="$root/shader-transpiler/corpus/hlsl"
|
||||
out=${OUT:-$root/target/shader-corpus}
|
||||
mkdir -p "$out"
|
||||
|
||||
# Wine takes Windows paths; Z: maps the host root.
|
||||
win() { printf 'Z:%s' "$1"; }
|
||||
compile() { WINEDEBUG=-all "$WINE" --bottle "$BOTTLE" "$@"; }
|
||||
|
||||
failures=0
|
||||
for hlsl in "$src"/*.hlsl; do
|
||||
name=$(basename "$hlsl" .hlsl)
|
||||
log="$out/$name.log"
|
||||
: > "$log"
|
||||
if ! compile "$XDXC" -T cs_6_6 -E main -Fo "$(win "$out/$name.xs.cso")" -Fc "$(win "$out/$name.xs.lst")" \
|
||||
"$(win "$hlsl")" >>"$log" 2>&1; then
|
||||
echo "FAIL $name: xdxc (see $log)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
if ! compile "$PIX_DXC" -T cs_6_6 -E main -Fc "$(win "$out/$name.pix.lst")" "$(win "$hlsl")" >>"$log" 2>&1; then
|
||||
echo "FAIL $name: PIX dxc (see $log)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
if ! compile "$DXC" -nologo -T cs_6_6 -E main -Fo "$(win "$out/$name.pc.cso")" "$(win "$hlsl")" >>"$log" 2>&1; then
|
||||
echo "FAIL $name: PC dxc (see $log)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
if ! python3 "$root/scripts/shader-corpus/extract_code.py" "$out/$name.xs.cso" \
|
||||
--bin "$out/$name.code.bin" --asm "$out/$name.aco.s" --llvm-mc "$LLVM_MC"; then
|
||||
echo "FAIL $name: code extraction or decode (see $out/$name.aco.s)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$failures" -ne 0 ]; then
|
||||
echo "FAIL: shader corpus ($failures kernel(s) failed)"
|
||||
exit 1
|
||||
fi
|
||||
# Sums of the compiled inputs, so two people with the compilers can confirm they hold the same
|
||||
# corpus (README, "Reproducibility"). Local only, like every other output.
|
||||
(cd "$out" && shasum -a 256 ./*.xs.cso ./*.pc.cso > SHA256SUMS)
|
||||
echo "PASS: shader corpus built in $out"
|
||||
@@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Extract the RDNA 2 code from a console-compiled DXBC container (#649).
|
||||
|
||||
The layout below was derived from containers the console compiler produced for BetterXen's own
|
||||
corpus kernels (shader-transpiler/corpus/README.md). Every assumption is checked; anything that
|
||||
does not match raises instead of guessing.
|
||||
|
||||
- DXBC: chunk count at byte 28, chunk offsets from byte 32; each chunk is a FourCC, a u32 size
|
||||
and the payload. The console code is in the `ACCC` chunk.
|
||||
- FSPX (the ACCC payload): a 16-byte header (magic `FSPX`, version, section count, total size),
|
||||
then one 16-byte entry per section: kind, offset, size, reserved (0). Offsets are relative to
|
||||
the start of the payload.
|
||||
- Section kind 6 holds the code. It starts with `v_nop_xbox_data` instructions that carry the
|
||||
shader hash, followed by gfx1030 machine code ending in `s_endpgm`. A `v_nop_xbox_data` is the
|
||||
public VOP3 `v_nop` opcode (top 16 bits of the first word 0xD580) whose third source operand is
|
||||
a 32-bit literal (operand value 255), which makes it 12 bytes; the public decoder rejects that
|
||||
form. A plain `v_nop` (8 bytes, no literal) is ordinary code and is not skipped.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
FSPX_MAGIC = b"FSPX"
|
||||
CODE_SECTION_KIND = 6
|
||||
XBOX_DATA_NOP_HIGH = 0xD580 # VOP3 v_nop, top 16 bits of the first word
|
||||
XBOX_DATA_NOP_BYTES = 12 # two VOP3 words and one 32-bit literal
|
||||
VOP3_SRC2_SHIFT = 18 # second word: src0 [8:0], src1 [17:9], src2 [26:18]
|
||||
VOP3_OPERAND_MASK = 0x1FF
|
||||
OPERAND_LITERAL = 255 # public gfx10 operand value for "a 32-bit literal follows"
|
||||
S_ENDPGM = 0xBF810000
|
||||
|
||||
|
||||
class LayoutError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def chunk(container, fourcc):
|
||||
if container[:4] != b"DXBC" or len(container) < 32:
|
||||
raise LayoutError("not a DXBC container")
|
||||
count = struct.unpack_from("<I", container, 28)[0]
|
||||
if 32 + 4 * count > len(container):
|
||||
raise LayoutError("chunk table overruns the container")
|
||||
for i in range(count):
|
||||
offset = struct.unpack_from("<I", container, 32 + 4 * i)[0]
|
||||
if offset + 8 > len(container):
|
||||
raise LayoutError(f"chunk {i} header overruns the container")
|
||||
size = struct.unpack_from("<I", container, offset + 4)[0]
|
||||
if container[offset:offset + 4] == fourcc:
|
||||
if offset + 8 + size > len(container):
|
||||
raise LayoutError(f"{fourcc.decode()} chunk overruns the container")
|
||||
return container[offset + 8:offset + 8 + size]
|
||||
raise LayoutError(f"no {fourcc.decode()} chunk")
|
||||
|
||||
|
||||
def sections(payload):
|
||||
if payload[:4] != FSPX_MAGIC or len(payload) < 16:
|
||||
raise LayoutError("ACCC payload does not start with FSPX")
|
||||
_version, count, total = struct.unpack_from("<III", payload, 4)
|
||||
if total != len(payload):
|
||||
raise LayoutError(f"FSPX total size {total} != payload size {len(payload)}")
|
||||
table_end = 16 + 16 * count
|
||||
if table_end > len(payload):
|
||||
raise LayoutError("FSPX section table overruns the payload")
|
||||
result = []
|
||||
for i in range(count):
|
||||
kind, offset, size, reserved = struct.unpack_from("<IIII", payload, 16 + 16 * i)
|
||||
if reserved != 0:
|
||||
raise LayoutError(f"FSPX section {i} reserved word is {reserved:#x}, not 0")
|
||||
if offset < table_end or offset + size > len(payload):
|
||||
raise LayoutError(f"FSPX section {i} [{offset}, {offset + size}) is out of bounds")
|
||||
result.append((kind, offset, size))
|
||||
return result
|
||||
|
||||
|
||||
def code_section(payload):
|
||||
matches = [(o, s) for k, o, s in sections(payload) if k == CODE_SECTION_KIND]
|
||||
if len(matches) != 1:
|
||||
raise LayoutError(f"expected one kind-{CODE_SECTION_KIND} section, found {len(matches)}")
|
||||
offset, size = matches[0]
|
||||
return payload[offset:offset + size]
|
||||
|
||||
|
||||
def is_xbox_data_nop(code):
|
||||
"""True when `code` starts with a v_nop whose third source operand is a literal."""
|
||||
if len(code) < XBOX_DATA_NOP_BYTES:
|
||||
return False
|
||||
first, second = struct.unpack_from("<II", code, 0)
|
||||
return (first >> 16 == XBOX_DATA_NOP_HIGH
|
||||
and (second >> VOP3_SRC2_SHIFT) & VOP3_OPERAND_MASK == OPERAND_LITERAL)
|
||||
|
||||
|
||||
def strip_xbox_data(code):
|
||||
"""Return (machine code, number of v_nop_xbox_data skipped)."""
|
||||
skipped = 0
|
||||
while is_xbox_data_nop(code):
|
||||
code = code[XBOX_DATA_NOP_BYTES:]
|
||||
skipped += 1
|
||||
return code, skipped
|
||||
|
||||
|
||||
def until_endpgm(code):
|
||||
"""Cut after the first dword-aligned s_endpgm. A literal that happens to equal it is not
|
||||
excluded here; the disassembler run is the authority on instruction boundaries."""
|
||||
for i in range(0, len(code) - 3, 4):
|
||||
if struct.unpack_from("<I", code, i)[0] == S_ENDPGM:
|
||||
return code[:i + 4]
|
||||
raise LayoutError("no s_endpgm in the code section")
|
||||
|
||||
|
||||
def extract(container):
|
||||
code, skipped = strip_xbox_data(code_section(chunk(container, b"ACCC")))
|
||||
return until_endpgm(code), skipped
|
||||
|
||||
|
||||
def disassemble(code, llvm_mc):
|
||||
text = " ".join(f"0x{b:02x}" for b in code)
|
||||
run = subprocess.run(
|
||||
[llvm_mc, "-arch=amdgcn", "-mcpu=gfx1030", "--disassemble", "-show-encoding"],
|
||||
input=text, capture_output=True, text=True, check=False,
|
||||
)
|
||||
lines = [ln.strip() for ln in run.stdout.splitlines() if ln.strip() and not ln.strip().startswith(".")]
|
||||
problems = [ln for ln in run.stderr.splitlines() if "invalid" in ln.lower() or "warning" in ln.lower()]
|
||||
return lines, problems
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("container", help="console-compiled .cso (DXBC with an ACCC chunk)")
|
||||
parser.add_argument("--bin", help="write the extracted machine code here")
|
||||
parser.add_argument("--asm", help="write the llvm-mc disassembly here (needs --llvm-mc)")
|
||||
parser.add_argument("--llvm-mc", help="path to llvm-mc with the AMDGPU target")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
code, skipped = extract(open(args.container, "rb").read())
|
||||
except LayoutError as error:
|
||||
print(f"error: {args.container}: {error}", file=sys.stderr)
|
||||
return 2
|
||||
if args.bin:
|
||||
open(args.bin, "wb").write(code)
|
||||
status = 0
|
||||
summary = f"{len(code)} code bytes, {skipped} v_nop_xbox_data skipped"
|
||||
if args.llvm_mc:
|
||||
lines, problems = disassemble(code, args.llvm_mc)
|
||||
summary += f", {len(lines)} instructions"
|
||||
if problems or not lines or "s_endpgm" not in lines[-1]:
|
||||
summary += ", DECODE PROBLEMS"
|
||||
status = 1
|
||||
if args.asm:
|
||||
open(args.asm, "w").write("\n".join(lines + problems) + "\n")
|
||||
print(f"{args.container}: {summary}")
|
||||
return status
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,106 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Unit tests for extract_code.py on synthetic containers (no GDK or compiler needed)."""
|
||||
|
||||
import importlib.util
|
||||
import struct
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
spec = importlib.util.spec_from_file_location("extract_code", Path(__file__).with_name("extract_code.py"))
|
||||
ec = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(ec)
|
||||
|
||||
S_NOP = struct.pack("<I", 0xBF800000) # public gfx10 encoding of s_nop 0
|
||||
S_ENDPGM = struct.pack("<I", 0xBF810000)
|
||||
# Synthetic, not compiler output: the v_nop opcode with made-up low bits, a second word whose
|
||||
# third source operand is 255 (literal) with made-up low bits, and a made-up literal.
|
||||
XBOX_DATA = struct.pack("<III", 0xD5801111, 0x03FC2222, 0x33333333)
|
||||
# The public VOP3 encoding of a plain `v_nop` (llvm-mc -mcpu=gfx1030): 8 bytes, no literal.
|
||||
V_NOP_E64 = struct.pack("<II", 0xD5800000, 0x02010080)
|
||||
|
||||
|
||||
def fspx(sections, total=None):
|
||||
"""sections: list of (kind, bytes). Builds an FSPX payload with the parsed layout."""
|
||||
count = len(sections)
|
||||
offset = 16 + 16 * count
|
||||
table, body = b"", b""
|
||||
for kind, data in sections:
|
||||
table += struct.pack("<IIII", kind, offset + len(body), len(data), 0)
|
||||
body += data
|
||||
size = 16 + len(table) + len(body)
|
||||
return b"FSPX" + struct.pack("<III", 1, count, size if total is None else total) + table + body
|
||||
|
||||
|
||||
def dxbc(chunks):
|
||||
"""chunks: list of (fourcc, bytes)."""
|
||||
header = 32 + 4 * len(chunks)
|
||||
offsets, body = [], b""
|
||||
for fourcc, data in chunks:
|
||||
offsets.append(header + len(body))
|
||||
body += fourcc + struct.pack("<I", len(data)) + data
|
||||
total = header + len(body)
|
||||
head = b"DXBC" + b"\0" * 16 + struct.pack("<III", 1, total, len(chunks))
|
||||
return head + b"".join(struct.pack("<I", o) for o in offsets) + body
|
||||
|
||||
|
||||
class ExtractTests(unittest.TestCase):
|
||||
def test_extracts_code_after_xbox_data_nops(self):
|
||||
code = XBOX_DATA * 3 + S_NOP + S_ENDPGM + b"\0" * 8
|
||||
container = dxbc([(b"DXIL", b"x" * 12), (b"ACCC", fspx([(0, b"a" * 28), (6, code), (7, b"b" * 8)]))])
|
||||
extracted, skipped = ec.extract(container)
|
||||
self.assertEqual(skipped, 3)
|
||||
self.assertEqual(extracted, S_NOP + S_ENDPGM)
|
||||
|
||||
def test_plain_v_nop_is_code_not_xbox_data(self):
|
||||
# A plain v_nop at the start of the code must not be skipped as 12 bytes, which would
|
||||
# misalign everything after it.
|
||||
code = V_NOP_E64 + S_NOP + S_ENDPGM
|
||||
container = dxbc([(b"ACCC", fspx([(6, code)]))])
|
||||
self.assertEqual(ec.extract(container), (code, 0))
|
||||
|
||||
def test_plain_v_nop_after_xbox_data_is_kept(self):
|
||||
code = XBOX_DATA * 2 + V_NOP_E64 + S_ENDPGM
|
||||
container = dxbc([(b"ACCC", fspx([(6, code)]))])
|
||||
self.assertEqual(ec.extract(container), (V_NOP_E64 + S_ENDPGM, 2))
|
||||
|
||||
def test_no_xbox_data_nops(self):
|
||||
container = dxbc([(b"ACCC", fspx([(6, S_NOP + S_ENDPGM)]))])
|
||||
self.assertEqual(ec.extract(container), (S_NOP + S_ENDPGM, 0))
|
||||
|
||||
def test_missing_accc(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "no ACCC chunk"):
|
||||
ec.extract(dxbc([(b"DXIL", b"x" * 4)]))
|
||||
|
||||
def test_not_fspx(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "does not start with FSPX"):
|
||||
ec.extract(dxbc([(b"ACCC", b"ABCD" + b"\0" * 12)]))
|
||||
|
||||
def test_total_size_mismatch(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "total size"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(6, S_ENDPGM)], total=999))]))
|
||||
|
||||
def test_section_inside_table_is_rejected(self):
|
||||
payload = bytearray(fspx([(6, S_ENDPGM)]))
|
||||
struct.pack_into("<I", payload, 16 + 4, 4) # section offset points into the header
|
||||
with self.assertRaisesRegex(ec.LayoutError, "out of bounds"):
|
||||
ec.extract(dxbc([(b"ACCC", bytes(payload))]))
|
||||
|
||||
def test_nonzero_reserved_word_is_rejected(self):
|
||||
payload = bytearray(fspx([(6, S_ENDPGM)]))
|
||||
struct.pack_into("<I", payload, 16 + 12, 1)
|
||||
with self.assertRaisesRegex(ec.LayoutError, "reserved word"):
|
||||
ec.extract(dxbc([(b"ACCC", bytes(payload))]))
|
||||
|
||||
def test_needs_exactly_one_code_section(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "found 0"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(0, S_ENDPGM)]))]))
|
||||
with self.assertRaisesRegex(ec.LayoutError, "found 2"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(6, S_ENDPGM), (6, S_ENDPGM)]))]))
|
||||
|
||||
def test_code_without_endpgm(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "no s_endpgm"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(6, S_NOP * 4)]))]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,110 @@
|
||||
# Shader corpus (Phase 0, #649)
|
||||
|
||||
A corpus of BetterXen-authored compute kernels compiled for the console, so the RDNA 2 shader
|
||||
translator ([ADR 0008](../../docs/adr/0008-m2-shader-format-gate.md), Branch D2) can be tested
|
||||
against inputs whose correct behaviour is known independently of the translator
|
||||
([AGENTS.md](../../AGENTS.md) §5).
|
||||
|
||||
For each kernel in [`hlsl/`](hlsl), three compilers produce:
|
||||
|
||||
- the **console container** a title would ship: DXBC with `DXIL` **and** an `ACCC` chunk whose
|
||||
payload is an `FSPX` package holding the RDNA 2 code;
|
||||
- **the console compiler's listing** of the RDNA 2 code for the same source, with encodings (compiler output, not
|
||||
Microsoft documentation);
|
||||
- **PC DXIL** from the public DXC, which runs on D3DMetal today and gives the reference result.
|
||||
|
||||
## What is committed and what is not
|
||||
|
||||
| Committed | Not committed |
|
||||
|---|---|
|
||||
| The HLSL kernels in `hlsl/` (original BetterXen code, GPL-3.0-or-later) | Every compiler output: containers, listings, extracted code and disassembly |
|
||||
| [`scripts/shader-corpus/build.sh`](../../scripts/shader-corpus/build.sh) and [`extract_code.py`](../../scripts/shader-corpus/extract_code.py) with its unit tests | The GDK, its compilers, and any file from it |
|
||||
| Layout facts derived from our own outputs (below) | |
|
||||
|
||||
The console compilers come from authorized GDK material and run on BetterXen's own HLSL only.
|
||||
Their outputs stay in `target/shader-corpus/` (git-ignored) and are never committed. Run the
|
||||
compilers in a scratch bottle, never in a title's bottle.
|
||||
|
||||
The layout facts below are derived from those outputs and **are** published in this file. On
|
||||
2026-11-29 the repository owner reported that the team had approved publishing them, and decided
|
||||
that BetterXen is no longer a clean-room project ([CONTRIBUTING](../../CONTRIBUTING.md), #650):
|
||||
contributors may use the GDK compilers and read this file. The compilers, their outputs and the
|
||||
GDK itself are still never committed.
|
||||
|
||||
## Reproducibility
|
||||
|
||||
The corpus can only be rebuilt by someone who has the GDK compilers. CI cannot rebuild it, and a
|
||||
contributor without the GDK cannot reproduce its inputs. That limits what the corpus proves: it
|
||||
checks a translator against shaders with known source, on the word of whoever built it.
|
||||
|
||||
To let two people with access confirm they hold the same inputs, `build.sh` writes
|
||||
`target/shader-corpus/SHA256SUMS` with the SHA-256 of every `.xs.cso` and `.pc.cso`. The sums are
|
||||
not listed here yet: they are worth committing only once two independent builds agree, which
|
||||
also shows whether the compilers' output is deterministic.
|
||||
|
||||
## Building
|
||||
|
||||
```sh
|
||||
WINE=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/bin/wine \
|
||||
BOTTLE=<scratch bottle> \
|
||||
XDXC=<GDK>/…/xbox/bin/gen9/xdxc.exe \
|
||||
PIX_DXC=<GDK>/…/bin/Scarlett/pixsc/dxc.exe \
|
||||
DXC=<DXC v1.9.2609>/bin/x64/dxc.exe \
|
||||
LLVM_MC=$(brew --prefix llvm)/bin/llvm-mc \
|
||||
scripts/shader-corpus/build.sh
|
||||
```
|
||||
|
||||
All eight kernels currently build, and every kernel's console code extracts and decodes with
|
||||
LLVM's public `gfx1030` disassembler (2026-11-28, Apple Silicon, CrossOver 26.3):
|
||||
|
||||
| Kernel | What it exercises | Console instructions |
|
||||
|---|---|---|
|
||||
| `fill` | integer ALU | 11 |
|
||||
| `branch` | divergent if/else | 17 |
|
||||
| `loop` | per-lane trip count, early exit | 60 |
|
||||
| `lds` | groupshared memory, barriers, tree reduction | 58 |
|
||||
| `wave` | `WaveActiveSum`, `WavePrefixSum`, `WaveReadLaneFirst`, `WaveActiveBallot` | 47 |
|
||||
| `atomic` | global `InterlockedAdd` / `InterlockedMax` with returned values | 57 |
|
||||
| `floatmath` | `mad`, `sqrt`, `rcp`, float/uint conversion | 22 |
|
||||
| `groupid` | 2D groups, `SV_GroupID`, `SV_GroupThreadID`, `SV_GroupIndex` | 17 |
|
||||
|
||||
`extract_code.py`'s unit tests use synthetic containers and need no GDK:
|
||||
`python3 -m unittest scripts/shader-corpus/test_extract_code.py`.
|
||||
|
||||
## Layout facts (derived from our own outputs)
|
||||
|
||||
- **Container:** `xdxc` keeps the `DXIL` chunk and adds `ACCC`. Title containers can be `ACCC`-only;
|
||||
the `ACCC` format is the same. `bx-cli shader` rejects these containers with the same `FSPX`
|
||||
error as a title's console-only shaders, so the corpus is a faithful stand-in for that format.
|
||||
- **`FSPX`:** a 16-byte header (magic `FSPX`, version `1`, section count, total size equal to the
|
||||
payload size), then one 16-byte entry per section: kind, offset from the start of the payload,
|
||||
size, and a reserved `0`. The corpus containers have four sections, of kinds 0, 1, 6 and 7.
|
||||
- **Code:** section kind 6. It starts with `v_nop_xbox_data` instructions that carry the shader
|
||||
hash: the public VOP3 `v_nop` opcode (top 16 bits `0xD580`) with a literal as its third source
|
||||
operand, 12 bytes each, a form the public decoder rejects. A plain `v_nop` (8 bytes) is ordinary
|
||||
code. Every corpus kernel has three `v_nop_xbox_data`. They are followed by `gfx1030` machine code ending in `s_endpgm`, then
|
||||
padding.
|
||||
- **Two console backends.** `xdxc`'s `ACCC` code comes from its ACO step; the PIX compiler's
|
||||
listing comes from its NewBE step. They generate different code for the same source (for example,
|
||||
the inline buffer descriptor's word 3 is `0x31016fac` from ACO and `0x11014fac` from NewBE). The
|
||||
NewBE listing documents the console ABI (#638); the ACO code is what `ACCC` containers carry.
|
||||
Both use the root UAV address in `s[4:5]` here.
|
||||
|
||||
## Observations so far
|
||||
|
||||
- `wave` compiles to the cross-lane instructions that matter for running 64-wide waves on 32-wide
|
||||
Apple GPUs: DPP `row_shr` and `quad_perm`, `v_permlanex16`, `v_readlane` and `v_readfirstlane`.
|
||||
- **Open question:** in `wave`, LLVM decodes one instruction in the ballot sequence as
|
||||
`v_cmp_class_f16` with literal `0x7c01`, although the kernel has no half-precision code. Either
|
||||
ACO genuinely emits it there, or the console gives that opcode a meaning the public `gfx1030`
|
||||
decoder does not know. The reference runs below should tell.
|
||||
|
||||
## Next steps
|
||||
|
||||
1. A reference runner: dispatch each kernel's PC DXIL on D3DMetal with fixed inputs and record
|
||||
the output buffers as expected results, plus CPU-computed expectations where the result is a
|
||||
pure function of the inputs.
|
||||
2. The decoder (Phase 1), checked instruction by instruction against LLVM's disassembly and the
|
||||
NewBE listings.
|
||||
3. More kernels as the decoder grows: textures and samplers, structured control flow with nested
|
||||
loops, 64-bit atomics, and wave32 versus wave64 variants.
|
||||
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Global atomics: add and max into shared counters, with returned old values.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint x = input[tid.x];
|
||||
uint before;
|
||||
InterlockedAdd(output[0], x, before);
|
||||
InterlockedMax(output[1], x);
|
||||
output[2u + tid.x] = before;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Divergent control flow: lanes take different sides of an if/else.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint x = input[tid.x];
|
||||
uint r;
|
||||
if ((x & 1u) != 0u) { r = x * 3u + 1u; } else { r = x >> 1; }
|
||||
output[tid.x] = r;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Integer ALU: multiply, shift, xor-add (no memory reads).
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint v = tid.x * 0x9e3779b1u;
|
||||
output[tid.x] = (v ^ (v >> 15)) + 0x01234567u;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Float ALU and conversions: fma, sqrt, rcp, float<->uint.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
float f = (float)input[tid.x] * asfloat(c0);
|
||||
float g = mad(f, 0.5f, 1.0f);
|
||||
float h = sqrt(abs(g)) + rcp(g + 2.0f);
|
||||
output[tid.x] = asuint(h) ^ (uint)floor(h * 256.0f);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// System values: group id, group thread id and flattened indices with a 2D group.
|
||||
[RootSignature(BX_RS)] [numthreads(8, 8, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID, uint3 gtid : SV_GroupThreadID, uint3 gid : SV_GroupID, uint gi : SV_GroupIndex) {
|
||||
uint idx = (gid.y * c0 + gid.x) * 64u + gi;
|
||||
output[idx] = (gtid.x << 24) | (gtid.y << 16) | (tid.x << 8) | tid.y;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Groupshared memory and barriers: a per-group tree reduction.
|
||||
groupshared uint scratch[64];
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID, uint3 gtid : SV_GroupThreadID, uint3 gid : SV_GroupID) {
|
||||
scratch[gtid.x] = input[tid.x];
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
for (uint s = 32u; s > 0u; s >>= 1) {
|
||||
if (gtid.x < s) { scratch[gtid.x] += scratch[gtid.x + s]; }
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
if (gtid.x == 0u) { output[gid.x] = scratch[0]; }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Loop with a per-lane, data-dependent trip count and an early exit.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint n = input[tid.x] % (c0 + 1u);
|
||||
uint acc = 0u;
|
||||
for (uint i = 0u; i < n; ++i) {
|
||||
acc += i * c1;
|
||||
if (acc > c2) { break; }
|
||||
}
|
||||
output[tid.x] = acc;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Cross-lane wave operations: the costly case when a 64-wide wave runs as two 32-wide halves.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint x = input[tid.x];
|
||||
uint sum = WaveActiveSum(x);
|
||||
uint prefix = WavePrefixSum(x);
|
||||
uint first = WaveReadLaneFirst(x);
|
||||
uint4 ballot = WaveActiveBallot((x & 1u) != 0u);
|
||||
output[tid.x * 4u + 0u] = sum;
|
||||
output[tid.x * 4u + 1u] = prefix;
|
||||
output[tid.x * 4u + 2u] = first;
|
||||
output[tid.x * 4u + 3u] = countbits(ballot.x) + countbits(ballot.y);
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -2,6 +2,15 @@
|
||||
|
||||
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:
|
||||
|
||||
@@ -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,8 +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"
|
||||
@@ -1,7 +1,10 @@
|
||||
#include "proxy.h"
|
||||
#include "vmem.h"
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
|
||||
/*
|
||||
@@ -20,6 +23,38 @@ HMODULE get_host_d3d12() {
|
||||
return mod;
|
||||
}
|
||||
|
||||
// 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, [] {
|
||||
@@ -33,17 +68,29 @@ void initialize_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;
|
||||
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();
|
||||
@@ -98,12 +145,40 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
|
||||
}
|
||||
char detail[256];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"host_device=%p highest_host_interface=ID3D12Device%d feature_level=11_0 params=%s (not interpreted) trace_d3d=%u",
|
||||
static_cast<void*>(proxy->h_ID3D12Device), highest, params ? "non-null" : "null", g_bx_trace_d3d);
|
||||
"host_device=%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;
|
||||
}
|
||||
|
||||
@@ -122,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,496 @@
|
||||
/*
|
||||
* 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);
|
||||
}
|
||||
|
||||
HRESULT refused_always_fail(HRESULT hr, const char* kind) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "%s pipeline refused hr=0x%08lx", kind, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_refused", detail);
|
||||
return hr;
|
||||
}
|
||||
|
||||
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 always fail with E_NOTIMPL and log
|
||||
* `pipeline_refused` — even in null-render mode — so a title falls back to creating its pipelines
|
||||
* from shader containers instead of receiving a null pipeline (#669).
|
||||
*/
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void*, const void*, REFIID,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeGraphicsPipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
return refused_always_fail(E_NOTIMPL, "deserialized graphics (console code)");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void*, const void*, REFIID,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeComputePipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
return refused_always_fail(E_NOTIMPL, "deserialized compute (console code)");
|
||||
}
|
||||
|
||||
/*
|
||||
* CreateDerived{Graphics,Compute}PipelineStateX: a pipeline equal to `source` with some state
|
||||
* groups replaced. Deriving from a host pipeline needs its creation description, which this layer
|
||||
* does not keep yet. Both calls always fail with E_NOTIMPL and log `pipeline_refused` — even in
|
||||
* null-render mode — so a title falls back to creating its pipelines from shader containers
|
||||
* instead of silently receiving null pipelines (#669).
|
||||
*/
|
||||
namespace {
|
||||
HRESULT derived(ID3D12PipelineState* source, 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_always_fail(E_NOTIMPL, kind);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void*, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDerivedGraphicsPipelineStateX");
|
||||
return derived(source, ppv, "derived graphics");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void*, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDerivedComputePipelineStateX");
|
||||
return derived(source, 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;
|
||||
}
|
||||
+179
-6
@@ -4,6 +4,10 @@
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#include "presentx.h"
|
||||
|
||||
#include "shader_gate.h"
|
||||
|
||||
@@ -429,6 +433,132 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreateComputePipelineState(const D3D12_
|
||||
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) {
|
||||
@@ -436,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;
|
||||
}
|
||||
@@ -525,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"
|
||||
@@ -117,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);
|
||||
@@ -385,7 +385,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreateCommittedResource2(const D3D12
|
||||
HRESULT STDMETHODCALLTYPE BxDeviceProxyGen::CreatePlacedResource1(ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6) {
|
||||
BX_D3D_TRACE("ID3D12Device8", "CreatePlacedResource1");
|
||||
if (!h_ID3D12Device8) { BX_VTABLE_STUB_LOG("ID3D12Device8", 70u, "CreatePlacedResource1"); return E_NOTIMPL; }
|
||||
return h_ID3D12Device8->CreatePlacedResource1(bx_unwrap(a0), a1, a2, a3, a4, a5, a6);
|
||||
return 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(bx_unwrap(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) {
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -149,13 +149,21 @@ 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) {
|
||||
const bool wide_wave = c.has_lanes && c.lanes_min > 32;
|
||||
return wide_wave || (c.flags & (kAtomic64Typed | kAtomic64GroupShared | kAtomic64Heap));
|
||||
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";
|
||||
@@ -254,6 +262,26 @@ HRESULT BxShaderGate::admit(const char* pso_kind, const char* stage, const D3D12
|
||||
++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];
|
||||
@@ -268,6 +296,13 @@ HRESULT BxShaderGate::admit(const char* pso_kind, const char* stage, const D3D12
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -24,7 +24,8 @@ public:
|
||||
* host gets: the bridge's prepared DXIL copy for DXIL and dual containers, or `in` unchanged
|
||||
* for legacy DXBC, unclassifiable input, or when the bridge is missing (logged once as
|
||||
* `shader_bridge_missing`). Returns E_NOTIMPL for an ACCC-only container, which has no
|
||||
* DXIL for D3DMetal until M3 Branch D2, with or without the bridge. Copies live until this
|
||||
* 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,
|
||||
|
||||
@@ -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,6 +44,16 @@ 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.
|
||||
@@ -117,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"', ""]
|
||||
|
||||
@@ -125,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}";']
|
||||
@@ -162,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(" ", "")
|
||||
@@ -180,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;",
|
||||
" /*",
|
||||
@@ -194,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()
|
||||
+412
-151
@@ -5,6 +5,7 @@
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
|
||||
/*
|
||||
@@ -30,11 +31,18 @@
|
||||
* vkd3d on CrossOver 26.2 faults on that pointer with or without this shim.
|
||||
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createheap
|
||||
*
|
||||
* CreatePlacedResource forwards the caller's parameters to the host.
|
||||
* On the backing heap the offset must be a multiple of the alignment
|
||||
* GetResourceAllocationInfo reports, the resource
|
||||
* must fit, and an upload or readback heap (not this CUSTOM heap) must use the
|
||||
* initial state Microsoft Learn requires:
|
||||
* CreatePlacedResource, CreatePlacedResource1 and CreatePlacedResource2 share one
|
||||
* path (create_placed_common) and check every heap, not only the backing heap,
|
||||
* before the host call: heap and desc are non-null, a buffer has no clear value,
|
||||
* the offset is a multiple of the alignment GetResourceAllocationInfo (or
|
||||
* GetResourceAllocationInfo2 for the DESC1 entry points) reports, and the
|
||||
* resource fits in the heap. CreatePlacedResource and CreatePlacedResource1 also
|
||||
* require the initial state Microsoft Learn gives for an upload or readback heap;
|
||||
* CreatePlacedResource2 takes a barrier layout, which is not checked. A failure
|
||||
* returns E_INVALIDARG with *out null and is logged. Research register A-7
|
||||
* recorded the host accepting an invalid placement, so this check is not left
|
||||
* to the host. A shim heap is unwrapped for the host call and retained by the
|
||||
* resource on all three paths:
|
||||
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-createplacedresource
|
||||
* https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device-getresourceallocationinfo
|
||||
* Heap alignment values 0, 64 KiB and 4 MiB, and ID3D12Heap1:
|
||||
@@ -52,6 +60,11 @@ constexpr GUID kPlacedResourceHeap = {0x3a652cbb, 0xb5b3, 0x4e09, {0xb3, 0x6c, 0
|
||||
|
||||
struct Record {
|
||||
bool configured = false;
|
||||
bool xbox_configured = false;
|
||||
uint32_t xbox_page_table_4mb_pages = 0;
|
||||
uint32_t xbox_frame_buffer_preserve_bytes = 0;
|
||||
/* D3D12ConfigureVirtualMemoryX fails with E_FAIL once a device exists. */
|
||||
bool device_created = false;
|
||||
bool backing_opt_in = false;
|
||||
bx_hardware_profile_t profile = BX_PROFILE_LOCKHART;
|
||||
uint64_t title_limit = 0;
|
||||
@@ -60,9 +73,10 @@ struct Record {
|
||||
uint64_t config_size = 0;
|
||||
uint64_t config_generation = 0;
|
||||
bx_xmem_region_info_t region{};
|
||||
/* Bytes of host heaps still alive. D3DMetal keeps freed memory in its own
|
||||
pool, so this counts live heaps only: charge on create, credit on the
|
||||
final Release. It does not assume the OS reclaimed the pages. */
|
||||
/* Diagnostic mirror of the external xmem charges for live host heaps.
|
||||
D3DMetal keeps freed memory in its own pool, so this counts live heaps
|
||||
only: charge on create, credit on the final Release. It does not assume
|
||||
the OS reclaimed the pages. xmem's external_bytes is authoritative. */
|
||||
uint64_t charged_private_bytes = 0;
|
||||
uint64_t cpu_pointer = 0;
|
||||
class BxChargedHeap* backing = nullptr;
|
||||
@@ -96,44 +110,43 @@ uint64_t title_limit() {
|
||||
return 8ull << 30;
|
||||
}
|
||||
|
||||
uint64_t active_cap(const bx_xmem_stats_t& stats) {
|
||||
uint64_t cap = title_limit();
|
||||
if (stats.title_limit_bytes != 0 && stats.title_limit_bytes < cap) {
|
||||
cap = stats.title_limit_bytes;
|
||||
}
|
||||
return cap;
|
||||
}
|
||||
|
||||
const char* profile_name(bx_hardware_profile_t profile) {
|
||||
return profile == BX_PROFILE_ANACONDA ? "anaconda" : "lockhart";
|
||||
}
|
||||
|
||||
/* Private host heaps count against the same Lockhart/Anaconda cap as xmem. */
|
||||
/* Private host heaps count against the same Lockhart/Anaconda cap as xmem.
|
||||
* xmem's external_bytes is the authoritative ledger: bx_xmem_try_charge_external
|
||||
* admits atomically under usage_lock, against every owner, so no local pre-check
|
||||
* can add anything correct (a snapshot taken outside that lock would also count
|
||||
* live graphics heaps twice now that xmem's stats include external charges).
|
||||
* The local mirror is kept only for the gpu_heap_bytes diagnostic log; it cannot
|
||||
* wrap, because xmem has already admitted `bytes` under a cap <= UINT64_MAX.
|
||||
* The hook is called while g_section is held (lock order g_section ->
|
||||
* usage_lock, matching every other path in both DLLs). */
|
||||
bool try_charge(uint64_t bytes) {
|
||||
Guard guard(g_section);
|
||||
bx_xmem_stats_t stats{};
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
const uint64_t cap = active_cap(stats);
|
||||
const uint64_t xmem_used = stats.committed_virtual_bytes + stats.allocated_physical_bytes;
|
||||
if (bytes > cap || xmem_used > cap || g_record.charged_private_bytes > cap - xmem_used) {
|
||||
if (!bx_xmem_try_charge_external(bytes)) {
|
||||
return false;
|
||||
}
|
||||
const uint64_t room = cap - xmem_used - g_record.charged_private_bytes;
|
||||
if (bytes > room) {
|
||||
return false;
|
||||
}
|
||||
g_record.charged_private_bytes += bytes;
|
||||
g_record.charged_private_bytes += bytes; /* diagnostic mirror */
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Each heap wrapper calls this exactly once, on its final Release, which is what
|
||||
* keeps a heap from being released twice. The mirror check below is a coarse
|
||||
* guard on the total: it refuses a release larger than all outstanding graphics
|
||||
* charges (refusing leaves a charge in place, so the cap stays strict), but as a
|
||||
* single total it cannot tell one heap's double release from another heap's
|
||||
* charge. */
|
||||
void release_charge(uint64_t bytes) {
|
||||
Guard guard(g_section);
|
||||
if (bytes > g_record.charged_private_bytes) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "heap_budget", "GPU heap charge underflow on release");
|
||||
g_record.charged_private_bytes = 0;
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "heap_budget",
|
||||
"GPU heap charge underflow on release; xmem charge left unchanged");
|
||||
return;
|
||||
}
|
||||
g_record.charged_private_bytes -= bytes;
|
||||
bx_xmem_release_charge_external(bytes);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -557,41 +570,6 @@ HRESULT host_private_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFI
|
||||
return hr;
|
||||
}
|
||||
|
||||
bool is_backing_heap(ID3D12Heap* heap) {
|
||||
if (!heap) {
|
||||
return false;
|
||||
}
|
||||
BxChargedHeap* backing = nullptr;
|
||||
{
|
||||
Guard guard(g_section);
|
||||
backing = g_record.backing;
|
||||
if (!backing) {
|
||||
return false;
|
||||
}
|
||||
backing->AddRef();
|
||||
}
|
||||
IUnknown* want = nullptr;
|
||||
IUnknown* got = nullptr;
|
||||
const HRESULT want_hr = backing->QueryInterface(IID_IUnknown, reinterpret_cast<void**>(&want));
|
||||
const HRESULT got_hr = heap->QueryInterface(IID_IUnknown, reinterpret_cast<void**>(&got));
|
||||
const bool same = SUCCEEDED(want_hr) && SUCCEEDED(got_hr) && want == got;
|
||||
if (want) {
|
||||
want->Release();
|
||||
}
|
||||
if (got) {
|
||||
got->Release();
|
||||
}
|
||||
backing->Release();
|
||||
return same;
|
||||
}
|
||||
|
||||
void log_placed(UINT64 offset, HRESULT hr) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "CreatePlacedResource offset=%llu hr=0x%08lx",
|
||||
static_cast<unsigned long long>(offset), static_cast<unsigned long>(hr));
|
||||
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "placed_resource", detail);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE create_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC* desc, REFIID riid, void** out) {
|
||||
BX_D3D_TRACE("ID3D12Device", "CreateHeap");
|
||||
if (!self || !self->h_ID3D12Device) {
|
||||
@@ -621,34 +599,97 @@ HRESULT STDMETHODCALLTYPE create_heap(BxDeviceProxy* self, const D3D12_HEAP_DESC
|
||||
return host_private_heap(self, desc, riid, out, true);
|
||||
}
|
||||
|
||||
HRESULT validate_backing_placement(ID3D12Device* device, ID3D12Heap* heap, UINT64 offset, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear) {
|
||||
if (!heap || !desc) {
|
||||
/* The inputs that differ between CreatePlacedResource, CreatePlacedResource1 and
|
||||
CreatePlacedResource2. `state` is null for CreatePlacedResource2, which takes a
|
||||
barrier layout instead of a resource state. */
|
||||
struct Placement {
|
||||
const char* method;
|
||||
ID3D12Heap* heap;
|
||||
UINT64 offset;
|
||||
D3D12_RESOURCE_DIMENSION dimension;
|
||||
const D3D12_CLEAR_VALUE* clear;
|
||||
const D3D12_RESOURCE_STATES* state;
|
||||
D3D12_RESOURCE_ALLOCATION_INFO info;
|
||||
};
|
||||
|
||||
/* Runs on every heap: the backing heap, a heap from CreateHeap, or a host heap the
|
||||
caller passes directly. The heap desc is read from the host heap; BxChargedHeap
|
||||
forwards GetDesc to the same object. */
|
||||
HRESULT validate_placement(const Placement& p) {
|
||||
if (p.dimension == D3D12_RESOURCE_DIMENSION_BUFFER && p.clear) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && clear) {
|
||||
D3D12_HEAP_DESC heap_desc = bx_unwrap(p.heap)->GetDesc();
|
||||
if (p.state) {
|
||||
if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_UPLOAD && *p.state != D3D12_RESOURCE_STATE_GENERIC_READ) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_READBACK && *p.state != D3D12_RESOURCE_STATE_COPY_DEST) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
}
|
||||
if (p.info.SizeInBytes == 0 || p.info.SizeInBytes == ~0ull) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
D3D12_HEAP_DESC heap_desc = heap->GetDesc();
|
||||
if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_UPLOAD && state != D3D12_RESOURCE_STATE_GENERIC_READ) {
|
||||
if (p.info.Alignment != 0 && (p.offset % p.info.Alignment) != 0) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (heap_desc.Properties.Type == D3D12_HEAP_TYPE_READBACK && state != D3D12_RESOURCE_STATE_COPY_DEST) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, desc);
|
||||
if (info.SizeInBytes == 0 || info.SizeInBytes == ~0ull) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (info.Alignment != 0 && (offset % info.Alignment) != 0) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (offset > heap_desc.SizeInBytes || info.SizeInBytes > heap_desc.SizeInBytes - offset) {
|
||||
if (p.offset > heap_desc.SizeInBytes || p.info.SizeInBytes > heap_desc.SizeInBytes - p.offset) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
void log_placed(const char* method, UINT64 offset, HRESULT hr) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s offset=%llu hr=0x%08lx", method, static_cast<unsigned long long>(offset),
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "placed_resource", detail);
|
||||
}
|
||||
|
||||
/*
|
||||
* The one placement path for slots 29, 70 and 77. `p.heap` and `desc` are already
|
||||
* known non-null; `p.info` comes from the matching GetResourceAllocationInfo call.
|
||||
* `host_call(host_heap)` performs the host Create call with the unwrapped heap.
|
||||
*/
|
||||
template <typename HostCall>
|
||||
HRESULT create_placed_common(const Placement& p, void** out, HostCall&& host_call) {
|
||||
const HRESULT check_hr = validate_placement(p);
|
||||
if (FAILED(check_hr)) {
|
||||
log_placed(p.method, p.offset, check_hr);
|
||||
return check_hr;
|
||||
}
|
||||
ID3D12Heap* host_heap = bx_unwrap(p.heap);
|
||||
HRESULT hr = host_call(host_heap);
|
||||
if (SUCCEEDED(hr) && out && *out && host_heap != p.heap) {
|
||||
/* The resource owns a reference to the shim heap through its host
|
||||
object's private data, including across QueryInterface calls. */
|
||||
auto* created = static_cast<IUnknown*>(*out);
|
||||
ID3D12Object* object = nullptr;
|
||||
HRESULT retain_hr = created->QueryInterface(__uuidof(ID3D12Object), reinterpret_cast<void**>(&object));
|
||||
if (SUCCEEDED(retain_hr)) {
|
||||
retain_hr = object->SetPrivateDataInterface(kPlacedResourceHeap, p.heap);
|
||||
object->Release();
|
||||
}
|
||||
if (FAILED(retain_hr)) {
|
||||
created->Release();
|
||||
*out = nullptr;
|
||||
hr = retain_hr;
|
||||
}
|
||||
}
|
||||
log_placed(p.method, p.offset, hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
/* Null heap or desc never reaches the host. */
|
||||
HRESULT reject_null_placement(const char* method, ID3D12Heap* heap, const void* desc, UINT64 offset) {
|
||||
if (heap && desc) {
|
||||
return S_OK;
|
||||
}
|
||||
log_placed(method, offset, E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE create_placed(BxDeviceProxy* self, ID3D12Heap* heap, UINT64 offset,
|
||||
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) {
|
||||
@@ -663,83 +704,188 @@ HRESULT STDMETHODCALLTYPE create_placed(BxDeviceProxy* self, ID3D12Heap* heap, U
|
||||
if (out) {
|
||||
*out = nullptr;
|
||||
}
|
||||
if (is_backing_heap(heap)) {
|
||||
const HRESULT check_hr = validate_backing_placement(self->h_ID3D12Device, heap, offset, desc, state, clear);
|
||||
if (FAILED(check_hr)) {
|
||||
log_placed(offset, check_hr);
|
||||
return check_hr;
|
||||
}
|
||||
const char* method = "CreatePlacedResource";
|
||||
const HRESULT null_hr = reject_null_placement(method, heap, desc, offset);
|
||||
if (FAILED(null_hr)) {
|
||||
return null_hr;
|
||||
}
|
||||
ID3D12Heap* host_heap = bx_unwrap(heap);
|
||||
HRESULT hr = self->h_ID3D12Device->CreatePlacedResource(host_heap, offset, desc, state, clear, riid, out);
|
||||
if (SUCCEEDED(hr) && out && *out && host_heap != heap) {
|
||||
/* The resource owns a reference to the shim heap through its host
|
||||
object's private data, including across QueryInterface calls. */
|
||||
auto* created = static_cast<IUnknown*>(*out);
|
||||
ID3D12Object* object = nullptr;
|
||||
HRESULT retain_hr = created->QueryInterface(__uuidof(ID3D12Object), reinterpret_cast<void**>(&object));
|
||||
if (SUCCEEDED(retain_hr)) {
|
||||
retain_hr = object->SetPrivateDataInterface(kPlacedResourceHeap, heap);
|
||||
object->Release();
|
||||
}
|
||||
if (FAILED(retain_hr)) {
|
||||
created->Release();
|
||||
*out = nullptr;
|
||||
hr = retain_hr;
|
||||
}
|
||||
}
|
||||
log_placed(offset, hr);
|
||||
return hr;
|
||||
ID3D12Device* device = self->h_ID3D12Device;
|
||||
const Placement p{method, heap, offset, desc->Dimension, clear, &state, device->GetResourceAllocationInfo(0, 1, desc)};
|
||||
return create_placed_common(p, out, [&](ID3D12Heap* host_heap) {
|
||||
return device->CreatePlacedResource(host_heap, offset, desc, state, clear, riid, out);
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
HRESULT bx_vmem_create_placed_resource1(ID3D12Device8* host, ID3D12Heap* heap, UINT64 offset,
|
||||
const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES state,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) {
|
||||
if (out) {
|
||||
*out = nullptr;
|
||||
}
|
||||
const char* method = "CreatePlacedResource1";
|
||||
const HRESULT null_hr = reject_null_placement(method, heap, desc, offset);
|
||||
if (FAILED(null_hr)) {
|
||||
return null_hr;
|
||||
}
|
||||
const Placement p{method, heap, offset, desc->Dimension, clear, &state,
|
||||
host->GetResourceAllocationInfo2(0, 1, desc, nullptr)};
|
||||
return create_placed_common(p, out, [&](ID3D12Heap* host_heap) {
|
||||
return host->CreatePlacedResource1(host_heap, offset, desc, state, clear, riid, out);
|
||||
});
|
||||
}
|
||||
|
||||
/* The initial barrier layout is not checked against the heap type: only the
|
||||
resource-state rule for UPLOAD and READBACK heaps is applied, on the other two
|
||||
entry points. Allocation info comes from GetResourceAllocationInfo2, which
|
||||
does not take the castable-format list (GetResourceAllocationInfo3 is on
|
||||
ID3D12Device12, past this proxy's ID3D12Device10). */
|
||||
HRESULT bx_vmem_create_placed_resource2(ID3D12Device10* host, ID3D12Heap* heap, UINT64 offset,
|
||||
const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout,
|
||||
const D3D12_CLEAR_VALUE* clear, UINT32 num_castable, DXGI_FORMAT* castable,
|
||||
REFIID riid, void** out) {
|
||||
if (out) {
|
||||
*out = nullptr;
|
||||
}
|
||||
const char* method = "CreatePlacedResource2";
|
||||
const HRESULT null_hr = reject_null_placement(method, heap, desc, offset);
|
||||
if (FAILED(null_hr)) {
|
||||
return null_hr;
|
||||
}
|
||||
const Placement p{method, heap, offset, desc->Dimension, clear, nullptr,
|
||||
host->GetResourceAllocationInfo2(0, 1, desc, nullptr)};
|
||||
return create_placed_common(p, out, [&](ID3D12Heap* host_heap) {
|
||||
return host->CreatePlacedResource2(host_heap, offset, desc, layout, clear, num_castable, castable, riid, out);
|
||||
});
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct ConfigHeader {
|
||||
uint32_t magic;
|
||||
uint32_t struct_size;
|
||||
};
|
||||
static_assert(sizeof(ConfigHeader) == 8, "config probe is the 8-byte header");
|
||||
|
||||
void write_cpu_pointer(void* config, uint64_t pointer) {
|
||||
std::memcpy(static_cast<char*>(config) + offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer), &pointer, sizeof(pointer));
|
||||
bool is_accessible_protect(DWORD protect, bool write) {
|
||||
if ((protect & (PAGE_GUARD | PAGE_NOACCESS)) != 0) {
|
||||
return false;
|
||||
}
|
||||
switch (protect & 0xFFu) {
|
||||
case PAGE_READWRITE:
|
||||
case PAGE_WRITECOPY:
|
||||
case PAGE_EXECUTE_READWRITE:
|
||||
case PAGE_EXECUTE_WRITECOPY:
|
||||
return true;
|
||||
case PAGE_READONLY:
|
||||
case PAGE_EXECUTE_READ:
|
||||
return !write;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
|
||||
if (!config) {
|
||||
/* Titles call this before reserving memory and require S_OK. */
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
bool can_access_bytes(const void* ptr, size_t len, bool write) {
|
||||
if (!ptr || len == 0) {
|
||||
return false;
|
||||
}
|
||||
/*
|
||||
* PVOID has no size. Read 8 bytes, and only then the rest of a block that
|
||||
* names this struct. A mismatch is left untouched.
|
||||
*/
|
||||
ConfigHeader header{};
|
||||
std::memcpy(&header, config, sizeof(header));
|
||||
if (header.magic != BX_D3D12_VMEM_MAGIC || header.struct_size != sizeof(BxD3d12VirtualMemoryConfig)) {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
const uintptr_t start = reinterpret_cast<uintptr_t>(ptr);
|
||||
if (start > std::numeric_limits<uintptr_t>::max() - len) {
|
||||
return false;
|
||||
}
|
||||
const uintptr_t end = start + len;
|
||||
uintptr_t cursor = start;
|
||||
while (cursor < end) {
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
if (VirtualQuery(reinterpret_cast<LPCVOID>(cursor), &mbi, sizeof(mbi)) == 0) {
|
||||
return false;
|
||||
}
|
||||
if (mbi.State != MEM_COMMIT || !is_accessible_protect(mbi.Protect, write) || mbi.RegionSize == 0) {
|
||||
return false;
|
||||
}
|
||||
const uintptr_t region_base = reinterpret_cast<uintptr_t>(mbi.BaseAddress);
|
||||
if (region_base > cursor || mbi.RegionSize > std::numeric_limits<uintptr_t>::max() - region_base) {
|
||||
return false;
|
||||
}
|
||||
const uintptr_t region_end = region_base + mbi.RegionSize;
|
||||
if (region_end <= cursor) {
|
||||
return false;
|
||||
}
|
||||
cursor = region_end;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool copy_readable_bytes(const void* source, void* destination, size_t len) {
|
||||
if (!destination || !can_access_bytes(source, len, false)) {
|
||||
return false;
|
||||
}
|
||||
SIZE_T bytes_read = 0;
|
||||
return ReadProcessMemory(GetCurrentProcess(), source, destination, len, &bytes_read) != 0 && bytes_read == len;
|
||||
}
|
||||
|
||||
bool write_cpu_pointer(void* config, uint64_t pointer) {
|
||||
auto* destination = static_cast<char*>(config) + offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer);
|
||||
if (!can_access_bytes(destination, sizeof(pointer), true)) {
|
||||
return false;
|
||||
}
|
||||
SIZE_T bytes_written = 0;
|
||||
return WriteProcessMemory(GetCurrentProcess(), destination, &pointer, sizeof(pointer), &bytes_written) != 0 &&
|
||||
bytes_written == sizeof(pointer);
|
||||
}
|
||||
|
||||
/* Writes `len` bytes at `offset` in caller memory, after checking the range is writable. */
|
||||
bool write_config_bytes(void* config, size_t offset, const void* source, size_t len) {
|
||||
auto* destination = static_cast<char*>(config) + offset;
|
||||
if (!can_access_bytes(destination, len, true)) {
|
||||
return false;
|
||||
}
|
||||
SIZE_T bytes_written = 0;
|
||||
return WriteProcessMemory(GetCurrentProcess(), destination, source, len, &bytes_written) != 0 &&
|
||||
bytes_written == len;
|
||||
}
|
||||
|
||||
void log_vmem_fallback(const char* decoder, const char* reason) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "decoder=%s applied=0 reason=%s", decoder, reason);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "vmem_config_fallback", detail);
|
||||
}
|
||||
|
||||
void log_vmem_failed(const char* decoder, const char* reason, HRESULT hr) {
|
||||
char detail[192];
|
||||
std::snprintf(detail, sizeof(detail), "decoder=%s applied=0 reason=%s hr=0x%08lx", decoder, reason,
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "vmem_config_failed", detail);
|
||||
}
|
||||
|
||||
HRESULT decode_bxvm_config(void* config) {
|
||||
BxD3d12VirtualMemoryConfig in{};
|
||||
std::memcpy(&in, config, sizeof(in));
|
||||
if (!copy_readable_bytes(config, &in, sizeof(in))) {
|
||||
log_vmem_fallback("bxvm", "unreadable_tail");
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const uint32_t unknown_flags = in.flags & ~BX_D3D12_VMEM_FLAG_BACKING_HEAP;
|
||||
if (in.version != kConfigVersion || unknown_flags != 0 || in.reserved != 0) {
|
||||
/* A console parameter block is not this struct. Leave those bytes alone. */
|
||||
log_vmem_fallback("bxvm", "unsupported_options");
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const bx_runtime_config_t* cfg = bx_get_runtime_config();
|
||||
const uint64_t cap = title_limit();
|
||||
const auto profile = (cfg && cfg->profile == BX_PROFILE_ANACONDA) ? BX_PROFILE_ANACONDA : BX_PROFILE_LOCKHART;
|
||||
if (in.size_bytes != 0 && (in.size_bytes % k64K != 0 || in.size_bytes > cap)) {
|
||||
log_vmem_failed("bxvm", "invalid_size", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
bx_xmem_stats_t stats{};
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
if (in.size_bytes != 0 && stats.title_limit_bytes != 0 && in.size_bytes > stats.title_limit_bytes) {
|
||||
log_vmem_failed("bxvm", "exceeds_xmem_limit", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
@@ -749,16 +895,19 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
|
||||
bx_xmem_region_info_t first{};
|
||||
if (!bx_xmem_query_region(in.base_va, &first) || first.size_bytes == 0 || first.base_va != in.base_va ||
|
||||
first.base_va % k64K != 0 || first.size_bytes % k64K != 0) {
|
||||
log_vmem_failed("bxvm", "unknown_xmem_region", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
const uint64_t span = in.size_bytes != 0 ? in.size_bytes : first.size_bytes;
|
||||
if (span < first.size_bytes || span % first.size_bytes != 0) {
|
||||
log_vmem_failed("bxvm", "unaligned_region_span", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
for (uint64_t offset = 0; offset < span; offset += first.size_bytes) {
|
||||
bx_xmem_region_info_t page{};
|
||||
if (!bx_xmem_query_region(first.base_va + offset, &page) || page.base_va != first.base_va + offset ||
|
||||
page.size_bytes != first.size_bytes) {
|
||||
log_vmem_failed("bxvm", "discontiguous_xmem_region", E_INVALIDARG);
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
}
|
||||
@@ -767,49 +916,60 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
|
||||
have_region = true;
|
||||
}
|
||||
|
||||
if (!can_access_bytes(static_cast<char*>(config) + offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer),
|
||||
sizeof(in.cpu_pointer), true)) {
|
||||
log_vmem_fallback("bxvm", "unwritable_output");
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
const uint64_t new_base = have_region ? region.base_va : in.base_va;
|
||||
const uint64_t new_size = have_region ? region.size_bytes : in.size_bytes;
|
||||
const bool backing_opt_in = (in.flags & BX_D3D12_VMEM_FLAG_BACKING_HEAP) != 0;
|
||||
BxChargedHeap* old_heap = nullptr;
|
||||
ID3D12Resource* old_buffer = nullptr;
|
||||
uint64_t published = 0;
|
||||
bool output_written = false;
|
||||
{
|
||||
Guard guard(g_section);
|
||||
const bool same = g_record.configured && g_record.config_base == new_base && g_record.config_size == new_size;
|
||||
if (!same) {
|
||||
take_cached_heap_locked(&old_heap, &old_buffer);
|
||||
published = same ? g_record.cpu_pointer : 0;
|
||||
output_written = write_cpu_pointer(config, published);
|
||||
if (output_written) {
|
||||
if (!same) {
|
||||
take_cached_heap_locked(&old_heap, &old_buffer);
|
||||
}
|
||||
if (!same || g_record.backing_opt_in != backing_opt_in || g_record.have_region != have_region) {
|
||||
++g_record.config_generation;
|
||||
}
|
||||
g_record.configured = true;
|
||||
g_record.backing_opt_in = backing_opt_in;
|
||||
g_record.profile = profile;
|
||||
g_record.title_limit = cap;
|
||||
g_record.have_region = have_region;
|
||||
g_record.config_base = new_base;
|
||||
g_record.config_size = new_size;
|
||||
g_record.region = have_region ? region : bx_xmem_region_info_t{};
|
||||
}
|
||||
if (!same || g_record.backing_opt_in != backing_opt_in || g_record.have_region != have_region) {
|
||||
++g_record.config_generation;
|
||||
}
|
||||
g_record.configured = true;
|
||||
g_record.backing_opt_in = backing_opt_in;
|
||||
g_record.profile = profile;
|
||||
g_record.title_limit = cap;
|
||||
g_record.have_region = have_region;
|
||||
g_record.config_base = new_base;
|
||||
g_record.config_size = new_size;
|
||||
g_record.region = have_region ? region : bx_xmem_region_info_t{};
|
||||
published = g_record.cpu_pointer;
|
||||
}
|
||||
/* The only write to caller memory, and it happens before this call returns. */
|
||||
write_cpu_pointer(config, published);
|
||||
if (old_buffer) {
|
||||
old_buffer->Unmap(0, nullptr);
|
||||
old_buffer->Release();
|
||||
}
|
||||
if (old_heap) {
|
||||
old_heap->Release();
|
||||
if (!output_written) {
|
||||
log_vmem_failed("bxvm", "unwritable_output", E_INVALIDARG);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
release_backing_pair(old_heap, old_buffer);
|
||||
uint64_t charged = 0;
|
||||
{
|
||||
Guard guard(g_section);
|
||||
charged = g_record.charged_private_bytes;
|
||||
}
|
||||
|
||||
char detail[384];
|
||||
char detail[416];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"profile=%s title_limit=%llu xmem_used=%llu xmem_region=%d base=0x%llx region_bytes=%llu gpu_heap_bytes=%llu",
|
||||
/* cap_used is everything counted against the title cap, graphics heaps
|
||||
* included (xmem's stats include external charges); gpu_heap_bytes is the
|
||||
* graphics part of it, so the two must not be added. */
|
||||
"decoder=bxvm applied=1 profile=%s title_limit=%llu cap_used=%llu xmem_region=%d base=0x%llx region_bytes=%llu gpu_heap_bytes=%llu",
|
||||
profile_name(profile), static_cast<unsigned long long>(cap),
|
||||
static_cast<unsigned long long>(stats.committed_virtual_bytes + stats.allocated_physical_bytes),
|
||||
have_region ? 1 : 0, static_cast<unsigned long long>(have_region ? region.base_va : 0),
|
||||
@@ -819,6 +979,105 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT decode_xbox_config(void* config) {
|
||||
/* The structure has no size field, so all 32 bytes must be readable and writable. */
|
||||
BxXboxVirtualMemoryConfig in{};
|
||||
if (!copy_readable_bytes(config, &in, sizeof(in))) {
|
||||
log_vmem_failed("xbox", "unreadable_config", E_INVALIDARG);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (in.page_table_memory_4mb_page_count == 0u) {
|
||||
log_vmem_failed("xbox", "zero_page_table_pages", E_INVALIDARG);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
{
|
||||
Guard guard(g_section);
|
||||
if (g_record.device_created) {
|
||||
log_vmem_failed("xbox", "device_already_created", E_FAIL);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_FAIL;
|
||||
}
|
||||
}
|
||||
|
||||
const bool clamped = in.page_table_memory_4mb_page_count > BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES;
|
||||
const uint32_t pages = clamped ? BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES : in.page_table_memory_4mb_page_count;
|
||||
uint32_t preserve = in.frame_buffer_preserve_memory_size_bytes;
|
||||
if (preserve != BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_LEGACY &&
|
||||
preserve > BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES) {
|
||||
preserve = BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES;
|
||||
}
|
||||
const uint64_t outputs[2] = {BX_D3D12_XBOX_MIN_GRAPHICS_ADDRESS,
|
||||
static_cast<uint64_t>(pages) * BX_D3D12_XBOX_GRAPHICS_BYTES_PER_4MB_PAGE};
|
||||
if (!write_config_bytes(config, offsetof(BxXboxVirtualMemoryConfig, minimum_valid_graphics_address), outputs,
|
||||
sizeof(outputs))) {
|
||||
log_vmem_failed("xbox", "unwritable_output", E_INVALIDARG);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
/*
|
||||
* The host sizes no GPU page tables and keeps no cross-process frame buffer, so both
|
||||
* values are only recorded. This path leaves the BXVM record and its cached backing heap
|
||||
* untouched, reports applied=0 and keeps BX_STUB_LOG, so `bx-cli trace` still lists
|
||||
* D3D12ConfigureVirtualMemoryX as unimplemented.
|
||||
*/
|
||||
bool repeat = false;
|
||||
{
|
||||
Guard guard(g_section);
|
||||
repeat = g_record.xbox_configured && g_record.xbox_page_table_4mb_pages == pages &&
|
||||
g_record.xbox_frame_buffer_preserve_bytes == preserve;
|
||||
g_record.xbox_configured = true;
|
||||
g_record.xbox_page_table_4mb_pages = pages;
|
||||
g_record.xbox_frame_buffer_preserve_bytes = preserve;
|
||||
}
|
||||
|
||||
char detail[320];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"decoder=xbox applied=0 recorded_only=1 page_table_4mb_pages=%u clamped=%d "
|
||||
"frame_buffer_preserve_bytes=%u min_gpu_va=0x%llx max_gpu_va=0x%llx max_estimated=%d "
|
||||
"repeat=%d reason=host_ignores_page_table_size",
|
||||
pages, clamped ? 1 : 0, preserve, static_cast<unsigned long long>(outputs[0]),
|
||||
static_cast<unsigned long long>(outputs[1]),
|
||||
pages == BX_D3D12_XBOX_PAGE_TABLE_DEFAULT_4MB_PAGES ? 0 : 1, repeat ? 1 : 0);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "vmem_config_recorded", detail);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
|
||||
if (!config) {
|
||||
/* Titles call this before reserving memory and require S_OK. */
|
||||
log_vmem_fallback("none", "null_config");
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
/*
|
||||
* PVOID has no size. Verify 8 bytes are committed and readable before
|
||||
* probing the header, and let each decoder verify its own full length.
|
||||
*/
|
||||
ConfigHeader header{};
|
||||
if (!copy_readable_bytes(config, &header, sizeof(header))) {
|
||||
log_vmem_fallback("none", "unreadable_header");
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
if (header.magic == BX_D3D12_VMEM_MAGIC && header.struct_size == sizeof(BxD3d12VirtualMemoryConfig)) {
|
||||
return decode_bxvm_config(config);
|
||||
}
|
||||
if (header.magic == 0u) {
|
||||
return decode_xbox_config(config);
|
||||
}
|
||||
|
||||
log_vmem_fallback("none", "unrecognized_header");
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
bool bx_vmem_final_release(void* device_proxy) {
|
||||
Guard guard(g_section);
|
||||
auto* proxy = static_cast<BxDeviceProxy*>(device_proxy);
|
||||
@@ -856,6 +1115,7 @@ bool bx_vmem_install_device_hooks(void* device) {
|
||||
static bool installed = false;
|
||||
Guard guard(g_section);
|
||||
if (installed) {
|
||||
g_record.device_created = true;
|
||||
return true;
|
||||
}
|
||||
auto* proxy = static_cast<BxDeviceProxy*>(device);
|
||||
@@ -871,6 +1131,7 @@ bool bx_vmem_install_device_hooks(void* device) {
|
||||
DWORD ignored = 0;
|
||||
VirtualProtect(vtable + 28, sizeof(void*) * 2, old, &ignored);
|
||||
installed = true;
|
||||
g_record.device_created = true;
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "vmem_hook", "CreateHeap and CreatePlacedResource installed");
|
||||
return true;
|
||||
}
|
||||
+62
-11
@@ -9,17 +9,20 @@
|
||||
* BetterXen-defined parameter block for D3D12ConfigureVirtualMemoryX.
|
||||
*
|
||||
* The export is PVOID and the frozen ABI has no size argument (abi/ is out of
|
||||
* scope). The first 8 bytes are therefore the minimum dereference: magic then
|
||||
* the struct size. Magic is 'BXVM' (0x4D565842). struct_size must equal
|
||||
* sizeof(BxD3d12VirtualMemoryConfig). Any other pointer, including null, is not
|
||||
* this struct: the call logs the unimplemented-API stub and returns S_OK. It
|
||||
* does not read past those 8 bytes and it does not write.
|
||||
* 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 still returns E_INVALIDARG and is not written.
|
||||
* 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.
|
||||
@@ -47,16 +50,17 @@
|
||||
* returns HRESULT_FROM_WIN32(ERROR_RETRY) and discards any newly allocated heap.
|
||||
* Any other CreateHeap is the host CreateHeap. The desc is not modified.
|
||||
* The live-heap budget charge is taken on create and dropped on the wrapper's
|
||||
* final Release. A resource created by CreatePlacedResource holds the wrapper
|
||||
* for its lifetime.
|
||||
* 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.
|
||||
* CreatePlacedResource1 and CreatePlacedResource2 unwrap the wrapper to the
|
||||
* host heap before the host call. The cache records the host ID3D12Device
|
||||
* 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,
|
||||
@@ -87,9 +91,56 @@ static_assert(offsetof(BxD3d12VirtualMemoryConfig, size_bytes) == 24, "size_byte
|
||||
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. */
|
||||
/* 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
|
||||
|
||||
@@ -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
|
||||
@@ -2,6 +2,8 @@
|
||||
#include <unknwn.h>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <new>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "bx_log.h"
|
||||
@@ -43,14 +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;
|
||||
@@ -133,10 +159,9 @@ public:
|
||||
SrwExclusiveLock guard(callback_lock_);
|
||||
return callbacks_.erase(token) > 0;
|
||||
}
|
||||
virtual HRESULT WINAPI CreateDispatcher(void** out) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 14, "CreateDispatcher");
|
||||
return unavailable(out);
|
||||
}
|
||||
// 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);
|
||||
@@ -166,6 +191,93 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
#include <windows.h>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
@@ -23,10 +24,25 @@ struct SrwLockGuard {
|
||||
SrwLockGuard& operator=(const SrwLockGuard&) = delete;
|
||||
};
|
||||
|
||||
// Exception-free open-addressed hash set backed by the Win32 process heap so
|
||||
// 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 {
|
||||
uintptr_t* slots = nullptr;
|
||||
Entry* slots = nullptr;
|
||||
size_t capacity = 0;
|
||||
size_t count = 0;
|
||||
size_t used = 0; // active entries + tombstones
|
||||
@@ -42,24 +58,24 @@ struct TokenSet {
|
||||
}
|
||||
|
||||
bool rehash(size_t new_capacity) {
|
||||
if (new_capacity == 0 || new_capacity > SIZE_MAX / sizeof(uintptr_t)) {
|
||||
if (new_capacity == 0 || new_capacity > SIZE_MAX / sizeof(Entry)) {
|
||||
return false;
|
||||
}
|
||||
HANDLE heap = GetProcessHeap();
|
||||
if (!heap) {
|
||||
return false;
|
||||
}
|
||||
auto* fresh = static_cast<uintptr_t*>(
|
||||
HeapAlloc(heap, HEAP_ZERO_MEMORY, new_capacity * sizeof(uintptr_t)));
|
||||
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 uintptr_t entry = slots[i];
|
||||
if (entry != kEmptySlot && entry != kTombstoneSlot) {
|
||||
size_t idx = hash(entry) & mask;
|
||||
while (fresh[idx] != kEmptySlot) {
|
||||
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;
|
||||
@@ -74,13 +90,15 @@ struct TokenSet {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool insert(uintptr_t token) {
|
||||
// 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(uintptr_t)) / 2) {
|
||||
return false;
|
||||
if (capacity > (SIZE_MAX / sizeof(Entry)) / 2) {
|
||||
return nullptr;
|
||||
}
|
||||
next_capacity = capacity * 2;
|
||||
} else {
|
||||
@@ -89,28 +107,36 @@ struct TokenSet {
|
||||
}
|
||||
}
|
||||
if (!rehash(next_capacity)) {
|
||||
return false;
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
const size_t mask = capacity - 1;
|
||||
size_t idx = hash(token) & mask;
|
||||
size_t first_tombstone = capacity;
|
||||
while (true) {
|
||||
const uintptr_t entry = slots[idx];
|
||||
if (entry == token) {
|
||||
return true;
|
||||
Entry& entry = slots[idx];
|
||||
if (entry.token == token) {
|
||||
entry.callback = callback;
|
||||
entry.context = context;
|
||||
return &entry;
|
||||
}
|
||||
if (entry == kEmptySlot) {
|
||||
if (entry.token == kEmptySlot) {
|
||||
if (first_tombstone != capacity) {
|
||||
slots[first_tombstone] = token;
|
||||
} else {
|
||||
slots[idx] = token;
|
||||
++used;
|
||||
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 true;
|
||||
return &entry;
|
||||
}
|
||||
if (entry == kTombstoneSlot && first_tombstone == capacity) {
|
||||
if (entry.token == kTombstoneSlot && first_tombstone == capacity) {
|
||||
first_tombstone = idx;
|
||||
}
|
||||
idx = (idx + 1) & mask;
|
||||
@@ -124,12 +150,16 @@ struct TokenSet {
|
||||
const size_t mask = capacity - 1;
|
||||
size_t idx = hash(token) & mask;
|
||||
for (size_t probed = 0; probed < capacity; ++probed) {
|
||||
const uintptr_t entry = slots[idx];
|
||||
if (entry == kEmptySlot) {
|
||||
Entry& entry = slots[idx];
|
||||
if (entry.token == kEmptySlot) {
|
||||
return false;
|
||||
}
|
||||
if (entry == token) {
|
||||
slots[idx] = kTombstoneSlot;
|
||||
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;
|
||||
}
|
||||
@@ -166,7 +196,15 @@ struct Registrations {
|
||||
Registrations g_state{SRWLOCK_INIT, {}, kStatePrefix, kConstrainedPrefix, 1};
|
||||
Registrations g_constrained{SRWLOCK_INIT, {}, kConstrainedPrefix, kStatePrefix, 1};
|
||||
|
||||
ULONG register_notification(Registrations& registrations, PVOID callback,
|
||||
// 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;
|
||||
@@ -177,6 +215,8 @@ ULONG register_notification(Registrations& registrations, PVOID callback,
|
||||
}
|
||||
|
||||
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.
|
||||
@@ -184,14 +224,24 @@ ULONG register_notification(Registrations& registrations, PVOID callback,
|
||||
return ERROR_NOT_ENOUGH_MEMORY;
|
||||
}
|
||||
token = registrations.own_prefix | static_cast<uintptr_t>(registrations.next_seq);
|
||||
if (!registrations.active.insert(token)) {
|
||||
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);
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, "registered_offline");
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -218,6 +268,8 @@ extern "C" {
|
||||
|
||||
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();
|
||||
@@ -230,16 +282,18 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
|
||||
return register_notification(g_state, callback, out_reg, "RegisterAppStateChangeNotification");
|
||||
ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID context, PVOID* out_reg) {
|
||||
return register_notification(g_state, callback, context, out_reg,
|
||||
"RegisterAppStateChangeNotification");
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppStateChangeNotification(PVOID reg) {
|
||||
unregister_notification(g_state, reg, "UnregisterAppStateChangeNotification");
|
||||
}
|
||||
|
||||
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
|
||||
return register_notification(g_constrained, callback, out_reg, "RegisterAppConstrainedChangeNotification");
|
||||
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) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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)
|
||||
|
||||
@@ -55,12 +55,15 @@ struct Request {
|
||||
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;
|
||||
|
||||
+537
-16
@@ -1,4 +1,5 @@
|
||||
#include "synthetic_storage.h"
|
||||
#include "zlib_inflate.h"
|
||||
|
||||
// Public PC DirectStorage contract: Microsoft.Direct3D.DirectStorage 1.4.0,
|
||||
// MIT per file, vendored unmodified under dstorage/ (see dstorage/README.md).
|
||||
@@ -8,6 +9,8 @@
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
@@ -415,7 +418,65 @@ CopyResult copy_staged(HANDLE file, const Request& request) {
|
||||
return staged.finish(win32_error());
|
||||
}
|
||||
|
||||
HRESULT inflate_request(HANDLE file, const Request& request) {
|
||||
if (!request.destination || !request.output_size || request.size >= request.output_size) return E_INVALIDARG;
|
||||
auto* compressed = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, request.size));
|
||||
if (!compressed) return E_OUTOFMEMORY;
|
||||
HRESULT hr = read_bytes(file, request.file_offset, compressed, request.source, request.size);
|
||||
if (SUCCEEDED(hr)) {
|
||||
const BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
|
||||
request.output_size);
|
||||
if (r != BxInflateResult::ok) {
|
||||
static std::atomic<UINT> logged{0};
|
||||
if (logged.fetch_add(1) < 16) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "zlib stream of %lu bytes to %lu bytes: %s", request.size,
|
||||
request.output_size, bx_inflate_result_name(r));
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_zlib_failed", detail);
|
||||
}
|
||||
hr = E_DSTORAGE_DECOMPRESSION_ERROR;
|
||||
}
|
||||
}
|
||||
HeapFree(GetProcessHeap(), 0, compressed);
|
||||
return hr;
|
||||
}
|
||||
|
||||
CopyResult fulfill_request(HANDLE file, const Request& request);
|
||||
|
||||
// Diagnostics (off unless BX_DSTORAGE_TRACE=1): one line per memory-destination request with its
|
||||
// destination range, sizes, file offset, result and the first 16 bytes written, up to 20000.
|
||||
bool dstorage_trace_enabled() {
|
||||
static const bool on = [] {
|
||||
char value[8];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_DSTORAGE_TRACE", value, sizeof(value));
|
||||
return n > 0 && n < sizeof(value) && value[0] == '1';
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
|
||||
CopyResult fulfill(HANDLE file, const Request& request) {
|
||||
const CopyResult result = fulfill_request(file, request);
|
||||
if (!dstorage_trace_enabled() || request.resource) return result;
|
||||
static std::atomic<UINT> traced{0};
|
||||
if (traced.fetch_add(1) >= 20000) return result;
|
||||
const DWORD out = request.compression == compression_zlib ? request.output_size : request.size;
|
||||
uint64_t head[2] = {0, 0};
|
||||
if (SUCCEEDED(result.hr) && request.destination && out >= 16) std::memcpy(head, request.destination, 16);
|
||||
char detail[220];
|
||||
std::snprintf(detail, sizeof(detail), "dst=%p..%p out=%lu src=%lu offset=0x%llx compression=%u hr=0x%08lx head=%016llx %016llx",
|
||||
request.destination, static_cast<const uint8_t*>(request.destination) + out, out, request.size,
|
||||
static_cast<unsigned long long>(request.file_offset), request.compression,
|
||||
static_cast<unsigned long>(result.hr), static_cast<unsigned long long>(head[0]),
|
||||
static_cast<unsigned long long>(head[1]));
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_request", detail);
|
||||
return result;
|
||||
}
|
||||
|
||||
CopyResult fulfill_request(HANDLE file, const Request& request) {
|
||||
if (request.compression == compression_zlib) {
|
||||
if (request.resource) return {E_NOTIMPL, false};
|
||||
return {inflate_request(file, request), false};
|
||||
}
|
||||
if (request.compression) {
|
||||
log_compression(request.compression);
|
||||
return {E_NOTIMPL, false};
|
||||
@@ -443,9 +504,12 @@ CopyResult fulfill(HANDLE file, const Request& request) {
|
||||
}
|
||||
|
||||
// Each queue is drained serially, in FIFO order, by a single threadpool work item.
|
||||
// A `blocking` queue makes a full enqueue wait for a free slot (submitting what is
|
||||
// pending first) instead of failing with ERROR_BUSY. A non-zero `auto_submit`
|
||||
// submits once that many entries are waiting. The public DirectStorage queues use
|
||||
// A `blocking` queue makes a full enqueue wait for a free slot instead of failing
|
||||
// with ERROR_BUSY. A non-zero `auto_submit` submits once that many entries are
|
||||
// waiting, and a full queue submits what is pending before it waits. With
|
||||
// `auto_submit` 0 (Xbox DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled) nothing runs
|
||||
// before Submit: a full queue stalls the enqueuer until Submit is called on
|
||||
// another thread and the drain frees a slot. The public DirectStorage queues use
|
||||
// both; the BetterXen synthetic queues use neither.
|
||||
class WorkQueue final : public Object<Queue, queue_iid> {
|
||||
public:
|
||||
@@ -471,7 +535,8 @@ public:
|
||||
}
|
||||
Entry entry{Kind::request, *request};
|
||||
if (request->resource) request->resource->AddRef();
|
||||
if (request->file && !request->compression) {
|
||||
// Uncompressed and zlib requests read the file; other compressions are refused when fulfilled.
|
||||
if (request->file && (request->compression == compression_none || request->compression == compression_zlib)) {
|
||||
const HRESULT result = request->file->GetHandle(&entry.handle);
|
||||
if (FAILED(result)) {
|
||||
if (request->resource) request->resource->Release();
|
||||
@@ -613,7 +678,7 @@ private:
|
||||
if (closed_) return HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE);
|
||||
if (size_ < capacity_) return S_OK;
|
||||
if (!blocking_) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
if (submitted_ < size_) submit();
|
||||
if (auto_submit_ && submitted_ < size_) submit();
|
||||
SleepConditionVariableSRW(&space_, &mutex_, INFINITE, 0);
|
||||
}
|
||||
}
|
||||
@@ -913,6 +978,17 @@ bool reserved_fields_clear(const DSTORAGE_REQUEST_OPTIONS& options) {
|
||||
// (the header: an empty queue reports capacity - 1 empty slots), and requests
|
||||
// are submitted automatically once N / 2 are waiting (the header: "until the
|
||||
// queue is half full").
|
||||
// Maps the engine's command kind onto the header's DSTORAGE_COMMAND_TYPE for
|
||||
// RetrieveErrorRecord on the public PC queue.
|
||||
DSTORAGE_COMMAND_TYPE command_type(Kind kind) {
|
||||
switch (kind) {
|
||||
case Kind::status: return DSTORAGE_COMMAND_TYPE_STATUS;
|
||||
case Kind::signal: return DSTORAGE_COMMAND_TYPE_SIGNAL;
|
||||
case Kind::event: return DSTORAGE_COMMAND_TYPE_EVENT;
|
||||
default: return DSTORAGE_COMMAND_TYPE_REQUEST;
|
||||
}
|
||||
}
|
||||
|
||||
class PublicQueue final : public PublicObject<IDStorageQueue4> {
|
||||
public:
|
||||
PublicQueue(WorkQueue* queue, const DSTORAGE_QUEUE_DESC1& desc) : queue_(queue), desc_(desc) {
|
||||
@@ -1045,15 +1121,6 @@ private:
|
||||
|| IsEqualIID(riid, __uuidof(IDStorageQueue4));
|
||||
}
|
||||
|
||||
static DSTORAGE_COMMAND_TYPE command_type(Kind kind) {
|
||||
switch (kind) {
|
||||
case Kind::status: return DSTORAGE_COMMAND_TYPE_STATUS;
|
||||
case Kind::signal: return DSTORAGE_COMMAND_TYPE_SIGNAL;
|
||||
case Kind::event: return DSTORAGE_COMMAND_TYPE_EVENT;
|
||||
default: return DSTORAGE_COMMAND_TYPE_REQUEST;
|
||||
}
|
||||
}
|
||||
|
||||
// Maps a DSTORAGE_REQUEST onto the engine's Request. Only uncompressed
|
||||
// file/memory sources into memory or buffer destinations are supported.
|
||||
HRESULT translate(const DSTORAGE_REQUEST* request, Request* out) const {
|
||||
@@ -1264,11 +1331,459 @@ private:
|
||||
return publish(wrapper, riid, ppv);
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Xbox Series DirectStorage COM interfaces (IDStorage*X), inferred from call-site
|
||||
// observation of a project-authorized target build (provenance pending maintainer
|
||||
// review; not a public contract), layered over the same WorkQueue / StorageFile /
|
||||
// StatusArray engine. Unimplemented vtable slots log through BX_VTABLE_STUB_LOG
|
||||
// so any newly reached slot surfaces immediately in bx-cli trace.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
constexpr IID kXboxFactoryIid{0x62959d11, 0xd45f, 0x4884, {0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae}};
|
||||
constexpr IID kXboxFileIid{0x43704f9f, 0x27c6, 0x4a9f, {0x88, 0x15, 0xd1, 0x65, 0x27, 0x89, 0x4d, 0xf4}};
|
||||
constexpr IID kXboxStatusArrayIid{0xcd66d752, 0x2786, 0x44f7, {0x90, 0x70, 0xe2, 0xa6, 0xfd, 0xad, 0x3f, 0x1b}};
|
||||
constexpr IID kXboxQueueIid{0x3c02cb0c, 0xc050, 0x4195, {0x99, 0xa1, 0xa1, 0xce, 0x94, 0xba, 0x33, 0xc5}};
|
||||
|
||||
struct XboxQueueDesc {
|
||||
UINT64 source_type;
|
||||
UINT16 capacity;
|
||||
INT8 priority;
|
||||
UINT8 reserved_pad[5];
|
||||
PCSTR name;
|
||||
UINT64 flags;
|
||||
};
|
||||
static_assert(sizeof(XboxQueueDesc) == 32, "XboxQueueDesc must be 32 bytes");
|
||||
static_assert(offsetof(XboxQueueDesc, source_type) == 0x00, "source_type offset");
|
||||
static_assert(offsetof(XboxQueueDesc, capacity) == 0x08, "capacity offset");
|
||||
static_assert(offsetof(XboxQueueDesc, priority) == 0x0a, "priority offset");
|
||||
static_assert(offsetof(XboxQueueDesc, name) == 0x10, "name offset");
|
||||
static_assert(offsetof(XboxQueueDesc, flags) == 0x18, "flags offset");
|
||||
|
||||
struct XboxRequest {
|
||||
UINT64 options; // +0x00: bit 22 (0x400000) = memory source, bit 0 = compressed
|
||||
void* destination; // +0x08
|
||||
UINT64 destination_pad; // +0x10
|
||||
UINT32 destination_size; // +0x18
|
||||
UINT32 reserved1c; // +0x1c
|
||||
void* source_ptr; // +0x20: IXboxDStorageFile* (file) or const void* (memory)
|
||||
UINT64 file_offset; // +0x28
|
||||
UINT32 source_size; // +0x30
|
||||
UINT32 reserved34; // +0x34
|
||||
};
|
||||
static_assert(sizeof(XboxRequest) == 56, "XboxRequest must be 56 bytes");
|
||||
static_assert(offsetof(XboxRequest, options) == 0x00, "options offset");
|
||||
static_assert(offsetof(XboxRequest, destination) == 0x08, "destination offset");
|
||||
static_assert(offsetof(XboxRequest, destination_size) == 0x18, "destination_size offset");
|
||||
static_assert(offsetof(XboxRequest, source_ptr) == 0x20, "source_ptr offset");
|
||||
static_assert(offsetof(XboxRequest, file_offset) == 0x28, "file_offset offset");
|
||||
static_assert(offsetof(XboxRequest, source_size) == 0x30, "source_size offset");
|
||||
|
||||
// DSTORAGE_REQUEST_OPTIONS (authorized GDK documentation): ZlibDecompress:1, BcpackMode:4,
|
||||
// SwizzleMode:16, DestinationIsPhysicalPages:1, SourceType:1, SourceIsPhysicalPages:1.
|
||||
constexpr UINT64 kXboxRequestSourceMemoryBit = 0x400000ull; // SourceType, bit 22
|
||||
constexpr UINT64 kXboxRequestCompressedBit = 0x1ull; // ZlibDecompress, bit 0
|
||||
constexpr UINT64 kXboxRequestBcpackMask = 0xFull << 1;
|
||||
constexpr UINT64 kXboxRequestSwizzleMask = 0xFFFFull << 5;
|
||||
constexpr UINT64 kXboxRequestDestinationPagesBit = 1ull << 21;
|
||||
constexpr UINT64 kXboxRequestSourcePagesBit = 1ull << 23;
|
||||
|
||||
// Logs each distinct option combination once, so a run shows which MDU stages a title uses.
|
||||
void log_request_options(UINT64 options, UINT32 source_size, UINT32 destination_size, UINT32 intermediate_size) {
|
||||
static std::mutex lock;
|
||||
static UINT64 seen[64];
|
||||
static size_t count = 0;
|
||||
const UINT64 key = options & ~kXboxRequestSourceMemoryBit;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(lock);
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (seen[i] == key) return;
|
||||
}
|
||||
if (count < 64) seen[count++] = key;
|
||||
}
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"options=0x%llx zlib=%d bcpack_mode=%llu swizzle_mode=%llu dest_pages=%d source_memory=%d source_pages=%d "
|
||||
"first sizes: source=%u destination=%u intermediate=%u",
|
||||
static_cast<unsigned long long>(options), static_cast<int>(options & 1),
|
||||
static_cast<unsigned long long>((options & kXboxRequestBcpackMask) >> 1),
|
||||
static_cast<unsigned long long>((options & kXboxRequestSwizzleMask) >> 5),
|
||||
(options & kXboxRequestDestinationPagesBit) ? 1 : 0, (options & kXboxRequestSourceMemoryBit) ? 1 : 0,
|
||||
(options & kXboxRequestSourcePagesBit) ? 1 : 0, source_size, destination_size, intermediate_size);
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_request_options", detail);
|
||||
}
|
||||
|
||||
struct IXboxDStorageFile : IUnknown {
|
||||
virtual void STDMETHODCALLTYPE Close() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot5() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot6() = 0;
|
||||
};
|
||||
|
||||
struct IXboxDStorageStatusArray : IUnknown {
|
||||
virtual bool STDMETHODCALLTYPE IsComplete(UINT32 index) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot5() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot6() = 0;
|
||||
};
|
||||
|
||||
struct IXboxDStorageQueue : IUnknown {
|
||||
virtual void STDMETHODCALLTYPE EnqueueRequest(const XboxRequest* request) = 0;
|
||||
virtual void STDMETHODCALLTYPE EnqueueStatus(IXboxDStorageStatusArray* status_array, UINT32 index) = 0;
|
||||
virtual void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) = 0;
|
||||
virtual void STDMETHODCALLTYPE Submit() = 0;
|
||||
virtual void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0;
|
||||
virtual void STDMETHODCALLTYPE Close() = 0;
|
||||
virtual HANDLE STDMETHODCALLTYPE GetErrorEvent() = 0;
|
||||
virtual void STDMETHODCALLTYPE RetrieveErrorRecord(void* record) = 0;
|
||||
virtual void STDMETHODCALLTYPE Query(void* info) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot12() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot13() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot14() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot15() = 0;
|
||||
};
|
||||
|
||||
struct IXboxDStorageFactory : IUnknown {
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0;
|
||||
virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot7() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot9() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot11() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot12() = 0;
|
||||
};
|
||||
|
||||
class XboxFile final : public PublicObject<IXboxDStorageFile> {
|
||||
public:
|
||||
explicit XboxFile(StorageFile* file) : file_(file) {}
|
||||
|
||||
void STDMETHODCALLTYPE Close() override { (void)file_->Close(); }
|
||||
HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) override {
|
||||
return file_->GetFileInformation(info);
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot5() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFileX", 5u, "Slot5");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot6() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFileX", 6u, "Slot6");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
File* inner() const { return file_; }
|
||||
|
||||
private:
|
||||
~XboxFile() override { file_->Release(); }
|
||||
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxFileIid); }
|
||||
|
||||
StorageFile* file_;
|
||||
};
|
||||
|
||||
class XboxStatusArray final : public PublicObject<IXboxDStorageStatusArray> {
|
||||
public:
|
||||
explicit XboxStatusArray(StatusArray* array) : array_(array) {}
|
||||
|
||||
bool STDMETHODCALLTYPE IsComplete(UINT32 index) override { return array_->GetResult(index) != E_PENDING; }
|
||||
HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) override { return array_->GetResult(index); }
|
||||
HRESULT STDMETHODCALLTYPE StubSlot5() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageStatusArrayX", 5u, "Slot5");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot6() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageStatusArrayX", 6u, "Slot6");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
StatusArray* inner() const { return array_; }
|
||||
|
||||
private:
|
||||
~XboxStatusArray() override { array_->Release(); }
|
||||
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxStatusArrayIid); }
|
||||
|
||||
StatusArray* array_;
|
||||
};
|
||||
|
||||
class XboxQueue final : public PublicObject<IXboxDStorageQueue> {
|
||||
public:
|
||||
XboxQueue(WorkQueue* queue, UINT64 source_type) : queue_(queue), source_type_(source_type) {}
|
||||
|
||||
void STDMETHODCALLTYPE EnqueueRequest(const XboxRequest* request) override {
|
||||
if (!request) {
|
||||
reject(E_INVALIDARG, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
const bool is_memory = (request->options & kXboxRequestSourceMemoryBit) != 0;
|
||||
if ((is_memory && source_type_ == 0) || (!is_memory && source_type_ != 0)) {
|
||||
reject(E_DSTORAGE_INVALID_SOURCE_TYPE, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
log_request_options(request->options, request->source_size, request->destination_size, request->reserved34);
|
||||
if (request->options & kXboxRequestBcpackMask) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_bcpack");
|
||||
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
if (request->options & kXboxRequestSwizzleMask) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_swizzle");
|
||||
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
if (request->options & (kXboxRequestDestinationPagesBit | kXboxRequestSourcePagesBit)) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_physical_pages");
|
||||
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
const bool zlib = (request->options & kXboxRequestCompressedBit) != 0;
|
||||
if (!request->destination || (zlib ? request->source_size >= request->destination_size
|
||||
: request->source_size != request->destination_size)) {
|
||||
reject(E_DSTORAGE_INVALID_DESTINATION_SIZE, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
|
||||
Request translated{};
|
||||
translated.destination = request->destination;
|
||||
translated.size = request->source_size;
|
||||
if (zlib) {
|
||||
translated.compression = compression_zlib;
|
||||
translated.output_size = request->destination_size;
|
||||
}
|
||||
if (is_memory) {
|
||||
if (!request->source_ptr) {
|
||||
reject(E_INVALIDARG, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
translated.source = request->source_ptr;
|
||||
} else {
|
||||
auto* file = public_impl<XboxFile>(static_cast<IXboxDStorageFile*>(request->source_ptr));
|
||||
if (!file) {
|
||||
reject(E_DSTORAGE_FILE_NOT_OPEN, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
translated.file = file->inner();
|
||||
translated.file_offset = request->file_offset;
|
||||
}
|
||||
accept(queue_->EnqueueRequest(&translated), Kind::request, "EnqueueRequest");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE EnqueueStatus(IXboxDStorageStatusArray* status_array, UINT32 index) override {
|
||||
auto* array = public_impl<XboxStatusArray>(status_array);
|
||||
if (!array) {
|
||||
reject(E_DSTORAGE_INVALID_STATUS_ARRAY, Kind::status, "EnqueueStatus");
|
||||
return;
|
||||
}
|
||||
HRESULT hr = queue_->EnqueueStatus(array->inner(), index);
|
||||
if (hr == E_INVALIDARG) hr = E_DSTORAGE_INDEX_BOUND;
|
||||
accept(hr, Kind::status, "EnqueueStatus");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) override {
|
||||
if (!fence) {
|
||||
reject(E_DSTORAGE_INVALID_FENCE, Kind::signal, "EnqueueSignal");
|
||||
return;
|
||||
}
|
||||
accept(queue_->EnqueueSignal(fence, value), Kind::signal, "EnqueueSignal");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE Submit() override {
|
||||
if (FAILED(queue_->Submit())) {
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_queue_closed", "Submit after Close; nothing submitted");
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64, UINT64) override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 7u, "CancelRequestsWithTag");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE Close() override { (void)queue_->Close(); }
|
||||
|
||||
HANDLE STDMETHODCALLTYPE GetErrorEvent() override { return queue_->error_event(); }
|
||||
|
||||
void STDMETHODCALLTYPE RetrieveErrorRecord(void*) override {
|
||||
// The size and layout of the Xbox caller's output are unverified.
|
||||
// Do not write the public PC record into it.
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 10u, "RetrieveErrorRecord");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE Query(void*) override { BX_VTABLE_STUB_LOG("IDStorageQueueX", 11u, "Query"); }
|
||||
HRESULT STDMETHODCALLTYPE StubSlot12() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 12u, "Slot12");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot13() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 13u, "Slot13");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot14() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 14u, "Slot14");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot15() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 15u, "Slot15");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
private:
|
||||
~XboxQueue() override { queue_->Release(); }
|
||||
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxQueueIid); }
|
||||
|
||||
void reject(HRESULT hr, Kind kind, const char* method) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "xbox %s hr=0x%08lx", method, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_enqueue_rejected", detail);
|
||||
if (FAILED(queue_->enqueue_failure(hr, kind))) {
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_queue_closed", "enqueue after Close; command dropped");
|
||||
}
|
||||
}
|
||||
|
||||
void accept(HRESULT hr, Kind kind, const char* method) {
|
||||
if (SUCCEEDED(hr)) return;
|
||||
if (queue_->closed()) {
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_queue_closed", "enqueue after Close; command dropped");
|
||||
return;
|
||||
}
|
||||
reject(hr, kind, method);
|
||||
}
|
||||
|
||||
WorkQueue* queue_;
|
||||
UINT64 source_type_;
|
||||
};
|
||||
|
||||
class XboxFactory final : public PublicObject<IXboxDStorageFactory> {
|
||||
public:
|
||||
HRESULT STDMETHODCALLTYPE CreateQueue(const void*, REFIID, void** ppv) override {
|
||||
if (ppv) *ppv = nullptr;
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 3u, "CreateQueue");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
if (!path || !*path) return E_INVALIDARG;
|
||||
HANDLE handle = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
|
||||
FILE_FLAG_OVERLAPPED, nullptr);
|
||||
if (handle == INVALID_HANDLE_VALUE) return win32_error();
|
||||
auto* file = new (std::nothrow) StorageFile(handle);
|
||||
if (!file) {
|
||||
CloseHandle(handle);
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
auto* wrapper = new (std::nothrow) XboxFile(file);
|
||||
if (!wrapper) {
|
||||
file->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
return publish(wrapper, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR, REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
if (!capacity || capacity > 65535) return E_INVALIDARG;
|
||||
auto* slots = new (std::nothrow) StatusArray::Slot[capacity];
|
||||
if (!slots) return E_OUTOFMEMORY;
|
||||
auto* array = new (std::nothrow) StatusArray(slots, capacity);
|
||||
if (!array) {
|
||||
delete[] slots;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
auto* wrapper = new (std::nothrow) XboxStatusArray(array);
|
||||
if (!wrapper) {
|
||||
array->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
return publish(wrapper, riid, ppv);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) override {
|
||||
if (flags) BX_VTABLE_STUB_LOG("IDStorageFactoryX", 6u, "SetDebugFlags");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE StubSlot7() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 7u, "Slot7");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) override {
|
||||
char detail[80];
|
||||
/* Like the public factory: the engine has no staging buffer to size. */
|
||||
std::snprintf(detail, sizeof(detail), "xbox size=%lu has no effect", static_cast<unsigned long>(size));
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_staging_buffer_size", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE StubSlot9() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 9u, "Slot9");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
if (!desc) return E_INVALIDARG;
|
||||
if (desc->capacity < 2 || desc->capacity > DSTORAGE_MAX_QUEUE_CAPACITY) {
|
||||
return E_DSTORAGE_INVALID_QUEUE_CAPACITY;
|
||||
}
|
||||
if (desc->source_type > 1) {
|
||||
return E_DSTORAGE_INVALID_SOURCE_TYPE;
|
||||
}
|
||||
/* desc->priority is ignored on purpose: the Xbox priority range is not part of
|
||||
* the inferred contract, so no value is rejected (the public queue's
|
||||
* E_DSTORAGE_INVALID_QUEUE_PRIORITY range check is not assumed to apply). */
|
||||
const UINT slots = desc->capacity - 1u;
|
||||
auto* entries = new (std::nothrow) Entry[slots];
|
||||
if (!entries) return E_OUTOFMEMORY;
|
||||
// desc->flags is DSTORAGE_QUEUE_OPTIONS (authorized GDK documentation): bit 0,
|
||||
// AutoSubmitDisabled, makes the queue wait for Submit. A title maps a request's
|
||||
// destination pages after enqueueing it and before submitting, so starting work at half
|
||||
// capacity wrote into pages that were not mapped yet.
|
||||
constexpr UINT64 kAutoSubmitDisabled = 1;
|
||||
const UINT auto_submit = (desc->flags & kAutoSubmitDisabled) ? 0u : desc->capacity / 2u;
|
||||
auto* queue = new (std::nothrow) WorkQueue(entries, slots, true, auto_submit);
|
||||
if (!queue) {
|
||||
delete[] entries;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "xbox queue '%s' capacity=%u source=%llu auto_submit=%s",
|
||||
desc->name ? desc->name : "", static_cast<unsigned>(desc->capacity),
|
||||
static_cast<unsigned long long>(desc->source_type), auto_submit ? "half capacity" : "disabled");
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_queue", detail);
|
||||
if (!queue->create_work()) {
|
||||
const HRESULT error = win32_error();
|
||||
queue->Release();
|
||||
return error;
|
||||
}
|
||||
auto* wrapper = new (std::nothrow) XboxQueue(queue, desc->source_type);
|
||||
if (!wrapper) {
|
||||
queue->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
return publish(wrapper, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE StubSlot11() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 11u, "Slot11");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE StubSlot12() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 12u, "Slot12");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
private:
|
||||
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxFactoryIid); }
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// Accepts BetterXen's synthetic factory IID and IUnknown (the synthetic factory),
|
||||
// and the public PC IDStorageFactory / IDStorageFactory1. Any other IID is logged
|
||||
// with its value so `bx-cli trace` names the interface a guest asked for.
|
||||
// the public PC IDStorageFactory / IDStorageFactory1, and the inferred Xbox
|
||||
// IDStorageFactoryX IID. Any other IID is logged with its value so `bx-cli trace`
|
||||
// names the interface a guest asked for.
|
||||
extern "C" HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv) {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
@@ -1276,6 +1791,12 @@ extern "C" HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv) {
|
||||
auto* factory = new (std::nothrow) PublicFactory;
|
||||
return factory ? publish(factory, riid, ppv) : E_OUTOFMEMORY;
|
||||
}
|
||||
if (IsEqualIID(riid, kXboxFactoryIid)) {
|
||||
auto* factory = new (std::nothrow) XboxFactory;
|
||||
if (!factory) return E_OUTOFMEMORY;
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_get_factory", "dispatch xbox_com=IDStorageFactoryX");
|
||||
return publish(factory, riid, ppv);
|
||||
}
|
||||
if (!IsEqualIID(riid, factory_iid) && !IsEqualIID(riid, IID_IUnknown)) {
|
||||
char iid[40];
|
||||
format_iid(riid, iid);
|
||||
|
||||
@@ -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
@@ -34,6 +34,8 @@ HRESULT WINAPI XTaskQueueCreate(bx::gdk::DispatchMode, bx::gdk::DispatchMode, vo
|
||||
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);
|
||||
@@ -103,6 +105,11 @@ constexpr GUID kNetworkingClsid = {0x37E56907, 0x2F10, 0x41E8, {0xB7, 0x2F, 0x36
|
||||
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;
|
||||
@@ -184,9 +191,11 @@ HRESULT WINAPI core_tq_submit(void*, void* queue, Port port, void* ctx, void (CA
|
||||
HRESULT WINAPI core_tq_submit_delayed(void*, void* queue, Port port, uint32_t delay_ms, void* ctx,
|
||||
void (CALLBACK* cb)(void*, bool)) {
|
||||
if (delay_ms > 0) {
|
||||
BX_VTABLE_STUB_LOG("IXGameRuntimeCore", 19, "XTaskQueueSubmitDelayedCallback(nonzero_delay)");
|
||||
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 XTaskQueueSubmitCallback(queue, port, ctx, cb);
|
||||
return XTaskQueueSubmitDelayedCallback(queue, port, delay_ms, ctx, cb);
|
||||
}
|
||||
bool WINAPI core_tq_get_process(void*, void** out) {
|
||||
return XTaskQueueGetCurrentProcessTaskQueue(out);
|
||||
@@ -292,6 +301,78 @@ const std::array<const void*, 12> kSystemVtbl = [] {
|
||||
}();
|
||||
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*) {}
|
||||
@@ -670,12 +751,6 @@ BX_HR(gs_files_folder_async, "IXGameSaveImpl2", 30, "XGameSaveFilesGetFolderWith
|
||||
BX_HR(gs_files_folder_result, "IXGameSaveImpl2", 31, "XGameSaveFilesGetFolderWithUiResult")
|
||||
BX_HR(gs_files_quota, "IXGameSaveImpl2", 32, "XGameSaveFilesGetRemainingQuota")
|
||||
|
||||
BX_HR(pk_create_monitor, "IXPackageImpl", 5, "XPackageCreateInstallationMonitor")
|
||||
BX_VOID(pk_close_monitor, "IXPackageImpl", 6, "XPackageCloseInstallationMonitorHandle")
|
||||
BX_VOID(pk_get_progress, "IXPackageImpl", 7, "XPackageGetInstallationProgress")
|
||||
BX_BOOL(pk_update_monitor, "IXPackageImpl", 8, "XPackageUpdateInstallationMonitor")
|
||||
BX_HR(pk_reg_progress, "IXPackageImpl", 9, "XPackageRegisterInstallationProgressChanged")
|
||||
BX_BOOL(pk_unreg_progress, "IXPackageImpl", 10, "XPackageUnregisterInstallationProgressChanged")
|
||||
BX_HR(pk_locale, "IXPackageImpl", 11, "XPackageGetUserLocale")
|
||||
BX_HR(pk_find_chunk, "IXPackageImpl", 12, "XPackageFindChunkAvailability")
|
||||
BX_HR(pk_enum_chunk, "IXPackageImpl", 13, "XPackageEnumerateChunkAvailability")
|
||||
@@ -689,16 +764,13 @@ BX_HR(pk_unknown_20, "IXPackageImpl", 20, "unknown")
|
||||
BX_HR(pk_unknown_21, "IXPackageImpl", 21, "unknown")
|
||||
BX_BOOL(pk_unreg_installed, "IXPackageImpl", 22, "XPackageUnregisterPackageInstalled")
|
||||
BX_HR(pk_unknown_27, "IXPackageImpl", 27, "unknown")
|
||||
BX_HR(pk_enum_packages, "IXPackageImpl", 28, "XPackageEnumeratePackages")
|
||||
BX_HR(pk_reg_installed, "IXPackageImpl", 29, "XPackageRegisterPackageInstalled")
|
||||
BX_HR(pk_write_stats, "IXPackageImpl", 30, "XPackageGetWriteStats")
|
||||
BX_HR(pk_unknown_31, "IXPackageImpl", 31, "unknown")
|
||||
BX_HR(pk_uninstall_uwp, "IXPackageImpl", 32, "XPackageUninstallUWPInstance")
|
||||
BX_HR(pk_enum_features, "IXPackageImpl", 33, "XPackageEnumerateFeatures")
|
||||
BX_HR(pk_uninstall, "IXPackageImpl", 34, "XPackageUninstallPackage")
|
||||
BX_HR(pk_enum_packages_2, "IXPackageImpl2", 35, "XPackageEnumeratePackages")
|
||||
BX_HR(pk_reg_installed_2, "IXPackageImpl2", 36, "XPackageRegisterPackageInstalled")
|
||||
BX_HR(pk_enum_packages_3, "IXPackageImpl3", 39, "XPackageEnumeratePackages")
|
||||
BX_HR(pk_reg_installed_3, "IXPackageImpl3", 40, "XPackageRegisterPackageInstalled")
|
||||
#undef BX_HR
|
||||
#undef BX_VOID
|
||||
@@ -746,12 +818,12 @@ const std::array<const void*, 42> kPackageVtbl = [] {
|
||||
v[0] = reinterpret_cast<const void*>(&package_query_interface);
|
||||
v[3] = reinterpret_cast<const void*>(&get_current_process_package_identifier);
|
||||
v[4] = reinterpret_cast<const void*>(&is_packaged_process);
|
||||
v[5] = reinterpret_cast<const void*>(&pk_create_monitor);
|
||||
v[6] = reinterpret_cast<const void*>(&pk_close_monitor);
|
||||
v[7] = reinterpret_cast<const void*>(&pk_get_progress);
|
||||
v[8] = reinterpret_cast<const void*>(&pk_update_monitor);
|
||||
v[9] = reinterpret_cast<const void*>(&pk_reg_progress);
|
||||
v[10] = reinterpret_cast<const void*>(&pk_unreg_progress);
|
||||
v[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);
|
||||
@@ -769,18 +841,18 @@ const std::array<const void*, 42> kPackageVtbl = [] {
|
||||
v[25] = reinterpret_cast<const void*>(&get_mount_path);
|
||||
v[26] = reinterpret_cast<const void*>(&close_mount_handle);
|
||||
v[27] = reinterpret_cast<const void*>(&pk_unknown_27);
|
||||
v[28] = reinterpret_cast<const void*>(&pk_enum_packages);
|
||||
v[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*>(&pk_enum_packages_2);
|
||||
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*>(&pk_enum_packages_3);
|
||||
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;
|
||||
@@ -797,6 +869,8 @@ 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},
|
||||
|
||||
@@ -22,9 +22,18 @@
|
||||
* 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.
|
||||
* - 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"
|
||||
|
||||
@@ -37,6 +46,7 @@
|
||||
#include <new>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace bx::gdk {
|
||||
namespace {
|
||||
@@ -250,6 +260,148 @@ void WINAPI close_mount_handle(void*, void* 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) {
|
||||
@@ -301,6 +453,7 @@ const void* const package_object = &kObject;
|
||||
void release_package_state() {
|
||||
std::lock_guard lock(mount_mutex);
|
||||
mounts.clear();
|
||||
monitors.clear();
|
||||
}
|
||||
|
||||
} // namespace bx::gdk
|
||||
@@ -106,4 +106,23 @@ 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
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "task_queue.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
@@ -43,7 +44,11 @@ public:
|
||||
std::unique_lock lock(mutex);
|
||||
if (closed && !is_completion) return false;
|
||||
if (mode == DispatchMode::immediate || (closed && mode == DispatchMode::manual)) {
|
||||
// No lane storage on these paths, so the submitting thread waits out
|
||||
// the remainder of the delay and then runs the callback itself.
|
||||
const uint64_t due_ms = task->due_ms;
|
||||
lock.unlock();
|
||||
wait_until(due_ms);
|
||||
task->run(owner->shared_from_this());
|
||||
return true;
|
||||
}
|
||||
@@ -62,6 +67,30 @@ public:
|
||||
SubmitThreadpoolWork(worker);
|
||||
}
|
||||
|
||||
bool due() const { return first && (first->due_ms == 0 || GetTickCount64() >= first->due_ms); }
|
||||
|
||||
// Sleep out the remainder of a GetTickCount64 deadline. Saturating: the
|
||||
// deadline can pass between the check and the clock read, and an unsigned
|
||||
// subtraction there would wrap to ~584 million years.
|
||||
static void wait_until(uint64_t due_ms) {
|
||||
for (;;) {
|
||||
const uint64_t now = GetTickCount64();
|
||||
if (due_ms == 0 || now >= due_ms) return;
|
||||
const uint64_t left = due_ms - now;
|
||||
// INFINITE would mean "wait forever", so a `left` of exactly
|
||||
// 0xFFFFFFFF would never wake to re-check the deadline.
|
||||
Sleep(finite_sleep_chunk_ms(left));
|
||||
}
|
||||
}
|
||||
|
||||
// FIFO: the head holds the lane until it is due, so a later task never
|
||||
// overtakes a delayed one. Wait only until that deadline, never spin.
|
||||
std::chrono::steady_clock::time_point head_due() const {
|
||||
const uint64_t now = GetTickCount64();
|
||||
const uint64_t left = first->due_ms > now ? first->due_ms - now : 0;
|
||||
return std::chrono::steady_clock::now() + std::chrono::milliseconds(left);
|
||||
}
|
||||
|
||||
void schedule_serial() {
|
||||
if (mode == DispatchMode::serialized && first && !serial_running && workers == 0) {
|
||||
schedule();
|
||||
@@ -92,11 +121,25 @@ public:
|
||||
bool dispatch(uint32_t timeout) {
|
||||
if (mode == DispatchMode::immediate) return false;
|
||||
std::unique_lock lock(mutex);
|
||||
const auto has_task = [this] { return closed || (first && !serial_running); };
|
||||
const auto has_task = [this] { return closed || (due() && !serial_running); };
|
||||
if (timeout == INFINITE) {
|
||||
ready.wait(lock, has_task);
|
||||
} else if (!ready.wait_for(lock, std::chrono::milliseconds(timeout), has_task)) {
|
||||
return false;
|
||||
while (!has_task()) {
|
||||
if (first && !serial_running) {
|
||||
ready.wait_until(lock, head_due());
|
||||
} else {
|
||||
ready.wait(lock);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout);
|
||||
while (!has_task()) {
|
||||
if (std::chrono::steady_clock::now() >= deadline) return false;
|
||||
auto wake = deadline;
|
||||
if (first && !serial_running) {
|
||||
wake = std::min(wake, head_due());
|
||||
}
|
||||
ready.wait_until(lock, wake);
|
||||
}
|
||||
}
|
||||
if (closed) return false;
|
||||
auto task = pop();
|
||||
@@ -118,6 +161,14 @@ public:
|
||||
std::unique_lock lock(lane.mutex);
|
||||
queue = lane.worker_owner;
|
||||
while (lane.first && !lane.serial_running) {
|
||||
// A delayed head must not run early. Wait on the condition variable
|
||||
// until its deadline (or a push changes the head) instead of popping
|
||||
// it, so FIFO order holds and nothing is dropped. Close drains what
|
||||
// was already accepted, as it did before delays existed.
|
||||
if (!lane.closed && !lane.due()) {
|
||||
lane.ready.wait_until(lock, lane.head_due());
|
||||
continue;
|
||||
}
|
||||
auto task = lane.pop();
|
||||
const bool serial = lane.mode == DispatchMode::serialized;
|
||||
lane.serial_running = serial;
|
||||
@@ -190,6 +241,7 @@ bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool i
|
||||
return queue->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
|
||||
}
|
||||
|
||||
|
||||
} // namespace bx::gdk
|
||||
|
||||
using namespace bx::gdk;
|
||||
@@ -237,12 +289,23 @@ bool WINAPI XTaskQueueDispatch(void* handle, Port port, uint32_t timeout) {
|
||||
return queue && queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
|
||||
}
|
||||
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
|
||||
CallbackTask::Callback callback);
|
||||
|
||||
HRESULT WINAPI XTaskQueueSubmitCallback(void* handle, Port port, void* context, CallbackTask::Callback callback) {
|
||||
return XTaskQueueSubmitDelayedCallback(handle, port, 0, context, callback);
|
||||
}
|
||||
|
||||
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
|
||||
CallbackTask::Callback callback) {
|
||||
if (!handle || port > Port::completion || !callback) return E_INVALIDARG;
|
||||
const auto queue = acquire_queue(handle);
|
||||
if (!queue) return E_HANDLE;
|
||||
auto task = std::unique_ptr<Task>(new (std::nothrow) CallbackTask(callback, context));
|
||||
if (!task) return E_OUTOFMEMORY;
|
||||
// delay_ms == 0 is due now, which is the common case and matches the old
|
||||
// immediate-submit behaviour. A nonzero delay is a GetTickCount64 deadline.
|
||||
task->due_ms = delay_ms == 0 ? 0 : GetTickCount64() + delay_ms;
|
||||
return submit(queue, port, std::move(task)) ? S_OK : E_HANDLE;
|
||||
}
|
||||
|
||||
|
||||
@@ -17,10 +17,26 @@ struct Task {
|
||||
virtual void run(const QueueRef& queue) = 0;
|
||||
virtual void cancel(const QueueRef& queue) { run(queue); }
|
||||
|
||||
// GetTickCount64 deadline; zero means due immediately.
|
||||
uint64_t due_ms = 0;
|
||||
std::unique_ptr<Task> next;
|
||||
};
|
||||
|
||||
QueueRef acquire_queue(void* handle);
|
||||
bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool is_completion = false);
|
||||
|
||||
// Largest finite Sleep() chunk. INFINITE (0xFFFFFFFF) means "wait forever", so
|
||||
// a delay whose remaining time is exactly INFINITE must never be passed to
|
||||
// Sleep: the wait would never wake to re-check the deadline, and the callback
|
||||
// would never run. Clamp every chunk to at most INFINITE - 1.
|
||||
inline constexpr uint32_t kMaxFiniteSleepMs = INFINITE - 1;
|
||||
|
||||
// Split a GetTickCount64 remainder into one finite Sleep() chunk. `left` is
|
||||
// uint64_t because a deadline subtraction can exceed 32 bits; the result is
|
||||
// always in [1, INFINITE - 1] for any positive `left`, so the caller's loop
|
||||
// always wakes up and re-checks the deadline.
|
||||
inline uint32_t finite_sleep_chunk_ms(uint64_t left) {
|
||||
return static_cast<uint32_t>(left < kMaxFiniteSleepMs ? left : kMaxFiniteSleepMs);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -798,6 +798,8 @@ HRESULT WINAPI XTaskQueueCreate(bx::gdk::DispatchMode, bx::gdk::DispatchMode, vo
|
||||
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 InitializeApiImpl(uint32_t gdk_ver, uint32_t gs_ver) {
|
||||
|
||||
+598
-122
@@ -1,6 +1,7 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
|
||||
@@ -10,35 +11,86 @@
|
||||
|
||||
namespace {
|
||||
constexpr SIZE_T small_page = 64 * 1024;
|
||||
constexpr SIZE_T large_page = 2 * 1024 * 1024;
|
||||
|
||||
struct PageBlock;
|
||||
|
||||
struct Page {
|
||||
PageBlock* block;
|
||||
HANDLE section;
|
||||
bool allocated;
|
||||
bool releasing;
|
||||
};
|
||||
|
||||
// One XMemAllocatePhysicalPages call: a single pagefile-backed section holding all its pages,
|
||||
// page i at offset i * 64 KB. One section per call, not per page, keeps a title that asks for
|
||||
// gigabytes at once (about 100,000 pages) within the host's open-file limit. A freed page stays
|
||||
// backed by the section until every page of its block is freed.
|
||||
struct PageBlock {
|
||||
ULONG_PTR first_tag;
|
||||
SIZE_T count;
|
||||
SIZE_T size;
|
||||
SIZE_T live;
|
||||
HANDLE section;
|
||||
Page* entries;
|
||||
PageBlock* next;
|
||||
};
|
||||
|
||||
ULONG64 page_offset(const Page* page) {
|
||||
return static_cast<ULONG64>(page - page->block->entries) * small_page;
|
||||
}
|
||||
|
||||
// A run of `pages` consecutive pages of one block (offsets page..page+pages-1), mapped as one view
|
||||
// at `address`. A title maps its page pool in long runs; one view per run keeps the number of
|
||||
// placeholder splits and MapViewOfFile3 calls (each a Wine server round trip) proportional to the
|
||||
// runs, not the pages. Unmapping part of a run unmaps the view and maps the remaining sub-runs again.
|
||||
struct View {
|
||||
Page* page;
|
||||
SIZE_T pages;
|
||||
BYTE* address;
|
||||
View* next;
|
||||
// Mapped into an XMEM_MAPPABLE reservation: unmapping restores the placeholder so the
|
||||
// range stays reserved and can be mapped again.
|
||||
bool preserve;
|
||||
};
|
||||
|
||||
uintptr_t view_begin(const View* view) { return reinterpret_cast<uintptr_t>(view->address); }
|
||||
uintptr_t view_end(const View* view) { return view_begin(view) + view->pages * small_page; }
|
||||
bool follows(const Page* before, const Page* after) {
|
||||
return after->block == before->block && after == before + 1;
|
||||
}
|
||||
|
||||
// An XMemVirtualAlloc(MEM_RESERVE, XMEM_MAPPABLE) range, held as a placeholder.
|
||||
struct Reservation {
|
||||
uintptr_t begin;
|
||||
uintptr_t end;
|
||||
SIZE_T page;
|
||||
DWORD protect;
|
||||
Reservation* next;
|
||||
};
|
||||
|
||||
SRWLOCK memory_lock = SRWLOCK_INIT;
|
||||
PageBlock* blocks = nullptr;
|
||||
View* views = nullptr;
|
||||
ULONG_PTR next_tag = 1;
|
||||
Reservation* reservations = nullptr;
|
||||
// Page tags are physical page numbers, which count 4 KiB frames: a 64 KiB page's number is a
|
||||
// multiple of 16. Titles rely on that: the target build keeps a page as the 21-bit `number >> 4`
|
||||
// and rebuilds it with `<< 4`, so consecutive numbers per 64 KiB page made sixteen pages collapse
|
||||
// into one. Each allocation also starts on a kTagAlignment boundary, so a title rounding its first
|
||||
// number down to a large page stays inside it; 0 stays unused, and every number fits the 25 bits
|
||||
// (21 + 4) the title keeps.
|
||||
constexpr ULONG_PTR kFramesPerPage = small_page / 4096; // 16
|
||||
constexpr ULONG_PTR kTagAlignment = 0x1000; // 256 pages = 16 MB, in frames
|
||||
constexpr ULONG_PTR kTagLimit = ULONG_PTR{1} << 25;
|
||||
ULONG_PTR next_tag = kTagAlignment;
|
||||
|
||||
// XMemAllocatePhysicalPages flags (authorized GDK documentation): 2 MB clusters, and the four
|
||||
// memory-bandwidth values, which only the Series X Advanced memory mode uses.
|
||||
// XMEM_2MB_CLUSTERS is MEM_2MB_PAGES; MEM_64K_PAGES is MEM_2MB_PAGES | MEM_PHYSICAL (authorized GDK
|
||||
// headers). Public samples pass MEM_64K_PAGES for 64 KB pages, so both bits together mean 64 KB
|
||||
// pages, and the 2 MB bit alone means 2 MB clusters.
|
||||
constexpr uint64_t xmem_2mb_clusters = 0x20000000;
|
||||
constexpr uint64_t mem_physical = 0x00400000;
|
||||
constexpr uint64_t mem_64k_pages = xmem_2mb_clusters | mem_physical;
|
||||
constexpr uint64_t xmem_bandwidth_bits = 0x380;
|
||||
|
||||
struct Lock {
|
||||
Lock() { AcquireSRWLockExclusive(&memory_lock); }
|
||||
@@ -49,11 +101,13 @@ using ReservePlaceholder = PVOID (WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG,
|
||||
MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
using ReplacePlaceholder = PVOID (WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG,
|
||||
ULONG, MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
using UnmapPreserving = BOOL (WINAPI*)(HANDLE, PVOID, ULONG);
|
||||
|
||||
struct PlaceholderApi {
|
||||
HMODULE kernel = GetModuleHandleW(L"kernelbase.dll");
|
||||
ReservePlaceholder reserve = resolve<ReservePlaceholder>("VirtualAlloc2");
|
||||
ReplacePlaceholder replace = resolve<ReplacePlaceholder>("MapViewOfFile3");
|
||||
UnmapPreserving unmap = resolve<UnmapPreserving>("UnmapViewOfFile2");
|
||||
|
||||
template<class Function>
|
||||
Function resolve(const char* name) const {
|
||||
@@ -61,35 +115,36 @@ struct PlaceholderApi {
|
||||
}
|
||||
};
|
||||
|
||||
// The public backlog defines the supported sizes. The flags accepted here
|
||||
// belong to BetterXen's synthetic fixtures, pending a public console flags ABI.
|
||||
SIZE_T page_size(uint64_t flags) {
|
||||
switch (flags) {
|
||||
case 0:
|
||||
case small_page: return small_page;
|
||||
case large_page: return large_page;
|
||||
default: return 0;
|
||||
const PlaceholderApi& placeholder_api() {
|
||||
static const PlaceholderApi api;
|
||||
return api;
|
||||
}
|
||||
|
||||
// The reservation holding all of [begin, end), or nullptr.
|
||||
Reservation* find_reservation(uintptr_t begin, uintptr_t end) {
|
||||
for (Reservation* r = reservations; r; r = r->next) {
|
||||
if (begin >= r->begin && end <= r->end && begin < end) return r;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Page* find_page(ULONG_PTR tag) {
|
||||
for (PageBlock* block = blocks; block; block = block->next) {
|
||||
if (tag >= block->first_tag && tag - block->first_tag < block->count) {
|
||||
Page* page = &block->entries[tag - block->first_tag];
|
||||
return page->section ? page : nullptr;
|
||||
if (tag >= block->first_tag && (tag - block->first_tag) % kFramesPerPage == 0 &&
|
||||
(tag - block->first_tag) / kFramesPerPage < block->count) {
|
||||
Page* page = &block->entries[(tag - block->first_tag) / kFramesPerPage];
|
||||
return page->allocated ? page : nullptr;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ULONG_PTR page_tag(const Page* page) {
|
||||
return page->block->first_tag + (page - page->block->entries);
|
||||
return page->block->first_tag + static_cast<ULONG_PTR>(page - page->block->entries) * kFramesPerPage;
|
||||
}
|
||||
|
||||
void delete_block(PageBlock* block) {
|
||||
for (SIZE_T i = 0; i < block->count; ++i) {
|
||||
if (block->entries[i].section) CloseHandle(block->entries[i].section);
|
||||
}
|
||||
if (block->section) CloseHandle(block->section);
|
||||
delete[] block->entries;
|
||||
delete block;
|
||||
}
|
||||
@@ -110,7 +165,11 @@ bool valid_span(PVOID base, SIZE_T count, SIZE_T size) {
|
||||
|
||||
bool remove_view(View** link) {
|
||||
View* view = *link;
|
||||
if (!UnmapViewOfFile(view->address)) return false;
|
||||
const bool unmapped = view->preserve
|
||||
? placeholder_api().unmap && placeholder_api().unmap(GetCurrentProcess(), view->address,
|
||||
MEM_PRESERVE_PLACEHOLDER)
|
||||
: UnmapViewOfFile(view->address) != 0;
|
||||
if (!unmapped) return false;
|
||||
*link = view->next;
|
||||
delete view;
|
||||
return true;
|
||||
@@ -129,9 +188,8 @@ PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
|
||||
|
||||
SIZE_T matched = 0;
|
||||
for (const View* view = views; view; view = view->next) {
|
||||
const auto address = reinterpret_cast<uintptr_t>(view->address);
|
||||
if (address >= begin && address < end && view->page->block->size == size) {
|
||||
++matched;
|
||||
if (view_begin(view) >= begin && view_end(view) <= end && view->page->block->size == size) {
|
||||
matched += view->pages;
|
||||
}
|
||||
}
|
||||
if (matched != count) {
|
||||
@@ -141,8 +199,7 @@ PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
|
||||
|
||||
for (View** link = &views; *link;) {
|
||||
View* view = *link;
|
||||
const auto address = reinterpret_cast<uintptr_t>(view->address);
|
||||
if (address >= begin && address < end && view->page->block->size == size) {
|
||||
if (view_begin(view) >= begin && view_end(view) <= end && view->page->block->size == size) {
|
||||
if (!remove_view(link)) return nullptr;
|
||||
} else {
|
||||
link = &view->next;
|
||||
@@ -151,50 +208,236 @@ PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
|
||||
return base;
|
||||
}
|
||||
|
||||
// Duplicate tags in `tags` are intentionally permitted so a single virtual span
|
||||
// can alias one physical page at multiple offsets (e.g. ring buffers / tiles).
|
||||
PVOID map_pages(PVOID address, SIZE_T count, uint64_t flags, const ULONG_PTR* tags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!valid_span(address, count, size)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
if (!tags) return unmap_span(static_cast<BYTE*>(address), count, size);
|
||||
|
||||
static const PlaceholderApi api;
|
||||
if (!api.reserve || !api.replace) {
|
||||
BX_STUB_LOG("xmem.dll", "MapViewOfFile3");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
View* pending = nullptr;
|
||||
for (SIZE_T i = count; i > 0; --i) {
|
||||
Page* page = find_page(tags[i - 1]);
|
||||
if (!page || page->block->size != size) {
|
||||
destroy_views(pending);
|
||||
// Builds one unlinked View per tag, in order, after checking that every tag names a live page.
|
||||
bool build_views(const ULONG_PTR* tags, SIZE_T count, bool preserve, View** out) {
|
||||
View* first = nullptr;
|
||||
View** tail = &first;
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
Page* page = find_page(tags[i]);
|
||||
if (!page) {
|
||||
destroy_views(first);
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return false;
|
||||
}
|
||||
auto* view = new (std::nothrow) View{page, 1, nullptr, nullptr, preserve};
|
||||
if (!view) {
|
||||
destroy_views(first);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return false;
|
||||
}
|
||||
*tail = view;
|
||||
tail = &view->next;
|
||||
}
|
||||
*out = first;
|
||||
return true;
|
||||
}
|
||||
|
||||
void publish(View* pending) {
|
||||
while (pending) {
|
||||
View* next = pending->next;
|
||||
pending->next = views;
|
||||
views = pending;
|
||||
pending = next;
|
||||
}
|
||||
}
|
||||
|
||||
// Maps the run [first, first + pages) at `address` inside a reservation. The range may cover one
|
||||
// placeholder or several (left by earlier mappings); each placeholder piece inside it is split out
|
||||
// where it extends past the range and replaced with one view, so a range inside one placeholder
|
||||
// becomes one view. Returns the unlinked chain of views (through `next`) and its tail in *tail,
|
||||
// or nullptr with the error set and nothing mapped.
|
||||
View* map_run(Page* first, SIZE_T pages, BYTE* address, DWORD protect, View** tail = nullptr) {
|
||||
const PlaceholderApi& api = placeholder_api();
|
||||
const uintptr_t begin = reinterpret_cast<uintptr_t>(address);
|
||||
const uintptr_t end = begin + pages * small_page;
|
||||
View* head = nullptr;
|
||||
View** link = &head;
|
||||
View* last = nullptr;
|
||||
for (uintptr_t at = begin; at < end;) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t piece_end = end;
|
||||
if (VirtualQuery(reinterpret_cast<void*>(at), ®ion, sizeof(region)) && region.State == MEM_RESERVE) {
|
||||
const uintptr_t region_end = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
if (region_end < piece_end) piece_end = region_end;
|
||||
}
|
||||
const SIZE_T piece_pages = (piece_end - at) / small_page;
|
||||
Page* piece_first = first + (at - begin) / small_page;
|
||||
auto* view = new (std::nothrow) View{piece_first, piece_pages, reinterpret_cast<BYTE*>(at), nullptr, true};
|
||||
if (!view) SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
if (view) VirtualFree(reinterpret_cast<void*>(at), piece_end - at, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER);
|
||||
if (!view || !api.replace(first->block->section, GetCurrentProcess(), reinterpret_cast<void*>(at),
|
||||
page_offset(piece_first), piece_end - at, MEM_REPLACE_PLACEHOLDER, protect,
|
||||
nullptr, 0)) {
|
||||
const DWORD error = GetLastError();
|
||||
delete view;
|
||||
while (head) {
|
||||
View* next = head->next;
|
||||
api.unmap(GetCurrentProcess(), head->address, MEM_PRESERVE_PLACEHOLDER);
|
||||
delete head;
|
||||
head = next;
|
||||
}
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
auto* view = new (std::nothrow) View{page, nullptr, pending};
|
||||
*link = view;
|
||||
link = &view->next;
|
||||
last = view;
|
||||
at = piece_end;
|
||||
}
|
||||
if (tail) *tail = last;
|
||||
return head;
|
||||
}
|
||||
|
||||
// The protection of the reservation holding `view` (the view was mapped with it).
|
||||
DWORD view_protect(const View* view) {
|
||||
const Reservation* r = find_reservation(view_begin(view), view_end(view));
|
||||
return r ? r->protect : PAGE_READWRITE;
|
||||
}
|
||||
|
||||
// Unmaps the pages of *link for which removed(page, page_address) is true. A view losing every
|
||||
// page is removed; one losing some (only in a reservation) is unmapped and its remaining sub-runs
|
||||
// are mapped again in its place. On return *link is the first view after the ones handled.
|
||||
template <class Removed>
|
||||
bool drop_pages(View**& link, Removed removed) {
|
||||
View* view = *link;
|
||||
SIZE_T gone = 0;
|
||||
for (SIZE_T i = 0; i < view->pages; ++i) gone += removed(view->page + i, view_begin(view) + i * small_page);
|
||||
if (gone == 0) {
|
||||
link = &view->next;
|
||||
return true;
|
||||
}
|
||||
if (gone == view->pages) return remove_view(link);
|
||||
if (!view->preserve) { // a span mapped without a reservation is unmapped as a whole
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return false;
|
||||
}
|
||||
const DWORD protect = view_protect(view);
|
||||
Page* first = view->page;
|
||||
const SIZE_T pages = view->pages;
|
||||
BYTE* address = view->address;
|
||||
if (!remove_view(link)) return false;
|
||||
for (SIZE_T i = 0; i < pages;) {
|
||||
if (removed(first + i, reinterpret_cast<uintptr_t>(address) + i * small_page)) {
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
SIZE_T j = i + 1;
|
||||
while (j < pages && !removed(first + j, reinterpret_cast<uintptr_t>(address) + j * small_page)) ++j;
|
||||
View* kept_tail = nullptr;
|
||||
View* kept = map_run(first + i, j - i, address + i * small_page, protect, &kept_tail);
|
||||
if (!kept) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "remapping %llu kept pages after a partial unmap failed error=%lu",
|
||||
static_cast<unsigned long long>(j - i), static_cast<unsigned long>(GetLastError()));
|
||||
bx_log_emit(BX_LOG_ERROR, "xmem", "physical_remap_failed", detail);
|
||||
return false;
|
||||
}
|
||||
kept_tail->next = *link;
|
||||
*link = kept;
|
||||
link = &kept_tail->next;
|
||||
i = j;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Unmaps every mapped page in [begin, end). Views in a reservation keep its placeholder.
|
||||
bool unmap_range(uintptr_t begin, uintptr_t end) {
|
||||
for (View** link = &views; *link;) {
|
||||
View* view = *link;
|
||||
if (view_end(view) <= begin || view_begin(view) >= end) {
|
||||
link = &view->next;
|
||||
continue;
|
||||
}
|
||||
if (!drop_pages(link, [&](const Page*, uintptr_t at) { return at >= begin && at < end; })) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Maps `count` pages (any order, duplicates allowed) at consecutive slots from `address`, one view
|
||||
// per run of consecutive pages of one block. On failure nothing stays mapped and the error is set.
|
||||
bool map_pages(Page* const* pages, SIZE_T count, BYTE* address, DWORD protect) {
|
||||
View* done = nullptr;
|
||||
for (SIZE_T i = 0; i < count;) {
|
||||
SIZE_T j = i + 1;
|
||||
while (j < count && follows(pages[j - 1], pages[j])) ++j;
|
||||
View* view_tail = nullptr;
|
||||
View* view = map_run(pages[i], j - i, address + i * small_page, protect, &view_tail);
|
||||
if (!view) {
|
||||
destroy_views(pending);
|
||||
const DWORD error = GetLastError();
|
||||
while (done) {
|
||||
View* next = done->next;
|
||||
placeholder_api().unmap(GetCurrentProcess(), done->address, MEM_PRESERVE_PLACEHOLDER);
|
||||
delete done;
|
||||
done = next;
|
||||
}
|
||||
SetLastError(error);
|
||||
return false;
|
||||
}
|
||||
view_tail->next = done;
|
||||
done = view;
|
||||
i = j;
|
||||
}
|
||||
publish(done);
|
||||
return true;
|
||||
}
|
||||
|
||||
// XMemMapPhysicalPages into an XMEM_MAPPABLE reservation. Pages already mapped in the range are
|
||||
// unmapped first; a NULL `tags` only unmaps. Duplicate tags alias one page at several offsets.
|
||||
PVOID map_reserved(Reservation* reservation, BYTE* base, SIZE_T count, const ULONG_PTR* tags) {
|
||||
if (reservation->page != small_page) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPages(MEM_2MB_PAGES)");
|
||||
SetLastError(ERROR_NOT_SUPPORTED);
|
||||
return nullptr;
|
||||
}
|
||||
const auto begin = reinterpret_cast<uintptr_t>(base);
|
||||
Page** pages = nullptr;
|
||||
if (tags) {
|
||||
pages = new (std::nothrow) Page*[count];
|
||||
if (!pages) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
pending = view;
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
pages[i] = find_page(tags[i]);
|
||||
if (!pages[i]) {
|
||||
delete[] pages;
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!unmap_range(begin, begin + count * small_page)) {
|
||||
const DWORD error = GetLastError();
|
||||
delete[] pages;
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
if (pages) {
|
||||
const bool mapped = map_pages(pages, count, base, reservation->protect);
|
||||
const DWORD error = GetLastError();
|
||||
delete[] pages;
|
||||
if (!mapped) {
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
// BetterXen extension, used by synthetic fixtures: with no address, reserve a fresh
|
||||
// placeholder of `count` pages and map `tags` into it. Unmapping such a span frees it.
|
||||
PVOID map_unreserved(SIZE_T count, const ULONG_PTR* tags) {
|
||||
const PlaceholderApi& api = placeholder_api();
|
||||
View* pending = nullptr;
|
||||
if (!build_views(tags, count, false, &pending)) return nullptr;
|
||||
|
||||
MEM_ADDRESS_REQUIREMENTS requirements{};
|
||||
requirements.Alignment = size;
|
||||
requirements.Alignment = small_page;
|
||||
MEM_EXTENDED_PARAMETER alignment{};
|
||||
alignment.Type = MemExtendedParameterAddressRequirements;
|
||||
alignment.Pointer = &requirements;
|
||||
auto* base = static_cast<BYTE*>(api.reserve(nullptr, address, count * size,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS,
|
||||
address ? nullptr : &alignment, address ? 0 : 1));
|
||||
auto* base = static_cast<BYTE*>(api.reserve(nullptr, nullptr, count * small_page,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, &alignment, 1));
|
||||
if (!base) {
|
||||
const DWORD error = GetLastError();
|
||||
destroy_views(pending);
|
||||
@@ -205,13 +448,13 @@ PVOID map_pages(PVOID address, SIZE_T count, uint64_t flags, const ULONG_PTR* ta
|
||||
BYTE* cursor = base;
|
||||
SIZE_T remaining = count;
|
||||
View* view = pending;
|
||||
for (; view; view = view->next, cursor += size, --remaining) {
|
||||
for (; view; view = view->next, cursor += small_page, --remaining) {
|
||||
const bool split = remaining > 1;
|
||||
if (split && !VirtualFree(cursor, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) break;
|
||||
if (!api.replace(view->page->section, nullptr, cursor, 0, size,
|
||||
if (split && !VirtualFree(cursor, small_page, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) break;
|
||||
if (!api.replace(view->page->block->section, GetCurrentProcess(), cursor, page_offset(view->page), small_page,
|
||||
MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) {
|
||||
const DWORD error = GetLastError();
|
||||
if (split) VirtualFree(cursor + size, 0, MEM_RELEASE);
|
||||
if (split) VirtualFree(cursor + small_page, 0, MEM_RELEASE);
|
||||
SetLastError(error);
|
||||
break;
|
||||
}
|
||||
@@ -228,31 +471,151 @@ PVOID map_pages(PVOID address, SIZE_T count, uint64_t flags, const ULONG_PTR* ta
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
while (pending) {
|
||||
View* next = pending->next;
|
||||
pending->next = views;
|
||||
views = pending;
|
||||
pending = next;
|
||||
}
|
||||
publish(pending);
|
||||
return base;
|
||||
}
|
||||
|
||||
bool have_placeholder_api() {
|
||||
const PlaceholderApi& api = placeholder_api();
|
||||
if (api.reserve && api.replace && api.unmap) return true;
|
||||
BX_STUB_LOG("xmem.dll", "MapViewOfFile3");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return false;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// Clean-room synthetic signatures modeled after public Win32 AWE
|
||||
// AllocateUserPhysicalPages / FreeUserPhysicalPages (memoryapi.h, [in, out]
|
||||
// page count pointer), pending a public console flags/signature ABI.
|
||||
extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
|
||||
uint64_t flags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
|
||||
namespace bx_xmem {
|
||||
|
||||
PVOID reserve_placeholder(PVOID address, SIZE_T size, uintptr_t highest) {
|
||||
const PlaceholderApi& api = placeholder_api();
|
||||
if (!have_placeholder_api()) return nullptr;
|
||||
const auto requested = reinterpret_cast<uintptr_t>(address);
|
||||
const uintptr_t begin = requested - requested % small_page;
|
||||
if (!size || size > std::numeric_limits<uintptr_t>::max() - requested - small_page) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
return nullptr;
|
||||
}
|
||||
const uintptr_t end = (requested + size + small_page - 1) / small_page * small_page;
|
||||
MEM_ADDRESS_REQUIREMENTS requirements{};
|
||||
requirements.Alignment = small_page;
|
||||
requirements.HighestEndingAddress = highest ? reinterpret_cast<PVOID>(highest) : nullptr;
|
||||
MEM_EXTENDED_PARAMETER parameter{};
|
||||
parameter.Type = MemExtendedParameterAddressRequirements;
|
||||
parameter.Pointer = &requirements;
|
||||
return api.reserve(GetCurrentProcess(), begin ? reinterpret_cast<PVOID>(begin) : nullptr, end - begin,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, begin ? nullptr : ¶meter,
|
||||
begin ? 0 : 1);
|
||||
}
|
||||
|
||||
PVOID reserve_mappable(PVOID address, SIZE_T size, SIZE_T page, DWORD protect, bool adopt, uintptr_t highest) {
|
||||
const PlaceholderApi& api = placeholder_api();
|
||||
const auto requested = reinterpret_cast<uintptr_t>(address);
|
||||
if (!have_placeholder_api()) return nullptr;
|
||||
if (adopt && (!address || requested % page != 0 || size % page != 0)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
if (!size || size > std::numeric_limits<uintptr_t>::max() - requested - page) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
// A reservation's base rounds down to its page size and its end rounds up.
|
||||
const uintptr_t begin = requested - requested % page;
|
||||
const uintptr_t end = (requested + size + page - 1) / page * page;
|
||||
|
||||
MEM_ADDRESS_REQUIREMENTS requirements{};
|
||||
requirements.Alignment = page;
|
||||
requirements.HighestEndingAddress = highest ? reinterpret_cast<PVOID>(highest) : nullptr;
|
||||
MEM_EXTENDED_PARAMETER alignment{};
|
||||
alignment.Type = MemExtendedParameterAddressRequirements;
|
||||
alignment.Pointer = &requirements;
|
||||
auto* reservation = new (std::nothrow) Reservation{};
|
||||
if (!reservation) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
PVOID base = nullptr;
|
||||
if (adopt) {
|
||||
// MEM_REPLACE_PLACEHOLDER: the title split this range out of its own placeholder; it
|
||||
// stays as it is and becomes mappable.
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(address, ®ion, sizeof(region)) || region.State != MEM_RESERVE
|
||||
|| reinterpret_cast<uintptr_t>(region.BaseAddress) != requested || region.RegionSize < size) {
|
||||
delete reservation;
|
||||
SetLastError(ERROR_INVALID_ADDRESS);
|
||||
return nullptr;
|
||||
}
|
||||
base = address;
|
||||
} else {
|
||||
base = api.reserve(GetCurrentProcess(), begin ? reinterpret_cast<PVOID>(begin) : nullptr,
|
||||
end - begin, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS,
|
||||
begin ? nullptr : &alignment, begin ? 0 : 1);
|
||||
}
|
||||
if (!base) {
|
||||
delete reservation;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
const auto b = reinterpret_cast<uintptr_t>(base);
|
||||
// A range the title released with VirtualFree may come back: drop stale records over it.
|
||||
for (Reservation** link = &reservations; *link;) {
|
||||
if ((*link)->begin < b + (end - begin) && b < (*link)->end) {
|
||||
Reservation* stale = *link;
|
||||
*link = stale->next;
|
||||
delete stale;
|
||||
} else {
|
||||
link = &(*link)->next;
|
||||
}
|
||||
}
|
||||
*reservation = {b, b + (end - begin), page, protect, reservations};
|
||||
reservations = reservation;
|
||||
return base;
|
||||
}
|
||||
|
||||
} // namespace bx_xmem
|
||||
|
||||
// Diagnostics (off unless BX_XMEM_TRACE=1): one line per map call (address, count, first and last
|
||||
// tag; Scatter: first and last slot too), up to 4000 calls.
|
||||
bool xmem_trace_on() {
|
||||
static const bool on = [] {
|
||||
char v[4];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_XMEM_TRACE", v, sizeof(v));
|
||||
return n > 0 && n < sizeof(v) && v[0] == '1';
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
void trace_map(const char* kind, const void* first_address, const void* last_address, ULONG_PTR count,
|
||||
const ULONG_PTR* tags) {
|
||||
static LONG traced = 0;
|
||||
if (!xmem_trace_on() || InterlockedIncrement(&traced) > 4000) return;
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "%s va=%p..%p count=%llu tags=%llx..%llx", kind, first_address, last_address,
|
||||
static_cast<unsigned long long>(count), tags ? static_cast<unsigned long long>(tags[0]) : 0ull,
|
||||
tags ? static_cast<unsigned long long>(tags[count - 1]) : 0ull);
|
||||
bx_log_emit(BX_LOG_INFO, "xmem", "map_trace", detail);
|
||||
}
|
||||
|
||||
// Authorized GDK documentation: XMemAllocatePhysicalPages(XMemFlags, NumberOfPages,
|
||||
// PageArray), in 64 KB pages. XMEM_2MB_CLUSTERS is not implemented.
|
||||
extern "C" BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR num_pages,
|
||||
PULONG_PTR page_array) {
|
||||
if ((flags & mem_64k_pages) == mem_64k_pages) flags &= ~mem_64k_pages; // 64 KB pages: the default
|
||||
if ((flags & ~(xmem_2mb_clusters | xmem_bandwidth_bits)) != 0 || !num_pages || !page_array
|
||||
|| !valid_span(nullptr, *num_pages, small_page)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
if (flags & xmem_2mb_clusters) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemAllocatePhysicalPages(XMEM_2MB_CLUSTERS)");
|
||||
SetLastError(ERROR_NOT_SUPPORTED);
|
||||
return FALSE;
|
||||
}
|
||||
const SIZE_T size = small_page;
|
||||
|
||||
Lock lock;
|
||||
const SIZE_T count = *num_pages;
|
||||
if (count > std::numeric_limits<ULONG_PTR>::max() - next_tag
|
||||
if (count > (kTagLimit - next_tag) / kFramesPerPage
|
||||
|| count > std::numeric_limits<SIZE_T>::max() / sizeof(Page)
|
||||
|| count > std::numeric_limits<uint64_t>::max() / size) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
@@ -260,6 +623,10 @@ extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR p
|
||||
}
|
||||
const uint64_t total_bytes = static_cast<uint64_t>(count) * size;
|
||||
if (!bx_xmem::try_reserve_physical(total_bytes)) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "XMemAllocatePhysicalPages flags=0x%llx pages=%llu exceeds the physical budget",
|
||||
static_cast<unsigned long long>(flags), static_cast<unsigned long long>(count));
|
||||
bx_log_emit(BX_LOG_WARN, "xmem", "physical_budget_exceeded", detail);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
@@ -270,49 +637,64 @@ extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR p
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
auto* block = new (std::nothrow) PageBlock{next_tag, count, size, count, entries, blocks};
|
||||
const HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE,
|
||||
static_cast<DWORD>(total_bytes >> 32),
|
||||
static_cast<DWORD>(total_bytes & 0xFFFFFFFFu), nullptr);
|
||||
if (!section) {
|
||||
const DWORD error = GetLastError();
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "CreateFileMappingW for %llu pages failed error=%lu",
|
||||
static_cast<unsigned long long>(count), static_cast<unsigned long>(error));
|
||||
bx_log_emit(BX_LOG_WARN, "xmem", "physical_pages_failed", detail);
|
||||
delete[] entries;
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
auto* block = new (std::nothrow) PageBlock{next_tag, count, size, count, section, entries, blocks};
|
||||
if (!block) {
|
||||
CloseHandle(section);
|
||||
delete[] entries;
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE,
|
||||
0, static_cast<DWORD>(size), nullptr);
|
||||
if (!section) {
|
||||
const DWORD error = GetLastError();
|
||||
delete_block(block);
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
entries[i] = {block, section, false};
|
||||
}
|
||||
for (SIZE_T i = 0; i < count; ++i) entries[i] = {block, true, false};
|
||||
|
||||
blocks = block;
|
||||
for (SIZE_T i = 0; i < count; ++i) page_array[i] = next_tag + i;
|
||||
next_tag += count;
|
||||
for (SIZE_T i = 0; i < count; ++i) page_array[i] = next_tag + i * kFramesPerPage;
|
||||
if (xmem_trace_on()) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "allocate flags=0x%llx count=%llu tags=%llx..%llx",
|
||||
static_cast<unsigned long long>(flags), static_cast<unsigned long long>(count),
|
||||
static_cast<unsigned long long>(next_tag),
|
||||
static_cast<unsigned long long>(next_tag + (count - 1) * kFramesPerPage));
|
||||
bx_log_emit(BX_LOG_INFO, "xmem", "alloc_trace", detail);
|
||||
}
|
||||
next_tag += count * kFramesPerPage;
|
||||
next_tag = (next_tag + kTagAlignment - 1) & ~(kTagAlignment - 1);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// Rejects unknown, wrong-size, or duplicate tags in `page_array` with
|
||||
// ERROR_INVALID_PARAMETER without mutating `page_array` or live views.
|
||||
extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
|
||||
uint64_t flags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
|
||||
// XMemFreePhysicalPages(NumberOfPages, PageArray). Unknown or duplicate tags in `page_array`
|
||||
// fail with ERROR_INVALID_PARAMETER without changing `page_array` or live views.
|
||||
extern "C" BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR page_array) {
|
||||
if (xmem_trace_on() && page_array && count) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "free count=%llu tags=%llx..%llx", static_cast<unsigned long long>(count),
|
||||
static_cast<unsigned long long>(page_array[0]), static_cast<unsigned long long>(page_array[count - 1]));
|
||||
bx_log_emit(BX_LOG_INFO, "xmem", "free_trace", detail);
|
||||
}
|
||||
if (!page_array || !valid_span(nullptr, count, small_page)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
const SIZE_T count = *num_pages;
|
||||
SIZE_T validated = 0;
|
||||
for (; validated < count; ++validated) {
|
||||
Page* page = find_page(page_array[validated]);
|
||||
if (!page || page->block->size != size || page->releasing) break;
|
||||
if (!page || page->releasing) break;
|
||||
page->releasing = true;
|
||||
}
|
||||
if (validated != count) {
|
||||
@@ -322,22 +704,17 @@ extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_
|
||||
}
|
||||
|
||||
for (View** link = &views; *link;) {
|
||||
if ((*link)->page->releasing) {
|
||||
if (!remove_view(link)) {
|
||||
const DWORD error = GetLastError();
|
||||
for (SIZE_T i = 0; i < count; ++i) find_page(page_array[i])->releasing = false;
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
} else {
|
||||
link = &(*link)->next;
|
||||
if (!drop_pages(link, [](const Page* page, uintptr_t) { return page->releasing; })) {
|
||||
const DWORD error = GetLastError();
|
||||
for (SIZE_T i = 0; i < count; ++i) find_page(page_array[i])->releasing = false;
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
Page* page = find_page(page_array[i]);
|
||||
CloseHandle(page->section);
|
||||
page->section = nullptr;
|
||||
page->allocated = false;
|
||||
--page->block->live;
|
||||
page_array[i] = 0;
|
||||
}
|
||||
@@ -350,18 +727,115 @@ extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_
|
||||
delete_block(block);
|
||||
}
|
||||
}
|
||||
bx_xmem::release_physical(static_cast<uint64_t>(count) * size);
|
||||
bx_xmem::release_physical(static_cast<uint64_t>(count) * small_page);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
extern "C" PVOID WINAPI XMemMapPhysicalPages(PVOID base, SIZE_T count, uint64_t flags,
|
||||
PULONG_PTR page_array) {
|
||||
return map_pages(base, count, flags, page_array);
|
||||
// XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray). The address must lie in an
|
||||
// XMemVirtualAlloc(MEM_RESERVE | MEM_64K_PAGES, XMEM_MAPPABLE) reservation. A NULL address is a
|
||||
// BetterXen extension (see map_unreserved); a span mapped that way is unmapped as a whole.
|
||||
extern "C" PVOID WINAPI XMemMapPhysicalPages(PVOID address, ULONG_PTR count, PULONG_PTR page_array) {
|
||||
if (count) trace_map("map", address, static_cast<BYTE*>(address) + (count - 1) * small_page, count, page_array);
|
||||
if (!valid_span(address, count, small_page)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
if (!have_placeholder_api()) return nullptr;
|
||||
Lock lock;
|
||||
auto* base = static_cast<BYTE*>(address);
|
||||
const auto begin = reinterpret_cast<uintptr_t>(address);
|
||||
if (address) {
|
||||
if (Reservation* reservation = find_reservation(begin, begin + count * small_page)) {
|
||||
return map_reserved(reservation, base, count, page_array);
|
||||
}
|
||||
if (!page_array) return unmap_span(base, count, small_page);
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
if (!page_array) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
return map_unreserved(count, page_array);
|
||||
}
|
||||
|
||||
extern "C" PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID base, SIZE_T count, uint64_t flags,
|
||||
PULONG_PTR page_array) {
|
||||
return map_pages(base, count, flags, page_array);
|
||||
// XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray): parallel arrays of
|
||||
// 64 KB slots in XMEM_MAPPABLE reservations and page tags. A NULL `page_array`, or a 0 tag,
|
||||
// unmaps the slot. All entries are checked before any is changed.
|
||||
static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_array);
|
||||
|
||||
extern "C" BOOL WINAPI XMemMapPhysicalPagesScatter(PVOID* addresses, ULONG_PTR count,
|
||||
PULONG_PTR page_array) {
|
||||
const BOOL ok = scatter_impl(addresses, count, page_array);
|
||||
if (!ok) {
|
||||
const DWORD error = GetLastError();
|
||||
static LONG logged = 0;
|
||||
if (InterlockedIncrement(&logged) <= 32) {
|
||||
// The first entry that is not a mappable 64 KB slot or names an unknown page.
|
||||
ULONG_PTR bad = count;
|
||||
for (ULONG_PTR k = 0; addresses && k < count; ++k) {
|
||||
const auto slot = reinterpret_cast<uintptr_t>(addresses[k]);
|
||||
Lock lock;
|
||||
const bool slot_ok = slot % small_page == 0 && find_reservation(slot, slot + small_page);
|
||||
const bool page_ok = !page_array || !page_array[k] || find_page(page_array[k]);
|
||||
if (!slot_ok || !page_ok) { bad = k; break; }
|
||||
}
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "scatter of %llu slots failed error=%lu; first bad entry %llu: slot %p tag 0x%llx",
|
||||
static_cast<unsigned long long>(count), static_cast<unsigned long>(error),
|
||||
static_cast<unsigned long long>(bad), bad < count ? addresses[bad] : nullptr,
|
||||
bad < count && page_array ? static_cast<unsigned long long>(page_array[bad]) : 0ull);
|
||||
bx_log_emit(BX_LOG_WARN, "xmem", "scatter_failed", detail);
|
||||
}
|
||||
SetLastError(error);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_array) {
|
||||
if (addresses && count) trace_map("scatter", addresses[0], addresses[count - 1], count, page_array);
|
||||
if (!addresses || !count) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
if (!have_placeholder_api()) return FALSE;
|
||||
Lock lock;
|
||||
for (ULONG_PTR i = 0; i < count; ++i) {
|
||||
const auto slot = reinterpret_cast<uintptr_t>(addresses[i]);
|
||||
Reservation* reservation = slot % small_page == 0 ? find_reservation(slot, slot + small_page) : nullptr;
|
||||
if (!reservation || (page_array && page_array[i] && !find_page(page_array[i]))) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
if (reservation->page != small_page) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPagesScatter(MEM_2MB_PAGES)");
|
||||
SetLastError(ERROR_NOT_SUPPORTED);
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
// Entries whose slots and pages both advance by one form a run, unmapped and mapped at once.
|
||||
for (ULONG_PTR i = 0; i < count;) {
|
||||
auto* slot = static_cast<BYTE*>(addresses[i]);
|
||||
const auto begin = reinterpret_cast<uintptr_t>(slot);
|
||||
const ULONG_PTR tag = page_array ? page_array[i] : 0;
|
||||
const Reservation* reservation = find_reservation(begin, begin + small_page);
|
||||
ULONG_PTR j = i + 1;
|
||||
while (j < count && reinterpret_cast<uintptr_t>(addresses[j]) == begin + (j - i) * small_page &&
|
||||
find_reservation(begin, begin + (j - i + 1) * small_page) == reservation &&
|
||||
(tag ? page_array[j] == tag + (j - i) * kFramesPerPage && find_page(page_array[j]) &&
|
||||
follows(find_page(page_array[j - 1]), find_page(page_array[j]))
|
||||
: !(page_array && page_array[j]))) {
|
||||
++j;
|
||||
}
|
||||
if (!unmap_range(begin, begin + (j - i) * small_page)) return FALSE;
|
||||
if (tag) {
|
||||
View* view = map_run(find_page(tag), j - i, slot, reservation->protect);
|
||||
if (!view) return FALSE;
|
||||
publish(view);
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info) {
|
||||
@@ -369,15 +843,17 @@ extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info
|
||||
|
||||
Lock lock;
|
||||
for (const View* view = views; view; view = view->next) {
|
||||
const auto base = reinterpret_cast<uintptr_t>(view->address);
|
||||
const SIZE_T size = view->page->block->size;
|
||||
if (va >= base && va - base < size) {
|
||||
if (va >= view_begin(view) && va < view_end(view)) {
|
||||
// Reported per 64 KB page, as when every page had its own view.
|
||||
const SIZE_T index = (va - view_begin(view)) / small_page;
|
||||
const uintptr_t base = view_begin(view) + index * small_page;
|
||||
const SIZE_T size = view->page->block->size;
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(view->address, ®ion, sizeof(region))
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(base), ®ion, sizeof(region))
|
||||
|| region.AllocationBase != view->address || region.Type != MEM_MAPPED) {
|
||||
return 0;
|
||||
}
|
||||
*out_info = {base, size, size, region.Protect, region.Type, page_tag(view->page)};
|
||||
*out_info = {base, size, size, region.Protect, region.Type, page_tag(view->page + index)};
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
+134
-20
@@ -2,6 +2,7 @@
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
@@ -63,6 +64,10 @@ CommitTable virtual_commits;
|
||||
uint64_t heap_bytes = 0;
|
||||
uint64_t virtual_bytes = 0;
|
||||
uint64_t physical_bytes = 0;
|
||||
/* Bytes admitted through bx_xmem_try_charge_external() on behalf of other
|
||||
* DLLs (e.g. d3d12_xs private host heaps). Counted in can_commit so both
|
||||
* allocation orders (graphics-first or xmem-first) obey one title cap. */
|
||||
uint64_t external_bytes = 0;
|
||||
uint64_t peak_bytes = 0;
|
||||
|
||||
uint64_t title_limit() {
|
||||
@@ -72,12 +77,12 @@ uint64_t title_limit() {
|
||||
|
||||
bool can_commit(uint64_t bytes) {
|
||||
const uint64_t limit = title_limit();
|
||||
const uint64_t used = heap_bytes + virtual_bytes + physical_bytes;
|
||||
const uint64_t used = heap_bytes + virtual_bytes + physical_bytes + external_bytes;
|
||||
return used <= limit && bytes <= limit - used;
|
||||
}
|
||||
|
||||
void update_peak() {
|
||||
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes);
|
||||
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes + external_bytes);
|
||||
}
|
||||
|
||||
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
|
||||
@@ -110,14 +115,29 @@ bool refresh_virtual_commits() {
|
||||
return true;
|
||||
}
|
||||
|
||||
void report_unsupported_host_hooks() {
|
||||
static const bool reported = [] {
|
||||
if (GetProcAddress(GetModuleHandleW(nullptr), "__XMemAllocationHooks__")) {
|
||||
BX_STUB_LOG("xmem.dll", "__XMemAllocationHooks__");
|
||||
// XMEM_SET_ALLOCATION_HOOKS (xmem.h, authorized GDK documentation): the title exports
|
||||
// `__XMemAllocationHooks__ = { AllocRoutine, FreeRoutine }`, and XMemAlloc / XMemFree call those
|
||||
// routines instead of the default allocator. A hook usually handles the allocations it cares
|
||||
// about and passes the rest to XMemAllocDefault / XMemFreeDefault.
|
||||
struct AllocationHooks {
|
||||
PVOID (WINAPI* alloc)(SIZE_T size, ULONGLONG attributes);
|
||||
VOID (WINAPI* free)(PVOID address, ULONGLONG attributes);
|
||||
};
|
||||
|
||||
const AllocationHooks& title_hooks() {
|
||||
static const AllocationHooks hooks = [] {
|
||||
AllocationHooks found{};
|
||||
const auto* exported = reinterpret_cast<const AllocationHooks*>(
|
||||
reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(nullptr), "__XMemAllocationHooks__")));
|
||||
if (exported) found = *exported;
|
||||
if (found.alloc || found.free) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "alloc=%d free=%d", found.alloc ? 1 : 0, found.free ? 1 : 0);
|
||||
bx_log_emit(BX_LOG_INFO, "xmem", "allocation_hooks", detail);
|
||||
}
|
||||
return true;
|
||||
return found;
|
||||
}();
|
||||
(void)reported;
|
||||
return hooks;
|
||||
}
|
||||
|
||||
SIZE_T page_size() {
|
||||
@@ -168,29 +188,94 @@ VOID WINAPI XMemFreeDefault(PVOID address, uint64_t /*attributes*/) {
|
||||
}
|
||||
|
||||
PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes) {
|
||||
report_unsupported_host_hooks();
|
||||
if (const auto alloc = title_hooks().alloc) return alloc(size, attributes);
|
||||
return XMemAllocDefault(size, attributes);
|
||||
}
|
||||
|
||||
VOID WINAPI XMemFree(PVOID address, uint64_t attributes) {
|
||||
report_unsupported_host_hooks();
|
||||
if (const auto free_routine = title_hooks().free) {
|
||||
free_routine(address, attributes);
|
||||
return;
|
||||
}
|
||||
XMemFreeDefault(address, attributes);
|
||||
}
|
||||
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWORD protect) {
|
||||
/*
|
||||
* XMemVirtualAlloc(BaseAddress, Size, AllocationType, XMemFlags, PageProtection), as the
|
||||
* authorized GDK documentation gives it. AllocationType may carry MEM_64K_PAGES (0x20400000) or
|
||||
* MEM_2MB_PAGES (0x20000000). An XMEM_MAPPABLE (0x20) reservation is a placeholder for
|
||||
* XMemMapPhysicalPages. The other XMemFlags (CPU, graphics, address-width limits) select
|
||||
* console memory types the host does not distinguish, so plain reservations and commits
|
||||
* ignore them.
|
||||
*/
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, uint64_t xmem_flags,
|
||||
DWORD protect) {
|
||||
constexpr DWORD mem_64k_pages = 0x20400000;
|
||||
constexpr DWORD mem_2mb_pages = 0x20000000;
|
||||
constexpr DWORD mem_reserve_placeholder = 0x00040000;
|
||||
constexpr DWORD mem_replace_placeholder = 0x00004000;
|
||||
constexpr uint64_t xmem_mappable = 0x20;
|
||||
constexpr uint64_t xmem_graphics_32bit_address = 0x7;
|
||||
// PAGE_GRAPHICS_* bits (0x800 and up) set the GPU view, which the host does not have; the
|
||||
// CPU protection is the low byte.
|
||||
const DWORD cpu_protect = protect & 0xFF;
|
||||
const uintptr_t highest = (xmem_flags & xmem_graphics_32bit_address) == xmem_graphics_32bit_address
|
||||
? 0xFFFFFFFFull : 0;
|
||||
if (xmem_flags & xmem_mappable) {
|
||||
const SIZE_T mappable_page = (alloc_type & mem_64k_pages) == mem_64k_pages ? 64 * 1024
|
||||
: (alloc_type & mem_2mb_pages) ? 2 * 1024 * 1024 : 0;
|
||||
if (!mappable_page || !(alloc_type & MEM_RESERVE) || (alloc_type & MEM_COMMIT)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
return bx_xmem::reserve_mappable(address, size, mappable_page, cpu_protect,
|
||||
(alloc_type & mem_replace_placeholder) != 0, highest);
|
||||
}
|
||||
// A GPU-only reservation of 64 KiB or 2 MiB pages (no CPU access, a PAGE_GRAPHICS_* bit set) is
|
||||
// a GPU address window the title fills with CopyPageMappingsX / CopyPageMappingsBatchX. It is
|
||||
// reserved as a mappable placeholder so the page-pool pages can be mapped into it; the views
|
||||
// are CPU readable and writable, since BetterXen works the GPU side through CPU addresses.
|
||||
const bool large_pages = (alloc_type & mem_64k_pages) == mem_64k_pages || (alloc_type & mem_2mb_pages);
|
||||
if (large_pages && (alloc_type & MEM_RESERVE) && !(alloc_type & (MEM_COMMIT | mem_replace_placeholder)) &&
|
||||
cpu_protect == PAGE_NOACCESS && (protect & ~0xFFu) != 0) {
|
||||
const SIZE_T window_page = (alloc_type & mem_64k_pages) == mem_64k_pages ? 64 * 1024 : 2 * 1024 * 1024;
|
||||
PVOID window = bx_xmem::reserve_mappable(address, size, window_page, PAGE_READWRITE, false, highest);
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "GPU window %p size=0x%llx page=0x%llx flags=0x%llx protect=0x%lx -> %p",
|
||||
address, static_cast<unsigned long long>(size), static_cast<unsigned long long>(window_page),
|
||||
static_cast<unsigned long long>(xmem_flags), static_cast<unsigned long>(protect), window);
|
||||
bx_log_emit(window ? BX_LOG_INFO : BX_LOG_WARN, "xmem", "gpu_window", detail);
|
||||
return window;
|
||||
}
|
||||
if (alloc_type & mem_reserve_placeholder) {
|
||||
if ((alloc_type & (MEM_COMMIT | mem_replace_placeholder)) || !(alloc_type & MEM_RESERVE)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
return bx_xmem::reserve_placeholder(address, size, highest);
|
||||
}
|
||||
if (alloc_type & mem_replace_placeholder) {
|
||||
// Committing over a title-managed placeholder is not implemented (no caller seen yet).
|
||||
BX_STUB_LOG("xmem.dll", "XMemVirtualAlloc(MEM_REPLACE_PLACEHOLDER)");
|
||||
SetLastError(ERROR_NOT_SUPPORTED);
|
||||
return nullptr;
|
||||
}
|
||||
/* Strip console-only high bits before forwarding to standard Win32 VirtualAlloc. */
|
||||
DWORD win_alloc = alloc_type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET | MEM_TOP_DOWN);
|
||||
if (win_alloc == 0) win_alloc = MEM_COMMIT | MEM_RESERVE;
|
||||
/* Console callers may pass multi-bit Xbox memory attributes (e.g. 0x21) in arg 4;
|
||||
* valid Win32 base page protections are a single power-of-two bit in 0x01..0x80. */
|
||||
DWORD low_prot = protect & 0xFFu;
|
||||
DWORD win_prot = (low_prot != 0 && (low_prot & (low_prot - 1)) == 0)
|
||||
? (protect & (0xFFu | PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE))
|
||||
: PAGE_READWRITE;
|
||||
const DWORD win_prot = protect & (0xFFu | PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE);
|
||||
/* MEM_RESET combined with MEM_COMMIT is rejected by Win32 VirtualAlloc, so returning
|
||||
* early here cannot commit pages outside the working-set budget. */
|
||||
if (!(win_alloc & MEM_COMMIT) || (win_alloc & MEM_RESET)) {
|
||||
return VirtualAlloc(address, size, win_alloc, win_prot);
|
||||
PVOID result = VirtualAlloc(address, size, win_alloc, win_prot);
|
||||
if (size >= (SIZE_T{256} << 20)) {
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "reserve %p size=0x%llx type=0x%lx flags=0x%llx protect=0x%lx -> %p",
|
||||
address, static_cast<unsigned long long>(size), static_cast<unsigned long>(alloc_type),
|
||||
static_cast<unsigned long long>(xmem_flags), static_cast<unsigned long>(protect), result);
|
||||
bx_log_emit(BX_LOG_INFO, "xmem", "large_reservation", detail);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const uintptr_t requested = reinterpret_cast<uintptr_t>(address);
|
||||
@@ -290,7 +375,7 @@ BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
|
||||
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes + external_bytes, physical_bytes, peak_bytes};
|
||||
std::memset(out_stats, 0, stats_size);
|
||||
std::memcpy(out_stats, &stats, sizeof(stats));
|
||||
return TRUE;
|
||||
@@ -306,10 +391,39 @@ void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats) {
|
||||
// The internal ABI has no error return. Preserve the most recent
|
||||
// accounting snapshot if refreshing it runs out of bookkeeping memory.
|
||||
std::lock_guard guard(usage_lock);
|
||||
*out_stats = {title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
|
||||
*out_stats = {title_limit(), heap_bytes + virtual_bytes + external_bytes, physical_bytes, peak_bytes};
|
||||
}
|
||||
}
|
||||
|
||||
int bx_xmem_try_charge_external(uint64_t bytes) {
|
||||
std::lock_guard guard(usage_lock);
|
||||
if (!can_commit(bytes)) {
|
||||
if (!refresh_virtual_commits()) {
|
||||
// Bookkeeping ran out of memory: not a budget decision, so say so.
|
||||
bx_log_emit(BX_LOG_ERROR, "xmem", "external_charge",
|
||||
"refresh_virtual_commits failed; charge refused without a budget check");
|
||||
return 0;
|
||||
}
|
||||
if (!can_commit(bytes)) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
external_bytes += bytes;
|
||||
update_peak();
|
||||
return 1;
|
||||
}
|
||||
|
||||
void bx_xmem_release_charge_external(uint64_t bytes) {
|
||||
std::lock_guard guard(usage_lock);
|
||||
if (bytes > external_bytes) {
|
||||
// Refuse: zeroing would also drop other owners' outstanding charges.
|
||||
bx_log_emit(BX_LOG_ERROR, "xmem", "external_charge",
|
||||
"release exceeds outstanding external charge; counter left unchanged");
|
||||
return;
|
||||
}
|
||||
external_bytes -= bytes;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
namespace bx_xmem {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#ifndef BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
#define BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace bx_xmem {
|
||||
@@ -10,6 +12,18 @@ namespace bx_xmem {
|
||||
bool try_reserve_physical(uint64_t bytes);
|
||||
void release_physical(uint64_t bytes);
|
||||
|
||||
// Reserves an XMEM_MAPPABLE range as a placeholder that XMemMapPhysicalPages maps into, and
|
||||
// records its page size and the protection mapped views get. Returns the base, or NULL with
|
||||
// the Win32 error set.
|
||||
// With `adopt`, `address` is already a placeholder the title split out of its own
|
||||
// MEM_RESERVE_PLACEHOLDER reservation (MEM_REPLACE_PLACEHOLDER) and is only recorded. A non-zero
|
||||
// `highest` keeps a new reservation at or below that address (XMEM_GRAPHICS_32BIT_ADDRESS).
|
||||
PVOID reserve_mappable(PVOID address, SIZE_T size, SIZE_T page, DWORD protect, bool adopt, uintptr_t highest);
|
||||
|
||||
// A MEM_RESERVE_PLACEHOLDER reservation the title manages itself (split with VirtualFree and
|
||||
// MEM_PRESERVE_PLACEHOLDER). It is not recorded.
|
||||
PVOID reserve_placeholder(PVOID address, SIZE_T size, uintptr_t highest);
|
||||
|
||||
} // namespace bx_xmem
|
||||
|
||||
#endif // BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
@@ -10,3 +10,65 @@ Every directory matching `test_*/CMakeLists.txt` is **auto-discovered** by `test
|
||||
```sh
|
||||
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_<shim>.exe
|
||||
```
|
||||
|
||||
## Exit Status: Pass, Fail, and Unavailable
|
||||
|
||||
`bx-cli run` normally returns the guest's exit status. A timeout returns 124, a signal
|
||||
returns 128 plus its number, and a cleanup failure raises an otherwise successful status
|
||||
to at least 1. Fixtures that cannot reach a conclusion on the host report **exit 77**
|
||||
and print `SKIP: <reason>` on stdout; for example
|
||||
`test_d3dmetal_gpu_limits` skips when `d3d12.dll`, device creation, or shader model 6.6 is
|
||||
unavailable.
|
||||
|
||||
A skip is **not** a pass and **not** a failure. AGENTS.md §5 forbids counting a skipped test
|
||||
as a pass, so record the three outcomes separately:
|
||||
|
||||
```sh
|
||||
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin \
|
||||
--log /tmp/bx-test.jsonl --exe build-shims/bin/test_<shim>.exe
|
||||
status=$?
|
||||
case $status in
|
||||
0) echo "PASS: test_<shim>" ;;
|
||||
77) echo "UNAVAILABLE (skip): test_<shim> — see the SKIP line above" ;;
|
||||
*) echo "FAIL: test_<shim> (exit $status)" ;;
|
||||
esac
|
||||
```
|
||||
|
||||
`bx-cli` does not itself reinterpret 77 (it is the guest's own status, and other fixtures use
|
||||
their own conventions), so always read the status before reporting a run. For a fixture that
|
||||
adopts this protocol, printing a `SKIP:` line without exit 77, or exiting 77 without one, is a
|
||||
defect. Older per-check skip conventions, such as `test_d3d12_xs`, are separate: its `SKIP:`
|
||||
lines are informational and the fixture exits according to `g_failures`.
|
||||
|
||||
## M2 First-Frame Fixture
|
||||
|
||||
The M2 fixture requires both the placed-resource and PresentX headers. Its CMake target fails
|
||||
configuration if either provider contract is missing; the fixture must not be silently skipped.
|
||||
Run it with a D3DMetal bottle:
|
||||
|
||||
```sh
|
||||
target/debug/bx-cli run --bottle <d3dmetal_bottle> --backend d3dmetal \
|
||||
--shims build-shims/bin --log /tmp/bx-m2-first-frame.jsonl \
|
||||
--exe build-shims/bin/test_m2_first_frame.exe
|
||||
```
|
||||
|
||||
Replace `<d3dmetal_bottle>` with the installed CrossOver bottle name.
|
||||
|
||||
To verify that the pixel comparison detects a mismatch, set the injection variable in the
|
||||
launcher environment and opt into environment inheritance. `env -i` keeps this test-only
|
||||
variable and the listed runtime essentials from exposing unrelated host environment values to
|
||||
the guest:
|
||||
|
||||
```sh
|
||||
env -i HOME="$HOME" USER="$USER" LOGNAME="$LOGNAME" TMPDIR=/tmp LANG=C \
|
||||
PATH=/usr/bin:/bin:/usr/sbin:/sbin \
|
||||
BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH=1 \
|
||||
target/debug/bx-cli run --inherit-env --bottle <d3dmetal_bottle> --backend d3dmetal \
|
||||
--shims build-shims/bin --log /tmp/bx-m2-first-frame-negative.jsonl \
|
||||
--exe build-shims/bin/test_m2_first_frame.exe
|
||||
```
|
||||
|
||||
Replace `<d3dmetal_bottle>` with the installed CrossOver bottle name.
|
||||
|
||||
The negative control should print `NOTE: pixel mismatch control armed` and exit 1.
|
||||
The `pixel_readback` checkpoint should report `pixel (0,0) expected 01234567 got 9f598b46`.
|
||||
@@ -0,0 +1,2 @@
|
||||
add_executable(test_acphal_default_heap main.cpp)
|
||||
target_link_libraries(test_acphal_default_heap PRIVATE acphal kernel32)
|
||||
@@ -0,0 +1,90 @@
|
||||
// AcpHal's default APU heap, in a fresh process: a title that allocates shape contexts before
|
||||
// any ApuCreateHeap gets a 64 MB default heap (BetterXen's stand-in for the console's default
|
||||
// non-cached APU heap). test_audio_input creates its own heap first, so this branch needs a
|
||||
// process of its own.
|
||||
//
|
||||
// Expected values come from this file: 64 MiB is the documented-in-CHANGELOG default, so shape
|
||||
// contexts of exactly 64 MiB must fit and 64 MiB + 64 bytes must not.
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void*);
|
||||
HRESULT WINAPI AcpHalReleaseShapeContexts(void);
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t, uint32_t);
|
||||
void* WINAPI ApuMapApuAddress(uint32_t);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
int g_failures = 0;
|
||||
void check(bool ok, const char* what) {
|
||||
if (!ok) {
|
||||
++g_failures;
|
||||
std::printf("FAIL: test_acphal_default_heap: %s\n", what);
|
||||
}
|
||||
}
|
||||
|
||||
struct ShapeContexts {
|
||||
uint32_t counts[6]; // SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM
|
||||
void* arrays[6];
|
||||
uint32_t apu[6];
|
||||
};
|
||||
static_assert(sizeof(ShapeContexts) == 96, "SHAPE_CONTEXTS");
|
||||
|
||||
constexpr uint32_t kXmaBytes = 64;
|
||||
constexpr uint32_t kDefaultHeap = 64u << 20;
|
||||
|
||||
std::string read_log() {
|
||||
char path[MAX_PATH];
|
||||
std::string text;
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return text;
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) return text;
|
||||
char buf[65536];
|
||||
DWORD got = 0;
|
||||
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got) text.append(buf, got);
|
||||
CloseHandle(f);
|
||||
return text;
|
||||
}
|
||||
|
||||
size_t count_of(const std::string& text, const char* needle) {
|
||||
size_t n = 0;
|
||||
for (size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
char probe[8];
|
||||
if (GetEnvironmentVariableA("BX_LOG_FILE", probe, sizeof(probe)) == 0) {
|
||||
std::printf("FAIL: test_acphal_default_heap: BX_LOG_FILE must be set (run under bx-cli run --log)\n");
|
||||
return 1;
|
||||
}
|
||||
// No ApuCreateHeap. One XMA element more than 64 MiB holds does not fit the default heap...
|
||||
ShapeContexts too_big{};
|
||||
too_big.counts[4] = kDefaultHeap / kXmaBytes + 1;
|
||||
check(AcpHalAllocateShapeContexts(&too_big) == E_OUTOFMEMORY, "64 MiB + 64 bytes exceeds the default heap");
|
||||
// ...and exactly 64 MiB does (the failed attempt above left nothing allocated).
|
||||
ShapeContexts exact{};
|
||||
exact.counts[4] = kDefaultHeap / kXmaBytes;
|
||||
check(AcpHalAllocateShapeContexts(&exact) == S_OK && exact.arrays[4] && exact.apu[4],
|
||||
"exactly 64 MiB of shape contexts fits the default heap");
|
||||
check(exact.apu[4] && ApuMapApuAddress(exact.apu[4]) == exact.arrays[4], "the shape array is an APU heap allocation");
|
||||
// The default heap is the heap: a later ApuCreateHeap finds one already created.
|
||||
check(ApuCreateHeap(64, 64) == HRESULT_FROM_WIN32(ERROR_BUSY), "ApuCreateHeap after the default heap reports busy");
|
||||
check(AcpHalReleaseShapeContexts() == S_OK, "release");
|
||||
const std::string log = read_log();
|
||||
check(count_of(log, "\"event\":\"apu_default_heap\"") == 1, "the default heap is created once and logged");
|
||||
if (g_failures) {
|
||||
std::printf("FAIL: test_acphal_default_heap (%d failed)\n", g_failures);
|
||||
return 1;
|
||||
}
|
||||
std::printf("PASS: test_acphal_default_heap\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -1,12 +1,17 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI AcpHalCreate(void**);
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void*);
|
||||
HRESULT WINAPI AcpHalReleaseShapeContexts(void);
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t, uint32_t);
|
||||
HRESULT WINAPI ApuAlloc(void**, uint32_t*, uint32_t, uint32_t);
|
||||
HRESULT WINAPI ApuFree(void*);
|
||||
@@ -29,17 +34,133 @@ HRESULT WINAPI XDspDisconnect(void*);
|
||||
|
||||
namespace {
|
||||
void WINAPI dummy_device_callback(uint64_t, void*, void*, uint64_t, uint32_t, uint32_t) {}
|
||||
|
||||
bool file_contains(const char* path, uint64_t offset, const char* needle_a, const char* needle_b) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
return false;
|
||||
}
|
||||
bool found = false;
|
||||
LARGE_INTEGER size = {};
|
||||
if (GetFileSizeEx(f, &size) && size.QuadPart >= 0 &&
|
||||
offset <= static_cast<uint64_t>(size.QuadPart) &&
|
||||
static_cast<uint64_t>(size.QuadPart) - offset < (64ull << 20)) {
|
||||
LARGE_INTEGER pos{};
|
||||
pos.QuadPart = static_cast<LONGLONG>(offset);
|
||||
if (!SetFilePointerEx(f, pos, nullptr, FILE_BEGIN)) {
|
||||
CloseHandle(f);
|
||||
return false;
|
||||
}
|
||||
const DWORD remaining = static_cast<DWORD>(static_cast<uint64_t>(size.QuadPart) - offset);
|
||||
auto* buf = static_cast<char*>(HeapAlloc(GetProcessHeap(), 0, static_cast<SIZE_T>(remaining) + 1));
|
||||
DWORD total = 0;
|
||||
while (buf && total < remaining) {
|
||||
DWORD got = 0;
|
||||
if (!ReadFile(f, buf + total, remaining - total, &got, nullptr) || got == 0) break;
|
||||
total += got;
|
||||
}
|
||||
if (buf && total == remaining) {
|
||||
buf[total] = '\0';
|
||||
/* Both needles must sit on the same JSONL line. */
|
||||
for (char* line = buf; line && *line && !found;) {
|
||||
char* end = std::strchr(line, '\n');
|
||||
if (end) *end = '\0';
|
||||
found = std::strstr(line, needle_a) && std::strstr(line, needle_b);
|
||||
line = end ? end + 1 : nullptr;
|
||||
}
|
||||
}
|
||||
if (buf) HeapFree(GetProcessHeap(), 0, buf);
|
||||
}
|
||||
CloseHandle(f);
|
||||
return found;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
|
||||
// Read the JSONL log the shim wrote, so the dispatcher's live-reference
|
||||
// count can be checked rather than assumed. The log is the only place the
|
||||
// count is observable: `Release` returning 0 proves the reference count
|
||||
// reached zero, and the `dispatch_mode` lines prove the live-dispatcher
|
||||
// counter followed it. They do not prove the object was freed: `Release`
|
||||
// updates the counter before `delete this`, so a leak would not show here.
|
||||
// `bx-cli run` appends to the supplied BX_LOG_FILE, so a re-run with the
|
||||
// same log can pass from stale lines even if this run emits none. Capture
|
||||
// the file's size before the run and assert only on the bytes appended by
|
||||
// this run.
|
||||
static uint64_t log_file_size(const char* path) {
|
||||
if (!path || !*path) return 0;
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) return 0;
|
||||
LARGE_INTEGER size{};
|
||||
const BOOL ok = GetFileSizeEx(f, &size);
|
||||
CloseHandle(f);
|
||||
return ok ? static_cast<uint64_t>(size.QuadPart) : 0;
|
||||
}
|
||||
|
||||
static std::string read_log_file_from(const char* path, uint64_t offset) {
|
||||
std::string text;
|
||||
if (!path || !*path) return text;
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) return text;
|
||||
LARGE_INTEGER pos{};
|
||||
pos.QuadPart = static_cast<LONGLONG>(offset);
|
||||
if (!SetFilePointerEx(f, pos, nullptr, FILE_BEGIN)) {
|
||||
CloseHandle(f);
|
||||
return text;
|
||||
}
|
||||
char buf[4096];
|
||||
DWORD got = 0;
|
||||
while (ReadFile(f, buf, sizeof(buf), &got, nullptr) && got > 0) {
|
||||
text.append(buf, got);
|
||||
}
|
||||
CloseHandle(f);
|
||||
return text;
|
||||
}
|
||||
|
||||
int main() {
|
||||
// The dispatcher checks below read the shim's JSONL log, so BX_LOG_FILE
|
||||
// must name it before the process starts (`bx-cli run --log`). Setting it
|
||||
// here would be too late: AcpHal.dll imports bx_runtime_veh.dll, which
|
||||
// reads BX_LOG_FILE once in DLL_PROCESS_ATTACH, before main runs.
|
||||
char dispatcher_log_path[MAX_PATH]{};
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", dispatcher_log_path, sizeof(dispatcher_log_path));
|
||||
if (n == 0 || n >= sizeof(dispatcher_log_path)) {
|
||||
std::fprintf(stderr, "FAIL: BX_LOG_FILE must be set before launch (run under bx-cli run --log)\n");
|
||||
return 1;
|
||||
}
|
||||
const uint64_t log_start = log_file_size(dispatcher_log_path);
|
||||
|
||||
// IAcpHal is not a COM interface (authorized GDK documentation): slots Connect(numCommands,
|
||||
// numMessages), Disconnect(), SubmitCommand(command, id, audioFrame, data, notification),
|
||||
// PopMessage(message), GetNumMessages() and Release(). BetterXen has no ACP: commands are
|
||||
// accepted and no message arrives.
|
||||
void* object = nullptr;
|
||||
CHECK(AcpHalCreate(&object) == S_OK && object);
|
||||
auto* hal = static_cast<IUnknown*>(object);
|
||||
CHECK(hal->QueryInterface(IID_IUnknown, &object) == S_OK && object == hal);
|
||||
CHECK(hal->Release() == 1);
|
||||
void* hal = object;
|
||||
const void* const* acp = *static_cast<const void* const* const*>(hal);
|
||||
using ConnectFn = HRESULT(WINAPI*)(void*, uint32_t, uint32_t);
|
||||
using DisconnectFn = HRESULT(WINAPI*)(void*);
|
||||
using SubmitFn = HRESULT(WINAPI*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
|
||||
using PopFn = bool(WINAPI*)(void*, void*);
|
||||
using CountFn = uint32_t(WINAPI*)(void*);
|
||||
using ReleaseFn = void(WINAPI*)(void*);
|
||||
CHECK(reinterpret_cast<SubmitFn>(acp[2])(hal, 2, 1, 0, nullptr, 0) == E_UNEXPECTED); // before Connect
|
||||
CHECK(reinterpret_cast<ConnectFn>(acp[0])(hal, 0x1000, 0x1000) == S_OK);
|
||||
CHECK(FAILED(reinterpret_cast<ConnectFn>(acp[0])(hal, 0x1000, 0x1000)));
|
||||
CHECK(reinterpret_cast<SubmitFn>(acp[2])(hal, 2, 1, 0, nullptr, 0) == S_OK);
|
||||
unsigned char message[64]{};
|
||||
CHECK(!reinterpret_cast<PopFn>(acp[3])(hal, message) && reinterpret_cast<CountFn>(acp[4])(hal) == 0);
|
||||
CHECK(reinterpret_cast<DisconnectFn>(acp[1])(hal) == S_OK);
|
||||
void *va = nullptr, *second = nullptr;
|
||||
uint32_t base = 0, other = 0;
|
||||
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
|
||||
// A zero-capacity heap must not report S_OK: it can never satisfy an
|
||||
// allocation (#580). ApuAlloc still refuses with E_OUTOFMEMORY.
|
||||
CHECK(ApuCreateHeap(0, 0) == E_INVALIDARG);
|
||||
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
|
||||
CHECK(ApuCreateHeap(64, 64) == S_OK);
|
||||
CHECK(ApuAlloc(&va, nullptr, 64, 64) == S_OK && va);
|
||||
CHECK(ApuFree(va) == S_OK);
|
||||
@@ -61,7 +182,48 @@ int main() {
|
||||
CHECK(ApuFree(tail) == E_INVALIDARG);
|
||||
CHECK(ApuFree(va) == S_OK && !ApuMapApuAddress(base) && !ApuMapVirtualAddress(va));
|
||||
CHECK(ApuFree(va) == E_INVALIDARG && ApuMapApuAddress(other) == second);
|
||||
CHECK(ApuFree(second) == S_OK && hal->Release() == 0);
|
||||
CHECK(ApuFree(second) == S_OK);
|
||||
reinterpret_cast<ReleaseFn>(acp[5])(hal);
|
||||
|
||||
// AcpHalAllocateShapeContexts(SHAPE_CONTEXTS*) (authorized GDK documentation): six counts in
|
||||
// (SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM), six CPU pointers and six APU addresses out, the
|
||||
// arrays from the APU heap (XMA elements are 64 bytes). A second allocation without a release
|
||||
// fails with ACP_E_ALREADY_ALLOCATED (0x8AC80001).
|
||||
struct ShapeContexts {
|
||||
uint32_t counts[6];
|
||||
void* arrays[6];
|
||||
uint32_t apu[6];
|
||||
};
|
||||
static_assert(sizeof(ShapeContexts) == 96 && offsetof(ShapeContexts, arrays) == 24 &&
|
||||
offsetof(ShapeContexts, apu) == 72,
|
||||
"SHAPE_CONTEXTS layout");
|
||||
constexpr HRESULT kAlreadyAllocated = static_cast<HRESULT>(0x8AC80001);
|
||||
CHECK(AcpHalAllocateShapeContexts(nullptr) == E_INVALIDARG);
|
||||
CHECK(AcpHalReleaseShapeContexts() == S_OK); // nothing allocated
|
||||
ShapeContexts shape{};
|
||||
shape.counts[4] = 2; // two XMA contexts: 128 bytes, the whole 64 + 64 heap
|
||||
CHECK(AcpHalAllocateShapeContexts(&shape) == S_OK);
|
||||
CHECK(shape.arrays[4] && shape.apu[4] && ApuMapApuAddress(shape.apu[4]) == shape.arrays[4]);
|
||||
CHECK(!shape.arrays[0] && !shape.arrays[5] && !shape.apu[0]);
|
||||
CHECK(static_cast<const unsigned char*>(shape.arrays[4])[127] == 0); // zero-filled
|
||||
ShapeContexts again{};
|
||||
again.counts[4] = 1;
|
||||
CHECK(AcpHalAllocateShapeContexts(&again) == kAlreadyAllocated);
|
||||
CHECK(AcpHalReleaseShapeContexts() == S_OK && !ApuMapApuAddress(shape.apu[4]));
|
||||
CHECK(AcpHalAllocateShapeContexts(&again) == S_OK && again.arrays[4]);
|
||||
CHECK(AcpHalReleaseShapeContexts() == S_OK);
|
||||
|
||||
char log_path[MAX_PATH];
|
||||
DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
if (log_len > 0 && log_len < sizeof(log_path)) {
|
||||
CHECK(file_contains(log_path, log_start, "\"event\":\"shape_contexts_allocated\"", "xma=2"));
|
||||
CHECK(file_contains(log_path, log_start, "\"event\":\"connect\"", "commands=4096"));
|
||||
} else {
|
||||
// Unreachable under `bx-cli run --log`. A SKIP that still exits 0 would
|
||||
// contradict the exit-77 protocol, so a missing log is a failure.
|
||||
std::fprintf(stderr, "FAIL: BX_LOG_FILE must be set before launch (run under bx-cli run --log)\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
void *apu = nullptr, *peer = nullptr, *dsp = nullptr;
|
||||
CHECK(XApuConnect(&apu) == S_OK && XApuConnect(&peer) == S_OK && peer != apu);
|
||||
@@ -186,8 +348,51 @@ int main() {
|
||||
CHECK(!unreg_cb(v0, tok2, 0));
|
||||
set_focus(v0, 0x2);
|
||||
|
||||
// Slot 14: IGameInput::CreateDispatcher. The singleton refcount is checked
|
||||
// below via the pre-existing GameInput release sequence, which must be
|
||||
// unchanged by dispatcher creation.
|
||||
using CreateDispatcherFn = HRESULT (WINAPI*)(IUnknown*, void**);
|
||||
using DispatchFn = bool (WINAPI*)(IUnknown*, uint64_t);
|
||||
using OpenWaitHandleFn = HRESULT (WINAPI*)(IUnknown*, HANDLE*);
|
||||
auto create_dispatcher = reinterpret_cast<CreateDispatcherFn>(table[14]);
|
||||
CHECK(create_dispatcher(v0, nullptr) == E_POINTER);
|
||||
void* dispatcher = reinterpret_cast<void*>(uintptr_t{1});
|
||||
CHECK(create_dispatcher(v0, &dispatcher) == S_OK && dispatcher);
|
||||
auto* disp_unknown = static_cast<IUnknown*>(dispatcher);
|
||||
auto** disp_table = *reinterpret_cast<void***>(disp_unknown);
|
||||
void* disp_qi = nullptr;
|
||||
CHECK(reinterpret_cast<HRESULT (WINAPI*)(IUnknown*, REFIID, void**)>(disp_table[0])(
|
||||
disp_unknown, IID_IUnknown, &disp_qi) == S_OK && disp_qi == dispatcher);
|
||||
CHECK(disp_unknown->Release() == 1);
|
||||
void* disp_other = reinterpret_cast<void*>(uintptr_t{1});
|
||||
CHECK(reinterpret_cast<HRESULT (WINAPI*)(IUnknown*, REFIID, void**)>(disp_table[0])(
|
||||
disp_unknown, kUnknownIid, &disp_other) == E_NOINTERFACE && !disp_other);
|
||||
auto dispatch = reinterpret_cast<DispatchFn>(disp_table[3]);
|
||||
CHECK(!dispatch(disp_unknown, 0));
|
||||
CHECK(!dispatch(disp_unknown, 1000000));
|
||||
auto open_wait = reinterpret_cast<OpenWaitHandleFn>(disp_table[4]);
|
||||
CHECK(open_wait(disp_unknown, nullptr) == E_POINTER);
|
||||
HANDLE wait1 = nullptr, wait2 = nullptr;
|
||||
CHECK(open_wait(disp_unknown, &wait1) == S_OK && wait1);
|
||||
CHECK(WaitForSingleObject(wait1, 0) == WAIT_TIMEOUT);
|
||||
CHECK(open_wait(disp_unknown, &wait2) == S_OK && wait2 && wait2 != wait1);
|
||||
CHECK(CloseHandle(wait1) && CloseHandle(wait2));
|
||||
CHECK(disp_unknown->Release() == 0);
|
||||
|
||||
// `dispatch_mode` logs each manual/automatic transition with the live
|
||||
// dispatcher count. These checks catch a Release that never calls
|
||||
// `on_dispatcher_released` (no `live_dispatchers=0` line). They cannot
|
||||
// catch a missing `delete this`, which runs after the counter update.
|
||||
{
|
||||
const std::string log = read_log_file_from(dispatcher_log_path, log_start);
|
||||
CHECK(log.find("live_dispatchers=1") != std::string::npos);
|
||||
CHECK(log.find("live_dispatchers=0") != std::string::npos);
|
||||
CHECK(log.find("mode=manual") != std::string::npos);
|
||||
CHECK(log.find("mode=automatic") != std::string::npos);
|
||||
}
|
||||
|
||||
CHECK(v0->Release() == 1);
|
||||
CHECK(input->Release() == 0);
|
||||
FreeLibrary(dll);
|
||||
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1 and device callbacks");
|
||||
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1, device callbacks, dispatcher");
|
||||
}
|
||||
@@ -25,12 +25,27 @@
|
||||
|
||||
extern "C" {
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12ConfigureVirtualMemoryX(void* config);
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(void* params, REFIID riid, void** ppv);
|
||||
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* count, PULONG_PTR pages, uint64_t flags);
|
||||
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(SIZE_T* count, PULONG_PTR pages, uint64_t flags);
|
||||
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID base, SIZE_T count, uint64_t flags, PULONG_PTR pages);
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
|
||||
__declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes);
|
||||
__declspec(dllimport) VOID WINAPI XMemFree(PVOID address, uint64_t attributes);
|
||||
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR count, PULONG_PTR pages);
|
||||
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR pages);
|
||||
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID base, ULONG_PTR count, PULONG_PTR pages);
|
||||
__declspec(dllimport) BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size);
|
||||
}
|
||||
|
||||
struct bx_xmem_stats_t {
|
||||
uint64_t title_limit_bytes;
|
||||
uint64_t committed_virtual_bytes;
|
||||
uint64_t allocated_physical_bytes;
|
||||
uint64_t peak_committed_bytes;
|
||||
};
|
||||
static_assert(sizeof(bx_xmem_stats_t) == 32, "xmem stats struct is 32 bytes");
|
||||
|
||||
/* D3D12XboxCreateDevice requires a D3D12XBOX_CREATE_DEVICE_PARAMETERS block (80 bytes on Xbox
|
||||
Series); a zeroed one asks for defaults. Only its Version field is read by the shim. */
|
||||
alignas(8) static const unsigned char kCreateParams[80] = {};
|
||||
|
||||
struct BxD3d12VirtualMemoryConfig {
|
||||
uint32_t magic;
|
||||
uint32_t struct_size;
|
||||
@@ -77,6 +92,7 @@ static_assert(kFootprint <= kAlign, "texture footprint fits in one 64 KiB page")
|
||||
static_assert(kRegionBytes == 128ull * 1024ull, "configured region is 128 KiB");
|
||||
|
||||
int g_checks = 0;
|
||||
int g_skipped = 0;
|
||||
int g_failures = 0;
|
||||
|
||||
__attribute__((format(gnu_printf, 2, 3)))
|
||||
@@ -331,7 +347,7 @@ DWORD WINAPI check_device_startup(LPVOID context) {
|
||||
return 1;
|
||||
}
|
||||
ID3D12Device* device = nullptr;
|
||||
result.device_hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
result.device_hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (SUCCEEDED(result.device_hr) && device) {
|
||||
const auto desc = heap_of(D3D12_HEAP_TYPE_UPLOAD, 600ull << 20, D3D12_HEAP_FLAG_NONE);
|
||||
ID3D12Heap* heap = nullptr;
|
||||
@@ -365,7 +381,62 @@ void check_concurrent_device_startup() {
|
||||
CloseHandle(start);
|
||||
}
|
||||
|
||||
void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64_t region_base, uint64_t cap) {
|
||||
/* #554/#572: the three placement entry points. `entry` 0 is CreatePlacedResource
|
||||
(slot 29), 1 is CreatePlacedResource1 (ID3D12Device8 slot 70), 2 is
|
||||
CreatePlacedResource2 (ID3D12Device10 slot 77). A buffer on entry 2 uses the
|
||||
UNDEFINED layout that enhanced barriers require for buffers. Returns false in
|
||||
*available when the device does not expose that entry point. */
|
||||
const char* const kPlaceName[3] = {"CreatePlacedResource", "CreatePlacedResource1", "CreatePlacedResource2"};
|
||||
|
||||
HRESULT place_buffer(ID3D12Device* device, int entry, ID3D12Heap* heap, UINT64 offset, uint64_t bytes,
|
||||
D3D12_RESOURCE_STATES state, ID3D12Resource** out, bool* available) {
|
||||
*out = reinterpret_cast<ID3D12Resource*>(static_cast<uintptr_t>(0x1));
|
||||
*available = true;
|
||||
const D3D12_RESOURCE_DESC desc = buffer_desc(bytes);
|
||||
if (entry == 0) {
|
||||
return device->CreatePlacedResource(heap, offset, &desc, state, nullptr, __uuidof(ID3D12Resource),
|
||||
reinterpret_cast<void**>(out));
|
||||
}
|
||||
D3D12_RESOURCE_DESC1 desc1{};
|
||||
desc1.Dimension = desc.Dimension;
|
||||
desc1.Width = desc.Width;
|
||||
desc1.Height = desc.Height;
|
||||
desc1.DepthOrArraySize = desc.DepthOrArraySize;
|
||||
desc1.MipLevels = desc.MipLevels;
|
||||
desc1.Format = desc.Format;
|
||||
desc1.SampleDesc = desc.SampleDesc;
|
||||
desc1.Layout = desc.Layout;
|
||||
HRESULT hr = E_NOINTERFACE;
|
||||
if (entry == 1) {
|
||||
ID3D12Device8* dev8 = nullptr;
|
||||
if (device->QueryInterface(__uuidof(ID3D12Device8), reinterpret_cast<void**>(&dev8)) == S_OK && dev8) {
|
||||
hr = dev8->CreatePlacedResource1(heap, offset, &desc1, state, nullptr, __uuidof(ID3D12Resource),
|
||||
reinterpret_cast<void**>(out));
|
||||
dev8->Release();
|
||||
return hr;
|
||||
}
|
||||
} else {
|
||||
ID3D12Device10* dev10 = nullptr;
|
||||
if (device->QueryInterface(__uuidof(ID3D12Device10), reinterpret_cast<void**>(&dev10)) == S_OK && dev10) {
|
||||
hr = dev10->CreatePlacedResource2(heap, offset, &desc1, D3D12_BARRIER_LAYOUT_UNDEFINED, nullptr, 0,
|
||||
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(out));
|
||||
dev10->Release();
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
*out = nullptr;
|
||||
*available = false;
|
||||
return hr;
|
||||
}
|
||||
|
||||
void skip_case(const char* what, const char* why) {
|
||||
++g_skipped;
|
||||
std::printf("SKIP: %s: %s\n", what, why);
|
||||
std::fflush(stdout);
|
||||
}
|
||||
|
||||
void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64_t region_base, uint64_t cap,
|
||||
int entry) {
|
||||
const bool capped = cap == (512ull << 20);
|
||||
const uint64_t heap_bytes = capped ? 300ull << 20 : kAlign;
|
||||
const auto heap_desc = heap_of(D3D12_HEAP_TYPE_UPLOAD, heap_bytes, D3D12_HEAP_FLAG_NONE);
|
||||
@@ -375,11 +446,17 @@ void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64
|
||||
return;
|
||||
}
|
||||
ID3D12Resource* resource = nullptr;
|
||||
const auto desc = buffer_desc(kBufBytes);
|
||||
hr = device->CreatePlacedResource(heap, 0, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
|
||||
bool available = true;
|
||||
hr = place_buffer(device, entry, heap, 0, kBufBytes, D3D12_RESOURCE_STATE_GENERIC_READ, &resource, &available);
|
||||
heap->Release();
|
||||
if (!check(hr == S_OK && resource, "placed resource can outlive the caller's heap reference hr=0x%08lx", ul(hr))) {
|
||||
if (!available) {
|
||||
skip_case(kPlaceName[entry], "the device does not expose this entry point for the heap-charge check");
|
||||
return;
|
||||
}
|
||||
if (!check(hr == S_OK && resource, "%s resource can outlive the caller's heap reference hr=0x%08lx",
|
||||
kPlaceName[entry], ul(hr))) {
|
||||
if (hr != S_OK) resource = nullptr;
|
||||
if (resource) resource->Release();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -392,7 +469,7 @@ void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64
|
||||
auto cfg = make_block(region_base, kRegionBytes, kFlagBacking);
|
||||
hr = D3D12ConfigureVirtualMemoryX(&cfg);
|
||||
check(hr == S_OK && last_log_u64(log_path, "gpu_heap_bytes=") == kRegionBytes + heap_bytes,
|
||||
"live placed resource keeps the original heap charge");
|
||||
"live %s resource keeps the original heap charge", kPlaceName[entry]);
|
||||
|
||||
if (capped) {
|
||||
ID3D12Heap* second = nullptr;
|
||||
@@ -404,7 +481,7 @@ void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64
|
||||
resource->Release();
|
||||
hr = D3D12ConfigureVirtualMemoryX(&cfg);
|
||||
check(hr == S_OK && last_log_u64(log_path, "gpu_heap_bytes=") == kRegionBytes,
|
||||
"final placed resource release credits the original heap");
|
||||
"final %s resource release credits the original heap", kPlaceName[entry]);
|
||||
|
||||
if (capped) {
|
||||
ID3D12Heap* second = nullptr;
|
||||
@@ -414,6 +491,150 @@ void check_placed_heap_charge(ID3D12Device* device, const char* log_path, uint64
|
||||
}
|
||||
}
|
||||
|
||||
/* #552: graphics-first / xmem-first pairing through the public exports.
|
||||
* With a 512 MiB cap, a 300 MiB D3D12 heap registers an external charge in
|
||||
* xmem. A 300 MiB XMemAlloc must then fail (300+300 > 512), and a 200 MiB
|
||||
* XMemAlloc must succeed (300+200 <= 512). After releasing the heap the
|
||||
* 300 MiB XMemAlloc must succeed. This is the graphics-first overcommit
|
||||
* that the private-ledger version allowed. */
|
||||
void check_graphics_xmem_pairing(ID3D12Device* device, uint64_t cap) {
|
||||
if (cap != (512ull << 20)) {
|
||||
/* The pairing sizes are fixed against a 512 MiB cap, so at any other cap the
|
||||
* cross-DLL budget check does not run. Say so rather than pass silently. */
|
||||
++g_skipped;
|
||||
std::printf("SKIP: graphics/xmem pairing needs a 512 MiB cap "
|
||||
"(BX_MEM_LIMIT_MB=512 bx-cli run --inherit-env ...); this run's cap is %llu MiB\n",
|
||||
static_cast<unsigned long long>(cap >> 20));
|
||||
return;
|
||||
}
|
||||
const uint64_t heap_bytes = 300ull << 20;
|
||||
const auto heap_desc = heap_of(D3D12_HEAP_TYPE_UPLOAD, heap_bytes, D3D12_HEAP_FLAG_NONE);
|
||||
ID3D12Heap* heap = nullptr;
|
||||
HRESULT hr = device->CreateHeap(&heap_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&heap));
|
||||
if (!check(hr == S_OK && heap, "pairing: 300 MiB graphics heap hr=0x%08lx", ul(hr))) {
|
||||
return;
|
||||
}
|
||||
|
||||
bx_xmem_stats_t stats{};
|
||||
check(XMemGetWorkingSetStatistics(&stats, sizeof(stats)) != 0, "pairing: xmem stats readable");
|
||||
|
||||
/* 300 MiB heap + 300 MiB xmem = 600 MiB > 512 MiB cap. */
|
||||
void* too_much = XMemAlloc(300ull << 20, 0);
|
||||
check(too_much == nullptr, "pairing: 300 MiB XMemAlloc on top of 300 MiB heap exceeds the 512 MiB cap");
|
||||
if (too_much) XMemFree(too_much, 0);
|
||||
|
||||
/* 300 MiB heap + 200 MiB xmem = 500 MiB <= 512 MiB cap. */
|
||||
void* fits = XMemAlloc(200ull << 20, 0);
|
||||
check(fits != nullptr, "pairing: 200 MiB XMemAlloc fits beside the 300 MiB heap");
|
||||
if (fits) XMemFree(fits, 0);
|
||||
|
||||
heap->Release();
|
||||
|
||||
/* After the heap charge is released the 300 MiB allocation must fit. */
|
||||
void* after = XMemAlloc(300ull << 20, 0);
|
||||
check(after != nullptr, "pairing: 300 MiB XMemAlloc fits after releasing the graphics heap");
|
||||
if (after) XMemFree(after, 0);
|
||||
}
|
||||
|
||||
/* #554/#572: an ordinary heap from CreateHeap gets the same placement checks as
|
||||
the backing heap on every entry point. Each case is guarded by the alignment the
|
||||
host reports for the buffer, so a host alignment that would make the offset
|
||||
legal skips that case instead of passing it. */
|
||||
void check_ordinary_placement(ID3D12Device* device) {
|
||||
const uint64_t heap_bytes = 2 * kAlign;
|
||||
const D3D12_HEAP_DESC def_desc = heap_of(D3D12_HEAP_TYPE_DEFAULT, heap_bytes, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS);
|
||||
const D3D12_HEAP_DESC up_desc = heap_of(D3D12_HEAP_TYPE_UPLOAD, kAlign, D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS);
|
||||
ID3D12Heap* heap = nullptr;
|
||||
ID3D12Heap* upload = nullptr;
|
||||
HRESULT hr = device->CreateHeap(&def_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&heap));
|
||||
if (!check(hr == S_OK && heap, "ordinary DEFAULT heap for placement checks hr=0x%08lx", ul(hr))) {
|
||||
return;
|
||||
}
|
||||
hr = device->CreateHeap(&up_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&upload));
|
||||
check(hr == S_OK && upload, "ordinary UPLOAD heap for placement checks hr=0x%08lx", ul(hr));
|
||||
|
||||
const D3D12_RESOURCE_DESC one = buffer_desc(kAlign);
|
||||
const D3D12_RESOURCE_DESC two = buffer_desc(2 * kAlign);
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO one_info = device->GetResourceAllocationInfo(0, 1, &one);
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO two_info = device->GetResourceAllocationInfo(0, 1, &two);
|
||||
std::printf("ordinary_buffer_alloc align=%llu one=%llu two=%llu\n",
|
||||
static_cast<unsigned long long>(one_info.Alignment),
|
||||
static_cast<unsigned long long>(one_info.SizeInBytes),
|
||||
static_cast<unsigned long long>(two_info.SizeInBytes));
|
||||
std::fflush(stdout);
|
||||
const bool info_ok = one_info.SizeInBytes != 0 && one_info.SizeInBytes != ~0ull && two_info.SizeInBytes != 0 &&
|
||||
two_info.SizeInBytes != ~0ull;
|
||||
const uint64_t align = one_info.Alignment;
|
||||
const bool misaligned_real = info_ok && align != 0 && (256ull % align) != 0;
|
||||
/* kAlign is aligned, and a 2*kAlign buffer at kAlign ends past a 2*kAlign heap. */
|
||||
const bool overhang_real = info_ok && align != 0 && (kAlign % align) == 0 && two_info.SizeInBytes > kAlign;
|
||||
const bool valid_real = info_ok && align != 0 && (kAlign % align) == 0 && one_info.SizeInBytes <= kAlign;
|
||||
|
||||
for (int entry = 0; entry < 3; ++entry) {
|
||||
const char* name = kPlaceName[entry];
|
||||
char what[96];
|
||||
ID3D12Resource* res = nullptr;
|
||||
bool available = true;
|
||||
|
||||
std::snprintf(what, sizeof(what), "%s misaligned offset on an ordinary heap", name);
|
||||
if (misaligned_real) {
|
||||
hr = place_buffer(device, entry, heap, 256, kAlign, D3D12_RESOURCE_STATE_COMMON, &res, &available);
|
||||
if (!available) {
|
||||
skip_case(name, "the device does not expose this entry point");
|
||||
continue;
|
||||
}
|
||||
check(hr == E_INVALIDARG && res == nullptr, "%s returns E_INVALIDARG and null (alignment %llu) hr=0x%08lx",
|
||||
what, static_cast<unsigned long long>(align), ul(hr));
|
||||
if (hr == S_OK && res) res->Release();
|
||||
} else {
|
||||
skip_case(what, "the host's buffer alignment makes offset 256 legal");
|
||||
}
|
||||
|
||||
std::snprintf(what, sizeof(what), "%s aligned overhang on an ordinary heap", name);
|
||||
if (overhang_real) {
|
||||
hr = place_buffer(device, entry, heap, kAlign, 2 * kAlign, D3D12_RESOURCE_STATE_COMMON, &res, &available);
|
||||
if (!available) {
|
||||
skip_case(name, "the device does not expose this entry point");
|
||||
continue;
|
||||
}
|
||||
check(hr == E_INVALIDARG && res == nullptr, "%s returns E_INVALIDARG and null hr=0x%08lx", what, ul(hr));
|
||||
if (hr == S_OK && res) res->Release();
|
||||
} else {
|
||||
skip_case(what, "the host's buffer alignment or size does not make it an aligned overhang");
|
||||
}
|
||||
|
||||
std::snprintf(what, sizeof(what), "%s valid nonzero offset on an ordinary heap", name);
|
||||
if (valid_real) {
|
||||
hr = place_buffer(device, entry, heap, kAlign, kAlign, D3D12_RESOURCE_STATE_COMMON, &res, &available);
|
||||
if (!available) {
|
||||
skip_case(name, "the device does not expose this entry point");
|
||||
continue;
|
||||
}
|
||||
check(hr == S_OK && res != nullptr, "%s succeeds hr=0x%08lx", what, ul(hr));
|
||||
if (res && hr == S_OK) res->Release();
|
||||
} else {
|
||||
skip_case(what, "the host's buffer alignment or size does not fit offset 64 KiB");
|
||||
}
|
||||
|
||||
if (entry == 2) {
|
||||
/* CreatePlacedResource2 takes a barrier layout; the state rule does not apply. */
|
||||
continue;
|
||||
}
|
||||
std::snprintf(what, sizeof(what), "%s UPLOAD heap with COPY_DEST state", name);
|
||||
if (upload) {
|
||||
hr = place_buffer(device, entry, upload, 0, 256, D3D12_RESOURCE_STATE_COPY_DEST, &res, &available);
|
||||
if (!available) {
|
||||
skip_case(name, "the device does not expose this entry point");
|
||||
continue;
|
||||
}
|
||||
check(hr == E_INVALIDARG && res == nullptr, "%s returns E_INVALIDARG and null hr=0x%08lx", what, ul(hr));
|
||||
if (hr == S_OK && res) res->Release();
|
||||
}
|
||||
}
|
||||
if (upload) upload->Release();
|
||||
heap->Release();
|
||||
}
|
||||
|
||||
/* CreatePlacedResource1 must accept a heap from CreateHeap. CreatePlacedResource2
|
||||
is checked only when the host device implements ID3D12Device10. */
|
||||
void check_newer_placement(ID3D12Device* device) {
|
||||
@@ -571,6 +792,9 @@ int main() {
|
||||
return 1;
|
||||
}
|
||||
const char* profile = cfg->profile == BX_PROFILE_ANACONDA ? "anaconda" : "lockhart";
|
||||
char log_path[MAX_PATH];
|
||||
DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
const bool have_log = log_len > 0 && log_len < sizeof(log_path);
|
||||
|
||||
check(D3D12ConfigureVirtualMemoryX(nullptr) == S_OK, "null configuration is a logged stub that returns S_OK");
|
||||
|
||||
@@ -664,9 +888,9 @@ int main() {
|
||||
SIZE_T page_count = 2;
|
||||
ULONG_PTR pages[2] = {};
|
||||
uint8_t* view = nullptr;
|
||||
bool mapped = XMemAllocatePhysicalPages(&page_count, pages, 0) && page_count == 2 && pages[0] != 0 && pages[1] != 0;
|
||||
bool mapped = XMemAllocatePhysicalPages(0, &page_count, pages) && page_count == 2 && pages[0] != 0 && pages[1] != 0;
|
||||
if (mapped) {
|
||||
view = static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, page_count, 0, pages));
|
||||
view = static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, page_count, pages));
|
||||
mapped = view != nullptr && (reinterpret_cast<uintptr_t>(view) % kAlign) == 0;
|
||||
if (mapped) {
|
||||
view[kAlign] = 0x5A;
|
||||
@@ -680,7 +904,7 @@ int main() {
|
||||
check_concurrent_device_startup();
|
||||
}
|
||||
ID3D12Device* device = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (!check(hr == S_OK && device, "D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_placed (no device. %d of %d checks failed)\n", g_failures, g_checks);
|
||||
return 1;
|
||||
@@ -1239,9 +1463,6 @@ int main() {
|
||||
}
|
||||
}
|
||||
|
||||
char log_path[MAX_PATH];
|
||||
DWORD log_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
const bool have_log = log_len > 0 && log_len < sizeof(log_path);
|
||||
std::printf("RESULT: cpu_va=0x%llx map=0x%llx buffer_gpu_va=0x%llx flush=%d copy_buffer=%u/%u copy_texture=%u/%u "
|
||||
"texture_path=%s cpu_after_gpu=%u/%u small_align=%llu upload_100000=%llu\n",
|
||||
static_cast<unsigned long long>(cpu_va), static_cast<unsigned long long>(map_pointer),
|
||||
@@ -1291,7 +1512,13 @@ int main() {
|
||||
if (placed_buf) placed_buf->Release();
|
||||
|
||||
if (mapped && backing && have_log) {
|
||||
check_placed_heap_charge(device, log_path, region_base, cfg->title_memory_limit_bytes);
|
||||
for (int entry = 0; entry < 3; ++entry) {
|
||||
check_placed_heap_charge(device, log_path, region_base, cfg->title_memory_limit_bytes, entry);
|
||||
}
|
||||
}
|
||||
|
||||
if (device) {
|
||||
check_graphics_xmem_pairing(device, cfg->title_memory_limit_bytes);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -1299,7 +1526,7 @@ int main() {
|
||||
* caller's device reference must leave the proxy alive for GetDevice.
|
||||
*/
|
||||
ID3D12Device* side = nullptr;
|
||||
hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&side));
|
||||
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&side));
|
||||
check(hr == S_OK && side, "side device for the ordinary-heap lifetime check hr=0x%08lx", ul(hr));
|
||||
if (side) {
|
||||
D3D12_HEAP_DESC side_desc = heap_of(D3D12_HEAP_TYPE_UPLOAD, kAlign, D3D12_HEAP_FLAG_NONE);
|
||||
@@ -1338,7 +1565,11 @@ int main() {
|
||||
* section. There is no timing stress test for those windows.
|
||||
*/
|
||||
check_newer_placement(device);
|
||||
check_ordinary_placement(device);
|
||||
|
||||
uint64_t host_before = 0;
|
||||
uint64_t host_ignored = 0;
|
||||
int host_before_count = 0;
|
||||
if (backing) {
|
||||
BxD3d12VirtualMemoryConfig detached = make_block(0, 0, kFlagBacking);
|
||||
const HRESULT away = D3D12ConfigureVirtualMemoryX(&detached);
|
||||
@@ -1351,7 +1582,7 @@ int main() {
|
||||
device = nullptr;
|
||||
backing->Release();
|
||||
backing = nullptr;
|
||||
hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
check(hr == S_OK && device, "device recreated after the detach check hr=0x%08lx", ul(hr));
|
||||
if (device && mapped) {
|
||||
BxD3d12VirtualMemoryConfig again = make_block(region_base, kRegionBytes, kFlagBacking);
|
||||
@@ -1370,6 +1601,10 @@ int main() {
|
||||
SetEnvironmentVariableA("BX_D3D12_FORCE_BACKING_REPLACE", nullptr);
|
||||
check(hr == S_OK && replaced && !same_object(replaced, backing),
|
||||
"forced host replacement publishes a different backing heap hr=0x%08lx", ul(hr));
|
||||
if (have_log) {
|
||||
/* Capture the device whose forced replacement heap remains in the cache. */
|
||||
log_u64_ends(log_path, "host_device=", &host_ignored, &host_before, &host_before_count);
|
||||
}
|
||||
check(get_device_closed(backing), "GetDevice on the heap replaced by another host device fails closed");
|
||||
const ULONG left = device->Release();
|
||||
check(left == 0, "proxy released to zero while the replaced heap is still held (refs=%lu)", left);
|
||||
@@ -1377,7 +1612,7 @@ int main() {
|
||||
backing->Release();
|
||||
backing = replaced;
|
||||
device = nullptr;
|
||||
hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
check(hr == S_OK && device, "device recreated after the replacement check hr=0x%08lx", ul(hr));
|
||||
if (device && mapped && backing) {
|
||||
/* The replacement already published a heap for this region. A same-host
|
||||
@@ -1405,16 +1640,14 @@ int main() {
|
||||
if (dead) dead->Release();
|
||||
}
|
||||
|
||||
uint64_t host_before = 0;
|
||||
uint64_t host_ignored = 0;
|
||||
int host_before_count = 0;
|
||||
uint64_t latest_host_before_b = 0;
|
||||
if (have_log) {
|
||||
log_u64_ends(log_path, "host_device=", &host_ignored, &host_before, &host_before_count);
|
||||
log_u64_ends(log_path, "host_device=", &host_ignored, &latest_host_before_b, &host_before_count);
|
||||
}
|
||||
check(SetEnvironmentVariableA("BX_D3D12_REUSE_BACKING_HOST", "1") != 0,
|
||||
"test hook BX_D3D12_REUSE_BACKING_HOST=1 is set");
|
||||
ID3D12Device* device_b = nullptr;
|
||||
hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device_b));
|
||||
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device_b));
|
||||
SetEnvironmentVariableA("BX_D3D12_REUSE_BACKING_HOST", nullptr);
|
||||
check(hr == S_OK && device_b, "device B is a new proxy on the cached host device hr=0x%08lx", ul(hr));
|
||||
uint64_t host_after = 0;
|
||||
@@ -1455,11 +1688,10 @@ int main() {
|
||||
}
|
||||
|
||||
if (view) {
|
||||
XMemMapPhysicalPages(view, page_count, 0, nullptr);
|
||||
XMemMapPhysicalPages(view, page_count, nullptr);
|
||||
}
|
||||
if (pages[0] || pages[1]) {
|
||||
SIZE_T free_count = 2;
|
||||
XMemFreePhysicalPages(&free_count, pages, 0);
|
||||
XMemFreePhysicalPages(2, pages);
|
||||
}
|
||||
if (sync.ready) CloseHandle(sync.ready);
|
||||
if (sync.done) CloseHandle(sync.done);
|
||||
@@ -1468,9 +1700,9 @@ int main() {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_placed (%d of %d checks failed)\n", g_failures, g_checks);
|
||||
return 1;
|
||||
}
|
||||
std::printf("PASS: test_d3d12_placed (%d checks passed, buffer %u/%u bytes, texture %u/%u bytes, "
|
||||
std::printf("PASS: test_d3d12_placed (%d checks passed, %d skipped, buffer %u/%u bytes, texture %u/%u bytes, "
|
||||
"texture_path=%s, cpu_after_gpu %u/%u, small_align=%llu, upload_100000=%llu)\n",
|
||||
g_checks, buf_match, kBufBytes, tex_match, kFootprint, texture_path, reverse_match, kBufBytes,
|
||||
g_checks, g_skipped, buf_match, kBufBytes, tex_match, kFootprint, texture_path, reverse_match, kBufBytes,
|
||||
static_cast<unsigned long long>(small_align), static_cast<unsigned long long>(odd_size));
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# M2-C2 (#465): rendered frames through d3d12_xs.dll's presentation bridge, verified by readback.
|
||||
add_executable(test_d3d12_presentx main.cpp)
|
||||
target_include_directories(test_d3d12_presentx PRIVATE "${BX_ABI_INCLUDE_DIR}" "${BX_ROOT_DIR}/shims/d3d12_xs")
|
||||
target_link_libraries(test_d3d12_presentx PRIVATE d3d12_xs bx_runtime_veh user32 kernel32)
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user