mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 23:01:12 +00:00
Compare commits
189
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a648cdecc7 | ||
|
|
911c27f62b | ||
|
|
9b9c3c63ee | ||
|
|
b16bdc1d4a | ||
|
|
21700c2869 | ||
|
|
da82407073 | ||
|
|
2e55cf2259 | ||
|
|
4cb858e6f5 | ||
|
|
b36e397681 | ||
|
|
5bc4ff5cf4 | ||
|
|
5e204bd883 | ||
|
|
5c2e2c9b63 | ||
|
|
77dd9ffef3 | ||
|
|
abecde1c39 | ||
|
|
e532fc56ba | ||
|
|
ef58b18147 | ||
|
|
2deada1f9d | ||
|
|
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 | ||
|
|
ce1940d84c | ||
|
|
bd744727bd | ||
|
|
b141c4b261 | ||
|
|
c7a4b4cf19 | ||
|
|
b88ea24a30 | ||
|
|
b2ae7a604e | ||
|
|
901b68ffba | ||
|
|
3eb8900442 | ||
|
|
335e3e4d60 | ||
|
|
ca2ad143f9 | ||
|
|
c345ada8e9 | ||
|
|
3c1ee93df5 | ||
|
|
87a03d0421 | ||
|
|
bf9dd7b383 | ||
|
|
b59696975a | ||
|
|
43bb5636bf | ||
|
|
b7a660d4b9 | ||
|
|
10f78645cb | ||
|
|
8c4610b51c | ||
|
|
3b1d168de7 | ||
|
|
0d9997ce66 | ||
|
|
bfbc84d251 | ||
|
|
e96de7c455 | ||
|
|
4b2985114a | ||
|
|
0b474941f0 | ||
|
|
fe749b1436 | ||
|
|
b7bb7615d8 | ||
|
|
3c65b393a4 | ||
|
|
b0e40e29ea | ||
|
|
90dc310b61 | ||
|
|
4bf52b14a3 | ||
|
|
bc7b622018 | ||
|
|
d8fea7b351 | ||
|
|
fe50a8edff | ||
|
|
d47eac809f | ||
|
|
8db5552e32 | ||
|
|
030c63f8c9 | ||
|
|
9a6f71abbc | ||
|
|
ad4bcc66b1 | ||
|
|
3d244ddcb0 | ||
|
|
ceaad9aee9 | ||
|
|
6bf2b9ab95 | ||
|
|
527cd6208f | ||
|
|
93a1f12bc6 | ||
|
|
55dfa39600 | ||
|
|
c39d33821e | ||
|
|
085e0d450e | ||
|
|
48378f8c35 | ||
|
|
0521ea0c6c | ||
|
|
ce23d0b2b9 | ||
|
|
d17525c165 | ||
|
|
3cfb9ed690 | ||
|
|
51ac3bd766 | ||
|
|
e816c16495 | ||
|
|
076b354d61 | ||
|
|
0bd188e602 | ||
|
|
b86be87576 | ||
|
|
62290b2f21 | ||
|
|
30c071845f | ||
|
|
781f473ea3 | ||
|
|
04ad81ee26 | ||
|
|
e0f8b0e8f6 | ||
|
|
2fc82c4d58 | ||
|
|
1b25f3422b | ||
|
|
766055e948 | ||
|
|
54b87f613c | ||
|
|
bbd3b8a9d4 | ||
|
|
32d02efc33 | ||
|
|
ac82a55039 | ||
|
|
e40d7293f8 | ||
|
|
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)
|
||||
|
||||
@@ -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.
|
||||
|
||||
---
|
||||
|
||||
@@ -115,13 +156,13 @@ _Reserved — policy migration in progress._
|
||||
|
||||
## 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
|
||||
|
||||
+132
@@ -10,17 +10,105 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
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
|
||||
- `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.
|
||||
@@ -61,8 +149,36 @@ remains unsupported.
|
||||
- **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.
|
||||
@@ -110,6 +226,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.
|
||||
@@ -190,10 +311,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).
|
||||
|
||||
+2
-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).
|
||||
|
||||
@@ -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.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
|
||||
|
||||
+15
-9
@@ -137,8 +137,10 @@ not define the patterns.
|
||||
|
||||
`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, so BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are **local** constants,
|
||||
not the console's.
|
||||
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
|
||||
|
||||
@@ -164,11 +166,15 @@ 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_xs.exe`
|
||||
re-derives its expected offsets from those masks (and, at 32 bpp, from the
|
||||
D3D12 page) rather than reading them back from the shim: one test per block
|
||||
size, covering 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 `SW_64KB_D`, `SW_64KB_R`, 1D/3D,
|
||||
MSAA, and every multi-mip or multi-slice case. Synthetic evidence only; no
|
||||
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.
|
||||
+81
-20
@@ -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,7 +19,7 @@ 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.
|
||||
|
||||
@@ -35,34 +35,95 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
|
||||
|
||||
---
|
||||
|
||||
## 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`), integrate the shipped xmem-configured D3D12 placed heap (#464) into the first-frame fixture (#469), 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 |
|
||||
|
||||
### Startup diagnosis
|
||||
"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)).
|
||||
|
||||
The product goal is to reach a frame presented by the target software. Under the current [contribution rules](../CONTRIBUTING.md), project runs use original synthetic workloads. Start with `test_integration_boot.exe` for startup and `test_veh_unhandled.exe` as a crash-logging control. Use a focused synthetic reproducer once a failing contract is identified.
|
||||
### Boot
|
||||
|
||||
Before treating either startup warning as causal, add diagnostics that record the requested DirectStorage factory IID and returned HRESULT (#483) and distinguish null, unrecognized and supported BetterXen virtual-memory configurations (#464 follow-up). On a pinned launcher, shim set and backend, repeat the synthetic case before and after a fix. Record normal exit, crash or timeout, the last completed checkpoint, and the exception thread and module offset when available. Progress means reaching the next named checkpoint in the same reproducer. Startup diagnosis and the budget fix proceed alongside the M2 exit gates.
|
||||
**Known work, all found by running the target build:**
|
||||
|
||||
### M2 first-frame acceptance and parallel memory work
|
||||
| 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/` |
|
||||
|
||||
- **First frame (#465, #469).** The synthetic placement criterion uses BetterXen's `BXVM` block to configure the separate D3D12-owned WRITE_BACK heap shipped in #486. On the recorded overlay, #494 copied the backbuffer before the flip, counted one host `Present`, then compared 256 RGBA8 pixels through the D3D12 mapping after waiting. The xmem sentinel shows that the original page remained separate. Visibility through the original xmem address remains an open compatibility question for M3, informed by #473. Displayed-image verification is outside this fixture's measurements. Record a single `main` commit containing the integrated presentation and fixture changes, confirm that the fixture executable built, and have someone who authored neither the fixture nor the presentation bridge verify the D3DMetal run and pixel-mismatch control. The shader gate still requires a recorded D1/D2 selection. [Fixture and receipts](https://github.com/MacosPorters/betterxen/pull/494) · [ADR 0008](adr/0008-m2-shader-format-gate.md)
|
||||
- **Shader format gate (#466, ADR 0008).** D1 remains the only branch with end-to-end execution evidence, and the static scan gives it measured inputs in the target workload: 52 DXIL SM 6.5 compute containers with LLVM bitcode. The same scan makes D2 a concrete compatibility candidate rather than a hypothesis: the workload's FidelityFX upscaler component embeds 29 ACCC-only containers. Select D2 work only when a required pipeline-creation path refuses an ACCC-only container at runtime — if that refusal precedes the first presented frame, treat it as a first-frame blocker; if it appears only with upscaling enabled, track it under M4 upscaling. Two Track D parser prerequisites precede any D2 trial: extend the clean-room `FSPX` section-table layout to accept the observed tables (a maintainer provenance decision, since no public format description exists), and stop the classifier from treating a `NOBC` header-only program as executable DXIL. The first `shader_gate` record the target workload writes names the shader path its first pipeline creation actually submits. [ADR 0008](adr/0008-m2-shader-format-gate.md)
|
||||
- **Title budget (#550, #552).** Keep current allocation ownership and give xmem atomic admission authority through an ABI-first contract. The initial scope combines xmem usage with the existing charged `CreateHeap` path. Under a 512 MiB cap, an xmem allocation of 256 MiB followed by a 384 MiB heap was refused, while the reverse admitted 640 MiB. Test both orders, concurrent admission and rollback. Charge a backing allocation once across aliases. Accounting for `CreateHeap1`, committed and reserved resources, and internal buffers such as XCRDAPI staging remains an open scope decision. Placement and wrapper lifetime have separate checks (#554, #572). [Merged-base reproduction](https://github.com/MacosPorters/betterxen/pull/486#issuecomment-7209751182)
|
||||
- **M3 resource handling.** Keep explicit paths for fixed addresses, existing contents, pre-device allocations, sections/scatter and opaque textures. The draft eligibility analysis found no reliable end-to-end classifier. Resolve the `XMemVirtualAlloc` argument-count question (#518) before using graphics flags as evidence. A mapped-buffer trial is optional and opt-in, with the existing path as fallback. Require a known consumer before returning a pointer, verify its alignment and lifetime, and confirm completion on every participating queue before reusing memory for work BetterXen submits. #483 retains its DirectStorage interface scope. [Draft eligibility analysis](https://github.com/MacosPorters/betterxen/blob/7e0b515131150fec6b5117c9498b6c0faf0ca382/docs/architecture/proposals/001-unified-memory/appendix/eligibility.md)
|
||||
- **M6 optimization.** Compare the existing path with a candidate allocator or bounded pool on the same 16 GB host and backend. Check correct output for both paths across repeated matched workloads. Include cold setup, transfers, fragmentation, pending retirements, post-release footprint and whole-frame time. Require a repeatable workload benefit before choosing a default.
|
||||
**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
|
||||
);
|
||||
}
|
||||
}
|
||||
+1018
-27
File diff suppressed because it is too large.
Load diff
@@ -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"));
|
||||
}
|
||||
@@ -18,6 +18,9 @@ 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).
|
||||
@@ -182,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();
|
||||
@@ -344,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
|
||||
@@ -420,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#"
|
||||
|
||||
@@ -21,7 +21,7 @@ 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*$")
|
||||
|
||||
@@ -227,5 +227,70 @@ class CheckLinksTests(unittest.TestCase):
|
||||
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);
|
||||
}
|
||||
@@ -100,6 +100,55 @@ 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,
|
||||
@@ -1787,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,487 @@
|
||||
/*
|
||||
* Pipeline states on the Xbox-layout device (ADR 0009), and the opt-in null-render mode.
|
||||
*
|
||||
* Every pipeline creation goes through the M2 shader format gate (shader_gate.h, ADR 0008), so
|
||||
* each stage writes a `shader_gate` record, and the title's root signature is unwrapped before
|
||||
* the description reaches the host. The Xbox *X variants take extended descriptions
|
||||
* (D3D12XBOX_EXTENDED_*_PIPELINE_STATE_DESC) that have no host equivalent; their count is logged
|
||||
* and the base description is created.
|
||||
*
|
||||
* Null-render mode (BX_NULL_RENDER=1, off by default): a pipeline the host refuses, for example
|
||||
* one whose shaders are console-only, becomes a BetterXen null pipeline instead of a failure.
|
||||
* Binding it is recorded per command list, and draws and dispatches recorded while it is bound
|
||||
* are skipped. Everything else still runs, so fences complete and frames present, with the
|
||||
* skipped work missing from them. Each refusal and each skip is logged: the mode exists to see
|
||||
* how far a title gets, not to hide what it cannot run.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include "proxy.h"
|
||||
#include "shader_gate.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
|
||||
namespace {
|
||||
|
||||
bool null_render_enabled() {
|
||||
static const bool enabled = [] {
|
||||
char value[8] = {};
|
||||
const DWORD n = GetEnvironmentVariableA("BX_NULL_RENDER", value, sizeof(value));
|
||||
const bool on = n > 0 && n < sizeof(value) && value[0] == '1';
|
||||
if (on) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "null_render", "enabled: refused pipelines become null pipelines");
|
||||
return on;
|
||||
}();
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/* A pipeline-state object with no host pipeline behind it. */
|
||||
class NullPipelineState final : public ID3D12PipelineState {
|
||||
public:
|
||||
explicit NullPipelineState(ID3D12Device* device) : device_(device) { device_->AddRef(); }
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) ||
|
||||
riid == __uuidof(ID3D12Pageable) || riid == __uuidof(ID3D12PipelineState)) {
|
||||
*ppv = static_cast<ID3D12PipelineState*>(this);
|
||||
AddRef();
|
||||
return S_OK;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
|
||||
ULONG STDMETHODCALLTYPE Release() override {
|
||||
const ULONG left = --refs_;
|
||||
if (!left) {
|
||||
device_->Release();
|
||||
delete this;
|
||||
}
|
||||
return left;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT* size, void*) override {
|
||||
if (size) *size = 0;
|
||||
return DXGI_ERROR_NOT_FOUND;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; }
|
||||
HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; }
|
||||
HRESULT STDMETHODCALLTYPE SetName(LPCWSTR) override { return S_OK; }
|
||||
HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** ppv) override { return device_->QueryInterface(riid, ppv); }
|
||||
HRESULT STDMETHODCALLTYPE GetCachedBlob(ID3DBlob** blob) override {
|
||||
if (blob) *blob = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
private:
|
||||
ID3D12Device* device_;
|
||||
std::atomic<ULONG> refs_{1};
|
||||
};
|
||||
|
||||
std::mutex g_lock;
|
||||
NullPipelineState** g_nulls = nullptr; // live null pipelines, so they can be recognised
|
||||
size_t g_null_count = 0;
|
||||
size_t g_null_capacity = 0;
|
||||
ID3D12GraphicsCommandList** g_lists = nullptr; // lists whose bound pipeline is a null pipeline
|
||||
size_t g_list_count = 0;
|
||||
size_t g_list_capacity = 0;
|
||||
|
||||
template <typename T>
|
||||
bool push(T**& items, size_t& count, size_t& capacity, T* item) {
|
||||
if (count == capacity) {
|
||||
const size_t grown_capacity = capacity ? capacity * 2 : 16;
|
||||
auto** grown = new (std::nothrow) T*[grown_capacity];
|
||||
if (!grown) return false;
|
||||
for (size_t i = 0; i < count; ++i) grown[i] = items[i];
|
||||
delete[] items;
|
||||
items = grown;
|
||||
capacity = grown_capacity;
|
||||
}
|
||||
items[count++] = item;
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool erase(T** items, size_t& count, const T* item) {
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (items[i] == item) {
|
||||
items[i] = items[--count];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool contains(T* const* items, size_t count, const T* item) {
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
if (items[i] == item) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Returns the host pipeline for a title pipeline, or nullptr for a null pipeline. */
|
||||
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null) {
|
||||
ID3D12PipelineState* host = bx_xbox_unwrap_as(title);
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
*is_null = host && contains(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
|
||||
return *is_null ? nullptr : host;
|
||||
}
|
||||
|
||||
void set_list_null(ID3D12GraphicsCommandList* list, bool null_bound) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
const bool present = contains(g_lists, g_list_count, list);
|
||||
if (null_bound && !present) push(g_lists, g_list_count, g_list_capacity, list);
|
||||
if (!null_bound && present) erase(g_lists, g_list_count, list);
|
||||
}
|
||||
|
||||
bool list_skips(ID3D12GraphicsCommandList* list, const char* what) {
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (!contains(g_lists, g_list_count, list)) return false;
|
||||
}
|
||||
static std::atomic<uint64_t> skipped{0};
|
||||
const uint64_t n = ++skipped;
|
||||
if ((n & (n - 1)) == 0) { // 1, 2, 4, 8, ...: enough to follow without flooding the log
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "%s with a null pipeline bound; total skipped=%llu", what,
|
||||
static_cast<unsigned long long>(n));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "null_render_skip", detail);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid, void** ppv) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "%s pipeline refused hr=0x%08lx%s", kind, static_cast<unsigned long>(hr),
|
||||
null_render_enabled() ? "; null pipeline returned" : "");
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_refused", detail);
|
||||
if (!null_render_enabled() || !ppv) return hr;
|
||||
auto* null_pso = new (std::nothrow) NullPipelineState(device);
|
||||
if (!null_pso) return E_OUTOFMEMORY;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (!push(g_nulls, g_null_count, g_null_capacity, null_pso)) {
|
||||
null_pso->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
*ppv = static_cast<ID3D12PipelineState*>(null_pso);
|
||||
return bx_xbox_wrap_result(S_OK, riid, ppv);
|
||||
}
|
||||
|
||||
void log_extended(const char* kind, UINT count) {
|
||||
if (!count) return;
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "%s: %u extended description(s) not applied", kind, count);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_extended_desc", detail);
|
||||
}
|
||||
|
||||
HRESULT create_compute(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
BxShaderGate gate;
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC admitted = *desc;
|
||||
admitted.pRootSignature = bx_xbox_unwrap_as(desc->pRootSignature);
|
||||
HRESULT hr = gate.admit("compute", "CS", desc->CS, admitted.CS);
|
||||
if (SUCCEEDED(hr)) hr = device->CreateComputePipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "compute", riid, ppv);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT create_graphics(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
BxShaderGate gate;
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC admitted = *desc;
|
||||
admitted.pRootSignature = bx_xbox_unwrap_as(desc->pRootSignature);
|
||||
HRESULT hr = gate.admit("graphics", "VS", desc->VS, admitted.VS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "PS", desc->PS, admitted.PS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "DS", desc->DS, admitted.DS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "HS", desc->HS, admitted.HS);
|
||||
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "GS", desc->GS, admitted.GS);
|
||||
if (SUCCEEDED(hr)) hr = device->CreateGraphicsPipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "graphics", riid, ppv);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
auto* device = bx_xbox_host<ID3D12Device2>(self);
|
||||
std::vector<uint8_t> stream;
|
||||
std::vector<size_t> offsets;
|
||||
std::vector<const char*> names;
|
||||
size_t root_offset = SIZE_MAX;
|
||||
HRESULT hr = copy_stream(*desc, stream, offsets, names, &root_offset);
|
||||
if (FAILED(hr)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "stream of %llu bytes not parsed (unknown or console subobject?)",
|
||||
static_cast<unsigned long long>(desc->SizeInBytes));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pso_stream", detail);
|
||||
return refused(device, hr, "stream", riid, ppv);
|
||||
}
|
||||
if (root_offset != SIZE_MAX) {
|
||||
ID3D12RootSignature* root = nullptr;
|
||||
std::memcpy(&root, &stream[root_offset], sizeof(root));
|
||||
root = bx_xbox_unwrap_as(root);
|
||||
std::memcpy(&stream[root_offset], &root, sizeof(root));
|
||||
}
|
||||
BxShaderGate gate;
|
||||
for (size_t i = 0; i < offsets.size() && SUCCEEDED(hr); ++i) {
|
||||
D3D12_SHADER_BYTECODE in{};
|
||||
std::memcpy(&in, &stream[offsets[i]], sizeof(in));
|
||||
D3D12_SHADER_BYTECODE out = in;
|
||||
hr = gate.admit("stream", names[i], in, out);
|
||||
if (SUCCEEDED(hr)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
|
||||
}
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
|
||||
admitted.pPipelineStateSubobjectStream = stream.data();
|
||||
if (SUCCEEDED(hr)) hr = device->CreatePipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_pipeline_state(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePipelineState");
|
||||
return create_stream(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
bool bx_xbox_pipeline_is_null(ID3D12PipelineState* title) {
|
||||
bool is_null = false;
|
||||
host_pipeline(title, &is_null);
|
||||
return is_null;
|
||||
}
|
||||
|
||||
void bx_xbox_pipeline_forget(IUnknown* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
erase(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
|
||||
}
|
||||
|
||||
void bx_xbox_list_forget(IUnknown* host) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
erase(g_lists, g_list_count, static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineState");
|
||||
return create_compute(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateGraphicsPipelineState");
|
||||
return create_graphics(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state_x(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
|
||||
UINT extended_count, const void*, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineStateX");
|
||||
log_extended("CreateComputePipelineStateX", extended_count);
|
||||
return create_compute(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_graphics_pipeline_state_x(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc,
|
||||
UINT extended_count, const void*, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateGraphicsPipelineStateX");
|
||||
log_extended("CreateGraphicsPipelineStateX", extended_count);
|
||||
return create_graphics(self, desc, riid, ppv);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12PipelineState* pso) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetPipelineState");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
bool is_null = false;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
|
||||
set_list_null(list, is_null);
|
||||
if (!is_null) list->SetPipelineState(host);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Reset");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
bool is_null = false;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
|
||||
set_list_null(list, is_null);
|
||||
bx_xbox_gpu_writes_reset(list);
|
||||
return list->Reset(bx_xbox_unwrap_as(allocator), host);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UINT instances, UINT first_vertex,
|
||||
UINT first_instance) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawInstanced");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (!list_skips(list, "DrawInstanced")) list->DrawInstanced(vertices, instances, first_vertex, first_instance);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indices, UINT instances, UINT first_index,
|
||||
INT base_vertex, UINT first_instance) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawIndexedInstanced");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (!list_skips(list, "DrawIndexedInstanced")) {
|
||||
list->DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance);
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Dispatch");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (!list_skips(list, "Dispatch")) list->Dispatch(x, y, z);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSignature* signature, UINT max_commands,
|
||||
ID3D12Resource* arguments, UINT64 arguments_offset,
|
||||
ID3D12Resource* count, UINT64 count_offset) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "ExecuteIndirect");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (list_skips(list, "ExecuteIndirect")) return;
|
||||
list->ExecuteIndirect(bx_xbox_unwrap_as(signature), max_commands, bx_xbox_unwrap_as(arguments), arguments_offset,
|
||||
bx_xbox_unwrap_as(count), count_offset);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
|
||||
ID3D12RootSignature* root, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommandSignature");
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
// D3D12XBOX_INDIRECT_ARGUMENT_TYPE_* values start at 100 and have no PC equivalent, except
|
||||
// DISPATCH_SINGLE / DISPATCH_L2 (105): a dispatch whose arguments are D3D12_DISPATCH_ARGUMENTS
|
||||
// and whose D3D12XBOX_DISPATCH_FLAGS are a direct parameter (authorized GDK documentation), so
|
||||
// the host gets D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH. The flags are cache hints and are dropped.
|
||||
constexpr int kFirstXboxArgument = 100;
|
||||
constexpr int kXboxDispatchSingle = 105;
|
||||
constexpr UINT kMaxArguments = 32;
|
||||
D3D12_INDIRECT_ARGUMENT_DESC host_args[kMaxArguments] = {};
|
||||
char types[160] = {};
|
||||
size_t used = 0;
|
||||
bool console_only = desc->NumArgumentDescs > kMaxArguments;
|
||||
for (UINT i = 0; i < desc->NumArgumentDescs && i < kMaxArguments && desc->pArgumentDescs; ++i) {
|
||||
const int type = static_cast<int>(desc->pArgumentDescs[i].Type);
|
||||
host_args[i] = desc->pArgumentDescs[i];
|
||||
if (type == kXboxDispatchSingle) {
|
||||
host_args[i] = {};
|
||||
host_args[i].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH;
|
||||
} else if (type >= kFirstXboxArgument) {
|
||||
console_only = true;
|
||||
}
|
||||
if (used < sizeof(types) - 8) used += std::snprintf(types + used, sizeof(types) - used, "%s%d", i ? "," : "", type);
|
||||
}
|
||||
D3D12_COMMAND_SIGNATURE_DESC host_desc = *desc;
|
||||
host_desc.pArgumentDescs = host_args;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
HRESULT hr = console_only ? E_NOTIMPL
|
||||
: device->CreateCommandSignature(&host_desc, bx_xbox_unwrap_as(root), riid, ppv);
|
||||
char detail[256];
|
||||
std::snprintf(detail, sizeof(detail), "stride=%u args=[%s] root_signature=%d hr=0x%08lx%s", desc->ByteStride, types,
|
||||
root ? 1 : 0, static_cast<unsigned long>(hr), console_only ? " (console argument types)" : "");
|
||||
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "command_signature", detail);
|
||||
return SUCCEEDED(hr) ? bx_xbox_wrap_result(hr, riid, ppv) : hr;
|
||||
}
|
||||
|
||||
namespace {
|
||||
void log_once(std::atomic<bool>& flag, const char* event, const char* detail) {
|
||||
if (!flag.exchange(true)) bx_log_emit(BX_LOG_INFO, "d3d12_xs", event, detail);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_list_reset_x(void* self, ID3D12CommandAllocator* allocator, ID3D12PipelineState* pso,
|
||||
UINT flags) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "ResetX");
|
||||
static std::atomic<bool> logged{false};
|
||||
if (flags) log_once(logged, "reset_x_flags", "D3D12XBOX_COMMAND_LIST_RESET_FLAGS have no host meaning; ignored");
|
||||
return bx_xbox_list_reset(self, allocator, pso);
|
||||
}
|
||||
|
||||
// Console cache synchronisation points. The closest host D3D12 operation is a global UAV
|
||||
// barrier: all prior UAV work completes before later work starts.
|
||||
void STDMETHODCALLTYPE bx_xbox_list_sync_x(void* self, UINT, UINT, D3D12_GPU_VIRTUAL_ADDRESS, SIZE_T) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SyncTopOfPipeX/SyncBottomOfPipeX");
|
||||
static std::atomic<bool> logged{false};
|
||||
log_once(logged, "sync_x", "SyncTopOfPipeX/SyncBottomOfPipeX recorded as a global UAV barrier");
|
||||
D3D12_RESOURCE_BARRIER barrier{};
|
||||
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResourceBarrier(1, &barrier);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void*, void* callback, UINT64) {
|
||||
BX_D3D_TRACE("XboxCommandAllocator", "SetAllocatorCallbackX");
|
||||
static std::atomic<bool> logged{false};
|
||||
if (callback) {
|
||||
log_once(logged, "allocator_callback_x",
|
||||
"SetAllocatorCallbackX accepted; host command lists do not allocate from title memory, so it is never called");
|
||||
}
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
/*
|
||||
* DeserializeGraphics/ComputePipelineStateX create a pipeline from a serialized console pipeline
|
||||
* (console shader code), which has no host form. They fail with E_NOTIMPL (logged as a refused
|
||||
* pipeline); in null-render mode they return a null pipeline like any other refused pipeline.
|
||||
*/
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void*, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeGraphicsPipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized graphics (console code)", riid, ppv);
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void*, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "DeserializeComputePipelineStateX");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized compute (console code)", riid, ppv);
|
||||
}
|
||||
|
||||
/*
|
||||
* CreateDerived{Graphics,Compute}PipelineStateX: a pipeline equal to `source` with some state
|
||||
* groups replaced. Derived from a null pipeline, the result is a null pipeline too. Deriving
|
||||
* from a host pipeline needs its creation description, which this layer does not keep yet: that
|
||||
* case is refused (logged) and, in null-render mode, is a null pipeline as well.
|
||||
*/
|
||||
namespace {
|
||||
HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv, const char* kind) {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
const bool from_null = bx_xbox_pipeline_is_null(source);
|
||||
if (!from_null) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 4) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_derived",
|
||||
"deriving from a host pipeline is not implemented (its creation description is not kept)");
|
||||
}
|
||||
}
|
||||
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, kind, riid, ppv);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDerivedGraphicsPipelineStateX");
|
||||
return derived(self, source, riid, ppv, "derived graphics");
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
|
||||
UINT, const void*, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDerivedComputePipelineStateX");
|
||||
return derived(self, source, riid, ppv, "derived compute");
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
/*
|
||||
* Resources placed at a title-chosen GPU virtual address (ADR 0009, "translation by copy").
|
||||
*
|
||||
* On the console a title maps its own physical pages at an address and places resources there
|
||||
* with ID3D12Device::CreatePlacedResourceX / CreatePlacedResourceX1; CPU and GPU see the same
|
||||
* memory. D3DMetal cannot create a resource over existing memory (the existing-memory imports
|
||||
* measured for #473 return E_NOTIMPL), so each such resource gets a shadow resource on the host:
|
||||
*
|
||||
* - a buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's
|
||||
* memory when it is created;
|
||||
* - a texture gets a committed texture whose contents are not filled (logged); texture
|
||||
* contents need the console tiling translation (xg_xs) first.
|
||||
*
|
||||
* The title's address and the shadow are recorded, and the resource reports the title's address
|
||||
* from GetGPUVirtualAddress. Keeping the shadow in step with later CPU writes, and translating
|
||||
* title addresses in GPU calls, are not done yet; both are logged when reached.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
|
||||
extern "C" __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
|
||||
|
||||
namespace {
|
||||
|
||||
struct Shadow {
|
||||
ID3D12Resource* host; // owned by the Xbox object, or (implicit shadows) by this table
|
||||
uint64_t title_va;
|
||||
uint64_t size;
|
||||
bool buffer;
|
||||
D3D12_RESOURCE_DESC desc;
|
||||
ULONGLONG title_attributes; // non-zero: title_va came from XMemAlloc and is freed with the resource
|
||||
int mapped = 0; // outstanding Map calls on title memory (buffers)
|
||||
};
|
||||
|
||||
// Copies between a buffer's title memory and its host resource, when the host is CPU-mappable.
|
||||
bool copy_buffer(const Shadow& s, bool to_host, uint64_t begin, uint64_t end) {
|
||||
if (!s.buffer || end <= begin || end > s.size) return false;
|
||||
void* mapped = nullptr;
|
||||
const D3D12_RANGE none{0, 0};
|
||||
if (FAILED(s.host->Map(0, to_host ? &none : nullptr, &mapped)) || !mapped) return false;
|
||||
auto* host = static_cast<uint8_t*>(mapped) + begin;
|
||||
auto* title = reinterpret_cast<uint8_t*>(s.title_va) + begin;
|
||||
if (to_host) std::memcpy(host, title, static_cast<size_t>(end - begin));
|
||||
else std::memcpy(title, host, static_cast<size_t>(end - begin));
|
||||
const D3D12_RANGE written{static_cast<SIZE_T>(begin), static_cast<SIZE_T>(end)};
|
||||
s.host->Unmap(0, to_host ? &written : &none);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::mutex g_lock;
|
||||
Shadow* g_shadows = nullptr;
|
||||
size_t g_count = 0;
|
||||
size_t g_capacity = 0;
|
||||
|
||||
bool remember(const Shadow& shadow) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (g_count == g_capacity) {
|
||||
const size_t capacity = g_capacity ? g_capacity * 2 : 64;
|
||||
auto* grown = new (std::nothrow) Shadow[capacity];
|
||||
if (!grown) return false;
|
||||
if (g_count) std::memcpy(grown, g_shadows, g_count * sizeof(Shadow));
|
||||
delete[] g_shadows;
|
||||
g_shadows = grown;
|
||||
g_capacity = capacity;
|
||||
}
|
||||
g_shadows[g_count++] = shadow;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool readable(const void* p, uint64_t size) {
|
||||
auto cursor = reinterpret_cast<uintptr_t>(p);
|
||||
const uintptr_t end = cursor + size;
|
||||
while (cursor < end) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(cursor), ®ion, sizeof(region)) || region.State != MEM_COMMIT
|
||||
|| (region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
|
||||
return false;
|
||||
}
|
||||
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc, const char* method,
|
||||
ID3D12Resource** out) {
|
||||
*out = nullptr;
|
||||
const bool buffer = desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
if (buffer) {
|
||||
heap.Type = D3D12_HEAP_TYPE_CUSTOM;
|
||||
heap.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
|
||||
heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
} else {
|
||||
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
}
|
||||
D3D12_RESOURCE_DESC host_desc = desc;
|
||||
// Console tiling layouts and D3D12XBOX_RESOURCE_FLAG_* bits have no PC meaning.
|
||||
constexpr UINT kPcResourceFlags = 0x1FF;
|
||||
host_desc.Layout = buffer ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN;
|
||||
host_desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(desc.Flags & kPcResourceFlags);
|
||||
ID3D12Resource* resource = nullptr;
|
||||
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON,
|
||||
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
|
||||
char detail[224];
|
||||
std::snprintf(detail, sizeof(detail), "%s title_va=0x%llx dim=%d width=%llu height=%u format=%d hr=0x%08lx",
|
||||
method, static_cast<unsigned long long>(title_va), static_cast<int>(desc.Dimension),
|
||||
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<int>(desc.Format),
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(SUCCEEDED(hr) ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", detail);
|
||||
if (FAILED(hr) || !resource) return FAILED(hr) ? hr : E_FAIL;
|
||||
|
||||
const auto* title = reinterpret_cast<const void*>(title_va);
|
||||
if (buffer) {
|
||||
void* mapped = nullptr;
|
||||
if (SUCCEEDED(resource->Map(0, nullptr, &mapped)) && mapped) {
|
||||
if (readable(title, desc.Width)) {
|
||||
std::memcpy(mapped, title, static_cast<size_t>(desc.Width));
|
||||
} else {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", "title memory not readable; shadow left zeroed");
|
||||
}
|
||||
resource->Unmap(0, nullptr);
|
||||
}
|
||||
} else {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "CreatePlacedResourceX(texture contents)");
|
||||
}
|
||||
if (!remember({resource, title_va, desc.Width, buffer, desc, 0})) {
|
||||
resource->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*out = resource;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT create_shadow(void* self, uint64_t title_va, const D3D12_RESOURCE_DESC& desc, REFIID riid, void** ppv,
|
||||
const char* method) {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
ID3D12Resource* resource = nullptr;
|
||||
const HRESULT hr = make_shadow(bx_xbox_host<ID3D12Device>(self), title_va, desc, method, &resource);
|
||||
if (FAILED(hr)) return hr;
|
||||
*ppv = resource;
|
||||
return bx_xbox_wrap_result(S_OK, riid, ppv);
|
||||
}
|
||||
|
||||
bool same_shape(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) {
|
||||
return a.Dimension == b.Dimension && a.Width == b.Width && a.Height == b.Height &&
|
||||
a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels == b.MipLevels && a.Format == b.Format;
|
||||
}
|
||||
|
||||
// A view of placed memory with no resource object: reuse the shadow made for the same address
|
||||
// and shape, or make one. These shadows live for the rest of the process (logged).
|
||||
ID3D12Resource* implicit_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc) {
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_shadows[i].title_va == title_va && same_shape(g_shadows[i].desc, desc)) return g_shadows[i].host;
|
||||
}
|
||||
}
|
||||
ID3D12Resource* resource = nullptr;
|
||||
return SUCCEEDED(make_shadow(device, title_va, desc, "implicit shadow for a placed view", &resource)) ? resource : nullptr;
|
||||
}
|
||||
|
||||
// The Xbox view descriptions start with the PC description's 40 bytes; ResourceLocation follows.
|
||||
constexpr size_t kPcViewDescBytes = 40;
|
||||
static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == kPcViewDescBytes, "PC SRV description size");
|
||||
static_assert(sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == kPcViewDescBytes, "PC UAV description size");
|
||||
|
||||
uint64_t view_location(const void* xbox_desc) {
|
||||
uint64_t va = 0;
|
||||
std::memcpy(&va, static_cast<const char*>(xbox_desc) + kPcViewDescBytes, sizeof(va));
|
||||
return va;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
|
||||
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedResourceX");
|
||||
if (!desc || !location) return E_INVALIDARG;
|
||||
return create_shadow(self, location, *desc, riid, ppv, "CreatePlacedResourceX");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource_x1(void* self, D3D12_GPU_VIRTUAL_ADDRESS location,
|
||||
const D3D12_RESOURCE_DESC1* desc1, UINT,
|
||||
const D3D12_CLEAR_VALUE*, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedResourceX1");
|
||||
if (!desc1 || !location) return E_INVALIDARG;
|
||||
// D3D12_RESOURCE_DESC1 is D3D12_RESOURCE_DESC followed by SamplerFeedbackMipRegion.
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
std::memcpy(&desc, desc1, sizeof(desc));
|
||||
return create_shadow(self, location, desc, riid, ppv, "CreatePlacedResourceX1");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedRawShaderResourceViewX");
|
||||
if (!resource_desc || !xbox_desc) return;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
ID3D12Resource* resource = implicit_shadow(device, view_location(xbox_desc), *resource_desc);
|
||||
if (!resource) return;
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
|
||||
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
device->CreateShaderResourceView(resource, &pc, bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
const void* xbox_desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedRawUnorderedAccessViewX");
|
||||
if (!resource_desc || !xbox_desc) return;
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
ID3D12Resource* resource = implicit_shadow(device, view_location(xbox_desc), *resource_desc);
|
||||
if (!resource) return;
|
||||
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
|
||||
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
device->CreateUnorderedAccessView(resource, nullptr, &pc, bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedShaderResourceViewX");
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
|
||||
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as(resource), xbox_desc ? &pc : nullptr,
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedUnorderedAccessViewX");
|
||||
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
|
||||
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateUnorderedAccessView(bx_xbox_unwrap_as(resource), nullptr,
|
||||
xbox_desc ? &pc : nullptr, bx_xbox_host_cpu_handle(dest));
|
||||
}
|
||||
|
||||
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title) {
|
||||
if (!title) return title;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
const Shadow& s = g_shadows[i];
|
||||
if (title >= s.title_va && title < s.title_va + s.size) return s.host->GetGPUVirtualAddress() + (title - s.title_va);
|
||||
}
|
||||
return title; // not a title address this layer knows: a host address already, or untranslated
|
||||
}
|
||||
|
||||
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes) {
|
||||
return remember({host, title_va, size, host->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER, host->GetDesc(),
|
||||
attributes});
|
||||
}
|
||||
|
||||
void bx_xbox_placed_forget(IUnknown* host) {
|
||||
Shadow gone{};
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (static_cast<IUnknown*>(g_shadows[i].host) == host) {
|
||||
gone = g_shadows[i];
|
||||
g_shadows[i] = g_shadows[--g_count];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (gone.title_attributes) XMemFree(reinterpret_cast<void*>(gone.title_va), gone.title_attributes);
|
||||
}
|
||||
|
||||
D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE bx_xbox_resource_get_gpu_virtual_address(void* self) {
|
||||
BX_D3D_TRACE("XboxResource", "GetGPUVirtualAddress");
|
||||
auto* host = bx_xbox_host<ID3D12Resource>(self);
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_shadows[i].host == host) return g_shadows[i].title_va;
|
||||
}
|
||||
}
|
||||
return host->GetGPUVirtualAddress();
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
/*
|
||||
* Page pools (RegisterPagePoolX / UnregisterPagePoolX, authorized GDK documentation): a title
|
||||
* registers a 64 KB-aligned, fully mapped range of its graphics memory as the source of later
|
||||
* CopyPageMappingsX calls. Registration is validated and recorded; the handle is the record.
|
||||
* CopyPageMappingsX itself (a queue method) is not implemented yet and stays a logged stub.
|
||||
*/
|
||||
namespace {
|
||||
|
||||
struct PagePool {
|
||||
uint64_t address;
|
||||
UINT pages;
|
||||
PagePool* next;
|
||||
};
|
||||
|
||||
PagePool* g_pools = nullptr; // guarded by g_lock
|
||||
|
||||
bool fully_mapped(uint64_t address, uint64_t size) {
|
||||
auto cursor = static_cast<uintptr_t>(address);
|
||||
const uintptr_t end = cursor + static_cast<uintptr_t>(size);
|
||||
while (cursor < end) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(cursor), ®ion, sizeof(region)) || region.State != MEM_COMMIT) {
|
||||
return false;
|
||||
}
|
||||
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_register_page_pool_x(void*, D3D12_GPU_VIRTUAL_ADDRESS address, UINT pages,
|
||||
HANDLE* handle) {
|
||||
BX_D3D_TRACE("XboxDevice", "RegisterPagePoolX");
|
||||
constexpr uint64_t kPage = 64 * 1024;
|
||||
const bool valid = handle && pages && address && (address % kPage) == 0 && fully_mapped(address, pages * kPage);
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "address=0x%llx pages=%u %s", static_cast<unsigned long long>(address), pages,
|
||||
valid ? "registered" : "rejected (unaligned, empty or not fully mapped)");
|
||||
bx_log_emit(valid ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "page_pool", detail);
|
||||
if (!valid) return E_INVALIDARG;
|
||||
auto* pool = new (std::nothrow) PagePool{address, pages, nullptr};
|
||||
if (!pool) return E_OUTOFMEMORY;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
pool->next = g_pools;
|
||||
g_pools = pool;
|
||||
}
|
||||
*handle = pool;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void*, HANDLE handle) {
|
||||
BX_D3D_TRACE("XboxDevice", "UnregisterPagePoolX");
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (PagePool** link = &g_pools; *link; link = &(*link)->next) {
|
||||
if (*link == handle) {
|
||||
PagePool* gone = *link;
|
||||
*link = gone->next;
|
||||
delete gone;
|
||||
return S_OK;
|
||||
}
|
||||
}
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
/*
|
||||
* Map on a resource that has title-visible memory (placed at a title address, or committed with
|
||||
* XMemAlloc memory) returns that memory, as on the console, where CPU and GPU share it. Other
|
||||
* resources map their host resource. Writes through the title pointer reach the host resource
|
||||
* only where this layer copies them (buffers at creation; texture contents are not copied yet,
|
||||
* logged at creation).
|
||||
*/
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subresource, const D3D12_RANGE* read, void** data) {
|
||||
BX_D3D_TRACE("XboxResource", "Map");
|
||||
auto* host = bx_xbox_host<ID3D12Resource>(self);
|
||||
uint64_t title_va = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
Shadow& s = g_shadows[i];
|
||||
if (s.host != host) continue;
|
||||
title_va = s.title_va;
|
||||
// Make GPU results visible: refresh the read range of title memory from the host.
|
||||
const uint64_t begin = read ? read->Begin : 0, end = read ? read->End : s.size;
|
||||
if (s.buffer && end > begin) copy_buffer(s, false, begin, end < s.size ? end : s.size);
|
||||
++s.mapped;
|
||||
}
|
||||
}
|
||||
if (!title_va) {
|
||||
const HRESULT hr = host->Map(subresource, read, data);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxResource", "Map", hr);
|
||||
return hr;
|
||||
}
|
||||
if (subresource != 0) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 4) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "title_memory_map",
|
||||
"Map of a non-zero subresource of title memory returns the resource base");
|
||||
}
|
||||
}
|
||||
if (data) *data = reinterpret_cast<void*>(title_va);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
extern "C" void STDMETHODCALLTYPE bx_xbox_resource_unmap(void* self, UINT subresource, const D3D12_RANGE* written) {
|
||||
BX_D3D_TRACE("XboxResource", "Unmap");
|
||||
auto* host = bx_xbox_host<ID3D12Resource>(self);
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
Shadow& s = g_shadows[i];
|
||||
if (s.host != host) continue;
|
||||
// Hand the CPU's writes to the host resource (a null range means all of it).
|
||||
const uint64_t begin = written ? written->Begin : 0, end = written ? written->End : s.size;
|
||||
if (s.buffer && end > begin) copy_buffer(s, true, begin, end < s.size ? end : s.size);
|
||||
if (s.mapped > 0) --s.mapped;
|
||||
return;
|
||||
}
|
||||
}
|
||||
host->Unmap(subresource, written);
|
||||
}
|
||||
|
||||
/*
|
||||
* Before a submission, buffers the title keeps mapped (persistent maps) are copied from title
|
||||
* memory to their host resources, up to 16 MB each; larger ones are logged once and not copied.
|
||||
*/
|
||||
void bx_xbox_sync_mapped_buffers() {
|
||||
constexpr uint64_t kLimit = 16ull << 20;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
const Shadow& s = g_shadows[i];
|
||||
if (!s.mapped || !s.buffer) continue;
|
||||
if (s.size > kLimit) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 4) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "persistently mapped buffer of %llu bytes not copied to the host before submit",
|
||||
static_cast<unsigned long long>(s.size));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "title_memory_sync", detail);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
copy_buffer(s, true, 0, s.size);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
#include "presentx.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <new>
|
||||
|
||||
#include "proxy.h"
|
||||
|
||||
/*
|
||||
* Track C (M2-C2, #465). See presentx.h for the contract and for what this is not.
|
||||
* Host DXGI is loaded on demand, like the host d3d12.dll in d3d12_xs.cpp.
|
||||
*/
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr HRESULT kWaitTimedOut = static_cast<HRESULT>(0x800705B4u); /* HRESULT_FROM_WIN32(ERROR_TIMEOUT) */
|
||||
|
||||
bool is_device_removed_hr(HRESULT hr) {
|
||||
return hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_HUNG ||
|
||||
hr == DXGI_ERROR_DEVICE_RESET || hr == DXGI_ERROR_DRIVER_INTERNAL_ERROR;
|
||||
}
|
||||
|
||||
void log_hr(bx_log_level_t level, const char* event, const char* what, HRESULT hr) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s hr=0x%08lx", what, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(level, "d3d12_xs", event, detail);
|
||||
}
|
||||
|
||||
/* Releases an already acquired lock and records its owner, so re-entry can be refused. */
|
||||
class SrwOwner {
|
||||
public:
|
||||
SrwOwner(SRWLOCK& lock, std::atomic<DWORD>& owner) : lock_(lock), owner_(owner) { owner_ = GetCurrentThreadId(); }
|
||||
~SrwOwner() {
|
||||
owner_ = 0;
|
||||
ReleaseSRWLockExclusive(&lock_);
|
||||
}
|
||||
SrwOwner(const SrwOwner&) = delete;
|
||||
SrwOwner& operator=(const SrwOwner&) = delete;
|
||||
|
||||
private:
|
||||
SRWLOCK& lock_;
|
||||
std::atomic<DWORD>& owner_;
|
||||
};
|
||||
|
||||
class BxPresentSwapChain final : public IBxPresentSwapChain {
|
||||
public:
|
||||
/* `queue_proxy` is referenced for the lifetime of the chain; `host_queue` is its host object. */
|
||||
static HRESULT create(ID3D12CommandQueue* queue_proxy, ID3D12CommandQueue* host_queue, HWND window,
|
||||
const BxPresentDesc& desc, IBxPresentSwapChain** out);
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override;
|
||||
ULONG STDMETHODCALLTYPE AddRef() override;
|
||||
ULONG STDMETHODCALLTYPE Release() override;
|
||||
|
||||
HRESULT STDMETHODCALLTYPE GetBuffer(UINT index, REFIID riid, void** ppv) override;
|
||||
UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() override;
|
||||
HRESULT STDMETHODCALLTYPE Present(UINT sync_interval, UINT flags) override;
|
||||
HRESULT STDMETHODCALLTYPE WaitForIdle(DWORD timeout_ms) override;
|
||||
HRESULT STDMETHODCALLTYPE GetHostSwapChain(REFIID riid, void** ppv) override;
|
||||
|
||||
private:
|
||||
BxPresentSwapChain() = default;
|
||||
~BxPresentSwapChain() = default;
|
||||
|
||||
HRESULT init(HWND window, const BxPresentDesc& desc);
|
||||
HRESULT signal_locked(UINT64* value);
|
||||
HRESULT wait_locked(UINT64 value, ULONGLONG start, DWORD timeout_ms);
|
||||
HRESULT idle_locked(ULONGLONG start, DWORD timeout_ms);
|
||||
HRESULT post_present_failure(const char* event, const char* what, HRESULT hr, HRESULT live_device_result);
|
||||
HRESULT removed_reason();
|
||||
void destroy();
|
||||
|
||||
std::atomic<ULONG> refs_{1};
|
||||
SRWLOCK lock_ = SRWLOCK_INIT; /* guards the fence counter, the event and Present */
|
||||
ID3D12CommandQueue* queue_proxy_ = nullptr;
|
||||
ID3D12CommandQueue* host_queue_ = nullptr;
|
||||
HWND window_ = nullptr;
|
||||
IDXGISwapChain3* swap_ = nullptr;
|
||||
ID3D12Fence* fence_ = nullptr;
|
||||
HANDLE event_ = nullptr;
|
||||
std::atomic<DWORD> owner_{0}; /* thread holding lock_ */
|
||||
UINT64 last_signaled_ = 0;
|
||||
UINT64 presented_ = 0;
|
||||
bool needs_idle_ = false; /* post-present signal or wait failed; only an idle queue clears this */
|
||||
UINT64 buffer_value_[DXGI_MAX_SWAP_CHAIN_BUFFERS] = {};
|
||||
};
|
||||
|
||||
HRESULT BxPresentSwapChain::create(ID3D12CommandQueue* queue_proxy, ID3D12CommandQueue* host_queue, HWND window,
|
||||
const BxPresentDesc& desc, IBxPresentSwapChain** out) {
|
||||
auto* self = new (std::nothrow) BxPresentSwapChain();
|
||||
if (!self) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
queue_proxy->AddRef();
|
||||
self->queue_proxy_ = queue_proxy;
|
||||
host_queue->AddRef();
|
||||
self->host_queue_ = host_queue;
|
||||
self->window_ = window;
|
||||
|
||||
HRESULT hr = self->init(window, desc);
|
||||
if (FAILED(hr)) {
|
||||
self->destroy(); /* nothing was submitted, so every partially created object can go */
|
||||
return hr;
|
||||
}
|
||||
*out = self;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::init(HWND window, const BxPresentDesc& desc) {
|
||||
static HMODULE dxgi = LoadLibraryA("dxgi.dll");
|
||||
using CreateFactoryFn = HRESULT(WINAPI*)(REFIID, void**);
|
||||
auto create_factory = dxgi
|
||||
? reinterpret_cast<CreateFactoryFn>(reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory1")))
|
||||
: nullptr;
|
||||
if (!create_factory) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_dxgi_missing", "dxgi.dll!CreateDXGIFactory1 not available");
|
||||
return DXGI_ERROR_UNSUPPORTED;
|
||||
}
|
||||
|
||||
IDXGIFactory4* factory = nullptr;
|
||||
HRESULT hr = create_factory(__uuidof(IDXGIFactory4), reinterpret_cast<void**>(&factory));
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateDXGIFactory1", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
DXGI_SWAP_CHAIN_DESC1 sd = {};
|
||||
sd.Width = desc.width;
|
||||
sd.Height = desc.height;
|
||||
sd.Format = desc.format;
|
||||
sd.SampleDesc.Count = 1;
|
||||
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
|
||||
sd.BufferCount = desc.buffer_count;
|
||||
sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
|
||||
|
||||
IDXGISwapChain1* swap1 = nullptr;
|
||||
/* For D3D12 the "device" argument of CreateSwapChainForHwnd is the command queue. */
|
||||
hr = factory->CreateSwapChainForHwnd(host_queue_, window, &sd, nullptr, nullptr, &swap1);
|
||||
if (SUCCEEDED(hr)) {
|
||||
/* Alt+Enter would require ResizeBuffers handling that the bridge does not have. */
|
||||
HRESULT assoc = factory->MakeWindowAssociation(window, DXGI_MWA_NO_ALT_ENTER);
|
||||
if (FAILED(assoc)) {
|
||||
log_hr(BX_LOG_WARN, "present_window_association", "MakeWindowAssociation", assoc);
|
||||
}
|
||||
}
|
||||
factory->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateSwapChainForHwnd", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
hr = swap1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void**>(&swap_));
|
||||
swap1->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "QueryInterface(IDXGISwapChain3)", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
ID3D12Device* device = nullptr;
|
||||
hr = host_queue_->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence_));
|
||||
device->Release();
|
||||
}
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateFence", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
event_ = CreateEventA(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!event_) {
|
||||
hr = HRESULT_FROM_WIN32(GetLastError());
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateEvent", hr);
|
||||
return hr;
|
||||
}
|
||||
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "width=%u height=%u format=%d buffers=%u",
|
||||
desc.width, desc.height, static_cast<int>(desc.format), desc.buffer_count);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "present_chain_created", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::removed_reason() {
|
||||
ID3D12Device* device = nullptr;
|
||||
HRESULT hr = host_queue_->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (FAILED(hr)) {
|
||||
return hr;
|
||||
}
|
||||
hr = device->GetDeviceRemovedReason();
|
||||
device->Release();
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::signal_locked(UINT64* value) {
|
||||
const UINT64 next = last_signaled_ + 1;
|
||||
HRESULT hr = host_queue_->Signal(fence_, next);
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_signal_failed", "ID3D12CommandQueue::Signal", hr);
|
||||
return hr;
|
||||
}
|
||||
last_signaled_ = next;
|
||||
*value = next;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::wait_locked(UINT64 value, ULONGLONG start, DWORD timeout_ms) {
|
||||
for (;;) {
|
||||
const UINT64 completed = fence_->GetCompletedValue();
|
||||
if (completed == UINT64_MAX) { /* the documented value after device removal */
|
||||
HRESULT reason = removed_reason();
|
||||
log_hr(BX_LOG_ERROR, "present_device_removed", "fence", reason);
|
||||
return FAILED(reason) ? reason : DXGI_ERROR_DEVICE_REMOVED;
|
||||
}
|
||||
if (completed >= value) {
|
||||
return S_OK;
|
||||
}
|
||||
const ULONGLONG elapsed = GetTickCount64() - start;
|
||||
if (elapsed >= timeout_ms) {
|
||||
break;
|
||||
}
|
||||
HRESULT hr = fence_->SetEventOnCompletion(value, event_);
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_wait_failed", "SetEventOnCompletion", hr);
|
||||
return hr;
|
||||
}
|
||||
const ULONGLONG elapsed_after_registration = GetTickCount64() - start;
|
||||
if (elapsed_after_registration >= timeout_ms) {
|
||||
continue; /* Recheck the fence before reporting a timeout. */
|
||||
}
|
||||
/* The event can be left over from an earlier timed-out wait, so the loop re-reads the fence. */
|
||||
DWORD waited = WaitForSingleObject(event_, static_cast<DWORD>(timeout_ms - elapsed_after_registration));
|
||||
if (waited == WAIT_FAILED) {
|
||||
hr = HRESULT_FROM_WIN32(GetLastError());
|
||||
log_hr(BX_LOG_ERROR, "present_wait_failed", "WaitForSingleObject", hr);
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "timeout_ms=%lu wanted=%llu completed=%llu", static_cast<unsigned long>(timeout_ms),
|
||||
static_cast<unsigned long long>(value), static_cast<unsigned long long>(fence_->GetCompletedValue()));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", detail);
|
||||
return kWaitTimedOut;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::post_present_failure(const char* event, const char* what, HRESULT hr,
|
||||
HRESULT live_device_result) {
|
||||
const HRESULT removed = removed_reason();
|
||||
if (FAILED(removed)) {
|
||||
log_hr(BX_LOG_ERROR, "present_device_removed", what, removed);
|
||||
return removed;
|
||||
}
|
||||
needs_idle_ = true;
|
||||
if (event) {
|
||||
log_hr(BX_LOG_ERROR, event, what, hr);
|
||||
}
|
||||
if (is_device_removed_hr(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_device_removed", what, hr);
|
||||
return hr;
|
||||
}
|
||||
return live_device_result;
|
||||
}
|
||||
|
||||
HRESULT BxPresentSwapChain::idle_locked(ULONGLONG start, DWORD timeout_ms) {
|
||||
if (GetTickCount64() - start >= timeout_ms) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "timeout_ms=%lu wanted=%llu completed=unknown; expired before Signal",
|
||||
static_cast<unsigned long>(timeout_ms), static_cast<unsigned long long>(last_signaled_ + 1));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", detail);
|
||||
return kWaitTimedOut;
|
||||
}
|
||||
UINT64 value = 0;
|
||||
HRESULT hr = signal_locked(&value);
|
||||
return FAILED(hr) ? hr : wait_locked(value, start, timeout_ms);
|
||||
}
|
||||
|
||||
void BxPresentSwapChain::destroy() {
|
||||
if (swap_ && fence_ && event_) {
|
||||
HRESULT idle = idle_locked(GetTickCount64(), BX_PRESENT_WAIT_MS);
|
||||
if (FAILED(idle) && SUCCEEDED(removed_reason())) {
|
||||
/* The device is alive and the GPU may still be using the back buffers. */
|
||||
log_hr(BX_LOG_ERROR, "present_chain_leaked", "queue not idle; GPU-visible objects deliberately not released", idle);
|
||||
/*
|
||||
* swap_, fence_, event_ and host_queue_ stay: pending work may touch them. The proxy
|
||||
* is only BetterXen's wrapper; host_queue_ keeps the host queue alive without it.
|
||||
*/
|
||||
ID3D12CommandQueue* proxy = queue_proxy_;
|
||||
delete this;
|
||||
proxy->Release();
|
||||
return;
|
||||
}
|
||||
}
|
||||
const bool had_swap = swap_ != nullptr;
|
||||
ULONG swap_refs = 0;
|
||||
if (swap_) swap_refs = swap_->Release();
|
||||
if (fence_) fence_->Release();
|
||||
if (event_) CloseHandle(event_);
|
||||
if (had_swap) {
|
||||
/*
|
||||
* The count the host's Release returned. Non-zero means something else still references
|
||||
* the swapchain: back buffers or host pointers the caller holds, or the host itself
|
||||
* (see docs/research/d3dmetal-swapchain-references.md). It is reported, never "fixed up"
|
||||
* by releasing references this object does not own.
|
||||
*/
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "presented=%llu swapchain_release_returned=%lu",
|
||||
static_cast<unsigned long long>(presented_), static_cast<unsigned long>(swap_refs));
|
||||
bx_log_emit(swap_refs ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "present_chain_destroyed", detail);
|
||||
}
|
||||
ID3D12CommandQueue* host_queue = host_queue_;
|
||||
ID3D12CommandQueue* queue_proxy = queue_proxy_;
|
||||
delete this;
|
||||
if (host_queue) host_queue->Release();
|
||||
if (queue_proxy) queue_proxy->Release();
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::QueryInterface(REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
if (IsEqualGUID(riid, __uuidof(IUnknown)) || IsEqualGUID(riid, IID_IBxPresentSwapChain)) {
|
||||
AddRef();
|
||||
*ppv = static_cast<IBxPresentSwapChain*>(this);
|
||||
return S_OK;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE BxPresentSwapChain::AddRef() {
|
||||
return refs_.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE BxPresentSwapChain::Release() {
|
||||
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (left == 0) {
|
||||
destroy();
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::GetBuffer(UINT index, REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
HRESULT hr = swap_->GetBuffer(index, riid, ppv);
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_WARN, "present_get_buffer_failed", "IDXGISwapChain::GetBuffer", hr);
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
UINT STDMETHODCALLTYPE BxPresentSwapChain::GetCurrentBackBufferIndex() {
|
||||
return swap_->GetCurrentBackBufferIndex();
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::Present(UINT sync_interval, UINT flags) {
|
||||
BX_D3D_TRACE("IBxPresentSwapChain", "Present");
|
||||
if (sync_interval > 4 || flags != 0 || !IsWindow(window_)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "sync=%u flags=0x%x window_alive=%d", sync_interval, flags,
|
||||
IsWindow(window_) ? 1 : 0);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_rejected", detail);
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
if (owner_ == GetCurrentThreadId()) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_rejected", "re-entered on the same thread");
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
/*
|
||||
* Never wait for the lock. Its holder may be inside the host's Present, and DXGI can make that
|
||||
* call wait for the window's thread: the caller here.
|
||||
*/
|
||||
if (!TryAcquireSRWLockExclusive(&lock_)) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_busy", "another call holds the swapchain; nothing presented");
|
||||
return BX_PRESENT_E_BUSY;
|
||||
}
|
||||
SrwOwner guard(lock_, owner_);
|
||||
if (needs_idle_) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_needs_idle", "completion unconfirmed; nothing presented");
|
||||
return BX_PRESENT_E_NEEDS_IDLE;
|
||||
}
|
||||
const UINT presented_index = swap_->GetCurrentBackBufferIndex();
|
||||
if (presented_index < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
|
||||
/* Busy only after an earlier BX_PRESENT_E_NEXT_BUFFER_BUSY. Nothing is presented then. */
|
||||
const HRESULT ready = wait_locked(buffer_value_[presented_index], GetTickCount64(), BX_PRESENT_WAIT_MS);
|
||||
if (FAILED(ready)) {
|
||||
return ready;
|
||||
}
|
||||
}
|
||||
HRESULT hr = swap_->Present(sync_interval, flags);
|
||||
if (FAILED(hr)) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "sync=%u flags=0x%x hr=0x%08lx device_removed_reason=0x%08lx", sync_interval,
|
||||
flags, static_cast<unsigned long>(hr), static_cast<unsigned long>(removed_reason()));
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_failed", detail);
|
||||
return hr;
|
||||
}
|
||||
++presented_;
|
||||
|
||||
UINT64 value = 0;
|
||||
HRESULT sync_hr = signal_locked(&value);
|
||||
if (FAILED(sync_hr)) {
|
||||
/* signal_locked already logged present_signal_failed when the device stays live. */
|
||||
return post_present_failure(nullptr, "signal after Present", sync_hr, BX_PRESENT_E_COMPLETION_UNCONFIRMED);
|
||||
}
|
||||
if (presented_index < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
|
||||
buffer_value_[presented_index] = value;
|
||||
}
|
||||
const UINT next = swap_->GetCurrentBackBufferIndex();
|
||||
if (next < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
|
||||
sync_hr = wait_locked(buffer_value_[next], GetTickCount64(), BX_PRESENT_WAIT_MS);
|
||||
if (sync_hr == kWaitTimedOut) {
|
||||
return BX_PRESENT_E_NEXT_BUFFER_BUSY;
|
||||
}
|
||||
if (FAILED(sync_hr)) {
|
||||
return post_present_failure("present_next_buffer_wait_failed", "wait_locked", sync_hr,
|
||||
BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED);
|
||||
}
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::WaitForIdle(DWORD timeout_ms) {
|
||||
if (timeout_ms == 0 || timeout_ms == INFINITE) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (owner_ == GetCurrentThreadId()) {
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
const ULONGLONG start = GetTickCount64();
|
||||
while (!TryAcquireSRWLockExclusive(&lock_)) {
|
||||
if (GetTickCount64() - start >= timeout_ms) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", "swapchain busy in another call");
|
||||
return kWaitTimedOut;
|
||||
}
|
||||
Sleep(1);
|
||||
}
|
||||
SrwOwner guard(lock_, owner_);
|
||||
const HRESULT hr = idle_locked(start, timeout_ms);
|
||||
if (hr == S_OK) {
|
||||
/* A signal queued after every presented frame has completed. */
|
||||
needs_idle_ = false;
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::GetHostSwapChain(REFIID riid, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*ppv = nullptr;
|
||||
return swap_->QueryInterface(riid, ppv);
|
||||
}
|
||||
|
||||
bool desc_is_valid(const BxPresentDesc& d) {
|
||||
const bool format_ok = d.format == DXGI_FORMAT_R8G8B8A8_UNORM || d.format == DXGI_FORMAT_B8G8R8A8_UNORM ||
|
||||
d.format == DXGI_FORMAT_R10G10B10A2_UNORM || d.format == DXGI_FORMAT_R16G16B16A16_FLOAT;
|
||||
return format_ok && d.width >= 1 && d.width <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && d.height >= 1 &&
|
||||
d.height <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && d.buffer_count >= 2 &&
|
||||
d.buffer_count <= DXGI_MAX_SWAP_CHAIN_BUFFERS;
|
||||
}
|
||||
|
||||
/* COM tear-off: its own reference count, one reference on the queue, and the queue's identity. */
|
||||
class BxPresentQueue final : public IBxPresentQueue {
|
||||
public:
|
||||
explicit BxPresentQueue(ID3D12CommandQueue* queue_proxy) : queue_(queue_proxy) { queue_->AddRef(); }
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
if (IsEqualGUID(riid, IID_IBxPresentQueue)) {
|
||||
AddRef();
|
||||
*ppv = static_cast<IBxPresentQueue*>(this);
|
||||
return S_OK;
|
||||
}
|
||||
return queue_->QueryInterface(riid, ppv);
|
||||
}
|
||||
|
||||
ULONG STDMETHODCALLTYPE AddRef() override { return refs_.fetch_add(1, std::memory_order_relaxed) + 1; }
|
||||
|
||||
ULONG STDMETHODCALLTYPE Release() override {
|
||||
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
|
||||
if (left == 0) {
|
||||
ID3D12CommandQueue* queue = queue_;
|
||||
delete this;
|
||||
queue->Release();
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE CreateSwapChain(HWND window, const BxPresentDesc* desc, IBxPresentSwapChain** out) override {
|
||||
if (!out) {
|
||||
return E_POINTER;
|
||||
}
|
||||
*out = nullptr;
|
||||
if (!desc) {
|
||||
return E_POINTER;
|
||||
}
|
||||
if (!window || !IsWindow(window) || !desc_is_valid(*desc)) {
|
||||
log_hr(BX_LOG_WARN, "present_create_rejected", "invalid window or description", DXGI_ERROR_INVALID_CALL);
|
||||
return DXGI_ERROR_INVALID_CALL;
|
||||
}
|
||||
ID3D12CommandQueue* host = nullptr;
|
||||
HRESULT hr = static_cast<IUnknown*>(bx_unwrap_raw(queue_))
|
||||
->QueryInterface(__uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&host));
|
||||
if (FAILED(hr)) {
|
||||
log_hr(BX_LOG_ERROR, "present_create_failed", "host command queue", hr);
|
||||
return hr;
|
||||
}
|
||||
D3D12_COMMAND_QUEUE_DESC queue_desc = {};
|
||||
host->GetDesc(&queue_desc);
|
||||
if (queue_desc.Type != D3D12_COMMAND_LIST_TYPE_DIRECT) {
|
||||
log_hr(BX_LOG_WARN, "present_create_rejected", "queue is not a DIRECT queue", DXGI_ERROR_INVALID_CALL);
|
||||
hr = DXGI_ERROR_INVALID_CALL;
|
||||
} else {
|
||||
hr = BxPresentSwapChain::create(queue_, host, window, *desc, out);
|
||||
}
|
||||
host->Release();
|
||||
return hr;
|
||||
}
|
||||
|
||||
private:
|
||||
~BxPresentQueue() = default;
|
||||
std::atomic<ULONG> refs_{1};
|
||||
ID3D12CommandQueue* queue_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
HRESULT bx_present_query_queue(ID3D12CommandQueue* queue_proxy, void** ppv) {
|
||||
if (!ppv) {
|
||||
return E_POINTER;
|
||||
}
|
||||
auto* bridge = new (std::nothrow) BxPresentQueue(queue_proxy);
|
||||
if (!bridge) {
|
||||
*ppv = nullptr;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
*ppv = static_cast<IBxPresentQueue*>(bridge);
|
||||
return S_OK;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
#ifndef BETTERXEN_D3D12_XS_PRESENTX_H
|
||||
#define BETTERXEN_D3D12_XS_PRESENTX_H
|
||||
|
||||
/*
|
||||
* Track C (M2-C2, #465): the PresentX presentation bridge over host DXGI.
|
||||
*
|
||||
* THESE INTERFACES ARE DEFINED BY BETTERXEN. They are not the console's PresentX, whose
|
||||
* signature and structures are not defined in abi/, and no binary compatibility with any Xbox
|
||||
* interface is claimed. A guest that calls a console-only command queue slot still lands on the
|
||||
* proxy's logged stub.
|
||||
*
|
||||
* Use: QueryInterface the command queue returned by a D3D12XboxCreateDevice device for
|
||||
* IID_IBxPresentQueue, then create a swapchain on a Win32 window. No new DLL export is involved.
|
||||
*
|
||||
* This is a subset of the public DXGI flip model, not all of it: the caller records its own
|
||||
* resource transitions and every back buffer must be in D3D12_RESOURCE_STATE_PRESENT when it is
|
||||
* presented. D3D12 offers no way to query a resource's state, so the bridge cannot check this.
|
||||
* ResizeBuffers and fullscreen are not implemented.
|
||||
*/
|
||||
#ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <d3d12.h>
|
||||
#include <dxgi1_4.h>
|
||||
|
||||
/* {34127279-2D93-4642-88A6-97B834217B8A} */
|
||||
inline const GUID IID_IBxPresentQueue = {0x34127279, 0x2d93, 0x4642, {0x88, 0xa6, 0x97, 0xb8, 0x34, 0x21, 0x7b, 0x8a}};
|
||||
/* {DEC9F73E-DE84-4F87-9167-26203B3A1152} */
|
||||
inline const GUID IID_IBxPresentSwapChain = {0xdec9f73e, 0xde84, 0x4f87, {0x91, 0x67, 0x26, 0x20, 0x3b, 0x3a, 0x11, 0x52}};
|
||||
|
||||
/* Longest single GPU wait Present() performs, and the destructor's wait for the GPU. */
|
||||
inline constexpr DWORD BX_PRESENT_WAIT_MS = 5000;
|
||||
/*
|
||||
* Present() result: the frame WAS handed to the host, but the next back buffer is still busy.
|
||||
* Do not present that frame again. Call WaitForIdle until it returns S_OK before reusing a buffer.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_NEXT_BUFFER_BUSY = static_cast<HRESULT>(0x80040201u);
|
||||
/*
|
||||
* Present() result: the frame was NOT handed to the host, because another Present or WaitForIdle
|
||||
* on this swapchain is in progress. Present never waits for that call. Try again after it returns.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_BUSY = static_cast<HRESULT>(0x80040202u);
|
||||
/*
|
||||
* Present() result: the frame WAS handed to the host, but the following fence signal failed on
|
||||
* a live device, so its completion is unknown. Do not present that frame again. Call WaitForIdle
|
||||
* until it returns S_OK before recording to any back buffer or presenting again. Device removal
|
||||
* returns the removal HRESULT unchanged instead.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_COMPLETION_UNCONFIRMED = static_cast<HRESULT>(0x80040203u);
|
||||
/*
|
||||
* Present() result: the frame was NOT handed to the host, because an earlier Present returned
|
||||
* BX_PRESENT_E_COMPLETION_UNCONFIRMED or BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED and no WaitForIdle
|
||||
* has succeeded since.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_NEEDS_IDLE = static_cast<HRESULT>(0x80040204u);
|
||||
/*
|
||||
* Present() result: the frame WAS handed to the host and signaled, but waiting on the next back
|
||||
* buffer failed on a live device (for example SetEventOnCompletion or WaitForSingleObject). Do not
|
||||
* present that frame again. Call WaitForIdle until it returns S_OK before reusing any back buffer
|
||||
* or presenting again. Device removal returns the removal HRESULT unchanged instead.
|
||||
*/
|
||||
inline constexpr HRESULT BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED = static_cast<HRESULT>(0x80040205u);
|
||||
|
||||
struct BxPresentDesc {
|
||||
UINT width; /* 1..16384; 0 ("use the window size") is not accepted */
|
||||
UINT height; /* 1..16384 */
|
||||
DXGI_FORMAT format; /* R8G8B8A8_UNORM, B8G8R8A8_UNORM, R10G10B10A2_UNORM or R16G16B16A16_FLOAT */
|
||||
UINT buffer_count; /* 2..DXGI_MAX_SWAP_CHAIN_BUFFERS */
|
||||
};
|
||||
|
||||
/*
|
||||
* One swapchain. Holds a reference on the command queue it was created from.
|
||||
* The final Release waits (bounded) for the queue to go idle. If that fails and the device
|
||||
* reports it has not been removed, it logs and deliberately leaks what pending GPU work may
|
||||
* still touch (swapchain, fence, event, host queue) and releases its queue proxy reference.
|
||||
* After device removal everything is released. Time spent inside the host's own Release is not bounded: on the
|
||||
* wined3d/vkd3d path (not D3DMetal) an intermittent stall in it was observed.
|
||||
*/
|
||||
struct IBxPresentSwapChain : public IUnknown {
|
||||
/* Same rules as IDXGISwapChain::GetBuffer. The caller owns the returned reference. */
|
||||
virtual HRESULT STDMETHODCALLTYPE GetBuffer(UINT index, REFIID riid, void** ppv) = 0;
|
||||
virtual UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() = 0;
|
||||
/*
|
||||
* Waits (bounded) until the current back buffer is idle, calls IDXGISwapChain::Present,
|
||||
* signals a fence on the queue, then waits until the next back buffer is idle. It never waits
|
||||
* for another thread's call on this swapchain. Results:
|
||||
* - a DXGI success code, including DXGI_STATUS_OCCLUDED: presented, next buffer idle;
|
||||
* - HRESULT_FROM_WIN32(ERROR_TIMEOUT): NOT presented (the current buffer is still busy);
|
||||
* - BX_PRESENT_E_NEXT_BUFFER_BUSY: presented, see its definition;
|
||||
* - BX_PRESENT_E_BUSY: NOT presented, another call holds the swapchain;
|
||||
* - BX_PRESENT_E_COMPLETION_UNCONFIRMED: presented, the fence signal failed on a live device;
|
||||
* - BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED: presented, waiting on the next back buffer failed
|
||||
* on a live device;
|
||||
* - BX_PRESENT_E_NEEDS_IDLE: NOT presented, WaitForIdle must succeed first;
|
||||
* - another failure: the host's Present failure, a pre-Present fence wait or device failure
|
||||
* (nothing was presented), or a device-removal HRESULT (such as DXGI_ERROR_DEVICE_REMOVED
|
||||
* or DXGI_ERROR_DEVICE_RESET) observed after host Present, returned unchanged. If the
|
||||
* device still reports itself as live, WaitForIdle must succeed before the next Present.
|
||||
* The bounds cover BetterXen's own waits, not time spent inside the host's Present.
|
||||
*
|
||||
* The bridge itself returns DXGI_ERROR_INVALID_CALL, without calling the host, for a
|
||||
* sync_interval above 4, for any flag (none is supported, including DXGI_PRESENT_TEST),
|
||||
* once the window is destroyed, and when Present or WaitForIdle is re-entered on a thread
|
||||
* already inside one of them. D3DMetal 3.0 was observed to answer S_OK to the first three.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE Present(UINT sync_interval, UINT flags) = 0;
|
||||
/*
|
||||
* Waits until everything submitted to the queue before this call has finished. S_OK also ends
|
||||
* the recovery state left by a post-Present synchronization failure on a live device.
|
||||
* Only positive, finite timeouts are supported. Zero and INFINITE return E_INVALIDARG
|
||||
* without signaling. A timeout returns HRESULT_FROM_WIN32(ERROR_TIMEOUT).
|
||||
* Lock acquisition, fence signaling, and fence waiting share timeout_ms; if lock acquisition
|
||||
* uses the whole budget, WaitForIdle times out without signaling. Time spent inside host calls
|
||||
* reduces the remaining wait, but the bridge cannot interrupt those calls.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE WaitForIdle(DWORD timeout_ms) = 0;
|
||||
/*
|
||||
* The host DXGI swapchain, for diagnostics and tests. The caller owns the reference and must
|
||||
* not call Present or ResizeBuffers on it: the bridge's buffer tracking would not follow.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE GetHostSwapChain(REFIID riid, void** ppv) = 0;
|
||||
};
|
||||
|
||||
/* Tear-off on the command queue proxy; QueryInterface for any other IID returns the queue's answer. */
|
||||
struct IBxPresentQueue : public IUnknown {
|
||||
/*
|
||||
* The queue must be a DIRECT queue and `window` an existing window. Argument errors return
|
||||
* E_POINTER or DXGI_ERROR_INVALID_CALL; host failures are returned unchanged and logged.
|
||||
*/
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateSwapChain(HWND window, const BxPresentDesc* desc, IBxPresentSwapChain** out) = 0;
|
||||
};
|
||||
|
||||
/* Internal to d3d12_xs.dll: the command queue proxy answers IID_IBxPresentQueue with this. */
|
||||
HRESULT bx_present_query_queue(ID3D12CommandQueue* queue_proxy, void** ppv);
|
||||
|
||||
#endif /* BETTERXEN_D3D12_XS_PRESENTX_H */
|
||||
@@ -0,0 +1,350 @@
|
||||
/*
|
||||
* ID3D12CommandQueue::PresentX as titles call it on the Xbox-layout queue (authorized GDK
|
||||
* documentation: PresentX(PlaneCount, const D3D12XBOX_PRESENT_PLANE_PARAMETERS*,
|
||||
* const D3D12XBOX_PRESENT_PARAMETERS*)). This is separate from presentx.h, BetterXen's own
|
||||
* swapchain bridge for synthetic fixtures.
|
||||
*
|
||||
* On the first present, a host DXGI flip-model swapchain is created on the title's top-level
|
||||
* window (the visible window owned by this process), sized to plane 0's first resource. Each
|
||||
* present copies that resource into the current back buffer when formats and sizes match, and
|
||||
* otherwise leaves the back buffer unchanged (logged once), then presents with sync interval 0: frame pacing
|
||||
* is the title's own, through the frame events (frame_pacing.cpp). Plane 1, source and
|
||||
* destination rectangles, colour spaces and scaling are not applied (logged once).
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <dxgi1_4.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <mutex>
|
||||
#include <cstdlib>
|
||||
#include <cwchar>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
struct PlaneParameters { // D3D12XBOX_PRESENT_PLANE_PARAMETERS
|
||||
UINT64 Token;
|
||||
UINT ResourceCount;
|
||||
ID3D12Resource** ppResources;
|
||||
D3D12_RECT* pSrcViewRects;
|
||||
void* pDestPlacementBase;
|
||||
UINT ColorSpace;
|
||||
UINT ScaleFilter;
|
||||
UINT ExtendedDescCount;
|
||||
void* pExtendedDescs;
|
||||
UINT Flags;
|
||||
};
|
||||
static_assert(sizeof(PlaneParameters) == 72, "D3D12XBOX_PRESENT_PLANE_PARAMETERS layout");
|
||||
|
||||
constexpr UINT kBuffers = 3;
|
||||
|
||||
struct Presenter {
|
||||
std::mutex lock;
|
||||
bool failed = false;
|
||||
ID3D12CommandQueue* queue = nullptr; // host queue the swapchain was made for
|
||||
IDXGISwapChain3* swapchain = nullptr;
|
||||
ID3D12CommandAllocator* allocators[kBuffers] = {};
|
||||
ID3D12GraphicsCommandList* list = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
UINT64 fence_values[kBuffers] = {};
|
||||
UINT64 next_value = 1;
|
||||
HANDLE event = nullptr;
|
||||
DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
|
||||
UINT width = 0, height = 0;
|
||||
UINT64 presents = 0;
|
||||
};
|
||||
Presenter g;
|
||||
|
||||
struct FindWindow {
|
||||
DWORD pid;
|
||||
HWND found;
|
||||
};
|
||||
BOOL CALLBACK find_window(HWND window, LPARAM param) {
|
||||
auto* f = reinterpret_cast<FindWindow*>(param);
|
||||
DWORD pid = 0;
|
||||
GetWindowThreadProcessId(window, &pid);
|
||||
if (pid == f->pid && IsWindowVisible(window) && !GetWindow(window, GW_OWNER)) {
|
||||
f->found = window;
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void log_hr(const char* what, HRESULT hr) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "%s hr=0x%08lx", what, static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail);
|
||||
}
|
||||
|
||||
DXGI_FORMAT swapchain_format(DXGI_FORMAT f) {
|
||||
switch (f) {
|
||||
case DXGI_FORMAT_R8G8B8A8_UNORM:
|
||||
case DXGI_FORMAT_B8G8R8A8_UNORM:
|
||||
case DXGI_FORMAT_R10G10B10A2_UNORM:
|
||||
case DXGI_FORMAT_R16G16B16A16_FLOAT: return f;
|
||||
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
default: return DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
}
|
||||
}
|
||||
|
||||
bool create_locked(ID3D12CommandQueue* queue, const D3D12_RESOURCE_DESC& source) {
|
||||
FindWindow f{GetCurrentProcessId(), nullptr};
|
||||
EnumWindows(find_window, reinterpret_cast<LPARAM>(&f));
|
||||
if (!f.found) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", "no visible window owned by the title; frames not shown");
|
||||
return false;
|
||||
}
|
||||
using CreateFactory2 = HRESULT(WINAPI*)(UINT, REFIID, void**);
|
||||
HMODULE dxgi = LoadLibraryW(L"dxgi.dll");
|
||||
auto create_factory = dxgi ? reinterpret_cast<CreateFactory2>(reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory2"))) : nullptr;
|
||||
IDXGIFactory2* factory = nullptr;
|
||||
HRESULT hr = create_factory ? create_factory(0, __uuidof(IDXGIFactory2), reinterpret_cast<void**>(&factory)) : E_NOINTERFACE;
|
||||
if (FAILED(hr)) {
|
||||
log_hr("CreateDXGIFactory2", hr);
|
||||
return false;
|
||||
}
|
||||
g.width = static_cast<UINT>(source.Width);
|
||||
g.height = source.Height;
|
||||
g.format = swapchain_format(source.Format);
|
||||
DXGI_SWAP_CHAIN_DESC1 desc{};
|
||||
desc.Width = g.width;
|
||||
desc.Height = g.height;
|
||||
desc.Format = g.format;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
|
||||
desc.BufferCount = kBuffers;
|
||||
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
|
||||
IDXGISwapChain1* chain1 = nullptr;
|
||||
hr = factory->CreateSwapChainForHwnd(queue, f.found, &desc, nullptr, nullptr, &chain1);
|
||||
factory->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr("CreateSwapChainForHwnd", hr);
|
||||
return false;
|
||||
}
|
||||
hr = chain1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void**>(&g.swapchain));
|
||||
chain1->Release();
|
||||
if (FAILED(hr)) {
|
||||
log_hr("IDXGISwapChain3", hr);
|
||||
return false;
|
||||
}
|
||||
ID3D12Device* device = nullptr;
|
||||
hr = queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
for (UINT i = 0; SUCCEEDED(hr) && i < kBuffers; ++i) {
|
||||
hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
|
||||
reinterpret_cast<void**>(&g.allocators[i]));
|
||||
}
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g.allocators[0], nullptr,
|
||||
__uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(&g.list));
|
||||
}
|
||||
if (SUCCEEDED(hr)) hr = g.list->Close();
|
||||
if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&g.fence));
|
||||
if (device) device->Release();
|
||||
g.event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (FAILED(hr) || !g.event) {
|
||||
log_hr("present resources", FAILED(hr) ? hr : E_OUTOFMEMORY);
|
||||
return false;
|
||||
}
|
||||
g.queue = queue;
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "swapchain %ux%u format=%d on the title window (title buffer format=%d)", g.width,
|
||||
g.height, static_cast<int>(g.format), static_cast<int>(source.Format));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_xbox", detail);
|
||||
return true;
|
||||
}
|
||||
|
||||
void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* r, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) {
|
||||
D3D12_RESOURCE_BARRIER b{};
|
||||
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
b.Transition.pResource = r;
|
||||
b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
b.Transition.StateBefore = before;
|
||||
b.Transition.StateAfter = after;
|
||||
list->ResourceBarrier(1, &b);
|
||||
}
|
||||
|
||||
|
||||
// Diagnostics (off unless BX_PRESENT_DUMP=<folder>): every BX_PRESENT_DUMP_EVERY-th present (default
|
||||
// 64, at most 32 files) the presented buffer is copied to a readback buffer and written as a BMP,
|
||||
// downscaled 4x, for looking at frames without screen-recording access.
|
||||
const wchar_t* dump_folder() {
|
||||
static wchar_t folder[MAX_PATH] = L"";
|
||||
static const bool on = GetEnvironmentVariableW(L"BX_PRESENT_DUMP", folder, MAX_PATH) > 0;
|
||||
return on ? folder : nullptr;
|
||||
}
|
||||
UINT64 dump_every() {
|
||||
static const UINT64 every = [] {
|
||||
char v[16];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_PRESENT_DUMP_EVERY", v, sizeof(v));
|
||||
const unsigned long k = (n > 0 && n < sizeof(v)) ? std::strtoul(v, nullptr, 10) : 64;
|
||||
return static_cast<UINT64>(k ? k : 64);
|
||||
}();
|
||||
return every;
|
||||
}
|
||||
|
||||
void dump_frame(ID3D12CommandQueue* queue, ID3D12Resource* source, const D3D12_RESOURCE_DESC& desc, UINT64 frame) {
|
||||
static int written = 0;
|
||||
if (written >= 32 || desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return;
|
||||
const DXGI_FORMAT f = desc.Format;
|
||||
const bool bgra = f == DXGI_FORMAT_B8G8R8A8_UNORM || f == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
|
||||
const bool rgba = f == DXGI_FORMAT_R8G8B8A8_UNORM || f == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
|
||||
if (!bgra && !rgba) return;
|
||||
ID3D12Device* device = nullptr;
|
||||
if (FAILED(queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device)))) return;
|
||||
D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{};
|
||||
UINT rows = 0;
|
||||
UINT64 row_bytes = 0, total = 0;
|
||||
device->GetCopyableFootprints(&desc, 0, 1, 0, &fp, &rows, &row_bytes, &total);
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_READBACK;
|
||||
D3D12_RESOURCE_DESC buf{};
|
||||
buf.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buf.Width = total;
|
||||
buf.Height = 1;
|
||||
buf.DepthOrArraySize = 1;
|
||||
buf.MipLevels = 1;
|
||||
buf.SampleDesc.Count = 1;
|
||||
buf.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
ID3D12Resource* readback = nullptr;
|
||||
ID3D12CommandAllocator* alloc = nullptr;
|
||||
ID3D12GraphicsCommandList* list = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&readback));
|
||||
if (SUCCEEDED(hr)) hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&alloc));
|
||||
if (SUCCEEDED(hr)) hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc, nullptr, __uuidof(ID3D12GraphicsCommandList), reinterpret_cast<void**>(&list));
|
||||
if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
|
||||
if (SUCCEEDED(hr)) {
|
||||
barrier(list, source, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{readback, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
|
||||
dst.PlacedFootprint = fp;
|
||||
D3D12_TEXTURE_COPY_LOCATION src{source, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
|
||||
barrier(list, source, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON);
|
||||
list->Close();
|
||||
ID3D12CommandList* lists[] = {list};
|
||||
queue->ExecuteCommandLists(1, lists);
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
queue->Signal(fence, 1);
|
||||
fence->SetEventOnCompletion(1, done);
|
||||
WaitForSingleObject(done, 5000);
|
||||
CloseHandle(done);
|
||||
const BYTE* data = nullptr;
|
||||
if (SUCCEEDED(readback->Map(0, nullptr, reinterpret_cast<void**>(const_cast<BYTE**>(&data))))) {
|
||||
const UINT w = static_cast<UINT>(desc.Width) / 4, h = desc.Height / 4;
|
||||
const UINT stride = (w * 3 + 3) & ~3u;
|
||||
std::vector<BYTE> bmp(54 + static_cast<size_t>(stride) * h, 0);
|
||||
auto put32 = [&](size_t at, uint32_t v) { std::memcpy(&bmp[at], &v, 4); };
|
||||
bmp[0] = 'B'; bmp[1] = 'M';
|
||||
put32(2, static_cast<uint32_t>(bmp.size())); put32(10, 54); put32(14, 40);
|
||||
put32(18, w); put32(22, h); bmp[26] = 1; bmp[28] = 24; put32(34, static_cast<uint32_t>(stride * h));
|
||||
uint64_t sum = 0;
|
||||
for (UINT y = 0; y < h; ++y) {
|
||||
const BYTE* row = data + fp.Offset + static_cast<UINT64>(y * 4) * fp.Footprint.RowPitch;
|
||||
BYTE* out = &bmp[54 + static_cast<size_t>(h - 1 - y) * stride];
|
||||
for (UINT x = 0; x < w; ++x) {
|
||||
const BYTE* px = row + static_cast<size_t>(x) * 16;
|
||||
const BYTE r = bgra ? px[2] : px[0], g = px[1], b = bgra ? px[0] : px[2];
|
||||
out[x * 3 + 0] = b; out[x * 3 + 1] = g; out[x * 3 + 2] = r;
|
||||
sum += r + g + b;
|
||||
}
|
||||
}
|
||||
readback->Unmap(0, nullptr);
|
||||
wchar_t path[MAX_PATH];
|
||||
std::swprintf(path, MAX_PATH, L"%ls\\frame_%06llu.bmp", dump_folder(), static_cast<unsigned long long>(frame));
|
||||
HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (file != INVALID_HANDLE_VALUE) {
|
||||
DWORD wrote = 0;
|
||||
WriteFile(file, bmp.data(), static_cast<DWORD>(bmp.size()), &wrote, nullptr);
|
||||
CloseHandle(file);
|
||||
++written;
|
||||
}
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "frame %llu dumped %ux%u, mean channel value %.1f",
|
||||
static_cast<unsigned long long>(frame), w, h, w && h ? double(sum) / (double(w) * h * 3) : 0.0);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "present_dump", detail);
|
||||
}
|
||||
}
|
||||
if (fence) fence->Release();
|
||||
if (list) list->Release();
|
||||
if (alloc) alloc->Release();
|
||||
if (readback) readback->Release();
|
||||
device->Release();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT plane_count, const void* planes_raw,
|
||||
const void* parameters) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "PresentX");
|
||||
(void)parameters;
|
||||
const auto* planes = static_cast<const PlaneParameters*>(planes_raw);
|
||||
if (plane_count == 0 || !planes || planes[0].ResourceCount == 0 || !planes[0].ppResources) return S_OK;
|
||||
ID3D12Resource* source = bx_xbox_unwrap_as(planes[0].ppResources[0]);
|
||||
if (!source) return E_INVALIDARG;
|
||||
auto* queue = bx_xbox_host<ID3D12CommandQueue>(self);
|
||||
std::lock_guard<std::mutex> guard(g.lock);
|
||||
if (g.failed) return S_OK;
|
||||
const D3D12_RESOURCE_DESC desc = source->GetDesc();
|
||||
if (!g.swapchain && !create_locked(queue, desc)) {
|
||||
g.failed = true;
|
||||
return S_OK; // the title keeps running; frames are not shown (logged)
|
||||
}
|
||||
static std::atomic<bool> logged_extra{false};
|
||||
if ((plane_count > 1 || planes[0].pSrcViewRects || planes[0].pDestPlacementBase) && !logged_extra.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_xbox",
|
||||
"plane 1, view rectangles, placement and scaling are not applied; plane 0 is copied as is");
|
||||
}
|
||||
const UINT index = g.swapchain->GetCurrentBackBufferIndex();
|
||||
if (g.fence->GetCompletedValue() < g.fence_values[index]) {
|
||||
g.fence->SetEventOnCompletion(g.fence_values[index], g.event);
|
||||
WaitForSingleObject(g.event, 2000);
|
||||
}
|
||||
ID3D12Resource* back = nullptr;
|
||||
HRESULT hr = g.swapchain->GetBuffer(index, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&back));
|
||||
if (FAILED(hr)) {
|
||||
log_hr("GetBuffer", hr);
|
||||
return S_OK;
|
||||
}
|
||||
g.allocators[index]->Reset();
|
||||
g.list->Reset(g.allocators[index], nullptr);
|
||||
const bool copyable = desc.Width == g.width && desc.Height == g.height && swapchain_format(desc.Format) == g.format &&
|
||||
desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1;
|
||||
if (copyable) {
|
||||
// The title's buffer is assumed to be presentable (PRESENT, i.e. COMMON) when PresentX is called.
|
||||
barrier(g.list, source, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
barrier(g.list, back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{back, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
D3D12_TEXTURE_COPY_LOCATION src{source, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
g.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
|
||||
barrier(g.list, back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT);
|
||||
barrier(g.list, source, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON);
|
||||
} else {
|
||||
static std::atomic<bool> logged{false};
|
||||
if (!logged.exchange(true)) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "title buffer %llux%u format=%d does not match the swapchain; not copied, the window shows the previous contents",
|
||||
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<int>(desc.Format));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail);
|
||||
}
|
||||
}
|
||||
g.list->Close();
|
||||
ID3D12CommandList* lists[] = {g.list};
|
||||
g.queue->ExecuteCommandLists(1, lists);
|
||||
back->Release();
|
||||
hr = g.swapchain->Present(0, 0);
|
||||
g.fence_values[index] = g.next_value++;
|
||||
g.queue->Signal(g.fence, g.fence_values[index]);
|
||||
const UINT64 n = ++g.presents;
|
||||
if (dump_folder() && copyable && n % dump_every() == 0) dump_frame(g.queue, source, desc, n);
|
||||
if ((n & (n - 1)) == 0) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "frames presented=%llu last hr=0x%08lx", static_cast<unsigned long long>(n),
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_frames", detail);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
@@ -4,8 +4,11 @@
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#include "presentx.h"
|
||||
|
||||
#include "shader_gate.h"
|
||||
|
||||
/* {6B1D5C0E-2F4A-4E0B-9A57-3C0E5D7B1A42}: private to this DLL, never handed to a host object. */
|
||||
@@ -510,10 +513,13 @@ const StreamSubobject* find_subobject(uint32_t type) {
|
||||
}
|
||||
|
||||
/* 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. An unknown tag,
|
||||
* 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) {
|
||||
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);
|
||||
@@ -540,6 +546,7 @@ HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<ui
|
||||
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));
|
||||
@@ -572,7 +579,7 @@ HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELIN
|
||||
std::vector<uint8_t> stream;
|
||||
std::vector<size_t> offsets;
|
||||
std::vector<const char*> names;
|
||||
const HRESULT copied = copy_stream(*desc, stream, offsets, 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",
|
||||
@@ -686,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";
|
||||
|
||||
@@ -296,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
|
||||
@@ -1,8 +1,12 @@
|
||||
#include <windows.h>
|
||||
#include <tlhelp32.h>
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstdarg>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cwchar>
|
||||
#include <initializer_list>
|
||||
#include <intrin.h>
|
||||
|
||||
#include "bx_config.h"
|
||||
@@ -18,6 +22,12 @@ LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = nullptr;
|
||||
std::atomic_flag g_crash_logged{};
|
||||
std::atomic<bool> g_crash_in_flight{false};
|
||||
std::atomic<uint64_t> g_clwb_traps{0};
|
||||
std::atomic<uint32_t> g_breakpoint_records{0};
|
||||
|
||||
// Breakpoint and assertion-failure records per process, so a guest that uses int3 on purpose
|
||||
// cannot flood the log.
|
||||
constexpr uint32_t kMaxBreakpointRecords = 16;
|
||||
constexpr DWORD kStatusAssertionFailure = 0xC0000420;
|
||||
|
||||
// Other AMD-only instructions Rosetta 2 (and Intel CPUs) raise #UD on. Their
|
||||
// counts reach the JSONL trace only: the frozen .def has no export for them.
|
||||
@@ -354,11 +364,874 @@ LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) {
|
||||
return disposition;
|
||||
}
|
||||
|
||||
// A guest with its own crash reporter replaces the top-level filter installed at attach, so
|
||||
// log_unhandled_exception never sees its assertions. The vectored handler runs before the
|
||||
// guest's top-level filter and before any vectored handler the guest registers last; a handler
|
||||
// the guest registers first can resume the exception before this one sees it. It records
|
||||
// breakpoints and assertion failures with their module offset. They are first-chance, so the
|
||||
// guest may still handle them; handling is left unchanged.
|
||||
void log_breakpoint(const EXCEPTION_RECORD& record) {
|
||||
// Past the cap the counter is not advanced again, so it cannot wrap around to 1.
|
||||
if (g_breakpoint_records.load(std::memory_order_relaxed) >= kMaxBreakpointRecords) {
|
||||
return;
|
||||
}
|
||||
const uint32_t index = g_breakpoint_records.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
if (index > kMaxBreakpointRecords) {
|
||||
return;
|
||||
}
|
||||
// The calls below can change the thread's last-error value; a resumed first-chance exception
|
||||
// must leave the guest's error state as it was.
|
||||
const DWORD last_error = GetLastError();
|
||||
const uintptr_t address = reinterpret_cast<uintptr_t>(record.ExceptionAddress);
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t module_base = 0;
|
||||
char module[MAX_PATH] = "?";
|
||||
if (VirtualQuery(record.ExceptionAddress, ®ion, sizeof(region)) &&
|
||||
region.Type == MEM_IMAGE) {
|
||||
module_base = reinterpret_cast<uintptr_t>(region.AllocationBase);
|
||||
// Wide API plus an explicit UTF-8 conversion: the ANSI form returns the name in the
|
||||
// active code page, which would make a non-ASCII module name invalid UTF-8 in the JSON.
|
||||
wchar_t path[MAX_PATH];
|
||||
const DWORD length =
|
||||
GetModuleFileNameW(reinterpret_cast<HMODULE>(module_base), path, MAX_PATH);
|
||||
if (length > 0 && length < MAX_PATH) {
|
||||
const wchar_t* slash = std::wcsrchr(path, L'\\');
|
||||
const wchar_t* name = slash ? slash + 1 : path;
|
||||
if (WideCharToMultiByte(CP_UTF8, 0, name, -1, module, sizeof(module), nullptr, nullptr) == 0) {
|
||||
std::snprintf(module, sizeof(module), "?");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
char line[1024];
|
||||
const int length = std::snprintf(
|
||||
line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\","
|
||||
"\"event\":\"breakpoint_exception\",\"exception_code\":\"0x%08lx\","
|
||||
"\"module\":\"%s\",\"module_base\":\"0x%016llx\",\"rva\":\"0x%016llx\","
|
||||
"\"address\":\"0x%016llx\",\"record\":%u,\"limit\":%u}\n",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
record.ExceptionCode, module, static_cast<unsigned long long>(module_base),
|
||||
static_cast<unsigned long long>(module_base ? address - module_base : 0),
|
||||
static_cast<unsigned long long>(address), index, kMaxBreakpointRecords);
|
||||
if (length > 0 && length < static_cast<int>(sizeof(line))) {
|
||||
write_log_line(line, static_cast<size_t>(length));
|
||||
}
|
||||
SetLastError(last_error);
|
||||
}
|
||||
|
||||
// Diagnostics (off unless BX_VEH_AV_CONTEXT is set): the first access violations in an image
|
||||
// are logged with the general registers and, for each address in the variable, 64 bytes of
|
||||
// memory. An entry "*ADDR+OFF" first reads the pointer at ADDR, then dumps at pointer + OFF.
|
||||
// Reads are guarded by VirtualQuery; handling is left unchanged (first chance, search continues).
|
||||
bool readable_bytes(uintptr_t address, size_t size) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(address), ®ion, sizeof(region)) || region.State != MEM_COMMIT ||
|
||||
(region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
|
||||
return false;
|
||||
}
|
||||
return address + size <= reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
|
||||
// A JSONL line built with bounded appends: an append that does not fit is dropped and marks the
|
||||
// line truncated, so the length never passes the buffer. Four bytes stay reserved for the closing
|
||||
// "\"}\n". Text from the environment or module names goes through add_escaped.
|
||||
class LineBuf {
|
||||
public:
|
||||
LineBuf(char* p, size_t cap) : p_(p), cap_(cap - 4) { p_[0] = '\0'; }
|
||||
void add(const char* fmt, ...) {
|
||||
if (truncated_) return;
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
const int n = std::vsnprintf(p_ + len_, cap_ - len_, fmt, ap);
|
||||
va_end(ap);
|
||||
if (n < 0 || static_cast<size_t>(n) >= cap_ - len_) {
|
||||
p_[len_] = '\0'; // drop the partial append
|
||||
truncated_ = true;
|
||||
return;
|
||||
}
|
||||
len_ += static_cast<size_t>(n);
|
||||
}
|
||||
// JSON string escaping for " \ and control characters; other bytes (UTF-8) pass through.
|
||||
void add_escaped(const char* text, size_t max) {
|
||||
for (size_t i = 0; text[i] && i < max && !truncated_; ++i) {
|
||||
const unsigned char ch = static_cast<unsigned char>(text[i]);
|
||||
if (ch == '"' || ch == '\\') add("\\%c", ch);
|
||||
else if (ch < 0x20) add("\\u%04x", ch);
|
||||
else add("%c", ch);
|
||||
}
|
||||
}
|
||||
bool room(size_t n) const { return !truncated_ && cap_ - len_ > n; }
|
||||
// Closes the JSON string and object and writes the line.
|
||||
void finish() {
|
||||
std::memcpy(p_ + len_, "\"}\n", 4);
|
||||
write_log_line(p_, len_ + 3);
|
||||
}
|
||||
|
||||
private:
|
||||
char* p_;
|
||||
size_t cap_;
|
||||
size_t len_ = 0;
|
||||
bool truncated_ = false;
|
||||
};
|
||||
|
||||
// A module's file name (without the directory) in UTF-8, or "?" when it cannot be read.
|
||||
void module_name_utf8(uintptr_t base, char* out, size_t size) {
|
||||
wchar_t path[MAX_PATH];
|
||||
const DWORD n = base ? GetModuleFileNameW(reinterpret_cast<HMODULE>(base), path, MAX_PATH) : 0;
|
||||
if (n == 0 || n >= MAX_PATH) {
|
||||
std::snprintf(out, size, "?");
|
||||
return;
|
||||
}
|
||||
const wchar_t* slash = std::wcsrchr(path, L'\\');
|
||||
const wchar_t* name = slash ? slash + 1 : path;
|
||||
if (WideCharToMultiByte(CP_UTF8, 0, name, -1, out, static_cast<int>(size), nullptr, nullptr) == 0) {
|
||||
std::snprintf(out, size, "?");
|
||||
}
|
||||
}
|
||||
|
||||
// BX_VEH_AV_CONTEXT and BX_VEH_AV_ALL, read once when runtime_veh attaches. With the context
|
||||
// switch unset the access-violation path does nothing at all.
|
||||
char g_av_spec[512];
|
||||
bool g_av_context_on = false;
|
||||
bool g_av_all = false;
|
||||
|
||||
void read_av_switches() {
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_AV_CONTEXT", g_av_spec, sizeof(g_av_spec));
|
||||
g_av_context_on = n > 0 && n < sizeof(g_av_spec);
|
||||
char v[4];
|
||||
const DWORD k = GetEnvironmentVariableA("BX_VEH_AV_ALL", v, sizeof(v));
|
||||
g_av_all = k > 0 && k < sizeof(v) && v[0] == '1';
|
||||
}
|
||||
|
||||
void log_av_context(const EXCEPTION_POINTERS& ep) {
|
||||
static std::atomic<uint32_t> logged{0};
|
||||
if (!g_av_context_on || logged.fetch_add(1) >= 16) return;
|
||||
const CONTEXT& c = *ep.ContextRecord;
|
||||
char line[1600];
|
||||
LineBuf out(line, sizeof(line));
|
||||
out.add("{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"av_context\","
|
||||
"\"detail\":\"rip=%llx fault=%llx rax=%llx rbx=%llx rcx=%llx rdx=%llx rsi=%llx rdi=%llx rbp=%llx "
|
||||
"rsp=%llx r8=%llx r9=%llx r10=%llx r11=%llx r12=%llx r13=%llx r14=%llx r15=%llx",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
(unsigned long long)c.Rip,
|
||||
(unsigned long long)(ep.ExceptionRecord->NumberParameters >= 2 ? ep.ExceptionRecord->ExceptionInformation[1] : 0),
|
||||
(unsigned long long)c.Rax, (unsigned long long)c.Rbx, (unsigned long long)c.Rcx,
|
||||
(unsigned long long)c.Rdx, (unsigned long long)c.Rsi, (unsigned long long)c.Rdi,
|
||||
(unsigned long long)c.Rbp, (unsigned long long)c.Rsp, (unsigned long long)c.R8,
|
||||
(unsigned long long)c.R9, (unsigned long long)c.R10, (unsigned long long)c.R11,
|
||||
(unsigned long long)c.R12, (unsigned long long)c.R13, (unsigned long long)c.R14,
|
||||
(unsigned long long)c.R15);
|
||||
// The comma-separated spec, scanned without shared state (several threads can fault at once).
|
||||
for (const char* cursor = g_av_spec; *cursor && out.room(220);) {
|
||||
const char* comma = std::strchr(cursor, ',');
|
||||
const size_t length = comma ? static_cast<size_t>(comma - cursor) : std::strlen(cursor);
|
||||
char item[64];
|
||||
const size_t take = length < sizeof(item) - 1 ? length : sizeof(item) - 1;
|
||||
std::memcpy(item, cursor, take);
|
||||
item[take] = '\0';
|
||||
cursor += length + (comma ? 1 : 0);
|
||||
// "*A+O": dump at [A]+O. "**A+O1+O2": dump at [[A]+O1]+O2.
|
||||
const int derefs = item[0] == '*' ? (item[1] == '*' ? 2 : 1) : 0;
|
||||
char* rest = nullptr;
|
||||
uintptr_t address = static_cast<uintptr_t>(std::strtoull(item + derefs, &rest, 16));
|
||||
uintptr_t offsets[2] = {0, 0};
|
||||
for (int k = 0; k < 2 && rest && *rest == '+'; ++k) offsets[k] = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
|
||||
bool ok = true;
|
||||
for (int k = 0; k < derefs && ok; ++k) {
|
||||
ok = readable_bytes(address, 8);
|
||||
if (ok) address = *reinterpret_cast<const uintptr_t*>(address) + offsets[k];
|
||||
}
|
||||
out.add(" | ");
|
||||
out.add_escaped(item, sizeof(item));
|
||||
if (!ok) {
|
||||
out.add(" unresolved");
|
||||
continue;
|
||||
}
|
||||
if (derefs == 0) address += offsets[0];
|
||||
out.add(" @%llx:", (unsigned long long)address);
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
if (VirtualQuery(reinterpret_cast<void*>(address), &mbi, sizeof(mbi))) {
|
||||
out.add(" [type=%lx prot=%lx alloc=%llx region=%llx+%llx]", static_cast<unsigned long>(mbi.Type),
|
||||
static_cast<unsigned long>(mbi.Protect), (unsigned long long)reinterpret_cast<uintptr_t>(mbi.AllocationBase),
|
||||
(unsigned long long)reinterpret_cast<uintptr_t>(mbi.BaseAddress), (unsigned long long)mbi.RegionSize);
|
||||
}
|
||||
if (!readable_bytes(address, 64)) {
|
||||
out.add(" unreadable");
|
||||
continue;
|
||||
}
|
||||
const auto* q = reinterpret_cast<const uint64_t*>(address);
|
||||
for (int i = 0; i < 8; ++i) out.add(" %llx", (unsigned long long)q[i]);
|
||||
}
|
||||
// The faulting thread's stack: up to eight frames, unwound from its context, as module+offset.
|
||||
out.add(" | stack:");
|
||||
CONTEXT walk = c;
|
||||
for (int i = 0; i < 8 && walk.Rip && out.room(64); ++i) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t base = 0;
|
||||
if (VirtualQuery(reinterpret_cast<void*>(walk.Rip), ®ion, sizeof(region)) && region.Type == MEM_IMAGE) {
|
||||
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
|
||||
}
|
||||
char name[96] = "anon";
|
||||
if (base) module_name_utf8(base, name, sizeof(name));
|
||||
out.add(" ");
|
||||
out.add_escaped(name, 24);
|
||||
out.add("+%llx", (unsigned long long)(walk.Rip - base));
|
||||
DWORD64 image = 0;
|
||||
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
|
||||
if (!fn) {
|
||||
if (!readable_bytes(static_cast<uintptr_t>(walk.Rsp), 8)) break;
|
||||
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
|
||||
walk.Rsp += 8;
|
||||
continue;
|
||||
}
|
||||
PVOID handler_data = nullptr;
|
||||
DWORD64 frame = 0;
|
||||
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
|
||||
}
|
||||
out.finish();
|
||||
}
|
||||
|
||||
// A diagnostic that had to stop (a protection change failed): logged once per kind.
|
||||
void log_disarmed(const char* what, uintptr_t address) {
|
||||
char line[256];
|
||||
const int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"WARN\",\"sub\":\"runtime_veh\",\"event\":\"diagnostic_disarmed\","
|
||||
"\"detail\":\"%s address=%llx error=%lu\"}\n",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), what,
|
||||
(unsigned long long)address, GetLastError());
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
|
||||
// Set when runtime_veh detaches: helper threads stop at their next step and log nothing more.
|
||||
std::atomic<bool> g_diag_stop{false};
|
||||
std::atomic<int> g_diag_threads{0};
|
||||
|
||||
// Diagnostics (off unless BX_VEH_WATCH=ADDR:LEN, hex): a software write watch. A helper thread
|
||||
// makes the page holding [ADDR, ADDR+LEN) read-only as soon as that page is committed. Each
|
||||
// write fault in the page is allowed by restoring write access and single-stepping the writing
|
||||
// instruction; writes inside the range are logged with the instruction's module offset and the
|
||||
// value after the write, then the page is protected again. Writes by other threads while the
|
||||
// page is briefly writable are not seen, and system calls that write into the page fail while
|
||||
// it is protected, so this is for diagnosis only.
|
||||
uintptr_t g_watch_begin = 0, g_watch_end = 0, g_watch_page = 0;
|
||||
std::atomic<bool> g_watch_armed{false};
|
||||
std::atomic<uint32_t> g_watch_logged{0};
|
||||
DWORD g_watch_tls = TLS_OUT_OF_INDEXES;
|
||||
|
||||
// The watched address: "A:LEN", or a pointer chain "*A+O:LEN" / "**A+O1+O2:LEN" that the helper
|
||||
// thread resolves once every pointer in it is non-null and readable.
|
||||
uintptr_t g_watch_root = 0, g_watch_offsets[2] = {0, 0}, g_watch_length = 8;
|
||||
int g_watch_derefs = 0;
|
||||
|
||||
bool resolve_watch(uintptr_t* out) {
|
||||
uintptr_t address = g_watch_root;
|
||||
for (int k = 0; k < g_watch_derefs; ++k) {
|
||||
if (!readable_bytes(address, 8)) return false;
|
||||
const uintptr_t next = *reinterpret_cast<const uintptr_t*>(address);
|
||||
if (!next) return false;
|
||||
address = next + g_watch_offsets[k];
|
||||
}
|
||||
if (g_watch_derefs == 0) address += g_watch_offsets[0];
|
||||
*out = address;
|
||||
return true;
|
||||
}
|
||||
|
||||
DWORD WINAPI watch_arm_thread(LPVOID) {
|
||||
for (int i = 0; i < 600000 && !g_watch_armed.load() && !g_diag_stop.load(); ++i) {
|
||||
uintptr_t begin = 0;
|
||||
DWORD old = 0;
|
||||
if (resolve_watch(&begin) && readable_bytes(begin, g_watch_length)) {
|
||||
g_watch_begin = begin;
|
||||
g_watch_end = begin + g_watch_length;
|
||||
g_watch_page = begin & ~static_cast<uintptr_t>(4095);
|
||||
char line[512];
|
||||
int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"watch_armed\","
|
||||
"\"detail\":\"address=%llx contents:",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
(unsigned long long)begin);
|
||||
for (uintptr_t a = begin; a + 8 <= g_watch_end && len < static_cast<int>(sizeof(line)) - 24; a += 8) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " %llx",
|
||||
(unsigned long long)*reinterpret_cast<const uint64_t*>(a));
|
||||
}
|
||||
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
if (VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) {
|
||||
g_watch_armed = true;
|
||||
} else {
|
||||
log_disarmed("watch: could not protect the page", g_watch_page);
|
||||
}
|
||||
break;
|
||||
}
|
||||
Sleep(1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void start_write_watch() {
|
||||
char spec[96];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_WATCH", spec, sizeof(spec));
|
||||
if (n == 0 || n >= sizeof(spec)) return;
|
||||
g_watch_derefs = spec[0] == '*' ? (spec[1] == '*' ? 2 : 1) : 0;
|
||||
char* rest = nullptr;
|
||||
g_watch_root = static_cast<uintptr_t>(std::strtoull(spec + g_watch_derefs, &rest, 16));
|
||||
for (int k = 0; k < 2 && rest && *rest == '+'; ++k) g_watch_offsets[k] = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
|
||||
if (rest && *rest == ':') g_watch_length = static_cast<uintptr_t>(std::strtoull(rest + 1, nullptr, 16));
|
||||
g_watch_tls = TlsAlloc();
|
||||
if (g_watch_tls == TLS_OUT_OF_INDEXES) return;
|
||||
if (HANDLE t = CreateThread(nullptr, 0, watch_arm_thread, nullptr, 0, nullptr)) {
|
||||
++g_diag_threads;
|
||||
CloseHandle(t);
|
||||
}
|
||||
}
|
||||
|
||||
void log_watched_write(uintptr_t rip, uintptr_t address, uint64_t value) {
|
||||
if (g_watch_logged.fetch_add(1) >= 64) return;
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t base = 0;
|
||||
if (VirtualQuery(reinterpret_cast<void*>(rip), ®ion, sizeof(region)) && region.Type == MEM_IMAGE) {
|
||||
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
|
||||
}
|
||||
char line[256];
|
||||
const int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"watched_write\","
|
||||
"\"detail\":\"rip=%llx module_base=%llx address=%llx value_after=%llx\"}\n",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
(unsigned long long)rip, (unsigned long long)base, (unsigned long long)address,
|
||||
(unsigned long long)value);
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
|
||||
// Returns true when the exception belonged to the write watch and was handled.
|
||||
bool handle_write_watch(PEXCEPTION_POINTERS ep) {
|
||||
if (!g_watch_armed.load() || g_watch_tls == TLS_OUT_OF_INDEXES) return false;
|
||||
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
|
||||
if (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1) {
|
||||
const uintptr_t address = static_cast<uintptr_t>(r.ExceptionInformation[1]);
|
||||
if ((address & ~static_cast<uintptr_t>(4095)) != g_watch_page) return false;
|
||||
DWORD old = 0;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old)) {
|
||||
// Fail open: the write cannot be allowed, so the guest gets its access violation.
|
||||
g_watch_armed = false;
|
||||
log_disarmed("watch: could not unprotect the page", g_watch_page);
|
||||
return false;
|
||||
}
|
||||
// Remember the write for the single-step that follows it (+1 so 0 means "none").
|
||||
TlsSetValue(g_watch_tls, reinterpret_cast<void*>(address + 1));
|
||||
ep->ContextRecord->EFlags |= 0x100;
|
||||
return true;
|
||||
}
|
||||
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
|
||||
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_watch_tls));
|
||||
if (!pending) return false;
|
||||
TlsSetValue(g_watch_tls, nullptr);
|
||||
const uintptr_t address = pending - 1;
|
||||
if (address >= g_watch_begin && address < g_watch_end) {
|
||||
const uintptr_t slot = address & ~static_cast<uintptr_t>(7);
|
||||
log_watched_write(static_cast<uintptr_t>(reinterpret_cast<uintptr_t>(r.ExceptionAddress)), address,
|
||||
*reinterpret_cast<const uint64_t*>(slot));
|
||||
}
|
||||
DWORD old = 0;
|
||||
if (!g_watch_armed.load() || !VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READONLY, &old)) {
|
||||
if (g_watch_armed.exchange(false)) log_disarmed("watch: could not re-protect the page", g_watch_page);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Diagnostics (off unless BX_VEH_WATCH_RANGE=A:LEN, hex, at most 16 MiB): a write watch over a
|
||||
// range of pages, for data whose exact address moves between runs. A helper thread makes each
|
||||
// read-write page in the range read-only as soon as it is committed. A write fault is allowed by
|
||||
// restoring the page and single-stepping the instruction; the write is logged with its address,
|
||||
// the value after it and up to six frames of the writing thread, unwound from its context. After
|
||||
// 64 logged writes the whole range is made writable again and the watch stops.
|
||||
constexpr size_t kRangeWatchPages = 4096;
|
||||
uintptr_t g_rw_begin = 0, g_rw_end = 0;
|
||||
std::atomic<uint8_t> g_rw_armed[kRangeWatchPages];
|
||||
std::atomic<bool> g_rw_on{false};
|
||||
std::atomic<uint32_t> g_rw_logged{0};
|
||||
DWORD g_rw_tls = TLS_OUT_OF_INDEXES;
|
||||
|
||||
void range_watch_stop() {
|
||||
g_rw_on = false;
|
||||
for (size_t i = 0; i < kRangeWatchPages; ++i) {
|
||||
if (g_rw_armed[i].exchange(0)) {
|
||||
DWORD old = 0;
|
||||
VirtualProtect(reinterpret_cast<void*>(g_rw_begin + i * 4096), 4096, PAGE_READWRITE, &old);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// "*A+O:LEN": the range starts at [A] + O, resolved once the pointer at A is readable and non-zero.
|
||||
uintptr_t g_rw_root = 0, g_rw_offset = 0, g_rw_length = 0;
|
||||
|
||||
DWORD WINAPI range_watch_thread(LPVOID) {
|
||||
if (g_rw_root) {
|
||||
for (int i = 0; i < 600000; ++i) {
|
||||
if (g_diag_stop.load()) return 0;
|
||||
if (readable_bytes(g_rw_root, 8) && *reinterpret_cast<const uintptr_t*>(g_rw_root)) break;
|
||||
Sleep(1);
|
||||
}
|
||||
if (!readable_bytes(g_rw_root, 8) || !*reinterpret_cast<const uintptr_t*>(g_rw_root)) return 0;
|
||||
const uintptr_t begin = (*reinterpret_cast<const uintptr_t*>(g_rw_root) + g_rw_offset) & ~static_cast<uintptr_t>(4095);
|
||||
g_rw_end = (begin + g_rw_length + 4095) & ~static_cast<uintptr_t>(4095);
|
||||
g_rw_begin = begin;
|
||||
char line[200];
|
||||
const int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"range_watch_resolved\","
|
||||
"\"detail\":\"begin=%llx end=%llx\"}\n",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
(unsigned long long)g_rw_begin, (unsigned long long)g_rw_end);
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
const size_t pages = (g_rw_end - g_rw_begin) / 4096;
|
||||
for (int round = 0; round < 600000 && g_rw_on.load() && !g_diag_stop.load(); ++round) {
|
||||
bool all = true;
|
||||
for (size_t i = 0; i < pages && g_rw_on.load(); ++i) {
|
||||
if (g_rw_armed[i].load()) continue;
|
||||
all = false;
|
||||
const uintptr_t page = g_rw_begin + i * 4096;
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(page), ®ion, sizeof(region)) || region.State != MEM_COMMIT ||
|
||||
region.Protect != PAGE_READWRITE) {
|
||||
continue;
|
||||
}
|
||||
DWORD old = 0;
|
||||
if (VirtualProtect(reinterpret_cast<void*>(page), 4096, PAGE_READONLY, &old)) g_rw_armed[i] = 1;
|
||||
}
|
||||
if (all) break;
|
||||
Sleep(1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void start_range_watch() {
|
||||
char spec[64];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_WATCH_RANGE", spec, sizeof(spec));
|
||||
if (n == 0 || n >= sizeof(spec)) return;
|
||||
char* rest = nullptr;
|
||||
const bool chain = spec[0] == '*';
|
||||
const uintptr_t first = static_cast<uintptr_t>(std::strtoull(spec + (chain ? 1 : 0), &rest, 16));
|
||||
uintptr_t offset = 0;
|
||||
if (chain && rest && *rest == '+') offset = static_cast<uintptr_t>(std::strtoull(rest + 1, &rest, 16));
|
||||
const uintptr_t length = rest && *rest == ':' ? static_cast<uintptr_t>(std::strtoull(rest + 1, nullptr, 16)) : 0;
|
||||
if (!first || !length || length > kRangeWatchPages * 4096) return;
|
||||
g_rw_tls = TlsAlloc();
|
||||
if (g_rw_tls == TLS_OUT_OF_INDEXES) return;
|
||||
if (chain) {
|
||||
g_rw_root = first;
|
||||
g_rw_offset = offset;
|
||||
g_rw_length = length;
|
||||
} else {
|
||||
g_rw_begin = first & ~static_cast<uintptr_t>(4095);
|
||||
g_rw_end = (g_rw_begin + length + 4095) & ~static_cast<uintptr_t>(4095);
|
||||
}
|
||||
g_rw_on = true;
|
||||
if (HANDLE t = CreateThread(nullptr, 0, range_watch_thread, nullptr, 0, nullptr)) {
|
||||
++g_diag_threads;
|
||||
CloseHandle(t);
|
||||
}
|
||||
}
|
||||
|
||||
void log_range_write(const CONTEXT& c, uintptr_t address) {
|
||||
uintptr_t frames[6]{};
|
||||
int count = 0;
|
||||
CONTEXT walk = c;
|
||||
for (; count < 6 && walk.Rip; ++count) {
|
||||
frames[count] = static_cast<uintptr_t>(walk.Rip);
|
||||
DWORD64 image = 0;
|
||||
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
|
||||
if (!fn) {
|
||||
if (!readable_bytes(static_cast<uintptr_t>(walk.Rsp), 8)) { ++count; break; }
|
||||
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
|
||||
walk.Rsp += 8;
|
||||
continue;
|
||||
}
|
||||
PVOID handler_data = nullptr;
|
||||
DWORD64 frame = 0;
|
||||
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
|
||||
}
|
||||
char line[640];
|
||||
int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"range_write\","
|
||||
"\"detail\":\"address=%llx value_after=%llx frames:",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
|
||||
(unsigned long long)address,
|
||||
(unsigned long long)*reinterpret_cast<const uint64_t*>(address & ~static_cast<uintptr_t>(7)));
|
||||
for (int i = 0; i < count && len < static_cast<int>(sizeof(line)) - 48; ++i) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t base = 0;
|
||||
if (VirtualQuery(reinterpret_cast<void*>(frames[i]), ®ion, sizeof(region)) && region.Type == MEM_IMAGE) {
|
||||
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
|
||||
}
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " %llx+%llx", (unsigned long long)base,
|
||||
(unsigned long long)(frames[i] - base));
|
||||
}
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line)) - 4) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
|
||||
write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true when the exception belonged to the range watch and was handled.
|
||||
bool handle_range_watch(PEXCEPTION_POINTERS ep) {
|
||||
if (g_rw_tls == TLS_OUT_OF_INDEXES) return false;
|
||||
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
|
||||
if (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1) {
|
||||
const uintptr_t address = static_cast<uintptr_t>(r.ExceptionInformation[1]);
|
||||
if (address < g_rw_begin || address >= g_rw_end) return false;
|
||||
const size_t index = (address - g_rw_begin) / 4096;
|
||||
if (!g_rw_armed[index].load()) return false;
|
||||
DWORD old = 0;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READWRITE, &old)) {
|
||||
g_rw_armed[index] = 0; // fail open: the guest gets its access violation
|
||||
log_disarmed("range watch: could not unprotect a page", g_rw_begin + index * 4096);
|
||||
return false;
|
||||
}
|
||||
TlsSetValue(g_rw_tls, reinterpret_cast<void*>(address + 1));
|
||||
ep->ContextRecord->EFlags |= 0x100;
|
||||
return true;
|
||||
}
|
||||
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
|
||||
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_rw_tls));
|
||||
if (!pending) return false;
|
||||
TlsSetValue(g_rw_tls, nullptr);
|
||||
const uintptr_t address = pending - 1;
|
||||
static const uint32_t cap = [] {
|
||||
char v[16];
|
||||
const DWORD k = GetEnvironmentVariableA("BX_VEH_WATCH_RANGE_MAX", v, sizeof(v));
|
||||
const unsigned long want = (k > 0 && k < sizeof(v)) ? std::strtoul(v, nullptr, 10) : 64;
|
||||
return static_cast<uint32_t>(want == 0 ? 64 : (want > 200000 ? 200000 : want));
|
||||
}();
|
||||
const uint32_t n = g_rw_logged.fetch_add(1);
|
||||
if (n < cap) log_range_write(*ep->ContextRecord, address);
|
||||
if (n + 1 >= cap) {
|
||||
range_watch_stop();
|
||||
} else if (g_rw_on.load()) {
|
||||
DWORD old = 0;
|
||||
const size_t index = (address - g_rw_begin) / 4096;
|
||||
if (g_rw_armed[index].load() &&
|
||||
!VirtualProtect(reinterpret_cast<void*>(g_rw_begin + index * 4096), 4096, PAGE_READONLY, &old)) {
|
||||
g_rw_armed[index] = 0;
|
||||
log_disarmed("range watch: could not re-protect a page", g_rw_begin + index * 4096);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Diagnostics (off unless BX_VEH_HIT=A1,A2,..., hex, at most 8): software code breakpoints in this
|
||||
// process. Each address gets an int3 when runtime_veh attaches; a hit logs the registers, puts the
|
||||
// original byte back, single-steps that instruction and re-inserts the int3. The first 16 hits per
|
||||
// address are logged, then every 256th. Other threads can pass an address unseen while its byte is
|
||||
// restored, so this is for diagnosis only.
|
||||
struct CodeHit {
|
||||
uintptr_t address;
|
||||
uint8_t original;
|
||||
std::atomic<uint32_t> hits;
|
||||
};
|
||||
CodeHit g_code_hits[8];
|
||||
int g_code_hit_count = 0;
|
||||
DWORD g_code_hit_tls = TLS_OUT_OF_INDEXES;
|
||||
|
||||
// False when the byte could not be written. A failure to restore the page's original protection
|
||||
// is logged: the page then stays writable, which the log record makes visible.
|
||||
bool write_code_byte(uintptr_t address, uint8_t value) {
|
||||
DWORD old = 0;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(address), 1, PAGE_EXECUTE_READWRITE, &old)) return false;
|
||||
*reinterpret_cast<volatile uint8_t*>(address) = value;
|
||||
DWORD unused = 0;
|
||||
if (!VirtualProtect(reinterpret_cast<void*>(address), 1, old, &unused)) {
|
||||
log_disarmed("code hit: could not restore the page protection", address);
|
||||
}
|
||||
FlushInstructionCache(GetCurrentProcess(), reinterpret_cast<void*>(address), 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Diagnostics (off unless BX_VEH_SAMPLE=MS, decimal): a sampling profiler for every thread in the
|
||||
// process. Every MS milliseconds a helper thread visits each other thread: while it is suspended
|
||||
// only its context and up to 64 KiB of its stack are copied (no heap or loader calls, so a thread
|
||||
// suspended inside either cannot deadlock the sampler). After it resumes, up to eight frames are
|
||||
// unwound against the copy with the images' unwind data and logged as module base + offset, with
|
||||
// the thread id. At most 20000 samples are logged. For diagnosis only.
|
||||
DWORD g_sample_interval = 0;
|
||||
DWORD g_sample_self = 0;
|
||||
alignas(16) uint8_t g_sample_stack[64 * 1024];
|
||||
|
||||
void sample_thread(DWORD tid) {
|
||||
HANDLE h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, tid);
|
||||
if (!h) return;
|
||||
CONTEXT c{};
|
||||
c.ContextFlags = CONTEXT_FULL;
|
||||
uintptr_t stack_lo = 0;
|
||||
size_t copied = 0;
|
||||
bool got = false;
|
||||
if (SuspendThread(h) != static_cast<DWORD>(-1)) {
|
||||
got = GetThreadContext(h, &c) != FALSE;
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (got && VirtualQuery(reinterpret_cast<void*>(c.Rsp), ®ion, sizeof(region)) && region.State == MEM_COMMIT) {
|
||||
stack_lo = static_cast<uintptr_t>(c.Rsp);
|
||||
const uintptr_t end = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
copied = end - stack_lo < sizeof(g_sample_stack) ? end - stack_lo : sizeof(g_sample_stack);
|
||||
std::memcpy(g_sample_stack, reinterpret_cast<const void*>(stack_lo), copied);
|
||||
}
|
||||
ResumeThread(h);
|
||||
}
|
||||
CloseHandle(h);
|
||||
if (!got) return;
|
||||
// Unwind against the copy: stack addresses (rsp, and rbp when it points into the stack) are
|
||||
// rebased into g_sample_stack; return addresses read from it are the thread's real ones.
|
||||
const uintptr_t copy = reinterpret_cast<uintptr_t>(g_sample_stack);
|
||||
auto in_stack = [&](DWORD64 a) { return a >= stack_lo && a < stack_lo + copied; };
|
||||
CONTEXT walk = c;
|
||||
walk.Rsp = copy;
|
||||
if (in_stack(c.Rbp)) walk.Rbp = copy + (c.Rbp - stack_lo);
|
||||
uintptr_t frames[8]{};
|
||||
int count = 0;
|
||||
for (; count < 8 && walk.Rip; ++count) {
|
||||
frames[count] = static_cast<uintptr_t>(walk.Rip);
|
||||
if (walk.Rsp < copy || walk.Rsp + 8 > copy + copied) { ++count; break; }
|
||||
DWORD64 image = 0;
|
||||
PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(walk.Rip, &image, nullptr);
|
||||
if (!fn) { // leaf function: the return address is at rsp
|
||||
walk.Rip = *reinterpret_cast<const DWORD64*>(walk.Rsp);
|
||||
walk.Rsp += 8;
|
||||
continue;
|
||||
}
|
||||
PVOID handler_data = nullptr;
|
||||
DWORD64 frame = 0;
|
||||
RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, walk.Rip, fn, &walk, &handler_data, &frame, nullptr);
|
||||
}
|
||||
char line[760];
|
||||
LineBuf out(line, sizeof(line));
|
||||
out.add("{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"sample\",\"detail\":\"thread=%lu",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), tid);
|
||||
for (int i = 0; i < count && out.room(64); ++i) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t base = 0;
|
||||
if (VirtualQuery(reinterpret_cast<void*>(frames[i]), ®ion, sizeof(region)) && region.Type == MEM_IMAGE) {
|
||||
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
|
||||
}
|
||||
// The thread runs again, so the loader lock taken by GetModuleFileNameW cannot be held by it.
|
||||
char name[96] = "anon";
|
||||
if (base) module_name_utf8(base, name, sizeof(name));
|
||||
out.add(" ");
|
||||
out.add_escaped(name, 24);
|
||||
out.add("+%llx", (unsigned long long)(frames[i] - base));
|
||||
}
|
||||
if (!g_diag_stop.load()) out.finish();
|
||||
}
|
||||
|
||||
DWORD WINAPI sampler_main(LPVOID) {
|
||||
const DWORD pid = GetCurrentProcessId();
|
||||
for (int logged = 0; logged < 20000 && !g_diag_stop.load();) {
|
||||
Sleep(g_sample_interval);
|
||||
if (g_diag_stop.load()) break;
|
||||
DWORD tids[256];
|
||||
int n = 0;
|
||||
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
|
||||
if (snap == INVALID_HANDLE_VALUE) continue;
|
||||
THREADENTRY32 te{};
|
||||
te.dwSize = sizeof(te);
|
||||
for (BOOL ok = Thread32First(snap, &te); ok && n < 256; ok = Thread32Next(snap, &te)) {
|
||||
if (te.th32OwnerProcessID == pid && te.th32ThreadID != g_sample_self) tids[n++] = te.th32ThreadID;
|
||||
}
|
||||
CloseHandle(snap);
|
||||
for (int i = 0; i < n; ++i, ++logged) sample_thread(tids[i]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void start_sampler() {
|
||||
char spec[16];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_SAMPLE", spec, sizeof(spec));
|
||||
if (n == 0 || n >= sizeof(spec)) return;
|
||||
g_sample_interval = static_cast<DWORD>(std::strtoul(spec, nullptr, 10));
|
||||
if (g_sample_interval == 0) return;
|
||||
if (HANDLE t = CreateThread(nullptr, 0, sampler_main, nullptr, 0, &g_sample_self)) {
|
||||
++g_diag_threads;
|
||||
CloseHandle(t);
|
||||
}
|
||||
}
|
||||
|
||||
void start_code_hits() {
|
||||
char spec[256];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT", spec, sizeof(spec));
|
||||
if (n == 0 || n >= sizeof(spec)) return;
|
||||
g_code_hit_tls = TlsAlloc();
|
||||
if (g_code_hit_tls == TLS_OUT_OF_INDEXES) return;
|
||||
for (const char* item = spec; *item && g_code_hit_count < 8;) {
|
||||
char* end = nullptr;
|
||||
const uintptr_t address = static_cast<uintptr_t>(std::strtoull(item, &end, 16));
|
||||
const char* comma = std::strchr(item, ',');
|
||||
item = comma ? comma + 1 : item + std::strlen(item);
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!address || !VirtualQuery(reinterpret_cast<void*>(address), ®ion, sizeof(region)) ||
|
||||
region.Type != MEM_IMAGE || region.State != MEM_COMMIT) {
|
||||
continue;
|
||||
}
|
||||
CodeHit& hit = g_code_hits[g_code_hit_count];
|
||||
hit.address = address;
|
||||
hit.original = *reinterpret_cast<const uint8_t*>(address);
|
||||
if (write_code_byte(address, 0xCC)) ++g_code_hit_count;
|
||||
}
|
||||
char line[160];
|
||||
const int len = std::snprintf(line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"code_hits_armed\","
|
||||
"\"detail\":\"count=%d\"}\n",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), g_code_hit_count);
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line))) write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
|
||||
void log_code_hit(const CodeHit& hit, uint32_t count, const CONTEXT& c) {
|
||||
char line[2048];
|
||||
int len = std::snprintf(
|
||||
line, sizeof(line),
|
||||
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"INFO\",\"sub\":\"runtime_veh\",\"event\":\"code_hit\","
|
||||
"\"detail\":\"address=%llx hit=%u rax=%llx rbx=%llx rcx=%llx rdx=%llx rsi=%llx rdi=%llx rbp=%llx rsp=%llx "
|
||||
"r8=%llx r9=%llx r10=%llx r11=%llx r12=%llx r13=%llx r14=%llx r15=%llx",
|
||||
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(), (unsigned long long)hit.address, count,
|
||||
(unsigned long long)c.Rax, (unsigned long long)c.Rbx, (unsigned long long)c.Rcx, (unsigned long long)c.Rdx,
|
||||
(unsigned long long)c.Rsi, (unsigned long long)c.Rdi, (unsigned long long)c.Rbp, (unsigned long long)c.Rsp,
|
||||
(unsigned long long)c.R8, (unsigned long long)c.R9, (unsigned long long)c.R10, (unsigned long long)c.R11,
|
||||
(unsigned long long)c.R12, (unsigned long long)c.R13, (unsigned long long)c.R14, (unsigned long long)c.R15);
|
||||
// The first 16 bytes behind the three argument registers, when they point at readable memory.
|
||||
const struct {
|
||||
const char* name;
|
||||
DWORD64 value;
|
||||
} args[] = {{"rcx", c.Rcx}, {"rdx", c.Rdx}, {"r8", c.R8}};
|
||||
for (const auto& a : args) {
|
||||
if (len <= 0 || len >= static_cast<int>(sizeof(line)) - 64 || !readable_bytes(static_cast<uintptr_t>(a.value), 16)) continue;
|
||||
const auto* q = reinterpret_cast<const uint64_t*>(static_cast<uintptr_t>(a.value));
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " [%s]=%016llx %016llx", a.name, (unsigned long long)q[0],
|
||||
(unsigned long long)q[1]);
|
||||
// Printable text (a path or name argument): up to 96 characters of it.
|
||||
const auto* s = reinterpret_cast<const unsigned char*>(static_cast<uintptr_t>(a.value));
|
||||
if (s[0] >= 0x20 && s[0] < 0x7f && s[1] >= 0x20 && s[1] < 0x7f && readable_bytes(static_cast<uintptr_t>(a.value), 96)) {
|
||||
char text[97];
|
||||
int n = 0;
|
||||
while (n < 96 && s[n] >= 0x20 && s[n] < 0x7f) {
|
||||
text[n] = (s[n] == '"' || s[n] == '\\') ? '_' : static_cast<char>(s[n]);
|
||||
++n;
|
||||
}
|
||||
text[n] = '\0';
|
||||
if (len < static_cast<int>(sizeof(line)) - 120) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " [%s]s=%s", a.name, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
// BX_VEH_HIT_RDX=LEN (hex, at most 0x200): also dump LEN bytes of the object rdx points to.
|
||||
static const size_t rdx_len = [] {
|
||||
char v[16];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT_RDX", v, sizeof(v));
|
||||
if (n == 0 || n >= sizeof(v)) return static_cast<size_t>(0);
|
||||
const size_t want = static_cast<size_t>(std::strtoull(v, nullptr, 16)) & ~static_cast<size_t>(7);
|
||||
return want > 0x200 ? static_cast<size_t>(0x200) : want;
|
||||
}();
|
||||
if (rdx_len && len > 0 && readable_bytes(static_cast<uintptr_t>(c.Rdx), rdx_len)) {
|
||||
const auto* q = reinterpret_cast<const uint64_t*>(static_cast<uintptr_t>(c.Rdx));
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " rdx_obj:");
|
||||
for (size_t i = 0; i < rdx_len / 8 && len < static_cast<int>(sizeof(line)) - 24; ++i) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, " %llx", (unsigned long long)q[i]);
|
||||
}
|
||||
}
|
||||
if (len > 0 && len < static_cast<int>(sizeof(line)) - 4) {
|
||||
len += std::snprintf(line + len, sizeof(line) - len, "\"}\n");
|
||||
write_log_line(line, static_cast<size_t>(len));
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true when the exception belonged to a code breakpoint and was handled.
|
||||
bool handle_code_hit(PEXCEPTION_POINTERS ep) {
|
||||
if (g_code_hit_count == 0) return false;
|
||||
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
|
||||
CONTEXT& c = *ep->ContextRecord;
|
||||
if (r.ExceptionCode == EXCEPTION_BREAKPOINT) {
|
||||
const uintptr_t at = reinterpret_cast<uintptr_t>(r.ExceptionAddress);
|
||||
for (int i = 0; i < g_code_hit_count; ++i) {
|
||||
CodeHit& hit = g_code_hits[i];
|
||||
if (at != hit.address && c.Rip - 1 != hit.address) continue;
|
||||
const uint32_t count = hit.hits.fetch_add(1) + 1;
|
||||
static const bool every = [] {
|
||||
char v[4];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_VEH_HIT_ALL", v, sizeof(v));
|
||||
return n > 0 && n < sizeof(v) && v[0] == '1';
|
||||
}();
|
||||
if (count <= 16 || count % 256 == 0 || (every && count <= 20000)) log_code_hit(hit, count, c);
|
||||
if (!write_code_byte(hit.address, hit.original)) {
|
||||
// The original instruction cannot be put back: stop handling this address and let
|
||||
// the breakpoint reach the guest instead of looping on it.
|
||||
log_disarmed("code hit: could not restore the original byte", hit.address);
|
||||
hit.address = 0;
|
||||
return false;
|
||||
}
|
||||
c.Rip = hit.address;
|
||||
c.EFlags |= 0x100;
|
||||
TlsSetValue(g_code_hit_tls, reinterpret_cast<void*>(static_cast<uintptr_t>(i + 1)));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (r.ExceptionCode == EXCEPTION_SINGLE_STEP) {
|
||||
const uintptr_t pending = reinterpret_cast<uintptr_t>(TlsGetValue(g_code_hit_tls));
|
||||
if (!pending) return false;
|
||||
TlsSetValue(g_code_hit_tls, nullptr);
|
||||
CodeHit& hit = g_code_hits[pending - 1];
|
||||
if (hit.address && !g_diag_stop.load() && !write_code_byte(hit.address, 0xCC)) {
|
||||
log_disarmed("code hit: could not re-insert the breakpoint", hit.address);
|
||||
hit.address = 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Restores every page and code byte the diagnostics changed (used at detach).
|
||||
void disarm_diagnostics() {
|
||||
if (g_watch_armed.exchange(false)) {
|
||||
DWORD old = 0;
|
||||
VirtualProtect(reinterpret_cast<void*>(g_watch_page), 4096, PAGE_READWRITE, &old);
|
||||
}
|
||||
if (g_rw_on.load() || g_rw_begin) range_watch_stop();
|
||||
for (int i = 0; i < g_code_hit_count; ++i) {
|
||||
CodeHit& hit = g_code_hits[i];
|
||||
if (hit.address && *reinterpret_cast<const volatile uint8_t*>(hit.address) == 0xCC) {
|
||||
write_code_byte(hit.address, hit.original);
|
||||
}
|
||||
hit.address = 0;
|
||||
}
|
||||
for (DWORD* tls : {&g_watch_tls, &g_rw_tls, &g_code_hit_tls}) {
|
||||
if (*tls != TLS_OUT_OF_INDEXES) {
|
||||
TlsFree(*tls);
|
||||
*tls = TLS_OUT_OF_INDEXES;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
|
||||
if (!ep || !ep->ExceptionRecord || !ep->ContextRecord) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION) {
|
||||
if (handle_code_hit(ep)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
if (handle_range_watch(ep)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
if (handle_write_watch(ep)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
const DWORD code = ep->ExceptionRecord->ExceptionCode;
|
||||
if (code == EXCEPTION_BREAKPOINT || code == kStatusAssertionFailure) {
|
||||
log_breakpoint(*ep->ExceptionRecord);
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
if (code == EXCEPTION_ACCESS_VIOLATION) {
|
||||
if (!g_av_context_on) return EXCEPTION_CONTINUE_SEARCH; // diagnostics off: no work at all
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (g_av_all || (VirtualQuery(ep->ExceptionRecord->ExceptionAddress, ®ion, sizeof(region)) && region.Type == MEM_IMAGE)) {
|
||||
log_av_context(*ep);
|
||||
}
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
if (code != EXCEPTION_ILLEGAL_INSTRUCTION) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
@@ -479,6 +1352,15 @@ const bx_runtime_config_t* bx_get_runtime_config(void) {
|
||||
int bx_veh_install(void) {
|
||||
if (!g_veh_handle) {
|
||||
g_veh_handle = AddVectoredExceptionHandler(1, bx_veh_handler);
|
||||
if (g_veh_handle) {
|
||||
read_av_switches();
|
||||
// The helper threads below start running only after the loader lock is released; nothing
|
||||
// here waits for them. They check g_diag_stop and stop at detach.
|
||||
start_write_watch();
|
||||
start_code_hits();
|
||||
start_sampler();
|
||||
start_range_watch();
|
||||
}
|
||||
}
|
||||
return g_veh_handle != nullptr ? 1 : 0;
|
||||
}
|
||||
@@ -503,15 +1385,23 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
|
||||
if (current_filter != log_unhandled_exception) {
|
||||
SetUnhandledExceptionFilter(current_filter);
|
||||
}
|
||||
// Stop the diagnostics and take them out of the guest's memory: restore watched pages and
|
||||
// original code bytes. Nothing waits for the helper threads (that would deadlock on the
|
||||
// loader lock); they stop at their next step.
|
||||
g_diag_stop = true;
|
||||
disarm_diagnostics();
|
||||
if (g_veh_handle) {
|
||||
RemoveVectoredExceptionHandler(g_veh_handle);
|
||||
g_veh_handle = nullptr;
|
||||
}
|
||||
if (g_log_handle != INVALID_HANDLE_VALUE) {
|
||||
// A helper thread may still be inside write_log_line when this runs. While any helper was
|
||||
// started, the log handle and its lock are left alive (the process is ending, or the DLL is
|
||||
// being unloaded with threads that only touch them); otherwise they are released.
|
||||
if (g_diag_threads.load() == 0 && g_log_handle != INVALID_HANDLE_VALUE) {
|
||||
CloseHandle(g_log_handle);
|
||||
g_log_handle = INVALID_HANDLE_VALUE;
|
||||
}
|
||||
if (g_log_lock_ready) {
|
||||
if (g_diag_threads.load() == 0 && g_log_lock_ready) {
|
||||
DeleteCriticalSection(&g_log_lock);
|
||||
g_log_lock_ready = false;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
+135
-11
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -1314,8 +1379,39 @@ 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");
|
||||
|
||||
constexpr UINT64 kXboxRequestSourceMemoryBit = 0x400000ull;
|
||||
constexpr UINT64 kXboxRequestCompressedBit = 0x1ull;
|
||||
// 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;
|
||||
@@ -1424,12 +1520,25 @@ public:
|
||||
reject(E_DSTORAGE_INVALID_SOURCE_TYPE, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
if ((request->options & kXboxRequestCompressedBit) != 0) {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_compressed");
|
||||
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->destination || request->source_size != request->destination_size) {
|
||||
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;
|
||||
}
|
||||
@@ -1437,6 +1546,10 @@ public:
|
||||
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");
|
||||
@@ -1623,11 +1736,22 @@ public:
|
||||
const UINT slots = desc->capacity - 1u;
|
||||
auto* entries = new (std::nothrow) Entry[slots];
|
||||
if (!entries) return E_OUTOFMEMORY;
|
||||
auto* queue = new (std::nothrow) WorkQueue(entries, slots, true, desc->capacity / 2u);
|
||||
// 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();
|
||||
|
||||
@@ -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
@@ -105,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;
|
||||
@@ -296,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*) {}
|
||||
@@ -674,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")
|
||||
@@ -693,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
|
||||
@@ -750,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);
|
||||
@@ -773,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;
|
||||
@@ -801,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
|
||||
+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,6 +1,7 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -9,6 +10,8 @@
|
||||
|
||||
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*);
|
||||
@@ -31,19 +34,60 @@ 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 count reached zero,
|
||||
// not that the object was freed. Removing `delete this` would leave the
|
||||
// count correct while leaking, so this assertion is what catches it.
|
||||
// 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. This works whether the log path came from the runner or from
|
||||
// the temp file the fixture creates below.
|
||||
// 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,
|
||||
@@ -77,28 +121,46 @@ static std::string read_log_file_from(const char* path, uint64_t offset) {
|
||||
}
|
||||
|
||||
int main() {
|
||||
// `bx-cli run` sets BX_LOG_FILE for the guest. When the fixture is
|
||||
// run directly there is no such variable, so create a temp log and
|
||||
// point the shim at it; otherwise the assertions below would read an
|
||||
// empty file and fail for the wrong reason.
|
||||
char log_path[MAX_PATH]{};
|
||||
DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
if (n == 0 || n >= sizeof(log_path)) {
|
||||
char temp_dir[MAX_PATH]{};
|
||||
CHECK(GetTempPathA(sizeof(temp_dir), temp_dir) > 0);
|
||||
CHECK(GetTempFileNameA(temp_dir, "bxg", 0, log_path) != 0);
|
||||
CHECK(SetEnvironmentVariableA("BX_LOG_FILE", log_path));
|
||||
}
|
||||
const uint64_t log_start = log_file_size(log_path);
|
||||
// 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);
|
||||
@@ -120,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);
|
||||
@@ -276,13 +379,12 @@ int main() {
|
||||
CHECK(CloseHandle(wait1) && CloseHandle(wait2));
|
||||
CHECK(disp_unknown->Release() == 0);
|
||||
|
||||
// The live-dispatcher count is the only observable evidence that the
|
||||
// dispatcher was destroyed: `Release` returning 0 proves the count, not
|
||||
// the deallocation. `dispatch_mode` logs `mode=manual live_dispatchers=N`
|
||||
// on every transition, so a `delete this` removal that leaks the object
|
||||
// would leave `live_dispatchers=1` behind and fail here.
|
||||
// `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(log_path, log_start);
|
||||
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);
|
||||
|
||||
@@ -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) {
|
||||
@@ -667,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;
|
||||
@@ -683,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;
|
||||
@@ -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,6 +1565,7 @@ 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;
|
||||
@@ -1354,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);
|
||||
@@ -1384,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
|
||||
@@ -1419,7 +1647,7 @@ int main() {
|
||||
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;
|
||||
@@ -1460,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);
|
||||
@@ -1473,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
+64
@@ -0,0 +1,64 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Runs test_d3d12_presentx once normally and once per negative control, and checks that each
|
||||
# control fails in its own stage with its own evidence. Needs build-shims/ and bx-cli built.
|
||||
# Usage (from the repository root): tests/conformance/test_d3d12_presentx/run_controls.sh <bottle>
|
||||
set -u
|
||||
|
||||
bottle=${1:?usage: run_controls.sh <d3dmetal_bottle>}
|
||||
dir=$(mktemp -d) || exit 1
|
||||
bad=0
|
||||
|
||||
run() { # name injection
|
||||
BX_PRESENTX_INJECT=$2 target/debug/bx-cli run --inherit-env --bottle "$bottle" --backend d3dmetal \
|
||||
--shims build-shims/bin --log "$dir/$1.jsonl" --timeout 90 \
|
||||
--exe build-shims/bin/test_d3d12_presentx.exe >"$dir/$1.out" 2>&1
|
||||
status=$?
|
||||
}
|
||||
expect() { # name file pattern
|
||||
grep -aq -- "$3" "$dir/$1.$2" || { echo "$1: missing in $2: $3"; bad=1; }
|
||||
}
|
||||
must_fail() { # name stage
|
||||
[ "$status" -ne 0 ] || { echo "$1: exited 0"; bad=1; }
|
||||
expect "$1" out "first failing stage: $2)"
|
||||
}
|
||||
|
||||
run normal ""
|
||||
[ "$status" -eq 0 ] || { echo "normal: exit $status"; bad=1; }
|
||||
expect normal out "^PASS: test_d3d12_presentx (.* 0 skipped)"
|
||||
|
||||
run bad-window bad-window
|
||||
must_fail bad-window create
|
||||
expect bad-window out "FAIL \[create\]: CreateSwapChain hr=0x887a0001"
|
||||
# The contract stage logs seven argument rejections; the injected window must add the eighth.
|
||||
n=$(grep -ac '"event":"present_create_rejected".*invalid window or description' "$dir/bad-window.jsonl")
|
||||
[ "$n" -eq 8 ] || { echo "bad-window: $n argument rejections logged, expected 8"; bad=1; }
|
||||
|
||||
run skip-draw skip-draw
|
||||
must_fail skip-draw pixels
|
||||
expect skip-draw out "frame 5: 2432 of 6000 pixels differ"
|
||||
expect skip-draw out "pixels_wrong=2432 "
|
||||
|
||||
run wrong-expectation wrong-expectation
|
||||
must_fail wrong-expectation pixels
|
||||
expect wrong-expectation out "pixels_wrong=29184 "
|
||||
|
||||
run skip-wait-fault skip-wait-fault
|
||||
must_fail skip-wait-fault sync
|
||||
expect skip-wait-fault out "SetEventOnCompletion fault was not injected"
|
||||
|
||||
run wrong-removed-hr wrong-removed-hr
|
||||
must_fail wrong-removed-hr sync
|
||||
expect wrong-removed-hr out "post-present device reset must return DXGI_ERROR_DEVICE_RESET: hr=0x80040205"
|
||||
|
||||
run zero-timeout-overrun zero-timeout-overrun
|
||||
must_fail zero-timeout-overrun sync
|
||||
expect zero-timeout-overrun out "WaitForIdle(0) must reject zero without signaling:"
|
||||
|
||||
if [ "$bad" -ne 0 ]; then
|
||||
echo "FAIL: run_controls (output kept in $dir)"
|
||||
exit 1
|
||||
fi
|
||||
rm -rf "$dir"
|
||||
echo "PASS: run_controls (1 normal run, 6 negative controls)"
|
||||
@@ -0,0 +1,4 @@
|
||||
# Synthetic conformance test for the Xbox 32-byte D3D12ConfigureVirtualMemoryX decoder.
|
||||
add_executable(test_d3d12_vmem_xbox main.cpp)
|
||||
target_include_directories(test_d3d12_vmem_xbox PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_d3d12_vmem_xbox PRIVATE d3d12_xs xmem bx_runtime_veh kernel32)
|
||||
@@ -0,0 +1,529 @@
|
||||
/*
|
||||
* Conformance test for the Xbox virtual-memory configuration decoder in
|
||||
* d3d12_xs.dll!D3D12ConfigureVirtualMemoryX (D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION).
|
||||
*
|
||||
* Expected values come from the authorized GDK documentation of the function and the
|
||||
* structure, written out here rather than taken from the shim's header:
|
||||
* - the default page-table size (5 x 4 MB) reports a minimum graphics address of 2 GiB and
|
||||
* a maximum of 159.375 GiB; the input fields are left as the caller set them;
|
||||
* - the page-table size is clamped to 33, the frame-buffer preserve size to 64 MiB, and -1
|
||||
* (the legacy size) is kept;
|
||||
* - after a D3D12 device exists the call fails with E_FAIL and writes nothing;
|
||||
* - every accepted configuration is recorded only (applied=0) and still emits the
|
||||
* unimplemented-API stub, and leaves a cached BXVM backing heap untouched.
|
||||
* Inferred, and marked as such in the log: the maximum for other page-table sizes scales
|
||||
* linearly (max_estimated=1), and a page-table size of 0, an unreadable configuration and
|
||||
* unwritable outputs fail with E_INVALIDARG.
|
||||
*
|
||||
* Several fixtures share one BX_LOG_FILE, so every log check reads only the
|
||||
* bytes appended since the step it checks began.
|
||||
*/
|
||||
#include <d3d12.h>
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdarg>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
extern "C" {
|
||||
// The documented four parameters (adapter, parameters, riid, device); a zeroed block (Version 0)
|
||||
// keeps the PC-layout proxy this test is written against (ADR 0009).
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(void* adapter, const void* params, REFIID riid, void** ppv);
|
||||
alignas(8) static const unsigned char kPcLayoutParams[80] = {};
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12ConfigureVirtualMemoryX(void* config);
|
||||
__declspec(dllimport) PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, uint64_t xmem_flags,
|
||||
DWORD protect);
|
||||
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR page_count, PULONG_PTR pages);
|
||||
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR page_count, PULONG_PTR pages);
|
||||
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID address, ULONG_PTR page_count, PULONG_PTR pages);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t kBxvmMagic = 0x4D565842u;
|
||||
constexpr uint32_t kBxvmFlagBacking = 0x1u;
|
||||
constexpr uint64_t k64K = 64ull * 1024ull;
|
||||
|
||||
struct BxvmConfig {
|
||||
uint32_t magic;
|
||||
uint32_t struct_size;
|
||||
uint32_t version;
|
||||
uint32_t flags;
|
||||
uint64_t base_va;
|
||||
uint64_t size_bytes;
|
||||
uint64_t reserved;
|
||||
uint64_t cpu_pointer;
|
||||
};
|
||||
|
||||
struct XboxConfig {
|
||||
uint32_t flags;
|
||||
uint32_t page_table_4mb_pages;
|
||||
uint32_t frame_buffer_preserve_bytes;
|
||||
uint32_t padding;
|
||||
uint64_t min_gpu_va;
|
||||
uint64_t max_gpu_va;
|
||||
};
|
||||
static_assert(sizeof(BxvmConfig) == 48);
|
||||
static_assert(offsetof(BxvmConfig, magic) == 0);
|
||||
static_assert(offsetof(BxvmConfig, struct_size) == 4);
|
||||
static_assert(offsetof(BxvmConfig, version) == 8);
|
||||
static_assert(offsetof(BxvmConfig, flags) == 12);
|
||||
static_assert(offsetof(BxvmConfig, base_va) == 16);
|
||||
static_assert(offsetof(BxvmConfig, size_bytes) == 24);
|
||||
static_assert(offsetof(BxvmConfig, reserved) == 32);
|
||||
static_assert(offsetof(BxvmConfig, cpu_pointer) == 40);
|
||||
static_assert(sizeof(XboxConfig) == 32);
|
||||
static_assert(offsetof(XboxConfig, flags) == 0);
|
||||
static_assert(offsetof(XboxConfig, page_table_4mb_pages) == 4);
|
||||
static_assert(offsetof(XboxConfig, frame_buffer_preserve_bytes) == 8);
|
||||
static_assert(offsetof(XboxConfig, padding) == 12);
|
||||
static_assert(offsetof(XboxConfig, min_gpu_va) == 16);
|
||||
static_assert(offsetof(XboxConfig, max_gpu_va) == 24);
|
||||
|
||||
/* From the documentation: 2 GB minimum, about 159.375 GB maximum at the default size. */
|
||||
constexpr uint64_t kMinGpuVa = 0x80000000ull;
|
||||
constexpr uint64_t kDefaultMaxGpuVa = 0x27D8000000ull;
|
||||
constexpr uint64_t kOutputSentinel = 0xA5A5A5A5A5A5A5A5ull;
|
||||
|
||||
int g_failed = 0;
|
||||
|
||||
void check(bool cond, const char* fmt, ...) {
|
||||
if (cond) {
|
||||
return;
|
||||
}
|
||||
++g_failed;
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
std::fprintf(stderr, "FAIL: ");
|
||||
std::vfprintf(stderr, fmt, args);
|
||||
std::fprintf(stderr, "\n");
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
unsigned long ul(HRESULT hr) {
|
||||
return static_cast<unsigned long>(hr);
|
||||
}
|
||||
|
||||
bool read_file_from(const char* path, long start, std::string& out) {
|
||||
out.clear();
|
||||
FILE* f = std::fopen(path, "rb");
|
||||
if (!f) {
|
||||
return false;
|
||||
}
|
||||
if (start > 0 && std::fseek(f, start, SEEK_SET) != 0) {
|
||||
std::fclose(f);
|
||||
return false;
|
||||
}
|
||||
char buf[4096];
|
||||
size_t n = 0;
|
||||
while ((n = std::fread(buf, 1, sizeof(buf), f)) > 0) {
|
||||
out.append(buf, n);
|
||||
}
|
||||
std::fclose(f);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Current size of the log, used as the start offset of the next step. */
|
||||
long log_size(const char* path) {
|
||||
FILE* f = std::fopen(path, "rb");
|
||||
if (!f) {
|
||||
return 0;
|
||||
}
|
||||
long size = 0;
|
||||
if (std::fseek(f, 0, SEEK_END) == 0) {
|
||||
size = std::ftell(f);
|
||||
}
|
||||
std::fclose(f);
|
||||
return size < 0 ? 0 : size;
|
||||
}
|
||||
|
||||
bool log_contains_since(const char* path, long start, const char* needle) {
|
||||
std::string text;
|
||||
return read_file_from(path, start, text) && text.find(needle) != std::string::npos;
|
||||
}
|
||||
|
||||
constexpr const char* kStubNeedle = "d3d12_xs.dll!D3D12ConfigureVirtualMemoryX";
|
||||
|
||||
BxvmConfig make_bxvm(uint64_t base_va, uint64_t size_bytes, uint32_t flags) {
|
||||
BxvmConfig cfg{};
|
||||
cfg.magic = kBxvmMagic;
|
||||
cfg.struct_size = sizeof(BxvmConfig);
|
||||
cfg.version = 1;
|
||||
cfg.flags = flags;
|
||||
cfg.base_va = base_va;
|
||||
cfg.size_bytes = size_bytes;
|
||||
cfg.reserved = 0;
|
||||
cfg.cpu_pointer = 0xA5A5A5A5A5A5A5A5ull;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
XboxConfig make_xbox(uint32_t pages, uint32_t preserve = 0) {
|
||||
XboxConfig cfg{};
|
||||
cfg.page_table_4mb_pages = pages;
|
||||
cfg.frame_buffer_preserve_bytes = preserve;
|
||||
cfg.min_gpu_va = kOutputSentinel;
|
||||
cfg.max_gpu_va = kOutputSentinel;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/* The caller's input fields, which the decoder must not change. */
|
||||
bool inputs_unchanged(const XboxConfig& after, const XboxConfig& before) {
|
||||
return after.flags == before.flags && after.page_table_4mb_pages == before.page_table_4mb_pages &&
|
||||
after.frame_buffer_preserve_bytes == before.frame_buffer_preserve_bytes &&
|
||||
after.padding == before.padding;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
const bx_runtime_config_t* cfg = bx_get_runtime_config();
|
||||
if (!cfg) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_vmem_xbox (no runtime config)\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
char log_path[MAX_PATH] = {};
|
||||
const 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(have_log, "BX_LOG_FILE must be set");
|
||||
|
||||
long mark = have_log ? log_size(log_path) : 0;
|
||||
const long test_start = mark;
|
||||
|
||||
/* 1. The default configuration reports the documented address range. */
|
||||
XboxConfig def = make_xbox(5);
|
||||
const XboxConfig def_before = def;
|
||||
HRESULT hr = D3D12ConfigureVirtualMemoryX(&def);
|
||||
check(hr == S_OK, "default Xbox config must return S_OK (hr=0x%08lx)", ul(hr));
|
||||
check(inputs_unchanged(def, def_before), "Xbox decoder must not change the input fields");
|
||||
check(def.min_gpu_va == kMinGpuVa, "minimum graphics address must be 2 GiB (got 0x%llx)",
|
||||
static_cast<unsigned long long>(def.min_gpu_va));
|
||||
check(def.max_gpu_va == kDefaultMaxGpuVa, "default maximum graphics address must be 159.375 GiB (got 0x%llx)",
|
||||
static_cast<unsigned long long>(def.max_gpu_va));
|
||||
if (have_log) {
|
||||
check(log_contains_since(log_path, mark,
|
||||
"decoder=xbox applied=0 recorded_only=1 page_table_4mb_pages=5 clamped=0 "
|
||||
"frame_buffer_preserve_bytes=0 min_gpu_va=0x80000000 max_gpu_va=0x27d8000000 "
|
||||
"max_estimated=0 repeat=0"),
|
||||
"log must record the default Xbox config as recorded only");
|
||||
check(log_contains_since(log_path, mark, kStubNeedle),
|
||||
"a recorded-only Xbox config must still emit the unimplemented-API stub");
|
||||
check(!log_contains_since(log_path, mark, "applied=1"),
|
||||
"a recorded-only Xbox config must not report applied=1");
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
|
||||
/* 2. Repeated identical call (repeat=1). */
|
||||
hr = D3D12ConfigureVirtualMemoryX(&def);
|
||||
check(hr == S_OK, "repeated identical Xbox config must return S_OK (hr=0x%08lx)", ul(hr));
|
||||
if (have_log) {
|
||||
check(log_contains_since(log_path, mark, "page_table_4mb_pages=5 clamped=0") &&
|
||||
log_contains_since(log_path, mark, "repeat=1"),
|
||||
"repeated identical Xbox config must log repeat=1");
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
|
||||
/* 3. The page-table sizes observed at title startup, 4 and 3: the maximum is estimated. */
|
||||
for (uint32_t pages : {4u, 3u}) {
|
||||
XboxConfig cfg = make_xbox(pages);
|
||||
const XboxConfig before = cfg;
|
||||
hr = D3D12ConfigureVirtualMemoryX(&cfg);
|
||||
check(hr == S_OK, "Xbox config with %u pages must return S_OK (hr=0x%08lx)", pages, ul(hr));
|
||||
check(inputs_unchanged(cfg, before), "%u-page config input fields must stay unchanged", pages);
|
||||
check(cfg.min_gpu_va == kMinGpuVa, "%u-page config minimum must be 2 GiB", pages);
|
||||
check(cfg.max_gpu_va == kDefaultMaxGpuVa / 5u * pages, "%u-page config maximum must scale from the default",
|
||||
pages);
|
||||
if (have_log) {
|
||||
char needle[96];
|
||||
std::snprintf(needle, sizeof(needle), "page_table_4mb_pages=%u clamped=0", pages);
|
||||
check(log_contains_since(log_path, mark, needle) &&
|
||||
log_contains_since(log_path, mark, "max_estimated=1 repeat=0"),
|
||||
"%u-page config must log its size, max_estimated=1 and repeat=0", pages);
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
}
|
||||
|
||||
/* 4. Documented clamps: page table to 33, frame-buffer preserve to 64 MiB; -1 is the legacy size. */
|
||||
XboxConfig big = make_xbox(100u, 128u * 1024u * 1024u);
|
||||
hr = D3D12ConfigureVirtualMemoryX(&big);
|
||||
check(hr == S_OK, "oversized Xbox config must be clamped, not refused (hr=0x%08lx)", ul(hr));
|
||||
check(big.page_table_4mb_pages == 100u, "clamping must not rewrite the caller's page count");
|
||||
check(big.max_gpu_va == kDefaultMaxGpuVa / 5u * 33u, "clamped maximum must use 33 pages");
|
||||
if (have_log) {
|
||||
check(log_contains_since(log_path, mark,
|
||||
"page_table_4mb_pages=33 clamped=1 frame_buffer_preserve_bytes=67108864"),
|
||||
"oversized config must log the clamped page count and preserve size");
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
XboxConfig legacy = make_xbox(5u, 0xFFFFFFFFu);
|
||||
hr = D3D12ConfigureVirtualMemoryX(&legacy);
|
||||
check(hr == S_OK, "legacy frame-buffer preserve size must be accepted (hr=0x%08lx)", ul(hr));
|
||||
if (have_log) {
|
||||
check(log_contains_since(log_path, mark, "frame_buffer_preserve_bytes=4294967295"),
|
||||
"the legacy preserve size (-1) must be recorded as given");
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
|
||||
/* 5. Refused configurations write nothing. */
|
||||
XboxConfig zero = make_xbox(0);
|
||||
const XboxConfig zero_before = zero;
|
||||
hr = D3D12ConfigureVirtualMemoryX(&zero);
|
||||
check(hr == E_INVALIDARG, "a page-table size of 0 must fail with E_INVALIDARG (hr=0x%08lx)", ul(hr));
|
||||
check(std::memcmp(&zero, &zero_before, sizeof(zero)) == 0, "a refused config must not be written");
|
||||
|
||||
SYSTEM_INFO ro_sys{};
|
||||
GetSystemInfo(&ro_sys);
|
||||
const SIZE_T ro_bytes = ro_sys.dwPageSize ? ro_sys.dwPageSize : 4096;
|
||||
void* ro_page = VirtualAlloc(nullptr, ro_bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
check(ro_page != nullptr, "VirtualAlloc for the read-only Xbox probe must succeed");
|
||||
if (ro_page) {
|
||||
const XboxConfig ro_cfg = make_xbox(5);
|
||||
std::memcpy(ro_page, &ro_cfg, sizeof(ro_cfg));
|
||||
DWORD old_protect = 0;
|
||||
if (VirtualProtect(ro_page, ro_bytes, PAGE_READONLY, &old_protect)) {
|
||||
hr = D3D12ConfigureVirtualMemoryX(ro_page);
|
||||
check(hr == E_INVALIDARG, "read-only Xbox outputs must fail with E_INVALIDARG (hr=0x%08lx)", ul(hr));
|
||||
check(std::memcmp(ro_page, &ro_cfg, sizeof(ro_cfg)) == 0, "read-only Xbox config must stay unchanged");
|
||||
DWORD ignored = 0;
|
||||
VirtualProtect(ro_page, ro_bytes, old_protect, &ignored);
|
||||
} else {
|
||||
check(false, "Xbox config page must become read-only");
|
||||
}
|
||||
VirtualFree(ro_page, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
void* edge_mem = VirtualAlloc(nullptr, ro_bytes * 2, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
check(edge_mem != nullptr, "VirtualAlloc for the Xbox page-edge probe must succeed");
|
||||
if (edge_mem) {
|
||||
auto* edge_base = static_cast<uint8_t*>(edge_mem);
|
||||
DWORD old_prot = 0;
|
||||
check(VirtualProtect(edge_base + ro_bytes, ro_bytes, PAGE_NOACCESS, &old_prot) != 0,
|
||||
"second page must be PAGE_NOACCESS");
|
||||
uint8_t* edge = edge_base + ro_bytes - 8;
|
||||
const uint32_t header[2] = {0u, 5u};
|
||||
std::memcpy(edge, header, sizeof(header));
|
||||
hr = D3D12ConfigureVirtualMemoryX(edge);
|
||||
check(hr == E_INVALIDARG, "an Xbox config cut off by an unreadable page must fail (hr=0x%08lx)", ul(hr));
|
||||
VirtualProtect(edge_base + ro_bytes, ro_bytes, PAGE_READWRITE, &old_prot);
|
||||
VirtualFree(edge_mem, 0, MEM_RELEASE);
|
||||
}
|
||||
if (have_log) {
|
||||
for (const char* needle : {"decoder=xbox applied=0 reason=zero_page_table_pages hr=0x80070057",
|
||||
"decoder=xbox applied=0 reason=unwritable_output hr=0x80070057",
|
||||
"decoder=xbox applied=0 reason=unreadable_config hr=0x80070057"}) {
|
||||
check(log_contains_since(log_path, mark, needle), "missing refused-config log: %s", needle);
|
||||
}
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
|
||||
/*
|
||||
* 4. Verify XMemVirtualAlloc reservation works after Xbox configuration
|
||||
* (matching the caller's MEM_RESERVE + console high-bit pattern).
|
||||
*/
|
||||
PVOID reserved_va = XMemVirtualAlloc(nullptr, 2ull * 1024ull * 1024ull, 0x20402000u, 0x21u, PAGE_READWRITE);
|
||||
check(reserved_va != nullptr, "XMemVirtualAlloc reservation after Xbox config must succeed");
|
||||
if (reserved_va) {
|
||||
check(VirtualFree(reserved_va, 0, MEM_RELEASE) != 0, "release the XMemVirtualAlloc reservation");
|
||||
}
|
||||
|
||||
/*
|
||||
* 5. Configure a BXVM backing heap, create and cache it, then apply an Xbox
|
||||
* configuration. The Xbox path does not apply a backing configuration, so the
|
||||
* cached BXVM backing heap, its cpu_pointer and its device link must
|
||||
* survive.
|
||||
*/
|
||||
ID3D12Device* device = nullptr;
|
||||
hr = D3D12XboxCreateDevice(nullptr, kPcLayoutParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
check(hr == S_OK && device != nullptr, "D3D12XboxCreateDevice must succeed (hr=0x%08lx)", ul(hr));
|
||||
|
||||
SIZE_T page_count = 2;
|
||||
ULONG_PTR pages[2] = {};
|
||||
const BOOL phys_ok = XMemAllocatePhysicalPages(0, &page_count, pages);
|
||||
check(phys_ok && page_count == 2, "XMemAllocatePhysicalPages(2) must succeed");
|
||||
uint8_t* mapped_region = phys_ok ? static_cast<uint8_t*>(XMemMapPhysicalPages(nullptr, 2, pages)) : nullptr;
|
||||
check(mapped_region != nullptr, "XMemMapPhysicalPages(2) must succeed");
|
||||
|
||||
if (device && mapped_region) {
|
||||
const uint64_t region_va = reinterpret_cast<uint64_t>(mapped_region);
|
||||
const uint64_t region_bytes = 2ull * k64K;
|
||||
|
||||
BxvmConfig bxvm = make_bxvm(region_va, region_bytes, kBxvmFlagBacking);
|
||||
hr = D3D12ConfigureVirtualMemoryX(&bxvm);
|
||||
check(hr == S_OK, "BXVM backing config must succeed (hr=0x%08lx)", ul(hr));
|
||||
check(bxvm.cpu_pointer == 0, "BXVM cpu_pointer must start at 0 before CreateHeap");
|
||||
|
||||
D3D12_HEAP_DESC backing_desc{};
|
||||
backing_desc.SizeInBytes = region_bytes;
|
||||
backing_desc.Alignment = k64K;
|
||||
backing_desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM;
|
||||
backing_desc.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
|
||||
backing_desc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
backing_desc.Flags = D3D12_HEAP_FLAG_NONE;
|
||||
|
||||
ID3D12Heap* backing_heap = nullptr;
|
||||
hr = device->CreateHeap(&backing_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&backing_heap));
|
||||
check(hr == S_OK && backing_heap != nullptr, "CreateHeap for BXVM backing must succeed (hr=0x%08lx)", ul(hr));
|
||||
|
||||
BxvmConfig query = make_bxvm(region_va, region_bytes, kBxvmFlagBacking);
|
||||
hr = D3D12ConfigureVirtualMemoryX(&query);
|
||||
check(hr == S_OK && query.cpu_pointer != 0,
|
||||
"BXVM query after CreateHeap must return non-zero cached cpu_pointer (hr=0x%08lx)", ul(hr));
|
||||
|
||||
/* Once a device exists the Xbox call fails, writes nothing and leaves the cached heap alone. */
|
||||
XboxConfig switch_cfg = make_xbox(4);
|
||||
const XboxConfig switch_before = switch_cfg;
|
||||
const long switch_mark = have_log ? log_size(log_path) : 0;
|
||||
hr = D3D12ConfigureVirtualMemoryX(&switch_cfg);
|
||||
check(hr == E_FAIL, "Xbox config after device creation must fail with E_FAIL (hr=0x%08lx)", ul(hr));
|
||||
check(std::memcmp(&switch_cfg, &switch_before, sizeof(switch_cfg)) == 0,
|
||||
"Xbox config refused after device creation must not be written");
|
||||
if (have_log) {
|
||||
check(log_contains_since(log_path, switch_mark,
|
||||
"decoder=xbox applied=0 reason=device_already_created hr=0x80004005"),
|
||||
"Xbox config after device creation must log device_already_created");
|
||||
}
|
||||
|
||||
if (backing_heap) {
|
||||
ID3D12Device* still_dev = nullptr;
|
||||
const HRESULT dev_hr = backing_heap->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&still_dev));
|
||||
check(SUCCEEDED(dev_hr) && still_dev != nullptr,
|
||||
"cached BXVM backing heap must keep its device after an Xbox config (hr=0x%08lx)", ul(dev_hr));
|
||||
if (still_dev) {
|
||||
still_dev->Release();
|
||||
}
|
||||
}
|
||||
|
||||
BxvmConfig after_xbox = make_bxvm(region_va, region_bytes, kBxvmFlagBacking);
|
||||
hr = D3D12ConfigureVirtualMemoryX(&after_xbox);
|
||||
check(hr == S_OK && after_xbox.cpu_pointer == query.cpu_pointer,
|
||||
"BXVM cpu_pointer must be unchanged after an Xbox config (hr=0x%08lx)", ul(hr));
|
||||
|
||||
if (backing_heap) {
|
||||
backing_heap->Release();
|
||||
backing_heap = nullptr;
|
||||
}
|
||||
|
||||
/* Ordinary D3D12 heap creation still works after the refused Xbox call. */
|
||||
D3D12_HEAP_DESC ordinary_desc{};
|
||||
ordinary_desc.SizeInBytes = k64K;
|
||||
ordinary_desc.Alignment = k64K;
|
||||
ordinary_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
ordinary_desc.Flags = D3D12_HEAP_FLAG_NONE;
|
||||
ID3D12Heap* ordinary_heap = nullptr;
|
||||
hr = device->CreateHeap(&ordinary_desc, __uuidof(ID3D12Heap), reinterpret_cast<void**>(&ordinary_heap));
|
||||
check(hr == S_OK && ordinary_heap != nullptr,
|
||||
"ordinary CreateHeap must succeed after a refused Xbox config (hr=0x%08lx)", ul(hr));
|
||||
if (ordinary_heap) {
|
||||
ordinary_heap->Release();
|
||||
}
|
||||
}
|
||||
|
||||
if (mapped_region) {
|
||||
XMemMapPhysicalPages(mapped_region, 2, nullptr);
|
||||
}
|
||||
if (phys_ok) {
|
||||
XMemFreePhysicalPages(2, pages);
|
||||
}
|
||||
if (device) {
|
||||
device->Release();
|
||||
}
|
||||
|
||||
/* 6. Malformed and page-edge unreadable inputs to the shared entry point. */
|
||||
if (have_log) {
|
||||
mark = log_size(log_path);
|
||||
}
|
||||
check(D3D12ConfigureVirtualMemoryX(nullptr) == S_OK, "null config must fall back with S_OK");
|
||||
|
||||
uint32_t unknown_hdr[8] = {0x11223344u, 4u, 0u, 0u, 0u, 0u, 0u, 0u};
|
||||
uint32_t unknown_hdr_before[8];
|
||||
std::memcpy(unknown_hdr_before, unknown_hdr, sizeof(unknown_hdr));
|
||||
check(D3D12ConfigureVirtualMemoryX(unknown_hdr) == S_OK, "unrecognized header must fall back with S_OK");
|
||||
check(std::memcmp(unknown_hdr, unknown_hdr_before, sizeof(unknown_hdr)) == 0,
|
||||
"unrecognized header bytes must stay unchanged");
|
||||
|
||||
BxvmConfig readonly_bxvm = make_bxvm(0, 0, 0);
|
||||
SYSTEM_INFO readonly_sys{};
|
||||
GetSystemInfo(&readonly_sys);
|
||||
const SIZE_T readonly_page_bytes = readonly_sys.dwPageSize ? readonly_sys.dwPageSize : 4096;
|
||||
void* readonly_page =
|
||||
VirtualAlloc(nullptr, readonly_page_bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
check(readonly_page != nullptr, "VirtualAlloc for read-only BXVM probe must succeed");
|
||||
if (readonly_page) {
|
||||
std::memcpy(readonly_page, &readonly_bxvm, sizeof(readonly_bxvm));
|
||||
DWORD old_protect = 0;
|
||||
const bool protected_readonly =
|
||||
VirtualProtect(readonly_page, readonly_page_bytes, PAGE_READONLY, &old_protect) != 0;
|
||||
check(protected_readonly, "BXVM config page must become read-only");
|
||||
if (protected_readonly) {
|
||||
check(D3D12ConfigureVirtualMemoryX(readonly_page) == S_OK,
|
||||
"read-only BXVM output must fall back with S_OK");
|
||||
check(std::memcmp(readonly_page, &readonly_bxvm, sizeof(readonly_bxvm)) == 0,
|
||||
"read-only BXVM config bytes must stay unchanged");
|
||||
DWORD ignored_protect = 0;
|
||||
const bool writable =
|
||||
VirtualProtect(readonly_page, readonly_page_bytes, old_protect, &ignored_protect) != 0;
|
||||
check(writable, "make the BXVM page writable for the invalid-size case");
|
||||
if (writable) {
|
||||
const BxvmConfig invalid_bxvm = make_bxvm(0, 1, 0);
|
||||
std::memcpy(readonly_page, &invalid_bxvm, sizeof(invalid_bxvm));
|
||||
const bool readonly_again =
|
||||
VirtualProtect(readonly_page, readonly_page_bytes, PAGE_READONLY, &ignored_protect) != 0;
|
||||
check(readonly_again, "protect the invalid-size BXVM page");
|
||||
if (readonly_again) {
|
||||
check(D3D12ConfigureVirtualMemoryX(readonly_page) == E_INVALIDARG,
|
||||
"invalid BXVM size must be rejected before the read-only fallback");
|
||||
check(std::memcmp(readonly_page, &invalid_bxvm, sizeof(invalid_bxvm)) == 0,
|
||||
"rejected BXVM config bytes must stay unchanged");
|
||||
}
|
||||
}
|
||||
}
|
||||
VirtualFree(readonly_page, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
SYSTEM_INFO sys{};
|
||||
GetSystemInfo(&sys);
|
||||
const SIZE_T page_bytes = sys.dwPageSize ? sys.dwPageSize : 4096;
|
||||
void* guard_mem = VirtualAlloc(nullptr, page_bytes * 2, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
check(guard_mem != nullptr, "VirtualAlloc for page-edge probe must succeed");
|
||||
if (guard_mem) {
|
||||
DWORD old_prot = 0;
|
||||
auto* base = static_cast<uint8_t*>(guard_mem);
|
||||
check(VirtualProtect(base + page_bytes, page_bytes, PAGE_NOACCESS, &old_prot) != 0,
|
||||
"second page must be PAGE_NOACCESS");
|
||||
|
||||
/* Unreadable header directly on NOACCESS page. */
|
||||
check(D3D12ConfigureVirtualMemoryX(base + page_bytes) == S_OK,
|
||||
"unreadable header must not fault and must return S_OK");
|
||||
|
||||
VirtualProtect(base + page_bytes, page_bytes, PAGE_READWRITE, &old_prot);
|
||||
VirtualFree(guard_mem, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
if (have_log) {
|
||||
constexpr const char* expected_fallbacks[] = {
|
||||
"\"event\":\"vmem_config_fallback\",\"detail\":\"decoder=none applied=0 reason=null_config\"",
|
||||
"\"event\":\"vmem_config_fallback\",\"detail\":\"decoder=none applied=0 reason=unrecognized_header\"",
|
||||
"\"event\":\"vmem_config_fallback\",\"detail\":\"decoder=none applied=0 reason=unreadable_header\"",
|
||||
"\"event\":\"vmem_config_fallback\",\"detail\":\"decoder=bxvm applied=0 reason=unwritable_output\"",
|
||||
};
|
||||
for (const char* needle : expected_fallbacks) {
|
||||
check(log_contains_since(log_path, mark, needle), "missing expected fallback log: %s", needle);
|
||||
}
|
||||
check(log_contains_since(log_path, test_start, "\"event\":\"vmem_config_recorded\""),
|
||||
"the Xbox path must log vmem_config_recorded");
|
||||
}
|
||||
|
||||
if (g_failed != 0) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_vmem_xbox (%d failed)\n", g_failed);
|
||||
return 1;
|
||||
}
|
||||
std::printf("PASS: test_d3d12_vmem_xbox\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_d3d12_xbox_layout main.cpp)
|
||||
target_compile_definitions(test_d3d12_xbox_layout PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_xbox_layout PRIVATE d3d12_xs xmem kernel32 uuid)
|
||||
@@ -0,0 +1,414 @@
|
||||
/*
|
||||
* ADR 0009: d3d12_xs.dll hands a title an Xbox-layout device, and the objects it creates are
|
||||
* Xbox-layout too. This program calls them the way a title built against the Xbox Series D3D12
|
||||
* header does: through the object's function table, by slot number.
|
||||
*
|
||||
* The slot numbers and object offsets below were written out by hand from that header (used
|
||||
* under Microsoft's authorization). They are not taken from the shim's generated tables.
|
||||
* Expected results come from a second device created in the PC layout (Version 0) and called
|
||||
* through <d3d12.h>, not from the Xbox objects.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
extern "C" __declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t flags, PULONG_PTR count, PULONG_PTR pages);
|
||||
extern "C" __declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR pages);
|
||||
extern "C" __declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID address, ULONG_PTR count, PULONG_PTR pages);
|
||||
extern "C" __declspec(dllimport) PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD type, uint64_t flags,
|
||||
DWORD protect);
|
||||
|
||||
namespace {
|
||||
|
||||
// Xbox function-table slots (Series header).
|
||||
constexpr int kQueryInterface = 0, kAddRef = 1, kRelease = 2;
|
||||
constexpr int kDevGetNodeCount = 7, kDevCheckFeatureSupport = 13, kDevGetResourceAllocationInfo = 25;
|
||||
constexpr int kDevCreateHeap = 28, kDevCreatePlacedResource = 29, kDevGetAdapterLuid = 43;
|
||||
constexpr int kDevCreateComponentPlacedResourceX = 45; // an Xbox-only slot still stubbed
|
||||
constexpr int kDevCreateCommittedResource1 = 92; // ID3D12Device4; PC places it elsewhere
|
||||
constexpr int kResMap = 8, kResGetDesc = 10, kResGetGpuVirtualAddress = 11;
|
||||
// Object offsets (Series header): m_RefCount at +12; ID3D12Device's m_OutOfLineFlags at +24.
|
||||
constexpr size_t kRefCountOffset = 12, kOutOfLineOffset = 24;
|
||||
|
||||
const IID kIidDevice11 = {0x5405c344, 0xd457, 0x444e, {0xb4, 0xdd, 0x23, 0x66, 0xe4, 0x5a, 0xee, 0x39}};
|
||||
|
||||
int g_failed = 0;
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_xbox_layout:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
|
||||
using QueryInterfaceFn = HRESULT(STDMETHODCALLTYPE*)(void*, REFIID, void**);
|
||||
using RefFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using GetNodeCountFn = UINT(STDMETHODCALLTYPE*)(void*);
|
||||
using CheckFeatureSupportFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_FEATURE, void*, UINT);
|
||||
using GetAllocationInfoFn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT,
|
||||
const D3D12_RESOURCE_DESC*);
|
||||
using GetAdapterLuidFn = LUID(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_DESC*, REFIID, void**);
|
||||
using CreatePlacedFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64, const D3D12_RESOURCE_DESC*,
|
||||
D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
using StubFn = HRESULT(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateCommitted1Fn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, void*, REFIID, void**);
|
||||
using MapFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*, void**);
|
||||
using GetDescFn = void(STDMETHODCALLTYPE*)(void*, D3D12_RESOURCE_DESC*);
|
||||
using GetGpuVaFn = D3D12_GPU_VIRTUAL_ADDRESS(STDMETHODCALLTYPE*)(void*);
|
||||
|
||||
D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) {
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
desc.Width = bytes;
|
||||
desc.Height = 1;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
return desc;
|
||||
}
|
||||
|
||||
std::string read_log() {
|
||||
char path[MAX_PATH];
|
||||
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
if (n == 0 || n >= sizeof(path)) return {};
|
||||
std::string text;
|
||||
if (FILE* f = std::fopen(path, "rb")) {
|
||||
char buffer[4096];
|
||||
size_t got;
|
||||
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
|
||||
std::fclose(f);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
// A title sets Version (the GDK documentation asks for D3D12_SDK_VERSION); a zeroed block is
|
||||
// BetterXen's synthetic PC-layout client.
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004;
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
alignas(8) static const unsigned char pc_params[80] = {};
|
||||
|
||||
ID3D12Device* pc = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, pc_params, __uuidof(ID3D12Device), reinterpret_cast<void**>(&pc));
|
||||
CHECK(hr == S_OK && pc, "PC-layout device hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
void* dev = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
// A host device without the interface the Xbox table forwards to (vkd3d stops at
|
||||
// ID3D12Device9) must refuse the Xbox-layout device rather than return the PC one.
|
||||
CHECK(dev == nullptr, "a refused Xbox-layout device clears the out pointer");
|
||||
if (pc) pc->Release();
|
||||
if (g_failed) return 1;
|
||||
std::printf("SKIP: test_d3d12_xbox_layout: this host cannot back an Xbox-layout device; the refusal "
|
||||
"(E_NOINTERFACE, null device) was verified, the layout checks need the D3DMetal backend\n");
|
||||
return 77;
|
||||
}
|
||||
CHECK(hr == S_OK && dev, "Xbox-layout device hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!dev || !pc) return 1;
|
||||
CHECK(*reinterpret_cast<void**>(dev) != *reinterpret_cast<void**>(pc), "Xbox device must not use the PC table");
|
||||
|
||||
// Object layout a title can read.
|
||||
CHECK(*reinterpret_cast<uint32_t*>(static_cast<char*>(dev) + kRefCountOffset) == 1, "m_RefCount starts at 1");
|
||||
CHECK(static_cast<uint8_t*>(dev)[kOutOfLineOffset] != 0, "m_OutOfLineFlags makes inline helpers call out");
|
||||
|
||||
// IUnknown slots; QueryInterface for the interface the title asks for returns the same object.
|
||||
void* dev11 = nullptr;
|
||||
CHECK(slot<QueryInterfaceFn>(dev, kQueryInterface)(dev, kIidDevice11, &dev11) == S_OK && dev11 == dev,
|
||||
"QueryInterface(ID3D12Device11) returns the Xbox device");
|
||||
CHECK(slot<RefFn>(dev, kAddRef)(dev) == 3, "AddRef counts the QueryInterface reference");
|
||||
CHECK(*reinterpret_cast<uint32_t*>(static_cast<char*>(dev) + kRefCountOffset) == 3, "m_RefCount mirrors AddRef");
|
||||
slot<RefFn>(dev, kRelease)(dev);
|
||||
slot<RefFn>(dev, kRelease)(dev);
|
||||
|
||||
// Shared ID3D12Device slots, including the two struct-return conventions.
|
||||
CHECK(slot<GetNodeCountFn>(dev, kDevGetNodeCount)(dev) == pc->GetNodeCount(), "GetNodeCount at slot 7");
|
||||
D3D12_FEATURE_DATA_D3D12_OPTIONS options{};
|
||||
CHECK(slot<CheckFeatureSupportFn>(dev, kDevCheckFeatureSupport)(dev, D3D12_FEATURE_D3D12_OPTIONS, &options,
|
||||
sizeof(options)) == S_OK,
|
||||
"CheckFeatureSupport at slot 13");
|
||||
LUID pc_luid{};
|
||||
pc->GetAdapterLuid(&pc_luid);
|
||||
const LUID luid = slot<GetAdapterLuidFn>(dev, kDevGetAdapterLuid)(dev);
|
||||
CHECK(luid.LowPart == pc_luid.LowPart && luid.HighPart == pc_luid.HighPart,
|
||||
"GetAdapterLuid (8-byte struct, returned in RAX) matches the PC device");
|
||||
const D3D12_RESOURCE_DESC desc = buffer_desc(64 * 1024);
|
||||
D3D12_RESOURCE_ALLOCATION_INFO pc_info{};
|
||||
pc->GetResourceAllocationInfo(&pc_info, 0, 1, &desc);
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO info =
|
||||
slot<GetAllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &desc);
|
||||
CHECK(info.SizeInBytes == pc_info.SizeInBytes && info.Alignment == pc_info.Alignment && info.SizeInBytes >= 65536,
|
||||
"GetResourceAllocationInfo (16-byte struct, hidden pointer) matches the PC device");
|
||||
|
||||
// An Xbox-only slot without an implementation is a logged stub.
|
||||
CHECK(slot<StubFn>(dev, kDevCreateComponentPlacedResourceX)(dev) == E_NOTIMPL, "CreateComponentPlacedResourceX is a stub");
|
||||
|
||||
// A Device4 method at its Xbox slot creates an Xbox-layout resource.
|
||||
D3D12_HEAP_PROPERTIES upload{};
|
||||
upload.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
void* resource = nullptr;
|
||||
hr = slot<CreateCommitted1Fn>(dev, kDevCreateCommittedResource1)(dev, &upload, D3D12_HEAP_FLAG_NONE, &desc,
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
nullptr, __uuidof(ID3D12Resource), &resource);
|
||||
CHECK(hr == S_OK && resource, "CreateCommittedResource1 at slot 92 hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (resource) {
|
||||
D3D12_RESOURCE_DESC got{};
|
||||
slot<GetDescFn>(resource, kResGetDesc)(resource, &got);
|
||||
CHECK(got.Width == desc.Width && got.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER, "resource GetDesc at slot 10");
|
||||
CHECK(slot<GetGpuVaFn>(resource, kResGetGpuVirtualAddress)(resource) != 0, "resource GPU VA at slot 11");
|
||||
void* mapped = nullptr;
|
||||
CHECK(slot<MapFn>(resource, kResMap)(resource, 0, nullptr, &mapped) == S_OK && mapped, "resource Map at slot 8");
|
||||
if (mapped) static_cast<unsigned char*>(mapped)[0] = 0x5a;
|
||||
CHECK(slot<RefFn>(resource, kRelease)(resource) == 0, "resource Release at slot 2");
|
||||
}
|
||||
|
||||
// An Xbox heap passed back into a forwarded call is unwrapped to its host.
|
||||
D3D12_HEAP_DESC heap_desc{};
|
||||
heap_desc.SizeInBytes = 64 * 1024;
|
||||
heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS;
|
||||
void* heap = nullptr;
|
||||
hr = slot<CreateHeapFn>(dev, kDevCreateHeap)(dev, &heap_desc, __uuidof(ID3D12Heap), &heap);
|
||||
CHECK(hr == S_OK && heap, "CreateHeap at slot 28 hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (heap) {
|
||||
void* placed = nullptr;
|
||||
hr = slot<CreatePlacedFn>(dev, kDevCreatePlacedResource)(dev, heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON,
|
||||
nullptr, __uuidof(ID3D12Resource), &placed);
|
||||
CHECK(hr == S_OK && placed, "CreatePlacedResource on an Xbox heap hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (placed) slot<RefFn>(placed, kRelease)(placed);
|
||||
slot<RefFn>(heap, kRelease)(heap);
|
||||
}
|
||||
|
||||
// Command recording through Xbox objects: queue, allocator and list from the Xbox methods, a
|
||||
// copy between two Xbox buffers with a barrier, execution and a fence wait.
|
||||
{
|
||||
struct QueueDescX { D3D12_COMMAND_LIST_TYPE Type; UINT Flags, EngineOrPipeIndex, QueueIndex; };
|
||||
struct ListDescX { D3D12_COMMAND_LIST_TYPE Type; UINT Flags, NodeMask, ResourceBarrierBatchSize; };
|
||||
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
|
||||
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
|
||||
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
|
||||
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
using CreateFenceFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, D3D12_FENCE_FLAGS, REFIID, void**);
|
||||
using GetTypeFn = D3D12_COMMAND_LIST_TYPE(STDMETHODCALLTYPE*)(void*);
|
||||
using CopyBufferFn = void(STDMETHODCALLTYPE*)(void*, void*, UINT64, void*, UINT64, UINT64);
|
||||
using BarrierFn = UINT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RESOURCE_BARRIER*);
|
||||
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
|
||||
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
|
||||
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
|
||||
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
|
||||
constexpr int kDevCreateCommandAllocator = 9, kDevCreateCommittedResource = 27, kDevCreateFence = 36;
|
||||
constexpr int kDevCreateCommandQueueX = 48, kDevCreateCommandListX = 73;
|
||||
constexpr int kListGetType = 8, kListClose = 9, kListCopyBufferRegion = 15, kListResourceBarrier = 26;
|
||||
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
|
||||
constexpr size_t kPutBufferOffset = 16, kPutBufferPointers = 5;
|
||||
|
||||
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
void* queue = nullptr;
|
||||
void* allocator = nullptr;
|
||||
void* list = nullptr;
|
||||
CHECK(slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue) == S_OK,
|
||||
"CreateCommandQueueX at slot 48");
|
||||
CHECK(slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT,
|
||||
__uuidof(ID3D12CommandAllocator), &allocator) == S_OK,
|
||||
"CreateCommandAllocator at slot 9");
|
||||
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
hr = slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr,
|
||||
__uuidof(ID3D12GraphicsCommandList), &list);
|
||||
CHECK(hr == S_OK && list, "CreateCommandListX at slot 73 hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
|
||||
D3D12_HEAP_PROPERTIES readback{};
|
||||
readback.Type = D3D12_HEAP_TYPE_READBACK;
|
||||
void* src = nullptr;
|
||||
void* dst = nullptr;
|
||||
CHECK(slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &upload, D3D12_HEAP_FLAG_NONE, &desc,
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), &src) == S_OK,
|
||||
"upload buffer at slot 27");
|
||||
CHECK(slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &readback, D3D12_HEAP_FLAG_NONE, &desc,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
__uuidof(ID3D12Resource), &dst) == S_OK,
|
||||
"readback buffer at slot 27");
|
||||
void* fence = nullptr;
|
||||
CHECK(slot<CreateFenceFn>(dev, kDevCreateFence)(dev, 0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &fence) == S_OK,
|
||||
"CreateFence at slot 36");
|
||||
|
||||
// A buffer placed at a title-chosen address (CreatePlacedResourceX, slot 44) reports that
|
||||
// address and carries the title memory's contents to the GPU: it replaces `src` below.
|
||||
using CreatePlacedXFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_GPU_VIRTUAL_ADDRESS, const D3D12_RESOURCE_DESC*,
|
||||
D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
constexpr int kDevCreatePlacedResourceXSlot = 44;
|
||||
auto* title_memory = static_cast<unsigned char*>(VirtualAlloc(nullptr, 64 * 1024, MEM_COMMIT | MEM_RESERVE,
|
||||
PAGE_READWRITE));
|
||||
void* placed_x = nullptr;
|
||||
if (title_memory) {
|
||||
std::memset(title_memory, 0xa7, 256);
|
||||
const auto title_va = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(title_memory);
|
||||
hr = slot<CreatePlacedXFn>(dev, kDevCreatePlacedResourceXSlot)(dev, title_va, &desc, D3D12_RESOURCE_STATE_COMMON,
|
||||
nullptr, __uuidof(ID3D12Resource), &placed_x);
|
||||
CHECK(hr == S_OK && placed_x, "CreatePlacedResourceX at slot 44 hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (placed_x) {
|
||||
CHECK(slot<GetGpuVaFn>(placed_x, kResGetGpuVirtualAddress)(placed_x) == title_va,
|
||||
"a resource placed at a title address reports that address");
|
||||
if (src) slot<RefFn>(src, kRelease)(src);
|
||||
src = placed_x;
|
||||
}
|
||||
}
|
||||
|
||||
if (queue && allocator && list && src && dst && fence) {
|
||||
// Zero put-buffer pointers make the title's inline fast paths call through the table.
|
||||
const auto* put = reinterpret_cast<const uint64_t*>(static_cast<char*>(list) + kPutBufferOffset);
|
||||
bool zero = true;
|
||||
for (size_t i = 0; i < kPutBufferPointers; ++i) zero = zero && put[i] == 0;
|
||||
CHECK(zero, "command-list put-buffer pointers are zero");
|
||||
// The Xbox command list is 1384 bytes and header-inline code writes its fields, up to
|
||||
// the last one (authorized GDK documentation). Every field after the 16-byte base is
|
||||
// title-owned: overwriting all of them (with zeros, which the put-buffer pointers must
|
||||
// hold anyway) must not disturb BetterXen's state, so the list must still record,
|
||||
// close and execute below.
|
||||
constexpr size_t kXboxCommandListBytes = 1384, kXboxBaseBytes = 16;
|
||||
std::memset(static_cast<char*>(list) + kXboxBaseBytes, 0, kXboxCommandListBytes - kXboxBaseBytes);
|
||||
CHECK(slot<GetTypeFn>(list, kListGetType)(list) == D3D12_COMMAND_LIST_TYPE_DIRECT, "list GetType at slot 8");
|
||||
|
||||
if (!placed_x) {
|
||||
void* mapped = nullptr;
|
||||
CHECK(slot<MapFn>(src, kResMap)(src, 0, nullptr, &mapped) == S_OK && mapped, "upload Map");
|
||||
if (mapped) std::memset(mapped, 0xa7, 256);
|
||||
}
|
||||
D3D12_RESOURCE_BARRIER uav{};
|
||||
uav.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
|
||||
uav.UAV.pResource = static_cast<ID3D12Resource*>(src); // an Xbox object, unwrapped by the shim
|
||||
CHECK(slot<BarrierFn>(list, kListResourceBarrier)(list, 1, &uav) == 0, "ResourceBarrier at slot 26 returns 0");
|
||||
slot<CopyBufferFn>(list, kListCopyBufferRegion)(list, dst, 0, src, 0, 256);
|
||||
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close at slot 9");
|
||||
void* lists[] = {list};
|
||||
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, lists);
|
||||
CHECK(slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, 1) == S_OK, "queue Signal at slot 16");
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
CHECK(slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, 1, done) == S_OK, "fence event at slot 9");
|
||||
CHECK(WaitForSingleObject(done, 5000) == WAIT_OBJECT_0, "GPU work completes");
|
||||
CloseHandle(done);
|
||||
void* result = nullptr;
|
||||
CHECK(slot<MapFn>(dst, kResMap)(dst, 0, nullptr, &result) == S_OK && result, "readback Map");
|
||||
CHECK(result && static_cast<unsigned char*>(result)[0] == 0xa7 && static_cast<unsigned char*>(result)[255] == 0xa7,
|
||||
"the copy recorded through Xbox objects reached the readback buffer (source: the title-address shadow)");
|
||||
}
|
||||
for (void* object : {fence, dst, src, list, allocator, queue}) {
|
||||
if (object) slot<RefFn>(object, kRelease)(object);
|
||||
}
|
||||
if (title_memory) VirtualFree(title_memory, 0, MEM_RELEASE);
|
||||
}
|
||||
|
||||
// Console GPU page mappings (authorized GDK documentation): CopyPageMappingsX (queue slot 29),
|
||||
// ClearPageMappingsX (30); D3D12XBOX_PAGE_MAPPING_RANGE {RangeType, StartPageIndexInPool,
|
||||
// PageCount}, range types 0 incrementing, 1 constant, 2 null, 3 skip; 64 KiB pages. GPU
|
||||
// addresses are CPU addresses in BetterXen, so the result is visible through the CPU view.
|
||||
{
|
||||
struct Range {
|
||||
UINT type, start, count;
|
||||
};
|
||||
static_assert(sizeof(Range) == 12, "D3D12XBOX_PAGE_MAPPING_RANGE");
|
||||
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const void*, REFIID, void**);
|
||||
using CopyMappingsFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_GPU_VIRTUAL_ADDRESS, UINT, const Range*,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS, UINT, UINT);
|
||||
using ClearMappingsFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_GPU_VIRTUAL_ADDRESS, UINT, UINT);
|
||||
constexpr int kDevCreateCommandQueueX = 48, kQueueCopyPageMappingsX = 29, kQueueClearPageMappingsX = 30;
|
||||
constexpr size_t kPage = 64 * 1024;
|
||||
const UINT qdesc[4] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
void* queue = nullptr;
|
||||
CHECK(slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, qdesc, __uuidof(ID3D12CommandQueue), &queue) == S_OK,
|
||||
"page-mapping queue");
|
||||
ULONG_PTR pool_pages[2] = {};
|
||||
ULONG_PTR two = 2;
|
||||
CHECK(XMemAllocatePhysicalPages(0, &two, pool_pages), "physical pages for the pool");
|
||||
auto* pool = static_cast<unsigned char*>(XMemMapPhysicalPages(nullptr, 2, pool_pages));
|
||||
// The destination is a GPU-only reservation with 64 KB pages (MEM_RESERVE | MEM_64K_PAGES,
|
||||
// CPU protection PAGE_NOACCESS with a GPU protection bit), the kind titles fill with page
|
||||
// mappings. BetterXen keeps it CPU-visible, so the mapping can be checked here.
|
||||
constexpr DWORD kMem64kPages = 0x20400000, kGpuOnly = PAGE_NOACCESS | 0x800;
|
||||
auto* dst = static_cast<unsigned char*>(XMemVirtualAlloc(nullptr, 2 * kPage, MEM_RESERVE | kMem64kPages, 0, kGpuOnly));
|
||||
CHECK(dst != nullptr, "GPU-only 64 KB-page reservation");
|
||||
if (queue && pool && dst) {
|
||||
pool[0] = 0x11;
|
||||
pool[kPage] = 0x22;
|
||||
const auto dva = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(dst);
|
||||
const auto pva = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(pool);
|
||||
auto copy = slot<CopyMappingsFn>(queue, kQueueCopyPageMappingsX);
|
||||
const Range constant[] = {{1, 1, 2}}; // both destination pages show pool page 1
|
||||
CHECK(copy(queue, dva, 1, constant, pva, 2, 0) == S_OK, "CopyPageMappingsX constant range");
|
||||
CHECK(dst[0] == 0x22 && dst[kPage] == 0x22, "a constant range maps every page onto one pool page");
|
||||
const Range ranges[] = {{0, 0, 1}, {3, 0, 1}}; // page 0 <- pool page 0, page 1 skipped
|
||||
CHECK(copy(queue, dva, 2, ranges, pva, 2, 0) == S_OK, "CopyPageMappingsX incrementing + skip");
|
||||
CHECK(dst[0] == 0x11 && dst[kPage] == 0x22, "incrementing maps pool page 0; skip leaves page 1 as it was");
|
||||
pool[0] = 0x33;
|
||||
CHECK(dst[0] == 0x33, "the destination shows the pool page, not a copy of it");
|
||||
CHECK(copy(queue, dva, 1, constant, pva, 1, 0) == E_INVALIDARG, "a pool page past PoolPageCount is refused");
|
||||
const Range null_page[] = {{2, 0, 1}};
|
||||
CHECK(copy(queue, dva + kPage, 1, null_page, pva, 2, 0) == S_OK, "CopyPageMappingsX null range");
|
||||
MEMORY_BASIC_INFORMATION mbi{};
|
||||
CHECK(VirtualQuery(dst + kPage, &mbi, sizeof(mbi)) && mbi.State != MEM_COMMIT, "a null range unmaps the page");
|
||||
CHECK(slot<ClearMappingsFn>(queue, kQueueClearPageMappingsX)(queue, dva, 1, 0) == S_OK &&
|
||||
VirtualQuery(dst, &mbi, sizeof(mbi)) && mbi.State != MEM_COMMIT,
|
||||
"ClearPageMappingsX unmaps the page");
|
||||
}
|
||||
if (queue) slot<RefFn>(queue, kRelease)(queue);
|
||||
if (dst) VirtualFree(dst, 0, MEM_RELEASE); // xmem has no XMemVirtualFree; titles use VirtualFree
|
||||
XMemFreePhysicalPages(2, pool_pages);
|
||||
}
|
||||
|
||||
// Frame pacing: an interval, an origin event, and waits that return new frame tokens.
|
||||
{
|
||||
using SetIntervalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT, UINT, UINT);
|
||||
using ScheduleFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, UINT, void*, UINT);
|
||||
using WaitFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, UINT, void*, UINT, UINT64*);
|
||||
constexpr int kDevSetFrameIntervalX = 78, kDevScheduleFrameEventX = 79, kDevWaitFrameEventX = 80;
|
||||
constexpr UINT kOrigin = 0, kVblank = 1;
|
||||
UINT64 token = 0;
|
||||
CHECK(slot<WaitFn>(dev, kDevWaitFrameEventX)(dev, kVblank, 0, nullptr, 0, &token) == E_INVALIDARG,
|
||||
"waiting on an unscheduled event fails");
|
||||
CHECK(slot<ScheduleFn>(dev, kDevScheduleFrameEventX)(dev, kOrigin, 0, nullptr, 0) == E_INVALIDARG,
|
||||
"scheduling before an interval exists fails");
|
||||
CHECK(slot<SetIntervalFn>(dev, kDevSetFrameIntervalX)(dev, nullptr, 16667, 5, 0) == E_INVALIDARG,
|
||||
"a period above 4 is refused");
|
||||
CHECK(slot<SetIntervalFn>(dev, kDevSetFrameIntervalX)(dev, nullptr, 16667, 1, 0) == S_OK, "SetFrameIntervalX at slot 78");
|
||||
CHECK(slot<ScheduleFn>(dev, kDevScheduleFrameEventX)(dev, kOrigin, 0, nullptr, 0) == S_OK, "ScheduleFrameEventX at slot 79");
|
||||
CHECK(slot<WaitFn>(dev, kDevWaitFrameEventX)(dev, kOrigin, 1000, nullptr, 0, &token) == S_OK && token != 0,
|
||||
"WaitFrameEventX at slot 80 returns a frame token");
|
||||
UINT64 next = 0;
|
||||
CHECK(slot<WaitFn>(dev, kDevWaitFrameEventX)(dev, kOrigin, 1000, nullptr, 0, &next) == S_OK && next > token,
|
||||
"the next origin produces a newer token");
|
||||
}
|
||||
|
||||
CHECK(slot<RefFn>(dev, kRelease)(dev) == 0, "device Release at slot 2");
|
||||
pc->Release();
|
||||
|
||||
const std::string log = read_log();
|
||||
if (!log.empty()) {
|
||||
CHECK(log.find("device=xbox_function_tables") != std::string::npos, "log records the Xbox layout");
|
||||
CHECK(log.find("XboxDevice[45]::CreateComponentPlacedResourceX") != std::string::npos, "the stub slot is logged");
|
||||
}
|
||||
if (g_failed) return 1;
|
||||
std::printf("PASS: test_d3d12_xbox_layout\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -23,7 +23,11 @@
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
|
||||
|
||||
/* 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] = {};
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -133,16 +137,22 @@ int main() {
|
||||
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
|
||||
|
||||
/* --- 1. Argument contract ------------------------------------------------------------------ */
|
||||
check(D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), nullptr) == E_POINTER,
|
||||
check(D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), nullptr) == E_POINTER,
|
||||
"D3D12XboxCreateDevice(ppv=null) must return E_POINTER");
|
||||
{
|
||||
void* unset = reinterpret_cast<void*>(0x1);
|
||||
check(D3D12XboxCreateDevice(nullptr, nullptr, __uuidof(ID3D12Device), &unset) == E_INVALIDARG,
|
||||
"D3D12XboxCreateDevice(params=null) must return E_INVALIDARG (documented)");
|
||||
check(unset == nullptr, "D3D12XboxCreateDevice(params=null) must clear the out pointer");
|
||||
}
|
||||
void* bogus = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, kUnusedIid, &bogus);
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, kUnusedIid, &bogus);
|
||||
check(hr == E_NOINTERFACE && bogus == nullptr,
|
||||
"unknown riid must yield E_NOINTERFACE and a null object (hr=0x%08lx obj=%p)", ul(hr), bogus);
|
||||
|
||||
/* --- 2. Device creation and identity ------------------------------------------------------- */
|
||||
ID3D12Device* device = nullptr;
|
||||
hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (!check(hr == S_OK && device, "D3D12XboxCreateDevice hr=0x%08lx device=%p", ul(hr), static_cast<void*>(device))) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_xs (no device; %d of %d checks failed)\n", g_failures, g_checks);
|
||||
return 1;
|
||||
|
||||
@@ -25,7 +25,8 @@
|
||||
*
|
||||
* Function prototypes below mirror the in-tree shim sources and abi/defs; this
|
||||
* fixture deliberately invents no console structure layouts. The xg_xs
|
||||
* descriptor and vtable are BetterXen's own, from shims/xg_xs/xg_texture.h.
|
||||
* descriptor and method order are the documented XG contract recorded in
|
||||
* shims/xg_xs/xg_xbox.cpp (derived facts, no header text).
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
@@ -33,6 +34,7 @@
|
||||
#include <immintrin.h>
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -41,7 +43,6 @@
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xg_texture.h"
|
||||
|
||||
#define BX_IMPORT __declspec(dllimport)
|
||||
|
||||
@@ -54,7 +55,8 @@ BX_IMPORT uint64_t bx_veh_get_clwb_trap_count(void);
|
||||
BX_IMPORT PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes);
|
||||
BX_IMPORT VOID WINAPI XMemFree(PVOID address, uint64_t attributes);
|
||||
BX_IMPORT BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t flags);
|
||||
BX_IMPORT PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWORD protect);
|
||||
BX_IMPORT PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, uint64_t xmem_flags,
|
||||
DWORD protect);
|
||||
BX_IMPORT SIZE_T WINAPI XMemVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buf, SIZE_T len);
|
||||
|
||||
/* xgameruntime.dll */
|
||||
@@ -96,10 +98,31 @@ BX_IMPORT HRESULT WINAPI XDspDisconnect(void* handle);
|
||||
/* GameInput.dll (ordinal 1) */
|
||||
BX_IMPORT HRESULT WINAPI GameInputCreate(void** out_game_input);
|
||||
|
||||
/* xg_xs.dll is declared by "xg_texture.h". */
|
||||
/* xg_xs.dll: the documented XG_RESOURCE_DESC (56 bytes) and XGTextureAddressComputer, whose
|
||||
methods are AddRef, Release, GetResourceLayout, GetResourceSizeBytes,
|
||||
GetResourceBaseAlignmentBytes, GetMipLevelOffsetBytes, ... (no IUnknown QueryInterface). */
|
||||
struct XgResourceDesc {
|
||||
uint32_t Dimension;
|
||||
UINT64 Alignment;
|
||||
UINT64 Width;
|
||||
UINT Height;
|
||||
UINT16 DepthOrArraySize;
|
||||
UINT16 MipLevels;
|
||||
uint32_t Format;
|
||||
UINT SampleCount;
|
||||
UINT SampleQuality;
|
||||
uint32_t Layout;
|
||||
uint32_t MiscFlags;
|
||||
};
|
||||
BX_IMPORT HRESULT WINAPI XGCreateTextureComputer(const XgResourceDesc* desc, void** computer);
|
||||
BX_IMPORT HRESULT WINAPI XGSuggestSwizzleMode(const XgResourceDesc* desc, uint32_t flags, uint32_t* layout);
|
||||
|
||||
/* d3d12_xs.dll (D3D12SerializeVersionedRootSignature is declared by <d3d12.h>) */
|
||||
BX_IMPORT HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
|
||||
BX_IMPORT HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
|
||||
|
||||
/* 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] = {};
|
||||
} // extern "C"
|
||||
|
||||
namespace {
|
||||
@@ -437,7 +460,7 @@ void stage_xmem(const bx_runtime_config_t* cfg) {
|
||||
std::memset(dst, 0, kHeapBytes);
|
||||
bool transfer_ok = XMemTransferMemory(dst, src, kHeapBytes, 0) && std::memcmp(src, dst, kHeapBytes) == 0;
|
||||
|
||||
auto* vmem = static_cast<uint8_t*>(XMemVirtualAlloc(nullptr, kVirtualBytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
|
||||
auto* vmem = static_cast<uint8_t*>(XMemVirtualAlloc(nullptr, kVirtualBytes, MEM_COMMIT | MEM_RESERVE, 0x1 /* XMEM_CPU */, PAGE_READWRITE));
|
||||
bool virtual_ok = false;
|
||||
if (vmem) {
|
||||
vmem[0] = 0xA5;
|
||||
@@ -649,25 +672,34 @@ void stage_acphal_heap() {
|
||||
|
||||
/* ---- Stage 13: xg_xs ---------------------------------------------------------------------- */
|
||||
|
||||
static_assert(sizeof(XgResourceDesc) == 56 && offsetof(XgResourceDesc, Alignment) == 8, "XG_RESOURCE_DESC");
|
||||
constexpr uint32_t kXgTexture2D = 3; // XG_RESOURCE_DIMENSION_TEXTURE2D
|
||||
constexpr uint32_t kXgLayoutSwizzleLinear = 0x100; // XG_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR
|
||||
enum : int { kXgAddRef = 0, kXgRelease = 1, kXgSizeBytes = 3, kXgBaseAlignment = 4, kXgMipOffset = 5 };
|
||||
|
||||
template <typename Fn>
|
||||
Fn xg_slot(void* computer, int slot) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(computer))[slot]);
|
||||
}
|
||||
|
||||
/*
|
||||
* 100x50 R8G8B8A8 with two mips, so both public D3D12 alignments matter. By hand:
|
||||
* mip 0: 100 * 4 = 400 bytes per row, pitch 512 (256-byte pitch alignment);
|
||||
* ends at 49 * 512 + 400 = 25488.
|
||||
* mip 1: starts at the next 512 boundary, 25600; 50 * 4 = 200 bytes per row,
|
||||
* pitch 256; ends at 25600 + 24 * 256 + 200 = 31944.
|
||||
* total: 31944 rounded up to 512 = 32256.
|
||||
* 100x50 R8G8B8A8 with two mips under BetterXen's linear rule (shims/xg_xs/xg_xbox.cpp: rows aligned
|
||||
* to 256 bytes, mips to 512, the resource to 64 KiB). By hand:
|
||||
* mip 0: 100 * 4 = 400 bytes per row, pitch 512; 50 rows = 25600 bytes at offset 0.
|
||||
* mip 1: offset 25600 (already 512-aligned); 50 * 4 = 200 bytes per row, pitch 256;
|
||||
* 25 rows = 6400 bytes, ending at 32000.
|
||||
* resource: 32000 rounded up to 64 KiB = 65536, base alignment 65536.
|
||||
*/
|
||||
void* stage_xg_texture_computer() {
|
||||
begin_stage("xg_xs_texture_computer");
|
||||
bx_xg_resource_desc desc = {};
|
||||
desc.dimension = BX_XG_DIMENSION_TEXTURE2D;
|
||||
desc.width = 100;
|
||||
desc.height = 50;
|
||||
desc.depth_or_array_size = 1;
|
||||
desc.mip_levels = 2;
|
||||
desc.format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.sample_desc.count = 1;
|
||||
desc.layout = BX_XG_LAYOUT_LINEAR;
|
||||
XgResourceDesc desc = {};
|
||||
desc.Dimension = kXgTexture2D;
|
||||
desc.Width = 100;
|
||||
desc.Height = 50;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 2;
|
||||
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.SampleCount = 1;
|
||||
|
||||
void* object = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
HRESULT hr = XGCreateTextureComputer(&desc, &object);
|
||||
@@ -676,41 +708,41 @@ void* stage_xg_texture_computer() {
|
||||
static_cast<unsigned long>(hr), object);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(object);
|
||||
bx_xg_placed_footprint mips[2] = {};
|
||||
uint32_t rows[2] = {};
|
||||
uint64_t row_bytes[2] = {};
|
||||
uint64_t total = 0;
|
||||
hr = computer->lpVtbl->GetResourceLayout(computer, 0, 2, 0, mips, rows, row_bytes, &total);
|
||||
auto shape_is = [](const bx_xg_subresource_footprint& f, uint32_t width, uint32_t height, uint32_t pitch) {
|
||||
return f.format == DXGI_FORMAT_R8G8B8A8_UNORM && f.width == width && f.height == height && f.depth == 1 &&
|
||||
f.row_pitch == pitch;
|
||||
};
|
||||
const bool mip0 = mips[0].offset == 0 && shape_is(mips[0].footprint, 100, 50, 512) && mips[0].copy_end == 25488 &&
|
||||
rows[0] == 50 && row_bytes[0] == 400;
|
||||
const bool mip1 = mips[1].offset == 25600 && shape_is(mips[1].footprint, 50, 25, 256) && mips[1].copy_end == 31944 &&
|
||||
rows[1] == 25 && row_bytes[1] == 200;
|
||||
if (hr == S_OK && mip0 && mip1 && total == 32256) {
|
||||
using U64Fn = UINT64(WINAPI*)(void*);
|
||||
using MipFn = UINT64(WINAPI*)(void*, UINT32, UINT32);
|
||||
const UINT64 size = xg_slot<U64Fn>(object, kXgSizeBytes)(object);
|
||||
const UINT64 alignment = xg_slot<U64Fn>(object, kXgBaseAlignment)(object);
|
||||
const UINT64 mip0 = xg_slot<MipFn>(object, kXgMipOffset)(object, 0, 0);
|
||||
const UINT64 mip1 = xg_slot<MipFn>(object, kXgMipOffset)(object, 0, 1);
|
||||
if (size == 65536 && alignment == 65536 && mip0 == 0 && mip1 == 25600) {
|
||||
checkpoint("xg_xs_texture_computer", Status::Pass,
|
||||
"100x50 RGBA8 two-mip linear footprints and 32256 total bytes match hand-computed values");
|
||||
"100x50 RGBA8 two-mip linear layout matches hand-computed size, alignment and mip offsets");
|
||||
} else {
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail,
|
||||
"GetResourceLayout hr=0x%08lx mip0_ok=%d mip1_ok=%d total=%llu",
|
||||
static_cast<unsigned long>(hr), mip0, mip1, static_cast<unsigned long long>(total));
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail, "size=%llu alignment=%llu mip0=%llu mip1=%llu",
|
||||
static_cast<unsigned long long>(size), static_cast<unsigned long long>(alignment),
|
||||
static_cast<unsigned long long>(mip0), static_cast<unsigned long long>(mip1));
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
void* stage_xg_xs() {
|
||||
begin_stage("xg_xs_swizzle_mode");
|
||||
/* D3D12_RESOURCE_DIMENSION_TEXTURE2D / DXGI_FORMAT_R8G8B8A8_UNORM, 256x256, 1 mip, 1 sample. */
|
||||
uint32_t mode_a = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
|
||||
uint32_t mode_b = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
|
||||
if (mode_a == BX_XG_LAYOUT_LINEAR && mode_b == mode_a) {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode suggests linear and is deterministic (mode=%u)", mode_a);
|
||||
XgResourceDesc desc = {};
|
||||
desc.Dimension = kXgTexture2D;
|
||||
desc.Width = 256;
|
||||
desc.Height = 256;
|
||||
desc.DepthOrArraySize = 1;
|
||||
desc.MipLevels = 1;
|
||||
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.SampleCount = 1;
|
||||
uint32_t mode_a = 0, mode_b = 0;
|
||||
const HRESULT hr_a = XGSuggestSwizzleMode(&desc, 0, &mode_a);
|
||||
const HRESULT hr_b = XGSuggestSwizzleMode(&desc, 0, &mode_b);
|
||||
if (hr_a == S_OK && hr_b == S_OK && mode_a == kXgLayoutSwizzleLinear && mode_b == mode_a) {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode suggests linear and is deterministic (layout=0x%x)", mode_a);
|
||||
} else {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode returned %u then %u, expected linear", mode_a, mode_b);
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode hr=0x%08lx/0x%08lx layout=0x%x then 0x%x, expected linear",
|
||||
static_cast<unsigned long>(hr_a), static_cast<unsigned long>(hr_b), mode_a, mode_b);
|
||||
}
|
||||
|
||||
return stage_xg_texture_computer();
|
||||
@@ -751,7 +783,7 @@ void stage_d3d12_root_signature() {
|
||||
void* stage_d3d12_create_device() {
|
||||
begin_stage("d3d12xbox_create_device");
|
||||
void* device = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), &device);
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), &device);
|
||||
if (device == reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD))) {
|
||||
checkpoint("d3d12xbox_create_device", Status::Fail, "D3D12XboxCreateDevice left the out pointer unwritten (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
@@ -870,8 +902,7 @@ int main(int argc, char** argv) {
|
||||
/* The fixture holds the only reference, so this Release must return 0. */
|
||||
ULONG texture_refs = 0;
|
||||
if (texture_computer) {
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(texture_computer);
|
||||
texture_refs = computer->lpVtbl->Release(computer);
|
||||
texture_refs = xg_slot<ULONG(WINAPI*)(void*)>(texture_computer, kXgRelease)(texture_computer);
|
||||
}
|
||||
release_com(game_input);
|
||||
bool dsp_closed = true;
|
||||
@@ -880,7 +911,8 @@ int main(int argc, char** argv) {
|
||||
dsp_closed = deact_hr == S_OK && XDspDisconnect(dsp) == S_OK;
|
||||
}
|
||||
bool apu_closed = apu_conn ? XApuDisconnect(apu_conn) == S_OK : true;
|
||||
release_com(acp_hal);
|
||||
/* IAcpHal is not COM: Release is its sixth slot and returns nothing. */
|
||||
if (acp_hal) reinterpret_cast<void(WINAPI*)(void*)>((*static_cast<void* const* const*>(acp_hal))[5])(acp_hal);
|
||||
release_com(dstorage_factory);
|
||||
if (psm_constrained_reg) UnregisterAppConstrainedChangeNotification(psm_constrained_reg);
|
||||
if (psm_state_reg) UnregisterAppStateChangeNotification(psm_state_reg);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
set(d3d12_xs_headers "${BX_ROOT_DIR}/shims/d3d12_xs")
|
||||
if(NOT EXISTS "${d3d12_xs_headers}/vmem.h" OR NOT EXISTS "${d3d12_xs_headers}/presentx.h")
|
||||
message(FATAL_ERROR "test_m2_first_frame requires the placed-resource and PresentX contracts (#486 and #471)")
|
||||
endif()
|
||||
|
||||
add_executable(test_m2_first_frame main.cpp)
|
||||
target_include_directories(test_m2_first_frame PRIVATE
|
||||
"${BX_ABI_INCLUDE_DIR}"
|
||||
"${d3d12_xs_headers}"
|
||||
"${BX_ROOT_DIR}/shader-transpiler/crates/d3dmetal-harness/probe/shaders"
|
||||
)
|
||||
target_link_libraries(test_m2_first_frame PRIVATE d3d12_xs xmem bx_runtime_veh user32)
|
||||
target_compile_options(test_m2_first_frame PRIVATE -fexceptions)
|
||||
@@ -0,0 +1,363 @@
|
||||
// Original synthetic M2 workload. The compute output is copied into the flip
|
||||
// buffer and read back through a placed D3D12 buffer before the host flip.
|
||||
//
|
||||
// Limitations: the frame is a compute write copied into the back buffer, not a
|
||||
// rasterized draw. The shader-gate stage covers only the DXIL fast path. The
|
||||
// pixel compare reads pre-flip back-buffer contents, not what reached the
|
||||
// screen. The readback lives in the D3D12 WRITE_BACK backing heap's own map;
|
||||
// the xmem page only names the configured region and is checked to stay
|
||||
// untouched, so this does not show xmem-backed placed memory (#469).
|
||||
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
#include <wrl/client.h>
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include "bx_log.h"
|
||||
#include "fill_cs66.h"
|
||||
#include "presentx.h"
|
||||
#include "vmem.h"
|
||||
|
||||
using Microsoft::WRL::ComPtr;
|
||||
extern "C" {
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12ConfigureVirtualMemoryX(void*);
|
||||
// The documented four parameters (adapter, parameters, riid, device); a zeroed block (Version 0)
|
||||
// keeps the PC-layout proxy this test is written against (ADR 0009).
|
||||
__declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(void*, const void*, REFIID, void**);
|
||||
alignas(8) static const unsigned char kPcLayoutParams[80] = {};
|
||||
__declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(uint64_t, PULONG_PTR, PULONG_PTR);
|
||||
__declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR, PULONG_PTR);
|
||||
__declspec(dllimport) PVOID WINAPI XMemMapPhysicalPages(PVOID, ULONG_PTR, PULONG_PTR);
|
||||
}
|
||||
|
||||
namespace {
|
||||
const char* stage = "gdk_boot";
|
||||
unsigned seq = 0;
|
||||
void checkpoint(bool ok, const char* detail) {
|
||||
std::printf(
|
||||
"{\"bx_checkpoint\":\"test_m2_first_frame\",\"seq\":%u,\"stage\":\"%s\",\"status\":\"%s\",\"detail\":\"%s\"}\n",
|
||||
++seq, stage, ok ? "pass" : "fail", detail);
|
||||
std::fflush(stdout);
|
||||
char message[384];
|
||||
std::snprintf(message, sizeof(message), "%s: %s", stage, detail);
|
||||
bx_log_emit(ok ? BX_LOG_INFO : BX_LOG_ERROR, "m2_first_frame", ok ? "stage_pass" : "stage_fail", message);
|
||||
}
|
||||
bool cleanup_ok = true;
|
||||
void cleanup(bool ok, const char* call) {
|
||||
if (!ok) {
|
||||
cleanup_ok = false;
|
||||
checkpoint(false, call);
|
||||
}
|
||||
}
|
||||
struct Failure {};
|
||||
void require(bool ok, const char* detail) {
|
||||
if (!ok) {
|
||||
checkpoint(false, detail);
|
||||
throw Failure{};
|
||||
}
|
||||
}
|
||||
void checked(HRESULT hr, const char* call) {
|
||||
if (FAILED(hr)) {
|
||||
char detail[192];
|
||||
std::snprintf(detail, sizeof(detail), "%s hr=0x%08lx", call, static_cast<unsigned long>(hr));
|
||||
require(false, detail);
|
||||
}
|
||||
}
|
||||
template <class T> T symbol(HMODULE module, const char* name) {
|
||||
auto address = GetProcAddress(module, name);
|
||||
require(address != nullptr, name);
|
||||
T result;
|
||||
std::memcpy(&result, &address, sizeof(result));
|
||||
return result;
|
||||
}
|
||||
struct Runtime {
|
||||
HMODULE module = LoadLibraryExW(L"xgameruntime.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
HRESULT(WINAPI* uninit)() = nullptr;
|
||||
bool active = false;
|
||||
~Runtime() {
|
||||
if (active)
|
||||
cleanup(uninit() == S_OK, "UninitializeApiImpl");
|
||||
if (module)
|
||||
cleanup(FreeLibrary(module), "FreeLibrary");
|
||||
}
|
||||
};
|
||||
struct Region {
|
||||
static constexpr size_t page_bytes = 65536;
|
||||
static constexpr unsigned char sentinel = 0xa5;
|
||||
SIZE_T count = 1;
|
||||
ULONG_PTR page = 0;
|
||||
void* view = nullptr;
|
||||
BxD3d12VirtualMemoryConfig config = [] {
|
||||
// Assigned by name so a field reorder in vmem.h cannot compile silently.
|
||||
BxD3d12VirtualMemoryConfig c{};
|
||||
c.magic = BX_D3D12_VMEM_MAGIC;
|
||||
c.struct_size = sizeof(BxD3d12VirtualMemoryConfig);
|
||||
c.version = 1;
|
||||
c.flags = BX_D3D12_VMEM_FLAG_BACKING_HEAP;
|
||||
c.base_va = 0;
|
||||
c.size_bytes = page_bytes;
|
||||
c.reserved = 0;
|
||||
c.cpu_pointer = 0;
|
||||
return c;
|
||||
}();
|
||||
~Region() {
|
||||
if (config.base_va) {
|
||||
config.base_va = config.size_bytes = 0;
|
||||
cleanup(D3D12ConfigureVirtualMemoryX(&config) == S_OK, "clear configured region");
|
||||
}
|
||||
if (view)
|
||||
cleanup(XMemMapPhysicalPages(view, count, nullptr) == view, "unmap physical page");
|
||||
if (page)
|
||||
cleanup(XMemFreePhysicalPages(count, &page), "free physical page");
|
||||
}
|
||||
};
|
||||
// Declared just before ExecuteCommandLists, so on a failure after the submit it is
|
||||
// destroyed before the queue, back buffer and output resource it protects: it
|
||||
// signals the queue and waits (bounded) so nothing is released while the GPU may
|
||||
// still be using it. Disarmed once the readback fence has completed.
|
||||
struct GpuDrain {
|
||||
ID3D12CommandQueue* queue = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
bool armed = false;
|
||||
~GpuDrain() {
|
||||
if (!armed) return;
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
bool drained = done && SUCCEEDED(queue->Signal(fence, 2)) &&
|
||||
(fence->GetCompletedValue() >= 2 ||
|
||||
(SUCCEEDED(fence->SetEventOnCompletion(2, done)) &&
|
||||
WaitForSingleObject(done, 5000) == WAIT_OBJECT_0));
|
||||
if (done) CloseHandle(done);
|
||||
cleanup(drained, "drain the queue before releasing resources after a failure");
|
||||
}
|
||||
};
|
||||
struct Window {
|
||||
HWND hwnd = CreateWindowExW(0, L"STATIC", L"BetterXen M2", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT,
|
||||
CW_USEDEFAULT, 320, 240, nullptr, nullptr, nullptr, nullptr);
|
||||
~Window() {
|
||||
if (hwnd)
|
||||
cleanup(DestroyWindow(hwnd), "destroy window");
|
||||
}
|
||||
};
|
||||
|
||||
void run(bool inject_pixel_mismatch) {
|
||||
Runtime rt;
|
||||
require(rt.module, "LoadLibraryExW system32");
|
||||
auto init = symbol<HRESULT(WINAPI*)(uint32_t, uint32_t)>(rt.module, "InitializeApiImpl");
|
||||
rt.uninit = symbol<decltype(rt.uninit)>(rt.module, "UninitializeApiImpl");
|
||||
auto query = symbol<HRESULT(WINAPI*)(const GUID*, const GUID*, void**)>(rt.module, "QueryApiImpl");
|
||||
checked(init(1, 1), "InitializeApiImpl");
|
||||
rt.active = true;
|
||||
const GUID core_guid = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
|
||||
const GUID sys_clsid = {0xE349BD1A, 0xFC20, 0x4E40, {0xB9, 0x9C, 0x41, 0x78, 0xCC, 0x6B, 0x40, 0x9F}};
|
||||
const GUID sys_iid = {0x1861CF2E, 0xE18B, 0x4834, {0xA9, 0xF5, 0xB4, 0xA4, 0xE6, 0xEF, 0xB4, 0xCF}};
|
||||
const GUID user_guid = {0x01ACD177, 0x91F9, 0x4763, {0xA3, 0x8E, 0xCC, 0xBB, 0x55, 0xCE, 0x32, 0xE0}};
|
||||
ComPtr<IUnknown> core, system, user;
|
||||
checked(query(&core_guid, &core_guid, reinterpret_cast<void**>(core.GetAddressOf())), "IXGameRuntimeCore");
|
||||
checked(query(&sys_clsid, &sys_iid, reinterpret_cast<void**>(system.GetAddressOf())), "IXSystem");
|
||||
checked(query(&user_guid, &user_guid, reinterpret_cast<void**>(user.GetAddressOf())), "IXUser");
|
||||
require(core && system && user, "GDK COM interfaces");
|
||||
checkpoint(true, "runtime initialized and three public interfaces acquired");
|
||||
|
||||
stage = "placed_resource";
|
||||
Region region;
|
||||
require(XMemAllocatePhysicalPages(0, ®ion.count, ®ion.page) && region.count == 1, "allocate physical page");
|
||||
region.view = XMemMapPhysicalPages(nullptr, 1, ®ion.page);
|
||||
require(region.view, "map physical page");
|
||||
std::memset(region.view, Region::sentinel, Region::page_bytes);
|
||||
region.config.base_va = reinterpret_cast<uintptr_t>(region.view);
|
||||
checked(D3D12ConfigureVirtualMemoryX(®ion.config), "configure xmem region");
|
||||
ComPtr<ID3D12Device> device;
|
||||
checked(D3D12XboxCreateDevice(nullptr, kPcLayoutParams, IID_PPV_ARGS(&device)), "create Xbox device");
|
||||
D3D12_HEAP_DESC hd{};
|
||||
hd.SizeInBytes = region.config.size_bytes;
|
||||
hd.Properties.Type = D3D12_HEAP_TYPE_CUSTOM;
|
||||
hd.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
|
||||
hd.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
|
||||
ComPtr<ID3D12Heap> heap;
|
||||
checked(device->CreateHeap(&hd, IID_PPV_ARGS(&heap)), "create configured heap");
|
||||
checked(D3D12ConfigureVirtualMemoryX(®ion.config), "query backing map");
|
||||
require(region.config.cpu_pointer != 0, "configured heap must publish its backing map");
|
||||
require(region.config.cpu_pointer != reinterpret_cast<uintptr_t>(region.view),
|
||||
"D3D12 backing map must be distinct from the xmem region view");
|
||||
constexpr UINT width = 64, height = 4, pitch = 256;
|
||||
D3D12_RESOURCE_DESC buffer{};
|
||||
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buffer.Width = height * pitch;
|
||||
buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1;
|
||||
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
ComPtr<ID3D12Resource> readback;
|
||||
checked(device->CreatePlacedResource(heap.Get(), 0, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
IID_PPV_ARGS(&readback)),
|
||||
"place readback buffer");
|
||||
checkpoint(true, "xmem region configured; readback placed in a separate D3D12 WRITE_BACK heap");
|
||||
|
||||
stage = "shader_gate";
|
||||
char path[MAX_PATH];
|
||||
DWORD length = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
|
||||
require(length && length < sizeof(path), "BX_LOG_FILE required");
|
||||
// Start at EOF before PSO creation so stale shader_gate records cannot pass this check.
|
||||
std::ifstream log(path, std::ios::binary | std::ios::ate);
|
||||
require(log.good(), "open launch log");
|
||||
D3D12_ROOT_PARAMETER param{};
|
||||
param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
|
||||
D3D12_VERSIONED_ROOT_SIGNATURE_DESC signature{};
|
||||
signature.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
|
||||
signature.Desc_1_0.NumParameters = 1;
|
||||
signature.Desc_1_0.pParameters = ¶m;
|
||||
ComPtr<ID3DBlob> blob;
|
||||
checked(D3D12SerializeVersionedRootSignature(&signature, &blob, nullptr), "serialize root signature");
|
||||
ComPtr<ID3D12RootSignature> root;
|
||||
checked(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)),
|
||||
"root signature");
|
||||
D3D12_COMPUTE_PIPELINE_STATE_DESC ps{};
|
||||
ps.pRootSignature = root.Get();
|
||||
ps.CS = {g_fill_cs66, sizeof(g_fill_cs66)};
|
||||
ComPtr<ID3D12PipelineState> pso;
|
||||
checked(device->CreateComputePipelineState(&ps, IID_PPV_ARGS(&pso)), "SM 6.6 compute PSO");
|
||||
bool inspected = false;
|
||||
for (std::string line; std::getline(log, line);) {
|
||||
if (line.find("\"event\":\"shader_gate\"") != line.npos && line.find("decision=pass_dxil") != line.npos &&
|
||||
line.find("pso=compute") != line.npos && line.find("sm=6.6") != line.npos)
|
||||
inspected = true;
|
||||
}
|
||||
require(inspected, "missing SM 6.6 pass_dxil telemetry for PSO");
|
||||
checkpoint(true, "inspected SM 6.6 compute PSO");
|
||||
|
||||
stage = "present";
|
||||
Window window;
|
||||
require(window.hwnd, "create window");
|
||||
D3D12_COMMAND_QUEUE_DESC qd{};
|
||||
ComPtr<ID3D12CommandQueue> queue;
|
||||
checked(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue)), "direct queue");
|
||||
ComPtr<IBxPresentQueue> bridge;
|
||||
checked(queue->QueryInterface(IID_IBxPresentQueue, reinterpret_cast<void**>(bridge.GetAddressOf())),
|
||||
"PresentX queue interface");
|
||||
BxPresentDesc desc{width, height, DXGI_FORMAT_R8G8B8A8_UNORM, 2};
|
||||
ComPtr<IBxPresentSwapChain> chain;
|
||||
checked(bridge->CreateSwapChain(window.hwnd, &desc, &chain), "create flip chain");
|
||||
ComPtr<ID3D12Resource> back;
|
||||
checked(chain->GetBuffer(chain->GetCurrentBackBufferIndex(), IID_PPV_ARGS(&back)), "get current backbuffer");
|
||||
D3D12_HEAP_PROPERTIES props{};
|
||||
props.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
ComPtr<ID3D12Resource> output;
|
||||
checked(device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &buffer,
|
||||
D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&output)),
|
||||
"shader output");
|
||||
ComPtr<ID3D12CommandAllocator> alloc;
|
||||
ComPtr<ID3D12GraphicsCommandList> list;
|
||||
checked(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc)), "command allocator");
|
||||
checked(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.Get(), pso.Get(), IID_PPV_ARGS(&list)),
|
||||
"command list");
|
||||
list->SetComputeRootSignature(root.Get());
|
||||
list->SetComputeRootUnorderedAccessView(0, output->GetGPUVirtualAddress());
|
||||
list->Dispatch(height, 1, 1);
|
||||
auto transition = [&](ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) {
|
||||
D3D12_RESOURCE_BARRIER barrier{};
|
||||
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to};
|
||||
list->ResourceBarrier(1, &barrier);
|
||||
};
|
||||
transition(output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
transition(back.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
D3D12_TEXTURE_COPY_LOCATION texture{}, linear{};
|
||||
texture.pResource = back.Get();
|
||||
texture.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
linear.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
|
||||
linear.PlacedFootprint.Footprint = {desc.format, width, height, 1, pitch};
|
||||
linear.pResource = output.Get();
|
||||
list->CopyTextureRegion(&texture, 0, 0, 0, &linear, nullptr);
|
||||
if (inject_pixel_mismatch) {
|
||||
const D3D12_BOX second_pixel{1, 0, 0, 2, 1, 1};
|
||||
list->CopyTextureRegion(&texture, 0, 0, 0, &linear, &second_pixel);
|
||||
}
|
||||
transition(back.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
linear.pResource = readback.Get();
|
||||
list->CopyTextureRegion(&linear, 0, 0, 0, &texture, nullptr);
|
||||
transition(back.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_PRESENT);
|
||||
checked(list->Close(), "close command list");
|
||||
ID3D12CommandList* commands[] = {list.Get()};
|
||||
ComPtr<IDXGISwapChain1> host;
|
||||
checked(chain->GetHostSwapChain(IID_PPV_ARGS(&host)), "get host swapchain");
|
||||
UINT before = 0, after = 0;
|
||||
checked(host->GetLastPresentCount(&before), "initial host present count");
|
||||
ComPtr<ID3D12Fence> fence;
|
||||
checked(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)), "readback fence");
|
||||
GpuDrain drain{queue.Get(), fence.Get(), true};
|
||||
queue->ExecuteCommandLists(1, commands);
|
||||
const HRESULT present_hr = chain->Present(0, 0);
|
||||
if (present_hr != S_OK) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "PresentX hr=0x%08lx", static_cast<unsigned long>(present_hr));
|
||||
require(false, detail);
|
||||
}
|
||||
checked(chain->WaitForIdle(5000), "wait for frame");
|
||||
// Wait on our own queue fence before the CPU reads the backing map, so the
|
||||
// readback does not depend on what WaitForIdle covers.
|
||||
checked(queue->Signal(fence.Get(), 1), "signal readback fence");
|
||||
if (fence->GetCompletedValue() < 1) {
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
require(done != nullptr, "readback fence event");
|
||||
const HRESULT wait_hr = fence->SetEventOnCompletion(1, done);
|
||||
const DWORD waited = SUCCEEDED(wait_hr) ? WaitForSingleObject(done, 5000) : WAIT_FAILED;
|
||||
cleanup(CloseHandle(done) != 0, "close readback fence event");
|
||||
checked(wait_hr, "readback fence SetEventOnCompletion");
|
||||
require(waited == WAIT_OBJECT_0, "readback fence wait timed out");
|
||||
}
|
||||
drain.armed = false; // everything submitted has completed
|
||||
checked(host->GetLastPresentCount(&after), "final host present count");
|
||||
require(after == before + 1, "host must present exactly once");
|
||||
checkpoint(true, "one host present completed");
|
||||
|
||||
stage = "pixel_readback";
|
||||
auto pixels = reinterpret_cast<const uint32_t*>(region.config.cpu_pointer);
|
||||
for (UINT i = 0; i < width * height; ++i) {
|
||||
// Mirrors fill_cs66.hlsl in shader-transpiler/crates/d3dmetal-harness/probe/shaders;
|
||||
// a change to that shader must change this formula too.
|
||||
uint32_t v = i * 0x9e3779b1u;
|
||||
uint32_t expected = (v ^ (v >> 15)) + 0x01234567u;
|
||||
if (pixels[i] != expected) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "pixel (%u,%u) expected %08x got %08x", i % width, i / width,
|
||||
expected, pixels[i]);
|
||||
require(false, detail);
|
||||
}
|
||||
}
|
||||
const auto* xmem_bytes = static_cast<const unsigned char*>(region.view);
|
||||
require(std::all_of(xmem_bytes, xmem_bytes + Region::page_bytes,
|
||||
[](unsigned char byte) { return byte == Region::sentinel; }),
|
||||
"xmem region bytes changed during frame readback");
|
||||
checkpoint(true, "256 pre-flip RGBA8 pixels matched in the D3D12 map; xmem region sentinel intact");
|
||||
stage = "teardown";
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
// The mismatch control is armed only by exactly "1". Any other value is a
|
||||
// configuration error rather than a silently ignored control, so a run that
|
||||
// meant to arm it cannot pass as an ordinary run.
|
||||
char inject[16];
|
||||
const DWORD inject_len =
|
||||
GetEnvironmentVariableA("BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH", inject, sizeof(inject));
|
||||
const bool inject_pixel_mismatch = inject_len == 1 && inject[0] == '1';
|
||||
if (inject_len != 0 && !inject_pixel_mismatch) {
|
||||
std::fprintf(stderr, "FAIL: BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH must be unset or exactly 1\n");
|
||||
return 1;
|
||||
}
|
||||
if (inject_pixel_mismatch) {
|
||||
std::printf("NOTE: pixel mismatch control armed; this run must fail at pixel_readback\n");
|
||||
}
|
||||
try {
|
||||
run(inject_pixel_mismatch);
|
||||
} catch (const Failure&) {
|
||||
return 1;
|
||||
}
|
||||
if (!cleanup_ok)
|
||||
return 1;
|
||||
checkpoint(true, "resources released and runtime shut down");
|
||||
return 0;
|
||||
}
|
||||
@@ -9,7 +9,8 @@
|
||||
* with no object and no call reaching the host device;
|
||||
* 3. creates PSOs from the #453 [WaveSize(64)] and 64-bit typed-atomic blobs and requires the
|
||||
* gate to log their constraints;
|
||||
* 4. checks the structured `shader_gate` JSONL records.
|
||||
* 4. checks the structured `shader_gate` JSONL records, including the field order and
|
||||
* space-free values bx-telemetry's key=value parser relies on (#535).
|
||||
*
|
||||
* It then runs a copy of itself with --no-bridge from a directory holding d3d12_xs.dll but not
|
||||
* the bridge, which must still run DXIL and refuse ACCC-only with E_NOTIMPL.
|
||||
@@ -39,7 +40,12 @@
|
||||
#include "fill_cs66.h" // g_fill_cs66, d3dmetal-harness
|
||||
#include "wave64_lanes.h" // g_wave64_lanes_cs, #453
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv);
|
||||
|
||||
/* 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] = {};
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12SerializeVersionedRootSignature(
|
||||
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, ID3DBlob** blob, ID3DBlob** error);
|
||||
|
||||
@@ -140,6 +146,51 @@ bool log_has(const std::string& log, std::initializer_list<const char*> needles)
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Every JSONL line whose text holds `needle`, so shape checks can loop over
|
||||
* the records the shim actually wrote rather than the lines typed by hand in
|
||||
* the trace-summary fixtures. */
|
||||
std::vector<std::string> log_lines_with(const std::string& log, const char* needle) {
|
||||
std::vector<std::string> lines;
|
||||
size_t start = 0;
|
||||
while (start < log.size()) {
|
||||
size_t end = log.find('\n', start);
|
||||
if (end == std::string::npos) end = log.size();
|
||||
const std::string line = log.substr(start, end - start);
|
||||
if (line.find(needle) != std::string::npos) lines.push_back(line);
|
||||
start = end + 1;
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/* The `detail` value of one JSONL line, or empty when there is none. */
|
||||
std::string detail_of(const std::string& line) {
|
||||
const char* key = "\"detail\":\"";
|
||||
const size_t at = line.find(key);
|
||||
if (at == std::string::npos) return {};
|
||||
const size_t begin = at + std::strlen(key);
|
||||
size_t end = begin;
|
||||
while (end < line.size() && !(line[end] == '"' && line[end - 1] != '\\')) ++end;
|
||||
return line.substr(begin, end - begin);
|
||||
}
|
||||
|
||||
/* The structured part of a `shader_gate` detail: everything before the first
|
||||
* token that has no `=`. The gap record ends in prose, so it stops there. */
|
||||
std::vector<std::string> structured_tokens(const std::string& detail, bool stop_at_free_text) {
|
||||
std::vector<std::string> tokens;
|
||||
size_t i = 0;
|
||||
while (i < detail.size()) {
|
||||
while (i < detail.size() && detail[i] == ' ') ++i;
|
||||
if (i >= detail.size()) break;
|
||||
size_t end = detail.find(' ', i);
|
||||
if (end == std::string::npos) end = detail.size();
|
||||
const std::string token = detail.substr(i, end - i);
|
||||
if (token.find('=') == std::string::npos && stop_at_free_text) break;
|
||||
tokens.push_back(token);
|
||||
i = end;
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
ID3D12RootSignature* make_root(ID3D12Device* device, const D3D12_ROOT_PARAMETER& param) {
|
||||
D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc = {};
|
||||
desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
|
||||
@@ -316,7 +367,7 @@ std::wstring directory_of(const wchar_t* path) {
|
||||
* bx_shader_bridge.dll. DXIL must still run and ACCC-only must still be refused. */
|
||||
int no_bridge_main() {
|
||||
ID3D12Device* device = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, kCreateParams, __uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
if (!check(SUCCEEDED(hr) && device, "no-bridge: D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) return finish();
|
||||
D3D12_ROOT_PARAMETER uav = {};
|
||||
uav.ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
|
||||
@@ -411,7 +462,7 @@ int main() {
|
||||
}
|
||||
|
||||
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(SUCCEEDED(hr) && device, "D3D12XboxCreateDevice hr=0x%08lx", ul(hr))) return finish();
|
||||
|
||||
D3D12_ROOT_PARAMETER uav = {};
|
||||
@@ -566,6 +617,81 @@ int main() {
|
||||
|
||||
// 5. The JSONL records.
|
||||
const std::string log = read_log();
|
||||
// The trace-summary fixtures in bx-telemetry/bx-cli are typed by hand from
|
||||
// reading shader_gate.cpp. These checks pin the shape the parser assumes,
|
||||
// against the log this fixture actually wrote, so the two cannot drift
|
||||
// apart silently (#535).
|
||||
{
|
||||
const std::vector<std::string> gate_lines = log_lines_with(log, "\"event\":\"shader_gate\"");
|
||||
check(!gate_lines.empty(), "the fixture wrote at least one shader_gate record");
|
||||
|
||||
bool order_ok = true;
|
||||
bool classified_has_kind = true;
|
||||
bool unclassified_lacks_kind = true;
|
||||
bool values_have_no_space = true;
|
||||
for (const std::string& line : gate_lines) {
|
||||
const std::string detail = detail_of(line);
|
||||
const size_t pso = detail.find("pso=");
|
||||
const size_t stage = detail.find("stage=");
|
||||
const size_t decision = detail.find("decision=");
|
||||
const size_t hr = detail.find("hr=");
|
||||
// The summarizer extracts these by key, so the order the emitter
|
||||
// writes them is the order it relies on. Every key must be present:
|
||||
// a missing one is npos, the largest value, which would satisfy `<`.
|
||||
const bool all_present = pso != std::string::npos && stage != std::string::npos &&
|
||||
decision != std::string::npos && hr != std::string::npos;
|
||||
if (!(all_present && pso < stage && stage < decision && decision < hr)) {
|
||||
order_ok = false;
|
||||
}
|
||||
const bool unclassified = detail.find("unclassified") != std::string::npos;
|
||||
const bool has_kind = detail.find("kind=") != std::string::npos;
|
||||
/* A record with an inspection always logs a kind; the no-bridge records
|
||||
* (`*_unclassified`) and `pass_uninspected` have none. */
|
||||
const bool classified = !unclassified &&
|
||||
(detail.find("decision=pass_dxil") != std::string::npos ||
|
||||
detail.find("decision=reject_accc_only") != std::string::npos ||
|
||||
detail.find("decision=pass_original") != std::string::npos ||
|
||||
detail.find("decision=prepare_failed") != std::string::npos ||
|
||||
detail.find("decision=copy_limit") != std::string::npos);
|
||||
if (unclassified && has_kind) unclassified_lacks_kind = false;
|
||||
if (classified && !has_kind) classified_has_kind = false;
|
||||
for (const std::string& token : structured_tokens(detail, false)) {
|
||||
if (token.find('=') == std::string::npos) values_have_no_space = false;
|
||||
}
|
||||
}
|
||||
check(order_ok, "every shader_gate record writes pso, stage, decision, hr in that order");
|
||||
check(classified_has_kind, "a classified shader_gate record carries kind=");
|
||||
check(unclassified_lacks_kind, "an unclassified record carries no kind=");
|
||||
check(values_have_no_space,
|
||||
"no key=value in a shader_gate record is split by a space, which is what "
|
||||
"parse_key_values(..., false) assumes");
|
||||
|
||||
const std::vector<std::string> gap_lines = log_lines_with(log, "\"event\":\"shader_d3dmetal_gap\"");
|
||||
check(!gap_lines.empty(), "the fixture wrote at least one gap record");
|
||||
bool gap_ok = true;
|
||||
bool gap_values_have_no_space = true;
|
||||
for (const std::string& line : gap_lines) {
|
||||
const std::string detail = detail_of(line);
|
||||
if (detail.find("pso=") == std::string::npos ||
|
||||
detail.find("stage=") == std::string::npos ||
|
||||
detail.find("wave_lanes_min=") == std::string::npos ||
|
||||
detail.find(':') == std::string::npos) {
|
||||
gap_ok = false;
|
||||
}
|
||||
// parse_key_values(..., true) stops at the first token without
|
||||
// '=', so every structured token must be a key=value pair.
|
||||
for (const std::string& token : structured_tokens(detail, true)) {
|
||||
if (token.find('=') == std::string::npos) gap_values_have_no_space = false;
|
||||
}
|
||||
}
|
||||
check(gap_ok,
|
||||
"every gap record carries pso=, stage=, wave_lanes_min= and the colon "
|
||||
"that ends its structured part");
|
||||
check(gap_values_have_no_space,
|
||||
"no key=value in a gap record's structured part is split by a space, which is "
|
||||
"what parse_key_values(..., true) assumes");
|
||||
}
|
||||
|
||||
char fill_bytes[32];
|
||||
std::snprintf(fill_bytes, sizeof(fill_bytes), "bytes=%u ", static_cast<unsigned>(sizeof(g_fill_cs66)));
|
||||
check(log_has(log, {"\"event\":\"shader_gate\"", "pso=compute", "decision=pass_dxil", "kind=dxil", "sm=6.6",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
add_executable(test_veh_breakpoint main.cpp)
|
||||
target_link_libraries(test_veh_breakpoint PRIVATE bx_runtime_veh kernel32)
|
||||
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user