Compare commits

...
Author SHA1 Message Date
ates 10238c33b4 d3d12_xs: draw console rectangle lists as triangle strips
D3D_PRIMITIVE_TOPOLOGY_RECTLIST (17) and D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT
(19) are Xbox extensions: three vertices per rectangle, the fourth corner
v0 + v2 - v1. The host knows neither value; a title's full-screen passes
drew half a rectangle or nothing.

- Pipelines are created with the triangle topology type when the title
  asks for a console type, and their input layout is remembered.
- IASetPrimitiveTopology(RECTLIST) sets TRIANGLESTRIP on the host.
- A non-indexed draw builds four vertices per rectangle (order v1, v2,
  v0, v3, which keeps the winding) in a host upload ring, from the
  title's slot-0 vertex data and the pipeline's input layout, then puts
  the title's binding back.
- Indexed rectangle lists, layouts with per-vertex data outside slot 0
  and unhandled element formats are logged as unimplemented.

test_d3d12_rect_list renders through an Xbox-layout device and reads the
pixels back: full coverage and the computed fourth corner for one
rectangle, two rectangles in one draw from a non-zero first vertex, an
ordinary triangle list afterwards, and the unimplemented log for an
indexed rectangle list. 25 of 25 checks, twice in a row; against main's
d3d12_xs the host never completes the work.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 22:02:21 +03:00
Ateş f6bec97548 Merge pull request #693 from MacosPorters/track-c/unbacked-buffer-bindings
[Boot] null read in D3DMetal under IASetIndexBuffer: unbacked index and vertex bindings
2026-11-29 20:41:25 +03:00
ates 638673a173 Merge remote-tracking branch 'origin/main' into track-c/unbacked-buffer-bindings
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 20:41:08 +03:00
Ateş 7feebe38f6 Merge pull request #690 from MacosPorters/track-c/console-only-formats
[Boot] Metal abort: console-only DXGI formats and depth-stencil unordered-access views
2026-11-29 20:40:14 +03:00
ates 00c270062b tests: conformance test for unbacked index and vertex bindings
test_d3d12_unbacked_buffers records into an Xbox-layout command list:
bindings inside a committed buffer (translated, not logged), an index
binding and the second of two vertex streams in plain title memory
(each left empty and logged as unimplemented exactly once), and null
bindings (unchanged, not logged). The list must still close.

Against main's d3d12_xs the process dies with a read at 0xa8 inside
D3DMetal, the same fault the target build hit. 13 of 13 checks pass
with the fix, twice in a row.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 20:19:39 +03:00
ates 4389f74b2b d3d12_xs: leave index and vertex bindings empty when the address has no host buffer
A title binds index and vertex data by address in plain title memory,
with no Direct3D resource behind it. The address was passed to the host
unchanged and D3DMetal dereferenced the buffer it failed to find (a
null read under IASetIndexBuffer). Such a binding is now left empty and
logged as unimplemented. Supplying the data is separate work.

Work in progress: no conformance test or changelog entry yet.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 18:50:57 +03:00
ates 0ab348cb5d tests: conformance test for console-only formats and depth-stencil unordered-access views
test_d3d12_console_formats drives an Xbox-layout device through its
function table: allocation info in all three forms for format 118 and
the four colour formats (expected sizes are the host's answers for the
documented substitute formats, asked for directly), a committed depth
texture and clear value in format 118, depth-stencil and plane views in
formats 118, 119 and 120, and an unordered-access view on a
depth-stencil texture, which must be logged as unimplemented exactly
once while a view on an ordinary texture is not.

Against main's d3d12_xs the process dies in Metal at the first
console-only format. 21 of 21 checks pass with the fix, twice in a row.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 18:46:49 +03:00
ates 46e7135f6c d3d12_xs: translate console-only DXGI formats and refuse depth-stencil UAVs before the host sees them
The Xbox Series DXGI_FORMAT enumeration has values the PC one lacks
(116-120, 189, 190). D3DMetal turns one into an invalid Metal pixel
format and Metal aborts the process, so no error code comes back. A
title also creates unordered-access views on depth-stencil textures,
which the console allows and PC Direct3D 12 forbids; D3DMetal answers
with a Metal texture view that Metal refuses, again by aborting.

- console_formats.h: bx_host_format and bx_host_resource_format map
  each console-only format to the nearest host format. A depth texture
  is created typeless and each view names the concrete format.
- The three GetResourceAllocationInfo forms, CreatePlacedResource,
  CreateReservedResource, the four view-creation methods, the four
  committed-resource forms, CreatePlacedResourceX and the four placed
  view forms translate before calling the host.
- An unordered-access view on a depth-stencil resource becomes a null
  view of the same description and is logged as unimplemented.

