Compare commits

..
Author SHA1 Message Date
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 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 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
21 changed files with 817 additions and 26 deletions

No files matched your search

+3
View File
@@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- **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 +24,7 @@ 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
- 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 +84,7 @@ 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` 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.
---
+3 -2
View File
@@ -4,7 +4,7 @@
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
- [Roadmap](roadmap.md) — Single authoritative plan: the foundation milestones (M0–M2) and the stages the target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), with exit gates and decision gates.
- [Working Method](process/working-method.md) — What an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
- [Working Method](process/working-method.md) — Proposed: what an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
@@ -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
+2 -2
View File
@@ -1,6 +1,6 @@
# Working Method: the Blocker Queue
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
**Status: proposed**, together with the matching change to [AGENTS.md §0](../../AGENTS.md).
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?*
@@ -175,7 +175,7 @@ Everything else is the queue.
## Starting the queue
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.
The queue starts with what the first target-build runs already found. Each line becomes a blocker issue or a tooling issue when this proposal is accepted.
| Stage | Signature or task | Track |
| --- | --- | --- |
+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);
}
+26 -17
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];
@@ -433,33 +440,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 +479,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");
}
@@ -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;
}