Compare commits

..
Author SHA1 Message Date
ates 4cb858e6f5 docs: the working method is in effect; point to the ladder issue
#662 is merged, so the working method no longer says 'proposed'. It
names the pinned ladder issue (#663) and notes that the starting queue
was filed as #664-#680.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:49:50 +03:00
22 changed files with 13 additions and 842 deletions

No files matched your search

-3
View File
@@ -10,7 +10,6 @@ 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.
@@ -24,8 +23,6 @@ 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 `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`.
- 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`);
+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.
## Licensing & Provenance Policy
## Clean-Room, 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.
- 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.
- 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.
- 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]
> **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.
> **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.
---
+2 -3
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) — Proposed: 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) — 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,7 +27,6 @@
- [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.
@@ -35,7 +34,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, provenance policy, and DCO sign-off.
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, clean-room 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 @@
# Legal scope
# Clean-room 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, 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.
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.
## User-provided game files
+2 -2
View File
@@ -1,6 +1,6 @@
# Working Method: the Blocker Queue
**Status: proposed**, together with the matching change to [AGENTS.md §0](../../AGENTS.md).
**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?*
@@ -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 becomes a blocker issue or a tooling issue when this proposal is accepted.
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 |
| --- | --- | --- |
-66
View File
@@ -1,66 +0,0 @@
#!/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
@@ -1,158 +0,0 @@
#!/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
@@ -1,106 +0,0 @@
# 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
@@ -1,110 +0,0 @@
# 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
@@ -1,17 +0,0 @@
// 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
@@ -1,16 +0,0 @@
// 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
@@ -1,14 +0,0 @@
// 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;
}
@@ -1,16 +0,0 @@
// 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);
}
@@ -1,14 +0,0 @@
// 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
@@ -1,20 +0,0 @@
// 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
@@ -1,19 +0,0 @@
// 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
@@ -1,21 +0,0 @@
// 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);
}
-33
View File
@@ -37,9 +37,6 @@ 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*);
@@ -179,32 +176,6 @@ 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);
}
@@ -249,11 +220,7 @@ 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);
+2 -82
View File
@@ -185,31 +185,13 @@ 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) {
@@ -256,9 +238,7 @@ QueueRef acquire_queue(void* handle) {
}
bool submit(const QueueRef& queue, Port port, std::unique_ptr<Task> task, bool is_completion) {
QueueRef target = queue;
resolve_lane(target, port);
return target->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
return queue->lanes[static_cast<uint32_t>(port)].push(std::move(task), is_completion);
}
@@ -295,10 +275,6 @@ 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.
@@ -309,64 +285,8 @@ 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);
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;
}
return queue && queue->lanes[static_cast<uint32_t>(port)].dispatch(timeout);
}
HRESULT WINAPI XTaskQueueSubmitDelayedCallback(void* handle, Port port, uint32_t delay_ms, void* context,
+1 -6
View File
@@ -167,10 +167,6 @@ 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)
@@ -229,7 +225,7 @@ private:
queued = false;
write_state(block, state);
}
if (completion) submit(origin ? origin : queue, Port::completion, std::move(completion), true);
if (completion) submit(queue, Port::completion, std::move(completion), true);
}
};
@@ -240,7 +236,6 @@ 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;
+1 -131
View File
@@ -199,134 +199,6 @@ 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;
@@ -850,8 +722,7 @@ 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]);
// Slot 20 (XTaskQueueRegisterWaiter by the public order) is not implemented.
auto unimpl_slot = reinterpret_cast<HRESULT(WINAPI*)(void*)>(core_vtbl[20]);
auto unimpl_slot = reinterpret_cast<HRESULT(WINAPI*)(void*)>(core_vtbl[14]);
void* qi_out = nullptr;
CHECK(SUCCEEDED(qi(com_core, &iunknown, &qi_out)) && qi_out == com_core);
void* q = nullptr;
@@ -932,7 +803,6 @@ int main() {
CHECK(!unreg_ev(com_user, ev_tok, false));
check_delayed_callback(query_api);
check_async_run_and_queue_handles(query_api);
}
XGameRuntimeUninitialize();