Compare commits

...
Author SHA1 Message Date
ates e59a1eb1b7 gfx10-translate: integer, conversion and lane instructions (#716)
Signed scalar add/sub/min/max, v_cvt_u32_f32 with the ISA's clamping,
v_cvt_f32_ubyte0-3, v_rcp_iflag_f32, a three-source integer table
(v_lshl_add, v_add_lshl, v_lshl_or, v_and_or, v_or3, v_xor3, v_add3,
v_bfi, v_bfe) and v_readfirstlane_b32 as WaveReadLaneFirst. Locally 802
of the target build's 4,331 VS/PS shaders now translate (703 before).

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 06:09:53 +03:00
Ateş e52d5b0df7 Merge pull request #723 from MacosPorters/track-f/picture-stage-and-llvm-licence
[Docs] Current stage: Picture; LLVM opcode table accepted
2026-11-30 05:16:01 +03:00
ates 0dae988c7c Roadmap: current stage is Picture; record the LLVM opcode table as accepted
Repository owner's decisions of 2026-11-30: Boot is left (its gate was
not run under the run protocol) and Picture is current; the LLVM-
generated facts in gfx10-translate are accepted under section 4.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 05:15:41 +03:00
Ateş ba24aed650 Merge pull request #714 from MacosPorters/track-d/gfx10-translate-skeleton
[Picture] gfx10-translate: BetterXen's GFX10.3 shader translator on main
2026-11-30 04:55:36 +03:00
ates 5c3d4df8cf gfx10-translate: BetterXen's GFX10.3 shader translator on main
A Rust crate replacing the experiment-branch Python prototype:
console container reader, a decoder for every encoding format (opcode
names generated from the public LLVM disassembler; SDWA/DPP extension
words), HLSL translation of every prototype rule through family
tables, and coverage over local shaders. bx-cli shader translate and
bx-cli shader coverage run it.