The Xbox device table routes nine more slots to hand-written entry
points (generated by tools/gen_xbox_tables.py).

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 18:29:48 +03:00
Ateş bff53517be Merge pull request #685 from MacosPorters/track-e/667-gamesave-container-info
[Boot] xgameruntime: serve IXGameSaveImpl slots 13 and 15
2026-11-29 16:57:49 +03:00
ates 6898077c20 Merge remote-tracking branch 'origin/main' into fix-685
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 16:57:18 +03:00
Ateş 49585b92b0 Merge pull request #686 from MacosPorters/track-e/666-async-run-task-queues
[Boot] xgameruntime: XAsyncRun and task-queue duplicate, port and composite
2026-11-29 16:56:23 +03:00
ates c2f5652694 Merge remote-tracking branch 'origin/main' into track-e/666-async-run-task-queues
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 16:56:09 +03:00
Ateş 41b755014a Merge pull request #687 from MacosPorters/track-a/664-run-tooling
[Boot] bx-cli: run reports and blocker signatures (#664, part 1)
2026-11-29 16:55:22 +03:00
ates 9d5ecf39e4 Merge remote-tracking branch 'origin/main' into track-a/664-run-tooling
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 16:55:07 +03:00
Ateş d910e43df3 Merge pull request #682 from MacosPorters/track-e/680-xuser-duplicate
[Boot] xgameruntime: XUserDuplicateHandle through IXUser slot 3
2026-11-29 16:54:25 +03:00
Ateş c0aaaa005b Merge pull request #681 from MacosPorters/track-a/665-clzero-loop
[Boot] runtime_veh: complete a CLZERO loop in one exception
2026-11-29 16:54:03 +03:00
ates 69242d1215 Merge remote-tracking branch 'origin/main' into track-a/664-run-tooling
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	launcher/crates/bx-cli/src/main.rs
2026-11-29 16:50:36 +03:00
ates 808c5d17c5 Merge remote-tracking branch 'origin/main' into track-e/680-xuser-duplicate
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 16:50:01 +03:00
ates 23d631e3c7 Merge remote-tracking branch 'origin/main' into track-a/665-clzero-loop
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 16:49:50 +03:00
Ateş 64f9b1dcb5 Merge pull request #684 from MacosPorters/track-c/669-serialized-pipelines-fail
[Boot] d3d12_xs: fail serialized and derived pipeline calls in null-render mode
2026-11-29 15:44:46 +03:00
Ateş 740df46b10 Merge pull request #689 from MacosPorters/process/agent-self-setup
[Process] A collaborator only says "work": the agent makes the machine ready itself
2026-11-29 15:44:23 +03:00
ates a648cdecc7 A collaborator only says 'work': the agent makes the machine ready itself
AGENTS.md section 0, step 1 told an agent whose preflight failed to stop
and hand the setup back to its person. It now fixes what it can and
stops only for what it cannot supply.

bx-cli setup --find searches the home folder and saves both settings:
- the GDK is recognised by its d3d12_xs.h and remembered as the first
  folder below Documents, Downloads, Desktop, Developer or Projects (or
  below home);
- the target build is recognised by structure, never by name: a PE32+
  file of at least 16 MiB that imports d3d12_xs.dll;
- executables inside the GDK folder are its own tools, not titles;
- byte-identical copies are one build, and the copy kept is the one
  with the most of its imported DLLs beside it, which is the
  installation rather than a stray copy;
- hidden folders, Library, application bundles and build folders are
  not searched, and the walk is bounded.
A target build is saved only when exactly one distinct build is found;
choosing between builds is the collaborator's decision.

The agent may also install mingw-w64, cmake and gh with Homebrew and
free disk space by removing its own scratch. It stops for: no Apple
Silicon Mac, CrossOver not installed, the build or the GDK not on the
machine, or more than one distinct build.

On the authoring Mac the search took about a second and chose the
installation among four identical copies and two GDK tools.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 15:42:41 +03:00
Ateş 911c27f62b Merge pull request #688 from MacosPorters/process/pr-first-required-materials
[Process] Pull requests are the unit of work; the target build and the GDK are required
2026-11-29 15:36:48 +03:00
ates 9b9c3c63ee bx-cli setup: remember where the target build and the GDK are
Environment variables have to be set in every shell, and an agent's
shell often does not inherit them. bx-cli setup --target-exe <path>
--gdk-root <folder> checks each path with the same rules as preflight
and saves it in ~/.config/betterxen/local.conf (or under
XDG_CONFIG_HOME): outside every checkout, so it cannot be committed,
and shared by every worktree, shell and agent session of that user.
Preflight reads it; BX_TARGET_EXE and BX_GDK_ROOT still override it for
one command. With no arguments, setup shows what is saved as present or
missing without printing a path.

The repository cannot find the target build itself, because it must
never contain the build's file name; the collaborator names it once.

AGENTS.md section 0 and the working method describe setup. The unit
test covers writing and reading the settings, unknown keys, comments
and the override order.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 15:35:08 +03:00
ates b16bdc1d4a Rules: pull requests are the unit of work; the target build and GDK are required
Two decisions by the repository owner:

1. No agent works without the target build and the GDK. bx-cli preflight
   (new) fails unless the host is an Apple Silicon Mac with CrossOver,
   D3DMetal and mingw-w64, BX_TARGET_EXE names the target build's
   executable, BX_GDK_ROOT is a folder holding the GDK (its d3d12_xs.h is
   found by a bounded walk), and 10 GiB of disk is free. It prints no
   local path. AGENTS.md section 0 makes it step 1: if it fails, the
   agent stops and does no work.

2. A blocker an agent can fix gets a pull request, not an issue. The
   agent runs the build, takes the first signature no open pull request
   covers, and claims it with a draft pull request titled with that
   signature. Issues remain for handoffs (label handoff), decisions for
   a person, and the ladder status. Claim comments and the 7-day stale
   window are removed; an idle draft may be taken over after 3 days.

The working method is rewritten to match and explains why: an issue of
the form 'the build stops at X' is a fact about one run on one machine,
while the conformance test holds everywhere.

A unit test covers the target-build and GDK checks and the not-ready
verdict.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 15:31:16 +03:00
ates 340cd1deec bx-cli: run reports and blocker signatures (#664, part 1)
bx-cli report <log.jsonl>... treats each log as one run and prints, per
run: how it ended, the frames presented (a lower bound), every
unimplemented call with its count, faults whose innermost frame is in a
BetterXen module, and pipelines by kind. A summary then counts clean
runs and lists each blocker signature with the number of runs that hit
it. Blocker issues are titled with those signatures, so two people who
hit the same thing file the same issue.

bx-cli run appends a run_end record to its log (exited with a status,
timeout, signal, launch failure). A log without it has an unknown
outcome and is never counted as clean.

The report says what a log cannot show instead of guessing: stall
detection is not attempted, because frames are logged at powers of two.

Seven unit tests on synthetic logs cover the signatures, the fault
module rule, the run endings, pipeline counts, the summary and
non-record lines.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 15:15:37 +03:00
erkinemreta1 ab7863142e test_xgameruntime_saves: isolate slot 15 prefix checks in their own provider
Signed-off-by: erkinemreta1 <erkinemreta1@users.noreply.github.com>
2026-11-29 15:07:47 +03:00
Ateş 21700c2869 Merge pull request #683 from MacosPorters/docs/working-method-accepted
[Process] The working method is in effect; point to the ladder issue
2026-11-29 14:56:57 +03:00
ates a4026459d9 xgameruntime: XAsyncRun and task-queue duplicate, port and composite (#666)
IXGameRuntimeCore slots 6, 13, 14 and 15, by the declaration order of
the public XAsync.h and XTaskQueue.h:
- XAsyncRun runs the title's work callback on the block's work port and
  completes the block with the callback's HRESULT.
- XTaskQueueDuplicateHandle returns another handle to the same queue;
  closing a handle shuts the queue's lanes down only when it is the
  last one.
- XTaskQueueGetPort returns a port handle, and
  XTaskQueueCreateComposite makes a queue whose ports forward to the
  ports it was made from.
- An async block's completion is submitted through the queue the block
  named, so on a composite it reaches the composite's completion port
  (the task itself runs with the queue that owns the lane).

A project-authorized target build uses these for its save-game work and
exited with status 1 when XAsyncRun returned E_NOTIMPL.

test_xgameruntime checks each through QueryApiImpl: work and completion
ports, a failing work callback's status, a duplicate surviving the
original's close, forwarding in both directions, XAsyncRun on a
composite, and refusals. It fails on the previous runtime at the first
XAsyncRun call.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 14:50:36 +03:00
erkinemreta1 80fb4cc1f6 xgameruntime: serve IXGameSaveImpl slots 13 and 15
Signed-off-by: erkinemreta1 <erkinemreta1@users.noreply.github.com>
2026-11-29 14:45:06 +03:00
erkinemreta1 77af218878 d3d12_xs: fail serialized and derived pipeline calls in null-render mode
Signed-off-by: erkinemreta1 <erkinemreta1@users.noreply.github.com>
2026-11-29 14:08:41 +03:00
Ateş da82407073 Merge pull request #650 from MacosPorters/track-d/649-shader-corpus
[M3-D3] shader-transpiler: Phase 0 corpus of console-compiled kernels with known source
2026-11-29 13:01:13 +03:00
ates 2e55cf2259 Merge main; BetterXen is no longer a clean-room project (#650)
Merges current main (conflict: CHANGELOG.md only) and records the
repository owner's decisions of 2026-11-29 that resolve review point 1:
- the team approved publishing layout facts derived from the GDK
  compilers' output for BetterXen's own source;
- BetterXen is no longer a clean-room project. CONTRIBUTING.md says
  that material the project is authorized to use may be used and that
  facts derived from it may be committed, while the material and its
  outputs are never committed; leaked or unauthorized material stays
  forbidden. README.md, docs/README.md and docs/legal.md no longer call
  the project clean-room; the corpus README states the decision.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 13:00:39 +03:00
ates 620019564b xgameruntime: restore the XUserDuplicateHandle implementation (#680)
The previous commit on this branch recorded main's com_dispatch.cpp and
xgameruntime.cpp by mistake (they had been restored into the index for
the negative-control run), which removed the fix and left only its
test. This puts the implementation back; it is the code the fixture was
built and run against.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:46:43 +03:00
ates 36a0f3f6c5 xgameruntime: XUserDuplicateHandle through IXUser slot 3 (#680)
Slot 3 follows the public XUser.h order (duplicate, close, compare). A
duplicate is a new handle to the one offline user; each handle is closed
on its own; XUserCompare returns 0 for two valid handles of that user.
A project-authorized target build duplicates its user handle after
sign-in and waited when the slot returned E_NOTIMPL.

test_xgameruntime obtains a user, duplicates it through the slot, and
checks comparison, independent closing, refusal of a closed handle with
the out pointer cleared, and E_POINTER. It fails on the previous
runtime. Built and run on D3DMetal; the earlier WIP commit on this
branch holds the code.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:38:36 +03:00
ates 29c8a29051 Merge remote-tracking branch 'origin/main' into track-e/680-xuser-duplicate 2026-11-29 11:37:55 +03:00
ates 6db66dc4a4 Merge remote-tracking branch 'origin/main' into track-a/665-clzero-loop 2026-11-29 11:36:35 +03:00
ates 9239ba6551 WIP: XUserDuplicateHandle through IXUser slot 3 (#680), not yet built or tested
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:22:02 +03:00
ates ef58b18147 shader corpus: skip only literal-form v_nop; synthetic test words; reproducibility
Review of #650:
- extract_code.py treated every leading word with top bits 0xD580 as a
  12-byte v_nop_xbox_data. A plain v_nop (8 bytes) there would have been
  skipped as 12 and misaligned the rest. It now requires the literal
  operand (third source operand 255) that makes the instruction 12
  bytes. Two unit tests cover a plain v_nop at the start and after
  hash words.
- The test's hash words are replaced by obviously synthetic values of
  the same shape.
- README: the reproducibility limit is stated; build.sh writes
  SHA256SUMS of the compiled inputs for cross-checking between people
  with the compilers. Wording: the v_nop opcode is public, its literal
  form is what the public decoder rejects; the listing is compiler
  output, not Microsoft documentation. The contradiction about
  publishing is replaced by a plain statement that the layout facts are
  published and that this waits for a maintainer decision.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:16:58 +03:00
ates 2deada1f9d Merge remote-tracking branch 'origin/main' into fix-650-corpus
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 11:15:49 +03:00
ates 65eef5b08e runtime_veh: complete a CLZERO loop in one exception (#665)
A title that zeroes memory with
    clzero ; add rax, 0x40 ; cmp rax, <reg64> ; jb <the clzero>
raised one illegal-instruction exception per 64 bytes under Rosetta 2.
A project-authorized target build spent tens of seconds of its frame
loop there (more than two million exceptions in a run).

When the trapped CLZERO is followed by exactly that form, the handler
zeroes every remaining line below the limit and leaves RAX at the last
one, so the title's own add/cmp/jb leaves the loop. The range is zeroed
region by region and stops at memory that is not committed and writable;
the title's next CLZERO then traps and faults as before. Any other loop
form keeps the per-instruction path.

test_veh_clzero_loop runs its own machine-code loops, checks the memory
result line by line with sentinels, and counts illegal-instruction
exceptions with a handler registered ahead of BetterXen's: one per
recognised loop, one per line otherwise, three for a range that runs
into a read-only page. On the old handler five of its sixteen checks
fail.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:14:52 +03:00
ates e57046a17d shader-transpiler: Phase 0 corpus of console-compiled kernels with known source (#649)
Eight BetterXen-authored compute kernels, a build script that compiles each locally with the console xdxc (DXIL + ACCC/FSPX), the console PIX compiler (ISA listing) and the PC DXC (DXIL), and an extractor that takes the FSPX kind-6 code section, skips v_nop_xbox_data and disassembles it with llvm-mc gfx1030. All eight build and decode cleanly. Compiler outputs stay in the git-ignored target/shader-corpus/. The extractor has unit tests on synthetic containers.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 19:11:57 +03:00
53 changed files with 4718 additions and 189 deletions

No files matched your search

+52 -24
View File
@@ -8,55 +8,83 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
Collaborators point their agent at this repository and say "work" (or "contribute", "continue", "what next?"). That is a complete instruction. Do not ask what to work on: follow this section. The method behind it is in [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md).
**"Work" authorizes, for the one item you pick:** posting a claim or a review, committing with DCO sign-off, pushing a branch, and opening a pull request. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
**"Work" authorizes, for the one item you pick:** opening a draft pull request, posting a review, committing with DCO sign-off, and pushing a branch. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
### Step 1 — Preflight
### Step 1 — Preflight: make the machine ready yourself
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`. If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`). Verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor`. It must report the toolchain, CrossOver, at least 10 GB of free disk space, and no other game run on this machine.
- Work in your own worktree and your own bottle. Never use a bottle another session is using.
```sh
cargo build --locked -p bx-cli && target/debug/bx-cli preflight
```
`bx-cli preflight` must print `Ready to work.` It requires **all** of:
| Required | How it is found |
| --- | --- |
| An Apple Silicon Mac with CrossOver 26.3+, D3DMetal and `mingw-w64` | Checked on the host |
| **The project-authorized target build** | Found and saved by `bx-cli setup --find` |
| **The GDK** (headers and compilers, under the project's authorization) | Found and saved by `bx-cli setup --find` |
| At least 10 GiB of free disk space | Measured |
**If preflight fails, fix it yourself and run it again.** Your person said "work"; do not hand the setup back to them.
| `MISSING` line | What you do |
| --- | --- |
| Target build, GDK | `target/debug/bx-cli setup --find`. It searches the home folder, recognises the GDK by its header and the build by its structure (never by name), and saves both. |
| `mingw-w64 g++` (also `cmake`, `gh`) | `brew install mingw-w64 cmake gh`. Being told to "work" authorizes installing these three. |
| Free disk space | Remove your own scratch: build folders and scratch bottles of worktrees you created. Never another session's files. |
**Stop only for what an agent cannot supply**, and say exactly which:
- the host is not an Apple Silicon Mac;
- CrossOver is not installed (it is licensed software; do not install it);
- `setup --find` reports that the target build or the GDK is not on this machine, or found more than one distinct build (which build to use is your person's choice: they run `bx-cli setup --target-exe <path>` once).
In those cases do not work around it: no fixes, tests or reviews "for someone else to verify". Work here is found by running the target build and checked against the GDK; an agent without them is guessing.
Also check `git`, `gh` (`gh auth status`; if not logged in, ask the user to run `gh auth login`), `cargo`, `cmake` and `python3`; verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`); sync with `origin/main`. Work in your own worktree and your own bottle; never use a bottle another session is using.
`bx-cli setup` remembers the two locations in `~/.config/betterxen/local.conf`, outside every checkout, so it happens once per machine and works in every worktree, shell and agent session. (`BX_TARGET_EXE` and `BX_GDK_ROOT` override it for one command.) Never commit those paths, and never put a path, file name, hash or byte from the target build or the GDK into a commit, issue or pull request (Section 6).
### Step 2 — Pick exactly one thing, in this order
Take the first that applies. Do not skip ahead because a later one looks more interesting.
Take the first that applies.
1. **Your person's pull requests that need attention.**
```sh
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,statusCheckRollup,mergeStateStatus
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,isDraft,reviewDecision,statusCheckRollup,mergeStateStatus
```
If one has requested changes, unresolved review comments, failing checks or conflicts: fix that pull request. Resolve every review point, re-run Section 8, push, and reply to each point.
Requested changes, unresolved review comments, failing checks, conflicts, or a draft you opened and have not finished: do that. Resolve every review point, re-run Section 8, push, and reply to each point.
2. **Review someone else's pull request.**
```sh
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,reviewDecision,isDraft,createdAt
```
Take the oldest open, non-draft pull request that your person did not open and that has no current review. Check out its branch, run Section 8 and its new test, confirm the test fails without the fix, read its proof, and post an approval or a change request with what you ran. If it needs deep review (the list is in the working method) and you can give one, do. If it is approved, green and not your person's, merge it (Section 7).
Take the oldest open, non-draft pull request that your person did not open and that has no current review. Check out its branch, run Section 8 and its new test **twice in a row**, confirm the test fails without the fix, and post an approval or a change request with what you ran. If it is approved, green and not your person's, merge it (Section 7).
3. **Fix one blocker of the current stage.**
3. **A handoff issue of the current stage.**
```sh
gh issue list --repo MacosPorters/betterxen --state open --label blocker --label "stage: <current>" --json number,title,labels,comments
gh issue list --repo MacosPorters/betterxen --state open --label handoff --label "stage: <current>" --json number,title,labels
```
The current stage is named on the pinned issue labelled `ladder`. Take the top unclaimed blocker: those labelled `first`, then lowest number. A blocker is claimed if it has a `Claiming —` comment less than 3 days old or an open pull request. Then follow Step 3.
A handoff is something a collaborator found and could not finish. The current stage is named on the pinned issue labelled `ladder`. Take the lowest-numbered one that no open pull request mentions, and follow Step 3.
4. **Discover.** If the current stage has no unclaimed blocker, run the stage's gate check (ten runs, [run protocol](docs/process/working-method.md#run-protocol)). For each signature in the report that has no issue, open or closed, file a blocker issue in the fixed shape. If the gate passes, post the ten-run result on the ladder issue and label it `needs-human`.
4. **Run the target build and fix the first thing it stops on.** Run it under the [run protocol](docs/process/working-method.md#run-protocol) and read `bx-cli report`. Take the first signature in the report that no open pull request is titled with or mentions, and follow Step 3. A blocker you can see and fix needs **no issue**: the pull request is the record.
5. **Nothing applies.** Say so and stop. Do not invent work, open research documents, or start on a later stage's blockers while the current stage has claimed, unfinished ones — unless your person tells you to.
5. **The run stops on nothing.** Make the stage's gate check (ten runs). If it passes, post the result on the ladder issue and label it `needs-human`; a person confirms the stage change. Then stop.
**Stop and label `needs-human`** whenever the next step is a decision that is not yours: a decision gate, a licence or provenance question, sources of truth that disagree, or a rule change.
### Step 3 — Work one blocker
1. **Claim:** comment `Claiming — branch: track-<a..f>/<issue>-<slug>` and branch from `origin/main`.
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. If you cannot explain the blocker in this session, write what you learned on the issue, release the claim, and stop. Do not guess a fix.
1. **Claim with a draft pull request, before writing the fix.** Branch `track-<a..f>/<slug>` from `origin/main`, push it with an empty commit or the first small change, and open a **draft** pull request titled `[<Stage>] <signature>`. Before opening it, list open pull requests once more; if one now covers the signature, take the next signature instead. A draft with no push for 3 days may be taken over; say so on it.
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. Check the contract against the GDK where the GDK covers it.
3. **Smallest fix:** only what removes this blocker. Stay inside the track directories it needs (Section 2); a new cross-DLL export goes through an `[ABI]` pull request first.
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix.
5. **Verify:** every command in Section 8. Without CrossOver you can still run the Rust checks, `scripts/build-shims.sh` and the docs check; say plainly which live checks were not run. Never report an unrun check as passed.
6. **Proof:** ten runs before and ten after, every run reported, with the machine and the `main` commit.
7. **Pull request:** one blocker; the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof); `Closes #<issue>`; DCO sign-off; no AI trailers. Watch CI until `Hybrid build and shim checks` and `Repository hygiene` pass.
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix and passes twice in a row. The test is what holds on every machine; your run is only why you looked.
5. **Verify:** every command in Section 8.
6. **Proof:** runs before and after on your machine, every run reported, with the machine and the `main` commit. Another collaborator's machine may never take the path yours took; say which path your runs took.
7. **Finish:** fill in the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof), sign off, no AI trailers, mark the pull request ready. Do not wait for CI before moving on.
8. **Stop.** The next "work" starts again at Step 2.
Nothing from the target build goes into a commit, issue or pull request (Section 6): keep run logs, dumps and captures in your private evidence folder outside the repository.
**If you cannot fix what you found** (too large, out of session, or it needs a decision): close your draft, file one **handoff issue** labelled `handoff` and `stage: <name>`, titled `[handoff] <signature>`, with what you saw, what you tried and what is still unknown. That is the only time a blocker gets an issue.
---
@@ -128,10 +156,10 @@ _Reserved — policy migration in progress._
## 7. Claiming, Git Safety & Changelog
1. **Check before coding (open backlog issues):** When picking an unclaimed backlog issue, read every comment and check open PRs so you never claim over an active claim; reply `Claiming — branch: track-<a..f>/<issue>-<slug>` (stale after 7 days without commits/PR). Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
1. **Check before coding (claims):** A blocker is claimed by an open draft pull request titled with its signature (Section 0, Step 3); check open pull requests before opening yours. A draft with no push for 3 days may be taken over. Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
2. **Isolate with branches or worktrees:**
```sh
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
git worktree add ../wt-<slug> -b track-<a..f>/<slug> origin/main
```
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user (being told to "work" authorizes them for the one item picked, Section 0); never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
+17
View File
@@ -10,6 +10,9 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- **A collaborator only has to say "work"** (AGENTS.md §0, step 1). When `bx-cli preflight` fails, the agent makes the machine ready itself: the new `bx-cli setup --find` searches the home folder, recognises the GDK by its header and the target build by its structure (a large PE32+ file that imports `d3d12_xs.dll`; never by name), ignores the GDK's own tools, treats byte-identical copies as one build and keeps the copy with its imported DLLs beside it, and saves both settings. The agent may install `mingw-w64`, `cmake` and `gh` with Homebrew and free disk space by removing its own scratch. It stops only for what it cannot supply: no Apple Silicon Mac, no CrossOver, the build or the GDK not on the machine, or more than one distinct build.
- **Working rules: the pull request is the unit of work, and the target build and the GDK are required** (AGENTS.md §0, [working method](docs/process/working-method.md)). An agent told to "work" first runs the new `bx-cli preflight`, which fails unless the host is an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`, the target build's executable and the GDK folder are known, and 10 GiB of disk is free. A collaborator records the two locations once with the new `bx-cli setup --target-exe <path> --gdk-root <folder>`, which checks them and keeps them in `~/.config/betterxen/local.conf`, outside the repository (`BX_TARGET_EXE` and `BX_GDK_ROOT` override it). If preflight fails the agent stops and does no work. A blocker the agent can fix no longer gets an issue: it is claimed by a draft pull request titled with its run-report signature. Issues are kept for handoffs (label `handoff`), decisions for a person, and the ladder status. Claims by comment and the 7-day stale window are gone; an idle draft may be taken over after 3 days.
- **BetterXen is no longer a clean-room project** (repository owner's decision, #650). `CONTRIBUTING.md` now says that material the project is authorized to use, such as the GDK and its compilers, may be used and that facts derived from it may be committed, while the material and its outputs are never committed. Leaked or unauthorized material remains forbidden.
- **Roadmap and working method (proposed).** `docs/roadmap.md` replaces the subsystem milestones M3–M6 with stages the project-authorized target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), each judged on ten recorded runs on a 16 GB Mac, with decision gates for the D3DMetal back end, reference images, memory and frame rate. [docs/process/working-method.md](docs/process/working-method.md) describes the blocker queue for a team that works by telling coding agents to "work": where state lives, the order of work (own pull requests, review, one blocker, discover), the run protocol, source ranks and pull-request shape. AGENTS.md §0 is rewritten to match.
- `xg_xs.dll` follows the documented XG contract titles call: `XG_RESOURCE_DESC` and the 14-method `XGTextureAddressComputer`, from the authorized GDK documentation. Behaviour:
- **Linear layouts:** every texture is laid out linearly with BetterXen's documented alignment.
@@ -23,6 +26,11 @@ 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
- `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`.
- `xgameruntime.dll` serves `XAsyncRun`, `XTaskQueueCreateComposite`, `XTaskQueueGetPort` and `XTaskQueueDuplicateHandle` through `IXGameRuntimeCore` slots 6, 13, 14 and 15 (#666). `XAsyncRun` runs the title's work callback on the block's work port and completes the block with its result. A duplicated queue handle shares the queue, and only the last close shuts its lanes down. A composite queue forwards each port to the port it was made from, and an async block's completion returns through the queue the block named. A project-authorized target build uses these for its save-game work and exited when `XAsyncRun` was unimplemented. `test_xgameruntime` checks all four through `QueryApiImpl`.
- `bx-cli report <log.jsonl>...` (#664, part 1): a run report per log (one log is one run) and a summary across runs. Per run: how it ended, the frames presented (a lower bound), every unimplemented call with its count, faults whose innermost frame is in a BetterXen module, and pipelines by kind. The summary counts clean runs and lists each blocker signature with the number of runs that hit it; blocker issues are titled with those signatures. `bx-cli run` now appends a `run_end` record to its log (exited with a status, timeout, signal or launch failure), which the report reads. A log without it has an unknown outcome and is never counted as clean.
- `xgameruntime.dll` serves `XUserDuplicateHandle` through `IXUser` slot 3 (#680). A duplicate is a new handle to the one offline user; each handle is closed on its own, and `XUserCompare` returns 0 for any two valid handles of that user. A project-authorized target build duplicates its user handle after sign-in and waited when the slot was unimplemented. `test_xgameruntime` checks the slot through `QueryApiImpl`.
- Shader corpus, Phase 0 of the console shader translator (#649). `shader-transpiler/corpus/hlsl/` holds eight BetterXen-authored compute kernels covering integer and float ALU, divergent branches, loops, groupshared memory, wave operations, atomics and system values. `scripts/shader-corpus/build.sh` compiles each one locally with the console `xdxc` (a title-style container: `DXIL` plus `ACCC`/`FSPX`), the console PIX compiler (Microsoft's ISA listing) and the public PC DXC (DXIL for a D3DMetal reference run). `extract_code.py` then takes the code from the `FSPX` kind-6 section, skips the leading `v_nop_xbox_data` words and disassembles it with LLVM's public `gfx1030` decoder. All eight kernels build and decode cleanly. The extractor has nine unit tests on synthetic containers that need no GDK. Compiler outputs stay in the git-ignored `target/shader-corpus/`. One open question is recorded: a `v_cmp_class_f16` in the `wave` kernel's ballot sequence.
- `docs/research/console-shader-abi.md` and `CLAIM-XBOX-CS-ENTRY-ABI` (class U, not yet independently reproduced): the compute shader entry ABI observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler, used under Microsoft's authorization, on eleven project-authored probes. Compute code is wave64. Root data starts at `s4` in root-parameter order: one SGPR per constant, two per root descriptor address, one per 32-bit table pointer. The thread-group IDs follow the root data, and `s0:s1` holds the root-data address when it overflows. Root buffer descriptors are built inline with no effective bounds check, table buffer descriptors are 32 bytes apart (samplers 16), and the compiler reports the HLSL binding of each descriptor load. No compiler output, binary or documentation text is in the repository. Register roles are inferences, and the ACCC container layout remains unknown.
- Opt-in diagnostics in `bx_runtime_veh.dll`, all off by default:
- an access-violation context with the memory type and the faulting thread's stack (`BX_VEH_AV_CONTEXT`, `BX_VEH_AV_ALL`);
@@ -82,6 +90,15 @@ 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
- **`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).
- **`d3d12_xs.dll`: an index or vertex binding at a title address without a host buffer no longer crashes the process.** A title binds index and vertex data by address in plain title memory, with no Direct3D resource behind it. The address reached D3DMetal unchanged and it read through a null buffer (`IASetIndexBuffer`). Such a binding is now left empty and logged as unimplemented (`IASetIndexBuffer(title memory without a host buffer)`, likewise `IASetVertexBuffers`); bindings inside resources BetterXen created are translated as before. Supplying the data is separate work. Test: `test_d3d12_unbacked_buffers` (13 checks; without the fix it dies with the same null read).
- **`d3d12_xs.dll`: console-only DXGI formats and depth-stencil unordered-access views no longer end the process.** The Xbox Series `DXGI_FORMAT` enumeration has values the PC one lacks (116-120, 189, 190; GDK `d3d12_xs.h`). D3DMetal turns one into an invalid Metal pixel format and Metal aborts, which a target build's crash reporter then turned into either "exit status 5" or a stall with every thread stopped.
- **Formats:** `console_formats.h` maps each to the nearest host format (a depth texture is created typeless, each view names the concrete format). The three `GetResourceAllocationInfo` forms, `CreatePlacedResource`, `CreateReservedResource`, the four view-creation methods, the committed-resource forms and the placed (X) resource and view forms translate before the host call.
- **Depth-stencil unordered-access views** (allowed on the console, forbidden on PC): the descriptor gets a null view and the call is logged as unimplemented (`CreateUnorderedAccessView(depth-stencil resource)`).
- **Limits:** sizes reported for a translated format are the host format's, `GetDesc` reports the host format, and pipeline-state formats are not translated yet.
- **Test:** `test_d3d12_console_formats` (21 checks; without the fix the process dies at the first console-only format).
- `bx_runtime_veh.dll` completes a `CLZERO` loop in one exception (#665). A title that zeroes memory with `clzero; add rax,0x40; cmp rax,<reg64>; jb` raised one illegal-instruction exception per 64 bytes under Rosetta 2, which stalled a project-authorized target build's frame loop for tens of seconds. When the trapped `CLZERO` is followed by exactly that form, the handler zeroes every remaining line below the limit and leaves `RAX` at the last one, so the title's own `add`/`cmp`/`jb` leaves the loop. The range is zeroed region by region and stops at memory that is not committed and writable, where the next `CLZERO` traps and faults as before. Other loop forms keep the per-instruction path. `test_veh_clzero_loop` checks the memory result and counts the exceptions; it fails on the old handler.
- `d3d12_xs.dll` no longer turns `DeserializeGraphicsPipelineStateX`, `DeserializeComputePipelineStateX`, `CreateDerivedGraphicsPipelineStateX` or `CreateDerivedComputePipelineStateX` into null pipelines in null-render mode (`BX_NULL_RENDER=1`) (#669). All four calls now always return `E_NOTIMPL`, clear `*ppv` and log `pipeline_refused` without `; null pipeline returned`, so a title falls back to creating pipelines from shader containers instead of silently receiving null pipelines. `test_d3d12_serialized_pipelines` checks all four slots and their refusal log lines with `BX_NULL_RENDER=1` active alongside a control shader-container null pipeline.
- `XCRDAPI.dll` Xbox DirectStorage fixes:
- **Zlib requests read the file.** The file handle was not set for them, so every compressed file request failed. The request options are now decoded, and zlib streams are inflated in-tree.
- **`AutoSubmitDisabled` is honoured.** Xbox `CreateQueueX` respects `DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled`: a queue with the flag runs nothing before `Submit`, and when it is full the enqueuer waits until `Submit` is called on another thread. A queue without the flag submits by itself once half full.
+2 -2
View File
@@ -31,10 +31,10 @@ python3 scripts/audit/docs_hygiene.py
Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/skip counts. Never report a skipped test or unavailable tool as a pass.
## Clean-Room, Licensing & Provenance Policy
## Licensing & Provenance Policy
- Use publicly accessible specifications, publicly licensed software, independently authored synthetic workloads, and project-authorized target builds only under every condition in [AGENTS.md](AGENTS.md) §6 (maintainer approval alone is not enough). Never obtain or use leaked or unauthorized material, and never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
- Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
- BetterXen is **not** a clean-room project (repository owner's decision, 2026-11-29, #650). Material the project is authorized to use, such as the Microsoft GDK and its compilers under the project's authorization, may be used by contributors, and facts derived from it (layouts, slot orders, flag values, binary conventions) may be committed. The material itself, and its outputs, are never committed. **Leaked or unauthorized material is still forbidden:** anyone who has used it for this work must not contribute what they learned from it. Do not post details of restricted material in issues or PRs.
- Before incorporating third-party code, verify **per-file** license compatibility with `GPL-3.0-or-later`, record provenance in [docs/research/upstream-registry.md](docs/research/upstream-registry.md) and [docs/research/component-reuse-matrix.md](docs/research/component-reuse-matrix.md), preserve copyright notices, and update [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Public visibility or a GPL license does not clear code derived from leaked material.
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
- Never claim Xbox hardware verification (BetterXen has no Xbox hardware access) or independent certification of your own work; classify evidence per [docs/claims.toml](docs/claims.toml).
+1 -1
View File
@@ -23,7 +23,7 @@ BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Ro
- **Shader pipeline** (`shader-transpiler/`, Rust) for classifying `DXBC` containers (`DXIL` vs. `ACCC`/`FSPX` RDNA 2 machine code) and handling console shader translation where required.
> [!CAUTION]
> **Clean-room and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
> **Provenance and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
---
+2 -1
View File
@@ -27,6 +27,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.
- [Shader Corpus](../shader-transpiler/corpus/README.md) — Phase 0 of the console shader translator: BetterXen-authored kernels built locally into console containers, Microsoft ISA listings and PC DXIL, with the derived `FSPX` code-section layout (#649).
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
@@ -34,7 +35,7 @@
## Governance, Security & Legal
- [Engineering & Agent Rules](../AGENTS.md) (`CLAUDE.md` symlink) — Mandatory rules for human contributors and coding agents.
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, clean-room policy, and DCO sign-off.
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, provenance policy, and DCO sign-off.
- [Claims & Evidence Classes](claims.toml) — Scoped claims with an evidence-class legend (A, B, D, E, U); classes describe evidence type, not Xbox hardware verification.
- [Legal Scope](legal.md), [Dependency Licensing](licenses.md), and [Third-Party Notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution boundaries.
- [Threat Model](threat-model.md) & [Security Policy](../SECURITY.md) — Isolation boundaries and vulnerability reporting.
+2 -2
View File
@@ -1,6 +1,6 @@
# Clean-room scope
# Legal scope
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, vendor documentation and tools the project is authorized to use (never committed; see [CONTRIBUTING](../CONTRIBUTING.md)), its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
## User-provided game files
+56 -54
View File
@@ -1,10 +1,23 @@
# Working Method: the Blocker Queue
# Working Method: Run, Fix, Pull Request
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
BetterXen is built by collaborators who each have the project-authorized target build and who work by pointing a coding agent at this repository and saying **"work"**. This document is written for that. It answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
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?*
There are no meetings, no rotating roles and no plan to interpret. The state of the project is in GitHub; the rules are here and in AGENTS.md.
The short answer: run the build, fix the first thing it stops on, and open a pull request. The pull request is the unit of work. There are no meetings, no rotating roles and no backlog to interpret.
## What you must have
No agent works without all of these. `bx-cli preflight` checks them and fails if one is missing:
- an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`;
- **the project-authorized target build**;
- **the GDK**, headers and compilers, under the project's authorization;
- at least 10 GiB of free disk space.
A collaborator only says "work". When preflight fails, the agent makes the machine ready itself: `bx-cli setup --find` searches the home folder, recognises the GDK by its header and the target build by its structure (never by name), and saves both in `~/.config/betterxen/local.conf`, outside the repository, where every worktree and agent session on that machine finds them. It installs missing build tools with Homebrew and frees disk space by removing its own scratch.
Work here is found by running the build and checked against the GDK. Without them an agent can only guess, and a guess that looks like a fix costs a reviewer more than it saves. An agent stops only for what it cannot supply: the host is not an Apple Silicon Mac, CrossOver is not installed, the build or the GDK is not on the machine, or more than one distinct build is (the choice is the collaborator's). Then it says exactly which, and does not write fixes, tests or reviews "for someone else to verify".
## Why this shape
@@ -24,49 +37,58 @@ The [roadmap](../roadmap.md) is a ladder of stages the target build reaches: **B
## Where the state lives
| What | Where | Who writes it |
| --- | --- | --- |
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) | Any agent that runs the gate check |
| Everything the build is known to stop on | One **blocker issue** each (label `blocker`, plus `stage: <name>` and a track label) | The agent that found it |
| Who is working on what | A claim comment on the blocker issue | The claiming agent |
| What needs a person | Label `needs-human` | Any agent |
| Rules | AGENTS.md and this document | Maintainers, by pull request |
| What | Where |
| --- | --- |
| A blocker someone is fixing | An open pull request titled with its signature (a draft while in progress) |
| A blocker someone found and could not finish | A **handoff issue** (label `handoff`, plus `stage: <name>`) |
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) |
| What needs a person | Label `needs-human` |
| Rules | AGENTS.md and this document, changed by pull request |
Nothing about status is kept in files in the repository: agents editing one status file would conflict all day.
### Blocker issues
### Why a blocker gets a pull request and not an issue
A blocker issue is small and has a fixed shape, so that two agents that find the same thing file the same issue.
An agent that runs the build and sees what it stops on usually knows the fix a few minutes later. Writing an issue, claiming it and then opening a pull request that closes it is three steps where one does the job. And an issue of the form "the build stops at X" is a fact about one run on one machine: the build takes different start-up paths from run to run, so another collaborator may never see it.
- **Title:** `[blocker] <signature>`. The signature is taken from the run report, not invented: for example `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll (write, unmapped)`, `exit status 1 after save query`, `stall: presenting thread in trapped instruction`. Before filing, search open and closed issues for the signature.
- **Body:** the stage it blocks; how many of ten runs hit it; the run-report lines; what is known and not known. No bytes, names, hashes or addresses from the build.
- **Order:** within a stage, the label `first` marks blockers that every run hits before any other; after those, lower issue number first.
What holds on every machine is the **test**: "the console does X for this call, and this test fails without the fix". The run is why you looked; the test is the proof.
So:
- **You can fix it:** open a draft pull request titled with the signature, before writing the fix. The draft is the claim.
- **You cannot fix it** (too large, out of session, needs a decision): file one handoff issue with what you saw, what you tried and what is unknown.
### Signatures
A signature is the fixed string `bx-cli report` prints for something a run stopped on: `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll`, `exit status 5`. Pull requests and handoff issues are titled with it (`[Boot] unimplemented IXUser slot 3`), so searching open pull requests for a signature tells you whether someone is already on it.
## What an agent does when told "work"
AGENTS.md §0 has the binding version. In short, in strict order:
1. **Preflight.** Tools, login, disk space, an own bottle, a current `main`.
2. **Your own pull requests first.** Requested changes, failing checks or conflicts on a pull request your person opened.
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. Review it, and merge it if it is approved, green and not your person's. Review comes before new work because unreviewed work is worth nothing to the next run.
4. **Then one blocker.** The top unclaimed blocker of the current stage. Claim it, and do only that.
5. **Then discover.** If the current stage has no unclaimed blocker, run the stage's gate check and file what it finds. If the gate passes, post the result on the ladder issue and label it `needs-human`: a person confirms the stage change.
6. **Otherwise stop.** Report that the queue is empty. Do not invent work.
1. **Preflight.** `bx-cli preflight` must pass. If it does not, stop.
2. **Your own pull requests first.** Requested changes, failing checks, conflicts, or a draft you have not finished.
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. Merge it if it is approved, green and not your person's. Review comes before new work because unreviewed work is worth nothing to the next run.
4. **Then a handoff issue** of the current stage that no pull request covers.
5. **Then run the build** and fix the first thing it stops on that no open pull request covers.
6. **If the run stops on nothing,** make the stage's ten-run gate check and post it on the ladder issue with `needs-human`.
An agent stops and labels `needs-human` whenever it meets a decision that is not its to make: a decision gate, a licence or provenance question, a rule change, or two sources of truth that disagree.
## Working one blocker
```text
claim → evidence → smallest fix + test → ten runs → pull request → (someone else reviews and merges)
run → signature → draft pull request (the claim) → evidence → smallest fix + test → runs before and after → ready → someone else reviews and merges
```
1. **Claim.** Comment `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue. A claim with no commits or pull request after 3 days is free to take; say so in a comment when you take it.
2. **Evidence before code.** Find what the build asked for and what it got. Use the run report, then the diagnostics (thread sampler, fault context, call trace). If that does not explain it within the session, write what was learned on the issue and release the claim; do not guess a fix.
3. **Smallest fix.** Only what removes this blocker, inside the track directories it needs. A new cross-DLL export still goes through an `[ABI]` pull request first.
4. **A test for the contract.** Every contract the fix teaches a shim gets a synthetic conformance test that fails without the fix.
5. **Proof.** Ten runs before and ten after. Report every run.
6. **Pull request.** One blocker, five short parts (below). Then stop: the next "work" starts from the top of the list.
1. **Claim with a draft pull request.** Check open pull requests for the signature. If nobody has it, branch from `origin/main`, push, and open a draft titled `[<Stage>] <signature>`. A draft with no push for 3 days may be taken over.
2. **Evidence before code.** Find what the build asked for and what it got: the run report, then the diagnostics (thread sampler, fault context, call trace). Check the contract against the GDK where the GDK covers it. Do not guess a fix.
3. **Smallest fix.** Only what removes this blocker. A new cross-DLL export still goes through an `[ABI]` pull request first.
4. **A test for the contract.** It fails without the fix and passes twice in a row in the same bottle.
5. **Proof.** Runs before and after on your machine, every run reported. Say which start-up path your runs took: another machine may take a different one.
6. **Mark it ready** with the five-part description. Then stop: the next "work" starts from the top of the list.
If the blocker turns out to be more than you can finish, close the draft and file a handoff issue.
### Pull-request description
@@ -116,7 +138,9 @@ Until the launcher does, the offline-run procedure and the diagnostic switches a
- pipelines drawn with: translated, passed through, skipped;
- on a stall: every thread's stack.
It ends with a ten-run summary and a list of **signatures**, the strings blocker issues are titled with.
It ends with a ten-run summary and a list of **signatures**, the strings pull requests and handoff issues are titled with.
**What exists today** (#664): `bx-cli report <log.jsonl>...` produces the per-run report and the summary with signatures from run logs, and `bx-cli run` records how each run ended. Not yet in the launcher: the offline runner, per-session bottles, the machine-wide lock, thread stacks on a stall, and stall detection itself (frames are logged at powers of two, so a log cannot yet tell a stall from slow presentation).
## Sources of truth
@@ -158,7 +182,7 @@ From the Menus stage on, the build no longer stops by itself at the next missing
| An agent looking at a capture | Obvious breakage: black screen, missing geometry, garbage textures | No; subtle errors are missed |
| A person's mark during play | Feel, audio sync, input lag, anything that "looks off" | Yes |
Findings enter the queue as blocker issues with signatures of the same kind: `route 7: crash at 1:40 (3/10)`, `capture 12: 340 draws skipped`, `capture 12: differs from reference in the sky`. The order of work does not change.
Findings become pull requests (or handoff issues, when they cannot be fixed at once) with signatures of the same kind: `route 7: crash at 1:40 (3/10)`, `capture 12: 340 draws skipped`, `capture 12: differs from reference in the sky`. The order of work does not change.
Whether the game is good to play is a question only people answer. Their time goes into playing and marking, never into reproducing or bisecting.
@@ -173,28 +197,6 @@ People are needed for exactly four things, each marked `needs-human`:
Everything else is the queue.
## Starting the queue
## The first handoffs
The queue starts with what the first target-build runs already found. Each line was filed as an issue on 2026-11-29 (#664–#680); the table is kept as a record of the starting point, and the issues are the live state.
| Stage | Signature or task | Track |
| --- | --- | --- |
| Boot | Run tooling in the repository: offline runner, per-run report with signatures, ten-run summary, thread sampler, machine-wide run lock, per-session bottle | A |
| Boot | `stall: presenting thread in trapped CLZERO loop` | A |
| Boot | `unimplemented IXUser slot 3` (handle duplication) | E |
| Boot | `unimplemented IXGameRuntimeCore slots 6, 13, 14, 15` (async run; task-queue composite, port, duplicate) | E |
| Boot | `unimplemented IXGameSaveImpl slot 13` (container info; and slot 15) | E |
| Boot | `fault in XCRDAPI.dll (write, unmapped)` — page remapping is not atomic | B |
| Boot | `serialized-pipeline calls succeed with a null pipeline` — they must fail and be logged | C |
| Boot | `exit status 1, nothing logged` (1 run in 5) | A |
| Picture | D3DMetal capability checks: direct heap indexing, 64-lane compute through the translator, 64-bit atomics, mesh and amplification shaders | D, F |
| Picture | Vendor the upstream translator with provenance entries; amend ADR 0008 | D |
| Picture | Translator behind `bx_shader_bridge.dll`; host pipelines created on first use | C, D |
| Picture | `placed texture contents not uploaded` | C |
| Picture | `build waits after sign-in with nothing unimplemented` — needs evidence | E |
| Picture | Reference images for the first screens | `needs-human` |
| Menus | Input record and replay in the `GameInput` shim; routes as ten-run regression tests | E, A |
| Menus | Play-session recording in the launcher: input stream, starting saves, mark hotkey | A |
| Fidelity | Frame capture in `d3d12_xs` and an offline frame replayer | C |
Fixes for several Boot lines exist on a local experiment branch; they still go through the queue, one pull request each, with tests and ten-run proof.
When this method started, the first target-build runs had already found more than could be fixed at once. Those were filed as issues #664–#680. The ones that were only "a blocker with a fix on the way" close as their pull requests merge; the ones that remain open as handoffs are the larger pieces: the run tooling, the D3DMetal capability checks, the translator, the reference images and the record-and-replay tools.
+791 -3
View File
@@ -63,7 +63,10 @@ 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 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"
}
@@ -136,6 +139,537 @@ fn cmd_doctor() -> ExitCode {
ExitCode::SUCCESS
}
/// One preflight requirement: its name and what was found, or why it is not met.
type Requirement = (&'static str, Result<String, String>);
/// A check of one local setting: what was found, or why it is not usable.
type SettingCheck = fn(Option<&str>) -> Result<String, String>;
/// The GDK header BetterXen's Xbox-layout tables are generated from. Finding it under
/// `BX_GDK_ROOT` is the evidence that the GDK is really there. The walk is bounded so a wrong
/// root (a home directory, say) cannot make preflight crawl a disk.
const GDK_MARKER: &str = "d3d12_xs.h";
fn find_gdk_marker(root: &Path) -> Option<PathBuf> {
const MAX_DEPTH: usize = 8;
const MAX_ENTRIES: usize = 200_000;
let mut seen = 0usize;
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() {
seen += 1;
if seen > MAX_ENTRIES {
return None;
}
let path = entry.path();
let Ok(kind) = entry.file_type() else {
continue;
};
if kind.is_file() && entry.file_name() == GDK_MARKER {
return Some(path);
}
if kind.is_dir() && depth < MAX_DEPTH {
stack.push((path, depth + 1));
}
}
}
None
}
/// Where this machine's local settings live: outside every checkout, so they cannot be
/// committed, and shared by every worktree, shell and agent session of this user.
fn local_config_path() -> Option<PathBuf> {
let base = env::var_os("XDG_CONFIG_HOME")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))?;
Some(base.join("betterxen").join("local.conf"))
}
/// `key = value` lines; `#` starts a comment. Unknown keys are kept by [`write_local_config`].
fn parse_local_config(text: &str) -> BTreeMap<String, String> {
text.lines()
.filter_map(|line| {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
return None;
}
let (key, value) = line.split_once('=')?;
Some((key.trim().to_owned(), value.trim().to_owned()))
})
.collect()
}
fn read_local_config(path: &Path) -> BTreeMap<String, String> {
fs::read_to_string(path)
.map(|text| parse_local_config(&text))
.unwrap_or_default()
}
fn write_local_config(path: &Path, values: &BTreeMap<String, String>) -> std::io::Result<()> {
if let Some(dir) = path.parent() {
fs::create_dir_all(dir)?;
}
let mut text = String::from(
"# BetterXen local settings for this machine (written by `bx-cli setup`).\n\
# Never commit this file or its contents.\n",
);
for (key, value) in values {
let _ = writeln!(text, "{key} = {value}");
}
fs::write(path, text)
}
/// A local setting: the environment variable wins (a one-off override), then the saved file.
fn local_setting(env_name: &str, key: &str, config: &BTreeMap<String, String>) -> Option<String> {
env::var(env_name)
.ok()
.filter(|v| !v.is_empty())
.or_else(|| config.get(key).cloned())
}
const TARGET_EXE_KEY: &str = "target_exe";
const GDK_ROOT_KEY: &str = "gdk_root";
/// 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
/// too, but they are small and live in build folders the search skips.
const TITLE_IMPORT: &str = "d3d12_xs.dll";
const TITLE_MIN_BYTES: u64 = 16 << 20;
fn looks_like_title(path: &Path) -> bool {
let large = fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() >= TITLE_MIN_BYTES);
if !large {
return false;
}
let Ok(bytes) = fs::read(path) else {
return false;
};
probe_pe32_plus(&bytes).is_ok_and(|pe| {
pe.imports
.keys()
.any(|dll| dll.eq_ignore_ascii_case(TITLE_IMPORT))
})
}
/// The folder to remember for a GDK header found at `header`: the first folder below a
/// well-known top-level folder of `home` (Documents, Downloads, ...), or below `home` itself.
fn gdk_root_for(home: &Path, header: &Path) -> Option<PathBuf> {
const TOP_LEVEL: &[&str] = &["Documents", "Downloads", "Desktop", "Developer", "Projects"];
let relative = header.strip_prefix(home).ok()?;
let mut parts = relative.components();
let first = parts.next()?.as_os_str().to_owned();
let mut root = home.join(&first);
if TOP_LEVEL.iter().any(|name| first == *name) {
root = root.join(parts.next()?.as_os_str());
}
(root.is_dir() && root != header).then_some(root)
}
#[derive(Debug, Default, PartialEq, Eq)]
struct Found {
gdk_roots: Vec<PathBuf>,
target_exes: Vec<PathBuf>,
/// The search gave up before visiting everything.
truncated: bool,
}
/// Searches `home` for the GDK (by its header) and for Xbox Series executables (by structure).
/// Hidden folders, `Library`, application bundles and build folders are skipped, and the walk is
/// bounded so it always ends.
fn search_for_materials(home: &Path) -> Found {
const MAX_DEPTH: usize = 14;
const MAX_ENTRIES: usize = 3_000_000;
const SKIP: &[&str] = &[
"Library",
"node_modules",
"target",
"build-shims",
"Applications",
];
let mut found = Found::default();
let mut seen = 0usize;
let mut stack = vec![(home.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() {
seen += 1;
if seen > MAX_ENTRIES {
found.truncated = true;
return found;
}
let name = entry.file_name();
let name_text = name.to_string_lossy();
let Ok(kind) = entry.file_type() else {
continue;
};
let path = entry.path();
if kind.is_dir() {
let skip = name_text.starts_with('.')
|| name_text.ends_with(".app")
|| name_text.ends_with(".photoslibrary")
|| SKIP.iter().any(|s| name_text == *s);
if !skip && depth < MAX_DEPTH {
stack.push((path, depth + 1));
}
} else if kind.is_file() {
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()
{
found.gdk_roots.push(root);
}
} else if name_text.to_ascii_lowercase().ends_with(".exe")
&& looks_like_title(&path)
{
found.target_exes.push(path);
}
}
}
}
found.gdk_roots.sort();
found.target_exes.sort();
// The GDK ships tools that import the same library; they are not titles.
let roots = found.gdk_roots.clone();
found
.target_exes
.retain(|exe| !roots.iter().any(|root| exe.starts_with(root)));
found.target_exes = distinct_builds(std::mem::take(&mut found.target_exes));
found
}
fn content_hash(path: &Path) -> Option<(u64, u64)> {
let bytes = fs::read(path).ok()?;
// FNV-1a: only to tell copies of one file from different files, never recorded anywhere.
let hash = bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| {
(h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3)
});
Some((bytes.len() as u64, hash))
}
/// How many of the DLLs an executable imports are present in its own folder. A title ships some
/// of its DLLs beside it, so the real installation scores higher than a stray copy of the file.
fn companion_dlls(path: &Path) -> usize {
let Some(dir) = path.parent() else {
return 0;
};
let Ok(bytes) = fs::read(path) else {
return 0;
};
let Ok(pe) = probe_pe32_plus(&bytes) else {
return 0;
};
let present: Vec<String> = fs::read_dir(dir)
.map(|entries| {
entries
.flatten()
.map(|e| e.file_name().to_string_lossy().to_ascii_lowercase())
.collect()
})
.unwrap_or_default();
pe.imports
.keys()
.filter(|dll| present.contains(&dll.to_ascii_lowercase()))
.count()
}
/// Byte-identical copies are one build. Of the copies, the one with the most of its imported
/// DLLs beside it is kept: that is the installation, and the others are stray copies of the file.
fn distinct_builds(candidates: Vec<PathBuf>) -> Vec<PathBuf> {
distinct_builds_by(candidates, companion_dlls)
}
fn distinct_builds_by(candidates: Vec<PathBuf>, siblings: impl Fn(&Path) -> usize) -> Vec<PathBuf> {
let mut builds: Vec<((u64, u64), PathBuf)> = Vec::new();
for path in candidates {
let Some(identity) = content_hash(&path) else {
continue;
};
match builds.iter_mut().find(|(known, _)| *known == identity) {
Some((_, kept)) => {
if siblings(&path) > siblings(kept) {
*kept = path;
}
}
None => builds.push((identity, path)),
}
}
builds.into_iter().map(|(_, path)| path).collect()
}
/// `bx-cli setup --find`: fills in whichever of the two settings is not already valid. A GDK is
/// a GDK, so the first one found is used. A target build is saved only when exactly one is found:
/// which build to use is the collaborator's choice, not the tool's.
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 {
return false;
}
let Some(home) = env::var_os("HOME").map(PathBuf::from) else {
eprintln!("--find: no HOME to search");
return false;
};
println!(
"Searching the home folder for the GDK and the target build (this can take a minute)..."
);
let found = search_for_materials(&home);
let mut changed = false;
if need_gdk {
match found.gdk_roots.first() {
Some(root) => {
config.insert(GDK_ROOT_KEY.to_owned(), root.to_string_lossy().into_owned());
changed = true;
println!(" GDK : found and saved");
}
None => println!(" GDK : not found in the home folder"),
}
}
if need_target {
match found.target_exes.as_slice() {
[only] => {
config.insert(
TARGET_EXE_KEY.to_owned(),
only.to_string_lossy().into_owned(),
);
changed = true;
println!(" target build : found and saved");
}
[] => println!(" target build : no Xbox Series executable found in the home folder"),
several => {
println!(
" target build : {} Xbox Series executables found; choose one with --target-exe:",
several.len()
);
for path in several {
println!(" {}", path.display());
}
}
}
}
if found.truncated {
println!(" (the search stopped early: the home folder has too many entries)");
}
changed
}
/// `bx-cli setup`: checks the given paths with the same rules as preflight and remembers them.
/// `--find` searches the home folder for whatever is not set. With no arguments it shows what
/// is saved, as present or missing, without printing a path.
fn cmd_setup(args: &[String]) -> ExitCode {
let Some(path) = local_config_path() else {
eprintln!("error: no HOME or XDG_CONFIG_HOME to keep local settings in");
return ExitCode::FAILURE;
};
let mut config = read_local_config(&path);
let mut i = 0;
let mut changed = false;
let mut find = false;
while i < args.len() {
if args[i] == "--find" {
find = true;
i += 1;
continue;
}
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),
other => {
eprintln!("error: unknown argument: {other}");
return ExitCode::FAILURE;
}
};
let Some(value) = args.get(i + 1) else {
eprintln!("error: {} needs a path", args[i]);
return ExitCode::FAILURE;
};
// Saved as an absolute path, so it means the same thing from every directory.
let absolute = fs::canonicalize(value).unwrap_or_else(|_| PathBuf::from(value));
let absolute = absolute.to_string_lossy().into_owned();
if let Err(why) = check(Some(&absolute)) {
eprintln!("error: {} was not saved: {why}", args[i]);
return ExitCode::FAILURE;
}
config.insert(key.to_owned(), absolute);
changed = true;
i += 2;
}
if find {
changed |= find_materials(&mut config);
}
if changed && let Err(e) = write_local_config(&path, &config) {
eprintln!("error: could not save local settings: {e}");
return ExitCode::FAILURE;
}
let state = |key: &str, check: SettingCheck| match config.get(key) {
Some(value) => check(Some(value)).unwrap_or_else(|why| format!("saved, but {why}")),
None => "not set".to_owned(),
};
println!(
"Local settings ({}):",
if changed { "saved" } else { "unchanged" }
);
println!(
" target build : {}",
state(TARGET_EXE_KEY, check_target_exe)
);
println!(" GDK : {}", state(GDK_ROOT_KEY, check_gdk_root));
println!("They are kept outside the repository. Run `bx-cli preflight` to check everything.");
ExitCode::SUCCESS
}
/// The target build: the setting must name a readable PE file.
fn check_target_exe(value: Option<&str>) -> Result<String, String> {
let path = value.filter(|v| !v.is_empty()).ok_or(
"not set; run `bx-cli setup --find`, or `bx-cli setup --target-exe <path to the target build's executable>`",
)?;
let mut magic = [0u8; 2];
let read = fs::File::open(path).and_then(|mut f| std::io::Read::read_exact(&mut f, &mut magic));
match read {
Ok(()) if &magic == b"MZ" => Ok("present".to_owned()),
Ok(()) => Err("the saved path does not name a Windows executable".to_owned()),
Err(e) => Err(format!("the saved path cannot be read: {e}")),
}
}
/// 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
.filter(|v| !v.is_empty())
.ok_or("not set; run `bx-cli setup --find`, or `bx-cli setup --gdk-root <folder that holds the GDK>`")?;
let root = Path::new(root);
if !root.is_dir() {
return Err("the saved path is not a folder".to_owned());
}
match find_gdk_marker(root) {
Some(_) => Ok(format!("present ({GDK_MARKER} found)")),
None => Err(format!(
"no {GDK_MARKER} under it: that folder does not hold the GDK"
)),
}
}
/// Free space on the volume holding `path`, in GiB.
fn free_gib(path: &Path) -> Option<u64> {
use std::os::unix::ffi::OsStrExt;
let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
// SAFETY: `c_path` is a valid NUL-terminated path and `stat` is a zeroed out-parameter
// that statvfs fills on success.
let stat = unsafe {
let mut stat: libc::statvfs = std::mem::zeroed();
(libc::statvfs(c_path.as_ptr(), &raw mut stat) == 0).then_some(stat)
}?;
Some(u64::from(stat.f_bavail).saturating_mul(stat.f_frsize) / (1 << 30))
}
const MIN_FREE_GIB: u64 = 10;
fn render_preflight(requirements: &[Requirement]) -> (String, bool) {
let mut out = String::from("=== BetterXen Preflight ===\n");
let mut ready = true;
for (name, result) in requirements {
match result {
Ok(found) => {
let _ = writeln!(out, "ok {name:<22}: {found}");
}
Err(why) => {
ready = false;
let _ = writeln!(out, "MISSING {name:<22}: {why}");
}
}
}
out.push_str(if ready {
"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. \
Stop only for what is not on this machine.\n"
});
(out, ready)
}
/// `bx-cli preflight`: everything AGENTS.md section 0 requires before any work. Unlike `doctor`,
/// which only reports, this fails when something is missing.
fn cmd_preflight() -> ExitCode {
let arch = run_capture("uname", &["-m"]).unwrap_or_default();
let crossover = run_capture(
"defaults",
&[
"read",
"/Applications/CrossOver.app/Contents/Info.plist",
"CFBundleShortVersionString",
],
);
let d3dmetal = Path::new(
"/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/lib64/apple_gptk/external/D3DMetal.framework",
)
.exists();
let mingw = run_capture("which", &["x86_64-w64-mingw32-g++"]);
let free = env::current_dir().ok().and_then(|dir| free_gib(&dir));
let config = local_config_path()
.map(|path| read_local_config(&path))
.unwrap_or_default();
let requirements: Vec<Requirement> = vec![
(
"Apple Silicon host",
if arch == "arm64" {
Ok(arch)
} else {
Err(format!("this host is '{arch}', not arm64"))
},
),
(
"CrossOver",
crossover.ok_or_else(|| "not installed".to_owned()),
),
(
"D3DMetal",
if d3dmetal {
Ok("present".to_owned())
} else {
Err("not found in CrossOver".to_owned())
},
),
(
"mingw-w64 g++",
mingw
.map(|_| "present".to_owned())
.ok_or_else(|| "missing (brew install mingw-w64)".to_owned()),
),
(
"Target build",
check_target_exe(local_setting("BX_TARGET_EXE", TARGET_EXE_KEY, &config).as_deref()),
),
(
"GDK",
check_gdk_root(local_setting("BX_GDK_ROOT", GDK_ROOT_KEY, &config).as_deref()),
),
(
"Free disk space",
match free {
Some(gib) if gib >= MIN_FREE_GIB => Ok(format!("{gib} GiB")),
Some(gib) => Err(format!(
"{gib} GiB free; at least {MIN_FREE_GIB} GiB is needed"
)),
None => Err("could not be measured".to_owned()),
},
),
];
let (text, ready) = render_preflight(&requirements);
print!("{text}");
if ready {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}
fn cmd_probe(path: &str) -> ExitCode {
let data = match fs::read(path) {
Ok(d) => d,
@@ -360,6 +894,47 @@ fn cmd_trace(path: &str) -> ExitCode {
ExitCode::SUCCESS
}
/// `bx-cli report <log>...`: each log is one run. Prints every run's report, then the summary
/// whose signatures blocker issues are titled with (docs/process/working-method.md).
fn cmd_report(paths: &[String]) -> ExitCode {
let mut runs = Vec::new();
for path in paths {
let bytes = match fs::read(path) {
Ok(bytes) => bytes,
Err(e) => {
eprintln!("error reading {path}: {e}");
return ExitCode::FAILURE;
}
};
// Guest text may not be valid UTF-8; the records that matter are ASCII.
let report = bx_telemetry::report::report_run(&String::from_utf8_lossy(&bytes));
let name = Path::new(path)
.file_stem()
.map_or_else(|| path.clone(), |stem| stem.to_string_lossy().into_owned());
print!("{}", bx_telemetry::report::render_run(&name, &report));
runs.push((name, report));
}
print!("\n{}", bx_telemetry::report::render_summary(&runs));
ExitCode::SUCCESS
}
/// The record `bx-cli run` appends to the log when the run is over, so a log says how its run
/// ended (`bx-cli report` reads it). It carries no guest timestamp.
fn run_end_record(outcome: &std::io::Result<Outcome>) -> String {
let detail = match outcome {
Ok(Outcome::Exited(status)) => match status.code() {
Some(code) => format!("outcome=exited status={code}"),
None => "outcome=signal signal=0".to_owned(),
},
Ok(Outcome::Stopped(Stop::TimedOut)) => "outcome=timeout".to_owned(),
Ok(Outcome::Stopped(Stop::Signalled(signal))) => format!("outcome=signal signal={signal}"),
Err(_) => "outcome=launch_failed".to_owned(),
};
format!(
"{{\"ts_ms\":0,\"tid\":0,\"level\":\"INFO\",\"sub\":\"bx_cli\",\"event\":\"run_end\",\"detail\":\"{detail}\"}}\n"
)
}
fn render_trace(text: &str) -> String {
let mut out = String::new();
let summary = summarize_jsonl(text);
@@ -1072,6 +1647,14 @@ fn cmd_run(args: &[String]) -> ExitCode {
_ => {}
}
// The log says how its run ended. A log that cannot be appended to is not a reason to
// fail the run.
if let Some(log) = &abs_log
&& let Ok(mut file) = fs::OpenOptions::new().append(true).create(true).open(log)
{
let _ = file.write_all(run_end_record(&outcome).as_bytes());
}
// Printed for failed and stopped runs too, which is when it matters most. The log is
// appended to across runs, so only what this run added is summarized.
if let Some(log) = &abs_log
@@ -1191,7 +1774,9 @@ impl<'a> Dispatch<'a> {
};
match sub.as_str() {
"--help" | "-h" | "help" => Dispatch::Help,
"doctor" | "probe" | "shader" | "trace" | "run" => Dispatch::Sub(sub.as_str()),
"doctor" | "setup" | "preflight" | "probe" | "shader" | "trace" | "report" | "run" => {
Dispatch::Sub(sub.as_str())
}
_ => Dispatch::Unknown(sub.as_str()),
}
}
@@ -1220,9 +1805,12 @@ fn main() -> ExitCode {
Dispatch::NoArgs | Dispatch::Unknown(_) => ExitCode::FAILURE,
Dispatch::Sub(sub) => match sub {
"doctor" => cmd_doctor(),
"setup" => cmd_setup(&args[1..]),
"preflight" => cmd_preflight(),
"probe" if args.len() >= 2 => cmd_probe(&args[1]),
"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..]),
"run" => cmd_run(&args[1..]),
// Only reachable when a subcommand that needs an argument got none.
_ => {
@@ -1939,7 +2527,16 @@ sub setup_bottle_wineprefix {
);
assert!(bogus.is_usage_error(), "an unknown subcommand is an error");
for real in ["doctor", "probe", "shader", "trace", "run"] {
for real in [
"doctor",
"setup",
"preflight",
"probe",
"shader",
"trace",
"report",
"run",
] {
let argv = args(&[real]);
let dispatch = Dispatch::classify(&argv);
assert_eq!(dispatch, Dispatch::Sub(real), "{real} is a real subcommand");
@@ -1948,6 +2545,188 @@ sub setup_bottle_wineprefix {
}
}
/// Preflight: the target build and the GDK are required, and a missing one is named.
#[test]
fn preflight_requires_the_target_build_and_the_gdk() {
let dir = env::temp_dir().join(format!("bx-preflight-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("a/b/include")).unwrap();
// Target build: unset, missing, not a PE, a PE.
assert!(check_target_exe(None).unwrap_err().contains("not set"));
assert!(check_target_exe(Some("")).unwrap_err().contains("not set"));
assert!(
check_target_exe(None)
.unwrap_err()
.contains("bx-cli setup --find")
);
let missing = dir.join("none.exe");
assert!(
check_target_exe(missing.to_str())
.unwrap_err()
.contains("cannot be read")
);
let text = dir.join("text.exe");
fs::write(&text, b"not a program").unwrap();
assert!(
check_target_exe(text.to_str())
.unwrap_err()
.contains("not name a Windows executable")
);
let pe = dir.join("title.exe");
fs::write(&pe, b"MZ\x90\x00").unwrap();
assert_eq!(check_target_exe(pe.to_str()), Ok("present".to_owned()));
// GDK: unset, not a folder, a folder without the header, a folder with it nested.
assert!(check_gdk_root(None).unwrap_err().contains("not set"));
assert!(
check_gdk_root(pe.to_str())
.unwrap_err()
.contains("not a folder")
);
assert!(
check_gdk_root(dir.to_str())
.unwrap_err()
.contains("does not hold the GDK")
);
fs::write(dir.join("a/b/include").join(GDK_MARKER), b"// header").unwrap();
assert!(check_gdk_root(dir.to_str()).unwrap().contains("found"));
// One missing requirement makes the whole preflight not ready, and says so.
let (text, ready) = render_preflight(&[
("Target build", Ok("present".to_owned())),
("GDK", Err("not set".to_owned())),
]);
assert!(!ready);
assert!(text.contains("MISSING GDK"), "{text}");
assert!(text.contains("Fix what you can yourself"), "{text}");
let (text, ready) = render_preflight(&[("Target build", Ok("present".to_owned()))]);
assert!(ready && text.contains("Ready to work."), "{text}");
assert!(
free_gib(&dir).is_some(),
"free space is measurable for an existing folder"
);
// Local settings: written, read back, unknown keys kept, comments ignored; the
// environment variable wins over the saved value.
let conf = dir.join("conf/local.conf");
let mut values = BTreeMap::new();
values.insert(TARGET_EXE_KEY.to_owned(), pe.to_string_lossy().into_owned());
values.insert("future_key".to_owned(), "kept".to_owned());
write_local_config(&conf, &values).unwrap();
let read = read_local_config(&conf);
assert_eq!(read, values);
assert!(
fs::read_to_string(&conf)
.unwrap()
.starts_with("# BetterXen local settings")
);
assert_eq!(read_local_config(&dir.join("absent.conf")), BTreeMap::new());
assert_eq!(
local_setting(
"BX_TEST_UNSET_VARIABLE_FOR_PREFLIGHT",
TARGET_EXE_KEY,
&read
)
.as_deref(),
pe.to_str()
);
assert_eq!(
local_setting("BX_TEST_UNSET_VARIABLE_FOR_PREFLIGHT", GDK_ROOT_KEY, &read),
None
);
assert_eq!(
parse_local_config("# c\n\n a = 1 \nbroken line\nb=2=3\n").len(),
2
);
let _ = fs::remove_dir_all(&dir);
}
/// `setup --find`: the GDK is recognised by its header and remembered as the first folder
/// below Documents; build folders and hidden folders are not searched; a small executable
/// is not taken for a title.
#[test]
fn find_recognises_the_gdk_and_skips_what_is_not_a_title() {
let home = env::temp_dir().join(format!("bx-find-{}", std::process::id()));
let _ = fs::remove_dir_all(&home);
let header_dir = home.join("Documents/sdk/pkg/xbox/include/gen9");
fs::create_dir_all(&header_dir).unwrap();
fs::write(header_dir.join(GDK_MARKER), b"// header").unwrap();
// The same header in places the search must not look.
for skipped in [
".hidden/x",
"Library/x",
"Documents/proj/build-shims/x",
"Documents/proj/target/x",
] {
fs::create_dir_all(home.join(skipped)).unwrap();
fs::write(home.join(skipped).join(GDK_MARKER), b"// header").unwrap();
}
// A small PE-looking file and a non-PE .exe: neither is a title.
fs::create_dir_all(home.join("Documents/game")).unwrap();
fs::write(home.join("Documents/game/small.exe"), b"MZ\x90\x00").unwrap();
let found = search_for_materials(&home);
assert_eq!(found.gdk_roots, vec![home.join("Documents/sdk")]);
assert!(found.target_exes.is_empty());
assert!(!found.truncated);
assert_eq!(
gdk_root_for(&home, &home.join("sdk2/include/d3d12_xs.h")),
None,
"a folder that does not exist is not a root"
);
fs::create_dir_all(home.join("sdk2/include")).unwrap();
assert_eq!(
gdk_root_for(&home, &home.join("sdk2/include/d3d12_xs.h")),
Some(home.join("sdk2")),
"directly below home, the first folder is the root"
);
assert!(!looks_like_title(&home.join("Documents/game/small.exe")));
assert!(!looks_like_title(&home.join("Documents/game/absent.exe")));
// Identical copies are one build, kept where the folder is fullest; a different file is
// another build.
let full = home.join("Documents/install");
let stray = home.join("Downloads");
fs::create_dir_all(&full).unwrap();
fs::create_dir_all(&stray).unwrap();
fs::write(full.join("title.exe"), b"same bytes").unwrap();
fs::write(full.join("data1.pak"), b"x").unwrap();
fs::write(full.join("data2.pak"), b"x").unwrap();
fs::write(stray.join("title.exe"), b"same bytes").unwrap();
fs::write(home.join("Documents/game/other.exe"), b"other bytes").unwrap();
// Synthetic files are not PE images, so the folder is scored here by its entry count;
// real candidates are scored by the imported DLLs found beside them.
let entries = |path: &Path| {
path.parent()
.and_then(|dir| fs::read_dir(dir).ok())
.map_or(0, Iterator::count)
};
let kept = distinct_builds_by(
vec![
stray.join("title.exe"),
full.join("title.exe"),
home.join("Documents/game/other.exe"),
],
entries,
);
assert_eq!(
companion_dlls(&full.join("title.exe")),
0,
"not a PE image: no companions"
);
assert_eq!(
kept,
vec![
full.join("title.exe"),
home.join("Documents/game/other.exe")
]
);
let _ = fs::remove_dir_all(&home);
}
/// The usage text must name every subcommand, so the classifier above is
/// not testing a table that nothing prints.
#[test]
@@ -1957,7 +2736,16 @@ sub setup_bottle_wineprefix {
text.contains("BetterXen Hybrid CLI"),
"usage carries the banner"
);
for sub in ["doctor", "probe", "shader", "trace", "run"] {
for sub in [
"doctor",
"setup",
"preflight",
"probe",
"shader",
"trace",
"report",
"run",
] {
assert!(text.contains(sub), "usage documents {sub}");
}
}
+2
View File
@@ -6,6 +6,8 @@
use std::collections::BTreeMap;
pub mod report;
#[derive(Debug, Default, PartialEq, Eq)]
pub struct TraceSummary {
pub total_lines: usize,
+582
View File
@@ -0,0 +1,582 @@
//! Run reports for the blocker queue (docs/process/working-method.md, "Run protocol").
//!
//! One JSONL log is one run. [`report_run`] reduces it to what decides the next task: how the
//! run ended, how far it got, and everything it stopped on. [`RunReport::signatures`] turns
//! those into the fixed strings blocker issues are titled with, so two people who hit the
//! same thing file the same issue. [`render_summary`] puts several runs side by side.
//!
//! What a log cannot show is said, not guessed: a run with no `run_end` record has an unknown
//! outcome, and a stall cannot be told from slow presentation because frames are logged at
//! powers of two.
use std::collections::BTreeMap;
use std::fmt::Write as _;
/// BetterXen's own guest modules. A fault whose innermost frame is in one of them is ours.
const BETTERXEN_MODULES: &[&str] = &[
"d3d12_xs.dll",
"xmem.dll",
"xcrdapi.dll",
"xgameruntime.dll",
"xg_xs.dll",
"acphal.dll",
"xapu.dll",
"chad.dll",
"gameinput.dll",
"bx_runtime_veh.dll",
"bx_shader_bridge.dll",
"ffx_bvh_hooks.dll",
];
/// How a run ended, from the launcher's `run_end` record.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum RunEnd {
/// No `run_end` record: the launcher was killed, or the log predates the record.
#[default]
Unknown,
/// The guest exited by itself with this status.
Exited(i32),
/// The launcher's `--timeout` stopped it: the run lasted as long as it was allowed to.
TimedOut,
/// A signal stopped the launcher.
Signalled(i32),
/// CrossOver could not be started.
LaunchFailed,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RunReport {
pub events: u64,
/// Guest clock span of the log, in milliseconds.
pub span_ms: u64,
pub end: RunEnd,
/// The last power-of-two frame count logged: at least this many frames were presented.
pub frames_at_least: Option<u64>,
/// Unimplemented calls reached, by signature, with how often.
pub unimplemented: BTreeMap<String, u64>,
/// Faults whose innermost frame is in a BetterXen module, by module.
pub faults: BTreeMap<String, u64>,
/// Exceptions nothing handled.
pub unhandled_exceptions: u64,
/// Pipeline stages that reached the shader gate, by "kind decision" (for example
/// "stream reject_unclassified_dxil").
pub shader_gate: BTreeMap<String, u64>,
/// Refused pipeline creations by kind.
pub pipelines_refused: BTreeMap<String, u64>,
/// Draws and dispatches skipped with a null pipeline bound (a lower bound).
pub skipped_work_at_least: Option<u64>,
}
fn json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let needle = format!("\"{key}\":\"");
let start = line.find(&needle)? + needle.len();
let rest = &line[start..];
// Details do not contain escaped quotes in practice; stop at the first unescaped one.
let mut end = 0;
let bytes = rest.as_bytes();
while end < bytes.len() {
if bytes[end] == b'"' && (end == 0 || bytes[end - 1] != b'\\') {
return Some(&rest[..end]);
}
end += 1;
}
None
}
fn json_u64(line: &str, key: &str) -> Option<u64> {
let needle = format!("\"{key}\":");
let start = line.find(&needle)? + needle.len();
let digits = &line[start..];
let end = digits
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(digits.len());
digits[..end].parse().ok()
}
fn number_after(detail: &str, key: &str) -> Option<u64> {
let start = detail.find(key)? + key.len();
let digits = &detail[start..];
let end = digits
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(digits.len());
digits[..end].parse().ok()
}
/// `IXUser[3]::slot_3` -> `unimplemented IXUser slot 3`;
/// `XboxDevice[81]::GetFrameStatisticsX` -> `unimplemented XboxDevice slot 81 (GetFrameStatisticsX)`.
fn vtable_signature(detail: &str) -> String {
let parsed = (|| {
let open = detail.find('[')?;
let close = detail[open..].find(']')? + open;
let slot: u32 = detail[open + 1..close].parse().ok()?;
let method = detail[close + 1..].strip_prefix("::")?;
Some((&detail[..open], slot, method))
})();
match parsed {
Some((interface, slot, method)) if method.starts_with("slot_") || method.is_empty() => {
format!("unimplemented {interface} slot {slot}")
}
Some((interface, slot, method)) => {
format!("unimplemented {interface} slot {slot} ({method})")
}
None => format!("unimplemented {detail}"),
}
}
/// The module of the innermost stack frame in an `av_context` detail (`... | stack: A.dll+12 B.dll+34`).
fn fault_module(detail: &str) -> Option<&str> {
let stack = detail.split("stack: ").nth(1)?;
let frame = stack.split_whitespace().next()?;
Some(frame.split('+').next().unwrap_or(frame))
}
fn is_betterxen_module(module: &str) -> bool {
BETTERXEN_MODULES
.iter()
.any(|m| m.eq_ignore_ascii_case(module))
}
/// Reduces one run's JSONL log to its report.
pub fn report_run(input: &str) -> RunReport {
let mut report = RunReport::default();
let mut first_ts = None;
let mut last_ts = 0;
for line in input.lines() {
let line = line.trim();
if !line.starts_with('{') {
continue;
}
report.events += 1;
let event = json_str(line, "event").unwrap_or("");
let detail = json_str(line, "detail").unwrap_or("");
if event == "run_end" {
report.end = match detail {
d if d.starts_with("outcome=exited") => {
let status = d
.split("status=")
.nth(1)
.and_then(|s| s.trim().parse().ok());
status.map_or(RunEnd::Unknown, RunEnd::Exited)
}
"outcome=timeout" => RunEnd::TimedOut,
d if d.starts_with("outcome=signal") => {
RunEnd::Signalled(number_after(d, "signal=").unwrap_or(0) as i32)
}
"outcome=launch_failed" => RunEnd::LaunchFailed,
_ => RunEnd::Unknown,
};
continue; // the launcher's record carries no guest timestamp
}
if let Some(ts) = json_u64(line, "ts_ms") {
first_ts.get_or_insert(ts);
last_ts = last_ts.max(ts);
}
match event {
"presentx_frames" => {
if let Some(n) = number_after(detail, "presented=") {
report.frames_at_least = Some(report.frames_at_least.unwrap_or(0).max(n));
}
}
"unimpl_vtable" => {
*report
.unimplemented
.entry(vtable_signature(detail))
.or_default() += 1
}
"unimpl_api" => {
*report
.unimplemented
.entry(format!("unimplemented {detail}"))
.or_default() += 1
}
"av_context" => {
if let Some(module) = fault_module(detail).filter(|m| is_betterxen_module(m)) {
*report.faults.entry(module.to_owned()).or_default() += 1;
}
}
"unhandled_exception" => report.unhandled_exceptions += 1,
"shader_gate" => {
let kind = detail
.split("pso=")
.nth(1)
.and_then(|s| s.split_whitespace().next());
let decision = detail
.split("decision=")
.nth(1)
.and_then(|s| s.split_whitespace().next());
if let (Some(kind), Some(decision)) = (kind, decision) {
*report
.shader_gate
.entry(format!("{kind} {decision}"))
.or_default() += 1;
}
}
"pipeline_refused" => {
let kind = detail.split(" pipeline refused").next().unwrap_or(detail);
*report.pipelines_refused.entry(kind.to_owned()).or_default() += 1;
}
"null_render_skip" => {
if let Some(n) = number_after(detail, "total skipped=") {
report.skipped_work_at_least =
Some(report.skipped_work_at_least.unwrap_or(0).max(n));
}
}
_ => {}
}
}
report.span_ms = first_ts.map_or(0, |first| last_ts.saturating_sub(first));
report
}
impl RunReport {
/// The strings blocker issues are titled with (`[blocker] <signature>`), most severe first.
pub fn signatures(&self) -> Vec<String> {
let mut out = Vec::new();
match self.end {
RunEnd::Exited(status) if status != 0 => out.push(format!("exit status {status}")),
RunEnd::LaunchFailed => out.push("launch failed".to_owned()),
_ => {}
}
if self.unhandled_exceptions > 0 {
out.push("unhandled exception".to_owned());
}
out.extend(
self.faults
.keys()
.map(|module| format!("fault in {module}")),
);
out.extend(self.unimplemented.keys().cloned());
if self.skipped_work_at_least.is_some() {
out.push("draws or dispatches skipped with a null pipeline".to_owned());
}
out
}
/// True when the run reached the frame loop and stopped on nothing: the Boot gate's
/// per-run condition, except for its length, which the caller sets with `--timeout`.
pub fn clean_boot(&self) -> bool {
self.end == RunEnd::TimedOut
&& self.frames_at_least.is_some()
&& self.unimplemented.is_empty()
&& self.faults.is_empty()
&& self.unhandled_exceptions == 0
}
}
fn end_text(end: &RunEnd) -> String {
match end {
RunEnd::Unknown => "unknown (no run_end record)".to_owned(),
RunEnd::Exited(status) => format!("exited by itself, status {status}"),
RunEnd::TimedOut => "ran until the timeout".to_owned(),
RunEnd::Signalled(signal) => format!("stopped by signal {signal}"),
RunEnd::LaunchFailed => "launch failed".to_owned(),
}
}
/// The report of one run, as text.
pub fn render_run(name: &str, report: &RunReport) -> String {
let mut out = String::new();
let _ = writeln!(out, "Run {name}");
let _ = writeln!(out, " outcome : {}", end_text(&report.end));
let _ = writeln!(
out,
" frames presented : {}",
report
.frames_at_least
.map_or("none".to_owned(), |n| format!("at least {n}"))
);
let _ = writeln!(
out,
" log span : {:.1} s, {} events",
report.span_ms as f64 / 1000.0,
report.events
);
if !report.unimplemented.is_empty() {
let _ = writeln!(out, " unimplemented calls:");
for (signature, count) in &report.unimplemented {
let _ = writeln!(out, " {count:>7}x {signature}");
}
}
if !report.faults.is_empty() || report.unhandled_exceptions > 0 {
let _ = writeln!(out, " faults:");
for (module, count) in &report.faults {
let _ = writeln!(out, " {count:>7}x fault in {module}");
}
if report.unhandled_exceptions > 0 {
let _ = writeln!(
out,
" {:>7}x unhandled exception",
report.unhandled_exceptions
);
}
}
if !report.shader_gate.is_empty() || !report.pipelines_refused.is_empty() {
let _ = writeln!(out, " pipelines:");
for (kind, count) in &report.shader_gate {
let _ = writeln!(out, " {count:>7}x shader stage: {kind}");
}
for (kind, count) in &report.pipelines_refused {
let _ = writeln!(out, " {count:>7}x refused: {kind}");
}
if let Some(skipped) = report.skipped_work_at_least {
let _ = writeln!(
out,
" at least {skipped} draws or dispatches skipped (null pipeline)"
);
}
}
out
}
/// Several runs side by side, then every signature with the number of runs that hit it.
pub fn render_summary(runs: &[(String, RunReport)]) -> String {
let mut out = String::new();
let total = runs.len();
let _ = writeln!(out, "Summary of {total} run(s)");
for (name, report) in runs {
let _ = writeln!(
out,
" {name}: {}; frames {}; {}",
end_text(&report.end),
report
.frames_at_least
.map_or("none".to_owned(), |n| format!(">= {n}")),
if report.clean_boot() {
"clean"
} else {
"not clean"
}
);
}
let clean = runs.iter().filter(|(_, r)| r.clean_boot()).count();
let _ = writeln!(
out,
"Clean runs (frame loop reached, nothing stopped on, ran to the timeout): {clean} of {total}"
);
let mut hits: BTreeMap<String, usize> = BTreeMap::new();
for (_, report) in runs {
for signature in report.signatures() {
*hits.entry(signature).or_default() += 1;
}
}
if hits.is_empty() {
let _ = writeln!(out, "Signatures: none");
} else {
let _ = writeln!(out, "Signatures (runs that hit each):");
let mut ordered: Vec<_> = hits.into_iter().collect();
ordered.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
for (signature, count) in ordered {
let _ = writeln!(out, " {count} of {total} {signature}");
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn line(ts: u64, sub: &str, event: &str, detail: &str) -> String {
format!(
"{{\"ts_ms\":{ts},\"tid\":1,\"level\":\"INFO\",\"sub\":\"{sub}\",\"event\":\"{event}\",\"detail\":\"{detail}\"}}\n"
)
}
#[test]
fn a_clean_run_reports_frames_span_and_no_signatures() {
let log = line(
1000,
"d3d12_xs",
"presentx_frames",
"frames presented=1 last hr=0x00000000",
) + &line(
4000,
"d3d12_xs",
"presentx_frames",
"frames presented=64 last hr=0x00000000",
) + &line(0, "bx_cli", "run_end", "outcome=timeout");
let report = report_run(&log);
assert_eq!(report.frames_at_least, Some(64));
assert_eq!(
report.span_ms, 3000,
"the launcher's record must not stretch the guest span"
);
assert_eq!(report.end, RunEnd::TimedOut);
assert!(report.clean_boot());
assert!(report.signatures().is_empty());
}
#[test]
fn unimplemented_calls_become_stable_signatures() {
let log = line(1, "com_vtable", "unimpl_vtable", "IXUser[3]::slot_3")
+ &line(
2,
"com_vtable",
"unimpl_vtable",
"XboxDevice[81]::GetFrameStatisticsX",
)
+ &line(
3,
"com_vtable",
"unimpl_vtable",
"XboxDevice[81]::GetFrameStatisticsX",
)
+ &line(
4,
"stub",
"unimpl_api",
"d3d12_xs.dll!CreatePlacedResourceX(texture contents)",
);
let report = report_run(&log);
assert_eq!(
report.unimplemented.get("unimplemented IXUser slot 3"),
Some(&1)
);
assert_eq!(
report
.unimplemented
.get("unimplemented XboxDevice slot 81 (GetFrameStatisticsX)"),
Some(&2)
);
assert!(report.signatures().contains(
&"unimplemented d3d12_xs.dll!CreatePlacedResourceX(texture contents)".to_owned()
));
assert!(
!report.clean_boot(),
"an unimplemented call is not a clean run"
);
}
#[test]
fn a_fault_counts_only_when_its_innermost_frame_is_a_betterxen_module() {
let ours = line(
1,
"runtime_veh",
"av_context",
"rip=1 fault=2 | stack: XCRDAPI.dll+9a51 ntdll.dll+10",
);
let theirs = line(
2,
"runtime_veh",
"av_context",
"rip=1 fault=2 | stack: title.exe+10 XCRDAPI.dll+9a51",
);
let report = report_run(&(ours + &theirs));
assert_eq!(report.faults.get("XCRDAPI.dll"), Some(&1));
assert_eq!(report.faults.len(), 1);
assert_eq!(report.signatures(), vec!["fault in XCRDAPI.dll".to_owned()]);
}
#[test]
fn the_end_of_a_run_is_read_from_the_launcher_record() {
let exited = report_run(&line(0, "bx_cli", "run_end", "outcome=exited status=5"));
assert_eq!(exited.end, RunEnd::Exited(5));
assert_eq!(exited.signatures(), vec!["exit status 5".to_owned()]);
assert_eq!(
report_run(&line(0, "bx_cli", "run_end", "outcome=exited status=0")).signatures(),
Vec::<String>::new()
);
assert_eq!(
report_run(&line(0, "bx_cli", "run_end", "outcome=signal signal=15")).end,
RunEnd::Signalled(15)
);
assert_eq!(
report_run(&line(0, "bx_cli", "run_end", "outcome=launch_failed")).end,
RunEnd::LaunchFailed
);
// No record: unknown, and never "clean".
let unknown = report_run(&line(
1,
"d3d12_xs",
"presentx_frames",
"frames presented=8 last hr=0x0",
));
assert_eq!(unknown.end, RunEnd::Unknown);
assert!(!unknown.clean_boot());
}
#[test]
fn pipelines_are_counted_by_kind() {
let log = line(
1,
"d3d12_xs",
"shader_gate",
"pso=stream stage=VS decision=reject_unclassified_dxil hr=0x80004001",
) + &line(
2,
"d3d12_xs",
"shader_gate",
"pso=compute stage=CS decision=pass_dxil hr=0x00000000",
) + &line(
3,
"d3d12_xs",
"pipeline_refused",
"deserialized graphics (console code) pipeline refused hr=0x80004001",
) + &line(
4,
"d3d12_xs",
"null_render_skip",
"DrawInstanced with a null pipeline bound; total skipped=4",
) + &line(
5,
"d3d12_xs",
"null_render_skip",
"DrawInstanced with a null pipeline bound; total skipped=8",
);
let report = report_run(&log);
assert_eq!(
report.shader_gate.get("stream reject_unclassified_dxil"),
Some(&1)
);
assert_eq!(report.shader_gate.get("compute pass_dxil"), Some(&1));
assert_eq!(
report
.pipelines_refused
.get("deserialized graphics (console code)"),
Some(&1)
);
assert_eq!(report.skipped_work_at_least, Some(8));
}
#[test]
fn the_summary_counts_runs_per_signature_and_clean_runs() {
let clean = report_run(
&(line(
1,
"d3d12_xs",
"presentx_frames",
"frames presented=16 last hr=0x0",
) + &line(0, "bx_cli", "run_end", "outcome=timeout")),
);
let stopped = report_run(
&(line(1, "com_vtable", "unimpl_vtable", "IXUser[3]::slot_3")
+ &line(0, "bx_cli", "run_end", "outcome=exited status=1")),
);
let text = render_summary(&[
("a".to_owned(), clean),
("b".to_owned(), stopped.clone()),
("c".to_owned(), stopped),
]);
assert!(
text.contains(
"Clean runs (frame loop reached, nothing stopped on, ran to the timeout): 1 of 3"
),
"{text}"
);
assert!(text.contains(" 2 of 3 exit status 1\n"), "{text}");
assert!(
text.contains(" 2 of 3 unimplemented IXUser slot 3\n"),
"{text}"
);
}
#[test]
fn lines_that_are_not_json_records_are_ignored() {
let report = report_run("warning: not a record\n\n{\"broken\n");
assert_eq!(
report.events, 1,
"a line starting with a brace is counted even when malformed"
);
assert!(report.signatures().is_empty());
}
}
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Build the shader corpus (#649) locally. For every kernel in shader-transpiler/corpus/hlsl:
# <name>.xs.cso / .xs.lst console container (DXIL + ACCC/FSPX) and listing, from xdxc
# <name>.pix.lst console ISA listing with encodings, from the PIX compiler
# <name>.pc.cso DXIL from the public PC DXC, for a D3DMetal reference run
# <name>.code.bin / .aco.s console machine code extracted from the ACCC chunk, and its
# llvm-mc gfx1030 disassembly
# Outputs go to $OUT (default target/shader-corpus, which git ignores) and must not be
# committed: they are compiler outputs from authorized GDK tools (see the corpus README).
#
# Required environment:
# WINE a CrossOver/Wine loader that accepts --bottle (CrossOver's bin/wine)
# BOTTLE a scratch bottle for the compilers (never a title's bottle)
# XDXC the console xdxc.exe (GDK, xbox/bin/gen9)
# PIX_DXC the console PIX dxc.exe (GDK, bin/Scarlett/pixsc)
# DXC the PC dxc.exe from DXC release v1.9.2609
# LLVM_MC llvm-mc built with the AMDGPU target
set -euo pipefail
for var in WINE BOTTLE XDXC PIX_DXC DXC LLVM_MC; do
if [ -z "${!var:-}" ]; then
echo "error: set $var (see the header of $0)" >&2
exit 2
fi
done
root=$(cd "$(dirname "$0")/../.." && pwd)
src="$root/shader-transpiler/corpus/hlsl"
out=${OUT:-$root/target/shader-corpus}
mkdir -p "$out"
# Wine takes Windows paths; Z: maps the host root.
win() { printf 'Z:%s' "$1"; }
compile() { WINEDEBUG=-all "$WINE" --bottle "$BOTTLE" "$@"; }
failures=0
for hlsl in "$src"/*.hlsl; do
name=$(basename "$hlsl" .hlsl)
log="$out/$name.log"
: > "$log"
if ! compile "$XDXC" -T cs_6_6 -E main -Fo "$(win "$out/$name.xs.cso")" -Fc "$(win "$out/$name.xs.lst")" \
"$(win "$hlsl")" >>"$log" 2>&1; then
echo "FAIL $name: xdxc (see $log)"; failures=$((failures + 1)); continue
fi
if ! compile "$PIX_DXC" -T cs_6_6 -E main -Fc "$(win "$out/$name.pix.lst")" "$(win "$hlsl")" >>"$log" 2>&1; then
echo "FAIL $name: PIX dxc (see $log)"; failures=$((failures + 1)); continue
fi
if ! compile "$DXC" -nologo -T cs_6_6 -E main -Fo "$(win "$out/$name.pc.cso")" "$(win "$hlsl")" >>"$log" 2>&1; then
echo "FAIL $name: PC dxc (see $log)"; failures=$((failures + 1)); continue
fi
if ! python3 "$root/scripts/shader-corpus/extract_code.py" "$out/$name.xs.cso" \
--bin "$out/$name.code.bin" --asm "$out/$name.aco.s" --llvm-mc "$LLVM_MC"; then
echo "FAIL $name: code extraction or decode (see $out/$name.aco.s)"; failures=$((failures + 1)); continue
fi
done
if [ "$failures" -ne 0 ]; then
echo "FAIL: shader corpus ($failures kernel(s) failed)"
exit 1
fi
# Sums of the compiled inputs, so two people with the compilers can confirm they hold the same
# corpus (README, "Reproducibility"). Local only, like every other output.
(cd "$out" && shasum -a 256 ./*.xs.cso ./*.pc.cso > SHA256SUMS)
echo "PASS: shader corpus built in $out"
+158
View File
@@ -0,0 +1,158 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Extract the RDNA 2 code from a console-compiled DXBC container (#649).
The layout below was derived from containers the console compiler produced for BetterXen's own
corpus kernels (shader-transpiler/corpus/README.md). Every assumption is checked; anything that
does not match raises instead of guessing.
- DXBC: chunk count at byte 28, chunk offsets from byte 32; each chunk is a FourCC, a u32 size
and the payload. The console code is in the `ACCC` chunk.
- FSPX (the ACCC payload): a 16-byte header (magic `FSPX`, version, section count, total size),
then one 16-byte entry per section: kind, offset, size, reserved (0). Offsets are relative to
the start of the payload.
- Section kind 6 holds the code. It starts with `v_nop_xbox_data` instructions that carry the
shader hash, followed by gfx1030 machine code ending in `s_endpgm`. A `v_nop_xbox_data` is the
public VOP3 `v_nop` opcode (top 16 bits of the first word 0xD580) whose third source operand is
a 32-bit literal (operand value 255), which makes it 12 bytes; the public decoder rejects that
form. A plain `v_nop` (8 bytes, no literal) is ordinary code and is not skipped.
"""
import argparse
import struct
import subprocess
import sys
FSPX_MAGIC = b"FSPX"
CODE_SECTION_KIND = 6
XBOX_DATA_NOP_HIGH = 0xD580 # VOP3 v_nop, top 16 bits of the first word
XBOX_DATA_NOP_BYTES = 12 # two VOP3 words and one 32-bit literal
VOP3_SRC2_SHIFT = 18 # second word: src0 [8:0], src1 [17:9], src2 [26:18]
VOP3_OPERAND_MASK = 0x1FF
OPERAND_LITERAL = 255 # public gfx10 operand value for "a 32-bit literal follows"
S_ENDPGM = 0xBF810000
class LayoutError(Exception):
pass
def chunk(container, fourcc):
if container[:4] != b"DXBC" or len(container) < 32:
raise LayoutError("not a DXBC container")
count = struct.unpack_from("<I", container, 28)[0]
if 32 + 4 * count > len(container):
raise LayoutError("chunk table overruns the container")
for i in range(count):
offset = struct.unpack_from("<I", container, 32 + 4 * i)[0]
if offset + 8 > len(container):
raise LayoutError(f"chunk {i} header overruns the container")
size = struct.unpack_from("<I", container, offset + 4)[0]
if container[offset:offset + 4] == fourcc:
if offset + 8 + size > len(container):
raise LayoutError(f"{fourcc.decode()} chunk overruns the container")
return container[offset + 8:offset + 8 + size]
raise LayoutError(f"no {fourcc.decode()} chunk")
def sections(payload):
if payload[:4] != FSPX_MAGIC or len(payload) < 16:
raise LayoutError("ACCC payload does not start with FSPX")
_version, count, total = struct.unpack_from("<III", payload, 4)
if total != len(payload):
raise LayoutError(f"FSPX total size {total} != payload size {len(payload)}")
table_end = 16 + 16 * count
if table_end > len(payload):
raise LayoutError("FSPX section table overruns the payload")
result = []
for i in range(count):
kind, offset, size, reserved = struct.unpack_from("<IIII", payload, 16 + 16 * i)
if reserved != 0:
raise LayoutError(f"FSPX section {i} reserved word is {reserved:#x}, not 0")
if offset < table_end or offset + size > len(payload):
raise LayoutError(f"FSPX section {i} [{offset}, {offset + size}) is out of bounds")
result.append((kind, offset, size))
return result
def code_section(payload):
matches = [(o, s) for k, o, s in sections(payload) if k == CODE_SECTION_KIND]
if len(matches) != 1:
raise LayoutError(f"expected one kind-{CODE_SECTION_KIND} section, found {len(matches)}")
offset, size = matches[0]
return payload[offset:offset + size]
def is_xbox_data_nop(code):
"""True when `code` starts with a v_nop whose third source operand is a literal."""
if len(code) < XBOX_DATA_NOP_BYTES:
return False
first, second = struct.unpack_from("<II", code, 0)
return (first >> 16 == XBOX_DATA_NOP_HIGH
and (second >> VOP3_SRC2_SHIFT) & VOP3_OPERAND_MASK == OPERAND_LITERAL)
def strip_xbox_data(code):
"""Return (machine code, number of v_nop_xbox_data skipped)."""
skipped = 0
while is_xbox_data_nop(code):
code = code[XBOX_DATA_NOP_BYTES:]
skipped += 1
return code, skipped
def until_endpgm(code):
"""Cut after the first dword-aligned s_endpgm. A literal that happens to equal it is not
excluded here; the disassembler run is the authority on instruction boundaries."""
for i in range(0, len(code) - 3, 4):
if struct.unpack_from("<I", code, i)[0] == S_ENDPGM:
return code[:i + 4]
raise LayoutError("no s_endpgm in the code section")
def extract(container):
code, skipped = strip_xbox_data(code_section(chunk(container, b"ACCC")))
return until_endpgm(code), skipped
def disassemble(code, llvm_mc):
text = " ".join(f"0x{b:02x}" for b in code)
run = subprocess.run(
[llvm_mc, "-arch=amdgcn", "-mcpu=gfx1030", "--disassemble", "-show-encoding"],
input=text, capture_output=True, text=True, check=False,
)
lines = [ln.strip() for ln in run.stdout.splitlines() if ln.strip() and not ln.strip().startswith(".")]
problems = [ln for ln in run.stderr.splitlines() if "invalid" in ln.lower() or "warning" in ln.lower()]
return lines, problems
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("container", help="console-compiled .cso (DXBC with an ACCC chunk)")
parser.add_argument("--bin", help="write the extracted machine code here")
parser.add_argument("--asm", help="write the llvm-mc disassembly here (needs --llvm-mc)")
parser.add_argument("--llvm-mc", help="path to llvm-mc with the AMDGPU target")
args = parser.parse_args()
try:
code, skipped = extract(open(args.container, "rb").read())
except LayoutError as error:
print(f"error: {args.container}: {error}", file=sys.stderr)
return 2
if args.bin:
open(args.bin, "wb").write(code)
status = 0
summary = f"{len(code)} code bytes, {skipped} v_nop_xbox_data skipped"
if args.llvm_mc:
lines, problems = disassemble(code, args.llvm_mc)
summary += f", {len(lines)} instructions"
if problems or not lines or "s_endpgm" not in lines[-1]:
summary += ", DECODE PROBLEMS"
status = 1
if args.asm:
open(args.asm, "w").write("\n".join(lines + problems) + "\n")
print(f"{args.container}: {summary}")
return status
if __name__ == "__main__":
sys.exit(main())
+106
View File
@@ -0,0 +1,106 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Unit tests for extract_code.py on synthetic containers (no GDK or compiler needed)."""
import importlib.util
import struct
import unittest
from pathlib import Path
spec = importlib.util.spec_from_file_location("extract_code", Path(__file__).with_name("extract_code.py"))
ec = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ec)
S_NOP = struct.pack("<I", 0xBF800000) # public gfx10 encoding of s_nop 0
S_ENDPGM = struct.pack("<I", 0xBF810000)
# Synthetic, not compiler output: the v_nop opcode with made-up low bits, a second word whose
# third source operand is 255 (literal) with made-up low bits, and a made-up literal.
XBOX_DATA = struct.pack("<III", 0xD5801111, 0x03FC2222, 0x33333333)
# The public VOP3 encoding of a plain `v_nop` (llvm-mc -mcpu=gfx1030): 8 bytes, no literal.
V_NOP_E64 = struct.pack("<II", 0xD5800000, 0x02010080)
def fspx(sections, total=None):
"""sections: list of (kind, bytes). Builds an FSPX payload with the parsed layout."""
count = len(sections)
offset = 16 + 16 * count
table, body = b"", b""
for kind, data in sections:
table += struct.pack("<IIII", kind, offset + len(body), len(data), 0)
body += data
size = 16 + len(table) + len(body)
return b"FSPX" + struct.pack("<III", 1, count, size if total is None else total) + table + body
def dxbc(chunks):
"""chunks: list of (fourcc, bytes)."""
header = 32 + 4 * len(chunks)
offsets, body = [], b""
for fourcc, data in chunks:
offsets.append(header + len(body))
body += fourcc + struct.pack("<I", len(data)) + data
total = header + len(body)
head = b"DXBC" + b"\0" * 16 + struct.pack("<III", 1, total, len(chunks))
return head + b"".join(struct.pack("<I", o) for o in offsets) + body
class ExtractTests(unittest.TestCase):
def test_extracts_code_after_xbox_data_nops(self):
code = XBOX_DATA * 3 + S_NOP + S_ENDPGM + b"\0" * 8
container = dxbc([(b"DXIL", b"x" * 12), (b"ACCC", fspx([(0, b"a" * 28), (6, code), (7, b"b" * 8)]))])
extracted, skipped = ec.extract(container)
self.assertEqual(skipped, 3)
self.assertEqual(extracted, S_NOP + S_ENDPGM)
def test_plain_v_nop_is_code_not_xbox_data(self):
# A plain v_nop at the start of the code must not be skipped as 12 bytes, which would
# misalign everything after it.
code = V_NOP_E64 + S_NOP + S_ENDPGM
container = dxbc([(b"ACCC", fspx([(6, code)]))])
self.assertEqual(ec.extract(container), (code, 0))
def test_plain_v_nop_after_xbox_data_is_kept(self):
code = XBOX_DATA * 2 + V_NOP_E64 + S_ENDPGM
container = dxbc([(b"ACCC", fspx([(6, code)]))])
self.assertEqual(ec.extract(container), (V_NOP_E64 + S_ENDPGM, 2))
def test_no_xbox_data_nops(self):
container = dxbc([(b"ACCC", fspx([(6, S_NOP + S_ENDPGM)]))])
self.assertEqual(ec.extract(container), (S_NOP + S_ENDPGM, 0))
def test_missing_accc(self):
with self.assertRaisesRegex(ec.LayoutError, "no ACCC chunk"):
ec.extract(dxbc([(b"DXIL", b"x" * 4)]))
def test_not_fspx(self):
with self.assertRaisesRegex(ec.LayoutError, "does not start with FSPX"):
ec.extract(dxbc([(b"ACCC", b"ABCD" + b"\0" * 12)]))
def test_total_size_mismatch(self):
with self.assertRaisesRegex(ec.LayoutError, "total size"):
ec.extract(dxbc([(b"ACCC", fspx([(6, S_ENDPGM)], total=999))]))
def test_section_inside_table_is_rejected(self):
payload = bytearray(fspx([(6, S_ENDPGM)]))
struct.pack_into("<I", payload, 16 + 4, 4) # section offset points into the header
with self.assertRaisesRegex(ec.LayoutError, "out of bounds"):
ec.extract(dxbc([(b"ACCC", bytes(payload))]))
def test_nonzero_reserved_word_is_rejected(self):
payload = bytearray(fspx([(6, S_ENDPGM)]))
struct.pack_into("<I", payload, 16 + 12, 1)
with self.assertRaisesRegex(ec.LayoutError, "reserved word"):
ec.extract(dxbc([(b"ACCC", bytes(payload))]))
def test_needs_exactly_one_code_section(self):
with self.assertRaisesRegex(ec.LayoutError, "found 0"):
ec.extract(dxbc([(b"ACCC", fspx([(0, S_ENDPGM)]))]))
with self.assertRaisesRegex(ec.LayoutError, "found 2"):
ec.extract(dxbc([(b"ACCC", fspx([(6, S_ENDPGM), (6, S_ENDPGM)]))]))
def test_code_without_endpgm(self):
with self.assertRaisesRegex(ec.LayoutError, "no s_endpgm"):
ec.extract(dxbc([(b"ACCC", fspx([(6, S_NOP * 4)]))]))
if __name__ == "__main__":
unittest.main()
+110
View File
@@ -0,0 +1,110 @@
# Shader corpus (Phase 0, #649)
A corpus of BetterXen-authored compute kernels compiled for the console, so the RDNA 2 shader
translator ([ADR 0008](../../docs/adr/0008-m2-shader-format-gate.md), Branch D2) can be tested
against inputs whose correct behaviour is known independently of the translator
([AGENTS.md](../../AGENTS.md) §5).
For each kernel in [`hlsl/`](hlsl), three compilers produce:
- the **console container** a title would ship: DXBC with `DXIL` **and** an `ACCC` chunk whose
payload is an `FSPX` package holding the RDNA 2 code;
- **the console compiler's listing** of the RDNA 2 code for the same source, with encodings (compiler output, not
Microsoft documentation);
- **PC DXIL** from the public DXC, which runs on D3DMetal today and gives the reference result.
## What is committed and what is not
| Committed | Not committed |
|---|---|
| The HLSL kernels in `hlsl/` (original BetterXen code, GPL-3.0-or-later) | Every compiler output: containers, listings, extracted code and disassembly |
| [`scripts/shader-corpus/build.sh`](../../scripts/shader-corpus/build.sh) and [`extract_code.py`](../../scripts/shader-corpus/extract_code.py) with its unit tests | The GDK, its compilers, and any file from it |
| Layout facts derived from our own outputs (below) | |
The console compilers come from authorized GDK material and run on BetterXen's own HLSL only.
Their outputs stay in `target/shader-corpus/` (git-ignored) and are never committed. Run the
compilers in a scratch bottle, never in a title's bottle.
The layout facts below are derived from those outputs and **are** published in this file. On
2026-11-29 the repository owner reported that the team had approved publishing them, and decided
that BetterXen is no longer a clean-room project ([CONTRIBUTING](../../CONTRIBUTING.md), #650):
contributors may use the GDK compilers and read this file. The compilers, their outputs and the
GDK itself are still never committed.
## Reproducibility
The corpus can only be rebuilt by someone who has the GDK compilers. CI cannot rebuild it, and a
contributor without the GDK cannot reproduce its inputs. That limits what the corpus proves: it
checks a translator against shaders with known source, on the word of whoever built it.
To let two people with access confirm they hold the same inputs, `build.sh` writes
`target/shader-corpus/SHA256SUMS` with the SHA-256 of every `.xs.cso` and `.pc.cso`. The sums are
not listed here yet: they are worth committing only once two independent builds agree, which
also shows whether the compilers' output is deterministic.
## Building
```sh
WINE=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/bin/wine \
BOTTLE=<scratch bottle> \
XDXC=<GDK>/…/xbox/bin/gen9/xdxc.exe \
PIX_DXC=<GDK>/…/bin/Scarlett/pixsc/dxc.exe \
DXC=<DXC v1.9.2609>/bin/x64/dxc.exe \
LLVM_MC=$(brew --prefix llvm)/bin/llvm-mc \
scripts/shader-corpus/build.sh
```
All eight kernels currently build, and every kernel's console code extracts and decodes with
LLVM's public `gfx1030` disassembler (2026-11-28, Apple Silicon, CrossOver 26.3):
| Kernel | What it exercises | Console instructions |
|---|---|---|
| `fill` | integer ALU | 11 |
| `branch` | divergent if/else | 17 |
| `loop` | per-lane trip count, early exit | 60 |
| `lds` | groupshared memory, barriers, tree reduction | 58 |
| `wave` | `WaveActiveSum`, `WavePrefixSum`, `WaveReadLaneFirst`, `WaveActiveBallot` | 47 |
| `atomic` | global `InterlockedAdd` / `InterlockedMax` with returned values | 57 |
| `floatmath` | `mad`, `sqrt`, `rcp`, float/uint conversion | 22 |
| `groupid` | 2D groups, `SV_GroupID`, `SV_GroupThreadID`, `SV_GroupIndex` | 17 |
`extract_code.py`'s unit tests use synthetic containers and need no GDK:
`python3 -m unittest scripts/shader-corpus/test_extract_code.py`.
## Layout facts (derived from our own outputs)
- **Container:** `xdxc` keeps the `DXIL` chunk and adds `ACCC`. Title containers can be `ACCC`-only;
the `ACCC` format is the same. `bx-cli shader` rejects these containers with the same `FSPX`
error as a title's console-only shaders, so the corpus is a faithful stand-in for that format.
- **`FSPX`:** a 16-byte header (magic `FSPX`, version `1`, section count, total size equal to the
payload size), then one 16-byte entry per section: kind, offset from the start of the payload,
size, and a reserved `0`. The corpus containers have four sections, of kinds 0, 1, 6 and 7.
- **Code:** section kind 6. It starts with `v_nop_xbox_data` instructions that carry the shader
hash: the public VOP3 `v_nop` opcode (top 16 bits `0xD580`) with a literal as its third source
operand, 12 bytes each, a form the public decoder rejects. A plain `v_nop` (8 bytes) is ordinary
code. Every corpus kernel has three `v_nop_xbox_data`. They are followed by `gfx1030` machine code ending in `s_endpgm`, then
padding.
- **Two console backends.** `xdxc`'s `ACCC` code comes from its ACO step; the PIX compiler's
listing comes from its NewBE step. They generate different code for the same source (for example,
the inline buffer descriptor's word 3 is `0x31016fac` from ACO and `0x11014fac` from NewBE). The
NewBE listing documents the console ABI (#638); the ACO code is what `ACCC` containers carry.
Both use the root UAV address in `s[4:5]` here.
## Observations so far
- `wave` compiles to the cross-lane instructions that matter for running 64-wide waves on 32-wide
Apple GPUs: DPP `row_shr` and `quad_perm`, `v_permlanex16`, `v_readlane` and `v_readfirstlane`.
- **Open question:** in `wave`, LLVM decodes one instruction in the ballot sequence as
`v_cmp_class_f16` with literal `0x7c01`, although the kernel has no half-precision code. Either
ACO genuinely emits it there, or the console gives that opcode a meaning the public `gfx1030`
decoder does not know. The reference runs below should tell.
## Next steps
1. A reference runner: dispatch each kernel's PC DXIL on D3DMetal with fixed inputs and record
the output buffers as expected results, plus CPU-computed expectations where the result is a
pure function of the inputs.
2. The decoder (Phase 1), checked instruction by instruction against LLVM's disassembly and the
NewBE listings.
3. More kernels as the decoder grows: textures and samplers, structured control flow with nested
loops, 64-bit atomics, and wave32 versus wave64 variants.
+17
View File
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// BetterXen shader corpus (#649): original kernel, written for translator tests.
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
StructuredBuffer<uint> input : register(t0);
RWStructuredBuffer<uint> output : register(u0);
// Global atomics: add and max into shared counters, with returned old values.
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
void main(uint3 tid : SV_DispatchThreadID) {
uint x = input[tid.x];
uint before;
InterlockedAdd(output[0], x, before);
InterlockedMax(output[1], x);
output[2u + tid.x] = before;
}
+16
View File
@@ -0,0 +1,16 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// BetterXen shader corpus (#649): original kernel, written for translator tests.
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
StructuredBuffer<uint> input : register(t0);
RWStructuredBuffer<uint> output : register(u0);
// Divergent control flow: lanes take different sides of an if/else.
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
void main(uint3 tid : SV_DispatchThreadID) {
uint x = input[tid.x];
uint r;
if ((x & 1u) != 0u) { r = x * 3u + 1u; } else { r = x >> 1; }
output[tid.x] = r;
}
+14
View File
@@ -0,0 +1,14 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// BetterXen shader corpus (#649): original kernel, written for translator tests.
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
StructuredBuffer<uint> input : register(t0);
RWStructuredBuffer<uint> output : register(u0);
// Integer ALU: multiply, shift, xor-add (no memory reads).
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
void main(uint3 tid : SV_DispatchThreadID) {
uint v = tid.x * 0x9e3779b1u;
output[tid.x] = (v ^ (v >> 15)) + 0x01234567u;
}
@@ -0,0 +1,16 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// BetterXen shader corpus (#649): original kernel, written for translator tests.
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
StructuredBuffer<uint> input : register(t0);
RWStructuredBuffer<uint> output : register(u0);
// Float ALU and conversions: fma, sqrt, rcp, float<->uint.
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
void main(uint3 tid : SV_DispatchThreadID) {
float f = (float)input[tid.x] * asfloat(c0);
float g = mad(f, 0.5f, 1.0f);
float h = sqrt(abs(g)) + rcp(g + 2.0f);
output[tid.x] = asuint(h) ^ (uint)floor(h * 256.0f);
}
@@ -0,0 +1,14 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// BetterXen shader corpus (#649): original kernel, written for translator tests.
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
StructuredBuffer<uint> input : register(t0);
RWStructuredBuffer<uint> output : register(u0);
// System values: group id, group thread id and flattened indices with a 2D group.
[RootSignature(BX_RS)] [numthreads(8, 8, 1)]
void main(uint3 tid : SV_DispatchThreadID, uint3 gtid : SV_GroupThreadID, uint3 gid : SV_GroupID, uint gi : SV_GroupIndex) {
uint idx = (gid.y * c0 + gid.x) * 64u + gi;
output[idx] = (gtid.x << 24) | (gtid.y << 16) | (tid.x << 8) | tid.y;
}
+20
View File
@@ -0,0 +1,20 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// BetterXen shader corpus (#649): original kernel, written for translator tests.
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
StructuredBuffer<uint> input : register(t0);
RWStructuredBuffer<uint> output : register(u0);
// Groupshared memory and barriers: a per-group tree reduction.
groupshared uint scratch[64];
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
void main(uint3 tid : SV_DispatchThreadID, uint3 gtid : SV_GroupThreadID, uint3 gid : SV_GroupID) {
scratch[gtid.x] = input[tid.x];
GroupMemoryBarrierWithGroupSync();
for (uint s = 32u; s > 0u; s >>= 1) {
if (gtid.x < s) { scratch[gtid.x] += scratch[gtid.x + s]; }
GroupMemoryBarrierWithGroupSync();
}
if (gtid.x == 0u) { output[gid.x] = scratch[0]; }
}
+19
View File
@@ -0,0 +1,19 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// BetterXen shader corpus (#649): original kernel, written for translator tests.
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
StructuredBuffer<uint> input : register(t0);
RWStructuredBuffer<uint> output : register(u0);
// Loop with a per-lane, data-dependent trip count and an early exit.
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
void main(uint3 tid : SV_DispatchThreadID) {
uint n = input[tid.x] % (c0 + 1u);
uint acc = 0u;
for (uint i = 0u; i < n; ++i) {
acc += i * c1;
if (acc > c2) { break; }
}
output[tid.x] = acc;
}
+21
View File
@@ -0,0 +1,21 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// BetterXen shader corpus (#649): original kernel, written for translator tests.
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
StructuredBuffer<uint> input : register(t0);
RWStructuredBuffer<uint> output : register(u0);
// Cross-lane wave operations: the costly case when a 64-wide wave runs as two 32-wide halves.
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
void main(uint3 tid : SV_DispatchThreadID) {
uint x = input[tid.x];
uint sum = WaveActiveSum(x);
uint prefix = WavePrefixSum(x);
uint first = WaveReadLaneFirst(x);
uint4 ballot = WaveActiveBallot((x & 1u) != 0u);
output[tid.x * 4u + 0u] = sum;
output[tid.x * 4u + 1u] = prefix;
output[tid.x * 4u + 2u] = first;
output[tid.x * 4u + 3u] = countbits(ballot.x) + countbits(ballot.y);
}
+2
View File
@@ -10,7 +10,9 @@ bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
placed_x.cpp
descriptor_heaps.cpp
committed.cpp
console_formats.cpp
pipelines.cpp
rect_list.cpp
gpu_writes.cpp
fences.cpp
presentx_xbox.cpp
+18
View File
@@ -14,6 +14,8 @@
*/
#include "xbox_facade.h"
#include "console_formats.h"
#include <cstdio>
extern "C" __declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
@@ -57,6 +59,10 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, c
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource");
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
desc = host_desc.of_resource(desc, "CreateCommittedResource");
clear = host_clear.of(clear, "CreateCommittedResource");
auto* device = bx_xbox_host<ID3D12Device>(self);
return finish(device, device->CreateCommittedResource(heap, flags, desc, state, clear, riid, ppv), riid, ppv,
"CreateCommittedResource");
@@ -68,6 +74,10 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self,
ID3D12ProtectedResourceSession* session, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource1");
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
desc = host_desc.of_resource(desc, "CreateCommittedResource1");
clear = host_clear.of(clear, "CreateCommittedResource1");
auto* device = bx_xbox_host<ID3D12Device4>(self);
return finish(device, device->CreateCommittedResource1(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
riid, ppv, "CreateCommittedResource1");
@@ -79,6 +89,10 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self,
ID3D12ProtectedResourceSession* session, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource2");
BxHostFormat<D3D12_RESOURCE_DESC1> host_desc;
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
desc = host_desc.of_resource(desc, "CreateCommittedResource2");
clear = host_clear.of(clear, "CreateCommittedResource2");
auto* device = bx_xbox_host<ID3D12Device8>(self);
return finish(device, device->CreateCommittedResource2(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
riid, ppv, "CreateCommittedResource2");
@@ -90,6 +104,10 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self,
ID3D12ProtectedResourceSession* session, UINT32 formats,
DXGI_FORMAT* castable, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource3");
BxHostFormat<D3D12_RESOURCE_DESC1> host_desc;
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
desc = host_desc.of_resource(desc, "CreateCommittedResource3");
clear = host_clear.of(clear, "CreateCommittedResource3");
auto* device = bx_xbox_host<ID3D12Device10>(self);
return finish(device,
device->CreateCommittedResource3(heap, flags, desc, layout, clear, bx_xbox_unwrap_as(session), formats,
+172
View File
@@ -0,0 +1,172 @@
/*
* Console-only DXGI formats and console-only view combinations: the Xbox-layout device entry
* points that carry a format to the host and are otherwise plain forwarders. See
* console_formats.h for the formats and the reason.
*
* Covered here: the three GetResourceAllocationInfo forms, CreatePlacedResource,
* CreateReservedResource and the four view-creation methods. Committed resources and the placed
* (X) resources and views translate in committed.cpp and placed_x.cpp. Pipeline-state formats are
* not translated yet: no console pipeline is created on the host so far.
*/
#include "console_formats.h"
#include "xbox_facade.h"
#include <atomic>
#include <cstdio>
#include <vector>
void bx_note_console_format(DXGI_FORMAT format, const char* where) {
static std::atomic<uint32_t> noted{0}; // one bit per console-only format
const int f = static_cast<int>(format);
const uint32_t bit = 1u << (f >= 189 ? f - 189 + 8 : f - 116);
if (noted.fetch_or(bit) & bit) return;
char detail[200];
std::snprintf(detail, sizeof(detail),
"console-only format %d is translated for the host (view and clear format %d, resource format %d; first seen in %s)",
f, static_cast<int>(bx_host_format(format)), static_cast<int>(bx_host_resource_format(format)), where);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_format", detail);
}
/* The console allows D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL together with ALLOW_UNORDERED_ACCESS,
* and a title writes the depth plane from a compute shader through an R32_FLOAT unordered-access
* view. PC Direct3D 12 forbids the combination. D3DMetal accepts the resource, answers the view
* with a Metal texture view that Metal refuses ("texture view pixelFormat
* (MTLPixelFormatDepth32Float) not castable"), and Metal aborts the process.
*
* Until that write path is emulated, such a descriptor gets a null view of the same description
* (Direct3D 12 defines it: reads return zero, writes are discarded) and the call is logged as
* unimplemented, so the gap is visible in every run report instead of ending the process. */
void bx_xbox_create_host_uav(ID3D12Device* device, ID3D12Resource* host, ID3D12Resource* counter,
const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE host_dest,
const char* method) {
BxHostFormat<D3D12_UNORDERED_ACCESS_VIEW_DESC> translated;
desc = translated.of(desc, method);
if (host && (host->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
BX_STUB_LOG("d3d12_xs.dll", "CreateUnorderedAccessView(depth-stencil resource)");
// A null view needs a description; without one the descriptor is left as it was.
if (desc) device->CreateUnorderedAccessView(nullptr, nullptr, desc, host_dest);
return;
}
device->CreateUnorderedAccessView(host, counter, desc, host_dest);
}
namespace {
/* An array of resource descriptions as the host must see it. */
template <typename Desc>
class HostDescs {
public:
HostDescs(const Desc* in, UINT count, const char* where) : descs_(in) {
if (!in) return;
for (UINT i = 0; i < count; ++i) {
if (!bx_is_console_only_format(in[i].Format)) continue;
if (copy_.empty()) copy_.assign(in, in + count);
bx_note_console_format(in[i].Format, where);
copy_[i].Format = bx_host_resource_format(in[i].Format);
}
if (!copy_.empty()) descs_ = copy_.data();
}
const Desc* get() const { return descs_; }
private:
const Desc* descs_;
std::vector<Desc> copy_;
};
} // namespace
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{};
bx_xbox_host<ID3D12Device>(self)->GetResourceAllocationInfo(&result, mask, count, host.get());
return result;
}
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{};
bx_xbox_host<ID3D12Device4>(self)->GetResourceAllocationInfo1(&result, mask, count, host.get(), each);
return result;
}
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{};
bx_xbox_host<ID3D12Device8>(self)->GetResourceAllocationInfo2(&result, mask, count, host.get(), each);
return result;
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource(void* self, ID3D12Heap* heap, UINT64 offset,
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedResource");
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreatePlacedResource(
bx_xbox_unwrap_as<ID3D12Heap>(heap), offset, host_desc.of_resource(desc, "CreatePlacedResource"), state,
host_clear.of(clear, "CreatePlacedResource"), riid, ppv);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreatePlacedResource", hr);
return bx_xbox_wrap_result(hr, riid, ppv);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_reserved_resource(void* self, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateReservedResource");
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateReservedResource(
host_desc.of_resource(desc, "CreateReservedResource"), state, host_clear.of(clear, "CreateReservedResource"), riid, ppv);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateReservedResource", hr);
return bx_xbox_wrap_result(hr, riid, ppv);
}
void STDMETHODCALLTYPE bx_xbox_device_create_shader_resource_view(void* self, ID3D12Resource* resource,
const D3D12_SHADER_RESOURCE_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreateShaderResourceView");
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
host.of(desc, "CreateShaderResourceView"),
bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_create_unordered_access_view(void* self, ID3D12Resource* resource, ID3D12Resource* counter,
const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreateUnorderedAccessView");
bx_xbox_create_host_uav(bx_xbox_host<ID3D12Device>(self), bx_xbox_unwrap_as<ID3D12Resource>(resource),
bx_xbox_unwrap_as<ID3D12Resource>(counter), desc, bx_xbox_host_cpu_handle(dest),
"CreateUnorderedAccessView");
}
void STDMETHODCALLTYPE bx_xbox_device_create_render_target_view(void* self, ID3D12Resource* resource,
const D3D12_RENDER_TARGET_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreateRenderTargetView");
BxHostFormat<D3D12_RENDER_TARGET_VIEW_DESC> host;
bx_xbox_host<ID3D12Device>(self)->CreateRenderTargetView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
host.of(desc, "CreateRenderTargetView"),
bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D12Resource* resource,
const D3D12_DEPTH_STENCIL_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreateDepthStencilView");
BxHostFormat<D3D12_DEPTH_STENCIL_VIEW_DESC> host;
bx_xbox_host<ID3D12Device>(self)->CreateDepthStencilView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
host.of(desc, "CreateDepthStencilView"),
bx_xbox_host_cpu_handle(dest));
}
} // extern "C"
+91
View File
@@ -0,0 +1,91 @@
/* Console-only DXGI formats.
*
* The Xbox Series DXGI_FORMAT enumeration (GDK d3d12_xs.h) has values the PC enumeration does
* not have: 116-120, 189 and 190. A PC Direct3D 12 implementation does not know them. D3DMetal
* turns one into an invalid Metal pixel format, and Metal then aborts the process ("Texture
* Descriptor Validation: MTLTextureDescriptor has invalid pixelFormat"), so no error code ever
* comes back. Every format that reaches the host therefore goes through bx_host_format first.
*
* The host format is the nearest one the host can create that holds at least the same precision:
*
* 116 R10G10B10_7E3_A2_FLOAT -> R16G16B16A16_FLOAT
* 117 R10G10B10_6E4_A2_FLOAT -> R16G16B16A16_FLOAT
* 118 D16_UNORM_S8_UINT -> D32_FLOAT_S8X24_UINT (depth + stencil; views, clear values)
* -> R32G8X24_TYPELESS (the texture itself, see below)
* 119 R16_UNORM_X8_TYPELESS -> R32_FLOAT_X8X24_TYPELESS (its depth plane, read)
* 120 X16_TYPELESS_G8_UINT -> X32_TYPELESS_G8X24_UINT (its stencil plane, read)
* 189 R10G10B10_SNORM_A2_UNORM -> R16G16B16A16_SNORM
* 190 R4G4_UNORM -> R8G8_UNORM
*
* A depth texture that is also read is created typeless on the host, with the concrete format
* named by each view: D3DMetal creates a fully typed depth-stencil texture without the ability
* to be viewed in another format, and Metal aborts on the depth-plane view. The title's own
* D32 buffers already follow that pattern (R32G8X24_TYPELESS texture, D32_FLOAT_S8X24_UINT view).
* bx_host_resource_format is therefore used for resource descriptions and bx_host_format for
* everything else.
*
* Known limits. The texel size differs, so a host resource of a substituted format cannot take
* the title's raw texel bytes (part of uploading placed texture contents, which is separate
* work), the sizes GetResourceAllocationInfo and GetCopyableFootprints report are the host
* format's, and GetDesc on such a resource reports the host format.
*/
#ifndef BX_D3D12_XS_CONSOLE_FORMATS_H
#define BX_D3D12_XS_CONSOLE_FORMATS_H
#include <dxgiformat.h>
constexpr int kBxFormatR10G10B10_7E3_A2_FLOAT = 116;
constexpr int kBxFormatR10G10B10_6E4_A2_FLOAT = 117;
constexpr int kBxFormatD16_UNORM_S8_UINT = 118;
constexpr int kBxFormatR16_UNORM_X8_TYPELESS = 119;
constexpr int kBxFormatX16_TYPELESS_G8_UINT = 120;
constexpr int kBxFormatR10G10B10_SNORM_A2_UNORM = 189;
constexpr int kBxFormatR4G4_UNORM = 190;
constexpr bool bx_is_console_only_format(DXGI_FORMAT format) {
const int f = static_cast<int>(format);
return (f >= 116 && f <= 120) || f == 189 || f == 190;
}
constexpr DXGI_FORMAT bx_host_format(DXGI_FORMAT format) {
switch (static_cast<int>(format)) {
case kBxFormatR10G10B10_7E3_A2_FLOAT:
case kBxFormatR10G10B10_6E4_A2_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
case kBxFormatD16_UNORM_S8_UINT: return DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
case kBxFormatR16_UNORM_X8_TYPELESS: return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
case kBxFormatX16_TYPELESS_G8_UINT: return DXGI_FORMAT_X32_TYPELESS_G8X24_UINT;
case kBxFormatR10G10B10_SNORM_A2_UNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
case kBxFormatR4G4_UNORM: return DXGI_FORMAT_R8G8_UNORM;
default: return format;
}
}
constexpr DXGI_FORMAT bx_host_resource_format(DXGI_FORMAT format) {
return static_cast<int>(format) == kBxFormatD16_UNORM_S8_UINT ? DXGI_FORMAT_R32G8X24_TYPELESS : bx_host_format(format);
}
/* Logs the first translation of each console-only format (console_formats.cpp). */
void bx_note_console_format(DXGI_FORMAT format, const char* where);
/* A structure with a `Format` member (resource description, clear value, view description) as
* the host must see it. of() returns the caller's pointer unchanged when nothing needs
* translating, so the common case costs one comparison and no copy. */
template <typename T>
class BxHostFormat {
public:
const T* of(const T* in, const char* where) { return translate(in, where, false); }
/* For D3D12_RESOURCE_DESC and D3D12_RESOURCE_DESC1. */
const T* of_resource(const T* in, const char* where) { return translate(in, where, true); }
private:
const T* translate(const T* in, const char* where, bool resource) {
if (!in || !bx_is_console_only_format(in->Format)) return in;
bx_note_console_format(in->Format, where);
value_ = *in;
value_.Format = resource ? bx_host_resource_format(in->Format) : bx_host_format(in->Format);
return &value_;
}
T value_;
};
#endif
+33 -2
View File
@@ -214,6 +214,28 @@ void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count
dsv ? &host_dsv : nullptr);
}
namespace {
/* On the console a GPU virtual address is the title's own address, so a title can bind index and
* vertex data that lives in plain title memory, with no Direct3D resource created for it. This
* layer has a host buffer only for memory it was told about (placed and committed resources).
* An address without one must not reach the host: it is not a host address, and D3DMetal
* dereferences the buffer it fails to find (a null read under IASetIndexBuffer). Such a binding
* is left empty and logged as unimplemented; the first few are logged with their details.
* Supplying the data (a host buffer filled from the title memory) is separate work. */
void note_unbacked(const char* what, D3D12_GPU_VIRTUAL_ADDRESS address, UINT size, const char* stub) {
static std::atomic<uint32_t> noted{0};
if (noted.fetch_add(1) < 8) {
char detail[128];
std::snprintf(detail, sizeof(detail), "%s at 0x%llx (%u bytes) has no host buffer; the binding is left empty", what,
static_cast<unsigned long long>(address), size);
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "unbacked_buffer", detail);
}
BX_STUB_LOG("d3d12_xs.dll", stub);
}
} // namespace
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
const D3D12_VERTEX_BUFFER_VIEW* views) {
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetVertexBuffers");
@@ -221,9 +243,14 @@ void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start
const UINT n = count > 32 ? 32 : count;
for (UINT i = 0; views && i < n; ++i) {
host[i] = views[i];
host[i].BufferLocation = bx_xbox_host_gpu_va(views[i].BufferLocation);
if (views[i].BufferLocation && !bx_xbox_try_host_gpu_va(views[i].BufferLocation, &host[i].BufferLocation)) {
note_unbacked("vertex buffer", views[i].BufferLocation, views[i].SizeInBytes,
"IASetVertexBuffers(title memory without a host buffer)");
host[i] = D3D12_VERTEX_BUFFER_VIEW{};
}
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetVertexBuffers(start, n, views ? host : nullptr);
bx_xbox_rect_note_vertex_buffers(bx_xbox_host<ID3D12GraphicsCommandList>(self), start, n, views);
}
void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_INDEX_BUFFER_VIEW* view) {
@@ -231,7 +258,11 @@ void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_
D3D12_INDEX_BUFFER_VIEW host{};
if (view) {
host = *view;
host.BufferLocation = bx_xbox_host_gpu_va(view->BufferLocation);
if (view->BufferLocation && !bx_xbox_try_host_gpu_va(view->BufferLocation, &host.BufferLocation)) {
note_unbacked("index buffer", view->BufferLocation, view->SizeInBytes,
"IASetIndexBuffer(title memory without a host buffer)");
view = nullptr;
}
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetIndexBuffer(view ? &host : nullptr);
}
+66 -20
View File
@@ -173,6 +173,13 @@ HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid,
return bx_xbox_wrap_result(S_OK, riid, ppv);
}
HRESULT refused_always_fail(HRESULT hr, const char* kind) {
char detail[128];
std::snprintf(detail, sizeof(detail), "%s pipeline refused hr=0x%08lx", kind, static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_refused", detail);
return hr;
}
void log_extended(const char* kind, UINT count) {
if (!count) return;
char detail[96];
@@ -193,6 +200,12 @@ HRESULT create_compute(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc
return bx_xbox_wrap_result(hr, riid, ppv);
}
/* The console's pipeline topology types for rectangle and quad lists
(D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT = 19, _QUAD = 32) are drawn with triangles on the host. */
D3D12_PRIMITIVE_TOPOLOGY_TYPE host_topology_type(D3D12_PRIMITIVE_TOPOLOGY_TYPE type) {
return type > D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : type;
}
HRESULT create_graphics(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
@@ -205,8 +218,11 @@ HRESULT create_graphics(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* de
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "DS", desc->DS, admitted.DS);
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "HS", desc->HS, admitted.HS);
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "GS", desc->GS, admitted.GS);
admitted.PrimitiveTopologyType = host_topology_type(desc->PrimitiveTopologyType);
if (SUCCEEDED(hr)) hr = device->CreateGraphicsPipelineState(&admitted, riid, ppv);
if (FAILED(hr)) return refused(device, hr, "graphics", riid, ppv);
bx_xbox_rect_pipeline_created(static_cast<ID3D12PipelineState*>(*ppv), desc->InputLayout.pInputElementDescs,
desc->InputLayout.NumElements);
return bx_xbox_wrap_result(hr, riid, ppv);
}
@@ -240,10 +256,23 @@ HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
hr = gate.admit("stream", names[i], in, out);
if (SUCCEEDED(hr)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
}
const size_t topology_at = bx_stream_payload(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY);
if (topology_at != SIZE_MAX) {
D3D12_PRIMITIVE_TOPOLOGY_TYPE type{};
std::memcpy(&type, &stream[topology_at], sizeof(type));
type = host_topology_type(type);
std::memcpy(&stream[topology_at], &type, sizeof(type));
}
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
admitted.pPipelineStateSubobjectStream = stream.data();
if (SUCCEEDED(hr)) hr = device->CreatePipelineState(&admitted, riid, ppv);
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv);
{
D3D12_INPUT_LAYOUT_DESC layout{};
const size_t layout_at = bx_stream_payload(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT);
if (layout_at != SIZE_MAX) std::memcpy(&layout, &stream[layout_at], sizeof(layout));
bx_xbox_rect_pipeline_created(static_cast<ID3D12PipelineState*>(*ppv), layout.pInputElementDescs, layout.NumElements);
}
return bx_xbox_wrap_result(hr, riid, ppv);
}
@@ -267,12 +296,19 @@ void bx_xbox_pipeline_forget(IUnknown* host) {
}
void bx_xbox_list_forget(IUnknown* host) {
bx_xbox_rect_list_forget(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
std::lock_guard<std::mutex> guard(g_lock);
erase(g_lists, g_list_count, static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
}
extern "C" {
void STDMETHODCALLTYPE bx_xbox_list_ia_set_primitive_topology(void* self, D3D12_PRIMITIVE_TOPOLOGY topology) {
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetPrimitiveTopology");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
list->IASetPrimitiveTopology(bx_xbox_rect_note_topology(list, topology));
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineState");
@@ -307,6 +343,7 @@ void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12Pipelin
bool is_null = false;
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
set_list_null(list, is_null);
bx_xbox_rect_note_pipeline(list, host);
if (!is_null) list->SetPipelineState(host);
}
@@ -317,6 +354,7 @@ HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator*
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
set_list_null(list, is_null);
bx_xbox_gpu_writes_reset(list);
bx_xbox_rect_list_reset(list, host);
return list->Reset(bx_xbox_unwrap_as(allocator), host);
}
@@ -324,16 +362,22 @@ void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UI
UINT first_instance) {
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawInstanced");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (!list_skips(list, "DrawInstanced")) list->DrawInstanced(vertices, instances, first_vertex, first_instance);
if (list_skips(list, "DrawInstanced")) return;
if (!bx_xbox_draw_rect_list(list, vertices, instances, first_vertex, first_instance)) {
list->DrawInstanced(vertices, instances, first_vertex, first_instance);
}
}
void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indices, UINT instances, UINT first_index,
INT base_vertex, UINT first_instance) {
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawIndexedInstanced");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (!list_skips(list, "DrawIndexedInstanced")) {
list->DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance);
if (list_skips(list, "DrawIndexedInstanced")) return;
if (bx_xbox_rect_list_bound(list)) {
BX_STUB_LOG("d3d12_xs.dll", "DrawIndexedInstanced(rectangle list)");
return;
}
list->DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance);
}
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z) {
@@ -433,33 +477,35 @@ void STDMETHODCALLTYPE bx_xbox_allocator_set_callback_x(void*, void* callback, U
/*
* DeserializeGraphics/ComputePipelineStateX create a pipeline from a serialized console pipeline
* (console shader code), which has no host form. They fail with E_NOTIMPL (logged as a refused
* pipeline); in null-render mode they return a null pipeline like any other refused pipeline.
* (console shader code), which has no host form. They always fail with E_NOTIMPL and log
* `pipeline_refused` — even in null-render mode — so a title falls back to creating its pipelines
* from shader containers instead of receiving a null pipeline (#669).
*/
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void*, REFIID riid,
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void*, const void*, REFIID,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "DeserializeGraphicsPipelineStateX");
if (!ppv) return E_POINTER;
*ppv = nullptr;
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized graphics (console code)", riid, ppv);
return refused_always_fail(E_NOTIMPL, "deserialized graphics (console code)");
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void*, REFIID riid,
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void*, const void*, REFIID,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "DeserializeComputePipelineStateX");
if (!ppv) return E_POINTER;
*ppv = nullptr;
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, "deserialized compute (console code)", riid, ppv);
return refused_always_fail(E_NOTIMPL, "deserialized compute (console code)");
}
/*
* CreateDerived{Graphics,Compute}PipelineStateX: a pipeline equal to `source` with some state
* groups replaced. Derived from a null pipeline, the result is a null pipeline too. Deriving
* from a host pipeline needs its creation description, which this layer does not keep yet: that
* case is refused (logged) and, in null-render mode, is a null pipeline as well.
* groups replaced. Deriving from a host pipeline needs its creation description, which this layer
* does not keep yet. Both calls always fail with E_NOTIMPL and log `pipeline_refused` — even in
* null-render mode — so a title falls back to creating its pipelines from shader containers
* instead of silently receiving null pipelines (#669).
*/
namespace {
HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv, const char* kind) {
HRESULT derived(ID3D12PipelineState* source, void** ppv, const char* kind) {
if (!ppv) return E_POINTER;
*ppv = nullptr;
const bool from_null = bx_xbox_pipeline_is_null(source);
@@ -470,18 +516,18 @@ HRESULT derived(void* self, ID3D12PipelineState* source, REFIID riid, void** ppv
"deriving from a host pipeline is not implemented (its creation description is not kept)");
}
}
return refused(bx_xbox_host<ID3D12Device>(self), E_NOTIMPL, kind, riid, ppv);
return refused_always_fail(E_NOTIMPL, kind);
}
} // namespace
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void* self, ID3D12PipelineState* source,
UINT, const void*, REFIID riid, void** ppv) {
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_graphics_pipeline_state_x(void*, ID3D12PipelineState* source,
UINT, const void*, REFIID, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateDerivedGraphicsPipelineStateX");
return derived(self, source, riid, ppv, "derived graphics");
return derived(source, ppv, "derived graphics");
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void* self, ID3D12PipelineState* source,
UINT, const void*, REFIID riid, void** ppv) {
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_derived_compute_pipeline_state_x(void*, ID3D12PipelineState* source,
UINT, const void*, REFIID, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateDerivedComputePipelineStateX");
return derived(self, source, riid, ppv, "derived compute");
return derived(source, ppv, "derived compute");
}
+26 -6
View File
@@ -15,6 +15,7 @@
* from GetGPUVirtualAddress. Keeping the shadow in step with later CPU writes, and translating
* title addresses in GPU calls, are not done yet; both are logged when reached.
*/
#include "console_formats.h"
#include "xbox_facade.h"
#include <atomic>
@@ -102,6 +103,10 @@ HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURC
constexpr UINT kPcResourceFlags = 0x1FF;
host_desc.Layout = buffer ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN;
host_desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(desc.Flags & kPcResourceFlags);
if (bx_is_console_only_format(desc.Format)) {
bx_note_console_format(desc.Format, "CreatePlacedResourceX");
host_desc.Format = bx_host_resource_format(desc.Format);
}
ID3D12Resource* resource = nullptr;
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON,
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
@@ -207,7 +212,8 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const
if (!resource) return;
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
device->CreateShaderResourceView(resource, &pc, bx_xbox_host_cpu_handle(dest));
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
device->CreateShaderResourceView(resource, host.of(&pc, "CreatePlacedRawShaderResourceViewX"), bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
@@ -219,7 +225,7 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const
if (!resource) return;
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
device->CreateUnorderedAccessView(resource, nullptr, &pc, bx_xbox_host_cpu_handle(dest));
bx_xbox_create_host_uav(device, resource, nullptr, &pc, bx_xbox_host_cpu_handle(dest), "CreatePlacedRawUnorderedAccessViewX");
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
@@ -227,8 +233,10 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Reso
BX_D3D_TRACE("XboxDevice", "CreatePlacedShaderResourceViewX");
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as(resource), xbox_desc ? &pc : nullptr,
bx_xbox_host_cpu_handle(dest));
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(
bx_xbox_unwrap_as(resource), xbox_desc ? host.of(&pc, "CreatePlacedShaderResourceViewX") : nullptr,
bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
@@ -236,8 +244,20 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Reso
BX_D3D_TRACE("XboxDevice", "CreatePlacedUnorderedAccessViewX");
D3D12_UNORDERED_ACCESS_VIEW_DESC pc{};
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
bx_xbox_host<ID3D12Device>(self)->CreateUnorderedAccessView(bx_xbox_unwrap_as(resource), nullptr,
xbox_desc ? &pc : nullptr, bx_xbox_host_cpu_handle(dest));
bx_xbox_create_host_uav(bx_xbox_host<ID3D12Device>(self), bx_xbox_unwrap_as(resource), nullptr, xbox_desc ? &pc : nullptr,
bx_xbox_host_cpu_handle(dest), "CreatePlacedUnorderedAccessViewX");
}
bool bx_xbox_try_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title, D3D12_GPU_VIRTUAL_ADDRESS* host) {
std::lock_guard<std::mutex> guard(g_lock);
for (size_t i = 0; i < g_count; ++i) {
const Shadow& s = g_shadows[i];
if (title >= s.title_va && title < s.title_va + s.size) {
*host = s.host->GetGPUVirtualAddress() + (title - s.title_va);
return true;
}
}
return false;
}
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title) {
+13
View File
@@ -559,6 +559,19 @@ HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<ui
return S_OK;
}
size_t bx_stream_payload(const std::vector<uint8_t>& stream, uint32_t type) {
size_t offset = 0;
while (offset + sizeof(SIZE_T) <= stream.size()) {
uint32_t raw = 0;
std::memcpy(&raw, &stream[offset], sizeof(raw));
const StreamSubobject* entry = find_subobject(raw);
if (!entry) return SIZE_MAX;
if (raw == type) return offset + entry->payload_offset;
offset += entry->record_size;
}
return SIZE_MAX;
}
HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
BX_D3D_TRACE("ID3D12Device2", "CreatePipelineState");
if (!h_ID3D12Device2) {
+2
View File
@@ -124,3 +124,5 @@ using BxCommandListProxy = BxChildProxy<BxCommandListProxyGen>;
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names,
size_t* root_offset);
/* The payload offset of the subobject of `type` in a stream copy_stream accepted, or SIZE_MAX. */
size_t bx_stream_payload(const std::vector<uint8_t>& stream, uint32_t type);
+261
View File
@@ -0,0 +1,261 @@
/*
* Console rectangle lists.
*
* The Xbox Series headers add primitive topologies PC Direct3D 12 does not have. A title draws
* its full-screen passes with D3D_PRIMITIVE_TOPOLOGY_RECTLIST (17): three vertices per rectangle,
* the fourth corner being v0 + v2 - v1, in pipelines whose topology type is
* D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT (19). The host knows neither value. Passed through, the
* pipeline is created anyway and the three vertices are drawn as one triangle: half of every
* rectangle is missing and no error is reported.
*
* Here a rectangle list is drawn as triangle strips:
* - the pipeline's topology type becomes TRIANGLE when it is created (pipelines.cpp);
* - IASetPrimitiveTopology(RECTLIST) sets TRIANGLESTRIP on the host and is remembered;
* - a non-indexed draw builds four vertices per rectangle, in the order v1, v2, v0, v3 (which
* keeps the winding of v0, v1, v2), in a host upload buffer and draws them. The vertices are
* read from the title's memory behind vertex-buffer slot 0, and v3 is computed element by
* element from the pipeline's input layout.
*
* Limits, each logged as unimplemented when reached: indexed rectangle lists; layouts with
* per-vertex elements outside slot 0; element formats other than 32-bit float and 8-bit
* normalised (those elements take the third vertex's value). Quad lists, quad strips and line
* loops are not emulated.
*/
#include "xbox_facade.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <unordered_map>
#include <vector>
namespace {
constexpr int kRectList = 17; // D3D_PRIMITIVE_TOPOLOGY_RECTLIST (Xbox extension)
struct Element {
DXGI_FORMAT format;
UINT slot;
UINT offset;
bool per_vertex;
};
struct ListState {
int topology = 0; // the title's last IASetPrimitiveTopology value
D3D12_VERTEX_BUFFER_VIEW vb0{}; // the title's view of slot 0 (title address)
ID3D12PipelineState* pipeline = nullptr; // host pipeline bound, or nullptr
};
std::mutex g_lock;
std::unordered_map<const void*, ListState> g_lists;
std::unordered_map<const void*, std::vector<Element>> g_layouts; // host pipeline -> input elements
bool readable(uint64_t address, uint64_t size) {
uint64_t cursor = address;
const uint64_t end = address + size;
while (cursor < end) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(cursor), &region, sizeof(region)) || region.State != MEM_COMMIT ||
(region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
return false;
}
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
return true;
}
/* Space for generated vertices: one upload buffer used as a ring. A position is reused after the
ring wraps, which is 4 MiB of generated rectangles later; frames use a few hundred bytes. */
bool ring_place(ID3D12Device* device, const uint8_t* data, size_t size, D3D12_GPU_VIRTUAL_ADDRESS* address) {
constexpr uint64_t kRing = 4ull << 20;
static std::mutex lock;
static ID3D12Resource* ring = nullptr;
static uint8_t* mapped = nullptr;
static uint64_t cursor = 0;
if (size == 0 || size > kRing) return false;
std::lock_guard<std::mutex> guard(lock);
if (!ring) {
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_UPLOAD;
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = kRing;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
ID3D12Resource* created = nullptr;
void* base = nullptr;
if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&created))) ||
!created) {
return false;
}
if (FAILED(created->Map(0, nullptr, &base)) || !base) {
created->Release();
return false;
}
ring = created;
mapped = static_cast<uint8_t*>(base);
}
const uint64_t aligned = (size + 15) & ~15ull;
if (cursor + aligned > kRing) cursor = 0;
std::memcpy(mapped + cursor, data, size);
*address = ring->GetGPUVirtualAddress() + cursor;
cursor += aligned;
return true;
}
void unimplemented(const char* what) { BX_STUB_LOG("d3d12_xs.dll", what); }
} // namespace
void bx_xbox_rect_pipeline_created(ID3D12PipelineState* host, const D3D12_INPUT_ELEMENT_DESC* elements, UINT count) {
if (!host) return;
std::vector<Element> layout;
for (UINT i = 0; elements && i < count; ++i) {
layout.push_back({elements[i].Format, elements[i].InputSlot, elements[i].AlignedByteOffset,
elements[i].InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA});
}
std::lock_guard<std::mutex> guard(g_lock);
g_layouts[host] = std::move(layout); // also replaces a released pipeline's entry at a reused address
}
D3D12_PRIMITIVE_TOPOLOGY bx_xbox_rect_note_topology(ID3D12GraphicsCommandList* list, D3D12_PRIMITIVE_TOPOLOGY topology) {
{
std::lock_guard<std::mutex> guard(g_lock);
g_lists[list].topology = static_cast<int>(topology);
}
return static_cast<int>(topology) == kRectList ? D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP : topology;
}
void bx_xbox_rect_note_vertex_buffers(ID3D12GraphicsCommandList* list, UINT start, UINT count,
const D3D12_VERTEX_BUFFER_VIEW* views) {
if (start != 0 || count == 0) return;
std::lock_guard<std::mutex> guard(g_lock);
g_lists[list].vb0 = views ? views[0] : D3D12_VERTEX_BUFFER_VIEW{};
}
void bx_xbox_rect_note_pipeline(ID3D12GraphicsCommandList* list, ID3D12PipelineState* host) {
std::lock_guard<std::mutex> guard(g_lock);
g_lists[list].pipeline = host;
}
void bx_xbox_rect_list_reset(ID3D12GraphicsCommandList* list, ID3D12PipelineState* host) {
std::lock_guard<std::mutex> guard(g_lock);
g_lists[list] = ListState{};
g_lists[list].pipeline = host;
}
void bx_xbox_rect_list_forget(ID3D12GraphicsCommandList* list) {
std::lock_guard<std::mutex> guard(g_lock);
g_lists.erase(list);
}
bool bx_xbox_rect_list_bound(ID3D12GraphicsCommandList* list) {
std::lock_guard<std::mutex> guard(g_lock);
auto it = g_lists.find(list);
return it != g_lists.end() && it->second.topology == kRectList;
}
/* True when the list's topology is the rectangle list: the draw was done here, or could not be
and was logged as unimplemented. Either way the caller must not issue its own draw. */
bool bx_xbox_draw_rect_list(ID3D12GraphicsCommandList* list, UINT vertices, UINT instances, UINT first_vertex,
UINT first_instance) {
ListState state;
std::vector<Element> layout;
bool have_layout = false;
{
std::lock_guard<std::mutex> guard(g_lock);
auto it = g_lists.find(list);
if (it == g_lists.end() || it->second.topology != kRectList) return false;
state = it->second;
auto found = g_layouts.find(state.pipeline);
if (found != g_layouts.end()) {
layout = found->second;
have_layout = true;
}
}
const UINT stride = state.vb0.StrideInBytes;
const UINT rects = vertices / 3;
if (rects == 0) return true;
if (!have_layout || !state.vb0.BufferLocation || stride == 0 || stride > 1024) {
unimplemented("DrawInstanced(rectangle list without a known input layout or slot-0 vertex buffer)");
return true;
}
for (const Element& e : layout) {
if (e.per_vertex && e.slot != 0) {
unimplemented("DrawInstanced(rectangle list with per-vertex elements outside slot 0)");
return true;
}
}
const uint64_t source = state.vb0.BufferLocation + static_cast<uint64_t>(first_vertex) * stride;
if (!readable(source, static_cast<uint64_t>(rects) * 3 * stride)) {
unimplemented("DrawInstanced(rectangle list whose vertices are not readable title memory)");
return true;
}
std::vector<uint8_t> out(static_cast<size_t>(rects) * 4 * stride);
for (UINT r = 0; r < rects; ++r) {
const auto* v0 = reinterpret_cast<const uint8_t*>(source + static_cast<uint64_t>(3 * r) * stride);
const uint8_t* v1 = v0 + stride;
const uint8_t* v2 = v1 + stride;
uint8_t* dst = &out[static_cast<size_t>(r) * 4 * stride];
std::memcpy(dst, v1, stride);
std::memcpy(dst + stride, v2, stride);
std::memcpy(dst + 2 * stride, v0, stride);
uint8_t* v3 = dst + 3 * stride;
std::memcpy(v3, v2, stride);
for (const Element& e : layout) {
if (!e.per_vertex || e.offset >= stride) continue;
unsigned floats = 0, bytes = 0;
switch (e.format) {
case DXGI_FORMAT_R32G32B32A32_FLOAT: floats = 4; break;
case DXGI_FORMAT_R32G32B32_FLOAT: floats = 3; break;
case DXGI_FORMAT_R32G32_FLOAT: floats = 2; break;
case DXGI_FORMAT_R32_FLOAT: floats = 1; break;
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_B8G8R8A8_UNORM: bytes = 4; break;
default: unimplemented("DrawInstanced(rectangle list element format; third vertex's value used)"); break;
}
for (unsigned i = 0; i < floats && e.offset + 4 * (i + 1) <= stride; ++i) {
float a, b, c;
std::memcpy(&a, v0 + e.offset + 4 * i, 4);
std::memcpy(&b, v1 + e.offset + 4 * i, 4);
std::memcpy(&c, v2 + e.offset + 4 * i, 4);
const float d = a + c - b;
std::memcpy(v3 + e.offset + 4 * i, &d, 4);
}
for (unsigned i = 0; i < bytes && e.offset + i < stride; ++i) {
const int d = static_cast<int>(v0[e.offset + i]) + v2[e.offset + i] - v1[e.offset + i];
v3[e.offset + i] = static_cast<uint8_t>(d < 0 ? 0 : d > 255 ? 255 : d);
}
}
}
ID3D12Device* device = nullptr;
D3D12_GPU_VIRTUAL_ADDRESS placed = 0;
const bool ok = SUCCEEDED(list->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) && device &&
ring_place(device, out.data(), out.size(), &placed);
if (device) device->Release();
if (!ok) {
unimplemented("DrawInstanced(rectangle list: no host buffer for the generated vertices)");
return true;
}
const D3D12_VERTEX_BUFFER_VIEW generated{placed, static_cast<UINT>(out.size()), stride};
list->IASetVertexBuffers(0, 1, &generated);
for (UINT r = 0; r < rects; ++r) list->DrawInstanced(4, instances, 4 * r, first_instance);
// Put the title's own slot-0 binding back.
D3D12_VERTEX_BUFFER_VIEW title = state.vb0;
if (bx_xbox_try_host_gpu_va(state.vb0.BufferLocation, &title.BufferLocation)) {
list->IASetVertexBuffers(0, 1, &title);
} else {
list->IASetVertexBuffers(0, 1, nullptr);
}
static std::atomic<bool> logged{false};
if (!logged.exchange(true)) {
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "rect_list",
"console rectangle lists are drawn as triangle strips (fourth corner v0 + v2 - v1); later draws are not logged");
}
return true;
}
+10
View File
@@ -71,6 +71,15 @@ CUSTOM = {
"CreateGraphicsPipelineState": "bx_xbox_device_create_graphics_pipeline_state",
"CreateComputePipelineStateX": "bx_xbox_device_create_compute_pipeline_state_x",
"CreateGraphicsPipelineStateX": "bx_xbox_device_create_graphics_pipeline_state_x",
"GetResourceAllocationInfo": "bx_xbox_device_get_resource_allocation_info",
"GetResourceAllocationInfo1": "bx_xbox_device_get_resource_allocation_info1",
"GetResourceAllocationInfo2": "bx_xbox_device_get_resource_allocation_info2",
"CreatePlacedResource": "bx_xbox_device_create_placed_resource",
"CreateReservedResource": "bx_xbox_device_create_reserved_resource",
"CreateShaderResourceView": "bx_xbox_device_create_shader_resource_view",
"CreateUnorderedAccessView": "bx_xbox_device_create_unordered_access_view",
"CreateRenderTargetView": "bx_xbox_device_create_render_target_view",
"CreateDepthStencilView": "bx_xbox_device_create_depth_stencil_view",
"CreateCommittedResource": "bx_xbox_device_create_committed_resource",
"CreateCommittedResource1": "bx_xbox_device_create_committed_resource1",
"CreateCommittedResource2": "bx_xbox_device_create_committed_resource2",
@@ -96,6 +105,7 @@ CUSTOM = {
"CopyTextureRegion": "bx_xbox_list_copy_texture_region",
"OMSetRenderTargets": "bx_xbox_list_om_set_render_targets",
"IASetVertexBuffers": "bx_xbox_list_ia_set_vertex_buffers",
"IASetPrimitiveTopology": "bx_xbox_list_ia_set_primitive_topology",
"IASetIndexBuffer": "bx_xbox_list_ia_set_index_buffer",
"SetPipelineState": "bx_xbox_list_set_pipeline_state",
"Reset": "bx_xbox_list_reset",
+48
View File
@@ -176,6 +176,9 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void* self, UINT typ
D3D12_CPU_DESCRIPTOR_HANDLE bx_xbox_host_cpu_handle(D3D12_CPU_DESCRIPTOR_HANDLE title);
D3D12_GPU_DESCRIPTOR_HANDLE bx_xbox_host_gpu_handle(D3D12_GPU_DESCRIPTOR_HANDLE title);
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title);
/* True, with the host address in *host, when `title` lies in memory this layer has a host buffer
* for; false (and *host untouched) otherwise. */
bool bx_xbox_try_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title, D3D12_GPU_VIRTUAL_ADDRESS* host);
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type);
void bx_xbox_descriptor_heap_forget(IUnknown* host);
/* Records title-visible memory (from XMemAlloc) for a host resource; freed when it is released. */
@@ -290,6 +293,51 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self,
ID3D12ProtectedResourceSession* session, UINT32 formats,
DXGI_FORMAT* castable, REFIID riid, void** ppv);
/* Creates an unordered-access view on the host, or a null view (logged as unimplemented) when the
* resource is a depth-stencil texture, which the host cannot give one (console_formats.cpp). */
void bx_xbox_create_host_uav(ID3D12Device* device, ID3D12Resource* host, ID3D12Resource* counter,
const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE host_dest,
const char* method);
/* Entry points that only translate console-only formats before the host call (console_formats.cpp). */
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info(void* self, UINT mask, UINT count,
const D3D12_RESOURCE_DESC* descs);
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);
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);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource(void* self, ID3D12Heap* heap, UINT64 offset,
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_reserved_resource(void* self, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
REFIID riid, void** ppv);
void STDMETHODCALLTYPE bx_xbox_device_create_shader_resource_view(void* self, ID3D12Resource* resource,
const D3D12_SHADER_RESOURCE_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest);
void STDMETHODCALLTYPE bx_xbox_device_create_unordered_access_view(void* self, ID3D12Resource* resource, ID3D12Resource* counter,
const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest);
void STDMETHODCALLTYPE bx_xbox_device_create_render_target_view(void* self, ID3D12Resource* resource,
const D3D12_RENDER_TARGET_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest);
void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D12Resource* resource,
const D3D12_DEPTH_STENCIL_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest);
/* Console rectangle lists (rect_list.cpp). */
void bx_xbox_rect_pipeline_created(ID3D12PipelineState* host, const D3D12_INPUT_ELEMENT_DESC* elements, UINT count);
D3D12_PRIMITIVE_TOPOLOGY bx_xbox_rect_note_topology(ID3D12GraphicsCommandList* list, D3D12_PRIMITIVE_TOPOLOGY topology);
void bx_xbox_rect_note_vertex_buffers(ID3D12GraphicsCommandList* list, UINT start, UINT count,
const D3D12_VERTEX_BUFFER_VIEW* views);
void bx_xbox_rect_note_pipeline(ID3D12GraphicsCommandList* list, ID3D12PipelineState* host);
void bx_xbox_rect_list_reset(ID3D12GraphicsCommandList* list, ID3D12PipelineState* host);
void bx_xbox_rect_list_forget(ID3D12GraphicsCommandList* list);
bool bx_xbox_rect_list_bound(ID3D12GraphicsCommandList* list);
bool bx_xbox_draw_rect_list(ID3D12GraphicsCommandList* list, UINT vertices, UINT instances, UINT first_vertex,
UINT first_instance);
extern "C" void STDMETHODCALLTYPE bx_xbox_list_ia_set_primitive_topology(void* self, D3D12_PRIMITIVE_TOPOLOGY topology);
/* Descriptor heaps with title-visible storage (descriptor_heaps.cpp). */
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_descriptor_heap(void* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc,
REFIID riid, void** ppv);
+12 -62
View File
@@ -62,22 +62,6 @@ static HRESULT STDMETHODCALLTYPE x_Device_16(void* self, UINT a0, const void * a
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateRootSignature", hr);
return bx_xbox_wrap_result(hr, a3, a4);
}
static void STDMETHODCALLTYPE x_Device_18(void* self, ID3D12Resource * a0, const D3D12_SHADER_RESOURCE_VIEW_DESC * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
BX_D3D_TRACE("XboxDevice", "CreateShaderResourceView");
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_host_cpu_handle(a2));
}
static void STDMETHODCALLTYPE x_Device_19(void* self, ID3D12Resource * a0, ID3D12Resource * a1, const D3D12_UNORDERED_ACCESS_VIEW_DESC * a2, D3D12_CPU_DESCRIPTOR_HANDLE a3) {
BX_D3D_TRACE("XboxDevice", "CreateUnorderedAccessView");
bx_xbox_host<ID3D12Device>(self)->CreateUnorderedAccessView(bx_xbox_unwrap_as<ID3D12Resource>(a0), bx_xbox_unwrap_as<ID3D12Resource>(a1), a2, bx_xbox_host_cpu_handle(a3));
}
static void STDMETHODCALLTYPE x_Device_20(void* self, ID3D12Resource * a0, const D3D12_RENDER_TARGET_VIEW_DESC * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
BX_D3D_TRACE("XboxDevice", "CreateRenderTargetView");
bx_xbox_host<ID3D12Device>(self)->CreateRenderTargetView(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_host_cpu_handle(a2));
}
static void STDMETHODCALLTYPE x_Device_21(void* self, ID3D12Resource * a0, const D3D12_DEPTH_STENCIL_VIEW_DESC * a1, D3D12_CPU_DESCRIPTOR_HANDLE a2) {
BX_D3D_TRACE("XboxDevice", "CreateDepthStencilView");
bx_xbox_host<ID3D12Device>(self)->CreateDepthStencilView(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_host_cpu_handle(a2));
}
static void STDMETHODCALLTYPE x_Device_22(void* self, const D3D12_SAMPLER_DESC * a0, D3D12_CPU_DESCRIPTOR_HANDLE a1) {
BX_D3D_TRACE("XboxDevice", "CreateSampler");
bx_xbox_host<ID3D12Device>(self)->CreateSampler(a0, bx_xbox_host_cpu_handle(a1));
@@ -86,12 +70,6 @@ static void STDMETHODCALLTYPE x_Device_24(void* self, UINT a0, const D3D12_CPU_D
BX_D3D_TRACE("XboxDevice", "CopyDescriptorsSimple");
bx_xbox_host<ID3D12Device>(self)->CopyDescriptorsSimple(a0, bx_xbox_host_cpu_handle(a1), bx_xbox_host_cpu_handle(a2), a3);
}
static D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE x_Device_25(void* self, UINT a0, UINT a1, const D3D12_RESOURCE_DESC * a2) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo");
D3D12_RESOURCE_ALLOCATION_INFO result{};
bx_xbox_host<ID3D12Device>(self)->GetResourceAllocationInfo(&result, a0, a1, a2);
return result;
}
static D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE x_Device_26(void* self, UINT a0, D3D12_HEAP_TYPE a1) {
BX_D3D_TRACE("XboxDevice", "GetCustomHeapProperties");
D3D12_HEAP_PROPERTIES result{};
@@ -104,18 +82,6 @@ static HRESULT STDMETHODCALLTYPE x_Device_28(void* self, const D3D12_HEAP_DESC *
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateHeap", hr);
return bx_xbox_wrap_result(hr, a1, a2);
}
static HRESULT STDMETHODCALLTYPE x_Device_29(void* self, ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedResource");
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreatePlacedResource(bx_xbox_unwrap_as<ID3D12Heap>(a0), a1, a2, a3, a4, a5, a6);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreatePlacedResource", hr);
return bx_xbox_wrap_result(hr, a5, a6);
}
static HRESULT STDMETHODCALLTYPE x_Device_30(void* self, const D3D12_RESOURCE_DESC * a0, D3D12_RESOURCE_STATES a1, const D3D12_CLEAR_VALUE * a2, REFIID a3, void ** a4) {
BX_D3D_TRACE("XboxDevice", "CreateReservedResource");
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateReservedResource(a0, a1, a2, a3, a4);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateReservedResource", hr);
return bx_xbox_wrap_result(hr, a3, a4);
}
static HRESULT STDMETHODCALLTYPE x_Device_31(void* self, ID3D12DeviceChild * a0, const SECURITY_ATTRIBUTES * a1, DWORD a2, const WCHAR * a3, HANDLE * a4) {
BX_D3D_TRACE("XboxDevice", "CreateSharedHandle");
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateSharedHandle(bx_xbox_unwrap_as<ID3D12DeviceChild>(a0), a1, a2, a3, a4);
@@ -294,12 +260,6 @@ static HRESULT STDMETHODCALLTYPE x_Device_94(void* self, const D3D12_RESOURCE_DE
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateReservedResource1", hr);
return bx_xbox_wrap_result(hr, a4, a5);
}
static D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE x_Device_95(void* self, UINT a0, UINT a1, const D3D12_RESOURCE_DESC * a2, D3D12_RESOURCE_ALLOCATION_INFO1 * a3) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo1");
D3D12_RESOURCE_ALLOCATION_INFO result{};
bx_xbox_host<ID3D12Device4>(self)->GetResourceAllocationInfo1(&result, a0, a1, a2, a3);
return result;
}
static HRESULT STDMETHODCALLTYPE x_Device_96(void* self, ID3D12LifetimeOwner * a0, REFIID a1, void ** a2) {
BX_D3D_TRACE("XboxDevice", "CreateLifetimeTracker");
HRESULT hr = bx_xbox_host<ID3D12Device5>(self)->CreateLifetimeTracker(bx_xbox_unwrap_as<ID3D12LifetimeOwner>(a0), a1, a2);
@@ -362,12 +322,6 @@ static HRESULT STDMETHODCALLTYPE x_Device_107(void* self, const D3D12_PROTECTED_
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateProtectedResourceSession1", hr);
return bx_xbox_wrap_result(hr, a1, a2);
}
static D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE x_Device_108(void* self, UINT a0, UINT a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_RESOURCE_ALLOCATION_INFO1 * a3) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo2");
D3D12_RESOURCE_ALLOCATION_INFO result{};
bx_xbox_host<ID3D12Device8>(self)->GetResourceAllocationInfo2(&result, a0, a1, a2, a3);
return result;
}
static HRESULT STDMETHODCALLTYPE x_Device_110(void* self, ID3D12Heap * a0, UINT64 a1, const D3D12_RESOURCE_DESC1 * a2, D3D12_RESOURCE_STATES a3, const D3D12_CLEAR_VALUE * a4, REFIID a5, void ** a6) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedResource1");
HRESULT hr = bx_xbox_host<ID3D12Device8>(self)->CreatePlacedResource1(bx_xbox_unwrap_as<ID3D12Heap>(a0), a1, a2, a3, a4, a5, a6);
@@ -468,19 +422,19 @@ const void* const kDeviceTable[] = {
reinterpret_cast<const void*>(&bx_xbox_device_get_descriptor_handle_increment_size),
reinterpret_cast<const void*>(&x_Device_16),
reinterpret_cast<const void*>(&bx_xbox_device_create_constant_buffer_view),
reinterpret_cast<const void*>(&x_Device_18),
reinterpret_cast<const void*>(&x_Device_19),
reinterpret_cast<const void*>(&x_Device_20),
reinterpret_cast<const void*>(&x_Device_21),
reinterpret_cast<const void*>(&bx_xbox_device_create_shader_resource_view),
reinterpret_cast<const void*>(&bx_xbox_device_create_unordered_access_view),
reinterpret_cast<const void*>(&bx_xbox_device_create_render_target_view),
reinterpret_cast<const void*>(&bx_xbox_device_create_depth_stencil_view),
reinterpret_cast<const void*>(&x_Device_22),
reinterpret_cast<const void*>(&bx_xbox_device_copy_descriptors),
reinterpret_cast<const void*>(&x_Device_24),
reinterpret_cast<const void*>(&x_Device_25),
reinterpret_cast<const void*>(&bx_xbox_device_get_resource_allocation_info),
reinterpret_cast<const void*>(&x_Device_26),
reinterpret_cast<const void*>(&bx_xbox_device_create_committed_resource),
reinterpret_cast<const void*>(&x_Device_28),
reinterpret_cast<const void*>(&x_Device_29),
reinterpret_cast<const void*>(&x_Device_30),
reinterpret_cast<const void*>(&bx_xbox_device_create_placed_resource),
reinterpret_cast<const void*>(&bx_xbox_device_create_reserved_resource),
reinterpret_cast<const void*>(&x_Device_31),
reinterpret_cast<const void*>(&x_Device_32),
reinterpret_cast<const void*>(&x_Device_33),
@@ -545,7 +499,7 @@ const void* const kDeviceTable[] = {
reinterpret_cast<const void*>(&bx_xbox_device_create_committed_resource1),
reinterpret_cast<const void*>(&x_Device_93),
reinterpret_cast<const void*>(&x_Device_94),
reinterpret_cast<const void*>(&x_Device_95),
reinterpret_cast<const void*>(&bx_xbox_device_get_resource_allocation_info1),
reinterpret_cast<const void*>(&x_Device_96),
reinterpret_cast<const void*>(&x_Device_97),
reinterpret_cast<const void*>(&x_Device_98),
@@ -558,7 +512,7 @@ const void* const kDeviceTable[] = {
reinterpret_cast<const void*>(&x_Device_105),
reinterpret_cast<const void*>(&x_Device_106),
reinterpret_cast<const void*>(&x_Device_107),
reinterpret_cast<const void*>(&x_Device_108),
reinterpret_cast<const void*>(&bx_xbox_device_get_resource_allocation_info2),
reinterpret_cast<const void*>(&bx_xbox_device_create_committed_resource2),
reinterpret_cast<const void*>(&x_Device_110),
reinterpret_cast<const void*>(&x_Device_111),
@@ -607,7 +561,7 @@ const IID kDeviceIids[] = {
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
};
/* ID3D12Device11: 139 slots (63 forwarded, 35 shared, 41 stubs); hosted on ID3D12Device10. */
/* ID3D12Device11: 139 slots (54 forwarded, 44 shared, 41 stubs); hosted on ID3D12Device10. */
const IID kHostDevice = __uuidof(ID3D12Device10);
static HRESULT STDMETHODCALLTYPE x_Resource_3(void* self, REFGUID a0, UINT * a1, void * a2) {
@@ -1348,10 +1302,6 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_19(void* self, ID3D12Resourc
BX_D3D_TRACE("XboxGraphicsCommandList", "ResolveSubresource");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResolveSubresource(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_unwrap_as<ID3D12Resource>(a2), a3, a4);
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_20(void* self, D3D12_PRIMITIVE_TOPOLOGY a0) {
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetPrimitiveTopology");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetPrimitiveTopology(a0);
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_21(void* self, UINT a0, const D3D12_VIEWPORT * a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "RSSetViewports");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->RSSetViewports(a0, a1);
@@ -1716,7 +1666,7 @@ const void* const kGraphicsCommandListTable[] = {
reinterpret_cast<const void*>(&x_GraphicsCommandList_17),
reinterpret_cast<const void*>(&x_GraphicsCommandList_18),
reinterpret_cast<const void*>(&x_GraphicsCommandList_19),
reinterpret_cast<const void*>(&x_GraphicsCommandList_20),
reinterpret_cast<const void*>(&bx_xbox_list_ia_set_primitive_topology),
reinterpret_cast<const void*>(&x_GraphicsCommandList_21),
reinterpret_cast<const void*>(&x_GraphicsCommandList_22),
reinterpret_cast<const void*>(&x_GraphicsCommandList_23),
@@ -1863,7 +1813,7 @@ const IID kGraphicsCommandListIids[] = {
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
};
/* ID3D12GraphicsCommandList8: 150 slots (66 forwarded, 24 shared, 60 stubs); hosted on ID3D12GraphicsCommandList7. */
/* ID3D12GraphicsCommandList8: 150 slots (65 forwarded, 25 shared, 60 stubs); hosted on ID3D12GraphicsCommandList7. */
const IID kHostGraphicsCommandList = __uuidof(ID3D12GraphicsCommandList7);
} // namespace
+63 -3
View File
@@ -279,12 +279,72 @@ bool zero_guest_cache_line(uint64_t address, EXCEPTION_RECORD& exception) {
return false;
}
// A title that zeroes memory with CLZERO does it in a loop, and each iteration would trap again
// (an exception round trip per 64 bytes: seconds per 100 MB). When the trapped CLZERO is followed
// by exactly
// add rax, 0x40 ; cmp rax, <reg64> ; jb <the clzero>
// the remaining iterations are done here: every further line below the limit is zeroed and RAX is
// left at the last one, so the title's own add/cmp/jb then leaves the loop. The range is zeroed
// region by region and stops early at memory that is not committed and writable, where the
// title's next CLZERO traps as before. Returns the number of extra lines zeroed.
uint64_t clzero_loop_fast_path(CONTEXT& context) {
const auto* code = reinterpret_cast<const uint8_t*>(context.Rip);
MEMORY_BASIC_INFORMATION text{};
if (!VirtualQuery(code, &text, sizeof(text)) || text.State != MEM_COMMIT ||
reinterpret_cast<uintptr_t>(code) + 12 > reinterpret_cast<uintptr_t>(text.BaseAddress) + text.RegionSize) {
return 0;
}
if (code[0] != 0x0F || code[1] != 0x01 || code[2] != 0xFC) return 0; // clzero
if (code[3] != 0x48 || code[4] != 0x83 || code[5] != 0xC0 || code[6] != 0x40) return 0; // add rax, 0x40
if ((code[7] != 0x48 && code[7] != 0x4C) || code[8] != 0x39 || (code[9] & 0xC7) != 0xC0) return 0; // cmp rax, r64
if (code[10] != 0x72 || code[11] != 0xF4) return 0; // jb -12
const unsigned reg = ((code[9] >> 3) & 7) | (code[7] == 0x4C ? 8 : 0);
const DWORD64* registers = &context.Rax; // Rax, Rcx, Rdx, Rbx, Rsp, Rbp, Rsi, Rdi, R8..R15
const uint64_t limit = registers[reg];
constexpr uint64_t line = 64;
uint64_t next = context.Rax + line;
if (reg == 0 || next >= limit || limit - next > (1ull << 32)) return 0;
const uint64_t last = next + ((limit - 1 - next) / line) * line; // largest next + 64k below limit
constexpr DWORD writable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
uint64_t done = 0;
while (next <= last) {
const uint64_t start = next & ~(line - 1);
MEMORY_BASIC_INFORMATION page{};
if (!VirtualQuery(reinterpret_cast<const void*>(start), &page, sizeof(page)) || page.State != MEM_COMMIT ||
!(page.Protect & writable) || (page.Protect & PAGE_GUARD)) {
break;
}
const uint64_t region_end = reinterpret_cast<uintptr_t>(page.BaseAddress) + page.RegionSize;
uint64_t lines = (last - next) / line + 1;
const uint64_t fit = (region_end - start) / line;
if (fit == 0) break;
if (lines > fit) lines = fit;
std::memset(reinterpret_cast<void*>(start), 0, static_cast<size_t>(lines * line));
context.Rax = next + (lines - 1) * line;
next += lines * line;
done += lines;
}
return done;
}
bool apply_amd_instruction(const AmdInstruction& instruction, CONTEXT& context,
EXCEPTION_RECORD& exception) {
switch (instruction.kind) {
case kClzero:
return zero_guest_cache_line(instruction.address32 ? static_cast<uint32_t>(context.Rax)
: context.Rax, exception);
case kClzero: {
if (!zero_guest_cache_line(instruction.address32 ? static_cast<uint32_t>(context.Rax) : context.Rax,
exception)) {
return false;
}
if (!instruction.address32) {
static std::atomic<uint64_t> batched{0};
const uint64_t lines = clzero_loop_fast_path(context);
if (lines && batched.fetch_add(1) == 0) {
bx_log_emit(BX_LOG_INFO, "runtime_veh", "clzero_loop",
"CLZERO loop (add rax,0x40; cmp; jb) completed in one trap; later loops are not logged");
}
}
return true;
}
case kMonitorx:
// There is no host monitor state. MWAITX may complete immediately.
return true;
+46 -4
View File
@@ -37,6 +37,9 @@ HRESULT WINAPI XTaskQueueSubmitCallback(void*, bx::gdk::Port, void*, void (CALLB
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void*, bx::gdk::Port, uint32_t, void*,
void (CALLBACK*)(void*, bool));
bool WINAPI XTaskQueueGetCurrentProcessTaskQueue(void**);
HRESULT WINAPI bx_xtq_duplicate_handle(void*, void**);
HRESULT WINAPI bx_xtq_get_port(void*, bx::gdk::Port, void**);
HRESULT WINAPI bx_xtq_create_composite(void*, void*, void**);
HRESULT WINAPI XAsyncGetStatus(void*, bool);
HRESULT WINAPI XAsyncGetResultSize(void*, size_t*);
@@ -45,6 +48,8 @@ void WINAPI XAsyncCancel(void*);
HRESULT WINAPI XUserAddAsync(uint32_t, void*);
HRESULT WINAPI XUserAddResult(void*, void**);
void WINAPI XUserCloseHandle(void*);
HRESULT WINAPI bx_xuser_duplicate_handle(void*, void**);
bool WINAPI bx_xuser_is_handle(void*);
HRESULT WINAPI XUserGetId(void*, uint64_t*);
HRESULT WINAPI XUserGetGamertag(void*, uint32_t, size_t, char*, size_t*);
HRESULT WINAPI XUserGetTokenAndSignatureAsync(void*, uint32_t, const char*, const char*, size_t, const void*, size_t,
@@ -176,6 +181,32 @@ HRESULT WINAPI core_async_get_result_size(void*, void* async, size_t* size) {
void WINAPI core_async_cancel(void*, void* async) {
XAsyncCancel(async);
}
// XAsyncRun: the title's work callback runs on the block's work port and its return value
// completes the block (no result payload).
struct AsyncRunOp final : bx::gdk::AsyncOp {
using Work = HRESULT (CALLBACK*)(void*);
Work work;
void* block;
AsyncRunOp(Work work, void* block) : work(work), block(block) {}
uint32_t kind() const override { return 0x4E5552u; } // "RUN"
HRESULT execute() override { return work(block); }
size_t result_size() const override { return 0; }
};
HRESULT WINAPI core_async_run(void*, void* async, AsyncRunOp::Work work) {
if (!async || !work) return E_INVALIDARG;
auto op = std::unique_ptr<bx::gdk::AsyncOp>(new (std::nothrow) AsyncRunOp(work, async));
if (!op) return E_OUTOFMEMORY;
return bx::gdk::begin_async_op(async, std::move(op));
}
HRESULT WINAPI core_tq_create_composite(void*, void* work_port, void* completion_port, void** out) {
return bx_xtq_create_composite(work_port, completion_port, out);
}
HRESULT WINAPI core_tq_get_port(void*, void* queue, Port port, void** out) {
return bx_xtq_get_port(queue, port, out);
}
HRESULT WINAPI core_tq_duplicate(void*, void* queue, void** out) {
return bx_xtq_duplicate_handle(queue, out);
}
HRESULT WINAPI core_tq_create(void*, DispatchMode work, DispatchMode comp, void** out) {
return XTaskQueueCreate(work, comp, out);
}
@@ -220,7 +251,11 @@ const std::array<const void*, 36> kCoreVtbl = [] {
v[3] = reinterpret_cast<const void*>(&core_async_get_status);
v[4] = reinterpret_cast<const void*>(&core_async_get_result_size);
v[5] = reinterpret_cast<const void*>(&core_async_cancel);
v[6] = reinterpret_cast<const void*>(&core_async_run);
v[12] = reinterpret_cast<const void*>(&core_tq_create);
v[13] = reinterpret_cast<const void*>(&core_tq_create_composite);
v[14] = reinterpret_cast<const void*>(&core_tq_get_port);
v[15] = reinterpret_cast<const void*>(&core_tq_duplicate);
v[16] = reinterpret_cast<const void*>(&core_tq_dispatch);
v[17] = reinterpret_cast<const void*>(&core_tq_close);
v[18] = reinterpret_cast<const void*>(&core_tq_submit);
@@ -433,8 +468,16 @@ std::unordered_set<uint64_t> user_event_tokens;
void WINAPI user_close_handle(void*, void* h) {
XUserCloseHandle(h);
}
HRESULT WINAPI user_duplicate_handle(void*, void* user, void** out) {
const HRESULT hr = bx_xuser_duplicate_handle(user, out);
bx_log_emit(SUCCEEDED(hr) ? BX_LOG_INFO : BX_LOG_WARN, "xgameruntime", "XUserDuplicateHandle",
SUCCEEDED(hr) ? "duplicate handle for the offline user" : "invalid user handle");
return hr;
}
int32_t WINAPI user_compare(void*, void* u1, void* u2) {
if (u1 == u2) return 0;
// One offline user: every valid handle (duplicates included) names the same user.
if (bx_xuser_is_handle(u1) && bx_xuser_is_handle(u2)) return 0;
return reinterpret_cast<uintptr_t>(u1) < reinterpret_cast<uintptr_t>(u2) ? -1 : 1;
}
HRESULT WINAPI user_get_max_users(void*, uint32_t* max_users) {
@@ -517,6 +560,7 @@ HRESULT WINAPI user_get_gamertag(void*, void* user, uint32_t comp, size_t sz, ch
const std::array<const void*, 64> kUserVtbl = [] {
auto v = make_default_vtbl<64>();
v[3] = reinterpret_cast<const void*>(&user_duplicate_handle);
v[4] = reinterpret_cast<const void*>(&user_close_handle);
v[5] = reinterpret_cast<const void*>(&user_compare);
v[6] = reinterpret_cast<const void*>(&user_get_max_users);
@@ -742,8 +786,6 @@ BX_HR(gs_quota_result, "IXGameSaveImpl", 9, "XGameSaveGetRemainingQuotaResult")
BX_HR(gs_delete, "IXGameSaveImpl", 10, "XGameSaveDeleteContainer")
BX_HR(gs_delete_async, "IXGameSaveImpl", 11, "XGameSaveDeleteContainerAsync")
BX_HR(gs_delete_result, "IXGameSaveImpl", 12, "XGameSaveDeleteContainerResult")
BX_HR(gs_container_info, "IXGameSaveImpl", 13, "XGameSaveGetContainerInfo")
BX_HR(gs_enum_by_name, "IXGameSaveImpl", 15, "XGameSaveEnumerateContainerInfoByName")
BX_HR(gs_enum_blobs, "IXGameSaveImpl", 18, "XGameSaveEnumerateBlobInfo")
BX_HR(gs_enum_blobs_by_name, "IXGameSaveImpl", 19, "XGameSaveEnumerateBlobInfoByName")
BX_HR(gs_blob_delete, "IXGameSaveImpl", 26, "XGameSaveSubmitBlobDelete")
@@ -789,9 +831,9 @@ const std::array<const void*, 33> kGameSaveVtbl = [] {
v[10] = reinterpret_cast<const void*>(&gs_delete);
v[11] = reinterpret_cast<const void*>(&gs_delete_async);
v[12] = reinterpret_cast<const void*>(&gs_delete_result);
v[13] = reinterpret_cast<const void*>(&gs_container_info);
v[13] = reinterpret_cast<const void*>(&get_container_info);
v[14] = reinterpret_cast<const void*>(&enumerate_container_info);
v[15] = reinterpret_cast<const void*>(&gs_enum_by_name);
v[15] = reinterpret_cast<const void*>(&enumerate_container_info_by_name);
v[16] = reinterpret_cast<const void*>(&create_container);
v[17] = reinterpret_cast<const void*>(&close_container);
v[18] = reinterpret_cast<const void*>(&gs_enum_blobs);
+57 -1
View File
@@ -841,7 +841,55 @@ HRESULT WINAPI read_blob_data_result(void*, void* async, size_t size, void* blob
});
}
HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, GameSaveContainerInfoCallback callback) {
HRESULT WINAPI get_container_info(void*, void* provider, const char* container_name, void* context,
GameSaveContainerInfoCallback callback) {
if (!callback) return E_INVALIDARG;
const auto typed = reinterpret_cast<ContainerInfoCallback>(callback);
const auto generation = active_runtime_generation();
ContainerData data;
bool exists = false;
try {
std::wstring dir;
{
std::lock_guard lock(handle_mutex);
const auto* open = find_provider(provider, generation);
if (!open) return stale_handle_error(generation);
if (!valid_container_name(container_name)) return kInvalidContainerName;
dir = open->dir;
}
const std::string name(container_name);
DirectoryLock lock(dir);
if (FAILED(lock.status())) return lock.status();
const auto path = container_file(dir, name);
std::vector<uint8_t> bytes;
const auto hr = read_file(path, bytes, exists);
if (FAILED(hr)) return hr;
if (exists) {
if (!parse(bytes, data, false)) {
log_bad_file("corrupt_container", path);
return kFileCorrupt;
}
if (data.name != name) {
log_bad_file("container_id_collision", path);
return HRESULT_FROM_WIN32(ERROR_FILE_EXISTS);
}
}
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
// Inference (source rank 3, #667): when the named container does not exist, succeed without
// invoking the callback.
if (!exists) return S_OK;
// No lock is held here, so the callback may call back into XGameSave.
const ContainerInfo info{data.name.c_str(), data.display_name.c_str(),
static_cast<uint32_t>(data.blobs.size()), data.total_size,
static_cast<time_t>(data.last_modified), false};
(void)typed(&info, context);
return S_OK;
}
HRESULT WINAPI enumerate_container_info_by_name(void*, void* provider, const char* prefix, void* context,
GameSaveContainerInfoCallback callback) {
if (!callback) return E_INVALIDARG;
const auto typed = reinterpret_cast<ContainerInfoCallback>(callback);
const auto generation = active_runtime_generation();
@@ -854,10 +902,14 @@ HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, Ga
if (!open) return stale_handle_error(generation);
dir = open->dir;
}
const std::string filter = prefix ? std::string(prefix) : std::string();
DirectoryLock lock(dir);
if (FAILED(lock.status())) return lock.status();
const auto hr = list_containers(dir, list);
if (FAILED(hr)) return hr;
if (!filter.empty()) {
std::erase_if(list, [&](const ContainerData& item) { return !item.name.starts_with(filter); });
}
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
@@ -872,6 +924,10 @@ HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, Ga
return S_OK;
}
HRESULT WINAPI enumerate_container_info(void*, void* provider, void* context, GameSaveContainerInfoCallback callback) {
return enumerate_container_info_by_name(nullptr, provider, nullptr, context, callback);
}
// Synchronous public slots. Each one runs the async operation above on the process task
// queue (a null XAsyncBlock queue) and waits. syncOnDemand is passed through and has no
// effect, the same as InitializeProviderAsync. Signatures follow the public Microsoft Learn
+4
View File
@@ -83,8 +83,12 @@ HRESULT WINAPI initialize_provider_result(void* self, void* async, void** provid
void WINAPI close_provider(void* self, void* provider);
HRESULT WINAPI create_container(void* self, void* provider, const char* name, void** out);
void WINAPI close_container(void* self, void* container);
HRESULT WINAPI get_container_info(void* self, void* provider, const char* container_name, void* context,
GameSaveContainerInfoCallback callback);
HRESULT WINAPI enumerate_container_info(void* self, void* provider, void* context,
GameSaveContainerInfoCallback callback);
HRESULT WINAPI enumerate_container_info_by_name(void* self, void* provider, const char* prefix, void* context,
GameSaveContainerInfoCallback callback);
HRESULT WINAPI read_blob_data(void* self, void* container, const char** names, uint32_t* count, size_t size,
void* blobs);
HRESULT WINAPI read_blob_data_async(void* self, void* container, const char** names, uint32_t count, void* async);
+82 -2
View File
@@ -185,13 +185,31 @@ public:
Queue(DispatchMode work, DispatchMode completion) : lanes{{this, work}, {this, completion}} {}
Lane lanes[2];
// A composite queue (XTaskQueueCreateComposite) has no lanes of its own in use: each port
// forwards to a port of another queue.
QueueRef forward[2];
Port forward_port[2] = {Port::work, Port::completion};
};
// Follows composite forwarding to the queue and port that hold the lane.
static void resolve_lane(QueueRef& queue, Port& port) {
for (int depth = 0; depth < 8 && queue; ++depth) {
const auto index = static_cast<uint32_t>(port);
if (!queue->forward[index]) return;
const Port next_port = queue->forward_port[index];
queue = queue->forward[index];
port = next_port;
}
}
namespace {
std::mutex queues_mutex;
std::unordered_map<uintptr_t, QueueRef> handles;
uintptr_t next_handle = 1;
// XTaskQueuePortHandle values (even numbers, so they never collide with queue handles).
std::unordered_map<uintptr_t, std::pair<QueueRef, Port>> port_handles;
uintptr_t next_port_handle = 2;
QueueRef process_queue;
HRESULT make_queue(DispatchMode work, DispatchMode completion, QueueRef& queue) {
@@ -238,7 +256,9 @@ QueueRef acquire_queue(void* handle) {
}
bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool is_completion) {
return queue->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
QueueRef target = queue;
resolve_lane(target, port);
return target->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
}
@@ -275,6 +295,10 @@ void WINAPI XTaskQueueCloseHandle(void* handle) {
queue = std::move(it->second);
close_queue = queue != process_queue;
handles.erase(it);
// Duplicated handles share the queue: only the last close shuts its lanes down.
for (const auto& other : handles) {
if (other.second == queue) close_queue = false;
}
}
// The frozen ABI exposes no termination or duplicate-handle API. Drain manual
// completion callbacks on close and let accepted pool work finish normally.
@@ -285,8 +309,64 @@ void WINAPI XTaskQueueCloseHandle(void* handle) {
bool WINAPI XTaskQueueDispatch(void* handle, Port port, uint32_t timeout) {
if (!handle || port > Port::completion) return false;
auto queue = acquire_queue(handle);
if (!queue) return false;
resolve_lane(queue, port);
return queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
}
// Not exported: reached through IXGameRuntimeCore (com_dispatch.cpp).
HRESULT WINAPI bx_xtq_duplicate_handle(void* handle, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
const auto queue = acquire_queue(handle);
return queue && queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
if (!queue) return E_HANDLE;
try {
std::lock_guard lock(queues_mutex);
*out = add_handle(queue);
return S_OK;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
}
HRESULT WINAPI bx_xtq_get_port(void* handle, Port port, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (port > Port::completion) return E_INVALIDARG;
const auto queue = acquire_queue(handle);
if (!queue) return E_HANDLE;
try {
std::lock_guard lock(queues_mutex);
const auto id = next_port_handle;
next_port_handle += 2;
port_handles.emplace(id, std::make_pair(queue, port));
*out = reinterpret_cast<void*>(id);
return S_OK;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
}
HRESULT WINAPI bx_xtq_create_composite(void* work_port, void* completion_port, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
try {
std::lock_guard lock(queues_mutex);
const auto work = port_handles.find(reinterpret_cast<uintptr_t>(work_port));
const auto completion = port_handles.find(reinterpret_cast<uintptr_t>(completion_port));
if (work == port_handles.end() || completion == port_handles.end()) return E_HANDLE;
// Immediate lanes: never used, every submit and dispatch is forwarded.
auto queue = std::make_shared<Queue>(DispatchMode::immediate, DispatchMode::immediate);
queue->forward[0] = work->second.first;
queue->forward_port[0] = work->second.second;
queue->forward[1] = completion->second.first;
queue->forward_port[1] = completion->second.second;
*out = add_handle(queue);
return S_OK;
} catch (const std::bad_alloc&) {
return E_OUTOFMEMORY;
}
}
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
+21 -1
View File
@@ -167,6 +167,10 @@ public:
Operation operation;
std::unique_ptr<AsyncOp> op;
std::unique_ptr<CompletionTask> completion;
// The queue the block named. A composite queue forwards its ports to other queues, and a
// task runs with the queue that owns the lane, so the completion must go back through
// this one to reach the composite's completion port.
QueueRef origin;
bool queued = false;
AsyncTask(AsyncBlock* block, Operation operation, std::unique_ptr<AsyncOp> op)
@@ -225,7 +229,7 @@ private:
queued = false;
write_state(block, state);
}
if (completion) submit(queue, Port::completion, std::move(completion), true);
if (completion) submit(origin ? origin : queue, Port::completion, std::move(completion), true);
}
};
@@ -236,6 +240,7 @@ HRESULT begin(AsyncBlock* block, Operation operation, void* store = nullptr, std
auto work = std::unique_ptr<AsyncTask>(new (std::nothrow) AsyncTask(block, operation, std::move(op)));
if (!work) return E_OUTOFMEMORY;
work->origin = queue;
if (block->callback) {
work->completion.reset(new (std::nothrow) CompletionTask(block));
if (!work->completion) return E_OUTOFMEMORY;
@@ -643,6 +648,21 @@ HRESULT WINAPI XUserAddResult(AsyncBlock* block, void** out) {
return result;
}
// Not exported: XUserDuplicateHandle is reached through IXUser (com_dispatch.cpp). A duplicate is
// a new handle to the same (single, offline) user; each handle is closed separately.
HRESULT WINAPI bx_xuser_duplicate_handle(void* user, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
std::lock_guard lock(state_mutex);
if (!users.contains(user)) return runtime_invalid_handle;
return create_handle(users, out);
}
bool WINAPI bx_xuser_is_handle(void* user) {
std::lock_guard lock(state_mutex);
return users.contains(user);
}
void WINAPI XUserCloseHandle(void* user) {
std::lock_guard lock(state_mutex);
users.erase(user);
@@ -0,0 +1,3 @@
add_executable(test_d3d12_console_formats main.cpp)
target_compile_definitions(test_d3d12_console_formats PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_console_formats PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,300 @@
/*
* Conformance test: console-only DXGI formats and console-only view combinations must not reach
* the host Direct3D 12 implementation.
*
* Contract (Xbox Series GDK d3d12_xs.h): DXGI_FORMAT has values the PC enumeration lacks:
* 116 R10G10B10_7E3_A2_FLOAT, 117 R10G10B10_6E4_A2_FLOAT, 118 D16_UNORM_S8_UINT,
* 119 R16_UNORM_X8_TYPELESS, 120 X16_TYPELESS_G8_UINT, 189 R10G10B10_SNORM_A2_UNORM,
* 190 R4G4_UNORM.
* A title built for the console passes them to resource, allocation-info and view calls, and
* creates unordered-access views on depth-stencil textures (the console allows
* ALLOW_DEPTH_STENCIL together with ALLOW_UNORDERED_ACCESS; PC Direct3D 12 does not).
*
* On a host that does not know them (D3DMetal), either makes Metal abort the process, so the
* failure mode of this test without the fix is that the process dies at the first such call and
* the runner sees a non-zero exit with no PASS line.
*
* Every call goes through the Xbox-layout function table of an Xbox-layout device (ADR 0009).
* Slots: 2 Release; device 14 CreateDescriptorHeap, 18 CreateShaderResourceView,
* 19 CreateUnorderedAccessView, 21 CreateDepthStencilView, 25 GetResourceAllocationInfo,
* 27 CreateCommittedResource, 95 GetResourceAllocationInfo1, 108 GetResourceAllocationInfo2;
* resource 10 GetDesc; descriptor heap 9 GetCPUDescriptorHandleForHeapStart.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2;
constexpr int kDevCreateDescriptorHeap = 14, kDevCreateShaderResourceView = 18, kDevCreateUnorderedAccessView = 19;
constexpr int kDevCreateDepthStencilView = 21, kDevGetResourceAllocationInfo = 25, kDevCreateCommittedResource = 27;
constexpr int kDevGetResourceAllocationInfo1 = 95, kDevGetResourceAllocationInfo2 = 108;
constexpr int kResGetDesc = 10, kHeapGetCpuStart = 9;
// Console-only formats, by number: the PC <dxgiformat.h> has no names for them.
constexpr DXGI_FORMAT kD16_UNORM_S8_UINT = static_cast<DXGI_FORMAT>(118);
constexpr DXGI_FORMAT kR16_UNORM_X8_TYPELESS = static_cast<DXGI_FORMAT>(119);
constexpr DXGI_FORMAT kX16_TYPELESS_G8_UINT = static_cast<DXGI_FORMAT>(120);
int g_checks = 0;
int g_failed = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_console_formats:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using AllocationInfoFn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_RESOURCE_DESC*);
using AllocationInfo1Fn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_RESOURCE_DESC*,
D3D12_RESOURCE_ALLOCATION_INFO1*);
using AllocationInfo2Fn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_RESOURCE_DESC1*,
D3D12_RESOURCE_ALLOCATION_INFO1*);
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 CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_DESCRIPTOR_HEAP_DESC*, REFIID, void**);
using HeapStartFn = D3D12_CPU_DESCRIPTOR_HANDLE(STDMETHODCALLTYPE*)(void*);
using GetDescFn = void(STDMETHODCALLTYPE*)(void*, D3D12_RESOURCE_DESC*);
using CreateSrvFn = void(STDMETHODCALLTYPE*)(void*, void*, const D3D12_SHADER_RESOURCE_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
using CreateUavFn = void(STDMETHODCALLTYPE*)(void*, void*, void*, const D3D12_UNORDERED_ACCESS_VIEW_DESC*,
D3D12_CPU_DESCRIPTOR_HANDLE);
using CreateDsvFn = void(STDMETHODCALLTYPE*)(void*, void*, const D3D12_DEPTH_STENCIL_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
D3D12_RESOURCE_DESC texture(DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags) {
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
desc.Width = 256;
desc.Height = 256;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.Format = format;
desc.SampleDesc.Count = 1;
desc.Flags = flags;
return desc;
}
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* f = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
std::fclose(f);
}
return text;
}
size_t count_of(const std::string& text, const char* needle) {
size_t n = 0;
for (size_t pos = text.find(needle); pos != std::string::npos; pos = text.find(needle, pos + 1)) ++n;
return n;
}
} // namespace
int main() {
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_console_formats: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
return 77;
}
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
if (!dev) return 1;
const size_t stubs_before = count_of(read_log(), "CreateUnorderedAccessView(depth-stencil resource)");
// 1. Allocation info for a console-only format. The host's answer for the PC format the shim
// documents as its substitute (R32G8X24_TYPELESS for a D16_UNORM_S8_UINT texture) is the
// expected value, asked for directly so the expectation does not pass through the
// translation under test.
const D3D12_RESOURCE_FLAGS depth = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
const D3D12_RESOURCE_DESC console_depth = texture(kD16_UNORM_S8_UINT, depth);
const D3D12_RESOURCE_DESC pc_depth = texture(DXGI_FORMAT_R32G8X24_TYPELESS, depth);
const D3D12_RESOURCE_ALLOCATION_INFO want = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &pc_depth);
CHECK(want.SizeInBytes != 0 && want.SizeInBytes != UINT64_MAX, "control: host sizes a PC depth texture (size=%llu)",
static_cast<unsigned long long>(want.SizeInBytes));
D3D12_RESOURCE_ALLOCATION_INFO got = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &console_depth);
CHECK(got.SizeInBytes == want.SizeInBytes && got.Alignment == want.Alignment,
"GetResourceAllocationInfo(format 118): size=%llu alignment=%llu, want %llu/%llu",
static_cast<unsigned long long>(got.SizeInBytes), static_cast<unsigned long long>(got.Alignment),
static_cast<unsigned long long>(want.SizeInBytes), static_cast<unsigned long long>(want.Alignment));
D3D12_RESOURCE_ALLOCATION_INFO1 each{};
got = slot<AllocationInfo1Fn>(dev, kDevGetResourceAllocationInfo1)(dev, 0, 1, &console_depth, &each);
CHECK(got.SizeInBytes == want.SizeInBytes, "GetResourceAllocationInfo1(format 118): size=%llu, want %llu",
static_cast<unsigned long long>(got.SizeInBytes), static_cast<unsigned long long>(want.SizeInBytes));
D3D12_RESOURCE_DESC1 console_depth1{};
std::memcpy(&console_depth1, &console_depth, sizeof(console_depth)); // DESC1 is DESC plus a trailing region
got = slot<AllocationInfo2Fn>(dev, kDevGetResourceAllocationInfo2)(dev, 0, 1, &console_depth1, &each);
CHECK(got.SizeInBytes == want.SizeInBytes, "GetResourceAllocationInfo2(format 118): size=%llu, want %llu",
static_cast<unsigned long long>(got.SizeInBytes), static_cast<unsigned long long>(want.SizeInBytes));
// An array with a console-only format in the second place only: every entry is translated,
// not just the first.
const D3D12_RESOURCE_DESC pair[2] = {texture(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE), console_depth};
const D3D12_RESOURCE_DESC pc_pair[2] = {pair[0], pc_depth};
const D3D12_RESOURCE_ALLOCATION_INFO want_pair = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 2, pc_pair);
got = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 2, pair);
CHECK(got.SizeInBytes == want_pair.SizeInBytes && got.SizeInBytes != 0,
"GetResourceAllocationInfo(two descriptions, the second console-only): size=%llu, want %llu",
static_cast<unsigned long long>(got.SizeInBytes), static_cast<unsigned long long>(want_pair.SizeInBytes));
// The colour formats: each is sized as the documented substitute.
const struct {
int console;
DXGI_FORMAT substitute;
} colour[] = {{116, DXGI_FORMAT_R16G16B16A16_FLOAT},
{117, DXGI_FORMAT_R16G16B16A16_FLOAT},
{189, DXGI_FORMAT_R16G16B16A16_SNORM},
{190, DXGI_FORMAT_R8G8_UNORM}};
for (const auto& c : colour) {
const D3D12_RESOURCE_DESC a = texture(static_cast<DXGI_FORMAT>(c.console), D3D12_RESOURCE_FLAG_NONE);
const D3D12_RESOURCE_DESC b = texture(c.substitute, D3D12_RESOURCE_FLAG_NONE);
const D3D12_RESOURCE_ALLOCATION_INFO expected = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &b);
got = slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &a);
CHECK(got.SizeInBytes == expected.SizeInBytes && got.SizeInBytes != 0, "GetResourceAllocationInfo(format %d): size=%llu, want %llu",
c.console, static_cast<unsigned long long>(got.SizeInBytes), static_cast<unsigned long long>(expected.SizeInBytes));
}
// 2. A committed depth texture of the console format, with a clear value of the console format.
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
D3D12_CLEAR_VALUE clear{};
clear.Format = kD16_UNORM_S8_UINT;
clear.DepthStencil.Depth = 1.0f;
void* depth_texture = nullptr;
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &heap, D3D12_HEAP_FLAG_NONE, &console_depth,
D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear,
__uuidof(ID3D12Resource), &depth_texture);
CHECK(hr == S_OK && depth_texture, "CreateCommittedResource(format 118) hr=0x%08lx", static_cast<unsigned long>(hr));
// Views on it: depth-stencil in the console format, and its two planes read through the
// console's plane formats.
D3D12_DESCRIPTOR_HEAP_DESC dsv_heap_desc{};
dsv_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
dsv_heap_desc.NumDescriptors = 2;
void* dsv_heap = nullptr;
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &dsv_heap_desc, __uuidof(ID3D12DescriptorHeap), &dsv_heap);
CHECK(hr == S_OK && dsv_heap, "CreateDescriptorHeap(DSV) hr=0x%08lx", static_cast<unsigned long>(hr));
D3D12_DESCRIPTOR_HEAP_DESC view_heap_desc{};
view_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
view_heap_desc.NumDescriptors = 8;
void* view_heap = nullptr;
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &view_heap_desc, __uuidof(ID3D12DescriptorHeap), &view_heap);
CHECK(hr == S_OK && view_heap, "CreateDescriptorHeap(CBV_SRV_UAV) hr=0x%08lx", static_cast<unsigned long>(hr));
if (!depth_texture || !dsv_heap || !view_heap) {
std::fprintf(stderr, "FAIL: test_d3d12_console_formats: setup\n");
return 1;
}
const D3D12_CPU_DESCRIPTOR_HANDLE dsv = slot<HeapStartFn>(dsv_heap, kHeapGetCpuStart)(dsv_heap);
const D3D12_CPU_DESCRIPTOR_HANDLE views = slot<HeapStartFn>(view_heap, kHeapGetCpuStart)(view_heap);
constexpr SIZE_T kXboxViewSize = 32; // console CBV/SRV/UAV descriptor size (ADR 0009)
D3D12_DEPTH_STENCIL_VIEW_DESC dsv_desc{};
dsv_desc.Format = kD16_UNORM_S8_UINT;
dsv_desc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
slot<CreateDsvFn>(dev, kDevCreateDepthStencilView)(dev, depth_texture, &dsv_desc, dsv);
CHECK(true, "CreateDepthStencilView(format 118) returned");
D3D12_SHADER_RESOURCE_VIEW_DESC srv_desc{};
srv_desc.Format = kR16_UNORM_X8_TYPELESS;
srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
srv_desc.Texture2D.MipLevels = 1;
slot<CreateSrvFn>(dev, kDevCreateShaderResourceView)(dev, depth_texture, &srv_desc, views);
CHECK(true, "CreateShaderResourceView(format 119, depth plane) returned");
srv_desc.Format = kX16_TYPELESS_G8_UINT;
srv_desc.Texture2D.PlaneSlice = 1;
slot<CreateSrvFn>(dev, kDevCreateShaderResourceView)(dev, depth_texture, &srv_desc, {views.ptr + kXboxViewSize});
CHECK(true, "CreateShaderResourceView(format 120, stencil plane) returned");
// The documented limit: GetDesc reports the host format of the texture.
D3D12_RESOURCE_DESC reported{};
slot<GetDescFn>(depth_texture, kResGetDesc)(depth_texture, &reported);
CHECK(reported.Format == DXGI_FORMAT_R32G8X24_TYPELESS && reported.Width == 256,
"GetDesc of the format-118 texture reports host format %d (want %d)", static_cast<int>(reported.Format),
static_cast<int>(DXGI_FORMAT_R32G8X24_TYPELESS));
// 3. An unordered-access view on a depth-stencil texture: the descriptor gets a null view and
// the call is logged as unimplemented. A view on an ordinary texture is not affected.
void* depth_uav_texture = nullptr;
const D3D12_RESOURCE_DESC depth_uav =
texture(DXGI_FORMAT_R32G8X24_TYPELESS, depth | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &heap, D3D12_HEAP_FLAG_NONE, &depth_uav,
D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr,
__uuidof(ID3D12Resource), &depth_uav_texture);
D3D12_UNORDERED_ACCESS_VIEW_DESC uav_desc{};
uav_desc.Format = DXGI_FORMAT_R32_FLOAT;
uav_desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
bool depth_uav_exercised = false;
if (hr == S_OK && depth_uav_texture) {
slot<CreateUavFn>(dev, kDevCreateUnorderedAccessView)(dev, depth_uav_texture, nullptr, &uav_desc,
{views.ptr + 2 * kXboxViewSize});
CHECK(true, "CreateUnorderedAccessView(R32_FLOAT on a depth-stencil texture) returned");
depth_uav_exercised = true;
} else {
// A host that refuses the resource itself cannot reach the view; say so instead of passing silently.
std::printf("note: host refused a depth-stencil texture with unordered access (hr=0x%08lx); the view check did not run\n",
static_cast<unsigned long>(hr));
}
void* colour_texture = nullptr;
const D3D12_RESOURCE_DESC colour_uav = texture(DXGI_FORMAT_R32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &heap, D3D12_HEAP_FLAG_NONE, &colour_uav,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr,
__uuidof(ID3D12Resource), &colour_texture);
CHECK(hr == S_OK && colour_texture, "CreateCommittedResource(R32_FLOAT, unordered access) hr=0x%08lx",
static_cast<unsigned long>(hr));
if (colour_texture) {
slot<CreateUavFn>(dev, kDevCreateUnorderedAccessView)(dev, colour_texture, nullptr, &uav_desc,
{views.ptr + 3 * kXboxViewSize});
}
const std::string log = read_log();
if (!log.empty()) {
const size_t stubs = count_of(log, "CreateUnorderedAccessView(depth-stencil resource)") - stubs_before;
CHECK(stubs == (depth_uav_exercised ? 1u : 0u),
"the depth-stencil view is logged as unimplemented once and the ordinary view is not (logged %zu time(s))", stubs);
CHECK(log.find("console-only format 118") != std::string::npos, "the first translation of format 118 is logged");
} else {
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
}
if (colour_texture) slot<ReleaseFn>(colour_texture, kRelease)(colour_texture);
if (depth_uav_texture) slot<ReleaseFn>(depth_uav_texture, kRelease)(depth_uav_texture);
slot<ReleaseFn>(view_heap, kRelease)(view_heap);
slot<ReleaseFn>(dsv_heap, kRelease)(dsv_heap);
slot<ReleaseFn>(depth_texture, kRelease)(depth_texture);
slot<ReleaseFn>(dev, kRelease)(dev);
std::printf("%s: test_d3d12_console_formats (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS", g_checks - g_failed,
g_checks);
return g_failed ? 1 : 0;
}
@@ -0,0 +1,3 @@
add_executable(test_d3d12_rect_list main.cpp)
target_compile_definitions(test_d3d12_rect_list PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_rect_list PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,437 @@
/*
* Conformance test: console rectangle lists.
*
* Contract (Xbox Series GDK d3d12_xs.h): D3D_PRIMITIVE_TOPOLOGY_RECTLIST = 17 is an Xbox
* extension that takes three vertices per rectangle, and a pipeline that draws it has topology
* type D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT = 19. The fourth corner is v0 + v2 - v1, and
* attributes are extended the same way (the convention of rectangle lists since Direct3D 9 on
* Xbox; recorded here as the contract the shim implements).
*
* PC Direct3D 12 has neither value. The test renders into a 128x128 target through an
* Xbox-layout device and reads the pixels back:
* - top-left quadrant: one rectangle with three differently coloured vertices. Every pixel must
* be covered (a single triangle covers half), and the corner that has no vertex of its own
* must show v0 + v2 - v1;
* - bottom-left quadrant: two rectangles in one draw that starts at a non-zero first vertex;
* - top-right quadrant: an ordinary triangle list afterwards, which must still work;
* - bottom-right quadrant: nothing drawn, including by an indexed rectangle-list draw, which
* is not emulated and must be logged as unimplemented.
*
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
* 10 CreateGraphicsPipelineState, 14 CreateDescriptorHeap, 16 CreateRootSignature,
* 20 CreateRenderTargetView, 27 CreateCommittedResource, 36 CreateFence, 48 CreateCommandQueueX,
* 73 CreateCommandListX; resource 8 Map, 11 GetGPUVirtualAddress; descriptor heap 9
* GetCPUDescriptorHandleForHeapStart; command list 9 Close, 12 DrawInstanced,
* 13 DrawIndexedInstanced, 16 CopyTextureRegion, 20 IASetPrimitiveTopology, 21 RSSetViewports,
* 22 RSSetScissorRects, 25 SetPipelineState, 26 ResourceBarrier, 34 SetGraphicsRootSignature,
* 48 IASetVertexBuffers, 50 OMSetRenderTargets, 52 ClearRenderTargetView; queue 10
* ExecuteCommandLists, 16 Signal; fence 9 SetEventOnCompletion.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2;
constexpr int kDevCreateCommandAllocator = 9, kDevCreateGraphicsPipelineState = 10, kDevCreateDescriptorHeap = 14;
constexpr int kDevCreateRootSignature = 16, kDevCreateRenderTargetView = 20, kDevCreateCommittedResource = 27;
constexpr int kDevCreateFence = 36, kDevCreateCommandQueueX = 48, kDevCreateCommandListX = 73;
constexpr int kResMap = 8, kResGetGpuVirtualAddress = 11, kHeapGetCpuStart = 9;
constexpr int kListClose = 9, kListDrawInstanced = 12, kListDrawIndexedInstanced = 13, kListCopyTextureRegion = 16;
constexpr int kListIASetPrimitiveTopology = 20, kListRSSetViewports = 21, kListRSSetScissorRects = 22;
constexpr int kListSetPipelineState = 25, kListResourceBarrier = 26, kListSetGraphicsRootSignature = 34;
constexpr int kListIASetVertexBuffers = 48, kListOMSetRenderTargets = 50, kListClearRenderTargetView = 52;
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
constexpr auto kRectList = static_cast<D3D12_PRIMITIVE_TOPOLOGY>(17); // D3D_PRIMITIVE_TOPOLOGY_RECTLIST
constexpr auto kTopologyTypeRect = static_cast<D3D12_PRIMITIVE_TOPOLOGY_TYPE>(19); // D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT
constexpr UINT kSize = 128;
int g_checks = 0;
int g_failed = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_rect_list:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
struct QueueDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, EngineOrPipeIndex, QueueIndex;
};
struct ListDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, NodeMask, ResourceBarrierBatchSize;
};
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, REFIID, void**);
using CreateFenceFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, D3D12_FENCE_FLAGS, REFIID, void**);
using CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_DESCRIPTOR_HEAP_DESC*, REFIID, void**);
using HeapStartFn = D3D12_CPU_DESCRIPTOR_HANDLE(STDMETHODCALLTYPE*)(void*);
using CreateRootFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const void*, SIZE_T, REFIID, void**);
using CreateRtvFn = void(STDMETHODCALLTYPE*)(void*, void*, const D3D12_RENDER_TARGET_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
using CreatePsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_GRAPHICS_PIPELINE_STATE_DESC*, REFIID, void**);
using MapFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*, void**);
using GetGpuVaFn = D3D12_GPU_VIRTUAL_ADDRESS(STDMETHODCALLTYPE*)(void*);
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
using DrawFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, UINT, UINT);
using DrawIndexedFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, UINT, INT, UINT);
using CopyTextureFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_TEXTURE_COPY_LOCATION*, UINT, UINT, UINT,
const D3D12_TEXTURE_COPY_LOCATION*, const D3D12_BOX*);
using TopologyFn = void(STDMETHODCALLTYPE*)(void*, D3D12_PRIMITIVE_TOPOLOGY);
using ViewportsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_VIEWPORT*);
using ScissorsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RECT*);
using SetObjectFn = void(STDMETHODCALLTYPE*)(void*, void*);
using BarrierFn = UINT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RESOURCE_BARRIER*);
using SetVbFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_VERTEX_BUFFER_VIEW*);
using SetTargetsFn = void(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL,
const D3D12_CPU_DESCRIPTOR_HANDLE*);
using ClearFn = void(STDMETHODCALLTYPE*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, const FLOAT*, UINT, const D3D12_RECT*);
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
using D3DCompileFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, LPCSTR, const void*, void*, LPCSTR, LPCSTR, UINT, UINT, ID3DBlob**,
ID3DBlob**);
using SerializeRootFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
const char kShader[] =
"struct V { float4 pos : SV_Position; float4 col : COLOR; };\n"
"V vs(float2 p : POSITION, float4 c : COLOR) { V o; o.pos = float4(p, 0.0f, 1.0f); o.col = c; return o; }\n"
"float4 ps(V i) : SV_Target0 { return i.col; }\n";
ID3DBlob* compile(const char* entry, const char* target) {
HMODULE compiler = LoadLibraryA("d3dcompiler_47.dll");
auto fn = compiler ? reinterpret_cast<D3DCompileFn>(reinterpret_cast<void*>(GetProcAddress(compiler, "D3DCompile"))) : nullptr;
if (!fn) return nullptr;
ID3DBlob* code = nullptr;
ID3DBlob* errors = nullptr;
const HRESULT hr = fn(kShader, sizeof(kShader) - 1, "rect_list", nullptr, nullptr, entry, target, 0, 0, &code, &errors);
if (FAILED(hr) && errors) std::fprintf(stderr, "D3DCompile(%s): %s\n", entry, static_cast<const char*>(errors->GetBufferPointer()));
if (errors) errors->Release();
return SUCCEEDED(hr) ? code : nullptr;
}
struct Vertex {
float x, y;
float r, g, b, a;
};
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* f = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
std::fclose(f);
}
return text;
}
size_t count_of(const std::string& text, const char* needle) {
size_t n = 0;
for (size_t pos = text.find(needle); pos != std::string::npos; pos = text.find(needle, pos + 1)) ++n;
return n;
}
struct Pixel {
int r, g, b;
};
const uint8_t* g_pixels = nullptr;
constexpr UINT kRowPitch = kSize * 4; // 512: a multiple of the 256-byte texture data pitch alignment
Pixel at(UINT x, UINT y) {
const uint8_t* p = g_pixels + static_cast<size_t>(y) * kRowPitch + static_cast<size_t>(x) * 4;
return {p[0], p[1], p[2]};
}
bool is_clear(Pixel p) { return p.r < 40 && p.g > 215 && p.b < 40; } // the clear colour is green
/* Pixels of the half-open quadrant [x0, x0+64) x [y0, y0+64) that still show the clear colour. */
unsigned clear_pixels(UINT x0, UINT y0) {
unsigned n = 0;
for (UINT y = y0; y < y0 + kSize / 2; ++y) {
for (UINT x = x0; x < x0 + kSize / 2; ++x) n += is_clear(at(x, y)) ? 1 : 0;
}
return n;
}
} // namespace
int main() {
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_rect_list: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
return 77;
}
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
if (!dev) return 1;
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
auto serialize = d3d12 ? reinterpret_cast<SerializeRootFn>(
reinterpret_cast<void*>(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")))
: nullptr;
ID3DBlob* vs = compile("vs", "vs_5_0");
ID3DBlob* ps = compile("ps", "ps_5_0");
if (!serialize || !vs || !ps) {
std::printf("SKIP: test_d3d12_rect_list: no shader compiler or root-signature serializer in this bottle\n");
return 77;
}
// Queue, allocator, list, fence.
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
void* queue = nullptr;
void* allocator = nullptr;
void* list = nullptr;
void* fence = nullptr;
slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue);
slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
&allocator);
slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList), &list);
slot<CreateFenceFn>(dev, kDevCreateFence)(dev, 0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &fence);
// Root signature (input assembler only) and the pipeline, created with the console's
// rectangle topology type.
D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{};
root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0;
root_desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
ID3DBlob* root_blob = nullptr;
hr = serialize(&root_desc, &root_blob, nullptr);
void* root = nullptr;
if (SUCCEEDED(hr) && root_blob) {
hr = slot<CreateRootFn>(dev, kDevCreateRootSignature)(dev, 0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(),
__uuidof(ID3D12RootSignature), &root);
}
CHECK(hr == S_OK && root, "CreateRootSignature hr=0x%08lx", static_cast<unsigned long>(hr));
const D3D12_INPUT_ELEMENT_DESC elements[] = {
{"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 8, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
};
auto pipeline_desc = [&](D3D12_PRIMITIVE_TOPOLOGY_TYPE type) {
D3D12_GRAPHICS_PIPELINE_STATE_DESC d{};
d.pRootSignature = static_cast<ID3D12RootSignature*>(root);
d.VS = {vs->GetBufferPointer(), vs->GetBufferSize()};
d.PS = {ps->GetBufferPointer(), ps->GetBufferSize()};
d.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
d.SampleMask = UINT_MAX;
d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
d.RasterizerState.DepthClipEnable = TRUE;
d.InputLayout = {elements, 2};
d.PrimitiveTopologyType = type;
d.NumRenderTargets = 1;
d.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
d.SampleDesc.Count = 1;
return d;
};
void* rect_pipeline = nullptr;
void* triangle_pipeline = nullptr;
D3D12_GRAPHICS_PIPELINE_STATE_DESC pd = pipeline_desc(kTopologyTypeRect);
hr = slot<CreatePsoFn>(dev, kDevCreateGraphicsPipelineState)(dev, &pd, __uuidof(ID3D12PipelineState), &rect_pipeline);
CHECK(hr == S_OK && rect_pipeline, "CreateGraphicsPipelineState(topology type RECT) hr=0x%08lx", static_cast<unsigned long>(hr));
pd = pipeline_desc(D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE);
hr = slot<CreatePsoFn>(dev, kDevCreateGraphicsPipelineState)(dev, &pd, __uuidof(ID3D12PipelineState), &triangle_pipeline);
CHECK(hr == S_OK && triangle_pipeline, "CreateGraphicsPipelineState(TRIANGLE) hr=0x%08lx", static_cast<unsigned long>(hr));
// Render target, its view, the readback buffer and the vertex buffer.
D3D12_HEAP_PROPERTIES default_heap{}, upload_heap{}, readback_heap{};
default_heap.Type = D3D12_HEAP_TYPE_DEFAULT;
upload_heap.Type = D3D12_HEAP_TYPE_UPLOAD;
readback_heap.Type = D3D12_HEAP_TYPE_READBACK;
D3D12_RESOURCE_DESC target_desc{};
target_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
target_desc.Width = kSize;
target_desc.Height = kSize;
target_desc.DepthOrArraySize = 1;
target_desc.MipLevels = 1;
target_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
target_desc.SampleDesc.Count = 1;
target_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
D3D12_RESOURCE_DESC buffer_desc{};
buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffer_desc.Height = 1;
buffer_desc.DepthOrArraySize = 1;
buffer_desc.MipLevels = 1;
buffer_desc.SampleDesc.Count = 1;
buffer_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
void* target = nullptr;
void* readback = nullptr;
void* vertices = nullptr;
auto committed = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource);
hr = committed(dev, &default_heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
__uuidof(ID3D12Resource), &target);
CHECK(hr == S_OK && target, "render target hr=0x%08lx", static_cast<unsigned long>(hr));
buffer_desc.Width = static_cast<UINT64>(kRowPitch) * kSize;
hr = committed(dev, &readback_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
__uuidof(ID3D12Resource), &readback);
CHECK(hr == S_OK && readback, "readback buffer hr=0x%08lx", static_cast<unsigned long>(hr));
buffer_desc.Width = 64 * 1024;
hr = committed(dev, &upload_heap, D3D12_HEAP_FLAG_NONE, &buffer_desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
__uuidof(ID3D12Resource), &vertices);
CHECK(hr == S_OK && vertices, "vertex buffer hr=0x%08lx", static_cast<unsigned long>(hr));
D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
heap_desc.NumDescriptors = 1;
void* rtv_heap = nullptr;
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &heap_desc, __uuidof(ID3D12DescriptorHeap), &rtv_heap);
CHECK(hr == S_OK && rtv_heap, "RTV heap hr=0x%08lx", static_cast<unsigned long>(hr));
if (!queue || !allocator || !list || !fence || !root || !rect_pipeline || !triangle_pipeline || !target || !readback ||
!vertices || !rtv_heap) {
std::fprintf(stderr, "FAIL: test_d3d12_rect_list: setup\n");
return 1;
}
const D3D12_CPU_DESCRIPTOR_HANDLE rtv = slot<HeapStartFn>(rtv_heap, kHeapGetCpuStart)(rtv_heap);
slot<CreateRtvFn>(dev, kDevCreateRenderTargetView)(dev, target, nullptr, rtv);
const float R[4] = {1, 0, 0, 1}, K[4] = {0, 0, 0, 1}, B[4] = {0, 0, 1, 1}, W[4] = {1, 1, 1, 1}, Y[4] = {1, 1, 0, 1};
auto v = [](float x, float y, const float* c) { return Vertex{x, y, c[0], c[1], c[2], c[3]}; };
const Vertex data[] = {
// 0..2: one rectangle over the top-left quadrant; the corner (0, 1) has no vertex.
v(-1, 1, R), v(-1, 0, K), v(0, 0, B),
// 3..8: two rectangles that together cover the bottom-left quadrant.
v(-1, 0, W), v(-1, -1, W), v(-0.5f, -1, W),
v(-0.5f, 0, W), v(-0.5f, -1, W), v(0, -1, W),
// 9..11: a triangle inside the top-right quadrant, drawn as a triangle list.
v(0.1f, 0.9f, Y), v(0.9f, 0.9f, Y), v(0.1f, 0.1f, Y),
};
void* mapped = nullptr;
hr = slot<MapFn>(vertices, kResMap)(vertices, 0, nullptr, &mapped);
CHECK(hr == S_OK && mapped, "vertex buffer Map hr=0x%08lx", static_cast<unsigned long>(hr));
if (!mapped) return 1;
std::memcpy(mapped, data, sizeof(data));
const D3D12_VERTEX_BUFFER_VIEW vbv{slot<GetGpuVaFn>(vertices, kResGetGpuVirtualAddress)(vertices), sizeof(data), sizeof(Vertex)};
const std::string before = read_log();
const size_t stubs_before = count_of(before, "DrawIndexedInstanced(rectangle list)");
// Record.
const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(kSize), static_cast<float>(kSize), 0, 1};
const D3D12_RECT scissor{0, 0, static_cast<LONG>(kSize), static_cast<LONG>(kSize)};
const FLOAT green[4] = {0, 1, 0, 1};
slot<SetObjectFn>(list, kListSetGraphicsRootSignature)(list, root);
slot<SetTargetsFn>(list, kListOMSetRenderTargets)(list, 1, &rtv, FALSE, nullptr);
slot<ViewportsFn>(list, kListRSSetViewports)(list, 1, &viewport);
slot<ScissorsFn>(list, kListRSSetScissorRects)(list, 1, &scissor);
slot<ClearFn>(list, kListClearRenderTargetView)(list, rtv, green, 0, nullptr);
slot<SetVbFn>(list, kListIASetVertexBuffers)(list, 0, 1, &vbv);
slot<SetObjectFn>(list, kListSetPipelineState)(list, rect_pipeline);
slot<TopologyFn>(list, kListIASetPrimitiveTopology)(list, kRectList);
slot<DrawFn>(list, kListDrawInstanced)(list, 3, 1, 0, 0); // one rectangle
slot<DrawFn>(list, kListDrawInstanced)(list, 6, 1, 3, 0); // two rectangles from vertex 3
slot<DrawIndexedFn>(list, kListDrawIndexedInstanced)(list, 3, 1, 0, 0, 0); // not emulated: logged, draws nothing
slot<SetObjectFn>(list, kListSetPipelineState)(list, triangle_pipeline);
slot<TopologyFn>(list, kListIASetPrimitiveTopology)(list, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
slot<DrawFn>(list, kListDrawInstanced)(list, 3, 1, 9, 0); // an ordinary triangle afterwards
D3D12_RESOURCE_BARRIER to_copy{};
to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
to_copy.Transition.pResource = static_cast<ID3D12Resource*>(target);
to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
slot<BarrierFn>(list, kListResourceBarrier)(list, 1, &to_copy);
D3D12_TEXTURE_COPY_LOCATION dst{};
dst.pResource = static_cast<ID3D12Resource*>(readback);
dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, kRowPitch};
D3D12_TEXTURE_COPY_LOCATION src{};
src.pResource = static_cast<ID3D12Resource*>(target);
src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
slot<CopyTextureFn>(list, kListCopyTextureRegion)(list, &dst, 0, 0, 0, &src, nullptr);
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close");
void* lists[] = {list};
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, lists);
CHECK(slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, 1) == S_OK, "queue Signal");
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
CHECK(slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, 1, done) == S_OK, "fence event");
CHECK(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0, "GPU work completes");
CloseHandle(done);
void* result = nullptr;
hr = slot<MapFn>(readback, kResMap)(readback, 0, nullptr, &result);
CHECK(hr == S_OK && result, "readback Map hr=0x%08lx", static_cast<unsigned long>(hr));
if (!result) return 1;
g_pixels = static_cast<const uint8_t*>(result);
// Control: the clear reached the target and the untouched quadrant kept it.
const unsigned half = kSize / 2, quadrant = half * half;
CHECK(clear_pixels(half, half) == quadrant, "bottom-right quadrant: %u of %u pixels show the clear colour", clear_pixels(half, half),
quadrant);
// Top-left: the whole rectangle is covered, and the fourth corner is v0 + v2 - v1.
CHECK(clear_pixels(0, 0) == 0, "top-left rectangle: %u pixel(s) are not covered (a single triangle leaves about %u)",
clear_pixels(0, 0), quadrant / 2);
Pixel p = at(2, 2);
CHECK(p.r > 200 && p.g < 40 && p.b < 40, "corner v0 is red: (%d, %d, %d)", p.r, p.g, p.b);
p = at(2, half - 3);
CHECK(p.r < 40 && p.g < 40 && p.b < 40, "corner v1 is black: (%d, %d, %d)", p.r, p.g, p.b);
p = at(half - 3, half - 3);
CHECK(p.r < 40 && p.g < 40 && p.b > 200, "corner v2 is blue: (%d, %d, %d)", p.r, p.g, p.b);
p = at(half - 3, 2);
CHECK(p.r > 200 && p.g < 40 && p.b > 200, "the fourth corner is v0 + v2 - v1 = magenta: (%d, %d, %d)", p.r, p.g, p.b);
// Bottom-left: two rectangles from a non-zero first vertex cover the quadrant in white.
CHECK(clear_pixels(0, half) == 0, "bottom-left (two rectangles in one draw): %u pixel(s) are not covered", clear_pixels(0, half));
p = at(half - 3, half + 3);
CHECK(p.r > 215 && p.g > 215 && p.b > 215, "second rectangle's fourth corner is white: (%d, %d, %d)", p.r, p.g, p.b);
// Top-right: the triangle list afterwards draws a triangle, and only a triangle.
p = at(half + 13, 13); // near (0.2, 0.8): inside
CHECK(p.r > 215 && p.g > 215 && p.b < 40, "the triangle drawn afterwards is yellow inside: (%d, %d, %d)", p.r, p.g, p.b);
p = at(kSize - 8, half - 8); // near (0.88, 0.12): outside the triangle
CHECK(is_clear(p), "the triangle list is not turned into a rectangle: (%d, %d, %d)", p.r, p.g, p.b);
const std::string after = read_log();
if (!after.empty()) {
CHECK(count_of(after, "DrawIndexedInstanced(rectangle list)") - stubs_before == 1,
"the indexed rectangle-list draw is logged as unimplemented once (logged %zu time(s))",
count_of(after, "DrawIndexedInstanced(rectangle list)") - stubs_before);
} else {
std::printf("note: no BX_LOG_FILE; the log check did not run\n");
}
for (void* object : {rtv_heap, vertices, readback, target, triangle_pipeline, rect_pipeline, root, fence, list, allocator, queue,
dev}) {
slot<ReleaseFn>(object, kRelease)(object);
}
std::printf("%s: test_d3d12_rect_list (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS", g_checks - g_failed, g_checks);
return g_failed ? 1 : 0;
}
@@ -0,0 +1,3 @@
add_executable(test_d3d12_serialized_pipelines main.cpp)
target_compile_definitions(test_d3d12_serialized_pipelines PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_serialized_pipelines PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,198 @@
/*
* Conformance test for #669: serialized and derived Xbox pipeline-state calls must fail with
* E_NOTIMPL and log `pipeline_refused` even when BX_NULL_RENDER=1 is active, so a title falls
* back to creating pipelines from shader containers instead of silently receiving null pipelines.
*
* Slot numbers follow the Xbox Series ID3D12Device vtable layout (ADR 0009):
* 2 = Release
* 11 = CreateComputePipelineState
* 55 = CreateDerivedGraphicsPipelineStateX
* 57 = DeserializeGraphicsPipelineStateX
* 63 = CreateDerivedComputePipelineStateX
* 67 = DeserializeComputePipelineStateX
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2;
constexpr int kDevCreateComputePipelineState = 11;
constexpr int kDevCreateDerivedGraphicsPipelineStateX = 55;
constexpr int kDevDeserializeGraphicsPipelineStateX = 57;
constexpr int kDevCreateDerivedComputePipelineStateX = 63;
constexpr int kDevDeserializeComputePipelineStateX = 67;
int g_checks = 0;
int g_failed = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_serialized_pipelines:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using CreateComputePsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, REFIID, void**);
using DeserializePsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, const void*, REFIID, void**);
using CreateDerivedPsoFn = HRESULT(STDMETHODCALLTYPE*)(void*, ID3D12PipelineState*, UINT, const void*, REFIID, void**);
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* f = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
std::fclose(f);
}
return text;
}
bool log_has_refusal_without_null(const std::string& log, const char* kind) {
size_t pos = 0;
while (pos < log.size()) {
size_t end = log.find('\n', pos);
if (end == std::string::npos) end = log.size();
const std::string line = log.substr(pos, end - pos);
if (line.find("\"event\":\"pipeline_refused\"") != std::string::npos && line.find(kind) != std::string::npos) {
return line.find("null pipeline returned") == std::string::npos;
}
pos = end + 1;
}
return false;
}
} // namespace
int main() {
// Enable null-render mode before any pipeline call so d3d12_xs caches BX_NULL_RENDER=1.
SetEnvironmentVariableA("BX_NULL_RENDER", "1");
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_serialized_pipelines: host lacks Xbox-layout device interface (E_NOINTERFACE)\n");
return 77;
}
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
if (!dev) return 1;
// 1. Control check: a refused shader-container pipeline still becomes a null pipeline when
// BX_NULL_RENDER=1, confirming null-render mode is active.
static const uint8_t kBogusShader[16] = {0x44, 0x58, 0x42, 0x43};
D3D12_COMPUTE_PIPELINE_STATE_DESC compute_desc{};
compute_desc.CS.pShaderBytecode = kBogusShader;
compute_desc.CS.BytecodeLength = sizeof(kBogusShader);
void* null_pso = nullptr;
hr = slot<CreateComputePsoFn>(dev, kDevCreateComputePipelineState)(
dev, &compute_desc, __uuidof(ID3D12PipelineState), &null_pso);
CHECK(hr == S_OK && null_pso != nullptr,
"control: refused CreateComputePipelineState returns null pipeline in BX_NULL_RENDER=1 (hr=0x%08lx)",
static_cast<unsigned long>(hr));
// 2. Serialized pipeline calls must fail with E_NOTIMPL and clear *ppv even with BX_NULL_RENDER=1.
auto* sentinel = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
void* out = sentinel;
hr = slot<DeserializePsoFn>(dev, kDevDeserializeGraphicsPipelineStateX)(
dev, nullptr, __uuidof(ID3D12PipelineState), &out);
CHECK(hr == E_NOTIMPL && out == nullptr,
"DeserializeGraphicsPipelineStateX must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
static_cast<unsigned long>(hr), out);
hr = slot<DeserializePsoFn>(dev, kDevDeserializeGraphicsPipelineStateX)(
dev, nullptr, __uuidof(ID3D12PipelineState), nullptr);
CHECK(hr == E_POINTER, "DeserializeGraphicsPipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
static_cast<unsigned long>(hr));
out = sentinel;
hr = slot<DeserializePsoFn>(dev, kDevDeserializeComputePipelineStateX)(
dev, nullptr, __uuidof(ID3D12PipelineState), &out);
CHECK(hr == E_NOTIMPL && out == nullptr,
"DeserializeComputePipelineStateX must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
static_cast<unsigned long>(hr), out);
hr = slot<DeserializePsoFn>(dev, kDevDeserializeComputePipelineStateX)(
dev, nullptr, __uuidof(ID3D12PipelineState), nullptr);
CHECK(hr == E_POINTER, "DeserializeComputePipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
static_cast<unsigned long>(hr));
// 3. Derived pipeline calls must also fail with E_NOTIMPL and clear *ppv (both from a null
// pipeline source and from a nullptr source) even with BX_NULL_RENDER=1.
auto* null_src = static_cast<ID3D12PipelineState*>(null_pso);
out = sentinel;
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedGraphicsPipelineStateX)(
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
CHECK(hr == E_NOTIMPL && out == nullptr,
"CreateDerivedGraphicsPipelineStateX(null source) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
static_cast<unsigned long>(hr), out);
out = sentinel;
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedGraphicsPipelineStateX)(
dev, nullptr, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
CHECK(hr == E_NOTIMPL && out == nullptr,
"CreateDerivedGraphicsPipelineStateX(nullptr) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
static_cast<unsigned long>(hr), out);
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedGraphicsPipelineStateX)(
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), nullptr);
CHECK(hr == E_POINTER, "CreateDerivedGraphicsPipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
static_cast<unsigned long>(hr));
out = sentinel;
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedComputePipelineStateX)(
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
CHECK(hr == E_NOTIMPL && out == nullptr,
"CreateDerivedComputePipelineStateX(null source) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
static_cast<unsigned long>(hr), out);
out = sentinel;
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedComputePipelineStateX)(
dev, nullptr, 0, nullptr, __uuidof(ID3D12PipelineState), &out);
CHECK(hr == E_NOTIMPL && out == nullptr,
"CreateDerivedComputePipelineStateX(nullptr) must fail with E_NOTIMPL and null out (hr=0x%08lx, out=%p)",
static_cast<unsigned long>(hr), out);
hr = slot<CreateDerivedPsoFn>(dev, kDevCreateDerivedComputePipelineStateX)(
dev, null_src, 0, nullptr, __uuidof(ID3D12PipelineState), nullptr);
CHECK(hr == E_POINTER, "CreateDerivedComputePipelineStateX(ppv=nullptr) must return E_POINTER (hr=0x%08lx)",
static_cast<unsigned long>(hr));
// 4. When BX_LOG_FILE is active, verify each refusal was logged without "null pipeline returned".
const std::string log = read_log();
if (!log.empty()) {
CHECK(log_has_refusal_without_null(log, "deserialized graphics (console code)"),
"log must record deserialized graphics refusal without null pipeline");
CHECK(log_has_refusal_without_null(log, "deserialized compute (console code)"),
"log must record deserialized compute refusal without null pipeline");
CHECK(log_has_refusal_without_null(log, "derived graphics"),
"log must record derived graphics refusal without null pipeline");
CHECK(log_has_refusal_without_null(log, "derived compute"),
"log must record derived compute refusal without null pipeline");
}
if (null_pso) slot<ReleaseFn>(null_pso, kRelease)(null_pso);
slot<ReleaseFn>(dev, kRelease)(dev);
std::printf("%s: test_d3d12_serialized_pipelines (%d of %d checks passed)\n",
g_failed ? "FAIL" : "PASS", g_checks - g_failed, g_checks);
return g_failed ? 1 : 0;
}
@@ -0,0 +1,3 @@
add_executable(test_d3d12_unbacked_buffers main.cpp)
target_compile_definitions(test_d3d12_unbacked_buffers PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_unbacked_buffers PRIVATE d3d12_xs kernel32 uuid)
@@ -0,0 +1,206 @@
/*
* Conformance test: index and vertex bindings at a title address that has no host buffer behind it
* must not reach the host Direct3D 12 implementation.
*
* Contract: on the console a GPU virtual address is the title's own address, so a title binds
* index and vertex data that lives in plain title memory, with no Direct3D resource created for
* it (observed in a project-authorized target build: a 384 KiB index buffer and a 1.1 MiB vertex
* buffer bound this way every frame). BetterXen has a host buffer only for memory it created a
* resource for. Passed through unchanged, such an address is not a host address, and D3DMetal
* dereferences the buffer it fails to find: the process dies with a null read inside
* IASetIndexBuffer. Without the fix the failure mode of this test is that crash.
*
* With the fix the binding is left empty (Direct3D 12 defines a null binding) and the call is
* logged as unimplemented. A binding at an address inside a resource BetterXen created is still
* translated and is not logged.
*
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
* 27 CreateCommittedResource, 48 CreateCommandQueueX, 73 CreateCommandListX; resource 11
* GetGPUVirtualAddress; graphics command list 9 Close, 47 IASetIndexBuffer, 48 IASetVertexBuffers.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
namespace {
constexpr int kRelease = 2;
constexpr int kDevCreateCommandAllocator = 9, kDevCreateCommittedResource = 27, kDevCreateCommandQueueX = 48;
constexpr int kDevCreateCommandListX = 73;
constexpr int kResGetGpuVirtualAddress = 11;
constexpr int kListClose = 9, kListIASetIndexBuffer = 47, kListIASetVertexBuffers = 48;
int g_checks = 0;
int g_failed = 0;
#define CHECK(cond, ...) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_unbacked_buffers:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
struct QueueDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, EngineOrPipeIndex, QueueIndex;
};
struct ListDescX {
D3D12_COMMAND_LIST_TYPE Type;
UINT Flags, NodeMask, ResourceBarrierBatchSize;
};
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, REFIID, void**);
using GetGpuVaFn = D3D12_GPU_VIRTUAL_ADDRESS(STDMETHODCALLTYPE*)(void*);
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
using SetIndexFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_INDEX_BUFFER_VIEW*);
using SetVertexFn = void(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_VERTEX_BUFFER_VIEW*);
std::string read_log() {
char path[MAX_PATH];
const DWORD n = GetEnvironmentVariableA("BX_LOG_FILE", path, sizeof(path));
if (n == 0 || n >= sizeof(path)) return {};
std::string text;
if (FILE* f = std::fopen(path, "rb")) {
char buffer[4096];
size_t got;
while ((got = std::fread(buffer, 1, sizeof(buffer), f)) > 0) text.append(buffer, got);
std::fclose(f);
}
return text;
}
size_t count_of(const std::string& text, const char* needle) {
size_t n = 0;
for (size_t pos = text.find(needle); pos != std::string::npos; pos = text.find(needle, pos + 1)) ++n;
return n;
}
constexpr const char* kIndexStub = "IASetIndexBuffer(title memory without a host buffer)";
constexpr const char* kVertexStub = "IASetVertexBuffers(title memory without a host buffer)";
} // namespace
int main() {
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_unbacked_buffers: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
return 77;
}
CHECK(hr == S_OK && dev != nullptr, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
if (!dev) return 1;
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
void* queue = nullptr;
void* allocator = nullptr;
void* list = nullptr;
CHECK(slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue) == S_OK,
"CreateCommandQueueX");
CHECK(slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT,
__uuidof(ID3D12CommandAllocator), &allocator) == S_OK,
"CreateCommandAllocator");
hr = slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList),
&list);
CHECK(hr == S_OK && list, "CreateCommandListX hr=0x%08lx", static_cast<unsigned long>(hr));
// A buffer BetterXen created: its GPU address is a title address with a host buffer behind it.
D3D12_HEAP_PROPERTIES upload{};
upload.Type = D3D12_HEAP_TYPE_UPLOAD;
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = 64 * 1024;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
void* backed = nullptr;
hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(dev, &upload, D3D12_HEAP_FLAG_NONE, &desc,
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
__uuidof(ID3D12Resource), &backed);
CHECK(hr == S_OK && backed, "CreateCommittedResource(64 KiB upload buffer) hr=0x%08lx", static_cast<unsigned long>(hr));
// Plain title memory: no Direct3D resource was created for it.
auto* plain = static_cast<unsigned char*>(VirtualAlloc(nullptr, 64 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
CHECK(plain != nullptr, "VirtualAlloc(64 KiB)");
if (!queue || !allocator || !list || !backed || !plain) {
std::fprintf(stderr, "FAIL: test_d3d12_unbacked_buffers: setup\n");
return 1;
}
const D3D12_GPU_VIRTUAL_ADDRESS backed_va = slot<GetGpuVaFn>(backed, kResGetGpuVirtualAddress)(backed);
const auto plain_va = reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(plain);
CHECK(backed_va != 0, "the committed buffer reports a GPU address");
const std::string before = read_log();
const size_t index_before = count_of(before, kIndexStub);
const size_t vertex_before = count_of(before, kVertexStub);
// 1. Bindings inside the buffer BetterXen created: translated, not logged.
const D3D12_INDEX_BUFFER_VIEW backed_index{backed_va + 256, 4096, DXGI_FORMAT_R16_UINT};
slot<SetIndexFn>(list, kListIASetIndexBuffer)(list, &backed_index);
const D3D12_VERTEX_BUFFER_VIEW backed_vertex{backed_va + 8192, 4096, 16};
slot<SetVertexFn>(list, kListIASetVertexBuffers)(list, 0, 1, &backed_vertex);
CHECK(true, "bindings inside a created buffer returned");
// 2. Bindings in plain title memory: the process must survive them.
const D3D12_INDEX_BUFFER_VIEW plain_index{plain_va, 4096, DXGI_FORMAT_R16_UINT};
slot<SetIndexFn>(list, kListIASetIndexBuffer)(list, &plain_index);
CHECK(true, "IASetIndexBuffer at a title address without a host buffer returned");
// Two vertex streams: the first backed, the second not. Only the second is emptied.
const D3D12_VERTEX_BUFFER_VIEW streams[2] = {backed_vertex, {plain_va + 4096, 4096, 16}};
slot<SetVertexFn>(list, kListIASetVertexBuffers)(list, 0, 2, streams);
CHECK(true, "IASetVertexBuffers with one stream in plain title memory returned");
// 3. Null bindings stay null bindings and are not logged.
slot<SetIndexFn>(list, kListIASetIndexBuffer)(list, nullptr);
const D3D12_INDEX_BUFFER_VIEW zero_index{0, 0, DXGI_FORMAT_R16_UINT};
slot<SetIndexFn>(list, kListIASetIndexBuffer)(list, &zero_index);
const D3D12_VERTEX_BUFFER_VIEW zero_vertex{0, 0, 0};
slot<SetVertexFn>(list, kListIASetVertexBuffers)(list, 0, 1, &zero_vertex);
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "the list still closes");
const std::string after = read_log();
if (!after.empty()) {
CHECK(count_of(after, kIndexStub) - index_before == 1,
"exactly the unbacked index binding is logged as unimplemented (logged %zu time(s))",
count_of(after, kIndexStub) - index_before);
CHECK(count_of(after, kVertexStub) - vertex_before == 1,
"exactly the unbacked vertex stream is logged as unimplemented (logged %zu time(s))",
count_of(after, kVertexStub) - vertex_before);
} else {
std::printf("note: no BX_LOG_FILE; the log checks did not run\n");
}
VirtualFree(plain, 0, MEM_RELEASE);
for (void* object : {backed, list, allocator, queue, dev}) slot<ReleaseFn>(object, kRelease)(object);
std::printf("%s: test_d3d12_unbacked_buffers (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS", g_checks - g_failed,
g_checks);
return g_failed ? 1 : 0;
}
@@ -0,0 +1,3 @@
add_executable(test_veh_clzero_loop main.cpp)
target_include_directories(test_veh_clzero_loop PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_link_libraries(test_veh_clzero_loop PRIVATE bx_runtime_veh kernel32)
@@ -0,0 +1,199 @@
// Synthetic Windows x64 fixture for CLZERO loops under the Rosetta exception path (#665).
//
// CLZERO (AMD APM vol. 3, 24594) zeroes the 64-byte cache line that contains the address in RAX
// and changes no register. Rosetta 2 does not run it, so bx_runtime_veh.dll emulates it from the
// illegal-instruction exception. A loop of the form
//
// clzero ; add rax, 0x40 ; cmp rax, <reg64> ; jb <the clzero>
//
// would raise one exception per line. The handler completes such a loop in the first exception.
//
// This fixture runs its own machine-code loops (bytes written here, no title code) and checks:
// * the memory result against the instruction's definition, line by line, with sentinels;
// * the number of illegal-instruction exceptions, counted by a handler of its own that runs
// before BetterXen's: one per loop that matches the form, one per line otherwise;
// * a range that runs into a read-only page: the loop stops there with a write fault at that
// page, and finishes once the page is writable.
// On a host that runs CLZERO natively no exception is raised and the fixture skips (exit 77).
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" uint64_t bx_veh_get_clwb_trap_count(void); // imports bx_runtime_veh.dll, which installs the handler
namespace {
unsigned failures = 0;
unsigned checks = 0;
void expect(bool passed, const char* name) {
++checks;
if (passed) {
std::printf("ok: %s\n", name);
} else {
std::fprintf(stderr, "FAIL: %s\n", name);
++failures;
}
}
volatile LONG g_illegal = 0; // illegal-instruction exceptions seen first-chance
volatile LONG g_write_faults = 0; // write faults that reached the last handler
volatile ULONG_PTR g_fault_address = 0;
void* g_unprotect = nullptr; // page the last handler makes writable when it faults
SIZE_T g_unprotect_size = 0;
// Registered first: sees every illegal instruction before BetterXen's handler emulates it.
LONG CALLBACK count_first(PEXCEPTION_POINTERS ep) {
if (ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) InterlockedIncrement(&g_illegal);
return EXCEPTION_CONTINUE_SEARCH;
}
// Registered last: sees the write fault BetterXen passes on when a line is not writable.
LONG CALLBACK fix_last(PEXCEPTION_POINTERS ep) {
const EXCEPTION_RECORD& r = *ep->ExceptionRecord;
if (r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION || r.NumberParameters < 2 || r.ExceptionInformation[0] != 1) {
return EXCEPTION_CONTINUE_SEARCH;
}
InterlockedIncrement(&g_write_faults);
g_fault_address = r.ExceptionInformation[1];
DWORD old = 0;
if (!g_unprotect || !VirtualProtect(g_unprotect, g_unprotect_size, PAGE_READWRITE, &old)) {
return EXCEPTION_CONTINUE_SEARCH;
}
g_unprotect = nullptr;
return EXCEPTION_CONTINUE_EXECUTION; // the CLZERO runs again
}
using Loop = void (*)(uint8_t* start, uint8_t* limit); // rcx = start, rdx = limit
// mov rax, rcx ; L: clzero ; add rax, 0x40 ; cmp rax, rdx ; jb L ; ret
const uint8_t kLoopRdx[] = {0x48, 0x89, 0xC8, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4, 0xC3};
// mov rax, rcx ; mov r10, rdx ; L: clzero ; add rax, 0x40 ; cmp rax, r10 ; jb L ; ret
const uint8_t kLoopR10[] = {0x48, 0x89, 0xC8, 0x49, 0x89, 0xD2, 0x0F, 0x01, 0xFC, 0x48, 0x83,
0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4, 0xC3};
// The same loop with a NOP before the add, which is not the recognised form:
// mov rax, rcx ; L: clzero ; nop ; add rax, 0x40 ; cmp rax, rdx ; jb L ; ret
const uint8_t kLoopOther[] = {0x48, 0x89, 0xC8, 0x0F, 0x01, 0xFC, 0x90, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF3, 0xC3};
Loop make(const uint8_t* code, size_t size) {
void* page = VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (!page) return nullptr;
std::memcpy(page, code, size);
FlushInstructionCache(GetCurrentProcess(), page, size);
return reinterpret_cast<Loop>(page);
}
constexpr size_t kLine = 64;
// Lines [first, first + count) of `base` are zero and every other line of the `lines`-line buffer
// still holds the fill byte.
bool only_zeroed(const uint8_t* base, size_t lines, size_t first, size_t count) {
for (size_t line = 0; line < lines; ++line) {
const uint8_t want = (line >= first && line < first + count) ? 0x00 : 0xAA;
for (size_t i = 0; i < kLine; ++i) {
if (base[line * kLine + i] != want) return false;
}
}
return true;
}
LONG run(Loop loop, uint8_t* start, uint8_t* limit) {
InterlockedExchange(&g_illegal, 0);
loop(start, limit);
return g_illegal;
}
} // namespace
int main() {
(void)bx_veh_get_clwb_trap_count();
void* first = AddVectoredExceptionHandler(1, count_first);
void* last = AddVectoredExceptionHandler(0, fix_last);
Loop loop_rdx = make(kLoopRdx, sizeof(kLoopRdx));
Loop loop_r10 = make(kLoopR10, sizeof(kLoopR10));
Loop loop_other = make(kLoopOther, sizeof(kLoopOther));
if (!first || !last || !loop_rdx || !loop_r10 || !loop_other) {
std::fprintf(stderr, "FAIL: setup\n");
return 1;
}
// 1,026 lines: a sentinel line, 1,024 lines to work in, a sentinel line.
constexpr size_t kLines = 1026;
auto* buffer = static_cast<uint8_t*>(VirtualAlloc(nullptr, kLines * kLine, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
if (!buffer) {
std::fprintf(stderr, "FAIL: buffer\n");
return 1;
}
uint8_t* work = buffer + kLine;
// One line: the loop body runs once.
std::memset(buffer, 0xAA, kLines * kLine);
LONG illegal = run(loop_rdx, work, work + kLine);
if (illegal == 0) {
std::printf("SKIP: test_veh_clzero_loop: CLZERO raised no exception on this host (it runs natively)\n");
return 77;
}
expect(only_zeroed(buffer, kLines, 1, 1), "one line: exactly that line is zero");
expect(illegal == 1, "one line: one exception");
// 1,000 lines through the recognised form.
std::memset(buffer, 0xAA, kLines * kLine);
illegal = run(loop_rdx, work, work + 1000 * kLine);
expect(only_zeroed(buffer, kLines, 1, 1000), "1000 lines (cmp rax, rdx): exactly those lines are zero");
expect(illegal == 1, "1000 lines (cmp rax, rdx): one exception for the whole loop");
// The limit register is r10.
std::memset(buffer, 0xAA, kLines * kLine);
illegal = run(loop_r10, work, work + 1000 * kLine);
expect(only_zeroed(buffer, kLines, 1, 1000), "1000 lines (cmp rax, r10): exactly those lines are zero");
expect(illegal == 1, "1000 lines (cmp rax, r10): one exception for the whole loop");
// A limit one byte into an eleventh line: the loop runs while rax < limit, so eleven lines.
std::memset(buffer, 0xAA, kLines * kLine);
illegal = run(loop_rdx, work, work + 10 * kLine + 1);
expect(only_zeroed(buffer, kLines, 1, 11), "limit inside a line: that line is zeroed too");
expect(illegal == 1, "limit inside a line: one exception");
// A start 8 bytes into a line: each CLZERO zeroes the whole line containing rax. With the limit
// at the end of the tenth line, rax takes ten values below it.
std::memset(buffer, 0xAA, kLines * kLine);
illegal = run(loop_rdx, work + 8, work + 10 * kLine);
expect(only_zeroed(buffer, kLines, 1, 10), "unaligned start: ten whole lines are zero");
expect(illegal == 1, "unaligned start: one exception");
// A loop that is not the recognised form keeps the per-instruction path: same memory result,
// one exception per line.
std::memset(buffer, 0xAA, kLines * kLine);
illegal = run(loop_other, work, work + 8 * kLine);
expect(only_zeroed(buffer, kLines, 1, 8), "other loop form: exactly eight lines are zero");
expect(illegal == 8, "other loop form: one exception per line");
// A range that runs from a writable page into a read-only one. The lines of the first page are
// zeroed; the first line of the second page faults as a write to that page; once the last
// handler makes it writable the loop finishes.
auto* pages = static_cast<uint8_t*>(VirtualAlloc(nullptr, 2 * 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
if (!pages) {
std::fprintf(stderr, "FAIL: pages\n");
return 1;
}
std::memset(pages, 0xAA, 2 * 4096);
DWORD old = 0;
VirtualProtect(pages + 4096, 4096, PAGE_READONLY, &old);
g_unprotect = pages + 4096;
g_unprotect_size = 4096;
InterlockedExchange(&g_write_faults, 0);
g_fault_address = 0;
illegal = run(loop_rdx, pages + 4096 - 4 * kLine, pages + 4096 + 4 * kLine);
expect(g_write_faults == 1, "read-only page: one write fault is passed on");
expect(g_fault_address == reinterpret_cast<ULONG_PTR>(pages + 4096), "read-only page: the fault names the first line of that page");
expect(only_zeroed(pages, 2 * 4096 / kLine, 4096 / kLine - 4, 8), "read-only page: all eight lines are zero after it is made writable");
// First exception zeroes the four writable lines; the fifth line traps and faults; its retry
// traps again and finishes the range.
expect(illegal == 3, "read-only page: three exceptions (range start, the fault, the retry)");
RemoveVectoredExceptionHandler(last);
RemoveVectoredExceptionHandler(first);
std::printf("%s: test_veh_clzero_loop (%u of %u checks passed)\n", failures ? "FAIL" : "PASS", checks - failures, checks);
return failures ? 1 : 0;
}
+171 -1
View File
@@ -199,6 +199,134 @@ void CALLBACK record_order(void* context, bool canceled) {
else if (slot == 1) record.second = 2;
}
// XAsyncRun and the task-queue handle calls through IXGameRuntimeCore slots 6, 13, 14 and 15
// (#666). Slot numbers follow the declaration order of the public XAsync.h and XTaskQueue.h;
// the expected behaviour is the documented one.
struct RunRecord {
std::atomic<unsigned> work_runs{0};
std::atomic<unsigned> completions{0};
std::atomic<DWORD> work_thread{0};
HRESULT result = S_OK;
};
HRESULT CALLBACK run_work(Async* async) {
auto& record = *static_cast<RunRecord*>(async->context);
record.work_thread = GetCurrentThreadId();
++record.work_runs;
return record.result;
}
void CALLBACK run_completed(Async* async) {
++static_cast<RunRecord*>(async->context)->completions;
}
void check_async_run_and_queue_handles(HRESULT(WINAPI* query_api)(const GUID*, const GUID*, void**)) {
constexpr GUID kCore = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
void* core = nullptr;
CHECK(SUCCEEDED(query_api(&kCore, &kCore, &core)) && core);
auto** vtbl = *static_cast<void***>(core);
auto async_run = reinterpret_cast<HRESULT(WINAPI*)(void*, Async*, HRESULT(CALLBACK*)(Async*))>(vtbl[6]);
auto create_composite = reinterpret_cast<HRESULT(WINAPI*)(void*, void*, void*, void**)>(vtbl[13]);
auto get_port = reinterpret_cast<HRESULT(WINAPI*)(void*, void*, uint32_t, void**)>(vtbl[14]);
auto duplicate = reinterpret_cast<HRESULT(WINAPI*)(void*, void*, void**)>(vtbl[15]);
const DWORD main_thread = GetCurrentThreadId();
// XAsyncRun: the work callback runs on the block's work port, its return value becomes the
// block's status, and the completion callback runs on the completion port.
{
void* queue = nullptr;
CHECK(XTaskQueueCreate(manual, manual, &queue) == S_OK && queue);
RunRecord record{};
Async async{queue, &record, run_completed, {}};
CHECK(async_run(core, &async, run_work) == S_OK);
CHECK(XAsyncGetStatus(&async, false) == E_PENDING && record.work_runs.load() == 0);
CHECK(XTaskQueueDispatch(queue, work, 0));
CHECK(record.work_runs.load() == 1 && record.work_thread.load() == main_thread);
CHECK(record.completions.load() == 0);
CHECK(XTaskQueueDispatch(queue, completion, 0));
CHECK(record.completions.load() == 1 && XAsyncGetStatus(&async, false) == S_OK);
// A failing work callback's HRESULT is the block's status.
RunRecord failing{};
failing.result = E_ACCESSDENIED;
Async failed{queue, &failing, nullptr, {}};
CHECK(async_run(core, &failed, run_work) == S_OK);
CHECK(XTaskQueueDispatch(queue, work, 0));
CHECK(XAsyncGetStatus(&failed, false) == E_ACCESSDENIED);
CHECK(async_run(core, nullptr, run_work) == E_INVALIDARG);
CHECK(async_run(core, &failed, nullptr) == E_INVALIDARG);
XTaskQueueCloseHandle(queue);
}
// XTaskQueueDuplicateHandle: both handles name one queue, and closing one leaves the other
// usable. (Before the fix, closing any handle shut the queue's lanes down.)
{
void* queue = nullptr;
CHECK(XTaskQueueCreate(manual, manual, &queue) == S_OK && queue);
void* copy = nullptr;
CHECK(duplicate(core, queue, &copy) == S_OK && copy && copy != queue);
DelayRecord through_copy{};
CHECK(XTaskQueueSubmitCallback(copy, work, &through_copy, record_delay) == S_OK);
CHECK(XTaskQueueDispatch(queue, work, 0) && through_copy.runs.load() == 1);
XTaskQueueCloseHandle(queue);
DelayRecord after_close{};
CHECK(XTaskQueueSubmitCallback(copy, work, &after_close, record_delay) == S_OK);
CHECK(XTaskQueueDispatch(copy, work, 0) && after_close.runs.load() == 1 && after_close.cancels.load() == 0);
XTaskQueueCloseHandle(copy);
void* refused = reinterpret_cast<void*>(uintptr_t{0x1234});
CHECK(FAILED(duplicate(core, copy, &refused)) && refused == nullptr);
CHECK(duplicate(core, nullptr, nullptr) == E_POINTER);
}
// XTaskQueueGetPort and XTaskQueueCreateComposite: a composite's work port is one queue's
// work port and its completion port is another queue's completion port. A callback sent to
// the composite is dispatched from the queue that owns the port, and the other queue's own
// ports are untouched.
{
void* a = nullptr;
void* b = nullptr;
CHECK(XTaskQueueCreate(manual, manual, &a) == S_OK && a);
CHECK(XTaskQueueCreate(manual, manual, &b) == S_OK && b);
void* a_work = nullptr;
void* b_completion = nullptr;
CHECK(get_port(core, a, static_cast<uint32_t>(work), &a_work) == S_OK && a_work);
CHECK(get_port(core, b, static_cast<uint32_t>(completion), &b_completion) == S_OK && b_completion);
void* no_port = reinterpret_cast<void*>(uintptr_t{0x1234});
CHECK(get_port(core, a, 7, &no_port) == E_INVALIDARG && no_port == nullptr);
void* composite = nullptr;
CHECK(create_composite(core, a_work, b_completion, &composite) == S_OK && composite);
DelayRecord on_work{};
DelayRecord on_completion{};
CHECK(XTaskQueueSubmitCallback(composite, work, &on_work, record_delay) == S_OK);
CHECK(XTaskQueueSubmitCallback(composite, completion, &on_completion, record_delay) == S_OK);
// Not on the other queue's ports.
CHECK(!XTaskQueueDispatch(b, work, 0) && !XTaskQueueDispatch(a, completion, 0));
CHECK(on_work.runs.load() == 0 && on_completion.runs.load() == 0);
// On the ports the composite was made from, through either handle.
CHECK(XTaskQueueDispatch(a, work, 0) && on_work.runs.load() == 1);
CHECK(XTaskQueueDispatch(composite, completion, 0) && on_completion.runs.load() == 1);
// XAsyncRun on the composite: work on a's work port, completion on b's completion port.
RunRecord record{};
Async async{composite, &record, run_completed, {}};
CHECK(async_run(core, &async, run_work) == S_OK);
CHECK(XTaskQueueDispatch(a, work, 0) && record.work_runs.load() == 1);
CHECK(XTaskQueueDispatch(b, completion, 0) && record.completions.load() == 1);
void* bad = reinterpret_cast<void*>(uintptr_t{0x1234});
CHECK(FAILED(create_composite(core, a, b_completion, &bad)) && bad == nullptr); // a queue handle is not a port
XTaskQueueCloseHandle(composite);
// Closing the composite does not close the queues it forwards to.
DelayRecord still{};
CHECK(XTaskQueueSubmitCallback(a, work, &still, record_delay) == S_OK);
CHECK(XTaskQueueDispatch(a, work, 0) && still.runs.load() == 1);
XTaskQueueCloseHandle(a);
XTaskQueueCloseHandle(b);
}
}
void check_delayed_callback(HRESULT(WINAPI* query_api)(const GUID*, const GUID*, void**)) {
constexpr GUID kCore = {0x073B7DCB, 0x1FCF, 0x4030, {0x94, 0xBE, 0xE3, 0xC9, 0xEB, 0x62, 0x34, 0x28}};
void* core = nullptr;
@@ -722,7 +850,8 @@ int main() {
auto release = reinterpret_cast<ULONG(WINAPI*)(void*)>(core_vtbl[2]);
auto tq_create = reinterpret_cast<HRESULT(WINAPI*)(void*, uint32_t, uint32_t, void**)>(core_vtbl[12]);
auto tq_close = reinterpret_cast<void(WINAPI*)(void*, void*)>(core_vtbl[17]);
auto unimpl_slot = reinterpret_cast<HRESULT(WINAPI*)(void*)>(core_vtbl[14]);
// Slot 20 (XTaskQueueRegisterWaiter by the public order) is not implemented.
auto unimpl_slot = reinterpret_cast<HRESULT(WINAPI*)(void*)>(core_vtbl[20]);
void* qi_out = nullptr;
CHECK(SUCCEEDED(qi(com_core, &iunknown, &qi_out)) && qi_out == com_core);
void* q = nullptr;
@@ -802,7 +931,48 @@ int main() {
CHECK(unreg_ev(com_user, ev_tok, false));
CHECK(!unreg_ev(com_user, ev_tok, false));
// XUserDuplicateHandle, XUserCloseHandle and XUserCompare through IXUser slots 3, 4 and 5
// (#680). Slot numbers follow the public XUser.h declaration order; the expected behaviour
// is the documented one: a duplicate is a separate handle to the same user, each handle
// is closed on its own, and XUserCompare returns 0 for two handles of one user.
{
auto dup = reinterpret_cast<HRESULT(WINAPI*)(void*, void*, void**)>(user_vtbl[3]);
auto close = reinterpret_cast<void(WINAPI*)(void*, void*)>(user_vtbl[4]);
auto compare = reinterpret_cast<int32_t(WINAPI*)(void*, void*, void*)>(user_vtbl[5]);
auto get_id = reinterpret_cast<HRESULT(WINAPI*)(void*, void*, uint64_t*)>(user_vtbl[11]);
Async add{nullptr, nullptr, nullptr, {}};
CHECK(XUserAddAsync(1, &add) == S_OK);
CHECK(XAsyncGetStatus(&add, true) == S_OK);
void* original = nullptr;
CHECK(XUserAddResult(&add, &original) == S_OK && original);
void* copy = nullptr;
CHECK(dup(com_user, original, &copy) == S_OK && copy && copy != original);
CHECK(compare(com_user, original, copy) == 0 && compare(com_user, copy, original) == 0);
uint64_t copy_id = 0;
CHECK(get_id(com_user, copy, &copy_id) == S_OK && copy_id == 0x0009000000000001ULL);
// Closing the original leaves the duplicate valid, and the other way round.
close(com_user, original);
uint64_t gone = 0;
CHECK(FAILED(XUserGetId(original, &gone)));
CHECK(get_id(com_user, copy, &copy_id) == S_OK);
void* second = nullptr;
CHECK(dup(com_user, copy, &second) == S_OK && second && second != copy);
close(com_user, copy);
CHECK(FAILED(XUserGetId(copy, &gone)));
CHECK(XUserGetId(second, &gone) == S_OK);
// A closed or unknown handle is refused and the out pointer is cleared.
void* refused = reinterpret_cast<void*>(uintptr_t{0x1234});
CHECK(FAILED(dup(com_user, copy, &refused)) && refused == nullptr);
CHECK(dup(com_user, second, nullptr) == E_POINTER);
CHECK(compare(com_user, second, copy) != 0);
close(com_user, second);
}
check_delayed_callback(query_api);
check_async_run_and_queue_handles(query_api);
}
XGameRuntimeUninitialize();
@@ -568,6 +568,87 @@ void check_public_dispatch(void* user, void* synthetic_save, void* synthetic_pac
CHECK(listing.seen[0].blob_count == 1 && listing.seen[0].total_size == sizeof(payload));
CHECK(!listing.seen[0].needs_sync && listing.seen[0].modified >= started);
// IXGameSaveImpl slots 13 (XGameSaveGetContainerInfo) and 15 (XGameSaveEnumerateContainerInfoByName) (#667).
{
using GetContainerInfoFn = HRESULT(WINAPI*)(void*, void*, const char*, void*, InfoCallback);
using EnumerateByNameFn = HRESULT(WINAPI*)(void*, void*, const char*, void*, InfoCallback);
const auto get_info = slot<GetContainerInfoFn>(save, kGsGetContainerInfo);
const auto enum_by_name = slot<EnumerateByNameFn>(save, kGsEnumerateByName);
Listing single;
CHECK(get_info(save, provider, kContainer, &single, collect) == S_OK);
CHECK(single.seen.size() == 1);
CHECK(single.seen[0].name == kContainer && single.seen[0].display_name == kDisplay);
CHECK(single.seen[0].blob_count == 1 && single.seen[0].total_size == sizeof(payload));
CHECK(!single.seen[0].needs_sync && single.seen[0].modified >= started);
// Missing container succeeds without invoking the callback (source rank 3 inference).
Listing missing;
CHECK(get_info(save, provider, "no_such_container", &missing, collect) == S_OK);
CHECK(missing.seen.empty());
// Validation errors on slot 13.
CHECK(get_info(save, provider, kContainer, &missing, nullptr) == E_INVALIDARG);
CHECK(get_info(save, provider, nullptr, &missing, collect) == kInvalidContainerName);
CHECK(get_info(save, provider, "", &missing, collect) == kInvalidContainerName);
CHECK(get_info(save, provider, "../bad", &missing, collect) == kInvalidContainerName);
CHECK(get_info(save, nullptr, kContainer, &missing, collect) == kInvalidHandle);
// Use a dedicated provider for slot 15 so persisting three containers does not disturb
// kPublicScid's single-container check on subsequent runs in the same bottle.
constexpr const char* kPrefixScid = "22222222-2222-2222-2222-222222222222";
void* prefix_provider = nullptr;
CHECK(slot<InitFn>(save, kGsInit)(save, user, kPrefixScid, false, &prefix_provider) == S_OK && prefix_provider);
auto write_extra = [&](const char* cname, const char* dname) {
void* c = nullptr;
CHECK(slot<CreateContainerFn>(save, kGsCreateContainer)(save, prefix_provider, cname, &c) == S_OK && c);
void* u = nullptr;
CHECK(slot<CreateUpdateFn>(save, kGsCreateUpdate)(save, c, dname, &u) == S_OK && u);
CHECK(slot<BlobWriteFn>(save, kGsBlobWrite)(save, u, kBlob, payload, sizeof(payload)) == S_OK);
CHECK(slot<SubmitFn>(save, kGsSubmit)(save, u) == S_OK);
slot<CloseFn>(save, kGsCloseUpdate)(save, u);
slot<CloseFn>(save, kGsCloseContainer)(save, c);
};
write_extra("pub_slot", "Round 1");
write_extra("pub_slot_2", "Round 2");
write_extra("other_slot", "Other");
Listing pub_only;
CHECK(enum_by_name(save, prefix_provider, "pub_slot", &pub_only, collect) == S_OK);
CHECK(pub_only.seen.size() == 2);
CHECK(pub_only.seen[0].name == "pub_slot" && pub_only.seen[1].name == "pub_slot_2");
Listing other_only;
CHECK(enum_by_name(save, prefix_provider, "other_", &other_only, collect) == S_OK);
CHECK(other_only.seen.size() == 1 && other_only.seen[0].name == "other_slot");
Listing none;
CHECK(enum_by_name(save, prefix_provider, "nomatch_", &none, collect) == S_OK);
CHECK(none.seen.empty());
Listing all_null;
CHECK(enum_by_name(save, prefix_provider, nullptr, &all_null, collect) == S_OK);
CHECK(all_null.seen.size() == 3);
CHECK(all_null.seen[0].name == "other_slot" && all_null.seen[1].name == "pub_slot" &&
all_null.seen[2].name == "pub_slot_2");
Listing all_empty;
CHECK(enum_by_name(save, prefix_provider, "", &all_empty, collect) == S_OK);
CHECK(all_empty.seen.size() == 3);
Listing stopped;
stopped.stop_after = 1;
CHECK(enum_by_name(save, prefix_provider, "pub_slot", &stopped, collect) == S_OK);
CHECK(stopped.seen.size() == 1 && stopped.seen[0].name == "pub_slot");
// Validation errors on slot 15.
CHECK(enum_by_name(save, prefix_provider, "pub_slot", &none, nullptr) == E_INVALIDARG);
CHECK(enum_by_name(save, nullptr, "pub_slot", &none, collect) == kInvalidHandle);
slot<CloseFn>(save, kGsCloseProvider)(save, prefix_provider);
}
slot<CloseFn>(save, kGsCloseUpdate)(save, update);
slot<CloseFn>(save, kGsCloseContainer)(save, container);
slot<CloseFn>(save, kGsCloseProvider)(save, provider);