Compare commits

..
Author SHA1 Message Date
ates 6e0b882691 Scripted input and assert stepping for unattended target-build runs
GameInput: BX_INPUT_SCRIPT presses gamepad buttons at given seconds,
without window focus, so an unattended run gets past screens that wait
for input. bx_runtime_veh: BX_CONTINUE_ASSERTS=1 steps over an int3 in
the title's own executable instead of letting it reach the crash
reporter, logging each address once and keeping the thread's last-error
value. Both are off unless set and documented with the other offline-run
diagnostics.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 04:24:10 +03:00
Ateş 6c52bfb030 Merge pull request #711 from MacosPorters/track-a/ghidra-results-required
[Process] Require the Ghidra results; check for existing work before any game problem
2026-11-30 04:09:42 +03:00
ates 6059d701e2 Require the Ghidra results; check for existing work before any game problem
The target build, the GDK and the target build's Ghidra results are a
hard requirement: preflight adds a Ghidra results row (present and
covering the target executable), setup --ghidra-results and --find save
them, and an agent lacking any of the three does not work on the repo.

Before investigating any problem the game shows, agents search open and
merged pull requests and open issues, and work on a covering pull
request's branch instead of writing a second fix.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 04:09:18 +03:00
Ateş d0a1c21a4e Merge pull request #710 from MacosPorters/track-c/gdk-xg-texture-layouts
[Picture] Console texture layouts and BCPack from the GDK's own libraries (ADR 0010)
2026-11-30 04:01:48 +03:00
ates 4fde342db1 Use the GDK's own texture libraries at run time (ADR 0010)
bx-cli run stages the configured GDK's xg_xs.dll and BCPack.dll for the
target build (recognised by their exports, never committed), and names
the decoder to XCRDAPI.dll. d3d12_xs answers GetResourceAllocationInfo
for console texture layouts with the GDK's XG size and alignment and
enables XG's exclusive locking at device creation. Conformance tests
keep BetterXen's own shims; test_d3d12_gdk_xg_sizes checks the d3d12_xs
side with a stand-in XG library.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 04:01:10 +03:00
Ateş a17edafe3b Merge pull request #709 from MacosPorters/track-b/storage-page-timing-zlib-bcpack
[Picture] DirectStorage: page arrays filled after enqueue, partial zlib reads, BCPack
2026-11-30 03:44:33 +03:00
ates 3cd97c3cc0 xcrdapi: map page destinations when the request runs, deliver partial zlib reads, decode BCPack via the GDK
A title can fill a DestinationIsPhysicalPages request's page array after
EnqueueRequest returns; the array is now read when the request runs.
A zlib request may ask for the first part of a longer block: the whole
stream is decoded and checked and its first DestinationSize bytes are
delivered. BCPack requests are decoded with the GDK's own BCPack.dll
when BX_BCPACK_DLL names it, and stay refused otherwise.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 03:44:01 +03:00
Ateş c504eb8fc8 Merge pull request #701 from 1Bartosz/track-c/get-frame-statistics-x
[Boot] unimplemented XboxDevice slot 81 (GetFrameStatisticsX)
2026-11-30 03:37:51 +03:00
Ateş 0f9a6e1e11 Merge pull request #692 from 1Bartosz/track-a/console-mode-registry
[Boot] exit status 3: the build reads the console type from the registry (ConsoleMode)
2026-11-30 03:37:25 +03:00
ates e24fa6d42f Merge remote-tracking branch 'origin/main' into pr692-r
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-30 03:37:12 +03:00
Ateş c46611ff9d Merge pull request #704 from MacosPorters/track-e/keyboard-gameinput
[Picture] GameInput: expose a keyboard-backed controller
2026-11-30 03:37:01 +03:00
ates 29a5cd70c0 Merge remote-tracking branch 'origin/main' into pr704-r
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-30 03:36:48 +03:00
ates 15b11b4be8 Merge remote-tracking branch 'origin/main' into pr701-r
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
#	shims/d3d12_xs/tools/gen_xbox_tables.py
2026-11-30 03:36:21 +03:00
Ateş 690c756037 Merge pull request #696 from 1Bartosz/track-c/create-committed-resource-x
[Boot] unimplemented XboxDevice slot 76 (CreateCommittedResourceX)
2026-11-30 03:35:20 +03:00
ates 5c1efdb517 Merge remote-tracking branch 'origin/main' into pr696-r
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-30 03:35:06 +03:00
Ateş 413c46545d Merge pull request #699 from 1Bartosz/track-b/xmem-working-set-stats
[Boot] XMemGetWorkingSetStatistics does not follow the GDK signature
2026-11-30 03:34:45 +03:00
ates 0565e0ac37 Merge remote-tracking branch 'origin/main' into pr699
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-30 03:34:31 +03:00
Ateş a74ad2da44 Merge pull request #706 from 1Bartosz/track-f/671-d3dmetal-capability-checks
[Picture] D3DMetal capability checks for translated console shaders
2026-11-30 03:33:25 +03:00
Ateş fc358d0525 Merge pull request #707 from 1Bartosz/track-b/705-dstorage-physical-pages
[Picture] DirectStorage rejects zlib requests with physical-page destinations
2026-11-30 03:32:42 +03:00
Ateş e502559470 Merge pull request #703 from MacosPorters/abi/xmem-remap-guard-contract
[ABI] Define the XMem remap guard contract
2026-11-30 03:32:24 +03:00
Bartosz Szczepański 06cd29a9a4 Merge remote-tracking branch 'origin/main' into track-b/705-dstorage-physical-pages 2026-11-30 00:45:14 +01:00
Ateş b49b0d9696 Merge pull request #691 from 1Bartosz/track-b/668-xmem-atomic-remap
[Boot] fault in XCRDAPI.dll: page remapping in xmem is not atomic
2026-11-30 02:26:15 +03:00
Bartosz Szczepański 5a53fe1fd5 changelog: DirectStorage physical-page destinations (#705)
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-30 00:13:45 +01:00
Bartosz Szczepański 0c8a583378 d3d12_xs: read DccOptions as the GDK struct of two enums
D3D12XBOX_DCC_OPTIONS is a struct of CompressionLevel and ColorTransform
(GDK d3d12_xs.h), not a single 32-bit enum. CreateCommittedResourceX read
only the first field and logged only non-zero values, although
CompressionLevel 0 is 64B compression, not none. Both fields are now read
and logged for the first 8 calls; the test lays the struct out as two
32-bit fields and asserts the 64-byte size.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-30 00:13:12 +01:00
Bartosz Szczepański 6fbe856b4e xcrdapi: write DirectStorage requests into physical-page destinations (#705)
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-30 00:09:33 +01:00
Bartosz Szczepański 084714739f xcrdapi: claim: DirectStorage requests with a physical-page destination (#705)
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-30 00:04:51 +01:00
Bartosz Szczepański 23f73ee906 bx-cli: match --profile without regard to case and refuse unknown values
The shims read BX_PROFILE with _stricmp, while ConsoleMode was chosen with an
exact comparison, so --profile Anaconda published 0x60 (Series S) next to
XSystemGetDeviceType 7 (Series X). The value is now normalized to lower case
and anything other than lockhart or anaconda is refused.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-30 00:04:35 +01:00
Bartosz Szczepański 33a3ec2329 Merge origin/main into track-b/xmem-working-set-stats
CHANGELOG.md: keep both sides' Fixed entries, this branch's first.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 23:38:47 +01:00
Bartosz Szczepański 84dd9e2df5 tests: cover the inflater and memory sources in test_xcrdapi_remap_guard
Review of #691 (point 1): the test only queued uncompressed requests into the window, so the mutant without the guard around the inflater passed. It now also inflates zlib streams into the window (built by hand from fixed Huffman codes, with a control run without remaps) and queues memory requests reading out of the window. The inflater mutant now dies in an access violation in 4 of 5 runs (a race, so not every run).

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 23:26:43 +01:00
42 changed files with 2039 additions and 3443 deletions

No files matched your search

+22 -5
View File
@@ -23,13 +23,16 @@ cargo build --locked -p bx-cli && target/debug/bx-cli preflight
| 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` |
| **The Ghidra results of the target build** (the static-analysis run: `RUN_REPORT.md`, `exports/`, `decompiled/`) covering its executable | Found and saved by `bx-cli setup --find` |
| At least 10 GiB of free disk space | Measured |
**The target build, the GDK and the Ghidra results are a hard requirement.** An agent that lacks even one of them does not work on this repository at all: no code, tests, reviews, merges, issues or documentation.
**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. |
| Target build, GDK, Ghidra results | `target/debug/bx-cli setup --find`. It searches the home folder, recognises the GDK by its header, the build by its structure (never by name) and the Ghidra results by their layout and the program they cover, and saves all three. |
| `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. |
@@ -37,13 +40,13 @@ cargo build --locked -p bx-cli && target/debug/bx-cli preflight
- 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).
- `setup --find` reports that the target build, the GDK or the Ghidra results covering the build are 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.
In those cases stop and do not work around it: no fixes, tests, reviews, merges or documentation "for someone else to verify". Work here is found by running the target build, located in the Ghidra results and checked against the GDK; an agent without all three 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).
`bx-cli setup` remembers the three 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`, `BX_GDK_ROOT` and `BX_GHIDRA_RESULTS` override it for one command.) Never commit those paths, and never put a path, file name, hash or byte from the target build, the GDK or the Ghidra results into a commit, issue or pull request (Section 6).
### Step 2 — Pick exactly one thing, in this order
@@ -75,6 +78,19 @@ Take the first that applies.
### Step 3 — Work one blocker
**Before touching any problem the game shows you, find out whether someone already has it.** This applies every time: to the blocker you picked, and to every further problem you meet along the way (a failed load, a refused request, an assert, a crash). Search by the log event, stub symbol, error code and the files you would change:
```sh
gh pr list --repo MacosPorters/betterxen --state open --search "<event, symbol or file>" --json number,title,headRefName
gh pr list --repo MacosPorters/betterxen --state merged --search "<event, symbol or file>" --limit 10 --json number,title,mergedAt
gh issue list --repo MacosPorters/betterxen --state open --search "<event, symbol or file>" --json number,title,labels
```
- **An open pull request covers it:** check out that branch (`gh pr checkout <n>`), run the build with it, and work there: report what you saw on the pull request, and push a fix to its branch or request changes. Do not write a second fix.
- **A merged pull request covers it:** sync with `origin/main` and run again before investigating.
- **An issue covers it:** take it up from the issue's notes, and link it from your pull request.
- **Nothing covers it:** carry on with step 1 below.
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.
@@ -99,6 +115,7 @@ Take the first that applies.
- `tests/conformance/` — Clean-room synthetic x86-64 PE32+ test binaries (auto-discovered via `test_*/CMakeLists.txt`).
- **Retired native-first code:** The earlier native-first workspace was retired from `main` per ADR 0006 and remains preserved permanently at Git tag `native-first-final`. Do not open native-only issues; if hybrid work requires an independent component (such as RDNA 2 decoding), file a focused track issue.
- **No unverified compatibility assumptions:** This is an active engineering foundation, not a verified Xbox game compatibility stack. Do not assume CrossOver, Rosetta 2, or D3DMetal provide Xbox runtime behavior without measurement.
- **GDK texture libraries (ADR 0010):** Console texture layouts (tiling) and BCPack decompression come from the GDK's own PC libraries, `xg_xs.dll` and `BCPack.dll`, which `bx-cli run` stages for the target build from the configured GDK. Do not reimplement them, and never commit or ship them.
---
@@ -156,7 +173,7 @@ _Reserved — policy migration in progress._
## 7. Claiming, Git Safety & Changelog
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.
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. Every problem met while running the game, not only the one picked, is searched for in open and merged pull requests and open issues before it is investigated; when a pull request covers it, check that branch out and work there (Section 0, Step 3). 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-<slug> -b track-<a..f>/<slug> origin/main
+24 -7
View File
@@ -10,6 +10,8 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- **Check for existing work before investigating any problem the game shows** (AGENTS.md Section 0 Step 3 and Section 7, `docs/process/working-method.md`). Every problem met while running the game, not only the picked blocker, is searched for in open and merged pull requests and open issues by its log event, stub symbol, error code and files. An open pull request that covers it is checked out and worked on, never duplicated. Prompted by a duplicate fix for physical-page DirectStorage requests made alongside #707.
- **The Ghidra results of the target build are required to work on the repository**, like the target build and the GDK (AGENTS.md Section 0, `docs/process/working-method.md`). An agent that lacks any of the three does not work on the repository. `bx-cli preflight` adds a `Ghidra results` row: present, and covering the configured target build's executable. `bx-cli setup --ghidra-results <dir>` saves them, and `setup --find` finds them by layout (`RUN_REPORT.md`, `decompiled/`, `exports/*/manifest.json` naming the program, `functions.csv`). `BX_GHIDRA_RESULTS` overrides the setting for one command. Unit tests cover an unset setting, a folder that isn't a results folder, results for another program, and results covering the target.
- **Roadmap, Picture stage: BetterXen writes its own shader translator** (repository owner's decision, 2026-11-29). The step that said to vendor the upstream GFX10-to-DXIL translator now describes a translator of our own in `shader-transpiler/`: one rule per instruction, control flow as numbered blocks, each rule checked against the console compiler.
- **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.
@@ -27,6 +29,15 @@ remains unsupported.
- `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
- **Unattended runs get past input screens and continuable asserts** (`docs/testing/target-build-review.md`, Diagnostics).
- **`GameInput.dll`:** `BX_INPUT_SCRIPT=A@40,DOWN@50.5,...` presses gamepad buttons at given seconds after the first reading, each for 300 ms, without window focus. Each press, and each entry it cannot read, is logged (`input_script`).
- **`bx_runtime_veh.dll`:** `BX_CONTINUE_ASSERTS=1` steps over an `int3` in the title's own executable instead of letting it reach the crash reporter, and logs each address once (`assert_continued`). An `int3` anywhere else is left alone.
- **Tests:** `test_gameinput_script` (readings at fixed times carry exactly the scripted buttons, and unreadable entries are skipped) and `test_veh_continue_asserts` (the executable's `int3` is stepped over twice; one outside any module is not). Both fail on `main`'s shims and pass twice with these.
- **The GDK's texture libraries at run time (ADR 0010).** Console texture layouts and BCPack come from the GDK's own PC libraries instead of being reimplemented.
- **`bx-cli run`** stages the configured GDK's `xg_xs.dll` (in place of the `xg_xs` shim) and `BCPack.dll` (named to `XCRDAPI.dll` through `BX_BCPACK_DLL`) when the executable is the configured target build, or with `--gdk-libraries`; `--no-gdk-libraries` turns it off. The libraries are recognised by their exports (`gdk_libs.rs`), copied into a temporary shim folder for the run, and never committed. Conformance tests keep BetterXen's own shims.
- **`d3d12_xs.dll`** answers `GetResourceAllocationInfo`, `GetResourceAllocationInfo1` and `GetResourceAllocationInfo2` for console texture layouts (`Layout >= 0x100`) with the GDK's XG size and base alignment (`gdk_xg.cpp`), other descriptions with the host's answer, laid out in order at their alignments. It enables XG's exclusive locking at device creation, since the title and the shim both create XG texture computers. Without the GDK's XG, sizes stay as before and the run log says so (`gdk_xg`).
- **Tests:** `test_d3d12_gdk_xg_sizes` loads a stand-in XG library with answers the test computes (not Microsoft's code) and checks the sizes, alignments, the two-description layout and the locking. On the previous `d3d12_xs.dll` 6 checks fail; with this change it passes twice. `bx-cli` unit tests cover recognising the libraries by their exports and merging them beside the shims.
- **Measured** on the target build (Apple Silicon, CrossOver 26.3, offline, scripted input): the launcher staged both libraries; XG answered 48 console-layout size queries; with #709, 0 page-destination errors, 0 zlib failures and 0 refused BCPack requests. 14 partial reads of compressed blocks remain, so the allocation size is not the only place the title gets a short size (#708 stays open).
- `GameInput.dll` exposes one keyboard-backed gamepad through v0 blocking enumeration and current readings. Enter or Space maps to A, Escape or Backspace to B, arrow keys to the D-pad, WASD and IJKL to the two sticks, Q/E to shoulders, Z/C to triggers, F/H to stick clicks, X/Y to the matching face buttons, and P/Tab to Menu/View. Input returns to neutral when another application owns the foreground.
- **D3DMetal capability checks for translated console shaders** (#671). `test_d3dmetal_translator_caps` measures, against the host D3D12 runtime, the features a translator of console code needs: SM 6.6 descriptors fetched by index (UAV, raw and typed SRVs, texture and sampler) run correctly; a 64-lane wave emulated over a 64-thread group gives the 64-lane answers through groupshared memory and through merged 32-lane host waves; amplification and mesh shaders draw correctly. With the 64-bit atomic results of `test_d3dmetal_gpu_limits` (native 64-bit atomics are not run even though D3DMetal reports support; the lock emulation with a 1024 cap is exact), no need is blocked. Results are in [D3DMetal GPU limits](docs/research/d3dmetal-gpu-limits.md#capability-checks-for-translated-console-shaders-671).
- `xgameruntime.dll` serves `XGameSaveGetContainerInfo` (slot 13) and `XGameSaveEnumerateContainerInfoByName` (slot 15) on `IXGameSaveImpl` (#667). `XGameSaveGetContainerInfo` reads container metadata without loading blob payloads and, when the named container does not exist, succeeds without invoking the callback (source rank 3 inference). `XGameSaveEnumerateContainerInfoByName` filters containers by name prefix (treating `nullptr` or empty prefix as all containers), sorts by name, and stops early when the callback returns `false`. `test_xgameruntime_saves` checks both slots through `QueryApiImpl`.
@@ -93,19 +104,25 @@ remains unsupported.
- `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`: physical-page destinations are mapped when the request runs, partial reads of compressed blocks are delivered, and BCPack requests can be decoded.**
- **Page array timing:** a title can fill the `DestinationPageArray` of a `DestinationIsPhysicalPages` request after `EnqueueRequest` returns. #707 read the array at enqueue, so such requests failed (in the target build, about 290 per run named page 0). The array is now read, and its pages mapped, when the request runs; they are unmapped once it is fulfilled.
- **Partial compressed reads:** a title may ask for only the first `DestinationSize` bytes of a zlib block (in the target build, 8 to 128 KiB blocks read 4 to 16 KiB at a time; 16 failures per run). The whole stream is decoded, its Adler-32 checked, and its first `DestinationSize` bytes delivered; a stream shorter than the destination is still an error. Logged as `dstorage_zlib_partial`.
- **BCPack:** a request with `BcpackMode` 1 to 7 is decoded with `BCPackDecompress` from the GDK's own `BCPack.dll` when `BX_BCPACK_DLL` names it (the collaborator's GDK; nothing from the GDK is shipped). Without it, or combined with zlib, BCPack stays refused with `E_NOTIMPL`. Logged as `bcpack_codec` and `dstorage_bcpack_failed`.
- **Tests:** `test_xcrdapi_page_destination` (24 checks) adds a page array filled after `EnqueueRequest` and a 4096-byte zlib destination from a 136000-byte stream (exact first part, nothing written past it). Both fail on the previous shim (4 checks) and pass twice with this one. BCPack needs the GDK's decoder, so it is not covered by a conformance test.
- **`GetFrameStatisticsX` is implemented** (#701). Slot 81 of the Xbox device table returned `E_NOTIMPL`, which the documented method never returns. It now answers as the authorized GDK documentation describes: frame-event (ORIGIN: wait call, signal and wait return) and present (PresentX call and return) statistics per frame pipeline token for the last 17 frames, in QueryPerformanceCounter ticks; `S_FALSE` when none of the requested types is available; `E_INVALIDARG` for unknown tokens, invalid type sets and invalid list arrangements. Interval, power-scaling, render, display and input statistics have no host source and are never reported; `GPUProcessTime` is 0 (not measured). Test: `test_d3d12_frame_statistics_x`.
- **`CreateCommittedResourceX` is implemented** (#696). Slot 76 of the Xbox device table takes a `D3D12XBOX_RESOURCE_DESC`, which is the PC resource description followed by `DccOptions` (authorized GDK header). It now creates the resource from the PC part through the same path as `CreateCommittedResource` (console format translation, the `XMemAlloc` request a title's hook sees); `DccOptions`, console colour compression, has no host counterpart and is logged and ignored. Until now the slot returned `E_NOTIMPL`, and the target build exited with status 99 about a second after it was refused. `tools/gen_xbox_tables.py` routes the slot to the new entry point; the regenerated table differs only there. Test: `test_d3d12_committed_resource_x`.
- **`d3d12_xs.dll`: index and vertex data bound from plain title memory are drawn.** A title keeps such data in its own memory with no Direct3D resource, and may write it after recording the draw. A bound range now gets a CPU-writable host buffer (once; later ranges inside it reuse it) and every range bound on a list is copied from the title memory when the list is submitted (`bx_xbox_bind_title_memory`, `placed_x.cpp`). This replaces leaving such bindings empty; only memory that is not readable is still left empty and logged as unimplemented. Tests: `test_d3d12_title_memory_geometry` (26 checks, pixel readback, data written after recording and changed between submissions); `test_d3d12_unbacked_buffers` now covers the unreadable case.
- **`d3d12_xs.dll`: console rectangle lists are drawn.** `D3D_PRIMITIVE_TOPOLOGY_RECTLIST` (17) and the pipeline topology type `D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT` (19) are Xbox extensions (GDK `d3d12_xs.h`): three vertices per rectangle, the fourth corner `v0 + v2 - v1`. The host knew neither value, so a title's full-screen passes drew half a rectangle or nothing. A rectangle list is now drawn as triangle strips (`rect_list.cpp`): the pipeline is created with the triangle type, and a non-indexed draw builds four vertices per rectangle from the title's vertex data and the pipeline's input layout. Indexed rectangle lists and quad lists are not emulated and are logged as unimplemented. Test: `test_d3d12_rect_list` (25 checks, pixel readback).
- **`bx_runtime_veh.dll`: a CLWB range loop completes in one exception.** A title flushes an address range with `clwb [reg]; add reg, 0x40; cmp reg, <reg64>; jbe|jb`; each CLWB trapped under Rosetta, about 94,000 exception round trips per 6 MiB buffer. CLWB changes no register, flag or memory, so the handler now advances the pointer register to the last value the loop would have used and the title's own add/cmp/jcc leaves the loop. Other forms keep the per-instruction path. Test: `test_veh_clwb_loop` (15 checks; without the fix the four loop cases take one exception per line).
- **Committed render targets request the console's size from XMemAlloc** (#695). The console lays out a 2D render-target or unordered-access texture with one mip and one sample in 64 KB tiles (64KB_R_X for every size: 128x128 elements at 4 bytes, 128x64 at 8, 64x64 at 16, 256x128 at 2, 256x256 at 1; authorized GDK XG library), and a title that hooks XMemAlloc sizes its pool for those requests and asserts that less than 2 MB is left over. `d3d12_xs.dll` requested the host's size instead, 1920x1080 RGBA8 as 128 pages where the console takes 135, and on the Series S path the target build stopped on that assertion. The XMemAlloc request for those textures is now the tile size, computed from the title's format; every other resource keeps the host's size, and XG's render-target compression metadata after the tiles (8 KB to 96 KB in the cases measured) is not modelled. `GetResourceAllocationInfo` still answers with the host's size. Test: `test_d3d12_committed_tile_size`.
- **XCRDAPI holds an xmem guard while accessing title memory** (#668). Replacing a mapped view on Windows or Wine can temporarily make pages in that view inaccessible. DirectStorage reads and writes that can touch title memory now hold the shared guard while xmem mapping and freeing operations hold it exclusively. A loaded xmem DLL without both guard exports produces a warning. The guard covers DirectStorage accesses through BetterXen.
- **The console type is published where a title reads it** (#692). A title can read the REG_DWORD `ConsoleMode` under `HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM` instead of calling `XSystemGetDeviceType`: 0x60 is Series S, 0x64 Series X and 0x68 the Scarlett devkit, and without the value the title takes itself for a PC and sizes its memory for Series X. Wine has no such value, so under the Lockhart profile the target build asked for its Series X memory set and stopped on the 8 GiB budget. `bx-cli run` writes the value in the selected Wine environment before launching the guest, using the same profile as `XSystemGetDeviceType` (0x60 for Lockhart, 0x64 for Anaconda). The test `test_console_mode` reads it the way the title does and checks it against the profile and `XSystemGetDeviceType`.
- **`CreateCommittedResourceX` is implemented** (#696). Slot 76 of the Xbox device table takes a `D3D12XBOX_RESOURCE_DESC`, which is the PC resource description followed by `DccOptions` (authorized GDK header). It now creates the resource from the PC part through the same path as `CreateCommittedResource` (console format translation, the `XMemAlloc` request a title's hook sees); `DccOptions` (a struct of `CompressionLevel` and `ColorTransform`), console colour compression, has no host counterpart; both fields are logged for the first 8 calls and ignored. Until now the slot returned `E_NOTIMPL`, and the target build exited with status 99 about a second after it was refused. `tools/gen_xbox_tables.py` routes the slot to the new entry point; the regenerated table differs only there. Test: `test_d3d12_committed_resource_x`.
- `xmem.dll!XMemGetWorkingSetStatistics` takes the documented `(WorkingSetFlags, Statistics)` and fills the documented 120-byte `XMEM_WORKING_SET_STATISTICS` (source: the authorized GDK header). Before, it took `(out_stats, stats_size)` and wrote BetterXen's own 32-byte `bx_xmem_stats_t`. A title calling it as documented had its flags read as the output address and its structure pointer as the size, and the shim zeroed memory at the flags value. A project-authorized target build calls it on a tools-memory path with the tools and kernel-pool flags and treats `FALSE` as fatal; runs have not reached that path yet.
- **Values:** the whole structure is written, whatever the flags. `GameLimit` is the title cap, `GameUsed` everything the cap counts (XMem heap, virtual commits, physical pages and external charges), `GameUsedPeak` its highest value and `GameAllocatedPhysicalPageCount` the 64 KiB physical pages. The tools fields are 0, since `XMemIsToolsMemAvailable` is `FALSE`. The counters the host does not have or xmem does not count are 0 (stack, GPU-optimal bandwidth, kernel pool, DirectStorage, frame-preserve buffer, page tables), and so are the reserved words. These values are BetterXen's inference.
- **Refusals:** a NULL structure, or flags outside the five `XMEM_WORKING_SET_*` values, fails with `ERROR_INVALID_PARAMETER` and logs `working_set_statistics`. `bx_xmem_get_internal_stats` is unchanged for internal callers.
- **Tests:** new `test_xmem_working_set` reads the structure between guard bands at offsets written out from the header, with the tools and kernel-pool flags, `XMEM_WORKING_SET_TITLE` and `XMEM_WORKING_SET_ALL`. Against the previous `xmem.dll` it fails with an access violation inside the call. `test_xmem`, `test_xmem_physical`, `test_xmem_external_charge` and `test_d3d12_placed` use the documented form. `test_xmem_physical` now reads its two aliased page views through `volatile`: the compiler cannot see that they share a page, and after this change it scheduled the read before the write.
- **Not covered:** `XMemVirtualQuery` and `XMemTransferMemory` still differ from their documented signatures (#642).
- **`XCRDAPI.dll`: DirectStorage requests can write into physical pages** (#705). With `DestinationIsPhysicalPages` (bit 21 of `DSTORAGE_REQUEST_OPTIONS`), the destination of an Xbox request is an array of 64 KB page numbers from `XMemAllocatePhysicalPages` and a 16-bit offset into the first page, at +0x08 and +0x10 (authorized GDK header). `IDStorageQueueX::EnqueueRequest` refused such requests with `E_NOTIMPL`, and the target build stopped at a breakpoint about two milliseconds later (exit status 3). The request now maps its pages through `xmem.dll`'s `XMemMapPhysicalPages` with a NULL address (the existing BetterXen extension) into a span of its own, writes the destination there, file or memory source, plain or zlib, and unmaps the span once it is fulfilled; the pages are sections, so the title's views see the bytes. A physical-page source (`SourceIsPhysicalPages`) is still refused and logged as `EnqueueRequest_physical_page_source`. Test: `test_xcrdapi_page_destination` (19 checks: a zlib file request across three pages given out of order from an offset, an uncompressed memory request across a page boundary, an unallocated page number, the refused source form).
- **`d3d12_xs.dll`: index and vertex data bound from plain title memory are drawn.** A title keeps such data in its own memory with no Direct3D resource, and may write it after recording the draw. A bound range now gets a CPU-writable host buffer (once; later ranges inside it reuse it) and every range bound on a list is copied from the title memory when the list is submitted (`bx_xbox_bind_title_memory`, `placed_x.cpp`). This replaces leaving such bindings empty; only memory that is not readable is still left empty and logged as unimplemented. Tests: `test_d3d12_title_memory_geometry` (26 checks, pixel readback, data written after recording and changed between submissions); `test_d3d12_unbacked_buffers` now covers the unreadable case.
- **`d3d12_xs.dll`: console rectangle lists are drawn.** `D3D_PRIMITIVE_TOPOLOGY_RECTLIST` (17) and the pipeline topology type `D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT` (19) are Xbox extensions (GDK `d3d12_xs.h`): three vertices per rectangle, the fourth corner `v0 + v2 - v1`. The host knew neither value, so a title's full-screen passes drew half a rectangle or nothing. A rectangle list is now drawn as triangle strips (`rect_list.cpp`): the pipeline is created with the triangle type, and a non-indexed draw builds four vertices per rectangle from the title's vertex data and the pipeline's input layout. Indexed rectangle lists and quad lists are not emulated and are logged as unimplemented. Test: `test_d3d12_rect_list` (25 checks, pixel readback).
- **`bx_runtime_veh.dll`: a CLWB range loop completes in one exception.** A title flushes an address range with `clwb [reg]; add reg, 0x40; cmp reg, <reg64>; jbe|jb`; each CLWB trapped under Rosetta, about 94,000 exception round trips per 6 MiB buffer. CLWB changes no register, flag or memory, so the handler now advances the pointer register to the last value the loop would have used and the title's own add/cmp/jcc leaves the loop. Other forms keep the per-instruction path. Test: `test_veh_clwb_loop` (15 checks; without the fix the four loop cases take one exception per line).
- **Committed render targets request the console's size from XMemAlloc** (#695). The console lays out a 2D render-target or unordered-access texture with one mip and one sample in 64 KB tiles (64KB_R_X for every size: 128x128 elements at 4 bytes, 128x64 at 8, 64x64 at 16, 256x128 at 2, 256x256 at 1; authorized GDK XG library), and a title that hooks XMemAlloc sizes its pool for those requests and asserts that less than 2 MB is left over. `d3d12_xs.dll` requested the host's size instead, 1920x1080 RGBA8 as 128 pages where the console takes 135, and on the Series S path the target build stopped on that assertion. The XMemAlloc request for those textures is now the tile size, computed from the title's format; every other resource keeps the host's size, and XG's render-target compression metadata after the tiles (8 KB to 96 KB in the cases measured) is not modelled. `GetResourceAllocationInfo` still answers with the host's size. Test: `test_d3d12_committed_tile_size`.
- **The console type is published where a title reads it** (#692). A title can read the REG_DWORD `ConsoleMode` under `HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM` instead of calling `XSystemGetDeviceType`: 0x60 is Series S, 0x64 Series X and 0x68 the Scarlett devkit, and without the value the title takes itself for a PC and sizes its memory for Series X. Wine has no such value, so under the Lockhart profile the target build asked for its Series X memory set and stopped on the 8 GiB budget. `bx-cli run` writes the value in the selected Wine environment before launching the guest, using the same profile as `XSystemGetDeviceType` (0x60 for Lockhart, 0x64 for Anaconda). `--profile` is matched without regard to case, as the shims match `BX_PROFILE`, and a value other than `lockhart` or `anaconda` is refused, so the two cannot name different consoles. The test `test_console_mode` reads it the way the title does and checks it against the profile and `XSystemGetDeviceType`.
- **XCRDAPI holds an xmem guard while accessing title memory** (#668). Replacing a mapped view on Windows or Wine can temporarily make pages in that view inaccessible. DirectStorage reads and writes that can touch title memory now hold the shared guard while xmem mapping and freeing operations hold it exclusively. A loaded xmem DLL without both guard exports produces a warning. The guard covers DirectStorage accesses through BetterXen. `test_xcrdapi_remap_guard` exercises memory-to-memory stores into a window, zlib streams inflated into it and memory requests reading out of it while it is remapped; accesses by the title's own threads are not covered.
- **`d3d12_xs.dll`: an index or vertex binding at a title address without a host buffer no longer crashes the process.** A title binds index and vertex data by address in plain title memory, with no Direct3D resource behind it. The address reached D3DMetal unchanged and it read through a null buffer (`IASetIndexBuffer`). Such a binding is now left empty and logged as unimplemented (`IASetIndexBuffer(title memory without a host buffer)`, likewise `IASetVertexBuffers`); bindings inside resources BetterXen created are translated as before. Supplying the data is separate work. Test: `test_d3d12_unbacked_buffers` (13 checks; without the fix it dies with the same null read).
- **`d3d12_xs.dll`: console-only DXGI formats and depth-stencil unordered-access views no longer end the process.** The Xbox Series `DXGI_FORMAT` enumeration has values the PC one lacks (116-120, 189, 190; GDK `d3d12_xs.h`). D3DMetal turns one into an invalid Metal pixel format and Metal aborts, which a target build's crash reporter then turned into either "exit status 5" or a stall with every thread stopped.
- **Formats:** `console_formats.h` maps each to the nearest host format (a depth texture is created typeless, each view names the concrete format). The three `GetResourceAllocationInfo` forms, `CreatePlacedResource`, `CreateReservedResource`, the four view-creation methods, the committed-resource forms and the placed (X) resource and view forms translate before the host call.
-1
View File
@@ -19,4 +19,3 @@ EXPORTS
bx_xmem_release_charge_external
bx_xmem_remap_guard_enter @18
bx_xmem_remap_guard_leave @19
bx_xmem_write_physical_pages @20
+1
View File
@@ -17,6 +17,7 @@
- [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 0010: The GDK's texture libraries at run time](adr/0010-gdk-texture-libraries.md) — Accepted: console texture layouts and BCPack come from the GDK's own PC libraries (`xg_xs.dll`, `BCPack.dll`), staged by `bx-cli run` for the target build from each machine's GDK; never reimplemented, committed or shipped.
- [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
+29
View File
@@ -0,0 +1,29 @@
# ADR 0010: The GDK's texture libraries at run time
Status: **Accepted** (2026-11-30, by the repository owner). The evidence is from local Apple Silicon runs by the implementer.
## Context
Console textures differ from PC textures in two ways that BetterXen had no answer for:
- **Tiled layouts.** A console texture carries a swizzle layout (`D3D12XBOX_TEXTURE_LAYOUT`, `0x100 | XG_SWIZZLE_MODE`; most of the target build's textures use the 4 KB "S" mode). A title sizes its placements and loads from the layout, and the bytes arrive tiled. BetterXen's `xg_xs` shim answers every layout as linear, so sizes were too small (#708) and textures could not be uploaded.
- **BCPack.** Texture data in the target build's archives is BCPack-compressed (`DSTORAGE_BCPACK_MODE` 1 to 7). There is no public specification of the format. `XCRDAPI.dll` refused those requests (34 per run).
The GDK the project is authorized to use contains Microsoft's **PC builds** of both: the XG library (`xg_xs.dll`, which computes layouts and copies between tiled and linear data) and the BCPack decoder (`BCPack.dll`). Both are pure computation, with only standard Windows imports, and load under CrossOver. Measured on the target build with them in place: the GDK's XG answers the device's console-layout size queries, detiling through it produced the first real image of the title's menu artwork, and BCPack requests decode.
Reimplementing either would mean deriving the console's tiling rules and the BCPack format from observation, with the result only ever approximating Microsoft's.
## Decision
1. **Use Microsoft's libraries at run time; do not reimplement them.** `bx-cli run` stages the GDK's `xg_xs.dll` in place of BetterXen's shim and `BCPack.dll` beside it, and names the decoder to `XCRDAPI.dll` through `BX_BCPACK_DLL` (`launcher/crates/bx-cli/src/gdk_libs.rs`). `d3d12_xs` uses the XG library when it is the loaded `xg_xs.dll` (`shims/d3d12_xs/gdk_xg.cpp`).
2. **From each machine's own GDK.** The libraries come from the GDK configured by `bx-cli setup`, which preflight already requires. They are found by their exports, not their place in the GDK.
3. **Never committed or shipped**, unless the project records an authorization that covers redistributing them. Commits name only the documented interfaces (`XGCreateTextureComputer`, `BCPackDecompress`, ...), as with every other GDK contract.
4. **Only for the target build.** Conformance tests check BetterXen's own shims, so the GDK's libraries are staged only when the executable is the configured target build, or with `--gdk-libraries`. `--no-gdk-libraries` turns them off.
5. **BetterXen's `xg_xs` shim stays** as the fallback (and for CI, which has no GDK). Without the GDK's XG, console textures are sized linearly, and the run log says so (`gdk_xg`).
## Consequences
- Correct console layouts and BCPack decoding now, without a reverse-engineering effort for either.
- Running the title needs the GDK on the machine. Preflight already requires it.
- Conformance tests cannot call Microsoft's libraries in CI. Tests cover BetterXen's side of the contract with stand-ins whose answers the test computes (`test_d3d12_gdk_xg_sizes`). Microsoft's results are exercised on machines with the GDK.
- Agents need no special knowledge: the target build's run protocol stages the libraries automatically, and `CLAUDE.md` Section 1 says not to reimplement them.
+12 -8
View File
@@ -2,7 +2,7 @@
**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?*
BetterXen is built by collaborators who each have the project-authorized target build, the GDK and the target build's Ghidra results, 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.
@@ -13,11 +13,14 @@ No agent works without all of these. `bx-cli preflight` checks them and fails if
- 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;
- **the Ghidra results of the target build**: the static-analysis run (`RUN_REPORT.md`, `exports/`, `decompiled/`) covering its executable;
- 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.
The target build, the GDK and the Ghidra results are a hard requirement: an agent that lacks even one of them does not work on the repository at all.
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".
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, the target build by its structure (never by name) and the Ghidra results by their layout and the program they cover, and saves all three 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, located in the Ghidra results and checked against the GDK. Without all three 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, the GDK or the Ghidra results are 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
@@ -82,11 +85,12 @@ run → signature → draft pull request (the claim) → evidence → smallest f
```
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.
2. **Is it already someone's?** Before investigating any problem the game shows (the picked blocker or one met along the way), search open and merged pull requests and open issues for its log event, stub symbol, error code and the files a fix would touch. If an open pull request covers it, check that branch out, run with it and work there. If a merged one does, sync and run again. On 2026-11-30 a session fixed physical-page DirectStorage requests in parallel with an open pull request for the same problem (#707), and found the overlap only afterwards.
3. **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.
4. **Smallest fix.** Only what removes this blocker. A new cross-DLL export still goes through an `[ABI]` pull request first.
5. **A test for the contract.** It fails without the fix and passes twice in a row in the same bottle.
6. **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.
7. **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.
+3 -1
View File
@@ -94,7 +94,7 @@ sandbox-exec -p "$PROFILE" /usr/bin/curl -sS -m 5 https://example.com >/dev/null
# 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 \
BX_TRACE_D3D=0 BX_NULL_RENDER=1 BX_PRESENT_DUMP='Z:\<frames folder>' BX_INPUT_SCRIPT=A@40,A@50 \
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>
@@ -116,6 +116,8 @@ All switches are off unless set, and none changes behaviour beyond what its row
| `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 |
| `BX_INPUT_SCRIPT=<presses>` | `GameInput` | Scripted gamepad presses for unattended runs, without window focus: comma-separated `BUTTON@SECONDS` (`A@40,DOWN@50.5,A@52`), each held 300 ms, timed from the first gamepad reading. Buttons `MENU VIEW A B X Y UP DOWN LEFT RIGHT`. Each press is logged (`input_script`), and so is each entry that cannot be read |
| `BX_CONTINUE_ASSERTS=1` | `bx_runtime_veh` | Steps over an `int3` in the title's own executable (a continuable assert) instead of letting it reach the title's crash reporter. Each address is logged once (`assert_continued`), so the report still lists every assert. Use it to get past a known assert to the next blocker, and say so in the evidence |
Their output can contain title addresses and file names, so it goes only into the private evidence store.
+184
View File
@@ -0,0 +1,184 @@
//! The GDK's own texture libraries, staged for runs of the target build (ADR 0010).
//!
//! Console textures use tiled layouts and BCPack compression. BetterXen does not reimplement
//! either: a run of the target build loads Microsoft's PC builds of the GDK's XG library
//! (`xg_xs.dll`, in place of BetterXen's `xg_xs` shim) and BCPack decoder (`BCPack.dll`, named to
//! `XCRDAPI.dll` through `BX_BCPACK_DLL`) from the GDK configured on this machine. Nothing from
//! the GDK is committed or shipped.
//!
//! The libraries are recognised by what they export, never by their place in the GDK: an
//! x86-64 PE32+ file named `xg_xs.dll` that exports `XGComputeTexture2DLayout` and does not
//! import `xmem.dll` (the console build does), and one named `BCPack.dll` that exports
//! `BCPackDecompress`. Conformance tests keep BetterXen's own shim: the GDK's are staged only
//! for the configured target build, or with `--gdk-libraries`.
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use bx_probe::probe_pe32_plus;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct GdkLibraries {
pub xg: Option<PathBuf>,
pub bcpack: Option<PathBuf>,
}
fn contains(bytes: &[u8], needle: &[u8]) -> bool {
bytes.windows(needle.len()).any(|w| w == needle)
}
/// Whether `bytes` are the PC build of the GDK's XG library.
pub fn is_pc_xg(bytes: &[u8]) -> bool {
let Ok(summary) = probe_pe32_plus(bytes) else {
return false;
};
contains(bytes, b"XGComputeTexture2DLayout\0")
&& contains(bytes, b"XGCreateTextureComputer\0")
&& !summary
.imports
.keys()
.any(|dll| dll.eq_ignore_ascii_case("xmem.dll"))
}
/// Whether `bytes` are the GDK's BCPack decoder.
pub fn is_bcpack(bytes: &[u8]) -> bool {
probe_pe32_plus(bytes).is_ok() && contains(bytes, b"BCPackDecompress\0")
}
/// Finds the two libraries under `root` (bounded depth). When the GDK holds several builds,
/// the first by path order is used, so the choice is the same on every run.
pub fn find(root: &Path) -> GdkLibraries {
let mut xg = Vec::new();
let mut bcpack = Vec::new();
let mut stack = vec![(root.to_path_buf(), 0usize)];
while let Some((dir, depth)) = stack.pop() {
let Ok(entries) = fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(kind) = entry.file_type() else {
continue;
};
if kind.is_dir() {
if depth < 14 {
stack.push((path, depth + 1));
}
continue;
}
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
if name != "xg_xs.dll" && name != "bcpack.dll" {
continue;
}
let Ok(bytes) = fs::read(&path) else {
continue;
};
if name == "xg_xs.dll" && is_pc_xg(&bytes) {
xg.push(path);
} else if name == "bcpack.dll" && is_bcpack(&bytes) {
bcpack.push(path);
}
}
}
xg.sort();
bcpack.sort();
GdkLibraries {
xg: xg.into_iter().next(),
bcpack: bcpack.into_iter().next(),
}
}
/// Builds `out` as a copy of the shim folder's files with the GDK's libraries added: its
/// `xg_xs.dll` replaces BetterXen's shim, and `BCPack.dll` sits beside it. Returns the path of
/// the staged `BCPack.dll`, when there is one.
pub fn merge_shims(shims: &Path, libs: &GdkLibraries, out: &Path) -> io::Result<Option<PathBuf>> {
fs::create_dir_all(out)?;
for entry in fs::read_dir(shims)? {
let entry = entry?;
if entry.file_type()?.is_file() {
fs::copy(entry.path(), out.join(entry.file_name()))?;
}
}
if let Some(xg) = &libs.xg {
fs::copy(xg, out.join("xg_xs.dll"))?;
}
match &libs.bcpack {
Some(bcpack) => {
let staged = out.join("BCPack.dll");
fs::copy(bcpack, &staged)?;
Ok(Some(staged))
}
None => Ok(None),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A minimal x86-64 PE32+ image with no sections, followed by `tail`. Import tables are
/// not modelled, so "imports xmem.dll" is covered by `is_pc_xg` on a real probe only.
fn pe(tail: &[u8]) -> Vec<u8> {
let mut b = vec![0u8; 0x200];
b[0..2].copy_from_slice(b"MZ");
b[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
b[0x40..0x44].copy_from_slice(b"PE\0\0");
b[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes()); // machine
b[0x54..0x56].copy_from_slice(&240u16.to_le_bytes()); // SizeOfOptionalHeader
b[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes()); // PE32+
b[0x58 + 108..0x58 + 112].copy_from_slice(&16u32.to_le_bytes()); // NumberOfRvaAndSizes
b.extend_from_slice(tail);
b
}
#[test]
fn recognises_the_libraries_by_their_exports() {
assert!(is_pc_xg(&pe(
b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"
)));
// BetterXen's own shim exports only what titles import.
assert!(!is_pc_xg(&pe(
b"XGCreateTextureComputer\0XGSuggestSwizzleMode\0"
)));
assert!(!is_pc_xg(
b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"
));
assert!(is_bcpack(&pe(b"BCPackCompress\0BCPackDecompress\0")));
assert!(!is_bcpack(&pe(b"BCPackCompress\0")));
}
#[test]
fn finds_by_content_and_merges_beside_the_shims() {
let root = std::env::temp_dir().join(format!("bx-gdk-libs-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let gdk = root.join("gdk");
fs::create_dir_all(gdk.join("a/b")).unwrap();
fs::create_dir_all(gdk.join("c")).unwrap();
fs::write(
gdk.join("a/b/xg_xs.dll"),
pe(b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"),
)
.unwrap();
fs::write(gdk.join("c/xg_xs.dll"), pe(b"XGCreateTextureComputer\0")).unwrap(); // not the PC library
fs::write(gdk.join("c/BCPack.dll"), pe(b"BCPackDecompress\0")).unwrap();
let libs = find(&gdk);
assert_eq!(libs.xg, Some(gdk.join("a/b/xg_xs.dll")));
assert_eq!(libs.bcpack, Some(gdk.join("c/BCPack.dll")));
let shims = root.join("shims");
fs::create_dir_all(&shims).unwrap();
fs::write(shims.join("xg_xs.dll"), b"shim").unwrap();
fs::write(shims.join("d3d12_xs.dll"), b"d3d12").unwrap();
let out = root.join("out");
let staged = merge_shims(&shims, &libs, &out).unwrap();
assert_eq!(staged, Some(out.join("BCPack.dll")));
assert_eq!(fs::read(out.join("d3d12_xs.dll")).unwrap(), b"d3d12");
assert_eq!(
fs::read(out.join("xg_xs.dll")).unwrap(),
fs::read(gdk.join("a/b/xg_xs.dll")).unwrap()
);
assert_eq!(fs::read(shims.join("xg_xs.dll")).unwrap(), b"shim");
let _ = fs::remove_dir_all(&root);
}
}
+264 -10
View File
@@ -1,6 +1,7 @@
//! Track A (M1-A1): Native ARM64 macOS CLI for BetterXen hybrid execution.
mod drives;
mod gdk_libs;
mod stage;
mod supervise;
@@ -26,6 +27,11 @@ ext-ms-win-rtcore-ntuser-window-l1-1-0,ext-ms-win-rtcore-ntuser-window-ansi-l1-1
/// Accepted `--backend` values. CrossOver ignores an unknown value silently, so one is refused.
const BACKENDS: [&str; 4] = ["d3dmetal", "dxmt", "dxvk", "wined3d"];
/// Accepted `--profile` values. The shims compare `BX_PROFILE` without regard to case and take
/// anything but "anaconda" for Lockhart, while `ConsoleMode` is chosen here, so the value is
/// normalized and an unknown one is refused instead of the two disagreeing.
const PROFILES: [&str; 2] = ["lockhart", "anaconda"];
const SAFE_CHILD_PATH: &str = "/usr/bin:/bin:/usr/sbin:/sbin";
const HOST_ENV_ALLOWLIST: &[&str] = &[
@@ -63,12 +69,12 @@ fn usage_text() -> &'static str {
bx-cli doctor Inspect Apple Silicon host, Rosetta 2, CrossOver & mingw-w64\n\
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] Remember where the target build and the GDK are on this machine (saved outside the repository); --find searches the home folder for them\n\
bx-cli preflight Check everything work needs: host, CrossOver, the target build, the GDK, disk space. Fails if anything is missing\n\
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] [--ghidra-results <dir>] Remember where the target build, the GDK and the target build's Ghidra results are on this machine (saved outside the repository); --find searches the home folder for them\n\
bx-cli preflight Check everything work needs: host, CrossOver, the target build, the GDK, the Ghidra results, disk space. Fails if anything is missing\n\
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
bx-cli report <log.jsonl>... Run report per log (one log = one run), then a summary with blocker signatures\n\
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)]\n\
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix)\n"
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)] [--gdk-libraries | --no-gdk-libraries]\n\
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix; the GDK's XG and BCPack libraries are staged for the configured target build)\n"
}
fn run_capture(program: &str, args: &[&str]) -> Option<String> {
@@ -233,6 +239,57 @@ fn local_setting(env_name: &str, key: &str, config: &BTreeMap<String, String>) -
const TARGET_EXE_KEY: &str = "target_exe";
const GDK_ROOT_KEY: &str = "gdk_root";
const GHIDRA_RESULTS_KEY: &str = "ghidra_results";
/// The static-analysis results of the target build, recognised by structure: a folder with the
/// run's `RUN_REPORT.md`, a `decompiled/` folder, and `exports/<program>/` folders each holding a
/// `manifest.json` (naming the program) and a `functions.csv`.
const GHIDRA_REPORT: &str = "RUN_REPORT.md";
/// The `"program"` value of an exports manifest, read without a JSON parser.
fn manifest_program(text: &str) -> Option<String> {
let rest = &text[text.find("\"program\"")? + "\"program\"".len()..];
let rest = rest
.trim_start()
.strip_prefix(':')?
.trim_start()
.strip_prefix('"')?;
Some(rest[..rest.find('"')?].to_owned())
}
/// The programs a Ghidra results folder covers, or `None` when it is not one.
fn ghidra_programs(root: &Path) -> Option<Vec<String>> {
if !root.join(GHIDRA_REPORT).is_file() || !root.join("decompiled").is_dir() {
return None;
}
let mut programs = Vec::new();
for entry in fs::read_dir(root.join("exports")).ok()?.flatten() {
let dir = entry.path();
if !dir.join("functions.csv").is_file() {
continue;
}
if let Some(program) = fs::read_to_string(dir.join("manifest.json"))
.ok()
.and_then(|text| manifest_program(&text))
{
programs.push(program);
}
}
(!programs.is_empty()).then_some(programs)
}
/// Whether the results cover the executable at `target` (by its file name, compared on this
/// machine only).
fn ghidra_covers(root: &Path, target: &Path) -> bool {
let Some(name) = target
.file_name()
.map(|n| n.to_string_lossy().to_ascii_lowercase())
else {
return false;
};
ghidra_programs(root)
.is_some_and(|programs| programs.iter().any(|p| p.to_ascii_lowercase() == name))
}
/// An Xbox Series title's executable is recognised by structure, never by name: a large PE32+
/// file that imports the console's D3D12 library. BetterXen's own test executables import it
@@ -273,6 +330,7 @@ fn gdk_root_for(home: &Path, header: &Path) -> Option<PathBuf> {
struct Found {
gdk_roots: Vec<PathBuf>,
target_exes: Vec<PathBuf>,
ghidra_results: Vec<PathBuf>,
/// The search gave up before visiting everything.
truncated: bool,
}
@@ -318,7 +376,13 @@ fn search_for_materials(home: &Path) -> Found {
stack.push((path, depth + 1));
}
} else if kind.is_file() {
if name_text == GDK_MARKER {
if name_text == GHIDRA_REPORT {
if let Some(dir) = path.parent()
&& ghidra_programs(dir).is_some()
{
found.ghidra_results.push(dir.to_path_buf());
}
} else if name_text == GDK_MARKER {
if let Some(root) = gdk_root_for(home, &path)
&& !found.gdk_roots.contains(&root)
&& check_gdk_root(root.to_str()).is_ok()
@@ -335,6 +399,7 @@ fn search_for_materials(home: &Path) -> Found {
}
found.gdk_roots.sort();
found.target_exes.sort();
found.ghidra_results.sort();
// The GDK ships tools that import the same library; they are not titles.
let roots = found.gdk_roots.clone();
found
@@ -409,7 +474,12 @@ fn distinct_builds_by(candidates: Vec<PathBuf>, siblings: impl Fn(&Path) -> usiz
fn find_materials(config: &mut BTreeMap<String, String>) -> bool {
let need_target = check_target_exe(config.get(TARGET_EXE_KEY).map(String::as_str)).is_err();
let need_gdk = check_gdk_root(config.get(GDK_ROOT_KEY).map(String::as_str)).is_err();
if !need_target && !need_gdk {
let need_ghidra = check_ghidra_for_target(
config.get(GHIDRA_RESULTS_KEY).map(String::as_str),
config.get(TARGET_EXE_KEY).map(String::as_str),
)
.is_err();
if !need_target && !need_gdk && !need_ghidra {
return false;
}
let Some(home) = env::var_os("HOME").map(PathBuf::from) else {
@@ -417,7 +487,7 @@ fn find_materials(config: &mut BTreeMap<String, String>) -> bool {
return false;
};
println!(
"Searching the home folder for the GDK and the target build (this can take a minute)..."
"Searching the home folder for the GDK, the target build and its Ghidra results (this can take a minute)..."
);
let found = search_for_materials(&home);
let mut changed = false;
@@ -453,6 +523,30 @@ fn find_materials(config: &mut BTreeMap<String, String>) -> bool {
}
}
}
if need_ghidra {
// Results are only useful for the build being worked on: the first that covers it.
let target = config.get(TARGET_EXE_KEY).map(PathBuf::from);
let covering = target
.as_deref()
.and_then(|t| found.ghidra_results.iter().find(|r| ghidra_covers(r, t)));
match (covering, target.is_some(), found.ghidra_results.is_empty()) {
(Some(results), _, _) => {
config.insert(
GHIDRA_RESULTS_KEY.to_owned(),
results.to_string_lossy().into_owned(),
);
changed = true;
println!(" Ghidra results: found and saved");
}
(None, false, _) => {
println!(" Ghidra results: set the target build first, then run --find again")
}
(None, true, true) => println!(" Ghidra results: not found in the home folder"),
(None, true, false) => {
println!(" Ghidra results: found, but none covers the target build")
}
}
}
if found.truncated {
println!(" (the search stopped early: the home folder has too many entries)");
}
@@ -480,6 +574,7 @@ fn cmd_setup(args: &[String]) -> ExitCode {
let (key, check): (&str, SettingCheck) = match args[i].as_str() {
"--target-exe" => (TARGET_EXE_KEY, check_target_exe),
"--gdk-root" => (GDK_ROOT_KEY, check_gdk_root),
"--ghidra-results" => (GHIDRA_RESULTS_KEY, check_ghidra_results),
other => {
eprintln!("error: unknown argument: {other}");
return ExitCode::FAILURE;
@@ -520,6 +615,10 @@ fn cmd_setup(args: &[String]) -> ExitCode {
state(TARGET_EXE_KEY, check_target_exe)
);
println!(" GDK : {}", state(GDK_ROOT_KEY, check_gdk_root));
println!(
" Ghidra results: {}",
state(GHIDRA_RESULTS_KEY, check_ghidra_results)
);
println!("They are kept outside the repository. Run `bx-cli preflight` to check everything.");
ExitCode::SUCCESS
}
@@ -538,6 +637,33 @@ fn check_target_exe(value: Option<&str>) -> Result<String, String> {
}
}
/// The Ghidra results: the setting must be a results folder (see [`ghidra_programs`]).
fn check_ghidra_results(value: Option<&str>) -> Result<String, String> {
let root = value.filter(|v| !v.is_empty()).ok_or(
"not set; run `bx-cli setup --find`, or `bx-cli setup --ghidra-results <folder with RUN_REPORT.md, exports/ and decompiled/>`",
)?;
match ghidra_programs(Path::new(root)) {
Some(programs) => Ok(format!("present ({} programs analysed)", programs.len())),
None => Err("that folder is not a Ghidra results folder (RUN_REPORT.md, exports/*/manifest.json, decompiled/)".to_owned()),
}
}
/// Preflight's view of the Ghidra results: present, and covering the configured target build.
fn check_ghidra_for_target(results: Option<&str>, target: Option<&str>) -> Result<String, String> {
let found = check_ghidra_results(results)?;
match target.filter(|t| !t.is_empty()) {
Some(target)
if ghidra_covers(Path::new(results.unwrap_or_default()), Path::new(target)) =>
{
Ok(found)
}
Some(_) => {
Err("the results do not cover the configured target build's executable".to_owned())
}
None => Err("cannot be matched: the target build is not set".to_owned()),
}
}
/// The GDK: the setting must be a folder that contains the GDK's `d3d12_xs.h`.
fn check_gdk_root(value: Option<&str>) -> Result<String, String> {
let root = value
@@ -588,7 +714,7 @@ fn render_preflight(requirements: &[Requirement]) -> (String, bool) {
"Ready to work.\n"
} else {
"Not ready. Fix what you can yourself (AGENTS.md section 0, step 1): `bx-cli setup --find` for the \
target build and the GDK, Homebrew for missing tools, your own scratch files for disk space. \
target build, the GDK and the Ghidra results, Homebrew for missing tools, your own scratch files for disk space. \
Stop only for what is not on this machine.\n"
});
(out, ready)
@@ -650,6 +776,13 @@ fn cmd_preflight() -> ExitCode {
"GDK",
check_gdk_root(local_setting("BX_GDK_ROOT", GDK_ROOT_KEY, &config).as_deref()),
),
(
"Ghidra results",
check_ghidra_for_target(
local_setting("BX_GHIDRA_RESULTS", GHIDRA_RESULTS_KEY, &config).as_deref(),
local_setting("BX_TARGET_EXE", TARGET_EXE_KEY, &config).as_deref(),
),
),
(
"Free disk space",
match free {
@@ -1045,6 +1178,9 @@ struct RunArgs {
inherit_env: bool,
timeout: Option<Duration>,
backend: Option<String>,
/// The GDK's texture libraries (gdk_libs): `Some` when asked for or refused, `None` to use
/// them only for the configured target build.
gdk_libraries: Option<bool>,
}
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
@@ -1057,6 +1193,7 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
let mut inherit_env = false;
let mut timeout = None;
let mut backend: Option<String> = None;
let mut gdk_libraries: Option<bool> = None;
let mut i = 0;
while i < args.len() {
@@ -1070,7 +1207,15 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
i += 2;
}
"--profile" if i + 1 < args.len() => {
profile = args[i + 1].clone();
let name = args[i + 1].to_ascii_lowercase();
if !PROFILES.contains(&name.as_str()) {
return Err(format!(
"unknown profile {:?}; use one of {}",
args[i + 1],
PROFILES.join(", ")
));
}
profile = name;
i += 2;
}
"--bottle" if i + 1 < args.len() => {
@@ -1109,6 +1254,14 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
inherit_env = true;
i += 1;
}
"--gdk-libraries" => {
gdk_libraries = Some(true);
i += 1;
}
"--no-gdk-libraries" => {
gdk_libraries = Some(false);
i += 1;
}
other => return Err(format!("unknown argument: {other}")),
}
}
@@ -1133,6 +1286,7 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
inherit_env,
timeout,
backend,
gdk_libraries,
})
}
@@ -1450,6 +1604,7 @@ fn cmd_run(args: &[String]) -> ExitCode {
inherit_env,
timeout,
backend,
gdk_libraries,
} = run;
let cx_root = Path::new("/Applications/CrossOver.app/Contents/SharedSupport/CrossOver");
@@ -1460,8 +1615,62 @@ fn cmd_run(args: &[String]) -> ExitCode {
return ExitCode::FAILURE;
}
let abs_shims = fs::canonicalize(&shims_dir).unwrap_or(shims_dir);
let mut abs_shims = fs::canonicalize(&shims_dir).unwrap_or(shims_dir);
let abs_exe = fs::canonicalize(&exe).unwrap_or(exe);
// The GDK's texture libraries (gdk_libs.rs, ADR 0010): staged for the configured target
// build, or with --gdk-libraries, from the GDK configured on this machine.
let config = local_config_path()
.map(|p| read_local_config(&p))
.unwrap_or_default();
let is_target = local_setting("BX_TARGET_EXE", TARGET_EXE_KEY, &config)
.and_then(|t| fs::canonicalize(t).ok())
.is_some_and(|t| t == abs_exe);
let mut staged_bcpack: Option<PathBuf> = None;
let mut gdk_shims_dir: Option<PathBuf> = None;
if gdk_libraries.unwrap_or(is_target) {
match local_setting("BX_GDK_ROOT", GDK_ROOT_KEY, &config) {
Some(root) => {
let libs = gdk_libs::find(Path::new(&root));
let out = env::temp_dir().join(format!("bx-gdk-shims-{}", std::process::id()));
match gdk_libs::merge_shims(&abs_shims, &libs, &out) {
Ok(bcpack) => {
diag(format_args!(
"bx-cli: GDK texture libraries: XG {}, BCPack {}",
if libs.xg.is_some() {
"staged"
} else {
"not found"
},
if bcpack.is_some() {
"staged"
} else {
"not found"
}
));
staged_bcpack = bcpack;
abs_shims = out.clone();
gdk_shims_dir = Some(out);
}
Err(e) => diag(format_args!(
"warning: GDK texture libraries not staged: {e}"
)),
}
}
None => diag(
"warning: GDK texture libraries not staged: no GDK configured (bx-cli setup --find)",
),
}
}
struct RemoveOnDrop(Option<PathBuf>);
impl Drop for RemoveOnDrop {
fn drop(&mut self) {
if let Some(dir) = &self.0 {
let _ = fs::remove_dir_all(dir);
}
}
}
let _gdk_shims_cleanup = RemoveOnDrop(gdk_shims_dir);
let wine_shims_path = unix_to_wine_z_path(&abs_shims);
let resolved_prefix =
@@ -1655,6 +1864,9 @@ fn cmd_run(args: &[String]) -> ExitCode {
.env("WINEDLLOVERRIDES", SHIM_DLL_OVERRIDES)
.env("WINEPATH", &wine_shims_path)
.env("BX_PROFILE", &profile);
if let Some(bcpack) = &staged_bcpack {
cmd.env("BX_BCPACK_DLL", unix_to_wine_z_path(bcpack));
}
let abs_log = log_file.map(|lf| {
if lf.is_absolute() {
@@ -2167,12 +2379,16 @@ mod tests {
assert_eq!(run.backend.as_deref(), Some("d3dmetal"));
assert_eq!(run.shims_dir, PathBuf::from("build-shims/bin"));
assert_eq!(run.profile, "lockhart");
// ConsoleMode and BX_PROFILE must name the same console whatever the case.
let mixed = parse_run_args(&args(&["--exe", "a.exe", "--profile", "Anaconda"])).unwrap();
assert_eq!(mixed.profile, "anaconda");
let plain = parse_run_args(&args(&["--exe", "a.exe"])).unwrap();
assert!(plain.timeout.is_none() && plain.bottle.is_none() && plain.prefix.is_none());
for bad in [
&["--exe", "a.exe", "--timeout", "0"][..],
&["--exe", "a.exe", "--timeout", "soon"],
&["--exe", "a.exe", "--backend", "dmxt2"],
&["--exe", "a.exe", "--profile", "scarlett"],
&["--exe", "a.exe", "--bottle", "../x"],
&["--exe", "a.exe", "--timeout"],
&["--bottle", "b"],
@@ -2648,6 +2864,44 @@ sub setup_bottle_wineprefix {
fs::write(dir.join("a/b/include").join(GDK_MARKER), b"// header").unwrap();
assert!(check_gdk_root(dir.to_str()).unwrap().contains("found"));
// Ghidra results: unset, not a results folder, results for another program, results
// covering the target build (matched by its file name, whatever the case).
assert!(check_ghidra_results(None).unwrap_err().contains("not set"));
let results = dir.join("results");
fs::create_dir_all(results.join("exports/other")).unwrap();
assert!(
check_ghidra_results(results.to_str())
.unwrap_err()
.contains("not a Ghidra results folder")
);
fs::create_dir_all(results.join("decompiled")).unwrap();
fs::write(results.join(GHIDRA_REPORT), b"# RUN_REPORT").unwrap();
fs::write(results.join("exports/other/functions.csv"), b"").unwrap();
fs::write(
results.join("exports/other/manifest.json"),
br#"{"program": "other.dll", "rows": {}}"#,
)
.unwrap();
assert!(check_ghidra_results(results.to_str()).is_ok());
assert!(
check_ghidra_for_target(results.to_str(), pe.to_str())
.unwrap_err()
.contains("do not cover")
);
assert!(
check_ghidra_for_target(results.to_str(), None)
.unwrap_err()
.contains("target build is not set")
);
fs::create_dir_all(results.join("exports/t")).unwrap();
fs::write(results.join("exports/t/functions.csv"), b"").unwrap();
fs::write(
results.join("exports/t/manifest.json"),
br#"{"program":"TITLE.exe"}"#,
)
.unwrap();
assert!(check_ghidra_for_target(results.to_str(), pe.to_str()).is_ok());
// One missing requirement makes the whole preflight not ready, and says so.
let (text, ready) = render_preflight(&[
("Target build", Ok("present".to_owned())),
-927
View File
@@ -1,927 +0,0 @@
#!/usr/bin/env python3
"""Experimental RDNA 2 (gfx1030) -> HLSL translator for straight-line console VS/PS pairs.
Input: the VS and PS of a console graphics pipeline, each either a raw GPU instruction blob
(from a deserialized pipeline) or a console shader container (DXBC with an XBCH record).
Output, in --out: <vs>_<ps>.vs.hlsl / .ps.hlsl, compiled .vs.dxil / .ps.dxil (when --dxc is
given), and <vs>_<ps>.il, the input layout the shim creates the host pipeline with.
Model (inferences from the console compiler's listings and the target build's code; see the
first-frame notes):
* Code starts after a header of 12-byte `v_nop` + literal records (VOP3 word top half 0xD580).
* VS user data: s[0:1] = vertex-buffer descriptor table (16-byte V#s), s2 = base vertex.
Both stages: s8 = 32-bit pointer to root parameter 0's descriptor table (32-byte entries).
* A buffer V# loaded from the root table is a constant buffer; an 8-dword T# is a texture.
* PS v0:v1 are barycentrics; `v_interp_p1/p2 ... attrN.c` is attribute N, component c.
* VS `exp paramN` pairs with PS `attrN`; `exp pos0` is the position.
HLSL resources use register space 100 (+ root parameter index); the shim widens each title root
signature with overlapping ranges in that space so table entry k is register k.
Only straight-line code with the instructions below is accepted; anything else fails loudly.
"""
import argparse
import json
import os
import re
import struct
import zlib
import subprocess
import sys
LLVM_MC = os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc")
DXGI = {"R32_UINT": 42, "R32G32_UINT": 17, "R32G32B32_UINT": 7, "R32G32B32A32_UINT": 3,
"R8G8B8A8_UNORM": 28, "R16G16_FLOAT": 34, "R16G16B16A16_FLOAT": 10, "R32G32_FLOAT": 16}
TBUF_FMT = {"BUF_FMT_8_8_8_8_UNORM": ("R8G8B8A8_UNORM", 4, "float"),
"BUF_FMT_16_16_FLOAT": ("R16G16_FLOAT", 2, "float"),
"BUF_FMT_16_16_16_16_FLOAT": ("R16G16B16A16_FLOAT", 4, "float"),
"BUF_FMT_32_32_FLOAT": ("R32G32_FLOAT", 2, "float")}
class Unsupported(Exception):
pass
def container_code(blob):
"""The GPU code of one stage from a console shader container.
A container is a DXBC file whose DXIL part carries no bitcode; the console code is in an
`XBCH` record: magic, version, compressed size (u64), uncompressed size (u64), then a zlib
stream. It inflates to an `FSSM` block: a 16-byte header (magic, version, size), then
offsets relative to the end of that header. One of the per-stage slots at 0x18..0x78 is not
0xDEADBEEF filler and locates the stage record, whose first two u64 fields are the code
offset and the code size. (Layout inferred from containers of a project-authorized build.)
"""
at = blob.find(b"XBCH")
if at < 0:
raise Unsupported("container has no XBCH record")
csize, usize = struct.unpack_from("<QQ", blob, at + 8)
fssm = zlib.decompress(blob[at + 24:at + 24 + csize])
if len(fssm) != usize or fssm[:4] != b"FSSM":
raise Unsupported("XBCH record does not inflate to an FSSM block")
base = 16
record = None
for slot in range(0x18, 0x78, 8):
(v,) = struct.unpack_from("<Q", fssm, slot)
if v != 0xDEADBEEFDEADBEEF:
record = base + v
break
if record is None:
raise Unsupported("FSSM block has no stage record")
code_off, code_size = struct.unpack_from("<QQ", fssm, record)
code = fssm[base + code_off:base + code_off + code_size]
if len(code) < 12 or struct.unpack_from("<I", code, 0)[0] >> 16 != 0xD580:
raise Unsupported("stage code does not start with the expected header records")
return code
def code_words(blob):
if blob[:4] == b"DXBC":
blob = container_code(blob)
off = 0
while off + 12 <= len(blob) and struct.unpack_from("<I", blob, off)[0] >> 16 == 0xD580:
off += 12
return blob[off:]
def disassemble(blob):
body = code_words(blob)
text = " ".join("0x%02x" % b for b in body)
r = subprocess.run([LLVM_MC, "--disassemble", "-arch=amdgcn", "-mcpu=gfx1030"], input=text,
capture_output=True, text=True)
out = []
for line in r.stdout.splitlines():
line = line.split(";")[0].strip()
if not line or line.startswith("."):
continue
out.append(line)
if line == "s_endpgm":
break
if "s_endpgm" not in out:
raise Unsupported("no s_endpgm in decoded code")
return out
def split_ops(rest):
ops, depth, cur = [], 0, ""
for ch in rest:
if ch in "[(":
depth += 1
elif ch in "])":
depth -= 1
if ch == "," and depth == 0:
ops.append(cur.strip())
cur = ""
else:
cur += ch
if cur.strip():
ops.append(cur.strip())
return ops
def reg_range(op):
m = re.fullmatch(r"([sv])\[(\d+):(\d+)\]", op)
if m:
return m.group(1), int(m.group(2)), int(m.group(3))
m = re.fullmatch(r"([sv])(\d+)", op)
if m:
return m.group(1), int(m.group(2)), int(m.group(2))
return None
class Translator:
def __init__(self, stage):
self.stage = stage
self.lines = []
self.sprov = {} # sgpr -> provenance tuple
self.cbs = set() # table indices used as constant buffers
self.textures = set()
self.inputs = [] # VS: (semantic index, fmt, slot, offset, ncomp, kind)
self.attrs = set() # PS attribute indices read
self.exports = {} # name -> list of 4 expressions
self.used_v = set()
self.used_s = set()
self.written_v = set()
self.fetch_call = False # VS: attributes arrive in v4.. from the vertex-fetch subroutine
self.fetch_attrs = set() # attribute indices read that way
self.nexp = 0
self.ntmp = 0
self.tmps = []
# ---- operands -------------------------------------------------------------
def src(self, op, as_float=False):
"""HLSL expression (uint) for a 32-bit source operand."""
neg = False
if op.startswith("-") and not re.fullmatch(r"-\d+(\.\d+)?", op):
neg, op = True, op[1:]
m = re.fullmatch(r"neg\((.+)\)", op)
if m:
neg, op = True, m.group(1)
r = reg_range(op)
if r and r[1] == r[2]:
kind, n, _ = r
(self.used_v if kind == "v" else self.used_s).add(n)
if kind == "v" and self.fetch_call and n >= 4 and n not in self.written_v:
self.fetch_attrs.add((n - 4) // 4)
e = "%s%d" % (kind, n)
elif re.fullmatch(r"-?\d+\.\d+", op):
e = "asuint(%sf)" % op
elif re.fullmatch(r"0x[0-9a-fA-F]+", op):
e = "0x%xu" % int(op, 16)
elif re.fullmatch(r"-?\d+", op):
v = int(op)
e = "%du" % (v & 0xFFFFFFFF)
else:
raise Unsupported("operand %r" % op)
if neg:
e = "(asuint(-asfloat(%s)))" % e
return "asfloat(%s)" % e if as_float else e
def dst(self, op):
r = reg_range(op)
if not r or r[1] != r[2]:
raise Unsupported("destination %r" % op)
(self.used_v if r[0] == "v" else self.used_s).add(r[1])
if r[0] == "v":
self.written_v.add(r[1])
return "%s%d" % (r[0], r[1])
def emit(self, s):
self.lines.append(" " + s)
# ---- instructions -----------------------------------------------------------
def run(self, insts):
ignore = re.compile(r"^(s_waitcnt|s_clause|s_inst_prefetch|s_setprio|s_nop|s_wqm_b64|s_endpgm|v_nop)\b")
for line in insts:
if ignore.match(line):
continue
parts = line.split(None, 1)
op, rest = parts[0], parts[1] if len(parts) > 1 else ""
mods = ""
ops = split_ops(rest)
# modifiers after operands (e.g. "0 idxen offset:12", "dmask:0xf dim:...")
if op.endswith("_e64") and re.search(r"\b(clamp|mul:|div:|op_sel|abs\()", rest):
raise Unsupported("modifier in %r" % line)
handler = getattr(self, "i_" + op, None)
if handler is None:
raise Unsupported("instruction %r" % line)
handler(ops, line)
def exec_write(self, ops):
return ops and ops[0].startswith("exec")
def i_s_mov_b32(self, ops, line):
if ops[0] == "m0":
return
r = reg_range(ops[0])
s = reg_range(ops[1])
if s and s[0] == "s":
self.sprov[r[1]] = self.sprov.get(s[1], ("sgpr", s[1]))
elif re.fullmatch(r"-?(0x[0-9a-fA-F]+|\d+)", ops[1]):
self.sprov[r[1]] = ("imm", int(ops[1], 0) & 0xFFFFFFFF)
else:
self.sprov[r[1]] = ("unknown",)
self.emit("%s = %s;" % (self.dst(ops[0]), self.src(ops[1])))
def i_s_swappc_b64(self, ops, line):
# The call to the vertex-fetch subroutine the console runtime builds from the pipeline's
# input layout: on return, input element k is in v[4+4k : 7+4k] (observed: three-element
# layouts read v4..v15 in groups of four). The host input assembler does the fetch.
if self.stage != "vs" or self.lines or ops != ["s[4:5]", "s[4:5]"]:
raise Unsupported(line)
self.fetch_call = True
def i_s_mov_b64(self, ops, line):
if ops[0] == "exec" or ops[1] == "exec":
return
d = reg_range(ops[0])
s = reg_range(ops[1])
if s:
self.sprov[d[1]] = self.sprov.get(s[1], ("sgpr", s[1]))
self.sprov[d[1] + 1] = self.sprov.get(s[1] + 1, ("sgpr", s[1] + 1))
else:
v = int(ops[1], 0)
self.sprov[d[1]] = ("imm", v & 0xFFFFFFFF)
self.sprov[d[1] + 1] = ("imm", (v >> 32) & 0xFFFFFFFF)
def i_s_and_b64(self, ops, line):
# `s_and_b64 exec, exec, s[n:n+1]` restores the execution mask saved before s_wqm_b64
# (helper-pixel bookkeeping); it has no HLSL counterpart.
if ops[0] != "exec" or ops[1] != "exec":
raise Unsupported(line)
def i_s_movk_i32(self, ops, line):
r = reg_range(ops[0])
self.sprov[r[1]] = ("imm", int(ops[1], 0) & 0xFFFFFFFF)
self.emit("%s = %du;" % (self.dst(ops[0]), int(ops[1], 0) & 0xFFFFFFFF))
def i_s_lshl_b32(self, ops, line):
self.sprov[reg_range(ops[0])[1]] = ("unknown",)
self.emit("%s = %s << (%s & 31u);" % (self.dst(ops[0]), self.src(ops[1]), self.src(ops[2])))
def i_s_bfe_u32(self, ops, line):
pass # masks the high half of a copied table pointer; provenance is unchanged
def table_of(self, base):
b = reg_range(base)
p = self.sprov.get(b[1], ("sgpr", b[1]))
if p == ("sgpr", 0) and self.stage == "vs":
return "vbtable"
if p == ("sgpr", 8):
return "root0"
raise Unsupported("descriptor load from %r (provenance %r)" % (base, p))
def smem_load(self, ops, line, ndw):
d = reg_range(ops[0])
try:
table = self.table_of(ops[1])
except Unsupported:
if ndw != 4:
raise
for i in range(ndw):
self.sprov[d[1] + i] = ("smp", ops[1])
return
off = 0 if ops[2] == "null" else int(ops[2], 0)
if table == "vbtable":
prov = ("vb", off // 16)
elif ndw == 4:
prov = ("cb", off // 32)
elif ndw == 8:
prov = ("tex", off // 32)
else:
raise Unsupported(line)
for i in range(ndw):
self.sprov[d[1] + i] = prov
def i_s_load_dwordx4(self, ops, line):
self.smem_load(ops, line, 4)
def i_s_load_dwordx8(self, ops, line):
self.smem_load(ops, line, 8)
def s_buffer_load(self, ops, line, ndw):
d = reg_range(ops[0])
desc = reg_range(ops[1])
p = self.sprov.get(desc[1])
if not p or p[0] != "cb":
raise Unsupported("s_buffer_load from %r" % (p,))
cb = p[1]
self.cbs.add(cb)
off = 0 if ops[2] == "null" else int(ops[2], 0)
for i in range(ndw):
word = off // 4 + i
self.sprov[d[1] + i] = ("cbword", cb, word)
self.emit("s%d = cb%d_word(%d);" % (d[1] + i, cb, word))
self.used_s.add(d[1] + i)
def i_s_buffer_load_dword(self, ops, line):
self.s_buffer_load(ops, line, 1)
def i_s_buffer_load_dwordx2(self, ops, line):
self.s_buffer_load(ops, line, 2)
def i_s_buffer_load_dwordx4(self, ops, line):
self.s_buffer_load(ops, line, 4)
def i_s_buffer_load_dwordx8(self, ops, line):
self.s_buffer_load(ops, line, 8)
def i_s_buffer_load_dwordx16(self, ops, line):
self.s_buffer_load(ops, line, 16)
# vertex fetch -> input layout element
def vb_slot(self, op):
p = self.sprov.get(reg_range(op)[1])
if not p or p[0] != "vb":
raise Unsupported("vertex fetch through %r" % (p,))
return p[1]
def fetch(self, ops, line, ncomp, fmt, kind):
if "idxen" not in line or "offen" in line:
raise Unsupported(line)
d = reg_range(ops[0])
p = self.sprov.get(reg_range(ops[2])[1])
if p and p[0] == "cb" and "offset:" not in line:
# An indexed load from a buffer bound through the root table: element i is 16 bytes.
cb = p[1]
self.cbs.add(cb)
idx = self.src(ops[1])
for i in range(d[2] - d[1] + 1):
self.emit("t%d_%d = cb%d[%s].%s;" % (self.ntmp, i, cb, idx, "xyzw"[i]))
for i in range(d[2] - d[1] + 1):
self.emit("%s = t%d_%d;" % (self.dst("v%d" % (d[1] + i)), self.ntmp, i))
self.tmps.append((self.ntmp, d[2] - d[1] + 1))
self.ntmp += 1
return
slot = self.vb_slot(ops[2])
m = re.search(r"offset:(\d+)", line)
off = int(m.group(1)) if m else 0
sem = len(self.inputs)
self.inputs.append((sem, fmt, slot, off, ncomp, kind))
comps = "xyzw"
for i in range(d[2] - d[1] + 1):
src = "in%d.%s" % (sem, comps[i])
self.emit("v%d = %s;" % (d[1] + i, "asuint(%s)" % src if kind == "float" else src))
self.used_v.add(d[1] + i)
def i_buffer_load_dword(self, ops, line):
self.fetch(ops, line, 1, "R32_UINT", "uint")
def i_buffer_load_dwordx2(self, ops, line):
self.fetch(ops, line, 2, "R32G32_UINT", "uint")
def i_buffer_load_dwordx3(self, ops, line):
self.fetch(ops, line, 3, "R32G32B32_UINT", "uint")
def i_buffer_load_dwordx4(self, ops, line):
self.fetch(ops, line, 4, "R32G32B32A32_UINT", "uint")
def i_tbuffer_load_format_xyzw(self, ops, line):
m = re.search(r"format:\[(\w+)\]", line)
if not m or m.group(1) not in TBUF_FMT:
raise Unsupported(line)
fmt, n, kind = TBUF_FMT[m.group(1)]
self.fetch(ops, line, 4, fmt, kind)
# ALU
def vop2f(self, ops, expr):
a, b = self.src(ops[1], True), self.src(ops[2], True)
self.emit("%s = asuint(%s);" % (self.dst(ops[0]), expr % (a, b)))
def i_v_mul_f32_e32(self, ops, line):
self.vop2f(ops, "%s * %s")
i_v_mul_f32_e64 = i_v_mul_f32_e32
def i_v_add_f32_e32(self, ops, line):
self.vop2f(ops, "%s + %s")
i_v_add_f32_e64 = i_v_add_f32_e32
def i_v_sub_f32_e32(self, ops, line):
self.vop2f(ops, "%s - %s")
def i_v_max_f32_e32(self, ops, line):
self.vop2f(ops, "max(%s, %s)")
def i_v_min_f32_e32(self, ops, line):
self.vop2f(ops, "min(%s, %s)")
def i_v_fmac_f32_e32(self, ops, line):
d = self.dst(ops[0])
self.emit("%s = asuint(mad(%s, %s, asfloat(%s)));" % (d, self.src(ops[1], True), self.src(ops[2], True), d))
# ---- simple ALU, generated from (name, expression) tables ---------------------------------
def _vop2u(self, ops, expr):
a, b = self.src(ops[1]), self.src(ops[2])
self.emit("%s = %s;" % (self.dst(ops[0]), expr.format(a=a, b=b)))
def _vop2f(self, ops, expr):
a, b = self.src(ops[1], True), self.src(ops[2], True)
self.emit("%s = asuint(%s);" % (self.dst(ops[0]), expr.format(a=a, b=b)))
def _vop1f(self, ops, expr):
self.emit("%s = asuint(%s);" % (self.dst(ops[0]), expr.format(a=self.src(ops[1], True))))
def _sop2(self, ops, expr):
a, b = self.src(ops[1]), self.src(ops[2])
self.sprov[reg_range(ops[0])[1]] = ("unknown",)
self.emit("%s = %s;" % (self.dst(ops[0]), expr.format(a=a, b=b)))
def i_v_lshlrev_b32_e32(self, ops, line):
self._vop2u(ops, '({b} << ({a} & 31u))')
def i_v_lshlrev_b32_e64(self, ops, line):
self._vop2u(ops, '({b} << ({a} & 31u))')
def i_v_lshlrev_b32(self, ops, line):
self._vop2u(ops, '({b} << ({a} & 31u))')
def i_v_lshrrev_b32_e32(self, ops, line):
self._vop2u(ops, '({b} >> ({a} & 31u))')
def i_v_lshrrev_b32_e64(self, ops, line):
self._vop2u(ops, '({b} >> ({a} & 31u))')
def i_v_lshrrev_b32(self, ops, line):
self._vop2u(ops, '({b} >> ({a} & 31u))')
def i_v_ashrrev_i32_e32(self, ops, line):
self._vop2u(ops, '(uint)((int){b} >> ({a} & 31u))')
def i_v_ashrrev_i32_e64(self, ops, line):
self._vop2u(ops, '(uint)((int){b} >> ({a} & 31u))')
def i_v_ashrrev_i32(self, ops, line):
self._vop2u(ops, '(uint)((int){b} >> ({a} & 31u))')
def i_v_and_b32_e32(self, ops, line):
self._vop2u(ops, '({a} & {b})')
def i_v_and_b32_e64(self, ops, line):
self._vop2u(ops, '({a} & {b})')
def i_v_and_b32(self, ops, line):
self._vop2u(ops, '({a} & {b})')
def i_v_or_b32_e32(self, ops, line):
self._vop2u(ops, '({a} | {b})')
def i_v_or_b32_e64(self, ops, line):
self._vop2u(ops, '({a} | {b})')
def i_v_or_b32(self, ops, line):
self._vop2u(ops, '({a} | {b})')
def i_v_xor_b32_e32(self, ops, line):
self._vop2u(ops, '({a} ^ {b})')
def i_v_xor_b32_e64(self, ops, line):
self._vop2u(ops, '({a} ^ {b})')
def i_v_xor_b32(self, ops, line):
self._vop2u(ops, '({a} ^ {b})')
def i_v_sub_nc_u32_e32(self, ops, line):
self._vop2u(ops, '({a} - {b})')
def i_v_sub_nc_u32_e64(self, ops, line):
self._vop2u(ops, '({a} - {b})')
def i_v_sub_nc_u32(self, ops, line):
self._vop2u(ops, '({a} - {b})')
def i_v_subrev_nc_u32_e32(self, ops, line):
self._vop2u(ops, '({b} - {a})')
def i_v_subrev_nc_u32_e64(self, ops, line):
self._vop2u(ops, '({b} - {a})')
def i_v_subrev_nc_u32(self, ops, line):
self._vop2u(ops, '({b} - {a})')
def i_v_mul_u32_u24_e32(self, ops, line):
self._vop2u(ops, '(({a} & 0xffffffu) * ({b} & 0xffffffu))')
def i_v_mul_u32_u24_e64(self, ops, line):
self._vop2u(ops, '(({a} & 0xffffffu) * ({b} & 0xffffffu))')
def i_v_mul_u32_u24(self, ops, line):
self._vop2u(ops, '(({a} & 0xffffffu) * ({b} & 0xffffffu))')
def i_v_min_u32_e32(self, ops, line):
self._vop2u(ops, 'min({a}, {b})')
def i_v_min_u32_e64(self, ops, line):
self._vop2u(ops, 'min({a}, {b})')
def i_v_min_u32(self, ops, line):
self._vop2u(ops, 'min({a}, {b})')
def i_v_max_u32_e32(self, ops, line):
self._vop2u(ops, 'max({a}, {b})')
def i_v_max_u32_e64(self, ops, line):
self._vop2u(ops, 'max({a}, {b})')
def i_v_max_u32(self, ops, line):
self._vop2u(ops, 'max({a}, {b})')
def i_v_mul_lo_u32_e32(self, ops, line):
self._vop2u(ops, '({a} * {b})')
def i_v_mul_lo_u32_e64(self, ops, line):
self._vop2u(ops, '({a} * {b})')
def i_v_mul_lo_u32(self, ops, line):
self._vop2u(ops, '({a} * {b})')
def i_v_mul_hi_u32_e32(self, ops, line):
self._vop2u(ops, '(uint)(((uint64_t){a} * (uint64_t){b}) >> 32)')
def i_v_mul_hi_u32_e64(self, ops, line):
self._vop2u(ops, '(uint)(((uint64_t){a} * (uint64_t){b}) >> 32)')
def i_v_mul_hi_u32(self, ops, line):
self._vop2u(ops, '(uint)(((uint64_t){a} * (uint64_t){b}) >> 32)')
def i_v_max_f32_e64(self, ops, line):
self._vop2f(ops, 'max({a}, {b})')
def i_v_min_f32_e64(self, ops, line):
self._vop2f(ops, 'min({a}, {b})')
def i_v_sub_f32_e64(self, ops, line):
self._vop2f(ops, '({a} - {b})')
def i_v_subrev_f32_e32(self, ops, line):
self._vop2f(ops, '({b} - {a})')
def i_v_subrev_f32_e64(self, ops, line):
self._vop2f(ops, '({b} - {a})')
def i_v_rcp_f32_e32(self, ops, line):
self._vop1f(ops, '(1.0f / {a})')
def i_v_rcp_f32_e64(self, ops, line):
self._vop1f(ops, '(1.0f / {a})')
def i_v_rsq_f32_e32(self, ops, line):
self._vop1f(ops, 'rsqrt({a})')
def i_v_rsq_f32_e64(self, ops, line):
self._vop1f(ops, 'rsqrt({a})')
def i_v_sqrt_f32_e32(self, ops, line):
self._vop1f(ops, 'sqrt({a})')
def i_v_sqrt_f32_e64(self, ops, line):
self._vop1f(ops, 'sqrt({a})')
def i_v_floor_f32_e32(self, ops, line):
self._vop1f(ops, 'floor({a})')
def i_v_floor_f32_e64(self, ops, line):
self._vop1f(ops, 'floor({a})')
def i_v_fract_f32_e32(self, ops, line):
self._vop1f(ops, 'frac({a})')
def i_v_fract_f32_e64(self, ops, line):
self._vop1f(ops, 'frac({a})')
def i_v_exp_f32_e32(self, ops, line):
self._vop1f(ops, 'exp2({a})')
def i_v_exp_f32_e64(self, ops, line):
self._vop1f(ops, 'exp2({a})')
def i_v_log_f32_e32(self, ops, line):
self._vop1f(ops, 'log2({a})')
def i_v_log_f32_e64(self, ops, line):
self._vop1f(ops, 'log2({a})')
def i_v_trunc_f32_e32(self, ops, line):
self._vop1f(ops, 'trunc({a})')
def i_v_trunc_f32_e64(self, ops, line):
self._vop1f(ops, 'trunc({a})')
def i_v_rndne_f32_e32(self, ops, line):
self._vop1f(ops, 'round({a})')
def i_v_rndne_f32_e64(self, ops, line):
self._vop1f(ops, 'round({a})')
def i_v_ceil_f32_e32(self, ops, line):
self._vop1f(ops, 'ceil({a})')
def i_v_ceil_f32_e64(self, ops, line):
self._vop1f(ops, 'ceil({a})')
def i_v_cvt_f32_u32_e32(self, ops, line):
self._vop1f(ops, '(float)asuint({a})')
def i_v_cvt_f32_u32_e64(self, ops, line):
self._vop1f(ops, '(float)asuint({a})')
def i_v_cvt_f32_i32_e32(self, ops, line):
self._vop1f(ops, '(float)asint({a})')
def i_v_cvt_f32_i32_e64(self, ops, line):
self._vop1f(ops, '(float)asint({a})')
def i_v_sin_f32_e32(self, ops, line):
self._vop1f(ops, 'sin({a} * 6.2831853f)')
def i_v_sin_f32_e64(self, ops, line):
self._vop1f(ops, 'sin({a} * 6.2831853f)')
def i_v_cos_f32_e32(self, ops, line):
self._vop1f(ops, 'cos({a} * 6.2831853f)')
def i_v_cos_f32_e64(self, ops, line):
self._vop1f(ops, 'cos({a} * 6.2831853f)')
def i_s_or_b32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} | {b})')
def i_s_and_b32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} & {b})')
def i_s_xor_b32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} ^ {b})')
def i_s_mul_i32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} * {b})')
def i_s_add_u32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} + {b})')
def i_s_sub_u32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} - {b})')
def i_s_lshr_b32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} >> ({b} & 31u))')
def i_s_min_u32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, 'min({a}, {b})')
def i_s_max_u32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, 'max({a}, {b})')
def i_s_brev_b32(self, ops, line):
self.sprov[reg_range(ops[0])[1]] = ("unknown",)
self.emit("%s = reversebits(%s);" % (self.dst(ops[0]), self.src(ops[1])))
def i_s_setreg_imm32_b32(self, ops, line):
pass # mode register (rounding, denormals): the host defaults are used
def i_v_cvt_i32_f32_e32(self, ops, line):
self.emit("%s = (uint)(int)%s;" % (self.dst(ops[0]), self.src(ops[1], True)))
def i_v_med3_f32(self, ops, line):
a, b, c = (self.src(o, True) for o in ops[1:4])
self.emit("%s = asuint(max(min(%s, %s), min(max(%s, %s), %s)));" % (self.dst(ops[0]), a, b, a, b, c))
def i_v_mul_legacy_f32_e32(self, ops, line):
a, b = self.src(ops[1], True), self.src(ops[2], True)
self.emit("%s = asuint((%s == 0.0f || %s == 0.0f) ? 0.0f : %s * %s);" % (self.dst(ops[0]), a, b, a, b))
i_v_mul_legacy_f32_e64 = i_v_mul_legacy_f32_e32
def i_v_cvt_pkrtz_f16_f32_e32(self, ops, line):
a, b = self.src(ops[1], True), self.src(ops[2], True)
self.emit("%s = f32tof16(%s) | (f32tof16(%s) << 16);" % (self.dst(ops[0]), a, b))
i_v_cvt_pkrtz_f16_f32_e64 = i_v_cvt_pkrtz_f16_f32_e32
def i_v_interp_mov_f32_e32(self, ops, line):
m = re.fullmatch(r"attr(\d+)\.([xyzw])", ops[2])
if not m:
raise Unsupported(line)
n = int(m.group(1))
self.attrs.add(n)
self.emit("%s = asuint(attr%d.%s);" % (self.dst(ops[0]), n, m.group(2)))
def i_v_fma_f32(self, ops, line):
self.emit("%s = asuint(mad(%s, %s, %s));" % (self.dst(ops[0]), self.src(ops[1], True),
self.src(ops[2], True), self.src(ops[3], True)))
def i_v_mov_b32_e32(self, ops, line):
self.emit("%s = %s;" % (self.dst(ops[0]), self.src(ops[1])))
def i_v_add_nc_u32_e32(self, ops, line):
# only the vertex-index computation uses it here; the index itself is the IA's job
if self.stage == "vs":
return
self.emit("%s = %s + %s;" % (self.dst(ops[0]), self.src(ops[1]), self.src(ops[2])))
def fma_mix(self, ops, line, hi):
m = re.search(r"op_sel_hi:\[(\d),(\d),(\d)\]", line)
if "op_sel:" in line or not m:
raise Unsupported(line)
srcs = []
for i, sel in enumerate(m.groups()):
o = ops[1 + i].split()[0]
neg = False
mm = re.fullmatch(r"neg\((.+)\)", o)
if mm:
neg, o = True, mm.group(1)
e = self.src(o)
f = "f16tof32(%s & 0xffffu)" % e if sel == "1" else "asfloat(%s)" % e
srcs.append("(-%s)" % f if neg else f)
d = self.dst(ops[0])
val = "f32tof16(mad(%s, %s, %s))" % tuple(srcs)
if hi:
self.emit("%s = (%s & 0xffffu) | (%s << 16);" % (d, d, val))
else:
self.emit("%s = (%s & 0xffff0000u) | %s;" % (d, d, val))
def i_v_fma_mixlo_f16(self, ops, line):
self.fma_mix(ops, line, False)
def i_v_fma_mixhi_f16(self, ops, line):
self.fma_mix(ops, line, True)
# PS interpolation
def i_v_interp_p1_f32_e32(self, ops, line):
pass
def i_v_interp_p2_f32_e32(self, ops, line):
m = re.fullmatch(r"attr(\d+)\.([xyzw])", ops[2])
if not m:
raise Unsupported(line)
n = int(m.group(1))
self.attrs.add(n)
self.emit("%s = asuint(attr%d.%s);" % (self.dst(ops[0]), n, m.group(2)))
def i_image_sample(self, ops, line):
d = reg_range(ops[0])
c = reg_range(ops[1])
t = self.sprov.get(reg_range(ops[2])[1])
m = re.search(r"dmask:(0x[0-9a-f]+)", line)
if not t or t[0] != "tex" or "dim:SQ_RSRC_IMG_2D" not in line or not m:
raise Unsupported(line)
mask = int(m.group(1), 16)
comps = [c_ for i, c_ in enumerate("xyzw") if mask & (1 << i)]
if len(comps) != d[2] - d[1] + 1:
raise Unsupported("dmask and destination size differ: " + line)
self.textures.add(t[1])
self.used_v.update([c[1], c[1] + 1])
fn = "SampleLevel(smp0, float2(asfloat(v%d), asfloat(v%d)), 0)" if line.startswith("image_sample_lz") else \
"Sample(smp0, float2(asfloat(v%d), asfloat(v%d)))"
self.emit("{ float4 r = tex%d.%s;" % (t[1], fn % (c[1], c[1] + 1)))
for i, comp in enumerate(comps):
self.emit(" v%d = asuint(r.%s);" % (d[1] + i, comp))
self.used_v.add(d[1] + i)
self.emit("}")
i_image_sample_lz = i_image_sample
def i_exp(self, ops, line):
target = ops[0]
vals = [o.split()[0] for o in ops[1:5]]
compr = " compr" in line
if compr:
a, b = self.src(vals[0]), self.src(vals[2])
ex = ["f16tof32(%s & 0xffffu)" % a, "f16tof32(%s >> 16)" % a,
"f16tof32(%s & 0xffffu)" % b, "f16tof32(%s >> 16)" % b]
else:
ex = ["0.0f" if v == "off" else self.src(v, True) for v in vals]
# registers are reused after an export: take the values now
name = "exp%d_%s" % (self.nexp, target)
self.nexp += 1
self.emit("float4 %s = float4(%s);" % (name, ", ".join(ex)))
self.exports[target] = ["%s.%s" % (name, c) for c in "xyzw"]
# ---- output -----------------------------------------------------------------
def resources(self):
out = []
for cb in sorted(self.cbs):
out.append("cbuffer CB%d : register(b%d, space100) { uint4 cb%d[4096]; };" % (cb, cb, cb))
out.append("uint cb%d_word(uint w) { return cb%d[w >> 2][w & 3]; }" % (cb, cb))
for t in sorted(self.textures):
out.append("Texture2D<float4> tex%d : register(t%d, space100);" % (t, t))
if self.textures:
out.append("SamplerState smp0 : register(s0, space100);")
return out
def regs(self):
decl = []
for n in sorted(self.used_v):
k = (n - 4) // 4
if self.fetch_call and n >= 4 and k in self.fetch_attrs:
decl.append("uint v%d = asuint(a%d.%s);" % (n, k, "xyzw"[(n - 4) % 4]))
else:
decl.append("uint v%d = 0;" % n)
decl += ["uint s%d = 0;" % n for n in sorted(self.used_s)]
for n, count in self.tmps:
decl += ["uint t%d_%d = 0;" % (n, i) for i in range(count)]
return [" " + d for d in decl]
def build_vs(t):
ins = ["float4 a%d : ATTR%d" % (k, k) for k in sorted(t.fetch_attrs)]
for sem, fmt, slot, off, n, kind in t.inputs:
ty = ("float%d" if kind == "float" else "uint%d") % n if n > 1 else ("float" if kind == "float" else "uint")
ins.append("%s in%d : ATTR%d" % (ty, sem, sem))
params = sorted(k for k in t.exports if k.startswith("param"))
outs = ["float4 pos : SV_Position"] + ["float4 %s : PARAM%s" % (p, p[5:]) for p in params]
src = t.resources()
src.append("struct VSOut { %s; };" % "; ".join(outs))
src.append("VSOut main(%s) {" % ", ".join(ins))
src += t.regs() + t.lines
src.append(" VSOut o;")
pos = t.exports.get("pos0")
if not pos:
raise Unsupported("VS exports no position")
src.append(" o.pos = float4(%s);" % ", ".join(pos))
for p in params:
src.append(" o.%s = float4(%s);" % (p, ", ".join(t.exports[p])))
src.append(" return o;\n}")
return "\n".join(src) + "\n", params
def build_ps(t, vs_params):
for a in t.attrs:
if "param%d" % a not in vs_params:
raise Unsupported("PS reads attr%d that the VS does not export" % a)
ins = ["float4 pos : SV_Position"] + ["float4 attr%s : PARAM%s" % (p[5:], p[5:]) for p in vs_params]
if "mrt0" not in t.exports:
raise Unsupported("PS exports no mrt0")
src = t.resources()
src.append("float4 main(%s) : SV_Target0 {" % ", ".join(ins))
src += t.regs() + t.lines
src.append(" return float4(%s);\n}" % ", ".join(t.exports["mrt0"]))
return "\n".join(src) + "\n"
def fnv1a(data):
h = 1469598103934665603
for b in data:
h = ((h ^ b) * 1099511628211) & 0xFFFFFFFFFFFFFFFF
return "%016x" % h
def main():
ap = argparse.ArgumentParser()
ap.add_argument("vs")
ap.add_argument("ps")
ap.add_argument("--out", required=True)
ap.add_argument("--dxc", help="command prefix that runs a Windows dxc.exe (e.g. a wine wrapper)")
a = ap.parse_args()
vsb, psb = open(a.vs, "rb").read(), open(a.ps, "rb").read()
key = "%s_%s" % (fnv1a(vsb), fnv1a(psb))
vt, pt = Translator("vs"), Translator("ps")
vt.run(disassemble(vsb))
pt.run(disassemble(psb))
vs_src, params = build_vs(vt)
ps_src = build_ps(pt, params)
os.makedirs(a.out, exist_ok=True)
base = os.path.join(a.out, key)
open(base + ".vs.hlsl", "w").write(vs_src)
open(base + ".ps.hlsl", "w").write(ps_src)
with open(base + ".il", "w") as f:
if vt.fetch_call:
f.write("FETCH %d\n" % (max(vt.fetch_attrs) + 1 if vt.fetch_attrs else 0))
for sem, fmt, slot, off, n, kind in vt.inputs:
f.write("ATTR %d %d %d %d\n" % (sem, DXGI[fmt], slot, off))
for cb in sorted(vt.cbs | pt.cbs):
f.write("USE CB %d\n" % cb)
for tex in sorted(vt.textures | pt.textures):
f.write("USE TEX %d\n" % tex)
if a.dxc:
for st, prof in (("vs", "vs_6_0"), ("ps", "ps_6_0")):
cmd = a.dxc.split() + ["-T", prof, "-E", "main", "-Fo", base + ".%s.dxil" % st, base + ".%s.hlsl" % st]
r = subprocess.run(cmd, capture_output=True, text=True)
err = "\n".join(l for l in (r.stdout + r.stderr).splitlines() if "fixme" not in l)
if r.returncode or not os.path.exists(base + ".%s.dxil" % st):
sys.exit("dxc failed for %s:\n%s" % (st, err))
print(key)
if __name__ == "__main__":
try:
main()
except Unsupported as e:
sys.exit("unsupported: %s" % e)
+1 -1
View File
@@ -8,12 +8,12 @@ bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
xbox_facade.cpp
frame_pacing.cpp
placed_x.cpp
gdk_xg.cpp
descriptor_heaps.cpp
committed.cpp
console_formats.cpp
pipelines.cpp
rect_list.cpp
console_translate.cpp
gpu_writes.cpp
fences.cpp
presentx_xbox.cpp
+12 -10
View File
@@ -184,18 +184,20 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource_x(void* self,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResourceX");
if (!xbox_desc) return E_INVALIDARG;
// D3D12XBOX_RESOURCE_DESC begins with the PC description; DccOptions (a 32-bit enum) follows it.
// D3D12XBOX_RESOURCE_DESC begins with the PC description; DccOptions follows it. DccOptions is
// a struct of two 32-bit enums, CompressionLevel and ColorTransform; every value of either
// selects some form of colour compression (CompressionLevel 0 is 64B, not "none").
D3D12_RESOURCE_DESC desc{};
std::memcpy(&desc, xbox_desc, sizeof(desc));
UINT32 dcc = 0;
std::memcpy(&dcc, static_cast<const char*>(xbox_desc) + sizeof(desc), sizeof(dcc));
if (dcc) {
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 8) {
char detail[96];
std::snprintf(detail, sizeof(detail), "DccOptions=0x%x ignored (no colour compression on the host)", dcc);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommittedResourceX", detail);
}
UINT32 dcc[2] = {};
std::memcpy(dcc, static_cast<const char*>(xbox_desc) + sizeof(desc), sizeof(dcc));
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 8) {
char detail[128];
std::snprintf(detail, sizeof(detail),
"DccOptions CompressionLevel=%u ColorTransform=%u ignored (no colour compression on the host)",
dcc[0], dcc[1]);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommittedResourceX", detail);
}
return bx_xbox_device_create_committed_resource(self, heap, flags, &desc, state, clear, riid, ppv);
}
+75 -16
View File
@@ -11,7 +11,7 @@
#include "console_formats.h"
#include "xbox_facade.h"
#include "console_translate.h"
#include "gdk_xg.h"
#include <atomic>
#include <cstdio>
@@ -75,6 +75,68 @@ private:
std::vector<Desc> copy_;
};
D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC& d) { return d; }
D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC1& d) {
D3D12_RESOURCE_DESC out{};
out.Dimension = d.Dimension;
out.Alignment = d.Alignment;
out.Width = d.Width;
out.Height = d.Height;
out.DepthOrArraySize = d.DepthOrArraySize;
out.MipLevels = d.MipLevels;
out.Format = d.Format;
out.SampleDesc = d.SampleDesc;
out.Layout = d.Layout;
out.Flags = d.Flags;
return out;
}
/* Allocation info for descriptions that include a console texture layout. The console sizes come
from the GDK's XG (gdk_xg.h); other descriptions keep the host's answer, one at a time. The
total follows Direct3D 12: each resource at its alignment, in order; the total alignment is the
largest. Returns false (the host answers everything) when no description has a console layout
or XG is not loaded. */
template <typename Desc>
bool console_allocation(ID3D12Device* device, UINT mask, UINT count, const Desc* descs, D3D12_RESOURCE_ALLOCATION_INFO* total,
D3D12_RESOURCE_ALLOCATION_INFO1* each, const char* method) {
if (!descs || !count || !bx_gdk_xg_available()) return false;
bool any = false;
for (UINT i = 0; i < count && !any; ++i) any = bx_is_console_texture_layout(as_desc(descs[i]));
if (!any) return false;
uint64_t offset = 0, max_alignment = 0;
for (UINT i = 0; i < count; ++i) {
const D3D12_RESOURCE_DESC desc = as_desc(descs[i]);
uint64_t size = 0, alignment = 0;
if (!bx_is_console_texture_layout(desc) || !bx_gdk_xg_layout_size(desc, &size, &alignment)) {
D3D12_RESOURCE_DESC host = desc;
if (bx_is_console_only_format(host.Format)) host.Format = bx_host_resource_format(host.Format);
if (bx_is_console_texture_layout(host)) host.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
D3D12_RESOURCE_ALLOCATION_INFO one{};
device->GetResourceAllocationInfo(&one, mask, 1, &host);
size = one.SizeInBytes;
alignment = one.Alignment;
} else {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 24) {
char detail[192];
std::snprintf(detail, sizeof(detail), "%s %llux%ux%u mips=%u format=%d layout=0x%x: console size %llu, alignment %llu",
method, static_cast<unsigned long long>(desc.Width), desc.Height, desc.DepthOrArraySize, desc.MipLevels,
static_cast<int>(desc.Format), static_cast<UINT>(desc.Layout), static_cast<unsigned long long>(size),
static_cast<unsigned long long>(alignment));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_allocation", detail);
}
}
if (size == UINT64_MAX || !alignment) return false;
offset = (offset + alignment - 1) / alignment * alignment;
if (each) each[i] = D3D12_RESOURCE_ALLOCATION_INFO1{offset, alignment, size};
offset += size;
if (alignment > max_alignment) max_alignment = alignment;
}
total->SizeInBytes = offset;
total->Alignment = max_alignment;
return true;
}
} // namespace
extern "C" {
@@ -82,8 +144,11 @@ extern "C" {
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info(void* self, UINT mask, UINT count,
const D3D12_RESOURCE_DESC* descs) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo");
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo");
D3D12_RESOURCE_ALLOCATION_INFO result{};
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, nullptr, "GetResourceAllocationInfo")) {
return result;
}
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo");
bx_xbox_host<ID3D12Device>(self)->GetResourceAllocationInfo(&result, mask, count, host.get());
return result;
}
@@ -91,8 +156,11 @@ D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_all
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info1(
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo1");
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo1");
D3D12_RESOURCE_ALLOCATION_INFO result{};
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, each, "GetResourceAllocationInfo1")) {
return result;
}
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo1");
bx_xbox_host<ID3D12Device4>(self)->GetResourceAllocationInfo1(&result, mask, count, host.get(), each);
return result;
}
@@ -100,8 +168,11 @@ D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_all
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info2(
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo2");
const HostDescs<D3D12_RESOURCE_DESC1> host(descs, count, "GetResourceAllocationInfo2");
D3D12_RESOURCE_ALLOCATION_INFO result{};
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, each, "GetResourceAllocationInfo2")) {
return result;
}
const HostDescs<D3D12_RESOURCE_DESC1> host(descs, count, "GetResourceAllocationInfo2");
bx_xbox_host<ID3D12Device8>(self)->GetResourceAllocationInfo2(&result, mask, count, host.get(), each);
return result;
}
@@ -139,8 +210,6 @@ void STDMETHODCALLTYPE bx_xbox_device_create_shader_resource_view(void* self, ID
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
host.of(desc, "CreateShaderResourceView"),
bx_xbox_host_cpu_handle(dest));
bx_console_note_srv(dest.ptr, bx_xbox_unwrap_as<ID3D12Resource>(resource), desc);
bx_console_mark_srv(dest.ptr, bx_xbox_unwrap_as<ID3D12Resource>(resource), desc);
}
void STDMETHODCALLTYPE bx_xbox_device_create_unordered_access_view(void* self, ID3D12Resource* resource, ID3D12Resource* counter,
@@ -160,11 +229,6 @@ void STDMETHODCALLTYPE bx_xbox_device_create_render_target_view(void* self, ID3D
bx_xbox_host<ID3D12Device>(self)->CreateRenderTargetView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
host.of(desc, "CreateRenderTargetView"),
bx_xbox_host_cpu_handle(dest));
if (bx_console_translation_enabled()) {
DXGI_FORMAT f = desc ? bx_host_format(desc->Format) : DXGI_FORMAT_UNKNOWN;
if (f == DXGI_FORMAT_UNKNOWN && resource) f = bx_xbox_unwrap_as<ID3D12Resource>(resource)->GetDesc().Format;
bx_console_rtv_created(bx_xbox_host_cpu_handle(dest).ptr, f, bx_xbox_unwrap_as<ID3D12Resource>(resource));
}
}
void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D12Resource* resource,
@@ -175,11 +239,6 @@ void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D
bx_xbox_host<ID3D12Device>(self)->CreateDepthStencilView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
host.of(desc, "CreateDepthStencilView"),
bx_xbox_host_cpu_handle(dest));
if (bx_console_translation_enabled()) {
DXGI_FORMAT f = desc ? bx_host_format(desc->Format) : DXGI_FORMAT_UNKNOWN;
if (f == DXGI_FORMAT_UNKNOWN && resource) f = bx_xbox_unwrap_as<ID3D12Resource>(resource)->GetDesc().Format;
bx_console_dsv_created(bx_xbox_host_cpu_handle(dest).ptr, f);
}
}
} // extern "C"
File diff suppressed because it is too large. Load diff
-107
View File
@@ -1,107 +0,0 @@
#pragma once
/*
* Experimental translation of deserialized console pipelines (raw RDNA 2 code) for the first
* frames of a project-authorized target build. See console_translate.cpp.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <vector>
/* Records a created root signature's serialized form (host object -> description). */
void bx_console_root_signature_created(ID3D12RootSignature* host, const void* blob, size_t size);
/* The 1.1-converted description of a recorded root signature, or nullptr. */
const D3D12_ROOT_SIGNATURE_DESC1* bx_console_root_signature_desc(ID3D12RootSignature* host);
/* Writes a compact description of a recorded root signature. */
void bx_console_describe_root_signature(ID3D12RootSignature* host, char* out, size_t room);
/* True when BX_CONSOLE_SHADER_CACHE names a folder of translated shaders (opt-in). */
bool bx_console_translation_enabled();
/* With translation enabled: a serialized root signature widened with the translator's register
space (overlapping CBV/SRV ranges per descriptor table, one static sampler). The caller
creates the host root signature from it and falls back to the original on failure. */
ID3DBlob* bx_console_widen_root_signature(const void* blob, size_t size);
/* A console graphics pipeline whose stages have translated shaders in the cache. */
struct BxTranslated;
/* Looks the VS/PS pair up in the cache; nullptr when either is missing. */
std::shared_ptr<BxTranslated> bx_console_translate_graphics(ID3D12Device* device, ID3D12RootSignature* host_root,
const void* vs, size_t vs_size, const void* ps,
size_t ps_size);
/* True when the translated vertex shader takes its attributes from the pipeline's own input
layout (the console vertex-fetch call); the host pipeline is then built from the title's
stream, and bx_console_set_pipeline hands it over (the reference is taken). */
bool bx_console_uses_stream_layout(const BxTranslated* translated);
const void* bx_console_shader(const BxTranslated* translated, bool pixel, size_t* size);
void bx_console_set_pipeline(BxTranslated* translated, ID3D12PipelineState* host);
/* Hands over the title's stream (shaders already substituted) and its input elements; host
pipelines are then created from it per bound target formats. Offsets are payload offsets of
the input layout, render-target formats, depth format and topology type (SIZE_MAX: absent). */
void bx_console_set_stream(BxTranslated* translated, std::vector<uint8_t>&& stream,
std::vector<D3D12_INPUT_ELEMENT_DESC>&& elements, size_t layout_at, size_t rt_at, size_t ds_at,
size_t topology_at);
void bx_console_note_ib(ID3D12GraphicsCommandList* list, const D3D12_INDEX_BUFFER_VIEW* view);
/* The title set a viewport (true) or scissor rectangle (false) on this list since its reset. */
void bx_console_note_raster(ID3D12GraphicsCommandList* list, bool viewport);
void bx_console_note_viewport(ID3D12GraphicsCommandList* list, UINT count, const D3D12_VIEWPORT* viewports);
void bx_console_note_scissor(ID3D12GraphicsCommandList* list, UINT count, const D3D12_RECT* rects);
void bx_console_note_topology(ID3D12GraphicsCommandList* list, D3D12_PRIMITIVE_TOPOLOGY topology);
/* Diagnostic: logs the state a translated draw runs with (first few per pipeline). */
void bx_console_draw_state(const char* key, ID3D12GraphicsCommandList* list, UINT count, UINT instances, UINT start, INT base,
bool indexed);
void bx_console_stream_state(const char* key, const char* text);
/* A non-indexed draw on a list whose topology is the console rectangle list: draws each
rectangle as a four-vertex triangle strip built from the title's three vertices. True when the
draw was handled (the caller then skips its own draw). */
bool bx_console_draw_rect_list(BxTranslated* translated, ID3D12GraphicsCommandList* list, UINT vertices, UINT instances,
UINT first_vertex, UINT first_instance);
/* Diagnostic: the distinct render targets translated draws went into (at most `max`). */
int bx_console_debug_targets(ID3D12Resource** out, int max);
/* placed_x.cpp: makes sure [va, va + size) of plain title memory has a host buffer behind it. */
/* Writes a sampled console texture from title memory; returns the resource to view (a detiled
copy for tiled textures, otherwise `host`). */
extern "C" ID3D12Resource* bx_xbox_upload_linear_texture(ID3D12Resource* host);
extern "C" bool bx_xbox_back_title_buffer(ID3D12Device* device, uint64_t va, uint64_t size);
/* Render-target bookkeeping, so translated pipelines are created with the bound formats. */
void bx_console_rtv_created(SIZE_T host_cpu, DXGI_FORMAT format, ID3D12Resource* resource = nullptr);
void bx_console_dsv_created(SIZE_T host_cpu, DXGI_FORMAT format);
void bx_console_list_set_render_targets(ID3D12GraphicsCommandList* list, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* dsv);
/* Draw-time evidence (BX_PSO_PROFILE=1, local only). Handles are title descriptor addresses. */
void bx_console_note_cbv(uint64_t title_handle, uint64_t va, UINT size);
void bx_console_note_srv(uint64_t title_handle, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc);
void bx_console_note_table(ID3D12GraphicsCommandList* list, UINT param, uint64_t title_handle);
void bx_console_note_vb(ID3D12GraphicsCommandList* list, UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views);
void bx_console_evidence(const char* key, ID3D12GraphicsCommandList* list, UINT vertices);
const char* bx_console_key(const BxTranslated* translated);
/* Inline console descriptors: draws are recorded per list and decoded when it is submitted. */
void bx_console_list_reset(ID3D12GraphicsCommandList* list);
void bx_console_record_draw(const std::shared_ptr<BxTranslated>& translated, ID3D12GraphicsCommandList* list);
void bx_console_submit(ID3D12CommandList* const* lists, UINT count);
/* Descriptor markers in title memory (see console_translate.cpp, part 5). */
void bx_console_mark_cbv(uint64_t dest, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc, uint64_t title_va);
void bx_console_mark_srv(uint64_t dest, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc,
uint64_t title_va = 0, uint64_t title_size = 0);
void bx_console_copy_title(uint64_t dest, uint64_t src, UINT count);
/* placed_x.cpp: copies a title-memory range to the host shadow its address resolves to. */
extern "C" bool bx_xbox_sync_title_range(uint64_t title_va, uint64_t size);
extern "C" uint64_t bx_xbox_shadow_title_va(ID3D12Resource* host);
void bx_console_note_root_srv(ID3D12GraphicsCommandList* list, UINT param, uint64_t title_va);
/* Binds a translated pipeline to a host list before a draw; false when it cannot be created. */
bool bx_console_apply(BxTranslated* translated, ID3D12GraphicsCommandList* list);
+3 -2
View File
@@ -79,10 +79,11 @@ extern "C" {
* models (or one the host device answers); anything else fails with E_NOINTERFACE and a logged
* IID.
*/
extern "C" void bx_xbox_xg_enable_locking();
extern "C" void bx_gdk_xg_enable_locking();
HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv) {
static const bool xg_locking = (bx_xbox_xg_enable_locking(), true);
// The title creates XG texture computers on its own threads; the shim does too (gdk_xg.h).
static const bool xg_locking = (bx_gdk_xg_enable_locking(), true);
(void)xg_locking;
if (!ppv) {
return E_POINTER;
-20
View File
@@ -13,7 +13,6 @@
* other titles' descriptor writes on the out-of-line path, which reaches the host heap.
*/
#include "xbox_facade.h"
#include "console_translate.h"
#include <atomic>
#include <cstdio>
@@ -188,8 +187,6 @@ void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, co
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));
if (desc) bx_console_note_cbv(dest.ptr, desc->BufferLocation, desc->SizeInBytes);
if (desc) bx_console_mark_cbv(dest.ptr, host_desc, desc->BufferLocation);
}
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
@@ -201,17 +198,6 @@ void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ran
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]);
if (type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && dest_starts && src_starts) {
// console descriptors are bytes: copy the title's too (range by range, sizes default to 1)
UINT di = 0, dn = 0, si = 0, sn = 0;
auto dsize = [&](UINT i) { return dest_sizes ? dest_sizes[i] : 1u; };
auto ssize = [&](UINT i) { return src_sizes ? src_sizes[i] : 1u; };
while (di < dest_ranges && si < src_ranges) {
bx_console_copy_title(dest_starts[di].ptr + 32ull * dn, src_starts[si].ptr + 32ull * sn, 1);
if (++dn >= dsize(di)) { ++di; dn = 0; }
if (++sn >= ssize(si)) { ++si; sn = 0; }
}
}
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;
@@ -226,10 +212,6 @@ void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count
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);
if (bx_console_translation_enabled()) {
bx_console_list_set_render_targets(bx_xbox_host<ID3D12GraphicsCommandList>(self), n, rtvs ? host_rtvs : nullptr,
single_range, dsv ? &host_dsv : nullptr);
}
}
namespace {
@@ -272,13 +254,11 @@ void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetVertexBuffers(start, n, views ? host : nullptr);
bx_xbox_rect_note_vertex_buffers(bx_xbox_host<ID3D12GraphicsCommandList>(self), start, n, views);
bx_console_note_vb(bx_xbox_host<ID3D12GraphicsCommandList>(self), start, n, views);
}
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{};
bx_console_note_ib(bx_xbox_host<ID3D12GraphicsCommandList>(self), view);
if (view) {
host = *view;
if (view->BufferLocation &&
+94
View File
@@ -0,0 +1,94 @@
/* Console texture layouts through the GDK's own XG library (see gdk_xg.h).
*
* The documented interface (GDK xg_xs.h):
* HRESULT XGCreateTextureComputer(const XG_RESOURCE_DESC*, XGTextureAddressComputer**);
* XG_RESOURCE_DESC has the field order and sizes of D3D12_RESOURCE_DESC, with
* XG12_RESOURCE_MISC_FLAG in place of D3D12_RESOURCE_FLAGS; the title's console flags
* (render target, depth, UAV, deny-compression) are those values.
* XGTextureAddressComputer vtable: 0 AddRef, 1 Release, 2 GetResourceLayout,
* 3 GetResourceSizeBytes, 4 GetResourceBaseAlignmentBytes, ...
* void XGEnableExclusiveLocking(BOOL), to be called before any computer is created.
*/
#include "gdk_xg.h"
#include "bx_log.h"
#include <atomic>
#include <cstdio>
namespace {
struct XgComputer;
struct XgComputerVtbl {
ULONG(__cdecl* AddRef)(XgComputer*);
ULONG(__cdecl* Release)(XgComputer*);
void* GetResourceLayout;
UINT64 (*GetResourceSizeBytes)(XgComputer*);
UINT64 (*GetResourceBaseAlignmentBytes)(XgComputer*);
};
struct XgComputer {
const XgComputerVtbl* vtbl;
};
using CreateTextureComputerFn = HRESULT(__cdecl*)(const D3D12_RESOURCE_DESC*, XgComputer**);
using EnableLockingFn = void(__cdecl*)(BOOL);
HMODULE microsoft_xg() {
static const HMODULE module = [] {
HMODULE xg = GetModuleHandleW(L"xg_xs.dll");
if (!xg) xg = LoadLibraryW(L"xg_xs.dll");
const bool microsoft = xg && GetProcAddress(xg, "XGComputeTexture2DLayout");
bx_log_emit(microsoft ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "gdk_xg",
microsoft ? "GDK XG library loaded: console texture layouts are computed by it"
: "GDK XG library not loaded: console textures are sized linearly (bx-cli run stages it "
"from the configured GDK)");
return microsoft ? xg : static_cast<HMODULE>(nullptr);
}();
return module;
}
CreateTextureComputerFn create_computer() {
static const CreateTextureComputerFn fn = [] {
HMODULE xg = microsoft_xg();
return xg ? reinterpret_cast<CreateTextureComputerFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGCreateTextureComputer")))
: nullptr;
}();
return fn;
}
} // namespace
bool bx_gdk_xg_available() { return create_computer() != nullptr; }
bool bx_is_console_texture_layout(const D3D12_RESOURCE_DESC& desc) {
return desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && desc.Dimension != D3D12_RESOURCE_DIMENSION_UNKNOWN &&
static_cast<UINT>(desc.Layout) >= 0x100;
}
bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint64_t* alignment) {
const CreateTextureComputerFn create = create_computer();
if (!create || !bx_is_console_texture_layout(desc)) return false;
XgComputer* computer = nullptr;
const HRESULT hr = create(&desc, &computer);
if (FAILED(hr) || !computer) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 8) {
char detail[160];
std::snprintf(detail, sizeof(detail), "XGCreateTextureComputer refused %llux%u layout=0x%x format=%d: hr=0x%08lx",
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<UINT>(desc.Layout),
static_cast<int>(desc.Format), static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gdk_xg", detail);
}
return false;
}
*size = computer->vtbl->GetResourceSizeBytes(computer);
*alignment = computer->vtbl->GetResourceBaseAlignmentBytes(computer);
computer->vtbl->Release(computer);
return true;
}
extern "C" void bx_gdk_xg_enable_locking() {
HMODULE xg = microsoft_xg();
if (!xg) return;
auto enable = reinterpret_cast<EnableLockingFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGEnableExclusiveLocking")));
if (enable) enable(TRUE);
}
+27
View File
@@ -0,0 +1,27 @@
#pragma once
/* Console texture layouts through the GDK's own XG library.
*
* Console textures are laid out in tiled swizzle modes (D3D12XBOX_TEXTURE_LAYOUT / XG_TEXTURE_LAYOUT,
* 0x100 | XG_SWIZZLE_MODE). A title sizes its loads and placements from those layouts, so a
* linear answer makes it read less than the tiled data it stored. The layouts are computed by
* Microsoft's xg_xs.dll from the collaborator's own GDK, staged by `bx-cli run` in place of
* BetterXen's xg_xs shim (which exports only the two functions titles import). Nothing from the
* GDK is shipped. Without it these helpers report that no console layout is available.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
/* True when Microsoft's XG library is the loaded xg_xs.dll (it exports XGComputeTexture2DLayout). */
bool bx_gdk_xg_available();
/* A console texture layout (Layout >= 0x100) that the GDK's XG can describe. */
bool bx_is_console_texture_layout(const D3D12_RESOURCE_DESC& desc);
/* Size and base alignment of `desc` in the console layout. False when XG is not available or
refuses the description; `size` and `alignment` are then untouched. */
bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint64_t* alignment);
/* Enables XG's internal lock (XGEnableExclusiveLocking) before any texture computer is created,
so the title's threads and the shim can both create computers. Called at device creation. */
extern "C" void bx_gdk_xg_enable_locking();
-2
View File
@@ -8,7 +8,6 @@
* writes are therefore synchronous (logged once); executes without writes are not changed.
*/
#include "xbox_facade.h"
#include "console_translate.h"
#include <atomic>
#include <cstdio>
@@ -160,7 +159,6 @@ void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
for (const Write& w : pending) {
if (w.wait) apply_wait(queue, w);
}
bx_console_submit(host.data(), count);
queue->ExecuteCommandLists(count, host.data());
bool any_write = false;
for (const Write& w : pending) any_write = any_write || !w.wait;
+14 -374
View File
@@ -18,18 +18,12 @@
#include "proxy.h"
#include "shader_gate.h"
#include "console_translate.h"
#include "console_formats.h"
#include <algorithm>
#include <atomic>
#include <unordered_set>
#include <string>
#include <cstdio>
#include <cstring>
#include <vector>
#include <mutex>
#include <unordered_map>
namespace {
@@ -44,37 +38,10 @@ bool null_render_enabled() {
return enabled;
}
/* BX_PSO_PROFILE=1 (local diagnostics, off by default): each null pipeline gets an id, its
creation is described in a `pso_profile` record, and skipped draws and dispatches name the id
they were recorded with. The records hold title-derived sizes and hashes: they belong in
private evidence, never in the repository. */
bool pso_profile_enabled() {
static const bool enabled = [] {
char value[8] = {};
const DWORD n = GetEnvironmentVariableA("BX_PSO_PROFILE", value, sizeof(value));
return n > 0 && n < sizeof(value) && value[0] == '1';
}();
return enabled;
}
thread_local const char* t_pending_profile = nullptr; // description of the pipeline being refused
thread_local std::shared_ptr<BxTranslated> t_pending_translated; // translation for the pipeline being refused
struct DrawArgs {
UINT count, instances, start;
INT base;
bool indexed;
};
thread_local DrawArgs t_draw{}; // diagnostic: arguments of the draw being recorded
thread_local std::shared_ptr<BxTranslated> t_applied; // the translated pipeline list_skips just bound, if any
std::atomic<uint32_t> g_next_null_id{1};
/* A pipeline-state object with no host pipeline behind it. */
class NullPipelineState final : public ID3D12PipelineState {
public:
explicit NullPipelineState(ID3D12Device* device) : device_(device), id_(g_next_null_id.fetch_add(1)) {
device_->AddRef();
}
uint32_t id() const { return id_; }
std::shared_ptr<BxTranslated> translated; // console stages with translated shaders, if any
explicit NullPipelineState(ID3D12Device* device) : device_(device) { device_->AddRef(); }
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
if (!ppv) return E_POINTER;
@@ -111,7 +78,6 @@ public:
private:
ID3D12Device* device_;
uint32_t id_;
std::atomic<ULONG> refs_{1};
};
@@ -122,9 +88,6 @@ 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;
std::unordered_map<const void*, uint32_t> g_list_pso; // profile: null pipeline id bound per list
std::unordered_map<uint32_t, uint64_t> g_pso_uses; // profile: skipped work per null pipeline id
std::unordered_map<const void*, std::shared_ptr<BxTranslated>> g_list_translated; // translated pipeline bound per list
template <typename T>
bool push(T**& items, size_t& count, size_t& capacity, T* item) {
@@ -161,71 +124,24 @@ bool contains(T* const* items, size_t count, const T* item) {
}
/* Returns the host pipeline for a title pipeline, or nullptr for a null pipeline. */
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null, uint32_t* null_id = nullptr,
std::shared_ptr<BxTranslated>* translated = nullptr) {
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null) {
ID3D12PipelineState* host = bx_xbox_unwrap_as(title);
std::lock_guard<std::mutex> guard(g_lock);
auto* as_null = static_cast<NullPipelineState*>(static_cast<void*>(host));
*is_null = host && contains(g_nulls, g_null_count, as_null);
if (null_id) *null_id = *is_null ? as_null->id() : 0;
if (translated) *translated = *is_null ? as_null->translated : nullptr;
*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, uint32_t null_id = 0,
std::shared_ptr<BxTranslated> translated = nullptr) {
void set_list_null(ID3D12GraphicsCommandList* list, bool null_bound) {
std::lock_guard<std::mutex> guard(g_lock);
if (translated) {
g_list_translated[list] = std::move(translated);
} else {
g_list_translated.erase(list);
}
if (pso_profile_enabled()) g_list_pso[list] = null_bound ? null_id : 0;
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, bool is_draw = false) {
uint32_t id = 0;
uint64_t uses = 0;
std::shared_ptr<BxTranslated> translated;
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;
if (is_draw) {
auto it = g_list_translated.find(list);
if (it != g_list_translated.end()) translated = it->second;
}
}
t_applied.reset();
if (translated && bx_console_apply(translated.get(), list)) {
t_applied = translated;
bx_console_evidence(bx_console_key(translated.get()), list, 0);
bx_console_draw_state(bx_console_key(translated.get()), list, t_draw.count, t_draw.instances, t_draw.start, t_draw.base,
t_draw.indexed);
bx_console_record_draw(translated, list);
static std::atomic<uint64_t> drawn{0};
const uint64_t k = ++drawn;
if ((k & (k - 1)) == 0) {
char detail[96];
std::snprintf(detail, sizeof(detail), "%s with a translated console pipeline; total=%llu", what,
static_cast<unsigned long long>(k));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_draw", detail);
}
return false;
}
{
std::lock_guard<std::mutex> guard(g_lock);
if (pso_profile_enabled()) {
id = g_list_pso[list];
uses = ++g_pso_uses[id];
}
}
if (pso_profile_enabled() && (uses & (uses - 1)) == 0) { // each id's 1st, 2nd, 4th, ... use
char detail[96];
std::snprintf(detail, sizeof(detail), "use id=%u %s uses=%llu", id, what, static_cast<unsigned long long>(uses));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_profile", detail);
}
static std::atomic<uint64_t> skipped{0};
const uint64_t n = ++skipped;
@@ -253,15 +169,6 @@ HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid,
return E_OUTOFMEMORY;
}
}
if (pso_profile_enabled()) {
char detail[1800];
std::snprintf(detail, sizeof(detail), "create id=%u kind=%s %s", null_pso->id(), kind,
t_pending_profile ? t_pending_profile : "");
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_profile", detail);
}
t_pending_profile = nullptr;
null_pso->translated = std::move(t_pending_translated);
t_pending_translated.reset();
*ppv = static_cast<ID3D12PipelineState*>(null_pso);
return bx_xbox_wrap_result(S_OK, riid, ppv);
}
@@ -319,9 +226,6 @@ HRESULT create_graphics(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* de
return bx_xbox_wrap_result(hr, riid, ppv);
}
void dump_blob(const char* name, uint64_t hash, const char* part, const void* data, size_t size);
uint64_t fnv1a(const void* data, size_t size);
HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
@@ -342,48 +246,16 @@ HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
ID3D12RootSignature* root = nullptr;
std::memcpy(&root, &stream[root_offset], sizeof(root));
root = bx_xbox_unwrap_as(root);
if (pso_profile_enabled()) {
char d[64];
std::snprintf(d, sizeof(d), "stream pipeline root=%p", static_cast<void*>(root));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "pso_profile", d);
}
std::memcpy(&stream[root_offset], &root, sizeof(root));
}
BxShaderGate gate;
HRESULT first_failure = S_OK;
D3D12_SHADER_BYTECODE vs{}, ps{};
bool other_stage = false;
thread_local char stream_profile[400];
size_t described = 0;
stream_profile[0] = 0;
ID3D12RootSignature* host_root = nullptr;
if (root_offset != SIZE_MAX) std::memcpy(&host_root, &stream[root_offset], sizeof(host_root));
for (size_t i = 0; i < offsets.size(); ++i) {
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;
if (in.pShaderBytecode && in.BytecodeLength) {
const uint64_t h = fnv1a(in.pShaderBytecode, in.BytecodeLength);
dump_blob(names[i], h, "container", in.pShaderBytecode, in.BytecodeLength);
if (std::strcmp(names[i], "VS") == 0) {
vs = in;
} else if (std::strcmp(names[i], "PS") == 0) {
ps = in;
} else {
other_stage = true;
}
if (pso_profile_enabled() && described < sizeof(stream_profile)) {
const int k = std::snprintf(stream_profile + described, sizeof(stream_profile) - described, " %s=%llu#%016llx",
names[i], static_cast<unsigned long long>(in.BytecodeLength),
static_cast<unsigned long long>(h));
if (k > 0) described += static_cast<size_t>(k);
}
}
hr = gate.admit("stream", names[i], in, out);
if (SUCCEEDED(hr)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
else if (SUCCEEDED(first_failure)) first_failure = hr;
}
hr = first_failure;
const size_t topology_at = bx_stream_payload(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY);
if (topology_at != SIZE_MAX) {
D3D12_PRIMITIVE_TOPOLOGY_TYPE type{};
@@ -394,136 +266,7 @@ HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
admitted.pPipelineStateSubobjectStream = stream.data();
if (SUCCEEDED(hr)) hr = device->CreatePipelineState(&admitted, riid, ppv);
if (FAILED(hr)) {
if (pso_profile_enabled() && described) t_pending_profile = stream_profile;
// Console shader containers: a VS/PS pair with translated shaders in the cache (opt-in).
if (bx_console_translation_enabled() && !other_stage && vs.pShaderBytecode && ps.pShaderBytecode && host_root) {
t_pending_translated = bx_console_translate_graphics(device, host_root, vs.pShaderBytecode, vs.BytecodeLength,
ps.pShaderBytecode, ps.BytecodeLength);
if (bx_console_uses_stream_layout(t_pending_translated.get())) {
// The title's own stream with three substitutions: the translated shaders, an
// input layout whose semantics are ATTR<k> in element order, and host formats.
std::vector<uint8_t> host_stream = stream;
std::vector<D3D12_INPUT_ELEMENT_DESC> elements;
for (size_t i = 0; i < offsets.size(); ++i) {
const bool pixel = std::strcmp(names[i], "PS") == 0;
// Only the two translated stages: the stream also carries (empty) entries for
// the tessellation and geometry stages, which must stay empty.
if (!pixel && std::strcmp(names[i], "VS") != 0) continue;
D3D12_SHADER_BYTECODE code{};
size_t size = 0;
code.pShaderBytecode = bx_console_shader(t_pending_translated.get(), pixel, &size);
code.BytecodeLength = size;
std::memcpy(&host_stream[offsets[i]], &code, sizeof(code));
}
const size_t layout_at = bx_stream_payload(host_stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT);
if (layout_at != SIZE_MAX) {
D3D12_INPUT_LAYOUT_DESC layout{};
std::memcpy(&layout, &host_stream[layout_at], sizeof(layout));
for (UINT k = 0; layout.pInputElementDescs && k < layout.NumElements; ++k) {
D3D12_INPUT_ELEMENT_DESC e = layout.pInputElementDescs[k];
e.SemanticName = "ATTR";
e.SemanticIndex = k;
e.Format = bx_host_format(e.Format);
elements.push_back(e);
}
layout.pInputElementDescs = elements.data();
std::memcpy(&host_stream[layout_at], &layout, sizeof(layout));
}
const size_t rt_at = bx_stream_payload(host_stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS);
D3D12_RT_FORMAT_ARRAY formats{};
if (rt_at != SIZE_MAX) {
std::memcpy(&formats, &host_stream[rt_at], sizeof(formats));
for (UINT k = 0; k < 8; ++k) formats.RTFormats[k] = bx_host_format(formats.RTFormats[k]);
std::memcpy(&host_stream[rt_at], &formats, sizeof(formats));
}
const size_t ds_at = bx_stream_payload(host_stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT);
DXGI_FORMAT depth = DXGI_FORMAT_UNKNOWN;
if (ds_at != SIZE_MAX) {
std::memcpy(&depth, &host_stream[ds_at], sizeof(depth));
depth = bx_host_format(depth);
std::memcpy(&host_stream[ds_at], &depth, sizeof(depth));
}
const size_t topology_at = bx_stream_payload(host_stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY);
bx_console_set_stream(t_pending_translated.get(), std::vector<uint8_t>(host_stream), std::move(elements), layout_at,
rt_at, ds_at, topology_at);
{
char text[600];
int at = 0;
auto add = [&](const char* fmt, auto... args) {
if (at < static_cast<int>(sizeof(text)) - 1) at += std::snprintf(text + at, sizeof(text) - at, fmt, args...);
};
const size_t blend_at = bx_stream_payload(host_stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND);
if (blend_at != SIZE_MAX) {
D3D12_BLEND_DESC b{};
std::memcpy(&b, &host_stream[blend_at], sizeof(b));
add("blend0 enable=%d src=%d dst=%d op=%d srcA=%d dstA=%d mask=0x%x a2c=%d indep=%d; ", b.RenderTarget[0].BlendEnable,
b.RenderTarget[0].SrcBlend, b.RenderTarget[0].DestBlend, b.RenderTarget[0].BlendOp, b.RenderTarget[0].SrcBlendAlpha,
b.RenderTarget[0].DestBlendAlpha, b.RenderTarget[0].RenderTargetWriteMask, b.AlphaToCoverageEnable,
b.IndependentBlendEnable);
} else add("no blend; ");
const size_t mask_at = bx_stream_payload(host_stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK);
if (mask_at != SIZE_MAX) {
UINT m = 0;
std::memcpy(&m, &host_stream[mask_at], sizeof(m));
add("sample_mask=0x%x; ", m);
} else add("no sample mask; ");
const size_t rs_at = bx_stream_payload(host_stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER);
if (rs_at != SIZE_MAX) {
D3D12_RASTERIZER_DESC r{};
std::memcpy(&r, &host_stream[rs_at], sizeof(r));
add("fill=%d cull=%d ccw=%d clip=%d ms=%d forced=%u cons=%d; ", r.FillMode, r.CullMode, r.FrontCounterClockwise,
r.DepthClipEnable, r.MultisampleEnable, r.ForcedSampleCount, r.ConservativeRaster);
} else add("no rasterizer; ");
for (auto type : {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1}) {
const size_t ds = bx_stream_payload(host_stream, type);
if (ds == SIZE_MAX) continue;
D3D12_DEPTH_STENCIL_DESC d{};
std::memcpy(&d, &host_stream[ds], sizeof(d));
add("depth%d enable=%d write=%d func=%d stencil=%d rmask=0x%x front(func=%d); ",
type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, d.DepthEnable, d.DepthWriteMask, d.DepthFunc,
d.StencilEnable, d.StencilReadMask, d.FrontFace.StencilFunc);
}
const size_t topo_at = bx_stream_payload(host_stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY);
if (topo_at != SIZE_MAX) {
UINT topo = 0;
std::memcpy(&topo, &host_stream[topo_at], sizeof(topo));
add("topology_type=%u; ", topo);
} else add("no topology type; ");
const size_t sd_at = bx_stream_payload(host_stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC);
if (sd_at != SIZE_MAX) {
DXGI_SAMPLE_DESC sd{};
std::memcpy(&sd, &host_stream[sd_at], sizeof(sd));
add("samples=%u/%u", sd.Count, sd.Quality);
} else add("no sample desc");
bx_console_stream_state(bx_console_key(t_pending_translated.get()), text);
{ // every subobject in the stream: type and the first words of its payload
char list_text[640];
int lt = 0;
for (uint32_t type = 0; type < 32 && lt < static_cast<int>(sizeof(list_text)) - 60; ++type) {
const size_t at = bx_stream_payload(host_stream, type);
if (at == SIZE_MAX) continue;
uint32_t w[4] = {};
std::memcpy(w, &host_stream[at], std::min<size_t>(sizeof(w), host_stream.size() - at));
lt += std::snprintf(list_text + lt, sizeof(list_text) - lt, " t%u@%zu[%x %x %x %x]", type, at, w[0], w[1], w[2], w[3]);
}
std::string k = std::string(bx_console_key(t_pending_translated.get())) + "#subobjects";
bx_console_stream_state(k.c_str(), list_text);
const size_t ds1 = bx_stream_payload(host_stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1);
if (ds1 != SIZE_MAX) {
D3D12_DEPTH_STENCIL_DESC1 d1{};
std::memcpy(&d1, &host_stream[ds1], sizeof(d1));
char dt[120];
std::snprintf(dt, sizeof(dt), "depth bounds test enable=%d (size of stream %zu)", d1.DepthBoundsTestEnable, host_stream.size());
k = std::string(bx_console_key(t_pending_translated.get())) + "#depthbounds";
bx_console_stream_state(k.c_str(), dt);
}
}
}
}
}
return refused(device, hr, "stream", riid, ppv);
}
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv);
{
D3D12_INPUT_LAYOUT_DESC layout{};
const size_t layout_at = bx_stream_payload(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT);
@@ -554,7 +297,6 @@ void bx_xbox_pipeline_forget(IUnknown* host) {
void bx_xbox_list_forget(IUnknown* host) {
bx_xbox_rect_list_forget(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
bx_console_list_reset(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
std::lock_guard<std::mutex> guard(g_lock);
erase(g_lists, g_list_count, static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
}
@@ -565,7 +307,6 @@ void STDMETHODCALLTYPE bx_xbox_list_ia_set_primitive_topology(void* self, D3D12_
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetPrimitiveTopology");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
list->IASetPrimitiveTopology(bx_xbox_rect_note_topology(list, topology));
bx_console_note_topology(list, topology);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
@@ -600,10 +341,8 @@ void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12Pipelin
BX_D3D_TRACE("XboxGraphicsCommandList", "SetPipelineState");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
bool is_null = false;
uint32_t null_id = 0;
std::shared_ptr<BxTranslated> translated;
ID3D12PipelineState* host = host_pipeline(pso, &is_null, &null_id, &translated);
set_list_null(list, is_null, null_id, std::move(translated));
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
set_list_null(list, is_null);
bx_xbox_rect_note_pipeline(list, host);
if (!is_null) list->SetPipelineState(host);
}
@@ -612,14 +351,11 @@ HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator*
BX_D3D_TRACE("XboxGraphicsCommandList", "Reset");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
bool is_null = false;
uint32_t null_id = 0;
std::shared_ptr<BxTranslated> translated;
ID3D12PipelineState* host = host_pipeline(pso, &is_null, &null_id, &translated);
set_list_null(list, is_null, null_id, std::move(translated));
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
set_list_null(list, is_null);
bx_xbox_gpu_writes_reset(list);
bx_xbox_bound_memory_reset(list);
bx_xbox_rect_list_reset(list, host);
bx_console_list_reset(list);
return list->Reset(bx_xbox_unwrap_as(allocator), host);
}
@@ -627,8 +363,7 @@ void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UI
UINT first_instance) {
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawInstanced");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
t_draw = {vertices, instances, first_vertex, 0, false};
if (list_skips(list, "DrawInstanced", true)) return;
if (list_skips(list, "DrawInstanced")) return;
if (!bx_xbox_draw_rect_list(list, vertices, instances, first_vertex, first_instance)) {
list->DrawInstanced(vertices, instances, first_vertex, first_instance);
}
@@ -638,8 +373,7 @@ void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indi
INT base_vertex, UINT first_instance) {
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawIndexedInstanced");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
t_draw = {indices, instances, first_index, base_vertex, true};
if (list_skips(list, "DrawIndexedInstanced", true)) return;
if (list_skips(list, "DrawIndexedInstanced")) return;
if (bx_xbox_rect_list_bound(list)) {
BX_STUB_LOG("d3d12_xs.dll", "DrawIndexedInstanced(rectangle list)");
return;
@@ -742,91 +476,6 @@ void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void*, void* callback, U
} // extern "C"
namespace {
/* Layouts from the authorized GDK header (D3D12XBOX_DESERIALIZE_*_PIPELINE_STATE). */
struct DeserializeShader {
const void* instructions;
SIZE_T instructions_size;
const void* metadata;
SIZE_T metadata_size;
};
struct DeserializeGraphics {
ID3D12RootSignature* root;
void* packet;
SIZE_T packet_size;
void* metadata;
SIZE_T metadata_size;
DeserializeShader stages[7]; // PS, VS, GS, ES, HS, LS, FS
};
struct DeserializeCompute {
ID3D12RootSignature* root;
void* packet;
SIZE_T packet_size;
void* metadata;
SIZE_T metadata_size;
DeserializeShader cs;
};
uint64_t fnv1a(const void* data, size_t size) {
uint64_t h = 1469598103934665603ull;
const auto* p = static_cast<const uint8_t*>(data);
for (size_t i = 0; data && i < size; ++i) h = (h ^ p[i]) * 1099511628211ull;
return h;
}
/* BX_PSO_DUMP=<folder> with BX_PSO_DUMP_HASHES=<hex,hex,...>: writes the stages whose
instruction hash is listed (local evidence only). */
void dump_blob(const char* name, uint64_t hash, const char* part, const void* data, size_t size) {
static char folder[512] = {};
static char hashes[1024] = {};
static const bool on = [] {
return GetEnvironmentVariableA("BX_PSO_DUMP", folder, sizeof(folder)) > 0 &&
GetEnvironmentVariableA("BX_PSO_DUMP_HASHES", hashes, sizeof(hashes)) > 0;
}();
if (!on || !data || !size) return;
char hex[20];
std::snprintf(hex, sizeof(hex), "%016llx", static_cast<unsigned long long>(hash));
if (std::strcmp(hashes, "*") != 0 && !std::strstr(hashes, hex)) return;
{ // each hash once
static std::mutex seen_lock;
static std::unordered_set<uint64_t> seen;
std::lock_guard<std::mutex> guard(seen_lock);
if (!seen.insert(hash ^ static_cast<uint64_t>(part[0])).second) return;
}
char path[640];
std::snprintf(path, sizeof(path), "%s\\%s_%s.%s.bin", folder, hex, name, part);
if (FILE* f = std::fopen(path, "wb")) {
std::fwrite(data, 1, size, f);
std::fclose(f);
}
}
size_t describe_stage(char* out, size_t room, const char* name, const DeserializeShader& s) {
if (!s.instructions || !s.instructions_size || room < 2) return 0;
{
const uint64_t h = fnv1a(s.instructions, s.instructions_size);
dump_blob(name, h, "code", s.instructions, s.instructions_size);
dump_blob(name, h, "meta", s.metadata, s.metadata_size);
}
const int n = std::snprintf(out, room, " %s=%llu/%llu#%016llx", name,
static_cast<unsigned long long>(s.instructions_size),
static_cast<unsigned long long>(s.metadata_size),
static_cast<unsigned long long>(fnv1a(s.instructions, s.instructions_size)));
return n > 0 && static_cast<size_t>(n) < room ? static_cast<size_t>(n) : 0;
}
thread_local char t_profile_buffer[1600];
size_t describe_header(const void* packet, SIZE_T packet_size, SIZE_T metadata_size) {
dump_blob("pipeline", fnv1a(packet, packet_size), "packet", packet, packet_size);
const int n = std::snprintf(t_profile_buffer, sizeof(t_profile_buffer), "packet=%llu#%016llx meta=%llu",
static_cast<unsigned long long>(packet_size),
static_cast<unsigned long long>(fnv1a(packet, packet_size)),
static_cast<unsigned long long>(metadata_size));
return n > 0 ? static_cast<size_t>(n) : 0;
}
} // namespace
/*
* DeserializeGraphics/ComputePipelineStateX create a pipeline from a serialized console pipeline
* (console shader code), which has no host form. They always fail with E_NOTIMPL and log
@@ -860,16 +509,7 @@ namespace {
HRESULT derived(ID3D12PipelineState* source, void** ppv, const char* kind) {
if (!ppv) return E_POINTER;
*ppv = nullptr;
bool from_null = false;
uint32_t source_id = 0;
std::shared_ptr<BxTranslated> inherited;
host_pipeline(source, &from_null, &source_id, &inherited);
t_pending_translated = std::move(inherited); // a derived pipeline runs the same shaders
thread_local char derived_profile[48];
if (pso_profile_enabled()) {
std::snprintf(derived_profile, sizeof(derived_profile), "source=%u", source_id);
t_pending_profile = derived_profile;
}
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) {
+1 -298
View File
@@ -17,7 +17,6 @@
*/
#include "console_formats.h"
#include "xbox_facade.h"
#include "console_translate.h"
#include <atomic>
#include <cstdio>
@@ -89,130 +88,12 @@ bool readable(const void* p, uint64_t size) {
return true;
}
/* Bytes per texel of the uncompressed formats a linear console texture is uploaded for, or 0. */
UINT linear_texel_bytes(DXGI_FORMAT f) {
switch (f) {
case DXGI_FORMAT_A8_UNORM:
case DXGI_FORMAT_R8_UNORM:
case DXGI_FORMAT_R8_UINT: return 1;
case DXGI_FORMAT_R8G8_UNORM:
case DXGI_FORMAT_R16_FLOAT:
case DXGI_FORMAT_R16_UNORM: return 2;
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
case DXGI_FORMAT_B8G8R8A8_UNORM:
case DXGI_FORMAT_R32_FLOAT:
case DXGI_FORMAT_R32_UINT:
case DXGI_FORMAT_R10G10B10A2_UNORM: return 4;
case DXGI_FORMAT_R16G16B16A16_FLOAT: return 8;
default: return 0;
}
}
constexpr UINT kConsoleLayoutLinear = 0x100; // D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR (GDK)
bool linear_uploadable(const D3D12_RESOURCE_DESC& desc) {
return desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && static_cast<UINT>(desc.Layout) == kConsoleLayoutLinear &&
desc.DepthOrArraySize == 1 && linear_texel_bytes(desc.Format) != 0 &&
!(desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL));
}
/* Bytes per element (texel, or 4x4 block for BCn) of the formats a tiled texture is uploaded for, or 0. */
UINT element_bytes(DXGI_FORMAT f, bool* block) {
*block = false;
switch (f) {
case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM:
*block = true; return 8;
case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB:
case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB:
case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM:
case DXGI_FORMAT_BC6H_TYPELESS: case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16:
case DXGI_FORMAT_BC7_TYPELESS: case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB:
*block = true; return 16;
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_R16G16_FLOAT:
case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R16G16_UNORM:
return 4;
case DXGI_FORMAT_R32G32B32A32_FLOAT: return 16;
case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R32G32_FLOAT: return 8;
default: return linear_texel_bytes(f);
}
}
/* The GDK's XG library, when it is the one loaded as xg_xs.dll (bx-cli stages it from the
collaborator's own GDK). BetterXen's xg_xs shim exports only the two functions titles import,
so XGComputeTexture2DLayout marks Microsoft's library. Its texture computer is used through
the documented XGTextureAddressComputer interface (GDK xg_xs.h): slot 0 AddRef, 1 Release,
3 GetResourceSizeBytes, 9 CopyFromSubresource. */
struct XgComputer;
struct XgComputerVtbl {
ULONG(__cdecl* AddRef)(XgComputer*);
ULONG(__cdecl* Release)(XgComputer*);
void* GetResourceLayout;
UINT64 (*GetResourceSizeBytes)(XgComputer*);
void* GetResourceBaseAlignmentBytes;
void* GetMipLevelOffsetBytes;
void* GetTexelElementOffsetBytes;
void* GetTexelCoordinate;
void* CopyIntoSubresource;
HRESULT(__cdecl* CopyFromSubresource)(XgComputer*, void* linear, UINT32 plane, UINT32 subresource, UINT32 sample,
const void* tiled_base, UINT32 row_pitch, UINT32 slice_pitch);
};
struct XgComputer { const XgComputerVtbl* vtbl; };
using XgCreateTextureComputerFn = HRESULT(__cdecl*)(const D3D12_RESOURCE_DESC*, XgComputer**);
/* Microsoft's XG takes an internal lock in its texture-computer creation and layout functions only
when XGEnableExclusiveLocking(TRUE) was called before any computer exists (GDK xg_xs.h). The
title creates computers on its loading threads and the shim on the render thread, so locking is
enabled when the device is created. BX_XG_LOCKING=0 leaves it off. */
extern "C" void bx_xbox_xg_enable_locking() {
HMODULE xg = GetModuleHandleW(L"xg_xs.dll");
if (!xg) xg = LoadLibraryW(L"xg_xs.dll");
if (!xg || !GetProcAddress(xg, "XGComputeTexture2DLayout")) return;
char off[4] = {};
if (GetEnvironmentVariableA("BX_XG_LOCKING", off, sizeof(off)) && off[0] == '0') return;
using EnableFn = void(__cdecl*)(BOOL);
auto enable = reinterpret_cast<EnableFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGEnableExclusiveLocking")));
if (!enable) return;
enable(TRUE);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "texture_detiling", "GDK XG library: exclusive locking enabled");
}
XgCreateTextureComputerFn gdk_xg() {
static const XgCreateTextureComputerFn fn = [] {
char off[4] = {};
if (GetEnvironmentVariableA("BX_DETILE", off, sizeof(off)) && off[0] == '0') {
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "texture_detiling", "BX_DETILE=0: detiling disabled");
return static_cast<XgCreateTextureComputerFn>(nullptr);
}
HMODULE xg = GetModuleHandleW(L"xg_xs.dll");
if (!xg) xg = LoadLibraryW(L"xg_xs.dll");
const bool microsoft = xg && GetProcAddress(xg, "XGComputeTexture2DLayout");
auto create = microsoft ? reinterpret_cast<XgCreateTextureComputerFn>(
reinterpret_cast<void*>(GetProcAddress(xg, "XGCreateTextureComputer")))
: nullptr;
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "texture_detiling",
create ? "GDK XG library loaded: console textures are detiled on upload"
: "GDK XG library not loaded: only linear console textures are uploaded");
return create;
}();
return fn;
}
bool tiled_uploadable(const D3D12_RESOURCE_DESC& desc) {
bool block = false;
return gdk_xg() && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count <= 1 &&
element_bytes(desc.Format, &block) != 0 && !bx_is_console_only_format(desc.Format) &&
!(desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL |
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS));
}
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 || linear_uploadable(desc)) { // CPU-writable: buffers are copied, linear textures written per texel row
if (buffer) {
heap.Type = D3D12_HEAP_TYPE_CUSTOM;
heap.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
@@ -252,17 +133,6 @@ HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURC
}
} else {
BX_STUB_LOG("d3d12_xs.dll", "CreatePlacedResourceX(texture contents)");
{ // LOCAL DIAGNOSTIC: the console layout of each placed texture
static std::atomic<int> shown{0};
if (shown.fetch_add(1) < 400) {
char d[200];
std::snprintf(d, sizeof(d), "texture layout=0x%x flags=0x%x %llux%u depth=%u mips=%u format=%d align=%llu",
static_cast<unsigned>(desc.Layout), static_cast<unsigned>(desc.Flags),
static_cast<unsigned long long>(desc.Width), desc.Height, desc.DepthOrArraySize, desc.MipLevels,
static_cast<int>(desc.Format), static_cast<unsigned long long>(desc.Alignment));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "texture_layout", d);
}
}
}
if (!remember({resource, title_va, desc.Width, buffer, desc, 0})) {
resource->Release();
@@ -346,7 +216,6 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
device->CreateShaderResourceView(resource, host.of(&pc, "CreatePlacedRawShaderResourceViewX"), bx_xbox_host_cpu_handle(dest));
bx_console_mark_srv(dest.ptr, resource, &pc, view_location(xbox_desc), resource_desc->Width);
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
@@ -370,7 +239,6 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Reso
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(
bx_xbox_unwrap_as(resource), xbox_desc ? host.of(&pc, "CreatePlacedShaderResourceViewX") : nullptr,
bx_xbox_host_cpu_handle(dest));
bx_console_mark_srv(dest.ptr, bx_xbox_unwrap_as(resource), xbox_desc ? &pc : nullptr);
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
@@ -494,127 +362,6 @@ void bx_xbox_refresh_bound_memory(ID3D12CommandList* const* host_lists, UINT cou
}
}
/* A linear console texture (mip 0) is written from title memory to its CPU-writable host texture,
at most every 50 ms per texture. Rows in title memory are 256-byte aligned, the layout xg_xs
reports for linear textures. Returns false when `host` is not such a texture. */
/* A CPU-writable copy of a tiled texture's host resource, made the first time a translated pipeline
samples it; the title's own resource stays on its default heap. Keyed by host and title address. */
ID3D12Resource* detiled_copy(ID3D12Resource* host, uint64_t title_va) {
struct Copy { uint64_t title_va; ID3D12Resource* copy; };
static std::mutex lock;
static std::unordered_map<const void*, Copy> copies;
std::lock_guard<std::mutex> guard(lock);
auto found = copies.find(host);
if (found != copies.end() && found->second.title_va == title_va) return found->second.copy;
ID3D12Device* device = nullptr;
if (FAILED(host->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) || !device) return nullptr;
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_CUSTOM;
heap.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK;
heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0;
const D3D12_RESOURCE_DESC desc = host->GetDesc();
ID3D12Resource* copy = nullptr;
const HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&copy));
device->Release();
if (FAILED(hr) || !copy) return nullptr;
if (found != copies.end()) found->second.copy->Release();
copies[host] = Copy{title_va, copy};
return copy;
}
ID3D12Resource* bx_xbox_upload_linear_texture(ID3D12Resource* host) {
Shadow shadow{};
{
std::lock_guard<std::mutex> guard(g_lock);
size_t i = 0;
while (i < g_count && g_shadows[i].host != host) ++i;
if (i == g_count) return host;
shadow = g_shadows[i];
}
if (shadow.buffer) return host;
const bool tiled = tiled_uploadable(shadow.desc);
if (!tiled && !linear_uploadable(shadow.desc)) return host;
ID3D12Resource* target = host;
if (tiled) {
target = detiled_copy(host, shadow.title_va);
if (!target) return host;
}
static std::mutex lock;
static std::unordered_map<const void*, uint64_t> last;
const uint64_t now = GetTickCount64();
{
std::lock_guard<std::mutex> guard(lock);
uint64_t& when = last[host];
if (when && now - when < (tiled ? 500u : 50u)) return target;
when = now;
}
if (tiled) {
XgComputer* computer = nullptr;
HRESULT hr = gdk_xg()(&shadow.desc, &computer);
UINT done = 0;
if (SUCCEEDED(hr) && computer) {
const UINT64 size = computer->vtbl->GetResourceSizeBytes(computer);
if (!readable(reinterpret_cast<const void*>(shadow.title_va), size)) {
hr = E_ACCESSDENIED;
} else if (FAILED(hr = target->Map(0, nullptr, nullptr))) {
} else {
bool block = false;
const UINT eb = element_bytes(shadow.desc.Format, &block);
const UINT mips = shadow.desc.MipLevels ? shadow.desc.MipLevels : 1;
const UINT slices = shadow.desc.DepthOrArraySize ? shadow.desc.DepthOrArraySize : 1;
std::vector<uint8_t> linear;
for (UINT slice = 0; slice < slices && SUCCEEDED(hr); ++slice) {
for (UINT mip = 0; mip < mips && SUCCEEDED(hr); ++mip) {
const UINT w = std::max<UINT>(1u, static_cast<UINT>(shadow.desc.Width >> mip));
const UINT h = std::max<UINT>(1u, shadow.desc.Height >> mip);
const UINT cols = block ? (w + 3) / 4 : w, rows = block ? (h + 3) / 4 : h;
const UINT pitch = cols * eb, slice_pitch = pitch * rows;
linear.resize(slice_pitch);
const UINT sub = mip + slice * mips;
hr = computer->vtbl->CopyFromSubresource(computer, linear.data(), 0, sub, 0,
reinterpret_cast<const void*>(shadow.title_va), pitch, slice_pitch);
if (SUCCEEDED(hr)) hr = target->WriteToSubresource(sub, nullptr, linear.data(), pitch, slice_pitch);
if (SUCCEEDED(hr)) ++done;
}
}
target->Unmap(0, nullptr);
}
computer->vtbl->Release(computer);
}
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 8 || FAILED(hr)) {
static std::atomic<int> failures{0};
if (SUCCEEDED(hr) || failures.fetch_add(1) < 16) {
char detail[200];
std::snprintf(detail, sizeof(detail), "tiled texture %llux%u layout=0x%x format=%d mips=%u: %u subresources, hr=0x%08lx",
static_cast<unsigned long long>(shadow.desc.Width), shadow.desc.Height,
static_cast<UINT>(shadow.desc.Layout), static_cast<int>(shadow.desc.Format), shadow.desc.MipLevels,
done, static_cast<unsigned long>(hr));
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "tiled_texture_upload", detail);
}
}
return target;
}
const UINT bpp = linear_texel_bytes(shadow.desc.Format);
const UINT pitch = static_cast<UINT>((shadow.desc.Width * bpp + 255) / 256 * 256);
const uint64_t bytes = static_cast<uint64_t>(pitch) * shadow.desc.Height;
if (!readable(reinterpret_cast<const void*>(shadow.title_va), bytes)) return host;
if (FAILED(host->Map(0, nullptr, nullptr))) return host;
const HRESULT hr = host->WriteToSubresource(0, nullptr, reinterpret_cast<const void*>(shadow.title_va), pitch,
static_cast<UINT>(bytes));
host->Unmap(0, nullptr);
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 6 || FAILED(hr)) {
char detail[160];
std::snprintf(detail, sizeof(detail), "linear texture %llux%u format=%d pitch=%u from title 0x%llx: hr=0x%08lx",
static_cast<unsigned long long>(shadow.desc.Width), shadow.desc.Height, static_cast<int>(shadow.desc.Format),
pitch, static_cast<unsigned long long>(shadow.title_va), static_cast<unsigned long>(hr));
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "linear_texture_upload", detail);
}
return host;
}
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);
@@ -625,50 +372,6 @@ D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title) {
return title; // not a title address this layer knows: a host address already, or untranslated
}
/* Plain title memory bound as index or vertex data: a CPU-writable host buffer of the same size
is created for the range (once; later ranges inside it reuse it) and refreshed at submission. */
bool bx_xbox_back_title_buffer(ID3D12Device* device, uint64_t va, uint64_t size) {
if (!device || !va || !size) return false;
D3D12_GPU_VIRTUAL_ADDRESS host = 0;
if (bx_xbox_try_host_gpu_va(va, &host) && bx_xbox_try_host_gpu_va(va + size - 1, &host)) return true;
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = size;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
ID3D12Resource* resource = nullptr;
return SUCCEEDED(make_shadow(device, va, desc, "host buffer for bound title memory", &resource)) && resource;
}
/* The title address a host shadow resource was created for (0 when it is not a shadow). */
uint64_t bx_xbox_shadow_title_va(ID3D12Resource* host) {
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 0;
}
/* Copies [title_va, title_va + size) from title memory to the host shadow that
bx_xbox_host_gpu_va resolves the address to (first match). False when there is none. */
bool bx_xbox_sync_title_range(uint64_t title_va, uint64_t size) {
if (!title_va || !size) return false;
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_va >= s.title_va && title_va < s.title_va + s.size) {
const uint64_t begin = title_va - s.title_va;
const uint64_t end = begin + size > s.size ? s.size : begin + size;
if (!readable(reinterpret_cast<const void*>(title_va), end - begin)) return false;
return copy_buffer(s, true, begin, end);
}
}
return false;
}
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});
+3 -27
View File
@@ -12,7 +12,6 @@
* destination rectangles, colour spaces and scaling are not applied (logged once).
*/
#include "xbox_facade.h"
#include "console_translate.h"
#include <dxgi1_4.h>
@@ -187,10 +186,9 @@ UINT64 dump_every() {
return every;
}
void dump_frame(ID3D12CommandQueue* queue, ID3D12Resource* source, const D3D12_RESOURCE_DESC& desc, UINT64 frame,
const wchar_t* tag = L"frame") {
void dump_frame(ID3D12CommandQueue* queue, ID3D12Resource* source, const D3D12_RESOURCE_DESC& desc, UINT64 frame) {
static int written = 0;
if (written >= 160 || desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return;
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;
@@ -257,7 +255,7 @@ void dump_frame(ID3D12CommandQueue* queue, ID3D12Resource* source, const D3D12_R
}
readback->Unmap(0, nullptr);
wchar_t path[MAX_PATH];
std::swprintf(path, MAX_PATH, L"%ls\\%ls_%06llu.bmp", dump_folder(), tag, static_cast<unsigned long long>(frame));
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;
@@ -306,18 +304,6 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
std::lock_guard<std::mutex> guard(g.lock);
if (g.failed) return S_OK;
const D3D12_RESOURCE_DESC desc = source->GetDesc();
{ // diagnostic: which buffer is presented
static ID3D12Resource* last = nullptr;
static std::atomic<int> shown{0};
if (source != last && shown.fetch_add(1) < 12) {
char detail[160];
std::snprintf(detail, sizeof(detail), "presented buffer %p %llux%u format=%d planes=%u resources=%u", static_cast<void*>(source),
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<int>(desc.Format), plane_count,
planes[0].ResourceCount);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_target", detail);
}
last = source;
}
if (!g.swapchain && !create_locked(queue, desc)) {
g.failed = true;
return S_OK; // the title keeps running; frames are not shown (logged)
@@ -369,16 +355,6 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
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 (dump_folder() && n % dump_every() == 0) { // diagnostic: the targets translated draws went into
ID3D12Resource* targets[8];
const int count = bx_console_debug_targets(targets, 8);
for (int k = 0; k < count; ++k) {
if (targets[k] == source) continue;
wchar_t tag[32];
std::swprintf(tag, 32, L"target%d", k);
dump_frame(g.queue, targets[k], targets[k]->GetDesc(), n, tag);
}
}
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),
+2 -2
View File
@@ -324,8 +324,8 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void* self, HAND
/* Committed resources with title-visible memory (committed.cpp). */
// CreateCommittedResourceX takes D3D12XBOX_RESOURCE_DESC: the PC D3D12_RESOURCE_DESC followed by
// DccOptions (authorized GDK header). DccOptions selects console colour compression, which the
// host does not have; it is logged and otherwise ignored.
// DccOptions, a struct of CompressionLevel and ColorTransform (authorized GDK header). DccOptions
// selects console colour compression, which the host does not have; it is logged and otherwise ignored.
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource_x(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const void* xbox_desc,
D3D12_RESOURCE_STATES state,
+1 -15
View File
@@ -1,7 +1,6 @@
// 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.
#include "xbox_tables_generated.h"
#include "console_translate.h"
namespace {
@@ -59,14 +58,8 @@ static HRESULT STDMETHODCALLTYPE x_Device_13(void* self, D3D12_FEATURE a0, void
}
static HRESULT STDMETHODCALLTYPE x_Device_16(void* self, UINT a0, const void * a1, SIZE_T a2, REFIID a3, void ** a4) {
BX_D3D_TRACE("XboxDevice", "CreateRootSignature");
HRESULT hr = E_FAIL;
if (ID3DBlob* wide = bx_console_widen_root_signature(a1, a2)) { // opt-in console translation
hr = bx_xbox_host<ID3D12Device>(self)->CreateRootSignature(a0, wide->GetBufferPointer(), wide->GetBufferSize(), a3, a4);
wide->Release();
}
if (FAILED(hr)) hr = bx_xbox_host<ID3D12Device>(self)->CreateRootSignature(a0, a1, a2, a3, a4);
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateRootSignature(a0, a1, a2, a3, a4);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateRootSignature", hr);
if (SUCCEEDED(hr) && a4 && *a4) bx_console_root_signature_created(static_cast<ID3D12RootSignature*>(*a4), a1, a2);
return bx_xbox_wrap_result(hr, a3, a4);
}
static void STDMETHODCALLTYPE x_Device_22(void* self, const D3D12_SAMPLER_DESC * a0, D3D12_CPU_DESCRIPTOR_HANDLE a1) {
@@ -76,7 +69,6 @@ static void STDMETHODCALLTYPE x_Device_22(void* self, const D3D12_SAMPLER_DESC *
static void STDMETHODCALLTYPE x_Device_24(void* self, UINT a0, const D3D12_CPU_DESCRIPTOR_HANDLE a1, const D3D12_CPU_DESCRIPTOR_HANDLE a2, D3D12_DESCRIPTOR_HEAP_TYPE a3) {
BX_D3D_TRACE("XboxDevice", "CopyDescriptorsSimple");
bx_xbox_host<ID3D12Device>(self)->CopyDescriptorsSimple(a0, bx_xbox_host_cpu_handle(a1), bx_xbox_host_cpu_handle(a2), a3);
if (a3 == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) bx_console_copy_title(a1.ptr, a2.ptr, a0);
}
static D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE x_Device_26(void* self, UINT a0, D3D12_HEAP_TYPE a1) {
BX_D3D_TRACE("XboxDevice", "GetCustomHeapProperties");
@@ -1309,14 +1301,10 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_19(void* self, ID3D12Resourc
static void STDMETHODCALLTYPE x_GraphicsCommandList_21(void* self, UINT a0, const D3D12_VIEWPORT * a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "RSSetViewports");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->RSSetViewports(a0, a1);
bx_console_note_raster(bx_xbox_host<ID3D12GraphicsCommandList>(self), true);
bx_console_note_viewport(bx_xbox_host<ID3D12GraphicsCommandList>(self), a0, a1);
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_22(void* self, UINT a0, const D3D12_RECT * a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "RSSetScissorRects");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->RSSetScissorRects(a0, a1);
bx_console_note_raster(bx_xbox_host<ID3D12GraphicsCommandList>(self), false);
bx_console_note_scissor(bx_xbox_host<ID3D12GraphicsCommandList>(self), a0, a1);
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_23(void* self, const FLOAT a0[4]) {
BX_D3D_TRACE("XboxGraphicsCommandList", "OMSetBlendFactor");
@@ -1367,7 +1355,6 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_35(void* self, UINT a0, D3D1
static void STDMETHODCALLTYPE x_GraphicsCommandList_36(void* self, UINT a0, D3D12_GPU_DESCRIPTOR_HANDLE a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootDescriptorTable");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootDescriptorTable(a0, bx_xbox_host_gpu_handle(a1));
bx_console_note_table(bx_xbox_host<ID3D12GraphicsCommandList>(self), a0, a1.ptr);
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_37(void* self, UINT a0, UINT a1, UINT a2) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRoot32BitConstant");
@@ -1400,7 +1387,6 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_43(void* self, UINT a0, D3D1
static void STDMETHODCALLTYPE x_GraphicsCommandList_44(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootShaderResourceView");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootShaderResourceView(a0, bx_xbox_host_gpu_va(a1));
bx_console_note_root_srv(bx_xbox_host<ID3D12GraphicsCommandList>(self), a0, a1);
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_45(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootUnorderedAccessView");
+80 -40
View File
@@ -1,11 +1,9 @@
#include "keyboard_gamepad.h"
#include <array>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <atomic>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <new>
@@ -191,42 +189,81 @@ void sample_stick(int left, int right, int down, int up, float& x, float& y) {
}
}
/* LOCAL DIAGNOSTIC (not for review): BX_INPUT_SCRIPT="A@40,A@46,DOWN@50" presses a button for
300 ms at the given second after the first reading, regardless of window focus. Buttons: A B X Y
UP DOWN LEFT RIGHT MENU VIEW. Each press is logged. */
uint32_t scripted_buttons() {
struct Press { uint32_t button; uint64_t at_ms; };
static std::vector<Press> presses = [] {
std::vector<Press> out;
char spec[512] = {};
if (!GetEnvironmentVariableA("BX_INPUT_SCRIPT", spec, sizeof(spec))) return out;
const struct { const char* name; uint32_t bit; } names[] = {
{"MENU", 0x1}, {"VIEW", 0x2}, {"A", 0x4}, {"B", 0x8}, {"X", 0x10}, {"Y", 0x20},
{"UP", 0x40}, {"DOWN", 0x80}, {"LEFT", 0x100}, {"RIGHT", 0x200}};
for (char* item = std::strtok(spec, ","); item; item = std::strtok(nullptr, ",")) {
char* at = std::strchr(item, '@');
if (!at) continue;
*at = 0;
for (const auto& n : names) {
if (std::strcmp(n.name, item) == 0) out.push_back({n.bit, static_cast<uint64_t>(std::atof(at + 1) * 1000)});
}
/* Diagnostic (off unless BX_INPUT_SCRIPT is set): scripted gamepad presses, so an unattended run
can get past screens that wait for input without window focus. The script is a comma-separated
list of BUTTON@SECONDS, for example "A@40,DOWN@50.5,A@52"; each press holds the button for
300 ms, timed from the first reading of the keyboard gamepad. Buttons: MENU VIEW A B X Y UP DOWN
LEFT RIGHT. Each press is logged once (input_script); an entry it cannot read is logged and
skipped. */
struct ScriptedPress {
uint32_t button;
uint64_t at_ms;
};
constexpr size_t kMaxScriptedPresses = 128;
constexpr uint64_t kScriptedHoldMs = 300;
struct InputScript {
ScriptedPress presses[kMaxScriptedPresses];
std::atomic<bool> logged[kMaxScriptedPresses];
size_t count = 0;
uint64_t start_ms = 0;
};
uint32_t script_button(const char* name, size_t length) {
constexpr struct { const char* name; uint32_t bit; } names[] = {
{"MENU", 0x1}, {"VIEW", 0x2}, {"A", 0x4}, {"B", 0x8}, {"X", 0x10},
{"Y", 0x20}, {"UP", 0x40}, {"DOWN", 0x80}, {"LEFT", 0x100}, {"RIGHT", 0x200},
};
for (const auto& n : names) {
if (std::strlen(n.name) == length && std::strncmp(n.name, name, length) == 0) return n.bit;
}
return 0;
}
InputScript* load_script() {
char spec[2048] = {};
const DWORD n = GetEnvironmentVariableA("BX_INPUT_SCRIPT", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return nullptr;
auto* script = new (std::nothrow) InputScript();
if (!script) return nullptr;
for (const char* item = spec; *item && script->count < kMaxScriptedPresses;) {
const char* end = std::strchr(item, ',');
const size_t length = end ? static_cast<size_t>(end - item) : std::strlen(item);
const char* at = static_cast<const char*>(std::memchr(item, '@', length));
char seconds[32] = {};
uint32_t button = 0;
if (at && static_cast<size_t>(item + length - at - 1) < sizeof(seconds)) {
std::memcpy(seconds, at + 1, static_cast<size_t>(item + length - at - 1));
button = script_button(item, static_cast<size_t>(at - item));
}
return out;
}();
if (presses.empty()) return 0;
static const uint64_t start = GetTickCount64();
static std::vector<bool> logged(presses.size(), false);
const uint64_t now = GetTickCount64() - start;
char* parsed_end = nullptr;
const double when = std::strtod(seconds, &parsed_end);
if (button && parsed_end != seconds && *parsed_end == 0 && when >= 0) {
script->presses[script->count++] = {button, static_cast<uint64_t>(when * 1000.0)};
} else {
char detail[96];
std::snprintf(detail, sizeof(detail), "unreadable entry '%.*s' skipped", static_cast<int>(length < 40 ? length : 40), item);
bx_log_emit(BX_LOG_WARN, "gameinput", "input_script", detail);
}
item = end ? end + 1 : item + length;
}
script->start_ms = GetTickCount64();
return script;
}
uint32_t scripted_buttons() {
static InputScript* const script = load_script();
if (!script) return 0;
const uint64_t now = GetTickCount64() - script->start_ms;
uint32_t buttons = 0;
for (size_t i = 0; i < presses.size(); ++i) {
if (now >= presses[i].at_ms && now < presses[i].at_ms + 300) {
buttons |= presses[i].button;
if (!logged[i]) {
logged[i] = true;
char detail[80];
std::snprintf(detail, sizeof(detail), "scripted press 0x%x at %.1f s", presses[i].button, now / 1000.0);
bx_log_emit(BX_LOG_INFO, "gameinput", "input_script", detail);
}
for (size_t i = 0; i < script->count; ++i) {
const ScriptedPress& press = script->presses[i];
if (now < press.at_ms || now >= press.at_ms + kScriptedHoldMs) continue;
buttons |= press.button;
if (!script->logged[i].exchange(true)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "scripted press 0x%x at %.1f s", press.button, now / 1000.0);
bx_log_emit(BX_LOG_INFO, "gameinput", "input_script", detail);
}
}
return buttons;
@@ -234,8 +271,11 @@ uint32_t scripted_buttons() {
GamepadState sample_keyboard() {
GamepadState state{};
state.buttons = scripted_buttons();
if (!owns_foreground()) return state;
const uint32_t scripted = scripted_buttons();
if (!owns_foreground()) {
state.buttons = scripted;
return state;
}
constexpr struct KeyBinding { int key; uint32_t button; } buttons[] = {
{'P', 0x1}, {VK_TAB, 0x2}, {VK_RETURN, 0x4}, {VK_SPACE, 0x4},
@@ -251,7 +291,7 @@ GamepadState sample_keyboard() {
sample_stick('A', 'D', 'S', 'W', state.left_x, state.left_y);
sample_stick('J', 'L', 'K', 'I', state.right_x, state.right_y);
if (!owns_foreground()) state = GamepadState{};
state.buttons |= scripted_buttons();
state.buttons |= scripted;
return state;
}
+51 -34
View File
@@ -1,4 +1,3 @@
#include <mutex>
#include <windows.h>
#include <tlhelp32.h>
#include <atomic>
@@ -1331,6 +1330,56 @@ void disarm_diagnostics() {
}
}
/* Diagnostic (off unless BX_CONTINUE_ASSERTS=1): a title's continuable assert is an int3 in its
own executable followed by code that carries on when no debugger is attached to take it. With
the switch, such an int3 in the main executable is stepped over instead of reaching the title's
crash reporter. Each address is logged once (assert_continued), so the run report still lists
every assert that fired. An int3 anywhere else (BetterXen, system or other modules) is left as
it was. */
static bool continue_assert(PEXCEPTION_POINTERS ep) {
// Reading the switch and querying memory must not change the faulting thread's last-error
// value, which the title may read after it continues (test_veh_breakpoint checks it).
struct KeepLastError {
DWORD saved = GetLastError();
~KeepLastError() { SetLastError(saved); }
} keep_last_error;
static const bool enabled = [] {
char v[4] = {};
const DWORD n = GetEnvironmentVariableA("BX_CONTINUE_ASSERTS", v, sizeof(v));
return n == 1 && v[0] == '1';
}();
if (!enabled) return false;
const auto at = reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress);
const auto exe = reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(at), &region, sizeof(region)) ||
reinterpret_cast<uintptr_t>(region.AllocationBase) != exe || *reinterpret_cast<const uint8_t*>(at) != 0xCC) {
return false;
}
static std::atomic<uintptr_t> seen[256];
bool first = true;
for (auto& slot : seen) {
uintptr_t value = slot.load();
if (value == at) {
first = false;
break;
}
if (value == 0 && slot.compare_exchange_strong(value, at)) break;
if (value == at) {
first = false;
break;
}
}
if (first) {
char detail[96];
std::snprintf(detail, sizeof(detail), "title assert at rva 0x%llx stepped over",
static_cast<unsigned long long>(at - exe));
bx_log_emit(BX_LOG_WARN, "runtime_veh", "assert_continued", detail);
}
ep->ContextRecord->Rip = at + 1;
return true;
}
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
if (!ep || !ep->ExceptionRecord || !ep->ContextRecord) {
return EXCEPTION_CONTINUE_SEARCH;
@@ -1341,39 +1390,7 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
const DWORD code = ep->ExceptionRecord->ExceptionCode;
if (code == EXCEPTION_BREAKPOINT || code == kStatusAssertionFailure) {
log_breakpoint(*ep->ExceptionRecord);
// LOCAL DIAGNOSTIC (BX_CONTINUE_ASSERTS=1): a title's continuable assert is an int3 followed
// by code that carries on. Step over the int3 in the main executable instead of letting
// the crash reporter end the process. Each address is logged once.
static const bool continue_asserts = [] {
char v[4];
const DWORD n = GetEnvironmentVariableA("BX_CONTINUE_ASSERTS", v, sizeof(v));
return n > 0 && n < sizeof(v) && v[0] == '1';
}();
if (continue_asserts && code == EXCEPTION_BREAKPOINT) {
const auto at = reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress);
const auto exe = reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
MEMORY_BASIC_INFORMATION region{};
if (VirtualQuery(reinterpret_cast<void*>(at), &region, sizeof(region)) &&
reinterpret_cast<uintptr_t>(region.AllocationBase) == exe && *reinterpret_cast<const uint8_t*>(at) == 0xCC) {
static std::mutex seen_lock;
static uintptr_t seen[256];
static size_t seen_count = 0;
bool first = true;
{
std::lock_guard<std::mutex> guard(seen_lock);
for (size_t i = 0; i < seen_count; ++i) first = first && seen[i] != at;
if (first && seen_count < 256) seen[seen_count++] = at;
}
if (first) {
char detail[96];
std::snprintf(detail, sizeof(detail), "title assert at rva 0x%llx stepped over",
static_cast<unsigned long long>(at - exe));
bx_log_emit(BX_LOG_WARN, "runtime_veh", "assert_continued", detail);
}
ep->ContextRecord->Rip = at + 1;
return EXCEPTION_CONTINUE_EXECUTION;
}
}
if (code == EXCEPTION_BREAKPOINT && continue_assert(ep)) return EXCEPTION_CONTINUE_EXECUTION;
return EXCEPTION_CONTINUE_SEARCH;
}
if (code == EXCEPTION_ACCESS_VIOLATION) {
+9 -8
View File
@@ -55,14 +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`
// Xbox DestinationIsPhysicalPages: the result goes to these physical pages (the title's own
// page array, read when the request executes), starting `destination_page_offset` bytes
// into the first; `destination` then only marks the request as having a destination.
UINT bcpack_mode = 0; // compression_bcpack: DSTORAGE_BCPACK_MODE (BCn format 1-7)
ULONG_PTR* destination_pages = nullptr;
SIZE_T destination_page_count = 0;
UINT32 destination_page_offset = 0;
DWORD output_size = 0; // compression_zlib/bcpack: bytes the stream decodes to at `destination`
UINT bcpack_mode = 0; // compression_bcpack: DSTORAGE_BCPACK_MODE (BCn format 1-7)
// Xbox physical-page destination: the title's array of 64 KB page numbers and the offset into
// the first page. The title may fill the array after it enqueues the request, so the pages are
// mapped into `page_span` only when the request runs, and unmapped once it has been fulfilled.
const ULONG_PTR* page_array = nullptr;
UINT32 page_offset = 0;
void* page_span = nullptr;
ULONG_PTR page_span_count = 0;
};
inline constexpr UINT compression_none = 0;
+133 -115
View File
@@ -456,64 +456,37 @@ 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)) {
RemapGuard remap_guard;
BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
request.output_size);
size_t produced = 0;
if (r == BxInflateResult::output_mismatch) {
/* Measure what the stream really holds. A stream longer than the destination is cut to
the destination size (the title asked for the first part of a larger block); a
shorter one stays an error. BX_ZLIB_STRICT=1 keeps every mismatch an error. */
const size_t capacity = static_cast<size_t>(request.output_size) * 16 + 0x40000;
auto* whole = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, capacity));
if (whole) {
const BxInflateResult full = bx_zlib_inflate_any(compressed, request.size, whole, capacity, &produced);
char strict[4] = {};
const bool cut = full == BxInflateResult::ok && produced > request.output_size &&
!(GetEnvironmentVariableA("BX_ZLIB_STRICT", strict, sizeof(strict)) && strict[0] == '1');
if (cut) {
std::memcpy(request.destination, whole, request.output_size);
r = BxInflateResult::ok;
}
HeapFree(GetProcessHeap(), 0, whole);
}
static std::atomic<UINT> measured{0};
if (measured.fetch_add(1) < 32) {
char detail[160];
std::snprintf(detail, sizeof(detail), "zlib stream of %lu bytes holds %llu bytes, destination %lu: %s",
request.size, static_cast<unsigned long long>(produced), request.output_size,
r == BxInflateResult::ok ? "first part delivered" : "left failed");
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_zlib_measured", detail);
}
}
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;
}
/* A title may read only the first part of a compressed block: the stream then holds more than
DestinationSize bytes. The whole stream is decoded and checked (Adler-32), and its first
`output_size` bytes are delivered. A stream shorter than the destination stays an error. */
BxInflateResult inflate_first_part(const uint8_t* compressed, const Request& request) {
const size_t capacity = static_cast<size_t>(request.output_size) * 64 + 0x40000;
auto* whole = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, capacity));
if (!whole) return BxInflateResult::output_mismatch;
size_t produced = 0;
BxInflateResult r = bx_zlib_inflate_any(compressed, request.size, whole, capacity, &produced);
if (r == BxInflateResult::ok && produced > request.output_size) {
std::memcpy(request.destination, whole, request.output_size);
} else if (r == BxInflateResult::ok) {
r = BxInflateResult::output_mismatch;
}
HeapFree(GetProcessHeap(), 0, compressed);
return hr;
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 holds %llu bytes, destination %lu: %s", request.size,
static_cast<unsigned long long>(produced), request.output_size,
r == BxInflateResult::ok ? "first part delivered" : bx_inflate_result_name(r));
bx_log_emit(r == BxInflateResult::ok ? BX_LOG_INFO : BX_LOG_WARN, "xcrdapi", "dstorage_zlib_partial", detail);
}
HeapFree(GetProcessHeap(), 0, whole);
return r;
}
CopyResult fulfill_request(HANDLE file, const Request& request);
/* BCPack (Xbox texture block compression, DSTORAGE_BCPACK_MODE). The codec is Microsoft's
BCPack.dll from the GDK's PC tools, loaded from BX_BCPACK_DLL when set (each collaborator's own
GDK; never shipped). Its documented entry point: BCPackDecompress(bcIndex, output, outputSize,
packed, packedSize). Without it, the request fails with E_NOTIMPL as before. */
using BcpackDecompressFn = HRESULT (__cdecl*)(size_t, void*, size_t, const void*, size_t);
GDK; never shipped). Its documented entry point (GDK BCPack.h): BCPackDecompress(bcIndex,
output, outputSize, packed, packedSize). Without it, BCPack requests stay refused (E_NOTIMPL). */
using BcpackDecompressFn = HRESULT(__cdecl*)(size_t, void*, size_t, const void*, size_t);
BcpackDecompressFn bcpack_decompress() {
static const BcpackDecompressFn fn = [] {
wchar_t path[MAX_PATH];
@@ -556,6 +529,33 @@ HRESULT bcpack_request(HANDLE file, const Request& request) {
return hr;
}
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)) {
RemapGuard remap_guard;
BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
request.output_size);
if (r == BxInflateResult::output_mismatch) r = inflate_first_part(compressed, request);
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() {
@@ -567,49 +567,13 @@ bool dstorage_trace_enabled() {
return on;
}
/* Physical-page destinations: the request is fulfilled into a temporary buffer, which xmem then
writes into the pages (bx_xmem_write_physical_pages). */
CopyResult fulfill_to_pages(HANDLE file, const Request& request) {
using WritePages = BOOL (*)(const ULONG_PTR*, SIZE_T, SIZE_T, const void*, SIZE_T);
static const WritePages write_pages = [] {
const HMODULE xmem = GetModuleHandleW(L"xmem.dll");
return xmem ? reinterpret_cast<WritePages>(reinterpret_cast<void*>(GetProcAddress(xmem, "bx_xmem_write_physical_pages")))
: nullptr;
}();
const DWORD out = (request.compression == compression_zlib || request.compression == compression_bcpack) ? request.output_size
: request.size;
CopyResult result{E_NOTIMPL, false};
void* staging = write_pages && out ? HeapAlloc(GetProcessHeap(), 0, out) : nullptr;
if (staging) {
Request staged = request;
staged.destination = staging;
staged.destination_pages = nullptr;
result = fulfill_request(file, staged);
if (SUCCEEDED(result.hr) &&
!write_pages(request.destination_pages, request.destination_page_count, request.destination_page_offset, staging, out)) {
result.hr = HRESULT_FROM_WIN32(GetLastError());
}
HeapFree(GetProcessHeap(), 0, staging);
} else if (write_pages) {
result.hr = E_OUTOFMEMORY;
}
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 8 || FAILED(result.hr)) {
char detail[160];
std::snprintf(detail, sizeof(detail), "request to %zu physical page(s) at offset %u, %lu bytes: hr=0x%08lx",
request.destination_page_count, request.destination_page_offset, out, static_cast<unsigned long>(result.hr));
bx_log_emit(FAILED(result.hr) ? BX_LOG_WARN : BX_LOG_INFO, "xcrdapi", "dstorage_physical_pages", detail);
}
return result;
}
CopyResult fulfill(HANDLE file, const Request& request) {
if (request.destination_pages) return fulfill_to_pages(file, 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;
const DWORD out = (request.compression == compression_zlib || request.compression == compression_bcpack) ? request.output_size
: request.size;
uint64_t head[2] = {0, 0};
if (SUCCEEDED(result.hr) && request.destination && out >= 16) {
RemapGuard remap_guard;
@@ -668,6 +632,56 @@ CopyResult fulfill_request(HANDLE file, const Request& request) {
// 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.
// Xbox physical-page destinations (DSTORAGE_REQUEST.DestinationPageArray, authorized GDK header):
// 64 KB page numbers from XMemAllocatePhysicalPages. The request writes through a span of its own:
// xmem.dll's XMemMapPhysicalPages with a NULL address (a BetterXen extension, see
// shims/xmem/physical_pages.cpp) maps the pages contiguously, and the same call with a NULL page
// array unmaps the span. The pages are sections, so the title's own views see the bytes.
using MapPhysicalPagesFn = PVOID(WINAPI*)(PVOID, ULONG_PTR, PULONG_PTR);
MapPhysicalPagesFn map_physical_pages() {
static const MapPhysicalPagesFn fn = [] {
HMODULE xmem = GetModuleHandleW(L"xmem.dll");
if (!xmem) xmem = LoadLibraryW(L"xmem.dll");
return xmem ? reinterpret_cast<MapPhysicalPagesFn>(
reinterpret_cast<void*>(GetProcAddress(xmem, "XMemMapPhysicalPages")))
: nullptr;
}();
return fn;
}
/* Maps a physical-page destination's pages when the request runs. The title can fill its page
array after EnqueueRequest returns, so the array is read here, not at enqueue. */
HRESULT map_page_destination(Request& request) {
if (!request.page_array) return S_OK;
const MapPhysicalPagesFn map = map_physical_pages();
void* span = map ? map(nullptr, request.page_span_count, const_cast<PULONG_PTR>(request.page_array)) : nullptr;
if (!span) {
const DWORD error = map ? GetLastError() : ERROR_PROC_NOT_FOUND;
char detail[128];
std::snprintf(detail, sizeof(detail), "mapping %llu destination pages failed error=%lu",
static_cast<unsigned long long>(request.page_span_count), error);
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_page_destination", detail);
return HRESULT_FROM_WIN32(error);
}
request.page_span = span;
request.destination = static_cast<BYTE*>(span) + request.page_offset;
return S_OK;
}
void unmap_page_span(Request& request) {
if (!request.page_span) return;
const MapPhysicalPagesFn map = map_physical_pages();
if (!map || !map(request.page_span, request.page_span_count, nullptr)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "unmapping %llu destination pages failed error=%lu",
static_cast<unsigned long long>(request.page_span_count), GetLastError());
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_page_destination", detail);
}
request.page_span = nullptr;
request.page_span_count = 0;
}
class WorkQueue final : public Object<Queue, queue_iid> {
public:
WorkQueue(Entry* entries, UINT capacity, bool blocking = false, UINT auto_submit = 0)
@@ -885,8 +899,10 @@ private:
HRESULT result = S_OK;
switch (entry.kind) {
case Kind::request: {
const CopyResult outcome = fulfill(entry.handle, entry.request);
const HRESULT mapped = map_page_destination(entry.request);
const CopyResult outcome = SUCCEEDED(mapped) ? fulfill(entry.handle, entry.request) : CopyResult{mapped, false};
result = outcome.hr;
unmap_page_span(entry.request);
if (entry.handle) CloseHandle(entry.handle);
// keep_destination holds the AddRef taken at enqueue. Releasing
// it while the staged copy is still on the GPU frees the dest.
@@ -1520,8 +1536,10 @@ static_assert(offsetof(XboxQueueDesc, flags) == 0x18, "flags offset");
struct XboxRequest {
UINT64 options; // +0x00: bit 22 (0x400000) = memory source, bit 0 = compressed
void* destination; // +0x08
UINT64 destination_pad; // +0x10
void* destination; // +0x08: buffer, or the 64 KB page-number array (DestinationIsPhysicalPages)
UINT16 destination_page_offset; // +0x10: offset into the first page (DestinationIsPhysicalPages)
UINT16 reserved12;
UINT32 reserved14;
UINT32 destination_size; // +0x18
UINT32 reserved1c; // +0x1c
void* source_ptr; // +0x20: IXboxDStorageFile* (file) or const void* (memory)
@@ -1532,6 +1550,7 @@ struct XboxRequest {
static_assert(sizeof(XboxRequest) == 56, "XboxRequest must be 56 bytes");
static_assert(offsetof(XboxRequest, options) == 0x00, "options offset");
static_assert(offsetof(XboxRequest, destination) == 0x08, "destination offset");
static_assert(offsetof(XboxRequest, destination_page_offset) == 0x10, "destination_page_offset offset");
static_assert(offsetof(XboxRequest, destination_size) == 0x18, "destination_size offset");
static_assert(offsetof(XboxRequest, source_ptr) == 0x20, "source_ptr offset");
static_assert(offsetof(XboxRequest, file_offset) == 0x28, "file_offset offset");
@@ -1679,8 +1698,10 @@ public:
return;
}
log_request_options(request->options, request->source_size, request->destination_size, request->reserved34);
// BCPack (BcpackMode, DSTORAGE_BCPACK_MODE 1-7) is decoded by the GDK's BCPack.dll when
// BX_BCPACK_DLL names it; combined with zlib, or without the codec, it stays refused.
const UINT bcpack_mode = static_cast<UINT>((request->options & kXboxRequestBcpackMask) >> 1);
if (bcpack_mode && ((request->options & kXboxRequestCompressedBit) || !bcpack_decompress() || bcpack_mode > 7)) {
if (bcpack_mode && ((request->options & kXboxRequestCompressedBit) || bcpack_mode > 7 || !bcpack_decompress())) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_bcpack");
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
@@ -1691,26 +1712,11 @@ public:
return;
}
if (request->options & kXboxRequestSourcePagesBit) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_source_physical_pages");
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_physical_page_source");
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
}
// DestinationIsPhysicalPages (GDK dstorage_xs.h): +0x08 DestinationPageArray (64 KiB pages),
// +0x10 DestinationPageOffset (UINT16).
ULONG_PTR* pages = nullptr;
SIZE_T page_count = 0;
UINT32 page_offset = 0;
if (request->options & kXboxRequestDestinationPagesBit) {
page_offset = static_cast<UINT32>(request->destination_pad & 0xFFFF);
page_count = (page_offset + static_cast<SIZE_T>(request->destination_size) + 0xFFFF) / 0x10000;
// The array is read when the request executes, as the console does: a title may fill
// in its page table after enqueueing (observed: entries still 0 at enqueue time).
pages = static_cast<ULONG_PTR*>(request->destination);
if (!pages || !page_count) {
reject(E_INVALIDARG, Kind::request, "EnqueueRequest");
return;
}
}
const bool to_pages = (request->options & kXboxRequestDestinationPagesBit) != 0;
const bool zlib = (request->options & kXboxRequestCompressedBit) != 0;
if (!request->destination || (zlib ? request->source_size >= request->destination_size
: (!bcpack_mode && request->source_size != request->destination_size))) {
@@ -1721,9 +1727,6 @@ public:
Request translated{};
translated.destination = request->destination;
translated.size = request->source_size;
translated.destination_pages = pages;
translated.destination_page_count = page_count;
translated.destination_page_offset = page_offset;
if (zlib) {
translated.compression = compression_zlib;
translated.output_size = request->destination_size;
@@ -1747,6 +1750,21 @@ public:
translated.file = file->inner();
translated.file_offset = request->file_offset;
}
if (to_pages) {
// DestinationSize bytes from DestinationPageOffset in the first page, across as many
// 64 KB pages of the array as that covers.
constexpr UINT64 page = 64 * 1024;
const UINT64 end = static_cast<UINT64>(request->destination_page_offset) + request->destination_size;
const ULONG_PTR count = static_cast<ULONG_PTR>((end + page - 1) / page);
if (!map_physical_pages()) {
reject(HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND), Kind::request, "EnqueueRequest");
return;
}
// The array stays the title's: it is read when the request runs (map_page_destination).
translated.page_array = static_cast<const ULONG_PTR*>(request->destination);
translated.page_offset = request->destination_page_offset;
translated.page_span_count = count;
}
accept(queue_->EnqueueRequest(&translated), Kind::request, "EnqueueRequest");
}
+2 -1
View File
@@ -25,7 +25,8 @@ enum class BxInflateResult {
/* 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);
/* Decodes `input` into at most `capacity` bytes and reports how many the stream produced. */
/* Decodes `input` into at most `capacity` bytes and reports how many the stream produced
(checksum verified over those bytes). */
BxInflateResult bx_zlib_inflate_any(const uint8_t* input, size_t input_size, uint8_t* output, size_t capacity, size_t* produced);
const char* bx_inflate_result_name(BxInflateResult result);
-57
View File
@@ -1,4 +1,3 @@
#include <cstring>
#include <windows.h>
#include <cstdint>
@@ -853,62 +852,6 @@ static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_arra
return TRUE;
}
/* Writes `size` bytes of `data` into physical pages, starting `offset` bytes into the first page
(DirectStorage DestinationIsPhysicalPages). `pages` holds the page numbers
XMemAllocatePhysicalPages returned (4 KiB frame numbers, a multiple of 16 per 64 KiB page); a
64 KiB page index (the number divided by 16) is accepted as well. Each page is written through
a short-lived view of its block's section, so the memory is the same wherever the page is
mapped. Returns FALSE (SetLastError) when a page is unknown or a view cannot be made. */
extern "C" BOOL bx_xmem_write_physical_pages(const ULONG_PTR* pages, SIZE_T count, SIZE_T offset, const void* data,
SIZE_T size) {
if (!pages || !data || offset >= small_page || offset + size > count * small_page) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
Lock lock;
const auto* in = static_cast<const BYTE*>(data);
SIZE_T done = 0;
for (SIZE_T i = 0; done < size; ++i) {
Page* page = find_page(pages[i]);
if (!page) page = find_page(pages[i] * kFramesPerPage);
if (!page) {
static LONG logged = 0;
if (InterlockedIncrement(&logged) <= 12) { // LOCAL DIAGNOSTIC
char detail[200];
ULONG_PTR lo = 0, hi = 0;
for (PageBlock* b = blocks; b; b = b->next) {
if (!lo || b->first_tag < lo) lo = b->first_tag;
const ULONG_PTR end = b->first_tag + b->count * kFramesPerPage;
if (end > hi) hi = end;
}
bool freed = false;
for (PageBlock* b = blocks; b; b = b->next) {
if (pages[i] >= b->first_tag && pages[i] < b->first_tag + b->count * kFramesPerPage &&
(pages[i] - b->first_tag) % kFramesPerPage == 0) {
freed = !b->entries[(pages[i] - b->first_tag) / kFramesPerPage].allocated;
}
}
std::snprintf(detail, sizeof(detail), "unknown page number 0x%llx (entry %llu of %llu; known tags 0x%llx..0x%llx; %s)",
(unsigned long long)pages[i], (unsigned long long)i, (unsigned long long)count,
(unsigned long long)lo, (unsigned long long)hi, freed ? "in a block but freed" : "not in any block");
bx_log_emit(BX_LOG_WARN, "xmem", "write_physical_pages", detail);
}
SetLastError(ERROR_INVALID_ADDRESS);
return FALSE;
}
const SIZE_T start = i == 0 ? offset : 0;
const SIZE_T chunk = (small_page - start) < (size - done) ? (small_page - start) : (size - done);
const ULONG64 at = page_offset(page);
void* view = MapViewOfFile(page->block->section, FILE_MAP_WRITE, static_cast<DWORD>(at >> 32),
static_cast<DWORD>(at), small_page);
if (!view) return FALSE;
std::memcpy(static_cast<BYTE*>(view) + start, in + done, chunk);
UnmapViewOfFile(view);
done += chunk;
}
return TRUE;
}
extern "C" void bx_xmem_remap_guard_enter(void) {
AcquireSRWLockShared(&remap_lock);
}
@@ -1,7 +1,7 @@
/*
* CreateCommittedResourceX (Xbox device table slot 76): CreateCommittedResource with a
* D3D12XBOX_RESOURCE_DESC, which is the PC D3D12_RESOURCE_DESC followed by a 32-bit DccOptions
* (authorized GDK header). The resource must be created with the PC part of the description,
* D3D12XBOX_RESOURCE_DESC, which is the PC D3D12_RESOURCE_DESC followed by DccOptions, a struct of
* two 32-bit enums, CompressionLevel and ColorTransform (authorized GDK header). The resource must be created with the PC part of the description,
* whatever DccOptions says, and its memory requested through XMemAlloc like any committed
* resource (AllocatorId D3D 128, ObjectType Resource 4), so a title hooking XMemAlloc sees it.
*/
@@ -21,11 +21,16 @@ extern "C" __declspec(dllimport) VOID WINAPI XMemFreeDefault(PVOID, ULONGLONG);
namespace {
// D3D12XBOX_RESOURCE_DESC, written out from the GDK header's field list.
struct DccOptions {
UINT32 CompressionLevel; // D3D12XBOX_DCC_COMPRESSION_LEVEL: 64B 0, 128B 1, 256B 2, DEFAULT 3
UINT32 ColorTransform; // D3D12XBOX_DCC_COLOR_TRANSFORM: 0..3
};
struct XboxResourceDesc {
D3D12_RESOURCE_DESC pc;
UINT32 DccOptions;
DccOptions Dcc;
};
static_assert(offsetof(XboxResourceDesc, DccOptions) == 56, "DccOptions follows the 56-byte PC description");
static_assert(offsetof(XboxResourceDesc, Dcc) == 56, "DccOptions follows the 56-byte PC description");
static_assert(sizeof(XboxResourceDesc) == 64, "DccOptions is two 32-bit enums");
constexpr ULONGLONG kD3DResource = (128ull << 16) | 4;
int g_d3d_requests = 0;
@@ -110,7 +115,7 @@ int main() {
target.pc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
target.pc.SampleDesc.Count = 1;
target.pc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
target.DccOptions = 0x1; // any compression request: the host has none
target.Dcc = {2, 3}; // 256B with a correlated colour transform: the host has no compression
create_and_check(dev, target, "render target with DccOptions");
XboxResourceDesc buffer{};
@@ -0,0 +1,13 @@
# A stand-in for the GDK's XG library with known answers, built as xg_xs.dll in its own folder so
# it never replaces the xg_xs shim beside the other DLLs. The test loads it by full path.
add_library(test_gdk_xg_fake SHARED fake_xg.cpp)
# Its import library goes to its own folder too, or it would replace the xg_xs shim's.
set_target_properties(test_gdk_xg_fake PROPERTIES OUTPUT_NAME xg_xs PREFIX ""
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/gdk_xg_fake"
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/gdk_xg_fake_lib")
target_link_libraries(test_gdk_xg_fake PRIVATE kernel32)
add_executable(test_d3d12_gdk_xg_sizes main.cpp)
target_compile_definitions(test_d3d12_gdk_xg_sizes PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_gdk_xg_sizes PRIVATE d3d12_xs kernel32 uuid)
add_dependencies(test_d3d12_gdk_xg_sizes test_gdk_xg_fake)
@@ -0,0 +1,66 @@
/*
* A stand-in for the GDK's XG library (xg_xs.dll) with answers the test can compute. It has the
* documented shape the shim relies on (GDK xg_xs.h): the exports XGComputeTexture2DLayout (whose
* presence marks Microsoft's library), XGCreateTextureComputer and XGEnableExclusiveLocking, and a
* texture computer whose vtable starts AddRef, Release, GetResourceLayout, GetResourceSizeBytes,
* GetResourceBaseAlignmentBytes. It is not Microsoft's code and computes no real layout.
*
* Its answer for a texture: size = Width * Height * DepthOrArraySize * 16 + (Layout & 0xFF) * 0x1000,
* alignment = 0x10000 when the layout is 0x109 (a 64 KB mode), otherwise 0x1000.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
namespace {
struct Computer;
struct Vtbl {
ULONG(__cdecl* AddRef)(Computer*);
ULONG(__cdecl* Release)(Computer*);
HRESULT(__cdecl* GetResourceLayout)(Computer*, void*);
UINT64 (*GetResourceSizeBytes)(Computer*);
UINT64 (*GetResourceBaseAlignmentBytes)(Computer*);
};
struct Computer {
const Vtbl* vtbl;
LONG refs;
UINT64 size;
UINT64 alignment;
};
ULONG __cdecl add_ref(Computer* c) { return static_cast<ULONG>(InterlockedIncrement(&c->refs)); }
ULONG __cdecl release(Computer* c) {
const LONG left = InterlockedDecrement(&c->refs);
if (!left) HeapFree(GetProcessHeap(), 0, c);
return static_cast<ULONG>(left);
}
HRESULT __cdecl layout(Computer*, void*) { return E_NOTIMPL; }
UINT64 size_bytes(Computer* c) { return c->size; }
UINT64 alignment_bytes(Computer* c) { return c->alignment; }
const Vtbl kVtbl = {add_ref, release, layout, size_bytes, alignment_bytes};
LONG g_locking = 0;
} // namespace
extern "C" __declspec(dllexport) HRESULT __cdecl XGComputeTexture2DLayout(const void*, void*) { return E_NOTIMPL; }
extern "C" __declspec(dllexport) HRESULT __cdecl XGCreateTextureComputer(const D3D12_RESOURCE_DESC* desc, Computer** out) {
if (!desc || !out) return E_INVALIDARG;
auto* c = static_cast<Computer*>(HeapAlloc(GetProcessHeap(), 0, sizeof(Computer)));
if (!c) return E_OUTOFMEMORY;
const UINT layout_value = static_cast<UINT>(desc->Layout);
c->vtbl = &kVtbl;
c->refs = 1;
c->size = desc->Width * desc->Height * desc->DepthOrArraySize * 16ull + (layout_value & 0xFF) * 0x1000ull;
c->alignment = layout_value == 0x109 ? 0x10000 : 0x1000;
*out = c;
return S_OK;
}
extern "C" __declspec(dllexport) void __cdecl XGEnableExclusiveLocking(BOOL enabled) { g_locking = enabled ? 1 : 0; }
// For the test: whether the shim enabled XG's locking.
extern "C" __declspec(dllexport) LONG __cdecl FakeXGLockingEnabled() { return g_locking; }
@@ -0,0 +1,125 @@
/*
* GetResourceAllocationInfo for console texture layouts, answered by the GDK's XG library.
*
* Console textures carry a tiled layout (D3D12XBOX_TEXTURE_LAYOUT, 0x100 | swizzle mode), and a
* title sizes its loads and placements from the allocation size the device reports. When the
* GDK's XG library is the loaded xg_xs.dll, d3d12_xs answers console layouts with XG's size and
* base alignment, and everything else with the host's answer; several descriptions are laid out
* one after another at their alignments (Direct3D 12 rules), the total aligned to the largest.
*
* The library here is a stand-in with answers this test computes (fake_xg.cpp), not Microsoft's.
* The test also checks that the shim enabled XG's exclusive locking at device creation.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2, kDevGetResourceAllocationInfo = 25;
int g_failed = 0;
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using AllocationInfoFn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_RESOURCE_DESC*);
D3D12_RESOURCE_DESC texture(UINT64 w, UINT h, UINT16 slices, DXGI_FORMAT format, UINT layout) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
d.Width = w;
d.Height = h;
d.DepthOrArraySize = slices;
d.MipLevels = 1;
d.Format = format;
d.SampleDesc.Count = 1;
d.Layout = static_cast<D3D12_TEXTURE_LAYOUT>(layout);
return d;
}
// The stand-in library's answer (fake_xg.cpp), written out independently here.
UINT64 fake_size(const D3D12_RESOURCE_DESC& d) {
return d.Width * d.Height * d.DepthOrArraySize * 16ull + (static_cast<UINT>(d.Layout) & 0xFF) * 0x1000ull;
}
UINT64 fake_alignment(const D3D12_RESOURCE_DESC& d) { return static_cast<UINT>(d.Layout) == 0x109 ? 0x10000 : 0x1000; }
void expect(const char* what, UINT64 got, UINT64 want) {
std::printf("%-52s got=0x%llx expected=0x%llx\n", what, static_cast<unsigned long long>(got),
static_cast<unsigned long long>(want));
if (got != want) {
std::fprintf(stderr, "FAIL: test_d3d12_gdk_xg_sizes: %s\n", what);
++g_failed;
}
}
} // namespace
int main() {
// Load the stand-in as xg_xs.dll before the device exists, as bx-cli stages the GDK's.
wchar_t path[MAX_PATH];
const DWORD n = GetModuleFileNameW(nullptr, path, MAX_PATH);
wchar_t* slash = n ? wcsrchr(path, L'\\') : nullptr;
if (!slash || wcslen(path) + 32 >= MAX_PATH) return 1;
wcscpy(slash + 1, L"gdk_xg_fake\\xg_xs.dll");
HMODULE fake = LoadLibraryW(path);
if (!fake) {
std::fprintf(stderr, "FAIL: test_d3d12_gdk_xg_sizes: the stand-in XG library did not load (error %lu)\n", GetLastError());
return 1;
}
using LockingFn = LONG(__cdecl*)();
auto locking = reinterpret_cast<LockingFn>(reinterpret_cast<void*>(GetProcAddress(fake, "FakeXGLockingEnabled")));
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
std::memcpy(title_params, &version, sizeof(version));
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_gdk_xg_sizes: host lacks the Xbox-layout device interface\n");
return 77;
}
if (FAILED(hr) || !dev) {
std::fprintf(stderr, "FAIL: device creation hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
expect("XG exclusive locking enabled at device creation", locking ? static_cast<UINT64>(locking()) : 0, 1);
const auto info = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo);
// One console texture: XG's size and alignment.
const D3D12_RESOURCE_DESC tiled = texture(128, 4, 1, DXGI_FORMAT_R16G16B16A16_UNORM, 0x105);
D3D12_RESOURCE_ALLOCATION_INFO got = info(dev, 0, 1, &tiled);
expect("128x4 RGBA16 layout 0x105: size", got.SizeInBytes, fake_size(tiled));
expect("128x4 RGBA16 layout 0x105: alignment", got.Alignment, fake_alignment(tiled));
const D3D12_RESOURCE_DESC big = texture(256, 256, 6, DXGI_FORMAT_BC7_UNORM, 0x109);
got = info(dev, 0, 1, &big);
expect("256x256x6 BC7 layout 0x109: size", got.SizeInBytes, fake_size(big));
expect("256x256x6 BC7 layout 0x109: alignment", got.Alignment, fake_alignment(big));
// A PC-layout texture keeps the host's answer.
const D3D12_RESOURCE_DESC pc = texture(256, 256, 1, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_TEXTURE_LAYOUT_UNKNOWN);
const D3D12_RESOURCE_ALLOCATION_INFO host = info(dev, 0, 1, &pc);
expect("PC-layout texture: host size is answered", host.SizeInBytes != 0 && host.SizeInBytes != UINT64_MAX, 1);
// Console then PC texture: each at its alignment, in order; total alignment the largest.
const D3D12_RESOURCE_DESC pair[2] = {tiled, pc};
got = info(dev, 0, 2, pair);
const UINT64 second = (fake_size(tiled) + host.Alignment - 1) / host.Alignment * host.Alignment;
expect("console + PC texture: total size", got.SizeInBytes, second + host.SizeInBytes);
expect("console + PC texture: total alignment", got.Alignment,
host.Alignment > fake_alignment(tiled) ? host.Alignment : fake_alignment(tiled));
slot<ReleaseFn>(dev, kRelease)(dev);
if (g_failed) return 1;
std::puts("PASS: test_d3d12_gdk_xg_sizes");
return 0;
}
@@ -0,0 +1,2 @@
add_executable(test_gameinput_script main.cpp)
target_link_libraries(test_gameinput_script PRIVATE kernel32 uuid)
@@ -0,0 +1,92 @@
/*
* BX_INPUT_SCRIPT (GameInput diagnostic): scripted gamepad presses for unattended runs.
*
* The script "A@0.6,DOWN@0.6,B@1.6,BOGUS@1,X" asks for A and DOWN held from 0.6 s to 0.9 s and B
* from 1.6 s to 1.9 s after the first reading; the two unreadable entries are skipped. The test has
* no window, so the keyboard contributes nothing; readings taken at fixed times must carry exactly
* the scripted buttons inside each press and none outside. The times sit at least 0.2 s from every
* press boundary.
*/
#include <windows.h>
#include <unknwn.h>
#include <cstdint>
#include <cstdio>
namespace {
constexpr uint32_t gamepad_kind = 0x00040000;
constexpr uint32_t connected = 1;
struct State {
uint32_t buttons;
float lt, rt, lx, ly, rx, ry;
};
static_assert(sizeof(State) == 28);
template <typename Fn>
Fn slot(IUnknown* object, unsigned index) {
return reinterpret_cast<Fn>((*reinterpret_cast<void***>(object))[index]);
}
using Create = HRESULT(WINAPI*)(void**);
using Current = HRESULT(WINAPI*)(IUnknown*, uint32_t, IUnknown*, IUnknown**);
using DeviceCallback = void(WINAPI*)(uint64_t, void*, IUnknown*, uint64_t, uint32_t, uint32_t);
using Register = HRESULT(WINAPI*)(IUnknown*, IUnknown*, uint32_t, uint32_t, uint32_t, void*, DeviceCallback, uint64_t*);
using StateFn = bool(WINAPI*)(IUnknown*, State*);
void WINAPI note_device(uint64_t, void* context, IUnknown* device, uint64_t, uint32_t, uint32_t) {
*static_cast<IUnknown**>(context) = device;
}
IUnknown* g_input = nullptr;
IUnknown* g_pad = nullptr;
uint64_t g_start = 0;
// Waits until `seconds` after the first reading, then returns the buttons of a fresh reading.
uint32_t buttons_at(double seconds) {
while (GetTickCount64() - g_start < static_cast<uint64_t>(seconds * 1000.0)) Sleep(5);
IUnknown* reading = nullptr;
if (slot<Current>(g_input, 4)(g_input, gamepad_kind, g_pad, &reading) != S_OK || !reading) return 0xFFFFFFFF;
State state{};
const bool ok = slot<StateFn>(reading, 22)(reading, &state);
reading->Release();
return ok ? state.buttons : 0xFFFFFFFF;
}
int g_failed = 0;
void expect(const char* what, uint32_t got, uint32_t want) {
std::printf("%-34s buttons=0x%x expected=0x%x\n", what, got, want);
if (got != want) {
std::fprintf(stderr, "FAIL: test_gameinput_script: %s\n", what);
++g_failed;
}
}
} // namespace
int main() {
SetEnvironmentVariableA("BX_INPUT_SCRIPT", "A@0.6,DOWN@0.6,B@1.6,BOGUS@1,X");
HMODULE module = LoadLibraryW(L"GameInput.dll");
const auto create = module ? reinterpret_cast<Create>(reinterpret_cast<void*>(GetProcAddress(module, MAKEINTRESOURCEA(1)))) : nullptr;
if (!create || create(reinterpret_cast<void**>(&g_input)) != S_OK || !g_input) {
std::fprintf(stderr, "FAIL: test_gameinput_script: GameInput is not available\n");
return 1;
}
uint64_t token = 0;
if (slot<Register>(g_input, 9)(g_input, nullptr, gamepad_kind, connected, 2, &g_pad, note_device, &token) != S_OK || !g_pad) {
std::fprintf(stderr, "FAIL: test_gameinput_script: no gamepad device\n");
return 1;
}
g_start = GetTickCount64();
expect("first reading (0 s)", buttons_at(0.0), 0);
expect("0.3 s: before the first press", buttons_at(0.3), 0);
expect("0.75 s: A and DOWN held", buttons_at(0.75), 0x4 | 0x80);
expect("1.2 s: between presses", buttons_at(1.2), 0);
expect("1.75 s: B held", buttons_at(1.75), 0x8);
expect("2.2 s: after the script", buttons_at(2.2), 0);
if (g_failed) return 1;
std::puts("PASS: test_gameinput_script");
return 0;
}
@@ -0,0 +1,2 @@
add_executable(test_veh_continue_asserts main.cpp)
target_link_libraries(test_veh_continue_asserts PRIVATE bx_runtime_veh kernel32)
@@ -0,0 +1,90 @@
/*
* BX_CONTINUE_ASSERTS=1 (bx_runtime_veh diagnostic): an int3 in the main executable is stepped
* over, as a continuable assert is when no debugger takes it; an int3 anywhere else is not.
*
* The test sets the switch, then executes an int3 in its own code twice (the same address, so the
* second is a repeat) and once in a page outside any module. A vectored handler of its own,
* registered after bx_runtime_veh's, counts every breakpoint that reaches it and steps over it so
* the test can report: the executable's int3s must never reach it, the other one must. Stepping
* over must leave the thread's last-error value as it was.
*/
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" uint64_t bx_veh_get_clwb_trap_count(void);
namespace {
volatile LONG g_exe_reached = 0;
volatile LONG g_other_reached = 0;
uintptr_t g_other_page = 0;
LONG CALLBACK last_handler(PEXCEPTION_POINTERS ep) {
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT) return EXCEPTION_CONTINUE_SEARCH;
const auto at = reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress);
if (g_other_page && at >= g_other_page && at < g_other_page + 4096) {
InterlockedIncrement(&g_other_reached);
} else {
InterlockedIncrement(&g_exe_reached);
}
ep->ContextRecord->Rip = at + 1;
return EXCEPTION_CONTINUE_EXECUTION;
}
__attribute__((noinline)) int assert_site(int value) {
__asm__ volatile("int3" ::: "memory");
return value + 1;
}
} // namespace
int main() {
SetErrorMode(SEM_NOGPFAULTERRORBOX);
// Keep a static import on bx_runtime_veh.dll so its handler is installed at load.
volatile uint64_t attached = bx_veh_get_clwb_trap_count();
(void)attached;
SetEnvironmentVariableA("BX_CONTINUE_ASSERTS", "1");
AddVectoredExceptionHandler(0, last_handler);
SetLastError(0x1234);
int value = assert_site(1);
value = assert_site(value);
const DWORD last_error = GetLastError();
// An int3 outside any module: int3; ret.
auto* page = static_cast<uint8_t*>(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE));
if (!page) return 1;
g_other_page = reinterpret_cast<uintptr_t>(page);
page[0] = 0xCC;
page[1] = 0xC3;
FlushInstructionCache(GetCurrentProcess(), page, 2);
reinterpret_cast<void (*)()>(page)();
int failed = 0;
if (value != 3) {
std::fprintf(stderr, "FAIL: test_veh_continue_asserts: execution after the int3 did not continue (value %d)\n", value);
++failed;
}
if (last_error != 0x1234) {
std::fprintf(stderr, "FAIL: test_veh_continue_asserts: a stepped-over int3 changed the last-error value (0x%lx)\n",
static_cast<unsigned long>(last_error));
++failed;
}
if (g_exe_reached != 0) {
std::fprintf(stderr, "FAIL: test_veh_continue_asserts: %ld int3s in the executable were not stepped over\n",
static_cast<long>(g_exe_reached));
++failed;
}
if (g_other_reached != 1) {
std::fprintf(stderr, "FAIL: test_veh_continue_asserts: an int3 outside the executable must be left alone (reached %ld)\n",
static_cast<long>(g_other_reached));
++failed;
}
VirtualFree(page, 0, MEM_RELEASE);
if (failed) return 1;
std::puts("PASS: test_veh_continue_asserts");
return 0;
}
@@ -0,0 +1,6 @@
# Synthetic conformance test: Xbox DirectStorage requests whose destination is an array of
# xmem.dll physical pages (DestinationIsPhysicalPages).
add_executable(test_xcrdapi_page_destination main.cpp)
target_compile_definitions(test_xcrdapi_page_destination PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_include_directories(test_xcrdapi_page_destination PRIVATE "${BX_ABI_INCLUDE_DIR}" "${BX_ROOT_DIR}/shims/xcrdapi/dstorage")
target_link_libraries(test_xcrdapi_page_destination PRIVATE xcrdapi xmem bx_runtime_veh kernel32)
@@ -0,0 +1,450 @@
/*
* Synthetic conformance test: Xbox DirectStorage requests whose destination is an array of
* physical pages (DSTORAGE_REQUEST_OPTIONS.DestinationIsPhysicalPages).
*
* Contract, from the authorized GDK header and documentation of DSTORAGE_REQUEST:
* - DestinationIsPhysicalPages is bit 21 of the options (after ZlibDecompress:1, BcpackMode:4,
* SwizzleMode:16); SourceType is bit 22 and SourceIsPhysicalPages bit 23.
* - With it, the destination union holds DestinationPageArray (an array of 64 KB page numbers
* from XMemAllocatePhysicalPages) at +0x08 and DestinationPageOffset (UINT16, the offset into
* the first page where the destination starts) at +0x10.
* - DestinationSize bytes are written from that offset, page after page in array order.
* The 56-byte request layout is the one test_xcrdapi_xbox already uses.
*
* The expected bytes are built here from a formula; the zlib stream was produced from the same
* formula by CPython's zlib module (level 9), not by the code under test.
*/
#include <windows.h>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include "dstorage.h"
extern "C" {
__declspec(dllimport) HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv);
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, uint64_t, DWORD);
BOOL WINAPI XMemAllocatePhysicalPages(uint64_t, PULONG_PTR, PULONG_PTR);
BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR, PULONG_PTR);
PVOID WINAPI XMemMapPhysicalPages(PVOID, ULONG_PTR, PULONG_PTR);
}
struct XboxQueueDesc {
UINT64 source_type;
UINT16 capacity;
INT8 priority;
UINT8 reserved_pad[5];
PCSTR name;
UINT64 flags;
};
struct XboxRequest {
UINT64 options;
void* destination; // DestinationPageArray when bit 21 is set
UINT16 destination_page_offset; // DestinationPageOffset
UINT16 reserved12;
UINT32 reserved14;
UINT32 destination_size;
UINT32 reserved1c;
void* source_ptr;
UINT64 file_offset;
UINT32 source_size;
UINT32 reserved34;
};
static_assert(sizeof(XboxRequest) == 56, "DSTORAGE_REQUEST is 56 bytes");
static_assert(offsetof(XboxRequest, destination_page_offset) == 0x10, "DestinationPageOffset at +0x10");
static_assert(offsetof(XboxRequest, destination_size) == 0x18, "DestinationSize at +0x18");
struct IXboxDStorageFile : IUnknown {
virtual void STDMETHODCALLTYPE Close() = 0;
virtual HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) = 0;
};
struct IXboxDStorageStatusArray : IUnknown {
virtual bool STDMETHODCALLTYPE IsComplete(UINT32 index) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) = 0;
};
struct IXboxDStorageQueue : IUnknown {
virtual void STDMETHODCALLTYPE EnqueueRequest(const XboxRequest* request) = 0;
virtual void STDMETHODCALLTYPE EnqueueStatus(IXboxDStorageStatusArray* status_array, UINT32 index) = 0;
virtual void STDMETHODCALLTYPE EnqueueSignal(void* fence, UINT64 value) = 0;
virtual void STDMETHODCALLTYPE Submit() = 0;
virtual void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0;
virtual void STDMETHODCALLTYPE Close() = 0;
};
struct IXboxDStorageFactory : IUnknown {
virtual HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0;
virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot7() = 0;
virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0;
virtual HRESULT STDMETHODCALLTYPE StubSlot9() = 0;
virtual HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) = 0;
};
namespace {
constexpr IID kXboxFactoryIid{0x62959d11, 0xd45f, 0x4884, {0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae}};
constexpr IID kXboxFileIid{0x43704f9f, 0x27c6, 0x4a9f, {0x88, 0x15, 0xd1, 0x65, 0x27, 0x89, 0x4d, 0xf4}};
constexpr IID kXboxStatusArrayIid{0xcd66d752, 0x2786, 0x44f7, {0x90, 0x70, 0xe2, 0xa6, 0xfd, 0xad, 0x3f, 0x1b}};
constexpr IID kXboxQueueIid{0x3c02cb0c, 0xc050, 0x4195, {0x99, 0xa1, 0xa1, 0xce, 0x94, 0xba, 0x33, 0xc5}};
// DSTORAGE_REQUEST_OPTIONS bits (authorized GDK header).
constexpr UINT64 kZlibDecompress = 1ull << 0;
constexpr UINT64 kDestinationIsPhysicalPages = 1ull << 21;
constexpr UINT64 kSourceTypeMemory = 1ull << 22;
constexpr UINT64 kSourceIsPhysicalPages = 1ull << 23;
// xmem constants (authorized GDK documentation, as in test_xmem_physical).
constexpr SIZE_T kPage = 64 * 1024;
constexpr DWORD kMem64KPages = 0x20400000;
constexpr uint64_t kXMemCpu = 0x1;
constexpr uint64_t kXMemMappable = 0x20;
constexpr BYTE kFill = 0xCC;
int g_failed = 0;
int g_checks = 0;
void check(bool cond, const char* fmt, ...) {
++g_checks;
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);
}
bool wait_complete(IXboxDStorageStatusArray* status, UINT32 index) {
for (int i = 0; i < 500; ++i) {
if (status->IsComplete(index)) return true;
Sleep(10);
}
return false;
}
/* "pg %04d;" for i % 251, i = 0..16999 (136000 bytes), zlib level 9 (CPython). */
constexpr size_t kPlainSize = 136000;
const uint8_t kZlibStream[] = {
0x78, 0xda, 0xed, 0xd5, 0xbb, 0x0d, 0x05, 0x86, 0x0d, 0x04, 0xc1, 0x56, 0x5c, 0x82, 0x8e, 0xef,
0x0f, 0x17, 0xe4, 0x54, 0xfd, 0x47, 0x16, 0xac, 0x75, 0x09, 0xca, 0x86, 0x09, 0xb3, 0xcb, 0x16,
0xf3, 0xe7, 0x7f, 0xfe, 0xf5, 0xc7, 0x5f, 0xf7, 0xef, 0x3f, 0xff, 0xf7, 0xd7, 0xbf, 0xfe, 0xa3,
0xff, 0xec, 0xbf, 0xfa, 0xef, 0xfe, 0xa7, 0xff, 0xed, 0xff, 0xfe, 0xfe, 0x6b, 0x6f, 0xed, 0xad,
0xbd, 0xb5, 0xb7, 0xf6, 0xd6, 0xde, 0xda, 0x5b, 0x7b, 0x6b, 0x6f, 0xed, 0x5d, 0x7b, 0xd7, 0xde,
0xb5, 0x77, 0xed, 0x5d, 0x7b, 0xd7, 0xde, 0xb5, 0x77, 0xed, 0x5d, 0x7b, 0xd7, 0xde, 0xa3, 0xbd,
0x47, 0x7b, 0x8f, 0xf6, 0x1e, 0xed, 0x3d, 0xda, 0x7b, 0xb4, 0xf7, 0x68, 0xef, 0xd1, 0xde, 0xa3,
0xbd, 0x47, 0x7b, 0xcf, 0xf6, 0x9e, 0xed, 0x3d, 0xdb, 0x7b, 0xb6, 0xf7, 0x6c, 0xef, 0xd9, 0xde,
0xb3, 0xbd, 0x67, 0x7b, 0xcf, 0xf6, 0x9e, 0xed, 0xbd, 0xda, 0x7b, 0xb5, 0xf7, 0x6a, 0xef, 0xd5,
0xde, 0xab, 0xbd, 0x57, 0x7b, 0xaf, 0xf6, 0x5e, 0xed, 0xbd, 0xda, 0x7b, 0xb5, 0xf7, 0x6e, 0xef,
0xdd, 0xde, 0xbb, 0xbd, 0x77, 0x7b, 0xef, 0xf6, 0xde, 0xed, 0xbd, 0xdb, 0x7b, 0xb7, 0xf7, 0x6e,
0xef, 0xdd, 0xde, 0xa7, 0xbd, 0x4f, 0x7b, 0x9f, 0xf6, 0x3e, 0xed, 0x7d, 0xda, 0xfb, 0xb4, 0xf7,
0x69, 0xef, 0xd3, 0xde, 0xa7, 0xbd, 0x4f, 0x7b, 0xdf, 0xf6, 0xbe, 0xed, 0x7d, 0xdb, 0xfb, 0xb6,
0xf7, 0x6d, 0xef, 0xdb, 0xde, 0xb7, 0xbd, 0x6f, 0x7b, 0xdf, 0xf6, 0xbe, 0xed, 0xfd, 0xda, 0xfb,
0xb5, 0xf7, 0x6b, 0xef, 0xd7, 0xde, 0xaf, 0xbd, 0x5f, 0x7b, 0xbf, 0xf6, 0x7e, 0xed, 0xfd, 0xda,
0xfb, 0xfd, 0xbd, 0xb7, 0xfa, 0x58, 0x7d, 0xac, 0x3e, 0x56, 0x1f, 0xab, 0x8f, 0xd5, 0xc7, 0xea,
0x63, 0xf5, 0xb1, 0xfa, 0x58, 0x7d, 0xac, 0x3e, 0x56, 0x1f, 0xab, 0x8f, 0xd5, 0xc7, 0xea, 0x63,
0xf5, 0xb1, 0xfa, 0x58, 0x7d, 0xac, 0x3e, 0x56, 0x1f, 0xab, 0x8f, 0xd5, 0xc7, 0xea, 0x63, 0xf5,
0xb1, 0xfa, 0x58, 0x7d, 0xac, 0x3e, 0x56, 0x1f, 0xab, 0x8f, 0xd5, 0xc7, 0xea, 0x63, 0xf5, 0xb1,
0xfa, 0x58, 0x7d, 0xac, 0x3e, 0x56, 0x1f, 0xab, 0x8f, 0xd5, 0xc7, 0xea, 0x63, 0xf5, 0xb1, 0xfa,
0x58, 0x7d, 0xac, 0x3e, 0x56, 0x1f, 0xab, 0x8f, 0xd5, 0xc7, 0xea, 0x63, 0xf5, 0xb1, 0xfa, 0x58,
0x7d, 0xac, 0x3e, 0x56, 0x1f, 0xab, 0x8f, 0xd5, 0xc7, 0xea, 0x63, 0xf5, 0xb1, 0xfa, 0x58, 0x7d,
0xac, 0x3e, 0x56, 0x1f, 0xab, 0x8f, 0xd5, 0xc7, 0xea, 0x63, 0xf5, 0xb1, 0xfa, 0x58, 0x7d, 0xac,
0x3e, 0x56, 0x1f, 0xab, 0x8f, 0xd5, 0xc7, 0xea, 0x63, 0xf5, 0xb1, 0xfa, 0x58, 0x7d, 0xac, 0x3e,
0x56, 0x1f, 0xab, 0x8f, 0xd5, 0xc7, 0xea, 0x63, 0xf5, 0xb1, 0xfa, 0x58, 0x7d, 0xac, 0x3e, 0x56,
0x1f, 0xab, 0x8f, 0xd5, 0xc7, 0xea, 0x63, 0xf5, 0xb1, 0xfa, 0x58, 0x7d, 0xac, 0x3e, 0x56, 0x1f,
0xab, 0x8f, 0xd5, 0xc7, 0xea, 0x63, 0xf5, 0xb1, 0xfa, 0x58, 0x7d, 0xac, 0x3e, 0x56, 0x1f, 0x57,
0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57,
0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57,
0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57,
0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57,
0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57,
0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57, 0x1f, 0x57,
0x1f, 0x57, 0x1f, 0xf7, 0x7f, 0x3f, 0xb8, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a,
0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae,
0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7,
0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75,
0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c,
0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce,
0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb,
0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9,
0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d,
0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7,
0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73,
0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a,
0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae,
0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7,
0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75,
0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c,
0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce,
0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb,
0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9,
0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d,
0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7,
0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73,
0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a,
0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae,
0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7,
0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75,
0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c,
0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce,
0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb,
0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9,
0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d,
0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7,
0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73,
0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a,
0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae,
0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7,
0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75,
0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c,
0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce,
0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb,
0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9,
0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d,
0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7,
0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73,
0x9d, 0xeb, 0x5c, 0xe7, 0x3a, 0xd7, 0xb9, 0xce, 0x75, 0xae, 0x73, 0x9d, 0xeb, 0x5c, 0xe7, 0xfa,
0x3f, 0xe2, 0xfa, 0x7f, 0x01, 0xc6, 0xe2, 0x9e, 0xc4,
};
char g_plain[kPlainSize + 1];
void build_plain() {
for (int i = 0, at = 0; i < 17000; ++i) {
at += std::snprintf(g_plain + at, sizeof(g_plain) - at, "pg %04d;", i % 251);
}
}
// The title's view: its four pages mapped in allocation order at `view`.
BYTE* g_view = nullptr;
ULONG_PTR g_pages[4] = {};
BYTE* page_in_view(ULONG_PTR number) {
for (int i = 0; i < 4; ++i) {
if (g_pages[i] == number) return g_view + i * kPage;
}
return nullptr;
}
void fill_view() { std::memset(g_view, kFill, 4 * kPage); }
// Checks that `size` bytes of `expected` were written from `offset` through `array` (in array
// order), and that every other byte of the four pages kept the fill.
void check_written(const char* what, const ULONG_PTR* array, size_t count, size_t offset, const void* expected,
size_t size) {
static BYTE want[4 * kPage];
std::memset(want, kFill, sizeof(want));
const auto* src = static_cast<const BYTE*>(expected);
for (size_t j = 0; j < size; ++j) {
const size_t at = offset + j;
const size_t k = at / kPage;
if (k >= count) break;
BYTE* page = page_in_view(array[k]);
want[(page - g_view) + at % kPage] = src[j];
}
size_t first_bad = SIZE_MAX;
for (size_t i = 0; i < sizeof(want) && first_bad == SIZE_MAX; ++i) {
if (g_view[i] != want[i]) first_bad = i;
}
check(first_bad == SIZE_MAX, "%s: page bytes differ first at page %zu offset 0x%zx (got 0x%02x, want 0x%02x)",
what, first_bad / kPage, first_bad % kPage, first_bad == SIZE_MAX ? 0 : g_view[first_bad],
first_bad == SIZE_MAX ? 0 : want[first_bad]);
}
} // namespace
int main() {
build_plain();
ULONG_PTR count = 4;
check(XMemAllocatePhysicalPages(0, &count, g_pages) && count == 4, "XMemAllocatePhysicalPages(4) must succeed");
g_view = static_cast<BYTE*>(
XMemVirtualAlloc(nullptr, 4 * kPage, MEM_RESERVE | kMem64KPages, kXMemMappable | kXMemCpu, PAGE_READWRITE));
check(g_view && XMemMapPhysicalPages(g_view, 4, g_pages) == g_view, "the title view of the pages must map");
if (g_failed) return 1;
IXboxDStorageFactory* factory = nullptr;
HRESULT hr = DStorageGetFactory(kXboxFactoryIid, reinterpret_cast<void**>(&factory));
check(hr == S_OK && factory, "DStorageGetFactory(Xbox) must succeed (hr=0x%08lx)", static_cast<unsigned long>(hr));
IXboxDStorageStatusArray* status = nullptr;
hr = factory ? factory->CreateStatusArray(8, "pages", kXboxStatusArrayIid, reinterpret_cast<void**>(&status)) : E_FAIL;
check(hr == S_OK && status, "CreateStatusArray must succeed (hr=0x%08lx)", static_cast<unsigned long>(hr));
if (g_failed) return 1;
/* 1. File source, zlib, into three pages given out of order, starting 0x9000 into the first:
* 136000 bytes from 0x9000 end in the third page. */
WCHAR temp_dir[MAX_PATH] = {};
WCHAR zlib_file[MAX_PATH] = {};
check(GetTempPathW(MAX_PATH, temp_dir) > 0 && GetTempFileNameW(temp_dir, L"bxp", 0, zlib_file) != 0,
"a temporary file name must be available");
HANDLE raw = CreateFileW(zlib_file, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (raw != INVALID_HANDLE_VALUE) {
BYTE prefix[100];
std::memset(prefix, 0x5A, sizeof(prefix));
DWORD written = 0;
check(WriteFile(raw, prefix, sizeof(prefix), &written, nullptr) &&
WriteFile(raw, kZlibStream, sizeof(kZlibStream), &written, nullptr) && written == sizeof(kZlibStream),
"the zlib payload must be written");
CloseHandle(raw);
}
IXboxDStorageFile* file = nullptr;
hr = factory->OpenFile(zlib_file, kXboxFileIid, reinterpret_cast<void**>(&file));
check(hr == S_OK && file, "OpenFile must succeed (hr=0x%08lx)", static_cast<unsigned long>(hr));
XboxQueueDesc file_desc{};
file_desc.capacity = 16;
file_desc.name = "page_file_queue";
IXboxDStorageQueue* file_q = nullptr;
hr = factory->CreateQueueX(&file_desc, kXboxQueueIid, reinterpret_cast<void**>(&file_q));
check(hr == S_OK && file_q, "CreateQueueX(file) must succeed (hr=0x%08lx)", static_cast<unsigned long>(hr));
if (file && file_q) {
ULONG_PTR array[] = {g_pages[2], g_pages[0], g_pages[1]};
fill_view();
XboxRequest r{};
r.options = kZlibDecompress | kDestinationIsPhysicalPages;
r.destination = array;
r.destination_page_offset = 0x9000;
r.destination_size = kPlainSize;
r.source_ptr = file;
r.file_offset = 100;
r.source_size = sizeof(kZlibStream);
file_q->EnqueueRequest(&r);
file_q->EnqueueStatus(status, 0);
file_q->Submit();
check(wait_complete(status, 0) && status->GetHResult(0) == S_OK,
"zlib file request into physical pages must succeed (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(0)));
check_written("zlib file request", array, 3, 0x9000, g_plain, kPlainSize);
/* 2. A page number that was never allocated fails the request and writes nothing. */
ULONG_PTR bad[] = {g_pages[3], g_pages[0] + g_pages[1] + g_pages[2] + g_pages[3] + 16 * 1024};
fill_view();
XboxRequest b = r;
b.destination = bad;
b.destination_page_offset = 0;
b.destination_size = static_cast<UINT32>(kPage + 16);
b.source_size = sizeof(kZlibStream);
file_q->EnqueueRequest(&b);
file_q->EnqueueStatus(status, 1);
file_q->Submit();
check(wait_complete(status, 1) && FAILED(status->GetHResult(1)),
"a request naming an unallocated page must fail (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(1)));
check_written("unallocated page", bad, 0, 0, g_plain, 0);
/* 5. A title may read only the first part of a compressed block: a 4096-byte destination
* from the 136000-byte stream receives exactly the stream's first 4096 bytes, and the
* bytes after the destination keep their fill. */
static BYTE part[4096 + 64];
std::memset(part, 0xA5, sizeof(part));
XboxRequest f{};
f.options = kZlibDecompress;
f.destination = part;
f.destination_size = 4096;
f.source_ptr = file;
f.file_offset = 100;
f.source_size = sizeof(kZlibStream);
file_q->EnqueueRequest(&f);
file_q->EnqueueStatus(status, 4);
file_q->Submit();
check(wait_complete(status, 4) && status->GetHResult(4) == S_OK,
"a zlib request for the first 4096 bytes of a longer stream must succeed (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(4)));
check(std::memcmp(part, g_plain, 4096) == 0, "the first 4096 bytes of the stream must be delivered");
bool tail_kept = true;
for (size_t i = 4096; i < sizeof(part); ++i) tail_kept = tail_kept && part[i] == 0xA5;
check(tail_kept, "bytes after a partial zlib destination must not be written");
file_q->Close();
}
/* 3. Memory source, uncompressed, 64 bytes across a page boundary (0xFFE0 in the first page). */
XboxQueueDesc mem_desc{};
mem_desc.source_type = 1;
mem_desc.capacity = 16;
mem_desc.name = "page_memory_queue";
IXboxDStorageQueue* mem_q = nullptr;
hr = factory->CreateQueueX(&mem_desc, kXboxQueueIid, reinterpret_cast<void**>(&mem_q));
check(hr == S_OK && mem_q, "CreateQueueX(memory) must succeed (hr=0x%08lx)", static_cast<unsigned long>(hr));
if (mem_q) {
BYTE source[64];
for (int i = 0; i < 64; ++i) source[i] = static_cast<BYTE>(0x80 + i);
ULONG_PTR array[] = {g_pages[3], g_pages[1]};
fill_view();
XboxRequest m{};
m.options = kSourceTypeMemory | kDestinationIsPhysicalPages;
m.destination = array;
m.destination_page_offset = 0xFFE0;
m.destination_size = sizeof(source);
m.source_ptr = source;
m.source_size = sizeof(source);
mem_q->EnqueueRequest(&m);
mem_q->EnqueueStatus(status, 2);
mem_q->Submit();
check(wait_complete(status, 2) && status->GetHResult(2) == S_OK,
"memory request into physical pages must succeed (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(2)));
check_written("memory request", array, 2, 0xFFE0, source, sizeof(source));
/* 4. A physical-page source is not implemented: refused with E_NOTIMPL, nothing written. */
fill_view();
XboxRequest s = m;
s.options = kSourceTypeMemory | kSourceIsPhysicalPages;
s.destination = source;
s.destination_page_offset = 0;
s.source_ptr = array;
mem_q->EnqueueRequest(&s);
mem_q->EnqueueStatus(status, 3);
mem_q->Submit();
check(wait_complete(status, 3) && status->GetHResult(3) == E_NOTIMPL,
"a physical-page source must be refused with E_NOTIMPL (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(3)));
check_written("physical-page source", array, 0, 0, source, 0);
/* 6. The title fills its page array after EnqueueRequest returns and before it submits:
* the pages it names then are the ones written. */
ULONG_PTR late[2] = {0, 0};
fill_view();
XboxRequest l = m;
l.destination = late;
l.destination_page_offset = 0x100;
mem_q->EnqueueRequest(&l);
late[0] = g_pages[2];
late[1] = g_pages[0];
mem_q->EnqueueStatus(status, 5);
mem_q->Submit();
check(wait_complete(status, 5) && status->GetHResult(5) == S_OK,
"a page array filled after EnqueueRequest must be used (hr=0x%08lx)",
static_cast<unsigned long>(status->GetHResult(5)));
check_written("page array filled after enqueue", late, 1, 0x100, source, sizeof(source));
mem_q->Close();
mem_q->Release();
}
if (file_q) file_q->Release();
if (file) {
file->Close();
file->Release();
}
DeleteFileW(zlib_file);
status->Release();
factory->Release();
/* The request's own mapping is gone: the pages can be unmapped and freed. */
check(XMemMapPhysicalPages(g_view, 4, nullptr) == g_view, "the title view must unmap");
check(XMemFreePhysicalPages(4, g_pages), "the pages must be freed");
if (g_failed) {
std::fprintf(stderr, "test_xcrdapi_page_destination: %d of %d checks failed\n", g_failed, g_checks);
return 1;
}
std::printf("test_xcrdapi_page_destination: PASS (%d checks)\n", g_checks);
return 0;
}
@@ -5,7 +5,15 @@
* view in one step, so XCRDAPI.dll brackets its stores with xmem.dll's remap guard
* (bx_xmem_remap_guard_enter / _leave) and the remapping calls wait for it. Memory requests that
* span the window are queued while the window is remapped over and over; without the guard a
* store lands in a gap and the process dies in an access violation.
* store lands in a gap and the process dies in an access violation. Three request shapes, each
* for about 2 s:
* 1. memory to memory into the window (public DirectStorage interface): stores;
* 2. a zlib stream inflated into the window for about 4 s (BetterXen's request interface):
* stores and back-reference loads by the inflater;
* 3. memory to memory out of the window into private memory: loads, which fault in the gap
* like stores.
* The zlib stream is built here by hand (RFC 1950/1951, fixed Huffman codes), so the expected
* output does not come from the code under test.
*/
#include <windows.h>
@@ -15,6 +23,7 @@
#include <vector>
#include "dstorage_mingw.h"
#include "synthetic_storage.h"
extern "C" {
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, uint64_t, DWORD);
@@ -50,6 +59,62 @@ struct Com {
void** out() { return reinterpret_cast<void**>(&value); }
};
// RFC 1950 stream for `count` copies of `byte`: one fixed-Huffman deflate block (RFC 1951
// 3.2.6) holding the byte as a literal, then copies of distance 1 (length 258, and one shorter
// copy for the rest), then end of block; adler-32 at the end.
class BitWriter {
public:
std::vector<unsigned char> bytes;
void bits(uint32_t value, int n) { // LSB first, as deflate packs header and extra bits
for (int i = 0; i < n; ++i) put((value >> i) & 1u);
}
void code(uint32_t value, int n) { // Huffman codes are packed most significant bit first
for (int i = n - 1; i >= 0; --i) put((value >> i) & 1u);
}
private:
void put(uint32_t bit) {
if (used_ == 0) bytes.push_back(0);
bytes.back() |= static_cast<unsigned char>(bit << used_);
used_ = (used_ + 1) & 7;
}
int used_ = 0;
};
std::vector<unsigned char> zlib_repeat(unsigned char byte, uint32_t count) {
BitWriter w;
w.bits(1, 1); // BFINAL
w.bits(1, 2); // BTYPE = 01, fixed Huffman codes
w.code(0x30u + byte, 8); // literals 0-143: 8-bit codes 00110000 + value
uint32_t left = count - 1;
while (left) {
if (left >= 258) {
w.code(0xC0u + (285 - 280), 8); // length 258: symbol 285, codes 280-287 are 11000000 + n
left -= 258;
} else {
// Lengths 3..257 below 258 use symbols 257-284 with extra bits; this stream only needs
// what is left after 258-byte copies, which the test keeps at 15 (symbol 267: lengths
// 15-16, 1 extra bit).
if (left != 15) return {};
w.code(267 - 256, 7); // symbols 256-279: 7-bit codes 0000000 + (n - 256)
w.bits(0, 1); // extra bit: 15 = base 15 + 0
left = 0;
}
w.code(0, 5); // distance code 0 = distance 1, 5-bit fixed code, no extra bits
}
w.code(0, 7); // end of block: symbol 256
std::vector<unsigned char> out = {0x78, 0x01};
out.insert(out.end(), w.bytes.begin(), w.bytes.end());
uint32_t a = 1, b = 0;
for (uint32_t i = 0; i < count; ++i) {
a = (a + byte) % 65521;
b = (b + a) % 65521;
}
const uint32_t adler = (b << 16) | a;
for (int shift = 24; shift >= 0; shift -= 8) out.push_back(static_cast<unsigned char>(adler >> shift));
return out;
}
} // namespace
int main() {
@@ -101,8 +166,77 @@ int main() {
++batches;
}
CHECK(WaitForSingleObject(queue->GetErrorEvent(), 0) == WAIT_TIMEOUT);
std::printf("batches=%d remaps=%d\n", batches, remaps);
std::printf("stores: batches=%d remaps=%d\n", batches, remaps);
CHECK(batches > 10 && remaps > 40);
// 2. zlib streams inflated into the window, through BetterXen's request interface.
using namespace bx::storage;
Com<Factory> synthetic;
CHECK(DStorageGetFactory(factory_iid, synthetic.out()) == S_OK && synthetic.value);
Com<Queue> zqueue;
CHECK(synthetic->CreateQueue(64, queue_iid, zqueue.out()) == S_OK && zqueue.value);
const std::vector<unsigned char> zstream = zlib_repeat(0x5A, kRequestBytes); // 1 + 1016 * 258 + 15 bytes
CHECK(!zstream.empty() && zstream.size() < kRequestBytes);
Request zrequest{nullptr, 0, zstream.data(), base, static_cast<DWORD>(zstream.size()), compression_zlib};
zrequest.output_size = kRequestBytes;
// Control: the stream inflates correctly with nothing remapped.
zqueue->EnqueueRequest(&zrequest);
zqueue->EnqueueSetEvent(done);
zqueue->Submit();
CHECK(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0);
ErrorRecord zcontrol{};
zqueue->RetrieveErrorRecord(&zcontrol);
std::printf("zlib control: failures=%llu hr=0x%08lx first=%02x last=%02x\n",
static_cast<unsigned long long>(zcontrol.failure_count), static_cast<unsigned long>(zcontrol.first_error),
base[0], base[kRequestBytes - 1]);
CHECK(zcontrol.failure_count == 0 && base[0] == 0x5A && base[kPage + 7] == 0x5A && base[kRequestBytes - 1] == 0x5A);
int zbatches = 0;
const DWORD zstart = GetTickCount();
while (GetTickCount() - zstart < 4000) {
for (int i = 0; i < 4; ++i) zqueue->EnqueueRequest(&zrequest);
zqueue->EnqueueSetEvent(done);
zqueue->Submit();
for (int i = 0; i < 8; ++i) {
CHECK(XMemMapPhysicalPages(base + kPage, 2, (remaps & 1) ? swap_b : swap_a) == base + kPage);
++remaps;
}
CHECK(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0);
++zbatches;
}
ErrorRecord zerr{};
zqueue->RetrieveErrorRecord(&zerr);
std::printf("zlib under remap: batches=%d failures=%llu\n", zbatches, static_cast<unsigned long long>(zerr.failure_count));
if (zerr.failure_count) std::printf("zlib first error hr=0x%08lx count=%llu\n", static_cast<unsigned long>(zerr.first_error), static_cast<unsigned long long>(zerr.failure_count));
CHECK(zerr.failure_count == 0);
CHECK(base[0] == 0x5A && base[kRequestBytes - 1] == 0x5A); // slots 0 and 3 keep their pages
CHECK(zbatches > 10);
// 3. The window as the source: loads from title memory into private memory.
std::vector<unsigned char> sink(kRequestBytes, 0);
DSTORAGE_REQUEST load{};
load.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
load.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_MEMORY;
load.Source.Memory.Source = base;
load.Source.Memory.Size = kRequestBytes;
load.Destination.Memory.Buffer = sink.data();
load.Destination.Memory.Size = kRequestBytes;
int lbatches = 0;
const DWORD lstart = GetTickCount();
while (GetTickCount() - lstart < 2000) {
for (int i = 0; i < 4; ++i) queue->EnqueueRequest(&load);
queue->EnqueueSetEvent(done);
queue->Submit();
for (int i = 0; i < 4; ++i) {
CHECK(XMemMapPhysicalPages(base + kPage, 2, (remaps & 1) ? swap_b : swap_a) == base + kPage);
++remaps;
}
CHECK(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0);
++lbatches;
}
CHECK(WaitForSingleObject(queue->GetErrorEvent(), 0) == WAIT_TIMEOUT);
CHECK(sink[0] == 0x5A); // slot 0 still holds the inflated bytes
std::printf("loads: batches=%d remaps=%d\n", lbatches, remaps);
CHECK(lbatches > 10);
CloseHandle(done);
std::puts("test_xcrdapi_remap_guard: passed");
return 0;