The decoder prints the text llvm-mc prints for 127 instructions; three
shader pairs of our own translate to exactly the prototype's output.
Locally, all 4,331 target-build VS/PS shaders decode, 703 translate on
their own (491 with the prototype's rules), and all 214 pipeline pairs
the prototype translated give identical HLSL and layout.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 04:55:00 +03:00
Ateş 56783a31b1 Merge pull request #713 from MacosPorters/track-f/contributing-entry-point
[Docs] CONTRIBUTING: a short entry point for new members
2026-11-30 04:25:48 +03:00
ates 2567d87a65 CONTRIBUTING: a short entry point for new members, consistent with AGENTS.md
States the hard requirements (target build, GDK, Ghidra results,
distributed among members), setup and preflight, the current way of
working and how to run the target build, and removes the outdated
issue-comment claim workflow, 7-day rule and Wave 1 backlog.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 04:25:32 +03:00
Ateş b0b4f82f1d Merge pull request #712 from MacosPorters/track-a/run-diagnostics-input-asserts
[Boot] Scripted input and assert stepping for unattended target-build runs
2026-11-30 04:24:41 +03:00
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 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
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 8d7c3bf66c Merge remote-tracking branch 'origin/main' into track-c/get-frame-statistics-x
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 22:56:56 +01:00
ates 7f241ad170 Merge committed texture sizing into console profile fix
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:08:21 +03:00
ates 97947085bf Publish ConsoleMode before the guest starts
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:08:05 +03:00
ates f5aed211b5 Merge tested main into console profile registry fix
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:08:05 +03:00
Bartosz Szczepański a1fcd96836 d3d12_xs: implement GetFrameStatisticsX
Slot 81 returned E_NOTIMPL. It now answers frame-event (ORIGIN) and present statistics per frame pipeline token for the last 17 frames, in QueryPerformanceCounter ticks, S_FALSE when nothing of the requested types is available and E_INVALIDARG for unknown tokens, invalid type sets and invalid list arrangements, as documented. Types with no host source are never reported.

Test: test_d3d12_frame_statistics_x; 14 of its checks fail on main.
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 21:24:31 +01:00
Bartosz Szczepański 26003c37e2 d3d12_xs: claim: implement GetFrameStatisticsX
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 21:20:00 +01:00
Bartosz Szczepański 75f2ed8c3c Merge remote-tracking branch 'origin/main' into track-a/console-mode-registry
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 19:35:31 +01:00
Bartosz Szczepański c4ceadc39e runtime_veh: publish the console type as ConsoleMode in the registry
A title can read the REG_DWORD ConsoleMode under HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM instead of calling XSystemGetDeviceType. Without it the title takes itself for a PC and sizes its memory for Series X, which does not fit the Lockhart budget. bx_runtime_veh.dll now writes 0x60 (Lockhart) or 0x64 (Anaconda) at attach, from the profile XSystemGetDeviceType answers from.

Test: test_console_mode; it fails on main because the key does not exist.
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 18:20:18 +01:00
Bartosz Szczepański 00782e62e9 runtime_veh: claim: publish the console type in the registry
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 18:13:15 +01:00
75 changed files with 8864 additions and 104 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
+36
View File
@@ -10,6 +10,10 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- **Current stage: Picture** (`docs/roadmap.md`), by the repository owner's decision on 2026-11-30. Boot is marked as left without its ten-run gate having been run under the run protocol. The first frames and the menus are reached, and the open work is translation, textures and stability. The new pinned ladder issue carries the live status. The repository owner also accepted the LLVM-generated opcode table and test vectors of `gfx10-translate` (`docs/research/upstream-registry.md`).
- **`CONTRIBUTING.md` is a short entry point for new members, consistent with AGENTS.md.** It covers the hard requirements (the target build, the GDK and the Ghidra results, distributed among members), setup (`setup --find`, `preflight`), the current way of working (pick order, checking for existing work, draft pull request claims with the 3-day rule, tests, Section 8), and running the target build with its diagnostic switches. The outdated workflow is removed: issue-comment claims, the 7-day rule and the Wave 1 backlog. The licensing, sign-off and merge sections are unchanged.
- **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 +31,31 @@ 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
- **`gfx10-translate`: integer, conversion and lane instructions** (#716).
- **Scalar:** `s_add_i32`, `s_sub_i32`, `s_min_i32`, `s_max_i32`.
- **Conversions:** `v_cvt_u32_f32`, with the ISA's clamping of NaN, negative and too-large values; `v_cvt_f32_ubyte0`–`3`; `v_rcp_iflag_f32`.
- **New three-source integer table (`VOP3_UINT3`):** `v_lshl_add_u32`, `v_add_lshl_u32`, `v_lshl_or_b32`, `v_and_or_b32`, `v_or3_b32`, `v_xor3_b32`, `v_add3_u32`, `v_bfi_b32` and `v_bfe_u32`.
- **Lanes:** `v_readfirstlane_b32` as `WaveReadLaneFirst`.
- **Measured locally:** 802 of the target build's 4,331 vertex and pixel shaders translate on their own, up from 703.
- **Tests:** `integer_conversion_and_lane_instructions`, with llvm-mc encodings and expected HLSL from the ISA definitions. The prototype goldens are unchanged.
- **`shader-transpiler/crates/gfx10-translate`: BetterXen's GFX10.3 shader translator on `main`** (roadmap, Picture stage). It replaces the experiment-branch Python prototype, which moves to `scripts/console-shader/translate.py` as the reference.
- **Pieces:** console container reader (zlib ported from `zlib_inflate.cpp`); a decoder for every encoding format, with SDWA/DPP extension words; HLSL translation of every prototype rule through family tables; and coverage. `bx-cli shader translate <vs> <ps> --out <dir>` and `bx-cli shader coverage <dir>` run it.
- **Opcode table:** generated from the public LLVM disassembler by `scripts/console-shader/gen_opcodes.py` (gfx1030, gaps from gfx1010, whose GFX10.1 multiply-adds the console compiler emits). Facts only; recorded in the upstream registry.
- **Tests:** 127 instructions decode to exactly the text `llvm-mc` prints (`tests/llvm_vectors.txt`). Three shader pairs of our own, assembled by `llvm-mc`, translate to exactly the prototype's HLSL and layout (`tests/goldens/`). Plus refusals, the multiply-add family, wave32 mask bookkeeping and half compressed exports, and FNV-1a against the published vectors.
- **Measured locally on the target build's 4,331 vertex and pixel shaders** (they stay local):
- every one decodes; the scan takes 3.6 s, against about 10 minutes through `llvm-mc`;
- 703 (16.2%) translate on their own, against 491 for the prototype's rules alone;
- all 214 pipeline pairs the prototype translated give identical HLSL and layout.
- **Differences from the prototype** are listed in the crate README. Among them: `s_movk_i32` sign-extends, and cache keys use standard FNV-1a (the prototype's offset basis is missing a digit).
- **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,6 +122,12 @@ 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` (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.
@@ -104,6 +139,7 @@ remains unsupported.
- **`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.
+41 -22
View File
@@ -1,35 +1,53 @@
# Contributing to BetterXen
BetterXen is a modular, CrossOver-based Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS. Contributions are organized into **6 parallel tracks** so 5–8+ human contributors and coding agents can work simultaneously without merge conflicts.
BetterXen runs a project-authorized Xbox Series title on Apple Silicon Macs, through CrossOver, Rosetta 2 and D3DMetal plus BetterXen's own shims. Members work by pointing a coding agent at this repository and saying **"work"**; the agent follows [AGENTS.md](AGENTS.md). This page is the short version for a person joining.
## Active Work & Track Ownership
## What you need
The single authoritative plan is [docs/roadmap.md](docs/roadmap.md) (Milestones M0–M6), supported by [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and the ready-to-claim Wave 1 issues in [docs/issues/wave-1-backlog.md](docs/issues/wave-1-backlog.md). The earlier native-first workspace was retired from `main` per [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md) and remains preserved permanently at Git tag `native-first-final`.
These are a **hard requirement**. Without every one of them you, and your agent, do not work on the repository:
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**. Maintainer-directed tasks have a narrow exception ([AGENTS.md](AGENTS.md) §2).
4. If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both tracks implement in parallel.
5. Add new synthetic PE32+ conformance binaries under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake — no shared-file edits needed).
- an Apple Silicon Mac with CrossOver 26.3+ (licensed separately, never bundled), D3DMetal, and at least 10 GiB free;
- **the project-authorized target build**;
- **the GDK**, under the project's authorization;
- **the Ghidra results of the target build** (its static-analysis run: `RUN_REPORT.md`, `exports/`, `decompiled/`).
## Development & Verification
The target build, the GDK and the Ghidra results are distributed among members. Ask a maintainer for them; never get them anywhere else, and never commit, upload or post anything from them (paths, file names, hashes or bytes).
Requirements on Apple Silicon macOS: Rust 1.85+ (`aarch64-apple-darwin`), `mingw-w64` & `cmake` (`brew install mingw-w64 cmake`), Python 3.11+, Rosetta 2, and CrossOver 26.3+ (externally installed, never bundled).
Run these checks before opening a PR:
## Getting started
```sh
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli
scripts/build-shims.sh
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_veh_clwb.exe
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_shim_exports.exe
python3 scripts/audit/docs_hygiene.py
git clone https://github.com/MacosPorters/betterxen.git && cd betterxen
brew install mingw-w64 cmake gh # Rust 1.85+ and Python 3.11+ are also needed
cargo build --locked -p bx-cli
target/debug/bx-cli setup --find # finds the build, the GDK and the Ghidra results in your home folder
target/debug/bx-cli preflight # must print: Ready to work.
```
Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/skip counts. Never report a skipped test or unavailable tool as a pass.
`setup` saves the three locations in `~/.config/betterxen/local.conf`, outside the repository, once per machine. If `--find` finds more than one distinct build, choose with `bx-cli setup --target-exe <path>`.
Then tell your agent **"work"**. If you work by hand, follow the same steps yourself: [AGENTS.md](AGENTS.md) Section 0.
## How work is organised
The full process is [AGENTS.md](AGENTS.md) Section 0 and [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md). In short:
1. **Pick one thing**, in this order: your own pull requests that need attention; a review of someone else's; a `handoff` issue of the current stage (named on the pinned `ladder` issue); or the first thing the target build stops on.
2. **Check for existing work first.** Before investigating any problem the game shows, search open and merged pull requests and open issues for it. If an open pull request covers it, check that branch out and work there.
3. **Claim it with a draft pull request** titled `[<Stage>] <signature>`, before writing the fix. A draft with no push for 3 days may be taken over.
4. **Evidence, smallest fix, test.** Every contract the fix introduces gets a conformance test under `tests/conformance/test_<name>/` that fails without the fix and passes twice in a row with it.
5. **Verify** with [AGENTS.md](AGENTS.md) Section 8, fill in the five-part description (Blocker, Contract, Fix, Test, Proof), and mark it ready.
Something you can't finish goes into a `handoff` issue instead, with what you saw, tried and still don't know.
## Running the target build
Runs are made offline, inside a sandbox that blocks outbound network: [docs/testing/target-build-review.md](docs/testing/target-build-review.md) has the procedure and the diagnostic switches. Three switches matter for getting through the title unattended:
- `BX_INPUT_SCRIPT=A@40,A@50` presses buttons;
- `BX_CONTINUE_ASSERTS=1` steps over the title's continuable asserts;
- `BX_PRESENT_DUMP=<folder>` saves frames.
`bx-cli run` stages the GDK's texture libraries for the target build automatically ([ADR 0010](docs/adr/0010-gdk-texture-libraries.md)). `bx-cli report <log.jsonl>...` turns run logs into the report and the blocker signatures that pull requests are titled with.
## Licensing & Provenance Policy
@@ -39,9 +57,10 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
- Never claim Xbox hardware verification (BetterXen has no Xbox hardware access) or independent certification of your own work; classify evidence per [docs/claims.toml](docs/claims.toml).
## Pull Requests & DCO Sign-Off
- Branch from `main`, keep changes focused inside your track scope, link the issue with `Closes #<number>`, update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, and update [docs/README.md](docs/README.md) when adding or reorganizing docs.
- Branch from `main`, keep changes focused inside your track scope, link any related issue (`Closes #<number>` for a handoff it finishes), update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, and update [docs/README.md](docs/README.md) when adding or reorganizing docs.
- Disclose material AI assistance and personally review generated changes. Never include secrets, personal paths, or credentials in patches or logs.
- Sign off every commit under the [Developer Certificate of Origin](https://developercertificate.org/):
Generated
+5
View File
@@ -9,6 +9,7 @@ dependencies = [
"bx-probe",
"bx-telemetry",
"dxbc-accc",
"gfx10-translate",
"libc",
]
@@ -31,6 +32,10 @@ dependencies = [
name = "dxbc-accc"
version = "0.2.0"
[[package]]
name = "gfx10-translate"
version = "0.2.0"
[[package]]
name = "libc"
version = "0.2.191"
+1
View File
@@ -5,6 +5,7 @@ members = [
"launcher/crates/bx-telemetry",
"shader-transpiler/crates/d3dmetal-harness",
"shader-transpiler/crates/dxbc-accc",
"shader-transpiler/crates/gfx10-translate",
]
exclude = ["legacy-native"]
resolver = "3"
+2
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
@@ -27,6 +28,7 @@
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
- [gfx10-translate](../shader-transpiler/crates/gfx10-translate/README.md) — BetterXen's GFX10.3 console shader translator: container reader, decoder with an LLVM-generated opcode table, HLSL translation ported from the Python prototype, coverage over local shaders, and how to add an instruction.
- [Shader Corpus](../shader-transpiler/corpus/README.md) — Phase 0 of the console shader translator: BetterXen-authored kernels built locally into console containers, Microsoft ISA listings and PC DXIL, with the derived `FSPX` code-section layout (#649).
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
+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.
+1
View File
@@ -14,6 +14,7 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
| VIctory | [Marvisak/VIctory](https://github.com/Marvisak/VIctory) | `13f91caee25f` | GPL-3.0 (GitHub); a prior local review found per-file notices (see `experiments/victory-native/licenses.md`, local, untracked) | Discovery reference only | Described as an attempt at running one commercial game on PC. Its inputs are an Xbox Series build of that game. PortWatch describes the efforts it tracks as targeting a "leaked Xbox Series build". |
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in retired `portwatch-native-macos.md` at tag `native-first-final`). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
| LLVM (AMDGPU target) | [llvm/llvm-project](https://github.com/llvm/llvm-project) | Homebrew LLVM 23.1.6 (`llvm-mc`) | Apache-2.0 WITH LLVM-exception | Source of the generated GFX10.3 opcode table and decoder test vectors (`shader-transpiler/crates/gfx10-translate`) | Run locally by `scripts/console-shader/gen_opcodes.py` and `gen_llvm_vectors.py`. Only facts are committed (opcode number to mnemonic, instruction words to text); no LLVM code or tables are copied. Accepted by the repository owner on 2026-11-30 (AGENTS.md Section 4). |
| libc | [rust-lang/libc](https://github.com/rust-lang/libc) | `0.2.191` (`ccc2ff4aaab9`) | MIT OR Apache-2.0 (used under MIT) | `bx-cli` process groups and signals (#408) | Unmodified crates.io dependency, locked checksum. |
## Built and run for M1-D2 (#417)
+2 -2
View File
@@ -53,8 +53,8 @@ Every gate below is measured the same way ([working method](process/working-meth
| Stage | The target build… | Exit gate | Status |
| --- | --- | --- | --- |
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **In development** |
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | Planned |
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **Left** (repository owner's decision, 2026-11-30; the gate was not run under the run protocol) |
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | **Current** (since 2026-11-30) |
| **Menus** | plays its opening sequence and menus with sound and input | A scripted input sequence goes from launch to the last menu before gameplay in 10/10 runs; audio is audible and in sync by the checklist; a save written in one run is read in the next | Planned |
| **World** | loads into gameplay and keeps running | 10/10 runs enter gameplay and run 10 minutes with no crash, hang or early exit; streaming requests complete without error; memory stays inside the 16 GB profile | Planned |
| **Fidelity** | draws its 3D scenes as the console does | The scene checklist (geometry, textures, lighting, effects, HUD) passes against the reference set at the fixed capture points; no draw or dispatch is skipped or stubbed | Planned |
+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.
+1
View File
@@ -13,6 +13,7 @@ path = "src/main.rs"
bx-probe = { path = "../bx-probe" }
bx-telemetry = { path = "../bx-telemetry" }
dxbc-accc = { path = "../../../shader-transpiler/crates/dxbc-accc" }
gfx10-translate = { path = "../../../shader-transpiler/crates/gfx10-translate" }
# POSIX signals and process groups for `run` supervision.
libc = "=0.2.191"
+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);
}
}
+423 -28
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;
@@ -10,7 +11,7 @@ use std::fmt::Write as _;
use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use std::process::{Command, ExitCode, Stdio};
use std::time::{Duration, Instant};
use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus};
@@ -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,14 @@ 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 shader translate <vs> <ps> --out <dir> Translate a console VS/PS pair to HLSL (gfx10-translate)\n\
bx-cli shader coverage <dir> Rank what blocks translation across a folder of *_VS.* / *_PS.* shaders\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 +241,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 +332,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 +378,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 +401,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 +476,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 +489,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 +525,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 +576,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 +617,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 +639,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 +716,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 +778,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 +1180,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 +1195,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 +1209,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 +1256,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 +1288,7 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
inherit_env,
timeout,
backend,
gdk_libraries,
})
}
@@ -1450,6 +1606,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 +1617,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 =
@@ -1575,30 +1786,89 @@ fn cmd_run(args: &[String]) -> ExitCode {
None => diag("warning: Xbox drive G: not mapped: the executable has no parent directory"),
}
let mut cmd = if let Some(ref bname) = bottle {
let mut c = Command::new(&wine_wrapper);
c.args(["--bottle", bname])
.args(bottle_options(backend.as_deref()))
.arg(&abs_exe);
c
} else {
let _ = fs::create_dir_all(&resolved_prefix);
let mut c = Command::new(&wineloader);
c.arg(&abs_exe);
c
let guest_command = || {
let mut command = if let Some(ref bname) = bottle {
let mut command = Command::new(&wine_wrapper);
command
.args(["--bottle", bname])
.args(bottle_options(backend.as_deref()));
command
} else {
Command::new(&wineloader)
};
apply_host_env(&mut command, inherit_env);
if bottle.is_none() {
apply_prefix_env(&mut command, cx_root, &resolved_prefix, &wineloader);
}
command.env("WINEDEBUG", "-all");
command
};
apply_host_env(&mut cmd, inherit_env);
if bottle.is_none() {
apply_prefix_env(&mut cmd, cx_root, &resolved_prefix, &wineloader);
if staged_names.iter().any(|name| name == "bx_runtime_veh.dll") {
// This title reads the console profile before it calls any shim entry point.
// Publish the same profile as XSystemGetDeviceType while the prefix is locked.
let mode = if profile == "anaconda" {
"0x64"
} else {
"0x60"
};
let mut registry = guest_command();
registry
.args([
"reg.exe",
"add",
r"HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM",
"/v",
"ConsoleMode",
"/t",
"REG_DWORD",
"/d",
mode,
"/f",
])
.stdout(Stdio::null());
let active = active_time(started.elapsed(), supervise::suspended_time());
let remaining = match guest_time_left(timeout, active) {
Ok(remaining) => remaining,
Err(e) => {
diag(format_args!("timed out before setting ConsoleMode: {e}"));
return ExitCode::from(124);
}
};
match supervise::supervise(registry, remaining, supervise::received_signal) {
Ok(Outcome::Exited(status)) if status.success() => {
diag(format_args!("bx-cli: ConsoleMode={mode} profile={profile}"));
}
Ok(Outcome::Exited(status)) => {
diag(format_args!("warning: could not set ConsoleMode: {status}"));
}
Ok(outcome @ Outcome::Stopped(stop)) => {
let failed = stop_environment(
stop,
cx_root,
&environment_dir,
bottle.as_deref(),
inherit_env,
);
let code = outcome.exit_code();
return ExitCode::from(if failed { code.max(1) } else { code });
}
Err(e) => diag(format_args!("warning: could not set ConsoleMode: {e}")),
}
}
if bottle.is_none() {
let _ = fs::create_dir_all(&resolved_prefix);
}
let mut cmd = guest_command();
cmd.arg(&abs_exe);
cmd.env("ROSETTA_ADVERTISE_AVX", "1")
.env("WINEDLLOVERRIDES", SHIM_DLL_OVERRIDES)
.env("WINEPATH", &wine_shims_path)
.env("BX_PROFILE", &profile)
.env("WINEDEBUG", "-all");
.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() {
@@ -1722,6 +1992,85 @@ fn cmd_run(args: &[String]) -> ExitCode {
})
}
/// `bx-cli shader translate <vs> <ps> --out <dir>`: translates a console VS/PS pair (containers
/// or raw code blobs) with the gfx10-translate crate. Writes `<vs key>_<ps key>.vs.hlsl`,
/// `.ps.hlsl` and `.il` (the host pipeline's input layout and resources), keyed by FNV-1a of each
/// blob as the shim's shader cache expects. Compile the HLSL with the public DXC (vs_6_0/ps_6_0).
fn cmd_shader_translate(args: &[String]) -> ExitCode {
let (vs_path, ps_path, out) = match args {
[vs, ps, flag, out] if flag == "--out" => (vs, ps, out),
_ => {
eprintln!("usage: bx-cli shader translate <vs container> <ps container> --out <dir>");
return ExitCode::FAILURE;
}
};
let (vs, ps) = match (fs::read(vs_path), fs::read(ps_path)) {
(Ok(vs), Ok(ps)) => (vs, ps),
(Err(e), _) | (_, Err(e)) => {
eprintln!("error: cannot read the shaders: {e}");
return ExitCode::FAILURE;
}
};
let t = match gfx10_translate::translate_blobs(&vs, &ps) {
Ok(t) => t,
Err(e) => {
eprintln!("unsupported: {e}");
return ExitCode::FAILURE;
}
};
let key = format!(
"{}_{}",
gfx10_translate::translate::fnv1a(&vs),
gfx10_translate::translate::fnv1a(&ps)
);
let base = Path::new(out).join(&key);
let write = |ext: &str, text: &str| fs::write(base.with_extension(ext), text);
let written = fs::create_dir_all(out)
.and_then(|()| write("vs.hlsl", &t.vs_hlsl))
.and_then(|()| write("ps.hlsl", &t.ps_hlsl))
.and_then(|()| write("il", &t.layout));
match written {
Ok(()) => {
println!("{key}");
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("error: cannot write to {out}: {e}");
ExitCode::FAILURE
}
}
}
/// `bx-cli shader coverage <dir>`: how many of the console shaders in a local folder (`*_VS.*`,
/// `*_PS.*`) translate, and what blocks the rest, most frequent first.
fn cmd_shader_coverage(args: &[String]) -> ExitCode {
let [dir] = args else {
eprintln!("usage: bx-cli shader coverage <folder of *_VS.* / *_PS.* shaders>");
return ExitCode::FAILURE;
};
let cov = match gfx10_translate::coverage::scan(Path::new(dir)) {
Ok(c) => c,
Err(e) => {
eprintln!("error: cannot scan {dir}: {e}");
return ExitCode::FAILURE;
}
};
let pct = if cov.shaders == 0 {
0.0
} else {
100.0 * cov.translated as f64 / cov.shaders as f64
};
println!(
"shaders: {} translated: {} ({pct:.1}%)",
cov.shaders, cov.translated
);
println!("blockers (shaders stopped, reason):");
for (key, n) in cov.ranked().into_iter().take(40) {
println!(" {n:6} {key}");
}
ExitCode::SUCCESS
}
fn cmd_shader(path: &str) -> ExitCode {
let data = match fs::read(path) {
Ok(d) => d,
@@ -1808,6 +2157,10 @@ fn main() -> ExitCode {
"setup" => cmd_setup(&args[1..]),
"preflight" => cmd_preflight(),
"probe" if args.len() >= 2 => cmd_probe(&args[1]),
"shader" if args.len() >= 2 && args[1] == "translate" => {
cmd_shader_translate(&args[2..])
}
"shader" if args.len() >= 2 && args[1] == "coverage" => cmd_shader_coverage(&args[2..]),
"shader" if args.len() >= 2 => cmd_shader(&args[1]),
"trace" if args.len() >= 2 => cmd_trace(&args[1]),
"report" if args.len() >= 2 => cmd_report(&args[1..]),
@@ -2111,12 +2464,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"],
@@ -2592,6 +2949,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())),
+174
View File
@@ -0,0 +1,174 @@
#!/usr/bin/env python3
"""Generates shader-transpiler/crates/gfx10-translate/tests/llvm_vectors.txt: instruction
encodings and their canonical text from the public LLVM AMDGPU assembler (llvm-mc, gfx1030).
Each line is `<hex words> | <text>`. The decoder test decodes the words and requires the same
text, so the decoder is checked against an implementation independent of BetterXen.
usage: gen_llvm_vectors.py [--llvm-mc PATH] > shader-transpiler/crates/gfx10-translate/tests/llvm_vectors.txt
"""
import argparse
import os
import subprocess
# Every shape the translator handles, and common instructions of each format.
INSTRUCTIONS = """
s_add_u32 s0, s1, s2
s_add_u32 s3, s1, 0x12345678
s_or_b32 s0, s1, 7
s_and_b32 s4, s5, -1
s_xor_b32 s0, s1, s2
s_mul_i32 s0, s1, s2
s_sub_u32 s0, s1, 64
s_lshr_b32 s0, s1, 4
s_lshl_b32 s0, s1, 2
s_min_u32 s0, s1, s2
s_max_u32 s0, s1, s2
s_bfe_u32 s0, s1, 0x100000
s_mov_b32 s0, s1
s_mov_b32 s0, 0x3f800000
s_mov_b32 m0, s1
s_mov_b64 s[0:1], s[2:3]
s_mov_b64 s[0:1], exec
s_and_b64 exec, exec, s[2:3]
s_wqm_b64 exec, exec
s_brev_b32 s0, s1
s_swappc_b64 s[4:5], s[4:5]
s_movk_i32 s0, 0x1234
s_cmp_eq_u32 s0, s1
s_cbranch_scc0 4
s_endpgm
s_load_dwordx4 s[0:3], s[4:5], 0x10
s_load_dwordx8 s[8:15], s[4:5], 0x20
s_load_dwordx4 s[0:3], s[4:5], 0x0
s_buffer_load_dword s0, s[4:7], 0x0
s_buffer_load_dwordx2 s[0:1], s[4:7], 0x8
s_buffer_load_dwordx4 s[8:11], s[4:7], 0x10
s_buffer_load_dwordx8 s[8:15], s[4:7], 0x20
s_buffer_load_dwordx16 s[16:31], s[4:7], 0x40
v_mov_b32_e32 v0, v1
v_mov_b32_e32 v0, s2
v_mov_b32_e32 v0, 0x40490fdb
v_mov_b32_e32 v0, 1.0
v_mov_b32_e32 v0, -4.0
v_mov_b32_e32 v0, 0.15915494
v_mov_b32_e32 v0, 17
v_mov_b32_e32 v0, -3
v_add_f32_e32 v0, v1, v2
v_add_f32_e32 v0, 0.5, v1
v_mul_f32_e32 v0, 0x3e800000, v1
v_sub_f32_e32 v0, v1, v2
v_subrev_f32_e32 v0, v1, v2
v_max_f32_e32 v0, v1, v2
v_min_f32_e32 v0, v1, v2
v_fmac_f32_e32 v0, v1, v2
v_mul_legacy_f32_e32 v0, v1, v2
v_cvt_pkrtz_f16_f32_e32 v0, v1, v2
v_lshlrev_b32_e32 v0, 2, v1
v_lshrrev_b32_e32 v0, 16, v1
v_ashrrev_i32_e32 v0, 16, v1
v_and_b32_e32 v0, 0xff, v1
v_or_b32_e32 v0, v1, v2
v_xor_b32_e32 v0, v1, v2
v_sub_nc_u32_e32 v0, v1, v2
v_subrev_nc_u32_e32 v0, v1, v2
v_add_nc_u32_e32 v0, s2, v1
v_mul_u32_u24_e32 v0, v1, v2
v_min_u32_e32 v0, v1, v2
v_max_u32_e32 v0, v1, v2
v_rcp_f32_e32 v0, v1
v_rsq_f32_e32 v0, v1
v_sqrt_f32_e32 v0, v1
v_floor_f32_e32 v0, v1
v_fract_f32_e32 v0, v1
v_exp_f32_e32 v0, v1
v_log_f32_e32 v0, v1
v_trunc_f32_e32 v0, v1
v_rndne_f32_e32 v0, v1
v_ceil_f32_e32 v0, v1
v_cvt_f32_u32_e32 v0, v1
v_cvt_f32_i32_e32 v0, v1
v_cvt_i32_f32_e32 v0, v1
v_sin_f32_e32 v0, v1
v_cos_f32_e32 v0, v1
v_add_f32_e64 v0, v1, v2
v_mul_f32_e64 v0, -v1, v2
v_mul_f32_e64 v0, v1, -v2
v_mul_f32_e64 v0, -v1, |v2|
v_add_f32_e64 v0, v1, v2 clamp
v_mul_f32_e64 v0, v1, v2 mul:2
v_max_f32_e64 v0, v1, s2
v_sub_f32_e64 v0, v1, v2
v_rcp_f32_e64 v0, -v1
v_lshlrev_b32_e64 v0, s2, v1
v_mul_lo_u32 v0, v1, v2
v_mul_hi_u32 v0, v1, v2
v_fma_f32 v0, v1, v2, v3
v_fma_f32 v0, -v1, v2, 1.0
v_med3_f32 v0, v1, 0, 1.0
v_bfe_u32 v0, v1, 8, 8
v_cmp_lt_f32_e32 vcc_lo, v1, v2
v_cmpx_eq_u32_e32 v1, v2
v_cndmask_b32_e32 v0, v1, v2, vcc_lo
v_interp_p1_f32_e32 v2, v0, attr0.x
v_interp_p2_f32_e32 v2, v1, attr0.x
v_interp_p2_f32_e32 v3, v1, attr3.w
v_interp_mov_f32_e32 v0, p0, attr2.y
v_fma_mixlo_f16 v0, v1, v2, v3 op_sel_hi:[1,1,0]
v_fma_mixhi_f16 v0, v1, v2, v3 op_sel_hi:[1,1,1]
buffer_load_dword v0, v1, s[4:7], 0 idxen
buffer_load_dword v0, v1, s[4:7], 0 idxen offset:12
buffer_load_dwordx2 v[0:1], v2, s[4:7], 0 idxen
buffer_load_dwordx3 v[0:2], v3, s[4:7], 0 idxen offset:4
buffer_load_dwordx4 v[0:3], v4, s[8:11], 0 idxen
buffer_load_dword v0, v1, s[4:7], 0 offen
buffer_load_dword v0, off, s[4:7], s2 offset:16
tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_8_8_8_8_UNORM] idxen
tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] idxen offset:8
image_sample v[0:3], v[4:5], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
image_sample v0, v[4:5], s[8:15], s[16:19] dmask:0x8 dim:SQ_RSRC_IMG_2D
image_sample_lz v[0:1], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D
exp pos0, v0, v1, v2, v3 done
exp mrt0, v0, v1, v2, v3 done vm
exp mrt0, v0, off, off, off
exp param3, v4, v5, v6, v7
exp mrt0, v0, v0, v1, v1 done compr vm
v_fmaak_f32 v0, v1, v2, 0x3f800000
v_fmamk_f32 v0, v1, 0x40000000, v2
gfx1010 v_mac_f32_e32 v0, v1, v2
gfx1010 v_mac_f32_e64 v0, -v1, v2
gfx1010 v_mad_f32 v0, v1, v2, v3
gfx1010 v_madak_f32 v0, v1, v2, 0x3f800000
gfx1010 v_madmk_f32 v0, v1, 0x40000000, v2
"""
# Lines starting with a target name are assembled for that target: the console compiler emits a
# few GFX10.1 instructions (v_mac_f32, v_mad_f32, v_madak/madmk_f32) that LLVM knows only there.
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc"))
a = ap.parse_args()
lines = [l.strip() for l in INSTRUCTIONS.strip().splitlines() if l.strip()]
version = subprocess.run([a.llvm_mc, "--version"], capture_output=True, text=True).stdout.split("\n")
version = next((v.strip() for v in version if "version" in v.lower()), "unknown")
print("# @generated by scripts/console-shader/gen_llvm_vectors.py from %s (gfx1030)." % version)
print("# <instruction words> | <llvm-mc's text for them>")
for line in lines:
mcpu = "gfx1030"
if line.startswith("gfx"):
mcpu, line = line.split(" ", 1)
r = subprocess.run([a.llvm_mc, "-arch=amdgcn", "-mcpu=" + mcpu, "-show-encoding"], input=line,
capture_output=True, text=True)
enc = next(l for l in r.stdout.splitlines() if "encoding:" in l)
data = bytes(int(b, 16) for b in enc.split("encoding:")[1].strip().strip("[]").split(","))
words = " ".join("%08x" % int.from_bytes(data[i:i + 4], "little") for i in range(0, len(data), 4))
# The canonical text is what the disassembler prints for these bytes.
d = subprocess.run([a.llvm_mc, "--disassemble", "-arch=amdgcn", "-mcpu=" + mcpu],
input=" ".join("0x%02x" % b for b in data), capture_output=True, text=True)
text = next(l.strip() for l in d.stdout.splitlines() if l.strip() and not l.strip().startswith("."))
print("%s | %s" % (words, text))
if __name__ == "__main__":
main()
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""Generates shader-transpiler/crates/gfx10-translate/src/opcodes.rs: the GFX10.3 (gfx1030)
instruction names for every opcode value of every encoding format the decoder handles.
The names come from the public LLVM AMDGPU disassembler (llvm-mc, Apache-2.0 WITH
LLVM-exception): for each format, an instruction word is built with each opcode value and
fixed, valid operand fields, and llvm-mc names it or rejects it. Only the resulting facts (opcode
number -> mnemonic) are committed; LLVM itself is not.
usage: gen_opcodes.py [--llvm-mc PATH] > shader-transpiler/crates/gfx10-translate/src/opcodes.rs
"""
import argparse
import concurrent.futures
import os
import subprocess
import sys
# (name, opcode bits, word builder, mask of word 0's format and opcode bits) per format.
# Builders place `op` in the format's opcode field; the other fields hold valid registers.
# Layouts: AMD "RDNA 2" instruction set reference.
FORMATS = [
# SOP2 opcodes from 0x60 and VOP2 opcodes from 0x3E are the prefixes of other formats.
("SOP2", 7, lambda op: [0x80000000 | (op << 23) | (2 << 8) | 1] if op < 0x60 else None, 0xFF800000),
("SOPK", 5, lambda op: [[0xB0000000 | (op << 23) | 0x10], [0xB0000000 | (op << 23) | 0x1801, 0x1]], 0xFF800000),
("SOP1", 8, lambda op: [0xBE800000 | (op << 8) | 2], 0xFF80FF00),
("SOPC", 7, lambda op: [0xBF000000 | (op << 16) | (2 << 8) | 1], 0xFFFF0000),
("SOPP", 7, lambda op: [0xBF800000 | (op << 16)], 0xFFFF0000),
("SMEM", 8, lambda op: [0xF4000000 | (op << 18) | 2, 0xFA000010], 0xFFFC0000),
# v_madmk/madak/fmamk/fmaak carry a literal constant after the instruction word.
("VOP2", 6, lambda op: [[(op << 25) | (2 << 9) | 0x101], [(op << 25) | (2 << 9) | 0x101, 0x3F800000]] if op < 0x3E else None,
0xFE000000),
("VOP1", 8, lambda op: [0x7E000000 | (op << 9) | 0x101], 0xFE01FE00),
("VOPC", 8, lambda op: [0x7C000000 | (op << 17) | (2 << 9) | 0x101], 0xFFFE0000),
("VOP3", 10, lambda op: [0xD4000000 | (op << 16), (0x103 << 18) | (0x102 << 9) | 0x101], 0xFFFF0000),
("VOP3P", 7, lambda op: [0xCC000000 | (op << 16), (0x103 << 18) | (0x102 << 9) | 0x101], 0xFC7F0000),
("VINTRP", 2, lambda op: [0xC8000000 | (op << 16) | 1], 0xFC030000),
("DS", 8, lambda op: [[0xD8000000 | (op << 18), w] for w in (0x00000201, 0x00000001, 0x00030201)], 0xFFFC0000),
("MUBUF", 7, lambda op: [0xE0000000 | ((op & 0x7F) << 18) | 0x2000, 0x80010001], 0xFDFC0000),
("MTBUF", 4, lambda op: [0xE8000000 | (op & 7) << 16 | (22 << 19) | 0x2000, 0x80010001 | ((op >> 3) << 21)], 0xFC070000),
("MIMG", 8, lambda op: [[0xF0000000 | ((op & 0x7F) << 18) | ((op >> 7) << 0) | (1 << 3) | (0xF << 8), w]
for w in (0x00820004, 0x00020004)], 0xFDFC0001),
("FLAT", 7, lambda op: [0xDC000000 | (op << 18), 0x007D0001], 0xFDFCC000),
("GLOBAL", 7, lambda op: [0xDC008000 | (op << 18), 0x007D0001], 0xFDFCC000),
]
def name_of(llvm_mc, words, mask, mcpu):
"""The mnemonic llvm-mc gives `words`, or None. A name counts only when llvm-mc reports no
invalid encoding and its first instruction is as long as `words` with the same format and
opcode bits (`mask`): for an invalid opcode, llvm-mc skips a word and decodes the next one as
an instruction of its own. Operand fields may be re-encoded, so they are not compared."""
data = b"".join(w.to_bytes(4, "little") for w in words)
text = " ".join("0x%02x" % b for b in data)
r = subprocess.run([llvm_mc, "--disassemble", "-show-encoding", "-arch=amdgcn", "-mcpu=" + mcpu], input=text,
capture_output=True, text=True)
if "invalid instruction encoding" in r.stderr:
return None
for line in r.stdout.splitlines():
if "encoding:" not in line:
continue
asm, enc = line.split("; encoding:")
encoded = bytes(int(b, 16) for b in enc.strip().strip("[]").split(","))
same = len(encoded) == len(data) and (int.from_bytes(encoded[:4], "little") & mask) == (words[0] & mask)
return asm.split()[0] if same else None
return None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc"))
a = ap.parse_args()
version = subprocess.run([a.llvm_mc, "--version"], capture_output=True, text=True).stdout.split("\n")
version = next((v.strip() for v in version if "version" in v.lower()), "unknown")
jobs = [(fmt, op, build(op), mask) for fmt, bits, build, mask in FORMATS for op in range(1 << bits)]
def first_name(job):
# A builder gives one word list, or several variants of the operand fields to try in turn
# (llvm-mc rejects some opcodes unless their unused fields are zero).
if job[2] is None:
return None
variants = job[2] if isinstance(job[2][0], list) else [job[2]]
# gfx1030 first; the console compiler also emits a few GFX10.1 instructions that LLVM
# knows only for gfx1010 (v_mac_f32), so gaps are filled from there.
for mcpu in ("gfx1030", "gfx1010"):
for v in variants:
n = name_of(a.llvm_mc, v, job[3], mcpu)
if n:
return n
return None
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
names = list(pool.map(first_name, jobs))
out = ["// @generated by scripts/console-shader/gen_opcodes.py from %s (gfx1030, gaps from gfx1010)." % version,
"// Do not edit. Facts only: opcode number -> mnemonic, per encoding format, as named by the",
"// public LLVM AMDGPU disassembler (Apache-2.0 WITH LLVM-exception).", "",
"/// (opcode, mnemonic) pairs of one encoding format, sorted by opcode.", "pub type Table = &'static [(u16, &'static str)];", ""]
for fmt, _, _, _ in FORMATS:
rows = [(op, n) for (f, op, _, _), n in zip(jobs, names) if f == fmt and n]
out.append("pub static %s: Table = &[" % fmt)
for op, n in rows:
out.append(" (%d, \"%s\")," % (op, n))
out.append("];")
out.append("")
print("%s: %d opcodes" % (fmt, len(rows)), file=sys.stderr)
# MTBUF unified buffer formats (word 0 bits 25:19), named by the disassembler as format:[NAME].
def format_name(value):
words = [0xE8000000 | (value << 19) | (3 << 16) | 0x2000, 0x80000000]
text = " ".join("0x%02x" % b for w in words for b in w.to_bytes(4, "little"))
r = subprocess.run([a.llvm_mc, "--disassemble", "-arch=amdgcn", "-mcpu=gfx1030"], input=text,
capture_output=True, text=True)
if "invalid instruction encoding" in r.stderr or "format:[" not in r.stdout:
return None
return r.stdout.split("format:[")[1].split("]")[0]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
formats = list(pool.map(format_name, range(128)))
out.append("/// MTBUF unified buffer formats: (value, name), as `format:[NAME]` prints them.")
out.append("pub static BUF_FORMATS: Table = &[")
for value, name in enumerate(formats):
if name and not name.isdigit():
out.append(" (%d, \"%s\")," % (value, name))
out.append("];")
out.append("")
print("BUF_FORMATS: %d" % sum(1 for f in formats if f and not f.isdigit()), file=sys.stderr)
sys.stdout.write("\n".join(out))
if __name__ == "__main__":
main()
@@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""Generates the translator's golden files: small VS/PS pairs written in GFX10.3 assembly,
assembled by the public LLVM assembler (llvm-mc), and translated by the Python prototype
(translate.py, the reference). The Rust translator must produce the same HLSL and layout.
Writes shader-transpiler/crates/gfx10-translate/tests/goldens/<case>.{vs,ps}.hex (instruction
words), .vs.hlsl, .ps.hlsl and .il. The programs are BetterXen's own, written for these tests.
usage: gen_translate_goldens.py [--llvm-mc PATH]
"""
import argparse
import os
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import translate # noqa: E402 (the prototype)
OUT = os.path.join(HERE, "..", "..", "shader-transpiler", "crates", "gfx10-translate", "tests", "goldens")
# VS reading a fetch-subroutine input and a constant buffer; PS sampling a texture.
TEXTURED_VS = """
s_swappc_b64 s[4:5], s[4:5]
s_load_dwordx4 s[12:15], s[8:9], 0x0
s_waitcnt lgkmcnt(0)
s_buffer_load_dwordx4 s[16:19], s[12:15], 0x0
s_waitcnt lgkmcnt(0)
v_mul_f32_e32 v0, s16, v4
v_fma_f32 v1, s17, v5, s19
v_mov_b32_e32 v2, 0
v_mov_b32_e32 v3, 1.0
exp pos0, v0, v1, v2, v3 done
exp param0, v6, v7, v2, v3
s_endpgm
"""
TEXTURED_PS = """
s_mov_b64 s[10:11], exec
s_wqm_b64 exec, exec
s_mov_b32 m0, s2
v_interp_p1_f32_e32 v2, v0, attr0.x
v_interp_p2_f32_e32 v2, v1, attr0.x
v_interp_p1_f32_e32 v3, v0, attr0.y
v_interp_p2_f32_e32 v3, v1, attr0.y
s_load_dwordx8 s[0:7], s[8:9], 0x20
s_load_dwordx4 s[12:15], s[20:21], 0x0
s_and_b64 exec, exec, s[10:11]
s_waitcnt lgkmcnt(0)
image_sample v[4:7], v[2:3], s[0:7], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D
s_waitcnt vmcnt(0)
v_mul_f32_e32 v4, v4, v4
exp mrt0, v4, v5, v6, v7 done vm
s_endpgm
"""
# The ALU families and single rules, in a PS.
ALU_VS = """
s_swappc_b64 s[4:5], s[4:5]
exp pos0, v4, v5, v6, v7 done
exp param0, v8, v9, v10, v11
s_endpgm
"""
ALU_PS = """
v_interp_p1_f32_e32 v2, v0, attr0.x
v_interp_p2_f32_e32 v2, v1, attr0.x
v_interp_mov_f32_e32 v3, p0, attr0.y
s_movk_i32 s20, 0x1234
s_mov_b32 s21, 0x3f800000
s_lshl_b32 s22, s20, 2
s_or_b32 s23, s22, 7
s_and_b32 s23, s23, s21
s_xor_b32 s23, s23, s20
s_mul_i32 s23, s23, s22
s_add_u32 s23, s23, 64
s_sub_u32 s23, s23, s20
s_lshr_b32 s23, s23, 4
s_min_u32 s24, s23, s22
s_max_u32 s24, s24, s20
s_brev_b32 s25, s24
s_bfe_u32 s26, s25, 0x100000
s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 4), 3
v_lshlrev_b32_e32 v4, 2, v2
v_lshrrev_b32_e32 v4, 16, v4
v_ashrrev_i32_e32 v4, 1, v4
v_and_b32_e32 v4, 0xff, v4
v_or_b32_e32 v4, v4, v3
v_xor_b32_e32 v4, v4, v2
v_sub_nc_u32_e32 v4, v4, v3
v_subrev_nc_u32_e32 v4, v4, v2
v_mul_u32_u24_e32 v4, v4, v3
v_min_u32_e32 v4, v4, v2
v_max_u32_e32 v4, v4, v3
v_mul_lo_u32 v4, v4, v2
v_mul_hi_u32 v4, v4, s25
v_lshlrev_b32_e64 v4, s24, v4
v_add_f32_e32 v5, 0.5, v2
v_mul_f32_e32 v5, 0x3e800000, v5
v_sub_f32_e32 v5, v5, v3
v_subrev_f32_e32 v5, v5, v3
v_max_f32_e32 v5, v5, v2
v_min_f32_e32 v5, v5, v3
v_add_f32_e64 v5, v5, -v2
v_mul_f32_e64 v5, -v5, v3
v_sub_f32_e64 v5, v5, v2
v_max_f32_e64 v5, v5, s21
v_fmac_f32_e32 v5, v2, v3
v_rcp_f32_e32 v6, v5
v_rsq_f32_e32 v6, v6
v_sqrt_f32_e32 v6, v6
v_floor_f32_e32 v6, v6
v_fract_f32_e32 v6, v6
v_exp_f32_e32 v6, v6
v_log_f32_e32 v6, v6
v_trunc_f32_e32 v6, v6
v_rndne_f32_e32 v6, v6
v_ceil_f32_e32 v6, v6
v_sin_f32_e32 v6, v6
v_cos_f32_e32 v6, v6
v_rcp_f32_e64 v6, -v6
v_cvt_f32_u32_e32 v7, v4
v_cvt_f32_i32_e32 v7, v4
v_cvt_i32_f32_e32 v8, v7
v_med3_f32 v7, v7, 0, 1.0
v_fma_f32 v7, -v7, v2, 1.0
v_mul_legacy_f32_e32 v7, v7, v3
v_cvt_pkrtz_f16_f32_e32 v9, v7, v6
v_fma_mixlo_f16 v10, v9, v2, v3 op_sel_hi:[1,0,0]
v_fma_mixhi_f16 v10, v9, v9, v10 op_sel_hi:[1,1,1]
v_mov_b32_e32 v11, s23
v_add_nc_u32_e32 v11, v11, v8
exp mrt0, v9, v9, v10, v10 done compr vm
s_endpgm
"""
# A VS without the fetch subroutine: vertex buffers through s[0:1], typed buffer loads, and an
# indexed load from a buffer bound through the root table.
BUFFERS_VS = """
s_load_dwordx4 s[12:15], s[0:1], 0x0
s_load_dwordx4 s[16:19], s[0:1], 0x10
s_load_dwordx4 s[20:23], s[8:9], 0x20
v_add_nc_u32_e32 v1, s2, v0
s_waitcnt lgkmcnt(0)
buffer_load_dwordx2 v[2:3], v1, s[12:15], 0 idxen
tbuffer_load_format_xyzw v[4:7], v1, s[16:19], 0 format:[BUF_FMT_8_8_8_8_UNORM] idxen offset:8
buffer_load_dwordx3 v[8:10], v1, s[12:15], 0 idxen offset:8
buffer_load_dwordx4 v[12:15], v0, s[20:23], 0 idxen
s_waitcnt vmcnt(0)
v_mov_b32_e32 v11, 1.0
exp pos0, v2, v3, v8, v11 done
exp param0, v4, v5, v6, v7
exp param1, v12, v13, v14, v15
s_endpgm
"""
BUFFERS_PS = """
v_interp_mov_f32_e32 v2, p0, attr1.x
v_interp_mov_f32_e32 v3, p0, attr1.w
v_interp_p1_f32_e32 v4, v0, attr0.z
v_interp_p2_f32_e32 v4, v1, attr0.z
exp mrt0, v2, v3, v4, off done vm
s_endpgm
"""
CASES = [("textured", TEXTURED_VS, TEXTURED_PS), ("alu", ALU_VS, ALU_PS), ("buffers", BUFFERS_VS, BUFFERS_PS)]
def assemble(llvm_mc, text):
r = subprocess.run([llvm_mc, "-arch=amdgcn", "-mcpu=gfx1030", "-show-encoding"], input=text,
capture_output=True, text=True)
if r.returncode != 0:
sys.exit("llvm-mc failed:\n" + r.stderr)
data = bytearray()
for line in r.stdout.splitlines():
if "encoding:" in line:
data += bytes(int(b, 16) for b in line.split("encoding:")[1].strip().strip("[]").split(","))
return bytes(data)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc"))
a = ap.parse_args()
translate.LLVM_MC = a.llvm_mc
os.makedirs(OUT, exist_ok=True)
for name, vs_asm, ps_asm in CASES:
vs, ps = assemble(a.llvm_mc, vs_asm), assemble(a.llvm_mc, ps_asm)
vt, pt = translate.Translator("vs"), translate.Translator("ps")
vt.run(translate.disassemble(vs))
pt.run(translate.disassemble(ps))
vs_src, params = translate.build_vs(vt)
ps_src = translate.build_ps(pt, params)
il = ""
if vt.fetch_call:
il += "FETCH %d\n" % (max(vt.fetch_attrs) + 1 if vt.fetch_attrs else 0)
for sem, fmt, slot, off, n, kind in vt.inputs:
il += "ATTR %d %d %d %d\n" % (sem, translate.DXGI[fmt], slot, off)
for cb in sorted(vt.cbs | pt.cbs):
il += "USE CB %d\n" % cb
for tex in sorted(vt.textures | pt.textures):
il += "USE TEX %d\n" % tex
base = os.path.join(OUT, name)
for suffix, blob in ((".vs.hex", vs), (".ps.hex", ps)):
words = [int.from_bytes(blob[i:i + 4], "little") for i in range(0, len(blob), 4)]
open(base + suffix, "w").write(" ".join("%08x" % w for w in words) + "\n")
open(base + ".vs.hlsl", "w").write(vs_src)
open(base + ".ps.hlsl", "w").write(ps_src)
open(base + ".il", "w").write(il)
print("%s: VS %d words, PS %d words" % (name, len(vs) // 4, len(ps) // 4))
if __name__ == "__main__":
main()
+930
View File
@@ -0,0 +1,930 @@
#!/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.
Reference implementation for shader-transpiler/crates/gfx10-translate, which replaces it: the
crate's golden tests compare against this script's output (see that crate's README).
Model (inferences from the console compiler's listings and the target build's code, AGENTS.md
section 6):
* 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)
@@ -0,0 +1,10 @@
[package]
name = "gfx10-translate"
description = "BetterXen's GFX10.3 (RDNA 2) console shader translator: decoder, HLSL translation, coverage"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
@@ -0,0 +1,48 @@
# gfx10-translate
BetterXen's own translator for console shaders (roadmap, Picture stage): GFX10.3 (RDNA 2) machine code to HLSL, which the public DXC compiles to DXIL for D3DMetal. It is mechanical: one rule per instruction, registers as variables. Control flow is not translated yet.
| Module | Job |
| --- | --- |
| `container` | The stage code inside a console shader container (`XBCH` → `FSSM` → stage record). |
| `inflate` | zlib, ported from BetterXen's own `shims/xcrdapi/zlib_inflate.cpp` (no third-party dependency). |
| `decode` | Instruction words → instructions with structured operands, printed as LLVM-style text. |
| `opcodes` | **Generated.** Opcode → mnemonic per encoding format, and the buffer formats. |
| `translate` | Instructions → HLSL and the host input layout, through family tables and specific rules. |
| `coverage` | What blocks translation across a local folder of shaders, ranked. |
## Use
```sh
bx-cli shader coverage <folder> # *_VS.* / *_PS.* console shaders, on your machine
bx-cli shader translate <vs> <ps> --out <dir> # <vs key>_<ps key>.vs.hlsl / .ps.hlsl / .il
cargo run -p gfx10-translate --example listing -- <shader> # decoded listing
cargo run -p gfx10-translate --example why -- PS <shader>... # why each shader is refused
```
Game shaders stay on your machine: never commit a shader, a listing, or anything else from the target build (AGENTS.md Section 6).
## Adding an instruction
1. Run `bx-cli shader coverage` on your shaders and take the top blocker no open pull request covers (AGENTS.md Section 0, Step 3).
2. If it fits a family (`VOP2_UINT`, `VOP2_FLOAT`, `VOP1_FLOAT`, `SOP2_UINT` in `src/translate.rs`), add one row. Otherwise add an arm in `Translator::step`.
3. Write the expected HLSL from the instruction's definition, not from your code, and add a test in `tests/translate.rs` with the instruction words from `llvm-mc -show-encoding`.
4. Check the instruction's semantics against the console compiler's listing for a shader of our own (`shader-transpiler/corpus/`, source rank 2) where the ISA reference is unclear.
## Where the facts come from
- **Opcode names and buffer formats:** `scripts/console-shader/gen_opcodes.py` asks the public LLVM disassembler (`llvm-mc`, Apache-2.0 WITH LLVM-exception) to name every opcode value of every format: gfx1030 first, gaps filled from gfx1010. The console compiler also emits a few GFX10.1 instructions (`v_mac_f32`, `v_mad_f32`, `v_madak_f32`, `v_madmk_f32`) that LLVM knows only there. Only the facts are committed; LLVM is not.
- **Encoding layouts:** AMD's public RDNA 2 instruction set reference. `tests/llvm_vectors.txt` (from `scripts/console-shader/gen_llvm_vectors.py`) holds 127 instructions encoded and printed by `llvm-mc`. The decoder must print the same text for each.
- **Translation rules:** a port of the Python prototype `scripts/console-shader/translate.py`, kept as the reference. `tests/goldens/` holds small shaders of our own, assembled by `llvm-mc` and translated by the prototype (`scripts/console-shader/gen_translate_goldens.py`). The Rust output must be identical.
- **Container layout and the shader model:** inferences from the target build (module comments), AGENTS.md Section 6.
## Differences from the prototype
- `s_movk_i32` sign-extends its 16-bit immediate. The prototype read it unsigned.
- Output modifiers (`clamp`, `mul:`/`div:`, `op_sel`, `abs`) are refused on every VOP3 instruction, not only on `_e64` forms.
- `v_fma_mix*` with `op_sel_hi` all zero (all 32-bit sources) is accepted. The prototype refused it.
- **New rules:**
- the multiply-add family (`v_mac_f32`, `v_mad_f32`, `v_madak/madmk_f32`, `v_fmaak/fmamk_f32`);
- 32-lane execution-mask bookkeeping (`s_mov_b32 sN, exec_lo`, `s_wqm_b32`, `s_and_b32 exec_lo, exec_lo, sN`);
- compressed exports with a disabled half.
- **Cache keys use standard FNV-1a 64.** The prototype's offset basis is missing its last digit (`1469598103934665603`), so its keys differ. The shim's cache lookup must use the same function as this crate when translation moves into `bx_shader_bridge.dll`.
@@ -0,0 +1,26 @@
//! Prints the decoded listing of a shader: word index, words, and LLVM-style text.
//! usage: cargo run -p gfx10-translate --example listing -- <shader>
use gfx10_translate::container::code_words;
use gfx10_translate::decode::decode_one;
fn main() {
let path = std::env::args().nth(1).expect("usage: listing <shader>");
let words = code_words(&std::fs::read(&path).expect("read")).expect("container");
let mut at = 0;
while at < words.len() {
match decode_one(&words, at) {
Ok(inst) => {
let hex: Vec<String> = inst.words.iter().map(|w| format!("{w:08x}")).collect();
println!("{at:5} {:<26} {inst}", hex.join(" "));
at += inst.words.len();
if inst.name == "s_endpgm" {
break;
}
}
Err(e) => {
println!("{at:5} {:08x} error: {e}", words[at]);
break;
}
}
}
}
@@ -0,0 +1,48 @@
//! Prints why each given shader does not translate, with the instruction words involved.
//! usage: cargo run -p gfx10-translate --example why -- <VS|PS> <shader>...
use gfx10_translate::container::code_words;
use gfx10_translate::decode::{DecodeError, decode};
use gfx10_translate::translate::{Stage, Translator};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let stage = if args.first().map(String::as_str) == Some("VS") {
Stage::Vertex
} else {
Stage::Pixel
};
for path in &args[1..] {
let Ok(blob) = std::fs::read(path) else {
continue;
};
let words = match code_words(&blob) {
Ok(w) => w,
Err(e) => {
println!("{path}: {e}");
continue;
}
};
match decode(&words) {
Err(e) => {
let at = match e {
DecodeError::UnknownOpcode { at, .. }
| DecodeError::UnknownEncoding { at, .. }
| DecodeError::Truncated { at } => at,
DecodeError::NoEndProgram => 0,
};
let around: Vec<String> = words
.iter()
.skip(at)
.take(3)
.map(|w| format!("{w:08x}"))
.collect();
println!("{path}: {e}: {}", around.join(" "));
}
Ok(insts) => {
if let Err(e) = Translator::new(stage).run(&insts) {
println!("{path}: {e}");
}
}
}
}
}
@@ -0,0 +1,185 @@
//! The GPU code of one stage from a console shader container.
//!
//! A console 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 size. The code starts with 12-byte header records (a VOP3 word whose top half is 0xD580,
//! `v_nop` with a literal) before the first instruction.
//!
//! These are inferences from containers of the project-authorized target build (AGENTS.md
//! section 6), checked by the synthetic container in the tests below.
use crate::inflate::zlib_inflate;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContainerError {
NoXbch,
BadXbch(&'static str),
NoStageRecord,
BadCode(&'static str),
}
impl fmt::Display for ContainerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoXbch => write!(f, "container has no XBCH record"),
Self::BadXbch(why) => write!(f, "XBCH record: {why}"),
Self::NoStageRecord => write!(f, "FSSM block has no stage record"),
Self::BadCode(why) => write!(f, "stage code: {why}"),
}
}
}
impl std::error::Error for ContainerError {}
const HEADER_RECORD_TOP: u32 = 0xD580;
const FILLER: u64 = 0xDEAD_BEEF_DEAD_BEEF;
const MAX_FSSM: usize = 64 << 20;
fn u32_at(b: &[u8], at: usize) -> Option<u32> {
Some(u32::from_le_bytes(b.get(at..at + 4)?.try_into().ok()?))
}
fn u64_at(b: &[u8], at: usize) -> Option<u64> {
Some(u64::from_le_bytes(b.get(at..at + 8)?.try_into().ok()?))
}
/// The stage code inside a console container, header records included.
pub fn container_code(blob: &[u8]) -> Result<Vec<u8>, ContainerError> {
let at = blob
.windows(4)
.position(|w| w == b"XBCH")
.ok_or(ContainerError::NoXbch)?;
let csize = u64_at(blob, at + 8).ok_or(ContainerError::BadXbch("truncated header"))? as usize;
let usize_ = u64_at(blob, at + 16).ok_or(ContainerError::BadXbch("truncated header"))? as usize;
let stream = blob
.get(at + 24..at.saturating_add(24).saturating_add(csize))
.ok_or(ContainerError::BadXbch("compressed size past the end"))?;
let fssm = zlib_inflate(stream, usize_.min(MAX_FSSM))
.map_err(|_| ContainerError::BadXbch("zlib stream"))?;
if fssm.len() != usize_ || fssm.get(..4) != Some(b"FSSM") {
return Err(ContainerError::BadXbch("does not inflate to an FSSM block"));
}
const BASE: usize = 16;
let record = (0x18..0x78)
.step_by(8)
.filter_map(|slot| u64_at(&fssm, slot))
.find(|&v| v != FILLER)
.ok_or(ContainerError::NoStageRecord)? as usize
+ BASE;
let offset = u64_at(&fssm, record).ok_or(ContainerError::NoStageRecord)? as usize;
let size = u64_at(&fssm, record + 8).ok_or(ContainerError::NoStageRecord)? as usize;
let code = fssm
.get(BASE + offset..BASE + offset + size)
.ok_or(ContainerError::BadCode("outside the FSSM block"))?;
if code.len() < 12 || u32_at(code, 0).map(|w| w >> 16) != Some(HEADER_RECORD_TOP) {
return Err(ContainerError::BadCode(
"does not start with the expected header records",
));
}
Ok(code.to_vec())
}
/// The instruction words of a stage: from a console container (`DXBC` magic) or a raw code blob,
/// with the leading 12-byte header records skipped.
pub fn code_words(blob: &[u8]) -> Result<Vec<u32>, ContainerError> {
let code = if blob.get(..4) == Some(b"DXBC") {
container_code(blob)?
} else {
blob.to_vec()
};
let mut at = 0;
while at + 12 <= code.len() && u32_at(&code, at).map(|w| w >> 16) == Some(HEADER_RECORD_TOP) {
at += 12;
}
Ok(code[at..]
.chunks_exact(4)
.map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
.collect())
}
#[cfg(test)]
mod tests {
use super::*;
fn adler32(data: &[u8]) -> u32 {
let (mut a, mut b) = (1u32, 0u32);
for &byte in data {
a = (a + u32::from(byte)) % 65521;
b = (b + a) % 65521;
}
(b << 16) | a
}
/// zlib stream with one stored block (no compression), built by hand.
fn stored(data: &[u8]) -> Vec<u8> {
let len = data.len() as u16;
let mut s = vec![0x78, 0x01, 0x01];
s.extend_from_slice(&len.to_le_bytes());
s.extend_from_slice(&(!len).to_le_bytes());
s.extend_from_slice(data);
s.extend_from_slice(&adler32(data).to_be_bytes());
s
}
/// A container laid out as the module comment describes: one header record, then two
/// instruction words, the stage record in slot 0x30.
fn container(code_words_after_header: &[u32]) -> Vec<u8> {
let mut code = Vec::new();
code.extend_from_slice(&0xD580_0000u32.to_le_bytes());
code.extend_from_slice(&[0u8; 8]);
for w in code_words_after_header {
code.extend_from_slice(&w.to_le_bytes());
}
let mut fssm = vec![0u8; 0x100];
fssm[..4].copy_from_slice(b"FSSM");
for slot in (0x18..0x78).step_by(8) {
fssm[slot..slot + 8].copy_from_slice(&FILLER.to_le_bytes());
}
let record = 0x80usize; // relative to byte 16
fssm[0x30..0x38].copy_from_slice(&(record as u64).to_le_bytes());
let code_offset = 0xA0u64;
fssm[16 + record..16 + record + 8].copy_from_slice(&code_offset.to_le_bytes());
fssm[16 + record + 8..16 + record + 16].copy_from_slice(&(code.len() as u64).to_le_bytes());
fssm.resize(16 + code_offset as usize, 0);
fssm.extend_from_slice(&code);
let stream = stored(&fssm);
let mut blob = b"DXBC".to_vec();
blob.extend_from_slice(&[0u8; 28]);
blob.extend_from_slice(b"XBCH");
blob.extend_from_slice(&1u32.to_le_bytes());
blob.extend_from_slice(&(stream.len() as u64).to_le_bytes());
blob.extend_from_slice(&(fssm.len() as u64).to_le_bytes());
blob.extend_from_slice(&stream);
blob
}
#[test]
fn finds_the_stage_code_and_skips_header_records() {
let blob = container(&[0xBF81_0000, 0x1234_5678]);
assert_eq!(code_words(&blob).unwrap(), vec![0xBF81_0000, 0x1234_5678]);
}
#[test]
fn raw_code_blobs_pass_through() {
let mut raw = 0xD580_0000u32.to_le_bytes().to_vec();
raw.extend_from_slice(&[0u8; 8]);
raw.extend_from_slice(&0xBF81_0000u32.to_le_bytes());
assert_eq!(code_words(&raw).unwrap(), vec![0xBF81_0000]);
}
#[test]
fn reports_what_is_missing() {
assert_eq!(
code_words(b"DXBC without a record"),
Err(ContainerError::NoXbch)
);
let mut blob = container(&[0xBF81_0000]);
let at = blob.windows(4).position(|w| w == b"XBCH").unwrap();
blob[at + 24] = 0; // break the zlib header
assert!(matches!(code_words(&blob), Err(ContainerError::BadXbch(_))));
}
}
@@ -0,0 +1,117 @@
//! Translator coverage over a local folder of console shaders.
//!
//! Each file is one stage: a console container or a raw code blob, named `*_VS.*` or `*_PS.*`
//! (other files are skipped). Every shader is decoded and translated on its own; the first
//! reason it is refused counts as its blocker. The ranked list says which instruction or feature
//! to add next. Shaders come from a collaborator's own runs and stay on their machine.
use crate::container::code_words;
use crate::decode::decode;
use crate::translate::{Stage, Translator};
use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::path::Path;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Coverage {
pub shaders: usize,
pub translated: usize,
/// Blocker -> shaders it stops.
pub blockers: BTreeMap<String, usize>,
}
impl Coverage {
/// Blockers, most frequent first.
pub fn ranked(&self) -> Vec<(&str, usize)> {
let mut v: Vec<(&str, usize)> = self
.blockers
.iter()
.map(|(k, n)| (k.as_str(), *n))
.collect();
v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
v
}
}
/// The blocker key of a refusal: the instruction name when one was refused, else the reason
/// with register numbers and constants folded so similar cases count together.
pub fn blocker_key(reason: &str) -> String {
if let Some(rest) = reason.strip_prefix("instruction '") {
return rest.split([' ', '\'']).next().unwrap_or(rest).to_string();
}
let mut out = String::new();
let mut chars = reason.chars().peekable();
while let Some(c) = chars.next() {
if c.is_ascii_digit() {
while chars.peek().is_some_and(|d| d.is_ascii_alphanumeric()) {
chars.next();
}
out.push('#');
} else {
out.push(c);
}
}
out.chars().take(80).collect()
}
/// Why one stage does not translate, or `None` when it does.
pub fn stage_blocker(blob: &[u8], stage: Stage) -> Option<String> {
let words = match code_words(blob) {
Ok(w) => w,
Err(e) => return Some(format!("container: {e}")),
};
let insts = match decode(&words) {
Ok(i) => i,
Err(e) => return Some(blocker_key(&format!("decode: {e}"))),
};
let mut t = Translator::new(stage);
t.run(&insts).err().map(|e| blocker_key(&e.0))
}
pub fn scan(dir: &Path) -> io::Result<Coverage> {
let mut cov = Coverage::default();
let mut paths: Vec<_> = fs::read_dir(dir)?
.flatten()
.map(|e| e.path())
.filter(|p| p.is_file())
.collect();
paths.sort();
for path in paths {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let stage = if name.contains("_VS.") {
Stage::Vertex
} else if name.contains("_PS.") {
Stage::Pixel
} else {
continue;
};
let blob = fs::read(&path)?;
cov.shaders += 1;
match stage_blocker(&blob, stage) {
None => cov.translated += 1,
Some(key) => *cov.blockers.entry(key).or_default() += 1,
}
}
Ok(cov)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn blocker_keys_group_similar_reasons() {
assert_eq!(
blocker_key("instruction 'v_cmp_lt_f32_e32 vcc_lo, v1, v2'"),
"v_cmp_lt_f32_e32"
);
assert_eq!(
blocker_key("descriptor load from 's[12:13]' (provenance Sgpr(12))"),
"descriptor load from 's[#:#]' (provenance Sgpr(#))"
);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,381 @@
//! zlib (RFC 1950) / deflate (RFC 1951) decoder for console shader containers.
//!
//! A port of BetterXen's own `shims/xcrdapi/zlib_inflate.cpp`, so the crate needs no third-party
//! dependency. It decodes a whole stream into a growing buffer and checks the Adler-32 trailer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InflateError {
BadHeader,
BadData,
Truncated,
BadChecksum,
TooLarge,
}
struct Bits<'a> {
data: &'a [u8],
pos: usize,
buffer: u32,
count: u32,
overrun: bool,
}
impl Bits<'_> {
// RFC 1951 3.1.1: data elements are packed starting with the least significant bit.
fn get(&mut self, n: u32) -> u32 {
while self.count < n {
let Some(&byte) = self.data.get(self.pos) else {
self.overrun = true;
return 0;
};
self.pos += 1;
self.buffer |= u32::from(byte) << self.count;
self.count += 8;
}
let value = if n == 32 {
self.buffer
} else {
self.buffer & ((1u32 << n) - 1)
};
self.buffer = if n == 32 { 0 } else { self.buffer >> n };
self.count -= n;
value
}
fn align_to_byte(&mut self) {
self.buffer >>= self.count & 7;
self.count -= self.count & 7;
}
}
const MAX_BITS: usize = 15;
/// Canonical Huffman decoding (RFC 1951 3.2.2): counts per code length, symbols sorted by code.
struct Huffman {
counts: [u16; MAX_BITS + 1],
symbols: [u16; 320],
}
impl Huffman {
/// `None` for an over-subscribed set of lengths. An incomplete set is allowed (a single
/// distance code is legal); decoding an unassigned code then fails.
fn build(lengths: &[u8]) -> Option<Self> {
let mut h = Huffman {
counts: [0; MAX_BITS + 1],
symbols: [0; 320],
};
for &len in lengths {
h.counts[usize::from(len)] += 1;
}
h.counts[0] = 0;
let mut left: i32 = 1;
for &count in &h.counts[1..] {
left = (left << 1) - i32::from(count);
if left < 0 {
return None;
}
}
let mut offsets = [0u16; MAX_BITS + 2];
for len in 1..=MAX_BITS {
offsets[len + 1] = offsets[len] + h.counts[len];
}
for (symbol, &len) in lengths.iter().enumerate() {
if len != 0 {
let slot = &mut offsets[usize::from(len)];
h.symbols[usize::from(*slot)] = symbol as u16;
*slot += 1;
}
}
Some(h)
}
// Huffman codes are packed most significant bit first, one bit at a time.
fn decode(&self, input: &mut Bits) -> Option<usize> {
let (mut code, mut first, mut index) = (0i32, 0i32, 0i32);
for len in 1..=MAX_BITS {
code |= input.get(1) as i32;
if input.overrun {
return None;
}
let count = i32::from(self.counts[len]);
if code - first < count {
return Some(usize::from(self.symbols[(index + code - first) as usize]));
}
index += count;
first = (first + count) << 1;
code <<= 1;
}
None
}
}
// RFC 1951 3.2.5 length and distance tables.
const LENGTH_BASE: [u16; 29] = [
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131,
163, 195, 227, 258,
];
const LENGTH_EXTRA: [u8; 29] = [
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
];
const DIST_BASE: [u16; 30] = [
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
];
const DIST_EXTRA: [u8; 30] = [
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13,
13,
];
fn codes(
input: &mut Bits,
out: &mut Vec<u8>,
limit: usize,
lit: &Huffman,
dist: &Huffman,
) -> Result<(), InflateError> {
let fail = |input: &Bits| {
if input.overrun {
InflateError::Truncated
} else {
InflateError::BadData
}
};
loop {
let symbol = lit.decode(input).ok_or_else(|| fail(input))?;
if symbol < 256 {
if out.len() >= limit {
return Err(InflateError::TooLarge);
}
out.push(symbol as u8);
continue;
}
if symbol == 256 {
return Ok(());
}
let li = symbol - 257;
if li >= 29 {
return Err(InflateError::BadData);
}
let length = usize::from(LENGTH_BASE[li]) + input.get(u32::from(LENGTH_EXTRA[li])) as usize;
let ds = dist.decode(input).ok_or_else(|| fail(input))?;
if ds >= 30 {
return Err(InflateError::BadData);
}
let distance = usize::from(DIST_BASE[ds]) + input.get(u32::from(DIST_EXTRA[ds])) as usize;
if input.overrun {
return Err(InflateError::Truncated);
}
if distance > out.len() {
return Err(InflateError::BadData);
}
if length > limit - out.len() {
return Err(InflateError::TooLarge);
}
for _ in 0..length {
let byte = out[out.len() - distance];
out.push(byte);
}
}
}
fn dynamic_tables(input: &mut Bits) -> Result<(Huffman, Huffman), InflateError> {
let hlit = input.get(5) as usize + 257;
let hdist = input.get(5) as usize + 1;
let hclen = input.get(4) as usize + 4;
if input.overrun {
return Err(InflateError::Truncated);
}
if hlit > 286 || hdist > 30 {
return Err(InflateError::BadData);
}
const ORDER: [usize; 19] = [
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
];
let mut lengths = [0u8; 320];
for &slot in &ORDER[..hclen] {
lengths[slot] = input.get(3) as u8;
}
if input.overrun {
return Err(InflateError::Truncated);
}
let code_lengths = Huffman::build(&lengths[..19]).ok_or(InflateError::BadData)?;
lengths = [0u8; 320];
let mut index = 0;
while index < hlit + hdist {
let symbol = code_lengths.decode(input).ok_or(if input.overrun {
InflateError::Truncated
} else {
InflateError::BadData
})?;
if symbol < 16 {
lengths[index] = symbol as u8;
index += 1;
continue;
}
let (value, repeat) = match symbol {
16 => {
if index == 0 {
return Err(InflateError::BadData);
}
(lengths[index - 1], 3 + input.get(2) as usize)
}
17 => (0, 3 + input.get(3) as usize),
_ => (0, 11 + input.get(7) as usize),
};
if input.overrun {
return Err(InflateError::Truncated);
}
if index + repeat > hlit + hdist {
return Err(InflateError::BadData);
}
lengths[index..index + repeat].fill(value);
index += repeat;
}
if lengths[256] == 0 {
return Err(InflateError::BadData); // no end-of-block code
}
let lit = Huffman::build(&lengths[..hlit]).ok_or(InflateError::BadData)?;
let dist = Huffman::build(&lengths[hlit..hlit + hdist]).ok_or(InflateError::BadData)?;
Ok((lit, dist))
}
fn adler32(data: &[u8]) -> u32 {
let (mut a, mut b) = (1u32, 0u32);
for chunk in data.chunks(5552) {
for &byte in chunk {
a += u32::from(byte);
b += a;
}
a %= 65521;
b %= 65521;
}
(b << 16) | a
}
/// Decodes a whole zlib stream, producing at most `limit` bytes.
pub fn zlib_inflate(input: &[u8], limit: usize) -> Result<Vec<u8>, InflateError> {
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
if input.len() < 6 {
return Err(InflateError::BadHeader);
}
let (cmf, flg) = (input[0], input[1]);
if cmf & 0x0F != 8
|| cmf >> 4 > 7
|| ((u32::from(cmf) << 8) | u32::from(flg)) % 31 != 0
|| flg & 0x20 != 0
{
return Err(InflateError::BadHeader);
}
let mut bits = Bits {
data: &input[2..],
pos: 0,
buffer: 0,
count: 0,
overrun: false,
};
let mut out = Vec::new();
loop {
let final_block = bits.get(1);
let kind = bits.get(2);
if bits.overrun {
return Err(InflateError::Truncated);
}
match kind {
0 => {
bits.align_to_byte();
let len = bits.get(16) as usize;
let nlen = bits.get(16) as usize;
if bits.overrun {
return Err(InflateError::Truncated);
}
if len ^ 0xFFFF != nlen {
return Err(InflateError::BadData);
}
// After aligning, the bit buffer is empty: copy straight from the byte stream.
let stored = bits
.data
.get(bits.pos..bits.pos + len)
.ok_or(InflateError::Truncated)?;
if len > limit - out.len() {
return Err(InflateError::TooLarge);
}
out.extend_from_slice(stored);
bits.pos += len;
}
1 => {
let mut lengths = [0u8; 288];
lengths[..144].fill(8);
lengths[144..256].fill(9);
lengths[256..280].fill(7);
lengths[280..].fill(8);
let lit = Huffman::build(&lengths).ok_or(InflateError::BadData)?;
let dist = Huffman::build(&[5u8; 30]).ok_or(InflateError::BadData)?;
codes(&mut bits, &mut out, limit, &lit, &dist)?;
}
2 => {
let (lit, dist) = dynamic_tables(&mut bits)?;
codes(&mut bits, &mut out, limit, &lit, &dist)?;
}
_ => return Err(InflateError::BadData),
}
if final_block != 0 {
break;
}
}
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
bits.align_to_byte();
let trailer = bits.pos - (bits.count / 8) as usize;
let t = bits
.data
.get(trailer..trailer + 4)
.ok_or(InflateError::Truncated)?;
if adler32(&out) != u32::from_be_bytes([t[0], t[1], t[2], t[3]]) {
return Err(InflateError::BadChecksum);
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
// zlib.compress(b"hello hello hello hello, compressed by CPython zlib " * 3, 9), made with CPython,
// independently of this code: dynamic Huffman codes and back-references.
const HELLO: [u8; 49] = [
0x78, 0xda, 0xcb, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0xc8, 0x40, 0x27, 0x75, 0x14, 0x92, 0xf3,
0x73, 0x0b, 0x8a, 0x52, 0x8b, 0x8b, 0x53, 0x53, 0x14, 0x92, 0x2a, 0x15, 0x9c, 0x03, 0x2a,
0x4b, 0x32, 0xf2, 0xf3, 0x14, 0xaa, 0x72, 0x32, 0x93, 0x30, 0x55, 0xd3, 0x48, 0x0f, 0x00,
0x91, 0x2d, 0x39, 0x07,
];
#[test]
fn inflates_a_cpython_stream() {
let expected = b"hello hello hello hello, compressed by CPython zlib ".repeat(3);
assert_eq!(zlib_inflate(&HELLO, 4096).unwrap(), expected);
assert_eq!(
zlib_inflate(&HELLO[..HELLO.len() - 3], 4096),
Err(InflateError::Truncated)
);
assert_eq!(zlib_inflate(&HELLO, 10), Err(InflateError::TooLarge));
}
#[test]
fn rejects_what_is_not_zlib() {
assert_eq!(
zlib_inflate(b"\x00\x00\x00\x00\x00\x00", 64),
Err(InflateError::BadHeader)
);
assert_eq!(zlib_inflate(b"x", 64), Err(InflateError::BadHeader));
}
#[test]
fn stored_block_round_trip_and_checksum() {
// A stored block holding "abc": header, final+type 0, LEN, NLEN, data, Adler-32.
let mut s = vec![0x78, 0x01, 0x01, 0x03, 0x00, 0xfc, 0xff, b'a', b'b', b'c'];
s.extend_from_slice(&adler32(b"abc").to_be_bytes());
assert_eq!(zlib_inflate(&s, 64).unwrap(), b"abc");
*s.last_mut().unwrap() ^= 1;
assert_eq!(zlib_inflate(&s, 64), Err(InflateError::BadChecksum));
assert_eq!(zlib_inflate(&s, 2), Err(InflateError::TooLarge));
}
}
@@ -0,0 +1,36 @@
//! Track D: BetterXen's own GFX10.3 (RDNA 2) shader translator (roadmap, Picture stage).
//!
//! Console vertex and pixel shaders carry RDNA 2 machine code; D3DMetal needs DXIL. This crate
//! translates mechanically, one rule per instruction, with registers as variables:
//!
//! 1. [`container`]: the stage code inside a console container.
//! 2. [`decode`]: code words to instructions, with names from the generated [`opcodes`] tables.
//! 3. [`translate`]: instructions to HLSL, through family tables plus specific rules. The public
//! DXC compiles that HLSL to DXIL.
//! 4. [`coverage`]: which instructions block the most shaders in a local folder.
//!
//! The Python prototype it ports, `scripts/console-shader/translate.py`, stays as the reference
//! for identical output. Next steps (handoff issues): more instruction families, control flow as
//! numbered blocks, texture and sampler forms, and translation inside `bx_shader_bridge.dll` at
//! first draw. See this crate's README.
pub mod container;
pub mod coverage;
pub mod decode;
pub mod inflate;
#[rustfmt::skip]
pub mod opcodes;
pub mod translate;
pub use decode::{Format, Inst, Operand, decode};
pub use translate::{Stage, Translation, Unsupported, translate_pair};
/// Decodes and translates a VS/PS pair given as console containers or raw code blobs.
pub fn translate_blobs(vs: &[u8], ps: &[u8]) -> Result<Translation, Unsupported> {
let words = |blob: &[u8], what: &str| {
container::code_words(blob).map_err(|e| Unsupported(format!("{what}: {e}")))
};
let vs = decode(&words(vs, "VS")?).map_err(|e| Unsupported(format!("VS decode: {e}")))?;
let ps = decode(&words(ps, "PS")?).map_err(|e| Unsupported(format!("PS decode: {e}")))?;
translate_pair(&vs, &ps)
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
FETCH 2
@@ -0,0 +1 @@
c8080000 c8090001 c80e0102 b0141234 be9503f2 8f168214 88178716 87171517 89171417 93171617 8017c017 80971417 90178417 83981617 84981418 be990b18 939aff19 00100000 ba801801 00000003 34080482 2c080890 30080881 360808ff 000000ff 38080704 3a080504 4c080704 4e080504 16080704 26080504 28080704 d5690004 02020504 d56a0004 02003304 d51a0004 02020818 060a04f0 100a0aff 3e800000 080a0705 0a0a0705 200a0505 1e0a0705 d5030005 42020505 d5080005 22020705 d5040005 02020505 d5100005 02002b05 560a0702 7e0c5505 7e0c5d06 7e0c6706 7e0c4906 7e0c4106 7e0c4b06 7e0c4f06 7e0c4306 7e0c4706 7e0c4506 7e0c6b06 7e0c6d06 d5aa0006 22010106 7e0e0d04 7e0e0b04 7e101107 d5570007 03c90107 d54b0007 23ca0507 0e0e0707 5e120d07 cc21000a 0c0e0509 cc22400a 1c2a1309 7e160217 4a16110b f8001c0f 00000a09 bf810000
@@ -0,0 +1,84 @@
float4 main(float4 pos : SV_Position, float4 attr0 : PARAM0) : SV_Target0 {
uint v2 = 0;
uint v3 = 0;
uint v4 = 0;
uint v5 = 0;
uint v6 = 0;
uint v7 = 0;
uint v8 = 0;
uint v9 = 0;
uint v10 = 0;
uint v11 = 0;
uint s20 = 0;
uint s21 = 0;
uint s22 = 0;
uint s23 = 0;
uint s24 = 0;
uint s25 = 0;
v2 = asuint(attr0.x);
v3 = asuint(attr0.y);
s20 = 4660u;
s21 = asuint(1.0f);
s22 = s20 << (2u & 31u);
s23 = (s22 | 7u);
s23 = (s23 & s21);
s23 = (s23 ^ s20);
s23 = (s23 * s22);
s23 = (s23 + 64u);
s23 = (s23 - s20);
s23 = (s23 >> (4u & 31u));
s24 = min(s23, s22);
s24 = max(s24, s20);
s25 = reversebits(s24);
v4 = (v2 << (2u & 31u));
v4 = (v4 >> (16u & 31u));
v4 = (uint)((int)v4 >> (1u & 31u));
v4 = (0xffu & v4);
v4 = (v4 | v3);
v4 = (v4 ^ v2);
v4 = (v4 - v3);
v4 = (v2 - v4);
v4 = ((v4 & 0xffffffu) * (v3 & 0xffffffu));
v4 = min(v4, v2);
v4 = max(v4, v3);
v4 = (v4 * v2);
v4 = (uint)(((uint64_t)v4 * (uint64_t)s25) >> 32);
v4 = (v4 << (s24 & 31u));
v5 = asuint(asfloat(asuint(0.5f)) + asfloat(v2));
v5 = asuint(asfloat(0x3e800000u) * asfloat(v5));
v5 = asuint(asfloat(v5) - asfloat(v3));
v5 = asuint((asfloat(v3) - asfloat(v5)));
v5 = asuint(max(asfloat(v5), asfloat(v2)));
v5 = asuint(min(asfloat(v5), asfloat(v3)));
v5 = asuint(asfloat(v5) + asfloat((asuint(-asfloat(v2)))));
v5 = asuint(asfloat((asuint(-asfloat(v5)))) * asfloat(v3));
v5 = asuint((asfloat(v5) - asfloat(v2)));
v5 = asuint(max(asfloat(v5), asfloat(s21)));
v5 = asuint(mad(asfloat(v2), asfloat(v3), asfloat(v5)));
v6 = asuint((1.0f / asfloat(v5)));
v6 = asuint(rsqrt(asfloat(v6)));
v6 = asuint(sqrt(asfloat(v6)));
v6 = asuint(floor(asfloat(v6)));
v6 = asuint(frac(asfloat(v6)));
v6 = asuint(exp2(asfloat(v6)));
v6 = asuint(log2(asfloat(v6)));
v6 = asuint(trunc(asfloat(v6)));
v6 = asuint(round(asfloat(v6)));
v6 = asuint(ceil(asfloat(v6)));
v6 = asuint(sin(asfloat(v6) * 6.2831853f));
v6 = asuint(cos(asfloat(v6) * 6.2831853f));
v6 = asuint((1.0f / asfloat((asuint(-asfloat(v6))))));
v7 = asuint((float)asuint(asfloat(v4)));
v7 = asuint((float)asint(asfloat(v4)));
v8 = (uint)(int)asfloat(v7);
v7 = asuint(max(min(asfloat(v7), asfloat(0u)), min(max(asfloat(v7), asfloat(0u)), asfloat(asuint(1.0f)))));
v7 = asuint(mad(asfloat((asuint(-asfloat(v7)))), asfloat(v2), asfloat(asuint(1.0f))));
v7 = asuint((asfloat(v7) == 0.0f || asfloat(v3) == 0.0f) ? 0.0f : asfloat(v7) * asfloat(v3));
v9 = f32tof16(asfloat(v7)) | (f32tof16(asfloat(v6)) << 16);
v10 = (v10 & 0xffff0000u) | f32tof16(mad(f16tof32(v9 & 0xffffu), asfloat(v2), asfloat(v3)));
v10 = (v10 & 0xffffu) | (f32tof16(mad(f16tof32(v9 & 0xffffu), f16tof32(v9 & 0xffffu), f16tof32(v10 & 0xffffu))) << 16);
v11 = s23;
v11 = v11 + v8;
float4 exp0_mrt0 = float4(f16tof32(v9 & 0xffffu), f16tof32(v9 >> 16), f16tof32(v10 & 0xffffu), f16tof32(v10 >> 16));
return float4(exp0_mrt0.x, exp0_mrt0.y, exp0_mrt0.z, exp0_mrt0.w);
}
@@ -0,0 +1 @@
be842104 f80008cf 07060504 f800020f 0b0a0908 bf810000
@@ -0,0 +1,17 @@
struct VSOut { float4 pos : SV_Position; float4 param0 : PARAM0; };
VSOut main(float4 a0 : ATTR0, float4 a1 : ATTR1) {
uint v4 = asuint(a0.x);
uint v5 = asuint(a0.y);
uint v6 = asuint(a0.z);
uint v7 = asuint(a0.w);
uint v8 = asuint(a1.x);
uint v9 = asuint(a1.y);
uint v10 = asuint(a1.z);
uint v11 = asuint(a1.w);
float4 exp0_pos0 = float4(asfloat(v4), asfloat(v5), asfloat(v6), asfloat(v7));
float4 exp1_param0 = float4(asfloat(v8), asfloat(v9), asfloat(v10), asfloat(v11));
VSOut o;
o.pos = float4(exp0_pos0.x, exp0_pos0.y, exp0_pos0.z, exp0_pos0.w);
o.param0 = float4(exp1_param0.x, exp1_param0.y, exp1_param0.z, exp1_param0.w);
return o;
}
@@ -0,0 +1,4 @@
ATTR 0 17 0 0
ATTR 1 28 1 8
ATTR 2 7 0 8
USE CB 1
@@ -0,0 +1 @@
c80a0402 c80e0702 c8100200 c8110201 f8001807 00040302 bf810000
@@ -0,0 +1,10 @@
float4 main(float4 pos : SV_Position, float4 attr0 : PARAM0, float4 attr1 : PARAM1) : SV_Target0 {
uint v2 = 0;
uint v3 = 0;
uint v4 = 0;
v2 = asuint(attr1.x);
v3 = asuint(attr1.w);
v4 = asuint(attr0.z);
float4 exp0_mrt0 = float4(asfloat(v2), asfloat(v3), asfloat(v4), 0.0f);
return float4(exp0_mrt0.x, exp0_mrt0.y, exp0_mrt0.z, exp0_mrt0.w);
}
@@ -0,0 +1 @@
f4080300 fa000000 f4080400 fa000010 f4080504 fa000020 4a020002 bf8cc07f e0342000 80030201 e9c32008 80040401 e03c2008 80030801 e0382000 80050c00 bf8c3f70 7e1602f2 f80008cf 0b080302 f800020f 07060504 f800021f 0f0e0d0c bf810000
@@ -0,0 +1,50 @@
cbuffer CB1 : register(b1, space100) { uint4 cb1[4096]; };
uint cb1_word(uint w) { return cb1[w >> 2][w & 3]; }
struct VSOut { float4 pos : SV_Position; float4 param0 : PARAM0; float4 param1 : PARAM1; };
VSOut main(uint2 in0 : ATTR0, float4 in1 : ATTR1, uint3 in2 : ATTR2) {
uint v0 = 0;
uint v2 = 0;
uint v3 = 0;
uint v4 = 0;
uint v5 = 0;
uint v6 = 0;
uint v7 = 0;
uint v8 = 0;
uint v9 = 0;
uint v10 = 0;
uint v11 = 0;
uint v12 = 0;
uint v13 = 0;
uint v14 = 0;
uint v15 = 0;
uint t0_0 = 0;
uint t0_1 = 0;
uint t0_2 = 0;
uint t0_3 = 0;
v2 = in0.x;
v3 = in0.y;
v4 = asuint(in1.x);
v5 = asuint(in1.y);
v6 = asuint(in1.z);
v7 = asuint(in1.w);
v8 = in2.x;
v9 = in2.y;
v10 = in2.z;
t0_0 = cb1[v0].x;
t0_1 = cb1[v0].y;
t0_2 = cb1[v0].z;
t0_3 = cb1[v0].w;
v12 = t0_0;
v13 = t0_1;
v14 = t0_2;
v15 = t0_3;
v11 = asuint(1.0f);
float4 exp0_pos0 = float4(asfloat(v2), asfloat(v3), asfloat(v8), asfloat(v11));
float4 exp1_param0 = float4(asfloat(v4), asfloat(v5), asfloat(v6), asfloat(v7));
float4 exp2_param1 = float4(asfloat(v12), asfloat(v13), asfloat(v14), asfloat(v15));
VSOut o;
o.pos = float4(exp0_pos0.x, exp0_pos0.y, exp0_pos0.z, exp0_pos0.w);
o.param0 = float4(exp1_param0.x, exp1_param0.y, exp1_param0.z, exp1_param0.w);
o.param1 = float4(exp2_param1.x, exp2_param1.y, exp2_param1.z, exp2_param1.w);
return o;
}
@@ -0,0 +1,3 @@
FETCH 1
USE CB 0
USE TEX 1
@@ -0,0 +1 @@
be8a047e befe0a7e befc0302 c8080000 c8090001 c80c0100 c80d0101 f40c0004 fa000020 f408030a fa000000 87fe0a7e bf8cc07f f0800f08 00600402 bf8c3f70 10080904 f800180f 07060504 bf810000
@@ -0,0 +1,21 @@
Texture2D<float4> tex1 : register(t1, space100);
SamplerState smp0 : register(s0, space100);
float4 main(float4 pos : SV_Position, float4 attr0 : PARAM0) : SV_Target0 {
uint v2 = 0;
uint v3 = 0;
uint v4 = 0;
uint v5 = 0;
uint v6 = 0;
uint v7 = 0;
v2 = asuint(attr0.x);
v3 = asuint(attr0.y);
{ float4 r = tex1.Sample(smp0, float2(asfloat(v2), asfloat(v3)));
v4 = asuint(r.x);
v5 = asuint(r.y);
v6 = asuint(r.z);
v7 = asuint(r.w);
}
v4 = asuint(asfloat(v4) * asfloat(v4));
float4 exp0_mrt0 = float4(asfloat(v4), asfloat(v5), asfloat(v6), asfloat(v7));
return float4(exp0_mrt0.x, exp0_mrt0.y, exp0_mrt0.z, exp0_mrt0.w);
}
@@ -0,0 +1 @@
be842104 f4080304 fa000000 bf8cc07f f4280406 fa000000 bf8cc07f 10000810 d54b0001 004e0a11 7e040280 7e0602f2 f80008cf 03020100 f800020f 03020706 bf810000
@@ -0,0 +1,31 @@
cbuffer CB0 : register(b0, space100) { uint4 cb0[4096]; };
uint cb0_word(uint w) { return cb0[w >> 2][w & 3]; }
struct VSOut { float4 pos : SV_Position; float4 param0 : PARAM0; };
VSOut main(float4 a0 : ATTR0) {
uint v0 = 0;
uint v1 = 0;
uint v2 = 0;
uint v3 = 0;
uint v4 = asuint(a0.x);
uint v5 = asuint(a0.y);
uint v6 = asuint(a0.z);
uint v7 = asuint(a0.w);
uint s16 = 0;
uint s17 = 0;
uint s18 = 0;
uint s19 = 0;
s16 = cb0_word(0);
s17 = cb0_word(1);
s18 = cb0_word(2);
s19 = cb0_word(3);
v0 = asuint(asfloat(s16) * asfloat(v4));
v1 = asuint(mad(asfloat(s17), asfloat(v5), asfloat(s19)));
v2 = 0u;
v3 = asuint(1.0f);
float4 exp0_pos0 = float4(asfloat(v0), asfloat(v1), asfloat(v2), asfloat(v3));
float4 exp1_param0 = float4(asfloat(v6), asfloat(v7), asfloat(v2), asfloat(v3));
VSOut o;
o.pos = float4(exp0_pos0.x, exp0_pos0.y, exp0_pos0.z, exp0_pos0.w);
o.param0 = float4(exp1_param0.x, exp1_param0.y, exp1_param0.z, exp1_param0.w);
return o;
}
@@ -0,0 +1,42 @@
//! The decoder against the public LLVM AMDGPU disassembler: every line of llvm_vectors.txt
//! (generated by scripts/console-shader/gen_llvm_vectors.py) gives instruction words and the
//! text llvm-mc prints for them. Decoding the words must give the same text and consume exactly
//! those words.
use gfx10_translate::decode::decode_one;
#[test]
fn decoder_matches_llvm() {
let mut failures = Vec::new();
let mut checked = 0;
for line in include_str!("llvm_vectors.txt").lines() {
if line.starts_with('#') || line.trim().is_empty() {
continue;
}
let (hex, expected) = line.split_once(" | ").expect("vector line");
let words: Vec<u32> = hex
.split_whitespace()
.map(|w| u32::from_str_radix(w, 16).unwrap())
.collect();
checked += 1;
match decode_one(&words, 0) {
Ok(inst) if inst.words.len() != words.len() => failures.push(format!(
"{expected}: consumed {} of {} words",
inst.words.len(),
words.len()
)),
Ok(inst) if inst.to_string() != expected => {
failures.push(format!("{expected}\n got: {inst}"))
}
Ok(_) => {}
Err(e) => failures.push(format!("{expected}: {e}")),
}
}
assert!(checked > 100, "only {checked} vectors");
assert!(
failures.is_empty(),
"{} of {checked} differ from llvm-mc:\n {}",
failures.len(),
failures.join("\n ")
);
}
@@ -0,0 +1,129 @@
# @generated by scripts/console-shader/gen_llvm_vectors.py from Homebrew LLVM version 23.1.6 (gfx1030).
# <instruction words> | <llvm-mc's text for them>
80000201 | s_add_u32 s0, s1, s2
8003ff01 12345678 | s_add_u32 s3, s1, 0x12345678
88008701 | s_or_b32 s0, s1, 7
8704c105 | s_and_b32 s4, s5, -1
89000201 | s_xor_b32 s0, s1, s2
93000201 | s_mul_i32 s0, s1, s2
8080c001 | s_sub_u32 s0, s1, 64
90008401 | s_lshr_b32 s0, s1, 4
8f008201 | s_lshl_b32 s0, s1, 2
83800201 | s_min_u32 s0, s1, s2
84800201 | s_max_u32 s0, s1, s2
9380ff01 00100000 | s_bfe_u32 s0, s1, 0x100000
be800301 | s_mov_b32 s0, s1
be8003f2 | s_mov_b32 s0, 1.0
befc0301 | s_mov_b32 m0, s1
be800402 | s_mov_b64 s[0:1], s[2:3]
be80047e | s_mov_b64 s[0:1], exec
87fe027e | s_and_b64 exec, exec, s[2:3]
befe0a7e | s_wqm_b64 exec, exec
be800b01 | s_brev_b32 s0, s1
be842104 | s_swappc_b64 s[4:5], s[4:5]
b0001234 | s_movk_i32 s0, 0x1234
bf060100 | s_cmp_eq_u32 s0, s1
bf840004 | s_cbranch_scc0 4
bf810000 | s_endpgm
f4080002 fa000010 | s_load_dwordx4 s[0:3], s[4:5], 0x10
f40c0202 fa000020 | s_load_dwordx8 s[8:15], s[4:5], 0x20
f4080002 fa000000 | s_load_dwordx4 s[0:3], s[4:5], null
f4200002 fa000000 | s_buffer_load_dword s0, s[4:7], null
f4240002 fa000008 | s_buffer_load_dwordx2 s[0:1], s[4:7], 0x8
f4280202 fa000010 | s_buffer_load_dwordx4 s[8:11], s[4:7], 0x10
f42c0202 fa000020 | s_buffer_load_dwordx8 s[8:15], s[4:7], 0x20
f4300402 fa000040 | s_buffer_load_dwordx16 s[16:31], s[4:7], 0x40
7e000301 | v_mov_b32_e32 v0, v1
7e000202 | v_mov_b32_e32 v0, s2
7e0002ff 40490fdb | v_mov_b32_e32 v0, 0x40490fdb
7e0002f2 | v_mov_b32_e32 v0, 1.0
7e0002f7 | v_mov_b32_e32 v0, -4.0
7e0002f8 | v_mov_b32_e32 v0, 0.15915494
7e000291 | v_mov_b32_e32 v0, 17
7e0002c3 | v_mov_b32_e32 v0, -3
06000501 | v_add_f32_e32 v0, v1, v2
060002f0 | v_add_f32_e32 v0, 0.5, v1
100002ff 3e800000 | v_mul_f32_e32 v0, 0x3e800000, v1
08000501 | v_sub_f32_e32 v0, v1, v2
0a000501 | v_subrev_f32_e32 v0, v1, v2
20000501 | v_max_f32_e32 v0, v1, v2
1e000501 | v_min_f32_e32 v0, v1, v2
56000501 | v_fmac_f32_e32 v0, v1, v2
0e000501 | v_mul_legacy_f32_e32 v0, v1, v2
5e000501 | v_cvt_pkrtz_f16_f32_e32 v0, v1, v2
34000282 | v_lshlrev_b32_e32 v0, 2, v1
2c000290 | v_lshrrev_b32_e32 v0, 16, v1
30000290 | v_ashrrev_i32_e32 v0, 16, v1
360002ff 000000ff | v_and_b32_e32 v0, 0xff, v1
38000501 | v_or_b32_e32 v0, v1, v2
3a000501 | v_xor_b32_e32 v0, v1, v2
4c000501 | v_sub_nc_u32_e32 v0, v1, v2
4e000501 | v_subrev_nc_u32_e32 v0, v1, v2
4a000202 | v_add_nc_u32_e32 v0, s2, v1
16000501 | v_mul_u32_u24_e32 v0, v1, v2
26000501 | v_min_u32_e32 v0, v1, v2
28000501 | v_max_u32_e32 v0, v1, v2
7e005501 | v_rcp_f32_e32 v0, v1
7e005d01 | v_rsq_f32_e32 v0, v1
7e006701 | v_sqrt_f32_e32 v0, v1
7e004901 | v_floor_f32_e32 v0, v1
7e004101 | v_fract_f32_e32 v0, v1
7e004b01 | v_exp_f32_e32 v0, v1
7e004f01 | v_log_f32_e32 v0, v1
7e004301 | v_trunc_f32_e32 v0, v1
7e004701 | v_rndne_f32_e32 v0, v1
7e004501 | v_ceil_f32_e32 v0, v1
7e000d01 | v_cvt_f32_u32_e32 v0, v1
7e000b01 | v_cvt_f32_i32_e32 v0, v1
7e001101 | v_cvt_i32_f32_e32 v0, v1
7e006b01 | v_sin_f32_e32 v0, v1
7e006d01 | v_cos_f32_e32 v0, v1
d5030000 02020501 | v_add_f32_e64 v0, v1, v2
d5080000 22020501 | v_mul_f32_e64 v0, -v1, v2
d5080000 42020501 | v_mul_f32_e64 v0, v1, -v2
d5080200 22020501 | v_mul_f32_e64 v0, -v1, |v2|
d5038000 02020501 | v_add_f32_e64 v0, v1, v2 clamp
d5080000 0a020501 | v_mul_f32_e64 v0, v1, v2 mul:2
d5100000 02000501 | v_max_f32_e64 v0, v1, s2
d5040000 02020501 | v_sub_f32_e64 v0, v1, v2
d5aa0000 22010101 | v_rcp_f32_e64 v0, -v1
d51a0000 02020202 | v_lshlrev_b32_e64 v0, s2, v1
d5690000 02020501 | v_mul_lo_u32 v0, v1, v2
d56a0000 02020501 | v_mul_hi_u32 v0, v1, v2
d54b0000 040e0501 | v_fma_f32 v0, v1, v2, v3
d54b0000 23ca0501 | v_fma_f32 v0, -v1, v2, 1.0
d5570000 03c90101 | v_med3_f32 v0, v1, 0, 1.0
d5480000 02211101 | v_bfe_u32 v0, v1, 8, 8
7c020501 | v_cmp_lt_f32_e32 vcc_lo, v1, v2
7da40501 | v_cmpx_eq_u32_e32 v1, v2
02000501 | v_cndmask_b32_e32 v0, v1, v2, vcc_lo
c8080000 | v_interp_p1_f32_e32 v2, v0, attr0.x
c8090001 | v_interp_p2_f32_e32 v2, v1, attr0.x
c80d0f01 | v_interp_p2_f32_e32 v3, v1, attr3.w
c8020902 | v_interp_mov_f32_e32 v0, p0, attr2.y
cc210000 1c0e0501 | v_fma_mixlo_f16 v0, v1, v2, v3 op_sel_hi:[1,1,0]
cc224000 1c0e0501 | v_fma_mixhi_f16 v0, v1, v2, v3 op_sel_hi:[1,1,1]
e0302000 80010001 | buffer_load_dword v0, v1, s[4:7], 0 idxen
e030200c 80010001 | buffer_load_dword v0, v1, s[4:7], 0 idxen offset:12
e0342000 80010002 | buffer_load_dwordx2 v[0:1], v2, s[4:7], 0 idxen
e03c2004 80010003 | buffer_load_dwordx3 v[0:2], v3, s[4:7], 0 idxen offset:4
e0382000 80020004 | buffer_load_dwordx4 v[0:3], v4, s[8:11], 0 idxen
e0301000 80010001 | buffer_load_dword v0, v1, s[4:7], 0 offen
e0300010 02010000 | buffer_load_dword v0, off, s[4:7], s2 offset:16
e9c32000 80000004 | tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_8_8_8_8_UNORM] idxen
e8eb2008 80000004 | tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] idxen offset:8
f0800f08 00820004 | image_sample v[0:3], v[4:5], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
f0800808 00820004 | image_sample v0, v[4:5], s[8:15], s[16:19] dmask:0x8 dim:SQ_RSRC_IMG_2D
f09c0308 00820002 | image_sample_lz v[0:1], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D
f80008cf 03020100 | exp pos0, v0, v1, v2, v3 done
f800180f 03020100 | exp mrt0, v0, v1, v2, v3 done vm
f8000001 00000000 | exp mrt0, v0, off, off, off
f800023f 07060504 | exp param3, v4, v5, v6, v7
f8001c0f 00000100 | exp mrt0, v0, v0, v1, v1 done compr vm
5a000501 3f800000 | v_fmaak_f32 v0, v1, v2, 0x3f800000
58000501 40000000 | v_fmamk_f32 v0, v1, 0x40000000, v2
3e000501 | v_mac_f32_e32 v0, v1, v2
d51f0000 22020501 | v_mac_f32_e64 v0, -v1, v2
d5410000 040e0501 | v_mad_f32 v0, v1, v2, v3
42000501 3f800000 | v_madak_f32 v0, v1, v2, 0x3f800000
40000501 40000000 | v_madmk_f32 v0, v1, 0x40000000, v2
@@ -0,0 +1,230 @@
//! The translator against its reference. The golden files hold small VS/PS pairs written in
//! GFX10.3 assembly, assembled by the public LLVM assembler, with the HLSL and input layout the
//! Python prototype (scripts/console-shader/translate.py) produces for them; regenerate them
//! with scripts/console-shader/gen_translate_goldens.py. Between them the cases use every rule
//! the translator has. Refusals are checked separately.
use gfx10_translate::decode::decode;
use gfx10_translate::translate::{Stage, Translator, translate_pair};
fn words(hex: &str) -> Vec<u32> {
hex.split_whitespace()
.map(|w| u32::from_str_radix(w, 16).unwrap())
.collect()
}
fn golden(case: &str, vs: &str, ps: &str, vs_hlsl: &str, ps_hlsl: &str, il: &str) {
let vs = decode(&words(vs)).unwrap_or_else(|e| panic!("{case} VS: {e}"));
let ps = decode(&words(ps)).unwrap_or_else(|e| panic!("{case} PS: {e}"));
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{case}: {e}"));
assert_eq!(t.vs_hlsl, vs_hlsl, "{case} VS HLSL");
assert_eq!(t.ps_hlsl, ps_hlsl, "{case} PS HLSL");
assert_eq!(t.layout, il, "{case} layout");
}
macro_rules! golden_case {
($test:ident, $name:literal) => {
#[test]
fn $test() {
golden(
$name,
include_str!(concat!("goldens/", $name, ".vs.hex")),
include_str!(concat!("goldens/", $name, ".ps.hex")),
include_str!(concat!("goldens/", $name, ".vs.hlsl")),
include_str!(concat!("goldens/", $name, ".ps.hlsl")),
include_str!(concat!("goldens/", $name, ".il")),
);
}
};
}
golden_case!(textured_pair_matches_the_prototype, "textured");
golden_case!(alu_families_match_the_prototype, "alu");
golden_case!(vertex_buffers_match_the_prototype, "buffers");
/// Translates one stage given as instruction words, returning the refusal if any.
fn refusal(stage: Stage, hex: &str) -> Option<String> {
let insts = decode(&words(hex)).unwrap();
Translator::new(stage).run(&insts).err().map(|e| e.0)
}
// Encodings from llvm-mc (gfx1030); each program ends in s_endpgm (bf810000).
#[test]
fn refuses_what_it_does_not_model() {
// v_cmp_lt_f32_e32 vcc_lo, v1, v2: no rule for compares yet.
assert!(
refusal(Stage::Pixel, "7c020501 bf810000")
.unwrap()
.starts_with("instruction 'v_cmp_lt_f32_e32")
);
// v_add_f32_e64 v0, v1, v2 clamp: output modifiers are refused, not dropped.
assert!(
refusal(Stage::Pixel, "d5038000 02020501 bf810000")
.unwrap()
.starts_with("modifier in")
);
// v_mul_f32_e64 v0, v1, v2 mul:2
assert!(
refusal(Stage::Pixel, "d5080000 0a020501 bf810000")
.unwrap()
.starts_with("modifier in")
);
// s_load_dwordx8 s[8:15], s[4:5], 0x20: a texture from a descriptor table the model does not
// know. (A 4-dword load from such a table is a sampler and is accepted.)
assert!(
refusal(Stage::Pixel, "f40c0202 fa000020 bf810000")
.unwrap()
.starts_with("descriptor load from")
);
assert_eq!(refusal(Stage::Pixel, "f4080002 fa000010 bf810000"), None);
// s_swappc_b64 s[4:5], s[4:5] in a pixel shader.
assert!(refusal(Stage::Pixel, "be842104 bf810000").is_some());
}
#[test]
fn a_pixel_shader_reading_an_attribute_the_vertex_shader_does_not_export_is_refused() {
// VS: s_swappc_b64 s[4:5], s[4:5]; exp pos0, v4, v5, v6, v7 done; s_endpgm
// PS: v_interp_mov_f32_e32 v2, p0, attr1.x; exp mrt0, v2, off, off, off done; s_endpgm
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
let ps = decode(&words("c80a0402 f8000801 00000002 bf810000")).unwrap();
let err = translate_pair(&vs, &ps).unwrap_err();
assert_eq!(err.0, "PS reads attr1 that the VS does not export");
}
#[test]
fn s_movk_sign_extends() {
// s_movk_i32 s0, 0xffff; v_mov_b32_e32 v0, s0; exp mrt0, v0, off, off, off done; s_endpgm
let insts = decode(&words("b000ffff 7e000200 f8000801 00000000 bf810000")).unwrap();
let mut t = Translator::new(Stage::Pixel);
t.run(&insts).unwrap();
let (vs, params) = gfx10_translate::translate::build_vs(&{
let mut v = Translator::new(Stage::Vertex);
v.run(&decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap())
.unwrap();
v
})
.unwrap();
let ps = gfx10_translate::translate::build_ps(&t, &params).unwrap();
assert!(vs.contains("o.pos"));
assert!(ps.contains("s0 = 4294967295u;"), "{ps}");
}
/// The multiply-add family (not in the prototype). Encodings from llvm-mc (v_mac/v_mad/v_madak/
/// v_madmk for gfx1010, v_fmaak/v_fmamk for gfx1030); the expected HLSL follows the ISA's
/// definitions (D = S0*S1 + D; S0*S1 + S2; S0*S1 + K; S0*K + S1), written out here.
#[test]
fn multiply_add_family() {
let cases = [
(
"3e000501",
"v0 = asuint(mad(asfloat(v1), asfloat(v2), asfloat(v0)));",
),
(
"d51f0000 22020501",
"v0 = asuint(mad(asfloat((asuint(-asfloat(v1)))), asfloat(v2), asfloat(v0)));",
),
(
"d5410000 040e0501",
"v0 = asuint(mad(asfloat(v1), asfloat(v2), asfloat(v3)));",
),
(
"42000501 3f800000",
"v0 = asuint(mad(asfloat(v1), asfloat(v2), asfloat(0x3f800000u)));",
),
(
"40000501 40000000",
"v0 = asuint(mad(asfloat(v1), asfloat(0x40000000u), asfloat(v2)));",
),
(
"5a000501 3f800000",
"v0 = asuint(mad(asfloat(v1), asfloat(v2), asfloat(0x3f800000u)));",
),
(
"58000501 40000000",
"v0 = asuint(mad(asfloat(v1), asfloat(0x40000000u), asfloat(v2)));",
),
];
// VS: s_swappc_b64 s[4:5], s[4:5]; exp pos0, v4, v5, v6, v7 done; s_endpgm
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
for (hex, line) in cases {
// PS: <instruction>; exp mrt0, v0, off, off, off done; s_endpgm
let ps = decode(&words(&format!("{hex} f8000801 00000000 bf810000"))).unwrap();
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{hex}: {e}"));
assert!(
t.ps_hlsl.contains(&format!(" {line}\n")),
"{hex}:\n{}",
t.ps_hlsl
);
}
}
/// Extensions beyond the prototype: 32-lane execution-mask bookkeeping has no HLSL counterpart
/// (as the 64-lane form), and a compressed export with its second half disabled exports zeros
/// there. Encodings from llvm-mc (gfx1030, wave32).
#[test]
fn wave32_mask_bookkeeping_and_half_compressed_exports() {
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
// s_mov_b32 s94, exec_lo; s_wqm_b32 exec_lo, exec_lo; v_mov_b32_e32 v0, s2;
// s_and_b32 exec_lo, exec_lo, s94; exp mrt0, v0, v0, off, off done compr vm; s_endpgm
let ps = decode(&words(
"bede037e befe097e 7e000202 877e5e7e f8001c03 00000000 bf810000",
))
.unwrap();
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{e}"));
assert!(t.ps_hlsl.contains(" v0 = s2;\n"), "{}", t.ps_hlsl);
assert!(
t.ps_hlsl.contains(
"float4 exp0_mrt0 = float4(f16tof32(v0 & 0xffffu), f16tof32(v0 >> 16), 0.0f, 0.0f);"
),
"{}",
t.ps_hlsl
);
assert!(
!t.ps_hlsl.contains("s94 ="),
"the mask copy must not be emitted:\n{}",
t.ps_hlsl
);
}
/// Integer, conversion and lane instructions (#716). Encodings from llvm-mc (gfx1030); each
/// expected line follows the instruction's ISA definition.
#[test]
fn integer_conversion_and_lane_instructions() {
// (instruction words, register moved to v0 before the export, expected line)
let cases: &[(&str, &str, &str)] = &[
("81000201", "7e000200", "s0 = (s1 + s2);"),
(
"8300c201",
"7e000200",
"s0 = (uint)min((int)s1, (int)4294967294u);",
),
(
"7e000f01",
"",
"v0 = (isnan(asfloat(v1)) ? 0u : (asfloat(v1) >= 4294967296.0f ? 0xffffffffu : (uint)max(asfloat(v1), 0.0f)));",
),
("7e002301", "", "v0 = asuint((float)(v1 & 0xffu));"),
("7e002701", "", "v0 = asuint((float)((v1 >> 16) & 0xffu));"),
("7e005701", "", "v0 = asuint((1.0f / asfloat(v1)));"),
("d7460000 04090501", "", "v0 = ((v1 << (2u & 31u)) + v2);"),
(
"d5480000 02111101",
"",
"v0 = (((4u & 31u) == 0u) ? 0u : ((8u & 31u) + (4u & 31u) >= 32u ? (v1 >> (8u & 31u)) : ((v1 >> (8u & 31u)) & ((1u << (4u & 31u)) - 1u))));",
),
("d54a0000 040e0501", "", "v0 = ((v1 & v2) | (~v1 & v3));"),
("d76d0000 000e0501", "", "v0 = (v1 + v2 + s3);"),
("7e080501", "7e000204", "s4 = WaveReadLaneFirst(v1);"),
];
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
for (inst, mov, line) in cases {
// PS: <instruction>; [v_mov_b32_e32 v0, sN]; exp mrt0, v0, off, off, off done; s_endpgm
let ps = decode(&words(&format!("{inst} {mov} f8000801 00000000 bf810000"))).unwrap();
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{inst}: {e}"));
assert!(
t.ps_hlsl.contains(&format!(" {line}\n")),
"{inst}:\n{}",
t.ps_hlsl
);
}
}
+1
View File
@@ -8,6 +8,7 @@ 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
+75 -3
View File
@@ -11,6 +11,7 @@
#include "console_formats.h"
#include "xbox_facade.h"
#include "gdk_xg.h"
#include <atomic>
#include <cstdio>
@@ -74,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" {
@@ -81,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;
}
@@ -90,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;
}
@@ -99,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;
}
+5
View File
@@ -79,7 +79,12 @@ extern "C" {
* models (or one the host device answers); anything else fails with E_NOINTERFACE and a logged
* IID.
*/
extern "C" void bx_gdk_xg_enable_locking();
HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv) {
// 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;
}
+104 -1
View File
@@ -7,10 +7,17 @@
* FLIP events, and IntervalOffsetInMicroseconds later the ORIGIN event, which also produces a
* new frame pipeline token. Each signal also sets the ancillary events given to
* ScheduleFrameEventX. Timing follows the host's Sleep granularity; no display is involved.
*
* GetFrameStatisticsX (authorized GDK documentation) answers from a history of the last 17
* frames, kept per pipeline token: the ORIGIN event (wait call, signal and wait return times)
* and PresentX (call and return times), in QueryPerformanceCounter ticks as documented. The
* other statistics types (interval, power scaling, render, display, input) have no host source
* and are never reported; a query for only those answers S_FALSE, "not available yet".
*/
#include "xbox_facade.h"
#include <cstdio>
#include <cstring>
#include <mutex>
#include <thread>
@@ -43,6 +50,35 @@ UINT64 g_next_token = 1;
UINT64 g_last_origin_token = 0;
bool g_thread_started = false;
// Frame statistics history (GetFrameStatisticsX): the runtime keeps the last 17 frames.
constexpr UINT kHistory = 17;
struct FrameRecord {
UINT64 token = 0;
UINT64 wait_call = 0, signal = 0, wait_return = 0;
UINT offset_us = 0;
bool signaled = false;
bool waited = false;
bool presented = false;
UINT64 present_call = 0, present_return = 0;
};
FrameRecord g_history[kHistory];
UINT64 qpc_now() {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return static_cast<UINT64>(t.QuadPart);
}
// The record for `token`, created when `create` (replacing the one 17 frames older); else null.
FrameRecord* record_for(UINT64 token, bool create) {
FrameRecord& r = g_history[token % kHistory];
if (r.token == token) return &r;
if (!create) return nullptr;
r = FrameRecord{};
r.token = token;
return &r;
}
void close_ancillary(Scheduled& e) {
for (UINT i = 0; i < e.ancillary_count; ++i) CloseHandle(e.ancillary[i]);
e.ancillary_count = 0;
@@ -52,7 +88,13 @@ void signal(UINT type) {
std::lock_guard<std::mutex> guard(g_lock);
const Scheduled& e = g_events[type];
if (!e.active) return;
if (type == kOrigin) g_last_origin_token = g_next_token++;
if (type == kOrigin) {
g_last_origin_token = g_next_token++;
FrameRecord* r = record_for(g_last_origin_token, true);
r->signal = qpc_now();
r->offset_us = e.offset_us;
r->signaled = true;
}
SetEvent(g_signal[type]);
for (UINT i = 0; i < e.ancillary_count; ++i) SetEvent(e.ancillary[i]);
}
@@ -156,6 +198,7 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UI
}
const UINT ancillary = waits ? waits->Count : 0;
for (UINT i = 0; i < ancillary; ++i) handles[1 + i] = waits->pObjects[i];
const UINT64 wait_call = qpc_now();
const DWORD result = WaitForMultipleObjects(1 + ancillary, handles, (flags & kWaitAll) != 0,
timeout_ms == kInfinite ? INFINITE : timeout_ms);
const bool satisfied = result < WAIT_OBJECT_0 + 1 + ancillary;
@@ -166,8 +209,68 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UI
if (type == kOrigin && token && (satisfied || (flags & kWaitProcessTokenOnTimeout))) {
std::lock_guard<std::mutex> guard(g_lock);
*token = satisfied ? g_last_origin_token : g_next_token++;
if (FrameRecord* r = record_for(*token, true)) {
r->wait_call = wait_call;
r->wait_return = qpc_now();
r->waited = true;
}
}
return satisfied ? S_OK : S_FALSE;
}
void bx_xbox_frame_stats_present(UINT64 token, UINT64 call_time, UINT64 return_time) {
if (!token) return;
std::lock_guard<std::mutex> guard(g_lock);
if (FrameRecord* r = record_for(token, false)) {
r->presented = true;
r->present_call = call_time;
r->present_return = return_time;
}
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_get_frame_statistics_x(void*, UINT64 token, UINT type_set, UINT* count,
void* statistics) {
BX_D3D_TRACE("XboxDevice", "GetFrameStatisticsX");
if (!count || type_set == 0 || (type_set & ~kStatsKnownTypes) != 0 || (*count && !statistics)) return E_INVALIDARG;
BxXboxFrameStatistics found[2];
UINT n = 0;
{
std::lock_guard<std::mutex> guard(g_lock);
if (token == 0 || token >= g_next_token) return E_INVALIDARG; // documented: unknown pipeline token
if (const FrameRecord* r = record_for(token, false)) {
if ((type_set & kStatsFrameEvent) && (r->signaled || r->waited)) {
BxXboxFrameStatistics& out = found[n++];
std::memset(&out, 0, sizeof(out));
out.Type = kStatsFrameEvent;
out.Event.EventType = kOrigin;
out.Event.WaitCallTime = r->wait_call;
out.Event.SignalTime = r->signal;
out.Event.WaitReturnTime = r->wait_return;
out.Event.IntervalOffsetInMicroseconds = r->offset_us;
out.Event.StatisticsFlags = r->signaled ? 0 : kEventSignalPending;
}
if ((type_set & kStatsPresent) && r->presented) {
BxXboxFrameStatistics& out = found[n++];
std::memset(&out, 0, sizeof(out));
out.Type = kStatsPresent;
out.Present.PlaneIndex = 0;
out.Present.PlaneCount = 1;
out.Present.ViewCount = 1;
out.Present.PresentCallTime = r->present_call;
out.Present.PresentQueueTime = r->present_call; // queued in the call itself
out.Present.PresentReturnTime = r->present_return;
out.Present.PlaneSwapMask = 1; // GPUProcessTime: not measured, 0
}
}
}
if (!statistics) { // a size query
*count = n;
return n ? S_OK : S_FALSE;
}
const UINT written = n < *count ? n : *count;
std::memcpy(statistics, found, written * sizeof(BxXboxFrameStatistics));
*count = written;
return n ? S_OK : S_FALSE;
}
} // extern "C"
+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();
+15
View File
@@ -281,6 +281,21 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
const void* parameters) {
BX_D3D_TRACE("XboxCommandQueue", "PresentX");
(void)parameters;
// Call and return times for GetFrameStatisticsX, kept for the first plane's pipeline token.
struct PresentTimes {
UINT64 token;
UINT64 call;
~PresentTimes() {
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
bx_xbox_frame_stats_present(token, call, static_cast<UINT64>(now.QuadPart));
}
} times{plane_count && planes_raw ? static_cast<const PlaneParameters*>(planes_raw)[0].Token : 0, 0};
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
times.call = static_cast<UINT64>(now.QuadPart);
}
const auto* planes = static_cast<const PlaneParameters*>(planes_raw);
if (plane_count == 0 || !planes || planes[0].ResourceCount == 0 || !planes[0].ppResources) return S_OK;
ID3D12Resource* source = bx_xbox_unwrap_as(planes[0].ppResources[0]);
+1
View File
@@ -54,6 +54,7 @@ CUSTOM = {
"WaitFrameEventX": "bx_xbox_device_wait_frame_event_x",
"CreatePlacedResourceX": "bx_xbox_device_create_placed_resource_x",
"CreatePlacedResourceX1": "bx_xbox_device_create_placed_resource_x1",
"GetFrameStatisticsX": "bx_xbox_device_get_frame_statistics_x",
"CreateCommittedResourceX": "bx_xbox_device_create_committed_resource_x",
"CreateDescriptorHeap": "bx_xbox_device_create_descriptor_heap",
"GetDescriptorHandleIncrementSize": "bx_xbox_device_get_descriptor_handle_increment_size",
+42
View File
@@ -154,6 +154,48 @@ struct BxXboxFrameObjectList {
UINT Count;
HANDLE* pObjects;
};
// GetFrameStatisticsX (authorized GDK header): D3D12XBOX_FRAME_STATISTICS is a 32-bit Type and,
// 8 bytes in, a union of the per-type structures; the two this layer fills are mirrored here.
constexpr UINT kStatsFrameEvent = 0x2, kStatsPresent = 0x1000;
constexpr UINT kStatsKnownTypes = 0x1 | 0x2 | 0x4 | 0x100 | 0x1000 | 0x10000 | 0x100000;
constexpr UINT kEventSignalPending = 0x1; // D3D12XBOX_FRAME_EVENT_STATISTICS_FLAG_SIGNAL_PENDING
struct BxXboxFrameEventStatistics { // D3D12XBOX_FRAME_EVENT_STATISTICS
UINT32 EventType;
UINT64 WaitCallTime;
UINT64 SignalTime;
UINT64 WaitReturnTime;
UINT32 IntervalOffsetInMicroseconds;
UINT32 SignalFlags;
UINT32 StatisticsFlags;
};
struct BxXboxPresentStatistics { // D3D12XBOX_PRESENT_STATISTICS
UINT8 PlaneIndex;
UINT8 PlaneCount;
UINT8 ViewCount;
UINT64 PresentCallTime;
UINT64 PresentQueueTime;
UINT64 PresentReturnTime;
UINT64 GPUProcessTime;
UINT8 QueuedFrameCount;
UINT16 PlaneSwapMask;
UINT32 Flags;
};
struct BxXboxFrameStatistics { // D3D12XBOX_FRAME_STATISTICS
UINT32 Type;
union {
BxXboxFrameEventStatistics Event;
BxXboxPresentStatistics Present;
UINT8 Bytes[48]; // the union's size: its largest members are 48 bytes
};
};
static_assert(sizeof(BxXboxFrameEventStatistics) == 48 && sizeof(BxXboxPresentStatistics) == 48, "statistics layout");
static_assert(sizeof(BxXboxFrameStatistics) == 56 && offsetof(BxXboxFrameStatistics, Event) == 8, "frame statistics layout");
HRESULT STDMETHODCALLTYPE bx_xbox_device_get_frame_statistics_x(void* self, UINT64 token, UINT type_set, UINT* count,
void* statistics);
// Records PresentX for its frame pipeline token (frame_pacing.cpp keeps the history).
void bx_xbox_frame_stats_present(UINT64 token, UINT64 call_time, UINT64 return_time);
struct BxXboxFrameWaitList {
UINT Count;
HANDLE* pObjects;
+2 -4
View File
@@ -189,8 +189,6 @@ static HRESULT STDMETHODCALLTYPE x_Device_72(void*) { BX_VTABLE_STUB_LOG("XboxDe
/* Xbox-only method */
static HRESULT STDMETHODCALLTYPE x_Device_77(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 77u, "CreateComponentPlacedResourceX1"); return E_NOTIMPL; }
/* Xbox-only method */
static HRESULT STDMETHODCALLTYPE x_Device_81(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 81u, "GetFrameStatisticsX"); return E_NOTIMPL; }
/* Xbox-only method */
static HRESULT STDMETHODCALLTYPE x_Device_82(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 82u, "CreateCounterSetX"); return E_NOTIMPL; }
static HRESULT STDMETHODCALLTYPE x_Device_83(void* self, const void * a0, SIZE_T a1, REFIID a2, void ** a3) {
BX_D3D_TRACE("XboxDevice", "CreatePipelineLibrary");
@@ -483,7 +481,7 @@ const void* const kDeviceTable[] = {
reinterpret_cast<const void*>(&bx_xbox_device_set_frame_interval_x),
reinterpret_cast<const void*>(&bx_xbox_device_schedule_frame_event_x),
reinterpret_cast<const void*>(&bx_xbox_device_wait_frame_event_x),
reinterpret_cast<const void*>(&x_Device_81),
reinterpret_cast<const void*>(&bx_xbox_device_get_frame_statistics_x),
reinterpret_cast<const void*>(&x_Device_82),
reinterpret_cast<const void*>(&x_Device_83),
reinterpret_cast<const void*>(&x_Device_84),
@@ -559,7 +557,7 @@ const IID kDeviceIids[] = {
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
};
/* ID3D12Device11: 139 slots (54 forwarded, 45 shared, 40 stubs); hosted on ID3D12Device10. */
/* ID3D12Device11: 139 slots (54 forwarded, 46 shared, 39 stubs); hosted on ID3D12Device10. */
const IID kHostDevice = __uuidof(ID3D12Device10);
static HRESULT STDMETHODCALLTYPE x_Resource_3(void* self, REFGUID a0, UINT * a1, void * a2) {
+89 -2
View File
@@ -3,6 +3,7 @@
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <new>
@@ -188,9 +189,93 @@ void sample_stick(int left, int right, int down, int up, float& x, float& y) {
}
}
/* 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));
}
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 < 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;
}
GamepadState sample_keyboard() {
GamepadState state{};
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},
@@ -205,7 +290,9 @@ GamepadState sample_keyboard() {
state.right_trigger = pressed('C') ? 1.0f : 0.0f;
sample_stick('A', 'D', 'S', 'W', state.left_x, state.left_y);
sample_stick('J', 'L', 'K', 'I', state.right_x, state.right_y);
return owns_foreground() ? state : GamepadState{};
if (!owns_foreground()) state = GamepadState{};
state.buttons |= scripted;
return state;
}
struct Sample {
+51
View File
@@ -1330,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;
@@ -1340,6 +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);
if (code == EXCEPTION_BREAKPOINT && continue_assert(ep)) return EXCEPTION_CONTINUE_EXECUTION;
return EXCEPTION_CONTINUE_SEARCH;
}
if (code == EXCEPTION_ACCESS_VIOLATION) {
+7 -3
View File
@@ -55,9 +55,13 @@ 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 physical-page destination: the span of xmem.dll pages this request writes through,
// mapped when it was enqueued and unmapped once it has been fulfilled (0 when unused).
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;
};
+120 -21
View File
@@ -456,6 +456,79 @@ CopyResult copy_staged(HANDLE file, const Request& request) {
return staged.finish(win32_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;
}
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;
}
/* 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 (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];
const DWORD n = GetEnvironmentVariableW(L"BX_BCPACK_DLL", path, MAX_PATH);
if (n == 0 || n >= MAX_PATH) return static_cast<BcpackDecompressFn>(nullptr);
HMODULE dll = LoadLibraryW(path);
auto found = dll ? reinterpret_cast<BcpackDecompressFn>(reinterpret_cast<void*>(GetProcAddress(dll, "BCPackDecompress")))
: nullptr;
char detail[96];
std::snprintf(detail, sizeof(detail), "BX_BCPACK_DLL %s (error %lu)", found ? "loaded" : "not usable",
found ? 0ul : GetLastError());
bx_log_emit(found ? BX_LOG_INFO : BX_LOG_WARN, "xcrdapi", "bcpack_codec", detail);
return found;
}();
return fn;
}
HRESULT bcpack_request(HANDLE file, const Request& request) {
const BcpackDecompressFn decompress = bcpack_decompress();
if (!decompress) return E_NOTIMPL;
if (!request.destination || !request.output_size || !request.size) return E_INVALIDARG;
auto* packed = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, request.size));
if (!packed) return E_OUTOFMEMORY;
HRESULT hr = read_bytes(file, request.file_offset, packed, request.source, request.size);
if (SUCCEEDED(hr)) {
RemapGuard remap_guard;
hr = decompress(request.bcpack_mode, request.destination, request.output_size, packed, request.size);
if (FAILED(hr)) {
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 16) {
char detail[160];
std::snprintf(detail, sizeof(detail), "BCPack BC%u stream of %lu bytes to %lu bytes: hr=0x%08lx", request.bcpack_mode,
request.size, request.output_size, static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_bcpack_failed", detail);
}
hr = E_DSTORAGE_DECOMPRESSION_ERROR;
}
}
HeapFree(GetProcessHeap(), 0, packed);
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));
@@ -463,8 +536,9 @@ HRESULT inflate_request(HANDLE file, const Request& request) {
HRESULT hr = read_bytes(file, request.file_offset, compressed, request.source, request.size);
if (SUCCEEDED(hr)) {
RemapGuard remap_guard;
const BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
request.output_size);
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) {
@@ -498,7 +572,8 @@ CopyResult fulfill(HANDLE file, const Request& 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;
@@ -515,6 +590,10 @@ CopyResult fulfill(HANDLE file, const Request& request) {
}
CopyResult fulfill_request(HANDLE file, const Request& request) {
if (request.compression == compression_bcpack && request.bcpack_mode) {
if (request.resource) return {E_NOTIMPL, false};
return {bcpack_request(file, request), false};
}
if (request.compression == compression_zlib) {
if (request.resource) return {E_NOTIMPL, false};
return {inflate_request(file, request), false};
@@ -571,6 +650,25 @@ MapPhysicalPagesFn map_physical_pages() {
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();
@@ -609,7 +707,8 @@ public:
Entry entry{Kind::request, *request};
if (request->resource) request->resource->AddRef();
// Uncompressed and zlib requests read the file; other compressions are refused when fulfilled.
if (request->file && (request->compression == compression_none || request->compression == compression_zlib)) {
if (request->file && (request->compression == compression_none || request->compression == compression_zlib ||
request->compression == compression_bcpack)) {
const HRESULT result = request->file->GetHandle(&entry.handle);
if (FAILED(result)) {
if (request->resource) request->resource->Release();
@@ -800,7 +899,8 @@ 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);
@@ -1598,7 +1698,10 @@ public:
return;
}
log_request_options(request->options, request->source_size, request->destination_size, request->reserved34);
if (request->options & kXboxRequestBcpackMask) {
// 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_mode > 7 || !bcpack_decompress())) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_bcpack");
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
@@ -1616,7 +1719,7 @@ public:
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
: request->source_size != request->destination_size)) {
: (!bcpack_mode && request->source_size != request->destination_size))) {
reject(E_DSTORAGE_INVALID_DESTINATION_SIZE, Kind::request, "EnqueueRequest");
return;
}
@@ -1627,6 +1730,10 @@ public:
if (zlib) {
translated.compression = compression_zlib;
translated.output_size = request->destination_size;
} else if (bcpack_mode) {
translated.compression = compression_bcpack;
translated.bcpack_mode = bcpack_mode;
translated.output_size = request->destination_size;
}
if (is_memory) {
if (!request->source_ptr) {
@@ -1649,24 +1756,16 @@ public:
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);
const MapPhysicalPagesFn map = map_physical_pages();
void* span = map ? map(nullptr, count, static_cast<PULONG_PTR>(request->destination)) : 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>(count), error);
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_page_destination", detail);
reject(HRESULT_FROM_WIN32(error), Kind::request, "EnqueueRequest");
if (!map_physical_pages()) {
reject(HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND), Kind::request, "EnqueueRequest");
return;
}
translated.destination = static_cast<BYTE*>(span) + request->destination_page_offset;
translated.page_span = span;
// 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;
}
const HRESULT queued = queue_->EnqueueRequest(&translated);
if (FAILED(queued)) unmap_page_span(translated);
accept(queued, Kind::request, "EnqueueRequest");
accept(queue_->EnqueueRequest(&translated), Kind::request, "EnqueueRequest");
}
void STDMETHODCALLTYPE EnqueueStatus(IXboxDStorageStatusArray* status_array, UINT32 index) override {
+13 -3
View File
@@ -191,7 +191,7 @@ uint32_t adler32(const uint8_t* data, size_t size) {
} // namespace
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
BxInflateResult inflate_impl(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size, size_t* produced) {
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
if (!input || input_size < 6 || (!output && output_size)) return BxInflateResult::bad_header;
const uint8_t cmf = input[0], flg = input[1];
@@ -225,7 +225,8 @@ BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t
if (r != BxInflateResult::ok) return r;
if (final_block) break;
}
if (out.pos != out.size) return BxInflateResult::output_mismatch;
if (produced) *produced = out.pos;
else if (out.pos != out.size) return BxInflateResult::output_mismatch;
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
in.align_to_byte();
const size_t trailer = in.pos - static_cast<size_t>(in.count / 8);
@@ -233,7 +234,16 @@ BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t
const uint8_t* t = in.data + trailer;
const uint32_t expected = (static_cast<uint32_t>(t[0]) << 24) | (static_cast<uint32_t>(t[1]) << 16) |
(static_cast<uint32_t>(t[2]) << 8) | t[3];
return adler32(output, output_size) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
return adler32(output, out.pos) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
}
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
return inflate_impl(input, input_size, output, output_size, nullptr);
}
BxInflateResult bx_zlib_inflate_any(const uint8_t* input, size_t input_size, uint8_t* output, size_t capacity, size_t* produced) {
*produced = 0;
return inflate_impl(input, input_size, output, capacity, produced);
}
const char* bx_inflate_result_name(BxInflateResult result) {
+4
View File
@@ -25,4 +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
(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);
@@ -0,0 +1,2 @@
add_executable(test_console_mode main.cpp)
target_link_libraries(test_console_mode PRIVATE xgameruntime advapi32 kernel32)
@@ -0,0 +1,69 @@
/*
* The console type in the registry. A title can read the REG_DWORD ConsoleMode under
* HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM instead of calling XSystemGetDeviceType
* (target-build observation): it opens the key with RegOpenKeyW, reads the value with
* RegQueryValueExW and maps 0x60 to Series S, 0x64 to Series X and 0x68 to the Scarlett devkit;
* with no key it takes itself for a PC and sizes its memory for Series X. The XSystemDeviceType
* numbers below are those of the authorized GDK (XboxScarlettLockhart 6, XboxScarlettAnaconda 7,
* XboxScarlettDevkit 8, Pc 1). This test reads the value the same way and checks it against the
* BetterXen profile (BX_PROFILE, as bx-cli run sets it) and against XSystemGetDeviceType.
*/
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" uint32_t WINAPI XSystemGetDeviceType();
namespace {
#define CHECK(condition) \
do { \
if (!(condition)) { \
std::fprintf(stderr, "console mode:%d: %s\n", __LINE__, #condition); \
return 1; \
} \
} while (false)
// The title's mapping of ConsoleMode to XSystemDeviceType, written out from the observation.
uint32_t device_type_for(DWORD mode) {
switch (mode) {
case 0x10: case 0x20: case 0x21: case 0x30: case 0x31: return 2; // XboxOne
case 0x40: return 3; // XboxOneS
case 0x50: return 4; // XboxOneX
case 0x58: return 5; // XboxOneXDevkit
case 0x60: return 6; // XboxScarlettLockhart
case 0x64: return 7; // XboxScarlettAnaconda
case 0x68: return 8; // XboxScarlettDevkit
default: return 0; // Unknown
}
}
} // namespace
int main() {
char profile[32] = {};
GetEnvironmentVariableA("BX_PROFILE", profile, sizeof(profile));
const bool anaconda = _stricmp(profile, "anaconda") == 0;
const DWORD expected_mode = anaconda ? 0x64 : 0x60;
HKEY key = nullptr;
CHECK(RegOpenKeyW(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM", &key) ==
ERROR_SUCCESS); // without it the title takes itself for a PC
DWORD mode = 0;
DWORD type = 0;
DWORD size = sizeof(mode);
const LSTATUS status = RegQueryValueExW(key, L"ConsoleMode", nullptr, &type, reinterpret_cast<BYTE*>(&mode), &size);
RegCloseKey(key);
CHECK(status == ERROR_SUCCESS);
CHECK(type == REG_DWORD && size == sizeof(DWORD));
std::printf("ConsoleMode=0x%lx profile=%s XSystemGetDeviceType=%u\n", static_cast<unsigned long>(mode),
anaconda ? "anaconda" : "lockhart", XSystemGetDeviceType());
CHECK(mode == expected_mode);
CHECK(device_type_for(mode) == (anaconda ? 7u : 6u));
CHECK(device_type_for(mode) == XSystemGetDeviceType()); // both ways of asking agree
std::puts("PASS: test_console_mode");
return 0;
}
@@ -0,0 +1,3 @@
add_executable(test_d3d12_frame_statistics_x main.cpp)
target_compile_definitions(test_d3d12_frame_statistics_x PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_frame_statistics_x PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,228 @@
/*
* GetFrameStatisticsX (Xbox device table slot 81), against the authorized GDK documentation:
* GetFrameStatisticsX(Token, TypeSet, pCount, pStatistics) returns S_OK when one or more sets of
* the requested types are available (written subject to list space, *pCount updated to the
* number written), S_FALSE when none is available yet, and E_INVALIDARG for unknown frame
* pipeline tokens, invalid type sets and invalid list arrangements. The runtime keeps the last
* 17 frames. Times are QueryPerformanceCounter values.
* D3D12XBOX_FRAME_STATISTICS is written out below from the header's field list: a 32-bit Type,
* then (8 bytes in) a union whose largest members are 48 bytes. Tokens come from WaitFrameEventX
* on the ORIGIN event; PresentX gets the token through its plane parameters.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr UINT kTypeFrameEvent = 0x2, kTypeRender = 0x100, kTypePresent = 0x1000;
constexpr UINT kOrigin = 0;
struct FrameEventStatistics {
UINT32 EventType;
UINT64 WaitCallTime;
UINT64 SignalTime;
UINT64 WaitReturnTime;
UINT32 IntervalOffsetInMicroseconds;
UINT32 SignalFlags;
UINT32 StatisticsFlags;
};
struct PresentStatistics {
UINT8 PlaneIndex;
UINT8 PlaneCount;
UINT8 ViewCount;
UINT64 PresentCallTime;
UINT64 PresentQueueTime;
UINT64 PresentReturnTime;
UINT64 GPUProcessTime;
UINT8 QueuedFrameCount;
UINT16 PlaneSwapMask;
UINT32 Flags;
};
struct FrameStatistics {
UINT32 Type;
union {
FrameEventStatistics Event;
PresentStatistics Present;
UINT8 Bytes[48];
};
};
static_assert(sizeof(FrameStatistics) == 56 && offsetof(FrameStatistics, Event) == 8, "D3D12XBOX_FRAME_STATISTICS");
struct PlaneParameters { // D3D12XBOX_PRESENT_PLANE_PARAMETERS
UINT64 Token;
UINT ResourceCount;
void** ppResources;
D3D12_RECT* pSrcViewRects;
void* pDestPlacementBase;
UINT ColorSpace;
UINT ScaleFilter;
UINT ExtendedDescCount;
void* pExtendedDescs;
UINT Flags;
};
constexpr int kRelease = 2, kDevCreateCommandQueue = 8, kDevCreateCommittedResource = 27;
constexpr int kDevSetFrameIntervalX = 78, kDevScheduleFrameEventX = 79, kDevWaitFrameEventX = 80;
constexpr int kDevGetFrameStatisticsX = 81, kQueuePresentX = 32;
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 CreateQueueFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_COMMAND_QUEUE_DESC*, REFIID, void**);
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, REFIID, void**);
using SetIntervalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT, UINT, UINT);
using ScheduleFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, UINT, const void*, UINT);
using WaitFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, UINT, const void*, UINT, UINT64*);
using StatsFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, UINT, UINT*, FrameStatistics*);
using PresentFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const PlaneParameters*, const void*);
int g_failed = 0, g_checks = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_frame_statistics_x:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
} // namespace
int main() {
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004;
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_frame_statistics_x: 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;
}
auto stats = slot<StatsFn>(dev, kDevGetFrameStatisticsX);
FrameStatistics out[4]{};
UINT count = 4;
// Invalid arrangements, type sets and tokens.
CHECK(stats(dev, 1, kTypeFrameEvent, nullptr, out) == E_INVALIDARG, "null pCount");
CHECK(stats(dev, 1, 0, &count, out) == E_INVALIDARG, "empty type set");
count = 4;
CHECK(stats(dev, 1, 0x8, &count, out) == E_INVALIDARG, "unknown type bit");
count = 4;
CHECK(stats(dev, 1, kTypeFrameEvent, &count, nullptr) == E_INVALIDARG, "entries but no list");
count = 4;
CHECK(stats(dev, 0, kTypeFrameEvent, &count, out) == E_INVALIDARG, "token 0");
count = 4;
CHECK(stats(dev, 1ull << 40, kTypeFrameEvent, &count, out) == E_INVALIDARG, "token never issued");
// One frame: the ORIGIN event gives a token.
CHECK(slot<SetIntervalFn>(dev, kDevSetFrameIntervalX)(dev, nullptr, 16667, 1, 0) == S_OK, "SetFrameIntervalX");
CHECK(slot<ScheduleFn>(dev, kDevScheduleFrameEventX)(dev, kOrigin, 0, nullptr, 0) == S_OK, "ScheduleFrameEventX");
auto wait = slot<WaitFn>(dev, kDevWaitFrameEventX);
UINT64 token = 0;
hr = wait(dev, kOrigin, 2000, nullptr, 0, &token);
CHECK(hr == S_OK && token != 0, "WaitFrameEventX(ORIGIN) hr=0x%08lx token=%llu", static_cast<unsigned long>(hr),
static_cast<unsigned long long>(token));
count = 4;
hr = stats(dev, token, kTypeFrameEvent, &count, out);
CHECK(hr == S_OK && count == 1, "FRAME_EVENT: hr=0x%08lx count=%u", static_cast<unsigned long>(hr), count);
if (hr == S_OK && count == 1) {
const FrameEventStatistics& e = out[0].Event;
CHECK(out[0].Type == kTypeFrameEvent && e.EventType == kOrigin, "FRAME_EVENT type %u event %u", out[0].Type,
e.EventType);
CHECK(e.SignalTime && e.WaitCallTime && e.WaitReturnTime >= e.SignalTime && e.WaitReturnTime >= e.WaitCallTime,
"FRAME_EVENT times wait=%llu signal=%llu return=%llu", static_cast<unsigned long long>(e.WaitCallTime),
static_cast<unsigned long long>(e.SignalTime), static_cast<unsigned long long>(e.WaitReturnTime));
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
CHECK(e.WaitReturnTime <= static_cast<UINT64>(now.QuadPart), "times are QueryPerformanceCounter values");
}
count = 4;
CHECK(stats(dev, token, kTypePresent, &count, out) == S_FALSE && count == 0, "PRESENT before PresentX: S_FALSE");
count = 4;
CHECK(stats(dev, token, kTypeRender, &count, out) == S_FALSE && count == 0, "RENDER (no host source): S_FALSE");
// PresentX with that token records the present.
D3D12_COMMAND_QUEUE_DESC queue_desc{};
queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
void* queue = nullptr;
hr = slot<CreateQueueFn>(dev, kDevCreateCommandQueue)(dev, &queue_desc, __uuidof(ID3D12CommandQueue), &queue);
CHECK(hr == S_OK && queue, "CreateCommandQueue hr=0x%08lx", static_cast<unsigned long>(hr));
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
D3D12_RESOURCE_DESC rt{};
rt.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
rt.Width = 64;
rt.Height = 64;
rt.DepthOrArraySize = 1;
rt.MipLevels = 1;
rt.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
rt.SampleDesc.Count = 1;
rt.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
void* target = nullptr;
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &heap, D3D12_HEAP_FLAG_NONE, &rt,
D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), &target);
CHECK(hr == S_OK && target, "render target hr=0x%08lx", static_cast<unsigned long>(hr));
if (queue && target) {
PlaneParameters plane{};
plane.Token = token;
plane.ResourceCount = 1;
plane.ppResources = &target;
slot<PresentFn>(queue, kQueuePresentX)(queue, 1, &plane, nullptr);
count = 4;
hr = stats(dev, token, kTypeFrameEvent | kTypePresent, &count, out);
CHECK(hr == S_OK && count == 2, "FRAME_EVENT|PRESENT after PresentX: hr=0x%08lx count=%u",
static_cast<unsigned long>(hr), count);
for (UINT i = 0; i < count; ++i) {
if (out[i].Type != kTypePresent) continue;
const PresentStatistics& p = out[i].Present;
CHECK(p.PresentCallTime && p.PresentReturnTime >= p.PresentCallTime && p.PlaneCount == 1,
"PRESENT call=%llu return=%llu planes=%u", static_cast<unsigned long long>(p.PresentCallTime),
static_cast<unsigned long long>(p.PresentReturnTime), p.PlaneCount);
}
// A size query (no list) reports how many are available; a short list gets what fits.
count = 0;
CHECK(stats(dev, token, kTypeFrameEvent | kTypePresent, &count, nullptr) == S_OK && count == 2, "size query: %u",
count);
count = 1;
CHECK(stats(dev, token, kTypeFrameEvent | kTypePresent, &count, out) == S_OK && count == 1, "short list: %u",
count);
}
// Seventeen frames later the token has no statistics left.
UINT64 later = token;
for (int i = 0; i < 18; ++i) wait(dev, kOrigin, 2000, nullptr, 0, &later);
count = 4;
CHECK(stats(dev, token, kTypeFrameEvent, &count, out) == S_FALSE && count == 0, "token 18 frames old: S_FALSE");
count = 4;
CHECK(stats(dev, later, kTypeFrameEvent, &count, out) == S_OK && count == 1, "latest token: S_OK");
if (target) slot<ReleaseFn>(target, kRelease)(target);
if (queue) slot<ReleaseFn>(queue, kRelease)(queue);
slot<ReleaseFn>(dev, kRelease)(dev);
if (g_failed) {
std::printf("FAIL: test_d3d12_frame_statistics_x (%d of %d checks failed)\n", g_failed, g_checks);
return 1;
}
std::printf("PASS: test_d3d12_frame_statistics_x (%d checks)\n", g_checks);
return 0;
}
@@ -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;
}
@@ -274,7 +274,7 @@ int main() {
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(4, "pages", kXboxStatusArrayIid, reinterpret_cast<void**>(&status)) : E_FAIL;
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;
@@ -339,6 +339,29 @@ int main() {
"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();
}
@@ -384,6 +407,23 @@ int main() {
"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();
}